/
rule_grouping.py
1500 lines (1357 loc) · 90.1 KB
/
rule_grouping.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
# -*- coding: utf-8 -*-
# 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 logging
from collections.abc import Sequence
from datetime import datetime
from typing import TYPE_CHECKING, Any
from sqlalchemy import func
from sqlalchemy.orm.exc import NoResultFound
import rucio.core.did
import rucio.core.lock
import rucio.core.replica
from rucio.common.config import config_get_int
from rucio.common.exception import InsufficientTargetRSEs
from rucio.common.types import InternalScope
from rucio.core import account_counter, rse_counter, request as request_core
from rucio.core.rse_selector import RSESelector
from rucio.core.rse import get_rse, get_rse_attribute, get_rse_name
from rucio.db.sqla import models
from rucio.db.sqla.constants import LockState, RuleGrouping, ReplicaState, RequestType, DIDType, OBSOLETE
from rucio.db.sqla.session import transactional_session
if TYPE_CHECKING:
from sqlalchemy.orm import Session
@transactional_session
def apply_rule_grouping(
datasetfiles: Sequence[dict[str, Any]],
locks: dict[tuple[InternalScope, str], models.ReplicaLock],
replicas: dict[tuple[InternalScope, str], Sequence[models.CollectionReplica]],
source_replicas: dict[tuple[InternalScope, str], Sequence[models.CollectionReplica]],
rseselector: RSESelector, rule: models.ReplicationRule,
preferred_rse_ids: Sequence[str] = [],
source_rses: Sequence[str] = [],
*,
session: "Session"
) -> tuple[dict[str, list[dict[str, models.RSEFileAssociation]]],
dict[str, list[dict[str, models.ReplicaLock]]],
list[dict[str, Any]]]:
"""
Apply rule grouping to files.
:param datasetfiles: Dict holding all datasets and files.
:param locks: Dict holding all locks.
:param replicas: Dict holding all replicas.
:param source_replicas: Dict holding all source_replicas.
:param rseselector: The RSESelector to be used.
:param rule: The rule object.
:param preferred_rse_ids: Preferred RSE's to select.
:param source_rses: RSE ids of eglible source replicas.
:param session: Session of the db.
:returns: Dict of replicas to create, Dict of locks to create, List of transfers to create
:raises: InsufficientQuota, InsufficientTargetRSEs, RSEOverQuota
:attention: This method modifies the contents of the locks and replicas input parameters.
"""
# locks_to_create = {'rse_id': [locks]}
# replicas_to_create = {'rse_id': [replicas]}
# transfers_to_create = [{'dest_rse_id':, 'scope':, 'name':, 'request_type':, 'metadata':}]
if rule.grouping == RuleGrouping.NONE:
replicas_to_create, locks_to_create, \
transfers_to_create = __apply_rule_to_files_none_grouping(datasetfiles=datasetfiles,
locks=locks,
replicas=replicas,
source_replicas=source_replicas,
rseselector=rseselector,
rule=rule,
preferred_rse_ids=preferred_rse_ids,
source_rses=source_rses,
session=session)
elif rule.grouping == RuleGrouping.ALL:
replicas_to_create, locks_to_create, \
transfers_to_create = __apply_rule_to_files_all_grouping(datasetfiles=datasetfiles,
locks=locks,
replicas=replicas,
source_replicas=source_replicas,
rseselector=rseselector,
rule=rule,
preferred_rse_ids=preferred_rse_ids,
source_rses=source_rses,
session=session)
else: # rule.grouping == RuleGrouping.DATASET:
replicas_to_create, locks_to_create, \
transfers_to_create = __apply_rule_to_files_dataset_grouping(datasetfiles=datasetfiles,
locks=locks,
replicas=replicas,
source_replicas=source_replicas,
rseselector=rseselector,
rule=rule,
preferred_rse_ids=preferred_rse_ids,
source_rses=source_rses,
session=session)
return replicas_to_create, locks_to_create, transfers_to_create
@transactional_session
def repair_stuck_locks_and_apply_rule_grouping(
datasetfiles: Sequence[dict[str, Any]],
locks: dict[tuple[InternalScope, str], models.ReplicaLock],
replicas: dict[tuple[InternalScope, str], Any],
source_replicas: dict[tuple[InternalScope, str], Any],
rseselector: RSESelector, rule: models.ReplicationRule,
source_rses: Sequence[str],
*,
session: "Session"
) -> tuple[dict[str, list[dict[str, models.RSEFileAssociation]]],
dict[str, list[dict[str, models.ReplicaLock]]],
list[dict[str, Any]],
dict[str, list[dict[str, models.ReplicaLock]]]]:
"""
Apply rule grouping to files.
:param datasetfiles: Dict holding all datasets and files.
:param locks: Dict holding all locks.
:param replicas: Dict holding all replicas.
:param source_replicas: Dict holding all source_replicas.
:param rseselector: The RSESelector to be used.
:param rule: The rule object.
:param source_rses: RSE ids of eglible source_rses.
:param session: Session of the db.
:returns: List of replicas to create, List of locks to create, List of transfers to create, List of locks to Delete
:raises: InsufficientQuota, InsufficientTargetRSEs
:attention: This method modifies the contents of the locks and replicas input parameters.
"""
# locks_to_create = {'rse_id': [locks]}
# replicas_to_create = {'rse_id': [replicas]}
# transfers_to_create = [{'dest_rse_id':, 'scope':, 'name':, 'request_type':, 'metadata':}]
# locks_to_delete = {'rse_id': [locks]}
if rule.grouping == RuleGrouping.NONE:
replicas_to_create, locks_to_create, transfers_to_create, \
locks_to_delete = __repair_stuck_locks_with_none_grouping(datasetfiles=datasetfiles,
locks=locks,
replicas=replicas,
source_replicas=source_replicas,
rseselector=rseselector,
rule=rule,
source_rses=source_rses,
session=session)
elif rule.grouping == RuleGrouping.ALL:
replicas_to_create, locks_to_create, transfers_to_create, \
locks_to_delete = __repair_stuck_locks_with_all_grouping(datasetfiles=datasetfiles,
locks=locks,
replicas=replicas,
source_replicas=source_replicas,
rseselector=rseselector,
rule=rule,
source_rses=source_rses,
session=session)
else:
replicas_to_create, locks_to_create, transfers_to_create, \
locks_to_delete = __repair_stuck_locks_with_dataset_grouping(datasetfiles=datasetfiles,
locks=locks,
replicas=replicas,
source_replicas=source_replicas,
rseselector=rseselector,
rule=rule,
source_rses=source_rses,
session=session)
return replicas_to_create, locks_to_create, transfers_to_create, locks_to_delete
@transactional_session
def create_transfer_dict(dest_rse_id, request_type, scope, name, rule, lock=None, bytes_=None, md5=None, adler32=None, ds_scope=None, ds_name=None, copy_pin_lifetime=None, activity=None, retry_count=None, *, session: "Session"):
"""
This method creates a transfer dictionary and returns it
:param dest_rse_id: The destination RSE id.
:param request_Type: The request type.
:param scope: The scope of the file.
:param name: The name of the file.
:param rule: The rule responsible for the transfer.
:param lock: The lock responsible for the transfer.
:param bytes_: The filesize of the file in bytes.
:param md5: The md5 checksum of the file.
:param adler32: The adler32 checksum of the file.
:param ds_scope: Dataset the file belongs to.
:param ds_name: Dataset the file belongs to.
:param copy_pin_lifetime: Lifetime in the case of STAGIN requests.
:param activity: Activity to be used.
:param session: Session of the db.
:returns: Request dictionary.
"""
attributes = {'activity': activity or rule.activity or 'default',
'source_replica_expression': rule.source_replica_expression,
'lifetime': copy_pin_lifetime,
'ds_scope': ds_scope,
'ds_name': ds_name,
'bytes': bytes_,
'md5': md5,
'adler32': adler32,
'priority': rule.priority,
# 'allow_tape_source': has_account_attribute(account=rule.account, key='admin', session=session)}
'allow_tape_source': True}
return {'dest_rse_id': dest_rse_id,
'scope': scope,
'name': name,
'rule_id': rule.id,
'attributes': attributes,
'request_type': request_type,
'retry_count': retry_count,
'account': rule.account,
'requested_at': lock.created_at if lock else rule.created_at}
@transactional_session
def __apply_rule_to_files_none_grouping(datasetfiles, locks, replicas, source_replicas, rseselector, rule, preferred_rse_ids=[], source_rses=[], *, session: "Session"):
"""
Apply a rule to files with NONE grouping.
:param datasetfiles: Dict holding all datasets and files.
:param locks: Dict holding all locks.
:param replicas: Dict holding all replicas.
:param source_replicas: Dict holding all source_replicas.
:param rseselector: The RSESelector to be used.
:param rule: The rule object.
:param preferred_rse_ids: Preferred RSE's to select.
:param source_rses: RSE ids of eglible source replicas.
:param session: Session of the db.
:returns: replicas_to_create, locks_to_create, transfers_to_create
:raises: InsufficientAccountLimit, InsufficientTargetRSEs
:attention: This method modifies the contents of the locks and replicas input parameters.
"""
locks_to_create = {} # {'rse_id': [locks]}
replicas_to_create = {} # {'rse_id': [replicas]}
transfers_to_create = [] # [{'dest_rse_id':, 'scope':, 'name':, 'request_type':, 'metadata':}]
for dataset in datasetfiles:
selected_rse_ids = []
for file in dataset['files']:
if len([lock for lock in locks[(file['scope'], file['name'])] if lock.rule_id == rule.id]) == rule.copies:
# Nothing to do as the file already has the requested amount of locks
continue
rse_coverage = {replica.rse_id: file['bytes'] for replica in replicas[(file['scope'], file['name'])] if replica.state in (ReplicaState.AVAILABLE, ReplicaState.COPYING, ReplicaState.TEMPORARY_UNAVAILABLE)}
if len(preferred_rse_ids) == 0:
rse_tuples = rseselector.select_rse(size=file['bytes'],
preferred_rse_ids=rse_coverage.keys(),
blocklist=[replica.rse_id for replica in replicas[(file['scope'], file['name'])] if replica.state == ReplicaState.BEING_DELETED],
existing_rse_size=rse_coverage)
else:
rse_tuples = rseselector.select_rse(size=file['bytes'],
preferred_rse_ids=preferred_rse_ids,
blocklist=[replica.rse_id for replica in replicas[(file['scope'], file['name'])] if replica.state == ReplicaState.BEING_DELETED],
existing_rse_size=rse_coverage)
for rse_tuple in rse_tuples:
if len([lock for lock in locks[(file['scope'], file['name'])] if lock.rule_id == rule.id and lock.rse_id == rse_tuple[0]]) == 1:
# Due to a bug a lock could have been already submitted for this, in that case, skip it
continue
__create_lock_and_replica(file=file,
dataset=dataset,
rule=rule,
rse_id=rse_tuple[0],
staging_area=rse_tuple[1],
availability_write=rse_tuple[2],
locks_to_create=locks_to_create,
locks=locks,
source_rses=source_rses,
replicas_to_create=replicas_to_create,
replicas=replicas,
source_replicas=source_replicas,
transfers_to_create=transfers_to_create,
session=session)
selected_rse_ids.append(rse_tuple[0])
if dataset['scope'] is not None:
for rse_id in list(set(selected_rse_ids)):
try:
session.query(models.CollectionReplica).filter(models.CollectionReplica.scope == dataset['scope'],
models.CollectionReplica.name == dataset['name'],
models.CollectionReplica.rse_id == rse_id).one()
except NoResultFound:
models.CollectionReplica(scope=dataset['scope'],
name=dataset['name'],
did_type=DIDType.DATASET,
rse_id=rse_id,
bytes=0,
length=0,
available_bytes=0,
available_replicas_cnt=0,
state=ReplicaState.UNAVAILABLE).save(session=session)
models.UpdatedCollectionReplica(scope=dataset['scope'],
name=dataset['name'],
did_type=DIDType.DATASET).save(flush=False, session=session)
return replicas_to_create, locks_to_create, transfers_to_create
@transactional_session
def __apply_rule_to_files_all_grouping(datasetfiles, locks, replicas, source_replicas, rseselector, rule, preferred_rse_ids=[], source_rses=[], *, session: "Session"):
"""
Apply a rule to files with ALL grouping.
:param datasetfiles: Dict holding all datasets and files.
:param locks: Dict holding all locks.
:param replicas: Dict holding all replicas.
:param source_replicas: Dict holding all source_replicas.
:param rseselector: The RSESelector to be used.
:param rule: The rule object.
:param preferred_rse_ids: Preferred RSE's to select.
:param source_rses: RSE ids of eglible source replicas.
:param session: Session of the db.
:returns: replicas_to_create, locks_to_create, transfers_to_create
:raises: InsufficientQuota, InsufficientTargetRSEs
:attention: This method modifies the contents of the locks and replicas input parameters.
"""
locks_to_create = {} # {'rse_id': [locks]}
replicas_to_create = {} # {'rse_id': [replicas]}
transfers_to_create = [] # [{'dest_rse_id':, 'scope':, 'name':, 'request_type':, 'metadata':}]
bytes_ = 0
rse_coverage = {} # {'rse_id': coverage }
blocklist = set()
for dataset in datasetfiles:
for file in dataset['files']:
bytes_ += file['bytes']
for replica in replicas[(file['scope'], file['name'])]:
if replica.state == ReplicaState.BEING_DELETED:
blocklist.add(replica.rse_id)
continue
if replica.state in [ReplicaState.AVAILABLE, ReplicaState.COPYING, ReplicaState.TEMPORARY_UNAVAILABLE]:
if replica.rse_id in rse_coverage:
rse_coverage[replica.rse_id] += file['bytes']
else:
rse_coverage[replica.rse_id] = file['bytes']
if not preferred_rse_ids:
rse_tuples = rseselector.select_rse(size=bytes_,
preferred_rse_ids=[x[0] for x in sorted(rse_coverage.items(), key=lambda tup: tup[1], reverse=True)],
blocklist=list(blocklist),
prioritize_order_over_weight=True,
existing_rse_size=rse_coverage)
else:
rse_tuples = rseselector.select_rse(size=bytes_,
preferred_rse_ids=preferred_rse_ids,
blocklist=list(blocklist),
existing_rse_size=rse_coverage)
for rse_tuple in rse_tuples:
for dataset in datasetfiles:
for file in dataset['files']:
if len([lock for lock in locks[(file['scope'], file['name'])] if lock.rule_id == rule.id]) == rule.copies:
continue
if len([lock for lock in locks[(file['scope'], file['name'])] if lock.rule_id == rule.id and lock.rse_id == rse_tuple[0]]) == 1:
# Due to a bug a lock could have been already submitted for this, in that case, skip it
continue
__create_lock_and_replica(file=file,
dataset=dataset,
rule=rule,
rse_id=rse_tuple[0],
staging_area=rse_tuple[1],
availability_write=rse_tuple[2],
locks_to_create=locks_to_create,
locks=locks,
source_rses=source_rses,
replicas_to_create=replicas_to_create,
replicas=replicas,
source_replicas=source_replicas,
transfers_to_create=transfers_to_create,
session=session)
# Add a DatasetLock to the DB
if dataset['scope'] is not None:
try:
session.query(models.DatasetLock).filter(models.DatasetLock.scope == dataset['scope'],
models.DatasetLock.name == dataset['name'],
models.DatasetLock.rule_id == rule.id,
models.DatasetLock.rse_id == rse_tuple[0]).one()
except NoResultFound:
# Get dataset Information
is_open, bytes_, length = True, 0, 0
try:
is_open, bytes_, length = session.query(models.DataIdentifier.is_open,
models.DataIdentifier.bytes,
models.DataIdentifier.length).filter_by(scope=dataset['scope'], name=dataset['name']).one()
except NoResultFound:
pass
models.DatasetLock(scope=dataset['scope'],
name=dataset['name'],
rule_id=rule.id,
rse_id=rse_tuple[0],
state=LockState.REPLICATING,
account=rule.account,
length=length if not is_open else None,
bytes=bytes_ if not is_open else None).save(flush=False, session=session)
# Add a Dataset Replica to the DB
if dataset['scope'] is not None:
try:
session.query(models.CollectionReplica).filter(models.CollectionReplica.scope == dataset['scope'],
models.CollectionReplica.name == dataset['name'],
models.CollectionReplica.rse_id == rse_tuple[0]).one()
except NoResultFound:
models.CollectionReplica(scope=dataset['scope'],
name=dataset['name'],
did_type=DIDType.DATASET,
rse_id=rse_tuple[0],
bytes=0,
length=0,
available_bytes=0,
available_replicas_cnt=0,
state=ReplicaState.UNAVAILABLE).save(session=session)
models.UpdatedCollectionReplica(scope=dataset['scope'],
name=dataset['name'],
did_type=DIDType.DATASET).save(flush=False, session=session)
return replicas_to_create, locks_to_create, transfers_to_create
@transactional_session
def __apply_rule_to_files_dataset_grouping(datasetfiles, locks, replicas, source_replicas, rseselector, rule, preferred_rse_ids=[], source_rses=[], *, session: "Session"):
"""
Apply a rule to files with ALL grouping.
:param datasetfiles: Dict holding all datasets and files.
:param locks: Dict holding all locks.
:param replicas: Dict holding all replicas.
:param source_replicas: Dict holding all source replicas.
:param rseselector: The RSESelector to be used.
:param rule: The rule object.
:param preferred_rse_ids: Preferred RSE's to select.
:param source_rses: RSE ids of eglible source replicas.
:param session: Session of the db.
:returns: replicas_to_create, locks_to_create, transfers_to_create
:raises: InsufficientQuota, InsufficientTargetRSEs
:attention: This method modifies the contents of the locks and replicas input parameters.
"""
locks_to_create = {} # {'rse_id': [locks]}
replicas_to_create = {} # {'rse_id': [replicas]}
transfers_to_create = [] # [{'dest_rse_id':, 'scope':, 'name':, 'request_type':, 'metadata':}]
for dataset in datasetfiles:
bytes_ = sum([file['bytes'] for file in dataset['files']])
rse_coverage = {} # {'rse_id': coverage }
blocklist = set()
for file in dataset['files']:
for replica in replicas[(file['scope'], file['name'])]:
if replica.state == ReplicaState.BEING_DELETED:
blocklist.add(replica.rse_id)
continue
if replica.state in [ReplicaState.AVAILABLE, ReplicaState.COPYING, ReplicaState.TEMPORARY_UNAVAILABLE]:
if replica.rse_id in rse_coverage:
rse_coverage[replica.rse_id] += file['bytes']
else:
rse_coverage[replica.rse_id] = file['bytes']
if not preferred_rse_ids:
rse_tuples = rseselector.select_rse(size=bytes_,
preferred_rse_ids=[x[0] for x in sorted(rse_coverage.items(), key=lambda tup: tup[1], reverse=True)],
blocklist=list(blocklist),
prioritize_order_over_weight=True,
existing_rse_size=rse_coverage)
else:
rse_tuples = rseselector.select_rse(size=bytes_,
preferred_rse_ids=preferred_rse_ids,
blocklist=list(blocklist),
existing_rse_size=rse_coverage)
for rse_tuple in rse_tuples:
for file in dataset['files']:
if len([lock for lock in locks[(file['scope'], file['name'])] if lock.rule_id == rule.id]) == rule.copies:
continue
if len([lock for lock in locks[(file['scope'], file['name'])] if lock.rule_id == rule.id and lock.rse_id == rse_tuple[0]]) == 1:
# Due to a bug a lock could have been already submitted for this, in that case, skip it
continue
__create_lock_and_replica(file=file,
dataset=dataset,
rule=rule,
rse_id=rse_tuple[0],
staging_area=rse_tuple[1],
availability_write=rse_tuple[2],
locks_to_create=locks_to_create,
locks=locks,
source_rses=source_rses,
replicas_to_create=replicas_to_create,
replicas=replicas,
source_replicas=source_replicas,
transfers_to_create=transfers_to_create,
session=session)
# Add a DatasetLock to the DB
if dataset['scope'] is not None:
try:
session.query(models.DatasetLock).filter(models.DatasetLock.scope == dataset['scope'],
models.DatasetLock.name == dataset['name'],
models.DatasetLock.rule_id == rule.id,
models.DatasetLock.rse_id == rse_tuple[0]).one()
except NoResultFound:
# Get dataset Information
is_open, bytes_, length = True, None, None
try:
is_open, bytes_, length = session.query(models.DataIdentifier.is_open,
models.DataIdentifier.bytes,
models.DataIdentifier.length).filter_by(scope=dataset['scope'], name=dataset['name']).one()
except NoResultFound:
pass
models.DatasetLock(scope=dataset['scope'],
name=dataset['name'],
rule_id=rule.id,
rse_id=rse_tuple[0],
state=LockState.REPLICATING,
account=rule.account,
length=length if not is_open else None,
bytes=bytes_ if not is_open else None).save(flush=False, session=session)
# Add a Dataset Replica to the DB
if dataset['scope'] is not None:
try:
session.query(models.CollectionReplica).filter(models.CollectionReplica.scope == dataset['scope'],
models.CollectionReplica.name == dataset['name'],
models.CollectionReplica.rse_id == rse_tuple[0]).one()
except NoResultFound:
models.CollectionReplica(scope=dataset['scope'],
name=dataset['name'],
did_type=DIDType.DATASET,
rse_id=rse_tuple[0],
bytes=0,
length=0,
available_bytes=0,
available_replicas_cnt=0,
state=ReplicaState.UNAVAILABLE).save(session=session)
models.UpdatedCollectionReplica(scope=dataset['scope'],
name=dataset['name'],
did_type=DIDType.DATASET).save(flush=False, session=session)
return replicas_to_create, locks_to_create, transfers_to_create
@transactional_session
def __repair_stuck_locks_with_none_grouping(datasetfiles, locks, replicas, source_replicas, rseselector, rule, source_rses, *, session: "Session", logger=logging.log):
"""
Apply a rule to files with NONE grouping.
:param datasetfiles: Dict holding all datasets and files.
:param locks: Dict holding all locks.
:param replicas: Dict holding all replicas.
:param source_replicas: Dict holding all source_replicas.
:param rseselector: The RSESelector to be used.
:param rule: The rule object.
:param source_rses: RSE ids of eglible source replicas.
:param session: Session of the db.
:param logger: Optional decorated logger that can be passed from the calling daemons or servers.
:returns: replicas_to_create, locks_to_create, transfers_to_create, locks_to_delete
:raises: InsufficientAccountLimit, InsufficientTargetRSEs
:attention: This method modifies the contents of the locks and replicas input parameters.
"""
locks_to_create = {} # {'rse_id': [locks]}
replicas_to_create = {} # {'rse_id': [replicas]}
transfers_to_create = [] # [{'dest_rse_id':, 'scope':, 'name':, 'request_type':, 'metadata':}]
locks_to_delete = {} # {'rse_id': [locks]}
selector_rse_dict = rseselector.get_rse_dictionary()
# Iterate the datasetfiles structure and search for stuck locks
for dataset in datasetfiles:
for file in dataset['files']:
# Iterate and try to repair STUCK locks
for lock in [stucked_lock for stucked_lock in locks[(file['scope'], file['name'])] if stucked_lock.rule_id == rule.id and stucked_lock.state == LockState.STUCK]:
# Check if there are actually already enough locks
if len([good_lock for good_lock in locks[(file['scope'], file['name'])] if good_lock.rule_id == rule.id and good_lock.state != LockState.STUCK]) >= rule.copies:
# Remove the lock
logger(logging.DEBUG, 'There are too many locks for %s:%s for rule %s. Deleting lock', file['scope'], file['name'], str(rule.id))
if lock.rse_id in locks_to_delete:
locks_to_delete[lock.rse_id].append(lock)
else:
locks_to_delete[lock.rse_id] = [lock]
rule.locks_stuck_cnt -= 1
continue
# Check if the replica is AVAILABLE now
if [replica for replica in replicas[(file['scope'], file['name'])] if replica.state in [ReplicaState.AVAILABLE, ReplicaState.TEMPORARY_UNAVAILABLE] and replica.rse_id == lock.rse_id]:
lock.state = LockState.OK
rule.locks_stuck_cnt -= 1
rule.locks_ok_cnt += 1
# Recalculate the replica_lock_cnt
associated_replica = [replica for replica in replicas[(file['scope'], file['name'])] if replica.state in [ReplicaState.AVAILABLE, ReplicaState.TEMPORARY_UNAVAILABLE] and replica.rse_id == lock.rse_id][0]
associated_replica.tombstone = None
associated_replica.lock_cnt = session.query(func.count(models.ReplicaLock.rule_id)).filter_by(scope=associated_replica.scope, name=associated_replica.name, rse_id=lock.rse_id).one()[0]
continue
# Check if this is a STUCK lock due to source_replica filtering
if source_rses:
associated_replica = [replica for replica in replicas[(file['scope'], file['name'])] if replica.rse_id == lock.rse_id][0]
# Check if there is an eglible source replica for this lock
if set(source_replicas.get((file['scope'], file['name']), [])).intersection(source_rses) and (selector_rse_dict.get(lock.rse_id, {}).get('availability_write', True) or rule.ignore_availability):
__update_lock_replica_and_create_transfer(lock=lock,
replica=associated_replica,
rule=rule,
dataset=dataset,
transfers_to_create=transfers_to_create,
session=session)
else:
blocklist_rses = [bl_lock.rse_id for bl_lock in locks[(file['scope'], file['name'])] if bl_lock.rule_id == rule.id]
try:
rse_coverage = {replica.rse_id: file['bytes'] for replica in replicas[(file['scope'], file['name'])] if replica.state in (ReplicaState.AVAILABLE, ReplicaState.COPYING, ReplicaState.TEMPORARY_UNAVAILABLE)}
rse_tuples = rseselector.select_rse(size=file['bytes'],
preferred_rse_ids=rse_coverage.keys(),
copies=1,
blocklist=[replica.rse_id for replica in replicas[(file['scope'], file['name'])] if replica.state == ReplicaState.BEING_DELETED] + blocklist_rses + [lock.rse_id],
existing_rse_size=rse_coverage)
for rse_tuple in rse_tuples:
__create_lock_and_replica(file=file,
dataset=dataset,
rule=rule,
rse_id=rse_tuple[0],
staging_area=rse_tuple[1],
availability_write=rse_tuple[2],
locks_to_create=locks_to_create,
locks=locks,
source_rses=source_rses,
replicas_to_create=replicas_to_create,
replicas=replicas,
source_replicas=source_replicas,
transfers_to_create=transfers_to_create,
session=session)
rule.locks_stuck_cnt -= 1
__set_replica_unavailable(replica=[replica for replica in replicas[(file['scope'], file['name'])] if replica.rse_id == lock.rse_id][0],
session=session)
if lock.rse_id in locks_to_delete:
locks_to_delete[lock.rse_id].append(lock)
else:
locks_to_delete[lock.rse_id] = [lock]
except InsufficientTargetRSEs:
# Just retry the already existing lock
if __is_retry_required(lock=lock, activity=rule.activity) and (selector_rse_dict.get(lock.rse_id, {}).get('availability_write', True) or rule.ignore_availability):
associated_replica = [replica for replica in replicas[(file['scope'], file['name'])] if replica.rse_id == lock.rse_id][0]
__update_lock_replica_and_create_transfer(lock=lock,
replica=associated_replica,
rule=rule,
dataset=dataset,
transfers_to_create=transfers_to_create,
session=session)
return replicas_to_create, locks_to_create, transfers_to_create, locks_to_delete
@transactional_session
def __repair_stuck_locks_with_all_grouping(datasetfiles, locks, replicas, source_replicas, rseselector, rule, source_rses, *, session: "Session", logger=logging.log):
"""
Apply a rule to files with ALL grouping.
:param datasetfiles: Dict holding all datasets and files.
:param locks: Dict holding all locks.
:param replicas: Dict holding all replicas.
:param source_replicas: Dict holding all source_replicas.
:param rseselector: The RSESelector to be used.
:param rule: The rule object.
:param source_rses: RSE ids of eglible source replicas.
:param session: Session of the db.
:param logger: Optional decorated logger that can be passed from the calling daemons or servers.
:returns: replicas_to_create, locks_to_create, transfers_to_create, locks_to_delete
:raises: InsufficientAccountLimit, InsufficientTargetRSEs
:attention: This method modifies the contents of the locks and replicas input parameters.
"""
locks_to_create = {} # {'rse_id': [locks]}
replicas_to_create = {} # {'rse_id': [replicas]}
transfers_to_create = [] # [{'dest_rse_id':, 'scope':, 'name':, 'request_type':, 'metadata':}]
locks_to_delete = {} # {'rse_id': [locks]}
selector_rse_dict = rseselector.get_rse_dictionary()
# Iterate the datasetfiles structure and search for stuck locks
for dataset in datasetfiles:
for file in dataset['files']:
# Iterate and try to repair STUCK locks
for lock in [stucked_lock for stucked_lock in locks[(file['scope'], file['name'])] if stucked_lock.rule_id == rule.id and stucked_lock.state == LockState.STUCK]:
# Check if there are actually already enough locks
if len([good_lock for good_lock in locks[(file['scope'], file['name'])] if good_lock.rule_id == rule.id and good_lock.state != LockState.STUCK]) >= rule.copies:
# Remove the lock
logger(logging.DEBUG, 'There are too many locks for %s:%s for rule %s. Deleting lock', file['scope'], file['name'], str(rule.id))
if lock.rse_id in locks_to_delete:
locks_to_delete[lock.rse_id].append(lock)
else:
locks_to_delete[lock.rse_id] = [lock]
rule.locks_stuck_cnt -= 1
continue
# Check if the replica is AVAILABLE now
if [replica for replica in replicas[(file['scope'], file['name'])] if replica.state in [ReplicaState.AVAILABLE, ReplicaState.TEMPORARY_UNAVAILABLE] and replica.rse_id == lock.rse_id]:
lock.state = LockState.OK
rule.locks_stuck_cnt -= 1
rule.locks_ok_cnt += 1
# Recalculate the replica_lock_cnt
associated_replica = [replica for replica in replicas[(file['scope'], file['name'])] if replica.state in [ReplicaState.AVAILABLE, ReplicaState.TEMPORARY_UNAVAILABLE] and replica.rse_id == lock.rse_id][0]
associated_replica.tombstone = None
associated_replica.lock_cnt = session.query(func.count(models.ReplicaLock.rule_id)).filter_by(scope=associated_replica.scope, name=associated_replica.name, rse_id=lock.rse_id).one()[0]
continue
# Check if this is a STUCK lock due to source_replica filtering
if source_rses:
associated_replica = [replica for replica in replicas[(file['scope'], file['name'])] if replica.rse_id == lock.rse_id][0]
# Check if there is an eglible source replica for this lock
if set(source_replicas.get((file['scope'], file['name']), [])).intersection(source_rses) and (selector_rse_dict.get(lock.rse_id, {}).get('availability_write', True) or rule.ignore_availability):
__update_lock_replica_and_create_transfer(lock=lock,
replica=associated_replica,
rule=rule,
dataset=dataset,
transfers_to_create=transfers_to_create,
session=session)
else:
# Just retry the already existing lock
if __is_retry_required(lock=lock, activity=rule.activity) and (selector_rse_dict.get(lock.rse_id, {}).get('availability_write', True) or rule.ignore_availability):
associated_replica = [replica for replica in replicas[(file['scope'], file['name'])] if replica.rse_id == lock.rse_id][0]
__update_lock_replica_and_create_transfer(lock=lock,
replica=associated_replica,
rule=rule,
dataset=dataset,
transfers_to_create=transfers_to_create,
session=session)
return replicas_to_create, locks_to_create, transfers_to_create, locks_to_delete
@transactional_session
def __repair_stuck_locks_with_dataset_grouping(datasetfiles, locks, replicas, source_replicas, rseselector, rule, source_rses, *, session: "Session", logger=logging.log):
"""
Apply a rule to files with DATASET grouping.
:param datasetfiles: Dict holding all datasets and files.
:param locks: Dict holding all locks.
:param replicas: Dict holding all replicas.
:param source_replicas: Dict holding all source_replicas.
:param rseselector: The RSESelector to be used.
:param rule: The rule object.
:param source_rses: RSE ids of eglible source replicas.
:param session: Session of the db.
:param logger: Optional decorated logger that can be passed from the calling daemons or servers.
:returns: replicas_to_create, locks_to_create, transfers_to_create, locks_to_delete
:raises: InsufficientAccountLimit, InsufficientTargetRSEs
:attention: This method modifies the contents of the locks and replicas input parameters.
"""
locks_to_create = {} # {'rse_id': [locks]}
replicas_to_create = {} # {'rse_id': [replicas]}
transfers_to_create = [] # [{'dest_rse_id':, 'scope':, 'name':, 'request_type':, 'metadata':}]
locks_to_delete = {} # {'rse_id': [locks]}
selector_rse_dict = rseselector.get_rse_dictionary()
# Iterate the datasetfiles structure and search for stuck locks
for dataset in datasetfiles:
for file in dataset['files']:
# Iterate and try to repair STUCK locks
for lock in [stucked_lock for stucked_lock in locks[(file['scope'], file['name'])] if stucked_lock.rule_id == rule.id and stucked_lock.state == LockState.STUCK]:
# Check if there are actually already enough locks
if len([good_lock for good_lock in locks[(file['scope'], file['name'])] if good_lock.rule_id == rule.id and good_lock.state != LockState.STUCK]) >= rule.copies:
# Remove the lock
logger(logging.DEBUG, 'There are too many locks for %s:%s for rule %s. Deleting lock', file['scope'], file['name'], str(rule.id))
if lock.rse_id in locks_to_delete:
locks_to_delete[lock.rse_id].append(lock)
else:
locks_to_delete[lock.rse_id] = [lock]
rule.locks_stuck_cnt -= 1
continue
# Check if the replica is AVAILABLE now
if [replica for replica in replicas[(file['scope'], file['name'])] if replica.state in [ReplicaState.AVAILABLE, ReplicaState.TEMPORARY_UNAVAILABLE] and replica.rse_id == lock.rse_id]:
lock.state = LockState.OK
rule.locks_stuck_cnt -= 1
rule.locks_ok_cnt += 1
# Recalculate the replica_lock_cnt
associated_replica = [replica for replica in replicas[(file['scope'], file['name'])] if replica.state in [ReplicaState.AVAILABLE, ReplicaState.TEMPORARY_UNAVAILABLE] and replica.rse_id == lock.rse_id][0]
associated_replica.tombstone = None
associated_replica.lock_cnt = session.query(func.count(models.ReplicaLock.rule_id)).filter_by(scope=associated_replica.scope, name=associated_replica.name, rse_id=lock.rse_id).one()[0]
continue
# Check if this is a STUCK lock due to source_replica filtering
if source_rses:
associated_replica = [replica for replica in replicas[(file['scope'], file['name'])] if replica.rse_id == lock.rse_id][0]
# Check if there is an eglible source replica for this lock
if set(source_replicas.get((file['scope'], file['name']), [])).intersection(source_rses) and (selector_rse_dict.get(lock.rse_id, {}).get('availability_write', True) or rule.ignore_availability):
__update_lock_replica_and_create_transfer(lock=lock,
replica=associated_replica,
rule=rule,
dataset=dataset,
transfers_to_create=transfers_to_create,
session=session)
else:
# Just retry the already existing lock
if __is_retry_required(lock=lock, activity=rule.activity) and (selector_rse_dict.get(lock.rse_id, {}).get('availability_write', True) or rule.ignore_availability):
associated_replica = [replica for replica in replicas[(file['scope'], file['name'])] if replica.rse_id == lock.rse_id][0]
__update_lock_replica_and_create_transfer(lock=lock,
replica=associated_replica,
rule=rule,
dataset=dataset,
transfers_to_create=transfers_to_create,
session=session)
return replicas_to_create, locks_to_create, transfers_to_create, locks_to_delete
def __is_retry_required(lock, activity):
"""
:param lock: The lock to check.
:param activity: The activity of the rule.
"""
created_at_diff = (datetime.utcnow() - lock.created_at).days * 24 * 3600 + (datetime.utcnow() - lock.created_at).seconds
updated_at_diff = (datetime.utcnow() - lock.updated_at).days * 24 * 3600 + (datetime.utcnow() - lock.updated_at).seconds
if activity == 'Express':
if updated_at_diff > 3600 * 2:
return True
elif activity == 'DebugJudge':
return True
elif created_at_diff < 24 * 3600: # First Day
# Retry every 2 hours
if updated_at_diff > 3600 * 2:
return True
elif created_at_diff < 2 * 24 * 3600: # Second Day
# Retry every 4 hours
if updated_at_diff > 3600 * 4:
return True
elif created_at_diff < 3 * 24 * 3600: # Third Day
# Retry every 6 hours
if updated_at_diff > 3600 * 6:
return True
else: # Four and more days
if updated_at_diff > 3600 * 8:
return True
return False
@transactional_session
def __create_lock_and_replica(file, dataset, rule, rse_id, staging_area, availability_write, locks_to_create, locks, source_rses, replicas_to_create, replicas, source_replicas, transfers_to_create, *, session: "Session", logger=logging.log):
"""
This method creates a lock and if necessary a new replica and fills the corresponding dictionaries.
:param file: File dictionary holding the file information.
:param dataset: Dataset dictionary holding the dataset information.
:param rule: Rule object.
:param rse_id: RSE id the lock and replica should be created at.
:param staging_area: Boolean variable if the RSE is a staging area.
:param availability_write: Boolean variable if the RSE is write enabled.
:param locks_to_create: Dictionary of the locks to create.
:param locks: Dictionary of all locks.
:param source_rses: RSE ids of eglible source replicas.
:param replicas_to_create: Dictionary of the replicas to create.
:param replicas: Dictionary of the replicas.
:param source_replicas: Dictionary of the source replicas.
:param transfers_to_create: List of transfers to create.
:param session: The db session in use.
:param logger: Optional decorated logger that can be passed from the calling daemons or servers.
:returns: True, if the created lock is replicating, False otherwise.
:attention: This method modifies the contents of the locks, locks_to_create, replicas_to_create and replicas input parameters.
"""
if rule.expires_at:
copy_pin_lifetime = rule.expires_at - datetime.utcnow()
copy_pin_lifetime = copy_pin_lifetime.seconds + copy_pin_lifetime.days * 24 * 3600
else:
copy_pin_lifetime = None
# If it is a Staging Area, the pin has to be extended
if staging_area:
transfers_to_create.append(create_transfer_dict(dest_rse_id=rse_id,
request_type=RequestType.STAGEIN,
scope=file['scope'],
name=file['name'],
rule=rule,
bytes_=file['bytes'],
md5=file['md5'],
adler32=file['adler32'],
ds_scope=dataset['scope'],
ds_name=dataset['name'],
copy_pin_lifetime=copy_pin_lifetime,
session=session))
# If staging_required type RSE then set pin to RSE attribute maximum_pin_lifetime
staging_required = get_rse_attribute(rse_id, 'staging_required', session=session)
maximum_pin_lifetime = get_rse_attribute(rse_id, 'maximum_pin_lifetime', session=session)
if staging_required:
if (not copy_pin_lifetime and maximum_pin_lifetime) or (copy_pin_lifetime and maximum_pin_lifetime and copy_pin_lifetime < int(maximum_pin_lifetime)):
copy_pin_lifetime = maximum_pin_lifetime
rse_name = get_rse_name(rse_id=rse_id, session=session)
logger(logging.DEBUG, f'Destination RSE {rse_name} is type staging_required with pin value: {copy_pin_lifetime}')
existing_replicas = [replica for replica in replicas[(file['scope'], file['name'])] if replica.rse_id == rse_id]
if existing_replicas: # A replica already exists (But could be UNAVAILABLE)
existing_replica = existing_replicas[0]
# Replica is fully available -- AVAILABLE
if existing_replica.state in [ReplicaState.AVAILABLE, ReplicaState.TEMPORARY_UNAVAILABLE]:
new_lock = __create_lock(rule=rule,
rse_id=rse_id,
scope=file['scope'],
name=file['name'],
bytes_=file['bytes'],
existing_replica=existing_replica,
state=LockState.OK if not staging_required else LockState.REPLICATING)
if rse_id not in locks_to_create:
locks_to_create[rse_id] = []
locks_to_create[rse_id].append(new_lock)
locks[(file['scope'], file['name'])].append(new_lock)
if not staging_required:
return False
transfers_to_create.append(create_transfer_dict(dest_rse_id=rse_id,
request_type=RequestType.STAGEIN,
scope=file['scope'],
name=file['name'],
rule=rule,
lock=new_lock,
bytes_=file['bytes'],
md5=file['md5'],
adler32=file['adler32'],
ds_scope=dataset['scope'],
ds_name=dataset['name'],
copy_pin_lifetime=copy_pin_lifetime,
session=session))
# Replica is not available -- UNAVAILABLE
elif existing_replica.state == ReplicaState.UNAVAILABLE:
available_source_replica = True
if source_rses:
available_source_replica = False
# Check if there is an eglible source replica for this lock
if set(source_replicas.get((file['scope'], file['name']), [])).intersection(source_rses):
available_source_replica = True
new_lock = __create_lock(rule=rule,
rse_id=rse_id,
scope=file['scope'],
name=file['name'],
bytes_=file['bytes'],
existing_replica=existing_replica,
state=LockState.REPLICATING if (available_source_replica and availability_write) else LockState.STUCK)
if rse_id not in locks_to_create:
locks_to_create[rse_id] = []
locks_to_create[rse_id].append(new_lock)
locks[(file['scope'], file['name'])].append(new_lock)
if not staging_area and not staging_required and available_source_replica and availability_write:
transfers_to_create.append(create_transfer_dict(dest_rse_id=rse_id,
request_type=RequestType.TRANSFER,
scope=file['scope'],
name=file['name'],
rule=rule,
lock=new_lock,
bytes_=file['bytes'],
md5=file['md5'],
adler32=file['adler32'],
ds_scope=dataset['scope'],
ds_name=dataset['name'],
session=session))
return True
return False
# Replica is not available at the rse yet -- COPYING
else:
new_lock = __create_lock(rule=rule,
rse_id=rse_id,
scope=file['scope'],
name=file['name'],
bytes_=file['bytes'],
existing_replica=existing_replica,
state=LockState.REPLICATING)
if rse_id not in locks_to_create:
locks_to_create[rse_id] = []
locks_to_create[rse_id].append(new_lock)
locks[(file['scope'], file['name'])].append(new_lock)
return True
else: # Replica has to be created
available_source_replica = True
if source_rses:
available_source_replica = False
# Check if there is an eglible source replica for this lock
if set(source_replicas.get((file['scope'], file['name']), [])).intersection(source_rses):
available_source_replica = True
new_replica = __create_replica(rse_id=rse_id,
scope=file['scope'],
name=file['name'],
bytes_=file['bytes'],
md5=file['md5'],
adler32=file['adler32'],
state=ReplicaState.COPYING if (available_source_replica and availability_write) else ReplicaState.UNAVAILABLE)
if rse_id not in replicas_to_create:
replicas_to_create[rse_id] = []
replicas_to_create[rse_id].append(new_replica)
replicas[(file['scope'], file['name'])].append(new_replica)
new_lock = __create_lock(rule=rule,
rse_id=rse_id,
scope=file['scope'],
name=file['name'],
bytes_=file['bytes'],
existing_replica=new_replica,
state=LockState.REPLICATING if (available_source_replica and availability_write) else LockState.STUCK)
if rse_id not in locks_to_create: