-
Notifications
You must be signed in to change notification settings - Fork 40
/
fpsync
executable file
·1984 lines (1812 loc) · 68.6 KB
/
fpsync
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/sh
# Copyright (c) 2014-2024 Ganael LAPLANCHE <[email protected]>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
# This script is a simple wrapper showing how fpart can be used to migrate data.
# It uses fpart and a copy tool to spawn multiple instances to migrate data from
# src_dir/ to dst_url/. Jobs can execute either locally or over SSH.
FPSYNC_VERSION="1.6.1"
########## Default values for options
# External tool used to copy files
OPT_TOOL_NAME="rsync"
# External tool path
OPT_TOOL_PATH=""
# Number of sync jobs to run in parallel ("workers", -n)
OPT_JOBS=2
# Same, but autodetected
#OPT_JOBS=$(sysctl -n hw.ncpu) # On FreeBSD
#OPT_JOBS=$(nproc) # On Linux
# Maximum files or directories per sync job (-f)
OPT_FPMAXPARTFILES="2000"
# Maximum bytes per sync job (-s)
OPT_FPMAXPARTSIZE="$((4 * 1024 * 1024 * 1024))" # 4 GB
# Work on a per-directory basis (disabled by default)
OPT_DIRSONLY=""
# Pack erroneous dirs apart and enable recursive rsync
OPT_AGGRESSIVE=""
# SSH workers (execute jobs locally if not defined, -w)
OPT_WRKRS=""
# Shared dir (must be shared amongst all workers, -d)
OPT_SHDIR=""
# Temporary dir (local, used for queue management, -t)
OPT_TMPDIR="/tmp/fpsync"
# E-mail report option (-M)
OPT_MAIL=""
# Prepare mode (-p)
OPT_PREPARERUN=""
# List runs (-l)
OPT_LISTRUNS=""
# Run ID for resume mode (-r)
OPT_RUNID=""
# Replay mode (-R)
OPT_REPLAYRUN=""
# Archive run (-a)
OPT_ARCHIVERUN=""
# Delete run (-D)
OPT_DELETERUN=""
# User-settable tool options (-o)
OPT_TOOL=""
# Fpart options (-O)
OPT_FPART="-x|.zfs|-x|.snapshot*|-x|.ckpt"
# Sudo mode (-S)
OPT_SUDO=""
# Verbose mode (-v)
OPT_VERBOSE="0"
# Source directory
OPT_SRCDIR=""
# Destination directory
OPT_DSTURL=""
########## Internal variables (cannot be set through CLI yet)
# Force color usage (even if stdout and stderr are *not* associated with a terminal)
OPT_FORCECOLORS=""
# POSIX-compliant shell used within generated jobs. It must exist locally
# and remotely (when using workers), as well as support '-c' (commands) and
# '-s' (stdin) options.
# That option may be used to work-around missing 'pipefail' option from '/bin/sh'
# on certain systems (e.g. Debian)
OPT_JOBSSHELL="/bin/sh"
#OPT_JOBSSHELL="/bin/bash"
########## Various functions
#set -o errexit
#set -o nounset
LC_ALL=C
# Our color constants
# See: https://en.wikipedia.org/wiki/ANSI_escape_code
COLOR_BLUE=$(tput setaf 4)
COLOR_GREEN=$(tput setaf 2)
COLOR_ORANGE=$(tput setaf 3)
COLOR_RED=$(tput setaf 1)
COLOR_WHITE=$(tput setaf 7)
COLOR_STOP=$(tput sgr0)
# Disable 'pipefail' option if not supported
QUIRK_PIPEFAIL='set -o pipefail'
${OPT_JOBSSHELL} -c "${QUIRK_PIPEFAIL}" 2>/dev/null || \
QUIRK_PIPEFAIL=':'
# Print help
usage () {
cat << EOF
fpsync v${FPSYNC_VERSION} - Sync directories in parallel using fpart
Copyright (c) 2014-2024 Ganael LAPLANCHE <[email protected]>
WWW: http://contribs.martymac.org
Usage: $0 [-p] [OPTIONS...] src_dir/ dst_url/
$0 -l
$0 -r runid [-R] [OPTIONS...]
$0 -a runid
$0 -D runid
COMMON OPTIONS:
-t /dir/ set fpsync temp dir to </dir/> (absolute path)
-d /dir/ set fpsync shared dir to </dir/> (absolute path)
This option is mandatory when using SSH workers.
-M mailaddr send an e-mail to mailaddr after a run. Multiple
-space-separated- addresses can be specified.
-v verbose mode (default: quiet)
This option can be be specified several times to
increase verbosity level.
-h this help
SYNCHRONIZATION OPTIONS:
-m tool external copy tool to use: $(tool_print_supported)
(default: 'rsync')
-T path absolute path of copy tool (default: guessed)
-f y transfer at most <y> files or directories per sync job
-s z transfer at most <z> bytes per sync job
-E work on a per-directory basis ('rsync' tool only)
(WARNING!!! Enables rsync(1)'s --delete option!)
Specify twice to enable "aggressive" mode that will isolate
erroneous directories and enable recursive synchronization for
them ('rsync' tool only)
-o options override default copy tool options with <options>
See fpsync(1) for more details.
-O options override default fpart options with pipe-separated <options>
See fpsync(1) for more details.
-S use sudo for filesystem crawling and synchronizations
src_dir/ source directory (absolute path)
dst_url/ destination directory (or URL, when using 'rsync' tool)
JOB HANDLING AND DISPATCHING OPTIONS:
-n x start <x> concurrent sync jobs per run
-w wrks space-separated list of SSH workers
e.g.: -w 'login@host1 login@host2 login@host3'
or: -w 'login@host1' -w 'login@host2' -w 'login@host3'
Jobs are executed locally if not specified (default).
RUN HANDLING OPTIONS:
-p prepare mode: prepare target(s) and create a resumable
run by crawling filesystem but do not actually start
synchronization jobs.
-l list previous runs and their status.
-r runid resume run <runid>
(options -m, -T, -f, -s, -E, -o, -O, -S, /src_dir/ and
/dst_url/ are ignored when resuming a previous run)
-R replay mode (needs option -r): re-synchronize all
partitions from run <runid> instead of working on
remaining ones only.
-a runid archive run <runid> to temp dir
-D runid delete run <runid>
See fpsync(1) for more details.
EOF
}
# Print a message to stdout and exit with normal exit code
end_ok () {
[ -n "$1" ] && echo "$1"
exit 0
}
# Print a message to stderr and exit with error code 1
end_die () {
[ -n "$1" ] && echo "$1" 1>&2
exit 1
}
# Print (to stdout) and log a message
# $1 = level (0 = quiet, 1 = verbose, >=2 more verbose)
# $2 = message to log
# $3 = color
echo_log () {
local _log_ts=$(date '+%s')
local _color_start=''
local _color_stop=''
# Prepare color
if { [ -t 1 ] && [ -t 2 ] ;} || [ -n "${OPT_FORCECOLORS}" ]
then
case "$3" in
"blue")
_color_start="${COLOR_BLUE}"
_color_stop="${COLOR_STOP}"
;;
"green")
_color_start="${COLOR_GREEN}"
_color_stop="${COLOR_STOP}"
;;
"orange")
_color_start="${COLOR_ORANGE}"
_color_stop="${COLOR_STOP}"
;;
"red")
_color_start="${COLOR_RED}"
_color_stop="${COLOR_STOP}"
;;
"white")
_color_start="${COLOR_WHITE}"
_color_stop="${COLOR_STOP}"
;;
esac
fi
is_num "$1" && [ ${OPT_VERBOSE} -ge $1 ] && [ -n "$2" ] && \
printf '%s\n' "${_log_ts} ${_color_start}$2${_color_stop}"
[ -n "$2" ] && \
echo "${_log_ts} $2" >> "${FPSYNC_LOGFILE}"
}
# Check if $1 is an absolute path
is_abs_path() {
echo "$1" | grep -qE '^/'
}
# Check if $1 is a valid rsync URL
# Cf. rsync(1) :
# SSH: [USER@]HOST:DEST
# Rsync: [USER@]HOST::DEST
# Rsync: rsync://[USER@]HOST[:PORT]/DEST
# Simplified as: "anything but slash" followed by at least one ":"
is_remote_path() {
echo "$1" | grep -qE '^[^/]+:'
}
# Check if $1 is a number
is_num () {
echo "$1" | grep -qE '^[0-9]+$'
}
# Check if $1 is an acceptable size argument
# - must be greater than 0
# - may contain 'kKmMgGtTpP' suffix
is_size () {
echo "$1" | grep -qE '^0*[1-9][0-9]*[kKmMgGtTpP]?$'
}
# Check if $1 contains (at least) a valid e-mail address
is_mailaddr () {
echo "$1" | grep -qE '^[a-zA-Z0-9+._-]+@[a-zA-Z0-9-]+\.'
}
# Check if $1 is a valid run ID
is_runid () {
echo "$1" | grep -qE '^[0-9]+-[0-9]+$'
}
########## Results handling
# Get files from specified run's logdir, by extension
# $1 = run ID
# $2 = file extension
run_logs_list_by_ext () {
[ -n "$1" ] && [ -n "$2" ] && \
find "${FPSYNC_LOGDIR_BASE}/${1}/" -type f -name "*.${2}" ! -size 0 2>/dev/null
}
# Check if file $1 exists and contains something
# $1 = file path
file_is_not_empty () {
[ -s "$1" ]
}
# Return contents of .ret file $1
# $1 = .ret file path
retfile_get_code () {
cat "$1" 2>/dev/null
}
# Check if .ret file $1 exists and contains a non-error return code
# $1 = .ret file path
retfile_is_success () {
grep -q '^0$' "$1" 2>/dev/null
}
# Check if .ret file $1 exists and contains an error return code
# $1 = .ret file path
retfile_is_error () {
grep -q -v '^0$' "$1" 2>/dev/null
}
# Return corresponding .stderr files from .ret file list
# Only non-empty log files are returned
logfiles_filter_ret_to_stderr () {
while read _line
do
case "${_line}" in
*.ret)
file_is_not_empty "${_line%.ret}.stderr" && \
echo "${_line%.ret}.stderr"
;;
esac
done
}
# Return .ret files containing an error return code from .ret file list
logfiles_filter_ret_with_errors () {
while read _line
do
case "${_line}" in
*.ret)
retfile_is_error "${_line}" && \
echo "${_line}"
;;
esac
done
}
# Return .stderr files with no error associated
# Those logs may contain interesting additional warnings
logfiles_filter_stderr_without_ret () {
while read _line
do
case "${_line}" in
*.stderr)
retfile_is_error "${_line%.stderr}.ret" || \
echo "${_line}"
;;
esac
done
}
########## Tool handling
# Chek if a tool is supported
# $1 = tool name
tool_is_supported () {
echo "$1" | grep -qE '^(rsync|cpio|pax|tar|tarify)$'
}
# Chek if TAR_BIN is GNU tar
# TAR_BIN must be initialized
tar_is_GNU_tar () {
[ -n "${TAR_BIN}" ] &&
"${TAR_BIN}" --version 2>/dev/null | head -n 1 | grep -q 'GNU tar'
}
# Print supported tools in a friendly manner
tool_print_supported () {
echo "'rsync', 'cpio', 'pax', 'tar' or 'tarify'"
}
# Check if a tool supports a URL as sync target
# $1 = tool name
tool_supports_urls () {
echo "$1" | grep -q '^rsync$'
}
# Check if a tool supports directory-only mode
# (requires the ability to sync a single-level directory tree)
# $1 = tool name
tool_supports_dirsonly () {
echo "$1" | grep -q '^rsync$'
}
# Check if a tool supports aggressive mode
# (requires the ability to sync recursively)
# $1 = tool name
tool_supports_aggressive () {
echo "$1" | grep -q '^rsync$'
}
# Get default tool-related options
# $1 = tool name
tool_get_base_opts () {
[ "$1" = "rsync" ] &&
printf '%s\n' '-q -lptgoD --numeric-ids'
}
# Get mode-specific complementary tool-related options
# (main call or left part of a pipeline)
# $1 = tool name
# $2 = dirs only mode (if string not empty)
tool_get_tool_mode_opts () {
if [ -z "$2" ]
then
# File-based mode: recursion is usually disabled here
# as we are working with leaf elements only
case "$1" in
"rsync")
# Non-recursive (more exactly: single-depth) rsync(1)
printf '%s\n' '-d'
;;
"cpio")
# Passthrough mode, create directories, preserve modification time
printf '%s\n' '-pdm'
;;
"pax")
# Read/Write mode, do not copy directories recursively, preserve everything
printf '%s\n' '-r -w -d -p e'
;;
"tar"|"tarify")
printf '%s\n' '--no-recursion'
;;
*)
;;
esac
else
# Dirs-only mode
case "$1" in
"rsync")
# Single-depth rsync(1) + deletion
# Postpone deletion to limit impacts of a user interruption
# XXX Aggressive mode can set option -r, which takes precedence
# over -d (in fact, aggressive mode *depends* on having option -r
# overriding -d)
printf '%s\n' '-d --relative --delete --delete-after'
;;
*)
;;
esac
fi
}
# Get mode-specific complementary tool-related options
# (right part of a pipeline), if any)
# $1 = tool name
# $2 = dirs only mode (if string not empty)
tool_get_tool_mode_opts_2 () {
if [ -z "$2" ]
then
# File-based mode: recursion is usually disabled here
# as we are working with leaf elements only
case "$1" in
"tar")
# GNU Tar needs --delay-directory-restore during extraction.
if tar_is_GNU_tar
then
printf '%s\n' '--delay-directory-restore'
fi
;;
*)
;;
esac
fi
}
# Get recursive option for specified tool
# $1 = tool name
tool_get_tool_mode_opts_recursive () {
[ "$1" = "rsync" ] &&
printf '%s\n' '-r'
}
# Get file list separator option for fpart
# $1 = tool name
tool_get_fpart_separator_opt () {
case "$1" in
"pax")
printf '%s\n' ''
;;
*)
# Every other tool supports a null-separated list of files
printf '%s\n' '-0'
;;
esac
}
# Get mode-specific fpart options
# $1 = tool name
# $2 = dirs only mode (if string not empty)
# $3 = aggressive mode (if string not empty)
tool_get_fpart_mode_opts () {
if [ -z "$2" ]
then
# File-based mode
case "$1" in
"rsync")
printf '%s\n' '-zz'
;;
"cpio"|"pax"|"tar"|"tarify")
# We want empty directory entries with those tools
# and fix parent dirs' timestamps with option -P
# to re-apply correct metadata
printf '%s\n' '-zzzP'
;;
*)
;;
esac
else
# Dirs-only mode
case "$1" in
"rsync")
if [ -z "$3" ]
then
# Regular mode
#
# We do *not* want fpart option -zz in regular dirs-only mode
# because unreadable directories will be created when sync'ing
# the parent
printf '%s\n' '-E'
else
# Aggressive mode
#
# Erroneous dirs are -from fpart's point of view-, mostly leaf
# dirs (no subdirs should have been packed before, except
# maybe in case of partially-read directories containing
# subdirs). Pack erroneous dirs separately and enable recursive
# rsync for them to try to overcome transcient errors such as
# Linux SMB client deferring opendir() to support compound SMB
# requests. See: https://github.com/martymac/fpart/pull/37
printf '%s\n' '-E|-zz|-Z'
fi
;;
*)
;;
esac
fi
}
# Init tool-specific fpart hooks (black magic is here !)
# $1 = tool name
# $2 = aggressive mode (if string not empty)
# XXX That function modifies a global variable to avoid too many escape
# characters when returning values through stdout
tool_init_fpart_job_command () {
case "$1" in
"rsync")
if [ -z "$2" ]
then
# Regular mode
FPART_JOBCOMMAND="${OPT_JOBSSHELL} -c '${SUDO} ${TOOL_BIN} ${OPT_TOOL} \
${TOOL_MODEOPTS} --files-from=\\\"\${FPART_PARTFILENAME}\\\" --from0 \
\\\"${OPT_SRCDIR}/\\\" \
\\\"${OPT_DSTURL}/\\\"' \
1>\"${FPSYNC_LOGDIR}/\${FPART_PARTNUMBER}.stdout\" \
2>\"${FPSYNC_LOGDIR}/\${FPART_PARTNUMBER}.stderr\""
else
# Aggressive mode: enable recursivity for erroneous partitions
# (i.e. where: (errno != 0) && (errno != EACCESS))
# Also, skip sync for errno==EACCESS as this is a legitimate error:
# unaccessible dirs will be re-created by parents, anyway
FPART_JOBCOMMAND="${OPT_JOBSSHELL} -c ' \
FPART_PARTERRNO=\\\"\${FPART_PARTERRNO}\\\"; \
TOOL_MODEOPTS_R=; \
if [ \\\${FPART_PARTERRNO} -ne 0 ]; \
then \
if [ \\\${FPART_PARTERRNO} -eq 13 ]; \
then \
exit 0; \
else \
TOOL_MODEOPTS_R=\\\"${TOOL_MODEOPTS_R}\\\"; \
fi; \
fi; \
${SUDO} ${TOOL_BIN} ${OPT_TOOL} ${TOOL_MODEOPTS} \
\\\${TOOL_MODEOPTS_R} --files-from=\\\"\${FPART_PARTFILENAME}\\\" --from0 \
\\\"${OPT_SRCDIR}/\\\" \
\\\"${OPT_DSTURL}/\\\"' \
1>\"${FPSYNC_LOGDIR}/\${FPART_PARTNUMBER}.stdout\" \
2>\"${FPSYNC_LOGDIR}/\${FPART_PARTNUMBER}.stderr\""
fi
;;
"cpio")
# XXX Warning: -0 and --quiet are non-standard
# (not supported on Solaris), see:
# http://pubs.opengroup.org/onlinepubs/7908799/xcu/cpio.html
# XXX Exec whole shell cmd as root, because we need to cwd first
FPART_JOBCOMMAND="${SUDO} ${OPT_JOBSSHELL} -c '${QUIRK_PIPEFAIL} ; \
cd \\\"${OPT_SRCDIR}/\\\" && \
cat \\\"\${FPART_PARTFILENAME}\\\" | \
${TOOL_BIN} ${OPT_TOOL} -0 --quiet ${TOOL_MODEOPTS} \
\\\"${OPT_DSTURL}/\\\"' \
1>\"${FPSYNC_LOGDIR}/\${FPART_PARTNUMBER}.stdout\" \
2>\"${FPSYNC_LOGDIR}/\${FPART_PARTNUMBER}.stderr\""
;;
"pax")
# https://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html
# XXX Exec whole shell cmd as root, because we need to cwd first
FPART_JOBCOMMAND="${SUDO} ${OPT_JOBSSHELL} -c '${QUIRK_PIPEFAIL} ; \
cd \\\"${OPT_SRCDIR}/\\\" && \
cat \\\"\${FPART_PARTFILENAME}\\\" | \
${TOOL_BIN} ${OPT_TOOL} ${TOOL_MODEOPTS} \
\\\"${OPT_DSTURL}/\\\"' \
1>\"${FPSYNC_LOGDIR}/\${FPART_PARTNUMBER}.stdout\" \
2>\"${FPSYNC_LOGDIR}/\${FPART_PARTNUMBER}.stderr\""
;;
"tar")
FPART_JOBCOMMAND="${OPT_JOBSSHELL} -c '${QUIRK_PIPEFAIL} ; \
${SUDO} ${TOOL_BIN} cf - \
${OPT_TOOL} -C \\\"${OPT_SRCDIR}/\\\" ${TOOL_MODEOPTS} \
--null -T \\\"\${FPART_PARTFILENAME}\\\" | \
${SUDO} ${TOOL_BIN} xpf - \
${OPT_TOOL} -C \\\"${OPT_DSTURL}/\\\" ${TOOL_MODEOPTS_2}' \
1>\"${FPSYNC_LOGDIR}/\${FPART_PARTNUMBER}.stdout\" \
2>\"${FPSYNC_LOGDIR}/\${FPART_PARTNUMBER}.stderr\""
;;
"tarify")
FPART_JOBCOMMAND="${OPT_JOBSSHELL} -c '${SUDO} ${TOOL_BIN} c \
-f \\\"${OPT_DSTURL}/\${FPART_PARTNUMBER}.tar\\\" \
${OPT_TOOL} -C \\\"${OPT_SRCDIR}/\\\" ${TOOL_MODEOPTS} \
--null -T \\\"\${FPART_PARTFILENAME}\\\"' \
1>\"${FPSYNC_LOGDIR}/\${FPART_PARTNUMBER}.stdout\" \
2>\"${FPSYNC_LOGDIR}/\${FPART_PARTNUMBER}.stderr\""
;;
*)
;;
esac
}
# Check if $2 contains invalid options regarding tool $1
# $1 = tool name
# $2 = tool options
tool_uses_forbidden_option () {
# For rsync, prevent usage of :
# --delete
# --recursive, -r
# -a (implies -r)
# and leave fpsync handle them internally.
[ "$1" = "rsync" ] && \
{ printf '%s\n' "$2" | grep -q -- '--delete' || \
printf '%s\n' "$2" | grep -q -- '--recursive' || \
printf '%s\n' "$2" | grep -qE -- '(^|[[:space:]])-[^[:space:]-]*r' || \
printf '%s\n' "$2" | grep -qE -- '(^|[[:space:]])-[^[:space:]-]*a' ;}
}
########## Options handling
# Parse user options and initialize OPT_* global variables
parse_opts () {
local opt OPTARG OPTIND
while getopts "m:T:n:f:s:Ew:d:t:M:plr:Ra:D:o:O:Svh" opt
do
case "${opt}" in
"m")
if tool_is_supported "${OPTARG}"
then
OPT_TOOL_NAME=${OPTARG}
else
end_die "Unsupported tool, please specify $(tool_print_supported)"
fi
;;
"T")
if is_abs_path "${OPTARG}"
then
OPT_TOOL_PATH="${OPTARG}"
else
end_die "Please supply an absolute path for tool path"
fi
;;
"n")
if is_num "${OPTARG}" && [ ${OPTARG} -ge 1 ]
then
OPT_JOBS=${OPTARG}
else
end_die "Option -n expects a numeric value >= 1"
fi
;;
"f")
if is_num "${OPTARG}" && [ ${OPTARG} -ge 0 ]
then
OPT_FPMAXPARTFILES=${OPTARG}
else
end_die "Option -f expects a numeric value >= 0"
fi
;;
"s")
if { is_num "${OPTARG}" && [ ${OPTARG} -ge 0 ] ;} || is_size "${OPTARG}"
then
OPT_FPMAXPARTSIZE=${OPTARG}
else
end_die "Option -s expects a numeric value >= 0"
fi
;;
"E")
if [ "${OPT_DIRSONLY}" = "yes" ]
then
OPT_AGGRESSIVE="yes"
fi
OPT_DIRSONLY="yes"
;;
"w")
if [ -n "${OPTARG}" ]
then
OPT_WRKRS="${OPT_WRKRS} ${OPTARG}"
else
end_die "Invalid workers list supplied"
fi
;;
"d")
if is_abs_path "${OPTARG}"
then
OPT_SHDIR="${OPTARG}"
else
end_die "Please supply an absolute path for shared dir"
fi
;;
"t")
if is_abs_path "${OPTARG}"
then
OPT_TMPDIR="${OPTARG}"
else
end_die "Please supply an absolute path for temp dir"
fi
;;
"M")
if [ -n "${OPTARG}" ] && is_mailaddr "${OPTARG}"
then
OPT_MAIL="${OPTARG}"
else
end_die "Please supply a valid e-mail address"
fi
;;
"p")
OPT_PREPARERUN="yes"
;;
"l")
OPT_LISTRUNS="yes"
;;
"r")
if [ -n "${OPTARG}" ] && is_runid "${OPTARG}"
then
OPT_RUNID="${OPTARG}"
else
end_die "Invalid run ID supplied"
fi
;;
"R")
OPT_REPLAYRUN="yes"
;;
"a")
if [ -n "${OPTARG}" ] && is_runid "${OPTARG}"
then
OPT_ARCHIVERUN="${OPTARG}"
else
end_die "Invalid run ID supplied"
fi
;;
"D")
if [ -n "${OPTARG}" ] && is_runid "${OPTARG}"
then
OPT_DELETERUN="${OPTARG}"
else
end_die "Invalid run ID supplied"
fi
;;
"o")
if [ -n "${OPTARG}" ]
then
OPT_TOOL="${OPTARG}"
else
end_die "Invalid tool options supplied"
fi
;;
"O")
if [ -n "${OPTARG}" ]
then
OPT_FPART="${OPTARG}"
else
end_die "Invalid fpart options supplied"
fi
;;
"S")
OPT_SUDO="yes"
;;
"v")
OPT_VERBOSE="$((${OPT_VERBOSE} + 1))"
;;
"h")
usage
end_ok
;;
*)
usage
end_die "Invalid option specified"
;;
esac
done
shift $((${OPTIND} - 1))
# Validate OPT_SHDIR (shared directory)
if [ -z "${OPT_WRKRS}" ]
then
# For local jobs, set shared directory to temporary directory
[ -z "${OPT_SHDIR}" ] && \
OPT_SHDIR="${OPT_TMPDIR}"
else
# For remote ones, specifying a shared directory is mandatory
[ -z "${OPT_SHDIR}" ] && \
end_die "Please supply a shared dir when specifying workers"
fi
# Run handling constraints
_err_msg="Please specify only a single option from: -p, -l -r, -a or -D"
[ -n "${OPT_PREPARERUN}" ] && \
{ [ -n "${OPT_LISTRUNS}" ] || \
[ -n "${OPT_RUNID}" ] || \
[ -n "${OPT_ARCHIVERUN}" ] || \
[ -n "${OPT_DELETERUN}" ] ;} && \
end_die "${_err_msg}"
[ -n "${OPT_LISTRUNS}" ] && \
{ [ -n "${OPT_RUNID}" ] || \
[ -n "${OPT_ARCHIVERUN}" ] || \
[ -n "${OPT_DELETERUN}" ] ;} && \
end_die "${_err_msg}"
[ -n "${OPT_RUNID}" ] && \
{ [ -n "${OPT_ARCHIVERUN}" ] || \
[ -n "${OPT_DELETERUN}" ] ;} && \
end_die "${_err_msg}"
[ -n "${OPT_ARCHIVERUN}" ] && \
[ -n "${OPT_DELETERUN}" ] && \
end_die "${_err_msg}"
_err_msg=
[ -n "${OPT_REPLAYRUN}" ] && [ -z "${OPT_RUNID}" ] && \
end_die "Replay (-R) option can only be used with resume (-r) option"
# Validate partitions' constraints
if is_num "${OPT_FPMAXPARTFILES}" && [ ${OPT_FPMAXPARTFILES} -eq 0 ] && \
is_num "${OPT_FPMAXPARTSIZE}" && [ ${OPT_FPMAXPARTSIZE} -eq 0 ]
then
end_die "Please specify a least a file (-f) or size (-s) limit for partitions"
fi
# Check for src_dir and dst_url presence and validity
if [ -z "${OPT_RUNID}" ] && [ -z "${OPT_LISTRUNS}" ] && \
[ -z "${OPT_ARCHIVERUN}" ] && [ -z "${OPT_DELETERUN}" ]
then
# Check src dir, must be an absolute path
if is_abs_path "$1"
then
OPT_SRCDIR="$1"
else
usage
end_die "Please supply an absolute path for src_dir/"
fi
# Check dst_url, must be either an absolute path or a URL
if is_abs_path "$2" || is_remote_path "$2"
then
is_remote_path "$2" && ! tool_supports_urls "${OPT_TOOL_NAME}" && \
end_die "URLs are not supported when using ${OPT_TOOL_NAME}"
OPT_DSTURL="$2"
else
usage
if tool_supports_urls "${OPT_TOOL_NAME}"
then
end_die "Please supply either an absolute path or a rsync URL for dst_url/"
else
end_die "Please supply an absolute path for dst_url/"
fi
fi
fi
# Handle tool-related options
if [ "${OPT_DIRSONLY}" = "yes" ] && ! tool_supports_dirsonly "${OPT_TOOL_NAME}"
then
end_die "Option -E is invalid when using ${OPT_TOOL_NAME} tool"
fi
if [ "${OPT_AGGRESSIVE}" = "yes" ] && ! tool_supports_aggressive "${OPT_TOOL_NAME}"
then
end_die "Aggressive mode is invalid when using ${OPT_TOOL_NAME} tool"
fi
if [ -z "${OPT_TOOL}" ]
then
OPT_TOOL=$(tool_get_base_opts "${OPT_TOOL_NAME}")
else
tool_uses_forbidden_option "${OPT_TOOL_NAME}" "${OPT_TOOL}" && \
end_die "Incompatible option(s) detected within toolopts (option -o)"
fi
}
########## Work-related functions (in-memory, running-jobs handling)
# Initialize WORK_FREEWORKERS by expanding OPT_WRKRS up to OPT_JOBS elements,
# assigning a fixed number of slots to each worker.
# Sanitize OPT_WRKRS if necessary.
work_list_free_workers_init () {
local _OPT_WRKRS_NUM=$(echo ${OPT_WRKRS} | awk '{print NF}')
if [ ${_OPT_WRKRS_NUM} -gt 0 ]
then
local _i=0
while [ ${_i} -lt ${OPT_JOBS} ]
do
local _OPT_WRKRS_IDX="$((${_i} % ${_OPT_WRKRS_NUM} + 1))"
WORK_FREEWORKERS="${WORK_FREEWORKERS} $(echo ${OPT_WRKRS} | awk '{print $'${_OPT_WRKRS_IDX}'}')"
_i=$((${_i} + 1))
done
else
OPT_WRKRS=""
WORK_FREEWORKERS="local"
fi
}
# Pick-up next worker
work_list_pick_next_free_worker () {
echo "${WORK_FREEWORKERS}" | awk '{print $1}'
}
# Remove next worker from list
work_list_trunc_next_free_worker () {
WORK_FREEWORKERS="$(echo ${WORK_FREEWORKERS} | sed -E 's/^[[:space:]]*[^[:space:]]+[[:space:]]*//')"
}
# Push a work to the list of currently-running ones
work_list_push () {
if [ -n "$1" ]
then
WORK_LIST="${WORK_LIST} $1"
WORK_NUM="$((${WORK_NUM} + 1))"
fi
}
# Rebuild the currently-running jobs' list by examining each process' state
work_list_refresh () {
local _WORK_LIST=""
local _WORK_NUM=0
local _JOB_PID=""
local _JOB_PART=""
local _JOB_HOST=""
for _JOB in ${WORK_LIST}
do
# Extract job info
_JOB_PID="${_JOB%%:*}"
_JOB_PART="${_JOB#*:}" ; _JOB_PART="${_JOB_PART%:*}"
_JOB_HOST="${_JOB##*:}"
if ps -p "${_JOB_PID}" 1>/dev/null 2>&1
then
# The process is still alive, keep it
_WORK_LIST="${_WORK_LIST} ${_JOB}"
_WORK_NUM="$((${_WORK_NUM} + 1))"
else
# Job exited (either naturally or by signal)
if [ -n "${OPT_WRKRS}" ]
then
WORK_FREEWORKERS="${WORK_FREEWORKERS} ${_JOB_HOST}"
fi
# Not finding a .ret file is abnormal
# Main job script (the one that generates the .ret file
# itself) must have been killed. We mark it as erroneous by
# simulating a SIGTERM with a return code of 143 (128 + SIGTERM).
# See: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_08_02
if ! file_is_not_empty "${FPSYNC_LOGDIR}/${_JOB_PART}.ret"
then
echo "143" 2>/dev/null >"${FPSYNC_LOGDIR}/${_JOB_PART}.ret" || \
end_die "Error writing to .ret file: ${FPSYNC_LOGDIR}/${_JOB_PART}.ret"
echo "Job killed (SIGTERM simulated by fpsync)" 2>/dev/null >>"${FPSYNC_LOGDIR}/${_JOB_PART}.stderr" || \
end_die "Error writing to .stderr file: ${FPSYNC_LOGDIR}/${_JOB_PART}.stderr"
fi
_retcode=$(retfile_get_code "${FPSYNC_LOGDIR}/${_JOB_PART}.ret")
is_num "${_retcode}" || \
end_die "Invalid return code fetched for job: ${_JOB_PART}"
if [ "${_retcode}" -le 128 ] && \
# XXX Workaround for rsync(1) returning 20 when killed
{ [ "${OPT_TOOL_NAME}" != "rsync" ] || [ "${_retcode}" -ne 20 ] ;}
then
# Job finished naturally, check return value
if retfile_is_success "${FPSYNC_LOGDIR}/${_JOB_PART}.ret"
then
echo_log "2" "<= [QMGR] Job ${_JOB_PART} (${_JOB}) exited (success)" "green"
else
echo_log "2" "<= [QMGR] Job ${_JOB_PART} (${_JOB}) exited (error: ${_retcode})" "red"
fi
# Update status counters
_run_done_jobs=$(( ${_run_done_jobs} + 1 ))
_run_done_files=$(( \
${_run_done_files} + $( \
job_files=0 ; \
. "${FPSYNC_PARTSTMPL}.${_JOB_PART}.meta" 2>/dev/null ; \
echo "${job_files}" \
) \
))
_run_done_size=$(( \
${_run_done_size} + $( \
job_size=0 ; \
. "${FPSYNC_PARTSTMPL}.${_JOB_PART}.meta" 2>/dev/null ; \
echo "${job_size}" \
) \
))