No Description
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.

datasource_plugin.py 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. from .plugins import Plugin
  2. from .exceptions import *
  3. from lodel.settings.validator import SettingValidator
  4. ##@brief Designed to handles datasources plugins
  5. #
  6. #A datasource provide data access to LeAPI typically a connector on a DB
  7. #or an API
  8. #
  9. #Provide methods to initialize datasource attribute in LeAPI LeObject child
  10. #classes (see @ref leapi.leobject.LeObject._init_datasources() )
  11. #
  12. #@note For the moment implementation is done with a retro-compatibilities
  13. #priority and not with a convenience priority.
  14. #@todo Refactor and rewrite lodel2 datasource handling
  15. #@todo Write abstract classes for Datasource and MigrationHandler !!!
  16. class DatasourcePlugin(Plugin):
  17. ##@brief Stores confspecs indicating where DatasourcePlugin list is stored
  18. _plist_confspecs = {
  19. 'section': 'lodel2',
  20. 'key': 'datasource_connectors',
  21. 'default': None,
  22. 'validator': SettingValidator('strip', none_is_valid = False) }
  23. _type_conf_name = 'datasource'
  24. ##@brief Construct a DatasourcePlugin
  25. #@param name str : plugin name
  26. #@see plugins.Plugin
  27. def __init__(self, name):
  28. super().__init__(name)
  29. self.__datasource_cls = None
  30. ##@brief Accessor to the datasource class
  31. #@return A python datasource class
  32. def datasource_cls(self):
  33. if self.__datasource_cls is None:
  34. self.__datasource_cls = self.loader_module().Datasource
  35. return self.__datasource_cls
  36. ##@brief Accessor to migration handler class
  37. #@return A python migration handler class
  38. def migration_handler_cls(self):
  39. return self.loader_module().migration_handler_class()
  40. ##@brief Return an initialized Datasource instance
  41. #@param ds_name str : The name of the datasource to instanciate
  42. #@param ro bool
  43. #@return A properly initialized Datasource instance
  44. #@throw SettingsError if an error occurs in settings
  45. #@throw DatasourcePluginError for various errors
  46. @classmethod
  47. def init_datasource(cls, ds_name, ro):
  48. plugin_name, ds_identifier = cls.plugin_name(ds_name, ro)
  49. ds_conf = cls._get_ds_connection_conf(ds_identifier, plugin_name)
  50. ds_cls = cls.get_datasource(plugin_name)
  51. return ds_cls(**ds_conf)
  52. ##@brief Return an initialized MigrationHandler instance
  53. #@param ds_name str : The datasource name
  54. #@return A properly initialized MigrationHandler instance
  55. @classmethod
  56. def init_migration_handler(cls, ds_name):
  57. plugin_name, ds_identifier = cls.plugin_name(ds_name, False)
  58. ds_conf = cls._get_ds_connection_conf(ds_identifier, plugin_name)
  59. mh_cls = cls.get_migration_handler(plugin_name)
  60. if 'read_only' in ds_conf:
  61. if ds_conf['read_only']:
  62. raise PluginError("A read only datasource was given to \
  63. migration handler !!!")
  64. del(ds_conf['read_only'])
  65. return mh_cls(**ds_conf)
  66. ##@brief Given a datasource name returns a DatasourcePlugin name
  67. #@param ds_name str : datasource name
  68. #@param ro bool : if true consider the datasource as readonly
  69. #@return a DatasourcePlugin name
  70. #@throw PluginError if datasource name not found
  71. #@throw DatasourcePermError if datasource is read_only but ro flag arg is
  72. #false
  73. @staticmethod
  74. def plugin_name(ds_name, ro):
  75. from lodel.settings import Settings
  76. # fetching connection identifier given datasource name
  77. try:
  78. ds_identifier = getattr(Settings.datasources, ds_name)
  79. except (NameError, AttributeError):
  80. raise DatasourcePluginError("Unknown or unconfigured datasource \
  81. '%s'" % ds_name)
  82. # fetching read_only flag
  83. try:
  84. read_only = getattr(ds_identifier, 'read_only')
  85. except (NameError, AttributeError):
  86. raise SettingsError("Malformed datasource configuration for '%s' \
  87. : missing read_only key" % ds_name)
  88. # fetching datasource identifier
  89. try:
  90. ds_identifier = getattr(ds_identifier, 'identifier')
  91. except (NameError,AttributeError) as e:
  92. raise SettingsError("Malformed datasource configuration for '%s' \
  93. : missing identifier key" % ds_name)
  94. # settings and ro arg consistency check
  95. if read_only and not ro:
  96. raise DatasourcePluginError("ro argument was set to False but \
  97. True found in settings for datasource '%s'" % ds_name)
  98. res = ds_identifier.split('.')
  99. if len(res) != 2:
  100. raise SettingsError("expected value for identifier is like \
  101. DS_PLUGIN_NAME.DS_INSTANCE_NAME. But got %s" % ds_identifier)
  102. return res
  103. ##@brief Try to fetch a datasource configuration
  104. #@param ds_identifier str : datasource name
  105. #@param ds_plugin_name : datasource plugin name
  106. #@return a dict containing datasource initialisation options
  107. #@throw NameError if a datasource plugin or instance cannot be found
  108. @staticmethod
  109. def _get_ds_connection_conf(ds_identifier,ds_plugin_name):
  110. from lodel.settings import Settings
  111. if ds_plugin_name not in Settings.datasource._fields:
  112. msg = "Unknown or unconfigured datasource plugin %s"
  113. msg %= ds_plugin
  114. raise DatasourcePluginError(msg)
  115. ds_conf = getattr(Settings.datasource, ds_plugin_name)
  116. if ds_identifier not in ds_conf._fields:
  117. msg = "Unknown or unconfigured datasource instance %s"
  118. msg %= ds_identifier
  119. raise DatasourcePluginError(msg)
  120. ds_conf = getattr(ds_conf, ds_identifier)
  121. return {k: getattr(ds_conf,k) for k in ds_conf._fields }
  122. ##@brief DatasourcePlugin instance accessor
  123. #@param ds_name str : plugin name
  124. #@return a DatasourcePlugin instance
  125. #@throw PluginError if no plugin named ds_name found
  126. #@throw PluginTypeError if ds_name ref to a plugin that is not a
  127. #DatasourcePlugin
  128. @classmethod
  129. def get(cls, ds_name):
  130. pinstance = super().get(ds_name) #Will raise PluginError if bad name
  131. if not isinstance(pinstance, DatasourcePlugin):
  132. raise PluginTypeErrror("A name of a DatasourcePlugin was excepted \
  133. but %s is a %s" % (ds_name, pinstance.__class__.__name__))
  134. return pinstance
  135. ##@brief Return a datasource class given a datasource name
  136. #@param ds_name str : datasource plugin name
  137. #@throw PluginError if ds_name is not an existing plugin name
  138. #@throw PluginTypeError if ds_name is not the name of a DatasourcePlugin
  139. @classmethod
  140. def get_datasource(cls, ds_plugin_name):
  141. return cls.get(ds_plugin_name).datasource_cls()
  142. ##@brief Given a plugin name returns a migration handler class
  143. #@param ds_plugin_name str : a datasource plugin name
  144. @classmethod
  145. def get_migration_handler(cls, ds_plugin_name):
  146. return cls.get(ds_plugin_name).migration_handler_cls()
  147. ##@page lodel2_datasources Lodel2 datasources
  148. #
  149. #@par lodel2_datasources_intro Intro
  150. # A single lodel2 website can interact with multiple datasources. This page
  151. # aims to describe configuration & organisation of datasources in lodel2.
  152. # Each object is attached to a datasource. This association is done in the
  153. # editorial model, the datasource is identified by a name.
  154. #
  155. #@par Datasources declaration
  156. # To define a datasource you have to write something like this in confs file :
  157. #<pre>
  158. #[lodel2.datasources.DATASOURCE_NAME]
  159. #identifier = DATASOURCE_FAMILY.SOURCE_NAME
  160. #</pre>
  161. # See below for DATASOURCE_FAMILY & SOURCE_NAME
  162. #
  163. #@par Datasources plugins
  164. # Each datasource family is a plugin (
  165. #@ref plugin_doc "More informations on plugins" ). For example mysql or a
  166. #mongodb plugins. Here is the CONFSPEC variable templates for datasources
  167. #plugin
  168. #<pre>
  169. #CONFSPEC = {
  170. # 'lodel2.datasource.example.*' : {
  171. # 'conf1' : VALIDATOR_OPTS,
  172. # 'conf2' : VALIDATOR_OPTS,
  173. # ...
  174. # }
  175. #}
  176. #</pre>
  177. #MySQL example
  178. #<pre>
  179. #CONFSPEC = {
  180. # 'lodel2.datasource.mysql.*' : {
  181. # 'host': ( 'localhost',
  182. # SettingValidator('host')),
  183. # 'db_name': ( 'lodel',
  184. # SettingValidator('string')),
  185. # 'username': ( None,
  186. # SettingValidator('string')),
  187. # 'password': ( None,
  188. # SettingValidator('string')),
  189. # }
  190. #}
  191. #</pre>
  192. #
  193. #@par Configuration example
  194. #<pre>
  195. # [lodel2.datasources.main]
  196. # identifier = mysql.Core
  197. # [lodel2.datasources.revues_write]
  198. # identifier = mysql.Revues
  199. # [lodel2.datasources.revues_read]
  200. # identifier = mysql.Revues
  201. # [lodel2.datasources.annuaire_persons]
  202. # identifier = persons_web_api.example
  203. # ;
  204. # ; Then, in the editorial model you are able to use "main", "revues_write",
  205. # ; etc as datasource
  206. # ;
  207. # ; Here comes the datasources declarations
  208. # [lodel2.datasource.mysql.Core]
  209. # host = db.core.labocleo.org
  210. # db_name = core
  211. # username = foo
  212. # password = bar
  213. # ;
  214. # [lodel2.datasource.mysql.Revues]
  215. # host = revues.org
  216. # db_name = RO
  217. # username = foo
  218. # password = bar
  219. # ;
  220. # [lodel2.datasource.persons_web_api.example]
  221. # host = foo.bar
  222. # username = cleo
  223. #</pre>