config.py 8 KB
Newer Older
Markus Scheidgen's avatar
Markus Scheidgen committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Copyright 2018 Markus Scheidgen
#
# 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.

Markus Scheidgen's avatar
Markus Scheidgen committed
15
import logging
16
17
18
import os
import os.path
import yaml
Markus Scheidgen's avatar
Markus Scheidgen committed
19
20
import warnings

Markus Scheidgen's avatar
Markus Scheidgen committed
21
22
23
from nomad import gitinfo


Markus Scheidgen's avatar
Markus Scheidgen committed
24
25
26
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")

27

28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class NomadConfig(dict):
    """
    A dict subclass that uses attributes as key/value pairs.
    """
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def __getattr__(self, name):
        if name in self:
            return self[name]
        else:
            raise AttributeError("No such attribute: " + name)

    def __setattr__(self, name, value):
        self[name] = value
43

44
45
46
47
48
    def __delattr__(self, name):
        if name in self:
            del self[name]
        else:
            raise AttributeError("No such attribute: " + name)
49
50


51
52
CELERY_WORKER_ROUTING = 'worker'
CELERY_QUEUE_ROUTING = 'queue'
53

54
55
56
57
58
rabbitmq = NomadConfig(
    host='localhost',
    user='rabbitmq',
    password='rabbitmq'
)
59

60

61
62
def rabbitmq_url():
    return 'pyamqp://%s:%s@%s//' % (rabbitmq.user, rabbitmq.password, rabbitmq.host)
63

64

65
66
67
68
celery = NomadConfig(
    max_memory=64e6,  # 64 GB
    timeout=1800,  # 1/2 h
    acks_late=True,
69
    routing=CELERY_QUEUE_ROUTING,
70
71
72
73
74
    priorities={
        'Upload.process_upload': 5,
        'Upload.delete_upload': 9,
        'Upload.publish_upload': 10
    }
75
)
76

77
78
79
80
fs = NomadConfig(
    tmp='.volumes/fs/tmp',
    staging='.volumes/fs/staging',
    public='.volumes/fs/public',
81
    coe_extracted='.volumes/fs/extracted',
82
    migration_packages='.volumes/fs/migration_packages',
83
    local_tmp='/tmp',
84
85
    prefix_size=2,
    working_directory=os.getcwd()
86
)
87

88
89
90
91
92
elastic = NomadConfig(
    host='localhost',
    port=9200,
    index_name='nomad_fairdi_calcs'
)
93

94
repository_db = NomadConfig(
95
96
    sequential_publish=False,
    publish_enabled=True,
97
98
99
100
    host='localhost',
    port=5432,
    dbname='nomad_fairdi_repo_db',
    user='postgres',
101
    password='nomad',
102
103
    handle_prefix='21.11132/',
    mode='fairdi'
104
)
Markus Scheidgen's avatar
Markus Scheidgen committed
105

106
107
108
109
110
mongo = NomadConfig(
    host='localhost',
    port=27017,
    db_name='nomad_fairdi'
)
111

112
113
114
115
116
117
logstash = NomadConfig(
    enabled=True,
    host='localhost',
    tcp_port='5000',
    level=logging.DEBUG
)
Markus Scheidgen's avatar
Markus Scheidgen committed
118

119
120
121
services = NomadConfig(
    api_host='localhost',
    api_port=8000,
122
    api_base_path='/fairdi/nomad/latest/api',
123
    api_secret='defaultApiSecret',
124
    api_chaos=0,
125
    admin_password='password',
126
    disable_reset=True,
127
    not_processed_value='not processed',
128
    unavailable_value='unavailable',
129
    https=False,
130
    upload_limit=10
131
132
)

Markus Scheidgen's avatar
Markus Scheidgen committed
133
134
135
136
tests = NomadConfig(
    default_timeout=30
)

137

Markus Scheidgen's avatar
Markus Scheidgen committed
138
def api_url():
Markus Scheidgen's avatar
Markus Scheidgen committed
139
    return '%s://%s%s%s' % (
Markus Scheidgen's avatar
Markus Scheidgen committed
140
141
        'https' if services.https else 'http',
        services.api_host,
Markus Scheidgen's avatar
Markus Scheidgen committed
142
        ':%s' % services.api_port if int(services.api_port) != 80 else '',
Markus Scheidgen's avatar
Markus Scheidgen committed
143
        services.api_base_path)
144
145
146
147
148
149
150
151
152
153
154
155
156
157


migration_source_db = NomadConfig(
    host='db-repository.nomad.esc',
    port=5432,
    dbname='nomad_prod',
    user='nomadlab',
    password='*'
)

mail = NomadConfig(
    enabled=False,
    with_login=False,
    host='',
Markus Scheidgen's avatar
Markus Scheidgen committed
158
    port=8995,
159
160
161
162
163
164
    user='',
    password='',
    from_address='webmaster@nomad-coe.eu'
)

normalize = NomadConfig(
165
    all_systems=False,
166
    system_classification_with_clusters_threshold=50
167
168
169
170
171
)

client = NomadConfig(
    user='leonard.hofstadter@nomad-fairdi.tests.de',
    password='password',
172
    url='http://localhost:8000/fairdi/nomad/latest/api'
173
174
)

Markus Scheidgen's avatar
Markus Scheidgen committed
175
version = '0.5.1'
176
commit = gitinfo.commit
177
release = 'devel'
178
179
domain = 'DFT'
service = 'unknown nomad service'
180
auxfile_cutoff = 100
181
console_log_level = logging.WARNING
182

183

184
185
def normalize_loglevel(value, default_level=logging.INFO):
    plain_value = value
186
187
188
189
190
191
    if plain_value is None:
        return default_level
    else:
        try:
            return int(plain_value)
        except ValueError:
192
            return getattr(logging, plain_value)
193
194


195
transformations = {
196
197
    'console_log_level': normalize_loglevel,
    'logstash_level': normalize_loglevel
198
}
Markus Scheidgen's avatar
Markus Scheidgen committed
199

Markus Scheidgen's avatar
Markus Scheidgen committed
200

201
202
203
204
# use std python logger, since logging is not configured while loading configuration
logger = logging.getLogger(__name__)


205
def apply(key, value) -> None:
206
207
208
209
210
211
212
213
    """
    Changes the config according to given key and value. The keys are interpreted as paths
    to config values with ``_`` as a separator. E.g. ``fs_staging`` leading to
    ``config.fs.staging``
    """
    path = list(reversed(key.split('_')))
    child_segment = None
    current_value = None
214
    child_config = globals()
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
    child_key = None

    try:
        while len(path) > 0:
            if child_segment is None:
                child_segment = path.pop()
            else:
                child_segment += '_' + path.pop()

            if child_segment in child_config:
                current_value = child_config[child_segment]

            if current_value is None:
                if len(path) == 0:
                    raise KeyError
230
231

                continue
232
233
            if isinstance(current_value, NomadConfig):
                child_config = current_value
234
                current_value = None
235
236
237
238
                child_segment = None
            else:
                if len(path) > 0:
                    raise KeyError()
Markus Scheidgen's avatar
Markus Scheidgen committed
239
240
241

                child_key = child_segment
                break
242
243
244
245

        if child_key is None or current_value is None:
            raise KeyError()
    except KeyError:
Markus Scheidgen's avatar
Markus Scheidgen committed
246
        return
247
248
249
250
251
252
253
254
255
256
257

    if not isinstance(value, type(current_value)):
        try:
            value = transformations.get(key, type(current_value))(value)
        except Exception as e:
            logger.error(
                'config key %s value %s has wrong type: %s' % (key, str(value), str(e)))

    child_config[child_key] = value


Markus Scheidgen's avatar
Markus Scheidgen committed
258
259
def load_config(config_file: str = os.environ.get('NOMAD_CONFIG', 'nomad.yaml')) -> None:
    # load yaml and override defaults
260
261
262
    if os.path.exists(config_file):
        with open(config_file, 'r') as stream:
            try:
263
                config_data = yaml.load(stream, Loader=getattr(yaml, 'FullLoader'))
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
            except yaml.YAMLError as e:
                logger.error('cannot read nomad config', exc_info=e)

        def adapt(config, new_config, child_key=None):
            for key, value in new_config.items():
                if key in config:
                    if child_key is None:
                        qualified_key = key
                    else:
                        qualified_key = '%s_%s' % (child_key, key)

                    current_value = config[key]
                    if isinstance(value, dict) and isinstance(current_value, NomadConfig):
                        adapt(current_value, value, qualified_key)
                    else:
                        if not isinstance(value, type(current_value)):
                            try:
                                value = transformations.get(qualified_key, type(current_value))(value)
                            except Exception as e:
                                logger.error(
                                    'config key %s value %s has wrong type: %s' % (key, str(value), str(e)))
                        else:
                            config[key] = value
287
                            logger.info('override config key %s with value %s' % (key, str(value)))
288
289
290
291
292
                else:
                    logger.error('config key %s does not exist' % key)

        adapt(globals(), config_data)

Markus Scheidgen's avatar
Markus Scheidgen committed
293
    # load env and override yaml and defaults
294
295
296
297
298
    kwargs = {
        key[len('NOMAD_'):].lower(): value
        for key, value in os.environ.items()
        if key.startswith('NOMAD_')
    }
299

300
    for key, value in kwargs.items():
301
        apply(key, value)
302
303
304


load_config()