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 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. from .plugins import Plugin
  2. from .exceptions import *
  3. from lodel.exceptions import *
  4. from lodel.settings.validator import SettingValidator
  5. _glob_typename = 'datasource'
  6. ##@brief Datasource class in plugins HAVE TO inherit from this abstract class
  7. class AbstractDatasource(object):
  8. ##@brief Trigger LodelFatalError when abtract method called
  9. @staticmethod
  10. def _abs_err():
  11. raise LodelFatalError("This method is abstract and HAVE TO be \
  12. reimplemented by plugin datasource child class")
  13. ##@brief The constructor
  14. def __init__(self, *conn_args, **conn_kwargs):
  15. self._abs_err()
  16. ##@brief Provide a new uniq numeric ID
  17. #@param emcomp LeObject subclass (not instance) : To know on wich things we
  18. #have to be uniq
  19. #@return an integer
  20. def new_numeric_id(self, emcomp):
  21. self._abs_err()
  22. ##@brief returns a selection of documents from the datasource
  23. #@param target_cls Emclass
  24. #@param field_list list
  25. #@param filters list : List of filters
  26. #@param rel_filters list : List of relational filters
  27. #@param order list : List of column to order. ex: order = [('title', 'ASC'),]
  28. #@param group list : List of tupple representing the column to group together. ex: group = [('title', 'ASC'),]
  29. #@param limit int : Number of records to be returned
  30. #@param offset int: used with limit to choose the start record
  31. #@param instanciate bool : If true, the records are returned as instances, else they are returned as dict
  32. #@return list
  33. def select(self, target, field_list, filters, rel_filters=None, order=None, group=None, limit=None, offset=0,
  34. instanciate=True):
  35. self._abs_err()
  36. ##@brief Deletes records according to given filters
  37. #@param target Emclass : class of the record to delete
  38. #@param filters list : List of filters
  39. #@param relational_filters list : List of relational filters
  40. #@return int : number of deleted records
  41. def delete(self, target, filters, relational_filters):
  42. self._abs_err()
  43. ## @brief updates records according to given filters
  44. #@param target Emclass : class of the object to insert
  45. #@param filters list : List of filters
  46. #@param relational_filters list : List of relational filters
  47. #@param upd_datas dict : datas to update (new values)
  48. #@return int : Number of updated records
  49. def update(self, target, filters, relational_filters, upd_datas):
  50. self._abs_err()
  51. ## @brief Inserts a record in a given collection
  52. # @param target Emclass : class of the object to insert
  53. # @param new_datas dict : datas to insert
  54. # @return the inserted uid
  55. def insert(self, target, new_datas):
  56. self._abs_err()
  57. ## @brief Inserts a list of records in a given collection
  58. # @param target Emclass : class of the objects inserted
  59. # @param datas_list list : list of dict
  60. # @return list : list of the inserted records' ids
  61. def insert_multi(self, target, datas_list):
  62. self._abs_err()
  63. ##@brief Designed to handles datasources plugins
  64. #
  65. #A datasource provide data access to LeAPI typically a connector on a DB
  66. #or an API
  67. #
  68. #Provide methods to initialize datasource attribute in LeAPI LeObject child
  69. #classes (see @ref leapi.leobject.LeObject._init_datasources() )
  70. #
  71. #@note For the moment implementation is done with a retro-compatibilities
  72. #priority and not with a convenience priority.
  73. #@todo Refactor and rewrite lodel2 datasource handling
  74. #@todo Write abstract classes for Datasource and MigrationHandler !!!
  75. class DatasourcePlugin(Plugin):
  76. _type_conf_name = _glob_typename
  77. ##@brief Stores confspecs indicating where DatasourcePlugin list is stored
  78. _plist_confspecs = {
  79. 'section': 'lodel2',
  80. 'key': 'datasource_connectors',
  81. 'default': None,
  82. 'validator': SettingValidator(
  83. 'custom_list', none_is_valid = False,
  84. validator_name = 'plugin', validator_kwargs = {
  85. 'ptype': _glob_typename,
  86. 'none_is_valid': False})
  87. }
  88. ##@brief Construct a DatasourcePlugin
  89. #@param name str : plugin name
  90. #@see plugins.Plugin
  91. def __init__(self, name):
  92. super().__init__(name)
  93. self.__datasource_cls = None
  94. ##@brief Accessor to the datasource class
  95. #@return A python datasource class
  96. def datasource_cls(self):
  97. if self.__datasource_cls is None:
  98. self.__datasource_cls = self.loader_module().Datasource
  99. if not issubclass(self.__datasource_cls, AbstractDatasource):
  100. raise DatasourcePluginError("The datasource class of the \
  101. '%s' plugin is not a child class of \
  102. lodel.plugin.datasource_plugin.AbstractDatasource" % (self.name))
  103. return self.__datasource_cls
  104. ##@brief Accessor to migration handler class
  105. #@return A python migration handler class
  106. def migration_handler_cls(self):
  107. return self.loader_module().migration_handler_class()
  108. ##@brief Return an initialized Datasource instance
  109. #@param ds_name str : The name of the datasource to instanciate
  110. #@param ro bool
  111. #@return A properly initialized Datasource instance
  112. #@throw SettingsError if an error occurs in settings
  113. #@throw DatasourcePluginError for various errors
  114. @classmethod
  115. def init_datasource(cls, ds_name, ro):
  116. plugin_name, ds_identifier = cls.plugin_name(ds_name, ro)
  117. ds_conf = cls._get_ds_connection_conf(ds_identifier, plugin_name)
  118. ds_cls = cls.get_datasource(plugin_name)
  119. return ds_cls(**ds_conf)
  120. ##@brief Return an initialized MigrationHandler instance
  121. #@param ds_name str : The datasource name
  122. #@return A properly initialized MigrationHandler instance
  123. @classmethod
  124. def init_migration_handler(cls, ds_name):
  125. plugin_name, ds_identifier = cls.plugin_name(ds_name, False)
  126. ds_conf = cls._get_ds_connection_conf(ds_identifier, plugin_name)
  127. mh_cls = cls.get_migration_handler(plugin_name)
  128. if 'read_only' in ds_conf:
  129. if ds_conf['read_only']:
  130. raise PluginError("A read only datasource was given to \
  131. migration handler !!!")
  132. del(ds_conf['read_only'])
  133. return mh_cls(**ds_conf)
  134. ##@brief Given a datasource name returns a DatasourcePlugin name
  135. #@param ds_name str : datasource name
  136. #@param ro bool : if true consider the datasource as readonly
  137. #@return a DatasourcePlugin name
  138. #@throw PluginError if datasource name not found
  139. #@throw DatasourcePermError if datasource is read_only but ro flag arg is
  140. #false
  141. @staticmethod
  142. def plugin_name(ds_name, ro):
  143. from lodel.settings import Settings
  144. # fetching connection identifier given datasource name
  145. try:
  146. ds_identifier = getattr(Settings.datasources, ds_name)
  147. except (NameError, AttributeError):
  148. raise DatasourcePluginError("Unknown or unconfigured datasource \
  149. '%s'" % ds_name)
  150. # fetching read_only flag
  151. try:
  152. read_only = getattr(ds_identifier, 'read_only')
  153. except (NameError, AttributeError):
  154. raise SettingsError("Malformed datasource configuration for '%s' \
  155. : missing read_only key" % ds_name)
  156. # fetching datasource identifier
  157. try:
  158. ds_identifier = getattr(ds_identifier, 'identifier')
  159. except (NameError,AttributeError) as e:
  160. raise SettingsError("Malformed datasource configuration for '%s' \
  161. : missing identifier key" % ds_name)
  162. # settings and ro arg consistency check
  163. if read_only and not ro:
  164. raise DatasourcePluginError("ro argument was set to False but \
  165. True found in settings for datasource '%s'" % ds_name)
  166. res = ds_identifier.split('.')
  167. if len(res) != 2:
  168. raise SettingsError("expected value for identifier is like \
  169. DS_PLUGIN_NAME.DS_INSTANCE_NAME. But got %s" % ds_identifier)
  170. return res
  171. ##@brief Try to fetch a datasource configuration
  172. #@param ds_identifier str : datasource name
  173. #@param ds_plugin_name : datasource plugin name
  174. #@return a dict containing datasource initialisation options
  175. #@throw NameError if a datasource plugin or instance cannot be found
  176. @staticmethod
  177. def _get_ds_connection_conf(ds_identifier,ds_plugin_name):
  178. from lodel.settings import Settings
  179. if ds_plugin_name not in Settings.datasource._fields:
  180. msg = "Unknown or unconfigured datasource plugin %s"
  181. msg %= ds_plugin
  182. raise DatasourcePluginError(msg)
  183. ds_conf = getattr(Settings.datasource, ds_plugin_name)
  184. if ds_identifier not in ds_conf._fields:
  185. msg = "Unknown or unconfigured datasource instance %s"
  186. msg %= ds_identifier
  187. raise DatasourcePluginError(msg)
  188. ds_conf = getattr(ds_conf, ds_identifier)
  189. return {k: getattr(ds_conf,k) for k in ds_conf._fields }
  190. ##@brief DatasourcePlugin instance accessor
  191. #@param ds_name str : plugin name
  192. #@return a DatasourcePlugin instance
  193. #@throw PluginError if no plugin named ds_name found
  194. #@throw PluginTypeError if ds_name ref to a plugin that is not a
  195. #DatasourcePlugin
  196. @classmethod
  197. def get(cls, ds_name):
  198. pinstance = super().get(ds_name) #Will raise PluginError if bad name
  199. if not isinstance(pinstance, DatasourcePlugin):
  200. raise PluginTypeErrror("A name of a DatasourcePlugin was excepted \
  201. but %s is a %s" % (ds_name, pinstance.__class__.__name__))
  202. return pinstance
  203. ##@brief Return a datasource class given a datasource name
  204. #@param ds_name str : datasource plugin name
  205. #@throw PluginError if ds_name is not an existing plugin name
  206. #@throw PluginTypeError if ds_name is not the name of a DatasourcePlugin
  207. @classmethod
  208. def get_datasource(cls, ds_plugin_name):
  209. return cls.get(ds_plugin_name).datasource_cls()
  210. ##@brief Given a plugin name returns a migration handler class
  211. #@param ds_plugin_name str : a datasource plugin name
  212. @classmethod
  213. def get_migration_handler(cls, ds_plugin_name):
  214. return cls.get(ds_plugin_name).migration_handler_cls()
  215. ##@page lodel2_datasources Lodel2 datasources
  216. #
  217. #@par lodel2_datasources_intro Intro
  218. # A single lodel2 website can interact with multiple datasources. This page
  219. # aims to describe configuration & organisation of datasources in lodel2.
  220. # Each object is attached to a datasource. This association is done in the
  221. # editorial model, the datasource is identified by a name.
  222. #
  223. #@par Datasources declaration
  224. # To define a datasource you have to write something like this in confs file :
  225. #<pre>
  226. #[lodel2.datasources.DATASOURCE_NAME]
  227. #identifier = DATASOURCE_FAMILY.SOURCE_NAME
  228. #</pre>
  229. # See below for DATASOURCE_FAMILY & SOURCE_NAME
  230. #
  231. #@par Datasources plugins
  232. # Each datasource family is a plugin (
  233. #@ref plugin_doc "More informations on plugins" ). For example mysql or a
  234. #mongodb plugins. Here is the CONFSPEC variable templates for datasources
  235. #plugin
  236. #<pre>
  237. #CONFSPEC = {
  238. # 'lodel2.datasource.example.*' : {
  239. # 'conf1' : VALIDATOR_OPTS,
  240. # 'conf2' : VALIDATOR_OPTS,
  241. # ...
  242. # }
  243. #}
  244. #</pre>
  245. #MySQL example
  246. #<pre>
  247. #CONFSPEC = {
  248. # 'lodel2.datasource.mysql.*' : {
  249. # 'host': ( 'localhost',
  250. # SettingValidator('host')),
  251. # 'db_name': ( 'lodel',
  252. # SettingValidator('string')),
  253. # 'username': ( None,
  254. # SettingValidator('string')),
  255. # 'password': ( None,
  256. # SettingValidator('string')),
  257. # }
  258. #}
  259. #</pre>
  260. #
  261. #@par Configuration example
  262. #<pre>
  263. # [lodel2.datasources.main]
  264. # identifier = mysql.Core
  265. # [lodel2.datasources.revues_write]
  266. # identifier = mysql.Revues
  267. # [lodel2.datasources.revues_read]
  268. # identifier = mysql.Revues
  269. # [lodel2.datasources.annuaire_persons]
  270. # identifier = persons_web_api.example
  271. # ;
  272. # ; Then, in the editorial model you are able to use "main", "revues_write",
  273. # ; etc as datasource
  274. # ;
  275. # ; Here comes the datasources declarations
  276. # [lodel2.datasource.mysql.Core]
  277. # host = db.core.labocleo.org
  278. # db_name = core
  279. # username = foo
  280. # password = bar
  281. # ;
  282. # [lodel2.datasource.mysql.Revues]
  283. # host = revues.org
  284. # db_name = RO
  285. # username = foo
  286. # password = bar
  287. # ;
  288. # [lodel2.datasource.persons_web_api.example]
  289. # host = foo.bar
  290. # username = cleo
  291. #</pre>