diff --git a/AGENTS.md b/AGENTS.md index e04bf42..1e7d796 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,19 +42,20 @@ java -jar target/floci.jar `FlociCli` is the Picocli root command. Every subcommand is registered in its `subcommands = {}` array. All commands implement `Callable` and return an exit code. -Bare commands (`floci start`) route to the configured default product (`aws` unless changed via `floci config default-product aws|gcp|az`). Explicit product groups are `floci aws` (same classes as the root tree), `floci gcp`, and `floci az`. +Bare commands (`floci start`) route to the configured default product (`aws` unless changed via `floci config default-product aws|gcp|az|oci`). Explicit product groups are `floci aws` (same classes as the root tree), `floci gcp`, `floci az`, and `floci oci`. -### The three product trees — CRITICAL +### The four product trees — CRITICAL -The GCP (`commands/gcp/`) and Azure (`commands/az/`) command trees are near-verbatim copies of the root/AWS tree (`commands/`), each with its own `GlobalOptions` variant: +The GCP (`commands/gcp/`), Azure (`commands/az/`), and OCI (`commands/oci/`) command trees are near-verbatim copies of the root/AWS tree (`commands/`), each with its own `GlobalOptions` variant: | Tree | Mixin | Default endpoint | Container | Env prefix | Control prefix | |------|-------|------------------|-----------|------------|----------------| | root / `aws` | `GlobalOptions` | `http://localhost:4566` | `floci` | `FLOCI_*` | `/_floci` | | `gcp` | `GcpGlobalOptions` | `http://localhost:4588` | `floci-gcp` | `FLOCI_GCP_*` | `/_floci-gcp` | | `az` | `AzGlobalOptions` | `http://localhost:4577` | `floci-az` | `FLOCI_AZ_*` | `/_floci` (same as AWS — intentional) | +| `oci` | `OciGlobalOptions` | `http://localhost:4599` | `floci-oci` | `FLOCI_OCI_*` | `/_floci-oci` | -**Until the trees are unified: any change to a shared command MUST be applied to all three trees** (e.g. `StartCommand`, `GcpStartCommand`, `AzStartCommand`). Drift between the copies is a known bug source — check the sibling trees before and after editing. Only `EnvCommand`/`GcpEnvCommand`/`AzEnvCommand` are genuinely product-specific. +**Until the trees are unified: any change to a shared command MUST be applied to all four trees** (e.g. `StartCommand`, `GcpStartCommand`, `AzStartCommand`, `OciStartCommand`). Drift between the copies is a known bug source — check the sibling trees before and after editing. Only `EnvCommand`/`GcpEnvCommand`/`AzEnvCommand`/`OciEnvCommand` are genuinely product-specific, plus the OCI-only `OciSetupCommand` (the OCI CLI/SDKs require a config file + signing key, so `floci oci setup` scaffolds them; no other tree needs an equivalent). Commands call `global.printer()` at the start of `call()` — never store a `Printer` as a field. @@ -85,13 +86,13 @@ if (printer.format() != OutputFormat.text) { The structure differs per tree (do not assume they match): - **AWS** (`commands/DoctorCommand.java`): `DOCKER_CHECKS` (static list of the 9 Docker/server checks) + `AWS_COMPANION_CHECKS` (AWS CLI checks), combined via constructor into an instance `allChecks` list. -- **GCP/Azure** (`GcpDoctorCommand`/`AzDoctorCommand`): a single static `ALL_CHECKS` list built in a static initializer. +- **GCP/Azure/OCI** (`GcpDoctorCommand`/`AzDoctorCommand`/`OciDoctorCommand`): a single static `ALL_CHECKS` list built in a static initializer. To add a check: create a class in `doctor/checks/`, then append it to the relevant list(s) — in all trees where it applies. ### Config profiles -`ProfileStore` reads/writes YAML files under `~/.floci/profiles/.yaml` via Jackson. `Profile` is a plain bean — keep it `@JsonIgnoreProperties(ignoreUnknown = true)` to stay forward-compatible. The store is shared by all three product trees (no per-product namespacing). `GlobalConfigStore` persists `~/.floci/config.yaml` (currently just `default-product`). +`ProfileStore` reads/writes YAML files under `~/.floci/profiles/.yaml` via Jackson. `Profile` is a plain bean — keep it `@JsonIgnoreProperties(ignoreUnknown = true)` to stay forward-compatible. The store is shared by all four product trees (no per-product namespacing). `GlobalConfigStore` persists `~/.floci/config.yaml` (currently just `default-product`). ### Self-update @@ -122,7 +123,7 @@ To add a check: create a class in `doctor/checks/`, then append it to the releva - **No cloud resource commands.** This CLI manages Floci itself (lifecycle, config, diagnostics, state). Resource operations belong to the vendor CLIs pointed at the emulator: `aws` + `AWS_ENDPOINT_URL`, `gcloud`/SDK emulator-host vars, `az` + connection string. - **No telemetry, no TUI, no Floci Cloud commands.** - **Self-update is in scope** (`floci update`) — but it must never auto-run; updates happen only on explicit user invocation. -- **Snapshot commands:** the AWS `save/load/list/delete` call `/_floci/snapshots/*` and degrade gracefully (404/501 → "not available"); `export/import` and the entire GCP/Azure snapshot subtrees are stubs pending server-side endpoints in `floci-io/floci`, `floci-io/floci-gcp`, and `floci-io/floci-az`. Do not invent client-side snapshot behavior — the server API contract comes first. +- **Snapshot commands:** the AWS `save/load/list/delete` call `/_floci/snapshots/*` and degrade gracefully (404/501 → "not available"); `export/import` and the entire GCP/Azure/OCI snapshot subtrees are stubs pending server-side endpoints in `floci-io/floci`, `floci-io/floci-gcp`, `floci-io/floci-az`, and `floci-io/floci-oci`. Do not invent client-side snapshot behavior — the server API contract comes first. --- @@ -138,6 +139,6 @@ printer.error("Container 'floci' not found.\nRun 'floci start' to launch one."); ## Documentation Rules -- `README.md` documents all three product trees (AWS, GCP, Azure). If you add/change a command or flag, update the README in the same change. +- `README.md` documents all four product trees (AWS, GCP, Azure, OCI). If you add/change a command or flag, update the README in the same change. - `CHANGELOG.md` follows Keep a Changelog. Every user-visible change gets an entry under `[Unreleased]` in the same PR. - `CLAUDE.md` is gitignored (maintainer-local); this file (`AGENTS.md`) is the tracked source of truth for agent guidance. Update it here. diff --git a/CHANGELOG.md b/CHANGELOG.md index 38f91f4..83e672c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ This project uses [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Added + +- `floci oci` command group — full lifecycle support for the Floci OCI (Oracle Cloud) emulator (`floci-oci`, default port 4599): `start`, `stop`, `restart`, `status`, `logs`, `wait`, `version`, `services`, `doctor`, `env`, `config`, and stub `snapshot` commands, mirroring the GCP/Azure trees. `floci oci env` exports `OCI_CLI_ENDPOINT`, `FLOCI_OCI_ENDPOINT`, and `TF_VAR_CLIENT_HOST_OVERRIDES` for the OCI CLI, the `ocilocal` wrapper, and the `oracle/oci` Terraform provider. `floci config default-product oci` routes bare commands to the OCI tree +- `floci oci setup` — one-step OCI CLI/SDK client setup: generates a local RSA-2048 API signing key (`~/.oci/floci_key.pem`, with the `OCI_API_KEY` label and a real computed fingerprint) and writes a `[FLOCI]` profile to `~/.oci/config` using the emulator's canonical throwaway tenancy. Idempotent; never modifies existing profiles; `--profile-name` overrides the section name. `floci oci env` additionally exports `OCI_CLI_PROFILE` for whichever profile setup wrote (detected via its `key_file`), so `eval $(floci oci env)` is the only connect step needed; env exports are single-quoted per shell so hostile endpoint values cannot inject commands through `eval` +- `FlociHttpClient` now accepts both health-endpoint `services` shapes: the array of names reported by the AWS/GCP/Azure servers and the `{name: status}` object reported by floci-oci (previously the object shape read as zero services in `status`/`services`/`wait`) + ## [0.1.9] — 2026-07-24 ### Added diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d31c7a3..714dbd5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -50,7 +50,7 @@ java -jar target/floci.jar stop ## Architecture -See [AGENTS.md](AGENTS.md) for the architecture: command wiring, the three product trees (AWS/GCP/Azure), the Docker and HTTP I/O boundaries, the output pipeline, native-image constraints, and scope rules. +See [AGENTS.md](AGENTS.md) for the architecture: command wiring, the four product trees (AWS/GCP/Azure/OCI), the Docker and HTTP I/O boundaries, the output pipeline, native-image constraints, and scope rules. `AGENTS.md` is the canonical agent instructions file for this repository, following the [AGENTS.md standard](https://agents.md/). If your coding agent expects a different filename, create a local symlink instead of copying the file: @@ -61,7 +61,7 @@ ln -s AGENTS.md GEMINI.md ### Rules that trip up most PRs -- **Three product trees.** The `gcp` and `az` command trees mirror the root/AWS tree. A change to a shared command (start, stop, status, logs, wait, doctor, …) must be applied to **all three trees** — `StartCommand`, `GcpStartCommand`, and `AzStartCommand` — until they are unified. +- **Four product trees.** The `gcp`, `az`, and `oci` command trees mirror the root/AWS tree. A change to a shared command (start, stop, status, logs, wait, doctor, …) must be applied to **all four trees** — `StartCommand`, `GcpStartCommand`, `AzStartCommand`, and `OciStartCommand` — until they are unified. - **Native image.** New Jackson DTOs must be registered in `reflect-config.json`; prefer passing `Map`/`JsonNode` to `printer.structured(...)`, which needs no registration. No reflection-heavy dependencies. - **Error messages.** Every `printer.error(...)` must end with a suggested next step: diff --git a/README.md b/README.md index ac251b6..ea5d1d5 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # floci-cli -Official command-line interface for [Floci](https://floci.io) — the free, open-source local cloud emulator for AWS, GCP, and Azure. +Official command-line interface for [Floci](https://floci.io) — the free, open-source local cloud emulator for AWS, GCP, Azure, and OCI. ```sh # AWS (default) @@ -17,6 +17,12 @@ gcloud storage buckets create gs://my-bucket floci az start eval $(floci az env) az storage container create --name mycontainer + +# OCI +floci oci start +floci oci setup +eval $(floci oci env) +oci os ns get ``` ## Installation @@ -132,6 +138,30 @@ az storage blob upload --container-name mycontainer --name hello.txt --data "hel floci az stop ``` +### OCI + +```sh +# Start Floci OCI emulator +floci oci start + +# Check environment +floci oci doctor + +# One-time: create a throwaway OCI CLI profile (API key + ~/.oci/config) +floci oci setup + +# Export OCI endpoint variables +eval $(floci oci env) + +# Use OCI services normally +oci os ns get +oci os bucket create --namespace-name floci-local --name my-bucket \ + --compartment-id ocid1.tenancy.oc1..flocilocaltenancy0000000000000000000000000000000000000000 + +# Stop Floci OCI +floci oci stop +``` + ### Switch default product Bare commands like `floci start` route to the configured default product (AWS by default). @@ -139,6 +169,7 @@ Bare commands like `floci start` route to the configured default product (AWS by ```sh floci config default-product gcp # make floci gcp the default floci config default-product az # make floci az the default +floci config default-product oci # make floci oci the default floci config default-product aws # revert to aws ``` @@ -146,7 +177,7 @@ floci config default-product aws # revert to aws ## Command Reference -Commands are organized into three product groups — `floci aws` (or bare `floci`), `floci gcp`, and `floci az`. All groups expose the same lifecycle commands. +Commands are organized into four product groups — `floci aws` (or bare `floci`), `floci gcp`, `floci az`, and `floci oci`. All groups expose the same lifecycle commands. ### Shared commands (product-independent) @@ -155,7 +186,7 @@ Commands are organized into three product groups — `floci aws` (or bare `floci | `floci config show` | Show active configuration | | `floci config validate` | Validate a docker-compose.yml | | `floci config profile` | Manage named profiles | -| `floci config default-product` | Set the default product (aws, gcp, or az) | +| `floci config default-product` | Set the default product (aws, gcp, az, or oci) | | `floci update` | Self-update the CLI to the latest release | | `floci completion bash\|zsh` | Generate shell completion scripts | | `floci update` | Update the CLI to the latest release | @@ -208,6 +239,23 @@ Commands are organized into three product groups — `floci aws` (or bare `floci | `floci az env` | Print Azure connection string / SDK env vars | | `floci az snapshot` | Snapshot commands (coming soon) | +### OCI commands (`floci oci`) + +| Command | Description | +|---------|-------------| +| `floci oci start` | Launch the Floci OCI container | +| `floci oci stop` | Stop (and optionally remove) the container | +| `floci oci restart` | Stop then start | +| `floci oci status` | Show container state and server health | +| `floci oci logs` | Stream container logs | +| `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 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`) | +| `floci oci snapshot` | Snapshot commands (coming soon) | + All commands support `--help`. --- @@ -250,6 +298,18 @@ All commands support `--help`. --profile Load settings from ~/.floci/profiles/.yaml ``` +### OCI global flags + +``` +--endpoint Floci OCI server URL (default: http://localhost:4599, env: FLOCI_OCI_ENDPOINT) +--container Container name (default: floci-oci, env: FLOCI_OCI_CONTAINER) +--output|-o text|json|yaml Output format (default: text) +--quiet, -q Suppress non-error output +--verbose, -v Debug logging to stderr +--no-color Disable ANSI colors +--profile Load settings from ~/.floci/profiles/.yaml +``` + > **Port auto-detection** — `status`, `version`, `wait`, and `env` automatically derive the correct > endpoint from the container's port mapping. You don't need to pass `--endpoint` when using > a non-default port, as long as `--container` points to the right container. @@ -258,14 +318,14 @@ All commands support `--help`. ## Commands -### `floci start` / `floci gcp start` / `floci az start` +### `floci start` / `floci gcp start` / `floci az start` / `floci oci start` Pulls the image (if needed), starts the container, and waits for readiness. ```sh # AWS floci start # default port 4566 -floci start --port 4599 # custom host port +floci start --port 4567 # custom host port floci start --services s3,dynamodb # enable specific services floci start --persist ./data # persist state to a host directory floci start --pull always # always pull the latest image @@ -279,6 +339,10 @@ floci gcp start --persist ./data # persist state to a host directory floci az start # default port 4577 floci az start --port 4578 # custom host port floci az start --persist ./data # persist state to a host directory + +# OCI +floci oci start # default port 4599 +floci oci start --persist ./data # persist state to a host directory ``` #### Docker daemon resolution (Podman, rootless, remote contexts) @@ -313,7 +377,7 @@ For a `unix://` socket the resolved path is bind-mounted into the container; for remote `tcp://` daemon the `DOCKER_HOST` value is passed through to the container instead. Run `floci doctor` to see which endpoint was resolved. -### `floci stop` / `floci gcp stop` / `floci az stop` +### `floci stop` / `floci gcp stop` / `floci az stop` / `floci oci stop` ```sh floci stop # graceful stop (10s timeout) @@ -321,7 +385,7 @@ floci stop --timeout 30 # wait up to 30s before force-kill floci stop --remove # also remove the container after stopping ``` -### `floci status` / `floci gcp status` / `floci az status` +### `floci status` / `floci gcp status` / `floci az status` / `floci oci status` ```sh floci status # auto-detects endpoint from container port mapping @@ -408,7 +472,46 @@ floci az env -o json # structured output | `AZURE_APP_CONFIGURATION_ENDPOINT` | `http://localhost.floci.io:/devstoreaccount1-appconfig` | | `AZURE_KEY_VAULT_ENDPOINT` | `http://localhost.floci.io:/devstoreaccount1-keyvault` | -### `floci logs` / `floci gcp logs` / `floci az logs` +### `floci oci env` + +Prints OCI endpoint variables for the running Floci OCI instance. OCI SDKs and the +`oci` CLI take a single endpoint for every service, so no per-service variables are needed. + +```sh +eval $(floci oci env) # endpoint vars for CLI, wrappers, and Terraform + +floci oci env --shell fish | source # fish +floci oci env -o json # structured output +``` + +Variables exported: + +| Variable | Purpose | +|----------|---------| +| `OCI_CLI_ENDPOINT` | Default `--endpoint` for the `oci` CLI | +| `FLOCI_OCI_ENDPOINT` | Used by this CLI and the `ocilocal` wrapper | +| `TF_VAR_CLIENT_HOST_OVERRIDES` | Per-client host overrides for the `oracle/oci` Terraform provider | +| `OCI_CLI_PROFILE` | The profile `floci oci setup` wrote (default `FLOCI`) — only exported when detected in `~/.oci/config`, and skipped for `DEFAULT` | + +### `floci oci setup` + +The OCI CLI and SDKs refuse to run without a config file and an API signing key — even +against an emulator that never validates them. `floci oci setup` creates both in one step: +a locally generated RSA-2048 key at `~/.oci/floci_key.pem` and a `[FLOCI]` profile in +`~/.oci/config` with the emulator's canonical throwaway tenancy. Existing profiles are +never touched; re-running is a no-op. + +```sh +floci oci setup # create key + [FLOCI] profile +floci oci setup --profile-name DEFAULT # write a different profile section +floci oci setup -o json # structured output + +# then connect: +eval $(floci oci env) # exports OCI_CLI_PROFILE=FLOCI too +oci os ns get +``` + +### `floci logs` / `floci gcp logs` / `floci az logs` / `floci oci logs` ```sh floci logs # last logs from the container @@ -417,7 +520,7 @@ floci logs --since 5m # logs from the last 5 minutes floci logs --follow # stream live logs (Ctrl-C to stop) ``` -### `floci wait` / `floci gcp wait` / `floci az wait` +### `floci wait` / `floci gcp wait` / `floci az wait` / `floci oci wait` ```sh floci wait # wait up to 30s (default) @@ -426,7 +529,7 @@ floci wait --service dynamodb # wait until a specific service is ready floci wait -o json # machine-readable output ``` -### `floci doctor` / `floci gcp doctor` / `floci az doctor` +### `floci doctor` / `floci gcp doctor` / `floci az doctor` / `floci oci doctor` ```sh floci doctor # run all checks @@ -436,16 +539,17 @@ floci doctor -o json # structured output for scripts floci gcp doctor # GCP-specific checks floci az doctor # Azure-specific checks (includes az CLI + connection string) +floci oci doctor # OCI-specific checks ``` -### `floci version` / `floci gcp version` / `floci az version` +### `floci version` / `floci gcp version` / `floci az version` / `floci oci version` ```sh floci version # CLI version, server version, image digest floci version -o json ``` -### `floci services` / `floci gcp services` / `floci az services` +### `floci services` / `floci gcp services` / `floci az services` / `floci oci services` ```sh floci services # list all enabled services @@ -456,7 +560,7 @@ floci services -o json ```sh floci config show # show active configuration -floci config default-product aws|gcp|az # set the default product (persisted to ~/.floci/config.yaml) +floci config default-product aws|gcp|az|oci # set the default product (persisted to ~/.floci/config.yaml) floci config profile list # list saved profiles floci config profile create # create a new profile floci config profile show # show a profile @@ -480,7 +584,7 @@ floci snapshot export -o tarball.tar.gz floci snapshot import tarball.tar.gz ``` -> GCP and Azure snapshots (`floci gcp snapshot` / `floci az snapshot`) are not yet available — they require server-side endpoints not yet implemented in Floci GCP / Floci Azure. `floci snapshot export|import` (AWS) are also pending server support. +> GCP, Azure, and OCI snapshots (`floci gcp snapshot` / `floci az snapshot` / `floci oci snapshot`) are not yet available — they require server-side endpoints not yet implemented in Floci GCP / Floci Azure / Floci OCI. `floci snapshot export|import` (AWS) are also pending server support. ### `floci update` @@ -598,13 +702,35 @@ services: - /var/run/docker.sock:/var/run/docker.sock ``` +### OCI CI + +```sh +floci oci start --detach +floci oci wait --timeout 60s +eval $(floci oci env) +pytest # or your test command +floci oci stop --remove +``` + +With Docker Compose: + +```yaml +services: + floci-oci: + image: floci/floci-oci:latest + ports: + - "4599:4599" + volumes: + - /var/run/docker.sock:/var/run/docker.sock +``` + --- ## Scope `floci-cli` manages Floci's lifecycle, config, state, and diagnostics. -It does **not** wrap the AWS, GCP, or Azure CLIs, or manage cloud resources directly. -Use `aws` with `AWS_ENDPOINT_URL`, `gcloud`/SDKs with the emulator host variables, or `az` with the appropriate connection string for resource operations. +It does **not** wrap the AWS, GCP, Azure, or OCI CLIs, or manage cloud resources directly. +Use `aws` with `AWS_ENDPOINT_URL`, `gcloud`/SDKs with the emulator host variables, `az` with the appropriate connection string, or `oci` with `OCI_CLI_ENDPOINT` for resource operations. --- diff --git a/src/main/java/io/floci/cli/FlociCli.java b/src/main/java/io/floci/cli/FlociCli.java index 47364d8..1eab879 100644 --- a/src/main/java/io/floci/cli/FlociCli.java +++ b/src/main/java/io/floci/cli/FlociCli.java @@ -4,6 +4,7 @@ import io.floci.cli.commands.*; import io.floci.cli.commands.aws.AwsCommand; import io.floci.cli.commands.az.AzCommand; import io.floci.cli.commands.gcp.GcpCommand; +import io.floci.cli.commands.oci.OciCommand; import io.floci.cli.commands.config.ConfigCommand; import io.floci.cli.commands.snapshot.SnapshotCommand; import io.floci.cli.config.GlobalConfigStore; @@ -23,6 +24,7 @@ import picocli.CommandLine.*; " floci aws — explicit AWS emulator commands%n" + " floci az — Azure emulator commands%n" + " floci gcp — GCP emulator commands%n" + + " floci oci — OCI emulator commands%n" + " floci update — Update the CLI to the latest release", mixinStandardHelpOptions = true, versionProvider = FlociCli.VersionProvider.class, @@ -43,6 +45,7 @@ import picocli.CommandLine.*; AwsCommand.class, AzCommand.class, GcpCommand.class, + OciCommand.class, HelpCommand.class, UpdateCommand.class, } @@ -81,6 +84,8 @@ public class FlociCli implements Runnable { effectiveArgs = prepend("az", args); } else if ("gcp".equals(defaultProduct)) { effectiveArgs = prepend("gcp", args); + } else if ("oci".equals(defaultProduct)) { + effectiveArgs = prepend("oci", args); } } @@ -115,7 +120,7 @@ public class FlociCli implements Runnable { private static boolean isExplicitProduct(String[] args) { for (String arg : args) { if (arg.startsWith("-")) continue; - return "aws".equals(arg) || "az".equals(arg) || "gcp".equals(arg) + return "aws".equals(arg) || "az".equals(arg) || "gcp".equals(arg) || "oci".equals(arg) || "config".equals(arg) || "completion".equals(arg) || "help".equals(arg) || "update".equals(arg); } diff --git a/src/main/java/io/floci/cli/OciGlobalOptions.java b/src/main/java/io/floci/cli/OciGlobalOptions.java new file mode 100644 index 0000000..e38a346 --- /dev/null +++ b/src/main/java/io/floci/cli/OciGlobalOptions.java @@ -0,0 +1,83 @@ +package io.floci.cli; + +import io.floci.cli.docker.DockerClient; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; +import io.floci.cli.output.Printer; +import picocli.CommandLine.Option; + +import java.net.URI; + +public class OciGlobalOptions { + + /** Control-plane path prefix exposed by the floci-oci server (differs from AWS/Azure's {@code /_floci}). */ + public static final String CONTROL_PREFIX = "/_floci-oci"; + + @Option(names = {"--endpoint"}, + description = "Floci OCI server endpoint URL", + defaultValue = "${FLOCI_OCI_ENDPOINT:-http://localhost:4599}", + paramLabel = "") + public String endpoint; + + @Option(names = {"--container"}, + description = "Floci OCI container name", + defaultValue = "${FLOCI_OCI_CONTAINER:-floci-oci}", + paramLabel = "") + public String container; + + @Option(names = {"--profile"}, + description = "Config profile from ~/.floci/profiles/", + paramLabel = "") + public String profile; + + @Option(names = {"--output", "-o"}, + description = "Output format: text, json, yaml", + defaultValue = "text", + paramLabel = "text|json|yaml") + public OutputFormat output; + + @Option(names = {"--quiet", "-q"}, description = "Suppress non-error output") + public boolean quiet; + + @Option(names = {"--verbose", "-v"}, description = "Debug logging to stderr") + public boolean verbose; + + @Option(names = {"--no-color"}, description = "Disable ANSI colors") + public boolean noColor; + + public Printer printer() { + if (noColor || System.console() == null) { + Ansi.disable(); + } + return new Printer(System.out, System.err, output, quiet); + } + + public String resolvedEndpoint(DockerClient docker) { + try { + return docker.inspectContainer(container) + .map(info -> endpointFromPorts(info.ports(), endpoint)) + .orElse(endpoint); + } catch (Exception e) { + return endpoint; + } + } + + public String endpointFromPorts(String ports, String fallback) { + if (ports == null || ports.isBlank()) return fallback; + try { + int containerPort = URI.create(fallback).getPort(); + if (containerPort == -1) containerPort = 4599; + 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; + } + } + } catch (Exception ignored) {} + return fallback; + } +} \ No newline at end of file diff --git a/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java index 62f1dbe..9fe172c 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java @@ -19,14 +19,14 @@ public class ConfigDefaultProductCommand implements Callable { @Mixin GlobalOptions global; - @Parameters(index = "0", description = "Product to use by default: aws, az, gcp", paramLabel = "aws|az|gcp") + @Parameters(index = "0", description = "Product to use by default: aws, az, gcp, oci", paramLabel = "aws|az|gcp|oci") String product; @Override public Integer call() { Printer printer = global.printer(); - if (!"aws".equals(product) && !"az".equals(product) && !"gcp".equals(product)) { - printer.error("Unknown product '" + product + "'. Use: aws, az, gcp"); + if (!"aws".equals(product) && !"az".equals(product) && !"gcp".equals(product) && !"oci".equals(product)) { + printer.error("Unknown product '" + product + "'. Use: aws, az, gcp, oci"); return 1; } GlobalConfigStore store = new GlobalConfigStore(); diff --git a/src/main/java/io/floci/cli/commands/oci/OciCommand.java b/src/main/java/io/floci/cli/commands/oci/OciCommand.java new file mode 100644 index 0000000..c704940 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/OciCommand.java @@ -0,0 +1,43 @@ +package io.floci.cli.commands.oci; + +import io.floci.cli.commands.CompletionCommand; +import io.floci.cli.commands.oci.config.OciConfigCommand; +import io.floci.cli.commands.oci.snapshot.OciSnapshotCommand; +import picocli.CommandLine; +import picocli.CommandLine.*; + +@Command( + name = "oci", + description = "Manage the Floci OCI emulator (floci-oci)%n%n" + + " floci oci start — launch the container%n" + + " floci oci stop — stop the container%n" + + " floci oci status — show health and version%n" + + " floci oci doctor — diagnose environment issues%n" + + " floci oci env — print OCI environment variables%n" + + " floci oci setup — create a local OCI CLI profile (key + ~/.oci/config)%n", + mixinStandardHelpOptions = true, + subcommands = { + OciStartCommand.class, + OciStopCommand.class, + OciRestartCommand.class, + OciStatusCommand.class, + OciLogsCommand.class, + OciWaitCommand.class, + OciVersionCommand.class, + OciServicesCommand.class, + OciDoctorCommand.class, + OciEnvCommand.class, + OciSetupCommand.class, + OciConfigCommand.class, + OciSnapshotCommand.class, + CompletionCommand.class, + HelpCommand.class + } +) +public class OciCommand implements Runnable { + + @Override + public void run() { + new CommandLine(this).usage(System.out); + } +} diff --git a/src/main/java/io/floci/cli/commands/oci/OciDoctorCommand.java b/src/main/java/io/floci/cli/commands/oci/OciDoctorCommand.java new file mode 100644 index 0000000..d77d987 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/OciDoctorCommand.java @@ -0,0 +1,108 @@ +package io.floci.cli.commands.oci; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.commands.DoctorCommand; +import io.floci.cli.doctor.Check; +import io.floci.cli.doctor.CheckResult; +import io.floci.cli.doctor.CheckStatus; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.doctor.checks.ContainerRunningCheck; +import io.floci.cli.doctor.checks.DockerDaemonCheck; +import io.floci.cli.doctor.checks.DockerInstalledCheck; +import io.floci.cli.doctor.checks.DockerSocketCheck; +import io.floci.cli.doctor.checks.DockerVersionCheck; +import io.floci.cli.doctor.checks.EndpointReachableCheck; +import io.floci.cli.doctor.checks.ImagePresentCheck; +import io.floci.cli.doctor.checks.ImageVersionCheck; +import io.floci.cli.doctor.checks.PortAvailableCheck; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; + +@Command( + name = "doctor", + description = "Run environment diagnostics for Floci OCI", + mixinStandardHelpOptions = true +) +public class OciDoctorCommand implements Callable { + + @Mixin + OciGlobalOptions global; + + @Option(names = {"--check"}, description = "Run only a specific check by name", paramLabel = "") + String checkName; + + @Option(names = {"--fix"}, description = "Attempt to auto-fix fixable issues") + boolean fix; + + private static final List ALL_CHECKS; + + static { + List checks = new ArrayList<>(); + checks.add(new DockerInstalledCheck()); + checks.add(new DockerDaemonCheck()); + checks.add(new DockerSocketCheck()); + checks.add(new DockerVersionCheck()); + checks.add(new PortAvailableCheck()); + checks.add(new ImagePresentCheck("floci/floci-oci")); + checks.add(new ImageVersionCheck("floci/floci-oci")); + checks.add(new ContainerRunningCheck()); + checks.add(new EndpointReachableCheck(io.floci.cli.OciGlobalOptions.CONTROL_PREFIX)); + ALL_CHECKS = List.copyOf(checks); + } + + @Override + public Integer call() { + Printer printer = global.printer(); + List results = new ArrayList<>(); + String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); + + boolean textMode = printer.format() == OutputFormat.text; + + if (textMode) { + printer.println(Ansi.bold("Floci OCI Doctor") + " — checking your environment"); + printer.println(""); + } + + for (Check check : ALL_CHECKS) { + CheckResult result = check.run(effectiveEndpoint, global.container); + if (checkName != null && !result.name().equals(checkName)) continue; + results.add(result); + if (textMode) DoctorCommand.printResult(printer, result); + } + + if (!textMode) { + List> structured = new ArrayList<>(); + for (CheckResult r : results) { + Map m = new LinkedHashMap<>(); + m.put("name", r.name()); + m.put("status", r.status().name()); + m.put("message", r.message()); + if (r.fix() != null) m.put("fix", r.fix()); + structured.add(m); + } + printer.structured(structured); + return 0; + } + + long fails = results.stream().filter(r -> r.status() == CheckStatus.fail).count(); + long warns = results.stream().filter(r -> r.status() == CheckStatus.warn).count(); + + printer.println(""); + if (fails == 0 && warns == 0) { + printer.println(Ansi.green("All checks passed.")); + } else { + printer.println(fails + " issue(s) found (" + fails + " fail, " + warns + " warn)." + + (fix ? "" : " Run with --fix to auto-resolve fixable issues.")); + } + + return fails > 0 ? 1 : 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/oci/OciEnvCommand.java b/src/main/java/io/floci/cli/commands/oci/OciEnvCommand.java new file mode 100644 index 0000000..98c5365 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/OciEnvCommand.java @@ -0,0 +1,84 @@ +package io.floci.cli.commands.oci; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.Callable; + +@Command( + name = "env", + description = "Print OCI environment variables to connect to Floci OCI", + mixinStandardHelpOptions = true +) +public class OciEnvCommand implements Callable { + + @Mixin + OciGlobalOptions global; + + @Option(names = {"--shell"}, + description = "Shell format: bash, fish, powershell (default: bash)", + defaultValue = "bash", + paramLabel = "bash|fish|powershell") + String shell; + + @Override + public Integer call() { + Printer printer = global.printer(); + String endpoint = global.resolvedEndpoint(new DockerClient()); + + Map vars = new LinkedHashMap<>(); + // OCI SDKs and CLI take one endpoint for every service; ocilocal reads FLOCI_OCI_ENDPOINT. + vars.put("OCI_CLI_ENDPOINT", endpoint); + vars.put("FLOCI_OCI_ENDPOINT", endpoint); + // The oracle/oci Terraform provider routes via per-client host overrides. + vars.put("TF_VAR_CLIENT_HOST_OVERRIDES", + "oci_identity.IdentityClient=" + endpoint + + ";oci_object_storage.ObjectStorageClient=" + endpoint); + // Select the throwaway profile written by 'floci oci setup', when present. + // DEFAULT needs no selection — the OCI CLI uses it implicitly. + try { + Path config = Path.of(System.getProperty("user.home"), ".oci", "config"); + String setupProfile = OciSetupCommand.detectSetupProfile(config); + if (setupProfile != null && !"DEFAULT".equals(setupProfile)) { + vars.put("OCI_CLI_PROFILE", setupProfile); + } + } catch (Exception ignored) { + } + + if (printer.format() != OutputFormat.text) { + printer.structured(vars); + return 0; + } + + for (Map.Entry entry : vars.entrySet()) { + printer.println(formatExport(shell, entry.getKey(), entry.getValue())); + } + printer.println(""); + printer.println(Ansi.gray("# Run: eval $(floci oci env)")); + return 0; + } + + /** + * Renders one export line. The output is documented as {@code eval} input, so values + * are single-quoted with per-shell escaping — no interpolation of {@code $}, backticks, + * or quotes can occur even for hostile {@code --endpoint} / env-var values. + */ + public static String formatExport(String shell, String key, String value) { + return switch (shell.toLowerCase()) { + // fish single quotes: only \' and \\ are escapes, backslash must be doubled first + case "fish" -> "set -x " + key + " '" + + value.replace("\\", "\\\\").replace("'", "\\'") + "'"; + // PowerShell single quotes: literal except '' for a quote + case "powershell", "ps1" -> "$env:" + key + " = '" + value.replace("'", "''") + "'"; + // POSIX single quotes: close, escaped quote, reopen + default -> "export " + key + "='" + value.replace("'", "'\\''") + "'"; + }; + } +} diff --git a/src/main/java/io/floci/cli/commands/oci/OciLogsCommand.java b/src/main/java/io/floci/cli/commands/oci/OciLogsCommand.java new file mode 100644 index 0000000..1de7376 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/OciLogsCommand.java @@ -0,0 +1,54 @@ +package io.floci.cli.commands.oci; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "logs", + description = "Fetch logs from the Floci OCI container", + mixinStandardHelpOptions = true +) +public class OciLogsCommand implements Callable { + + @Mixin + OciGlobalOptions global; + + @Option(names = {"--follow", "-f"}, description = "Follow log output") + boolean follow; + + @Option(names = {"--tail"}, description = "Number of lines from the end (0 = all)", defaultValue = "100", paramLabel = "") + int tail; + + @Option(names = {"--since"}, description = "Show logs since duration (e.g. 5m, 1h) or timestamp", paramLabel = "") + String since; + + @Override + public Integer call() { + Printer printer = global.printer(); + DockerClient docker = new DockerClient(); + + try { + var info = docker.inspectContainer(global.container); + if (info.isEmpty()) { + printer.error("Container '" + global.container + "' not found.\nRun 'floci oci start' to launch one."); + return 1; + } + } catch (DockerException e) { + printer.error("Failed to inspect container: " + e.getMessage()); + return 1; + } + + try { + docker.streamLogs(global.container, follow, tail, since); + return 0; + } catch (DockerException e) { + printer.error("Failed to fetch logs: " + e.getMessage()); + return 1; + } + } +} \ No newline at end of file diff --git a/src/main/java/io/floci/cli/commands/oci/OciRestartCommand.java b/src/main/java/io/floci/cli/commands/oci/OciRestartCommand.java new file mode 100644 index 0000000..44140d0 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/OciRestartCommand.java @@ -0,0 +1,40 @@ +package io.floci.cli.commands.oci; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "restart", + description = "Stop and restart the Floci OCI container", + mixinStandardHelpOptions = true +) +public class OciRestartCommand implements Callable { + + @Mixin + OciGlobalOptions global; + + @Override + public Integer call() { + Printer printer = global.printer(); + + OciStopCommand stop = new OciStopCommand(); + stop.global = global; + stop.remove = false; + stop.timeout = 10; + int stopResult = stop.call(); + if (stopResult != 0) return stopResult; + + try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } + + OciStartCommand start = new OciStartCommand(); + start.global = global; + start.port = 4599; + start.pull = "missing"; + start.image = "floci/floci-oci:latest"; + start.detach = false; + return start.call(); + } +} \ No newline at end of file diff --git a/src/main/java/io/floci/cli/commands/oci/OciServicesCommand.java b/src/main/java/io/floci/cli/commands/oci/OciServicesCommand.java new file mode 100644 index 0000000..ab3d01f --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/OciServicesCommand.java @@ -0,0 +1,59 @@ +package io.floci.cli.commands.oci; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.docker.DockerClient; +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.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; + +@Command( + name = "services", + description = "List services available in the running Floci OCI instance", + mixinStandardHelpOptions = true +) +public class OciServicesCommand implements Callable { + + @Mixin + OciGlobalOptions global; + + @Override + public Integer call() { + Printer printer = global.printer(); + // Resolve the endpoint from the container's port mapping, like status/wait/env do, + // so a container started with --port is still found without --endpoint. + String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); + FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, OciGlobalOptions.CONTROL_PREFIX); + + List services; + try { + var health = client.health(); + services = Arrays.asList(health.services()); + } catch (Exception e) { + printer.error("Could not reach Floci OCI at " + effectiveEndpoint + ".\nIs Floci OCI running? Try 'floci oci start'."); + return 1; + } + + if (printer.format() != OutputFormat.text) { + printer.structured(Map.of("services", services, "count", services.size())); + return 0; + } + + printer.println(Ansi.bold("Floci OCI Services") + " " + Ansi.gray("(" + services.size() + " enabled)")); + printer.println(""); + for (String svc : services) { + printer.println(" " + Ansi.green("✓") + " " + svc); + } + if (services.isEmpty()) { + printer.println(" " + Ansi.gray("(no services reported)")); + } + + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/oci/OciSetupCommand.java b/src/main/java/io/floci/cli/commands/oci/OciSetupCommand.java new file mode 100644 index 0000000..3f65340 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/OciSetupCommand.java @@ -0,0 +1,191 @@ +package io.floci.cli.commands.oci; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.RSAPublicKeySpec; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.Callable; + +@Command( + name = "setup", + description = "Create a local OCI CLI profile (API key + ~/.oci/config) for the emulator", + mixinStandardHelpOptions = true +) +public class OciSetupCommand implements Callable { + + // Canonical throwaway identity documented by floci-oci; the emulator partitions + // state by the tenancy OCID but never validates the credentials themselves. + static final String TENANCY = "ocid1.tenancy.oc1..flocilocaltenancy0000000000000000000000000000000000000000"; + static final String USER = "ocid1.user.oc1..flocilocaluser0000000000000000000000000000000000000000000000"; + static final String REGION = "us-ashburn-1"; + static final String KEY_FILE_NAME = "floci_key.pem"; + + @Mixin + OciGlobalOptions global; + + @Option(names = {"--profile-name"}, + description = "Profile section name to write in ~/.oci/config (default: FLOCI)", + defaultValue = "FLOCI", + paramLabel = "") + String profileName; + + private final Path ociDir; + + public OciSetupCommand() { + this(Path.of(System.getProperty("user.home"), ".oci")); + } + + public OciSetupCommand(Path ociDir) { + this.ociDir = ociDir; + } + + @Override + public Integer call() { + Printer printer = global.printer(); + Path keyFile = ociDir.resolve(KEY_FILE_NAME); + Path configFile = ociDir.resolve("config"); + + boolean keyCreated; + boolean profileAdded; + String fingerprint; + try { + Files.createDirectories(ociDir); + restrictPermissions(ociDir, "rwx------"); + + keyCreated = !Files.exists(keyFile); + if (keyCreated) { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + KeyPair pair = generator.generateKeyPair(); + Files.writeString(keyFile, toPem(pair.getPrivate().getEncoded())); + restrictPermissions(keyFile, "rw-------"); + } + fingerprint = fingerprint(keyFile); + + profileAdded = !profileExists(configFile, profileName); + if (profileAdded) { + String section = (Files.exists(configFile) ? "\n" : "") + + "[" + profileName + "]\n" + + "user=" + USER + "\n" + + "fingerprint=" + fingerprint + "\n" + + "tenancy=" + TENANCY + "\n" + + "region=" + REGION + "\n" + + "key_file=" + keyFile.toAbsolutePath() + "\n"; + Files.writeString(configFile, section, + java.nio.file.StandardOpenOption.CREATE, java.nio.file.StandardOpenOption.APPEND); + restrictPermissions(configFile, "rw-------"); + } + } catch (Exception e) { + printer.error("Could not set up the OCI profile: " + e.getMessage() + + "\nCheck that " + ociDir + " is writable, or remove a corrupt " + + KEY_FILE_NAME + " and re-run 'floci oci setup'."); + return 1; + } + + if (printer.format() != OutputFormat.text) { + Map out = new LinkedHashMap<>(); + out.put("keyFile", keyFile.toAbsolutePath().toString()); + out.put("keyCreated", keyCreated); + out.put("configFile", configFile.toAbsolutePath().toString()); + out.put("profile", profileName); + out.put("profileAdded", profileAdded); + out.put("fingerprint", fingerprint); + printer.structured(out); + return 0; + } + + printer.println((keyCreated ? Ansi.green("Created ") : Ansi.gray("Reusing ")) + + keyFile.toAbsolutePath() + Ansi.gray(" (RSA 2048)")); + printer.println((profileAdded ? Ansi.green("Added profile ") : Ansi.gray("Profile already present: ")) + + Ansi.bold("[" + profileName + "]") + " in " + configFile.toAbsolutePath()); + printer.println(""); + printer.println("Connect with:"); + printer.println(" " + Ansi.bold("eval $(floci oci env)")); + printer.println(" " + Ansi.bold("oci os ns get")); + return 0; + } + + static boolean profileExists(Path configFile, String profileName) throws Exception { + return Files.exists(configFile) + && Files.readAllLines(configFile).stream() + .map(String::trim) + .anyMatch(("[" + profileName + "]")::equals); + } + + /** + * Finds the profile section this command wrote, whatever {@code --profile-name} was used: + * the section whose {@code key_file} points at the setup-generated key. Prefers + * {@code FLOCI} (the default name) when several sections share the key. + * Returns {@code null} when no setup-written profile exists. + */ + public static String detectSetupProfile(Path configFile) throws Exception { + if (!Files.exists(configFile)) return null; + String section = null; + String found = null; + for (String raw : Files.readAllLines(configFile)) { + String line = raw.trim(); + if (line.startsWith("[") && line.endsWith("]")) { + section = line.substring(1, line.length() - 1); + continue; + } + if (section == null || !line.startsWith("key_file")) continue; + String[] kv = line.split("=", 2); + if (kv.length == 2 && kv[1].trim().endsWith(KEY_FILE_NAME)) { + if ("FLOCI".equals(section)) return section; + if (found == null) found = section; + } + } + return found; + } + + private static String toPem(byte[] pkcs8) { + // 64-char lines per RFC 7468; the trailing OCI_API_KEY label is the marker the + // OCI CLI looks for to confirm the key is API-only (suppresses its warning). + String base64 = Base64.getMimeEncoder(64, "\n".getBytes()).encodeToString(pkcs8); + return "-----BEGIN PRIVATE KEY-----\n" + base64 + "\n-----END PRIVATE KEY-----\nOCI_API_KEY\n"; + } + + /** OCI API-key fingerprint: colon-separated MD5 of the DER-encoded public key. */ + private static String fingerprint(Path keyFile) throws Exception { + String pem = Files.readString(keyFile) + .replaceAll("-----[A-Z ]+-----", "") + .replace("OCI_API_KEY", "") + .replaceAll("\\s", ""); + RSAPrivateCrtKey priv = (RSAPrivateCrtKey) KeyFactory.getInstance("RSA") + .generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(pem))); + byte[] publicDer = KeyFactory.getInstance("RSA") + .generatePublic(new RSAPublicKeySpec(priv.getModulus(), priv.getPublicExponent())) + .getEncoded(); + byte[] digest = MessageDigest.getInstance("MD5").digest(publicDer); + StringBuilder sb = new StringBuilder(); + for (byte b : digest) { + if (sb.length() > 0) sb.append(':'); + sb.append(String.format("%02x", b)); + } + return sb.toString(); + } + + private static void restrictPermissions(Path path, String posix) { + try { + Files.setPosixFilePermissions(path, PosixFilePermissions.fromString(posix)); + } catch (UnsupportedOperationException ignored) { + // Windows: no POSIX permissions; ~/.oci inherits the user's ACLs. + } catch (Exception ignored) { + } + } +} diff --git a/src/main/java/io/floci/cli/commands/oci/OciStartCommand.java b/src/main/java/io/floci/cli/commands/oci/OciStartCommand.java new file mode 100644 index 0000000..581d77a --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/OciStartCommand.java @@ -0,0 +1,113 @@ +package io.floci.cli.commands.oci; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; + +@Command( + name = "start", + description = "Start the Floci OCI emulator container", + mixinStandardHelpOptions = true +) +public class OciStartCommand implements Callable { + + @Mixin + OciGlobalOptions global; + + @Option(names = {"--port"}, description = "Host port to bind (default: 4599)", defaultValue = "4599", paramLabel = "") + int port; + + @Option(names = {"--persist"}, description = "Host directory for persistent state", paramLabel = "") + String persistDir; + + @Option(names = {"--services"}, description = "Comma-separated list of services to enable", paramLabel = "") + String services; + + @Option(names = {"--detach"}, description = "Return immediately without waiting for readiness") + boolean detach; + + @Option(names = {"--image"}, description = "Image reference to use (default: floci/floci-oci:latest)", defaultValue = "floci/floci-oci:latest", paramLabel = "") + String image; + + @Option(names = {"--pull"}, description = "Image pull policy: always, missing, never", defaultValue = "missing", paramLabel = "always|missing|never") + String pull; + + @Override + public Integer call() { + Printer printer = global.printer(); + DockerClient docker = new DockerClient(); + + if (!DockerClient.isInstalled()) { + printer.error("docker binary not found in PATH.\nInstall Docker Desktop from https://docs.docker.com/get-docker/"); + return 1; + } + + try { + var existing = docker.inspectContainer(global.container); + if (existing.isPresent()) { + String state = existing.get().state(); + if ("running".equals(state)) { + printer.error("Container '" + global.container + "' is already running.\nRun 'floci oci stop' first or pass --container to use a different name."); + return 1; + } + printer.println(Ansi.gray("Removing stopped container '" + global.container + "'...")); + docker.removeContainer(global.container); + } + } catch (DockerException e) { + printer.error("Failed to inspect container: " + e.getMessage()); + return 1; + } + + try { + printer.println(Ansi.gray("Checking image " + image + " (policy: " + pull + ")...")); + docker.pull(image, pull); + } catch (DockerException e) { + printer.error("Failed to pull image: " + e.getMessage() + "\nRun 'floci oci start --pull never' to skip pulling."); + return 1; + } + + List args = new ArrayList<>(); + args.addAll(List.of("-d", "--name", global.container)); + args.addAll(List.of("-p", port + ":4599")); + args.addAll(DockerClient.dockerSocketRunArgs()); + if (persistDir != null) { + args.addAll(List.of("-v", persistDir + ":/app/data")); + // The server defaults to in-memory storage; enable persistent mode so + // state is actually written to the mounted directory and survives restarts. + args.addAll(List.of("-e", "FLOCI_OCI_STORAGE_MODE=persistent")); + } + if (services != null && !services.isBlank()) { + args.addAll(List.of("-e", "FLOCI_OCI_SERVICES=" + services)); + } + args.add(image); + + try { + printer.println("Starting " + Ansi.gold("Floci OCI") + " container..."); + String id = docker.startContainer(args); + printer.println(Ansi.green("Container started") + " (" + id.substring(0, Math.min(12, id.length())) + ")"); + } catch (DockerException e) { + printer.error("Failed to start container: " + e.getMessage()); + return 1; + } + + if (detach) { + printer.println(Ansi.gray("Detached. Run 'floci oci wait' to poll for readiness.")); + return 0; + } + + global.endpoint = "http://localhost:" + port; + + printer.println(Ansi.gray("Waiting for Floci OCI to be ready...")); + OciWaitCommand wait = new OciWaitCommand(); + wait.global = global; + wait.timeout = "30s"; + return wait.call(); + } +} \ No newline at end of file diff --git a/src/main/java/io/floci/cli/commands/oci/OciStatusCommand.java b/src/main/java/io/floci/cli/commands/oci/OciStatusCommand.java new file mode 100644 index 0000000..6641bbf --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/OciStatusCommand.java @@ -0,0 +1,98 @@ +package io.floci.cli.commands.oci; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; +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.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.Callable; + +@Command( + name = "status", + description = "Show Floci OCI container and server status", + mixinStandardHelpOptions = true +) +public class OciStatusCommand implements Callable { + + @Mixin + OciGlobalOptions global; + + @Override + public Integer call() { + Printer printer = global.printer(); + DockerClient docker = new DockerClient(); + + String containerState = "not found"; + String containerImage = ""; + String containerPorts = ""; + String effectiveEndpoint = global.endpoint; + try { + Optional info = docker.inspectContainer(global.container); + if (info.isPresent()) { + containerState = info.get().state(); + containerImage = info.get().image(); + containerPorts = info.get().ports(); + effectiveEndpoint = global.endpointFromPorts(containerPorts, global.endpoint); + } + } catch (DockerException e) { + containerState = "error: " + e.getMessage(); + } + + String serverVersion = "unavailable"; + String serverEdition = ""; + boolean reachable = false; + FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, OciGlobalOptions.CONTROL_PREFIX); + try { + var health = client.health(); + serverVersion = health.version(); + serverEdition = health.edition(); + reachable = true; + } catch (Exception ignored) {} + + Map data = new LinkedHashMap<>(); + data.put("container", global.container); + data.put("state", containerState); + data.put("image", containerImage); + data.put("ports", containerPorts); + data.put("endpoint", effectiveEndpoint); + data.put("reachable", reachable); + data.put("version", serverVersion); + data.put("edition", serverEdition); + + if (printer.format() != OutputFormat.text) { + printer.structured(data); + return 0; + } + + printer.println(Ansi.bold("Floci OCI Status")); + printer.println(""); + String stateColor = switch (containerState) { + case "running" -> Ansi.green(containerState); + case "not found" -> Ansi.gray(containerState); + default -> Ansi.red(containerState); + }; + printer.println(" Container: " + global.container + " " + stateColor); + if (!containerImage.isBlank()) printer.println(" Image: " + containerImage); + if (!containerPorts.isBlank()) printer.println(" Ports: " + containerPorts); + printer.println(" Endpoint: " + effectiveEndpoint); + printer.println(" Reachable: " + (reachable ? Ansi.green("yes") : Ansi.red("no"))); + if (reachable) { + printer.println(" Version: " + serverVersion); + if (!serverEdition.isBlank()) printer.println(" Edition: " + serverEdition); + } + + if (!reachable && !"running".equals(containerState)) { + printer.println(""); + printer.println(Ansi.gray("Run 'floci oci start' to launch Floci OCI.")); + } + + return 0; + } +} \ No newline at end of file diff --git a/src/main/java/io/floci/cli/commands/oci/OciStopCommand.java b/src/main/java/io/floci/cli/commands/oci/OciStopCommand.java new file mode 100644 index 0000000..cf024ba --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/OciStopCommand.java @@ -0,0 +1,73 @@ +package io.floci.cli.commands.oci; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.docker.DockerException; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "stop", + description = "Stop the Floci OCI container", + mixinStandardHelpOptions = true +) +public class OciStopCommand implements Callable { + + @Mixin + OciGlobalOptions global; + + @Option(names = {"--remove", "-r"}, description = "Remove the container after stopping") + boolean remove; + + @Option(names = {"--timeout"}, description = "Seconds to wait before forcefully killing (default: 10)", defaultValue = "10", paramLabel = "") + int timeout; + + @Override + public Integer call() { + Printer printer = global.printer(); + DockerClient docker = new DockerClient(); + + try { + var info = docker.inspectContainer(global.container); + if (info.isEmpty()) { + printer.error("Container '" + global.container + "' not found.\nRun 'floci oci start' to launch one."); + return 1; + } + if (!"running".equals(info.get().state())) { + printer.println(Ansi.yellow("Container '" + global.container + "' is not running (state: " + info.get().state() + ")")); + if (remove) { + docker.removeContainer(global.container); + printer.println("Container removed."); + } + return 0; + } + } catch (DockerException e) { + printer.error("Failed to inspect container: " + e.getMessage()); + return 1; + } + + try { + printer.println("Stopping " + Ansi.gold("Floci OCI") + " container '" + global.container + "'..."); + docker.stopContainer(global.container, timeout); + printer.println(Ansi.green("Stopped.")); + } catch (DockerException e) { + printer.error("Failed to stop container: " + e.getMessage()); + return 1; + } + + if (remove) { + try { + docker.removeContainer(global.container); + printer.println("Container removed."); + } catch (DockerException e) { + printer.error("Failed to remove container: " + e.getMessage()); + return 1; + } + } + + return 0; + } +} \ No newline at end of file diff --git a/src/main/java/io/floci/cli/commands/oci/OciVersionCommand.java b/src/main/java/io/floci/cli/commands/oci/OciVersionCommand.java new file mode 100644 index 0000000..23cfe9b --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/OciVersionCommand.java @@ -0,0 +1,72 @@ +package io.floci.cli.commands.oci; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.commands.VersionCommand; +import io.floci.cli.docker.DockerClient; +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.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.Callable; + +@Command( + name = "version", + description = "Show CLI version, connected Floci OCI server version, and image digest", + mixinStandardHelpOptions = true +) +public class OciVersionCommand implements Callable { + + @Mixin + OciGlobalOptions global; + + @Override + public Integer call() { + Printer printer = global.printer(); + + String serverVersion = null; + String serverEdition = null; + String imageDigest = null; + + DockerClient docker = new DockerClient(); + String effectiveEndpoint = global.resolvedEndpoint(docker); + + FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, OciGlobalOptions.CONTROL_PREFIX); + try { + var info = client.info(); + serverVersion = info.version(); + serverEdition = info.edition(); + } catch (Exception ignored) {} + + try { + imageDigest = docker.imageDigest("floci/floci-oci").orElse(null); + } catch (Exception ignored) {} + + Map data = new LinkedHashMap<>(); + data.put("cli", VersionCommand.CLI_VERSION); + data.put("server", Optional.ofNullable(serverVersion).orElse("unavailable")); + data.put("edition", Optional.ofNullable(serverEdition).orElse("")); + if (imageDigest != null) data.put("digest", imageDigest); + + if (printer.format() != OutputFormat.text) { + printer.structured(data); + return 0; + } + + printer.println(Ansi.bold("Floci CLI") + " " + Ansi.gold(VersionCommand.CLI_VERSION)); + if (serverVersion != null) { + printer.println("Server: " + serverVersion + (serverEdition != null ? " (" + serverEdition + ")" : "")); + } else { + printer.println("Server: " + Ansi.gray("not reachable at " + effectiveEndpoint)); + } + if (imageDigest != null) { + printer.println("Image: " + imageDigest); + } + + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/oci/OciWaitCommand.java b/src/main/java/io/floci/cli/commands/oci/OciWaitCommand.java new file mode 100644 index 0000000..ce37c72 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/OciWaitCommand.java @@ -0,0 +1,73 @@ +package io.floci.cli.commands.oci; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.commands.WaitCommand; +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.time.Duration; +import java.time.Instant; +import java.util.Map; +import java.util.concurrent.Callable; + +@Command( + name = "wait", + description = "Wait until Floci OCI is ready to accept requests", + mixinStandardHelpOptions = true +) +public class OciWaitCommand implements Callable { + + @Mixin + OciGlobalOptions global; + + @Option(names = {"--timeout"}, description = "Maximum time to wait (e.g. 30s, 2m)", defaultValue = "30s", paramLabel = "") + String timeout; + + @Option(names = {"--service"}, description = "Wait until a specific service is enabled", paramLabel = "") + String service; + + @Override + public Integer call() { + Printer printer = global.printer(); + long timeoutMillis = WaitCommand.parseDuration(timeout); + String effectiveEndpoint = global.resolvedEndpoint(new io.floci.cli.docker.DockerClient()); + FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, OciGlobalOptions.CONTROL_PREFIX); + Instant deadline = Instant.now().plusMillis(timeoutMillis); + + while (Instant.now().isBefore(deadline)) { + if (isReady(client, service)) { + if (printer.format() != OutputFormat.text) { + printer.structured(Map.of("ready", true, "endpoint", effectiveEndpoint)); + } else { + printer.println(Ansi.green("Floci OCI is ready") + " (" + effectiveEndpoint + ")"); + } + return 0; + } + long remaining = Duration.between(Instant.now(), deadline).toSeconds(); + printer.print("\r" + Ansi.gray("Waiting... (" + remaining + "s remaining)") + " "); + try { Thread.sleep(500); } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } + } + + printer.error("Timed out waiting for Floci OCI after " + timeout + ".\nIs the container running? Try 'floci oci status'."); + return 1; + } + + private boolean isReady(FlociHttpClient client, String requiredService) { + try { + var health = client.health(); + if (requiredService == null) return true; + for (String s : health.services()) { + if (s.equalsIgnoreCase(requiredService)) return true; + } + return false; + } catch (Exception e) { + return false; + } + } +} \ No newline at end of file diff --git a/src/main/java/io/floci/cli/commands/oci/config/OciConfigCommand.java b/src/main/java/io/floci/cli/commands/oci/config/OciConfigCommand.java new file mode 100644 index 0000000..95f586d --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/config/OciConfigCommand.java @@ -0,0 +1,23 @@ +package io.floci.cli.commands.oci.config; + +import picocli.CommandLine; +import picocli.CommandLine.*; + +@Command( + name = "config", + description = "Manage Floci OCI configuration", + mixinStandardHelpOptions = true, + subcommands = { + OciConfigShowCommand.class, + OciConfigValidateCommand.class, + OciConfigProfileCommand.class, + HelpCommand.class + } +) +public class OciConfigCommand implements Runnable { + + @Override + public void run() { + new CommandLine(this).usage(System.out); + } +} diff --git a/src/main/java/io/floci/cli/commands/oci/config/OciConfigProfileCommand.java b/src/main/java/io/floci/cli/commands/oci/config/OciConfigProfileCommand.java new file mode 100644 index 0000000..d66c0a8 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/config/OciConfigProfileCommand.java @@ -0,0 +1,115 @@ +package io.floci.cli.commands.oci.config; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.config.Profile; +import io.floci.cli.config.ProfileStore; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.Callable; + +@Command( + name = "profile", + description = "Manage Floci OCI configuration profiles", + mixinStandardHelpOptions = true, + subcommands = {HelpCommand.class} +) +public class OciConfigProfileCommand implements Callable { + + @Mixin + OciGlobalOptions global; + + @Parameters(index = "0", description = "Action: list, show, create, delete", paramLabel = "list|show|create|delete") + String action; + + @Parameters(index = "1", description = "Profile name (required for show, create, delete)", arity = "0..1", paramLabel = "") + String name; + + @Override + public Integer call() { + Printer printer = global.printer(); + ProfileStore store = new ProfileStore(); + + return switch (action.toLowerCase()) { + case "list" -> listProfiles(printer, store); + case "show" -> showProfile(printer, store); + case "create" -> createProfile(printer, store); + case "delete" -> deleteProfile(printer, store); + default -> { + printer.error("Unknown action '" + action + "'. Use: list, show, create, delete"); + yield 1; + } + }; + } + + private int listProfiles(Printer printer, ProfileStore store) { + try { + List profiles = store.list(); + if (profiles.isEmpty()) { + printer.println(Ansi.gray("No profiles found. Create one with: floci oci config profile create ")); + return 0; + } + printer.println(Ansi.bold("Profiles:")); + for (Profile p : profiles) { + printer.println(" " + p.name + Ansi.gray(" " + (p.endpoint != null ? p.endpoint : ""))); + } + return 0; + } catch (IOException e) { + printer.error("Could not list profiles: " + e.getMessage()); + return 1; + } + } + + private int showProfile(Printer printer, ProfileStore store) { + if (name == null) { printer.error("Profile name required."); return 1; } + try { + var profile = store.get(name); + if (profile.isEmpty()) { printer.error("Profile '" + name + "' not found."); return 1; } + Profile p = profile.get(); + printer.println(Ansi.bold("Profile: ") + p.name); + if (p.endpoint != null) printer.println(" endpoint: " + p.endpoint); + if (p.container != null) printer.println(" container: " + p.container); + if (p.image != null) printer.println(" image: " + p.image); + if (p.port != null) printer.println(" port: " + p.port); + if (p.persistDir != null) printer.println(" persistDir: " + p.persistDir); + if (p.services != null) printer.println(" services: " + p.services); + return 0; + } catch (IOException e) { + printer.error("Could not read profile: " + e.getMessage()); + return 1; + } + } + + private int createProfile(Printer printer, ProfileStore store) { + if (name == null) { printer.error("Profile name required."); return 1; } + try { + if (store.get(name).isPresent()) { + printer.error("Profile '" + name + "' already exists. Delete it first or edit " + store.profileFile(name)); + return 1; + } + Profile p = new Profile(name); + store.save(p); + printer.println(Ansi.green("Created") + " profile '" + name + "' at " + store.profileFile(name)); + printer.println(Ansi.gray("Edit the file to customize endpoint, container, image, etc.")); + return 0; + } catch (IOException e) { + printer.error("Could not create profile: " + e.getMessage()); + return 1; + } + } + + private int deleteProfile(Printer printer, ProfileStore store) { + if (name == null) { printer.error("Profile name required."); return 1; } + try { + if (!store.delete(name)) { printer.error("Profile '" + name + "' not found."); return 1; } + printer.println(Ansi.green("Deleted") + " profile '" + name + "'"); + return 0; + } catch (IOException e) { + printer.error("Could not delete profile: " + e.getMessage()); + return 1; + } + } +} diff --git a/src/main/java/io/floci/cli/commands/oci/config/OciConfigShowCommand.java b/src/main/java/io/floci/cli/commands/oci/config/OciConfigShowCommand.java new file mode 100644 index 0000000..027dceb --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/config/OciConfigShowCommand.java @@ -0,0 +1,70 @@ +package io.floci.cli.commands.oci.config; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.config.Profile; +import io.floci.cli.config.ProfileStore; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.Callable; + +@Command( + name = "show", + description = "Show the active Floci OCI configuration", + mixinStandardHelpOptions = true +) +public class OciConfigShowCommand implements Callable { + + @Mixin + OciGlobalOptions global; + + @Override + public Integer call() { + Printer printer = global.printer(); + ProfileStore store = new ProfileStore(); + + Profile active = new Profile(global.profile != null ? global.profile : "default"); + active.endpoint = global.endpoint; + active.container = global.container; + active.output = global.output != null ? global.output.name() : "text"; + + if (global.profile != null) { + try { + Optional loaded = store.get(global.profile); + if (loaded.isPresent()) { + active = loaded.get(); + } else { + printer.warn("Profile '" + global.profile + "' not found. Using defaults."); + } + } catch (IOException e) { + printer.warn("Could not load profile: " + e.getMessage()); + } + } + + Map data = new LinkedHashMap<>(); + data.put("profile", active.name); + data.put("endpoint", active.endpoint != null ? active.endpoint : global.endpoint); + data.put("container", active.container != null ? active.container : global.container); + data.put("output", active.output); + + if (printer.format() != OutputFormat.text) { + printer.structured(data); + return 0; + } + + printer.println(Ansi.bold("Active Configuration (Floci OCI)")); + printer.println(""); + printer.println(" Profile: " + active.name); + printer.println(" Endpoint: " + (active.endpoint != null ? active.endpoint : global.endpoint)); + printer.println(" Container: " + (active.container != null ? active.container : global.container)); + printer.println(" Output: " + (active.output != null ? active.output : "text")); + + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/oci/config/OciConfigValidateCommand.java b/src/main/java/io/floci/cli/commands/oci/config/OciConfigValidateCommand.java new file mode 100644 index 0000000..b13754b --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/config/OciConfigValidateCommand.java @@ -0,0 +1,91 @@ +package io.floci.cli.commands.oci.config; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.regex.Pattern; + +@Command( + name = "validate", + description = "Validate a docker-compose.yml file for Floci OCI compatibility", + mixinStandardHelpOptions = true +) +public class OciConfigValidateCommand implements Callable { + + @Mixin + OciGlobalOptions global; + + @Option(names = {"--file", "-f"}, description = "Path to docker-compose file", paramLabel = "") + String file; + + @Override + public Integer call() { + Printer printer = global.printer(); + + Path composeFile = resolveComposeFile(); + if (composeFile == null) { + printer.error("No docker-compose file found. Pass --file or run in a directory with docker-compose.yml."); + return 1; + } + + String content; + try { + content = Files.readString(composeFile); + } catch (IOException e) { + printer.error("Could not read " + composeFile + ": " + e.getMessage()); + return 1; + } + + printer.println(Ansi.bold("Validating") + " " + composeFile); + printer.println(""); + + List issues = new ArrayList<>(); + List warnings = new ArrayList<>(); + + if (!content.contains("/var/run/docker.sock")) { + warnings.add("Missing /var/run/docker.sock volume mount — required for Kafka/Redpanda support"); + } + + if (!Pattern.compile("4599\\s*:\\s*4599").matcher(content).find()) { + issues.add("Port mapping 4599:4599 not found — Floci OCI listens on 4599 by default"); + } + + if (!content.contains("floci/floci-oci") && !content.contains("ghcr.io/floci-io/floci-oci")) { + warnings.add("Floci OCI image reference not detected — ensure your service uses floci/floci-oci"); + } + + for (String issue : issues) { + printer.println(" " + Ansi.red("✗") + " " + issue); + } + for (String warn : warnings) { + printer.println(" " + Ansi.yellow("⚠") + " " + warn); + } + if (issues.isEmpty() && warnings.isEmpty()) { + printer.println(" " + Ansi.green("✓") + " Compose file looks good"); + } + + printer.println(""); + if (!issues.isEmpty()) { + printer.println(issues.size() + " error(s) found."); + return 1; + } + return 0; + } + + private Path resolveComposeFile() { + if (file != null) return Path.of(file); + for (String name : List.of("docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml")) { + Path p = Path.of(name); + if (Files.exists(p)) return p; + } + return null; + } +} diff --git a/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotCommand.java b/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotCommand.java new file mode 100644 index 0000000..17e8cae --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotCommand.java @@ -0,0 +1,26 @@ +package io.floci.cli.commands.oci.snapshot; + +import picocli.CommandLine; +import picocli.CommandLine.*; + +@Command( + name = "snapshot", + description = "Manage Floci OCI state snapshots (coming soon)", + mixinStandardHelpOptions = true, + subcommands = { + OciSnapshotSaveCommand.class, + OciSnapshotLoadCommand.class, + OciSnapshotListCommand.class, + OciSnapshotDeleteCommand.class, + OciSnapshotExportCommand.class, + OciSnapshotImportCommand.class, + HelpCommand.class + } +) +public class OciSnapshotCommand implements Runnable { + + @Override + public void run() { + new CommandLine(this).usage(System.out); + } +} diff --git a/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotDeleteCommand.java b/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotDeleteCommand.java new file mode 100644 index 0000000..0669160 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotDeleteCommand.java @@ -0,0 +1,28 @@ +package io.floci.cli.commands.oci.snapshot; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.output.Ansi; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "delete", + description = "Delete a Floci OCI snapshot", + mixinStandardHelpOptions = true +) +public class OciSnapshotDeleteCommand implements Callable { + + @Mixin + OciGlobalOptions global; + + @Parameters(index = "0", description = "Snapshot name", paramLabel = "") + String name; + + @Override + public Integer call() { + global.printer().println(Ansi.yellow("Snapshots are not yet available for Floci OCI.") + + "\nTrack progress: https://github.com/floci-io/floci-oci/issues"); + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotExportCommand.java b/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotExportCommand.java new file mode 100644 index 0000000..cf4ce92 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotExportCommand.java @@ -0,0 +1,31 @@ +package io.floci.cli.commands.oci.snapshot; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.output.Ansi; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "export", + description = "Export a Floci OCI snapshot to a tarball file", + mixinStandardHelpOptions = true +) +public class OciSnapshotExportCommand implements Callable { + + @Mixin + OciGlobalOptions global; + + @Parameters(index = "0", description = "Snapshot name", paramLabel = "") + String name; + + @Option(names = {"--file", "-f"}, description = "Destination file path", required = true, paramLabel = "") + String outputFile; + + @Override + public Integer call() { + global.printer().println(Ansi.yellow("Snapshots are not yet available for Floci OCI.") + + "\nTrack progress: https://github.com/floci-io/floci-oci/issues"); + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotImportCommand.java b/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotImportCommand.java new file mode 100644 index 0000000..c6b4c8f --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotImportCommand.java @@ -0,0 +1,31 @@ +package io.floci.cli.commands.oci.snapshot; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.output.Ansi; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "import", + description = "Import a Floci OCI snapshot from a tarball file", + mixinStandardHelpOptions = true +) +public class OciSnapshotImportCommand implements Callable { + + @Mixin + OciGlobalOptions global; + + @Parameters(index = "0", description = "Snapshot name", paramLabel = "") + String name; + + @Option(names = {"--file", "-f"}, description = "Source file path", required = true, paramLabel = "") + String inputFile; + + @Override + public Integer call() { + global.printer().println(Ansi.yellow("Snapshots are not yet available for Floci OCI.") + + "\nTrack progress: https://github.com/floci-io/floci-oci/issues"); + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotListCommand.java b/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotListCommand.java new file mode 100644 index 0000000..7f9df90 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotListCommand.java @@ -0,0 +1,34 @@ +package io.floci.cli.commands.oci.snapshot; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; + +@Command( + name = "list", + description = "List available Floci OCI snapshots", + mixinStandardHelpOptions = true +) +public class OciSnapshotListCommand implements Callable { + + @Mixin + OciGlobalOptions global; + + @Override + public Integer call() { + Printer printer = global.printer(); + if (printer.format() != OutputFormat.text) { + printer.structured(Map.of("snapshots", List.of(), "note", "not yet available")); + return 0; + } + printer.println(Ansi.gray("No snapshots found.") + + " (Snapshot support for Floci OCI is coming — https://github.com/floci-io/floci-oci/issues)"); + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotLoadCommand.java b/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotLoadCommand.java new file mode 100644 index 0000000..c446226 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotLoadCommand.java @@ -0,0 +1,28 @@ +package io.floci.cli.commands.oci.snapshot; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.output.Ansi; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "load", + description = "Load a Floci OCI snapshot", + mixinStandardHelpOptions = true +) +public class OciSnapshotLoadCommand implements Callable { + + @Mixin + OciGlobalOptions global; + + @Parameters(index = "0", description = "Snapshot name", paramLabel = "") + String name; + + @Override + public Integer call() { + global.printer().println(Ansi.yellow("Snapshots are not yet available for Floci OCI.") + + "\nTrack progress: https://github.com/floci-io/floci-oci/issues"); + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotSaveCommand.java b/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotSaveCommand.java new file mode 100644 index 0000000..133c80a --- /dev/null +++ b/src/main/java/io/floci/cli/commands/oci/snapshot/OciSnapshotSaveCommand.java @@ -0,0 +1,31 @@ +package io.floci.cli.commands.oci.snapshot; + +import io.floci.cli.OciGlobalOptions; +import io.floci.cli.output.Ansi; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "save", + description = "Save the current Floci OCI state as a named snapshot", + mixinStandardHelpOptions = true +) +public class OciSnapshotSaveCommand implements Callable { + + @Mixin + OciGlobalOptions global; + + @Parameters(index = "0", description = "Snapshot name", paramLabel = "") + String name; + + @Option(names = {"--message", "-m"}, description = "Optional description", paramLabel = "") + String message; + + @Override + public Integer call() { + global.printer().println(Ansi.yellow("Snapshots are not yet available for Floci OCI.") + + "\nTrack progress: https://github.com/floci-io/floci-oci/issues"); + return 0; + } +} diff --git a/src/main/java/io/floci/cli/config/GlobalConfigStore.java b/src/main/java/io/floci/cli/config/GlobalConfigStore.java index 155d7f7..8e1e545 100644 --- a/src/main/java/io/floci/cli/config/GlobalConfigStore.java +++ b/src/main/java/io/floci/cli/config/GlobalConfigStore.java @@ -28,6 +28,7 @@ public class GlobalConfigStore { GlobalConfig config = YAML.readValue(configFile.toFile(), GlobalConfig.class); if ("az".equals(config.defaultProduct)) return "az"; if ("gcp".equals(config.defaultProduct)) return "gcp"; + if ("oci".equals(config.defaultProduct)) return "oci"; return "aws"; } catch (IOException e) { return "aws"; diff --git a/src/main/java/io/floci/cli/http/FlociHttpClient.java b/src/main/java/io/floci/cli/http/FlociHttpClient.java index 1f68505..bacccc2 100644 --- a/src/main/java/io/floci/cli/http/FlociHttpClient.java +++ b/src/main/java/io/floci/cli/http/FlociHttpClient.java @@ -8,6 +8,8 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; +import java.util.ArrayList; +import java.util.List; import java.util.Map; import java.util.Optional; @@ -45,9 +47,21 @@ public class FlociHttpClient { return new HealthInfo( node.path("version").asText("unknown"), node.path("original_edition").asText(node.path("edition").asText("community")), - node.path("services").isArray() - ? MAPPER.convertValue(node.path("services"), String[].class) - : new String[0]); + serviceNames(node.path("services"))); + } + + // AWS/GCP/Azure report services as an array of names; OCI reports a + // {name: status} object. Accept both. + private static String[] serviceNames(JsonNode services) { + if (services.isArray()) { + return MAPPER.convertValue(services, String[].class); + } + if (services.isObject()) { + List names = new ArrayList<>(); + services.fieldNames().forEachRemaining(names::add); + return names.toArray(String[]::new); + } + return new String[0]; } public Optional healthOptional() { diff --git a/src/test/java/io/floci/cli/unit/OciEnvFormatTest.java b/src/test/java/io/floci/cli/unit/OciEnvFormatTest.java new file mode 100644 index 0000000..6d9e7e8 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/OciEnvFormatTest.java @@ -0,0 +1,39 @@ +package io.floci.cli.unit; + +import io.floci.cli.commands.oci.OciEnvCommand; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +/** Pins the shell-quoting of `floci oci env` output — it is documented as `eval` input. */ +class OciEnvFormatTest { + + @Test + void bashExportsAreSingleQuoted() { + assertEquals("export OCI_CLI_ENDPOINT='http://localhost:4599'", + OciEnvCommand.formatExport("bash", "OCI_CLI_ENDPOINT", "http://localhost:4599")); + } + + @Test + void hostileValuesCannotEscapeBashQuoting() { + String hostile = "http://x\"; echo pwned; $(touch /tmp/pwned) `id` $HOME"; + String export = OciEnvCommand.formatExport("bash", "K", hostile); + // Entire value stays inside single quotes; no interpolation possible. + assertEquals("export K='" + hostile + "'", export); + + String withQuote = "it's"; + assertEquals("export K='it'\\''s'", OciEnvCommand.formatExport("bash", "K", withQuote)); + } + + @Test + void fishEscapesBackslashesAndQuotes() { + assertEquals("set -x K 'a\\\\b\\'c'", + OciEnvCommand.formatExport("fish", "K", "a\\b'c")); + } + + @Test + void powershellDoublesSingleQuotes() { + assertEquals("$env:K = 'it''s $x'", + OciEnvCommand.formatExport("powershell", "K", "it's $x")); + } +} diff --git a/src/test/java/io/floci/cli/unit/OciSetupCommandTest.java b/src/test/java/io/floci/cli/unit/OciSetupCommandTest.java new file mode 100644 index 0000000..c9c5b75 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/OciSetupCommandTest.java @@ -0,0 +1,100 @@ +package io.floci.cli.unit; + +import io.floci.cli.commands.oci.OciSetupCommand; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import picocli.CommandLine; + +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.*; + +class OciSetupCommandTest { + + @TempDir + Path tempDir; + + private int run(Path ociDir, String... args) { + return new CommandLine(new OciSetupCommand(ociDir)).execute(args); + } + + @Test + void createsKeyAndConfig() throws Exception { + Path ociDir = tempDir.resolve(".oci"); + assertEquals(0, run(ociDir)); + + Path keyFile = ociDir.resolve("floci_key.pem"); + Path configFile = ociDir.resolve("config"); + assertTrue(Files.exists(keyFile)); + assertTrue(Files.exists(configFile)); + + String pem = Files.readString(keyFile); + assertTrue(pem.startsWith("-----BEGIN PRIVATE KEY-----")); + assertTrue(pem.contains("OCI_API_KEY")); + + String config = Files.readString(configFile); + assertTrue(config.contains("[FLOCI]")); + assertTrue(config.contains("tenancy=ocid1.tenancy.oc1..flocilocaltenancy")); + assertTrue(config.contains("key_file=" + keyFile.toAbsolutePath())); + // fingerprint is 16 colon-separated hex bytes + assertTrue(config.matches("(?s).*fingerprint=([0-9a-f]{2}:){15}[0-9a-f]{2}\n.*")); + } + + @Test + void isIdempotent() throws Exception { + Path ociDir = tempDir.resolve(".oci"); + assertEquals(0, run(ociDir)); + String keyBefore = Files.readString(ociDir.resolve("floci_key.pem")); + String configBefore = Files.readString(ociDir.resolve("config")); + + assertEquals(0, run(ociDir)); + assertEquals(keyBefore, Files.readString(ociDir.resolve("floci_key.pem"))); + assertEquals(configBefore, Files.readString(ociDir.resolve("config"))); + } + + @Test + void appendsToExistingConfigWithoutTouchingOtherProfiles() throws Exception { + Path ociDir = tempDir.resolve(".oci"); + Files.createDirectories(ociDir); + String existing = "[DEFAULT]\nuser=ocid1.user.oc1..real\nregion=eu-frankfurt-1\n"; + Files.writeString(ociDir.resolve("config"), existing); + + assertEquals(0, run(ociDir)); + + String config = Files.readString(ociDir.resolve("config")); + assertTrue(config.startsWith(existing)); + assertTrue(config.contains("[FLOCI]")); + } + + @Test + void honorsCustomProfileName() throws Exception { + Path ociDir = tempDir.resolve(".oci"); + assertEquals(0, run(ociDir, "--profile-name", "DEFAULT")); + String config = Files.readString(ociDir.resolve("config")); + assertTrue(config.contains("[DEFAULT]")); + assertFalse(config.contains("[FLOCI]")); + } + + @Test + void detectsTheProfileSetupWrote() throws Exception { + Path ociDir = tempDir.resolve(".oci"); + assertNull(OciSetupCommand.detectSetupProfile(ociDir.resolve("config"))); + + assertEquals(0, run(ociDir, "--profile-name", "CUSTOM")); + assertEquals("CUSTOM", OciSetupCommand.detectSetupProfile(ociDir.resolve("config"))); + + // A second, FLOCI-named section sharing the setup key wins over CUSTOM + assertEquals(0, run(ociDir)); + assertEquals("FLOCI", OciSetupCommand.detectSetupProfile(ociDir.resolve("config"))); + } + + @Test + void detectIgnoresForeignProfiles() throws Exception { + Path ociDir = tempDir.resolve(".oci"); + Files.createDirectories(ociDir); + Files.writeString(ociDir.resolve("config"), + "[PROD]\nuser=ocid1.user.oc1..real\nkey_file=~/.oci/prod_key.pem\n"); + assertNull(OciSetupCommand.detectSetupProfile(ociDir.resolve("config"))); + } +}