bccache.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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.IO[bytes]) -> 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. # Don't test for existence before opening the file, since the
  216. # file could disappear after the test before the open.
  217. try:
  218. f = open(filename, "rb")
  219. except (FileNotFoundError, IsADirectoryError, PermissionError):
  220. # PermissionError can occur on Windows when an operation is
  221. # in progress, such as calling clear().
  222. return
  223. with f:
  224. bucket.load_bytecode(f)
  225. def dump_bytecode(self, bucket: Bucket) -> None:
  226. # Write to a temporary file, then rename to the real name after
  227. # writing. This avoids another process reading the file before
  228. # it is fully written.
  229. name = self._get_cache_filename(bucket)
  230. f = tempfile.NamedTemporaryFile(
  231. mode="wb",
  232. dir=os.path.dirname(name),
  233. prefix=os.path.basename(name),
  234. suffix=".tmp",
  235. delete=False,
  236. )
  237. def remove_silent() -> None:
  238. try:
  239. os.remove(f.name)
  240. except OSError:
  241. # Another process may have called clear(). On Windows,
  242. # another program may be holding the file open.
  243. pass
  244. try:
  245. with f:
  246. bucket.write_bytecode(f)
  247. except BaseException:
  248. remove_silent()
  249. raise
  250. try:
  251. os.replace(f.name, name)
  252. except OSError:
  253. # Another process may have called clear(). On Windows,
  254. # another program may be holding the file open.
  255. remove_silent()
  256. except BaseException:
  257. remove_silent()
  258. raise
  259. def clear(self) -> None:
  260. # imported lazily here because google app-engine doesn't support
  261. # write access on the file system and the function does not exist
  262. # normally.
  263. from os import remove
  264. files = fnmatch.filter(os.listdir(self.directory), self.pattern % ("*",))
  265. for filename in files:
  266. try:
  267. remove(os.path.join(self.directory, filename))
  268. except OSError:
  269. pass
  270. class MemcachedBytecodeCache(BytecodeCache):
  271. """This class implements a bytecode cache that uses a memcache cache for
  272. storing the information. It does not enforce a specific memcache library
  273. (tummy's memcache or cmemcache) but will accept any class that provides
  274. the minimal interface required.
  275. Libraries compatible with this class:
  276. - `cachelib <https://github.com/pallets/cachelib>`_
  277. - `python-memcached <https://pypi.org/project/python-memcached/>`_
  278. (Unfortunately the django cache interface is not compatible because it
  279. does not support storing binary data, only text. You can however pass
  280. the underlying cache client to the bytecode cache which is available
  281. as `django.core.cache.cache._client`.)
  282. The minimal interface for the client passed to the constructor is this:
  283. .. class:: MinimalClientInterface
  284. .. method:: set(key, value[, timeout])
  285. Stores the bytecode in the cache. `value` is a string and
  286. `timeout` the timeout of the key. If timeout is not provided
  287. a default timeout or no timeout should be assumed, if it's
  288. provided it's an integer with the number of seconds the cache
  289. item should exist.
  290. .. method:: get(key)
  291. Returns the value for the cache key. If the item does not
  292. exist in the cache the return value must be `None`.
  293. The other arguments to the constructor are the prefix for all keys that
  294. is added before the actual cache key and the timeout for the bytecode in
  295. the cache system. We recommend a high (or no) timeout.
  296. This bytecode cache does not support clearing of used items in the cache.
  297. The clear method is a no-operation function.
  298. .. versionadded:: 2.7
  299. Added support for ignoring memcache errors through the
  300. `ignore_memcache_errors` parameter.
  301. """
  302. def __init__(
  303. self,
  304. client: "_MemcachedClient",
  305. prefix: str = "jinja2/bytecode/",
  306. timeout: t.Optional[int] = None,
  307. ignore_memcache_errors: bool = True,
  308. ):
  309. self.client = client
  310. self.prefix = prefix
  311. self.timeout = timeout
  312. self.ignore_memcache_errors = ignore_memcache_errors
  313. def load_bytecode(self, bucket: Bucket) -> None:
  314. try:
  315. code = self.client.get(self.prefix + bucket.key)
  316. except Exception:
  317. if not self.ignore_memcache_errors:
  318. raise
  319. else:
  320. bucket.bytecode_from_string(code)
  321. def dump_bytecode(self, bucket: Bucket) -> None:
  322. key = self.prefix + bucket.key
  323. value = bucket.bytecode_to_string()
  324. try:
  325. if self.timeout is not None:
  326. self.client.set(key, value, self.timeout)
  327. else:
  328. self.client.set(key, value)
  329. except Exception:
  330. if not self.ignore_memcache_errors:
  331. raise