L2DatabaseFactory.java 9.5 KB

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