-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker-stack-restore.sh
More file actions
461 lines (378 loc) · 13.8 KB
/
docker-stack-restore.sh
File metadata and controls
461 lines (378 loc) · 13.8 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
#!/bin/bash
#######################################
# Docker Stack Restore Script
# Interactive restoration of Docker Compose stacks from backup
#######################################
set -euo pipefail
#######################################
# OS Detection
#######################################
detect_os() {
if [[ -f /etc/os-release ]]; then
. /etc/os-release
OS_NAME="$NAME"
OS_ID="$ID"
OS_VERSION="$VERSION_ID"
# Detect specific distributions
case "$OS_ID" in
debian)
OS_TYPE="debian"
;;
ubuntu)
OS_TYPE="ubuntu"
;;
scale|truenas)
OS_TYPE="truenas"
;;
proxmox)
OS_TYPE="proxmox"
;;
*)
# Check if it's TrueNAS by other means
if [[ -f /etc/version ]] && grep -q "TrueNAS" /etc/version 2>/dev/null; then
OS_TYPE="truenas"
# Debian-based fallback
elif [[ -f /etc/debian_version ]]; then
OS_TYPE="debian"
else
OS_TYPE="unknown"
fi
;;
esac
else
OS_TYPE="unknown"
OS_NAME="Unknown"
fi
export OS_TYPE OS_NAME OS_ID OS_VERSION
}
# Detect OS on script start
detect_os
# Configuration
BACKUP_BASE="/mnt/backup/docker-backups"
DOCKHAND_BASE="/opt/dockhand/stacks" # Base path where Dockhand stores stacks (hostname will be appended)
APPDATA_PATH="/mnt/datastor/appdata" # Path where stack appdata is stored
LOG_FILE="/var/log/docker-restore.log"
# 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'
#######################################
# Logging functions
#######################################
log() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_FILE"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $*" | tee -a "$LOG_FILE"
}
log_success() {
echo -e "${GREEN}[SUCCESS]${NC} $*" | tee -a "$LOG_FILE"
}
log_warning() {
echo -e "${YELLOW}[WARNING]${NC} $*" | tee -a "$LOG_FILE"
}
#######################################
# UI Helper functions
#######################################
print_header() {
echo -e "\n${BOLD}${BLUE}═══════════════════════════════════════════════════════${NC}"
echo -e "${BOLD}${BLUE} Docker Stack Restore Wizard${NC}"
echo -e "${BOLD}${BLUE} Current Host: $HOSTNAME | OS: $OS_NAME${NC}"
echo -e "${BOLD}${BLUE}═══════════════════════════════════════════════════════${NC}\n"
}
print_section() {
echo -e "\n${CYAN}▶ $1${NC}\n"
}
prompt_continue() {
local message="${1:-Continue?}"
echo -e -n "${YELLOW}$message [y/N]: ${NC}"
read -r response
[[ "$response" =~ ^[Yy]$ ]]
}
prompt_input() {
local prompt="$1"
local default="${2:-}"
if [[ -n "$default" ]]; then
echo -e -n "${CYAN}$prompt [$default]: ${NC}"
else
echo -e -n "${CYAN}$prompt: ${NC}"
fi
read -r input
echo "${input:-$default}"
}
#######################################
# Select hostname
#######################################
select_hostname() {
print_section "Step 1: Select Host"
local -a hostnames
local i=1
for host_dir in "$BACKUP_BASE"/*; do
if [[ -d "$host_dir" ]]; then
hostnames+=("$(basename "$host_dir")")
fi
done
if [[ ${#hostnames[@]} -eq 0 ]]; then
log_error "No backup hosts found in $BACKUP_BASE"
exit 1
fi
echo "Available hosts:"
for hostname in "${hostnames[@]}"; do
echo -e " ${GREEN}$i)${NC} $hostname"
((i++))
done
echo ""
local selection=$(prompt_input "Select host number" "1")
if [[ ! "$selection" =~ ^[0-9]+$ ]] || [[ $selection -lt 1 ]] || [[ $selection -gt ${#hostnames[@]} ]]; then
log_error "Invalid selection"
exit 1
fi
selected_hostname="${hostnames[$((selection-1))]}"
echo -e "\n${GREEN}✓${NC} Selected host: ${BOLD}$selected_hostname${NC}"
}
#######################################
# Select backup timestamp
#######################################
select_timestamp() {
print_section "Step 2: Select Backup Date"
local host_dir="$BACKUP_BASE/$selected_hostname"
local -a timestamps
local i=1
for backup_dir in "$host_dir"/*; do
if [[ -d "$backup_dir" ]]; then
timestamps+=("$(basename "$backup_dir")")
fi
done | sort -r
if [[ ${#timestamps[@]} -eq 0 ]]; then
log_error "No backups found for host $selected_hostname"
exit 1
fi
echo "Available backups (newest first):"
for timestamp in "${timestamps[@]}"; do
local date_part="${timestamp%_*}"
local time_part="${timestamp#*_}"
local formatted_date=$(date -d "${date_part:0:4}-${date_part:4:2}-${date_part:6:2}" +"%B %d, %Y" 2>/dev/null || echo "$date_part")
local formatted_time="${time_part:0:2}:${time_part:2:2}:${time_part:4:2}"
local stack_count=$(find "$host_dir/$timestamp" -name "*.tar.gz" | wc -l)
echo -e " ${GREEN}$i)${NC} $formatted_date at $formatted_time (${stack_count} stacks)"
((i++))
done
echo ""
local selection=$(prompt_input "Select backup number" "1")
if [[ ! "$selection" =~ ^[0-9]+$ ]] || [[ $selection -lt 1 ]] || [[ $selection -gt ${#timestamps[@]} ]]; then
log_error "Invalid selection"
exit 1
fi
selected_timestamp="${timestamps[$((selection-1))]}"
echo -e "\n${GREEN}✓${NC} Selected backup: ${BOLD}$selected_timestamp${NC}"
}
#######################################
# Select stack
#######################################
select_stack() {
print_section "Step 3: Select Stack to Restore"
local backup_dir="$BACKUP_BASE/$selected_hostname/$selected_timestamp"
local -a stacks
local i=1
for backup_file in "$backup_dir"/*.tar.gz; do
if [[ -f "$backup_file" ]]; then
local stack_name=$(basename "$backup_file" .tar.gz)
stacks+=("$stack_name")
fi
done
if [[ ${#stacks[@]} -eq 0 ]]; then
log_error "No stack backups found"
exit 1
fi
echo "Available stacks:"
for stack in "${stacks[@]}"; do
local size=$(du -h "$backup_dir/${stack}.tar.gz" | cut -f1)
echo -e " ${GREEN}$i)${NC} $stack (${size})"
((i++))
done
echo ""
local selection=$(prompt_input "Select stack number" "1")
if [[ ! "$selection" =~ ^[0-9]+$ ]] || [[ $selection -lt 1 ]] || [[ $selection -gt ${#stacks[@]} ]]; then
log_error "Invalid selection"
exit 1
fi
selected_stack="${stacks[$((selection-1))]}"
selected_backup_file="$backup_dir/${selected_stack}.tar.gz"
echo -e "\n${GREEN}✓${NC} Selected stack: ${BOLD}$selected_stack${NC}"
}
#######################################
# Preview backup contents
#######################################
preview_backup() {
print_section "Step 4: Preview Backup Contents"
echo "Contents of backup:"
echo -e "${BLUE}─────────────────────────────────────────────────────────${NC}"
tar -tzf "$selected_backup_file" | head -20
local total_files=$(tar -tzf "$selected_backup_file" | wc -l)
if [[ $total_files -gt 20 ]]; then
echo -e "${YELLOW}... and $((total_files - 20)) more files${NC}"
fi
echo -e "${BLUE}─────────────────────────────────────────────────────────${NC}\n"
if ! prompt_continue "Proceed with restore?"; then
echo "Restore cancelled."
exit 0
fi
}
#######################################
# Check for conflicts
#######################################
check_conflicts() {
print_section "Step 5: Check for Conflicts"
local stack_dir="$DOCKHAND_BASE/$selected_hostname/$selected_stack"
local appdata_dir="$APPDATA_PATH/$selected_stack"
local has_conflicts=false
# Check if stack directory exists
if [[ -d "$stack_dir" ]]; then
log_warning "Stack directory already exists: $stack_dir"
has_conflicts=true
# Check if stack is running
if (cd "$stack_dir" && docker compose ps --services --filter "status=running" 2>/dev/null | grep -q .); then
log_warning "Stack has running containers!"
has_conflicts=true
fi
fi
# Check if appdata exists
if [[ -d "$appdata_dir" ]]; then
local appdata_size=$(du -sh "$appdata_dir" | cut -f1)
log_warning "Appdata directory already exists: $appdata_dir ($appdata_size)"
has_conflicts=true
fi
if [[ "$has_conflicts" == true ]]; then
echo -e "\n${YELLOW}⚠ Conflicts detected!${NC}\n"
echo "Choose how to proceed:"
echo -e " ${GREEN}1)${NC} Stop containers and overwrite everything (destructive)"
echo -e " ${GREEN}2)${NC} Backup existing data first, then restore"
echo -e " ${GREEN}3)${NC} Cancel restore"
local choice=$(prompt_input "Select option" "3")
case $choice in
1)
echo -e "\n${RED}⚠ WARNING: This will permanently overwrite existing data!${NC}"
if ! prompt_continue "Are you absolutely sure?"; then
echo "Restore cancelled."
exit 0
fi
restore_mode="overwrite"
;;
2)
restore_mode="backup_first"
;;
3|*)
echo "Restore cancelled."
exit 0
;;
esac
else
echo -e "${GREEN}✓${NC} No conflicts detected"
restore_mode="clean"
fi
}
#######################################
# Perform restore
#######################################
perform_restore() {
print_section "Step 6: Performing Restore"
local stack_dir="$DOCKHAND_BASE/$selected_hostname/$selected_stack"
local appdata_dir="$APPDATA_PATH/$selected_stack"
local temp_restore=$(mktemp -d)
trap "rm -rf '$temp_restore'" RETURN
# Handle existing data based on mode
if [[ "$restore_mode" == "backup_first" ]]; then
local safety_backup_dir="/tmp/docker-restore-backup-$(date +%Y%m%d_%H%M%S)"
mkdir -p "$safety_backup_dir"
log "Creating safety backup in $safety_backup_dir"
if [[ -d "$stack_dir" ]]; then
cp -a "$stack_dir" "$safety_backup_dir/stack"
fi
if [[ -d "$appdata_dir" ]]; then
cp -a "$appdata_dir" "$safety_backup_dir/appdata"
fi
log_success "Safety backup created"
fi
# Stop existing containers if any
if [[ -d "$stack_dir" ]]; then
log "Stopping existing stack"
(cd "$stack_dir" && docker compose down 2>/dev/null) || true
fi
# Extract backup to temp directory
log "Extracting backup..."
tar -xzf "$selected_backup_file" -C "$temp_restore"
# Restore compose files
log "Restoring stack configuration..."
mkdir -p "$stack_dir"
if [[ -f "$temp_restore/docker-compose.yml" ]]; then
cp "$temp_restore/docker-compose.yml" "$stack_dir/"
fi
if [[ -f "$temp_restore/.env" ]]; then
cp "$temp_restore/.env" "$stack_dir/"
fi
# Restore appdata
log "Restoring appdata..."
if [[ -d "$appdata_dir" ]]; then
rm -rf "$appdata_dir"
fi
if [[ -d "$temp_restore/$selected_stack" ]]; then
cp -a "$temp_restore/$selected_stack" "$APPDATA_PATH/"
fi
log_success "Files restored successfully"
# Ask about starting stack
echo ""
if prompt_continue "Start the stack now?"; then
log "Starting stack..."
if (cd "$stack_dir" && docker compose up -d); then
log_success "Stack started successfully"
echo -e "\n${GREEN}Container status:${NC}"
(cd "$stack_dir" && docker compose ps)
else
log_error "Failed to start stack"
return 1
fi
else
echo -e "\n${YELLOW}Stack not started. You can start it manually with:${NC}"
echo " cd $stack_dir && docker compose up -d"
fi
}
#######################################
# Main function
#######################################
main() {
print_header
log "========================================="
log "Starting Docker stack restore wizard"
log "Current Host: $HOSTNAME"
log "OS: $OS_NAME ($OS_TYPE)"
log "========================================="
# Check if running as root
if [[ $EUID -ne 0 ]]; then
log_error "This script must be run as root"
exit 1
fi
# Check if backup directory exists
if [[ ! -d "$BACKUP_BASE" ]]; then
log_error "Backup directory not found: $BACKUP_BASE"
exit 1
fi
# Interactive selection process
select_hostname
select_timestamp
select_stack
preview_backup
check_conflicts
perform_restore
print_section "Restore Complete!"
log_success "Stack '$selected_stack' has been restored from backup"
echo -e "\n${GREEN}✓ All done!${NC}\n"
log "========================================="
log "Restore completed successfully"
log "========================================="
}
# Run main function
main "$@"