-
Notifications
You must be signed in to change notification settings - Fork 22
/
eve4pve-barc
executable file
·1565 lines (1309 loc) · 57.6 KB
/
eve4pve-barc
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
# EnterpriseVE Backup And Restore Ceph for Proxmox VE.
# Author: Daniele Corsini <[email protected]>
# Bastian Mäuser <[email protected]>
declare -r VERSION=0.2.8
declare -r NAME=$(basename "$0")
declare -r PROGNAME=${NAME%.*}
declare -r PVE_DIR="/etc/pve"
declare -r PVE_FIREWALL="$PVE_DIR/firewall"
declare -r PVE_NODES="$PVE_DIR/nodes"
declare -r QEMU='qemu-server'
declare -r LXC='lxc'
declare -r QEMU_CONF_CLUSTER="$PVE_NODES/*/$QEMU"
declare -r LXC_CONF_CLUSTER="$PVE_NODES/*/$LXC"
declare -r LOG_FILE=$(mktemp)
declare -r EXT_IMAGE='.img'
declare -r EXT_DIFF='.diff'
declare -r EXT_CONF='.conf'
declare -r EXT_FIREWALL='.fw'
declare -r -A -g ckext=( [md5sum]="md5" [sha1sum]="sha1" [sha224sum]="sha224" [sha256sum]="sha256" [sha384sum]="sha384" [sha512sum]="sha512" )
declare -r -A -g compext=( [none]="" [gzip]=".gz" [bzip2]=".bz2" [pigz]=".zz")
declare opt_vm_ids=''
declare opt_cksum=true
declare opt_ckmethod="sha1sum"
declare opt_compress="none"
declare opt_compressthreads=2
declare opt_qemu_freeze=false
declare opt_renew #=0
declare opt_retain
declare -i opt_keep #=0
declare -i opt_iothreads=10
declare -i opt_syslog=0
declare -i opt_debug=0
declare -i opt_dry_run=0
declare opt_path_backup=''
declare opt_label=''
declare opt_script=''
declare opt_addr_mail=''
declare -i opt_unprotect_snap=0
declare snap_name_prefix=''
declare path_backup=''
declare -i vm_id=0
declare -A vm_ids
declare -A -g pvnode
declare -i -g vmtotal=0
declare -i -g vmok=0
declare -i -g snapshottotal=0
declare -i -g snapshotok=0
declare -i -g exporttotal=0
declare -i -g exportok=0
declare -i -g bytecount=0
declare -i -g uncompressedbytecount=0
declare -g startts
declare -g endts
declare -r renum='^[0-9]+$'
declare -r retime='([0-9]+)([d,w])$'
declare -r reimg='^([0-9]+)([a-zA-Z0-9_-]+)\.(.*)\.(diff|img).?(.*)?'
declare -r redateex='^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})$'
function map_vmids_to_host(){
for node in $(/usr/bin/pvecm nodes | tail -n +5 | tr -s ' ' | cut -d' ' -f 4)
do
for vm in $(ssh root@$node qm list | tail -n +2 | tr -s ' ' | cut -f 2 -d' ')
do
pvnode[$vm]=$node
done
done
}
function usage(){
shift
if [ "$1" != "--no-logo" ]; then
cat << EOF
______ __ _ _ ________
/ ____/___ / /____ _________ _____(_)_______ | | / / ____/
/ __/ / __ \/ __/ _ \/ ___/ __ \/ ___/ / ___/ _ \ | | / / __/
/ /___/ / / / /_/ __/ / / /_/ / / / (__ ) __/ | |/ / /___
/_____/_/ /_/\__/\___/_/ / .___/_/ /_/____/\___/ |___/_____/
/_/
EOF
fi
cat << EOF
EnterpriseVE Backup And Restore Ceph for Proxmox VE (Made in Italy)
Usage:
$PROGNAME <COMMAND> [ARGS] [OPTIONS]
$PROGNAME help
$PROGNAME version
$PROGNAME create --vmid=<string> --label=<string> --path=<string> [--keep=<integer>|--renew=<integer>]
--script=<string> --mail=<string> --unprotect-snap --syslog
$PROGNAME destroy --vmid=<string> --label=<string> --path=<string>
$PROGNAME enable --vmid=<string> --label=<string> --path=<string>
$PROGNAME disable --vmid=<string> --label=<string> --path=<string>
$PROGNAME backup --vmid=<string> --label=<string> --path=<string> [--keep=<integer>|--renew=<integer>]
--script=<string> --mail=<string> --unprotect-snap --syslog
$PROGNAME restore --vmid=<string> --label=<string> --path=<string>
--script=<string> --syslog
$PROGNAME status --vmid=<string> --label=<string> --path=<string>
$PROGNAME clean --vmid=<string> --label=<string> --path=<string> [--keep=<integer>|--renew=<integer>]
$PROGNAME reset --vmid=<string> --label=<string>
$PROGNAME assemble --vmid=<string> --label=<string> --path=<string>
--script=<string>
Commands:
version Show version program
help Show help program
create Create backup job from scheduler
destroy Remove backup job from scheduler
enable Enable backup job from scheduler
disable Disable backup job from scheduler
status Get list of all backups
clean Clear all backup
reset Remove all snapshots on images specific VM/CT in Ceph
backup Will backup one time
restore Will restore image one time
assemble Assemble a unique image with diff file. (Require eve4ceph-mdti)
Options:
--vmid The ID of the VM/CT, comma separated (es. 100,101,102),
'all-???' for all known guest systems in specific host (es. all-pve1, all-\$(hostname)),
'all' for all known guest systems in cluster,
'storage-???' storage Proxmox VE (pool Ceph)
--label Is usually 'hourly', 'daily', 'weekly', or 'monthly'
--path Path destination backup
--keep Specify the number of differential backups which should will keep, (default: 1)
--renew Specify how many diffs may accumulate, until a full Backup is issued
--renew=10 for keeping 10 Diffs until making a new full export
--renew=7d for making diffs up to 7 days, until making a new full export
--retain Specify how many Backups should be kept, timewise (default: infinite - if unset, nothing is ever deleted)
--retain=30d to keep Backups for 30 days. If the Point in time matches a diff,
it keeps all previous diffs up to the preceding full image to ensure possibility to restore data
--cksum Store checksums for snapshot validation (default: true)
--ckmethod Method used for Checksumming [m5sum, sha1sum, sha224sum, sha384sum, sha512sum] (default: sha1sum)
--qemu-freeze Issue fsfreeze-freeze prio snapshotting and fsfreeze-thaw after snapshot completion (default: true)
--iothreads Specify number of IO threads for exporting (default: 10)
--compress Specify compression method [none,gzip,bzip2,pigz] (default: none)
--compressthreads Specify compression threads for pigz (default: 2)
--script Use specified hook script
E.g. /usr/share/doc/$PROGNAME/examples/script-hook.sh
--syslog Write messages into the system log
--mail Email addresses send log backup, comma separated (es. [email protected],[email protected])
--unprotect-snap Disable protection snapshot, default is protected.
In Proxmox VE 'protected snapshot' cause problem in remove VM/CT see documentation.
--debug Show detail debug
--dry-run Not execute command print only
Report bugs to <[email protected]>
EOF
exit 1
}
function log(){
local level=$1
shift 1
local message=$*
case $level in
debug)
if [ $opt_debug -eq 1 ]; then
echo -e "$(date "+%F %T") DEBUG: $message";
echo -e "$(date "+%F %T") DEBUG: $message" >> "$LOG_FILE";
fi
;;
info)
echo -e "$message";
echo -e "$message" >> "$LOG_FILE";
[ $opt_syslog -eq 1 ] && logger -t "$PROGNAME" "$message"
;;
warn)
echo "WARNING: $message" 1>&2
echo -e "$message" >> "$LOG_FILE";
[ $opt_syslog -eq 1 ] && logger -t "$PROGNAME" -p daemon.warn "$message"
;;
error)
echo "ERROR: $message" 1>&2
echo -e "$message" >> "$LOG_FILE";
[ $opt_syslog -eq 1 ] && logger -t "$PROGNAME" -p daemon.err "$message"
;;
*)
echo "$message" 1>&2
echo -e "$message" >> "$LOG_FILE";
[ $opt_syslog -eq 1 ] && logger -t "$PROGNAME" "$message"
;;
esac
}
function get_vm_ids(){
local data=''
local conf=''
while [ $# -gt 0 ]; do
for conf in $1; do
[ ! -e "$conf" ] && break
conf=$(basename "$conf")
[ "$data" != '' ] && data="$data,"
data="$data${conf%.*}"
done
shift
done
echo "$data"
}
function exist_file(){
local file=''
for file in $1; do
[ -e "$file" ] && return 0 || return 1
break
done
}
function parse_opts(){
local action=$1
shift
local args
args=$(getopt \
--options '' \
--longoptions=path:,vmid:,label:,keep:,renew:,retain:,cksum:,ckmethod:,iothreads:,compress:,compressthreads:,mail: \
--longoptions=script:,syslog,debug,dry-run,unprotect-snap,qemu-freeze \
--name "$PROGNAME" \
-- "$@") \
|| end_process 128
eval set -- "$args"
while true; do
case "$1" in
--vmid) opt_vm_ids=$2; shift 2;;
--label) opt_label="$2"; shift 2;;
--keep) opt_keep=$2; shift 2;;
--renew) opt_renew="$2"; shift 2;;
--retain) opt_retain="$2"; shift 2;;
--cksum) opt_cksum=$2; shift 2;;
--ckmethod) opt_ckmethod=$2; shift 2;;
--iothreads) opt_iothreads=$2; shift 2;;
--compress) opt_compress=$2; shift 2;;
--compressthreads) opt_compressthreads=$2; shift;;
--qemu-freeze) opt_qemu_freeze=true; shift;;
--path) opt_path_backup="$2"; shift 2;;
--script) opt_script="$2"; shift 2;;
--syslog) opt_syslog=1; shift;;
--debug) opt_debug=1; shift;;
--dry-run) opt_dry_run=1; shift;;
--unprotect-snap) opt_unprotect_snap=1; shift;;
--mail) opt_addr_mail="$2"; shift 2;;
--) shift; break;;
*) break;;
esac
done
if [ $opt_debug -eq 1 ]; then
log info "============================================"
log info "EnterpriseVE BARC Version: $VERSION";
log info "============================================"
log info "Proxmox VE Version:"
#info proxmox
pveversion --verbose
log info "============================================"
fi
if [ "$action" != "reset" ]; then
[ ! -d "$opt_path_backup" ] && { log info "Path Backup is not set"; end_process 1; }
fi
if ! [[ "$opt_ckmethod" == "md5sum" || "$opt_ckmethod" == "sha1sum" || "$opt_ckmethod" == "sha224sum" || "$opt_ckmethod" == "sha384sum" || "$opt_ckmethod" == "sha512sum" ]]; then
log info "Invalid --ckmethod."
end_process 1
fi
if [ "$opt_keep" ] && [ "$opt_renew" ]; then
log info "Conflicting Options! You cannot use --keep in conjunction with --renew."
end_process 1
fi
[ -z "$opt_vm_ids" ] && { log info "VM id is not set."; end_process 1; }
if [ "$opt_vm_ids" = "all" ]; then
#all in cluster
local data=''
data=$(get_vm_ids "$QEMU_CONF_CLUSTER/*$EXT_CONF" "$LXC_CONF_CLUSTER/*$EXT_CONF")
vm_ids=$(echo "$data" | tr ',' '\n')
elif [[ "$opt_vm_ids" == "all-"* ]]; then
#all in specific host
local host=${opt_vm_ids#*-}
if ! exist_file "$PVE_NODES/$host"; then
log info "Host not found!"
end_process 1
fi
local data=''
data=$(get_vm_ids "$PVE_NODES/$host/$QEMU/*$EXT_CONF" "$PVE_NODES/$host/$LXC/*$EXT_CONF")
[ -z "$data" ] && { log info "VM id is not set."; end_process 1; }
vm_ids=$(echo "$data" | tr ',' '\n')
elif [[ "$opt_vm_ids" == "storage-"* ]]; then
#all in specific storage (pool Ceph)
local storage=${opt_vm_ids#*-}
if ! pvesm list "$storage" > /dev/null 2>&1; then
log info "Pool '$storage' not found in Proxmox VE storage."
end_process 1
fi
vm_ids=$(pvesm list "$storage" | awk '{print $4}' | awk '!a[$0]++' )
else
#comma separated
vm_ids=$(echo "$opt_vm_ids" | tr ',' "\n")
fi
[ -z "$opt_label" ] && { log info "Label is not set correctly"; end_process 1; }
[ "$opt_keep" ] && [ "$opt_keep" -le 0 ] && { log info "Keep is not set correctly. Value > 0."; end_process 1; }
snap_name_prefix="barc$opt_label"
}
function get_path(){
path_backup="$opt_path_backup/barc/$vm_id/$opt_label"
}
function cron_action_job(){
local action=$1
parse_opts "$@"
local -r cron_file="/etc/cron.d/$PROGNAME"
local -r job_key_cron="backup --vmid=$opt_vm_ids --label='$opt_label' --path='$opt_path_backup'"
#create cron file if not exist
if [ ! -e "$cron_file" ]; then
cat > "$cron_file" << EOL
#Cron file for $PROGNAME automatically generated
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
EOL
fi
local check=0; [ "$action" = "create" ] && check=1
if grep -h "$job_key_cron" "$cron_file"; then
[ $check -eq 1 ] && { log info "Job already exists in cron file '$cron_file'"; exit 1; }
else
[ $check -eq 0 ] && { log info "Job not exists in cron file '$cron_file'"; exit 1; }
fi
#action
case $action in
create)
local cron_scheduling="0 0 * * *" #Default run once a day at midnight
case "$opt_label" in
(*hourly*) cron_scheduling="0 * * * *";; #Run once an hour at the beginning of the hour
(*daily*) cron_scheduling="0 0 * * *";; #Run once a day at midnight
(*weekly*) cron_scheduling="0 0 * * 0";; #Run once a week at midnight on Sunday morning
(*monthly*) cron_scheduling="0 0 1 * *";; #Run once a month at midnight of the first day of the month
esac
local job="$cron_scheduling root $PROGNAME $job_key_cron"
[ ! -z "$opt_keep" ] && job="$job --keep=$opt_keep"
[ ! -z "$opt_renew" ] && job="$job --renew=$opt_renew"
[ ! -z "$opt_retain" ] && job="$job --retain=$opt_retain"
[ ! -z "$opt_compress" ] && job="$job --compress=$opt_compress"
[ ! -z "$opt_compressthreads" ] && job="$job --compressthreads=$opt_compressthreads"
[ ! -z "$opt_iothreads" ] && job="$job --iothreads=$opt_iothreads"
[ -e "$opt_script" ] && job="$job --script='$opt_script'"
[ $opt_unprotect_snap -eq 1 ] && job="$job --unprotect-snap"
[ $opt_syslog -eq 1 ] && job="$job --syslog"
[ ! -z "$opt_addr_mail" ] && job="$job --mail='$opt_addr_mail'"
echo -e "$job" >> "$cron_file"
;;
destroy) sed -i "\?$job_key_cron?d" "$cron_file";;
enable) sed -i "\?$job_key_cron?s?^#??g" "$cron_file";;
disable) sed -i "\?$job_key_cron?s?^?#?g" "$cron_file";;
esac
echo -e "Job $action in cron file '$cron_file'";
}
function vm_freeze() {
local fvm=$1;
local fhost=$2;
status=$(ssh root@$fhost qm status $fvm|cut -d' ' -f 2)
if ! [[ "$status" == "running" ]]; then
log info "VM $fvm - Not running, skipping fsfreeze-freeze"
return
fi
local cmd="ssh root@$fhost /usr/sbin/qm guest cmd $fvm fsfreeze-freeze"
log info "VM $fvm - Issuing fsfreeze-freeze to $fvm on $fhost"
log debug "$cmd"
do_run "$cmd"
rc=$?
log debug "vm_freeze() return $rc"
}
function vm_unfreeze() {
local fvm=$1;
local fhost=$2;
status=$(ssh root@$fhost qm status $fvm|cut -d' ' -f 2)
if ! [[ "$status" == "running" ]]; then
log info "VM $fvm - Not running, skipping fsfreeze-thaw"
return
fi
local cmd="ssh root@$fhost /usr/sbin/qm guest cmd $fvm fsfreeze-thaw"
log info "VM $fvm - Issuing fsfreeze-thaw to $fvm on $fhost"
log debug "$cmd"
do_run "$cmd"
rc=$?
log debug "vm_unfreeze() return $rc"
}
function do_run(){
local cmd=$*;
local -i rc=0;
if [ $opt_dry_run -eq 1 ]; then
echo "$cmd"
rc=$?
else
log debug "$cmd"
eval "$cmd"
rc=$?
[ $rc != 0 ] && log error "$cmd"
log debug "return $rc ps ${PIPESTATUS[@]}"
fi
return $rc
}
function clean(){
parse_opts "$@"
local begin=$SECONDS
log debug "$PROGNAME $VERSION"
log debug "Command line: $*"
call_hook_script "clean-job-start" "-" "-"
for vm_id in $vm_ids; do
get_path
merge_diff_backup
done
vm_id=0
call_hook_script "clean-job-end" "-" "-"
log debug "Execution: $((SECONDS-begin)) sec."
}
function create_snapshot(){
local snap="$1"
call_hook_script "snap-create-pre" "$snap" "-"
log info "VM $vm_id - Creating snapshot $snap"
if ! do_run "rbd snap create $snap"; then
call_hook_script "snap-create-abort" "$snap" "-"
return 1;
fi
#check if protected/unprotect mode snapshot
if [ $opt_unprotect_snap -eq 0 ]; then
if ! do_run "rbd snap protect $snap"; then
call_hook_script "snap-create-abort" "$snap" "-"
return 1;
fi
else
log info "VM $vm_id - !!!!! >>> UNPROTECTED SNAPSHOT $snap <<< !!!!!"
fi
call_hook_script "snap-create-post" "$snap" "-"
}
function remove_snaphot(){
local snap="$1"
local hook="$2"
[ "$hook" -eq 1 ] && call_hook_script "snap-remove-pre" "$snap" "-"
log info "VM $vm_id - Remove snapshot $snap"
#check is protectd
local info; info=$(rbd info $snap | grep 'protected: True');
if [ ! -z "$info" ]; then
if ! do_run "rbd snap unprotect $snap"; then
[ "$hook" -eq 1 ] && call_hook_script "snap-remove-abort" "$snap" "-"
return 1;
fi
fi
if ! do_run "rbd snap rm $snap"; then
[ "$hook" -eq 1 ] && call_hook_script "snap-remove-abort" "$snap" "-"
return 1;
fi
[ "$hook" -eq 1 ] && call_hook_script "snap-remove-post" "$snap" "-"
}
function call_hook_script(){
export EVE4PVE_BARC_PHASE="$1"
export EVE4PVE_BARC_SNAP_NAME="$2"
export EVE4PVE_BARC_BACKUP_FILE="$3"
export EVE4PVE_BARC_VMID=$vm_id
export EVE4PVE_BARC_PATH="$opt_path_backup"
export EVE4PVE_BARC_LABEL="$opt_label"
export EVE4PVE_BARC_KEEP=$opt_keep
log debug "-------------------------------------------------------"
log debug "EVE4PVE_BARC_PHASE: $EVE4PVE_BARC_PHASE"
log debug "EVE4PVE_BARC_VMID: $EVE4PVE_BARC_VMID"
log debug "EVE4PVE_BARC_PATH: $EVE4PVE_BARC_PATH"
log debug "EVE4PVE_BARC_LABEL: $EVE4PVE_BARC_LABEL"
log debug "EVE4PVE_BARC_KEEP: $EVE4PVE_BARC_KEEP"
log debug "EVE4PVE_BARC_SNAP_NAME: $EVE4PVE_BARC_SNAP_NAME"
log debug "EVE4PVE_BARC_BACKUP_FILE: $EVE4PVE_BARC_BACKUP_FILE"
log debug "-------------------------------------------------------"
if [ -e "$opt_script" ]; then
log debug "VM $vm_id - Script hook: $opt_script"
do_run "$opt_script"
fi
}
function get_disks_from_config(){
local disks;
local file_config=$1
#disks available for vm/ct
#exclude no backup
#read current config
disks=$(while read -r line; do
[[ "$line" == "" ]] && break
echo "$line"
done < "$file_config" | \
grep -P '^(?:((?:virtio|ide|scsi|sata|mp|efidisk)\d+)|rootfs): ' | \
grep -v -P '^(?!.*cloudinit).*media=cdrom.*$' | \
grep -v -P 'backup=0' | \
awk '{ split($0,a,","); split(a[1],b," "); print b[2]}')
echo "$disks"
}
function backup(){
local -i rc=0;
local vmname
parse_opts "$@"
startts=$(date +%s)
log info "ACTION: Backup"
local timestamp; timestamp=$(date +%Y%m%d%H%M%S)
log info "Start backup $(date "+%F %T")"
#create pid file
local pid_file="/var/run/$PROGNAME.pid"
if [[ -e "$pid_file" ]]; then
local pid; pid=$(cat "${pid_file}")
if ps -p "$pid" > /dev/null 2>&1; then
log error "Process already running with pid ${pid}"
end_process 1
fi
fi
if ! echo $$ > "$pid_file"; then
log error "Could not create PID file $pid_file"
end_process 1
fi
call_hook_script "backup-job-start" "-" "-"
map_vmids_to_host
for vm_id in $vm_ids; do
log debug "Backing up VMID: $vm_id"
vmtotal=$((vmtotal+1))
local file_config; file_config=$(get_config_file)
[ -z "$file_config" ] && continue
#create path backup
get_path
if ! mkdir -p "$path_backup"; then
log error "VM $vm_id - Problem creation path '$path_backup'"
rc=10
continue
fi
local -a export_image_spec=()
local -a export_current_snap=()
local -a export_backup_file=()
local -a export_latest_snap=()
local -a export_type=()
local -i export_idx=0
local image_spec
local current_snap
local backup_file
local backup_file_present
local latest_snap
local compress
vmname=`cat $file_config|grep "name\:"|cut -d' ' -f 2`
log info "VM $vm_id - ======== Start backup VMID $vm_id ($vmname) ========"
log info "VM $vm_id - -------- Snapshots Disks VMID $vm_id--------"
[[ "$opt_qemu_freeze" == true ]] && vm_freeze "$vm_id" "${pvnode[$vm_id]}"
#loop disk create snapshot
local disk=''
for disk in $(get_disks_from_config "$file_config"); do
log debug "Working on disk $disk"
snapshottotal=$((snapshottotal+1))
#check rbd device image-spec is pool-name/image-name
image_spec=$(get_image_spec "$disk")
[ -z "$image_spec" ] && continue
#pool-name/image-name@snap-name
current_snap="$image_spec@$snap_name_prefix$timestamp"
local suffix_backup_file=${image_spec//\//.}
backup_file="$path_backup/$timestamp$suffix_backup_file"
#data export
#export_current_snap[$export_idx]="$current_snap"
export_image_spec[$export_idx]="$image_spec"
export_latest_snap[$export_idx]=""
export_type[$export_idx]=""
#obey renew policy
local diffcount=0
local renew=false
#count mode (accumulate diff's until they exceed a given number --renew=X)
log debug "opt_renew: $opt_renew"
if [[ $opt_renew =~ $renum ]]; then
log debug "Iterating backup files..."
for backup_files_present in $(ls -r $path_backup/*$suffix_backup_file{$EXT_DIFF,$EXT_IMAGE}{.zz,.gz,.bz2,} 2>/dev/null); do
log debug "backup_files_present is: $backup_files_present"
file_base=$(basename "$backup_files_present")
log debug "file_base: $file_base"
if [[ "$file_base" =~ $reimg ]]; then
log "Image file found."
ext=${BASH_REMATCH[4]}
if [ "$ext" == 'diff' ]; then
log debug ".diff extension found. Incrementing diff count."
diffcount=$((diffcount+1))
elif [ "$ext" == 'img' ] && [ "$opt_renew" -gt 0 ]; then
log debug ".img extension found & opt_renew is greater than 0. Setting renew to false."
renew=false
break;
else
log debug "Not a .diff file, or not a .img file with opt_renew greater than 0. Setting renew to true."
renew=true
break;
fi
fi
if [ "$diffcount" -ge "$opt_renew" ]; then
log debug "Diff count is greater than opt_renew. Setting renew to true."
renew=true
break;
fi
done
#time mode (accumulate diff's until given time has passed --renew=Xd)
elif [[ $opt_renew =~ $retime ]]; then
local factor=86400 #tbd: support d, w, m
maxage=$((${BASH_REMATCH[1]}*$factor))
for backup_files_present in $(ls -r $path_backup/*$suffix_backup_file{$EXT_DIFF,$EXT_IMAGE}{.zz,.gz,.bz2,} 2>/dev/null); do
log debug "backup_files_present is: $backup_files_present"
file_base=$(basename "$backup_files_present")
log debug "file_base: $file_base"
if [[ "$file_base" =~ $reimg ]]; then
ext=${BASH_REMATCH[4]}
ts=${BASH_REMATCH[1]}
if [[ $ts =~ $redateex ]]; then
fdate=$((`date --date "${BASH_REMATCH[1]}/${BASH_REMATCH[2]}/${BASH_REMATCH[3]} ${BASH_REMATCH[4]}:${BASH_REMATCH[5]}:${BASH_REMATCH[6]}" +%s`))
else
rc=70
break;
fi
age=$((`date +"%s"`-$fdate))
log debug "TS: $ts $ext $fdate $age $backup_files_present"
if [ "$ext" == 'img' ]; then
log debug "Full found, age ($age), maxage ($maxage)"
if [[ $age -ge $maxage ]]; then
log debug "Age of most recent full exceeds maxage"
renew=true
break;
fi
break;
fi
fi
done
fi
#check exist initial export
if [[ $(ls $path_backup/*$suffix_backup_file$EXT_IMAGE{.zz,.gz,.bz2,} 2>/dev/null|wc -l) == 0 ]]; then
#initial export not exist
log info "VM $vm_id - No previous backup: issueing full run for $disk"
backup_file="$backup_file$EXT_IMAGE"
if ! create_snapshot "$current_snap"; then
[[ "$opt_qemu_freeze" == true ]] && vm_unfreeze "$vm_id" "${pvnode[$vm_id]}"
rc=20
break;
fi
export_type[$export_idx]="image"
else
if [ "$renew" == true ]; then
log info "VM $vm_id - Renew policy requires full run for $disk"
backup_file="$backup_file$EXT_IMAGE"
else
log info "VM $vm_id - Renew policy tolerates incremental run for $disk"
backup_file="$backup_file$EXT_DIFF"
fi
#Snapshot Housekeeping..
#find last snapshot in ceph
latest_snap=$(rbd snap ls "$image_spec" | \
awk '{print $2}' | \
grep "$opt_label" | sort -r | head -n 1)
#not exist snapshot on rbd
if [ -z "$latest_snap" ]; then
log error "VM $vm_id - Ceph last snapshot '$image_spec' not found!";
call_hook_script "export-diff-abort" "-" "-"
rc=30
break;
fi
#verify exist last snapshot ceph in file backup
#timestamp last snapshot
local tms_latest_snap
tms_latest_snap=$(echo "$latest_snap" | \
awk -v prf="$snap_name_prefix" '{print substr($1,length(prf)+1)}')
if ! exist_file "$path_backup/$tms_latest_snap$suffix_backup_file.*"; then
log warn "VM $vm_id - Ceph snapshot '$image_spec@$latest_snap' not found in backup '$path_backup/$tms_latest_snap$suffix_backup_file.*'"
log info "VM $vm_id - Issuing full run for $image_spec"
renew=true
fi
#verify exist last backup in ceph snapshot
local latest_backup
latest_backup=$(ls -r $path_backup/*$suffix_backup_file{$EXT_DIFF,$EXT_IMAGE}{.zz,.gz,.bz2,} 2>/dev/null | \
head -n 1 | xargs -n 1 basename | awk '{print substr($1,1,14)}')
latest_backup="$snap_name_prefix$latest_backup"
if ! rbd snap ls "$image_spec" | awk '{print $2}' | grep -q "$latest_backup"; then
log warn "VM $vm_id - Backup '$latest_backup' not found in ceph '$image_spec' snapshot!";
log info "VM $vm_id - Issuing full run for $image_spec"
renew=true
fi
if ! create_snapshot "$current_snap"; then
[[ "$opt_qemu_freeze" == true ]] && vm_unfreeze "$vm_id" "${pvnode[$vm_id]}"
rc=60
break;
fi
export_latest_snap[$export_idx]="$latest_snap"
if [ "$renew" == true ]; then
export_type[$export_idx]="image"
else
export_type[$export_idx]="diff"
fi
fi
snapshotok=$((snapshotok+1))
export_current_snap[$export_idx]="$current_snap"
export_backup_file[$export_idx]="$backup_file"
let export_idx++
done
[[ "$opt_qemu_freeze" == true ]] && vm_unfreeze "$vm_id" "${pvnode[$vm_id]}"
log info "VM $vm_id - -------- Export images -------- "
#loop export file from Ceph
for (( i=0; i<${#export_current_snap[@]}; i++ )); do
exporttotal=$((exporttotal+1))
image_spec=${export_image_spec[$i]};
current_snap=${export_current_snap[$i]};
backup_file="${export_backup_file[$i]}${compext[$opt_compress]}";
latest_snap=${export_latest_snap[$i]};
type=${export_type[$i]};
case "$opt_compress" in
"none" )
compress="cat"
;;
"gzip" )
compress="gzip"
;;
"bzip2" )
compress="bzip2"
;;
"pigz" )
compress="pigz -3 -p $opt_compressthreads"
;;
esac
if [ "$type" == "image" ]; then
#export full
call_hook_script "export-pre" "$current_snap" "$backup_file"
log info "VM $vm_id - Export initial '$backup_file'"
if [ "$opt_cksum" == true ]; then
excmd="rbd export --rbd-concurrent-management-ops $opt_iothreads $current_snap - | tee >($compress > '$backup_file') >({ wc -c; } > $backup_file.${ckext[$opt_ckmethod]}.size) | $opt_ckmethod > $backup_file.${ckext[$opt_ckmethod]}"
else
excmd="rbd export --rbd-concurrent-management-ops $opt_iothreads $current_snap '$backup_file'"
fi
log info "VM $vm_id - excmd: $excmd"
if ! do_run "$excmd"; then
remove_snaphot "$current_snap" 0
call_hook_script "export-abort" "$current_snap" "$backup_file"
log info "VM $vm_id - Remove file '$backup_file'"
rm -f "$backup_file"
break;
fi
call_hook_script "export-post" "$current_snap" "$backup_file"
#Check if previous snapshots has to be removed
if [ "$latest_snap" != "" ]; then
remove_snaphot "$image_spec@$latest_snap" 1
fi
elif [ "$type" == "diff" ]; then
#export-diff difference previous snapshot
call_hook_script "export-diff-pre" "$current_snap" "$backup_file"
log info "VM $vm_id - Export diff '$backup_file'"
if [ "$opt_cksum" == true ]; then
excmd="rbd export-diff --from-snap $latest_snap $current_snap - | tee >($compress > '$backup_file') >({ wc -c; } > $backup_file.${ckext[$opt_ckmethod]}.size) | $opt_ckmethod > $backup_file.${ckext[$opt_ckmethod]}"
else
excmd="rbd export-diff --from-snap $latest_snap $current_snap '$backup_file'"
fi
log info "VM $vm_id - excmd: $excmd"
if ! do_run "$excmd"; then
remove_snaphot "$current_snap" 0
call_hook_script "export-diff-abort" "$current_snap" "$backup_file"
log info "VM $vm_id - Remove file '$backup_file'"
rm -f "$backup_file"
break;
fi
call_hook_script "export-diff-post" "$current_snap" "$backup_file"
#remove previous snapshot
remove_snaphot "$image_spec@$latest_snap" 1
fi
exportok=$((exportok+1))
log info "VM $vm_id - Size $(bytesToHuman "$(get_size_file "$backup_file")") Uncompressed: $(bytesToHuman "$(<$backup_file.${ckext[$opt_ckmethod]}.size)") Compressionratio 1:$(($(<$backup_file.${ckext[$opt_ckmethod]}.size)/$(get_size_file "$backup_file")))"
bytecount=$((bytecount+$(sum_size_file "$backup_file")))
uncompressedbytecount=$((uncompressedbytecount+$(<$backup_file.${ckext[$opt_ckmethod]}.size)))
done
#copy config files
log info "VM $vm_id - -------- Copy config --------"
do_run "cp '$file_config' '$path_backup/$timestamp$EXT_CONF'"
#copy firewall files
local file_firewall="$PVE_FIREWALL/$vm_id$EXT_FIREWALL"
if [ -e "$file_firewall" ]; then
log info "VM $vm_id - -------- Copy firewall --------"
do_run "cp '$file_firewall' '$path_backup/$timestamp$EXT_FIREWALL'"
fi
vmok=$((vmok+1))
# If no renew policy is set, do the merge magic
if [[ "$opt_renew" == "" ]]; then
log info "VM $vm_id - -------- Merge diff file --------"
merge_diff_backup
fi
# If renew policy is set, do some housekeeping
if ! [[ "$opt_renew" == "" ]] && [[ $opt_retain =~ $retime ]] || [[ $opt_retain =~ $renum ]]; then
log info "VM $vm_id - -------- Housekeeping --------"
housekeeping
fi
done
vm_id=0
rm "$pid_file"
call_hook_script "backup-job-end" "-" "-"
timestamp=$(date +%Y%m%d%H%M%S)
log info "End backup $(date "+%F %T")"
endts=$(date +%s)
end_process $rc
}
function get_size_file(){
echo $(ls -l "$1" | awk '{print $5}')
}
function sum_size_file(){
echo $((sumbytes+$(ls -l "$1" | awk '{print $5}')))
}
function housekeeping() {
local image=''
local keepfile=true
local imgreached=false
local factor=86400 #tbd
local filecount=0
if [[ $opt_retain =~ $retime ]]; then
log debug "Time based housekeeping."
maxage=$((${BASH_REMATCH[1]}*$factor))
for image in $(ls -r $path_backup/*{$EXT_DIFF,$EXT_IMAGE}{.zz,.gz,.bz2,} 2>/dev/null); do
log debug "Image: $image"
file_base=$(basename "$image")
if [[ "$file_base" =~ $reimg ]]; then
ext=${BASH_REMATCH[4]}
ts=${BASH_REMATCH[1]}
if [[ $ts =~ $redateex ]]; then
fdate=$((`date --date "${BASH_REMATCH[1]}/${BASH_REMATCH[2]}/${BASH_REMATCH[3]} ${BASH_REMATCH[4]}:${BASH_REMATCH[5]}:${BASH_REMATCH[6]}" +%s`))
else
rc=10
log error "Houskeeping Error"
break;
fi
age=$((`date +"%s"`-$fdate))
if [[ $age -ge $maxage ]]; then
if [[ ".$ext" == "$EXT_IMAGE" ]]; then
imgreached=true
fi
fi
if ! [[ "$keepfile" == true ]]; then
log info "VM $vm_id - Houskeeping deleting: $image"
do_run "rm $image*"
do_run "rm $path_backup/$ts.conf"
fi
if [[ "$imgreached" == true ]]; then
keepfile=false
fi
fi
done
elif [[ $opt_retain =~ $renum ]]; then
log debug "Number based housekeeping."
for image in $(ls -r $path_backup/*{$EXT_DIFF,$EXT_IMAGE}{.zz,.gz,.bz2,} 2>/dev/null); do
log debug "Image: $image"
file_base=$(basename "$image")
if [[ "$file_base" =~ $reimg ]]; then
filecount=$((filecount+1))
ext=${BASH_REMATCH[4]}
ts=${BASH_REMATCH[1]}
if [[ "$filecount" -ge "$opt_retain" ]]; then
if [[ ".$ext" == "$EXT_IMAGE" ]]; then
imgreached=true
fi
fi
if ! [[ "$keepfile" == true ]]; then
log info "VM $vm_id - Houskeeping deleting: $image"
do_run "rm $image*"
do_run "rm $path_backup/$ts.conf"
fi
if [[ "$imgreached" == true ]]; then