Repository navigation
Expand file tree
/
Copy pathods-update.sh
More file actions
executable file
·1400 lines (1250 loc) · 52.9 KB
/
Copy pathods-update.sh
File metadata and controls
executable file
·1400 lines (1250 loc) · 52.9 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
#!/bin/bash
# ods-update.sh - ODS Update Manager
#
# Commands:
# check - Check for updates against GitHub releases
# status - Show current version, install path, last check
# backup - Backup compose files, .env, and version state
# update - Pull new version, run migrations, restart services
# rollback - Restore from last backup
# changelog - Show version changelog
# health - Run health checks on all services
set -euo pipefail
# Prerequisites
command -v jq >/dev/null 2>&1 || { echo "Error: jq is required but not installed." >&2; echo "Install with: apt install jq (Debian/Ubuntu) or brew install jq (macOS)" >&2; exit 1; }
#==============================================================================
# CONFIGURATION
#==============================================================================
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
INSTALL_DIR="${SCRIPT_DIR}"
VERSION_FILE="${INSTALL_DIR}/.version"
BACKUP_DIR="${HOME}/.ods/backups"
ROLLBACK_DIR="${INSTALL_DIR}/data/backups" # pre-update rollback snapshots live here
MAX_BACKUPS="${MAX_BACKUPS:-10}"
UPDATE_CHANNEL="${UPDATE_CHANNEL:-stable}"
HEALTH_TIMEOUT="${HEALTH_TIMEOUT:-120}"
GITHUB_REPO="${GITHUB_REPO:-Osmantic/ODS}"
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
# Prerequisites check
command -v jq >/dev/null 2>&1 || { echo -e "${RED}Error: jq is required but not installed.${NC}" >&2; echo "Install with: apt install jq (Debian/Ubuntu) or brew install jq (macOS)" >&2; exit 1; }
command -v curl >/dev/null 2>&1 || { echo -e "${RED}Error: curl is required but not installed.${NC}" >&2; exit 1; }
#==============================================================================
# HELPER FUNCTIONS
#==============================================================================
log_info() { echo -e "${BLUE}[INFO]${NC} $*"; }
log_ok() { echo -e "${GREEN}[OK]${NC} $*"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
log_error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
# Installed version. .version is written by this script after an update
# (git describe), so when it carries a version it is the freshest record for
# this flow. No installer creates it, though, and `check` only stores
# last_check in it -- so on a fresh install fall back to what the installer
# did record: ODS_VERSION in .env (Linux phase 06), then manifest.json's
# ods_version, the same sources ods-cli and the dashboard read.
get_current_version() {
local version=""
if [[ -f "$VERSION_FILE" ]]; then
version=$(jq -r '.version // empty' "$VERSION_FILE" 2>/dev/null || true)
fi
if [[ -z "$version" ]]; then
version=$(env_file_value ODS_VERSION)
fi
if [[ -z "$version" && -f "${INSTALL_DIR}/manifest.json" ]]; then
version=$(jq -r '.ods_version // empty' "${INSTALL_DIR}/manifest.json" 2>/dev/null || true)
fi
echo "${version:-0.0.0}"
}
env_file_value() {
local key="$1"
[[ -f "${INSTALL_DIR}/.env" ]] || return 0
awk -F= -v key="$key" '
$1 == key {
value = substr($0, index($0, "=") + 1)
gsub(/\r$/, "", value)
gsub(/^["'\'']|["'\'']$/, "", value)
print value
exit
}
' "${INSTALL_DIR}/.env" 2>/dev/null || true
}
COMPOSE_PARSED_ARGS=()
compose_flags_parse() {
local flags="$1" parsed="" token
COMPOSE_PARSED_ARGS=()
[[ -n "$flags" ]] || return 0
# xargs tokenizes shell-style quotes without evaluating substitutions or
# commands. One token per output line preserves whitespace inside a path;
# compose filenames containing newlines are intentionally unsupported.
parsed="$(printf '%s\n' "$flags" | xargs -n 1 printf '%s\n')" || return 1
while IFS= read -r token; do
[[ -n "$token" ]] && COMPOSE_PARSED_ARGS+=("$token")
done <<< "$parsed"
}
compose_flags_files_exist() {
local flags="$1" index path
compose_flags_parse "$flags" || return 1
for ((index = 0; index < ${#COMPOSE_PARSED_ARGS[@]}; index++)); do
[[ "${COMPOSE_PARSED_ARGS[$index]}" == "-f" ]] || continue
((index + 1 < ${#COMPOSE_PARSED_ARGS[@]})) || return 1
path="${COMPOSE_PARSED_ARGS[$((index + 1))]}"
if [[ "$path" = /* ]]; then
[[ -f "$path" ]] || return 1
else
[[ -f "${INSTALL_DIR}/${path}" ]] || return 1
fi
done
return 0
}
resolve_compose_flags() {
local cached=""
if [[ -f "${INSTALL_DIR}/.compose-flags" ]]; then
cached="$(< "${INSTALL_DIR}/.compose-flags")"
if [[ -n "$cached" ]] && compose_flags_files_exist "$cached"; then
printf '%s\n' "$cached"
return 0
fi
log_warn "Cached compose flags are missing or stale; trying dynamic compose resolution." >&2
fi
local gpu_backend tier gpu_count ods_mode
gpu_backend="$(env_file_value GPU_BACKEND)"
tier="$(env_file_value TIER)"
gpu_count="$(env_file_value GPU_COUNT)"
ods_mode="$(env_file_value ODS_MODE)"
local resolved=""
if [[ -x "${INSTALL_DIR}/scripts/resolve-compose-stack.sh" ]]; then
resolved=$(bash "${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}" | tail -1) || resolved=""
if [[ -n "$resolved" ]] && compose_flags_files_exist "$resolved"; then
echo "$resolved"
return 0
fi
fi
if [[ -f "${INSTALL_DIR}/docker-compose.yml" ]]; then
echo "-f docker-compose.yml"
return 0
fi
if [[ -f "${INSTALL_DIR}/docker-compose.base.yml" ]]; then
local fallback="-f docker-compose.base.yml"
case "${gpu_backend:-}" in
nvidia|amd|cpu|apple|intel|sycl)
if [[ -f "${INSTALL_DIR}/docker-compose.${gpu_backend}.yml" ]]; then
fallback="$fallback -f docker-compose.${gpu_backend}.yml"
fi
;;
esac
echo "$fallback"
return 0
fi
return 1
}
is_git_checkout() {
command -v git >/dev/null 2>&1 || return 1
git -C "${INSTALL_DIR}" rev-parse --is-inside-work-tree >/dev/null 2>&1 || return 1
local prefix top
top=$(git -C "${INSTALL_DIR}" rev-parse --show-toplevel 2>/dev/null || return 1)
prefix=$(git -C "${INSTALL_DIR}" rev-parse --show-prefix 2>/dev/null || return 1)
git -C "${top}" ls-files --error-unmatch "${prefix}ods-update.sh" >/dev/null 2>&1
}
runtime_update_guidance() {
log_info "For routine runtime/image updates, run: cd \"${INSTALL_DIR}\" && ./ods-cli update"
log_info "For source-code updates, reinstall or run this command from a git-backed ODS source checkout."
}
ensure_source_checkout_for_update() {
if ! command -v git >/dev/null 2>&1; then
log_error "git is required for ods-update.sh source-code updates."
runtime_update_guidance
return 1
fi
if ! is_git_checkout; then
log_error "ods-update.sh update only works from a git-backed ODS source checkout."
log_info "Install path: ${INSTALL_DIR}"
runtime_update_guidance
log_info "No files, services, or rollback snapshots were changed."
return 1
fi
}
# Semver compare: returns 0 if equal, 1 if v1 > v2, 2 if v1 < v2
semver_compare() {
local v1="${1#v}"
local v2="${2#v}"
if [[ "$v1" == "$v2" ]]; then
return 0
fi
local IFS='.'
local i v1_parts=($v1) v2_parts=($v2)
for ((i=0; i<3; i++)); do
local n1="${v1_parts[$i]:-0}"
local n2="${v2_parts[$i]:-0}"
# Strip any non-numeric suffix
n1="${n1%%[!0-9]*}"
n2="${n2%%[!0-9]*}"
if ((n1 > n2)); then
return 1
elif ((n1 < n2)); then
return 2
fi
done
return 0
}
# _prune_rollback_snapshots
# Removes oldest pre-update snapshots beyond MAX_BACKUPS.
# Guards against misconfigured ROLLBACK_DIR before any rm -rf.
_prune_rollback_snapshots() {
if [[ -z "$ROLLBACK_DIR" || "$ROLLBACK_DIR" != */data/backups ]]; then
log_warn "ROLLBACK_DIR '${ROLLBACK_DIR}' does not end in /data/backups; skipping prune." >&2
return 0
fi
[[ -d "$ROLLBACK_DIR" ]] || return 0
local count=0
while IFS= read -r old_snap; do
count=$(( count + 1 ))
if (( count > MAX_BACKUPS )); then
log_info "Pruning old rollback snapshot: $(basename "$old_snap")" >&2
rm -rf "$old_snap"
fi
done < <(find "${ROLLBACK_DIR}" -maxdepth 1 -type d -name "pre-update-*" | sort -r)
}
_require_positive_backup_retention() {
if [[ ! "$MAX_BACKUPS" =~ ^[1-9][0-9]{0,8}$ ]]; then
log_error "MAX_BACKUPS must be a positive integer (1-999999999); refusing to create a snapshot that may be pruned immediately."
return 1
fi
}
# snapshot_pre_update <timestamp>
# Creates data/backups/pre-update-<timestamp>/ and copies:
# • .env and .env.* variants
# • docker-compose*.yml overlays (tracks active stack)
# • config/{litellm,n8n,searxng}/ (per-extension config)
# • .version
# Validates timestamp format, writes snapshot.json, verifies integrity,
# then prints the snapshot directory path on stdout.
snapshot_pre_update() {
local timestamp="${1:-$(date +%Y%m%d-%H%M%S)}"
_require_positive_backup_retention || return 1
# All log calls redirect to stderr so command-substitution callers
# (snap_dir=$(snapshot_pre_update ...)) only capture the path on stdout.
if [[ ! "$timestamp" =~ ^[0-9]{8}-[0-9]{6}$ ]]; then
log_error "Invalid timestamp format '${timestamp}'; expected YYYYMMDD-HHMMSS." >&2
return 1
fi
local snap_dir="${ROLLBACK_DIR}/pre-update-${timestamp}"
log_info "Creating rollback snapshot: pre-update-${timestamp}" >&2
mkdir -p "${snap_dir}"
local files_saved=0
# .env and .env.* variants
for pattern in ".env" ".env.*"; do
for f in "${INSTALL_DIR}"/${pattern}; do
[[ -f "$f" ]] || continue
cp "$f" "${snap_dir}/"
files_saved=$(( files_saved + 1 ))
done
done
# Active compose overlays — needed to re-create the exact stack on rollback
<
8
/div> for f in "${INSTALL_DIR}"/docker-compose*.yml "${INSTALL_DIR}"/docker-compose*.yaml; do
[[ -f "$f" ]] || continue
cp "$f" "${snap_dir}/"
files_saved=$(( files_saved + 1 ))
done
# Cached compose flags — records which overlays were active, so rollback
# can bring the restored stack up with the same file selection
if [[ -f "${INSTALL_DIR}/.compose-flags" ]]; then
cp "${INSTALL_DIR}/.compose-flags" "${snap_dir}/"
files_saved=$(( files_saved + 1 ))
fi
# Per-extension config directories. config/openclaw is no longer captured:
# the legacy OpenClaw extension was removed and its folder is left on disk
# untouched, so it does not need a rollback copy.
for ext_dir in litellm n8n searxng; do
local src="${INSTALL_DIR}/config/${ext_dir}"
if [[ -d "$src" ]]; then
cp -r "$src" "${snap_dir}/config-${ext_dir}"
files_saved=$(( files_saved + 1 ))
fi
done
# Version file
if [[ -f "$VERSION_FILE" ]]; then
cp "$VERSION_FILE" "${snap_dir}/.version"
files_saved=$(( files_saved + 1 ))
fi
# Snapshot metadata
jq -n \
--arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
--arg ver "$(get_current_version)" \
--argjson fc "$files_saved" \
--arg dir "$INSTALL_DIR" \
'{type:"pre-update", timestamp:$ts, version:$ver, files_count:$fc, install_dir:$dir}' \
> "${snap_dir}/snapshot.json"
# Integrity check: verify metadata is valid JSON before declaring success
if ! jq empty "${snap_dir}/snapshot.json"; then
log_error "Snapshot metadata is not valid JSON; aborting snapshot." >&2
rm -rf "${snap_dir}"
return 1
fi
log_ok "Rollback snapshot ready (${files_saved} items): ${snap_dir}" >&2
_prune_rollback_snapshots
echo "${snap_dir}"
}
# _restore_snapshot <snap_dir>
# Validates snapshot integrity, then restores .env files, compose overlays,
# and per-extension config dirs. Does NOT restart services.
_restore_snapshot() (
local snap_dir="$1"
if [[ ! -d "$snap_dir" ]]; then
log_error "Rollback snapshot not found: ${snap_dir}"
return 1
fi
# Integrity: snapshot.json must exist and be valid JSON
if [[ ! -f "${snap_dir}/snapshot.json" ]]; then
log_error "Snapshot is missing snapshot.json; cannot verify integrity: ${snap_dir}"
return 1
fi
if ! jq empty "${snap_dir}/snapshot.json"; then
log_error "snapshot.json is not valid JSON; snapshot may be corrupt: ${snap_dir}"
return 1
fi
# Warn about absent critical files (non-fatal — install may not have had them)
for required in ".env" ".version"; do
if [[ ! -f "${snap_dir}/${required}" ]]; then
log_warn "Snapshot is missing ${required} — snapshot may be incomplete."
fi
done
log_info "Restoring from rollback snapshot: $(basename "${snap_dir}")"
# A subshell owns shell options and traps even when callers use `if !`.
# Stage every item before touching live files; keep displaced originals
# beside their destination so all publication/rollback renames stay local.
local -a sources=() destinations=() workspaces=() publishing=()
local f base ext_dir parent workspace i completed=false recovery_failed=false
shopt -s dotglob nullglob
for f in "${snap_dir}"/*; do
base="$(basename "$f")"
[[ -f "$f" && "$base" != snapshot.json && "$base" != metadata.json ]] || continue
sources+=("$f")
destinations+=("${INSTALL_DIR}/${base}")
done
# config-openclaw exists only in snapshots taken before the legacy OpenClaw
# extension was removed. Restoring it keeps a rollback across the removal
# faithful to what that snapshot captured; newer snapshots never contain it.
for ext_dir in litellm n8n openclaw searxng; do
f="${snap_dir}/config-${ext_dir}"
[[ -d "$f" ]] || continue
sources+=("$f")
destinations+=("${INSTALL_DIR}/config/${ext_dir}")
done
restore_cleanup() {
local status=$? index target work
trap - EXIT INT TERM
if [[ "$completed" != true ]]; then
for ((index=${#workspaces[@]}-1; index>=0; index--)); do
target="${destinations[index]}"
work="${workspaces[index]}"
if [[ "${publishing[index]:-false}" == true && ! -e "$work/new" && ! -L "$work/new"
&& ( -e "$target" || -L "$target" ) ]]; then
if ! mv -- "$target" "$work/new"; then
recovery_failed=true
log_error "Cannot withdraw restored item ${target}; recovery files retained at ${work}"
continue
fi
fi
if [[ -e "$work/old" || -L "$work/old" ]]; then
if ! mv -- "$work/old" "$target"; then
recovery_failed=true
log_error "Cannot restore original ${target}; original retained at ${work}/old"
continue
fi
fi
done
fi
for ((index=0; index<${#workspaces[@]}; index++)); do
# If recovery failed, never remove a workspace containing originals.
if [[ "$completed" == true || ( ! -e "${workspaces[index]}/old" && ! -L "${workspaces[index]}/old" ) ]]; then
rm -rf -- "${workspaces[index]}" || log_warn "Could not remove staging ${workspaces[index]}"
fi
done
if [[ "$recovery_failed" == true ]]; then
log_error "Rollback could not restore every original. Manual recovery required from the retained paths above."
fi
[[ "$completed" == true && "$status" == 0 ]] || status=1
exit "$status"
}
trap restore_cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
for ((i=0; i<${#sources[@]}; i++)); do
parent="$(dirname "${destinations[i]}")"
if ! mkdir -p -- "$parent"; then
log_error "Cannot prepare restore destination ${parent}"
return 1
fi
workspace="$(mktemp -d "${parent}/.ods-restore.XXXXXX")" || return 1
workspaces+=("$workspace")
# cp -a preserves private .env modes, links and directory attributes.
if ! cp -a -- "${sources[i]}" "$workspace/new"; then
log_error "Failed to stage ${sources[i]}; live configuration is unchanged."
return 1
fi
done
for ((i=0; i<${#destinations[@]}; i++)); do
f="${destinations[i]}"
workspace="${workspaces[i]}"
publishing[i]=true
if [[ -e "$f" || -L "$f" ]]; then
if ! mv -- "$f" "$workspace/old"; then
log_error "Cannot preserve original ${f}; undoing restore."
return 1
fi
fi
if ! mv -- "$workspace/new" "$f"; then
log_error "Cannot activate restored ${f}; undoing restore."
return 1
fi
done
completed=true
for f in "${destinations[@]}"; do
if [[ -d "$f" ]]; then
log_info " Restored: ${f#"${INSTALL_DIR}/"}/"
else
log_info " Restored: ${f#"${INSTALL_DIR}/"}"
fi
done
log_ok "Snapshot restored."
)
# wait_for_healthy
# Polls cmd_health every 10 s until it passes or HEALTH_TIMEOUT expires.
# Health output is captured to a temp log; shown in full only on timeout.
# Returns 0 on success, 1 on timeout.
wait_for_healthy() {
local deadline=$(( SECONDS + HEALTH_TIMEOUT ))
local attempt=0
local delay=10
local health_log
health_log=$(mktemp "${TMPDIR:-/tmp}/ods-health-XXXXXX.log")
log_info "Waiting for services (timeout: ${HEALTH_TIMEOUT}s)..."
while (( SECONDS < deadline )); do
attempt=$(( attempt + 1 ))
if cmd_health > "$health_log" 2>&1; then
log_ok "Services healthy after ${attempt} attempt(s)."
rm -f "$health_log"
return 0
fi
local remaining=$(( deadline - SECONDS ))
if (( remaining > delay )); then
log_info " Not yet healthy — retrying in ${delay}s (${remaining}s remaining)..."
sleep "$delay"
elif (( remaining > 0 )); then
sleep "$remaining"
fi
done
log_error "Health-check timeout after ${HEALTH_TIMEOUT}s. Final status:"
cat "$health_log"
rm -f "$health_log"
return 1
}
# Shared native identity check also covers the prospective snapshot selection.
# This is a refusal boundary, not a source/image/runtime rollback transaction.
_native_rollback_preflight() {
local snapshot="$1" helper="${INSTALL_DIR}/scripts/source-update-preflight.py"
if [[ ! -f "$helper" ]] || ! command -v python3 >/dev/null 2>&1; then
log_error "Rollback safety helper or Python 3 is unavailable; no configuration or services were changed."
return 1
fi
python3 "$helper" rollback --install-dir "$INSTALL_DIR" --snapshot "$snapshot"
}
# _update_rollback <reason> <snap_dir> [compose_flags]
# Restores the given snapshot and restarts services.
# Called when cmd_update encounters a non-zero exit at any step.
_update_rollback() {
local reason="$1"
local snap_dir_arg="$2"
local compose_flags_arg="${3:-}"
log_error "${reason}"
if ! _native_rollback_preflight "$snap_dir_arg"; then
log_error "Automatic rollback refused before configuration or service changes; keep the retained snapshot for reviewed recovery."
return 1
fi
log_warn "Auto-restoring rollback snapshot and restarting services..."
if ! _restore_snapshot "$snap_dir_arg"; then
log_error "CRITICAL: Snapshot restore failed. Manual recovery required."
log_error " Snapshot : ${snap_dir_arg}"
log_error " Steps :"
log_error " 1. cp \"${snap_dir_arg}/.env\" \"${INSTALL_DIR}/.env\""
log_error " 2. cd \"${INSTALL_DIR}\" && ./ods-cli start"
return 1
fi
local -a rollback_compose_args=()
if [[ -n "$compose_flags_arg" ]] && ! compose_flags_files_exist "$compose_flags_arg"; then
# Rollback restores configuration, not git, so the update may have
# deleted Compose files these flags name. Restart the stack the
# current tree resolves to instead.
log_warn "Compose flags name files that no longer exist; resolving the stack again."
if ! compose_flags_arg="$(resolve_compose_flags)"; then
compose_flags_arg=""
fi
fi
if ! compose_flags_parse "$compose_flags_arg"; then
log_error "Cannot restart rollback with malformed compose flags."
return 1
fi
rollback_compose_args=("${COMPOSE_PARSED_ARGS[@]}")
cd "$INSTALL_DIR"
if [[ -n "${compose_flags_arg}" ]]; then
if ! docker compose "${rollback_compose_args[@]}" down --remove-orphans; then
log_warn "docker compose v2 down failed, trying v1..."
docker-compose "${rollback_compose_args[@]}" down --remove-orphans
fi
if ! docker compose "${rollback_compose_args[@]}" up -d; then
log_warn "docker compose v2 up failed, trying v1..."
docker-compose "${rollback_compose_args[@]}" up -d
fi
else
if ! docker compose down --remove-orphans; then
log_warn "docker compose v2 down failed, trying v1..."
docker-compose down --remove-orphans
fi
if ! docker compose up -d; then
log_warn "docker compose v2 up failed, trying v1..."
docker-compose up -d
fi
fi
log_warn "Rollback complete. Run 'ods-update.sh health' to verify."
}
#==============================================================================
# COMMAND: CHECK
#==============================================================================
cmd_check() {
log_info "Checking for updates..."
local current_version
current_version=$(get_current_version)
log_info "Current version: ${current_version}"
# Fetch latest release from GitHub
local api_url="https://api.github.com/repos/${GITHUB_REPO}/releases/latest"
local response fetched=true
# A header file keeps the token out of argv, which any local user can read.
if [[ -n "${GITHUB_TOKEN:-}" ]]; then
response=$(curl -sf --max-time 15 -H @<(printf 'Authorization: Bearer %s\n' "$GITHUB_TOKEN") \
"${api_url}" 2>/dev/null) || fetched=false
else
response=$(curl -sf --max-time 15 "${api_url}" 2>/dev/null) || fetched=false
fi
if [[ "$fetched" != true ]]; then
log_error "Failed to check for updates. Check network or GITHUB_TOKEN."
return 1
fi
local latest_version
latest_version=$(echo "$response" | jq -r '.tag_name // empty')
if [[ -z "$latest_version" ]]; then
log_warn "No releases found on GitHub. You may be on a development version."
return 0
fi
log_info "Latest version: ${latest_version}"
# Compare versions
set +e
semver_compare "$current_version" "$latest_version"
local cmp_result=$?
set -e
case $cmp_result in
0)
log_ok "You are on the latest version."
;;
1)
log_warn "You are ahead of the latest release (development version)."
;;
2)
log_info "Update available: ${current_version} → ${latest_version}"
echo ""
echo "Run 'ods update' or './ods-cli update' for normal runtime updates."
if is_git_checkout; then
echo "Source checkout detected: run 'ods-update.sh update' only when you intend to pull source code."
fi
;;
esac
# Update last check timestamp
mkdir -p "$(dirname "$VERSION_FILE")"
local version_data
if [[ -f "$VERSION_FILE" ]]; then
version_data=$(cat "$VERSION_FILE")
else
version_data='{}'
fi
local tmp_version_file
tmp_version_file=$(mktemp "${VERSION_FILE}.tmp.XXXXXX")
echo "$version_data" | jq --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" '.last_check = $ts' > "$tmp_version_file"
mv -f "$tmp_version_file" "$VERSION_FILE"
}
#==============================================================================
# COMMAND: STATUS
#==============================================================================
cmd_status() {
echo "ODS Status"
echo "==================="
echo ""
echo "Version: $(get_current_version)"
echo "Install path: ${INSTALL_DIR}"
echo "Backup path: ${BACKUP_DIR}"
echo "Update channel: ${UPDATE_CHANNEL}"
echo ""
if [[ -f "$VERSION_FILE" ]]; then
local last_check
last_check=$(jq -r '.last_check // "never"' "$VERSION_FILE" 2>/dev/null || echo "never")
local last_update
last_update=$(jq -r '.last_update // "never"' "$VERSION_FILE" 2>/dev/null || echo "never")
echo "Last check: ${last_check}"
echo "Last update: ${last_update}"
else
echo "Last check: never"
echo "Last update: never"
fi
echo ""
# Count rollback snapshots
local snap_count=0
if [[ -d "$ROLLBACK_DIR" ]]; then
snap_count=$(find "$ROLLBACK_DIR" -maxdepth 1 -type d -name "pre-update-*" 2>/dev/null | wc -l)
fi
echo "Rollback snaps: ${snap_count} (max: ${MAX_BACKUPS}, path: ${ROLLBACK_DIR})"
# Show last rollback point recorded in version file
if [[ -f "$VERSION_FILE" ]]; then
local last_snap
last_snap=$(jq -r '.last_rollback_point // "none"' "$VERSION_FILE" 2>/dev/null || echo "none")
echo "Last snap path: ${last_snap}"
fi
echo ""
# Count general backups
if [[ -d "$BACKUP_DIR" ]]; then
local backup_count
backup_count=$(find "$BACKUP_DIR" -maxdepth 1 -type d -name "backup-*" 2>/dev/null | wc -l)
echo "General backups: ${backup_count} (max: ${MAX_BACKUPS}, path: ${BACKUP_DIR})"
else
echo "General backups: 0 (max: ${MAX_BACKUPS})"
fi
}
#==============================================================================
# COMMAND: BACKUP
#==============================================================================
cmd_backup() (
local backup_name="${1:-}"
_require_positive_backup_retention || return 1
command -v python3 >/dev/null 2>&1 || { log_error "Python 3 is required to publish a backup safely."; return 1; }
if [[ "$backup_name" == */* || "$backup_name" == *\\* || "$backup_name" =~ [[:cntrl:]] ]]; then
log_error "Invalid backup name. Path separators and control characters are not allowed."
return 1
fi
local timestamp
timestamp=$(date +%Y%m%d-%H%M%S)
local backup_id="backup-${timestamp}"
if [[ -n "$backup_name" ]]; then
backup_id="backup-${backup_name}-${timestamp}"
fi
local backup_path="${BACKUP_DIR}/${backup_id}"
log_info "Creating backup: ${backup_id}"
local lock_path="${BACKUP_DIR}/.${backup_id}.lock" staging_path="" publication_started=false
mkdir -p "$BACKUP_DIR"
if ! mkdir -m 700 "$lock_path"; then
log_error "Backup already in progress: ${backup_id}"
return 1
fi
trap '[[ -z "$staging_path" || "$publication_started" == true ]] || rm -rf -- "$staging_path"; rmdir -- "$lock_path"' EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
if [[ -e "$backup_path" || -L "$backup_path" ]]; then
log_error "Backup already exists: ${backup_id}"
return 1
fi
# Rollback discovery must never see a partially copied configuration.
# mktemp keeps raw environment and config private until publication.
staging_path=$(mktemp -d "${BACKUP_DIR}/.${backup_id}.tmp.XXXXXX")
# Backup compose files
# NB: x=$((x + 1)) not ((x++)) — the post-increment form evaluates to 0
# on the first increment, which set -e treats as failure and aborts the
# backup after copying a single file.
local files_backed_up=0
for pattern in "docker-compose*.yml" "docker-compose*.yaml" ".env" ".env.*"; do
for file in "${INSTALL_DIR}"/${pattern}; do
if [[ -f "$file" ]]; then
cp "$file" "$staging_path/"
files_backed_up=$((files_backed_up + 1))
fi
done
done
# Cached compose flags — records which overlays were active, so rollback
# can bring the restored stack up with the same file selection (same set
# snapshot_pre_update captures).
if [[ -f "${INSTALL_DIR}/.compose-flags" ]]; then
cp "${INSTALL_DIR}/.compose-flags" "$staging_path/"
files_backed_up=$((files_backed_up + 1))
fi
# Per-extension config directories — the same set snapshot_pre_update
# captures. `ods update` delegates its pre-update snapshot to this
# command; without config-* entries a rollback cannot restore litellm,
# n8n, or searxng configuration.
for ext_dir in litellm n8n searxng; do
local src="${INSTALL_DIR}/config/${ext_dir}"
if [[ -d "$src" ]]; then
cp -r "$src" "${staging_path}/config-${ext_dir}"
files_backed_up=$((files_backed_up + 1))
fi
done
# Backup version file
if [[ -f "$VERSION_FILE" ]]; then
cp "$VERSION_FILE" "$staging_path/.version"
files_backed_up=$((files_backed_up + 1))
fi
# Generate metadata (use jq for safe JSON construction)
jq -n \
--arg bid "$backup_id" \
--arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
--arg ver "$(get_current_version)" \
--argjson fc "$files_backed_up" \
--arg dir "$INSTALL_DIR" \
'{backup_id: $bid, timestamp: $ts, version: $ver, files_count: $fc, install_dir: $dir}' \
> "$staging_path/metadata.json"
# snapshot.json routes restores through the transactional
# _restore_snapshot path, which knows how t
10338
o put config-* directories
# back; the legacy flat-file restore used for metadata.json-only backups
# would silently drop them.
jq -n \
--arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
--arg ver "$(get_current_version)" \
--argjson fc "$files_backed_up" \
--arg dir "$INSTALL_DIR" \
'{type:"backup", timestamp:$ts, version:$ver, files_count:$fc, install_dir:$dir}' \
> "$staging_path/snapshot.json"
jq empty "$staging_path/metadata.json" "$staging_path/snapshot.json"
# Ordinary mv can nest the snapshot inside a destination created after the
# initial check. Preserve both names if exclusive publication is refused or
# interrupted; never discard potentially recoverable bytes after this point.
publication_started=true
if ! python3 -I "${SCRIPT_DIR}/scripts/publish-update-backup.py" "$staging_path" "$backup_path"; then
log_error "Backup publication was not confirmed. Inspect preserved staging '$staging_path' and destination '$backup_path'; no retention cleanup was run."
return 1
fi
staging_path=""
log_ok "Backup created: ${backup_path}"
log_info "Files backed up: ${files_backed_up}"
# Bash's glob preserves whole paths, including spaces/newlines, without
# requiring GNU sort -z on macOS. Never follow backup symlinks.
# Order by the creation timestamp this function appends to every name, not
# by the whole name: a labelled "backup-dashboard-<ts>" sorts after every
# unlabelled "backup-<ts>", which would prune the backup just created.
# Only the fixed-width timestamps and array indexes are sorted.
local backup_dirs=() dir index stamp count=0 order=""
local stamp_re='-([0-9]{8}-[0-9]{6})$'
for dir in "$BACKUP_DIR"/backup-*; do
[[ -d "$dir" && ! -L "$dir" ]] || continue
[[ "$dir" =~ $stamp_re ]] || continue
order+="${BASH_REMATCH[1]} ${#backup_dirs[@]}"$'\n'
backup_dirs+=("$dir")
done
while read -r stamp index; do
dir="${backup_dirs[$index]}"
count=$((count + 1))
if ((count > MAX_BACKUPS)); then
log_info "Removing old backup: $(basename "$dir")"
rm -rf "$dir"
fi
done < <(printf '%s' "$order" | LC_ALL=C sort -r)
)
#==============================================================================
# COMMAND: UPDATE
#==============================================================================
cmd_update() {
log_info "Starting ODS update..."
local current_version
current_version=$(get_current_version)
if ! ensure_source_checkout_for_update; then
return 1
fi
# Verify the runtime/source transition before snapshots or git mutation.
# These guards do not affect the image-only `ods update` command.
local preflight="${INSTALL_DIR}/scripts/source-update-preflight.py"
if [[ ! -f "$preflight" ]] || ! command -v python3 >/dev/null 2>&1; then
log_error "Source update safety helper or Python 3 is unavailable; no files were changed."
return 1
fi
if ! python3 "$preflight" native --install-dir "$INSTALL_DIR"; then
return 1
fi
local compose_flags=""
compose_flags=$(resolve_compose_flags 2>/dev/null || true)
local -a compose_args=()
if ! compose_flags_parse "$compose_flags"; then
log_error "Cannot update with malformed compose flags."
return 1
fi
compose_args=("${COMPOSE_PARSED_ARGS[@]}")
if [[ ${#compose_args[@]} -gt 0 ]]; then
if ! (cd "$INSTALL_DIR" && docker compose "${compose_args[@]}" config --format json) | python3 "$preflight" compose; then
log_error "Source update requires a verified image-only Compose stack and Compose v2 JSON configuration; no files were changed."
return 1
fi
else
log_error "Cannot verify the active Compose stack for a source update; no files were changed."
return 1
fi
# ── Step 1: rollback snapshot ─────────────────────────────────────────────
local timestamp
timestamp=$(date +%Y%m%d-%H%M%S)
local snap_dir
snap_dir=$(snapshot_pre_update "$timestamp")
# ── Step 2: pull latest changes ───────────────────────────────────────────
log_info "Pulling latest changes..."
cd "$INSTALL_DIR"
local update_branch
update_branch=$(git branch --show-current 2>/dev/null || true)
if [[ -z "$update_branch" ]]; then
_update_rollback "Cannot update a detached checkout safely. Check out a branch first." \
"$snap_dir" "$compose_flags"
return 1
fi
git fetch origin
if ! git pull --ff-only origin "$update_branch"; then
_update_rollback "Git pull failed." "$snap_dir" "$compose_flags"
return 1
fi
# ── Step 3: migrations ────────────────────────────────────────────────────
local migrations_dir="${INSTALL_DIR}/migrations"
if [[ -d "$migrations_dir" ]]; then
log_info "Running migrations..."
for migration in "$migrations_dir"/migrate-v*.sh; do
if [[ -f "$migration" && -x "$migration" ]]; then
log_info "Running: $(basename "$migration")"
if ! bash "$migration"; then
_update_rollback "Migration failed: $(basename "$migration")." \
"$snap_dir" "$compose_flags"
return 1
fi
fi
done
fi
# The pull and the migrations can delete Compose files that the pre-pull
# flags name, for example a removed bundled service. Resolve the stack
# again so the restart uses the updated tree, and so `down
# --remove-orphans` removes containers whose service is gone.
if ! compose_flags_files_exist "$compose_flags"; then
log_warn "The update removed Compose files the running stack used; resolving the stack again."
local updated_compose_flags=""
if ! updated_compose_flags="$(resolve_compose_flags)"; then
updated_compose_flags=""
fi
if ! compose_flags_parse "$updated_compose_flags"; then
_update_rollback "Cannot restart with malformed compose flags after the update." \
"$snap_dir" "$compose_flags"
return 1
fi
compose_flags="$updated_compose_flags"
compose_args=("${COMPOSE_PARSED_ARGS[@]}")
fi
# ── Step 4: restart services ──────────────────────────────────────────────
log_info "Restarting services..."
cd "$INSTALL_DIR"
if [[ -n "${compose_flags}" ]]; then
if ! docker compose "${compose_args[@]}" down --remove-orphans; then
log_warn "docker compose v2 down failed, trying v1..."
docker-compose "${compose_args[@]}" down --remove-orphans
fi
if ! docker compose "${compose_args[@]}" up -d; then
log_warn "docker compose v2 up failed, trying v1..."
if ! docker-compose "${compose_args[@]}" up -d; then
_update_rollback "Both Docker Compose v2 and v1 failed to restart services." \
"$snap_dir" "$compose_flags"
return 1
fi
fi
elif [[ -f "${INSTALL_DIR}/docker-compose.yml" ]]; then
if ! docker compose down --remove-orphans; then
log_warn "docker compose v2 down failed, trying v1..."
docker-compose down --remove-orphans
fi
if ! docker compose up -d; then
log_warn "docker compose v2 up failed, trying v1..."
if ! docker-compose up -d; then
_update_rollback "Both Docker Compose v2 and v1 failed to restart services." \
"$snap_dir" "$compose_flags"
return 1
fi
fi
else
log_warn "No compose files found. Skipping container restart."
fi
# ── Step 5: health-check with timeout ────────────────────────────────────
if ! wait_for_healthy; then
_update_rollback \
"Services failed to become healthy after update (timeout: ${HEALTH_TIMEOUT}s)." \
"$snap_dir" "$compose_flags"
return 1
fi
# ── Step 6: record new version ────────────────────────────────────────────
local new_version
new_version=$(git describe --tags 2>/dev/null || git rev-parse --short HEAD)
local version_data='{}'
[[ -f "$VERSION_FILE" ]] && version_data=$(cat "$VERSION_FILE")
local tmp_version_file
tmp_version_file=$(mktemp "${VERSION_FILE}.tmp.XXXXXX")
echo "$version_data" | jq \
--arg v "$new_version" \
--arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
You can’t perform that action at this time.