Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -613,13 +613,33 @@ public void postExecute(CommandTree commandLine, String[] args, int exitCode) {
}

/**
* Finish this main with given exit code. By default, uses system exit to terminate. Subclasses may want to
* overwrite this exit behavior e.g. during unit tests.
* Finish this main with given exit code. By default, uses system exit to terminate, except for exit code 0 when no
* other thread keeps the JVM running: then this returns, and the JVM ends when the main method returns. Subclasses
* may want to overwrite this exit behavior e.g. during unit tests.
*/
public void quit(int exitCode) {
if (exitCode == CliExitCode.OK
&& !hasOtherNonDaemonThread(Thread.currentThread(), Thread.getAllStackTraces().keySet())) {
// The JVM then ends with exit code 0 and runs the shutdown hooks, as System.exit(0) does. Since JDK 21,
// System.exit logs the exit through a System.Logger, and the first System.Logger makes the JDK look for a
// LoggerFinder in every JAR of the class path: about 50 ms with the 340 JARs of the distribution.
return;
}
System.exit(exitCode);
}

/**
* Whether another thread than the given one keeps the JVM running (a live thread that is not a daemon).
*/
static boolean hasOtherNonDaemonThread(Thread current, Collection<Thread> threads) {
for (Thread thread : threads) {
if (thread != current && thread.isAlive() && !thread.isDaemon()) {
return true;
}
}
return false;
}

@Override
public CommandResult execute(CommandInvocation invocation) {
if (versionRequested) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@
import java.util.jar.JarFile;

import org.apache.camel.RuntimeCamelException;
import org.apache.camel.catalog.CamelCatalog;
import org.apache.camel.catalog.DefaultCamelCatalog;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
import org.apache.camel.dsl.jbang.run.common.Printer;
Expand Down Expand Up @@ -385,8 +384,9 @@ public static Map<String, Plugin> getActivePlugins(
return activePlugins;
}
if (config != null) {
CamelCatalog catalog = new DefaultCamelCatalog();
String version = catalog.getCatalogVersion();
// no local of the interface type: the verifier would load CamelCatalog when it loads this class, and its JAR
// is far down the class path of the distribution
String version = new DefaultCamelCatalog().getCatalogVersion();
JsonObject plugins = config.getMap("plugins");
if (plugins == null) {
return activePlugins;
Expand Down Expand Up @@ -1205,8 +1205,7 @@ private static boolean loadPluginFromService(
// Check version compatibility if needed
CamelJBangPlugin annotation = pluginClass.getAnnotation(CamelJBangPlugin.class);
if (annotation != null) {
CamelCatalog catalog = new DefaultCamelCatalog();
String version = catalog.getCatalogVersion();
String version = new DefaultCamelCatalog().getCatalogVersion();
String firstVersion = annotation.firstVersion();
if (!version.isBlank() && !firstVersion.isBlank()) {
PluginHelper.versionCheck(main, version, firstVersion, command);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package org.apache.camel.dsl.jbang.core.common;

import java.util.Locale;
import java.util.function.BooleanSupplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

Expand Down Expand Up @@ -50,8 +51,11 @@ private TerminalWidthHelper() {
* Windows. Returns {@value #DEFAULT_WIDTH} if detection fails or if the output is not connected to a terminal.
*/
public static int getTerminalWidth() {
return getTerminalWidth(System.getenv("COLUMNS"), EnvironmentHelper::hasTerminal);
}

static int getTerminalWidth(String cols, BooleanSupplier terminal) {
// Try COLUMNS env var first (set by most shells)
String cols = System.getenv("COLUMNS");
if (cols != null) {
try {
int w = Integer.parseInt(cols.trim());
Expand All @@ -62,6 +66,13 @@ public static int getTerminalWidth() {
// ignore
}
}
if (!terminal.getAsBoolean()) {
// No terminal (output piped or redirected, or input not a terminal, as when an AI agent runs the CLI): the
// command would fail or size a terminal that the output does not go to. Starting it costs tens of
// milliseconds, as from JDK 24 starting a process asks for a System.Logger, which makes the JDK look for a
// LoggerFinder in every JAR of the class path.
return DEFAULT_WIDTH;
}
// Fall back to an OS native command that reads the terminal size without escape sequences
int w = isWindows()
? readWidthFromCommand("cmd", "/c", "mode", "con")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* 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.camel.dsl.jbang.core.commands;

import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

/**
* quit(0) returns instead of calling System.exit only when no other thread keeps the JVM running.
*/
class CamelJBangMainQuitTest {

private final Thread current = Thread.currentThread();

@Test
void onlyTheCurrentThread() {
assertThat(CamelJBangMain.hasOtherNonDaemonThread(current, List.of(current))).isFalse();
}

@Test
void aDaemonThreadDoesNotKeepTheJvmRunning() throws Exception {
CountDownLatch done = new CountDownLatch(1);
Thread thread = waitingThread(done, true);
try {
assertThat(CamelJBangMain.hasOtherNonDaemonThread(current, List.of(current, thread))).isFalse();
} finally {
done.countDown();
thread.join();
}
}

@Test
void aNonDaemonThreadKeepsTheJvmRunning() throws Exception {
CountDownLatch done = new CountDownLatch(1);
Thread thread = waitingThread(done, false);
try {
assertThat(CamelJBangMain.hasOtherNonDaemonThread(current, List.of(current, thread))).isTrue();
} finally {
done.countDown();
thread.join();
}
// ended: no longer keeps the JVM running
assertThat(CamelJBangMain.hasOtherNonDaemonThread(current, List.of(current, thread))).isFalse();
}

@Test
void aThreadThatIsNotStarted() {
Thread thread = new Thread(() -> {
});
assertThat(CamelJBangMain.hasOtherNonDaemonThread(current, List.of(current, thread))).isFalse();
}

private static Thread waitingThread(CountDownLatch done, boolean daemon) {
Thread thread = new Thread(() -> {
try {
done.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
thread.setDaemon(daemon);
thread.start();
return thread;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,22 @@ void getTerminalWidthReturnsPositiveValue() {
assertTrue(width >= 40, "Terminal width should be at least 40, got: " + width);
}

@Test
void getTerminalWidthWithoutTerminalRunsNoCommand() {
// no stty without a terminal: the default width, and the terminal check is the last thing asked
assertEquals(120, TerminalWidthHelper.getTerminalWidth(null, () -> false));
assertEquals(120, TerminalWidthHelper.getTerminalWidth("abc", () -> false));
}

@Test
void getTerminalWidthPrefersColumns() {
// COLUMNS wins, also without a terminal, and the terminal is then not checked
assertEquals(100, TerminalWidthHelper.getTerminalWidth("100", () -> {
throw new AssertionError("the terminal is not checked when COLUMNS is set");
}));
assertEquals(40, TerminalWidthHelper.getTerminalWidth("10", () -> false));
}

// --- fillWidth ---

@Test
Expand Down
26 changes: 26 additions & 0 deletions dsl/camel-jbang/camel-launcher/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,32 @@
</dependencyManagement>

<dependencies>
<!--
First, as the class path of the distribution (the Class-Path of the launcher JAR) follows the order of the
dependencies: the JARs that the short commands (camel ps, get, log, doc, catalog, ...) load classes from,
which camel-jbang-core brings in only further down. The JVM opens the JARs of the class path in order until
it finds a class, so a class from a JAR far down opens every JAR before it.
-->
<dependency>
<groupId>org.aesh</groupId>
<artifactId>aesh</artifactId>
<version>${aesh-version}</version>
</dependency>
<dependency>
<groupId>com.github.freva</groupId>
<artifactId>ascii-table</artifactId>
<version>${ascii-table-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j-api-version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-catalog</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jbang-core</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,19 @@ public class CamelLauncherMain extends CamelJBangMain {
private record EmbeddedPlugin(Supplier<Plugin> factory, Set<String> commands) {
}

// Lambdas, not constructor references (GeneratePlugin::new): a constructor reference loads its class when this list
// is created, so every command would load all the plugins (and the test plugin loads Citrus and picocli). Their
// JARs are far down the class path of the distribution, and loading a class from there opens every JAR before it.
@SuppressWarnings("java:S1612")
private static final List<EmbeddedPlugin> PLUGINS = List.of(
new EmbeddedPlugin(GeneratePlugin::new, Set.of("generate")),
new EmbeddedPlugin(KubernetesPlugin::new, Set.of("kubernetes", "k8s")),
new EmbeddedPlugin(() -> new GeneratePlugin(), Set.of("generate")),
new EmbeddedPlugin(() -> new KubernetesPlugin(), Set.of("kubernetes", "k8s")),
// its jar was in the launcher, but camel mcp installed the plugin on first use, in the plugin configuration
new EmbeddedPlugin(McpPlugin::new, Set.of("mcp")),
new EmbeddedPlugin(SelfUpdatePlugin::new, Set.of("self-update")),
new EmbeddedPlugin(TuiPlugin::new, Set.of("tui")),
new EmbeddedPlugin(ValidatePlugin::new, Set.of("validate")),
new EmbeddedPlugin(TestPlugin::new, Set.of("test")));
new EmbeddedPlugin(() -> new McpPlugin(), Set.of("mcp")),
new EmbeddedPlugin(() -> new SelfUpdatePlugin(), Set.of("self-update")),
new EmbeddedPlugin(() -> new TuiPlugin(), Set.of("tui")),
new EmbeddedPlugin(() -> new ValidatePlugin(), Set.of("validate")),
new EmbeddedPlugin(() -> new TestPlugin(), Set.of("test")));

@Override
public void preExecute(CommandTree commandLine, String[] args) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import java.time.Duration;
import java.util.Properties;

import org.apache.camel.catalog.CamelCatalog;
import org.apache.camel.catalog.DefaultCamelCatalog;
import org.apache.camel.dsl.jbang.core.common.InstallDetector;
import org.apache.camel.dsl.jbang.run.common.VersionHelper;
Expand Down Expand Up @@ -80,13 +79,22 @@ public static void maybeNotify(String[] args) {
refresh = thread;
}

CamelCatalog catalog = new DefaultCamelCatalog();
String running = catalog.getCatalogVersion();
String running = runningVersion();
if (shouldNotify(cache, running, target)) {
System.err.println(formatNotice(running, cache.getProperty("latest_version")));
}
}

/**
* The version of the running launcher, from the manifest of its JAR. The catalog has the same version, but loading
* it on every command opens every JAR of the class path before the catalog JAR, which is far down the class path of
* the distribution.
*/
static String runningVersion() {
String version = UpdateChecker.class.getPackage().getImplementationVersion();
return version != null ? version : new DefaultCamelCatalog().getCatalogVersion();
}

/**
* Waits a little (at most 2 seconds) for the refresh of the cache that {@link #maybeNotify(String[])} started in
* this process. Most commands end before the fetch over the network would, and the JVM then stops it, so the cache
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,20 @@
import java.util.Properties;

import com.sun.net.httpserver.HttpServer;
import org.apache.camel.catalog.DefaultCamelCatalog;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

class UpdateCheckerTest {

@Test
void runningVersionIsTheCatalogVersion() {
// from the manifest of the launcher JAR, or from the catalog when there is no manifest (as in this test)
assertThat(UpdateChecker.runningVersion()).isEqualTo(new DefaultCamelCatalog().getCatalogVersion());
}

@Test
void formatsNoticeWhenNewerVersionCached() {
String notice = UpdateChecker.formatNotice("4.22.0", "4.23.0");
Expand Down
Loading