Merge remote-tracking branch 'origin/main' into test/core-units

Adds the two cases the update fixes made testable end to end: --check exits 2 when the check fails, and an install behind a symlink is updated in place.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura committed 2026-10-10 22:11:41 -05:00
commit 15d3c67db8
32 files changed
+1421 -65

No files matched your search

+1 -1
View File
@@ -72,7 +72,7 @@ Commands call `global.printer()` at the start of `call()`; never store a `Printe
**Docker:** `DockerClient` wraps `docker` CLI subprocesses, with no docker-java library. This is a deliberate native-image trade-off. `DockerClient` returns plain records (`ContainerInfo`, `ImageInfo`) and throws `DockerException` on non-zero exit codes.
**Floci server:** `FlociHttpClient` wraps `java.net.http.HttpClient` against the Floci REST API. All methods throw `FlociException`. The control-plane prefix is constructor-configurable: AWS and Azure use `/_floci`, GCP uses `/_floci-gcp`. Known live endpoints: `/_floci/health`, `/_floci/info`, `/_floci/init`, and on floci-az only `/_floci/tls-cert` (`tlsCert()`, the PEM CA; 404 when TLS is off). Snapshot endpoints (`/_floci/snapshots/*`) do not exist on the server yet.
**Floci server:** `FlociHttpClient` wraps `java.net.http.HttpClient` against the Floci REST API. All methods throw `FlociException`. The control-plane prefix is constructor-configurable: AWS and Azure use `/_floci`, GCP uses `/_floci-gcp`. Known live endpoints: `/_floci/health`, `/_floci/info`, `/_floci/init`, `POST <prefix>/state/reset` (AWS, GCP and OCI; `floci reset`), and on floci-az only `/_floci/tls-cert` (`tlsCert()`, the PEM CA; 404 when TLS is off). Snapshot endpoints (`/_floci/snapshots/*`) do not exist on the server yet.
### Output pipeline
+22 -3
View File
@@ -103,7 +103,7 @@ java -jar floci.jar version
Native-binary installs (install script, direct download) can self-update:
```sh
floci update --check # exit 0: up to date, exit 1: update available
floci update --check # exit 0: up to date, 1: update available, 2: the check failed
floci update # download, verify checksum, replace the binary
```
@@ -241,6 +241,7 @@ Commands are organized into four product groups: `floci aws` (or bare `floci`),
| `floci wait` | Poll until Floci is ready (CI-friendly) |
| `floci version` | Show CLI and server versions |
| `floci services` | List enabled AWS services |
| `floci reset` | Delete every resource in the running emulator, keeping it running |
| `floci doctor` | Run environment diagnostics |
| `floci env` | Print AWS environment variables |
| `floci snapshot save/load/list/delete` | Manage state snapshots |
@@ -261,6 +262,7 @@ Bare `floci config ...` always means the AWS tree, whatever the default product;
| `floci gcp wait` | Poll until Floci GCP is ready (CI-friendly) |
| `floci gcp version` | Show CLI and server versions |
| `floci gcp services` | List enabled GCP services |
| `floci gcp reset` | Delete every resource in the running emulator, keeping it running |
| `floci gcp doctor` | Run GCP environment diagnostics |
| `floci gcp env` | Print GCP SDK emulator host variables |
| `floci gcp snapshot` | Snapshot commands (coming soon) |
@@ -278,6 +280,7 @@ Bare `floci config ...` always means the AWS tree, whatever the default product;
| `floci az wait` | Poll until Floci Azure is ready (CI-friendly) |
| `floci az version` | Show CLI and server versions |
| `floci az services` | List enabled Azure services |
| `floci az reset` | Delete every resource in the running emulator, keeping it running |
| `floci az doctor` | Run Azure environment diagnostics |
| `floci az env` | Print Azure connection string / SDK env vars |
| `floci az setup` | Point the `az` CLI at the emulator: trust its certificate, register the cloud, log in |
@@ -296,6 +299,7 @@ Bare `floci config ...` always means the AWS tree, whatever the default product;
| `floci oci wait` | Poll until Floci OCI is ready (CI-friendly) |
| `floci oci version` | Show CLI and server versions |
| `floci oci services` | List enabled OCI services |
| `floci oci reset` | Delete every resource in the running emulator, keeping it running |
| `floci oci doctor` | Run OCI environment diagnostics |
| `floci oci env` | Print OCI endpoint variables |
| `floci oci setup` | Create a local OCI CLI profile (API key + `~/.oci/config`) |
@@ -660,7 +664,6 @@ floci wait -o json # machine-readable output
```sh
floci doctor # run all checks
floci doctor --check docker.installed # run a single check by name
floci doctor --fix # auto-fix fixable issues
floci doctor -o json # structured output for scripts
floci gcp doctor # GCP-specific checks
@@ -682,6 +685,22 @@ floci services # list all enabled services
floci services -o json
```
### `floci reset` / `floci gcp reset` / `floci az reset` / `floci oci reset`
```sh
floci reset # asks first, then deletes every resource; the emulator keeps running
floci reset --yes # no prompt (required when not on a terminal, e.g. in CI)
floci gcp reset -y -o json
```
It calls the emulator's `POST <prefix>/state/reset`. The AWS, GCP and OCI emulators serve it; on a
server without it (currently floci-az) the command says reset is not available and exits 1. Without
`--yes` and with no terminal to ask on, it exits 2.
Reset never guesses which server to wipe. An `--endpoint` you type is used as given. A container you
select (`--container`, a profile, or `FLOCI_CONTAINER`) has to be running: if it is missing or
stopped, nothing is reset and the command exits 1 instead of falling back to the default instance.
### `floci config`
```sh
@@ -832,7 +851,7 @@ sha256 against the release's `sha256sums.txt`, and atomically replaces the runni
```sh
floci update # update to the latest release
floci update --check # exit 0: up to date, exit 1: update available
floci update --check # exit 0: up to date, 1: update available, 2: the check failed
floci update --version 0.1.7 # install a specific version
floci update --check || floci update # script-friendly: update only when stale
```
+1
View File
@@ -42,6 +42,7 @@ import java.util.Arrays;
WaitCommand.class,
VersionCommand.class,
ServicesCommand.class,
ResetCommand.class,
DoctorCommand.class,
EnvCommand.class,
ConfigCommand.class,
+24 -11
View File
@@ -9,6 +9,7 @@ import picocli.CommandLine.Option;
import picocli.CommandLine.Spec;
import java.net.URI;
import java.util.Optional;
import java.util.function.UnaryOperator;
import java.util.regex.Pattern;
@@ -105,7 +106,8 @@ public class GlobalOptions {
return "";
}
private boolean typed(String option) {
/** Whether {@code option} was given on the command line, as opposed to coming from a profile, the environment or the default. */
public boolean typed(String option) {
try {
return mixee != null && mixee.commandLine() != null
&& mixee.commandLine().getParseResult() != null
@@ -150,20 +152,31 @@ public class GlobalOptions {
try {
int containerPort = URI.create(fallback).getPort();
if (containerPort == -1) containerPort = product.defaultPort();
for (String mapping : ports.trim().split("\\s+")) {
int arrow = mapping.indexOf("->");
if (arrow < 0) continue;
String hostPort = mapping.substring(0, arrow);
String rest = mapping.substring(arrow + 2);
String cPort = rest.contains("/") ? rest.substring(0, rest.indexOf('/')) : rest;
if (String.valueOf(containerPort).equals(cPort)) {
return "http://localhost:" + hostPort;
}
}
return publishedEndpoint(ports, containerPort).orElse(fallback);
} catch (Exception ignored) {}
return fallback;
}
/**
* Where a container with these published {@code ports} ("14566->4566/tcp ...") is reached for
* its {@code containerPort}, or empty when that port is not published. For callers that must
* not fall back to a configured endpoint.
*/
public static Optional<String> publishedEndpoint(String ports, int containerPort) {
if (ports == null || ports.isBlank()) return Optional.empty();
for (String mapping : ports.trim().split("\\s+")) {
int arrow = mapping.indexOf("->");
if (arrow < 0) continue;
String hostPort = mapping.substring(0, arrow);
String rest = mapping.substring(arrow + 2);
String cPort = rest.contains("/") ? rest.substring(0, rest.indexOf('/')) : rest;
if (String.valueOf(containerPort).equals(cPort)) {
return Optional.of("http://localhost:" + hostPort);
}
}
return Optional.empty();
}
private static boolean isStdoutTty() {
return System.console() != null;
}
@@ -50,9 +50,6 @@ public class DoctorCommand implements Callable<Integer> {
@Option(names = {"--check"}, description = "Run only a specific check by name", paramLabel = "<name>")
String checkName;
@Option(names = {"--fix"}, description = "Attempt to auto-fix fixable issues")
boolean fix;
/** The base environment checks every product runs, in order: Docker first, then server. */
public static List<Check> dockerChecks(ProductProfile profile) {
return dockerChecks(profile, new CachingDockerClient());
@@ -182,7 +179,7 @@ public class DoctorCommand implements Callable<Integer> {
printer.println(Ansi.green("No failures") + ", " + warns + " warning(s) to review.");
} else {
printer.println(fails + " issue(s) found (" + fails + " fail, " + warns + " warn)."
+ (fix ? "" : " Run with --fix to auto-resolve fixable issues."));
+ " Follow the Fix line under each one.");
}
return fails > 0 ? 1 : 0;
@@ -0,0 +1,173 @@
package io.floci.cli.commands;
import io.floci.cli.GlobalOptions;
import io.floci.cli.ProductProfile;
import io.floci.cli.docker.DockerClient;
import io.floci.cli.docker.DockerException;
import io.floci.cli.http.FlociException;
import io.floci.cli.http.FlociHttpClient;
import io.floci.cli.output.Ansi;
import io.floci.cli.output.OutputFormat;
import io.floci.cli.output.Printer;
import picocli.CommandLine.*;
import java.io.Console;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Callable;
@Command(
name = "reset",
description = "Delete every resource in the running Floci AWS instance, keeping it running",
mixinStandardHelpOptions = true
)
public class ResetCommand implements Callable<Integer> {
protected final ProductProfile profile;
@Mixin
protected GlobalOptions global;
@Option(names = {"--yes", "-y"}, description = "Reset without asking for confirmation")
boolean yes;
public ResetCommand() {
this(ProductProfile.AWS);
}
protected ResetCommand(ProductProfile profile) {
this(profile, new DockerClient(), Prompt.console());
}
/** Test seam: {@code docker} answers the container lookup and {@code prompt} the confirmation. */
public ResetCommand(ProductProfile profile, DockerClient docker, Prompt prompt) {
this.profile = profile;
this.global = new GlobalOptions(profile);
this.docker = docker;
this.prompt = prompt;
}
private final DockerClient docker;
private final Prompt prompt;
/** The person at the terminal, when there is one. */
public interface Prompt {
/** False when nobody can answer (a pipe, CI). */
boolean available();
/** The answer to {@code question}, or null at end of input. */
String ask(String question);
static Prompt console() {
return new Prompt() {
@Override
public boolean available() {
Console console = System.console();
return console != null && console.isTerminal();
}
@Override
public String ask(String question) {
return System.console().readLine("%s", question);
}
};
}
}
/** The server a reset will wipe, or why none could be settled on. Exactly one is set. */
public record Target(String endpoint, String error) {}
/**
* Where this reset acts. Reset deletes data, so unlike the read-only commands it never
* guesses: an {@code --endpoint} the user typed is used as given, and a container the user
* chose must be found running. Falling back to the configured endpoint, as
* {@link GlobalOptions#resolvedEndpoint} does, is right only for the default container: there
* the configured endpoint names the same default instance.
*/
public Target target() {
if (global.typed("--endpoint")) return new Target(global.endpoint, null);
boolean chosen = global.typed("--container") || !profile.defaultContainer().equals(global.container);
String how = "\nRun '" + profile.commandPrefix() + " status" + global.instanceSelector()
+ "' to check it, or pass --endpoint <url> to name the server to reset.";
Optional<DockerClient.ContainerInfo> info;
try {
info = docker.inspectContainer(global.container);
} catch (DockerException e) {
if (chosen) {
return new Target(null, "Could not look up container '" + global.container + "': " + e.getMessage() + how);
}
info = Optional.empty();
}
if (info.isEmpty()) {
return chosen
? new Target(null, "Container '" + global.container + "' not found, so nothing was reset." + how)
: new Target(global.endpoint, null);
}
if (chosen && !"running".equals(info.get().state())) {
return new Target(null, "Container '" + global.container + "' is not running (state: "
+ info.get().state() + "), so nothing was reset." + how);
}
// By the emulator's own port inside the container, which never changes; the configured
// endpoint names the host port, and that differs on every instance but the default one.
Optional<String> published = GlobalOptions.publishedEndpoint(info.get().ports(), profile.defaultPort());
if (chosen && published.isEmpty()) {
// No port to find it by: the configured endpoint may well be another instance.
return new Target(null, "Container '" + global.container
+ "' publishes no port for the emulator, so nothing was reset." + how);
}
return new Target(published.orElse(global.endpoint), null);
}
@Override
public Integer call() {
Printer printer = global.printer();
Target target = target();
if (target.error() != null) {
printer.error(target.error());
return 1;
}
String effectiveEndpoint = target.endpoint();
if (!yes) {
if (!prompt.available()) {
// Nobody to ask: a script must say so explicitly.
printer.error("reset deletes every resource in " + profile.displayName() + " and needs confirmation.\n"
+ "Pass --yes to reset without asking.");
return 2;
}
String answer = prompt.ask("Delete every resource in " + profile.displayName()
+ " at " + effectiveEndpoint + "? [y/N] ");
if (answer == null || !(answer.trim().equalsIgnoreCase("y") || answer.trim().equalsIgnoreCase("yes"))) {
printer.println("Reset cancelled.");
return 1;
}
}
try {
new FlociHttpClient(effectiveEndpoint, profile).resetState();
} catch (FlociException e) {
if (e.endpointMissing()) {
printer.error("Resetting state is not available on this " + profile.displayName() + " server version.\n"
+ "Restart it without --persist for a clean state, or track progress: " + profile.serverRepo() + "/issues");
} else {
String message = "Failed to reset " + profile.displayName() + ": " + e.getMessage();
// Connection errors already say what to do; others get the status hint.
printer.error(message.contains("\n") ? message
: message + "\nRun '" + profile.commandPrefix() + " status" + global.instanceSelector() + "' to check the emulator.");
}
return 1;
}
if (printer.format() != OutputFormat.text) {
Map<String, Object> out = new LinkedHashMap<>();
out.put("reset", true);
out.put("endpoint", effectiveEndpoint);
printer.structured(out);
return 0;
}
printer.println(Ansi.green("✓") + " " + profile.displayName() + " state reset" + Ansi.gray(" (" + effectiveEndpoint + ")"));
return 0;
}
}
@@ -35,9 +35,6 @@ public class ServicesCommand implements Callable<Integer> {
this.global = new GlobalOptions(profile);
}
@Option(names = {"--mode"}, description = "Filter mode: docker, in-process, all (default: all)", defaultValue = "all", paramLabel = "docker|in-process|all")
String mode;
@Override
public Integer call() {
Printer printer = global.printer();
@@ -26,6 +26,8 @@ import java.security.MessageDigest;
import java.time.Duration;
import java.util.HexFormat;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.function.BooleanSupplier;
/**
* Self-update: downloads the target release binary from the public GitHub repository
@@ -46,7 +48,7 @@ import java.util.concurrent.Callable;
public class UpdateCommand implements Callable<Integer> {
@Option(names = "--check",
description = "Only report whether an update is available (exit 0: up to date, 1: update available)")
description = "Only report whether an update is available (exit 0: up to date, 1: update available, 2: the check failed)")
boolean check;
// No mixinStandardHelpOptions here: its -V/--version would collide with this option.
@@ -97,6 +99,10 @@ public class UpdateCommand implements Callable<Integer> {
try {
String current = CliVersion.CLI_VERSION;
boolean pinned = to != null && !to.isBlank();
if (pinned && !Version.isValid(to.trim())) {
// It goes into the download URL; refuse anything that is not a release version.
throw new UpdateException("invalid --version '" + to + "'.\nPass a release version such as 0.3.0.");
}
String target = pinned ? to.trim() : fetchLatestVersion();
// Unpinned updates are semantic, not string-equal: a pre-release/snapshot build
@@ -109,7 +115,7 @@ public class UpdateCommand implements Callable<Integer> {
printer.println("update available: " + current + " → " + Ansi.bold(target));
if (check) {
printer.println(Ansi.gray("run 'floci update' to install it"));
printer.println(Ansi.gray(installHint()));
// Non-zero so scripts can gate on staleness: floci update --check || floci update
return 1;
}
@@ -137,10 +143,10 @@ public class UpdateCommand implements Callable<Integer> {
return 0;
} catch (UpdateException e) {
printer.error(e.getMessage());
return 1;
return check ? 2 : 1; // --check keeps 1 for "update available"
} catch (Exception e) {
printer.error("update failed: " + e.getMessage());
return 1;
printer.error("update failed: " + e.getMessage() + "\nCheck your network connection and re-run 'floci update'.");
return check ? 2 : 1;
}
}
@@ -171,7 +177,7 @@ public class UpdateCommand implements Callable<Integer> {
private Path resolveSelf() {
if (selfPath != null) {
return selfPath;
return realExecutable(selfPath);
}
String cmd = ProcessHandle.current().info().command()
.orElseThrow(() -> new UpdateException("cannot locate the running executable"));
@@ -181,7 +187,31 @@ public class UpdateCommand implements Callable<Integer> {
throw new UpdateException("running from a jar (java -jar), not the native binary — "
+ "nothing to self-update. Reinstall instead: curl -fsSL https://floci.io/install.sh | sh");
}
return path;
return realExecutable(path);
}
/**
* The file an update of {@code path} has to replace. A symlinked install
* (~/bin/floci -> /opt/floci/floci) must replace the real file, not the link; this also
* resolves a relative argv[0] against the working directory.
*/
public static Path realExecutable(Path path) {
try {
return path.toRealPath();
} catch (IOException e) {
throw new UpdateException("cannot locate the running executable (" + path + ").\n"
+ "Reinstall instead: curl -fsSL https://floci.io/install.sh | sh");
}
}
// What --check suggests: 'floci update' where it can install, the installer where it cannot.
private static String installHint() {
try {
detectPlatform();
return "run 'floci update' to install it";
} catch (UpdateException e) {
return e.getMessage();
}
}
/**
@@ -217,15 +247,24 @@ public class UpdateCommand implements Callable<Integer> {
// ── platform (mirrors installer/install.sh) ──────────────────────────────
static String detectPlatform() {
String os = System.getProperty("os.name", "").toLowerCase();
String arch = System.getProperty("os.arch", "").toLowerCase();
return detectPlatform(System.getProperty("os.name", ""), System.getProperty("os.arch", ""),
UpdateCommand::appleSilicon);
}
/**
* The release asset suffix for this machine. An x86_64 build on a Mac may be running under
* Rosetta on Apple Silicon; it then updates to the arm64 build instead of staying x86 forever.
*/
public static String detectPlatform(String osName, String osArch, BooleanSupplier appleSilicon) {
String os = osName.toLowerCase();
String arch = osArch.toLowerCase();
String o = null;
if (os.contains("mac")) {
o = "darwin";
} else if (os.contains("linux")) {
o = "linux";
} else if (os.contains("windows")) {
throw new UpdateException("self-update is not supported on Windows — "
throw new UpdateException("self-update is not supported on Windows; "
+ "re-run the installer: irm https://floci.io/install.ps1 | iex");
}
String a = switch (arch) {
@@ -236,9 +275,40 @@ public class UpdateCommand implements Callable<Integer> {
if (o == null || a == null) {
throw new UpdateException("no published build for this platform (" + os + "/" + arch + ")");
}
if (o.equals("darwin") && a.equals("amd64") && appleSilicon.getAsBoolean()) {
a = "arm64";
}
return o + "-" + a;
}
private static boolean appleSilicon() {
try {
return "1".equals(probe(Duration.ofSeconds(5), "sysctl", "-n", "hw.optional.arm64"));
} catch (Exception e) {
return false;
}
}
/**
* The trimmed output of a short command, or null when it does not finish within {@code limit}.
* The wait comes first and a late process is killed: reading first would block for as long as
* the process keeps its output open, and the limit would never apply. Only for commands that
* print a line or two, which fit the pipe without being drained.
*/
public static String probe(Duration limit, String... command) throws IOException, InterruptedException {
Process p = new ProcessBuilder(command)
.redirectError(ProcessBuilder.Redirect.DISCARD)
.start();
try {
if (!p.waitFor(limit.toMillis(), TimeUnit.MILLISECONDS)) {
return null;
}
return new String(p.getInputStream().readAllBytes()).trim();
} finally {
p.destroyForcibly(); // a no-op once it has exited
}
}
// ── download + verify ────────────────────────────────────────────────────
private String fetchString(String url) throws IOException, InterruptedException {
@@ -288,7 +358,7 @@ public class UpdateCommand implements Callable<Integer> {
in.transferTo(OutputStream.nullOutputStream());
}
String actual = HexFormat.of().formatHex(sha256.digest());
if (!actual.equals(expected)) {
if (!actual.equalsIgnoreCase(expected)) {
throw new UpdateException("checksum mismatch for " + asset + "\n expected: " + expected
+ "\n actual: " + actual + "\nThe download may be corrupt or tampered with. Aborting.");
}
@@ -296,7 +366,8 @@ public class UpdateCommand implements Callable<Integer> {
// ── atomic replace ───────────────────────────────────────────────────────
private static void replaceAtomically(Path fresh, Path target) throws IOException {
/** Puts {@code fresh} in place of {@code target} in one step. Public as a test seam. */
public static void replaceAtomically(Path fresh, Path target) throws IOException {
// Stage in the TARGET's directory (same filesystem), then atomically rename over it.
// The running process keeps its old inode; the path now serves the new binary.
Path staged = target.resolveSibling("." + target.getFileName() + ".new");
@@ -24,6 +24,7 @@ import picocli.CommandLine.*;
WaitCommand.class,
VersionCommand.class,
ServicesCommand.class,
ResetCommand.class,
DoctorCommand.class,
EnvCommand.class,
ConfigCommand.class,
@@ -25,6 +25,7 @@ import picocli.CommandLine.*;
AzWaitCommand.class,
AzVersionCommand.class,
AzServicesCommand.class,
AzResetCommand.class,
AzDoctorCommand.class,
AzEnvCommand.class,
AzSetupCommand.class,
@@ -0,0 +1,17 @@
package io.floci.cli.commands.az;
import io.floci.cli.ProductProfile;
import io.floci.cli.commands.ResetCommand;
import picocli.CommandLine.Command;
@Command(
name = "reset",
description = "Delete every resource in the running Floci Azure instance, keeping it running",
mixinStandardHelpOptions = true
)
public class AzResetCommand extends ResetCommand {
public AzResetCommand() {
super(ProductProfile.AZ);
}
}
@@ -24,6 +24,7 @@ import picocli.CommandLine.*;
GcpWaitCommand.class,
GcpVersionCommand.class,
GcpServicesCommand.class,
GcpResetCommand.class,
GcpDoctorCommand.class,
GcpEnvCommand.class,
GcpConfigCommand.class,
@@ -0,0 +1,17 @@
package io.floci.cli.commands.gcp;
import io.floci.cli.ProductProfile;
import io.floci.cli.commands.ResetCommand;
import picocli.CommandLine.Command;
@Command(
name = "reset",
description = "Delete every resource in the running Floci GCP instance, keeping it running",
mixinStandardHelpOptions = true
)
public class GcpResetCommand extends ResetCommand {
public GcpResetCommand() {
super(ProductProfile.GCP);
}
}
@@ -25,6 +25,7 @@ import picocli.CommandLine.*;
OciWaitCommand.class,
OciVersionCommand.class,
OciServicesCommand.class,
OciResetCommand.class,
OciDoctorCommand.class,
OciEnvCommand.class,
OciSetupCommand.class,
@@ -0,0 +1,17 @@
package io.floci.cli.commands.oci;
import io.floci.cli.ProductProfile;
import io.floci.cli.commands.ResetCommand;
import picocli.CommandLine.Command;
@Command(
name = "reset",
description = "Delete every resource in the running Floci OCI instance, keeping it running",
mixinStandardHelpOptions = true
)
public class OciResetCommand extends ResetCommand {
public OciResetCommand() {
super(ProductProfile.OCI);
}
}
@@ -47,7 +47,12 @@ public class SnapshotDeleteCommand implements Callable<Integer> {
printer.println(Ansi.green("Snapshot deleted:") + " " + name);
return 0;
} catch (FlociException e) {
printer.error("Failed to delete snapshot: " + e.getMessage());
if (e.endpointMissing()) {
printer.error("Snapshot API not available on this server version.\n" +
"Track progress: " + profile.serverRepo() + "/issues");
} else {
printer.error("Failed to delete snapshot: " + e.getMessage());
}
return 1;
}
}
@@ -38,7 +38,7 @@ public class SnapshotExportCommand implements Callable<Integer> {
public Integer call() {
Printer printer = global.printer();
// TODO: implement GET /_floci/snapshots/<name>/export streaming to file
printer.error("snapshot export requires floci-server >= 1.6.0\n" +
printer.error("snapshot export is not available yet: the emulator has no snapshot export API.\n" +
"Track progress: " + profile.serverRepo() + "/issues");
return 1;
}
@@ -38,7 +38,7 @@ public class SnapshotImportCommand implements Callable<Integer> {
public Integer call() {
Printer printer = global.printer();
// TODO: implement POST /_floci/snapshots/import with multipart upload
printer.error("snapshot import requires floci-server >= 1.6.0\n" +
printer.error("snapshot import is not available yet: the emulator has no snapshot import API.\n" +
"Track progress: " + profile.serverRepo() + "/issues");
return 1;
}
@@ -54,7 +54,7 @@ public class SnapshotListCommand implements Callable<Integer> {
node.forEach(s -> printer.println(" " + s.asText()));
return 0;
} catch (FlociException e) {
if (e.getMessage().contains("404") || e.getMessage().contains("501")) {
if (e.endpointMissing()) {
printer.error("Snapshot API not available on this server version.\n" +
"Track progress: " + profile.serverRepo() + "/issues");
} else {
@@ -47,7 +47,7 @@ public class SnapshotLoadCommand implements Callable<Integer> {
printer.println(Ansi.green("Snapshot loaded:") + " " + name);
return 0;
} catch (FlociException e) {
if (e.getMessage().contains("404") || e.getMessage().contains("501")) {
if (e.endpointMissing()) {
printer.error("Snapshot API not available on this server version.\n" +
"Track progress: " + profile.serverRepo() + "/issues");
} else {
@@ -45,12 +45,16 @@ public class SnapshotSaveCommand implements Callable<Integer> {
// so a container started with --port <n> is still found without --endpoint.
String effectiveEndpoint = global.resolvedEndpoint(new DockerClient());
FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile);
if (message != null && !message.isBlank()) {
// The snapshot API contract has no description field yet; say so rather than drop it.
printer.warn("--message is not sent: the snapshot API does not take a description yet.");
}
try {
client.postSnapshot(name);
printer.println(Ansi.green("Snapshot saved:") + " " + name);
return 0;
} catch (FlociException e) {
if (e.getMessage().contains("404") || e.getMessage().contains("501")) {
if (e.endpointMissing()) {
printer.error("Snapshot API not available on this server version.\n" +
"Track progress: " + profile.serverRepo() + "/issues");
} else {
@@ -1,7 +1,29 @@
package io.floci.cli.http;
public class FlociException extends Exception {
private final int status;
public FlociException(String message) {
this(message, 0);
}
/** An error the server answered with HTTP {@code status}. */
public FlociException(String message, int status) {
super(message);
this.status = status;
}
/** The HTTP status the server answered with, or 0 when the failure was not an HTTP response. */
public int status() {
return status;
}
/**
* The server has no such endpoint (404) or does not implement it (501). Asked of the status,
* never of the message: the message carries the request path, and a path can contain "404".
*/
public boolean endpointMissing() {
return status == 404 || status == 501;
}
}
@@ -6,10 +6,12 @@ import io.floci.cli.ProductProfile;
import java.net.ConnectException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpTimeoutException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
@@ -59,11 +61,14 @@ public class FlociHttpClient {
int query = base.indexOf('?');
this.query = query >= 0 ? base.substring(query) : "";
base = query >= 0 ? base.substring(0, query) : base;
this.endpoint = base.endsWith("/") ? base.substring(0, base.length() - 1) : base;
this.endpoint = base.replaceAll("/+$", "");
this.controlPrefix = controlPrefix.endsWith("/")
? controlPrefix.substring(0, controlPrefix.length() - 1)
: controlPrefix;
// HTTP/1.1: the emulators speak it, and the default (HTTP/2) first tries an h2c upgrade on
// every plain-http request. Redirects are not followed; see checkStatus.
this.http = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(5))
.build();
}
@@ -159,7 +164,7 @@ public class FlociHttpClient {
message.contains("not available yet"));
}
if (resp.statusCode() >= 400) {
throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path);
throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path, resp.statusCode());
}
return resp.body();
} catch (FlociException e) {
@@ -171,12 +176,17 @@ public class FlociHttpClient {
}
}
/** Deletes every resource the emulator holds ({@code POST <prefix>/state/reset}). */
public Map<String, Object> resetState() throws FlociException {
return postJson(controlPrefix + "/state/reset", "{}");
}
public Map<String, Object> postSnapshot(String name) throws FlociException {
return postJson(controlPrefix + "/snapshots/" + name, "{}");
return postJson(controlPrefix + "/snapshots/" + snapshotSegment(name), "{}");
}
public Map<String, Object> loadSnapshot(String name) throws FlociException {
return postJson(controlPrefix + "/snapshots/" + name + "/load", "{}");
return postJson(controlPrefix + "/snapshots/" + snapshotSegment(name) + "/load", "{}");
}
public JsonNode listSnapshots() throws FlociException {
@@ -184,7 +194,7 @@ public class FlociHttpClient {
}
public void deleteSnapshot(String name) throws FlociException {
deleteRequest(controlPrefix + "/snapshots/" + name);
deleteRequest(controlPrefix + "/snapshots/" + snapshotSegment(name));
}
private JsonNode getJson(String path) throws FlociException {
@@ -215,10 +225,8 @@ public class FlociHttpClient {
if (e.getCause() instanceof HttpTimeoutException) throw timedOut(path, timeout);
throw new FlociException("Request failed: " + e.getCause().getMessage());
}
if (resp.statusCode() >= 400) {
throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path);
}
return MAPPER.readTree(resp.body());
checkStatus(resp, path);
return readJson(resp.body(), path);
} catch (FlociException e) {
throw e;
} catch (InterruptedException e) {
@@ -246,11 +254,9 @@ public class FlociHttpClient {
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString());
if (resp.statusCode() >= 400) {
throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path);
}
checkStatus(resp, path);
if (resp.body() == null || resp.body().isBlank()) return Map.of();
return MAPPER.readValue(resp.body(), Map.class);
return MAPPER.convertValue(readJson(resp.body(), path), Map.class);
} catch (FlociException e) {
throw e;
} catch (ConnectException e) {
@@ -268,9 +274,7 @@ public class FlociHttpClient {
.DELETE()
.build();
HttpResponse<Void> resp = http.send(req, HttpResponse.BodyHandlers.discarding());
if (resp.statusCode() >= 400) {
throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path);
}
checkStatus(resp, path);
} catch (FlociException e) {
throw e;
} catch (Exception e) {
@@ -285,4 +289,36 @@ public class FlociHttpClient {
private URI url(String path) {
return URI.create(endpoint + path + query);
}
// A redirect usually means --endpoint names a proxy or the wrong address; following it
// silently could send requests elsewhere, so it is reported instead.
private void checkStatus(HttpResponse<?> resp, String path) throws FlociException {
int status = resp.statusCode();
if (status >= 300 && status < 400) {
String location = resp.headers().firstValue("Location").orElse("another address");
throw new FlociException("Server redirected " + path + " to " + location + ".\n"
+ "Point --endpoint at the address Floci listens on.");
}
if (status >= 400) {
throw new FlociException("Server returned HTTP " + status + " for " + path, status);
}
}
private JsonNode readJson(String body, String path) throws FlociException {
try {
return MAPPER.readTree(body);
} catch (Exception e) {
throw new FlociException("The response from " + endpoint + path + " is not JSON, so this may not be a Floci server.\n"
+ "Run '" + commandPrefix + " status' to see the endpoint the emulator answers on.");
}
}
/** A snapshot name as one URL path segment; names that could change the path are refused. */
static String snapshotSegment(String name) throws FlociException {
if (name == null || name.isBlank() || name.equals(".") || name.equals("..") || name.contains("/")) {
throw new FlociException("Invalid snapshot name '" + name + "'.\n"
+ "Use a name that is not '.' or '..' and has no '/'.");
}
return URLEncoder.encode(name, StandardCharsets.UTF_8).replace("+", "%20");
}
}
@@ -29,6 +29,9 @@ public final class UpdateNotifier {
static final Duration TTL = Duration.ofHours(24);
/** How soon a check that did not produce a result (still in flight, or failed) is tried again. */
static final Duration RETRY_AFTER = Duration.ofHours(1);
private static final ObjectMapper JSON = new ObjectMapper();
/** The in-flight refresh, if this run started one; lets main() grant it a short grace. */
@@ -74,22 +77,54 @@ public final class UpdateNotifier {
if (cache.isPresent() && !isStale(cache.get())) {
return;
}
// Virtual threads do not keep the JVM alive: a quick exit just drops the check and it
// is retried next time; main() grants a short grace via awaitRefresh so commands that
// finish fast still get the cache populated eventually.
// Virtual threads do not keep the JVM alive: a quick exit just drops the check; main()
// grants a short grace via awaitRefresh so commands that finish fast still get the cache
// populated eventually.
REFRESH.set(Thread.ofVirtual().name("floci-update-check").start(() -> {
// The attempt is recorded before the request, not after it fails: a request that is
// still waiting when the command exits never reaches a catch block, and every run
// would start it again and wait at exit.
if (!recordAttempt()) {
return; // another process got there first
}
try {
String latest = fetchLatestVersion(latestReleaseUrl);
Path path = cachePath();
Files.createDirectories(path.getParent());
JSON.writeValue(path.toFile(),
new UpdateCache(Instant.now().getEpochSecond(), latest));
write(new UpdateCache(Instant.now().getEpochSecond(), latest));
} catch (Exception _) {
// Network/parse failure — never surfaced; the stale/absent cache stays as-is.
// Network/parse failure, never surfaced. The attempt is already on record.
}
}));
}
/**
* Marks the cache as "checked, try again in {@link #RETRY_AFTER}", keeping the last known
* version. The file is read again right before the write: another process may have finished
* a check since this one found the cache stale, and its result (or its own attempt) stands.
*
* @return false when the cache is no longer stale, so there is nothing left to check
*/
static boolean recordAttempt() {
try {
Optional<UpdateCache> onDisk = readQuietly();
if (onDisk.isPresent() && !isStale(onDisk.get())) {
return false;
}
// Backdated so the entry turns stale again after RETRY_AFTER rather than a full TTL:
// an attempt is not a result.
long checkedAt = Instant.now().minus(TTL).plus(RETRY_AFTER).getEpochSecond();
write(new UpdateCache(checkedAt, onDisk.map(UpdateCache::latestVersion).orElse(null)));
} catch (Exception _) {
// An unwritable cache must not stop the check itself.
}
return true;
}
private static void write(UpdateCache cache) throws Exception {
Path path = cachePath();
Files.createDirectories(path.getParent());
JSON.writeValue(path.toFile(), cache);
}
/** Give an in-flight refresh a bounded chance to finish before the JVM exits. */
public static void awaitRefresh(Duration grace) {
Thread refresh = REFRESH.get();
@@ -0,0 +1,99 @@
package io.floci.cli.unit;
import com.sun.net.httpserver.HttpServer;
import io.floci.cli.http.FlociException;
import io.floci.cli.http.FlociHttpClient;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
/** BL-047: what FlociHttpClient sends, and how it reports responses that are not what it expects. */
class FlociHttpClientRobustnessTest {
private HttpServer server;
private final AtomicReference<String> lastPath = new AtomicReference<>();
private final AtomicInteger status = new AtomicInteger(200);
private final AtomicReference<String> body = new AtomicReference<>("{\"version\":\"1.0\",\"services\":[]}");
private final AtomicReference<String> location = new AtomicReference<>();
@BeforeEach
void start() throws Exception {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
lastPath.set(exchange.getRequestURI().getRawPath());
if (location.get() != null) exchange.getResponseHeaders().add("Location", location.get());
byte[] bytes = body.get().getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(status.get(), bytes.length == 0 ? -1 : bytes.length);
if (bytes.length > 0) {
try (OutputStream out = exchange.getResponseBody()) {
out.write(bytes);
}
}
exchange.close();
});
server.start();
}
@AfterEach
void stop() {
server.stop(0);
}
private String endpoint() {
return "http://127.0.0.1:" + server.getAddress().getPort();
}
@Test
void everyTrailingSlashIsStripped() throws Exception {
new FlociHttpClient(endpoint() + "///", "/_floci").health();
assertEquals("/_floci/health", lastPath.get());
}
@Test
void aBodyThatIsNotJsonIsReportedAsSuch() {
body.set("OK");
FlociException e = assertThrows(FlociException.class, () -> new FlociHttpClient(endpoint(), "/_floci").health());
assertTrue(e.getMessage().contains("is not JSON"), e.getMessage());
}
@Test
void aRedirectIsReportedNotFollowed() {
status.set(302);
body.set("");
location.set("http://elsewhere.example/_floci/health");
FlociException e = assertThrows(FlociException.class, () -> new FlociHttpClient(endpoint(), "/_floci").health());
assertTrue(e.getMessage().contains("redirected"), e.getMessage());
assertTrue(e.getMessage().contains("elsewhere.example"), e.getMessage());
}
@Test
void snapshotNamesAreOnePathSegment() throws Exception {
status.set(204);
body.set("");
new FlociHttpClient(endpoint(), "/_floci").deleteSnapshot("my snap?x");
assertEquals("/_floci/snapshots/my%20snap%3Fx", lastPath.get());
}
@Test
void snapshotNamesThatWouldChangeThePathAreRefused() {
FlociHttpClient client = new FlociHttpClient(endpoint(), "/_floci");
for (String bad : new String[]{"..", ".", "a/b", "../escape"}) {
FlociException e = assertThrows(FlociException.class, () -> client.deleteSnapshot(bad), bad);
assertTrue(e.getMessage().contains("Invalid snapshot name"), e.getMessage());
}
assertNull(lastPath.get(), "nothing reached the server");
}
}
@@ -19,7 +19,7 @@ class ProductTreesParsingTest {
private static final Set<String> LIFECYCLE_COMMANDS = Set.of(
"start", "stop", "restart", "status", "logs", "wait",
"version", "services", "doctor", "env", "config", "snapshot", "completion", "help");
"version", "services", "reset", "doctor", "env", "config", "snapshot", "completion", "help");
private static CommandSpec leafSpec(String... args) {
ParseResult r = new CommandLine(new FlociCli()).parseArgs(args);
@@ -43,6 +43,7 @@ class ProductTreesParsingTest {
void awsTreeDefaults() {
assertDefaults("http://localhost:4566", "floci", "status");
assertDefaults("http://localhost:4566", "floci", "aws", "status");
assertDefaults("http://localhost:4566", "floci", "reset");
assertStartDefaults("4566", "floci/floci:latest", "start");
assertStartDefaults("4566", "floci/floci:latest", "aws", "start");
}
@@ -50,18 +51,21 @@ class ProductTreesParsingTest {
@Test
void gcpTreeDefaults() {
assertDefaults("http://localhost:4588", "floci-gcp", "gcp", "status");
assertDefaults("http://localhost:4588", "floci-gcp", "gcp", "reset");
assertStartDefaults("4588", "floci/floci-gcp:latest", "gcp", "start");
}
@Test
void azTreeDefaults() {
assertDefaults("http://localhost:4577", "floci-az", "az", "status");
assertDefaults("http://localhost:4577", "floci-az", "az", "reset");
assertStartDefaults("4577", "floci/floci-az:latest", "az", "start");
}
@Test
void ociTreeDefaults() {
assertDefaults("http://localhost:4599", "floci-oci", "oci", "status");
assertDefaults("http://localhost:4599", "floci-oci", "oci", "reset");
assertStartDefaults("4599", "floci/floci-oci:latest", "oci", "start");
}
@@ -0,0 +1,39 @@
package io.floci.cli.unit;
import io.floci.cli.FlociCli;
import io.floci.cli.config.ProfileStore;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import picocli.CommandLine;
import picocli.CommandLine.UnmatchedArgumentException;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.*;
/**
* BL-051, BL-052: doctor --fix fixed nothing and services --mode filtered nothing, so both were
* removed rather than kept as promises. They stay rejected in every product tree.
*/
class RemovedFlagsTest {
@TempDir
Path tempDir;
private CommandLine cli() {
return FlociCli.buildCommandLine(new ProfileStore(tempDir));
}
@ParameterizedTest
@ValueSource(strings = {"aws", "gcp", "az", "oci"})
void doctorHasNoFixFlag(String product) {
assertThrows(UnmatchedArgumentException.class, () -> cli().parseArgs(product, "doctor", "--fix"));
}
@ParameterizedTest
@ValueSource(strings = {"aws", "gcp", "az", "oci"})
void servicesHasNoModeFlag(String product) {
assertThrows(UnmatchedArgumentException.class, () -> cli().parseArgs(product, "services", "--mode", "docker"));
}
}
@@ -0,0 +1,383 @@
package io.floci.cli.unit;
import com.sun.net.httpserver.HttpServer;
import io.floci.cli.FlociCli;
import io.floci.cli.ProductProfile;
import io.floci.cli.commands.ResetCommand;
import io.floci.cli.config.ProfileDefaultValueProvider;
import io.floci.cli.config.ProfileStore;
import io.floci.cli.docker.DockerClient;
import io.floci.cli.docker.DockerException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import picocli.CommandLine;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
/** BL-064: floci reset against a stub emulator. */
class ResetCommandTest {
@TempDir
Path tempDir;
private HttpServer server;
private final List<String> requests = new CopyOnWriteArrayList<>();
private final AtomicInteger status = new AtomicInteger(200);
private record Run(int exit, String out, String err) {}
@BeforeEach
void start() throws Exception {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
requests.add(exchange.getRequestMethod() + " " + exchange.getRequestURI().getPath());
byte[] body = "{\"status\":\"OK\"}".getBytes(StandardCharsets.UTF_8);
if (status.get() == 200) {
exchange.sendResponseHeaders(200, body.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(body);
}
} else {
exchange.sendResponseHeaders(status.get(), -1);
}
exchange.close();
});
server.start();
}
@AfterEach
void stop() {
server.stop(0);
}
private Run run(String... args) {
List<String> all = new ArrayList<>(List.of(args));
all.addAll(List.of("--endpoint", "http://127.0.0.1:" + server.getAddress().getPort(),
"--container", "floci-reset-test-none"));
PrintStream out = System.out;
PrintStream err = System.err;
ByteArrayOutputStream outBuf = new ByteArrayOutputStream();
ByteArrayOutputStream errBuf = new ByteArrayOutputStream();
System.setOut(new PrintStream(outBuf));
System.setErr(new PrintStream(errBuf));
try {
int exit = FlociCli.buildCommandLine(new ProfileStore(tempDir)).execute(all.toArray(String[]::new));
return new Run(exit, outBuf.toString(), errBuf.toString());
} finally {
System.setOut(out);
System.setErr(err);
}
}
@Test
void yesPostsToTheProductsResetEndpoint() {
Run r = run("gcp", "reset", "--yes");
assertEquals(0, r.exit(), r.err());
assertEquals(List.of("POST /_floci-gcp/state/reset"), requests);
assertTrue(r.out().contains("state reset"), r.out());
}
@Test
void structuredOutputReportsTheReset() {
Run r = run("reset", "-y", "-o", "json");
assertEquals(0, r.exit(), r.err());
assertEquals(List.of("POST /_floci/state/reset"), requests);
assertTrue(r.out().contains("\"reset\" : true") || r.out().contains("\"reset\":true"), r.out());
}
/** Nobody to ask: without --yes nothing is deleted and the exit code says it was a usage problem. */
@Test
void withoutATerminalItNeedsYes() {
Run r = run("oci", "reset");
assertEquals(2, r.exit());
assertTrue(r.err().contains("Pass --yes"), r.err());
assertEquals(List.of(), requests, "nothing was reset");
}
@Test
void aServerWithoutTheEndpointSaysResetIsNotAvailable() {
status.set(404);
Run r = run("az", "reset", "--yes");
assertEquals(1, r.exit());
assertTrue(r.err().contains("not available"), r.err());
assertTrue(r.err().contains("floci-az"), r.err());
}
// ---- which server a reset acts on -------------------------------------------------------
private static DockerClient dockerWith(String name, String state, String ports) {
return new DockerClient() {
@Override
public Optional<ContainerInfo> inspectContainer(String asked) {
return asked.equals(name)
? Optional.of(new ContainerInfo("abc", name, "floci/floci:latest", state, ports))
: Optional.empty();
}
};
}
private static final ResetCommand.Prompt NOBODY = new ResetCommand.Prompt() {
@Override
public boolean available() {
return false;
}
@Override
public String ask(String question) {
throw new AssertionError("nobody to ask");
}
};
private static ResetCommand.Target targetOf(DockerClient docker, String... args) {
ResetCommand reset = new ResetCommand(ProductProfile.AWS, docker, NOBODY);
new CommandLine(reset).parseArgs(args);
return reset.target();
}
/** A typed --endpoint is the server to reset, even with a local container of the same name running. */
@Test
void aTypedEndpointIsNeverReplacedByALocalContainer() {
DockerClient local = dockerWith("floci", "running", "14566->4566/tcp");
ResetCommand.Target target = targetOf(local, "--endpoint", "http://remote-host:4566");
assertEquals("http://remote-host:4566", target.endpoint());
assertNull(target.error());
}
@Test
void theDefaultContainerIsFoundThroughItsPortMapping() {
ResetCommand.Target target = targetOf(dockerWith("floci", "running", "14566->4566/tcp"));
assertEquals("http://localhost:14566", target.endpoint());
}
/** A container the user chose and that is not there must not fall back to the default instance. */
@Test
void aChosenContainerThatIsMissingResetsNothing() {
ResetCommand.Target target = targetOf(dockerWith("floci", "running", "4566->4566/tcp"),
"--container", "floci-team-b");
assertNull(target.endpoint());
assertTrue(target.error().contains("Container 'floci-team-b' not found, so nothing was reset."), target.error());
assertTrue(target.error().contains("floci status --container floci-team-b"), target.error());
assertTrue(target.error().contains("--endpoint <url>"), target.error());
}
/** A stopped container has no port mapping; the fallback would again be the default instance. */
@Test
void aChosenContainerThatIsStoppedResetsNothing() {
ResetCommand.Target target = targetOf(dockerWith("floci-team-b", "exited", ""), "--container", "floci-team-b");
assertNull(target.endpoint());
assertTrue(target.error().contains("is not running (state: exited)"), target.error());
}
/**
* Running, but with no published port for the emulator (or only an unrelated one): there is
* nothing to find it by, and the configured endpoint may be the default instance.
*/
@ParameterizedTest
@ValueSource(strings = {"", "18080->8080/tcp"})
void aChosenContainerWithoutAMatchingPortResetsNothing(String ports) {
ResetCommand.Target target = targetOf(dockerWith("floci-team-b", "running", ports), "--container", "floci-team-b");
assertNull(target.endpoint());
assertTrue(target.error().contains("publishes no port for the emulator, so nothing was reset."), target.error());
}
@Test
void aChosenContainerIsFoundThroughItsPortMapping() {
ResetCommand.Target target = targetOf(dockerWith("floci-team-b", "running", "14566->4566/tcp"),
"--container", "floci-team-b");
assertEquals("http://localhost:14566", target.endpoint());
}
/**
* An instance on its own host port: the profile's endpoint names that host port (14566), the
* container still listens on the emulator's (4566). It is found by the latter.
*/
@Test
void anInstanceOnACustomHostPortIsFoundByTheEmulatorsPort() throws Exception {
Files.createDirectories(tempDir);
Files.writeString(tempDir.resolve("team-b.yaml"),
"container: floci-team-b\nendpoint: http://localhost:14566\nport: 14566\n");
ResetCommand reset = new ResetCommand(ProductProfile.AWS,
dockerWith("floci-team-b", "running", "14566->4566/tcp"), NOBODY);
new CommandLine(reset)
.setDefaultValueProvider(new ProfileDefaultValueProvider(new ProfileStore(tempDir)))
.parseArgs("--profile", "team-b");
ResetCommand.Target target = reset.target();
assertNull(target.error(), target.error());
assertEquals("http://localhost:14566", target.endpoint());
}
@Test
void theOtherProductsAreFoundByTheirOwnPort() {
ResetCommand gcp = new ResetCommand(ProductProfile.GCP, dockerWith("floci-gcp-b", "running", "14588->4588/tcp"), NOBODY);
new CommandLine(gcp).parseArgs("--container", "floci-gcp-b");
assertEquals("http://localhost:14588", gcp.target().endpoint());
}
/** The default container without a published port (host networking) is still the default instance. */
@Test
void theDefaultContainerWithoutAPublishedPortUsesItsConfiguredEndpoint() {
ResetCommand.Target target = targetOf(dockerWith("floci", "running", ""));
assertEquals("http://localhost:4566", target.endpoint());
}
@Test
void aChosenContainerDockerCannotLookUpResetsNothing() {
DockerClient broken = new DockerClient() {
@Override
public Optional<ContainerInfo> inspectContainer(String name) throws DockerException {
throw new DockerException("Cannot connect to the Docker daemon");
}
};
ResetCommand.Target target = targetOf(broken, "--container", "floci-team-b");
assertNull(target.endpoint());
assertTrue(target.error().contains("Cannot connect to the Docker daemon"), target.error());
}
@Test
void aChosenContainerWithATypedEndpointUsesTheEndpoint() {
ResetCommand.Target target = targetOf(dockerWith("floci", "running", "4566->4566/tcp"),
"--container", "floci-team-b", "--endpoint", "http://localhost:14577");
assertEquals("http://localhost:14577", target.endpoint());
}
/** Without any selection the default instance is meant, also when it runs outside a 'floci' container. */
@Test
void theDefaultInstanceFallsBackToItsConfiguredEndpoint() {
ResetCommand.Target target = targetOf(dockerWith("something-else", "running", ""));
assertEquals("http://localhost:4566", target.endpoint());
}
@Test
void aMissingChosenContainerSendsNoRequest() {
ResetCommand reset = new ResetCommand(ProductProfile.AWS, dockerWith("floci", "running", "4566->4566/tcp"), NOBODY);
Run r = execute(reset, "--yes", "--container", "floci-team-b");
assertEquals(1, r.exit());
assertTrue(r.err().contains("nothing was reset"), r.err());
assertEquals(List.of(), requests);
}
// ---- the confirmation --------------------------------------------------------------------
private static ResetCommand.Prompt answering(String answer, List<String> asked) {
return new ResetCommand.Prompt() {
@Override
public boolean available() {
return true;
}
@Override
public String ask(String question) {
asked.add(question);
return answer;
}
};
}
private Run execute(ResetCommand reset, String... args) {
PrintStream out = System.out;
PrintStream err = System.err;
ByteArrayOutputStream outBuf = new ByteArrayOutputStream();
ByteArrayOutputStream errBuf = new ByteArrayOutputStream();
System.setOut(new PrintStream(outBuf));
System.setErr(new PrintStream(errBuf));
try {
int exit = new CommandLine(reset).execute(args);
return new Run(exit, outBuf.toString(), errBuf.toString());
} finally {
System.setOut(out);
System.setErr(err);
}
}
private Run confirmWith(String answer, List<String> asked) {
ResetCommand reset = new ResetCommand(ProductProfile.AWS, dockerWith("none", "running", ""), answering(answer, asked));
return execute(reset, "--endpoint", "http://127.0.0.1:" + server.getAddress().getPort());
}
/** Anything but a yes deletes nothing: a no, a bare Enter, something else. */
@ParameterizedTest
@ValueSource(strings = {"n", "N", "no", "", " ", "yep", "y es"})
void decliningSendsNoRequest(String answer) {
List<String> asked = new ArrayList<>();
Run r = confirmWith(answer, asked);
assertEquals(1, r.exit());
assertEquals(List.of(), requests, "nothing was reset");
assertTrue(r.out().contains("Reset cancelled."), r.out());
assertEquals(1, asked.size());
}
/** End of input (Ctrl-D) is not a yes. */
@Test
void endOfInputSendsNoRequest() {
Run r = confirmWith(null, new ArrayList<>());
assertEquals(1, r.exit());
assertEquals(List.of(), requests, "nothing was reset");
}
@ParameterizedTest
@ValueSource(strings = {"y", "Y", "yes", "YES", " yes "})
void confirmingSendsExactlyOneRequest(String answer) {
List<String> asked = new ArrayList<>();
Run r = confirmWith(answer, asked);
assertEquals(0, r.exit(), r.err());
assertEquals(List.of("POST /_floci/state/reset"), requests);
assertTrue(asked.get(0).contains("http://127.0.0.1:" + server.getAddress().getPort()), asked.get(0));
}
/** --yes asks nobody. */
@Test
void yesDoesNotAsk() {
List<String> asked = new ArrayList<>();
ResetCommand reset = new ResetCommand(ProductProfile.AWS, dockerWith("none", "running", ""), answering("n", asked));
Run r = execute(reset, "--yes", "--endpoint", "http://127.0.0.1:" + server.getAddress().getPort());
assertEquals(0, r.exit(), r.err());
assertEquals(List.of(), asked);
assertEquals(List.of("POST /_floci/state/reset"), requests);
}
}
@@ -0,0 +1,106 @@
package io.floci.cli.unit;
import com.sun.net.httpserver.HttpServer;
import io.floci.cli.FlociCli;
import io.floci.cli.config.ProfileStore;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.*;
/** BL-048: the snapshot commands against a server that has no snapshot API (404). */
class SnapshotCommandsTest {
@TempDir
Path tempDir;
private HttpServer server;
private volatile int status = 404;
@BeforeEach
void start() throws Exception {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
exchange.sendResponseHeaders(status, -1);
exchange.close();
});
server.start();
}
@AfterEach
void stop() {
server.stop(0);
}
private String[] run(String... args) {
String[] all = new String[args.length + 4];
System.arraycopy(args, 0, all, 0, args.length);
all[args.length] = "--endpoint";
all[args.length + 1] = "http://127.0.0.1:" + server.getAddress().getPort();
all[args.length + 2] = "--container";
all[args.length + 3] = "floci-snapshot-test-none";
PrintStream out = System.out;
PrintStream err = System.err;
ByteArrayOutputStream outBuf = new ByteArrayOutputStream();
ByteArrayOutputStream errBuf = new ByteArrayOutputStream();
System.setOut(new PrintStream(outBuf));
System.setErr(new PrintStream(errBuf));
try {
int exit = FlociCli.buildCommandLine(new ProfileStore(tempDir)).execute(all);
return new String[]{String.valueOf(exit), outBuf.toString(), errBuf.toString()};
} finally {
System.setOut(out);
System.setErr(err);
}
}
@Test
void deleteSaysTheApiIsMissingLikeSaveAndLoad() {
String[] r = run("snapshot", "delete", "nightly");
assertEquals("1", r[0]);
assertTrue(r[2].contains("Snapshot API not available"), r[2]);
}
@Test
void aMessageIsNotDroppedSilently() {
String[] r = run("snapshot", "save", "nightly", "-m", "before upgrade");
assertTrue(r[2].contains("--message is not sent"), r[2]);
}
/**
* Only the status says the API is missing. A name that happens to contain "404" or "501" must
* not turn a real server error into "not available".
*/
@ParameterizedTest
@CsvSource({"delete, nightly404", "save, build-501", "load, 404"})
void aStatusLookingNameDoesNotHideARealError(String command, String name) {
status = 500;
String[] r = run("snapshot", command, name);
assertEquals("1", r[0]);
assertFalse(r[2].contains("Snapshot API not available"), r[2]);
assertTrue(r[2].contains("HTTP 500"), r[2]);
}
@ParameterizedTest
@CsvSource({"404", "501"})
void bothMissingEndpointStatusesReadAsNotAvailable(int missing) {
status = missing;
String[] r = run("snapshot", "delete", "nightly");
assertTrue(r[2].contains("Snapshot API not available"), r[2]);
}
}
@@ -227,4 +227,33 @@ class UpdateCommandTest {
assertEquals(1, downloads.size(), downloads.toString());
assertTrue(downloads.get(0).startsWith("/download/98.0.0/floci-"), downloads.toString());
}
/** --check tells "the check failed" (2) from "an update is available" (1). */
@Test
void aCheckThatCannotBeMadeExitsTwo() throws Exception {
Path binary = installed(tempDir.resolve("bin"));
latest.set("{}");
Run r = update(binary, "--check");
assertEquals(2, r.exit());
assertTrue(r.err().contains("cannot determine the latest version"), r.err());
assertEquals(List.of(), downloads);
}
/** The whole update through a symlinked install: the real file is replaced, the link stays a link. */
@Test
void anInstallBehindASymlinkIsUpdatedInPlace() throws Exception {
Path real = installed(tempDir.resolve("opt"));
Path link = Files.createSymbolicLink(Files.createDirectories(tempDir.resolve("bin")).resolve("floci"), real);
Run r = update(link);
assertEquals(0, r.exit(), r.err());
assertTrue(Files.isSymbolicLink(link), "the link is still a link");
assertArrayEquals(FRESH, Files.readAllBytes(real));
try (var left = Files.list(real.getParent())) {
assertEquals(List.of("floci"), left.map(p -> p.getFileName().toString()).toList(), "no staging file left behind");
}
}
}
@@ -0,0 +1,114 @@
package io.floci.cli.unit;
import io.floci.cli.commands.UpdateCommand;
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 picocli.CommandLine;
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 static org.junit.jupiter.api.Assertions.*;
/** BL-049: which release asset floci update picks for the machine it runs on. */
class UpdatePlatformTest {
@Test
void picksTheAssetForEachPublishedPlatform() {
assertEquals("darwin-arm64", UpdateCommand.detectPlatform("Mac OS X", "aarch64", () -> true));
assertEquals("linux-amd64", UpdateCommand.detectPlatform("Linux", "amd64", () -> false));
assertEquals("linux-arm64", UpdateCommand.detectPlatform("Linux", "aarch64", () -> false));
}
/** An x86 build under Rosetta must move to the arm64 build, not stay x86 forever. */
@Test
void anX86BuildOnAppleSiliconUpdatesToArm64() {
assertEquals("darwin-arm64", UpdateCommand.detectPlatform("Mac OS X", "x86_64", () -> true));
assertEquals("darwin-amd64", UpdateCommand.detectPlatform("Mac OS X", "x86_64", () -> false));
}
@Test
void windowsPointsAtTheInstaller() {
RuntimeException e = assertThrows(RuntimeException.class,
() -> UpdateCommand.detectPlatform("Windows 11", "amd64", () -> false));
assertTrue(e.getMessage().contains("install.ps1"), e.getMessage());
}
/** An invalid --version is refused before it reaches a download URL; --check reports it as 2. */
@Test
void anInvalidVersionIsAFailedCheck() {
PrintStream err = System.err;
PrintStream out = System.out;
ByteArrayOutputStream errBuf = new ByteArrayOutputStream();
System.setErr(new PrintStream(errBuf));
System.setOut(new PrintStream(new ByteArrayOutputStream()));
int exit;
try {
exit = new CommandLine(new UpdateCommand()).execute("--check", "--version", "../../evil");
} finally {
System.setErr(err);
System.setOut(out);
}
assertEquals(2, exit);
assertTrue(errBuf.toString().contains("invalid --version"), errBuf.toString());
}
/**
* An install reached through a symlink (~/bin/floci -> /opt/floci/floci): the update replaces
* the file the link points at and leaves the link a link.
*/
@Test
@DisabledOnOs(OS.WINDOWS)
void updatingThroughASymlinkReplacesItsTargetAndKeepsTheLink(@TempDir Path dir) throws Exception {
Path real = Files.writeString(Files.createDirectories(dir.resolve("opt")).resolve("floci"), "old");
Path link = Files.createSymbolicLink(Files.createDirectories(dir.resolve("bin")).resolve("floci"), real);
Path fresh = Files.writeString(dir.resolve("download"), "new");
Path binary = UpdateCommand.realExecutable(link);
UpdateCommand.replaceAtomically(fresh, binary);
assertEquals(real.toRealPath(), binary);
assertTrue(Files.isSymbolicLink(link), "the link is still a link");
assertEquals(real.toRealPath(), link.toRealPath());
assertEquals("new", Files.readString(real));
assertEquals("new", Files.readString(link));
try (var files = Files.list(real.getParent())) {
assertEquals(List.of("floci"), files.map(p -> p.getFileName().toString()).toList(), "no staging file left");
}
}
@Test
void anExecutableThatCannotBeFoundIsReportedWithAWayOut(@TempDir Path dir) {
RuntimeException e = assertThrows(RuntimeException.class,
() -> UpdateCommand.realExecutable(dir.resolve("gone")));
assertTrue(e.getMessage().contains("cannot locate the running executable"), e.getMessage());
assertTrue(e.getMessage().contains("install.sh"), e.getMessage());
}
/** A probe that stalls with its output still open is cut off at the limit, and killed. */
@Test
@DisabledOnOs(OS.WINDOWS)
void aStalledProbeGivesUpAtItsLimit() throws Exception {
long start = System.nanoTime();
String out = UpdateCommand.probe(Duration.ofMillis(300), "sh", "-c", "echo 1; exec sleep 30");
long elapsedMs = (System.nanoTime() - start) / 1_000_000;
assertNull(out);
assertTrue(elapsedMs < 3_000, "took " + elapsedMs + " ms");
}
@Test
@DisabledOnOs(OS.WINDOWS)
void aProbeThatFinishesReturnsItsOutput() throws Exception {
assertEquals("1", UpdateCommand.probe(Duration.ofSeconds(5), "sh", "-c", "echo 1"));
}
}
@@ -0,0 +1,154 @@
package io.floci.cli.update;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
/** BL-026: a failed check is recorded too, so the next run does not retry and wait again. */
class UpdateNotifierTest {
@TempDir
Path home;
private String realHome;
@BeforeEach
void pointHomeAtATempDir() {
realHome = System.getProperty("user.home");
System.setProperty("user.home", home.toString());
}
@AfterEach
void restoreHome() {
System.setProperty("user.home", realHome);
}
private Path cache;
private void writeCache(Instant checkedAt, String version) throws Exception {
cache = home.resolve(".floci").resolve("update-check.json");
Files.createDirectories(cache.getParent());
Files.writeString(cache, "{\"checkedAtEpochSeconds\":" + checkedAt.getEpochSecond()
+ ",\"latestVersion\":" + (version == null ? "null" : "\"" + version + "\"") + "}");
}
private UpdateCache readCache() throws Exception {
return new ObjectMapper().readValue(cache.toFile(), UpdateCache.class);
}
private static boolean staleAt(UpdateCache entry, Instant when) {
return Instant.ofEpochSecond(entry.checkedAtEpochSeconds()).plus(UpdateNotifier.TTL).isBefore(when);
}
// A port that was just bound and released: nothing listens there, so the fetch fails at once.
private static String refusedUrl() throws Exception {
try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
return "http://127.0.0.1:" + socket.getLocalPort() + "/releases/latest";
}
}
@Test
void aFailedCheckIsNotRetriedByTheNextRunAndKeepsTheLastKnownVersion() throws Exception {
writeCache(Instant.now().minus(Duration.ofDays(3)), "0.2.0");
UpdateNotifier.refreshInBackground(refusedUrl());
UpdateNotifier.awaitRefresh(Duration.ofSeconds(5));
UpdateCache written = readCache();
assertEquals("0.2.0", written.latestVersion());
assertFalse(staleAt(written, Instant.now()), "the next run does not check again");
assertTrue(staleAt(written, Instant.now().plus(UpdateNotifier.RETRY_AFTER).plusSeconds(60)),
"but an attempt is not a result: it is tried again after RETRY_AFTER, not a full day");
}
/**
* The attempt is on record before the request is answered. A command that exits while the
* request is still waiting never reaches a failure handler, and would otherwise check again,
* and wait again, on every run.
*/
@Test
void anAttemptIsRecordedWhileTheRequestIsStillWaiting() throws Exception {
writeCache(Instant.now().minus(Duration.ofDays(3)), "0.2.0");
CountDownLatch release = new CountDownLatch(1);
HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
server.createContext("/", exchange -> {
try {
release.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
exchange.close();
});
server.start();
try {
UpdateNotifier.refreshInBackground("http://127.0.0.1:" + server.getAddress().getPort() + "/latest");
UpdateNotifier.awaitRefresh(Duration.ofMillis(250)); // what main() grants a quick command
UpdateCache written = readCache();
assertEquals("0.2.0", written.latestVersion());
assertFalse(staleAt(written, Instant.now()), "recorded although the request has not come back");
} finally {
release.countDown();
server.stop(0);
}
}
/** Another process finished a check in the meantime: its result stands and nothing is overwritten. */
@Test
void anAttemptDoesNotOverwriteAResultAnotherProcessJustWrote() throws Exception {
writeCache(Instant.now(), "0.4.0");
String before = Files.readString(cache);
assertFalse(UpdateNotifier.recordAttempt());
assertEquals(before, Files.readString(cache));
}
@Test
void anAttemptOnAStaleCacheKeepsItsVersionAndAsksToGoOn() throws Exception {
writeCache(Instant.now().minus(Duration.ofDays(3)), "0.2.0");
assertTrue(UpdateNotifier.recordAttempt());
assertEquals("0.2.0", readCache().latestVersion());
}
@Test
void aSuccessfulCheckStoresTheVersionForAFullDay() throws Exception {
writeCache(Instant.now().minus(Duration.ofDays(3)), "0.2.0");
HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
server.createContext("/", exchange -> {
byte[] body = "{\"tag_name\":\"0.4.0\"}".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
server.start();
try {
UpdateNotifier.refreshInBackground("http://127.0.0.1:" + server.getAddress().getPort() + "/latest");
UpdateNotifier.awaitRefresh(Duration.ofSeconds(5));
UpdateCache written = readCache();
assertEquals("0.4.0", written.latestVersion());
assertFalse(staleAt(written, Instant.now().plus(UpdateNotifier.RETRY_AFTER).plusSeconds(60)));
} finally {
server.stop(0);
}
}
}