bccache.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. # -*- coding: utf-8 -*-
  2. """
  3. jinja2.bccache
  4. ~~~~~~~~~~~~~~
  5. This module implements the bytecode cache system Jinja is optionally
  6. using. This is useful if you have very complex template situations and
  7. the compiliation of all those templates slow down your application too
  8. much.
  9. Situations where this is useful are often forking web applications that
  10. are initialized on the first request.
  11. :copyright: (c) 2017 by the Jinja Team.
  12. :license: BSD.
  13. """
  14. from os import path, listdir
  15. import os
  16. import sys
  17. import stat
  18. import errno
  19. import marshal
  20. import tempfile
  21. import fnmatch
  22. from hashlib import sha1
  23. from jinja2.utils import open_if_exists
  24. from jinja2._compat import BytesIO, pickle, PY2, text_type
  25. # marshal works better on 3.x, one hack less required
  26. if not PY2:
  27. marshal_dump = marshal.dump
  28. marshal_load = marshal.load
  29. else:
  30. def marshal_dump(code, f):
  31. if isinstance(f, file):
  32. marshal.dump(code, f)
  33. else:
  34. f.write(marshal.dumps(code))
  35. def marshal_load(f):
  36. if isinstance(f, file):
  37. return marshal.load(f)
  38. return marshal.loads(f.read())
  39. bc_version = 3
  40. # magic version used to only change with new jinja versions. With 2.6
  41. # we change this to also take Python version changes into account. The
  42. # reason for this is that Python tends to segfault if fed earlier bytecode
  43. # versions because someone thought it would be a good idea to reuse opcodes
  44. # or make Python incompatible with earlier versions.
  45. bc_magic = 'j2'.encode('ascii') + \
  46. pickle.dumps(bc_version, 2) + \
  47. pickle.dumps((sys.version_info[0] << 24) | sys.version_info[1])
  48. class Bucket(object):
  49. """Buckets are used to store the bytecode for one template. It's created
  50. and initialized by the bytecode cache and passed to the loading functions.
  51. The buckets get an internal checksum from the cache assigned and use this
  52. to automatically reject outdated cache material. Individual bytecode
  53. cache subclasses don't have to care about cache invalidation.
  54. """
  55. def __init__(self, environment, key, checksum):
  56. self.environment = environment
  57. self.key = key
  58. self.checksum = checksum
  59. self.reset()
  60. def reset(self):
  61. """Resets the bucket (unloads the bytecode)."""
  62. self.code = None
  63. def load_bytecode(self, f):
  64. """Loads bytecode from a file or file like object."""
  65. # make sure the magic header is correct
  66. magic = f.read(len(bc_magic))
  67. if magic != bc_magic:
  68. self.reset()
  69. return
  70. # the source code of the file changed, we need to reload
  71. checksum = pickle.load(f)
  72. if self.checksum != checksum:
  73. self.reset()
  74. return
  75. # if marshal_load fails then we need to reload
  76. try:
  77. self.code = marshal_load(f)
  78. except (EOFError, ValueError, TypeError):
  79. self.reset()
  80. return
  81. def write_bytecode(self, f):
  82. """Dump the bytecode into the file or file like object passed."""
  83. if self.code is None:
  84. raise TypeError('can\'t write empty bucket')
  85. f.write(bc_magic)
  86. pickle.dump(self.checksum, f, 2)
  87. marshal_dump(self.code, f)
  88. def bytecode_from_string(self, string):
  89. """Load bytecode from a string."""
  90. self.load_bytecode(BytesIO(string))
  91. def bytecode_to_string(self):
  92. """Return the bytecode as string."""
  93. out = BytesIO()
  94. self.write_bytecode(out)
  95. return out.getvalue()
  96. class BytecodeCache(object):
  97. """To implement your own bytecode cache you have to subclass this class
  98. and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of
  99. these methods are passed a :class:`~jinja2.bccache.Bucket`.
  100. A very basic bytecode cache that saves the bytecode on the file system::
  101. from os import path
  102. class MyCache(BytecodeCache):
  103. def __init__(self, directory):
  104. self.directory = directory
  105. def load_bytecode(self, bucket):
  106. filename = path.join(self.directory, bucket.key)
  107. if path.exists(filename):
  108. with open(filename, 'rb') as f:
  109. bucket.load_bytecode(f)
  110. def dump_bytecode(self, bucket):
  111. filename = path.join(self.directory, bucket.key)
  112. with open(filename, 'wb') as f:
  113. bucket.write_bytecode(f)
  114. A more advanced version of a filesystem based bytecode cache is part of
  115. Jinja2.
  116. """
  117. def load_bytecode(self, bucket):
  118. """Subclasses have to override this method to load bytecode into a
  119. bucket. If they are not able to find code in the cache for the
  120. bucket, it must not do anything.
  121. """
  122. raise NotImplementedError()
  123. def dump_bytecode(self, bucket):
  124. """Subclasses have to override this method to write the bytecode
  125. from a bucket back to the cache. If it unable to do so it must not
  126. fail silently but raise an exception.
  127. """
  128. raise NotImplementedError()
  129. def clear(self):
  130. """Clears the cache. This method is not used by Jinja2 but should be
  131. implemented to allow applications to clear the bytecode cache used
  132. by a particular environment.
  133. """
  134. def get_cache_key(self, name, filename=None):
  135. """Returns the unique hash key for this template name."""
  136. hash = sha1(name.encode('utf-8'))
  137. if filename is not None:
  138. filename = '|' + filename
  139. if isinstance(filename, text_type):
  140. filename = filename.encode('utf-8')
  141. hash.update(filename)
  142. return hash.hexdigest()
  143. def get_source_checksum(self, source):
  144. """Returns a checksum for the source."""
  145. return sha1(source.encode('utf-8')).hexdigest()
  146. def get_bucket(self, environment, name, filename, source):
  147. """Return a cache bucket for the given template. All arguments are
  148. mandatory but filename may be `None`.
  149. """
  150. key = self.get_cache_key(name, filename)
  151. checksum = self.get_source_checksum(source)
  152. bucket = Bucket(environment, key, checksum)
  153. self.load_bytecode(bucket)
  154. return bucket
  155. def set_bucket(self, bucket):
  156. """Put the bucket into the cache."""
  157. self.dump_bytecode(bucket)
  158. class FileSystemBytecodeCache(BytecodeCache):
  159. """A bytecode cache that stores bytecode on the filesystem. It accepts
  160. two arguments: The directory where the cache items are stored and a
  161. pattern string that is used to build the filename.
  162. If no directory is specified a default cache directory is selected. On
  163. Windows the user's temp directory is used, on UNIX systems a directory
  164. is created for the user in the system temp directory.
  165. The pattern can be used to have multiple separate caches operate on the
  166. same directory. The default pattern is ``'__jinja2_%s.cache'``. ``%s``
  167. is replaced with the cache key.
  168. >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')
  169. This bytecode cache supports clearing of the cache using the clear method.
  170. """
  171. def __init__(self, directory=None, pattern='__jinja2_%s.cache'):
  172. if directory is None:
  173. directory = self._get_default_cache_dir()
  174. self.directory = directory
  175. self.pattern = pattern
  176. def _get_default_cache_dir(self):
  177. def _unsafe_dir():
  178. raise RuntimeError('Cannot determine safe temp directory. You '
  179. 'need to explicitly provide one.')
  180. tmpdir = tempfile.gettempdir()
  181. # On windows the temporary directory is used specific unless
  182. # explicitly forced otherwise. We can just use that.
  183. if os.name == 'nt':
  184. return tmpdir
  185. if not hasattr(os, 'getuid'):
  186. _unsafe_dir()
  187. dirname = '_jinja2-cache-%d' % os.getuid()
  188. actual_dir = os.path.join(tmpdir, dirname)
  189. try:
  190. os.mkdir(actual_dir, stat.S_IRWXU)
  191. except OSError as e:
  192. if e.errno != errno.EEXIST:
  193. raise
  194. try:
  195. os.chmod(actual_dir, stat.S_IRWXU)
  196. actual_dir_stat = os.lstat(actual_dir)
  197. if actual_dir_stat.st_uid != os.getuid() \
  198. or not stat.S_ISDIR(actual_dir_stat.st_mode) \
  199. or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
  200. _unsafe_dir()
  201. except OSError as e:
  202. if e.errno != errno.EEXIST:
  203. raise
  204. actual_dir_stat = os.lstat(actual_dir)
  205. if actual_dir_stat.st_uid != os.getuid() \
  206. or not stat.S_ISDIR(actual_dir_stat.st_mode) \
  207. or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
  208. _unsafe_dir()
  209. return actual_dir
  210. def _get_cache_filename(self, bucket):
  211. return path.join(self.directory, self.pattern % bucket.key)
  212. def load_bytecode(self, bucket):
  213. f = open_if_exists(self._get_cache_filename(bucket), 'rb')
  214. if f is not None:
  215. try:
  216. bucket.load_bytecode(f)
  217. finally:
  218. f.close()
  219. def dump_bytecode(self, bucket):
  220. f = open(self._get_cache_filename(bucket), 'wb')
  221. try:
  222. bucket.write_bytecode(f)
  223. finally:
  224. f.close()
  225. def clear(self):
  226. # imported lazily here because google app-engine doesn't support
  227. # write access on the file system and the function does not exist
  228. # normally.
  229. from os import remove
  230. files = fnmatch.filter(listdir(self.directory), self.pattern % '*')
  231. for filename in files:
  232. try:
  233. remove(path.join(self.directory, filename))
  234. except OSError:
  235. pass
  236. class MemcachedBytecodeCache(BytecodeCache):
  237. """This class implements a bytecode cache that uses a memcache cache for
  238. storing the information. It does not enforce a specific memcache library
  239. (tummy's memcache or cmemcache) but will accept any class that provides
  240. the minimal interface required.
  241. Libraries compatible with this class:
  242. - `werkzeug <http://werkzeug.pocoo.org/>`_.contrib.cache
  243. - `python-memcached <https://www.tummy.com/Community/software/python-memcached/>`_
  244. - `cmemcache <http://gijsbert.org/cmemcache/>`_
  245. (Unfortunately the django cache interface is not compatible because it
  246. does not support storing binary data, only unicode. You can however pass
  247. the underlying cache client to the bytecode cache which is available
  248. as `django.core.cache.cache._client`.)
  249. The minimal interface for the client passed to the constructor is this:
  250. .. class:: MinimalClientInterface
  251. .. method:: set(key, value[, timeout])
  252. Stores the bytecode in the cache. `value` is a string and
  253. `timeout` the timeout of the key. If timeout is not provided
  254. a default timeout or no timeout should be assumed, if it's
  255. provided it's an integer with the number of seconds the cache
  256. item should exist.
  257. .. method:: get(key)
  258. Returns the value for the cache key. If the item does not
  259. exist in the cache the return value must be `None`.
  260. The other arguments to the constructor are the prefix for all keys that
  261. is added before the actual cache key and the timeout for the bytecode in
  262. the cache system. We recommend a high (or no) timeout.
  263. This bytecode cache does not support clearing of used items in the cache.
  264. The clear method is a no-operation function.
  265. .. versionadded:: 2.7
  266. Added support for ignoring memcache errors through the
  267. `ignore_memcache_errors` parameter.
  268. """
  269. def __init__(self, client, prefix='jinja2/bytecode/', timeout=None,
  270. ignore_memcache_errors=True):
  271. self.client = client
  272. self.prefix = prefix
  273. self.timeout = timeout
  274. self.ignore_memcache_errors = ignore_memcache_errors
  275. def load_bytecode(self, bucket):
  276. try:
  277. code = self.client.get(self.prefix + bucket.key)
  278. except Exception:
  279. if not self.ignore_memcache_errors:
  280. raise
  281. code = None
  282. if code is not None:
  283. bucket.bytecode_from_string(code)
  284. def dump_bytecode(self, bucket):
  285. args = (self.prefix + bucket.key, bucket.bytecode_to_string())
  286. if self.timeout is not None:
  287. args += (self.timeout,)
  288. try:
  289. self.client.set(*args)
  290. except Exception:
  291. if not self.ignore_memcache_errors:
  292. raise