-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathplanb-objsync.py
executable file
·2104 lines (1810 loc) · 76.8 KB
/
planb-objsync.py
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 python3
import logging
import os
import re
import signal
import sys
import threading
import traceback
import warnings
from argparse import ArgumentParser
from collections import OrderedDict
from configparser import RawConfigParser, SectionProxy
from datetime import datetime, timezone
from functools import cached_property, lru_cache
from hashlib import md5
from tempfile import NamedTemporaryFile
from time import time
from unittest import TestCase
try:
from boto3 import client as S3Client
from botocore.client import Config as S3Config
except ImportError:
warnings.warn('No boto3? You probably need to {!r}'.format(
'apt-get install python3-boto3 --no-install-recommends'))
sys.exit(1)
else:
from botocore.exceptions import ClientError as S3ClientError
try:
from swiftclient import Connection as SwiftConnection
except ImportError:
warnings.warn('No swiftclient? You probably need to {!r}'.format(
'apt-get install python3-swiftclient --no-install-recommends'))
sys.exit(1)
else:
from swiftclient.exceptions import ClientException as SwiftClientError
# TODO: when stopping mid-add, we get lots of "ValueError: early abort"
# backtraces polluting the log; should do without error
SAMPLE_INIFILE = r"""
[acme_swift_v1_config]
; Use rclone(1) to see the containers: `rclone lsd acme_swift_v1_config:`
type = swift
user = NAMESPACE:USER
key = KEY
auth = https://AUTHSERVER/auth/v1.0
; You can use one or more 'planb_translate' or use 'planb_translate_<N>'
; to define filename translation rules. They may be needed to circumvent
; local filesystem limits (like not allowing trailing / in a filename).
; GUID-style (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) to "ID/GU/FULLGUID".
planb_translate_0 = document=
^([0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{8}([0-9a-f]{2})([0-9a-f]{2}))$=
\4/\3/\1
; BEWARE ^^ remove excess linefeeds and indentation from this example ^^
; Translate in the 'wsdl' container all paths that start with "YYYYMMDD"
; to "YYYY/MM/DD/"
planb_translate_1 = wsdl=^(\d{4})(\d{2})(\d{2})/=\1/\2/\3/
; Translate in all containers all paths (files) that end with a slash to %2F.
; (This will conflict with files actually having a %2F there, but that
; is not likely to happen.)
planb_translate_2 = *=/$=%2F
; You can use one or more 'planb_exclude' or use 'planb_exclude_<N>'
; to define download exclusion rules.
; Example: skip segments/* in the registry container.
planb_exclude_0 = registry=^segments/
; The location of the CA bundle to verify the server certificates.
; When set to "false" the certificate verification is disabled.
; Defaults to "true" and will use the client library default CA bundle.
;planb_ca_cert = /path/to/my-ca-bundle.crt
; The connect/read timeout (int/float)
; A single value is applied to both the connect and read timeout.
; The S3 client can set the connect and read timeout separately with
; comma separated values. The Swift client does not suport this and the
; connect timeout is used for both.
;planb_timeout = 60 ; 60s connect and read timeout (default)
;planb_timeout = 10, 30 ; 10s connect and 30s read timeout.
[acme_swift_v3_config]
type = swift
domain = USER_DOMAIN
user = USER
key = KEY
auth = https://AUTHSERVER/v3/
tenant = PROJECT
tenant_domain = PROJECT_DOMAIN
auth_version = 3
; Set this to always to skip autodetection of DLO segment support: not all DLO
; segments are stored in a separate <container>_segments container.
; (You may need to clear the planb-objsync.new cache after setting this.)
planb_container_has_segments = always
[acme_minio_s3_config]
type = s3
provider = Minio
access_key_id = USER
secret_access_key = SECRET_KEY
endpoint = https://MINIOSERVER
; The planb exclude/translate options apply to s3 storage too.
; planb_container_has_segments has no function on on s3 object storage.
"""
logging.basicConfig(
level=logging.INFO,
format=(
'%(asctime)s [planb-objsync:%(threadName)-10.10s] '
'[%(levelname)-3.3s] %(message)s'),
handlers=[logging.StreamHandler()])
log = logging.getLogger()
def _signal_handler(signo, _stack_frame):
global _MT_ABORT, _MT_HAS_THREADS
_MT_ABORT = signo
log.info('Got signal %d', signo)
if not _MT_HAS_THREADS:
# If we have no threads, we can abort immediately.
log.info('Killing self because of signal %d', signo)
sys.exit(128 + signo) # raises SystemExit()
_MT_ABORT = 0 # noqa -- aborting?
_MT_HAS_THREADS = False # do we have threads at all?
signal.signal(signal.SIGHUP, _signal_handler)
signal.signal(signal.SIGINT, _signal_handler)
signal.signal(signal.SIGTERM, _signal_handler)
signal.signal(signal.SIGQUIT, _signal_handler)
class PathExcluder:
"""
Excludes path from remote_path in listing.
"""
def __init__(self, container, exclude_rules):
assert '/' not in container, container
self.container = container
self.excludes = []
for exclude_rule in exclude_rules:
container_match, needle = exclude_rule.split('=', 1)
if container == container_match or container_match == '*':
self.excludes.append(re.compile(needle))
def __bool__(self):
return bool(self.excludes)
def __call__(self, remote_path):
for needle in self.excludes:
if needle.search(remote_path):
return True
return False
class PathTranslator:
"""
Translates path from remote_path to local_path.
When single_container=True, the container name is not added into the
local_path.
Test using:
planb_storage_destination=$(pwd)/data \
./planb-objsync -c planb-objsync.conf SECTION \
--test-path-translate CONTAINERNAME
(provide remote paths on stdin)
"""
def __init__(self, data_path, container, translations, single_container):
assert '/' not in container, container
assert isinstance(single_container, bool)
self.data_path = data_path
self.container = container
self.single_container = single_container
self.replacements = []
for translation_rule in translations:
container_match, needle, replacement = translation_rule.split('=')
if container == container_match or container_match == '*':
self.replacements.append((
re.compile(needle), replacement))
def __call__(self, remote_path):
for needle, replacement in self.replacements:
local_path = needle.sub(replacement, remote_path)
if local_path != remote_path:
break
else:
local_path = remote_path
# Single container: LOCAL_BASE + TRANSLATED_REMOTE_PATH
if self.single_container:
return os.path.join(self.data_path, local_path)
# Multiple containers: LOCAL_BASE + CONTAINER + TRANSLATED_REMOTE_PATH
return os.path.join(self.data_path, self.container, local_path)
class ConfigParserMultiValues(OrderedDict):
"""
Accept duplicate keys in the RawConfigParser.
"""
def __setitem__(self, key, value):
# The RawConfigParser does a second pass. First lists are passed.
# Secondly concatenated strings are passed.
assert isinstance(value, (
ConfigParserMultiValues, SectionProxy, list, str)), (
key, value, type(value))
# For the second pass, we could do an optional split by LF. But that
# makes it harder to notice when this breaks. Instead, just skip the
# str-setting.
if isinstance(value, str): # and '\n' in value:
# super().__setitem__(key, value.split('\n'))
return
if key in self and isinstance(value, list):
self[key].extend(value)
else:
super().__setitem__(key, value)
class SyncConfig:
def __init__(self, inifile, section):
self.read_inifile(inifile, section)
self.read_environment()
def read_inifile(self, inifile, section):
configparser = RawConfigParser(
strict=False, empty_lines_in_values=False,
dict_type=ConfigParserMultiValues)
configparser.read([inifile])
try:
config = configparser[section]
except KeyError:
raise ValueError(
'no section {!r} found in {!r}'.format(section, inifile))
self.read_planb_config(config)
self.sync_type = config.get('type', [None])[-1]
if self.sync_type == 's3':
self.read_s3_config(config)
elif self.sync_type == 'swift':
self.read_swift_config(config)
else:
raise ValueError(
f'Unsupported type {self.sync_type!r} in {section!r} of '
f'{inifile!r}')
def read_planb_config(self, config):
# Accept multiple planb_translate keys. But also accept
# planb_translate_<id> keys. If you use the rclone config tool,
# rewriting the file would destroy duplicate keys, so using a
# suffix is preferred.
self.planb_translations = []
for key in sorted(config.keys()):
if key == 'planb_translate' or key.startswith('planb_translate_'):
self.planb_translations.extend(config[key])
# Accept multiple planb_exclude keys. But also accept
# planb_exclude_<id> keys. See reasoning at planb_translate.
self.planb_excludes = []
for key in sorted(config.keys()):
if key == 'planb_exclude' or key.startswith('planb_exclude_'):
self.planb_excludes.extend(config[key])
# Sometimes segment autodetection can fail, resulting in:
# > Filesize mismatch for '...': 0 != 9515
# This is probably because the object has X-Object-Manifest and is a
# Dynamic Large Object (DLO).
self.all_containers_have_segments = (
config.get('planb_container_has_segments', [''])[-1] == 'always')
# CA bundle to verify server certificates.
# Defaults to true to enable verification and use the client CA bundle.
self.ca_cert = config.get('planb_ca_cert', ['true'])[-1]
if self.ca_cert.lower() in ('true', 'false'):
self.ca_cert = bool(self.ca_cert.lower() == 'true')
# Connect/read timeout.
# S3 defaults to 60 seconds while Swift waits forever.
# Adopt 60 seconds as the planb default.
timeouts = config.get('planb_timeout', ['60, 60'])[-1].split(',')
self.connect_timeout, self.read_timeout = (
float(timeouts[0]), float(timeouts[-1]))
def read_s3_config(self, config):
self.s3_access_key_id = config['access_key_id'][-1]
self.s3_secret_access_key = config['secret_access_key'][-1]
self.s3_endpoint = config['endpoint'][-1]
self.s3_verify = self.ca_cert
def read_swift_config(self, config):
self.swift_authver = config.get('auth_version', ['1'])[-1]
self.swift_auth = config['auth'][-1] # authurl
self.swift_user = config['user'][-1]
self.swift_key = config['key'][-1]
# auth_version v3:
self.swift_project = config.get('tenant', [None])[-1] # project
self.swift_pdomain = (
config.get('tenant_domain', [None])[-1]) # project-domain
self.swift_udomain = (
config.get('domain', [None])[-1]) # user-domain
if self.ca_cert in (True, False):
self.swift_insecure = bool(not self.ca_cert)
self.swift_cacert = None
else:
self.swift_insecure = False
self.swift_cacert = self.ca_cert
def read_environment(self):
# /tank/customer-friendly_name/data
storage = os.environ['planb_storage_destination']
# friendly_name = os.environ['planb_fileset_friendly_name']
# fileset_id = os.environ['planb_fileset_id']
if not storage.endswith('/data'):
raise ValueError(
'expected storage path to end in /data, got {!r}'.format(
storage))
if not os.path.exists(storage):
raise ValueError(
'data_path does not exist: {!r}'.format(storage))
self.data_path = storage
self.metadata_path = storage.rsplit('/', 1)[0]
assert self.metadata_path.startswith('/'), self.metadata_path
def get_excluder(self, container):
return PathExcluder(container, self.planb_excludes)
def get_translator(self, container, single_container):
return PathTranslator(
self.data_path, container, self.planb_translations,
single_container)
class SyncConfigPathTranslators(dict):
def __init__(self, config, single_container):
assert isinstance(single_container, bool)
super().__init__()
self._config = config
self._single_container = single_container
def get(self, *args, **kwargs):
raise NotImplementedError()
def __getitem__(self, container):
try:
translator = super().__getitem__(container)
except KeyError:
translator = self._config.get_translator(
container, single_container=self._single_container)
super().__setitem__(container, translator)
return translator
class Container(str):
# The OpenStack Swift canonical method for handling large objects,
# is using Dynamic Large Objects (DLO) or Static Large Objects
# (SLO).
#
# In both (DLO and SLO) cases, the CONTAINER file segments are
# uploaded to a separate container called CONTAINER_segments.
# When doing a listing over CONTAINER, the segmented files are
# reported as having 0 size. When that happens, we have to do a HEAD
# on those files to retrieve the actual concatenated file size.
#
# This boolean allows us to skip those expensive lookups for all
# containers X that do not have an X_segments helper container.
has_segments = False
class ObjectLine:
def __init__(self, obj, size, modified, path):
self.obj = obj
self.size = size
self.modified = modified
self.path = path
assert not self.path.startswith(('\\', '/', './', '../')), self.path
assert '/../' not in self.path, self.path # disallow harmful path
assert '/./' not in self.path, self.path # disallow awkward path
@classmethod
def from_s3_line(cls, obj):
# {'Key': 'string',
# 'LastModified': datetime(2015, 1, 1),
# 'ETag': 'string',
# 'ChecksumAlgorithm': [
# 'CRC32'|'CRC32C'|'SHA1'|'SHA256',
# ],
# 'Size': 123,
# 'StorageClass': 'STANDARD'|'REDUCED_REDUNDANCY'|...,
# 'Owner': {
# 'DisplayName': 'string',
# 'ID': 'string'
# },
# 'RestoreStatus': {
# 'IsRestoreInProgress': True|False,
# 'RestoreExpiryDate': datetime(2015, 1, 1)
# }}
return cls(
obj=obj, size=obj['Size'], path=obj['Key'],
modified=obj['LastModified'].strftime('%Y-%m-%dT%H:%M:%S.%f'))
@classmethod
def from_swift_line(cls, obj):
# {'bytes': 107713,
# 'last_modified': '2018-05-25T15:11:14.501890',
# 'hash': '89602749f508fc9820ef575a52cbfaba',
# 'name': '20170101/mr/administrative',
# 'content_type': 'text/xml'}]
assert len(obj['last_modified']) == 26, obj
assert obj['last_modified'][10] == 'T', obj
return cls(
obj=obj, size=obj['bytes'], modified=obj['last_modified'],
path=obj['name'])
class ObjectHeaders:
@staticmethod
def contentlength(headers):
size = headers.get('content-length')
assert size.isdigit(), headers
return int(size)
@staticmethod
def etag(headers):
"normalize_etag"
tag = headers.get('etag')
if tag and tag.startswith('"') and tag.endswith('"') and tag != '"':
tag = tag[1:-1]
return tag
@staticmethod
def xtimestamp(headers):
xtimestamp = headers.get('x-timestamp')
assert all(i in '0123456789.' for i in xtimestamp), headers
tm = datetime.utcfromtimestamp(float(xtimestamp))
return tm
class ListLine:
# >>> escaped_re.findall('containerx|file||name|0|1234\n')
# ['containerx', '|', 'file||name', '|', '0', '|', '1234\n']
escaped_re = re.compile(r'(?P<part>(?:[^|]|(?:[|][|]))+|[|])')
@classmethod
def from_object_head(cls, container, path, head_dict):
"""
{'server': 'nginx', 'date': 'Fri, 02 Jul 2021 13:04:35 GMT',
'content-type': 'image/jpg', 'content-length': '241190',
'etag': '7bc4ca634783b4c83cf506188cd7176b',
'x-object-meta-mtime': '1581604242',
'last-modified': 'Tue, 08 Jun 2021 07:03:34 GMT',
'x-timestamp': '1623135813.04310', 'accept-ranges': 'bytes',
'x-trans-id': 'txcxxx-xxx', 'x-openstack-request-id': 'txcxxx-xxx'}
"""
size = ObjectHeaders.contentlength(head_dict)
tm = ObjectHeaders.xtimestamp(head_dict)
tms = tm.strftime('%Y-%m-%dT%H:%M:%S.%f')
if container:
assert '|' not in container, (
'unescaping can only cope with pipe in path: {!r} + {!r}'
.format(container, path))
return cls('{}|{}|{}|{}\n'.format(
container, path.replace('|', '||'),
tms, size))
return cls('{}|{}|{}\n'.format(path.replace('|', '||'), tms, size))
def __init__(self, line):
# Line looks like: [container|]path|modified|size<LF>
# But path may contain double pipes.
if '||' not in line:
# Simple matching.
self.path, self._modified, self._size = line.rsplit('|', 2)
if '|' in self.path:
self.container, self.path = self.path.split('|', 1)
else:
self.container = None
assert '|' not in self.path, 'bad line: {!r}'.format(line)
else:
# Complicated regex matching. Path may include double pipes.
matches = self.escaped_re.findall(line)
assert ''.join(matches) == line, (line, matches)
if len(matches) == 7:
path = ''.join(matches[0:3]) # move pipes to path
self.container, path = path.split('|', 1)
self._modified = matches[4]
self._size = matches[6]
elif len(matches) == 5:
path = matches[0]
self.container = None
self._modified = matches[2]
self._size = matches[4]
else:
assert False, 'bad line: {!r}'.format(line)
self.path = path.replace('||', '|')
assert self.container is None or self.container, (
'bad container in line: {!r}'.format(line))
self.line = line
self.container_path = (self.container, self.path)
@property
def size(self):
# NOTE: _size has a trailing LF, but int() silently eats it for us.
return int(self._size)
@property
def modified(self):
# The time is zone agnostic, so let's assume UTC.
if not hasattr(self, '_modified_cache'):
dates, us = self._modified.split('.', 1)
dates = int(
datetime.strptime(dates, '%Y-%m-%dT%H:%M:%S')
.replace(tzinfo=timezone.utc).timestamp())
assert len(us) == 6
self._modified_cache = 1000000000 * dates + 1000 * int(us)
return self._modified_cache
def __eq__(self, other):
return (self.size == other.size
and self.container == other.container
and self.container_path == other.container_path
and self.path == other.path)
class SyncWorkerStatus:
"""
Status class. Is True if anything was wrong.
>>> s = SwiftSyncWorkerStatus()
>>> bool(s)
False
>>> s.badattr = 1
AttributeError
>>> s.config_errors += 1
>>> bool(s)
True
>>> sum([s, s])
<SwiftSyncWorkerStatus({config_errors: 2, failed_fetches: 0})>
"""
__slots__ = ('config_errors', 'failed_fetches', 'unhandled_errors')
def __init__(self):
for attr in self.__slots__:
setattr(self, attr, 0)
def __bool__(self):
return any(getattr(self, attr) for attr in self.__slots__)
def __int__(self):
return sum(getattr(self, attr) for attr in self.__slots__)
def __add__(self, other):
"Add, so we can sum() these"
new = self.__class__()
for attr in self.__slots__:
setattr(new, attr, getattr(self, attr) + getattr(other, attr))
return new
def __radd__(self, other):
"Reverse add, to make the sum() initial element work"
assert other == 0, ('expected [0 + SwiftSyncWorkerStatus()]', other)
return self.__add__(self.__class__())
def __str__(self):
return '{{{}}}'.format(', '.join(
'{}: {}'.format(attr, getattr(self, attr))
for attr in self.__slots__))
def __repr__(self):
return '<SwiftSyncWorkerStatus({})>'.format(str(self))
class BaseSyncClient:
def __init__(self, config, container=None):
self.config = config
self.container = container
@cached_property
def client(self):
return self.get_client()
def clone(self):
'''
Return a copy of the client that is safe to use in a new thread.
'''
return self.__class__(self.config, self.container)
def get_client(self):
'''
Return the client to interface with the object storage.
'''
raise NotImplementedError()
def get_containers(self):
'''
Return a list of container names in the object storage.
'''
raise NotImplementedError()
def get_container(self, name):
'''
Return an iterator for the object listing of the container.
'''
raise NotImplementedError()
def head_object(self, container, name):
'''
Return a dict with headers of the object in the container.
'''
raise NotImplementedError()
def get_object(self, container, name):
'''
Return a (dict, stream) with headers and object data of the object in
the container.
'''
raise NotImplementedError()
def is_valid_etag(self, etag):
'''
Validate the etag value for the client.
'''
return bool(
etag
and len(etag) == 32
and all(i in '0123456789abcdef' for i in etag))
class S3SyncClient(BaseSyncClient):
ClientError = S3ClientError
MAX_RESULTS = 1000 # AWS S3 default/max allowed.
def get_client(self):
config = S3Config(
connect_timeout=self.config.connect_timeout,
read_timeout=self.config.read_timeout)
return S3Client(
's3', aws_access_key_id=self.config.s3_access_key_id,
aws_secret_access_key=self.config.s3_secret_access_key,
endpoint_url=self.config.s3_endpoint, verify=self.config.s3_verify,
config=config)
@lru_cache
def get_containers(self):
if self.container:
return [Container(self.container)]
container_names = []
params = {}
# Note: ContinuationToken is the cursor for the next page and there is
# no NextContinuationToken.
# If the ContinuationToken is given is must be valid.
while params.get('ContinuationToken') != '':
response = self.client.list_buckets(
MaxBuckets=self.MAX_RESULTS, **params)
if 'Buckets' not in response: # Page break falls on last object.
break
for container in response['Buckets']:
container_names.append(Container(container['Name']))
params['ContinuationToken'] = response.get('ContinuationToken', '')
return sorted(set(container_names))
def get_container(self, name):
params = {}
# Note: The response NextContinuationToken is the cursor for the
# next page and ContinuationToken is the cursor of the current page.
# If the ContinuationToken is given is must be valid.
while params.get('ContinuationToken') != '':
response = self.client.list_objects_v2(
Bucket=name, MaxKeys=self.MAX_RESULTS, **params)
if 'Contents' not in response: # Page break falls on last object.
break
for line in response['Contents']:
yield ObjectLine.from_s3_line(line)
params['ContinuationToken'] = response.get(
'NextContinuationToken', '')
def get_object(self, container, name):
response = self.client.get_object(Bucket=container, Key=name)
# response is a mix of body, headers and s3 properties.
# the body is a StreamingBody which can be read in chunks.
return (response['ResponseMetadata']['HTTPHeaders'], response['Body'])
def head_object(self, container, name):
return self.client.head_object(Bucket=container, Key=name)
def is_dynamic_large_object(self, headers):
return bool('-' in headers.get('etag', ''))
def is_valid_etag(self, etag):
'''
Validate the etag value for the client.
'''
# The S3 multipart etag is a md5 hash with a parts count.
# {md5(''.join(md5(part) for part in parts))}-{len(parts)}
if super().is_valid_etag(etag):
return True
try:
etag, parts = etag.split('-')
except (AttributeError, ValueError):
return False
else:
return bool(super().is_valid_etag(etag) and parts.isdigit())
class SwiftSyncClient(BaseSyncClient):
ClientError = SwiftClientError
def get_client(self):
# The swift keystoneclient does not support separate connect/read
# timeout values while the requests library it uses does.
# timeout = (self.config.connect_timeout, self.config.read_timeout)
timeout = self.config.connect_timeout
if self.config.swift_authver == '3':
os_options = {
'project_name': self.config.swift_project,
'project_domain_name': self.config.swift_pdomain,
'user_domain_name': self.config.swift_udomain,
}
client = SwiftConnection(
auth_version='3', authurl=self.config.swift_auth,
user=self.config.swift_user, key=self.config.swift_key,
os_options=os_options, insecure=self.config.swift_insecure,
cacert=self.config.swift_cacert, timeout=timeout)
elif self.config.swift_authver == '1':
client = SwiftConnection(
auth_version='1', authurl=self.config.swift_auth,
user=self.config.swift_user, key=self.config.swift_key,
tenant_name='UNUSED', insecure=self.config.swift_insecure,
cacert=self.config.swift_cacert, timeout=timeout)
else:
raise NotImplementedError(
'auth_version? {!r}'.format(self.swift_authver))
return client
@lru_cache
def get_containers(self):
resp_headers, containers = self.client.get_account()
# containers == [
# {'count': 350182, 'bytes': 78285833087,
# 'name': 'containerA'}]
container_names = set(i['name'] for i in containers)
force_segments = self.config.all_containers_have_segments
# Translate container set into containers with and without
# segments. For example:
# - containerA (has_segments=False)
# - containerB (has_segments=True)
# - containerB_segments (skipped, belongs with containerB)
# - containerC_segments (has_segments=False)
selected_containers = []
for name in sorted(container_names):
# We're looking for a specific container. Only check whether a
# X_segments exists. (Because of DLO/SLO we must do the
# get_accounts() lookup even though we already know
# which container to process.)
if self.container:
if self.container == name:
new = Container(name)
if force_segments or (
'{}_segments'.format(name) in container_names):
new.has_segments = True
selected_containers.append(new)
break
# We're getting all containers. Check if X_segments exists for
# it. And only add X_segments containers if there is no X
# container.
else:
if (name.endswith('_segments')
and name.rsplit('_', 1)[0] in container_names):
# Don't add X_segments, because X exists.
pass
else:
new = Container(name)
if force_segments or (
'{}_segments'.format(name) in container_names):
new.has_segments = True
selected_containers.append(new)
# It's already sorted because we sort the container_names
# before inserting.
return selected_containers
def get_container(self, container):
'''
Return an iterator for the object listing of the container.
'''
marker = '' # "start _after_ marker"
prev_marker = 'anything_except_the_empty_string'
limit = 10000
while True:
assert marker != prev_marker, marker # loop trap
resp_headers, lines = self.client.get_container(
container, full_listing=False, limit=limit,
marker=marker)
for idx, line in enumerate(lines):
yield ObjectLine.from_swift_line(line)
if not lines or (idx + 1 < limit):
break
marker, prev_marker = line['name'], marker
def get_object(self, container, name):
return self.client.get_object(
container, name, resp_chunk_size=(16 * 1024 * 1024))
def head_object(self, container, name):
return self.client.head_object(container, name)
def is_dynamic_large_object(self, headers):
return bool(headers.get('x-object-manifest'))
class ObjectSync:
def __init__(self, client, config, container=None):
self.client = client
self.config = config
self.container = container
# Init translators. They're done lazily, so we don't need to know which
# containers exist yet.
self._translators = SyncConfigPathTranslators(
self.config, single_container=bool(container))
# Get data path. Chdir into it so no unmounting can take place.
data_path = config.data_path
os.chdir(data_path)
# Get metadata path where we store listings.
metadata_path = config.metadata_path
self._filelock = os.path.join(metadata_path, 'planb-objsync.lock')
self._path_cur = os.path.join(metadata_path, 'planb-objsync.cur')
# ^-- this contains the local truth
self._path_new = os.path.join(metadata_path, 'planb-objsync.new')
# ^-- the unreached goal
self._path_del = os.path.join(metadata_path, 'planb-objsync.del')
self._path_add = os.path.join(metadata_path, 'planb-objsync.add')
self._path_utime = os.path.join(metadata_path, 'planb-objsync.utime')
# ^-- the work we have to do to reach the goal
# NOTE: For changed files, we get an entry in both del and add.
# Sometimes however, only the mtime is changed. For that case we
# use the utime list, where we check the hash before
# downloading/overwriting.
def _migrate_swift_to_obj_db(self):
'''
Rename the `planb-swiftsync.cur` database to `planb-objsync.cur`.
Note: only use when `self._filelock` is ours.
'''
# Skip if the new database exists.
if os.path.isfile(self._path_cur):
return
metadata_path = self.config.metadata_path
old_path_cur = os.path.join(metadata_path, 'planb-swiftsync.cur')
# Skip if the old database does not exists (new client).
if not os.path.isfile(old_path_cur):
return
old_filelock = os.path.join(metadata_path, 'planb-swiftsync.lock')
old_lock_fd = None
try:
# Get lock on the old metadata location.
old_lock_fd = os.open(
old_filelock, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
except FileExistsError:
# Failed to get lock.
log.error('Failed to get %r lock', old_filelock)
sys.exit(1)
else:
# Check again after gaining the lock.
if (not os.path.isfile(self._path_cur)
and os.path.isfile(old_path_cur)):
os.rename(old_path_cur, self._path_cur)
finally:
if old_lock_fd is not None:
os.close(old_lock_fd)
os.unlink(old_filelock)
def get_translators(self):
return self._translators
def sync(self):
lock_fd = None
try:
# Get lock.
lock_fd = os.open(
self._filelock, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
except FileExistsError:
# Failed to get lock.
log.error('Failed to get %r lock', self._filelock)
sys.exit(1)
else:
self._migrate_swift_to_obj_db()
self._locked_sync()
finally:
if lock_fd is not None:
os.close(lock_fd)
os.unlink(self._filelock)
def _locked_sync(self):
times = []
status = SyncWorkerStatus()
# Do work.
times.append(['make_lists', time()])
self.make_lists()
times.append(['delete_from_list', time()])
status += self.delete_from_list()
times.append(['add_from_list', time()])
status += self.add_from_list()
times.append(['update_from_list', time()])
status += self.update_from_list()
# Add end-time, convert all times to relative, drop end-time.
times.append(['end', time()])
for idx, tarr in enumerate(times[0:-1]):
tarr[1] = times[idx + 1][1] - tarr[1]
times.pop()
log.info('Total time used: {%s}', ', '.join(
'{}: {:.1f}'.format(tn, tt) for tn, tt in times))
# If we bailed out with failures, but without an exception, we'll
# still clear out the list. Perhaps the list was bad and we simply
# need to fetch a clean new one (on the next run, that is).
self.clean_lists()
log.info('Sync done (status: %s)', status)
if status:
if (not status.config_errors
and not status.unhandled_errors
and sum(tarr[1] for tarr in times) > 1800):
# Sync took more than 30 minutes and there were no
# terrible failures. Exit 0.
log.warning(
'Not bailing out with exit 1 because this is a '
'slow job. Next backup run will fix/resume')
else:
raise SystemExit(1)
def make_lists(self):
"""
Build planb-objsync.add, planb-objsync.del, planb-objsync.utime.
"""
log.info('Building lists')
# Only create new list if it didn't exist yet (because we completed
# successfully the last time) or if it's rather old.
try:
last_modified = os.path.getmtime(self._path_new)
except FileNotFoundError:
last_modified = 0
if not last_modified or (time() - last_modified) > (18 * 3600.0):
self._make_new_list()
# Make the add/del/utime lists based off cur/new.
#
# * The add/del lists are obvious. Changed files get an entry in
# both del and add.
#
# * The utime list is for cases when only the mtime has changed:
# To avoid rewriting (duplicating) the file on COW storage (ZFS),
# we'll want to check the file hash to avoid rewriting it if it's
# the same. (Useful when the source files have been moved/copied
# and the X-Timestamps have thus been renewed.)
#
self._make_diff_lists()
def delete_from_list(self):
"""
Delete from planb-objsync.del.