/
__init__.py
269 lines (220 loc) · 9.37 KB
/
__init__.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
import sys
import logging.config
import time
import signal
import yaml
from IPy import IP
from typing import Any, List
import os
from dotted.collection import DottedDict
IRRD_CONFIG_PATH_ENV = 'IRRD_CONFIG_PATH'
IRRD_CONFIG_CHECK_FORCE_ENV = 'IRRD_CONFIG_CHECK_FORCE'
logger = logging.getLogger(__name__)
PASSWORD_HASH_DUMMY_VALUE = 'DummyValue'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(asctime)s irrd[%(process)d]: [%(name)s#%(levelname)s] %(message)s'
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'verbose'
},
},
'loggers': {
# Tune down some very loud and not very useful loggers from libraries.
'passlib.registry': {
'level': 'INFO',
'propagate': True,
},
'gnupg': {
'level': 'INFO',
'propagate': True,
},
'sqlalchemy': {
'level': 'WARNING',
'propagate': True,
},
'': {
'handlers': ['console'],
'level': 'INFO',
'propagate': True,
},
}
}
logging.config.dictConfig(LOGGING)
logging.Formatter.converter = time.gmtime
class ConfigurationError(ValueError):
pass
# testing_overrides can be set to a DottedDict, and is used
# to override settings while testing, using the config_override
# fixture.
testing_overrides = None
class Configuration:
"""
The Configuration class stores the current IRRD configuration,
checks the validity of the settings, and offers graceful reloads.
"""
user_config_staging: DottedDict
user_config_live: DottedDict
def __init__(self):
"""
Load the default config and load and check the user provided config.
If a logfile was specified, direct logs there.
"""
default_config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'default_config.yaml')
default_config_yaml = yaml.safe_load(open(default_config_path))
self.default_config = DottedDict(default_config_yaml['irrd'])
errors = self._staging_reload_check()
if errors:
raise ConfigurationError(f'Errors found in configuration, unable to start: {errors}')
self._commit_staging()
log_filename = self.get_setting_live('log.logfile_path')
if log_filename:
LOGGING['handlers']['file'] = {
'class': 'logging.handlers.WatchedFileHandler',
'filename': log_filename,
'formatter': 'verbose',
}
# noinspection PyTypeChecker
LOGGING['loggers']['']['handlers'] = ['file']
logging.config.dictConfig(LOGGING)
def reload(self) -> bool:
"""
Reload the configuration, if it passes the checks.
"""
errors = self._staging_reload_check()
if errors:
logger.error(f'Errors found in configuration, continuing with current settings: {errors}')
return False
self._commit_staging()
return True
def _staging_reload_check(self) -> List[str]:
"""
Reload the staging configuration, and run the config checks on it.
Returns a list of errors if any were found, or an empty list of the
staging config is valid.
"""
if all([
hasattr(sys, '_called_from_test'),
IRRD_CONFIG_PATH_ENV not in os.environ,
IRRD_CONFIG_CHECK_FORCE_ENV not in os.environ
]):
self.user_config_staging = DottedDict({})
return []
try:
user_config_path = os.environ[IRRD_CONFIG_PATH_ENV]
except KeyError:
return [f'Environment variable {IRRD_CONFIG_PATH_ENV} not set.']
try:
user_config_yaml = yaml.safe_load(open(user_config_path))
except OSError as oe:
return [f'Error opening config file {user_config_path}: {oe}']
except yaml.YAMLError as ye:
return [f'Error parsing YAML file: {ye}']
if not isinstance(user_config_yaml, dict) or 'irrd' not in user_config_yaml:
return [f'Could not find root item "irrd" in config file {user_config_path}']
self.user_config_staging = DottedDict(user_config_yaml['irrd'])
errors = self._check_staging_config()
if not errors:
logger.info(f'Configuration successfully (re)loaded from {user_config_path}')
return errors
def _commit_staging(self):
"""
Activate the current staging config as the live config.
"""
self.user_config_live = self.user_config_staging
logging.getLogger('').setLevel(self.get_setting_live('log.level', default='INFO'))
def get_setting_live(self, setting_name: str, default: Any=None) -> Any:
"""
Get a setting from the live config.
In order, this will look in:
- A env variable, uppercase and dots replaced by underscores, e.g.
IRRD_SERVER_WHOIS_INTERFACE
- The testing_overrides DottedDict
- The live user config.
- The default config.
If it is not found in any, the value of the default paramater
is returned, which is None by default.
"""
env_key = 'IRRD_' + setting_name.upper().replace('.', '_')
if env_key in os.environ:
return os.environ[env_key]
if testing_overrides:
try:
return testing_overrides[setting_name]
except KeyError:
pass
try:
return self.user_config_live[setting_name]
except KeyError:
return self.default_config.get(setting_name, default)
def _check_staging_config(self) -> List[str]:
"""
Validate the current staging configuration.
Returns a list of any errors, or an empty list for a valid config.
"""
errors = []
config = self.user_config_staging
if not self._check_is_str(config, 'database_url'):
errors.append(f'Setting database_url is required.')
expected_access_lists = {
config.get('server.whois.access_list'),
config.get('server.http.access_list'),
}
if not self._check_is_str(config, 'email.from') or '@' not in config.get('email.from'):
errors.append(f'Setting email.from is required and must be an email address.')
if not self._check_is_str(config, 'email.smtp'):
errors.append(f'Setting email.smtp is required.')
if not self._check_is_str(config, 'email.footer', required=False):
errors.append(f'Setting email.footer must be a string.')
if not self._check_is_str(config, 'auth.gnupg_keyring'):
errors.append(f'Setting auth.gnupg_keyring is required.')
access_lists = set(config.get('access_lists', {}).keys())
unresolved_access_lists = {x for x in expected_access_lists.difference(access_lists) if x}
if unresolved_access_lists:
errors.append(f'Access lists {", ".join(unresolved_access_lists)} referenced in settings, but not defined.')
for name, access_list in config.get('access_lists', {}).items():
for item in access_list:
try:
IP(item)
except ValueError as ve:
errors.append(f'Invalid item in access list {name}: {ve}.')
known_sources = set(config.get('sources', {}).keys())
unknown_default_sources = set(config.get('sources_default', [])).difference(known_sources)
if unknown_default_sources:
errors.append(f'Setting sources_default contains unknown sources: {", ".join(unknown_default_sources)}')
for name, details in config.get('sources', {}).items():
nrtm_mirror = details.get('nrtm_host') and details.get('nrtm_port') and details.get('import_serial_source')
if details.get('keep_journal') and not (nrtm_mirror or details.get('authoritative')):
errors.append(f'Setting keep_journal for source {name} can not be enabled unless either authoritative '
f'is enabled, or all three of nrtm_host, nrtm_port and import_serial_source.')
if config.get('log.level') and not config.get('log.level') in ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']:
errors.append(f'Invalid log.level: {config.get("log.level")}. '
f'Valid settings for log.level are `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`.')
return errors
def _check_is_str(self, config, key, required=True):
if required:
return config.get(key) and isinstance(config.get(key), str)
return config.get(key) is None or isinstance(config.get(key), str)
configuration = None
def get_setting(setting_name: str, default: Any=None) -> Any:
"""
Convenience wrapper to get the value of a setting.
Creates a Configuration object if none exists, and
retrieves the live setting from that object.
"""
global configuration
if not configuration:
configuration = Configuration()
return configuration.get_setting_live(setting_name, default)
def sighup_handler(signum, frame):
global configuration
if not configuration: # pragma: no cover
configuration = Configuration()
configuration.reload()
signal.signal(signal.SIGHUP, sighup_handler)