labapp.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  1. """A tornado based Jupyter lab server."""
  2. # Copyright (c) Jupyter Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. import dataclasses
  5. import json
  6. import os
  7. import sys
  8. from jupyter_core.application import JupyterApp, NoStart, base_aliases, base_flags
  9. from jupyter_server._version import version_info as jpserver_version_info
  10. from jupyter_server.serverapp import flags
  11. from jupyter_server.utils import url_path_join as ujoin
  12. from jupyterlab_server import (
  13. LabServerApp,
  14. LicensesApp,
  15. WorkspaceExportApp,
  16. WorkspaceImportApp,
  17. WorkspaceListApp,
  18. )
  19. from jupyterlab_server.config import get_static_page_config
  20. from notebook_shim.shim import NotebookConfigShimMixin
  21. from traitlets import Bool, Instance, Type, Unicode, default
  22. from ._version import __version__
  23. from .commands import (
  24. DEV_DIR,
  25. HERE,
  26. AppOptions,
  27. build,
  28. clean,
  29. ensure_app,
  30. ensure_core,
  31. ensure_dev,
  32. get_app_dir,
  33. get_app_version,
  34. get_user_settings_dir,
  35. get_workspaces_dir,
  36. pjoin,
  37. watch,
  38. watch_dev,
  39. )
  40. from .coreconfig import CoreConfig
  41. from .debuglog import DebugLogFileMixin
  42. from .extensions import MANAGERS as EXT_MANAGERS
  43. from .extensions.manager import PluginManager
  44. from .extensions.readonly import ReadOnlyExtensionManager
  45. from .handlers.announcements import (
  46. CheckForUpdate,
  47. CheckForUpdateABC,
  48. CheckForUpdateHandler,
  49. NewsHandler,
  50. check_update_handler_path,
  51. news_handler_path,
  52. )
  53. from .handlers.build_handler import Builder, BuildHandler, build_path
  54. from .handlers.error_handler import ErrorHandler
  55. from .handlers.extension_manager_handler import ExtensionHandler, extensions_handler_path
  56. from .handlers.plugin_manager_handler import PluginHandler, plugins_handler_path
  57. DEV_NOTE = """You're running JupyterLab from source.
  58. If you're working on the TypeScript sources of JupyterLab, try running
  59. jupyter lab --dev-mode --watch
  60. to have the system incrementally watch and build JupyterLab for you, as you
  61. make changes.
  62. """
  63. CORE_NOTE = """
  64. Running the core application with no additional extensions or settings
  65. """
  66. build_aliases = dict(base_aliases)
  67. build_aliases["app-dir"] = "LabBuildApp.app_dir"
  68. build_aliases["name"] = "LabBuildApp.name"
  69. build_aliases["version"] = "LabBuildApp.version"
  70. build_aliases["dev-build"] = "LabBuildApp.dev_build"
  71. build_aliases["minimize"] = "LabBuildApp.minimize"
  72. build_aliases["debug-log-path"] = "DebugLogFileMixin.debug_log_path"
  73. build_flags = dict(base_flags)
  74. build_flags["dev-build"] = (
  75. {"LabBuildApp": {"dev_build": True}},
  76. "Build in development mode.",
  77. )
  78. build_flags["no-minimize"] = (
  79. {"LabBuildApp": {"minimize": False}},
  80. "Do not minimize a production build.",
  81. )
  82. build_flags["splice-source"] = (
  83. {"LabBuildApp": {"splice_source": True}},
  84. "Splice source packages into app directory.",
  85. )
  86. version = __version__
  87. app_version = get_app_version()
  88. if version != app_version:
  89. version = f"{__version__} (dev), {app_version} (app)"
  90. build_failure_msg = """Build failed.
  91. Troubleshooting: If the build failed due to an out-of-memory error, you
  92. may be able to fix it by disabling the `dev_build` and/or `minimize` options.
  93. If you are building via the `jupyter lab build` command, you can disable
  94. these options like so:
  95. jupyter lab build --dev-build=False --minimize=False
  96. You can also disable these options for all JupyterLab builds by adding these
  97. lines to a Jupyter config file named `jupyter_config.py`:
  98. c.LabBuildApp.minimize = False
  99. c.LabBuildApp.dev_build = False
  100. If you don't already have a `jupyter_config.py` file, you can create one by
  101. adding a blank file of that name to any of the Jupyter config directories.
  102. The config directories can be listed by running:
  103. jupyter --paths
  104. Explanation:
  105. - `dev-build`: This option controls whether a `dev` or a more streamlined
  106. `production` build is used. This option will default to `False` (i.e., the
  107. `production` build) for most users. However, if you have any labextensions
  108. installed from local files, this option will instead default to `True`.
  109. Explicitly setting `dev-build` to `False` will ensure that the `production`
  110. build is used in all circumstances.
  111. - `minimize`: This option controls whether your JS bundle is minified
  112. during the Webpack build, which helps to improve JupyterLab's overall
  113. performance. However, the minifier plugin used by Webpack is very memory
  114. intensive, so turning it off may help the build finish successfully in
  115. low-memory environments.
  116. """
  117. class LabBuildApp(JupyterApp, DebugLogFileMixin):
  118. version = version
  119. description = """
  120. Build the JupyterLab application
  121. The application is built in the JupyterLab app directory in `/staging`.
  122. When the build is complete it is put in the JupyterLab app `/static`
  123. directory, where it is used to serve the application.
  124. """
  125. aliases = build_aliases
  126. flags = build_flags
  127. # Not configurable!
  128. core_config = Instance(CoreConfig, allow_none=True)
  129. app_dir = Unicode("", config=True, help="The app directory to build in")
  130. name = Unicode("JupyterLab", config=True, help="The name of the built application")
  131. version = Unicode("", config=True, help="The version of the built application")
  132. dev_build = Bool(
  133. None,
  134. allow_none=True,
  135. config=True,
  136. 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).",
  137. )
  138. minimize = Bool(
  139. True,
  140. config=True,
  141. help="Whether to minimize a production build (defaults to True).",
  142. )
  143. pre_clean = Bool(
  144. False, config=True, help="Whether to clean before building (defaults to False)"
  145. )
  146. splice_source = Bool(False, config=True, help="Splice source packages into app directory.")
  147. def start(self):
  148. app_dir = self.app_dir or get_app_dir()
  149. app_options = AppOptions(
  150. app_dir=app_dir,
  151. logger=self.log,
  152. core_config=self.core_config,
  153. splice_source=self.splice_source,
  154. )
  155. self.log.info(f"JupyterLab {version}")
  156. with self.debug_logging():
  157. if self.pre_clean:
  158. self.log.info(f"Cleaning {app_dir}")
  159. clean(app_options=app_options)
  160. self.log.info(f"Building in {app_dir}")
  161. try:
  162. production = None if self.dev_build is None else not self.dev_build
  163. build(
  164. name=self.name,
  165. version=self.version,
  166. app_options=app_options,
  167. production=production,
  168. minimize=self.minimize,
  169. )
  170. except Exception as e:
  171. self.log.error(build_failure_msg)
  172. raise e
  173. clean_aliases = dict(base_aliases)
  174. clean_aliases["app-dir"] = "LabCleanApp.app_dir"
  175. ext_warn_msg = "WARNING: this will delete all of your extensions, which will need to be reinstalled"
  176. clean_flags = dict(base_flags)
  177. clean_flags["extensions"] = (
  178. {"LabCleanApp": {"extensions": True}},
  179. f"Also delete <app-dir>/extensions.\n{ext_warn_msg}",
  180. )
  181. clean_flags["settings"] = (
  182. {"LabCleanApp": {"settings": True}},
  183. "Also delete <app-dir>/settings",
  184. )
  185. clean_flags["static"] = (
  186. {"LabCleanApp": {"static": True}},
  187. "Also delete <app-dir>/static",
  188. )
  189. clean_flags["all"] = (
  190. {"LabCleanApp": {"all": True}},
  191. f"Delete the entire contents of the app directory.\n{ext_warn_msg}",
  192. )
  193. class LabCleanAppOptions(AppOptions):
  194. extensions = Bool(False)
  195. settings = Bool(False)
  196. staging = Bool(True)
  197. static = Bool(False)
  198. all = Bool(False)
  199. class LabCleanApp(JupyterApp):
  200. version = version
  201. description = """
  202. Clean the JupyterLab application
  203. This will clean the app directory by removing the `staging` directories.
  204. Optionally, the `extensions`, `settings`, and/or `static` directories,
  205. or the entire contents of the app directory, can also be removed.
  206. """
  207. aliases = clean_aliases
  208. flags = clean_flags
  209. # Not configurable!
  210. core_config = Instance(CoreConfig, allow_none=True)
  211. app_dir = Unicode("", config=True, help="The app directory to clean")
  212. extensions = Bool(False, config=True, help=f"Also delete <app-dir>/extensions.\n{ext_warn_msg}")
  213. settings = Bool(False, config=True, help="Also delete <app-dir>/settings")
  214. static = Bool(False, config=True, help="Also delete <app-dir>/static")
  215. all = Bool(
  216. False,
  217. config=True,
  218. help=f"Delete the entire contents of the app directory.\n{ext_warn_msg}",
  219. )
  220. def start(self):
  221. app_options = LabCleanAppOptions(
  222. logger=self.log,
  223. core_config=self.core_config,
  224. app_dir=self.app_dir,
  225. extensions=self.extensions,
  226. settings=self.settings,
  227. static=self.static,
  228. all=self.all,
  229. )
  230. clean(app_options=app_options)
  231. class LabPathApp(JupyterApp):
  232. version = version
  233. description = """
  234. Print the configured paths for the JupyterLab application
  235. The application path can be configured using the JUPYTERLAB_DIR
  236. environment variable.
  237. The user settings path can be configured using the JUPYTERLAB_SETTINGS_DIR
  238. environment variable or it will fall back to
  239. `/lab/user-settings` in the default Jupyter configuration directory.
  240. The workspaces path can be configured using the JUPYTERLAB_WORKSPACES_DIR
  241. environment variable or it will fall back to
  242. '/lab/workspaces' in the default Jupyter configuration directory.
  243. """
  244. def start(self):
  245. print(f"Application directory: {get_app_dir()}")
  246. print(f"User Settings directory: {get_user_settings_dir()}")
  247. print(f"Workspaces directory: {get_workspaces_dir()}")
  248. class LabWorkspaceExportApp(WorkspaceExportApp):
  249. version = version
  250. @default("workspaces_dir")
  251. def _default_workspaces_dir(self):
  252. return get_workspaces_dir()
  253. class LabWorkspaceImportApp(WorkspaceImportApp):
  254. version = version
  255. @default("workspaces_dir")
  256. def _default_workspaces_dir(self):
  257. return get_workspaces_dir()
  258. class LabWorkspaceListApp(WorkspaceListApp):
  259. version = version
  260. @default("workspaces_dir")
  261. def _default_workspaces_dir(self):
  262. return get_workspaces_dir()
  263. class LabWorkspaceApp(JupyterApp):
  264. version = version
  265. description = """
  266. Import or export a JupyterLab workspace or list all the JupyterLab workspaces
  267. There are three sub-commands for export, import or listing of workspaces. This app
  268. should not otherwise do any work.
  269. """
  270. subcommands = {}
  271. subcommands["export"] = (
  272. LabWorkspaceExportApp,
  273. LabWorkspaceExportApp.description.splitlines()[0],
  274. )
  275. subcommands["import"] = (
  276. LabWorkspaceImportApp,
  277. LabWorkspaceImportApp.description.splitlines()[0],
  278. )
  279. subcommands["list"] = (
  280. LabWorkspaceListApp,
  281. LabWorkspaceListApp.description.splitlines()[0],
  282. )
  283. def start(self):
  284. try:
  285. super().start()
  286. self.log.error("One of `export`, `import` or `list` must be specified.")
  287. self.exit(1)
  288. except NoStart:
  289. pass
  290. self.exit(0)
  291. class LabLicensesApp(LicensesApp):
  292. version = version
  293. dev_mode = Bool(
  294. False,
  295. config=True,
  296. help="""Whether to start the app in dev mode. Uses the unpublished local
  297. JavaScript packages in the `dev_mode` folder. In this case JupyterLab will
  298. show a red stripe at the top of the page. It can only be used if JupyterLab
  299. is installed as `pip install -e .`.
  300. """,
  301. )
  302. app_dir = Unicode("", config=True, help="The app directory for which to show licenses")
  303. aliases = {
  304. **LicensesApp.aliases,
  305. "app-dir": "LabLicensesApp.app_dir",
  306. }
  307. flags = {
  308. **LicensesApp.flags,
  309. "dev-mode": (
  310. {"LabLicensesApp": {"dev_mode": True}},
  311. "Start the app in dev mode for running from source.",
  312. ),
  313. }
  314. @default("app_dir")
  315. def _default_app_dir(self):
  316. return get_app_dir()
  317. @default("static_dir")
  318. def _default_static_dir(self):
  319. return pjoin(self.app_dir, "static")
  320. aliases = dict(base_aliases)
  321. aliases.update(
  322. {
  323. "ip": "ServerApp.ip",
  324. "port": "ServerApp.port",
  325. "port-retries": "ServerApp.port_retries",
  326. "keyfile": "ServerApp.keyfile",
  327. "certfile": "ServerApp.certfile",
  328. "client-ca": "ServerApp.client_ca",
  329. "notebook-dir": "ServerApp.root_dir",
  330. "browser": "ServerApp.browser",
  331. "pylab": "ServerApp.pylab",
  332. }
  333. )
  334. class LabApp(NotebookConfigShimMixin, LabServerApp):
  335. version = version
  336. name = "lab"
  337. app_name = "JupyterLab"
  338. # Should your extension expose other server extensions when launched directly?
  339. load_other_extensions = True
  340. description = """
  341. JupyterLab - An extensible computational environment for Jupyter.
  342. This launches a Tornado based HTML Server that serves up an
  343. HTML5/Javascript JupyterLab client.
  344. JupyterLab has three different modes of running:
  345. * Core mode (`--core-mode`): in this mode JupyterLab will run using the JavaScript
  346. assets contained in the installed `jupyterlab` Python package. In core mode, no
  347. extensions are enabled. This is the default in a stable JupyterLab release if you
  348. have no extensions installed.
  349. * Dev mode (`--dev-mode`): uses the unpublished local JavaScript packages in the
  350. `dev_mode` folder. In this case JupyterLab will show a red stripe at the top of
  351. the page. It can only be used if JupyterLab is installed as `pip install -e .`.
  352. * App mode: JupyterLab allows multiple JupyterLab "applications" to be
  353. created by the user with different combinations of extensions. The `--app-dir` can
  354. be used to set a directory for different applications. The default application
  355. path can be found using `jupyter lab path`.
  356. """
  357. examples = """
  358. jupyter lab # start JupyterLab
  359. jupyter lab --dev-mode # start JupyterLab in development mode, with no extensions
  360. jupyter lab --core-mode # start JupyterLab in core mode, with no extensions
  361. jupyter lab --app-dir=~/myjupyterlabapp # start JupyterLab with a particular set of extensions
  362. jupyter lab --certfile=mycert.pem # use SSL/TLS certificate
  363. """
  364. aliases = aliases
  365. aliases.update(
  366. {
  367. "watch": "LabApp.watch",
  368. }
  369. )
  370. aliases["app-dir"] = "LabApp.app_dir"
  371. flags = flags
  372. flags["core-mode"] = (
  373. {"LabApp": {"core_mode": True}},
  374. "Start the app in core mode.",
  375. )
  376. flags["dev-mode"] = (
  377. {"LabApp": {"dev_mode": True}},
  378. "Start the app in dev mode for running from source.",
  379. )
  380. flags["skip-dev-build"] = (
  381. {"LabApp": {"skip_dev_build": True}},
  382. "Skip the initial install and JS build of the app in dev mode.",
  383. )
  384. flags["watch"] = ({"LabApp": {"watch": True}}, "Start the app in watch mode.")
  385. flags["splice-source"] = (
  386. {"LabApp": {"splice_source": True}},
  387. "Splice source packages into app directory.",
  388. )
  389. flags["expose-app-in-browser"] = (
  390. {"LabApp": {"expose_app_in_browser": True}},
  391. "Expose the global app instance to browser via window.jupyterapp.",
  392. )
  393. flags["extensions-in-dev-mode"] = (
  394. {"LabApp": {"extensions_in_dev_mode": True}},
  395. "Load prebuilt extensions in dev-mode.",
  396. )
  397. flags["collaborative"] = (
  398. {"LabApp": {"collaborative": True}},
  399. """To enable real-time collaboration, you must install the extension `jupyter_collaboration`.
  400. You can install it using pip for example:
  401. python -m pip install jupyter_collaboration
  402. This flag is now deprecated and will be removed in JupyterLab v5.""",
  403. )
  404. flags["custom-css"] = (
  405. {"LabApp": {"custom_css": True}},
  406. "Load custom CSS in template html files. Default is False",
  407. )
  408. subcommands = {
  409. "build": (LabBuildApp, LabBuildApp.description.splitlines()[0]),
  410. "clean": (LabCleanApp, LabCleanApp.description.splitlines()[0]),
  411. "path": (LabPathApp, LabPathApp.description.splitlines()[0]),
  412. "paths": (LabPathApp, LabPathApp.description.splitlines()[0]),
  413. "workspace": (LabWorkspaceApp, LabWorkspaceApp.description.splitlines()[0]),
  414. "workspaces": (LabWorkspaceApp, LabWorkspaceApp.description.splitlines()[0]),
  415. "licenses": (LabLicensesApp, LabLicensesApp.description.splitlines()[0]),
  416. }
  417. default_url = Unicode("/lab", config=True, help="The default URL to redirect to from `/`")
  418. override_static_url = Unicode(
  419. config=True, help=("The override url for static lab assets, typically a CDN.")
  420. )
  421. override_theme_url = Unicode(
  422. config=True,
  423. help=("The override url for static lab theme assets, typically a CDN."),
  424. )
  425. app_dir = Unicode(None, config=True, help="The app directory to launch JupyterLab from.")
  426. user_settings_dir = Unicode(
  427. get_user_settings_dir(), config=True, help="The directory for user settings."
  428. )
  429. workspaces_dir = Unicode(get_workspaces_dir(), config=True, help="The directory for workspaces")
  430. core_mode = Bool(
  431. False,
  432. config=True,
  433. help="""Whether to start the app in core mode. In this mode, JupyterLab
  434. will run using the JavaScript assets that are within the installed
  435. JupyterLab Python package. In core mode, third party extensions are disabled.
  436. The `--dev-mode` flag is an alias to this to be used when the Python package
  437. itself is installed in development mode (`pip install -e .`).
  438. """,
  439. )
  440. dev_mode = Bool(
  441. False,
  442. config=True,
  443. help="""Whether to start the app in dev mode. Uses the unpublished local
  444. JavaScript packages in the `dev_mode` folder. In this case JupyterLab will
  445. show a red stripe at the top of the page. It can only be used if JupyterLab
  446. is installed as `pip install -e .`.
  447. """,
  448. )
  449. extensions_in_dev_mode = Bool(
  450. False,
  451. config=True,
  452. help="""Whether to load prebuilt extensions in dev mode. This may be
  453. useful to run and test prebuilt extensions in development installs of
  454. JupyterLab. APIs in a JupyterLab development install may be
  455. incompatible with published packages, so prebuilt extensions compiled
  456. against published packages may not work correctly.""",
  457. )
  458. extension_manager = Unicode(
  459. "pypi",
  460. config=True,
  461. help="""The extension manager factory to use. The default options are:
  462. "readonly" for a manager without installation capability or "pypi" for
  463. a manager using PyPi.org and pip to install extensions.""",
  464. )
  465. watch = Bool(False, config=True, help="Whether to serve the app in watch mode")
  466. skip_dev_build = Bool(
  467. False,
  468. config=True,
  469. help="Whether to skip the initial install and JS build of the app in dev mode",
  470. )
  471. splice_source = Bool(False, config=True, help="Splice source packages into app directory.")
  472. expose_app_in_browser = Bool(
  473. False,
  474. config=True,
  475. help="Whether to expose the global app instance to browser via window.jupyterapp",
  476. )
  477. custom_css = Bool(
  478. False,
  479. config=True,
  480. help="""Whether custom CSS is loaded on the page.
  481. Defaults to False.
  482. """,
  483. )
  484. collaborative = Bool(
  485. False,
  486. config=True,
  487. help="""To enable real-time collaboration, you must install the extension `jupyter_collaboration`.
  488. You can install it using pip for example:
  489. python -m pip install jupyter_collaboration
  490. This flag is now deprecated and will be removed in JupyterLab v5.""",
  491. )
  492. news_url = Unicode(
  493. "https://jupyterlab.github.io/assets/feed.xml",
  494. allow_none=True,
  495. help="""URL that serves news Atom feed; by default the JupyterLab organization announcements will be fetched. Set to None to turn off fetching announcements.""",
  496. config=True,
  497. )
  498. lock_all_plugins = Bool(
  499. False,
  500. config=True,
  501. help="Whether all plugins are locked (cannot be enabled/disabled from the UI)",
  502. )
  503. check_for_updates_class = Type(
  504. default_value=CheckForUpdate,
  505. klass=CheckForUpdateABC,
  506. config=True,
  507. help="""A callable class that receives the current version at instantiation and calling it must return asynchronously a string indicating which version is available and how to install or None if no update is available. The string supports Markdown format.""",
  508. )
  509. @default("app_dir")
  510. def _default_app_dir(self):
  511. app_dir = get_app_dir()
  512. if self.core_mode:
  513. app_dir = HERE
  514. elif self.dev_mode:
  515. app_dir = DEV_DIR
  516. return app_dir
  517. @default("app_settings_dir")
  518. def _default_app_settings_dir(self):
  519. return pjoin(self.app_dir, "settings")
  520. @default("app_version")
  521. def _default_app_version(self):
  522. return app_version
  523. @default("cache_files")
  524. def _default_cache_files(self):
  525. return False
  526. @default("schemas_dir")
  527. def _default_schemas_dir(self):
  528. return pjoin(self.app_dir, "schemas")
  529. @default("templates_dir")
  530. def _default_templates_dir(self):
  531. return pjoin(self.app_dir, "static")
  532. @default("themes_dir")
  533. def _default_themes_dir(self):
  534. if self.override_theme_url:
  535. return ""
  536. return pjoin(self.app_dir, "themes")
  537. @default("static_dir")
  538. def _default_static_dir(self):
  539. return pjoin(self.app_dir, "static")
  540. @default("static_url_prefix")
  541. def _default_static_url_prefix(self):
  542. if self.override_static_url:
  543. return self.override_static_url
  544. else:
  545. static_url = f"/static/{self.name}/"
  546. return ujoin(self.serverapp.base_url, static_url)
  547. @default("theme_url")
  548. def _default_theme_url(self):
  549. if self.override_theme_url:
  550. return self.override_theme_url
  551. return ""
  552. def initialize_templates(self):
  553. # Determine which model to run JupyterLab
  554. if self.core_mode or self.app_dir.startswith(HERE + os.sep):
  555. self.core_mode = True
  556. self.log.info("Running JupyterLab in core mode")
  557. if self.dev_mode or self.app_dir.startswith(DEV_DIR + os.sep):
  558. self.dev_mode = True
  559. self.log.info("Running JupyterLab in dev mode")
  560. if self.watch and self.core_mode:
  561. self.log.warning("Cannot watch in core mode, did you mean --dev-mode?")
  562. self.watch = False
  563. if self.core_mode and self.dev_mode:
  564. self.log.warning("Conflicting modes, choosing dev_mode over core_mode")
  565. self.core_mode = False
  566. # Set the paths based on JupyterLab's mode.
  567. if self.dev_mode:
  568. dev_static_dir = ujoin(DEV_DIR, "static")
  569. self.static_paths = [dev_static_dir]
  570. self.template_paths = [dev_static_dir]
  571. if not self.extensions_in_dev_mode:
  572. # Add an exception for @jupyterlab/galata-extension
  573. galata_extension = pjoin(HERE, "galata")
  574. self.labextensions_path = (
  575. [galata_extension]
  576. if galata_extension in map(os.path.abspath, self.labextensions_path)
  577. else []
  578. )
  579. self.extra_labextensions_path = (
  580. [galata_extension]
  581. if galata_extension in map(os.path.abspath, self.extra_labextensions_path)
  582. else []
  583. )
  584. elif self.core_mode:
  585. dev_static_dir = ujoin(HERE, "static")
  586. self.static_paths = [dev_static_dir]
  587. self.template_paths = [dev_static_dir]
  588. self.labextensions_path = []
  589. self.extra_labextensions_path = []
  590. else:
  591. self.static_paths = [self.static_dir]
  592. self.template_paths = [self.templates_dir]
  593. def _prepare_templates(self):
  594. super()._prepare_templates()
  595. self.jinja2_env.globals.update(custom_css=self.custom_css)
  596. def initialize_handlers(self): # noqa
  597. handlers = []
  598. # Set config for Jupyterlab
  599. page_config = self.serverapp.web_app.settings.setdefault("page_config_data", {})
  600. page_config.update(get_static_page_config(logger=self.log, level="all"))
  601. page_config.setdefault("buildAvailable", not self.core_mode and not self.dev_mode)
  602. page_config.setdefault("buildCheck", not self.core_mode and not self.dev_mode)
  603. page_config["devMode"] = self.dev_mode
  604. page_config["token"] = self.serverapp.identity_provider.token
  605. page_config["exposeAppInBrowser"] = self.expose_app_in_browser
  606. page_config["quitButton"] = self.serverapp.quit_button
  607. page_config["allow_hidden_files"] = self.serverapp.contents_manager.allow_hidden
  608. if hasattr(self.serverapp.contents_manager, "delete_to_trash"):
  609. page_config["delete_to_trash"] = self.serverapp.contents_manager.delete_to_trash
  610. # Client-side code assumes notebookVersion is a JSON-encoded string
  611. page_config["notebookVersion"] = json.dumps(jpserver_version_info)
  612. self.log.info(f"JupyterLab extension loaded from {HERE!s}")
  613. self.log.info(f"JupyterLab application directory is {self.app_dir!s}")
  614. if self.custom_css:
  615. handlers.append(
  616. (
  617. r"/custom/(.*)(?<!\.js)$",
  618. self.serverapp.web_app.settings["static_handler_class"],
  619. {
  620. "path": self.serverapp.web_app.settings["static_custom_path"],
  621. "no_cache_paths": ["/"], # don't cache anything in custom
  622. },
  623. )
  624. )
  625. app_options = AppOptions(
  626. logger=self.log,
  627. app_dir=self.app_dir,
  628. labextensions_path=self.extra_labextensions_path + self.labextensions_path,
  629. splice_source=self.splice_source,
  630. )
  631. builder = Builder(self.core_mode, app_options=app_options)
  632. build_handler = (build_path, BuildHandler, {"builder": builder})
  633. handlers.append(build_handler)
  634. errored = False
  635. if self.core_mode:
  636. self.log.info(CORE_NOTE.strip())
  637. ensure_core(self.log)
  638. elif self.dev_mode:
  639. if not (self.watch or self.skip_dev_build):
  640. ensure_dev(self.log)
  641. self.log.info(DEV_NOTE)
  642. else:
  643. if self.splice_source:
  644. ensure_dev(self.log)
  645. msgs = ensure_app(self.app_dir)
  646. if msgs:
  647. [self.log.error(msg) for msg in msgs]
  648. handler = (self.app_url, ErrorHandler, {"messages": msgs})
  649. handlers.append(handler)
  650. errored = True
  651. if self.watch:
  652. self.log.info("Starting JupyterLab watch mode...")
  653. if self.dev_mode:
  654. watch_dev(self.log)
  655. else:
  656. watch(app_options=app_options)
  657. page_config["buildAvailable"] = False
  658. self.cache_files = False
  659. if not self.core_mode and not errored:
  660. # Add extension management handlers
  661. provider = self.extension_manager
  662. entry_point = EXT_MANAGERS.get(provider)
  663. if entry_point is None:
  664. self.log.error(f"Extension Manager: No manager defined for provider '{provider}'.")
  665. raise NotImplementedError()
  666. else:
  667. self.log.info(f"Extension Manager is '{provider}'.")
  668. manager_factory = entry_point.load()
  669. config = self.settings.get("config", {}).get("LabServerApp", {})
  670. blocked_extensions_uris = config.get("blocked_extensions_uris", "")
  671. allowed_extensions_uris = config.get("allowed_extensions_uris", "")
  672. if (blocked_extensions_uris) and (allowed_extensions_uris):
  673. self.log.error(
  674. "Simultaneous LabServerApp.blocked_extensions_uris and LabServerApp.allowed_extensions_uris is not supported. Please define only one of those."
  675. )
  676. import sys
  677. sys.exit(-1)
  678. listings_config = {
  679. "blocked_extensions_uris": set(
  680. filter(lambda uri: len(uri) > 0, blocked_extensions_uris.split(","))
  681. ),
  682. "allowed_extensions_uris": set(
  683. filter(lambda uri: len(uri) > 0, allowed_extensions_uris.split(","))
  684. ),
  685. "listings_refresh_seconds": config.get("listings_refresh_seconds", 60 * 60),
  686. "listings_tornado_options": config.get("listings_tornado_options", {}),
  687. }
  688. if len(listings_config["blocked_extensions_uris"]) or len(
  689. listings_config["allowed_extensions_uris"]
  690. ):
  691. self.log.debug(f"Extension manager will be constrained by {listings_config}")
  692. try:
  693. ext_manager = manager_factory(app_options, listings_config, self)
  694. metadata = dataclasses.asdict(ext_manager.metadata)
  695. except Exception as err:
  696. self.log.warning(
  697. f"Failed to instantiate the extension manager {provider}. Falling back to read-only manager.",
  698. exc_info=err,
  699. )
  700. ext_manager = ReadOnlyExtensionManager(app_options, listings_config, self)
  701. metadata = dataclasses.asdict(ext_manager.metadata)
  702. page_config["extensionManager"] = metadata
  703. ext_handler = (
  704. extensions_handler_path,
  705. ExtensionHandler,
  706. {"manager": ext_manager},
  707. )
  708. handlers.append(ext_handler)
  709. # Add plugin manager handlers
  710. lock_rules = frozenset(
  711. {rule for rule, value in page_config.get("lockedExtensions", {}).items() if value}
  712. )
  713. handlers.append(
  714. (
  715. plugins_handler_path,
  716. PluginHandler,
  717. {
  718. "manager": PluginManager(
  719. app_options=app_options,
  720. ext_options={
  721. "lock_rules": lock_rules,
  722. "all_locked": self.lock_all_plugins,
  723. },
  724. parent=self,
  725. )
  726. },
  727. )
  728. )
  729. # Add announcement handlers
  730. page_config["news"] = {"disabled": self.news_url is None}
  731. handlers.extend(
  732. [
  733. (
  734. check_update_handler_path,
  735. CheckForUpdateHandler,
  736. {
  737. "update_checker": self.check_for_updates_class(__version__),
  738. },
  739. ),
  740. (
  741. news_handler_path,
  742. NewsHandler,
  743. {
  744. "news_url": self.news_url,
  745. },
  746. ),
  747. ]
  748. )
  749. # If running under JupyterHub, add more metadata.
  750. if "hub_prefix" in self.serverapp.tornado_settings:
  751. tornado_settings = self.serverapp.tornado_settings
  752. hub_prefix = tornado_settings["hub_prefix"]
  753. page_config["hubPrefix"] = hub_prefix
  754. page_config["hubHost"] = tornado_settings["hub_host"]
  755. page_config["hubUser"] = tornado_settings["user"]
  756. page_config["shareUrl"] = ujoin(hub_prefix, "user-redirect")
  757. # Assume the server_name property indicates running JupyterHub 1.0.
  758. if hasattr(self.serverapp, "server_name"):
  759. page_config["hubServerName"] = self.serverapp.server_name
  760. # avoid setting API token in page config
  761. # $JUPYTERHUB_API_TOKEN identifies the server, not the client
  762. # but at least make sure we don't use the token
  763. # if the serverapp set one
  764. page_config["token"] = ""
  765. # Update Jupyter Server's webapp settings with jupyterlab settings.
  766. self.serverapp.web_app.settings["page_config_data"] = page_config
  767. # Extend Server handlers with jupyterlab handlers.
  768. self.handlers.extend(handlers)
  769. super().initialize_handlers()
  770. def initialize(self, argv=None):
  771. """Subclass because the ExtensionApp.initialize() method does not take arguments"""
  772. super().initialize()
  773. if self.collaborative:
  774. try:
  775. import jupyter_collaboration # noqa
  776. except ImportError:
  777. self.log.critical(
  778. """\
  779. Jupyter Lab cannot start, because `jupyter_collaboration` was configured but cannot be `import`ed.
  780. To fix this, either:
  781. 1) install the extension `jupyter-collaboration`; for example: `python -m pip install jupyter-collaboration`
  782. 2) disable collaboration; for example, remove the `--collaborative` flag from the commandline. To see more ways to adjust the collaborative behavior, see https://jupyterlab-realtime-collaboration.readthedocs.io/en/latest/configuration.html .
  783. """
  784. )
  785. sys.exit(1)
  786. # -----------------------------------------------------------------------------
  787. # Main entry point
  788. # -----------------------------------------------------------------------------
  789. main = launch_new_instance = LabApp.launch_instance
  790. if __name__ == "__main__":
  791. main()