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