-
Notifications
You must be signed in to change notification settings - Fork 136
/
ZFS.pm
1571 lines (1295 loc) · 62 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::ForkCall;
use Data::Dumper;
### Property inheritance levels - how deep we go in routines
### that (need to) care about these nuances beyond a boolean.
### Primarily intended for getSnapshotProperties() to get props
### defined by snapshots of parent datasets with same snapnames.
### For "usual" datasets (filesystem,volume) `zfs` returns the
### properties inherited from higher level datasets; but for
### snapshots it only returns the same - not from higher snaps.
my %inheritLevels = (
local_only => 0,
local_zfsinherit => 1,
local_recurseparent => 2,
local_recurseparent_zfsinherit => 3,
);
### attributes ###
has debug => sub { 0 };
has noaction => sub { 0 };
has nodestroy => sub { 1 };
has oracleMode => sub { 0 };
has recvu => sub { 0 };
has compressed => sub { 0 };
has sendRaw => sub { 0 };
has skipIntermediates => 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 {
return ($_[0] =~ /^(?:([^:\/]+):)?([^:]+|[^:@]+\@.+)$/);
};
my $splitDataSetSnapshot = sub {
return ($_[0] =~ /^([^\@]+)\@([^\@]+)$/);
};
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;
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 = $_[0] || qr/.*/;
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;
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);
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);
}
#remove trailing \n
chomp $destroyError;
Mojo::Exception->throw($destroyError) if $destroyError ne '';
return 1;
}
#combinedDestroy
for my $task (@toDestroy){
my ($remote, $dataSetPathAndSnap) = $splitHostDataSet->($task);
my ($dataSet, $snapshot) = $splitDataSetSnapshot->($dataSetPathAndSnap);
#tag local snapshots as 'local' so we have a key to build the hash
$remote = $remote || 'local';
exists $toDestroy{$remote} or $toDestroy{$remote} = [];
push @{$toDestroy{$remote}}, scalar @{$toDestroy{$remote}} ? $snapshot : "$dataSet\@$snapshot" ;
}
for $remote (keys %toDestroy){
#check if remote is flaged as 'local'.
my @ssh = $self->$buildRemote($remote ne 'local'
? $remote : undef, [@{$self->priv}, qw(zfs destroy), @recursive, join(',', @{$toDestroy{$remote}})]);
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 = $_[0] || qr/.*/;
my $srcSnapshots = $self->listSnapshots($srcDataSet, $snapshotFilter);
my $dstSnapshots = $self->listSnapshots($dstDataSet, $snapshotFilter);
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.
# See %inheritLevels for reusable definitions.
# TODO: Remake from use of magic numbers to direct use of instances of that structure
my $inherit = shift; # May be not passed => undef
if (!defined($inherit)) {
$inherit = $inheritLevels{local_recurseparent_zfsinherit};
# 3 = local + zfs inherited + recurse into same-named snapshot of parent(s)
}
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 = $_[0] || qr/.*/;
my @recvOpt = $self->recvu ? qw(-u) : ();
push @recvOpt, '-F' if !$self->sendRaw;
my $incrOpt = $self->skipIntermediates ? '-i' : '-I';
my @sendOpt = $self->compressed ? qw(-Lce) : ();
push @sendOpt, '-w' if $self->sendRaw;
my $remote;
my $mbufferPort;
my $dstDataSetPath;
($remote, $dstDataSetPath) = $splitHostDataSet->($dstDataSet);
my ($lastSnapshot, $lastCommon,$dstSnapCount)
= $self->lastAndCommonSnapshots($srcDataSet, $dstDataSet, $snapFilter);
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
!$lastCommon and $dstSnapCount
and 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 $fc = Mojo::IOLoop::ForkCall->new;
$fc->run(
#receive worker fork
sub {
my $cmd = shift;
my $debug = shift;
my $noaction = shift;
print STDERR "# " . ($self->noaction ? "WOULD # " : "" ) . "$cmd\n" if $debug;
system($cmd)
&& Mojo::Exception->throw('ERROR: executing receive process') if !$noaction;
},
#arguments
[$cmd, $self->debug, $self->noaction],
#callback
sub {
my ($fc, $err) = @_;
$self->zLog->debug("receive process on $remote done ($recvPid)");
Mojo::Exception->throw($err) if $err;
}
);
#spawn event
$fc->on(
spawn => sub {
my ($fc, $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
$fc->on(
error => sub {
my ($fc, $err) = @_;
die $err;
}
);
#start forkcall event loop
$fc->ioloop->start if !$fc->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));
if ($inherit) {
push (@cmd, qw(-s), 'local,inherited');
} else {
push (@cmd, qw(-s local));
}
if ($self->zfsGetType) {
push (@cmd, qw(-t), 'filesystem,volume');
}
if ($recurse) {
push (@cmd, qw(-r));
}
push (@cmd, qw(-o), 'name,property,value,source', 'all', $listElem);
print STDERR '# ' . join(' ', @cmd) . "\n" if $self->debug;
# Really a rare event, not to confuse with just
# getting no properties or bad zfs CLI args
open my $props, '-|', @cmd or Mojo::Exception->throw("ERROR: could not execute zfs to get properties from $listElem");
# NOTE: Code below assumes that the listing groups all items of one dataset together
my $prev_srcds = "";
my $prevSkipped_srcds = "";
while (my $prop = <$props>){
chomp $prop;
if ( (!$self->zfsGetType) && ($prop =~ /^\S+@\S+\s/) ) {
# Filter away snapshot properties ASAP
#$self->zLog->debug("=== getDataSetProperties(): SKIP: '$prop' "
# . "because it is a snapshot property") if $self->debug;
next;
}
# NOTE: This regex assumes the dataset names do not have trailing whitespaces
my ($srcds, $key, $value, $sourcetype, $tail) = $prop =~ /^(.+)\s+\Q$propertyPrefix\E:(\S+)\s+(.+)\s+(local|inherited from )(.*)$/ or next; ### |received|default|-
# If we are here, the property name (key) is under $propertyPrefix
# namespace. So this dataset has at least one "interesting" prop...
# Check if we have inherit mode and should spend time
# and memory about cached data (selective trimming)
if ($inherit && $sourcetype ne 'local') {
# We should trim (non-local) descendants of a listed dataset
# so as to not define the whole world as if having explicit
# backup plans configured
if (defined($cachedInheritance{"$srcds\tattr:source"})) {
# We've already seen a line of this and decided to skip it
if ($prevSkipped_srcds ne $srcds && $self->debug) {
$self->zLog->debug("=== getDataSetProperties(): SKIP: '$srcds' "
. "because it is already skipped");
}
$prevSkipped_srcds = $srcds;
next;
}
my $srcdsParent = $srcds;
$srcdsParent =~ s,/[^/]+$,,; # chop off the tail (if any - none on root datasets)
if (defined($cachedInheritance{"$srcdsParent\tattr:source"})) {
if ($prevSkipped_srcds ne $srcds && $self->debug) {
# Even if we recurse+inherit, we do not need to return
# dozens of backup configurations, one for each child.
# The backup activity would recurse from the topmost.
$self->zLog->debug("=== getDataSetProperties(): SKIP: '$srcds' "
. "because parent config '$srcdsParent' is already listed ("
. $cachedInheritance{"$srcdsParent\tattr:source"} .")");
}
$cachedInheritance{"$srcds\tattr:source"} = "${sourcetype}${tail}";
$prevSkipped_srcds = $srcds;
# TODO/THINK: Do we assume that a configured dataset has ALL fields
# "local" via e.g. znapzendzetup, or if in case of recursion we can
# have a mix of inherited and local? Sounds probable for "enabled"
# property at least. Maybe we should not chop this away right here,
# but do a smarter analysis below in SAVE/SAVE-LAST blocks instead.
%properties = ();
next;
}
}
$self->zLog->debug("=== getDataSetProperties(): FOUND: '$srcds' => '$key' == '$value' (source: '${sourcetype}${tail}')") if $self->debug;
if ($srcds ne $prev_srcds) {
if (%properties && $prev_srcds ne ""){
# place source dataset on list, too. so we know where the properties are from...
$self->zLog->debug("=== getDataSetProperties(): SAVE: '$prev_srcds'") if $self->debug;
$properties{src} = $prev_srcds;
# Note: replacing %properties completely proved hard,
# it just pushed references to same object for many
# really-found datasets. So we make unique copies and
# push them instead.
my %newProps = %properties;
push @propertyList, \%newProps;
%properties = ();
if ($inherit) {
# We've just had a successful save of 1+ attrs we chose
# to keep, so should trim descendants above.
# TODO: Track somehow else? We effectively save the
# source of last seen property here, but are really
# interested if this dataset is end of tree walk
# (as far as non-local attrs go)...
# TODO! Even worse, we now check the new line's source
# type and tail, not the prev-dataset's ones. It doesn't
# matter much at the moment, as we now only care about it
# being set, but can matter after TODO/THINK note above.
$cachedInheritance{"$prev_srcds\tattr:source"} = "${sourcetype}${tail}";
}
}
$prev_srcds = $srcds;
}
# We are okay to use this dataset if:
# * sourcetype == local (any inheritance value)
# * sourcetype == inherited* and the tail names a dataset whose value for the property is local (and inheritance is allowed)
# A bit of optimization (speed vs mem tradeoff) is to cache seen
# property sources (as magic int values); do not bother if not in
# inheritance mode at all.
my $inheritKey = "$srcds\t$key"; # TODO: lowmemInherit => "$srcds" ?
if ($inherit) {
if (!defined($cachedInheritance{$inheritKey})) {
if ($sourcetype eq 'local') {
# this DS defines this property
$cachedInheritance{$inheritKey} = 1;
} else {
# inherited from something... technically there are other
# categories too (default, received) but we only care to
# not run "zfs get" in vain for known misses
$cachedInheritance{$inheritKey} = 2;
}
}
}
if ($sourcetype eq 'local') {
$properties{$key} = $value;
} else {
# Not a local...
# print STDERR "NAL: '$inherit' && '$sourcetype' eq 'inherited from ' && '$tail' ne ''\n" if $self->debug;
if ($inherit && $sourcetype eq 'inherited from ' && $tail ne '') {
my $tail_inheritKey = "$tail\t$key"; # TODO: lowmemInherit => "$tail" ?
if (!defined($cachedInheritance{$tail_inheritKey})) {
# Call zfs get for $tail, fetch all interesting attrs while at it
$self->zLog->debug("=== getDataSetProperties(): "
. "Looking for '$key' under inheritance source "
. "'$tail' to see if it is local there")
if $self->debug;
my @inh_cmd = (@{$self->priv}, qw(zfs get -H -s local));
if ($self->zfsGetType) {
push (@inh_cmd, qw(-t), 'filesystem,volume');
}
# TODO: here and in mock t/zfs, reduce to "-o name,property,source"
# or even "-o property,source" when zfsGetType is enabled
push (@inh_cmd, qw(-o), 'name,property,value,source',
'all', $tail);
print STDERR '## ' . join(' ', @inh_cmd) . "\n" if $self->debug;
open my $inh_props, '-|', @inh_cmd or Mojo::Exception->throw("ERROR: could not execute zfs to get properties from $tail");
while (my $inh_prop = <$inh_props>){
chomp $inh_prop;
if ( (!$self->zfsGetType) && ($inh_prop =~ /^\S+@\S+\s/) ) {
# Filter away snapshot properties ASAP
#$self->zLog->debug("=== getDataSetProperties(): SKIP: inherited '$inh_prop' "
# . "because it is a snapshot property") if $self->debug;
next;
}
my ($inh_srcds, $inh_key, $inh_value, $inh_sourcetype, $inh_tail) =
$inh_prop =~ /^(.+)\s+\Q$propertyPrefix\E:(\S+)\s+(.+)\s+(local|inherited from |received|default|-)(.*)$/
or next;
$self->zLog->debug("=== getDataSetProperties(): FOUND ORIGIN: '$inh_srcds' => '$inh_key' == '$inh_value' (source: '${inh_sourcetype}${inh_tail}')") if $self->debug;
my $inh_inheritKey = "$inh_srcds\t$inh_key"; # TODO: lowmemInherit => "$inh_srcds" ?
if ($inh_sourcetype eq 'local') {
# this DS defines this property
$cachedInheritance{$inh_inheritKey} = 1;
} else {
# inherited from something... technically there are other
# categories too (default, received) but we only care to
# not run "zfs get" in vain for known misses
$cachedInheritance{$inh_inheritKey} = 2;
}
}
# } else {