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