Shutdown.java 19 KB

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