-
Notifications
You must be signed in to change notification settings - Fork 0
/
btrbk
executable file
·7122 lines (6373 loc) · 268 KB
/
btrbk
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
#!/usr/bin/perl
#
# btrbk - Create snapshots and remote backups of btrfs subvolumes
#
# Copyright (C) 2014-2022 Axel Burri
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ---------------------------------------------------------------------
# The official btrbk website is located at:
# https://digint.ch/btrbk/
#
# Author:
# Axel Burri <[email protected]>
# ---------------------------------------------------------------------
use strict;
use warnings FATAL => qw( all ), NONFATAL => qw( deprecated );
use Carp qw(confess);
use Getopt::Long qw(GetOptions);
use Time::Local qw( timelocal timegm timegm_nocheck );
use IPC::Open3 qw(open3);
use Symbol qw(gensym);
use Cwd qw(abs_path);
our $VERSION = '0.33.0-dev';
our $AUTHOR = 'Axel Burri <[email protected]>';
our $PROJECT_HOME = '<https://digint.ch/btrbk/>';
our $BTRFS_PROGS_MIN = '4.12'; # required since btrbk-v0.27.0
my $VERSION_INFO = "btrbk command line client, version $VERSION";
my @config_src = ("/etc/btrbk.conf", "/etc/btrbk/btrbk.conf");
my %compression = (
# NOTE: also adapt "compress_list" in ssh_filter_btrbk.sh if you change this
gzip => { name => 'gzip', format => 'gz', compress_cmd => [ 'gzip', '-c' ], decompress_cmd => [ 'gzip', '-d', '-c' ], level_min => 1, level_max => 9 },
pigz => { name => 'pigz', format => 'gz', compress_cmd => [ 'pigz', '-c' ], decompress_cmd => [ 'pigz', '-d', '-c' ], level_min => 1, level_max => 9, threads => '-p' },
bzip2 => { name => 'bzip2', format => 'bz2', compress_cmd => [ 'bzip2', '-c' ], decompress_cmd => [ 'bzip2', '-d', '-c' ], level_min => 1, level_max => 9 },
pbzip2 => { name => 'pbzip2', format => 'bz2', compress_cmd => [ 'pbzip2', '-c' ], decompress_cmd => [ 'pbzip2', '-d', '-c' ], level_min => 1, level_max => 9, threads => '-p' },
xz => { name => 'xz', format => 'xz', compress_cmd => [ 'xz', '-c' ], decompress_cmd => [ 'xz', '-d', '-c' ], level_min => 0, level_max => 9, threads => '-T' },
lzo => { name => 'lzo', format => 'lzo', compress_cmd => [ 'lzop', '-c' ], decompress_cmd => [ 'lzop', '-d', '-c' ], level_min => 1, level_max => 9 },
lz4 => { name => 'lz4', format => 'lz4', compress_cmd => [ 'lz4', '-c' ], decompress_cmd => [ 'lz4', '-d', '-c' ], level_min => 1, level_max => 9 },
zstd => { name => 'zstd', format => 'zst', compress_cmd => [ 'zstd', '-c' ], decompress_cmd => [ 'zstd', '-d', '-c' ], level_min => 1, level_max => 19, threads => '-T', long => '--long=', adapt => '--adapt' },
);
my $compress_format_alt = join '|', map { $_->{format} } values %compression; # note: this contains duplicate alternations
my $ipv4_addr_match = qr/(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])/;
my $ipv6_addr_match = qr/[a-fA-F0-9]*:[a-fA-F0-9]*:[a-fA-F0-9:]+/; # simplified (contains at least two colons), matches "::1", "2001:db8::7"
my $host_name_match = qr/(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])/;
my $uuid_match = qr/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/;
my $btrbk_timestamp_match = qr/(?<YYYY>[0-9]{4})(?<MM>[0-9]{2})(?<DD>[0-9]{2})(T(?<hh>[0-9]{2})(?<mm>[0-9]{2})((?<ss>[0-9]{2})(?<zz>(Z|[+-][0-9]{4})))?)?(_(?<NN>[0-9]+))?/; # matches "YYYYMMDD[Thhmm[ss+0000]][_NN]"
my $raw_postfix_match = qr/\.btrfs(\.($compress_format_alt))?(\.(gpg|encrypted))?/; # matches ".btrfs[.gz|bz2|xz][.gpg|encrypted]"
my $safe_file_match = qr/[0-9a-zA-Z_@\+\-\.\/]+/; # note: ubuntu uses '@' in the subvolume layout: <https://help.ubuntu.com/community/btrfs>
my $group_match = qr/[a-zA-Z0-9_:-]+/;
my $config_split_match = qr/\s*[,\s]\s*/;
my %day_of_week_map = ( sunday => 0, monday => 1, tuesday => 2, wednesday => 3, thursday => 4, friday => 5, saturday => 6 );
my @syslog_facilities = qw( user mail daemon auth lpr news cron authpriv local0 local1 local2 local3 local4 local5 local6 local7 );
my @incremental_prefs_avail = qw(sro srn sao san aro arn);
my @incremental_prefs_default = qw(sro:1 srn:1 sao:1 san:1 aro:1 arn:1);
my $incremental_prefs_match = "(defaults|(" . join("|", @incremental_prefs_avail) . ")(:[0-9]+)?)";
my %config_options = (
# NOTE: the parser always maps "no" to undef
# NOTE: keys "volume", "subvolume" and "target" are hardcoded
# NOTE: files "." and "no" map to <undef>
timestamp_format => { default => "long", accept => [qw( short long long-iso )], context => [qw( global volume subvolume )] },
snapshot_dir => { default => undef, accept_file => { relative => 1, absolute => 1 }, context => [qw( global volume subvolume )] },
snapshot_name => { c_default => 1, accept_file => { name_only => 1 }, context => [qw( subvolume )], deny_glob_context => 1 }, # NOTE: defaults to the subvolume name (hardcoded)
snapshot_create => { default => "always", accept => [qw( no always ondemand onchange )], context => [qw( global volume subvolume )] },
incremental => { default => "yes", accept => [qw( yes no strict )] },
incremental_prefs => { default => \@incremental_prefs_default, accept => [ qr/$incremental_prefs_match/ ], split => 1 },
incremental_clones => { default => "yes", accept => [qw( yes no )] },
incremental_resolve => { default => "mountpoint", accept => [qw( mountpoint directory _all_accessible )] },
preserve_day_of_week => { default => "sunday", accept => [ (keys %day_of_week_map) ] },
preserve_hour_of_day => { default => 0, accept => [ (0..23) ] },
snapshot_preserve => { default => undef, accept => [qw( no )], accept_preserve_matrix => 1, context => [qw( global volume subvolume )], },
snapshot_preserve_min => { default => "all", accept => [qw( all latest ), qr/[1-9][0-9]*[hdwmy]/ ], context => [qw( global volume subvolume )], },
target_preserve => { default => undef, accept => [qw( no )], accept_preserve_matrix => 1 },
target_preserve_min => { default => "all", accept => [qw( all latest no ), qr/[0-9]+[hdwmy]/ ] },
target_create_dir => { default => undef, accept => [qw( yes no )] },
archive_preserve => { default => undef, accept => [qw( no )], accept_preserve_matrix => 1, context => [qw( global )] },
archive_preserve_min => { default => "all", accept => [qw( all latest no ), qr/[0-9]+[hdwmy]/ ], context => [qw( global )] },
btrfs_commit_delete => { default => undef, accept => [qw( after each no )] },
ssh_identity => { default => undef, accept_file => { absolute => 1 } },
ssh_user => { default => "root", accept => [ qr/[a-z_][a-z0-9_-]*/ ] },
ssh_compression => { default => undef, accept => [qw( yes no )] },
ssh_cipher_spec => { default => [ "default" ], accept => [qw( default ), qr/[a-z0-9][[email protected]]+/ ], split => 1 },
transaction_log => { default => undef, accept => [qw( no )], accept_file => { absolute => 1 }, context => [qw( global )] },
transaction_syslog => { default => undef, accept => [qw( no ), @syslog_facilities ], context => [qw( global )] },
lockfile => { default => undef, accept => [qw( no )], accept_file => { absolute => 1 }, context => [qw( global )] },
rate_limit => { default => undef, accept => [qw( no ), qr/[0-9]+[kmgtKMGT]?/ ], require_bin => 'mbuffer' },
rate_limit_remote => { default => undef, accept => [qw( no ), qr/[0-9]+[kmgtKMGT]?/ ] }, # NOTE: requires 'mbuffer' command on remote hosts
stream_buffer => { default => undef, accept => [qw( no ), qr/[0-9]+[kmgKMG%]?/ ], require_bin => 'mbuffer' },
stream_buffer_remote => { default => undef, accept => [qw( no ), qr/[0-9]+[kmgKMG%]?/ ] }, # NOTE: requires 'mbuffer' command on remote hosts
stream_compress => { default => undef, accept => [qw( no ), (keys %compression) ] },
stream_compress_level => { default => "default", accept => [qw( default ), qr/[0-9]+/ ] },
stream_compress_long => { default => "default", accept => [qw( default ), qr/[0-9]+/ ] },
stream_compress_threads => { default => "default", accept => [qw( default ), qr/[0-9]+/ ] },
stream_compress_adapt => { default => undef, accept => [qw( yes no )] },
raw_target_compress => { default => undef, accept => [qw( no ), (keys %compression) ] },
raw_target_compress_level => { default => "default", accept => [qw( default ), qr/[0-9]+/ ] },
raw_target_compress_long => { default => "default", accept => [qw( default ), qr/[0-9]+/ ] },
raw_target_compress_threads => { default => "default", accept => [qw( default ), qr/[0-9]+/ ] },
raw_target_encrypt => { default => undef, accept => [qw( no gpg openssl_enc )] },
raw_target_block_size => { default => "128K", accept => [ qr/[0-9]+[kmgKMG]?/ ] },
raw_target_split => { default => undef, accept => [qw( no ), qr/[0-9]+([kmgtpezyKMGTPEZY][bB]?)?/ ] },
gpg_keyring => { default => undef, accept_file => { absolute => 1 } },
gpg_recipient => { default => undef, accept => [ qr/[0-9a-zA-Z_@\+\-\.]+/ ], split => 1 },
openssl_ciphername => { default => "aes-256-cbc", accept => [ qr/[0-9a-zA-Z\-]+/ ] },
openssl_iv_size => { default => undef, accept => [qw( no ), qr/[0-9]+/ ] },
openssl_keyfile => { default => undef, accept_file => { absolute => 1 } },
kdf_backend => { default => undef, accept_file => { absolute => 1 } },
kdf_keysize => { default => "32", accept => [ qr/[0-9]+/ ] },
kdf_keygen => { default => "once", accept => [qw( once each )] },
group => { default => undef, accept => [ qr/$group_match/ ], allow_multiple => 1, split => 1 },
noauto => { default => undef, accept => [qw( yes no )] },
backend => { default => "btrfs-progs", accept => [qw( btrfs-progs btrfs-progs-btrbk btrfs-progs-sudo btrfs-progs-doas )] },
backend_local => { default => undef, accept => [qw( no btrfs-progs btrfs-progs-btrbk btrfs-progs-sudo btrfs-progs-doas )] },
backend_remote => { default => undef, accept => [qw( no btrfs-progs btrfs-progs-btrbk btrfs-progs-sudo btrfs-progs-doas )] },
backend_local_user => { default => undef, accept => [qw( no btrfs-progs btrfs-progs-btrbk btrfs-progs-sudo btrfs-progs-doas )] },
compat => { default => undef, accept => [qw( no busybox ignore_receive_errors )], split => 1 },
compat_local => { default => undef, accept => [qw( no busybox ignore_receive_errors )], split => 1 },
compat_remote => { default => undef, accept => [qw( no busybox ignore_receive_errors )], split => 1 },
safe_commands => { default => undef, accept => [qw( yes no )], context => [qw( global )] },
snapshot_qgroup_destroy => { default => undef, accept => [qw( yes no )], context => [qw( global volume subvolume )] },
target_qgroup_destroy => { default => undef, accept => [qw( yes no )] },
archive_qgroup_destroy => { default => undef, accept => [qw( yes no )], context => [qw( global )] },
archive_exclude => { default => undef, accept_file => { wildcards => 1 }, allow_multiple => 1, context => [qw( global )] },
archive_exclude_older => { default => undef, accept => [qw( yes no )] },
cache_dir => { default => undef, accept_file => { absolute => 1 }, allow_multiple => 1, context => [qw( global )] },
ignore_extent_data_inline => { default => "yes", accept => [qw( yes no )] },
warn_unknown_targets => { default => undef, accept => [qw( yes no )] },
# deprecated options
ssh_port => { default => "default", accept => [qw( default ), qr/[0-9]+/ ],
deprecated => { DEFAULT => { warn => 'Please use "ssh://hostname[:port]" notation in the "volume" and "target" configuration lines.' } } },
btrfs_progs_compat => { default => undef, accept => [qw( yes no )],
deprecated => { DEFAULT => { ABORT => 1, warn => 'This feature has been dropped in btrbk-v0.23.0. Please update to newest btrfs-progs, AT LEAST >= $BTRFS_PROGS_MIN' } } },
snapshot_preserve_daily => { default => 'all', accept => [qw( all ), qr/[0-9]+/ ], context => [qw( global volume subvolume )],
deprecated => { DEFAULT => { FAILSAFE_PRESERVE => 1, warn => 'Please use "snapshot_preserve" and/or "snapshot_preserve_min"' } } },
snapshot_preserve_weekly => { default => 0, accept => [qw( all ), qr/[0-9]+/ ], context => [qw( global volume subvolume )],
deprecated => { DEFAULT => { FAILSAFE_PRESERVE => 1, warn => 'Please use "snapshot_preserve" and/or "snapshot_preserve_min"' } } },
snapshot_preserve_monthly => { default => 'all', accept => [qw( all ), qr/[0-9]+/ ], context => [qw( global volume subvolume )],
deprecated => { DEFAULT => { FAILSAFE_PRESERVE => 1, warn => 'Please use "snapshot_preserve" and/or "snapshot_preserve_min"' } } },
target_preserve_daily => { default => 'all', accept => [qw( all ), qr/[0-9]+/ ],
deprecated => { DEFAULT => { FAILSAFE_PRESERVE => 1, warn => 'Please use "target_preserve" and/or "target_preserve_min"' } } },
target_preserve_weekly => { default => 0, accept => [qw( all ), qr/[0-9]+/ ],
deprecated => { DEFAULT => { FAILSAFE_PRESERVE => 1, warn => 'Please use "target_preserve" and/or "target_preserve_min"' } } },
target_preserve_monthly => { default => 'all', accept => [qw( all ), qr/[0-9]+/ ],
deprecated => { DEFAULT => { FAILSAFE_PRESERVE => 1, warn => 'Please use "target_preserve" and/or "target_preserve_min"' } } },
resume_missing => { default => "yes", accept => [qw( yes no )],
deprecated => { yes => { warn => 'ignoring (missing backups are always resumed since btrbk v0.23.0)' },
no => { FAILSAFE_PRESERVE => 1, warn => 'Please use "target_preserve_min latest" and "target_preserve no" if you want to keep only the latest backup', } } },
snapshot_create_always => { default => undef, accept => [qw( yes no )],
deprecated => { yes => { warn => "Please use \"snapshot_create always\"",
replace_key => "snapshot_create",
replace_value => "always",
},
no => { warn => "Please use \"snapshot_create no\" or \"snapshot_create ondemand\"",
replace_key => "snapshot_create",
replace_value => "ondemand",
}
},
},
receive_log => { default => undef, accept => [qw( sidecar no )], accept_file => { absolute => 1 },
deprecated => { DEFAULT => { warn => "ignoring" } },
}
);
my @config_target_types = qw(send-receive raw); # first in list is default
my %table_formats = (
config_volume => {
table => [ qw( -volume_host -volume_port volume_path ) ],
long => [ qw( volume_host -volume_port volume_path -volume_rsh ) ],
raw => [ qw( volume_url volume_host volume_port volume_path volume_rsh ) ],
single_column => [ qw( volume_url ) ],
},
config_source => {
table => [ qw( -source_host -source_port source_subvolume snapshot_path snapshot_name ) ],
long => [ qw( source_host -source_port source_subvolume snapshot_path snapshot_name -source_rsh ) ],
raw => [ qw( source_url source_host source_port source_subvolume snapshot_path snapshot_name source_rsh ) ],
single_column => [ qw( source_url ) ],
},
config_target => {
table => [ qw( -target_host -target_port target_path ) ],
long => [ qw( target_host -target_port target_path -target_rsh ) ],
raw => [ qw( target_url target_host target_port target_path target_rsh ) ],
single_column => [ qw( target_url ) ],
},
config => {
table => [ qw( -source_host -source_port source_subvolume snapshot_path snapshot_name -target_host -target_port target_path ) ],
long => [ qw( -source_host -source_port source_subvolume snapshot_path snapshot_name -target_host -target_port target_path target_type snapshot_preserve target_preserve ) ],
raw => [ qw( source_url source_host source_port source_subvolume snapshot_path snapshot_name target_url target_host target_port target_path target_type snapshot_preserve target_preserve source_rsh target_rsh ) ],
},
resolved => {
table => [ qw( -source_host -source_port source_subvolume snapshot_subvolume status -target_host -target_port target_subvolume ) ],
long => [ qw( -source_host -source_port source_subvolume snapshot_subvolume status -target_host -target_port target_subvolume target_type ) ],
raw => [ qw( type source_url source_host source_port source_subvolume snapshot_subvolume snapshot_name status target_url target_host target_port target_subvolume target_type source_rsh target_rsh ) ],
},
snapshots => {
table => [ qw( -source_host -source_port source_subvolume snapshot_subvolume status ) ],
long => [ qw( -source_host -source_port source_subvolume snapshot_subvolume status ) ],
raw => [ qw( source_url source_host source_port source_subvolume snapshot_subvolume snapshot_name status source_rsh ) ],
single_column => [ qw( snapshot_url ) ],
},
backups => { # same as resolved, except for single_column
table => [ qw( -source_host -source_port source_subvolume snapshot_subvolume status -target_host -target_port target_subvolume ) ],
long => [ qw( -source_host -source_port source_subvolume snapshot_subvolume status -target_host -target_port target_subvolume target_type ) ],
raw => [ qw( type source_url source_host source_port source_subvolume snapshot_subvolume snapshot_name status target_url target_host target_port target_subvolume target_type source_rsh target_rsh ) ],
single_column => [ qw( target_url ) ],
},
latest => { # same as resolved, except hiding target if not present
table => [ qw( -source_host -source_port source_subvolume snapshot_subvolume status -target_host -target_port -target_subvolume ) ],
long => [ qw( -source_host -source_port source_subvolume snapshot_subvolume status -target_host -target_port -target_subvolume -target_type ) ],
raw => [ qw( type source_url source_host source_port source_subvolume snapshot_subvolume snapshot_name status target_url target_host target_port target_subvolume target_type source_rsh target_rsh ) ],
},
stats => {
table => [ qw( -source_host -source_port source_subvolume snapshot_subvolume -target_host -target_port -target_subvolume snapshots -backups ) ],
long => [ qw( -source_host -source_port source_subvolume snapshot_subvolume -target_host -target_port -target_subvolume snapshot_status backup_status snapshots -backups -correlated -orphaned -incomplete ) ],
raw => [ qw( source_url source_host source_port source_subvolume snapshot_subvolume snapshot_name target_url target_host target_port target_subvolume snapshot_status backup_status snapshots backups correlated orphaned incomplete ) ],
RALIGN => { snapshots=>1, backups=>1, correlated=>1, orphaned=>1, incomplete=>1 },
},
schedule => {
table => [ qw( action -host -port subvolume scheme reason ) ],
long => [ qw( action -host -port subvolume scheme reason ) ],
raw => [ qw( topic action url host port path hod dow min h d w m y) ],
},
usage => {
table => [ qw( -host -port mount_source path size used free ) ],
long => [ qw( type -host -port mount_source path size used device_size device_allocated device_unallocated device_missing device_used free free_min data_ratio metadata_ratio global_reserve global_reserve_used ) ],
raw => [ qw( type host port mount_source path size used device_size device_allocated device_unallocated device_missing device_used free free_min data_ratio metadata_ratio global_reserve global_reserve_used ) ],
RALIGN => { size=>1, used=>1, device_size=>1, device_allocated=>1, device_unallocated=>1, device_missing=>1, device_used=>1, free=>1, free_min=>1, data_ratio=>1, metadata_ratio=>1, global_reserve=>1, global_reserve_used=>1 },
},
transaction => {
table => [ qw( type status -target_host -target_port target_subvolume -source_host -source_port source_subvolume parent_subvolume ) ],
long => [ qw( localtime type status duration target_host -target_port target_subvolume source_host -source_port source_subvolume parent_subvolume message ) ],
tlog => [ qw( localtime type status target_url source_url parent_url message ) ],
syslog => [ qw( type status target_url source_url parent_url message ) ],
raw => [ qw( time localtime type status duration target_url source_url parent_url message ) ],
},
origin_tree => {
table => [ qw( tree uuid parent_uuid received_uuid ) ],
long => [ qw( tree uuid parent_uuid received_uuid recursion ) ],
raw => [ qw( tree uuid parent_uuid received_uuid recursion ) ],
},
diff => {
table => [ qw( flags count size file ) ],
long => [ qw( flags count size file ) ],
raw => [ qw( flags count size file ) ],
RALIGN => { count=>1, size=>1 },
},
fs_list => {
table => [ qw( -host mount_source mount_subvol mount_point id flags subvolume_path path ) ],
short => [ qw( -host mount_source id flags path ) ],
long => [ qw( -host mount_source id top cgen gen uuid parent_uuid received_uuid flags path ) ],
raw => [ qw( host mount_source mount_subvol mount_point mount_subvolid id top_level cgen gen uuid parent_uuid received_uuid readonly path subvolume_path subvolume_rel_path url ) ],
single_column => [ qw( url ) ],
RALIGN => { id=>1, top=>1, cgen=>1, gen=>1 },
},
extent_diff => {
table => [ qw( total exclusive -diff -set subvol ) ],
long => [ qw( id cgen gen total exclusive -diff -set subvol ) ],
raw => [ qw( id cgen gen total exclusive -diff -set subvol ) ],
RALIGN => { id=>1, cgen=>1, gen=>1, total=>1, exclusive=>1, diff=>1, set=>1 },
},
);
my @btrfs_cmd = (
"btrfs subvolume list",
"btrfs subvolume show",
"btrfs subvolume snapshot",
"btrfs subvolume delete",
"btrfs send",
"btrfs receive",
"btrfs filesystem usage",
"btrfs qgroup destroy",
);
my @system_cmd = (
"readlink",
"test",
);
my %backend_cmd_map = (
"btrfs-progs-btrbk" => { map +( $_ => [ s/ /-/gr ] ), @btrfs_cmd },
"btrfs-progs-sudo" => { map +( $_ => [ qw( sudo -n ), split(" ", $_) ] ), @btrfs_cmd, @system_cmd },
"btrfs-progs-doas" => { map +( $_ => [ qw( doas -n ), split(" ", $_) ] ), @btrfs_cmd, @system_cmd },
);
# keys used in raw target sidecar files (.info):
my %raw_info_sort = (
TYPE => 1,
FILE => 2,
RECEIVED_UUID => 3,
RECEIVED_PARENT_UUID => 4,
INCOMPLETE => 5,
# disabled for now, as its not very useful and might leak information
#source_url => 6,
#parent_url => 7,
#target_url => 8,
compress => 9,
split => 10,
encrypt => 11,
cipher => 12,
iv => 13,
# kdf_* (generated by kdf_backend)
);
my %raw_url_cache; # map URL to (fake) btr_tree node
my %mountinfo_cache; # map MACHINE_ID to mount points (sorted descending by file length)
my %mount_source_cache; # map URL_PREFIX:mount_source (aka device) to btr_tree node
my %uuid_cache; # map UUID to btr_tree node
my %realpath_cache; # map URL to realpath (symlink target). empty string denotes an error.
my $tree_inject_id = 0; # fake subvolume id for injected nodes (negative)
my $fake_uuid_prefix = 'XXXXXXXX-XXXX-XXXX-XXXX-'; # plus 0-padded inject_id: XXXXXXXX-XXXX-XXXX-XXXX-000000000000
my $program_name; # "btrbk" or "lsbtr", default to "btrbk"
my $safe_commands;
my $dryrun;
my $loglevel = 1;
my $quiet;
my @exclude_vf;
my $do_dumper;
my $do_trace;
my $show_progress = 0;
my $output_format;
my $output_pretty = 0;
my @output_unit;
my $lockfile;
my $tlog_fh;
my $syslog_enabled = 0;
my $current_transaction;
my @transaction_log;
my %config_override;
my @tm_now; # current localtime ( sec, min, hour, mday, mon, year, wday, yday, isdst )
my @stderr; # stderr of last run_cmd
my %warn_once;
my %kdf_vars;
my $kdf_session_key;
$SIG{__DIE__} = sub {
print STDERR "\nERROR: process died unexpectedly (btrbk v$VERSION)";
print STDERR "\nPlease contact the author: $AUTHOR\n\n";
print STDERR "Stack Trace:\n----------------------------------------\n";
Carp::confess @_;
};
$SIG{INT} = sub {
print STDERR "\nERROR: Caught SIGINT, dumping transaction log:\n";
action("signal", status => "SIGINT");
print_formatted("transaction", \@transaction_log, output_format => "tlog", outfile => *STDERR);
exit 1;
};
sub VERSION_MESSAGE
{
print $VERSION_INFO . "\n";
}
sub ERROR_HELP_MESSAGE
{
return if($quiet);
print STDERR "See '$program_name --help'.\n";
}
sub HELP_MESSAGE
{
return if($quiet);
#80-----------------------------------------------------------------------------
if($program_name eq "lsbtr") {
print <<"END_HELP_LSBTR";
usage: lsbtr [<options>] [[--] <path>...]
options:
-h, --help display this help message
--version display version information
-l, --long use long listing format
-u, --uuid print uuid table (parent/received relations)
-1, --single-column Print path column only
--raw print raw table format
-v, --verbose increase output verbosity
-c, --config=FILE specify btrbk configuration file
--override=KEY=VALUE globally override a configuration option
For additional information, see $PROJECT_HOME
END_HELP_LSBTR
}
else {
print <<"END_HELP_BTRBK";
usage: btrbk [<options>] <command> [[--] <filter>...]
options:
-h, --help display this help message
--version display version information
-c, --config=FILE specify configuration file
-n, --dry-run perform a trial run with no changes made
--exclude=FILTER exclude configured sections
-p, --preserve preserve all (do not delete anything)
--preserve-snapshots preserve snapshots (do not delete snapshots)
--preserve-backups preserve backups (do not delete backups)
--wipe delete all but latest snapshots
-v, --verbose be more verbose (increase logging level)
-q, --quiet be quiet (do not print backup summary)
-l, --loglevel=LEVEL set logging level (error, warn, info, debug, trace)
-t, --table change output to table format
-L, --long change output to long format
--format=FORMAT change output format, FORMAT=table|long|raw
-S, --print-schedule print scheduler details (for the "run" command)
--progress show progress bar on send-receive operation
--lockfile=FILE create and check lockfile
--override=KEY=VALUE globally override a configuration option
commands:
run run snapshot and backup operations
dryrun don't run btrfs commands; show what would be executed
snapshot run snapshot operations only
resume run backup operations, and delete snapshots
prune only delete snapshots and backups
archive <src> <dst> recursively copy all subvolumes
clean delete incomplete (garbled) backups
stats print snapshot/backup statistics
list <subcommand> available subcommands are (default "all"):
all snapshots and backups
snapshots snapshots
backups backups and correlated snapshots
latest most recent snapshots and backups
config configured source/snapshot/target relations
source configured source/snapshot relations
volume configured volume sections
target configured targets
usage print filesystem usage
ls <path> list all btrfs subvolumes below path
origin <subvol> print origin information for subvolume
diff <from> <to> list file changes between related subvolumes
extents [diff] <path> calculate accurate disk space usage
For additional information, see $PROJECT_HOME
END_HELP_BTRBK
}
#80-----------------------------------------------------------------------------
}
sub _log_cont { my $p = shift; print STDERR $p . join("\n${p}... ", @_) . "\n"; }
sub TRACE { print STDERR map { "___ $_\n" } @_ if($loglevel >= 4) }
sub DEBUG { _log_cont("", @_) if($loglevel >= 3) }
sub INFO { _log_cont("", @_) if($loglevel >= 2) }
sub WARN { _log_cont("WARNING: ", @_) if($loglevel >= 1) }
sub ERROR { _log_cont("ERROR: ", @_) }
sub INFO_ONCE {
my $t = shift;
if($warn_once{INFO}{$t}) { TRACE("INFO(again): $t", @_) if($do_trace); return 0; }
else { $warn_once{INFO}{$t} = 1; INFO($t, @_); return 1; }
}
sub WARN_ONCE {
my $t = shift;
if($warn_once{WARN}{$t}) { TRACE("WARNING(again): $t", @_) if($do_trace); return 0; }
else { $warn_once{WARN}{$t} = 1; WARN($t, @_); return 1; }
}
sub VINFO {
return undef unless($do_dumper);
my $vinfo = shift; my $t = shift || "vinfo"; my $maxdepth = shift // 2;
print STDERR Data::Dumper->new([$vinfo], [$t])->Maxdepth($maxdepth)->Dump();
}
sub SUBVOL_LIST {
return undef unless($do_dumper);
my $vol = shift; my $t = shift // "SUBVOL_LIST"; my $svl = vinfo_subvol_list($vol);
print STDERR "$t:\n " . join("\n ", map { "$vol->{PRINT}/./$_->{SUBVOL_PATH}\t$_->{node}{id}" } @$svl) . "\n";
}
sub ABORTED($$;$)
{
my $config = shift;
my $abrt_key = shift // die;
my $abrt = shift;
$config = $config->{CONFIG} if($config->{CONFIG}); # accept vinfo for $config
unless(defined($abrt)) {
# no key (only text) set: switch arguments, use default key
$abrt = $abrt_key;
$abrt_key = "abort_" . $config->{CONTEXT};
}
unless($abrt_key =~ /^skip_/) {
# keys starting with "skip_" are not actions
$abrt =~ s/\n/\\\\/g;
$abrt =~ s/\r//g;
action($abrt_key,
status => "ABORT",
vinfo_prefixed_keys("target", vinfo($config->{url}, $config)),
message => $abrt,
);
}
$config->{ABORTED} = { key => $abrt_key, text => $abrt };
}
sub IS_ABORTED($;$)
{
my $config = shift;
$config = $config->{CONFIG} if($config->{CONFIG}); # accept vinfo for $config
return undef unless(defined($config->{ABORTED}));
my $abrt_key = $config->{ABORTED}->{key};
return undef unless(defined($abrt_key));
my $filter_prefix = shift;
return undef if($filter_prefix && ($abrt_key !~ /^$filter_prefix/));
return $abrt_key;
}
sub ABORTED_TEXT($)
{
my $config = shift;
$config = $config->{CONFIG} if($config->{CONFIG}); # accept vinfo for $config
return "" unless(defined($config->{ABORTED}));
return $config->{ABORTED}->{text} // "";
}
sub FIX_MANUALLY($$)
{
# treated as error, but does not abort config section
my $config = shift;
$config = $config->{CONFIG} if($config->{CONFIG}); # accept vinfo for $config
my $msg = shift // die;
$config->{FIX_MANUALLY} //= [];
push(@{$config->{FIX_MANUALLY}}, $msg);
}
sub eval_quiet(&)
{
local $SIG{__DIE__};
return eval { $_[0]->() }
}
sub require_data_dumper
{
if(eval_quiet { require Data::Dumper; }) {
Data::Dumper->import("Dumper");
$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Quotekeys = 0;
$do_dumper = 1;
# silence perl warning: Name "Data::Dumper::Sortkeys" used only once: possible typo at...
TRACE "Successfully loaded Dumper module: sortkeys=$Data::Dumper::Sortkeys, quotekeys=$Data::Dumper::Quotekeys" if($do_trace);
} else {
WARN "Perl module \"Data::Dumper\" not found: data trace dumps disabled!" if($do_trace);
}
}
sub init_transaction_log($$)
{
my $file = shift;
my $config_syslog_facility = shift;
if(defined($file) && (not $dryrun)) {
if(open($tlog_fh, '>>', $file)) {
# print headers (disabled)
# print_formatted("transaction", [ ], output_format => "tlog", outfile => $tlog_fh);
INFO "Using transaction log: $file";
} else {
$tlog_fh = undef;
ERROR "Failed to open transaction log '$file': $!";
}
}
if(defined($config_syslog_facility) && (not $dryrun)) {
DEBUG "Opening syslog";
if(eval_quiet { require Sys::Syslog; }) {
$syslog_enabled = 1;
Sys::Syslog::openlog("btrbk", "", $config_syslog_facility);
DEBUG "Syslog enabled";
}
else {
WARN "Syslog disabled: $@";
}
}
action("DEFERRED", %$_) foreach (@transaction_log);
}
sub close_transaction_log()
{
if($tlog_fh) {
DEBUG "Closing transaction log";
close $tlog_fh || ERROR "Failed to close transaction log: $!";
}
if($syslog_enabled) {
DEBUG "Closing syslog";
eval_quiet { Sys::Syslog::closelog(); };
}
}
sub action($@)
{
my $type = shift // die;
my $h = { @_ };
unless($type eq "DEFERRED") {
my $time = $h->{time} // time;
$h->{type} = $type;
$h->{time} = $time;
$h->{localtime} = timestamp($time, 'debug-iso');
push @transaction_log, $h;
}
print_formatted("transaction", [ $h ], output_format => "tlog", no_header => 1, outfile => $tlog_fh) if($tlog_fh);
print_formatted("transaction", [ $h ], output_format => "syslog", no_header => 1) if($syslog_enabled); # dirty hack, this calls syslog()
return $h;
}
sub start_transaction($@)
{
my $type = shift // die;
my $time = time;
die("start_transaction() while transaction is running") if($current_transaction);
my @actions = (ref($_[0]) eq "HASH") ? @_ : { @_ }; # single action is not hashref
$current_transaction = [];
foreach (@actions) {
push @$current_transaction, action($type, %$_, status => ($dryrun ? "dryrun_starting" : "starting"), time => $time);
}
}
sub end_transaction($$)
{
my $type = shift // die;
my $success = shift; # scalar or coderef: if scalar, status is set for all current transitions
my $time = time;
die("end_transaction() while no transaction is running") unless($current_transaction);
foreach (@$current_transaction) {
die("end_transaction() has different type") unless($_->{type} eq $type);
my $status = (ref($success) ? &{$success} ($_) : $success) ? "success" : "ERROR";
$status = "dryrun_" . $status if($dryrun);
action($type, %$_, status => $status, time => $time, duration => ($dryrun ? undef : ($time - $_->{time})));
}
$current_transaction = undef;
}
sub syslog($)
{
return undef unless($syslog_enabled);
my $line = shift;
eval_quiet { Sys::Syslog::syslog("info", $line); };
}
sub check_exe($)
{
my $cmd = shift // die;
foreach my $path (split(":", $ENV{PATH})) {
return 1 if( -x "$path/$cmd" );
}
return 0;
}
sub stream_buffer_cmd_text($)
{
my $opts = shift;
my $rl_in = $opts->{rate_limit_in} // $opts->{rate_limit}; # maximum read rate: b,k,M,G
my $rl_out = $opts->{rate_limit_out}; # maximum write rate: b,k,M,G
my $bufsize = $opts->{stream_buffer}; # b,k,M,G,% (default: 2%)
my $blocksize = $opts->{blocksize}; # defaults to 10k
my $progress = $opts->{show_progress};
# return empty array if mbuffer is not needed
return () unless($rl_in || $rl_out || $bufsize || $progress);
# NOTE: mbuffer takes defaults from /etc/mbuffer.rc
my @cmd = ( "mbuffer" );
push @cmd, ( "-v", "1" ); # disable warnings (they arrive asynchronously and cant be caught)
push @cmd, "-q" unless($progress);
push @cmd, ( "-s", $blocksize ) if($blocksize);
push @cmd, ( "-m", lc($bufsize) ) if($bufsize);
push @cmd, ( "-r", lc($rl_in) ) if($rl_in);
push @cmd, ( "-R", lc($rl_out) ) if($rl_out);
return { cmd_text => join(' ', @cmd) };
}
sub compress_cmd_text($;$)
{
my $def = shift // die;
my $decompress = shift;
my $cc = $compression{$def->{key}};
my @cmd = $decompress ? @{$cc->{decompress_cmd}} : @{$cc->{compress_cmd}};
if((not $decompress) && defined($def->{level}) && ($def->{level} ne "default")) {
my $level = $def->{level};
if($level < $cc->{level_min}) {
WARN_ONCE "Compression level capped to minimum for '$cc->{name}': $cc->{level_min}";
$level = $cc->{level_min};
}
if($level > $cc->{level_max}) {
WARN_ONCE "Compression level capped to maximum for '$cc->{name}': $cc->{level_max}";
$level = $cc->{level_max};
}
push @cmd, '-' . $level;
}
if(defined($def->{threads}) && ($def->{threads} ne "default")) {
my $thread_opt = $cc->{threads};
if($thread_opt) {
push @cmd, $thread_opt . $def->{threads};
}
else {
WARN_ONCE "Threading is not supported for '$cc->{name}', ignoring";
}
}
if(defined($def->{long}) && ($def->{long} ne "default")) {
my $long_opt = $cc->{long};
if($long_opt) {
push @cmd, $long_opt . $def->{long};
}
else {
WARN_ONCE "Long distance matching is not supported for '$cc->{name}', ignoring";
}
}
if(defined($def->{adapt})) {
my $adapt_opt = $cc->{adapt};
if($adapt_opt) {
push @cmd, $adapt_opt;
}
else {
WARN_ONCE "Adaptive compression is not supported for '$cc->{name}', ignoring";
}
}
return { cmd_text => join(' ', @cmd) };
}
sub decompress_cmd_text($)
{
return compress_cmd_text($_[0], 1);
}
sub _piped_cmd_txt($)
{
my $cmd_pipe = shift;
my $cmd = "";
my $pipe = "";
my $last;
foreach (map $_->{cmd_text}, @$cmd_pipe) {
die if($last);
if(/^>/) {
# can't be first, must be last
die unless($pipe);
$last = 1;
$pipe = ' ';
}
$cmd .= $pipe . $_;
$pipe = ' | ';
}
return $cmd;
}
sub quoteshell(@) {
# replace ' -> '\''
join ' ', map { "'" . s/'/'\\''/gr . "'" } @_
}
sub _safe_cmd($;$)
{
# hashes of form: "{ unsafe => 'string' }" get translated to "'string'"
my $aref = shift;
my $offending = shift;
return join ' ', map {
if(ref($_)) {
my $prefix = $_->{prefix} // "";
my $postfix = $_->{postfix} // "";
$_ = $_->{unsafe};
die "cannot quote leading dash for command: $_" if(/^-/);
# NOTE: all files must be absolute
if($offending) {
push @$offending, $_ unless(defined(check_file($_, { absolute => 1 })));
push @$offending, $_ unless(!$safe_commands || /^($safe_file_match)$/);
}
$_ = $prefix . quoteshell($_) . $postfix;
}
$_
} @$aref;
}
sub run_cmd(@)
{
# IPC::Open3 based implementation.
# NOTE: multiple filters are not supported!
my @cmd_pipe_in = (ref($_[0]) eq "HASH") ? @_ : { @_ };
die unless(scalar(@cmd_pipe_in));
@stderr = ();
my $destructive = 0;
my @cmd_pipe;
my @unsafe_cmd;
my $compressed = undef;
my $large_output;
my $stream_options = $cmd_pipe_in[0]->{stream_options} // {};
my @filter_stderr;
my $fatal_stderr;
my $has_rsh;
$cmd_pipe_in[0]->{stream_source} = 1;
$cmd_pipe_in[-1]->{stream_sink} = 1;
foreach my $href (@cmd_pipe_in)
{
die if(defined($href->{cmd_text}));
push @filter_stderr, ((ref($href->{filter_stderr}) eq "ARRAY") ? @{$href->{filter_stderr}} : $href->{filter_stderr}) if($href->{filter_stderr});
$fatal_stderr = $href->{fatal_stderr} if($href->{fatal_stderr});
$destructive = 1 unless($href->{non_destructive});
$has_rsh = 1 if($href->{rsh});
$large_output = 1 if($href->{large_output});
if($href->{redirect_to_file}) {
die unless($href->{stream_sink});
$href->{cmd_text} = _safe_cmd([ '>', $href->{redirect_to_file} ], \@unsafe_cmd);
}
elsif($href->{compress_stdin}) {
# does nothing if already compressed correctly by stream_compress
if($compressed && ($compression{$compressed->{key}}->{format} ne $compression{$href->{compress_stdin}->{key}}->{format})) {
# re-compress with different algorithm
push @cmd_pipe, decompress_cmd_text($compressed);
$compressed = undef;
}
unless($compressed) {
push @cmd_pipe, compress_cmd_text($href->{compress_stdin});
$compressed = $href->{compress_stdin};
}
next;
}
elsif($href->{cmd}) {
$href->{cmd_text} = _safe_cmd($href->{cmd}, \@unsafe_cmd);
}
return undef unless(defined($href->{cmd_text}));
my @rsh_compress_in;
my @rsh_compress_out;
my @decompress_in;
# input stream compression: local, in front of rsh_cmd_pipe
if($href->{rsh} && $stream_options->{stream_compress} && (not $href->{stream_source})) {
if($compressed && ($compression{$compressed->{key}}->{format} ne $compression{$stream_options->{stream_compress}->{key}}->{format})) {
# re-compress with different algorithm, should be avoided!
push @rsh_compress_in, decompress_cmd_text($compressed);
$compressed = undef;
}
if(not $compressed) {
$compressed = $stream_options->{stream_compress};
push @rsh_compress_in, compress_cmd_text($compressed);
}
}
if($compressed && (not ($href->{compressed_ok}))) {
push @decompress_in, decompress_cmd_text($compressed);
$compressed = undef;
}
# output stream compression: remote, at end of rsh_cmd_pipe
if($href->{rsh} && $stream_options->{stream_compress} && (not $href->{stream_sink}) && (not $compressed)) {
$compressed = $stream_options->{stream_compress};
push @rsh_compress_out, compress_cmd_text($compressed);
}
if($href->{rsh}) {
# honor stream_buffer_remote, rate_limit_remote for stream source / sink
my @rsh_stream_buffer_in = $href->{stream_sink} ? stream_buffer_cmd_text($stream_options->{rsh_sink}) : ();
my @rsh_stream_buffer_out = $href->{stream_source} ? stream_buffer_cmd_text($stream_options->{rsh_source}) : ();
my @rsh_cmd_pipe = (
@decompress_in,
@rsh_stream_buffer_in,
$href,
@rsh_stream_buffer_out,
@rsh_compress_out,
);
@decompress_in = ();
# fixup redirect_to_file
if((scalar(@rsh_cmd_pipe) == 1) && ($rsh_cmd_pipe[0]->{redirect_to_file})) {
# NOTE: direct redirection in ssh command does not work: "ssh '> outfile'"
# we need to assemble: "ssh 'cat > outfile'"
unshift @rsh_cmd_pipe, { cmd_text => 'cat' };
}
my $rsh_text = _safe_cmd($href->{rsh}, \@unsafe_cmd);
return undef unless(defined($rsh_text));
$href->{cmd_text} = $rsh_text . ' ' . quoteshell(_piped_cmd_txt(\@rsh_cmd_pipe));
}
# local stream_buffer, rate_limit and show_progress in front of stream sink
my @stream_buffer_in = $href->{stream_sink} ? stream_buffer_cmd_text($stream_options->{local_sink}) : ();
push @cmd_pipe, (
@decompress_in, # empty if rsh
@stream_buffer_in,
@rsh_compress_in, # empty if not rsh
$href, # command or rsh_cmd_pipe
);
}
my $cmd = _piped_cmd_txt(\@cmd_pipe);
if(scalar(@unsafe_cmd)) {
ERROR "Unsafe command `$cmd`", map "Offending string: \"$_\"", @unsafe_cmd;
return undef;
}
if($dryrun && $destructive) {
DEBUG "### (dryrun) $cmd";
return [];
}
DEBUG "### $cmd";
# execute command
my ($pid, $out_fh, $err_fh, @stdout);
$err_fh = gensym;
if(eval_quiet { $pid = open3(undef, $out_fh, $err_fh, $cmd); }) {
chomp(@stdout = readline($out_fh));
chomp(@stderr = readline($err_fh));
waitpid($pid, 0);
if($do_trace) {
if($large_output) {
TRACE "Command output lines=" . scalar(@stdout) . " (large_output, not dumped)";
} else {
TRACE map("[stdout] $_", @stdout);
}
TRACE map("[stderr] $_", @stderr);
}
}
else {
ERROR "Command execution failed ($!): `$cmd`";
return undef;
}
# fatal errors
if($? == -1) {
ERROR "Command execution failed ($!): `$cmd`";
return undef;
}
elsif ($? & 127) {
my $signal = $? & 127;
ERROR "Command execution failed (child died with signal $signal): `$cmd`";
return undef;
}
my $exitcode = $? >> 8;
# call hooks: fatal_stderr, filter_stderr
if(($exitcode == 0) && $fatal_stderr) {
$exitcode = -1 if(grep &{$fatal_stderr}(), @stderr);
}
foreach my $filter_fn (@filter_stderr) {
@stderr = map { &{$filter_fn} ($exitcode); $_ // () } @stderr;
}
if($exitcode) {
unshift @stderr, "sh: $cmd";
if($has_rsh && ($exitcode == 255)) {
# SSH returns exit status 255 if an error occurred (including
# network errors, dns failures).
unshift @stderr, "SSH command failed (exitcode=$exitcode)";
} else {
unshift @stderr, "Command execution failed (exitcode=$exitcode)";
}
DEBUG @stderr;
return undef;