1 # SPDX-License-Identifier: GPL-2.0-only
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Nominatim configuration accessor.
10 from typing import Dict, Any
13 from pathlib import Path
17 from dotenv import dotenv_values
19 from nominatim.errors import UsageError
21 LOG = logging.getLogger()
22 CONFIG_CACHE : Dict[str, Any] = {}
24 def flatten_config_list(content, section=''):
25 """ Flatten YAML configuration lists that contain include sections
26 which are lists themselves.
31 if not isinstance(content, list):
32 raise UsageError(f"List expected in section '{section}'.")
36 if isinstance(ele, list):
37 output.extend(flatten_config_list(ele, section))
45 """ Load and manage the project configuration.
47 Nominatim uses dotenv to configure the software. Configuration options
48 are resolved in the following order:
50 * from the OS environment (or the dirctionary given in `environ`
51 * from the .env file in the project directory of the installation
52 * from the default installation in the configuration directory
54 All Nominatim configuration options are prefixed with 'NOMINATIM_' to
55 avoid conflicts with other environment variables.
58 def __init__(self, project_dir, config_dir, environ=None):
59 self.environ = environ or os.environ
60 self.project_dir = project_dir
61 self.config_dir = config_dir
62 self._config = dotenv_values(str((config_dir / 'env.defaults').resolve()))
63 if project_dir is not None and (project_dir / '.env').is_file():
64 self._config.update(dotenv_values(str((project_dir / '.env').resolve())))
69 self.lib_dir = _LibDirs()
71 def set_libdirs(self, **kwargs):
72 """ Set paths to library functions and data.
74 for key, value in kwargs.items():
75 setattr(self.lib_dir, key, Path(value).resolve())
77 def __getattr__(self, name):
78 name = 'NOMINATIM_' + name
80 if name in self.environ:
81 return self.environ[name]
83 return self._config[name]
85 def get_bool(self, name):
86 """ Return the given configuration parameter as a boolean.
87 Values of '1', 'yes' and 'true' are accepted as truthy values,
88 everything else is interpreted as false.
90 return getattr(self, name).lower() in ('1', 'yes', 'true')
93 def get_int(self, name):
94 """ Return the given configuration parameter as an int.
97 return int(getattr(self, name))
98 except ValueError as exp:
99 LOG.fatal("Invalid setting NOMINATIM_%s. Needs to be a number.", name)
100 raise UsageError("Configuration error.") from exp
103 def get_str_list(self, name):
104 """ Return the given configuration parameter as a list of strings.
105 The values are assumed to be given as a comma-sparated list and
106 will be stripped before returning them. On empty values None
109 raw = getattr(self, name)
111 return [v.strip() for v in raw.split(',')] if raw else None
114 def get_path(self, name):
115 """ Return the given configuration parameter as a Path.
116 If a relative path is configured, then the function converts this
117 into an absolute path with the project directory as root path.
118 If the configuration is unset, a falsy value is returned.
120 value = getattr(self, name)
124 if not value.is_absolute():
125 value = self.project_dir / value
127 value = value.resolve()
131 def get_libpq_dsn(self):
132 """ Get configured database DSN converted into the key/value format
133 understood by libpq and psycopg.
135 dsn = self.DATABASE_DSN
137 def quote_param(param):
138 key, val = param.split('=')
139 val = val.replace('\\', '\\\\').replace("'", "\\'")
141 val = "'" + val + "'"
142 return key + '=' + val
144 if dsn.startswith('pgsql:'):
145 # Old PHP DSN format. Convert before returning.
146 return ' '.join([quote_param(p) for p in dsn[6:].split(';')])
151 def get_import_style_file(self):
152 """ Return the import style file as a path object. Translates the
153 name of the standard styles automatically into a file in the
156 style = getattr(self, 'IMPORT_STYLE')
158 if style in ('admin', 'street', 'address', 'full', 'extratags'):
159 return self.config_dir / f'import-{style}.style'
161 return self.find_config_file('', 'IMPORT_STYLE')
164 def get_os_env(self):
165 """ Return a copy of the OS environment with the Nominatim configuration
168 env = dict(self._config)
169 env.update(self.environ)
174 def load_sub_configuration(self, filename, config=None):
175 """ Load additional configuration from a file. `filename` is the name
176 of the configuration file. The file is first searched in the
177 project directory and then in the global settings dirctory.
179 If `config` is set, then the name of the configuration file can
180 be additionally given through a .env configuration option. When
181 the option is set, then the file will be exclusively loaded as set:
182 if the name is an absolute path, the file name is taken as is,
183 if the name is relative, it is taken to be relative to the
186 The format of the file is determined from the filename suffix.
187 Currently only files with extension '.yaml' are supported.
189 YAML files support a special '!include' construct. When the
190 directive is given, the value is taken to be a filename, the file
191 is loaded using this function and added at the position in the
194 configfile = self.find_config_file(filename, config)
196 if str(configfile) in CONFIG_CACHE:
197 return CONFIG_CACHE[str(configfile)]
199 if configfile.suffix in ('.yaml', '.yml'):
200 result = self._load_from_yaml(configfile)
201 elif configfile.suffix == '.json':
202 with configfile.open('r', encoding='utf-8') as cfg:
203 result = json.load(cfg)
205 raise UsageError(f"Config file '{configfile}' has unknown format.")
207 CONFIG_CACHE[str(configfile)] = result
211 def find_config_file(self, filename, config=None):
212 """ Resolve the location of a configuration file given a filename and
213 an optional configuration option with the file name.
214 Raises a UsageError when the file cannot be found or is not
217 if config is not None:
218 cfg_filename = getattr(self, config)
220 cfg_filename = Path(cfg_filename)
222 if cfg_filename.is_absolute():
223 cfg_filename = cfg_filename.resolve()
225 if not cfg_filename.is_file():
226 LOG.fatal("Cannot find config file '%s'.", cfg_filename)
227 raise UsageError("Config file not found.")
231 filename = cfg_filename
234 search_paths = [self.project_dir, self.config_dir]
235 for path in search_paths:
236 if path is not None and (path / filename).is_file():
237 return path / filename
239 LOG.fatal("Configuration file '%s' not found.\nDirectories searched: %s",
240 filename, search_paths)
241 raise UsageError("Config file not found.")
244 def _load_from_yaml(self, cfgfile):
245 """ Load a YAML configuration file. This installs a special handler that
246 allows to include other YAML files using the '!include' operator.
248 yaml.add_constructor('!include', self._yaml_include_representer,
249 Loader=yaml.SafeLoader)
250 return yaml.safe_load(cfgfile.read_text(encoding='utf-8'))
253 def _yaml_include_representer(self, loader, node):
254 """ Handler for the '!include' operator in YAML files.
256 When the filename is relative, then the file is first searched in the
257 project directory and then in the global settings dirctory.
259 fname = loader.construct_scalar(node)
261 if Path(fname).is_absolute():
262 configfile = Path(fname)
264 configfile = self.find_config_file(loader.construct_scalar(node))
266 if configfile.suffix != '.yaml':
267 LOG.fatal("Format error while reading '%s': only YAML format supported.",
269 raise UsageError("Cannot handle config file format.")
271 return yaml.safe_load(configfile.read_text(encoding='utf-8'))