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