bccache.py 12 KB

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