-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmobius3.py
1581 lines (1287 loc) · 55 KB
/
mobius3.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
import array
import argparse
import asyncio
from collections import (
defaultdict,
)
import ctypes
import contextlib
import datetime
import enum
import fcntl
import hashlib
import hmac
import termios
import json
import logging
import os
import re
import signal
import ssl
import stat
import sys
import time
import uuid
import urllib.parse
from pathlib import (
PurePosixPath,
)
import struct
from weakref import (
WeakValueDictionary,
)
from xml.etree import (
ElementTree as ET,
)
import httpx
from fifolock import (
FifoLock,
)
import sentry_sdk
from sentry_sdk.integrations.httpx import HttpxIntegration
libc = ctypes.CDLL('libc.so.6', use_errno=True)
libc.inotify_init.argtypes = []
libc.inotify_add_watch.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_uint32]
def call_libc(func, *args):
value = func(*args)
latest_errno = ctypes.set_errno(0)
if latest_errno:
raise OSError(latest_errno, os.strerror(latest_errno))
return value
class FileContentChanged(Exception):
pass
class WeakReferenceableDict(dict):
pass
class Mutex(asyncio.Future):
@staticmethod
def is_compatible(holds):
return not holds[Mutex]
class InotifyEvents(enum.IntEnum):
IN_MODIFY = 0x00000002
IN_ATTRIB = 0x00000004
IN_CLOSE_WRITE = 0x00000008
IN_MOVED_FROM = 0x00000040
IN_MOVED_TO = 0x00000080
IN_CREATE = 0x00000100
IN_DELETE = 0x00000200
# Sent by the kernel without explicitly watching for them
IN_Q_OVERFLOW = 0x00004000
IN_IGNORED = 0x00008000
class InotifyFlags(enum.IntEnum):
IN_ONLYDIR = 0x01000000
IN_ISDIR = 0x40000000
class S3SyncLoggerAdapter(logging.LoggerAdapter):
def process(self, msg, kwargs):
return \
('[s3sync] %s' % (msg,), kwargs) if not self.extra else \
('[s3sync:%s] %s' % (','.join(str(v) for v in self.extra.values()), msg), kwargs)
def child_adapter(s3sync_adapter, extra):
return S3SyncLoggerAdapter(
s3sync_adapter.logger,
{**s3sync_adapter.extra, **extra},
)
def get_logger_adapter_default(extra):
return S3SyncLoggerAdapter(logging.getLogger('mobius3'), extra)
WATCH_MASK = \
InotifyEvents.IN_MODIFY | \
InotifyEvents.IN_ATTRIB | \
InotifyEvents.IN_CLOSE_WRITE | \
InotifyEvents.IN_MOVED_FROM | \
InotifyEvents.IN_MOVED_TO | \
InotifyEvents.IN_CREATE | \
InotifyEvents.IN_DELETE | \
InotifyFlags.IN_ONLYDIR
# We watch the download directly only for moves to be able to use the cookie
# to determine if a move is from a download so we then don't re-upload it
DOWNLOAD_WATCH_MASK = \
InotifyEvents.IN_MOVED_FROM
EVENT_HEADER = struct.Struct('iIII')
get_current_task = \
asyncio.current_task if hasattr(asyncio, 'current_task') else \
asyncio.Task.current_task
async def empty_async_iterator():
while False:
yield
async def streamed(data):
yield data
async def buffered(data):
return b''.join([chunk async for chunk in data])
@contextlib.contextmanager
def timeout(loop, max_time):
cancelling_due_to_timeout = False
current_task = get_current_task()
def cancel():
nonlocal cancelling_due_to_timeout
cancelling_due_to_timeout = True
current_task.cancel()
def reset():
nonlocal handle
handle.cancel()
handle = loop.call_later(max_time, cancel)
handle = loop.call_later(max_time, cancel)
try:
yield reset
except asyncio.CancelledError:
if cancelling_due_to_timeout:
raise asyncio.TimeoutError()
raise
finally:
handle.cancel()
def Pool(
get_ssl_context=ssl.create_default_context,
get_logger_adapter=get_logger_adapter_default,
force_ipv4=False,
):
logger = get_logger_adapter({})
async def log_request(request):
logger.info('[http] Request: %s %s', request.method, request.url)
async def log_response(response):
logger.info('[http] Response: %s %s %s', response.request.method, response.request.url, response.status_code)
return httpx.AsyncClient(
timeout=10.0,
transport=httpx.AsyncHTTPTransport(
retries=3,
verify=get_ssl_context(),
local_address="0.0.0.0" if force_ipv4 else None,
),
event_hooks={'request': [log_request], 'response': [log_response]}
)
def AWSAuth(service, region, client, get_credentials, content_hash=hashlib.sha256().hexdigest()):
def aws_sigv4_headers(access_key_id, secret_access_key, pre_auth_headers,
method, path, params):
algorithm = 'AWS4-HMAC-SHA256'
now = datetime.datetime.utcnow()
amzdate = now.strftime('%Y%m%dT%H%M%SZ')
datestamp = now.strftime('%Y%m%d')
credential_scope = f'{datestamp}/{region}/{service}/aws4_request'
pre_auth_headers_lower = tuple(
(header_key.lower(), ' '.join(header_value.split()))
for header_key, header_value in pre_auth_headers
)
required_headers = (
('x-amz-content-sha256', content_hash),
('x-amz-date', amzdate),
)
headers = sorted(pre_auth_headers_lower + required_headers)
signed_headers = ';'.join(key for key, _ in headers)
def signature():
def canonical_request():
canonical_uri = urllib.parse.quote(path, safe='/~')
quoted_params = sorted(
(urllib.parse.quote(key, safe='~'), urllib.parse.quote(value, safe='~'))
for key, value in params
)
canonical_querystring = '&'.join(f'{key}={value}' for key, value in quoted_params)
canonical_headers = ''.join(f'{key}:{value}\n' for key, value in headers)
return f'{method}\n{canonical_uri}\n{canonical_querystring}\n' + \
f'{canonical_headers}\n{signed_headers}\n{content_hash}'
def sign(key, msg):
return hmac.new(key, msg.encode('ascii'), hashlib.sha256).digest()
string_to_sign = f'{algorithm}\n{amzdate}\n{credential_scope}\n' + \
hashlib.sha256(canonical_request().encode('ascii')).hexdigest()
date_key = sign(('AWS4' + secret_access_key).encode('ascii'), datestamp)
region_key = sign(date_key, region)
service_key = sign(region_key, service)
request_key = sign(service_key, 'aws4_request')
return sign(request_key, string_to_sign).hex()
return (
('authorization', (
f'{algorithm} Credential={access_key_id}/{credential_scope}, '
f'SignedHeaders={signed_headers}, Signature=' + signature())
),
('x-amz-date', amzdate),
('x-amz-content-sha256', content_hash),
)
class _AWSAuth(httpx.Auth):
async def async_auth_flow(self, request):
access_key_id, secret_access_key, auth_headers = await get_credentials(client)
params = tuple((key.decode(), value.decode()) for (key, value) in urllib.parse.parse_qsl(request.url.query, keep_blank_values=True))
existing_headers = tuple((key, value) for (key, value) in request.headers.items() if key == 'host' or key.startswith('content-') or key.startswith('x-amz-'))
headers_to_set = aws_sigv4_headers(
access_key_id, secret_access_key, existing_headers + auth_headers,
request.method, request.url.path, params,
) + auth_headers
for key, value in headers_to_set:
request.headers[key] = value
yield request
return _AWSAuth()
async def get_credentials_from_environment(_):
return os.environ['AWS_ACCESS_KEY_ID'], os.environ['AWS_SECRET_ACCESS_KEY'], ()
def get_credentials_from_ecs_endpoint():
aws_access_key_id = None
aws_secret_access_key = None
pre_auth_headers = None
expiration = datetime.datetime.fromtimestamp(0)
async def _get_credentials(client):
nonlocal aws_access_key_id
nonlocal aws_secret_access_key
nonlocal pre_auth_headers
nonlocal expiration
now = datetime.datetime.now()
if now > expiration:
response = await client.request(
b'GET',
'http://169.254.170.2' + os.environ['AWS_CONTAINER_CREDENTIALS_RELATIVE_URI']
)
creds = json.loads(response.content)
aws_access_key_id = creds['AccessKeyId']
aws_secret_access_key = creds['SecretAccessKey']
expiration = datetime.datetime.strptime(creds['Expiration'], '%Y-%m-%dT%H:%M:%SZ')
pre_auth_headers = (
('x-amz-security-token', creds['Token']),
)
return aws_access_key_id, aws_secret_access_key, pre_auth_headers
return _get_credentials
def Syncer(
directory, bucket, endpoint, region,
prefix='',
concurrent_uploads=5,
concurrent_downloads=5,
get_credentials=get_credentials_from_environment,
get_pool=Pool,
flush_file_root='.__mobius3_flush__',
flush_file_timeout=5,
directory_watch_timeout=5,
download_directory='.mobius3',
get_logger_adapter=get_logger_adapter_default,
local_modification_persistance=120,
download_interval=10,
exclude_remote=r'^$',
exclude_local=r'^$',
upload_on_create=r'^$',
cloudwatch_monitoring_endpoint='',
cloudwatch_monitoring_region='',
cloudwatch_monitoring_namespace='',
):
loop = asyncio.get_running_loop()
logger = get_logger_adapter({})
directory = PurePosixPath(directory)
exclude_remote = re.compile(exclude_remote)
exclude_local = re.compile(exclude_local)
upload_on_create = re.compile(upload_on_create)
bucket_url = endpoint.format(bucket)
# The file descriptor returned from inotify_init
fd = None
# Watch descriptors to paths. A notification returns only a relative
# path to its watch descriptor path: these are used to find the full
# path of any notified-on files
wds_to_path = {}
# To migitate (but not eliminate) the chance that nested files are
# immediately re-uploaded
directory_watch_events = WeakValueDictionary()
# The asyncio task pool that performs the uploads
upload_tasks = []
# PUTs and DELETEs are initiated in the order generated by inotify events
upload_job_queue = asyncio.Queue()
download_manager_task = None
download_tasks = []
download_job_queue = asyncio.Queue()
# To prevent concurrent HTTP requests on the same files where order of
# receipt by S3 cannot be guaranteed, we wrap each request by a lock
# e.g. to prevent a DELETE overtaking a PUT
path_locks = WeakValueDictionary()
# A path -> content version dict is maintained during queues and uploads,
# and incremented on every modification of a file. When a path is
# scheduled to be uploaded, its version is copied. After the last read of
# data for an upload, but before it's uploaded, the copied version of the
# path is compared to the current version. If this is different, there was
# a change to the file contents, we know another upload will be scheduled,
# so we abort the current upload
content_versions = WeakValueDictionary()
# Before completing an upload, we force a flush of the event queue for
# the uploads directory to ensure that we have processed any change events
# that would upate the corresponding item in content_versions
flushes = WeakValueDictionary()
# During a queue of a PUT or DELETE, and for
# local_modification_persistance seconds, we do not overwrite local files
# with information from S3 for eventual consistency reasons
push_queued = defaultdict(int)
push_completed = ExpiringSet(loop, local_modification_persistance)
# When moving download files from the hidden directory to their final
# position, we would like to detect if this is indeed a move from a
# download (in which case we don't re-upload), or a real move from
download_cookies = ExpiringSet(loop, 10)
# When we delete a file locally, do not attempt to delete it remotely
ignore_next_delete = {}
# When we add a directory from a download, do not attempt to reupload
ignore_next_directory_upload = {}
# When downloading a file, we note its etag. We don't re-download it later
# if the etag matches
etags = {}
# Don't re-upload metadata if we think S3 already has it
meta = {}
# A cache of the file tree is maintained. Used for directory renames: we
# only get notified of renames _after_ they have happened, we need a way
# to know what objects are on S3 in order to DELETE them
tree_cache_root = {
'type': 'directory',
'children': {},
}
client = get_pool()
auth = AWSAuth(service='s3', region=region, client=client, get_credentials=get_credentials, content_hash='UNSIGNED-PAYLOAD')
def ensure_file_in_tree_cache(path):
parent_dir = ensure_parent_dir_in_tree_cache(path)
parent_dir['children'][path.name] = {
'type': 'file',
}
def ensure_dir_in_tree_cache(path):
parent_dir = ensure_parent_dir_in_tree_cache(path)
parent_dir['children'].setdefault(path.name, {
'type': 'directory',
'children': {},
})
def ensure_parent_dir_in_tree_cache(path):
directory = tree_cache_root
for parent in reversed(list(path.parents)):
directory = directory['children'].setdefault(parent.name, {
'type': 'directory',
'children': {},
})
return directory
def remove_from_tree_cache(path):
directory = tree_cache_root
for parent in reversed(list(path.parents)):
directory = directory['children'][parent.name]
del directory['children'][path.name]
def tree_cache_directory(path):
directory = tree_cache_root
for parent in reversed(list(path.parents)):
directory = directory['children'][parent.name]
return directory['children'][path.name]
def set_etag(path, headers):
etags[path] = headers['etag']
def queued_push_local_change(path):
push_queued[path] += 1
def completed_push_local_change(path):
push_queued[path] -= 1
if push_queued[path] == 0:
del push_queued[path]
push_completed.add(path)
def is_dir_pull_blocked(path):
return path in push_queued or path in push_completed
def is_pull_blocked(path):
# For extremely recent modifications we may not have yielded the event
# loop to add files to the queue. We do our best and check the mtime
# to prevent overriding with older remote data. However, after we
# check a file could still be modified locally, and we have no way to
# detect this
def modified_recently():
now = datetime.datetime.now().timestamp()
try:
return now - os.lstat(path).st_mtime < local_modification_persistance
except FileNotFoundError:
return False
return path in push_queued or path in push_completed or modified_recently()
async def start():
logger = get_logger_adapter({'mobius3_component': 'start'})
logger.info('Starting')
logger.info('Excluding: %s', exclude_remote)
nonlocal upload_tasks
nonlocal download_tasks
nonlocal download_manager_task
start_time = time.monotonic()
try:
os.mkdir(directory / download_directory)
except FileExistsError:
pass
upload_tasks = [
asyncio.create_task(process_jobs(upload_job_queue))
for i in range(0, concurrent_uploads)
]
download_tasks = [
asyncio.create_task(process_jobs(download_job_queue))
for i in range(0, concurrent_downloads)
]
start_inotify(logger, upload=False)
await list_and_schedule_downloads(logger)
download_manager_task = asyncio.create_task(
download_manager(get_logger_adapter({'mobius3_component': 'download'}))
)
end_time = time.monotonic()
logger.info('Finished starting: %s seconds', end_time - start_time)
if cloudwatch_monitoring_endpoint and cloudwatch_monitoring_region and cloudwatch_monitoring_namespace:
logger.info('Posting startup time to %s in region %s in namespace %s', cloudwatch_monitoring_endpoint, cloudwatch_monitoring_region, cloudwatch_monitoring_namespace)
cloudwatch_auth = AWSAuth(service='monitoring', region=cloudwatch_monitoring_region, client=client, get_credentials=get_credentials)
response = await client.post(cloudwatch_monitoring_endpoint, params=(
('Version', '2010-08-01'),
('Action', 'PutMetricData'),
('Namespace', cloudwatch_monitoring_namespace),
('MetricData.member.1.MetricName', 'StartupSyncTime'),
('MetricData.member.1.Unit', 'Seconds'),
('MetricData.member.1.Value', str(end_time - start_time)),
), auth=cloudwatch_auth)
response.raise_for_status()
def start_inotify(logger, upload):
nonlocal wds_to_path
nonlocal meta
nonlocal etags
nonlocal tree_cache_root
nonlocal fd
nonlocal ignore_next_delete
nonlocal ignore_next_directory_upload
ignore_next_delete = {}
ignore_next_directory_upload = {}
wds_to_path = {}
meta = {}
etags = {}
tree_cache_root = {
'type': 'directory',
'children': {},
}
fd = call_libc(libc.inotify_init)
def _read_events():
logger = get_logger_adapter({'mobius3_component': 'event'})
read_events(logger)
loop.add_reader(fd, _read_events)
watch_directory(download_directory, DOWNLOAD_WATCH_MASK)
watch_directory_recursive(logger, directory, WATCH_MASK, upload)
async def stop():
async def cancel(task):
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
# Make every effort to read all incoming events and finish the queue
logger = get_logger_adapter({'mobius3_component': 'stop'})
logger.info('Stopping')
if download_manager_task is not None:
await cancel(download_manager_task)
for task in download_tasks:
await cancel(task)
read_events(logger)
while upload_job_queue._unfinished_tasks:
await upload_job_queue.join()
read_events(logger)
stop_inotify()
for task in upload_tasks:
await cancel(task)
await client.aclose()
await asyncio.sleep(0)
logger.info('Finished stopping')
def stop_inotify():
loop.remove_reader(fd)
os.close(fd)
def watch_directory(path, mask):
try:
wd = call_libc(libc.inotify_add_watch, fd, str(path).encode('utf-8'), mask)
except (NotADirectoryError, FileNotFoundError):
return
# After a directory rename, we will be changing the path of an
# existing entry, but that's fine
wds_to_path[wd] = path
# Notify any waiting watchers
directory_watch_events.setdefault(path, default=asyncio.Event()).set()
def watch_directory_recursive(logger, path, mask, upload):
logger.info('Watching directory: %s, with upload: %s', path, upload)
watch_directory(path, mask)
if PurePosixPath(path) not in [directory, directory / download_directory]:
try:
del ignore_next_directory_upload[path]
except KeyError:
if upload:
logger.info('Scheduling upload directory: %s', path)
schedule_upload_directory(logger, path)
# By the time we've added a watcher, files or subdirectories may have
# already been created
for root, dirs, files in os.walk(path):
if PurePosixPath(root) == directory / download_directory:
continue
if upload:
for file in files:
logger.info('Scheduling upload: %s', PurePosixPath(root) / file)
schedule_upload(logger, PurePosixPath(root) / file)
for d in dirs:
watch_directory_recursive(logger, PurePosixPath(root) / d, mask, upload)
def remote_delete_directory(logger, path):
# Directory nesting not likely to be large
def recursive_delete(prefix, directory):
for child_name, child in list(directory['children'].items()):
if child['type'] == 'file':
logger.info('Scheduling delete: %s', prefix / child_name)
schedule_delete(logger, prefix / child_name)
else:
recursive_delete(prefix / child_name, child)
schedule_delete_directory(logger, prefix / child_name)
try:
cache_directory = tree_cache_directory(path)
except KeyError:
# We may be moving from or deleting something not yet watched,
# in which case we leave S3 as it is. There may be file(s) in
# the queue to upload, but they will correctly fail if it can't
# find the file(s)
pass
else:
recursive_delete(path, cache_directory)
schedule_delete_directory(logger, path)
def read_events(parent_logger):
FIONREAD_output = array.array('i', [0])
fcntl.ioctl(fd, termios.FIONREAD, FIONREAD_output)
bytes_to_read = FIONREAD_output[0]
if not bytes_to_read:
return
raw_bytes = os.read(fd, bytes_to_read)
offset = 0
while offset < len(raw_bytes):
wd, mask, cookie, length = EVENT_HEADER.unpack_from(raw_bytes, offset)
offset += EVENT_HEADER.size
path = PurePosixPath(raw_bytes[offset:offset+length].rstrip(b'\0').decode('utf-8'))
offset += length
event_id = uuid.uuid4().hex[:8]
logger = child_adapter(parent_logger, {'event': event_id})
full_path = \
wds_to_path[wd] / path if wd != -1 else \
directory # Overflow event
events = [event for event in InotifyEvents.__members__.values() if event & mask]
item_type = \
'overflow' if mask & InotifyEvents.IN_Q_OVERFLOW else \
'flush' if path.name.startswith(flush_file_root) and full_path in flushes else \
'download' if full_path.parent == directory / download_directory else \
'dir' if mask & InotifyFlags.IN_ISDIR else \
'file'
for event in events:
handler_name = f'handle__{item_type}__{event.name}'
try:
handler = parent_locals[handler_name]
except KeyError:
continue
else:
logger.debug('Path: %s', full_path)
logger.debug('Handler: %s', handler_name)
try:
handler(logger, wd, cookie, full_path)
except Exception:
logger.exception('Exception calling handler')
def handle__overflow__IN_Q_OVERFLOW(logger, _, __, ___):
logger.warning('IN_Q_OVERFLOW. Restarting')
stop_inotify()
start_inotify(logger, upload=True)
def handle__flush__IN_CREATE(logger, _, __, path):
flush = flushes[path]
logger.debug('Flushing: %s', path)
flush.set()
def handle__download__IN_MOVED_FROM(logger, __, cookie, ___):
logger.debug('Cookie: %s', cookie)
download_cookies.add(cookie)
def handle__file__IN_ATTRIB(logger, _, __, path):
schedule_upload_meta(logger, path)
def handle__file__IN_CLOSE_WRITE(logger, _, __, path):
schedule_upload(logger, path)
def handle__file__IN_CREATE(logger, _, __, path):
if upload_on_create.match(str(path)) or os.path.islink(path):
schedule_upload(logger, path)
def handle__dir__IN_CREATE(logger, _, __, path):
watch_directory_recursive(logger, path, WATCH_MASK, upload=True)
def handle__file__IN_DELETE(logger, _, __, path):
try:
del etags[path]
except KeyError:
pass
try:
del meta[path]
except KeyError:
pass
try:
del ignore_next_delete[path]
except KeyError:
pass
else:
return
# Correctness does not depend on this bump: it's an optimisation
# that ensures we abandon any upload of this path ahead of us
# in the queue
bump_content_version(path)
schedule_delete(logger, path)
def handle__dir__IN_DELETE(logger, _, __, path):
try:
del ignore_next_delete[path]
except KeyError:
pass
else:
return
schedule_delete_directory(logger, path)
def handle__file__IN_IGNORED(_, wd, __, ___):
# For some reason IN_ISDIR is not set with IN_IGNORED
del wds_to_path[wd]
def handle__file__IN_MODIFY(_, __, ___, path):
bump_content_version(path)
def handle__dir__IN_MOVED_FROM(logger, _, __, path):
remote_delete_directory(logger, path)
def handle__file__IN_MOVED_FROM(logger, _, __, path):
try:
del etags[path]
except KeyError:
pass
schedule_delete(logger, path)
def handle__dir__IN_MOVED_TO(logger, _, __, path):
watch_directory_recursive(logger, path, WATCH_MASK, upload=True)
def handle__file__IN_MOVED_TO(logger, _, cookie, path):
bump_content_version(path)
if cookie in download_cookies:
logger.debug('Cookie: %s', cookie)
return
schedule_upload(logger, path)
def get_content_version(path):
return content_versions.setdefault(path, default=WeakReferenceableDict(version=0))
def bump_content_version(path):
get_content_version(path)['version'] += 1
def get_lock(path):
return path_locks.setdefault(path, default=FifoLock())
def schedule_upload_meta(logger, path):
if exclude_local.match(str(path)):
logger.info('Excluding from upload: %s', path)
return
version_current = get_content_version(path)
version_original = version_current.copy()
async def function():
try:
await upload_meta(logger, path, version_current, version_original)
finally:
completed_push_local_change(path)
ensure_file_in_tree_cache(path)
upload_job_queue.put_nowait((logger, function))
queued_push_local_change(path)
def schedule_upload(logger, path):
if exclude_local.match(str(path)):
logger.info('Excluding from upload: %s', path)
return
version_current = get_content_version(path)
version_original = version_current.copy()
async def function():
try:
await upload(logger, path, version_current, version_original)
finally:
completed_push_local_change(path)
ensure_file_in_tree_cache(path)
upload_job_queue.put_nowait((logger, function))
queued_push_local_change(path)
def schedule_upload_directory(logger, path):
if exclude_local.match(str(path)):
logger.info('Excluding from upload: %s', path)
return
async def function():
try:
await upload_directory(logger, path)
finally:
completed_push_local_change(path)
ensure_dir_in_tree_cache(path)
upload_job_queue.put_nowait((logger, function))
queued_push_local_change(path)
def schedule_delete(logger, path):
if exclude_local.match(str(path)):
logger.info('Excluding from delete: %s', path)
return
version_current = get_content_version(path)
version_original = version_current.copy()
async def function():
try:
await delete(logger, path, version_current, version_original)
finally:
completed_push_local_change(path)
try:
remove_from_tree_cache(path)
except KeyError:
pass
upload_job_queue.put_nowait((logger, function))
queued_push_local_change(path)
def schedule_delete_directory(logger, path):
if exclude_local.match(str(path)):
logger.info('Excluding from delete: %s', path)
return
async def function():
try:
await delete_directory(logger, path)
finally:
completed_push_local_change(path)
try:
remove_from_tree_cache(path)
except KeyError:
pass
upload_job_queue.put_nowait((logger, function))
queued_push_local_change(path)
async def process_jobs(queue):
while True:
logger, job = await queue.get()
try:
await job()
except Exception as exception:
if isinstance(exception, asyncio.CancelledError):
raise
if (
isinstance(exception, FileContentChanged) or
isinstance(exception.__cause__, FileContentChanged)
):
logger.info('Content changed, aborting: %s', exception)
if (
isinstance(exception, FileNotFoundError) or
isinstance(exception.__cause__, FileNotFoundError)
):
logger.info('File not found: %s', exception)
if (
not isinstance(exception, FileNotFoundError) and
not isinstance(exception.__cause__, FileNotFoundError) and
not isinstance(exception, FileContentChanged) and
not isinstance(exception.__cause__, FileContentChanged)
):
logger.exception('Exception during %s', job)
finally:
queue.task_done()
async def flush_events(logger, path):
flush_path = path.parent / (flush_file_root + uuid.uuid4().hex)
logger.debug('Creating flush file: %s', flush_path)
event = asyncio.Event()
flushes[flush_path] = event
with open(flush_path, 'w'):
pass
os.remove(flush_path)
# In rare cases, the event queue could be full and the event for
# the flush file is dropped
with timeout(loop, flush_file_timeout):
await event.wait()
async def wait_for_directory_watched(path):
# Inneficient search
if path.parent in wds_to_path.values():
return
event = directory_watch_events.setdefault(path.parent, default=asyncio.Event())
with timeout(loop, directory_watch_timeout):
await event.wait()
async def upload(logger, path, content_version_current, content_version_original):
logger.info('Uploading %s', path)
def with_is_last(iterable):
try:
last = next(iterable)
except StopIteration:
return
for val in iterable:
yield False, last
last = val
yield True, last
async def file_body():
with open(path, 'rb') as file:
for is_last, chunk in with_is_last(iter(lambda: file.read(16384), b'')):
if is_last:
await flush_events(logger, path)
if content_version_current != content_version_original:
raise FileContentChanged(path)
yield chunk
async def symlink_points_to():
yield os.readlink(path).encode('utf-8')
is_symlink = os.path.islink(path)
if not is_symlink:
content = file_body()
content_length = str(os.stat(path).st_size)
else:
content = symlink_points_to()
content_length = str(len(os.readlink(path).encode('utf-8')))
mtime = str(os.lstat(path).st_mtime)
mode = str(os.lstat(path).st_mode)
# Ensure we only progress if the content length hasn't changed since
# we have queued the upload
await flush_events(logger, path)
if content_version_current != content_version_original:
raise FileContentChanged(path)
data = (
('x-amz-meta-mtime', mtime),
('x-amz-meta-mode', mode),
)
def set_etag_and_meta(path, headers):
meta[path] = data
set_etag(path, headers)
await locked_request(
logger, b'PUT', path, file_key_for_path(path), content=content,
get_headers=lambda: (
('content-length', content_length),
) + data,
on_done=set_etag_and_meta,
)
async def upload_meta(logger, path, content_version_current, content_version_original):
logger.info('Uploading meta %s', path)
mtime = str(os.lstat(path).st_mtime)
mode = str(os.lstat(path).st_mode)
# Ensure we only progress if the content hasn't changed since we have
# queued the upload
await flush_events(logger, path)
if content_version_current != content_version_original:
raise FileContentChanged(path)
data = (