-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnukelabctl
More file actions
executable file
·519 lines (469 loc) · 20 KB
/
Copy pathnukelabctl
File metadata and controls
executable file
·519 lines (469 loc) · 20 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
#!/bin/bash
# SPDX-FileCopyrightText: 2023-2026 NukeHub Developers
# SPDX-License-Identifier: BSD-2-Clause
# NukeLab Platform — Unified Management Script
# Usage: ./nukelabctl <command> [target] [flags]
#
# Commands are implemented as modules in scripts/manage.d/*.sh
# Shared infrastructure lives in scripts/lib.sh.
set -euo pipefail
set -E
# ─── Shared Helpers ────────────────────────────────────────────────────────
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" > /dev/null 2>&1 && pwd)"
cd "$DIR"
source "$DIR/scripts/lib.sh"
# ─── Setup ─────────────────────────────────────────────────────────────────
FRONTEND_PID_FILE="$DIR/.frontend.pid"
# Dev and prod are isolated as separate Compose projects with their own state.
PROD_PROJECT_NAME="nukelab"
DEV_PROJECT_NAME="nukelab-dev"
PROD_STATE_FILE="$DIR/.nukelab-state.sh"
DEV_STATE_FILE="$DIR/.nukelab-state-dev.sh"
COMPOSE_FILE="$DIR/compose.yml"
DEV_COMPOSE_FILE="$DIR/.nukelab-dev-compose.yml"
COMPOSE_ARGS=(-f "$COMPOSE_FILE")
# Defaults; the active mode selects the actual values before dispatch.
# COMPOSE_PROJECT_NAME must be exported so compose subprocesses actually
# isolate dev and prod into separate Compose projects.
export COMPOSE_PROJECT_NAME="$PROD_PROJECT_NAME"
STATE_FILE="$PROD_STATE_FILE"
# ─── Argument Parsing ─────────────────────────────────────────────────────-
CMD=""
TARGET=""
USE_DEV_MODE=false
USE_COVERAGE=false
SHOW_HELP=false
SKIP_PORT_CHECK=false
NO_ALERTMANAGER=false
EXTRA_ARGS=()
COMPOSE_OVERLAY_FILES=()
# Per-command options that take a value. These are passed through to command
# parsers so the value is not misinterpreted as a target.
VALUE_OPTIONS=("--tail" "-n" "--timeout" "-t" "-k")
parse_args() {
# Phase 1: consume global flags that may appear before the command.
while [[ $# -gt 0 ]]; do
case "$1" in
--help | -h)
print_help
exit 0
;;
--coverage)
USE_COVERAGE=true
;;
--verbose | -v)
VERBOSE=true
QUIET=false
LOG_LEVEL=DEBUG
;;
--quiet | -q)
QUIET=true
VERBOSE=false
LOG_LEVEL=ERROR
;;
--overlay | -o)
shift
COMPOSE_OVERLAY_FILES+=("$1")
;;
--skip-port-check)
SKIP_PORT_CHECK=true
;;
--no-alertmanager)
NO_ALERTMANAGER=true
;;
--version)
CMD="version"
shift || true
break
;;
-*)
# Unknown leading option or a command-specific option placed
# before the command. Stop global parsing and let the next
# phase decide.
break
;;
*)
# First positional token is the command.
break
;;
esac
shift
done
# If --version was given, CMD is already set and we are done parsing.
if [ "$CMD" = "version" ]; then
return
fi
CMD="${1:-help}"
shift || true
# Normalize aliases early so the dispatcher never needs a special case.
[[ "$CMD" == "rm" ]] && CMD="remove"
# Normalize top-level help requests.
case "$CMD" in
help | --help | -h)
print_help
exit 0
;;
esac
# Phase 2: parse command arguments, targets, and per-command options.
while [[ $# -gt 0 ]]; do
case "$1" in
backend | frontend | shell | all)
if [ "$CMD" = "dev" ]; then
# The dev meta-command parses subcommands/targets itself.
EXTRA_ARGS+=("$1")
elif [ -z "$TARGET" ]; then
TARGET="$1"
else
# A target was already fixed; treat this token as a command
# argument (e.g. `build env all`).
EXTRA_ARGS+=("$1")
fi
;;
--coverage)
USE_COVERAGE=true
;;
--verbose | -v)
VERBOSE=true
QUIET=false
LOG_LEVEL=DEBUG
;;
--quiet | -q)
QUIET=true
VERBOSE=false
LOG_LEVEL=ERROR
;;
--overlay | -o)
shift
COMPOSE_OVERLAY_FILES+=("$1")
;;
--skip-port-check)
SKIP_PORT_CHECK=true
;;
--no-alertmanager)
NO_ALERTMANAGER=true
;;
--version)
# Ignore --version when it appears after the command.
;;
--help | -h)
SHOW_HELP=true
;;
-*)
EXTRA_ARGS+=("$1")
# Preserve the value of known value-taking options, but only
# while we have not yet fixed the positional target. After the
# target is known, subsequent tokens are command arguments and
# must not have their values consumed (e.g. `exec backend ls -t`).
if [[ -z "$TARGET" ]]; then
for _opt in "${VALUE_OPTIONS[@]}"; do
if [[ "$1" == "$_opt" && $# -gt 1 ]]; then
shift
EXTRA_ARGS+=("$1")
break
fi
done
fi
;;
*)
# e2e has no target: positionals are Playwright arguments
# (spec files, test dirs) and must be forwarded in order.
if [[ -z "$TARGET" ]] && [ "$CMD" != "dev" ] && [ "$CMD" != "e2e" ]; then
TARGET="$1"
else
EXTRA_ARGS+=("$1")
fi
;;
esac
shift
done
if [[ -z "$TARGET" ]]; then
# loadtest has its own "all" profile; default it to baseline instead.
if [ "$CMD" = "loadtest" ]; then
TARGET="baseline"
else
TARGET="all"
fi
fi
}
# ─── Help ─────────────────────────────────────────────────────────────────-
print_help() {
cat <<- EOF
${BOLD}${CYAN}
_ _ _ _ _
| \\ | | | | | | | |
| \\| |_ _| | _____| | __ _| |__
| . \` | | | | |/ / _ \\ | / _\` | '_ \\
| |\\ | |_| | < __/ |___| (_| | |_) |
|_| \\_|\\__,_|_|\\_\\___|______\\__,_|_.__/ ${RESET}${DIM}$(_nukelab_version)
${RESET}
${DIM}Unified Management Script${RESET}
${BOLD}${CYAN}────────────────────────────────────────────${RESET}
${BOLD}Usage:${RESET} ./nukelabctl <command> [target] [flags]
${BOLD}${MAGENTA}Quick Start:${RESET}
${GREEN}start${RESET} [target] Start services
${GREEN}stop${RESET} [target] Stop services
${GREEN}restart${RESET} [target] Restart services
${GREEN}status${RESET} Show status
${BOLD}Development Stack:${RESET}
${GREEN}dev${RESET} <subcommand> Manage the dev stack
start [target] [options] Start dev stack (default)
restart [target] Restart dev stack
stop [target] Stop dev stack
logs [service] [options] Stream dev stack logs
status [options] Show dev stack status
${BOLD}Build & Deploy:${RESET}
${GREEN}build${RESET} [target] Build containers
${GREEN}update${RESET} Pull images & rebuild
${GREEN}pull${RESET} Pull latest base images
${BOLD}Toolchains:${RESET}
${GREEN}cache-toolchain${RESET} <image> Pre-populate a shared toolchain volume
${BOLD}Maintenance:${RESET}
${GREEN}clean${RESET} Remove dangling images/volumes
${GREEN}remove${RESET} [target] Remove containers (keep data)
${GREEN}reset${RESET} ⚠️ Delete ALL data & containers
${GREEN}init-user-auth-keys${RESET} Generate initial user-auth Ed25519 keys
${GREEN}rotate-user-auth-key${RESET} Rotate the active user-auth Ed25519 key
${GREEN}cleanup-user-auth-keys${RESET} Remove expired retired user-auth keys
${BOLD}Environment:${RESET}
${GREEN}check-env${RESET} [options] Compare env files to .env.example
${GREEN}sync-env${RESET} [file] [options] Merge missing keys from .env.example
${BOLD}Development Tools:${RESET}
${GREEN}shell${RESET} [service] Open shell in container
${GREEN}exec${RESET} [service] [command] Execute command in container
${GREEN}install${RESET} [target] Install dependencies
${BOLD}Database:${RESET}
${GREEN}db-migrate${RESET} Run Alembic migrations
${GREEN}db-shell${RESET} Open PostgreSQL shell
${GREEN}backup${RESET} Create database backup
${GREEN}restore${RESET} <file> Restore database from backup
${BOLD}Testing:${RESET}
${GREEN}test${RESET} [target] [--coverage] Run tests
${GREEN}e2e${RESET} [playwright-args...] Run Playwright E2E tests
${GREEN}loadtest${RESET} [profile] Run Locust/k6 load tests
${GREEN}selftest${RESET} Quick nukelabctl sanity check
${BOLD}Code Quality:${RESET}
${GREEN}lint${RESET} [target] [--fix] Lint backend/frontend/shell/markdown code
${BOLD}Security:${RESET}
${GREEN}security${RESET} [options] Run Bandit, pip-audit, and npm audit
${GREEN}verify-hardening${RESET} [container] Verify spawned container hardening
${BOLD}Diagnostics:${RESET}
${GREEN}doctor${RESET} Check host environment readiness
${GREEN}version${RESET} Show version and engine info
${BOLD}Other:${RESET}
${GREEN}install-completion${RESET} Install bash tab-completion
${BOLD}Targets:${RESET} ${DIM}(optional, default: all)${RESET}
backend Backend services (api, workers, db, redis, traefik)
frontend Frontend unit/lint tests
shell Shell scripts
markdown Markdown lint and link check
all Everything ${DIM}(default)${RESET}
${BOLD}Flags:${RESET}
--coverage Run tests with coverage report (backend only)
--overlay, -o Add a compose overlay file (repeatable)
--verbose, -v Show debug output
--quiet, -q Suppress non-error output
--skip-port-check Bypass the pre-flight port check
--no-alertmanager Skip the Alertmanager overlay (useful for tests/load tests)
${BOLD}Examples:${RESET}
./nukelabctl start # Production: all containers
./nukelabctl dev # Start dev stack
./nukelabctl dev backend --no-build # Start backend only, no image build
./nukelabctl dev restart backend # Restart backend in dev mode
./nukelabctl dev logs backend -f # Stream backend logs in dev mode
./nukelabctl dev stop # Stop dev stack
./nukelabctl stop frontend # Stop only frontend
./nukelabctl build backend # Build backend image only
./nukelabctl shell backend # Shell into backend container
./nukelabctl exec backend python -v # Run command in backend
./nukelabctl db-migrate # Run migrations
./nukelabctl backup # Backup database
./nukelabctl restore backups/nukelab_backup_20250607_120000.sql
./nukelabctl test backend --coverage # Run backend tests with coverage
./nukelabctl loadtest baseline # Run Locust baseline load test
./nukelabctl security # Run all security scanners
./nukelabctl verify-hardening # Verify a running server container
./nukelabctl lint # Lint backend, frontend, shell, and markdown
./nukelabctl lint frontend --fix # Auto-fix frontend issues
./nukelabctl lint markdown # Lint markdown and check links
./nukelabctl clean # Clean up dangling resources
./nukelabctl cache-toolchain nukelab/radiation-transport:v1.2.3
./nukelabctl init-user-auth-keys # Generate initial user-auth keys (production setup)
./nukelabctl rotate-user-auth-key # Rotate the active user-auth key
./nukelabctl cleanup-user-auth-keys # Prune expired retired public keys
./nukelabctl check-env # Check active env file for drift
./nukelabctl check-env --all --changed # Check all env files including value drift
./nukelabctl sync-env .env.development --dry-run # Preview missing keys
EOF
}
# ─── Bootstrap helper ──────────────────────────────────────────────────────
# Shared setup for commands that touch the container engine. Flags select
# which steps run:
# lock acquire the concurrency lock
# restore try restore_state; fall back to setup_compose_args on failure
# setup always run setup_compose_args (instead of restore)
# raw skip compose-args setup entirely
# preflight run preflight_checks at the end
_bootstrap() {
local _do_lock=false _do_preflight=false _do_restore=false _do_setup=false _raw=false
while [ $# -gt 0 ]; do
case "$1" in
lock) _do_lock=true ;;
preflight) _do_preflight=true ;;
restore) _do_restore=true ;;
setup) _do_setup=true ;;
raw) _raw=true ;;
*) die "_bootstrap: unknown flag '$1'" ;;
esac
shift
done
if $_do_lock; then _acquire_lock; fi
init_env "$USE_DEV_MODE"
detect_engine
setup_podman_socket
if ! $_raw; then
if $_do_restore; then
if ! restore_state; then setup_compose_args; fi
elif $_do_setup; then
setup_compose_args
fi
fi
if $_do_preflight; then preflight_checks; fi
}
# ─── Command Loader ────────────────────────────────────────────────────────
_dispatch_command() {
local command="$1"
local cmd_file="$DIR/scripts/manage.d/${command}.sh"
if [ ! -f "$cmd_file" ]; then
die "Command module missing: $cmd_file"
fi
source "$cmd_file"
# Function names cannot contain hyphens, so map db-migrate -> cmd_db_migrate.
local base_name="${command//-/_}"
if $SHOW_HELP; then
# Dev meta-command: `dev --help` shows dev help; `dev <sub> --help`
# shows help for that subcommand.
if [ "$command" = "dev" ] && type -t parse_dev_args | grep -q function; then
if [[ ${#EXTRA_ARGS[@]} -eq 0 ]]; then
help_dev
exit 0
fi
parse_dev_args
local _subcmd_file="$DIR/scripts/manage.d/${DEV_SUBCMD}.sh"
if [ -f "$_subcmd_file" ]; then
# shellcheck source=/dev/null
source "$_subcmd_file"
local _help_func="help_${DEV_SUBCMD}"
if type -t "$_help_func" | grep -q function; then
"$_help_func"
exit 0
fi
fi
fi
local help_func="help_${base_name}"
if type -t "$help_func" | grep -q function; then
"$help_func"
else
warn "No detailed help available for '$command'."
print_help
fi
exit 0
fi
local parse_func="parse_${base_name}_args"
if type -t "$parse_func" | grep -q function; then
"$parse_func"
fi
"cmd_${base_name}"
}
# ─── Main ─────────────────────────────────────────────────────────────────-
main() {
parse_args "$@"
# Top-level help (./nukelabctl help or ./nukelabctl --help).
if [ "$CMD" = "help" ]; then
print_help
return 0
fi
# Tests and load tests don't need Alertmanager; auto-skip its overlay.
if [ "$CMD" = "test" ] || [ "$CMD" = "loadtest" ]; then
NO_ALERTMANAGER=true
fi
# Command-specific help can be shown without loading env/engine state.
if $SHOW_HELP; then
_dispatch_command "$CMD"
return 0
fi
case "$CMD" in
start | build | update | pull)
_bootstrap lock setup preflight
_dispatch_command "$CMD"
;;
clean)
# Clean only prunes stopped resources and local state; it does not
# need the stack reachable or ports free.
_bootstrap lock raw
_dispatch_command "$CMD"
;;
cache-toolchain)
# Pre-populates a shared toolchain volume; only needs the container
# engine, not a running stack.
_bootstrap raw
_dispatch_command "$CMD"
;;
dev)
# dev is a meta-command: it loads the dev environment and then
# dispatches to start/restart/stop/logs/status with USE_DEV_MODE=true.
USE_DEV_MODE=true
export COMPOSE_PROJECT_NAME="$DEV_PROJECT_NAME"
STATE_FILE="$DEV_STATE_FILE"
_bootstrap raw
_dispatch_command "$CMD"
;;
stop | restart | remove | reset)
_bootstrap lock restore
_dispatch_command "$CMD"
;;
lint)
_dispatch_command "$CMD"
;;
check-env | sync-env)
# These commands only parse env files; no container engine or env state needed.
_dispatch_command "$CMD"
;;
status | logs | shell | exec | db-migrate | db-shell | backup | restore | e2e | security | doctor | init-user-auth-keys | rotate-user-auth-key | cleanup-user-auth-keys | verify-hardening)
_bootstrap restore
_dispatch_command "$CMD"
;;
loadtest)
# Load tests need the multi-worker prod backend; always target prod.
USE_DEV_MODE=false
export COMPOSE_PROJECT_NAME="$PROD_PROJECT_NAME"
STATE_FILE="$PROD_STATE_FILE"
_bootstrap restore
_dispatch_command "$CMD"
;;
version)
detect_engine
_dispatch_command "$CMD"
;;
install | test)
if [ "$TARGET" = "backend" ] || [ "$TARGET" = "all" ]; then
# Tests run one-off containers on the internal network and
# never bind host ports; the port check would wrongly fail
# while the dev/prod stack is running.
if [ "$CMD" = "test" ]; then SKIP_PORT_CHECK=true; fi
_bootstrap lock restore preflight
fi
_dispatch_command "$CMD"
;;
install-completion | selftest)
_dispatch_command "$CMD"
;;
*)
die "Unknown command: $CMD\nRun './nukelabctl help' for usage."
;;
esac
}
# Install traps and run.
trap '_error_trap' ERR
trap '_interrupt_trap' INT TERM
trap '_cleanup_trap' EXIT
main "$@"