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

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