forked from rucio/rucio
/
transfer.py
1516 lines (1282 loc) · 62.6 KB
/
transfer.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
# Copyright European Organization for Nuclear Research (CERN) since 2012
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import datetime
import logging
import operator
import re
import sys
import time
import traceback
from collections import defaultdict
from typing import TYPE_CHECKING, cast
from dogpile.cache import make_region
from dogpile.cache.api import NoValue
from sqlalchemy import select, update
from sqlalchemy.exc import IntegrityError
from rucio.common import constants
from rucio.common.config import config_get, config_get_list
from rucio.common.constants import SUPPORTED_PROTOCOLS
from rucio.common.exception import InvalidRSEExpression, RequestNotFound, RSEProtocolNotSupported, RucioException, UnsupportedOperation
from rucio.common.utils import construct_surl
from rucio.core import did
from rucio.core import message as message_core
from rucio.core import request as request_core
from rucio.core.account import list_accounts
from rucio.core.monitor import MetricManager
from rucio.core.request import DirectTransfer, RequestSource, RequestWithSources, TransferDestination, transition_request_state
from rucio.core.rse import RseData
from rucio.core.rse_expression_parser import parse_expression
from rucio.db.sqla import models
from rucio.db.sqla.constants import DIDType, RequestState, RequestType, TransferLimitDirection
from rucio.db.sqla.session import read_session, stream_session, transactional_session
from rucio.rse import rsemanager as rsemgr
from rucio.transfertool.bittorrent import BittorrentTransfertool
from rucio.transfertool.fts3 import FTS3Transfertool
from rucio.transfertool.globus import GlobusTransferTool
from rucio.transfertool.mock import MockTransfertool
from rucio.transfertool.transfertool import TransferStatusReport, Transfertool
if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from typing import Any, Optional, Type
from sqlalchemy.orm import Session
from rucio.common.types import InternalAccount
from rucio.core.topology import Topology
from rucio.rse.protocols.protocol import RSEProtocol
LoggerFunction = Callable[..., Any]
"""
The core transfer.py is specifically for handling transfer-requests, thus requests
where the external_id is already known.
Requests accessed by request_id are covered in the core request.py
"""
REGION_ACCOUNTS = make_region().configure('dogpile.cache.memory', expiration_time=600)
METRICS = MetricManager(module=__name__)
WEBDAV_TRANSFER_MODE = config_get('conveyor', 'webdav_transfer_mode', False, None)
DEFAULT_MULTIHOP_TOMBSTONE_DELAY = int(datetime.timedelta(hours=2).total_seconds())
TRANSFERTOOL_CLASSES_BY_NAME: "dict[str, Type[Transfertool]]" = {
FTS3Transfertool.external_name: FTS3Transfertool,
GlobusTransferTool.external_name: GlobusTransferTool,
MockTransfertool.external_name: MockTransfertool,
BittorrentTransfertool.external_name: BittorrentTransfertool,
}
class ProtocolFactory:
"""
Creates and caches protocol objects. Allowing to reuse them.
"""
def __init__(self):
self.protocols = {}
def protocol(self, rse: RseData, scheme: "Optional[str]", operation: str):
protocol_key = '%s_%s_%s' % (operation, rse.id, scheme)
protocol = self.protocols.get(protocol_key)
if not protocol:
protocol = rsemgr.create_protocol(rse.info, operation, scheme)
self.protocols[protocol_key] = protocol
return protocol
class DirectTransferImplementation(DirectTransfer):
"""
The configuration for a direct (non-multi-hop) transfer. It can be a multi-source transfer.
The class wraps the legacy dict-based transfer definition to maintain compatibility with existing code
during the migration.
"""
def __init__(self, source: RequestSource, destination: TransferDestination, rws: RequestWithSources,
protocol_factory: ProtocolFactory, operation_src: str, operation_dest: str):
super().__init__(sources=[source], rws=rws)
self.destination = destination
self.protocol_factory = protocol_factory
self.operation_src = operation_src
self.operation_dest = operation_dest
self._dest_url = None
self._source_urls = {}
def __str__(self):
return '{sources}--{request_id}->{destination}'.format(
sources=','.join([str(s.rse) for s in self.sources]),
request_id=self.rws.request_id or '',
destination=self.dst.rse
)
@property
def src(self) -> RequestSource:
return self.sources[0]
@property
def dst(self) -> TransferDestination:
return self.destination
@property
def dest_url(self) -> str:
if not self._dest_url:
self._dest_url = self._generate_dest_url(self.dst, self.rws, self.protocol_factory, self.operation_dest)
return self._dest_url
def source_url(self, source: RequestSource) -> str:
url = self._source_urls.get(source.rse)
if not url:
self._source_urls[source.rse] = url = self._generate_source_url(
source,
self.dst,
rws=self.rws,
protocol_factory=self.protocol_factory,
operation=self.operation_src
)
return url
def dest_protocol(self) -> "RSEProtocol":
return self.protocol_factory.protocol(self.dst.rse, self.dst.scheme, self.operation_dest)
def source_protocol(self, source: RequestSource) -> "RSEProtocol":
return self.protocol_factory.protocol(source.rse, source.scheme, self.operation_src)
@staticmethod
def __rewrite_source_url(source_url, source_sign_url, dest_sign_url, source_scheme):
"""
Parametrize source url for some special cases of source and destination schemes
"""
if dest_sign_url == 'gcs':
if source_scheme in ['davs', 'https']:
source_url += '?copy_mode=push'
elif dest_sign_url == 's3':
if source_scheme in ['davs', 'https']:
source_url += '?copy_mode=push'
elif WEBDAV_TRANSFER_MODE:
if source_scheme in ['davs', 'https']:
source_url += '?copy_mode=%s' % WEBDAV_TRANSFER_MODE
source_sign_url_map = {'gcs': 'gclouds', 's3': 's3s'}
if source_sign_url in source_sign_url_map:
if source_url[:7] == 'davs://':
source_url = source_sign_url_map[source_sign_url] + source_url[4:]
if source_url[:8] == 'https://':
source_url = source_sign_url_map[source_sign_url] + source_url[5:]
if source_url[:12] == 'srm+https://':
source_url = 'srm' + source_url[9:]
return source_url
@staticmethod
def __rewrite_dest_url(dest_url, dest_sign_url):
"""
Parametrize destination url for some special cases of destination schemes
"""
if dest_sign_url == 'gcs':
dest_url = re.sub('davs', 'gclouds', dest_url)
dest_url = re.sub('https', 'gclouds', dest_url)
elif dest_sign_url == 's3':
dest_url = re.sub('davs', 's3s', dest_url)
dest_url = re.sub('https', 's3s', dest_url)
if dest_url[:12] == 'srm+https://':
dest_url = 'srm' + dest_url[9:]
return dest_url
@classmethod
def _generate_source_url(cls, src: RequestSource, dst: TransferDestination, rws: RequestWithSources, protocol_factory: ProtocolFactory, operation: str):
"""
Generate the source url which will be used as origin to copy the file from request rws towards the given dst endpoint
"""
# Get source protocol
protocol = protocol_factory.protocol(src.rse, src.scheme, operation)
# Compute the source URL
source_sign_url = src.rse.attributes.get('sign_url', None)
dest_sign_url = dst.rse.attributes.get('sign_url', None)
source_url = list(protocol.lfns2pfns(lfns={'scope': rws.scope.external, 'name': rws.name, 'path': src.file_path}).values())[0]
source_url = cls.__rewrite_source_url(source_url, source_sign_url=source_sign_url, dest_sign_url=dest_sign_url, source_scheme=src.scheme)
return source_url
@classmethod
def _generate_dest_url(cls, dst: TransferDestination, rws: RequestWithSources, protocol_factory: ProtocolFactory, operation: str):
"""
Generate the destination url for copying the file of request rws
"""
# Get destination protocol
protocol = protocol_factory.protocol(dst.rse, dst.scheme, operation)
if dst.rse.info['deterministic']:
dest_url = list(protocol.lfns2pfns(lfns={'scope': rws.scope.external, 'name': rws.name}).values())[0]
else:
# compute dest url in case of non deterministic
# naming convention, etc.
dsn = get_dsn(rws.scope, rws.name, rws.attributes.get('dsn', None))
# DQ2 path always starts with /, but prefix might not end with /
naming_convention = dst.rse.attributes.get('naming_convention', None)
dest_path = construct_surl(dsn, rws.scope.external, rws.name, naming_convention)
if dst.rse.is_tape():
if rws.retry_count or rws.activity == 'Recovery':
dest_path = '%s_%i' % (dest_path, int(time.time()))
dest_url = list(protocol.lfns2pfns(lfns={'scope': rws.scope.external, 'name': rws.name, 'path': dest_path}).values())[0]
dest_sign_url = dst.rse.attributes.get('sign_url', None)
dest_url = cls.__rewrite_dest_url(dest_url, dest_sign_url=dest_sign_url)
return dest_url
class StageinTransferImplementation(DirectTransferImplementation):
"""
A definition of a transfer which triggers a stagein operation.
- The source and destination url are identical
- must be from TAPE to non-TAPE RSE
- can only have one source
"""
def __init__(
self,
source: RequestSource,
destination: TransferDestination,
rws: RequestWithSources,
protocol_factory: ProtocolFactory,
operation_src: str,
operation_dest: str
):
if not source.rse.is_tape() or destination.rse.is_tape():
# allow staging_required QoS RSE to be TAPE to TAPE for pin
if not destination.rse.attributes.get('staging_required', None):
raise RucioException("Stageing request {} must be from TAPE to DISK rse. Got {} and {}.".format(rws, source, destination))
super().__init__(source, destination, rws, protocol_factory, operation_src, operation_dest)
@property
def dest_url(self) -> str:
if not self._dest_url:
self._dest_url = self.src.url if self.src.url else self._generate_source_url(self.src,
self.dst,
rws=self.rws,
protocol_factory=self.protocol_factory,
operation=self.operation_dest)
return self._dest_url
def source_url(self, source: RequestSource) -> str:
# Source and dest url is the same for stagein requests
return self.dest_url
def transfer_path_str(transfer_path: "list[DirectTransfer]") -> str:
"""
an implementation of __str__ for a transfer path, which is a list of direct transfers, so not really an object
"""
if not transfer_path:
return 'empty transfer path'
multi_tt = False
if len({hop.rws.transfertool for hop in transfer_path if hop.rws.transfertool}) > 1:
# The path relies on more than one transfertool
multi_tt = True
if len(transfer_path) == 1:
return str(transfer_path[0])
path_str = str(transfer_path[0].src.rse)
for hop in transfer_path:
path_str += '--{request_id}{transfertool}->{destination}'.format(
request_id=hop.rws.request_id or '',
transfertool=':{}'.format(hop.rws.transfertool) if multi_tt else '',
destination=hop.dst.rse,
)
return path_str
@transactional_session
def mark_submitting(
transfer: "DirectTransfer",
external_host: str,
*,
logger: "Callable",
session: "Session",
):
"""
Mark a transfer as submitting
:param transfer: A transfer object
:param session: Database session to use.
"""
log_str = 'PREPARING REQUEST %s DID %s:%s TO SUBMITTING STATE PREVIOUS %s FROM %s TO %s USING %s ' % (transfer.rws.request_id,
transfer.rws.scope,
transfer.rws.name,
transfer.rws.previous_attempt_id,
[transfer.source_url(s) for s in transfer.sources],
transfer.dest_url,
external_host)
logger(logging.DEBUG, "%s", log_str)
stmt = update(
models.Request
).where(
models.Request.id == transfer.rws.request_id,
models.Request.state == RequestState.QUEUED
).execution_options(
synchronize_session=False
).values(
{
'state': RequestState.SUBMITTING,
'external_id': None,
'external_host': external_host,
'dest_url': transfer.dest_url,
'submitted_at': datetime.datetime.utcnow(),
}
)
rowcount = session.execute(stmt).rowcount
if rowcount == 0:
raise RequestNotFound("Failed to prepare transfer: request %s does not exist or is not in queued state" % transfer.rws)
@transactional_session
def ensure_db_sources(
transfer_path: "list[DirectTransfer]",
*,
logger: "Callable",
session: "Session",
):
"""
Ensure the needed DB source objects exist
"""
desired_sources = []
for transfer in transfer_path:
for source in transfer.sources:
common_source_attrs = {
"scope": transfer.rws.scope,
"name": transfer.rws.name,
"rse_id": source.rse.id,
"dest_rse_id": transfer.dst.rse.id,
"ranking": source.ranking,
"bytes": transfer.rws.byte_count,
"url": transfer.source_url(source),
"is_using": True,
}
desired_sources.append({'request_id': transfer.rws.request_id, **common_source_attrs})
if len(transfer_path) > 1 and transfer is not transfer_path[-1]:
# For multihop transfers, each hop's source is also an initial transfer's source.
desired_sources.append({'request_id': transfer_path[-1].rws.request_id, **common_source_attrs})
for source in desired_sources:
stmt = update(
models.Source
).where(
models.Source.request_id == source['request_id'],
models.Source.rse_id == source['rse_id']
).execution_options(
synchronize_session=False
).values(
is_using=True
)
src_rowcount = session.execute(stmt).rowcount
if src_rowcount == 0:
models.Source(**source).save(session=session, flush=False)
@transactional_session
def set_transfers_state(
transfers,
state: "RequestState",
submitted_at: datetime.datetime,
external_host: str,
external_id: str,
transfertool: str,
*,
session: "Session",
logger
):
"""
Update the transfer info of a request.
:param transfers: Dictionary containing request transfer info.
:param session: Database session to use.
"""
logger(logging.INFO, 'Setting state(%s), transfertool(%s), external_host(%s) and eid(%s) for transfers: %s',
state.name, transfertool, external_host, external_id, ', '.join(t.rws.request_id for t in transfers))
try:
for transfer in transfers:
rws = transfer.rws
logger(logging.DEBUG, 'COPYING REQUEST %s DID %s:%s USING %s with state(%s) with eid(%s)' % (rws.request_id, rws.scope, rws.name, external_host, state, external_id))
stmt = update(
models.Request
).where(
models.Request.id == transfer.rws.request_id,
models.Request.state == RequestState.SUBMITTING
).execution_options(
synchronize_session=False
).values(
{
models.Request.state: state,
models.Request.external_id: external_id,
models.Request.external_host: external_host,
models.Request.source_rse_id: transfer.src.rse.id,
models.Request.submitted_at: submitted_at,
models.Request.transfertool: transfertool,
}
)
rowcount = session.execute(stmt).rowcount
if rowcount == 0:
raise RucioException("%s: failed to set transfer state: request doesn't exist or is not in SUBMITTING state" % rws)
stmt = select(
models.DataIdentifier.datatype
).where(
models.DataIdentifier.scope == rws.scope,
models.DataIdentifier.name == rws.name,
)
datatype = session.execute(stmt).scalar_one_or_none()
msg = {'request-id': rws.request_id,
'request-type': rws.request_type,
'scope': rws.scope.external,
'name': rws.name,
'dataset': None,
'datasetScope': None,
'src-rse-id': transfer.src.rse.id,
'src-rse': transfer.src.rse.name,
'dst-rse-id': transfer.dst.rse.id,
'dst-rse': transfer.dst.rse.name,
'state': state,
'activity': rws.activity,
'file-size': rws.byte_count,
'bytes': rws.byte_count,
'checksum-md5': rws.md5,
'checksum-adler': rws.adler32,
'external-id': external_id,
'external-host': external_host,
'queued_at': str(submitted_at),
'datatype': datatype}
if rws.scope.vo != 'def':
msg['vo'] = rws.scope.vo
ds_scope = transfer.rws.attributes.get('ds_scope')
if ds_scope:
msg['datasetScope'] = ds_scope
ds_name = transfer.rws.attributes.get('ds_name')
if ds_name:
msg['dataset'] = ds_name
if msg['request-type']:
transfer_status = '%s-%s' % (msg['request-type'].name, msg['state'].name)
else:
transfer_status = 'transfer-%s' % msg['state']
transfer_status = transfer_status.lower()
message_core.add_message(transfer_status, msg, session=session)
except IntegrityError as error:
raise RucioException(error.args)
logger(logging.DEBUG, 'Finished to register transfer state for %s' % external_id)
@transactional_session
def update_transfer_state(
tt_status_report: TransferStatusReport,
stats_manager: request_core.TransferStatsManager,
*,
session: "Session",
logger=logging.log
):
"""
Used by poller and consumer to update the internal state of requests,
after the response by the external transfertool.
:param tt_status_report: The transfertool status update, retrieved via request.query_request().
:param session: The database session to use.
:param logger: Optional decorated logger that can be passed from the calling daemons or servers.
:returns: The number of updated requests
"""
request_id = tt_status_report.request_id
nb_updated = 0
try:
fields_to_update = tt_status_report.get_db_fields_to_update(session=session, logger=logger)
if not fields_to_update:
request_core.update_request(request_id, raise_on_missing=True, session=session)
return False
else:
logger(logging.INFO, 'UPDATING REQUEST %s FOR %s with changes: %s' % (str(request_id), tt_status_report, fields_to_update))
request = request_core.get_request(request_id, session=session)
updated = transition_request_state(request_id, request=request, session=session, **fields_to_update)
if not updated:
return nb_updated
nb_updated += 1
if tt_status_report.state == RequestState.FAILED:
if request_core.is_intermediate_hop(request):
nb_updated += request_core.handle_failed_intermediate_hop(request, session=session)
if tt_status_report.state:
stats_manager.observe(
src_rse_id=request['source_rse_id'],
dst_rse_id=request['dest_rse_id'],
activity=request['activity'],
state=tt_status_report.state,
file_size=request['bytes'],
submitted_at=request.get('submitted_at', None),
started_at=fields_to_update.get('started_at', None),
transferred_at=fields_to_update.get('transferred_at', None),
session=session,
)
request_core.add_monitor_message(
new_state=tt_status_report.state,
request=request,
additional_fields=tt_status_report.get_monitor_msg_fields(session=session, logger=logger),
session=session
)
return nb_updated
except UnsupportedOperation as error:
logger(logging.WARNING, "Request %s doesn't exist - Error: %s" % (request_id, str(error).replace('\n', '')))
return 0
except Exception:
logger(logging.CRITICAL, "Exception", exc_info=True)
@transactional_session
def mark_transfer_lost(request, *, session: "Session", logger=logging.log):
new_state = RequestState.LOST
reason = "The FTS job lost"
err_msg = request_core.get_transfer_error(new_state, reason)
transition_request_state(request['id'], state=new_state, external_id=request['external_id'], err_msg=err_msg, session=session, logger=logger)
request_core.add_monitor_message(new_state=new_state, request=request, additional_fields={'reason': reason}, session=session)
@METRICS.count_it
@transactional_session
def touch_transfer(external_host, transfer_id, *, session: "Session"):
"""
Update the timestamp of requests in a transfer. Fails silently if the transfer_id does not exist.
:param request_host: Name of the external host.
:param transfer_id: External transfer job id as a string.
:param session: Database session to use.
"""
try:
# don't touch it if it's already touched in 30 seconds
stmt = update(
models.Request
).prefix_with(
"/*+ INDEX(REQUESTS REQUESTS_EXTERNALID_UQ) */", dialect='oracle'
).where(
models.Request.external_id == transfer_id,
models.Request.state == RequestState.SUBMITTED,
models.Request.updated_at < datetime.datetime.utcnow() - datetime.timedelta(seconds=30)
).execution_options(
synchronize_session=False
).values(
updated_at=datetime.datetime.utcnow()
)
session.execute(stmt)
except IntegrityError as error:
raise RucioException(error.args)
def _create_transfer_definitions(
topology: "Topology",
protocol_factory: ProtocolFactory,
rws: RequestWithSources,
sources: "Iterable[RequestSource]",
max_sources: int,
multi_source_sources: "Iterable[RequestSource]",
limit_dest_schemes: list[str],
operation_src: str,
operation_dest: str,
domain: str,
*,
session: "Session",
) -> "dict[RseData, list[DirectTransfer]]":
"""
Find the all paths from sources towards the destination of the given transfer request.
Create the transfer definitions for each point-to-point transfer (multi-source, when possible)
"""
shortest_paths = topology.search_shortest_paths(src_nodes=[s.rse for s in sources], dst_node=rws.dest_rse,
operation_src=operation_src, operation_dest=operation_dest,
domain=domain, limit_dest_schemes=limit_dest_schemes, session=session)
transfers_by_source = {}
sources_by_rse = {s.rse: s for s in sources}
paths_by_source = {sources_by_rse[rse]: path for rse, path in shortest_paths.items()}
for source, list_hops in paths_by_source.items():
transfer_path = []
for hop in list_hops:
hop_src_rse = hop['source_rse']
hop_dst_rse = hop['dest_rse']
src = RequestSource(
rse=hop_src_rse,
file_path=source.file_path if hop_src_rse == source.rse else None,
ranking=source.ranking if hop_src_rse == source.rse else 0,
distance=hop['cumulated_distance'] if hop_src_rse == source.rse else hop['hop_distance'],
scheme=hop['source_scheme'],
)
dst = TransferDestination(
rse=hop_dst_rse,
scheme=hop['dest_scheme'],
)
hop_definition = DirectTransferImplementation(
source=src,
destination=dst,
operation_src=operation_src,
operation_dest=operation_dest,
# keep the current rws for last hop; create a new one for other hops
rws=rws if hop_dst_rse == rws.dest_rse else RequestWithSources(
id_=None,
request_type=rws.request_type,
rule_id=None,
scope=rws.scope,
name=rws.name,
md5=rws.md5,
adler32=rws.adler32,
byte_count=rws.byte_count,
activity=rws.activity,
attributes={
'activity': rws.activity,
'source_replica_expression': None,
'lifetime': None,
'ds_scope': None,
'ds_name': None,
'bytes': rws.byte_count,
'md5': rws.md5,
'adler32': rws.adler32,
'priority': None,
'allow_tape_source': True
},
previous_attempt_id=None,
dest_rse=hop_dst_rse,
account=rws.account,
retry_count=0,
priority=rws.priority,
transfertool=rws.transfertool,
),
protocol_factory=protocol_factory,
)
transfer_path.append(hop_definition)
transfers_by_source[source.rse] = transfer_path
# create multi-source transfers: add additional sources if possible
for transfer_path in transfers_by_source.values():
if len(transfer_path) == 1 and not transfer_path[0].src.rse.is_tape():
# Multiple single-hop DISK rses can be used together in "multi-source" transfers
#
# Try adding additional single-hop DISK rses sources to the transfer
main_source_schemes = __add_compatible_schemes(schemes=[transfer_path[0].dst.scheme], allowed_schemes=SUPPORTED_PROTOCOLS)
added_sources = 0
for source in sorted(multi_source_sources, key=lambda s: (-s.ranking, s.distance)):
if added_sources >= max_sources:
break
edge = topology.edge(source.rse, transfer_path[0].dst.rse)
if not edge:
# There is no direct connection between this source and the destination
continue
if source.rse == transfer_path[0].src.rse:
# This is the main source. Don't add a duplicate.
continue
if source.rse.is_tape():
continue
try:
matching_scheme = rsemgr.find_matching_scheme(
rse_settings_src=source.rse.info,
rse_settings_dest=transfer_path[0].dst.rse.info,
operation_src=operation_src,
operation_dest=operation_dest,
domain=domain,
scheme=main_source_schemes)
except RSEProtocolNotSupported:
continue
transfer_path[0].sources.append(
RequestSource(
rse=source.rse,
file_path=source.file_path,
ranking=source.ranking,
distance=edge.cost,
scheme=matching_scheme[1],
)
)
added_sources += 1
return transfers_by_source
def _create_stagein_definitions(
rws: RequestWithSources,
sources: "Iterable[RequestSource]",
limit_dest_schemes: list[str],
operation_src: str,
operation_dest: str,
protocol_factory: ProtocolFactory,
) -> "dict[RseData, list[DirectTransfer]]":
"""
for each source, create a single-hop transfer path with a one stageing definition inside
"""
transfers_by_source = {
source.rse: [
cast(DirectTransfer, StageinTransferImplementation(
source=RequestSource(
rse=source.rse,
file_path=source.file_path,
url=source.url,
scheme=limit_dest_schemes,
),
destination=TransferDestination(
rse=rws.dest_rse,
scheme=limit_dest_schemes,
),
operation_src=operation_src,
operation_dest=operation_dest,
rws=rws,
protocol_factory=protocol_factory,
))
]
for source in sources
}
return transfers_by_source
def get_dsn(scope, name, dsn):
if dsn:
return dsn
# select a containing dataset
for parent in did.list_parent_dids(scope, name):
if parent['type'] == DIDType.DATASET:
return parent['name']
return 'other'
def __compress_multihops(
paths_by_source: "Iterable[tuple[RequestSource, Sequence[DirectTransfer]]]",
sources: "Iterable[RequestSource]",
) -> "Iterator[tuple[RequestSource, Sequence[DirectTransfer]]]":
# Compress multihop transfers which contain other sources as part of itself.
# For example: multihop A->B->C and B is a source, compress A->B->C into B->C
source_rses = {s.rse.id for s in sources}
seen_source_rses = set()
for source, path in paths_by_source:
if len(path) > 1:
# find the index of the first hop starting from the end which is also a source. Path[0] will always be a source.
last_source_idx = next((idx for idx, hop in reversed(list(enumerate(path))) if hop.src.rse.id in source_rses), (0, None))
if last_source_idx > 0:
path = path[last_source_idx:]
# Deduplicate paths from same source
src_rse_id = path[0].src.rse.id
if src_rse_id not in seen_source_rses:
seen_source_rses.add(src_rse_id)
yield source, path
class TransferPathBuilder:
def __init__(
self,
topology: "Topology",
protocol_factory: ProtocolFactory,
max_sources: int,
preparer_mode: bool = False,
schemes: "Optional[list[str]]" = None,
failover_schemes: "Optional[list[str]]" = None,
requested_source_only: bool = False,
):
self.failover_schemes = failover_schemes if failover_schemes is not None else []
self.schemes = schemes if schemes is not None else []
self.topology = topology
self.preparer_mode = preparer_mode
self.protocol_factory = protocol_factory
self.max_sources = max_sources
self.requested_source_only = requested_source_only
self.definition_by_request_id = {}
def build_or_return_cached(
self,
rws: RequestWithSources,
sources: "Iterable[RequestSource]",
*,
logger: "LoggerFunction" = logging.log,
session: "Session"
) -> "Mapping[RseData, Sequence[DirectTransfer]]":
"""
Warning: The function currently caches the result for the given request and returns it for later calls
with the same request id. As a result: it can return more (or less) sources than what is provided in the
`sources` argument. This is done for performance reasons. As of time of writing, this behavior is not problematic
for the callers of this method.
"""
definition = self.definition_by_request_id.get(rws.request_id)
if definition:
return definition
transfer_schemes = self.schemes
if rws.previous_attempt_id and self.failover_schemes:
transfer_schemes = self.failover_schemes
candidate_sources = sources
if self.requested_source_only and rws.requested_source:
candidate_sources = [rws.requested_source] if rws.requested_source in sources else []
if rws.request_type == RequestType.STAGEIN:
definition = _create_stagein_definitions(
rws=rws,
sources=sources,
limit_dest_schemes=transfer_schemes,
operation_src='read',
operation_dest='write',
protocol_factory=self.protocol_factory
)
else:
definition = _create_transfer_definitions(
topology=self.topology,
rws=rws,
sources=candidate_sources,
max_sources=self.max_sources,
multi_source_sources=[] if self.preparer_mode else sources,
limit_dest_schemes=transfer_schemes,
operation_src='third_party_copy_read',
operation_dest='third_party_copy_write',
domain='wan',
protocol_factory=self.protocol_factory,
session=session
)
self.definition_by_request_id[rws.request_id] = definition
return definition
class _SkipSource:
pass
SKIP_SOURCE = _SkipSource()
class RequestRankingContext:
"""
Helper class used by SourceRankingStrategy. It allows to store additional request-specific
context data and access it when handling a specific source of the given request.
"""
def __init__(self, strategy: "SourceRankingStrategy", rws: "RequestWithSources"):
self.strategy = strategy
self.rws = rws
def apply(self, source: RequestSource) -> "int | _SkipSource":
verdict = self.strategy.apply(self, source)
if verdict is None:
verdict = sys.maxsize
return verdict
class SourceRankingStrategy:
"""
Represents a source ranking strategy. Used to order the sources of a request and decide
which will be the actual source used for the transfer.
If filter_only is True, any value other than SKIP_SOURCE returned by apply() will be ignored.
"""
filter_only: bool = False
def for_request(
self,
rws: RequestWithSources,
sources: "Iterable[RequestSource]",
*,
logger: "LoggerFunction" = logging.log,
session: "Session"
) -> "RequestRankingContext":
return RequestRankingContext(self, rws)
def apply(self, ctx: RequestRankingContext, source: RequestSource) -> "Optional[int | _SkipSource]":
"""
Normally, this function will be called indirectly, via self.for_request(...).apply(source).
It is expected to either return SKIP_SOURCE to signal that this source must be ignored;
or an integer which gives the cost of the given source under the current strategy
(smaller cost: higher priority).
If `None` is returned, it will be interpreted as sys.maxsize (i.e. very low priority).
This is done to avoid requiring an explicit integer in filter-only strategies.
"""
pass
class _ClassNameDescriptor:
"""
Automatically set the external_name of the strategy to the class name.
"""
def __get__(self, obj, objtype=None):
if objtype is not None:
return objtype.__name__
return type(obj).__name__
external_name = _ClassNameDescriptor()
class SourceFilterStrategy(SourceRankingStrategy):
filter_only = True
class EnforceSourceRSEExpression(SourceFilterStrategy):
class _RankingContext(RequestRankingContext):
def __init__(self, strategy: "SourceRankingStrategy", rws: "RequestWithSources", allowed_source_rses: "Optional[set[str]]"):
super().__init__(strategy, rws)
self.allowed_source_rses = allowed_source_rses
def for_request(
self,
rws: RequestWithSources,
sources: "Iterable[RequestSource]",
*,
logger: "LoggerFunction" = logging.log,
session: "Session"
) -> "RequestRankingContext":
# parse source expression
allowed_source_rses = None
source_replica_expression = rws.attributes.get('source_replica_expression', None)
if source_replica_expression:
try:
parsed_rses = parse_expression(source_replica_expression, session=session)
except InvalidRSEExpression as error:
logger(logging.ERROR, "%s: Invalid RSE exception %s: %s", rws.request_id, source_replica_expression, str(error))
allowed_source_rses = set()
else:
allowed_source_rses = {x['id'] for x in parsed_rses}
return self._RankingContext(self, rws, allowed_source_rses)
def apply(self, ctx: RequestRankingContext, source: RequestSource) -> "Optional[int | _SkipSource]":
ctx = cast(EnforceSourceRSEExpression._RankingContext, ctx)
if ctx.allowed_source_rses is not None and source.rse.id not in ctx.allowed_source_rses:
return SKIP_SOURCE
class SkipRestrictedRSEs(SourceFilterStrategy):
def __init__(self, admin_accounts: "Optional[set[InternalAccount]]" = None):
super().__init__()
self.admin_accounts = admin_accounts if admin_accounts is not None else []
def apply(self, ctx: RequestRankingContext, source: RequestSource) -> "Optional[int | _SkipSource]":
if source.rse.attributes.get('restricted_read') and ctx.rws.account not in self.admin_accounts:
return SKIP_SOURCE
class SkipBlocklistedRSEs(SourceFilterStrategy):
def __init__(self, topology: "Topology"):
super().__init__()
self.topology = topology
def apply(self, ctx: RequestRankingContext, source: RequestSource) -> "Optional[int | _SkipSource]":
# Ignore blocklisted RSEs
if not source.rse.columns['availability_read'] and not self.topology.ignore_availability:
return SKIP_SOURCE