DebugHandler.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. /*
  2. * Copyright (C) 2004-2014 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.gameserver.GameTimeController;
  36. import com.l2jserver.gameserver.LoginServerThread;
  37. import com.l2jserver.gameserver.ThreadPoolManager;
  38. import com.l2jserver.gameserver.datatables.AdminTable;
  39. import com.l2jserver.gameserver.enums.ItemLocation;
  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\n");
  159. uptime = _uptime;
  160. sb.append(getServerStatus());
  161. sb.append("\n\n");
  162. sb.append("\n## Java Platform Information ##");
  163. sb.append("\nJava Runtime Name: " + System.getProperty("java.runtime.name"));
  164. sb.append("\nJava Version: " + System.getProperty("java.version"));
  165. sb.append("\nJava Class Version: " + System.getProperty("java.class.version"));
  166. sb.append('\n');
  167. sb.append("\n## Virtual Machine Information ##");
  168. sb.append("\nVM Name: " + System.getProperty("java.vm.name"));
  169. sb.append("\nVM Version: " + System.getProperty("java.vm.version"));
  170. sb.append("\nVM Vendor: " + System.getProperty("java.vm.vendor"));
  171. sb.append("\nVM Info: " + System.getProperty("java.vm.info"));
  172. sb.append('\n');
  173. sb.append("\n## OS Information ##");
  174. sb.append("\nName: " + System.getProperty("os.name"));
  175. sb.append("\nArchiteture: " + System.getProperty("os.arch"));
  176. sb.append("\nVersion: " + System.getProperty("os.version"));
  177. sb.append('\n');
  178. sb.append("\n## Runtime Information ##");
  179. sb.append("\nCPU Count: " + Runtime.getRuntime().availableProcessors());
  180. sb.append("\nCurrent Free Heap Size: " + (Runtime.getRuntime().freeMemory() / 1024 / 1024) + " mb");
  181. sb.append("\nCurrent Heap Size: " + (Runtime.getRuntime().totalMemory() / 1024 / 1024) + " mb");
  182. sb.append("\nMaximum Heap Size: " + (Runtime.getRuntime().maxMemory() / 1024 / 1024) + " mb");
  183. sb.append('\n');
  184. sb.append("\n## Class Path Information ##\n");
  185. String cp = System.getProperty("java.class.path");
  186. String[] libs = cp.split(File.pathSeparator);
  187. for (String lib : libs)
  188. {
  189. sb.append(lib);
  190. sb.append('\n');
  191. }
  192. sb.append('\n');
  193. sb.append("## Threads Information ##\n");
  194. Map<Thread, StackTraceElement[]> allThread = Thread.getAllStackTraces();
  195. FastTable<Entry<Thread, StackTraceElement[]>> entries = new FastTable<>();
  196. entries.setValueComparator(new FastComparator<Entry<Thread, StackTraceElement[]>>()
  197. {
  198. /**
  199. *
  200. */
  201. private static final long serialVersionUID = 1L;
  202. @Override
  203. public boolean areEqual(Entry<Thread, StackTraceElement[]> e1, Entry<Thread, StackTraceElement[]> e2)
  204. {
  205. return e1.getKey().getName().equals(e2.getKey().getName());
  206. }
  207. @Override
  208. public int compare(Entry<Thread, StackTraceElement[]> e1, Entry<Thread, StackTraceElement[]> e2)
  209. {
  210. return e1.getKey().getName().compareTo(e2.getKey().getName());
  211. }
  212. @Override
  213. public int hashCodeOf(Entry<Thread, StackTraceElement[]> e)
  214. {
  215. return e.hashCode();
  216. }
  217. });
  218. entries.addAll(allThread.entrySet());
  219. entries.sort();
  220. for (Entry<Thread, StackTraceElement[]> entry : entries)
  221. {
  222. StackTraceElement[] stes = entry.getValue();
  223. Thread t = entry.getKey();
  224. sb.append("--------------\n");
  225. sb.append(t.toString() + " (" + t.getId() + ")\n");
  226. sb.append("State: " + t.getState() + '\n');
  227. sb.append("isAlive: " + t.isAlive() + " | isDaemon: " + t.isDaemon() + " | isInterrupted: " + t.isInterrupted() + '\n');
  228. sb.append('\n');
  229. for (StackTraceElement ste : stes)
  230. {
  231. sb.append(ste.toString());
  232. sb.append('\n');
  233. }
  234. sb.append('\n');
  235. }
  236. sb.append('\n');
  237. ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
  238. long[] ids = findDeadlockedThreads(mbean);
  239. if ((ids != null) && (ids.length > 0))
  240. {
  241. Thread[] threads = new Thread[ids.length];
  242. for (int i = 0; i < threads.length; i++)
  243. {
  244. threads[i] = findMatchingThread(mbean.getThreadInfo(ids[i]));
  245. }
  246. sb.append("Deadlocked Threads:\n");
  247. sb.append("-------------------\n");
  248. for (Thread thread : threads)
  249. {
  250. System.err.println(thread);
  251. for (StackTraceElement ste : thread.getStackTrace())
  252. {
  253. sb.append("\t" + ste);
  254. sb.append('\n');
  255. }
  256. }
  257. }
  258. sb.append("\n\n## Thread Pool Manager Statistics ##\n");
  259. for (String line : ThreadPoolManager.getInstance().getStats())
  260. {
  261. sb.append(line);
  262. sb.append('\n');
  263. }
  264. int i = 0;
  265. File f = new File("./log/Debug-" + i + ".txt");
  266. while (f.exists())
  267. {
  268. i++;
  269. f = new File("./log/Debug-" + i + ".txt");
  270. }
  271. f.getParentFile().mkdirs();
  272. fos = new FileOutputStream(f);
  273. out = new OutputStreamWriter(fos, "UTF-8");
  274. out.write(sb.toString());
  275. out.flush();
  276. out.close();
  277. fos.close();
  278. _print.println("Debug output saved to log/" + f.getName());
  279. _print.flush();
  280. }
  281. }
  282. catch (Exception e)
  283. {
  284. }
  285. finally
  286. {
  287. try
  288. {
  289. if (out != null)
  290. {
  291. out.close();
  292. }
  293. }
  294. catch (Exception e)
  295. {
  296. }
  297. try
  298. {
  299. if (fos != null)
  300. {
  301. fos.close();
  302. }
  303. }
  304. catch (Exception e)
  305. {
  306. }
  307. }
  308. }
  309. return false;
  310. }
  311. private long[] findDeadlockedThreads(ThreadMXBean mbean)
  312. {
  313. // JDK 1.5 only supports the findMonitorDeadlockedThreads()
  314. // method, so you need to comment out the following three lines
  315. if (mbean.isSynchronizerUsageSupported())
  316. {
  317. return mbean.findDeadlockedThreads();
  318. }
  319. return mbean.findMonitorDeadlockedThreads();
  320. }
  321. private Thread findMatchingThread(ThreadInfo inf)
  322. {
  323. for (Thread thread : Thread.getAllStackTraces().keySet())
  324. {
  325. if (thread.getId() == inf.getThreadId())
  326. {
  327. return thread;
  328. }
  329. }
  330. throw new IllegalStateException("Deadlocked Thread not found");
  331. }
  332. public String getServerStatus()
  333. {
  334. int playerCount = 0, objectCount = 0;
  335. int max = LoginServerThread.getInstance().getMaxPlayer();
  336. playerCount = L2World.getInstance().getAllPlayersCount();
  337. objectCount = L2World.getInstance().getVisibleObjectsCount();
  338. int itemCount = 0;
  339. int itemVoidCount = 0;
  340. int monsterCount = 0;
  341. int minionCount = 0;
  342. int minionsGroupCount = 0;
  343. int npcCount = 0;
  344. int charCount = 0;
  345. int pcCount = 0;
  346. int detachedCount = 0;
  347. int doorCount = 0;
  348. int summonCount = 0;
  349. int AICount = 0;
  350. for (L2Object obj : L2World.getInstance().getVisibleObjects())
  351. {
  352. if (obj == null)
  353. {
  354. continue;
  355. }
  356. if (obj instanceof L2Character)
  357. {
  358. if (((L2Character) obj).hasAI())
  359. {
  360. AICount++;
  361. }
  362. }
  363. if (obj instanceof L2ItemInstance)
  364. {
  365. if (((L2ItemInstance) obj).getItemLocation() == ItemLocation.VOID)
  366. {
  367. itemVoidCount++;
  368. }
  369. else
  370. {
  371. itemCount++;
  372. }
  373. }
  374. else if (obj instanceof L2MonsterInstance)
  375. {
  376. monsterCount++;
  377. if (((L2MonsterInstance) obj).hasMinions())
  378. {
  379. minionCount += ((L2MonsterInstance) obj).getMinionList().countSpawnedMinions();
  380. minionsGroupCount += ((L2MonsterInstance) obj).getMinionList().lazyCountSpawnedMinionsGroups();
  381. }
  382. }
  383. else if (obj instanceof L2Npc)
  384. {
  385. npcCount++;
  386. }
  387. else if (obj instanceof L2PcInstance)
  388. {
  389. pcCount++;
  390. if ((((L2PcInstance) obj).getClient() != null) && ((L2PcInstance) obj).getClient().isDetached())
  391. {
  392. detachedCount++;
  393. }
  394. }
  395. else if (obj instanceof L2Summon)
  396. {
  397. summonCount++;
  398. }
  399. else if (obj instanceof L2DoorInstance)
  400. {
  401. doorCount++;
  402. }
  403. else if (obj instanceof L2Character)
  404. {
  405. charCount++;
  406. }
  407. }
  408. StringBuilder sb = new StringBuilder();
  409. sb.append("Server Status: ");
  410. sb.append("\r\n ---> Player Count: " + playerCount + "/" + max);
  411. sb.append("\r\n ---> Offline Count: " + detachedCount + "/" + playerCount);
  412. sb.append("\r\n +--> Object Count: " + objectCount);
  413. sb.append("\r\n +--> AI Count: " + AICount);
  414. sb.append("\r\n +.... L2Item(Void): " + itemVoidCount);
  415. sb.append("\r\n +.......... L2Item: " + itemCount);
  416. sb.append("\r\n +....... L2Monster: " + monsterCount);
  417. sb.append("\r\n +......... Minions: " + minionCount);
  418. sb.append("\r\n +.. Minions Groups: " + minionsGroupCount);
  419. sb.append("\r\n +........... L2Npc: " + npcCount);
  420. sb.append("\r\n +............ L2Pc: " + pcCount);
  421. sb.append("\r\n +........ L2Summon: " + summonCount);
  422. sb.append("\r\n +.......... L2Door: " + doorCount);
  423. sb.append("\r\n +.......... L2Char: " + charCount);
  424. sb.append("\r\n ---> Ingame Time: " + gameTime());
  425. sb.append("\r\n ---> Server Uptime: " + getUptime(uptime));
  426. sb.append("\r\n ---> GM Count: " + getOnlineGMS());
  427. sb.append("\r\n ---> Threads: " + Thread.activeCount());
  428. sb.append("\r\n RAM Used: " + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1048576)); // 1024 * 1024 = 1048576
  429. sb.append("\r\n");
  430. return sb.toString();
  431. }
  432. private int getOnlineGMS()
  433. {
  434. return AdminTable.getInstance().getAllGms(true).size();
  435. }
  436. private String getUptime(int time)
  437. {
  438. int uptime = (int) System.currentTimeMillis() - time;
  439. uptime = uptime / 1000;
  440. int h = uptime / 3600;
  441. int m = (uptime - (h * 3600)) / 60;
  442. int s = ((uptime - (h * 3600)) - (m * 60));
  443. return h + "hrs " + m + "mins " + s + "secs";
  444. }
  445. private String gameTime()
  446. {
  447. int t = GameTimeController.getInstance().getGameTime();
  448. int h = t / 60;
  449. int m = t % 60;
  450. SimpleDateFormat format = new SimpleDateFormat("H:mm");
  451. Calendar cal = Calendar.getInstance();
  452. cal.set(Calendar.HOUR_OF_DAY, h);
  453. cal.set(Calendar.MINUTE, m);
  454. return format.format(cal.getTime());
  455. }
  456. @Override
  457. public String[] getCommandList()
  458. {
  459. return _commands;
  460. }
  461. }