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.

plugins.py 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  1. #
  2. # This file is part of Lodel 2 (https://github.com/OpenEdition)
  3. #
  4. # Copyright (C) 2015-2017 Cléo UMS-3287
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU Affero General Public License as published
  8. # by the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU Affero General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Affero General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. # @package lodel.plugin.plugins
  20. import sys
  21. import os.path
  22. import importlib
  23. import copy
  24. import json
  25. from importlib.machinery import SourceFileLoader
  26. from lodel.context import LodelContext
  27. LodelContext.expose_modules(globals(), {
  28. 'lodel.logger': 'logger',
  29. 'lodel.settings.utils': ['SettingsError'],
  30. 'lodel.plugin.hooks': ['LodelHook'],
  31. 'lodel.plugin.exceptions': ['PluginError', 'PluginVersionError',
  32. 'PluginTypeError', 'LodelScriptError', 'DatasourcePluginError'],
  33. 'lodel.exceptions': ['LodelException', 'LodelExceptions',
  34. 'LodelFatalError', 'DataNoneValid', 'FieldValidationError']})
  35. ##  @package lodel.plugins Lodel2 plugins management
  36. #@ingroup lodel2_plugins
  37. #
  38. # Lodel2 plugins are stored in directories
  39. # A typical lodel2 plugin directory structure looks like :
  40. # - {{__init__.py}}} containing informations like full_name, authors, licence etc.
  41. # - main.py containing hooks registration etc
  42. # - confspec.py containing a configuration specification dictionary named CONFSPEC
  43. #
  44. # All plugins are expected to be found in the lodel package (lodel.plugins)
  45. #
  46. # @defgroup plugin_init_specs Plugins __init__.py specifications
  47. #@ingroup lodel2_plugins
  48. #@{
  49. ## @brief The package in which we will load plugins modules
  50. VIRTUAL_PACKAGE_NAME = 'lodel.plugins'
  51. ## @brief The temporary package to import python sources
  52. VIRTUAL_TEMP_PACKAGE_NAME = 'lodel.plugin_tmp'
  53. ## @brief Plugin init filename
  54. INIT_FILENAME = '__init__.py' # Loaded with settings
  55. ## @brief Name of the variable containing the plugin name
  56. PLUGIN_NAME_VARNAME = '__plugin_name__'
  57. ## @brief Name of the variable containing the plugin type
  58. PLUGIN_TYPE_VARNAME = '__plugin_type__'
  59. ## @brief Name of the variable containing the plugin version
  60. PLUGIN_VERSION_VARNAME = '__version__'
  61. ## @brief Name of the variable containing the confpsec filename
  62. CONFSPEC_FILENAME_VARNAME = '__confspec__'
  63. ## @brief Name of the variable containing the confspecs
  64. CONFSPEC_VARNAME = 'CONFSPEC'
  65. ## @brief Name of the variable containing the loader filename
  66. LOADER_FILENAME_VARNAME = '__loader__'
  67. ## @brief Name of the variable containing the plugin dependencies
  68. PLUGIN_DEPS_VARNAME = '__plugin_deps__'
  69. ## @brief Name of the optional activate method
  70. ACTIVATE_METHOD_NAME = '_activate'
  71. ## @brief Default & failover value for plugins path list
  72. PLUGINS_PATH = os.path.join(LodelContext.context_dir(), 'plugins')
  73. ## @brief List storing the mandatory variables expected in a plugin __init__.py
  74. # file
  75. MANDATORY_VARNAMES = [PLUGIN_NAME_VARNAME, LOADER_FILENAME_VARNAME,
  76. PLUGIN_VERSION_VARNAME]
  77. ## @brief Default plugin type
  78. DEFAULT_PLUGIN_TYPE = 'extension' # Value found in lodel/plugin/extensions.py::Extensions._type_conf_name
  79. # @}
  80. ## @brief Describe and handle version numbers
  81. #@ingroup lodel2_plugins
  82. #
  83. # A version number can be represented by a string like MAJOR.MINOR.PATCH
  84. # or by a list [MAJOR, MINOR,PATCH ].
  85. #
  86. # The class implements basics comparison function and string repr
  87. class PluginVersion(object):
  88. PROPERTY_LIST = ['major', 'minor', 'revision']
  89. ## @brief Version constructor
  90. #@param *args : You can either give a str that will be splitted on . or you
  91. # can give a iterable containing 3 integers or 3 arguments representing
  92. # major, minor and revision version
  93. def __init__(self, *args):
  94. self.__version = [0 for _ in range(3)]
  95. if len(args) == 1:
  96. arg = args[0]
  97. if isinstance(arg, str):
  98. # Casting from string to version numbers
  99. spl = arg.split('.')
  100. invalid = False
  101. if len(spl) > 3:
  102. raise PluginVersionError("The string '%s' is not a valid plugin \
  103. version number" % arg)
  104. if len(spl) < 3:
  105. spl += [0 for _ in range(3 - len(spl))]
  106. try:
  107. self.__version = [int(s) for s in spl]
  108. except (ValueError, TypeError):
  109. raise PluginVersionError("The string '%s' is not a valid lodel2 \
  110. plugin version number" % arg)
  111. else:
  112. try:
  113. if len(arg) >= 1:
  114. if len(arg) > 3:
  115. raise PluginVersionError("Expected maximum 3 value to \
  116. create a plugin version number but found '%s' as argument" % arg)
  117. for i, v in enumerate(arg):
  118. self.__version[i] = int(arg[i])
  119. except (TypeError, ValueError):
  120. raise PluginVersionError("Unable to convert argument into plugin \
  121. version number" % arg)
  122. elif len(args) > 3:
  123. raise PluginError("Expected between 1 and 3 positional arguments \
  124. but %d arguments found" % len(args))
  125. else:
  126. for i, v in enumerate(args):
  127. self.__version[i] = int(v)
  128. # Checks that version numbering is correct
  129. for v in self.__version:
  130. if v < 0:
  131. raise PluginVersionError("No negative version number allowed !")
  132. ## @brief Property to access major version number
  133. @property
  134. def major(self):
  135. return self.__version[0]
  136. ## @brief Property to access minor version number
  137. @property
  138. def minor(self):
  139. return self.__version[1]
  140. ## @brief Property to access patch version number
  141. @property
  142. def revision(self):
  143. return self.__version[2]
  144. ## @brief Check and prepare comparison argument
  145. #@return A PluginVersion instance
  146. #@throw PluginError if invalid argument provided
  147. def __cmp_check(self, other):
  148. if not isinstance(other, PluginVersion):
  149. try:
  150. if len(other) <= 3 and len(other) > 0:
  151. return PluginVersion(other)
  152. except TypeError:
  153. raise PluginError("Cannot compare argument '%s' with \
  154. a PluginVersion instance" % other)
  155. return other
  156. ## @brief Allow accessing to version parts using integer index
  157. #@param key int : index
  158. #@return major for key == 0, minor for key == 1, revision for key == 2
  159. def __getitem__(self, key):
  160. try:
  161. key = int(key)
  162. except (ValueError, TypeError):
  163. raise ValueError("Expected an int as key")
  164. if key < 0 or key > 2:
  165. raise ValueError("Key is expected to be in [0..2]")
  166. return self.__version[key]
  167. def __lt__(self, other):
  168. for i in range(3):
  169. if self[i] < other[i]:
  170. return True
  171. elif self[i] > other[i]:
  172. return False
  173. return False
  174. def __eq__(self, other):
  175. for i in range(3):
  176. if self[i] != other[i]:
  177. return False
  178. return True
  179. def __gt__(self, other):
  180. for i in range(3):
  181. if self[i] > other[i]:
  182. return True
  183. elif self[i] < other[i]:
  184. return False
  185. return False
  186. def __le__(self, other):
  187. return self < other or self == other
  188. def __ne__(self, other):
  189. return not(self == other)
  190. def __ge__(self, other):
  191. return self > other or self == other
  192. def __str__(self):
  193. return '%d.%d.%d' % tuple(self.__version)
  194. def __repr__(self):
  195. return "{'major': %d, 'minor': %d, 'revision': %d}" % tuple(
  196. self.__version)
  197. ## @brief Plugin metaclass that allows to "catch" child class declaration
  198. #@ingroup lodel2_plugins
  199. #
  200. # Automatic script registration on child class declaration
  201. class MetaPlugType(type):
  202. ## @brief Dict storing all plugin types
  203. #
  204. # key is the _type_conf_name and value is the class
  205. _all_ptypes = dict()
  206. ## @brief type constructor reimplementation
  207. def __init__(self, name, bases, attrs):
  208. # Here we can store all child classes of Plugin
  209. super().__init__(name, bases, attrs)
  210. if len(bases) == 1 and bases[0] == object:
  211. return
  212. # Regitering a new plugin type
  213. MetaPlugType._all_ptypes[self._type_conf_name] = self
  214. ## @brief Accessor to the list of plugin types
  215. #@return A copy of _all_ptypes attribute (a dict with typename as key
  216. # and the class as value)
  217. @classmethod
  218. def all_types(cls):
  219. return copy.copy(cls._all_ptypes)
  220. ## @brief Accessor to the list of plugin names
  221. #@return a list of all plugin names
  222. @classmethod
  223. def all_ptype_names(cls):
  224. return list(cls._all_ptypes.keys())
  225. ## @brief Given a plugin type name returns a Plugin child class
  226. #@param ptype_name str : a plugin type name
  227. #@return A Plugin child class
  228. #@throw PluginError if ptype_name is not an exsiting plugin type name
  229. @classmethod
  230. def type_from_name(cls, ptype_name):
  231. if ptype_name not in cls._all_ptypes:
  232. raise PluginError("Unknown plugin type '%s'" % ptype_name)
  233. return cls._all_ptypes[ptype_name]
  234. ## @brief Call the clear classmethod on each child classes
  235. @classmethod
  236. def clear_cls(cls):
  237. for pcls in cls._all_ptypes.values():
  238. pcls.clear_cls()
  239. ## @brief Handle plugins
  240. #@ingroup lodel2_plugins
  241. #
  242. # An instance represent a loaded plugin. Class methods allow to load/preload
  243. # plugins.
  244. #
  245. # Typicall Plugins load sequence is :
  246. # 1. Settings call start method to instanciate all plugins found in confs
  247. # 2. Settings fetch all confspecs
  248. # 3. the loader call load_all to register hooks etc
  249. class Plugin(object, metaclass=MetaPlugType):
  250. ## @brief Stores Plugin instances indexed by name
  251. _plugin_instances = dict()
  252. ## @brief Attribute used by load_all and load methods to detect circular
  253. # dependencies
  254. _load_called = []
  255. ## @brief Attribute that stores plugins list from discover cache file
  256. _plugin_list = None
  257. #@brief Designed to store, in child classes, the confspec indicating \
  258. # where plugin list is stored
  259. _plist_confspecs = None
  260. ## @brief The name of the plugin type in the confguration
  261. #
  262. # None in abstract classes and implemented by child classes
  263. _type_conf_name = None
  264. ## @brief Stores virtual modules uniq key
  265. #@note When testing if a dir contains a plugin, if we reimport the __init__
  266. # in a module with the same name, all non existing value (plugin_type for
  267. # example) are replaced by previous plugin values
  268. _mod_cnt = 0
  269. ## @brief Plugin class constructor
  270. #
  271. # Called by setting in early stage of lodel2 boot sequence using classmethod
  272. # register
  273. #
  274. # @param plugin_name str : plugin name
  275. # @throw PluginError
  276. def __init__(self, plugin_name):
  277. ## @brief The plugin name
  278. self.name = plugin_name
  279. ## @brief The plugin package path
  280. self.path = self.plugin_path(plugin_name)
  281. ## @brief Stores the plugin module
  282. self.module = None
  283. ## @brief Stores the plugin loader module
  284. self.__loader_module = None
  285. ## @brief The plugin confspecs
  286. self.__confspecs = dict()
  287. ## @brief Boolean flag telling if the plugin is loaded or not
  288. self.loaded = False
  289. # Importing __init__.py infos in it
  290. plugin_module = self.module_name()
  291. self.module = LodelContext.module(plugin_module)
  292. # loading confspecs
  293. try:
  294. # Loading confspec directly from __init__.py
  295. self.__confspecs = getattr(self.module, CONFSPEC_VARNAME)
  296. except AttributeError:
  297. # Loading file in __confspec__ var in __init__.py
  298. try:
  299. module = self._import_from_init_var(CONFSPEC_FILENAME_VARNAME)
  300. except AttributeError:
  301. msg = "Malformed plugin {plugin} . No {varname} not {filevar} found in __init__.py"
  302. msg = msg.format(
  303. plugin=self.name,
  304. varname=CONFSPEC_VARNAME,
  305. filevar=CONFSPEC_FILENAME_VARNAME)
  306. raise PluginError(msg)
  307. except ImportError as e:
  308. msg = "Broken plugin {plugin} : {expt}"
  309. msg = msg.format(
  310. plugin=self.name,
  311. expt=str(e))
  312. raise PluginError(msg)
  313. except Exception as e:
  314. msg = "Plugin '%s' :" + str(e)
  315. raise e.__class__(msg)
  316. try:
  317. # loading confpsecs from file
  318. self.__confspecs = getattr(module, CONFSPEC_VARNAME)
  319. except AttributeError:
  320. msg = "Broken plugin. {varname} not found in '{filename}'"
  321. msg = msg.format(
  322. varname=CONFSPEC_VARNAME,
  323. filename=confspec_filename)
  324. raise PluginError(msg)
  325. # loading plugin version
  326. try:
  327. # this try block should be useless. The existance of
  328. # PLUGIN_VERSION_VARNAME in init file is mandatory
  329. self.__version = getattr(self.module, PLUGIN_VERSION_VARNAME)
  330. except AttributeError:
  331. msg = "Error that should not append while loading plugin '%s': no \
  332. %s found in plugin init file. Malformed plugin"
  333. msg %= (plugin_name, PLUGIN_VERSION_VARNAME)
  334. raise LodelFatalError(msg)
  335. # Load plugin type
  336. try:
  337. self.__type = getattr(self.module, PLUGIN_TYPE_VARNAME)
  338. except AttributeError:
  339. self.__type = DEFAULT_PLUGIN_TYPE
  340. self.__type = str(self.__type).lower()
  341. if self.__type not in MetaPlugType.all_ptype_names():
  342. raise PluginError("Unknown plugin type '%s'" % self.__type)
  343. # Load plugin name from init file (just for checking)
  344. try:
  345. # this try block should be useless. The existance of
  346. # PLUGIN_NAME_VARNAME in init file is mandatory
  347. pname = getattr(self.module, PLUGIN_NAME_VARNAME)
  348. except AttributeError:
  349. msg = "Error that should not append : no %s found in plugin \
  350. init file. Malformed plugin"
  351. msg %= PLUGIN_NAME_VARNAME
  352. raise LodelFatalError(msg)
  353. if pname != plugin_name:
  354. msg = "Plugin's discover cache inconsistency detected ! Cached \
  355. name differ from the one found in plugin's init file"
  356. raise PluginError(msg)
  357. ## @brief Try to import a file from a variable in __init__.py
  358. #@param varname str : The variable name
  359. #@return loaded module
  360. #@throw AttributeError if varname not found
  361. #@throw ImportError if the file fails to be imported
  362. #@throw PluginError if the filename was not valid
  363. #@todo Some strange things append :
  364. # when loading modules in test self.module.__name__ does not contains
  365. # the package... but in prod cases the self.module.__name__ is
  366. # the module fullname... Just a reminder note to explain the dirty
  367. # if on self_modname
  368. def _import_from_init_var(self, varname):
  369. # Read varname
  370. try:
  371. filename = getattr(self.module, varname)
  372. except AttributeError:
  373. msg = "Malformed plugin {plugin}. No {varname} found in __init__.py"
  374. msg = msg.format(
  375. plugin=self.name,
  376. varname=LOADER_FILENAME_VARNAME)
  377. raise PluginError(msg)
  378. # Path are not allowed
  379. if filename != os.path.basename(filename):
  380. msg = "Invalid {varname} content : '{fname}' for plugin {name}"
  381. msg = msg.format(
  382. varname=varname,
  383. fname=filename,
  384. name=self.name)
  385. raise PluginError(msg)
  386. # See the todo
  387. if len(self.module.__name__.split('.')) == 1:
  388. self_modname = self.module.__package__
  389. else:
  390. self_modname = self.module.__name__
  391. # extract module name from filename
  392. base_mod = '.'.join(filename.split('.')[:-1])
  393. module_name = self_modname + "." + base_mod
  394. return importlib.import_module(module_name)
  395. ## @brief Return associated module name
  396. def module_name(self):
  397. path_array = self.path.split('/')
  398. if 'plugins' not in self.path:
  399. raise PluginError("Bad path for plugin %s : %s" % (
  400. self.name, self.path))
  401. return '.'.join(['lodel'] + path_array[path_array.index('plugins'):])
  402. ## @brief Check dependencies of plugin
  403. #@return A list of plugin name to be loaded before
  404. def check_deps(self):
  405. try:
  406. res = getattr(self.module, PLUGIN_DEPS_VARNAME)
  407. except AttributeError:
  408. return list()
  409. result = list()
  410. errors = list()
  411. for plugin_name in res:
  412. try:
  413. result.append(self.get(plugin_name))
  414. except PluginError:
  415. errors.append(plugin_name)
  416. if len(errors) > 0:
  417. raise PluginError("Bad dependencie for '%s' :" % self.name,
  418. ', '.join(errors))
  419. return result
  420. ## @brief Check if the plugin should be activated
  421. #
  422. # Try to fetch a function called @ref ACTIVATE_METHOD_NAME in __init__.py
  423. # of a plugin. If none found assert that the plugin can be loaded, else
  424. # the method is called. If it returns anything else that True, the plugin
  425. # is noted as not activable
  426. #
  427. # @note Maybe we have to exit everything if a plugin cannot be loaded...
  428. def activable(self):
  429. try:
  430. test_fun = getattr(self.module, ACTIVATE_METHOD_NAME)
  431. except AttributeError:
  432. msg = "No %s method found for plugin %s. Assuming plugin is ready to be loaded"
  433. msg %= (ACTIVATE_METHOD_NAME, self.name)
  434. logger.debug(msg)
  435. test_fun = lambda: True
  436. return test_fun()
  437. ## @brief Load a plugin
  438. #
  439. # Loading a plugin means importing a file. The filename is defined in the
  440. # plugin's __init__.py file in a LOADER_FILENAME_VARNAME variable.
  441. #
  442. # The loading process has to take care of other things :
  443. #- loading dependencies (other plugins)
  444. #- check that the plugin can be activated using Plugin.activate() method
  445. #- avoid circular dependencies infinite loop
  446. def _load(self):
  447. if self.loaded:
  448. return
  449. # Test that plugin "wants" to be activated
  450. activable = self.activable()
  451. if not(activable is True):
  452. msg = "Plugin %s is not activable : %s"
  453. msg %= (self.name, activable)
  454. raise PluginError(msg)
  455. # Circular dependencie detection
  456. if self.name in self._load_called:
  457. raise PluginError("Circular dependencie in Plugin detected. Abording")
  458. else:
  459. self._load_called.append(self.name)
  460. # Dependencie load
  461. for dependencie in self.check_deps():
  462. activable = dependencie.activable()
  463. if activable is True:
  464. dependencie._load()
  465. else:
  466. msg = "Plugin {plugin_name} not activable because it depends on plugin {dep_name} that is not activable : {reason}"
  467. msg = msg.format(
  468. plugin_name=self.name,
  469. dep_name=dependencie.name,
  470. reason=activable)
  471. # Loading the plugin
  472. try:
  473. self.__loader_module = self._import_from_init_var(LOADER_FILENAME_VARNAME)
  474. except PluginError as e:
  475. raise e
  476. except ImportError as e:
  477. msg = "Broken plugin {plugin} : {expt}"
  478. msg = msg.format(
  479. plugin=self.name,
  480. expt=str(e))
  481. raise PluginError(msg)
  482. logger.debug("Plugin '%s' loaded" % self.name)
  483. self.loaded = True
  484. ## @brief Returns the loader module
  485. #
  486. # Accessor for the __loader__ python module
  487. def loader_module(self):
  488. if not self.loaded:
  489. raise RuntimeError("Plugin %s not loaded yet." % self.name)
  490. return self.__loader_module
  491. def __str__(self):
  492. return "<LodelPlugin '%s' version %s>" % (self.name, self.__version)
  493. ## @brief Call load method on every pre-loaded plugins
  494. #
  495. # Called by loader to trigger hooks registration.
  496. # This method have to avoid circular dependencies infinite loops. For this
  497. # purpose a class attribute _load_called exists.
  498. # @throw PluginError
  499. @classmethod
  500. def load_all(cls):
  501. errors = dict()
  502. cls._load_called = []
  503. for name, plugin in cls._plugin_instances.items():
  504. try:
  505. plugin._load()
  506. except PluginError as e:
  507. errors[name] = e
  508. if len(errors) > 0:
  509. msg = "Errors while loading plugins :"
  510. for name, e in errors.items():
  511. msg += "\n\t%20s : %s" % (name, e)
  512. msg += "\n"
  513. raise PluginError(msg)
  514. LodelHook.call_hook(
  515. "lodel2_plugins_loaded", cls, cls._plugin_instances)
  516. # @return a copy of __confspecs attr
  517. @property
  518. def confspecs(self):
  519. return copy.copy(self.__confspecs)
  520. ## @brief Accessor to confspec indicating where we can find the plugin list
  521. #@note Abtract method implemented only for Plugin child classes
  522. # This attribute indicate where we fetch the plugin list.
  523. @classmethod
  524. def plist_confspecs(cls):
  525. if cls._plist_confspecs is None:
  526. raise LodelFatalError('Unitialized _plist_confspecs attribute for \
  527. %s' % cls.__name__)
  528. return copy.copy(cls._plist_confspecs)
  529. ## @brief Retrieves plugin list confspecs
  530. #
  531. # This method ask for each Plugin child class the confspecs specifying where
  532. # the wanted plugin list is stored. (For example DatasourcePlugin expect
  533. # that a list of ds plugin to load stored in lodel2 section, datasources key
  534. # etc...
  535. @classmethod
  536. def plugin_list_confspec(cls):
  537. LodelContext.expose_modules(globals(), {
  538. 'lodel.settings.validator': ['confspec_append']})
  539. res = dict()
  540. for pcls in cls.plugin_types():
  541. plcs = pcls.plist_confspec()
  542. confspec_append(res, plcs)
  543. return res
  544. ## @brief Register a new plugin
  545. #
  546. #@param plugin_name str : The plugin name
  547. #@return a Plugin instance
  548. #@throw PluginError
  549. @classmethod
  550. def register(cls, plugin_name):
  551. if plugin_name in cls._plugin_instances:
  552. msg = "Plugin allready registered with same name %s"
  553. msg %= plugin_name
  554. raise PluginError(msg)
  555. # Here we check that previous discover found a plugin with that name
  556. pdcache = cls.discover()
  557. if plugin_name not in pdcache:
  558. raise PluginError("No plugin named '%s' found" % plugin_name)
  559. ptype = pdcache[plugin_name]['type']
  560. pcls = MetaPlugType.type_from_name(ptype)
  561. plugin = pcls(plugin_name)
  562. cls._plugin_instances[plugin_name] = plugin
  563. logger.debug("Plugin %s available." % plugin)
  564. return plugin
  565. ## @brief Plugins instances accessor
  566. #
  567. #@param plugin_name str: The plugin name
  568. #@return a Plugin instance
  569. #@throw PluginError if plugin not found
  570. @classmethod
  571. def get(cls, plugin_name):
  572. try:
  573. return cls._plugin_instances[plugin_name]
  574. except KeyError:
  575. msg = "No plugin named '%s' loaded"
  576. msg %= plugin_name
  577. raise PluginError(msg)
  578. ## @brief Given a plugin name returns the plugin path
  579. # @param plugin_name str : The plugin name
  580. # @return the plugin directory path
  581. @classmethod
  582. def plugin_path(cls, plugin_name):
  583. plist = cls.plugin_list()
  584. if plugin_name not in plist:
  585. raise PluginError("No plugin named '%s' found" % plugin_name)
  586. try:
  587. return cls.get(plugin_name).path
  588. except PluginError:
  589. pass
  590. return plist[plugin_name]['path']
  591. ## @brief Return the plugin module name
  592. #
  593. # This module name is the "virtual" module where we imported the plugin.
  594. #
  595. # Typically composed like VIRTUAL_PACKAGE_NAME.PLUGIN_NAME
  596. #@warning Brokes subdire feature
  597. #@param plugin_name str : a plugin name
  598. #@return a string representing a module name
  599. #@todo fix broken subdir capabilitie ( @see module_name() )
  600. #@todo check if used, else delete it
  601. @classmethod
  602. def plugin_module_name(cls, plugin_name):
  603. return "%s.%s" % (VIRTUAL_PACKAGE_NAME, plugin_name)
  604. ## @brief Start the Plugin class
  605. #
  606. # Called by Settings.__bootstrap()
  607. #
  608. # This method load path and preload plugins
  609. @classmethod
  610. def start(cls, plugins):
  611. for plugin_name in plugins:
  612. cls.register(plugin_name)
  613. ## @brief Attempt to "restart" the Plugin class
  614. @classmethod
  615. def clear(cls):
  616. if cls._plugin_instances != dict():
  617. cls._plugin_instances = dict()
  618. if cls._load_called != []:
  619. cls._load_called = []
  620. MetaPlugType.clear_cls()
  621. ## @brief Designed to be implemented by child classes
  622. @classmethod
  623. def clear_cls(cls):
  624. pass
  625. ## @brief Reccursively walk throught paths to find plugin, then stores
  626. # found plugin in a static var
  627. #
  628. # Found plugins are stored in cls._plugin_list
  629. #@note The discover is run only if no cached datas are found
  630. #@return a list of dict with plugin infos { see @ref _discover }
  631. #@todo add max_depth and no symlink following feature
  632. @classmethod
  633. def discover(cls):
  634. if cls._plugin_list is not None:
  635. return cls._plugin_list
  636. logger.info("Running plugin discover")
  637. tmp_res = cls._discover(PLUGINS_PATH)
  638. # Formating and dedoubloning result
  639. result = dict()
  640. for pinfos in tmp_res:
  641. pname = pinfos['name']
  642. if (pname in result
  643. and pinfos['version'] > result[pname]['version'])\
  644. or pname not in result:
  645. result[pname] = pinfos
  646. else:
  647. # dropped
  648. pass
  649. cls._plugin_list = result
  650. return result
  651. ## @brief Return discover result
  652. #@param refresh bool : if true invalidate all plugin list cache
  653. #@note If discover cache file not found run discover first
  654. #@note if refresh is set to True discover MUST have been run at least
  655. # one time. In fact refresh action load the list of path to explore
  656. # from the plugin's discover cache
  657. @classmethod
  658. def plugin_list(cls, refresh=False):
  659. return cls._plugin_list
  660. ## @brief Return a list of child Class Plugin
  661. @classmethod
  662. def plugin_types(cls):
  663. return MetaPlugType.all_types()
  664. ## @brief Check if a directory is a plugin module
  665. #@param path str : path to check
  666. #@param assert_in_package bool : if False didn't check that path is
  667. # a subdir of PLUGINS_PATH
  668. #@return a dict with name, version and path if path is a plugin module, else False
  669. @classmethod
  670. def dir_is_plugin(cls, path, assert_in_package=True):
  671. log_msg = "%s is not a plugin directory because : " % path
  672. if assert_in_package:
  673. # Check that path is a subdir of PLUGINS_PATH
  674. abspath = os.path.abspath(path)
  675. if not abspath.startswith(os.path.abspath(PLUGINS_PATH)):
  676. raise PluginError(
  677. "%s is not a subdir of %s" % log_msg, PLUGINS_PATH)
  678. # Checks that path exists
  679. if not os.path.isdir(path):
  680. raise ValueError(
  681. "Expected path to be a directory, but '%s' found" % path)
  682. # Checks that path contains plugin's init file
  683. initfile = os.path.join(path, INIT_FILENAME)
  684. if not os.path.isfile(initfile):
  685. log_msg += "'%s' not found" % (INIT_FILENAME)
  686. logger.debug(log_msg)
  687. return False
  688. # Importing plugin's init file to check contained datas
  689. try:
  690. initmod, modname = cls.import_init(path)
  691. except PluginError as e:
  692. log_msg += "unable to load '%s'. Exception raised : %s"
  693. log_msg %= (INIT_FILENAME, e)
  694. logger.debug(log_msg)
  695. return False
  696. # Checking mandatory init module variables
  697. for attr_name in MANDATORY_VARNAMES:
  698. if not hasattr(initmod, attr_name):
  699. log_msg += " mandatory variable '%s' not found in '%s'"
  700. log_msg %= (attr_name, INIT_FILENAME)
  701. logger.debug(log_msg)
  702. return False
  703. # Fetching plugin's version
  704. try:
  705. pversion = getattr(initmod, PLUGIN_VERSION_VARNAME)
  706. except (NameError, AttributeError) as e:
  707. msg = "Invalid plugin version found in %s : %s"
  708. msg %= (path, e)
  709. raise PluginError(msg)
  710. # Fetching plugin's type
  711. try:
  712. ptype = getattr(initmod, PLUGIN_TYPE_VARNAME)
  713. except (NameError, AttributeError) as e:
  714. ptype = DEFAULT_PLUGIN_TYPE
  715. pname = getattr(initmod, PLUGIN_NAME_VARNAME)
  716. return {'name': pname,
  717. 'version': PluginVersion(pversion),
  718. 'path': path,
  719. 'type': ptype}
  720. ## @brief Import init file from a plugin path
  721. #@param path str : Directory path
  722. #@return a tuple (init_module, module_name)
  723. #@todo replace by LodelContext usage !!! (not mandatory, this fun
  724. # is only used in plugin discover method)
  725. @classmethod
  726. def import_init(cls, path):
  727. cls._mod_cnt += 1 # in order to ensure module name unicity
  728. init_source = os.path.join(path, INIT_FILENAME)
  729. temp_module = '%s.%s.%s%d' % (
  730. VIRTUAL_TEMP_PACKAGE_NAME, os.path.basename(os.path.dirname(path)),
  731. 'test_init', cls._mod_cnt)
  732. try:
  733. loader = SourceFileLoader(temp_module, init_source)
  734. except (ImportError, FileNotFoundError) as e:
  735. raise PluginError("Unable to import init file from '%s' : %s" % (
  736. temp_module, e))
  737. try:
  738. res_module = loader.load_module()
  739. except Exception as e:
  740. raise PluginError("Unable to import initfile : %s" % e)
  741. return (res_module, temp_module)
  742. @classmethod
  743. def debug_wrapper(cls, updglob=None):
  744. if updglob is not None:
  745. for k, v in updglob.items():
  746. globals()[k] = v
  747. print(logger)
  748. ## @brief Reccursiv plugin discover given a path
  749. #@param path str : the path to walk through
  750. #@return A dict with plugin_name as key and {'path':..., 'version':...} as value
  751. @classmethod
  752. def _discover(cls, path):
  753. # Ensure plugins symlink creation
  754. LodelContext.expose_modules(globals(), {
  755. 'lodel.plugins': 'plugins'})
  756. res = []
  757. to_explore = [path]
  758. while len(to_explore) > 0:
  759. cur_path = to_explore.pop()
  760. for f in os.listdir(cur_path):
  761. f_path = os.path.join(cur_path, f)
  762. if f not in ['.', '..'] and os.path.isdir(f_path):
  763. # Check if it is a plugin directory
  764. test_result = cls.dir_is_plugin(f_path)
  765. if not (test_result is False):
  766. logger.info("Plugin '%s' found in %s" % (
  767. test_result['name'], f_path))
  768. res.append(test_result)
  769. else:
  770. to_explore.append(f_path)
  771. return res
  772. def debug_wrapper_mod():
  773. print("MOD : ", logger)
  774. ## @brief Decorator class designed to allow plugins to add custom methods
  775. # to LeObject childs (dyncode objects)
  776. #@ingroup lodel2_plugins
  777. #
  778. class CustomMethod(object):
  779. ## @brief Stores registered custom methods
  780. #
  781. # Key = LeObject child class name
  782. # Value = CustomMethod instance
  783. _custom_methods = dict()
  784. INSTANCE_METHOD = 0
  785. CLASS_METHOD = 1
  786. STATIC_METHOD = 2
  787. ## @brief Decorator constructor
  788. #@param component_name str : the name of the component to enhance
  789. #@param method_name str : the name of the method to inject (if None given
  790. #@param method_type int : take value in one of
  791. # CustomMethod::INSTANCE_METHOD CustomMethod::CLASS_METHOD or
  792. # CustomMethod::STATIC_METHOD
  793. # use the function name
  794. def __init__(self, component_name, method_name=None, method_type=0):
  795. ## @brief The targeted LeObject child class
  796. self._comp_name = component_name
  797. ## @brief The method name
  798. self._method_name = method_name
  799. ## @brief The function (that will be the injected method)
  800. self._fun = None
  801. ## @brief Stores the type of method (instance, class or static)
  802. self._type = int(method_type)
  803. if self._type not in (self.INSTANCE_METHOD, self.CLASS_METHOD,
  804. self.STATIC_METHOD):
  805. raise ValueError("Excepted value for method_type was one of \
  806. CustomMethod::INSTANCE_METHOD CustomMethod::CLASS_METHOD or \
  807. CustomMethod::STATIC_METHOD, but got %s" % self._type)
  808. ## @brief called just after __init__
  809. #@param fun function : the decorated function
  810. def __call__(self, fun):
  811. if self._method_name is None:
  812. self._method_name = fun.__name__
  813. if self._comp_name not in self._custom_methods:
  814. self._custom_methods[self._comp_name] = list()
  815. if self._method_name in [scm._method_name for scm in self._custom_methods[self._comp_name]]:
  816. raise RuntimeError("A method named %s allready registered by \
  817. another plugin : %s" % (
  818. self._method_name,
  819. self._custom_methods[self._comp_name].__module__))
  820. self._fun = fun
  821. self._custom_methods[self._comp_name].append(self)
  822. ## @brief Textual representation
  823. #@return textual representation of the CustomMethod instance
  824. def __repr__(self):
  825. res = "<CustomMethod name={method_name} target={classname} \
  826. source={module_name}.{fun_name}>"
  827. return res.format(
  828. method_name=self._method_name,
  829. classname=self._comp_name,
  830. module_name=self._fun.__module__,
  831. fun_name=self._fun.__name__)
  832. ## @brief Return a well formed method
  833. #
  834. #@note the type of method depends on the _type attribute
  835. #@return a method directly injectable in the target class
  836. def __get_method(self):
  837. if self._type == self.INSTANCE_METHOD:
  838. def custom__get__(self, obj, objtype=None):
  839. return types.MethodType(self, obj, objtype)
  840. setattr(self._fun, '__get__', custom__get__)
  841. return self._fun
  842. elif self._type == self.CLASS_METHOD:
  843. return classmethod(self._fun)
  844. elif self._type == self.STATIC_METHOD:
  845. return staticmethod(self._fun)
  846. else:
  847. raise RuntimeError("Attribute _type is not one of \
  848. CustomMethod::INSTANCE_METHOD CustomMethod::CLASS_METHOD \
  849. CustomMethod::STATIC_METHOD")
  850. ## @brief Handle custom method dynamic injection in LeAPI dyncode
  851. #
  852. # Called by lodel2_dyncode_loaded hook defined at
  853. # lodel.plugin.core_hooks.lodel2_plugin_custom_methods()
  854. #
  855. #@param cls
  856. #@param dynclasses LeObject child classes : List of dynamically generated
  857. # LeObject child classes
  858. @classmethod
  859. def set_registered(cls, dynclasses):
  860. from lodel import logger
  861. dyn_cls_dict = {dc.__name__: dc for dc in dynclasses}
  862. for cls_name, custom_methods in cls._custom_methods.items():
  863. for custom_method in custom_methods:
  864. if cls_name not in dyn_cls_dict:
  865. logger.error("Custom method %s adding fails : No dynamic \
  866. LeAPI objects named %s." % (custom_method, cls_name))
  867. elif custom_method._method_name in dir(dyn_cls_dict[cls_name]):
  868. logger.warning("Overriding existing method '%s' on target \
  869. with %s" % (custom_method._method_name, custom_method))
  870. else:
  871. setattr(
  872. dyn_cls_dict[cls_name],
  873. custom_method._method_name,
  874. custom_method.__get_method())
  875. logger.debug(
  876. "Custom method %s added to target" % custom_method)
  877. def wrapper_debug_fun():
  878. print(logger)