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

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