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