diff --git a/CHANGELOG.md b/CHANGELOG.md index df95979db..f99c8ca1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -67,6 +67,10 @@ release that first shipped the module. ### Documented +- **`RecoverBuildQueue` recovers from two coordinator crashes.** The Java + example reattaches to a worker by pane ID and commits one artifact per + logical job across attempts. (#272) + - **The Kotlin and Scala quick starts now run as standalone programs.** Each includes its build file and starts a private tmux session using the published libraries. (#203) diff --git a/examples/README.md b/examples/README.md index 443ef4484..107172693 100644 --- a/examples/README.md +++ b/examples/README.md @@ -9,6 +9,7 @@ programs with a `main`, short enough to read in one go and real enough to run. | --- | --- | | [`BuildAWorkspace`](src/main/java/io/github/libtmux/examples/BuildAWorkspace.java) | making a session, a window, a split, and choosing a layout | | [`FindPanesRunning`](src/main/java/io/github/libtmux/examples/FindPanesRunning.java) | typed filters over a capture, without asking tmux twice | +| [`RecoverBuildQueue`](#recover-a-build-after-a-crash) | reattaching to a worker and publishing a job once after a coordinator restart | | [`WatchPaneOutput`](src/main/java/io/github/libtmux/examples/WatchPaneOutput.java) | control mode: reading `%output` as tmux pushes it | | [`WatchWhatChanges`](src/main/java/io/github/libtmux/examples/WatchWhatChanges.java) | control mode: typed notifications as the server changes | | [`RunACommand`](src/main/java/io/github/libtmux/examples/RunACommand.java) | running a command to its exit status, not reading the screen | @@ -49,6 +50,34 @@ $ java -cp examples/build/classes/java/main:libtmux/build/classes/java/main \ The Scala programs take the tmux executable, socket path and configuration file as their arguments. The Cats programs run their `IO` in `main`. +## Recover a build after a crash + +[`RecoverBuildQueue.java`](src/main/java/io/github/libtmux/examples/RecoverBuildQueue.java) +starts a private tmux server and runs its coordinators in separate JVMs. +Run from the checkout on JDK 25 or newer with tmux on `PATH` and a local +filesystem that supports hard links. + +```console +$ ./gradlew :examples:compileJava +``` + +```console +$ java -cp examples/build/classes/java/main:libtmux/build/classes/java/main \ + io.github.libtmux.examples.RecoverBuildQueue +``` + +The first coordinator stops with a worker still in its pane. The second opens +the same socket and shows the same pane ID and process ID. It lets the worker +finish, checks the completed file, and publishes it before stopping in turn. + +The third coordinator runs a fresh attempt for the same job. A hard link from +the completed file to the logical job's publication path creates that path only +once. The example prints `Published app-release: 1`. + +Pass `--naive` after the class name to replace the commit with an append. +Retrying after a successful append produces `Published app-release: 2`. +The owner closes the private server and removes the example files in both runs. + ## Next - [`libtmux`](../libtmux/) ยท [Getting started](../docs/guide/getting-started.md) diff --git a/examples/src/main/java/io/github/libtmux/examples/RecoverBuildQueue.java b/examples/src/main/java/io/github/libtmux/examples/RecoverBuildQueue.java new file mode 100644 index 000000000..4d02746f0 --- /dev/null +++ b/examples/src/main/java/io/github/libtmux/examples/RecoverBuildQueue.java @@ -0,0 +1,182 @@ +package io.github.libtmux.examples; + +import io.github.libtmux.Pane; +import io.github.libtmux.PaneId; +import io.github.libtmux.Server; +import io.github.libtmux.ServerConfig; +import io.github.libtmux.ServerEndpoint; +import io.github.libtmux.ServerLaunch; +import io.github.libtmux.WakeReason; +import java.io.IOException; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** Recovers a build queue on the same tmux socket after two abrupt coordinator exits. */ +public final class RecoverBuildQueue { + + private static final String JOB = "app-release"; + private static final String FIRST = "attempt-1"; + private static final String RETRY = "attempt-2"; + private static final String ARTIFACT = "ARTIFACT"; + private static final int BEFORE_PUBLISH = 47; + private static final int AFTER_PUBLISH = 48; + private static final Path DEV_ROOT = Path.of("/tmp/libtmux-java-dev"); + private static final Path TEST_ROOT = Path.of("/tmp/libtmux-java-test"); + private static final String WORKER = """ + IFS= read -r request && [ "$request" = build ] && + exec tr '[:lower:]' '[:upper:]' < source.txt > "$1" + """; + + private RecoverBuildQueue() {} + + public static void main(String[] args) throws IOException, InterruptedException { + if (args.length > 0 && args[0].equals("coordinator")) { + coordinate(args[1], Path.of(args[2]), underProjectRoot(Path.of(args[3])), Boolean.parseBoolean(args[4])); + return; + } + boolean naive = args.length > 0 && args[0].equals("--naive"); + Path root = args.length < 2 ? DEV_ROOT : underProjectRoot(Path.of(args[1])); + Path work = Files.createTempDirectory(Files.createDirectories(root), "queue-"); + try (Server owner = Server.start(ServerLaunch.builder().root(root).build())) { + owner.globalOptions().set("remain-on-exit", "on"); + Files.writeString(work.resolve("source.txt"), "artifact\n"); + var socket = (ServerEndpoint.SocketPath) owner.config().endpoint(); + runCoordinator("start", socket.path(), work, naive, BEFORE_PUBLISH); + if (Files.exists(work.resolve(JOB))) { + throw new IllegalStateException("Published before the worker was released"); + } + System.out.println("Coordinator stopped before publication"); + + runCoordinator("publish", socket.path(), work, naive, AFTER_PUBLISH); + if (!Files.readString(work.resolve(JOB)).equals(ARTIFACT + "\n")) { + throw new IllegalStateException("The publication did not survive the coordinator"); + } + System.out.println("Coordinator stopped after publication"); + + runCoordinator("retry", socket.path(), work, naive, 0); + List publications = Files.readAllLines(work.resolve(JOB)); + if (publications.size() != (naive ? 2 : 1) || !publications.stream().allMatch(ARTIFACT::equals)) { + throw new IllegalStateException("Unexpected publications: " + publications); + } + if (!naive && !Files.isSameFile(work.resolve(JOB), work.resolve(FIRST))) { + throw new IllegalStateException("Retry replaced the first publication"); + } + System.out.println("Published " + JOB + ": " + publications.size()); + } finally { + try (var files = Files.list(work)) { + for (Path file : files.toList()) { + Files.delete(file); + } + } + Files.delete(work); + } + } + + private static void coordinate(String stage, Path socket, Path work, boolean naive) + throws IOException, InterruptedException { + var config = ServerConfig.builder() + .endpoint(ServerEndpoint.socketPath(underProjectRoot(socket))) + .build(); + try (Server server = Server.open(config)) { + Path saved = work.resolve("worker"); + switch (stage) { + case "start" -> { + Pane pane = startWorker(server, work, FIRST); + Files.write(saved, List.of(pane.id().value(), identity(pane))); + Runtime.getRuntime().halt(BEFORE_PUBLISH); + } + case "publish" -> { + List worker = Files.readAllLines(saved); + Pane pane = server.pane(new PaneId(worker.getFirst())).orElseThrow(); + if (!identity(pane).equals(worker.get(1))) { + throw new IllegalStateException("Original worker is gone"); + } + System.out.println("Reattached " + FIRST + " pane " + pane.id() + " pid " + + pane.pid().orElseThrow()); + completeAndPublish(pane, work, FIRST, naive); + Runtime.getRuntime().halt(AFTER_PUBLISH); + } + case "retry" -> completeAndPublish(startWorker(server, work, RETRY), work, RETRY, naive); + default -> throw new IllegalArgumentException("Unknown coordinator stage " + stage); + } + } + } + + private static Pane startWorker(Server server, Path work, String attempt) { + Pane pane = server.newSession(s -> s.named(attempt).in(work).running("sh", "-c", WORKER, "worker", attempt)) + .activePane() + .orElseThrow(); + System.out.println("Started " + attempt + " pane " + pane.id() + " pid " + + pane.pid().orElseThrow()); + return pane; + } + + private static String identity(Pane pane) { + return pane.expand("#{pid}:#{start_time}:#{pane_pid}"); + } + + private static void completeAndPublish(Pane pane, Path work, String attempt, boolean naive) + throws IOException, InterruptedException { + pane.sendLine("build"); + if (pane.await(Pane::dead, Duration.ofSeconds(5)) != WakeReason.SIGNALLED) { + throw new IllegalStateException(attempt + " did not exit"); + } + Path candidate = work.resolve(attempt); + String completed = Files.readString(candidate); + if (!completed.equals(ARTIFACT + "\n")) { + throw new IllegalStateException(attempt + " did not produce the expected artifact"); + } + Path release = work.resolve(JOB); + if (naive) { + Files.writeString(release, completed, StandardOpenOption.CREATE, StandardOpenOption.APPEND); + } else { + try { + Files.createLink(release, candidate); + } catch (FileAlreadyExistsException committed) { + // All attempts publish this job under the same name. + } + } + } + + private static void runCoordinator(String stage, Path socket, Path work, boolean naive, int expectedExit) + throws IOException, InterruptedException { + Process coordinator = new ProcessBuilder( + Path.of(System.getProperty("java.home"), "bin", "java").toString(), + "-cp", + System.getProperty("java.class.path"), + RecoverBuildQueue.class.getName(), + "coordinator", + stage, + socket.toString(), + work.toString(), + Boolean.toString(naive)) + .inheritIO() + .start(); + try { + if (!coordinator.waitFor(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Coordinator stage " + stage + " did not exit in 15 seconds"); + } + if (coordinator.exitValue() != expectedExit) { + throw new IllegalStateException("Coordinator stage " + stage + " exited " + coordinator.exitValue() + + ", expected " + expectedExit); + } + } finally { + if (coordinator.isAlive()) { + coordinator.destroyForcibly().onExit().join(); + } + } + } + + private static Path underProjectRoot(Path path) { + Path exact = path.toAbsolutePath().normalize(); + if (!exact.startsWith(DEV_ROOT) && !exact.startsWith(TEST_ROOT)) { + throw new IllegalArgumentException("Choose a path under " + DEV_ROOT + " or " + TEST_ROOT); + } + return exact; + } +} diff --git a/examples/src/test/java/io/github/libtmux/examples/MainsTest.java b/examples/src/test/java/io/github/libtmux/examples/MainsTest.java index a2156c003..dc8e265ec 100644 --- a/examples/src/test/java/io/github/libtmux/examples/MainsTest.java +++ b/examples/src/test/java/io/github/libtmux/examples/MainsTest.java @@ -23,6 +23,8 @@ import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** * Every example's own {@code main}, in its own JVM, as a reader would run it. @@ -45,6 +47,7 @@ void everyExampleIsLaunched() throws IOException { List.of( "BuildAWorkspace", "FindPanesRunning", + "RecoverBuildQueue", "RunACommand", "ServeTmuxOverMcp", "WatchPaneOutput", @@ -69,6 +72,26 @@ void findPanesRunning(TmuxSocketPath socket) throws Exception { assertEquals("", out); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void queueRecoversAfterTwoCrashes(boolean naive) throws Exception { + Path root = Path.of(System.getProperty("java.io.tmpdir"), naive ? "q-naive" : "q"); + String out = launch("RecoverBuildQueue", naive ? "--naive" : "--safe", root.toString()); + + assertTrue(out.contains("Coordinator stopped before publication"), out); + assertTrue(out.contains("Coordinator stopped after publication"), out); + String worker = out.lines() + .filter(line -> line.startsWith("Started attempt-1 pane %")) + .findFirst() + .orElseThrow(); + assertTrue(out.contains("Reattached" + worker.substring("Started".length())), out); + assertTrue(out.contains("Started attempt-2 pane %"), out); + assertTrue(out.endsWith("Published app-release: " + (naive ? 2 : 1) + "\n"), out); + try (var files = Files.list(root)) { + assertTrue(files.findAny().isEmpty(), out); + } + } + @Test void runACommand(TmuxSocketPath socket) throws Exception { String out = launch("RunACommand", socket.path().toString(), "printf 'built\\n'; exit 3");