fileio.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. """
  2. Utilities for file-based Contents/Checkpoints managers.
  3. """
  4. # Copyright (c) Jupyter Development Team.
  5. # Distributed under the terms of the Modified BSD License.
  6. from contextlib import contextmanager
  7. import errno
  8. import io
  9. import os
  10. import shutil
  11. from tornado.web import HTTPError
  12. from notebook.utils import (
  13. to_api_path,
  14. to_os_path,
  15. )
  16. import nbformat
  17. from ipython_genutils.py3compat import str_to_unicode
  18. from traitlets.config import Configurable
  19. from traitlets import Bool
  20. try: #PY3
  21. from base64 import encodebytes, decodebytes
  22. except ImportError: #PY2
  23. from base64 import encodestring as encodebytes, decodestring as decodebytes
  24. def replace_file(src, dst):
  25. """ replace dst with src
  26. switches between os.replace or os.rename based on python 2.7 or python 3
  27. """
  28. if hasattr(os, 'replace'): # PY3
  29. os.replace(src, dst)
  30. else:
  31. if os.name == 'nt' and os.path.exists(dst):
  32. # Rename over existing file doesn't work on Windows
  33. os.remove(dst)
  34. os.rename(src, dst)
  35. def copy2_safe(src, dst, log=None):
  36. """copy src to dst
  37. like shutil.copy2, but log errors in copystat instead of raising
  38. """
  39. shutil.copyfile(src, dst)
  40. try:
  41. shutil.copystat(src, dst)
  42. except OSError:
  43. if log:
  44. log.debug("copystat on %s failed", dst, exc_info=True)
  45. def path_to_intermediate(path):
  46. '''Name of the intermediate file used in atomic writes.
  47. The .~ prefix will make Dropbox ignore the temporary file.'''
  48. dirname, basename = os.path.split(path)
  49. return os.path.join(dirname, '.~'+basename)
  50. def path_to_invalid(path):
  51. '''Name of invalid file after a failed atomic write and subsequent read.'''
  52. dirname, basename = os.path.split(path)
  53. return os.path.join(dirname, basename+'.invalid')
  54. @contextmanager
  55. def atomic_writing(path, text=True, encoding='utf-8', log=None, **kwargs):
  56. """Context manager to write to a file only if the entire write is successful.
  57. This works by copying the previous file contents to a temporary file in the
  58. same directory, and renaming that file back to the target if the context
  59. exits with an error. If the context is successful, the new data is synced to
  60. disk and the temporary file is removed.
  61. Parameters
  62. ----------
  63. path : str
  64. The target file to write to.
  65. text : bool, optional
  66. Whether to open the file in text mode (i.e. to write unicode). Default is
  67. True.
  68. encoding : str, optional
  69. The encoding to use for files opened in text mode. Default is UTF-8.
  70. **kwargs
  71. Passed to :func:`io.open`.
  72. """
  73. # realpath doesn't work on Windows: https://bugs.python.org/issue9949
  74. # Luckily, we only need to resolve the file itself being a symlink, not
  75. # any of its directories, so this will suffice:
  76. if os.path.islink(path):
  77. path = os.path.join(os.path.dirname(path), os.readlink(path))
  78. tmp_path = path_to_intermediate(path)
  79. if os.path.isfile(path):
  80. copy2_safe(path, tmp_path, log=log)
  81. if text:
  82. # Make sure that text files have Unix linefeeds by default
  83. kwargs.setdefault('newline', '\n')
  84. fileobj = io.open(path, 'w', encoding=encoding, **kwargs)
  85. else:
  86. fileobj = io.open(path, 'wb', **kwargs)
  87. try:
  88. yield fileobj
  89. except:
  90. # Failed! Move the backup file back to the real path to avoid corruption
  91. fileobj.close()
  92. replace_file(tmp_path, path)
  93. raise
  94. # Flush to disk
  95. fileobj.flush()
  96. os.fsync(fileobj.fileno())
  97. fileobj.close()
  98. # Written successfully, now remove the backup copy
  99. if os.path.isfile(tmp_path):
  100. os.remove(tmp_path)
  101. @contextmanager
  102. def _simple_writing(path, text=True, encoding='utf-8', log=None, **kwargs):
  103. """Context manager to write file without doing atomic writing
  104. ( for weird filesystem eg: nfs).
  105. Parameters
  106. ----------
  107. path : str
  108. The target file to write to.
  109. text : bool, optional
  110. Whether to open the file in text mode (i.e. to write unicode). Default is
  111. True.
  112. encoding : str, optional
  113. The encoding to use for files opened in text mode. Default is UTF-8.
  114. **kwargs
  115. Passed to :func:`io.open`.
  116. """
  117. # realpath doesn't work on Windows: https://bugs.python.org/issue9949
  118. # Luckily, we only need to resolve the file itself being a symlink, not
  119. # any of its directories, so this will suffice:
  120. if os.path.islink(path):
  121. path = os.path.join(os.path.dirname(path), os.readlink(path))
  122. if text:
  123. # Make sure that text files have Unix linefeeds by default
  124. kwargs.setdefault('newline', '\n')
  125. fileobj = io.open(path, 'w', encoding=encoding, **kwargs)
  126. else:
  127. fileobj = io.open(path, 'wb', **kwargs)
  128. try:
  129. yield fileobj
  130. except:
  131. fileobj.close()
  132. raise
  133. fileobj.close()
  134. class FileManagerMixin(Configurable):
  135. """
  136. Mixin for ContentsAPI classes that interact with the filesystem.
  137. Provides facilities for reading, writing, and copying both notebooks and
  138. generic files.
  139. Shared by FileContentsManager and FileCheckpoints.
  140. Note
  141. ----
  142. Classes using this mixin must provide the following attributes:
  143. root_dir : unicode
  144. A directory against against which API-style paths are to be resolved.
  145. log : logging.Logger
  146. """
  147. use_atomic_writing = Bool(True, config=True, help=
  148. """By default notebooks are saved on disk on a temporary file and then if succefully written, it replaces the old ones.
  149. This procedure, namely 'atomic_writing', causes some bugs on file system whitout operation order enforcement (like some networked fs).
  150. If set to False, the new notebook is written directly on the old one which could fail (eg: full filesystem or quota )""")
  151. @contextmanager
  152. def open(self, os_path, *args, **kwargs):
  153. """wrapper around io.open that turns permission errors into 403"""
  154. with self.perm_to_403(os_path):
  155. with io.open(os_path, *args, **kwargs) as f:
  156. yield f
  157. @contextmanager
  158. def atomic_writing(self, os_path, *args, **kwargs):
  159. """wrapper around atomic_writing that turns permission errors to 403.
  160. Depending on flag 'use_atomic_writing', the wrapper perform an actual atomic writing or
  161. simply writes the file (whatever an old exists or not)"""
  162. with self.perm_to_403(os_path):
  163. if self.use_atomic_writing:
  164. with atomic_writing(os_path, *args, log=self.log, **kwargs) as f:
  165. yield f
  166. else:
  167. with _simple_writing(os_path, *args, log=self.log, **kwargs) as f:
  168. yield f
  169. @contextmanager
  170. def perm_to_403(self, os_path=''):
  171. """context manager for turning permission errors into 403."""
  172. try:
  173. yield
  174. except (OSError, IOError) as e:
  175. if e.errno in {errno.EPERM, errno.EACCES}:
  176. # make 403 error message without root prefix
  177. # this may not work perfectly on unicode paths on Python 2,
  178. # but nobody should be doing that anyway.
  179. if not os_path:
  180. os_path = str_to_unicode(e.filename or 'unknown file')
  181. path = to_api_path(os_path, root=self.root_dir)
  182. raise HTTPError(403, u'Permission denied: %s' % path)
  183. else:
  184. raise
  185. def _copy(self, src, dest):
  186. """copy src to dest
  187. like shutil.copy2, but log errors in copystat
  188. """
  189. copy2_safe(src, dest, log=self.log)
  190. def _get_os_path(self, path):
  191. """Given an API path, return its file system path.
  192. Parameters
  193. ----------
  194. path : string
  195. The relative API path to the named file.
  196. Returns
  197. -------
  198. path : string
  199. Native, absolute OS path to for a file.
  200. Raises
  201. ------
  202. 404: if path is outside root
  203. """
  204. root = os.path.abspath(self.root_dir)
  205. os_path = to_os_path(path, root)
  206. if not (os.path.abspath(os_path) + os.path.sep).startswith(root):
  207. raise HTTPError(404, "%s is outside root contents directory" % path)
  208. return os_path
  209. def _read_notebook(self, os_path, as_version=4):
  210. """Read a notebook from an os path."""
  211. with self.open(os_path, 'r', encoding='utf-8') as f:
  212. try:
  213. return nbformat.read(f, as_version=as_version)
  214. except Exception as e:
  215. e_orig = e
  216. # If use_atomic_writing is enabled, we'll guess that it was also
  217. # enabled when this notebook was written and look for a valid
  218. # atomic intermediate.
  219. tmp_path = path_to_intermediate(os_path)
  220. if not self.use_atomic_writing or not os.path.exists(tmp_path):
  221. raise HTTPError(
  222. 400,
  223. u"Unreadable Notebook: %s %r" % (os_path, e_orig),
  224. )
  225. # Move the bad file aside, restore the intermediate, and try again.
  226. invalid_file = path_to_invalid(os_path)
  227. replace_file(os_path, invalid_file)
  228. replace_file(tmp_path, os_path)
  229. return self._read_notebook(os_path, as_version)
  230. def _save_notebook(self, os_path, nb):
  231. """Save a notebook to an os_path."""
  232. with self.atomic_writing(os_path, encoding='utf-8') as f:
  233. nbformat.write(nb, f, version=nbformat.NO_CONVERT)
  234. def _read_file(self, os_path, format):
  235. """Read a non-notebook file.
  236. os_path: The path to be read.
  237. format:
  238. If 'text', the contents will be decoded as UTF-8.
  239. If 'base64', the raw bytes contents will be encoded as base64.
  240. If not specified, try to decode as UTF-8, and fall back to base64
  241. """
  242. if not os.path.isfile(os_path):
  243. raise HTTPError(400, "Cannot read non-file %s" % os_path)
  244. with self.open(os_path, 'rb') as f:
  245. bcontent = f.read()
  246. if format is None or format == 'text':
  247. # Try to interpret as unicode if format is unknown or if unicode
  248. # was explicitly requested.
  249. try:
  250. return bcontent.decode('utf8'), 'text'
  251. except UnicodeError:
  252. if format == 'text':
  253. raise HTTPError(
  254. 400,
  255. "%s is not UTF-8 encoded" % os_path,
  256. reason='bad format',
  257. )
  258. return encodebytes(bcontent).decode('ascii'), 'base64'
  259. def _save_file(self, os_path, content, format):
  260. """Save content of a generic file."""
  261. if format not in {'text', 'base64'}:
  262. raise HTTPError(
  263. 400,
  264. "Must specify format of file contents as 'text' or 'base64'",
  265. )
  266. try:
  267. if format == 'text':
  268. bcontent = content.encode('utf8')
  269. else:
  270. b64_bytes = content.encode('ascii')
  271. bcontent = decodebytes(b64_bytes)
  272. except Exception as e:
  273. raise HTTPError(
  274. 400, u'Encoding error saving %s: %s' % (os_path, e)
  275. )
  276. with self.atomic_writing(os_path, text=False) as f:
  277. f.write(bcontent)