DebugHandler.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. /*
  2. * Copyright (C) 2004-2013 L2J DataPack
  3. *
  4. * This file is part of L2J DataPack.
  5. *
  6. * L2J DataPack 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 DataPack 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 handlers.telnethandlers;
  20. import java.io.File;
  21. import java.io.FileOutputStream;
  22. import java.io.OutputStreamWriter;
  23. import java.io.PrintWriter;
  24. import java.lang.management.ManagementFactory;
  25. import java.lang.management.ThreadInfo;
  26. import java.lang.management.ThreadMXBean;
  27. import java.net.Socket;
  28. import java.text.SimpleDateFormat;
  29. import java.util.Calendar;
  30. import java.util.Map;
  31. import java.util.Map.Entry;
  32. import java.util.StringTokenizer;
  33. import javolution.util.FastComparator;
  34. import javolution.util.FastTable;
  35. import com.l2jserver.Config;
  36. import com.l2jserver.gameserver.GameTimeController;
  37. import com.l2jserver.gameserver.LoginServerThread;
  38. import com.l2jserver.gameserver.ThreadPoolManager;
  39. import com.l2jserver.gameserver.datatables.AdminTable;
  40. import com.l2jserver.gameserver.handler.ITelnetHandler;
  41. import com.l2jserver.gameserver.model.L2Object;
  42. import com.l2jserver.gameserver.model.L2World;
  43. import com.l2jserver.gameserver.model.actor.L2Character;
  44. import com.l2jserver.gameserver.model.actor.L2Npc;
  45. import com.l2jserver.gameserver.model.actor.L2Summon;
  46. import com.l2jserver.gameserver.model.actor.instance.L2DoorInstance;
  47. import com.l2jserver.gameserver.model.actor.instance.L2MonsterInstance;
  48. import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
  49. import com.l2jserver.gameserver.model.items.instance.L2ItemInstance;
  50. import com.l2jserver.gameserver.network.serverpackets.AdminForgePacket;
  51. import com.l2jserver.gameserver.taskmanager.DecayTaskManager;
  52. /**
  53. * @author UnAfraid
  54. */
  55. public class DebugHandler implements ITelnetHandler
  56. {
  57. private final String[] _commands =
  58. {
  59. "debug"
  60. };
  61. private int uptime = 0;
  62. @Override
  63. public boolean useCommand(String command, PrintWriter _print, Socket _cSocket, int _uptime)
  64. {
  65. if (command.startsWith("debug") && (command.length() > 6))
  66. {
  67. StringTokenizer st = new StringTokenizer(command.substring(6));
  68. // TODO: Rewrite to use ARM.
  69. FileOutputStream fos = null;
  70. OutputStreamWriter out = null;
  71. try
  72. {
  73. String dbg = st.nextToken();
  74. if (dbg.equals("decay"))
  75. {
  76. _print.print(DecayTaskManager.getInstance().toString());
  77. }
  78. else if (dbg.equals("packetsend"))
  79. {
  80. if (st.countTokens() < 2)
  81. {
  82. _print.println("Usage: debug packetsend <charName> <packetData>");
  83. return false;
  84. }
  85. String charName = st.nextToken();
  86. L2PcInstance targetPlayer = L2World.getInstance().getPlayer(charName);
  87. if (targetPlayer == null)
  88. {
  89. _print.println("Player " + charName + " cannot be found online");
  90. return false;
  91. }
  92. AdminForgePacket sp = new AdminForgePacket();
  93. while (st.hasMoreTokens())
  94. {
  95. String b = st.nextToken();
  96. if (!b.isEmpty())
  97. {
  98. sp.addPart("C".getBytes()[0], "0x" + b);
  99. }
  100. }
  101. targetPlayer.sendPacket(sp);
  102. _print.println("Packet sent to player " + charName);
  103. }
  104. else if (dbg.equals("PacketTP"))
  105. {
  106. String str = ThreadPoolManager.getInstance().getPacketStats();
  107. _print.println(str);
  108. int i = 0;
  109. File f = new File("./log/StackTrace-PacketTP-" + i + ".txt");
  110. while (f.exists())
  111. {
  112. i++;
  113. f = new File("./log/StackTrace-PacketTP-" + i + ".txt");
  114. }
  115. f.getParentFile().mkdirs();
  116. fos = new FileOutputStream(f);
  117. out = new OutputStreamWriter(fos, "UTF-8");
  118. out.write(str);
  119. }
  120. else if (dbg.equals("IOPacketTP"))
  121. {
  122. String str = ThreadPoolManager.getInstance().getIOPacketStats();
  123. _print.println(str);
  124. int i = 0;
  125. File f = new File("./log/StackTrace-IOPacketTP-" + i + ".txt");
  126. while (f.exists())
  127. {
  128. i++;
  129. f = new File("./log/StackTrace-IOPacketTP-" + i + ".txt");
  130. }
  131. f.getParentFile().mkdirs();
  132. fos = new FileOutputStream(f);
  133. out = new OutputStreamWriter(fos, "UTF-8");
  134. out.write(str);
  135. }
  136. else if (dbg.equals("GeneralTP"))
  137. {
  138. String str = ThreadPoolManager.getInstance().getGeneralStats();
  139. _print.println(str);
  140. int i = 0;
  141. File f = new File("./log/StackTrace-GeneralTP-" + i + ".txt");
  142. while (f.exists())
  143. {
  144. i++;
  145. f = new File("./log/StackTrace-GeneralTP-" + i + ".txt");
  146. }
  147. f.getParentFile().mkdirs();
  148. fos = new FileOutputStream(f);
  149. out = new OutputStreamWriter(fos, "UTF-8");
  150. out.write(str);
  151. }
  152. else if (dbg.equals("full"))
  153. {
  154. Calendar cal = Calendar.getInstance();
  155. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
  156. StringBuilder sb = new StringBuilder();
  157. sb.append(sdf.format(cal.getTime()));
  158. sb.append("\n\nL2J Server Version: " + Config.SERVER_VERSION);
  159. sb.append("\nDP Revision: " + Config.DATAPACK_VERSION);
  160. sb.append("\n\n");
  161. uptime = _uptime;
  162. sb.append(getServerStatus());
  163. sb.append("\n\n");
  164. sb.append("\n## Java Platform Information ##");
  165. sb.append("\nJava Runtime Name: " + System.getProperty("java.runtime.name"));
  166. sb.append("\nJava Version: " + System.getProperty("java.version"));
  167. sb.append("\nJava Class Version: " + System.getProperty("java.class.version"));
  168. sb.append('\n');
  169. sb.append("\n## Virtual Machine Information ##");
  170. sb.append("\nVM Name: " + System.getProperty("java.vm.name"));
  171. sb.append("\nVM Version: " + System.getProperty("java.vm.version"));
  172. sb.append("\nVM Vendor: " + System.getProperty("java.vm.vendor"));
  173. sb.append("\nVM Info: " + System.getProperty("java.vm.info"));
  174. sb.append('\n');
  175. sb.append("\n## OS Information ##");
  176. sb.append("\nName: " + System.getProperty("os.name"));
  177. sb.append("\nArchiteture: " + System.getProperty("os.arch"));
  178. sb.append("\nVersion: " + System.getProperty("os.version"));
  179. sb.append('\n');
  180. sb.append("\n## Runtime Information ##");
  181. sb.append("\nCPU Count: " + Runtime.getRuntime().availableProcessors());
  182. sb.append("\nCurrent Free Heap Size: " + (Runtime.getRuntime().freeMemory() / 1024 / 1024) + " mb");
  183. sb.append("\nCurrent Heap Size: " + (Runtime.getRuntime().totalMemory() / 1024 / 1024) + " mb");
  184. sb.append("\nMaximum Heap Size: " + (Runtime.getRuntime().maxMemory() / 1024 / 1024) + " mb");
  185. sb.append('\n');
  186. sb.append("\n## Class Path Information ##\n");
  187. String cp = System.getProperty("java.class.path");
  188. String[] libs = cp.split(File.pathSeparator);
  189. for (String lib : libs)
  190. {
  191. sb.append(lib);
  192. sb.append('\n');
  193. }
  194. sb.append('\n');
  195. sb.append("## Threads Information ##\n");
  196. Map<Thread, StackTraceElement[]> allThread = Thread.getAllStackTraces();
  197. FastTable<Entry<Thread, StackTraceElement[]>> entries = new FastTable<>();
  198. entries.setValueComparator(new FastComparator<Entry<Thread, StackTraceElement[]>>()
  199. {
  200. /**
  201. *
  202. */
  203. private static final long serialVersionUID = 1L;
  204. @Override
  205. public boolean areEqual(Entry<Thread, StackTraceElement[]> e1, Entry<Thread, StackTraceElement[]> e2)
  206. {
  207. return e1.getKey().getName().equals(e2.getKey().getName());
  208. }
  209. @Override
  210. public int compare(Entry<Thread, StackTraceElement[]> e1, Entry<Thread, StackTraceElement[]> e2)
  211. {
  212. return e1.getKey().getName().compareTo(e2.getKey().getName());
  213. }
  214. @Override
  215. public int hashCodeOf(Entry<Thread, StackTraceElement[]> e)
  216. {
  217. return e.hashCode();
  218. }
  219. });
  220. entries.addAll(allThread.entrySet());
  221. entries.sort();
  222. for (Entry<Thread, StackTraceElement[]> entry : entries)
  223. {
  224. StackTraceElement[] stes = entry.getValue();
  225. Thread t = entry.getKey();
  226. sb.append("--------------\n");
  227. sb.append(t.toString() + " (" + t.getId() + ")\n");
  228. sb.append("State: " + t.getState() + '\n');
  229. sb.append("isAlive: " + t.isAlive() + " | isDaemon: " + t.isDaemon() + " | isInterrupted: " + t.isInterrupted() + '\n');
  230. sb.append('\n');
  231. for (StackTraceElement ste : stes)
  232. {
  233. sb.append(ste.toString());
  234. sb.append('\n');
  235. }
  236. sb.append('\n');
  237. }
  238. sb.append('\n');
  239. ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
  240. long[] ids = findDeadlockedThreads(mbean);
  241. if ((ids != null) && (ids.length > 0))
  242. {
  243. Thread[] threads = new Thread[ids.length];
  244. for (int i = 0; i < threads.length; i++)
  245. {
  246. threads[i] = findMatchingThread(mbean.getThreadInfo(ids[i]));
  247. }
  248. sb.append("Deadlocked Threads:\n");
  249. sb.append("-------------------\n");
  250. for (Thread thread : threads)
  251. {
  252. System.err.println(thread);
  253. for (StackTraceElement ste : thread.getStackTrace())
  254. {
  255. sb.append("\t" + ste);
  256. sb.append('\n');
  257. }
  258. }
  259. }
  260. sb.append("\n\n## Thread Pool Manager Statistics ##\n");
  261. for (String line : ThreadPoolManager.getInstance().getStats())
  262. {
  263. sb.append(line);
  264. sb.append('\n');
  265. }
  266. int i = 0;
  267. File f = new File("./log/Debug-" + i + ".txt");
  268. while (f.exists())
  269. {
  270. i++;
  271. f = new File("./log/Debug-" + i + ".txt");
  272. }
  273. f.getParentFile().mkdirs();
  274. fos = new FileOutputStream(f);
  275. out = new OutputStreamWriter(fos, "UTF-8");
  276. out.write(sb.toString());
  277. out.flush();
  278. out.close();
  279. fos.close();
  280. _print.println("Debug output saved to log/" + f.getName());
  281. _print.flush();
  282. }
  283. }
  284. catch (Exception e)
  285. {
  286. }
  287. finally
  288. {
  289. try
  290. {
  291. if (out != null)
  292. {
  293. out.close();
  294. }
  295. }
  296. catch (Exception e)
  297. {
  298. }
  299. try
  300. {
  301. if (fos != null)
  302. {
  303. fos.close();
  304. }
  305. }
  306. catch (Exception e)
  307. {
  308. }
  309. }
  310. }
  311. return false;
  312. }
  313. private long[] findDeadlockedThreads(ThreadMXBean mbean)
  314. {
  315. // JDK 1.5 only supports the findMonitorDeadlockedThreads()
  316. // method, so you need to comment out the following three lines
  317. if (mbean.isSynchronizerUsageSupported())
  318. {
  319. return mbean.findDeadlockedThreads();
  320. }
  321. return mbean.findMonitorDeadlockedThreads();
  322. }
  323. private Thread findMatchingThread(ThreadInfo inf)
  324. {
  325. for (Thread thread : Thread.getAllStackTraces().keySet())
  326. {
  327. if (thread.getId() == inf.getThreadId())
  328. {
  329. return thread;
  330. }
  331. }
  332. throw new IllegalStateException("Deadlocked Thread not found");
  333. }
  334. public String getServerStatus()
  335. {
  336. int playerCount = 0, objectCount = 0;
  337. int max = LoginServerThread.getInstance().getMaxPlayer();
  338. playerCount = L2World.getInstance().getAllPlayersCount();
  339. objectCount = L2World.getInstance().getAllVisibleObjectsCount();
  340. int itemCount = 0;
  341. int itemVoidCount = 0;
  342. int monsterCount = 0;
  343. int minionCount = 0;
  344. int minionsGroupCount = 0;
  345. int npcCount = 0;
  346. int charCount = 0;
  347. int pcCount = 0;
  348. int detachedCount = 0;
  349. int doorCount = 0;
  350. int summonCount = 0;
  351. int AICount = 0;
  352. L2Object[] objs = L2World.getInstance().getAllVisibleObjectsArray();
  353. for (L2Object obj : objs)
  354. {
  355. if (obj == null)
  356. {
  357. continue;
  358. }
  359. if (obj instanceof L2Character)
  360. {
  361. if (((L2Character) obj).hasAI())
  362. {
  363. AICount++;
  364. }
  365. }
  366. if (obj instanceof L2ItemInstance)
  367. {
  368. if (((L2ItemInstance) obj).getLocation() == L2ItemInstance.ItemLocation.VOID)
  369. {
  370. itemVoidCount++;
  371. }
  372. else
  373. {
  374. itemCount++;
  375. }
  376. }
  377. else if (obj instanceof L2MonsterInstance)
  378. {
  379. monsterCount++;
  380. if (((L2MonsterInstance) obj).hasMinions())
  381. {
  382. minionCount += ((L2MonsterInstance) obj).getMinionList().countSpawnedMinions();
  383. minionsGroupCount += ((L2MonsterInstance) obj).getMinionList().lazyCountSpawnedMinionsGroups();
  384. }
  385. }
  386. else if (obj instanceof L2Npc)
  387. {
  388. npcCount++;
  389. }
  390. else if (obj instanceof L2PcInstance)
  391. {
  392. pcCount++;
  393. if ((((L2PcInstance) obj).getClient() != null) && ((L2PcInstance) obj).getClient().isDetached())
  394. {
  395. detachedCount++;
  396. }
  397. }
  398. else if (obj instanceof L2Summon)
  399. {
  400. summonCount++;
  401. }
  402. else if (obj instanceof L2DoorInstance)
  403. {
  404. doorCount++;
  405. }
  406. else if (obj instanceof L2Character)
  407. {
  408. charCount++;
  409. }
  410. }
  411. StringBuilder sb = new StringBuilder();
  412. sb.append("Server Status: ");
  413. sb.append("\r\n ---> Player Count: " + playerCount + "/" + max);
  414. sb.append("\r\n ---> Offline Count: " + detachedCount + "/" + playerCount);
  415. sb.append("\r\n +--> Object Count: " + objectCount);
  416. sb.append("\r\n +--> AI Count: " + AICount);
  417. sb.append("\r\n +.... L2Item(Void): " + itemVoidCount);
  418. sb.append("\r\n +.......... L2Item: " + itemCount);
  419. sb.append("\r\n +....... L2Monster: " + monsterCount);
  420. sb.append("\r\n +......... Minions: " + minionCount);
  421. sb.append("\r\n +.. Minions Groups: " + minionsGroupCount);
  422. sb.append("\r\n +........... L2Npc: " + npcCount);
  423. sb.append("\r\n +............ L2Pc: " + pcCount);
  424. sb.append("\r\n +........ L2Summon: " + summonCount);
  425. sb.append("\r\n +.......... L2Door: " + doorCount);
  426. sb.append("\r\n +.......... L2Char: " + charCount);
  427. sb.append("\r\n ---> Ingame Time: " + gameTime());
  428. sb.append("\r\n ---> Server Uptime: " + getUptime(uptime));
  429. sb.append("\r\n ---> GM Count: " + getOnlineGMS());
  430. sb.append("\r\n ---> Threads: " + Thread.activeCount());
  431. sb.append("\r\n RAM Used: " + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1048576)); // 1024 * 1024 = 1048576
  432. sb.append("\r\n");
  433. return sb.toString();
  434. }
  435. private int getOnlineGMS()
  436. {
  437. return AdminTable.getInstance().getAllGms(true).size();
  438. }
  439. private String getUptime(int time)
  440. {
  441. int uptime = (int) System.currentTimeMillis() - time;
  442. uptime = uptime / 1000;
  443. int h = uptime / 3600;
  444. int m = (uptime - (h * 3600)) / 60;
  445. int s = ((uptime - (h * 3600)) - (m * 60));
  446. return h + "hrs " + m + "mins " + s + "secs";
  447. }
  448. private String gameTime()
  449. {
  450. int t = GameTimeController.getInstance().getGameTime();
  451. int h = t / 60;
  452. int m = t % 60;
  453. SimpleDateFormat format = new SimpleDateFormat("H:mm");
  454. Calendar cal = Calendar.getInstance();
  455. cal.set(Calendar.HOUR_OF_DAY, h);
  456. cal.set(Calendar.MINUTE, m);
  457. return format.format(cal.getTime());
  458. }
  459. @Override
  460. public String[] getCommandList()
  461. {
  462. return _commands;
  463. }
  464. }