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 09fdd6c54c6a CAMEL-26939: camel-jbang - camel cmd reload --wait
reloads the changed files at once and says how it went (#29882)
09fdd6c54c6a is described below
commit 09fdd6c54c6a4fdb442727979fa819d6b99e2d67
Author: Claus Ibsen <[email protected]>
AuthorDate: Fri Nov 13 23:44:32 2026 +0100
CAMEL-26939: camel-jbang - camel cmd reload --wait reloads the changed
files at once and says how it went (#29882)
## What
CAMEL-26939, a sub-task of CAMEL-26935 (make the Camel CLI faster for AI
agents).
After an edit, an agent waited for the next scan of dev mode (every 2
seconds, 1.1 s on average), and read the log to find out whether the reload
worked. `camel cmd reload` did not help: it reloads the context, which rebuilds
the routes from what was loaded, not from the files.
`camel cmd reload <name> --wait` asks the integration to reload the files
changed since the last scan now, and prints them, or why the reload failed
(exit code 1). With `--json` the outcome is one document:
```
$ camel cmd reload rl1 --wait --json
{"pid":35136,"name":"rl1","status":"reloaded","files":["hello.camel.yaml"]}
$ camel cmd reload rl1 --wait --json
{"pid":35136,"name":"rl1","status":"unchanged","files":[]}
$ camel cmd reload rl1 --wait --json # after a typo in the route
{"pid":35136,"name":"rl1","status":"failed","files":["hello.camel.yaml"],"error":"Unknown
node id: lgo\n in file:hello.camel.yaml, line 8, column 11:\n -
lgo:\n ^\n"}
```
The statuses are the ones of the reload outcome of the MCP write tools
(`reloaded`, `failed`), and `unchanged`.
- `camel-support`: `FileWatcherResourceReloadStrategy.reloadChanged()`
scans and reloads the changed files on the calling thread, under the same lock
as the scan of the watcher, so a file is reloaded once. A file still being
written, such as the one just edited, is waited for (up to five times the
stable timeout). `onReload`, which did nothing, does the same.
- `camel-cli-connector`: the `reload` action with `"changed": true` reloads
through the strategy that scans (`camel run --source-dir` also has a
`RouteOnDemandReloadStrategy`, which only reloads on demand), and answers with
the files and the error. Without dev mode the answer says that the integration
does not watch its files.
- `camel-jbang-core`: `camel cmd reload --wait [--json]` for one
integration. An integration of Camel before 4.24 is told apart before anything
is sent; `--json` without `--wait` is a usage error.
The scan of dev mode stays at 2 seconds (CAMEL-25042: it groups the files
of one save into one reload); `camel_run` of the MCP server keeps its 500 ms.
`camel cmd reload` without `--wait` does as before, except on an
integration whose only reload strategy is the file watcher (no context reload,
such as Spring Boot with `camel.main.routesReloadEnabled`): there it now
reloads the changed files, where it did nothing.
## Tried end to end
The camel-launcher with the three jars of this PR, macOS, JDK 25, `camel
run hello.camel.yaml --dev --background`, and the same with `--source-dir=.`:
- an edit, then `camel cmd reload --wait --json`: `reloaded` in 0.67 s for
the whole command (the CLI starting included), and the log has one reload, on
the connector thread, and the new message right after;
- again: `unchanged`;
- a typo: `failed` with the line and column of the parser, exit code 1.
Found on the way, also on main without this PR: after a failed reload, the
reload of the fixed file fails with `duplicate route id detected hello`, and
the old route keeps running until a restart. The route restored from the last
good content is an in-memory resource whose URI is relative
(`file:hello.camel.yaml`), and the file from disk has an absolute one, so the
next reload does not see they are the same file and loads both. Not changed
here: CAMEL-26943 (`RouteWatcherReloadStrategy`).
## Tests
- `FileScanReloadTest` (camel-core): a reload asked for reloads the changed
files at once, the properties first, and nothing when nothing changed; it waits
for a file just written.
- `LocalCliConnectorFileTransportTest`: the answer with the files, with the
error of a failed reload, and without dev mode.
- `CamelReloadActionTest`, moved to AssertJ: `--wait` sends `changed`,
prints the files, the outcome as JSON, a failed reload is exit code 1 (one JSON
document, or an `ERROR:`), an integration that cannot reload on demand, and
`--json` without `--wait`.
- The reload tests of camel-core, and the tests of `camel-cli-connector`
and `camel-jbang-core` pass.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../apache/camel/support/FileScanReloadTest.java | 31 ++++++
.../support/FileWatcherResourceReloadStrategy.java | 60 +++++++++-
.../modules/ROOT/pages/camel-jbang-running.adoc | 11 ++
.../jbang-commands/camel-jbang-cmd-reload.adoc | 2 +
.../camel/cli/connector/LocalCliConnector.java | 46 +++++++-
.../LocalCliConnectorFileTransportTest.java | 71 ++++++++++++
.../META-INF/camel-jbang-commands-metadata.json | 2 +-
.../core/commands/action/CamelReloadAction.java | 87 ++++++++++++++-
.../commands/action/CamelReloadActionTest.java | 124 ++++++++++++++++++---
.../src/test/resources/golden/cli-help.txt | 8 +-
10 files changed, 418 insertions(+), 24 deletions(-)
diff --git
a/core/camel-core/src/test/java/org/apache/camel/support/FileScanReloadTest.java
b/core/camel-core/src/test/java/org/apache/camel/support/FileScanReloadTest.java
index 349b90dcb930..9e87d4c166fa 100644
---
a/core/camel-core/src/test/java/org/apache/camel/support/FileScanReloadTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/support/FileScanReloadTest.java
@@ -24,6 +24,7 @@ import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.camel.ContextTestSupport;
import org.junit.jupiter.api.AfterEach;
@@ -149,6 +150,36 @@ public class FileScanReloadTest extends ContextTestSupport
{
assertThat(scanNames()).isEmpty();
}
+ @Test
+ public void testAReloadAskedForReloadsTheChangedFilesAtOnce() throws
Exception {
+ // CAMEL-26939: camel cmd reload --wait, right after an edit, does not
wait for the next scan
+ List<String> reloaded = new CopyOnWriteArrayList<>();
+ strategy.setResourceReload((name, resource) -> reloaded.add(new
File(name).getName()));
+ Files.writeString(dir.resolve("shop.yaml"), "one");
+ Files.writeString(dir.resolve("shop.properties"), "a=1");
+
+ assertThat(strategy.reloadChanged()).extracting(f -> new
File(f).getName())
+ .containsExactlyInAnyOrder("shop.yaml", "shop.properties");
+ // the properties first, as when the watcher reloads them
+ assertThat(reloaded).containsExactly("shop.properties", "shop.yaml");
+
+ // nothing changed since
+ assertThat(strategy.reloadChanged()).isEmpty();
+ assertThat(reloaded).hasSize(2);
+ }
+
+ @Test
+ public void testAReloadAskedForWaitsForAFileStillBeingWritten() throws
Exception {
+ List<String> reloaded = new CopyOnWriteArrayList<>();
+ strategy.setResourceReload((name, resource) -> reloaded.add(new
File(name).getName()));
+ strategy.setStableTimeout(300);
+ Files.writeString(dir.resolve("shop.yaml"), "one");
+
+ // just written, so the reload waits until it has settled rather than
say that nothing changed
+ assertThat(strategy.reloadChanged()).extracting(f -> new
File(f).getName()).containsExactly("shop.yaml");
+ assertThat(reloaded).containsExactly("shop.yaml");
+ }
+
@Test
public void testASaveStillBeingWrittenIsLeftForTheNextScan() throws
Exception {
strategy.setStableTimeout(60_000);
diff --git
a/core/camel-support/src/main/java/org/apache/camel/support/FileWatcherResourceReloadStrategy.java
b/core/camel-support/src/main/java/org/apache/camel/support/FileWatcherResourceReloadStrategy.java
index 5739f843dd57..99ea7e375462 100644
---
a/core/camel-support/src/main/java/org/apache/camel/support/FileWatcherResourceReloadStrategy.java
+++
b/core/camel-support/src/main/java/org/apache/camel/support/FileWatcherResourceReloadStrategy.java
@@ -29,10 +29,13 @@ import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
import org.apache.camel.api.management.ManagedAttribute;
import org.apache.camel.api.management.ManagedResource;
@@ -58,7 +61,13 @@ import org.slf4j.LoggerFactory;
public class FileWatcherResourceReloadStrategy extends
ResourceReloadStrategySupport {
private static final Logger LOG =
LoggerFactory.getLogger(FileWatcherResourceReloadStrategy.class);
+ // how many more scans a reload asked for waits for a file still being
written
+ private static final int SETTLE_SCANS = 5;
+ /** One scan and its reload at a time: the watcher's, or one asked for
with {@link #reloadChanged()}. */
+ private final Lock scanLock = new ReentrantLock();
+ /** Whether the last scan left a file still being written for the next
scan. */
+ private boolean settling;
ExecutorService executorService;
WatchFileChangesTask task;
/** The modification time and length of every file of the previous scan,
by path: what a change is measured from. */
@@ -153,9 +162,53 @@ public class FileWatcherResourceReloadStrategy extends
ResourceReloadStrategySup
this.fileFilter = fileFilter;
}
+ /**
+ * Reloads the files changed since the last scan now, see {@link
#reloadChanged()}.
+ */
@Override
public void onReload(Object source) {
- // this implementation uses a watcher to automatic reload
+ reloadChanged();
+ }
+
+ /**
+ * Reloads the files changed since the last scan now, rather than at the
next scan, as the Camel CLI asks for right
+ * after an edit (<tt>camel cmd reload --wait</tt>). A file still being
written, such as the one just edited, is
+ * waited for. The files are reloaded on the calling thread, one scan at a
time with the watcher.
+ *
+ * @return the files that changed, also those that are gone; empty when
nothing changed
+ * @since 4.24
+ */
+ public List<String> reloadChanged() {
+ if (folder == null) {
+ return List.of();
+ }
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ scanLock.lock();
+ try {
+ // the classloader of Camel, as the watcher has it
+ ClassLoader acl = getCamelContext() != null ?
getCamelContext().getApplicationContextClassLoader() : null;
+ if (acl != null) {
+ Thread.currentThread().setContextClassLoader(acl);
+ }
+ Set<File> changed = new LinkedHashSet<>(scan());
+ for (int i = 0; settling && i < SETTLE_SCANS; i++) {
+ try {
+ Thread.sleep(stableTimeout);
+ } catch (InterruptedException e) {
+ // the files scanned so far are reloaded, as the next scan
does not report them again
+ Thread.currentThread().interrupt();
+ break;
+ }
+ changed.addAll(scan());
+ }
+ if (!changed.isEmpty()) {
+ onReloadBatch(new ArrayList<>(changed));
+ }
+ return changed.stream().map(f ->
FileUtil.compactPath(f.getPath())).toList();
+ } finally {
+ scanLock.unlock();
+ Thread.currentThread().setContextClassLoader(cl);
+ }
}
@Override
@@ -213,6 +266,7 @@ public class FileWatcherResourceReloadStrategy extends
ResourceReloadStrategySup
* otherwise be reloaded half-finished.
*/
protected List<File> scan() {
+ settling = false;
List<File> changed = new ArrayList<>();
Set<String> seen = new HashSet<>();
Path root = new File(folder).toPath();
@@ -264,6 +318,7 @@ public class FileWatcherResourceReloadStrategy extends
ResourceReloadStrategySup
// still being written: leave it, and let the next
scan report it. A modification time in the
// future (a clock askew on a network share, a touch
-t) is reported now rather than waited out
seen.remove(name);
+ settling = true;
return FileVisitResult.CONTINUE;
}
known.put(name, new long[] { modified, length });
@@ -365,6 +420,7 @@ public class FileWatcherResourceReloadStrategy extends
ResourceReloadStrategySup
}
LOG.trace("FileReloadStrategy is scanning for file changes
in directory: {}", folder);
+ scanLock.lock();
try {
List<File> changed = scan();
if (!changed.isEmpty()) {
@@ -376,6 +432,8 @@ public class FileWatcherResourceReloadStrategy extends
ResourceReloadStrategySup
// an error such as StackOverflowError has no message:
name it rather than print null
LOG.warn("Error reloading files in directory: {} due
to: {}. This exception is ignored.", folder,
e.getMessage() != null ? e.getMessage() :
e.getClass().getName(), e);
+ } finally {
+ scanLock.unlock();
}
}
} finally {
diff --git a/docs/user-manual/modules/ROOT/pages/camel-jbang-running.adoc
b/docs/user-manual/modules/ROOT/pages/camel-jbang-running.adoc
index 4a53b844d74c..9f8d664c80e3 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-jbang-running.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-jbang-running.adoc
@@ -28,6 +28,17 @@ camel run foo.yaml --dev
--prop=camel.main.routesReloadInterval=500
A shorter interval reloads a change sooner. A longer one groups more of one
save together, such as several files
an editor saves one after the other.
+To reload a change at once, rather than at the next scan, and hear how it
went, use `camel cmd reload --wait`, as an
+AI agent does after it edits a file. It reloads the files changed since the
last scan, and prints them, or why the
+reload failed (exit code 1). With `--json` the outcome is one JSON document,
with the status `reloaded`, `unchanged`
+or `failed`:
+
+[source,bash]
+----
+$ camel cmd reload foo --wait --json
+{"pid":35136,"name":"foo","status":"reloaded","files":["foo.yaml"]}
+----
+
`camel dev` is a shortcut for `camel run --dev`, and without files it runs the
current folder
(as `--source-dir=.`):
diff --git
a/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-cmd-reload.adoc
b/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-cmd-reload.adoc
index d5914d127798..d64318005a87 100644
---
a/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-cmd-reload.adoc
+++
b/docs/user-manual/modules/ROOT/pages/jbang-commands/camel-jbang-cmd-reload.adoc
@@ -19,7 +19,9 @@ camel cmd reload [options]
[cols="2,5,1,2",options="header"]
|===
| Option | Description | Default | Type
+| `--json` | The outcome of --wait as JSON | | boolean
| `--timeout` | How long to wait for the integration to answer, in millis or
as a duration such as 30s | 10000 | long
+| `--wait` | Reload the files changed since the last scan of dev mode now, and
wait for the outcome: the files reloaded, or why the reload failed | | boolean
| `-h,--help` | Display this help and exit | | boolean
|===
diff --git
a/dsl/camel-cli-connector/src/main/java/org/apache/camel/cli/connector/LocalCliConnector.java
b/dsl/camel-cli-connector/src/main/java/org/apache/camel/cli/connector/LocalCliConnector.java
index ef4d34f672d2..d63bc12a0587 100644
---
a/dsl/camel-cli-connector/src/main/java/org/apache/camel/cli/connector/LocalCliConnector.java
+++
b/dsl/camel-cli-connector/src/main/java/org/apache/camel/cli/connector/LocalCliConnector.java
@@ -86,6 +86,7 @@ import org.apache.camel.spi.RoutesLoader;
import org.apache.camel.spi.RuntimeEndpointRegistry;
import org.apache.camel.spi.ShutdownPrepared;
import org.apache.camel.spi.annotations.PeriodicTask;
+import org.apache.camel.support.FileWatcherResourceReloadStrategy;
import org.apache.camel.support.LoadOnDemandReloadStrategy;
import org.apache.camel.support.MessageHelper;
import org.apache.camel.support.PatternHelper;
@@ -383,7 +384,7 @@ public class LocalCliConnector extends ServiceSupport
} else if ("load".equals(action)) {
doActionLoadTask(root);
} else if ("reload".equals(action)) {
- doActionReloadTask();
+ doActionReloadTask(root);
} else if ("debug".equals(action)) {
doActionDebugTask(root);
} else if ("reset-stats".equals(action)) {
@@ -1411,7 +1412,11 @@ public class LocalCliConnector extends ServiceSupport
}
}
- private void doActionReloadTask() {
+ private void doActionReloadTask(JsonObject root) throws IOException {
+ if (root.getBooleanOrDefault("changed", false)) {
+ doActionReloadChangedTask();
+ return;
+ }
ContextReloadStrategy cr =
camelContext.hasService(ContextReloadStrategy.class);
if (cr != null) {
cr.onReload("Camel CLI");
@@ -1423,6 +1428,43 @@ public class LocalCliConnector extends ServiceSupport
}
}
+ /**
+ * Reloads the files changed since the last scan of dev mode now, and
answers with them and the error when the
+ * reload failed (camel cmd reload --wait, CAMEL-26939). A context reload
rebuilds the routes from what was loaded,
+ * so it does not load an edit.
+ */
+ private void doActionReloadChangedTask() throws IOException {
+ FileWatcherResourceReloadStrategy watcher = fileWatcher();
+ if (watcher == null) {
+ reportError("The integration does not watch its files, as it does
not run in dev mode: restart it to load"
+ + " what changed");
+ return;
+ }
+ int failed = watcher.getFailedCounter();
+ List<String> files = watcher.reloadChanged();
+ JsonObject result = new JsonObject();
+ result.put("files", new JsonArray(files));
+ writeOutput(result);
+ if (watcher.getFailedCounter() > failed) {
+ Exception cause = watcher.getLastError();
+ reportError(cause != null && cause.getMessage() != null ?
cause.getMessage() : "Reloading failed");
+ }
+ }
+
+ /**
+ * The strategy that watches the files: the one that scans them, rather
than the one that camel run --source-dir
+ * also has, which only reloads on demand.
+ */
+ private FileWatcherResourceReloadStrategy fileWatcher() {
+ FileWatcherResourceReloadStrategy answer = null;
+ for (ResourceReloadStrategy rr :
camelContext.hasServices(ResourceReloadStrategy.class)) {
+ if (rr instanceof FileWatcherResourceReloadStrategy watcher &&
(answer == null || watcher.isRunning())) {
+ answer = watcher;
+ }
+ }
+ return answer;
+ }
+
private void doActionLoggerTask(JsonObject root) {
try {
String command = root.getString("command");
diff --git
a/dsl/camel-cli-connector/src/test/java/org/apache/camel/cli/connector/LocalCliConnectorFileTransportTest.java
b/dsl/camel-cli-connector/src/test/java/org/apache/camel/cli/connector/LocalCliConnectorFileTransportTest.java
index bb273620bab4..a224657e272d 100644
---
a/dsl/camel-cli-connector/src/test/java/org/apache/camel/cli/connector/LocalCliConnectorFileTransportTest.java
+++
b/dsl/camel-cli-connector/src/test/java/org/apache/camel/cli/connector/LocalCliConnectorFileTransportTest.java
@@ -24,6 +24,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
+import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
@@ -32,6 +33,8 @@ import org.apache.camel.ServiceStatus;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.console.DevConsoleRegistry;
import org.apache.camel.spi.CliConnectorFactory;
+import org.apache.camel.spi.ResourceReload;
+import org.apache.camel.support.FileWatcherResourceReloadStrategy;
import org.apache.camel.test.junit6.CamelTestSupport;
import org.apache.camel.util.json.JsonArray;
import org.apache.camel.util.json.JsonObject;
@@ -300,6 +303,55 @@ class LocalCliConnectorFileTransportTest extends
CamelTestSupport {
.untilAsserted(() -> assertThat(sigterms).hasValue(1));
}
+ @Test
+ void reloadOfTheChangedFilesAnswersWithThem() throws Exception {
+ // CAMEL-26939: camel cmd reload --wait, right after an edit
+ List<String> reloaded = new CopyOnWriteArrayList<>();
+ Path sources = watchSources((name, resource) -> reloaded.add(new
File(name).getName()));
+ startConnector();
+ Files.writeString(sources.resolve("orders.yaml"), "- route: {}");
+
+ writeAction(reloadChanged(), "r1");
+
+ JsonArray files = awaitJson(file(PID +
"-output-r1.json")).getCollection("files");
+ assertThat(files).hasSize(1);
+ assertThat(reloaded).containsExactly("orders.yaml");
+
+ // nothing changed since
+ writeAction(reloadChanged(), "r2");
+ JsonArray none = awaitJson(file(PID +
"-output-r2.json")).getCollection("files");
+ assertThat(none).isEmpty();
+ }
+
+ @Test
+ void reloadOfTheChangedFilesAnswersWithTheError() throws Exception {
+ Path sources = watchSources((name, resource) -> {
+ throw new IllegalArgumentException("Unknown step: frm");
+ });
+ startConnector();
+ Files.writeString(sources.resolve("orders.yaml"), "- route: {}");
+
+ writeAction(reloadChanged(), "r1");
+
+ JsonObject reply = awaitJson(file(PID + "-output-r1.json"));
+ assertThat(reply.getString("status")).isEqualTo("failed");
+ assertThat(reply.getString("error")).isEqualTo("Unknown step: frm");
+ JsonObject result = reply.getMap("result");
+ JsonArray files = result.getCollection("files");
+ assertThat(files).hasSize(1);
+ }
+
+ @Test
+ void reloadOfTheChangedFilesNeedsDevMode() {
+ startConnector();
+
+ writeAction(reloadChanged(), "r1");
+
+ JsonObject reply = awaitJson(file(PID + "-output-r1.json"));
+ assertThat(reply.getString("status")).isEqualTo("failed");
+ assertThat(reply.getString("error")).contains("does not watch its
files");
+ }
+
@Test
void stopDeletesTheFiles() {
startConnector();
@@ -323,6 +375,25 @@ class LocalCliConnectorFileTransportTest extends
CamelTestSupport {
connector.start();
}
+ /**
+ * Watches a folder of sources as dev mode does, without the scan of its
own, so only the reload asked for reloads.
+ */
+ private Path watchSources(ResourceReload listener) throws Exception {
+ Path sources = Files.createDirectories(home.resolve("app"));
+ FileWatcherResourceReloadStrategy watcher = new
FileWatcherResourceReloadStrategy(sources.toString());
+ watcher.setScheduler(false);
+ watcher.setStableTimeout(0);
+ watcher.setResourceReload(listener);
+ context.addService(watcher);
+ return sources;
+ }
+
+ private static JsonObject reloadChanged() {
+ JsonObject jo = action("reload");
+ jo.put("changed", true);
+ return jo;
+ }
+
private File file(String name) {
return new File(dir, name);
}
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 7912e6878834..224c88ad7ab6 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
@@ -3,7 +3,7 @@
{ "name": "ask", "fullName": "ask", "description": "Ask a question about a
running Camel application using AI", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.Ask", "options": [ { "names":
"--api-key", "description": "API key. Also reads ANTHROPIC_API_KEY,
OPENAI_API_KEY, WATSONX_APIKEY, or LLM_API_KEY env vars", "javaType":
"java.lang.String", "type": "string" }, { "names": "--api-type", "description":
"API type: 'ollama', 'openai', 'anthropic', or 'watsonx'", "javaType": [...]
{ "name": "bind", "fullName": "bind", "description": "DEPRECATED: Bind
source and sink Kamelets as a new Camel integration", "deprecated": true,
"sourceClass": "org.apache.camel.dsl.jbang.core.commands.bind.Bind", "options":
[ { "names": "--error-handler", "description": "Add error handler
(none|log|sink:<endpoint>). Sink endpoints are expected in the format
\"[[apigroup\/]version:]kind:[namespace\/]name\", plain Camel URIs or Kamelet
name.", "javaType": "java.lang.String", "type": " [...]
{ "name": "catalog", "fullName": "catalog", "description": "List artifacts
from Camel Catalog", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.catalog.CatalogCommand", "options": [
{ "names": "-h,--help", "description": "Display this help and exit",
"javaType": "boolean", "type": "boolean" } ], "subcommands": [ { "name":
"component", "fullName": "catalog component", "description": "List components
from the Camel Catalog", "sourceClass": "org.apache.camel.dsl.jbang.core.comm
[...]
- { "name": "cmd", "fullName": "cmd", "description": "Performs commands in
the running Camel integrations, such as start\/stop route, or change logging
levels.", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.action.CamelAction", "options": [ {
"names": "-h,--help", "description": "Display this help and exit", "javaType":
"boolean", "type": "boolean" } ], "subcommands": [ { "name": "browse",
"fullName": "cmd browse", "description": "Browse pending messages on
endpoints", "sou [...]
+ { "name": "cmd", "fullName": "cmd", "description": "Performs commands in
the running Camel integrations, such as start\/stop route, or change logging
levels.", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.action.CamelAction", "options": [ {
"names": "-h,--help", "description": "Display this help and exit", "javaType":
"boolean", "type": "boolean" } ], "subcommands": [ { "name": "browse",
"fullName": "cmd browse", "description": "Browse pending messages on
endpoints", "sou [...]
{ "name": "completion", "fullName": "completion", "description": "Generate
completion script for bash\/zsh", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.Complete", "options": [ { "names":
"-h,--help", "description": "Display this help and exit", "javaType":
"boolean", "type": "boolean" } ] },
{ "name": "config", "fullName": "config", "description": "Get and set user
configuration values", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.config.ConfigCommand", "options": [ {
"names": "-h,--help", "description": "Display this help and exit", "javaType":
"boolean", "type": "boolean" } ], "subcommands": [ { "name": "get", "fullName":
"config get", "description": "Display user configuration value", "sourceClass":
"org.apache.camel.dsl.jbang.core.commands.config.ConfigG [...]
{ "name": "debug", "fullName": "debug", "description": "Debug local Camel
integration", "sourceClass": "org.apache.camel.dsl.jbang.core.commands.Debug",
"options": [ { "names": "--ago", "description": "Use ago instead of yyyy-MM-dd
HH:mm:ss in timestamp.", "javaType": "boolean", "type": "boolean" }, { "names":
"--background", "description": "Run in the background", "defaultValue":
"false", "javaType": "boolean", "type": "boolean" }, { "names":
"--background-wait", "description": "How [...]
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReloadAction.java
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReloadAction.java
index d5402e86d3f5..6a2b1d3ad8b3 100644
---
a/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReloadAction.java
+++
b/dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReloadAction.java
@@ -19,17 +19,36 @@ package org.apache.camel.dsl.jbang.core.commands.action;
import org.aesh.command.CommandDefinition;
import org.aesh.command.option.Argument;
import org.aesh.command.option.Mixin;
+import org.aesh.command.option.Option;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
+import org.apache.camel.dsl.jbang.core.common.ActionClient;
+import org.apache.camel.dsl.jbang.core.common.ActionClient.ActionResult;
+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.JsonOutput;
+import org.apache.camel.dsl.jbang.core.common.ProcessFinder.CamelProcess;
+import org.apache.camel.util.json.JsonArray;
+import org.apache.camel.util.json.JsonObject;
@CommandDefinition(name = "reload", description = "Trigger reloading Camel",
generateHelp = true,
footer = {
"Examples:",
- " camel cmd reload" })
+ " camel cmd reload",
+ " camel cmd reload myapp --wait",
+ " camel cmd reload myapp --wait --json" })
public class CamelReloadAction extends ActionBaseCommand {
@Argument(description = "Name or pid of running Camel integration.
(default selects all)")
String name = "*";
+ @Option(name = "wait", hasValue = false,
+ description = "Reload the files changed since the last scan of dev
mode now, and wait for the outcome: the"
+ + " files reloaded, or why the reload failed")
+ boolean waitForOutcome;
+
+ @Option(name = "json", hasValue = false, description = "The outcome of
--wait as JSON")
+ boolean jsonOutput;
+
@Mixin
ActionTimeoutMixin timeoutOption;
@@ -39,7 +58,71 @@ public class CamelReloadAction extends ActionBaseCommand {
@Override
public Integer doCall() throws Exception {
- return sendAction(findProcesses(name), "reload", null);
+ if (!waitForOutcome) {
+ if (jsonOutput) {
+ throw CliException.usage("--json is the outcome of --wait: use
both");
+ }
+ return sendAction(findProcesses(name), "reload", null);
+ }
+ CamelProcess process = findOne(name);
+ String version = process.camelVersion();
+ if (version != null && !ActionClient.isAtLeast(version, 4, 24)) {
+ throw CliException.failure("The integration " + process.name() + "
runs Camel " + version
+ + ", which reloads the changed files at
its next scan only: --wait needs Camel"
+ + " 4.24 or later");
+ }
+ // a context reload rebuilds the routes from what was loaded: the
changed files are what an edit needs
+ ActionResult result = ActionClient.execute(process, "reload", o ->
o.put("changed", true), timeout());
+ JsonObject outcome = outcome(process, result);
+ boolean failed = "failed".equals(outcome.getString("status"));
+ if (jsonOutput) {
+ JsonOutput.print(printer(), outcome);
+ return failed ? CliExitCode.FAILURE : CliExitCode.OK;
+ }
+ if (failed) {
+ throw CliException.failure("Reloading " + process.name() + "
failed: " + outcome.getString("error"));
+ }
+ JsonArray files = outcome.getCollection("files");
+ if (files.isEmpty()) {
+ printer().println("No files of " + process.name() + " changed
since they were last reloaded");
+ } else {
+ printer().println("Reloaded " + process.name() + ":");
+ for (Object file : files) {
+ printer().println(" " + file);
+ }
+ }
+ return CliExitCode.OK;
+ }
+
+ /**
+ * The outcome of a reload of the changed files: <tt>reloaded</tt> with
the files, <tt>unchanged</tt> when no file
+ * changed, or <tt>failed</tt> with the error and the files whose reload
failed.
+ *
+ * @throws CliException when the integration did not answer in time, or
stopped (see {@link ActionResult#orThrow()})
+ */
+ static JsonObject outcome(CamelProcess process, ActionResult result) {
+ JsonObject outcome = new JsonObject();
+ outcome.put("pid", process.pid());
+ outcome.put("name", process.name());
+ if (result.status() == ActionClient.Status.ERROR &&
!result.isNotFound()) {
+ JsonObject partial = result.reply() != null &&
result.reply().get("result") instanceof JsonObject jo ? jo : null;
+ outcome.put("status", "failed");
+ outcome.put("files", partial != null &&
partial.getCollection("files") != null
+ ? partial.getCollection("files") : new JsonArray());
+ outcome.put("error", result.error());
+ return outcome;
+ }
+ JsonObject reply = result.orThrow();
+ JsonArray files = reply != null ? reply.getCollection("files") : null;
+ if (files == null) {
+ // a context reload, by a connector of a Camel before this option
+ throw CliException.failure("The integration " + process.name()
+ + " does not reload the changed files
on demand: it reloads them at its next"
+ + " scan");
+ }
+ outcome.put("status", files.isEmpty() ? "unchanged" : "reloaded");
+ outcome.put("files", files);
+ return outcome;
}
}
diff --git
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReloadActionTest.java
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReloadActionTest.java
index 152b6f437504..980d32f97e6a 100644
---
a/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReloadActionTest.java
+++
b/dsl/camel-jbang/camel-jbang-core/src/test/java/org/apache/camel/dsl/jbang/core/commands/action/CamelReloadActionTest.java
@@ -19,15 +19,15 @@ package org.apache.camel.dsl.jbang.core.commands.action;
import org.apache.camel.dsl.jbang.core.commands.CamelJBangMain;
import org.apache.camel.dsl.jbang.core.common.CliException;
import org.apache.camel.dsl.jbang.core.common.CliExitCode;
+import org.apache.camel.util.json.JsonArray;
import org.apache.camel.util.json.JsonObject;
+import org.apache.camel.util.json.Jsoner;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
@ExtendWith(MockitoExtension.class)
class CamelReloadActionTest extends ActionCommandTestSupport {
@@ -36,28 +36,118 @@ class CamelReloadActionTest extends
ActionCommandTestSupport {
void testWritesReloadActionForMatchingName() throws Exception {
writeStatusFile(TEST_PID, "myApp");
- CamelReloadAction command = new CamelReloadAction(new
CamelJBangMain().withPrinter(printer));
- command.name = "myApp";
-
- int exit = callWithSingleProcess(command);
+ int exit = callWithSingleProcess(command("myApp"));
- assertEquals(0, exit);
+ assertThat(exit).isZero();
JsonObject action = readActionFile(TEST_PID);
- assertNotNull(action, "action file should be written for the matched
process");
- assertEquals("reload", action.getString("action"));
+ assertThat(action).as("action file should be written for the matched
process").isNotNull();
+ assertThat(action.getString("action")).isEqualTo("reload");
+ assertThat(action.containsKey("changed")).isFalse();
}
@Test
void testNoActionWhenNameDoesNotMatch() throws Exception {
writeStatusFile(TEST_PID, "myApp");
+ CamelReloadAction command = command("doesNotExist");
- CamelReloadAction command = new CamelReloadAction(new
CamelJBangMain().withPrinter(printer));
- command.name = "doesNotExist";
+ assertThatThrownBy(() ->
callWithSingleProcess(command)).isInstanceOf(CliException.class)
+ .hasMessage("No running Camel integration matches:
doesNotExist")
+ .extracting(e -> ((CliException)
e).getExitCode()).isEqualTo(CliExitCode.NOT_FOUND);
+ assertThat(readActionFile(TEST_PID)).as("no action file should be
written when no process matches").isNull();
+ }
+
+ @Test
+ void waitReloadsTheChangedFilesAndPrintsThem() throws Exception {
+ // CAMEL-26939: right after an edit, an agent reloads it at once and
hears what came of it
+ writeStatusFile(TEST_PID, "myApp");
+ CamelReloadAction command = command("myApp");
+ command.waitForOutcome = true;
+
+ int exit = callWithResponse(command,
json("{\"files\":[\"routes/orders.yaml\"]}"));
+
+ assertThat(exit).isEqualTo(CliExitCode.OK);
+ assertThat(readActionFile(TEST_PID).getBoolean("changed")).isTrue();
+ assertThat(printer.getStdout()).contains("Reloaded myApp:",
"routes/orders.yaml");
+ }
+
+ @Test
+ void waitSaysWhenNothingChanged() throws Exception {
+ writeStatusFile(TEST_PID, "myApp");
+ CamelReloadAction command = command("myApp");
+ command.waitForOutcome = true;
+ command.jsonOutput = true;
+
+ int exit = callWithResponse(command, json("{\"files\":[]}"));
+
+ assertThat(exit).isEqualTo(CliExitCode.OK);
+ JsonObject outcome = json(printer.getStdout());
+ assertThat(outcome.getLong("pid")).isEqualTo(TEST_PID);
+ assertThat(outcome.getString("name")).isEqualTo("myApp");
+ assertThat(outcome.getString("status")).isEqualTo("unchanged");
+ JsonArray files = outcome.getCollection("files");
+ assertThat(files).isEmpty();
+ }
+
+ @Test
+ void aFailedReloadIsTheOutcomeWithExitCodeOne() throws Exception {
+ writeStatusFile(TEST_PID, "myApp");
+ JsonObject failed = json("{\"status\":\"failed\",\"error\":\"Unknown
step: frm\","
+ +
"\"result\":{\"files\":[\"routes/orders.yaml\"]}}");
+ CamelReloadAction command = command("myApp");
+ command.waitForOutcome = true;
+ command.jsonOutput = true;
+
+ int exit = callWithResponse(command, failed);
+
+ assertThat(exit).isEqualTo(CliExitCode.FAILURE);
+ // one document: the outcome, with the files whose reload failed
+ JsonObject outcome = json(printer.getStdout());
+ assertThat(outcome.getString("status")).isEqualTo("failed");
+ assertThat(outcome.getString("error")).isEqualTo("Unknown step: frm");
+ JsonArray files = outcome.getCollection("files");
+ assertThat(files).containsExactly("routes/orders.yaml");
+
+ CamelReloadAction text = command("myApp");
+ text.waitForOutcome = true;
+ assertThatThrownBy(() -> callWithResponse(text,
failed)).isInstanceOf(CliException.class)
+ .hasMessage("Reloading myApp failed: Unknown step: frm")
+ .extracting(e -> ((CliException)
e).getExitCode()).isEqualTo(CliExitCode.FAILURE);
+ }
+
+ @Test
+ void waitNeedsAnIntegrationThatReloadsOnDemand() throws Exception {
+ writeStatusFile(TEST_PID,
json("{\"context\":{\"name\":\"myApp\",\"version\":\"4.23.0\"}}"));
+ CamelReloadAction command = command("myApp");
+ command.waitForOutcome = true;
+
+ assertThatThrownBy(() ->
callWithSingleProcess(command)).isInstanceOf(CliException.class)
+ .hasMessageContaining("runs Camel
4.23.0").hasMessageContaining("--wait needs Camel 4.24 or later");
+ assertThat(readActionFile(TEST_PID)).isNull();
+
+ // a connector that does not know the option reloads the context, and
answers without the files
+ writeStatusFile(TEST_PID, "myApp");
+ assertThatThrownBy(() -> callWithResponse(command,
json("{\"status\":\"success\"}")))
+ .isInstanceOf(CliException.class).hasMessageContaining("does
not reload the changed files on demand");
+ }
+
+ @Test
+ void jsonGoesWithWait() throws Exception {
+ writeStatusFile(TEST_PID, "myApp");
+ CamelReloadAction command = command("myApp");
+ command.jsonOutput = true;
- CliException e = assertThrows(CliException.class, () ->
callWithSingleProcess(command));
+ assertThatThrownBy(() ->
callWithSingleProcess(command)).isInstanceOf(CliException.class)
+ .extracting(e -> ((CliException)
e).getExitCode()).isEqualTo(CliExitCode.USAGE);
+ assertThat(readActionFile(TEST_PID)).isNull();
+ }
+
+ private CamelReloadAction command(String name) {
+ CamelReloadAction command = new CamelReloadAction(new
CamelJBangMain().withPrinter(printer));
+ command.name = name;
+ return command;
+ }
- assertEquals(CliExitCode.NOT_FOUND, e.getExitCode());
- assertEquals("No running Camel integration matches: doesNotExist",
e.getMessage());
- assertNull(readActionFile(TEST_PID), "no action file should be written
when no process matches");
+ private static JsonObject json(String text) {
+ return Jsoner.deserialize(text.trim(), (JsonObject) null);
}
}
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 bff8a628efdf..d08fe9e29773 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
@@ -1368,10 +1368,14 @@ Examples:
== camel cmd reload --help
Trigger reloading Camel
-Usage: camel cmd reload [-h] [--timeout=<timeout>] [<name>]
+Usage: camel cmd reload [-h] [--wait] [--json] [--timeout=<timeout>] [<name>]
Options:
-h, --help Display this help and exit
+ --wait Reload the files changed since the last scan of dev
+ mode now, and wait for the outcome: the files
+ reloaded, or why the reload failed
+ --json The outcome of --wait as JSON
--timeout=<timeout> How long to wait for the integration to answer, in
millis or as a duration such as 30s
Default: 10000
@@ -1380,6 +1384,8 @@ Options:
Examples:
camel cmd reload
+ camel cmd reload myapp --wait
+ camel cmd reload myapp --wait --json
== camel cmd reset-stats --help
Reset performance statistics