Repository navigation
Expand file tree
/
Copy pathods-cli
More file actions
executable file
·4693 lines (4154 loc) · 180 KB
/
Copy pathods-cli
File metadata and controls
executable file
·4693 lines (4154 loc) · 180 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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# ods-cli - Command line interface for ODS
# Mission: M5 (Clonable ODS Setup Server)
# Version: 2.0.0 — Registry-driven service resolution
set -euo pipefail
# Require Bash 4+ (associative arrays used by service registry and ods-cli)
if (( BASH_VERSINFO[0] < 4 )); then
echo -e "\033[0;31m✗\033[0m ods-cli requires Bash 4.0+ (you have $BASH_VERSION)" >&2
echo " macOS ships Bash 3.2 due to licensing. Install a modern version:" >&2
echo " brew install bash" >&2
echo " Then re-run with: /opt/homebrew/bin/bash $0 $*" >&2
exit 1
fi
#=============================================================================
# Configuration
#=============================================================================
_source="${BASH_SOURCE[0]}"
while [[ -L "$_source" ]]; do
_dir="$(cd "$(dirname "$_source")" && pwd)"
_source="$(readlink "$_source")"
[[ "$_source" != /* ]] && _source="$_dir/$_source"
done
SCRIPT_DIR="$(cd "$(dirname "$_source")" && pwd)"
INSTALL_DIR="${ODS_HOME:-$HOME/ods}"
VERSION="2.0.0"
if [[ -f "$INSTALL_DIR/.env" ]]; then
_v=$(awk -F= '/^ODS_VERSION=/{gsub(/^["'"'"']|["'"'"']$/,"",$2); print $2; exit}' "$INSTALL_DIR/.env" 2>/dev/null) || true
[[ -n "${_v:-}" ]] && VERSION="$_v"
fi
# Colors — use ANSI-C quoting ($'\033') so the variables hold real ESC bytes
# at assignment time. Single-quoted strings store the backslash literally,
# which breaks unquoted heredocs (cmd_help) that never re-interpret escapes.
# Guard on TTY + NO_COLOR so redirected / piped output stays clean.
# Per no-color.org, NO_COLOR disables colors when it is present (set to any
# value, including empty), so we check set-ness with ${NO_COLOR+x} — which
# expands to "x" whenever NO_COLOR is set and to "" only when truly unset —
# rather than ${NO_COLOR:-} which would treat NO_COLOR="" as unset.
if [[ -t 1 ]] && [[ -z "${NO_COLOR+x}" ]]; then
RED=$'\033[0;31m'
GREEN=$'\033[0;32m'
YELLOW=$'\033[1;33m'
BLUE=$'\033[0;34m'
CYAN=$'\033[0;36m'
NC=$'\033[0m'
else
RED=''
GREEN=''
YELLOW=''
BLUE=''
CYAN=''
NC=''
fi
#=============================================================================
# Helpers
#=============================================================================
log() { echo -e "${CYAN}[ods]${NC} $1" >&2; }
success() { echo -e "${GREEN}✓${NC} $1"; }
warn() { echo -e "${YELLOW}⚠${NC} $1" >&2; }
error() { echo -e "${RED}✗${NC} $1" >&2; exit 1; }
log_error() { echo -e "${RED}✗${NC} $1" >&2; }
# Map cmd_list status string to a colour. Returns an empty string for unknown
# statuses so future state names don't break formatting.
_status_color() {
case "$1" in
enabled|always-on) echo "$GREEN" ;;
disabled|stopped) echo "$YELLOW" ;;
unhealthy|error) echo "$RED" ;;
*) echo "" ;;
esac
}
_json_escape() {
local s="${1-}"
s=${s//\\/\\\\}
s=${s//\"/\\\"}
s=${s//$'\b'/\\b}
s=${s//$'\f'/\\f}
s=${s//$'\n'/\\n}
s=${s//$'\r'/\\r}
s=${s//$'\t'/\\t}
printf '%s' "$s"
}
# Print a separator of repeated characters filling the given width.
# Usage: hr <width> [<char=─>]
hr() {
local w="${1:-10}" c="${2:-─}" out=''
printf -v out '%*s' "$w" ''
printf '%s' "${out// /$c}"
}
# Update or add a key=value in .env
_env_set() {
local key="$1" val="$2" file="$INSTALL_DIR/.env"
if grep -q "^${key}=" "$file" 2>/dev/null; then
# Use awk to avoid sed delimiter collisions with values containing | / or =
awk -v k="$key" -v v="$val" '{
if (index($0, k "=") == 1) print k "=" v; else print
}' "$file" > "${file}.tmp" && cat "${file}.tmp" > "$file" && rm -f "${file}.tmp"
else
echo "${key}=${val}" >> "$file"
fi
}
_env_unset() {
local key="$1" file="$INSTALL_DIR/.env"
[[ -f "$file" ]] || return 0
awk -v k="$key" 'index($0, k "=") != 1 { print }' "$file" > "${file}.tmp" \
&& cat "${file}.tmp" > "$file" \
&& rm -f "${file}.tmp"
}
_env_get_raw() {
local key="$1" file="$INSTALL_DIR/.env"
[[ -f "$file" ]] || { echo ""; return 0; }
grep -m1 "^${key}=" "$file" 2>/dev/null | cut -d= -f2- | tr -d '\r' || true
}
_ods_cli_bootstrap_status() {
local status_file="$INSTALL_DIR/data/bootstrap-status.json"
[[ -f "$status_file" ]] || return 0
grep -o '"status"[[:space:]]*:[[:space:]]*"[^"]*"' "$status_file" \
| sed -n '1p' \
| sed 's/.*"status"[[:space:]]*:[[:space:]]*"//' \
| sed 's/"//' \
|| true
}
_ods_cli_wait_for_bootstrap_compose_safe() {
local action="${1:-service operation}"
local status_file="$INSTALL_DIR/data/bootstrap-status.json"
[[ -f "$status_file" ]] || return 0
local max_wait="${ODS_CLI_BOOTSTRAP_COMPOSE_WAIT_SECONDS:-900}"
local interval="${ODS_CLI_BOOTSTRAP_COMPOSE_WAIT_INTERVAL:-5}"
if ! [[ "$max_wait" =~ ^[0-9]+$ ]] || (( max_wait < 0 )); then
max_wait=900
fi
if ! [[ "$interval" =~ ^[0-9]+$ ]] || (( interval < 1 )); then
interval=5
fi
local waited=0 announced=false status=""
while true; do
status="$(_ods_cli_bootstrap_status)"
case "$status" in
starting|verifying|swapping)
if [[ "$announced" == "false" ]]; then
log " Model Upgrade: $status; waiting before $action touches llama-server"
announced=true
fi
if (( waited >= max_wait )); then
warn "Model upgrade is still $status after ${max_wait}s; refusing to run $action against an active hot-swap."
return 1
fi
sleep "$interval"
waited=$(( waited + interval ))
;;
*)
if [[ "$announced" == "true" ]]; then
log " Model Upgrade: ${status:-idle}; continuing with $action"
fi
return 0
;;
esac
done
}
_get_host_logical_cpus() {
local cores
cores=$(nproc 2>/dev/null || grep -c '^processor' /proc/cpuinfo 2>/dev/null || echo "1")
if [[ "$cores" =~ ^[0-9]+$ ]] && [[ "$cores" -gt 0 ]]; then
echo "$cores"
else
echo "1"
fi
}
_get_docker_available_cpus() {
local cores=""
if command -v docker &>/dev/null; then
cores=$(docker info --format '{{.NCPU}}' 2>/dev/null || true)
cores="${cores//[!0-9]/}"
fi
if [[ "$cores" =~ ^[0-9]+$ ]] && [[ "$cores" -gt 0 ]]; then
echo "$cores"
return 0
fi
_get_host_logical_cpus
}
_calculate_llama_cpu_budget() {
local backend="${1:-cpu}"
local available="${2:-$(_get_docker_available_cpus)}"
local desired_limit=8
local desired_reservation=1
case "$backend" in
amd)
desired_limit=16
desired_reservation=4
;;
nvidia|intel|sycl)
desired_limit=16
desired_reservation=2
;;
apple)
desired_limit=8
desired_reservation=2
;;
esac
if ! [[ "$available" =~ ^[0-9]+$ ]] || [[ "$available" -lt 1 ]]; then
available=1
fi
local limit="$desired_limit"
local reservation="$desired_reservation"
[[ "$available" -lt "$limit" ]] && limit="$available"
[[ "$reservation" -gt "$limit" ]] && reservation="$limit"
echo "$limit $reservation $available"
}
_select_auto_cpu_value() {
local existing="$1" detected="$2"
if [[ "$existing" =~ ^[0-9]+([.][0-9]+)?$ ]] && LC_ALL=C awk "BEGIN { exit !($existing > 0 && $existing <= $detected) }"; then
echo "$existing"
else
echo "$detected"
fi
}
_cap_cpu_value() {
local desired="$1" ceiling="$2"
LC_ALL=C awk -v desired="$desired" -v ceiling="$ceiling" '
BEGIN {
if (ceiling <= 0) ceiling = 1
value = desired
if (value > ceiling) value = ceiling
if (value < 0.01) value = 0.01
printf "%.1f", value
}'
}
_ensure_service_cpu_pair() {
local available="$1" name="$2" desired_limit="$3" desired_reservation="$4"
local limit_key="${name}_CPU_LIMIT"
local reservation_key="${name}_CPU_RESERVATION"
local detected_limit detected_reservation current_limit current_reservation final_limit final_reservation
detected_limit="$(_cap_cpu_value "$desired_limit" "$available")"
current_limit="$(_env_get_raw "$limit_key")"
final_limit="$(_select_auto_cpu_value "$current_limit" "$detected_limit")"
detected_reservation="$(_cap_cpu_value "$desired_reservation" "$final_limit")"
current_reservation="$(_env_get_raw "$reservation_key")"
final_reservation="$(_select_auto_cpu_value "$current_reservation" "$detected_reservation")"
if LC_ALL=C awk "BEGIN { exit !($final_reservation > $final_limit) }"; then
final_reservation="$final_limit"
fi
if [[ "$current_limit" != "$final_limit" ]]; then
_env_set "$limit_key" "$final_limit"
SERVICE_CPU_BUDGET_CHANGED=true
fi
if [[ "$current_reservation" != "$final_reservation" ]]; then
_env_set "$reservation_key" "$final_reservation"
SERVICE_CPU_BUDGET_CHANGED=true
fi
}
ensure_llama_cpu_budget() {
local env_file="$INSTALL_DIR/.env"
[[ -f "$env_file" ]] || return 0
local backend
backend="$(_env_get_raw "GPU_BACKEND")"
backend=$(echo "${backend:-cpu}" | tr '[:upper:]' '[:lower:]')
[[ "$backend" == "none" ]] && backend="cpu"
local limit_raw reservation_raw available
read -r limit_raw reservation_raw available <<< "$(_calculate_llama_cpu_budget "$backend")"
local detected_limit="${limit_raw}.0"
local detected_reservation="${reservation_raw}.0"
local current_limit current_reservation final_limit final_reservation
current_limit="$(_env_get_raw "LLAMA_CPU_LIMIT")"
current_reservation="$(_env_get_raw "LLAMA_CPU_RESERVATION")"
final_limit="$(_select_auto_cpu_value "$current_limit" "$detected_limit")"
final_reservation="$(_select_auto_cpu_value "$current_reservation" "$detected_reservation")"
if LC_ALL=C awk "BEGIN { exit !($final_reservation > $final_limit) }"; then
final_reservation="$final_limit"
fi
local changed=false
if [[ "$current_limit" != "$final_limit" ]]; then
_env_set "LLAMA_CPU_LIMIT" "$final_limit"
changed=true
fi
if [[ "$current_reservation" != "$final_reservation" ]]; then
_env_set "LLAMA_CPU_RESERVATION" "$final_reservation"
changed=true
fi
if [[ "$changed" == "true" ]]; then
log "Auto-adjusted llama-server CPU budget: limit=${final_limit}, reservation=${final_reservation} (Docker CPUs: ${available})"
fi
SERVICE_CPU_BUDGET_CHANGED=false
_ensure_service_cpu_pair "$available" "TTS" "8.0" "2.0"
_ensure_service_cpu_pair "$available" "WHISPER" "4.0" "1.0"
_ensure_service_cpu_pair "$available" "HERMES" "4.0" "0.5"
_ensure_service_cpu_pair "$available" "COMFYUI" "16.0" "2.0"
if [[ "$SERVICE_CPU_BUDGET_CHANGED" == "true" ]]; then
log "Auto-adjusted bundled service CPU budgets (Docker CPUs: ${available})"
fi
unset SERVICE_CPU_BUDGET_CHANGED
}
check_install() {
if [[ ! -d "$INSTALL_DIR" ]]; then
error "ODS not found at $INSTALL_DIR. Set ODS_HOME or run installer first."
fi
if [[ ! -f "$INSTALL_DIR/docker-compose.base.yml" ]]; then
# Backward compat: check for monolithic docker-compose.yml
if [[ ! -f "$INSTALL_DIR/docker-compose.yml" ]]; then
error "docker-compose.base.yml not found in $INSTALL_DIR"
fi
fi
}
# Extract the major component of a semver string (e.g. "2.1.0" → "2").
# Used only for counting major-version jumps; not for ordering comparisons.
_semver_major() {
echo "${1%%.*}"
}
# Full 3-component semver less-than: returns 0 (true) if v1 < v2.
# Strips any leading "v" and ignores pre-release suffixes.
_semver_lt() {
local v1="${1#v}" v2="${2#v}"
local IFS='.'
local -a a=($v1) b=($v2)
local i
for i in 0 1 2; do
local n1="${a[$i]:-0}" n2="${b[$i]:-0}"
n1="${n1%%[!0-9]*}" n2="${n2%%[!0-9]*}"
if (( n1 < n2 )); then return 0; fi
if (( n1 > n2 )); then return 1; fi
done
return 1 # equal → not less-than
}
# Read a top-level or nested string field from a JSON file.
# Usage: _manifest_field <file> <field> e.g. _manifest_field manifest.json ods_version
# Logs a warning to stderr on parse failure rather than silently returning empty.
_manifest_field() {
local file="$1" field="$2" value=""
if [[ ! -f "$file" ]]; then
warn "_manifest_field: file not found: ${file}" >&2
return 1
fi
if command -v jq &>/dev/null; then
if ! value=$(jq -r --arg f "$field" '.[$f] // .release.version // empty' "$file"); then
warn "_manifest_field: jq failed to parse ${file}" >&2
fi
fi
if [[ -z "$value" ]] && command -v python3 &>/dev/null; then
# Pass file and field as argv to avoid shell-injection via string interpolation.
if ! value=$(python3 -c '
import json, sys
try:
d = json.load(open(sys.argv[1]))
f = sys.argv[2]
print(d.get(f) or d.get("release", {}).get("version") or "")
except Exception as e:
sys.stderr.write("_manifest_field: " + str(e) + "\n")
' "$file" "$field"); then
warn "_manifest_field: python3 failed to parse ${file}" >&2
fi
fi
echo "$value"
}
# Version compatibility check for ods update.
# Returns 0 (ok) or 1 (user aborted / hard-blocked).
# Sets _COMPAT_INSTALLED_VER and _COMPAT_TARGET_VER as side-effects.
#
# Version source precedence (single source of truth policy):
# installed: ODS_VERSION in .env > .version file > manifest.json ods_version
# target: manifest.json ods_version (post-pull reflects the incoming release)
_check_version_compat() {
local force="${1:-false}"
# 1. Installed version
# `|| true` preserves the tolerant fallback semantics required by
# the maintainer audit on PR #998: under `set -euo pipefail`,
# a fresh install whose .env lacks ODS_VERSION must fall back
# to .version / manifest.json (handled below), not exit out of
# the surrounding command. Landed on main via #1008.
_COMPAT_INSTALLED_VER=$(grep '^ODS_VERSION=' "$INSTALL_DIR/.env" 2>/dev/null \
| sed -n '1p' | cut -d= -f2 | tr -d '[:space:]' || true)
# Fall back to .version file (written by ods-update.sh / PR #349 convention)
if [[ -z "$_COMPAT_INSTALLED_VER" && -f "$INSTALL_DIR/.version" ]]; then
_COMPAT_INSTALLED_VER=$(jq -r '.version // empty' "$INSTALL_DIR/.version" 2>/dev/null \
|| grep -o '"version"[[:space:]]*:[[:space:]]*"[^"]*"' \
"$INSTALL_DIR/.version" 2>/dev/null | cut -d'"' -f4 \
|| true)
fi
if [[ -z "$_COMPAT_INSTALLED_VER" && -f "$INSTALL_DIR/manifest.json" ]]; then
_COMPAT_INSTALLED_VER=$(_manifest_field "$INSTALL_DIR/manifest.json" "ods_version")
fi
[[ -z "$_COMPAT_INSTALLED_VER" ]] && _COMPAT_INSTALLED_VER="$VERSION"
# 2. Target version — from manifest.json (reflects the incoming release after pull)
_COMPAT_TARGET_VER=""
if [[ -f "$INSTALL_DIR/manifest.json" ]]; then
_COMPAT_TARGET_VER=$(_manifest_field "$INSTALL_DIR/manifest.json" "ods_version")
fi
# 3. min_compatible_ods_version — read via _manifest_field to avoid 2>/dev/null + injection
local min_compat_ver=""
if [[ -f "$INSTALL_DIR/manifest.json" ]]; then
min_compat_ver=$(_manifest_field "$INSTALL_DIR/manifest.json" "min_compatible_ods_version")
fi
# Skip checks if we can't determine versions
if [[ -z "$_COMPAT_INSTALLED_VER" || -z "$_COMPAT_TARGET_VER" ]]; then
return 0
fi
# Skip if installed == target (no actual update)
[[ "$_COMPAT_INSTALLED_VER" == "$_COMPAT_TARGET_VER" ]] && return 0
local cur_major new_major
cur_major=$(_semver_major "$_COMPAT_INSTALLED_VER")
new_major=$(_semver_major "$_COMPAT_TARGET_VER")
# major_jump may be negative (downgrade); use arithmetic not regex for sign-aware logic
local major_jump=$(( new_major - cur_major ))
# 4. Downgrade detection — warn and confirm before proceeding
if (( major_jump < 0 )); then
echo ""
echo -e "${YELLOW}┌──────────────────────────────────────────────────────────┐${NC}"
echo -e "${YELLOW}│ Downgrade detected │${NC}"
echo -e "${YELLOW}└──────────────────────────────────────────────────────────┘${NC}"
echo ""
warn "Installed : v${_COMPAT_INSTALLED_VER} (major ${cur_major})"
warn "Target : v${_COMPAT_TARGET_VER} (major ${new_major})"
echo ""
log "Downgrading may corrupt data or break your installation."
log "Consider restoring a backup instead: ods rollback"
echo ""
if [[ "$force" == "true" ]]; then
warn "--force specified: proceeding with downgrade."
else
read -p " Proceed with downgrade? [y/N] " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
log "Update cancelled."
return 1
fi
fi
echo ""
fi
# 5. Hard block: installed version is below min_compatible_ods_version.
# Uses full 3-component comparison — major-only was insufficient
# (e.g. 1.2.0 vs min 1.5.0 both have major 1 but 1.2.0 < 1.5.0).
if [[ -n "$min_compat_ver" ]] && _semver_lt "$_COMPAT_INSTALLED_VER" "$min_compat_ver"; then
echo ""
echo -e "${RED}╔══════════════════════════════════════════════════════════╗${NC}"
echo -e "${RED}║ UPGRADE BLOCKED — installed version is too old ║${NC}"
echo -e "${RED}╚══════════════════════════════════════════════════════════╝${NC}"
echo ""
warn "Installed : v${_COMPAT_INSTALLED_VER}"
warn "Target : v${_COMPAT_TARGET_VER}"
warn "Minimum : v${min_compat_ver} (min_compatible_ods_version)"
echo ""
log "Your installation is below the minimum supported upgrade version."
log "Upgrade incrementally: first update to v${min_compat_ver}, then re-run."
log "See CHANGELOG.md for migration steps."
echo ""
if [[ "$force" == "true" ]]; then
warn "--force specified: proceeding despite compatibility block. DATA LOSS RISK."
else
log "Use 'ods update --force' to override (not recommended)."
return 1
fi
fi
# 6. Warn: major version jump > 1
if (( major_jump > 1 )); then
echo ""
echo -e "${YELLOW}┌──────────────────────────────────────────────────────────┐${NC}"
echo -e "${YELLOW}│ Major version jump detected │${NC}"
echo -e "${YELLOW}└──────────────────────────────────────────────────────────┘${NC}"
echo ""
warn "Installed : v${_COMPAT_INSTALLED_VER} (major ${cur_major})"
warn "Target : v${_COMPAT_TARGET_VER} (major ${new_major})"
warn "Jump : ${major_jump} major versions"
echo ""
log "Skipping more than 1 major version may introduce breaking changes."
log "Recommended: upgrade step-by-step (v${cur_major} → v$((cur_major+1)) → … → v${new_major})."
log "Review CHANGELOG.md for each major version before proceeding."
echo ""
if [[ "$force" == "true" ]]; then
warn "--force specified: skipping confirmation."
else
read -p " Proceed with v${_COMPAT_INSTALLED_VER} → v${_COMPAT_TARGET_VER} anyway? [y/N] " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
log "Update cancelled."
return 1
fi
warn "Proceeding — back up your data first: ods backup"
fi
echo ""
fi
return 0
}
#=============================================================================
# Safe .env loading (no eval; use lib/safe-env.sh)
#=============================================================================
[[ -f "$SCRIPT_DIR/lib/safe-env.sh" ]] && . "$SCRIPT_DIR/lib/safe-env.sh"
load_env() {
[[ -f "$INSTALL_DIR/.env" ]] || { warn ".env not found at $INSTALL_DIR — run installer first"; return 1; }
load_env_file "$INSTALL_DIR/.env"
}
#=============================================================================
# Service Registry
#=============================================================================
. "$SCRIPT_DIR/lib/service-registry.sh"
# Resolve a user-provided service name to a compose service ID
resolve_service() {
local resolved
resolved=$(sr_resolve "$1")
echo "$resolved"
}
# Regenerate .compose-flags after enable/disable
_regenerate_compose_flags() {
if [[ -x "$INSTALL_DIR/scripts/resolve-compose-stack.sh" ]]; then
# --gpu-count gates the multigpu-{backend}.yml overlay; without it,
# toggling any extension would silently strip multi-GPU plumbing
# from the persisted cache.
"$INSTALL_DIR/scripts/resolve-compose-stack.sh" \
--script-dir "$INSTALL_DIR" --tier "${TIER:-1}" --gpu-backend "${GPU_BACKEND:-nvidia}" \
--gpu-count "${GPU_COUNT:-1}" --ods-mode "${ODS_MODE:-local}" \
> "$INSTALL_DIR/.compose-flags" 2>/dev/null || rm -f "$INSTALL_DIR/.compose-flags"
else
rm -f "$INSTALL_DIR/.compose-flags"
fi
}
# Run a lifecycle hook for a service (reads manifest directly via Python)
_run_hook() {
local service_id="$1" hook_name="$2"
local ext_dir="$INSTALL_DIR/extensions/services/$service_id"
# Also check user-extensions
[[ -d "$ext_dir" ]] || ext_dir="$INSTALL_DIR/data/user-extensions/$service_id"
[[ -d "$ext_dir" ]] || return 0
local hook_path
hook_path=$(python3 - "$ext_dir" "$hook_name" <<'PYEOF'
import yaml, sys
from pathlib import Path
ext_dir = Path(sys.argv[1])
hook_name = sys.argv[2]
manifest_path = None
for name in ("manifest.yaml", "manifest.yml"):
candidate = ext_dir / name
if candidate.exists():
manifest_path = candidate
break
if manifest_path is None:
sys.exit(0)
with open(manifest_path) as f:
m = yaml.safe_load(f)
if not isinstance(m, dict):
sys.exit(0)
service = m.get("service", {})
if not isinstance(service, dict):
sys.exit(0)
# Check hooks map first
hooks = service.get("hooks", {})
hook_script = ""
if isinstance(hooks, dict):
hook_script = hooks.get(hook_name, "")
# Fallback: setup_hook -> post_install only
if not hook_script and hook_name == "post_install":
hook_script = service.get("setup_hook", "")
if not hook_script:
sys.exit(0)
# Validate path containment
hook_path = (ext_dir / hook_script).resolve()
try:
hook_path.relative_to(ext_dir.resolve())
except ValueError:
print(f"ERROR: hook path escapes extension directory: {hook_script}", file=sys.stderr)
sys.exit(1)
if not hook_path.is_file():
sys.exit(0)
print(str(hook_path))
PYEOF
) || return 0
[[ -z "$hook_path" || ! -f "$hook_path" ]] && return 0
log "Running $hook_name hook for $service_id..."
SERVICE_ID="$service_id" \
SERVICE_PORT="${SERVICE_PORTS[$service_id]:-0}" \
SERVICE_DATA_DIR="$INSTALL_DIR/data/$service_id" \
ODS_VERSION="$VERSION" \
GPU_BACKEND="${GPU_BACKEND:-}" \
HOOK_NAME="$hook_name" \
bash "$hook_path" "$INSTALL_DIR" "${GPU_BACKEND:-}" \
|| warn "$hook_name hook failed for $service_id (non-fatal)"
}
# Build full compose flags: base + GPU overlay + enabled extensions
get_compose_flags() {
# Fast path: use saved flags from installer if available
if [[ -f "$INSTALL_DIR/.compose-flags" ]]; then
local cached
cached=$(< "$INSTALL_DIR/.compose-flags")
if [[ "$cached" == -f\ * ]]; then
# Validate that every referenced compose file still exists.
# Protects against renames across upgrades (e.g. multigpu.yml →
# multigpu-nvidia.yml) where the cache would otherwise hand docker
# compose a path that no longer resolves.
local stale=0 prev="" tok
for tok in $cached; do
if [[ "$prev" == "-f" ]]; then
if [[ "$tok" = /* ]]; then
[[ -f "$tok" ]] || { stale=1; break; }
else
[[ -f "$INSTALL_DIR/$tok" ]] || { stale=1; break; }
fi
fi
prev="$tok"
done
local _ods_mode="${ODS_MODE:-local}"
local _lemonade_external="${LEMONADE_EXTERNAL:-false}"
local _amd_runtime="${AMD_INFERENCE_RUNTIME:-}"
local _amd_managed="${AMD_INFERENCE_MANAGED:-true}"
_lemonade_external="${_lemonade_external,,}"
_amd_runtime="${_amd_runtime,,}"
_amd_managed="${_amd_managed,,}"
local _external_lemonade_active="false"
if [[ "$_ods_mode" == "lemonade" ]]; then
if [[ "$_lemonade_external" =~ ^(1|true|yes|on)$ ]] || \
{ [[ "$_amd_runtime" == "lemonade" ]] && [[ "$_amd_managed" =~ ^(0|false|no|off)$ ]]; }; then
_external_lemonade_active="true"
fi
fi
if [[ "$_ods_mode" == "cloud" ]] && \
{ [[ "$cached" == *"docker-compose.cpu.yml"* ]] || [[ "$cached" == *"compose.local.yaml"* ]] || [[ "$cached" != *"docker-compose.cloud.yml"* ]]; }; then
stale=1
fi
if [[ "$_external_lemonade_active" == "true" ]] && \
{ [[ "$cached" == *"compose.local.yaml"* ]] || [[ "$cached" == *"docker-compose.amd.yml"* ]] || [[ "$cached" != *"docker-compose.cloud.yml"* ]] || [[ "$cached" != *"docker-compose.lemonade-external.yml"* ]]; }; then
stale=1
fi
if [[ "$_ods_mode" != "cloud" ]] && [[ "$_external_lemonade_active" != "true" ]] && \
[[ "$cached" == *"docker-compose.cloud.yml"* ]]; then
stale=1
fi
if [[ "$stale" == "0" ]]; then
echo "$cached"
return
fi
fi
# Stale or corrupt — remove and fall through to dynamic resolution
rm -f "$INSTALL_DIR/.compose-flags"
fi
# Fallback: resolve dynamically
local base_flags
if [[ -x "$INSTALL_DIR/scripts/resolve-compose-stack.sh" ]]; then
# Resolver handles base + GPU overlay + extension compose files.
# --gpu-count gates the multigpu-{backend}.yml overlay — without it,
# this fallback path resolves to a single-GPU stack on multi-GPU hosts.
base_flags=$("$INSTALL_DIR/scripts/resolve-compose-stack.sh" \
--script-dir "$INSTALL_DIR" --tier "${TIER:-1}" --gpu-backend "${GPU_BACKEND:-nvidia}" \
--gpu-count "${GPU_COUNT:-1}" --ods-mode "${ODS_MODE:-local}")
echo "$base_flags"
elif [[ -f "$INSTALL_DIR/docker-compose.base.yml" ]]; then
base_flags="-f docker-compose.base.yml"
local ext_flags
ext_flags=$(sr_compose_flags)
echo "$base_flags $ext_flags"
else
base_flags="-f docker-compose.yml"
local ext_flags
ext_flags=$(sr_compose_flags)
echo "$base_flags $ext_flags"
fi
}
# Run `docker compose <args...>` with a compact summary on success and a
# surfaced error banner on failure.
#
# Usage: _compose_run_with_summary <verb> <compose_args...>
# <verb> Human-readable gerund phrase, e.g. "Restarting all services"
# <compose_args> Everything that goes after `docker compose`, including
# any `-f` flags resolved by get_compose_flags.
#
# Behavior:
# - Runs `docker compose --progress quiet <compose_args>`, capturing
# stdout+stderr to a mktemp log file.
# - On success: prints "<verb> — done" and removes the log file.
# - On failure: prints an error banner, surfaces up to 20 lines matching
# /error|unhealthy|failed|dependency/, preserves the full
# log file for inspection, and returns the compose exit
# code so the caller (under `set -e`) aborts with it.
#
# The summary grep pipeline can legitimately produce zero matches if the
# failing compose output has no error-keyword hits. `upstream/main` today
# runs under `set -e` only (no `pipefail`), so grep's exit 1 is absorbed
# by the pipeline's final-stage exit and the function continues to the
# log-path surface below. When pipefail is eventually adopted (sibling
# nounset/exit-code audit change), grep's no-match or a SIGPIPE from
# `head -20` on >20 matches would abort this function before the caller
# sees the compose log path or the compose exit code. `|| warn "..."`
# is the project-blessed form (per CLAUDE.md) for "tolerate this specific
# non-match and log why the summary is empty" — it costs nothing today
# and keeps the function correct under future pipefail.
_compose_run_with_summary() {
local _verb="$1"; shift
log "${_verb}..."
_check_docker_access
local _compose_log
_compose_log=$(mktemp)
trap 'rm -f "$_compose_log"' INT TERM
local _is_compose_up=false _arg
for _arg in "$@"; do
[[ "$_arg" == "up" ]] && _is_compose_up=true
done
_compose_remove_conflicting_ods_containers() {
local _log_path="$1"
local _removed=false
local _name _id
while read -r _name _id; do
[[ -n "${_name:-}" && -n "${_id:-}" ]] || continue
case "$_name" in
/ods-*|ods-*)
docker rm -f "$_id" >>"$_log_path" 2>&1 || return 1
_removed=true
;;
*)
warn "Refusing to remove conflicting non-ODS container $_name."
return 1
;;
esac
done < <(sed -nE 's/.*container name "([^"]+)".*already in use by container "([0-9a-fA-F]+)".*/\1 \2/p' "$_log_path" | awk '!seen[$0]++')
$_removed
}
local _rc=0
docker compose --progress quiet "$@" >"$_compose_log" 2>&1 || _rc=$?
if (( _rc != 0 )) && $_is_compose_up \
&& grep -Eiq 'port is already allocated|Bind for .* failed: port is already allocated' "$_compose_log"; then
warn "Docker reported a port allocation race; waiting briefly and retrying once."
sleep "${ODS_COMPOSE_PORT_RETRY_DELAY:-10}"
: >"$_compose_log"
_rc=0
docker compose --progress quiet "$@" >"$_compose_log" 2>&1 || _rc=$?
fi
local _startup_max_attempts="${ODS_COMPOSE_STARTUP_RETRY_ATTEMPTS:-3}"
if ! [[ "$_startup_max_attempts" =~ ^[0-9]+$ ]] || (( _startup_max_attempts < 1 )); then
_startup_max_attempts=3
fi
local _startup_attempt=1
local _startup_retries=$(( _startup_max_attempts - 1 ))
local _name_conflict_retries="${ODS_COMPOSE_NAME_CONFLICT_RETRY_ATTEMPTS:-1}"
if ! [[ "$_name_conflict_retries" =~ ^[0-9]+$ ]] || (( _name_conflict_retries < 0 )); then
_name_conflict_retries=1
fi
local _name_conflict_attempt=0
while (( _rc != 0 )) && $_is_compose_up; do
if grep -Eiq 'container name "/?ods-[^"]+" is already in use by container "[0-9a-fA-F]+"' "$_compose_log"; then
if (( _name_conflict_attempt >= _name_conflict_retries )); then
break
fi
_name_conflict_attempt=$(( _name_conflict_attempt + 1 ))
warn "Docker reported a stale ODS container-name conflict; removing the conflicting container and retrying (${_name_conflict_attempt}/${_name_conflict_retries})."
_compose_remove_conflicting_ods_containers "$_compose_log" || break
sleep "${ODS_COMPOSE_NAME_CONFLICT_RETRY_DELAY:-3}"
elif (( _startup_attempt < _startup_max_attempts )) \
&& grep -Eiq 'dependency failed to start|No such container|container .* (exited|is unhealthy)|service .* failed to start|failed to start.*container' "$_compose_log"; then
warn "Docker reported a transient service startup failure; waiting briefly and retrying (${_startup_attempt}/${_startup_retries})."
sleep "${ODS_COMPOSE_STARTUP_RETRY_DELAY:-15}"
_startup_attempt=$(( _startup_attempt + 1 ))
else
break
fi
: >"$_compose_log"
_rc=0
docker compose --progress quiet "$@" >"$_compose_log" 2>&1 || _rc=$?
done
if (( _rc == 0 )); then
success "${_verb} — done"
rm -f "$_compose_log"
trap - INT TERM
return 0
fi
log_error "${_verb} failed:"
local _surfaced
_surfaced=$(grep -iE 'error|unhealthy|failed|dependency|permission denied|docker API|docker daemon|docker\.sock|/var/run/docker\.sock' "$_compose_log" \
| sed 's/^/ /' \
| head -20 || true)
if [[ -n "$_surfaced" ]]; then
printf '%s\n' "$_surfaced"
else
warn "(no error keywords matched in compose log)"
fi
if grep -qiE 'permission denied.*(docker API|docker daemon|docker\.sock|/var/run/docker\.sock)|/var/run/docker\.sock.*permission denied' "$_compose_log"; then
warn "Docker socket permission denied. Add your user to the docker group, then start a new login shell:"
warn " sudo usermod -aG docker \"\$USER\""
warn " newgrp docker # or log out and back in"
warn "Then verify with: docker ps"
fi
echo ""
log "Full compose output: $_compose_log"
trap - INT TERM
return "$_rc"
}
#=============================================================================
# Warn (don't exit) when the current user can't reach the Docker daemon on
# Linux. Phase 05 of the installer sets DOCKER_CMD="sudo docker" for users
# not in the docker group, but ods-cli calls bare `docker compose` and
# can't see that. Without this check, --rebuild-images fails with an opaque
# "permission denied while trying to connect to the Docker daemon socket"
# and users have no idea what to do next. macOS Docker Desktop grants
# socket access to the logged-in user, so the check is Linux-only.
#=============================================================================
_check_docker_access() {
[[ "$(uname -s)" == Linux* ]] || return 0
local _docker_ps_output
if _docker_ps_output=$(docker ps 2>&1); then
return 0
fi
if grep -qiE 'permission denied.*(docker API|docker daemon|docker\.sock|/var/run/docker\.sock)|/var/run/docker\.sock.*permission denied' <<<"$_docker_ps_output"; then
warn "Current user cannot reach the Docker daemon: Docker socket permission denied."
warn "Run: sudo usermod -aG docker \"\$USER\""
warn "Then run: newgrp docker (or log out and back in) and retry."
else
warn "Current user cannot reach the Docker daemon. Start Docker and verify with: docker ps"
fi
}
#=============================================================================
# Rebuild local-built images (opt-in via --rebuild-images on restart/start/update).
# Always rebuilds: dashboard, dashboard-api, ape, token-spy, privacy-shield.
# Conditionally rebuilds based on .env state:
# - comfyui (ENABLE_COMFYUI=true)
# - llama-server (GPU_BACKEND=amd, e.g. AMD Lemonade)
# Mirrors the conditional logic in installers/phases/11-services.sh. Unlike that
# phase's image-inspect fast-path, --rebuild-images is an explicit opt-in so we
# always rebuild every applicable service from source.
#=============================================================================
_ods_cli_rebuild_images() {
local flags=("$@")
local svcs=(dashboard dashboard-api ape token-spy privacy-shield)
# Mirror phases/11-services.sh conditional builds: ComfyUI when enabled
# and llama-server on AMD (Lemonade builds the binary in the container).
# Other GPU backends pull pre-built images.
[[ "${ENABLE_COMFYUI:-}" == "true" ]] && svcs+=(comfyui)
[[ "${GPU_BACKEND:-}" == "amd" ]] && svcs+=(llama-server)
_check_docker_access
log "Rebuilding local-built images (--rebuild-images)..."
if ! docker compose "${flags[@]}" build --no-cache "${svcs[@]}"; then
warn "One or more images failed to rebuild (continuing — see compose output above)"
fi
}
#=============================================================================
# Commands
#=============================================================================
cmd_status() {
local json_mode="false"
while [[ $# -gt 0 ]]; do
case "$1" in
--json) json_mode="true"; shift ;;
*) error "Unknown argument to 'ods status': $1" ;;
esac
done
if [[ "$json_mode" == "true" ]]; then
# Subshell isolates cmd_status_json's RETURN trap so it can't leak
# into this caller's frame and re-fire with an unbound $tmp under set -u.
( cmd_status_json )
return $?
fi
check_install
cd "$INSTALL_DIR"
load_env
sr_load
local flags_str
flags_str=$(get_compose_flags)
local -a flags
read -ra flags <<< "$flags_str"
echo -e "${BLUE}━━━ ODS Status ━━━${NC}"
echo ""
# Container status
docker compose "${flags[@]}" ps --format "table {{.Name}}\t{{.Status}}\t{{.Ports}}" 2>/dev/null || docker-compose ps
echo ""
# Registry-driven health checks (parallel)
echo -e "${BLUE}━━━ Health Checks ━━━${NC}"
# Create temp directory for health check results
local tmpdir
tmpdir=$(mktemp -d)
trap "rm -rf '$tmpdir'" RETURN
# Array to track background job PIDs
local -a pids=()
# Launch parallel health checks
for sid in "${SERVICE_IDS[@]}"; do
local health="${SERVICE_HEALTH[$sid]}"
local port_env="${SERVICE_PORT_ENVS[$sid]}"
local default_port="${SERVICE_PORTS[$sid]}"
local name="${SERVICE_NAMES[$sid]:-$sid}"
local cat="${SERVICE_CATEGORIES[$sid]}"
# Skip services with no health endpoint or port
[[ -z "$health" || "$default_port" == "0" ]] && continue
# Resolve port from env var or default
local port="$default_port"
if [[ -n "$port_env" ]]; then
port="${!port_env:-$default_port}"
fi
# For non-core services, only check if container is running
if [[ "$cat" != "core" ]]; then
if ! docker compose "${flags[@]}" ps --format "{{.Name}}" 2>/dev/null | grep -qE "ods-${sid}|${sid}"; then
continue # Not running, skip silently
fi
fi
# Launch health check in background
(
url="http://127.0.0.1:${port}${health}"
timeout="${SERVICE_HEALTH_TIMEOUTS[$sid]:-5}"
if curl -sf --max-time "$timeout" "$url" > /dev/null 2>&1; then
echo "healthy|$name" > "$tmpdir/$sid"
else
echo "unhealthy|$name" > "$tmpdir/$sid"
fi
) &
pids+=($!)
done
# Wait for all health checks to complete
for pid in "${pids[@]}"; do
wait "$pid" 2>/dev/null || true
done
# Display results in SERVICE_IDS order
for sid in "${SERVICE_IDS[@]}"; do
if [[ -f "$tmpdir/$sid" ]]; then