-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBackup.sh
More file actions
executable file
·2135 lines (1877 loc) · 111 KB
/
Backup.sh
File metadata and controls
executable file
·2135 lines (1877 loc) · 111 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
# Backup Script for Directories with Special Focus on Docker and Its Databases
#
# Description:
# This script is designed to automate the backup process for directories on a Linux-based server,
# with special attention to Docker containers and their associated databases. It was created to provide
# a reliable, flexible, and efficient way to safeguard critical data from directories and Dockerized
# applications, ensuring easy restoration when needed.
#
# Key Features:
# - Backs up important directories and Docker databases, including PostgreSQL, MySQL, Redis, and more.
# - Provides the option to encrypt backups using AES-256 encryption for enhanced data security.
# - Implements the "1-2-3" backup strategy, copying backups to multiple locations for redundancy.
# - Allows for stopping and restarting Docker services to ensure consistent database snapshots.
# - Sends detailed backup reports via email, covering backup status, sizes, durations, and verification results.
# - Utilizes CPU parallelism for efficient compression, optimizing backup times on systems with multiple cores.
# - Offers customizable retention policies to automatically clean up old backups after a specified number of days.
# - Automatically detects the Linux distribution and installs required packages.
# - Supported distributions include Ubuntu, Debian, CentOS, RHEL, Fedora, and Arch Linux.
#
# Why This Script Was Created:
# This script was created to simplify and automate the process of backing up critical directories and Dockerized
# applications, particularly their databases. By handling these tasks automatically, the script minimizes the risk
# of data loss, reduces downtime in case of failures, and ensures that backups are performed consistently and securely.
#
# The script is highly customizable, allowing users to define backup directories, email configurations, and encryption
# preferences. It’s an ideal solution for system administrators who need a powerful tool to protect data and ensure
# disaster recovery, with a special focus on Docker environments.
# Variable for naming the backup that will be sent via email
# • Example: BACKUP_NAME="Docker-Compose, /etc, Databases"
# • You can change the name to reflect the content of your backup.
# • If you are backing up specific directories or databases, you can include their names in the BACKUP_NAME.
BACKUP_NAME=""
# Variable for the Server name
# • This variable stores the name of the server where the backup script is running.
# • Example: SERVER_NAME="HOME SERVER"
# • This can be customized to any server name that makes sense for your environment, and it will be included in email notifications.
SERVER_NAME=""
# Variable to enable backup encryption
# • This variable is used to determine whether to encrypt the backup files.
# • Values: "Y" or "N".
# • If you set ENCRYPT_BACKUP="Y", the backup will be encrypted with AES-256. If set to "N", no encryption will be applied.
ENCRYPT_BACKUP="Y"
# Default variables for the source directories
# • This is an array of directories you wish to back up.
# • Example: SOURCE_DIRS=( "/home/JohnDoe" "/etc" )
# • You can add multiple directories by separating each path with a space. Make sure each path points to valid directories you want to back up.
SOURCE_DIRS=(
"/home/JohnDoe"
"/etc"
)
# Default variables for exlude directories
# • This is an array of directories you want to exclude from the backup.
# • Example: EXCLUDE_DIRS=( "/home/JohnDoe/Personal" )
# • You can leave this array empty if you do not want to exclude any directories, or add paths you want to skip.
EXCLUDE_DIRS=(
"/home/JohnDoe/Personal"
)
# Backup destination directory
# • This is the destination directory where the backups will be stored.
# • Example: BACKUP_DIR="/media/nvme/1TB/BACKUP"
# • This should point to the directory where you have sufficient storage space for backups.
BACKUP_DIR=""
# Log file for the backup script
LOG_FILE="$BACKUP_DIR/Compose.log"
# Email Configuration Variables
# • EMAIL_RECIPIENT: The email address to which the backup report will be sent. Example: EMAIL_RECIPIENT="JohnDoe@icloud.com"
# • SMTP Configuration Variables (SMTP_HOST, SMTP_PORT, SMTP_FROM, SMTP_USER, SMTP_PASSWORD):
# • These variables define the SMTP configuration needed to send emails.
# • Example:
# • SMTP_HOST="smtp.mail.me.com" (The SMTP server for sending emails)
# • SMTP_PORT="587" (The port for SMTP, typically 587 for TLS)
# • SMTP_FROM="JohnDoe@icloud.com" (The email address from which the email will be sent)
# • SMTP_USER="JohnDoe@icloud.com" (SMTP username, often the same as the sender’s email)
# • SMTP_PASSWORD="your-password" (Password for SMTP authentication) The app-specific password generated from iCloud*
EMAIL_RECIPIENT=""
SMTP_HOST=""
SMTP_PORT=""
SMTP_FROM=""
SMTP_USER=""
SMTP_PASSWORD=""
# Variable to define how many days to retain backups, Change the number of days as needed
# • This defines how many days to retain the backup files before they are automatically deleted.
# • Example: DAYS_TO_KEEP=6
# • You can adjust the number of days to suit your retention policy.
DAYS_TO_KEEP=6
# Variable to stop Docker before the backup
# • This variable controls whether Docker containers should be stopped before starting the backup.
# • Values: "Y" or "N".
# • Set it to "Y" if you want Docker services to stop before the backup (useful when you are backing up Docker data).
STOP_DOCKER_BEFORE_BACKUP="Y"
# Variable to enable database backup
# • This controls whether Docker databases should be backed up.
# • Values: "Y" or "N".
# • If set to "Y", the script will perform backups of the databases listed in the DATABASES variable.
BACKUP_DOCKER_DATABASE="Y"
# Backup destination database directory
# • The destination directory where database backups will be stored.
# • Example: BACKUP_DATABASE_DIR="/media/nvme/1TB/BACKUP/backup_databases"
# • Make sure this points to a directory with enough space to store database backups.
BACKUP_DATABASE_DIR=""
# List of databases to back up; in the logic of DB | CONTAINER-NAME | DB-NAME | DB-USER-NAME | DB-PASSWORD. Example follows below.
# • This is an array listing all the databases to be backed up. The format is:
# • DB_TYPE|CONTAINER_NAME|DB_NAME|DB_USER|DB_PASSWORD
# • Example: DATABASES=( "PostgreSQL|Joplin-Postgress|joplindb|joplin|joplin"
# • You can add multiple databases by separating each entry with a space. Make sure each entry is in the correct format.
# • You can find the database type, container name, database name, database user, and password by running the docker-compose ps command.
# • Make sure to replace the example values with the actual values for your databases.
# • You can leave this array empty if you do not want to back up any databases.
# • Supportoed databases: PostgreSQL, TimescaleDB, MySQL, MariaDB, MongoDB, Redis, Cassandra, Elasticsearch, SQLite, Neo4j,
# • CockroachDB, InfluxDB, Oracle, RethinkDB and Memcached.
#
## • Example:
# "PostgreSQL|Postgress-Container|postgress-db|postgress-login|postgress-pass"
# "TimescaleDB|Timescale-Container|timescaledb|timescaleuser|timescalepass"
# "MySQL|MySQLContainer|mydatabase|dbuser|password2"
# "MariaDB|MariaDBContainer|mariadb|mariauser|mariapass"
# "MongoDB|MongoContainer|mydb|mongouser|password3"
# "Redis|RedisContainer|myredisdb|redisuser|password4"
# "Cassandra|CassandraContainer|cassandradb|cassandrauser|cassandrapass"
# "Elasticsearch|ElasticContainer|elasticdb|elasticuser|elasticpass"
# "SQLite|SQLiteContainer|sqlitedb|sqliteuser|sqlitepass"
# "Neo4j|Neo4jContainer|neo4jdb|neo4juser|neo4jpass"
# "CockroachDB|CockroachContainer|cockroachdb|roachuser|roachpass"
# "InfluxDB|InfluxContainer|influxdb|influxuser|influxpass"
# "Oracle|OracleContainer|oracledb|oracleuser|oraclepass"
# "RethinkDB|RethinkDBContainer|rethinkdb|rethinkuser|rethinkpass"
# "Memcached|MemcachedContainer|memcacheddb|memcacheduser|memcachedpass"
#
DATABASES=(
"PostgreSQL|Joplin-Postgress|joplindb|joplin|joplin"
"PostgreSQL|Tesla-Postgres|teslamate|teslamate|teslamate"
"PostgreSQL|immich_postgres|immich|postgres|postgres"
"Redis|immich_redis||"
"PostgreSQL|Invidiuous-db|invidious|kemal|kemal"
)
# Variable for selecting the email template
# • This variable allows you to choose between different email templates.
# • Values: "random" or
# • "1" Dark Theme - "2" Crimson Night - "3" Cyberpunk - "4" Steel Gray - "5" Emerald Glow
# • "6" Home Lab Tech - "7" Light - "8" Midnight Blue - "9" Purple Dusk - "10" Retro Neon
MAIL_TEMPLATE="random"
# Variable to specify the maximum number of CPU cores to use for compression
# • The variable MAX_CPU_CORE allows you to define how many CPU cores should be used for compression during the backup process.
# • If you set this variable to a specific number, the script will use that many cores.
# • However, if you leave this variable unset or set it to an empty value The script will automatically detect the maximum number of available CPU cores on your system and use all of them for compression.
MAX_CPU_CORE=20
# • Controls whether the 1-2-3 backup "principle" (Working in Progress) is applied (creating multiple backup copies).
# • Values: "Y" or "N".
# • If enabled ("Y"), backups will be copied to additional storage locations defined by SATA_DISK1 and SATA_DISK2.
# • Example:
# • SATA_DISK1="/media/nvme/1TB/123-1"
# • SATA_DISK2="/media/nvme/1TB/123-2"
BACKUP_123="Y"
SATA_DISK1=""
SATA_DISK2=""
# SCP Configuration Variables
SCP_ENABLED="Y" # Set to "Y" to enable SCP backup
SCP_USER=""
SCP_USER_PASSWORD=""
SCP_HOST="" #IP Host
SCP_DEST_DIR=""
# SMB Configuration Variables
SMB_ENABLED="Y" # Set to "Y" to enable SMB backup
SMB_USER=""
SMB_PASSWORD=""
SMB_REMOTE_SERVER="" #IP Host
SMB_REMOTE_MOUNTPOINT=""
SMB_REMOTE_BACKUP=""
SMB_MOUNT_POINT=""
#####################################################################################################################################
# DO NOT EDIT BELOW THIS LINE - DO NOT EDIT BELOW THIS LINE - DO NOT EDIT BELOW THIS LINE - DO NOT EDIT BELOW THIS LINE #
# DO NOT EDIT BELOW THIS LINE - DO NOT EDIT BELOW THIS LINE - DO NOT EDIT BELOW THIS LINE - DO NOT EDIT BELOW THIS LINE #
# DO NOT EDIT BELOW THIS LINE - DO NOT EDIT BELOW THIS LINE - DO NOT EDIT BELOW THIS LINE - DO NOT EDIT BELOW THIS LINE #
# DO NOT EDIT BELOW THIS LINE - DO NOT EDIT BELOW THIS LINE - DO NOT EDIT BELOW THIS LINE - DO NOT EDIT BELOW THIS LINE #
# DO NOT EDIT BELOW THIS LINE - DO NOT EDIT BELOW THIS LINE - DO NOT EDIT BELOW THIS LINE - DO NOT EDIT BELOW THIS LINE #
#####################################################################################################################################
# Check if the script is being run as root
if [ "$EUID" -ne 0 ]; then
echo "Error: This script must be run as root user." >&2
exit 1
fi
# Function to detect the Linux distribution and install required packages
check_and_install_dependencies() {
# Identify the distribution
if [ -f /etc/os-release ]; then
. /etc/os-release
DISTRO=$ID
echo "Distro found: $DISTRO"
echo
elif [ -f /etc/lsb-release ]; then
. /etc/lsb-release
DISTRO=$DISTRIB_ID
echo "Distro found: $DISTRO"
echo
elif [ -f /etc/debian_version ]; then
DISTRO="debian"
echo "Distro found: $DISTRO"
echo
elif [ -f /etc/redhat-release ]; then
DISTRO="rhel"
echo "Distro found: $DISTRO"
echo
else
DISTRO=$(uname -s)
echo "Distro found: $DISTRO"
echo
fi
# Required packages
REQUIRED_PACKAGES="tar bc bar pigz openssl msmtp coreutils cifs-utils openssh-client sshpass smbclient"
case "$DISTRO" in
ubuntu|debian)
# Check if nala is installed
if command -v nala > /dev/null 2>&1; then
PACKAGE_MANAGER="nala"
else
PACKAGE_MANAGER="apt"
fi
# Check if packages are already installed
for pkg in $REQUIRED_PACKAGES; do
if ! dpkg -s $pkg > /dev/null 2>&1; then
echo "Installing package $pkg on $DISTRO using $PACKAGE_MANAGER..."
$PACKAGE_MANAGER update && $PACKAGE_MANAGER install -y $pkg
else
echo "$pkg is already installed."
fi
done
;;
centos|rhel|fedora)
# Check if packages are already installed
for pkg in $REQUIRED_PACKAGES; do
if ! rpm -q $pkg > /dev/null 2>&1; then
echo "Installing package $pkg on $DISTRO..."
yum install -y $pkg
else
echo "$pkg is already installed."
fi
done
;;
arch)
# Check if packages are already installed
for pkg in $REQUIRED_PACKAGES; do
if ! pacman -Qi $pkg > /dev/null 2>&1; then
echo "Installing package $pkg on $DISTRO..."
pacman -Syu --noconfirm $pkg
else
echo "$pkg is already installed."
fi
done
;;
*)
echo "Unsupported distribution: $DISTRO" >&2
exit 1
;;
esac
}
check_and_install_dependencies
# Variable to specify the maximum number of CPU cores to use for compression and decompression
# If not set, use the maximum available cores
MAX_CPU_CORE=${MAX_CPU_CORE:-$(nproc)}
# Get the number of available CPU cores
AVAILABLE_CPU_CORES=$(nproc)
# Ensure MAX_CPU_CORE does not exceed the available CPU cores
if [ "$MAX_CPU_CORE" -gt "$AVAILABLE_CPU_CORES" ]; then
MAX_CPU_CORE="$AVAILABLE_CPU_CORES"
fi
# Function to gather host statistics
gather_host_statistics() {
KERNEL_VERSION=$(uname -r)
TOTAL_MEMORY=$(free -h | grep Mem | awk '{print $2}')
USED_MEMORY=$(free -h | grep Mem | awk '{print $3}')
AVAILABLE_MEMORY=$(free -h | grep Mem | awk '{print $7}')
CPU_LOAD=$(uptime | awk -F'load average:' '{ print $2 }' | awk '{ print $1 }')
DISK_USAGE=$(df -h / | grep / | awk '{print $5}')
}
# Function to generate current date and time
CURRENT_DATE=$(date +%Y%m%d)
# Variables to accumulate backup reports
SOURCE_DIR_LIST=""
EXCLUDE_DIR_LIST=""
# Arrays to accumulate individual backup metrics
BACKUP_FILES=()
BACKUP_SIZES=()
MD5_SUMS=()
DISK_SPEEDS=()
BACKUP_DURATIONS=()
BACKUP_STARTS=()
BACKUP_ENDS=()
TEST_STATUSES=()
# Arrays to separately manage backup files for directories and databases
DIRECTORY_BACKUP_FILES=()
DATABASE_BACKUP_FILES=()
DIRECTORY_PASSWORDS=()
DATABASE_PASSWORDS=()
DATABASE_BACKUP_DETAILS=()
DATABASE_BACKUP_DURATIONS=()
DATABASE_BACKUP_STARTS=()
DATABASE_BACKUP_ENDS=()
DATABASE_TEST_STATUSES=()
# Array to store generated passwords
BACKUP_PASSWORDS=()
# Check if SOURCE_DIRS is not empty
if [ ${#SOURCE_DIRS[@]} -eq 0 ]; then
echo "Error: No source directories specified for backup." >&2
exit 1
fi
# Check if the backup directory does not exist
if [ ! -d "$BACKUP_DIR" ]; then
# Create the backup directory
mkdir -p "$BACKUP_DIR"
fi
# Check if the backup database directory does not exist
if [ ! -d "$BACKUP_DATABASE_DIR" ]; then
# Create the backup directory
mkdir -p "$BACKUP_DATABASE_DIR"
fi
# Function to check and create backup destination directories
check_and_create_directories() {
local dirs=("$@")
for dir in "${dirs[@]}"; do
if [ ! -d "$dir" ]; then
echo
echo "Directory $dir does not exist. Creating it..."
mkdir -p "$dir"
else
echo
echo "Directory $dir already exists."
echo
fi
done
}
# Function to check and create remote directory via SCP
check_and_create_scp_directory() {
sshpass -p "$SCP_USER_PASSWORD" ssh "$SCP_USER@$SCP_HOST" "mkdir -p $SCP_DEST_DIR"
}
# Function to check and create remote directory via SMB
check_and_create_smb_directory() {
# Mount the SMB share
mount_smb_share
# Construct the full path for the remote backup directory
FULL_REMOTE_PATH="${SMB_MOUNT_POINT}/${SMB_REMOTE_BACKUP}"
# Check if the remote backup directory exists
if [ ! -d "$FULL_REMOTE_PATH" ]; then
echo "Directory $FULL_REMOTE_PATH does not exist. Creating it..."
mkdir -p "$FULL_REMOTE_PATH"
if [ $? -eq 0 ]; then
echo "Directory created successfully."
else
echo "Failed to create directory."
exit 1
fi
else
echo "Directory $FULL_REMOTE_PATH already exists."
fi
}
# Function to mount SMB share
mount_smb_share() {
# Check if the mount point exists, otherwise create it
if [ ! -d "$SMB_MOUNT_POINT" ]; then
echo "Creating local mount point at $SMB_MOUNT_POINT"
mkdir -p "$SMB_MOUNT_POINT"
fi
# Check if the SMB share is already mounted
if mount | grep "$SMB_MOUNT_POINT" > /dev/null; then
echo "SMB share already mounted at $SMB_MOUNT_POINT"
else
echo "Mounting SMB share //${SMB_REMOTE_SERVER}${SMB_REMOTE_MOUNTPOINT} at $SMB_MOUNT_POINT"
mount -t cifs -o username="$SMB_USER",password="$SMB_PASSWORD" "//${SMB_REMOTE_SERVER}${SMB_REMOTE_MOUNTPOINT}" "$SMB_MOUNT_POINT"
# Check if the mount command was successful
if [ $? -ne 0 ]; then
echo "Error: Failed to mount SMB share //${SMB_REMOTE_SERVER}${SMB_REMOTE_MOUNTPOINT} at $SMB_MOUNT_POINT" >&2
exit 1
fi
echo "SMB share mounted successfully at $SMB_MOUNT_POINT."
fi
}
# Function to unmount SMB share
unmount_smb_share() {
echo "Unmounting SMB share at $SMB_MOUNT_POINT..."
# Check if the share is mounted before unmounting it
if mount | grep "$SMB_MOUNT_POINT" > /dev/null; then
umount "$SMB_MOUNT_POINT"
if [ $? -ne 0 ]; then
echo "Warning: Failed to unmount SMB share at $SMB_MOUNT_POINT" >&2
else
echo "SMB share unmounted successfully."
fi
else
echo "SMB share is not mounted at $SMB_MOUNT_POINT."
fi
}
# Check and create backup destination directories for the 1,2,3 principle if 123BACKUP is enabled
if [ "$BACKUP_123" == "Y" ]; then
check_and_create_directories "$SATA_DISK1" "$SATA_DISK2"
fi
# Function to stop Docker based on the distribution
stop_docker() {
echo
echo "##############################################################################################"
echo "# "
echo "# "
echo "# STOPPING DOCKER "
echo "# "
echo "# "
echo "##############################################################################################"
echo
case "$DISTRO" in
ubuntu|debian)
sudo systemctl stop docker.service
sudo systemctl stop docker.socket
sudo systemctl stop containerd.service
;;
centos|rhel|fedora)
sudo systemctl stop docker
sudo systemctl stop docker.socket
sudo systemctl stop containerd
;;
arch)
sudo systemctl stop docker
sudo systemctl stop docker.socket
sudo systemctl stop containerd
;;
*)
echo "Unsupported distribution: $DISTRO ????" >&2
exit 1
;;
esac
echo "Docker services stopped." | tee -a "$LOG_FILE"
}
# Function to start Docker based on the distribution
start_docker() {
echo
echo "##############################################################################################"
echo "# "
echo "# "
echo "# STARTING DOCKER "
echo "# "
echo "# "
echo "##############################################################################################"
echo
case "$DISTRO" in
ubuntu|debian)
sudo systemctl start docker.service
sudo systemctl start docker.socket
sudo systemctl start containerd.service
;;
centos|rhel|fedora)
sudo systemctl start docker
sudo systemctl start docker.socket
sudo systemctl start containerd
;;
arch)
sudo systemctl start docker
sudo systemctl start docker.socket
sudo systemctl start containerd
;;
*)
echo "Unsupported distribution: $DISTRO" >&2
exit 1
;;
esac
echo "Docker services started." | tee -a "$LOG_FILE"
}
# Function to check if Docker has stopped
check_docker_stopped() {
local retries=5
local wait_time=5
echo
echo "##############################################################################################"
echo "# "
echo "# "
echo "# CHECK IF DOCKER IS STOPPED "
echo "# "
echo "# "
echo "##############################################################################################"
echo
for ((i=1; i<=retries; i++)); do
if ! systemctl is-active --quiet docker; then
echo "Docker has stopped successfully." | tee -a "$LOG_FILE"
return 0
fi
echo "Waiting for Docker to stop... ($i/$retries)" | tee -a "$LOG_FILE"
sleep $wait_time
done
echo "Error: Docker did not stop within the expected time." | tee -a "$LOG_FILE"
exit 1
}
# Function to generate a random password
generate_password() {
openssl rand -base64 32
}
# Function to calculate the MD5 checksum
calculate_md5() {
local file="$1"
md5sum "$file" | awk '{ print $1 }'
}
# Function to calculate the total size of source directories
calculate_total_source_size() {
local total_size=0
for dir in "${SOURCE_DIRS[@]}"; do
dir_size=$(du -sb "$dir" | awk '{print $1}')
total_size=$((total_size + dir_size))
done
echo "$total_size"
}
# Function to calculate the file size in a human-readable format
calculate_file_size_readable() {
local file="$1"
du -sh "$file" | awk '{print $1}'
}
# Function to verify the backup using pigz for parallel decompression
verify_backup() {
local file="$1"
local password="$2"
TEST_START=$(date +%s)
echo
echo "Begin backup verification for file: $file" | tee -a "$LOG_FILE"
if [[ "$file" == *.enc ]]; then
# Decrypt and then verify the backup
if openssl enc -d -aes-256-cbc -pbkdf2 -iter 10000 -in "$file" -pass pass:"$password" | pigz -p $MAX_CPU_CORE -dc -9 | bar -s $(stat -c%s "$file") | tar -tf - > /dev/null 2>&1; then
TEST_END=$(date +%s)
TEST_STATUS="Successful"
echo
echo "Verification successful for encrypted file: $file"
else
TEST_END=$(date +%s)
TEST_STATUS="Failed"
echo
echo "Verification failed for encrypted file: $file" >> "$LOG_FILE"
echo "Verification failed for encrypted file: $file"
fi
else
# Verify the backup using pigz for parallel decompression
if pigz -p $MAX_CPU_CORE -dc -9 "$file" | bar -s $(stat -c%s "$file") | tar -tf - > /dev/null 2>&1; then
TEST_END=$(date +%s)
TEST_STATUS="Successful"
echo
echo "Verification successful for non-encrypted file: $file"
else
TEST_END=$(date +%s)
TEST_STATUS="Failed"
echo
echo "Verification failed for non-encrypted file: $file" >> "$LOG_FILE"
echo "Verification failed for non-encrypted file: $file"
fi
fi
echo
echo "Backup verification completed for file: $file" | tee -a "$LOG_FILE"
# Calculate the test duration in minutes and seconds
local test_duration=$(( TEST_END - TEST_START ))
local test_minutes=$(( test_duration / 60 ))
local test_seconds=$(( test_duration % 60 ))
TEST_DURATION="${test_minutes} minutes and ${test_seconds} seconds"
# Convert the timestamps to a readable format
TEST_START_READABLE=$(convert_timestamp_to_date "$TEST_START")
TEST_END_READABLE=$(convert_timestamp_to_date "$TEST_END")
}
# Function to compress and encrypt the database backup
compress_and_encrypt_backup() {
local file="$1"
local encrypted_file="$2"
local password="$3"
# Remove the .sql.enc extension from the original file name to get the correct name
local base_file=$(basename "$file" .sql.enc)
local backup_dir=$(dirname "$file") # Get the directory of the file
# Full path for the compressed file
local compressed_file="${backup_dir}/${base_file}.tar.gz"
# Compress the backup file in every case
echo
echo "Compressing the backup file $file..."
tar -P -cf - "$file" | bar -s $(du -sb "$file" | awk '{print $1}') | pigz -p $MAX_CPU_CORE -9 > "$compressed_file"
if [ $? -ne 0 ]; then
echo "Compression failed for $file" >> "$LOG_FILE"
return 1
else
echo "Compression completed for $file. Compressed file: $compressed_file" >> "$LOG_FILE"
fi
# Calculate the MD5 before encrypting
local md5_checksum=$(md5sum "$compressed_file" | awk '{ print $1 }')
echo "MD5 checksum: $md5_checksum"
echo
DATABASE_MD5_SUMS+=("$md5_checksum")
if [ "$ENCRYPT_BACKUP" == "Y" ]; then
echo "Encrypting the compressed file $compressed_file..."
openssl enc -aes-256-cbc -pbkdf2 -iter 10000 -salt -in "$compressed_file" -out "${encrypted_file}.tar.gz.enc" -pass pass:"$password"
if [ $? -ne 0 ]; then
echo "Encryption failed for $compressed_file" >> "$LOG_FILE"
echo
return 1
else
echo "Encryption completed for $compressed_file" >> "$LOG_FILE"
echo
rm -f "$compressed_file" # Delete the file only after encryption is complete
fi
else
COMPRESSED_BACKUP_SIZES+=($(stat -c%s "$compressed_file"))
fi
# Delete the original .sql file after compression and/or encryption
rm -f "$file"
echo "Original file $file deleted." >> "$LOG_FILE"
}
# Function to encrypt the backup file with AES-256
encrypt_backup() {
local file="$1"
local password="$2"
local encrypted_file="${file}.enc"
# Encrypt the backup file using AES-256-CBC with PBKDF2 and 10,000 iterations
openssl enc -aes-256-cbc -pbkdf2 -iter 10000 -salt -in "$file" -out "$encrypted_file" -pass pass:"$password" 2>> "$LOG_FILE"
# Remove the unencrypted file
rm -f "$file"
echo "$encrypted_file"
}
# Function to convert a UNIX timestamp to a readable date
convert_timestamp_to_date() {
local timestamp=$1
date -d @"$timestamp" +"%a %d %b %Y, %H:%M:%S %Z"
}
# Function to calculate the backup duration in minutes and seconds
calculate_backup_duration() {
local start_time=$1
local end_time=$2
local duration=$(( end_time - start_time ))
# If the duration is too short (less than 1 second), set it to 1 second
if [[ $duration -eq 0 ]]; then
duration=1
fi
# Calculate minutes and seconds
local minutes=$(( duration / 60 ))
local seconds=$(( duration % 60 ))
# Return the calculated duration
echo "${minutes} minutes and ${seconds} seconds"
}
# Function to calculate disk speed
calculate_disk_speed() {
local file_path=$1 # The backup file
local start_time=$2 # Backup start timestamp
local end_time=$3 # Backup end timestamp
# Calculate the backup file size in bytes
local size_bytes=$(stat -c%s "$file_path")
# Calculate the duration in seconds
local time_seconds=$((end_time - start_time))
# Avoid division by zero: if the time is 0, set the duration to 1 second
if [[ $time_seconds -eq 0 ]]; then
time_seconds=1
fi
# Calculate speed in MB/s (bytes / seconds -> MB/s)
DISK_SPEED=$(echo "scale=2; $size_bytes / $time_seconds / 1024 / 1024" | bc -l)
# Write the speed to the log for debugging without duplicating "MB/s"
echo "$DISK_SPEED" | tee -a "$LOG_FILE"
}
# Function to perform the database backup
backup_database() {
local db_info="$1"
local db_type=$(echo $db_info | cut -d'|' -f1)
local container_name=$(echo $db_info | cut -d'|' -f2)
local db_name=$(echo $db_info | cut -d'|' -f3)
local db_user=$(echo $db_info | cut -d'|' -f4)
local db_password=$(echo $db_info | cut -d'|' -f5)
local backup_file="$BACKUP_DATABASE_DIR/${db_name}-$(date +%Y%m%d).sql"
local encrypted_file="${backup_file}"
# Log the backup start time
local BACKUP_START=$(date +%s)
case "$db_type" in
"PostgreSQL"|"TimescaleDB")
echo "##############################################################################################"
echo "# "
echo "# Performing the database backup $db_type..., "
echo "# MD5 checksum, Compressing and Verifivation "
echo "# of "$container_name" "
echo "# "
echo "##############################################################################################"
docker exec "$container_name" pg_dump -U "$db_user" "$db_name" > "$backup_file"
;;
"MySQL"|"MariaDB")
echo "##############################################################################################"
echo "# "
echo "# Performing the database backup $db_type..., "
echo "# MD5 checksum, Compressing and Verifivation "
echo "# of "$container_name" "
echo "# "
echo "##############################################################################################"
docker exec "$container_name" mysqldump -u "$db_user" -p"$db_password" "$db_name" > "$backup_file"
;;
"MongoDB")
echo "##############################################################################################"
echo "# "
echo "# Performing the database backup $db_type..., "
echo "# MD5 checksum, Compressing and Verifivation "
echo "# of "$container_name" "
echo "# "
echo "##############################################################################################"
docker exec "$container_name" mongodump --db "$db_name" --out "$BACKUP_DATABASE_DIR/$db_name-$(date +%Y%m%d)"
;;
"Redis")
echo "##############################################################################################"
echo "# "
echo "# Performing the database backup $db_type..., "
echo "# MD5 checksum, Compressing and Verifivation "
echo "# of "$container_name" "
echo "# "
echo "##############################################################################################"
docker exec "$container_name" redis-cli BGSAVE
# Wait for the Redis backup to complete
while ! docker exec "$container_name" redis-cli LASTSAVE > /dev/null; do
sleep 1
done
# Copy the dump.rdb file from the Redis container to the backup directory
docker cp "$container_name:/data/dump.rdb" "$BACKUP_DATABASE_DIR/dump-$CURRENT_DATE.rdb"
# Update the backup file name with the correct container name
backup_file="$BACKUP_DATABASE_DIR/dump-$CURRENT_DATE.rdb"
encrypted_file="$BACKUP_DATABASE_DIR/${container_name}_dump-$CURRENT_DATE"
;;
"Cassandra")
echo "##############################################################################################"
echo "# "
echo "# Performing the database backup $db_type..., "
echo "# MD5 checksum, Compressing and Verifivation "
echo "# of "$container_name" "
echo "# "
echo "##############################################################################################"
docker exec "$container_name" nodetool snapshot -t "$(date +%Y%m%d)-snapshot"
;;
"Elasticsearch")
echo "##############################################################################################"
echo "# "
echo "# Performing the database backup $db_type..., "
echo "# MD5 checksum, Compressing and Verifivation "
echo "# of "$container_name" "
echo "# "
echo "##############################################################################################"
docker exec "$container_name" elasticsearch-snapshot --repository backup-repo --snapshot "$(date +%Y%m%d)"
;;
"SQLite")
echo "##############################################################################################"
echo "# "
echo "# Performing the database backup $db_type..., "
echo "# MD5 checksum, Compressing and Verifivation "
echo "# of "$container_name" "
echo "# "
echo "##############################################################################################"
docker cp "$container_name:/path/to/database.sqlite" "$BACKUP_DATABASE_DIR/sqlite-backup-$(date +%Y%m%d).sqlite"
;;
"Neo4j")
echo "##############################################################################################"
echo "# "
echo "# Performing the database backup $db_type..., "
echo "# MD5 checksum, Compressing and Verifivation "
echo "# of "$container_name" "
echo "# "
echo "##############################################################################################"
docker exec "$container_name" neo4j-admin backup --from="$container_name" --backup-dir="$BACKUP_DATABASE_DIR"
;;
"CockroachDB")
echo "##############################################################################################"
echo "# "
echo "# Performing the database backup $db_type..., "
echo "# MD5 checksum, Compressing and Verifivation "
echo "# of "$container_name" "
echo "# "
echo "##############################################################################################"
docker exec "$container_name" cockroach sql --execute="BACKUP TO '$BACKUP_DATABASE_DIR/backup'"
;;
"InfluxDB")
echo "##############################################################################################"
echo "# "
echo "# Performing the database backup $db_type..., "
echo "# MD5 checksum, Compressing and Verifivation "
echo "# of "$container_name" "
echo "# "
echo "##############################################################################################"
docker exec "$container_name" influx backup -portable "$BACKUP_DATABASE_DIR"
;;
"Oracle")
echo "##############################################################################################"
echo "# "
echo "# Performing the database backup $db_type..., "
echo "# MD5 checksum, Compressing and Verifivation "
echo "# of "$container_name" "
echo "# "
echo "##############################################################################################"
docker exec "$container_name" rman target / <<EOF
backup database;
EOF
;;
"RethinkDB")
echo "##############################################################################################"
echo "# "
echo "# Performing the database backup $db_type..., "
echo "# MD5 checksum, Compressing and Verifivation "
echo "# of "$container_name" "
echo "# "
echo "##############################################################################################"
docker exec "$container_name" rethinkdb dump -f "$BACKUP_DATABASE_DIR/rethinkdb-backup-$(date +%Y%m%d).tar.gz"
;;
"Memcached")
echo
echo "Memcached does not require a backup of persistent data. Ignoring…"
echo
;;
*)
echo
echo "Unsupported database type: $db_type"
echo
return 1
;;
esac
# Calculate the original size of the database file
local original_db_size=$(calculate_file_size_readable "$backup_file")
DATABASE_ORIGINAL_SIZES+=("$original_db_size") # Store the original size in the array
if [ "$ENCRYPT_BACKUP" == "Y" ]; then
local password=$(generate_password)
compress_and_encrypt_backup "$backup_file" "$encrypted_file" "$password"
DATABASE_PASSWORDS+=("$password")
DATABASE_BACKUP_FILES+=("${encrypted_file}.tar.gz.enc")
# Verify backup
verify_backup "${encrypted_file}.tar.gz.enc" "$password"
echo
echo "Verifying the Encrypted backup..."
echo
else
compress_and_encrypt_backup "$backup_file" "" ""
DATABASE_PASSWORDS+=("No encryption")
DATABASE_BACKUP_FILES+=("${backup_file}.tar.gz")
# Verify backup
verify_backup "${backup_file}.tar.gz" ""
echo
echo "Verifying the UnEncrypted backup..."
echo
fi
# Add the verification status to the DATABASE_TEST_STATUSES variable
DATABASE_TEST_STATUSES+=("$TEST_STATUS")
# Log the backup end time
local BACKUP_END=$(date +%s)
# Convert timestamps to a readable format
local BACKUP_START_READABLE=$(convert_timestamp_to_date "$BACKUP_START")
local BACKUP_END_READABLE=$(convert_timestamp_to_date "$BACKUP_END")
# Calculate the backup duration
local BACKUP_DURATION=$(calculate_backup_duration "$BACKUP_START" "$BACKUP_END")
# Store the backup details
DATABASE_BACKUP_DURATIONS+=("$BACKUP_DURATION")
DATABASE_BACKUP_STARTS+=("$BACKUP_START_READABLE")
DATABASE_BACKUP_ENDS+=("$BACKUP_END_READABLE")
# Add database backup details for the email report
DATABASE_BACKUP_DETAILS+=("<tr><td>${db_name}</td><td>${container_name}</td><td>${BACKUP_DATABASE_DIR}</td><td>${original_db_size}</td></tr>")
echo "Backup and compression completed for the database $db_name."
echo
}
# Function to perform the database restore
restore_database() {
local db_info="$1"
local db_type=$(echo $db_info | cut -d'|' -f1)
local container_name=$(echo $db_info | cut -d'|' -f2)
local db_name=$(echo $db_info | cut -d'|' -f3)
local db_user=$(echo $db_info | cut -d'|' -f4)
local db_password=$(echo $db_info | cut -d'|' -f5)
local backup_file="$BACKUP_DATABASE_DIR/${db_name}-$(date +%Y%m%d).sql"
case "$db_type" in
"PostgreSQL"|"TimescaleDB")
echo "Restoring the database $db_type..."
docker exec -i "$container_name" psql -U "$db_user" "$db_name" < "$backup_file"
;;
"MySQL"|"MariaDB")
echo "Restoring the database MySQL/MariaDB..."
docker exec -i "$container_name" mysql -u "$db_user" -p"$db_password" "$db_name" < "$backup_file"
;;
"MongoDB")
echo "Restoring the database MongoDB..."
docker exec "$container_name" mongorestore --db "$db_name" "$BACKUP_DATABASE_DIR/$db_name-$(date +%Y%m%d)"
;;
"Redis")
echo "Restoring the database Redis..."
docker cp "$backup_file" "$container_name:/data/dump.rdb"
docker exec "$container_name" redis-cli shutdown save
docker start "$container_name"
;;
"Cassandra")
echo "Restoring the database Cassandra..."
docker exec "$container_name" nodetool refresh -- $db_name $(date +%Y%m%d)-snapshot