In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
In this issue, the editor will bring you about how to use the tracking tool BTrace when Java is running. The article is rich in content and analyzes and describes it from a professional point of view. I hope you can get something after reading this article.
1. What is BTrace?
Btrace, an open source project developed by sundararajan in June 2009, is a tool for dynamically tracking and analyzing a running Java application. BTrace is a secure and dynamic tracking tool developed for the Java platform. BTrace dynamically injects tracking code (bytecode tracking) into the bytecode of the target application, which is expressed in the BTrace language, that is, the Java script.
2. BTrace constraint
In order to ensure that the tracking actions are "read-only" (that is, these actions cannot modify the state of the tracked program) and are limited (such as ending in a fixed time). A BTrace program is only allowed to perform specified actions. Here are some things BTrace can't do:
Cannot create new object
Cannot create a new array
Cannot throw exception
Cannot catch exception
No instance or static functions can be performed-only static functions in the com.sun.btrace.BTraceUtils class or functions declared by the BTrace program itself can be called by BTrace
You cannot assign values to the class of the target program, or to the static or instance-level field of the object. However, BTrace's own classes can assign values to its static field
There can be no outer,inner, nested or local classes.
Cannot have synchronized code blocks or synchronized functions
Cannot have loop statements (for,while, do..while)
Cannot inherit other classes (parent class can only be java.lang.Object)
Unable to implement interface
Cannot contain assert statements
Class literals cannot be used
The above restrictions can be changed through a configuration: unsafe=true, when using the BTrace annotation, change the default value (false) of the property to true, that is, @ BTrace (unsafe=true); you can also explicitly declare-Dcom.sun.btrace.unsafe=true (the response also has a-u parameter) in the startup option; now you can do whatever you want. BUT, before doing this, it's best to consider the risk and double-check the script, please consider using it!
3. BTrace installation
Btrace git download address, download the release version and decompress it directly to use it.
3.1 basic syntax btrace script
The btrace command line tool runs the command as follows:
Common options for btrace: [- I] [- p] [- cp]
Parameter description:
Where possible options include:-- version Show the version-v Run in verbose mode-o The path to store the probe output (will disable showing the output in console)-u Run in trusted mode-d Dump the instrumented classes to the specified path-pd The search path for the probe XML descriptors-classpath Specify where to find user class Files and annotation processors-cp Specify where to find user class files and annotation processors-I Specify where to find include files-p Specify port to which the btrace agent listens for clients-statsd Specify the statsd server If any
Include-path: directories used to find header files. BTrace includes a simple preprocessing that supports # define,# + include and conditional compilation. It's not like a complete C / C++ preprocessor-it's a useful subset. For details, see the demo code "ThreadBean.java", if there is no explicit declaration option-Imam Btrace skips the preprocessor call step.
Port: the port on which the BTrace agent listens, which is optional. The default is 2020
Classpath: directories used to find jar files. The default is the current directory.
Pid: to track the target program id
Btrace-script: it's the tracking program itself. If this is a java file, it will be compiled before it is submitted. Otherwise, it is considered to have been precompiled (that is, it must be a class) and submitted
Arguments: this is the parameter passed to the BTrace program. BTrace programs can refer to these parameters through built-in symbols, and length is the number of these parameters.
There are many examples in the samples directory, and some traces are useful and can be used directly.
4. BTrace's Note 4.1 method Notes
Com.sun.btrace.annotations.OnMethod this annotation can be used to specify the target class, the target method, and the "location" in the target method. The annotated action method is executed when the corresponding method runs to the specified "location". In this note, the target class is specified with the "clazz" attribute, and the target method is specified with the "method" attribute. "clazz" can be the full path of the class (such as java.awt.Component or the regular expression in the middle of two backslashes, refer to the examples NewComponent.java and Classload.java to see their usage, regular expressions can match 0 or more target classes, when multiple classes are changed by dynamic instructions. For example, / java.awt.+/ matches all classes under the java.awt package). Method names can also use such regular expressions to match zero or more methods. Refer to the example MultiClass.java to see the usage. There is also a way to specify tracking classes and functions. The classes and functions to be tracked can be specified with annotations. For example, if the "clazz" attribute is @ javax.jws.Webservice. Then BTrace will change dynamic instructions for all functions that are annotated with this. Similarly, method-level annotations can be used to execute methods. See the example WebServiceTracker.java to learn how to use it. You can use regular expressions and annotations together, for example, @ / com.acme..+/ can match any class, as long as the annotations of that class match that regular expression. You can match multiple class names by specifying a parent class, such as + java.lang.Runnable, to match all classes that implement the java.lang.Runnable interface. Refer to the example SubtypeTracer.java to see its usage.
@ com.sun.btrace.annotations.OnTimer this annotation can be used to perform trace operations that require periodicity (millisecond intervals). Refer to Histogram.java for its usage.
Com.sun.btrace.annotations.OnError this annotation can be used to specify the action to be performed when any exception is thrown. The BTrace function modified by this annotation is executed when an exception is thrown by other operating methods of the same BTrace class.
Com.sun.btrace.annotations.OnExit this annotation is used to perform the actions that need to be performed after the party BTrace code calls exit (int) to end the trace session. Refer to the example ProbeExit.java to learn how to use it.
@ com.sun.btrace.annotations.OnEvent this annotation is used to trace the function associated with "external" events. When the BTrace client sends an "event", the action in the annotation is performed. Events sent by the client may be triggered by the user (such as pressing Ctrl-C). The name of the event is a string so that the trace operation is performed only after the corresponding event is triggered. To the target, the BTrace command line client sends an event after the user presses Ctrl-C. Refer to the example HistoOnEvent.java for usage.
@ com.sun.btrace.annotations.OnLowMemory this annotation can be used to track events when a specific memory threshold is used up. See the example MemAlerter.java for usage.
Com.sun.btrace.annotations.OnProbe this annotation can be used to avoid using inner classes of BTrace scripts. The @ OnProbe probe point is mapped to one or more @ OnMethod. Currently this mapping is specified by a XML probe description file class (this file will be used by the BTrace agent). Refer to the example SocketTracker1.java and the corresponding description file java.net.socket.xml. When running this example, the xml file needs to be placed in all the running directories of the target JVM (or modify the probeDescPath option in btracer.bat to point to any xml file).
Com.sun.btrace.annotations.Location: this annotation specifies a specific "location" in a traced/probed method
@ com.sun.btrace.annotations.Simpled: Mark @ OnMethod annotation processor sampling. When sampling the handler, not all events will be tracked, only a statistical sample with a given meaning. An adaptive sampling is used by default. BTrace will increase or decrease the number of calls between samples to maintain the average time window, thus reducing the overall overhead.
4.2 comments related to parameters
Com.sun.btrace.annotations.Self: this annotation identifies a parameter that retains the value of the this pointed to by the target function. Refer to the examples AWTEventTracer.java and AllCalls1.java.
Com.sun.btrace.annotations.Return: this annotation indicates that this parameter holds the return value of the target function. Refer to the example Classload.java
Com.sun.btrace.annotations.ProbeClassName: the modified parameter retains the class name of the probe class. See AllMethods.java (there are multiple probe classes)
Com.sun.btrace.annotations.ProbeMethodName: the modified argument retains the name of the probe function. Reference WebServiceTracker.java (multiple probe functions)
Com.sun.btrace.annotations.TargetInstance: the decorated parameter retains the instance being called. Refer to the example AllCall2.java.
Com.sun.btrace.annotations.TargetMethodOrField: the argument decorated by this annotation holds the name of the called function. Refer to AllCalls1.java and AllCall2.java
Com.sun.btrace.annotations.Duration: the receiver of the probe method parameter marked as the duration value, that is, the time in nanoseconds for the execution of the target method. Just use @ OnMethod with the Location attribute, and you need to use it with Kind.ERROR or Kind.RETURN
4.3 unannotated parameters
Unannotated BTrace probe function parameters are used for signature matching because they must appear in a fixed location. However, they can be exchanged with other annotation parameters. If a parameter is of type _ AnyType [] _, it will "eat" all remaining parameters. The specific meaning of unannotated parameters is related to their location:
The name acts as the Kind.ARRAY_GET array element loads the Kind.ARRAY_SET array element stores the Kind.CALL method calls the Kind.CATCH exception catch Kind.CHECKCASTcheckcastKind.ENTRY method to enter. It means to enter the matching probe point, which has nothing to do with the clazz and method set by you @ Location. Kind.ERROR error, exception is not caught, return Kind.FIELD_GETfield to get Kind.FIELD_SETfield settings Kind.INSTANCEOF instance detection Kind.LINE source code line number Kind.NEW create new instance Kind.NEWARRAY new array object is created Kind.RETURN means that a point matching A class method is called from a method that matches A class method Be sure to enter a synchronous method lock with clazKind.SYNC_ENTRY Kind.SYNC_EXIT leaves a synchronous method lock Kind.THROW throws comments related to the exception 4.4 field
The @ com.sun.btrace.annotations.Export BTrace field uses this annotation to indicate that it has been mapped to a jvmstat counter. Using this annotation, BTrace programs can expose trace counters to external jvmstat clients (such as jstat). Refer to the example ThreadCounter.java
@ com.sun.btrace.annotations.Property this annotation identifies a field as a MBean attribute. If a BTrace class has at least one static field that uses this annotation. Then a MBean will be created and registered with the platform MBean server. JMX clients such as VisualVM,jconsole can access this field to view the MBean of BTrace. After attaching BTrace to the target program, you can also attach VisualVM or jconsole to the same target program to view the MBean attribute you just created. With VisualVM or jconsole, you can view BTrace-related fields through the MBeans tab page, and then check their values. Refer to the examples ThreadCounterBean.java and HistogramBean.java for usage
The @ com.sun.btrace.annotations.TLS BTrace field uses this annotation to indicate that it is a thread-local field (thread local field). Note that you can only access such fields in the @ OnMethod annotated function. Each Java thread has a copy of this field. For this approach to work, the type of this field can only be immutable (such as the primitive type) or cloneable (which implements the Cloneable interface and overrides the clone () function). These thread-local fields can be used by BTrace programs to identify whether it has performed multiple probe operations in the same thread. Refer to the examples OnThrow.java and WebServiceTracker.java
4.5 related notes
Com.sun.btrace.annotations.DTrace this annotation is used to associate a small D script (embedded in the java class of BTrace) with the BTrace program. Refer to the example DTraceInline.java
@ com.sun.btrace.annotations.DTraceRef is the same as the previous note, except that the D script is in a separate file, not embedded in the java class.
@ com.sun.btrace.annotations.BTrace must use this annotation to specify that a Java class is a BTrace program. The BTrace compiler forces the annotation to be found, and the BTrace agent checks to see if it has it. If not, an error is prompted and will not be executed.
5. Use example 5.1 to prepare the sample code package com.gitee.funcy.jtools.btrace;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.URL;import java.net.URLConnection;/** * the program periodically performs network read operations * * @ author chengyan * @ date 2019-11-03 10:41 afternoon * / public class HoldNetTask implements Runnable {public void visitWeb (String strUrl) {URL url = null URLConnection urlconn = null; InputStream is = null; try {url = new URL (strUrl); urlconn = url.openConnection (); is = urlconn.getInputStream (); BufferedReader bufferedReader = new BufferedReader (new InputStreamReader (is)); StringBuffer bs = new StringBuffer (); String l = null While ((l = bufferedReader.readLine ())! = null) {bs.append (l) .append ("\ r\ n");}} catch (Exception e) {e.printStackTrace ();} finally {if (is! = null) {try {is.close () } catch (Exception e) {}} @ Override public void run () {while (true) {visitWeb ("http://www.sina.com.cn");}} public static void main (String [] args) {new Thread (new HoldNetTask ()) .start () Import related jar package 1. Import the jar package directly
The java package corresponding to BTrace is located in the build directory of the Btrace release file. There are three jar packages in total:
Btrace-agent.jarbtrace-boot.jarbtrace-client.jar2. Using maven to introduce jar packages
You can also use maven to introduce dependency packages and add the following to the pom file:
... Omit the other 1.3.11.3. Omit other com.sun.tools.btrace btrace-agent ${btrace.version} com.sun.tools.btrace btrace-boot ${btrace.version} com.sun.tools.btrace Btrace-client ${btrace.version} btrace-repo btrace-repo https://dl.bintray.com/btraceio/maven/ true false
It is important to note that the latest version of btrace may not be available in the maven central repository, and additional repositories need to be configured for this.
5.3 time spent monitoring functions
Using the BTrace script, you can specify the time it takes to monitor a particular method of a particular class through regular expressions, and the following code monitors the execution time of a function named visitWeb () in all classes.
Package com.gitee.funcy.jtools.btrace;import com.sun.btrace.annotations.BTrace;import com.sun.btrace.annotations.Kind;import com.sun.btrace.annotations.Location;import com.sun.btrace.annotations.OnMethod;import com.sun.btrace.annotations.ProbeClassName;import com.sun.btrace.annotations.ProbeMethodName;import com.sun.btrace.annotations.TLS;import static com.sun.btrace.BTraceUtils.* / * {add a description here} * @ author chengyan * @ date 2019-11-03 12:13 AM * / @ BTracepublic class PrintTimes {@ TLS private static long startTime = 0 / * * method call start * clazz = "/. + /": monitor any class * method= "/ visitWeb/": monitor visitWeb method * / @ OnMethod (clazz = "/. + /", method= "/ visitWeb/") public static void startMethod () {startTime = timeMillis () } @ OnMethod (clazz = "/. + /", method= "/ visitWeb/", location=@Location (Kind.RETURN)) public static void endMethod (@ ProbeClassName String pcm, @ ProbeMethodName String pmn) {println (pcm + "." + pmn + "[Time taken:" + str (timeMillis ()-startTime) + "ms]");}}
Running result:
$btrace 42188 PrintTimes.javacom.gitee.funcy.jtools.btrace.HoldNetTask.visitWeb [Time taken: 55ms] com.gitee.funcy.jtools.btrace.HoldNetTask.visitWeb [Time taken: 50ms] com.gitee.funcy.jtools.btrace.HoldNetTask.visitWeb [Time taken: 52ms] com.gitee.funcy.jtools.btrace.HoldNetTask.visitWeb [Time taken: 49ms] com.gitee.funcy.jtools.btrace.HoldNetTask.visitWeb [Time taken: 54ms] com.gitee.funcy.jtools.btrace.HoldNetTask.visitWeb [Time taken: 54ms] 5.4 Monitoring function parameters
In addition to the execution time, BTrace can also output the parameters of the function:
Package com.gitee.funcy.jtools.btrace;import com.sun.btrace.AnyType;import com.sun.btrace.BTraceUtils;import com.sun.btrace.annotations.BTrace;import com.sun.btrace.annotations.OnMethod;import com.sun.btrace.annotations.ProbeClassName;import com.sun.btrace.annotations.ProbeMethodName / * {add description here} * * @ author chengyan * @ date 2019-11-03 10:43 afternoon * / @ BTracepublic class PrintArgs {@ OnMethod (clazz = "/ .* HoldNetTask/", method = "/ visitWeb/") public static void anyWriteFile (@ ProbeClassName String pcn, @ ProbeMethodName String pmn, AnyType [] args) {BTraceUtils.print (pcn + "-" + pmn); BTraceUtils.printArray (args);}}
Running result:
$btrace 46877 PrintArgs.javacom.gitee.funcy.jtools.btrace.HoldNetTask-visitWeb [http://www.sina.com.cn,] com.gitee.funcy.jtools.btrace.HoldNetTask-visitWeb [http://www.sina.com.cn,] com.gitee.funcy.jtools.btrace.HoldNetTask-visitWeb [http://www.sina.com.cn,] com.gitee.funcy.jtools.btrace.HoldNetTask-visitWeb [http://www.sina.com.cn, ] com.gitee.funcy.jtools.btrace.HoldNetTask-visitWeb [http://www.sina.com.cn,] com.gitee.funcy.jtools.btrace.HoldNetTask-visitWeb [http://www.sina.com.cn,] 5.5 get information about doing arbitrary lines of code
Through the BTrace script @ Location annotation, you can specify that a behavior is triggered when the program runs to a line of code. The following example shows getting information about line 27 of the HoldNetTask class through the BTrace script (triggering the BTrace script when the target program runs to line 27).
Package com.gitee.funcy.jtools.btrace;import static com.sun.btrace.BTraceUtils.*;import com.sun.btrace.annotations.BTrace;import com.sun.btrace.annotations.Location;import com.sun.btrace.annotations.OnMethod;import com.sun.btrace.annotations.Kind;import com.sun.btrace.annotations.ProbeClassName;import com.sun.btrace.annotations.ProbeMethodName / * {add description here} * * @ author chengyan * @ date 2019-11-04 10:02 10:02 * / @ BTracepublic class AllLines {@ OnMethod (clazz = "/. * HoldNetTask/", location = @ Location (value = Kind.LINE, line = 27)) public static void online (@ ProbeClassName String pcn, @ ProbeMethodName String pmn, int line) {println (pcn + "." + pmn + ":" + line);}}
Running result:
$btrace 46877 AllLines.javacom.gitee.funcy.jtools.btrace.HoldNetTask.visitWeb:27com.gitee.funcy.jtools.btrace.HoldNetTask.visitWeb:27com.gitee.funcy.jtools.btrace.HoldNetTask.visitWeb:27com.gitee.funcy.jtools.btrace.HoldNetTask.visitWeb:27com.gitee.funcy.jtools.btrace.HoldNetTask.visitWeb:27com.gitee.funcy.jtools.btrace.HoldNetTask.visitWeb:27
As you can see from the script output, BTrace correctly recognizes line 27 of the HoldNetTask class, which is in the running interval of the visitWeb () function. If you set the value of line in @ Location to-1, the BTrace script will trigger on each line.
5.6 timing trigger
BTrace scripts support timing triggering. You can periodically perform a behavior to obtain system information. The following example uses the @ OnTimer flag to set up two periodic tasks that run once per second and once every 3 seconds.
Package com.gitee.funcy.jtools.btrace;import com.sun.btrace.BTraceUtils;import com.sun.btrace.annotations.BTrace;import com.sun.btrace.annotations.OnTimer;import static com.sun.btrace.BTraceUtils.jstackAll;import static com.sun.btrace.BTraceUtils.println / * {add a description here} * * @ author chengyan * @ date 2019-11-04 10:11 afternoon * / @ BTracepublic class Timers {@ OnTimer (1000) public static void getUpTime () {println (BTraceUtils.Strings.strcat ("1000 msec:", BTraceUtils.Strings.str (BTraceUtils.Sys.VM.vmUptime ();} @ OnTimer (3000) public static void getStack () {jstackAll ();}}
Running result:
$btrace 46969 Timers.java1000 msec:276541000 msec:28647Thread [Attach Listener,9,system] Thread [Signal Dispatcher,9,system] Thread [Thread-1 Reader 9 System] java.net.PlainSocketImpl.socketAccept (Native Method) java.net.AbstractPlainSocketImpl.accept (AbstractPlainSocketImpl.java:409) java.net.ServerSocket.implAccept (ServerSocket.java:545) java.net.ServerSocket.accept (ServerSocket.java:513) com.sun.btrace.agent.Main.startServer (Main.java:668) com.sun.btrace.agent.Main.access$000 (Main.java:63) com .sun.btrace.agent.Main $2.run (Main.java:128) java.lang.Thread.run (Thread.java:748)
In the getUpTime () method, you specify a task to run every second and print the startup time of the virtual machine. In the getStack () method, you specify a task that runs every 3 seconds, and each time a thread snapshot of the system is exported.
5.7 get the properties of the class
During the running of the program, BTrace can get the field information of the object instance at the specified location. For example, in this example, you can look at the address of the actual opened URL when you call URL.openConnection ().
Package com.gitee.funcy.jtools.btrace;import com.sun.btrace.annotations.BTrace;import com.sun.btrace.annotations.Location;import com.sun.btrace.annotations.OnMethod;import com.sun.btrace.annotations.Kind;import com.sun.btrace.annotations.ProbeClassName;import com.sun.btrace.annotations.ProbeMethodName;import com.sun.btrace.annotations.Self;import static com.sun.btrace.BTraceUtils.* / * {add description here} * * @ author chengyan * @ date 2019-11-04 10:20 10:20 * / @ BTracepublic class PrintField {@ OnMethod (clazz = "/. * URL/", method = "/. * openConnection/", location = @ Location (value = Kind.ENTRY)) public static void visitWebEntry (@ Self Object self, @ ProbeClassName String pcn, @ ProbeMethodName String pmn) {println (pcn + "." + pmn); println (self) / / only static variable println (get (field (classOf (self), "protocolPathProp")); / / instance variable println (get (classOf (self), "host"), self)); println ("=");}}
Running result:
$btrace 46969 PrintField.javajava.net.URL.openConnection http://www.sina.com.cnjava.protocol.handler.pkgswww.sina.com.cn===============
Here, the URL object is monitored, and when the openConnection () method is called, the current object instance self is obtained, and then the host and other properties of the corresponding instance are obtained.
6. Matters needing attention
The method parameters in the script need to be consistent with the original method parameter types.
Classes other than btrace are not allowed in the script, BTraceUtils.strcat () is used to concatenate strings, BTraceUtils.println () is used to print, and BTraceUtils.Threads is used to get threads.
The code implanted by BTrace will remain until the application is restarted. So even if Btrace exits, the business function executes the code implanted by Btrace every time it executes.
This is how the Java runtime uses the tracking tool BTrace, which is shared by the editor. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.