DebugHandler.java 15 KB

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