L2DatabaseFactory.java 8.0 KB

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