From 1712334ef34f70c3dc72f3241818c3729770639b Mon Sep 17 00:00:00 2001 From: hengyunabc Date: Mon, 23 Nov 2026 16:10:05 +0800 Subject: [PATCH] Make version checks asynchronous and optional (#3286) --- core/src/main/java/arthas.properties | 4 + .../taobao/arthas/core/config/Configure.java | 13 + .../arthas/core/server/ArthasBootstrap.java | 14 + .../taobao/arthas/core/util/ArthasBanner.java | 84 +++--- .../arthas/core/config/ConfigureTest.java | 23 ++ .../core/server/ArthasBootstrapTest.java | 17 ++ .../arthas/core/util/ArthasBannerTest.java | 247 ++++++++++++++++++ site/docs/doc/arthas-properties.md | 22 ++ site/docs/en/doc/arthas-properties.md | 22 ++ 9 files changed, 409 insertions(+), 37 deletions(-) create mode 100644 core/src/test/java/com/taobao/arthas/core/util/ArthasBannerTest.java diff --git a/core/src/main/java/arthas.properties b/core/src/main/java/arthas.properties index c0e8d90a8..a2a5ed44f 100644 --- a/core/src/main/java/arthas.properties +++ b/core/src/main/java/arthas.properties @@ -6,6 +6,10 @@ arthas.ip=127.0.0.1 # seconds arthas.sessionTimeout=10800 +# Check for the latest version once in the background (enabled by default). +# Set to false to avoid this request and its DNS lookup in the target JVM. +#arthas.checkLatestVersion=false + #arthas.enhanceLoaders=java.lang.ClassLoader # https://arthas.aliyun.com/doc/en/auth diff --git a/core/src/main/java/com/taobao/arthas/core/config/Configure.java b/core/src/main/java/com/taobao/arthas/core/config/Configure.java index eba5908bc..3f083241d 100644 --- a/core/src/main/java/com/taobao/arthas/core/config/Configure.java +++ b/core/src/main/java/com/taobao/arthas/core/config/Configure.java @@ -63,6 +63,11 @@ public class Configure { */ private String statUrl; + /** + * Check for the latest version in the background. Enabled when unspecified. + */ + private Boolean checkLatestVersion; + /** * session timeout seconds * @see ShellServerOptions#DEFAULT_SESSION_TIMEOUT @@ -182,6 +187,14 @@ public class Configure { this.statUrl = statUrl; } + public boolean isCheckLatestVersion() { + return !Boolean.FALSE.equals(checkLatestVersion); + } + + public void setCheckLatestVersion(boolean checkLatestVersion) { + this.checkLatestVersion = checkLatestVersion; + } + public String getAppName() { return appName; } diff --git a/core/src/main/java/com/taobao/arthas/core/server/ArthasBootstrap.java b/core/src/main/java/com/taobao/arthas/core/server/ArthasBootstrap.java index 2b62037d1..31943ffc5 100644 --- a/core/src/main/java/com/taobao/arthas/core/server/ArthasBootstrap.java +++ b/core/src/main/java/com/taobao/arthas/core/server/ArthasBootstrap.java @@ -120,6 +120,7 @@ public class ArthasBootstrap { private Instrumentation instrumentation; private InstrumentTransformer classLoaderInstrumentTransformer; private Thread shutdown; + private Thread versionCheckThread; private ShellServer shellServer; private ScheduledExecutorService executorService; private SessionManager sessionManager; @@ -193,6 +194,15 @@ public class ArthasBootstrap { transformerManager = new TransformerManager(instrumentation); Runtime.getRuntime().addShutdownHook(shutdown); + + startVersionCheck(); + } + + void startVersionCheck() { + logger().info("Current arthas version: {}", ArthasBanner.version()); + if (configure.isCheckLatestVersion()) { + versionCheckThread = ArthasBanner.checkLatestVersionAsync(); + } } private void initFastjson() { @@ -840,6 +850,10 @@ public class ArthasBootstrap { * call reset() before destroy() */ public void destroy() { + if (versionCheckThread != null) { + versionCheckThread.interrupt(); + versionCheckThread = null; + } if (this.arthasMcpBootstrap != null) { try { // stop 时需要主动关闭 mcp keep-alive 调度线程,避免 stop 后残留线程导致 ArthasClassLoader 无法回收 diff --git a/core/src/main/java/com/taobao/arthas/core/util/ArthasBanner.java b/core/src/main/java/com/taobao/arthas/core/util/ArthasBanner.java index 9a11ad2f9..2ac032444 100644 --- a/core/src/main/java/com/taobao/arthas/core/util/ArthasBanner.java +++ b/core/src/main/java/com/taobao/arthas/core/util/ArthasBanner.java @@ -9,12 +9,12 @@ import com.taobao.text.Decoration; import com.taobao.text.ui.TableElement; import com.taobao.text.util.RenderUtil; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.InterruptedIOException; import java.net.HttpURLConnection; -import java.net.MalformedURLException; import java.net.URL; -import java.net.URLConnection; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; @@ -106,7 +106,6 @@ public class ArthasBanner { } public static String welcome(Map infos) { - logger.info("Current arthas version: {}, recommend latest version: {}", version(), latestVersion()); String appName = System.getProperty("project.name"); if (appName == null) { appName = System.getProperty("app.name"); @@ -132,56 +131,67 @@ public class ArthasBanner { return logo() + "\n" + RenderUtil.render(table); } - static String latestVersion() { - final String[] version = { "" }; + /** + * Start a single, best-effort version check without waiting for network I/O. + * The caller owns the thread and should interrupt it when Arthas stops. + */ + public static Thread checkLatestVersionAsync() { + try { + return checkLatestVersionAsync(new URL(ARTHAS_LATEST_VERSIONS_URL)); + } catch (Throwable e) { + logger.debug("start latest version check error", e); + return null; + } + } + + static Thread checkLatestVersionAsync(final URL url) { Thread thread = new Thread(new Runnable() { @Override public void run() { + if (Thread.currentThread().isInterrupted()) { + return; + } try { - URLConnection urlConnection = openURLConnection(ARTHAS_LATEST_VERSIONS_URL); - InputStream inputStream = urlConnection.getInputStream(); - version[0] = com.taobao.arthas.common.IOUtils.toString(inputStream).trim(); + String latestVersion = latestVersion(url); + if (!Thread.currentThread().isInterrupted()) { + logger.info("Current arthas version: {}, recommend latest version: {}", version(), latestVersion); + } } catch (Throwable e) { logger.debug("get latest version error", e); } } - }); - + }, "arthas-version-check"); thread.setDaemon(true); + thread.setContextClassLoader(ArthasBanner.class.getClassLoader()); thread.start(); - try { - thread.join(2000); // Wait up to 2 seconds for the version check - } catch (Throwable e) { - // Ignore - } - - return version[0]; + return thread; } - /** - * support redirect - * - * @param url - * @return - * @throws MalformedURLException - * @throws IOException - */ - private static URLConnection openURLConnection(String url) throws MalformedURLException, IOException { - URLConnection connection = new URL(url).openConnection(); - if (connection instanceof HttpURLConnection) { + private static String latestVersion(URL url) throws IOException { + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + try { connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); - // normally, 3xx is redirect - int status = ((HttpURLConnection) connection).getResponseCode(); + // Use the JDK's bounded redirect handling instead of recursive requests. + connection.setInstanceFollowRedirects(true); + int status = connection.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { - if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM - || status == HttpURLConnection.HTTP_SEE_OTHER) { - String newUrl = connection.getHeaderField("Location"); - logger.debug("Try to open url: {}, redirect to: {}", url, newUrl); - return openURLConnection(newUrl); - } + throw new IOException("Unexpected version check HTTP status: " + status); } + try (InputStream inputStream = connection.getInputStream()) { + ByteArrayOutputStream result = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + while (!Thread.currentThread().isInterrupted()) { + int length = inputStream.read(buffer); + if (length == -1) { + return result.toString("UTF-8").trim(); + } + result.write(buffer, 0, length); + } + throw new InterruptedIOException("Version check interrupted"); + } + } finally { + connection.disconnect(); } - return connection; } } diff --git a/core/src/test/java/com/taobao/arthas/core/config/ConfigureTest.java b/core/src/test/java/com/taobao/arthas/core/config/ConfigureTest.java index c3aa16e5b..ce65254ed 100644 --- a/core/src/test/java/com/taobao/arthas/core/config/ConfigureTest.java +++ b/core/src/test/java/com/taobao/arthas/core/config/ConfigureTest.java @@ -12,6 +12,29 @@ import com.taobao.arthas.core.env.MapPropertySource; public class ConfigureTest { + @Test + public void shouldEnableVersionCheckByDefault() { + Configure configure = new Configure(); + assertThat(configure.isCheckLatestVersion()).isTrue(); + assertThat(FeatureCodec.DEFAULT_COMMANDLINE_CODEC.toMap(configure.toString())) + .doesNotContainKey("checkLatestVersion"); + } + + @Test + public void shouldBindAndSerializeVersionCheckSetting() throws Exception { + for (boolean enabled : new boolean[] { false, true }) { + Map properties = new HashMap(); + properties.put("arthas.checkLatestVersion", String.valueOf(enabled)); + ArthasEnvironment environment = new ArthasEnvironment(); + environment.addFirst(new MapPropertySource("test", properties)); + Configure configure = new Configure(); + BinderUtils.inject(environment, configure); + + assertThat(configure.isCheckLatestVersion()).isEqualTo(enabled); + assertThat(Configure.toConfigure(configure.toString()).isCheckLatestVersion()).isEqualTo(enabled); + } + } + @Test public void shouldTransmitCrossMountNamespaceMetadataThroughAgentArgs() { Configure source = new Configure(); diff --git a/core/src/test/java/com/taobao/arthas/core/server/ArthasBootstrapTest.java b/core/src/test/java/com/taobao/arthas/core/server/ArthasBootstrapTest.java index 65a7c23e2..0a275dd18 100644 --- a/core/src/test/java/com/taobao/arthas/core/server/ArthasBootstrapTest.java +++ b/core/src/test/java/com/taobao/arthas/core/server/ArthasBootstrapTest.java @@ -133,4 +133,21 @@ public class ArthasBootstrapTest { Mockito.verifyNoInteractions(logger); } + + @Test + public void shouldNotStartVersionCheckWhenDisabled() throws Exception { + Configure configure = new Configure(); + configure.setCheckLatestVersion(false); + ArthasBootstrap bootstrap = Mockito.mock(ArthasBootstrap.class); + Mockito.doCallRealMethod().when(bootstrap).startVersionCheck(); + Field configureField = ArthasBootstrap.class.getDeclaredField("configure"); + configureField.setAccessible(true); + configureField.set(bootstrap, configure); + + bootstrap.startVersionCheck(); + + Field versionCheckThreadField = ArthasBootstrap.class.getDeclaredField("versionCheckThread"); + versionCheckThreadField.setAccessible(true); + assertThat(versionCheckThreadField.get(bootstrap)).isNull(); + } } diff --git a/core/src/test/java/com/taobao/arthas/core/util/ArthasBannerTest.java b/core/src/test/java/com/taobao/arthas/core/util/ArthasBannerTest.java new file mode 100644 index 000000000..4f951c6d1 --- /dev/null +++ b/core/src/test/java/com/taobao/arthas/core/util/ArthasBannerTest.java @@ -0,0 +1,247 @@ +package com.taobao.arthas.core.util; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.SocketAddress; +import java.net.URI; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLStreamHandler; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Test; + +import com.taobao.arthas.core.shell.ShellServerOptions; + +public class ArthasBannerTest { + + @Test + public void shouldRenderWelcomeWithoutCheckingForUpdates() throws Exception { + Path log = Files.createTempFile("arthas-welcome-probe-", ".log"); + try { + String classPath = System.getProperty("surefire.test.class.path", System.getProperty("java.class.path")); + // Isolate the JVM-wide proxy selector from workers started by other tests. + Process process = new ProcessBuilder(new File(System.getProperty("java.home"), "bin/java").getPath(), + "-cp", classPath, WelcomeProbe.class.getName()) + .redirectErrorStream(true).redirectOutput(log.toFile()).start(); + try { + assertThat(process.waitFor(30, TimeUnit.SECONDS)).as("Welcome probe timed out: %s", log).isTrue(); + assertThat(process.exitValue()).as(new String(Files.readAllBytes(log), StandardCharsets.UTF_8)).isZero(); + } finally { + process.destroyForcibly(); + process.waitFor(5, TimeUnit.SECONDS); + } + } finally { + Files.deleteIfExists(log); + } + } + + @Test + public void shouldCheckLatestVersionWithoutWaitingForResponse() throws Exception { + final HttpURLConnection connection = mock(HttpURLConnection.class); + when(connection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + final CountDownLatch requestStarted = new CountDownLatch(1); + final CountDownLatch responseReady = new CountDownLatch(1); + final AtomicBoolean responseClosed = new AtomicBoolean(); + final InputStream response = new ByteArrayInputStream("4.3.5\n".getBytes(StandardCharsets.UTF_8)) { + @Override + public void close() throws IOException { + responseClosed.set(true); + super.close(); + } + }; + when(connection.getInputStream()).thenAnswer(invocation -> { + requestStarted.countDown(); + if (!responseReady.await(5, TimeUnit.SECONDS)) { + throw new IOException("Test response was not released"); + } + return response; + }); + final URL url = urlFor(connection); + ExecutorService caller = Executors.newSingleThreadExecutor(); + Thread worker = null; + try { + worker = caller.submit(new Callable() { + @Override + public Thread call() { + return ArthasBanner.checkLatestVersionAsync(url); + } + }).get(1, TimeUnit.SECONDS); + + assertThat(requestStarted.await(1, TimeUnit.SECONDS)).isTrue(); + assertThat(worker.isAlive()).isTrue(); + assertThat(worker.isDaemon()).isTrue(); + assertThat(worker.getName()).isEqualTo("arthas-version-check"); + assertThat(worker.getContextClassLoader()).isSameAs(ArthasBanner.class.getClassLoader()); + + responseReady.countDown(); + worker.join(5000); + assertThat(worker.isAlive()).isFalse(); + verify(connection).setConnectTimeout(1000); + verify(connection).setReadTimeout(1000); + assertThat(responseClosed.get()).isTrue(); + verify(connection).disconnect(); + } finally { + responseReady.countDown(); + caller.shutdownNow(); + if (worker != null) { + worker.interrupt(); + worker.join(5000); + } + } + } + + @Test + public void shouldReleaseConnectionWhenVersionCheckFails() throws Exception { + HttpURLConnection connection = mock(HttpURLConnection.class); + when(connection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(connection.getInputStream()).thenThrow(new IOException("Version service unavailable")); + + Thread worker = ArthasBanner.checkLatestVersionAsync(urlFor(connection)); + worker.join(5000); + + assertThat(worker.isAlive()).isFalse(); + verify(connection).getInputStream(); + verify(connection).disconnect(); + } + + @Test + public void shouldRejectNonOkVersionResponses() throws Exception { + for (int status : new int[] { 302, 304, 204, 500 }) { + HttpURLConnection connection = mock(HttpURLConnection.class); + when(connection.getResponseCode()).thenReturn(status); + when(connection.getInputStream()).thenReturn(new ByteArrayInputStream( + "not a version".getBytes(StandardCharsets.UTF_8))); + + Thread worker = ArthasBanner.checkLatestVersionAsync(urlFor(connection)); + worker.join(5000); + + assertThat(worker.isAlive()).isFalse(); + verify(connection, never()).getInputStream(); + verify(connection).getResponseCode(); + verify(connection).disconnect(); + } + } + + @Test + public void shouldStopReadingWhenVersionCheckIsInterrupted() throws Exception { + HttpURLConnection connection = mock(HttpURLConnection.class); + when(connection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + InputStream response = mock(InputStream.class); + when(connection.getInputStream()).thenReturn(response); + CountDownLatch firstReadStarted = new CountDownLatch(1); + CountDownLatch firstReadCompleted = new CountDownLatch(1); + CountDownLatch endOfResponse = new CountDownLatch(1); + AtomicInteger reads = new AtomicInteger(); + when(response.read(any(byte[].class))).thenAnswer(invocation -> { + if (reads.getAndIncrement() == 0) { + firstReadStarted.countDown(); + // Ordinary socket reads may finish normally even after interruption. + awaitUninterruptibly(firstReadCompleted); + byte[] buffer = invocation.getArgument(0); + buffer[0] = '4'; + return 1; + } + awaitUninterruptibly(endOfResponse); + return -1; + }); + + Thread worker = ArthasBanner.checkLatestVersionAsync(urlFor(connection)); + try { + assertThat(firstReadStarted.await(5, TimeUnit.SECONDS)).isTrue(); + worker.interrupt(); + firstReadCompleted.countDown(); + worker.join(1000); + + assertThat(worker.isAlive()).isFalse(); + verify(response).read(any(byte[].class)); + verify(response).close(); + verify(connection).disconnect(); + } finally { + firstReadCompleted.countDown(); + endOfResponse.countDown(); + worker.interrupt(); + worker.join(5000); + } + } + + private static void awaitUninterruptibly(CountDownLatch latch) { + boolean interrupted = false; + while (true) { + try { + latch.await(); + break; + } catch (InterruptedException e) { + interrupted = true; + } + } + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + + private static URL urlFor(final HttpURLConnection connection) throws Exception { + return new URL(null, "https://version-check.test/latest_version", new URLStreamHandler() { + @Override + protected URLConnection openConnection(URL url) { + return connection; + } + }); + } + + public static class WelcomeProbe { + public static void main(String[] args) { + final ProxySelector previous = ProxySelector.getDefault(); + final AtomicInteger requests = new AtomicInteger(); + ProxySelector.setDefault(new ProxySelector() { + @Override + public List select(URI uri) { + if ("arthas.aliyun.com".equals(uri.getHost())) { + requests.incrementAndGet(); + // Fail before DNS or network I/O, even when testing the old implementation. + throw new IllegalStateException("Unexpected version check while rendering the welcome message"); + } + return previous == null ? Collections.singletonList(Proxy.NO_PROXY) : previous.select(uri); + } + + @Override + public void connectFailed(URI uri, SocketAddress address, IOException failure) { + if (previous != null) { + previous.connectFailed(uri, address, failure); + } + } + }); + try { + assertThat(new ShellServerOptions().getWelcomeMessage()).contains(ArthasBanner.version()); + assertThat(ArthasBanner.welcome()).contains(ArthasBanner.version()); + assertThat(ArthasBanner.welcome(Collections.singletonMap("test", "welcome"))).contains("welcome"); + assertThat(requests.get()).isZero(); + } finally { + ProxySelector.setDefault(previous); + } + } + } +} diff --git a/site/docs/doc/arthas-properties.md b/site/docs/doc/arthas-properties.md index 40399246b..b06b2550e 100644 --- a/site/docs/doc/arthas-properties.md +++ b/site/docs/doc/arthas-properties.md @@ -34,6 +34,28 @@ arthas.sessionTimeout=10800 如果是防止一个机器上启动多个 arthas 端口冲突。可以配置为随机端口,或者配置为 -1,并且通过 tunnel server 来使用 arthas。 ::: +### 最新版本检查 + +`arthas.checkLatestVersion` 默认为 `true`。Arthas 启动完成后,会在独立的后台守护线程中查询一次最新版本,并将结果写入 `arthas.log`。启动和客户端连接不会等待查询完成,生成欢迎信息也不会重复查询。查询失败只记录 debug 日志,不会重试。 + +仅接受最终 HTTP 状态为 200 的响应;未被自动跟随的重定向等其他状态按查询失败处理。停止 Arthas 时会中断查询线程,响应读取会在两次读取之间检查中断并释放资源。连接和读取超时不是整个查询的总超时,也不能保证中断卡住的原生 DNS 调用。 + +如果不希望目标 JVM 为版本检查发起网络请求,可以在 `arthas.properties` 中配置: + +```properties +arthas.checkLatestVersion=false +``` + +也可以在**目标应用**启动时添加 JVM 参数 `-Darthas.checkLatestVersion=false`。通过 API 初始化时,可以传入: + +```java +ArthasBootstrap.getInstance(instrumentation, "checkLatestVersion=false"); +``` + +使用 `Map` 重载时,对应的 key 是 `arthas.checkLatestVersion`,value 是 `false`。配置需要在 Arthas 初始化前生效。 + +后台查询仍然在目标 JVM 内执行,不能隔离 DNS 等原生代码的进程级崩溃。如果版本查询会触发此类问题,应关闭检查;关闭后不会创建版本检查线程,也不会访问 `/api/latest_version`。此配置只控制目标 JVM 内的版本检查,不影响 `arthas-boot` 为选择或下载版本发起的请求。 + ### 禁止指定命令 ::: tip diff --git a/site/docs/en/doc/arthas-properties.md b/site/docs/en/doc/arthas-properties.md index c16dab426..c4eaaee98 100644 --- a/site/docs/en/doc/arthas-properties.md +++ b/site/docs/en/doc/arthas-properties.md @@ -34,6 +34,28 @@ arthas.sessionTimeout=10800 If you want to prevent multiple arthas port conflicts on a machine. It can be configured as a random port, or configured as -1, and use arthas through the tunnel server. ::: +### Latest version check + +`arthas.checkLatestVersion` defaults to `true`. After Arthas starts, a dedicated background daemon thread checks for the latest version once and writes the result to `arthas.log`. Startup and client connections do not wait for the check, and rendering the welcome message does not trigger additional checks. A failed check is logged at debug level without retries. + +Only a final HTTP status of 200 is accepted. Other responses, including redirects that are not followed automatically, are treated as failed checks. Stopping Arthas interrupts the worker, which checks for interruption between response reads and releases its resources. Connection and read timeouts do not impose a deadline on the entire check or guarantee interruption of a stuck native DNS call. + +To prevent the target JVM from making this version-check request, configure the following in `arthas.properties`: + +```properties +arthas.checkLatestVersion=false +``` + +Alternatively, add `-Darthas.checkLatestVersion=false` to the JVM options of the **target application**. When initializing Arthas through the API, use: + +```java +ArthasBootstrap.getInstance(instrumentation, "checkLatestVersion=false"); +``` + +For the `Map` overload, use the key `arthas.checkLatestVersion` with the value `false`. The setting must take effect before Arthas is initialized. + +The background check still runs inside the target JVM and cannot isolate process crashes in native code such as DNS resolution. Disable the check if it triggers such a problem. When disabled, no version-check thread is created and `/api/latest_version` is not requested. This setting only controls the check in the target JVM; it does not affect requests made by `arthas-boot` to select or download a version. + ### disable specify commands ::: tip