-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVM-backup.sh
2943 lines (1868 loc) · 109 KB
/
VM-backup.sh
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
#backgroundOnly=true
#arrayStarted=true
#noParity=true
# v1.3.1 - 2020/01/21
#### DISCLAIMER ####
# Use at your own risk. This is a work-in-progress and provided as is.
# I have tested this on my own server, as best as I am able, but YMMV.
# -jtok
# what is the scripts' official name.
official_script_name="script"
# set the name of the script to a variable so it can be used.
me=$(basename "$0")
# this script copies unRAID vm's vdisks and their configurations to a specified location.
################################################## script variables start ######################################################
# default 0 but set the master switch to 1 if you want to enable the script otherwise it will not run.
enabled="1"
# backup location to put vdisks.
backup_location="/mnt/user/backup/vm-backup"
# default is 0. backup all vms or use vms_to_backup.
# when set to 1, vms_to_backup will be used as an exclusion list.
backup_all_vms="1"
# list of vms that will be backed up separated by a new line.
# if backup_all_vms is set to 1, this will be used as a list of vms to exclude instead.
vms_to_backup="
"
# list of specific vdisks to be skipped separated by a new line. use the full path.
# NOTE: must match path in vm config file. remember this if you change the virtual disk path to enable snapshots.
vdisks_to_skip=""
# list of specific vdisk extensions to be skipped separated by a new line. this replaces the old ignore_isos variable.
vdisk_extensions_to_skip=""
# default is 0. use snapshots to backup vms.
# NOTE: vms that are backed up using snapshots will not be shutdown. if a vm is already shutdown the default backup method will be used.
# NOTE: it is highly recommended that you install the qemu guest agent on your vms before using snapshots to ensure the integrity of your backups.
# WARNING: this will fail if the config path for the virtual disk is /mnt/user/. you must use /mnt/cache/ or /mnt/diskX/ for snapshots to work.
use_snapshots="0"
# default is 0. set this to 1 if you would like to kill a vm if it cant be shutdown cleanly.
kill_vm_if_cant_shutdown="0"
# default is 1. set this to 0 if you do not want a vm to be started if it was running before the backup started. Paused VMs will be left stopped.
set_vm_to_original_state="1"
# default is 0. set this to the number of days backups should be kept. 0 means indefinitely.
number_of_days_to_keep_backups="40"
# default is 0. set this to the number of backups that should be kept. 0 means infinitely.
# WARNING: If VM has multiple vdisks, then they must end in sequential numbers in order to be correctly backed up (i.e. vdisk1.img, vdisk2.img, etc.).
number_of_backups_to_keep="10"
# default is 0. set this to 1 if you would like to perform inline zstd compression. This overrides the "compress_backups" and "compare_files" options.
inline_zstd_compress="1"
# default is 3. higher values may produce smaller archives but are slower and use more CPU.
zstd_level="3"
# default is 2. set this to the desired number of compression worker threads, or 0 to auto detect (i.e. use all)
zstd_threads="2"
# default is 0. set this to 1 if you would like to compress backups. This can add a significant amount of time to the backup process. uses tar.gz for sparse file compatibility.
# this is the legacy setting for compression.
# WARNING: do not turn on if you already have uncompressed backups. You will need to move or delete uncompressed backups before using. this will compress all config, nvram, and vdisk images in the backup directory into ONE tarball.
compress_backups="0"
# default is 1. set this to 0 if you would like to have backups without a timestamp. Timestamps are dropped only when number_of_backups_to_keep is equal to 1.
timestamp_files="1"
#### logging and notifications ####
# default is 1. set to 0 to have log file deleted after the backup has completed.
# NOTE: error logs are separate. settings for error logs can be found in the advanced variables.
keep_log_file="1"
# default is 1. number of successful log files to keep. 0 means infinitely.
number_of_log_files_to_keep="30"
# default is "logs". set to "" to put in root of backups folder. set to "logs/<subfolder>" to keep logs separate if running multiple versions of this script.
log_file_subfolder="logs"
# default is 0. create a vm specific log in each vm's subfolder using the same retention policy as the vm's backups.
enable_vm_log_file="0"
# default is 1. set to 0 to prevent notification system from being used. Script failures that occur before logging can start, and before this variable is validated will still be sent.
send_notifications="1"
# default is 0. set to 1 to receive more detailed notifications. will not work with send_notifications disabled or only_send_error_notifications enabled.
detailed_notifications="0"
#### advanced variables ####
# default is snap. extension used when creating snapshots.
# WARNING: do not choose an extension that is the same as one of your vdisks or the script will error out. cannot be blank.
snapshot_extension="snap"
# default is 0. fallback to standard backup if snapshot creation fails.
# NOTE: this will act as though use_snapshots was disabled for just the vm with the failed snapshot command.
snapshot_fallback="0"
# default is 0. pause vms instead of shutting them down during standard backups.
# WARNING: this could result in unusable backups, but I have not thoroughly tested.
pause_vms="0"
# list of vms that will be backed up WITHOUT first shutting down separated by a new line. these must also be listed in vms_to_backup.
# NOTE: vms backed up via snapshot will not be shutdown (see use_snapshots option).
# WARNING: using this setting can result in an unusable backup. not recommended.
vms_to_backup_running="
"
# default is 0. set to 1 to have reconstruct write (a.k.a. turbo write) enabled during the backup and then disabled after the backup completes.
# NOTE: may break auto functionality when it is implemented. do not use if reconstruct write is already enabled. backups may run faster with this enabled.
enable_reconstruct_write="0"
# default is 0. set this to 1 to compare files after copy and run rsync in the event of failure. could add significant amount of time depending on the size of vms.
compare_files="0"
# default is 1. set to 0 if you would like to skip backing up xml configuration files.
backup_xml="1"
# default is 1. set to 0 if you would like to skip backing up nvram files.
backup_nvram="1"
# default is 1. set to 0 if you would like to skip backing up vdisks. setting this to 0 will automatically disable compression.
backup_vdisks="1"
# default is 0. set this to 1 if you would like to start a vm after it has successfully been backed up. will override set_vm_to_original_state when set to 1.
start_vm_after_backup="0"
# default is 0. set this to 1 if you would like to start a vm after it has failed to have been backed up. will override set_vm_to_original_state when set to 1.
start_vm_after_failure="0"
# default is 0. set this to 1 to disable rsync delta syncs.
disable_delta_sync="0"
# default is 0. set this to 1 to always use rsync instead of cp.
# NOTE: rsync was significantly slower in my tests.
rsync_only="0"
# default is 1. set this to 0 if you would like to perform a dry-run backup.
# NOTE: dry run will not work unless rsync_only is set to 1. if this is set to 1 rsync_only will be set to 1.
actually_copy_files="1"
# default is 20. set this to the number of times you would like to check if a clean shutdown of a vm has been successful.
clean_shutdown_checks="20"
# default is 30. set this to the number of seconds to wait in between checks to see if a clean shutdown has been successful.
seconds_to_wait="30"
# default is 1. set to 0 to have error log files deleted after the backup has completed.
keep_error_log_file="1"
# default is 10. number of error log files to keep. 0 means infinitely.
number_of_error_log_files_to_keep="10"
# default is 0. set to 1 to only send error notifications.
only_send_error_notifications="0"
################################################## script variables end #########################################################
###################################################### script start #############################################################
#### define functions start ####
# copy files based on passed arguments.
copy_file () {
# assign arguments to local variables for readability.
local source="$1"
local destination="$2"
local rsync_dry_run_option="$3"
local sync_type="$4"
local rsync_only="$5"
if [[ ! "$rsync_only" =~ ^[0-9]+$ ]]; then
local rsync_only="0"
fi
# determine the copy command that should be ran and capture the result.
case "$sync_type" in
"standard")
# perform standard rsync.
rsync -av"$rsync_dry_run_option" "$source" "$destination"
local copy_result="$?"
;;
"inline_zstd_compress")
# perform inline zstd compression (with sparse file support).
zstd -$zstd_level -T$zstd_threads --sparse "$source" -o "$destination"
local copy_result="$?"
;;
"sparse")
# perform rsync or copy with support for sparse files.
if [ "$rsync_only" -eq 1 ]; then
rsync -av"$rsync_dry_run_option" --sparse "$source" "$destination"
local copy_result="$?"
else
cp -av --sparse=always "$source" "$destination"
local copy_result="$?"
fi
;;
"inplace")
# perform inplace copy (i.e. delta sync).
rsync -av"$rsync_dry_run_option" --inplace --no-whole-file "$source" "$destination"
;;
*)
# no valid copy choice was able to be ran.
log_message "failure: no valid copy choice was able to run for copy of $source to $destination failed." "copy failed" "alert"
# exit the function
return 1
;;
esac
# get rsync result and send notification
if [[ "$copy_result" -eq 1 ]]; then
log_message "failure: copy of $source to $destination failed." "copy failed" "alert"
else
# set actually_copy_files based rsync_dry_run_option
if [ "$rsync_dry_run_option" == "n" ]; then
local actually_copy_files="0"
else
local actually_copy_files="1"
fi
# send a message to the user based on whether there was an actual copy or a dry-run.
if [ "$actually_copy_files" -eq 0 ]; then
log_message "information: dry-run copy of $source to $destination complete."
else
log_message "information: copy of $source to $destination complete." "completed copy" "normal"
fi
fi
}
# pass log messages to log files and system notifications.
log_message () {
# assign arguments to local variables for readability.
local message="$1"
local description="$2"
local importance="$3"
case "$importance" in
"information")
local is_error="0"
;;
"alert")
local is_error="1"
;;
"warning")
local is_error="1"
;;
*)
local is_error="0"
;;
esac
if [ "$description" ] && [ "$importance" ]; then
local enable_detailed_notifications="1"
else
local enable_detailed_notifications="0"
fi
local force_notification="$4"
# add the message to the main log file.
echo "$(date '+%Y-%m-%d %H:%M:%S') $message" | tee -a "$backup_location/$log_file_subfolder$timestamp""unraid-vmbackup.log"
# add the message to the vm specific log file if enabled.
if [[ -n "$vm_log_file" ]] && [ "$enable_vm_log_file" -eq 1 ]; then
echo "$(date '+%Y-%m-%d %H:%M:%S') $message" >> "$vm_log_file"
fi
# check to see if the message is an error message.
if [ "$is_error" -eq 1 ]; then
# mark that the script encountered an error.
errors="1"
# send a notification if they are enabled.
if [ "$send_notifications" -eq 1 ] || [ "$force_notification" == "force_notification" ]; then
/usr/local/emhttp/plugins/dynamix/scripts/notify -s "unRAID VM Backup script" -d "$description" -i "$importance" -m "$(date '+%Y-%m-%d %H:%M:%S') $message"
fi
fi
# send a detailed notification if it is enabled and if they should be used.
if [ "$enable_detailed_notifications" -eq 1 ] && [ "$detailed_notifications" -eq 1 ]; then
if [ "$send_notifications" -eq 1 ] && [ "$only_send_error_notifications" -eq 0 ]; then
/usr/local/emhttp/plugins/dynamix/scripts/notify -s "unRAID VM Backup script" -d "$description" -i "$importance" -m "$(date '+%Y-%m-%d %H:%M:%S') $message"
fi
fi
}
# pass notification messages to system notifications.
notification_message () {
# assign arguments to local variables for readability.
local message="$1"
local description="$2"
local importance="$3"
# show the message in the log.
echo "$(date '+%Y-%m-%d %H:%M:%S') $message"
# send message notification.
if [[ -n "$description" ]] && [[ -n "$importance" ]]; then
/usr/local/emhttp/plugins/dynamix/scripts/notify -s "unRAID VM Backup script" -d "$description" -i "$importance" -m "$(date '+%Y-%m-%d %H:%M:%S') $message"
fi
}
# compare two files.
run_compare () {
# assign arguments to local variables for readability.
local source="$1"
local destination="$2"
local file_type="$3"
# check to see if compare_files is enabled. if yes, check for config differences.
if [ "$compare_files" -eq 1 ]; then
if ! cmp -s "$source" "$destination"; then
log_message "warning: $file_type file for $vm is different than source file. retrying backup." "$(basename "$source") compare failed" "warning"
case "$file_type" in
"config")
copy_file "$source" "$destination" "$rsync_dry_run_option" "standard" "$rsync_only"
;;
"nvram")
copy_file "$source" "$destination" "$rsync_dry_run_option" "standard" "$rsync_only"
;;
"vdisk")
copy_file "$source" "$destination" "$rsync_dry_run_option" "sparse" "$rsync_only"
;;
*)
log_message "warning: unable to re-run copy command for $source. file_type is $file_type." "$(basename "$source") compare copy failed" "warning"
;;
esac
# make sure copy has current date/time for modified attribute so that removing old backups by date will work.
touch -d "now" "$destination"
if ! cmp -s "$source" "$destination"; then
log_message "failure: $file_type file for $vm failed second comparison." "$(basename "$source") second compare failed" "alert"
else
log_message "information: $file_type file for $vm passed second comparison. moving on."
fi
else
log_message "information: $file_type file for $vm matches source file. moving on."
fi
fi
}
# copy vdisks.
copy_vdisks () {
# assign arguments to local variables for readability.
local mode="$1"
# get number of vdisks assoicated with the vm.
vdisk_count=$(xmllint --xpath "count(/domain/devices/disk/source/@file)" "$vm.xml")
# unset array for vdisks.
unset vdisks
# initialize vdisks as empty array
vdisks=()
# unset dictionary for vdisk_types.
unset vdisk_types
# initailize vdisk_types as dictionary.
declare -A vdisk_types
# unset dictionary for vdisk_types.
unset vdisk_specs
# initailize vdisk_types as dictionary.
declare -A vdisk_specs
# get vdisk paths from config file.
for (( i=1; i<=vdisk_count; i++ ))
do
vdisk_path="$(xmllint --xpath "string(/domain/devices/disk[$i]/source/@file)" "$vm.xml")"
vdisk_type="$(xmllint --xpath "string(/domain/devices/disk[$i]/driver/@type)" "$vm.xml")"
vdisk_spec="$(xmllint --xpath "string(/domain/devices/disk[$i]/target/@dev)" "$vm.xml")"
vdisks+=("$vdisk_path")
vdisk_types["$vdisk_path"]="$vdisk_type"
vdisk_specs["$vdisk_path"]="$vdisk_spec"
done
# check for the header in vdisks to see if there are any disks
if [ ${#vdisks[@]} -eq 0 ]; then
log_message "warning: there are no vdisk(s) associated with $vm to backup." "no vdisk(s) for $vm" "warning"
fi
# unset array for vdisk_extensions.
unset vdisk_extensions
# initialize vdisk_extensions as empty array.
vdisk_extensions=()
# get vdisk names to check on current backups
for disk in "${vdisks[@]}"
do
if [[ -n "$disk" ]]; then
# assume disk will not be skipped.
skip_disk="0"
# check to see if vdisk should be explicitly skipped.
for skipvdisk_name in $vdisks_to_skip
do
if [ "$skipvdisk_name" == "$disk" ]; then
skip_disk="1"
log_message "information: $disk on $vm was found in vdisks_to_skip. skipping disk."
fi
done
# get the extension of the disk.
disk_extension="${disk##*.}"
# disable case matching.
shopt -s nocasematch
# check to see if vdisk extension is the same as the snapshot extension. if it is, error and skip the vm.
if [[ "$disk_extension" == "$snapshot_extension" ]]; then
log_message "failure: extension for $disk on $vm is the same as the snapshot extension $snapshot_extension. disk will always be skipped. this usually means that the disk path in the config was not changed from /mnt/user. if disk path is correct, then try changing snapshot_extension or vdisk extension." "cannot backup vdisk on $vm" "alert"
fi
# check to see if vdisk should be skipped by extension.
for skipvdisk_extension in $vdisk_extensions_to_skip
do
if [[ "$skipvdisk_extension" == "$disk_extension" ]]; then
skip_disk="1"
log_message "information: extension for $disk on $vm was found in vdisks_extensions_to_skip. skipping disk."
fi
done
# re-enable case matching.
shopt -u nocasematch
# get the filename of the disk without the path.
new_disk=$(basename "$disk")
if [ "$mode" == "existing_backup" ]; then
# unset vairiable for disk_number
unset -v disk_number
# get the disk number and extension
vdisknameregex="[0-9]+\\.$disk_extension"
if [[ $disk =~ $vdisknameregex ]]; then
disk_number=${BASH_REMATCH[0]}
fi
# skip the vdisk if skip_disk is set to 1
if [ "$skip_disk" -ne 1 ]; then
# unset variable for the most recent vdisk file.
unset -v newest_vdisk_file
# see if disk_number is empty. if not, set to wildcard.
if [[ -z "$disk_number" ]]; then
disk_number='.@'$disk_extension''
fi
# enable extended globbing
shopt -s extglob
# get the most recent vdisk file.
for diskimage in "$backup_location/$vm/"*"$disk_number"
do
[[ $diskimage -nt $newest_vdisk_file ]] && newest_vdisk_file=$diskimage
done
# disable extended globbing
shopt -u extglob
# check to see if a backup already exists for this vdisk and make a copy of it before shutting down the guest.
if [[ -f "$newest_vdisk_file" ]]; then
log_message "information: copy of backup of $newest_vdisk_file vdisk to $backup_location/$vm/$timestamp$new_disk starting." "script starting copy $vm backup" "normal"
# call function copy_files to copy existing backup
copy_file "$newest_vdisk_file" "$backup_location/$vm/$timestamp$new_disk" "$rsync_dry_run_option" "sparse" "$rsync_only"
# make sure copy has current date/time for modified attribute so that removing old backups by date will work.
touch -d "now" "$backup_location/$vm/$timestamp$new_disk"
fi
fi
elif [ "$mode" == "source_image" ]; then
# skip the vdisk if skip_disk is set to 1
if [ "$skip_disk" -ne 1 ]; then
# add the extension of the disk being backed up to an array of vdisk extensions if it doesn't already exist
# set variable extension_exists to false.
extension_exists=false
# for each extension check to see if it is already in the array.
for extension in "${vdisk_extensions[@]}"
do
# if the extension already exists in the array set extension_exists to true and break out of the current loop.
if [ "$extension" == "$disk_extension" ]; then
extension_exists=true
break
fi
done
# if the extension was not found in the array add it.
if [ "$extension_exists" = false ]; then
vdisk_extensions+=("$disk_extension")
fi
# check to see if snapshots should be used, and if the vm is running.
if [ "$use_snapshots" -eq 1 ] && [ "$vm_state" == "running" ]; then
snapshot_using_traditional_backup=false
log_message "information: able to perform snapshot for disk $disk on $vm. use_snapshots is $use_snapshots. vm_state is $vm_state. vdisk_type is ${vdisk_types[$disk]}"
# set variable for qemu agent is installed.
qemu_agent_installed=$(virsh qemu-agent-command "$vm" '{"execute":"guest-info"}' | grep -c "version" | awk '{ print $0 }')
# get directory of current disk.
disk_directory=$(dirname "$disk")
# remove trailing slash.
disk_directory=${disk_directory%/}
# get name of current disk without extension and add snapshot extension.
snap_name="${new_disk%.*}.$snapshot_extension"
# check to see if qemu agent is installed for snapshot creation command.
if [[ "$qemu_agent_installed" -eq 1 ]]; then
# set quiesce to enabled.
quiesce="--quiesce"
log_message "information: qemu agent found. enabling quiesce on snapshot."
else
# set quiesce to disabled.
quiesce=""
log_message "information: qemu agent not found. disabling quiesce on snapshot."
fi
# create snapshot command.
# unset array for snapshot_cmd.
unset snapshot_cmd
# initialize snapshot_cmd as empty array.
snapshot_cmd=()
# find each vdisk_spec and use it to build a snapshot command.
for vdisk_spec in "${vdisk_specs[@]}"
do
# check to see if snapshot command is empty.
if [ ${#snapshot_cmd[@]} -eq 0 ]; then
# build intial snapshot command.
snapshot_cmd=(virsh)
snapshot_cmd+=(snapshot-create-as)
snapshot_cmd+=(--domain "$vm")
snapshot_cmd+=(--name "$vm-$snap_name")
# check to see if this is the vdisk we are currently working with.
if [ "$vdisk_spec" == "${vdisk_specs[$disk]}" ]; then
# if it is, set the command to make a snapshot.
snapshot_cmd+=(--diskspec "$vdisk_spec,file=$disk_directory/$snap_name,snapshot=external")
else
# if it is not, set the command to not make a snapshot.
snapshot_cmd+=(--diskspec "$vdisk_spec,snapshot=no")
fi
else
# add additional extensions to snapshot command.
# check to see if this is the vdisk we are currently working with.
if [ "$vdisk_spec" == "${vdisk_specs[$disk]}" ]; then
# if it is, set the command to make a snapshot.
snapshot_cmd+=(--diskspec "$vdisk_spec,file=$disk_directory/$snap_name,snapshot=external")
else
# if it is not, set the command to not make a snapshot.
snapshot_cmd+=(--diskspec "$vdisk_spec,snapshot=no")
fi
fi
done
# add additonal options to snapshot command.
snapshot_cmd+=(--disk-only)
snapshot_cmd+=(--no-metadata)
snapshot_cmd+=(--atomic)
# check to see if snapshot command should include --quiesce.
if [[ -n "$quiesce" ]]; then
snapshot_cmd+=("$quiesce")
fi
# create snapshot.
if ! "${snapshot_cmd[@]}"; then
snapshot_succeeded=false
log_message "failure: snapshot command failed on $snap_name for $vm." "$vm snapshot failed" "alert"
# attempt backup using fallback method.
if [ "$snapshot_fallback" -eq 1 ]; then
log_message "warning: snapshot_fallback is $snapshot_fallback. attempting backup for $vm using fallback method." "$vm fallback backup" "warning"
# get the state of the vm for making sure it is off before backing up.
vm_state=$(virsh domstate "$vm")
# get the state of the vm for putting the VM in it's original state after backing up.
vm_original_state=$vm_state
# initialize skip_vm_shutdown variable as false.
skip_vm_shutdown=false
# determine if vm should be kept running.
# first check to see if vm exists in vms_to_backup_running variable.
for vm_to_keep_running in $vms_to_backup_running
do
if [[ "$vm_to_keep_running" == "$vm" ]]; then
skip_vm_shutdown=true
fi
done
# if vm is not found in vms_to_backup_running and use_snapshots is disabled, then skip shutdown proceedure.
if [ "$skip_vm_shutdown" = false ]; then
log_message "information: skip_vm_shutdown is false. beginning vm shutdown procedure."
# prepare vm for backup.
prepare_vm "$vm" "$vm_state"
elif [ "$skip_vm_shutdown" = true ]; then
can_backup_vm="y"
log_message "information: skip_vm_shutdown is $skip_vm_shutdown and use_snapshots is $use_snapshots. skipping vm shutdown procedure. $vm is $vm_state. can_backup_vm set to $can_backup_vm."
else
log_message "failure: skip_vm_shutdown is $skip_vm_shutdown and use_snapshots is $use_snapshots. skipping vm shutdown procedure. $vm is $vm_state. can_backup_vm set to $can_backup_vm." "$vm backup failed" "alert"
fi
# break out of current vdisk loop to prevent potential data loss.
else
log_message "failure: snapshot_fallback is $snapshot_fallback. skipping backup for $vm to prevent data loss. no cleanup will be performed for this vm." "$vm snapshot failed" "alert"
break
fi
else
snapshot_succeeded=true
log_message "information: snapshot command succeeded on $snap_name for $vm."
fi
elif [ "$use_snapshots" -eq 1 ] && [ ! "$vm_state" == "running" ]; then
snapshot_using_traditional_backup=true
log_message "information: unable to perform snapshot for disk $disk on $vm. falling back to traditional backup. use_snapshots is $use_snapshots. vm_state is $vm_state. vdisk_type is ${vdisk_types[$disk]}."
fi
local dest_disk="$backup_location/$vm/$new_disk"
if [ "$timestamp_files" -eq 1 ] || [ "$number_of_backups_to_keep" -ne 1 ]; then
# if timestamps are enabled or more than one backup is being kept, add a timestamp to the destination filename.
dest_disk="$backup_location/$vm/$timestamp$new_disk"
fi
# copy or pretend to copy the vdisk to the backup location specified by the user.
if [ "$inline_zstd_compress" -eq 1 ]; then
# if inline_zstd_compress is enabled, add ".zst" to the destination filename, and don't run the comparison.
dest_disk+=".zst"
copy_file "$disk" "$dest_disk" "$rsync_dry_run_option" "inline_zstd_compress" "$rsync_only"
else
if [ -f "$dest_disk" ]; then
# if there is an existing backup, use rsync to just copy the changes (i.e. delta_sync).
copy_file "$disk" "$dest_disk" "$rsync_dry_run_option" "inplace" "$rsync_only"
else
# otherwise, copy the whole file (with sparse support)
copy_file "$disk" "$dest_disk" "$rsync_dry_run_option" "sparse" "$rsync_only"
fi
# run compare function. compare will not run if compare_files is disabled.
run_compare "$disk" "$dest_disk" "vdisk"
fi
# make sure the copy has the current date/time for the modified attribute so that removing old backups by date will work.
touch -d "now" "$dest_disk"
# send a message to the user based on whether there was an actual copy or a dry-run.
if [ "$actually_copy_files" -eq 0 ]; then
log_message "information: dry-run backup of $disk vdisk to $dest_disk complete."
else
log_message "information: backup of $disk vdisk to $dest_disk complete."
fi
# check to see if snapshot was created.
if [[ "$snapshot_succeeded" = true ]] && [[ ! "$snapshot_using_traditional_backup" = true ]]; then
# verify vm is still running before attempting to commit changes from snapshot.
if [ "$vm_state" == "running" ]; then
# commit changes from snapshot.
virsh blockcommit "$vm" "${vdisk_specs[$disk]}" --active --wait --verbose --pivot
# wait 5 seconds.
sleep 5
log_message "information: commited changes from snapshot for $disk on $vm."
# see if snapshot still exists.
if [[ -f "$disk_directory/$snap_name" ]]; then
# if it does, forcibly remove it.
rm -fv "$disk_directory/$snap_name"
log_message "information: forcibly removed snapshot $disk_directory/$snap_name for $vm."
fi
else
log_message "warning: snapshot performed for $vm, but vm state is $vm_state. cannot commit changes from snapshot." "script skipping $vm" "warning"
fi
fi
fi
fi
fi
done
}
# build vdisk_extensions_find_cmd.
build_vdisk_extensions_find_cmd () {
# assign arguments to local variables for readability.
local search_directory="$1"
# unset array vdisk_extensions_find_cmd.
unset vdisk_extensions_find_cmd
# initialize vdisk_extensions_find_cmd as empty array.
vdisk_extensions_find_cmd=()
# find each vdisk extension and use it to build a find command.
for extension in "${vdisk_extensions[@]}"
do
local _ext="$extension"
if [ "$inline_zstd_compress" -eq 1 ]; then
_ext+=".zst"
fi
# check to see if find command is empty.
if [ ${#vdisk_extensions_find_cmd[@]} -eq 0 ]; then
# build initial find command.
vdisk_extensions_find_cmd=(find)
vdisk_extensions_find_cmd+=("$search_directory")
vdisk_extensions_find_cmd+=(-type f)
vdisk_extensions_find_cmd+=(\()
vdisk_extensions_find_cmd+=(-name '*.'"$_ext")
else
# add additional extensions to find command.
vdisk_extensions_find_cmd+=(-or -name '*.'"$_ext")
fi
done
# put closing parenthesis on find command.
vdisk_extensions_find_cmd+=(\))
}
# build remove_old_files_cmd.
build_remove_old_files_cmd () {
# assign arguments to local variables for readability.
local search_directory="$1"
# remove config, nvram, and image files that were compressed.
# unset array remove_old_files_cmd.
unset remove_old_files_cmd
# initialize remove_old_files_cmd as empty array.
remove_old_files_cmd=()
# find each vdisk extension and use it to build a remove command.
for extension in "${vdisk_extensions[@]}"
do
# check to see if remove command is empty.
if [ ${#remove_old_files_cmd[@]} -eq 0 ]; then
# build intial remove command.
remove_old_files_cmd=(find)
remove_old_files_cmd+=("$search_directory")
remove_old_files_cmd+=(-type f)
remove_old_files_cmd+=(\()
remove_old_files_cmd+=(-name '*.'"$extension")
else
# add additional extensions to remove command.
remove_old_files_cmd+=(-or -name '*.'"$extension")
fi
done
# add config files to remove command.
remove_old_files_cmd+=(-or -name '*.xml')
# add nvram files to remove command.
remove_old_files_cmd+=(-or -name '*.'"$nvram_extension")
# put closing parenthesis on remove command.
remove_old_files_cmd+=(\))
# add delete command to remove command.
remove_old_files_cmd+=(-delete)
}
# remove old files
remove_old_files () {
# assign arguments to local variables for readability.
local -n _find_cmd=$1
local _type="$2"
# create variable equal to number_of_days_to_keep_backups plus one to make sure that there are files younger than the cutoff date.
local _days_plus_one=$((number_of_days_to_keep_backups + 1))
local _days_to_mins=$((24*60))
local _deleted_files
if [[ -n $("${_find_cmd[@]}" -mmin -$((_days_plus_one*_days_to_mins))) ]]; then
_deleted_files=$("${_find_cmd[@]}" -mmin +$((number_of_days_to_keep_backups*_days_to_mins)) -delete -print)
fi
if [[ -n "$_deleted_files" ]]; then
for _deleted_file in $_deleted_files
do
log_message "information: $_deleted_file $_type file." "script removing $_type file" "normal"
done
else
log_message "information: did not find any $_type files to remove." "script removing $_type file" "normal"
fi
}
# remove over limit files
remove_over_limit_files () {
# assign arguments to local variables for readability.
local -n _find_cmd=$1
local _number_of_files_to_keep="$2"
local _type="$3"
local _deleted_files
_deleted_files=$("${_find_cmd[@]}" -printf '%T@\t%p\n' | sort -t $'\t' -gr | tail -n +$((_number_of_files_to_keep + 1)) | cut -d $'\t' -f 2- | xargs -d '\n' -r rm -fv --)
if [[ -n "$_deleted_files" ]]; then
for _deleted_file in $_deleted_files
do
log_message "information: $_deleted_file $_type file." "script removing $_type file" "normal"
done
else
log_message "information: did not find any $_type files to remove." "script removing $_type file" "normal"
fi
}
# prepare vm for backup.
prepare_vm () {
# assign arguments to local variables for readability.
local vm="$1"
local vm_state="$2"
if [ "$pause_vms" -eq 1 ]; then
vm_desired_state="paused"
else
vm_desired_state="shut off"
fi
# check to see if the vm is in the desired state.
if [ "$vm_state" == "$vm_desired_state" ]; then
# set a flag to check later to indicate whether to backup this vm or not.
can_backup_vm="y"
log_message "information: $vm is $vm_state. vm desired state is $vm_desired_state. can_backup_vm set to $can_backup_vm."
# check to see if vm is shut off.
elif [ "$vm_state" == "shut off" ] && [ ! "$vm_desired_state" == "shut off" ]; then
# set a flag to check later to indicate whether to backup this vm or not.
can_backup_vm="y"
log_message "information: $vm is $vm_state. vm desired state is $vm_desired_state. can_backup_vm set to $can_backup_vm."
# if the vm is running, try to get it to the desired state.
elif [ "$vm_state" == "running" ] || { [ "$vm_state" == "paused" ] && [ ! "$vm_desired_state" == "paused" ]; }; then
log_message "infomration: $vm is $vm_state. vm desired state is $vm_desired_state."
if [ "$vm_desired_state" == "paused" ]; then
# attempt to pause the vm.
virsh suspend "$vm"
log_message "information: $vm is $vm_state. vm desired state is $vm_desired_state. performing $clean_shutdown_checks $seconds_to_wait second cycles waiting for $vm to pause. "
elif [ "$vm_desired_state" == "shut off" ]; then
# resume the vm if it is suspended, based on testing this should be instant but will trap later if it has not resumed.
if [ "$vm_state" == "paused" ]; then
log_message "action: $vm is $vm_state. vm desired state is $vm_desired_state. resuming."
# resume the vm.
virsh resume "$vm"
fi
# attempt to cleanly shutdown the vm.
virsh shutdown "$vm"
log_message "information: performing $clean_shutdown_checks $seconds_to_wait second cycles waiting for $vm to shutdown cleanly."
fi
# the shutdown of the vm may last a while so we are going to check periodically based on global input variables.
for (( i=1; i<=clean_shutdown_checks; i++ ))
do
log_message "information: cycle $i of $clean_shutdown_checks: waiting $seconds_to_wait seconds before checking if the vm has entered the desired state."
# wait x seconds based on how many seconds the user wants to wait between checks for a clean shutdown.
sleep $seconds_to_wait
# get the state of the vm.
vm_state=$(virsh domstate "$vm")
# if the vm is running decide what to do.
if [ ! "$vm_state" == "$vm_desired_state" ]; then
log_message "information: $vm is $vm_state. vm desired state is $vm_desired_state."
# if we have already exhausted our wait time set by the script variables then its time to do something else.
if [ $i = "$clean_shutdown_checks" ] ; then
# check if the user wants to kill the vm on failure of unclean shutdown.
if [ "$kill_vm_if_cant_shutdown" -eq 1 ]; then
log_message "information: kill_vm_if_cant_shutdown is $kill_vm_if_cant_shutdown. killing vm."
# destroy vm, based on testing this should be instant and without failure.
virsh destroy "$vm"
# get the state of the vm.
vm_state=$(virsh domstate "$vm")
# if the vm is shut off then proceed or give up.
if [ "$vm_state" == "shut off" ]; then
# set a flag to check later to indicate whether to backup this vm or not.
can_backup_vm="y"
log_message "information: $vm is $vm_state. vm desired state is $vm_desired_state. can_backup_vm set to $can_backup_vm."
break
else
# set a flag to check later to indicate whether to backup this vm or not.
can_backup_vm="n"
log_message "failure: $vm is $vm_state. vm desired state is $vm_desired_state. can_backup_vm set to $can_backup_vm." "$vm backup failed" "alert"
fi
# if the user doesn't want to force a shutdown then there is nothing more to do so i cannot backup the vm.
else
# set a flag to check later to indicate whether to backup this vm or not.
can_backup_vm="n"
log_message "failure: $vm is $vm_state. vm desired state is $vm_desired_state. can_backup_vm set to $can_backup_vm." "$vm backup failed" "alert"
fi
fi