]> git.openstreetmap.org Git - nominatim.git/blob - nominatim/config.py
replace NOMINATIM_PHRASE_CONFIG with command line option
[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         # Add defaults for variables that are left empty to set the default.
60         # They may still be overwritten by environment variables.
61         if not self._config['NOMINATIM_ADDRESS_LEVEL_CONFIG']:
62             self._config['NOMINATIM_ADDRESS_LEVEL_CONFIG'] = \
63                 str(config_dir / 'address-levels.json')
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_libpq_dsn(self):
103         """ Get configured database DSN converted into the key/value format
104             understood by libpq and psycopg.
105         """
106         dsn = self.DATABASE_DSN
107
108         def quote_param(param):
109             key, val = param.split('=')
110             val = val.replace('\\', '\\\\').replace("'", "\\'")
111             if ' ' in val:
112                 val = "'" + val + "'"
113             return key + '=' + val
114
115         if dsn.startswith('pgsql:'):
116             # Old PHP DSN format. Convert before returning.
117             return ' '.join([quote_param(p) for p in dsn[6:].split(';')])
118
119         return dsn
120
121
122     def get_import_style_file(self):
123         """ Return the import style file as a path object. Translates the
124             name of the standard styles automatically into a file in the
125             config style.
126         """
127         style = self.__getattr__('IMPORT_STYLE')
128
129         if style in ('admin', 'street', 'address', 'full', 'extratags'):
130             return self.config_dir / 'import-{}.style'.format(style)
131
132         return Path(style)
133
134
135     def get_os_env(self):
136         """ Return a copy of the OS environment with the Nominatim configuration
137             merged in.
138         """
139         env = dict(self._config)
140         env.update(self.environ)
141
142         return env
143
144
145     def load_sub_configuration(self, filename, config=None):
146         """ Load additional configuration from a file. `filename` is the name
147             of the configuration file. The file is first searched in the
148             project directory and then in the global settings dirctory.
149
150             If `config` is set, then the name of the configuration file can
151             be additionally given through a .env configuration option. When
152             the option is set, then the file will be exclusively loaded as set:
153             if the name is an absolute path, the file name is taken as is,
154             if the name is relative, it is taken to be relative to the
155             project directory.
156
157             The format of the file is determined from the filename suffix.
158             Currently only files with extension '.yaml' are supported.
159
160             YAML files support a special '!include' construct. When the
161             directive is given, the value is taken to be a filename, the file
162             is loaded using this function and added at the position in the
163             configuration tree.
164         """
165         configfile = self.find_config_file(filename, config)
166
167         if configfile.suffix in ('.yaml', '.yml'):
168             return self._load_from_yaml(configfile)
169
170         if configfile.suffix == '.json':
171             with configfile.open('r') as cfg:
172                 return json.load(cfg)
173
174         raise UsageError(f"Config file '{configfile}' has unknown format.")
175
176
177     def find_config_file(self, filename, config=None):
178         """ Resolve the location of a configuration file given a filename and
179             an optional configuration option with the file name.
180             Raises a UsageError when the file cannot be found or is not
181             a regular file.
182         """
183         if config is not None:
184             cfg_filename = self.__getattr__(config)
185             if cfg_filename:
186                 cfg_filename = Path(cfg_filename)
187
188                 if cfg_filename.is_absolute():
189                     cfg_filename = cfg_filename.resolve()
190
191                     if not cfg_filename.is_file():
192                         LOG.fatal("Cannot find config file '%s'.", cfg_filename)
193                         raise UsageError("Config file not found.")
194
195                     return cfg_filename
196
197                 filename = cfg_filename
198
199
200         search_paths = [self.project_dir, self.config_dir]
201         for path in search_paths:
202             if path is not None and (path / filename).is_file():
203                 return path / filename
204
205         LOG.fatal("Configuration file '%s' not found.\nDirectories searched: %s",
206                   filename, search_paths)
207         raise UsageError("Config file not found.")
208
209
210     def _load_from_yaml(self, cfgfile):
211         """ Load a YAML configuration file. This installs a special handler that
212             allows to include other YAML files using the '!include' operator.
213         """
214         yaml.add_constructor('!include', self._yaml_include_representer,
215                              Loader=yaml.SafeLoader)
216         return yaml.safe_load(cfgfile.read_text(encoding='utf-8'))
217
218
219     def _yaml_include_representer(self, loader, node):
220         """ Handler for the '!include' operator in YAML files.
221
222             When the filename is relative, then the file is first searched in the
223             project directory and then in the global settings dirctory.
224         """
225         fname = loader.construct_scalar(node)
226
227         if Path(fname).is_absolute():
228             configfile = Path(fname)
229         else:
230             configfile = self.find_config_file(loader.construct_scalar(node))
231
232         if configfile.suffix != '.yaml':
233             LOG.fatal("Format error while reading '%s': only YAML format supported.",
234                       configfile)
235             raise UsageError("Cannot handle config file format.")
236
237         return yaml.safe_load(configfile.read_text(encoding='utf-8'))