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 / f'import-{style}.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 str(configfile) in CONFIG_CACHE:
 
 185             return CONFIG_CACHE[str(configfile)]
 
 187         if configfile.suffix in ('.yaml', '.yml'):
 
 188             result = self._load_from_yaml(configfile)
 
 189         elif configfile.suffix == '.json':
 
 190             with configfile.open('r', encoding='utf-8') as cfg:
 
 191                 result = json.load(cfg)
 
 193             raise UsageError(f"Config file '{configfile}' has unknown format.")
 
 195         CONFIG_CACHE[str(configfile)] = result
 
 199     def find_config_file(self, filename, config=None):
 
 200         """ Resolve the location of a configuration file given a filename and
 
 201             an optional configuration option with the file name.
 
 202             Raises a UsageError when the file cannot be found or is not
 
 205         if config is not None:
 
 206             cfg_filename = self.__getattr__(config)
 
 208                 cfg_filename = Path(cfg_filename)
 
 210                 if cfg_filename.is_absolute():
 
 211                     cfg_filename = cfg_filename.resolve()
 
 213                     if not cfg_filename.is_file():
 
 214                         LOG.fatal("Cannot find config file '%s'.", cfg_filename)
 
 215                         raise UsageError("Config file not found.")
 
 219                 filename = cfg_filename
 
 222         search_paths = [self.project_dir, self.config_dir]
 
 223         for path in search_paths:
 
 224             if path is not None and (path / filename).is_file():
 
 225                 return path / filename
 
 227         LOG.fatal("Configuration file '%s' not found.\nDirectories searched: %s",
 
 228                   filename, search_paths)
 
 229         raise UsageError("Config file not found.")
 
 232     def _load_from_yaml(self, cfgfile):
 
 233         """ Load a YAML configuration file. This installs a special handler that
 
 234             allows to include other YAML files using the '!include' operator.
 
 236         yaml.add_constructor('!include', self._yaml_include_representer,
 
 237                              Loader=yaml.SafeLoader)
 
 238         return yaml.safe_load(cfgfile.read_text(encoding='utf-8'))
 
 241     def _yaml_include_representer(self, loader, node):
 
 242         """ Handler for the '!include' operator in YAML files.
 
 244             When the filename is relative, then the file is first searched in the
 
 245             project directory and then in the global settings dirctory.
 
 247         fname = loader.construct_scalar(node)
 
 249         if Path(fname).is_absolute():
 
 250             configfile = Path(fname)
 
 252             configfile = self.find_config_file(loader.construct_scalar(node))
 
 254         if configfile.suffix != '.yaml':
 
 255             LOG.fatal("Format error while reading '%s': only YAML format supported.",
 
 257             raise UsageError("Cannot handle config file format.")
 
 259         return yaml.safe_load(configfile.read_text(encoding='utf-8'))