config.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. """JupyterLab Server config"""
  2. # Copyright (c) Jupyter Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from __future__ import annotations
  5. import json
  6. import os.path as osp
  7. from glob import iglob
  8. from itertools import chain
  9. from logging import Logger
  10. from os.path import join as pjoin
  11. from typing import Any
  12. import json5
  13. from jupyter_core.paths import SYSTEM_CONFIG_PATH, jupyter_config_dir, jupyter_path
  14. from jupyter_server.services.config.manager import ConfigManager, recursive_update
  15. from jupyter_server.utils import url_path_join as ujoin
  16. from traitlets import Bool, HasTraits, List, Unicode, default
  17. # -----------------------------------------------------------------------------
  18. # Module globals
  19. # -----------------------------------------------------------------------------
  20. DEFAULT_TEMPLATE_PATH = osp.join(osp.dirname(__file__), "templates")
  21. def get_package_url(data: dict[str, Any]) -> str:
  22. """Get the url from the extension data"""
  23. # homepage, repository are optional
  24. if "homepage" in data:
  25. url = data["homepage"]
  26. elif "repository" in data and isinstance(data["repository"], dict):
  27. url = data["repository"].get("url", "")
  28. else:
  29. url = ""
  30. return url
  31. def get_federated_extensions(labextensions_path: list[str]) -> dict[str, Any]:
  32. """Get the metadata about federated extensions"""
  33. federated_extensions = {}
  34. for ext_dir in labextensions_path:
  35. # extensions are either top-level directories, or two-deep in @org directories
  36. for ext_path in chain(
  37. iglob(pjoin(ext_dir, "[!@]*", "package.json")),
  38. iglob(pjoin(ext_dir, "@*", "*", "package.json")),
  39. ):
  40. with open(ext_path, encoding="utf-8") as fid:
  41. pkgdata = json.load(fid)
  42. if pkgdata["name"] not in federated_extensions:
  43. data = dict(
  44. name=pkgdata["name"],
  45. version=pkgdata["version"],
  46. description=pkgdata.get("description", ""),
  47. url=get_package_url(pkgdata),
  48. ext_dir=ext_dir,
  49. ext_path=osp.dirname(ext_path),
  50. is_local=False,
  51. dependencies=pkgdata.get("dependencies", dict()),
  52. jupyterlab=pkgdata.get("jupyterlab", dict()),
  53. )
  54. # Add repository info if available
  55. if "repository" in pkgdata and "url" in pkgdata.get("repository", {}):
  56. data["repository"] = dict(url=pkgdata.get("repository").get("url"))
  57. install_path = osp.join(osp.dirname(ext_path), "install.json")
  58. if osp.exists(install_path):
  59. with open(install_path, encoding="utf-8") as fid:
  60. data["install"] = json.load(fid)
  61. federated_extensions[data["name"]] = data
  62. return federated_extensions
  63. def get_static_page_config(
  64. app_settings_dir: str | None = None, # noqa: ARG001
  65. logger: Logger | None = None, # noqa: ARG001
  66. level: str = "all",
  67. include_higher_levels: bool = False,
  68. ) -> dict[str, Any]:
  69. """Get the static page config for JupyterLab
  70. Parameters
  71. ----------
  72. logger: logger, optional
  73. An optional logging object
  74. level: string, optional ['all']
  75. The level at which to get config: can be 'all', 'user', 'sys_prefix', or 'system'
  76. """
  77. cm = _get_config_manager(level, include_higher_levels)
  78. return cm.get("page_config") # type:ignore[no-untyped-call]
  79. def load_config(path: str) -> Any:
  80. """Load either a json5 or a json config file.
  81. Parameters
  82. ----------
  83. path : str
  84. Path to the file to be loaded
  85. Returns
  86. -------
  87. Dict[Any, Any]
  88. Dictionary of json or json5 data
  89. """
  90. with open(path, encoding="utf-8") as fid:
  91. if path.endswith(".json5"):
  92. return json5.load(fid)
  93. return json.load(fid)
  94. def get_page_config(
  95. labextensions_path: list[str], app_settings_dir: str | None = None, logger: Logger | None = None
  96. ) -> dict[str, Any]:
  97. """Get the page config for the application handler"""
  98. # Build up the full page config
  99. page_config: dict = {}
  100. disabled_key = "disabledExtensions"
  101. # Start with the app_settings_dir as lowest priority
  102. if app_settings_dir:
  103. config_paths = [
  104. pjoin(app_settings_dir, "page_config.json5"),
  105. pjoin(app_settings_dir, "page_config.json"),
  106. ]
  107. for path in config_paths:
  108. if osp.exists(path) and osp.getsize(path):
  109. data = load_config(path)
  110. # Convert lists to dicts
  111. for key in [disabled_key, "deferredExtensions"]:
  112. if key in data:
  113. data[key] = {key: True for key in data[key]}
  114. recursive_update(page_config, data)
  115. break
  116. # Get the traitlets config
  117. static_page_config = get_static_page_config(logger=logger, level="all")
  118. recursive_update(page_config, static_page_config)
  119. # Handle federated extensions that disable other extensions
  120. disabled_by_extensions_all = {}
  121. extensions = page_config["federated_extensions"] = []
  122. federated_exts = get_federated_extensions(labextensions_path)
  123. # Ensure there is a disabled key
  124. page_config.setdefault(disabled_key, {})
  125. for _, ext_data in federated_exts.items():
  126. if "_build" not in ext_data["jupyterlab"]:
  127. if logger:
  128. logger.warning("%s is not a valid extension", ext_data["name"])
  129. continue
  130. extbuild = ext_data["jupyterlab"]["_build"]
  131. extension = {"name": ext_data["name"], "load": extbuild["load"]}
  132. if "extension" in extbuild:
  133. extension["extension"] = extbuild["extension"]
  134. if "mimeExtension" in extbuild:
  135. extension["mimeExtension"] = extbuild["mimeExtension"]
  136. if "style" in extbuild:
  137. extension["style"] = extbuild["style"]
  138. # FIXME @experimental for plugin with no-code entrypoints.
  139. extension["entrypoints"] = extbuild.get("entrypoints")
  140. extensions.append(extension)
  141. # If there is disabledExtensions metadata, consume it.
  142. name = ext_data["name"]
  143. if ext_data["jupyterlab"].get(disabled_key):
  144. disabled_by_extensions_all[ext_data["name"]] = ext_data["jupyterlab"][disabled_key]
  145. # Handle source extensions that disable other extensions
  146. # Check for `jupyterlab`:`extensionMetadata` in the built application directory's package.json
  147. if app_settings_dir:
  148. app_dir = osp.dirname(app_settings_dir)
  149. package_data_file = pjoin(app_dir, "static", "package.json")
  150. if osp.exists(package_data_file):
  151. with open(package_data_file, encoding="utf-8") as fid:
  152. app_data = json.load(fid)
  153. all_ext_data = app_data["jupyterlab"].get("extensionMetadata", {})
  154. for ext, ext_data in all_ext_data.items():
  155. if ext in disabled_by_extensions_all:
  156. continue
  157. if ext_data.get(disabled_key):
  158. disabled_by_extensions_all[ext] = ext_data[disabled_key]
  159. disabled_by_extensions = {}
  160. for name in sorted(disabled_by_extensions_all):
  161. # skip if the extension itself is disabled by other config
  162. if page_config[disabled_key].get(name) is True:
  163. continue
  164. disabled_list = disabled_by_extensions_all[name]
  165. for item in disabled_list:
  166. disabled_by_extensions[item] = True
  167. rollup_disabled = disabled_by_extensions
  168. rollup_disabled.update(page_config.get(disabled_key, []))
  169. page_config[disabled_key] = rollup_disabled
  170. # Convert dictionaries to lists to give to the front end
  171. for key, value in page_config.items():
  172. if isinstance(value, dict):
  173. page_config[key] = [subkey for subkey in value if value[subkey]]
  174. return page_config
  175. def write_page_config(page_config: dict[str, Any], level: str = "all") -> None:
  176. """Write page config to disk"""
  177. cm = _get_config_manager(level)
  178. cm.set("page_config", page_config) # type:ignore[no-untyped-call]
  179. class LabConfig(HasTraits):
  180. """The lab application configuration object."""
  181. app_name = Unicode("", help="The name of the application.").tag(config=True)
  182. app_version = Unicode("", help="The version of the application.").tag(config=True)
  183. app_namespace = Unicode("", help="The namespace of the application.").tag(config=True)
  184. app_url = Unicode("/lab", help="The url path for the application.").tag(config=True)
  185. app_settings_dir = Unicode("", help="The application settings directory.").tag(config=True)
  186. extra_labextensions_path = List(
  187. Unicode(), help="""Extra paths to look for federated JupyterLab extensions"""
  188. ).tag(config=True)
  189. labextensions_path = List(
  190. Unicode(), help="The standard paths to look in for federated JupyterLab extensions"
  191. ).tag(config=True)
  192. templates_dir = Unicode("", help="The application templates directory.").tag(config=True)
  193. static_dir = Unicode(
  194. "",
  195. help=(
  196. "The optional location of local static files. "
  197. "If given, a static file handler will be "
  198. "added."
  199. ),
  200. ).tag(config=True)
  201. labextensions_url = Unicode("", help="The url for federated JupyterLab extensions").tag(
  202. config=True
  203. )
  204. settings_url = Unicode(help="The url path of the settings handler.").tag(config=True)
  205. user_settings_dir = Unicode(
  206. "", help=("The optional location of the user settings directory.")
  207. ).tag(config=True)
  208. schemas_dir = Unicode(
  209. "",
  210. help=(
  211. "The optional location of the settings "
  212. "schemas directory. If given, a handler will "
  213. "be added for settings."
  214. ),
  215. ).tag(config=True)
  216. workspaces_api_url = Unicode(help="The url path of the workspaces API.").tag(config=True)
  217. workspaces_dir = Unicode(
  218. "",
  219. help=(
  220. "The optional location of the saved "
  221. "workspaces directory. If given, a handler "
  222. "will be added for workspaces."
  223. ),
  224. ).tag(config=True)
  225. listings_url = Unicode(help="The listings url.").tag(config=True)
  226. themes_url = Unicode(help="The theme url.").tag(config=True)
  227. licenses_url = Unicode(help="The third-party licenses url.")
  228. themes_dir = Unicode(
  229. "",
  230. help=(
  231. "The optional location of the themes "
  232. "directory. If given, a handler will be added "
  233. "for themes."
  234. ),
  235. ).tag(config=True)
  236. translations_api_url = Unicode(help="The url path of the translations handler.").tag(
  237. config=True
  238. )
  239. tree_url = Unicode(help="The url path of the tree handler.").tag(config=True)
  240. cache_files = Bool(
  241. True,
  242. help=("Whether to cache files on the server. This should be `True` except in dev mode."),
  243. ).tag(config=True)
  244. notebook_starts_kernel = Bool(
  245. True, help="Whether a notebook should start a kernel automatically."
  246. ).tag(config=True)
  247. copy_absolute_path = Bool(
  248. False,
  249. help="Whether getting a relative (False) or absolute (True) path when copying a path.",
  250. ).tag(config=True)
  251. @default("templates_dir")
  252. def _default_templates_dir(self) -> str:
  253. return DEFAULT_TEMPLATE_PATH
  254. @default("labextensions_url")
  255. def _default_labextensions_url(self) -> str:
  256. return ujoin(self.app_url, "extensions/")
  257. @default("labextensions_path")
  258. def _default_labextensions_path(self) -> list[str]:
  259. return jupyter_path("labextensions")
  260. @default("workspaces_url")
  261. def _default_workspaces_url(self) -> str:
  262. return ujoin(self.app_url, "workspaces/")
  263. @default("workspaces_api_url")
  264. def _default_workspaces_api_url(self) -> str:
  265. return ujoin(self.app_url, "api", "workspaces/")
  266. @default("settings_url")
  267. def _default_settings_url(self) -> str:
  268. return ujoin(self.app_url, "api", "settings/")
  269. @default("listings_url")
  270. def _default_listings_url(self) -> str:
  271. return ujoin(self.app_url, "api", "listings/")
  272. @default("themes_url")
  273. def _default_themes_url(self) -> str:
  274. return ujoin(self.app_url, "api", "themes/")
  275. @default("licenses_url")
  276. def _default_licenses_url(self) -> str:
  277. return ujoin(self.app_url, "api", "licenses/")
  278. @default("tree_url")
  279. def _default_tree_url(self) -> str:
  280. return ujoin(self.app_url, "tree/")
  281. @default("translations_api_url")
  282. def _default_translations_api_url(self) -> str:
  283. return ujoin(self.app_url, "api", "translations/")
  284. def get_allowed_levels() -> list[str]:
  285. """
  286. Returns the levels where configs can be stored.
  287. """
  288. return ["all", "user", "sys_prefix", "system", "app", "extension"]
  289. def _get_config_manager(level: str, include_higher_levels: bool = False) -> ConfigManager:
  290. """Get the location of config files for the current context
  291. Returns the string to the environment
  292. """
  293. # Delayed import since this gets monkey-patched in tests
  294. from jupyter_core.paths import ENV_CONFIG_PATH
  295. allowed = get_allowed_levels()
  296. if level not in allowed:
  297. msg = f"Page config level must be one of: {allowed}"
  298. raise ValueError(msg)
  299. config_name = "labconfig"
  300. if level == "all":
  301. return ConfigManager(config_dir_name=config_name)
  302. paths: dict[str, list] = {
  303. "app": [],
  304. "system": SYSTEM_CONFIG_PATH,
  305. "sys_prefix": [ENV_CONFIG_PATH[0]],
  306. "user": [jupyter_config_dir()],
  307. "extension": [],
  308. }
  309. levels = allowed[allowed.index(level) :] if include_higher_levels else [level]
  310. read_config_paths, write_config_dir = [], None
  311. for _level in levels:
  312. for p in paths[_level]:
  313. read_config_paths.append(osp.join(p, config_name))
  314. if write_config_dir is None and paths[_level]: # type: ignore[redundant-expr]
  315. write_config_dir = osp.join(paths[_level][0], config_name)
  316. return ConfigManager(read_config_path=read_config_paths, write_config_dir=write_config_dir)