L2DatabaseFactory.java 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /*
  2. * This program is free software: you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation, either version 3 of the License, or (at your option) any later
  5. * version.
  6. *
  7. * This program is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU General Public License along with
  13. * this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package com.l2jserver;
  16. import java.sql.Connection;
  17. import java.sql.SQLException;
  18. import java.util.concurrent.Executors;
  19. import java.util.concurrent.ScheduledExecutorService;
  20. import java.util.concurrent.TimeUnit;
  21. import java.util.logging.Level;
  22. import java.util.logging.Logger;
  23. import com.l2jserver.gameserver.ThreadPoolManager;
  24. import com.mchange.v2.c3p0.ComboPooledDataSource;
  25. public class L2DatabaseFactory
  26. {
  27. static Logger _log = Logger.getLogger(L2DatabaseFactory.class.getName());
  28. public static enum ProviderType
  29. {
  30. MySql, MsSql
  31. }
  32. private static L2DatabaseFactory _instance;
  33. private static ScheduledExecutorService _executor;
  34. private ProviderType _providerType;
  35. private ComboPooledDataSource _source;
  36. public L2DatabaseFactory() throws SQLException
  37. {
  38. try
  39. {
  40. if (Config.DATABASE_MAX_CONNECTIONS < 2)
  41. {
  42. Config.DATABASE_MAX_CONNECTIONS = 2;
  43. _log.warning("A minimum of " + Config.DATABASE_MAX_CONNECTIONS + " db connections are required.");
  44. }
  45. _source = new ComboPooledDataSource();
  46. _source.setAutoCommitOnClose(true);
  47. _source.setInitialPoolSize(10);
  48. _source.setMinPoolSize(10);
  49. _source.setMaxPoolSize(Math.max(10, Config.DATABASE_MAX_CONNECTIONS));
  50. _source.setAcquireRetryAttempts(0); // try to obtain connections indefinitely (0 = never quit)
  51. _source.setAcquireRetryDelay(500); // 500 milliseconds wait before try to acquire connection again
  52. _source.setCheckoutTimeout(0); // 0 = wait indefinitely for new connection
  53. // if pool is exhausted
  54. _source.setAcquireIncrement(5); // if pool is exhausted, get 5 more connections at a time
  55. // cause there is a "long" delay on acquire connection
  56. // so taking more than one connection at once will make connection pooling
  57. // more effective.
  58. // this "connection_test_table" is automatically created if not already there
  59. _source.setAutomaticTestTable("connection_test_table");
  60. _source.setTestConnectionOnCheckin(false);
  61. // testing OnCheckin used with IdleConnectionTestPeriod is faster than testing on checkout
  62. _source.setIdleConnectionTestPeriod(3600); // test idle connection every 60 sec
  63. _source.setMaxIdleTime(Config.DATABASE_MAX_IDLE_TIME); // 0 = idle connections never expire
  64. // *THANKS* to connection testing configured above
  65. // but I prefer to disconnect all connections not used
  66. // for more than 1 hour
  67. // enables statement caching, there is a "semi-bug" in c3p0 0.9.0 but in 0.9.0.2 and later it's fixed
  68. _source.setMaxStatementsPerConnection(100);
  69. _source.setBreakAfterAcquireFailure(false); // never fail if any way possible
  70. // setting this to true will make
  71. // c3p0 "crash" and refuse to work
  72. // till restart thus making acquire
  73. // errors "FATAL" ... we don't want that
  74. // it should be possible to recover
  75. _source.setDriverClass(Config.DATABASE_DRIVER);
  76. _source.setJdbcUrl(Config.DATABASE_URL);
  77. _source.setUser(Config.DATABASE_LOGIN);
  78. _source.setPassword(Config.DATABASE_PASSWORD);
  79. /* Test the connection */
  80. _source.getConnection().close();
  81. if (Config.DEBUG)
  82. _log.fine("Database Connection Working");
  83. if (Config.DATABASE_DRIVER.toLowerCase().contains("microsoft"))
  84. _providerType = ProviderType.MsSql;
  85. else
  86. _providerType = ProviderType.MySql;
  87. }
  88. catch (SQLException x)
  89. {
  90. if (Config.DEBUG)
  91. _log.fine("Database Connection FAILED");
  92. // re-throw the exception
  93. throw x;
  94. }
  95. catch (Exception e)
  96. {
  97. if (Config.DEBUG)
  98. _log.fine("Database Connection FAILED");
  99. throw new SQLException("Could not init DB connection:" + e.getMessage());
  100. }
  101. }
  102. public final String prepQuerySelect(String[] fields, String tableName, String whereClause, boolean returnOnlyTopRecord)
  103. {
  104. String msSqlTop1 = "";
  105. String mySqlTop1 = "";
  106. if (returnOnlyTopRecord)
  107. {
  108. if (getProviderType() == ProviderType.MsSql)
  109. msSqlTop1 = " Top 1 ";
  110. if (getProviderType() == ProviderType.MySql)
  111. mySqlTop1 = " Limit 1 ";
  112. }
  113. String query = "SELECT " + msSqlTop1 + safetyString(fields) + " FROM " + tableName + " WHERE " + whereClause + mySqlTop1;
  114. return query;
  115. }
  116. public void shutdown()
  117. {
  118. try
  119. {
  120. _source.close();
  121. }
  122. catch (Exception e)
  123. {
  124. _log.log(Level.INFO, "", e);
  125. }
  126. try
  127. {
  128. _source = null;
  129. }
  130. catch (Exception e)
  131. {
  132. _log.log(Level.INFO, "", e);
  133. }
  134. }
  135. public final String safetyString(String... whatToCheck)
  136. {
  137. // NOTE: Use brace as a safty precaution just incase name is a reserved word
  138. final char braceLeft;
  139. final char braceRight;
  140. if (getProviderType() == ProviderType.MsSql)
  141. {
  142. braceLeft = '[';
  143. braceRight = ']';
  144. }
  145. else
  146. {
  147. braceLeft = '`';
  148. braceRight = '`';
  149. }
  150. int length = 0;
  151. for (String word : whatToCheck)
  152. {
  153. length += word.length() + 4;
  154. }
  155. final StringBuilder sbResult = new StringBuilder(length);
  156. for (String word : whatToCheck)
  157. {
  158. if (sbResult.length() > 0)
  159. {
  160. sbResult.append(", ");
  161. }
  162. sbResult.append(braceLeft);
  163. sbResult.append(word);
  164. sbResult.append(braceRight);
  165. }
  166. return sbResult.toString();
  167. }
  168. public static L2DatabaseFactory getInstance() throws SQLException
  169. {
  170. synchronized (L2DatabaseFactory.class)
  171. {
  172. if (_instance == null)
  173. {
  174. _instance = new L2DatabaseFactory();
  175. }
  176. }
  177. return _instance;
  178. }
  179. public Connection getConnection()
  180. {
  181. Connection con = null;
  182. while (con == null)
  183. {
  184. try
  185. {
  186. con = _source.getConnection();
  187. if (Server.serverMode == Server.MODE_GAMESERVER)
  188. ThreadPoolManager.getInstance().scheduleGeneral(new ConnectionCloser(con, new RuntimeException()), Config.CONNECTION_CLOSE_TIME);
  189. else
  190. getExecutor().schedule(new ConnectionCloser(con, new RuntimeException()), 60, TimeUnit.SECONDS);
  191. }
  192. catch (SQLException e)
  193. {
  194. _log.log(Level.WARNING, "L2DatabaseFactory: getConnection() failed, trying again " + e.getMessage(), e);
  195. }
  196. }
  197. return con;
  198. }
  199. private static class ConnectionCloser implements Runnable
  200. {
  201. private final Connection c;
  202. private final RuntimeException exp;
  203. public ConnectionCloser(Connection con, RuntimeException e)
  204. {
  205. c = con;
  206. exp = e;
  207. }
  208. @Override
  209. public void run()
  210. {
  211. try
  212. {
  213. if (!c.isClosed())
  214. {
  215. _log.log(Level.WARNING, "Unclosed connection! Trace: " + exp.getStackTrace()[1], exp);
  216. }
  217. }
  218. catch (SQLException e)
  219. {
  220. _log.log(Level.WARNING, "", e);
  221. }
  222. }
  223. }
  224. public static void close(Connection con)
  225. {
  226. if (con == null)
  227. return;
  228. try
  229. {
  230. con.close();
  231. }
  232. catch (SQLException e)
  233. {
  234. _log.log(Level.WARNING, "Failed to close database connection!", e);
  235. }
  236. }
  237. private static ScheduledExecutorService getExecutor()
  238. {
  239. if (_executor == null)
  240. {
  241. synchronized (L2DatabaseFactory.class)
  242. {
  243. if (_executor == null)
  244. _executor = Executors.newSingleThreadScheduledExecutor();
  245. }
  246. }
  247. return _executor;
  248. }
  249. public int getBusyConnectionCount() throws SQLException
  250. {
  251. return _source.getNumBusyConnectionsDefaultUser();
  252. }
  253. public int getIdleConnectionCount() throws SQLException
  254. {
  255. return _source.getNumIdleConnectionsDefaultUser();
  256. }
  257. public final ProviderType getProviderType()
  258. {
  259. return _providerType;
  260. }
  261. }