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.enums.ItemLocation;
  41. import com.l2jserver.gameserver.handler.ITelnetHandler;
  42. import com.l2jserver.gameserver.model.L2Object;
  43. import com.l2jserver.gameserver.model.L2World;
  44. import com.l2jserver.gameserver.model.actor.L2Character;
  45. import com.l2jserver.gameserver.model.actor.L2Npc;
  46. import com.l2jserver.gameserver.model.actor.L2Summon;
  47. import com.l2jserver.gameserver.model.actor.instance.L2DoorInstance;
  48. import com.l2jserver.gameserver.model.actor.instance.L2MonsterInstance;
  49. import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
  50. import com.l2jserver.gameserver.model.items.instance.L2ItemInstance;
  51. import com.l2jserver.gameserver.network.serverpackets.AdminForgePacket;
  52. import com.l2jserver.gameserver.taskmanager.DecayTaskManager;
  53. /**
  54. * @author UnAfraid
  55. */
  56. public class DebugHandler implements ITelnetHandler
  57. {
  58. private final String[] _commands =
  59. {
  60. "debug"
  61. };
  62. private int uptime = 0;
  63. @Override
  64. public boolean useCommand(String command, PrintWriter _print, Socket _cSocket, int _uptime)
  65. {
  66. if (command.startsWith("debug") && (command.length() > 6))
  67. {
  68. StringTokenizer st = new StringTokenizer(command.substring(6));
  69. // TODO: Rewrite to use ARM.
  70. FileOutputStream fos = null;
  71. OutputStreamWriter out = null;
  72. try
  73. {
  74. String dbg = st.nextToken();
  75. if (dbg.equals("decay"))
  76. {
  77. _print.print(DecayTaskManager.getInstance().toString());
  78. }
  79. else if (dbg.equals("packetsend"))
  80. {
  81. if (st.countTokens() < 2)
  82. {
  83. _print.println("Usage: debug packetsend <charName> <packetData>");
  84. return false;
  85. }
  86. String charName = st.nextToken();
  87. L2PcInstance targetPlayer = L2World.getInstance().getPlayer(charName);
  88. if (targetPlayer == null)
  89. {
  90. _print.println("Player " + charName + " cannot be found online");
  91. return false;
  92. }
  93. AdminForgePacket sp = new AdminForgePacket();
  94. while (st.hasMoreTokens())
  95. {
  96. String b = st.nextToken();
  97. if (!b.isEmpty())
  98. {
  99. sp.addPart("C".getBytes()[0], "0x" + b);
  100. }
  101. }
  102. targetPlayer.sendPacket(sp);
  103. _print.println("Packet sent to player " + charName);
  104. }
  105. else if (dbg.equals("PacketTP"))
  106. {
  107. String str = ThreadPoolManager.getInstance().getPacketStats();
  108. _print.println(str);
  109. int i = 0;
  110. File f = new File("./log/StackTrace-PacketTP-" + i + ".txt");
  111. while (f.exists())
  112. {
  113. i++;
  114. f = new File("./log/StackTrace-PacketTP-" + i + ".txt");
  115. }
  116. f.getParentFile().mkdirs();
  117. fos = new FileOutputStream(f);
  118. out = new OutputStreamWriter(fos, "UTF-8");
  119. out.write(str);
  120. }
  121. else if (dbg.equals("IOPacketTP"))
  122. {
  123. String str = ThreadPoolManager.getInstance().getIOPacketStats();
  124. _print.println(str);
  125. int i = 0;
  126. File f = new File("./log/StackTrace-IOPacketTP-" + i + ".txt");
  127. while (f.exists())
  128. {
  129. i++;
  130. f = new File("./log/StackTrace-IOPacketTP-" + i + ".txt");
  131. }
  132. f.getParentFile().mkdirs();
  133. fos = new FileOutputStream(f);
  134. out = new OutputStreamWriter(fos, "UTF-8");
  135. out.write(str);
  136. }
  137. else if (dbg.equals("GeneralTP"))
  138. {
  139. String str = ThreadPoolManager.getInstance().getGeneralStats();
  140. _print.println(str);
  141. int i = 0;
  142. File f = new File("./log/StackTrace-GeneralTP-" + i + ".txt");
  143. while (f.exists())
  144. {
  145. i++;
  146. f = new File("./log/StackTrace-GeneralTP-" + i + ".txt");
  147. }
  148. f.getParentFile().mkdirs();
  149. fos = new FileOutputStream(f);
  150. out = new OutputStreamWriter(fos, "UTF-8");
  151. out.write(str);
  152. }
  153. else if (dbg.equals("full"))
  154. {
  155. Calendar cal = Calendar.getInstance();
  156. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
  157. StringBuilder sb = new StringBuilder();
  158. sb.append(sdf.format(cal.getTime()));
  159. sb.append("\n\nL2J Server Version: " + Config.SERVER_VERSION);
  160. sb.append("\nDP Revision: " + Config.DATAPACK_VERSION);
  161. sb.append("\n\n");
  162. uptime = _uptime;
  163. sb.append(getServerStatus());
  164. sb.append("\n\n");
  165. sb.append("\n## Java Platform Information ##");
  166. sb.append("\nJava Runtime Name: " + System.getProperty("java.runtime.name"));
  167. sb.append("\nJava Version: " + System.getProperty("java.version"));
  168. sb.append("\nJava Class Version: " + System.getProperty("java.class.version"));
  169. sb.append('\n');
  170. sb.append("\n## Virtual Machine Information ##");
  171. sb.append("\nVM Name: " + System.getProperty("java.vm.name"));
  172. sb.append("\nVM Version: " + System.getProperty("java.vm.version"));
  173. sb.append("\nVM Vendor: " + System.getProperty("java.vm.vendor"));
  174. sb.append("\nVM Info: " + System.getProperty("java.vm.info"));
  175. sb.append('\n');
  176. sb.append("\n## OS Information ##");
  177. sb.append("\nName: " + System.getProperty("os.name"));
  178. sb.append("\nArchiteture: " + System.getProperty("os.arch"));
  179. sb.append("\nVersion: " + System.getProperty("os.version"));
  180. sb.append('\n');
  181. sb.append("\n## Runtime Information ##");
  182. sb.append("\nCPU Count: " + Runtime.getRuntime().availableProcessors());
  183. sb.append("\nCurrent Free Heap Size: " + (Runtime.getRuntime().freeMemory() / 1024 / 1024) + " mb");
  184. sb.append("\nCurrent Heap Size: " + (Runtime.getRuntime().totalMemory() / 1024 / 1024) + " mb");
  185. sb.append("\nMaximum Heap Size: " + (Runtime.getRuntime().maxMemory() / 1024 / 1024) + " mb");
  186. sb.append('\n');
  187. sb.append("\n## Class Path Information ##\n");
  188. String cp = System.getProperty("java.class.path");
  189. String[] libs = cp.split(File.pathSeparator);
  190. for (String lib : libs)
  191. {
  192. sb.append(lib);
  193. sb.append('\n');
  194. }
  195. sb.append('\n');
  196. sb.append("## Threads Information ##\n");
  197. Map<Thread, StackTraceElement[]> allThread = Thread.getAllStackTraces();
  198. FastTable<Entry<Thread, StackTraceElement[]>> entries = new FastTable<>();
  199. entries.setValueComparator(new FastComparator<Entry<Thread, StackTraceElement[]>>()
  200. {
  201. /**
  202. *
  203. */
  204. private static final long serialVersionUID = 1L;
  205. @Override
  206. public boolean areEqual(Entry<Thread, StackTraceElement[]> e1, Entry<Thread, StackTraceElement[]> e2)
  207. {
  208. return e1.getKey().getName().equals(e2.getKey().getName());
  209. }
  210. @Override
  211. public int compare(Entry<Thread, StackTraceElement[]> e1, Entry<Thread, StackTraceElement[]> e2)
  212. {
  213. return e1.getKey().getName().compareTo(e2.getKey().getName());
  214. }
  215. @Override
  216. public int hashCodeOf(Entry<Thread, StackTraceElement[]> e)
  217. {
  218. return e.hashCode();
  219. }
  220. });
  221. entries.addAll(allThread.entrySet());
  222. entries.sort();
  223. for (Entry<Thread, StackTraceElement[]> entry : entries)
  224. {
  225. StackTraceElement[] stes = entry.getValue();
  226. Thread t = entry.getKey();
  227. sb.append("--------------\n");
  228. sb.append(t.toString() + " (" + t.getId() + ")\n");
  229. sb.append("State: " + t.getState() + '\n');
  230. sb.append("isAlive: " + t.isAlive() + " | isDaemon: " + t.isDaemon() + " | isInterrupted: " + t.isInterrupted() + '\n');
  231. sb.append('\n');
  232. for (StackTraceElement ste : stes)
  233. {
  234. sb.append(ste.toString());
  235. sb.append('\n');
  236. }
  237. sb.append('\n');
  238. }
  239. sb.append('\n');
  240. ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
  241. long[] ids = findDeadlockedThreads(mbean);
  242. if ((ids != null) && (ids.length > 0))
  243. {
  244. Thread[] threads = new Thread[ids.length];
  245. for (int i = 0; i < threads.length; i++)
  246. {
  247. threads[i] = findMatchingThread(mbean.getThreadInfo(ids[i]));
  248. }
  249. sb.append("Deadlocked Threads:\n");
  250. sb.append("-------------------\n");
  251. for (Thread thread : threads)
  252. {
  253. System.err.println(thread);
  254. for (StackTraceElement ste : thread.getStackTrace())
  255. {
  256. sb.append("\t" + ste);
  257. sb.append('\n');
  258. }
  259. }
  260. }
  261. sb.append("\n\n## Thread Pool Manager Statistics ##\n");
  262. for (String line : ThreadPoolManager.getInstance().getStats())
  263. {
  264. sb.append(line);
  265. sb.append('\n');
  266. }
  267. int i = 0;
  268. File f = new File("./log/Debug-" + i + ".txt");
  269. while (f.exists())
  270. {
  271. i++;
  272. f = new File("./log/Debug-" + i + ".txt");
  273. }
  274. f.getParentFile().mkdirs();
  275. fos = new FileOutputStream(f);
  276. out = new OutputStreamWriter(fos, "UTF-8");
  277. out.write(sb.toString());
  278. out.flush();
  279. out.close();
  280. fos.close();
  281. _print.println("Debug output saved to log/" + f.getName());
  282. _print.flush();
  283. }
  284. }
  285. catch (Exception e)
  286. {
  287. }
  288. finally
  289. {
  290. try
  291. {
  292. if (out != null)
  293. {
  294. out.close();
  295. }
  296. }
  297. catch (Exception e)
  298. {
  299. }
  300. try
  301. {
  302. if (fos != null)
  303. {
  304. fos.close();
  305. }
  306. }
  307. catch (Exception e)
  308. {
  309. }
  310. }
  311. }
  312. return false;
  313. }
  314. private long[] findDeadlockedThreads(ThreadMXBean mbean)
  315. {
  316. // JDK 1.5 only supports the findMonitorDeadlockedThreads()
  317. // method, so you need to comment out the following three lines
  318. if (mbean.isSynchronizerUsageSupported())
  319. {
  320. return mbean.findDeadlockedThreads();
  321. }
  322. return mbean.findMonitorDeadlockedThreads();
  323. }
  324. private Thread findMatchingThread(ThreadInfo inf)
  325. {
  326. for (Thread thread : Thread.getAllStackTraces().keySet())
  327. {
  328. if (thread.getId() == inf.getThreadId())
  329. {
  330. return thread;
  331. }
  332. }
  333. throw new IllegalStateException("Deadlocked Thread not found");
  334. }
  335. public String getServerStatus()
  336. {
  337. int playerCount = 0, objectCount = 0;
  338. int max = LoginServerThread.getInstance().getMaxPlayer();
  339. playerCount = L2World.getInstance().getAllPlayersCount();
  340. objectCount = L2World.getInstance().getVisibleObjectsCount();
  341. int itemCount = 0;
  342. int itemVoidCount = 0;
  343. int monsterCount = 0;
  344. int minionCount = 0;
  345. int minionsGroupCount = 0;
  346. int npcCount = 0;
  347. int charCount = 0;
  348. int pcCount = 0;
  349. int detachedCount = 0;
  350. int doorCount = 0;
  351. int summonCount = 0;
  352. int AICount = 0;
  353. for (L2Object obj : L2World.getInstance().getVisibleObjects())
  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).getItemLocation() == 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. }