This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new 8e78f5f5968e CAMEL-27004: camel-jbang - camel infra run --background
waits for the service to start, and says why one could not (#30123)
8e78f5f5968e is described below
commit 8e78f5f5968e28e635dc15463fb16d70cee5cfc5
Author: Claus Ibsen <[email protected]>
AuthorDate: Sun Nov 15 23:07:01 2026 +0100
CAMEL-27004: camel-jbang - camel infra run --background waits for the
service to start, and says why one could not (#30123)
… service to start, and says why one could not
camel infra run --background started the service with its output in a
pipe that nobody read, and returned 0 right away. A service that could
not start, such as with Docker down or its container name taken, was
gone without a word, and camel infra ps showed nothing.
Now the output goes to ~/.camel/<pid>-run.log, as for camel run
--background, and the command waits until the service has written its
pid file, which it does once it has started:
- started: prints its connection details (--json: as serviceData, like
camel infra get --json), exit 0
- ended before it started: prints why, exits with its exit code (1 when
that was 0)
- still starting after the wait (such as pulling the image the first
time): left running, exit 124
--background-wait (60s by default, false to not wait) is the option of
camel run, also on camel infra restart. The service removes its run log
when it stops, and camel infra stop --kill, infra restart --kill and the
pruning of stale pid files remove it too.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Claus Ibsen <[email protected]>
---
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 16 ++
.../ROOT/pages/camel-jbang-dev-services.adoc | 20 +++
.../jbang-commands/camel-jbang-infra-restart.adoc | 1 +
.../jbang-commands/camel-jbang-infra-run.adoc | 1 +
.../META-INF/camel-jbang-commands-metadata.json | 2 +-
.../dsl/jbang/core/commands/BackgroundWait.java | 14 +-
.../core/commands/infra/InfraBaseCommand.java | 3 +
.../jbang/core/commands/infra/InfraRestart.java | 12 ++
.../dsl/jbang/core/commands/infra/InfraRun.java | 122 +++++++++++--
.../dsl/jbang/core/commands/infra/InfraStop.java | 3 +
.../commands/infra/InfraRunBackgroundTest.java | 198 +++++++++++++++++++++
.../src/test/resources/golden/cli-help.txt | 18 +-
12 files changed, 387 insertions(+), 23 deletions(-)
diff --git
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 7b30527645df..f63eebcf15e1 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -9109,6 +9109,22 @@ The `withFixedPort()` container of
`camel-test-infra-artemis` maps the same port
A service that does not start because a port it maps on the host is taken now
fails with one line that names the port,
and the infra service that has it, instead of the stack trace of the container
runtime.
+=== camel-jbang - camel infra run --background waits for the service to start
+
+`camel infra run --background` and `camel infra restart --background` wait up
to 60 seconds for the service to start,
+and then print its connection details, as `camel infra run` does in the
foreground (`--json` adds them as
+`serviceData`, as `camel infra get --json` does). Before, the command returned
right away with `0`, and a service that
+could not start, such as with Docker down, was gone without a word. Now:
+
+* A service that ends before it started exits with its exit code (`1` when
that was `0`), and prints why.
+* A service that is still starting after the wait, such as while it pulls its
container image the first time, exits
+ with `124` and is left running.
+* `--background-wait` takes how long, such as `--background-wait=5m`, or
`false` to return right away, as for
+ `camel run --background`.
+
+The output of the service goes to `~/.camel/<pid>-run.log`, instead of a pipe
that nobody read. `camel infra stop`
+removes it.
+
=== camel-jbang - camel run loads one version of each library
`camel run` downloads the JARs of each component when it is first used. It now
keeps one version of each library: when
diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-dev-services.adoc
b/docs/user-manual/modules/ROOT/pages/camel-jbang-dev-services.adoc
index 0d8a9381d9a7..bdbcf9fab2d6 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-dev-services.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-dev-services.adoc
@@ -64,6 +64,26 @@ Starting service kafka with implementation redpanda
}
----
+=== Running in the background
+
+Use `--background` to run the service detached from the terminal. The command
waits until the service has started
+(60 seconds at most), and prints its connection details:
+
+[source,bash]
+----
+$ camel infra run kafka --background
+Running kafka in background with PID: 80093 (waiting for it to start)
+{
+ "getBootstrapServers" : "localhost:9092"
+}
+Log: /Users/me/.camel/80093-run.log
+----
+
+A service that cannot start, such as with Docker down, prints why and exits
with its exit code. A service that is still
+starting after the wait, such as when it pulls its container image the first
time, is left running and the command
+exits with `124`. Set how long with `--background-wait`, such as
`--background-wait=5m`, or do not wait with
+`--background-wait=false`. The output of the service is in
`~/.camel/<pid>-run.log` until `camel infra stop` stops it.
+
== Configuring a service
A service reads its own settings from system properties, so `--property`
passes them through. The
diff --git
a/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-infra-restart.adoc
b/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-infra-restart.adoc
index 5d778f35b67e..657ea8c28797 100644
---
a/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-infra-restart.adoc
+++
b/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-infra-restart.adoc
@@ -20,6 +20,7 @@ camel infra restart [options]
|===
| Option | Description | Default | Type
| `--background` | Run in the background | false | boolean
+| `--background-wait` | How long to wait for the service in the background to
start, before returning, in millis or as a duration such as 2m (true waits 60
seconds, false does not wait) | 60s | long
| `--json` | Output in JSON Format | | boolean
| `--kill` | To force killing the process (SIGKILL) when stopping | | boolean
| `--log` | Log container output to console | | boolean
diff --git
a/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-infra-run.adoc
b/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-infra-run.adoc
index 66717b3d8840..10e4026995ed 100644
---
a/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-infra-run.adoc
+++
b/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-infra-run.adoc
@@ -20,6 +20,7 @@ camel infra run [options]
|===
| Option | Description | Default | Type
| `--background` | Run in the background | false | boolean
+| `--background-wait` | How long to wait for the service in the background to
start, before returning, in millis or as a duration such as 2m (true waits 60
seconds, false does not wait) | 60s | long
| `--json` | Output in JSON Format | | boolean
| `--log` | Log container output to console | | boolean
| `--no-ui` | Do not start companion UI containers | false | boolean
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/generated/resources/META-INF/camel-jbang-commands-metadata.json
b/dsl/camel-jbang/camel-jbang-core/src/generated/resources/META-INF/camel-jbang-commands-metadata.json
index 39c2389bd534..1b7c81fc7c46 100644
---
a/dsl/camel-jbang/camel-jbang-core/src/generated/resources/META-INF/camel-jbang-commands-metadata.json
+++
b/dsl/camel-jbang/camel-jbang-core/src/generated/resources/META-INF/camel-jbang-commands-metadata.json
@@ -17,7 +17,7 @@
{ "name": "get", "fullName": "get", "description": "Get status of Camel
integrations", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.process.CamelStatus", "options": [ {
"names": "--watch", "description": "Execute periodically and showing output
fullscreen", "javaType": "boolean", "type": "boolean" }, { "names":
"-h,--help", "description": "Display this help and exit", "javaType":
"boolean", "type": "boolean" } ], "subcommands": [ { "name": "about",
"fullName": "get about" [...]
{ "name": "harden", "fullName": "harden", "description": "Suggest security
hardening for Camel routes using AI\/LLM", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.Harden", "options": [ { "names":
"--api-key", "description": "API key for authentication. Also reads
OPENAI_API_KEY or LLM_API_KEY env vars", "javaType": "java.lang.String",
"type": "string" }, { "names": "--api-type", "description": "API type: 'ollama'
or 'openai' (OpenAI-compatible)", "defaultValue": "ollama", [...]
{ "name": "hawtio", "fullName": "hawtio", "description": "Launch Hawtio
web console", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.process.Hawtio", "options": [ {
"names": "--host", "description": "Hostname to bind the Hawtio web console to",
"defaultValue": "127.0.0.1", "javaType": "java.lang.String", "type": "string"
}, { "names": "--open-url,--openUrl", "description": "To automatic open Hawtio
web console in the web browser (without an interactive terminal the default
[...]
- { "name": "infra", "fullName": "infra", "description": "List and Run
external services for testing and prototyping", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.infra.InfraCommand", "options": [ {
"names": "--json", "description": "Output in JSON Format", "javaType":
"boolean", "type": "boolean" }, { "names": "-h,--help", "description": "Display
this help and exit", "javaType": "boolean", "type": "boolean" } ],
"subcommands": [ { "name": "get", "fullName": "infra get", " [...]
+ { "name": "infra", "fullName": "infra", "description": "List and Run
external services for testing and prototyping", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.infra.InfraCommand", "options": [ {
"names": "--json", "description": "Output in JSON Format", "javaType":
"boolean", "type": "boolean" }, { "names": "-h,--help", "description": "Display
this help and exit", "javaType": "boolean", "type": "boolean" } ],
"subcommands": [ { "name": "get", "fullName": "infra get", " [...]
{ "name": "init", "fullName": "init", "description": "Creates a new Camel
integration", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.Init",
"options": [ { "names": "--clean-dir,--clean-directory", "description":
"Whether to clean directory first (deletes all files in directory)",
"javaType": "boolean", "type": "boolean" }, { "names": "--dir,--directory",
"description": "Directory relative path where the new Camel integration will be
saved", "defaultValue": ".", "javaType" [...]
{ "name": "jolokia", "fullName": "jolokia", "description": "Attach Jolokia
JVM Agent to a running Camel integration", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.process.Jolokia", "options": [ {
"names": "--port", "description": "To use a specific port number when attaching
Jolokia JVM Agent (default a free port is found in range 8778-9999)",
"javaType": "int", "type": "integer" }, { "names": "--stop", "description":
"Stops the Jolokia JVM Agent in the running Camel inte [...]
{ "name": "log", "fullName": "log", "description": "Tail logs from running
Camel integrations", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.action.CamelLogAction", "options": [
{ "names": "--duration", "description": "How long to keep watching or
following, in millis or as a duration such as 30s (default: until Enter is
pressed)", "javaType": "long", "type": "integer" }, { "names": "--find",
"description": "Find and highlight matching text (ignore case).", "javaType":
"j [...]
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/BackgroundWait.java
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/BackgroundWait.java
index d45d617d2082..43d023508bb7 100644
---
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/BackgroundWait.java
+++
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/BackgroundWait.java
@@ -24,13 +24,13 @@ import
org.apache.camel.dsl.jbang.core.common.StringConverter;
import org.apache.camel.util.TimeUtils;
/**
- * The <tt>--background-wait</tt> option of camel run: how long to wait for an
integration that runs in the background
- * to start, in millis or as a duration such as <tt>2m</tt>. <tt>true</tt> (or
no value) waits 60 seconds, and
- * <tt>false</tt> does not wait. A file name after the option is not its value.
+ * The <tt>--background-wait</tt> option of camel run and camel infra run: how
long to wait for an integration that runs
+ * in the background to start, in millis or as a duration such as <tt>2m</tt>.
<tt>true</tt> (or no value) waits 60
+ * seconds, and <tt>false</tt> does not wait. A file name after the option is
not its value.
*/
-final class BackgroundWait {
+public final class BackgroundWait {
- static final long DEFAULT = 60000;
+ public static final long DEFAULT = 60000;
private BackgroundWait() {
}
@@ -50,7 +50,7 @@ final class BackgroundWait {
/**
* The time to wait, in millis (0 is not to wait).
*/
- static long parse(String text) {
+ public static long parse(String text) {
String value = text.trim();
if ("true".equalsIgnoreCase(value)) {
return DEFAULT;
@@ -73,7 +73,7 @@ final class BackgroundWait {
* The arguments of camel run for the integration that runs in the
background: without <tt>--background</tt> and
* <tt>--background-wait</tt> (with its value).
*/
- static List<String> withoutBackgroundOptions(List<String> args) {
+ public static List<String> withoutBackgroundOptions(List<String> args) {
List<String> answer = new ArrayList<>(args.size());
for (int i = 0; i < args.size(); i++) {
String arg = args.get(i);
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraBaseCommand.java
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraBaseCommand.java
index d1f1a085f55e..7a8c4e811560 100644
---
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraBaseCommand.java
+++
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraBaseCommand.java
@@ -45,6 +45,7 @@ import org.apache.camel.catalog.CamelCatalog;
import org.apache.camel.catalog.DefaultCamelCatalog;
import org.apache.camel.dsl.jbang.core.commands.CamelCommand;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.common.BackgroundLog;
import org.apache.camel.dsl.jbang.core.common.CamelTableColumns;
import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
import org.apache.camel.dsl.jbang.core.common.ProcessHelper;
@@ -193,6 +194,8 @@ public abstract class InfraBaseCommand extends CamelCommand
{
private void pruneStaleFiles(Path camelDir, String service, String pid) {
PathUtils.deleteFile(camelDir.resolve(getJsonFileName(service, pid)));
PathUtils.deleteFile(camelDir.resolve(getLogFileName(service, pid)));
+ // and the output of a service that ran in the background
+ BackgroundLog.remove(Long.parseLong(pid));
}
/**
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRestart.java
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRestart.java
index da403219a2a2..d36a1cbf0083 100644
---
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRestart.java
+++
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRestart.java
@@ -27,7 +27,9 @@ import org.aesh.command.CommandDefinition;
import org.aesh.command.option.Arguments;
import org.aesh.command.option.Option;
import org.aesh.command.option.OptionList;
+import org.apache.camel.dsl.jbang.core.commands.BackgroundWait;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.common.BackgroundLog;
import org.apache.camel.dsl.jbang.run.common.PathUtils;
@CommandDefinition(name = "restart", description = "Restarts a running
external service", generateHelp = true,
@@ -49,6 +51,13 @@ public class InfraRestart extends InfraBaseCommand {
@Option(name = "background", hasValue = false, description = "Run in the
background", defaultValue = "false")
boolean background;
+ @Option(name = "background-wait",
+ description = "How long to wait for the service in the background
to start, before returning, in millis"
+ + " or as a duration such as 2m (true waits 60
seconds, false does not wait)",
+ defaultValue = "60s", optionalValue = true, fallbackValue =
"true", converter = BackgroundWait.Converter.class,
+ parser = BackgroundWait.Parser.class)
+ long backgroundWait = BackgroundWait.DEFAULT;
+
@OptionList(name = "prop", aliases = { "property" }, valueSeparator =
OptionList.NO_SEPARATOR,
description = "Service properties, ex.
--property=ollama.model=qwen2.5:0.5b")
List<String> serviceProperties = new ArrayList<>();
@@ -74,6 +83,8 @@ public class InfraRestart extends InfraBaseCommand {
}
if (kill) {
ProcessHandle.of(entry.getKey()).ifPresent(ProcessHandle::destroyForcibly);
+ // a killed service cannot remove the output it had in the
background
+ BackgroundLog.remove(entry.getKey());
}
}
@@ -97,6 +108,7 @@ public class InfraRestart extends InfraBaseCommand {
infraRun.port = port;
infraRun.setLogToStdout(logToStdout);
infraRun.background = background;
+ infraRun.backgroundWait = backgroundWait;
// a restart starts a new service, so it takes its properties the way
it takes its port
infraRun.serviceProperties = serviceProperties;
return infraRun.doCall();
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRun.java
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRun.java
index 5f091df5a51f..e712462fbc95 100644
---
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRun.java
+++
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRun.java
@@ -36,8 +36,11 @@ import org.aesh.command.CommandDefinition;
import org.aesh.command.option.Arguments;
import org.aesh.command.option.Option;
import org.aesh.command.option.OptionList;
+import org.apache.camel.dsl.jbang.core.commands.BackgroundWait;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.common.BackgroundLog;
import org.apache.camel.dsl.jbang.core.common.CliException;
+import org.apache.camel.dsl.jbang.core.common.CliExitCode;
import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
import org.apache.camel.dsl.jbang.core.common.EnvironmentHelper;
import org.apache.camel.dsl.jbang.core.common.JsonOutput;
@@ -47,6 +50,7 @@ import org.apache.camel.dsl.jbang.run.common.RuntimeUtil;
import org.apache.camel.main.download.DependencyDownloaderClassLoader;
import org.apache.camel.main.download.MavenDependencyDownloader;
import org.apache.camel.tooling.maven.MavenArtifact;
+import org.apache.camel.util.TimeUtils;
import org.apache.camel.util.json.JsonObject;
import org.apache.logging.log4j.core.config.Configurator;
import org.slf4j.Logger;
@@ -64,6 +68,9 @@ public class InfraRun extends InfraBaseCommand {
private static final Logger LOG = LoggerFactory.getLogger(InfraRun.class);
+ // how often a run in the background checks whether the service has started
+ private static final long STARTUP_POLL_INTERVAL = 200;
+
@Arguments(paramLabel = "service", required = true, description = "Service
name")
private List<String> serviceName;
@@ -73,6 +80,13 @@ public class InfraRun extends InfraBaseCommand {
@Option(name = "background", hasValue = false, description = "Run in the
background", defaultValue = "false")
boolean background;
+ @Option(name = "background-wait",
+ description = "How long to wait for the service in the background
to start, before returning, in millis"
+ + " or as a duration such as 2m (true waits 60
seconds, false does not wait)",
+ defaultValue = "60s", optionalValue = true, fallbackValue =
"true", converter = BackgroundWait.Converter.class,
+ parser = BackgroundWait.Parser.class)
+ long backgroundWait = BackgroundWait.DEFAULT;
+
@Option(name = "port", description = "Override the default port for the
service")
Integer port;
@@ -171,25 +185,107 @@ public class InfraRun extends InfraBaseCommand {
}
}
- cmds.remove("--background=true");
- cmds.remove("--background");
+ cmds = BackgroundWait.withoutBackgroundOptions(cmds);
addCamelCLICommand(cmds);
ProcessBuilder pb = new ProcessBuilder();
pb.command(cmds);
- Process p = pb.start();
- if (jsonOutput) {
- JsonObject jo = new JsonObject();
- jo.put("pid", String.valueOf(p.pid()));
- jo.put("alias", testService);
- JsonOutput.print(printer(), jo);
- } else {
- printer().println(
- "Running " + testService + " in background with PID: " +
p.pid());
+ return startInBackground(pb, testService);
+ }
+
+ /**
+ * Starts the service in the background, with its output in
<tt>~/.camel/<pid>-run.log</tt>, and waits until
+ * it has written its pid file with its service data, which it does once
it has started (CAMEL-27004: the output
+ * went to a pipe that nobody read, so a service that could not start,
such as with Docker down, was gone without a
+ * word, and the command exited with 0).
+ *
+ * @param pb the process of the service
+ * @param testService the alias of the service, which names its pid file
+ * @return 0 when the service started, or the exit code of a
service that ended before it started
+ * @throws CliException a timeout when the service is still starting after
the wait, and is left running
+ */
+ int startInBackground(ProcessBuilder pb, String testService) throws
Exception {
+ BackgroundLog.Started started = BackgroundLog.start(pb);
+ Process p = started.process();
+ Path log = started.log();
+ String pid = String.valueOf(p.pid());
+
+ if (!jsonOutput) {
+ printer().println("Running " + testService + " in background with
PID: " + pid
+ + (backgroundWait > 0 ? " (waiting for it to
start)" : ""));
}
- return 0;
+ if (backgroundWait <= 0) {
+ if (jsonOutput) {
+ JsonObject jo = new JsonObject();
+ jo.put("pid", pid);
+ jo.put("alias", testService);
+ jo.put("log", log.toString());
+ JsonOutput.print(printer(), jo);
+ } else {
+ printer().println("Log: " + log);
+ }
+ return 0;
+ }
+
+ Path pidFile =
CommandLineHelper.getCamelDir().resolve(getJsonFileName(testService, pid));
+ long deadline = System.currentTimeMillis() + backgroundWait;
+ String serviceData = startedServiceData(pidFile);
+ while (serviceData == null && p.isAlive() &&
System.currentTimeMillis() < deadline) {
+ try {
+ Thread.sleep(STARTUP_POLL_INTERVAL);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ break;
+ }
+ serviceData = startedServiceData(pidFile);
+ }
+
+ if (serviceData != null) {
+ if (jsonOutput) {
+ JsonObject jo = new JsonObject();
+ jo.put("pid", pid);
+ jo.put("alias", testService);
+ jo.put("log", log.toString());
+ jo.put("serviceData", parseServiceData(serviceData));
+ JsonOutput.print(printer(), jo);
+ } else {
+ printer().println(jsonMapper.writerWithDefaultPrettyPrinter()
+ .writeValueAsString(jsonMapper.readTree(serviceData)));
+ printer().println("Log: " + log);
+ }
+ return 0;
+ }
+ if (!p.isAlive()) {
+ // ended before it started: why is in its output
+ int exitCode = p.exitValue();
+ printer().printErr("Service " + testService + " (PID: " + pid + ")
did not start (exit code " + exitCode + ")");
+ String output = BackgroundLog.read(log);
+ if (!output.isBlank()) {
+ // on stderr with --json, so the output stays JSON
+ if (jsonOutput) {
+ printer().printDiagnostic(output.stripTrailing());
+ } else {
+ printer().println(output.stripTrailing());
+ }
+ }
+ Files.deleteIfExists(log);
+ return exitCode != 0 ? exitCode : CliExitCode.FAILURE;
+ }
+ // still starting, such as pulling its container image the first time:
it is left running
+ String waited = backgroundWait < 1000 ? backgroundWait + "ms" :
TimeUtils.printDuration(backgroundWait);
+ throw CliException.timeout("Service " + testService + " (PID: " + pid
+ ") is still starting after " + waited
+ + "; the log is in " + log);
+ }
+
+ /**
+ * The service data the service wrote to its pid file once it started, or
null while it has not (the file is created
+ * empty, and written after).
+ */
+ private static String startedServiceData(Path pidFile) {
+ String data = readServiceData(pidFile);
+ return data != null && !data.isBlank() && parseServiceData(data) !=
null ? data : null;
}
protected Integer doRun(
@@ -508,6 +604,8 @@ public class InfraRun extends InfraBaseCommand {
} catch (Exception e) {
// ignore
}
+ // the output of a service in the background, which is of no use
once it is stopped
+ BackgroundLog.remove(ProcessHandle.current().pid());
clearInfraProperties();
restoreProperties(replacedProperties);
}
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraStop.java
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraStop.java
index 56688ef3f774..9dc7cdda5e11 100644
---
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraStop.java
+++
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraStop.java
@@ -24,6 +24,7 @@ import org.aesh.command.CommandDefinition;
import org.aesh.command.option.Argument;
import org.aesh.command.option.Option;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.common.BackgroundLog;
import org.apache.camel.dsl.jbang.core.common.CliException;
import org.apache.camel.dsl.jbang.core.common.JsonOutput;
import org.apache.camel.dsl.jbang.run.common.PathUtils;
@@ -75,6 +76,8 @@ public class InfraStop extends InfraBaseCommand {
}
ph.destroyForcibly();
});
+ // a killed service cannot remove the output it had in the
background
+ BackgroundLog.remove(service.pidNumber());
}
}
if (jsonOutput) {
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRunBackgroundTest.java
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRunBackgroundTest.java
new file mode 100644
index 000000000000..a7da71910238
--- /dev/null
+++
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/infra/InfraRunBackgroundTest.java
@@ -0,0 +1,198 @@
+/*
+ * 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.infra;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.common.BackgroundLog;
+import org.apache.camel.dsl.jbang.core.common.CliException;
+import org.apache.camel.dsl.jbang.core.common.CliExitCode;
+import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
+import org.apache.camel.util.json.JsonObject;
+import org.apache.camel.util.json.Jsoner;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.DisabledOnOs;
+import org.junit.jupiter.api.condition.OS;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/**
+ * camel infra run --background has the output of the service in its log, and
waits until the service has written its
+ * pid file, which it does once it has started (CAMEL-27004: the output went
to a pipe nobody read, so a service that
+ * could not start was gone without a word, and the command exited with 0).
+ * <p>
+ * A shell stands in for the service: it writes the pid file
<tt>infra-<service>-$$.json</tt> as infra run does.
+ */
+@DisabledOnOs(OS.WINDOWS)
+class InfraRunBackgroundTest extends InfraCommandTestSupport {
+
+ private static final Pattern PID = Pattern.compile("(?:PID:
|\"pid\"\\s*:\\s*\")(\\d+)");
+
+ @AfterEach
+ void stopService() {
+ // the shell that stands in for the service, which the command left
running
+ Matcher m = PID.matcher(printer.getStdout() + "\n" +
printer.getStderr());
+ if (m.find()) {
+
ProcessHandle.of(Long.parseLong(m.group(1))).ifPresent(ProcessHandle::destroyForcibly);
+ }
+ }
+
+ @Test
+ void waitsForTheServiceToStart() throws Exception {
+ InfraRun infraRun = infraRun();
+
+ int exit = infraRun.startInBackground(
+ service("echo Starting service kafka; sleep 0.5; printf
'{\"getBootstrapServers\":\"localhost:9092\"}' > "
+ + pidFileOfShell("kafka") + "; sleep 60"),
+ "kafka");
+
+ assertThat(exit).isZero();
+ long pid = pid();
+ assertThat(printer.getStdout())
+ .contains("Running kafka in background with PID: " + pid + "
(waiting for it to start)")
+ .contains("\"getBootstrapServers\" : \"localhost:9092\"")
+ .contains("Log: " + BackgroundLog.of(pid));
+
assertThat(ProcessHandle.of(pid).map(ProcessHandle::isAlive)).contains(true);
+ // the log has the output of the service
+
assertThat(BackgroundLog.read(BackgroundLog.of(pid))).contains("Starting
service kafka");
+ }
+
+ @Test
+ void theServiceDataAsJson() throws Exception {
+ InfraRun infraRun = infraRun();
+ infraRun.jsonOutput = true;
+
+ int exit = infraRun.startInBackground(
+ service("printf '{\"getBootstrapServers\":\"localhost:9092\"}'
> " + pidFileOfShell("kafka")
+ + "; sleep 60"),
+ "kafka");
+
+ assertThat(exit).isZero();
+ long pid = pid();
+ JsonObject json = (JsonObject) Jsoner.deserialize(printer.getStdout());
+ assertThat(json.getString("pid")).isEqualTo(String.valueOf(pid));
+ assertThat(json.getString("alias")).isEqualTo("kafka");
+
assertThat(json.getString("log")).isEqualTo(BackgroundLog.of(pid).toString());
+ assertThat(((Map<?, ?>)
json.get("serviceData")).get("getBootstrapServers")).isEqualTo("localhost:9092");
+ }
+
+ @Test
+ void aServiceThatCannotStartTellsWhy() throws Exception {
+ InfraRun infraRun = infraRun();
+
+ int exit = infraRun.startInBackground(
+ service("echo 'Could not find a valid Docker environment';
exit 1"), "kafka");
+
+ assertThat(exit).isEqualTo(1);
+ long pid = pid();
+ assertThat(printer.getStderr()).contains("Service kafka (PID: " + pid
+ ") did not start (exit code 1)");
+ assertThat(printer.getStdout()).contains("Could not find a valid
Docker environment");
+ // it was shown, and the service is gone
+ assertThat(BackgroundLog.of(pid)).doesNotExist();
+ }
+
+ @Test
+ void whyAServiceCannotStartIsOnStderrWithJson() throws Exception {
+ InfraRun infraRun = infraRun();
+ infraRun.jsonOutput = true;
+
+ int exit = infraRun.startInBackground(
+ service("echo 'Could not find a valid Docker environment';
exit 3"), "kafka");
+
+ assertThat(exit).isEqualTo(3);
+ assertThat(printer.getStdout()).isEmpty();
+ assertThat(printer.getStderr()).contains("did not start (exit code 3)")
+ .contains("Could not find a valid Docker environment");
+ }
+
+ @Test
+ void aServiceThatEndsWithZeroBeforeItStartedIsAFailure() throws Exception {
+ int exit = infraRun().startInBackground(service("exit 0"), "kafka");
+
+ assertThat(exit).isEqualTo(CliExitCode.FAILURE);
+ assertThat(printer.getStderr()).contains("did not start (exit code
0)");
+ }
+
+ @Test
+ void aServiceStillStartingIsLeftRunning() throws Exception {
+ InfraRun infraRun = infraRun();
+ infraRun.backgroundWait = 500;
+
+ // such as pulling its container image the first time
+ assertThatThrownBy(() -> infraRun.startInBackground(service("echo
Pulling image; sleep 60"), "kafka"))
+ .isInstanceOf(CliException.class)
+ .hasMessageContaining("is still starting after 500ms")
+ .hasMessageContaining("the log is in " +
BackgroundLog.of(pid()))
+ .extracting(e -> ((CliException)
e).getExitCode()).isEqualTo(CliExitCode.TIMEOUT);
+
assertThat(ProcessHandle.of(pid()).map(ProcessHandle::isAlive)).contains(true);
+ }
+
+ @Test
+ void noWait() throws Exception {
+ InfraRun infraRun = infraRun();
+ infraRun.backgroundWait = 0;
+
+ int exit = infraRun.startInBackground(service("sleep 60"), "kafka");
+
+ assertThat(exit).isZero();
+ long pid = pid();
+ assertThat(printer.getStdout())
+ .contains("Running kafka in background with PID: " + pid)
+ .doesNotContain("waiting")
+ .contains("Log: " + BackgroundLog.of(pid));
+ }
+
+ @Test
+ void theOutputOfAServiceThatIsGoneIsRemoved() throws Exception {
+ writePidFile("kafka", 1234, "{}");
+ Files.writeString(BackgroundLog.of(1234), "Starting service kafka");
+
+ InfraStop command = new InfraStop(new
CamelJBangMain().withPrinter(printer));
+ command.aliveCheck = pid -> false;
+ command.findRunningServices("kafka");
+
+ assertThat(BackgroundLog.of(1234)).doesNotExist();
+ }
+
+ private InfraRun infraRun() {
+ return new InfraRun(new CamelJBangMain().withPrinter(printer));
+ }
+
+ // the pid file of the shell that stands in for the service, named after
its pid ($$)
+ private static String pidFileOfShell(String service) {
+ Path dir = CommandLineHelper.getCamelDir();
+ return "'" + dir + "/infra-" + service + "-'$$'.json'";
+ }
+
+ private static ProcessBuilder service(String script) {
+ return new ProcessBuilder("sh", "-c", script);
+ }
+
+ // the pid of the service, as the command printed it
+ private long pid() {
+ Matcher m = PID.matcher(printer.getStdout() + "\n" +
printer.getStderr());
+ assertThat(m.find()).as("the command printed the pid").isTrue();
+ return Long.parseLong(m.group(1));
+ }
+}
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/test/resources/golden/cli-help.txt
b/dsl/camel-jbang/camel-jbang-core/src/test/resources/golden/cli-help.txt
index 179bacf1baac..b79d56d98e41 100644
--- a/dsl/camel-jbang/camel-jbang-core/src/test/resources/golden/cli-help.txt
+++ b/dsl/camel-jbang/camel-jbang-core/src/test/resources/golden/cli-help.txt
@@ -5014,7 +5014,8 @@ Examples:
== camel infra restart --help
Restarts a running external service
Usage: camel infra restart [-h] [--port=<port>] [--log] [--background]
- [--prop=<prop>] [--kill] [--json] <service>
+ [--background-wait] [--prop=<prop>] [--kill]
+ [--json] <service>
Options:
-h, --help Display this help and exit
@@ -5022,6 +5023,11 @@ Options:
--log Log container output to console
--background Run in the background
Default: false
+ --background-wait How long to wait for the service in the background
+ to start, before returning, in millis or as a
+ duration such as 2m (true waits 60 seconds, false
+ does not wait)
+ Default: 60s
--prop, --property=<prop>
Service properties, ex.
--property=ollama.model=qwen2.5:0.5b
@@ -5035,14 +5041,20 @@ Examples:
== camel infra run --help
Run an external service
-Usage: camel infra run [-h] [--log] [--background] [--port=<port>] [--no-ui]
- [--prop=<prop>] [--json] <service>
+Usage: camel infra run [-h] [--log] [--background] [--background-wait]
+ [--port=<port>] [--no-ui] [--prop=<prop>] [--json]
+ <service>
Options:
-h, --help Display this help and exit
--log Log container output to console
--background Run in the background
Default: false
+ --background-wait How long to wait for the service in the background
+ to start, before returning, in millis or as a
+ duration such as 2m (true waits 60 seconds, false
+ does not wait)
+ Default: 60s
--port=<port> Override the default port for the service
--no-ui Do not start companion UI containers
Default: false