Merge branch 'master' of github.com:alibaba/arthas

This commit is contained in:
hengyunabc
2020-08-07 18:23:51 +08:00
79 changed files with 4258 additions and 97 deletions
@@ -29,7 +29,8 @@ public class SessionManagerImpl implements SessionManager {
private final InternalCommandManager commandManager;
private final Instrumentation instrumentation;
private final JobController jobController;
private final long timeoutMillis;
private final long sessionTimeoutMillis;
private final int consumerTimeoutMillis;
private final long reaperInterval;
private final Map<String, Session> sessions;
private final long pid;
@@ -42,7 +43,8 @@ public class SessionManagerImpl implements SessionManager {
this.commandManager = commandManager;
this.jobController = jobController;
this.sessions = new ConcurrentHashMap<String, Session>();
this.timeoutMillis = options.getSessionTimeout();
this.sessionTimeoutMillis = options.getSessionTimeout();
this.consumerTimeoutMillis = 5 * 60 * 1000; // 5 minutes
this.reaperInterval = options.getReaperInterval();
this.instrumentation = options.getInstrumentation();
this.pid = options.getPid();
@@ -62,9 +64,6 @@ public class SessionManagerImpl implements SessionManager {
String sessionId = UUID.randomUUID().toString();
session.put(Session.ID, sessionId);
//Result Distributor
session.setResultDistributor(new SharingResultDistributorImpl(session));
sessions.put(sessionId, session);
return session;
}
@@ -135,7 +134,7 @@ public class SessionManagerImpl implements SessionManager {
// do not close if there is still job running,
// e.g. trace command might wait for a long time before condition is met
//TODO check background job size
if (now - session.getLastAccessTime() > timeoutMillis && session.getForegroundJob() == null) {
if (now - session.getLastAccessTime() > sessionTimeoutMillis && session.getForegroundJob() == null) {
toClose.add(session);
}
evictConsumers(session);
@@ -146,7 +145,7 @@ public class SessionManagerImpl implements SessionManager {
if (job != null) {
job.interrupt();
}
long timeOutInMinutes = timeoutMillis / 1000 / 60;
long timeOutInMinutes = sessionTimeoutMillis / 1000 / 60;
String reason = "session is inactive for " + timeOutInMinutes + " min(s).";
session.getResultDistributor().appendResult(new MessageModel(reason));
this.removeSession(session.getSessionId());
@@ -166,7 +165,7 @@ public class SessionManagerImpl implements SessionManager {
long now = System.currentTimeMillis();
for (ResultConsumer consumer : consumers) {
long inactiveTime = now - consumer.getLastAccessTime();
if (inactiveTime > 30000) {
if (inactiveTime > consumerTimeoutMillis) {
//inactive duration must be large than pollTimeLimit
logger.info("Removing inactive consumer from session, sessionId: {}, consumerId: {}, inactive duration: {}",
session.getSessionId(), consumer.getConsumerId(), inactiveTime);
@@ -13,8 +13,7 @@ public class ApiRequest {
private String requestId;
private String sessionId;
private String consumerId;
private Integer timeout;
private Map<String, Object> options;
private Integer execTimeout;
@Override
public String toString() {
@@ -24,8 +23,7 @@ public class ApiRequest {
", requestId='" + requestId + '\'' +
", sessionId='" + sessionId + '\'' +
", consumerId='" + consumerId + '\'' +
", timeout=" + timeout +
", options=" + options +
", execTimeout=" + execTimeout +
'}';
}
@@ -45,14 +43,6 @@ public class ApiRequest {
this.command = command;
}
public Map<String, Object> getOptions() {
return options;
}
public void setOptions(Map<String, Object> options) {
this.options = options;
}
public String getRequestId() {
return requestId;
}
@@ -77,11 +67,11 @@ public class ApiRequest {
this.consumerId = consumerId;
}
public Integer getTimeout() {
return timeout;
public Integer getExecTimeout() {
return execTimeout;
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
public void setExecTimeout(Integer execTimeout) {
this.execTimeout = execTimeout;
}
}
@@ -8,8 +8,10 @@ import com.taobao.arthas.core.command.model.*;
import com.taobao.arthas.core.distribution.PackingResultDistributor;
import com.taobao.arthas.core.distribution.ResultConsumer;
import com.taobao.arthas.core.distribution.ResultDistributor;
import com.taobao.arthas.core.distribution.SharingResultDistributor;
import com.taobao.arthas.core.distribution.impl.PackingResultDistributorImpl;
import com.taobao.arthas.core.distribution.impl.ResultConsumerImpl;
import com.taobao.arthas.core.distribution.impl.SharingResultDistributorImpl;
import com.taobao.arthas.core.shell.cli.CliToken;
import com.taobao.arthas.core.shell.cli.CliTokens;
import com.taobao.arthas.core.shell.cli.Completion;
@@ -53,7 +55,6 @@ public class HttpApiHandler {
private static final Logger logger = LoggerFactory.getLogger(HttpApiHandler.class);
public static final int DEFAULT_EXEC_TIMEOUT = 30000;
private final SessionManager sessionManager;
private final AtomicInteger requestIdGenerator = new AtomicInteger(0);
private static HttpApiHandler instance;
private final InternalCommandManager commandManager;
private final JobController jobController;
@@ -84,13 +85,13 @@ public class HttpApiHandler {
ApiResponse result;
String requestBody = null;
String requestId = "req_" + requestIdGenerator.addAndGet(1);
String requestId = null;
try {
HttpMethod method = request.method();
if (HttpMethod.POST.equals(method)) {
requestBody = getBody(request);
ApiRequest apiRequest = parseRequest(requestBody);
apiRequest.setRequestId(requestId);
requestId = apiRequest.getRequestId();
result = processRequest(apiRequest);
} else {
result = createResponse(ApiState.REFUSED, "Unsupported http method: " + method.name());
@@ -210,15 +211,20 @@ public class HttpApiHandler {
}
//required session
Session session = null;
boolean allowNullSession = ApiAction.EXEC.equals(action);
String sessionId = apiRequest.getSessionId();
if (StringUtils.isBlank(sessionId)) {
throw new ApiException("'sessionId' is required");
if (!allowNullSession) {
throw new ApiException("'sessionId' is required");
}
} else {
session = sessionManager.getSession(sessionId);
if (session == null) {
throw new ApiException("session not found: " + sessionId);
}
sessionManager.updateAccessTime(session);
}
Session session = sessionManager.getSession(sessionId);
if (session == null) {
throw new ApiException("session not found: " + sessionId);
}
sessionManager.updateAccessTime(session);
//dispatch requests
ApiResponse response = dispatchRequest(action, apiRequest, session);
@@ -266,11 +272,14 @@ public class HttpApiHandler {
Session session = sessionManager.createSession();
if (session != null) {
//Result Distributor
SharingResultDistributorImpl resultDistributor = new SharingResultDistributorImpl(session);
//create consumer
ResultConsumer resultConsumer = new ResultConsumerImpl();
session.getResultDistributor().addConsumer(resultConsumer);
resultDistributor.addConsumer(resultConsumer);
session.setResultDistributor(resultDistributor);
session.getResultDistributor().appendResult(new MessageModel("Welcome to arthas!"));
resultDistributor.appendResult(new MessageModel("Welcome to arthas!"));
//welcome message
WelcomeModel welcomeModel = new WelcomeModel();
@@ -279,7 +288,7 @@ public class HttpApiHandler {
welcomeModel.setTutorials(ArthasBanner.tutorials());
welcomeModel.setPid(PidUtils.currentPid());
welcomeModel.setTime(DateUtils.getCurrentDate());
session.getResultDistributor().appendResult(welcomeModel);
resultDistributor.appendResult(welcomeModel);
//allow input
updateSessionInputStatus(session, InputStatus.ALLOW_INPUT);
@@ -300,7 +309,10 @@ public class HttpApiHandler {
* @param inputStatus
*/
private void updateSessionInputStatus(Session session, InputStatus inputStatus) {
session.getResultDistributor().appendResult(new InputStatusModel(inputStatus));
SharingResultDistributor resultDistributor = session.getResultDistributor();
if (resultDistributor != null) {
resultDistributor.appendResult(new InputStatusModel(inputStatus));
}
}
private ApiResponse processJoinSessionRequest(ApiRequest apiRequest, Session session) {
@@ -347,78 +359,90 @@ public class HttpApiHandler {
* @return
*/
private ApiResponse processExecRequest(ApiRequest apiRequest, Session session) {
String commandLine = apiRequest.getCommand();
Map<String, Object> body = new TreeMap<String, Object>();
body.put("command", commandLine);
ApiResponse response = new ApiResponse();
response.setSessionId(session.getSessionId())
.setBody(body);
if (!session.tryLock()) {
response.setState(ApiState.REFUSED)
.setMessage("Another command is executing.");
return response;
boolean oneTimeAccess = false;
if (session == null) {
oneTimeAccess = true;
session = sessionManager.createSession();
}
int lock = session.getLock();
PackingResultDistributor packingResultDistributor = null;
Job job = null;
try {
Job foregroundJob = session.getForegroundJob();
if (foregroundJob != null) {
String commandLine = apiRequest.getCommand();
Map<String, Object> body = new TreeMap<String, Object>();
body.put("command", commandLine);
ApiResponse response = new ApiResponse();
response.setSessionId(session.getSessionId())
.setBody(body);
if (!session.tryLock()) {
response.setState(ApiState.REFUSED)
.setMessage("Another job is running.");
logger.info("Another job is running, jobId: {}", foregroundJob.id());
.setMessage("Another command is executing.");
return response;
}
//distribute result message both to origin session channel and request channel by CompositeResultDistributor
packingResultDistributor = new PackingResultDistributorImpl(session);
//ResultDistributor resultDistributor = new CompositeResultDistributorImpl(packingResultDistributor, session.getResultDistributor());
job = this.createJob(commandLine, session, packingResultDistributor);
session.setForegroundJob(job);
updateSessionInputStatus(session, InputStatus.ALLOW_INTERRUPT);
int lock = session.getLock();
PackingResultDistributor packingResultDistributor = null;
Job job = null;
try {
Job foregroundJob = session.getForegroundJob();
if (foregroundJob != null) {
response.setState(ApiState.REFUSED)
.setMessage("Another job is running.");
logger.info("Another job is running, jobId: {}", foregroundJob.id());
return response;
}
job.run();
packingResultDistributor = new PackingResultDistributorImpl(session);
//distribute result message both to origin session channel and request channel by CompositeResultDistributor
//ResultDistributor resultDistributor = new CompositeResultDistributorImpl(packingResultDistributor, session.getResultDistributor());
job = this.createJob(commandLine, session, packingResultDistributor);
session.setForegroundJob(job);
updateSessionInputStatus(session, InputStatus.ALLOW_INTERRUPT);
} catch (Throwable e) {
logger.error("Exec command failed:" + e.getMessage() + ", command:" + commandLine, e);
response.setState(ApiState.FAILED).setMessage("Exec command failed:" + e.getMessage());
job.run();
} catch (Throwable e) {
logger.error("Exec command failed:" + e.getMessage() + ", command:" + commandLine, e);
response.setState(ApiState.FAILED).setMessage("Exec command failed:" + e.getMessage());
return response;
} finally {
if (session.getLock() == lock) {
session.unLock();
}
}
//wait for job completed or timeout
Integer timeout = apiRequest.getExecTimeout();
if (timeout == null || timeout <= 0) {
timeout = DEFAULT_EXEC_TIMEOUT;
}
boolean timeExpired = !waitForJob(job, timeout);
if (timeExpired) {
logger.warn("Job is exceeded time limit, force interrupt it, jobId: {}", job.id());
job.interrupt();
response.setState(ApiState.INTERRUPTED).setMessage("The job is exceeded time limit, force interrupt");
} else {
response.setState(ApiState.SUCCEEDED);
}
//packing results
body.put("jobId", job.id());
body.put("jobStatus", job.status());
body.put("timeExpired", timeExpired);
if (timeExpired) {
body.put("timeout", timeout);
}
body.put("results", packingResultDistributor.getResults());
response.setSessionId(session.getSessionId())
//.setConsumerId(consumerId)
.setBody(body);
return response;
} finally {
if (session.getLock() == lock) {
session.unLock();
if (oneTimeAccess) {
sessionManager.removeSession(session.getSessionId());
}
}
//wait for job completed or timeout
Integer timeout = apiRequest.getTimeout();
if (timeout == null || timeout <= 0) {
timeout = DEFAULT_EXEC_TIMEOUT;
}
boolean timeExpired = !waitForJob(job, timeout);
if (timeExpired) {
logger.warn("Job is exceeded time limit, force interrupt it, jobId: {}", job.id());
job.interrupt();
response.setState(ApiState.INTERRUPTED).setMessage("The job is exceeded time limit, force interrupt");
} else {
response.setState(ApiState.SUCCEEDED);
}
//packing results
body.put("jobId", job.id());
body.put("jobStatus", job.status());
body.put("timeExpired", timeExpired);
if (timeExpired) {
body.put("timeout", timeout);
}
body.put("results", packingResultDistributor.getResults());
response.setSessionId(session.getSessionId())
//.setConsumerId(consumerId)
.setBody(body);
return response;
}
/**
@@ -81,6 +81,21 @@
{{ tutorial.names[language] }}
</a>
<div class="dropdown-divider"></div>
<a v-for="tutorial in getTutorials('COMMAND-CLASS-LOADER-RELATED')" v-bind:class="{ 'dropdown-item-checked': tutorial.id === tutorialId }"
class="dropdown-item" v-bind:href='currentUrl() + "?language=" + language + "&id=" + tutorial.id'>
{{ tutorial.names[language] }}
</a>
<div class="dropdown-divider"></div>
<a v-for="tutorial in getTutorials('COMMAND-MONITOR-RELATED')" v-bind:class="{ 'dropdown-item-checked': tutorial.id === tutorialId }"
class="dropdown-item" v-bind:href='currentUrl() + "?language=" + language + "&id=" + tutorial.id'>
{{ tutorial.names[language] }}
</a>
<div class="dropdown-divider"></div>
<a v-for="tutorial in getTutorials('COMMAND-OPTIONS')" v-bind:class="{ 'dropdown-item-checked': tutorial.id === tutorialId }"
class="dropdown-item" v-bind:href='currentUrl() + "?language=" + language + "&id=" + tutorial.id'>
{{ tutorial.names[language] }}
</a>
<div class="dropdown-divider"></div>
<a v-for="tutorial in getTutorials('COMMAND-BASIC')" v-bind:class="{ 'dropdown-item-checked': tutorial.id === tutorialId }"
class="dropdown-item" v-bind:href='currentUrl() + "?language=" + language + "&id=" + tutorial.id'>
{{ tutorial.names[language] }}
@@ -334,6 +349,30 @@
cn: "command-pwd-cn",
}
},
{
id: "command-plaintext",
type: "COMMAND-BASIC",
names: {
en: "plaintext",
cn: "plaintext",
},
ids: {
en: "command-plaintext-en",
cn: "command-plaintext-cn",
}
},
{
id: "command-wc",
type: "COMMAND-BASIC",
names: {
en: "wc",
cn: "wc",
},
ids: {
en: "command-wc-en",
cn: "command-wc-cn",
}
},
{
id: "command-dashboard",
type: "COMMAND-JVM-RELATED",
@@ -417,6 +456,378 @@
en: "command-perfcounter-en",
cn: "command-perfcounter-cn",
}
},
{
id: "command-logger",
type: "COMMAND-JVM-RELATED",
names: {
en: "logger",
cn: "logger",
},
ids: {
en: "command-logger-en",
cn: "command-logger-cn",
}
},
{
id: "command-getstatic",
type: "COMMAND-JVM-RELATED",
names: {
en: "getstatic",
cn: "getstatic",
},
ids: {
en: "command-getstatic-en",
cn: "command-getstatic-cn",
}
},
{
id: "command-ognl",
type: "COMMAND-JVM-RELATED",
names: {
en: "ognl",
cn: "ognl",
},
ids: {
en: "command-ognl-en",
cn: "command-ognl-cn",
}
},
{
id: "command-mbean",
type: "COMMAND-JVM-RELATED",
names: {
en: "mbean",
cn: "mbean",
},
ids: {
en: "command-mbean-en",
cn: "command-mbean-cn",
}
},
{
id: "command-heapdump",
type: "COMMAND-JVM-RELATED",
names: {
en: "heapdump",
cn: "heapdump",
},
ids: {
en: "command-heapdump-en",
cn: "command-heapdump-cn",
}
},
{
id: "command-sc",
type: "COMMAND-CLASS-LOADER-RELATED",
names: {
en: "sc",
cn: "sc",
},
ids: {
en: "command-sc-en",
cn: "command-sc-cn",
}
},
{
id: "command-sm",
type: "COMMAND-CLASS-LOADER-RELATED",
names: {
en: "sm",
cn: "sm",
},
ids: {
en: "command-sm-en",
cn: "command-sm-cn",
}
},
{
id: "command-jad",
type: "COMMAND-CLASS-LOADER-RELATED",
names: {
en: "jad",
cn: "jad",
},
ids: {
en: "command-jad-en",
cn: "command-jad-cn",
}
},
{
id: "command-mc",
type: "COMMAND-CLASS-LOADER-RELATED",
names: {
en: "mc",
cn: "mc",
},
ids: {
en: "command-mc-en",
cn: "command-mc-cn",
}
},
{
id: "command-redefine",
type: "COMMAND-CLASS-LOADER-RELATED",
names: {
en: "redefine",
cn: "redefine",
},
ids: {
en: "command-redefine-en",
cn: "command-redefine-cn",
}
},
{
id: "command-dump",
type: "COMMAND-CLASS-LOADER-RELATED",
names: {
en: "dump",
cn: "dump",
},
ids: {
en: "command-dump-en",
cn: "command-dump-cn",
}
},
{
id: "command-classloader",
type: "COMMAND-CLASS-LOADER-RELATED",
names: {
en: "classloader",
cn: "classloader",
},
ids: {
en: "command-classloader-en",
cn: "command-classloader-cn",
}
},
{
id: "command-monitor",
type: "COMMAND-MONITOR-RELATED",
names: {
en: "monitor",
cn: "monitor",
},
ids: {
en: "command-monitor-en",
cn: "command-monitor-cn",
}
},
{
id: "command-watch",
type: "COMMAND-MONITOR-RELATED",
names: {
en: "watch",
cn: "watch",
},
ids: {
en: "command-watch-en",
cn: "command-watch-cn",
}
},
{
id: "command-trace",
type: "COMMAND-MONITOR-RELATED",
names: {
en: "trace",
cn: "trace",
},
ids: {
en: "command-trace-en",
cn: "command-trace-cn",
}
},
{
id: "command-stack",
type: "COMMAND-MONITOR-RELATED",
names: {
en: "stack",
cn: "stack",
},
ids: {
en: "command-stack-en",
cn: "command-stack-cn",
}
},
{
id: "command-tt",
type: "COMMAND-MONITOR-RELATED",
names: {
en: "tt",
cn: "tt",
},
ids: {
en: "command-tt-en",
cn: "command-tt-cn",
}
},
{
id: "command-options",
type: "COMMAND-OPTIONS",
names: {
en: "options",
cn: "options",
},
ids: {
en: "command-options-en",
cn: "command-options-cn",
}
},
{
id: "case-web-console",
type: "USERCASE",
names: {
en: "Web Console",
cn: "Web Console",
},
ids: {
en: "case-web-console-en",
cn: "case-web-console-cn",
}
},
{
id: "case-save-log",
type: "USERCASE",
names: {
en: "Log the output",
cn: "执行结果存日志",
},
ids: {
en: "case-save-log-en",
cn: "case-save-log-cn",
}
},
{
id: "case-watch-method-exception",
type: "USERCASE",
names: {
en: "Troubleshooting method invoke exception",
cn: "排查函数调用异常",
},
ids: {
en: "case-watch-method-exception-en",
cn: "case-watch-method-exception-cn",
}
},
{
id: "case-thread",
type: "USERCASE",
names: {
en: "Find CPU usage Top N threads",
cn: "查找Top N线程",
},
ids: {
en: "case-thread-en",
cn: "case-thread-cn",
}
},
{
id: "case-ognl-update-logger-level",
type: "USERCASE",
names: {
en: "Change Logger Level",
cn: "动态更新应用Logger Level",
},
ids: {
en: "case-ognl-update-logger-level-en",
cn: "case-ognl-update-logger-level-cn",
}
},
{
id: "case-logger-config-problem",
type: "USERCASE",
names: {
en: "Troubleshoot logger conflicts",
cn: "排查logger冲突问题",
},
ids: {
en: "case-logger-config-problem-en",
cn: "case-logger-config-problem-cn",
}
},
{
id: "case-jad-mc-redefine",
type: "USERCASE",
names: {
en: "Hotswap code",
cn: "热更新代码",
},
ids: {
en: "case-jad-mc-redefine-en",
cn: "case-jad-mc-redefine-cn",
}
},
{
id: "case-http-404",
type: "USERCASE",
names: {
en: "Troubleshooting HTTP request returns 404",
cn: "排查HTTP请求返回404",
},
ids: {
en: "case-http-404-en",
cn: "case-http-404-cn",
}
},
{
id: "case-http-401",
type: "USERCASE",
names: {
en: "Troubleshooting HTTP request returns 401",
cn: "排查HTTP请求返回401",
},
ids: {
en: "case-http-401-en",
cn: "case-http-401-cn",
}
},
{
id: "case-get-spring-context",
type: "USERCASE",
names: {
en: "Get the Spring Context",
cn: "获取Spring Context",
},
ids: {
en: "case-get-spring-context-en",
cn: "case-get-spring-context-cn",
}
},
{
id: "case-classloader",
type: "USERCASE",
names: {
en: "The ClassLoaders in Spring Boot application",
cn: "理解Spring Boot应用的ClassLoader结构",
},
ids: {
en: "case-classloader-en",
cn: "case-classloader-cn",
}
},
{
id: "case-boot-details",
type: "USERCASE",
names: {
en: "Arthas boot supported options",
cn: " arthas-boot支持的参数",
},
ids: {
en: "case-boot-details-en",
cn: "case-boot-details-cn",
}
},
{
id: "case-async-jobs",
type: "USERCASE",
names: {
en: "Async in Background",
cn: "后台异步任务",
},
ids: {
en: "case-async-jobs-en",
cn: "case-async-jobs-cn",
}
}
],
},
Binary file not shown.

After

Width:  |  Height:  |  Size: 244 KiB

+2
View File
@@ -1,6 +1,8 @@
heapdump
===
[`heapdump` online tutorial](https://alibaba.github.io/arthas/arthas-tutorials?language=en&id=command-heapdump)
> dump java heap in hprof binary format, like `jmap`.
+713
View File
@@ -0,0 +1,713 @@
Http API
========
### Overview
Http API provides a RESTful-like interactive interface, and both
requests and responses data in JSON format. Compared with
Telnet/WebConsole's output unstructured text data, Http API can provide
structured data and support more complex interactive functions, such as
a series of diagnostic operations in specific application scenarios.
#### Access address
The Http API address is: `http://ip:port/api`, the request parameters
must be submitted using `POST`. Such as POST
`http://127.0.0.1:8563/api`.
Note: The telnet port `3658` has compatibility issues with the Chrome
browser. It is recommended to use the http port `8563` to access the
http api.
#### Request data format
```json
{
"action": "exec",
"requestId": "req112"
"sessionId": "94766d3c-8b39-42d3-8596-98aee3ccbefb"
"consumerId": "955dbd1325334a84972b0f3ac19de4f7_2"
"command": "version",
"execTimeout": "10000"
}
```
Request data format description:
* `action` : The requested action/behavior, please refer to "Request
Actions" for optional values.
* `requestId` : Optional request ID, generated by the client.
* `sessionId` : Arthas session ID, one-time command does not need to
set the session ID.
* `consumerId` : Arthas consumer ID, used for multi-person sharing
sessions.
* `command` : Arthas command line
* `execTimeout` : Timeout for executing commands (ms), default value is 30000.
Note: Different actions use different parameters. Set the parameters
according to the specific action.
#### Request Actions
Currently supported request actions are as follows:
* `exec` : The command is executed synchronously, and the command
results is returned after the command execution end or interrupted.
* `async_exec` : The command is executed asynchronously, and the
scheduling result of the command is returned immediately. The command
execution result is obtained through `pull_results` action.
* `interrupt_job` : To interrupt the foreground command of the session,
similar to the function of Telnet `Ctrl + c`.
* `pull_results` : Get the result of the command executed
asynchronously, and execute it repeatedly in http long-polling mode.
* `init_session` : Create new session.
* `join_session` : Join the session, used to support multiple people
sharing the same Arthas session.
* `close_session` : Close the session.
#### Response status
The state attribute in the response indicates the request processing
state, and its value is as follows:
* `SCHEDULED`: When the command is executed asynchronously, it means that
the job has been created, and may not be executed yet or is being
executed;
* `SUCCEEDED`: The request is processed successfully (completed status);
* `FAILED`: Request processing failed (completed status), usually
accompanied by a message explaining the reason;
* `REFUSED`: The request is rejected (completed status), usually
accompanied by a message explaining the reason;
### One-time command
Similar to executing batch commands, the one-time commands are executed
synchronously. No need to create a session, no need to set the
`sessionId` option.
```json
{
"action": "exec",
"command": "<Arthas command line>"
}
```
For example, get the Arthas version number:
```bash
curl -Ss -XPOST http://localhost:8563/api -d '
{
"action":"exec",
"command":"version"
}
'
```
The response is as follows:
```json
{
"state" : "SUCCEEDED",
"sessionId" : "ee3bc004-4586-43de-bac0-b69d6db7a869",
"body" : {
"results" : [
{
"type" : "version",
"version" : "3.3.8-SNAPSHOT",
"jobId" : 5
},
{
"jobId" : 5,
"statusCode" : 0,
"type" : "status"
}
],
"timeExpired" : false,
"command" : "version",
"jobStatus" : "TERMINATED",
"jobId" : 5
}
}
```
Response data format description:
* `state`: Request processing status, refer to the description of
"Response Status".
* `sessionId `: Arthas session ID, one-time command to automatically
create and destroy temporary sessions.
* `body.jobId`: The job ID of the command, all output results of the
same job are the same jobId.
* `body.jobStatus`: The job status of the command.
* `body.timeExpired`: Whether the job execution timed out.
* `body/results`: Command execution results.
**Command result format description**
```json
[{
"type" : "version",
"version" : "3.3.8-SNAPSHOT",
"jobId" : 5
},
{
"jobId" : 5,
"statusCode" : 0,
"type" : "status"
}]
```
* `type` : The command result type, except for the special ones such as
`status`, the others remain the same as the Arthas command name.
Please refer to the section
"[Special command results](#special_command_results)".
* `jobId` : The job ID of the command.
* Other fields are the data of each different command.
Note: You can also use a one-time command to execute continuous output
commands such as watch/trace, but you can't interrupt the command
execution, and there may be hang up for a long time. Please refer to the
example in the
"[Make watch command output a map object](#change_watch_value_to_map)"
section.
Please try to deal with it in the following way:
* Set a reasonable `execTimeout` to forcibly interrupt the command
execution after the timeout period is reached to avoid a long hang.
* Use the `-n` parameter to specify a smaller number of executions.
* Ensure the methods of the command matched can be successfully hit and
the `condition-express` is written correctly. If the `watch/trace` does
not hit, even if `-n 1` is specified, it will hang and wait until the
execution timeout.
### Session interaction
Users create and manage Arthas sessions, which are suitable for complex
interactive processes. The access process is as follows:
* Create a session
* Join the session (optional)
* Pull command results
* Execute a series of commands
* Interrupt command execution
* Close the session
#### Create session
```bash
curl -Ss -XPOST http://localhost:8563/api -d '
{
"action":"init_session"
}
'
```
Response result:
```json
{
"sessionId" : "b09f1353-202c-407b-af24-701b744f971e",
"consumerId" : "5ae4e5fbab8b4e529ac404f260d4e2d1_1",
"state" : "SUCCEEDED"
}
```
The new session ID is: `b09f1353-202c-407b-af24-701b744f971e`, and
consumer ID is: `5ae4e5fbab8b4e529ac404f260d4e2d1_1`.
#### Join session
Specify the session ID to join, and the server will assign a new
consumer ID. Multiple consumers can receive the same command results of
target session. This interface is used to support multiple people
sharing the same session or refreshing the page to retrieve the session
history.
```bash
curl -Ss -XPOST http://localhost:8563/api -d '
{
"action":"join_session",
"sessionId" : "b09f1353-202c-407b-af24-701b744f971e"
}
'
```
Response result:
```json
{
"consumerId" : "8f7f6ad7bc2d4cb5aa57a530927a95cc_2",
"sessionId" : "b09f1353-202c-407b-af24-701b744f971e",
"state" : "SUCCEEDED"
}
```
The new consumer ID is `8f7f6ad7bc2d4cb5aa57a530927a95cc_2 ` .
#### Pull command results
The action of pulling the command result message is `pull_results`.
Please use the Http long-polling method to periodically pull the result
messages. The consumer's timeout period is 5 minutes. After the timeout,
you need to call `join_session` to allocate a new consumer.
Each consumer is allocated a cache queue separately, and the pull order
does not affect the content received by the consumer.
The request parameters require session ID and consumer ID:
```bash
curl -Ss -XPOST http://localhost:8563/api -d '
{
"action":"pull_results",
"sessionId" : "b09f1353-202c-407b-af24-701b744f971e",
"consumerId" : "8f7f6ad7bc2d4cb5aa57a530927a95cc_2"
}
'
```
Use Bash scripts to regularly pull results messages:
```bash
while true; do curl -Ss -XPOST http://localhost:8563/api -d '
{
"action":"pull_results",
"sessionId" : "2b085b5d-883b-4914-ab35-b2c5c1d5aa2a",
"consumerId" : "8ecb9cb7c7804d5d92e258b23d5245cc_1"
}
' | json_pp; sleep 2; done
```
Note: The `json_pp` tool formats the output content as pretty json.
The response content is as follows:
```json
{
"body" : {
"results" : [
{
"inputStatus" : "DISABLED",
"jobId" : 0,
"type" : "input_status"
},
{
"type" : "message",
"jobId" : 0,
"message" : "Welcome to arthas!"
},
{
"tutorials" : "https://alibaba.github.io/arthas/arthas-tutorials",
"time" : "2020-08-06 15:56:43",
"type" : "welcome",
"jobId" : 0,
"pid" : "7909",
"wiki" : "https://alibaba.github.io/arthas",
"version" : "3.3.8-SNAPSHOT"
},
{
"inputStatus" : "ALLOW_INPUT",
"type" : "input_status",
"jobId" : 0
}
]
},
"sessionId" : "b09f1353-202c-407b-af24-701b744f971e",
"consumerId" : "8f7f6ad7bc2d4cb5aa57a530927a95cc_2",
"state" : "SUCCEEDED"
}
```
#### Execute commands asynchronously
```bash
curl -Ss -XPOST http://localhost:8563/api -d '''
{
"action":"async_exec",
"command":"watch demo.MathGame primeFactors \"{params, returnObj, throwExp}\" ",
"sessionId" : "2b085b5d-883b-4914-ab35-b2c5c1d5aa2a"
}
'''
```
Response of `async_exec`:
```json
{
"sessionId" : "2b085b5d-883b-4914-ab35-b2c5c1d5aa2a",
"state" : "SCHEDULED",
"body" : {
"jobStatus" : "READY",
"jobId" : 3,
"command" : "watch demo.MathGame primeFactors \"{params, returnObj, throwExp}\" "
}
}
```
* `state` : The status of `SCHEDULED` means that the command has been
parsed and generated the job, but the execution has not started.
* `body.jobId` : The job id of command execution, filter the command
results output in `pull_results` according to this job ID.
* `body.jobStatus` : The job status `READY` means that execution has not started.
The shell output of the script that continuously pulls the result message:
```json
{
"body" : {
"results" : [
{
"type" : "command",
"jobId" : 3,
"state" : "SCHEDULED",
"command" : "watch demo.MathGame primeFactors \"{params, returnObj, throwExp}\" "
},
{
"inputStatus" : "ALLOW_INTERRUPT",
"jobId" : 0,
"type" : "input_status"
},
{
"success" : true,
"jobId" : 3,
"effect" : {
"listenerId" : 3,
"cost" : 24,
"classCount" : 1,
"methodCount" : 1
},
"type" : "enhancer"
},
{
"sizeLimit" : 10485760,
"expand" : 1,
"jobId" : 3,
"type" : "watch",
"cost" : 0.071499,
"ts" : 1596703453237,
"value" : [
[
-170365
],
null,
{
"stackTrace" : [
{
"className" : "demo.MathGame",
"classLoaderName" : "app",
"methodName" : "primeFactors",
"nativeMethod" : false,
"lineNumber" : 46,
"fileName" : "MathGame.java"
},
...
],
"localizedMessage" : "number is: -170365, need >= 2",
"@type" : "java.lang.IllegalArgumentException",
"message" : "number is: -170365, need >= 2"
}
]
},
{
"type" : "watch",
"cost" : 0.033375,
"jobId" : 3,
"ts" : 1596703454241,
"value" : [
[
1
],
[
2,
2,
2,
2,
13,
491
],
null
],
"sizeLimit" : 10485760,
"expand" : 1
}
]
},
"consumerId" : "8ecb9cb7c7804d5d92e258b23d5245cc_1",
"sessionId" : "2b085b5d-883b-4914-ab35-b2c5c1d5aa2a",
"state" : "SUCCEEDED"
}
```
The `value` of the watch command result is the value of watch-experss,
and the above command is `{params, returnObj, throwExp}`, so the value
of the watch result is an array of length 3, and each element
corresponds to the expression in the corresponding order.
Please refer to the section "[Make watch command output a map object](#change_watch_value_to_map)".
#### Interrupt command execution
Interrupt the running foreground job of the session:
```bash
curl -Ss -XPOST http://localhost:8563/api -d '''
{
"action":"interrupt_job",
"sessionId" : "2b085b5d-883b-4914-ab35-b2c5c1d5aa2a"
}
'''
```
```json
{
"state" : "SUCCEEDED",
"body" : {
"jobStatus" : "TERMINATED",
"jobId" : 3
}
}
```
#### Close session
Specify the session ID to close the session.
```bash
curl -Ss -XPOST http://localhost:8563/api -d '''
{
"action":"close_session",
"sessionId" : "2b085b5d-883b-4914-ab35-b2c5c1d5aa2a"
}
'''
```
```json
{
"state" : "SUCCEEDED"
}
```
### Web UI
![](../_static/arthas-web-ui.png "arthas web ui")
A Web UI based on Http API, visit url :
[http://127.0.0.1:8563/ui](http://127.0.0.1:8563/ui) .
Completed functions:
* Create a session
* Copy and open the url to join the session, share the session with
multiple people
* Continuously pull session command result messages
* Refresh the web page or join the session to pull command messages
history
* Control input or interrupt command status
Pending function:
* Improve the readability of command result messages
* Support automatic completion of input commands and command templates
* Provide command help
* Support personal profile settings
<a id="special_command_results"></a>
### Special command results
#### status
```json
{
"jobId" : 5,
"statusCode" : 0,
"type" : "status"
}
```
`type` is `status` to indicate the command execution status:
After each command is executed, there is a unique status result. If the
`statusCode` is 0, it means the execution is successful, and the
`statusCode` is a non-zero value that means the execution failed,
similar to the process exit code.
When the command execution fails, an error message is generally provided, such as:
```json
{
"jobId":3,
"message":"The argument 'class-pattern' is required",
"statusCode":-10,
"type":"status"
}
```
#### input_status
```json
{
"inputStatus" : "ALLOW_INPUT",
"type" : "input_status",
"jobId" : 0
}
```
`type` is `input_status` to indicate input status:
It is used to control user input during UI interaction, and a change
message will be sent before and after each command is executed.
Possible values ​​of `inputStatus`:
* `ALLOW_INPUT` : Allow users to enter commands, which means that the
session has no foreground command being executed and can accept new
command.
* `ALLOW_INTERRUPT` : Allow the user to interrupt the command execution,
indicating that a command is currently being executed, and the user
can send `interrupt_job` to interrupt the execution.
* `DISABLED` : In the disabled state, commands cannot be entered or
interrupted.
#### command
```json
{
"type" : "command",
"jobId" : 3,
"state" : "SCHEDULED",
"command" : "watch demo.MathGame primeFactors \"{params, returnObj, throwExp}\" "
}
```
`type` is `command` to indicate the input command data:
It is used for the interactive UI to echo the commands entered by the
user. The pulled session command message history will contain messages
of type `command`, which can be processed in order.
#### enhancer
```json
{
"success" : true,
"jobId" : 3,
"effect" : {
"listenerId" : 3,
"cost" : 24,
"classCount" : 1,
"methodCount" : 1
},
"type" : "enhancer"
}
```
`type` is `enhancer` to indicate the result of class enhancement:
Commands such as `trace/watch/jad/tt` need to enhance the class and will
receive this `enhancer` result. It may happen that the result of
`enhancer` is successful, but there is no hit method. The client can
prompt the user according to the result of `enhancer`.
### Others
<a id="change_watch_value_to_map"></a>
#### Make watch command output a map object
The result value of `watch` is generated by calculating the
`watch-express` ognl expression. You can change the ognl expression to
generate the desired value, please refer to
[OGNL document](https://commons.apache.org/proper/commons-ognl/language-guide.html).
> Maps can also be created using a special syntax.
>
>#{ "foo" : "foo value", "bar" : "bar value" }
>
>This creates a Map initialized with mappings for "foo" and "bar".
The following command generates values ​​in map format:
```bash
watch *MathGame prime* '#{ "params" : params, "returnObj" : returnObj, "throwExp": throwExp}' -x 2 -n 5
```
Execute the above command in Telnet shell/WebConsole, the output result:
```bash
ts=2020-08-06 16:57:20; [cost=0.241735ms] result=@LinkedHashMap[
@String[params]:@Object[][
@Integer[1],
],
@String[returnObj]:@ArrayList[
@Integer[2],
@Integer[241],
@Integer[379],
],
@String[throwExp]:null,
]
```
Execute the above command with Http api, pay attention to escaping the JSON double quotes:
```bash
curl -Ss -XPOST http://localhost:8563/api -d @- << EOF
{
"action":"exec",
"execTimeout": 30000,
"command":"watch *MathGame prime* '#{ \"params\" : params, \"returnObj\" : returnObj, \"throwExp\": throwExp}' -n 3 "
}
EOF
```
Http api execution result:
```json
{
"body": {
...
"results": [
...
{
...
"type": "watch",
"value": {
"params": [
1
],
"returnObj": [
2,
5,
17,
23,
23
]
}
},
{
...
"type": "watch",
"value": {
"params": [
-98278
],
"throwExp": {
"@type": "java.lang.IllegalArgumentException",
"localizedMessage": "number is: -98278, need >= 2",
"message": "number is: -98278, need >= 2",
"stackTrace": [
...
]
}
}
},
...
}
```
You can see that the value of the watch result becomes a map object, and
the program can read value through a key .
+1
View File
@@ -46,6 +46,7 @@ Contents
* [Advanced usage](advanced-use.md)
* [Commands](commands.md)
* [WebConsole](web-console.md)
* [Http API](http-api.md)
* [Docker](docker.md)
* [Arthas Spring Boot Starter](spring-boot-starter.md)
* [User cases](https://github.com/alibaba/arthas/issues?q=label%3Auser-case)
+2
View File
@@ -1,6 +1,8 @@
trace
=====
[`trace` online tutorial](https://alibaba.github.io/arthas/arthas-tutorials?language=en&id=command-trace)
> Trace method calling path, and output the time cost for each node in the path.
`trace` can track the calling path specified by `class-pattern` / `method-pattern`, and calculate the time cost on the whole path.
+2
View File
@@ -1,6 +1,8 @@
tt
==
[`tt` online tutorial](https://alibaba.github.io/arthas/arthas-tutorials?language=en&id=command-tt)
Check the `parameters`, `return values` and `exceptions` of the methods at different times.
`watch` is a powerful command but due to its feasibility and complexity, it's quite hard to locate the issue effectively.
+2
View File
@@ -1,6 +1,8 @@
watch
=====
[`watch` online tutorial](https://alibaba.github.io/arthas/arthas-tutorials?language=en&id=command-watch)
Monitor methods in data aspect including `return values`, `exceptions` and `parameters`.
With the help of [OGNL](https://commons.apache.org/proper/commons-ognl/index.html), you can easily check the details of variables when methods being invoked.
+1
View File
@@ -1,6 +1,7 @@
Web Console
===
[`Web Console` online tutorial](https://alibaba.github.io/arthas/arthas-tutorials?language=en&id=case-web-console)
### Connect arthas through the browser
+2
View File
@@ -1,6 +1,8 @@
heapdump
===
[`heapdump`在线教程](https://alibaba.github.io/arthas/arthas-tutorials?language=cn&id=command-heapdump)
> dump java heap, 类似jmap命令的heap dump功能。
+632
View File
@@ -0,0 +1,632 @@
Http API
========
### 概览
Http API
提供类似RESTful的交互接口,请求和响应均为JSON格式的数据。相对于Telnet/WebConsole的输出非结构化文本数据,Http
API可以提供结构化的数据,支持更复杂的交互功能,比如特定应用场景的一系列诊断操作。
#### 访问地址
Http API接口地址为:`http://ip:port/api`,必须使用POST方式提交请求参数。如POST
`http://127.0.0.1:8563/api` 。
注意:telnet服务的3658端口与Chrome浏览器有兼容性问题,建议使用http端口8563来访问http接口。
#### 请求数据格式
```json
{
"action": "exec",
"requestId": "req112"
"sessionId": "94766d3c-8b39-42d3-8596-98aee3ccbefb"
"consumerId": "955dbd1325334a84972b0f3ac19de4f7_2"
"command": "version",
"execTimeout": "10000"
}
```
请求数据格式说明:
* `action` : 请求的动作/行为,可选值请参考"请求Action"小节。
* `requestId` : 可选请求ID,由客户端生成。
* `sessionId` : Arthas会话ID,一次性命令不需要设置会话ID。
* `consumerId` : Arthas消费者ID,用于多人共享会话。
* `command` : Arthas command line 。
* `execTimeout` : 命令同步执行的超时时间(ms),默认为30000。
注意: 不同的action使用到参数不同,根据具体的action来设置参数。
#### 请求Action
目前支持的请求Action如下:
* `exec` : 同步执行命令,命令正常结束或者超时后中断命令执行后返回命令的执行结果。
* `async_exec` : 异步执行命令,立即返回命令的调度结果,命令执行结果通过`pull_results`获取。
* `interrupt_job` : 中断会话当前的命令,类似Telnet `Ctrl + c`的功能。
* `pull_results` : 获取异步执行的命令的结果,以http 长轮询(long-polling)方式重复执行
* `init_session` : 创建会话
* `join_session` : 加入会话,用于支持多人共享同一个Arthas会话
* `close_session` : 关闭会话
#### 响应状态
响应中的state属性表示请求处理状态,取值如下:
* `SCHEDULED`:异步执行命令时表示已经创建job并已提交到命令执行队列,命令可能还没开始执行或者执行中;
* `SUCCEEDED`:请求处理成功(完成状态);
* `FAILED`:请求处理失败(完成状态),通常附带message说明原因;
* `REFUSED`:请求被拒绝(完成状态),通常附带message说明原因;
### 一次性命令
与执行批处理命令类似,一次性命令以同步方式执行。不需要创建会话,不需要设置`sessionId`选项。
```json
{
"action": "exec",
"command": "<Arthas command line>"
}
```
比如获取Arthas版本号:
```bash
curl -Ss -XPOST http://localhost:8563/api -d '
{
"action":"exec",
"command":"version"
}
'
```
响应内容如下:
```json
{
"state" : "SUCCEEDED",
"sessionId" : "ee3bc004-4586-43de-bac0-b69d6db7a869",
"body" : {
"results" : [
{
"type" : "version",
"version" : "3.3.8-SNAPSHOT",
"jobId" : 5
},
{
"jobId" : 5,
"statusCode" : 0,
"type" : "status"
}
],
"timeExpired" : false,
"command" : "version",
"jobStatus" : "TERMINATED",
"jobId" : 5
}
}
```
响应数据解析:
* `state`: 请求处理状态,参考“接口响应状态”说明
* `sessionId `: Arthas会话ID,一次性命令自动创建及销毁临时会话
* `body.jobId`: 命令的任务ID,同一任务输出的所有Result都是相同的jobId
* `body.jobStatus`: 任务状态,同步执行正常结束为`TERMINATED `
* `body.timeExpired`: 任务执行是否超时
* `body/results`: 命令执行的结果列表
**命令结果格式说明**
```json
[{
"type" : "version",
"version" : "3.3.8-SNAPSHOT",
"jobId" : 5
},
{
"jobId" : 5,
"statusCode" : 0,
"type" : "status"
}]
```
* `type` : 命令结果类型,除了`status`等特殊的几个外,其它的保持与Arthas命令名称一致。请参考"[特殊命令结果](#special_command_results)"小节。
* `jobId` : 处理命令的任务ID。
* 其它字段为每个不同命令的数据。
注意:也可以使用一次性命令的方式执行watch/trace等连续输出的命令,但不能中断命令执行,可能出现长时间没有结束的问题。请参考"[watch命令输出map对象](#change_watch_value_to_map)"小节的示例。
请尽量按照以下方式处理:
* 设置合理的`execTimeout`,到达超时时间后强制中断命令执行,避免长时间挂起。
* 通过`-n`参数指定较少的执行次数。
* 保证命令匹配的方法可以成功命中和condition-express编写正确,如果watch/trace没有命中就算指定`-n
1`也会挂起等待到执行超时。
### 会话交互
由用户创建及管理Arthas会话,适用于复杂的交互过程。访问流程如下:
* 创建会话
* 加入会话(可选)
* 拉取命令结果
* 执行一系列命令
* 中断命令执行
* 关闭会话
#### 创建会话
```bash
curl -Ss -XPOST http://localhost:8563/api -d '
{
"action":"init_session"
}
'
```
响应结果:
```json
{
"sessionId" : "b09f1353-202c-407b-af24-701b744f971e",
"consumerId" : "5ae4e5fbab8b4e529ac404f260d4e2d1_1",
"state" : "SUCCEEDED"
}
```
当前会话ID为: `b09f1353-202c-407b-af24-701b744f971e`, 当前消费者ID为:`5ae4e5fbab8b4e529ac404f260d4e2d1_1 `。
#### 加入会话
指定要加入的会话ID,服务端将分配一个新的消费者ID。多个消费者可以接收到同一个会话的命令结果。本接口用于支持多人共享同一个会话或刷新页面后重新拉取会话历史记录。
```bash
curl -Ss -XPOST http://localhost:8563/api -d '
{
"action":"join_session",
"sessionId" : "b09f1353-202c-407b-af24-701b744f971e"
}
'
```
响应结果:
```json
{
"consumerId" : "8f7f6ad7bc2d4cb5aa57a530927a95cc_2",
"sessionId" : "b09f1353-202c-407b-af24-701b744f971e",
"state" : "SUCCEEDED"
}
```
新的消费者ID为`8f7f6ad7bc2d4cb5aa57a530927a95cc_2 ` 。
#### 拉取命令结果
拉取命令结果消息的action为`pull_results`。请使用Http long-polling方式,定时循环拉取结果消息。
消费者的超时时间为5分钟,超时后需要调用`join_session`分配新的消费者。每个消费者单独分配一个缓存队列,按顺序拉取命令结果,不会影响到其它消费者。
请求参数需要指定会话ID及消费者ID:
```bash
curl -Ss -XPOST http://localhost:8563/api -d '
{
"action":"pull_results",
"sessionId" : "b09f1353-202c-407b-af24-701b744f971e",
"consumerId" : "8f7f6ad7bc2d4cb5aa57a530927a95cc_2"
}
'
```
用Bash脚本定时拉取结果消息:
```bash
while true; do curl -Ss -XPOST http://localhost:8563/api -d '
{
"action":"pull_results",
"sessionId" : "2b085b5d-883b-4914-ab35-b2c5c1d5aa2a",
"consumerId" : "8ecb9cb7c7804d5d92e258b23d5245cc_1"
}
' | json_pp; sleep 2; done
```
注: `json_pp` 工具将输出内容格式化为pretty json。
响应内容如下:
```json
{
"body" : {
"results" : [
{
"inputStatus" : "DISABLED",
"jobId" : 0,
"type" : "input_status"
},
{
"type" : "message",
"jobId" : 0,
"message" : "Welcome to arthas!"
},
{
"tutorials" : "https://alibaba.github.io/arthas/arthas-tutorials",
"time" : "2020-08-06 15:56:43",
"type" : "welcome",
"jobId" : 0,
"pid" : "7909",
"wiki" : "https://alibaba.github.io/arthas",
"version" : "3.3.8-SNAPSHOT"
},
{
"inputStatus" : "ALLOW_INPUT",
"type" : "input_status",
"jobId" : 0
}
]
},
"sessionId" : "b09f1353-202c-407b-af24-701b744f971e",
"consumerId" : "8f7f6ad7bc2d4cb5aa57a530927a95cc_2",
"state" : "SUCCEEDED"
}
```
#### 异步执行命令
```bash
curl -Ss -XPOST http://localhost:8563/api -d '''
{
"action":"async_exec",
"command":"watch demo.MathGame primeFactors \"{params, returnObj, throwExp}\" ",
"sessionId" : "2b085b5d-883b-4914-ab35-b2c5c1d5aa2a"
}
'''
```
`async_exec` 的结果:
```json
{
"sessionId" : "2b085b5d-883b-4914-ab35-b2c5c1d5aa2a",
"state" : "SCHEDULED",
"body" : {
"jobStatus" : "READY",
"jobId" : 3,
"command" : "watch demo.MathGame primeFactors \"{params, returnObj, throwExp}\" "
}
}
```
* `state` : `SCHEDULED` 状态表示已经解析命令生成任务,但未开始执行。
* `body.jobId` :
异步执行命令的任务ID,可以根据此任务ID来过滤在`pull_results`输出的命令结果。
* `body.jobStatus` : 任务状态`READY`表示未开始执行。
查看上面自动拉取结果消息脚本的shell输出:
```json
{
"body" : {
"results" : [
{
"type" : "command",
"jobId" : 3,
"state" : "SCHEDULED",
"command" : "watch demo.MathGame primeFactors \"{params, returnObj, throwExp}\" "
},
{
"inputStatus" : "ALLOW_INTERRUPT",
"jobId" : 0,
"type" : "input_status"
},
{
"success" : true,
"jobId" : 3,
"effect" : {
"listenerId" : 3,
"cost" : 24,
"classCount" : 1,
"methodCount" : 1
},
"type" : "enhancer"
},
{
"sizeLimit" : 10485760,
"expand" : 1,
"jobId" : 3,
"type" : "watch",
"cost" : 0.071499,
"ts" : 1596703453237,
"value" : [
[
-170365
],
null,
{
"stackTrace" : [
{
"className" : "demo.MathGame",
"classLoaderName" : "app",
"methodName" : "primeFactors",
"nativeMethod" : false,
"lineNumber" : 46,
"fileName" : "MathGame.java"
},
...
],
"localizedMessage" : "number is: -170365, need >= 2",
"@type" : "java.lang.IllegalArgumentException",
"message" : "number is: -170365, need >= 2"
}
]
},
{
"type" : "watch",
"cost" : 0.033375,
"jobId" : 3,
"ts" : 1596703454241,
"value" : [
[
1
],
[
2,
2,
2,
2,
13,
491
],
null
],
"sizeLimit" : 10485760,
"expand" : 1
}
]
},
"consumerId" : "8ecb9cb7c7804d5d92e258b23d5245cc_1",
"sessionId" : "2b085b5d-883b-4914-ab35-b2c5c1d5aa2a",
"state" : "SUCCEEDED"
}
```
watch命令结果的`value`为watch-experss的值,上面命令中为`{params, returnObj,
throwExp}`,所以watch结果的value为一个长度为3的数组,每个元素分别对应相应顺序的表达式。
请参考"[watch命令输出map对象](#change_watch_value_to_map)"小节。
#### 中断命令执行
中断会话正在运行的前台Job(前台任务):
```bash
curl -Ss -XPOST http://localhost:8563/api -d '''
{
"action":"interrupt_job",
"sessionId" : "2b085b5d-883b-4914-ab35-b2c5c1d5aa2a"
}
'''
```
```
{
"state" : "SUCCEEDED",
"body" : {
"jobStatus" : "TERMINATED",
"jobId" : 3
}
}
```
#### 关闭会话
指定会话ID,关闭会话。
```bash
curl -Ss -XPOST http://localhost:8563/api -d '''
{
"action":"close_session",
"sessionId" : "2b085b5d-883b-4914-ab35-b2c5c1d5aa2a"
}
'''
```
```json
{
"state" : "SUCCEEDED"
}
```
### Web UI
![](_static/arthas-web-ui.png "arthas web ui")
一个基于Http API接口实现的Web UI,访问地址为: [http://127.0.0.1:8563/ui](http://127.0.0.1:8563/ui) 。
已实现功能:
* 创建会话
* 复制并打开url加入会话,多人共享会话
* 周期性拉取会话命令结果消息
* 刷新页面或者加入会话拉取会话历史命令消息
* 输入命令/中断命令状态控制
待开发功能:
* 改进将命令结果消息可读性
* 命令输入支持自动完成及命令模板
* 提供命令帮助
* 支持个人选项设置
<a id="special_command_results"></a>
### 特殊命令结果
#### status
```json
{
"jobId" : 5,
"statusCode" : 0,
"type" : "status"
}
```
`type`为`status`表示命令执行状态:
每个命令执行结束后都有唯一一个status结果。`statusCode`
为0表示执行成功,`statusCode` 为非0值表示执行失败,类似进程退出码(exit code)。
命令执行失败时一般会提供错误消息,如:
```json
{
"jobId":3,
"message":"The argument 'class-pattern' is required",
"statusCode":-10,
"type":"status"
}
```
#### input_status
```json
{
"inputStatus" : "ALLOW_INPUT",
"type" : "input_status",
"jobId" : 0
}
```
`type`为`input_status`表示输入状态:
用于UI交互时控制用户输入,每次执行命令前后会发送改变的消息。
`inputStatus` 的值说明:
* `ALLOW_INPUT` :
允许用户输入命令,表示会话没有在执行的前台命令,可以接受新的命令。
* `ALLOW_INTERRUPT` :
允许用户中断命令执行,表示当前正在执行命令,用户可以发送`interrupt_job`中断执行。
* `DISABLED` : 禁用状态,不能输入命令也不能中断命令。
#### command
```json
{
"type" : "command",
"jobId" : 3,
"state" : "SCHEDULED",
"command" : "watch demo.MathGame primeFactors \"{params, returnObj, throwExp}\" "
}
```
`type` 为`command`表示输入的命令数据:
用于交互UI回显用户输入的命令,拉取的会话命令消息历史会包含`command`类型的消息,按顺序处理即可。
#### enhancer
```json
{
"success" : true,
"jobId" : 3,
"effect" : {
"listenerId" : 3,
"cost" : 24,
"classCount" : 1,
"methodCount" : 1
},
"type" : "enhancer"
}
```
`type`为`enhancer`表示类增强结果:
`trace/watch/jad/tt`等命令需要对类进行增强,会接收到这个`enhancer`结果。可能出现`enhancer`结果成功,但没有命中方法的情况,客户端可以根据`enhancer`结果提示用户。
### 其它
<a id="change_watch_value_to_map"></a>
#### watch命令输出map对象
watch的结果值由计算`watch-express` ognl表达式产生,可以通过改变ognl表达式来生成想要的值,请参考[OGNL文档](https://commons.apache.org/proper/commons-ognl/language-guide.html)。
> Maps can also be created using a special syntax.
>
>#{ "foo" : "foo value", "bar" : "bar value" }
>
>This creates a Map initialized with mappings for "foo" and "bar".
下面的命令生成map格式的值:
```bash
watch *MathGame prime* '#{ "params" : params, "returnObj" : returnObj, "throwExp": throwExp}' -x 2 -n 5
```
在Telnet shell/WebConsole 中执行上面的命令,输出的结果:
```bash
ts=2020-08-06 16:57:20; [cost=0.241735ms] result=@LinkedHashMap[
@String[params]:@Object[][
@Integer[1],
],
@String[returnObj]:@ArrayList[
@Integer[2],
@Integer[241],
@Integer[379],
],
@String[throwExp]:null,
]
```
用Http api 执行上面的命令,注意对JSON双引号转义:
```bash
curl -Ss -XPOST http://localhost:8563/api -d @- << EOF
{
"action":"exec",
"execTimeout": 30000,
"command":"watch *MathGame prime* '#{ \"params\" : params, \"returnObj\" : returnObj, \"throwExp\": throwExp}' -n 3 "
}
EOF
```
Http api 执行结果:
```json
{
"body": {
...
"results": [
...
{
...
"type": "watch",
"value": {
"params": [
1
],
"returnObj": [
2,
5,
17,
23,
23
]
}
},
{
...
"type": "watch",
"value": {
"params": [
-98278
],
"throwExp": {
"@type": "java.lang.IllegalArgumentException",
"localizedMessage": "number is: -98278, need >= 2",
"message": "number is: -98278, need >= 2",
"stackTrace": [
...
]
}
}
},
...
}
```
可以看到watch结果的value变成map对象,程序可以通过key读取结果。
+1
View File
@@ -37,6 +37,7 @@ Contents
* [进阶使用](advanced-use.md)
* [命令列表](commands.md)
* [WebConsole](web-console.md)
* [Http API](http-api.md)
* [Docker](docker.md)
* [Arthas Spring Boot Starter](spring-boot-starter.md)
* [用户案例](https://github.com/alibaba/arthas/issues?q=label%3Auser-case)
+2
View File
@@ -1,6 +1,8 @@
trace
===
[`trace`在线教程](https://alibaba.github.io/arthas/arthas-tutorials?language=cn&id=command-trace)
> 方法内部调用路径,并输出方法路径上的每个节点上耗时
`trace` 命令能主动搜索 `class-pattern`/`method-pattern` 对应的方法调用路径,渲染和统计整个调用链路上的所有性能开销和追踪调用链路。
+2
View File
@@ -1,6 +1,8 @@
tt
===
[`tt`在线教程](https://alibaba.github.io/arthas/arthas-tutorials?language=cn&id=command-tt)
> 方法执行数据的时空隧道,记录下指定方法每次调用的入参和返回信息,并能对这些不同的时间下调用进行观测
`watch` 虽然很方便和灵活,但需要提前想清楚观察表达式的拼写,这对排查问题而言要求太高,因为很多时候我们并不清楚问题出自于何方,只能靠蛛丝马迹进行猜测。
+2
View File
@@ -1,6 +1,8 @@
watch
===
[`watch`在线教程](https://alibaba.github.io/arthas/arthas-tutorials?language=cn&id=command-watch)
> 方法执行数据观测
让你能方便的观察到指定方法的调用情况。能观察到的范围为:`返回值`、`抛出异常`、`入参`,通过编写 OGNL 表达式进行对应变量的查看。
+1 -1
View File
@@ -1,7 +1,7 @@
Web Console
===
[`Web Console`在线教程](https://alibaba.github.io/arthas/arthas-tutorials?language=cn&id=case-web-console)
### 通过浏览器连接arthas
@@ -0,0 +1,16 @@
在新的`Terminal 2`里,下载`arthas-boot.jar`,再用`java -jar`命令启动:
`wget https://alibaba.github.io/arthas/arthas-boot.jar
java -jar arthas-boot.jar --target-ip 0.0.0.0`{{execute T2}}
`arthas-boot`是`Arthas`的启动程序,它启动后,会列出所有的Java进程,用户可以选择需要诊断的目标进程。
选择第一个进程,输入 `1`{{execute T2}} ,再`Enter/回车`:
Attach成功之后,会打印Arthas LOGO。输入 `help`{{execute T2}} 可以获取到更多的帮助信息。
![Arthas Boot](/arthas/scenarios/common-resources/assets/arthas-boot.png)
@@ -0,0 +1,10 @@
下载`arthas-demo.jar`,再用`java -jar`命令启动:
`wget https://alibaba.github.io/arthas/arthas-demo.jar
java -jar arthas-demo.jar`{{execute T1}}
`arthas-demo`是一个很简单的程序,它随机生成整数,再执行因式分解,把结果打印出来。如果生成的随机数是负数,则会打印提示信息。
@@ -0,0 +1,10 @@
通过本教程基本掌握了Arthas Web Console。更多高级特性,可以在下面的进阶指南里继续了解。
* [Arthas进阶](https://alibaba.github.io/arthas/arthas-tutorials?language=cn&id=arthas-advanced)
* [Arthas Github](https://github.com/alibaba/arthas)
* [Arthas 文档](https://alibaba.github.io/arthas/)
欢迎关注公众号,获取Arthas项目的信息,源码分析,案例实践。
![Arthas公众号](/arthas/scenarios/common-resources/assets/qrcode_gongzhonghao.jpg)
@@ -0,0 +1,35 @@
{
"title": "Arthas Web Console 案例",
"description": "Arthas Web Console 案例",
"difficulty": "精通者",
"time": "10-20 分钟",
"details": {
"steps": [
{
"title": "启动arthas demo",
"text": "arthas-demo.md"
},
{
"title": "启动arthas-boot",
"text": "arthas-boot.md"
},
{
"title": "Web Console",
"text": "web-console.md"
}
],
"intro": {
"text": "intro.md"
},
"finish": {
"text": "finish.md"
}
},
"environment": {
"uilayout": "terminal"
},
"backend": {
"imageid": "java",
"environmentsprotocol": "http"
}
}
@@ -0,0 +1,11 @@
![Arthas](https://alibaba.github.io/arthas/_images/arthas.png)
`Arthas` 是Alibaba开源的Java诊断工具,深受开发者喜爱。在线排查问题,无需重启;动态跟踪Java代码;实时监控JVM状态。
`Arthas` 支持JDK 6+,支持Linux/Mac/Windows,采用命令行交互模式,同时提供丰富的 `Tab` 自动补全功能,进一步方便进行问题的定位和诊断。
* Github: https://github.com/alibaba/arthas
* 文档: https://alibaba.github.io/arthas/
@@ -0,0 +1,19 @@
Arthas支持通过Web Socket来连接。
## 教程里的Web Console
http://[[HOST_SUBDOMAIN]]-8563-[[KATACODA_HOST]].environments.katacoda.com/?ip=[[HOST_SUBDOMAIN]]-8563-[[KATACODA_HOST]].environments.katacoda.com&port=80
> 注意:教程里访问的是80端口,因为做了端口转发。在本地体验时,需要访问8563端口。
## 本地体验
当在本地启动时,可以访问 http://127.0.0.1:8563/ ,通过浏览器来使用Arthas。
![Arthas WebConsole](/arthas/scenarios/common-resources/assets/web-console.png)
推荐通过“快速入门”来体验: https://alibaba.github.io/arthas/quick-start.html
@@ -0,0 +1,16 @@
In the new `Terminal 2`, download `arthas-boot.jar` and start with the `java -jar` command:
`wget https://alibaba.github.io/arthas/arthas-boot.jar
java -jar arthas-boot.jar --target-ip 0.0.0.0`{{execute T2}}
`arthas-boot` is the launcher for `Arthas`. It lists all the Java processes, and the user can select the target process to be diagnosed.
Select the first process, type `1`{{execute T2}} ,then type `Enter`:
After the Attach is successful, Arthas LOGO is printed. Enter `help`{{execute T2}} for more help.
![Arthas Boot](/arthas/scenarios/common-resources/assets/arthas-boot.png)
@@ -0,0 +1,11 @@
Download `arthas-demo.jar` and start with the `java -jar` command:
`wget https://alibaba.github.io/arthas/arthas-demo.jar
java -jar arthas-demo.jar`{{execute T1}}
`arthas-demo` is a very simple program that randomly generates integers, performs factorization, and prints the results.
If the generated random number is negative, a error message will be printed.
@@ -0,0 +1,6 @@
Through this tutorial, you can know how to use Arthas `Web console`. More advanced features can be found in the Advanced Guide below.
* [Arthas Advanced](https://alibaba.github.io/arthas/arthas-tutorials?language=en&id=arthas-advanced)
* [Arthas Github](https://github.com/alibaba/arthas)
* [Arthas Documentation](https://alibaba.github.io/arthas/en)
@@ -0,0 +1,35 @@
{
"title": "Arthas Web Console",
"description": "Arthas Web Console",
"difficulty": "master",
"time": "10-20 minutes",
"details": {
"steps": [
{
"title": "Arthas demo",
"text": "arthas-demo.md"
},
{
"title": "Start arthas-boot",
"text": "arthas-boot.md"
},
{
"title": "Web Console",
"text": "web-console.md"
}
],
"intro": {
"text": "intro.md"
},
"finish": {
"text": "finish.md"
}
},
"environment": {
"uilayout": "terminal"
},
"backend": {
"imageid": "java",
"environmentsprotocol": "http"
}
}
@@ -0,0 +1,11 @@
![Arthas](https://alibaba.github.io/arthas/_images/arthas.png)
`Arthas` is a Java diagnostic tool open-sourced by Alibaba middleware team. Arthas helps developers in trouble-shooting issues in production environment for Java based applications without modifying code or restarting servers.
`Arthas` supports JDK 6+, supports Linux/Mac/Windows.
* Github: https://github.com/alibaba/arthas
* Documentation: https://alibaba.github.io/arthas/en
@@ -0,0 +1,20 @@
Arthas supports connections via a Web Socket.
## The Web Console in the tutorial
http://[[HOST_SUBDOMAIN]]-8563-[[KATACODA_HOST]].environments.katacoda.com/?ip=[[HOST_SUBDOMAIN]]-8563-[[KATACODA_HOST]].environments.katacoda.com&port=80
> Note: The 80 port is accessed in the tutorial because port forwarding. In the local, you need to access port 8563.
## Local
When launching locally, you can access Arthas through a browser by visiting http://127.0.0.1:8563/.
![Arthas WebConsole](/arthas/scenarios/common-resources/assets/web-console.png)
It is recommended to experience it through "Quick Start": https://alibaba.github.io/arthas/en/quick-start.html
@@ -0,0 +1,16 @@
在新的`Terminal 2`里,下载`arthas-boot.jar`,再用`java -jar`命令启动:
`wget https://alibaba.github.io/arthas/arthas-boot.jar
java -jar arthas-boot.jar`{{execute T2}}
`arthas-boot`是`Arthas`的启动程序,它启动后,会列出所有的Java进程,用户可以选择需要诊断的目标进程。
选择第一个进程,输入 `1`{{execute T2}} ,再`Enter/回车`:
Attach成功之后,会打印Arthas LOGO。输入 `help`{{execute T2}} 可以获取到更多的帮助信息。
![Arthas Boot](/arthas/scenarios/common-resources/assets/arthas-boot.png)
@@ -0,0 +1,10 @@
下载`arthas-demo.jar`,再用`java -jar`命令启动:
`wget https://alibaba.github.io/arthas/arthas-demo.jar
java -jar arthas-demo.jar`{{execute T1}}
`arthas-demo`是一个很简单的程序,它随机生成整数,再执行因式分解,把结果打印出来。如果生成的随机数是负数,则会打印提示信息。
@@ -0,0 +1,12 @@
在“heapdump”中,我们演示了了Arthas的heapdump命令。如果有更多的技巧或者使用疑问,欢迎在Issue里提出。
* Issues: https://github.com/alibaba/arthas/issues
* 文档: https://alibaba.github.io/arthas
如果您在使用Arthas,请让我们知道,您的使用对我们非常重要:[查看](https://github.com/alibaba/arthas/issues/111)
欢迎关注公众号,获取Arthas项目的信息,源码分析,案例实践。
![Arthas公众号](/arthas/scenarios/common-resources/assets/qrcode_gongzhonghao.jpg)
@@ -0,0 +1,38 @@
> dump java heap, 类似jmap命令的heap dump功能。
### 使用参考
#### dump到指定文件
`heapdump /tmp/dump.hprof`{{execute T2}}
```bash
[arthas@58205]$ heapdump /tmp/dump.hprof
Dumping heap to /tmp/dump.hprof...
Heap dump file created
```
#### 只dump live对象
`heapdump --live /tmp/dump.hprof`{{execute T2}}
```bash
[arthas@58205]$ heapdump --live /tmp/dump.hprof
Dumping heap to /tmp/dump.hprof...
Heap dump file created
```
### dump到临时文件
`heapdump`{{execute T2}}
```bash
[arthas@58205]$ heapdump
Dumping heap to /var/folders/my/wy7c9w9j5732xbkcyt1mb4g40000gp/T/heapdump2019-09-03-16-385121018449645518991.hprof...
Heap dump file created
```
@@ -0,0 +1,35 @@
{
"title": "Arthas heapdump命令",
"description": "Arthas heapdump命令",
"difficulty": "精通者",
"time": "10-20 分钟",
"details": {
"steps": [
{
"title": "启动arthas demo",
"text": "arthas-demo.md"
},
{
"title": "启动arthas-boot",
"text": "arthas-boot.md"
},
{
"title": "heapdump命令",
"text": "heapdump.md"
}
],
"intro": {
"text": "intro.md"
},
"finish": {
"text": "finish.md"
}
},
"environment": {
"uilayout": "terminal"
},
"backend": {
"imageid": "java",
"environmentsprotocol": "http"
}
}
@@ -0,0 +1,23 @@
![Arthas](https://alibaba.github.io/arthas/_images/arthas.png)
`Arthas` 是Alibaba开源的Java诊断工具,深受开发者喜爱。在线排查问题,无需重启;动态跟踪Java代码;实时监控JVM状态。
`Arthas` 支持JDK 6+,支持Linux/Mac/Windows,采用命令行交互模式,同时提供丰富的 `Tab` 自动补全功能,进一步方便进行问题的定位和诊断。
当你遇到以下类似问题而束手无策时,Arthas可以帮助你解决:
- 这个类从哪个 jar 包加载的?为什么会报各种类相关的 Exception?
- 我改的代码为什么没有执行到?难道是我没 commit?分支搞错了?
- 遇到问题无法在线上 debug,难道只能通过加日志再重新发布吗?
- 线上遇到某个用户的数据处理有问题,但线上同样无法 debug,线下无法重现!
- 是否有一个全局视角来查看系统的运行状况?
- 有什么办法可以监控到JVM的实时运行状态?
- 怎么快速定位应用的热点,生成火焰图?
本教程会以一个简单的应用为例,演示heapdump命令。
* Github: https://github.com/alibaba/arthas
* 文档: https://alibaba.github.io/arthas/
@@ -0,0 +1,16 @@
In the new `Terminal 2`, download `arthas-boot.jar` and start with the `java -jar` command:
`wget https://alibaba.github.io/arthas/arthas-boot.jar
java -jar arthas-boot.jar`{{execute T2}}
`arthas-boot` is the launcher for `Arthas`. It lists all the Java processes, and the user can select the target process to be diagnosed.
Select the first process, type `1`{{execute T2}} ,then type `Enter`:
After the Attach is successful, Arthas LOGO is printed. Enter `help`{{execute T2}} for more help.
![Arthas Boot](/arthas/scenarios/common-resources/assets/arthas-boot.png)
@@ -0,0 +1,11 @@
Download `arthas-demo.jar` and start with the `java -jar` command:
`wget https://alibaba.github.io/arthas/arthas-demo.jar
java -jar arthas-demo.jar`{{execute T1}}
`arthas-demo` is a very simple program that randomly generates integers, performs factorization, and prints the results.
If the generated random number is negative, a error message will be printed.
@@ -0,0 +1,8 @@
The `heapdump Tutorial` demonstrates the usage of heapdump. If you have more tips or questions, please feel free to ask in Issue.
* Issues: https://github.com/alibaba/arthas/issues
* Documentation: https://alibaba.github.io/arthas
If you are using Arthas, please let us know. Your use is very important to us: [View](https://github.com/alibaba/arthas/issues/111)
@@ -0,0 +1,38 @@
> dump java heap in hprof binary format, like `jmap`.
### Usage
#### Dump to file
`heapdump /tmp/dump.hprof`{{execute T2}}
```bash
[arthas@58205]$ heapdump /tmp/dump.hprof
Dumping heap to /tmp/dump.hprof...
Heap dump file created
```
#### Dump only live objects
`heapdump --live /tmp/dump.hprof`{{execute T2}}
```bash
[arthas@58205]$ heapdump --live /tmp/dump.hprof
Dumping heap to /tmp/dump.hprof...
Heap dump file created
```
#### Dump to tmp file
`heapdump`{{execute T2}}
```bash
[arthas@58205]$ heapdump
Dumping heap to /var/folders/my/wy7c9w9j5732xbkcyt1mb4g40000gp/T/heapdump2019-09-03-16-385121018449645518991.hprof...
Heap dump file created
```
@@ -0,0 +1,35 @@
{
"title": "Arthas heapdump Command",
"description": "Arthas heapdump Command",
"difficulty": "master",
"time": "10-20 minutes",
"details": {
"steps": [
{
"title": "Arthas demo",
"text": "arthas-demo.md"
},
{
"title": "Start arthas-boot",
"text": "arthas-boot.md"
},
{
"title": "heapdump Command",
"text": "heapdump.md"
}
],
"intro": {
"text": "intro.md"
},
"finish": {
"text": "finish.md"
}
},
"environment": {
"uilayout": "terminal"
},
"backend": {
"imageid": "java",
"environmentsprotocol": "http"
}
}
@@ -0,0 +1,40 @@
![Arthas](https://alibaba.github.io/arthas/_images/arthas.png)
`Arthas` is a Java diagnostic tool open-sourced by Alibaba middleware team. Arthas helps developers in trouble-shooting issues in production environment for Java based applications without modifying code or restarting servers.
`Arthas` supports JDK 6+, supports Linux/Mac/Windows.
## Background
Oftentimes the production system network is inaccessible from local development environment. If issues are encountered in production systems, it is impossible to use IDE to debug the application remotely. What’s even worse, debugging in production environment is unacceptable, as it will suspend all the threads, leading to services downtime.
Developers could always try to reproduce the same issue on the test/staging environment. However, this is tricky as some issues cannot be reproduced easily in a different environment, or even disappear once restarted.
And if you’re thinking of adding some logs to your code to help trouble-shoot the issue, you will have to go through the following lifecycle: test, staging, and then to production. Time is money! This approach is inefficient! Worse still, the issue may not be fixed since it might be irreproducible once the JVM is restarted, as described above.
Arthas is built to solve these issues. A developer can troubleshoot production issues on the fly. No JVM restart, no additional code changes. Arthas works as an observer, that is, it will never suspend your running threads.
## Key features
- Check whether a class is loaded? Or where the class is loaded from? (Useful for trouble-shooting jar file conflicts)
- Decompile a class to ensure the code is running as expected.
- Check classloader statistics, e.g. the number of classloaders, the number of classes loaded per classloader, the classloader hierarchy, possible classloader leaks, etc.
- Check the method invocation details, e.g. method parameter, returned values, exceptions and etc.
- Check the stack trace of specified method invocation. This is useful when a developer wants to know the caller of the method.
- Trace the method invocation to find slow sub-invocations.
- Monitor method invocation statistics, e.g. QPS (Query Per Second), RT (Return Time), success rate and etc.
- Monitor system metrics, thread states and CPU usage, GC statistics and etc.
- Supports command line interactive mode, with auto-complete feature enabled.
- Supports telnet and WebSocket, which enables both local and remote diagnostics with command line and browsers.
- Supports profiler/Flame Graph
- Supports JDK 6+
- Supports Linux/Mac/Windows
This tutorial takes a simple application as an example to demonstrate the the usage of heapdump.
* Github: https://github.com/alibaba/arthas
* Docs: https://alibaba.github.io/arthas/
@@ -0,0 +1,16 @@
在新的`Terminal 2`里,下载`arthas-boot.jar`,再用`java -jar`命令启动:
`wget https://alibaba.github.io/arthas/arthas-boot.jar
java -jar arthas-boot.jar`{{execute T2}}
`arthas-boot`是`Arthas`的启动程序,它启动后,会列出所有的Java进程,用户可以选择需要诊断的目标进程。
选择第一个进程,输入 `1`{{execute T2}} ,再`Enter/回车`:
Attach成功之后,会打印Arthas LOGO。输入 `help`{{execute T2}} 可以获取到更多的帮助信息。
![Arthas Boot](/arthas/scenarios/common-resources/assets/arthas-boot.png)
@@ -0,0 +1,10 @@
下载`arthas-demo.jar`,再用`java -jar`命令启动:
`wget https://alibaba.github.io/arthas/arthas-demo.jar
java -jar arthas-demo.jar`{{execute T1}}
`arthas-demo`是一个很简单的程序,它随机生成整数,再执行因式分解,把结果打印出来。如果生成的随机数是负数,则会打印提示信息。
@@ -0,0 +1,12 @@
在“mbean”中,我们演示了了Arthas的mbean命令。如果有更多的技巧或者使用疑问,欢迎在Issue里提出。
* Issues: https://github.com/alibaba/arthas/issues
* 文档: https://alibaba.github.io/arthas
如果您在使用Arthas,请让我们知道,您的使用对我们非常重要:[查看](https://github.com/alibaba/arthas/issues/111)
欢迎关注公众号,获取Arthas项目的信息,源码分析,案例实践。
![Arthas公众号](/arthas/scenarios/common-resources/assets/qrcode_gongzhonghao.jpg)
@@ -0,0 +1,35 @@
{
"title": "Arthas mbean命令",
"description": "Arthas mbean命令",
"difficulty": "精通者",
"time": "10-20 分钟",
"details": {
"steps": [
{
"title": "启动arthas demo",
"text": "arthas-demo.md"
},
{
"title": "启动arthas-boot",
"text": "arthas-boot.md"
},
{
"title": "mbean命令",
"text": "mbean.md"
}
],
"intro": {
"text": "intro.md"
},
"finish": {
"text": "finish.md"
}
},
"environment": {
"uilayout": "terminal"
},
"backend": {
"imageid": "java",
"environmentsprotocol": "http"
}
}
@@ -0,0 +1,23 @@
![Arthas](https://alibaba.github.io/arthas/_images/arthas.png)
`Arthas` 是Alibaba开源的Java诊断工具,深受开发者喜爱。在线排查问题,无需重启;动态跟踪Java代码;实时监控JVM状态。
`Arthas` 支持JDK 6+,支持Linux/Mac/Windows,采用命令行交互模式,同时提供丰富的 `Tab` 自动补全功能,进一步方便进行问题的定位和诊断。
当你遇到以下类似问题而束手无策时,Arthas可以帮助你解决:
- 这个类从哪个 jar 包加载的?为什么会报各种类相关的 Exception?
- 我改的代码为什么没有执行到?难道是我没 commit?分支搞错了?
- 遇到问题无法在线上 debug,难道只能通过加日志再重新发布吗?
- 线上遇到某个用户的数据处理有问题,但线上同样无法 debug,线下无法重现!
- 是否有一个全局视角来查看系统的运行状况?
- 有什么办法可以监控到JVM的实时运行状态?
- 怎么快速定位应用的热点,生成火焰图?
本教程会以一个简单的应用为例,演示mbean命令。
* Github: https://github.com/alibaba/arthas
* 文档: https://alibaba.github.io/arthas/
@@ -0,0 +1,198 @@
> 方法内部调用路径,并输出方法路径上的每个节点上耗时
`trace` 命令能主动搜索 `class-pattern`/`method-pattern` 对应的方法调用路径,渲染和统计整个调用链路上的所有性能开销和追踪调用链路。
### 参数说明
|参数名称|参数说明|
|---:|:---|
|*class-pattern*|类名表达式匹配|
|*method-pattern*|方法名表达式匹配|
|*condition-express*|条件表达式|
|[E]|开启正则表达式匹配,默认为通配符匹配|
|`[n:]`|命令执行次数|
|`#cost`|方法执行耗时|
这里重点要说明的是观察表达式,观察表达式的构成主要由 ognl 表达式组成,所以你可以这样写`"{params,returnObj}"`,只要是一个合法的 ognl 表达式,都能被正常支持。
观察的维度也比较多,主要体现在参数 `advice` 的数据结构上。`Advice` 参数最主要是封装了通知节点的所有信息。
请参考[表达式核心变量](advice-class.md)中关于该节点的描述。
* 特殊用法请参考:[https://github.com/alibaba/arthas/issues/71](https://github.com/alibaba/arthas/issues/71)
* OGNL表达式官网:[https://commons.apache.org/proper/commons-ognl/language-guide.html](https://commons.apache.org/proper/commons-ognl/language-guide.html)
很多时候我们只想看到某个方法的rt大于某个时间之后的trace结果,现在Arthas可以按照方法执行的耗时来进行过滤了,例如`trace *StringUtils isBlank '#cost>100'`表示当执行时间超过100ms的时候,才会输出trace的结果。
> watch/stack/trace这个三个命令都支持`#cost`
### 注意事项
`trace` 能方便的帮助你定位和发现因 RT 高而导致的性能问题缺陷,但其每次只能跟踪一级方法的调用链路。
参考:[Trace命令的实现原理](https://github.com/alibaba/arthas/issues/597)
3.3.0 版本后,可以使用动态Trace功能,不断增加新的匹配类,参考下面的示例。
### 使用参考
#### trace函数
`trace demo.MathGame run`{{execute T2}}
```bash
$ trace demo.MathGame run
Press Q or Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 28 ms.
`---ts=2019-12-04 00:45:08;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[0.617465ms] demo.MathGame:run()
`---[0.078946ms] demo.MathGame:primeFactors() #24 [throws Exception]
`---ts=2019-12-04 00:45:09;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[1.276874ms] demo.MathGame:run()
`---[0.03752ms] demo.MathGame:primeFactors() #24 [throws Exception]
```
#### trace次数限制
如果方法调用的次数很多,那么可以用`-n`参数指定捕捉结果的次数。比如下面的例子里,捕捉到一次调用就退出命令。
`trace demo.MathGame run -n 1`{{execute T2}}
```bash
$ trace demo.MathGame run -n 1
Press Q or Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 20 ms.
`---ts=2019-12-04 00:45:53;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[0.549379ms] demo.MathGame:run()
+---[0.059839ms] demo.MathGame:primeFactors() #24
`---[0.232887ms] demo.MathGame:print() #25
Command execution times exceed limit: 1, so command will exit. You can set it with -n option.
```
#### 包含jdk的函数
* `--skipJDKMethod <value> ` skip jdk method trace, default value true.
`trace --skipJDKMethod false demo.MathGame run`{{execute T2}}
默认情况下,trace不会包含jdk里的函数调用,如果希望trace jdk里的函数,需要显式设置`--skipJDKMethod false`。
```bash
$ trace --skipJDKMethod false demo.MathGame run
Press Q or Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 60 ms.
`---ts=2019-12-04 00:44:41;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[1.357742ms] demo.MathGame:run()
+---[0.028624ms] java.util.Random:nextInt() #23
+---[0.045534ms] demo.MathGame:primeFactors() #24 [throws Exception]
+---[0.005372ms] java.lang.StringBuilder:<init>() #28
+---[0.012257ms] java.lang.Integer:valueOf() #28
+---[0.234537ms] java.lang.String:format() #28
+---[min=0.004539ms,max=0.005778ms,total=0.010317ms,count=2] java.lang.StringBuilder:append() #28
+---[0.013777ms] java.lang.Exception:getMessage() #28
+---[0.004935ms] java.lang.StringBuilder:toString() #28
`---[0.06941ms] java.io.PrintStream:println() #28
`---ts=2019-12-04 00:44:42;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[3.030432ms] demo.MathGame:run()
+---[0.010473ms] java.util.Random:nextInt() #23
+---[0.023715ms] demo.MathGame:primeFactors() #24 [throws Exception]
+---[0.005198ms] java.lang.StringBuilder:<init>() #28
+---[0.006405ms] java.lang.Integer:valueOf() #28
+---[0.178583ms] java.lang.String:format() #28
+---[min=0.011636ms,max=0.838077ms,total=0.849713ms,count=2] java.lang.StringBuilder:append() #28
+---[0.008747ms] java.lang.Exception:getMessage() #28
+---[0.019768ms] java.lang.StringBuilder:toString() #28
`---[0.076457ms] java.io.PrintStream:println() #28
```
#### 据调用耗时过滤
`trace demo.MathGame run '#cost > 10'`{{execute T2}}
```bash
$ trace demo.MathGame run '#cost > 10'
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 41 ms.
`---ts=2018-12-04 01:12:02;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[12.033735ms] demo.MathGame:run()
+---[0.006783ms] java.util.Random:nextInt()
+---[11.852594ms] demo.MathGame:primeFactors()
`---[0.05447ms] demo.MathGame:print()
```
> 只会展示耗时大于10ms的调用路径,有助于在排查问题的时候,只关注异常情况
- 是不是很眼熟,没错,在 JProfiler 等收费软件中你曾经见识类似的功能,这里你将可以通过命令就能打印出指定调用路径。 友情提醒下,`trace` 在执行的过程中本身是会有一定的性能开销,在统计的报告中并未像 JProfiler 一样预先减去其自身的统计开销。所以这统计出来有些许的不准,渲染路径上调用的类、方法越多,性能偏差越大。但还是能让你看清一些事情的。
- [12.033735ms] 的含义,`12.033735` 的含义是:当前节点在当前步骤的耗时,单位为毫秒
- [0,0,0ms,11]xxx:yyy() [throws Exception],对该方法中相同的方法调用进行了合并,`0,0,0ms,11` 表示方法调用耗时,`min,max,total,count`;`throws Exception` 表明该方法调用中存在异常返回
- 这里存在一个统计不准确的问题,就是所有方法耗时加起来可能会小于该监测方法的总耗时,这个是由于 Arthas 本身的逻辑会有一定的耗时
#### trace多个类或者多个函数
trace命令只会trace匹配到的函数里的子调用,并不会向下trace多层。因为trace是代价比较贵的,多层trace可能会导致最终要trace的类和函数非常多。
可以用正则表匹配路径上的多个类和函数,一定程度上达到多层trace的效果。
```bash
trace -E com.test.ClassA|org.test.ClassB method1|method2|method3
```
### 动态trace
3.3.0 版本后支持。
打开终端1,trace `run`函数,可以看到打印出 `listenerId: 1`:
`trace demo.MathGame run`{{execute T2}}
```bash
[arthas@59161]$ trace demo.MathGame run
Press Q or Ctrl+C to abort.
Affect(class count: 1 , method count: 1) cost in 112 ms, listenerId: 1
`---ts=2020-07-09 16:48:11;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[1.389634ms] demo.MathGame:run()
`---[0.123934ms] demo.MathGame:primeFactors() #24 [throws Exception]
`---ts=2020-07-09 16:48:12;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[3.716391ms] demo.MathGame:run()
+---[3.182813ms] demo.MathGame:primeFactors() #24
`---[0.167786ms] demo.MathGame:print() #25
```
现在想要深入子函数`primeFactors`,可以打开一个新终端2,使用`telnet localhost 3658`连接上arthas,再trace `primeFactors`时,指定`listenerId`。
`trace demo.MathGame primeFactors --listenerId 1`{{execute T2}}
```bash
[arthas@59161]$ trace demo.MathGame primeFactors --listenerId 1
Press Q or Ctrl+C to abort.
Affect(class count: 1 , method count: 1) cost in 34 ms, listenerId: 1
```
这时终端2打印的结果,说明已经增强了一个函数:`Affect(class count: 1 , method count: 1)`,但不再打印更多的结果。
再查看终端1,可以发现trace的结果增加了一层,打印了`primeFactors`函数里的内容:
```bash
`---ts=2020-07-09 16:49:29;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[0.492551ms] demo.MathGame:run()
`---[0.113929ms] demo.MathGame:primeFactors() #24 [throws Exception]
`---[0.061462ms] demo.MathGame:primeFactors()
`---[0.001018ms] throw:java.lang.IllegalArgumentException() #46
`---ts=2020-07-09 16:49:30;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[0.409446ms] demo.MathGame:run()
+---[0.232606ms] demo.MathGame:primeFactors() #24
| `---[0.1294ms] demo.MathGame:primeFactors()
`---[0.084025ms] demo.MathGame:print() #25
```
通过指定`listenerId`的方式动态trace,可以不断深入。另外 `watch`/`tt`/`monitor`等命令也支持类似的功能。
@@ -0,0 +1,16 @@
In the new `Terminal 2`, download `arthas-boot.jar` and start with the `java -jar` command:
`wget https://alibaba.github.io/arthas/arthas-boot.jar
java -jar arthas-boot.jar`{{execute T2}}
`arthas-boot` is the launcher for `Arthas`. It lists all the Java processes, and the user can select the target process to be diagnosed.
Select the first process, type `1`{{execute T2}} ,then type `Enter`:
After the Attach is successful, Arthas LOGO is printed. Enter `help`{{execute T2}} for more help.
![Arthas Boot](/arthas/scenarios/common-resources/assets/arthas-boot.png)
@@ -0,0 +1,11 @@
Download `arthas-demo.jar` and start with the `java -jar` command:
`wget https://alibaba.github.io/arthas/arthas-demo.jar
java -jar arthas-demo.jar`{{execute T1}}
`arthas-demo` is a very simple program that randomly generates integers, performs factorization, and prints the results.
If the generated random number is negative, a error message will be printed.
@@ -0,0 +1,8 @@
The `mbean Tutorial` demonstrates the usage of mbean. If you have more tips or questions, please feel free to ask in Issue.
* Issues: https://github.com/alibaba/arthas/issues
* Documentation: https://alibaba.github.io/arthas
If you are using Arthas, please let us know. Your use is very important to us: [View](https://github.com/alibaba/arthas/issues/111)
@@ -0,0 +1,35 @@
{
"title": "Arthas mbean Command",
"description": "Arthas mbean Command",
"difficulty": "master",
"time": "10-20 minutes",
"details": {
"steps": [
{
"title": "Arthas demo",
"text": "arthas-demo.md"
},
{
"title": "Start arthas-boot",
"text": "arthas-boot.md"
},
{
"title": "mbean Command",
"text": "mbean.md"
}
],
"intro": {
"text": "intro.md"
},
"finish": {
"text": "finish.md"
}
},
"environment": {
"uilayout": "terminal"
},
"backend": {
"imageid": "java",
"environmentsprotocol": "http"
}
}
@@ -0,0 +1,40 @@
![Arthas](https://alibaba.github.io/arthas/_images/arthas.png)
`Arthas` is a Java diagnostic tool open-sourced by Alibaba middleware team. Arthas helps developers in trouble-shooting issues in production environment for Java based applications without modifying code or restarting servers.
`Arthas` supports JDK 6+, supports Linux/Mac/Windows.
## Background
Oftentimes the production system network is inaccessible from local development environment. If issues are encountered in production systems, it is impossible to use IDE to debug the application remotely. What’s even worse, debugging in production environment is unacceptable, as it will suspend all the threads, leading to services downtime.
Developers could always try to reproduce the same issue on the test/staging environment. However, this is tricky as some issues cannot be reproduced easily in a different environment, or even disappear once restarted.
And if you’re thinking of adding some logs to your code to help trouble-shoot the issue, you will have to go through the following lifecycle: test, staging, and then to production. Time is money! This approach is inefficient! Worse still, the issue may not be fixed since it might be irreproducible once the JVM is restarted, as described above.
Arthas is built to solve these issues. A developer can troubleshoot production issues on the fly. No JVM restart, no additional code changes. Arthas works as an observer, that is, it will never suspend your running threads.
## Key features
- Check whether a class is loaded? Or where the class is loaded from? (Useful for trouble-shooting jar file conflicts)
- Decompile a class to ensure the code is running as expected.
- Check classloader statistics, e.g. the number of classloaders, the number of classes loaded per classloader, the classloader hierarchy, possible classloader leaks, etc.
- Check the method invocation details, e.g. method parameter, returned values, exceptions and etc.
- Check the stack trace of specified method invocation. This is useful when a developer wants to know the caller of the method.
- Trace the method invocation to find slow sub-invocations.
- Monitor method invocation statistics, e.g. QPS (Query Per Second), RT (Return Time), success rate and etc.
- Monitor system metrics, thread states and CPU usage, GC statistics and etc.
- Supports command line interactive mode, with auto-complete feature enabled.
- Supports telnet and WebSocket, which enables both local and remote diagnostics with command line and browsers.
- Supports profiler/Flame Graph
- Supports JDK 6+
- Supports Linux/Mac/Windows
This tutorial takes a simple application as an example to demonstrate the the usage of mbean.
* Github: https://github.com/alibaba/arthas
* Docs: https://alibaba.github.io/arthas/
@@ -0,0 +1,194 @@
> Trace method calling path, and output the time cost for each node in the path.
`trace` can track the calling path specified by `class-pattern` / `method-pattern`, and calculate the time cost on the whole path.
### Parameters
|Name|Specification|
|---:|:---|
|*class-pattern*|pattern for the class name|
|*method-pattern*|pattern for the method name|
|*condition-express*|condition expression|
|`[E]`|enable regex match, the default behavior is wildcards match|
|`[n:]`|execution times|
|#cost|time cost|
There's one thing worthy noting here is observation expression. The observation expression supports OGNL grammar, for example, you can come up a expression like this `"{params,returnObj}"`. All OGNL expressions are supported as long as they are legal to the grammar.
Thanks for `advice`'s data structure, it is possible to observe from varieties of different angles. Inside `advice` parameter, all necessary information for notification can be found.
Pls. refer to [core parameters in expression](advice-class.md) for more details.
* Pls. also refer to [https://github.com/alibaba/arthas/issues/71](https://github.com/alibaba/arthas/issues/71) for more advanced usage
* OGNL official site: [https://commons.apache.org/proper/commons-ognl/language-guide.html](https://commons.apache.org/proper/commons-ognl/language-guide.html)
Many times what we are interested is the exact trace result when the method call takes time over one particular period. It is possible to achieve this in Arthas, for example: `trace *StringUtils isBlank '#cost>100'` means trace result will only be output when the executing time exceeds 100ms.
> `watch`/`stack`/`trace`, these three commands all support `#cost`.
### Notice
`trace` is handy to help discovering and locating the performance flaws in your system, but pls. note Arthas can only trace the first level method call each time.
After version 3.3.0, you can use the Dynamic Trace feature to add new matching classes/methods, see the following example.
### Usage
#### Trace method
`trace demo.MathGame run`{{execute T2}}
```bash
$ trace demo.MathGame run
Press Q or Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 28 ms.
`---ts=2019-12-04 00:45:08;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[0.617465ms] demo.MathGame:run()
`---[0.078946ms] demo.MathGame:primeFactors() #24 [throws Exception]
`---ts=2019-12-04 00:45:09;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[1.276874ms] demo.MathGame:run()
`---[0.03752ms] demo.MathGame:primeFactors() #24 [throws Exception]
```
#### Trace times limit
If the method invoked many times, use `-n` options to specify trace times. For example, the command will exit when received a trace result.
`trace demo.MathGame run -n 1`{{execute T2}}
```bash
$ trace demo.MathGame run -n 1
Press Q or Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 20 ms.
`---ts=2019-12-04 00:45:53;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[0.549379ms] demo.MathGame:run()
+---[0.059839ms] demo.MathGame:primeFactors() #24
`---[0.232887ms] demo.MathGame:print() #25
Command execution times exceed limit: 1, so command will exit. You can set it with -n option.
```
#### Include jdk method
* `--skipJDKMethod <value> ` skip jdk method trace, default value true.
`trace --skipJDKMethod false demo.MathGame run`{{execute T2}}
```bash
$ trace --skipJDKMethod false demo.MathGame run
Press Q or Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 60 ms.
`---ts=2019-12-04 00:44:41;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[1.357742ms] demo.MathGame:run()
+---[0.028624ms] java.util.Random:nextInt() #23
+---[0.045534ms] demo.MathGame:primeFactors() #24 [throws Exception]
+---[0.005372ms] java.lang.StringBuilder:<init>() #28
+---[0.012257ms] java.lang.Integer:valueOf() #28
+---[0.234537ms] java.lang.String:format() #28
+---[min=0.004539ms,max=0.005778ms,total=0.010317ms,count=2] java.lang.StringBuilder:append() #28
+---[0.013777ms] java.lang.Exception:getMessage() #28
+---[0.004935ms] java.lang.StringBuilder:toString() #28
`---[0.06941ms] java.io.PrintStream:println() #28
`---ts=2019-12-04 00:44:42;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[3.030432ms] demo.MathGame:run()
+---[0.010473ms] java.util.Random:nextInt() #23
+---[0.023715ms] demo.MathGame:primeFactors() #24 [throws Exception]
+---[0.005198ms] java.lang.StringBuilder:<init>() #28
+---[0.006405ms] java.lang.Integer:valueOf() #28
+---[0.178583ms] java.lang.String:format() #28
+---[min=0.011636ms,max=0.838077ms,total=0.849713ms,count=2] java.lang.StringBuilder:append() #28
+---[0.008747ms] java.lang.Exception:getMessage() #28
+---[0.019768ms] java.lang.StringBuilder:toString() #28
`---[0.076457ms] java.io.PrintStream:println() #28
```
#### Filtering by cost
`trace demo.MathGame run '#cost > 10'`{{execute T2}}
```bash
$ trace demo.MathGame run '#cost > 10'
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 41 ms.
`---ts=2018-12-04 01:12:02;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[12.033735ms] demo.MathGame:run()
+---[0.006783ms] java.util.Random:nextInt()
+---[11.852594ms] demo.MathGame:primeFactors()
`---[0.05447ms] demo.MathGame:print()
```
> Only the call path which's time cost is higher than `10ms` will be shown. This feature is handy to focus on what's needed to focus when troubleshoot.
* Here Arthas provides the similar functionality JProfile and other commercial software provide. Compared to these professional softwares, Arthas doesn't deduce the time cost `trace` itself takes, therefore it is not as accurate as these softwares offer. More classes and methods on the calling path, more inaccurate `trace` output is, but it is still helpful for diagnostics where the bottleneck is.
* "[12.033735ms]" means the method on the node takes `12.033735` ms.
* "[min=0.005428ms,max=0.094064ms,total=0.105228ms,count=3] demo:call()" means aggregating all same method calls into one single line. The minimum time cost is `0.005428` ms, the maximum time cost is `0.094064` ms, and the total time cost for all method calls (`3` times in total) to "demo:call()" is `0.105228ms`. If "throws Exception" appears in this line, it means some exceptions have been thrown from this method calls.
* The total time cost may not equal to the sum of the time costs each sub method call takes, this is because Arthas instrumented code takes time too.
#### Trace multiple classes or multiple methods
The trace command will only trace the subcalls in the method to the trace, and will not trace down multiple layers. Because traces are expensive, multi-layer traces can lead to a lot of classes and methods that ultimately have to be traced.
You can use the regular expression to match multiple classes and methods on the path to achieve a multi-layer trace effect to some extent.
```bash
Trace -E com.test.ClassA|org.test.ClassB method1|method2|method3
```
#### Dynamic trace
> Supported since version 3.3.0.
Open terminal 1, trace the `run` method, and you can see the printout `listenerId: 1` .
`trace demo.MathGame run`{{execute T2}}
```bash
[arthas@59161]$ trace demo.MathGame run
Press Q or Ctrl+C to abort.
Affect(class count: 1 , method count: 1) cost in 112 ms, listenerId: 1
`---ts=2020-07-09 16:48:11;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[1.389634ms] demo.MathGame:run()
`---[0.123934ms] demo.MathGame:primeFactors() #24 [throws Exception]
`---ts=2020-07-09 16:48:12;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[3.716391ms] demo.MathGame:run()
+---[3.182813ms] demo.MathGame:primeFactors() #24
`---[0.167786ms] demo.MathGame:print() #25
```
Now to drill down into the sub method `primeFactors`, you can open a new terminal 2 and use the `telnet localhost 3658` connects to the arthas, then trace `primeFactors` with the specify `listenerId`.
`trace demo.MathGame primeFactors --listenerId 1`{{execute T2}}
```bash
[arthas@59161]$ trace demo.MathGame primeFactors --listenerId 1
Press Q or Ctrl+C to abort.
Affect(class count: 1 , method count: 1) cost in 34 ms, listenerId: 1
```
At Terminal 2 prints the results, indicating that a method has been enhanced: `Affect(class count: 1 , method count: 1)`, but no more results are printed.
At terminal 1, you can see that the trace result has increased by one layer:
```bash
`---ts=2020-07-09 16:49:29;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[0.492551ms] demo.MathGame:run()
`---[0.113929ms] demo.MathGame:primeFactors() #24 [throws Exception]
`---[0.061462ms] demo.MathGame:primeFactors()
`---[0.001018ms] throw:java.lang.IllegalArgumentException() #46
`---ts=2020-07-09 16:49:30;thread_name=main;id=1;is_daemon=false;priority=5;TCCL=sun.misc.Launcher$AppClassLoader@3d4eac69
`---[0.409446ms] demo.MathGame:run()
+---[0.232606ms] demo.MathGame:primeFactors() #24
| `---[0.1294ms] demo.MathGame:primeFactors()
`---[0.084025ms] demo.MathGame:print() #25
```
Dynamic trace by specifying `listenerId`, you can go deeper and deeper. In addition, commands such as `watch`/`tt`/`monitor` also support similar functionality.
@@ -0,0 +1,16 @@
在新的`Terminal 2`里,下载`arthas-boot.jar`,再用`java -jar`命令启动:
`wget https://alibaba.github.io/arthas/arthas-boot.jar
java -jar arthas-boot.jar`{{execute T2}}
`arthas-boot`是`Arthas`的启动程序,它启动后,会列出所有的Java进程,用户可以选择需要诊断的目标进程。
选择第一个进程,输入 `1`{{execute T2}} ,再`Enter/回车`:
Attach成功之后,会打印Arthas LOGO。输入 `help`{{execute T2}} 可以获取到更多的帮助信息。
![Arthas Boot](/arthas/scenarios/common-resources/assets/arthas-boot.png)
@@ -0,0 +1,10 @@
下载`arthas-demo.jar`,再用`java -jar`命令启动:
`wget https://alibaba.github.io/arthas/arthas-demo.jar
java -jar arthas-demo.jar`{{execute T1}}
`arthas-demo`是一个很简单的程序,它随机生成整数,再执行因式分解,把结果打印出来。如果生成的随机数是负数,则会打印提示信息。
@@ -0,0 +1,12 @@
在“tt”中,我们演示了了Arthas的tt命令。如果有更多的技巧或者使用疑问,欢迎在Issue里提出。
* Issues: https://github.com/alibaba/arthas/issues
* 文档: https://alibaba.github.io/arthas
如果您在使用Arthas,请让我们知道,您的使用对我们非常重要:[查看](https://github.com/alibaba/arthas/issues/111)
欢迎关注公众号,获取Arthas项目的信息,源码分析,案例实践。
![Arthas公众号](/arthas/scenarios/common-resources/assets/qrcode_gongzhonghao.jpg)
@@ -0,0 +1,35 @@
{
"title": "Arthas tt命令",
"description": "Arthas tt命令",
"difficulty": "精通者",
"time": "10-20 分钟",
"details": {
"steps": [
{
"title": "启动arthas demo",
"text": "arthas-demo.md"
},
{
"title": "启动arthas-boot",
"text": "arthas-boot.md"
},
{
"title": "tt命令",
"text": "tt.md"
}
],
"intro": {
"text": "intro.md"
},
"finish": {
"text": "finish.md"
}
},
"environment": {
"uilayout": "terminal"
},
"backend": {
"imageid": "java",
"environmentsprotocol": "http"
}
}
+23
View File
@@ -0,0 +1,23 @@
![Arthas](https://alibaba.github.io/arthas/_images/arthas.png)
`Arthas` 是Alibaba开源的Java诊断工具,深受开发者喜爱。在线排查问题,无需重启;动态跟踪Java代码;实时监控JVM状态。
`Arthas` 支持JDK 6+,支持Linux/Mac/Windows,采用命令行交互模式,同时提供丰富的 `Tab` 自动补全功能,进一步方便进行问题的定位和诊断。
当你遇到以下类似问题而束手无策时,Arthas可以帮助你解决:
- 这个类从哪个 jar 包加载的?为什么会报各种类相关的 Exception?
- 我改的代码为什么没有执行到?难道是我没 commit?分支搞错了?
- 遇到问题无法在线上 debug,难道只能通过加日志再重新发布吗?
- 线上遇到某个用户的数据处理有问题,但线上同样无法 debug,线下无法重现!
- 是否有一个全局视角来查看系统的运行状况?
- 有什么办法可以监控到JVM的实时运行状态?
- 怎么快速定位应用的热点,生成火焰图?
本教程会以一个简单的应用为例,演示tt命令。
* Github: https://github.com/alibaba/arthas
* 文档: https://alibaba.github.io/arthas/
+189
View File
@@ -0,0 +1,189 @@
> 方法执行数据的时空隧道,记录下指定方法每次调用的入参和返回信息,并能对这些不同的时间下调用进行观测
`watch` 虽然很方便和灵活,但需要提前想清楚观察表达式的拼写,这对排查问题而言要求太高,因为很多时候我们并不清楚问题出自于何方,只能靠蛛丝马迹进行猜测。
这个时候如果能记录下当时方法调用的所有入参和返回值、抛出的异常会对整个问题的思考与判断非常有帮助。
于是乎,TimeTunnel 命令就诞生了。
### 使用参考
#### 记录调用
对于一个最基本的使用来说,就是记录下当前方法的每次调用环境现场。
`tt -t demo.MathGame primeFactors`{{execute T2}}
```bash
$ tt -t demo.MathGame primeFactors
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 66 ms.
INDEX TIMESTAMP COST(ms) IS-RET IS-EXP OBJECT CLASS METHOD
-------------------------------------------------------------------------------------------------------------------------------------
1000 2018-12-04 11:15:38 1.096236 false true 0x4b67cf4d MathGame primeFactors
1001 2018-12-04 11:15:39 0.191848 false true 0x4b67cf4d MathGame primeFactors
1002 2018-12-04 11:15:40 0.069523 false true 0x4b67cf4d MathGame primeFactors
1003 2018-12-04 11:15:41 0.186073 false true 0x4b67cf4d MathGame primeFactors
1004 2018-12-04 11:15:42 17.76437 true false 0x4b67cf4d MathGame primeFactors
```
- 命令参数解析
- `-t`
tt 命令有很多个主参数,`-t` 就是其中之一。这个参数的表明希望记录下类 `*Test` 的 `print` 方法的每次执行情况。
- `-n 3`
当你执行一个调用量不高的方法时可能你还能有足够的时间用 `CTRL+C` 中断 tt 命令记录的过程,但如果遇到调用量非常大的方法,瞬间就能将你的 JVM 内存撑爆。
此时你可以通过 `-n` 参数指定你需要记录的次数,当达到记录次数时 Arthas 会主动中断tt命令的记录过程,避免人工操作无法停止的情况。
- 表格字段说明
|表格字段|字段解释|
|---|---|
|INDEX|时间片段记录编号,每一个编号代表着一次调用,后续tt还有很多命令都是基于此编号指定记录操作,非常重要。|
|TIMESTAMP|方法执行的本机时间,记录了这个时间片段所发生的本机时间|
|COST(ms)|方法执行的耗时|
|IS-RET|方法是否以正常返回的形式结束|
|IS-EXP|方法是否以抛异常的形式结束|
|OBJECT|执行对象的`hashCode()`,注意,曾经有人误认为是对象在JVM中的内存地址,但很遗憾他不是。但他能帮助你简单的标记当前执行方法的类实体|
|CLASS|执行的类名|
|METHOD|执行的方法名|
- 条件表达式
不知道大家是否有在使用过程中遇到以下困惑
* Arthas 似乎很难区分出重载的方法
* 我只需要观察特定参数,但是 tt 却全部都给我记录了下来
条件表达式也是用 `OGNL` 来编写,核心的判断对象依然是 `Advice` 对象。除了 `tt` 命令之外,`watch`、`trace`、`stack` 命令也都支持条件表达式。
- 解决方法重载
`tt -t *Test print params.length==1`
通过制定参数个数的形式解决不同的方法签名,如果参数个数一样,你还可以这样写
`tt -t *Test print 'params[1] instanceof Integer'`
- 解决指定参数
`tt -t *Test print params[0].mobile=="13989838402"`
- 构成条件表达式的 `Advice` 对象
前边看到了很多条件表达式中,都使用了 `params[0]`,有关这个变量的介绍,请参考[表达式核心变量](https://alibaba.github.io/arthas/advice-class.html)
#### 检索调用记录
当你用 `tt` 记录了一大片的时间片段之后,你希望能从中筛选出自己需要的时间片段,这个时候你就需要对现有记录进行检索。
假设我们有这些记录
`tt -l`{{execute T2}}
```bash
$ tt -l
INDEX TIMESTAMP COST(ms) IS-RET IS-EXP OBJECT CLASS METHOD
-------------------------------------------------------------------------------------------------------------------------------------
1000 2018-12-04 11:15:38 1.096236 false true 0x4b67cf4d MathGame primeFactors
1001 2018-12-04 11:15:39 0.191848 false true 0x4b67cf4d MathGame primeFactors
1002 2018-12-04 11:15:40 0.069523 false true 0x4b67cf4d MathGame primeFactors
1003 2018-12-04 11:15:41 0.186073 false true 0x4b67cf4d MathGame primeFactors
1004 2018-12-04 11:15:42 17.76437 true false 0x4b67cf4d MathGame primeFactors
9
1005 2018-12-04 11:15:43 0.4776 false true 0x4b67cf4d MathGame primeFactors
Affect(row-cnt:6) cost in 4 ms.
```
我需要筛选出 `primeFactors` 方法的调用信息
`tt -s 'method.name=="primeFactors"'`{{execute T2}}
```bash
$ tt -s 'method.name=="primeFactors"'
INDEX TIMESTAMP COST(ms) IS-RET IS-EXP OBJECT CLASS METHOD
-------------------------------------------------------------------------------------------------------------------------------------
1000 2018-12-04 11:15:38 1.096236 false true 0x4b67cf4d MathGame primeFactors
1001 2018-12-04 11:15:39 0.191848 false true 0x4b67cf4d MathGame primeFactors
1002 2018-12-04 11:15:40 0.069523 false true 0x4b67cf4d MathGame primeFactors
1003 2018-12-04 11:15:41 0.186073 false true 0x4b67cf4d MathGame primeFactors
1004 2018-12-04 11:15:42 17.76437 true false 0x4b67cf4d MathGame primeFactors
9
1005 2018-12-04 11:15:43 0.4776 false true 0x4b67cf4d MathGame primeFactors
Affect(row-cnt:6) cost in 607 ms.
```
你需要一个 `-s` 参数。<span style="color:red;">同样的,搜索表达式的核心对象依旧是 `Advice` 对象。</span>
#### 查看调用信息
对于具体一个时间片的信息而言,你可以通过 `-i` 参数后边跟着对应的 `INDEX` 编号查看到他的详细信息。
`tt -i 1003`{{execute T2}}
```bash
$ tt -i 1003
INDEX 1003
GMT-CREATE 2018-12-04 11:15:41
COST(ms) 0.186073
OBJECT 0x4b67cf4d
CLASS demo.MathGame
METHOD primeFactors
IS-RETURN false
IS-EXCEPTION true
PARAMETERS[0] @Integer[-564322413]
THROW-EXCEPTION java.lang.IllegalArgumentException: number is: -564322413, need >= 2
at demo.MathGame.primeFactors(MathGame.java:46)
at demo.MathGame.run(MathGame.java:24)
at demo.MathGame.main(MathGame.java:16)
Affect(row-cnt:1) cost in 11 ms.
```
#### 重做一次调用
当你稍稍做了一些调整之后,你可能需要前端系统重新触发一次你的调用,此时得求爷爷告奶奶的需要前端配合联调的同学再次发起一次调用。而有些场景下,这个调用不是这么好触发的。
`tt` 命令由于保存了当时调用的所有现场信息,所以我们可以自己主动对一个 `INDEX` 编号的时间片自主发起一次调用,从而解放你的沟通成本。此时你需要 `-p` 参数。通过 `--replay-times` 指定
调用次数,通过 `--replay-interval` 指定多次调用间隔(单位ms, 默认1000ms)
`tt -i 1004 -p`{{execute T2}}
```bash
$ tt -i 1004 -p
RE-INDEX 1004
GMT-REPLAY 2018-12-04 11:26:00
OBJECT 0x4b67cf4d
CLASS demo.MathGame
METHOD primeFactors
PARAMETERS[0] @Integer[946738738]
IS-RETURN true
IS-EXCEPTION false
COST(ms) 0.186073
RETURN-OBJ @ArrayList[
@Integer[2],
@Integer[11],
@Integer[17],
@Integer[2531387],
]
Time fragment[1004] successfully replayed.
Affect(row-cnt:1) cost in 14 ms.
```
你会发现结果虽然一样,但调用的路径发生了变化,有原来的程序发起变成了 Arthas 自己的内部线程发起的调用了。
- 需要强调的点
1. **ThreadLocal 信息丢失**
很多框架偷偷的将一些环境变量信息塞到了发起调用线程的 ThreadLocal 中,由于调用线程发生了变化,这些 ThreadLocal 线程信息无法通过 Arthas 保存,所以这些信息将会丢失。
一些常见的 CASE 比如:鹰眼的 TraceId 等。
2. **引用的对象**
需要强调的是,`tt` 命令是将当前环境的对象引用保存起来,但仅仅也只能保存一个引用而已。如果方法内部对入参进行了变更,或者返回的对象经过了后续的处理,那么在 `tt` 查看的时候将无法看到当时最准确的值。这也是为什么 `watch` 命令存在的意义。
@@ -0,0 +1,16 @@
In the new `Terminal 2`, download `arthas-boot.jar` and start with the `java -jar` command:
`wget https://alibaba.github.io/arthas/arthas-boot.jar
java -jar arthas-boot.jar`{{execute T2}}
`arthas-boot` is the launcher for `Arthas`. It lists all the Java processes, and the user can select the target process to be diagnosed.
Select the first process, type `1`{{execute T2}} ,then type `Enter`:
After the Attach is successful, Arthas LOGO is printed. Enter `help`{{execute T2}} for more help.
![Arthas Boot](/arthas/scenarios/common-resources/assets/arthas-boot.png)
@@ -0,0 +1,11 @@
Download `arthas-demo.jar` and start with the `java -jar` command:
`wget https://alibaba.github.io/arthas/arthas-demo.jar
java -jar arthas-demo.jar`{{execute T1}}
`arthas-demo` is a very simple program that randomly generates integers, performs factorization, and prints the results.
If the generated random number is negative, a error message will be printed.
@@ -0,0 +1,8 @@
The `tt Tutorial` demonstrates the usage of tt. If you have more tips or questions, please feel free to ask in Issue.
* Issues: https://github.com/alibaba/arthas/issues
* Documentation: https://alibaba.github.io/arthas
If you are using Arthas, please let us know. Your use is very important to us: [View](https://github.com/alibaba/arthas/issues/111)
@@ -0,0 +1,35 @@
{
"title": "Arthas tt Command",
"description": "Arthas tt Command",
"difficulty": "master",
"time": "10-20 minutes",
"details": {
"steps": [
{
"title": "Arthas demo",
"text": "arthas-demo.md"
},
{
"title": "Start arthas-boot",
"text": "arthas-boot.md"
},
{
"title": "tt Command",
"text": "tt.md"
}
],
"intro": {
"text": "intro.md"
},
"finish": {
"text": "finish.md"
}
},
"environment": {
"uilayout": "terminal"
},
"backend": {
"imageid": "java",
"environmentsprotocol": "http"
}
}
+40
View File
@@ -0,0 +1,40 @@
![Arthas](https://alibaba.github.io/arthas/_images/arthas.png)
`Arthas` is a Java diagnostic tool open-sourced by Alibaba middleware team. Arthas helps developers in trouble-shooting issues in production environment for Java based applications without modifying code or restarting servers.
`Arthas` supports JDK 6+, supports Linux/Mac/Windows.
## Background
Oftentimes the production system network is inaccessible from local development environment. If issues are encountered in production systems, it is impossible to use IDE to debug the application remotely. What’s even worse, debugging in production environment is unacceptable, as it will suspend all the threads, leading to services downtime.
Developers could always try to reproduce the same issue on the test/staging environment. However, this is tricky as some issues cannot be reproduced easily in a different environment, or even disappear once restarted.
And if you’re thinking of adding some logs to your code to help trouble-shoot the issue, you will have to go through the following lifecycle: test, staging, and then to production. Time is money! This approach is inefficient! Worse still, the issue may not be fixed since it might be irreproducible once the JVM is restarted, as described above.
Arthas is built to solve these issues. A developer can troubleshoot production issues on the fly. No JVM restart, no additional code changes. Arthas works as an observer, that is, it will never suspend your running threads.
## Key features
- Check whether a class is loaded? Or where the class is loaded from? (Useful for trouble-shooting jar file conflicts)
- Decompile a class to ensure the code is running as expected.
- Check classloader statistics, e.g. the number of classloaders, the number of classes loaded per classloader, the classloader hierarchy, possible classloader leaks, etc.
- Check the method invocation details, e.g. method parameter, returned values, exceptions and etc.
- Check the stack trace of specified method invocation. This is useful when a developer wants to know the caller of the method.
- Trace the method invocation to find slow sub-invocations.
- Monitor method invocation statistics, e.g. QPS (Query Per Second), RT (Return Time), success rate and etc.
- Monitor system metrics, thread states and CPU usage, GC statistics and etc.
- Supports command line interactive mode, with auto-complete feature enabled.
- Supports telnet and WebSocket, which enables both local and remote diagnostics with command line and browsers.
- Supports profiler/Flame Graph
- Supports JDK 6+
- Supports Linux/Mac/Windows
This tutorial takes a simple application as an example to demonstrate the the usage of tt.
* Github: https://github.com/alibaba/arthas
* Docs: https://alibaba.github.io/arthas/
+163
View File
@@ -0,0 +1,163 @@
Check the `parameters`, `return values` and `exceptions` of the methods at different times.
`watch` is a powerful command but due to its feasibility and complexity, it's quite hard to locate the issue effectively.
In such difficulties, `tt` comes into play.
With the help of `tt` (*TimeTunnel*), you can check the contexts of the methods at different times in execution history.
### Usage
#### Record method calls
`tt -t demo.MathGame primeFactors`{{execute T2}}
```bash
$ tt -t demo.MathGame primeFactors
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 66 ms.
INDEX TIMESTAMP COST(ms) IS-RET IS-EXP OBJECT CLASS METHOD
-------------------------------------------------------------------------------------------------------------------------------------
1000 2018-12-04 11:15:38 1.096236 false true 0x4b67cf4d MathGame primeFactors
1001 2018-12-04 11:15:39 0.191848 false true 0x4b67cf4d MathGame primeFactors
1002 2018-12-04 11:15:40 0.069523 false true 0x4b67cf4d MathGame primeFactors
1003 2018-12-04 11:15:41 0.186073 false true 0x4b67cf4d MathGame primeFactors
1004 2018-12-04 11:15:42 17.76437 true false 0x4b67cf4d MathGame primeFactors
```
* `-t`
record the calling context of the method `demo.MathGame primeFactors`
* `-n 3`
limit the number of the records (avoid overflow for too many records; with `-n` option, Arthas can automatically stop recording once the records reach the specified limit)
* Property
|Name|Specification|
|---|---|
|INDEX|the index for each call based on time|
|TIMESTAMP|time to invoke the method|
|COST(ms)|time cost of the method call|
|IS-RET|whether method exits with normal return|
|IS-EXP|whether method failed with exceptions|
|OBJECT|`hashCode()` of the object invoking the method|
|CLASS|class name of the object invoking the method|
|METHOD|method being invoked|
* Condition expression
Tips:
1. `tt -t *Test print params.length==1` with different amounts of parameters;
2. `tt -t *Test print 'params[1] instanceof Integer'` with different types of parameters;
3. `tt -t *Test print params[0].mobile=="13989838402"` with specified parameter.
Advanced:
* [Critical fields in expression](https://alibaba.github.io/arthas/en/advice-class.html)
* [Special usage](https://github.com/alibaba/arthas/issues/71)
* [OGNL official guide](https://commons.apache.org/proper/commons-ognl/language-guide.html)
#### List all records
`tt -l`{{execute T2}}
```bash
$ tt -l
INDEX TIMESTAMP COST(ms) IS-RET IS-EXP OBJECT CLASS METHOD
-------------------------------------------------------------------------------------------------------------------------------------
1000 2018-12-04 11:15:38 1.096236 false true 0x4b67cf4d MathGame primeFactors
1001 2018-12-04 11:15:39 0.191848 false true 0x4b67cf4d MathGame primeFactors
1002 2018-12-04 11:15:40 0.069523 false true 0x4b67cf4d MathGame primeFactors
1003 2018-12-04 11:15:41 0.186073 false true 0x4b67cf4d MathGame primeFactors
1004 2018-12-04 11:15:42 17.76437 true false 0x4b67cf4d MathGame primeFactors
9
1005 2018-12-04 11:15:43 0.4776 false true 0x4b67cf4d MathGame primeFactors
Affect(row-cnt:6) cost in 4 ms.
```
#### Searching for records
`tt -s 'method.name=="primeFactors"'`{{execute T2}}
```bash
$ tt -s 'method.name=="primeFactors"'
INDEX TIMESTAMP COST(ms) IS-RET IS-EXP OBJECT CLASS METHOD
-------------------------------------------------------------------------------------------------------------------------------------
1000 2018-12-04 11:15:38 1.096236 false true 0x4b67cf4d MathGame primeFactors
1001 2018-12-04 11:15:39 0.191848 false true 0x4b67cf4d MathGame primeFactors
1002 2018-12-04 11:15:40 0.069523 false true 0x4b67cf4d MathGame primeFactors
1003 2018-12-04 11:15:41 0.186073 false true 0x4b67cf4d MathGame primeFactors
1004 2018-12-04 11:15:42 17.76437 true false 0x4b67cf4d MathGame primeFactors
9
1005 2018-12-04 11:15:43 0.4776 false true 0x4b67cf4d MathGame primeFactors
Affect(row-cnt:6) cost in 607 ms.
```
Advanced:
* [Critical fields in expression](advice-class.md)
#### Check context of the call
`tt -i 1003`{{execute T2}}
Using `tt -i <index>` to check a specific calling details.
```bash
$ tt -i 1003
INDEX 1003
GMT-CREATE 2018-12-04 11:15:41
COST(ms) 0.186073
OBJECT 0x4b67cf4d
CLASS demo.MathGame
METHOD primeFactors
IS-RETURN false
IS-EXCEPTION true
PARAMETERS[0] @Integer[-564322413]
THROW-EXCEPTION java.lang.IllegalArgumentException: number is: -564322413, need >= 2
at demo.MathGame.primeFactors(MathGame.java:46)
at demo.MathGame.run(MathGame.java:24)
at demo.MathGame.main(MathGame.java:16)
Affect(row-cnt:1) cost in 11 ms.
```
### Replay record
Since Arthas stores the context of the call, you can even *replay* the method calling afterwards with extra option `-p` to replay the issue for advanced troubleshooting, option `--replay-times`
define the replay execution times, option `--replay-interval` define the interval(unit in ms,with default value 1000) of replays
`tt -i 1004 -p`{{execute T2}}
```bash
$ tt -i 1004 -p
RE-INDEX 1004
GMT-REPLAY 2018-12-04 11:26:00
OBJECT 0x4b67cf4d
CLASS demo.MathGame
METHOD primeFactors
PARAMETERS[0] @Integer[946738738]
IS-RETURN true
IS-EXCEPTION false
RETURN-OBJ @ArrayList[
@Integer[2],
@Integer[11],
@Integer[17],
@Integer[2531387],
]
Time fragment[1004] successfully replayed.
Affect(row-cnt:1) cost in 14 ms.
```
F.Y.I
1. **Loss** of the `ThreadLocal`
Arthas save params into an array, then invoke the method with the params again. The method execute in another thread, so the `ThreadLocal` **lost**.
1. params may be modified
Arthas save params into an array, they are object references. The Objects may be modified by other code.
@@ -0,0 +1,16 @@
在新的`Terminal 2`里,下载`arthas-boot.jar`,再用`java -jar`命令启动:
`wget https://alibaba.github.io/arthas/arthas-boot.jar
java -jar arthas-boot.jar`{{execute T2}}
`arthas-boot`是`Arthas`的启动程序,它启动后,会列出所有的Java进程,用户可以选择需要诊断的目标进程。
选择第一个进程,输入 `1`{{execute T2}} ,再`Enter/回车`:
Attach成功之后,会打印Arthas LOGO。输入 `help`{{execute T2}} 可以获取到更多的帮助信息。
![Arthas Boot](/arthas/scenarios/common-resources/assets/arthas-boot.png)
@@ -0,0 +1,10 @@
下载`arthas-demo.jar`,再用`java -jar`命令启动:
`wget https://alibaba.github.io/arthas/arthas-demo.jar
java -jar arthas-demo.jar`{{execute T1}}
`arthas-demo`是一个很简单的程序,它随机生成整数,再执行因式分解,把结果打印出来。如果生成的随机数是负数,则会打印提示信息。
@@ -0,0 +1,12 @@
在“watch”中,我们演示了了Arthas的watch命令。如果有更多的技巧或者使用疑问,欢迎在Issue里提出。
* Issues: https://github.com/alibaba/arthas/issues
* 文档: https://alibaba.github.io/arthas
如果您在使用Arthas,请让我们知道,您的使用对我们非常重要:[查看](https://github.com/alibaba/arthas/issues/111)
欢迎关注公众号,获取Arthas项目的信息,源码分析,案例实践。
![Arthas公众号](/arthas/scenarios/common-resources/assets/qrcode_gongzhonghao.jpg)
@@ -0,0 +1,35 @@
{
"title": "Arthas watch命令",
"description": "Arthas watch命令",
"difficulty": "精通者",
"time": "10-20 分钟",
"details": {
"steps": [
{
"title": "启动arthas demo",
"text": "arthas-demo.md"
},
{
"title": "启动arthas-boot",
"text": "arthas-boot.md"
},
{
"title": "watch命令",
"text": "watch.md"
}
],
"intro": {
"text": "intro.md"
},
"finish": {
"text": "finish.md"
}
},
"environment": {
"uilayout": "terminal"
},
"backend": {
"imageid": "java",
"environmentsprotocol": "http"
}
}
@@ -0,0 +1,23 @@
![Arthas](https://alibaba.github.io/arthas/_images/arthas.png)
`Arthas` 是Alibaba开源的Java诊断工具,深受开发者喜爱。在线排查问题,无需重启;动态跟踪Java代码;实时监控JVM状态。
`Arthas` 支持JDK 6+,支持Linux/Mac/Windows,采用命令行交互模式,同时提供丰富的 `Tab` 自动补全功能,进一步方便进行问题的定位和诊断。
当你遇到以下类似问题而束手无策时,Arthas可以帮助你解决:
- 这个类从哪个 jar 包加载的?为什么会报各种类相关的 Exception?
- 我改的代码为什么没有执行到?难道是我没 commit?分支搞错了?
- 遇到问题无法在线上 debug,难道只能通过加日志再重新发布吗?
- 线上遇到某个用户的数据处理有问题,但线上同样无法 debug,线下无法重现!
- 是否有一个全局视角来查看系统的运行状况?
- 有什么办法可以监控到JVM的实时运行状态?
- 怎么快速定位应用的热点,生成火焰图?
本教程会以一个简单的应用为例,演示watch命令。
* Github: https://github.com/alibaba/arthas
* 文档: https://alibaba.github.io/arthas/
@@ -0,0 +1,265 @@
> 方法执行数据观测
让你能方便的观察到指定方法的调用情况。能观察到的范围为:`返回值`、`抛出异常`、`入参`,通过编写 OGNL 表达式进行对应变量的查看。
### 参数说明
watch 的参数比较多,主要是因为它能在 4 个不同的场景观察对象
|参数名称|参数说明|
|---:|:---|
|*class-pattern*|类名表达式匹配|
|*method-pattern*|方法名表达式匹配|
|*express*|观察表达式|
|*condition-express*|条件表达式|
|[b]|在**方法调用之前**观察|
|[e]|在**方法异常之后**观察|
|[s]|在**方法返回之后**观察|
|[f]|在**方法结束之后**(正常返回和异常返回)观察|
|[E]|开启正则表达式匹配,默认为通配符匹配|
|[x:]|指定输出结果的属性遍历深度,默认为 1|
这里重点要说明的是观察表达式,观察表达式的构成主要由 ognl 表达式组成,所以你可以这样写`"{params,returnObj}"`,只要是一个合法的 ognl 表达式,都能被正常支持。
观察的维度也比较多,主要体现在参数 `advice` 的数据结构上。`Advice` 参数最主要是封装了通知节点的所有信息。请参考[表达式核心变量](advice-class.md)中关于该节点的描述。
* 特殊用法请参考:[https://github.com/alibaba/arthas/issues/71](https://github.com/alibaba/arthas/issues/71)
* OGNL表达式官网:[https://commons.apache.org/proper/commons-ognl/language-guide.html](https://commons.apache.org/proper/commons-ognl/language-guide.html)
**特别说明**:
* watch 命令定义了4个观察事件点,即 `-b` 方法调用前,`-e` 方法异常后,`-s` 方法返回后,`-f` 方法结束后
* 4个观察事件点 `-b`、`-e`、`-s` 默认关闭,`-f` 默认打开,当指定观察点被打开后,在相应事件点会对观察表达式进行求值并输出
* 这里要注意`方法入参`和`方法出参`的区别,有可能在中间被修改导致前后不一致,除了 `-b` 事件点 `params` 代表方法入参外,其余事件都代表方法出参
* 当使用 `-b` 时,由于观察事件点是在方法调用前,此时返回值或异常均不存在
### 使用参考
#### 观察方法出参和返回值
`watch demo.MathGame primeFactors "{params,returnObj}" -x 2`{{execute T2}}
```bash
$ watch demo.MathGame primeFactors "{params,returnObj}" -x 2
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 44 ms.
ts=2018-12-03 19:16:51; [cost=1.280502ms] result=@ArrayList[
@Object[][
@Integer[535629513],
],
@ArrayList[
@Integer[3],
@Integer[19],
@Integer[191],
@Integer[49199],
],
]
```
#### 观察方法入参
`watch demo.MathGame primeFactors "{params,returnObj}" -x 2 -b`{{execute T2}}
```bash
$ watch demo.MathGame primeFactors "{params,returnObj}" -x 2 -b
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 50 ms.
ts=2018-12-03 19:23:23; [cost=0.0353ms] result=@ArrayList[
@Object[][
@Integer[-1077465243],
],
null,
]
```
* 对比前一个例子,返回值为空(事件点为方法执行前,因此获取不到返回值)
#### 同时观察方法调用前和方法返回后
`watch demo.MathGame primeFactors "{params,target,returnObj}" -x 2 -b -s -n 2`{{execute T2}}
```bash
$ watch demo.MathGame primeFactors "{params,target,returnObj}" -x 2 -b -s -n 2
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 46 ms.
ts=2018-12-03 19:29:54; [cost=0.01696ms] result=@ArrayList[
@Object[][
@Integer[1544665400],
],
@MathGame[
random=@Random[java.util.Random@522b408a],
illegalArgumentCount=@Integer[13038],
],
null,
]
ts=2018-12-03 19:29:54; [cost=4.277392ms] result=@ArrayList[
@Object[][
@Integer[1544665400],
],
@MathGame[
random=@Random[java.util.Random@522b408a],
illegalArgumentCount=@Integer[13038],
],
@ArrayList[
@Integer[2],
@Integer[2],
@Integer[2],
@Integer[5],
@Integer[5],
@Integer[73],
@Integer[241],
@Integer[439],
],
]
```
* 参数里`-n 2`,表示只执行两次
* 这里输出结果中,第一次输出的是方法调用前的观察表达式的结果,第二次输出的是方法返回后的表达式的结果
* 结果的输出顺序和事件发生的先后顺序一致,和命令中 `-s -b` 的顺序无关
#### 调整`-x`的值,观察具体的方法参数值
`watch demo.MathGame primeFactors "{params,target}" -x 3`{{execute T2}}
```bash
$ watch demo.MathGame primeFactors "{params,target}" -x 3
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 58 ms.
ts=2018-12-03 19:34:19; [cost=0.587833ms] result=@ArrayList[
@Object[][
@Integer[47816758],
],
@MathGame[
random=@Random[
serialVersionUID=@Long[3905348978240129619],
seed=@AtomicLong[3133719055989],
multiplier=@Long[25214903917],
addend=@Long[11],
mask=@Long[281474976710655],
DOUBLE_UNIT=@Double[1.1102230246251565E-16],
BadBound=@String[bound must be positive],
BadRange=@String[bound must be greater than origin],
BadSize=@String[size must be non-negative],
seedUniquifier=@AtomicLong[-3282039941672302964],
nextNextGaussian=@Double[0.0],
haveNextNextGaussian=@Boolean[false],
serialPersistentFields=@ObjectStreamField[][isEmpty=false;size=3],
unsafe=@Unsafe[sun.misc.Unsafe@2eaa1027],
seedOffset=@Long[24],
],
illegalArgumentCount=@Integer[13159],
],
]
```
* `-x`表示遍历深度,可以调整来打印具体的参数和结果内容,默认值是1。
#### 条件表达式的例子
`watch demo.MathGame primeFactors "{params[0],target}" "params[0]<0"`{{execute T2}}
```bash
$ watch demo.MathGame primeFactors "{params[0],target}" "params[0]<0"
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 68 ms.
ts=2018-12-03 19:36:04; [cost=0.530255ms] result=@ArrayList[
@Integer[-18178089],
@MathGame[demo.MathGame@41cf53f9],
]
```
* 只有满足条件的调用,才会有响应。
* `watch-express` 单个值可以不加'{}',多个值需要加'{a,b,c}'。
* `condition-express` 不能加'{}',可以使用逗号分隔子表达式,取表达式最后一个值来判断。
如果watch的方法存在同名的其它重载方法,可以通过下面的办法进行过滤:
* 根据参数类型进行过滤
`watch demo.MathGame primeFactors '{params, params[0].class.name}' 'params[0].class.name == "java.lang.Integer"'`{{execute T2}}
* 根据参数个数进行过滤
`watch demo.MathGame primeFactors '{params, params.length}' 'params.length==1'`{{execute T2}}
#### 观察异常信息的例子
`watch demo.MathGame primeFactors "{params[0],throwExp}" -e -x 2`{{execute T2}}
```bash
$ watch demo.MathGame primeFactors "{params[0],throwExp}" -e -x 2
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 62 ms.
ts=2018-12-03 19:38:00; [cost=1.414993ms] result=@ArrayList[
@Integer[-1120397038],
java.lang.IllegalArgumentException: number is: -1120397038, need >= 2
at demo.MathGame.primeFactors(MathGame.java:46)
at demo.MathGame.run(MathGame.java:24)
at demo.MathGame.main(MathGame.java:16)
,
]
```
* `-e`表示抛出异常时才触发
* express中,表示异常信息的变量是`throwExp`
根据异常类型或者message进行过滤:
`watch demo.MathGame primeFactors '{params, throwExp}' '#msg=throwExp.toString(), #msg.contains("IllegalArgumentException")' -e -x 2`{{execute T2}}
#### 按照耗时进行过滤
`watch demo.MathGame primeFactors '{params, returnObj}' '#cost>200' -x 2`{{execute T2}}
```bash
$ watch demo.MathGame primeFactors '{params, returnObj}' '#cost>200' -x 2
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 66 ms.
ts=2018-12-03 19:40:28; [cost=2112.168897ms] result=@ArrayList[
@Object[][
@Integer[2141897465],
],
@ArrayList[
@Integer[5],
@Integer[428379493],
],
]
```
* `#cost>200`(单位是`ms`)表示只有当耗时大于200ms时才会输出,过滤掉执行时间小于200ms的调用
#### 观察当前对象中的属性
`watch demo.MathGame primeFactors 'target'`{{execute T2}}
如果想查看方法运行前后,当前对象中的属性,可以使用`target`关键字,代表当前对象
```bash
$ watch demo.MathGame primeFactors 'target'
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 52 ms.
ts=2018-12-03 19:41:52; [cost=0.477882ms] result=@MathGame[
random=@Random[java.util.Random@522b408a],
illegalArgumentCount=@Integer[13355],
]
```
然后使用`target.field_name`访问当前对象的某个属性
`watch demo.MathGame primeFactors 'target.illegalArgumentCount'`{{execute T2}}
```bash
$ watch demo.MathGame primeFactors 'target.illegalArgumentCount'
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 67 ms.
ts=2018-12-03 20:04:34; [cost=131.303498ms] result=@Integer[8]
ts=2018-12-03 20:04:35; [cost=0.961441ms] result=@Integer[8]
```
@@ -0,0 +1,16 @@
In the new `Terminal 2`, download `arthas-boot.jar` and start with the `java -jar` command:
`wget https://alibaba.github.io/arthas/arthas-boot.jar
java -jar arthas-boot.jar`{{execute T2}}
`arthas-boot` is the launcher for `Arthas`. It lists all the Java processes, and the user can select the target process to be diagnosed.
Select the first process, type `1`{{execute T2}} ,then type `Enter`:
After the Attach is successful, Arthas LOGO is printed. Enter `help`{{execute T2}} for more help.
![Arthas Boot](/arthas/scenarios/common-resources/assets/arthas-boot.png)
@@ -0,0 +1,11 @@
Download `arthas-demo.jar` and start with the `java -jar` command:
`wget https://alibaba.github.io/arthas/arthas-demo.jar
java -jar arthas-demo.jar`{{execute T1}}
`arthas-demo` is a very simple program that randomly generates integers, performs factorization, and prints the results.
If the generated random number is negative, a error message will be printed.
@@ -0,0 +1,8 @@
The `watch Tutorial` demonstrates the usage of watch. If you have more tips or questions, please feel free to ask in Issue.
* Issues: https://github.com/alibaba/arthas/issues
* Documentation: https://alibaba.github.io/arthas
If you are using Arthas, please let us know. Your use is very important to us: [View](https://github.com/alibaba/arthas/issues/111)
@@ -0,0 +1,35 @@
{
"title": "Arthas watch Command",
"description": "Arthas watch Command",
"difficulty": "master",
"time": "10-20 minutes",
"details": {
"steps": [
{
"title": "Arthas demo",
"text": "arthas-demo.md"
},
{
"title": "Start arthas-boot",
"text": "arthas-boot.md"
},
{
"title": "watch Command",
"text": "watch.md"
}
],
"intro": {
"text": "intro.md"
},
"finish": {
"text": "finish.md"
}
},
"environment": {
"uilayout": "terminal"
},
"backend": {
"imageid": "java",
"environmentsprotocol": "http"
}
}
@@ -0,0 +1,40 @@
![Arthas](https://alibaba.github.io/arthas/_images/arthas.png)
`Arthas` is a Java diagnostic tool open-sourced by Alibaba middleware team. Arthas helps developers in trouble-shooting issues in production environment for Java based applications without modifying code or restarting servers.
`Arthas` supports JDK 6+, supports Linux/Mac/Windows.
## Background
Oftentimes the production system network is inaccessible from local development environment. If issues are encountered in production systems, it is impossible to use IDE to debug the application remotely. What’s even worse, debugging in production environment is unacceptable, as it will suspend all the threads, leading to services downtime.
Developers could always try to reproduce the same issue on the test/staging environment. However, this is tricky as some issues cannot be reproduced easily in a different environment, or even disappear once restarted.
And if you’re thinking of adding some logs to your code to help trouble-shoot the issue, you will have to go through the following lifecycle: test, staging, and then to production. Time is money! This approach is inefficient! Worse still, the issue may not be fixed since it might be irreproducible once the JVM is restarted, as described above.
Arthas is built to solve these issues. A developer can troubleshoot production issues on the fly. No JVM restart, no additional code changes. Arthas works as an observer, that is, it will never suspend your running threads.
## Key features
- Check whether a class is loaded? Or where the class is loaded from? (Useful for trouble-shooting jar file conflicts)
- Decompile a class to ensure the code is running as expected.
- Check classloader statistics, e.g. the number of classloaders, the number of classes loaded per classloader, the classloader hierarchy, possible classloader leaks, etc.
- Check the method invocation details, e.g. method parameter, returned values, exceptions and etc.
- Check the stack trace of specified method invocation. This is useful when a developer wants to know the caller of the method.
- Trace the method invocation to find slow sub-invocations.
- Monitor method invocation statistics, e.g. QPS (Query Per Second), RT (Return Time), success rate and etc.
- Monitor system metrics, thread states and CPU usage, GC statistics and etc.
- Supports command line interactive mode, with auto-complete feature enabled.
- Supports telnet and WebSocket, which enables both local and remote diagnostics with command line and browsers.
- Supports profiler/Flame Graph
- Supports JDK 6+
- Supports Linux/Mac/Windows
This tutorial takes a simple application as an example to demonstrate the the usage of watch.
* Github: https://github.com/alibaba/arthas
* Docs: https://alibaba.github.io/arthas/
@@ -0,0 +1,264 @@
Monitor methods in data aspect including `return values`, `exceptions` and `parameters`.
With the help of [OGNL](https://commons.apache.org/proper/commons-ognl/index.html), you can easily check the details of variables when methods being invoked.
### Parameters & Options
There are four different scenarios for `watch` command, which makes it rather complicated.
|Name|Specification|
|---:|:---|
|*class-pattern*|pattern for the class name|
|*method-pattern*|pattern for the method name|
|*expression*|expression to monitor|
|*condition-expression*|condition expression to filter|
|[b]|before method being invoked|
|[e]|when method encountering exceptions|
|[s]|when method exits normally|
|[f]|when method exits (either succeed or fail with exceptions)|
|[E]|turn on regex matching while the default is wildcard matching|
|[x:]|the depth to print the specified property with default value: 1|
F.Y.I
1. any valid OGNL expression as `"{params,returnObj}"` supported
2. there are four *watching* points: `-b`, `-e`, `-s` and `-f` (the first three are off in default while `-f` on);
3. at the *watching* point, Arthas will use the *expression* to evaluate the variables and print them out;
4. `in parameters` and `out parameters` are different since they can be modified within the invoked methods; `params` stands for `in parameters` in `-b`while `out parameters` in other *watching* points;
5. there are no `return values` and `exceptions` when using `-b`.
Advanced:
* [Special usages](https://github.com/alibaba/arthas/issues/71)
* [OGNL official guide](https://commons.apache.org/proper/commons-ognl/language-guide.html)
### Usage
#### Check the `out parameters` and `return value`
`watch demo.MathGame primeFactors "{params,returnObj}" -x 2`{{execute T2}}
```bash
$ watch demo.MathGame primeFactors "{params,returnObj}" -x 2
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 44 ms.
ts=2018-12-03 19:16:51; [cost=1.280502ms] result=@ArrayList[
@Object[][
@Integer[535629513],
],
@ArrayList[
@Integer[3],
@Integer[19],
@Integer[191],
@Integer[49199],
],
]
```
#### Check `in parameters`
`watch demo.MathGame primeFactors "{params,returnObj}" -x 2 -b`{{execute T2}}
```bash
$ watch demo.MathGame primeFactors "{params,returnObj}" -x 2 -b
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 50 ms.
ts=2018-12-03 19:23:23; [cost=0.0353ms] result=@ArrayList[
@Object[][
@Integer[-1077465243],
],
null,
]
```
Compared to the previous *check*:
* `return value` is `null` since it's `-b`.
#### Check *before* and *after* at the same time
`watch demo.MathGame primeFactors "{params,target,returnObj}" -x 2 -b -s -n 2`{{execute T2}}
```bash
$ watch demo.MathGame primeFactors "{params,target,returnObj}" -x 2 -b -s -n 2
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 46 ms.
ts=2018-12-03 19:29:54; [cost=0.01696ms] result=@ArrayList[
@Object[][
@Integer[1544665400],
],
@MathGame[
random=@Random[java.util.Random@522b408a],
illegalArgumentCount=@Integer[13038],
],
null,
]
ts=2018-12-03 19:29:54; [cost=4.277392ms] result=@ArrayList[
@Object[][
@Integer[1544665400],
],
@MathGame[
random=@Random[java.util.Random@522b408a],
illegalArgumentCount=@Integer[13038],
],
@ArrayList[
@Integer[2],
@Integer[2],
@Integer[2],
@Integer[5],
@Integer[5],
@Integer[73],
@Integer[241],
@Integer[439],
],
]
```
F.Y.I
* `-n 2`: threshold of execution times is 2.
* the first block of output is the *before watching* point;
* *the order of the output determined by the *watching* order itself (nothing to do with the order of the options `-b -s`).
#### Use `-x` to check more details
`watch demo.MathGame primeFactors "{params,target}" -x 3`{{execute T2}}
```bash
$ watch demo.MathGame primeFactors "{params,target}" -x 3
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 58 ms.
ts=2018-12-03 19:34:19; [cost=0.587833ms] result=@ArrayList[
@Object[][
@Integer[47816758],
],
@MathGame[
random=@Random[
serialVersionUID=@Long[3905348978240129619],
seed=@AtomicLong[3133719055989],
multiplier=@Long[25214903917],
addend=@Long[11],
mask=@Long[281474976710655],
DOUBLE_UNIT=@Double[1.1102230246251565E-16],
BadBound=@String[bound must be positive],
BadRange=@String[bound must be greater than origin],
BadSize=@String[size must be non-negative],
seedUniquifier=@AtomicLong[-3282039941672302964],
nextNextGaussian=@Double[0.0],
haveNextNextGaussian=@Boolean[false],
serialPersistentFields=@ObjectStreamField[][isEmpty=false;size=3],
unsafe=@Unsafe[sun.misc.Unsafe@2eaa1027],
seedOffset=@Long[24],
],
illegalArgumentCount=@Integer[13159],
],
]
```
* `-x`: Expand level of object (1 by default)
#### Use condition expressions to locate specific call
`watch demo.MathGame primeFactors "{params[0],target}" "params[0]<0"`{{execute T2}}
```bash
$ watch demo.MathGame primeFactors "{params[0],target}" "params[0]<0"
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 68 ms.
ts=2018-12-03 19:36:04; [cost=0.530255ms] result=@ArrayList[
@Integer[-18178089],
@MathGame[demo.MathGame@41cf53f9],
]
```
* Only calls that meet the conditions will respond.
* `Watch Express` single value can not be added '{}', and multiple values need to be added '{a, B, C}'.
* `condition Express` cannot add '{}', you can use commas to separate subexpressions and take the last value of the expression to judge.
If there are other overloaded methods with the same name in the watch method, you can filter them by the following methods:
* Filter according to parameter type
`watch demo.MathGame primeFactors '{params, params[0].class.name}' 'params[0].class.name == "java.lang.Integer"'`{{execute T2}}
* Filter according to the number of parameters
`watch demo.MathGame primeFactors '{params, params.length}' 'params.length==1'`{{execute T2}}
#### Check `exceptions`
`watch demo.MathGame primeFactors "{params[0],throwExp}" -e -x 2`{{execute T2}}
```bash
$ watch demo.MathGame primeFactors "{params[0],throwExp}" -e -x 2
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 62 ms.
ts=2018-12-03 19:38:00; [cost=1.414993ms] result=@ArrayList[
@Integer[-1120397038],
java.lang.IllegalArgumentException: number is: -1120397038, need >= 2
at demo.MathGame.primeFactors(MathGame.java:46)
at demo.MathGame.run(MathGame.java:24)
at demo.MathGame.main(MathGame.java:16)
,
]
```
* `-e`: Trigger when an exception is thrown
* `throwExp`: the exception object
Filter according to exception type or message:
`watch demo.MathGame primeFactors '{params, throwExp}' '#msg=throwExp.toString(), #msg.contains("IllegalArgumentException")' -e -x 2`{{execute T2}}
#### Filter by time cost
`watch demo.MathGame primeFactors '{params, returnObj}' '#cost>200' -x 2`{{execute T2}}
```bash
$ watch demo.MathGame primeFactors '{params, returnObj}' '#cost>200' -x 2
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 66 ms.
ts=2018-12-03 19:40:28; [cost=2112.168897ms] result=@ArrayList[
@Object[][
@Integer[2141897465],
],
@ArrayList[
@Integer[5],
@Integer[428379493],
],
]
```
* `#cost>200` (`ms`) filter out all invokings that take less than `200ms`.
#### Check the field of the target object
* `target` is the `this` object in java.
`watch demo.MathGame primeFactors 'target'`{{execute T2}}
```bash
$ watch demo.MathGame primeFactors 'target'
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 52 ms.
ts=2018-12-03 19:41:52; [cost=0.477882ms] result=@MathGame[
random=@Random[java.util.Random@522b408a],
illegalArgumentCount=@Integer[13355],
]
```
* `target.field_name`: the field of the current object.
`watch demo.MathGame primeFactors 'target.illegalArgumentCount'`{{execute T2}}
```bash
$ watch demo.MathGame primeFactors 'target.illegalArgumentCount'
Press Ctrl+C to abort.
Affect(class-cnt:1 , method-cnt:1) cost in 67 ms.
ts=2018-12-03 20:04:34; [cost=131.303498ms] result=@Integer[8]
ts=2018-12-03 20:04:35; [cost=0.961441ms] result=@Integer[8]
```