mirror of
https://github.com/floci-io/floci-cli.git
synced 2026-11-22 21:50:47 -05:00
The help listed fish and powershell, which only produced an error; an unsupported shell is now a usage error (exit 2) with nothing on stdout. Container details are read from docker's inspect JSON instead of a pipe-delimited template, which a value containing the delimiter could shift. Signed-off-by: Hector Ventura <hectorvent@gmail.com>
347 lines
15 KiB
Java
347 lines
15 KiB
Java
package io.floci.cli.unit;
|
|
|
|
import com.fasterxml.jackson.databind.JsonNode;
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
import io.floci.cli.GlobalOptions;
|
|
import io.floci.cli.docker.DockerClient;
|
|
import io.floci.cli.docker.DockerException;
|
|
import org.junit.jupiter.api.Test;
|
|
import org.junit.jupiter.api.condition.DisabledOnOs;
|
|
import org.junit.jupiter.api.condition.OS;
|
|
import org.junit.jupiter.api.io.TempDir;
|
|
import org.junit.jupiter.params.ParameterizedTest;
|
|
import org.junit.jupiter.params.provider.ValueSource;
|
|
|
|
import java.io.ByteArrayOutputStream;
|
|
import java.io.PrintStream;
|
|
import java.nio.file.Files;
|
|
import java.nio.file.Path;
|
|
import java.time.Duration;
|
|
import java.util.List;
|
|
import java.util.concurrent.atomic.AtomicReference;
|
|
|
|
import static org.junit.jupiter.api.Assertions.*;
|
|
|
|
/** An abandoned docker call must not leave its process running after the CLI moves on. */
|
|
class DockerClientProcessTest {
|
|
|
|
@TempDir
|
|
Path tempDir;
|
|
|
|
@Test
|
|
@DisabledOnOs(OS.WINDOWS)
|
|
void anInterruptedCallKillsItsDockerProcess() throws Exception {
|
|
Path pidFile = tempDir.resolve("pid");
|
|
Path fakeDocker = tempDir.resolve("docker");
|
|
Files.writeString(fakeDocker, "#!/bin/sh\necho $$ > '" + pidFile + "'\nexec sleep 30\n");
|
|
assertTrue(fakeDocker.toFile().setExecutable(true));
|
|
DockerClient docker = new DockerClient(fakeDocker.toString());
|
|
|
|
Thread call = Thread.ofVirtual().start(() -> {
|
|
try {
|
|
docker.inspectContainer("floci");
|
|
} catch (DockerException expected) {
|
|
// "Interrupted"
|
|
}
|
|
});
|
|
long pid = awaitPid(pidFile);
|
|
|
|
call.interrupt();
|
|
call.join(5_000);
|
|
|
|
assertFalse(call.isAlive(), "the call should return once interrupted");
|
|
long deadline = System.currentTimeMillis() + 3_000;
|
|
while (isAlive(pid) && System.currentTimeMillis() < deadline) {
|
|
Thread.sleep(50);
|
|
}
|
|
assertFalse(isAlive(pid), "docker process " + pid + " outlived the interrupted call");
|
|
}
|
|
|
|
/** A stalled daemon probe is cut off at the time limit and reads as unreachable. */
|
|
@Test
|
|
@DisabledOnOs(OS.WINDOWS)
|
|
void aStalledDaemonProbeReportsUnreachableAndIsKilled() throws Exception {
|
|
Path pidFile = tempDir.resolve("pid");
|
|
DockerClient docker = new DockerClient(fakeDocker("echo $$ > '" + pidFile + "'\nexec sleep 30\n"),
|
|
Duration.ofMillis(500));
|
|
|
|
long start = System.nanoTime();
|
|
boolean reachable = docker.isDaemonReachable();
|
|
long elapsedMs = (System.nanoTime() - start) / 1_000_000;
|
|
|
|
assertFalse(reachable);
|
|
assertTrue(elapsedMs < 3_000, "took " + elapsedMs + " ms");
|
|
assertExits(awaitPid(pidFile), "the stalled probe is still running");
|
|
}
|
|
|
|
@Test
|
|
@DisabledOnOs(OS.WINDOWS)
|
|
void theDaemonProbeFollowsTheExitCode() throws Exception {
|
|
assertTrue(new DockerClient(fakeDocker("echo some output\nexit 0\n")).isDaemonReachable());
|
|
assertFalse(new DockerClient(fakeDocker("echo cannot connect >&2\nexit 1\n")).isDaemonReachable());
|
|
}
|
|
|
|
/** "stop --timeout -1" is docker's wait-indefinitely, so the CLI must not cut it short. */
|
|
@Test
|
|
@DisabledOnOs(OS.WINDOWS)
|
|
void anIndefiniteStopIsNotTimeLimited() throws Exception {
|
|
Path argsFile = tempDir.resolve("args");
|
|
DockerClient docker = new DockerClient(
|
|
fakeDocker("for a in \"$@\"; do echo \"$a\"; done > '" + argsFile + "'\nsleep 1.5\n"),
|
|
Duration.ofMillis(300));
|
|
|
|
docker.stopContainer("floci", -1);
|
|
|
|
assertEquals(List.of("stop", "-t", "-1", "--", "floci"), Files.readAllLines(argsFile));
|
|
}
|
|
|
|
/** A bounded stop still gets a limit: the grace period plus the client's own. */
|
|
@Test
|
|
@DisabledOnOs(OS.WINDOWS)
|
|
void aBoundedStopIsStillTimeLimited() throws Exception {
|
|
DockerClient docker = new DockerClient(fakeDocker("exec sleep 30\n"), Duration.ofMillis(300));
|
|
|
|
DockerException e = assertThrows(DockerException.class, () -> docker.stopContainer("floci", 0));
|
|
|
|
assertTrue(e.getMessage().contains("did not finish within"), e.getMessage());
|
|
}
|
|
|
|
/** Streaming calls have no time limit, so interruption is their only way out: it must kill docker. */
|
|
@ParameterizedTest
|
|
@ValueSource(strings = {"logs", "pull"})
|
|
@DisabledOnOs(OS.WINDOWS)
|
|
void anInterruptedStreamingCallKillsItsDockerProcess(String call) throws Exception {
|
|
Path pidFile = tempDir.resolve("pid");
|
|
// Lines on both streams first, so both reader threads are mid-read when the interrupt lands.
|
|
DockerClient docker = new DockerClient(
|
|
fakeDocker("echo $$ > '" + pidFile + "'\necho out\necho err >&2\nexec sleep 30\n"));
|
|
AtomicReference<String> failure = new AtomicReference<>();
|
|
|
|
Thread streaming = Thread.ofPlatform().start(() -> {
|
|
try {
|
|
if ("logs".equals(call)) {
|
|
docker.streamLogs("floci", true, 0, null);
|
|
} else {
|
|
docker.pull("floci/floci:latest", "always");
|
|
}
|
|
} catch (DockerException e) {
|
|
failure.set(e.getMessage());
|
|
}
|
|
});
|
|
long pid = awaitPid(pidFile);
|
|
|
|
streaming.interrupt();
|
|
streaming.join(5_000);
|
|
|
|
assertFalse(streaming.isAlive(), "the streaming call should return once interrupted");
|
|
assertEquals("Interrupted", failure.get());
|
|
assertExits(pid, "docker process " + pid + " outlived the interrupted streaming call");
|
|
}
|
|
|
|
private String fakeDocker(String body) throws Exception {
|
|
Path fakeDocker = Files.createTempFile(tempDir, "docker", "");
|
|
Files.writeString(fakeDocker, "#!/bin/sh\n" + body);
|
|
assertTrue(fakeDocker.toFile().setExecutable(true));
|
|
return fakeDocker.toString();
|
|
}
|
|
|
|
private static void assertExits(long pid, String message) throws Exception {
|
|
long deadline = System.currentTimeMillis() + 3_000;
|
|
while (isAlive(pid) && System.currentTimeMillis() < deadline) {
|
|
Thread.sleep(50);
|
|
}
|
|
assertFalse(isAlive(pid), message);
|
|
}
|
|
|
|
private static long awaitPid(Path pidFile) throws Exception {
|
|
long deadline = System.currentTimeMillis() + 5_000;
|
|
while (System.currentTimeMillis() < deadline) {
|
|
if (Files.exists(pidFile)) {
|
|
String text = Files.readString(pidFile).trim();
|
|
if (!text.isEmpty()) return Long.parseLong(text);
|
|
}
|
|
Thread.sleep(20);
|
|
}
|
|
throw new AssertionError("fake docker never started");
|
|
}
|
|
|
|
private static boolean isAlive(long pid) {
|
|
return ProcessHandle.of(pid).map(ProcessHandle::isAlive).orElse(false);
|
|
}
|
|
|
|
/** BL-045: a stalled docker call is killed at the time limit instead of hanging the CLI. */
|
|
@Test
|
|
@DisabledOnOs(OS.WINDOWS)
|
|
void aCallThatOutlivesItsTimeLimitIsKilledAndReported() throws Exception {
|
|
Path pidFile = tempDir.resolve("pid");
|
|
Path fakeDocker = tempDir.resolve("docker");
|
|
Files.writeString(fakeDocker, "#!/bin/sh\necho $$ > '" + pidFile + "'\nexec sleep 30\n");
|
|
assertTrue(fakeDocker.toFile().setExecutable(true));
|
|
DockerClient docker = new DockerClient(fakeDocker.toString(), Duration.ofMillis(500));
|
|
|
|
long start = System.nanoTime();
|
|
DockerException e = assertThrows(DockerException.class, docker::dockerVersion);
|
|
long elapsedMs = (System.nanoTime() - start) / 1_000_000;
|
|
|
|
assertTrue(elapsedMs < 3_000, "took " + elapsedMs + " ms");
|
|
assertTrue(e.getMessage().contains("did not finish within"), e.getMessage());
|
|
long pid = awaitPid(pidFile);
|
|
long deadline = System.currentTimeMillis() + 3_000;
|
|
while (isAlive(pid) && System.currentTimeMillis() < deadline) {
|
|
Thread.sleep(50);
|
|
}
|
|
assertFalse(isAlive(pid), "the timed-out docker process is still running");
|
|
}
|
|
|
|
/** BL-045: names go after "--", so a name starting with '-' is never read as a flag. */
|
|
@Test
|
|
@DisabledOnOs(OS.WINDOWS)
|
|
void namesArePassedAfterTheEndOfOptionsMarker() throws Exception {
|
|
Path argsFile = tempDir.resolve("args");
|
|
Path fakeDocker = tempDir.resolve("docker");
|
|
Files.writeString(fakeDocker, "#!/bin/sh\nfor a in \"$@\"; do echo \"$a\"; done > '" + argsFile + "'\n");
|
|
assertTrue(fakeDocker.toFile().setExecutable(true));
|
|
DockerClient docker = new DockerClient(fakeDocker.toString());
|
|
|
|
docker.removeContainer("--rm-everything");
|
|
List<String> args = Files.readAllLines(argsFile);
|
|
|
|
assertEquals(List.of("rm", "--", "--rm-everything"), args);
|
|
}
|
|
|
|
/** BL-033: restart reads the image, host port, data mount and environment back from inspect. */
|
|
@Test
|
|
@DisabledOnOs(OS.WINDOWS)
|
|
void runSettingsAreReadFromTheContainersInspectDocument() throws Exception {
|
|
Path json = tempDir.resolve("inspect.json");
|
|
Files.writeString(json, """
|
|
{"Config":{"Image":"floci/floci-gcp:0.9","Env":["FLOCI_GCP_SERVICES=storage","PATH=/usr/bin"]},
|
|
"HostConfig":{"PortBindings":{"4588/tcp":[{"HostIp":"","HostPort":"14588"}]}},
|
|
"Mounts":[{"Type":"bind","Source":"/data/gcp","Destination":"/app/data"}]}
|
|
""");
|
|
Path fakeDocker = tempDir.resolve("docker");
|
|
Files.writeString(fakeDocker, "#!/bin/sh\ncat '" + json + "'\n");
|
|
assertTrue(fakeDocker.toFile().setExecutable(true));
|
|
|
|
DockerClient.RunSettings run = new DockerClient(fakeDocker.toString())
|
|
.inspectRunSettings("floci-gcp", 4588).orElseThrow();
|
|
|
|
assertEquals("floci/floci-gcp:0.9", run.image());
|
|
assertEquals(14588, run.hostPort());
|
|
assertEquals("/data/gcp", run.persistSource());
|
|
assertEquals("storage", run.env().get("FLOCI_GCP_SERVICES"));
|
|
}
|
|
|
|
/** Without --persist the image's /app/data volume is mounted; that is not a persist directory. */
|
|
@Test
|
|
@DisabledOnOs(OS.WINDOWS)
|
|
void anAnonymousDataVolumeIsNotAPersistDirectory() throws Exception {
|
|
Path json = tempDir.resolve("inspect.json");
|
|
Files.writeString(json, """
|
|
{"Config":{"Image":"floci/floci-oci:latest","Env":[]},
|
|
"HostConfig":{"PortBindings":{"4599/tcp":[{"HostIp":"","HostPort":"4599"}]}},
|
|
"Mounts":[{"Type":"volume","Name":"3c3aef44","Source":"/var/lib/docker/volumes/3c3aef44/_data","Destination":"/app/data"}]}
|
|
""");
|
|
Path fakeDocker = tempDir.resolve("docker");
|
|
Files.writeString(fakeDocker, "#!/bin/sh\ncat '" + json + "'\n");
|
|
assertTrue(fakeDocker.toFile().setExecutable(true));
|
|
|
|
DockerClient.RunSettings run = new DockerClient(fakeDocker.toString())
|
|
.inspectRunSettings("floci-oci", 4599).orElseThrow();
|
|
|
|
assertNull(run.persistSource());
|
|
}
|
|
|
|
/** BL-041: with --verbose set, each docker command is echoed to stderr before it runs. */
|
|
@Test
|
|
@DisabledOnOs(OS.WINDOWS)
|
|
void verboseEchoesTheDockerCommand() throws Exception {
|
|
Path fakeDocker = tempDir.resolve("docker");
|
|
Files.writeString(fakeDocker, "#!/bin/sh\nexit 0\n");
|
|
assertTrue(fakeDocker.toFile().setExecutable(true));
|
|
PrintStream err = System.err;
|
|
ByteArrayOutputStream errBuf = new ByteArrayOutputStream();
|
|
System.setErr(new PrintStream(errBuf));
|
|
System.setProperty(GlobalOptions.VERBOSE_PROPERTY, "true");
|
|
try {
|
|
new DockerClient(fakeDocker.toString()).removeContainer("floci-x");
|
|
} finally {
|
|
System.clearProperty(GlobalOptions.VERBOSE_PROPERTY);
|
|
System.setErr(err);
|
|
}
|
|
|
|
assertTrue(errBuf.toString().contains("+ docker rm"), errBuf.toString());
|
|
assertTrue(errBuf.toString().contains("floci-x"), errBuf.toString());
|
|
}
|
|
|
|
private DockerClient dockerPrinting(String inspectJson) throws Exception {
|
|
Path json = Files.createTempFile(tempDir, "inspect", ".json");
|
|
Files.writeString(json, inspectJson);
|
|
Path fakeDocker = Files.createTempFile(tempDir, "docker", "");
|
|
Files.writeString(fakeDocker, "#!/bin/sh\ncat '" + json + "'\n");
|
|
assertTrue(fakeDocker.toFile().setExecutable(true));
|
|
return new DockerClient(fakeDocker.toString());
|
|
}
|
|
|
|
/** BL-046: container details come from the inspect document, not from a delimiter-split template. */
|
|
@Test
|
|
@DisabledOnOs(OS.WINDOWS)
|
|
void containerDetailsAreReadFromTheInspectDocument() throws Exception {
|
|
DockerClient docker = dockerPrinting("""
|
|
{"Id":"0123abcd","Name":"/floci-team-b","Config":{"Image":"floci/floci:1.6.0"},
|
|
"State":{"Status":"running"},
|
|
"NetworkSettings":{"Ports":{"4566/tcp":[{"HostIp":"0.0.0.0","HostPort":"14566"},{"HostIp":"::","HostPort":"14566"}],
|
|
"8080/tcp":null}}}
|
|
""");
|
|
|
|
DockerClient.ContainerInfo info = docker.inspectContainer("floci-team-b").orElseThrow();
|
|
|
|
assertEquals("0123abcd", info.id());
|
|
assertEquals("floci-team-b", info.name());
|
|
assertEquals("floci/floci:1.6.0", info.image());
|
|
assertEquals("running", info.state());
|
|
assertEquals("14566->4566/tcp", info.ports());
|
|
}
|
|
|
|
/** A value with the old delimiter in it cannot shift the fields any more. */
|
|
@Test
|
|
@DisabledOnOs(OS.WINDOWS)
|
|
void aPipeInAValueDoesNotShiftTheFields() throws Exception {
|
|
DockerClient docker = dockerPrinting("""
|
|
{"Id":"0123abcd","Name":"/floci","Config":{"Image":"registry.local/team|floci:latest"},
|
|
"State":{"Status":"exited"},"NetworkSettings":{"Ports":{}}}
|
|
""");
|
|
|
|
DockerClient.ContainerInfo info = docker.inspectContainer("floci").orElseThrow();
|
|
|
|
assertEquals("registry.local/team|floci:latest", info.image());
|
|
assertEquals("exited", info.state());
|
|
assertEquals("", info.ports());
|
|
}
|
|
|
|
@Test
|
|
void publishedPortsListEveryBindingAndSkipWhatIsNotPublished() throws Exception {
|
|
JsonNode ports = new ObjectMapper().readTree("""
|
|
{"4566/tcp":[{"HostIp":"","HostPort":"14566"}],"8080/tcp":null,"9000/tcp":[],
|
|
"4510/tcp":[{"HostIp":"","HostPort":"24510"}]}
|
|
""");
|
|
|
|
assertEquals("14566->4566/tcp 24510->4510/tcp", DockerClient.publishedPorts(ports));
|
|
assertEquals("", DockerClient.publishedPorts(new ObjectMapper().readTree("{}")));
|
|
}
|
|
|
|
@Test
|
|
@DisabledOnOs(OS.WINDOWS)
|
|
void aMissingContainerIsEmptyAndGarbageIsReportedWithANextStep() throws Exception {
|
|
Path missing = Files.createTempFile(tempDir, "docker", "");
|
|
Files.writeString(missing, "#!/bin/sh\necho 'Error response from daemon: No such container: floci' >&2\nexit 1\n");
|
|
assertTrue(missing.toFile().setExecutable(true));
|
|
|
|
assertTrue(new DockerClient(missing.toString()).inspectContainer("floci").isEmpty());
|
|
|
|
DockerException e = assertThrows(DockerException.class, () -> dockerPrinting("not json").inspectContainer("floci"));
|
|
assertTrue(e.getMessage().contains("Could not read the details of container 'floci'"), e.getMessage());
|
|
assertTrue(e.getMessage().contains("docker info"), e.getMessage());
|
|
}
|
|
}
|