L2DatabaseFactory.java 8.4 KB

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