/
did.py
3122 lines (2768 loc) · 123 KB
/
did.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
import random
from datetime import datetime, timedelta
from enum import Enum
from hashlib import md5
from re import match
from typing import TYPE_CHECKING
from sqlalchemy import and_, or_, exists, update, delete, insert
from sqlalchemy.exc import DatabaseError, IntegrityError
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.sql import not_, func
from sqlalchemy.sql.expression import bindparam, case, select, true, false, null
import rucio.core.replica # import add_replicas
import rucio.core.rule
from rucio.common import exception
from rucio.common.config import config_get_bool, config_get_int
from rucio.common.utils import is_archive, chunks
from rucio.core import did_meta_plugins
from rucio.core.message import add_message
from rucio.core.monitor import MetricManager
from rucio.core.naming_convention import validate_name
from rucio.db.sqla import models, filter_thread_work
from rucio.db.sqla.constants import DIDType, DIDReEvaluation, DIDAvailability, RuleState, BadFilesStatus
from rucio.db.sqla.session import read_session, transactional_session, stream_session
from rucio.db.sqla.util import temp_table_mngr
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
from typing import Any, Dict, Optional, Union, List
from sqlalchemy.orm import Session
from sqlalchemy.schema import Table
from rucio.common.types import InternalAccount, InternalScope
LoggerFunction = Callable[..., Any]
DIDListType = List[Dict]
METRICS = MetricManager(module=__name__)
@read_session
def list_expired_dids(
worker_number: int = None,
total_workers: int = None,
limit: int = None,
*,
session: "Session"
):
"""
List expired data identifiers.
:param limit: limit number.
:param session: The database session in use.
"""
sub_query = exists(
).where(
models.ReplicationRule.scope == models.DataIdentifier.scope,
models.ReplicationRule.name == models.DataIdentifier.name,
models.ReplicationRule.locked == true(),
)
list_stmt = select(
models.DataIdentifier.scope,
models.DataIdentifier.name,
models.DataIdentifier.did_type,
models.DataIdentifier.created_at,
models.DataIdentifier.purge_replicas
).where(
models.DataIdentifier.expired_at < datetime.utcnow(),
not_(sub_query),
).order_by(
models.DataIdentifier.expired_at
).with_hint(
models.DataIdentifier, "index(DIDS DIDS_EXPIRED_AT_IDX)", 'oracle'
)
if session.bind.dialect.name in ['oracle', 'mysql', 'postgresql']:
list_stmt = filter_thread_work(session=session, query=list_stmt, total_threads=total_workers, thread_id=worker_number, hash_variable='name')
elif session.bind.dialect.name == 'sqlite' and worker_number and total_workers and total_workers > 0:
row_count = 0
dids = list()
for scope, name, did_type, created_at, purge_replicas in session.execute(list_stmt).yield_per(10):
if int(md5(name).hexdigest(), 16) % total_workers == worker_number:
dids.append({'scope': scope,
'name': name,
'did_type': did_type,
'created_at': created_at,
'purge_replicas': purge_replicas})
row_count += 1
if limit and row_count >= limit:
return dids
return dids
else:
if worker_number and total_workers:
raise exception.DatabaseException('The database type %s returned by SQLAlchemy is invalid.' % session.bind.dialect.name)
if limit:
list_stmt = list_stmt.limit(limit)
return [{'scope': scope, 'name': name, 'did_type': did_type, 'created_at': created_at,
'purge_replicas': purge_replicas} for scope, name, did_type, created_at, purge_replicas in session.execute(list_stmt)]
@transactional_session
def add_did(
scope: "InternalScope",
name: str,
did_type: "Union[str, DIDType]",
account: "InternalAccount",
statuses: "Optional[dict[str, Any]]" = None,
meta: "Optional[dict[str, Any]]" = None,
rules: "Optional[Sequence[str]]" = None,
lifetime: "Optional[int]" = None,
dids: "Optional[Sequence[dict[str, Any]]]" = None,
rse_id: "Optional[str]" = None,
*,
session: "Session",
):
"""
Add data identifier.
:param scope: The scope name.
:param name: The data identifier name.
:param did_type: The data identifier type.
:param account: The account owner.
:param statuses: Dictionary with statuses, e.g.g {'monotonic':True}.
:meta: Meta-data associated with the data identifier is represented using key/value pairs in a dictionary.
:rules: Replication rules associated with the data identifier. A list of dictionaries, e.g., [{'copies': 2, 'rse_expression': 'TIERS1'}, ].
:param lifetime: DID's lifetime (in seconds).
:param dids: The content.
:param rse_id: The RSE id when registering replicas.
:param session: The database session in use.
"""
return add_dids(dids=[{'scope': scope, 'name': name, 'type': did_type,
'statuses': statuses or {}, 'meta': meta or {},
'rules': rules, 'lifetime': lifetime,
'dids': dids, 'rse_id': rse_id}],
account=account, session=session)
@transactional_session
def add_dids(
dids: "Sequence[dict[str, Any]]",
account: "InternalAccount",
*,
session: "Session",
):
"""
Bulk add data identifiers.
:param dids: A list of dids.
:param account: The account owner.
:param session: The database session in use.
"""
try:
for did in dids:
try:
if isinstance(did['type'], str):
did['type'] = DIDType[did['type']]
if did['type'] == DIDType.FILE:
raise exception.UnsupportedOperation('Only collection (dataset/container) can be registered.')
# Lifetime
expired_at = None
if did.get('lifetime'):
expired_at = datetime.utcnow() + timedelta(seconds=did['lifetime'])
# Insert new data identifier
new_did = models.DataIdentifier(scope=did['scope'], name=did['name'], account=did.get('account') or account,
did_type=did['type'], monotonic=did.get('statuses', {}).get('monotonic', False),
is_open=True, expired_at=expired_at)
new_did.save(session=session, flush=False)
if 'meta' in did and did['meta']:
# Add metadata
set_metadata_bulk(scope=did['scope'], name=did['name'], meta=did['meta'], recursive=False, session=session)
if did.get('dids', None):
attach_dids(scope=did['scope'], name=did['name'], dids=did['dids'],
account=account, rse_id=did.get('rse_id'), session=session)
if did.get('rules', None):
rucio.core.rule.add_rules(dids=[did, ], rules=did['rules'], session=session)
event_type = None
if did['type'] == DIDType.CONTAINER:
event_type = 'CREATE_CNT'
if did['type'] == DIDType.DATASET:
event_type = 'CREATE_DTS'
if event_type:
message = {'account': account.external,
'scope': did['scope'].external,
'name': did['name'],
'expired_at': str(expired_at) if expired_at is not None else None}
if account.vo != 'def':
message['vo'] = account.vo
add_message(event_type, message, session=session)
except KeyError:
# ToDo
raise
session.flush()
except IntegrityError as error:
if match('.*IntegrityError.*ORA-00001: unique constraint.*DIDS_PK.*violated.*', error.args[0]) \
or match('.*IntegrityError.*UNIQUE constraint failed: dids.scope, dids.name.*', error.args[0]) \
or match('.*IntegrityError.*1062.*Duplicate entry.*for key.*', error.args[0]) \
or match('.*IntegrityError.*duplicate key value violates unique constraint.*', error.args[0]) \
or match('.*UniqueViolation.*duplicate key value violates unique constraint.*', error.args[0]) \
or match('.*IntegrityError.*columns? .*not unique.*', error.args[0]):
raise exception.DataIdentifierAlreadyExists('Data Identifier already exists!')
if match('.*IntegrityError.*02291.*integrity constraint.*DIDS_SCOPE_FK.*violated - parent key not found.*', error.args[0]) \
or match('.*IntegrityError.*FOREIGN KEY constraint failed.*', error.args[0]) \
or match('.*IntegrityError.*1452.*Cannot add or update a child row: a foreign key constraint fails.*', error.args[0]) \
or match('.*IntegrityError.*02291.*integrity constraint.*DIDS_SCOPE_FK.*violated - parent key not found.*', error.args[0]) \
or match('.*IntegrityError.*insert or update on table.*violates foreign key constraint.*', error.args[0]) \
or match('.*ForeignKeyViolation.*insert or update on table.*violates foreign key constraint.*', error.args[0]) \
or match('.*IntegrityError.*foreign key constraints? failed.*', error.args[0]):
raise exception.ScopeNotFound('Scope not found!')
raise exception.RucioException(error.args)
except DatabaseError as error:
if match('.*(DatabaseError).*ORA-14400.*inserted partition key does not map to any partition.*', error.args[0]):
raise exception.ScopeNotFound('Scope not found!')
raise exception.RucioException(error.args)
@transactional_session
def attach_dids(
scope: "InternalScope",
name: str,
dids: "Sequence[dict[str, Any]]",
account: "InternalAccount",
rse_id: "Optional[str]" = None,
*,
session: "Session",
):
"""
Append data identifier.
:param scope: The scope name.
:param name: The data identifier name.
:param dids: The content.
:param account: The account owner.
:param rse_id: The RSE id for the replicas.
:param session: The database session in use.
"""
return attach_dids_to_dids(attachments=[{'scope': scope, 'name': name, 'dids': dids, 'rse_id': rse_id}], account=account, session=session)
@transactional_session
def attach_dids_to_dids(
attachments: "dict[str, Any]",
account: "InternalAccount",
ignore_duplicate: bool = False,
*,
session: "Session",
):
children_temp_table = temp_table_mngr(session).create_scope_name_table()
parent_dids = list()
first_iteration = True
for attachment in attachments:
try:
children = {(a['scope'], a['name']): a for a in attachment['dids']}
cont = []
stmt = select(
models.DataIdentifier
).where(
models.DataIdentifier.scope == attachment['scope'],
models.DataIdentifier.name == attachment['name']
).with_hint(
models.DataIdentifier, "INDEX(DIDS DIDS_PK)", 'oracle'
)
parent_did = session.execute(stmt).scalar_one()
update_parent = False
if not first_iteration:
session.query(children_temp_table).delete()
session.execute(insert(children_temp_table), [{'scope': s, 'name': n} for s, n in children])
if parent_did.did_type == DIDType.FILE:
# check if parent file has the archive extension
if is_archive(attachment['name']):
__add_files_to_archive(parent_did=parent_did,
files_temp_table=children_temp_table,
files=children,
account=account,
ignore_duplicate=ignore_duplicate,
session=session)
return
raise exception.UnsupportedOperation("Data identifier '%(scope)s:%(name)s' is a file" % attachment)
elif not parent_did.is_open:
raise exception.UnsupportedOperation("Data identifier '%(scope)s:%(name)s' is closed" % attachment)
elif parent_did.did_type == DIDType.DATASET:
cont = __add_files_to_dataset(parent_did=parent_did,
files_temp_table=children_temp_table,
files=children,
account=account,
ignore_duplicate=ignore_duplicate,
rse_id=attachment.get('rse_id'),
session=session)
update_parent = len(cont) > 0
elif parent_did.did_type == DIDType.CONTAINER:
__add_collections_to_container(parent_did=parent_did,
collections_temp_table=children_temp_table,
collections=children,
account=account,
session=session)
update_parent = True
if update_parent:
# cont contains the parent of the files and is only filled if the files does not exist yet
parent_dids.append({'scope': parent_did.scope,
'name': parent_did.name,
'rule_evaluation_action': DIDReEvaluation.ATTACH})
except NoResultFound:
raise exception.DataIdentifierNotFound("Data identifier '%s:%s' not found" % (attachment['scope'], attachment['name']))
first_iteration = False
# Remove all duplicated dictionnaries from the list
# (convert the list of dictionaries into a list of tuple, then to a set of tuple
# to remove duplicates, then back to a list of unique dictionaries)
parent_dids = [dict(tup) for tup in set(tuple(dictionary.items()) for dictionary in parent_dids)]
if parent_dids:
session.execute(insert(models.UpdatedDID), parent_dids)
def __add_files_to_archive(parent_did, files_temp_table, files, account, ignore_duplicate=False, *, session: "Session"):
"""
Add files to archive.
:param parent_did: the DataIdentifier object of the parent did
:param files: archive content.
:param account: The account owner.
:param ignore_duplicate: If True, ignore duplicate entries.
:param session: The database session in use.
"""
stmt = select(
files_temp_table.scope,
files_temp_table.name,
models.DataIdentifier.scope.label('did_scope'),
models.DataIdentifier.bytes,
models.DataIdentifier.guid,
models.DataIdentifier.events,
models.DataIdentifier.availability,
models.DataIdentifier.adler32,
models.DataIdentifier.md5,
models.DataIdentifier.is_archive,
models.DataIdentifier.constituent,
models.DataIdentifier.did_type,
).outerjoin_from(
files_temp_table,
models.DataIdentifier,
and_(
models.DataIdentifier.scope == files_temp_table.scope,
models.DataIdentifier.name == files_temp_table.name,
),
)
if ignore_duplicate:
stmt = stmt.add_columns(
models.ConstituentAssociation.scope.label('archive_contents_scope'),
).outerjoin_from(
files_temp_table,
models.ConstituentAssociation,
and_(
models.ConstituentAssociation.scope == parent_did.scope,
models.ConstituentAssociation.name == parent_did.name,
models.ConstituentAssociation.child_scope == files_temp_table.scope,
models.ConstituentAssociation.child_name == files_temp_table.name,
),
)
dids_to_add = {}
must_set_constituent = False
archive_contents_to_add = {}
for row in session.execute(stmt):
file = files[row.scope, row.name]
if ignore_duplicate and row.archive_contents_scope is not None:
continue
if (row.scope, row.name) in archive_contents_to_add:
# Ignore duplicate input
continue
if row.did_scope is None:
new_did = {}
new_did.update((k, v) for k, v in file.items() if k != 'meta')
for key in file.get('meta', {}):
new_did[key] = file['meta'][key]
new_did['constituent'] = True
new_did['did_type'] = DIDType.FILE
new_did['account'] = account
dids_to_add[row.scope, row.name] = new_did
new_content = {
'child_scope': file['scope'],
'child_name': file['name'],
'scope': parent_did.scope,
'name': parent_did.name,
'bytes': file['bytes'],
'adler32': file.get('adler32'),
'md5': file.get('md5'),
'guid': file.get('guid'),
'length': file.get('events')
}
else:
if row.did_type != DIDType.FILE:
raise exception.UnsupportedOperation('Data identifier %s:%s of type %s cannot be added to an archive ' % (row.scope, row.name, row.did_type))
if not row.constituent:
must_set_constituent = True
new_content = {
'child_scope': row.scope,
'child_name': row.name,
'scope': parent_did.scope,
'name': parent_did.name,
'bytes': row.bytes,
'adler32': row.adler32,
'md5': row.md5,
'guid': row.guid,
'length': row.events
}
archive_contents_to_add[row.scope, row.name] = new_content
# insert into archive_contents
try:
dids_to_add and session.execute(insert(models.DataIdentifier), list(dids_to_add.values()))
archive_contents_to_add and session.execute(insert(models.ConstituentAssociation), list(archive_contents_to_add.values()))
if must_set_constituent:
stmt = update(
models.DataIdentifier
).where(
exists(
select(1)
).where(
models.DataIdentifier.scope == files_temp_table.scope,
models.DataIdentifier.name == files_temp_table.name
)
).where(
or_(models.DataIdentifier.constituent.is_(None),
models.DataIdentifier.constituent == false())
).execution_options(
synchronize_session=False
).values(
constituent=True
)
session.execute(stmt)
session.flush()
except IntegrityError as error:
raise exception.RucioException(error.args)
if not parent_did.is_archive:
# mark tha archive file as is_archive
parent_did.is_archive = True
# mark parent datasets as is_archive = True
stmt = update(
models.DataIdentifier
).where(
exists(
select(1).prefix_with("/*+ INDEX(CONTENTS CONTENTS_CHILD_SCOPE_NAME_IDX) */", dialect="oracle")
).where(
models.DataIdentifierAssociation.child_scope == parent_did.scope,
models.DataIdentifierAssociation.child_name == parent_did.name,
models.DataIdentifierAssociation.scope == models.DataIdentifier.scope,
models.DataIdentifierAssociation.name == models.DataIdentifier.name
)
).where(
or_(models.DataIdentifier.is_archive.is_(None),
models.DataIdentifier.is_archive == false())
).execution_options(
synchronize_session=False
).values(
is_archive=True
)
session.execute(stmt)
@transactional_session
def __add_files_to_dataset(parent_did, files_temp_table, files, account, rse_id, ignore_duplicate=False, *, session: "Session"):
"""
Add files to dataset.
:param parent_did: the DataIdentifier object of the parent did
:param files_temp_table: Temporary table containing the scope and name of files to add.
:param account: The account owner.
:param rse_id: The RSE id for the replicas.
:param ignore_duplicate: If True, ignore duplicate entries.
:param session: The database session in use.
:returns: List of files attached (excluding the ones that were already attached to the dataset).
"""
# Get metadata from dataset
try:
dataset_meta = validate_name(scope=parent_did.scope, name=parent_did.name, did_type='D')
except Exception:
dataset_meta = None
if rse_id:
# Tier-0 uses this old work-around to register replicas on the RSE
# in the same call as attaching them to a dataset
rucio.core.replica.add_replicas(rse_id=rse_id, files=files.values(), dataset_meta=dataset_meta,
account=account, session=session)
stmt = select(
files_temp_table.scope,
files_temp_table.name,
models.DataIdentifier.scope.label('did_scope'),
models.DataIdentifier.bytes,
models.DataIdentifier.guid,
models.DataIdentifier.events,
models.DataIdentifier.availability,
models.DataIdentifier.adler32,
models.DataIdentifier.md5,
models.DataIdentifier.is_archive,
models.DataIdentifier.did_type,
).outerjoin_from(
files_temp_table,
models.DataIdentifier,
and_(
models.DataIdentifier.scope == files_temp_table.scope,
models.DataIdentifier.name == files_temp_table.name,
),
)
if ignore_duplicate:
stmt = stmt.add_columns(
models.DataIdentifierAssociation.scope.label('contents_scope'),
).outerjoin_from(
files_temp_table,
models.DataIdentifierAssociation,
and_(
models.DataIdentifierAssociation.scope == parent_did.scope,
models.DataIdentifierAssociation.name == parent_did.name,
models.DataIdentifierAssociation.child_scope == files_temp_table.scope,
models.DataIdentifierAssociation.child_name == files_temp_table.name,
),
)
files_to_add = {}
for row in session.execute(stmt):
file = files[row.scope, row.name]
if row.did_scope is None:
raise exception.DataIdentifierNotFound(f"Data identifier '{row.scope}:{row.name}' not found")
if row.availability == DIDAvailability.LOST:
raise exception.UnsupportedOperation('File %s:%s is LOST and cannot be attached' % (row.scope, row.name))
if row.did_type != DIDType.FILE:
raise exception.UnsupportedOperation('Data identifier %s:%s of type %s cannot be added to a dataset ' % (row.scope, row.name, row.did_type))
# Check meta-data, if provided
row_dict = row._asdict()
for key in ['bytes', 'adler32', 'md5']:
if key in file and str(file[key]) != str(row_dict[key]):
raise exception.FileConsistencyMismatch(key + " mismatch for '%(scope)s:%(name)s': " % row_dict + str(file.get(key)) + '!=' + str(row_dict[key]))
if ignore_duplicate and row.contents_scope is not None:
continue
if (row.scope, row.name) in files_to_add:
# Ignore duplicate input files
continue
if row.is_archive and not parent_did.is_archive:
parent_did.is_archive = True
files_to_add[(row.scope, row.name)] = {
'scope': parent_did.scope,
'name': parent_did.name,
'child_scope': row.scope,
'child_name': row.name,
'bytes': row.bytes,
'adler32': row.adler32,
'md5': row.md5,
'guid': row.guid,
'events': row.events,
'did_type': DIDType.DATASET,
'child_type': DIDType.FILE,
'rule_evaluation': True,
}
try:
files_to_add and session.execute(insert(models.DataIdentifierAssociation), list(files_to_add.values()))
session.flush()
return files_to_add
except IntegrityError as error:
if match('.*IntegrityError.*ORA-02291: integrity constraint .*CONTENTS_CHILD_ID_FK.*violated - parent key not found.*', error.args[0]) \
or match('.*IntegrityError.*1452.*Cannot add or update a child row: a foreign key constraint fails.*', error.args[0]) \
or match('.*IntegrityError.*foreign key constraints? failed.*', error.args[0]) \
or match('.*IntegrityError.*insert or update on table.*violates foreign key constraint.*', error.args[0]):
raise exception.DataIdentifierNotFound("Data identifier not found")
elif match('.*IntegrityError.*ORA-00001: unique constraint .*CONTENTS_PK.*violated.*', error.args[0]) \
or match('.*IntegrityError.*UNIQUE constraint failed: contents.scope, contents.name, contents.child_scope, contents.child_name.*', error.args[0]) \
or match('.*IntegrityError.*duplicate key value violates unique constraint.*', error.args[0]) \
or match('.*UniqueViolation.*duplicate key value violates unique constraint.*', error.args[0]) \
or match('.*IntegrityError.*1062.*Duplicate entry .*for key.*PRIMARY.*', error.args[0]) \
or match('.*duplicate entry.*key.*PRIMARY.*', error.args[0]) \
or match('.*IntegrityError.*columns? .*not unique.*', error.args[0]):
raise exception.FileAlreadyExists(error.args)
else:
raise exception.RucioException(error.args)
@transactional_session
def __add_collections_to_container(parent_did, collections_temp_table, collections, account, *, session: "Session"):
"""
Add collections (datasets or containers) to container.
:param parent_did: the DataIdentifier object of the parent did
:param collections: .
:param account: The account owner.
:param session: The database session in use.
"""
if (parent_did.scope, parent_did.name) in collections:
raise exception.UnsupportedOperation('Self-append is not valid!')
stmt = select(
collections_temp_table.scope,
collections_temp_table.name,
models.DataIdentifier.scope.label('did_scope'),
models.DataIdentifier.did_type
).outerjoin_from(
collections_temp_table,
models.DataIdentifier,
and_(
models.DataIdentifier.scope == collections_temp_table.scope,
models.DataIdentifier.name == collections_temp_table.name,
),
)
container_parents = None
child_type = None
for row in session.execute(stmt):
if row.did_scope is None:
raise exception.DataIdentifierNotFound("Data identifier '%(scope)s:%(name)s' not found" % row)
if row.did_type == DIDType.FILE:
raise exception.UnsupportedOperation("Adding a file (%s:%s) to a container (%s:%s) is forbidden" % (row.scope, row.name, parent_did.scope, parent_did.name))
if not child_type:
child_type = row.did_type
if child_type != row.did_type:
raise exception.UnsupportedOperation("Mixed collection is not allowed: '%s:%s' is a %s(expected type: %s)" % (row.scope, row.name, row.did_type, child_type))
if child_type == DIDType.CONTAINER:
if container_parents is None:
container_parents = {(parent['scope'], parent['name']) for parent in list_all_parent_dids(scope=parent_did.scope, name=parent_did.name, session=session)}
if (row.scope, row.name) in container_parents:
raise exception.UnsupportedOperation('Circular attachment detected. %s:%s is already a parent of %s:%s' % (row.scope, row.name, parent_did.scope, parent_did.name))
messages = []
for c in collections.values():
did_asso = models.DataIdentifierAssociation(
scope=parent_did.scope,
name=parent_did.name,
child_scope=c['scope'],
child_name=c['name'],
did_type=DIDType.CONTAINER,
child_type=child_type,
rule_evaluation=True
)
did_asso.save(session=session, flush=False)
# Send AMI messages
if child_type == DIDType.CONTAINER:
chld_type = 'CONTAINER'
elif child_type == DIDType.DATASET:
chld_type = 'DATASET'
else:
chld_type = 'UNKNOWN'
message = {'account': account.external,
'scope': parent_did.scope.external,
'name': parent_did.name,
'childscope': c['scope'].external,
'childname': c['name'],
'childtype': chld_type}
if account.vo != 'def':
message['vo'] = account.vo
messages.append(message)
try:
for message in messages:
add_message('REGISTER_CNT', message, session=session)
session.flush()
except IntegrityError as error:
if match('.*IntegrityError.*ORA-02291: integrity constraint .*CONTENTS_CHILD_ID_FK.*violated - parent key not found.*', error.args[0]) \
or match('.*IntegrityError.*1452.*Cannot add or update a child row: a foreign key constraint fails.*', error.args[0]) \
or match('.*IntegrityError.*foreign key constraints? failed.*', error.args[0]) \
or match('.*IntegrityError.*insert or update on table.*violates foreign key constraint.*', error.args[0]):
raise exception.DataIdentifierNotFound("Data identifier not found")
elif match('.*IntegrityError.*ORA-00001: unique constraint .*CONTENTS_PK.*violated.*', error.args[0]) \
or match('.*IntegrityError.*1062.*Duplicate entry .*for key.*PRIMARY.*', error.args[0]) \
or match('.*IntegrityError.*columns? scope.*name.*child_scope.*child_name.*not unique.*', error.args[0]) \
or match('.*IntegrityError.*duplicate key value violates unique constraint.*', error.args[0]) \
or match('.*UniqueViolation.*duplicate key value violates unique constraint.*', error.args[0]) \
or match('.*IntegrityError.* UNIQUE constraint failed: contents.scope, contents.name, contents.child_scope, contents.child_name.*', error.args[0]):
raise exception.DuplicateContent(error.args)
raise exception.RucioException(error.args)
def __add_files_to_archive_without_temp_tables(scope, name, files, account, ignore_duplicate=False, *, session: "Session"):
"""
Add files to archive.
:param scope: The scope name.
:param name: The data identifier name.
:param files: archive content.
:param account: The account owner.
:param ignore_duplicate: If True, ignore duplicate entries.
:param session: The database session in use.
"""
# lookup for existing files
files_query = select(
models.DataIdentifier.scope,
models.DataIdentifier.name,
models.DataIdentifier.bytes,
models.DataIdentifier.guid,
models.DataIdentifier.events,
models.DataIdentifier.availability,
models.DataIdentifier.adler32,
models.DataIdentifier.md5,
).where(
models.DataIdentifier.did_type == DIDType.FILE
).with_hint(
models.DataIdentifier, "INDEX(DIDS DIDS_PK)", 'oracle'
)
file_condition = []
for file in files:
file_condition.append(and_(models.DataIdentifier.scope == file['scope'],
models.DataIdentifier.name == file['name']))
existing_content, existing_files = [], {}
if ignore_duplicate:
# lookup for existing content
content_query = select(
models.ConstituentAssociation.scope,
models.ConstituentAssociation.name,
models.ConstituentAssociation.child_scope,
models.ConstituentAssociation.child_name
).with_hint(
models.ConstituentAssociation, "INDEX(ARCHIVE_CONTENTS ARCH_CONTENTS_PK)", 'oracle'
)
content_condition = []
for file in files:
content_condition.append(and_(models.ConstituentAssociation.scope == scope,
models.ConstituentAssociation.name == name,
models.ConstituentAssociation.child_scope == file['scope'],
models.ConstituentAssociation.child_name == file['name']))
for row in session.execute(content_query.where(or_(*content_condition))):
existing_content.append(row)
for row in session.execute(files_query.where(or_(*file_condition))):
existing_files['%s:%s' % (row.scope.internal, row.name)] = {'child_scope': row.scope,
'child_name': row.name,
'scope': scope,
'name': name,
'bytes': row.bytes,
'adler32': row.adler32,
'md5': row.md5,
'guid': row.guid,
'length': row.events}
contents = []
new_files, existing_files_condition = [], []
for file in files:
did_tag = '%s:%s' % (file['scope'].internal, file['name'])
if did_tag not in existing_files:
# For non existing files
# Add them to the content
contents.append({'child_scope': file['scope'],
'child_name': file['name'],
'scope': scope,
'name': name,
'bytes': file['bytes'],
'adler32': file.get('adler32'),
'md5': file.get('md5'),
'guid': file.get('guid'),
'length': file.get('events')})
file['constituent'] = True
file['did_type'] = DIDType.FILE
file['account'] = account
for key in file.get('meta', {}):
file[key] = file['meta'][key]
# Prepare new file registrations
new_files.append(file)
else:
# For existing files
# Prepare the dids updates
existing_files_condition.append(and_(models.DataIdentifier.scope == file['scope'],
models.DataIdentifier.name == file['name']))
# Check if they are not already in the content
if not existing_content or (scope, name, file['scope'], file['name']) not in existing_content:
contents.append(existing_files[did_tag])
# insert into archive_contents
try:
new_files and session.execute(insert(models.DataIdentifier), new_files)
if existing_files_condition:
for chunk in chunks(existing_files_condition, 20):
stmt = update(
models.DataIdentifier
).prefix_with(
"/*+ INDEX(DIDS DIDS_PK) */", dialect='oracle'
).where(
models.DataIdentifier.did_type == DIDType.FILE
).where(
or_(models.DataIdentifier.constituent.is_(None),
models.DataIdentifier.constituent == false())
).where(
or_(*chunk)
).values(
constituent=True
)
session.execute(stmt)
contents and session.execute(insert(models.ConstituentAssociation), contents)
session.flush()
except IntegrityError as error:
raise exception.RucioException(error.args)
stmt = select(
models.DataIdentifier
).where(
models.DataIdentifier.did_type == DIDType.FILE,
models.DataIdentifier.scope == scope,
models.DataIdentifier.name == name,
)
archive_did = session.execute(stmt).scalar()
if not archive_did.is_archive:
# mark tha archive file as is_archive
archive_did.is_archive = True
# mark parent datasets as is_archive = True
stmt = update(
models.DataIdentifier
).where(
exists(
select(1).prefix_with("/*+ INDEX(CONTENTS CONTENTS_CHILD_SCOPE_NAME_IDX) */", dialect="oracle")
).where(
models.DataIdentifierAssociation.child_scope == scope,
models.DataIdentifierAssociation.child_name == name,
models.DataIdentifierAssociation.scope == models.DataIdentifier.scope,
models.DataIdentifierAssociation.name == models.DataIdentifier.name
)
).where(
or_(models.DataIdentifier.is_archive.is_(None),
models.DataIdentifier.is_archive == false())
).execution_options(
synchronize_session=False
).values(
is_archive=True
)
session.execute(stmt)
@transactional_session
def __add_files_to_dataset_without_temp_tables(scope, name, files, account, rse_id, ignore_duplicate=False, *, session: "Session"):
"""
Add files to dataset.
:param scope: The scope name.
:param name: The data identifier name.
:param files: The list of files.
:param account: The account owner.
:param rse_id: The RSE id for the replicas.
:param ignore_duplicate: If True, ignore duplicate entries.
:param session: The database session in use.
:returns: List of files attached (excluding the ones that were already attached to the dataset).
"""
# Get metadata from dataset
try:
dataset_meta = validate_name(scope=scope, name=name, did_type='D')
except Exception:
dataset_meta = None
if rse_id:
rucio.core.replica.add_replicas(rse_id=rse_id, files=files, dataset_meta=dataset_meta,
account=account, session=session)
files = get_files(files=files, session=session)
existing_content = []
if ignore_duplicate:
content_query = select(
models.DataIdentifierAssociation.scope,
models.DataIdentifierAssociation.name,
models.DataIdentifierAssociation.child_scope,
models.DataIdentifierAssociation.child_name
).with_hint(
models.DataIdentifierAssociation, "INDEX(CONTENTS CONTENTS_PK)", 'oracle'
)
content_condition = []
for file in files:
content_condition.append(and_(models.DataIdentifierAssociation.scope == scope,
models.DataIdentifierAssociation.name == name,
models.DataIdentifierAssociation.child_scope == file['scope'],
models.DataIdentifierAssociation.child_name == file['name']))
for row in session.execute(content_query.where(or_(*content_condition))):
existing_content.append(row)
contents = []
added_archives_condition = []
for file in files:
if not existing_content or (scope, name, file['scope'], file['name']) not in existing_content:
contents.append({'scope': scope, 'name': name, 'child_scope': file['scope'],
'child_name': file['name'], 'bytes': file['bytes'],
'adler32': file.get('adler32'),
'guid': file['guid'], 'events': file['events'],
'md5': file.get('md5'), 'did_type': DIDType.DATASET,
'child_type': DIDType.FILE, 'rule_evaluation': True})
added_archives_condition.append(
and_(models.DataIdentifier.scope == file['scope'],
models.DataIdentifier.name == file['name'],
models.DataIdentifier.is_archive == true()))
# if any of the attached files is an archive, set is_archive = True on the dataset
stmt = select(
models.DataIdentifier
).with_hint(
models.DataIdentifier, "INDEX(DIDS DIDS_PK)", 'oracle'
).where(
or_(*added_archives_condition)
).limit(
1
)
if session.execute(stmt).scalar() is not None:
stmt = update(
models.DataIdentifier
).where(
models.DataIdentifier.scope == scope,
models.DataIdentifier.name == name,
).where(
or_(models.DataIdentifier.is_archive.is_(None),
models.DataIdentifier.is_archive == false())
).values(
is_archive=True
)
session.execute(stmt)
try:
contents and session.execute(insert(models.DataIdentifierAssociation), contents)
session.flush()
return contents
except IntegrityError as error:
if match('.*IntegrityError.*ORA-02291: integrity constraint .*CONTENTS_CHILD_ID_FK.*violated - parent key not found.*', error.args[0]) \
or match('.*IntegrityError.*1452.*Cannot add or update a child row: a foreign key constraint fails.*', error.args[0]) \
or match('.*IntegrityError.*foreign key constraints? failed.*', error.args[0]) \
or match('.*IntegrityError.*insert or update on table.*violates foreign key constraint.*', error.args[0]):
raise exception.DataIdentifierNotFound("Data identifier not found")
elif match('.*IntegrityError.*ORA-00001: unique constraint .*CONTENTS_PK.*violated.*', error.args[0]) \
or match('.*IntegrityError.*UNIQUE constraint failed: contents.scope, contents.name, contents.child_scope, contents.child_name.*', error.args[0])\
or match('.*IntegrityError.*duplicate key value violates unique constraint.*', error.args[0]) \
or match('.*UniqueViolation.*duplicate key value violates unique constraint.*', error.args[0]) \
or match('.*IntegrityError.*1062.*Duplicate entry .*for key.*PRIMARY.*', error.args[0]) \
or match('.*duplicate entry.*key.*PRIMARY.*', error.args[0]) \
or match('.*IntegrityError.*columns? .*not unique.*', error.args[0]):
raise exception.FileAlreadyExists(error.args)
else:
raise exception.RucioException(error.args)
@transactional_session
def __add_collections_to_container_without_temp_tables(scope, name, collections, account, *, session: "Session"):
"""
Add collections (datasets or containers) to container.