mirror of
https://github.com/basnijholt/compose-farm.git
synced 2026-02-08 16:29:55 +00:00
Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d65f4cf7f4 | ||
|
|
7ce2067fcb | ||
|
|
f32057aa7b | ||
|
|
c3e3aeb538 | ||
|
|
009f3b1403 | ||
|
|
51f74eab42 | ||
|
|
4acf797128 | ||
|
|
d167da9d63 | ||
|
|
a5eac339db | ||
|
|
9f3813eb72 | ||
|
|
b9ae0ad4d5 |
21
.github/workflows/docker.yml
vendored
21
.github/workflows/docker.yml
vendored
@@ -68,16 +68,35 @@ jobs:
|
||||
echo "✗ Timeout waiting for PyPI"
|
||||
exit 1
|
||||
|
||||
- name: Check if latest release
|
||||
id: latest
|
||||
run: |
|
||||
VERSION="${{ steps.version.outputs.version }}"
|
||||
# Get latest release tag from GitHub (strip 'v' prefix)
|
||||
LATEST=$(gh release view --json tagName -q '.tagName' | sed 's/^v//')
|
||||
echo "Building version: $VERSION"
|
||||
echo "Latest release: $LATEST"
|
||||
if [ "$VERSION" = "$LATEST" ]; then
|
||||
echo "is_latest=true" >> $GITHUB_OUTPUT
|
||||
echo "✓ This is the latest release, will tag as :latest"
|
||||
else
|
||||
echo "is_latest=false" >> $GITHUB_OUTPUT
|
||||
echo "⚠ This is NOT the latest release, skipping :latest tag"
|
||||
fi
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
# Only tag as 'latest' if this is the latest release (prevents re-runs of old releases from overwriting)
|
||||
tags: |
|
||||
type=semver,pattern={{version}},value=v${{ steps.version.outputs.version }}
|
||||
type=semver,pattern={{major}}.{{minor}},value=v${{ steps.version.outputs.version }}
|
||||
type=semver,pattern={{major}},value=v${{ steps.version.outputs.version }}
|
||||
type=raw,value=latest
|
||||
type=raw,value=latest,enable=${{ steps.latest.outputs.is_latest }}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
|
||||
@@ -59,18 +59,20 @@ Check:
|
||||
- Config file search order is accurate
|
||||
- Example YAML would actually work
|
||||
|
||||
### 4. Verify docs/architecture.md
|
||||
### 4. Verify docs/architecture.md and CLAUDE.md
|
||||
|
||||
```bash
|
||||
# What source files actually exist?
|
||||
git ls-files "src/**/*.py"
|
||||
```
|
||||
|
||||
Check:
|
||||
Check **both** `docs/architecture.md` and `CLAUDE.md` (Architecture section):
|
||||
- Listed files exist
|
||||
- No files are missing from the list
|
||||
- Descriptions match what the code does
|
||||
|
||||
Both files have architecture listings that can drift independently.
|
||||
|
||||
### 5. Check Examples
|
||||
|
||||
For examples in any doc:
|
||||
|
||||
22
CLAUDE.md
22
CLAUDE.md
@@ -17,18 +17,20 @@ src/compose_farm/
|
||||
│ ├── config.py # Config subcommand (init, show, path, validate, edit, symlink)
|
||||
│ ├── lifecycle.py # up, down, stop, pull, restart, update, apply, compose commands
|
||||
│ ├── management.py # refresh, check, init-network, traefik-file commands
|
||||
│ ├── monitoring.py # logs, ps, stats commands
|
||||
│ ├── monitoring.py # logs, ps, stats, list commands
|
||||
│ ├── ssh.py # SSH key management (setup, status, keygen)
|
||||
│ └── web.py # Web UI server command
|
||||
├── config.py # Pydantic models, YAML loading
|
||||
├── compose.py # Compose file parsing (.env, ports, volumes, networks)
|
||||
├── config.py # Pydantic models, YAML loading
|
||||
├── console.py # Shared Rich console instances
|
||||
├── executor.py # SSH/local command execution, streaming output
|
||||
├── operations.py # Business logic (up, migrate, discover, preflight checks)
|
||||
├── state.py # Deployment state tracking (which stack on which host)
|
||||
├── glances.py # Glances API integration for host resource stats
|
||||
├── logs.py # Image digest snapshots (dockerfarm-log.toml)
|
||||
├── operations.py # Business logic (up, migrate, discover, preflight checks)
|
||||
├── paths.py # Path utilities, config file discovery
|
||||
├── registry.py # Container registry client for update checking
|
||||
├── ssh_keys.py # SSH key path constants and utilities
|
||||
├── state.py # Deployment state tracking (which stack on which host)
|
||||
├── traefik.py # Traefik file-provider config generation from labels
|
||||
└── web/ # Web UI (FastAPI + HTMX)
|
||||
```
|
||||
@@ -100,6 +102,17 @@ Browser tests are marked with `@pytest.mark.browser`. They use Playwright to tes
|
||||
- **NEVER merge anything into main.** Always commit directly or use fast-forward/rebase.
|
||||
- Never force push.
|
||||
|
||||
## SSH Agent in Remote Sessions
|
||||
|
||||
When pushing to GitHub via SSH fails with "Permission denied (publickey)", fix the SSH agent socket:
|
||||
|
||||
```bash
|
||||
# Find and set the correct SSH agent socket
|
||||
SSH_AUTH_SOCK=$(ls -t ~/.ssh/agent/s.*.sshd.* 2>/dev/null | head -1) git push origin branch-name
|
||||
```
|
||||
|
||||
This is needed because the SSH agent socket path changes between sessions.
|
||||
|
||||
## Pull Requests
|
||||
|
||||
- Never include unchecked checklists (e.g., `- [ ] ...`) in PR descriptions. Either omit the checklist or use checked items.
|
||||
@@ -144,6 +157,7 @@ CLI available as `cf` or `compose-farm`.
|
||||
| `logs` | Show stack logs |
|
||||
| `ps` | Show status of all stacks |
|
||||
| `stats` | Show overview (hosts, stacks, pending migrations; `--live` for container counts) |
|
||||
| `list` | List stacks and hosts (`--simple` for scripting, `--host` to filter) |
|
||||
| `refresh` | Update state from reality: discover running stacks, capture image digests |
|
||||
| `check` | Validate config, traefik labels, mounts, networks; show host compatibility |
|
||||
| `init-network` | Create Docker network on hosts with consistent subnet/gateway |
|
||||
|
||||
45
README.md
45
README.md
@@ -395,6 +395,7 @@ Multi-host orchestration that Docker Compose can't do:
|
||||
| `cf traefik-file` | Generate Traefik file-provider config |
|
||||
| `cf config` | Manage config files (init, show, validate, edit, symlink) |
|
||||
| `cf ssh` | Manage SSH keys (setup, status, keygen) |
|
||||
| `cf list` | List all stacks and their assigned hosts |
|
||||
|
||||
### Aliases
|
||||
|
||||
@@ -403,10 +404,11 @@ Short aliases for frequently used commands:
|
||||
| Alias | Command | Alias | Command |
|
||||
|-------|---------|-------|---------|
|
||||
| `cf a` | `apply` | `cf s` | `stats` |
|
||||
| `cf l` | `logs` | `cf c` | `compose` |
|
||||
| `cf l` | `logs` | `cf ls` | `list` |
|
||||
| `cf r` | `restart` | `cf rf` | `refresh` |
|
||||
| `cf u` | `update` | `cf ck` | `check` |
|
||||
| `cf p` | `pull` | `cf tf` | `traefik-file` |
|
||||
| `cf c` | `compose` | | |
|
||||
|
||||
Each command replaces: look up host → SSH → find compose file → run `ssh host "cd /opt/compose/plex && docker compose up -d"`.
|
||||
|
||||
@@ -511,6 +513,7 @@ Full `--help` output for each command. See the [Usage](#usage) table above for a
|
||||
│ service. │
|
||||
│ ps Show status of stacks. │
|
||||
│ stats Show overview statistics for hosts and stacks. │
|
||||
│ list List all stacks and their assigned hosts. │
|
||||
╰──────────────────────────────────────────────────────────────────────────────╯
|
||||
╭─ Server ─────────────────────────────────────────────────────────────────────╮
|
||||
│ web Start the web UI server. │
|
||||
@@ -1176,11 +1179,47 @@ Full `--help` output for each command. See the [Usage](#usage) table above for a
|
||||
|
||||
Show overview statistics for hosts and stacks.
|
||||
|
||||
Without --live: Shows config/state info (hosts, stacks, pending migrations).
|
||||
Without flags: Shows config/state info (hosts, stacks, pending migrations).
|
||||
With --live: Also queries Docker on each host for container counts.
|
||||
With --containers: Shows per-container resource stats (requires Glances).
|
||||
|
||||
╭─ Options ────────────────────────────────────────────────────────────────────╮
|
||||
│ --live -l Query Docker for live container stats │
|
||||
│ --live -l Query Docker for live container stats │
|
||||
│ --containers -C Show per-container resource stats (requires │
|
||||
│ Glances) │
|
||||
│ --host -H TEXT Filter to stacks on this host │
|
||||
│ --config -c PATH Path to config file │
|
||||
│ --help -h Show this message and exit. │
|
||||
╰──────────────────────────────────────────────────────────────────────────────╯
|
||||
|
||||
```
|
||||
|
||||
<!-- OUTPUT:END -->
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>See the output of <code>cf list --help</code></summary>
|
||||
|
||||
<!-- CODE:BASH:START -->
|
||||
<!-- echo '```yaml' -->
|
||||
<!-- export NO_COLOR=1 -->
|
||||
<!-- export TERM=dumb -->
|
||||
<!-- export TERMINAL_WIDTH=90 -->
|
||||
<!-- cf list --help -->
|
||||
<!-- echo '```' -->
|
||||
<!-- CODE:END -->
|
||||
<!-- OUTPUT:START -->
|
||||
<!-- ⚠️ This content is auto-generated by `markdown-code-runner`. -->
|
||||
```yaml
|
||||
|
||||
Usage: cf list [OPTIONS]
|
||||
|
||||
List all stacks and their assigned hosts.
|
||||
|
||||
╭─ Options ────────────────────────────────────────────────────────────────────╮
|
||||
│ --host -H TEXT Filter to stacks on this host │
|
||||
│ --simple -s Plain output (one stack per line, for scripting) │
|
||||
│ --config -c PATH Path to config file │
|
||||
│ --help -h Show this message and exit. │
|
||||
╰──────────────────────────────────────────────────────────────────────────────╯
|
||||
|
||||
@@ -96,7 +96,7 @@ Typer-based CLI with subcommand modules:
|
||||
cli/
|
||||
├── app.py # Shared Typer app, version callback
|
||||
├── common.py # Shared helpers, options, progress utilities
|
||||
├── config.py # config subcommand (init, show, path, validate, edit, symlink)
|
||||
├── config.py # config subcommand (init, init-env, show, path, validate, edit, symlink)
|
||||
├── lifecycle.py # up, down, stop, pull, restart, update, apply, compose
|
||||
├── management.py # refresh, check, init-network, traefik-file
|
||||
├── monitoring.py # logs, ps, stats
|
||||
@@ -343,3 +343,19 @@ For repeated connections to the same host, SSH reuses connections.
|
||||
```
|
||||
|
||||
Icons use [Lucide](https://lucide.dev/). Add new icons as macros in `web/templates/partials/icons.html`.
|
||||
|
||||
### Host Resource Monitoring (`src/compose_farm/glances.py`)
|
||||
|
||||
Integration with [Glances](https://nicolargo.github.io/glances/) for real-time host stats:
|
||||
|
||||
- Fetches CPU, memory, and load from Glances REST API on each host
|
||||
- Used by web UI dashboard to display host resource usage
|
||||
- Requires `glances_stack` config option pointing to a Glances stack running on all hosts
|
||||
|
||||
### Container Registry Client (`src/compose_farm/registry.py`)
|
||||
|
||||
OCI Distribution API client for checking image updates:
|
||||
|
||||
- Parses image references (registry, namespace, name, tag, digest)
|
||||
- Fetches available tags from Docker Hub, GHCR, and other registries
|
||||
- Compares semantic versions to find newer releases
|
||||
|
||||
@@ -23,6 +23,7 @@ Commands are either **Docker Compose wrappers** (`up`, `down`, `stop`, `restart`
|
||||
| **Monitoring** | `ps` | Show stack status |
|
||||
| | `logs` | Show stack logs |
|
||||
| | `stats` | Show overview statistics |
|
||||
| | `list` | List stacks and hosts |
|
||||
| **Configuration** | `check` | Validate config and mounts |
|
||||
| | `refresh` | Sync state from reality |
|
||||
| | `init-network` | Create Docker network |
|
||||
@@ -38,6 +39,19 @@ cf --version, -v # Show version
|
||||
cf --help, -h # Show help
|
||||
```
|
||||
|
||||
## Command Aliases
|
||||
|
||||
Short aliases for frequently used commands:
|
||||
|
||||
| Alias | Command | Alias | Command |
|
||||
|-------|---------|-------|---------|
|
||||
| `cf a` | `apply` | `cf s` | `stats` |
|
||||
| `cf l` | `logs` | `cf ls` | `list` |
|
||||
| `cf r` | `restart` | `cf rf` | `refresh` |
|
||||
| `cf u` | `update` | `cf ck` | `check` |
|
||||
| `cf p` | `pull` | `cf tf` | `traefik-file` |
|
||||
| `cf c` | `compose` | | |
|
||||
|
||||
---
|
||||
|
||||
## Lifecycle Commands
|
||||
@@ -60,14 +74,16 @@ cf apply [OPTIONS]
|
||||
|--------|-------------|
|
||||
| `--dry-run, -n` | Preview changes without executing |
|
||||
| `--no-orphans` | Skip stopping orphaned stacks |
|
||||
| `--full, -f` | Also refresh running stacks |
|
||||
| `--no-strays` | Skip stopping stray stacks (running on wrong host) |
|
||||
| `--full, -f` | Also run up on all stacks (applies compose/env changes, triggers migrations) |
|
||||
| `--config, -c PATH` | Path to config file |
|
||||
|
||||
**What it does:**
|
||||
|
||||
1. Stops orphaned stacks (in state but removed from config)
|
||||
2. Migrates stacks on wrong host
|
||||
3. Starts missing stacks (in config but not running)
|
||||
2. Stops stray stacks (running on unauthorized hosts)
|
||||
3. Migrates stacks on wrong host
|
||||
4. Starts missing stacks (in config but not running)
|
||||
|
||||
**Examples:**
|
||||
|
||||
@@ -81,7 +97,10 @@ cf apply
|
||||
# Only start/migrate, don't stop orphans
|
||||
cf apply --no-orphans
|
||||
|
||||
# Also refresh all running stacks
|
||||
# Don't stop stray stacks
|
||||
cf apply --no-strays
|
||||
|
||||
# Also run up on all stacks (applies compose/env changes, triggers migrations)
|
||||
cf apply --full
|
||||
```
|
||||
|
||||
@@ -102,6 +121,8 @@ cf up [OPTIONS] [STACKS]...
|
||||
| `--all, -a` | Start all stacks |
|
||||
| `--host, -H TEXT` | Filter to stacks on this host |
|
||||
| `--service, -s TEXT` | Target a specific service within the stack |
|
||||
| `--pull` | Pull images before starting (`--pull always`) |
|
||||
| `--build` | Build images before starting |
|
||||
| `--config, -c PATH` | Path to config file |
|
||||
|
||||
**Examples:**
|
||||
@@ -447,6 +468,40 @@ cf stats --live
|
||||
|
||||
---
|
||||
|
||||
### cf list
|
||||
|
||||
List all stacks and their assigned hosts.
|
||||
|
||||
```bash
|
||||
cf list [OPTIONS]
|
||||
```
|
||||
|
||||
**Options:**
|
||||
|
||||
| Option | Description |
|
||||
|--------|-------------|
|
||||
| `--host, -H TEXT` | Filter to stacks on this host |
|
||||
| `--simple, -s` | Plain output for scripting (one stack per line) |
|
||||
| `--config, -c PATH` | Path to config file |
|
||||
|
||||
**Examples:**
|
||||
|
||||
```bash
|
||||
# List all stacks
|
||||
cf list
|
||||
|
||||
# Filter by host
|
||||
cf list --host nas
|
||||
|
||||
# Plain output for scripting
|
||||
cf list --simple
|
||||
|
||||
# Combine: list stack names on a specific host
|
||||
cf list --host nuc --simple
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration Commands
|
||||
|
||||
### cf check
|
||||
@@ -589,6 +644,7 @@ cf config COMMAND
|
||||
| Command | Description |
|
||||
|---------|-------------|
|
||||
| `init` | Create new config with examples |
|
||||
| `init-env` | Generate .env file for Docker deployment |
|
||||
| `show` | Display config with highlighting |
|
||||
| `path` | Print config file path |
|
||||
| `validate` | Validate syntax and schema |
|
||||
@@ -600,6 +656,7 @@ cf config COMMAND
|
||||
| Subcommand | Options |
|
||||
|------------|---------|
|
||||
| `init` | `--path/-p PATH`, `--force/-f` |
|
||||
| `init-env` | `--path/-p PATH`, `--output/-o PATH`, `--force/-f` |
|
||||
| `show` | `--path/-p PATH`, `--raw/-r` |
|
||||
| `edit` | `--path/-p PATH` |
|
||||
| `path` | `--path/-p PATH` |
|
||||
@@ -635,6 +692,12 @@ cf config symlink
|
||||
|
||||
# Create symlink to specific file
|
||||
cf config symlink /opt/compose-farm/config.yaml
|
||||
|
||||
# Generate .env file in current directory
|
||||
cf config init-env
|
||||
|
||||
# Generate .env at specific path
|
||||
cf config init-env -o /opt/stacks/.env
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -121,6 +121,16 @@ Stack name running Traefik. Stacks on the same host are skipped in file-provider
|
||||
traefik_stack: traefik
|
||||
```
|
||||
|
||||
### glances_stack
|
||||
|
||||
Stack name running [Glances](https://nicolargo.github.io/glances/) for host resource monitoring. When set, the web UI displays CPU, memory, and load stats for all hosts.
|
||||
|
||||
```yaml
|
||||
glances_stack: glances
|
||||
```
|
||||
|
||||
The Glances stack should run on all hosts and expose port 61208. See the README for full setup instructions.
|
||||
|
||||
## Hosts Configuration
|
||||
|
||||
### Basic Host
|
||||
|
||||
@@ -17,7 +17,7 @@ curl -O https://raw.githubusercontent.com/basnijholt/compose-farm/main/docker-co
|
||||
**2. Generate `.env` file:**
|
||||
|
||||
```bash
|
||||
cf config init-env -o .env
|
||||
cf config init-env
|
||||
```
|
||||
|
||||
This auto-detects settings from your `compose-farm.yaml`:
|
||||
|
||||
@@ -7,9 +7,10 @@ Real-world examples demonstrating compose-farm patterns for multi-host Docker de
|
||||
| Stack | Type | Demonstrates |
|
||||
|---------|------|--------------|
|
||||
| [traefik](traefik/) | Infrastructure | Reverse proxy, Let's Encrypt, file-provider |
|
||||
| [coredns](coredns/) | Infrastructure | Wildcard DNS for `*.local` domains |
|
||||
| [mealie](mealie/) | Single container | Traefik labels, resource limits, environment vars |
|
||||
| [uptime-kuma](uptime-kuma/) | Single container | Docker socket, user mapping, custom DNS |
|
||||
| [paperless-ngx](paperless-ngx/) | Multi-container | Redis + App stack (SQLite) |
|
||||
| [paperless-ngx](paperless-ngx/) | Multi-container | Redis + PostgreSQL + App stack |
|
||||
| [autokuma](autokuma/) | Multi-host | Demonstrates `all` keyword (runs on every host) |
|
||||
|
||||
## Key Patterns
|
||||
@@ -53,7 +54,8 @@ labels:
|
||||
- traefik.http.routers.myapp-local.entrypoints=web
|
||||
```
|
||||
|
||||
> **Note:** `.local` domains require local DNS (e.g., Pi-hole, Technitium) to resolve to your Traefik host.
|
||||
> **Note:** `.local` domains require local DNS to resolve to your Traefik host.
|
||||
> The [coredns](coredns/) example provides this - edit `Corefile` to set your Traefik IP.
|
||||
|
||||
### Environment Variables
|
||||
|
||||
@@ -88,23 +90,6 @@ stacks:
|
||||
autokuma: all # Runs on every configured host
|
||||
```
|
||||
|
||||
### Multi-Container Stacks
|
||||
|
||||
Database-backed apps with multiple services:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
redis:
|
||||
image: redis:7
|
||||
app:
|
||||
depends_on:
|
||||
- redis
|
||||
```
|
||||
|
||||
> **NFS + PostgreSQL Warning:** PostgreSQL should NOT run on NFS storage due to
|
||||
> fsync and file locking issues. Use SQLite (safe for single-writer on NFS) or
|
||||
> keep PostgreSQL data on local volumes (non-migratable).
|
||||
|
||||
### AutoKuma Labels (Optional)
|
||||
|
||||
The autokuma example demonstrates compose-farm's **multi-host feature** - running the same stack on all hosts using the `all` keyword. AutoKuma itself is not part of compose-farm; it's just a good example because it needs to run on every host to monitor local Docker containers.
|
||||
@@ -125,8 +110,8 @@ cd examples
|
||||
# 1. Create the shared network on all hosts
|
||||
compose-farm init-network
|
||||
|
||||
# 2. Start Traefik first (the reverse proxy)
|
||||
compose-farm up traefik
|
||||
# 2. Start infrastructure (reverse proxy + DNS)
|
||||
compose-farm up traefik coredns
|
||||
|
||||
# 3. Start other stacks
|
||||
compose-farm up mealie uptime-kuma
|
||||
|
||||
@@ -3,6 +3,7 @@ deployed:
|
||||
- primary
|
||||
- secondary
|
||||
- local
|
||||
coredns: primary
|
||||
mealie: secondary
|
||||
paperless-ngx: primary
|
||||
traefik: primary
|
||||
|
||||
@@ -27,6 +27,7 @@ hosts:
|
||||
stacks:
|
||||
# Infrastructure (runs on primary where Traefik is)
|
||||
traefik: primary
|
||||
coredns: primary # DNS for *.local resolution
|
||||
|
||||
# Multi-host stacks (runs on ALL hosts)
|
||||
# AutoKuma monitors Docker containers on each host
|
||||
|
||||
2
examples/coredns/.env
Normal file
2
examples/coredns/.env
Normal file
@@ -0,0 +1,2 @@
|
||||
# CoreDNS doesn't need environment variables
|
||||
# The Traefik IP is configured in the Corefile
|
||||
22
examples/coredns/Corefile
Normal file
22
examples/coredns/Corefile
Normal file
@@ -0,0 +1,22 @@
|
||||
# CoreDNS configuration for .local domain resolution
|
||||
#
|
||||
# Resolves *.local to the Traefik host IP (where your reverse proxy runs).
|
||||
# All other queries are forwarded to upstream DNS.
|
||||
|
||||
# Handle .local domains - resolve everything to Traefik's host
|
||||
local {
|
||||
template IN A {
|
||||
answer "{{ .Name }} 60 IN A 192.168.1.10"
|
||||
}
|
||||
template IN AAAA {
|
||||
# Return empty for AAAA to avoid delays on IPv4-only networks
|
||||
rcode NOERROR
|
||||
}
|
||||
}
|
||||
|
||||
# Forward everything else to upstream DNS
|
||||
. {
|
||||
forward . 1.1.1.1 8.8.8.8
|
||||
cache 300
|
||||
errors
|
||||
}
|
||||
27
examples/coredns/compose.yaml
Normal file
27
examples/coredns/compose.yaml
Normal file
@@ -0,0 +1,27 @@
|
||||
# CoreDNS - DNS server for .local domain resolution
|
||||
#
|
||||
# Demonstrates:
|
||||
# - Wildcard DNS for *.local domains
|
||||
# - Config file mounting from stack directory
|
||||
# - UDP/TCP port exposure
|
||||
#
|
||||
# This enables all the .local routes in the examples to work.
|
||||
# Point your devices/router DNS to this server's IP.
|
||||
name: coredns
|
||||
services:
|
||||
coredns:
|
||||
image: coredns/coredns:latest
|
||||
container_name: coredns
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- mynetwork
|
||||
ports:
|
||||
- "53:53/udp"
|
||||
- "53:53/tcp"
|
||||
volumes:
|
||||
- ./Corefile:/root/Corefile:ro
|
||||
command: -conf /root/Corefile
|
||||
|
||||
networks:
|
||||
mynetwork:
|
||||
external: true
|
||||
@@ -1,3 +1,4 @@
|
||||
# Copy to .env and fill in your values
|
||||
DOMAIN=example.com
|
||||
PAPERLESS_SECRET_KEY=change-me-to-a-random-string
|
||||
POSTGRES_PASSWORD=change-me-to-a-secure-password
|
||||
PAPERLESS_SECRET_KEY=change-me-to-a-long-random-string
|
||||
|
||||
@@ -1,44 +1,57 @@
|
||||
# Paperless-ngx - Document management system
|
||||
#
|
||||
# Demonstrates:
|
||||
# - HTTPS route: paperless.${DOMAIN} (e.g., paperless.example.com) with Let's Encrypt
|
||||
# - HTTP route: paperless.local for LAN access without TLS
|
||||
# - Multi-container stack (Redis + App with SQLite)
|
||||
#
|
||||
# NOTE: This example uses SQLite (the default) instead of PostgreSQL.
|
||||
# PostgreSQL should NOT be used with NFS storage due to fsync/locking issues.
|
||||
# If you need PostgreSQL, use local volumes for the database.
|
||||
# - HTTPS route: paperless.${DOMAIN} with Let's Encrypt
|
||||
# - HTTP route: paperless.local for LAN access
|
||||
# - Multi-container stack (Redis + PostgreSQL + App)
|
||||
# - Separate env_file for app-specific settings
|
||||
name: paperless-ngx
|
||||
services:
|
||||
redis:
|
||||
image: redis:8
|
||||
broker:
|
||||
image: redis:7
|
||||
container_name: paperless-redis
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- mynetwork
|
||||
volumes:
|
||||
- /mnt/data/paperless/redis:/data
|
||||
- /mnt/data/paperless/redisdata:/data
|
||||
|
||||
db:
|
||||
image: postgres:16
|
||||
container_name: paperless-db
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- mynetwork
|
||||
volumes:
|
||||
- /mnt/data/paperless/pgdata:/var/lib/postgresql/data
|
||||
environment:
|
||||
POSTGRES_DB: paperless
|
||||
POSTGRES_USER: paperless
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||
|
||||
paperless:
|
||||
image: ghcr.io/paperless-ngx/paperless-ngx:latest
|
||||
container_name: paperless
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- redis
|
||||
- db
|
||||
- broker
|
||||
networks:
|
||||
- mynetwork
|
||||
ports:
|
||||
- "8000:8000"
|
||||
volumes:
|
||||
# SQLite database stored here (safe on NFS for single-writer)
|
||||
- /mnt/data/paperless/data:/usr/src/paperless/data
|
||||
- /mnt/data/paperless/media:/usr/src/paperless/media
|
||||
- /mnt/data/paperless/export:/usr/src/paperless/export
|
||||
- /mnt/data/paperless/consume:/usr/src/paperless/consume
|
||||
environment:
|
||||
PAPERLESS_REDIS: redis://redis:6379
|
||||
PAPERLESS_REDIS: redis://broker:6379
|
||||
PAPERLESS_DBHOST: db
|
||||
PAPERLESS_URL: https://paperless.${DOMAIN}
|
||||
PAPERLESS_SECRET_KEY: ${PAPERLESS_SECRET_KEY}
|
||||
PAPERLESS_TIME_ZONE: America/Los_Angeles
|
||||
PAPERLESS_OCR_LANGUAGE: eng
|
||||
USERMAP_UID: 1000
|
||||
USERMAP_GID: 1000
|
||||
labels:
|
||||
|
||||
@@ -124,6 +124,10 @@ python_version = "3.11"
|
||||
strict = true
|
||||
plugins = ["pydantic.mypy"]
|
||||
|
||||
[[tool.mypy.overrides]]
|
||||
module = "compose_farm._version"
|
||||
ignore_missing_imports = true
|
||||
|
||||
[[tool.mypy.overrides]]
|
||||
module = "asyncssh.*"
|
||||
ignore_missing_imports = true
|
||||
@@ -174,8 +178,12 @@ python-version = "3.11"
|
||||
exclude = [
|
||||
"hatch_build.py", # Build-time only, hatchling not in dev deps
|
||||
"docs/demos/**", # Demo scripts with local conftest imports
|
||||
"src/compose_farm/_version.py", # Generated at build time
|
||||
]
|
||||
|
||||
[tool.ty.rules]
|
||||
unresolved-import = "ignore" # _version.py is generated at build time
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"mypy>=1.19.0",
|
||||
|
||||
@@ -342,7 +342,7 @@ def config_init_env(
|
||||
output: Annotated[
|
||||
Path | None,
|
||||
typer.Option(
|
||||
"--output", "-o", help="Output .env file path. Defaults to .env in config directory."
|
||||
"--output", "-o", help="Output .env file path. Defaults to .env in current directory."
|
||||
),
|
||||
] = None,
|
||||
force: _ForceOption = False,
|
||||
@@ -357,14 +357,14 @@ def config_init_env(
|
||||
|
||||
Example::
|
||||
|
||||
cf config init-env # Create .env next to config
|
||||
cf config init-env -o .env # Create .env in current directory
|
||||
cf config init-env # Create .env in current directory
|
||||
cf config init-env -o /path/to/.env # Create .env at specific path
|
||||
|
||||
"""
|
||||
config_file, cfg = _load_config_with_path(path)
|
||||
|
||||
# Determine output path
|
||||
env_path = output.expanduser().resolve() if output else config_file.parent / ".env"
|
||||
# Determine output path (default: current directory)
|
||||
env_path = output.expanduser().resolve() if output else Path.cwd() / ".env"
|
||||
|
||||
if env_path.exists() and not force:
|
||||
console.print(f"[yellow].env file already exists:[/] {env_path}")
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shlex
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Annotated
|
||||
|
||||
@@ -393,10 +394,10 @@ def compose(
|
||||
else:
|
||||
target_host = hosts[0]
|
||||
|
||||
# Build the full compose command
|
||||
# Build the full compose command (quote args to preserve spaces)
|
||||
full_cmd = command
|
||||
if args:
|
||||
full_cmd += " " + " ".join(args)
|
||||
full_cmd += " " + " ".join(shlex.quote(arg) for arg in args)
|
||||
|
||||
# Run with raw=True for proper TTY handling (progress bars, interactive)
|
||||
result = run_async(run_compose_on_host(cfg, resolved_stack, target_host, full_cmd, raw=True))
|
||||
|
||||
@@ -21,17 +21,22 @@ from compose_farm.cli.common import (
|
||||
report_results,
|
||||
run_async,
|
||||
run_parallel_with_progress,
|
||||
validate_hosts,
|
||||
)
|
||||
from compose_farm.console import console, print_error
|
||||
from compose_farm.console import console, print_error, print_warning
|
||||
from compose_farm.executor import run_command, run_on_stacks
|
||||
from compose_farm.state import get_stacks_needing_migration, group_stacks_by_host, load_state
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
from compose_farm.config import Config
|
||||
from compose_farm.glances import ContainerStats
|
||||
|
||||
|
||||
def _get_container_counts(cfg: Config) -> dict[str, int]:
|
||||
"""Get container counts from all hosts with a progress bar."""
|
||||
def _get_container_counts(cfg: Config, hosts: list[str] | None = None) -> dict[str, int]:
|
||||
"""Get container counts from hosts with a progress bar."""
|
||||
host_list = hosts if hosts is not None else list(cfg.hosts.keys())
|
||||
|
||||
async def get_count(host_name: str) -> tuple[str, int]:
|
||||
host = cfg.hosts[host_name]
|
||||
@@ -44,7 +49,7 @@ def _get_container_counts(cfg: Config) -> dict[str, int]:
|
||||
|
||||
results = run_parallel_with_progress(
|
||||
"Querying hosts",
|
||||
list(cfg.hosts.keys()),
|
||||
host_list,
|
||||
get_count,
|
||||
)
|
||||
return dict(results)
|
||||
@@ -67,7 +72,7 @@ def _build_host_table(
|
||||
if show_containers:
|
||||
table.add_column("Containers", justify="right")
|
||||
|
||||
for host_name in sorted(cfg.hosts.keys()):
|
||||
for host_name in sorted(stacks_by_host.keys()):
|
||||
host = cfg.hosts[host_name]
|
||||
configured = len(stacks_by_host[host_name])
|
||||
running = len(running_by_host[host_name])
|
||||
@@ -86,19 +91,46 @@ def _build_host_table(
|
||||
return table
|
||||
|
||||
|
||||
def _state_includes_host(host_value: str | list[str], host_name: str) -> bool:
|
||||
"""Check whether a state entry includes the given host."""
|
||||
if isinstance(host_value, list):
|
||||
return host_name in host_value
|
||||
return host_value == host_name
|
||||
|
||||
|
||||
def _build_summary_table(
|
||||
cfg: Config, state: dict[str, str | list[str]], pending: list[str]
|
||||
cfg: Config,
|
||||
state: dict[str, str | list[str]],
|
||||
pending: list[str],
|
||||
*,
|
||||
host_filter: str | None = None,
|
||||
) -> Table:
|
||||
"""Build the summary table."""
|
||||
on_disk = cfg.discover_compose_dirs()
|
||||
if host_filter:
|
||||
stacks_configured = [stack for stack in cfg.stacks if host_filter in cfg.get_hosts(stack)]
|
||||
stacks_configured_set = set(stacks_configured)
|
||||
state = {
|
||||
stack: hosts
|
||||
for stack, hosts in state.items()
|
||||
if _state_includes_host(hosts, host_filter)
|
||||
}
|
||||
on_disk = {stack for stack in on_disk if stack in stacks_configured_set}
|
||||
total_hosts = 1
|
||||
stacks_configured_count = len(stacks_configured)
|
||||
stacks_tracked_count = len(state)
|
||||
else:
|
||||
total_hosts = len(cfg.hosts)
|
||||
stacks_configured_count = len(cfg.stacks)
|
||||
stacks_tracked_count = len(state)
|
||||
|
||||
table = Table(title="Summary", show_header=False)
|
||||
table.add_column("Label", style="dim")
|
||||
table.add_column("Value", style="bold")
|
||||
|
||||
table.add_row("Total hosts", str(len(cfg.hosts)))
|
||||
table.add_row("Stacks (configured)", str(len(cfg.stacks)))
|
||||
table.add_row("Stacks (tracked)", str(len(state)))
|
||||
table.add_row("Total hosts", str(total_hosts))
|
||||
table.add_row("Stacks (configured)", str(stacks_configured_count))
|
||||
table.add_row("Stacks (tracked)", str(stacks_tracked_count))
|
||||
table.add_row("Compose files on disk", str(len(on_disk)))
|
||||
|
||||
if pending:
|
||||
@@ -111,6 +143,81 @@ def _build_summary_table(
|
||||
return table
|
||||
|
||||
|
||||
def _format_network(rx: int, tx: int, fmt: Callable[[int], str]) -> str:
|
||||
"""Format network I/O."""
|
||||
return f"[dim]↓[/]{fmt(rx)} [dim]↑[/]{fmt(tx)}"
|
||||
|
||||
|
||||
def _cpu_style(percent: float) -> str:
|
||||
"""Rich style for CPU percentage."""
|
||||
if percent > 80: # noqa: PLR2004
|
||||
return "red"
|
||||
if percent > 50: # noqa: PLR2004
|
||||
return "yellow"
|
||||
return "green"
|
||||
|
||||
|
||||
def _mem_style(percent: float) -> str:
|
||||
"""Rich style for memory percentage."""
|
||||
if percent > 90: # noqa: PLR2004
|
||||
return "red"
|
||||
if percent > 70: # noqa: PLR2004
|
||||
return "yellow"
|
||||
return "green"
|
||||
|
||||
|
||||
def _status_style(status: str) -> str:
|
||||
"""Rich style for container status."""
|
||||
s = status.lower()
|
||||
if s == "running":
|
||||
return "green"
|
||||
if s == "exited":
|
||||
return "red"
|
||||
if s == "paused":
|
||||
return "yellow"
|
||||
return "dim"
|
||||
|
||||
|
||||
def _build_containers_table(
|
||||
containers: list[ContainerStats],
|
||||
host_filter: str | None = None,
|
||||
) -> Table:
|
||||
"""Build Rich table for container stats."""
|
||||
from compose_farm.glances import format_bytes # noqa: PLC0415
|
||||
|
||||
table = Table(title="Containers", show_header=True, header_style="bold cyan")
|
||||
table.add_column("Stack", style="cyan")
|
||||
table.add_column("Service", style="dim")
|
||||
table.add_column("Host", style="magenta")
|
||||
table.add_column("Image")
|
||||
table.add_column("Status")
|
||||
table.add_column("Uptime", justify="right")
|
||||
table.add_column("CPU%", justify="right")
|
||||
table.add_column("Memory", justify="right")
|
||||
table.add_column("Net I/O", justify="right")
|
||||
|
||||
if host_filter:
|
||||
containers = [c for c in containers if c.host == host_filter]
|
||||
|
||||
# Sort by stack, then service
|
||||
containers = sorted(containers, key=lambda c: (c.stack.lower(), c.service.lower()))
|
||||
|
||||
for c in containers:
|
||||
table.add_row(
|
||||
c.stack or c.name,
|
||||
c.service or c.name,
|
||||
c.host,
|
||||
c.image,
|
||||
f"[{_status_style(c.status)}]{c.status}[/]",
|
||||
c.uptime or "[dim]-[/]",
|
||||
f"[{_cpu_style(c.cpu_percent)}]{c.cpu_percent:.1f}%[/]",
|
||||
f"[{_mem_style(c.memory_percent)}]{format_bytes(c.memory_usage)}[/]",
|
||||
_format_network(c.network_rx, c.network_tx, format_bytes),
|
||||
)
|
||||
|
||||
return table
|
||||
|
||||
|
||||
# --- Command functions ---
|
||||
|
||||
|
||||
@@ -175,24 +282,66 @@ def stats(
|
||||
bool,
|
||||
typer.Option("--live", "-l", help="Query Docker for live container stats"),
|
||||
] = False,
|
||||
containers: Annotated[
|
||||
bool,
|
||||
typer.Option(
|
||||
"--containers", "-C", help="Show per-container resource stats (requires Glances)"
|
||||
),
|
||||
] = False,
|
||||
host: HostOption = None,
|
||||
config: ConfigOption = None,
|
||||
) -> None:
|
||||
"""Show overview statistics for hosts and stacks.
|
||||
|
||||
Without --live: Shows config/state info (hosts, stacks, pending migrations).
|
||||
Without flags: Shows config/state info (hosts, stacks, pending migrations).
|
||||
With --live: Also queries Docker on each host for container counts.
|
||||
With --containers: Shows per-container resource stats (requires Glances).
|
||||
"""
|
||||
cfg = load_config_or_exit(config)
|
||||
|
||||
host_filter = None
|
||||
if host:
|
||||
validate_hosts(cfg, host)
|
||||
host_filter = host
|
||||
|
||||
# Handle --containers mode
|
||||
if containers:
|
||||
if not cfg.glances_stack:
|
||||
print_error("Glances not configured")
|
||||
console.print("[dim]Add 'glances_stack: glances' to compose-farm.yaml[/]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
from compose_farm.glances import fetch_all_container_stats # noqa: PLC0415
|
||||
|
||||
host_list = [host_filter] if host_filter else None
|
||||
container_list = run_async(fetch_all_container_stats(cfg, hosts=host_list))
|
||||
|
||||
if not container_list:
|
||||
print_warning("No containers found")
|
||||
raise typer.Exit(0)
|
||||
|
||||
console.print(_build_containers_table(container_list, host_filter=host_filter))
|
||||
return
|
||||
|
||||
# Validate and filter by host if specified
|
||||
if host_filter:
|
||||
all_hosts = [host_filter]
|
||||
selected_hosts = {host_filter: cfg.hosts[host_filter]}
|
||||
else:
|
||||
all_hosts = list(cfg.hosts.keys())
|
||||
selected_hosts = cfg.hosts
|
||||
|
||||
state = load_state(cfg)
|
||||
pending = get_stacks_needing_migration(cfg)
|
||||
|
||||
all_hosts = list(cfg.hosts.keys())
|
||||
stacks_by_host = group_stacks_by_host(cfg.stacks, cfg.hosts, all_hosts)
|
||||
running_by_host = group_stacks_by_host(state, cfg.hosts, all_hosts)
|
||||
# Filter pending migrations to selected host(s)
|
||||
if host_filter:
|
||||
pending = [stack for stack in pending if host_filter in cfg.get_hosts(stack)]
|
||||
stacks_by_host = group_stacks_by_host(cfg.stacks, selected_hosts, all_hosts)
|
||||
running_by_host = group_stacks_by_host(state, selected_hosts, all_hosts)
|
||||
|
||||
container_counts: dict[str, int] = {}
|
||||
if live:
|
||||
container_counts = _get_container_counts(cfg)
|
||||
container_counts = _get_container_counts(cfg, all_hosts)
|
||||
|
||||
host_table = _build_host_table(
|
||||
cfg, stacks_by_host, running_by_host, container_counts, show_containers=live
|
||||
@@ -200,9 +349,46 @@ def stats(
|
||||
console.print(host_table)
|
||||
|
||||
console.print()
|
||||
console.print(_build_summary_table(cfg, state, pending))
|
||||
console.print(_build_summary_table(cfg, state, pending, host_filter=host_filter))
|
||||
|
||||
|
||||
@app.command("list", rich_help_panel="Monitoring")
|
||||
def list_(
|
||||
host: HostOption = None,
|
||||
simple: Annotated[
|
||||
bool,
|
||||
typer.Option("--simple", "-s", help="Plain output (one stack per line, for scripting)"),
|
||||
] = False,
|
||||
config: ConfigOption = None,
|
||||
) -> None:
|
||||
"""List all stacks and their assigned hosts."""
|
||||
cfg = load_config_or_exit(config)
|
||||
|
||||
stacks: list[tuple[str, str | list[str]]] = list(cfg.stacks.items())
|
||||
if host:
|
||||
stacks = [(s, h) for s, h in stacks if str(h) == host or host in str(h).split(",")]
|
||||
|
||||
if simple:
|
||||
for stack, _ in sorted(stacks):
|
||||
console.print(stack)
|
||||
else:
|
||||
# Assign colors to hosts for visual grouping
|
||||
host_colors = ["magenta", "cyan", "green", "yellow", "blue", "red"]
|
||||
unique_hosts = sorted({str(h) for _, h in stacks})
|
||||
host_color_map = {h: host_colors[i % len(host_colors)] for i, h in enumerate(unique_hosts)}
|
||||
|
||||
table = Table(title="Stacks", show_header=True, header_style="bold cyan")
|
||||
table.add_column("Stack")
|
||||
table.add_column("Host")
|
||||
|
||||
for stack, host_val in sorted(stacks):
|
||||
color = host_color_map.get(str(host_val), "white")
|
||||
table.add_row(f"[{color}]{stack}[/]", f"[{color}]{host_val}[/]")
|
||||
|
||||
console.print(table)
|
||||
|
||||
|
||||
# Aliases (hidden from help)
|
||||
app.command("l", hidden=True)(logs) # cf l = cf logs
|
||||
app.command("ls", hidden=True)(list_) # cf ls = cf list
|
||||
app.command("s", hidden=True)(stats) # cf s = cf stats
|
||||
|
||||
@@ -280,8 +280,11 @@ def parse_external_networks(config: Config, stack: str) -> list[str]:
|
||||
return []
|
||||
|
||||
external_networks: list[str] = []
|
||||
for name, definition in networks.items():
|
||||
for key, definition in networks.items():
|
||||
if isinstance(definition, dict) and definition.get("external") is True:
|
||||
# Networks may have a "name" field, which may differ from the key.
|
||||
# Use it if present, else fall back to the key.
|
||||
name = str(definition.get("name", key))
|
||||
external_networks.append(name)
|
||||
|
||||
return external_networks
|
||||
|
||||
@@ -16,6 +16,13 @@ if TYPE_CHECKING:
|
||||
DEFAULT_GLANCES_PORT = 61208
|
||||
|
||||
|
||||
def format_bytes(bytes_val: int) -> str:
|
||||
"""Format bytes to human readable string (e.g., 1.5 GiB)."""
|
||||
import humanize # noqa: PLC0415
|
||||
|
||||
return humanize.naturalsize(bytes_val, binary=True, format="%.1f")
|
||||
|
||||
|
||||
def _get_glances_address(
|
||||
host_name: str,
|
||||
host: Host,
|
||||
@@ -244,11 +251,13 @@ async def fetch_container_stats(
|
||||
async def fetch_all_container_stats(
|
||||
config: Config,
|
||||
port: int = DEFAULT_GLANCES_PORT,
|
||||
hosts: list[str] | None = None,
|
||||
) -> list[ContainerStats]:
|
||||
"""Fetch container stats from all hosts in parallel, enriched with compose labels."""
|
||||
from .executor import get_container_compose_labels # noqa: PLC0415
|
||||
|
||||
glances_container = config.glances_stack
|
||||
host_names = hosts if hosts is not None else list(config.hosts.keys())
|
||||
|
||||
async def fetch_host_data(
|
||||
host_name: str,
|
||||
@@ -269,8 +278,9 @@ async def fetch_all_container_stats(
|
||||
return containers
|
||||
|
||||
tasks = [
|
||||
fetch_host_data(name, _get_glances_address(name, host, glances_container))
|
||||
for name, host in config.hosts.items()
|
||||
fetch_host_data(name, _get_glances_address(name, config.hosts[name], glances_container))
|
||||
for name in host_names
|
||||
if name in config.hosts
|
||||
]
|
||||
results = await asyncio.gather(*tasks)
|
||||
# Flatten list of lists
|
||||
|
||||
@@ -7,12 +7,11 @@ import re
|
||||
from typing import TYPE_CHECKING
|
||||
from urllib.parse import quote
|
||||
|
||||
import humanize
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import HTMLResponse, JSONResponse
|
||||
|
||||
from compose_farm.executor import TTLCache
|
||||
from compose_farm.glances import ContainerStats, fetch_all_container_stats
|
||||
from compose_farm.glances import ContainerStats, fetch_all_container_stats, format_bytes
|
||||
from compose_farm.registry import DOCKER_HUB_ALIASES, ImageRef
|
||||
from compose_farm.web.deps import get_config, get_templates
|
||||
|
||||
@@ -32,11 +31,6 @@ MIN_NAME_PARTS = 2
|
||||
_DASH_HTML = '<span class="text-xs opacity-50">-</span>'
|
||||
|
||||
|
||||
def _format_bytes(bytes_val: int) -> str:
|
||||
"""Format bytes to human readable string."""
|
||||
return humanize.naturalsize(bytes_val, binary=True, format="%.1f")
|
||||
|
||||
|
||||
def _parse_image(image: str) -> tuple[str, str]:
|
||||
"""Parse image string into (name, tag)."""
|
||||
# Handle registry prefix (e.g., ghcr.io/user/repo:tag)
|
||||
@@ -177,8 +171,8 @@ def _render_row(c: ContainerStats, idx: int | str) -> str:
|
||||
f'<td data-sort="{c.status.lower()}"><span class="{_status_class(c.status)}">{c.status}</span></td>'
|
||||
f'<td data-sort="{uptime_sec}" class="text-xs text-right font-mono">{c.uptime or "-"}</td>'
|
||||
f'<td data-sort="{cpu}" class="text-right font-mono"><div class="flex flex-col items-end gap-0.5"><div class="w-12 h-2 bg-base-300 rounded-full overflow-hidden"><div class="h-full {cpu_class}" style="width: {min(cpu, 100)}%"></div></div><span class="text-xs">{cpu:.0f}%</span></div></td>'
|
||||
f'<td data-sort="{c.memory_usage}" class="text-right font-mono"><div class="flex flex-col items-end gap-0.5"><div class="w-12 h-2 bg-base-300 rounded-full overflow-hidden"><div class="h-full {mem_class}" style="width: {min(mem, 100)}%"></div></div><span class="text-xs">{_format_bytes(c.memory_usage)}</span></div></td>'
|
||||
f'<td data-sort="{c.network_rx + c.network_tx}" class="text-xs text-right font-mono">↓{_format_bytes(c.network_rx)} ↑{_format_bytes(c.network_tx)}</td>'
|
||||
f'<td data-sort="{c.memory_usage}" class="text-right font-mono"><div class="flex flex-col items-end gap-0.5"><div class="w-12 h-2 bg-base-300 rounded-full overflow-hidden"><div class="h-full {mem_class}" style="width: {min(mem, 100)}%"></div></div><span class="text-xs">{format_bytes(c.memory_usage)}</span></div></td>'
|
||||
f'<td data-sort="{c.network_rx + c.network_tx}" class="text-xs text-right font-mono">↓{format_bytes(c.network_rx)} ↑{format_bytes(c.network_tx)}</td>'
|
||||
"</tr>"
|
||||
)
|
||||
|
||||
|
||||
@@ -551,7 +551,6 @@ function playFabIntro() {
|
||||
let commands = [];
|
||||
let filtered = [];
|
||||
let selected = 0;
|
||||
let originalTheme = null; // Store theme when palette opens for preview/restore
|
||||
|
||||
const post = (url) => () => htmx.ajax('POST', url, {swap: 'none'});
|
||||
const nav = (url, afterNav) => () => {
|
||||
@@ -575,20 +574,21 @@ function playFabIntro() {
|
||||
}
|
||||
htmx.ajax('POST', `/api/${endpoint}`, {swap: 'none'});
|
||||
};
|
||||
// Get saved theme from localStorage (source of truth)
|
||||
const getSavedTheme = () => localStorage.getItem(THEME_KEY) || 'dark';
|
||||
|
||||
// Apply theme and save to localStorage
|
||||
const setTheme = (theme) => () => {
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
localStorage.setItem(THEME_KEY, theme);
|
||||
};
|
||||
// Preview theme without saving (for hover)
|
||||
// Preview theme without saving (for hover). Guards against undefined/invalid themes.
|
||||
const previewTheme = (theme) => {
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
if (theme) document.documentElement.setAttribute('data-theme', theme);
|
||||
};
|
||||
// Restore original theme (when closing without selection)
|
||||
// Restore theme from localStorage (source of truth)
|
||||
const restoreTheme = () => {
|
||||
if (originalTheme) {
|
||||
document.documentElement.setAttribute('data-theme', originalTheme);
|
||||
}
|
||||
document.documentElement.setAttribute('data-theme', getSavedTheme());
|
||||
};
|
||||
// Generate color swatch HTML for a theme
|
||||
const themeSwatch = (theme) => `<span class="flex gap-0.5" data-theme="${theme}"><span class="w-2 h-4 rounded-l bg-primary"></span><span class="w-2 h-4 bg-secondary"></span><span class="w-2 h-4 bg-accent"></span><span class="w-2 h-4 rounded-r bg-neutral"></span></span>`;
|
||||
@@ -721,26 +721,24 @@ function playFabIntro() {
|
||||
// Scroll selected item into view
|
||||
const sel = list.querySelector(`[data-idx="${selected}"]`);
|
||||
if (sel) sel.scrollIntoView({ block: 'nearest' });
|
||||
// Preview theme if selected item is a theme command
|
||||
// Preview theme if selected item is a theme command, otherwise restore saved
|
||||
const selectedCmd = filtered[selected];
|
||||
if (selectedCmd?.themeId) {
|
||||
previewTheme(selectedCmd.themeId);
|
||||
} else if (originalTheme) {
|
||||
// Restore original when navigating away from theme commands
|
||||
previewTheme(originalTheme);
|
||||
} else {
|
||||
restoreTheme();
|
||||
}
|
||||
}
|
||||
|
||||
function open(initialFilter = '') {
|
||||
// Store original theme for preview/restore
|
||||
originalTheme = document.documentElement.getAttribute('data-theme') || 'dark';
|
||||
buildCommands();
|
||||
selected = 0;
|
||||
input.value = initialFilter;
|
||||
filter();
|
||||
// If opening theme picker, select current theme
|
||||
if (initialFilter.startsWith('theme:')) {
|
||||
const currentIdx = filtered.findIndex(c => c.themeId === originalTheme);
|
||||
const savedTheme = getSavedTheme();
|
||||
const currentIdx = filtered.findIndex(c => c.themeId === savedTheme);
|
||||
if (currentIdx >= 0) selected = currentIdx;
|
||||
}
|
||||
render();
|
||||
@@ -751,10 +749,6 @@ function playFabIntro() {
|
||||
function exec() {
|
||||
const cmd = filtered[selected];
|
||||
if (cmd) {
|
||||
if (cmd.themeId) {
|
||||
// Theme command commits the previewed choice.
|
||||
originalTheme = null;
|
||||
}
|
||||
dialog.close();
|
||||
cmd.action();
|
||||
}
|
||||
@@ -794,19 +788,14 @@ function playFabIntro() {
|
||||
if (a) previewTheme(a.dataset.themeId);
|
||||
});
|
||||
|
||||
// Mouse leaving list restores to selected item's theme (or original)
|
||||
// Mouse leaving list restores to selected item's theme (or saved)
|
||||
list.addEventListener('mouseleave', () => {
|
||||
const cmd = filtered[selected];
|
||||
previewTheme(cmd?.themeId || originalTheme);
|
||||
previewTheme(cmd?.themeId || getSavedTheme());
|
||||
});
|
||||
|
||||
// Restore theme when dialog closes without selection (Escape, backdrop click)
|
||||
dialog.addEventListener('close', () => {
|
||||
if (originalTheme) {
|
||||
restoreTheme();
|
||||
originalTheme = null;
|
||||
}
|
||||
});
|
||||
// Restore theme from localStorage when dialog closes
|
||||
dialog.addEventListener('close', restoreTheme);
|
||||
|
||||
// FAB click to open
|
||||
if (fab) fab.addEventListener('click', () => open());
|
||||
|
||||
168
tests/test_cli_monitoring.py
Normal file
168
tests/test_cli_monitoring.py
Normal file
@@ -0,0 +1,168 @@
|
||||
"""Tests for CLI monitoring commands (stats)."""
|
||||
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
import typer
|
||||
|
||||
from compose_farm.cli.monitoring import _build_summary_table, stats
|
||||
from compose_farm.config import Config, Host
|
||||
from compose_farm.glances import ContainerStats
|
||||
|
||||
|
||||
def _make_config(tmp_path: Path, glances_stack: str | None = None) -> Config:
|
||||
"""Create a minimal config for testing."""
|
||||
config_path = tmp_path / "compose-farm.yaml"
|
||||
config_path.write_text("")
|
||||
|
||||
return Config(
|
||||
compose_dir=tmp_path / "compose",
|
||||
hosts={"host1": Host(address="localhost")},
|
||||
stacks={"svc1": "host1"},
|
||||
config_path=config_path,
|
||||
glances_stack=glances_stack,
|
||||
)
|
||||
|
||||
|
||||
class TestStatsCommand:
|
||||
"""Tests for the stats command."""
|
||||
|
||||
def test_stats_containers_requires_glances_config(
|
||||
self, tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
"""--containers fails if glances_stack is not configured."""
|
||||
cfg = _make_config(tmp_path, glances_stack=None)
|
||||
|
||||
with (
|
||||
patch("compose_farm.cli.monitoring.load_config_or_exit", return_value=cfg),
|
||||
pytest.raises(typer.Exit) as exc_info,
|
||||
):
|
||||
stats(live=False, containers=True, host=None, config=None)
|
||||
|
||||
assert exc_info.value.exit_code == 1
|
||||
captured = capsys.readouterr()
|
||||
assert "Glances not configured" in captured.err
|
||||
|
||||
def test_stats_containers_success(
|
||||
self, tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
"""--containers fetches and displays container stats."""
|
||||
cfg = _make_config(tmp_path, glances_stack="glances")
|
||||
|
||||
mock_containers = [
|
||||
ContainerStats(
|
||||
name="nginx",
|
||||
host="host1",
|
||||
status="running",
|
||||
image="nginx:latest",
|
||||
cpu_percent=10.5,
|
||||
memory_usage=100 * 1024 * 1024,
|
||||
memory_limit=1024 * 1024 * 1024,
|
||||
memory_percent=10.0,
|
||||
network_rx=1000,
|
||||
network_tx=2000,
|
||||
uptime="1h",
|
||||
ports="80->80",
|
||||
engine="docker",
|
||||
stack="web",
|
||||
service="nginx",
|
||||
)
|
||||
]
|
||||
|
||||
async def mock_fetch_async(
|
||||
cfg: Config, hosts: list[str] | None = None
|
||||
) -> list[ContainerStats]:
|
||||
return mock_containers
|
||||
|
||||
with (
|
||||
patch("compose_farm.cli.monitoring.load_config_or_exit", return_value=cfg),
|
||||
patch(
|
||||
"compose_farm.glances.fetch_all_container_stats", side_effect=mock_fetch_async
|
||||
) as mock_fetch,
|
||||
):
|
||||
stats(live=False, containers=True, host=None, config=None)
|
||||
|
||||
mock_fetch.assert_called_once_with(cfg, hosts=None)
|
||||
|
||||
captured = capsys.readouterr()
|
||||
# Verify table output
|
||||
assert "nginx" in captured.out
|
||||
assert "host1" in captured.out
|
||||
assert "runni" in captured.out
|
||||
assert "10.5%" in captured.out
|
||||
|
||||
def test_stats_containers_empty(
|
||||
self, tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
"""--containers handles empty result gracefully."""
|
||||
cfg = _make_config(tmp_path, glances_stack="glances")
|
||||
|
||||
async def mock_fetch_empty(
|
||||
cfg: Config, hosts: list[str] | None = None
|
||||
) -> list[ContainerStats]:
|
||||
return []
|
||||
|
||||
with (
|
||||
patch("compose_farm.cli.monitoring.load_config_or_exit", return_value=cfg),
|
||||
patch("compose_farm.glances.fetch_all_container_stats", side_effect=mock_fetch_empty),
|
||||
):
|
||||
with pytest.raises(typer.Exit) as exc_info:
|
||||
stats(live=False, containers=True, host=None, config=None)
|
||||
|
||||
assert exc_info.value.exit_code == 0
|
||||
|
||||
captured = capsys.readouterr()
|
||||
assert "No containers found" in captured.err
|
||||
|
||||
def test_stats_containers_host_filter(self, tmp_path: Path) -> None:
|
||||
"""--host limits container queries in --containers mode."""
|
||||
cfg = _make_config(tmp_path, glances_stack="glances")
|
||||
|
||||
async def mock_fetch_async(
|
||||
cfg: Config, hosts: list[str] | None = None
|
||||
) -> list[ContainerStats]:
|
||||
return []
|
||||
|
||||
with (
|
||||
patch("compose_farm.cli.monitoring.load_config_or_exit", return_value=cfg),
|
||||
patch(
|
||||
"compose_farm.glances.fetch_all_container_stats", side_effect=mock_fetch_async
|
||||
) as mock_fetch,
|
||||
pytest.raises(typer.Exit),
|
||||
):
|
||||
stats(live=False, containers=True, host="host1", config=None)
|
||||
|
||||
mock_fetch.assert_called_once_with(cfg, hosts=["host1"])
|
||||
|
||||
def test_stats_summary_respects_host_filter(self, tmp_path: Path) -> None:
|
||||
"""--host filters summary counts to the selected host."""
|
||||
compose_dir = tmp_path / "compose"
|
||||
for name in ("svc1", "svc2", "svc3"):
|
||||
stack_dir = compose_dir / name
|
||||
stack_dir.mkdir(parents=True)
|
||||
(stack_dir / "compose.yaml").write_text("services: {}\n")
|
||||
|
||||
config_path = tmp_path / "compose-farm.yaml"
|
||||
config_path.write_text("")
|
||||
|
||||
cfg = Config(
|
||||
compose_dir=compose_dir,
|
||||
hosts={
|
||||
"host1": Host(address="localhost"),
|
||||
"host2": Host(address="127.0.0.2"),
|
||||
},
|
||||
stacks={"svc1": "host1", "svc2": "host2", "svc3": "host1"},
|
||||
config_path=config_path,
|
||||
)
|
||||
|
||||
state: dict[str, str | list[str]] = {"svc1": "host1", "svc2": "host2"}
|
||||
table = _build_summary_table(cfg, state, pending=[], host_filter="host1")
|
||||
labels = table.columns[0]._cells
|
||||
values = table.columns[1]._cells
|
||||
summary = dict(zip(labels, values, strict=True))
|
||||
|
||||
assert summary["Total hosts"] == "1"
|
||||
assert summary["Stacks (configured)"] == "2"
|
||||
assert summary["Stacks (tracked)"] == "1"
|
||||
assert summary["Compose files on disk"] == "2"
|
||||
@@ -370,7 +370,7 @@ class TestConfigInitEnv:
|
||||
assert "Aborted" in result.stdout
|
||||
assert env_file.read_text() == "KEEP_THIS=true"
|
||||
|
||||
def test_init_env_defaults_to_config_dir(
|
||||
def test_init_env_defaults_to_current_dir(
|
||||
self,
|
||||
runner: CliRunner,
|
||||
tmp_path: Path,
|
||||
@@ -378,12 +378,20 @@ class TestConfigInitEnv:
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.delenv("CF_CONFIG", raising=False)
|
||||
config_file = tmp_path / "compose-farm.yaml"
|
||||
config_dir = tmp_path / "config"
|
||||
config_dir.mkdir()
|
||||
config_file = config_dir / "compose-farm.yaml"
|
||||
config_file.write_text(yaml.dump(valid_config_data))
|
||||
|
||||
# Create a separate working directory
|
||||
work_dir = tmp_path / "workdir"
|
||||
work_dir.mkdir()
|
||||
monkeypatch.chdir(work_dir)
|
||||
|
||||
result = runner.invoke(app, ["config", "init-env", "-p", str(config_file)])
|
||||
|
||||
assert result.exit_code == 0
|
||||
# Should create .env in same directory as config
|
||||
env_file = tmp_path / ".env"
|
||||
# Should create .env in current directory, not config directory
|
||||
env_file = work_dir / ".env"
|
||||
assert env_file.exists()
|
||||
assert not (config_dir / ".env").exists()
|
||||
|
||||
@@ -7,10 +7,9 @@ import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from compose_farm.config import Config, Host
|
||||
from compose_farm.glances import ContainerStats
|
||||
from compose_farm.glances import ContainerStats, format_bytes
|
||||
from compose_farm.web.app import create_app
|
||||
from compose_farm.web.routes.containers import (
|
||||
_format_bytes,
|
||||
_infer_stack_service,
|
||||
_parse_image,
|
||||
_parse_uptime_seconds,
|
||||
@@ -23,25 +22,25 @@ GB = MB * 1024
|
||||
|
||||
|
||||
class TestFormatBytes:
|
||||
"""Tests for _format_bytes function (uses humanize library)."""
|
||||
"""Tests for format_bytes function (uses humanize library)."""
|
||||
|
||||
def test_bytes(self) -> None:
|
||||
assert _format_bytes(500) == "500 Bytes"
|
||||
assert _format_bytes(0) == "0 Bytes"
|
||||
assert format_bytes(500) == "500 Bytes"
|
||||
assert format_bytes(0) == "0 Bytes"
|
||||
|
||||
def test_kilobytes(self) -> None:
|
||||
assert _format_bytes(KB) == "1.0 KiB"
|
||||
assert _format_bytes(KB * 5) == "5.0 KiB"
|
||||
assert _format_bytes(KB + 512) == "1.5 KiB"
|
||||
assert format_bytes(KB) == "1.0 KiB"
|
||||
assert format_bytes(KB * 5) == "5.0 KiB"
|
||||
assert format_bytes(KB + 512) == "1.5 KiB"
|
||||
|
||||
def test_megabytes(self) -> None:
|
||||
assert _format_bytes(MB) == "1.0 MiB"
|
||||
assert _format_bytes(MB * 100) == "100.0 MiB"
|
||||
assert _format_bytes(MB * 512) == "512.0 MiB"
|
||||
assert format_bytes(MB) == "1.0 MiB"
|
||||
assert format_bytes(MB * 100) == "100.0 MiB"
|
||||
assert format_bytes(MB * 512) == "512.0 MiB"
|
||||
|
||||
def test_gigabytes(self) -> None:
|
||||
assert _format_bytes(GB) == "1.0 GiB"
|
||||
assert _format_bytes(GB * 2) == "2.0 GiB"
|
||||
assert format_bytes(GB) == "1.0 GiB"
|
||||
assert format_bytes(GB * 2) == "2.0 GiB"
|
||||
|
||||
|
||||
class TestParseImage:
|
||||
|
||||
@@ -338,6 +338,26 @@ def test_parse_external_networks_missing_compose(tmp_path: Path) -> None:
|
||||
assert networks == []
|
||||
|
||||
|
||||
def test_parse_external_networks_with_name_field(tmp_path: Path) -> None:
|
||||
"""Network with 'name' field uses actual name, not key."""
|
||||
cfg = Config(
|
||||
compose_dir=tmp_path,
|
||||
hosts={"host1": Host(address="192.168.1.10")},
|
||||
stacks={"app": "host1"},
|
||||
)
|
||||
compose_path = tmp_path / "app" / "compose.yaml"
|
||||
_write_compose(
|
||||
compose_path,
|
||||
{
|
||||
"services": {"app": {"image": "nginx"}},
|
||||
"networks": {"default": {"name": "compose-net", "external": True}},
|
||||
},
|
||||
)
|
||||
|
||||
networks = parse_external_networks(cfg, "app")
|
||||
assert networks == ["compose-net"]
|
||||
|
||||
|
||||
class TestExtractWebsiteUrls:
|
||||
"""Test extract_website_urls function."""
|
||||
|
||||
|
||||
Reference in New Issue
Block a user