-
Notifications
You must be signed in to change notification settings - Fork 136
/
Copy pathZFS.pm
1801 lines (1518 loc) · 74.6 KB
/
ZFS.pm
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
package ZnapZend::ZFS;
use Mojo::Base -base;
use Mojo::Exception;
use Mojo::IOLoop::Subprocess;
use Data::Dumper;
use inheritLevels;
### attributes ###
has debug => sub { 0 };
has noaction => sub { 0 };
has nodestroy => sub { 1 };
has oracleMode => sub { 0 };
has recvu => sub { 0 };
has resume => sub { 0 };
has compressed => sub { 0 };
has sendRaw => sub { 0 };
has skipIntermediates => sub { 0 };
has forbidDestRollback => sub { 0 };
has lowmemRecurse => sub { 0 };
has zfsGetType => sub { 0 };
has rootExec => sub { q{} };
has sendDelay => sub { 3 };
has connectTimeout => sub { 30 };
has propertyPrefix => sub { q{org.znapzend} };
has sshCmdArray => sub { [qw(ssh),
qw(-o batchMode=yes -o), 'ConnectTimeout=' . shift->connectTimeout] };
has mbufferParam => sub { [qw(-q -s 256k -W 600 -m)] }; #don't remove the -m as the buffer size will be added
has scrubInProgress => sub { qr/scrub in progress/ };
has zLog => sub {
my $stack = "";
for (my $i = 0; my @r = caller($i); $i++) { $stack .= "$r[1]:$r[2] $r[3]\n"; }
Mojo::Exception->throw('ZFS::zLog must be specified at creation time!' . "\n$stack");
};
has priv => sub { my $self = shift; [$self->rootExec ? split(/ /, $self->rootExec) : ()] };
### private functions ###
my $splitHostDataSet = sub {
# When troubleshooting, set to 1:
my $debugHere = 0;
#my $debugHere = 1;
# See also https://github.com/oetiker/znapzend/issues/585
# If there are further bugs in the regex, comment away the
# next implementation line and fall through to verbosely
# debugging code below to try and iterate a fix.
# In the "if" clause below we separate the regular expressions
# for the use-case where we have two "@" characters:
# user@host:dataset@snap
# from having zero or one "@" characters:
# host:dataset
# host:dataset@snap
# user@host:dataset
# and note that dataset may lack "/" chars (root dataset
# of a pool), and (non-root?) dataset and snapshot names
# may have ":" chars of their own, e.g.
# ...@znapzend-auto-2024-01-08T10:22:13Z
# pond/export/vm-1:2
# Also note that we can not discern "X@Y:Z" strings by pattern
# alone - are they a remote "user@host:rootds" or a local
# "rootds@funny:snapname"? For practical purposes, we proclaim
# preference for the former: we are more likely to look at funny
# local snapshot names, than to back up to (or otherwise care
# about) remote pools' ROOT datasets.
my $count = ($_[0] =~ tr/@//);
if ($count > 1) {
#return ($_[0] =~ /^(?:([^:\/]+):)?([^@\s]+|[^@\s]+\@[^@\s]+)$/);
print STDERR "[D] splitHostDataSet: use-case: Two or more \@\n" if $debugHere;
return ($_[0] =~ /^(?:([^:\/]+):)?([^@\s]+\@[^@\s]+)$/);
} else {
# Zero or one "@"
# Either "[host:]dataset[@snap]" or "[user@]host:dataset"
print STDERR "[D] splitHostDataSet: use-case: zero or one \@: " if $debugHere;
if ($_[0] =~ /^[^:@\/]+:/) {
# Got a colon before any "@" (if at all present):
# assume host:... (no "user@")
print STDERR "colon before any frog\n" if $debugHere;
return ($_[0] =~ /^(?:([^:@\/]+):)([^@\s]+|[^@\s]+\@[^@\s]+)$/);
} elsif ($_[0] =~ /^[^:@\/]+\//) {
# Slashes are not anticipated in user or host names, so:
# assume poolroot/...
print STDERR "slashes before colon\n" if $debugHere;
return (undef, $_[0]);
} elsif ($_[0] =~ /^[^:\/@]+@[^:@\/]+$/) {
# X@Y without colons or slashes:
# assume poolroot@snap
print STDERR "no colon, no slash, with frog\n" if $debugHere;
return (undef, $_[0]);
} elsif ($_[0] =~ /^[^:@\/]+@[^:@\/]+:.*\//) {
# X@Y:Z/W - snapshot names can not have slashes
# assume X@Y = user@host, Z/W = rootds/ds...[@snap]
print STDERR "X\@Y:Z/W without slashes in X and Y\n" if $debugHere;
return ($_[0] =~ /^([^:\/]+):(.+)$/);
} elsif ($_[0] =~ /^[^:@\/]+@[^:@\/]+:/) {
# X@Y:Z without slashes in X and Y - may be:
# either user@host:...
# or e.g. rootds@snap-12:34:56
print STDERR "X\@Y:Z without slashes in X and Y\n" if $debugHere;
}
print STDERR "other\n" if $debugHere;
return ($_[0] =~ /^(?:([^:@\/]+):)?([^@\s]+|[^@\s]+\@[^@\s]+)$/);
}
my @return;
###push @return, ($_[0] =~ /^(?:(.+)\s)?([^\s]+)$/);
###push @return, ($_[0] =~ /^(?:([^:\/]+):)?([^:]+|[^:@]+\@.+)$/);
push @return, ($_[0] =~ /^(?:([^:\/]+):)?([^@\s]+|[^@\s]+\@[^@\s]+)$/);
# Note: Claims `Use of uninitialized value $return[0]...` when there
# is no remote host portion matched, so using a map to stringify:
print STDERR "[D] Split '" . $_[0] . "' into: [" . join(", ", map { defined ? "'$_'" : '<undef>' } @return) . "]\n" if $debugHere;
return @return;
};
my $splitDataSetSnapshot = sub {
my $count = ($_[0] =~ tr/@//);
if ($count > 0) {
return ($_[0] =~ /^([^\@]+)\@([^\@]+)$/);
} else {
return ($_[0], undef);
}
};
my $shellQuote = sub {
my @return;
for my $group (@_){
my @args = @$group;
for (@args){
s/'/'"'"'/g;
}
push @return, join ' ', map {/^[-\/@=_0-9a-z]+$/i ? $_ : qq{'$_'}} @args;
}
return join '|', @return;
};
### private methods ###
my $buildRemoteRefArray = sub {
my $self = shift;
my $remote = shift;
if ($remote){
return [@{$self->sshCmdArray}, $remote, $shellQuote->(@_)];
}
return @_;
};
my $buildRemote = sub {
my $self = shift;
my @list = $self->$buildRemoteRefArray(@_);
return @{$list[0]};
};
my $scrubZpool = sub {
my $self = shift;
my $startstop = shift;
my $zpool = shift;
my $remote;
($remote, $zpool) = $splitHostDataSet->($zpool);
my @cmd = (@{$self->priv}, ($startstop ? qw(zpool scrub) : qw(zpool scrub -s)));
my @ssh = $self->$buildRemote($remote, [@cmd, $zpool]);
print STDERR '# ' . ($self->noaction ? "WOULD # " : "" ) . join(' ', @ssh) . "\n" if $self->debug;
system(@ssh) && Mojo::Exception->throw('ERROR: cannot '
. ($startstop ? 'start' : 'stop') . " scrub on $zpool") if !$self->noaction;
return 1;
};
### public methods ###
sub dataSetExists {
# Note: Despite the "dataset" in the name, this routine only asks about
# the "live datasets" (filesystem,volume) and not snapshots which are
# also a type of dataset in ZFS terminology. See snapshotExists() below.
my $self = shift;
my $dataSet = shift;
my $remote;
#just in case if someone asks to check '';
return 0 if !$dataSet;
($remote, $dataSet) = $splitHostDataSet->($dataSet);
my @ssh = $self->$buildRemote($remote, [@{$self->priv}, qw(zfs list -H -o name -t), 'filesystem,volume', $dataSet]);
print STDERR '# ' . join(' ', @ssh) . "\n" if $self->debug;
open my $dataSets, '-|', @ssh
or Mojo::Exception->throw('ERROR: cannot get datasets'
. ($remote ? " on $remote" : ''));
my @dataSets = <$dataSets>;
chomp(@dataSets);
return grep { $dataSet eq $_ } @dataSets;
}
sub snapshotExists {
my $self = shift;
# Note: this is a fully qualified name of dataset@snapshot ZFS object,
# not just the snapname. May also be with remote destination ID.
my $snapshot = shift;
my $quiet = shift; # Maybe we expect it to not be there?
if (!defined($quiet)) { $quiet = 0; }
my $quietStr = ( $quiet ? '2>/dev/null' : '');
my $remote;
#just in case if someone asks to check '';
return 0 if !$snapshot;
($remote, $snapshot) = $splitHostDataSet->($snapshot);
my @ssh = $self->$buildRemote($remote,
[@{$self->priv}, qw(zfs list -H -o name -t snapshot), $snapshot]);
print STDERR '# ' . join(' ', @ssh, $quietStr) . "\n" if $self->debug;
# FIXME : Find a way to really use $quietStr here safely... backticks?
open my $snapshots, '-|', @ssh
or Mojo::Exception->throw('ERROR: cannot get snapshots'
. ($remote ? " on $remote" : ''));
my @snapshots = <$snapshots>;
chomp(@snapshots);
return grep { $snapshot eq $_ } @snapshots;
}
sub listDataSets {
# Note: Despite the "dataset" in the name, this routine only asks about
# the "live datasets" (filesystem,volume) and not snapshots which are
# also a type of dataset in ZFS terminology. See listSnapshots() below.
my $self = shift;
my $remote = shift;
my $rootDataSets = shift; # May be not passed, or may be a string, or an array of strings
my $recurse = shift; # May be not passed => undef
my @ssh = $self->$buildRemote($remote, [@{$self->priv}, qw(zfs list -H -o name -t), 'filesystem,volume']);
# By default this lists all fs/vol datasets in the system
# Optionally we can ask for specific rootDataSets possibly with children
if (defined ($rootDataSets) && $rootDataSets) {
my @useRDS;
if ( (ref($rootDataSets) eq 'ARRAY') ) {
if (scalar(@$rootDataSets) > 0) {
push (@useRDS, @$rootDataSets);
}
} else {
# Assume string
if ($rootDataSets ne "") {
push (@useRDS, ($rootDataSets));
}
}
if (scalar(@useRDS) > 0) {
if (defined ($recurse) && $recurse) {
push (@ssh, qw(-r));
}
push(@ssh, @useRDS);
}
}
print STDERR '# ' . join(' ', @ssh) . "\n" if $self->debug;
open my $dataSets, '-|', @ssh
or Mojo::Exception->throw('ERROR: cannot get datasets'
. ($remote ? " on $remote" : ''));
my @dataSets = <$dataSets>;
chomp(@dataSets);
return \@dataSets;
}
sub listSnapshots {
my $self = shift;
my $dataSet = shift;
my $snapshotFilter = shift // qr/.*/;
my $lastSnapshotToSee = shift // undef; # Stop creation-ordered listing after registering this snapshot name - if there is one in the filtered selection
if (defined($lastSnapshotToSee)) {
if ($lastSnapshotToSee eq "") { $lastSnapshotToSee = undef; }
else { $lastSnapshotToSee =~ s/^.*\@// ; }
}
my $remote;
my @snapshots;
($remote, $dataSet) = $splitHostDataSet->($dataSet);
my @ssh = $self->$buildRemote($remote,
[@{$self->priv}, qw(zfs list -H -o name -t snapshot -s creation -d 1), $dataSet]);
print STDERR '# ' . join(' ', @ssh) . "\n" if $self->debug;
open my $snapshots, '-|', @ssh
or Mojo::Exception->throw("ERROR: cannot get snapshots on $dataSet");
while (my $snap = <$snapshots>){
chomp $snap;
if (defined($lastSnapshotToSee)) {
if ($snap =~ /^\Q$dataSet\E\@$lastSnapshotToSee$/) {
# Only add this name to list if it matches $snapshotFilter ...
push @snapshots, $snap if $snap =~ /^\Q$dataSet\E\@$snapshotFilter$/;
# ...but still stop iterating
$self->zLog->debug("listSnapshots() : for dataSet='$dataSet' snapshotFilter='$snapshotFilter' lastSnapshotToSee='$lastSnapshotToSee' matched '$snap' and stopping the iteration");
last;
}
}
next if $snap !~ /^\Q$dataSet\E\@$snapshotFilter$/;
push @snapshots, $snap;
}
@snapshots = map { ($remote ? "$remote:" : '') . $_ } @snapshots;
return \@snapshots;
}
sub extractSnapshotNames {
# Routines like listSnapshots() operate with fully qualified
# "dataset@snapname" strings as returned by ZFS. For some data
# matching we need to compare just the "snapname" lists.
my $self = shift;
my $array = shift; # Note: call with extractSnapshotNames(\@arrVarName) !
my @ret;
if (ref($array) eq 'ARRAY') {
if (scalar(@$array)) {
for (@$array) {
/\@(.+)$/ and push @ret, $1;
}
}
} else {
# return \@ret if (!$array);
# eval { return \@ret if ($array == 1); };
# String or unprocessed whitespace separated series?
#print STDERR "=== extractSnapshotNames:\n\tGOT '" . ref($array) . "', will recurse: " . Dumper($array) if $self->debug;
if ($array =~ m/\s+/) {
my @tmp = split(/\s+/, $array);
#print STDERR "=== extractSnapshotNames:\n\tTMP: " . Dumper(\@tmp) if $self->debug;
return $self->extractSnapshotNames(\@tmp);
}
return $self->extractSnapshotNames( [$array] );
}
#print STDERR "=== extractSnapshotNames:\n\tGOT '" . ref($array) . "': " . Dumper($array) . "\tMADE: " . Dumper(\@ret) if $self->debug;
return \@ret;
}
### Works:
# $self->zZfs->extractSnapshotNames( [ 'dsa@test1', 'dsa@test2', 'dsa@test3' ] );
# $self->zZfs->extractSnapshotNames('ds@test1 ds@test2
# ds@test3');
### Does not work;
# $self->zZfs->extractSnapshotNames( qw(dsq@test1 dsq@test2 dsq@test3) );
sub createDataSet {
my $self = shift;
my $dataSet = shift;
my $remote;
#just in case if someone asks to check '';
return 0 if !$dataSet;
($remote, $dataSet) = $splitHostDataSet->($dataSet);
my @ssh = $self->$buildRemote($remote,
[@{$self->priv}, qw(zfs create -p), $dataSet]);
print STDERR '# ' . ($self->noaction ? "WOULD # " : "" ) . join(' ', @ssh) . "\n" if $self->debug;
#return if 'noaction' or dataset creation successful
return 1 if $self->noaction || !system(@ssh);
#check if dataset already exists and therefore creation failed
return 0 if $self->dataSetExists($dataSet);
#creation failed and dataset does not exist, throw an exception
Mojo::Exception->throw("ERROR: cannot create dataSet $dataSet");
}
sub listSubDataSets {
my $self = shift;
my $hostAndDataSet = shift;
my @dataSets;
my ($remote, $dataSet) = $splitHostDataSet->($hostAndDataSet);
my @ssh = $self->$buildRemote($remote, [@{$self->priv}, qw(zfs list -H -r -o name -t), 'filesystem,volume', $dataSet]);
print STDERR '# ' . join(' ', @ssh) . "\n" if $self->debug;
open my $dataSets, '-|', @ssh
or Mojo::Exception->throw("ERROR: cannot get sub datasets on $dataSet");
while (my $task = <$dataSets>){
chomp $task;
next if $task !~ /^\Q$dataSet\E/;
push @dataSets, $task;
}
my @subDataSets = map { ($remote ? "$remote:" : '') . $_ } @dataSets;
return \@subDataSets;
}
sub createSnapshot {
my $self = shift;
my $hostAndDataSet = shift;
my @recursive = $_[0] ? ('-r') : ();
my ($remote, $dataSet) = $splitHostDataSet->($hostAndDataSet);
my @ssh = $self->$buildRemote($remote, [@{$self->priv}, qw(zfs snapshot), @recursive, $dataSet]);
print STDERR '# ' . ($self->noaction ? "WOULD # " : "" ) . join(' ', @ssh) . "\n" if $self->debug;
#return if 'noaction' or snapshot creation successful
return 1 if $self->noaction || !system(@ssh);
#check if snapshot already exists and therefore creation failed
return 0 if $self->snapshotExists($dataSet);
#creation failed and snapshot does not exist, throw an exception
Mojo::Exception->throw("ERROR: cannot create snapshot $dataSet");
}
sub destroySnapshots {
# known limitation: snapshots from subdatasets have to be
# destroyed individually on some ZFS implementations
my $self = shift;
my @toDestroy = ref($_[0]) eq "ARRAY" ? @{$_[0]} : ($_[0]);
my %toDestroy;
my ($remote, $dataSet, $snapshot);
my @recursive = $_[1] ? ('-r') : ();
#oracleMode: destroy each snapshot individually
if ($self->oracleMode){
my $destroyError = '';
for my $task (@toDestroy){
my ($remote, $dataSetPathAndSnap) = $splitHostDataSet->($task);
my ($dataSet, $snapshot) = $splitDataSetSnapshot->($dataSetPathAndSnap);
if (defined ($dataSet)) {
my @ssh = $self->$buildRemote($remote, [@{$self->priv}, qw(zfs destroy), @recursive, "$dataSet\@$snapshot"]);
print STDERR '# ' . (($self->noaction || $self->nodestroy) ? "WOULD # " : "") . join(' ', @ssh) . "\n" if $self->debug;
system(@ssh) and $destroyError .= "ERROR: cannot destroy snapshot $dataSet\@$snapshot\n"
if !($self->noaction || $self->nodestroy);
} else {
print STDERR "[D] task='$task' => remote='$remote' dataSetPathAndSnap='$dataSetPathAndSnap' => dataSet='$dataSet' snapshot='$snapshot'\n";
Mojo::Exception->throw("ERROR: oracleMode destroy: failed to parse task='$task', got undefined dataSet and/or snapshot");
}
}
#remove trailing \n
chomp $destroyError;
Mojo::Exception->throw($destroyError) if $destroyError ne '';
return 1;
}
#combinedDestroy
#collect "dataset1@snap1,snap2 dataset2@snap1,snap2,snap3..."
#to destroy one dataset at a time (maybe many snaps per each)
for my $task (@toDestroy){
my ($remote, $dataSetPathAndSnap) = $splitHostDataSet->($task);
my ($dataSet, $snapshot) = $splitDataSetSnapshot->($dataSetPathAndSnap);
if (defined ($dataSet)) {
#tag local snapshots as 'local' so we have a key to build the hash
$remote = $remote || 'local';
exists $toDestroy{$remote} or $toDestroy{$remote} = {};
exists $toDestroy{$remote}{$dataSet} or $toDestroy{$remote}{$dataSet} = [];
push @{$toDestroy{$remote}{$dataSet}}, scalar @{$toDestroy{$remote}{$dataSet}} ? $snapshot : "$dataSet\@$snapshot" ;
} else {
print STDERR "[D] task='$task' => remote='$remote' dataSetPathAndSnap='$dataSetPathAndSnap' => dataSet='$dataSet' snapshot='$snapshot'\n";
Mojo::Exception->throw("ERROR: combinedDestroy: failed to parse task='$task', got undefined dataSet and/or snapshot");
}
}
for $remote (keys %toDestroy){
for $dataSet (keys %{$toDestroy{$remote}}){
#check if remote is flagged as 'local'.
my @ssh = $self->$buildRemote($remote ne 'local'
? $remote : undef, [@{$self->priv}, qw(zfs destroy), @recursive, join(',', @{$toDestroy{$remote}{$dataSet}})]);
print STDERR '# ' . (($self->noaction || $self->nodestroy) ? "WOULD # " : "") . join(' ', @ssh) . "\n" if $self->debug;
system(@ssh) && Mojo::Exception->throw("ERROR: cannot destroy snapshot(s) $toDestroy[0]")
if !($self->noaction || $self->nodestroy);
}
}
return 1;
}
sub lastAndCommonSnapshots {
my $self = shift;
my $srcDataSet = shift;
my $dstDataSet = shift;
my $snapshotFilter = shift // qr/.*/;
my $lastSnapshotToSee = shift // undef; # Stop creation-ordered listing after registering this snapshot name - if there is one in the filtered selection
if (defined($lastSnapshotToSee)) {
if ($lastSnapshotToSee eq "") { $lastSnapshotToSee = undef; }
else { $lastSnapshotToSee =~ s/^.*\@// ; }
}
my $srcSnapshots = $self->listSnapshots($srcDataSet, $snapshotFilter, $lastSnapshotToSee);
my $dstSnapshots = $self->listSnapshots($dstDataSet, $snapshotFilter, $lastSnapshotToSee);
return (undef, undef, undef) if !scalar @$srcSnapshots;
# For default operations, snapshot name is the time-based pattern
my ($i, $snapName);
for ($i = $#{$srcSnapshots}; $i >= 0; $i--){
($snapName) = ${$srcSnapshots}[$i] =~ /^\Q$srcDataSet\E\@($snapshotFilter)/;
last if grep { /\@$snapName$/ } @$dstSnapshots;
}
### print STDERR "LASTCOMMON: i=$i snapName=$snapName\nSRC: " . Dumper($srcSnapshots) . "DST: ". Dumper($dstSnapshots) . "LastToSee: " . Dumper($lastSnapshotToSee) if $self->debug;
# returns: ($lastSrcSnapshotName, $lastCommonSnapshotName, $dstSnapCount)
return (
${$srcSnapshots}[-1],
( ($i >= 0 && grep { /\@$snapName$/ } @$dstSnapshots) ? ${$srcSnapshots}[$i] : undef),
scalar @$dstSnapshots
);
}
sub mostRecentCommonSnapshot {
# This is similar to lastAndCommonSnapshots() above, but considers not only
# the "live" information from a currently accessible destination, but as a
# fallback also the saved last-known-synced snapshot name.
my $self = shift;
my $srcDataSet = shift;
my $dstDataSet = shift;
my $dstName = shift; # name of the znapzend policy => property prefix
my $snapshotFilter = shift;
if (!defined($snapshotFilter) || !$snapshotFilter) {
$snapshotFilter = qr/.*/;
}
# We can recurse from sendRecvCleanup() when looking for protected children
# while preparing for a recursive cleanup of root backed-up source dataset.
# NOTE that it is then up to zfs command to either return only data for the
# snapshot named in the argument, or also same-named snapshots in children
# of the dataset this is a snapshot of, so this flag may be effectively
# ignored by OS.
my $recurse = shift; # May be not passed => undef
if (!defined($recurse)) {
$recurse = 0;
}
# We do not have callers for the "inherit" argument at this time.
# However we can have users replicating partial trees inheriting a policy.
# Current call stack for sendRecvCleanup (primary user of this routine)
# does not provide info whether this mode is used, so to be safer about
# deletion of "protected" last-known-synced snapshots, we consider both
# local and inherited values of the dst_X_synced flag, if present.
# See definition of recognized $inherit values for this context in
# getSnapshotProperties() code and struct inheritLevels.
my $inherit = shift; # May be not passed => undef
if (!defined($inherit)) {
# We leave defined but invalid values of $inherit to
# getSnapshotProperties() to figure out and complain,
# but for this routine's purposes set a specific default.
$inherit = new inheritLevels;
$inherit->zfs_local(1);
$inherit->zfs_inherit(1);
$inherit->snapshot_recurse_parent(1);
}
my ($lastSnapshot, $lastCommonSnapshot, $dstSnapCount);
### DEBUG: Uncomment next line to enforce going through getSnapshotProperties() below
#if(0)
{
local $@;
eval {
local $SIG{__DIE__};
($lastSnapshot, $lastCommonSnapshot, $dstSnapCount) = ($self->lastAndCommonSnapshots($srcDataSet, $dstDataSet, $snapshotFilter))[1];
};
if ($@){
if (blessed $@ && $@->isa('Mojo::Exception')){
$self->zLog->warn($@->message);
}
else{
$self->zLog->warn($@);
}
}
}
if (not $lastCommonSnapshot){
my $dstSyncedPropname = $dstName . '_synced';
my @dstSyncedProps = [$dstSyncedPropname, $dstName];
my $srcSnapshots = $self->listSnapshots($srcDataSet, $snapshotFilter);
my $i;
# Go from newest snapshot down in history and find the first one
# to have a "non-false" value (e.g. "1") in its $dstName . '_synced'
for ($i = $#{$srcSnapshots}; $i >= 0; $i--){
my $snapshot = ${$srcSnapshots}[$i];
my $properties = $self->getSnapshotProperties($snapshot, $recurse, $inherit, @dstSyncedProps);
if ($properties->{$dstName} and ($properties->{$dstName} eq $dstDataSet) and $properties->{$dstSyncedPropname}){
$lastCommonSnapshot = $snapshot;
last;
}
}
}
return $lastCommonSnapshot;
}
sub sendRecvSnapshots {
my $self = shift;
my $srcDataSet = shift;
my $dstDataSet = shift;
my $dstName = shift; # name of the znapzend policy => property prefix
my $mbuffer = shift;
my $mbufferSize = shift;
my $snapFilter = shift // qr/.*/;
# Limit creation-ordered listing after registering this snapshot name,
# (there may exist newer snapshots that would be not seen and replicated).
# For practical purposes, this can be used with --since=X mode to ensure
# that "X" exists on destination if it does not yet (note that if there
# are newer snapshots on destination, they would be removed to allow
# receiving "X", unless --forbidDestRollback is requested, in this case).
my $lastSnapshotToSee = shift // undef; # Stop creation-ordered listing after registering this snapshot name - if there is one in the filtered selection
if (defined($lastSnapshotToSee)) {
if ($lastSnapshotToSee eq "") { $lastSnapshotToSee = undef; }
else { $lastSnapshotToSee =~ s/^.*\@// ; }
}
# In certain cases, callers can set this argument to explicitly
# forbid (0), allow (1) or enforce if needed (2) a rollback of dest.
my $allowDestRollback = shift // undef;
if (!defined($allowDestRollback)) { $allowDestRollback = (!$self->sendRaw && !$self->forbidDestRollback) ; }
my @recvOpt = $self->recvu ? qw(-u) : ();
push @recvOpt, '-F' if $allowDestRollback;
my $incrOpt = $self->skipIntermediates ? '-i' : '-I';
my @sendOpt = $self->compressed ? qw(-Lce) : ();
push @sendOpt, '-w' if $self->sendRaw;
push @recvOpt, '-s' if $self->resume;
my $remote;
my $mbufferPort;
my $dstDataSetPath;
($remote, $dstDataSetPath) = $splitHostDataSet->($dstDataSet);
# As seen through filter:
# * Last existing snapshot on source,
# * Last common snapshot between source and this destination,
# * Overall count of snapshots on destination.
my ($lastSnapshot, $lastCommon, $dstSnapCount)
= $self->lastAndCommonSnapshots($srcDataSet, $dstDataSet, $snapFilter, $lastSnapshotToSee);
if (defined($lastSnapshotToSee)) {
$self->zLog->debug("sendRecvSnapshots() : " .
"for srcDataSet='$srcDataSet' srcDataSet='$srcDataSet' " .
"snapFilter='$snapFilter' lastSnapshotToSee='$lastSnapshotToSee' ".
"GOT: lastSnapshot='$lastSnapshot' " .
"lastCommon=" . ($lastCommon ? "'$lastCommon'" : "undef") . " " .
"dstSnapCount='$dstSnapCount'"
);
}
# We would set these source snapshot properties to mark that
# this snapshot has been delivered to destination, to keep the
# newest such snapshot if destination is unreachable currently.
my %snapshotSynced = (
$dstName, $dstDataSet,
$dstName . '_synced', 1
);
#nothing to do if no snapshot exists on source or if last common snapshot is last snapshot on source
return 1 if !$lastSnapshot;
if (defined $lastCommon && ($lastSnapshot eq $lastCommon)){
$self->setSnapshotProperties($lastCommon, \%snapshotSynced);
return 1;
}
#check if snapshots exist on destination if there is no common snapshot
#as this will cause zfs send/recv to fail
if (!$lastCommon and $dstSnapCount) {
if ($allowDestRollback == 2) {
# Asked to enforce if needed... is needed now
$self->zLog->warn('WARNING: snapshot(s) exist on destination, but '
. 'no common found on source and destination: was requested '
. 'to clean up destination ' . $dstDataSet . ' (i.e. destroy '
. 'existing snapshots that match the znapzend filter)');
# TOTHINK: Maybe a "zfs rollback" to the oldest dst snapshot
# and then removing it in one act is better for performance?
# Can be destructive for man-named snapshots (if any) though...
$self->destroySnapshots ($self->listSnapshots($dstDataSet, $snapFilter, undef));
# If there are any manually created snapshots, with names not
# matched by filter, `zfs recv -F` below would likely fail.
# Still it is up to admins/users then to clean what they made,
# we only mutilate automatically what we made automatically.
# Reevaluate what is there now and look at all snapshots,
# e.g. the manually named snapshots may be common to src
# and dst, to have a starting point for such resync
($lastSnapshot, $lastCommon, $dstSnapCount)
= $self->lastAndCommonSnapshots($srcDataSet, $dstDataSet, qr/.*/, $lastSnapshotToSee);
my $dstSnapCountAll = scalar($self->listSnapshots($dstDataSet, qr/.*/, undef));
# We do not throw/error here because snapshots may help sync
$self->zLog->warn('ERROR: some snapshot(s) not covered '
. 'by znapzend filter still exist on destination: '
. 'this should be judged and fixed by the sysadmin '
. '(i.e. destroy manually named snapshots); '
. 'the zfs send+receive would likely fail below!'
) if (!$lastCommon && $dstSnapCountAll>0);
} else {
Mojo::Exception->throw('ERROR: snapshot(s) exist on destination, but '
. 'no common found on source and destination: clean up destination '
. $dstDataSet . ' (i.e. destroy existing snapshots)');
}
}
($mbuffer, $mbufferPort) = split /:/, $mbuffer, 2;
my @cmd;
if ($lastCommon){
@cmd = ([@{$self->priv}, 'zfs', 'send', @sendOpt, $incrOpt, $lastCommon, $lastSnapshot]);
}
else{
@cmd = ([@{$self->priv}, 'zfs', 'send', @sendOpt, $lastSnapshot]);
}
#if mbuffer port is set, run in 'network mode'
if ($remote && $mbufferPort && $mbuffer ne 'off'){
my $recvPid;
my @recvCmd = $self->$buildRemoteRefArray($remote, [$mbuffer, @{$self->mbufferParam},
$mbufferSize, '-4', '-I', $mbufferPort], [@{$self->priv}, 'zfs', 'recv', @recvOpt, $dstDataSetPath]);
my $cmd = $shellQuote->(@recvCmd);
my $subprocess = Mojo::IOLoop::Subprocess->new;
$subprocess->run(
#receive worker fork
sub {
print STDERR "# " . ($self->noaction ? "WOULD # " : "" ) . "$cmd\n" if $self->debug;
system($cmd)
&& Mojo::Exception->throw('ERROR: executing receive process') if !$self->noaction;
},
#callback
sub {
my ($subprocess, $err) = @_;
$self->zLog->debug("receive process on $remote done ($recvPid)");
Mojo::Exception->throw($err) if $err;
}
);
#spawn event
$subprocess->on(
spawn => sub {
my ($subprocess) = @_;
my $pid = $subprocess->pid;
$recvPid = $pid;
$remote =~ s/^[^@]+\@//; #remove username if given
$self->zLog->debug("receive process on $remote spawned ($pid)");
push @cmd, [$mbuffer, @{$self->mbufferParam}, $mbufferSize,
'-O', "$remote:$mbufferPort"];
$cmd = $shellQuote->(@cmd);
print STDERR "# " . ($self->noaction ? "WOULD # " : "" ) . "$cmd\n" if $self->debug;
return if $self->noaction;
my $retryCounter = int($self->connectTimeout / $self->sendDelay) + 1;
while ($retryCounter--){
#wait so remote mbuffer has enough time to start listening
sleep $self->sendDelay;
system($cmd) || last;
}
$retryCounter <= 0 && Mojo::Exception->throw("ERROR: cannot send snapshots to $dstDataSet"
. ($remote ? " on $remote" : ''));
}
);
#error event
$subprocess->on(
error => sub {
my ($subprocess, $err) = @_;
die $err;
}
);
#start subprocess event loop
$subprocess->ioloop->start if !$subprocess->ioloop->is_running;
}
else {
my @mbCmd = $mbuffer ne 'off' ? ([$mbuffer, @{$self->mbufferParam}, $mbufferSize]) : () ;
my $recvCmd = [@{$self->priv}, 'zfs', 'recv' , @recvOpt, $dstDataSetPath];
push @cmd, $self->$buildRemoteRefArray($remote, @mbCmd, $recvCmd);
my $cmd = $shellQuote->(@cmd);
print STDERR "# " . ($self->noaction ? "WOULD # " : "" ) . "$cmd\n" if $self->debug;
system($cmd) && Mojo::Exception->throw("ERROR: cannot send snapshots to $dstDataSetPath"
. ($remote ? " on $remote" : '')) if !$self->noaction;
}
$self->setSnapshotProperties($lastSnapshot, \%snapshotSynced);
return 1;
}
sub filterPropertyNames {
# This routine is a helper for getXproperties to allow easy passing of
# specific properties we are interested to `zfs get`, to optimize some
# code around that. As an input it can get either:
# * string that would be passed through as is (after some sanitization);
# * array of strings that would be concatenated into a comma-separated
# string with our name-space propertyPrefix (e.g. "org.znapzend:...")
# prepended if needed;
# * undef for defaulting to 'all'
# Returns a string safe to pass into `zfs get`
my $self = shift;
my $propnames = shift;
my $propertyPrefix = $self->propertyPrefix;
if ($propnames) {
if (ref($propnames) eq 'ARRAY') {
if (scalar(@$propnames) > 0) {
my $propstring = '';
for my $propname (@$propnames) {
next if !defined($propname);
chomp $propname;
if ($propname eq '') {
$self->zLog->warn("=== filterPropertyNames(): got an empty propname in array");
next;
}
if ($propname eq 'all') {
# TOTHINK: Note that this short-circuiting "as is"
# forbids a scenario where we would fetch all zfs
# properties to cache them, and then iterate looking
# that all specific names have been discovered.
# If such needs arise, redefine this here and in
# callers checking for 'all' to also handle split(',').
$self->zLog->warn("=== filterPropertyNames(): got an 'all' propname in array, any filtering will be moot");
return 'all';
}
if ( $propname =~ /^$propertyPrefix\:/ ) {
1; # no-op, all good, use as is
} elsif ( $propname =~ /:/ ) {
$self->zLog->warn("=== filterPropertyNames(): got a propname not from our namespace: $propname");
} else {
$propname = $propertyPrefix . ':' . $propname;
}
if ($propstring eq '') {
$propstring = $propname;
} else {
$propstring .= ',' . $propname;
}
}
$propnames = $propstring;
$propnames =~ s/[\s]+//g;
} else {
# Got an array, but it was empty
$propnames = undef; # default below
}
} else {
# Assume string, pass verbatim; strip whitespaces for safety
$propnames =~ s/[\s]+//g ;
}
}
if ( !(defined($propnames)) || !($propnames) || ($propnames eq '') ) {
$propnames = 'all';
}
return $propnames;
}
sub getDataSetProperties {
# This routine finds properties of datasets (filesystem, volume) that
# are name-spaced with our propertyPrefix (e.g. "org.znapzend:...")
my $self = shift;
my $dataSet = shift;
my $recurse = shift; # May be not passed => undef
my $inherit = shift; # May be not passed => undef
my @propertyList;
my $propertyPrefix = $self->propertyPrefix;
my @list;
$self->zLog->debug("=== getDataSetProperties():\n"
. "\trecurse=" . Dumper($recurse)
. "\tinherit=" . Dumper($inherit)
. "\tDS=" . Dumper($dataSet)
. "\tlowmemRecurse=" . $self->lowmemRecurse
) if $self->debug;
if (!defined($recurse)) {
$recurse = 0;
}
if (!defined($inherit)) {
$inherit = 0;
}
# Note: Before the recursive and multiple dataset support we either
# used the provided dataSet name "as is" trusting it exists (failed
# later if not), or called listDataSets() to list everything on the
# system from `zfs` (also ensuring stuff exists). So we still do.
# Before the recursive the @list must have had individual dataset
# names, passed directly, or subsequently recursively listed above,
# to assign into the discovered list elements. So no recursion was
# needed in the logic below. Now we recurse by default to call `zfs`
# as rarely as we can and so complete faster. However, on systems
# with too many datasets this can exhaust the memory available to
# the process, and/or time out. To defend against this, we optionally
# can fall back to a big list of individual dataset names found by
# recursive listDataSets() invocations instead.
#
# If both recurse and inherit are specified, behavior depends on
# the dataset(s) whose name is passed. If the dataset has a local
# or inherited-from-local backup plan, the recursion stops here.
# If it has no plan (e.g. pool root dataset), we should recurse and
# report all children with a "local" backup plan (ignore inherit).
# Note that listDataSets(), optionally used below for either full
# or selective listing of datasets seen by the system, does not
# have a say in this dilemma ("zfs list" does not care about the
# "source" of a property, only "zfs get" used in this routine does).
#
if (defined($dataSet) && $dataSet) {
if (ref($dataSet) eq 'ARRAY') {
$self->zLog->debug("=== getDataSetProperties(): Is array...") if $self->debug;
if ($self->lowmemRecurse && $recurse) {
my $listds = $self->listDataSets(undef, $dataSet, $recurse);
if (scalar(@{$listds}) == 0) {
$self->zLog->debug("=== getDataSetProperties(): Failed to get data from listDataSets()") if $self->debug;
return \@propertyList;
}
push (@list, @{$listds});
$recurse = 0;
$inherit = 0;
} else {
if ( (scalar(@$dataSet) > 0) && (defined(@$dataSet[0])) ) {
push (@list, @$dataSet);
} else {
$self->zLog->debug("=== getDataSetProperties(): skip array context: value(s) inside undef...") if $self->debug;
}
}
} else {
# Assume a string, per usual invocation
$self->zLog->debug("=== getDataSetProperties(): Is string...") if $self->debug;
if ($self->lowmemRecurse && $recurse) {
my $listds = $self->listDataSets(undef, $dataSet, $recurse);
if (scalar(@{$listds}) == 0) {
$self->zLog->debug("=== getDataSetProperties(): Failed to get data from listDataSets()") if $self->debug;
return \@propertyList;
}
push (@list, @{$listds});
$recurse = 0;
$inherit = 0;
} else {
if ($dataSet ne '') {
push (@list, ($dataSet));
} else {
$self->zLog->debug("=== getDataSetProperties(): skip string context: value inside is empty...") if $self->debug;
}
}
}
} else {
$self->zLog->debug("=== getDataSetProperties(): no dataSet argument passed") if $self->debug;
}
if (scalar(@list) == 0) {
$self->zLog->debug("=== getDataSetProperties(): List all local datasets on the system...") if $self->debug;
my $listds = $self->listDataSets();
if (scalar(@{$listds}) == 0) {
$self->zLog->debug("=== getDataSetProperties(): Failed to get data from listDataSets()") if $self->debug;
return \@propertyList;
}
push (@list, @{$listds});
$recurse = 0;
$inherit = 0;
}
# Iterate every dataset pathname found above, e.g.:
# * (no args/empty/undef arg) all filesystem/volume datasets on all locally
# imported pools, and now recurse==0 and inherit==0 is enforced
# * (with args and with recursion originally, but lowmemRecurse enabled)
# one or more filesystem/volume named datasets and their children found
# via zfs list, and now recurse==0 and inherit==0 is enforced
# * (finally) one or more named datasets from args, with recursion and
# inheritance settings to be processed below
# Depending on inherit (and each dataset referenced in $listElem), pick
# either datasets that have a backup plan in their arguments with a
# "local" source, or those that have one inherited from a local (stop
# at a topmost such then).
# TODO/FIXME: There may be no support for new backup plan definitions
# inside a tree that has one above, and/or good grounds for conflicts.
my %cachedInheritance; # Cache datasets that we know to define znapzend attrs (if inherit mode is used)
for my $listElem (@list){
$self->zLog->debug("=== getDataSetProperties(): Looking under '$listElem' with "
. "zfsGetType='" . $self->zfsGetType . "', "
. "'$recurse' recursion mode and '$inherit' inheritance mode")
if $self->debug;
my %properties;
# TODO : support "inherit-from-local" mode
my @cmd = (@{$self->priv}, qw(zfs get -H));