How to use Arthas

I. Overview

1 Introduction

Arthas is an open source application diagnostic tool developed based on Java, which can help developers monitor and analyze the running status of Java applications in real time, and perform debugging and optimization.
Arthas provides a wealth of command line tools and visual interfaces, including thread stacks, class loaders, memory usage, method execution time, and other aspects of information, which can help users quickly locate and solve performance problems and exceptions in applications . At the same time, Arthas also supports remote diagnosis and operation of applications in the production environment, which greatly improves the efficiency and reliability of application troubleshooting.

2. Solve the problem

When you encounter the following similar problems and are at a loss, Arthas can help you solve them:
Which jar package is this class loaded from? Why are various types of related Exception reported?
Why is the code I changed not executed? Could it be that I didn't commit? Branching wrong?
If you encounter a problem and cannot debug online, can you only republish it by adding a log?
I encountered a problem with the data processing of a certain user online, but it also cannot be debugged online, and cannot be reproduced offline!
Is there a global view into the health of the system?
Is there any way to monitor the real-time running status of the JVM?
How to quickly locate application hotspots and generate flame graphs?
How to find an instance of a class directly from within the JVM?

3. The difference with jstack, jstat,jmap

Arthas, jstack, jstat, and jmap are all Java tuning tools, but they have the following differences:

Arthas is a brand-new Java diagnostic and debugging tool. It can not only execute traditional JVM monitoring commands, but also provides many other advanced features, such as real-time monitoring, dynamic code modification, decompilation, etc. In comparison, jstack, jstat and jmap are more basic, and only provide thread stack information, garbage collection information, heap dump information, etc.
Arthas' interactive command line interface enables developers to view and modify the status of the target JVM through command operations, supports real-time monitoring and dynamic code modification, and greatly facilitates the development and debugging process. However, jstack, jstat and jmap can only be executed through the command line, and cannot perform real-time interaction.
Arthas supports the monitoring of online applications without downtime, which is very advantageous for quick response to online problems. However, jstack, jstat and jmap need to stop the JVM process to perform relevant analysis.

Although Arthas, jstack, jstat, and jmap are all Java tuning tools, Arthas has more powerful functions and an interactive command line interface, which can be used to dynamically modify code, and is more suitable for JVM diagnosis and debugging in an online environment. And jstack, jstat and jmap are more suitable for local development, or scenarios that require downtime analysis.

4. Official documents

https://arthas.aliyun.com/

Two, download

https://arthas.aliyun.com/arthas-boot.jar

3. Quick start

1. Start math-game

curl -O https://arthas.aliyun.com/math-game.jar
java -jar math-game.jar

math-gameIt is a simple program that generates a random number every second, performs prime factorization, and prints out the result of the decomposition.
math-gameSource code: https://github.com/alibaba/arthas/blob/master/math-game/src/main/java/demo/MathGame.java

2. Start arthas

Execute under the command line (use the same user as the target process to start, otherwise the attach may fail):

curl -O https://arthas.aliyun.com/arthas-boot.jar
java -jar arthas-boot.jar

Select the application java process:

C:\Users\scy\Desktop\arthas>java -jar arthas-boot.jar
[INFO] JAVA_HOME: D:\Program Files\java\jdk1.8.0_171\jre
[INFO] arthas-boot version: 3.6.9
[INFO] Found existing java process, please choose one and input the serial number of the process, eg : 1. Then hit ENTER.
* [1]: 2072 org.jetbrains.idea.maven.server.RemoteMavenServer36
  [2]: 11468 org.jetbrains.idea.maven.server.RemoteMavenServer36
  [3]: 18044 oracle.ide.osgi.boot.OracleIdeLauncher
  [4]: 21356 org.jetbrains.idea.maven.server.RemoteMavenServer36
  [5]: 21948 math-game.jar
  [6]: 268

math-gameIf the process is the fifth, enter 5, and then enter 回车/enter. ArthasWill attachgo to the target process and output the log:

[INFO] arthas home: C:\Users\jiuhui-4\.arthas\lib\3.6.9\arthas
[INFO] Try to attach process 21948
[INFO] Attach process 21948 success.
[INFO] arthas-client connect 127.0.0.1 3658
  ,---.  ,------. ,--------.,--.  ,--.  ,---.   ,---.
 /  O  \ |  .--. ''--.  .--'|  '--'  | /  O  \ '   .-'
|  .-.  ||  '--'.'   |  |   |  .--.  ||  .-.  |`.  `-.
|  | |  ||  |\  \    |  |   |  |  |  ||  | |  |.-'    |
`--' `--'`--' '--'   `--'   `--'  `--'`--' `--'`-----'

wiki       https://arthas.aliyun.com/doc
tutorials  https://arthas.aliyun.com/doc/arthas-tutorials.html
version    3.6.9
main_class
pid        21948
time       2023-06-21 16:20:41

[arthas@21948]$

If the following exception occurs:

[ERROR] Can not read arthas version from: arthas.aliyun.com/api/latest_…
[ERROR] Can not find Arthas under local: /root/.arthas/lib and remote repo mirror: aliyun
[ERROR] Unable to download arthas from remote server, please download the full package according to wiki: github.com/alibaba/art…

Follow the prompts githubto download the full package. Download address: https://github.com/alibaba/arthas/releases to release to download arthas-bin.zip

After decompression arthas-bin.zip, run it directly java -jar arthas-boot.jarand enter the corresponding javaprogram number to proceed arthas.

3. Check the dashboard

Enter dashboard, press 回车/enter, the information of the current process will be displayed, press ctrl+cto interrupt the execution.

ID   NAME                          GROUP          PRIORITY  STATE    %CPU      DELTA_TIM TIME      INTERRUPT DAEMON
2    Reference Handler             system         10        WAITING  0.0       0.000     0:0.000   false     true
3    Finalizer                     system         8         WAITING  0.0       0.000     0:0.000   false     true
4    Signal Dispatcher             system         9         RUNNABLE 0.0       0.000     0:0.000   false     true
5    Attach Listener               system         5         RUNNABLE 0.0       0.000     0:0.015   false     true
12   arthas-timer                  system         5         WAITING  0.0       0.000     0:0.000   false     true
15   arthas-NettyHttpTelnetBootstr system         5         RUNNABLE 0.0       0.000     0:0.015   false     true
16   arthas-NettyWebsocketTtyBoots system         5         RUNNABLE 0.0       0.000     0:0.000   false     true
17   arthas-NettyWebsocketTtyBoots system         5         RUNNABLE 0.0       0.000     0:0.015   false     true
18   arthas-shell-server           system         5         TIMED_WA 0.0       0.000     0:0.000   false     true
19   arthas-session-manager        system         5         TIMED_WA 0.0       0.000     0:0.000   false     true
20   arthas-UserStat               system         5         WAITING  0.0       0.000     0:0.000   false     true
Memory                    used    total    max     usage    GC
heap                      110M    489M     7234M   1.53%    gc.ps_scavenge.count          0
ps_eden_space             110M    128M     2670M   4.14%    gc.ps_scavenge.time(ms)       0
ps_survivor_space         0K      21504K   21504K  0.00%    gc.ps_marksweep.count         0
ps_old_gen                0K      348160K          0.00%    gc.ps_marksweep.time(ms)      0
nonheap                   27M     28M      -1      97.22%
code_cache                6M      6M       240M    2.55%
metaspace                 19M     20M      -1      97.15%
compressed_class_space    2M      2M       1024M   0.23%
Runtime
os.name                                                     Windows 10
os.version                                                  10.0
java.version                                                1.8.0_171
java.home                                                   D:\Program Files\java\jdk1.8.0_171\jre
systemload.average                                          -1.00
processors                                                  12
timestamp/uptime                                            Wed Jun 21 16:33:43 CST 2023/885s

4. thread command

Through threadthe command to get math-gamethe processMain Class

thread 1will print the thread ID 1's stack, usually mainthe thread of the function.

[arthas@21948]$ thread 1 | grep 'main('
    at demo.MathGame.main(MathGame.java:17)

5. jad command

Decompile Main Class by jad

[arthas@21948]$ jad demo.MathGame

ClassLoader:
+-sun.misc.Launcher$AppClassLoader@55f96302
  +-sun.misc.Launcher$ExtClassLoader@74a14482

Location:
/C:/Users/scy/Desktop/arthas/math-game.jar

       /*
        * Decompiled with CFR.
        */
       package demo;

       import java.util.ArrayList;
       import java.util.List;
       import java.util.Random;
       import java.util.concurrent.TimeUnit;

       public class MathGame {
    
    
           private static Random random = new Random();
           private int illegalArgumentCount = 0;

           public static void main(String[] args) throws InterruptedException {
    
    
               MathGame game = new MathGame();
               while (true) {
    
    
/*16*/             game.run();
/*17*/             TimeUnit.SECONDS.sleep(1L);
               }
           }

           public void run() throws InterruptedException {
    
    
               try {
    
    
/*23*/             int number = random.nextInt() / 10000;
/*24*/             List<Integer> primeFactors = this.primeFactors(number);
/*25*/             MathGame.print(number, primeFactors);
               }
               catch (Exception e) {
    
    
/*28*/             System.out.println(String.format("illegalArgumentCount:%3d, ", this.illegalArgumentCount) + e.getMessage());
               }
           }

           public static void print(int number, List<Integer> primeFactors) {
    
    
               StringBuffer sb = new StringBuffer(number + "=");
/*34*/         for (int factor : primeFactors) {
    
    
/*35*/             sb.append(factor).append('*');
               }
/*37*/         if (sb.charAt(sb.length() - 1) == '*') {
    
    
/*38*/             sb.deleteCharAt(sb.length() - 1);
               }
/*40*/         System.out.println(sb);
           }

           public List<Integer> primeFactors(int number) {
    
    
/*44*/         if (number < 2) {
    
    
/*45*/             ++this.illegalArgumentCount;
                   throw new IllegalArgumentException("number is: " + number + ", need >= 2");
               }
               ArrayList<Integer> result = new ArrayList<Integer>();
/*50*/         int i = 2;
/*51*/         while (i <= number) {
    
    
/*52*/             if (number % i == 0) {
    
    
/*53*/                 result.add(i);
/*54*/                 number /= i;
/*55*/                 i = 2;
                       continue;
                   }
/*57*/             ++i;
               }
/*61*/         return result;
           }
       }

Affect(row-cnt:1) cost in 432 ms.
[arthas@21948]$

6. watch command

Use watchthe command to view demo.MathGame#primeFactorsthe return value of the function:

[arthas@21948]$ watch demo.MathGame primeFactors returnObj
Press Q or Ctrl+C to abort.
Affect(class count: 1 , method count: 1) cost in 66 ms, listenerId: 1
method=demo.MathGame.primeFactors location=AtExit
ts=2023-06-21 16:43:40; [cost=0.7314ms] result=@ArrayList[
    @Integer[2],
    @Integer[7],
    @Integer[13159],
]
method=demo.MathGame.primeFactors location=AtExceptionExit
ts=2023-06-21 16:43:41; [cost=0.1341ms] result=null
method=demo.MathGame.primeFactors location=AtExit
ts=2023-06-21 16:43:42; [cost=0.4295ms] result=@ArrayList[
    @Integer[3],
    @Integer[14197],
]

More functions can be viewed in advanced use: https://arthas.aliyun.com/doc/advanced-use.html

01. View the parameters, return value, and exception thrown of a method.

watch 全类名 方法名 returnObj// View the return value of the method

watch 全类名 方法名 '{params, throwExp}' -e// View parameters and exceptions, the method name supports wildcard *, -e means only capture the request when an exception is thrown, followed by -x 2, -x means "object level".

02. Set the output json format.

options json-format true//Set to output in json format.

7. Exit arthas

If you just exit the current connection, you can use quitthe or exitcommand. AttachTo the target process arthaswill continue to run, the port will remain open, and you can connect directly the next time you connect.

If you want to exit completely arthas, you can execute stopthe command.

8. Command summary

1) help: View all available Arthascommands and descriptions.

2) jvm: View the relevant information of the current JVM, including heap size, GC strategy, number of threads, etc.

3) classloader: View and operate class loader information, including loaded classes, class loader hierarchy, etc.

4) thread( Cpu usage is too high/deadlock ): View and operate thread status and stack information, including thread number, status, blocking information, etc.

5) trace( method time-consuming and tracking ): track the execution of the specified method, output method parameters, return value, time-consuming and other information.

6) watch( View function parameters/return value/abnormal information ): Monitor the execution of the specified method, and automatically trigger the corresponding operation when the specified condition is met.

7) sc: View and operate Spring context information, including Bean definition, Bean life cycle, etc.

8) sql: View and operate database connection and SQL execution, support common JDBC drivers.

9) dashboard( Memory leak ): Start the visual interface of Arthas to display various running conditions of the current application.

10) jad: Decompile the source code

11)tt:

  • Find exceptions and view exceptions tt -t com.UserServiceImpl check//Record method call information

    tt -i 1001//After the above command finds an exception, check the exception

    tt -i 1001 -p//Recall, reproduce the exception

  • View and update class member variable values

    ognl '@com.Arthas@hashSet'//Check

    ognl '@ com.Arthas @hashSet.add ("test")' //update

4. Reference

JVM tuning artifact, use Arthas to release the full potential of Java application performance
https://juejin.cn/post/7234545968094773307

Arthas
https://blog.csdn.net/weixin_42061487/article/details/120520260

ARTHAS advanced learning (common commands)
https://www.cnblogs.com/theRhyme/p/10659265.html

Guess you like

Origin blog.csdn.net/qq_25775675/article/details/107923477