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.
 
  12 from pathlib import Path
 
  16 from dotenv import dotenv_values
 
  18 from nominatim.errors import UsageError
 
  20 LOG = logging.getLogger()
 
  23 def flatten_config_list(content, section=''):
 
  24     """ Flatten YAML configuration lists that contain include sections
 
  25         which are lists themselves.
 
  30     if not isinstance(content, list):
 
  31         raise UsageError(f"List expected in section '{section}'.")
 
  35         if isinstance(ele, list):
 
  36             output.extend(flatten_config_list(ele, section))
 
  44     """ Load and manage the project configuration.
 
  46         Nominatim uses dotenv to configure the software. Configuration options
 
  47         are resolved in the following order:
 
  49          * from the OS environment (or the dirctionary given in `environ`
 
  50          * from the .env file in the project directory of the installation
 
  51          * from the default installation in the configuration directory
 
  53         All Nominatim configuration options are prefixed with 'NOMINATIM_' to
 
  54         avoid conflicts with other environment variables.
 
  57     def __init__(self, project_dir, config_dir, environ=None):
 
  58         self.environ = environ or os.environ
 
  59         self.project_dir = project_dir
 
  60         self.config_dir = config_dir
 
  61         self._config = dotenv_values(str((config_dir / 'env.defaults').resolve()))
 
  62         if project_dir is not None and (project_dir / '.env').is_file():
 
  63             self._config.update(dotenv_values(str((project_dir / '.env').resolve())))
 
  68         self.lib_dir = _LibDirs()
 
  70     def set_libdirs(self, **kwargs):
 
  71         """ Set paths to library functions and data.
 
  73         for key, value in kwargs.items():
 
  74             setattr(self.lib_dir, key, Path(value).resolve())
 
  76     def __getattr__(self, name):
 
  77         name = 'NOMINATIM_' + name
 
  79         if name in self.environ:
 
  80             return self.environ[name]
 
  82         return self._config[name]
 
  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.
 
  89         return getattr(self, name).lower() in ('1', 'yes', 'true')
 
  92     def get_int(self, name):
 
  93         """ Return the given configuration parameter as an int.
 
  96             return int(getattr(self, 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
 
 102     def get_str_list(self, name):
 
 103         """ Return the given configuration parameter as a list of strings.
 
 104             The values are assumed to be given as a comma-sparated list and
 
 105             will be stripped before returning them. On empty values None
 
 108         raw = getattr(self, name)
 
 110         return [v.strip() for v in raw.split(',')] if raw else None
 
 113     def get_path(self, name):
 
 114         """ Return the given configuration parameter as a Path.
 
 115             If a relative path is configured, then the function converts this
 
 116             into an absolute path with the project directory as root path.
 
 117             If the configuration is unset, a falsy value is returned.
 
 119         value = getattr(self, name)
 
 123             if not value.is_absolute():
 
 124                 value = self.project_dir / value
 
 126             value = value.resolve()
 
 130     def get_libpq_dsn(self):
 
 131         """ Get configured database DSN converted into the key/value format
 
 132             understood by libpq and psycopg.
 
 134         dsn = self.DATABASE_DSN
 
 136         def quote_param(param):
 
 137             key, val = param.split('=')
 
 138             val = val.replace('\\', '\\\\').replace("'", "\\'")
 
 140                 val = "'" + val + "'"
 
 141             return key + '=' + val
 
 143         if dsn.startswith('pgsql:'):
 
 144             # Old PHP DSN format. Convert before returning.
 
 145             return ' '.join([quote_param(p) for p in dsn[6:].split(';')])
 
 150     def get_import_style_file(self):
 
 151         """ Return the import style file as a path object. Translates the
 
 152             name of the standard styles automatically into a file in the
 
 155         style = getattr(self, 'IMPORT_STYLE')
 
 157         if style in ('admin', 'street', 'address', 'full', 'extratags'):
 
 158             return self.config_dir / f'import-{style}.style'
 
 160         return self.find_config_file('', 'IMPORT_STYLE')
 
 163     def get_os_env(self):
 
 164         """ Return a copy of the OS environment with the Nominatim configuration
 
 167         env = dict(self._config)
 
 168         env.update(self.environ)
 
 173     def load_sub_configuration(self, filename, config=None):
 
 174         """ Load additional configuration from a file. `filename` is the name
 
 175             of the configuration file. The file is first searched in the
 
 176             project directory and then in the global settings dirctory.
 
 178             If `config` is set, then the name of the configuration file can
 
 179             be additionally given through a .env configuration option. When
 
 180             the option is set, then the file will be exclusively loaded as set:
 
 181             if the name is an absolute path, the file name is taken as is,
 
 182             if the name is relative, it is taken to be relative to the
 
 185             The format of the file is determined from the filename suffix.
 
 186             Currently only files with extension '.yaml' are supported.
 
 188             YAML files support a special '!include' construct. When the
 
 189             directive is given, the value is taken to be a filename, the file
 
 190             is loaded using this function and added at the position in the
 
 193         configfile = self.find_config_file(filename, config)
 
 195         if str(configfile) in CONFIG_CACHE:
 
 196             return CONFIG_CACHE[str(configfile)]
 
 198         if configfile.suffix in ('.yaml', '.yml'):
 
 199             result = self._load_from_yaml(configfile)
 
 200         elif configfile.suffix == '.json':
 
 201             with configfile.open('r', encoding='utf-8') as cfg:
 
 202                 result = json.load(cfg)
 
 204             raise UsageError(f"Config file '{configfile}' has unknown format.")
 
 206         CONFIG_CACHE[str(configfile)] = result
 
 210     def find_config_file(self, filename, config=None):
 
 211         """ Resolve the location of a configuration file given a filename and
 
 212             an optional configuration option with the file name.
 
 213             Raises a UsageError when the file cannot be found or is not
 
 216         if config is not None:
 
 217             cfg_filename = getattr(self, config)
 
 219                 cfg_filename = Path(cfg_filename)
 
 221                 if cfg_filename.is_absolute():
 
 222                     cfg_filename = cfg_filename.resolve()
 
 224                     if not cfg_filename.is_file():
 
 225                         LOG.fatal("Cannot find config file '%s'.", cfg_filename)
 
 226                         raise UsageError("Config file not found.")
 
 230                 filename = cfg_filename
 
 233         search_paths = [self.project_dir, self.config_dir]
 
 234         for path in search_paths:
 
 235             if path is not None and (path / filename).is_file():
 
 236                 return path / filename
 
 238         LOG.fatal("Configuration file '%s' not found.\nDirectories searched: %s",
 
 239                   filename, search_paths)
 
 240         raise UsageError("Config file not found.")
 
 243     def _load_from_yaml(self, cfgfile):
 
 244         """ Load a YAML configuration file. This installs a special handler that
 
 245             allows to include other YAML files using the '!include' operator.
 
 247         yaml.add_constructor('!include', self._yaml_include_representer,
 
 248                              Loader=yaml.SafeLoader)
 
 249         return yaml.safe_load(cfgfile.read_text(encoding='utf-8'))
 
 252     def _yaml_include_representer(self, loader, node):
 
 253         """ Handler for the '!include' operator in YAML files.
 
 255             When the filename is relative, then the file is first searched in the
 
 256             project directory and then in the global settings dirctory.
 
 258         fname = loader.construct_scalar(node)
 
 260         if Path(fname).is_absolute():
 
 261             configfile = Path(fname)
 
 263             configfile = self.find_config_file(loader.construct_scalar(node))
 
 265         if configfile.suffix != '.yaml':
 
 266             LOG.fatal("Format error while reading '%s': only YAML format supported.",
 
 268             raise UsageError("Cannot handle config file format.")
 
 270         return yaml.safe_load(configfile.read_text(encoding='utf-8'))