repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/httptelnet/NettyHttpTelnetBootstrap.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/httptelnet/NettyHttpTelnetBootstrap.java
package com.taobao.arthas.core.shell.term.impl.httptelnet; import com.taobao.arthas.core.shell.term.impl.http.session.HttpSessionManager; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.DefaultChannelGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.util.concurrent.DefaultThreadFactory; import io.netty.util.concurrent.EventExecutorGroup; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.concurrent.ImmediateEventExecutor; import io.termd.core.function.Consumer; import io.termd.core.function.Supplier; import io.termd.core.telnet.TelnetBootstrap; import io.termd.core.telnet.TelnetHandler; import io.termd.core.tty.TtyConnection; /** * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> * @author hengyunabc 2019-11-05 */ public class NettyHttpTelnetBootstrap extends TelnetBootstrap { private EventLoopGroup group; private ChannelGroup channelGroup; private EventExecutorGroup workerGroup; private HttpSessionManager httpSessionManager; public NettyHttpTelnetBootstrap(EventExecutorGroup workerGroup, HttpSessionManager httpSessionManager) { this.workerGroup = workerGroup; this.group = new NioEventLoopGroup(new DefaultThreadFactory("arthas-NettyHttpTelnetBootstrap", true)); this.channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE); this.httpSessionManager = httpSessionManager; } public NettyHttpTelnetBootstrap setHost(String host) { return (NettyHttpTelnetBootstrap) super.setHost(host); } public NettyHttpTelnetBootstrap setPort(int port) { return (NettyHttpTelnetBootstrap) super.setPort(port); } @Override public void start(Supplier<TelnetHandler> factory, Consumer<Throwable> doneHandler) { // ignore, never invoke } public void start(final Supplier<TelnetHandler> handlerFactory, final Consumer<TtyConnection> factory, final Consumer<Throwable> doneHandler) { ServerBootstrap boostrap = new ServerBootstrap(); boostrap.group(group).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ProtocolDetectHandler(channelGroup, handlerFactory, factory, workerGroup, httpSessionManager)); } }); boostrap.bind(getHost(), getPort()).addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { if (future.isSuccess()) { doneHandler.accept(null); } else { doneHandler.accept(future.cause()); } } }); } @Override public void stop(final Consumer<Throwable> doneHandler) { GenericFutureListener<Future<Object>> adapter = new GenericFutureListener<Future<Object>>() { @Override public void operationComplete(Future<Object> future) throws Exception { try { doneHandler.accept(future.cause()); } finally { group.shutdownGracefully(); } } }; channelGroup.close().addListener(adapter); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/httptelnet/ProtocolDetectHandler.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/httptelnet/ProtocolDetectHandler.java
package com.taobao.arthas.core.shell.term.impl.httptelnet; import java.util.concurrent.TimeUnit; import com.taobao.arthas.common.ArthasConstants; import com.taobao.arthas.core.shell.term.impl.http.BasicHttpAuthenticatorHandler; import com.taobao.arthas.core.shell.term.impl.http.HttpRequestHandler; import com.taobao.arthas.core.shell.term.impl.http.TtyWebSocketFrameHandler; import com.taobao.arthas.core.shell.term.impl.http.session.HttpSessionManager; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelPipeline; import io.netty.channel.group.ChannelGroup; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.stream.ChunkedWriteHandler; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.concurrent.EventExecutorGroup; import io.netty.util.concurrent.ScheduledFuture; import io.termd.core.function.Consumer; import io.termd.core.function.Supplier; import io.termd.core.telnet.TelnetHandler; import io.termd.core.telnet.netty.TelnetChannelHandler; import io.termd.core.tty.TtyConnection; /** * * @author hengyunabc 2019-11-04 * */ public class ProtocolDetectHandler extends ChannelInboundHandlerAdapter { private ChannelGroup channelGroup; private Supplier<TelnetHandler> handlerFactory; private Consumer<TtyConnection> ttyConnectionFactory; private EventExecutorGroup workerGroup; private HttpSessionManager httpSessionManager; public ProtocolDetectHandler(ChannelGroup channelGroup, final Supplier<TelnetHandler> handlerFactory, Consumer<TtyConnection> ttyConnectionFactory, EventExecutorGroup workerGroup, HttpSessionManager httpSessionManager) { this.channelGroup = channelGroup; this.handlerFactory = handlerFactory; this.ttyConnectionFactory = ttyConnectionFactory; this.workerGroup = workerGroup; this.httpSessionManager = httpSessionManager; } private ScheduledFuture<?> detectTelnetFuture; @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { detectTelnetFuture = ctx.channel().eventLoop().schedule(new Runnable() { @Override public void run() { channelGroup.add(ctx.channel()); TelnetChannelHandler handler = new TelnetChannelHandler(handlerFactory); ChannelPipeline pipeline = ctx.pipeline(); pipeline.addLast(handler); pipeline.remove(ProtocolDetectHandler.this); ctx.fireChannelActive(); // trigger TelnetChannelHandler init } }, 1000, TimeUnit.MILLISECONDS); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; if (in.readableBytes() < 3) { return; } if (detectTelnetFuture != null && detectTelnetFuture.isCancellable()) { detectTelnetFuture.cancel(false); } byte[] bytes = new byte[3]; in.getBytes(0, bytes); String httpHeader = new String(bytes); ChannelPipeline pipeline = ctx.pipeline(); if (!"GET".equalsIgnoreCase(httpHeader)) { // telnet channelGroup.add(ctx.channel()); TelnetChannelHandler handler = new TelnetChannelHandler(handlerFactory); pipeline.addLast(handler); ctx.fireChannelActive(); // trigger TelnetChannelHandler init } else { pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new ChunkedWriteHandler()); pipeline.addLast(new HttpObjectAggregator(ArthasConstants.MAX_HTTP_CONTENT_LENGTH)); pipeline.addLast(new BasicHttpAuthenticatorHandler(httpSessionManager)); pipeline.addLast(workerGroup, "HttpRequestHandler", new HttpRequestHandler(ArthasConstants.DEFAULT_WEBSOCKET_PATH)); pipeline.addLast(new WebSocketServerProtocolHandler(ArthasConstants.DEFAULT_WEBSOCKET_PATH, null, false, ArthasConstants.MAX_HTTP_CONTENT_LENGTH, false, true)); pipeline.addLast(new IdleStateHandler(0, 0, ArthasConstants.WEBSOCKET_IDLE_SECONDS)); pipeline.addLast(new TtyWebSocketFrameHandler(channelGroup, ttyConnectionFactory)); ctx.fireChannelActive(); } pipeline.remove(this); ctx.fireChannelRead(in); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/NettyWebsocketTtyBootstrap.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/NettyWebsocketTtyBootstrap.java
package com.taobao.arthas.core.shell.term.impl.http; import com.taobao.arthas.common.ArthasConstants; import com.taobao.arthas.core.shell.term.impl.http.session.HttpSessionManager; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoopGroup; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.DefaultChannelGroup; import io.netty.channel.local.LocalAddress; import io.netty.channel.local.LocalServerChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.util.concurrent.DefaultThreadFactory; import io.netty.util.concurrent.EventExecutorGroup; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.concurrent.ImmediateEventExecutor; import io.termd.core.function.Consumer; import io.termd.core.tty.TtyConnection; import io.termd.core.util.CompletableFuture; import io.termd.core.util.Helper; /** * Convenience class for quickly starting a Netty Tty server. * * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> */ public class NettyWebsocketTtyBootstrap { private final ChannelGroup channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE); private String host; private int port; private EventLoopGroup group; private Channel channel; private EventExecutorGroup workerGroup; private HttpSessionManager httpSessionManager; public NettyWebsocketTtyBootstrap(EventExecutorGroup workerGroup, HttpSessionManager httpSessionManager) { this.workerGroup = workerGroup; this.host = "localhost"; this.port = 8080; this.httpSessionManager = httpSessionManager; } public String getHost() { return host; } public NettyWebsocketTtyBootstrap setHost(String host) { this.host = host; return this; } public int getPort() { return port; } public NettyWebsocketTtyBootstrap setPort(int port) { this.port = port; return this; } public void start(Consumer<TtyConnection> handler, final Consumer<Throwable> doneHandler) { group = new NioEventLoopGroup(new DefaultThreadFactory("arthas-NettyWebsocketTtyBootstrap", true)); if (this.port > 0) { ServerBootstrap b = new ServerBootstrap(); b.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new TtyServerInitializer(channelGroup, handler, workerGroup, httpSessionManager)); final ChannelFuture f = b.bind(host, port); f.addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { if (future.isSuccess()) { channel = f.channel(); doneHandler.accept(null); } else { doneHandler.accept(future.cause()); } } }); } // listen local address in VM communication ServerBootstrap b2 = new ServerBootstrap(); b2.group(group).channel(LocalServerChannel.class).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new LocalTtyServerInitializer(channelGroup, handler, workerGroup)); ChannelFuture bindLocalFuture = b2.bind(new LocalAddress(ArthasConstants.NETTY_LOCAL_ADDRESS)); if (this.port < 0) { // 保证回调doneHandler bindLocalFuture.addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { if (future.isSuccess()) { doneHandler.accept(null); } else { doneHandler.accept(future.cause()); } } }); } } public CompletableFuture<Void> start(Consumer<TtyConnection> handler) { CompletableFuture<Void> fut = new CompletableFuture<Void>(); start(handler, Helper.startedHandler(fut)); return fut; } public void stop(final Consumer<Throwable> doneHandler) { if (channel != null) { channel.close(); } channelGroup.close().addListener(new GenericFutureListener<Future<? super Void>>() { @Override public void operationComplete(Future<? super Void> future) throws Exception { try { doneHandler.accept(future.cause()); } finally { group.shutdownGracefully(); } } }); } public CompletableFuture<Void> stop() { CompletableFuture<Void> fut = new CompletableFuture<Void>(); stop(Helper.stoppedHandler(fut)); return fut; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/TtyServerInitializer.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/TtyServerInitializer.java
package com.taobao.arthas.core.shell.term.impl.http; import com.taobao.arthas.common.ArthasConstants; import com.taobao.arthas.core.shell.term.impl.http.session.HttpSessionManager; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.group.ChannelGroup; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.stream.ChunkedWriteHandler; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.concurrent.EventExecutorGroup; import io.termd.core.function.Consumer; import io.termd.core.tty.TtyConnection; /** * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> */ public class TtyServerInitializer extends ChannelInitializer<SocketChannel> { private final ChannelGroup group; private final Consumer<TtyConnection> handler; private EventExecutorGroup workerGroup; private HttpSessionManager httpSessionManager; public TtyServerInitializer(ChannelGroup group, Consumer<TtyConnection> handler, EventExecutorGroup workerGroup, HttpSessionManager httpSessionManager) { this.group = group; this.handler = handler; this.workerGroup = workerGroup; this.httpSessionManager = httpSessionManager; } @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new ChunkedWriteHandler()); pipeline.addLast(new HttpObjectAggregator(ArthasConstants.MAX_HTTP_CONTENT_LENGTH)); pipeline.addLast(new BasicHttpAuthenticatorHandler(httpSessionManager)); pipeline.addLast(workerGroup, "HttpRequestHandler", new HttpRequestHandler(ArthasConstants.DEFAULT_WEBSOCKET_PATH)); pipeline.addLast(new WebSocketServerProtocolHandler(ArthasConstants.DEFAULT_WEBSOCKET_PATH, null, false, ArthasConstants.MAX_HTTP_CONTENT_LENGTH, false, true)); pipeline.addLast(new IdleStateHandler(0, 0, ArthasConstants.WEBSOCKET_IDLE_SECONDS)); pipeline.addLast(new TtyWebSocketFrameHandler(group, handler)); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/HttpRequestHandler.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/HttpRequestHandler.java
package com.taobao.arthas.core.shell.term.impl.http; import com.alibaba.arthas.deps.org.slf4j.Logger; import com.alibaba.arthas.deps.org.slf4j.LoggerFactory; import com.taobao.arthas.common.IOUtils; import com.taobao.arthas.core.server.ArthasBootstrap; import com.taobao.arthas.core.shell.term.impl.http.api.HttpApiHandler; import com.taobao.arthas.mcp.server.protocol.server.handler.McpHttpRequestHandler; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.*; import io.termd.core.http.HttpTtyConnection; import io.termd.core.util.Logging; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URL; import static com.taobao.arthas.core.util.HttpUtils.createRedirectResponse; import static com.taobao.arthas.core.util.HttpUtils.createResponse; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; /** * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> * @author hengyunabc 2019-11-06 * @author gongdewei 2020-03-18 */ public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> { private static final Logger logger = LoggerFactory.getLogger(HttpRequestHandler.class); private final String wsUri; private File dir; private HttpApiHandler httpApiHandler; private McpHttpRequestHandler mcpRequestHandler; public HttpRequestHandler(String wsUri) { this(wsUri, ArthasBootstrap.getInstance().getOutputPath()); } public HttpRequestHandler(String wsUri, File dir) { this.wsUri = wsUri; this.dir = dir; dir.mkdirs(); this.httpApiHandler = ArthasBootstrap.getInstance().getHttpApiHandler(); this.mcpRequestHandler = ArthasBootstrap.getInstance().getMcpRequestHandler(); } @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { String path = new URI(request.uri()).getPath(); if (wsUri.equalsIgnoreCase(path)) { ctx.fireChannelRead(request.retain()); } else { if (HttpUtil.is100ContinueExpected(request)) { send100Continue(ctx); } HttpResponse response = null; if ("/".equals(path)) { path = "/index.html"; } boolean isFileResponseFinished = false; boolean isMcpHandled = false; try { //handle http restful api if ("/api".equals(path)) { response = httpApiHandler.handle(ctx, request); } //handle mcp request String mcpEndpoint = mcpRequestHandler.getMcpEndpoint(); if (mcpEndpoint.equals(path)) { mcpRequestHandler.handle(ctx, request); isMcpHandled = true; return; } //handle webui requests if (path.equals("/ui")) { response = createRedirectResponse(request, "/ui/"); } if (path.equals("/ui/")) { path += "index.html"; } //try classpath resource first if (response == null) { response = readFileFromResource(request, path); } //try output dir later, avoid overlay classpath resources files if (response == null) { response = DirectoryBrowser.directView(dir, path, request, ctx); isFileResponseFinished = response != null; } //not found if (response == null) { response = createResponse(request, HttpResponseStatus.NOT_FOUND, "Not found"); } } catch (Throwable e) { logger.error("arthas process http request error: " + request.uri(), e); } finally { //If it is null, an error may occur if (response == null) { response = createResponse(request, HttpResponseStatus.INTERNAL_SERVER_ERROR, "Server error"); } if (!isFileResponseFinished && !isMcpHandled) { ChannelFuture future = writeResponse(ctx, response); future.addListener(ChannelFutureListener.CLOSE); } } } } private ChannelFuture writeResponse(ChannelHandlerContext ctx, HttpResponse response) { // try to add content-length header for DefaultFullHttpResponse if (!HttpUtil.isTransferEncodingChunked(response) && response instanceof DefaultFullHttpResponse) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, ((DefaultFullHttpResponse) response).content().readableBytes()); return ctx.writeAndFlush(response); } //chunk response ctx.write(response); return ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } private HttpResponse readFileFromResource(FullHttpRequest request, String path) throws IOException { DefaultFullHttpResponse fullResp = null; InputStream in = null; try { URL res = HttpTtyConnection.class.getResource("/com/taobao/arthas/core/http" + path); if (res != null) { fullResp = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.OK); in = res.openStream(); byte[] tmp = new byte[256]; for (int l = 0; l != -1; l = in.read(tmp)) { fullResp.content().writeBytes(tmp, 0, l); } int li = path.lastIndexOf('.'); if (li != -1 && li != path.length() - 1) { String ext = path.substring(li + 1); String contentType; if ("html".equals(ext)) { contentType = "text/html"; } else if ("js".equals(ext)) { contentType = "application/javascript"; } else if ("css".equals(ext)) { contentType = "text/css"; } else { contentType = null; } if (contentType != null) { fullResp.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType); } } } } finally { IOUtils.close(in); } return fullResp; } private static void send100Continue(ChannelHandlerContext ctx) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.CONTINUE); ctx.writeAndFlush(response); } public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { Logging.logReportedIoError(cause); ctx.close(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/DirectoryBrowser.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/DirectoryBrowser.java
package com.taobao.arthas.core.shell.term.impl.http; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; import com.alibaba.arthas.deps.org.slf4j.Logger; import com.alibaba.arthas.deps.org.slf4j.LoggerFactory; import com.taobao.arthas.common.ArthasConstants; import com.taobao.arthas.common.IOUtils; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelProgressiveFuture; import io.netty.channel.ChannelProgressiveFutureListener; import io.netty.channel.DefaultFileRegion; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpChunkedInput; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaderValues; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpUtil; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http.LastHttpContent; import io.netty.handler.ssl.SslHandler; import io.netty.handler.stream.ChunkedFile; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; /** * * @author hengyunabc 2019-11-06 * */ public class DirectoryBrowser { public static final String HTTP_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz"; public static final String HTTP_DATE_GMT_TIMEZONE = "GMT"; public static final long MIN_NETTY_DIRECT_SEND_SIZE = ArthasConstants.MAX_HTTP_CONTENT_LENGTH; private static final Logger logger = LoggerFactory.getLogger(DirectoryBrowser.class); //@formatter:off private static String pageHeader = "<!DOCTYPE html>\n" + "<html>\n" + "\n" + "<head>\n" + " <title>Arthas Resouces: %s</title>\n" + " <meta charset=\"utf-8\" name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" + " <style>\n" + "body {\n" + " background: #fff;\n" + "}\n" + " </style>\n" + "</head>\n" + "\n" + "<body>\n" + " <header>\n" + " <h1>%s</h1>\n" + " </header>\n" + " <hr/>\n" + " <main>\n" + " <pre id=\"contents\">\n"; private static String pageFooter = " </pre>\n" + " </main>\n" + " <hr/>\n" + "</body>\n" + "\n" + "</html>"; //@formatter:on private static String linePart1Str = "<a href=\"%s\" title=\"%s\">"; private static String linePart2Str = "%-60s"; static String renderDir(File dir, boolean printParentLink) { File[] listFiles = dir.listFiles(); StringBuilder sb = new StringBuilder(8192); String dirName = dir.getName() + "/"; sb.append(String.format(pageHeader, dirName, dirName)); if (printParentLink) { sb.append("<a href=\"../\" title=\"../\">../</a>\n"); } if (listFiles != null) { Arrays.sort(listFiles); for (File f : listFiles) { if (f.isDirectory()) { String name = f.getName() + "/"; String part1Format = String.format(linePart1Str, name, name, name); sb.append(part1Format); String linePart2 = name + "</a>"; String part2Format = String.format(linePart2Str, linePart2); sb.append(part2Format); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String modifyStr = simpleDateFormat.format(new Date(f.lastModified())); sb.append(modifyStr); sb.append(" - ").append("\r\n"); } } for (File f : listFiles) { if (f.isFile()) { String name = f.getName(); String part1Format = String.format(linePart1Str, name, name, name); sb.append(part1Format); String linePart2 = name + "</a>"; String part2Format = String.format(linePart2Str, linePart2); sb.append(part2Format); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String modifyStr = simpleDateFormat.format(new Date(f.lastModified())); sb.append(modifyStr); String sizeStr = String.format("%10d ", f.length()); sb.append(sizeStr).append("\r\n"); } } } sb.append(pageFooter); return sb.toString(); } /** * write data here,still return not null just to know succeeded. * @param dir * @param path * @param request * @param ctx * @return * @throws IOException */ public static DefaultFullHttpResponse directView(File dir, String path, FullHttpRequest request, ChannelHandlerContext ctx) throws IOException { if (path.startsWith("/")) { path = path.substring(1); } // path maybe: arthas-output/20201225-203454.svg // 需要取 dir的parent来去掉前缀 File file = new File(dir.getParent(), path); HttpVersion version = request.protocolVersion(); if (isSubFile(dir, file)) { DefaultFullHttpResponse fullResp = new DefaultFullHttpResponse(version, HttpResponseStatus.OK); if (file.isDirectory()) { if (!path.endsWith("/")) { fullResp.setStatus(HttpResponseStatus.FOUND).headers().set(HttpHeaderNames.LOCATION, "/" + path + "/"); } String renderResult = renderDir(file, !isSameFile(dir, file)); fullResp.content().writeBytes(renderResult.getBytes("utf-8")); fullResp.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=utf-8"); ctx.write(fullResp); ChannelFuture future = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); future.addListener(ChannelFutureListener.CLOSE); return fullResp; } else { logger.info("get file now. file:" + file.getPath()); if (file.isHidden() || !file.exists() || file.isDirectory() || !file.isFile()) { return null; } long fileLength = file.length(); if (fileLength < MIN_NETTY_DIRECT_SEND_SIZE){ FileInputStream fileInputStream = new FileInputStream(file); try { byte[] content = IOUtils.getBytes(fileInputStream); fullResp.content().writeBytes(content); HttpUtil.setContentLength(fullResp, fullResp.content().readableBytes()); } finally { IOUtils.close(fileInputStream); } ChannelFuture channelFuture = ctx.writeAndFlush(fullResp); channelFuture.addListener((ChannelFutureListener) future -> { if (future.isSuccess()) { ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); lastContentFuture.addListener(ChannelFutureListener.CLOSE); } else { future.channel().close(); } }); return fullResp; } logger.info("file {} size bigger than {}, send by future.",file.getName(), MIN_NETTY_DIRECT_SEND_SIZE); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpUtil.setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (HttpUtil.isKeepAlive(request)) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } // Write the initial line and the header. ctx.write(response); // Write the content. ChannelFuture sendFileFuture; ChannelFuture lastContentFuture; RandomAccessFile raf = new RandomAccessFile(file, "r"); // will closed by netty if (ctx.pipeline().get(SslHandler.class) == null) { sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); // Write the end marker. lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { sendFileFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise()); // HttpChunkedInput will write the end marker (LastHttpContent) for us. lastContentFuture = sendFileFuture; } sendFileFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { if (total < 0) { // total unknown logger.info(future.channel() + " Transfer progress: " + progress); } else { logger.info(future.channel() + " Transfer progress: " + progress + " / " + total); } } @Override public void operationComplete(ChannelProgressiveFuture future) { logger.info(future.channel() + " Transfer complete."); } }); // Decide whether to close the connection or not. if (!HttpUtil.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } return fullResp; } } return null; } private static void setDateAndCacheHeaders(HttpResponse response, File fileToCache) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE)); // Date header Calendar time = new GregorianCalendar(); response.headers().set(HttpHeaderNames.DATE, dateFormatter.format(time.getTime())); // Add cache headers time.add(Calendar.SECOND, 3600); response.headers().set(HttpHeaderNames.EXPIRES, dateFormatter.format(time.getTime())); response.headers().set(HttpHeaderNames.CACHE_CONTROL, "private, max-age=" + 3600); response.headers().set( HttpHeaderNames.LAST_MODIFIED, dateFormatter.format(new Date(fileToCache.lastModified()))); } private static void setContentTypeHeader(HttpResponse response, File file) { String contentType = "application/octet-stream"; // 暂时hardcode 大文件的content-type response.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType); } public static boolean isSubFile(File parent, File child) throws IOException { String parentPath = parent.getCanonicalPath(); String childPath = child.getCanonicalPath(); if (parentPath.equals(childPath) || childPath.startsWith(parent.getCanonicalPath() + File.separator)) { return true; } return false; } public static boolean isSameFile(File a, File b) { try { return a.getCanonicalPath().equals(b.getCanonicalPath()); } catch (IOException e) { return false; } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/package-info.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/package-info.java
package com.taobao.arthas.core.shell.term.impl.http;
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/BasicHttpAuthenticatorHandler.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/BasicHttpAuthenticatorHandler.java
package com.taobao.arthas.core.shell.term.impl.http; import com.alibaba.arthas.deps.org.slf4j.Logger; import com.alibaba.arthas.deps.org.slf4j.LoggerFactory; import com.taobao.arthas.common.ArthasConstants; import com.taobao.arthas.core.security.AuthUtils; import com.taobao.arthas.core.security.BasicPrincipal; import com.taobao.arthas.core.security.BearerPrincipal; import com.taobao.arthas.core.security.SecurityAuthenticator; import com.taobao.arthas.core.server.ArthasBootstrap; import com.taobao.arthas.core.shell.term.impl.http.session.HttpSession; import com.taobao.arthas.core.shell.term.impl.http.session.HttpSessionManager; import com.taobao.arthas.core.util.StringUtils; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.base64.Base64; import io.netty.handler.codec.http.*; import io.netty.util.Attribute; import javax.security.auth.Subject; import java.nio.charset.Charset; import java.security.Principal; import java.util.List; import java.util.Map; import static com.taobao.arthas.mcp.server.util.McpAuthExtractor.SUBJECT_ATTRIBUTE_KEY; /** * * @author hengyunabc 2021-03-03 * */ public final class BasicHttpAuthenticatorHandler extends ChannelDuplexHandler { private static final Logger logger = LoggerFactory.getLogger(BasicHttpAuthenticatorHandler.class); private HttpSessionManager httpSessionManager; private SecurityAuthenticator securityAuthenticator = ArthasBootstrap.getInstance().getSecurityAuthenticator(); public BasicHttpAuthenticatorHandler(HttpSessionManager httpSessionManager) { this.httpSessionManager = httpSessionManager; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 先处理非 HttpRequest 消息 if (!(msg instanceof HttpRequest)) { ctx.fireChannelRead(msg); return; } HttpRequest httpRequest = (HttpRequest) msg; HttpSession session = httpSessionManager.getOrCreateHttpSession(ctx, httpRequest); // 无论是否需要登录认证,都从 URL 中提取 userId extractAndSetUserIdFromUrl(httpRequest, session); if (!securityAuthenticator.needLogin()) { ctx.fireChannelRead(msg); return; } boolean authed = false; // 判断session里是否有已登录信息 if (session != null) { Object subjectObj = session.getAttribute(ArthasConstants.SUBJECT_KEY); if (subjectObj != null) { authed =true; setAuthenticatedSubject(ctx, session, subjectObj); } } Principal principal = null; boolean isMcpRequest = isMcpRequest(httpRequest); if (!authed) { if (isMcpRequest) { principal = extractMcpAuthSubject(httpRequest); } else { principal = extractBasicAuthSubject(httpRequest); if (principal == null) { principal = extractBasicAuthSubjectFromUrl(httpRequest); } } if (principal == null) { // 判断是否本地连接 principal = AuthUtils.localPrincipal(ctx); } Subject subject = securityAuthenticator.login(principal); if (subject != null) { authed = true; setAuthenticatedSubject(ctx, session, subject); } } if (!authed) { // restricted resource, so send back 401 to require valid username/password HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED); if (isMcpRequest) { response.headers() .add(HttpHeaderNames.WWW_AUTHENTICATE, "Bearer realm=\"arthas mcp\"") .add(HttpHeaderNames.WWW_AUTHENTICATE, "Basic realm=\"arthas mcp\""); } else { response.headers().set(HttpHeaderNames.WWW_AUTHENTICATE, "Basic realm=\"arthas webconsole\""); } response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain"); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0); ctx.writeAndFlush(response); // close the channel ctx.channel().close(); return; } ctx.fireChannelRead(msg); } private void setAuthenticatedSubject(ChannelHandlerContext ctx, HttpSession session, Object subject) { ctx.channel().attr(SUBJECT_ATTRIBUTE_KEY).set(subject); if (session != null) { session.setAttribute(ArthasConstants.SUBJECT_KEY, subject); } } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof HttpResponse) { // write cookie HttpResponse response = (HttpResponse) msg; Attribute<HttpSession> attribute = ctx.channel().attr(HttpSessionManager.SESSION_KEY); HttpSession session = attribute.get(); if (session != null) { HttpSessionManager.setSessionCookie(response, session); } } super.write(ctx, msg, promise); } /** * 从 url 参数里提取 userId 并存入 HttpSession * * @param request * @param session */ protected static void extractAndSetUserIdFromUrl(HttpRequest request, HttpSession session) { if (session == null) { return; } QueryStringDecoder queryDecoder = new QueryStringDecoder(request.uri()); Map<String, List<String>> parameters = queryDecoder.parameters(); List<String> userIds = parameters.get(ArthasConstants.USER_ID_KEY); if (userIds != null && !userIds.isEmpty()) { String userId = userIds.get(0); if (!StringUtils.isBlank(userId)) { session.setAttribute(ArthasConstants.USER_ID_KEY, userId); logger.debug("Extracted userId from url: {}", userId); } } } /** * 从 url 参数里提取 ?username=hello&password=world * * @param request * @return */ protected static BasicPrincipal extractBasicAuthSubjectFromUrl(HttpRequest request) { QueryStringDecoder queryDecoder = new QueryStringDecoder(request.uri()); Map<String, List<String>> parameters = queryDecoder.parameters(); List<String> passwords = parameters.get(ArthasConstants.PASSWORD_KEY); if (passwords == null || passwords.size() == 0) { return null; } String password = passwords.get(0); String username = ArthasConstants.DEFAULT_USERNAME; List<String> usernames = parameters.get(ArthasConstants.USERNAME_KEY); if (usernames != null && !usernames.isEmpty()) { username = usernames.get(0); } BasicPrincipal principal = new BasicPrincipal(username, password); logger.debug("Extracted Basic Auth principal from url: {}", principal); return principal; } /** * Extracts the username and password details from the HTTP basic header * Authorization. * <p/> * This requires that the <tt>Authorization</tt> HTTP header is provided, and * its using Basic. Currently Digest is <b>not</b> supported. * * @return {@link HttpPrincipal} with username and password details, or * <tt>null</tt> if not possible to extract */ protected static BasicPrincipal extractBasicAuthSubject(HttpRequest request) { String auth = request.headers().get(HttpHeaderNames.AUTHORIZATION); if (auth != null) { String constraint = StringUtils.before(auth, " "); if (constraint != null) { if ("Basic".equalsIgnoreCase(constraint.trim())) { String decoded = StringUtils.after(auth, " "); if (decoded == null) { logger.error("Extracted Basic Auth principal failed, bad auth String: {}", auth); return null; } // the decoded part is base64 encoded, so we need to decode that ByteBuf buf = Unpooled.wrappedBuffer(decoded.getBytes()); ByteBuf out = Base64.decode(buf); String userAndPw = out.toString(Charset.defaultCharset()); String username = StringUtils.before(userAndPw, ":"); String password = StringUtils.after(userAndPw, ":"); BasicPrincipal principal = new BasicPrincipal(username, password); logger.debug("Extracted Basic Auth principal from HTTP header: {}", principal); return principal; } } } return null; } /** * 判断是否为MCP请求 * * @param request */ protected static boolean isMcpRequest(HttpRequest request) { try { String path = new java.net.URI(request.uri()).getPath(); if (path == null) { return false; } String mcpEndpoint = ArthasBootstrap.getInstance().getConfigure().getMcpEndpoint(); if (mcpEndpoint == null || mcpEndpoint.trim().isEmpty()) { // MCP 服务器未配置,不处理 MCP 请求 return false; } return mcpEndpoint.equals(path); } catch (Exception e) { logger.debug("Failed to parse request URI: {}", request.uri(), e); return false; } } /** * 为MCP请求提取认证主体,支持Bearer Token和Basic Auth两种方式 * * @param request */ protected static Principal extractMcpAuthSubject(HttpRequest request) { // 首先尝试Bearer Token认证 BearerPrincipal tokenPrincipal = extractBearerTokenSubject(request); if (tokenPrincipal != null) { return tokenPrincipal; } // 然后尝试Basic Auth认证 BasicPrincipal basicPrincipal = extractBasicAuthSubject(request); if (basicPrincipal != null) { return basicPrincipal; } // 最后尝试从URL参数提取 return extractBasicAuthSubjectFromUrl(request); } /** * 从Authorization header中提取Bearer Token * * @param request */ protected static BearerPrincipal extractBearerTokenSubject(HttpRequest request) { String auth = request.headers().get(HttpHeaderNames.AUTHORIZATION); if (auth != null) { String constraint = StringUtils.before(auth, " "); if (constraint != null) { if ("Bearer".equalsIgnoreCase(constraint.trim())) { String token = StringUtils.after(auth, " "); if (token == null || token.trim().isEmpty()) { logger.error("Extracted Bearer Token failed, bad auth String: {}", auth); return null; } BearerPrincipal principal = new BearerPrincipal(token.trim()); logger.debug("Extracted Bearer Token principal: {}", principal); return principal; } } } return null; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/TtyWebSocketFrameHandler.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/TtyWebSocketFrameHandler.java
/* * Copyright 2015 Julien Viet * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taobao.arthas.core.shell.term.impl.http; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.group.ChannelGroup; import io.netty.handler.codec.http.websocketx.PingWebSocketFrame; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.timeout.IdleStateEvent; import io.termd.core.function.Consumer; import io.termd.core.http.HttpTtyConnection; import io.termd.core.tty.TtyConnection; /** * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> */ public class TtyWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { private final ChannelGroup group; private final Consumer<TtyConnection> handler; private ChannelHandlerContext context; private HttpTtyConnection conn; public TtyWebSocketFrameHandler(ChannelGroup group, Consumer<TtyConnection> handler) { this.group = group; this.handler = handler; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); context = ctx; } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) { ctx.pipeline().remove(HttpRequestHandler.class); group.add(ctx.channel()); conn = new ExtHttpTtyConnection(context); handler.accept(conn); } else if (evt instanceof IdleStateEvent) { ctx.writeAndFlush(new PingWebSocketFrame()); } else { super.userEventTriggered(ctx, evt); } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { HttpTtyConnection tmp = conn; context = null; conn = null; if (tmp != null) { Consumer<Void> closeHandler = tmp.getCloseHandler(); if (closeHandler != null) { closeHandler.accept(null); } } } @Override public void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { conn.writeToDecoder(msg.text()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/LocalTtyServerInitializer.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/LocalTtyServerInitializer.java
package com.taobao.arthas.core.shell.term.impl.http; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.group.ChannelGroup; import io.netty.channel.local.LocalChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.stream.ChunkedWriteHandler; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.concurrent.EventExecutorGroup; import io.termd.core.function.Consumer; import io.termd.core.tty.TtyConnection; import com.taobao.arthas.common.ArthasConstants; /** * * @author hengyunabc 2020-09-02 * */ public class LocalTtyServerInitializer extends ChannelInitializer<LocalChannel> { private final ChannelGroup group; private final Consumer<TtyConnection> handler; private EventExecutorGroup workerGroup; public LocalTtyServerInitializer(ChannelGroup group, Consumer<TtyConnection> handler, EventExecutorGroup workerGroup) { this.group = group; this.handler = handler; this.workerGroup = workerGroup; } @Override protected void initChannel(LocalChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new ChunkedWriteHandler()); pipeline.addLast(new HttpObjectAggregator(ArthasConstants.MAX_HTTP_CONTENT_LENGTH)); pipeline.addLast(workerGroup, "HttpRequestHandler", new HttpRequestHandler(ArthasConstants.DEFAULT_WEBSOCKET_PATH)); pipeline.addLast(new WebSocketServerProtocolHandler(ArthasConstants.DEFAULT_WEBSOCKET_PATH, null, false, ArthasConstants.MAX_HTTP_CONTENT_LENGTH, false, true)); pipeline.addLast(new IdleStateHandler(0, 0, ArthasConstants.WEBSOCKET_IDLE_SECONDS)); pipeline.addLast(new TtyWebSocketFrameHandler(group, handler)); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/ExtHttpTtyConnection.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/ExtHttpTtyConnection.java
package com.taobao.arthas.core.shell.term.impl.http; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import com.taobao.arthas.common.ArthasConstants; import com.taobao.arthas.core.shell.term.impl.http.session.HttpSession; import com.taobao.arthas.core.shell.term.impl.http.session.HttpSessionManager; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.termd.core.http.HttpTtyConnection; /** * 从http请求传递过来的 session 信息。解析websocket创建的 term 还需要登录验证问题 * * @author hengyunabc 2021-03-04 * */ public class ExtHttpTtyConnection extends HttpTtyConnection { private ChannelHandlerContext context; public ExtHttpTtyConnection(ChannelHandlerContext context) { this.context = context; } @Override protected void write(byte[] buffer) { ByteBuf byteBuf = Unpooled.buffer(); byteBuf.writeBytes(buffer); if (context != null) { context.writeAndFlush(new TextWebSocketFrame(byteBuf)); } } @Override public void schedule(Runnable task, long delay, TimeUnit unit) { if (context != null) { context.executor().schedule(task, delay, unit); } } @Override public void execute(Runnable task) { if (context != null) { context.executor().execute(task); } } @Override public void close() { if (context != null) { context.close(); } } public Map<String, Object> extSessions() { if (context != null) { HttpSession httpSession = HttpSessionManager.getHttpSessionFromContext(context); if (httpSession != null) { Map<String, Object> result = new HashMap<String, Object>(); Object subject = httpSession.getAttribute(ArthasConstants.SUBJECT_KEY); if (subject != null) { result.put(ArthasConstants.SUBJECT_KEY, subject); } // pass userId from httpSession to arthas session Object userId = httpSession.getAttribute(ArthasConstants.USER_ID_KEY); if (userId != null) { result.put(ArthasConstants.USER_ID_KEY, userId); } if (!result.isEmpty()) { return result; } } } return Collections.emptyMap(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/api/ApiRequest.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/api/ApiRequest.java
package com.taobao.arthas.core.shell.term.impl.http.api; /** * Http Api request * * @author gongdewei 2020-03-19 */ public class ApiRequest { private String action; private String command; private String requestId; private String sessionId; private String consumerId; private Integer execTimeout; private String userId; @Override public String toString() { return "ApiRequest{" + "action='" + action + '\'' + ", command='" + command + '\'' + ", requestId='" + requestId + '\'' + ", sessionId='" + sessionId + '\'' + ", consumerId='" + consumerId + '\'' + ", execTimeout=" + execTimeout + ", userId='" + userId + '\'' + '}'; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public String getCommand() { return command; } public void setCommand(String command) { this.command = command; } public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public String getConsumerId() { return consumerId; } public void setConsumerId(String consumerId) { this.consumerId = consumerId; } public Integer getExecTimeout() { return execTimeout; } public void setExecTimeout(Integer execTimeout) { this.execTimeout = execTimeout; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/api/ApiException.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/api/ApiException.java
package com.taobao.arthas.core.shell.term.impl.http.api; /** * Http Api exception * @author gongdewei 2020-03-19 */ public class ApiException extends Exception { public ApiException(String message) { super(message); } public ApiException(String message, Throwable cause) { super(message, cause); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/api/HttpApiHandler.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/api/HttpApiHandler.java
package com.taobao.arthas.core.shell.term.impl.http.api; import com.alibaba.arthas.deps.org.slf4j.Logger; import com.alibaba.arthas.deps.org.slf4j.LoggerFactory; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.filter.ValueFilter; import com.taobao.arthas.common.ArthasConstants; import com.taobao.arthas.common.PidUtils; 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; import com.taobao.arthas.core.shell.handlers.Handler; import com.taobao.arthas.core.shell.history.HistoryManager; import com.taobao.arthas.core.shell.session.Session; import com.taobao.arthas.core.shell.session.SessionManager; import com.taobao.arthas.core.shell.system.Job; import com.taobao.arthas.core.shell.system.JobController; import com.taobao.arthas.core.shell.system.JobListener; import com.taobao.arthas.core.shell.system.impl.InternalCommandManager; import com.taobao.arthas.core.shell.term.SignalHandler; import com.taobao.arthas.core.shell.term.Term; import com.taobao.arthas.core.shell.term.impl.http.session.HttpSession; import com.taobao.arthas.core.shell.term.impl.http.session.HttpSessionManager; import com.taobao.arthas.core.util.ArthasBanner; import com.taobao.arthas.core.util.DateUtils; import com.taobao.arthas.core.util.StringUtils; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.*; import io.netty.util.CharsetUtil; import io.termd.core.function.Function; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * Http Restful Api Handler * * @author gongdewei 2020-03-18 */ public class HttpApiHandler { private static final Logger logger = LoggerFactory.getLogger(HttpApiHandler.class); private static final ValueFilter[] JSON_FILTERS = new ValueFilter[] { new ObjectVOFilter() }; private static final String ONETIME_SESSION_KEY = "oneTimeSession"; public static final int DEFAULT_EXEC_TIMEOUT = 30000; private final SessionManager sessionManager; private final InternalCommandManager commandManager; private final JobController jobController; private final HistoryManager historyManager; public HttpApiHandler(HistoryManager historyManager, SessionManager sessionManager) { this.historyManager = historyManager; this.sessionManager = sessionManager; commandManager = this.sessionManager.getCommandManager(); jobController = this.sessionManager.getJobController(); } public HttpResponse handle(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { ApiResponse result; String requestBody = null; String requestId = null; try { HttpMethod method = request.method(); if (HttpMethod.POST.equals(method)) { requestBody = getBody(request); ApiRequest apiRequest = parseRequest(requestBody); requestId = apiRequest.getRequestId(); result = processRequest(ctx, apiRequest); } else { result = createResponse(ApiState.REFUSED, "Unsupported http method: " + method.name()); } } catch (Throwable e) { result = createResponse(ApiState.FAILED, "Process request error: " + e.getMessage()); logger.error("arthas process http api request error: " + request.uri() + ", request body: " + requestBody, e); } if (result == null) { result = createResponse(ApiState.FAILED, "The request was not processed"); } result.setRequestId(requestId); byte[] jsonBytes = JSON.toJSONBytes(result, JSON_FILTERS); // create http response DefaultFullHttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.OK, Unpooled.wrappedBuffer(jsonBytes)); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=utf-8"); return response; } private ApiRequest parseRequest(String requestBody) throws ApiException { if (StringUtils.isBlank(requestBody)) { throw new ApiException("parse request failed: request body is empty"); } try { //ObjectMapper objectMapper = new ObjectMapper(); //return objectMapper.readValue(requestBody, ApiRequest.class); return JSON.parseObject(requestBody, ApiRequest.class); } catch (Exception e) { throw new ApiException("parse request failed: " + e.getMessage(), e); } } private ApiResponse processRequest(ChannelHandlerContext ctx, ApiRequest apiRequest) { String actionStr = apiRequest.getAction(); try { if (StringUtils.isBlank(actionStr)) { throw new ApiException("'action' is required"); } ApiAction action; try { action = ApiAction.valueOf(actionStr.trim().toUpperCase()); } catch (IllegalArgumentException e) { throw new ApiException("unknown action: " + actionStr); } //no session required if (ApiAction.INIT_SESSION.equals(action)) { return processInitSessionRequest(apiRequest); } //required session Session session = null; boolean allowNullSession = ApiAction.EXEC.equals(action); String sessionId = apiRequest.getSessionId(); if (StringUtils.isBlank(sessionId)) { 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 if (session == null) { session = sessionManager.createSession(); session.put(ONETIME_SESSION_KEY, new Object()); } // 请求到达这里,如果有需要鉴权,则已经在前面的handler里处理过了 // 如果有鉴权取到的 Subject,则传递到 arthas的session里 HttpSession httpSession = HttpSessionManager.getHttpSessionFromContext(ctx); if (httpSession != null) { Object subject = httpSession.getAttribute(ArthasConstants.SUBJECT_KEY); if (subject != null) { session.put(ArthasConstants.SUBJECT_KEY, subject); } // get userId from httpSession Object userId = httpSession.getAttribute(ArthasConstants.USER_ID_KEY); if (userId != null && session.getUserId() == null) { session.setUserId((String) userId); } } // set userId from apiRequest if provided if (!StringUtils.isBlank(apiRequest.getUserId())) { session.setUserId(apiRequest.getUserId()); } //dispatch requests ApiResponse response = dispatchRequest(action, apiRequest, session); if (response != null) { return response; } } catch (ApiException e) { logger.info("process http api request failed: {}", e.getMessage()); return createResponse(ApiState.FAILED, e.getMessage()); } catch (Throwable e) { logger.error("process http api request failed: " + e.getMessage(), e); return createResponse(ApiState.FAILED, "process http api request failed: " + e.getMessage()); } return createResponse(ApiState.REFUSED, "Unsupported action: " + actionStr); } private ApiResponse dispatchRequest(ApiAction action, ApiRequest apiRequest, Session session) throws ApiException { switch (action) { case EXEC: return processExecRequest(apiRequest, session); case ASYNC_EXEC: return processAsyncExecRequest(apiRequest, session); case INTERRUPT_JOB: return processInterruptJob(apiRequest, session); case PULL_RESULTS: return processPullResultsRequest(apiRequest, session); case SESSION_INFO: return processSessionInfoRequest(apiRequest, session); case JOIN_SESSION: return processJoinSessionRequest(apiRequest, session); case CLOSE_SESSION: return processCloseSessionRequest(apiRequest, session); case INIT_SESSION: break; } return null; } private ApiResponse processInitSessionRequest(ApiRequest apiRequest) throws ApiException { ApiResponse response = new ApiResponse(); //create session Session session = sessionManager.createSession(); if (session != null) { // set userId if provided if (!StringUtils.isBlank(apiRequest.getUserId())) { session.setUserId(apiRequest.getUserId()); } //Result Distributor SharingResultDistributorImpl resultDistributor = new SharingResultDistributorImpl(session); //create consumer ResultConsumer resultConsumer = new ResultConsumerImpl(); resultDistributor.addConsumer(resultConsumer); session.setResultDistributor(resultDistributor); resultDistributor.appendResult(new MessageModel("Welcome to arthas!")); //welcome message WelcomeModel welcomeModel = new WelcomeModel(); welcomeModel.setVersion(ArthasBanner.version()); welcomeModel.setWiki(ArthasBanner.wiki()); welcomeModel.setTutorials(ArthasBanner.tutorials()); welcomeModel.setMainClass(PidUtils.mainClass()); welcomeModel.setPid(PidUtils.currentPid()); welcomeModel.setTime(DateUtils.getCurrentDateTime()); resultDistributor.appendResult(welcomeModel); //allow input updateSessionInputStatus(session, InputStatus.ALLOW_INPUT); response.setSessionId(session.getSessionId()) .setConsumerId(resultConsumer.getConsumerId()) .setState(ApiState.SUCCEEDED); } else { throw new ApiException("create api session failed"); } return response; } /** * Update session input status for all consumer * * @param session * @param inputStatus */ private void updateSessionInputStatus(Session session, InputStatus inputStatus) { SharingResultDistributor resultDistributor = session.getResultDistributor(); if (resultDistributor != null) { resultDistributor.appendResult(new InputStatusModel(inputStatus)); } } private ApiResponse processJoinSessionRequest(ApiRequest apiRequest, Session session) { //create consumer ResultConsumer resultConsumer = new ResultConsumerImpl(); //disable input and interrupt resultConsumer.appendResult(new InputStatusModel(InputStatus.DISABLED)); SharingResultDistributor resultDistributor = session.getResultDistributor(); if (resultDistributor != null) { resultDistributor.addConsumer(resultConsumer); } ApiResponse response = new ApiResponse(); response.setSessionId(session.getSessionId()) .setConsumerId(resultConsumer.getConsumerId()) .setState(ApiState.SUCCEEDED); return response; } private ApiResponse processSessionInfoRequest(ApiRequest apiRequest, Session session) { ApiResponse response = new ApiResponse(); Map<String, Object> body = new TreeMap<String, Object>(); body.put("pid", session.getPid()); body.put("createTime", session.getCreateTime()); body.put("lastAccessTime", session.getLastAccessTime()); response.setState(ApiState.SUCCEEDED) .setSessionId(session.getSessionId()) //.setConsumerId(consumerId) .setBody(body); return response; } private ApiResponse processCloseSessionRequest(ApiRequest apiRequest, Session session) { sessionManager.removeSession(session.getSessionId()); ApiResponse response = new ApiResponse(); response.setState(ApiState.SUCCEEDED); return response; } /** * Execute command sync, wait for job finish or timeout, sending results immediately * * @param apiRequest * @param session * @return */ private ApiResponse processExecRequest(ApiRequest apiRequest, Session session) { boolean oneTimeAccess = false; if (session.get(ONETIME_SESSION_KEY) != null) { oneTimeAccess = true; } try { 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; } 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; } 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); 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 (oneTimeAccess) { sessionManager.removeSession(session.getSessionId()); } } } /** * Execute command async, create and schedule the job running, but no wait for the results. * * @param apiRequest * @param session * @return */ private ApiResponse processAsyncExecRequest(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; } int lock = session.getLock(); 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; } //create job Job job = this.createJob(commandLine, session, session.getResultDistributor()); body.put("jobId", job.id()); body.put("jobStatus", job.status()); response.setState(ApiState.SCHEDULED); //add command before exec job CommandRequestModel commandRequestModel = new CommandRequestModel(commandLine, response.getState().name()); commandRequestModel.setJobId(job.id()); SharingResultDistributor resultDistributor = session.getResultDistributor(); if (resultDistributor != null) { resultDistributor.appendResult(commandRequestModel); } session.setForegroundJob(job); updateSessionInputStatus(session, InputStatus.ALLOW_INTERRUPT); //run job job.run(); return response; } catch (Throwable e) { logger.error("Async exec command failed:" + e.getMessage() + ", command:" + commandLine, e); response.setState(ApiState.FAILED).setMessage("Async exec command failed:" + e.getMessage()); CommandRequestModel commandRequestModel = new CommandRequestModel(commandLine, response.getState().name(), response.getMessage()); session.getResultDistributor().appendResult(commandRequestModel); return response; } finally { if (session.getLock() == lock) { session.unLock(); } } } private ApiResponse processInterruptJob(ApiRequest apiRequest, Session session) { Job job = session.getForegroundJob(); if (job == null) { return new ApiResponse().setState(ApiState.FAILED).setMessage("no foreground job is running"); } job.interrupt(); Map<String, Object> body = new TreeMap<String, Object>(); body.put("jobId", job.id()); body.put("jobStatus", job.status()); return new ApiResponse() .setState(ApiState.SUCCEEDED) .setBody(body); } /** * Pull results from result queue * * @param apiRequest * @param session * @return */ private ApiResponse processPullResultsRequest(ApiRequest apiRequest, Session session) throws ApiException { String consumerId = apiRequest.getConsumerId(); if (StringUtils.isBlank(consumerId)) { throw new ApiException("'consumerId' is required"); } ResultConsumer consumer = null; SharingResultDistributor resultDistributor = session.getResultDistributor(); if (resultDistributor != null) { consumer = resultDistributor.getConsumer(consumerId); } if (consumer == null) { throw new ApiException("consumer not found: " + consumerId); } List<ResultModel> results = consumer.pollResults(); Map<String, Object> body = new TreeMap<String, Object>(); body.put("results", results); ApiResponse response = new ApiResponse(); response.setState(ApiState.SUCCEEDED) .setSessionId(session.getSessionId()) .setConsumerId(consumerId) .setBody(body); return response; } private boolean waitForJob(Job job, int timeout) { long startTime = System.currentTimeMillis(); while (true) { switch (job.status()) { case STOPPED: case TERMINATED: return true; } if (System.currentTimeMillis() - startTime > timeout) { return false; } try { Thread.sleep(100); } catch (InterruptedException e) { } } } private synchronized Job createJob(List<CliToken> args, Session session, ResultDistributor resultDistributor) { Job job = jobController.createJob(commandManager, args, session, new ApiJobHandler(session), new ApiTerm(session), resultDistributor); return job; } private Job createJob(String line, Session session, ResultDistributor resultDistributor) { historyManager.addHistory(line); return createJob(CliTokens.tokenize(line), session, resultDistributor); } private ApiResponse createResponse(ApiState apiState, String message) { ApiResponse apiResponse = new ApiResponse(); apiResponse.setState(apiState); apiResponse.setMessage(message); return apiResponse; } private String getBody(FullHttpRequest request) { ByteBuf buf = request.content(); return buf.toString(CharsetUtil.UTF_8); } private class ApiJobHandler implements JobListener { private Session session; public ApiJobHandler(Session session) { this.session = session; } @Override public void onForeground(Job job) { session.setForegroundJob(job); } @Override public void onBackground(Job job) { if (session.getForegroundJob() == job) { session.setForegroundJob(null); updateSessionInputStatus(session, InputStatus.ALLOW_INPUT); } } @Override public void onTerminated(Job job) { if (session.getForegroundJob() == job) { session.setForegroundJob(null); updateSessionInputStatus(session, InputStatus.ALLOW_INPUT); } } @Override public void onSuspend(Job job) { if (session.getForegroundJob() == job) { session.setForegroundJob(null); updateSessionInputStatus(session, InputStatus.ALLOW_INPUT); } } } private static class ApiTerm implements Term { private Session session; public ApiTerm(Session session) { this.session = session; } @Override public Term resizehandler(Handler<Void> handler) { return this; } @Override public String type() { return "web"; } @Override public int width() { return 1000; } @Override public int height() { return 200; } @Override public Term stdinHandler(Handler<String> handler) { return this; } @Override public Term stdoutHandler(Function<String, String> handler) { return this; } @Override public Term write(String data) { return this; } @Override public long lastAccessedTime() { return session.getLastAccessTime(); } @Override public Term echo(String text) { return this; } @Override public Term setSession(Session session) { return this; } @Override public Term interruptHandler(SignalHandler handler) { return this; } @Override public Term suspendHandler(SignalHandler handler) { return this; } @Override public void readline(String prompt, Handler<String> lineHandler) { } @Override public void readline(String prompt, Handler<String> lineHandler, Handler<Completion> completionHandler) { } @Override public Term closeHandler(Handler<Void> handler) { return this; } @Override public void close() { } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/api/ApiAction.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/api/ApiAction.java
package com.taobao.arthas.core.shell.term.impl.http.api; /** * Http api action enums * * @author gongdewei 2020-03-25 */ public enum ApiAction { /** * Execute command synchronized */ EXEC, /** * Execute command async */ ASYNC_EXEC, /** * Interrupt executing job */ INTERRUPT_JOB, /** * Pull the results from result queue of the session */ PULL_RESULTS, /** * Create a new session */ INIT_SESSION, /** * Join a exist session */ JOIN_SESSION, /** * Terminate the session */ CLOSE_SESSION, /** * Get session info */ SESSION_INFO }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/api/ApiState.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/api/ApiState.java
package com.taobao.arthas.core.shell.term.impl.http.api; /** * Http API response state * * @author gongdewei 2020-03-19 */ public enum ApiState { /** * Scheduled async exec job */ SCHEDULED, // RUNNING, /** * Request processed successfully */ SUCCEEDED, /** * Request processing interrupt */ INTERRUPTED, /** * Request processing failed */ FAILED, /** * Request is refused */ REFUSED }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/api/ObjectVOFilter.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/api/ObjectVOFilter.java
package com.taobao.arthas.core.shell.term.impl.http.api; import com.alibaba.fastjson2.filter.ValueFilter; import com.taobao.arthas.core.command.model.ObjectVO; import com.taobao.arthas.core.util.StringUtils; import com.taobao.arthas.core.view.ObjectView; /** * @author hengyunabc 2022-08-24 * */ public class ObjectVOFilter implements ValueFilter { @Override public Object apply(Object object, String name, Object value) { if (value instanceof ObjectVO) { ObjectVO vo = (ObjectVO) value; String resultStr = StringUtils.objectToString(vo.needExpand() ? new ObjectView(vo).draw() : value); return resultStr; } return value; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/api/ApiResponse.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/api/ApiResponse.java
package com.taobao.arthas.core.shell.term.impl.http.api; /** * Http Api exception * @author gongdewei 2020-03-19 */ public class ApiResponse<T> { private String requestId; private ApiState state; private String message; private String sessionId; private String consumerId; private String jobId; private T body; public String getRequestId() { return requestId; } public ApiResponse<T> setRequestId(String requestId) { this.requestId = requestId; return this; } public ApiState getState() { return state; } public ApiResponse<T> setState(ApiState state) { this.state = state; return this; } public String getMessage() { return message; } public ApiResponse<T> setMessage(String message) { this.message = message; return this; } public String getSessionId() { return sessionId; } public ApiResponse<T> setSessionId(String sessionId) { this.sessionId = sessionId; return this; } public String getConsumerId() { return consumerId; } public ApiResponse<T> setConsumerId(String consumerId) { this.consumerId = consumerId; return this; } public String getJobId() { return jobId; } public ApiResponse<T> setJobId(String jobId) { this.jobId = jobId; return this; } public T getBody() { return body; } public ApiResponse<T> setBody(T body) { this.body = body; return this; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/session/LRUCache.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/session/LRUCache.java
package com.taobao.arthas.core.shell.term.impl.http.session; import java.util.LinkedHashMap; import java.util.Collection; import java.util.Map; import java.util.ArrayList; /** * An LRU cache, based on <code>LinkedHashMap</code>. * * <p> * This cache has a fixed maximum number of elements (<code>cacheSize</code>). * If the cache is full and another entry is added, the LRU (least recently * used) entry is dropped. * * <p> * This class is thread-safe. All methods of this class are synchronized. * * <p> * Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland<br> * Multi-licensed: EPL / LGPL / GPL / AL / BSD. */ public class LRUCache<K, V> { private static final float hashTableLoadFactor = 0.75f; private LinkedHashMap<K, V> map; private int cacheSize; /** * Creates a new LRU cache. * * @param cacheSize the maximum number of entries that will be kept in this * cache. */ public LRUCache(int cacheSize) { this.cacheSize = cacheSize; int hashTableCapacity = (int) Math.ceil(cacheSize / hashTableLoadFactor) + 1; map = new LinkedHashMap<K, V>(hashTableCapacity, hashTableLoadFactor, true) { // (an anonymous inner class) private static final long serialVersionUID = 1; @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > LRUCache.this.cacheSize; } }; } /** * Retrieves an entry from the cache.<br> * The retrieved entry becomes the MRU (most recently used) entry. * * @param key the key whose associated value is to be returned. * @return the value associated to this key, or null if no value with this key * exists in the cache. */ public synchronized V get(K key) { return map.get(key); } /** * Adds an entry to this cache. The new entry becomes the MRU (most recently * used) entry. If an entry with the specified key already exists in the cache, * it is replaced by the new entry. If the cache is full, the LRU (least * recently used) entry is removed from the cache. * * @param key the key with which the specified value is to be associated. * @param value a value to be associated with the specified key. */ public synchronized void put(K key, V value) { map.put(key, value); } /** * Clears the cache. */ public synchronized void clear() { map.clear(); } /** * Returns the number of used entries in the cache. * * @return the number of entries currently in the cache. */ public synchronized int usedEntries() { return map.size(); } /** * Returns a <code>Collection</code> that contains a copy of all cache entries. * * @return a <code>Collection</code> with a copy of the cache content. */ public synchronized Collection<Map.Entry<K, V>> getAll() { return new ArrayList<Map.Entry<K, V>>(map.entrySet()); } } // end class LRUCache
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/session/SimpleHttpSession.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/session/SimpleHttpSession.java
package com.taobao.arthas.core.shell.term.impl.http.session; import java.util.Collections; import java.util.Enumeration; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.taobao.arthas.core.util.StringUtils; /** * * @author hengyunabc 2021-03-03 * */ public class SimpleHttpSession implements HttpSession { private Map<String, Object> attributes = new ConcurrentHashMap<String, Object>(); private String id; public SimpleHttpSession() { id = StringUtils.randomString(32); } @Override public long getCreationTime() { return 0; } @Override public String getId() { return id; } @Override public long getLastAccessedTime() { return 0; } @Override public void setMaxInactiveInterval(int interval) { } @Override public int getMaxInactiveInterval() { return 0; } @Override public Object getAttribute(String name) { return attributes.get(name); } @Override public Enumeration<String> getAttributeNames() { return Collections.enumeration(this.attributes.keySet()); } @Override public void setAttribute(String name, Object value) { attributes.put(name, value); } @Override public void removeAttribute(String name) { attributes.remove(name); } @Override public void invalidate() { } @Override public boolean isNew() { return false; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/session/HttpSession.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/session/HttpSession.java
package com.taobao.arthas.core.shell.term.impl.http.session; import java.util.Enumeration; /** * * @author hengyunabc 2021-03-03 * */ public interface HttpSession { /** * Returns the time when this session was created, measured in milliseconds * since midnight January 1, 1970 GMT. * * @return a <code>long</code> specifying when this session was created, * expressed in milliseconds since 1/1/1970 GMT * @exception IllegalStateException if this method is called on an invalidated * session */ public long getCreationTime(); /** * Returns a string containing the unique identifier assigned to this session. * The identifier is assigned by the servlet container and is implementation * dependent. * * @return a string specifying the identifier assigned to this session * @exception IllegalStateException if this method is called on an invalidated * session */ public String getId(); /** * Returns the last time the client sent a request associated with this session, * as the number of milliseconds since midnight January 1, 1970 GMT, and marked * by the time the container received the request. * <p> * Actions that your application takes, such as getting or setting a value * associated with the session, do not affect the access time. * * @return a <code>long</code> representing the last time the client sent a * request associated with this session, expressed in milliseconds since * 1/1/1970 GMT * @exception IllegalStateException if this method is called on an invalidated * session */ public long getLastAccessedTime(); /** * Specifies the time, in seconds, between client requests before the servlet * container will invalidate this session. A zero or negative time indicates * that the session should never timeout. * * @param interval An integer specifying the number of seconds */ public void setMaxInactiveInterval(int interval); /** * Returns the maximum time interval, in seconds, that the servlet container * will keep this session open between client accesses. After this interval, the * servlet container will invalidate the session. The maximum time interval can * be set with the <code>setMaxInactiveInterval</code> method. A zero or * negative time indicates that the session should never timeout. * * @return an integer specifying the number of seconds this session remains open * between client requests * @see #setMaxInactiveInterval */ public int getMaxInactiveInterval(); /** * Returns the object bound with the specified name in this session, or * <code>null</code> if no object is bound under the name. * * @param name a string specifying the name of the object * @return the object with the specified name * @exception IllegalStateException if this method is called on an invalidated * session */ public Object getAttribute(String name); /** * Returns an <code>Enumeration</code> of <code>String</code> objects containing * the names of all the objects bound to this session. * * @return an <code>Enumeration</code> of <code>String</code> objects specifying * the names of all the objects bound to this session * @exception IllegalStateException if this method is called on an invalidated * session */ public Enumeration<String> getAttributeNames(); /** * Binds an object to this session, using the name specified. If an object of * the same name is already bound to the session, the object is replaced. * <p> * After this method executes, and if the new object implements * <code>HttpSessionBindingListener</code>, the container calls * <code>HttpSessionBindingListener.valueBound</code>. The container then * notifies any <code>HttpSessionAttributeListener</code>s in the web * application. * <p> * If an object was already bound to this session of this name that implements * <code>HttpSessionBindingListener</code>, its * <code>HttpSessionBindingListener.valueUnbound</code> method is called. * <p> * If the value passed in is null, this has the same effect as calling * <code>removeAttribute()</code>. * * @param name the name to which the object is bound; cannot be null * @param value the object to be bound * @exception IllegalStateException if this method is called on an invalidated * session */ public void setAttribute(String name, Object value); /** * Removes the object bound with the specified name from this session. If the * session does not have an object bound with the specified name, this method * does nothing. * <p> * After this method executes, and if the object implements * <code>HttpSessionBindingListener</code>, the container calls * <code>HttpSessionBindingListener.valueUnbound</code>. The container then * notifies any <code>HttpSessionAttributeListener</code>s in the web * application. * * @param name the name of the object to remove from this session * @exception IllegalStateException if this method is called on an invalidated * session */ public void removeAttribute(String name); /** * Invalidates this session then unbinds any objects bound to it. * * @exception IllegalStateException if this method is called on an already * invalidated session */ public void invalidate(); /** * Returns <code>true</code> if the client does not yet know about the session * or if the client chooses not to join the session. For example, if the server * used only cookie-based sessions, and the client had disabled the use of * cookies, then a session would be new on each request. * * @return <code>true</code> if the server has created a session, but the client * has not yet joined * @exception IllegalStateException if this method is called on an already * invalidated session */ public boolean isNew(); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/session/HttpSessionManager.java
core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/session/HttpSessionManager.java
package com.taobao.arthas.core.shell.term.impl.http.session; import java.util.Collections; import java.util.Set; import com.taobao.arthas.common.ArthasConstants; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.cookie.Cookie; import io.netty.handler.codec.http.cookie.ServerCookieDecoder; import io.netty.handler.codec.http.cookie.ServerCookieEncoder; import io.netty.util.Attribute; import io.netty.util.AttributeKey; /** * <pre> * netty里的http session管理。因为同一域名的不同端口共享cookie,所以需要共用。 * </pre> * * @author hengyunabc 2021-03-03 * */ public class HttpSessionManager { public static AttributeKey<HttpSession> SESSION_KEY = AttributeKey.valueOf("session"); private LRUCache<String, HttpSession> sessions = new LRUCache<String, HttpSession>(1024); public HttpSessionManager() { } private HttpSession getSession(HttpRequest httpRequest) { // TODO 增加从 url中获取 session id 功能? Set<Cookie> cookies; String value = httpRequest.headers().get(HttpHeaderNames.COOKIE); if (value == null) { cookies = Collections.emptySet(); } else { cookies = ServerCookieDecoder.STRICT.decode(value); } for (Cookie cookie : cookies) { if (ArthasConstants.ASESSION_KEY.equals(cookie.name())) { String sessionId = cookie.value(); return sessions.get(sessionId); } } return null; } public static HttpSession getHttpSessionFromContext(ChannelHandlerContext ctx) { return ctx.channel().attr(SESSION_KEY).get(); } public HttpSession getOrCreateHttpSession(ChannelHandlerContext ctx, HttpRequest httpRequest) { // 尝试用 ctx 和从 cookie里读取出 session Attribute<HttpSession> attribute = ctx.channel().attr(SESSION_KEY); HttpSession httpSession = attribute.get(); if (httpSession != null) { return httpSession; } httpSession = getSession(httpRequest); if (httpSession != null) { attribute.set(httpSession); return httpSession; } // 创建session,并设置到ctx里 httpSession = newHttpSession(); attribute.set(httpSession); return httpSession; } private HttpSession newHttpSession() { SimpleHttpSession session = new SimpleHttpSession(); this.sessions.put(session.getId(), session); return session; } public static void setSessionCookie(HttpResponse response, HttpSession session) { response.headers().add(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(ArthasConstants.ASESSION_KEY, session.getId())); } public void start() { } public void stop() { sessions.clear(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/session/Session.java
core/src/main/java/com/taobao/arthas/core/shell/session/Session.java
package com.taobao.arthas.core.shell.session; import com.taobao.arthas.core.distribution.SharingResultDistributor; import com.taobao.arthas.core.shell.command.CommandResolver; import com.taobao.arthas.core.shell.system.Job; import java.lang.instrument.Instrumentation; import java.util.List; /** * A shell session. * * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> * @author gongdewei 2020-03-23 */ public interface Session { String COMMAND_MANAGER = "arthas-command-manager"; String PID = "pid"; String INSTRUMENTATION = "instrumentation"; String ID = "id"; String SERVER = "server"; String USER_ID = "userId"; /** * The tty this session related to. */ String TTY = "tty"; /** * Session create time */ String CREATE_TIME = "createTime"; /** * Session last active time */ String LAST_ACCESS_TIME = "lastAccessedTime"; /** * Command Result Distributor */ String RESULT_DISTRIBUTOR = "resultDistributor"; /** * The executing foreground job */ String FOREGROUND_JOB = "foregroundJob"; /** * Put some data in a session * * @param key the key for the data * @param obj the data * @return a reference to this, so the API can be used fluently */ Session put(String key, Object obj); /** * Get some data from the session * * @param key the key of the data * @return the data */ <T> T get(String key); /** * Remove some data from the session * * @param key the key of the data * @return the data that was there or null if none there */ <T> T remove(String key); /** * Check if the session has been already locked * * @return locked or not */ boolean isLocked(); /** * Unlock the session * */ void unLock(); /** * Try to fetch the current session's lock * * @return success or not */ boolean tryLock(); /** * Check current lock's sequence id * * @return lock's sequence id */ int getLock(); /** * Get session id * @return session id */ String getSessionId(); /** * Get Java PID * * @return java pid */ long getPid(); /** * Get all registered command resolvers * * @return command resolvers */ List<CommandResolver> getCommandResolvers(); /** * Get java instrumentation * * @return instrumentation instance */ Instrumentation getInstrumentation(); /** * Update session last access time * @param time new time */ void setLastAccessTime(long time); /** * Get session last access time * @return session last access time */ long getLastAccessTime(); /** * Get session create time * @return session create time */ long getCreateTime(); /** * Update session's command result distributor * @param resultDistributor */ void setResultDistributor(SharingResultDistributor resultDistributor); /** * Get session's command result distributor * @return */ SharingResultDistributor getResultDistributor(); /** * Set the foreground job */ void setForegroundJob(Job job); /** * Get the foreground job */ Job getForegroundJob(); /** * Whether the session is tty term */ boolean isTty(); /** * Get user id * @return user id */ String getUserId(); /** * Set user id * @param userId user id */ void setUserId(String userId); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/session/SessionManager.java
core/src/main/java/com/taobao/arthas/core/shell/session/SessionManager.java
package com.taobao.arthas.core.shell.session; import com.taobao.arthas.core.shell.system.JobController; import com.taobao.arthas.core.shell.system.impl.InternalCommandManager; import java.lang.instrument.Instrumentation; /** * Arthas Session Manager * @author gongdewei 2020-03-20 */ public interface SessionManager { Session createSession(); Session getSession(String sessionId); Session removeSession(String sessionId); void updateAccessTime(Session session); void close(); InternalCommandManager getCommandManager(); Instrumentation getInstrumentation(); JobController getJobController(); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/session/impl/SessionManagerImpl.java
core/src/main/java/com/taobao/arthas/core/shell/session/impl/SessionManagerImpl.java
package com.taobao.arthas.core.shell.session.impl; import com.alibaba.arthas.deps.org.slf4j.Logger; import com.alibaba.arthas.deps.org.slf4j.LoggerFactory; import com.taobao.arthas.core.command.model.MessageModel; import com.taobao.arthas.core.distribution.ResultConsumer; import com.taobao.arthas.core.distribution.SharingResultDistributor; import com.taobao.arthas.core.shell.ShellServerOptions; import com.taobao.arthas.core.shell.session.Session; import com.taobao.arthas.core.shell.session.SessionManager; import com.taobao.arthas.core.shell.system.Job; import com.taobao.arthas.core.shell.system.JobController; import com.taobao.arthas.core.shell.system.impl.InternalCommandManager; import java.lang.instrument.Instrumentation; import java.util.*; import java.util.concurrent.*; /** * Arthas Session Manager * * @author gongdewei 2020-03-20 */ public class SessionManagerImpl implements SessionManager { private static final Logger logger = LoggerFactory.getLogger(SessionManagerImpl.class); private final InternalCommandManager commandManager; private final Instrumentation instrumentation; private final JobController jobController; private final long sessionTimeoutMillis; private final int consumerTimeoutMillis; private final long reaperInterval; private final Map<String, Session> sessions; private final long pid; private boolean closed = false; private ScheduledExecutorService scheduledExecutorService; public SessionManagerImpl(ShellServerOptions options, InternalCommandManager commandManager, JobController jobController) { this.commandManager = commandManager; this.jobController = jobController; this.sessions = new ConcurrentHashMap<String, Session>(); this.sessionTimeoutMillis = options.getSessionTimeout(); this.consumerTimeoutMillis = 5 * 60 * 1000; // 5 minutes this.reaperInterval = options.getReaperInterval(); this.instrumentation = options.getInstrumentation(); this.pid = options.getPid(); //start evict session timer this.setEvictTimer(); } @Override public Session createSession() { Session session = new SessionImpl(); session.put(Session.COMMAND_MANAGER, commandManager); session.put(Session.INSTRUMENTATION, instrumentation); session.put(Session.PID, pid); //session.put(Session.SERVER, server); //session.put(Session.TTY, term); String sessionId = UUID.randomUUID().toString(); session.put(Session.ID, sessionId); sessions.put(sessionId, session); return session; } @Override public Session getSession(String sessionId) { return sessions.get(sessionId); } @Override public Session removeSession(String sessionId) { Session session = sessions.get(sessionId); if (session == null) { return null; } //interrupt foreground job Job job = session.getForegroundJob(); if (job != null) { job.interrupt(); } SharingResultDistributor resultDistributor = session.getResultDistributor(); if (resultDistributor != null) { resultDistributor.close(); } return sessions.remove(sessionId); } @Override public void updateAccessTime(Session session) { session.setLastAccessTime(System.currentTimeMillis()); } @Override public void close() { //TODO clear resources while shutdown arthas closed = true; if (scheduledExecutorService != null) { scheduledExecutorService.shutdownNow(); } ArrayList<Session> sessions = new ArrayList<Session>(this.sessions.values()); for (Session session : sessions) { SharingResultDistributor resultDistributor = session.getResultDistributor(); if (resultDistributor != null) { resultDistributor.appendResult(new MessageModel("arthas server is going to shutdown.")); } logger.info("Removing session before shutdown: {}, last access time: {}", session.getSessionId(), session.getLastAccessTime()); this.removeSession(session.getSessionId()); } jobController.close(); } private synchronized void setEvictTimer() { if (!closed && reaperInterval > 0) { scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable r) { final Thread t = new Thread(r, "arthas-session-manager"); t.setDaemon(true); return t; } }); scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { evictSessions(); } }, 0, reaperInterval, TimeUnit.MILLISECONDS); } } /** * Check and remove inactive session */ public void evictSessions() { long now = System.currentTimeMillis(); List<Session> toClose = new ArrayList<Session>(); for (Session session : sessions.values()) { // 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() > sessionTimeoutMillis && session.getForegroundJob() == null) { toClose.add(session); } evictConsumers(session); } for (Session session : toClose) { //interrupt foreground job Job job = session.getForegroundJob(); if (job != null) { job.interrupt(); } long timeOutInMinutes = sessionTimeoutMillis / 1000 / 60; String reason = "session is inactive for " + timeOutInMinutes + " min(s)."; SharingResultDistributor resultDistributor = session.getResultDistributor(); if (resultDistributor != null) { resultDistributor.appendResult(new MessageModel(reason)); } this.removeSession(session.getSessionId()); logger.info("Removing inactive session: {}, last access time: {}", session.getSessionId(), session.getLastAccessTime()); } } /** * Check and remove inactive consumer */ public void evictConsumers(Session session) { SharingResultDistributor distributor = session.getResultDistributor(); if (distributor != null) { List<ResultConsumer> consumers = distributor.getConsumers(); //remove inactive consumer from session directly long now = System.currentTimeMillis(); for (ResultConsumer consumer : consumers) { long inactiveTime = now - consumer.getLastAccessTime(); 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); consumer.appendResult(new MessageModel("consumer is inactive for a while, please refresh the page.")); distributor.removeConsumer(consumer); } } } } @Override public InternalCommandManager getCommandManager() { return commandManager; } @Override public Instrumentation getInstrumentation() { return instrumentation; } @Override public JobController getJobController() { return jobController; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/session/impl/SessionImpl.java
core/src/main/java/com/taobao/arthas/core/shell/session/impl/SessionImpl.java
package com.taobao.arthas.core.shell.session.impl; import com.taobao.arthas.core.distribution.SharingResultDistributor; import com.taobao.arthas.core.shell.command.CommandResolver; import com.taobao.arthas.core.shell.session.Session; import com.taobao.arthas.core.shell.system.Job; import com.taobao.arthas.core.shell.system.impl.InternalCommandManager; import java.lang.instrument.Instrumentation; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; /** * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> */ public class SessionImpl implements Session { private final static AtomicInteger lockSequence = new AtomicInteger(); private final static int LOCK_TX_EMPTY = -1; private final AtomicInteger lock = new AtomicInteger(LOCK_TX_EMPTY); private Map<String, Object> data = new ConcurrentHashMap<String, Object>(); public SessionImpl() { long now = System.currentTimeMillis(); data.put(CREATE_TIME, now); this.setLastAccessTime(now); } @Override public Session put(String key, Object obj) { if (obj == null) { data.remove(key); } else { data.put(key, obj); } return this; } @Override public <T> T get(String key) { return (T) data.get(key); } @Override public <T> T remove(String key) { return (T) data.remove(key); } @Override public boolean tryLock() { return lock.compareAndSet(LOCK_TX_EMPTY, lockSequence.getAndIncrement()); } @Override public void unLock() { int currentLockTx = lock.get(); if (!lock.compareAndSet(currentLockTx, LOCK_TX_EMPTY)) { throw new IllegalStateException(); } } @Override public boolean isLocked() { return lock.get() != LOCK_TX_EMPTY; } @Override public int getLock() { return lock.get(); } @Override public String getSessionId() { return (String) data.get(ID); } @Override public long getPid() { return (Long) data.get(PID); } @Override public List<CommandResolver> getCommandResolvers() { InternalCommandManager commandManager = (InternalCommandManager) data.get(COMMAND_MANAGER); return commandManager.getResolvers(); } @Override public Instrumentation getInstrumentation() { return (Instrumentation) data.get(INSTRUMENTATION); } @Override public void setLastAccessTime(long time) { this.put(LAST_ACCESS_TIME, time); } @Override public long getLastAccessTime() { return (Long)data.get(LAST_ACCESS_TIME); } @Override public long getCreateTime() { return (Long)data.get(CREATE_TIME); } @Override public void setResultDistributor(SharingResultDistributor resultDistributor) { if (resultDistributor == null) { data.remove(RESULT_DISTRIBUTOR); } else { data.put(RESULT_DISTRIBUTOR, resultDistributor); } } @Override public SharingResultDistributor getResultDistributor() { return (SharingResultDistributor) data.get(RESULT_DISTRIBUTOR); } @Override public void setForegroundJob(Job job) { if (job == null) { data.remove(FOREGROUND_JOB); } else { data.put(FOREGROUND_JOB, job); } } @Override public Job getForegroundJob() { return (Job) data.get(FOREGROUND_JOB); } @Override public boolean isTty() { return get(TTY) != null; } @Override public String getUserId() { return (String) data.get(USER_ID); } @Override public void setUserId(String userId) { if (userId == null) { data.remove(USER_ID); } else { data.put(USER_ID, userId); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/BindHandler.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/BindHandler.java
package com.taobao.arthas.core.shell.handlers; import com.alibaba.arthas.deps.org.slf4j.Logger; import com.alibaba.arthas.deps.org.slf4j.LoggerFactory; import com.taobao.arthas.core.shell.future.Future; import java.util.concurrent.atomic.AtomicBoolean; /** * @author ralf0131 2017-04-24 18:23. */ public class BindHandler implements Handler<Future<Void>> { private static final Logger logger = LoggerFactory.getLogger(BindHandler.class); private AtomicBoolean isBindRef; public BindHandler(AtomicBoolean isBindRef) { this.isBindRef = isBindRef; } @Override public void handle(Future<Void> event) { if (event.failed()) { logger.error("Error listening term server:", event.cause()); isBindRef.compareAndSet(true, false); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/Handler.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/Handler.java
package com.taobao.arthas.core.shell.handlers; public interface Handler<E> { /** * Something has happened, so handle it. * * @param event the event to handle */ void handle(E event); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/NoOpHandler.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/NoOpHandler.java
package com.taobao.arthas.core.shell.handlers; import com.alibaba.arthas.deps.org.slf4j.Logger; import com.alibaba.arthas.deps.org.slf4j.LoggerFactory; import com.taobao.arthas.core.shell.future.Future; /** * @author beiwei30 on 22/11/2016. */ public class NoOpHandler<E> implements Handler<E> { private static final Logger logger = LoggerFactory.getLogger(NoOpHandler.class); @Override public void handle(E event) { if (event instanceof Future && ((Future) event).failed()) { logger.error("Error listening term server:", ((Future) event).cause()); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/command/CommandInterruptHandler.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/command/CommandInterruptHandler.java
package com.taobao.arthas.core.shell.handlers.command; import com.taobao.arthas.core.shell.command.CommandProcess; import com.taobao.arthas.core.shell.handlers.Handler; /** * @author ralf0131 2017-01-09 13:23. */ public class CommandInterruptHandler implements Handler<Void> { private CommandProcess process; public CommandInterruptHandler(CommandProcess process) { this.process = process; } @Override public void handle(Void event) { process.end(); process.session().unLock(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/term/RequestHandler.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/term/RequestHandler.java
package com.taobao.arthas.core.shell.handlers.term; import com.taobao.arthas.core.shell.handlers.Handler; import com.taobao.arthas.core.shell.term.impl.TermImpl; import io.termd.core.function.Consumer; /** * @author beiwei30 on 23/11/2016. */ public class RequestHandler implements Consumer<String> { private TermImpl term; private final Handler<String> lineHandler; public RequestHandler(TermImpl term, Handler<String> lineHandler) { this.term = term; this.lineHandler = lineHandler; } @Override public void accept(String line) { term.setInReadline(false); lineHandler.handle(line); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/term/SizeHandlerWrapper.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/term/SizeHandlerWrapper.java
package com.taobao.arthas.core.shell.handlers.term; import com.taobao.arthas.core.shell.handlers.Handler; import io.termd.core.function.Consumer; import io.termd.core.util.Vector; /** * @author beiwei30 on 22/11/2016. */ public class SizeHandlerWrapper implements Consumer<Vector> { private final Handler<Void> handler; public SizeHandlerWrapper(Handler<Void> handler) { this.handler = handler; } @Override public void accept(Vector resize) { handler.handle(null); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/term/CloseHandlerWrapper.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/term/CloseHandlerWrapper.java
package com.taobao.arthas.core.shell.handlers.term; import com.taobao.arthas.core.shell.handlers.Handler; import io.termd.core.function.Consumer; /** * @author beiwei30 on 22/11/2016. */ public class CloseHandlerWrapper implements Consumer<Void> { private final Handler<Void> handler; public CloseHandlerWrapper(Handler<Void> handler) { this.handler = handler; } @Override public void accept(Void v) { handler.handle(v); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/term/StdinHandlerWrapper.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/term/StdinHandlerWrapper.java
package com.taobao.arthas.core.shell.handlers.term; import com.taobao.arthas.core.shell.handlers.Handler; import io.termd.core.function.Consumer; import io.termd.core.util.Helper; /** * @author beiwei30 on 22/11/2016. */ public class StdinHandlerWrapper implements Consumer<int[]> { private final Handler<String> handler; public StdinHandlerWrapper(Handler<String> handler) { this.handler = handler; } @Override public void accept(int[] codePoints) { handler.handle(Helper.fromCodePoints(codePoints)); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/term/DefaultTermStdinHandler.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/term/DefaultTermStdinHandler.java
package com.taobao.arthas.core.shell.handlers.term; import com.taobao.arthas.core.shell.term.impl.TermImpl; import io.termd.core.function.Consumer; /** * @author beiwei30 on 23/11/2016. */ public class DefaultTermStdinHandler implements Consumer<int[]> { private TermImpl term; public DefaultTermStdinHandler(TermImpl term) { this.term = term; } @Override public void accept(int[] codePoints) { // Echo term.echo(codePoints); term.getReadline().queueEvent(codePoints); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/term/EventHandler.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/term/EventHandler.java
package com.taobao.arthas.core.shell.handlers.term; import com.taobao.arthas.core.shell.term.impl.TermImpl; import io.termd.core.function.BiConsumer; import io.termd.core.tty.TtyEvent; /** * @author beiwei30 on 23/11/2016. */ public class EventHandler implements BiConsumer<TtyEvent, Integer> { private TermImpl term; public EventHandler(TermImpl term) { this.term = term; } @Override public void accept(TtyEvent event, Integer key) { switch (event) { case INTR: term.handleIntr(key); break; case EOF: term.handleEof(key); break; case SUSP: term.handleSusp(key); break; } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/server/SessionClosedHandler.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/server/SessionClosedHandler.java
package com.taobao.arthas.core.shell.handlers.server; import com.taobao.arthas.core.shell.future.Future; import com.taobao.arthas.core.shell.handlers.Handler; import com.taobao.arthas.core.shell.impl.ShellImpl; import com.taobao.arthas.core.shell.impl.ShellServerImpl; /** * @author beiwei30 on 23/11/2016. */ public class SessionClosedHandler implements Handler<Future<Void>> { private ShellServerImpl shellServer; private final ShellImpl session; public SessionClosedHandler(ShellServerImpl shellServer, ShellImpl session) { this.shellServer = shellServer; this.session = session; } @Override public void handle(Future<Void> ar) { shellServer.removeSession(session); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/server/SessionsClosedHandler.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/server/SessionsClosedHandler.java
package com.taobao.arthas.core.shell.handlers.server; import com.taobao.arthas.core.shell.future.Future; import com.taobao.arthas.core.shell.handlers.Handler; import java.util.concurrent.atomic.AtomicInteger; /** * @author beiwei30 on 23/11/2016. */ public class SessionsClosedHandler implements Handler<Future<Void>> { private final AtomicInteger count; private final Handler<Future<Void>> completionHandler; public SessionsClosedHandler(AtomicInteger count, Handler<Future<Void>> completionHandler) { this.count = count; this.completionHandler = completionHandler; } @Override public void handle(Future<Void> event) { if (count.decrementAndGet() == 0) { completionHandler.handle(Future.<Void>succeededFuture()); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/server/TermServerTermHandler.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/server/TermServerTermHandler.java
package com.taobao.arthas.core.shell.handlers.server; import com.taobao.arthas.core.shell.handlers.Handler; import com.taobao.arthas.core.shell.impl.ShellServerImpl; import com.taobao.arthas.core.shell.term.Term; /** * @author beiwei30 on 23/11/2016. */ public class TermServerTermHandler implements Handler<Term> { private ShellServerImpl shellServer; public TermServerTermHandler(ShellServerImpl shellServer) { this.shellServer = shellServer; } @Override public void handle(Term term) { shellServer.handleTerm(term); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/server/TermServerListenHandler.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/server/TermServerListenHandler.java
package com.taobao.arthas.core.shell.handlers.server; import com.taobao.arthas.core.shell.future.Future; import com.taobao.arthas.core.shell.handlers.Handler; import com.taobao.arthas.core.shell.impl.ShellServerImpl; import com.taobao.arthas.core.shell.term.TermServer; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * @author beiwei30 on 23/11/2016. */ public class TermServerListenHandler implements Handler<Future<TermServer>> { private ShellServerImpl shellServer; private Handler<Future<Void>> listenHandler; private List<TermServer> toStart; private AtomicInteger count; private AtomicBoolean failed; public TermServerListenHandler(ShellServerImpl shellServer, Handler<Future<Void>> listenHandler, List<TermServer> toStart) { this.shellServer = shellServer; this.listenHandler = listenHandler; this.toStart = toStart; this.count = new AtomicInteger(toStart.size()); this.failed = new AtomicBoolean(); } @Override public void handle(Future<TermServer> ar) { if (ar.failed()) { failed.set(true); } if (count.decrementAndGet() == 0) { if (failed.get()) { listenHandler.handle(Future.<Void>failedFuture(ar.cause())); for (TermServer termServer : toStart) { termServer.close(); } } else { shellServer.setClosed(false); shellServer.setTimer(); listenHandler.handle(Future.<Void>succeededFuture()); } } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/shell/ShellLineHandler.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/shell/ShellLineHandler.java
package com.taobao.arthas.core.shell.handlers.shell; import com.taobao.arthas.core.shell.cli.CliToken; import com.taobao.arthas.core.shell.cli.CliTokens; import com.taobao.arthas.core.shell.handlers.Handler; import com.taobao.arthas.core.shell.impl.ShellImpl; import com.taobao.arthas.core.shell.system.ExecStatus; import com.taobao.arthas.core.shell.system.Job; import com.taobao.arthas.core.shell.term.Term; import com.taobao.arthas.core.util.TokenUtils; import com.taobao.arthas.core.view.Ansi; import java.util.List; /** * @author beiwei30 on 23/11/2016. */ public class ShellLineHandler implements Handler<String> { private ShellImpl shell; private Term term; public ShellLineHandler(ShellImpl shell) { this.shell = shell; this.term = shell.term(); } @Override public void handle(String line) { if (line == null) { // EOF handleExit(); return; } List<CliToken> tokens = CliTokens.tokenize(line); CliToken first = TokenUtils.findFirstTextToken(tokens); if (first == null) { // For now do like this shell.readline(); return; } String name = first.value(); if (name.equals("exit") || name.equals("logout") || name.equals("q") || name.equals("quit")) { handleExit(); return; } else if (name.equals("jobs")) { handleJobs(); return; } else if (name.equals("fg")) { handleForeground(tokens); return; } else if (name.equals("bg")) { handleBackground(tokens); return; } else if (name.equals("kill")) { handleKill(tokens); return; } Job job = createJob(tokens); if (job != null) { job.run(); } } private int getJobId(String arg) { int result = -1; try { if (arg.startsWith("%")) { result = Integer.parseInt(arg.substring(1)); } else { result = Integer.parseInt(arg); } } catch (Exception e) { } return result; } private Job createJob(List<CliToken> tokens) { Job job; try { job = shell.createJob(tokens); } catch (Exception e) { term.echo(e.getMessage() + "\n"); shell.readline(); return null; } return job; } private void handleKill(List<CliToken> tokens) { String arg = TokenUtils.findSecondTokenText(tokens); if (arg == null) { term.write("kill: usage: kill job_id\n"); shell.readline(); return; } Job job = shell.jobController().getJob(getJobId(arg)); if (job == null) { term.write(arg + " : no such job\n"); shell.readline(); } else { job.terminate(); term.write("kill job " + job.id() + " success\n"); shell.readline(); } } private void handleBackground(List<CliToken> tokens) { String arg = TokenUtils.findSecondTokenText(tokens); Job job; if (arg == null) { job = shell.getForegroundJob(); } else { job = shell.jobController().getJob(getJobId(arg)); } if (job == null) { term.write(arg + " : no such job\n"); shell.readline(); } else { if (job.status() == ExecStatus.STOPPED) { job.resume(false); term.echo(shell.statusLine(job, ExecStatus.RUNNING)); shell.readline(); } else { term.write("job " + job.id() + " is already running\n"); shell.readline(); } } } private void handleForeground(List<CliToken> tokens) { String arg = TokenUtils.findSecondTokenText(tokens); Job job; if (arg == null) { job = shell.getForegroundJob(); } else { job = shell.jobController().getJob(getJobId(arg)); } if (job == null) { term.write(arg + " : no such job\n"); shell.readline(); } else { if (job.getSession() != shell.session()) { term.write("job " + job.id() + " doesn't belong to this session, so can not fg it\n"); shell.readline(); } else if (job.status() == ExecStatus.STOPPED) { job.resume(true); } else if (job.status() == ExecStatus.RUNNING) { // job is running job.toForeground(); } else { term.write("job " + job.id() + " is already terminated, so can not fg it\n"); shell.readline(); } } } private void handleJobs() { for (Job job : shell.jobController().jobs()) { String statusLine = shell.statusLine(job, job.status()); term.write(statusLine); } shell.readline(); } private void handleExit() { String msg = Ansi.ansi().fg(Ansi.Color.GREEN).a("Session has been terminated.\n" + "Arthas is still running in the background.\n" + "To completely shutdown arthas, please execute the 'stop' command.\n").reset().toString(); term.write(msg); term.close(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/shell/FutureHandler.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/shell/FutureHandler.java
package com.taobao.arthas.core.shell.handlers.shell; import com.taobao.arthas.core.shell.future.Future; import com.taobao.arthas.core.shell.handlers.Handler; /** * @author beiwei30 on 23/11/2016. */ public class FutureHandler implements Handler<Void> { private Future future; public FutureHandler(Future future) { this.future = future; } @Override public void handle(Void event) { future.complete(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/shell/QExitHandler.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/shell/QExitHandler.java
package com.taobao.arthas.core.shell.handlers.shell; import com.taobao.arthas.core.shell.command.CommandProcess; import com.taobao.arthas.core.shell.handlers.Handler; /** * * @author hengyunabc 2019-02-09 * */ public class QExitHandler implements Handler<String> { private CommandProcess process; public QExitHandler(CommandProcess process) { this.process = process; } @Override public void handle(String event) { if ("q".equalsIgnoreCase(event)) { process.end(); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/shell/SuspendHandler.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/shell/SuspendHandler.java
package com.taobao.arthas.core.shell.handlers.shell; import com.taobao.arthas.core.shell.impl.ShellImpl; import com.taobao.arthas.core.shell.system.ExecStatus; import com.taobao.arthas.core.shell.system.Job; import com.taobao.arthas.core.shell.term.SignalHandler; import com.taobao.arthas.core.shell.term.Term; /** * @author beiwei30 on 23/11/2016. */ public class SuspendHandler implements SignalHandler { private ShellImpl shell; public SuspendHandler(ShellImpl shell) { this.shell = shell; } @Override public boolean deliver(int key) { Term term = shell.term(); Job job = shell.getForegroundJob(); if (job != null) { term.echo(shell.statusLine(job, ExecStatus.STOPPED)); job.suspend(); } return true; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/shell/CloseHandler.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/shell/CloseHandler.java
package com.taobao.arthas.core.shell.handlers.shell; import com.taobao.arthas.core.shell.handlers.Handler; import com.taobao.arthas.core.shell.impl.ShellImpl; /** * @author beiwei30 on 23/11/2016. */ public class CloseHandler implements Handler<Void> { private ShellImpl shell; public CloseHandler(ShellImpl shell) { this.shell = shell; } @Override public void handle(Void event) { shell.jobController().close(shell.closedFutureHandler()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/shell/InterruptHandler.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/shell/InterruptHandler.java
package com.taobao.arthas.core.shell.handlers.shell; import com.taobao.arthas.core.shell.impl.ShellImpl; import com.taobao.arthas.core.shell.term.SignalHandler; /** * @author beiwei30 on 23/11/2016. */ public class InterruptHandler implements SignalHandler { private ShellImpl shell; public InterruptHandler(ShellImpl shell) { this.shell = shell; } @Override public boolean deliver(int key) { if (shell.getForegroundJob() != null) { return shell.getForegroundJob().interrupt(); } return true; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/shell/CommandManagerCompletionHandler.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/shell/CommandManagerCompletionHandler.java
package com.taobao.arthas.core.shell.handlers.shell; import com.taobao.arthas.core.shell.cli.Completion; import com.taobao.arthas.core.shell.handlers.Handler; import com.taobao.arthas.core.shell.system.impl.InternalCommandManager; /** * @author beiwei30 on 23/11/2016. */ public class CommandManagerCompletionHandler implements Handler<Completion> { private InternalCommandManager commandManager; public CommandManagerCompletionHandler(InternalCommandManager commandManager) { this.commandManager = commandManager; } @Override public void handle(Completion completion) { commandManager.complete(completion); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/handlers/shell/ShellForegroundUpdateHandler.java
core/src/main/java/com/taobao/arthas/core/shell/handlers/shell/ShellForegroundUpdateHandler.java
package com.taobao.arthas.core.shell.handlers.shell; import com.taobao.arthas.core.shell.handlers.Handler; import com.taobao.arthas.core.shell.impl.ShellImpl; import com.taobao.arthas.core.shell.system.Job; /** * @author beiwei30 on 23/11/2016. */ public class ShellForegroundUpdateHandler implements Handler<Job> { private ShellImpl shell; public ShellForegroundUpdateHandler(ShellImpl shell) { this.shell = shell; } @Override public void handle(Job job) { if (job == null) { shell.readline(); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/cli/CliToken.java
core/src/main/java/com/taobao/arthas/core/shell/cli/CliToken.java
package com.taobao.arthas.core.shell.cli; public interface CliToken { /** * @return the token value */ String value(); /** * @return the raw token value, that may contain unescaped chars, for instance {@literal "ab\"cd"} */ String raw(); /** * @return true when it's a text token */ boolean isText(); /** * @return true when it's a blank token */ boolean isBlank(); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/cli/CliTokens.java
core/src/main/java/com/taobao/arthas/core/shell/cli/CliTokens.java
package com.taobao.arthas.core.shell.cli; import com.taobao.arthas.core.shell.cli.impl.CliTokenImpl; import java.util.List; /** * @author beiwei30 on 09/11/2016. */ public class CliTokens { /** * Create a text token. * * @param text the text * @return the token */ public static CliToken createText(String text) { return new CliTokenImpl(true, text, text); } /** * Create a new blank token. * * @param blank the blank value * @return the token */ public static CliToken createBlank(String blank) { return new CliTokenImpl(false, blank, blank); } /** * Tokenize the string argument and return a list of tokens. * * @param s the tokenized string * @return the tokens */ public static List<CliToken> tokenize(String s) { return CliTokenImpl.tokenize(s); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/cli/OptionCompleteHandler.java
core/src/main/java/com/taobao/arthas/core/shell/cli/OptionCompleteHandler.java
package com.taobao.arthas.core.shell.cli; /** * * @author hengyunabc 2021-04-29 * */ public interface OptionCompleteHandler { boolean matchName(String token); boolean complete(Completion completion); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/cli/Completion.java
core/src/main/java/com/taobao/arthas/core/shell/cli/Completion.java
package com.taobao.arthas.core.shell.cli; import com.taobao.arthas.core.shell.session.Session; import java.util.List; /** * The completion object * * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> */ public interface Completion { /** * @return the shell current session, useful for accessing data like the current path for file completion, etc... */ Session session(); /** * @return the current line being completed in raw format, i.e without any char escape performed */ String rawLine(); /** * @return the current line being completed as preparsed tokens */ List<CliToken> lineTokens(); /** * End the completion with a list of candidates, these candidates will be displayed by the shell on the console. * * @param candidates the candidates */ void complete(List<String> candidates); /** * End the completion with a value that will be inserted to complete the line. * * @param value the value to complete with * @param terminal true if the value is terminal, i.e can be further completed */ void complete(String value, boolean terminal); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/cli/CompletionUtils.java
core/src/main/java/com/taobao/arthas/core/shell/cli/CompletionUtils.java
package com.taobao.arthas.core.shell.cli; import com.taobao.arthas.core.shell.session.Session; import com.taobao.arthas.core.shell.term.Tty; import com.taobao.arthas.core.util.SearchUtils; import com.taobao.arthas.core.util.StringUtils; import com.taobao.arthas.core.util.usage.StyledUsageFormatter; import com.taobao.middleware.cli.CLI; import com.taobao.middleware.cli.Option; import com.taobao.middleware.cli.annotations.CLIConfigurator; import io.termd.core.util.Helper; import java.io.File; import java.lang.instrument.Instrumentation; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; /** * @author beiwei30 on 09/11/2016. */ public class CompletionUtils { public static String findLongestCommonPrefix(Collection<String> values) { List<int[]> entries = new LinkedList<int[]>(); for (String value : values) { int[] entry = Helper.toCodePoints(value); entries.add(entry); } return Helper.fromCodePoints(io.termd.core.readline.Completion.findLongestCommonPrefix(entries)); } public static void complete(Completion completion, Class<?> clazz) { List<CliToken> tokens = completion.lineTokens(); CliToken lastToken = tokens.get(tokens.size() - 1); CLI cli = CLIConfigurator.define(clazz); List<com.taobao.middleware.cli.Option> options = cli.getOptions(); if (lastToken == null || lastToken.isBlank()) { completeUsage(completion, cli); } else if (lastToken.value().startsWith("--")) { completeLongOption(completion, lastToken, options); } else if (lastToken.value().startsWith("-")) { completeShortOption(completion, lastToken, options); } else { completion.complete(Collections.<String>emptyList()); } } /** * 从给定的查询数组中查询匹配的对象,并进行自动补全 */ public static boolean complete(Completion completion, Collection<String> searchScope) { List<CliToken> tokens = completion.lineTokens(); String lastToken = tokens.get(tokens.size() - 1).value(); List<String> candidates = new ArrayList<String>(); if (StringUtils.isBlank(lastToken)) { lastToken = ""; } for (String name: searchScope) { if (name.startsWith(lastToken)) { candidates.add(name); } } if (candidates.size() == 1) { completion.complete(candidates.get(0).substring(lastToken.length()), true); return true; } else { completion.complete(candidates); return true; } } private static boolean isEndOfDirectory(String token) { return !StringUtils.isBlank(token) && (token.endsWith(File.separator) || token.endsWith("/")); } /** * 返回true表示已经完成completion,返回否则表示没有,调用者需要另外完成补全 * @param completion * @return */ public static boolean completeFilePath(Completion completion) { List<CliToken> tokens = completion.lineTokens(); String token = tokens.get(tokens.size() - 1).value(); if (token.startsWith("-") || StringUtils.isBlank(token)) { return false; } File dir = null; String partName = ""; if (StringUtils.isBlank(token)) { dir = new File("").getAbsoluteFile(); token = ""; } else if (isEndOfDirectory(token)) { dir = new File(token); } else { File parent = new File(token).getAbsoluteFile().getParentFile(); if (parent != null && parent.exists()) { dir = parent; partName = new File(token).getName(); } } File tokenFile = new File(token); String tokenFileName = null; if (isEndOfDirectory(token)) { tokenFileName = ""; } else { tokenFileName = tokenFile.getName(); } if (dir == null) { return false; } File[] listFiles = dir.listFiles(); ArrayList<String> names = new ArrayList<>(); if (listFiles != null) { for (File child : listFiles) { if (child.getName().startsWith(partName)) { if (child.isDirectory()) { names.add(child.getName() + "/"); } else { names.add(child.getName()); } } } } if (names.size() == 1 && isEndOfDirectory(names.get(0))) { String name = names.get(0); // 这个函数补全后不会有空格,并且只能传入要补全的内容 completion.complete(name.substring(tokenFileName.length()), false); return true; } String prefix = null; if (isEndOfDirectory(token)) { prefix = token; } else { prefix = token.substring(0, token.length() - new File(token).getName().length()); } ArrayList<String> namesWithPrefix = new ArrayList<>(); for (String name : names) { namesWithPrefix.add(prefix + name); } // 这个函数需要保留前缀 CompletionUtils.complete(completion, namesWithPrefix); return true; } public static boolean completeClassName(Completion completion) { List<CliToken> tokens = completion.lineTokens(); String lastToken = tokens.get(tokens.size() - 1).value(); if (StringUtils.isBlank(lastToken)) { lastToken = ""; } if (lastToken.startsWith("-")) { return false; } Instrumentation instrumentation = completion.session().getInstrumentation(); Class<?>[] allLoadedClasses = instrumentation.getAllLoadedClasses(); Set<String> result = new HashSet<String>(); for(Class<?> clazz : allLoadedClasses) { String name = clazz.getName(); if (name.startsWith("[")) { continue; } if(name.startsWith(lastToken)) { int index = name.indexOf('.', lastToken.length()); if(index > 0) { result.add(name.substring(0, index + 1)); }else { result.add(name); } } } if(result.size() == 1 && result.iterator().next().endsWith(".")) { completion.complete(result.iterator().next().substring(lastToken.length()), false); }else { CompletionUtils.complete(completion, result); } return true; } public static boolean completeMethodName(Completion completion) { List<CliToken> tokens = completion.lineTokens(); String lastToken = completion.lineTokens().get(tokens.size() - 1).value(); if (StringUtils.isBlank(lastToken)) { lastToken = ""; } // retrieve the class name String className; if (StringUtils.isBlank(lastToken)) { // tokens = { " ", "CLASS_NAME", " "} className = tokens.get(tokens.size() - 2).value(); } else { // tokens = { " ", "CLASS_NAME", " ", "PARTIAL_METHOD_NAME"} className = tokens.get(tokens.size() - 3).value(); } Set<Class<?>> results = SearchUtils.searchClassOnly(completion.session().getInstrumentation(), className, 2); if (results.size() != 1) { // no class found or multiple class found completion.complete(Collections.<String>emptyList()); return true; } Class<?> clazz = results.iterator().next(); List<String> res = new ArrayList<String>(); for (Method method : clazz.getDeclaredMethods()) { if (StringUtils.isBlank(lastToken)) { res.add(method.getName()); } else if (method.getName().startsWith(lastToken)) { res.add(method.getName()); } } res.add("<init>"); if (res.size() == 1) { completion.complete(res.get(0).substring(lastToken.length()), true); return true; } else { CompletionUtils.complete(completion, res); return true; } } /** * 推断输入到哪一个 argument * @param completion * @return */ public static int detectArgumentIndex(Completion completion) { List<CliToken> tokens = completion.lineTokens(); CliToken lastToken = tokens.get(tokens.size() - 1); if (lastToken.value().startsWith("-") || lastToken.value().startsWith("--")) { return -1; } if (StringUtils.isBlank((lastToken.value())) && tokens.size() == 1) { return 1; } int tokenCount = 0; for (CliToken token : tokens) { if (StringUtils.isBlank(token.value()) || token.value().startsWith("-") || token.value().startsWith("--")) { // filter irrelevant tokens continue; } tokenCount++; } if (StringUtils.isBlank((lastToken.value())) && tokens.size() != 1) { tokenCount++; } return tokenCount; } public static void completeShortOption(Completion completion, CliToken lastToken, List<Option> options) { String prefix = lastToken.value().substring(1); List<String> candidates = new ArrayList<String>(); for (Option option : options) { if (option.getShortName().startsWith(prefix)) { candidates.add(option.getShortName()); } } complete(completion, prefix, candidates); } public static void completeLongOption(Completion completion, CliToken lastToken, List<Option> options) { String prefix = lastToken.value().substring(2); List<String> candidates = new ArrayList<String>(); for (Option option : options) { if (option.getLongName().startsWith(prefix)) { candidates.add(option.getLongName()); } } complete(completion, prefix, candidates); } public static void completeUsage(Completion completion, CLI cli) { Tty tty = completion.session().get(Session.TTY); String usage = StyledUsageFormatter.styledUsage(cli, tty.width()); completion.complete(Collections.singletonList(usage)); } private static void complete(Completion completion, String prefix, List<String> candidates) { if (candidates.size() == 1) { completion.complete(candidates.get(0).substring(prefix.length()), true); } else { String commonPrefix = CompletionUtils.findLongestCommonPrefix(candidates); if (commonPrefix.length() > 0) { if (commonPrefix.length() == prefix.length()) { completion.complete(candidates); } else { completion.complete(commonPrefix.substring(prefix.length()), false); } } else { completion.complete(candidates); } } } /** * <pre> * 检查是否应该补全某个 option。 * 比如 option是: --classPattern , tokens可能是: * 2个: '--classPattern' ' ' * 3个: '--classPattern' ' ' 'demo.' * </pre> * * @param option * @return */ public static boolean shouldCompleteOption(Completion completion, String option) { List<CliToken> tokens = completion.lineTokens(); // 有两个 tocken, 然后 倒数第一个不是 - 开头的 if (tokens.size() >= 2) { CliToken cliToken_1 = tokens.get(tokens.size() - 1); CliToken cliToken_2 = tokens.get(tokens.size() - 2); String token_2 = cliToken_2.value(); if (!cliToken_1.value().startsWith("-") && token_2.equals(option)) { return CompletionUtils.completeClassName(completion); } } // 有三个 token,然后 倒数第一个不是 - 开头的,倒数第2是空的,倒数第3是 --classPattern if (tokens.size() >= 3) { CliToken cliToken_1 = tokens.get(tokens.size() - 1); CliToken cliToken_2 = tokens.get(tokens.size() - 2); CliToken cliToken_3 = tokens.get(tokens.size() - 3); if (!cliToken_1.value().startsWith("-") && cliToken_2.isBlank() && cliToken_3.value().equals(option)) { return CompletionUtils.completeClassName(completion); } } return false; } public static boolean completeOptions(Completion completion, List<OptionCompleteHandler> handlers) { List<CliToken> tokens = completion.lineTokens(); /** * <pre> * 比如 ` --name a`,这样子的tokens * </pre> */ if (tokens.size() >= 3) { CliToken cliToken_2 = tokens.get(tokens.size() - 2); CliToken cliToken_3 = tokens.get(tokens.size() - 3); if (cliToken_2.isBlank()) { String token_3 = cliToken_3.value(); for (OptionCompleteHandler handler : handlers) { if (handler.matchName(token_3)) { return handler.complete(completion); } } } } /** * <pre> * 比如 ` --name `,这样子的tokens * </pre> */ if (tokens.size() >= 2) { CliToken cliToken_1 = tokens.get(tokens.size() - 1); CliToken cliToken_2 = tokens.get(tokens.size() - 2); if (cliToken_1.isBlank()) { String token_2 = cliToken_2.value(); for (OptionCompleteHandler handler : handlers) { if (handler.matchName(token_2)) { return handler.complete(completion); } } } } return false; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/cli/impl/CliTokenImpl.java
core/src/main/java/com/taobao/arthas/core/shell/cli/impl/CliTokenImpl.java
package com.taobao.arthas.core.shell.cli.impl; import com.taobao.arthas.core.shell.cli.CliToken; import io.termd.core.readline.LineStatus; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> */ public class CliTokenImpl implements CliToken { final boolean text; final String raw; final String value; public CliTokenImpl(boolean text, String value) { this(text, value, value); } public CliTokenImpl(boolean text, String raw, String value) { this.text = text; this.raw = raw; this.value = value; } @Override public boolean isText() { return text; } @Override public boolean isBlank() { return !text; } public String raw() { return raw; } public String value() { return value; } @Override public int hashCode() { return value.hashCode(); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } else if (obj instanceof CliTokenImpl) { CliTokenImpl that = (CliTokenImpl) obj; return text == that.text && value.equals(that.value); } return false; } @Override public String toString() { return "CliToken[text=" + text + ",value=" + value + "]"; } public static List<CliToken> tokenize(String s) { List<CliToken> tokens = new LinkedList<CliToken>(); tokenize(s, 0, tokens); tokens = correctPipeChar(tokens); return tokens; } /** * fix pipe char '|' problem: https://github.com/alibaba/arthas/issues/1151 * supported: * 1) thread| grep xxx * [thread|, grep] -> [thread, |, grep] * 2) thread |grep xxx * [thread, |grep] -> [thread, |, grep] * * unsupported: * 3) thread|grep xxx * 4) trace -E classA|classB methodA|methodB|grep classA * @param tokens * @return */ private static List<CliToken> correctPipeChar(List<CliToken> tokens) { List<CliToken> newTokens = new ArrayList<CliToken>(tokens.size()+4); for (CliToken token : tokens) { String tokenValue = token.value(); if (tokenValue.length()>1 && tokenValue.endsWith("|")) { //split last char '|' tokenValue = tokenValue.substring(0, tokenValue.length()-1); String rawValue = token.raw(); rawValue = rawValue.substring(0, rawValue.length()-1); newTokens.add(new CliTokenImpl(token.isText(), rawValue, tokenValue)); //add '|' char newTokens.add(new CliTokenImpl(true, "|", "|")); } else if (tokenValue.length()>1 && tokenValue.startsWith("|")) { //add '|' char newTokens.add(new CliTokenImpl(true, "|", "|")); //remove first char '|' tokenValue = tokenValue.substring(1); String rawValue = token.raw(); rawValue = rawValue.substring(1); newTokens.add(new CliTokenImpl(token.isText(), rawValue, tokenValue)); } else { newTokens.add(token); } } return newTokens; } private static void tokenize(String s, int index, List<CliToken> builder) { while (index < s.length()) { char c = s.charAt(index); switch (c) { case ' ': case '\t': index = blankToken(s, index, builder); break; default: index = textToken(s, index, builder); break; } } } // Todo use code points and not chars private static int textToken(String s, int index, List<CliToken> builder) { LineStatus quoter = new LineStatus(); int from = index; StringBuilder value = new StringBuilder(); while (index < s.length()) { char c = s.charAt(index); quoter.accept(c); if (!quoter.isQuoted() && !quoter.isEscaped() && isBlank(c)) { break; } if (quoter.isCodePoint()) { if (quoter.isEscaped() && quoter.isWeaklyQuoted() && c != '"') { value.append('\\'); } value.append(c); } index++; } builder.add(new CliTokenImpl(true, s.substring(from, index), value.toString())); return index; } private static int blankToken(String s, int index, List<CliToken> builder) { int from = index; while (index < s.length() && isBlank(s.charAt(index))) { index++; } builder.add(new CliTokenImpl(false, s.substring(from, index))); return index; } private static boolean isBlank(char c) { return c == ' ' || c == '\t'; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/shell/future/Future.java
core/src/main/java/com/taobao/arthas/core/shell/future/Future.java
package com.taobao.arthas.core.shell.future; import com.taobao.arthas.core.shell.handlers.Handler; public class Future<T> { private boolean failed; private boolean succeeded; private Handler<Future<T>> handler; private T result; private Throwable throwable; public Future() { } public Future(Throwable t) { fail(t); } public Future(String failureMessage) { this(new Throwable(failureMessage)); } public Future(T result) { complete(result); } public static <T> Future<T> future() { return new Future<T>(); } public static <T> Future<T> succeededFuture() { return new Future<T>((T) null); } public static <T> Future<T> succeededFuture(T result) { return new Future<T>(result); } public static <T> Future<T> failedFuture(Throwable t) { return new Future<T>(t); } public static <T> Future<T> failedFuture(String failureMessage) { return new Future<T>(failureMessage); } public boolean isComplete() { return failed || succeeded; } public Future<T> setHandler(Handler<Future<T>> handler) { this.handler = handler; checkCallHandler(); return this; } public void complete(T result) { checkComplete(); this.result = result; succeeded = true; checkCallHandler(); } public void complete() { complete(null); } public void fail(Throwable throwable) { checkComplete(); this.throwable = throwable; failed = true; checkCallHandler(); } public void fail(String failureMessage) { fail(new Throwable(failureMessage)); } public T result() { return result; } public Throwable cause() { return throwable; } public boolean succeeded() { return succeeded; } public boolean failed() { return failed; } public Handler<Future<T>> completer() { return new Handler<Future<T>>() { @Override public void handle(Future<T> ar) { if (ar.succeeded()) { complete(ar.result()); } else { fail(ar.cause()); } } }; } private void checkCallHandler() { if (handler != null && isComplete()) { handler.handle(this); } } private void checkComplete() { if (succeeded || failed) { throw new IllegalStateException("Result is already complete: " + (succeeded ? "succeeded" : "failed")); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/ArthasMcpBootstrap.java
core/src/main/java/com/taobao/arthas/core/mcp/ArthasMcpBootstrap.java
package com.taobao.arthas.core.mcp; import com.taobao.arthas.mcp.server.CommandExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Arthas MCP Bootstrap class * * @author Yeaury */ public class ArthasMcpBootstrap { private static final Logger logger = LoggerFactory.getLogger(ArthasMcpBootstrap.class); private ArthasMcpServer mcpServer; private final CommandExecutor commandExecutor; private final String mcpEndpoint; private final String protocol; private static ArthasMcpBootstrap instance; public ArthasMcpBootstrap(CommandExecutor commandExecutor, String mcpEndpoint, String protocol) { this.commandExecutor = commandExecutor; this.mcpEndpoint = mcpEndpoint; this.protocol = protocol; instance = this; } public static ArthasMcpBootstrap getInstance() { return instance; } public CommandExecutor getCommandExecutor() { return commandExecutor; } public ArthasMcpServer start() { logger.info("Initializing Arthas MCP Bootstrap..."); try { logger.debug("Creating MCP server instance with command executor: {}", commandExecutor.getClass().getSimpleName()); // Create and start MCP server with CommandExecutor and custom endpoint mcpServer = new ArthasMcpServer(mcpEndpoint, commandExecutor, protocol); logger.debug("MCP server instance created successfully"); mcpServer.start(); logger.info("Arthas MCP server initialized successfully"); logger.info("Bootstrap ready - server is operational"); return mcpServer; } catch (Exception e) { logger.error("Failed to initialize Arthas MCP server", e); throw new RuntimeException("Failed to initialize Arthas MCP server", e); } } public void shutdown() { logger.info("Initiating Arthas MCP Bootstrap shutdown..."); if (mcpServer != null) { logger.debug("Stopping MCP server..."); mcpServer.stop(); logger.info("MCP server stopped"); } else { logger.warn("MCP server was null during shutdown - may not have been properly initialized"); } logger.info("Arthas MCP Bootstrap shutdown completed"); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/ArthasMcpServer.java
core/src/main/java/com/taobao/arthas/core/mcp/ArthasMcpServer.java
package com.taobao.arthas.core.mcp; import com.fasterxml.jackson.databind.ObjectMapper; import com.taobao.arthas.core.mcp.tool.util.McpToolUtils; import com.taobao.arthas.mcp.server.CommandExecutor; import com.taobao.arthas.mcp.server.protocol.config.McpServerProperties; import com.taobao.arthas.mcp.server.protocol.config.McpServerProperties.ServerProtocol; import com.taobao.arthas.mcp.server.protocol.server.McpNettyServer; import com.taobao.arthas.mcp.server.protocol.server.McpServer; import com.taobao.arthas.mcp.server.protocol.server.McpStatelessNettyServer; import com.taobao.arthas.mcp.server.protocol.server.handler.McpHttpRequestHandler; import com.taobao.arthas.mcp.server.protocol.server.handler.McpStatelessHttpRequestHandler; import com.taobao.arthas.mcp.server.protocol.server.handler.McpStreamableHttpRequestHandler; import com.taobao.arthas.mcp.server.protocol.server.transport.NettyStatelessServerTransport; import com.taobao.arthas.mcp.server.protocol.server.transport.NettyStreamableServerTransportProvider; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema.Implementation; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema.ServerCapabilities; import com.taobao.arthas.mcp.server.protocol.spec.McpStreamableServerTransportProvider; import com.taobao.arthas.mcp.server.tool.DefaultToolCallbackProvider; import com.taobao.arthas.mcp.server.tool.ToolCallback; import com.taobao.arthas.mcp.server.tool.ToolCallbackProvider; import com.taobao.arthas.mcp.server.util.JsonParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.util.*; import java.util.stream.Collectors; /** * Arthas MCP Server * Used to expose HTTP service after Arthas startup */ public class ArthasMcpServer { private static final Logger logger = LoggerFactory.getLogger(ArthasMcpServer.class); /** * Arthas tool base package in core module */ public static final String ARTHAS_TOOL_BASE_PACKAGE = "com.taobao.arthas.core.mcp.tool.function"; private McpNettyServer streamableServer; private McpStatelessNettyServer statelessServer; private final String mcpEndpoint; private final ServerProtocol protocol; private final CommandExecutor commandExecutor; private McpHttpRequestHandler unifiedMcpHandler; private McpStreamableHttpRequestHandler streamableHandler; private McpStatelessHttpRequestHandler statelessHandler; public static final String DEFAULT_MCP_ENDPOINT = "/mcp"; public ArthasMcpServer(String mcpEndpoint, CommandExecutor commandExecutor, String protocol) { this.mcpEndpoint = mcpEndpoint != null ? mcpEndpoint : DEFAULT_MCP_ENDPOINT; this.commandExecutor = commandExecutor; ServerProtocol resolvedProtocol = ServerProtocol.STREAMABLE; if (protocol != null && !protocol.trim().isEmpty()) { try { resolvedProtocol = ServerProtocol.valueOf(protocol.toUpperCase()); } catch (IllegalArgumentException e) { logger.warn("Invalid MCP protocol: {}. Using default: STREAMABLE", protocol); } } this.protocol = resolvedProtocol; } public McpHttpRequestHandler getMcpRequestHandler() { return unifiedMcpHandler; } /** * Start MCP server */ public void start() { try { // Register Arthas-specific JSON filter com.taobao.arthas.core.mcp.util.McpObjectVOFilter.register(); McpServerProperties properties = new McpServerProperties.Builder() .name("arthas-mcp-server") .version("4.1.4") .mcpEndpoint(mcpEndpoint) .toolChangeNotification(true) .resourceChangeNotification(true) .promptChangeNotification(true) .objectMapper(JsonParser.getObjectMapper()) .protocol(this.protocol) .build(); // Use Arthas tool base package from core module DefaultToolCallbackProvider toolCallbackProvider = new DefaultToolCallbackProvider(); toolCallbackProvider.setToolBasePackage(ARTHAS_TOOL_BASE_PACKAGE); ToolCallback[] callbacks = toolCallbackProvider.getToolCallbacks(); List<ToolCallback> providerToolCallbacks = Arrays.stream(callbacks) .filter(Objects::nonNull) .collect(Collectors.toList()); unifiedMcpHandler = McpHttpRequestHandler.builder() .mcpEndpoint(properties.getMcpEndpoint()) .objectMapper(properties.getObjectMapper()) .protocol(properties.getProtocol()) .build(); if (properties.getProtocol() == ServerProtocol.STREAMABLE) { McpStreamableServerTransportProvider transportProvider = createStreamableHttpTransportProvider(properties); streamableHandler = transportProvider.getMcpRequestHandler(); unifiedMcpHandler.setStreamableHandler(streamableHandler); McpServer.StreamableServerNettySpecification streamableServerNettySpecification = McpServer.netty(transportProvider) .serverInfo(new Implementation(properties.getName(), properties.getVersion())) .capabilities(buildServerCapabilities(properties)) .instructions(properties.getInstructions()) .requestTimeout(properties.getRequestTimeout()) .commandExecutor(commandExecutor) .objectMapper(properties.getObjectMapper() != null ? properties.getObjectMapper() : JsonParser.getObjectMapper()); streamableServerNettySpecification.tools( McpToolUtils.toStreamableToolSpecifications(providerToolCallbacks)); streamableServer = streamableServerNettySpecification.build(); } else { NettyStatelessServerTransport statelessTransport = createStatelessHttpTransport(properties); statelessHandler = statelessTransport.getMcpRequestHandler(); unifiedMcpHandler.setStatelessHandler(statelessHandler); McpServer.StatelessServerNettySpecification statelessServerNettySpecification = McpServer.netty(statelessTransport) .serverInfo(new Implementation(properties.getName(), properties.getVersion())) .capabilities(buildServerCapabilities(properties)) .instructions(properties.getInstructions()) .requestTimeout(properties.getRequestTimeout()) .commandExecutor(commandExecutor) .objectMapper(properties.getObjectMapper() != null ? properties.getObjectMapper() : JsonParser.getObjectMapper()); statelessServerNettySpecification.tools( McpToolUtils.toStatelessToolSpecifications(providerToolCallbacks)); statelessServer = statelessServerNettySpecification.build(); } logger.info("Arthas MCP server started successfully"); logger.info("- MCP Endpoint: {}", properties.getMcpEndpoint()); logger.info("- Transport mode: {}", properties.getProtocol()); logger.info("- Available tools: {}", providerToolCallbacks.size()); logger.info("- Server ready to accept connections"); } catch (Exception e) { logger.error("Failed to start Arthas MCP server", e); throw new RuntimeException("Failed to start Arthas MCP server", e); } } /** * Default keep-alive interval for MCP server (15 seconds) */ public static final Duration DEFAULT_KEEP_ALIVE_INTERVAL = Duration.ofSeconds(15); /** * Create HTTP transport provider */ private NettyStreamableServerTransportProvider createStreamableHttpTransportProvider(McpServerProperties properties) { return NettyStreamableServerTransportProvider.builder() .mcpEndpoint(properties.getMcpEndpoint()) .objectMapper(properties.getObjectMapper() != null ? properties.getObjectMapper() : new ObjectMapper()) .keepAliveInterval(DEFAULT_KEEP_ALIVE_INTERVAL) .build(); } private NettyStatelessServerTransport createStatelessHttpTransport(McpServerProperties properties) { return NettyStatelessServerTransport.builder() .mcpEndpoint(properties.getMcpEndpoint()) .objectMapper(properties.getObjectMapper() != null ? properties.getObjectMapper() : new ObjectMapper()) .build(); } private ServerCapabilities buildServerCapabilities(McpServerProperties properties) { return ServerCapabilities.builder() .prompts(new ServerCapabilities.PromptCapabilities(properties.isPromptChangeNotification())) .resources(new ServerCapabilities.ResourceCapabilities(properties.isResourceSubscribe(), properties.isResourceChangeNotification())) .tools(new ServerCapabilities.ToolCapabilities(properties.isToolChangeNotification())) .build(); } public void stop() { logger.info("Stopping Arthas MCP server..."); try { if (unifiedMcpHandler != null) { logger.debug("Shutting down unified MCP handler"); unifiedMcpHandler.closeGracefully().get(); logger.info("Unified MCP handler stopped successfully"); } if (streamableServer != null) { logger.debug("Shutting down streamable server"); streamableServer.closeGracefully().get(); logger.info("Streamable server stopped successfully"); } if (statelessServer != null) { logger.debug("Shutting down stateless server"); statelessServer.closeGracefully().get(); logger.info("Stateless server stopped successfully"); } logger.info("Arthas MCP server stopped completely"); } catch (Exception e) { logger.error("Failed to stop Arthas MCP server gracefully", e); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/util/McpObjectVOFilter.java
core/src/main/java/com/taobao/arthas/core/mcp/util/McpObjectVOFilter.java
package com.taobao.arthas.core.mcp.util; import com.alibaba.fastjson2.filter.ValueFilter; import com.taobao.arthas.core.GlobalOptions; import com.taobao.arthas.core.command.model.ObjectVO; import com.taobao.arthas.core.view.ObjectView; import com.taobao.arthas.mcp.server.util.JsonParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * mcp specific ObjectVO serialization filter */ public class McpObjectVOFilter implements ValueFilter { private static final Logger logger = LoggerFactory.getLogger(McpObjectVOFilter.class); private static final McpObjectVOFilter INSTANCE = new McpObjectVOFilter(); private static volatile boolean registered = false; /** * Register this filter to JsonParser */ public static void register() { if (!registered) { synchronized (McpObjectVOFilter.class) { if (!registered) { JsonParser.registerFilter(INSTANCE); registered = true; logger.debug("McpObjectVOFilter registered to JsonParser"); } } } } @Override public Object apply(Object object, String name, Object value) { if (value == null) { return null; } // Direct type check instead of reflection if (value instanceof ObjectVO) { return handleObjectVO((ObjectVO) value); } return value; } private Object handleObjectVO(ObjectVO objectVO) { try { Object innerObject = objectVO.getObject(); Integer expand = objectVO.getExpand(); if (innerObject == null) { return "null"; } if (objectVO.needExpand()) { // 根据 GlobalOptions.isUsingJson 配置决定输出格式 if (GlobalOptions.isUsingJson) { return drawJsonView(innerObject); } else { return drawObjectView(objectVO); } } else { return objectToString(innerObject); } } catch (Exception e) { logger.warn("Failed to handle ObjectVO: {}", e.getMessage()); return "{\"error\":\"ObjectVO serialization failed\"}"; } } /** * 使用 ObjectView 输出对象结构 */ private String drawObjectView(ObjectVO objectVO) { try { ObjectView objectView = new ObjectView(objectVO); return objectView.draw(); } catch (Exception e) { logger.debug("ObjectView serialization failed, using toString: {}", e.getMessage()); return objectToString(objectVO.getObject()); } } /** * 使用 JSON 格式输出对象 */ private String drawJsonView(Object object) { try { return ObjectView.toJsonString(object); } catch (Exception e) { logger.debug("ObjectView-style serialization failed, using toString: {}", e.getMessage()); return objectToString(object); } } private String objectToString(Object object) { if (object == null) { return "null"; } try { return object.toString(); } catch (Exception e) { return object.getClass().getSimpleName() + "@" + Integer.toHexString(object.hashCode()); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/util/McpAuthExtractor.java
core/src/main/java/com/taobao/arthas/core/mcp/util/McpAuthExtractor.java
package com.taobao.arthas.core.mcp.util; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.util.AttributeKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * MCP认证信息提取工具 * * @author Yeaury */ public class McpAuthExtractor { private static final Logger logger = LoggerFactory.getLogger(McpAuthExtractor.class); public static final String MCP_AUTH_SUBJECT_KEY = "mcp.auth.subject"; /** * User ID 在 McpTransportContext 中的 key */ public static final String MCP_USER_ID_KEY = "mcp.user.id"; /** * 从 HTTP Header 中提取 User ID 的 header 名称 */ public static final String USER_ID_HEADER = "X-User-Id"; public static final AttributeKey<Object> SUBJECT_ATTRIBUTE_KEY = AttributeKey.valueOf("arthas.auth.subject"); /** * 从ChannelHandlerContext中提取认证主体 * * @param ctx Netty ChannelHandlerContext * @return 认证主体对象,如果未认证则返回null */ public static Object extractAuthSubjectFromContext(ChannelHandlerContext ctx) { if (ctx == null || ctx.channel() == null) { return null; } try { Object subject = ctx.channel().attr(SUBJECT_ATTRIBUTE_KEY).get(); if (subject != null) { logger.debug("Extracted auth subject from channel context: {}", subject.getClass().getSimpleName()); return subject; } } catch (Exception e) { logger.debug("Failed to extract auth subject from context: {}", e.getMessage()); } return null; } /** * 从 HTTP 请求中提取 User ID * * @param request HTTP 请求 * @return User ID,如果不存在则返回 null */ public static String extractUserIdFromRequest(FullHttpRequest request) { if (request == null) { return null; } String userId = request.headers().get(USER_ID_HEADER); if (userId != null && !userId.trim().isEmpty()) { logger.debug("Extracted userId from HTTP header {}: {}", USER_ID_HEADER, userId); return userId.trim(); } return null; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/util/McpToolUtils.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/util/McpToolUtils.java
package com.taobao.arthas.core.mcp.tool.util; import com.fasterxml.jackson.databind.ObjectMapper; import com.taobao.arthas.mcp.server.session.ArthasCommandContext; import com.taobao.arthas.mcp.server.protocol.server.McpServerFeatures; import com.taobao.arthas.mcp.server.protocol.server.McpStatelessServerFeatures; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema; import com.taobao.arthas.mcp.server.tool.ToolCallback; import com.taobao.arthas.mcp.server.tool.ToolContext; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; public final class McpToolUtils { public static final String TOOL_CONTEXT_MCP_EXCHANGE_KEY = "exchange"; public static final String TOOL_CONTEXT_COMMAND_CONTEXT_KEY = "commandContext"; public static final String MCP_TRANSPORT_CONTEXT = "mcpTransportContext"; public static final String PROGRESS_TOKEN = "progressToken"; private McpToolUtils() { } public static List<McpServerFeatures.ToolSpecification> toStreamableToolSpecifications( List<ToolCallback> tools) { if (tools == null || tools.isEmpty()) { return Collections.emptyList(); } // De-duplicate tools by their name, keeping the first occurrence of each tool name return tools.stream() .filter(Objects::nonNull) .collect(Collectors.toMap( tool -> tool.getToolDefinition().getName(), // Key: tool name tool -> tool, // Value: the tool itself (existing, replacement) -> existing // On duplicate key, keep the existing tool )) .values() .stream() .map(McpToolUtils::toToolSpecification) .collect(Collectors.toList()); } public static McpServerFeatures.ToolSpecification toToolSpecification(ToolCallback toolCallback) { McpSchema.Tool tool = new McpSchema.Tool( toolCallback.getToolDefinition().getName(), toolCallback.getToolDefinition().getDescription(), toolCallback.getToolDefinition().getInputSchema() ); McpServerFeatures.ToolCallFunction callFunction = (exchange, commandContext, request) -> { try { Map<String, Object> contextMap = new HashMap<>(); contextMap.put(TOOL_CONTEXT_MCP_EXCHANGE_KEY, exchange); contextMap.put(TOOL_CONTEXT_COMMAND_CONTEXT_KEY, commandContext); contextMap.put(PROGRESS_TOKEN, request.progressToken()); // Add MCP_TRANSPORT_CONTEXT from exchange for streamable tools to access auth info if (exchange != null && exchange.getTransportContext() != null) { contextMap.put(MCP_TRANSPORT_CONTEXT, exchange.getTransportContext()); } ToolContext toolContext = new ToolContext(contextMap); String requestJson = convertParametersToString(request.getArguments()); String callResult = toolCallback.call(requestJson, toolContext); return CompletableFuture.completedFuture(createSuccessResult(callResult)); } catch (Exception e) { return CompletableFuture.completedFuture(createErrorResult(e.getMessage())); } }; return new McpServerFeatures.ToolSpecification(tool, callFunction); } public static List<McpStatelessServerFeatures.ToolSpecification> toStatelessToolSpecifications(List<ToolCallback> providerToolCallbacks) { if (providerToolCallbacks == null || providerToolCallbacks.isEmpty()) { return Collections.emptyList(); } // De-duplicate tools by their name, keeping the first occurrence of each tool name return providerToolCallbacks.stream() .filter(Objects::nonNull) .collect(Collectors.toMap( tool -> tool.getToolDefinition().getName(), // Key: tool name tool -> tool, // Value: the tool itself (existing, replacement) -> existing // On duplicate key, keep the existing tool )) .values() .stream() .map(McpToolUtils::toStatelessToolSpecification) .collect(Collectors.toList()); } public static McpStatelessServerFeatures.ToolSpecification toStatelessToolSpecification(ToolCallback toolCallback) { McpSchema.Tool tool = new McpSchema.Tool( toolCallback.getToolDefinition().getName(), toolCallback.getToolDefinition().getDescription(), toolCallback.getToolDefinition().getInputSchema() ); McpStatelessServerFeatures.ToolCallFunction callFunction = (context, commandContext, arguments) -> { try { Map<String, Object> contextMap = new HashMap<>(); contextMap.put(MCP_TRANSPORT_CONTEXT, context); contextMap.put(TOOL_CONTEXT_COMMAND_CONTEXT_KEY, commandContext); ToolContext toolContext = new ToolContext(contextMap); String argumentsJson = convertParametersToString(arguments); String callResult = toolCallback.call(argumentsJson, toolContext); return CompletableFuture.completedFuture(createSuccessResult(callResult)); } catch (Exception e) { return CompletableFuture.completedFuture(createErrorResult("Error executing tool: " + e.getMessage())); } }; return new McpStatelessServerFeatures.ToolSpecification(tool, callFunction); } private static String convertParametersToString(Map<String, Object> parameters) { if (parameters == null) { return ""; } try { return new ObjectMapper().writeValueAsString(parameters); } catch (Exception e) { return parameters.toString(); } } private static McpSchema.CallToolResult createSuccessResult(String content) { List<McpSchema.Content> contents = new ArrayList<>(); String safeContent = (content != null && !content.trim().isEmpty()) ? content : "{}"; contents.add(new McpSchema.TextContent(safeContent)); return McpSchema.CallToolResult.builder() .content(contents) .isError(false) .build(); } private static McpSchema.CallToolResult createErrorResult(String errorMessage) { List<McpSchema.Content> contents = new ArrayList<>(); String safeErrorMessage = (errorMessage != null && !errorMessage.trim().isEmpty()) ? errorMessage : "Unknown error occurred"; contents.add(new McpSchema.TextContent(safeErrorMessage)); return McpSchema.CallToolResult.builder() .content(contents) .isError(true) .build(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/AbstractArthasTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/AbstractArthasTool.java
package com.taobao.arthas.core.mcp.tool.function; import com.taobao.arthas.mcp.server.session.ArthasCommandContext; import com.taobao.arthas.core.mcp.util.McpAuthExtractor; import com.taobao.arthas.mcp.server.protocol.server.McpNettyServerExchange; import com.taobao.arthas.mcp.server.protocol.server.McpTransportContext; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.util.JsonParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; import static com.taobao.arthas.core.mcp.tool.util.McpToolUtils.*; import static com.taobao.arthas.core.mcp.tool.function.StreamableToolUtils.*; /** * Arthas工具的抽象基类 */ public abstract class AbstractArthasTool { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); public static final int DEFAULT_TIMEOUT_SECONDS = (int) (StreamableToolUtils.DEFAULT_TIMEOUT_MS / 1000); private static final long DEFAULT_ASYNC_START_RETRY_INTERVAL_MS = 100L; private static final long DEFAULT_ASYNC_START_MAX_WAIT_MS = 3000L; /** * 工具执行上下文,包含所有必要的上下文信息 */ protected static class ToolExecutionContext { private final ArthasCommandContext commandContext; private final McpTransportContext mcpTransportContext; private final Object authSubject; private final String userId; private final McpNettyServerExchange exchange; private final String progressToken; private final boolean isStreamable; public ToolExecutionContext(ToolContext toolContext, boolean isStreamable) { this.commandContext = (ArthasCommandContext) toolContext.getContext().get(TOOL_CONTEXT_COMMAND_CONTEXT_KEY); this.isStreamable = isStreamable; // 尝试获取 Exchange (在 Stateless 模式下为 null) this.exchange = (McpNettyServerExchange) toolContext.getContext().get(TOOL_CONTEXT_MCP_EXCHANGE_KEY); // 尝试获取 Progress Token Object progressTokenObj = toolContext.getContext().get(PROGRESS_TOKEN); this.progressToken = progressTokenObj != null ? String.valueOf(progressTokenObj) : null; // 尝试获取 Transport Context (在 Stateless 模式下可能为 null) this.mcpTransportContext = (McpTransportContext) toolContext.getContext().get(MCP_TRANSPORT_CONTEXT); // 从 Transport Context 中提取认证信息 if (this.mcpTransportContext != null) { this.authSubject = mcpTransportContext.get(McpAuthExtractor.MCP_AUTH_SUBJECT_KEY); this.userId = (String) mcpTransportContext.get(McpAuthExtractor.MCP_USER_ID_KEY); } else { this.authSubject = null; this.userId = null; } } public ArthasCommandContext getCommandContext() { return commandContext; } public McpTransportContext getMcpTransportContext() { return mcpTransportContext; } public Object getAuthSubject() { return authSubject; } /** * 获取用户 ID * @return 用户 ID,如果未设置则返回 null */ public String getUserId() { return userId; } public McpNettyServerExchange getExchange() { return exchange; } public String getProgressToken() { return progressToken; } public boolean isStreamable() { return isStreamable; } } protected String executeSync(ToolContext toolContext, String commandStr) { try { ToolExecutionContext execContext = new ToolExecutionContext(toolContext, false); // 使用带 userId 参数的 executeSync 方法 Object result = execContext.getCommandContext().executeSync( commandStr, execContext.getAuthSubject(), execContext.getUserId() ); return JsonParser.toJson(result); } catch (Exception e) { logger.error("Error executing sync command: {}", commandStr, e); return JsonParser.toJson(createErrorResponse("Error executing command: " + e.getMessage())); } } protected String executeStreamable(ToolContext toolContext, String commandStr, Integer expectedResultCount, Integer pollIntervalMs, Integer timeoutMs, String successMessage) { ToolExecutionContext execContext = null; try { execContext = new ToolExecutionContext(toolContext, true); logger.info("Starting streamable execution: {}", commandStr); // Set userId to session before async execution for stat reporting if (execContext.getUserId() != null) { execContext.getCommandContext().setSessionUserId(execContext.getUserId()); } Map<String, Object> asyncResult = executeAsyncWithRetry(execContext, commandStr, timeoutMs); if (!isAsyncExecutionStarted(asyncResult)) { String errorMessage = asyncResult != null ? String.valueOf(asyncResult.get("error")) : "unknown error"; return JsonParser.toJson(createErrorResponse("Failed to start command: " + errorMessage)); } logger.debug("Async execution started: {}", asyncResult); Map<String, Object> results = executeAndCollectResults( execContext.getExchange(), execContext.getCommandContext(), expectedResultCount, pollIntervalMs, timeoutMs, execContext.getProgressToken() ); if (results != null) { String message = successMessage != null ? successMessage : "Command execution completed successfully"; if (Boolean.TRUE.equals(results.get("timedOut"))) { Integer count = (Integer) results.get("resultCount"); if (count != null && count > 0) { message = "Command execution ended (Timed out). Captured " + count + " results."; } else { message = "Command execution ended (Timed out). No results captured within the time limit."; } } return JsonParser.toJson(createCompletedResponse(message, results)); } else { return JsonParser.toJson(createErrorResponse("Command execution failed due to timeout or error limits exceeded")); } } catch (Exception e) { logger.error("Error executing streamable command: {}", commandStr, e); return JsonParser.toJson(createErrorResponse("Error executing command: " + e.getMessage())); } finally { if (execContext != null) { try { // 确保前台任务被及时释放,避免占用 session 影响后续 streamable 工具执行 execContext.getCommandContext().interruptJob(); } catch (Exception ignored) { } } } } private static boolean isAsyncExecutionStarted(Map<String, Object> asyncResult) { if (asyncResult == null) { return false; } Object success = asyncResult.get("success"); return Boolean.TRUE.equals(success); } private static boolean isRetryableAsyncStartError(Map<String, Object> asyncResult) { if (asyncResult == null) { return false; } Object success = asyncResult.get("success"); if (Boolean.TRUE.equals(success)) { return false; } Object error = asyncResult.get("error"); if (error == null) { return false; } String message = String.valueOf(error); return message.contains("Another job is running") || message.contains("Another command is executing"); } private static Map<String, Object> executeAsyncWithRetry(ToolExecutionContext execContext, String commandStr, Integer timeoutMs) { long maxWaitMs = DEFAULT_ASYNC_START_MAX_WAIT_MS; if (timeoutMs != null && timeoutMs > 0) { maxWaitMs = Math.min(maxWaitMs, timeoutMs); } long deadline = System.currentTimeMillis() + maxWaitMs; Map<String, Object> asyncResult = null; while (System.currentTimeMillis() < deadline) { asyncResult = execContext.getCommandContext().executeAsync(commandStr); if (isAsyncExecutionStarted(asyncResult)) { return asyncResult; } if (isRetryableAsyncStartError(asyncResult)) { try { execContext.getCommandContext().interruptJob(); } catch (Exception ignored) { } try { Thread.sleep(DEFAULT_ASYNC_START_RETRY_INTERVAL_MS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return asyncResult; } continue; } return asyncResult; } return asyncResult; } protected StringBuilder buildCommand(String baseCommand) { return new StringBuilder(baseCommand); } protected void addParameter(StringBuilder cmd, String flag, String value) { if (value != null && !value.trim().isEmpty()) { cmd.append(" ").append(flag).append(" ").append(value.trim()); } } protected void addParameter(StringBuilder cmd, String value) { if (value != null && !value.trim().isEmpty()) { // Safely quote the value to prevent command injection cmd.append(" '").append(value.trim().replace("'", "'\\''")).append("'"); } } protected void addFlag(StringBuilder cmd, String flag, Boolean condition) { if (Boolean.TRUE.equals(condition)) { cmd.append(" ").append(flag); } } /** * 添加引用参数到命令中(用于包含空格的参数) */ protected void addQuotedParameter(StringBuilder cmd, String value) { if (value != null && !value.trim().isEmpty()) { cmd.append(" '").append(value.trim()).append("'"); } } protected int getDefaultValue(Integer value, int defaultValue) { return (value != null && value > 0) ? value : defaultValue; } protected String getDefaultValue(String value, String defaultValue) { return (value != null && !value.trim().isEmpty()) ? value.trim() : defaultValue; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/StreamableToolUtils.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/StreamableToolUtils.java
package com.taobao.arthas.core.mcp.tool.function; import com.taobao.arthas.core.command.model.*; import com.taobao.arthas.mcp.server.session.ArthasCommandContext; import com.taobao.arthas.mcp.server.protocol.server.McpNettyServerExchange; import com.taobao.arthas.mcp.server.protocol.spec.McpSchema; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * 同步工具的工具类 * 提供同步执行命令并收集所有结果的功能 * * @author Yeaury */ public final class StreamableToolUtils { private static final Logger logger = LoggerFactory.getLogger(StreamableToolUtils.class); private static final int DEFAULT_POLL_INTERVAL_MS = 100; // 默认轮询间隔100ms private static final int ERROR_RETRY_INTERVAL_MS = 500; // 错误重试间隔500ms public static final long DEFAULT_TIMEOUT_MS = 30000L; // 默认超时时间30秒 private static final int MAX_ERROR_RETRIES = 10; // 最大错误重试次数 public static final int MIN_ALLOW_INPUT_COUNT_TO_COMPLETE = 2; private StreamableToolUtils() { } /** * 同步执行命令并收集所有结果,支持进度通知 * * @param exchange MCP交换器,用于发送进度通知 * @param commandContext 命令上下文 * @param expectedResultCount 预期结果数量 * @param intervalMs 轮询间隔 * @param timeoutMs 超时时间(毫秒) * @param progressToken 进度令牌 * @return 包含所有结果的Map,如果执行失败返回null */ public static Map<String, Object> executeAndCollectResults(McpNettyServerExchange exchange, ArthasCommandContext commandContext, Integer expectedResultCount, Integer intervalMs, Integer timeoutMs, String progressToken) { List<Object> allResults = new ArrayList<>(); int errorRetries = 0; int allowInputCount = 0; int totalResultCount = 0; // 轮询间隔使用命令执行间隙的 1/10,事件驱动则在命令中自定义默认轮询间隔 // 工具中默认轮询间隔为200ms int pullIntervalMs = (intervalMs != null && intervalMs > 0) ? intervalMs : DEFAULT_POLL_INTERVAL_MS; // 计算截止时间 // 如果没有指定超时时间,则使用默认超时时间 long executionTimeoutMs = (timeoutMs != null && timeoutMs > 0) ? timeoutMs : DEFAULT_TIMEOUT_MS; long deadline = System.currentTimeMillis() + executionTimeoutMs; boolean timedOut = false; try { while (System.currentTimeMillis() < deadline) { try { Map<String, Object> results = commandContext.pullResults(); if (results == null) { Thread.sleep(pullIntervalMs); continue; } errorRetries = 0; // 检查是否有错误消息 String errorMessage = checkForErrorMessages(results); if (errorMessage != null) { logger.warn("Command execution failed with error: {}", errorMessage); return createErrorResponseWithResults(errorMessage, allResults, totalResultCount); } Map<String, Object> filteredResults = filterCommandSpecificResults(results); List<Object> currentBatchResults = getCommandSpecificResults(filteredResults); if (currentBatchResults != null && !currentBatchResults.isEmpty()) { allResults.addAll(currentBatchResults); totalResultCount += currentBatchResults.size(); logger.debug("Collected {} results, total: {}", currentBatchResults.size(), totalResultCount); if (exchange != null) { sendProgressNotification(exchange, totalResultCount, expectedResultCount != null ? expectedResultCount : totalResultCount, progressToken); } } boolean commandCompleted = checkCommandCompletion(results, allowInputCount); if (commandCompleted) { allowInputCount++; } String jobStatus = (String) results.get("jobStatus"); // 判断是否应该结束 // 如果是TERMINATED状态,或者命令已完成且允许输入次数大于等于2,或者实际结果数量达到预期结果数量 boolean hasExpectedResultCount = (expectedResultCount != null); boolean reachedExpectedResultCount = hasExpectedResultCount && totalResultCount >= expectedResultCount; boolean allowInputCompletion = !hasExpectedResultCount && commandCompleted && allowInputCount >= MIN_ALLOW_INPUT_COUNT_TO_COMPLETE; if ("TERMINATED".equals(jobStatus) || allowInputCompletion || reachedExpectedResultCount) { logger.info("Command completed. Total results collected: {}, Expected: {}", totalResultCount, expectedResultCount); break; } } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.warn("Command execution interrupted"); return null; } catch (Exception e) { if (++errorRetries >= MAX_ERROR_RETRIES) { logger.error("Maximum error retries exceeded", e); return null; } try { Thread.sleep(ERROR_RETRY_INTERVAL_MS); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); return null; } } } // 检查是否超时 if (System.currentTimeMillis() >= deadline) { timedOut = true; } return createFinalResult(allResults, totalResultCount, timedOut, executionTimeoutMs); } catch (Exception e) { logger.error("Error in command execution", e); return null; } } private static boolean checkCommandCompletion(Map<String, Object> results, int currentAllowInputCount) { if (results == null) { return false; } @SuppressWarnings("unchecked") List<Object> resultList = (List<Object>) results.get("results"); if (resultList == null || resultList.isEmpty()) { return false; } for (Object result : resultList) { // Direct type check instead of reflection if (result instanceof InputStatusModel) { InputStatusModel inputStatusModel = (InputStatusModel) result; InputStatus inputStatus = inputStatusModel.getInputStatus(); if (inputStatus == InputStatus.ALLOW_INPUT) { logger.debug("Command completion detected: ALLOW_INPUT (count: {})", currentAllowInputCount + 1); return true; } } } return false; } /** * 检查结果中是否包含错误消息 */ private static String checkForErrorMessages(Map<String, Object> results) { if (results == null) { return null; } @SuppressWarnings("unchecked") List<Object> resultList = (List<Object>) results.get("results"); if (resultList == null || resultList.isEmpty()) { return null; } for (Object result : resultList) { String message = null; // Direct type checks instead of reflection if (result instanceof MessageModel) { message = ((MessageModel) result).getMessage(); } else if (result instanceof EnhancerModel) { message = ((EnhancerModel) result).getMessage(); } else if (result instanceof StatusModel) { message = ((StatusModel) result).getMessage(); } else if (result instanceof CommandRequestModel) { message = ((CommandRequestModel) result).getMessage(); } if (message != null && isErrorMessage(message)) { return message; } } return null; } private static boolean isErrorMessage(String message) { return message.matches(".*\\b(failed|error|exception)\\b.*") || message.contains("Malformed OGNL expression") || message.contains("ParseException") || message.contains("ExpressionSyntaxException") || message.matches(".*Exception.*") || message.matches(".*Error.*"); } private static Map<String, Object> filterCommandSpecificResults(Map<String, Object> results) { if (results == null) { return new HashMap<>(); } Map<String, Object> filteredResults = new HashMap<>(results); @SuppressWarnings("unchecked") List<Object> resultList = (List<Object>) results.get("results"); if (resultList == null || resultList.isEmpty()) { return filteredResults; } // Filter out auxiliary model types using direct type checks List<Object> filteredResultList = resultList.stream() .filter(result -> !isAuxiliaryModel(result)) .collect(Collectors.toList()); filteredResults.put("results", filteredResultList); filteredResults.put("resultCount", filteredResultList.size()); return filteredResults; } /** * Check if the result is an auxiliary model type that should be filtered out */ private static boolean isAuxiliaryModel(Object result) { return result instanceof InputStatusModel || result instanceof StatusModel || result instanceof WelcomeModel || result instanceof MessageModel || result instanceof CommandRequestModel || result instanceof SessionModel || result instanceof EnhancerModel; } private static List<Object> getCommandSpecificResults(Map<String, Object> filteredResults) { if (filteredResults == null) { return new ArrayList<>(); } @SuppressWarnings("unchecked") List<Object> resultList = (List<Object>) filteredResults.get("results"); return resultList != null ? resultList : new ArrayList<>(); } /** * 发送进度通知 */ private static void sendProgressNotification(McpNettyServerExchange exchange, int currentResultCount, int totalExpected, String progressToken) { try { if (progressToken != null && !progressToken.trim().isEmpty()) { exchange.progressNotification(new McpSchema.ProgressNotification( progressToken, currentResultCount, (double) totalExpected )).join(); } } catch (Exception e) { logger.error("Error sending progress notification", e); } } public static Map<String, Object> createErrorResponse(String message) { Map<String, Object> response = new HashMap<>(); response.put("error", true); response.put("message", message); response.put("status", "error"); response.put("stage", "final"); return response; } public static Map<String, Object> createErrorResponseWithResults(String message, List<Object> collectedResults, int resultCount) { Map<String, Object> response = createErrorResponse(message); response.put("results", collectedResults != null ? collectedResults : new ArrayList<>()); response.put("resultCount", resultCount); return response; } private static Map<String, Object> createFinalResult(List<Object> allResults, int totalResultCount, boolean timedOut, long timeoutMs) { Map<String, Object> finalResult = new HashMap<>(); finalResult.put("results", allResults); finalResult.put("resultCount", totalResultCount); finalResult.put("status", "completed"); finalResult.put("stage", "final"); finalResult.put("timedOut", timedOut); if (timedOut) { logger.warn("Command execution timed out after {} ms", timeoutMs); finalResult.put("warning", "Command execution timed out after " + timeoutMs + " ms."); } return finalResult; } public static Map<String, Object> createCompletedResponse(String message, Map<String, Object> results) { Map<String, Object> response = new HashMap<>(); response.put("status", "completed"); response.put("message", message); response.put("stage", "final"); if (results != null) { response.putAll(results); } return response; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/klass100/ClassLoaderTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/klass100/ClassLoaderTool.java
package com.taobao.arthas.core.mcp.tool.function.klass100; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class ClassLoaderTool extends AbstractArthasTool { public static final String MODE_STATS = "stats"; public static final String MODE_INSTANCES = "instances"; public static final String MODE_TREE = "tree"; public static final String MODE_ALL_CLASSES = "all-classes"; public static final String MODE_URL_STATS = "url-stats"; public static final String MODE_URL_CLASSES = "url-classes"; @Tool( name = "classloader", description = "ClassLoader 诊断工具,可以查看类加载器统计信息、继承树、URLs,以及进行资源查找和类加载操作。搜索类的场景优先使用 sc 工具" ) public String classloader( @ToolParam(description = "显示模式:stats(统计信息,默认), instances(实例详情), tree(继承树), all-classes(所有类,慎用), url-stats(URL统计), url-classes(URL与类关系)", required = false) String mode, @ToolParam(description = "ClassLoader的hashcode(16进制),用于指定特定的ClassLoader", required = false) String classLoaderHash, @ToolParam(description = "ClassLoader的完整类名,如sun.misc.Launcher$AppClassLoader,可替代hashcode", required = false) String classLoaderClass, @ToolParam(description = "要查找的资源名称,如META-INF/MANIFEST.MF", required = false) String resource, @ToolParam(description = "要加载的类名,支持全限定名", required = false) String loadClass, @ToolParam(description = "详情模式:列出每个 URL/jar 中的类名(等价于 -d),仅在 mode=url-classes 时生效", required = false) Boolean details, @ToolParam(description = "按 jar 包名/URL 关键字过滤,仅在 mode=url-classes 时生效", required = false) String jar, @ToolParam(description = "按类名/包名关键字过滤,仅在 mode=url-classes 时生效", required = false) String classFilter, @ToolParam(description = "是否使用正则匹配 jar/class(等价于 -E),仅在 mode=url-classes 时生效", required = false) Boolean regex, @ToolParam(description = "详情模式下每个 URL/jar 最多展示类数量(等价于 -n),默认 100,仅在 mode=url-classes 时生效", required = false) Integer limit, ToolContext toolContext) { StringBuilder cmd = buildCommand("classloader"); if (mode != null) { switch (mode.toLowerCase()) { case MODE_INSTANCES: cmd.append(" -l"); break; case MODE_TREE: cmd.append(" -t"); break; case MODE_ALL_CLASSES: cmd.append(" -a"); break; case MODE_URL_STATS: cmd.append(" --url-stat"); break; case MODE_URL_CLASSES: cmd.append(" --url-classes"); break; case MODE_STATS: default: break; } } if (classLoaderHash != null && !classLoaderHash.trim().isEmpty()) { addParameter(cmd, "-c", classLoaderHash); } else if (classLoaderClass != null && !classLoaderClass.trim().isEmpty()) { addParameter(cmd, "--classLoaderClass", classLoaderClass); } addParameter(cmd, "-r", resource); addParameter(cmd, "--load", loadClass); if (mode != null && MODE_URL_CLASSES.equalsIgnoreCase(mode)) { addFlag(cmd, "-d", details); addFlag(cmd, "-E", regex); if (limit != null && limit > 0) { addParameter(cmd, "-n", String.valueOf(limit)); } addParameter(cmd, "--jar", jar); addParameter(cmd, "--class", classFilter); } return executeSync(toolContext, cmd.toString()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/klass100/RedefineTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/klass100/RedefineTool.java
package com.taobao.arthas.core.mcp.tool.function.klass100; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class RedefineTool extends AbstractArthasTool { @Tool( name = "redefine", description = "重新加载类的字节码,允许在JVM运行时,重新加载已存在的类的字节码,实现热更新" ) public String redefine( @ToolParam(description = "要重新定义的.class文件路径,支持多个文件,用空格分隔") String classFilePaths, @ToolParam(description = "ClassLoader的hashcode(16进制),用于指定特定的ClassLoader", required = false) String classLoaderHash, @ToolParam(description = "指定执行表达式的ClassLoader的class name,如sun.misc.Launcher$AppClassLoader,可替代hashcode", required = false) String classLoaderClass, ToolContext toolContext) { StringBuilder cmd = buildCommand("redefine"); addParameter(cmd, classFilePaths); if (classLoaderHash != null && !classLoaderHash.trim().isEmpty()) { addParameter(cmd, "-c", classLoaderHash); } else if (classLoaderClass != null && !classLoaderClass.trim().isEmpty()) { addParameter(cmd, "--classLoaderClass", classLoaderClass); } return executeSync(toolContext, cmd.toString()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/klass100/DumpClassTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/klass100/DumpClassTool.java
package com.taobao.arthas.core.mcp.tool.function.klass100; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class DumpClassTool extends AbstractArthasTool { /** * Dump 命令 - 将JVM中已加载的类字节码导出到指定目录 * 适用于批量下载指定包目录的class字节码 */ @Tool( name = "dump", description = "将JVM中实际运行的class字节码dump到指定目录,适用于批量下载指定包目录的class字节码" ) public String dump( @ToolParam(description = "类名表达式匹配,如java.lang.String或demo.MathGame") String classPattern, @ToolParam(description = "指定输出目录,默认为arthas-output文件夹", required = false) String outputDir, @ToolParam(description = "ClassLoader的hashcode(16进制),用于指定特定的ClassLoader", required = false) String classLoaderHashcode, @ToolParam(description = "ClassLoader的完整类名,如sun.misc.Launcher$AppClassLoader,可替代hashcode", required = false) String classLoaderClass, @ToolParam(description = "是否包含子类,默认为false", required = false) Boolean includeInnerClasses, @ToolParam(description = "限制dump的类数量,避免输出过多文件", required = false) Integer limit, ToolContext toolContext) { StringBuilder cmd = buildCommand("dump"); addParameter(cmd, classPattern); addParameter(cmd, "-d", outputDir); if (classLoaderHashcode != null && !classLoaderHashcode.trim().isEmpty()) { addParameter(cmd, "-c", classLoaderHashcode); } else if (classLoaderClass != null && !classLoaderClass.trim().isEmpty()) { addParameter(cmd, "--classLoaderClass", classLoaderClass); } addFlag(cmd, "--include-inner-classes", includeInnerClasses); if (limit != null && limit > 0) { cmd.append(" --limit ").append(limit); } return executeSync(toolContext, cmd.toString()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/klass100/MemoryCompilerTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/klass100/MemoryCompilerTool.java
package com.taobao.arthas.core.mcp.tool.function.klass100; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; import java.nio.file.Paths; public class MemoryCompilerTool extends AbstractArthasTool { public static final String DEFAULT_DUMP_DIR = Paths.get("arthas-output").toAbsolutePath().toString(); @Tool( name = "mc", description = "Memory Compiler/内存编译器,编译.java文件生成.class" ) public String mc( @ToolParam(description = "要编译的.java文件路径,支持多个文件,用空格分隔") String javaFilePaths, @ToolParam(description = "ClassLoader的hashcode(16进制),用于指定特定的ClassLoader", required = false) String classLoaderHash, @ToolParam(description = "ClassLoader的完整类名,如sun.misc.Launcher$AppClassLoader,可替代hashcode", required = false) String classLoaderClass, @ToolParam(description = "指定输出目录,默认为工作目录下arthas-output文件夹", required = false) String outputDir, ToolContext toolContext) { StringBuilder cmd = buildCommand("mc"); addParameter(cmd, javaFilePaths); if (classLoaderHash != null && !classLoaderHash.trim().isEmpty()) { addParameter(cmd, "-c", classLoaderHash); } else if (classLoaderClass != null && !classLoaderClass.trim().isEmpty()) { addParameter(cmd, "--classLoaderClass", classLoaderClass); } if (outputDir != null && !outputDir.trim().isEmpty()) { addParameter(cmd, "-d", outputDir); } else { cmd.append(" -d ").append(DEFAULT_DUMP_DIR); } return executeSync(toolContext, cmd.toString()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/klass100/RetransformTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/klass100/RetransformTool.java
package com.taobao.arthas.core.mcp.tool.function.klass100; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class RetransformTool extends AbstractArthasTool { @Tool( name = "retransform", description = "热加载类的字节码,允许对已加载的类进行字节码修改并使其生效" ) public String retransform( @ToolParam(description = "要操作的.class文件路径,支持多个文件,用空格分隔") String classFilePaths, @ToolParam(description = "ClassLoader的hashcode(16进制),用于指定特定的ClassLoader", required = false) String classLoaderHash, @ToolParam(description = "ClassLoader的完整类名,如sun.misc.Launcher$AppClassLoader,可替代hashcode", required = false) String classLoaderClass, ToolContext toolContext) { StringBuilder cmd = buildCommand("retransform"); addParameter(cmd, classFilePaths); if (classLoaderHash != null && !classLoaderHash.trim().isEmpty()) { addParameter(cmd, "-c", classLoaderHash); } else if (classLoaderClass != null && !classLoaderClass.trim().isEmpty()) { addParameter(cmd, "--classLoaderClass", classLoaderClass); } return executeSync(toolContext, cmd.toString()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/klass100/SearchMethodTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/klass100/SearchMethodTool.java
package com.taobao.arthas.core.mcp.tool.function.klass100; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; /** * 方法搜索工具,对应 Arthas 的 sm 命令 * 用于搜索 JVM 中已加载类的方法,支持通配符和正则表达式匹配 */ public class SearchMethodTool extends AbstractArthasTool { @Tool( name = "sm", description = "搜索 JVM 中已加载类的方法。支持通配符(*)和正则表达式匹配,可查看方法的详细信息(返回类型、参数类型、异常类型、注解等)" ) public String sm( @ToolParam(description = "类名模式,支持全限定名。可使用通配符如 *StringUtils 或 org.apache.commons.lang.*,类名分隔符支持 '.' 或 '/'") String classPattern, @ToolParam(description = "方法名模式。可使用通配符如 get* 或 *Name。不指定时匹配所有方法", required = false) String methodPattern, @ToolParam(description = "是否显示方法的详细信息,包括返回类型、参数类型、异常类型、注解、类加载器等。默认为 true", required = false) Boolean detail, @ToolParam(description = "是否使用正则表达式匹配类名和方法名。默认为 false(使用通配符匹配)", required = false) Boolean regex, @ToolParam(description = "指定 ClassLoader 的 hashcode(16进制),用于在多个 ClassLoader 加载同名类时精确定位", required = false) String classLoaderHash, @ToolParam(description = "指定 ClassLoader 的完整类名,如 sun.misc.Launcher$AppClassLoader,可替代 hashcode", required = false) String classLoaderClass, @ToolParam(description = "最大匹配类数量限制。默认为 100,防止返回过多结果", required = false) Integer limit, ToolContext toolContext) { StringBuilder cmd = buildCommand("sm"); // 默认显示详细信息 boolean showDetail = (detail == null || detail); addFlag(cmd, "-d", showDetail); // 使用正则表达式匹配 addFlag(cmd, "-E", regex); // 指定类加载器(两种方式,优先使用 hashcode) if (classLoaderHash != null && !classLoaderHash.trim().isEmpty()) { addParameter(cmd, "-c", classLoaderHash); } else if (classLoaderClass != null && !classLoaderClass.trim().isEmpty()) { addParameter(cmd, "--classLoaderClass", classLoaderClass); } // 最大匹配类数量限制 if (limit != null && limit > 0) { addParameter(cmd, "-n", String.valueOf(limit)); } // 类名模式(必需参数) addParameter(cmd, classPattern); // 方法名模式(可选参数) if (methodPattern != null && !methodPattern.trim().isEmpty()) { addParameter(cmd, methodPattern); } return executeSync(toolContext, cmd.toString()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/klass100/SearchClassTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/klass100/SearchClassTool.java
package com.taobao.arthas.core.mcp.tool.function.klass100; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; /** * 类搜索工具,对应 Arthas 的 sc 命令 * 用于搜索 JVM 中已加载的类,支持通配符和正则表达式匹配 */ public class SearchClassTool extends AbstractArthasTool { @Tool( name = "sc", description = "搜索 JVM 中已加载的类。支持通配符(*)和正则表达式匹配,可查看类的详细信息(类加载器、接口、父类、注解等)和字段信息" ) public String sc( @ToolParam(description = "类名模式,支持全限定名。可使用通配符如 *StringUtils 或 org.apache.commons.lang.*,类名分隔符支持 '.' 或 '/'") String classPattern, @ToolParam(description = "是否显示类的详细信息,包括类加载器、代码来源、接口、父类、注解等。默认为 true", required = false) Boolean detail, @ToolParam(description = "是否显示类的所有成员变量(字段)信息。需要 detail 为 true 时才生效", required = false) Boolean field, @ToolParam(description = "是否使用正则表达式匹配类名。默认为 false(使用通配符匹配)", required = false) Boolean regex, @ToolParam(description = "指定 ClassLoader 的 hashcode(16进制),用于在多个 ClassLoader 加载同名类时精确定位", required = false) String classLoaderHash, @ToolParam(description = "指定 ClassLoader 的完整类名,如 sun.misc.Launcher$AppClassLoader,可替代 hashcode", required = false) String classLoaderClass, @ToolParam(description = "指定 ClassLoader 的 toString() 返回值,用于匹配特定的类加载器实例", required = false) String classLoaderStr, @ToolParam(description = "对象展开层级,用于展示更详细的对象结构。默认为 0", required = false) Integer expand, @ToolParam(description = "最大匹配类数量限制(仅在显示详细信息时生效)。默认为 100,防止返回过多结果", required = false) Integer limit, ToolContext toolContext) { StringBuilder cmd = buildCommand("sc"); // 默认显示详细信息 boolean showDetail = (detail == null || detail); addFlag(cmd, "-d", showDetail); // 显示字段信息 addFlag(cmd, "-f", field); // 使用正则表达式匹配 addFlag(cmd, "-E", regex); // 指定类加载器(三种方式,优先使用 hashcode) if (classLoaderHash != null && !classLoaderHash.trim().isEmpty()) { addParameter(cmd, "-c", classLoaderHash); } else if (classLoaderClass != null && !classLoaderClass.trim().isEmpty()) { addParameter(cmd, "--classLoaderClass", classLoaderClass); } else if (classLoaderStr != null && !classLoaderStr.trim().isEmpty()) { addParameter(cmd, "-cs", classLoaderStr); } // 对象展开层级 if (expand != null && expand > 0) { addParameter(cmd, "-x", String.valueOf(expand)); } // 最大匹配数量限制 if (limit != null && limit > 0) { addParameter(cmd, "-n", String.valueOf(limit)); } // 类名模式(必需参数) addParameter(cmd, classPattern); return executeSync(toolContext, cmd.toString()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/klass100/JadTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/klass100/JadTool.java
package com.taobao.arthas.core.mcp.tool.function.klass100; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class JadTool extends AbstractArthasTool { @Tool( name = "jad", description = "反编译指定已加载类的源码,将JVM中实际运行的class的bytecode反编译成java代码" ) public String jad( @ToolParam(description = "类名表达式匹配,如java.lang.String或demo.MathGame") String classPattern, @ToolParam(description = "ClassLoader的hashcode(16进制),用于指定特定的ClassLoader", required = false) String classLoaderHash, @ToolParam(description = "ClassLoader的完整类名,如sun.misc.Launcher$AppClassLoader,可替代hashcode", required = false) String classLoaderClass, @ToolParam(description = "反编译时只显示源代码,默认false", required = false) Boolean sourceOnly, @ToolParam(description = "反编译时不显示行号,默认false", required = false) Boolean noLineNumber, @ToolParam(description = "开启正则表达式匹配,默认为通配符匹配,默认false", required = false) Boolean useRegex, @ToolParam(description = "指定dump class文件目录,默认会dump到logback.xml中配置的log目录下", required = false) String dumpDirectory, ToolContext toolContext) { StringBuilder cmd = buildCommand("jad"); addParameter(cmd, classPattern); if (classLoaderHash != null && !classLoaderHash.trim().isEmpty()) { addParameter(cmd, "-c", classLoaderHash); } else if (classLoaderClass != null && !classLoaderClass.trim().isEmpty()) { addParameter(cmd, "--classLoaderClass", classLoaderClass); } addFlag(cmd, "--source-only", sourceOnly); addFlag(cmd, "-E", useRegex); if (Boolean.TRUE.equals(noLineNumber)) { cmd.append(" --lineNumber false"); } addParameter(cmd, "-d", dumpDirectory); return executeSync(toolContext, cmd.toString()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/monitor200/ProfilerTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/monitor200/ProfilerTool.java
package com.taobao.arthas.core.mcp.tool.function.monitor200; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; /** * profiler MCP Tool: Async Profiler(async-profiler)能力封装,对应 Arthas 的 profiler 命令。 * <p> * 参考:{@link com.taobao.arthas.core.command.monitor200.ProfilerCommand} */ public class ProfilerTool extends AbstractArthasTool { private static final String[] SUPPORTED_ACTIONS = new String[] { "start", "resume", "stop", "dump", "check", "status", "meminfo", "list", "version", "load", "execute", "dumpCollapsed", "dumpFlat", "dumpTraces", "getSamples", "actions" }; @Tool( name = "profiler", description = "Async Profiler 诊断工具: 对应 Arthas 的 profiler 命令,用于采样 CPU/alloc/lock 等事件并输出 flamegraph/jfr 等格式。\n" + "常用示例:\n" + "- start: 开始采样,如 action=start, event=cpu\n" + "- stop: 停止并输出文件,如 action=stop, format=flamegraph, file=/tmp/result.html\n" + "- status/list/actions: 查看状态/支持事件/支持动作\n" + "- execute: 直接传递 async-profiler agent 兼容参数,如 action=execute, actionArg=\"stop,file=/tmp/result.html\"" ) public String profiler( @ToolParam(description = "动作(必填),可选值: start/resume/stop/dump/check/status/meminfo/list/version/load/execute/dumpCollapsed/dumpFlat/dumpTraces/getSamples/actions") String action, @ToolParam(description = "动作参数(可选)。当 action=execute 时必填,示例: \"stop,file=/tmp/result.html\"", required = false) String actionArg, @ToolParam(description = "采样事件 (--event),如 cpu/alloc/lock/wall,默认 cpu", required = false) String event, @ToolParam(description = "采样间隔 ns (--interval),默认 10000000(10ms)", required = false) Long interval, @ToolParam(description = "最大 Java 栈深 (--jstackdepth),默认 2048", required = false) Integer jstackdepth, @ToolParam(description = "输出文件路径 (--file)。如果以 .html/.jfr 结尾可推断 format;也可包含 %t 等占位符(如 /tmp/result-%t.html)", required = false) String file, @ToolParam(description = "输出格式 (--format),支持 flat[=N]|traces[=N]|collapsed|flamegraph|tree|jfr(兼容传入 html)", required = false) String format, @ToolParam(description = "alloc 事件采样间隔字节数 (--alloc),如 1m/512k/1000 等", required = false) String alloc, @ToolParam(description = "仅对存活对象做 alloc 统计 (--live)", required = false) Boolean live, @ToolParam(description = "lock 事件阈值 ns (--lock),如 10ms/10000000 等", required = false) String lock, @ToolParam(description = "与 profiler 一起启动 JFR (--jfrsync),可为预置 profile 名称、.jfc 路径或 + 事件列表", required = false) String jfrsync, @ToolParam(description = "wall clock 采样间隔 ms (--wall),推荐 200", required = false) Long wall, @ToolParam(description = "按线程区分采样 (--threads)", required = false) Boolean threads, @ToolParam(description = "按调度策略分组线程 (--sched)", required = false) Boolean sched, @ToolParam(description = "C 栈采样方式 (--cstack),可选 fp|dwarf|lbr|no", required = false) String cstack, @ToolParam(description = "使用简单类名 (-s)", required = false) Boolean simple, @ToolParam(description = "打印方法签名 (-g)", required = false) Boolean sig, @ToolParam(description = "注解 Java 方法 (-a)", required = false) Boolean ann, @ToolParam(description = "前置库名 (-l)", required = false) Boolean lib, @ToolParam(description = "仅包含用户态事件 (--all-user)", required = false) Boolean allUser, @ToolParam(description = "规范化方法名,移除 lambda 类的数字后缀 (--norm)", required = false) Boolean norm, @ToolParam(description = "仅包含匹配的栈帧(可重复多次),等价 --include 'java/*'。传入数组。", required = false) String[] include, @ToolParam(description = "排除匹配的栈帧(可重复多次),等价 --exclude '*Unsafe.park*'。传入数组。", required = false) String[] exclude, @ToolParam(description = "当指定 native 函数执行时自动开始采样 (--begin)", required = false) String begin, @ToolParam(description = "当指定 native 函数执行时自动停止采样 (--end)", required = false) String end, @ToolParam(description = "time-to-safepoint 采样别名开关 (--ttsp),等价设置 begin/end 为特定函数", required = false) Boolean ttsp, @ToolParam(description = "FlameGraph 标题 (--title)", required = false) String title, @ToolParam(description = "FlameGraph 最小帧宽百分比 (--minwidth)", required = false) String minwidth, @ToolParam(description = "生成反向 FlameGraph/Call tree (--reverse)", required = false) Boolean reverse, @ToolParam(description = "统计总量而非样本数 (--total)", required = false) Boolean total, @ToolParam(description = "JFR chunk 大小 (--chunksize),默认 100MB 或其它单位", required = false) String chunksize, @ToolParam(description = "JFR chunk 时间 (--chunktime),默认 1h", required = false) String chunktime, @ToolParam(description = "循环采样参数 (--loop),用于 continuous profiling,如 300s", required = false) String loop, @ToolParam(description = "自动停止时间 (--timeout),绝对或相对时间,如 300s", required = false) String timeout, @ToolParam(description = "持续采样秒数 (--duration)。注意:到时自动 stop 在后台执行,stop 的结果不会回传到当前命令输出。", required = false) Long duration, @ToolParam(description = "启用的特性集合 (--features)", required = false) String features, @ToolParam(description = "采样信号 (--signal)", required = false) String signal, @ToolParam(description = "时间戳时钟源 (--clock),可选 monotonic 或 tsc", required = false) String clock, ToolContext toolContext ) { String normalizedAction = normalizeAction(action); if ("execute".equals(normalizedAction) && (actionArg == null || actionArg.trim().isEmpty())) { throw new IllegalArgumentException("actionArg is required when action=execute"); } StringBuilder cmd = buildCommand("profiler"); cmd.append(" ").append(normalizedAction); if (actionArg != null && !actionArg.trim().isEmpty()) { addParameter(cmd, actionArg); } // profiler options addOption(cmd, "--event", event); addOption(cmd, "--alloc", alloc); addFlag(cmd, "--live", live); addOption(cmd, "--lock", lock); addOption(cmd, "--jfrsync", jfrsync); addOption(cmd, "--file", file); addOption(cmd, "--format", format); addOption(cmd, "--interval", interval); addOption(cmd, "--jstackdepth", jstackdepth); addOption(cmd, "--wall", wall); addOption(cmd, "--features", features); addOption(cmd, "--signal", signal); addOption(cmd, "--clock", clock); addFlag(cmd, "--threads", threads); addFlag(cmd, "--sched", sched); addOption(cmd, "--cstack", cstack); addFlag(cmd, "-s", simple); addFlag(cmd, "-g", sig); addFlag(cmd, "-a", ann); addFlag(cmd, "-l", lib); addFlag(cmd, "--all-user", allUser); addFlag(cmd, "--norm", norm); addRepeatableOption(cmd, "--include", include); addRepeatableOption(cmd, "--exclude", exclude); addOption(cmd, "--begin", begin); addOption(cmd, "--end", end); addFlag(cmd, "--ttsp", ttsp); addOption(cmd, "--title", title); addOption(cmd, "--minwidth", minwidth); addFlag(cmd, "--reverse", reverse); addFlag(cmd, "--total", total); addOption(cmd, "--chunksize", chunksize); addOption(cmd, "--chunktime", chunktime); addOption(cmd, "--loop", loop); addOption(cmd, "--timeout", timeout); addOption(cmd, "--duration", duration); logger.info("Executing profiler command: {}", cmd); return executeSync(toolContext, cmd.toString()); } private static String normalizeAction(String action) { if (action == null || action.trim().isEmpty()) { throw new IllegalArgumentException("action is required"); } String input = action.trim(); for (String supported : SUPPORTED_ACTIONS) { if (supported.equalsIgnoreCase(input)) { return supported; } } StringBuilder supportedList = new StringBuilder(); for (int i = 0; i < SUPPORTED_ACTIONS.length; i++) { if (i > 0) { supportedList.append(", "); } supportedList.append(SUPPORTED_ACTIONS[i]); } throw new IllegalArgumentException("Unsupported action: " + input + ". Supported actions: " + supportedList); } private void addOption(StringBuilder cmd, String option, String value) { if (value == null || value.trim().isEmpty()) { return; } cmd.append(" ").append(option); addParameter(cmd, value); } private void addOption(StringBuilder cmd, String option, Long value) { if (value == null) { return; } cmd.append(" ").append(option).append(" ").append(value); } private void addOption(StringBuilder cmd, String option, Integer value) { if (value == null) { return; } cmd.append(" ").append(option).append(" ").append(value); } private void addRepeatableOption(StringBuilder cmd, String option, String[] values) { if (values == null || values.length == 0) { return; } for (String value : values) { if (value == null || value.trim().isEmpty()) { continue; } cmd.append(" ").append(option); addParameter(cmd, value); } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/monitor200/TimeTunnelTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/monitor200/TimeTunnelTool.java
package com.taobao.arthas.core.mcp.tool.function.monitor200; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class TimeTunnelTool extends AbstractArthasTool { public static final int DEFAULT_NUMBER_OF_EXECUTIONS = 1; public static final int DEFAULT_POLL_INTERVAL_MS = 100; public static final int DEFAULT_MAX_MATCH_COUNT = 50; /** * tt 时空隧道工具 (TimeTunnel) * 方法执行数据的时空隧道,记录下指定方法每次调用的入参和返回信息,并能对这些不同的时间下调用进行观测 */ @Tool( name = "tt", description = "TimeTunnel 时空隧道工具: 方法执行数据的时空隧道,记录下指定方法每次调用的入参和返回信息,对应 Arthas 的 tt 命令。支持记录、列表、搜索、查看详情、重放、删除等操作。", streamable = true ) public String timeTunnel( @ToolParam(description = "操作类型: record/t(记录), list/l(列表), search/s(搜索), info/i(查看详情), replay/p(重放), delete/d(删除), deleteAll/da(删除所有),默认record") String action, @ToolParam(description = "类名表达式匹配,支持通配符,如demo.MathGame或*Test。record操作时必需", required = false) String classPattern, @ToolParam(description = "方法名表达式匹配,支持通配符,如primeFactors或*method。record操作时必需", required = false) String methodPattern, @ToolParam(description = "OGNL条件表达式,满足条件的调用才会被记录,如params[0]<0或'params.length==1'", required = false) String condition, @ToolParam(description = "记录次数限制,默认值为 1。达到指定次数后自动停止(仅record操作)", required = false) Integer numberOfExecutions, @ToolParam(description = "开启正则表达式匹配,默认为通配符匹配,默认false", required = false) Boolean regex, @ToolParam(description = "指定索引,用于info/replay/delete等操作", required = false) Integer index, @ToolParam(description = "搜索表达式,用于search操作,支持OGNL表达式如'method.name==\"primeFactors\"'", required = false) String searchExpression, @ToolParam(description = "Class最大匹配数量,防止匹配到的Class数量太多导致JVM挂起,默认50", required = false) Integer maxMatchCount, @ToolParam(description = "命令执行超时时间,单位为秒,默认" + AbstractArthasTool.DEFAULT_TIMEOUT_SECONDS + "秒。超时后命令自动退出(仅record操作)", required = false) Integer timeout, ToolContext toolContext ) { String ttAction = normalizeAction(action); int execCount = getDefaultValue(numberOfExecutions, DEFAULT_NUMBER_OF_EXECUTIONS); int maxMatch = getDefaultValue(maxMatchCount, DEFAULT_MAX_MATCH_COUNT); int timeoutSeconds = getDefaultValue(timeout, DEFAULT_TIMEOUT_SECONDS); validateParameters(ttAction, classPattern, methodPattern, index, searchExpression); StringBuilder cmd = buildCommand("tt"); switch (ttAction) { case "record": cmd = buildRecordCommand(cmd, classPattern, methodPattern, condition, execCount, maxMatch, regex, timeoutSeconds); break; case "list": cmd = buildListCommand(cmd, searchExpression); break; case "info": cmd.append(" -i ").append(index); break; case "search": cmd.append(" -s '").append(searchExpression.trim()).append("'"); break; case "replay": cmd.append(" -i ").append(index).append(" -p"); break; case "delete": cmd.append(" -i ").append(index).append(" -d"); break; case "deleteall": cmd.append(" --delete-all"); break; default: throw new IllegalArgumentException("Unsupported action: " + ttAction + ". Supported actions: record(t), list(l), info(i), search(s), replay(p), delete(d), deleteAll(da)"); } return executeStreamable(toolContext, cmd.toString(), execCount, DEFAULT_POLL_INTERVAL_MS, timeoutSeconds * 1000, "TimeTunnel recording completed successfully"); } /** * 验证参数 */ private void validateParameters(String action, String classPattern, String methodPattern, Integer index, String searchExpression) { switch (action) { case "record": if (classPattern == null || classPattern.trim().isEmpty()) { throw new IllegalArgumentException("classPattern is required for record operation"); } if (methodPattern == null || methodPattern.trim().isEmpty()) { throw new IllegalArgumentException("methodPattern is required for record operation"); } break; case "info": case "replay": if (index == null) { throw new IllegalArgumentException(action + " operation requires index parameter"); } break; case "search": if (searchExpression == null || searchExpression.trim().isEmpty()) { throw new IllegalArgumentException("search operation requires searchExpression parameter"); } break; case "delete": if (index == null) { throw new IllegalArgumentException("delete operation requires index parameter"); } break; case "list": case "deleteall": break; default: throw new IllegalArgumentException("Unsupported action: " + action); } } /** * 标准化操作类型 */ private String normalizeAction(String action) { if (action == null || action.trim().isEmpty()) { return "record"; } String normalizedAction = action.trim().toLowerCase(); switch (normalizedAction) { case "record": case "r": case "-t": case "t": return "record"; case "list": case "l": case "-l": return "list"; case "info": case "i": case "-i": return "info"; case "search": case "s": case "-s": return "search"; case "replay": case "p": case "-p": return "replay"; case "delete": case "d": case "-d": return "delete"; case "deleteall": case "da": case "--delete-all": return "deleteall"; default: return normalizedAction; } } private StringBuilder buildRecordCommand(StringBuilder cmd, String classPattern, String methodPattern, String condition, int execCount, int maxMatch, Boolean regex, int timeoutSeconds) { cmd.append(" -t"); cmd.append(" --timeout ").append(timeoutSeconds); cmd.append(" -n ").append(execCount); cmd.append(" -m ").append(maxMatch); if (Boolean.TRUE.equals(regex)) { cmd.append(" -E"); } cmd.append(" '").append(classPattern.trim()).append("'"); cmd.append(" '").append(methodPattern.trim()).append("'"); if (condition != null && !condition.trim().isEmpty()) { cmd.append(" '").append(condition.trim()).append("'"); } return cmd; } private StringBuilder buildListCommand(StringBuilder cmd, String searchExpression) { cmd.append(" -l"); if (searchExpression != null && !searchExpression.trim().isEmpty()) { cmd.append(" '").append(searchExpression.trim()).append("'"); } return cmd; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/monitor200/StackTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/monitor200/StackTool.java
package com.taobao.arthas.core.mcp.tool.function.monitor200; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class StackTool extends AbstractArthasTool { public static final int DEFAULT_NUMBER_OF_EXECUTIONS = 1; public static final int DEFAULT_POLL_INTERVAL_MS = 50; /** * stack 调用堆栈跟踪工具 * 输出当前方法被调用的调用路径 * 支持: * - classPattern: 类名表达式匹配,支持通配符 * - methodPattern: 方法名表达式匹配,支持通配符 * - condition: OGNL条件表达式,满足条件的调用才会被跟踪 * - numberOfExecutions: 捕获次数限制,达到指定次数后自动停止 * - regex: 是否开启正则表达式匹配,默认false * - excludeClassPattern: 排除的类名模式 */ @Tool( name = "stack", description = "Stack 调用堆栈跟踪工具: 输出当前方法被调用的调用路径,帮助分析方法的调用链路。对应 Arthas 的 stack 命令。", streamable = true ) public String stack( @ToolParam(description = "类名表达式匹配,支持通配符,如demo.MathGame") String classPattern, @ToolParam(description = "方法名表达式匹配,支持通配符,如primeFactors", required = false) String methodPattern, @ToolParam(description = "OGNL条件表达式,满足条件的调用才会被跟踪,如params[0]<0", required = false) String condition, @ToolParam(description = "捕获次数限制,默认值为1。达到指定次数后自动停止", required = false) Integer numberOfExecutions, @ToolParam(description = "开启正则表达式匹配,默认为通配符匹配,默认false", required = false) Boolean regex, @ToolParam(description = "命令执行超时时间,单位为秒,默认" + AbstractArthasTool.DEFAULT_TIMEOUT_SECONDS + "秒。超时后命令自动退出", required = false) Integer timeout, ToolContext toolContext ) { int execCount = getDefaultValue(numberOfExecutions, DEFAULT_NUMBER_OF_EXECUTIONS); int timeoutSeconds = getDefaultValue(timeout, DEFAULT_TIMEOUT_SECONDS); StringBuilder cmd = buildCommand("stack"); cmd.append(" --timeout ").append(timeoutSeconds); cmd.append(" -n ").append(execCount); addFlag(cmd, "-E", regex); addParameter(cmd, classPattern); if (methodPattern != null && !methodPattern.trim().isEmpty()) { cmd.append(" ").append(methodPattern.trim()); } addQuotedParameter(cmd, condition); return executeStreamable(toolContext, cmd.toString(), execCount, DEFAULT_POLL_INTERVAL_MS, timeoutSeconds * 1000, "Stack execution completed successfully"); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/monitor200/MonitorTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/monitor200/MonitorTool.java
package com.taobao.arthas.core.mcp.tool.function.monitor200; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class MonitorTool extends AbstractArthasTool { public static final int DEFAULT_NUMBER_OF_EXECUTIONS = 1; public static final int DEFAULT_REFRESH_INTERVAL_MS = 3000; public static final int DEFAULT_MAX_MATCH_COUNT = 50; /** * monitor 方法调用监控工具 * 实时监控指定类的指定方法的调用情况 * 支持: * - classPattern: 类名表达式匹配,支持通配符 * - methodPattern: 方法名表达式匹配,支持通配符 * - condition: OGNL条件表达式,满足条件的调用才会被监控 * - intervalMs: 监控统计输出间隔,默认3000ms * - numberOfExecutions: 监控执行次数,默认1次 * - regex: 是否开启正则表达式匹配,默认false * - excludeClassPattern: 排除的类名模式 * - maxMatch: 最大匹配类数量,防止匹配过多类影响性能,默认50 */ @Tool( name = "monitor", description = "Monitor 方法调用监控工具: 实时监控指定类的指定方法的调用情况,包括调用次数、成功次数、失败次数、平均RT、失败率等统计信息。对应 Arthas 的 monitor 命令。", streamable = true ) public String monitor( @ToolParam(description = "类名表达式匹配,支持通配符,如demo.MathGame") String classPattern, @ToolParam(description = "方法名表达式匹配,支持通配符,如primeFactors", required = false) String methodPattern, @ToolParam(description = "OGNL条件表达式,满足条件的调用才会被监控,如params[0]<0", required = false) String condition, @ToolParam(description = "监控统计输出间隔,单位为毫秒,默认 3000ms。用于控制输出频率", required = false) Integer intervalMs, @ToolParam(description = "执行次数限制,默认值为" + DEFAULT_NUMBER_OF_EXECUTIONS + "。达到指定次数后自动停止", required = false) Integer numberOfExecutions, @ToolParam(description = "开启正则表达式匹配,默认为通配符匹配,默认false", required = false) Boolean regex, @ToolParam(description = "最大匹配类数量,防止匹配过多类影响性能,默认50", required = false) Integer maxMatch, @ToolParam(description = "命令执行超时时间,单位为秒,默认" + AbstractArthasTool.DEFAULT_TIMEOUT_SECONDS + "秒。超时后命令自动退出", required = false) Integer timeout, ToolContext toolContext ) { int interval = getDefaultValue(intervalMs, DEFAULT_REFRESH_INTERVAL_MS); int execCount = getDefaultValue(numberOfExecutions, DEFAULT_NUMBER_OF_EXECUTIONS); int maxMatchCount = getDefaultValue(maxMatch, DEFAULT_MAX_MATCH_COUNT); int timeoutSeconds = getDefaultValue(timeout, DEFAULT_TIMEOUT_SECONDS); StringBuilder cmd = buildCommand("monitor"); cmd.append(" --timeout ").append(timeoutSeconds); cmd.append(" -c ").append(interval / 1000); cmd.append(" -n ").append(execCount); cmd.append(" -m ").append(maxMatchCount); addFlag(cmd, "-E", regex); addParameter(cmd, classPattern); if (methodPattern != null && !methodPattern.trim().isEmpty()) { cmd.append(" ").append(methodPattern.trim()); } addQuotedParameter(cmd, condition); return executeStreamable(toolContext, cmd.toString(), execCount, interval / 10, timeoutSeconds * 1000, "Monitor execution completed successfully"); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/monitor200/WatchTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/monitor200/WatchTool.java
package com.taobao.arthas.core.mcp.tool.function.monitor200; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class WatchTool extends AbstractArthasTool { public static final int DEFAULT_NUMBER_OF_EXECUTIONS = 1; public static final int DEFAULT_POLL_INTERVAL_MS = 50; public static final int DEFAULT_MAX_MATCH_COUNT = 50; public static final int DEFAULT_EXPAND_LEVEL = 1; public static final String DEFAULT_EXPRESS = "{params, target, returnObj}"; /** * watch 方法执行观察工具 * 观察指定方法的调用情况,包括入参、返回值和抛出异常等信息 * 整合了完整的参数支持和流式输出能力 */ @Tool( name = "watch", description = "Watch 方法执行观察工具: 观察指定方法的调用情况,包括入参、返回值和抛出异常等信息,支持实时流式输出。对应 Arthas 的 watch 命令。", streamable = true ) public String watch( @ToolParam(description = "类名表达式匹配,支持通配符,如demo.MathGame") String classPattern, @ToolParam(description = "方法名表达式匹配,支持通配符,如primeFactors", required = false) String methodPattern, @ToolParam(description = "观察表达式,默认为{params, target, returnObj},支持OGNL表达式", required = false) String express, @ToolParam(description = "OGNL条件表达式,满足条件的调用才会被观察,如params[0]<0", required = false) String condition, @ToolParam(description = "在方法调用之前观察(-b),默认false", required = false) Boolean beforeMethod, @ToolParam(description = "在方法抛出异常后观察(-e),默认false", required = false) Boolean exceptionOnly, @ToolParam(description = "在方法正常返回后观察(-s),默认false", required = false) Boolean successOnly, @ToolParam(description = "执行次数限制,默认值为 1。达到指定次数后自动停止", required = false) Integer numberOfExecutions, @ToolParam(description = "开启正则表达式匹配,默认为通配符匹配,默认false", required = false) Boolean regex, @ToolParam(description = "指定Class最大匹配数量,默认50", required = false) Integer maxMatchCount, @ToolParam(description = "指定输出结果的属性遍历深度,默认1,最大4", required = false) Integer expandLevel, @ToolParam(description = "命令执行超时时间,单位为秒,默认" + AbstractArthasTool.DEFAULT_TIMEOUT_SECONDS + "秒。超时后命令自动退出", required = false) Integer timeout, ToolContext toolContext ) { int execCount = getDefaultValue(numberOfExecutions, DEFAULT_NUMBER_OF_EXECUTIONS); int maxMatch = getDefaultValue(maxMatchCount, DEFAULT_MAX_MATCH_COUNT); int expandDepth = (expandLevel != null && expandLevel >= 1 && expandLevel <= 4) ? expandLevel : DEFAULT_EXPAND_LEVEL; String watchExpress = getDefaultValue(express, DEFAULT_EXPRESS); int timeoutSeconds = getDefaultValue(timeout, DEFAULT_TIMEOUT_SECONDS); StringBuilder cmd = buildCommand("watch"); cmd.append(" --timeout ").append(timeoutSeconds); cmd.append(" -n ").append(execCount); cmd.append(" -m ").append(maxMatch); cmd.append(" -x ").append(expandDepth); addFlag(cmd, "-E", regex); if (Boolean.TRUE.equals(beforeMethod)) { cmd.append(" -b"); } else if (Boolean.TRUE.equals(exceptionOnly)) { cmd.append(" -e"); } else if (Boolean.TRUE.equals(successOnly)) { cmd.append(" -s"); } else { cmd.append(" -f"); } addParameter(cmd, classPattern); if (methodPattern != null && !methodPattern.trim().isEmpty()) { cmd.append(" ").append(methodPattern.trim()); } addQuotedParameter(cmd, watchExpress); addQuotedParameter(cmd, condition); return executeStreamable(toolContext, cmd.toString(), execCount, DEFAULT_POLL_INTERVAL_MS, timeoutSeconds * 1000, "Watch execution completed successfully"); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/monitor200/TraceTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/monitor200/TraceTool.java
package com.taobao.arthas.core.mcp.tool.function.monitor200; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class TraceTool extends AbstractArthasTool { public static final int DEFAULT_NUMBER_OF_EXECUTIONS = 1; public static final int DEFAULT_POLL_INTERVAL_MS = 100; public static final int DEFAULT_MAX_MATCH_COUNT = 50; /** * trace 方法内部调用路径跟踪工具 * 追踪方法内部调用路径,输出每个节点的耗时信息 */ @Tool( name = "trace", description = "Trace 方法内部调用路径跟踪工具: 追踪方法内部调用路径,输出每个节点的耗时信息,对应 Arthas 的 trace 命令。", streamable = true ) public String trace( @ToolParam(description = "类名表达式匹配,支持通配符,如demo.MathGame") String classPattern, @ToolParam(description = "方法名表达式匹配,支持通配符,如primeFactors", required = false) String methodPattern, @ToolParam(description = "OGNL条件表达式,包括#cost耗时过滤,如'#cost>100'表示耗时超过100ms", required = false) String condition, @ToolParam(description = "执行次数限制,默认值为1。达到指定次数后自动停止", required = false) Integer numberOfExecutions, @ToolParam(description = "开启正则表达式匹配,默认为通配符匹配,默认false", required = false) Boolean regex, @ToolParam(description = "指定Class最大匹配数量,默认50", required = false) Integer maxMatchCount, @ToolParam(description = "命令执行超时时间,单位为秒,默认" + AbstractArthasTool.DEFAULT_TIMEOUT_SECONDS + "秒。超时后命令自动退出", required = false) Integer timeout, ToolContext toolContext ) { int execCount = getDefaultValue(numberOfExecutions, DEFAULT_NUMBER_OF_EXECUTIONS); int maxMatch = getDefaultValue(maxMatchCount, DEFAULT_MAX_MATCH_COUNT); int timeoutSeconds = getDefaultValue(timeout, DEFAULT_TIMEOUT_SECONDS); StringBuilder cmd = buildCommand("trace"); cmd.append(" --timeout ").append(timeoutSeconds); cmd.append(" -n ").append(execCount); cmd.append(" -m ").append(maxMatch); addFlag(cmd, "-E", regex); addParameter(cmd, classPattern); if (methodPattern != null && !methodPattern.trim().isEmpty()) { cmd.append(" ").append(methodPattern.trim()); } addQuotedParameter(cmd, condition); return executeStreamable(toolContext, cmd.toString(), execCount, DEFAULT_POLL_INTERVAL_MS, timeoutSeconds * 1000, "Trace execution completed successfully"); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/basic1000/OptionsTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/basic1000/OptionsTool.java
package com.taobao.arthas.core.mcp.tool.function.basic1000; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; /** * Options MCP Tool: 查看和修改 Arthas 全局开关选项 */ public class OptionsTool extends AbstractArthasTool { @Tool( name = "options", description = "Options 诊断工具: 查看或修改 Arthas 全局开关选项,对应 Arthas 的 options 命令。\n" + "使用示例:\n" + "- 不带参数: 列出所有选项\n" + "- 只指定 name: 查看指定选项的当前值\n" + "- 指定 name 和 value: 修改选项的值\n" + "常用选项:\n" + "- unsafe: 是否支持系统类增强(默认 false)\n" + "- dump: 是否 dump 增强后的类(默认 false)\n" + "- json-format: 是否使用 JSON 格式输出(默认 false)\n" + "- strict: 是否启用严格模式,禁止设置对象属性(默认 true)" ) public String options( @ToolParam(description = "选项名称,如: unsafe, dump, json-format, strict 等", required = false) String name, @ToolParam(description = "选项值,用于修改选项时指定新值", required = false) String value, ToolContext toolContext ) { StringBuilder cmd = buildCommand("options"); if (name != null && !name.trim().isEmpty()) { cmd.append(" ").append(name.trim()); if (value != null && !value.trim().isEmpty()) { cmd.append(" ").append(value.trim()); } } return executeSync(toolContext, cmd.toString()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/basic1000/ViewFileTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/basic1000/ViewFileTool.java
package com.taobao.arthas.core.mcp.tool.function.basic1000; import com.fasterxml.jackson.core.type.TypeReference; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; import com.taobao.arthas.mcp.server.util.JsonParser; import java.io.RandomAccessFile; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import static com.taobao.arthas.core.mcp.tool.function.StreamableToolUtils.createCompletedResponse; import static com.taobao.arthas.core.mcp.tool.function.StreamableToolUtils.createErrorResponse; /** * ViewFile MCP Tool: 在允许目录内分段查看文件内容 */ public class ViewFileTool extends AbstractArthasTool { static final String ALLOWED_DIRS_ENV = "ARTHAS_MCP_VIEWFILE_ALLOWED_DIRS"; static final int DEFAULT_MAX_BYTES = 8192; static final int MAX_MAX_BYTES = 65536; @Tool( name = "viewfile", description = "查看文件内容(仅允许在配置的目录白名单内查看),并支持 cursor/offset 分段读取,避免一次性返回大量内容。\n" + "默认允许目录:当前工作目录下的 arthas-output(若存在)、用户目录下的 ~/logs/(若存在)。\n" + "配置白名单目录:\n" + "- 环境变量: " + ALLOWED_DIRS_ENV + "=/path/a,/path/b\n" + "使用方式:\n" + "- 首次读取:传 path(可传 offset/maxBytes)\n" + "- 继续读取:传 cursor(由上一次返回结果提供)" ) public String viewFile( @ToolParam(description = "文件路径(绝对路径或相对路径;相对路径会在允许目录下解析)。当提供 cursor 时可不传。", required = false) String path, @ToolParam(description = "游标(上一段返回的 nextCursor),用于继续读取。提供 cursor 时会忽略 path/offset。", required = false) String cursor, @ToolParam(description = "起始字节偏移量(默认 0)。", required = false) Long offset, @ToolParam(description = "本次最多读取字节数(默认 8192,最大 65536)。", required = false) Integer maxBytes, ToolContext toolContext ) { try { List<Path> allowedRoots = loadAllowedRoots(); if (allowedRoots.isEmpty()) { return JsonParser.toJson(createErrorResponse("viewfile 未配置允许目录白名单,且默认目录 arthas-output、~/logs/ 不可用。" + "请通过环境变量 " + ALLOWED_DIRS_ENV + "=/path/a,/path/b 进行配置。")); } CursorRequest cursorRequest = parseCursorOrArgs(path, cursor, offset); Path targetFile = resolveAllowedFile(cursorRequest.path, allowedRoots); int readMaxBytes = clampMaxBytes(maxBytes); long fileSize = Files.size(targetFile); long requestedOffset = cursorRequest.offset; long effectiveOffset = adjustOffset(cursorRequest.cursorUsed, requestedOffset, fileSize); byte[] bytes = readBytes(targetFile, effectiveOffset, readMaxBytes, fileSize); int safeLen = utf8SafeLength(bytes, bytes.length); String content = new String(bytes, 0, safeLen, StandardCharsets.UTF_8); long nextOffset = effectiveOffset + safeLen; boolean eof = nextOffset >= fileSize; Map<String, Object> result = new LinkedHashMap<>(); result.put("path", targetFile.toString()); result.put("fileSize", fileSize); result.put("requestedOffset", requestedOffset); result.put("startOffset", effectiveOffset); result.put("maxBytes", readMaxBytes); result.put("readBytes", safeLen); result.put("nextOffset", nextOffset); result.put("eof", eof); result.put("nextCursor", encodeCursor(targetFile.toString(), nextOffset)); result.put("content", content); if (cursorRequest.cursorUsed && requestedOffset > fileSize) { result.put("cursorReset", true); result.put("cursorResetReason", "offsetGreaterThanFileSize"); } return JsonParser.toJson(createCompletedResponse("ok", result)); } catch (Exception e) { logger.error("viewfile error", e); return JsonParser.toJson(createErrorResponse("viewfile 执行失败: " + e.getMessage())); } } private static final class CursorRequest { private final String path; private final long offset; private final boolean cursorUsed; private CursorRequest(String path, long offset, boolean cursorUsed) { this.path = path; this.offset = offset; this.cursorUsed = cursorUsed; } } private CursorRequest parseCursorOrArgs(String path, String cursor, Long offset) { if (cursor != null && !cursor.trim().isEmpty()) { CursorValue decoded = decodeCursor(cursor.trim()); return new CursorRequest(decoded.path, decoded.offset, true); } if (path == null || path.trim().isEmpty()) { throw new IllegalArgumentException("必须提供 path 或 cursor"); } if (offset != null && offset < 0) { throw new IllegalArgumentException("offset 不允许为负数"); } long resolvedOffset = (offset != null) ? offset : 0L; return new CursorRequest(path.trim(), resolvedOffset, false); } private static final class CursorValue { private final String path; private final long offset; private CursorValue(String path, long offset) { this.path = path; this.offset = offset; } } private CursorValue decodeCursor(String cursor) { try { byte[] jsonBytes = Base64.getUrlDecoder().decode(cursor); String json = new String(jsonBytes, StandardCharsets.UTF_8); Map<String, Object> map = JsonParser.fromJson(json, new TypeReference<Map<String, Object>>() {}); Object pathObj = map.get("path"); Object offsetObj = map.get("offset"); if (!(pathObj instanceof String) || ((String) pathObj).trim().isEmpty()) { throw new IllegalArgumentException("cursor 缺少 path"); } if (!(offsetObj instanceof Number)) { throw new IllegalArgumentException("cursor 缺少 offset"); } long offset = ((Number) offsetObj).longValue(); if (offset < 0) { throw new IllegalArgumentException("cursor offset 不允许为负数"); } return new CursorValue(((String) pathObj).trim(), offset); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("cursor 解析失败: " + e.getMessage(), e); } } private String encodeCursor(String path, long offset) { Map<String, Object> cursor = new LinkedHashMap<>(); cursor.put("v", 1); cursor.put("path", path); cursor.put("offset", offset); String json = JsonParser.toJson(cursor); return Base64.getUrlEncoder().withoutPadding().encodeToString(json.getBytes(StandardCharsets.UTF_8)); } private List<Path> loadAllowedRoots() { String config = System.getenv(ALLOWED_DIRS_ENV); List<Path> roots = new ArrayList<>(); if (config != null && !config.trim().isEmpty()) { String[] parts = config.split(","); for (String part : parts) { String p = (part != null) ? part.trim() : ""; if (p.isEmpty()) { continue; } try { Path root = Paths.get(p).toAbsolutePath().normalize(); if (!Files.isDirectory(root)) { logger.warn("viewfile allowed dir ignored (not a directory): {}", root); continue; } roots.add(root.toRealPath()); } catch (Exception e) { logger.warn("viewfile allowed dir ignored (invalid): {}", p, e); } } } // 默认目录:arthas-output try { Path defaultRoot = Paths.get("arthas-output").toAbsolutePath().normalize(); if (Files.isDirectory(defaultRoot)) { roots.add(defaultRoot.toRealPath()); } } catch (Exception e) { logger.debug("viewfile default root ignored: arthas-output", e); } // 默认目录:~/logs/ try { Path userLogsRoot = Paths.get(System.getProperty("user.home"), "logs").toAbsolutePath().normalize(); if (Files.isDirectory(userLogsRoot)) { roots.add(userLogsRoot.toRealPath()); } } catch (Exception e) { logger.debug("viewfile default root ignored: ~/logs/", e); } return deduplicate(roots); } private static List<Path> deduplicate(List<Path> roots) { if (roots == null || roots.isEmpty()) { return Collections.emptyList(); } LinkedHashSet<Path> set = new LinkedHashSet<>(roots); return new ArrayList<>(set); } private Path resolveAllowedFile(String requestedPath, List<Path> allowedRoots) throws Exception { Path req = Paths.get(requestedPath); if (req.isAbsolute()) { Path real = req.toRealPath(); assertRegularFile(real); if (!isUnderAllowedRoot(real, allowedRoots)) { throw new IllegalArgumentException("文件不在允许目录白名单内: " + requestedPath); } return real; } for (Path root : allowedRoots) { Path candidate = root.resolve(req).normalize(); if (!candidate.startsWith(root)) { continue; } if (!Files.exists(candidate)) { continue; } Path real = candidate.toRealPath(); if (!real.startsWith(root)) { continue; } assertRegularFile(real); return real; } throw new IllegalArgumentException("文件不存在或不在允许目录白名单内: " + requestedPath); } private static void assertRegularFile(Path file) { if (!Files.isRegularFile(file)) { throw new IllegalArgumentException("不是普通文件: " + file); } } private static boolean isUnderAllowedRoot(Path file, List<Path> allowedRoots) { for (Path root : allowedRoots) { if (file.startsWith(root)) { return true; } } return false; } private static int clampMaxBytes(Integer maxBytes) { int value = (maxBytes != null && maxBytes > 0) ? maxBytes : DEFAULT_MAX_BYTES; return Math.min(value, MAX_MAX_BYTES); } private static long adjustOffset(boolean cursorUsed, long requestedOffset, long fileSize) { if (requestedOffset < 0) { throw new IllegalArgumentException("offset 不允许为负数"); } if (requestedOffset <= fileSize) { return requestedOffset; } return cursorUsed ? 0L : fileSize; } private static byte[] readBytes(Path file, long offset, int maxBytes, long fileSize) throws Exception { if (offset < 0 || offset > fileSize) { return new byte[0]; } long remaining = fileSize - offset; int toRead = (int) Math.min(maxBytes, Math.max(0, remaining)); if (toRead <= 0) { return new byte[0]; } byte[] buf = new byte[toRead]; int read; try (RandomAccessFile raf = new RandomAccessFile(file.toFile(), "r")) { raf.seek(offset); read = raf.read(buf); } if (read <= 0) { return new byte[0]; } return Arrays.copyOf(buf, read); } /** * 避免把 UTF-8 多字节字符截断在末尾,导致展示出现大量 �。 */ static int utf8SafeLength(byte[] bytes, int length) { if (bytes == null || length <= 0) { return 0; } int lastIndex = length - 1; int lastByte = bytes[lastIndex] & 0xFF; if ((lastByte & 0x80) == 0) { return length; } int i = lastIndex; int continuation = 0; while (i >= 0 && (bytes[i] & 0xC0) == 0x80) { continuation++; i--; } if (i < 0) { return Math.max(0, length - continuation); } int lead = bytes[i] & 0xFF; int expectedLen; if ((lead & 0xE0) == 0xC0) { expectedLen = 2; } else if ((lead & 0xF0) == 0xE0) { expectedLen = 3; } else if ((lead & 0xF8) == 0xF0) { expectedLen = 4; } else { return length; } int actualLen = continuation + 1; if (actualLen < expectedLen) { return i; } return length; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/basic1000/StopTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/basic1000/StopTool.java
package com.taobao.arthas.core.mcp.tool.function.basic1000; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.util.JsonParser; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; import java.util.HashMap; import java.util.Map; import static com.taobao.arthas.core.mcp.tool.function.StreamableToolUtils.createCompletedResponse; import static com.taobao.arthas.core.mcp.tool.function.StreamableToolUtils.createErrorResponse; public class StopTool extends AbstractArthasTool { public static final int DEFAULT_SHUTDOWN_DELAY_MS = 1000; @Tool( name = "stop", description = "彻底停止 Arthas。注意停止之后不能再调用任何 tool 了。为了确保 MCP client 能收到返回结果,本 tool 会先返回,再延迟执行 stop。" ) public String stop( @ToolParam(description = "延迟执行 stop 的毫秒数,默认 1000ms。用于确保 MCP client 收到返回结果。", required = false) Integer delayMs, ToolContext toolContext) { try { int shutdownDelayMs = getDefaultValue(delayMs, DEFAULT_SHUTDOWN_DELAY_MS); ToolExecutionContext execContext = new ToolExecutionContext(toolContext, false); scheduleStop(execContext, shutdownDelayMs); Map<String, Object> result = new HashMap<>(); result.put("command", "stop"); result.put("scheduled", true); result.put("delayMs", shutdownDelayMs); result.put("note", "Arthas 将在返回结果后停止,MCP 连接会断开。"); return JsonParser.toJson(createCompletedResponse("Stop scheduled", result)); } catch (Exception e) { logger.error("Error scheduling stop", e); return JsonParser.toJson(createErrorResponse("Error scheduling stop: " + e.getMessage())); } } private void scheduleStop(ToolExecutionContext execContext, int delayMs) { Object authSubject = execContext.getAuthSubject(); String userId = execContext.getUserId(); Thread shutdownThread = new Thread(() -> { try { if (delayMs > 0) { Thread.sleep(delayMs); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } try { execContext.getCommandContext().getCommandExecutor() .executeSync("stop", 300000L, null, authSubject, userId); } catch (Throwable t) { logger.error("Error executing stop command in background thread", t); } }, "arthas-mcp-stop"); shutdownThread.setDaemon(true); shutdownThread.start(); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/DashboardTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/DashboardTool.java
package com.taobao.arthas.core.mcp.tool.function.jvm300; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class DashboardTool extends AbstractArthasTool { public static final int DEFAULT_NUMBER_OF_EXECUTIONS = 3; public static final int DEFAULT_REFRESH_INTERVAL_MS = 3000; /** * dashboard 实时面板命令 * 支持: * - intervalMs: 刷新间隔,单位 ms,默认 3000ms * - count: 刷新次数限制,即 -n 参数;如果不指定则使用 DEFAULT_NUMBER_OF_EXECUTIONS (3次) */ @Tool( name = "dashboard", description = "Dashboard 诊断工具: 实时展示 JVM/应用面板,可利用参数控制诊断次数与间隔。对应 Arthas 的 dashboard 命令。", streamable = true ) public String dashboard( @ToolParam(description = "刷新间隔,单位为毫秒,默认 3000ms。用于控制输出频率", required = false) Integer intervalMs, @ToolParam(description = "执行次数限制,默认值为 3。达到指定次数后自动停止", required = false) Integer numberOfExecutions, ToolContext toolContext ) { int interval = getDefaultValue(intervalMs, DEFAULT_REFRESH_INTERVAL_MS); int execCount = getDefaultValue(numberOfExecutions, DEFAULT_NUMBER_OF_EXECUTIONS); StringBuilder cmd = buildCommand("dashboard"); cmd.append(" -i ").append(interval); cmd.append(" -n ").append(execCount); // Dashboards typically run a fixed number of times, // and the timeout is based on (number * interval) + buffer time int calculatedTimeoutMs = execCount * interval + 5000; return executeStreamable(toolContext, cmd.toString(), execCount, interval / 10, calculatedTimeoutMs, "Dashboard execution completed successfully"); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/VMToolTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/VMToolTool.java
package com.taobao.arthas.core.mcp.tool.function.jvm300; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class VMToolTool extends AbstractArthasTool { public static final String ACTION_GET_INSTANCES = "getInstances"; public static final String ACTION_INTERRUPT_THREAD = "interruptThread"; @Tool( name = "vmtool", description = "虚拟机工具诊断工具: 查询实例、强制 GC、线程中断等,对应 Arthas 的 vmtool 命令。" ) public String vmtool( @ToolParam(description = "操作类型: getInstances/forceGc/interruptThread 等") String action, @ToolParam(description = "ClassLoader的hashcode(16进制),用于指定特定的ClassLoader", required = false) String classLoaderHash, @ToolParam(description = "ClassLoader的完整类名,如sun.misc.Launcher$AppClassLoader,可替代hashcode", required = false) String classLoaderClass, @ToolParam(description = "类名,全限定(getInstances 时使用)", required = false) String className, @ToolParam(description = "返回实例限制数量 (-l),getInstances 时使用,默认 10;<=0 表示不限制", required = false) Integer limit, @ToolParam(description = "结果对象展开层次 (-x),默认 1", required = false) Integer expandLevel, @ToolParam(description = "OGNL 表达式,对 getInstances 返回的 instances 执行 (--express)", required = false) String express, @ToolParam(description = "线程 ID (-t),interruptThread 时使用", required = false) Long threadId, ToolContext toolContext ) { StringBuilder cmd = buildCommand("vmtool"); if (action == null || action.trim().isEmpty()) { throw new IllegalArgumentException("vmtool: action 参数不能为空"); } cmd.append(" --action ").append(action.trim()); if (classLoaderHash != null && !classLoaderHash.trim().isEmpty()) { addParameter(cmd, "-c", classLoaderHash); } else if (classLoaderClass != null && !classLoaderClass.trim().isEmpty()) { addParameter(cmd, "--classLoaderClass", classLoaderClass); } if (ACTION_GET_INSTANCES.equals(action.trim())) { if (className != null && !className.trim().isEmpty()) { addParameter(cmd, "--className", className); } if (limit != null) { cmd.append(" --limit ").append(limit); } if (expandLevel != null && expandLevel > 0) { cmd.append(" -x ").append(expandLevel); } if (express != null && !express.trim().isEmpty()) { addParameter(cmd, "--express", express); } } if (ACTION_INTERRUPT_THREAD.equals(action.trim())) { if (threadId != null && threadId > 0) { cmd.append(" -t ").append(threadId); } else { throw new IllegalArgumentException("vmtool interruptThread 需要指定线程 ID (threadId)"); } } return executeSync(toolContext, cmd.toString()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/PerfCounterTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/PerfCounterTool.java
package com.taobao.arthas.core.mcp.tool.function.jvm300; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class PerfCounterTool extends AbstractArthasTool { @Tool( name = "perfcounter", description = "PerfCounter 诊断工具: 查看 JVM Perf Counter 信息,对应 Arthas 的 perfcounter 命令。" ) public String perfcounter( @ToolParam(description = "是否打印更多详情 (-d)", required = false) Boolean detailed, ToolContext toolContext ) { StringBuilder cmd = buildCommand("perfcounter"); addFlag(cmd, "-d", detailed); return executeSync(toolContext, cmd.toString()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/VMOptionTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/VMOptionTool.java
package com.taobao.arthas.core.mcp.tool.function.jvm300; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class VMOptionTool extends AbstractArthasTool { @Tool( name = "vmoption", description = "VMOption 诊断工具: 查看或更新 JVM VM options,对应 Arthas 的 vmoption 命令。" ) public String vmoption( @ToolParam(description = "Name of the VM option.", required = false) String key, @ToolParam(description = "更新值,仅在更新时使用", required = false) String value, ToolContext toolContext ) { StringBuilder cmd = buildCommand("vmoption"); if (key != null && !key.trim().isEmpty()) { cmd.append(" ").append(key.trim()); if (value != null && !value.trim().isEmpty()) { cmd.append(" ").append(value.trim()); } } return executeSync(toolContext, cmd.toString()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/ThreadTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/ThreadTool.java
package com.taobao.arthas.core.mcp.tool.function.jvm300; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class ThreadTool extends AbstractArthasTool { /** * thread 诊断工具: 查看线程信息及堆栈 * 支持: * - threadId: 线程 ID,required=false * - topN: 最忙前 N 个线程并打印堆栈 (-n),required=false * - blocking: 是否查找阻塞其他线程的线程 (-b),required=false * - all: 是否显示所有匹配线程 (--all),required=false */ @Tool( name = "thread", description = "Thread 诊断工具: 查看线程信息及堆栈,对应 Arthas 的 thread 命令。一次性输出结果。" ) public String thread( @ToolParam(description = "线程 ID", required = false) Long threadId, @ToolParam(description = "最忙前 N 个线程并打印堆栈 (-n)", required = false) Integer topN, @ToolParam(description = "是否查找阻塞其他线程的线程 (-b)", required = false) Boolean blocking, @ToolParam(description = "是否显示所有匹配线程 (--all)", required = false) Boolean all, ToolContext toolContext ) { StringBuilder cmd = buildCommand("thread"); addFlag(cmd, "-b", blocking); if (topN != null && topN > 0) { cmd.append(" -n ").append(topN); } addFlag(cmd, "--all", all); if (threadId != null && threadId > 0) { cmd.append(" ").append(threadId); } logger.info("Executing thread command: {}", cmd.toString()); return executeSync(toolContext, cmd.toString()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/SysEnvTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/SysEnvTool.java
package com.taobao.arthas.core.mcp.tool.function.jvm300; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class SysEnvTool extends AbstractArthasTool { @Tool( name = "sysenv", description = "SysEnv 诊断工具: 查看系统环境变量,对应 Arthas 的 sysenv 命令。" ) public String sysenv( @ToolParam(description = "环境变量名。若为空或空字符串,则查看所有变量;否则查看单个变量值。", required = false) String envName, ToolContext toolContext ) { StringBuilder cmd = buildCommand("sysenv"); if (envName != null && !envName.trim().isEmpty()) { cmd.append(" ").append(envName.trim()); } return executeSync(toolContext, cmd.toString()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/MBeanTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/MBeanTool.java
package com.taobao.arthas.core.mcp.tool.function.jvm300; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class MBeanTool extends AbstractArthasTool { public static final int DEFAULT_NUMBER_OF_EXECUTIONS = 1; public static final int DEFAULT_REFRESH_INTERVAL_MS = 3000; /** * mbean 诊断工具: 查看或监控 MBean 属性 * 支持: * - namePattern: MBean 名称表达式,支持通配符或正则(需开启 -E) * - attributePattern: 属性名称表达式,支持通配符或正则(需开启 -E) * - metadata: 是否查看元信息 (-m) * - intervalMs: 刷新属性值时间间隔 (ms) (-i),required=false * - numberOfExecutions: 刷新次数 (-n),若未指定或 <=0 则使用 DEFAULT_NUMBER_OF_EXECUTIONS * - regex: 是否启用正则匹配 (-E),required=false */ @Tool( name = "mbean", description = "MBean 诊断工具: 查看或监控 MBean 属性信息,对应 Arthas 的 mbean 命令。" ) public String mbean( @ToolParam(description = "MBean名称表达式匹配,如java.lang:type=GarbageCollector,name=*") String namePattern, @ToolParam(description = "属性名表达式匹配,支持通配符如CollectionCount", required = false) String attributePattern, @ToolParam(description = "是否查看元信息 (-m)", required = false) Boolean metadata, @ToolParam(description = "刷新间隔,单位为毫秒,默认 3000ms。用于控制输出频率", required = false) Integer intervalMs, @ToolParam(description = "执行次数限制,默认值为 1。达到指定次数后自动停止", required = false) Integer numberOfExecutions, @ToolParam(description = "开启正则表达式匹配,默认为通配符匹配,默认false", required = false) Boolean regex, ToolContext toolContext ) { boolean needStreamOutput = (intervalMs != null && intervalMs > 0) || (numberOfExecutions != null && numberOfExecutions > 0); int interval = getDefaultValue(intervalMs, DEFAULT_REFRESH_INTERVAL_MS); int execCount = getDefaultValue(numberOfExecutions, DEFAULT_NUMBER_OF_EXECUTIONS); StringBuilder cmd = buildCommand("mbean"); addFlag(cmd, "-m", metadata); addFlag(cmd, "-E", regex); // 只有在需要流式输出且不是查看元数据时才添加 -i 和 -n 参数 if (needStreamOutput && !Boolean.TRUE.equals(metadata)) { cmd.append(" -i ").append(interval); cmd.append(" -n ").append(execCount); } if (namePattern != null && !namePattern.trim().isEmpty()) { cmd.append(" ").append(namePattern.trim()); } if (attributePattern != null && !attributePattern.trim().isEmpty()) { cmd.append(" ").append(attributePattern.trim()); } logger.info("Starting mbean execution: {}", cmd.toString()); return executeSync(toolContext, cmd.toString()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/MemoryTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/MemoryTool.java
package com.taobao.arthas.core.mcp.tool.function.jvm300; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; public class MemoryTool extends AbstractArthasTool { @Tool( name = "memory", description = "Memory 诊断工具: 查看 JVM 内存使用情况,对应 Arthas 的 memory 命令。" ) public String memory(ToolContext toolContext) { return executeSync(toolContext, "memory"); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/SysPropTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/SysPropTool.java
package com.taobao.arthas.core.mcp.tool.function.jvm300; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class SysPropTool extends AbstractArthasTool { @Tool( name = "sysprop", description = "SysProp 诊断工具: 查看或修改系统属性,对应 Arthas 的 sysprop 命令。" ) public String sysprop( @ToolParam(description = "属性名", required = false) String propertyName, @ToolParam(description = "属性值;若指定则修改,否则查看", required = false) String propertyValue, ToolContext toolContext ) { StringBuilder cmd = buildCommand("sysprop"); if (propertyName != null && !propertyName.trim().isEmpty()) { cmd.append(" ").append(propertyName.trim()); if (propertyValue != null && !propertyValue.trim().isEmpty()) { cmd.append(" ").append(propertyValue.trim()); } } return executeSync(toolContext, cmd.toString()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/JvmTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/JvmTool.java
package com.taobao.arthas.core.mcp.tool.function.jvm300; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; public class JvmTool extends AbstractArthasTool { @Tool( name = "jvm", description = "Jvm 诊断工具: 查看当前 JVM 运行时信息。对应 Arthas 的 jvm 命令。" ) public String jvm(ToolContext toolContext) { return executeSync(toolContext, "jvm"); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/GetStaticTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/GetStaticTool.java
package com.taobao.arthas.core.mcp.tool.function.jvm300; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class GetStaticTool extends AbstractArthasTool { @Tool( name = "getstatic", description = "GetStatic 诊断工具: 查看类的静态字段值,可指定 ClassLoader,支持在返回结果上执行 OGNL 表达式。对应 Arthas 的 getstatic 命令。" ) public String getstatic( @ToolParam(description = "ClassLoader的hashcode(16进制),用于指定特定的ClassLoader", required = false) String classLoaderHash, @ToolParam(description = "ClassLoader的完整类名,如sun.misc.Launcher$AppClassLoader,可替代hashcode", required = false) String classLoaderClass, @ToolParam(description = "类名表达式匹配,如java.lang.String或demo.MathGame") String className, @ToolParam(description = "静态字段名") String fieldName, @ToolParam(description = "OGNL 表达式", required = false) String ognlExpression, ToolContext toolContext ) { StringBuilder cmd = buildCommand("getstatic"); if (classLoaderHash != null && !classLoaderHash.trim().isEmpty()) { addParameter(cmd, "-c", classLoaderHash); } else if (classLoaderClass != null && !classLoaderClass.trim().isEmpty()) { addParameter(cmd, "--classLoaderClass", classLoaderClass); } addParameter(cmd, className); addParameter(cmd, fieldName); if (ognlExpression != null && !ognlExpression.trim().isEmpty()) { cmd.append(" ").append(ognlExpression.trim()); } return executeSync(toolContext, cmd.toString()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/OgnlTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/OgnlTool.java
package com.taobao.arthas.core.mcp.tool.function.jvm300; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; public class OgnlTool extends AbstractArthasTool { @Tool( name = "ognl", description = "OGNL 诊断工具: 执行 OGNL 表达式,对应 Arthas 的 ognl 命令。" ) public String ognl( @ToolParam(description = "OGNL 表达式") String expression, @ToolParam(description = "ClassLoader的hashcode(16进制),用于指定特定的ClassLoader", required = false) String classLoaderHash, @ToolParam(description = "ClassLoader的完整类名,如sun.misc.Launcher$AppClassLoader,可替代hashcode", required = false) String classLoaderClass, @ToolParam(description = "结果对象展开层次 (-x),默认 1", required = false) Integer expandLevel, ToolContext toolContext ) { StringBuilder cmd = buildCommand("ognl"); if (classLoaderHash != null && !classLoaderHash.trim().isEmpty()) { addParameter(cmd, "-c", classLoaderHash); } else if (classLoaderClass != null && !classLoaderClass.trim().isEmpty()) { addParameter(cmd, "--classLoaderClass", classLoaderClass); } if (expandLevel != null && expandLevel > 0) { cmd.append(" -x ").append(expandLevel); } addParameter(cmd, expression); return executeSync(toolContext, cmd.toString()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/HeapdumpTool.java
core/src/main/java/com/taobao/arthas/core/mcp/tool/function/jvm300/HeapdumpTool.java
package com.taobao.arthas.core.mcp.tool.function.jvm300; import com.taobao.arthas.core.mcp.tool.function.AbstractArthasTool; import com.taobao.arthas.mcp.server.tool.ToolContext; import com.taobao.arthas.mcp.server.tool.annotation.Tool; import com.taobao.arthas.mcp.server.tool.annotation.ToolParam; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class HeapdumpTool extends AbstractArthasTool { public static final String DEFAULT_DUMP_DIR = Paths.get("arthas-output").toAbsolutePath().toString().replace("\\", "/"); private static final DateTimeFormatter TIMESTAMP_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"); /** * heapdump 诊断工具 * 支持: * - live: 是否只 dump 存活对象 (--live) * - filePath: 输出文件路径,若为空则使用默认临时文件 */ @Tool( name = "heapdump", description = "Heapdump 诊断工具: 生成 JVM heap dump,支持 --live 选项。对应 Arthas 的 heapdump 命令。" ) public String heapdump( @ToolParam(description = "是否只 dump 存活对象 (--live)", required = false) Boolean live, @ToolParam(description = "指定输出文件路径,默认为当前工作目录下的arthas-output文件夹中的时间戳命名的.hprof文件", required = false) String filePath, ToolContext toolContext ) throws IOException { String finalFilePath; if (filePath != null && !filePath.trim().isEmpty()) { finalFilePath = filePath.trim().replace("\\", "/"); } else { Path defaultDir = Paths.get(DEFAULT_DUMP_DIR); if (!Files.exists(defaultDir)) { Files.createDirectories(defaultDir); } String timestamp = LocalDateTime.now().format(TIMESTAMP_FORMATTER); String defaultFileName = String.format("heapdump_%s.hprof", timestamp); finalFilePath = Paths.get(DEFAULT_DUMP_DIR, defaultFileName).toString().replace("\\", "/"); } StringBuilder cmd = buildCommand("heapdump"); addFlag(cmd, "--live", live); cmd.append(" ").append(finalFilePath); return executeSync(toolContext, cmd.toString()); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/one/profiler/package-info.java
core/src/main/java/one/profiler/package-info.java
/** * This package is from https://github.com/async-profiler/async-profiler/ * tag v2.9 commit 32601bc */ package one.profiler;
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/one/profiler/Counter.java
core/src/main/java/one/profiler/Counter.java
/* * Copyright The async-profiler authors * SPDX-License-Identifier: Apache-2.0 */ package one.profiler; /** * Which metrics to use when generating profile in collapsed stack traces format. */ public enum Counter { SAMPLES, TOTAL }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/one/profiler/AsyncProfilerMXBean.java
core/src/main/java/one/profiler/AsyncProfilerMXBean.java
/* * Copyright The async-profiler authors * SPDX-License-Identifier: Apache-2.0 */ package one.profiler; /** * AsyncProfiler interface for JMX server. * How to register AsyncProfiler MBean: * * <pre>{@code * ManagementFactory.getPlatformMBeanServer().registerMBean( * AsyncProfiler.getInstance(), * new ObjectName("one.profiler:type=AsyncProfiler") * ); * }</pre> */ public interface AsyncProfilerMXBean { void start(String event, long interval) throws IllegalStateException; void resume(String event, long interval) throws IllegalStateException; void stop() throws IllegalStateException; long getSamples(); String getVersion(); String execute(String command) throws IllegalArgumentException, IllegalStateException, java.io.IOException; String dumpCollapsed(Counter counter); String dumpTraces(int maxTraces); String dumpFlat(int maxMethods); byte[] dumpOtlp(); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/one/profiler/AsyncProfiler.java
core/src/main/java/one/profiler/AsyncProfiler.java
/* * Copyright The async-profiler authors * SPDX-License-Identifier: Apache-2.0 */ package one.profiler; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * Java API for in-process profiling. Serves as a wrapper around * async-profiler native library. This class is a singleton. * The first call to {@link #getInstance()} initiates loading of * libasyncProfiler.so. */ public class AsyncProfiler implements AsyncProfilerMXBean { private static AsyncProfiler instance; private AsyncProfiler() { } public static AsyncProfiler getInstance() { return getInstance(null); } public static synchronized AsyncProfiler getInstance(String libPath) { if (instance != null) { return instance; } AsyncProfiler profiler = new AsyncProfiler(); if (libPath != null) { System.load(libPath); } else { try { // No need to load library, if it has been preloaded with -agentpath profiler.getVersion(); } catch (UnsatisfiedLinkError e) { File file = extractEmbeddedLib(); if (file != null) { try { System.load(file.getPath()); } finally { file.delete(); } } else { System.loadLibrary("asyncProfiler"); } } } instance = profiler; return profiler; } private static File extractEmbeddedLib() { String resourceName = "/" + getPlatformTag() + "/libasyncProfiler.so"; InputStream in = AsyncProfiler.class.getResourceAsStream(resourceName); if (in == null) { return null; } try { String extractPath = System.getProperty("one.profiler.extractPath"); File file = File.createTempFile("libasyncProfiler-", ".so", extractPath == null || extractPath.isEmpty() ? null : new File(extractPath)); try (FileOutputStream out = new FileOutputStream(file)) { byte[] buf = new byte[32000]; for (int bytes; (bytes = in.read(buf)) >= 0; ) { out.write(buf, 0, bytes); } } return file; } catch (IOException e) { throw new IllegalStateException(e); } finally { try { in.close(); } catch (IOException e) { // ignore } } } private static String getPlatformTag() { String os = System.getProperty("os.name").toLowerCase(); String arch = System.getProperty("os.arch").toLowerCase(); if (os.contains("linux")) { if (arch.equals("amd64") || arch.equals("x86_64") || arch.contains("x64")) { return "linux-x64"; } else if (arch.equals("aarch64") || arch.contains("arm64")) { return "linux-arm64"; } else if (arch.equals("aarch32") || arch.contains("arm")) { return "linux-arm32"; } else if (arch.contains("86")) { return "linux-x86"; } else if (arch.contains("ppc64")) { return "linux-ppc64le"; } } else if (os.contains("mac")) { return "macos"; } throw new UnsupportedOperationException("Unsupported platform: " + os + "-" + arch); } /** * Start profiling * * @param event Profiling event, see {@link Events} * @param interval Sampling interval, e.g. nanoseconds for Events.CPU * @throws IllegalStateException If profiler is already running */ @Override public void start(String event, long interval) throws IllegalStateException { if (event == null) { throw new NullPointerException(); } start0(event, interval, true); } /** * Start or resume profiling without resetting collected data. * Note that event and interval may change since the previous profiling session. * * @param event Profiling event, see {@link Events} * @param interval Sampling interval, e.g. nanoseconds for Events.CPU * @throws IllegalStateException If profiler is already running */ @Override public void resume(String event, long interval) throws IllegalStateException { if (event == null) { throw new NullPointerException(); } start0(event, interval, false); } /** * Stop profiling (without dumping results) * * @throws IllegalStateException If profiler is not running */ @Override public void stop() throws IllegalStateException { stop0(); } /** * Get the number of samples collected during the profiling session * * @return Number of samples */ @Override public native long getSamples(); /** * Get profiler agent version, e.g. "1.0" * * @return Version string */ @Override public String getVersion() { try { return execute0("version"); } catch (IOException e) { throw new IllegalStateException(e); } } /** * Execute an agent-compatible profiling command - * the comma-separated list of arguments described in arguments.cpp * * @param command Profiling command * @return The command result * @throws IllegalArgumentException If failed to parse the command * @throws IOException If failed to create output file */ @Override public String execute(String command) throws IllegalArgumentException, IllegalStateException, IOException { if (command == null) { throw new NullPointerException(); } return execute0(command); } /** * Dump profile in 'collapsed stacktraces' format * * @param counter Which counter to display in the output * @return Textual representation of the profile */ @Override public String dumpCollapsed(Counter counter) { try { return execute0("collapsed," + counter.name().toLowerCase()); } catch (IOException e) { throw new IllegalStateException(e); } } /** * Dump collected stack traces * * @param maxTraces Maximum number of stack traces to dump. 0 means no limit * @return Textual representation of the profile */ @Override public String dumpTraces(int maxTraces) { try { return execute0(maxTraces == 0 ? "traces" : "traces=" + maxTraces); } catch (IOException e) { throw new IllegalStateException(e); } } /** * Dump flat profile, i.e. the histogram of the hottest methods * * @param maxMethods Maximum number of methods to dump. 0 means no limit * @return Textual representation of the profile */ @Override public String dumpFlat(int maxMethods) { try { return execute0(maxMethods == 0 ? "flat" : "flat=" + maxMethods); } catch (IOException e) { throw new IllegalStateException(e); } } /** * Dump collected data in OTLP format. * <p> * This API is UNSTABLE and might change or be removed in the next version of async-profiler. * * @return OTLP representation of the profile */ @Override public byte[] dumpOtlp() { try { return execute1("otlp"); } catch (IOException e) { throw new IllegalStateException(e); } } /** * Add the given thread to the set of profiled threads. * 'filter' option must be enabled to use this method. * * @param thread Thread to include in profiling */ public void addThread(Thread thread) { filterThread(thread, true); } /** * Remove the given thread from the set of profiled threads. * 'filter' option must be enabled to use this method. * * @param thread Thread to exclude from profiling */ public void removeThread(Thread thread) { filterThread(thread, false); } private void filterThread(Thread thread, boolean enable) { if (thread == null || thread == Thread.currentThread()) { filterThread0(null, enable); } else { // Need to take lock to avoid race condition with a thread state change synchronized (thread) { Thread.State state = thread.getState(); if (state != Thread.State.NEW && state != Thread.State.TERMINATED) { filterThread0(thread, enable); } } } } private native void start0(String event, long interval, boolean reset) throws IllegalStateException; private native void stop0() throws IllegalStateException; private native String execute0(String command) throws IllegalArgumentException, IllegalStateException, IOException; private native byte[] execute1(String command) throws IllegalArgumentException, IllegalStateException, IOException; private native void filterThread0(Thread thread, boolean enable); }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/core/src/main/java/one/profiler/Events.java
core/src/main/java/one/profiler/Events.java
/* * Copyright The async-profiler authors * SPDX-License-Identifier: Apache-2.0 */ package one.profiler; /** * Predefined event names to use in {@link AsyncProfiler#start(String, long)} */ public class Events { public static final String CPU = "cpu"; public static final String ALLOC = "alloc"; public static final String LOCK = "lock"; public static final String WALL = "wall"; public static final String CTIMER = "ctimer"; public static final String ITIMER = "itimer"; }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/com/taobao/arthas/client/TelnetConsole.java
client/src/main/java/com/taobao/arthas/client/TelnetConsole.java
package com.taobao.arthas.client; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.apache.commons.net.telnet.InvalidTelnetOptionException; import org.apache.commons.net.telnet.TelnetClient; import org.apache.commons.net.telnet.TelnetOptionHandler; import org.apache.commons.net.telnet.WindowSizeOptionHandler; import com.taobao.arthas.common.OSUtils; import com.taobao.arthas.common.UsageRender; import com.taobao.middleware.cli.CLI; import com.taobao.middleware.cli.CommandLine; import com.taobao.middleware.cli.UsageMessageFormatter; import com.taobao.middleware.cli.annotations.Argument; import com.taobao.middleware.cli.annotations.CLIConfigurator; import com.taobao.middleware.cli.annotations.Description; import com.taobao.middleware.cli.annotations.Name; import com.taobao.middleware.cli.annotations.Option; import com.taobao.middleware.cli.annotations.Summary; import jline.Terminal; import jline.TerminalSupport; import jline.UnixTerminal; import jline.console.ConsoleReader; import jline.console.KeyMap; /** * @author ralf0131 2016-12-29 11:55. * @author hengyunabc 2018-11-01 */ @Name("arthas-client") @Summary("Arthas Telnet Client") @Description("EXAMPLES:\n" + " java -jar arthas-client.jar 127.0.0.1 3658\n" + " java -jar arthas-client.jar -c 'dashboard -n 1' \n" + " java -jar arthas-client.jar -f batch.as 127.0.0.1\n") public class TelnetConsole { private static final String PROMPT = "[arthas@"; // [arthas@49603]$ private static final int DEFAULT_CONNECTION_TIMEOUT = 5000; // 5000 ms private static final byte CTRL_C = 0x03; // ------- Status codes ------- // /** * Process success */ public static final int STATUS_OK = 0; /** * Generic error */ public static final int STATUS_ERROR = 1; /** * Execute commands timeout */ public static final int STATUS_EXEC_TIMEOUT = 100; /** * Execute commands error */ public static final int STATUS_EXEC_ERROR = 101; private boolean help = false; private String targetIp = "127.0.0.1"; private int port = 3658; private String command; private String batchFile; private int executionTimeout = -1; private Integer width = null; private Integer height = null; @Argument(argName = "target-ip", index = 0, required = false) @Description("Target ip") public void setTargetIp(String targetIp) { this.targetIp = targetIp; } @Argument(argName = "port", index = 1, required = false) @Description("The remote server port") public void setPort(int port) { this.port = port; } @Option(longName = "help", flag = true) @Description("Print usage") public void setHelp(boolean help) { this.help = help; } @Option(shortName = "c", longName = "command") @Description("Command to execute, multiple commands separated by ;") public void setCommand(String command) { this.command = command; } @Option(shortName = "f", longName = "batch-file") @Description("The batch file to execute") public void setBatchFile(String batchFile) { this.batchFile = batchFile; } @Option(shortName = "t", longName = "execution-timeout") @Description("The timeout (ms) of execute commands or batch file ") public void setExecutionTimeout(int executionTimeout) { this.executionTimeout = executionTimeout; } @Option(shortName = "w", longName = "width") @Description("The terminal width") public void setWidth(int width) { this.width = width; } @Option(shortName = "h", longName = "height") @Description("The terminal height") public void setheight(int height) { this.height = height; } public TelnetConsole() { } private static List<String> readLines(File batchFile) { List<String> list = new ArrayList<String>(); BufferedReader br = null; try { br = new BufferedReader(new FileReader(batchFile)); String line = br.readLine(); while (line != null) { list.add(line); line = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { // ignore } } } return list; } public static void main(String[] args) throws Exception { try { int status = process(args, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(STATUS_OK); } }); System.exit(status); } catch (Throwable e) { e.printStackTrace(); CLI cli = CLIConfigurator.define(TelnetConsole.class); System.out.println(usage(cli)); System.exit(STATUS_ERROR); } } /** * 提供给arthas-boot使用的主处理函数 * * @param args * @return status code * @throws IOException * @throws InterruptedException */ public static int process(String[] args) throws IOException, InterruptedException { return process(args, null); } /** * arthas client 主函数 * 注意: process()函数提供给arthas-boot使用,内部不能调用System.exit()结束进程的方法 * * @param args * @param eotEventCallback Ctrl+D signals an End of Transmission (EOT) event * @return status code * @throws IOException */ public static int process(String[] args, ActionListener eotEventCallback) throws IOException { // support mingw/cygw jline color if (OSUtils.isCygwinOrMinGW()) { System.setProperty("jline.terminal", System.getProperty("jline.terminal", "jline.UnixTerminal")); } TelnetConsole telnetConsole = new TelnetConsole(); CLI cli = CLIConfigurator.define(TelnetConsole.class); CommandLine commandLine = cli.parse(Arrays.asList(args)); CLIConfigurator.inject(commandLine, telnetConsole); if (telnetConsole.isHelp()) { System.out.println(usage(cli)); return STATUS_OK; } // Try to read cmds List<String> cmds = new ArrayList<String>(); if (telnetConsole.getCommand() != null) { for (String c : telnetConsole.getCommand().split(";")) { cmds.add(c.trim()); } } else if (telnetConsole.getBatchFile() != null) { File file = new File(telnetConsole.getBatchFile()); if (!file.exists()) { throw new IllegalArgumentException("batch file do not exist: " + telnetConsole.getBatchFile()); } else { cmds.addAll(readLines(file)); } } final ConsoleReader consoleReader = new ConsoleReader(System.in, System.out); consoleReader.setHandleUserInterrupt(true); Terminal terminal = consoleReader.getTerminal(); // support catch ctrl+c event terminal.disableInterruptCharacter(); if (terminal instanceof UnixTerminal) { ((UnixTerminal) terminal).disableLitteralNextCharacter(); } try { int width = TerminalSupport.DEFAULT_WIDTH; int height = TerminalSupport.DEFAULT_HEIGHT; if (!cmds.isEmpty()) { // batch mode if (telnetConsole.getWidth() != null) { width = telnetConsole.getWidth(); } if (telnetConsole.getheight() != null) { height = telnetConsole.getheight(); } } else { // normal telnet client, get current terminal size if (telnetConsole.getWidth() != null) { width = telnetConsole.getWidth(); } else { width = terminal.getWidth(); // hack for windows dos if (OSUtils.isWindows()) { width--; } } if (telnetConsole.getheight() != null) { height = telnetConsole.getheight(); } else { height = terminal.getHeight(); } } final TelnetClient telnet = new TelnetClient(); telnet.setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT); // send init terminal size TelnetOptionHandler sizeOpt = new WindowSizeOptionHandler(width, height, true, true, false, false); try { telnet.addOptionHandler(sizeOpt); } catch (InvalidTelnetOptionException e) { // ignore } // ctrl + c event callback consoleReader.getKeys().bind(Character.toString((char) CTRL_C), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { consoleReader.getCursorBuffer().clear(); // clear current line telnet.getOutputStream().write(CTRL_C); telnet.getOutputStream().flush(); } catch (Exception e1) { e1.printStackTrace(); } } }); // ctrl + d event call back consoleReader.getKeys().bind(Character.toString(KeyMap.CTRL_D), eotEventCallback); try { telnet.connect(telnetConsole.getTargetIp(), telnetConsole.getPort()); } catch (IOException e) { System.out.println("Connect to telnet server error: " + telnetConsole.getTargetIp() + " " + telnetConsole.getPort()); throw e; } if (cmds.isEmpty()) { IOUtil.readWrite(telnet.getInputStream(), telnet.getOutputStream(), consoleReader.getInput(), consoleReader.getOutput()); } else { try { return batchModeRun(telnet, cmds, telnetConsole.getExecutionTimeout()); } catch (Throwable e) { System.out.println("Execute commands error: " + e.getMessage()); e.printStackTrace(); return STATUS_EXEC_ERROR; } finally { try { telnet.disconnect(); } catch (IOException e) { //ignore ex } } } return STATUS_OK; } finally { //reset terminal setting, fix https://github.com/alibaba/arthas/issues/1412 try { terminal.restore(); } catch (Throwable e) { System.out.println("Restore terminal settings failure: "+e.getMessage()); e.printStackTrace(); } } } private static int batchModeRun(TelnetClient telnet, List<String> commands, final int executionTimeout) throws IOException, InterruptedException { if (commands.size() == 0) { return STATUS_OK; } long startTime = System.currentTimeMillis(); final InputStream inputStream = telnet.getInputStream(); final OutputStream outputStream = telnet.getOutputStream(); final BlockingQueue<String> receviedPromptQueue = new LinkedBlockingQueue<String>(1); Thread printResultThread = new Thread(new Runnable() { @Override public void run() { try { StringBuilder line = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); int b = -1; while (true) { b = in.read(); if (b == -1) { break; } line.appendCodePoint(b); // 检查到有 [arthas@ 时,意味着可以执行下一个命令了 int index = line.indexOf(PROMPT); if (index > 0) { line.delete(0, index + PROMPT.length()); receviedPromptQueue.put(""); } System.out.print(Character.toChars(b)); } } catch (Exception e) { // ignore } } }); printResultThread.start(); // send commands to arthas server for (String command : commands) { if (command.trim().isEmpty()) { continue; } // try poll prompt and check timeout while (receviedPromptQueue.poll(100, TimeUnit.MILLISECONDS) == null) { if (executionTimeout > 0) { long now = System.currentTimeMillis(); if (now - startTime > executionTimeout) { return STATUS_EXEC_TIMEOUT; } } } // send command to server outputStream.write((command + " | plaintext\n").getBytes()); outputStream.flush(); } // 读到最后一个命令执行后的 prompt ,可以直接发 quit命令了。 receviedPromptQueue.take(); outputStream.write("quit\n".getBytes()); outputStream.flush(); System.out.println(); return STATUS_OK; } private static String usage(CLI cli) { StringBuilder usageStringBuilder = new StringBuilder(); UsageMessageFormatter usageMessageFormatter = new UsageMessageFormatter(); usageMessageFormatter.setOptionComparator(null); cli.usage(usageStringBuilder, usageMessageFormatter); return UsageRender.render(usageStringBuilder.toString()); } public String getTargetIp() { return targetIp; } public int getPort() { return port; } public String getCommand() { return command; } public String getBatchFile() { return batchFile; } public int getExecutionTimeout() { return executionTimeout; } public Integer getWidth() { return width; } public Integer getheight() { return height; } public boolean isHelp() { return help; } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/com/taobao/arthas/client/IOUtil.java
client/src/main/java/com/taobao/arthas/client/IOUtil.java
package com.taobao.arthas.client; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Writer; /*** * This is a utility class providing a reader/writer capability required by the * weatherTelnet, rexec, rshell, and rlogin example programs. The only point of * the class is to hold the static method readWrite which spawns a reader thread * and a writer thread. The reader thread reads from a local input source * (presumably stdin) and writes the data to a remote output destination. The * writer thread reads from a remote input source and writes to a local output * destination. The threads terminate when the remote input source closes. ***/ public final class IOUtil { public static final void readWrite(final InputStream remoteInput, final OutputStream remoteOutput, final InputStream localInput, final Writer localOutput) { Thread reader, writer; reader = new Thread() { @Override public void run() { int ch; try { while (!interrupted() && (ch = localInput.read()) != -1) { remoteOutput.write(ch); remoteOutput.flush(); } } catch (IOException e) { // e.printStackTrace(); } } }; writer = new Thread() { @Override public void run() { try { InputStreamReader reader = new InputStreamReader(remoteInput); while (true) { int singleChar = reader.read(); if (singleChar == -1) { break; } localOutput.write(singleChar); localOutput.flush(); } } catch (IOException e) { e.printStackTrace(); } } }; writer.setPriority(Thread.currentThread().getPriority() + 1); writer.start(); reader.setDaemon(true); reader.start(); try { writer.join(); reader.interrupt(); } catch (InterruptedException e) { // Ignored } } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false
alibaba/arthas
https://github.com/alibaba/arthas/blob/17eb3c17e764728e6bf2cf3a37d56620e8835fd0/client/src/main/java/org/apache/commons/net/MalformedServerReplyException.java
client/src/main/java/org/apache/commons/net/MalformedServerReplyException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.net; import java.io.IOException; /*** * This exception is used to indicate that the reply from a server * could not be interpreted. Most of the NetComponents classes attempt * to be as lenient as possible when receiving server replies. Many * server implementations deviate from IETF protocol specifications, making * it necessary to be as flexible as possible. However, there will be * certain situations where it is not possible to continue an operation * because the server reply could not be interpreted in a meaningful manner. * In these cases, a MalformedServerReplyException should be thrown. * * ***/ public class MalformedServerReplyException extends IOException { private static final long serialVersionUID = 6006765264250543945L; /*** Constructs a MalformedServerReplyException with no message ***/ public MalformedServerReplyException() { super(); } /*** * Constructs a MalformedServerReplyException with a specified message. * * @param message The message explaining the reason for the exception. ***/ public MalformedServerReplyException(String message) { super(message); } }
java
Apache-2.0
17eb3c17e764728e6bf2cf3a37d56620e8835fd0
2026-01-04T14:45:57.082411Z
false