-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker-stack-backup.sh
More file actions
1153 lines (964 loc) · 34 KB
/
docker-stack-backup.sh
File metadata and controls
1153 lines (964 loc) · 34 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
#######################################
# Docker Compose Stack Backup Script
# Backs up Docker Compose stacks that have appdata bind mounts
#######################################
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
# Dry-run mode flag
DRY_RUN=false
# Configuration
DOCKHAND_BASE="/opt/dockhand/stacks" # Base path where Dockhand stores stacks (hostname will be appended)
HOSTNAME=$(hostname)
APPDATA_PATH="/mnt/datastor/appdata" # Path where stack appdata is stored
BACKUP_DEST="/mnt/backup/docker-backups" # Destination on TrueNAS
LOG_FILE="/var/log/docker-backup.log"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
# Compression Configuration
COMPRESSION_METHOD="none" # Options: gzip, bzip2, xz, zstd, none
COMPRESSION_LEVEL=6 # 1-9: 1=fastest/largest, 9=slowest/smallest (for gzip/bzip2/xz)
USE_PARALLEL=false # Use parallel compression (pigz/pbzip2/pxz) - faster on multi-core systems
PARALLEL_THREADS=0 # 0=auto-detect cores, or specify number (e.g., 4)
# Exclude patterns (relative to appdata directory)
EXCLUDE_PATTERNS=(
# "*/cache/*"
# "*/tmp/*"
# "*.log"
# "*/Trash/*"
)
# Notification Configuration
NOTIFY_ON_SUCCESS=true # Send notification when backup succeeds
NOTIFY_ON_FAILURE=true # Send notification when backup fails
# Ntfy (https://ntfy.sh)
NTFY_ENABLED=false
NTFY_URL="https://ntfy.sh" # Use your own server or ntfy.sh
NTFY_TOPIC="docker-backups" # Your topic name
NTFY_PRIORITY="default" # min, low, default, high, urgent
NTFY_TOKEN="" # Optional: for authenticated topics
# Pushover (https://pushover.net)
PUSHOVER_ENABLED=false
PUSHOVER_USER_KEY="" # Your user key
PUSHOVER_API_TOKEN="" # Your application API token
PUSHOVER_PRIORITY=0 # -2=lowest, -1=low, 0=normal, 1=high, 2=emergency
# Email
EMAIL_ENABLED=false
EMAIL_TO="" # Destination email address
EMAIL_FROM="docker-backup@$HOSTNAME" # From address
EMAIL_SUBJECT_PREFIX="[Docker Backup]" # Subject line prefix
# Email method: 'sendmail' or 'smtp'
EMAIL_METHOD="sendmail"
# SMTP settings (only needed if EMAIL_METHOD="smtp")
SMTP_SERVER="smtp.gmail.com"
SMTP_PORT="587"
SMTP_USER=""
SMTP_PASSWORD=""
SMTP_USE_TLS=true
SMTP_INSECURE=false # Set to true for self-signed certificates (e.g., Proton Mail Bridge)
# Colors for output
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' # No Color
#######################################
# 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"
}
#######################################
# File locking functions
#######################################
LOCK_FILE="/var/run/docker-stack-backup.lock"
LOCK_FD=200
acquire_lock() {
eval "exec $LOCK_FD>$LOCK_FILE"
if ! flock -n $LOCK_FD; then
log_error "Another backup is already running (lock file: $LOCK_FILE)"
log_error "If you're sure no backup is running, remove: $LOCK_FILE"
exit 1
fi
# Write PID to lock file
echo $$ >&$LOCK_FD
log "Lock acquired (PID: $$)"
}
release_lock() {
if [[ -n "${LOCK_FD:-}" ]]; then
flock -u $LOCK_FD 2>/dev/null || true
rm -f "$LOCK_FILE" 2>/dev/null || true
log "Lock released"
fi
}
# Ensure lock is released on exit
trap release_lock EXIT INT TERM
#######################################
# Pre-flight checks
#######################################
check_docker_running() {
if ! systemctl is-active --quiet docker 2>/dev/null && ! pgrep -x dockerd >/dev/null 2>&1; then
log_error "Docker daemon is not running"
log_error "Start with: systemctl start docker"
return 1
fi
if ! docker info >/dev/null 2>&1; then
log_error "Docker daemon not responding"
return 1
fi
log "✓ Docker daemon is running"
return 0
}
check_disk_space() {
local path="$1"
local min_free_gb="${2:-5}" # Default: require 5GB free
# Create directory if it doesn't exist
mkdir -p "$path" 2>/dev/null || true
if [[ ! -d "$path" ]]; then
log_error "Backup destination does not exist: $path"
return 1
fi
# Get available space in GB
local available_kb=$(df -k "$path" | awk 'NR==2 {print $4}')
local available_gb=$((available_kb / 1024 / 1024))
if [[ $available_gb -lt $min_free_gb ]]; then
log_error "Insufficient disk space on $path"
log_error "Available: ${available_gb}GB, Required: ${min_free_gb}GB"
return 1
fi
log "✓ Disk space: ${available_gb}GB available on $path"
return 0
}
check_mount_point() {
local path="$1"
# Check if path is accessible
if [[ ! -d "$path" ]]; then
log_warning "Path does not exist: $path (will be created)"
return 0
fi
# Check if we can write to it
if ! touch "$path/.write-test" 2>/dev/null; then
log_error "Cannot write to $path"
log_error "Check permissions and mount status"
return 1
fi
rm -f "$path/.write-test"
# Check if it's a mount point (optional, informational)
if mountpoint -q "$path" 2>/dev/null; then
log "✓ $path is a mount point ($(df -h "$path" | awk 'NR==2 {print $1}')"
else
log "✓ $path is accessible (local filesystem)"
fi
return 0
}
check_required_paths() {
log "Checking required paths..."
# Check Dockhand directory
local stack_base="$DOCKHAND_BASE/$HOSTNAME"
if [[ ! -d "$stack_base" ]]; then
log_error "Dockhand directory not found: $stack_base"
return 1
fi
log "✓ Dockhand directory exists: $stack_base"
# Check appdata directory
if [[ ! -d "$APPDATA_PATH" ]]; then
log_error "Appdata directory not found: $APPDATA_PATH"
return 1
fi
log "✓ Appdata directory exists: $APPDATA_PATH"
return 0
}
run_preflight_checks() {
log "========================================="
log "Running pre-flight checks..."
log "========================================="
local checks_passed=true
# Check Docker
if ! check_docker_running; then
checks_passed=false
fi
# Check required paths
if ! check_required_paths; then
checks_passed=false
fi
# Check backup destination
if ! check_mount_point "$BACKUP_DEST"; then
checks_passed=false
fi
# Check disk space (require at least 5GB free)
if ! check_disk_space "$BACKUP_DEST" 5; then
checks_passed=false
fi
if [[ "$checks_passed" == false ]]; then
log_error "Pre-flight checks failed!"
return 1
fi
log "========================================="
log "✓ All pre-flight checks passed"
log "========================================="
return 0
}
#######################################
# Improved restart error handling
#######################################
MAX_RESTART_ATTEMPTS=3
RESTART_RETRY_DELAY=5 # seconds
restart_stack_with_retry() {
local stack_path="$1"
local stack_name=$(basename "$stack_path")
local running_containers="$2"
local attempt=1
while [[ $attempt -le $MAX_RESTART_ATTEMPTS ]]; do
log "Starting containers (attempt $attempt/$MAX_RESTART_ATTEMPTS)..."
if (cd "$stack_path" && docker compose up -d $running_containers 2>&1 | tee -a "$LOG_FILE"); then
# Verify containers actually started
sleep 2
local started_count=$(cd "$stack_path" && docker compose ps --services --filter "status=running" 2>/dev/null | wc -l)
local expected_count=$(echo "$running_containers" | wc -w)
if [[ $started_count -eq $expected_count ]]; then
log_success "All containers started successfully"
return 0
else
log_warning "Only $started_count of $expected_count containers started"
fi
fi
if [[ $attempt -lt $MAX_RESTART_ATTEMPTS ]]; then
log_warning "Restart failed, waiting ${RESTART_RETRY_DELAY}s before retry..."
sleep $RESTART_RETRY_DELAY
fi
((attempt++))
done
log_error "Failed to restart stack after $MAX_RESTART_ATTEMPTS attempts"
log_error "Stack: $stack_name"
log_error "Containers that should be running: $running_containers"
log_error "Manual intervention required!"
log_error "To restart manually: cd $stack_path && docker compose up -d $running_containers"
# Send immediate critical notification
send_critical_restart_failure "$stack_name" "$stack_path" "$running_containers"
return 1
}
send_critical_restart_failure() {
local stack_name="$1"
local stack_path="$2"
local containers="$3"
local title="CRITICAL: Stack Failed to Restart - $HOSTNAME"
local message="Stack '$stack_name' failed to restart after backup!
⚠️ IMMEDIATE ACTION REQUIRED ⚠️
Stack: $stack_name
Host: $HOSTNAME
Containers: $containers
Manual restart command:
cd $stack_path && docker compose up -d $containers
Check logs:
$LOG_FILE"
# Send with high priority regardless of normal settings
if [[ "$NTFY_ENABLED" == true ]]; then
send_ntfy "$title" "$message" "urgent" "warning,backup"
fi
if [[ "$PUSHOVER_ENABLED" == true ]]; then
send_pushover "$title" "$message" 1 # High priority
fi
if [[ "$EMAIL_ENABLED" == true ]]; then
send_email "[CRITICAL] $title" "$message"
fi
}
#######################################
# Notification functions
#######################################
send_ntfy() {
if [[ "$NTFY_ENABLED" != true ]]; then
return 0
fi
local title="$1"
local message="$2"
local priority="${3:-$NTFY_PRIORITY}"
local tags="${4:-backup}"
local curl_args=(
-X POST
-H "Title: $title"
-H "Priority: $priority"
-H "Tags: $tags"
-d "$message"
)
if [[ -n "$NTFY_TOKEN" ]]; then
curl_args+=(-H "Authorization: Bearer $NTFY_TOKEN")
fi
if ! curl -s "${curl_args[@]}" "$NTFY_URL/$NTFY_TOPIC" >/dev/null 2>&1; then
log_error "Failed to send Ntfy notification"
fi
}
send_pushover() {
if [[ "$PUSHOVER_ENABLED" != true ]]; then
return 0
fi
if [[ -z "$PUSHOVER_USER_KEY" ]] || [[ -z "$PUSHOVER_API_TOKEN" ]]; then
log_error "Pushover enabled but USER_KEY or API_TOKEN not configured"
return 1
fi
local title="$1"
local message="$2"
local priority="${3:-$PUSHOVER_PRIORITY}"
if ! curl -s \
--form-string "token=$PUSHOVER_API_TOKEN" \
--form-string "user=$PUSHOVER_USER_KEY" \
--form-string "title=$title" \
--form-string "message=$message" \
--form-string "priority=$priority" \
https://api.pushover.net/1/messages.json >/dev/null 2>&1; then
log_error "Failed to send Pushover notification"
fi
}
send_email_sendmail() {
local subject="$1"
local body="$2"
if ! command -v sendmail &> /dev/null; then
log_error "sendmail not found. Install with: apt-get install sendmail or postfix"
return 1
fi
(
echo "To: $EMAIL_TO"
echo "From: $EMAIL_FROM"
echo "Subject: $subject"
echo ""
echo "$body"
) | sendmail -t
}
send_email_smtp() {
local subject="$1"
local body="$2"
if ! command -v curl &> /dev/null; then
log_error "curl not found for SMTP email"
return 1
fi
local smtp_url="smtp://$SMTP_SERVER:$SMTP_PORT"
if [[ "$SMTP_USE_TLS" == true ]]; then
smtp_url="smtps://$SMTP_SERVER:$SMTP_PORT"
fi
local email_content=$(cat <<EOF
From: $EMAIL_FROM
To: $EMAIL_TO
Subject: $subject
$body
EOF
)
local curl_args=(
--url "$smtp_url"
--mail-from "$EMAIL_FROM"
--mail-rcpt "$EMAIL_TO"
--upload-file -
)
# Add authentication if credentials provided
if [[ -n "$SMTP_USER" ]] && [[ -n "$SMTP_PASSWORD" ]]; then
curl_args+=(--user "$SMTP_USER:$SMTP_PASSWORD")
fi
# Handle self-signed certificates
if [[ "${SMTP_INSECURE:-false}" == true ]]; then
curl_args+=(--insecure)
fi
if ! echo "$email_content" | curl -s "${curl_args[@]}" >/dev/null 2>&1; then
log_error "Failed to send email via SMTP"
return 1
fi
}
send_email() {
if [[ "$EMAIL_ENABLED" != true ]]; then
return 0
fi
if [[ -z "$EMAIL_TO" ]]; then
log_error "Email enabled but EMAIL_TO not configured"
return 1
fi
local subject="$1"
local body="$2"
case "$EMAIL_METHOD" in
sendmail)
send_email_sendmail "$subject" "$body"
;;
smtp)
send_email_smtp "$subject" "$body"
;;
*)
log_error "Unknown email method: $EMAIL_METHOD"
return 1
;;
esac
}
send_notifications() {
local status="$1" # "success" or "failure"
local backed_up="$2"
local skipped="$3"
local failed="$4"
local total="$5"
# Check if we should send notification
if [[ "$status" == "success" ]] && [[ "$NOTIFY_ON_SUCCESS" != true ]]; then
return 0
fi
if [[ "$status" == "failure" ]] && [[ "$NOTIFY_ON_FAILURE" != true ]]; then
return 0
fi
# Build notification content
local title
local message
local priority
local tags
if [[ "$status" == "success" ]]; then
title="Docker Backup Complete - $HOSTNAME"
priority="default"
tags="white_check_mark,backup"
message="Backup completed successfully
✓ Successfully backed up: $backed_up
⊘ Skipped (no appdata): $skipped
✗ Failed: $failed
━━━━━━━━━━━━━━━━━━━━
Total stacks: $total
Host: $HOSTNAME
Time: $(date +'%Y-%m-%d %H:%M:%S')"
else
title="Docker Backup FAILED - $HOSTNAME"
priority="high"
tags="x,backup,warning"
message="Backup completed with errors
✓ Successfully backed up: $backed_up
⊘ Skipped (no appdata): $skipped
✗ FAILED: $failed
━━━━━━━━━━━━━━━━━━━━
Total stacks: $total
Host: $HOSTNAME
Time: $(date +'%Y-%m-%d %H:%M:%S')
Check logs: $LOG_FILE"
fi
# Send to all enabled services
send_ntfy "$title" "$message" "$priority" "$tags"
send_pushover "$title" "$message" "$([ "$status" == "failure" ] && echo 1 || echo 0)"
send_email "$EMAIL_SUBJECT_PREFIX $title" "$message"
}
#######################################
# Compression functions
#######################################
get_compression_extension() {
case "$COMPRESSION_METHOD" in
gzip) echo ".tar.gz" ;;
bzip2) echo ".tar.bz2" ;;
xz) echo ".tar.xz" ;;
zstd) echo ".tar.zst" ;;
none) echo ".tar" ;;
*) echo ".tar.gz" ;;
esac
}
get_tar_compression_flag() {
if [[ "$USE_PARALLEL" == true ]]; then
echo "" # We'll handle compression separately with parallel tools
else
case "$COMPRESSION_METHOD" in
gzip) echo "z" ;;
bzip2) echo "j" ;;
xz) echo "J" ;;
zstd) echo "--zstd" ;;
none) echo "" ;;
*) echo "z" ;;
esac
fi
}
check_compression_tool() {
local tool="$1"
if ! command -v "$tool" &> /dev/null; then
log_warning "$tool not found. Install with: apt-get install $tool"
return 1
fi
return 0
}
setup_compression_environment() {
# Set compression level environment variable
case "$COMPRESSION_METHOD" in
gzip)
export GZIP="-${COMPRESSION_LEVEL}"
;;
bzip2)
export BZIP2="-${COMPRESSION_LEVEL}"
;;
xz)
export XZ_OPT="-${COMPRESSION_LEVEL}"
;;
esac
}
create_compressed_archive() {
local output_file="$1"
shift
local tar_args=("$@")
setup_compression_environment
# Build exclude arguments
local exclude_args=()
for pattern in "${EXCLUDE_PATTERNS[@]}"; do
exclude_args+=(--exclude="$pattern")
done
if [[ "$USE_PARALLEL" == true ]]; then
# Use parallel compression
local compressor=""
local compressor_args=()
case "$COMPRESSION_METHOD" in
gzip)
if check_compression_tool pigz; then
compressor="pigz"
compressor_args=("-${COMPRESSION_LEVEL}")
if [[ $PARALLEL_THREADS -gt 0 ]]; then
compressor_args+=("-p" "$PARALLEL_THREADS")
fi
else
log_warning "pigz not found, falling back to standard gzip"
USE_PARALLEL=false
fi
;;
bzip2)
if check_compression_tool pbzip2; then
compressor="pbzip2"
compressor_args=("-${COMPRESSION_LEVEL}")
if [[ $PARALLEL_THREADS -gt 0 ]]; then
compressor_args+=("-p${PARALLEL_THREADS}")
fi
else
log_warning "pbzip2 not found, falling back to standard bzip2"
USE_PARALLEL=false
fi
;;
xz)
if check_compression_tool pxz; then
compressor="pxz"
compressor_args=("-${COMPRESSION_LEVEL}")
if [[ $PARALLEL_THREADS -gt 0 ]]; then
compressor_args+=("-T${PARALLEL_THREADS}")
fi
else
log_warning "pxz not found, falling back to standard xz"
USE_PARALLEL=false
fi
;;
zstd)
if check_compression_tool zstd; then
compressor="zstd"
compressor_args=("-${COMPRESSION_LEVEL}")
if [[ $PARALLEL_THREADS -gt 0 ]]; then
compressor_args+=("-T${PARALLEL_THREADS}")
fi
else
log_error "zstd not found"
return 1
fi
;;
none)
# No compression needed
tar -cf "$output_file" "${exclude_args[@]}" "${tar_args[@]}"
return $?
;;
esac
if [[ "$USE_PARALLEL" == true ]] && [[ -n "$compressor" ]]; then
tar -c "${exclude_args[@]}" "${tar_args[@]}" | "$compressor" "${compressor_args[@]}" > "$output_file"
return $?
fi
fi
# Fall back to standard tar compression
local compression_flag=$(get_tar_compression_flag)
if [[ "$compression_flag" == "--zstd" ]]; then
# zstd uses different syntax
if ! check_compression_tool zstd; then
log_error "zstd compression selected but zstd not found"
return 1
fi
tar -c $compression_flag -f "$output_file" "${exclude_args[@]}" "${tar_args[@]}"
elif [[ -n "$compression_flag" ]]; then
tar -c${compression_flag}f "$output_file" "${exclude_args[@]}" "${tar_args[@]}"
else
tar -cf "$output_file" "${exclude_args[@]}" "${tar_args[@]}"
fi
return $?
}
#######################################
# Check if stack has appdata bind mounts
#######################################
#######################################
# Check if stack has appdata bind mounts
#######################################
find_compose_file() {
local stack_path="$1"
# Check for various compose file names (in order of preference)
local possible_names=(
"compose.yaml"
"compose.yml"
"docker-compose.yaml"
"docker-compose.yml"
)
for name in "${possible_names[@]}"; do
if [[ -f "$stack_path/$name" ]]; then
echo "$stack_path/$name"
return 0
fi
done
return 1
}
stack_has_appdata() {
local compose_file="$1"
if [[ ! -f "$compose_file" ]]; then
return 1
fi
# Check if any volume is a bind mount to APPDATA_PATH
if grep -q "$APPDATA_PATH" "$compose_file"; then
return 0
fi
return 1
}
#######################################
# Dry-run backup simulation
#######################################
simulate_backup_stack() {
local stack_path="$1"
local stack_name=$(basename "$stack_path")
# Find compose file
local compose_file=$(find_compose_file "$stack_path")
if [[ -z "$compose_file" ]]; then
return 2 # Skip - no compose file
fi
# Check if stack has appdata
if ! stack_has_appdata "$compose_file"; then
return 2 # Skip
fi
local appdata_dir="$APPDATA_PATH/$stack_name"
if [[ ! -d "$appdata_dir" ]]; then
return 2 # Skip
fi
# Get appdata size
local size=$(du -sh "$appdata_dir" 2>/dev/null | cut -f1)
local size_bytes=$(du -sb "$appdata_dir" 2>/dev/null | cut -f1)
# Get running containers
local running_count=0
if (cd "$stack_path" && docker compose ps --services --filter "status=running" 2>/dev/null | grep -q .); then
running_count=$(cd "$stack_path" && docker compose ps --services --filter "status=running" 2>/dev/null | wc -l) || running_count=0
fi
# Output stack info
if [[ $running_count -gt 0 ]]; then
echo " ${GREEN}✓${NC} $stack_name ($size appdata, $running_count running)"
else
echo " ${YELLOW}○${NC} $stack_name ($size appdata, stopped)"
fi
# Return size in bytes for calculation
echo "$size_bytes" > /tmp/stack_size_$$
return 0 # Success
}
#######################################
# Backup a single stack
#######################################
backup_stack() {
local stack_path="$1"
local stack_name=$(basename "$stack_path")
# Find compose file
local compose_file=$(find_compose_file "$stack_path")
if [[ -z "$compose_file" ]]; then
log_warning "No compose file found for stack $stack_name"
return 0
fi
log "Processing stack: $stack_name"
# Check if stack has appdata
if ! stack_has_appdata "$compose_file"; then
log_warning "Stack $stack_name has no appdata bind mounts, skipping"
return 2 # Return 2 for skipped
fi
local appdata_dir="$APPDATA_PATH/$stack_name"
# Check if appdata directory exists or if it has subdirectories
# (some stacks have container-specific folders like dashboards/heimdall, dashboards/homepage)
if [[ ! -d "$appdata_dir" ]]; then
log_warning "Appdata directory $appdata_dir not found for stack $stack_name"
return 2 # Return 2 for skipped
fi
# Check if directory has any content (direct files or subdirectories)
if [[ -z "$(ls -A "$appdata_dir" 2>/dev/null)" ]]; then
log_warning "Appdata directory $appdata_dir is empty for stack $stack_name"
return 0
fi
# Create backup directory structure
local backup_dir="$BACKUP_DEST/$HOSTNAME/$TIMESTAMP"
mkdir -p "$backup_dir"
local backup_ext=$(get_compression_extension)
local backup_file="$backup_dir/${stack_name}${backup_ext}"
# Get list of running containers before stopping
log "Checking container states for stack: $stack_name"
local running_containers=$(cd "$stack_path" && docker compose ps --services --filter "status=running" 2>/dev/null || true)
if [[ -z "$running_containers" ]]; then
log_warning "No running containers in stack $stack_name, skipping backup"
return 0
fi
log "Running containers: $(echo "$running_containers" | tr '\n' ', ' | sed 's/,$//')"
log "Stopping stack: $stack_name"
if ! (cd "$stack_path" && docker compose down); then
log_error "Failed to stop stack $stack_name"
return 1
fi
log "Creating backup: $backup_file"
# Create a temporary directory for organizing backup contents
local temp_dir=$(mktemp -d)
trap "rm -rf '$temp_dir'" RETURN
# Copy compose file to temp directory
cp "$compose_file" "$temp_dir/"
# Copy any other files in the stack directory (env files, etc)
if [[ -f "$stack_path/.env" ]]; then
cp "$stack_path/.env" "$temp_dir/"
fi
# Create archive with configured compression
log "Creating ${COMPRESSION_METHOD} compressed backup (level ${COMPRESSION_LEVEL})..."
if [[ "$USE_PARALLEL" == true ]]; then
log "Using parallel compression"
fi
if create_compressed_archive "$backup_file" \
-C "$temp_dir" . \
-C "$APPDATA_PATH" "$stack_name" 2>&1 | tee -a "$LOG_FILE"; then
log_success "Backup created: $backup_file"
else
log_error "Failed to create backup for $stack_name"
# Restore only previously running containers
if [[ -n "$running_containers" ]]; then
log "Restoring previously running containers"
(cd "$stack_path" && docker compose up -d $running_containers)
fi
return 1
fi
# Start only the containers that were running before
# Docker Compose will automatically start any dependencies even if they weren't running
if [[ -n "$running_containers" ]]; then
log "Starting previously running containers: $(echo "$running_containers" | tr '\n' ', ' | sed 's/,$//')"
log "(Docker Compose will auto-start any dependencies as needed)"
if ! restart_stack_with_retry "$stack_path" "$running_containers"; then
# restart_stack_with_retry already logged and notified
return 1
fi
else
log "No containers to restart (none were running before backup)"
fi
log_success "Stack $stack_name backed up and restarted successfully"
return 0
}
#######################################
# Main function
#######################################
main() {
# Parse command line arguments
while [[ $# -gt 0 ]]; do
case $1 in
--dry-run|--dryrun|-n)
DRY_RUN=true
shift
;;
--help|-h)
echo "Usage: $0 [OPTIONS]"
echo ""
echo "Options:"
echo " --dry-run, -n Simulate backup without making changes"
echo " --help, -h Show this help message"
echo ""
echo "Examples:"
echo " $0 Run backup normally"
echo " $0 --dry-run Show what would be backed up"
exit 0
;;
*)
log_error "Unknown option: $1"
log_error "Use --help for usage information"
exit 1
;;
esac
done
if [[ "$DRY_RUN" == true ]]; then
echo -e "${BOLD}${CYAN}=========================================${NC}"
echo -e "${BOLD}${CYAN}DRY RUN MODE - No changes will be made${NC}"
echo -e "${BOLD}${CYAN}=========================================${NC}\n"
fi
log "========================================="
if [[ "$DRY_RUN" == true ]]; then
log "DRY RUN: Docker stack backup simulation"
else
log "Starting Docker stack backup"
fi
log "Hostname: $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
# Acquire lock to prevent concurrent runs (skip in dry-run)
if [[ "$DRY_RUN" != true ]]; then
acquire_lock
fi