forked from rucio/rucio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rucio-admin
executable file
·1803 lines (1572 loc) · 97.5 KB
/
rucio-admin
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 2012-2018 CERN for the benefit of the ATLAS collaboration.
#
# 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.
#
# Authors:
# - Mario Lassnig, <[email protected]>, 2012-2018
# - Martin Barisits, <[email protected]>, 2012-2017
# - Vincent Garonne, <[email protected]>, 2012-2018
# - Thomas Beermann, <[email protected]>, 2012-2013
# - Cedric Serfon, <[email protected]>, 2013-2017
# - Wen Guan, <[email protected]>, 2014
# - Ralph Vigne, <[email protected]>, 2014
# - David Cameron, <[email protected]>, 2014-2015
# - Cheng-Hsi Chao, <[email protected]>, 2014
# - Joaquin Bogado, <[email protected]>, 2014-2015
# - Brian Bockelman, <[email protected]>, 2017-2018
# - Nicolo Magini, <[email protected]>, 2018
from __future__ import print_function
import argparse
import json
import logging
import os
import signal
import sys
import time
import traceback
try:
from ConfigParser import NoOptionError, NoSectionError
except ImportError:
from configparser import NoOptionError, NoSectionError
from functools import wraps
from itertools import groupby
import argcomplete
import tabulate
from rucio.client import Client
from rucio.common.config import config_get
from rucio.common.exception import (AccountNotFound, DataIdentifierAlreadyExists, AccessDenied, DataIdentifierNotFound, InvalidObject, ReplicaNotFound,
RSENotFound, RSEOperationNotSupported, InvalidRSEExpression, DuplicateContent, RuleNotFound, CannotAuthenticate)
from rucio.common.utils import chunks, construct_surl, sizefmt
from rucio import version
from rucio.rse import rsemanager as rsemgr
possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]),
os.pardir, os.pardir))
if os.path.exists(os.path.join(possible_topdir, 'lib/rucio', '__init__.py')):
sys.path.insert(0, possible_topdir)
SUCCESS = 0
FAILURE = 1
DEFAULT_PORT = 443
logger = logging.getLogger("user")
tablefmt = 'psql'
def setup_logger(logger):
logger.setLevel(logging.DEBUG)
hdlr = logging.StreamHandler()
def emit_decorator(fcn):
def func(*args):
if True:
formatter = logging.Formatter("%(message)s")
else:
levelno = args[0].levelno
if levelno >= logging.CRITICAL:
color = '\033[31;1m'
elif levelno >= logging.ERROR:
color = '\033[31;1m'
elif levelno >= logging.WARNING:
color = '\033[33;1m'
elif levelno >= logging.INFO:
color = '\033[32;1m'
elif levelno >= logging.DEBUG:
color = '\033[36;1m'
else:
color = '\033[0m'
formatter = logging.Formatter('{0}%(asctime)s %(levelname)s [%(message)s]\033[0m'.format(color))
hdlr.setFormatter(formatter)
return fcn(*args)
return func
hdlr.emit = emit_decorator(hdlr.emit)
logger.addHandler(hdlr)
setup_logger(logger)
def signal_handler(signal, frame):
logger.warning('You pressed Ctrl+C! Exiting gracefully')
sys.exit(1)
signal.signal(signal.SIGINT, signal_handler)
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 AccountNotFound as error:
logger.error(error)
logger.debug('This means that the specified account cannot be found.')
return error.error_code
except NotImplementedError as error:
logger.error(error)
logger.debug('This means that the method is not implemented yet.')
return FAILURE
except Exception as error:
logger.error(error)
logger.error('Rucio exited with an unexpected/unknown error, please provide the traceback below to the developers.')
logger.debug(traceback.format_exc())
return FAILURE
return new_funct
def get_client(args):
"""
Returns a new client object.
"""
if args.auth_strategy == 'userpass':
creds = {'username': args.username, 'password': args.password}
else:
creds = None
try:
client = Client(rucio_host=args.host, auth_host=args.auth_host,
account=args.issuer,
auth_type=args.auth_strategy, creds=creds,
ca_cert=args.ca_certificate, timeout=args.timeout)
except CannotAuthenticate as error:
logger.error(error)
if not args.auth_strategy:
if 'RUCIO_AUTH_TYPE' in os.environ:
auth_type = os.environ['RUCIO_AUTH_TYPE']
else:
try:
auth_type = config_get('client', 'auth_type')
except (NoOptionError, NoSectionError):
logger.error('Cannot get AUTH_TYPE')
sys.exit(FAILURE)
if auth_type == 'x509_proxy':
logger.error('Please verify that your proxy is still valid and renew it if needed.')
sys.exit(FAILURE)
return client
def extract_scope(did):
# Try to extract the scope from the DSN
if did.find(':') > -1:
scope, name = did.split(':')[0], did.split(':')[1]
if name.endswith('/'):
name = name[:-1]
return scope, name
else:
scope = did.split('.')[0]
if did.startswith('user') or did.startswith('group'):
scope = ".".join(did.split('.')[0:2])
if did.endswith('/'):
did = did[:-1]
return scope, did
@exception_handler
def add_account(args):
"""
%(prog)s add [options] <field1=value1 field2=value2 ...>
Adds a new account. Specify metadata fields as arguments.
"""
client = get_client(args)
client.add_account(account=args.account, type=args.accounttype, email=args.accountemail)
print('Added new account: %s' % args.account)
return SUCCESS
@exception_handler
def delete_account(args):
"""
%(prog)s disable [options] <field1=value1 field2=value2 ...>
Delete account.
"""
client = get_client(args)
client.delete_account(args.acnt)
print('Deleted account: %s' % args.acnt)
return SUCCESS
@exception_handler
def ban_account(args):
"""
%(prog)s ban [options] <field1=value1 field2=value2 ...>
Ban an account.
"""
client = get_client(args)
client.set_account_status(account=args.account, status='SUSPENDED')
print('Account %s banned' % args.account)
return SUCCESS
@exception_handler
def unban_account(args):
"""
%(prog)s unban [options] <field1=value1 field2=value2 ...>
Unban a banned account.
"""
client = get_client(args)
client.set_account_status(account=args.account, status='ACTIVE')
print('Account %s unbanned' % args.account)
return SUCCESS
@exception_handler
def list_accounts(args):
"""
%(prog)s list [options] <field1=value1 field2=value2 ...>
List accounts.
"""
client = get_client(args)
filters = {}
if args.filters:
for key, value in [(_.split('=')[0], _.split('=')[1]) for _ in args.filters.split(',')]:
filters[key] = value
accounts = client.list_accounts(identity=args.identity, account_type=args.account_type, filters=filters)
for account in accounts:
print(account['account'])
return SUCCESS
@exception_handler
def info_account(args):
"""
%(prog)s show [options] <field1=value1 field2=value2 ...>
Show extended information of a given account
"""
client = get_client(args)
info = client.get_account(account=args.account)
for k in info:
print(k.ljust(10) + ' : ' + str(info[k]))
return SUCCESS
@exception_handler
def list_identities(args):
"""
%(prog)s list-identities [options] <field1=value1 field2=value2 ...>
List all identities on an account.
"""
client = get_client(args)
identities = client.list_identities(account=args.account)
for identity in identities:
print('Identity: %(identity)s,\ttype: %(type)s' % identity)
return SUCCESS
@exception_handler
def set_limits(args):
"""
%(prog)s set [options] <field1=value1 field2=value2 ...>
Set account limit for an account and rse.
"""
client = get_client(args)
client.set_account_limit(account=args.account, rse=args.rse, bytes=args.bytes)
print('Set account limit for account %s on RSE %s: %s' % (args.account, args.rse, sizefmt(args.bytes, True)))
return SUCCESS
@exception_handler
def get_limits(args):
"""
%(prog)s get-limits [options] <field1=value1 field2=value2 ...>
Grant an identity access to an account.
"""
client = get_client(args)
limits = client.get_account_limit(account=args.account, rse=args.rse)
for rse in limits:
print('Quota on %s for %s : %s' % (rse, args.account, sizefmt(limits[rse], True)))
return SUCCESS
@exception_handler
def delete_limits(args):
"""
%(prog)s delete [options] <field1=value1 field2=value2 ...>
Delete account limit for an account and rse.
"""
client = get_client(args)
client.delete_account_limit(account=args.account, rse=args.rse)
print('Deleted account limit for account %s and RSE %s' % (args.account, args.rse))
return SUCCESS
@exception_handler
def identity_add(args):
"""
%(prog)s del [options] <field1=value1 field2=value2 ...>
Grant an identity access to an account.
"""
client = get_client(args)
if args.email == "":
print('Error: --email argument can\'t be an empty string. Failed to grant an identity access to an account')
return FAILURE
client.add_identity(account=args.account, identity=args.identity, authtype=args.authtype, email=args.email)
print('Added new identity to account: %s-%s' % (args.identity, args.account))
return SUCCESS
@exception_handler
def identity_delete(args):
"""
%(prog)s delete [options] <field1=value1 field2=value2 ...>
Revoke an identity's access to an account.
"""
client = get_client(args)
client.del_identity(args.account, args.identity, authtype=args.authtype)
print('Deleted identity: %s' % args.identity)
return SUCCESS
@exception_handler
def add_rse(args):
"""
%(prog)s add [options] <field1=value1 field2=value2 ...>
Adds a new rse. Specify metadata fields as arguments.
"""
client = get_client(args)
client.add_rse(args.rse)
print('Added new RSE: %s' % args.rse)
return SUCCESS
@exception_handler
def disable_rse(args):
"""
%(prog)s del [options] <field1=value1 field2=value2 ...>
Disable rse.
"""
client = get_client(args)
client.delete_rse(args.rse)
return SUCCESS
@exception_handler
def list_rses(args):
"""
%(prog)s list [options] <field1=value1 field2=value2 ...>
List rses.
"""
client = get_client(args)
rses = client.list_rses()
for rse in rses:
print('%(rse)s' % rse)
return SUCCESS
@exception_handler
def info_rse(args):
"""
%(prog)s info [options] <field1=value1 field2=value2 ...>
Show extended information of a given rse
"""
client = get_client(args)
rseinfo = client.get_rse(rse=args.rse)
attributes = client.list_rse_attributes(rse=args.rse)
usage = client.get_rse_usage(rse=args.rse)
print('Settings:')
print('=========')
for key in rseinfo:
if key != 'protocols':
print(' ' + key + ': ' + str(rseinfo[key]))
print('Attributes:')
print('===========')
for attribute in attributes:
print(' ' + attribute + ': ' + str(attributes[attribute]))
print('Protocols:')
print('==========')
for protocol in rseinfo['protocols']:
print(' ' + protocol['scheme'])
for item in protocol:
print(' ' + item + ': ' + str(protocol[item]))
print('Usage:')
print('======')
for elem in usage:
print(' ' + elem['source'])
for item in elem:
print(' ' + item + ': ' + str(elem[item]))
return SUCCESS
@exception_handler
def set_attribute_rse(args):
"""
%(prog)s set-attribute [options] <field1=value1 field2=value2 ...>
setattr RSE.
"""
client = get_client(args)
client.add_rse_attribute(rse=args.rse, key=args.key, value=args.value)
print('Added new RSE attribute for %s: %s-%s ' % (args.rse, args.key, args.value))
return SUCCESS
@exception_handler
def get_attribute_rse(args):
"""
%(prog)s get-attribute [options] <field1=value1 field2=value2 ...>
getattr RSE.
"""
client = get_client(args)
attributes = client.list_rse_attributes(rse=args.rse)
for k in attributes:
print(k + ': ' + str(attributes[k]))
return SUCCESS
@exception_handler
def delete_attribute_rse(args):
"""
%(prog)s delete-attribute [options] <field1=value1 field2=value2 ...>
setattr RSE.
"""
client = get_client(args)
client.delete_rse_attribute(rse=args.rse, key=args.key)
print('Deleted RSE attribute for %s: %s-%s ' % (args.rse, args.key, args.value))
return SUCCESS
@exception_handler
def add_distance_rses(args):
"""
%(prog)s add-distance [options] SOURCE_RSE DEST_RSE
Set the distance between two RSEs.
"""
client = get_client(args)
params = {'ranking': args.ranking, 'distance': args.distance}
client.add_distance(args.source, args.destination, params)
print('Set distance from %s to %s to %d with ranking %d' % (args.source, args.destination, args.distance, args.ranking))
return SUCCESS
@exception_handler
def get_distance_rses(args):
"""
%(prog)s get-distance SOURCE_RSE DEST_RSE
Retrieve the existing distance information between two RSEs.
"""
client = get_client(args)
distance_info = client.get_distance(args.source, args.destination)
if distance_info:
print('Distance information from %s to %s: distance=%d, ranking=%d' % (args.source, args.destination, distance_info[0]['distance'], distance_info[0]['ranking']))
else:
print("No distance set from %s to %s" % (args.source, args.destination))
return SUCCESS
@exception_handler
def update_distance_rses(args):
"""
%(prog)s update-distance [options] SOURCE_RSE DEST_RSE
Update the existing distance entry between two RSEs.
"""
client = get_client(args)
params = {}
if args.ranking is not None:
params['ranking'] = args.ranking
if args.distance is not None:
params['distance'] = args.distance
client.update_distance(args.source, args.destination, params)
print('Update distance information from %s to %s:' % (args.source, args.destination))
if args.distance is not None:
print("- Distance set to %d" % args.distance)
if args.ranking is not None:
print("- Ranking set to %d" % args.ranking)
return SUCCESS
@exception_handler
def add_protocol_rse(args):
"""
%(prog)s add-protocol-rse [options] <rse>
Add a new protocol handler for an RSE
"""
client = get_client(args)
proto = {'hostname': args.hostname,
'scheme': args.scheme,
'port': args.port,
'impl': args.impl,
'prefix': args.prefix}
if args.domain_json:
proto['domains'] = args.domain_json
proto.setdefault('extended_attributes', {})
if args.ext_attr_json:
proto['extended_attributes'] = args.ext_attr_json
if proto['scheme'] == 'srm' and not args.web_service_path:
print('Error: space-token and web-service-path must be provided for SRM endpoints.')
return FAILURE
if args.space_token:
proto['extended_attributes']['space_token'] = args.space_token
if args.web_service_path:
proto['extended_attributes']['web_service_path'] = args.web_service_path
# Rucio 1.14.1 chokes on an empty extended_attributes key.
if not proto['extended_attributes']:
del proto['extended_attributes']
client.add_protocol(args.rse, proto)
return SUCCESS
@exception_handler
def del_protocol_rse(args):
"""
%(prog)s delete-protocol-rse [options] <rse>
Remove a protocol handler for a RSE
"""
client = get_client(args)
kwargs = {}
if args.port:
kwargs['port'] = args.port
if args.hostname:
kwargs['hostname'] = args.hostname
client.delete_protocols(args.rse, args.scheme, **kwargs)
@exception_handler
def add_scope(args):
"""
%(prog)s add [options] <field1=value1 field2=value2 ...>
Add scope.
"""
client = get_client(args)
client.add_scope(account=args.account, scope=args.scope)
print('Added new scope to account: %s-%s' % (args.scope, args.account))
return SUCCESS
@exception_handler
def list_scopes(args):
"""
%(prog)s list [options] <field1=value1 field2=value2 ...>
List scopes.
"""
client = get_client(args)
if args.account:
scopes = client.list_scopes_for_account(args.account)
else:
scopes = client.list_scopes()
for scope in scopes:
if 'mock' not in scope:
print(scope)
return SUCCESS
@exception_handler
def get_config(args):
"""
%(prog)s get [options] <field1=value1 field2=value2 ...>
Get the configuration. Either everything, or matching the given section/option.
"""
client = get_client(args)
res = client.get_config(section=args.section, option=args.option)
if not isinstance(res, dict):
print('[%s]\n%s=%s' % (args.section, args.option, str(res)))
else:
print_header = True
for i in list(res.keys()):
if print_header:
if args.section is not None:
print('[%s]' % args.section)
else:
print('[%s]' % i)
if not isinstance(res[i], dict):
print('%s=%s' % (i, str(res[i])))
print_header = False
else:
for j in list(res[i].keys()):
print('%s=%s' % (j, str(res[i][j])))
return SUCCESS
@exception_handler
def set_config_option(args):
"""
%(prog)s set [options] <field1=value1 field2=value2 ...>
Set the configuration value for a matching section/option. Missing section/option will be created.
"""
client = get_client(args)
client.set_config_option(section=args.section, option=args.option, value=args.value)
print('Set configuration: %s.%s=%s' % (args.section, args.option, args.value))
return SUCCESS
@exception_handler
def delete_config_option(args):
"""
%(prog)s delete [options] <field1=value1 field2=value2 ...>
Delete a configuration option from a section
"""
client = get_client(args)
if client.delete_config_option(section=args.section, option=args.option):
print('Deleted section \'%s\' option \'%s\'' % (args.section, args.option))
else:
print('Section \'%s\' option \'%s\' not found' % (args.section, args.option))
return SUCCESS
@exception_handler
def add_subscription(args):
"""
%(prog)s add [options] name Filter replication_rules
Add subscription.
"""
client = get_client(args)
if args.subs_account:
account = args.subs_account
elif args.issuer:
account = args.issuer
else:
account = client.account
subscription_id = client.add_subscription(name=args.name, account=account, filter=json.loads(args.filter), replication_rules=json.loads(args.replication_rules),
comments=args.comments, lifetime=args.lifetime, retroactive=False, dry_run=False, priority=args.priority)
print('Subscription added %s' % (subscription_id))
return SUCCESS
@exception_handler
def list_subscriptions(args):
"""
%(prog)s list [options] [name]
List subscriptions.
"""
client = get_client(args)
if args.subs_account:
account = args.subs_account
elif args.issuer:
account = args.issuer
else:
account = client.account
subs = client.list_subscriptions(name=args.name, account=account)
for sub in subs:
if args.long:
print('\n'.join('%s: %s' % (str(k), str(v)) for (k, v) in list(sub.items())))
print()
else:
print("%s: %s %s\n priority: %s\n filter: %s\n rules: %s\n comments: %s" % (sub['account'], sub['name'], sub['state'], sub['policyid'], sub['filter'], sub['replication_rules'], sub.get('comments', '')))
return SUCCESS
@exception_handler
def update_subscription(args):
"""
%(prog)s update [options] name filter replication_rules
Update a subscription.
"""
client = get_client(args)
if args.subs_account:
account = args.subs_account
elif args.issuer:
account = args.issuer
else:
account = client.account
client.update_subscription(name=args.name, account=account, filter=json.loads(args.filter), replication_rules=json.loads(args.replication_rules),
comments=args.comments, lifetime=args.lifetime, retroactive=False, dry_run=False, priority=args.priority)
return SUCCESS
@exception_handler
def reevaluate_did_for_subscription(args):
"""
%(prog)s reevaulate [options] dids
Reevaluate a list of DIDs against all active subscriptions.
"""
client = get_client(args)
for did in args.dids.split(','):
scope, name = extract_scope(did)
client.set_metadata(scope, name, 'is_new', True)
return SUCCESS
@exception_handler
def list_account_attributes(args):
"""
%(prog)s show [options] <field1=value1 field2=value2 ...>
List the attributes for an account.
"""
client = get_client(args)
account = args.account or client.account
attributes = next(client.list_account_attributes(account))
table = []
for attr in attributes:
table.append([attr['key'], attr['value']])
print(tabulate.tabulate(table, tablefmt=tablefmt, headers=['Key', 'Value']))
return SUCCESS
@exception_handler
def add_account_attribute(args):
"""
%(prog)s show [options] <field1=value1 field2=value2 ...>
Add attribute for an account.
"""
client = get_client(args)
client.add_account_attribute(account=args.account, key=args.key, value=args.value)
return SUCCESS
@exception_handler
def delete_account_attribute(args):
"""
%(prog)s show [options] <field1=value1 field2=value2 ...>
Delete attribute for an account.
"""
client = get_client(args)
client.delete_account_attribute(account=args.account, key=args.key)
return SUCCESS
@exception_handler
def declare_bad_file_replicas(args):
"""
%(prog)s show [options] <field1=value1 field2=value2 ...>
Declare a list of bad replicas.
"""
client = get_client(args)
bad_files = []
if args.inputfile:
with open(args.inputfile) as infile:
for line in infile:
bad_file = line.rstrip('\n')
if bad_file != '':
bad_files.append(bad_file)
else:
bad_files = args.listbadfiles
# Interpret filenames not in scheme://* format as LFNs and convert them to PFNs
bad_files_pfns = []
for bad_file in bad_files:
if bad_file.find('://') == -1:
scope, name = extract_scope(bad_file)
did_info = client.get_did(scope, name)
if did_info['type'].upper() != 'FILE' and not args.allow_collection:
print('DID %s:%s is a collection and --allow-collection was not specified.' % (scope, name))
return FAILURE
replicas = [replica for rep in client.list_replicas([{'scope': scope, 'name': name}])
for replica in list(rep['pfns'].keys())]
bad_files_pfns.extend(replicas)
else:
bad_files_pfns.append(bad_file)
if args.verbose:
print("PFNs that will be declared bad:")
for pfn in bad_files_pfns:
print(pfn)
# Group file list in separate sublists for different schemes
bad_files_pfns.sort()
bad_files_pfns_grouped = groupby(bad_files_pfns, lambda f: f[:f.find('://')])
for sublist in bad_files_pfns_grouped:
for chunk in chunks(list(sublist[1]), 500):
non_declared = client.declare_bad_file_replicas(pfns=chunk, reason=args.reason)
for rse in non_declared:
for pfn in non_declared[rse]:
print('%s : PFN %s cannot be declared.' % (rse, pfn))
return SUCCESS
@exception_handler
def list_pfns(args):
"""
%(prog)s list [options] <field1=value1 field2=value2 ...>
List the possible PFN for a file at a site.
"""
client = get_client(args)
dids = args.dids.split(',')
rse = args.rse
protocol = args.protocol
for input_did in dids:
scope, name = extract_scope(input_did)
replicas = [rep for rep in client.list_replicas([{'scope': scope, 'name': name}, ], schemes=[protocol, ])]
if rse in replicas[0]['rses'] and replicas[0]['rses'][rse]:
print(replicas[0]['rses'][rse][0])
else:
logger.warning('The file has no replica on the specified RSE')
rse_info = rsemgr.get_rse_info(rse)
proto = rsemgr.create_protocol(rse_info, 'read', scheme=protocol)
try:
pfn = proto.lfns2pfns(lfns={'scope': scope, 'name': name})
result = list(pfn.values())[0]
except ReplicaNotFound as error:
result = error
if isinstance(result, (RSEOperationNotSupported, ReplicaNotFound)):
if not rse_info['deterministic']:
logger.warning('This is a non-deterministic site, so the real PFN might be different from the on suggested')
rse_attr = client.list_rse_attributes(rse)
naming_convention = rse_attr.get('naming_convention', None)
parents = [did for did in client.list_parent_dids(scope, name)]
if len(parents) > 1:
logger.warning('The file has multiple parents')
for did in parents:
if did['type'] == 'DATASET':
path = construct_surl(did['name'], name, naming_convention=naming_convention)
pfn = ''.join([proto.attributes['scheme'],
'://',
proto.attributes['hostname'],
':',
str(proto.attributes['port']),
proto.attributes['prefix'],
path if not path.startswith('/') else path[1:]])
print(pfn)
else:
logger.error('Unexpected error')
return FAILURE
else:
print(result)
return SUCCESS
def get_parser():
"""
Returns the argparse parser.
"""
oparser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]), add_help=True)
subparsers = oparser.add_subparsers()
# Main arguments
oparser.add_argument('--version', action='version', version='%(prog)s ' + version.version_string())
oparser.add_argument('--verbose', '-v', default=False, action='store_true', help="Print more verbose output")
oparser.add_argument('-H', '--host', dest="host", metavar="ADDRESS", help="The Rucio API host")
oparser.add_argument('--auth-host', dest="auth_host", metavar="ADDRESS", help="The Rucio Authentication host")
oparser.add_argument('-a', '--account', dest="issuer", metavar="ACCOUNT", help="Rucio account to use")
oparser.add_argument('-S', '--auth-strategy', dest="auth_strategy", default=None, help="Authentication strategy (userpass, x509, ssh ...)")
oparser.add_argument('-T', '--timeout', dest="timeout", type=float, default=None, help="Set all timeout values to SECONDS")
# Options for the userpass auth_strategy
oparser.add_argument('-u', '--user', dest='username', default=None, help='username')
oparser.add_argument('-pwd', '--password', dest='password', default=None, help='password')
# Options for the x509 auth_strategy
oparser.add_argument('--certificate', dest='certificate', default=None, help='Client certificate file')
oparser.add_argument('--ca-certificate', dest='ca_certificate', default=None, help='CA certificate to verify peer against (SSL)')
# The account subparser
account_parser = subparsers.add_parser('account', help='Account methods')
account_subparser = account_parser.add_subparsers()
# The list_accounts command
list_account_parser = account_subparser.add_parser('list',
help='List Rucio accounts.',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='Usage example\n'
'"""""""""""""\n'
'::\n'
'\n'
' $ rucio-admin account list --type \'user\'\n'
'\n')
list_account_parser.add_argument('--type', dest='account_type', action='store', help='Account Type (USER, GROUP, SERVICE)')
list_account_parser.add_argument('--id', dest='identity', action='store', help='Identity (e.g. DN)')
list_account_parser.add_argument('--filters', dest='filters', action='store', help='Filter arguments in form `key=value,another_key=next_value`')
list_account_parser.set_defaults(which='list_accounts')
# The list_account_attributes command
list_attr_parser = account_subparser.add_parser('list-attributes',
help='List attributes for an account.',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='Usage example\n'
'"""""""""""""\n'
'::\n'
'\n'
' $ rucio-admin account list-attributes jdoe\n'
' +-------+---------+\n'
' | Key | Value |\n'
' |-------+---------|\n'
' | admin | False |\n'
' +-------+---------+\n'
'\n'
'Note: this table empty in most cases.\n'
'\n')
list_attr_parser.add_argument('account', action='store', help='Account name')
list_attr_parser.set_defaults(which='list_account_attributes')
# The add_account_attribute command