config.py 7.45 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
import warnings
20
from kombu import Queue
Markus Scheidgen's avatar
Markus Scheidgen committed
21

22
23
from nomad import utils

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
class NomadConfig(utils.POPO):
    pass


# class ConfigProperty:
#     def __init__(
#             self, name: str, default_value: Union[int, str, bool], help: str = None,
#             env_var: str = None) -> None:
#         self.name = name
#         self.default_value = default_value,
#         self.help = help
#         self.env_var = env_var

41
42
CELERY_WORKER_ROUTING = 'worker'
CELERY_QUEUE_ROUTING = 'queue'
43

44
45
46
47
48
rabbitmq = NomadConfig(
    host='localhost',
    user='rabbitmq',
    password='rabbitmq'
)
49

50

51
52
def rabbitmq_url():
    return 'pyamqp://%s:%s@%s//' % (rabbitmq.user, rabbitmq.password, rabbitmq.host)
53

54

55
56
57
58
celery = NomadConfig(
    max_memory=64e6,  # 64 GB
    timeout=1800,  # 1/2 h
    acks_late=True,
59
60
61
62
63
    routing=CELERY_QUEUE_ROUTING,
    task_queues=[
        Queue('calcs', routing_key='calcs', queue_arguments={'x-max-priority': 10}),
        Queue('uploads', routing_key='uploads', queue_arguments={'x-max-priority': 100})
    ]
64
)
65

66
67
68
69
fs = NomadConfig(
    tmp='.volumes/fs/tmp',
    staging='.volumes/fs/staging',
    public='.volumes/fs/public',
70
    migration_packages='.volumes/fs/migration_packages',
71
    local_tmp='/tmp',
72
73
    prefix_size=2,
    working_directory=os.getcwd()
74
)
75

76
77
78
79
80
elastic = NomadConfig(
    host='localhost',
    port=9200,
    index_name='nomad_fairdi_calcs'
)
81

82
repository_db = NomadConfig(
83
84
    sequential_publish=False,
    publish_enabled=True,
85
86
87
88
89
90
    host='localhost',
    port=5432,
    dbname='nomad_fairdi_repo_db',
    user='postgres',
    password='nomad'
)
Markus Scheidgen's avatar
Markus Scheidgen committed
91

92
93
94
95
96
mongo = NomadConfig(
    host='localhost',
    port=27017,
    db_name='nomad_fairdi'
)
97

98
99
100
101
102
103
logstash = NomadConfig(
    enabled=True,
    host='localhost',
    tcp_port='5000',
    level=logging.DEBUG
)
Markus Scheidgen's avatar
Markus Scheidgen committed
104

105
106
107
108
109
110
services = NomadConfig(
    api_host='localhost',
    api_port=8000,
    api_base_path='/nomad/api',
    api_secret='defaultApiSecret',
    admin_password='password',
111
    disable_reset=True,
112
113
    not_processed_value='not processed',
    unavailable_value='unavailable'
114
115
)

Markus Scheidgen's avatar
Markus Scheidgen committed
116
117
118
119
tests = NomadConfig(
    default_timeout=30
)

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

def upload_url():
    return 'http://%s:%s/%s/uploads' % (services.api_host, services.api_port, services.api_base_path[:-3])


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='',
    port=8995,
    user='',
    password='',
    from_address='webmaster@nomad-coe.eu'
)

normalize = NomadConfig(
    all_systems=False
)

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

153
version = '4.3'  # TODO replace with git hash?
154
release = 'devel'
155
156
domain = 'DFT'
service = 'unknown nomad service'
157
auxfile_cutoff = 30
158
console_log_level = logging.WARNING
159

160
161
162
163
164
165
166
167
168

def get_loglevel_from_env(key, default_level=logging.INFO):
    plain_value = os.environ.get(key, None)
    if plain_value is None:
        return default_level
    else:
        try:
            return int(plain_value)
        except ValueError:
169
            return getattr(logging, plain_value)
170
171


172
173
174
175
transformations = {
    'console_log_level': get_loglevel_from_env,
    'logstash_level': get_loglevel_from_env
}
Markus Scheidgen's avatar
Markus Scheidgen committed
176

Markus Scheidgen's avatar
Markus Scheidgen committed
177

178
179
180
181
# use std python logger, since logging is not configured while loading configuration
logger = logging.getLogger(__name__)


182
def apply(key, value) -> None:
183
184
185
186
187
188
189
190
    """
    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
191
    child_config = globals()
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
    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
207
208

                continue
209
210
            if isinstance(current_value, NomadConfig):
                child_config = current_value
211
                current_value = None
212
213
214
215
                child_segment = None
            else:
                if len(path) > 0:
                    raise KeyError()
Markus Scheidgen's avatar
Markus Scheidgen committed
216
217
218

                child_key = child_segment
                break
219
220
221
222

        if child_key is None or current_value is None:
            raise KeyError()
    except KeyError:
Markus Scheidgen's avatar
Markus Scheidgen committed
223
        return
224
225
226
227
228
229
230
231
232
233
234

    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
235
236
def load_config(config_file: str = os.environ.get('NOMAD_CONFIG', 'nomad.yaml')) -> None:
    # load yaml and override defaults
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
    if os.path.exists(config_file):
        with open(config_file, 'r') as stream:
            try:
                config_data = yaml.load(stream)
            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
                else:
                    logger.error('config key %s does not exist' % key)

        adapt(globals(), config_data)

Markus Scheidgen's avatar
Markus Scheidgen committed
269
    # load env and override yaml and defaults
270
271
272
273
274
    kwargs = {
        key[len('NOMAD_'):].lower(): value
        for key, value in os.environ.items()
        if key.startswith('NOMAD_')
    }
275

276
    for key, value in kwargs.items():
277
        apply(key, value)
278
279
280


load_config()