PageRenderTime 49ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/notebook/services/contents/manager.py

https://gitlab.com/yeah568/notebook
Python | 471 lines | 446 code | 7 blank | 18 comment | 0 complexity | e5a921fd60110e3264ac7b0c8b77283d MD5 | raw file
  1. """A base class for contents managers."""
  2. # Copyright (c) Jupyter Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from fnmatch import fnmatch
  5. import itertools
  6. import json
  7. import os
  8. import re
  9. from tornado.web import HTTPError
  10. from .checkpoints import Checkpoints
  11. from traitlets.config.configurable import LoggingConfigurable
  12. from nbformat import sign, validate, ValidationError
  13. from nbformat.v4 import new_notebook
  14. from ipython_genutils.importstring import import_item
  15. from traitlets import (
  16. Any,
  17. Dict,
  18. Instance,
  19. List,
  20. TraitError,
  21. Type,
  22. Unicode,
  23. )
  24. from ipython_genutils.py3compat import string_types
  25. copy_pat = re.compile(r'\-Copy\d*\.')
  26. class ContentsManager(LoggingConfigurable):
  27. """Base class for serving files and directories.
  28. This serves any text or binary file,
  29. as well as directories,
  30. with special handling for JSON notebook documents.
  31. Most APIs take a path argument,
  32. which is always an API-style unicode path,
  33. and always refers to a directory.
  34. - unicode, not url-escaped
  35. - '/'-separated
  36. - leading and trailing '/' will be stripped
  37. - if unspecified, path defaults to '',
  38. indicating the root path.
  39. """
  40. notary = Instance(sign.NotebookNotary)
  41. def _notary_default(self):
  42. return sign.NotebookNotary(parent=self)
  43. hide_globs = List(Unicode(), [
  44. u'__pycache__', '*.pyc', '*.pyo',
  45. '.DS_Store', '*.so', '*.dylib', '*~',
  46. ], config=True, help="""
  47. Glob patterns to hide in file and directory listings.
  48. """)
  49. untitled_notebook = Unicode("Untitled", config=True,
  50. help="The base name used when creating untitled notebooks."
  51. )
  52. untitled_file = Unicode("untitled", config=True,
  53. help="The base name used when creating untitled files."
  54. )
  55. untitled_directory = Unicode("Untitled Folder", config=True,
  56. help="The base name used when creating untitled directories."
  57. )
  58. pre_save_hook = Any(None, config=True,
  59. help="""Python callable or importstring thereof
  60. To be called on a contents model prior to save.
  61. This can be used to process the structure,
  62. such as removing notebook outputs or other side effects that
  63. should not be saved.
  64. It will be called as (all arguments passed by keyword)::
  65. hook(path=path, model=model, contents_manager=self)
  66. - model: the model to be saved. Includes file contents.
  67. Modifying this dict will affect the file that is stored.
  68. - path: the API path of the save destination
  69. - contents_manager: this ContentsManager instance
  70. """
  71. )
  72. def _pre_save_hook_changed(self, name, old, new):
  73. if new and isinstance(new, string_types):
  74. self.pre_save_hook = import_item(self.pre_save_hook)
  75. elif new:
  76. if not callable(new):
  77. raise TraitError("pre_save_hook must be callable")
  78. def run_pre_save_hook(self, model, path, **kwargs):
  79. """Run the pre-save hook if defined, and log errors"""
  80. if self.pre_save_hook:
  81. try:
  82. self.log.debug("Running pre-save hook on %s", path)
  83. self.pre_save_hook(model=model, path=path, contents_manager=self, **kwargs)
  84. except Exception:
  85. self.log.error("Pre-save hook failed on %s", path, exc_info=True)
  86. checkpoints_class = Type(Checkpoints, config=True)
  87. checkpoints = Instance(Checkpoints, config=True)
  88. checkpoints_kwargs = Dict(config=True)
  89. def _checkpoints_default(self):
  90. return self.checkpoints_class(**self.checkpoints_kwargs)
  91. def _checkpoints_kwargs_default(self):
  92. return dict(
  93. parent=self,
  94. log=self.log,
  95. )
  96. # ContentsManager API part 1: methods that must be
  97. # implemented in subclasses.
  98. def dir_exists(self, path):
  99. """Does a directory exist at the given path?
  100. Like os.path.isdir
  101. Override this method in subclasses.
  102. Parameters
  103. ----------
  104. path : string
  105. The path to check
  106. Returns
  107. -------
  108. exists : bool
  109. Whether the path does indeed exist.
  110. """
  111. raise NotImplementedError
  112. def is_hidden(self, path):
  113. """Is path a hidden directory or file?
  114. Parameters
  115. ----------
  116. path : string
  117. The path to check. This is an API path (`/` separated,
  118. relative to root dir).
  119. Returns
  120. -------
  121. hidden : bool
  122. Whether the path is hidden.
  123. """
  124. raise NotImplementedError
  125. def file_exists(self, path=''):
  126. """Does a file exist at the given path?
  127. Like os.path.isfile
  128. Override this method in subclasses.
  129. Parameters
  130. ----------
  131. path : string
  132. The API path of a file to check for.
  133. Returns
  134. -------
  135. exists : bool
  136. Whether the file exists.
  137. """
  138. raise NotImplementedError('must be implemented in a subclass')
  139. def exists(self, path):
  140. """Does a file or directory exist at the given path?
  141. Like os.path.exists
  142. Parameters
  143. ----------
  144. path : string
  145. The API path of a file or directory to check for.
  146. Returns
  147. -------
  148. exists : bool
  149. Whether the target exists.
  150. """
  151. return self.file_exists(path) or self.dir_exists(path)
  152. def get(self, path, content=True, type=None, format=None):
  153. """Get a file or directory model."""
  154. raise NotImplementedError('must be implemented in a subclass')
  155. def save(self, model, path):
  156. """
  157. Save a file or directory model to path.
  158. Should return the saved model with no content. Save implementations
  159. should call self.run_pre_save_hook(model=model, path=path) prior to
  160. writing any data.
  161. """
  162. raise NotImplementedError('must be implemented in a subclass')
  163. def delete_file(self, path):
  164. """Delete the file or directory at path."""
  165. raise NotImplementedError('must be implemented in a subclass')
  166. def rename_file(self, old_path, new_path):
  167. """Rename a file or directory."""
  168. raise NotImplementedError('must be implemented in a subclass')
  169. # ContentsManager API part 2: methods that have useable default
  170. # implementations, but can be overridden in subclasses.
  171. def delete(self, path):
  172. """Delete a file/directory and any associated checkpoints."""
  173. path = path.strip('/')
  174. if not path:
  175. raise HTTPError(400, "Can't delete root")
  176. self.delete_file(path)
  177. self.checkpoints.delete_all_checkpoints(path)
  178. def rename(self, old_path, new_path):
  179. """Rename a file and any checkpoints associated with that file."""
  180. self.rename_file(old_path, new_path)
  181. self.checkpoints.rename_all_checkpoints(old_path, new_path)
  182. def update(self, model, path):
  183. """Update the file's path
  184. For use in PATCH requests, to enable renaming a file without
  185. re-uploading its contents. Only used for renaming at the moment.
  186. """
  187. path = path.strip('/')
  188. new_path = model.get('path', path).strip('/')
  189. if path != new_path:
  190. self.rename(path, new_path)
  191. model = self.get(new_path, content=False)
  192. return model
  193. def info_string(self):
  194. return "Serving contents"
  195. def get_kernel_path(self, path, model=None):
  196. """Return the API path for the kernel
  197. KernelManagers can turn this value into a filesystem path,
  198. or ignore it altogether.
  199. The default value here will start kernels in the directory of the
  200. notebook server. FileContentsManager overrides this to use the
  201. directory containing the notebook.
  202. """
  203. return ''
  204. def increment_filename(self, filename, path='', insert=''):
  205. """Increment a filename until it is unique.
  206. Parameters
  207. ----------
  208. filename : unicode
  209. The name of a file, including extension
  210. path : unicode
  211. The API path of the target's directory
  212. Returns
  213. -------
  214. name : unicode
  215. A filename that is unique, based on the input filename.
  216. """
  217. path = path.strip('/')
  218. basename, ext = os.path.splitext(filename)
  219. for i in itertools.count():
  220. if i:
  221. insert_i = '{}{}'.format(insert, i)
  222. else:
  223. insert_i = ''
  224. name = u'{basename}{insert}{ext}'.format(basename=basename,
  225. insert=insert_i, ext=ext)
  226. if not self.exists(u'{}/{}'.format(path, name)):
  227. break
  228. return name
  229. def validate_notebook_model(self, model):
  230. """Add failed-validation message to model"""
  231. try:
  232. validate(model['content'])
  233. except ValidationError as e:
  234. model['message'] = u'Notebook Validation failed: {}:\n{}'.format(
  235. e.message, json.dumps(e.instance, indent=1, default=lambda obj: '<UNKNOWN>'),
  236. )
  237. return model
  238. def new_untitled(self, path='', type='', ext=''):
  239. """Create a new untitled file or directory in path
  240. path must be a directory
  241. File extension can be specified.
  242. Use `new` to create files with a fully specified path (including filename).
  243. """
  244. path = path.strip('/')
  245. if not self.dir_exists(path):
  246. raise HTTPError(404, 'No such directory: %s' % path)
  247. model = {}
  248. if type:
  249. model['type'] = type
  250. if ext == '.ipynb':
  251. model.setdefault('type', 'notebook')
  252. else:
  253. model.setdefault('type', 'file')
  254. insert = ''
  255. if model['type'] == 'directory':
  256. untitled = self.untitled_directory
  257. insert = ' '
  258. elif model['type'] == 'notebook':
  259. untitled = self.untitled_notebook
  260. ext = '.ipynb'
  261. elif model['type'] == 'file':
  262. untitled = self.untitled_file
  263. else:
  264. raise HTTPError(400, "Unexpected model type: %r" % model['type'])
  265. name = self.increment_filename(untitled + ext, path, insert=insert)
  266. path = u'{0}/{1}'.format(path, name)
  267. return self.new(model, path)
  268. def new(self, model=None, path=''):
  269. """Create a new file or directory and return its model with no content.
  270. To create a new untitled entity in a directory, use `new_untitled`.
  271. """
  272. path = path.strip('/')
  273. if model is None:
  274. model = {}
  275. if path.endswith('.ipynb'):
  276. model.setdefault('type', 'notebook')
  277. else:
  278. model.setdefault('type', 'file')
  279. # no content, not a directory, so fill out new-file model
  280. if 'content' not in model and model['type'] != 'directory':
  281. if model['type'] == 'notebook':
  282. model['content'] = new_notebook()
  283. model['format'] = 'json'
  284. else:
  285. model['content'] = ''
  286. model['type'] = 'file'
  287. model['format'] = 'text'
  288. model = self.save(model, path)
  289. return model
  290. def copy(self, from_path, to_path=None):
  291. """Copy an existing file and return its new model.
  292. If to_path not specified, it will be the parent directory of from_path.
  293. If to_path is a directory, filename will increment `from_path-Copy#.ext`.
  294. from_path must be a full path to a file.
  295. """
  296. path = from_path.strip('/')
  297. if to_path is not None:
  298. to_path = to_path.strip('/')
  299. if '/' in path:
  300. from_dir, from_name = path.rsplit('/', 1)
  301. else:
  302. from_dir = ''
  303. from_name = path
  304. model = self.get(path)
  305. model.pop('path', None)
  306. model.pop('name', None)
  307. if model['type'] == 'directory':
  308. raise HTTPError(400, "Can't copy directories")
  309. if to_path is None:
  310. to_path = from_dir
  311. if self.dir_exists(to_path):
  312. name = copy_pat.sub(u'.', from_name)
  313. to_name = self.increment_filename(name, to_path, insert='-Copy')
  314. to_path = u'{0}/{1}'.format(to_path, to_name)
  315. model = self.save(model, to_path)
  316. return model
  317. def log_info(self):
  318. self.log.info(self.info_string())
  319. def trust_notebook(self, path):
  320. """Explicitly trust a notebook
  321. Parameters
  322. ----------
  323. path : string
  324. The path of a notebook
  325. """
  326. model = self.get(path)
  327. nb = model['content']
  328. self.log.warn("Trusting notebook %s", path)
  329. self.notary.mark_cells(nb, True)
  330. self.save(model, path)
  331. def check_and_sign(self, nb, path=''):
  332. """Check for trusted cells, and sign the notebook.
  333. Called as a part of saving notebooks.
  334. Parameters
  335. ----------
  336. nb : dict
  337. The notebook dict
  338. path : string
  339. The notebook's path (for logging)
  340. """
  341. if self.notary.check_cells(nb):
  342. self.notary.sign(nb)
  343. else:
  344. self.log.warn("Saving untrusted notebook %s", path)
  345. def mark_trusted_cells(self, nb, path=''):
  346. """Mark cells as trusted if the notebook signature matches.
  347. Called as a part of loading notebooks.
  348. Parameters
  349. ----------
  350. nb : dict
  351. The notebook object (in current nbformat)
  352. path : string
  353. The notebook's path (for logging)
  354. """
  355. trusted = self.notary.check_signature(nb)
  356. if not trusted:
  357. self.log.warn("Notebook %s is not trusted", path)
  358. self.notary.mark_cells(nb, trusted)
  359. def should_list(self, name):
  360. """Should this file/directory name be displayed in a listing?"""
  361. return not any(fnmatch(name, glob) for glob in self.hide_globs)
  362. # Part 3: Checkpoints API
  363. def create_checkpoint(self, path):
  364. """Create a checkpoint."""
  365. return self.checkpoints.create_checkpoint(self, path)
  366. def restore_checkpoint(self, checkpoint_id, path):
  367. """
  368. Restore a checkpoint.
  369. """
  370. self.checkpoints.restore_checkpoint(self, checkpoint_id, path)
  371. def list_checkpoints(self, path):
  372. return self.checkpoints.list_checkpoints(path)
  373. def delete_checkpoint(self, checkpoint_id, path):
  374. return self.checkpoints.delete_checkpoint(checkpoint_id, path)