manager.py 16 KB

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