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

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