L2DatabaseFactory.java 10 KB

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