labapp.py 25 KB

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