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.

context.py 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. import importlib
  2. import importlib.machinery
  3. import importlib.abc
  4. import sys
  5. import types
  6. import os
  7. import os.path
  8. import re
  9. import copy
  10. import warnings #For the moment no way to use the logger in this file (I guess)
  11. #A try to avoid circular dependencies problems
  12. if 'lodel' not in sys.modules:
  13. import lodel
  14. else:
  15. globals()['lodel'] = sys.modules['lodel']
  16. if 'lodelsites' in sys.modules:
  17. #This should be true since LodelContext init method is called
  18. #for a MULTISITE context handling
  19. globals()['lodelsites'] = sys.modules['lodelsites']
  20. from lodel import buildconf
  21. ##@brief Name of the package that will contains all the virtual lodel
  22. #packages
  23. CTX_PKG = "lodelsites"
  24. ##@brief Reserved context name for loading steps
  25. #@note This context is designed to be set at loading time, allowing lodel2
  26. #main process to use lodel packages
  27. LOAD_CTX = "__loader__"
  28. #
  29. # Following exception classes are written here to avoid circular dependencies
  30. # problems.
  31. #
  32. ##@brief Designed to be raised by the context manager
  33. class ContextError(Exception):
  34. pass
  35. ##@brief Raised when an error concerning context modules occurs
  36. class ContextModuleError(ContextError):
  37. pass
  38. def dir_for_context(site_identifier):
  39. return os.path.join(lodelsites.__path__[0], site_identifier)
  40. ##@brief Designed to permit dynamic packages creation from the lodel package
  41. #
  42. #The class is added in first position in the sys.metapath variable. Doing this
  43. #we override the earlier steps of the import mechanism.
  44. #
  45. #When called the find_spec method determine wether the imported module is
  46. #a part of a virtual lodel package, else it returns None and the standart
  47. #import mechanism go further.
  48. #If it's a submodule of a virtual lodel package we create a symlink
  49. #to represent the lodel package os the FS and then we make python import
  50. #files from the symlink.
  51. #
  52. #
  53. #@note Current implementation is far from perfection. In fact no deletion
  54. #mechanisms is written and the virtual package cannot be a subpackage of
  55. #the lodel package for the moment...
  56. #@note Current implementation asserts that all plugins are in CWD
  57. #a symlink will be done to create a copy of the plugins folder in
  58. #lodelsites/SITENAME/ folder
  59. class LodelMetaPathFinder(importlib.abc.MetaPathFinder):
  60. ##@brief implements the find_spec method of MetaPathFinder
  61. #
  62. #@param fullname str : module fullname
  63. #@param path str : with be the value of __path__ of the parent package
  64. #@param target module : is a module object that the finder may use to
  65. #make a more educated guess about what spec to return
  66. #@see https://docs.python.org/3/library/importlib.html#importlib.abc.MetaPathFinder
  67. def find_spec(fullname, path, target = None):
  68. if fullname.startswith(CTX_PKG):
  69. spl = fullname.split('.')
  70. site_identifier = spl[1]
  71. #creating a symlink to represent the lodel site package
  72. mod_path = dir_for_context(site_identifier)
  73. if not os.path.exists(mod_path):
  74. os.symlink(lodel.__path__[0], mod_path, True)
  75. #Cache invalidation after we "created" the new package
  76. #importlib.invalidate_caches()
  77. return None
  78. ##@brief Class designed to handle context switching and virtual module
  79. #exposure
  80. #
  81. #The main entrypoint of this class is the expose_module method. A kind of
  82. #equivalent of the various import X [as Y], from X import Y [as Z] etc.
  83. #existing in Python.
  84. #The expose_module method add a preffix to the module fullname in order
  85. #to make it reconizable by the LodelMetaPathfinder::find_spec() method.
  86. #All module names are translated before import. The preffix is set at
  87. #__init__ call in __pkg_name. The resulting name is __pkg_name + fullname
  88. #
  89. #@par examples
  90. #When asking for lodel.leapi.leobject :
  91. #- in MONOSITE resulting module will be lodel.leapi.leobject
  92. #- in MULTISITE resulting module name will be
  93. #lodelsites.SITE_ID.lodel.leapi.leobject
  94. #
  95. #The lodelsites package will be a subdir of buildconf.MULTISITE_CONTEXTDIR
  96. #that will be itself added to sys.path in order to be able to import
  97. #lodelsites
  98. #
  99. #This class is also responsible to expose leapi_dyncode module.
  100. #
  101. #@note a dedicated context named LOAD_CTX is used as context for the
  102. #loading process
  103. class LodelContext(object):
  104. ##@brief FLag telling that the context handler is in single context mode
  105. MONOSITE = 1
  106. ##@brief Flag telling that the context manager is in multi context mode
  107. MULTISITE = 2
  108. ##@brief Static property storing current context name
  109. _current = None
  110. ##@brief Stores the context type (single or multiple)
  111. _type = None
  112. ##@brief Stores the contexts
  113. _contexts = None
  114. ##@brief Flag indicating if the classe is initialized
  115. __initialized = False
  116. ##@brief Create a new context
  117. #@see LodelContext.new()
  118. def __init__(self, site_id, instance_path = None):
  119. if site_id is None and self.multisite():
  120. site_id = LOAD_CTX
  121. if self.multisite() and site_id is not LOAD_CTX:
  122. with LodelContext.with_context(None) as ctx:
  123. ctx.expose_modules(globals(), {'lodel.logger': 'logger'})
  124. logger.info("New context instanciation named '%s'" % site_id)
  125. if site_id is None:
  126. self.__id = "MONOSITE"
  127. #Monosite instanciation
  128. if self.multisite():
  129. raise ContextError("Cannot instanciate a context with \
  130. site_id set to None when we are in MULTISITE beahavior")
  131. else:
  132. #More verification can be done here (singleton specs ? )
  133. self.__class__._current = self.__class__._contexts = self
  134. self.__pkg_name = ''
  135. self.__package = lodel
  136. self.__instance_path = os.getcwd()
  137. return
  138. else:
  139. #Multisite instanciation
  140. if not self.multisite():
  141. raise ContextError("Cannot instanciate a context with a \
  142. site_id when we are in MONOSITE beahvior")
  143. if not self.validate_identifier(site_id):
  144. raise ContextError("Given context name is not a valide identifier \
  145. : '%s'" % site_id)
  146. if site_id in self.__class__._contexts:
  147. raise ContextError(
  148. "A context named '%s' allready exists." % site_id)
  149. self.__id = site_id
  150. self.__pkg_name = '%s.%s.%s.' % (CTX_PKG, site_id)
  151. if instance_path is None:
  152. """
  153. raise ContextError("Cannot create a context without an \
  154. instance path")
  155. """
  156. warnings.warn("It can be a really BAD idea to create a \
  157. a context without a path......")
  158. self.__instance_path = None
  159. else:
  160. self.__instance_path = os.path.realpath(instance_path)
  161. #Importing the site package to trigger its creation
  162. self.__package = importlib.import_module(self.__pkg_name)
  163. self.__class__._contexts[site_id] = self
  164. #Designed to be use by with statement
  165. self.__previous_ctx = None
  166. ##@brief Expose a module from the context
  167. #@param globs globals : globals where we have to expose the module
  168. #@param spec tuple : first item is module name, second is the alias
  169. def expose(self, globs, spec):
  170. if len(spec) != 2:
  171. raise ContextError("Invalid argument given. Expected a tuple of \
  172. length == 2 but got : %s" % spec)
  173. module_fullname, exposure_spec = spec
  174. module_fullname = self._translate(module_fullname)
  175. if isinstance(exposure_spec, str):
  176. self._expose_module(globs, module_fullname, exposure_spec)
  177. else:
  178. self._expose_objects(globs, module_fullname, exposure_spec)
  179. ##@brief Return a module from current context
  180. def get_module(self, fullname):
  181. fullname = self._translate(fullname)
  182. module = importlib.import_module(fullname)
  183. return module
  184. ##@brief Delete a site's context
  185. #@param site_id str : the site's name to remove the context
  186. def remove(cls, site_id):
  187. if site_id is None:
  188. if cls._type == cls.MULTISITE:
  189. raise ContextError("Cannot have a context with \
  190. site_id set to None when we are in MULTISITE beahavior")
  191. del cls._contexts
  192. else:
  193. if cls._type == cls.MULTISITE:
  194. if site_id in cls._contexts:
  195. del cls._contexts[site_id]
  196. else:
  197. raise ContextError("No site %s exist" % site_id)
  198. else:
  199. raise ContextError("Cannot have a context with \
  200. site_id set when we are in MONOSITE beahavior")
  201. ##@return True if the class is in MULTISITE mode
  202. @classmethod
  203. def multisite(cls):
  204. return cls._type == cls.MULTISITE
  205. ##@brief helper class to use LodeContext with with statement
  206. #@note alias to get method
  207. #@note maybe useless
  208. #@todo delete me
  209. @classmethod
  210. def with_context(cls, target_ctx_id):
  211. return cls.get(target_ctx_id)
  212. ##@brief Set a context as active
  213. #
  214. #This method handle the context switching operations. Some static
  215. #attributes are set at this step.
  216. #@note if not in LOAD_CTX a sys.path update is done
  217. #@warning Inconsistency with lodelsites_datasource, we build again the
  218. #site context dir path using site_id. This information should come
  219. #from only one source
  220. #@param site_id str : site identifier (identify a context)
  221. #@todo unify the generation of the site specific context dir path
  222. @classmethod
  223. def set(cls, site_id):
  224. if cls._type == cls.MONOSITE:
  225. raise ContextError("Context cannot be set in MONOSITE beahvior")
  226. site_id = LOAD_CTX if site_id is None else site_id
  227. if not cls.validate_identifier(site_id):
  228. raise ContextError("Given context name is not a valide identifier \
  229. : '%s'" % site_id)
  230. if site_id not in cls._contexts:
  231. raise ContextError("No context named '%s' found." % site_id)
  232. wanted_ctx = cls._contexts[site_id]
  233. if hasattr(wanted_ctx, '__instance_path'):
  234. os.chdir(self.__instance_path) #May cause problems
  235. cls._current = wanted_ctx
  236. return cls._current
  237. ##@brief Getter for contexts
  238. #@param ctx_id str | None | False : if False return the current context
  239. #@return A LodelContext instance
  240. @classmethod
  241. def get(cls, ctx_id = False):
  242. if ctx_id is False:
  243. if cls._current is None:
  244. raise ContextError("No context loaded")
  245. return cls._current
  246. ctx_id = LOAD_CTX if ctx_id is None else ctx_id
  247. if ctx_id not in cls._contexts:
  248. raise ContextError("No context identified by '%s'" % ctx_id)
  249. return cls._contexts[ctx_id]
  250. ##@brief Returns the name of the loaded context
  251. @classmethod
  252. def get_name(cls):
  253. if cls._current is None:
  254. raise ContextError("No context loaded")
  255. return copy.copy(cls._current.__id)
  256. ##@brief Create a new context given a context name
  257. #
  258. #@note It's just an alias to the LodelContext.__init__ method
  259. #@param site_id str : context name
  260. #@return the context instance
  261. @classmethod
  262. def new(cls, site_id, instance_path = None):
  263. if site_id is None:
  264. site_id = LOAD_CTX
  265. return cls(site_id, instance_path)
  266. ##@brief Helper function that import and expose specified modules
  267. #
  268. #The specs given is a dict. Each element is indexed by a module
  269. #fullname. Items can be of two types :
  270. #@par Simple import with alias
  271. #In this case items of specs is a string representing the alias name
  272. #for the module we are exposing
  273. #@par from x import i,j,k equivalent
  274. #In this case items are lists of object name to expose as it in globals.
  275. #You can specify an alias by giving a tuple instead of a string as
  276. #list element. In this case the first element of the tuple is the object
  277. #name and the second it's alias in the globals
  278. #
  279. #@todo make the specs format more consitant
  280. #@param cls : bultin params
  281. #@param globs dict : the globals dict of the caller module
  282. #@param specs dict : specs of exposure (see comments of this method)
  283. #@todo implements relative module imports. (maybe by looking for
  284. #"calling" package in globs dict)
  285. @classmethod
  286. def expose_modules(cls, globs, specs):
  287. ctx = cls.get()
  288. for spec in specs.items():
  289. ctx.expose(globs, spec)
  290. ##@brief Return a module from current context
  291. #@param fullname str : module fullname
  292. @classmethod
  293. def module(cls, fullname):
  294. return cls.get().get_module(fullname)
  295. ##@brief Expose leapi_dyncode module
  296. @classmethod
  297. def expose_dyncode(cls, globs, alias = 'leapi_dyncode'):
  298. cls.get().expose_module(globs, 'leapi_dyncode')
  299. ##@brief Initialize the context manager
  300. #
  301. #@note Add the LodelMetaPathFinder class to sys.metapath if type is
  302. #LodelContext.MULTISITE
  303. #@note lodelsites package name is hardcoded and has to be
  304. #@param type FLAG : takes value in LodelContext.MONOSITE or
  305. #LodelContext.MULTISITE
  306. @classmethod
  307. def init(cls, type=MONOSITE):
  308. if cls._current is not None:
  309. raise ContextError("Context allready started and used. Enable to \
  310. initialize it anymore")
  311. if type not in ( cls.MONOSITE, cls.MULTISITE):
  312. raise ContextError("Invalid flag given : %s" % type)
  313. cls._type = type
  314. if cls._type == cls.MULTISITE:
  315. cls._contexts = dict()
  316. #Add custom MetaPathFinder allowing implementing custom imports
  317. sys.meta_path = [LodelMetaPathFinder] + sys.meta_path
  318. #Create and set __loader__ context
  319. cls.new(LOAD_CTX)
  320. cls.set(LOAD_CTX)
  321. #Modifying sys.path in order to be able to import
  322. #context specific packages
  323. sys.path.append(MULTISITE_CONTEXTDIR)
  324. if 'lodelsites' not in sys.modules:
  325. import lodelsites
  326. else:
  327. globals()['lodelsites'] = sys.modules['lodelsites']
  328. else:
  329. #Add a single context with no site_id
  330. cls._contexts = cls._current = cls(None)
  331. cls.__initialized = True
  332. ##@return True if the class is initialized
  333. @classmethod
  334. def is_initialized(cls):
  335. return cls.__initialized
  336. ##@brief Return the directory of the package of the current loaded context
  337. @classmethod
  338. def context_dir(cls):
  339. if cls._type == cls.MONOSITE:
  340. return './'
  341. return dir_for_context(cls._current.__id)
  342. ##@brief Validate a context identifier
  343. #@param identifier str : the identifier to validate
  344. #@return true if the name is valide else false
  345. @staticmethod
  346. def validate_identifier(identifier):
  347. if identifier == LOAD_CTX:
  348. return True
  349. return identifier is None or \
  350. re.match(r'^[a-zA-Z0-9][a-zA-Z0-9_]', identifier)
  351. ##@brief Safely expose a module in globals using an alias name
  352. #
  353. #@note designed to implements warning messages or stuff like that
  354. #when doing nasty stuff
  355. #
  356. #@warning Logging stuffs may lead in a performance issue
  357. #
  358. #@todo try to use the logger module instead of warnings
  359. #@param globs globals : the globals where we want to expose our
  360. #module alias
  361. #@param obj object : the object we want to expose
  362. #@param alias str : the alias name for our module
  363. @staticmethod
  364. def safe_exposure(globs, obj, alias):
  365. if alias in globs:
  366. if globs[alias] != obj:
  367. print("Context '%s' : A module exposure leads in globals overwriting for \
  368. key '%s' with a different value : %s != %s" % (LodelContext.get_name(), alias, globs[alias], obj))
  369. """#Uncomment this bloc to display a stack trace for dangerous modules overwriting
  370. print("DEBUG INFOS : ")
  371. import traceback
  372. traceback.print_stack()
  373. """
  374. else:
  375. print("Context '%s' : A module exposure leads in a useless replacement for \
  376. key '%s'" % (LodelContext.get_name(),alias))
  377. globs[alias] = obj
  378. ##@brief Create a context from a path and returns the context name
  379. #@param path str : the path from which we extract a sitename
  380. #@return the site identifier
  381. @classmethod
  382. def from_path(cls, path):
  383. if cls._type != cls.MULTISITE:
  384. raise ContextError("Cannot create a context from a path in \
  385. MONOSITE mode")
  386. site_id = os.path.basename(path.strip('/'))
  387. path = os.path.realpath(path)
  388. if not cls.validate_identifier(site_id):
  389. raise ContextError(
  390. "Unable to create a context named '%s'" % site_id)
  391. cls.new(site_id, path)
  392. return site_id
  393. ##@brief Utility method to expose a module with an alias name in globals
  394. #@param globs globals() : concerned globals dict
  395. #@param fullname str : module fullname
  396. #@param alias str : alias name
  397. @classmethod
  398. def _expose_module(cls, globs, fullname, alias):
  399. module = importlib.import_module(fullname)
  400. cls.safe_exposure(globs, module, alias)
  401. ##@brief Utility mehod to expose objects like in a from x import y,z
  402. #form
  403. #@param globs globals() : dict of globals
  404. #@param fullename str : module fullname
  405. #@param objects list : list of object names to expose
  406. @classmethod
  407. def _expose_objects(cls, globs, fullname, objects):
  408. errors = []
  409. module = importlib.import_module(fullname)
  410. for o_name in objects:
  411. if isinstance(o_name, str):
  412. alias = o_name
  413. else:
  414. o_name, alias = o_name
  415. if not hasattr(module, o_name):
  416. errors.append(o_name)
  417. else:
  418. cls.safe_exposure(globs, getattr(module, o_name), alias)
  419. if len(errors) > 0:
  420. msg = "Module %s does not have any of [%s] as attribute" % (
  421. fullname, ','.join(errors))
  422. raise ImportError(msg)
  423. ##@brief Translate a module fullname to the context equivalent
  424. #
  425. #Two transformation are possible :
  426. #- we are importing a submodule of the lodel package : resulting module
  427. #name will be : self.__pkg_name + module_fullname
  428. #- we are importing the dyncode : resulting module name is :
  429. #self.__pkg_name + dyncode_modulename
  430. #@param module_fullname str : a module fullname
  431. #@return The module name in the current context
  432. def _translate(self, module_fullname):
  433. if not module_fullname.startswith('lodel') and \
  434. not module_fullname.startswith('leapi_dyncode'):
  435. raise ContextModuleError("Given module is not lodel nor dyncode \
  436. or any submodule : '%s'" % module_fullname)
  437. return self.__pkg_name+module_fullname
  438. ##@brief Implements the with statement behavior
  439. #@see https://www.python.org/dev/peps/pep-0343/
  440. #@see https://wiki.python.org/moin/WithStatement
  441. def __enter__(self):
  442. if not self.multisite:
  443. warnings.warn("Using LodelContext with with statement in \
  444. MONOSITE mode")
  445. if self.__previous_ctx is not None:
  446. raise ContextError("__enter__ called but a previous context \
  447. is allready registered !!! Bailout")
  448. current = LodelContext.get().__id
  449. if current != self.__id:
  450. #Only switch if necessary
  451. self.__previous_ctx = LodelContext.get().__id
  452. LodelContext.set(self.__id)
  453. return self
  454. ##@brief Implements the with statement behavior
  455. #@see https://www.python.org/dev/peps/pep-0343/
  456. #@see https://wiki.python.org/moin/WithStatement
  457. def __exit__(self, exc_type, exc_val, exc_tb):
  458. prev = self.__previous_ctx
  459. self.__previous_ctx = None
  460. if prev is not None:
  461. #Only restore if needed
  462. LodelContext.set(self.__previous_ctx)