labapp.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. # coding: utf-8
  2. """A tornado based Jupyter lab server."""
  3. # Copyright (c) Jupyter Development Team.
  4. # Distributed under the terms of the Modified BSD License.
  5. import json
  6. import os
  7. import os.path as osp
  8. from os.path import join as pjoin
  9. import sys
  10. from jinja2 import Environment, FileSystemLoader
  11. from jupyter_core.application import JupyterApp, base_aliases, base_flags
  12. from jupyter_core.application import NoStart
  13. from jupyterlab_server import slugify, WORKSPACE_EXTENSION
  14. from jupyter_server.serverapp import flags
  15. from jupyter_server.utils import url_path_join as ujoin, url_escape
  16. from jupyter_server.services.config.manager import ConfigManager, recursive_update
  17. from jupyter_server._version import version_info as jpserver_version_info
  18. from traitlets import Bool, Instance, Unicode, default
  19. from nbclassic.shim import NBClassicConfigShimMixin
  20. from jupyterlab_server import LabServerApp
  21. from ._version import __version__
  22. from .debuglog import DebugLogFileMixin
  23. from .commands import (
  24. DEV_DIR, HERE,
  25. build, clean, get_app_dir, get_app_version, get_user_settings_dir,
  26. get_workspaces_dir, AppOptions, pjoin, get_app_info,
  27. ensure_core, ensure_dev, watch, watch_dev, ensure_app
  28. )
  29. from .coreconfig import CoreConfig
  30. from .handlers.build_handler import build_path, Builder, BuildHandler
  31. from .handlers.extension_manager_handler import (
  32. extensions_handler_path, ExtensionManager, ExtensionHandler
  33. )
  34. from .handlers.error_handler import ErrorHandler
  35. DEV_NOTE = """You're running JupyterLab from source.
  36. If you're working on the TypeScript sources of JupyterLab, try running
  37. jupyter lab --dev-mode --watch
  38. to have the system incrementally watch and build JupyterLab for you, as you
  39. make changes.
  40. """
  41. CORE_NOTE = """
  42. Running the core application with no additional extensions or settings
  43. """
  44. build_aliases = dict(base_aliases)
  45. build_aliases['app-dir'] = 'LabBuildApp.app_dir'
  46. build_aliases['name'] = 'LabBuildApp.name'
  47. build_aliases['version'] = 'LabBuildApp.version'
  48. build_aliases['dev-build'] = 'LabBuildApp.dev_build'
  49. build_aliases['minimize'] = 'LabBuildApp.minimize'
  50. build_aliases['debug-log-path'] = 'DebugLogFileMixin.debug_log_path'
  51. build_flags = dict(flags)
  52. build_flags['dev-build'] = (
  53. {'LabBuildApp': {'dev_build': True}},
  54. "Build in development mode."
  55. )
  56. build_flags['no-minimize'] = (
  57. {'LabBuildApp': {'minimize': False}},
  58. "Do not minimize a production build."
  59. )
  60. version = __version__
  61. app_version = get_app_version()
  62. if version != app_version:
  63. version = '%s (dev), %s (app)' % (__version__, app_version)
  64. buildFailureMsg = """Build failed.
  65. Troubleshooting: If the build failed due to an out-of-memory error, you
  66. may be able to fix it by disabling the `dev_build` and/or `minimize` options.
  67. If you are building via the `jupyter lab build` command, you can disable
  68. these options like so:
  69. jupyter lab build --dev-build=False --minimize=False
  70. You can also disable these options for all JupyterLab builds by adding these
  71. lines to a Jupyter config file named `jupyter_config.py`:
  72. c.LabBuildApp.minimize = False
  73. c.LabBuildApp.dev_build = False
  74. If you don't already have a `jupyter_config.py` file, you can create one by
  75. adding a blank file of that name to any of the Jupyter config directories.
  76. The config directories can be listed by running:
  77. jupyter --paths
  78. Explanation:
  79. - `dev-build`: This option controls whether a `dev` or a more streamlined
  80. `production` build is used. This option will default to `False` (i.e., the
  81. `production` build) for most users. However, if you have any labextensions
  82. installed from local files, this option will instead default to `True`.
  83. Explicitly setting `dev-build` to `False` will ensure that the `production`
  84. build is used in all circumstances.
  85. - `minimize`: This option controls whether your JS bundle is minified
  86. during the Webpack build, which helps to improve JupyterLab's overall
  87. performance. However, the minifier plugin used by Webpack is very memory
  88. intensive, so turning it off may help the build finish successfully in
  89. low-memory environments.
  90. """
  91. class LabBuildApp(JupyterApp, DebugLogFileMixin):
  92. version = version
  93. description = """
  94. Build the JupyterLab application
  95. The application is built in the JupyterLab app directory in `/staging`.
  96. When the build is complete it is put in the JupyterLab app `/static`
  97. directory, where it is used to serve the application.
  98. """
  99. aliases = build_aliases
  100. flags = build_flags
  101. # Not configurable!
  102. core_config = Instance(CoreConfig, allow_none=True)
  103. app_dir = Unicode('', config=True,
  104. help="The app directory to build in")
  105. name = Unicode('JupyterLab', config=True,
  106. help="The name of the built application")
  107. version = Unicode('', config=True,
  108. help="The version of the built application")
  109. dev_build = Bool(None, allow_none=True, config=True,
  110. help="Whether to build in dev mode. Defaults to True (dev mode) if there are any locally linked extensions, else defaults to False (production mode).")
  111. minimize = Bool(True, config=True,
  112. help="Whether to minimize a production build (defaults to True).")
  113. pre_clean = Bool(False, config=True,
  114. help="Whether to clean before building (defaults to False)")
  115. def start(self):
  116. app_dir = self.app_dir or get_app_dir()
  117. app_options = AppOptions(
  118. app_dir=app_dir, logger=self.log, core_config=self.core_config
  119. )
  120. self.log.info('JupyterLab %s', version)
  121. with self.debug_logging():
  122. if self.pre_clean:
  123. self.log.info('Cleaning %s' % app_dir)
  124. clean(app_options=app_options)
  125. self.log.info('Building in %s', app_dir)
  126. try:
  127. production = None if self.dev_build is None else not self.dev_build
  128. build(name=self.name, version=self.version,
  129. app_options=app_options, production = production, minimize=self.minimize)
  130. except Exception as e:
  131. print(buildFailureMsg)
  132. raise e
  133. clean_aliases = dict(base_aliases)
  134. clean_aliases['app-dir'] = 'LabCleanApp.app_dir'
  135. ext_warn_msg = "WARNING: this will delete all of your extensions, which will need to be reinstalled"
  136. clean_flags = dict(base_flags)
  137. clean_flags['extensions'] = ({'LabCleanApp': {'extensions': True}},
  138. 'Also delete <app-dir>/extensions.\n%s' % ext_warn_msg)
  139. clean_flags['settings'] = ({'LabCleanApp': {'settings': True}}, 'Also delete <app-dir>/settings')
  140. clean_flags['static'] = ({'LabCleanApp': {'static': True}}, 'Also delete <app-dir>/static')
  141. clean_flags['all'] = ({'LabCleanApp': {'all': True}},
  142. 'Delete the entire contents of the app directory.\n%s' % ext_warn_msg)
  143. class LabCleanAppOptions(AppOptions):
  144. extensions = Bool(False)
  145. settings = Bool(False)
  146. staging = Bool(True)
  147. static = Bool(False)
  148. all = Bool(False)
  149. class LabCleanApp(JupyterApp):
  150. version = version
  151. description = """
  152. Clean the JupyterLab application
  153. This will clean the app directory by removing the `staging` directories.
  154. Optionally, the `extensions`, `settings`, and/or `static` directories,
  155. or the entire contents of the app directory, can also be removed.
  156. """
  157. aliases = clean_aliases
  158. flags = clean_flags
  159. # Not configurable!
  160. core_config = Instance(CoreConfig, allow_none=True)
  161. app_dir = Unicode('', config=True, help='The app directory to clean')
  162. extensions = Bool(False, config=True,
  163. help="Also delete <app-dir>/extensions.\n%s" % ext_warn_msg)
  164. settings = Bool(False, config=True, help="Also delete <app-dir>/settings")
  165. static = Bool(False, config=True, help="Also delete <app-dir>/static")
  166. all = Bool(False, config=True,
  167. help="Delete the entire contents of the app directory.\n%s" % ext_warn_msg)
  168. def start(self):
  169. app_options = LabCleanAppOptions(
  170. logger=self.log,
  171. core_config=self.core_config,
  172. app_dir=self.app_dir,
  173. extensions=self.extensions,
  174. settings=self.settings,
  175. static=self.static,
  176. all=self.all
  177. )
  178. clean(app_options=app_options)
  179. class LabPathApp(JupyterApp):
  180. version = version
  181. description = """
  182. Print the configured paths for the JupyterLab application
  183. The application path can be configured using the JUPYTERLAB_DIR
  184. environment variable.
  185. The user settings path can be configured using the JUPYTERLAB_SETTINGS_DIR
  186. environment variable or it will fall back to
  187. `/lab/user-settings` in the default Jupyter configuration directory.
  188. The workspaces path can be configured using the JUPYTERLAB_WORKSPACES_DIR
  189. environment variable or it will fall back to
  190. '/lab/workspaces' in the default Jupyter configuration directory.
  191. """
  192. def start(self):
  193. print('Application directory: %s' % get_app_dir())
  194. print('User Settings directory: %s' % get_user_settings_dir())
  195. print('Workspaces directory: %s' % get_workspaces_dir())
  196. class LabWorkspaceExportApp(JupyterApp):
  197. version = version
  198. description = """
  199. Export a JupyterLab workspace
  200. If no arguments are passed in, this command will export the default
  201. workspace.
  202. If a workspace name is passed in, this command will export that workspace.
  203. If no workspace is found, this command will export an empty workspace.
  204. """
  205. def start(self):
  206. app = LabApp(config=self.config)
  207. base_url = app.settings.get('base_url', '/')
  208. directory = app.workspaces_dir
  209. app_url = app.app_url
  210. if len(self.extra_args) > 1:
  211. print('Too many arguments were provided for workspace export.')
  212. self.exit(1)
  213. workspaces_url = ujoin(app_url, 'workspaces')
  214. raw = (app_url if not self.extra_args
  215. else ujoin(workspaces_url, self.extra_args[0]))
  216. slug = slugify(raw, base_url)
  217. workspace_path = pjoin(directory, slug + WORKSPACE_EXTENSION)
  218. if osp.exists(workspace_path):
  219. with open(workspace_path) as fid:
  220. try: # to load the workspace file.
  221. print(fid.read())
  222. except Exception as e:
  223. print(json.dumps(dict(data=dict(), metadata=dict(id=raw))))
  224. else:
  225. print(json.dumps(dict(data=dict(), metadata=dict(id=raw))))
  226. class LabWorkspaceImportApp(JupyterApp):
  227. version = version
  228. description = """
  229. Import a JupyterLab workspace
  230. This command will import a workspace from a JSON file. The format of the
  231. file must be the same as what the export functionality emits.
  232. """
  233. workspace_name = Unicode(
  234. None,
  235. config=True,
  236. allow_none=True,
  237. help="""
  238. Workspace name. If given, the workspace ID in the imported
  239. file will be replaced with a new ID pointing to this
  240. workspace name.
  241. """
  242. )
  243. aliases = {
  244. 'name': 'LabWorkspaceImportApp.workspace_name'
  245. }
  246. def start(self):
  247. app = LabApp(config=self.config)
  248. base_url = app.settings.get('base_url', '/')
  249. directory = app.workspaces_dir
  250. app_url = app.app_url
  251. workspaces_url = ujoin(app.app_url, 'workspaces')
  252. if len(self.extra_args) != 1:
  253. print('One argument is required for workspace import.')
  254. self.exit(1)
  255. workspace = dict()
  256. with self._smart_open() as fid:
  257. try: # to load, parse, and validate the workspace file.
  258. workspace = self._validate(fid, base_url, app_url, workspaces_url)
  259. except Exception as e:
  260. print('%s is not a valid workspace:\n%s' % (fid.name, e))
  261. self.exit(1)
  262. if not osp.exists(directory):
  263. try:
  264. os.makedirs(directory)
  265. except Exception as e:
  266. print('Workspaces directory could not be created:\n%s' % e)
  267. self.exit(1)
  268. slug = slugify(workspace['metadata']['id'], base_url)
  269. workspace_path = pjoin(directory, slug + WORKSPACE_EXTENSION)
  270. # Write the workspace data to a file.
  271. with open(workspace_path, 'w') as fid:
  272. fid.write(json.dumps(workspace))
  273. print('Saved workspace: %s' % workspace_path)
  274. def _smart_open(self):
  275. file_name = self.extra_args[0]
  276. if file_name == '-':
  277. return sys.stdin
  278. else:
  279. file_path = osp.abspath(file_name)
  280. if not osp.exists(file_path):
  281. print('%s does not exist.' % file_name)
  282. self.exit(1)
  283. return open(file_path)
  284. def _validate(self, data, base_url, app_url, workspaces_url):
  285. workspace = json.load(data)
  286. if 'data' not in workspace:
  287. raise Exception('The `data` field is missing.')
  288. # If workspace_name is set in config, inject the
  289. # name into the workspace metadata.
  290. if self.workspace_name is not None:
  291. if self.workspace_name == "":
  292. workspace_id = ujoin(base_url, app_url)
  293. else:
  294. workspace_id = ujoin(base_url, workspaces_url, self.workspace_name)
  295. workspace['metadata'] = {'id': workspace_id}
  296. # else check that the workspace_id is valid.
  297. else:
  298. if 'id' not in workspace['metadata']:
  299. raise Exception('The `id` field is missing in `metadata`.')
  300. else:
  301. id = workspace['metadata']['id']
  302. if id != ujoin(base_url, app_url) and not id.startswith(ujoin(base_url, workspaces_url)):
  303. error = '%s does not match app_url or start with workspaces_url.'
  304. raise Exception(error % id)
  305. return workspace
  306. class LabWorkspaceApp(JupyterApp):
  307. version = version
  308. description = """
  309. Import or export a JupyterLab workspace
  310. There are two sub-commands for export or import of workspaces. This app
  311. should not otherwise do any work.
  312. """
  313. subcommands = dict()
  314. subcommands['export'] = (
  315. LabWorkspaceExportApp,
  316. LabWorkspaceExportApp.description.splitlines()[0]
  317. )
  318. subcommands['import'] = (
  319. LabWorkspaceImportApp,
  320. LabWorkspaceImportApp.description.splitlines()[0]
  321. )
  322. def start(self):
  323. try:
  324. super().start()
  325. print('Either `export` or `import` must be specified.')
  326. self.exit(1)
  327. except NoStart:
  328. pass
  329. self.exit(0)
  330. aliases = dict(base_aliases)
  331. aliases.update({
  332. 'ip': 'ServerApp.ip',
  333. 'port': 'ServerApp.port',
  334. 'port-retries': 'ServerApp.port_retries',
  335. 'keyfile': 'ServerApp.keyfile',
  336. 'certfile': 'ServerApp.certfile',
  337. 'client-ca': 'ServerApp.client_ca',
  338. 'notebook-dir': 'ServerApp.root_dir',
  339. 'browser': 'ServerApp.browser',
  340. 'pylab': 'ServerApp.pylab',
  341. })
  342. class LabApp(NBClassicConfigShimMixin, LabServerApp):
  343. version = version
  344. name = "lab"
  345. app_name = "JupyterLab"
  346. # Should your extension expose other server extensions when launched directly?
  347. load_other_extensions = True
  348. description = """
  349. JupyterLab - An extensible computational environment for Jupyter.
  350. This launches a Tornado based HTML Server that serves up an
  351. HTML5/Javascript JupyterLab client.
  352. JupyterLab has three different modes of running:
  353. * Core mode (`--core-mode`): in this mode JupyterLab will run using the JavaScript
  354. assets contained in the installed `jupyterlab` Python package. In core mode, no
  355. extensions are enabled. This is the default in a stable JupyterLab release if you
  356. have no extensions installed.
  357. * Dev mode (`--dev-mode`): uses the unpublished local JavaScript packages in the
  358. `dev_mode` folder. In this case JupyterLab will show a red stripe at the top of
  359. the page. It can only be used if JupyterLab is installed as `pip install -e .`.
  360. * App mode: JupyterLab allows multiple JupyterLab "applications" to be
  361. created by the user with different combinations of extensions. The `--app-dir` can
  362. be used to set a directory for different applications. The default application
  363. path can be found using `jupyter lab path`.
  364. """
  365. examples = """
  366. jupyter lab # start JupyterLab
  367. jupyter lab --dev-mode # start JupyterLab in development mode, with no extensions
  368. jupyter lab --core-mode # start JupyterLab in core mode, with no extensions
  369. jupyter lab --app-dir=~/myjupyterlabapp # start JupyterLab with a particular set of extensions
  370. jupyter lab --certfile=mycert.pem # use SSL/TLS certificate
  371. """
  372. aliases = aliases
  373. aliases.update({
  374. 'watch': 'LabApp.watch',
  375. })
  376. aliases['app-dir'] = 'LabApp.app_dir'
  377. flags = flags
  378. flags['core-mode'] = (
  379. {'LabApp': {'core_mode': True}},
  380. "Start the app in core mode."
  381. )
  382. flags['dev-mode'] = (
  383. {'LabApp': {'dev_mode': True}},
  384. "Start the app in dev mode for running from source."
  385. )
  386. flags['watch'] = (
  387. {'LabApp': {'watch': True}},
  388. "Start the app in watch mode."
  389. )
  390. flags['expose-app-in-browser'] = (
  391. {'LabApp': {'expose_app_in_browser': True}},
  392. "Expose the global app instance to browser via window.jupyterlab."
  393. )
  394. flags['extensions-in-dev-mode'] = (
  395. {'LabApp': {'extensions_in_dev_mode': True}},
  396. "Load prebuilt extensions in dev-mode."
  397. )
  398. subcommands = dict(
  399. build=(LabBuildApp, LabBuildApp.description.splitlines()[0]),
  400. clean=(LabCleanApp, LabCleanApp.description.splitlines()[0]),
  401. path=(LabPathApp, LabPathApp.description.splitlines()[0]),
  402. paths=(LabPathApp, LabPathApp.description.splitlines()[0]),
  403. workspace=(LabWorkspaceApp, LabWorkspaceApp.description.splitlines()[0]),
  404. workspaces=(LabWorkspaceApp, LabWorkspaceApp.description.splitlines()[0])
  405. )
  406. default_url = Unicode('/lab', config=True,
  407. help="The default URL to redirect to from `/`")
  408. override_static_url = Unicode(config=True, help=('The override url for static lab assets, typically a CDN.'))
  409. override_theme_url = Unicode(config=True, help=('The override url for static lab theme assets, typically a CDN.'))
  410. app_dir = Unicode(None, config=True,
  411. help="The app directory to launch JupyterLab from.")
  412. user_settings_dir = Unicode(get_user_settings_dir(), config=True,
  413. help="The directory for user settings.")
  414. workspaces_dir = Unicode(get_workspaces_dir(), config=True,
  415. help="The directory for workspaces")
  416. core_mode = Bool(False, config=True,
  417. help="""Whether to start the app in core mode. In this mode, JupyterLab
  418. will run using the JavaScript assets that are within the installed
  419. JupyterLab Python package. In core mode, third party extensions are disabled.
  420. The `--dev-mode` flag is an alias to this to be used when the Python package
  421. itself is installed in development mode (`pip install -e .`).
  422. """)
  423. dev_mode = Bool(False, config=True,
  424. help="""Whether to start the app in dev mode. Uses the unpublished local
  425. JavaScript packages in the `dev_mode` folder. In this case JupyterLab will
  426. show a red stripe at the top of the page. It can only be used if JupyterLab
  427. is installed as `pip install -e .`.
  428. """)
  429. extensions_in_dev_mode = Bool(False, config=True,
  430. help="""Whether to load prebuilt extensions in dev mode. This may be
  431. useful to run and test prebuilt extensions in development installs of
  432. JupyterLab. APIs in a JupyterLab development install may be
  433. incompatible with published packages, so prebuilt extensions compiled
  434. against published packages may not work correctly.""")
  435. watch = Bool(False, config=True,
  436. help="Whether to serve the app in watch mode")
  437. expose_app_in_browser = Bool(False, config=True,
  438. help="Whether to expose the global app instance to browser via window.jupyterlab")
  439. # By default, open a browser for JupyterLab
  440. serverapp_config = {
  441. "open_browser": True
  442. }
  443. @default('app_dir')
  444. def _default_app_dir(self):
  445. app_dir = get_app_dir()
  446. if self.core_mode:
  447. app_dir = HERE
  448. elif self.dev_mode:
  449. app_dir = DEV_DIR
  450. return app_dir
  451. @default('app_settings_dir')
  452. def _default_app_settings_dir(self):
  453. return pjoin(self.app_dir, 'settings')
  454. @default('app_version')
  455. def _default_app_version(self):
  456. return app_version
  457. @default('cache_files')
  458. def _default_cache_files(self):
  459. return False
  460. @default('schemas_dir')
  461. def _default_schemas_dir(self):
  462. return pjoin(self.app_dir, 'schemas')
  463. @default('templates_dir')
  464. def _default_templates_dir(self):
  465. return pjoin(self.app_dir, 'static')
  466. @default('themes_dir')
  467. def _default_themes_dir(self):
  468. if self.override_theme_url:
  469. return ''
  470. return pjoin(self.app_dir, 'themes')
  471. @default('static_dir')
  472. def _default_static_dir(self):
  473. return pjoin(self.app_dir, 'static')
  474. @default('static_url_prefix')
  475. def _default_static_url_prefix(self):
  476. if self.override_static_url:
  477. return self.override_static_url
  478. else:
  479. static_url = "/static/{name}/".format(
  480. name=self.name)
  481. return ujoin(self.serverapp.base_url, static_url)
  482. @default('theme_url')
  483. def _default_theme_url(self):
  484. if self.override_theme_url:
  485. return self.override_theme_url
  486. return ''
  487. def initialize_templates(self):
  488. # Determine which model to run JupyterLab
  489. if self.core_mode or self.app_dir.startswith(HERE):
  490. self.core_mode = True
  491. self.log.info('Running JupyterLab in core mode')
  492. if self.dev_mode or self.app_dir.startswith(DEV_DIR):
  493. self.dev_mode = True
  494. self.log.info('Running JupyterLab in dev mode')
  495. if self.watch and self.core_mode:
  496. self.log.warn('Cannot watch in core mode, did you mean --dev-mode?')
  497. self.watch = False
  498. if self.core_mode and self.dev_mode:
  499. self.log.warn('Conflicting modes, choosing dev_mode over core_mode')
  500. self.core_mode = False
  501. # Set the paths based on JupyterLab's mode.
  502. if self.dev_mode:
  503. dev_static_dir = ujoin(DEV_DIR, 'static')
  504. self.static_paths = [dev_static_dir]
  505. self.template_paths = [dev_static_dir]
  506. if not self.extensions_in_dev_mode:
  507. self.labextensions_path = []
  508. self.extra_labextensions_path = []
  509. elif self.core_mode:
  510. dev_static_dir = ujoin(HERE, 'static')
  511. self.static_paths = [dev_static_dir]
  512. self.template_paths = [dev_static_dir]
  513. self.labextensions_path = []
  514. self.extra_labextensions_path = []
  515. else:
  516. self.static_paths = [self.static_dir]
  517. self.template_paths = [self.templates_dir]
  518. def initialize_settings(self):
  519. super().initialize_settings()
  520. def initialize_handlers(self):
  521. handlers = []
  522. # Set config for Jupyterlab
  523. page_config = self.serverapp.web_app.settings.setdefault('page_config_data', {})
  524. page_config.setdefault('buildAvailable', not self.core_mode and not self.dev_mode)
  525. page_config.setdefault('buildCheck', not self.core_mode and not self.dev_mode)
  526. page_config['devMode'] = self.dev_mode
  527. page_config['token'] = self.serverapp.token
  528. page_config['exposeAppInBrowser'] = self.expose_app_in_browser
  529. page_config['quitButton'] = self.serverapp.quit_button
  530. # Client-side code assumes notebookVersion is a JSON-encoded string
  531. page_config['notebookVersion'] = json.dumps(jpserver_version_info)
  532. if self.serverapp.file_to_run:
  533. relpath = os.path.relpath(self.serverapp.file_to_run, self.serverapp.root_dir)
  534. uri = url_escape(ujoin('{}/tree'.format(self.app_url), *relpath.split(os.sep)))
  535. self.default_url = uri
  536. self.serverapp.file_to_run = ''
  537. self.log.info('JupyterLab extension loaded from %s' % HERE)
  538. self.log.info('JupyterLab application directory is %s' % self.app_dir)
  539. build_handler_options = AppOptions(logger=self.log, app_dir=self.app_dir, labextensions_path = self.extra_labextensions_path + self.labextensions_path)
  540. builder = Builder(self.core_mode, app_options=build_handler_options)
  541. build_handler = (build_path, BuildHandler, {'builder': builder})
  542. handlers.append(build_handler)
  543. errored = False
  544. if self.core_mode:
  545. self.log.info(CORE_NOTE.strip())
  546. ensure_core(self.log)
  547. elif self.dev_mode:
  548. if not self.watch:
  549. ensure_dev(self.log)
  550. self.log.info(DEV_NOTE)
  551. else:
  552. msgs = ensure_app(self.app_dir)
  553. if msgs:
  554. [self.log.error(msg) for msg in msgs]
  555. handler = (self.app_url, ErrorHandler, { 'messages': msgs })
  556. handlers.append(handler)
  557. errored = True
  558. if self.watch:
  559. self.log.info('Starting JupyterLab watch mode...')
  560. if self.dev_mode:
  561. watch_dev(self.log)
  562. else:
  563. watch(app_options=build_handler_options)
  564. page_config['buildAvailable'] = False
  565. self.cache_files = False
  566. if not self.core_mode and not errored:
  567. ext_manager = ExtensionManager(app_options=build_handler_options)
  568. ext_handler = (
  569. extensions_handler_path,
  570. ExtensionHandler,
  571. {'manager': ext_manager}
  572. )
  573. handlers.append(ext_handler)
  574. # If running under JupyterHub, add more metadata.
  575. if hasattr(self, 'hub_prefix'):
  576. page_config['hubPrefix'] = self.hub_prefix
  577. page_config['hubHost'] = self.hub_host
  578. page_config['hubUser'] = self.user
  579. page_config['shareUrl'] = ujoin(self.hub_prefix, 'user-redirect')
  580. # Assume the server_name property indicates running JupyterHub 1.0.
  581. if hasattr(self, 'server_name'):
  582. page_config['hubServerName'] = self.server_name
  583. api_token = os.getenv('JUPYTERHUB_API_TOKEN', '')
  584. page_config['token'] = api_token
  585. # Update Jupyter Server's webapp settings with jupyterlab settings.
  586. self.serverapp.web_app.settings['page_config_data'] = page_config
  587. # Extend Server handlers with jupyterlab handlers.
  588. self.handlers.extend(handlers)
  589. super().initialize_handlers()
  590. def initialize(self, argv=None):
  591. """Subclass because the ExtensionApp.initialize() method does not take arguments"""
  592. super().initialize()
  593. #-----------------------------------------------------------------------------
  594. # Main entry point
  595. #-----------------------------------------------------------------------------
  596. main = launch_new_instance = LabApp.launch_instance
  597. if __name__ == '__main__':
  598. main()