Java program troubleshooting tool Btrace



(1) Introduction of Btrace

BTrace is a safe and reliable dynamic tracing tool for Java. Its working principle is to dynamically enhance the class class in the running java program through instrument + asm. Return values, global variables and stack information, etc., and achieve the least intrusion and occupy the least system resources.


As some of the features described above, btrace is generally a powerful tool for troubleshooting jvm problems in the production environment. Using it, you don't need to worry about the application's log is not complete or detailed enough, and you don't need to restart the program again and again to troubleshoot problems. .







(2) Some limitations of Btrace

Since Btrace directly invades the script logic into the running code, it imposes many restrictions on its use:

1. Cannot create objects

2. Cannot use arrays

3. Cannot throw or catch exceptions

4. Cannot Use loop

5, cannot use synchronized keyword

6, properties and methods must be modified with static

In addition , improper use of BTrace may cause the production program to hang directly, so be sure to fully verify the correctness of the script in the development environment before going to the production environment.


(3) What can Btrace do

(1) Analyze the time-consuming situation of any interface or method

(2) Analyze the expansion of Map when adding data continuously

(3) Analyze which method calls the System.gc() method, and print Get out of the call stack

(4) When some methods throw exceptions, analyze their operating parameters

(5) Count the number of calls to some interfaces

(6) Analyze whether the code of some methods has been executed to a certain line

(7).


Note that all the above operations are monitoring the running program and will not have any impact.


(4) Installation of Btrace


(1) Download the latest binary package from github, the version is 1.3.10.2

wget https://github.com/btraceio/btrace/releases/download/v1.3.10.2/btrace-bin- 1.3.10.2.tgz

(2) Unzip to the specified path


(3) Set environment variables
````
BTRACE_HOME=/root/btrace
export BTRACE_HOME
export PATH=$PATH:$BTRACE_HOME/bin
````


(4) Verify that the installation is successful

````
[root@es1 ~]# btrace --version
BTrace v.1.3.10 (20171121)
````


(5) View the help documentation of btrace
````
[root@es1 build]# btrace
Usage: btrace <options> <pid> <btrace source or .class file> <btrace arguments>
where possible options include:
  --version             Show the version
  -v                    Run in verbose mode
  -o <file>             The path to store the probe output (will disable showing the output in console)
-u                    Run in trusted mode
  -d <path>             Dump the instrumented classes to the specified path
  -pd <path>            The search path for the probe XML descriptors
  -classpath <path>     Specify where to find user class files and annotation processors
  -cp <path>            Specify where to find user class files and annotation processors
  -I <path>             Specify where to find include files
  -p <port>             Specify port to which the btrace agent listens for clients
  -statsd <host[:port]> Specify the statsd server, if any
````


(5) An example of the use of btrace


Note that the jars released by btrace on maven are very low, and they are all versions a few years ago. If you want to write btrace scripts, it is recommended to copy the three core jars in the installation directory directly to the project. It can be used temporarily. If you want to use it at any time, you can also upload it to your company's maven private server.
````
[root@es1 btrace]# ll build/
Total usage 1572
-rw-r--r--. 1 root root 460271 12月 16 00:44 btrace-agent.jar
-rw-r--r--. 1 root root 358679 12月 16 00:44 btrace-boot.jar
-rw-r--r--. 1 root root 785219 12月 16 00:44 btrace-client.jar
````


(1) Before using btrace, we first need to write a simple java program to simulate a program running online. The

code is relatively simple, that is, randomly generate two integers at random times and sum them up:
````
package com.test;
import java.util.Random;

public class BtraceTest  {

    public static Random random=new Random();

    public int add (int a, int b)   {
        int sum=a+b;
        System.out.println("和:"+sum);
        return a+b;
    }

    public void run(){
        try {
            while (true) {
                add(random.nextInt(10), random.nextInt(10));
                Thread.sleep(random.nextInt(10) * 100);
            }

        }catch (Exception e){
            e.printStackTrace ();
        }
    }


    public static void main(String[] args)     {
        new BtraceTest().run();

    }

}


````


(2) The main program is already available. Next, we need to write a btrace script to monitor "our online program."
Note that the three jars mentioned above need to be introduced into the project.

The monitoring code is as follows:
````
package samples;
import com.sun.btrace.BTraceUtils;
import com.sun.btrace.annotations.*;
import com.sun.btrace.annotations.Export;
import static com.sun.btrace.BTraceUtils.*;

@BTrace
public class OnlineDebug {

    @OnExit//When the program exits, execute some commands
    public static void onexit(int code) {
        println("BTrace program exits! with code: " + code);
    }

    @Export //Can be used to count the number of calls
    public static long counter;

    @OnMethod(clazz="com.test.BtraceTest", method="add",
            location=@Location(value=Kind.RETURN))
    public static void m(@Self Object self, int a,int b,@Return int result,@Duration long time) {
        BTraceUtils.println("参数: a: "+a+"  b: "+b);
        BTraceUtils.println("Time spent: "+time*1.0/1000+"ms");
        jstack();//Print stack information
        counter++;
    }

    @OnEvent("1")//Triggered by an event, print the current number of program calls
    public static void setL1() {
        BTraceUtils.println("executor count:  "+counter);
    }

    //Whether the monitoring program goes to the 22nd line of code
    @OnMethod(clazz = "com.test.BtraceTest", location = @Location(value = Kind.LINE, line = 22))
    public static void onBind() {
        println("execute to line 22");
    }

    // print the number of calls every specified time
     @OnTimer(5000)
    public static void run(){
        BTraceUtils.println("executor count:  "+counter);
    }

// //Carefully use some classes or methods under java.lang whether it is called in the monitoring program
//    @OnMethod(clazz="/java\\.lang\\..*/", method="/.*/")
//    public static void swingMethods( @ProbeClassName String probeClass, @ProbeMethodName String probeMethod) {
//        print("entered " + probeClass + "."  + probeMethod);
//    }
}

````



(6) Simulation test

After step 5, we have prepared the simulation program and monitoring script. Let's deploy and test:

(1) First, package the simulation program into a jar through maven

(2) Select a linux machine to jar the jar Package upload

(3) Execute the command to start the simulation program
````
java -cp  xxx.jar com.test.BtraceTest
````

The output of the linux terminal is as follows:
````
and: 8
and: 11
and: 3
and: 12
and: 14
and: 15
and: 8
and: 2
and: 8
and: 7
and: 18
and: 4
````


(4) Open another linux terminal to deploy the monitoring script OnlineDebug.java to the specified directory and

grant execution permission:
````
chmod +x OnlineDebug.java
````
Execute the jps command to view the process id of the simulated program and

start the monitoring script:
````
btrace 2139 OnlineDebug.java
````


After waiting a few seconds, the console output is as follows:

````
Parameters: a: 0 b: 8
Time spent: 101.973ms
com.test.BtraceTest.add(BtraceTest.java:11)
com.test.BtraceTest.run(BtraceTest.java:17)
com.test.BtraceTest.main(BtraceTest.java:28)
Parameters: a: 3 b: 4
Time spent: 116.611ms
com.test.BtraceTest.add(BtraceTest.java:11)
com.test.BtraceTest.run(BtraceTest.java:17)
com.test.BtraceTest.main(BtraceTest.java:28)
Parameters: a: 0 b: 2
Time spent: 113.168ms
com.test.BtraceTest.add(BtraceTest.java:11)
com.test.BtraceTest.run(BtraceTest.java:17)
com.test.BtraceTest.main(BtraceTest.java:28)
Parameters: a: 7 b: 7
Time spent: 113.434ms
com.test.BtraceTest.add(BtraceTest.java:11)
com.test.BtraceTest.run(BtraceTest.java:17)
com.test.BtraceTest.main(BtraceTest.java:28)
Parameters: a: 6 b: 1
Time spent: 181.184ms
com.test.BtraceTest.add(BtraceTest.java:11)
com.test.BtraceTest.run(BtraceTest.java:17)
com.test.BtraceTest.main(BtraceTest.java:28)
Parameters: a: 7 b: 6
Time spent: 190.881ms
com.test.BtraceTest.add(BtraceTest.java:11)
com.test.BtraceTest.run(BtraceTest.java:17)
com.test.BtraceTest.main(BtraceTest.java:28)
executor count:  44
````


It can be seen that the monitoring script has taken effect, and the internal parameters and execution time of the simulation program have been successfully obtained. At the moment another terminal emulation program is still running
normally , but the internals have actually been enhanced.

How do I exit the monitoring script?

Very simple, execute the ctrl+c command and select 1 to exit:
````
Parameters: a: 9 b: 9
Time spent: 246.743ms
com.test.BtraceTest.add(BtraceTest.java:11)
com.test.BtraceTest.run(BtraceTest.java:17)
com.test.BtraceTest.main(BtraceTest.java:28)
Parameters: a: 3 b: 1
Time spent: 251.039ms
^CPlease enter your option:
        1. exit
        2. send an event
        3. send a named event
        4. flush console output
1
````






Summary:

Through the above examples, I believe that everyone can feel the power of btrace. It is very convenient to use it to troubleshoot the problems of running programs. Interested friends can try it out for themselves.


Reference link:

https://github.com/btraceio/btrace/wiki/BTrace-Annotations

https://yq.aliyun.com/articles/7569

https://www.jianshu.com/p/93e94b724476

What is the problem? Scan the code to follow the WeChat public account: I am the siege division (woshigcs), leave a message in the background for consultation. Technical debts cannot be owed, and health debts cannot be owed. On the road of seeking the Tao, walk with you.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326397745&siteId=291194637