-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathupgrade.sh
More file actions
executable file
·1603 lines (1346 loc) · 60.6 KB
/
upgrade.sh
File metadata and controls
executable file
·1603 lines (1346 loc) · 60.6 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
#
# Copyright (c) 2023-2025 Bito Inc.
# All rights reserved.
#
# This source code is proprietary and confidential to Bito Inc.
# Unauthorized copying, modification, distribution, or use is strictly prohibited.
#
# For licensing information, see the COPYRIGHT file in the root directory.
#
# @company Bito Inc.
# @website https://bito.ai
#
# Bito AI Architect Blue/Green Upgrade Script
# Standalone script - no external dependencies required
set -e
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
NC='\033[0m'
# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
OLD_DIR=""
CUSTOM_OLD_PATH=""
PARENT_DIR=""
TEMP_DOWNLOAD_DIR="/tmp/bito-upgrade-$$"
TARGET_VERSION=""
CUSTOM_URL=""
DOWNLOAD_BASE_URL="${UPGRADE_DOWNLOAD_URL:-https://aiarch.bito.ai}"
LOG_FILE="/tmp/bito-upgrade-$$.log"
# Global variables
NEW_DIR=""
NEW_ENV=""
OLD_ENV=""
UPGRADE_MODE="" # Will be set to "embedded", "standalone", or "kubernetes"
CURRENT_VERSION=""
DOCKER_COMPOSE_CMD=""
DEPLOYMENT_TYPE="docker-compose" # Will be set to "kubernetes" if detected
# Print functions
msg_success() { echo -e "${GREEN}✓${NC} $1" | tee -a "$LOG_FILE"; }
msg_error() { echo -e "${RED}✗${NC} $1" | tee -a "$LOG_FILE"; }
msg_info() { echo -e "${BLUE}ℹ${NC} $1" | tee -a "$LOG_FILE"; }
msg_warn() { echo -e "${YELLOW}⚠${NC} $1" | tee -a "$LOG_FILE"; }
print_header() {
echo "" | tee -a "$LOG_FILE"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}" | tee -a "$LOG_FILE"
echo -e "${BLUE}$1${NC}" | tee -a "$LOG_FILE"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}" | tee -a "$LOG_FILE"
echo "" | tee -a "$LOG_FILE"
}
log_silent() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}
# Detect docker compose command
detect_docker_compose() {
if docker compose version >/dev/null 2>&1; then
echo "docker compose"
elif docker-compose --version >/dev/null 2>&1; then
echo "docker-compose"
else
return 1
fi
}
# Detect current installation version
detect_current_version() {
local install_dir="$1"
local versions_file="${install_dir}/versions/service-versions.json"
if [[ -f "$versions_file" ]]; then
# Try with jq first
if command -v jq >/dev/null 2>&1; then
CURRENT_VERSION=$(jq -r '.platform_info.version // "unknown"' "$versions_file" 2>/dev/null || echo "unknown")
else
# Fallback to grep/cut
CURRENT_VERSION=$(grep -m1 '"version":' "$versions_file" 2>/dev/null | cut -d'"' -f4 || echo "unknown")
fi
log_silent "Detected current version: $CURRENT_VERSION"
return 0
else
CURRENT_VERSION="unknown"
log_silent "No versions file found, version unknown"
return 1
fi
}
# Show usage
show_usage() {
cat << EOF
Bito AI Architect Blue/Green Upgrade Script (Unified)
Usage: $0 [options]
Auto-detects version and uses appropriate upgrade method:
• Version 1.0.0: Uses direct docker compose commands
• Version >1.0.0: Uses setup.sh with --from-existing-config
Options:
--old-path=PATH Path to existing installation (required if not run from within installation)
--version=VERSION Upgrade to specific version (e.g., 1.1.0, 2.0.0)
--url=URL Upgrade from custom tarball URL
--help Show this help message
Examples:
# From within installation directory (auto-detect):
cd /path/to/installation
./scripts/upgrade.sh --version=2.0.0
# From independent directory:
./upgrade.sh --old-path=/path/to/installation --version=2.0.0
# From custom URL:
./upgrade.sh --old-path=/path/to/installation --url=file:///path/to/package.tar.gz
Features:
• Zero downtime (blue/green deployment)
• Data preservation (MySQL, volumes, configs)
• Automatic version detection and method selection
• Works with all versions (1.0.0 and newer)
EOF
}
# Detect deployment type
detect_deployment_type() {
# Check multiple locations for .deployment-type file
# For 1.4.x+: file is in /usr/local or ~/.local (standard paths)
# For older versions (1.3.x): file is in OLD_DIR
local deployment_type_file=""
if [[ -f "${OLD_DIR}/.deployment-type" ]] && [[ ! -L "${OLD_DIR}/.deployment-type" ]]; then
# Regular file in OLD_DIR (1.3.x or older)
deployment_type_file="${OLD_DIR}/.deployment-type"
log_silent "Found .deployment-type in OLD_DIR (regular file)"
elif [[ -f "/usr/local/etc/bitoarch/.deployment-type" ]]; then
deployment_type_file="/usr/local/etc/bitoarch/.deployment-type"
log_silent "Found .deployment-type in /usr/local/etc/bitoarch"
elif [[ -f "${HOME}/.local/bitoarch/etc/.deployment-type" ]]; then
deployment_type_file="${HOME}/.local/bitoarch/etc/.deployment-type"
log_silent "Found .deployment-type in ~/.local/bitoarch/etc"
fi
if [[ -n "$deployment_type_file" ]]; then
DEPLOYMENT_TYPE=$(cat "$deployment_type_file")
msg_info "Detected deployment type: $DEPLOYMENT_TYPE"
log_silent "Deployment type from $deployment_type_file: $DEPLOYMENT_TYPE"
else
DEPLOYMENT_TYPE="docker-compose"
msg_info "No deployment type marker found, assuming: docker-compose"
log_silent "Defaulting to docker deployment type"
fi
}
# Parse arguments
parse_args() {
TARGET_VERSION="latest"
while [[ $# -gt 0 ]]; do
case $1 in
--old-path=*)
CUSTOM_OLD_PATH="${1#--old-path=}"
shift
;;
--version=*)
TARGET_VERSION="${1#--version=}"
shift
;;
--url=*)
CUSTOM_URL="${1#--url=}"
shift
;;
--help|-h)
show_usage
exit 0
;;
*)
msg_error "Unknown option: $1"
show_usage
exit 1
;;
esac
done
# Determine OLD_DIR
if [[ -n "$CUSTOM_OLD_PATH" ]]; then
# User provided --old-path (expand tilde if present)
OLD_DIR="${CUSTOM_OLD_PATH/#\~/$HOME}"
msg_info "Using provided installation path: $OLD_DIR"
else
# Try to detect from script location
OLD_DIR="$(dirname "$SCRIPT_DIR")"
# Check if this looks like an installation directory
if [[ ! -f "${OLD_DIR}/.env-bitoarch" ]]; then
# Not run from within installation, prompt for path
echo ""
msg_warn "Script is not running from within an installation directory"
msg_info "Please provide the path to your existing installation"
echo ""
read -p "Enter path to existing installation: " OLD_DIR
if [[ -z "$OLD_DIR" ]] || [[ ! -d "$OLD_DIR" ]]; then
msg_error "Invalid installation path"
exit 1
fi
if [[ ! -f "${OLD_DIR}/.env-bitoarch" ]]; then
msg_error "Not a valid installation directory (missing .env-bitoarch)"
exit 1
fi
fi
fi
PARENT_DIR="$(dirname "$OLD_DIR")"
OLD_ENV="${OLD_DIR}/.env-bitoarch"
# Detect deployment type first
detect_deployment_type
# Detect current version and determine upgrade mode
detect_current_version "$OLD_DIR"
# Determine upgrade mode based on deployment type and version
if [[ "$DEPLOYMENT_TYPE" == "kubernetes" ]]; then
UPGRADE_MODE="kubernetes"
msg_info "Using Kubernetes upgrade mode (helm upgrade)"
elif [[ "$CURRENT_VERSION" == "1.0.0" ]]; then
UPGRADE_MODE="standalone"
msg_info "Detected version 1.0.0 - using standalone mode (direct docker compose)"
elif [[ "$CURRENT_VERSION" == "unknown" ]]; then
UPGRADE_MODE="embedded"
msg_warn "Version unknown - defaulting to embedded mode (setup.sh)"
else
UPGRADE_MODE="embedded"
msg_info "Detected version $CURRENT_VERSION - using embedded mode (setup.sh)"
fi
log_silent "Upgrade mode: $UPGRADE_MODE"
if [[ -n "$CUSTOM_URL" ]] && [[ "$TARGET_VERSION" != "latest" ]]; then
msg_error "Cannot use both --url and --version"
exit 1
fi
}
# Check prerequisites
check_prerequisites() {
msg_info "Checking system requirements..."
local missing=()
for tool in curl tar jq; do
if ! command -v "$tool" >/dev/null 2>&1; then
missing+=("$tool")
fi
done
if [[ ${#missing[@]} -gt 0 ]]; then
msg_error "Missing required tools: ${missing[*]}"
msg_info "Install them:"
msg_info " macOS: brew install ${missing[*]}"
msg_info " Ubuntu: apt-get install ${missing[*]}"
exit 1
fi
# Kubernetes-specific prerequisites
if [[ "$UPGRADE_MODE" == "kubernetes" ]]; then
msg_info "Checking Kubernetes prerequisites..."
# Check kubectl
if ! command -v kubectl >/dev/null 2>&1; then
msg_error "kubectl not found (required for Kubernetes deployment)"
msg_info "Install kubectl:"
msg_info " macOS: brew install kubectl"
msg_info " Ubuntu: sudo apt-get install -y kubectl"
exit 1
fi
# Check helm
if ! command -v helm >/dev/null 2>&1; then
msg_error "Helm not found (required for Kubernetes deployment)"
msg_info "Install Helm:"
msg_info " macOS: brew install helm"
msg_info " Ubuntu: curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash"
exit 1
fi
# Check kubectl connectivity
if ! kubectl cluster-info >/dev/null 2>&1; then
msg_error "Cannot connect to Kubernetes cluster"
msg_info "Please ensure kubectl is configured correctly"
exit 1
fi
log_silent "Kubernetes prerequisites verified: kubectl and helm found"
msg_success "Kubernetes prerequisites verified"
else
# Docker prerequisites for non-K8s deployments
if ! docker info >/dev/null 2>&1; then
msg_error "Docker is not running"
exit 1
fi
# Detect docker compose command for standalone mode
if [[ "$UPGRADE_MODE" == "standalone" ]]; then
DOCKER_COMPOSE_CMD=$(detect_docker_compose)
if [[ -z "$DOCKER_COMPOSE_CMD" ]]; then
msg_error "Docker Compose not found (tried 'docker compose' and 'docker-compose')"
exit 1
fi
log_silent "Using docker compose command: $DOCKER_COMPOSE_CMD"
fi
fi
msg_success "System requirements verified"
}
# Verify old installation
verify_old_installation() {
msg_info "Verifying existing installation..."
if [[ ! -d "$OLD_DIR" ]]; then
msg_error "Old installation not found: $OLD_DIR"
exit 1
fi
# Check for config files in multiple locations
# For 1.4.x+: files might be in /usr/local or ~/.local (standard paths)
# For older versions (1.3.x): files are in OLD_DIR
local config_found=false
if [[ -f "${OLD_DIR}/.env-bitoarch" ]] && [[ ! -L "${OLD_DIR}/.env-bitoarch" ]]; then
# Regular file in OLD_DIR (1.3.x or older)
config_found=true
log_silent "Config found in OLD_DIR (regular file)"
elif [[ -f "/usr/local/etc/bitoarch/.env-bitoarch" ]]; then
config_found=true
log_silent "Config found in /usr/local/etc/bitoarch"
elif [[ -f "${HOME}/.local/bitoarch/etc/.env-bitoarch" ]]; then
config_found=true
log_silent "Config found in ~/.local/bitoarch/etc"
elif [[ -L "${OLD_DIR}/.env-bitoarch" ]]; then
# Symlink in OLD_DIR - follow it to check actual file
if [[ -f "${OLD_DIR}/.env-bitoarch" ]]; then
config_found=true
log_silent "Config found via symlink in OLD_DIR"
fi
fi
if [[ "$config_found" == "false" ]]; then
msg_error "Configuration not found"
exit 1
fi
if [[ ! -f "${OLD_DIR}/setup.sh" ]]; then
msg_error "setup.sh not found in: $OLD_DIR"
exit 1
fi
msg_success "Existing installation verified"
}
# Download package
download_package() {
local version="$1"
local download_url="$2"
msg_info "Downloading version: ${version}" >&2
log_silent "Download URL: $download_url"
mkdir -p "$TEMP_DOWNLOAD_DIR"
local tarball_name=$(basename "$download_url")
local tarball_path="${TEMP_DOWNLOAD_DIR}/${tarball_name}"
# Download with proper error handling (disable set -e temporarily)
msg_info "Downloading from: $download_url" >&2
set +e
curl -# -L -f -o "$tarball_path" "$download_url" >&2
local curl_exit=$?
set -e
if [[ $curl_exit -ne 0 ]]; then
msg_error "Download failed from: $download_url" >&2
msg_error "Check URL accessibility and internet connection" >&2
msg_error "Curl exit code: $curl_exit" >&2
rm -rf "$TEMP_DOWNLOAD_DIR"
exit 1
fi
if [[ ! -f "$tarball_path" ]]; then
msg_error "Downloaded file not created" >&2
rm -rf "$TEMP_DOWNLOAD_DIR"
exit 1
fi
if [[ ! -s "$tarball_path" ]]; then
msg_error "Downloaded file is empty" >&2
rm -rf "$TEMP_DOWNLOAD_DIR"
exit 1
fi
local size_mb=$(du -m "$tarball_path" | cut -f1)
msg_success "Package downloaded (${size_mb}MB)" >&2
# Only output the path to stdout (everything else goes to stderr)
echo "$tarball_path"
}
# Extract package
extract_package() {
local tarball_path="$1"
local version="$2"
msg_info "Extracting package..."
local timestamp=$(date +%Y%m%d_%H%M%S)
NEW_DIR="${PARENT_DIR}/bito-ai-architect-${version}-${timestamp}"
mkdir -p "$NEW_DIR"
# Extract with strip-components=1 to remove the top-level directory from tarball
if ! tar -xzf "$tarball_path" --strip-components=1 -C "$NEW_DIR" 2>&1 | tee -a "$LOG_FILE" >/dev/null; then
msg_error "Extraction failed"
rm -rf "$NEW_DIR"
exit 1
fi
# Verify critical files exist
if [[ ! -f "${NEW_DIR}/setup.sh" ]]; then
msg_error "Invalid package (missing setup.sh)"
rm -rf "$NEW_DIR"
exit 1
fi
if [[ ! -f "${NEW_DIR}/bitoarch" ]]; then
msg_error "Invalid package (missing bitoarch)"
rm -rf "$NEW_DIR"
exit 1
fi
if [[ ! -d "${NEW_DIR}/scripts/lib" ]]; then
msg_error "Invalid package (missing scripts/lib directory)"
rm -rf "$NEW_DIR"
exit 1
fi
# Make scripts executable
chmod +x "${NEW_DIR}/setup.sh"
chmod +x "${NEW_DIR}/bitoarch"
[[ -f "${NEW_DIR}/scripts/upgrade.sh" ]] && chmod +x "${NEW_DIR}/scripts/upgrade.sh"
msg_success "Package extracted to: $NEW_DIR"
log_silent "Verified package structure (setup.sh, bitoarch, scripts/lib exist)"
}
# Merge new config keys from default env file into existing env file
# This ensures new configuration options added in newer versions are available
# with their default values while preserving user's existing configuration
merge_new_env_configs() {
local env_file="$1"
local default_env_file="${NEW_DIR}/.env-bitoarch.default"
if [[ ! -f "$default_env_file" ]]; then
log_silent "Skipping env config merge - default file not found: $default_env_file"
return 0
fi
if [[ ! -f "$env_file" ]]; then
log_silent "Skipping env config merge - env file not found: $env_file"
return 0
fi
log_silent "Checking for new configuration options in newer version..."
local new_keys_added=0
local temp_additions=$(mktemp)
# Read default env file line by line
while IFS= read -r line || [[ -n "$line" ]]; do
# Skip empty lines and comments
[[ -z "$line" ]] && continue
[[ "$line" =~ ^[[:space:]]*# ]] && continue
# Extract key from KEY=VALUE format
if [[ "$line" =~ ^([A-Za-z_][A-Za-z0-9_]*)= ]]; then
local key="${BASH_REMATCH[1]}"
# Check if this key already exists in the user's env file
if ! grep -q "^${key}=" "$env_file" 2>/dev/null; then
# Key doesn't exist - add it with default value
echo "$line" >> "$temp_additions"
new_keys_added=$((new_keys_added + 1))
log_silent "New config key found: $key"
fi
fi
done < "$default_env_file"
# If new keys were found, append them to the env file
if [[ $new_keys_added -gt 0 ]]; then
echo "" >> "$env_file"
echo "# ============================================================================" >> "$env_file"
echo "# NEW CONFIGURATION OPTIONS (added during upgrade from version ${CURRENT_VERSION:-unknown})" >> "$env_file"
echo "# Added on: $(date)" >> "$env_file"
echo "# ============================================================================" >> "$env_file"
cat "$temp_additions" >> "$env_file"
log_silent "Merged $new_keys_added new config keys from default to env file"
else
log_silent "No new config keys to merge - env file is up to date"
fi
rm -f "$temp_additions"
return 0
}
# Patch env file with IMAGE variables from new version
patch_env_with_images() {
local env_file="$1"
local versions_file="${NEW_DIR}/versions/service-versions.json"
# Check if IMAGE variables already exist
local images_exist=false
if grep -q "CIS_CONFIG_IMAGE=" "$env_file" 2>/dev/null; then
images_exist=true
log_silent "Updating IMAGE variables to new version..."
else
log_silent "Adding IMAGE variables from new version..."
fi
# Read versions and image bases from NEW version's versions/service-versions.json
local cis_config_version cis_config_image_base
local cis_manager_version cis_manager_image_base
local cis_provider_version cis_provider_image_base
local cis_tracker_version cis_tracker_image_base
local mysql_version mysql_image_base
if command -v jq >/dev/null 2>&1 && [[ -f "$versions_file" ]]; then
cis_config_version=$(jq -r '.services."cis-config".version' "$versions_file" 2>/dev/null || echo "latest")
cis_config_image_base=$(jq -r '.services."cis-config".image' "$versions_file" 2>/dev/null || echo "docker.io/bitoai/cis-config")
cis_manager_version=$(jq -r '.services."cis-manager".version' "$versions_file" 2>/dev/null || echo "latest")
cis_manager_image_base=$(jq -r '.services."cis-manager".image' "$versions_file" 2>/dev/null || echo "docker.io/bitoai/cis-manager")
cis_provider_version=$(jq -r '.services."cis-provider".version' "$versions_file" 2>/dev/null || echo "latest")
cis_provider_image_base=$(jq -r '.services."cis-provider".image' "$versions_file" 2>/dev/null || echo "docker.io/bitoai/xmcp")
cis_tracker_version=$(jq -r '.services."cis-tracker".version' "$versions_file" 2>/dev/null || echo "latest")
cis_tracker_image_base=$(jq -r '.services."cis-tracker".image' "$versions_file" 2>/dev/null || echo "docker.io/bitoai/cis-tracking")
mysql_version=$(jq -r '.services."mysql".version' "$versions_file" 2>/dev/null || echo "8.0")
mysql_image_base=$(jq -r '.services."mysql".image' "$versions_file" 2>/dev/null || echo "mysql")
else
# Fallback to defaults if jq not available or file missing
cis_config_version="latest"
cis_config_image_base="docker.io/bitoai/cis-config"
cis_manager_version="latest"
cis_manager_image_base="docker.io/bitoai/cis-manager"
cis_provider_version="latest"
cis_provider_image_base="docker.io/bitoai/xmcp"
cis_tracker_version="latest"
cis_tracker_image_base="docker.io/bitoai/cis-tracking"
mysql_version="8.0"
mysql_image_base="mysql"
fi
# Add or update IMAGE variables
if [ "$images_exist" = true ]; then
# Update existing IMAGE variables
sed -i.bak "s|^CIS_CONFIG_IMAGE=.*|CIS_CONFIG_IMAGE=${cis_config_image_base}:${cis_config_version}|" "$env_file"
sed -i.bak "s|^CIS_MANAGER_IMAGE=.*|CIS_MANAGER_IMAGE=${cis_manager_image_base}:${cis_manager_version}|" "$env_file"
sed -i.bak "s|^CIS_PROVIDER_IMAGE=.*|CIS_PROVIDER_IMAGE=${cis_provider_image_base}:${cis_provider_version}|" "$env_file"
sed -i.bak "s|^CIS_TRACKER_IMAGE=.*|CIS_TRACKER_IMAGE=${cis_tracker_image_base}:${cis_tracker_version}|" "$env_file"
sed -i.bak "s|^MYSQL_IMAGE=.*|MYSQL_IMAGE=${mysql_image_base}:${mysql_version}|" "$env_file"
else
# Append IMAGE variables to env file
cat >> "$env_file" << EOF
# Image variables (added during upgrade for compatibility with new version)
CIS_CONFIG_IMAGE=${cis_config_image_base}:${cis_config_version}
CIS_MANAGER_IMAGE=${cis_manager_image_base}:${cis_manager_version}
CIS_PROVIDER_IMAGE=${cis_provider_image_base}:${cis_provider_version}
CIS_TRACKER_IMAGE=${cis_tracker_image_base}:${cis_tracker_version}
MYSQL_IMAGE=${mysql_image_base}:${mysql_version}
EOF
fi
# Also update VERSION variables if they're empty
if grep -q "^CIS_CONFIG_VERSION=$" "$env_file" 2>/dev/null; then
sed -i.bak "s/^CIS_CONFIG_VERSION=$/CIS_CONFIG_VERSION=${cis_config_version}/" "$env_file"
fi
if grep -q "^CIS_MANAGER_VERSION=$" "$env_file" 2>/dev/null; then
sed -i.bak "s/^CIS_MANAGER_VERSION=$/CIS_MANAGER_VERSION=${cis_manager_version}/" "$env_file"
fi
if grep -q "^CIS_PROVIDER_VERSION=$" "$env_file" 2>/dev/null; then
sed -i.bak "s/^CIS_PROVIDER_VERSION=$/CIS_PROVIDER_VERSION=${cis_provider_version}/" "$env_file"
fi
if grep -q "^CIS_TRACKER_VERSION=$" "$env_file" 2>/dev/null; then
sed -i.bak "s/^CIS_TRACKER_VERSION=$/CIS_TRACKER_VERSION=${cis_tracker_version}/" "$env_file"
fi
# Clean up sed backup files
rm -f "${env_file}.bak"
log_silent "Env file patched with IMAGE variables from new version"
log_silent "Added IMAGE variables from new version: config=${cis_config_version}, manager=${cis_manager_version}, provider=${cis_provider_version}, tracker=${cis_tracker_version}, mysql=${mysql_version}"
}
# Migrate configuration
migrate_config() {
msg_info "Migrating configuration..."
# Backup old .env-bitoarch before migration
if [ -f "${OLD_DIR}/.env-bitoarch" ]; then
# Determine standard backup directory
local backup_var_dir
if [[ -d "/usr/local/var/bitoarch" ]] || [[ -w "/usr/local/var" ]]; then
backup_var_dir="/usr/local/var/bitoarch"
else
backup_var_dir="${HOME}/.local/bitoarch/var"
fi
local backup_dir="${backup_var_dir}/backups/configs/env"
local timestamp=$(date +%Y%m%d_%H%M%S)
local backup_file="${backup_dir}/.env-bitoarch.backup.${timestamp}"
# Create backup directory
mkdir -p "$backup_dir" 2>/dev/null || {
if command -v sudo >/dev/null 2>&1; then
sudo mkdir -p "$backup_dir"
sudo chown -R "$USER:$(id -gn)" "$backup_dir"
fi
}
# Create backup
if cp "${OLD_DIR}/.env-bitoarch" "$backup_file" 2>/dev/null; then
log_silent "Config backup saved to: $backup_file"
msg_info "Config backup: $backup_file"
else
msg_warn "Could not create config backup (non-critical)"
fi
# Rotate old backups (keep latest 5)
local retention=5
local backup_pattern="${backup_dir}/.env-bitoarch.backup.*"
local existing_backups=$(ls -t $backup_pattern 2>/dev/null | wc -l | tr -d ' ')
if [ "$existing_backups" -gt "$retention" ]; then
ls -t $backup_pattern 2>/dev/null | tail -n +$((retention + 1)) | xargs rm -f 2>/dev/null || true
log_silent "Rotated old backups (keeping latest ${retention})"
fi
fi
NEW_ENV="${NEW_DIR}/.env-bitoarch"
# Determine config source directory
# For 1.4.x+: configs are in /usr/local or ~/.local (standard paths)
# For older versions (1.3.x): configs are regular files in OLD_DIR
local config_source="$OLD_DIR"
if [[ -f "${OLD_DIR}/.env-bitoarch" ]] && [[ ! -L "${OLD_DIR}/.env-bitoarch" ]]; then
# Regular file in OLD_DIR (1.3.x or older) - use OLD_DIR
config_source="$OLD_DIR"
log_silent "Using config from OLD_DIR (regular file - 1.3.x installation)"
elif [[ -f "/usr/local/etc/bitoarch/.env-bitoarch" ]]; then
# 1.4.x+ installation with configs in /usr/local
config_source="/usr/local/etc/bitoarch"
log_silent "Using config from /usr/local/etc/bitoarch (1.4.x+ installation)"
elif [[ -f "${HOME}/.local/bitoarch/etc/.env-bitoarch" ]]; then
# 1.4.x+ installation with configs in ~/.local
config_source="${HOME}/.local/bitoarch/etc"
log_silent "Using config from ~/.local/bitoarch/etc (1.4.x+ installation)"
elif [[ -L "${OLD_DIR}/.env-bitoarch" ]] && [[ -f "${OLD_DIR}/.env-bitoarch" ]]; then
# Symlink in OLD_DIR that points to valid file - follow it
config_source="$OLD_DIR"
log_silent "Using config from OLD_DIR (symlink - 1.4.x+ installation)"
fi
log_silent "Config source: $config_source"
# Copy env files from detected source
[[ -f "${config_source}/.env-bitoarch" ]] && cp "${config_source}/.env-bitoarch" "${NEW_DIR}/.env-bitoarch"
[[ -f "${config_source}/.env-llm-bitoarch" ]] && cp "${config_source}/.env-llm-bitoarch" "${NEW_DIR}/.env-llm-bitoarch"
# Copy repo config
if [[ -f "${config_source}/.bitoarch-config.yaml" ]]; then
cp "${config_source}/.bitoarch-config.yaml" "${NEW_DIR}/.bitoarch-config.yaml"
fi
# Copy or create deployment type marker
if [[ -f "${config_source}/.deployment-type" ]]; then
cp "${config_source}/.deployment-type" "${NEW_DIR}/.deployment-type"
msg_info "Deployment type preserved: $(cat "${NEW_DIR}/.deployment-type")"
log_silent "Copied .deployment-type from $config_source"
else
# Old version without k8s support - default to docker-compose
echo "docker-compose" > "${NEW_DIR}/.deployment-type"
msg_info "Setting deployment type to: docker-compose (default for old versions)"
log_silent "Created .deployment-type with docker-compose for backward compatibility"
fi
# Merge new config keys from default env file (adds missing keys with default values)
if [[ -f "$NEW_ENV" ]]; then
merge_new_env_configs "$NEW_ENV"
fi
# Patch env file with IMAGE variables if missing (for old versions)
if [[ -f "$NEW_ENV" ]]; then
patch_env_with_images "$NEW_ENV"
fi
# Extract latest provider default.json from new package image
# This ensures the new version's config is used for both Docker and K8s
local deployment_type="docker-compose"
if [[ -f "${NEW_DIR}/.deployment-type" ]]; then
deployment_type=$(cat "${NEW_DIR}/.deployment-type")
fi
if [[ "$deployment_type" == "docker-compose" ]]; then
log_silent "Extracting latest provider configuration from new package..."
local docker_config_path="${NEW_DIR}/services/cis-provider/config/default.json"
# Source env to get provider image
if [[ -f "$NEW_ENV" ]]; then
source "$NEW_ENV"
local provider_image="${CIS_PROVIDER_IMAGE:-}"
if [[ -n "$provider_image" ]]; then
# Pull the image first
if docker pull "$provider_image" >> "$LOG_FILE" 2>&1; then
# Create temp container and extract config
if docker create --name temp-provider-config-upgrade "$provider_image" >/dev/null 2>&1; then
if docker cp temp-provider-config-upgrade:/opt/bito/xmcp/config/default.json "$docker_config_path" 2>> "$LOG_FILE"; then
chmod 666 "$docker_config_path" 2>/dev/null || true
log_silent "Provider configuration extracted from new image"
else
msg_warn "Could not extract provider config from image, using packaged config"
fi
docker rm temp-provider-config-upgrade >/dev/null 2>&1 || true
else
msg_warn "Could not create temp container for config extraction"
fi
else
msg_warn "Could not pull provider image for config extraction"
fi
fi
fi
else
# Kubernetes: extract latest default.json from image to helm chart path for ConfigMap
msg_info "Extracting latest provider configuration for Kubernetes deployment..."
local k8s_config_path="${NEW_DIR}/helm-bitoarch/services/cis-provider/config/default.json"
if [[ -f "$NEW_ENV" ]]; then
source "$NEW_ENV"
local provider_image="${CIS_PROVIDER_IMAGE:-}"
if [[ -n "$provider_image" ]]; then
if docker pull "$provider_image" >> "$LOG_FILE" 2>&1; then
if docker create --name temp-provider-config-k8s-upgrade "$provider_image" >/dev/null 2>&1; then
if docker cp temp-provider-config-k8s-upgrade:/opt/bito/xmcp/config/default.json "$k8s_config_path" 2>> "$LOG_FILE"; then
chmod 666 "$k8s_config_path" 2>/dev/null || true
log_silent "Provider configuration extracted from new image for Kubernetes"
log_silent "Extracted default.json to: $k8s_config_path"
else
msg_warn "Could not extract provider config from image, using packaged config"
fi
docker rm temp-provider-config-k8s-upgrade >/dev/null 2>&1 || true
else
msg_warn "Could not create temp container for config extraction"
fi
else
msg_warn "Could not pull provider image for config extraction"
fi
else
msg_warn "Provider image not set in env, using packaged config"
fi
else
msg_warn "Env file not found, using packaged config"
fi
fi
msg_success "Configuration migrated"
}
# Check if docker volumes exist from old installation
check_old_volumes() {
log_silent "Checking for existing data volumes..." >&2
# Try multiple methods to find volumes
local volumes_found=0
local found_project_name=""
# Method 1: Search for volumes matching common patterns
local all_volumes=$(docker volume ls --format "{{.Name}}" 2>/dev/null)
# Look for volumes with the standard suffixes
for suffix in "ai_architect_mysql_data" "ai_architect_data" "ai_architect_backups" "ai_architect_temp"; do
local matching_vol=$(echo "$all_volumes" | grep -E "_${suffix}$" | head -1)
if [[ -n "$matching_vol" ]]; then
volumes_found=$((volumes_found + 1))
# Extract project name from first match (e.g., "test-old" from "test-old_ai_architect_mysql_data")
if [[ -z "$found_project_name" ]]; then
found_project_name=$(echo "$matching_vol" | sed "s/_${suffix}$//")
log_silent "Detected project name from volume: $found_project_name"
fi
log_silent "Found existing volume: $matching_vol"
fi
done
if [[ $volumes_found -gt 0 ]]; then
log_silent "Found $volumes_found existing data volume(s) from project: $found_project_name" >&2
msg_info "Data will be preserved during the upgrade..." >&2
echo "$found_project_name"
else
msg_warn "No existing data volumes found - fresh volumes will be created" >&2
echo ""
fi
}
# Configure shared volumes
configure_volumes() {
log_silent "Configuring shared data volumes..."
local compose_file="${NEW_DIR}/docker-compose.yml"
local old_volumes_project=$(check_old_volumes)
# Backup original
cp "$compose_file" "${compose_file}.backup"
# Use awk to remove old volumes section and add new one
awk '
/^volumes:/ { in_volumes=1; next }
in_volumes && /^[a-z]/ { in_volumes=0 }
!in_volumes { print }
' "$compose_file" > "${compose_file}.tmp"
# Configure volumes based on whether old volumes exist
if [[ -n "$old_volumes_project" ]]; then
log_silent "Configuring to use existing data volumes (data will be preserved)"
# Append external volumes to reference existing ones
cat >> "${compose_file}.tmp" << EOF
volumes:
ai_architect_mysql_data:
external: true
name: ${old_volumes_project}_ai_architect_mysql_data
ai_architect_data:
external: true
name: ${old_volumes_project}_ai_architect_data
ai_architect_backups:
external: true
name: ${old_volumes_project}_ai_architect_backups
ai_architect_temp:
external: true
name: ${old_volumes_project}_ai_architect_temp
EOF
log_silent "Volume configuration updated to use external volumes from: $old_volumes_project"
else
msg_warn "⚠️ IMPORTANT: No existing data volumes found"
msg_warn " Fresh volumes will be created for this installation"
msg_warn " If this is unexpected, please verify your old installation had running services"
# Append local volumes (docker will create fresh ones)
cat >> "${compose_file}.tmp" << 'EOF'
volumes:
ai_architect_mysql_data:
driver: local
ai_architect_data:
driver: local
ai_architect_backups:
driver: local
ai_architect_temp:
driver: local
EOF
log_silent "Volume configuration updated to use fresh local volumes"
fi
mv "${compose_file}.tmp" "$compose_file"
log_silent "Volume configuration complete"
}
# Start new version using setup.sh --from-existing-config
start_new_version() {
msg_info "Starting new version..."
cd "$NEW_DIR" || exit 1
configure_volumes
# CRITICAL: Sync migrated configs to standard location BEFORE running setup.sh
# This ensures setup.sh reads the correct (old) credentials
# shellcheck disable=SC1090
source "${NEW_DIR}/scripts/lib/path-manager.sh"
init_paths
local standard_config_dir="$(get_config_dir)"
log_silent "Syncing migrated configs to standard location: $standard_config_dir"
mkdir -p "$standard_config_dir"
# Copy all config files from NEW_DIR (which has old installation's configs)
for config_file in .env-bitoarch .env-llm-bitoarch .bitoarch-config.yaml .deployment-type; do
if [[ -f "${NEW_DIR}/${config_file}" ]]; then
cp "${NEW_DIR}/${config_file}" "$standard_config_dir/${config_file}"
log_silent "Synced ${config_file} to $standard_config_dir"
fi
done
log_silent "All configs synced to standard location with correct credentials"
log_silent "Running: ./setup.sh --from-existing-config"
msg_info "This may take 2-5 minutes (starting containers)..."
# Run setup.sh in background and show progress
./setup.sh --from-existing-config > "$LOG_FILE" 2>&1 &
local setup_pid=$!
# Show progress dots while setup.sh is running
while kill -0 $setup_pid 2>/dev/null; do
echo -n "."
sleep 2
done
echo ""
# Check exit status (disable set -e temporarily)
set +e
wait $setup_pid
local exit_code=$?
set -e
if [ $exit_code -eq 0 ]; then
msg_success "New version started"
else
msg_error "Failed to start new version (exit code: $exit_code)"
msg_error "Check log file for details: $LOG_FILE"
echo ""
tail -30 "$LOG_FILE"
echo ""
exit 1
fi
}
# Start new version - STANDALONE MODE (direct docker compose)
start_new_version_standalone() {
msg_info "Starting new version (standalone mode)..."
cd "$NEW_DIR" || exit 1
configure_volumes
msg_info "Cleaning up old containers..."
docker ps -a --filter "name=ai-architect" --format "{{.Names}}" | xargs -r docker rm -f >> "$LOG_FILE" 2>&1 || true
msg_info "Cleaning up old networks..."
docker network ls --format "{{.Name}}" | grep "ai-architect-network" | xargs -r docker network rm >> "$LOG_FILE" 2>&1 || true
msg_info "Starting new services..."
msg_info "This may take 2-5 minutes (pulling images, starting containers)..."
if [[ "$DOCKER_COMPOSE_CMD" == "docker compose" ]]; then
docker compose --env-file "$ENV_FILE" up -d --pull always > "$LOG_FILE" 2>&1 &
else
# For docker-compose v1, use --env-file flag (requires docker-compose 1.25.0+)
# Fallback to sourcing if very old version
if $DOCKER_COMPOSE_CMD --help | grep -q "\-\-env-file"; then
$DOCKER_COMPOSE_CMD --env-file "$ENV_FILE" pull >> "$LOG_FILE" 2>&1 || true
$DOCKER_COMPOSE_CMD --env-file "$ENV_FILE" up -d > "$LOG_FILE" 2>&1 &
else
# Legacy fallback: source the file
set -a
source "$ENV_FILE"
set +a
$DOCKER_COMPOSE_CMD pull >> "$LOG_FILE" 2>&1 || true
$DOCKER_COMPOSE_CMD up -d > "$LOG_FILE" 2>&1 &
fi
fi
local compose_pid=$!
while kill -0 $compose_pid 2>/dev/null; do
echo -n "."
sleep 2
done
echo ""
set +e
wait $compose_pid
local exit_code=$?
set -e
if [ $exit_code -eq 0 ]; then
msg_success "New version started"
else
msg_error "Failed to start new version (exit code: $exit_code)"