/
config.py
796 lines (668 loc) · 23.7 KB
/
config.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
# -*- 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.
"""Provides functions to access the local configuration. The configuration locations are provided by get_config_dirs."""
import configparser
import json
import os
from collections.abc import Callable
from typing import TYPE_CHECKING, Optional, TypeVar, Union, overload
from rucio.common import exception
from rucio.common.exception import ConfigNotFound, DatabaseException
_T = TypeVar('_T')
_U = TypeVar('_U')
if TYPE_CHECKING:
from sqlalchemy.orm import Session
def convert_to_any_type(value) -> Union[bool, int, float, str]:
if value.lower() in ['true', 'yes', 'on']:
return True
elif value.lower() in ['false', 'no', 'off']:
return False
for conv in (int, float):
try:
return conv(value)
except:
pass
return value
def _convert_to_boolean(value):
if isinstance(value, bool):
return value
if value.lower() in ['true', 'yes', 'on', '1']:
return True
elif value.lower() in ['false', 'no', 'off', '0']:
return False
raise ValueError('Not a boolean: %s' % value)
@overload
def config_get(
section: str,
option: str,
*,
clean_cached: bool = ...,
check_config_table: bool = ...,
session: "Optional[Session]" = ...,
use_cache: bool = ...,
expiration_time: int = ...,
) -> str:
...
@overload
def config_get(
section: str,
option: str,
*,
default: _T = ...,
clean_cached: bool = ...,
check_config_table: bool = ...,
session: "Optional[Session]" = ...,
use_cache: bool = ...,
expiration_time: int = ...,
) -> Union[str, _T]:
...
@overload
def config_get(
section: str,
option: str,
raise_exception: bool,
default: _T = ...,
*,
clean_cached: bool = ...,
check_config_table: bool = ...,
session: "Optional[Session]" = ...,
use_cache: bool = ...,
expiration_time: int = ...,
) -> Union[str, _T]:
...
@overload
def config_get(
section: str,
option: str,
*,
clean_cached: bool = ...,
check_config_table: bool = ...,
session: "Optional[Session]" = ...,
use_cache: bool = ...,
expiration_time: int = ...,
convert_type_fnc: Callable[[str], _T],
) -> _T:
...
@overload
def config_get(
section: str,
option: str,
*,
default: _T = ...,
clean_cached: bool = ...,
check_config_table: bool = ...,
session: "Optional[Session]" = ...,
use_cache: bool = ...,
expiration_time: int = ...,
convert_type_fnc: Callable[[str], _U],
) -> Union[_T, _U]:
...
@overload
def config_get(
section: str,
option: str,
raise_exception: bool,
default: _T = ...,
*,
clean_cached: bool = ...,
check_config_table: bool = ...,
session: "Optional[Session]" = ...,
use_cache: bool = ...,
expiration_time: int = ...,
convert_type_fnc: Callable[[str], _U],
) -> Union[_T, _U]:
...
def config_get(
section: str,
option: str,
raise_exception: bool = True,
default: _U = None,
clean_cached: bool = False,
check_config_table: bool = True,
session: "Optional[Session]" = None,
use_cache: bool = True,
expiration_time: int = 900,
convert_type_fnc: Callable[[str], _T] = lambda x: x,
) -> Union[_T, _U]:
"""
Return the string value for a given option in a section
First it looks at the configuration file and, if it is not found, check in the config table only if it is called
from a server/daemon (and if check_config_table is set).
:param section: the named section.
:param option: the named option.
:param raise_exception: Boolean to raise or not NoOptionError, NoSectionError or RuntimeError.
:param default: the default value if not found.
:param clean_cached: Deletes the cached config singleton instance if no config value is found
:param check_config_table: if not set, avoid looking at config table even if it is called from server/daemon
:param session: The database session in use. Only used if not found in config file and if it is called from
server/daemon
:param use_cache: Boolean if the cache should be used. Only used if not found in config file and if it is called
from server/daemon
:param expiration_time: Time after that the cached value gets ignored. Only used if not found in config file and if
it is called from server/daemon
:param convert_type_fnc: A function used to parse the string config value into the desired destination type
:returns: the configuration value.
:raises NoOptionError
:raises NoSectionError
:raises RuntimeError
"""
try:
return convert_type_fnc(get_config().get(section, option))
except (configparser.NoOptionError, configparser.NoSectionError, RuntimeError) as err:
try:
legacy_config = get_legacy_config(section, option)
if legacy_config is not None:
return convert_type_fnc(legacy_config)
except RuntimeError:
pass
from rucio.common.utils import is_client
client_mode = is_client()
if not client_mode and check_config_table:
try:
return __config_get_table(section=section, option=option, raise_exception=raise_exception,
default=default, clean_cached=clean_cached, session=session,
use_cache=use_cache, expiration_time=expiration_time,
convert_type_fnc=convert_type_fnc)
except (ConfigNotFound, DatabaseException, ImportError):
raise err
else:
if raise_exception and default is None:
raise err
if clean_cached:
clean_cached_config()
return default
def get_legacy_config(section: str, option: str):
"""
Returns a legacy config value, if it is present.
:param section: The section of the new config.
:param option: The option of the new config.
:returns: The string value of the legacy option if one is found, None otherwise.
"""
LEGACY_SECTION_NAME = {}
LEGACY_OPTION_NAME = {}
section = LEGACY_SECTION_NAME.get(section, section)
option = LEGACY_OPTION_NAME.get(option, option)
if config_has_option(section, option):
return get_config().get(section, option)
return None
def config_has_section(section: str) -> bool:
"""
Indicates whether the named section is present in the configuration. The DEFAULT section is not acknowledged.
:param section: Name of section in the Rucio config to verify.
:returns: True if the section exists in the configuration; False otherwise
"""
return get_config().has_section(section)
def config_has_option(section: str, option: str) -> bool:
"""
Indicates whether the named option is present in the configuration. The DEFAULT section is not acknowledged.
:param section: Name of section in the Rucio config to verify.
:param option: Name of option in the Rucio config to verify.
:returns: True if the section and option exists in the configuration; False otherwise
"""
return get_config().has_option(section, option)
def config_add_section(section: str):
"""
Add a new section to the configuration object. Throws DuplicateSectionError if it already exists.
:param section: Name of section in the Rucio config to add.
:returns: None
"""
return get_config().add_section(section)
@overload
def config_get_int(
section: str,
option: str,
*,
check_config_table: bool = ...,
session: "Optional[Session]" = ...,
use_cache: bool = ...,
expiration_time: int = ...,
) -> int:
...
@overload
def config_get_int(
section: str,
option: str,
*,
default: int = ...,
check_config_table: bool = ...,
session: "Optional[Session]" = ...,
use_cache: bool = ...,
expiration_time: int = ...,
) -> int:
...
@overload
def config_get_int(
section: str,
option: str,
raise_exception,
default: _T = ...,
*,
check_config_table: bool = ...,
session: "Optional[Session]" = ...,
use_cache: bool = ...,
expiration_time: int = ...,
) -> Union[int, _T]:
...
def config_get_int(
section,
option,
raise_exception=True,
default=None,
check_config_table=True,
session=None,
use_cache=True,
expiration_time=900,
):
"""
Return the integer value for a given option in a section
:param section: the named section.
:param option: the named option.
:param raise_exception: Boolean to raise or not NoOptionError, NoSectionError or RuntimeError.
:param default: the default value if not found.
:param check_config_table: if not set, avoid looking at config table even if it is called from server/daemon
:param session: The database session in use. Only used if not found in config file and if it is called from
server/daemon
:param use_cache: Boolean if the cache should be used. Only used if not found in config file and if it is called
from server/daemon
:param expiration_time: Time after that the cached value gets ignored. Only used if not found in config file and if
it is called from server/daemon
:returns: the configuration value.
:raises NoOptionError
:raises NoSectionError
:raises RuntimeError
:raises ValueError
"""
return config_get(
section,
option,
raise_exception=raise_exception,
default=default,
check_config_table=check_config_table,
session=session,
use_cache=use_cache,
expiration_time=expiration_time,
convert_type_fnc=int,
)
@overload
def config_get_float(
section: str,
option: str,
*,
check_config_table: bool = ...,
session: "Optional[Session]" = ...,
use_cache: bool = ...,
expiration_time: int = ...,
) -> float:
...
@overload
def config_get_float(
section: str,
option: str,
*,
default: float = ...,
check_config_table: bool = ...,
session: "Optional[Session]" = ...,
use_cache: bool = ...,
expiration_time: int = ...,
) -> float:
...
@overload
def config_get_float(
section: str,
option: str,
raise_exception,
default: _T = ...,
*,
check_config_table: bool = ...,
session: "Optional[Session]" = ...,
use_cache: bool = ...,
expiration_time: int = ...,
) -> Union[float, _T]:
...
def config_get_float(
section,
option,
raise_exception=True,
default=None,
check_config_table=True,
session=None,
use_cache=True,
expiration_time=900,
):
"""
Return the floating point value for a given option in a section
:param section: the named section.
:param option: the named option.
:param raise_exception: Boolean to raise or not NoOptionError, NoSectionError or RuntimeError.
:param default: the default value if not found.
:param check_config_table: if not set, avoid looking at config table even if it is called from server/daemon
:param session: The database session in use. Only used if not found in config file and if it is called from
server/daemon
:param use_cache: Boolean if the cache should be used. Only used if not found in config file and if it is called
from server/daemon
:param expiration_time: Time after that the cached value gets ignored. Only used if not found in config file and if
it is called from server/daemon
:returns: the configuration value.
:raises NoOptionError
:raises NoSectionError
:raises RuntimeError
:raises ValueError
"""
return config_get(
section,
option,
raise_exception=raise_exception,
default=default,
check_config_table=check_config_table,
session=session,
use_cache=use_cache,
expiration_time=expiration_time,
convert_type_fnc=float,
)
@overload
def config_get_bool(
section: str,
option: str,
*,
check_config_table: bool = ...,
session: "Optional[Session]" = ...,
use_cache: bool = ...,
expiration_time: int = ...,
) -> bool:
...
@overload
def config_get_bool(
section: str,
option: str,
*,
default: bool = ...,
check_config_table: bool = ...,
session: "Optional[Session]" = ...,
use_cache: bool = ...,
expiration_time: int = ...,
) -> bool:
...
@overload
def config_get_bool(
section: str,
option: str,
raise_exception,
default: _T = ...,
*,
check_config_table: bool = ...,
session: "Optional[Session]" = ...,
use_cache: bool = ...,
expiration_time: int = ...,
) -> Union[bool, _T]:
...
def config_get_bool(
section,
option,
raise_exception=True,
default=None,
check_config_table=True,
session=None,
use_cache=True,
expiration_time=900,
):
"""
Return the boolean value for a given option in a section
:param section: the named section.
:param option: the named option.
:param raise_exception: Boolean to raise or not NoOptionError, NoSectionError or RuntimeError.
:param default: the default value if not found.
:param check_config_table: if not set, avoid looking at config table even if it is called from server/daemon
:param session: The database session in use. Only used if not found in config file and if it is called from
server/daemon
:param use_cache: Boolean if the cache should be used. Only used if not found in config file and if it is called
from server/daemon
:param expiration_time: Time after that the cached value gets ignored. Only used if not found in config file and if
it is called from server/daemon
.
:returns: the configuration value.
:raises NoOptionError
:raises NoSectionError
:raises RuntimeError
:raises ValueError
"""
return config_get(
section,
option,
raise_exception=raise_exception,
default=default,
check_config_table=check_config_table,
session=session,
use_cache=use_cache,
expiration_time=expiration_time,
convert_type_fnc=_convert_to_boolean,
)
@overload
def config_get_list(
section: str,
option: str,
*,
check_config_table: bool = ...,
session: "Optional[Session]" = ...,
use_cache: bool = ...,
expiration_time: int = ...,
) -> list[str]:
...
@overload
def config_get_list(
section: str,
option: str,
*,
default: list[str] = ...,
check_config_table: bool = ...,
session: "Optional[Session]" = ...,
use_cache: bool = ...,
expiration_time: int = ...,
) -> list[str]:
...
@overload
def config_get_list(
section: str,
option: str,
raise_exception,
default: _T = ...,
*,
check_config_table: bool = ...,
session: "Optional[Session]" = ...,
use_cache: bool = ...,
expiration_time: int = ...,
) -> Union[list[str], _T]:
...
def config_get_list(
section,
option,
raise_exception=True,
default=None,
check_config_table=True,
session=None,
use_cache=True,
expiration_time=900,
):
"""
Return a list for a given option in a section
:param section: the named section.
:param option: the named option.
:param raise_exception: Boolean to raise or not NoOptionError, NoSectionError or RuntimeError.
:param default: the default value if not found.
:param check_config_table: if not set, avoid looking at config table even if it is called from server/daemon
:param session: The database session in use. Only used if not found in config file and if it is called from
server/daemon
:param use_cache: Boolean if the cache should be used. Only used if not found in config file and if it is called
from server/daemon
:param expiration_time: Time after that the cached value gets ignored. Only used if not found in config file and if
it is called from server/daemon
.
:returns: the configuration value.
:raises NoOptionError
:raises NoSectionError
:raises RuntimeError
:raises ValueError
"""
value = config_get(
section,
option,
raise_exception=raise_exception,
default=default,
check_config_table=check_config_table,
session=session,
use_cache=use_cache,
expiration_time=expiration_time,
)
if isinstance(value, str):
value = __convert_string_to_list(value)
return value
def __convert_string_to_list(string: str) -> list[str]:
"""
Convert a comma separated string to a list
:param string: The input string.
:returns: A list extracted from the string.
"""
if not string or not string.strip():
return []
return [item.strip(' ') for item in string.split(',')]
def __config_get_table(
section: str,
option: str,
*,
raise_exception: bool = True,
default: _T = None,
clean_cached: bool = True,
session: "Optional[Session]" = None,
use_cache: bool = True,
expiration_time: int = 900,
convert_type_fnc: Optional[Callable[[str], _T]],
) -> _T:
"""
Search for a section-option configuration parameter in the configuration table
:param section: the named section.
:param option: the named option.
:param raise_exception: Boolean to raise or not ConfigNotFound.
:param default: the default value if not found.
:param session: The database session in use.
:param use_cache: Boolean if the cache should be used.
:param expiration_time: Time after that the cached value gets ignored.
:returns: the configuration value from the config table.
:raises ConfigNotFound
:raises DatabaseException
"""
global __CONFIG
try:
from rucio.core.config import get as core_config_get
return core_config_get(section, option, default=default, session=session, use_cache=use_cache,
expiration_time=expiration_time, convert_type_fnc=convert_type_fnc)
except (ConfigNotFound, DatabaseException, ImportError) as err:
if raise_exception and default is None:
raise err
if clean_cached:
__CONFIG = None
return default
def config_get_options(section: str) -> list[str]:
"""Return all options from a given section"""
return get_config().options(section)
def config_get_items(section: str) -> list[tuple[str, str]]:
"""Return all (name, value) pairs from a given section"""
return get_config().items(section)
def config_remove_option(section: str, option: str) -> bool:
"""
Remove the specified option from a given section.
:param section: Name of section in the Rucio config.
:param option: Name of option to remove from Rucio configuration.
:returns: True if the option existed in the configuration, False otherwise.
:raises NoSectionError: If the section does not exist.
"""
return get_config().remove_option(section, option)
def config_set(section: str, option: str, value: str):
"""
Set a configuration option in a given section.
:param section: Name of section in the Rucio config.
:param option: Name of option to set in the Rucio configuration.
:param value: New value for the option.
:raises NoSectionError: If the section does not exist.
"""
return get_config().set(section, option, value)
def get_config_dirs():
"""
Returns all available configuration directories in order:
- $RUCIO_HOME/etc/
- $VIRTUAL_ENV/etc/
- /opt/rucio/
"""
configdirs = []
if 'RUCIO_HOME' in os.environ:
configdirs.append('%s/etc/' % os.environ['RUCIO_HOME'])
if 'VIRTUAL_ENV' in os.environ:
configdirs.append('%s/etc/' % os.environ['VIRTUAL_ENV'])
configdirs.append('/opt/rucio/etc/')
return configdirs
def get_lfn2pfn_algorithm_default():
"""Returns the default algorithm name for LFN2PFN translation for this server."""
default_lfn2pfn = "hash"
try:
default_lfn2pfn = config_get('policy', 'lfn2pfn_algorithm_default')
except (configparser.NoOptionError, configparser.NoSectionError, RuntimeError):
pass
return default_lfn2pfn
def get_rse_credentials(path_to_credentials_file: Optional[Union[str, os.PathLike]] = None):
""" Returns credentials for RSEs. """
path = ''
if path_to_credentials_file: # Use specific file for this connect
path = path_to_credentials_file
else: # Use file defined in th RSEMgr
for confdir in get_config_dirs():
p = os.path.join(confdir, 'rse-accounts.cfg')
if os.path.exists(p):
path = p
try:
# Load all user credentials
with open(path) as cred_file:
credentials = json.load(cred_file)
except Exception as error:
raise exception.ErrorLoadingCredentials(error)
return credentials
__CONFIG = None
def get_config() -> configparser.ConfigParser:
"""Factory function for the configuration class. Returns the ConfigParser instance."""
global __CONFIG
if __CONFIG is None:
__CONFIG = Config()
return __CONFIG.parser
def clean_cached_config():
"""Deletes the cached config singleton instance."""
global __CONFIG
__CONFIG = None
class Config:
"""
The configuration class reading the config file on init, located by using
get_config_dirs or the use of the RUCIO_CONFIG environment variable.
"""
def __init__(self):
self.parser = configparser.ConfigParser()
if 'RUCIO_CONFIG' in os.environ:
self.configfile = os.environ['RUCIO_CONFIG']
else:
configs = [os.path.join(confdir, 'rucio.cfg') for confdir in get_config_dirs()]
self.configfile = next(iter(filter(os.path.exists, configs)), None)
if self.configfile is None:
raise RuntimeError('Could not load Rucio configuration file. '
'Rucio looked in the following paths for a configuration file, in order:'
'\n\t' + '\n\t'.join(configs))
if not self.parser.read(self.configfile) == [self.configfile]:
raise RuntimeError('Could not load Rucio configuration file. '
'Rucio tried loading the following configuration file:'
'\n\t' + self.configfile)