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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. 'plugin', none_is_valid = False,
  84. ptype = _glob_typename) }
  85. ##@brief Construct a DatasourcePlugin
  86. #@param name str : plugin name
  87. #@see plugins.Plugin
  88. def __init__(self, name):
  89. super().__init__(name)
  90. self.__datasource_cls = None
  91. ##@brief Accessor to the datasource class
  92. #@return A python datasource class
  93. def datasource_cls(self):
  94. if self.__datasource_cls is None:
  95. self.__datasource_cls = self.loader_module().Datasource
  96. if not issubclass(self.__datasource_cls, AbstractDatasource):
  97. raise DatasourcePluginError("The datasource class of the \
  98. '%s' plugin is not a child class of \
  99. lodel.plugin.datasource_plugin.AbstractDatasource" % (self.name))
  100. return self.__datasource_cls
  101. ##@brief Accessor to migration handler class
  102. #@return A python migration handler class
  103. def migration_handler_cls(self):
  104. return self.loader_module().migration_handler_class()
  105. ##@brief Return an initialized Datasource instance
  106. #@param ds_name str : The name of the datasource to instanciate
  107. #@param ro bool
  108. #@return A properly initialized Datasource instance
  109. #@throw SettingsError if an error occurs in settings
  110. #@throw DatasourcePluginError for various errors
  111. @classmethod
  112. def init_datasource(cls, ds_name, ro):
  113. plugin_name, ds_identifier = cls.plugin_name(ds_name, ro)
  114. ds_conf = cls._get_ds_connection_conf(ds_identifier, plugin_name)
  115. ds_cls = cls.get_datasource(plugin_name)
  116. return ds_cls(**ds_conf)
  117. ##@brief Return an initialized MigrationHandler instance
  118. #@param ds_name str : The datasource name
  119. #@return A properly initialized MigrationHandler instance
  120. @classmethod
  121. def init_migration_handler(cls, ds_name):
  122. plugin_name, ds_identifier = cls.plugin_name(ds_name, False)
  123. ds_conf = cls._get_ds_connection_conf(ds_identifier, plugin_name)
  124. mh_cls = cls.get_migration_handler(plugin_name)
  125. if 'read_only' in ds_conf:
  126. if ds_conf['read_only']:
  127. raise PluginError("A read only datasource was given to \
  128. migration handler !!!")
  129. del(ds_conf['read_only'])
  130. return mh_cls(**ds_conf)
  131. ##@brief Given a datasource name returns a DatasourcePlugin name
  132. #@param ds_name str : datasource name
  133. #@param ro bool : if true consider the datasource as readonly
  134. #@return a DatasourcePlugin name
  135. #@throw PluginError if datasource name not found
  136. #@throw DatasourcePermError if datasource is read_only but ro flag arg is
  137. #false
  138. @staticmethod
  139. def plugin_name(ds_name, ro):
  140. from lodel.settings import Settings
  141. # fetching connection identifier given datasource name
  142. try:
  143. ds_identifier = getattr(Settings.datasources, ds_name)
  144. except (NameError, AttributeError):
  145. raise DatasourcePluginError("Unknown or unconfigured datasource \
  146. '%s'" % ds_name)
  147. # fetching read_only flag
  148. try:
  149. read_only = getattr(ds_identifier, 'read_only')
  150. except (NameError, AttributeError):
  151. raise SettingsError("Malformed datasource configuration for '%s' \
  152. : missing read_only key" % ds_name)
  153. # fetching datasource identifier
  154. try:
  155. ds_identifier = getattr(ds_identifier, 'identifier')
  156. except (NameError,AttributeError) as e:
  157. raise SettingsError("Malformed datasource configuration for '%s' \
  158. : missing identifier key" % ds_name)
  159. # settings and ro arg consistency check
  160. if read_only and not ro:
  161. raise DatasourcePluginError("ro argument was set to False but \
  162. True found in settings for datasource '%s'" % ds_name)
  163. res = ds_identifier.split('.')
  164. if len(res) != 2:
  165. raise SettingsError("expected value for identifier is like \
  166. DS_PLUGIN_NAME.DS_INSTANCE_NAME. But got %s" % ds_identifier)
  167. return res
  168. ##@brief Try to fetch a datasource configuration
  169. #@param ds_identifier str : datasource name
  170. #@param ds_plugin_name : datasource plugin name
  171. #@return a dict containing datasource initialisation options
  172. #@throw NameError if a datasource plugin or instance cannot be found
  173. @staticmethod
  174. def _get_ds_connection_conf(ds_identifier,ds_plugin_name):
  175. from lodel.settings import Settings
  176. if ds_plugin_name not in Settings.datasource._fields:
  177. msg = "Unknown or unconfigured datasource plugin %s"
  178. msg %= ds_plugin
  179. raise DatasourcePluginError(msg)
  180. ds_conf = getattr(Settings.datasource, ds_plugin_name)
  181. if ds_identifier not in ds_conf._fields:
  182. msg = "Unknown or unconfigured datasource instance %s"
  183. msg %= ds_identifier
  184. raise DatasourcePluginError(msg)
  185. ds_conf = getattr(ds_conf, ds_identifier)
  186. return {k: getattr(ds_conf,k) for k in ds_conf._fields }
  187. ##@brief DatasourcePlugin instance accessor
  188. #@param ds_name str : plugin name
  189. #@return a DatasourcePlugin instance
  190. #@throw PluginError if no plugin named ds_name found
  191. #@throw PluginTypeError if ds_name ref to a plugin that is not a
  192. #DatasourcePlugin
  193. @classmethod
  194. def get(cls, ds_name):
  195. pinstance = super().get(ds_name) #Will raise PluginError if bad name
  196. if not isinstance(pinstance, DatasourcePlugin):
  197. raise PluginTypeErrror("A name of a DatasourcePlugin was excepted \
  198. but %s is a %s" % (ds_name, pinstance.__class__.__name__))
  199. return pinstance
  200. ##@brief Return a datasource class given a datasource name
  201. #@param ds_name str : datasource plugin name
  202. #@throw PluginError if ds_name is not an existing plugin name
  203. #@throw PluginTypeError if ds_name is not the name of a DatasourcePlugin
  204. @classmethod
  205. def get_datasource(cls, ds_plugin_name):
  206. return cls.get(ds_plugin_name).datasource_cls()
  207. ##@brief Given a plugin name returns a migration handler class
  208. #@param ds_plugin_name str : a datasource plugin name
  209. @classmethod
  210. def get_migration_handler(cls, ds_plugin_name):
  211. return cls.get(ds_plugin_name).migration_handler_cls()
  212. ##@page lodel2_datasources Lodel2 datasources
  213. #
  214. #@par lodel2_datasources_intro Intro
  215. # A single lodel2 website can interact with multiple datasources. This page
  216. # aims to describe configuration & organisation of datasources in lodel2.
  217. # Each object is attached to a datasource. This association is done in the
  218. # editorial model, the datasource is identified by a name.
  219. #
  220. #@par Datasources declaration
  221. # To define a datasource you have to write something like this in confs file :
  222. #<pre>
  223. #[lodel2.datasources.DATASOURCE_NAME]
  224. #identifier = DATASOURCE_FAMILY.SOURCE_NAME
  225. #</pre>
  226. # See below for DATASOURCE_FAMILY & SOURCE_NAME
  227. #
  228. #@par Datasources plugins
  229. # Each datasource family is a plugin (
  230. #@ref plugin_doc "More informations on plugins" ). For example mysql or a
  231. #mongodb plugins. Here is the CONFSPEC variable templates for datasources
  232. #plugin
  233. #<pre>
  234. #CONFSPEC = {
  235. # 'lodel2.datasource.example.*' : {
  236. # 'conf1' : VALIDATOR_OPTS,
  237. # 'conf2' : VALIDATOR_OPTS,
  238. # ...
  239. # }
  240. #}
  241. #</pre>
  242. #MySQL example
  243. #<pre>
  244. #CONFSPEC = {
  245. # 'lodel2.datasource.mysql.*' : {
  246. # 'host': ( 'localhost',
  247. # SettingValidator('host')),
  248. # 'db_name': ( 'lodel',
  249. # SettingValidator('string')),
  250. # 'username': ( None,
  251. # SettingValidator('string')),
  252. # 'password': ( None,
  253. # SettingValidator('string')),
  254. # }
  255. #}
  256. #</pre>
  257. #
  258. #@par Configuration example
  259. #<pre>
  260. # [lodel2.datasources.main]
  261. # identifier = mysql.Core
  262. # [lodel2.datasources.revues_write]
  263. # identifier = mysql.Revues
  264. # [lodel2.datasources.revues_read]
  265. # identifier = mysql.Revues
  266. # [lodel2.datasources.annuaire_persons]
  267. # identifier = persons_web_api.example
  268. # ;
  269. # ; Then, in the editorial model you are able to use "main", "revues_write",
  270. # ; etc as datasource
  271. # ;
  272. # ; Here comes the datasources declarations
  273. # [lodel2.datasource.mysql.Core]
  274. # host = db.core.labocleo.org
  275. # db_name = core
  276. # username = foo
  277. # password = bar
  278. # ;
  279. # [lodel2.datasource.mysql.Revues]
  280. # host = revues.org
  281. # db_name = RO
  282. # username = foo
  283. # password = bar
  284. # ;
  285. # [lodel2.datasource.persons_web_api.example]
  286. # host = foo.bar
  287. # username = cleo
  288. #</pre>