-
Notifications
You must be signed in to change notification settings - Fork 302
/
replica.py
4479 lines (3909 loc) · 217 KB
/
replica.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 copy
import heapq
import logging
import math
import random
from collections import defaultdict, namedtuple
from curses.ascii import isprint
from datetime import datetime, timedelta
from hashlib import sha256
from itertools import groupby
from json import dumps
from re import match
from struct import unpack
from typing import TYPE_CHECKING
from traceback import format_exc
import requests
from dogpile.cache.api import NO_VALUE
from sqlalchemy import func, and_, or_, exists, not_, update, delete, insert, union
from sqlalchemy.exc import DatabaseError, IntegrityError
from sqlalchemy.orm import aliased
from sqlalchemy.orm.exc import FlushError, NoResultFound
from sqlalchemy.sql import label
from sqlalchemy.sql.expression import case, select, text, false, true, null, literal, literal_column
import rucio.core.did
import rucio.core.lock
from rucio.common import exception
from rucio.common.cache import make_region_memcached
from rucio.common.config import config_get, config_get_bool
from rucio.common.types import InternalScope
from rucio.common.utils import chunks, clean_surls, str_to_date, add_url_query
from rucio.common.constants import SuspiciousAvailability
from rucio.core.credential import get_signed_url
from rucio.core import config as config_core
from rucio.core.message import add_messages
from rucio.core.monitor import MetricManager
from rucio.core.rse import get_rse, get_rse_name, get_rse_attribute, get_rse_vo, list_rses
from rucio.core.rse_counter import decrease, increase
from rucio.core.rse_expression_parser import parse_expression
from rucio.db.sqla import models, filter_thread_work
from rucio.db.sqla.constants import (DIDType, ReplicaState, OBSOLETE, DIDAvailability,
BadFilesStatus, RuleState, BadPFNStatus)
from rucio.db.sqla.session import (read_session, stream_session, transactional_session,
DEFAULT_SCHEMA_NAME, BASE)
from rucio.db.sqla.util import temp_table_mngr
from rucio.rse import rsemanager as rsemgr
if TYPE_CHECKING:
from rucio.rse.protocols.protocol import RSEProtocol
from typing import Any, Dict, List, Optional, Sequence, Tuple
from sqlalchemy.orm import Session
REGION = make_region_memcached(expiration_time=60)
METRICS = MetricManager(module=__name__)
ScopeName = namedtuple('ScopeName', ['scope', 'name'])
Association = namedtuple('Association', ['scope', 'name', 'child_scope', 'child_name'])
@read_session
def get_bad_replicas_summary(rse_expression=None, from_date=None, to_date=None, filter_=None, *, session: "Session"):
"""
List the bad file replicas summary. Method used by the rucio-ui.
:param rse_expression: The RSE expression.
:param from_date: The start date.
:param to_date: The end date.
:param filter_: Dictionary of attributes by which the RSE results should be filtered. e.g.: {'availability_write': True}
:param session: The database session in use.
"""
result = []
incidents = {}
rse_clause = []
if rse_expression:
for rse in parse_expression(expression=rse_expression, filter_=filter_, session=session):
rse_clause.append(models.BadReplicas.rse_id == rse['id'])
elif filter_:
# Ensure we limit results to current VO even if we don't specify an RSE expression
for rse in list_rses(filters=filter_, session=session):
rse_clause.append(models.BadReplicas.rse_id == rse['id'])
if session.bind.dialect.name == 'oracle':
to_days = func.trunc(models.BadReplicas.created_at, str('DD'))
elif session.bind.dialect.name == 'mysql':
to_days = func.date(models.BadReplicas.created_at)
elif session.bind.dialect.name == 'postgresql':
to_days = func.date_trunc('day', models.BadReplicas.created_at)
else:
to_days = func.strftime(models.BadReplicas.created_at, '%Y-%m-%d')
query = session.query(func.count(), to_days, models.BadReplicas.rse_id, models.BadReplicas.state, models.BadReplicas.reason)
# To be added : HINTS
if rse_clause != []:
query = query.filter(or_(*rse_clause))
if from_date:
query = query.filter(models.BadReplicas.created_at > from_date)
if to_date:
query = query.filter(models.BadReplicas.created_at < to_date)
summary = query.group_by(to_days, models.BadReplicas.rse_id, models.BadReplicas.reason, models.BadReplicas.state).all()
for row in summary:
if (row[2], row[1], row[4]) not in incidents:
incidents[(row[2], row[1], row[4])] = {}
incidents[(row[2], row[1], row[4])][str(row[3].name)] = row[0]
for incident in incidents:
res = incidents[incident]
res['rse_id'] = incident[0]
res['rse'] = get_rse_name(rse_id=incident[0], session=session)
res['created_at'] = incident[1]
res['reason'] = incident[2]
result.append(res)
return result
@read_session
def __exist_replicas(rse_id, replicas, *, session: "Session"):
"""
Internal method to check if a replica exists at a given site.
:param rse_id: The RSE id.
:param replicas: A list of tuples [(<scope>, <name>, <path>}) with either :
- scope and name are None and path not None
- scope and name are not None and path is None
:param session: The database session in use.
:returns: A list of tuple (<scope>, <name>, <path>, <exists>, <already_declared>, <bytes>)
where
- <exists> is a boolean that identifies if the replica exists
- <already_declared> is a boolean that identifies if the replica is already declared bad
"""
return_list = []
path_clause = []
did_clause = []
for scope, name, path in replicas:
if path:
path_clause.append(models.RSEFileAssociation.path == path)
if path.startswith('/'):
path_clause.append(models.RSEFileAssociation.path == path[1:])
else:
path_clause.append(models.RSEFileAssociation.path == '/%s' % path)
else:
did_clause.append(and_(models.RSEFileAssociation.scope == scope,
models.RSEFileAssociation.name == name))
for clause in [path_clause, did_clause]:
if clause:
for chunk in chunks(clause, 10):
query = session.query(models.RSEFileAssociation.path,
models.RSEFileAssociation.scope,
models.RSEFileAssociation.name,
models.RSEFileAssociation.rse_id,
models.RSEFileAssociation.bytes,
func.max(case((models.BadReplicas.state == BadFilesStatus.SUSPICIOUS, 0),
(models.BadReplicas.state == BadFilesStatus.BAD, 1),
else_=0))).\
with_hint(models.RSEFileAssociation, "INDEX(REPLICAS REPLICAS_PATH_IDX", 'oracle').\
outerjoin(models.BadReplicas,
and_(models.RSEFileAssociation.scope == models.BadReplicas.scope,
models.RSEFileAssociation.name == models.BadReplicas.name,
models.RSEFileAssociation.rse_id == models.BadReplicas.rse_id)).\
filter(models.RSEFileAssociation.rse_id == rse_id).filter(or_(*chunk)).\
group_by(models.RSEFileAssociation.path,
models.RSEFileAssociation.scope,
models.RSEFileAssociation.name,
models.RSEFileAssociation.rse_id,
models.RSEFileAssociation.bytes)
for path, scope, name, rse_id, size, state in query.all():
if (scope, name, path) in replicas:
replicas.remove((scope, name, path))
if (None, None, path) in replicas:
replicas.remove((None, None, path))
if (scope, name, None) in replicas:
replicas.remove((scope, name, None))
already_declared = False
if state == 1:
already_declared = True
return_list.append((scope, name, path, True, already_declared, size))
for scope, name, path in replicas:
return_list.append((scope, name, path, False, False, None))
return return_list
@read_session
def list_bad_replicas_status(state=BadFilesStatus.BAD, rse_id=None, younger_than=None, older_than=None, limit=None, list_pfns=False, vo='def', *, session: "Session"):
"""
List the bad file replicas history states. Method used by the rucio-ui.
:param state: The state of the file (SUSPICIOUS or BAD).
:param rse_id: The RSE id.
:param younger_than: datetime object to select bad replicas younger than this date.
:param older_than: datetime object to select bad replicas older than this date.
:param limit: The maximum number of replicas returned.
:param vo: The VO to find replicas from.
:param session: The database session in use.
"""
result = []
query = session.query(models.BadReplicas.scope, models.BadReplicas.name, models.BadReplicas.rse_id, models.BadReplicas.state, models.BadReplicas.created_at, models.BadReplicas.updated_at)
if state:
query = query.filter(models.BadReplicas.state == state)
if rse_id:
query = query.filter(models.BadReplicas.rse_id == rse_id)
if younger_than:
query = query.filter(models.BadReplicas.created_at >= younger_than)
if older_than:
query = query.filter(models.BadReplicas.created_at <= older_than)
if limit:
query = query.limit(limit)
for badfile in query.yield_per(1000):
if badfile.scope.vo == vo:
if list_pfns:
result.append({'scope': badfile.scope, 'name': badfile.name, 'type': DIDType.FILE})
else:
result.append({'scope': badfile.scope, 'name': badfile.name, 'rse': get_rse_name(rse_id=badfile.rse_id, session=session), 'rse_id': badfile.rse_id, 'state': badfile.state, 'created_at': badfile.created_at, 'updated_at': badfile.updated_at})
if list_pfns:
reps = []
for rep in list_replicas(result, schemes=None, unavailable=False, request_id=None, ignore_availability=True, all_states=True, session=session):
pfn = None
if rse_id in rep['rses'] and rep['rses'][rse_id]:
pfn = rep['rses'][rse_id][0]
if pfn and pfn not in reps:
reps.append(pfn)
else:
reps.extend([item for row in rep['rses'].values() for item in row])
list(set(reps))
result = reps
return result
@transactional_session
def __declare_bad_file_replicas(pfns, rse_id, reason, issuer, status=BadFilesStatus.BAD, scheme='srm', force=False, *, session: "Session"):
"""
Declare a list of bad replicas.
:param pfns: Either a list of PFNs (string) or a list of replicas {'scope': <scope>, 'name': <name>, 'rse_id': <rse_id>}.
:param rse_id: The RSE id.
:param reason: The reason of the loss.
:param issuer: The issuer account.
:param status: Either BAD or SUSPICIOUS.
:param scheme: The scheme of the PFNs.
:param force: boolean, if declaring BAD replica, ignore existing replica status in the bad_replicas table. Default: False
:param session: The database session in use.
"""
unknown_replicas = []
replicas = []
path_pfn_dict = {}
if len(pfns) > 0 and type(pfns[0]) is str:
# If pfns is a list of PFNs, the scope and names need to be extracted from the path
rse_info = rsemgr.get_rse_info(rse_id=rse_id, session=session)
proto = rsemgr.create_protocol(rse_info, 'read', scheme=scheme)
if rse_info['deterministic']:
# TBD : In case of deterministic RSE, call the extract_scope_from_path method
parsed_pfn = proto.parse_pfns(pfns=pfns)
for pfn in parsed_pfn:
# WARNING : this part is ATLAS specific and must be changed
path = parsed_pfn[pfn]['path']
if path.startswith('/user') or path.startswith('/group'):
scope = '%s.%s' % (path.split('/')[1], path.split('/')[2])
name = parsed_pfn[pfn]['name']
elif path.startswith('/'):
scope = path.split('/')[1]
name = parsed_pfn[pfn]['name']
else:
scope = path.split('/')[0]
name = parsed_pfn[pfn]['name']
scope = InternalScope(scope, vo=issuer.vo)
replicas.append({'scope': scope, 'name': name, 'rse_id': rse_id, 'state': status})
path = '%s%s' % (parsed_pfn[pfn]['path'], parsed_pfn[pfn]['name'])
path_pfn_dict[path] = pfn
else:
# For non-deterministic RSEs use the path + rse_id to extract the scope
parsed_pfn = proto.parse_pfns(pfns=pfns)
for pfn in parsed_pfn:
path = '%s%s' % (parsed_pfn[pfn]['path'], parsed_pfn[pfn]['name'])
replicas.append({'scope': None, 'name': None, 'rse_id': rse_id, 'path': path, 'state': status})
path_pfn_dict[path] = pfn
else:
# If pfns is a list of replicas, just use scope, name and rse_id
for pfn in pfns:
replicas.append({'scope': pfn['scope'], 'name': pfn['name'], 'rse_id': rse_id, 'state': status})
replicas_list = []
for replica in replicas:
scope, name, rse_id, path = replica['scope'], replica['name'], replica['rse_id'], replica.get('path', None)
replicas_list.append((scope, name, path))
bad_replicas_to_update = []
for scope, name, path, __exists, already_declared, size in __exist_replicas(rse_id=rse_id, replicas=replicas_list, session=session):
declared = False
if __exists:
if status == BadFilesStatus.BAD and (force or not already_declared):
bad_replicas_to_update.append({'scope': scope, 'name': name, 'rse_id': rse_id, 'state': ReplicaState.BAD})
declared = True
if status == BadFilesStatus.SUSPICIOUS or status == BadFilesStatus.BAD and not already_declared:
new_bad_replica = models.BadReplicas(scope=scope, name=name, rse_id=rse_id, reason=reason, state=status, account=issuer, bytes=size)
new_bad_replica.save(session=session, flush=False)
declared = True
if not declared:
if already_declared:
unknown_replicas.append('%s %s' % (path_pfn_dict.get(path, '%s:%s' % (scope, name)), 'Already declared'))
elif path:
no_hidden_char = True
for char in str(path):
if not isprint(char):
unknown_replicas.append('%s %s' % (path, 'PFN contains hidden chars'))
no_hidden_char = False
break
if no_hidden_char:
unknown_replicas.append('%s %s' % (path_pfn_dict[path], 'Unknown replica'))
if status == BadFilesStatus.BAD:
# For BAD file, we modify the replica state, not for suspicious
try:
# there shouldn't be any exceptions since all replicas exist
update_replicas_states(bad_replicas_to_update, session=session)
except exception.UnsupportedOperation:
raise exception.ReplicaNotFound("One or several replicas don't exist.")
try:
session.flush()
except IntegrityError as error:
raise exception.RucioException(error.args)
except DatabaseError as error:
raise exception.RucioException(error.args)
except FlushError as error:
raise exception.RucioException(error.args)
return unknown_replicas
@transactional_session
def add_bad_dids(dids, rse_id, reason, issuer, state=BadFilesStatus.BAD, *, session: "Session"):
"""
Declare a list of bad replicas.
:param dids: The list of DIDs.
:param rse_id: The RSE id.
:param reason: The reason of the loss.
:param issuer: The issuer account.
:param state: BadFilesStatus.BAD
:param session: The database session in use.
"""
unknown_replicas = []
replicas_for_update = []
replicas_list = []
for did in dids:
scope = InternalScope(did['scope'], vo=issuer.vo)
name = did['name']
replicas_list.append((scope, name, None))
for scope, name, _, __exists, already_declared, size in __exist_replicas(rse_id=rse_id, replicas=replicas_list, session=session):
if __exists and not already_declared:
replicas_for_update.append({'scope': scope, 'name': name, 'rse_id': rse_id, 'state': ReplicaState.BAD})
new_bad_replica = models.BadReplicas(scope=scope, name=name, rse_id=rse_id, reason=reason, state=state,
account=issuer, bytes=size)
new_bad_replica.save(session=session, flush=False)
session.query(models.Source).filter_by(scope=scope, name=name,
rse_id=rse_id).delete(synchronize_session=False)
else:
if already_declared:
unknown_replicas.append('%s:%s %s' % (did['scope'], name, 'Already declared'))
else:
unknown_replicas.append('%s:%s %s' % (did['scope'], name, 'Unknown replica'))
if state == BadFilesStatus.BAD:
try:
update_replicas_states(replicas_for_update, session=session)
except exception.UnsupportedOperation:
raise exception.ReplicaNotFound("One or several replicas don't exist.")
try:
session.flush()
except (IntegrityError, DatabaseError, FlushError) as error:
raise exception.RucioException(error.args)
return unknown_replicas
@transactional_session
def declare_bad_file_replicas(replicas: list, reason: str, issuer, status=BadFilesStatus.BAD, force: bool = False, *,
session: "Session"):
"""
Declare a list of bad replicas.
:param replicas: Either a list of PFNs (string) or a list of replicas {'scope': <scope>, 'name': <name>, 'rse_id': <rse_id>}.
:param reason: The reason of the loss.
:param issuer: The issuer account.
:param status: The status of the file (SUSPICIOUS or BAD).
:param force: boolean, if declaring BAD replica, ignore existing replica status in the bad_replicas table. Default: False
:param session: The database session in use.
:returns: Dictionary {rse_id -> [replicas failed to declare with errors]}
"""
unknown_replicas = {}
if replicas:
type_ = type(replicas[0])
files_to_declare = {}
scheme = None
for replica in replicas:
if not isinstance(replica, type_):
raise exception.InvalidType('Replicas must be specified either as a list of string or a list of dicts')
if type_ == str:
scheme, files_to_declare, unknown_replicas = get_pfn_to_rse(replicas, vo=issuer.vo, session=session)
else:
for replica in replicas:
rse_id = replica['rse_id']
files_to_declare.setdefault(rse_id, []).append(replica)
for rse_id in files_to_declare:
notdeclared = __declare_bad_file_replicas(files_to_declare[rse_id], rse_id, reason, issuer,
status=status, scheme=scheme,
force=force, session=session)
if notdeclared:
unknown_replicas[rse_id] = notdeclared
return unknown_replicas
@read_session
def get_pfn_to_rse(pfns, vo='def', *, session: "Session"):
"""
Get the RSE associated to a list of PFNs.
:param pfns: The list of pfn.
:param vo: The VO to find RSEs at.
:param session: The database session in use.
:returns: a tuple : scheme, {rse1 : [pfn1, pfn2, ...], rse2: [pfn3, pfn4, ...]}, {'unknown': [pfn5, pfn6, ...]}.
"""
unknown_replicas = {}
storage_elements = []
se_condition = []
dict_rse = {}
surls = clean_surls(pfns)
scheme = surls[0].split(':')[0] if surls else None
for surl in surls:
if surl.split(':')[0] != scheme:
raise exception.InvalidType('The PFNs specified must have the same protocol')
split_se = surl.split('/')[2].split(':')
storage_element = split_se[0]
if storage_element not in storage_elements:
storage_elements.append(storage_element)
se_condition.append(models.RSEProtocols.hostname == storage_element)
query = session.query(models.RSEProtocols.rse_id,
models.RSEProtocols.scheme,
models.RSEProtocols.hostname,
models.RSEProtocols.port,
models.RSEProtocols.prefix).\
join(models.RSE, models.RSE.id == models.RSEProtocols.rse_id).\
filter(and_(or_(*se_condition), models.RSEProtocols.scheme == scheme)).\
filter(models.RSE.deleted == false()).\
filter(models.RSE.staging_area == false())
protocols = {}
for rse_id, protocol, hostname, port, prefix in query.yield_per(10000):
if rse_id not in protocols:
protocols[rse_id] = []
protocols[rse_id].append('%s://%s:%s%s' % (protocol, hostname, port, prefix))
if '%s://%s%s' % (protocol, hostname, prefix) not in protocols[rse_id]:
protocols[rse_id].append('%s://%s%s' % (protocol, hostname, prefix))
hint = None
for surl in surls:
if hint:
for pattern in protocols[hint]:
if surl.find(pattern) > -1:
dict_rse[hint].append(surl)
else:
mult_rse_match = 0
for rse_id in protocols:
for pattern in protocols[rse_id]:
if surl.find(pattern) > -1 and get_rse_vo(rse_id=rse_id, session=session) == vo:
mult_rse_match += 1
if mult_rse_match > 1:
print('ERROR, multiple matches : %s at %s' % (surl, rse_id))
raise exception.RucioException('ERROR, multiple matches : %s at %s' % (surl, get_rse_name(rse_id=rse_id, session=session)))
hint = rse_id
if hint not in dict_rse:
dict_rse[hint] = []
dict_rse[hint].append(surl)
if mult_rse_match == 0:
if 'unknown' not in unknown_replicas:
unknown_replicas['unknown'] = []
unknown_replicas['unknown'].append(surl)
return scheme, dict_rse, unknown_replicas
@read_session
def get_bad_replicas_backlog(*, session: "Session"):
"""
Get the replica backlog by RSE.
:param session: The database session in use.
:returns: a list of dictionary {'rse_id': cnt_bad_replicas}.
"""
schema_dot = '%s.' % DEFAULT_SCHEMA_NAME if DEFAULT_SCHEMA_NAME else ''
if session.bind.dialect.name == 'oracle':
# The filter(text...)) is needed otherwise, SQLA uses bind variables and the index is not used.
query = session.query(func.count(models.RSEFileAssociation.rse_id), models.RSEFileAssociation.rse_id).\
with_hint(models.RSEFileAssociation, "INDEX(REPLICAS REPLICAS_STATE_IDX)", 'oracle').\
filter(text("CASE WHEN (%sreplicas.state != 'A') THEN %sreplicas.rse_id END IS NOT NULL" % (schema_dot,
schema_dot))). \
filter(models.RSEFileAssociation.state == ReplicaState.BAD)
else:
query = session.query(func.count(models.RSEFileAssociation.rse_id), models.RSEFileAssociation.rse_id).\
filter(models.RSEFileAssociation.state == ReplicaState.BAD)
query = query.join(models.DataIdentifier,
and_(models.DataIdentifier.scope == models.RSEFileAssociation.scope,
models.DataIdentifier.name == models.RSEFileAssociation.name)).\
filter(models.DataIdentifier.availability != DIDAvailability.LOST).\
group_by(models.RSEFileAssociation.rse_id)
result = dict()
for cnt, rse_id in query.all():
result[rse_id] = cnt
return result
@read_session
def list_bad_replicas(limit=10000, thread=None, total_threads=None, rses=None, *, session: "Session"):
"""
List RSE File replicas with no locks.
:param limit: The maximum number of replicas returned.
:param thread: The assigned thread for this necromancer.
:param total_threads: The total number of threads of all necromancers.
:param session: The database session in use.
:returns: a list of dictionary {'scope' scope, 'name': name, 'rse_id': rse_id, 'rse': rse}.
"""
schema_dot = '%s.' % DEFAULT_SCHEMA_NAME if DEFAULT_SCHEMA_NAME else ''
if session.bind.dialect.name == 'oracle':
# The filter(text...)) is needed otherwise, SQLA uses bind variables and the index is not used.
query = session.query(models.RSEFileAssociation.scope,
models.RSEFileAssociation.name,
models.RSEFileAssociation.rse_id).\
with_hint(models.RSEFileAssociation, "INDEX(REPLICAS REPLICAS_STATE_IDX)", 'oracle').\
filter(text("CASE WHEN (%sreplicas.state != 'A') THEN %sreplicas.rse_id END IS NOT NULL" % (schema_dot,
schema_dot))). \
filter(models.RSEFileAssociation.state == ReplicaState.BAD)
else:
query = session.query(models.RSEFileAssociation.scope,
models.RSEFileAssociation.name,
models.RSEFileAssociation.rse_id).\
filter(models.RSEFileAssociation.state == ReplicaState.BAD)
query = filter_thread_work(session=session, query=query, total_threads=total_threads, thread_id=thread, hash_variable='%sreplicas.name' % (schema_dot))
query = query.join(models.DataIdentifier,
and_(models.DataIdentifier.scope == models.RSEFileAssociation.scope,
models.DataIdentifier.name == models.RSEFileAssociation.name)).\
filter(models.DataIdentifier.availability != DIDAvailability.LOST)
if rses:
rse_clause = list()
for rse in rses:
rse_clause.append(models.RSEFileAssociation.rse_id == rse['id'])
query = query.filter(or_(*rse_clause))
query = query.limit(limit)
rows = []
for scope, name, rse_id in query.yield_per(1000):
rows.append({'scope': scope, 'name': name, 'rse_id': rse_id, 'rse': get_rse_name(rse_id=rse_id, session=session)})
return rows
@stream_session
def get_did_from_pfns(pfns, rse_id=None, vo='def', *, session: "Session"):
"""
Get the DIDs associated to a PFN on one given RSE
:param pfns: The list of PFNs.
:param rse_id: The RSE id.
:param vo: The VO to get DIDs from.
:param session: The database session in use.
:returns: A dictionary {pfn: {'scope': scope, 'name': name}}
"""
dict_rse = {}
if not rse_id:
scheme, dict_rse, unknown_replicas = get_pfn_to_rse(pfns, vo=vo, session=session)
if unknown_replicas:
raise Exception
else:
scheme = 'srm'
dict_rse[rse_id] = pfns
for rse_id in dict_rse:
pfns = dict_rse[rse_id]
rse_info = rsemgr.get_rse_info(rse_id=rse_id, session=session)
pfndict = {}
proto = rsemgr.create_protocol(rse_info, 'read', scheme=scheme)
if rse_info['deterministic']:
parsed_pfn = proto.parse_pfns(pfns=pfns)
# WARNING : this part is ATLAS specific and must be changed
for pfn in parsed_pfn:
path = parsed_pfn[pfn]['path']
if path.startswith('/user') or path.startswith('/group'):
scope = '%s.%s' % (path.split('/')[1], path.split('/')[2])
name = parsed_pfn[pfn]['name']
elif path.startswith('/'):
scope = path.split('/')[1]
name = parsed_pfn[pfn]['name']
else:
scope = path.split('/')[0]
name = parsed_pfn[pfn]['name']
scope = InternalScope(scope, vo)
yield {pfn: {'scope': scope, 'name': name}}
else:
condition = []
parsed_pfn = proto.parse_pfns(pfns=pfns)
for pfn in parsed_pfn:
path = '%s%s' % (parsed_pfn[pfn]['path'], parsed_pfn[pfn]['name'])
pfndict[path] = pfn
condition.append(and_(models.RSEFileAssociation.path == path, models.RSEFileAssociation.rse_id == rse_id))
for scope, name, pfn in session.query(models.RSEFileAssociation.scope, models.RSEFileAssociation.name, models.RSEFileAssociation.path).filter(or_(*condition)):
yield {pfndict[pfn]: {'scope': scope, 'name': name}}
def _pick_n_random(nrandom, generator):
"""
Select n random elements from the generator
"""
if not nrandom:
# pass-through the data unchanged
yield from generator
return
# A "reservoir sampling" algorithm:
# Copy the N first files from the generator. After that, following element may be picked to substitute
# one of the previously selected element with a probability which decreases as the number of encountered elements grows.
selected = []
i = 0
iterator = iter(generator)
try:
for _ in range(nrandom):
selected.append(next(iterator))
i += 1
while True:
element = next(iterator)
i += 1
index_to_substitute = random.randint(0, i)
if index_to_substitute < nrandom:
selected[index_to_substitute] = element
except StopIteration:
pass
for r in selected:
yield r
def _list_files_wo_replicas(files_wo_replica, *, session: "Session"):
if files_wo_replica:
file_wo_clause = []
for file in sorted(files_wo_replica, key=lambda f: (f['scope'], f['name'])):
file_wo_clause.append(and_(models.DataIdentifier.scope == file['scope'],
models.DataIdentifier.name == file['name']))
files_wo_replicas_query = session.query(models.DataIdentifier.scope,
models.DataIdentifier.name,
models.DataIdentifier.bytes,
models.DataIdentifier.md5,
models.DataIdentifier.adler32).\
filter_by(did_type=DIDType.FILE).filter(or_(*file_wo_clause)).\
with_hint(models.DataIdentifier, text="INDEX(DIDS DIDS_PK)", dialect_name='oracle')
for scope, name, bytes_, md5, adler32 in files_wo_replicas_query:
yield scope, name, bytes_, md5, adler32
def get_vp_endpoint():
"""
VP endpoint is the Virtual Placement server.
Once VP is integrated in Rucio it won't be needed.
"""
vp_endpoint = config_get('virtual_placement', 'vp_endpoint', default='')
return vp_endpoint
def get_multi_cache_prefix(cache_site, filename, logger=logging.log):
"""
for a givent cache site and filename, return address of the cache node that
should be prefixed.
:param cache_site: Cache site
:param filename: Filename
"""
vp_endpoint = get_vp_endpoint()
if not vp_endpoint:
return ''
x_caches = REGION.get('CacheSites')
if x_caches is NO_VALUE:
try:
response = requests.get('{}/serverRanges'.format(vp_endpoint), timeout=1, verify=False)
if response.ok:
x_caches = response.json()
REGION.set('CacheSites', x_caches)
else:
REGION.set('CacheSites', {'could not reload': ''})
return ''
except requests.exceptions.RequestException as re:
REGION.set('CacheSites', {'could not reload': ''})
logger(logging.WARNING, 'In get_multi_cache_prefix, could not access {}. Excaption:{}'.format(vp_endpoint, re))
return ''
if cache_site not in x_caches:
return ''
xcache_site = x_caches[cache_site]
h = float(
unpack('Q', sha256(filename.encode('utf-8')).digest()[:8])[0]) / 2**64
for irange in xcache_site['ranges']:
if h < irange[1]:
return xcache_site['servers'][irange[0]][0]
return ''
def _get_list_replicas_protocols(
rse_id: str,
domain: str,
schemes: "Sequence[str]",
additional_schemes: "Sequence[str]",
session: "Session"
) -> "List[Tuple[str, RSEProtocol, int]]":
"""
Select the protocols to be used by list_replicas to build the PFNs for all replicas on the given RSE
"""
domains = ['wan', 'lan'] if domain == 'all' else [domain]
rse_info = rsemgr.get_rse_info(rse_id=rse_id, session=session)
# compute scheme priorities, and don't forget to exclude disabled protocols
# 0 in RSE protocol definition = disabled, 1 = highest priority
scheme_priorities = {
'wan': {p['scheme']: p['domains']['wan']['read'] for p in rse_info['protocols'] if p['domains']['wan']['read'] > 0},
'lan': {p['scheme']: p['domains']['lan']['read'] for p in rse_info['protocols'] if p['domains']['lan']['read'] > 0},
}
rse_schemes = copy.copy(schemes) if schemes else []
if not rse_schemes:
try:
for domain in domains:
rse_schemes.append(rsemgr.select_protocol(rse_settings=rse_info,
operation='read',
domain=domain)['scheme'])
except exception.RSEProtocolNotSupported:
pass # no need to be verbose
except Exception:
print(format_exc())
for s in additional_schemes:
if s not in rse_schemes:
rse_schemes.append(s)
protocols = []
for s in rse_schemes:
try:
for domain in domains:
protocol = rsemgr.create_protocol(rse_settings=rse_info, operation='read', scheme=s, domain=domain)
priority = scheme_priorities[domain][s]
protocols.append((domain, protocol, priority))
except exception.RSEProtocolNotSupported:
pass # no need to be verbose
except Exception:
print(format_exc())
return protocols
def _build_list_replicas_pfn(
scope: "InternalScope",
name: str,
rse_id: str,
domain: str,
protocol: "RSEProtocol",
path: str,
sign_urls: bool,
signature_lifetime: int,
client_location: "Dict[str, Any]",
logger=logging.log,
*,
session: "Session",
) -> str:
"""
Generate the PFN for the given scope/name on the rse.
If needed, sign the PFN url
If relevant, add the server-side root proxy to te pfn url
"""
pfn: str = list(protocol.lfns2pfns(lfns={'scope': scope.external,
'name': name,
'path': path}).values())[0]
# do we need to sign the URLs?
if sign_urls and protocol.attributes['scheme'] == 'https':
service = get_rse_attribute(rse_id, 'sign_url', session=session)
if service:
pfn = get_signed_url(rse_id=rse_id, service=service, operation='read', url=pfn, lifetime=signature_lifetime)
# server side root proxy handling if location is set.
# supports root and http destinations
# cannot be pushed into protocols because we need to lookup rse attributes.
# ultra-conservative implementation.
if domain == 'wan' and protocol.attributes['scheme'] in ['root', 'http', 'https'] and client_location:
if 'site' in client_location and client_location['site']:
replica_site = get_rse_attribute(rse_id, 'site', session=session)
# does it match with the client? if not, it's an outgoing connection
# therefore the internal proxy must be prepended
if client_location['site'] != replica_site:
cache_site = config_get('clientcachemap', client_location['site'], default='', session=session)
if cache_site != '':
# print('client', client_location['site'], 'has cache:', cache_site)
# print('filename', name)
selected_prefix = get_multi_cache_prefix(cache_site, name)
if selected_prefix:
pfn = f"root://{selected_prefix}//{pfn.replace('davs://', 'root://')}"
else:
# print('site:', client_location['site'], 'has no cache')
# print('lets check if it has defined an internal root proxy ')
root_proxy_internal = config_get('root-proxy-internal', # section
client_location['site'], # option
default='', # empty string to circumvent exception
session=session)
if root_proxy_internal:
# TODO: XCache does not seem to grab signed URLs. Doublecheck with XCache devs.
# For now -> skip prepending XCache for GCS.
if 'storage.googleapis.com' in pfn or 'atlas-google-cloud.cern.ch' in pfn or 'amazonaws.com' in pfn:
pass # ATLAS HACK
else:
# don't forget to mangle gfal-style davs URL into generic https URL
pfn = f"root://{root_proxy_internal}//{pfn.replace('davs://', 'https://')}"
simulate_multirange = get_rse_attribute(rse_id, 'simulate_multirange')
if simulate_multirange is not None:
try:
# cover values that cannot be cast to int
simulate_multirange = int(simulate_multirange)
except ValueError:
simulate_multirange = 1
logger(logging.WARNING, 'Value encountered when retrieving RSE attribute "simulate_multirange" not compatible with "int", used default value "1".')
if simulate_multirange <= 0:
logger(logging.WARNING, f'Value {simulate_multirange} encountered when retrieving RSE attribute "simulate_multirange" is <= 0, used default value "1".')
simulate_multirange = 1
pfn += f'&#multirange=false&nconnections={simulate_multirange}'
return pfn
def _list_replicas(replicas, show_pfns, schemes, files_wo_replica, client_location, domain,
sign_urls, signature_lifetime, resolve_parents, filters, by_rse_name, *, session: "Session"):
# the `domain` variable name will be re-used throughout the function with different values
input_domain = domain
# find all RSEs local to the client's location in autoselect mode (i.e., when domain is None)
local_rses = []
if input_domain is None:
if client_location and 'site' in client_location and client_location['site']:
try:
local_rses = [rse['id'] for rse in parse_expression('site=%s' % client_location['site'], filter_=filters, session=session)]
except Exception:
pass # do not hard fail if site cannot be resolved or is empty
file, pfns_cache = {}, {}
protocols_cache = defaultdict(dict)
for _, replica_group in groupby(replicas, key=lambda x: (x[0], x[1])): # Group by scope/name
file = {}
pfns = {}
for scope, name, archive_scope, archive_name, bytes_, md5, adler32, path, state, rse_id, rse, rse_type, volatile in replica_group:
if isinstance(archive_scope, str):
archive_scope = InternalScope(archive_scope, fromExternal=False)
is_archive = bool(archive_scope and archive_name)
# it is the first row in the scope/name group
if not file:
file['scope'], file['name'] = scope, name
file['bytes'], file['md5'], file['adler32'] = bytes_, md5, adler32
file['pfns'], file['rses'], file['states'] = {}, {}, {}
if resolve_parents:
file['parents'] = ['%s:%s' % (parent['scope'].internal, parent['name'])
for parent in rucio.core.did.list_all_parent_dids(scope, name, session=session)]
if not rse_id:
continue
rse_key = rse if by_rse_name else rse_id
file['states'][rse_key] = str(state.name if state else state)
if not show_pfns:
continue
# It's the first time we see this RSE, initialize the protocols needed for PFN generation
protocols = protocols_cache.get(rse_id, {}).get(is_archive)
if not protocols:
# select the lan door in autoselect mode, otherwise use the wan door
domain = input_domain
if domain is None:
domain = 'wan'
if local_rses and rse_id in local_rses:
domain = 'lan'
protocols = _get_list_replicas_protocols(
rse_id=rse_id,
domain=domain,
schemes=schemes,
# We want 'root' for archives even if it wasn't included into 'schemes'
additional_schemes=['root'] if is_archive else [],
session=session,
)
protocols_cache[rse_id][is_archive] = protocols
# build the pfns
for domain, protocol, priority in protocols:
# If the current "replica" is a constituent inside an archive, we must construct the pfn for the
# parent (archive) file and append the xrdcl.unzip query string to it.
if is_archive:
t_scope = archive_scope
t_name = archive_name
else:
t_scope = scope
t_name = name
if 'determinism_type' in protocol.attributes: # PFN is cachable
try:
path = pfns_cache['%s:%s:%s' % (protocol.attributes['determinism_type'], t_scope.internal, t_name)]
except KeyError: # No cache entry scope:name found for this protocol
path = protocol._get_path(t_scope, t_name)
pfns_cache['%s:%s:%s' % (protocol.attributes['determinism_type'], t_scope.internal, t_name)] = path
try:
pfn = _build_list_replicas_pfn(
scope=t_scope,
name=t_name,
rse_id=rse_id,
domain=domain,
protocol=protocol,
path=path,
sign_urls=sign_urls,
signature_lifetime=signature_lifetime,
client_location=client_location,
session=session,
)
client_extract = False
if is_archive:
domain = 'zip'
pfn = add_url_query(pfn, {'xrdcl.unzip': name})
if protocol.attributes['scheme'] == 'root':
# xroot supports downloading files directly from inside an archive. Disable client_extract and prioritize xroot.
client_extract = False
priority = -1
else:
client_extract = True
pfns[pfn] = {
'rse_id': rse_id,
'rse': rse,
'type': str(rse_type.name),
'volatile': volatile,
'domain': domain,
'priority': priority,
'client_extract': client_extract
}
except Exception:
# never end up here
print(format_exc())