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, List, Mapping, Optional, Union
13 from pathlib import Path
17 from dotenv import dotenv_values
19 from nominatim.errors import UsageError
21 PathOrStr = Union[str, os.PathLike[str]]
23 LOG = logging.getLogger()
24 CONFIG_CACHE : Dict[str, Any] = {}
26 def flatten_config_list(content: Any, section: str = '') -> List[Any]:
27 """ Flatten YAML configuration lists that contain include sections
28 which are lists themselves.
33 if not isinstance(content, list):
34 raise UsageError(f"List expected in section '{section}'.")
38 if isinstance(ele, list):
39 output.extend(flatten_config_list(ele, section))
47 """ Load and manage the project configuration.
49 Nominatim uses dotenv to configure the software. Configuration options
50 are resolved in the following order:
52 * from the OS environment (or the dirctionary given in `environ`
53 * from the .env file in the project directory of the installation
54 * from the default installation in the configuration directory
56 All Nominatim configuration options are prefixed with 'NOMINATIM_' to
57 avoid conflicts with other environment variables.
60 def __init__(self, project_dir: Path, config_dir: Path,
61 environ: Optional[Mapping[str, str]] = None) -> None:
62 self.environ = environ or os.environ
63 self.project_dir = project_dir
64 self.config_dir = config_dir
65 self._config = dotenv_values(str((config_dir / 'env.defaults').resolve()))
66 if project_dir is not None and (project_dir / '.env').is_file():
67 self._config.update(dotenv_values(str((project_dir / '.env').resolve())))
72 self.lib_dir = _LibDirs()
75 def set_libdirs(self, **kwargs: PathOrStr) -> None:
76 """ Set paths to library functions and data.
78 for key, value in kwargs.items():
79 setattr(self.lib_dir, key, Path(value).resolve())
82 def __getattr__(self, name: str) -> str:
83 name = 'NOMINATIM_' + name
85 if name in self.environ:
86 return self.environ[name]
88 return self._config[name] or ''
91 def get_bool(self, name: str) -> bool:
92 """ Return the given configuration parameter as a boolean.
93 Values of '1', 'yes' and 'true' are accepted as truthy values,
94 everything else is interpreted as false.
96 return getattr(self, name).lower() in ('1', 'yes', 'true')
99 def get_int(self, name: str) -> int:
100 """ Return the given configuration parameter as an int.
103 return int(getattr(self, name))
104 except ValueError as exp:
105 LOG.fatal("Invalid setting NOMINATIM_%s. Needs to be a number.", name)
106 raise UsageError("Configuration error.") from exp
109 def get_str_list(self, name: str) -> Optional[List[str]]:
110 """ Return the given configuration parameter as a list of strings.
111 The values are assumed to be given as a comma-sparated list and
112 will be stripped before returning them. On empty values None
115 raw = getattr(self, name)
117 return [v.strip() for v in raw.split(',')] if raw else None
120 def get_path(self, name: str) -> Optional[Path]:
121 """ Return the given configuration parameter as a Path.
122 If a relative path is configured, then the function converts this
123 into an absolute path with the project directory as root path.
124 If the configuration is unset, None is returned.
126 value = getattr(self, name)
130 cfgpath = Path(value)
132 if not cfgpath.is_absolute():
133 cfgpath = self.project_dir / cfgpath
135 return cfgpath.resolve()
138 def get_libpq_dsn(self) -> str:
139 """ Get configured database DSN converted into the key/value format
140 understood by libpq and psycopg.
142 dsn = self.DATABASE_DSN
144 def quote_param(param: str) -> str:
145 key, val = param.split('=')
146 val = val.replace('\\', '\\\\').replace("'", "\\'")
148 val = "'" + val + "'"
149 return key + '=' + val
151 if dsn.startswith('pgsql:'):
152 # Old PHP DSN format. Convert before returning.
153 return ' '.join([quote_param(p) for p in dsn[6:].split(';')])
158 def get_import_style_file(self) -> Path:
159 """ Return the import style file as a path object. Translates the
160 name of the standard styles automatically into a file in the
163 style = getattr(self, 'IMPORT_STYLE')
165 if style in ('admin', 'street', 'address', 'full', 'extratags'):
166 return self.config_dir / f'import-{style}.style'
168 return self.find_config_file('', 'IMPORT_STYLE')
171 def get_os_env(self) -> Dict[str, Optional[str]]:
172 """ Return a copy of the OS environment with the Nominatim configuration
175 env = dict(self._config)
176 env.update(self.environ)
181 def load_sub_configuration(self, filename: PathOrStr,
182 config: Optional[str] = None) -> Any:
183 """ Load additional configuration from a file. `filename` is the name
184 of the configuration file. The file is first searched in the
185 project directory and then in the global settings dirctory.
187 If `config` is set, then the name of the configuration file can
188 be additionally given through a .env configuration option. When
189 the option is set, then the file will be exclusively loaded as set:
190 if the name is an absolute path, the file name is taken as is,
191 if the name is relative, it is taken to be relative to the
194 The format of the file is determined from the filename suffix.
195 Currently only files with extension '.yaml' are supported.
197 YAML files support a special '!include' construct. When the
198 directive is given, the value is taken to be a filename, the file
199 is loaded using this function and added at the position in the
202 configfile = self.find_config_file(filename, config)
204 if str(configfile) in CONFIG_CACHE:
205 return CONFIG_CACHE[str(configfile)]
207 if configfile.suffix in ('.yaml', '.yml'):
208 result = self._load_from_yaml(configfile)
209 elif configfile.suffix == '.json':
210 with configfile.open('r', encoding='utf-8') as cfg:
211 result = json.load(cfg)
213 raise UsageError(f"Config file '{configfile}' has unknown format.")
215 CONFIG_CACHE[str(configfile)] = result
219 def find_config_file(self, filename: PathOrStr,
220 config: Optional[str] = None) -> Path:
221 """ Resolve the location of a configuration file given a filename and
222 an optional configuration option with the file name.
223 Raises a UsageError when the file cannot be found or is not
226 if config is not None:
227 cfg_value = getattr(self, config)
229 cfg_filename = Path(cfg_value)
231 if cfg_filename.is_absolute():
232 cfg_filename = cfg_filename.resolve()
234 if not cfg_filename.is_file():
235 LOG.fatal("Cannot find config file '%s'.", cfg_filename)
236 raise UsageError("Config file not found.")
240 filename = cfg_filename
243 search_paths = [self.project_dir, self.config_dir]
244 for path in search_paths:
245 if path is not None and (path / filename).is_file():
246 return path / filename
248 LOG.fatal("Configuration file '%s' not found.\nDirectories searched: %s",
249 filename, search_paths)
250 raise UsageError("Config file not found.")
253 def _load_from_yaml(self, cfgfile: Path) -> Any:
254 """ Load a YAML configuration file. This installs a special handler that
255 allows to include other YAML files using the '!include' operator.
257 yaml.add_constructor('!include', self._yaml_include_representer,
258 Loader=yaml.SafeLoader)
259 return yaml.safe_load(cfgfile.read_text(encoding='utf-8'))
262 def _yaml_include_representer(self, loader: Any, node: yaml.Node) -> Any:
263 """ Handler for the '!include' operator in YAML files.
265 When the filename is relative, then the file is first searched in the
266 project directory and then in the global settings dirctory.
268 fname = loader.construct_scalar(node)
270 if Path(fname).is_absolute():
271 configfile = Path(fname)
273 configfile = self.find_config_file(loader.construct_scalar(node))
275 if configfile.suffix != '.yaml':
276 LOG.fatal("Format error while reading '%s': only YAML format supported.",
278 raise UsageError("Cannot handle config file format.")
280 return yaml.safe_load(configfile.read_text(encoding='utf-8'))