forked from ben-spanswick/AI-Deployment-Automation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.sh
More file actions
executable file
·1819 lines (1559 loc) · 64.4 KB
/
Copy pathsetup.sh
File metadata and controls
executable file
·1819 lines (1559 loc) · 64.4 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
# AI Box - Unified GPU-Accelerated AI Services Platform
# setup.sh - Dynamic service deployment and management
# Version: 2.1.0
set -euo pipefail
# Verbose mode flag
VERBOSE=false
# Parse command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
-v|--verbose)
VERBOSE=true
shift
;;
-h|--help)
echo "Usage: $0 [OPTIONS]"
echo "Options:"
echo " -v, --verbose Enable verbose output"
echo " -h, --help Show this help message"
exit 0
;;
*)
echo "Unknown option: $1"
echo "Use -h or --help for usage information"
exit 1
;;
esac
done
# Error handling
trap 'error_handler $? $LINENO' ERR
error_handler() {
local exit_code=$1
local line_number=$2
echo -e "${RED}[ERROR]${NC} Script failed with exit code $exit_code at line $line_number" >&2
echo -e "${RED}[ERROR]${NC} Check logs for more details" >&2
exit $exit_code
}
# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Configuration files
CONFIG_DIR="${SCRIPT_DIR}/config"
mkdir -p "$CONFIG_DIR"
CONFIG_FILE="${CONFIG_DIR}/deployment.conf"
STATE_FILE="${CONFIG_DIR}/deployment-state"
SERVICES_FILE="${CONFIG_DIR}/deployed-services.json"
# Log file
LOG_DIR="${SCRIPT_DIR}/logs"
mkdir -p "$LOG_DIR"
LOG_FILE="${LOG_DIR}/setup-$(date +%Y%m%d-%H%M%S).log"
# Logging function
log() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_FILE"
}
# Verbose logging function
vlog() {
if [[ "$VERBOSE" == "true" ]]; then
echo "[$(date +'%Y-%m-%d %H:%M:%S')] [VERBOSE] $*" | tee -a "$LOG_FILE"
else
echo "[$(date +'%Y-%m-%d %H:%M:%S')] [VERBOSE] $*" >> "$LOG_FILE"
fi
}
# Progress bar function
show_progress() {
if [[ "$VERBOSE" != "true" ]]; then
local current=$1
local total=$2
local width=50
local percentage=$((current * 100 / total))
local completed=$((width * current / total))
printf "\r[%-${width}s] %d%%" \
"$(printf '#%.0s' $(seq 1 $completed))" \
"$percentage"
if [[ $current -eq $total ]]; then
echo
fi
fi
}
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'
# Service Registry - Extensible service definitions
declare -A SERVICE_INFO
declare -A SERVICE_PORTS
declare -A SERVICE_IMAGES
declare -A SERVICE_VOLUMES
declare -A SERVICE_ENV
declare -A SERVICE_REQUIRES
# LLM Services
SERVICE_INFO["localai"]="LocalAI|OpenAI-compatible LLM API|llm"
SERVICE_PORTS["localai"]="8080"
SERVICE_IMAGES["localai"]="quay.io/go-skynet/local-ai:latest-gpu-nvidia-cuda-12"
SERVICE_VOLUMES["localai"]="models:/build/models;localai/cache:/tmp/generated"
SERVICE_ENV["localai"]="THREADS=8;DEBUG=false"
SERVICE_INFO["ollama"]="Ollama|Simple LLM management with CLI|llm"
SERVICE_PORTS["ollama"]="11434"
SERVICE_IMAGES["ollama"]="ollama/ollama:latest"
SERVICE_VOLUMES["ollama"]="ollama/models:/root/.ollama"
SERVICE_ENV["ollama"]="OLLAMA_HOST=0.0.0.0"
# ChromaDB - Vector database for embeddings
SERVICE_INFO["chromadb"]="ChromaDB|Vector database for RAG/embeddings|database"
SERVICE_PORTS["chromadb"]="8000"
SERVICE_IMAGES["chromadb"]="chromadb/chroma:latest"
SERVICE_VOLUMES["chromadb"]="chromadb:/chroma/chroma"
SERVICE_ENV["chromadb"]="IS_PERSISTENT=TRUE;PERSIST_DIRECTORY=/chroma/chroma;ANONYMIZED_TELEMETRY=FALSE"
SERVICE_REQUIRES["chromadb"]=""
# n8n - Workflow automation
SERVICE_INFO["n8n"]="n8n|Workflow automation for AI chains|automation"
SERVICE_PORTS["n8n"]="5678"
SERVICE_IMAGES["n8n"]="n8nio/n8n:latest"
SERVICE_VOLUMES["n8n"]="n8n:/home/node/.n8n"
SERVICE_ENV["n8n"]="N8N_SECURE_COOKIE=false;N8N_HOST=0.0.0.0;N8N_PORT=5678;NODE_ENV=production;WEBHOOK_URL=http://localhost:5678/"
SERVICE_REQUIRES["n8n"]=""
# Whisper - Speech to text
SERVICE_INFO["whisper"]="Whisper|OpenAI speech-to-text|audio"
SERVICE_PORTS["whisper"]="9000"
SERVICE_IMAGES["whisper"]="onerahmet/openai-whisper-asr-webservice:latest-gpu"
SERVICE_VOLUMES["whisper"]="whisper/models:/app/models"
SERVICE_ENV["whisper"]="ASR_MODEL=base;ASR_ENGINE=openai_whisper"
# Image Generation Services
SERVICE_INFO["forge"]="SD Forge|Optimized Stable Diffusion WebUI|image"
SERVICE_PORTS["forge"]="7860"
# SD Forge recommended image - CUDA 12.1 + PyTorch 2.3.1
SERVICE_IMAGES["forge"]="nykk3/stable-diffusion-webui-forge:latest"
SERVICE_VOLUMES["forge"]="models/stable-diffusion:/app/stable-diffusion-webui/models/Stable-diffusion;models/loras:/app/stable-diffusion-webui/models/Lora;models/vae:/app/stable-diffusion-webui/models/VAE;outputs/forge:/app/stable-diffusion-webui/outputs"
SERVICE_ENV["forge"]="COMMANDLINE_ARGS=--listen --api --xformers --medvram --skip-torch-cuda-test --skip-version-check --no-download-sd-model"
SERVICE_INFO["comfyui"]="ComfyUI|Node-based workflow (FLUX support!)|image"
SERVICE_PORTS["comfyui"]="8188"
SERVICE_IMAGES["comfyui"]="yanwk/comfyui-boot:cu121"
SERVICE_VOLUMES["comfyui"]="comfyui:/workspace;models:/workspace/models;comfyui/output:/workspace/output"
SERVICE_ENV["comfyui"]="CLI_ARGS=--listen"
# Image generation services - keeping only Forge and ComfyUI
# Removed: AUTOMATIC1111 (redundant with Forge), InvokeAI (redundant UI), Fooocus (simplified UI, redundant)
# Training/Tools - Currently empty (Kohya_ss removed due to compatibility issues)
# Support Services
SERVICE_INFO["dcgm"]="DCGM Exporter|NVIDIA GPU metrics|support"
SERVICE_PORTS["dcgm"]="9400"
SERVICE_IMAGES["dcgm"]="nvcr.io/nvidia/k8s/dcgm-exporter:3.1.8-3.1.5-ubuntu20.04"
SERVICE_VOLUMES["dcgm"]=""
SERVICE_ENV["dcgm"]="DCGM_EXPORTER_LISTEN=0.0.0.0:9400;DCGM_EXPORTER_KUBERNETES=false"
SERVICE_REQUIRES["dcgm"]=""
SERVICE_INFO["dashboard"]="Web Dashboard|Unified control panel|support"
SERVICE_PORTS["dashboard"]="80"
SERVICE_IMAGES["dashboard"]="nginx:alpine"
SERVICE_VOLUMES["dashboard"]="nginx/html:/usr/share/nginx/html:ro;nginx/nginx.conf:/etc/nginx/nginx.conf:ro"
SERVICE_ENV["dashboard"]=""
SERVICE_REQUIRES["dashboard"]=""
# Display Functions (overriding the logging functions for colored output)
log() { echo -e "${BLUE}[INFO]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1" >&2; }
success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
warn() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
# Print banner
print_banner() {
clear
echo -e "${CYAN}${BOLD}"
echo "╔════════════════════════════════════════════╗"
echo "║ AI Box Modular Setup v2.1 ║"
echo "║ Dynamic Service Management System ║"
echo "╚════════════════════════════════════════════╝"
echo -e "${NC}"
}
# Get actual user (works with or without sudo)
get_actual_user() {
if [[ -n "${SUDO_USER:-}" ]]; then
echo "$SUDO_USER"
else
echo "$USER"
fi
}
# Run command as actual user
run_as_user() {
local actual_user=$(get_actual_user)
if [[ $EUID -eq 0 ]] && [[ "$actual_user" != "root" ]]; then
sudo -u "$actual_user" "$@"
else
"$@"
fi
}
# Install NVIDIA drivers if needed
install_nvidia_drivers_if_needed() {
if ! command -v nvidia-smi &> /dev/null; then
warn "NVIDIA drivers not found. Installing NVIDIA drivers..."
# Update package list
apt-get update
# Install required packages for driver installation
apt-get install -y \
software-properties-common \
build-essential \
linux-headers-$(uname -r) \
ubuntu-drivers-common
# Detect recommended driver
log "Detecting recommended NVIDIA driver..."
local recommended_driver=$(ubuntu-drivers devices | grep recommended | awk '{print $3}')
if [[ -n "$recommended_driver" ]]; then
log "Installing recommended driver: $recommended_driver"
apt-get install -y "$recommended_driver"
else
# Fallback to latest driver
log "No recommended driver found, installing latest available driver..."
add-apt-repository -y ppa:graphics-drivers/ppa
apt-get update
# Get latest driver version
local latest_driver=$(apt-cache search nvidia-driver | grep -E "^nvidia-driver-[0-9]+" | sort -V | tail -n1 | awk '{print $1}')
if [[ -n "$latest_driver" ]]; then
log "Installing $latest_driver"
apt-get install -y "$latest_driver"
else
error "Could not determine NVIDIA driver to install"
exit 1
fi
fi
# Install CUDA support packages
apt-get install -y nvidia-cuda-toolkit nvidia-cuda-dev
# Enable persistence mode
nvidia-smi -pm 1 || true
success "NVIDIA drivers installed successfully!"
# Set flag to indicate fresh install
NVIDIA_FRESH_INSTALL=true
# Prompt for reboot
warn "NVIDIA drivers have been installed. A system reboot is required."
read -p "Would you like to reboot now? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
log "Rebooting system..."
reboot
else
warn "Please reboot the system manually to complete NVIDIA driver installation."
echo "After reboot, run this script again: sudo ./setup.sh"
exit 0
fi
else
log "NVIDIA drivers already installed"
nvidia-smi --query-gpu=driver_version,name --format=csv,noheader | while IFS=',' read -r version name; do
log " GPU: $name, Driver: $version"
done
# Display CUDA version
local cuda_version=$(nvidia-smi | grep "CUDA Version" | sed -n 's/.*CUDA Version: \([0-9]*\.[0-9]*\).*/\1/p')
if [[ -n "$cuda_version" ]]; then
log " CUDA Version: $cuda_version"
fi
# Check for CUDA toolkit installation
if [[ -d "/usr/local/cuda" ]]; then
local cuda_toolkit_version=$(cat /usr/local/cuda/version.txt 2>/dev/null | grep "CUDA Version" | awk '{print $3}' || echo "unknown")
if [[ "$cuda_toolkit_version" != "unknown" ]]; then
log " CUDA Toolkit: $cuda_toolkit_version (at $(readlink -f /usr/local/cuda))"
else
# Try alternative method
local cuda_link=$(readlink -f /usr/local/cuda)
if [[ "$cuda_link" =~ cuda-([0-9]+\.[0-9]+) ]]; then
log " CUDA Toolkit: ${BASH_REMATCH[1]} (at $cuda_link)"
fi
fi
fi
fi
}
# Install Docker if needed
install_docker_if_needed() {
if ! command -v docker &> /dev/null; then
warn "Docker is not installed. Installing Docker and NVIDIA Container Toolkit..."
# Install prerequisites
apt-get update
apt-get install -y \
apt-transport-https \
ca-certificates \
curl \
gnupg \
lsb-release \
software-properties-common
# Add Docker's official GPG key
mkdir -p /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
chmod a+r /etc/apt/keyrings/docker.gpg
# Add Docker repository
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
# Install Docker
apt-get update
apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
# Start and enable Docker
systemctl start docker
systemctl enable docker
# Add user to docker group
local actual_user=$(get_actual_user)
usermod -aG docker "$actual_user"
# Install NVIDIA Container Toolkit
curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | gpg --dearmor -o /etc/apt/keyrings/nvidia-container-toolkit.gpg
chmod a+r /etc/apt/keyrings/nvidia-container-toolkit.gpg
curl -s -L https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list | \
sed 's#deb https://#deb [signed-by=/etc/apt/keyrings/nvidia-container-toolkit.gpg] https://#g' | \
tee /etc/apt/sources.list.d/nvidia-container-toolkit.list
apt-get update
apt-get install -y nvidia-container-toolkit
# Configure Docker for GPU support
nvidia-ctk runtime configure --runtime=docker
systemctl restart docker
success "Docker installed successfully!"
# Set flag to indicate fresh install
DOCKER_FRESH_INSTALL=true
fi
}
# Check system requirements
check_system_requirements() {
log "Checking system requirements..."
# Check if we need sudo
if [[ $EUID -ne 0 ]]; then
error "This script must be run with sudo"
echo "Usage: sudo ./setup.sh"
exit 1
fi
# Get actual user
ACTUAL_USER=$(get_actual_user)
if [[ "$ACTUAL_USER" == "root" ]]; then
error "Please run this script with sudo as a normal user, not as root directly"
echo "Usage: sudo ./setup.sh"
exit 1
fi
log "Running as root, actual user is: $ACTUAL_USER"
# Install Docker if needed
install_docker_if_needed
# Check if user is in docker group (or just added)
if ! groups "$ACTUAL_USER" | grep -q docker && [[ -z "${DOCKER_FRESH_INSTALL:-}" ]]; then
error "User $ACTUAL_USER is not in the docker group"
echo "Adding user to docker group..."
usermod -aG docker "$ACTUAL_USER"
fi
# Install NVIDIA drivers if needed
install_nvidia_drivers_if_needed
# Check NVIDIA Container Toolkit
if ! run_as_user docker run --rm --gpus all nvidia/cuda:12.9-base-ubuntu22.04 nvidia-smi &> /dev/null; then
warn "NVIDIA Container Toolkit test failed - this may be normal on fresh install"
# Don't exit on fresh install or if NVIDIA drivers were just installed
if [[ -z "${DOCKER_FRESH_INSTALL:-}" ]] && [[ -z "${NVIDIA_FRESH_INSTALL:-}" ]]; then
error "NVIDIA Container Toolkit not working properly"
exit 1
fi
warn "GPU support may require a reboot or re-login to work properly"
fi
# Check disk space (require at least 50GB free)
local free_space=$(df -k /opt 2>/dev/null | awk 'NR==2 {print $4}' || df -k / | awk 'NR==2 {print $4}')
local required_space=$((50 * 1024 * 1024)) # 50GB in KB
# Validate that free_space is a number
if ! [[ "$free_space" =~ ^[0-9]+$ ]]; then
warn "Could not determine free disk space"
# Try alternative method
free_space=$(df -BK /opt 2>/dev/null | awk 'NR==2 {gsub(/K/, "", $4); print $4}' || df -BK / | awk 'NR==2 {gsub(/K/, "", $4); print $4}')
fi
if [[ "$free_space" =~ ^[0-9]+$ ]] && [[ $free_space -lt $required_space ]]; then
error "Insufficient disk space. At least 50GB free space required."
echo "Available: $(($free_space / 1024 / 1024))GB"
exit 1
fi
# Create AI Box directory if it doesn't exist
if [[ ! -d "/opt/ai-box" ]]; then
mkdir -p /opt/ai-box
chown "$ACTUAL_USER:$ACTUAL_USER" /opt/ai-box
fi
success "System requirements check passed"
}
# Install CUDA 12.1 alongside existing CUDA
install_cuda_12_1() {
log "Installing CUDA 12.1 toolkit..."
# Clean up any broken installations first
cleanup_broken_cuda_install() {
vlog "Checking for broken CUDA installations..."
# Remove broken repository packages
if dpkg -l | grep -q "cuda-repo-ubuntu.*-12-1-local"; then
warn "Found broken CUDA repository package, removing..."
sudo dpkg --purge cuda-repo-ubuntu*-12-1-local 2>/dev/null || true
fi
# Clean up all CUDA-related apt sources and keys
sudo rm -f /usr/share/keyrings/cuda-*-keyring.gpg 2>/dev/null || true
sudo rm -f /etc/apt/sources.list.d/cuda*.list 2>/dev/null || true
sudo rm -f /etc/apt/preferences.d/cuda*.pin 2>/dev/null || true
# Remove the local repo directory if it exists
sudo rm -rf /var/cuda-repo-ubuntu*-12-1-local 2>/dev/null || true
# Clean apt cache
sudo apt-get clean
sudo apt-get update 2>&1 | grep -v "NO_PUBKEY" || true
}
cleanup_broken_cuda_install
# Detect Ubuntu version
local ubuntu_version=$(lsb_release -rs | cut -d. -f1)
local ubuntu_codename="ubuntu${ubuntu_version}04"
# For Ubuntu 24+, use network installer for better compatibility
if [[ "$ubuntu_version" -ge 24 ]]; then
log "Ubuntu $ubuntu_version detected, downloading from NVIDIA network repository..."
# Install compatibility libraries first
log "Installing compatibility libraries..."
sudo add-apt-repository universe -y
sudo apt-get update
# Install libtinfo5 for Ubuntu 24
if ! dpkg -l | grep -q "libtinfo5"; then
wget -q http://archive.ubuntu.com/ubuntu/pool/universe/n/ncurses/libtinfo5_6.4-2_amd64.deb
sudo dpkg -i libtinfo5_6.4-2_amd64.deb || true
rm -f libtinfo5_6.4-2_amd64.deb
fi
# Use network installer for Ubuntu 24+
log "Setting up CUDA network repository..."
wget -q https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-keyring_1.1-1_all.deb
sudo dpkg -i cuda-keyring_1.1-1_all.deb
rm -f cuda-keyring_1.1-1_all.deb
sudo apt-get update
# Install minimal CUDA 12.1 components
log "Installing CUDA 12.1 toolkit (minimal installation for compatibility)..."
local cuda_packages=(
cuda-toolkit-12-1-config-common
cuda-toolkit-12-config-common
cuda-cudart-12-1
cuda-cudart-dev-12-1
cuda-compiler-12-1
cuda-nvcc-12-1
cuda-libraries-12-1
cuda-libraries-dev-12-1
libcublas-12-1
libcublas-dev-12-1
)
for package in "${cuda_packages[@]}"; do
vlog "Installing $package..."
sudo apt-get install -y --no-install-recommends "$package" 2>/dev/null || warn "Package $package failed, continuing..."
done
else
# For Ubuntu 20.04/22.04, download and use local installer package
if [[ "$ubuntu_version" -lt 20 ]]; then
ubuntu_codename="ubuntu2004"
warn "Using Ubuntu 20.04 CUDA repository for Ubuntu $ubuntu_version"
fi
# Add NVIDIA package repositories
log "Downloading CUDA repository configuration..."
wget -q https://developer.download.nvidia.com/compute/cuda/repos/${ubuntu_codename}/x86_64/cuda-${ubuntu_codename}.pin
sudo mv cuda-${ubuntu_codename}.pin /etc/apt/preferences.d/cuda-repository-pin-600
# Download CUDA 12.1 local installer package from NVIDIA
local cuda_repo_pkg="cuda-repo-${ubuntu_codename}-12-1-local_12.1.0-530.30.02-1_amd64.deb"
log "Downloading CUDA 12.1 installer package from NVIDIA (this may take a few minutes)..."
wget -q --show-progress https://developer.download.nvidia.com/compute/cuda/12.1.0/local_installers/${cuda_repo_pkg}
if [[ ! -f "$cuda_repo_pkg" ]]; then
error "Failed to download CUDA repository package"
return 1
fi
sudo dpkg -i ${cuda_repo_pkg}
sudo cp /var/cuda-repo-${ubuntu_codename}-12-1-local/cuda-*-keyring.gpg /usr/share/keyrings/
sudo apt-get update -qq
# Install CUDA 12.1 toolkit
log "Installing CUDA 12.1 toolkit packages..."
sudo apt-get install -y --no-install-recommends cuda-toolkit-12-1 || {
warn "Some packages failed, but continuing..."
}
# Clean up
rm -f ${cuda_repo_pkg}
fi
# Create symlink if installation succeeded
if [[ -d "/usr/local/cuda-12.1" ]]; then
sudo rm -f /usr/local/cuda
sudo ln -s /usr/local/cuda-12.1 /usr/local/cuda
log "Created /usr/local/cuda symlink"
# Set up alternatives for CUDA version management
if command -v update-alternatives &> /dev/null; then
sudo update-alternatives --install /usr/local/cuda cuda /usr/local/cuda-12.1 121 2>/dev/null || true
fi
else
error "CUDA 12.1 directory not found after installation"
return 1
fi
# Add CUDA to PATH if not already present
local actual_user=$(get_actual_user)
local user_bashrc="/home/$actual_user/.bashrc"
if [[ -f "$user_bashrc" ]] && ! grep -q "/usr/local/cuda/bin" "$user_bashrc"; then
echo 'export PATH=/usr/local/cuda/bin:$PATH' >> "$user_bashrc"
echo 'export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH' >> "$user_bashrc"
log "Added CUDA to PATH and LD_LIBRARY_PATH in $user_bashrc"
fi
# Verify installation
if [[ -f "/usr/local/cuda-12.1/bin/nvcc" ]]; then
local nvcc_version=$(/usr/local/cuda-12.1/bin/nvcc --version | grep "release" | awk '{print $5}' | sed 's/,//')
success "CUDA 12.1 installed successfully (nvcc version: $nvcc_version)"
log "Please run 'source ~/.bashrc' or restart your terminal to update PATH"
return 0
else
warn "CUDA installation completed but nvcc not found - installation may be incomplete"
return 1
fi
}
# Manage CUDA version switching
manage_cuda_version() {
echo
echo -e "${BOLD}CUDA Version Management${NC}"
# Check current driver CUDA support
local driver_cuda=$(nvidia-smi | grep "CUDA Version" | sed -n 's/.*CUDA Version: \([0-9]*\.[0-9]*\).*/\1/p')
if [[ -n "$driver_cuda" ]]; then
log "NVIDIA Driver supports CUDA: $driver_cuda"
fi
# List available CUDA versions
local cuda_versions=$(ls -d /usr/local/cuda-* 2>/dev/null | sort -V)
if [[ -z "$cuda_versions" ]]; then
warn "No CUDA Toolkit installations found"
echo
echo "Your NVIDIA driver supports CUDA $driver_cuda, but no CUDA Toolkit is installed."
echo "The CUDA Toolkit includes development tools, libraries, and compilers needed by applications."
echo
echo "SD Forge requires CUDA Toolkit 12.1 for optimal performance."
echo
echo "Options:"
echo "1) Install CUDA 12.1 Toolkit (recommended for SD Forge)"
echo "2) Install latest CUDA Toolkit"
echo "3) Fix broken CUDA installation and retry"
echo "4) Cancel"
echo
read -p "Select option [1-4]: " install_choice
case $install_choice in
1)
log "Installing CUDA 12.1 Toolkit..."
if ! install_cuda_12_1; then
warn "CUDA installation failed!"
echo
echo "This might be due to broken packages or repository issues."
read -p "Would you like to clean up and retry? [Y/n]: " cleanup_retry
if [[ ! "$cleanup_retry" =~ ^[Nn]$ ]]; then
log "Cleaning up broken CUDA installations..."
# Remove broken packages
if dpkg -l | grep -q "cuda-repo-ubuntu.*-12-1-local"; then
warn "Removing broken CUDA repository packages..."
sudo dpkg --purge cuda-repo-ubuntu*-12-1-local 2>/dev/null || true
fi
# Clean up keyrings and sources
sudo rm -f /usr/share/keyrings/cuda-*-keyring.gpg 2>/dev/null || true
sudo rm -f /etc/apt/sources.list.d/cuda*.list 2>/dev/null || true
sudo rm -f /etc/apt/preferences.d/cuda*.pin 2>/dev/null || true
sudo rm -rf /var/cuda-repo-ubuntu*-12-1-local 2>/dev/null || true
sudo apt-get clean
sudo apt-get update
success "Cleanup completed"
log "Returning to CUDA installation menu..."
sleep 2
# Recursively call manage_cuda_version to show the menu again
manage_cuda_version
return
fi
else
# Create symlink if not already created
if [[ -d "/usr/local/cuda-12.1" ]] && [[ ! -L "/usr/local/cuda" ]]; then
sudo ln -s /usr/local/cuda-12.1 /usr/local/cuda
fi
fi
;;
2)
log "Installing latest CUDA Toolkit..."
# Install latest CUDA from NVIDIA repos
apt-get update
apt-get install -y cuda
success "Latest CUDA Toolkit installed"
;;
3)
log "Cleaning up broken CUDA installations..."
# Remove broken packages
if dpkg -l | grep -q "cuda-repo-ubuntu.*-12-1-local"; then
warn "Removing broken CUDA repository packages..."
sudo dpkg --purge cuda-repo-ubuntu*-12-1-local 2>/dev/null || true
fi
# Clean up keyrings and sources
sudo rm -f /usr/share/keyrings/cuda-*-keyring.gpg 2>/dev/null || true
sudo rm -f /etc/apt/sources.list.d/cuda*.list 2>/dev/null || true
sudo rm -f /etc/apt/preferences.d/cuda*.pin 2>/dev/null || true
sudo apt-get clean
sudo apt-get update
success "Cleanup completed"
log "Returning to CUDA installation menu..."
sleep 2
# Recursively call to show menu again after cleanup
manage_cuda_version
return
;;
4)
log "CUDA installation cancelled"
;;
esac
return
fi
echo "Available CUDA Toolkit installations:"
echo "$cuda_versions"
echo
if [[ -L "/usr/local/cuda" ]]; then
echo "Current CUDA symlink points to: $(readlink /usr/local/cuda)"
else
warn "No /usr/local/cuda symlink found"
fi
echo
echo "Options:"
echo "1) Switch to CUDA 12.1 (recommended for SD Forge)"
echo "2) Switch to latest CUDA version"
echo "3) Install CUDA 12.1 (if not present)"
echo "4) Fix broken CUDA installation"
echo "5) Show current configuration"
echo "6) Cancel"
echo
read -p "Select option [1-6]: " cuda_mgmt_choice
case $cuda_mgmt_choice in
1)
if [[ -d "/usr/local/cuda-12.1" ]]; then
sudo rm -f /usr/local/cuda
sudo ln -s /usr/local/cuda-12.1 /usr/local/cuda
success "Switched to CUDA 12.1"
echo "You may need to update your PATH and LD_LIBRARY_PATH"
else
warn "CUDA 12.1 not found. Would you like to install it?"
read -p "Install CUDA 12.1? [y/N]: " install_cuda
if [[ "$install_cuda" =~ ^[Yy]$ ]]; then
install_cuda_12_1
sudo ln -s /usr/local/cuda-12.1 /usr/local/cuda
success "CUDA 12.1 installed and activated"
fi
fi
;;
2)
local latest_cuda=$(ls -d /usr/local/cuda-* 2>/dev/null | sort -V | tail -n1)
if [[ -n "$latest_cuda" ]]; then
sudo rm -f /usr/local/cuda
sudo ln -s "$latest_cuda" /usr/local/cuda
success "Switched to $latest_cuda"
else
error "No CUDA installations found"
fi
;;
3)
if [[ -d "/usr/local/cuda-12.1" ]]; then
log "CUDA 12.1 is already installed at /usr/local/cuda-12.1"
else
install_cuda_12_1
success "CUDA 12.1 installed successfully"
fi
;;
4)
log "Cleaning up broken CUDA installations..."
# Remove broken packages
if dpkg -l | grep -q "cuda-repo-ubuntu.*-12-1-local"; then
warn "Removing broken CUDA repository packages..."
sudo dpkg --purge cuda-repo-ubuntu*-12-1-local 2>/dev/null || true
fi
# Clean up keyrings
sudo rm -f /usr/share/keyrings/cuda-*-keyring.gpg 2>/dev/null || true
sudo rm -f /etc/apt/sources.list.d/cuda*.list 2>/dev/null || true
sudo rm -f /etc/apt/preferences.d/cuda*.pin 2>/dev/null || true
# Update package lists
sudo apt-get clean
sudo apt-get update
success "Cleanup completed"
echo
read -p "Would you like to install CUDA 12.1 now? [y/N]: " install_now
if [[ "$install_now" =~ ^[Yy]$ ]]; then
install_cuda_12_1
fi
;;
5)
echo "CUDA configuration:"
echo "==================="
ls -la /usr/local/ | grep cuda || echo "No CUDA installations in /usr/local/"
echo
echo "Environment variables:"
echo "PATH includes CUDA: $(echo $PATH | grep -q cuda && echo "Yes" || echo "No")"
echo "LD_LIBRARY_PATH: ${LD_LIBRARY_PATH:-Not set}"
;;
6)
log "CUDA version management cancelled"
;;
esac
}
# Detect GPUs
detect_gpus() {
log "Detecting GPUs..."
# Get GPU count
GPU_COUNT=$(nvidia-smi --query-gpu=name --format=csv,noheader | wc -l)
# Extract CUDA version for SD Forge selection
CUDA_VERSION_FULL=$(nvidia-smi | grep "CUDA Version" | sed -n 's/.*CUDA Version: \([0-9]*\.[0-9]*\).*/\1/p')
CUDA_VERSION_MAJOR=$(echo $CUDA_VERSION_FULL | cut -d. -f1)
CUDA_VERSION_MINOR=$(echo $CUDA_VERSION_FULL | cut -d. -f2)
if [[ $GPU_COUNT -eq 0 ]]; then
error "No GPUs detected"
exit 1
fi
# Get GPU model (first GPU)
GPU_MODEL=$(nvidia-smi --query-gpu=name --format=csv,noheader | head -n1)
success "Detected $GPU_COUNT GPU(s): $GPU_MODEL"
log "CUDA Version: $CUDA_VERSION_FULL"
# Save to config
echo "GPU_COUNT=$GPU_COUNT" >> "$CONFIG_FILE"
echo "GPU_MODEL=\"$GPU_MODEL\"" >> "$CONFIG_FILE"
echo "CUDA_VERSION=\"$CUDA_VERSION_FULL\"" >> "$CONFIG_FILE"
}
# Custom service selection
custom_service_selection() {
echo
echo -e "${BOLD}Custom Service Selection${NC}"
echo "Select services to deploy (space-separated numbers):"
local i=1
local service_array=()
# Build service array and display options
for service in "${!SERVICE_INFO[@]}"; do
service_array+=("$service")
IFS='|' read -r name desc category <<< "${SERVICE_INFO[$service]}"
echo "$i) $service - $name: $desc"
((i++))
done
read -p "Enter numbers (e.g., 1 3 5): " selections
SELECTED_SERVICES=""
for num in $selections; do
if [[ $num -ge 1 ]] && [[ $num -le ${#service_array[@]} ]]; then
SELECTED_SERVICES+="${service_array[$((num-1))]} "
fi
done
# Trim trailing space
SELECTED_SERVICES=${SELECTED_SERVICES% }
}
# Update existing services
update_existing_services() {
log "Updating existing services..."
if [[ -z "$DEPLOYED_SERVICES" ]]; then
warn "No services are currently deployed!"
return
fi
echo "Select update method:"
echo "1) Update images only (pull latest versions)"
echo "2) Reset configurations to defaults"
echo "3) Cancel"
read -p "Enter choice [1-3]: " update_choice
case $update_choice in
1)
echo "Pulling latest images for deployed services..."
# Pull images in parallel for better performance
local pull_pids=()
for service in $DEPLOYED_SERVICES; do
local image="${SERVICE_IMAGES[$service]}"
if [[ "$VERBOSE" == "true" ]]; then
log "Starting update for $service..."
run_as_user docker pull "$image" &
else
echo -n "Updating $service... "
run_as_user docker pull "$image" > /dev/null 2>&1 &
fi
pull_pids+=($!)
done
# Wait for all pulls to complete
log "Waiting for all image updates to complete..."
local failed_pulls=0
for pid in "${pull_pids[@]}"; do
if ! wait $pid; then
((failed_pulls++))
fi
done
if [[ $failed_pulls -gt 0 ]]; then
warn "$failed_pulls image(s) failed to update"
else
success "All images updated successfully"
fi
echo
read -p "Restart services with new images? [y/N]: " restart
if [[ "$restart" =~ ^[Yy]$ ]]; then
cd /opt/ai-box
# Stop ALL containers on ai-network first
echo "Stopping all AI Box services..."
docker ps -q --filter "network=ai-network" | xargs -r docker stop
docker ps -aq --filter "network=ai-network" | xargs -r docker rm
# Also try docker-compose down if compose file exists
if [[ -f "/opt/ai-box/docker-compose.yml" ]]; then
cd /opt/ai-box
run_as_user docker compose down || true
fi
run_as_user docker compose up -d
success "Services updated and restarted"
else
log "Images updated. Restart manually when ready."
fi
;;
2)
warn "This will reset all service configurations to defaults!"
read -p "Are you sure? Type 'yes' to confirm: " confirm
if [[ "$confirm" == "yes" ]]; then
# Stop all services
cd /opt/ai-box
# Stop ALL containers on ai-network first
echo "Stopping all AI Box services..."
docker ps -q --filter "network=ai-network" | xargs -r docker stop
docker ps -aq --filter "network=ai-network" | xargs -r docker rm
# Also try docker-compose down if compose file exists
if [[ -f "/opt/ai-box/docker-compose.yml" ]]; then
cd /opt/ai-box
run_as_user docker compose down || true
fi
# Wait for containers to fully stop
log "Waiting for services to stop..."
sleep 3
# Clear port assignments to force reconfiguration
for service in $DEPLOYED_SERVICES; do
local port_var="${service^^}_PORT"
unset $port_var
done
# Set flag to indicate we're reconfiguring
RECONFIGURE_MODE=true
SELECTED_SERVICES="$DEPLOYED_SERVICES"
success "Services stopped. Returning to configuration..."
# Return to main flow instead of regenerating here
return 0
else
log "Update cancelled"
fi
;;
*)
log "Update cancelled"
;;
esac
}
# Load existing deployment state
load_deployed_services() {
if [[ -f "$SERVICES_FILE" ]]; then
# Check if jq is available
if ! command -v jq &> /dev/null; then
warn "jq not found. Installing jq for JSON parsing..."
sudo apt-get update && sudo apt-get install -y jq
fi
# Parse with error handling
DEPLOYED_SERVICES=$(cat "$SERVICES_FILE" | jq -r '.services[]' 2>/dev/null | tr '\n' ' ' | sed 's/ $//')
# Validate the parsed result
if [[ -z "$DEPLOYED_SERVICES" ]] && [[ -s "$SERVICES_FILE" ]]; then
warn "Failed to parse services file. It may be corrupted."
# Try to recover by reading raw content
local raw_content=$(cat "$SERVICES_FILE")
if [[ "$raw_content" =~ \"services\":\[(.*)\] ]]; then
DEPLOYED_SERVICES=$(echo "${BASH_REMATCH[1]}" | sed 's/"//g' | sed 's/,/ /g')
log "Recovered services: $DEPLOYED_SERVICES"
fi
fi
else
DEPLOYED_SERVICES=""
fi
}
# Save deployment state
save_deployed_services() {
local services_json='{"services":['
local first=true
for service in $1; do
if [[ "$first" == "true" ]]; then
first=false
else
services_json+=","
fi
services_json+="\"$service\""
done
services_json+=']}'
echo "$services_json" > "$SERVICES_FILE"
}