]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/config.py
mypy: ignore dotenv library
[nominatim.git] / nominatim / config.py
1 # SPDX-License-Identifier: GPL-2.0-only
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Nominatim configuration accessor.
9 """
10 from typing import Dict, Any
11 import logging
12 import os
13 from pathlib import Path
14 import json
15 import yaml
16
17 from dotenv import dotenv_values
18
19 from nominatim.errors import UsageError
20
21 LOG = logging.getLogger()
22 CONFIG_CACHE : Dict[str, Any] = {}
23
24 def flatten_config_list(content, section=''):
25     """ Flatten YAML configuration lists that contain include sections
26         which are lists themselves.
27     """
28     if not content:
29         return []
30
31     if not isinstance(content, list):
32         raise UsageError(f"List expected in section '{section}'.")
33
34     output = []
35     for ele in content:
36         if isinstance(ele, list):
37             output.extend(flatten_config_list(ele, section))
38         else:
39             output.append(ele)
40
41     return output
42
43
44 class Configuration:
45     """ Load and manage the project configuration.
46
47         Nominatim uses dotenv to configure the software. Configuration options
48         are resolved in the following order:
49
50          * from the OS environment (or the dirctionary given in `environ`
51          * from the .env file in the project directory of the installation
52          * from the default installation in the configuration directory
53
54         All Nominatim configuration options are prefixed with 'NOMINATIM_' to
55         avoid conflicts with other environment variables.
56     """
57
58     def __init__(self, project_dir, config_dir, environ=None):
59         self.environ = environ or os.environ
60         self.project_dir = project_dir
61         self.config_dir = config_dir
62         self._config = dotenv_values(str((config_dir / 'env.defaults').resolve()))
63         if project_dir is not None and (project_dir / '.env').is_file():
64             self._config.update(dotenv_values(str((project_dir / '.env').resolve())))
65
66         class _LibDirs:
67             pass
68
69         self.lib_dir = _LibDirs()
70
71     def set_libdirs(self, **kwargs):
72         """ Set paths to library functions and data.
73         """
74         for key, value in kwargs.items():
75             setattr(self.lib_dir, key, Path(value).resolve())
76
77     def __getattr__(self, name):
78         name = 'NOMINATIM_' + name
79
80         if name in self.environ:
81             return self.environ[name]
82
83         return self._config[name]
84
85     def get_bool(self, name):
86         """ Return the given configuration parameter as a boolean.
87             Values of '1', 'yes' and 'true' are accepted as truthy values,
88             everything else is interpreted as false.
89         """
90         return getattr(self, name).lower() in ('1', 'yes', 'true')
91
92
93     def get_int(self, name):
94         """ Return the given configuration parameter as an int.
95         """
96         try:
97             return int(getattr(self, name))
98         except ValueError as exp:
99             LOG.fatal("Invalid setting NOMINATIM_%s. Needs to be a number.", name)
100             raise UsageError("Configuration error.") from exp
101
102
103     def get_str_list(self, name):
104         """ Return the given configuration parameter as a list of strings.
105             The values are assumed to be given as a comma-sparated list and
106             will be stripped before returning them. On empty values None
107             is returned.
108         """
109         raw = getattr(self, name)
110
111         return [v.strip() for v in raw.split(',')] if raw else None
112
113
114     def get_path(self, name):
115         """ Return the given configuration parameter as a Path.
116             If a relative path is configured, then the function converts this
117             into an absolute path with the project directory as root path.
118             If the configuration is unset, a falsy value is returned.
119         """
120         value = getattr(self, name)
121         if value:
122             value = Path(value)
123
124             if not value.is_absolute():
125                 value = self.project_dir / value
126
127             value = value.resolve()
128
129         return value
130
131     def get_libpq_dsn(self):
132         """ Get configured database DSN converted into the key/value format
133             understood by libpq and psycopg.
134         """
135         dsn = self.DATABASE_DSN
136
137         def quote_param(param):
138             key, val = param.split('=')
139             val = val.replace('\\', '\\\\').replace("'", "\\'")
140             if ' ' in val:
141                 val = "'" + val + "'"
142             return key + '=' + val
143
144         if dsn.startswith('pgsql:'):
145             # Old PHP DSN format. Convert before returning.
146             return ' '.join([quote_param(p) for p in dsn[6:].split(';')])
147
148         return dsn
149
150
151     def get_import_style_file(self):
152         """ Return the import style file as a path object. Translates the
153             name of the standard styles automatically into a file in the
154             config style.
155         """
156         style = getattr(self, 'IMPORT_STYLE')
157
158         if style in ('admin', 'street', 'address', 'full', 'extratags'):
159             return self.config_dir / f'import-{style}.style'
160
161         return self.find_config_file('', 'IMPORT_STYLE')
162
163
164     def get_os_env(self):
165         """ Return a copy of the OS environment with the Nominatim configuration
166             merged in.
167         """
168         env = dict(self._config)
169         env.update(self.environ)
170
171         return env
172
173
174     def load_sub_configuration(self, filename, config=None):
175         """ Load additional configuration from a file. `filename` is the name
176             of the configuration file. The file is first searched in the
177             project directory and then in the global settings dirctory.
178
179             If `config` is set, then the name of the configuration file can
180             be additionally given through a .env configuration option. When
181             the option is set, then the file will be exclusively loaded as set:
182             if the name is an absolute path, the file name is taken as is,
183             if the name is relative, it is taken to be relative to the
184             project directory.
185
186             The format of the file is determined from the filename suffix.
187             Currently only files with extension '.yaml' are supported.
188
189             YAML files support a special '!include' construct. When the
190             directive is given, the value is taken to be a filename, the file
191             is loaded using this function and added at the position in the
192             configuration tree.
193         """
194         configfile = self.find_config_file(filename, config)
195
196         if str(configfile) in CONFIG_CACHE:
197             return CONFIG_CACHE[str(configfile)]
198
199         if configfile.suffix in ('.yaml', '.yml'):
200             result = self._load_from_yaml(configfile)
201         elif configfile.suffix == '.json':
202             with configfile.open('r', encoding='utf-8') as cfg:
203                 result = json.load(cfg)
204         else:
205             raise UsageError(f"Config file '{configfile}' has unknown format.")
206
207         CONFIG_CACHE[str(configfile)] = result
208         return result
209
210
211     def find_config_file(self, filename, config=None):
212         """ Resolve the location of a configuration file given a filename and
213             an optional configuration option with the file name.
214             Raises a UsageError when the file cannot be found or is not
215             a regular file.
216         """
217         if config is not None:
218             cfg_filename = getattr(self, config)
219             if cfg_filename:
220                 cfg_filename = Path(cfg_filename)
221
222                 if cfg_filename.is_absolute():
223                     cfg_filename = cfg_filename.resolve()
224
225                     if not cfg_filename.is_file():
226                         LOG.fatal("Cannot find config file '%s'.", cfg_filename)
227                         raise UsageError("Config file not found.")
228
229                     return cfg_filename
230
231                 filename = cfg_filename
232
233
234         search_paths = [self.project_dir, self.config_dir]
235         for path in search_paths:
236             if path is not None and (path / filename).is_file():
237                 return path / filename
238
239         LOG.fatal("Configuration file '%s' not found.\nDirectories searched: %s",
240                   filename, search_paths)
241         raise UsageError("Config file not found.")
242
243
244     def _load_from_yaml(self, cfgfile):
245         """ Load a YAML configuration file. This installs a special handler that
246             allows to include other YAML files using the '!include' operator.
247         """
248         yaml.add_constructor('!include', self._yaml_include_representer,
249                              Loader=yaml.SafeLoader)
250         return yaml.safe_load(cfgfile.read_text(encoding='utf-8'))
251
252
253     def _yaml_include_representer(self, loader, node):
254         """ Handler for the '!include' operator in YAML files.
255
256             When the filename is relative, then the file is first searched in the
257             project directory and then in the global settings dirctory.
258         """
259         fname = loader.construct_scalar(node)
260
261         if Path(fname).is_absolute():
262             configfile = Path(fname)
263         else:
264             configfile = self.find_config_file(loader.construct_scalar(node))
265
266         if configfile.suffix != '.yaml':
267             LOG.fatal("Format error while reading '%s': only YAML format supported.",
268                       configfile)
269             raise UsageError("Cannot handle config file format.")
270
271         return yaml.safe_load(configfile.read_text(encoding='utf-8'))