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

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