You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

111 rivejä
3.8 KiB

  1. # Copyright 2017 New Vector Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import importlib
  15. import importlib.util
  16. from types import ModuleType
  17. from typing import Any, Tuple, Type
  18. import jsonschema
  19. from synapse.config._base import ConfigError
  20. from synapse.config._util import json_error_to_config_error
  21. from synapse.types import StrSequence
  22. def load_module(provider: dict, config_path: StrSequence) -> Tuple[Type, Any]:
  23. """Loads a synapse module with its config
  24. Args:
  25. provider: a dict with keys 'module' (the module name) and 'config'
  26. (the config dict).
  27. config_path: the path within the config file. This will be used as a basis
  28. for any error message.
  29. Returns
  30. Tuple of (provider class, parsed config object)
  31. """
  32. modulename = provider.get("module")
  33. if not isinstance(modulename, str):
  34. raise ConfigError("expected a string", path=tuple(config_path) + ("module",))
  35. # We need to import the module, and then pick the class out of
  36. # that, so we split based on the last dot.
  37. module_name, clz = modulename.rsplit(".", 1)
  38. module = importlib.import_module(module_name)
  39. provider_class = getattr(module, clz)
  40. # Load the module config. If None, pass an empty dictionary instead
  41. module_config = provider.get("config") or {}
  42. if hasattr(provider_class, "parse_config"):
  43. try:
  44. provider_config = provider_class.parse_config(module_config)
  45. except jsonschema.ValidationError as e:
  46. raise json_error_to_config_error(e, tuple(config_path) + ("config",))
  47. except ConfigError as e:
  48. raise _wrap_config_error(
  49. "Failed to parse config for module %r" % (modulename,),
  50. prefix=tuple(config_path) + ("config",),
  51. e=e,
  52. )
  53. except Exception as e:
  54. raise ConfigError(
  55. "Failed to parse config for module %r" % (modulename,),
  56. path=tuple(config_path) + ("config",),
  57. ) from e
  58. else:
  59. provider_config = module_config
  60. return provider_class, provider_config
  61. def load_python_module(location: str) -> ModuleType:
  62. """Load a python module, and return a reference to its global namespace
  63. Args:
  64. location: path to the module
  65. Returns:
  66. python module object
  67. """
  68. spec = importlib.util.spec_from_file_location(location, location)
  69. if spec is None:
  70. raise Exception("Unable to load module at %s" % (location,))
  71. mod = importlib.util.module_from_spec(spec)
  72. spec.loader.exec_module(mod) # type: ignore
  73. return mod
  74. def _wrap_config_error(msg: str, prefix: StrSequence, e: ConfigError) -> "ConfigError":
  75. """Wrap a relative ConfigError with a new path
  76. This is useful when we have a ConfigError with a relative path due to a problem
  77. parsing part of the config, and we now need to set it in context.
  78. """
  79. path = prefix
  80. if e.path:
  81. path = tuple(prefix) + tuple(e.path)
  82. e1 = ConfigError(msg, path)
  83. # ideally we would set the 'cause' of the new exception to the original exception;
  84. # however now that we have merged the path into our own, the stringification of
  85. # e will be incorrect, so instead we create a new exception with just the "msg"
  86. # part.
  87. e1.__cause__ = Exception(e.msg)
  88. e1.__cause__.__cause__ = e.__cause__
  89. return e1