-
Notifications
You must be signed in to change notification settings - Fork 75
/
msrsync
executable file
·1796 lines (1469 loc) · 62.5 KB
/
msrsync
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/env python2
# -*- coding: utf-8 -*-
# Copyright 2017 Jean-Baptiste Denis <[email protected]>
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This file includes a copy of the BSD licensed options.py file from the bup project
# See https://github.com/bup/bup/blob/master/lib/bup/options.py
VERSION = '20170730'
"""
Simple program from a very specific need. I needed to transfer multiple
terabytes of data using rsync. I can use multiple rsync in parallel to
improve the throughput but i didn't want to think about what data each rsync
should transfer, that's why i wrote this program.
I'm targeting a single file self sufficient python 2.6 program. Why 2.6 ? Because RHEL6 and
derivated. So please be indulgent regarding the pyton code. But feel free to make suggestions
to improve it in ways that keep it compatible with python 2.6.
This script build files lists to feed rsync with. It builds files lists whose total
disk size is below a provided limit and whose total number is below a provided limit.
Inspired by the fpsync tool from the fpart project. You should have a look since fpsync
is much more powerful right now and has been used to move around terabytes
of data already. See https://github.com/martymac/fpart
"""
# TODO
# - handle remote-shell src or dest dir, like a normal rsync
# - verbose, debug, multiprocessing compliant output
DEFAULT_RSYNC_OPTIONS = "-aS --numeric-ids"
MSRSYNC_OPTSPEC = """
msrsync [options] [--rsync "rsync-options-string"] SRCDIR [SRCDIR2...] DESTDIR
msrsync --selftest
--
msrsync options:
p,processes= number of rsync processes to use [1]
f,files= limit buckets to <files> files number [1000]
s,size= limit partitions to BYTES size (1024 suffixes: K, M, G, T, P, E, Z, Y) [1G]
b,buckets= where to put the buckets files (default: auto temporary directory)
k,keep do not remove buckets directory at the end
j,show show bucket directory
P,progress show progress
stats show additional stats
d,dry-run do not run rsync processes
v,version print version
rsync options:
r,rsync= MUST be last option. rsync options as a quoted string ["%s"]. The "--from0 --files-from=... --quiet --verbose --stats --log-file=..." options will ALWAYS be added, no matter what. Be aware that this will affect all rsync *from/filter files if you want to use them. See rsync(1) manpage for details.
self-test options:
t,selftest run the integrated unit and functional tests
e,bench run benchmarks
g,benchshm run benchmarks in /dev/shm or the directory in $SHM environment variable
""" % DEFAULT_RSYNC_OPTIONS
RSYNC_EXE = None
EOPTION_PARSER = 97
EPYTHON_VERSION = 10
EBUCKET_DIR_NOEXIST = 11
EBUCKET_DIR_PERMS = 12
EBUCKET_DIR_OSERROR = 12
EBUCKET_FILE_CREATE = 13
EBIN_NOTFOUND = 14
ESRC_NOT_DIR = 15
ESRC_NO_ACCESS = 16
EDEST_NO_ACCESS = 17
EDEST_NOT_DIR = 18
ERSYNC_OPTIONS_CHECK = 19
ERSYNC_TOO_LONG = 20
ERSYNC_JOB = 21
ERSYNC_OK = 22
EDEST_IS_FILE = 23
EDEST_CREATE = 24
ENEED_ROOT = 25
EBENCH = 26
EMSRSYNC_INTERRUPTED = 27
TYPE_RSYNC = 0
TYPE_RSYNC_SENTINEL = 1
MSG_STDERR = 10
MSG_STDOUT = 11
MSG_PROGRESS = 12
# pylint: disable=wrong-import-position
import os
import sys
import platform
import datetime
import tempfile
import shutil
import gzip
import time
import multiprocessing
import traceback
import shlex
import subprocess
import threading
import itertools
import random
import unittest
import signal
import timeit
STDOUT_ENCODING = sys.stdout.encoding if None else 'utf8'
def _e(value):
# pylint: disable=invalid-name
"""
dirty helper
"""
if type(value) is unicode:
return value.encode(STDOUT_ENCODING)
else:
return value
# Use the built-in version of scandir/walk if possible, otherwise
# use the scandir module version
USING_SCANDIR = True
try:
if sys.version_info < (3, 5):
from scandir import walk
os.walk = walk
except ImportError:
USING_SCANDIR = False
from multiprocessing.managers import SyncManager
G_MESSAGES_QUEUE = None
# Copy and paste from bup/options.py
# I'm disabling some pylint warning here
# pylint: disable=bad-whitespace, bad-continuation, unused-variable, invalid-name, wrong-import-position
# pylint: disable=reimported, missing-docstring, too-few-public-methods, unused-argument
# pylint: disable=too-many-instance-attributes, old-style-class, too-many-locals, multiple-statements
# pylint: disable=protected-access, superfluous-parens, pointless-string-statement, too-many-branches
# pylint: disable=too-many-statements, broad-except
# Copyright 2010-2012 Avery Pennarun and options.py contributors.
# All rights reserved.
#
# (This license applies to this file but not necessarily the other files in
# this package.)
#
# 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 AVERY PENNARUN ``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 <COPYRIGHT HOLDER> OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
"""Command-line options parser.
With the help of an options spec string, easily parse command-line options.
An options spec is made up of two parts, separated by a line with two dashes.
The first part is the synopsis of the command and the second one specifies
options, one per line.
Each non-empty line in the synopsis gives a set of options that can be used
together.
Option flags must be at the begining of the line and multiple flags are
separated by commas. Usually, options have a short, one character flag, and a
longer one, but the short one can be omitted.
Long option flags are used as the option's key for the OptDict produced when
parsing options.
When the flag definition is ended with an equal sign, the option takes
one string as an argument, and that string will be converted to an
integer when possible. Otherwise, the option does not take an argument
and corresponds to a boolean flag that is true when the option is
given on the command line.
The option's description is found at the right of its flags definition, after
one or more spaces. The description ends at the end of the line. If the
description contains text enclosed in square brackets, the enclosed text will
be used as the option's default value.
Options can be put in different groups. Options in the same group must be on
consecutive lines. Groups are formed by inserting a line that begins with a
space. The text on that line will be output after an empty line.
"""
import sys, os, textwrap, getopt, re, struct
def _invert(v, invert): # pragma: no cover
if invert:
return not v
return v
def _remove_negative_kv(k, v): # pragma: no cover
if k.startswith('no-') or k.startswith('no_'):
return k[3:], not v
return k,v
class OptDict(object): # pragma: no cover
"""Dictionary that exposes keys as attributes.
Keys can be set or accessed with a "no-" or "no_" prefix to negate the
value.
"""
def __init__(self, aliases):
self._opts = {}
self._aliases = aliases
def _unalias(self, k):
k, reinvert = _remove_negative_kv(k, False)
k, invert = self._aliases[k]
return k, invert ^ reinvert
def __setitem__(self, k, v):
k, invert = self._unalias(k)
self._opts[k] = _invert(v, invert)
def __getitem__(self, k):
k, invert = self._unalias(k)
return _invert(self._opts[k], invert)
def __getattr__(self, k):
return self[k]
def _default_onabort(msg): # pragma: no cover
sys.exit(97)
def _intify(v): # pragma: no cover
try:
vv = int(v or '')
if str(vv) == v:
return vv
except ValueError:
pass
return v
def _atoi(v): # pragma: no cover
try:
return int(v or 0)
except ValueError:
return 0
def _tty_width(): # pragma: no cover
# modification from the msrsync project : if sys.stderr is xStringIO or something else...
if not hasattr(sys.stderr, "fileno"):
return _atoi(os.environ.get('WIDTH')) or 70
s = struct.pack("HHHH", 0, 0, 0, 0)
try:
import fcntl, termios
s = fcntl.ioctl(sys.stderr.fileno(), termios.TIOCGWINSZ, s)
except (IOError, ImportError):
return _atoi(os.environ.get('WIDTH')) or 70
(ysize,xsize,ypix,xpix) = struct.unpack('HHHH', s)
return xsize or 70
class Options: # pragma: no cover
"""Option parser.
When constructed, a string called an option spec must be given. It
specifies the synopsis and option flags and their description. For more
information about option specs, see the docstring at the top of this file.
Two optional arguments specify an alternative parsing function and an
alternative behaviour on abort (after having output the usage string).
By default, the parser function is getopt.gnu_getopt, and the abort
behaviour is to exit the program.
"""
def __init__(self, optspec, optfunc=getopt.gnu_getopt,
onabort=_default_onabort):
self.optspec = optspec
self._onabort = onabort
self.optfunc = optfunc
self._aliases = {}
self._shortopts = 'h?'
self._longopts = ['help', 'usage']
self._hasparms = {}
self._defaults = {}
self._usagestr = self._gen_usage() # this also parses the optspec
def _gen_usage(self):
out = []
lines = self.optspec.strip().split('\n')
lines.reverse()
first_syn = True
while lines:
l = lines.pop()
if l == '--': break
out.append('%s: %s\n' % (first_syn and 'usage' or ' or', l))
first_syn = False
out.append('\n')
last_was_option = False
while lines:
l = lines.pop()
if l.startswith(' '):
out.append('%s%s\n' % (last_was_option and '\n' or '',
l.lstrip()))
last_was_option = False
elif l:
(flags,extra) = (l + ' ').split(' ', 1)
extra = extra.strip()
if flags.endswith('='):
flags = flags[:-1]
has_parm = 1
else:
has_parm = 0
g = re.search(r'\[([^\]]*)\]$', extra)
if g:
defval = _intify(g.group(1))
else:
defval = None
flagl = flags.split(',')
flagl_nice = []
flag_main, invert_main = _remove_negative_kv(flagl[0], False)
self._defaults[flag_main] = _invert(defval, invert_main)
for _f in flagl:
f,invert = _remove_negative_kv(_f, 0)
self._aliases[f] = (flag_main, invert_main ^ invert)
self._hasparms[f] = has_parm
if f == '#':
self._shortopts += '0123456789'
flagl_nice.append('-#')
elif len(f) == 1:
self._shortopts += f + (has_parm and ':' or '')
flagl_nice.append('-' + f)
else:
f_nice = re.sub(r'\W', '_', f)
self._aliases[f_nice] = (flag_main,
invert_main ^ invert)
self._longopts.append(f + (has_parm and '=' or ''))
self._longopts.append('no-' + f)
flagl_nice.append('--' + _f)
flags_nice = ', '.join(flagl_nice)
if has_parm:
flags_nice += ' ...'
prefix = ' %-20s ' % flags_nice
argtext = '\n'.join(textwrap.wrap(extra, width=_tty_width(),
initial_indent=prefix,
subsequent_indent=' '*28))
out.append(argtext + '\n')
last_was_option = True
else:
out.append('\n')
last_was_option = False
return ''.join(out).rstrip() + '\n'
def usage(self, msg=""):
"""Print usage string to stderr and abort."""
sys.stderr.write(self._usagestr)
if msg:
sys.stderr.write(msg)
e = self._onabort and self._onabort(msg) or None
if e:
raise e
def fatal(self, msg):
"""Print an error message to stderr and abort with usage string."""
msg = '\nerror: %s\n' % msg
return self.usage(msg)
def parse(self, args):
"""Parse a list of arguments and return (options, flags, extra).
In the returned tuple, "options" is an OptDict with known options,
"flags" is a list of option flags that were used on the command-line,
and "extra" is a list of positional arguments.
"""
try:
(flags,extra) = self.optfunc(args, self._shortopts, self._longopts)
except getopt.GetoptError, e:
self.fatal(e)
opt = OptDict(aliases=self._aliases)
for k,v in self._defaults.iteritems():
opt[k] = v
for (k,v) in flags:
k = k.lstrip('-')
if k in ('h', '?', 'help', 'usage'):
self.usage()
if (self._aliases.get('#') and
k in ('0','1','2','3','4','5','6','7','8','9')):
v = int(k) # guaranteed to be exactly one digit
k, invert = self._aliases['#']
opt['#'] = v
else:
k, invert = opt._unalias(k)
if not self._hasparms[k]:
assert(v == '')
v = (opt._opts.get(k) or 0) + 1
else:
v = _intify(v)
opt[k] = _invert(v, invert)
return (opt,flags,extra)
# pylint: enable=bad-whitespace, bad-continuation, unused-variable, invalid-name
# pylint: enable=reimported, missing-docstring, too-few-public-methods, unused-argument
# pylint: enable=too-many-instance-attributes, old-style-class, too-many-locals, multiple-statements
# pylint: enable=protected-access, superfluous-parens, pointless-string-statement, too-many-branches
# pylint: enable=too-many-statements, broad-except
def print_message(message, output=MSG_STDOUT):
"""
Add message to the message queue
"""
G_MESSAGES_QUEUE.put({"type": output, "message": message})
def print_update(data):
"""
Print 'data' on the same line as before
"""
sys.stdout.write("\r\x1b[K"+data.__str__())
sys.stdout.flush()
class BucketError(RuntimeError):
"""
Exception for bucket related error
"""
pass
def _check_python_version():
"""
Stupid python version checker
"""
major, minor, _ = platform.python_version_tuple()
if major == 2 and minor < 6:
python26_release = datetime.datetime(2008, 10, 1)
now = datetime.datetime.now()
years = (now - python26_release).days / 365
sys.stderr.write(("You need python >= 2.6 to run this program (more than %d years old)." + os.linesep) % years)
sys.exit(EPYTHON_VERSION)
def get_human_size(num, power="B"):
"""
Stolen from the ps_mem.py project for nice size output :)
"""
powers = ["B", "K", "M", "G", "T", "P", "E", "Z", "Y"]
while num >= 1000: #4 digits
num /= 1024.0
power = powers[powers.index(power)+1]
return "%.1f %s" % (num, power)
def human_size(value):
"""
parse the provided human size (with multiples K, M, G, T, E, P, Z, Y)
and return bytes
"""
if value.isdigit():
return int(value)
if not value[:-1].isdigit():
return None
m2s = {'K': 1024, \
'M': 1024*1024, \
'G': 1024*1024*1024, \
'T': 1024*1024*1024*1024, \
'P': 1024*1024*1024*1024*1024, \
'E': 1024*1024*1024*1024*1024*1024, \
'Z': 1024*1024*1024*1024*1024*1024*1024, \
'Y': 1024*1024*1024*1024*1024*1024*1024*1024}
size = int(value[:-1])
multiple = value[-1]
if multiple not in m2s.keys():
return None
return size * m2s[multiple]
def crawl(path, relative=False):
"""
Simple generator around os.walk that will
yield (size, fullpath) tuple for each file or link
underneath path.
If relative is True, the path will be relative to path, without
any leading ./ or /. For exemple, crawl("/home/jbdenis/Code", relative=True)
will yield (42, "toto") for "/home/jbdenis/Code/toto" file
"""
def onerror(oserror):
"""
helper
"""
print_message("msrsync crawl: %s" % oserror, MSG_STDERR)
root_size = len(path) if relative else 0
for root, dirs, files in os.walk(path, onerror=onerror):
# we want empty dir to be listed in bucket
if len(dirs) == 0 and len(files) == 0:
rpath = root[root_size:]
try:
yield os.lstat(root).st_size, rpath
except OSError, err:
print_message("msrsync crawl: %s" % err, MSG_STDERR)
continue
dir_links = [d for d in dirs if os.path.islink(os.path.join(root, d))]
for name in itertools.chain(files, dir_links):
fullpath = os.path.join(root, name)
try:
size = os.lstat(fullpath).st_size
except OSError, err:
print_message("msrsync crawl: %s" % err, MSG_STDERR)
continue
rpath = fullpath[root_size:]
yield size, rpath
def buckets(path, filesnr, size):
"""
Split files underneath path in buckets less than <size> bytes in total
or containing <filesnr> files maximum.
"""
bucket_files_nr = 0
bucket_size = 0
bucket = list()
# if we've got a trailing slash in the path, we want
# to sync the content of the path. I
# if we don't have a trailing slash, we want to sync the path
# itself
# Example:
# os.path.split("/home/jbdenis/Code")[1] will return 'Code'
# os.path.split("/home/jbdenis/Code/")[1] will return ''
base = os.path.split(path)[1]
for fsize, rpath in crawl(path, relative=True):
bucket.append(os.path.join(base, rpath.lstrip(os.sep)))
bucket_files_nr += 1
bucket_size += fsize
if bucket_size >= size or bucket_files_nr >= filesnr:
yield (bucket_files_nr, bucket_size, bucket)
bucket_size = 0
bucket_files_nr = 0
bucket = list()
if bucket_files_nr > 0:
yield (bucket_files_nr, bucket_size, bucket)
def _valid_rsync_options(options, rsync_opts):
"""
Check for weird stuff in rsync options
"""
rsync_args = rsync_opts.split()
for opt in rsync_args:
if opt.startswith("--delete"):
options.fatal("Cannot use --delete option type with msrsync. It would lead to disaster :)")
def parse_cmdline(cmdline_argv):
"""
command line parsing of msrsync using bup/options.py
See https://github.com/bup/bup/blob/master/lib/bup/options.py
"""
# If I want to run this script on RHEL6 and derivatives without installing any dependencies
# except python and rsync, I can't rely on argparse which is only available in python >= 2.7
# standard library. I don't want to rely on the installation of python-argparse for python 2.6
options = Options(MSRSYNC_OPTSPEC)
# it looks soooo fragile, but it works for me here.
# this block extracts the provided rsync options if present
# it assumes thats the SRC... DEST arguments are at the end of the command line
# I cannot use options parser to parse --rsync since some msrsync use some options
# name already used by rsync. So I only parse the command line up to the --rsync token
# and ugly parse what I want. Any better idea ?
if "-r" in cmdline_argv:
idx = cmdline_argv.index("-r")
cmdline_argv[idx] = "--rsync"
if "--rsync" in cmdline_argv:
idx = cmdline_argv.index("--rsync")
# we parse the command line up to --rsync options marker
(opt, _, extra) = options.parse(cmdline_argv[1:idx])
if len(cmdline_argv[idx:]) < 4: # we should have, at least, something like --rsync "-avz --whatever" src dest
options.fatal('You must provide a source, a destination and eventually rsync options with --rsync')
opt.rsync = opt.r = cmdline_argv[idx+1] # pylint: disable=invalid-name, attribute-defined-outside-init
_valid_rsync_options(options, opt.rsync)
srcs, dest = cmdline_argv[idx+2:-1], cmdline_argv[-1]
else:
# no --rsync options marker on the command line.
(opt, _, extra) = options.parse(cmdline_argv[1:])
if opt.selftest or opt.bench or opt.benchshm or opt.version: # early exit
return opt, [], ""
opt.rsync = opt.r = DEFAULT_RSYNC_OPTIONS # pylint: disable=attribute-defined-outside-init
if not extra or len(extra) < 2:
options.fatal('You must provide a source and a destination')
srcs, dest = extra[:-1], extra[-1]
size = human_size(str(opt.size))
if not size:
options.fatal("'%s' does not look like a valid size value" % opt.size)
try:
# pylint: disable=attribute-defined-outside-init, invalid-name
opt.files = opt.f = int(opt.f)
except ValueError:
options.fatal("'%s' does not look like a valid files number value" % opt.f)
opt.size = opt.s = size # pylint: disable=invalid-name, attribute-defined-outside-init
opt.compress = False # pylint: disable=attribute-defined-outside-init
return opt, srcs, dest
def rmtree_onerror(func, path, exc_info):
"""
Error handler for shutil.rmtree.
"""
# pylint: disable=unused-argument
print >>sys.stderr, "Error removing", path
def write_bucket(filename, bucket, compress=False):
"""
Dump bucket filenames in a optionnaly compressed file
"""
try:
fileno, path = filename
if not compress:
with os.fdopen(fileno, 'wb') as bfile:
for entry in bucket:
bfile.write(entry + '\0')
else:
os.close(fileno)
with gzip.open(path, 'wb') as bfile:
for entry in bucket:
bfile.write(entry)
except IOError, err:
raise BucketError("Cannot write bucket file %s: %s" % (path, err))
def consume_queue(jobs_queue):
"""
Simple helper around a shared queue
"""
while True:
item = jobs_queue.get()
if item is StopIteration:
return
yield item
# stolen from Forest http://stackoverflow.com/questions/1191374/subprocess-with-timeout
def kill_proc(proc, timeout):
""" helper function for run """
timeout["value"] = True
try:
proc.kill()
except OSError:
pass
# stolen and adapted from Forest http://stackoverflow.com/questions/1191374/subprocess-with-timeout
def run(cmd, capture_stdout=False, capture_stderr=False, timeout_sec=sys.maxsize):
""" run function with a timeout """
try:
stdout_p = subprocess.PIPE if capture_stdout else None
stderr_p = subprocess.PIPE if capture_stderr else None
proc = subprocess.Popen(shlex.split(cmd), stdout=stdout_p, stderr=stderr_p)
timeout = {"value": False}
timer = threading.Timer(timeout_sec, kill_proc, [proc, timeout])
starttime = time.time()
timer.start()
stdout, stderr = proc.communicate()
if stdout is None:
stdout = ""
if stderr is None:
stderr = ""
timer.cancel()
elapsed = time.time() - starttime
except OSError, err:
return -1, "", "Cannot launch %s: %s" % (cmd, err), False, 0
except KeyboardInterrupt:
if vars().has_key('timer'):
timer.cancel()
if proc:
if proc.stdout:
proc.stdout.close()
if proc.stderr:
proc.stderr.close()
proc.terminate()
proc.wait()
return 666, "", "Interrupted", False, 0
return proc.returncode, stdout.decode("utf-8", "replace"), stderr.decode("utf-8", "replace"), timeout["value"], elapsed
# stolen from stackoverflow (http://stackoverflow.com/a/377028)
def which(program):
"""
Python implementation of the which command
"""
def is_exe(fpath):
""" helper """
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, _ = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
def _check_rsync_options(options):
"""
Build a command line given the rsync options string
and try to execute it on empty directory
"""
rsync_cmd = None
try:
src = tempfile.mkdtemp()
dst = tempfile.mkdtemp()
rsync_log_fd, rsync_log = tempfile.mkstemp()
rsync_cmd = "%s %s %s %s" % (RSYNC_EXE, options + ' --quiet --stats --verbose --from0 --log-file %s' % rsync_log, src + os.sep, dst)
ret, _, stderr, timeout, _ = run(rsync_cmd, timeout_sec=60) # this should not take more than one minute =)
if timeout:
print >>sys.stderr, '''Error during rsync options check command "%s": took more than 60 seconds !''' % rsync_cmd
sys.exit(ERSYNC_OPTIONS_CHECK)
elif ret != 0:
print >>sys.stderr, '''Error during rsync options check command "%s": %s''' % (rsync_cmd, 2*os.linesep + stderr)
sys.exit(ERSYNC_OPTIONS_CHECK)
except OSError, err:
if rsync_cmd:
print >>sys.stderr, '''Error during rsync options check command "%s": %s''' % (rsync_cmd, 2*os.linesep + err)
else:
print >>sys.stderr, '''Error during rsync options check ("%s"): %s''' % (options, 2*os.linesep + err)
sys.exit(ERSYNC_OPTIONS_CHECK)
finally:
try:
os.rmdir(src)
os.rmdir(dst)
os.close(rsync_log_fd)
os.remove(rsync_log)
except OSError:
pass
def run_rsync(files_from, rsync_opts, src, dest, timeout=3600*24*7):
"""
Perform rsync using the --files-from option
"""
# this looks very close to the _check_rsync_options function...
# except the error message
rsync_log = files_from + '.log'
rsync_cmd = '%s %s %s "%s" "%s"' % (RSYNC_EXE, rsync_opts, "--quiet --verbose --stats --from0 --files-from=%s --log-file %s" % (files_from, rsync_log), src, dest)
#rsync_cmd = "%s %s %s %s %s" % (RSYNC_EXE, rsync_opts, "--quiet --from0 --files-from=%s" % (files_from,), src, dest)
rsync_result = dict()
rsync_result["rcode"] = -1
rsync_result["msg"] = None
rsync_result["cmdline"] = rsync_cmd
rsync_result["log"] = rsync_log
try:
ret, _, _, timeout, elapsed = run(rsync_cmd, timeout_sec=timeout)
rsync_result["rcode"] = ret
rsync_result["elapsed"] = elapsed
if timeout:
rsync_result["errcode"] = ERSYNC_TOO_LONG
elif ret != 0:
rsync_result["errcode"] = ERSYNC_JOB
except OSError, err:
rsync_result["errcode"] = ERSYNC_JOB
rsync_result["msg"] = str(err)
return rsync_result
def rsync_worker(jobs_queue, monitor_queue, options, dest):
"""
The queue will contains filenames of file to handle by individual rsync processes
"""
try:
for src, files_from, bucket_files_nr, bucket_size in consume_queue(jobs_queue):
if not options.dry_run:
rsync_result = run_rsync(files_from, options.rsync, src, dest)
else:
rsync_result = dict(rcode=0, elapsed=0, errcode=0, msg='')
rsync_mon_result = {"type": TYPE_RSYNC, "rsync_result": rsync_result, "size": bucket_size, "files_nr": bucket_files_nr, "jq_size": jobs_queue.qsize()}
monitor_queue.put(rsync_mon_result)
except (KeyboardInterrupt, SystemExit):
pass
finally:
jobs_queue.put(StopIteration)
# we insert a sentinel value to inform the monitor this process fnished
monitor_queue.put({"type": TYPE_RSYNC_SENTINEL, "pid": os.getpid()})
def handle_rsync_error_result(rsync_result):
""""
Helper
"""
msg = ''
if rsync_result["msg"] is not None:
msg = rsync_result["msg"]
if rsync_result["errcode"] == ERSYNC_TOO_LONG:
print_message(("rsync command took too long and has been killed (see '%s' rsync log file): %s\n" + rsync_result["cmdline"]) % (rsync_result["log"], msg), MSG_STDERR)
elif rsync_result["errcode"] == ERSYNC_JOB:
print_message(("errors during rsync command (see '%s' rsync log file): %s\n" + rsync_result["cmdline"]) % (rsync_result["log"], msg), MSG_STDERR)
else:
print_message("unknown rsync_result status: %s" % rsync_result, MSG_STDERR)
def rsync_monitor_worker(monitor_queue, nb_rsync_processes, total_size, total_files_nr, crawl_time, total_time, options):
"""
The monitor queue contains messages from the rsync workers
"""
current_size = 0
current_files_nr = 0
current_elapsed = 0
rsync_runtime = 0
rsync_workers_stops = 0
buckets_nr = 0
rsync_errors = 0
entries_per_second = 0
bytes_per_second = 0
try:
start = timeit.default_timer()
for result in consume_queue(monitor_queue):
if result["type"] == TYPE_RSYNC_SENTINEL:
# not needed, but we keep it for now
rsync_workers_stops += 1
continue
if result["type"] != TYPE_RSYNC:
print_message("rsync_monitor_worker process received an incompatile type message: %s" % result, MSG_STDERR)
continue
rsync_result = result["rsync_result"]
if rsync_result["rcode"] != 0:
rsync_errors += 1
handle_rsync_error_result(rsync_result)
continue
buckets_nr += 1
current_size += result["size"]
current_files_nr += result["files_nr"]
rsync_runtime += result["rsync_result"]["elapsed"]
current_elapsed = timeit.default_timer() - start
if current_elapsed > 0:
bytes_per_second = current_size / current_elapsed
else:
bytes_per_second = 0
if current_elapsed > 0:
entries_per_second = current_files_nr / current_elapsed
else:
entries_per_second = 0
if options.progress:
print_message("[%d/%d entries] [%s/%s transferred] [%d entries/s] [%s/s bw] [monq %d] [jq %d]" % \
(current_files_nr,\
total_files_nr.value,\
get_human_size(current_size),\
get_human_size(total_size.value),\
entries_per_second,\
get_human_size(bytes_per_second),\
monitor_queue.qsize(),\
result["jq_size"]),\
MSG_PROGRESS)
if rsync_errors > 0:
print_message("\nmsrsync error: somes files/attr were not transferred (see previous errors)", MSG_STDERR)
stats = dict()
stats["errors"] = rsync_errors
stats["total_size"] = total_size.value
stats["total_entries"] = total_files_nr.value
stats["buckets_nr"] = buckets_nr
stats["bytes_per_second"] = bytes_per_second
stats["entries_per_second"] = entries_per_second
stats["rsync_workers"] = nb_rsync_processes
stats["rsync_runtime"] = rsync_runtime
stats["crawl_time"] = crawl_time.value
stats["total_time"] = total_time.value
monitor_queue.put(stats)
except (KeyboardInterrupt, SystemExit):
pass
def messages_worker(options):
"""
This queue will contains messages to be print of the screen
"""
last_msg_type = cur_msg_type = None
try:
for result in consume_queue(G_MESSAGES_QUEUE):
if last_msg_type == MSG_PROGRESS:
newline = os.linesep
else:
newline = ''
cur_msg_type = result["type"]
if cur_msg_type == MSG_PROGRESS:
print_update(result["message"])
elif cur_msg_type == MSG_STDOUT:
print >>sys.stdout, _e(newline + result["message"])
elif cur_msg_type == MSG_STDERR:
print >>sys.stderr, _e(newline + result["message"])
else:
print >>sys.stderr, _e(newline + "Unknown message type '%s': %s" % (cur_msg_type, result))
last_msg_type = cur_msg_type
except (KeyboardInterrupt, SystemExit):
pass
finally:
if last_msg_type == MSG_PROGRESS:
print >>sys.stdout, ''
def start_rsync_workers(jobs_queue, monitor_queue, options, dest):
"""
Helper to start rsync processes
"""
processes = []
for _ in xrange(options.processes):
processes.append(multiprocessing.Process(target=rsync_worker, args=(jobs_queue, monitor_queue, options, dest)))
processes[-1].start()
return processes
def start_rsync_monitor_worker(monitor_queue, nb_rsync_processes, total_size, total_files_nr, crawl_time, total_time, options):
"""
Helper to start rsync monitor process
"""
proc = multiprocessing.Process(target=rsync_monitor_worker, args=(monitor_queue, nb_rsync_processes, total_size, total_files_nr, crawl_time, total_time, options))
proc.start()
return proc
def start_messages_worker(options):
"""
Helper to start messages process
"""
proc = multiprocessing.Process(target=messages_worker, args=(options,))
proc.start()