diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5d93d26..2f14090 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,29 +37,6 @@ jobs: - name: Run unit tests run: mvn test -B - native-linux-amd64: - name: Native image — linux/amd64 - runs-on: ubuntu-latest - timeout-minutes: 45 - steps: - - uses: actions/checkout@v4 - - - uses: graalvm/setup-graalvm@v1 - with: - java-version: '25' - distribution: 'graalvm-community' - cache: maven - github-token: ${{ secrets.GITHUB_TOKEN }} - - - name: Build native binary - run: mvn clean package -Pnative -DskipTests -B - - - name: Smoke test — version - run: ./target/floci version - - - name: Smoke test — doctor - run: ./target/floci doctor || true - native-linux-arm64: name: Native image — linux/arm64 runs-on: ubuntu-24.04-arm @@ -79,3 +56,6 @@ jobs: - name: Smoke test — version run: ./target/floci version + + - name: Smoke test — doctor + run: ./target/floci doctor || true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b0970f3..fca43f5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,7 +1,7 @@ name: Release # Triggered when a SemVer tag (e.g. 0.1.0) is pushed. -# Builds native binaries for all 5 platform targets and creates a GitHub Release. +# Builds native binaries for 4 platform targets and creates a GitHub Release. on: push: @@ -54,25 +54,6 @@ jobs: name: floci-linux-arm64 path: target/floci-linux-arm64 - build-darwin-amd64: - name: Build — darwin/amd64 - runs-on: macos-13 - timeout-minutes: 45 - steps: - - uses: actions/checkout@v4 - - uses: graalvm/setup-graalvm@v1 - with: - java-version: '25' - distribution: 'graalvm-community' - cache: maven - github-token: ${{ secrets.GITHUB_TOKEN }} - - run: mvn clean package -Pnative -DskipTests -B - - run: mv target/floci target/floci-darwin-amd64 - - uses: actions/upload-artifact@v4 - with: - name: floci-darwin-amd64 - path: target/floci-darwin-amd64 - build-darwin-arm64: name: Build — darwin/arm64 runs-on: macos-latest @@ -130,7 +111,7 @@ jobs: release: name: Create GitHub Release - needs: [build-linux-amd64, build-linux-arm64, build-darwin-amd64, build-darwin-arm64, build-windows-amd64, build-jar] + needs: [build-linux-amd64, build-linux-arm64, build-darwin-arm64, build-windows-amd64, build-jar] runs-on: ubuntu-latest timeout-minutes: 20 steps: @@ -178,7 +159,6 @@ jobs: files: | dist/floci-linux-amd64/floci-linux-amd64 dist/floci-linux-arm64/floci-linux-arm64 - dist/floci-darwin-amd64/floci-darwin-amd64 dist/floci-darwin-arm64/floci-darwin-arm64 dist/floci-windows-amd64/floci-windows-amd64.exe dist/floci-jar/floci.jar diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d7430d..f64dec3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,31 @@ This project uses [Semantic Versioning](https://semver.org/). ## [Unreleased] -## [0.1.0] — 2024-xx-xx +## [0.1.1] — 2026-05-15 + +### Added + +- `floci az` subcommand group — full Azure emulator lifecycle via `floci az start|stop|restart|status|logs|wait|version|services|doctor|env|snapshot|completion` +- `floci aws` subcommand group — explicit alias for all AWS commands (mirrors bare `floci *`) +- `floci az start` — launches `floci/floci-az:latest` on port 4577, mounts persist dir to `/app/data` +- `floci az env` — prints `AZURE_STORAGE_CONNECTION_STRING` (default) or individual SDK endpoint vars (`--format sdk-vars`); `--service` flag filters to specific services (blob, queue, table, functions, app-config, key-vault) +- `floci az doctor` — Azure-specific diagnostics: all Docker checks against `floci/floci-az` image, plus `az.cli.installed` and `az.cli.connection-string` checks +- `floci config default-product aws|az` — persists the default product to `~/.floci/config.yaml`; bare `floci start` routes to the configured default +- `floci az snapshot` stubs — commands registered but report "not yet available" pending server-side implementation in floci-az + +### Changed + +- `floci start` now routes to the configured default product (AWS unless overridden with `floci config default-product az`) +- `floci env` and `floci az env` now auto-detect the port from the running container's port mapping instead of using the option default +- CI native build reduced to linux/arm64 only — removed linux/amd64 native job from CI (covered by JVM test job); release still ships all platform binaries +- Release drops darwin/amd64 — `macos-13` Intel runners took 34+ minutes for native-image builds; darwin/arm64 (Apple Silicon) ships instead + +### Fixed + +- `floci env` reported wrong port when container ran on a non-default port — now calls `resolvedEndpoint()` before extracting port +- `floci az doctor` incorrectly checked for `floci/floci` image — now checks `floci/floci-az` + +## [0.1.0] — 2026-05-14 ### Added @@ -27,13 +51,11 @@ This project uses [Semantic Versioning](https://semver.org/). - `floci snapshot export|import` — stubs pending server implementation - `floci completion bash|zsh` — generates shell completion scripts - Global flags: `--endpoint`, `--container`, `--profile`, `--output text|json|yaml`, `--quiet`, `--verbose`, `--no-color` -- GraalVM native binary for linux/amd64, linux/arm64, darwin/amd64, darwin/arm64, windows/amd64 -- CI matrix across all 5 platforms with native smoke tests +- GraalVM native binary for linux/amd64, linux/arm64, darwin/arm64, windows/amd64 - Homebrew formula template and automated bump workflow - Scoop bucket template - `curl | sh` installer for Linux and macOS - PowerShell installer for Windows -- Docker image `floci/cli:` ### Known Limitations @@ -41,5 +63,6 @@ This project uses [Semantic Versioning](https://semver.org/). - `floci logs --service` filter is not yet supported (requires server-side log routing) - Shell completion for `fish` and `powershell` is not yet generated by Picocli -[Unreleased]: https://github.com/floci-io/floci-cli/compare/0.1.0...HEAD +[Unreleased]: https://github.com/floci-io/floci-cli/compare/0.1.1...HEAD +[0.1.1]: https://github.com/floci-io/floci-cli/releases/tag/0.1.0...0.1.1 [0.1.0]: https://github.com/floci-io/floci-cli/releases/tag/0.1.0 diff --git a/README.md b/README.md index e19d824..70c41c8 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,17 @@ # floci-cli -Official command-line interface for [Floci](https://floci.io) — the free, open-source local AWS emulator. +Official command-line interface for [Floci](https://floci.io) — the free, open-source local cloud emulator for AWS and Azure. ```sh +# AWS (default) floci start -floci doctor eval $(floci env) aws s3 mb s3://my-bucket + +# Azure +floci az start +eval $(floci az env) +az storage container create --name mycontainer ``` ## Installation @@ -48,8 +53,10 @@ java -jar floci.jar version ## Quick Start +### AWS + ```sh -# Start Floci +# Start Floci (AWS emulator) floci start # Check environment @@ -69,13 +76,56 @@ aws dynamodb create-table --table-name users \ floci stop ``` +### Azure + +```sh +# Start Floci Azure emulator +floci az start + +# Check environment +floci az doctor + +# Export Azure connection string +eval $(floci az env) + +# Use Azure services +az storage container create --name mycontainer +az storage blob upload --container-name mycontainer --name hello.txt --data "hello" + +# Stop Floci Azure +floci az stop +``` + +### Switch default product + +Bare commands like `floci start` route to the configured default product (AWS by default). + +```sh +floci config default-product az # make floci az the default +floci config default-product aws # revert to aws +``` + --- ## Command Reference +Commands are organized into two product groups — `floci aws` (or bare `floci`) and `floci az`. Both groups expose the same lifecycle commands. + +### Shared commands (product-independent) + | Command | Description | |---------|-------------| -| `floci start` | Launch the Floci container | +| `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 or az) | +| `floci completion bash\|zsh` | Generate shell completion scripts | + +### AWS commands (`floci` / `floci aws`) + +| Command | Description | +|---------|-------------| +| `floci start` | Launch the Floci AWS container | | `floci stop` | Stop (and optionally remove) the container | | `floci restart` | Stop then start | | `floci status` | Show container state and server health | @@ -85,25 +135,54 @@ floci stop | `floci services` | List enabled AWS services | | `floci doctor` | Run environment diagnostics | | `floci env` | Print AWS environment variables | -| `floci config show` | Show active configuration | -| `floci config validate` | Validate a docker-compose.yml | -| `floci config profile` | Manage named profiles | | `floci snapshot save/load/list/delete` | Manage state snapshots | -| `floci completion bash\|zsh` | Generate shell completion | -All commands support `--help`. Global flags available on every command: +### Azure commands (`floci az`) + +| Command | Description | +|---------|-------------| +| `floci az start` | Launch the Floci Azure container | +| `floci az stop` | Stop (and optionally remove) the container | +| `floci az restart` | Stop then start | +| `floci az status` | Show container state and server health | +| `floci az logs` | Stream container logs | +| `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 doctor` | Run Azure environment diagnostics | +| `floci az env` | Print Azure connection string / SDK env vars | +| `floci az snapshot` | Snapshot commands (coming soon) | + +All commands support `--help`. + +--- + +## Global Flags + +### AWS global flags ``` ---endpoint Floci server URL (default: http://localhost:4566, env: FLOCI_ENDPOINT) ---container Container name (default: floci, env: FLOCI_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 +--endpoint Floci server URL (default: http://localhost:4566, env: FLOCI_ENDPOINT) +--container Container name (default: floci, env: FLOCI_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`, and `wait` automatically derive the correct +### Azure global flags + +``` +--endpoint Floci Azure server URL (default: http://localhost:4577, env: FLOCI_AZ_ENDPOINT) +--container Container name (default: floci-az, env: FLOCI_AZ_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 +``` + +> **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. @@ -111,20 +190,26 @@ All commands support `--help`. Global flags available on every command: ## Commands -### `floci start` +### `floci start` / `floci az 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 --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 floci start --detach # return immediately, don't wait + +# Azure +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 ``` -### `floci stop` +### `floci stop` / `floci az stop` ```sh floci stop # graceful stop (10s timeout) @@ -132,7 +217,7 @@ floci stop --timeout 30 # wait up to 30s before force-kill floci stop --remove # also remove the container after stopping ``` -### `floci status` +### `floci status` / `floci az status` ```sh floci status # auto-detects endpoint from container port mapping @@ -152,7 +237,6 @@ floci env --shell powershell | Invoke-Expression # PowerShell floci env --host myhost.local # custom hostname floci env --region eu-west-1 # custom region (default: us-east-1) -floci env --endpoint http://localhost:4599 # pick up port from a non-default instance floci env -o json # structured output for scripts ``` @@ -160,12 +244,44 @@ Variables exported: | Variable | Default value | |----------|---------------| -| `AWS_ENDPOINT_URL` | `http://localhost.floci.io:4566` | +| `AWS_ENDPOINT_URL` | `http://localhost.floci.io:` | | `AWS_ACCESS_KEY_ID` | `test` | | `AWS_SECRET_ACCESS_KEY` | `test` | | `AWS_DEFAULT_REGION` | `us-east-1` | -### `floci logs` +### `floci az env` + +Prints Azure connection variables for the running Floci Azure instance. + +```sh +eval $(floci az env) # connection string (default) +eval $(floci az env --format sdk-vars) # individual SDK endpoint vars +eval $(floci az env --format sdk-vars --service blob,queue) # specific services only + +floci az env --shell fish | source # fish +floci az env -o json # structured output +``` + +**Connection string mode** (default) exports: + +| Variable | Value | +|----------|-------| +| `AZURE_STORAGE_CONNECTION_STRING` | Full Azurite-compatible connection string | + +**SDK vars mode** (`--format sdk-vars`) exports: + +| Variable | Default value | +|----------|---------------| +| `AZURE_STORAGE_ACCOUNT` | `devstoreaccount1` | +| `AZURE_STORAGE_KEY` | Azurite dev key | +| `AZURE_STORAGE_BLOB_ENDPOINT` | `http://localhost.floci.io:/devstoreaccount1` | +| `AZURE_STORAGE_QUEUE_ENDPOINT` | `http://localhost.floci.io:/devstoreaccount1-queue` | +| `AZURE_STORAGE_TABLE_ENDPOINT` | `http://localhost.floci.io:/devstoreaccount1-table` | +| `AZURE_FUNCTIONS_ENDPOINT` | `http://localhost.floci.io:/devstoreaccount1-functions` | +| `AZURE_APP_CONFIGURATION_ENDPOINT` | `http://localhost.floci.io:/devstoreaccount1-appconfig` | +| `AZURE_KEY_VAULT_ENDPOINT` | `http://localhost.floci.io:/devstoreaccount1-keyvault` | + +### `floci logs` / `floci az logs` ```sh floci logs # last logs from the container @@ -174,7 +290,7 @@ floci logs --since 5m # logs from the last 5 minutes floci logs --follow # stream live logs (Ctrl-C to stop) ``` -### `floci wait` +### `floci wait` / `floci az wait` ```sh floci wait # wait up to 30s (default) @@ -183,28 +299,28 @@ floci wait --service dynamodb # wait until a specific service is ready floci wait -o json # machine-readable output ``` -### `floci doctor` +### `floci doctor` / `floci az doctor` ```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 az doctor # Azure-specific checks (includes az CLI + connection string) ``` -### `floci version` +### `floci version` / `floci az version` ```sh floci version # CLI version, server version, image digest floci version -o json ``` -### `floci services` +### `floci services` / `floci az services` ```sh floci services # list all enabled services -floci services --mode docker # only docker-backed services -floci services --mode in-process # only in-process services floci services -o json ``` @@ -212,6 +328,7 @@ floci services -o json ```sh floci config show # show active configuration +floci config default-product aws|az # 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 @@ -224,7 +341,7 @@ Use `--profile ` on any command to load one. ### `floci snapshot` -Save and restore named snapshots of Floci state (requires server-side support — coming soon). +Save and restore named snapshots of Floci AWS state. ```sh floci snapshot list @@ -235,6 +352,8 @@ floci snapshot export -o tarball.tar.gz floci snapshot import tarball.tar.gz ``` +> Azure snapshots (`floci az snapshot`) are not yet available — they require server-side endpoints not yet implemented in Floci Azure. + ### `floci completion` ```sh @@ -246,22 +365,16 @@ floci completion zsh >> ~/.zshrc ## CI Usage +### AWS CI + ```sh -floci start --port 4566 --detach +floci start --detach floci wait --timeout 60s +eval $(floci env) pytest # or your test command floci stop --remove ``` -Set AWS environment variables in CI before running tests: - -```sh -export AWS_ENDPOINT_URL=http://localhost:4566 -export AWS_ACCESS_KEY_ID=test -export AWS_SECRET_ACCESS_KEY=test -export AWS_DEFAULT_REGION=us-east-1 -``` - With Docker Compose: ```yaml @@ -274,13 +387,35 @@ services: - /var/run/docker.sock:/var/run/docker.sock ``` +### Azure CI + +```sh +floci az start --detach +floci az wait --timeout 60s +eval $(floci az env) +pytest # or your test command +floci az stop --remove +``` + +With Docker Compose: + +```yaml +services: + floci-az: + image: floci/floci-az:latest + ports: + - "4577:4577" + 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 CLI or manage AWS resources. -Use `aws` with `AWS_ENDPOINT_URL=http://localhost:4566` for resource operations. +It does **not** wrap the AWS CLI, Azure CLI, or manage cloud resources directly. +Use `aws` with `AWS_ENDPOINT_URL` or `az` with the appropriate connection string for resource operations. --- diff --git a/pom.xml b/pom.xml index f47b3d0..972258e 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ io.floci floci-cli - 0.1.0 + 0.1.1 jar Floci CLI diff --git a/src/main/java/io/floci/cli/AzGlobalOptions.java b/src/main/java/io/floci/cli/AzGlobalOptions.java new file mode 100644 index 0000000..673a73d --- /dev/null +++ b/src/main/java/io/floci/cli/AzGlobalOptions.java @@ -0,0 +1,80 @@ +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 AzGlobalOptions { + + @Option(names = {"--endpoint"}, + description = "Floci Azure server endpoint URL", + defaultValue = "${FLOCI_AZ_ENDPOINT:-http://localhost:4577}", + paramLabel = "") + public String endpoint; + + @Option(names = {"--container"}, + description = "Floci Azure container name", + defaultValue = "${FLOCI_AZ_CONTAINER:-floci-az}", + 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 = 4577; + 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; + } +} diff --git a/src/main/java/io/floci/cli/FlociCli.java b/src/main/java/io/floci/cli/FlociCli.java index 191dc8c..1d73c2f 100644 --- a/src/main/java/io/floci/cli/FlociCli.java +++ b/src/main/java/io/floci/cli/FlociCli.java @@ -1,21 +1,25 @@ package io.floci.cli; import io.floci.cli.commands.*; +import io.floci.cli.commands.aws.AwsCommand; +import io.floci.cli.commands.az.AzCommand; import io.floci.cli.commands.config.ConfigCommand; import io.floci.cli.commands.snapshot.SnapshotCommand; +import io.floci.cli.config.GlobalConfigStore; import io.floci.cli.output.Ansi; import picocli.CommandLine; import picocli.CommandLine.*; @Command( name = "floci", - description = "Manage your local Floci AWS emulator%n%n" + - " floci start — launch the container%n" + + description = "Manage your local Floci emulators%n%n" + + " floci start — launch the container (default: aws)%n" + " floci stop — stop the container%n" + " floci status — show health and version%n" + " floci doctor — diagnose environment issues%n" + - " floci logs — stream container logs%n" + - " floci env — print AWS environment variables%n", + " floci env — print environment variables%n" + + " floci aws — explicit AWS emulator commands%n" + + " floci az — Azure emulator commands%n", mixinStandardHelpOptions = true, versionProvider = FlociCli.VersionProvider.class, subcommands = { @@ -32,6 +36,8 @@ import picocli.CommandLine.*; ConfigCommand.class, SnapshotCommand.class, CompletionCommand.class, + AwsCommand.class, + AzCommand.class, HelpCommand.class } ) @@ -56,17 +62,45 @@ public class FlociCli implements Runnable { } public static void main(String[] args) { - // Honor NO_COLOR and non-TTY environments if (System.getenv("NO_COLOR") != null || System.console() == null) { Ansi.disable(); } + + // If no explicit product subcommand, route bare commands to the configured default. + // "floci az start" and "floci aws start" always win; only bare "floci start" is affected. + String[] effectiveArgs = args; + if (!isExplicitProduct(args)) { + String defaultProduct = new GlobalConfigStore().getDefaultProduct(); + if ("az".equals(defaultProduct)) { + effectiveArgs = prepend("az", args); + } + } + int exitCode = new CommandLine(new FlociCli()) .setExecutionExceptionHandler(new ExceptionHandler()) .setCaseInsensitiveEnumValuesAllowed(true) - .execute(args); + .execute(effectiveArgs); System.exit(exitCode); } + // Returns true when routing should NOT apply: explicit product subgroup, + // or a product-independent command like "config" or "completion". + private static boolean isExplicitProduct(String[] args) { + for (String arg : args) { + if (arg.startsWith("-")) continue; + return "aws".equals(arg) || "az".equals(arg) + || "config".equals(arg) || "completion".equals(arg) || "help".equals(arg); + } + return false; + } + + private static String[] prepend(String token, String[] args) { + String[] result = new String[args.length + 1]; + result[0] = token; + System.arraycopy(args, 0, result, 1, args.length); + return result; + } + @Override public void run() { new CommandLine(this).usage(System.out); diff --git a/src/main/java/io/floci/cli/ProductProfile.java b/src/main/java/io/floci/cli/ProductProfile.java new file mode 100644 index 0000000..78562b3 --- /dev/null +++ b/src/main/java/io/floci/cli/ProductProfile.java @@ -0,0 +1,22 @@ +package io.floci.cli; + +public record ProductProfile( + String name, + String defaultImage, + String defaultContainer, + int defaultPort, + String endpointEnvVar, + String containerEnvVar, + String persistPath, + String servicesEnvVar +) { + public static final ProductProfile AWS = new ProductProfile( + "aws", "floci/floci:latest", "floci", 4566, + "FLOCI_ENDPOINT", "FLOCI_CONTAINER", "/var/lib/floci", "FLOCI_SERVICES" + ); + + public static final ProductProfile AZ = new ProductProfile( + "az", "floci/floci-az:latest", "floci-az", 4577, + "FLOCI_AZ_ENDPOINT", "FLOCI_AZ_CONTAINER", "/app/data", "FLOCI_AZ_SERVICES" + ); +} diff --git a/src/main/java/io/floci/cli/commands/DoctorCommand.java b/src/main/java/io/floci/cli/commands/DoctorCommand.java index 39b69f2..09973db 100644 --- a/src/main/java/io/floci/cli/commands/DoctorCommand.java +++ b/src/main/java/io/floci/cli/commands/DoctorCommand.java @@ -43,7 +43,7 @@ public class DoctorCommand implements Callable { @Option(names = {"--fix"}, description = "Attempt to auto-fix fixable issues") boolean fix; - private static final List ALL_CHECKS = List.of( + public static final List DOCKER_CHECKS = List.of( new DockerInstalledCheck(), new DockerDaemonCheck(), new DockerSocketCheck(), @@ -52,11 +52,26 @@ public class DoctorCommand implements Callable { new ImagePresentCheck(), new ImageVersionCheck(), new ContainerRunningCheck(), - new EndpointReachableCheck(), + new EndpointReachableCheck() + ); + + public static final List AWS_COMPANION_CHECKS = List.of( new AwsCliEndpointCheck(), new AwsCliS3PathStyleCheck() ); + private final List allChecks; + + public DoctorCommand() { + this(AWS_COMPANION_CHECKS); + } + + public DoctorCommand(List companionChecks) { + List checks = new ArrayList<>(DOCKER_CHECKS); + checks.addAll(companionChecks); + this.allChecks = List.copyOf(checks); + } + @Override public Integer call() { Printer printer = global.printer(); @@ -70,7 +85,7 @@ public class DoctorCommand implements Callable { printer.println(""); } - for (Check check : ALL_CHECKS) { + for (Check check : allChecks) { CheckResult result = check.run(effectiveEndpoint, global.container); if (checkName != null && !result.name().equals(checkName)) continue; results.add(result); @@ -105,7 +120,7 @@ public class DoctorCommand implements Callable { return fails > 0 ? 1 : 0; } - private void printResult(Printer printer, CheckResult r) { + public static void printResult(Printer printer, CheckResult r) { String icon = switch (r.status()) { case ok -> Ansi.green("✓"); case warn -> Ansi.yellow("⚠"); diff --git a/src/main/java/io/floci/cli/commands/EnvCommand.java b/src/main/java/io/floci/cli/commands/EnvCommand.java index 694fb08..7fa9fb0 100644 --- a/src/main/java/io/floci/cli/commands/EnvCommand.java +++ b/src/main/java/io/floci/cli/commands/EnvCommand.java @@ -1,6 +1,7 @@ package io.floci.cli.commands; import io.floci.cli.GlobalOptions; +import io.floci.cli.docker.DockerClient; import io.floci.cli.output.Ansi; import io.floci.cli.output.OutputFormat; import io.floci.cli.output.Printer; @@ -42,7 +43,8 @@ public class EnvCommand implements Callable { @Override public Integer call() { Printer printer = global.printer(); - int port = extractPort(global.endpoint); + String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); + int port = extractPort(effectiveEndpoint); String endpointUrl = "http://" + host + ":" + port; Map vars = new LinkedHashMap<>(); diff --git a/src/main/java/io/floci/cli/commands/aws/AwsCommand.java b/src/main/java/io/floci/cli/commands/aws/AwsCommand.java new file mode 100644 index 0000000..5eb8174 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/aws/AwsCommand.java @@ -0,0 +1,41 @@ +package io.floci.cli.commands.aws; + +import io.floci.cli.commands.*; +import io.floci.cli.commands.config.ConfigCommand; +import io.floci.cli.commands.snapshot.SnapshotCommand; +import picocli.CommandLine; +import picocli.CommandLine.*; + +@Command( + name = "aws", + description = "Manage the Floci AWS emulator%n%n" + + " floci aws start — launch the container%n" + + " floci aws stop — stop the container%n" + + " floci aws status — show health and version%n" + + " floci aws doctor — diagnose environment issues%n" + + " floci aws env — print AWS environment variables%n", + mixinStandardHelpOptions = true, + subcommands = { + StartCommand.class, + StopCommand.class, + RestartCommand.class, + StatusCommand.class, + LogsCommand.class, + WaitCommand.class, + VersionCommand.class, + ServicesCommand.class, + DoctorCommand.class, + EnvCommand.class, + ConfigCommand.class, + SnapshotCommand.class, + CompletionCommand.class, + HelpCommand.class + } +) +public class AwsCommand implements Runnable { + + @Override + public void run() { + new CommandLine(this).usage(System.out); + } +} diff --git a/src/main/java/io/floci/cli/commands/az/AzCommand.java b/src/main/java/io/floci/cli/commands/az/AzCommand.java new file mode 100644 index 0000000..eb80d5f --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/AzCommand.java @@ -0,0 +1,41 @@ +package io.floci.cli.commands.az; + +import io.floci.cli.commands.CompletionCommand; +import io.floci.cli.commands.az.config.AzConfigCommand; +import io.floci.cli.commands.az.snapshot.AzSnapshotCommand; +import picocli.CommandLine; +import picocli.CommandLine.*; + +@Command( + name = "az", + description = "Manage the Floci Azure emulator (floci-az)%n%n" + + " floci az start — launch the container%n" + + " floci az stop — stop the container%n" + + " floci az status — show health and version%n" + + " floci az doctor — diagnose environment issues%n" + + " floci az env — print Azure environment variables%n", + mixinStandardHelpOptions = true, + subcommands = { + AzStartCommand.class, + AzStopCommand.class, + AzRestartCommand.class, + AzStatusCommand.class, + AzLogsCommand.class, + AzWaitCommand.class, + AzVersionCommand.class, + AzServicesCommand.class, + AzDoctorCommand.class, + AzEnvCommand.class, + AzConfigCommand.class, + AzSnapshotCommand.class, + CompletionCommand.class, + HelpCommand.class + } +) +public class AzCommand implements Runnable { + + @Override + public void run() { + new CommandLine(this).usage(System.out); + } +} diff --git a/src/main/java/io/floci/cli/commands/az/AzDoctorCommand.java b/src/main/java/io/floci/cli/commands/az/AzDoctorCommand.java new file mode 100644 index 0000000..e424627 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/AzDoctorCommand.java @@ -0,0 +1,116 @@ +package io.floci.cli.commands.az; + +import io.floci.cli.AzGlobalOptions; +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.AzCliConnectionStringCheck; +import io.floci.cli.doctor.checks.AzCliInstalledCheck; +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 Azure", + mixinStandardHelpOptions = true +) +public class AzDoctorCommand implements Callable { + + @Mixin + AzGlobalOptions 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; + + public static final List AZ_COMPANION_CHECKS = List.of( + new AzCliInstalledCheck(), + new AzCliConnectionStringCheck() + ); + + 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-az")); + checks.add(new ImageVersionCheck("floci/floci-az")); + checks.add(new ContainerRunningCheck()); + checks.add(new EndpointReachableCheck()); + checks.addAll(AZ_COMPANION_CHECKS); + 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 Azure 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/az/AzEnvCommand.java b/src/main/java/io/floci/cli/commands/az/AzEnvCommand.java new file mode 100644 index 0000000..ed4f86d --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/AzEnvCommand.java @@ -0,0 +1,161 @@ +package io.floci.cli.commands.az; + +import io.floci.cli.AzGlobalOptions; +import io.floci.cli.docker.DockerClient; +import io.floci.cli.doctor.checks.AzCliConnectionStringCheck; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.OutputFormat; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.net.URI; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.Callable; + +@Command( + name = "env", + description = "Print Azure environment variables to connect to Floci Azure", + mixinStandardHelpOptions = true +) +public class AzEnvCommand implements Callable { + + private static final String DEV_ACCOUNT = "devstoreaccount1"; + private static final String DEV_KEY = + "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMh0=="; + + private static final Set ALL_SERVICES = + Set.of("blob", "queue", "table", "functions", "app-config", "key-vault"); + + @Mixin + AzGlobalOptions global; + + @Option(names = {"--format"}, + description = "Output mode: connection-string, sdk-vars (default: connection-string)", + defaultValue = "connection-string", + paramLabel = "connection-string|sdk-vars") + String format; + + @Option(names = {"--service"}, + description = "Comma-separated services for sdk-vars mode: blob,queue,table,functions,app-config,key-vault", + paramLabel = "") + String serviceFilter; + + @Option(names = {"--account"}, + description = "Storage account name (default: devstoreaccount1)", + defaultValue = "${FLOCI_AZ_ACCOUNT:-devstoreaccount1}", + paramLabel = "") + String account; + + @Option(names = {"--host"}, + description = "Hostname for endpoint URLs (default: localhost.floci.io)", + defaultValue = "${FLOCI_AZ_HOST:-localhost.floci.io}", + paramLabel = "") + String host; + + @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 effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); + int port = extractPort(effectiveEndpoint); + + boolean sdkVarsMode = "sdk-vars".equals(format) || serviceFilter != null; + List requestedServices = resolveServices(); + + if (printer.format() != OutputFormat.text) { + Map out = new LinkedHashMap<>(); + if (!sdkVarsMode) { + out.put("AZURE_STORAGE_CONNECTION_STRING", + AzCliConnectionStringCheck.buildConnectionString(account, host, port)); + } else { + out.put("AZURE_STORAGE_ACCOUNT", account); + out.put("AZURE_STORAGE_KEY", DEV_KEY); + for (String svc : requestedServices) { + out.put(envVarName(svc), buildEndpointUrl(svc, host, port, account)); + } + } + printer.structured(out); + return 0; + } + + if (!sdkVarsMode) { + String connStr = AzCliConnectionStringCheck.buildConnectionString(account, host, port); + printer.println(formatExport("AZURE_STORAGE_CONNECTION_STRING", connStr)); + printer.println(""); + printer.println(Ansi.gray("# Run: eval $(floci az env)")); + } else { + printer.println(formatExport("AZURE_STORAGE_ACCOUNT", account)); + printer.println(formatExport("AZURE_STORAGE_KEY", DEV_KEY)); + for (String svc : requestedServices) { + printer.println(formatExport(envVarName(svc), buildEndpointUrl(svc, host, port, account))); + } + printer.println(""); + printer.println(Ansi.gray("# Run: eval $(floci az env --format sdk-vars)")); + } + + return 0; + } + + private List resolveServices() { + if (serviceFilter != null && !serviceFilter.isBlank()) { + List result = new ArrayList<>(); + for (String s : serviceFilter.split(",")) { + String svc = s.trim().toLowerCase(); + if (ALL_SERVICES.contains(svc)) result.add(svc); + } + return result; + } + return List.of("blob", "queue", "table", "functions", "app-config", "key-vault"); + } + + private String envVarName(String service) { + return switch (service) { + case "blob" -> "AZURE_STORAGE_BLOB_ENDPOINT"; + case "queue" -> "AZURE_STORAGE_QUEUE_ENDPOINT"; + case "table" -> "AZURE_STORAGE_TABLE_ENDPOINT"; + case "functions" -> "AZURE_FUNCTIONS_ENDPOINT"; + case "app-config" -> "AZURE_APP_CONFIGURATION_ENDPOINT"; + case "key-vault" -> "AZURE_KEY_VAULT_ENDPOINT"; + default -> "AZURE_" + service.toUpperCase().replace('-', '_') + "_ENDPOINT"; + }; + } + + private String buildEndpointUrl(String service, String host, int port, String accountName) { + String base = "http://" + host + ":" + port + "/" + accountName; + return switch (service) { + case "blob" -> base; + case "queue" -> base + "-queue"; + case "table" -> base + "-table"; + case "functions" -> base + "-functions"; + case "app-config" -> base + "-appconfig"; + case "key-vault" -> base + "-keyvault"; + default -> base + "-" + service; + }; + } + + private String formatExport(String key, String value) { + return switch (shell.toLowerCase()) { + case "fish" -> "set -x " + key + " \"" + value + "\""; + case "powershell", "ps1" -> "$env:" + key + " = \"" + value + "\""; + default -> "export " + key + "=" + value; + }; + } + + private int extractPort(String endpoint) { + try { + int p = URI.create(endpoint).getPort(); + return p == -1 ? 4577 : p; + } catch (Exception e) { + return 4577; + } + } +} diff --git a/src/main/java/io/floci/cli/commands/az/AzLogsCommand.java b/src/main/java/io/floci/cli/commands/az/AzLogsCommand.java new file mode 100644 index 0000000..d625616 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/AzLogsCommand.java @@ -0,0 +1,54 @@ +package io.floci.cli.commands.az; + +import io.floci.cli.AzGlobalOptions; +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 Azure container", + mixinStandardHelpOptions = true +) +public class AzLogsCommand implements Callable { + + @Mixin + AzGlobalOptions 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 az 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; + } + } +} diff --git a/src/main/java/io/floci/cli/commands/az/AzRestartCommand.java b/src/main/java/io/floci/cli/commands/az/AzRestartCommand.java new file mode 100644 index 0000000..b5e0444 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/AzRestartCommand.java @@ -0,0 +1,40 @@ +package io.floci.cli.commands.az; + +import io.floci.cli.AzGlobalOptions; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "restart", + description = "Stop and restart the Floci Azure container", + mixinStandardHelpOptions = true +) +public class AzRestartCommand implements Callable { + + @Mixin + AzGlobalOptions global; + + @Override + public Integer call() { + Printer printer = global.printer(); + + AzStopCommand stop = new AzStopCommand(); + 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(); } + + AzStartCommand start = new AzStartCommand(); + start.global = global; + start.port = 4577; + start.pull = "missing"; + start.image = "floci/floci-az:latest"; + start.detach = false; + return start.call(); + } +} diff --git a/src/main/java/io/floci/cli/commands/az/AzServicesCommand.java b/src/main/java/io/floci/cli/commands/az/AzServicesCommand.java new file mode 100644 index 0000000..ec61217 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/AzServicesCommand.java @@ -0,0 +1,55 @@ +package io.floci.cli.commands.az; + +import io.floci.cli.AzGlobalOptions; +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 Azure instance", + mixinStandardHelpOptions = true +) +public class AzServicesCommand implements Callable { + + @Mixin + AzGlobalOptions global; + + @Override + public Integer call() { + Printer printer = global.printer(); + FlociHttpClient client = new FlociHttpClient(global.endpoint); + + List services; + try { + var health = client.health(); + services = Arrays.asList(health.services()); + } catch (Exception e) { + printer.error("Could not reach Floci Azure at " + global.endpoint + ".\nIs Floci Azure running? Try 'floci az start'."); + return 1; + } + + if (printer.format() != OutputFormat.text) { + printer.structured(Map.of("services", services, "count", services.size())); + return 0; + } + + printer.println(Ansi.bold("Floci Azure 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/az/AzStartCommand.java b/src/main/java/io/floci/cli/commands/az/AzStartCommand.java new file mode 100644 index 0000000..f3bac80 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/AzStartCommand.java @@ -0,0 +1,110 @@ +package io.floci.cli.commands.az; + +import io.floci.cli.AzGlobalOptions; +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 Azure emulator container", + mixinStandardHelpOptions = true +) +public class AzStartCommand implements Callable { + + @Mixin + AzGlobalOptions global; + + @Option(names = {"--port"}, description = "Host port to bind (default: 4577)", defaultValue = "4577", 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-az:latest)", defaultValue = "floci/floci-az: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 az 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 az 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 + ":4577")); + args.addAll(List.of("-v", "/var/run/docker.sock:/var/run/docker.sock")); + if (persistDir != null) { + args.addAll(List.of("-v", persistDir + ":/app/data")); + } + if (services != null && !services.isBlank()) { + args.addAll(List.of("-e", "FLOCI_AZ_SERVICES=" + services)); + } + args.add(image); + + try { + printer.println("Starting " + Ansi.gold("Floci Azure") + " 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 az wait' to poll for readiness.")); + return 0; + } + + global.endpoint = "http://localhost:" + port; + + printer.println(Ansi.gray("Waiting for Floci Azure to be ready...")); + AzWaitCommand wait = new AzWaitCommand(); + wait.global = global; + wait.timeout = "30s"; + return wait.call(); + } +} diff --git a/src/main/java/io/floci/cli/commands/az/AzStatusCommand.java b/src/main/java/io/floci/cli/commands/az/AzStatusCommand.java new file mode 100644 index 0000000..7751cb7 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/AzStatusCommand.java @@ -0,0 +1,98 @@ +package io.floci.cli.commands.az; + +import io.floci.cli.AzGlobalOptions; +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 Azure container and server status", + mixinStandardHelpOptions = true +) +public class AzStatusCommand implements Callable { + + @Mixin + AzGlobalOptions 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); + 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 Azure 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 az start' to launch Floci Azure.")); + } + + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/az/AzStopCommand.java b/src/main/java/io/floci/cli/commands/az/AzStopCommand.java new file mode 100644 index 0000000..dba11e1 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/AzStopCommand.java @@ -0,0 +1,73 @@ +package io.floci.cli.commands.az; + +import io.floci.cli.AzGlobalOptions; +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 Azure container", + mixinStandardHelpOptions = true +) +public class AzStopCommand implements Callable { + + @Mixin + AzGlobalOptions 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 az 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 Azure") + " 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; + } +} diff --git a/src/main/java/io/floci/cli/commands/az/AzVersionCommand.java b/src/main/java/io/floci/cli/commands/az/AzVersionCommand.java new file mode 100644 index 0000000..2015208 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/AzVersionCommand.java @@ -0,0 +1,72 @@ +package io.floci.cli.commands.az; + +import io.floci.cli.AzGlobalOptions; +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 Azure server version, and image digest", + mixinStandardHelpOptions = true +) +public class AzVersionCommand implements Callable { + + @Mixin + AzGlobalOptions 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); + try { + var info = client.info(); + serverVersion = info.version(); + serverEdition = info.edition(); + } catch (Exception ignored) {} + + try { + imageDigest = docker.imageDigest("floci/floci-az").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/az/AzWaitCommand.java b/src/main/java/io/floci/cli/commands/az/AzWaitCommand.java new file mode 100644 index 0000000..a06bc23 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/AzWaitCommand.java @@ -0,0 +1,73 @@ +package io.floci.cli.commands.az; + +import io.floci.cli.AzGlobalOptions; +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 Azure is ready to accept requests", + mixinStandardHelpOptions = true +) +public class AzWaitCommand implements Callable { + + @Mixin + AzGlobalOptions 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); + 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 Azure 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 Azure after " + timeout + ".\nIs the container running? Try 'floci az 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; + } + } +} diff --git a/src/main/java/io/floci/cli/commands/az/config/AzConfigCommand.java b/src/main/java/io/floci/cli/commands/az/config/AzConfigCommand.java new file mode 100644 index 0000000..686a16c --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/config/AzConfigCommand.java @@ -0,0 +1,23 @@ +package io.floci.cli.commands.az.config; + +import picocli.CommandLine; +import picocli.CommandLine.*; + +@Command( + name = "config", + description = "Manage Floci Azure configuration", + mixinStandardHelpOptions = true, + subcommands = { + AzConfigShowCommand.class, + AzConfigValidateCommand.class, + AzConfigProfileCommand.class, + HelpCommand.class + } +) +public class AzConfigCommand implements Runnable { + + @Override + public void run() { + new CommandLine(this).usage(System.out); + } +} diff --git a/src/main/java/io/floci/cli/commands/az/config/AzConfigProfileCommand.java b/src/main/java/io/floci/cli/commands/az/config/AzConfigProfileCommand.java new file mode 100644 index 0000000..1d3167c --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/config/AzConfigProfileCommand.java @@ -0,0 +1,115 @@ +package io.floci.cli.commands.az.config; + +import io.floci.cli.AzGlobalOptions; +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 Azure configuration profiles", + mixinStandardHelpOptions = true, + subcommands = {HelpCommand.class} +) +public class AzConfigProfileCommand implements Callable { + + @Mixin + AzGlobalOptions 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 az 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/az/config/AzConfigShowCommand.java b/src/main/java/io/floci/cli/commands/az/config/AzConfigShowCommand.java new file mode 100644 index 0000000..6340534 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/config/AzConfigShowCommand.java @@ -0,0 +1,70 @@ +package io.floci.cli.commands.az.config; + +import io.floci.cli.AzGlobalOptions; +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 Azure configuration", + mixinStandardHelpOptions = true +) +public class AzConfigShowCommand implements Callable { + + @Mixin + AzGlobalOptions 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 Azure)")); + 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/az/config/AzConfigValidateCommand.java b/src/main/java/io/floci/cli/commands/az/config/AzConfigValidateCommand.java new file mode 100644 index 0000000..a326f79 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/config/AzConfigValidateCommand.java @@ -0,0 +1,91 @@ +package io.floci.cli.commands.az.config; + +import io.floci.cli.AzGlobalOptions; +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 Azure compatibility", + mixinStandardHelpOptions = true +) +public class AzConfigValidateCommand implements Callable { + + @Mixin + AzGlobalOptions 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 Azure Functions"); + } + + if (!Pattern.compile("4577\\s*:\\s*4577").matcher(content).find()) { + issues.add("Port mapping 4577:4577 not found — Floci Azure listens on 4577 by default"); + } + + if (!content.contains("floci/floci-az") && !content.contains("ghcr.io/floci-io/floci-az")) { + warnings.add("Floci Azure image reference not detected — ensure your service uses floci/floci-az"); + } + + 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/az/snapshot/AzSnapshotCommand.java b/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotCommand.java new file mode 100644 index 0000000..7729791 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotCommand.java @@ -0,0 +1,26 @@ +package io.floci.cli.commands.az.snapshot; + +import picocli.CommandLine; +import picocli.CommandLine.*; + +@Command( + name = "snapshot", + description = "Manage Floci Azure state snapshots (coming soon)", + mixinStandardHelpOptions = true, + subcommands = { + AzSnapshotSaveCommand.class, + AzSnapshotLoadCommand.class, + AzSnapshotListCommand.class, + AzSnapshotDeleteCommand.class, + AzSnapshotExportCommand.class, + AzSnapshotImportCommand.class, + HelpCommand.class + } +) +public class AzSnapshotCommand implements Runnable { + + @Override + public void run() { + new CommandLine(this).usage(System.out); + } +} diff --git a/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotDeleteCommand.java b/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotDeleteCommand.java new file mode 100644 index 0000000..9a3493e --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotDeleteCommand.java @@ -0,0 +1,28 @@ +package io.floci.cli.commands.az.snapshot; + +import io.floci.cli.AzGlobalOptions; +import io.floci.cli.output.Ansi; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "delete", + description = "Delete a Floci Azure snapshot", + mixinStandardHelpOptions = true +) +public class AzSnapshotDeleteCommand implements Callable { + + @Mixin + AzGlobalOptions 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 Azure.") + + "\nTrack progress: https://github.com/floci-io/floci-az/issues"); + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotExportCommand.java b/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotExportCommand.java new file mode 100644 index 0000000..6dfbb89 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotExportCommand.java @@ -0,0 +1,31 @@ +package io.floci.cli.commands.az.snapshot; + +import io.floci.cli.AzGlobalOptions; +import io.floci.cli.output.Ansi; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "export", + description = "Export a Floci Azure snapshot to a tarball file", + mixinStandardHelpOptions = true +) +public class AzSnapshotExportCommand implements Callable { + + @Mixin + AzGlobalOptions 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 Azure.") + + "\nTrack progress: https://github.com/floci-io/floci-az/issues"); + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotImportCommand.java b/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotImportCommand.java new file mode 100644 index 0000000..e471c19 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotImportCommand.java @@ -0,0 +1,31 @@ +package io.floci.cli.commands.az.snapshot; + +import io.floci.cli.AzGlobalOptions; +import io.floci.cli.output.Ansi; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "import", + description = "Import a Floci Azure snapshot from a tarball file", + mixinStandardHelpOptions = true +) +public class AzSnapshotImportCommand implements Callable { + + @Mixin + AzGlobalOptions global; + + @Option(names = {"--file", "-f"}, description = "Source tarball path", required = true, paramLabel = "") + String inputFile; + + @Option(names = {"--name"}, description = "Name for the imported snapshot", paramLabel = "") + String name; + + @Override + public Integer call() { + global.printer().println(Ansi.yellow("Snapshots are not yet available for Floci Azure.") + + "\nTrack progress: https://github.com/floci-io/floci-az/issues"); + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotListCommand.java b/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotListCommand.java new file mode 100644 index 0000000..ebc592d --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotListCommand.java @@ -0,0 +1,34 @@ +package io.floci.cli.commands.az.snapshot; + +import io.floci.cli.AzGlobalOptions; +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 Azure snapshots", + mixinStandardHelpOptions = true +) +public class AzSnapshotListCommand implements Callable { + + @Mixin + AzGlobalOptions 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 Azure is coming — https://github.com/floci-io/floci-az/issues)"); + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotLoadCommand.java b/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotLoadCommand.java new file mode 100644 index 0000000..996e2e9 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotLoadCommand.java @@ -0,0 +1,28 @@ +package io.floci.cli.commands.az.snapshot; + +import io.floci.cli.AzGlobalOptions; +import io.floci.cli.output.Ansi; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "load", + description = "Restore a saved Floci Azure snapshot", + mixinStandardHelpOptions = true +) +public class AzSnapshotLoadCommand implements Callable { + + @Mixin + AzGlobalOptions 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 Azure.") + + "\nTrack progress: https://github.com/floci-io/floci-az/issues"); + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotSaveCommand.java b/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotSaveCommand.java new file mode 100644 index 0000000..9375590 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/az/snapshot/AzSnapshotSaveCommand.java @@ -0,0 +1,32 @@ +package io.floci.cli.commands.az.snapshot; + +import io.floci.cli.AzGlobalOptions; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.util.concurrent.Callable; + +@Command( + name = "save", + description = "Save the current Floci Azure state as a named snapshot", + mixinStandardHelpOptions = true +) +public class AzSnapshotSaveCommand implements Callable { + + @Mixin + AzGlobalOptions 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 Azure.") + + "\nTrack progress: https://github.com/floci-io/floci-az/issues"); + return 0; + } +} diff --git a/src/main/java/io/floci/cli/commands/config/ConfigCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigCommand.java index 21a3d94..7cd1237 100644 --- a/src/main/java/io/floci/cli/commands/config/ConfigCommand.java +++ b/src/main/java/io/floci/cli/commands/config/ConfigCommand.java @@ -11,6 +11,7 @@ import picocli.CommandLine.*; ConfigShowCommand.class, ConfigValidateCommand.class, ConfigProfileCommand.class, + ConfigDefaultProductCommand.class, HelpCommand.class } ) diff --git a/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java b/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java new file mode 100644 index 0000000..c8c9874 --- /dev/null +++ b/src/main/java/io/floci/cli/commands/config/ConfigDefaultProductCommand.java @@ -0,0 +1,44 @@ +package io.floci.cli.commands.config; + +import io.floci.cli.GlobalOptions; +import io.floci.cli.config.GlobalConfigStore; +import io.floci.cli.output.Ansi; +import io.floci.cli.output.Printer; +import picocli.CommandLine.*; + +import java.io.IOException; +import java.util.concurrent.Callable; + +@Command( + name = "default-product", + description = "Set the default product for bare commands like 'floci start'", + mixinStandardHelpOptions = true +) +public class ConfigDefaultProductCommand implements Callable { + + @Mixin + GlobalOptions global; + + @Parameters(index = "0", description = "Product to use by default: aws, az", paramLabel = "aws|az") + String product; + + @Override + public Integer call() { + Printer printer = global.printer(); + if (!"aws".equals(product) && !"az".equals(product)) { + printer.error("Unknown product '" + product + "'. Use: aws, az"); + return 1; + } + GlobalConfigStore store = new GlobalConfigStore(); + try { + store.setDefaultProduct(product); + printer.println(Ansi.green("Default product set to: ") + Ansi.bold(product)); + printer.println(Ansi.gray("'floci start' will now run: floci " + product + " start")); + printer.println(Ansi.gray("Config saved to: " + store.configFilePath())); + return 0; + } catch (IOException e) { + printer.error("Could not save config: " + e.getMessage()); + return 1; + } + } +} diff --git a/src/main/java/io/floci/cli/config/GlobalConfigStore.java b/src/main/java/io/floci/cli/config/GlobalConfigStore.java new file mode 100644 index 0000000..312035a --- /dev/null +++ b/src/main/java/io/floci/cli/config/GlobalConfigStore.java @@ -0,0 +1,50 @@ +package io.floci.cli.config; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +public class GlobalConfigStore { + + private static final ObjectMapper YAML = new ObjectMapper(new YAMLFactory()); + + private final Path configFile; + + public GlobalConfigStore() { + this(Path.of(System.getProperty("user.home"), ".floci", "config.yaml")); + } + + public GlobalConfigStore(Path configFile) { + this.configFile = configFile; + } + + public String getDefaultProduct() { + if (!Files.exists(configFile)) return "aws"; + try { + GlobalConfig config = YAML.readValue(configFile.toFile(), GlobalConfig.class); + return "az".equals(config.defaultProduct) ? "az" : "aws"; + } catch (IOException e) { + return "aws"; + } + } + + public void setDefaultProduct(String product) throws IOException { + Files.createDirectories(configFile.getParent()); + GlobalConfig config = new GlobalConfig(); + config.defaultProduct = product; + YAML.writeValue(configFile.toFile(), config); + } + + public Path configFilePath() { + return configFile; + } + + public static class GlobalConfig { + @JsonProperty("default-product") + public String defaultProduct = "aws"; + } +} diff --git a/src/main/java/io/floci/cli/doctor/checks/AzCliConnectionStringCheck.java b/src/main/java/io/floci/cli/doctor/checks/AzCliConnectionStringCheck.java new file mode 100644 index 0000000..33ce515 --- /dev/null +++ b/src/main/java/io/floci/cli/doctor/checks/AzCliConnectionStringCheck.java @@ -0,0 +1,59 @@ +package io.floci.cli.doctor.checks; + +import io.floci.cli.doctor.Check; +import io.floci.cli.doctor.CheckResult; + +import java.net.URI; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class AzCliConnectionStringCheck implements Check { + + private static final Pattern ENDPOINT_PORT_PATTERN = + Pattern.compile("BlobEndpoint=https?://[^:]+:(\\d+)/", Pattern.CASE_INSENSITIVE); + + @Override + public CheckResult run(String endpoint, String container) { + String connStr = System.getenv("AZURE_STORAGE_CONNECTION_STRING"); + int effectivePort = extractPort(endpoint); + + if (connStr != null && !connStr.isBlank()) { + Matcher m = ENDPOINT_PORT_PATTERN.matcher(connStr); + if (m.find()) { + int connPort = Integer.parseInt(m.group(1)); + if (effectivePort != -1 && connPort != effectivePort) { + String corrected = connStr.replaceAll(":(\\d+)/", ":" + effectivePort + "/"); + return CheckResult.warn("az.cli.connection-string", + "AZURE_STORAGE_CONNECTION_STRING port mismatch — floci-az is on port " + effectivePort, + "export AZURE_STORAGE_CONNECTION_STRING=\"" + corrected + "\""); + } + } + return CheckResult.ok("az.cli.connection-string", "AZURE_STORAGE_CONNECTION_STRING is set"); + } + + int port = effectivePort != -1 ? effectivePort : 4577; + String suggested = buildConnectionString("devstoreaccount1", "localhost.floci.io", port); + return CheckResult.warn("az.cli.connection-string", + "AZURE_STORAGE_CONNECTION_STRING is not set", + "export AZURE_STORAGE_CONNECTION_STRING=\"" + suggested + "\""); + } + + private int extractPort(String url) { + try { + int port = URI.create(url).getPort(); + return port == -1 ? 4577 : port; + } catch (Exception e) { + return -1; + } + } + + public static String buildConnectionString(String account, String host, int port) { + String base = "http://" + host + ":" + port + "/" + account; + return "DefaultEndpointsProtocol=http" + + ";AccountName=" + account + + ";AccountKey=Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMh0==" + + ";BlobEndpoint=" + base + + ";QueueEndpoint=" + base + "-queue" + + ";TableEndpoint=" + base + "-table;"; + } +} diff --git a/src/main/java/io/floci/cli/doctor/checks/AzCliInstalledCheck.java b/src/main/java/io/floci/cli/doctor/checks/AzCliInstalledCheck.java new file mode 100644 index 0000000..8f417ff --- /dev/null +++ b/src/main/java/io/floci/cli/doctor/checks/AzCliInstalledCheck.java @@ -0,0 +1,22 @@ +package io.floci.cli.doctor.checks; + +import io.floci.cli.doctor.Check; +import io.floci.cli.doctor.CheckResult; + +public class AzCliInstalledCheck implements Check { + + @Override + public CheckResult run(String endpoint, String container) { + try { + Process p = new ProcessBuilder("az", "--version").start(); + if (p.waitFor() == 0) { + return CheckResult.ok("az.cli.installed", "az CLI found"); + } + return CheckResult.warn("az.cli.installed", "az CLI not found in PATH", + "Install from https://learn.microsoft.com/en-us/cli/azure/install-azure-cli"); + } catch (Exception e) { + return CheckResult.warn("az.cli.installed", "az CLI not found in PATH", + "Install from https://learn.microsoft.com/en-us/cli/azure/install-azure-cli"); + } + } +} diff --git a/src/main/java/io/floci/cli/doctor/checks/ImagePresentCheck.java b/src/main/java/io/floci/cli/doctor/checks/ImagePresentCheck.java index 0b24382..868f6ad 100644 --- a/src/main/java/io/floci/cli/doctor/checks/ImagePresentCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/ImagePresentCheck.java @@ -7,17 +7,25 @@ import io.floci.cli.doctor.CheckResult; public class ImagePresentCheck implements Check { - private static final String IMAGE = "floci/floci"; + private final String image; + + public ImagePresentCheck() { + this("floci/floci"); + } + + public ImagePresentCheck(String image) { + this.image = image; + } @Override public CheckResult run(String endpoint, String container) { try { DockerClient docker = new DockerClient(); - if (docker.isImagePresent(IMAGE)) { - return CheckResult.ok("image.present", IMAGE + " image present locally"); + if (docker.isImagePresent(image)) { + return CheckResult.ok("image.present", image + " image present locally"); } return CheckResult.fail("image.present", - IMAGE + " not pulled locally", + image + " not pulled locally", "floci start --pull always"); } catch (DockerException e) { return CheckResult.warn("image.present", "Could not check image presence: " + e.getMessage(), null); diff --git a/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java b/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java index a21553a..a4bbdb1 100644 --- a/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java +++ b/src/main/java/io/floci/cli/doctor/checks/ImageVersionCheck.java @@ -7,19 +7,27 @@ import io.floci.cli.doctor.CheckResult; public class ImageVersionCheck implements Check { - private static final String IMAGE = "floci/floci"; + private final String image; private static final String MIN_VERSION = "1.5.0"; + public ImageVersionCheck() { + this("floci/floci"); + } + + public ImageVersionCheck(String image) { + this.image = image; + } + @Override public CheckResult run(String endpoint, String container) { try { DockerClient docker = new DockerClient(); - if (!docker.isImagePresent(IMAGE)) { - return CheckResult.warn("image.version", IMAGE + " not present — version cannot be checked", + if (!docker.isImagePresent(image)) { + return CheckResult.warn("image.version", image + " not present — version cannot be checked", "floci start --pull always"); } // Try reading version label from the image - String version = readImageLabel(docker, IMAGE); + String version = readImageLabel(docker, image); if (version == null) { return CheckResult.ok("image.version", "Image version unknown (no label); assuming compatible"); } @@ -28,7 +36,7 @@ public class ImageVersionCheck implements Check { } return CheckResult.warn("image.version", "Server image version " + version + " is below minimum " + MIN_VERSION, - "docker pull " + IMAGE + ":latest"); + "docker pull " + image + ":latest"); } catch (DockerException e) { return CheckResult.warn("image.version", "Could not check image version: " + e.getMessage(), null); } diff --git a/src/main/resources/META-INF/native-image/io.floci/floci-cli/reflect-config.json b/src/main/resources/META-INF/native-image/io.floci/floci-cli/reflect-config.json index fd6c4f1..0eb2d5a 100644 --- a/src/main/resources/META-INF/native-image/io.floci/floci-cli/reflect-config.json +++ b/src/main/resources/META-INF/native-image/io.floci/floci-cli/reflect-config.json @@ -5,6 +5,12 @@ "allDeclaredMethods": true, "allDeclaredConstructors": true }, + { + "name": "io.floci.cli.config.GlobalConfigStore$GlobalConfig", + "allDeclaredFields": true, + "allDeclaredMethods": true, + "allDeclaredConstructors": true + }, { "name": "com.fasterxml.jackson.databind.ser.std.ToStringSerializer", "allDeclaredMethods": true