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 self.__getattr__(name).lower() in ('1', 'yes', 'true')
 
  92     def get_int(self, name):
 
  93         """ Return the given configuration parameter as an int.
 
  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
 
 102     def get_path(self, name):
 
 103         """ Return the given configuration parameter as a Path.
 
 104             If a relative path is configured, then the function converts this
 
 105             into an absolute path with the project directory as root path.
 
 106             If the configuration is unset, a falsy value is returned.
 
 108         value = self.__getattr__(name)
 
 112             if not value.is_absolute():
 
 113                 value = self.project_dir / value
 
 115             value = value.resolve()
 
 119     def get_libpq_dsn(self):
 
 120         """ Get configured database DSN converted into the key/value format
 
 121             understood by libpq and psycopg.
 
 123         dsn = self.DATABASE_DSN
 
 125         def quote_param(param):
 
 126             key, val = param.split('=')
 
 127             val = val.replace('\\', '\\\\').replace("'", "\\'")
 
 129                 val = "'" + val + "'"
 
 130             return key + '=' + val
 
 132         if dsn.startswith('pgsql:'):
 
 133             # Old PHP DSN format. Convert before returning.
 
 134             return ' '.join([quote_param(p) for p in dsn[6:].split(';')])
 
 139     def get_import_style_file(self):
 
 140         """ Return the import style file as a path object. Translates the
 
 141             name of the standard styles automatically into a file in the
 
 144         style = self.__getattr__('IMPORT_STYLE')
 
 146         if style in ('admin', 'street', 'address', 'full', 'extratags'):
 
 147             return self.config_dir / 'import-{}.style'.format(style)
 
 149         return self.find_config_file('', 'IMPORT_STYLE')
 
 152     def get_os_env(self):
 
 153         """ Return a copy of the OS environment with the Nominatim configuration
 
 156         env = dict(self._config)
 
 157         env.update(self.environ)
 
 162     def load_sub_configuration(self, filename, config=None):
 
 163         """ Load additional configuration from a file. `filename` is the name
 
 164             of the configuration file. The file is first searched in the
 
 165             project directory and then in the global settings dirctory.
 
 167             If `config` is set, then the name of the configuration file can
 
 168             be additionally given through a .env configuration option. When
 
 169             the option is set, then the file will be exclusively loaded as set:
 
 170             if the name is an absolute path, the file name is taken as is,
 
 171             if the name is relative, it is taken to be relative to the
 
 174             The format of the file is determined from the filename suffix.
 
 175             Currently only files with extension '.yaml' are supported.
 
 177             YAML files support a special '!include' construct. When the
 
 178             directive is given, the value is taken to be a filename, the file
 
 179             is loaded using this function and added at the position in the
 
 182         configfile = self.find_config_file(filename, config)
 
 184         if configfile.suffix in ('.yaml', '.yml'):
 
 185             return self._load_from_yaml(configfile)
 
 187         if configfile.suffix == '.json':
 
 188             with configfile.open('r') as cfg:
 
 189                 return json.load(cfg)
 
 191         raise UsageError(f"Config file '{configfile}' has unknown format.")
 
 194     def find_config_file(self, filename, config=None):
 
 195         """ Resolve the location of a configuration file given a filename and
 
 196             an optional configuration option with the file name.
 
 197             Raises a UsageError when the file cannot be found or is not
 
 200         if config is not None:
 
 201             cfg_filename = self.__getattr__(config)
 
 203                 cfg_filename = Path(cfg_filename)
 
 205                 if cfg_filename.is_absolute():
 
 206                     cfg_filename = cfg_filename.resolve()
 
 208                     if not cfg_filename.is_file():
 
 209                         LOG.fatal("Cannot find config file '%s'.", cfg_filename)
 
 210                         raise UsageError("Config file not found.")
 
 214                 filename = cfg_filename
 
 217         search_paths = [self.project_dir, self.config_dir]
 
 218         for path in search_paths:
 
 219             if path is not None and (path / filename).is_file():
 
 220                 return path / filename
 
 222         LOG.fatal("Configuration file '%s' not found.\nDirectories searched: %s",
 
 223                   filename, search_paths)
 
 224         raise UsageError("Config file not found.")
 
 227     def _load_from_yaml(self, cfgfile):
 
 228         """ Load a YAML configuration file. This installs a special handler that
 
 229             allows to include other YAML files using the '!include' operator.
 
 231         yaml.add_constructor('!include', self._yaml_include_representer,
 
 232                              Loader=yaml.SafeLoader)
 
 233         return yaml.safe_load(cfgfile.read_text(encoding='utf-8'))
 
 236     def _yaml_include_representer(self, loader, node):
 
 237         """ Handler for the '!include' operator in YAML files.
 
 239             When the filename is relative, then the file is first searched in the
 
 240             project directory and then in the global settings dirctory.
 
 242         fname = loader.construct_scalar(node)
 
 244         if Path(fname).is_absolute():
 
 245             configfile = Path(fname)
 
 247             configfile = self.find_config_file(loader.construct_scalar(node))
 
 249         if configfile.suffix != '.yaml':
 
 250             LOG.fatal("Format error while reading '%s': only YAML format supported.",
 
 252             raise UsageError("Cannot handle config file format.")
 
 254         return yaml.safe_load(configfile.read_text(encoding='utf-8'))