labapp.py 26 KB

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