-
Notifications
You must be signed in to change notification settings - Fork 302
/
rucio
executable file
·2504 lines (2172 loc) · 124 KB
/
rucio
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# 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 argparse
import errno
import itertools
import logging
import math
import os
import signal
import subprocess
import sys
import time
import traceback
import unittest
import uuid
from configparser import NoOptionError, NoSectionError
from copy import deepcopy
from datetime import datetime
from functools import wraps
from tabulate import tabulate
# rucio module has the same name as this executable module, so this rule fails. pylint: disable=no-name-in-module
from rucio import version
from rucio.client import Client
from rucio.common.config import config_get, config_get_float
from rucio.common.constants import ReplicaState
from rucio.common.exception import (
AccessDenied,
CannotAuthenticate,
DataIdentifierAlreadyExists,
DataIdentifierNotFound,
DIDFilterSyntaxError,
DuplicateContent,
DuplicateCriteriaInDIDFilter,
DuplicateRule,
InputValidationError,
InvalidObject,
InvalidRSEExpression,
InvalidType,
MissingDependency,
RSENotFound,
RucioException,
RuleNotFound,
UnsupportedOperation,
)
from rucio.common.extra import import_extras
from rucio.common.test_rucio_server import TestRucioServer
from rucio.common.utils import Color, StoreAndDeprecateWarningAction, chunks, detect_client_location, extract_scope, parse_did_filter_from_string, parse_did_filter_from_string_fe, setup_logger, sizefmt
EXTRA_MODULES = import_extras(['argcomplete'])
if EXTRA_MODULES['argcomplete']:
import argcomplete # pylint: disable=E0401
SUCCESS = 0
FAILURE = 1
DEFAULT_SECURE_PORT = 443
DEFAULT_PORT = 80
logger = logging.log
gfal2_logger = logging.getLogger("gfal2")
tablefmt = 'psql'
def setup_gfal2_logger(logger):
logger.setLevel(logging.CRITICAL)
logger.addHandler(logging.StreamHandler())
setup_gfal2_logger(gfal2_logger)
def signal_handler(sig, frame):
logger.warning('You pressed Ctrl+C! Exiting gracefully')
child_processes = subprocess.Popen('ps -o pid --ppid %s --noheaders' % os.getpid(), shell=True, stdout=subprocess.PIPE)
child_processes = child_processes.stdout.read()
for pid in child_processes.split("\n")[:-1]:
try:
os.kill(int(pid), signal.SIGTERM)
except Exception:
print('Cannot kill child process')
sys.exit(1)
signal.signal(signal.SIGINT, signal_handler)
def get_scope(did, client):
try:
scope, name = extract_scope(did)
return scope, name
except TypeError:
scopes = client.list_scopes()
scope, name = extract_scope(did, scopes)
return scope, name
return None, did
def exception_handler(function):
@wraps(function)
def new_funct(*args, **kwargs):
try:
return function(*args, **kwargs)
except InvalidObject as error:
logger.error(error)
return error.error_code
except DataIdentifierNotFound as error:
logger.error(error)
logger.debug('This means that the Data IDentifier you provided is not known by Rucio.')
return error.error_code
except AccessDenied as error:
logger.error(error)
logger.debug('This error is a permission issue. You cannot run this command with your account.')
return error.error_code
except DataIdentifierAlreadyExists as error:
logger.error(error)
logger.debug('This means that the Data IDentifier you try to add is already registered in Rucio.')
return error.error_code
except RSENotFound as error:
logger.error(error)
logger.debug('This means that the Rucio Storage Element you provided is not known by Rucio.')
return error.error_code
except InvalidRSEExpression as error:
logger.error(error)
logger.debug('This means the RSE expression you provided is not syntactically correct.')
return error.error_code
except DuplicateContent as error:
logger.error(error)
logger.debug('This means that the DID you want to attach is already in the target DID.')
return error.error_code
except TypeError as error:
logger.error(error)
logger.debug('This means the parameter you passed has a wrong type.')
return FAILURE
except RuleNotFound as error:
logger.error(error)
logger.debug('This means the rule you specified does not exist.')
return error.error_code
except UnsupportedOperation as error:
logger.error(error)
logger.debug('This means you cannot change the status of the DID.')
return error.error_code
except MissingDependency as error:
logger.error(error)
logger.debug('This means one dependency is missing.')
return error.error_code
except KeyError as error:
if 'x-rucio-auth-token' in str(error):
used_account = None
try: # get the configured account from the configuration file
used_account = '%s (from rucio.cfg)' % config_get('client', 'account')
except:
pass
try: # are we overriden by the environment?
used_account = '%s (from RUCIO_ACCOUNT)' % os.environ['RUCIO_ACCOUNT']
except:
pass
logger.error('Specified account %s does not have an associated identity.' % used_account)
else:
logger.debug(traceback.format_exc())
contact = config_get('policy', 'support', raise_exception=False)
support = ('Please follow up with all relevant information at: ' + contact) if contact else ''
logger.error('\nThe object is missing this property: %s\n'
'This should never happen. Please rerun the last command with the "-v" option to gather more information.\n'
'%s' % (str(error), support))
return FAILURE
except RucioException as error:
logger.error(error)
return error.error_code
except Exception as error:
if isinstance(error, IOError) and getattr(error, 'errno', None) == errno.EPIPE:
# Ignore Broken Pipe
# While in python3 we can directly catch 'BrokenPipeError', in python2 it doesn't exist.
# Python flushes standard streams on exit; redirect remaining output
# to devnull to avoid another BrokenPipeError at shutdown
devnull = os.open(os.devnull, os.O_WRONLY)
os.dup2(devnull, sys.stdout.fileno())
return SUCCESS
logger.debug(traceback.format_exc())
logger.error(error)
contact = config_get('policy', 'support', raise_exception=False)
support = ("If it's a problem concerning your experiment or if you're unsure what to do, please follow up at: %s\n" % contact) if contact else ''
contact = config_get('policy', 'support_rucio', default='https://github.com/rucio/rucio/issues')
support += "If you're sure there is a problem with Rucio itself, please follow up at: " + contact
logger.error('\nRucio exited with an unexpected/unknown error.\n'
'Please rerun the last command with the "-v" option to gather more information.\n'
'%s' % support)
return FAILURE
return new_funct
def get_client(args):
"""
Returns a new client object.
"""
if not args.auth_strategy:
if 'RUCIO_AUTH_TYPE' in os.environ:
auth_type = os.environ['RUCIO_AUTH_TYPE'].lower()
else:
try:
auth_type = config_get('client', 'auth_type').lower()
except (NoOptionError, NoSectionError):
logger.error('Cannot get AUTH_TYPE')
sys.exit(FAILURE)
else:
auth_type = args.auth_strategy.lower()
if auth_type in ['userpass', 'saml'] and args.username is not None and args.password is not None:
creds = {'username': args.username, 'password': args.password}
elif auth_type == 'oidc':
if args.oidc_issuer:
args.oidc_issuer = args.oidc_issuer.lower()
creds = {'oidc_auto': args.oidc_auto,
'oidc_scope': args.oidc_scope,
'oidc_audience': args.oidc_audience,
'oidc_polling': args.oidc_polling,
'oidc_refresh_lifetime': args.oidc_refresh_lifetime,
'oidc_issuer': args.oidc_issuer,
'oidc_username': args.oidc_username,
'oidc_password': args.oidc_password}
else:
creds = None
try:
client = Client(rucio_host=args.host, auth_host=args.auth_host,
account=args.account,
auth_type=auth_type, creds=creds,
ca_cert=args.ca_certificate, timeout=args.timeout,
user_agent=args.user_agent, vo=args.vo,
logger=logger)
except CannotAuthenticate as error:
logger.error(error)
if 'alert certificate expired' in str(error):
logger.error('The server certificate expired.')
elif auth_type.lower() == 'x509_proxy':
logger.error('Please verify that your proxy is still valid and renew it if needed.')
sys.exit(FAILURE)
return client
def __resolve_containers_to_datasets(scope, name, client):
"""
Helper function to resolve a container into its dataset content.
"""
datasets = []
for did in client.list_content(scope, name):
if did['type'] == 'DATASET':
datasets.append({'scope': did['scope'], 'name': did['name']})
elif did['type'] == 'CONTAINER':
datasets.extend(__resolve_containers_to_datasets(did['scope'], did['name'], client))
return datasets
@exception_handler
def ping(args):
"""
Pings a Rucio server.
"""
client = get_client(args)
server_info = client.ping()
if server_info:
print(server_info['version'])
return SUCCESS
logger.error('Ping failed')
return FAILURE
@exception_handler
def whoami_account(args):
"""
%(prog)s show [options] <field1=value1 field2=value2 ...>
Show extended information of a given account
"""
client = get_client(args)
info = client.whoami()
for k in info:
print(k.ljust(10) + ' : ' + str(info[k]))
return SUCCESS
@exception_handler
def list_dataset_replicas(args):
"""
%(prog)s list [options] <field1=value1 field2=value2 ...>
List dataset replicas
"""
client = get_client(args)
result = {}
datasets = []
def _append_to_datasets(scope, name):
filedid = {'scope': scope, 'name': name}
if filedid not in datasets:
datasets.append(filedid)
def _fetch_datasets_for_meta(meta):
"""Internal function to fetch datasets and recurse into files."""
if meta['did_type'] != 'DATASET':
dids = client.scope_list(scope=meta['scope'], name=meta['name'], recursive=True)
for did in dids:
if did['type'] == 'FILE':
_append_to_datasets(did['parent']['scope'], did['parent']['name'])
else:
_append_to_datasets(meta['scope'], meta['name'])
def _append_result(dsn, replica):
if dsn not in result:
result[dsn] = {}
result[dsn][replica['rse']] = [replica['rse'], replica['available_length'], replica['length']]
if len(args.dids) == 1:
scope, name = get_scope(args.dids[0], client)
dmeta = client.get_metadata(scope, name)
_fetch_datasets_for_meta(meta=dmeta)
else:
extractdids = (get_scope(did, client) for did in args.dids)
splitdids = [{'scope': scope, 'name': name} for scope, name in extractdids]
for dmeta in client.get_metadata_bulk(dids=splitdids):
_fetch_datasets_for_meta(meta=dmeta)
if args.deep or len(datasets) < 2:
for did in datasets:
dsn = "%s:%s" % (did['scope'], did['name'])
for rep in client.list_dataset_replicas(scope=did['scope'], name=did['name'], deep=args.deep):
_append_result(dsn=dsn, replica=rep)
else:
for rep in client.list_dataset_replicas_bulk(dids=datasets):
dsn = "%s:%s" % (rep['scope'], rep['name'])
_append_result(dsn=dsn, replica=rep)
if args.csv:
for dsn in result:
for rse in list(result[dsn].values()):
print(rse[0], rse[1], rse[2], sep=',')
else:
for dsn in result:
print('\nDATASET: %s' % (dsn))
print(tabulate(list(result[dsn].values()), tablefmt=tablefmt, headers=['RSE', 'FOUND', 'TOTAL']))
return SUCCESS
@exception_handler
def list_file_replicas(args):
"""
%(prog)s list [options] <field1=value1 field2=value2 ...>
List file replicas
"""
if args.missing:
args.all_states = True
client = get_client(args)
protocols = None
if args.protocols:
protocols = args.protocols.split(',')
table = []
dids = []
if args.missing and not args.rses:
print('Cannot use --missing without specifying a RSE')
return FAILURE
if args.link and ':' not in args.link:
print('The substitution parameter must equal --link="/pfn/dir:/dst/dir"')
return FAILURE
for did in args.dids:
scope, name = get_scope(did, client)
client.get_metadata(scope=scope, name=name) # break with Exception before streaming replicas if DID does not exist
dids.append({'scope': scope, 'name': name})
replicas = client.list_replicas(dids, schemes=protocols,
ignore_availability=True,
all_states=args.all_states,
rse_expression=args.rses,
metalink=args.metalink,
client_location=detect_client_location(),
sort=args.sort, domain=args.domain,
resolve_archives=not args.no_resolve_archives)
rses = [rse["rse"] for rse in client.list_rses(rse_expression=args.rses)]
if args.metalink:
print(replicas[:-1]) # last character is newline, no need to print that
return SUCCESS
if args.missing:
for replica, rse in itertools.product(replicas, rses):
if 'states' in replica and rse in replica['states'] and replica['states'].get(rse) != 'AVAILABLE':
table.append([replica['scope'], replica['name'], "({0}) {1}".format(ReplicaState[replica['states'].get(rse)].value, rse)])
print(tabulate(table, tablefmt=tablefmt, headers=['SCOPE', 'NAME', '(STATE) RSE']))
elif args.link:
pfn_dir, dst_dir = args.link.split(':')
if args.rses:
for replica, rse in itertools.product(replicas, rses):
if rse in list(replica['rses'].keys()) and replica['rses'][rse]:
for pfn in replica['rses'][rse]:
os.symlink(dst_dir + pfn.rsplit(pfn_dir)[-1], replica['name'])
else:
for replica in replicas:
for rse in replica['rses']:
if replica['rses'][rse]:
for pfn in replica['rses'][rse]:
os.symlink(dst_dir + pfn.rsplit(pfn_dir)[-1], replica['name'])
elif args.pfns:
if args.rses:
for replica, rse in itertools.product(replicas, rses):
if rse in list(replica['rses'].keys()) and replica['rses'][rse]:
for pfn in replica['rses'][rse]:
print(pfn)
else:
for replica in replicas:
for rse in replica['rses']:
if replica['rses'][rse]:
for pfn in replica['rses'][rse]:
print(pfn)
else:
if args.all_states:
header = ['SCOPE', 'NAME', 'FILESIZE', 'ADLER32', '(STATE) RSE: REPLICA']
else:
header = ['SCOPE', 'NAME', 'FILESIZE', 'ADLER32', 'RSE: REPLICA']
for replica in replicas:
if 'bytes' in replica:
for rse in replica['rses']:
for pfn in replica['rses'][rse]:
if args.all_states:
rse_string = '({2}) {0}: {1}'.format(rse, pfn, ReplicaState[replica['states'][rse]].value)
else:
rse_string = '{0}: {1}'.format(rse, pfn)
if args.rses:
for selected_rse in rses:
if rse == selected_rse:
table.append([replica['scope'], replica['name'], sizefmt(replica['bytes'], args.human), replica['adler32'], rse_string])
else:
table.append([replica['scope'], replica['name'], sizefmt(replica['bytes'], args.human), replica['adler32'], rse_string])
print(tabulate(table, tablefmt=tablefmt, headers=header, disable_numparse=True))
return SUCCESS
@exception_handler
def add_dataset(args):
"""
%(prog)s add-dataset [options] <dsn>
Add a dataset identifier.
"""
client = get_client(args)
scope, name = get_scope(args.did, client)
client.add_dataset(scope=scope, name=name, statuses={'monotonic': args.monotonic}, lifetime=args.lifetime)
print('Added %s:%s' % (scope, name))
return SUCCESS
@exception_handler
def add_container(args):
"""
%(prog)s add-container [options] <dsn>
Add a container identifier.
"""
client = get_client(args)
scope, name = get_scope(args.did, client)
client.add_container(scope=scope, name=name, statuses={'monotonic': args.monotonic}, lifetime=args.lifetime)
print('Added %s:%s' % (scope, name))
return SUCCESS
@exception_handler
def attach(args):
"""
%(prog)s attach [options] <field1=value1 field2=value2 ...>
Attach a data identifier.
"""
client = get_client(args)
scope, name = get_scope(args.todid, client)
dids = args.dids
limit = 499
if args.fromfile:
if len(dids) > 1:
logger.error("If --fromfile option is active, only one file is supported. The file should contain a list of dids, one per line.")
return FAILURE
try:
f = open(dids[0], 'r')
dids = [did.rstrip() for did in f.readlines()]
except OSError:
logger.error("Can't open file '" + dids[0] + "'.")
return FAILURE
dids = [{'scope': get_scope(did, client)[0], 'name': get_scope(did, client)[1]} for did in dids]
if len(dids) <= limit:
client.attach_dids(scope=scope, name=name, dids=dids)
else:
logger.warning("You are trying to attach too much DIDs. Therefore they will be chunked and attached in multiple commands.")
missing_dids = []
for i, chunk in enumerate(chunks(dids, limit)):
logger.info("Try to attach chunk {0}/{1}".format(i, int(math.ceil(float(len(dids)) / float(limit)))))
try:
client.attach_dids(scope=scope, name=name, dids=chunk)
except Exception:
content = [{'scope': did['scope'], 'name': did['name']} for did in client.list_content(scope=scope, name=name)]
missing_dids += [did for did in chunk if did not in content]
if missing_dids:
for chunk in chunks(missing_dids, limit):
client.attach_dids(scope=scope, name=name, dids=chunk)
print('DIDs successfully attached to %s:%s' % (scope, name))
return SUCCESS
@exception_handler
def detach(args):
"""
%(prog)s detach [options] <field1=value1 field2=value2 ...>
Detach data identifier.
"""
client = get_client(args)
scope, name = get_scope(args.fromdid, client)
dids = []
for did in args.dids:
cscope, cname = get_scope(did, client)
dids.append({'scope': cscope, 'name': cname})
client.detach_dids(scope=scope, name=name, dids=dids)
print('DIDs successfully detached from %s:%s' % (scope, name))
return SUCCESS
@exception_handler
def list_dids(args):
"""
%(prog)s list-dids scope[:*|:name] [--filter 'value' | --recursive]
List the data identifiers for a given scope.
"""
client = get_client(args)
filters = {}
type_ = 'collection'
table = []
try:
scope, name = get_scope(args.did[0], client)
if name == '':
name = '*'
except InvalidObject:
scope = args.did[0]
name = '*'
if scope not in client.list_scopes():
logger.error('Scope not found')
return FAILURE
if args.recursive and '*' in name:
logger.error('Option recursive cannot be used with wildcards')
return FAILURE
else:
if filters:
if ('name' in filters) and (name != '*'):
logger.error('Must have a wildcard in did name if filtering by name')
return FAILURE
try:
filters, type_ = parse_did_filter_from_string_fe(args.filter, name)
except InvalidType as error:
logger.error(error)
return FAILURE
except DuplicateCriteriaInDIDFilter as error:
logger.error(error)
return FAILURE
except DIDFilterSyntaxError as error:
logger.error(error)
return FAILURE
except ValueError as error:
logger.error(error)
return FAILURE
except Exception as e:
logger.error(e)
return FAILURE
for did in client.list_dids(scope, filters=filters, did_type=type_, long=True, recursive=args.recursive):
table.append(['%s:%s' % (did['scope'], did['name']), did['did_type']])
if args.short:
for did, _ in table:
print(did)
else:
print(tabulate(table, tablefmt=tablefmt, headers=['SCOPE:NAME', '[DID TYPE]']))
return SUCCESS
@exception_handler
def list_dids_extended(args):
"""
%(prog)s list-dids-extended scope[:*|:name] [--filter 'key=value' | --recursive]
List the data identifiers for a given scope (DEPRECATED).
"""
logger.error("This command has been deprecated. Please use list_dids instead.")
return FAILURE
@exception_handler
def list_scopes(args):
"""
%(prog)s list-scopes <scope>
List scopes.
"""
# For the moment..
client = get_client(args)
scopes = client.list_scopes()
for scope in scopes:
print(scope)
return SUCCESS
@exception_handler
def list_files(args):
"""
%(prog)s list-files [options] <field1=value1 field2=value2 ...>
List data identifier contents.
"""
client = get_client(args)
if args.csv:
for did in args.dids:
scope, name = get_scope(did, client)
for f in client.list_files(scope=scope, name=name):
guid = f['guid']
if guid:
guid = '%s-%s-%s-%s-%s' % (guid[0:8], guid[8:12], guid[12:16], guid[16:20], guid[20:32])
else:
guid = '(None)'
print('{}:{}'.format(f['scope'], f['name']), guid, f['adler32'], sizefmt(f['bytes'], args.human), f['events'], sep=',')
return SUCCESS
elif args.LOCALPATH:
print('''<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE POOLFILECATALOG SYSTEM "InMemory">
<POOLFILECATALOG>''')
file_str = ''' <File ID="%s">
<physical>
<pfn filetype="ROOT_All" name="%s/%s"/>
</physical>
<logical>
<lfn name="%s"/>
</logical>
</File>'''
for did in args.dids:
scope, name = get_scope(did, client)
for f in client.list_files(scope=scope, name=name):
guid = f['guid']
if guid:
guid = '%s-%s-%s-%s-%s' % (guid[0:8], guid[8:12], guid[12:16], guid[16:20], guid[20:32])
else:
guid = '(None)'
print(file_str % (guid, args.LOCALPATH, f['name'], f['name']))
print('</POOLFILECATALOG>')
return SUCCESS
else:
table = []
for did in args.dids:
totfiles = 0
totsize = 0
totevents = 0
scope, name = get_scope(did, client)
for file in client.list_files(scope=scope, name=name):
totfiles += 1
totsize += int(file['bytes'])
if file['events']:
totevents += int(file.get('events', 0))
guid = file['guid']
if guid:
guid = '%s-%s-%s-%s-%s' % (guid[0:8], guid[8:12], guid[12:16], guid[16:20], guid[20:32])
else:
guid = '(None)'
table.append(['%s:%s' % (file['scope'], file['name']), guid, 'ad:%s' % file['adler32'], sizefmt(file['bytes'], args.human), file['events']])
print(tabulate(table, tablefmt=tablefmt, headers=['SCOPE:NAME', 'GUID', 'ADLER32', 'FILESIZE', 'EVENTS'], disable_numparse=True))
print('Total files : %s' % totfiles)
print('Total size : %s' % sizefmt(totsize, args.human))
if totevents:
print('Total events : %s' % totevents)
return SUCCESS
@exception_handler
def list_content(args):
"""
%(prog)s list-content [options] <field1=value1 field2=value2 ...>
List data identifier contents.
"""
client = get_client(args)
table = []
for did in args.dids:
scope, name = get_scope(did, client)
for content in client.list_content(scope=scope, name=name):
table.append(['%s:%s' % (content['scope'], content['name']), content['type'].upper()])
if args.short:
for did, dummy in table:
print(did)
else:
print(tabulate(table, tablefmt=tablefmt, headers=['SCOPE:NAME', '[DID TYPE]']))
return SUCCESS
@exception_handler
def list_content_history(args):
"""
%(prog)s list-content-history [options] <field1=value1 field2=value2 ...>
List data identifier contents.
"""
client = get_client(args)
table = []
for did in args.dids:
scope, name = get_scope(did, client)
for content in client.list_content_history(scope=scope, name=name):
table.append(['%s:%s' % (content['scope'], content['name']), content['type'].upper()])
print(tabulate(table, tablefmt=tablefmt, headers=['SCOPE:NAME', '[DID TYPE]']))
return SUCCESS
@exception_handler
def list_parent_dids(args):
"""
%(prog)s list-parent-dids
List parent data identifier.
"""
client = get_client(args)
if args.pfns:
dict_datasets = {}
for res in client.get_did_from_pfns(args.pfns):
for key in res:
if key not in dict_datasets:
dict_datasets[key] = []
for rule in client.list_associated_rules_for_file(res[key]['scope'], res[key]['name']):
if '%s:%s' % (rule['scope'], rule['name']) not in dict_datasets[key]:
dict_datasets[key].append('%s:%s' % (rule['scope'], rule['name']))
for pfn in dict_datasets:
print('PFN: ', pfn)
print('Parents: ', ','.join(dict_datasets[pfn]))
elif args.guids:
guids = []
for input_ in args.guids:
try:
uuid.UUID(input_)
except ValueError:
continue
dict_datasets = {}
for guid in guids:
for did in client.get_dataset_by_guid(guid):
if guid not in dict_datasets:
dict_datasets[guid] = []
for rule in client.list_associated_rules_for_file(did['scope'], did['name']):
if '%s:%s' % (rule['scope'], rule['name']) not in dict_datasets[guid]:
dict_datasets[guid].append('%s:%s' % (rule['scope'], rule['name']))
for guid in dict_datasets:
print('GUID: ', guid)
print('Parents : ', ','.join(dict_datasets[guid]))
elif args.did:
table = []
scope, name = get_scope(args.did, client)
for dataset in client.list_parent_dids(scope=scope, name=name):
table.append(['%s:%s' % (dataset['scope'], dataset['name']), dataset['type']])
print(tabulate(table, tablefmt=tablefmt, headers=['SCOPE:NAME', '[DID TYPE]']))
else:
print('At least one option has to be given. Use -h to list the options.')
return FAILURE
return SUCCESS
@exception_handler
def close(args):
"""
%(prog)s close [options] <field1=value1 field2=value2 ...>
Close a dataset or container.
"""
client = get_client(args)
for did in args.dids:
scope, name = get_scope(did, client)
client.set_status(scope=scope, name=name, open=False)
print(f'{scope}:{name} has been closed.')
return SUCCESS
@exception_handler
def reopen(args):
"""
%(prog)s reopen [options] <field1=value1 field2=value2 ...>
Reopen a dataset or container (only for privileged users).
"""
client = get_client(args)
for did in args.dids:
scope, name = get_scope(did, client)
client.set_status(scope=scope, name=name, open=True)
print(f'{scope}:{name} has been reopened.')
return SUCCESS
@exception_handler
def stat(args):
"""
%(prog)s stat [options] <field1=value1 field2=value2 ...>
List attributes and statuses about data identifiers..
"""
client = get_client(args)
for i, did in enumerate(args.dids):
if i > 0:
print('------')
scope, name = get_scope(did, client)
info = client.get_did(scope=scope, name=name, dynamic_depth='DATASET')
table = [(k + ':', str(v)) for (k, v) in sorted(info.items())]
print(tabulate(table, tablefmt='plain', disable_numparse=True))
return SUCCESS
def erase(args):
"""
%(prog)s erase [options] <field1=value1 field2=value2 ...>
Delete data identifier.
"""
client = get_client(args)
for did in args.dids:
if '*' in did:
logger.warning("This command doesn't support wildcards! Skipping DID: %s" % did)
continue
try:
scope, name = get_scope(did, client)
except RucioException as error:
logger.warning('DID is in wrong format: %s' % did)
logger.debug('Error: %s' % error)
continue
if args.undo:
try:
client.set_metadata(scope=scope, name=name, key='lifetime', value=None)
logger.info('Erase undo for DID: {0}:{1}'.format(scope, name))
except Exception:
logger.warning('Cannot undo erase operation on DID. DID not existent or grace period of 24 hours already expired.')
logger.warning(' DID: {0}:{1}'.format(scope, name))
else:
try:
# set lifetime to expire in 24 hours (value is in seconds).
client.set_metadata(scope=scope, name=name, key='lifetime', value=86400)
logger.info('CAUTION! erase operation is irreversible after 24 hours. To cancel this operation you can run the following command:')
print("rucio erase --undo {0}:{1}".format(scope, name))
except RucioException as error:
logger.warning('Failed to erase DID: %s' % did)
logger.debug('Error: %s' % error)
return SUCCESS
@exception_handler
def upload(args):
"""
rucio upload [scope:datasetname] [folder/] [files1 file2 file3]
%(prog)s upload [options] <field1=value1 field2=value2 ...>
Upload files into Rucio
"""
if args.lifetime and args.expiration_date:
logger.error("--lifetime and --expiration-date cannot be specified at the same time.")
return FAILURE
elif args.expiration_date:
expiration_date = datetime.strptime(args.expiration_date, "%Y-%m-%d-%H:%M:%S")
if expiration_date < datetime.utcnow():
logger.error("The specified expiration date should be in the future!")
return FAILURE
args.lifetime = (expiration_date - datetime.utcnow()).total_seconds()
dsscope = None
dsname = None
for arg in args.args:
did = arg.split(':')
if not dsscope and len(did) == 2:
dsscope = did[0]
dsname = did[1]
elif len(did) == 2:
logger.warning('Ignoring input {} because dataset DID is already set {}:{}'.format(arg, dsscope, dsname))
items = []
for arg in args.args:
if arg.count(':') > 0:
continue
if args.pfn:
if args.impl:
logger.warning('Ignoring --impl option because --pfn option given')
args.impl = None
items.append({'path': arg,
'rse': args.rse,
'did_scope': args.scope,
'did_name': args.name,
'impl': args.impl,
'dataset_scope': dsscope,
'dataset_name': dsname,
'force_scheme': args.protocol,
'pfn': args.pfn,
'no_register': args.no_register,
'lifetime': args.lifetime,
'register_after_upload': args.register_after_upload,
'transfer_timeout': args.transfer_timeout,
'guid': args.guid,
'recursive': args.recursive})
if len(items) < 1:
raise InputValidationError('No files could be extracted from the given arguments')
if len(items) > 1 and args.guid:
logger.error("A single GUID was specified on the command line, but there are multiple files to upload.")
logger.error("If GUID auto-detection is not used, only one file may be uploaded at a time")
raise InputValidationError('Invalid input argument composition')
if len(items) > 1 and args.name:
logger.error("A single LFN was specified on the command line, but there are multiple files to upload.")
logger.error("If LFN auto-detection is not used, only one file may be uploaded at a time")
raise InputValidationError('Invalid input argument composition')
if args.recursive and args.pfn:
logger.error("It is not possible to create the folder structure into collections with a non-deterministic way.")
logger.error("If PFN is specified, you cannot use --recursive")
raise InputValidationError('Invalid input argument composition')
client = get_client(args)
from rucio.client.uploadclient import UploadClient
upload_client = UploadClient(client, logger=logger)
summary_file_path = 'rucio_upload.json' if args.summary else None
upload_client.upload(items, summary_file_path)
return SUCCESS
@exception_handler
def download(args):
"""
%(prog)s download [options] <field1=value1 field2=value2 ...>
Download files from Rucio using new threaded model and RSE expression support
"""
# Input validation
if not args.dids and not args.filter and not args.metalink_file:
logger.error('At least one did is mandatory')
return FAILURE
elif not args.dids and args.filter and not args.scope:
logger.error('The argument scope is mandatory')
return FAILURE
if args.filter and args.metalink_file:
logger.error('Arguments filter and metalink cannot be used together.')
return FAILURE
if args.dids and args.metalink_file:
logger.error('Arguments dids and metalink cannot be used together.')
return FAILURE
if args.ignore_checksum and args.check_local_with_filesize_only:
logger.error('Arguments ignore-checksum and check-local-with-filesize-only cannot be used together.')
return FAILURE
trace_pattern = {}
if args.trace_appid:
trace_pattern['appid'] = args.trace_appid
if args.trace_dataset:
trace_pattern['dataset'] = args.trace_dataset
if args.trace_datasetscope:
trace_pattern['datasetScope'] = args.trace_datasetscope
if args.trace_eventtype:
trace_pattern['eventType'] = args.trace_eventtype
if args.trace_pq:
trace_pattern['pq'] = args.trace_pq
if args.trace_taskid:
trace_pattern['taskid'] = args.trace_taskid
if args.trace_usrdn:
trace_pattern['usrdn'] = args.trace_usrdn