-
Notifications
You must be signed in to change notification settings - Fork 40
/
zxfer
executable file
·2350 lines (2013 loc) · 78.3 KB
/
zxfer
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/sh
# BSD HEADER START
# Copyright (c) 2013-2019 Allan Jude <allanjude@freebsd.org>
# Copyright (c) 2010,2011 Ivan Nash Dreckman
# Copyright (c) 2007, 2008 Constantin Gonzalez
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# BSD HEADER END
#
# zxfer
#
# Transfer a source zfs filesystem, directory or files to a destination, using
# either zfs send/receive or rsync to do the heavy lifting.
# Comments, suggestions, bug reports please to:
# Allan Jude <allanjude a-t freebsd d-o-t org>
#
# Acknowledgments
# Thanks to Ivan Nash Dreckman for creating zxfer and writing good documentation
# which resulted in zxfer being the most useful of the available tools
#
# Thanks to Constantin Gonzalez (original author of zfs-replicate) for
# the generous permission and licensing of his script zfs-replicate which
# (version 0.7) was used as the basis for this script. Thanks in turn to
# those who contributed to his script.
# Also thanks very much to Constantin for his encouragement, support and
# collaboration along the way. His advice on various decision paths has been
# invaluable.
# Background
# This script is a merge of two scripts - one of my own using Constantin's
# as a template, and my extensively modified version of his zfs-replicate
# script.
# There were two different use cases that lead to both being developed. One
# was an extension of zfs-replicate - I wanted to be able to easily back up
# a whole storage pool to a HDD via an e-SATA dock, with one command. I
# wanted an exact replica of that pool, including snapshots and properties.
# The other use case was to backup a SSD based root mirror to a larger
# HDD based storage pool. It needed atomicity and it needed to be independent
# of snapshots, because I was keeping most of the snapshots on the HDD based
# pool. For this I used rsync.
# In both cases I wanted the reliability that comes with checking hashes
# and checksums against the original files to ensure that the correct
# information had been written, and AFAIK both tools to do this.
# Since then, the scripts have been merged, and the number of features has
# increased. I hope you find it useful.
# Known bugs/gotchas:
# (This is a bug of ZFS on FreeBSD and not this script.)
# There are several properties in FreeBSD that when set via "zfs create"
# or "zfs set" will have the source stay as default while others are
# set to local. This does not have any real impacts because these properties
# are not inheritable. See definition for $fbsd_readonly_properties.
#
# zxfer [-dFnPsUv] [-k | -e] [-b | -B] {-N path/to/src | -R path/to/src}
# [-m [c FMRI|pattern[ FMRI|pattern]...]]] [-O user@host]
# [-D 'progress dialog options'] [-I properties,to,ignore]
# [-T user@host] [-o option1=value1,option2=value2...] [-g days]
# destination
# zxfer {-S} [-dilpPnv] [-k | -e] [-b | -B] [-f /path/to/rsfile]
# {-R /path/to/src1,path/to/src2... | -N /path/to/src1,path/to/src2...}
# [-o option1=value1,option2=value2...] [-E pattern] [-L value]
# [-u snapshot] destination
# zxfer [-h]
#
# Where destination is a ZFS filesystem e.g. poolname/fsname
# zxfer version
zxfer_version="1.1.7-20190219"
# Default values
option_b=0
option_B=0
option_d=0
option_D=""
option_e=0
option_E=""
option_f=""
option_g=""
option_i=0
option_I=""
option_F=""
option_k=0
option_l=0
option_L=""
option_o=""
option_O=""
option_p=0
option_P=0
option_R=""
option_m=0
option_n=0
option_N=""
option_S=0
option_s=0
option_T=""
option_u=0
option_U=0
option_v=0
exit_status=1 # defaults to failure
services=""
torestart=""
source=""
sourcefs=""
destination=""
backup_file_extension=".zxfer_backup_info"
backup_file_contents=""
# operating systems
source_os=""
dest_os=""
home_os=$(uname)
# as in the "cp" man page
trailing_slash=0
LZFS=$( which zfs )
RZFS=$LZFS
LCAT=""
AWK=$( which awk ) # location of awk or gawk on home OS
current_date=$(date +%s) # current date in seconds from 1970
# specific to rsync mode
snapshot_name="zxfertempsnap"
# used in rsync transfers, to turn off the backup file writing
# the first time
dont_write_backup=0
ensure_writable=0 # when creating/setting properties, ensures readonly=off
# default rsync options - see http://www.daemonforums.org/showthread.php?t=3948
default_rsync_options="-clptgoD --inplace --relative -H --numeric-ids"
# note that I am including in the "readonly properties list
# 3 properties that are technically not readonly but we will
# remove them from the override list as it does not make
# sense to try and transfer them - version, volsize and mountpoint
# Others have been added since. This is a potential refactor point
# to split into two lists, $readonly_properties and $zxfer_unsupported_properties
readonly_properties="type,creation,used,available,referenced,\
compressratio,mounted,version,primarycache,secondarycache,\
usedbysnapshots,usedbydataset,usedbychildren,usedbyrefreservation,\
version,volsize,mountpoint,mlslabel,keysource,keystatus,rekeydate,encryption,\
refcompressratio,written,logicalused,logicalreferenced,createtxg,guid,origin,\
filesystem_count,snapshot_count,clones,defer_destroy,receive_resume_token,\
userrefs,objsetid"
# Properties not supported on FreeBSD
fbsd_readonly_properties="aclmode,aclinherit,devices,nbmand,shareiscsi,vscan,\
xattr,dnodesize"
# Properties not supported on Solaris Express 11
solexp_readonly_properties="jailed,aclmode,shareiscsi"
#
# Beeps a success sound if -B enabled, and a failure sound if -b or -B enabled.
# Takes: $exit_status (0 if success, 1 if failure)
#
beep() {
if [ $option_b -eq 1 -o $option_B -eq 1 ]; then
# load the speaker kernel module if not loaded already
speaker_km_loaded=$(kldstat | grep -c speaker.ko)
if [ "$speaker_km_loaded" = "0" ]; then
kldload "speaker"
fi
# play the appropriate beep
if [ $exit_status -eq 0 ]; then
if [ $option_B -eq 1 ]; then
echo "T255CCMLEG~EG..." > /dev/speaker # success sound
fi
else
echo "T150A<C.." > /dev/speaker # failure sound
fi
fi
}
#
# Gets a $(uname), i.e. the operating system, for origin or target, if remote.
# Takes: $1=either $option_O or $option_T
#
get_os() {
input_optionts=$1
output_os=""
# Get uname of the destination (target) machine, local or remote
if [ "$input_optionts" = "" ]; then
output_os=$(uname)
else
output_os=$($input_optionts uname)
fi
}
#
# Initializes OS and local/remote specific variables
#
init_variables() {
get_os "$option_T"
dest_os="$output_os"
get_os "$option_O"
source_os="$output_os"
if [ $option_e -eq 1 ]; then
LCAT=$( ${option_O} which cat )
fi
if [ $option_S -eq 1 ]; then
RSYNC=$( which rsync )
fi
if [ "$home_os" = "SunOS" ]; then
AWK=$( which gawk )
fi
}
#
# Print out usage information
#
usage() {
cat <<EOT
usage:
zxfer [-dFnPsUv] [-k | -e] [-b | -B] {-N path/to/src | -R path/to/src}
[-m [c FMRI|pattern[ FMRI|pattern]...]]] [-O user@host]
[-D 'progress dialog options'] [-I properties,to,ignore]
[-T user@host] [-o option1=value1,option2=value2...] [-g days]
destination
zxfer {-S} [-dilpPnv] [-k | -e] [-b | -B] [-f /path/to/rsfile]
{-R /path/to/src1,path/to/src2... | -N /path/to/src1,path/to/src2...}
[-o option1=value1,option2=value2...] [-E pattern] [-L value]
[-u snapshot] destination
zxfer [-h]
Where destination is a ZFS filesystem e.g. poolname/fsname
zxfer has a man page that explains each of the options in detail, along with
usage examples. To access the man page, type:
$ man zxfer
EOT
}
#
# Print out information if in verbose mode
#
echov() {
if [ $option_v -eq 1 ]; then echo "$@"; fi
}
#
# Stop a list of SMF services. The services are read in from stdin.
#
stopsvcs() {
while read service; do
echov "Disabling service $service."
svcadm disable -st "$service" || \
{ echo "Could not disable service $service."; relaunch; exit 1; }
torestart=$(echo $torestart $service)
done
}
#
# Relaunch a list of stopped services
#
relaunch() {
for i in $torestart; do
echov "Restarting service $i"
svcadm enable "$i" || { echo "Couldn't re-enable service $i."; exit; }
done
}
#
# Checks that options make sense, etc.
#
consistency_check() {
# disallow backup and restore of properties at same time
if [ $option_k -eq 1 -a $option_e -eq 1 ]; then
echo "Error: You cannot bac(k)up and r(e)store properties at the same time."
usage
exit 1
fi
# disallow both beep modes, enforce using one or the other.
if [ $option_b -eq 1 -a $option_B -eq 1 ]; then
echo "Error: You cannot use both beep modes at the same time."
usage
exit 1
fi
if [ $option_S -eq 1 ]; then
# rsync mode
# check for incompatible options
if [ "$option_F" = "-F" ]; then
echo "Error: -F option cannot be used with -S (rsync mode)"
usage
exit 1
fi
if [ $option_s -eq 1 ]; then
echo "Error: -s option cannot be used with -S (rsync mode)"
usage
exit 1
fi
if [ "$option_O" != "" -o "$option_T" != "" ]; then
echo "Error: -O or -T option cannot be used with -S (rsync mode)"
usage
exit 1
fi
if [ $option_m -eq 1 ]; then
echo "Error: -m option cannot be used with -S (rsync mode)"
usage
exit 1
fi
else
#zfs send mode
# check for incompatible options
if [ "$option_f" != "" ]; then
echo "Error: -f option can only be used with -S (rsync mode)"
usage
exit 1
fi
if [ "$option_L" != "" ]; then
echo "Error: -L option can only be used with -S (rsync mode)"
usage
exit 1
fi
# disallow migration related options and remote transfers at same time
if [ "$option_T" != "" -o "$option_O" != "" ]; then
if [ $option_m -eq 1 -o "$services" != "" ]; then
echo "Error: You cannot migrate to or from a remote host."
usage
exit 1
fi
fi
fi
}
#
# Copy a snapshot using zfs send/receive. If a third argument is used, then use
# send -i and the third argument is the base to create the increment from.
# Arguments should be compatible with zfs send and receive commands. Does
# nothing if the snapshot already exists.
# Takes $snapshot, $dest, $lastsnap
#
copy_snap() {
# Test if the snapshot exists already.
copysrc=$snapshot
copydest=$dest
copyprev=$lastsnap
copysrctail=$( echo "$copysrc" | cut -d/ -f2- )
if [ -z "$( echo "$rzfs_list_ho_s" | grep "^$dest/$copysrctail" )" ]; then
echov "Sending $copysrc to $copydest."
if [ "$copyprev" = "" ]; then
if [ "$option_D" != "" ]; then
if [ $option_n -eq 0 ]; then
SIZE_DATASET=$( $LZFS send -nPv "$copysrc" 2>&1 ) ||
{ echo "Error calculating estimate: $SIZE_DATASET"; beep; exit 1; }
SIZE_EST=$( echo "$SIZE_DATASET" | grep ^size | tail -n 1 | cut -f 2 )
echo "Estimated size is: ${SIZE_EST}"
PROGRESS_DIALOG=$( echo "$option_D" | sed "s#%%size%%#$SIZE_EST#g" | \
sed "s#%%title%%#$copysrc#g" )
$LZFS send "$copysrc" | dd obs=1048576 | dd bs=1048576 | $PROGRESS_DIALOG | \
$RZFS receive $option_F "$copydest" || \
{ echo "Error when zfs send/receiving."; beep; exit 1; }
else
SIZE_DATASET=$( $LZFS send -nPv "$copysrc" 2>&1 ) ||
{ echo "Error calculating estimate: $SIZE_DATASET"; beep; exit 1; }
SIZE_EST=$( echo "$SIZE_DATASET" | grep ^size | tail -n 1 | cut -f 2 )
echo "Estimated size is: ${SIZE_EST}"
PROGRESS_DIALOG=$( echo $option_D | sed "s#%%size%%#$SIZE_EST#g" | \
sed "s#%%title%%#$copysrc#g" )
$LZFS send -nv "$copysrc"
echo "$LZFS send $copysrc | dd obs=1048576 | dd bs=1048576 | $PROGRESS_DIALOG |
$RZFS receive $option_F $copydest"
fi
else
if [ $option_n -eq 0 ]; then
$LZFS send "$copysrc" | $RZFS receive $option_F "$copydest" || \
{ echo "Error when zfs send/receiving."; beep; exit 1; }
else
echo "$LZFS send $copysrc | $RZFS receive $option_F $copydest"
fi
fi
else
echov " (incremental to $copyprev.)"
if [ "$option_D" != "" ]; then
if [ $option_n -eq 0 ]; then
SIZE_DATASET=$( $LZFS send -nPv -i "$copyprev" "$copysrc" 2>&1 ) ||
{ echo "Error calculating estimate: $SIZE_DATASET"; beep; exit 1; }
SIZE_EST=$( echo "$SIZE_DATASET" | grep ^size | tail -n 1 | cut -f 2 )
echo "Estimated size is: ${SIZE_EST}"
PROGRESS_DIALOG=$( echo $option_D | sed "s#%%size%%#$SIZE_EST#g" | \
sed "s#%%title%%#$copysrc#g" )
$LZFS send -i "$copyprev" "$copysrc" | dd obs=1048576 | dd bs=1048576 | \
$PROGRESS_DIALOG | $RZFS receive $option_F "$copydest" || \
{ echo "Error when zfs send/receiving."; beep; exit 1; }
else
SIZE_DATASET=$( $LZFS send -nPv -i "$copyprev" "$copysrc" 2>&1 ) ||
{ echo "Error calculating estimate: $SIZE_DATASET"; beep; exit 1; }
SIZE_EST=$( echo "$SIZE_DATASET" | grep ^size | tail -n 1 | cut -f 2 )
echo "Estimated size is: ${SIZE_EST}"
PROGRESS_DIALOG=$( echo $option_D | sed "s#%%size%%#$SIZE_EST#g" | \
sed "s#%%title%%#$copysrc#g" )
$LZFS send -nv -i "$copyprev" "$copysrc"
echo "$LZFS send -i $copyprev $copysrc | dd obs=1048576 | dd bs=1048576 | \
$PROGRESS_DIALOG | $RZFS receive $option_F $copydest"
fi
else
if [ $option_n -eq 0 ]; then
$LZFS send -i "$copyprev" "$copysrc" | $RZFS receive $option_F "$copydest" \
|| { echo "Error when zfs send/receiving."; beep; exit 1; }
else
echo "$LZFS send -i $copyprev $copysrc | $RZFS receive $option_F
$copydest"
fi
fi
fi
fi
}
#
# Copy the list of snapshots given in stdin to the destination in $1.
# Use incremental snapshots where possible. Assumes that the list of snapshots
# is given in creation order. copy_snap is responsible for skipping already
# existing snapshots on the destination side.
# Takes: $dest, $copy_fs_snapshot_list
#
copy_snap_multiple() {
snapshot=""
destsnap=""
desttest=""
lastsnap=""
# if there is a snapshot common to both src and dest, set that to be $lastsnap
if [ $found_last_common_snap -eq 1 ]; then
lastsnap="$source@$last_common_snap"
fi
# XXX: This can get stale, especially if it has taken hours to copy the
# previous snapshot. Consider adding a time check and refreshing the list of
# snapshots if it has been too long since we got the list
for snapshot in $copy_fs_snapshot_list; do
copy_snap
lastsnap=$snapshot
done
}
#
# Copy all snapshots of a given filesystem.
# This takes $src_snapshot_transfer_list and $actual_dest.
#
copy_fs() {
dest=$actual_dest
# Instead of transferring all the source snapshots, this just transfers
# the ones starting from the latest common snapshot on src and dest
copy_fs_snapshot_list=$(echo $src_snapshot_transfer_list | grep ".")
copy_snap_multiple
}
#
# Create a new recursive snapshot.
#
newsnap() {
snap=zxfer_$$_$(date +%Y%m%d%H%M%S)
if [ "$option_R" != "" ]; then
echov "Creating recursive snapshot $sourcefs@$snap."
if [ $option_n -eq 0 ]; then
$LZFS snapshot -r "${sourcefs}@${snap}" || \
{ echo "Error when snapshotting."; exit 1; }
else
echo "$LZFS snapshot -r $sourcefs@$snap"
fi
else
echov "Creating snapshot $sourcefs@$snap."
if [ $option_n -eq 0 ]; then
$LZFS snapshot "${sourcefs}@${snap}" || \
{ echo "Error when snapshotting."; exit 1; }
else
echo "$LZFS snapshot $sourcefs@$snap"
fi
fi
}
#
# Tests a snapshot to see if it is older than the grandfather option allows for.
# Takes $ds, (a destination shapshot)
#
grandfather_test() {
ds=$1
snap_date=$($RZFS get -H -o value -p creation "$ds")
diff_sec=$((current_date-snap_date))
diff_day=$((diff_sec/86400))
if [ $diff_day -ge $option_g ]; then
snap_date_english=$($RZFS get -H -o value creation "$ds")
current_date_english=$(date)
echo "Error: On the destination there is a snapshot marked for destruction"
echo "by zxfer that is protected by the use of the \"grandfather"
echo "protection\" option, -g."
echo
echo "You have set grandfather protection at $option_g days."
echo "Snapshot name: $ds"
echo "Snapshot age : $diff_day days old"
echo "Snapshot date: $snap_date_english."
echo "Your current system date: $current_date_english."
echo
echo "Either amend/remove option g, fix your system date, or manually"
echo "destroy the offending snapshot. Also double check that your"
echo "snapshot management tool isn't erroneously deleting source snapshots."
echo "Note that for option g to work correctly, you should set it just"
echo "above a number of days that will preclude \"father\" snapshots from"
echo "being encountered."
echo
usage; beep
exit 1
fi
}
#
# Find the most recent common snapshot on source and destination.
# Then, create a list of snapshots on source, starting from the
# one after the most recent common snapshot.
# If the -d option is present, delete the snapshots on destination
# that are no longer present on the source.
#
inspect_delete_snap() {
# Get the list of source snapshots
zfs_source_snaps=$(echo "$lzfs_list_hr_S_snap" | \
grep ^$source@) > /dev/null 2>&1
# save a copy for when we need to make a new list
zfs_source_snaps_orig=$zfs_source_snaps
# Get the list of destination snapshots
zfs_dest_snaps=$(echo "$rzfs_list_hr_S_snap" \
| grep ^$actual_dest@) > /dev/null 2>&1
found_last_common_snap=0
# This gets the last common snap, and deletes non-common snaps on destination
# if asked to.
for dest_snap in $zfs_dest_snaps; do
mark_snap_for_deletion=1
for src_snap in $zfs_source_snaps; do
# if the snaps are identical
if [ $(echo $dest_snap | grep @ | cut -d@ -f2) = $(echo $src_snap | \
grep @ | cut -d@ -f2) ]; then
# mark snap not to be deleted
mark_snap_for_deletion=0
# snap is the most recent common snap
if [ $found_last_common_snap -eq 0 ]; then
found_last_common_snap=1
last_common_snap=$(echo $dest_snap | grep @ | cut -d@ -f2)
fi
# since the snap was matched, let's not waste our time searching for
# it again
zfs_source_snaps=$(echo "$zfs_source_snaps" | grep -v "$src_snap")
# let's also break out of the loop, since we've already found what we
# are looking for
break
fi
done
if [ $mark_snap_for_deletion = 1 -a "$option_g" != "" ]; then
grandfather_test "$dest_snap"
fi
if [ $mark_snap_for_deletion = 1 -a $option_d -eq 1 ]; then
echov "Destroying destination snapshot $dest_snap."
if [ $option_n -eq 0 ]; then
# A failed destroy is not a critical error, it is likely caused by
# a hold or a clone. Continue with the replication
$RZFS destroy "$dest_snap" || \
{ echo "Error when zfs destroying."; }
else
echo "$RZFS destroy $dest_snap"
fi
fi
done
src_snapshot_transfer_list=""
found_common=0
# This prepares a list of source snapshots to transfer, beginning with
# the first snapshot after the last common one.
for test_snap in $zfs_source_snaps_orig; do
if [ "$test_snap" != "$source@$last_common_snap" ]; then
if [ $found_common = 0 ]; then
src_snapshot_transfer_list="$test_snap,$src_snapshot_transfer_list"
fi
else
found_common=1
fi
done
src_snapshot_transfer_list=$(echo "$src_snapshot_transfer_list" | tr -s "," "\n")
}
#
# Caches zfs list commands to cut execution time
#
get_zfs_list() {
# 0 if not a trailing slash; regex is one character of any sort followed by
# zero or more of any character until "/" followed by the end of the
# string.
trailing_slash=$(echo "$initial_source" | grep -c '..*/$' )
# Now that we know whether there was a trailing slash on the source, no
# need to confuse things by keeping it on there. Get rid of it.
# The regex gets of every instance of a slash at the end of the line
# provided that it is preceded by 1 character.
## initial_source=$(echo "$initial_source" | sed -e 's%\(.\)/$%\1%')
# Above replaced by shell expansion to avoid forking
initial_source=${initial_source%/}
rzfs_list_ho_s=$($RZFS list -t filesystem,volume -Ho name -s creation) ||
{ echo "Failed to retrieve datasets from the destination"; exit 3; }
lzfs_list_hr_s_snap=$($LZFS list -Hr -o name -s creation -t snapshot $initial_source) ||
{ echo "Failed to retrieve snapshots from the source"; exit 3; }
# Note that for OpenSolaris compatibility, instead of using gtac
# we will use ...| cat -n | sort -nr | cut -c 8-
# gtac line
lzfs_list_hr_S_snap=$(echo "$lzfs_list_hr_s_snap" | cat -n)
lzfs_list_hr_S_snap=$(echo "$lzfs_list_hr_S_snap" | sort -nr | cut -c 8- )
rzfs_list_hr_S_snap=$($RZFS list -Hr -o name -S creation -t snapshot $destination) ||
{ echo "Failed to retrieve snapshots from the destination"; exit 3; }
recursive_source_list=$($LZFS list -t filesystem,volume -Hr -o name "$initial_source") ||
{ echo "Failed to retrieve list of datasets from the source"; exit 3; }
recursive_dest_list=$($RZFS list -t filesystem,volume -Hr -o name "$destination") ||
{ echo "Failed to retrieve list of datasets from the destination"; exit 3; }
# Exit if source not sound
if [ "$recursive_source_list" = "" ]; then
echo "Error: Source does not exist."
usage
exit 1
fi
# Exit if destination not sound
if [ "$recursive_dest_list" = "" ]; then
echo "Error: Destination filesystem does not exist. Create it first."
usage
exit 1
fi
}
#
# Caches zfs list commands to cut execution time, for option -S
#
get_zfs_list_rsync_mode() {
recursive_dest_list=$($RZFS list -t filesystem,volume -Hr -o name $destination)
# Exit if destination not sound
if [ "$recursive_dest_list" = "" ]; then
echo "Error: Destination filesystem does not exist. Create it first."
usage
exit 1
fi
OLD_IFS=$IFS
IFS=","
source_fs_list=""
root_fs=""
# We want to get a list of every ZFS filesystem that holds data that will be
# transferred. Note that trailing slashes don't seem to matter.
option_RN="$option_R,$option_N"
##option_RN=$(echo "$option_RN" | sed -e 's/^,//g' | sed -e 's/,$//g')
# Replace the above with shell expansion
option_RN=${option_RN#,}
option_RN=${option_RN%,}
if [ "$option_L" != "" ];then
if [ $option_L -lt "1" ]; then
echo "Error: Option L, if specified, should be 1 or greater."
usage
exit 1
fi
inc_option_L=$(expr $option_L + 1)
fi
for source_RN in $option_RN; do
source_RN_trailing_slash=$(echo "$source_RN" | grep -c '..*/$')
if [ $source_RN_trailing_slash -eq 1 ]; then
echo "Error: Do not specify trailing slashes in sources."
echo "There is no\
meaning in the context of this program and so this has been disabled."
usage
exit 1
fi
temp_fs_list=$($LZFS list -t filesystem,volume -Hr -o name $source_RN)
temp_fs_list_comma=$(echo "$temp_fs_list" | tr -s "\n" ",")
##temp_fs_list_comma=$(echo "$temp_fs_list_comma" | sed -e 's/,$//g')
# Replace above with shell expansion
temp_fs_list_comma=${temp_fs_list_comma%,}
if [ "$option_L" != "" ];then
for fs in $temp_fs_list_comma; do
# count the "/" in the line, should be equal or greater to option_L
slash_no=$(echo "$fs" | $AWK '$0= NF-1' FS=/)
if [ "$slash_no" -lt "$option_L" ]; then
echo "Error: If using option L, ensure that all source files and\
directories are contained in filesystems with as many \"/\" as L."
usage
exit 1
fi
old_root_fs=$root_fs
root_fs=$(echo "$fs" | $AWK '{for (i=1; i <= '$inc_option_L'; i++) printf("%s%c", $i, (i=='$inc_option_L')?ORS:OFS)}' FS=/ OFS=/ ORS=)
if [ "$root_fs" != "$old_root_fs" -a "$old_root_fs" != "" ]; then
echo "Error: No common root filesystem. If using option L, ensure \
that each source file/directory comes from a common filesystem, and that the
the level specified is not after this common filesystem. e.g. if your pool
has been backed up to storage/backups/root_pool then the level you should
specify is \"2\"."
usage
exit 1
fi
done
fi
# exit if source is bogus
if [ "$temp_fs_list" = "" ]; then
echo "Error: Source in -N or -R option does not exist, or is stored"
echo "on a filesystem that is not ZFS."
usage
exit 1
fi
# used printf in order to print the newlines
source_fs_list=$(printf "$temp_fs_list\n$source_fs_list")
done
# We will use primarily the root_fs_parent, but got root_fs because
# we wanted to check that root_fs is unique.
# This line strips out the last bit, e.g. tank/back/zroot becomes tank/back
# The regex is a slash, followed by zero or more non-slash characters,
# until the end of the line.
root_fs_parent=$(echo "$root_fs" | sed -e 's%/[^/]*$%%g')
# Remove redundant entries and sort properly
source_fs_list=$(echo "$source_fs_list" | sort -u)
source_fs_list_rev=$(echo "$source_fs_list" | sort -r)
# Gets the pools for the fs (e.g. in storage/tmp/foo, this would be "storage")
source_pool_list=$(echo "$source_fs_list" | cut -f1 -d/ | sort -u)
source_pool_number=$(echo "$source_pool_list" | wc -l | sed -e 's/ //g' )
if [ $source_pool_number -ne 1 ]; then
echo "Error: The sources you list are stored on a total of\
"$source_pool_number" pools."
echo "Amend your list of sources until there is only one\
pool relating to them all."
usage
exit 1
fi
# prepares the variables we will end up using later
if [ "$option_L" = "" ]; then
root_fs="$source_pool_list"
root_fs_parent=""
fi
# for recursive option
zfs_list_Ho_name=$($LZFS list -t filesystem,volume -H -o name)
lzfs_list_Ho_mountpoint=$($LZFS list -t filesystem,volume -Ho mountpoint)
rzfs_list_Ho_mountpoint=$($RZFS list -t filesystem,volume -Ho mountpoint)
initial_source=$root_fs
recursive_source_list=$($LZFS list -t filesystem,volume -Hr -o name "$root_fs" \
| grep -v ^$destination)
IFS="$OLD_IFS"
}
#
# Creates a list of exclude options to pass to rsync, so that empty directories
# on source corresponding to filesystem mountpoints don't cause a delete
# on the destination, and also optionally to exclude fs mountpoints on dest.
# Takes $opt_srs_all_inc_fs, $opt_src_fs_modif
# Outputs $exclude_options, exclude options to be added to other rsync options
get_exclude_list() {
exclude_options=""
# First, exclude known source-side filesystem mountpoints
# They will be empty, and if not excluded --del will delete those folders
# which will hold valid data on the destination
exclude_dir_list=$(echo "$opt_srs_all_inc_fs" | grep ^$opt_src_fs_modif | \
grep -v "^$opt_src_fs_modif$")
exclude_dir_list=$(echo "$exclude_dir_list" | sed -e "s%^$opt_src_fs_modif%%g")
# Second, by default we exclude filesystem mountpoints on the
# destination, as they will have their own rsync transfer or be
# left for an independent restore procedure.
if [ $option_i -eq 0 ]; then
dest_exclude_dir_list=$(echo "$rzfs_list_Ho_mountpoint" | grep ^$rs_dest\
| grep -v "^$rs_dest$")
dest_exclude_dir_list=$(echo "$dest_exclude_dir_list" | \
sed -e "s%^$rs_dest%%g")
if [ "$rs_dest" = "/" ]; then
dest_exclude_dir_list=$(echo "$dest_exclude_dir_list" | sed -e 's%^%/%')
fi
# now to remove duplicates
exclude_dir_list="$exclude_dir_list
$dest_exclude_dir_list"
exclude_dir_list=$(echo "$exclude_dir_list" | sort -u | grep -v "^$")
fi
for exd in $exclude_dir_list; do
exclude_options="--exclude=$exd $exclude_options"
done
# Removes space at end
exclude_options=$(echo "$exclude_options" | sed -e "s% $%%g")
}
#
# Transfers a source via rsync
# Takes $source_type, where:
# n = non-recursive
# r = recursive
# Takes $opt_source, which is a source directly from the -N or -R option
rsync_transfer() {
# Note that the source is actually in the snapshot. This gets the
# ZFS filesystem corresponding to the source in the original -R or -N list.
opt_src_fs=$($LZFS list -t filesystem,volume -H -o name $opt_source)
# We need to get all the filesystems at or below the level of the source.
# This is a bit tricky; if opt_source is /tmp/foo/bar, and the filesystem
# that contains it is zroot/tmp/foo (and there is also a zroot/tmp/foo/yip,
# which we don't want, we only should be concerned about zroot/tmp/foo as
# everything will be contained therein.
# If OTOH, we want to transfer /tmp/foo, and this maps to zroot/tmp/foo
# which also has zroot/tmp/foo/yip, then we must transfer everything in
# every filesystem under this across.
# To find out whether the directory is a filesystem, look at the mountpoint
# properties. Note that this approach won't work for legacy mounts, but as
# long as we aren't trying to recursively transfer "/", we should be fine.
# is the source (directory) a filesystem?
is_fs=$(echo $lzfs_list_Ho_mountpoint | tr " " "\n" | grep -c ^$opt_source$)
if [ $source_type = "r" -a $is_fs -eq "1" ]; then
# the directory is a filesystem - need to include all fs under source fs
opt_srs_all_inc_fs=$($LZFS list -t filesystem,volume -H -o name | grep ^$opt_src_fs)
else
opt_srs_all_inc_fs=$opt_src_fs # we will only loop through once
fi
for opt_src_fs in $opt_srs_all_inc_fs; do
if [ $source_type = "r" -a $is_fs -eq "1" ]; then
# We need to get the mountpoints of each sub filesystem
sub_opt_source=$($LZFS get -H -o value mountpoint $opt_src_fs)
else
sub_opt_source=$opt_source
fi
# the mountpoint of the above
opt_src_fs_mountpoint=$($LZFS get -Ho value mountpoint "$opt_src_fs")
if [ "$opt_src_fs_mountpoint" = "legacy" ]; then
if [ $option_l -eq 0 ]; then
echo "Error: legacy mountpoint encountered. Enable -l to assume"
echo "that the legacy mountpoint is \"/\"."
usage; beep
exit 1
fi
opt_src_fs_mountpoint="/"
opt_src_tail=$opt_source
rs_source=\
"$opt_src_fs_mountpoint.zfs/snapshot/$snapshot_name/.$opt_src_tail"
else
# the part of the original source less the mountpoint part
opt_src_tail=$(echo "$sub_opt_source" |\
sed -e "s%^$opt_src_fs_mountpoint%%g")
# This is the source (from the atomic snapshot), nearly suitable for
# rsync usage. What it is will depend on whether it is filesystem
# or directory.
rs_source=\
"$opt_src_fs_mountpoint/.zfs/snapshot/$snapshot_name/.$opt_src_tail"
fi
# We can think of using L option as restoring, and without L option as
# backing up. When we back up we copy the root filesystem and everything
# in it into the destination. (e.g. zroot, zroot/tmp etc. goes into
# storage/backups/zroot, storage/backups/zroot/tmp etc.) In the case of
# restoring, we are going the other way around, but it is as if we are
# coping the original root filesystem directly into the destination (which
# may be a pool) otherwise we would not be able to restore a pool.
opt_src_fs_modif=$opt_src_fs
# This will impact the source and destination that we feed to rsync.
if [ "$option_L" != "" ]; then
# This will trim ($option_L + 1) folders off the beginning of the fs, e.g.
# "tank/foo/bar/zroot/tmp/yum" becomes (with option_L = 3) "tmp/yum"
inc_option_L=$(expr $option_L + 1)
n=1
while [ ${n} -le ${inc_option_L} ]; do
opt_src_fs_modif=$(echo "$opt_src_fs_modif" | sed -e 's%^[^/]*%%' | sed -e 's%^/%%' )
n=$((n+1))
done
fi
#rs_dest="/$destination/$opt_src_fs_modif$opt_src_tail"
rs_dest="/$destination/$opt_src_fs_modif"
# if $destination is "zroot/foo/bar", this regex gets "zroot"
dest_root=$(echo "$destination" | sed -e 's%/.*$%%')
dest_root_mountpoint=$($RZFS get -Ho value mountpoint "$dest_root")
if [ "$dest_root_mountpoint" = "legacy" ]; then
if [ $option_l -eq 0 ]; then
echo "Error: legacy mountpoint encountered. Enable -l to assume"
echo "that the legacy mountpoint is \"/\"."
usage; beep
exit 1
fi
rs_dest=$(echo "$rs_dest" | sed -e "s%^/[^/]*%%g")
fi
full_rs_options="$rsync_options"
get_exclude_list
if [ "$source_type" = "r" ]; then
# Appends a slash and the "-r" option, to suit rsync
rs_source="$rs_source/"
full_rs_options="$full_rs_options $exclude_options -r"
if [ $option_d -eq 1 ]; then