Shutdown.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. /*
  2. * Copyright (C) 2004-2015 L2J Server
  3. *
  4. * This file is part of L2J Server.
  5. *
  6. * L2J Server is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * L2J Server is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. package com.l2jserver.gameserver;
  20. import java.util.concurrent.TimeUnit;
  21. import org.slf4j.Logger;
  22. import org.slf4j.LoggerFactory;
  23. import com.l2jserver.Config;
  24. import com.l2jserver.UPnPService;
  25. import com.l2jserver.commons.database.pool.impl.ConnectionFactory;
  26. import com.l2jserver.gameserver.data.sql.impl.ClanTable;
  27. import com.l2jserver.gameserver.data.sql.impl.OfflineTradersTable;
  28. import com.l2jserver.gameserver.datatables.BotReportTable;
  29. import com.l2jserver.gameserver.instancemanager.CHSiegeManager;
  30. import com.l2jserver.gameserver.instancemanager.CastleManorManager;
  31. import com.l2jserver.gameserver.instancemanager.CursedWeaponsManager;
  32. import com.l2jserver.gameserver.instancemanager.GlobalVariablesManager;
  33. import com.l2jserver.gameserver.instancemanager.GrandBossManager;
  34. import com.l2jserver.gameserver.instancemanager.ItemAuctionManager;
  35. import com.l2jserver.gameserver.instancemanager.ItemsOnGroundManager;
  36. import com.l2jserver.gameserver.instancemanager.QuestManager;
  37. import com.l2jserver.gameserver.instancemanager.RaidBossSpawnManager;
  38. import com.l2jserver.gameserver.model.L2World;
  39. import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
  40. import com.l2jserver.gameserver.model.entity.Hero;
  41. import com.l2jserver.gameserver.model.olympiad.Olympiad;
  42. import com.l2jserver.gameserver.network.L2GameClient;
  43. import com.l2jserver.gameserver.network.SystemMessageId;
  44. import com.l2jserver.gameserver.network.gameserverpackets.ServerStatus;
  45. import com.l2jserver.gameserver.network.serverpackets.ServerClose;
  46. import com.l2jserver.gameserver.network.serverpackets.SystemMessage;
  47. import com.l2jserver.gameserver.util.Broadcast;
  48. /**
  49. * This class provides the functions for shutting down and restarting the server.<br>
  50. * It closes all open client connections and saves all data.
  51. * @version $Revision: 1.2.4.5 $ $Date: 2005/03/27 15:29:09 $
  52. */
  53. public class Shutdown extends Thread
  54. {
  55. private static final Logger _log = LoggerFactory.getLogger(Shutdown.class);
  56. private static Shutdown _counterInstance = null;
  57. private int _secondsShut;
  58. private int _shutdownMode;
  59. public static final int SIGTERM = 0;
  60. public static final int GM_SHUTDOWN = 1;
  61. public static final int GM_RESTART = 2;
  62. public static final int ABORT = 3;
  63. private static final String[] MODE_TEXT =
  64. {
  65. "SIGTERM",
  66. "shutting down",
  67. "restarting",
  68. "aborting"
  69. };
  70. /**
  71. * This function starts a shutdown count down from Telnet (Copied from Function startShutdown())
  72. * @param seconds seconds until shutdown
  73. */
  74. private void SendServerQuit(int seconds)
  75. {
  76. SystemMessage sysm = SystemMessage.getSystemMessage(SystemMessageId.THE_SERVER_WILL_BE_COMING_DOWN_IN_S1_SECONDS);
  77. sysm.addInt(seconds);
  78. Broadcast.toAllOnlinePlayers(sysm);
  79. }
  80. public void startTelnetShutdown(String IP, int seconds, boolean restart)
  81. {
  82. _log.warn("IP: {} issued shutdown command. {} in {} seconds!", IP, MODE_TEXT[_shutdownMode], seconds);
  83. if (restart)
  84. {
  85. _shutdownMode = GM_RESTART;
  86. }
  87. else
  88. {
  89. _shutdownMode = GM_SHUTDOWN;
  90. }
  91. if (_shutdownMode > 0)
  92. {
  93. switch (seconds)
  94. {
  95. case 540:
  96. case 480:
  97. case 420:
  98. case 360:
  99. case 300:
  100. case 240:
  101. case 180:
  102. case 120:
  103. case 60:
  104. case 30:
  105. case 10:
  106. case 5:
  107. case 4:
  108. case 3:
  109. case 2:
  110. case 1:
  111. break;
  112. default:
  113. SendServerQuit(seconds);
  114. }
  115. }
  116. if (_counterInstance != null)
  117. {
  118. _counterInstance._abort();
  119. }
  120. _counterInstance = new Shutdown(seconds, restart);
  121. _counterInstance.start();
  122. }
  123. /**
  124. * This function aborts a running countdown
  125. * @param IP IP Which Issued shutdown command
  126. */
  127. public void telnetAbort(String IP)
  128. {
  129. _log.warn("IP: {} issued shutdown ABORT. {} has been stopped!", IP, MODE_TEXT[_shutdownMode]);
  130. if (_counterInstance != null)
  131. {
  132. _counterInstance._abort();
  133. Broadcast.toAllOnlinePlayers("Server aborts " + MODE_TEXT[_shutdownMode] + " and continues normal operation!", false);
  134. }
  135. }
  136. /**
  137. * Default constructor is only used internal to create the shutdown-hook instance
  138. */
  139. protected Shutdown()
  140. {
  141. _secondsShut = -1;
  142. _shutdownMode = SIGTERM;
  143. }
  144. /**
  145. * This creates a countdown instance of Shutdown.
  146. * @param seconds how many seconds until shutdown
  147. * @param restart true is the server shall restart after shutdown
  148. */
  149. public Shutdown(int seconds, boolean restart)
  150. {
  151. if (seconds < 0)
  152. {
  153. seconds = 0;
  154. }
  155. _secondsShut = seconds;
  156. if (restart)
  157. {
  158. _shutdownMode = GM_RESTART;
  159. }
  160. else
  161. {
  162. _shutdownMode = GM_SHUTDOWN;
  163. }
  164. }
  165. /**
  166. * This function is called, when a new thread starts if this thread is the thread of getInstance, then this is the shutdown hook and we save all data and disconnect all clients.<br>
  167. * After this thread ends, the server will completely exit if this is not the thread of getInstance, then this is a countdown thread.<br>
  168. * We start the countdown, and when we finished it, and it was not aborted, we tell the shutdown-hook why we call exit, and then call exit when the exit status of the server is 1, startServer.sh / startServer.bat will restart the server.
  169. */
  170. @Override
  171. public void run()
  172. {
  173. if (this == getInstance())
  174. {
  175. TimeCounter tc = new TimeCounter();
  176. TimeCounter tc1 = new TimeCounter();
  177. try
  178. {
  179. UPnPService.getInstance().removeAllPorts();
  180. _log.info("UPnP Service: All ports mappings deleted ({}ms).", tc.getEstimatedTimeAndRestartCounter());
  181. }
  182. catch (Exception e)
  183. {
  184. _log.warn("Error while removing UPnP port mappings!", e);
  185. }
  186. try
  187. {
  188. if ((Config.OFFLINE_TRADE_ENABLE || Config.OFFLINE_CRAFT_ENABLE) && Config.RESTORE_OFFLINERS)
  189. {
  190. OfflineTradersTable.getInstance().storeOffliners();
  191. _log.info("Offline Traders Table: Offline shops stored({}ms).", tc.getEstimatedTimeAndRestartCounter());
  192. }
  193. }
  194. catch (Exception e)
  195. {
  196. _log.warn("Error saving offline shops!", e);
  197. }
  198. try
  199. {
  200. disconnectAllCharacters();
  201. _log.info("All players disconnected and saved({}ms).", tc.getEstimatedTimeAndRestartCounter());
  202. }
  203. catch (Exception e)
  204. {
  205. // ignore
  206. }
  207. // ensure all services are stopped
  208. try
  209. {
  210. GameTimeController.getInstance().stopTimer();
  211. _log.info("Game Time Controller: Timer stopped({}ms).", tc.getEstimatedTimeAndRestartCounter());
  212. }
  213. catch (Exception e)
  214. {
  215. // ignore
  216. }
  217. // stop all thread pools
  218. try
  219. {
  220. ThreadPoolManager.getInstance().shutdown();
  221. _log.info("Thread Pool Manager: Manager has been shut down({}ms).", tc.getEstimatedTimeAndRestartCounter());
  222. }
  223. catch (Exception e)
  224. {
  225. // ignore
  226. }
  227. try
  228. {
  229. LoginServerThread.getInstance().interrupt();
  230. _log.info("Login Server Thread: Thread interruped({}ms).", tc.getEstimatedTimeAndRestartCounter());
  231. }
  232. catch (Exception e)
  233. {
  234. // ignore
  235. }
  236. // last byebye, save all data and quit this server
  237. saveData();
  238. tc.restartCounter();
  239. // saveData sends messages to exit players, so shutdown selector after it
  240. try
  241. {
  242. GameServer.gameServer.getSelectorThread().shutdown();
  243. _log.info("Game Server: Selector thread has been shut down({}ms).", tc.getEstimatedTimeAndRestartCounter());
  244. }
  245. catch (Exception e)
  246. {
  247. // ignore
  248. }
  249. // commit data, last chance
  250. try
  251. {
  252. ConnectionFactory.getInstance().close();
  253. _log.info("ConnectionFactory: Database connection has been shut down({}ms).", tc.getEstimatedTimeAndRestartCounter());
  254. }
  255. catch (Exception e)
  256. {
  257. }
  258. // server will quit, when this function ends.
  259. if (getInstance()._shutdownMode == GM_RESTART)
  260. {
  261. Runtime.getRuntime().halt(2);
  262. }
  263. else
  264. {
  265. Runtime.getRuntime().halt(0);
  266. }
  267. _log.info("The server has been successfully shut down in {}seconds.", TimeUnit.MILLISECONDS.toSeconds(tc1.getEstimatedTime()));
  268. }
  269. else
  270. {
  271. // gm shutdown: send warnings and then call exit to start shutdown sequence
  272. countdown();
  273. // last point where logging is operational :(
  274. _log.warn("GM shutdown countdown is over. {} NOW!", MODE_TEXT[_shutdownMode]);
  275. switch (_shutdownMode)
  276. {
  277. case GM_SHUTDOWN:
  278. getInstance().setMode(GM_SHUTDOWN);
  279. System.exit(0);
  280. break;
  281. case GM_RESTART:
  282. getInstance().setMode(GM_RESTART);
  283. System.exit(2);
  284. break;
  285. case ABORT:
  286. LoginServerThread.getInstance().setServerStatus(ServerStatus.STATUS_AUTO);
  287. break;
  288. }
  289. }
  290. }
  291. /**
  292. * This functions starts a shutdown countdown.
  293. * @param activeChar GM who issued the shutdown command
  294. * @param seconds seconds until shutdown
  295. * @param restart true if the server will restart after shutdown
  296. */
  297. public void startShutdown(L2PcInstance activeChar, int seconds, boolean restart)
  298. {
  299. if (restart)
  300. {
  301. _shutdownMode = GM_RESTART;
  302. }
  303. else
  304. {
  305. _shutdownMode = GM_SHUTDOWN;
  306. }
  307. _log.warn("GM: {}({}) issued shutdown command. {} in {} seconds!", activeChar.getName(), activeChar.getObjectId(), MODE_TEXT[_shutdownMode], seconds);
  308. if (_shutdownMode > 0)
  309. {
  310. switch (seconds)
  311. {
  312. case 540:
  313. case 480:
  314. case 420:
  315. case 360:
  316. case 300:
  317. case 240:
  318. case 180:
  319. case 120:
  320. case 60:
  321. case 30:
  322. case 10:
  323. case 5:
  324. case 4:
  325. case 3:
  326. case 2:
  327. case 1:
  328. break;
  329. default:
  330. SendServerQuit(seconds);
  331. }
  332. }
  333. if (_counterInstance != null)
  334. {
  335. _counterInstance._abort();
  336. }
  337. // the main instance should only run for shutdown hook, so we start a new instance
  338. _counterInstance = new Shutdown(seconds, restart);
  339. _counterInstance.start();
  340. }
  341. /**
  342. * This function aborts a running countdown.
  343. * @param activeChar GM who issued the abort command
  344. */
  345. public void abort(L2PcInstance activeChar)
  346. {
  347. _log.warn("GM: {}({}) issued shutdown ABORT. {} has been stopped!", activeChar.getName(), activeChar.getObjectId(), MODE_TEXT[_shutdownMode]);
  348. if (_counterInstance != null)
  349. {
  350. _counterInstance._abort();
  351. Broadcast.toAllOnlinePlayers("Server aborts " + MODE_TEXT[_shutdownMode] + " and continues normal operation!", false);
  352. }
  353. }
  354. /**
  355. * Set the shutdown mode.
  356. * @param mode what mode shall be set
  357. */
  358. private void setMode(int mode)
  359. {
  360. _shutdownMode = mode;
  361. }
  362. /**
  363. * Set shutdown mode to ABORT.
  364. */
  365. private void _abort()
  366. {
  367. _shutdownMode = ABORT;
  368. }
  369. /**
  370. * This counts the countdown and reports it to all players countdown is aborted if mode changes to ABORT.
  371. */
  372. private void countdown()
  373. {
  374. try
  375. {
  376. while (_secondsShut > 0)
  377. {
  378. switch (_secondsShut)
  379. {
  380. case 540:
  381. SendServerQuit(540);
  382. break;
  383. case 480:
  384. SendServerQuit(480);
  385. break;
  386. case 420:
  387. SendServerQuit(420);
  388. break;
  389. case 360:
  390. SendServerQuit(360);
  391. break;
  392. case 300:
  393. SendServerQuit(300);
  394. break;
  395. case 240:
  396. SendServerQuit(240);
  397. break;
  398. case 180:
  399. SendServerQuit(180);
  400. break;
  401. case 120:
  402. SendServerQuit(120);
  403. break;
  404. case 60:
  405. LoginServerThread.getInstance().setServerStatus(ServerStatus.STATUS_DOWN); // avoids new players from logging in
  406. SendServerQuit(60);
  407. break;
  408. case 30:
  409. SendServerQuit(30);
  410. break;
  411. case 10:
  412. SendServerQuit(10);
  413. break;
  414. case 5:
  415. SendServerQuit(5);
  416. break;
  417. case 4:
  418. SendServerQuit(4);
  419. break;
  420. case 3:
  421. SendServerQuit(3);
  422. break;
  423. case 2:
  424. SendServerQuit(2);
  425. break;
  426. case 1:
  427. SendServerQuit(1);
  428. break;
  429. }
  430. _secondsShut--;
  431. int delay = 1000; // milliseconds
  432. Thread.sleep(delay);
  433. if (_shutdownMode == ABORT)
  434. {
  435. break;
  436. }
  437. }
  438. }
  439. catch (InterruptedException e)
  440. {
  441. // this will never happen
  442. }
  443. }
  444. /**
  445. * This sends a last byebye, disconnects all players and saves data.
  446. */
  447. private void saveData()
  448. {
  449. switch (_shutdownMode)
  450. {
  451. case SIGTERM:
  452. _log.info("SIGTERM received. Shutting down NOW!");
  453. break;
  454. case GM_SHUTDOWN:
  455. _log.info("GM shutdown received. Shutting down NOW!");
  456. break;
  457. case GM_RESTART:
  458. _log.info("GM restart received. Restarting NOW!");
  459. break;
  460. }
  461. TimeCounter tc = new TimeCounter();
  462. // Seven Signs data is now saved along with Festival data.
  463. if (!SevenSigns.getInstance().isSealValidationPeriod())
  464. {
  465. SevenSignsFestival.getInstance().saveFestivalData(false);
  466. _log.info("SevenSignsFestival: Festival data saved({}ms).", tc.getEstimatedTimeAndRestartCounter());
  467. }
  468. // Save Seven Signs data before closing. :)
  469. SevenSigns.getInstance().saveSevenSignsData();
  470. _log.info("SevenSigns: Seven Signs data saved({}ms).", tc.getEstimatedTimeAndRestartCounter());
  471. SevenSigns.getInstance().saveSevenSignsStatus();
  472. _log.info("SevenSigns: Seven Signs status saved({}ms).", tc.getEstimatedTimeAndRestartCounter());
  473. // Save all raidboss and GrandBoss status ^_^
  474. RaidBossSpawnManager.getInstance().cleanUp();
  475. _log.info("RaidBossSpawnManager: All raidboss info saved({}ms).", tc.getEstimatedTimeAndRestartCounter());
  476. GrandBossManager.getInstance().cleanUp();
  477. _log.info("GrandBossManager: All Grand Boss info saved({}ms).", tc.getEstimatedTimeAndRestartCounter());
  478. ItemAuctionManager.getInstance().shutdown();
  479. _log.info("Item Auction Manager: All tasks stopped({}ms).", tc.getEstimatedTimeAndRestartCounter());
  480. Olympiad.getInstance().saveOlympiadStatus();
  481. _log.info("Olympiad System: Data saved({}ms).", tc.getEstimatedTimeAndRestartCounter());
  482. Hero.getInstance().shutdown();
  483. _log.info("Hero System: Data saved({}ms).", tc.getEstimatedTimeAndRestartCounter());
  484. ClanTable.getInstance().storeClanScore();
  485. _log.info("Clan System: Data saved({}ms).", tc.getEstimatedTimeAndRestartCounter());
  486. // Save Cursed Weapons data before closing.
  487. CursedWeaponsManager.getInstance().saveData();
  488. _log.info("Cursed Weapons Manager: Data saved({}ms).", tc.getEstimatedTimeAndRestartCounter());
  489. // Save all manor data
  490. if (!Config.ALT_MANOR_SAVE_ALL_ACTIONS)
  491. {
  492. CastleManorManager.getInstance().storeMe();
  493. _log.info("Castle Manor Manager: Data saved({}ms).", tc.getEstimatedTimeAndRestartCounter());
  494. }
  495. CHSiegeManager.getInstance().onServerShutDown();
  496. _log.info("CHSiegeManager: Siegable hall attacker lists saved!");
  497. // Save all global (non-player specific) Quest data that needs to persist after reboot
  498. QuestManager.getInstance().save();
  499. _log.info("Quest Manager: Data saved({}ms).", tc.getEstimatedTimeAndRestartCounter());
  500. // Save all global variables data
  501. GlobalVariablesManager.getInstance().storeMe();
  502. _log.info("Global Variables Manager: Variables saved({}ms).", tc.getEstimatedTimeAndRestartCounter());
  503. // Save items on ground before closing
  504. if (Config.SAVE_DROPPED_ITEM)
  505. {
  506. ItemsOnGroundManager.getInstance().saveInDb();
  507. _log.info("Items On Ground Manager: Data saved({}ms).", tc.getEstimatedTimeAndRestartCounter());
  508. ItemsOnGroundManager.getInstance().cleanUp();
  509. _log.info("Items On Ground Manager: Cleaned up({}ms).", tc.getEstimatedTimeAndRestartCounter());
  510. }
  511. // Save bot reports to database
  512. if (Config.BOTREPORT_ENABLE)
  513. {
  514. BotReportTable.getInstance().saveReportedCharData();
  515. _log.info("Bot Report Table: Sucessfully saved reports to database!");
  516. }
  517. try
  518. {
  519. Thread.sleep(5000);
  520. }
  521. catch (InterruptedException e)
  522. {
  523. // never happens :p
  524. }
  525. }
  526. /**
  527. * This disconnects all clients from the server.
  528. */
  529. private void disconnectAllCharacters()
  530. {
  531. for (L2PcInstance player : L2World.getInstance().getPlayers())
  532. {
  533. // Logout Character
  534. try
  535. {
  536. L2GameClient client = player.getClient();
  537. if ((client != null) && !client.isDetached())
  538. {
  539. client.close(ServerClose.STATIC_PACKET);
  540. client.setActiveChar(null);
  541. player.setClient(null);
  542. }
  543. player.deleteMe();
  544. }
  545. catch (Exception e)
  546. {
  547. _log.warn("Failed logour char {}", player, e);
  548. }
  549. }
  550. }
  551. /**
  552. * A simple class used to track down the estimated time of method executions.<br>
  553. * Once this class is created, it saves the start time, and when you want to get the estimated time, use the getEstimatedTime() method.
  554. */
  555. private static final class TimeCounter
  556. {
  557. private long _startTime;
  558. protected TimeCounter()
  559. {
  560. restartCounter();
  561. }
  562. protected void restartCounter()
  563. {
  564. _startTime = System.currentTimeMillis();
  565. }
  566. protected long getEstimatedTimeAndRestartCounter()
  567. {
  568. final long toReturn = System.currentTimeMillis() - _startTime;
  569. restartCounter();
  570. return toReturn;
  571. }
  572. protected long getEstimatedTime()
  573. {
  574. return System.currentTimeMillis() - _startTime;
  575. }
  576. }
  577. /**
  578. * Get the shutdown-hook instance the shutdown-hook instance is created by the first call of this function, but it has to be registered externally.<br>
  579. * @return instance of Shutdown, to be used as shutdown hook
  580. */
  581. public static Shutdown getInstance()
  582. {
  583. return SingletonHolder._instance;
  584. }
  585. private static class SingletonHolder
  586. {
  587. protected static final Shutdown _instance = new Shutdown();
  588. }
  589. }