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

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