[toc]

Introduction to the

Arthas is known in Chinese as Arthas

The official address: alibaba. Making. IO/arthas

The installation

usearthas-boot(recommended)

Download arthas-boot.jar and start it with java-jar: Curl - O https://alibaba.github.io/arthas/arthas-boot.jar Java - jar arthas - boot. Java - jar jar print help information arthas - boot. The jar - h If the download speed is slow, you can use aliyun's image: Java -jar arthas-boot.jar --repo-mirror aliyun --use-http Can use gitee mirror curl - O https://arthas.gitee.io/arthas-boot.jarCopy the code

Run the as.sh command to start the system

Mac installation as sh, and set the shortcut curl - sk https://arthas.gitee.io/arthas-boot.jar - o ~ /. Arthas - boot. Jar && echo "alias as. Sh = 'Java Jar --repo-mirror aliyun --use-http'" >> ~/. Bashrc && source ~/. Bashrc If ZSH is installed, run the following command: curl -sk https://arthas.gitee.io/arthas-boot.jar -o ~/.arthas-boot.jar && echo "alias as.sh='java -jar ~/.arthas-boot.jar --repo-mirror aliyun --use-http'" >> ~/.zshrc && source ~/.zshrc Then just type as.sh on the command line to startCopy the code

Access arthas directly through the Cloud Toolkit plug-in

uninstall

  • In Linux/Unix/Mac platforms

    Delete the following files:

    rm -rf ~/.arthas/
    rm -rf ~/logs/arthas
    Copy the code
  • Windows platform directly delete the. Arthas and logs/arthas directories under user Home

Enter the arthas

  1. Start the program that needs to be diagnosed first, and then arthas

java -jar arthas-boot.jar

  1. Select the corresponding process ID

  2. Arthas is attached successfully if you see the following page

  3. You can then use arthad related commands to perform diagnostics

Exit arthas

To exit the current connection, use the quit or exit command. Arthas attached to the target process will continue to run and the port will remain open for direct connection next time.

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

Quick start

Common commands

Dashboard: the dashboard

Function: Displays the real-time data panel of the current system. Press Q or CTRL + C to exit

Jad: decompile a class or a method of a class

Purpose: decompile bytecode files into source code

Decompiling classes:

jad com.shinemo.todo.domain.TodoDO 
Copy the code

The compiling method:

Show details of the compiled jad com. Shinemo. Wangge. Core. Service. Todo. Impl. TodoServiceImpl operateTodoThing jad only display source code, source - only com.shinemo.wangge.core.service.todo.impl.TodoServiceImpl operateTodoThingCopy the code

Thread Thread-related commands

Function: View thread stack information for the current JVM

Thread-n: lists the threads with Top N CPU usage.

Thread ID: Displays the running stack for the specified thread

Thread-b: Identifies the threads currently blocking other threads

Deadlock cases:

@getMapping ("/test") @smignore public ApiResult<String> test() {/** Create resource */ Object resourceA = new Object(); Object resourceB = new Object(); ThreadA = new Thread(() -> {synchronized (resourceA) {log.info(thread.currentThread () + "get") ResourceA"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } log.info(Thread.currentThread() + "waiting get resourceB"); synchronized (resourceB) { log.info(Thread.currentThread() + " get resourceB"); }}}); Thread threadB = new Thread(() -> { synchronized (resourceB) { log.info(Thread.currentThread() + " get ResourceB"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } log.info(Thread.currentThread() + "waiting get resourceA"); synchronized (resourceA) { log.info(Thread.currentThread() + " get resourceA"); }}}); threadA.start(); threadB.start(); return ApiResult.success("success"); }Copy the code

Sc: View information about classes loaded by the JVM

Sc has subclass matching enabled by default, so you can use it to see which classes implement this interface.

Sc-d: displays detailed information

Sc-f: displays all member variables. Use this command together with -d

sc com.shinemo.wangge.core.handler.UrlRedirectHandler
Copy the code

Sm: View method information of the loaded class

Sm-d: Displays detailed information

sm com.shinemo.wangge.web.controller.todo.TodoController *
sm com.shinemo.wangge.web.controller.todo.TodoController getTypeList
Copy the code

Data observations performed by the Watch method

When we encounter an online data bug, we usually deal with it by simulating the online data in the development environment, looking for clues from the production log, or remotely debugging it. Above no matter which kind of screening means, relatively is more trouble. Arthas’s Watch helps us see the code execution in real time. Use an observation expression to view the parameters, return values, and exception information of a function. Observation expressions consist mainly of OGNL expressions, so you can write OGNL expressions to execute them.

Grammar:

Watch the package name. Class name Method name Examples of information to view: watch com.shinemo.wangge.web.controller.todo.TodoController getTodoList '{params,returnObj,throwExp}' -n 5 -x 5 '1==1' -x indicates the traversal depth, which can be adjusted to print specific parameters and results. The default value is 1. -n Indicates the execution timesCopy the code

View the return value of the function

watch com.shinemo.wangge.web.controller.common.IndexController getIndex returnObj
Copy the code

View the request parameters of the function

watch com.shinemo.wangge.web.controller.common.IndexController getIndex params
Copy the code

Saving Logs asynchronously

Arthas provides asynchronous tasks in the background to help us log. The usage is similar to Linux.

watch com.shinemo.wangge.web.controller.todo.TodoController getTodoList '{params,returnObj,throwExp}' -n 5 -x 5 '1==1' >  /data/logs/test.log &Copy the code

Trace: Outputs the method invocation path and time

We often encounter that the RT is too long when calling an API, so we need to find one or several functions in the call chain for optimization. We usually locate several possible anchors and print the RT between each anchor. Or you can find out the time difference from the log. Either way, it is tedious. This was easily accomplished when using arthas’s trace command.

This instruction is very useful for optimizing code to see how long each method takes to execute, or if it’s a repeat like a for loop, the maximum, minimum, and average time in n cycles.

 trace com.shinemo.wangge.web.controller.common.IndexController getIndex -n 5 '1==1'
Copy the code

The results are as follows:

[arthas@13090]$ trace com.shinemo.wangge.web.controller.common.IndexController getIndex -n 5 '1==1' Press Q or Ctrl+C to  abort. Affect(class count: 1 , method count: 1) cost in 233 ms, listenerId: 3 `---ts=2020-07-08 14:13:09; thread_name=http-nio-20014-exec-4; id=64; is_daemon=true; priority=5; TCCL = org. Springframework. Boot. Web. Embedded. Tomcat. TomcatEmbeddedWebappClassLoader @ 11 e1bd43 ` - [652.290636] ms Com.shinemo.wangge.web.controller.com mon. IndexController: getIndex () + - [0.030585] ms Com. Shinemo. Smartgrid. Domain. SmartGridContext: getLongUid () # 80 + - [0.012105] ms Com. Shinemo. Smartgrid. Domain. SmartGridContext: getMobile () # 81 + - [88.923084] ms Com. Shinemo. Wangge. Core. Service. Stallup. StallUpService: getSimpleInfo () # 82 + - [0.012727] ms Com.shinemo.com mon. Tools. Result. ApiResult: isSuccess () # 83 + - [0.009893] ms com.shinemo.common.tools.result.ApiResult:getData() #87Copy the code

Tt: Officially called time Tunnel

Watch can check the function invocation, which is more suitable for viewing information after the possible situation of the current invocation is known. If a function is called n times, there are several times for executing exceptions, and we need to find out the calls of these exceptions, it is not very convenient to check in Watch. You can use the tt command to view abnormal calls and information

After you enable tt for a method, it records every call (you need to set the maximum number of times to monitor), and then you can view the call at any time, including the outgoing parameter, the incoming parameter, the running time, whether the exception, etc

tt -t com.shinemo.wangge.web.controller.todo.TodoController getTodoList -n 5
Copy the code

Returns:

View Method View the call information

tt -w '{method.name,params,returnObj,throwExp}' -x 3 -i 1000
Copy the code

Trigger again

tt -p -i 1000
Copy the code

Trigger again 5 times, 2 seconds apart

tt -p --replay-times 5 --replay-interval 2000 -i 1000
Copy the code

Gets all call records

tt -l
Copy the code

Delete all call records

tt --delete-all
Copy the code

Stack: View the invocation path of the method

Use the stack command to view the method call information.

Monitor: indicates the statistics method time

Use the monitor command to monitor the execution of statistical methods, such as the total number of requests, the number of successes, the number of failures, the average response time, and the percentage of failures within a specified period.

-c: indicates the statistical period. The default value is 60 seconds

 monitor com.shinemo.wangge.web.controller.todo.TodoController getTodoList  -c 10
Copy the code

Re-define: Hot update

Common steps

  1. Decompile using JAD and then modify the source code using VIm
  2. Use the MC command to compile the modified code into a class file
  3. Load the new bytecode file with the re-define command
jad --source-only com.example.demo.arthas.user.UserController > /tmp/UserController.java
 
mc /tmp/UserController.java -d /tmp
 
redefine /tmp/com/example/demo/arthas/user/UserController.class
Copy the code

Matters needing attention

  1. Re-define class cannot modify, add, or delete the field and method of the class, including the method parameters, method name, and return value.
Re-define error! java.lang.UnsupportedOperationException: class redefinition failed: Attempted to change the schema (add/remove fields) new method will throw exceptions: redefine the error! java.lang.UnsupportedOperationException: class redefinition failed: Attempted to add a method to modify or delete method will throw exceptions: redefine the error! java.lang.UnsupportedOperationException: class redefinition failed: attempted to delete a methodCopy the code
  1. Running functions do not take effect without exit, such as the one added belowSystem.out.println, onlyrun()Theta in the delta function will work
public class MathGame {
    public static void main(String[] args) throws InterruptedException {
        MathGame game = new MathGame();
        while (true) {
            game.run();
            TimeUnit.SECONDS.sleep(1);
            // This doesn't work because the code keeps running in the while
            System.out.println("in loop"); }}public void run(a) throws InterruptedException {
        // This works because the run() function finishes completely each time
        System.out.println("call run()");
        try {
            int number = random.nextInt();
            List<Integer> primeFactors = primeFactors(number);
            print(number, primeFactors);
 
        } catch (Exception e) {
            System.out.println(String.format("illegalArgumentCount:%3d, ", illegalArgumentCount) + e.getMessage()); }}Copy the code

Asynchronously save requests to a file

1. Perform tasks in the background using &

watch com.shinemo.wangge.web.controller.common.IndexController getIndex '{params,returnObj,throwExp}' -n 5 -x 3 '1==1' &  
Copy the code

In this case, the command is executed in the background, and you can continue to execute other commands on the console.

Use Jobs to view all background tasks. Use kill to kill tasksCopy the code

2. Use >> to redirect the task output

You can print the output of the task to the specified file by > or >>, which can be used with & to implement background asynchronous tasks of the arthas command. Such as:

Watch of a specified file # com.shinemo.wangge.web.controller.com mon. IndexController getIndex '{params, returnObj, throwExp}' - n 5-3 x '1 = = 1 > >. Test out & # don't watch com.shinemo.wangge.web.controller.com mon. The specified file IndexController getIndex '{params, returnObj, throwExp}' - n - 3 x 5 '1 = = 1 > > & default will save to ~ / logs/arthas - cache / ${PID} / ${JobId}Copy the code

3. Save the command execution result in logs

By default, this function is disabled. To enable this function, run the following command:

options save-result true
Copy the code

The command execution results are asynchronously saved in {user.home}/logs/arthas-cache/result.log.

4. Exit arthas to continue performing background tasks

If you don’t want to stop arthas and continue with background tasks, you can quit the arthas console (stop will stop the arthas service)

Arthas supports the Web Console

After successfully starting the connection into the city, it has been automatically started and can be directly accessed: the operation mode on the http://localhost:8563/ page is exactly the same as the console.

Arthas supports pipeline commands

Arthas supports the use of pipes for further processing, the results of the above command such as sm org.. Apache log4j. Logger | grep

  • Grep — Searches for results that meet the criteria
  • Plaintext — Removes color from the result of a command
  • Wc — Count the output by row

Idea has arthas plug-in, which is very easy to use.