DebugHandler.java 14 KB

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