-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathxfer.py
executable file
·1370 lines (1046 loc) · 40.9 KB
/
xfer.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
"""
Use HTCondor to synchronize a directory on an access point with a directory
on an execution point.
"""
import abc
import argparse
import contextlib
import enum
import hashlib
import json
import logging
import os
import re
import shutil
import sys
import time
from pathlib import Path
from typing import Any, Dict, Iterable, Iterator, List, Mapping, Optional, Tuple, Type, TypeVar
T_JSON = Dict[str, Any]
T_CMD_INFO = List[Mapping[str, Path]]
KB = 2**10
MB = 2**20
GB = 2**30
TB = 2**40
METADATA_FILE_SIZE_LIMIT = 16 * KB
SANDBOX_FILE_NAME = "file-for-transfer"
REQUIREMENTS_FILE_NAME = "requirements.txt"
METADATA_FILE_NAME = "metadata"
LOCAL_MANIFEST_FILE_NAME = "local_manifest.txt"
REMOTE_MANIFEST_FILE_NAME = "remote_manifest.txt"
TRANSFER_MANIFEST_FILE_NAME = "transfer_manifest.txt"
TRANSFER_COMMANDS_FILE_NAME = "transfer_commands.json"
VERIFY_COMMANDS_FILE_NAME = "verify_commands.json"
DRY_RUN_OUTPUT_FILE_NAME = "dry_run.json"
OUTER_DAG_NAME = "outer.dag"
INNER_DAG_NAME = "inner.dag"
DAG_ARGS = {"force": True}
THIS_FILE = Path(__file__).resolve()
class TransferError(Exception):
pass
class InvalidManifestEntry(TransferError):
pass
class InconsistentManifest(TransferError):
pass
class TransferAlreadyRunning(TransferError):
pass
class VerificationFailed(TransferError):
pass
class NotACondorJob(TransferError):
pass
class StrEnum(str, enum.Enum):
def __repr__(self):
return repr(self.value)
def __str__(self):
return self.value
class Commands(StrEnum):
SYNC = "sync"
MAKE_REMOTE_FILE_MANIFEST = "make_remote_file_manifest"
WRITE_INNER_DAG = "write_inner_dag"
PULL_FILE = "pull_file"
PUSH_FILE = "push_file"
GET_REMOTE_METADATA = "get_remote_metadata"
POST_TRANSFER = "post_transfer"
FINALIZE_TRANSFER_MANIFEST = "finalize_transfer_manifest"
class TransferDirection(StrEnum):
PULL = "pull"
PUSH = "push"
DIRECTION_TO_COMMAND = {
TransferDirection.PULL: Commands.PULL_FILE,
TransferDirection.PUSH: Commands.PUSH_FILE,
}
def timestamp() -> float:
return time.time()
def write_requirements_file(working_dir: Path, requirements: str) -> None:
(working_dir / REQUIREMENTS_FILE_NAME).write_text(requirements)
def read_requirements_file(requirements_file: Optional[Path]) -> Optional[str]:
if requirements_file is None:
return None
return requirements_file.read_text().strip()
RE_SPLIT_CAMEL = re.compile(r".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)")
def camel_to_upper_snake(text: str) -> str:
return "_".join(m.group(0).upper() for m in RE_SPLIT_CAMEL.finditer(text))
class ManifestEntry(metaclass=abc.ABCMeta):
def __init__(self, **info):
expected_keys = set(self.keys)
given_keys = set(info.keys())
if given_keys < expected_keys:
raise InvalidManifestEntry(
"Info {} for {} is missing keys: {}".format(
info, type(self).__name__, expected_keys - given_keys
)
)
if given_keys > expected_keys:
logging.warning(
"Info {} for {} has extra keys: {}".format(
info, type(self).__name__, given_keys - expected_keys
)
)
self._info = {k: info[k] for k in self.keys}
def __eq__(self, other):
if not isinstance(other, type(self)):
return NotImplemented
return self._info == other._info
def __repr__(self):
return "{}({})".format(
type(self).__name__, ", ".join("{} = {!r}".format(k, v) for k, v in self._info.items())
)
def __str__(self):
return "{} {}".format(self.type, json.dumps(self.to_json()))
def to_json(self) -> T_JSON:
return path_values_to_strings(self._info)
def to_entry(self):
return "{}\n".format(self)
def write_entry_to(self, file):
file.write(self.to_entry())
@property
def type(self) -> str:
return camel_to_upper_snake(type(self).__name__)
@property
@abc.abstractmethod
def keys(self) -> Tuple[str, ...]:
raise NotImplementedError
class Name(ManifestEntry, metaclass=abc.ABCMeta):
def __init__(self, **info):
super().__init__(**info)
self._info["name"] = Path(self._info["name"])
@property
def name(self):
return self._info["name"]
class Size(ManifestEntry, metaclass=abc.ABCMeta):
def __init__(self, **info):
super().__init__(**info)
self._info["size"] = int(self._info["size"])
@property
def size(self):
return self._info["size"]
class Digest(Name, Size, metaclass=abc.ABCMeta):
@property
def digest(self):
return self._info["digest"]
class Timestamp(ManifestEntry, metaclass=abc.ABCMeta):
def __init__(self, **info):
super().__init__(**info)
self._info["timestamp"] = float(self._info["timestamp"])
@property
def timestamp(self):
return self._info["timestamp"]
class TransferRequest(Name, Size):
keys = ("name", "size")
class VerifyRequest(Name, Size):
keys = ("name", "size")
class TransferComplete(Digest, Timestamp):
keys = ("name", "size", "digest", "timestamp")
class SyncRequest(Timestamp):
keys = (
"direction",
"remote_prefix",
"files_at_source",
"files_to_transfer",
"bytes_to_transfer",
"files_to_verify",
"bytes_to_verify",
"timestamp",
)
def __init__(self, **info):
super().__init__(**info)
self._info["remote_prefix"] = Path(self._info["remote_prefix"])
class SyncRequestV2(SyncRequest):
keys = SyncRequest.keys + ("dry_run",)
def __init__(self, **info):
super().__init__(**info)
self._info["dry_run"] = bool(self._info["dry_run"])
class SyncDone(Timestamp):
keys = ("timestamp",)
class File(Name, Size):
keys = ("name", "size")
class Metadata(Digest):
keys = ("name", "size", "digest")
def descendants(cls):
for c in cls.__subclasses__():
yield c
yield from descendants(c)
ENTRY_TYPE_TO_CLASS = {
camel_to_upper_snake(cls.__name__): cls for cls in descendants(ManifestEntry)
}
def read_manifest(path: Path) -> Iterator[Tuple[ManifestEntry, int]]:
with path.open(mode="r", encoding="utf-8") as f:
for line_number, line in enumerate(f, start=1):
line = line.strip()
if not line or line.startswith("#"):
continue
try:
yield parse_manifest_entry(line), line_number
except Exception:
logging.exception(
'Failed to parse manifest entry at {}:{} ("{}")'.format(path, line_number, line)
)
raise
def parse_manifest_entry(entry: str) -> ManifestEntry:
entry = entry.strip()
type, info = entry.split(maxsplit=1)
cls = ENTRY_TYPE_TO_CLASS[type]
info = json.loads(info)
return cls(**info)
def create_file_manifest(root_path: Path, manifest_path: Path, test_mode: bool = False) -> None:
logging.info("Generating file listing for %s", root_path)
with manifest_path.open(mode="w", encoding="utf-8") as f:
if not root_path.exists():
return
for entry in walk(root_path):
size = entry.stat().st_size
if test_mode and size > 50 * MB:
continue
File(name=entry.path, size=size).write_entry_to(f)
def parse_file_manifest(prefix: Path, file_manifest_path: Path) -> Dict[Path, int]:
files = {}
for entry, _ in read_manifest(file_manifest_path):
entry = check_entry_type(entry, File)
fname = entry.name
size = entry.size
if prefix not in fname.parents:
logging.error("%s file (%s) does not start with specified prefix", fname)
if fname == prefix:
logging.warning("%s file, stripped of prefix (%s), is empty", prefix)
continue
files[fname.relative_to(prefix)] = size
return files
def walk(path):
for entry in os.scandir(str(path)):
if entry.is_dir():
yield from walk(entry.path)
elif entry.is_file():
yield entry
def write_metadata_file(path: Path, hasher, size: int) -> None:
metadata = Metadata(name=path, digest=hasher.hexdigest(), size=size)
logging.info("File metadata: {}".format(metadata))
with Path(METADATA_FILE_NAME).open(mode="w", encoding="utf-8") as f:
metadata.write_entry_to(f)
logging.info("Wrote metadata file")
def read_metadata_file(path: Path) -> Metadata:
if path.stat().st_size > METADATA_FILE_SIZE_LIMIT:
raise InvalidManifestEntry("Metadata file is too large")
entry, _ = tuple(read_manifest(path))[0]
return check_entry_type(entry, Metadata)
T = TypeVar("T", bound=ManifestEntry)
def check_entry_type(entry: ManifestEntry, expected_type: Type[T]) -> T:
if not isinstance(entry, expected_type):
raise InvalidManifestEntry(
"Expected a {}, but got a {}".format(expected_type.__name__, type(entry).__name__)
)
return entry
def write_json(j: T_JSON, path: Path) -> None:
with path.open(mode="w", encoding="utf-8") as f:
json.dump(j, f)
def load_json(path: Path) -> T_JSON:
with path.open(mode="r", encoding="utf-8") as f:
return json.load(f)
def make_hasher():
return hashlib.sha1()
def shared_submit_descriptors(
executable: Optional[Path] = None,
unique_id: Optional[str] = None,
requirements: Optional[str] = None,
annex_name: Optional[str] = None,
) -> Dict[str, str]:
# Only import htcondor submit-side
import classad
if executable is None:
executable = THIS_FILE
descriptors = {
"executable": executable.as_posix(),
"keep_claim_idle": "300",
"request_disk": "1GB",
"request_memory": "512MB",
"requirements": requirements or "true",
"My.Is_Transfer_Job": "true",
"My.WantFlocking": "true", # special attribute for the CHTC pool, not necessary at other sites
}
if unique_id:
descriptors["My.UniqueID"] = classad.quote(unique_id)
if annex_name:
descriptors["My.TargetAnnexName"] = classad.quote(annex_name)
return descriptors
def submit_outer_dag(
direction: TransferDirection,
working_dir: Path,
local_dir: Path,
remote_dir: Path,
requirements: Optional[str] = None,
unique_id: Optional[str] = None,
test_mode: bool = False,
annex_name: Optional[str] = None,
dry_run: bool = False,
) -> int:
# Only import htcondor submit-side
import htcondor
import htcondor.dags as dags
working_dir = working_dir.resolve()
local_dir = local_dir.resolve()
working_dir.mkdir(parents=True, exist_ok=True)
local_dir.mkdir(parents=True, exist_ok=True)
outer_dag = make_outer_dag(
direction=direction,
local_dir=local_dir,
remote_dir=remote_dir,
working_dir=working_dir,
requirements=requirements,
unique_id=unique_id,
test_mode=test_mode,
annex_name=annex_name,
dry_run=dry_run,
)
outer_dag_file = dags.write_dag(outer_dag, dag_dir=working_dir, dag_file_name=OUTER_DAG_NAME)
sub = htcondor.Submit.from_dag(str(outer_dag_file), DAG_ARGS)
with change_dir(working_dir):
schedd = htcondor.Schedd()
result = schedd.submit(sub)
return result.cluster()
def make_outer_dag(
direction: TransferDirection,
local_dir: Path,
remote_dir: Path,
working_dir: Path,
requirements: Optional[str],
unique_id: Optional[str],
test_mode: bool,
annex_name: Optional[str],
dry_run: bool,
):
# Only import htcondor submit-side
import htcondor
import htcondor.dags as dags
outer_dag = dags.DAG()
transfer_manifest_path = local_dir / TRANSFER_MANIFEST_FILE_NAME
if requirements:
write_requirements_file(working_dir, requirements)
# copy this script into the working dir for all further use
executable = working_dir / THIS_FILE.name
shutil.copy2(str(THIS_FILE), str(executable))
outer_dag.layer(
name="make_remote_file_manifest",
submit_description=htcondor.Submit(
{
"output": "make_remote_file_manifest.out",
"error": "make_remote_file_manifest.err",
"log": "make_remote_file_manifest.log",
"arguments": "{} {} {}".format(
Commands.MAKE_REMOTE_FILE_MANIFEST,
remote_dir,
"--test-mode" if test_mode else "",
),
"should_transfer_files": "yes",
**shared_submit_descriptors(
executable=executable,
unique_id=unique_id,
requirements=requirements,
annex_name=annex_name,
),
}
),
post=dags.Script(
executable=executable,
arguments=[
Commands.WRITE_INNER_DAG,
direction,
remote_dir,
REMOTE_MANIFEST_FILE_NAME,
local_dir,
"--requirements_file={}".format(REQUIREMENTS_FILE_NAME)
if requirements is not None
else "",
"--unique_id={}".format(unique_id) if unique_id is not None else "",
"--test-mode" if test_mode else "",
"--annex-name={}".format(annex_name) if annex_name is not None else "",
"--dry-run" if dry_run else "",
],
),
).child_subdag(
name="inner",
dag_file=working_dir / INNER_DAG_NAME,
post=dags.Script(
executable=executable,
arguments=[Commands.FINALIZE_TRANSFER_MANIFEST, transfer_manifest_path],
),
)
logging.info("Outer DAG shape:\n{}".format(outer_dag.describe()))
return outer_dag
def write_inner_dag(
direction: TransferDirection,
remote_prefix: Path,
remote_manifest: Path,
local_prefix: Path,
requirements=None,
test_mode: bool = False,
unique_id: Optional[str] = None,
annex_name: Optional[str] = None,
dry_run: bool = False,
):
# Only import htcondor submit-side
import htcondor.dags as dags
logging.info("Generating SUBGDAG for transfer of %s->%s", remote_prefix, local_prefix)
logging.info("Parsing remote file manifest...")
remote_files = parse_file_manifest(remote_prefix, remote_manifest)
logging.info("Generating local file manifest...")
local_manifest_path = Path(LOCAL_MANIFEST_FILE_NAME)
create_file_manifest(local_prefix, local_manifest_path)
local_files = parse_file_manifest(local_prefix, local_manifest_path)
transfer_manifest_path = local_prefix / TRANSFER_MANIFEST_FILE_NAME
transfer_manifest_path.parent.mkdir(parents=True, exist_ok=True)
transfer_manifest_path.touch(exist_ok=True)
# Never transfer the transfer manifest
transfer_manifest_file = transfer_manifest_path.relative_to(local_prefix)
local_files.pop(transfer_manifest_file, None)
remote_files.pop(transfer_manifest_file, None)
if direction is TransferDirection.PULL:
src_files, dest_files = remote_files, local_files
else: # This is a PUSH
src_files, dest_files = local_files, remote_files
files_to_transfer = {
fname for fname, size in src_files.items() if size != dest_files.get(fname, -1)
}
# Check for files that we have already verified, and do not verify them again.
files_verified = set()
for entry, _ in read_manifest(transfer_manifest_path):
if not isinstance(entry, TransferComplete):
continue
files_verified.add(entry.name)
# Verify files that already exist at the source and destination.
files_to_verify = set()
for fname in src_files:
if fname in files_to_transfer:
continue
if fname in dest_files and fname not in files_verified:
files_to_verify.add(fname)
files_to_transfer = sorted(files_to_transfer)
files_to_verify = sorted(files_to_verify)
if dry_run:
files_to_transfer = [os.fspath(p) for p in files_to_transfer]
files_to_verify = [os.fspath(p) for p in files_to_verify]
with Path(DRY_RUN_OUTPUT_FILE_NAME).open(mode="w", encoding="utf-8") as f:
json.dump(
{
"files_to_transfer": files_to_transfer,
"files_to_verify": files_to_verify,
},
f,
sort_keys=True,
indent=2,
)
files_to_transfer = []
files_to_verify = []
if direction is TransferDirection.PULL:
ensure_local_dirs_exist(local_prefix, files_to_transfer)
transfer_cmd_info = make_cmd_info(
direction, files_to_transfer, remote_prefix, local_prefix, transfer_manifest_path
)
verify_cmd_info = make_cmd_info(
direction, files_to_verify, remote_prefix, local_prefix, transfer_manifest_path
)
write_cmd_info(transfer_cmd_info, Path(TRANSFER_COMMANDS_FILE_NAME))
write_cmd_info(verify_cmd_info, Path(VERIFY_COMMANDS_FILE_NAME))
dags.write_dag(
make_inner_dag(
direction=direction,
requirements=requirements,
transfer_cmd_info=transfer_cmd_info,
verify_cmd_info=verify_cmd_info,
unique_id=unique_id,
test_mode=test_mode,
annex_name=annex_name,
),
dag_dir=Path.cwd(), # this will be the working dir of the outer DAG
dag_file_name=INNER_DAG_NAME,
)
bytes_to_transfer = sum(src_files[fname] for fname in files_to_transfer)
bytes_to_verify = sum(src_files[fname] for fname in files_to_verify)
with transfer_manifest_path.open(mode="a", encoding="utf-8") as f:
SyncRequestV2(
direction=direction,
remote_prefix=remote_prefix,
files_at_source=len(src_files),
files_to_transfer=len(files_to_transfer),
bytes_to_transfer=bytes_to_transfer,
files_to_verify=len(files_to_verify),
bytes_to_verify=bytes_to_verify,
timestamp=timestamp(),
dry_run=dry_run,
).write_entry_to(f)
for fname in files_to_transfer:
TransferRequest(name=fname, size=src_files[fname]).write_entry_to(f)
for fname in files_to_verify:
VerifyRequest(name=fname, size=src_files[fname]).write_entry_to(f)
def make_inner_dag(
direction: TransferDirection,
requirements: Optional[str],
transfer_cmd_info: T_CMD_INFO,
verify_cmd_info: T_CMD_INFO,
unique_id: Optional[str] = None,
test_mode: bool = False,
annex_name: Optional[str] = None,
):
# Only import htcondor submit-side
import classad
import htcondor
import htcondor.dags as dags
inner_dag = dags.DAG(max_jobs_by_category={"TRANSFER_JOBS": 1} if test_mode else None)
tof = [METADATA_FILE_NAME]
tor = {METADATA_FILE_NAME: "$(flattened_name).metadata"}
pull_tof = [SANDBOX_FILE_NAME]
pull_tor = {SANDBOX_FILE_NAME: "$(flattened_name)"}
shared_descriptors = shared_submit_descriptors(
unique_id=unique_id, requirements=requirements, annex_name=annex_name
)
inner_dag.layer(
name=direction,
submit_description=htcondor.Submit(
{
"output": "$(flattened_name).out",
"error": "$(flattened_name).err",
"log": "transfer_file.log",
"arguments": classad.quote(
"{} '$(remote_file)'".format(DIRECTION_TO_COMMAND[direction])
),
"should_transfer_files": "yes",
"transfer_input_files": "$(local_file)"
if direction is TransferDirection.PUSH
else "",
"transfer_output_files": ", ".join(
tof + (pull_tof if direction is TransferDirection.PULL else [])
),
"transfer_output_remaps": classad.quote(
" ; ".join(
"{} = {}".format(k, v)
for k, v in {**tor, **(pull_tor if TransferDirection.PULL else {})}.items()
)
),
**shared_descriptors,
}
),
vars=transfer_cmd_info,
post=dags.Script(
executable=THIS_FILE,
arguments=[
Commands.POST_TRANSFER,
"--cmd-info",
TRANSFER_COMMANDS_FILE_NAME,
"--key",
"$JOB",
],
),
)
inner_dag.layer(
name="verify",
submit_description=htcondor.Submit(
{
"output": "$(flattened_name).out",
"error": "$(flattened_name).err",
"log": "verify_file.log",
"arguments": classad.quote(
"{} '$(remote_file)'".format(Commands.GET_REMOTE_METADATA)
),
"should_transfer_files": "yes",
"transfer_output_files": ", ".join(tof),
"transfer_output_remaps": classad.quote(
" ; ".join("{} = {}".format(k, v) for k, v in tor.items())
),
**shared_descriptors,
}
),
vars=verify_cmd_info,
post=dags.Script(
executable=THIS_FILE,
arguments=[
Commands.POST_TRANSFER,
"--cmd-info",
VERIFY_COMMANDS_FILE_NAME,
"--key",
"$JOB",
"--only-verify",
],
),
)
logging.info("Inner DAG shape:\n{}".format(inner_dag.describe()))
return inner_dag
@contextlib.contextmanager
def change_dir(dir):
original = os.getcwd()
os.chdir(dir)
yield
os.chdir(original)
def ensure_local_dirs_exist(prefix: Path, relative_paths: Iterable[Path]) -> None:
for d in {(prefix / relative_path).parent for relative_path in relative_paths}:
d.mkdir(exist_ok=True, parents=True)
def make_cmd_info(
direction: TransferDirection, files, remote_prefix, local_prefix, transfer_manifest_path
):
cmd_info = []
for fname in files:
remote_file = remote_prefix / fname
local_file = local_prefix / fname
flattened_name = flatten_path(fname)
info = {
"direction": direction,
"remote_file": remote_file,
"local_file": local_file,
"local_prefix": local_prefix,
"flattened_name": flattened_name,
"transfer_manifest": transfer_manifest_path,
}
cmd_info.append(info)
return cmd_info
def write_cmd_info(cmd_info: T_CMD_INFO, path: Path) -> None:
write_json(dict(enumerate(map(path_values_to_strings, cmd_info))), path)
def flatten_path(path: Path) -> str:
# Generate a unique file name (technically, unique up to hash
# collisions) that will sort last alphabetically in the working
# directory.
digest = hashlib.sha1(bytes(str(path), "utf-8")).hexdigest()
suffix = path.suffix[:10]
return "zz_transferred_file_{}{}".format(digest, suffix)
def path_values_to_strings(mapping):
return {k: str(v) if isinstance(v, Path) else v for k, v in mapping.items()}
def pull_file(path: Path) -> None:
sandbox_path = Path(os.environ["_CONDOR_SCRATCH_DIR"]) / SANDBOX_FILE_NAME
hash, byte_count = copy_with_hash(src_path=path, dest_path=sandbox_path)
write_metadata_file(path, hash, byte_count)
def push_file(path: Path) -> None:
sandbox_path = Path(os.environ["_CONDOR_SCRATCH_DIR"]) / path.name
hash, byte_count = copy_with_hash(src_path=sandbox_path, dest_path=path)
write_metadata_file(path, hash, byte_count)
def get_remote_metadata(path: Path) -> None:
hash, byte_count = hash_file(path)
write_metadata_file(path, hash, byte_count)
def post_transfer(
direction: TransferDirection,
local_prefix: Path,
local_name: Path,
flattened_name: Path,
metadata_path: Path,
transfer_manifest_path: Path,
only_verify: bool,
) -> None:
logging.info("Running post transfer for %s", local_name)
entry = read_metadata_file(metadata_path)
remote_name = entry.name
remote_digest = entry.digest
remote_size = entry.size
if direction is TransferDirection.PULL and not only_verify:
local_target = flattened_name
else:
local_target = local_name
verify_metadata(local_target, remote_digest, remote_name, remote_size)
if direction is TransferDirection.PULL and not only_verify:
logging.info(
"This is a %s, renaming scratch file %s -> %s", direction, flattened_name, local_name
)
if flattened_name.stat().st_dev == local_name.parent.stat().st_dev:
flattened_name.rename(local_name)
else:
shutil.copy2(str(flattened_name), str(local_name))
verify_metadata(local_name, remote_digest, remote_name, remote_size)
flattened_name.unlink()
with transfer_manifest_path.open(mode="a", encoding="utf-8") as f:
TransferComplete(
name=local_name.relative_to(local_prefix),
digest=remote_digest,
size=remote_size,
timestamp=timestamp(),
).write_entry_to(f)
f.flush()
os.fsync(f.fileno())
for path in (
metadata_path,
metadata_path.with_suffix(".out"),
metadata_path.with_suffix(".err"),
flattened_name,
):
if path.exists():
path.unlink()
def verify_metadata(local_path: Path, remote_digest, remote_path: Path, remote_size: int):
local_size = local_path.stat().st_size
if remote_size != local_size:
raise VerificationFailed(
"Local file size ({} bytes) does not match remote file size ({} bytes)".format(
local_size, remote_size
)
)
hasher, byte_count = hash_file(local_path)
local_digest = hasher.hexdigest()
if remote_digest != local_digest:
raise VerificationFailed(
"Local file {} has digest of {}, which does not match remote file {} (digest {})".format(
local_path, local_digest, remote_path, remote_digest
)
)
logging.info(
"File verification successful: local file (%s) and remote file (%s) have matching digest (%s)",
local_path,
remote_path,
remote_digest,
)
def copy_with_hash(src_path: Path, dest_path: Path) -> Tuple[Any, int]:
tmp_path = dest_path.with_suffix(".tmp")
logging.info("About to copy %s to %s", src_path, tmp_path)
size = src_path.stat().st_size
logging.info("There are %.2f MB to copy", size / MB)
last_log = time.time()
hasher = make_hasher()
tmp_path.parent.mkdir(parents=True, exist_ok=True)
with src_path.open(mode="rb") as src, tmp_path.open(mode="wb") as dest:
buf = src.read(MB)
byte_count = len(buf)
while len(buf) > 0:
hasher.update(buf)
dest.write(buf)
buf = src.read(MB)
now = time.time()
if now - last_log > 5:
logging.info(
"Copied %.2f of %.2f MB; %.1f%% done",
byte_count / MB,
size / MB,
(byte_count / size) * 100,
)
last_log = now
byte_count += len(buf)
logging.info("Copy complete; about to synchronize file to disk")
dest.flush()
os.fsync(dest.fileno())
logging.info("File synchronized to disk")
logging.info("Copying file metadata from {} to {}".format(src_path, tmp_path))
# py3.5 compat; copystat did not take Paths yet
shutil.copystat(str(src_path), str(tmp_path))
logging.info("Copied file metadata")
logging.info("Renaming {} to {}".format(tmp_path, dest_path))
tmp_path.rename(dest_path)
logging.info("Renamed {} to {}".format(tmp_path, dest_path))
return hasher, byte_count
def hash_file(path: Path) -> Tuple[Any, int]:
logging.info("About to hash %s", path)