serverapp.py 118 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281
  1. """A tornado based Jupyter server."""
  2. # Copyright (c) Jupyter Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from __future__ import annotations
  5. import datetime
  6. import errno
  7. import gettext
  8. import hashlib
  9. import hmac
  10. import ipaddress
  11. import json
  12. import logging
  13. import mimetypes
  14. import os
  15. import pathlib
  16. import random
  17. import re
  18. import select
  19. import signal
  20. import socket
  21. import stat
  22. import sys
  23. import threading
  24. import time
  25. import typing as t
  26. import urllib
  27. import warnings
  28. from base64 import encodebytes
  29. from functools import partial
  30. from pathlib import Path
  31. import jupyter_client
  32. from jupyter_client.kernelspec import KernelSpecManager
  33. from jupyter_client.manager import KernelManager
  34. from jupyter_client.session import Session
  35. from jupyter_core.application import JupyterApp, base_aliases, base_flags
  36. from jupyter_core.paths import jupyter_runtime_dir
  37. from jupyter_events.logger import EventLogger
  38. from nbformat.sign import NotebookNotary
  39. from tornado import httpserver, ioloop, web
  40. from tornado.httputil import url_concat
  41. from tornado.log import LogFormatter, access_log, app_log, gen_log
  42. from tornado.netutil import bind_sockets
  43. from tornado.routing import Matcher, Rule
  44. if not sys.platform.startswith("win"):
  45. from tornado.netutil import bind_unix_socket
  46. if sys.platform.startswith("win"):
  47. try:
  48. import colorama
  49. colorama.init()
  50. except ImportError:
  51. pass
  52. from traitlets import (
  53. Any,
  54. Bool,
  55. Bytes,
  56. Dict,
  57. Float,
  58. Instance,
  59. Integer,
  60. List,
  61. TraitError,
  62. Type,
  63. Unicode,
  64. Union,
  65. default,
  66. observe,
  67. validate,
  68. )
  69. from traitlets.config import Config
  70. from traitlets.config.application import boolean_flag, catch_config_error
  71. from jupyter_server import (
  72. DEFAULT_EVENTS_SCHEMA_PATH,
  73. DEFAULT_JUPYTER_SERVER_PORT,
  74. DEFAULT_STATIC_FILES_PATH,
  75. DEFAULT_TEMPLATE_PATH_LIST,
  76. JUPYTER_SERVER_EVENTS_URI,
  77. __version__,
  78. )
  79. from jupyter_server._sysinfo import get_sys_info
  80. from jupyter_server._tz import utcnow
  81. from jupyter_server.auth.authorizer import AllowAllAuthorizer, Authorizer
  82. from jupyter_server.auth.identity import (
  83. IdentityProvider,
  84. LegacyIdentityProvider,
  85. PasswordIdentityProvider,
  86. )
  87. from jupyter_server.auth.login import LoginHandler
  88. from jupyter_server.auth.logout import LogoutHandler
  89. from jupyter_server.base.handlers import (
  90. FileFindHandler,
  91. MainHandler,
  92. RedirectWithParams,
  93. Template404,
  94. )
  95. from jupyter_server.extension.config import ExtensionConfigManager
  96. from jupyter_server.extension.manager import ExtensionManager
  97. from jupyter_server.extension.serverextension import ServerExtensionApp
  98. from jupyter_server.gateway.connections import GatewayWebSocketConnection
  99. from jupyter_server.gateway.gateway_client import GatewayClient
  100. from jupyter_server.gateway.managers import (
  101. GatewayKernelSpecManager,
  102. GatewayMappingKernelManager,
  103. GatewaySessionManager,
  104. )
  105. from jupyter_server.log import log_request
  106. from jupyter_server.prometheus.metrics import (
  107. ACTIVE_DURATION,
  108. LAST_ACTIVITY,
  109. SERVER_EXTENSION_INFO,
  110. SERVER_INFO,
  111. SERVER_STARTED,
  112. )
  113. from jupyter_server.services.config import ConfigManager
  114. from jupyter_server.services.contents.filemanager import (
  115. AsyncFileContentsManager,
  116. FileContentsManager,
  117. )
  118. from jupyter_server.services.contents.largefilemanager import AsyncLargeFileManager
  119. from jupyter_server.services.contents.manager import AsyncContentsManager, ContentsManager
  120. from jupyter_server.services.kernels.connection.base import BaseKernelWebsocketConnection
  121. from jupyter_server.services.kernels.connection.channels import ZMQChannelsWebsocketConnection
  122. from jupyter_server.services.kernels.kernelmanager import (
  123. AsyncMappingKernelManager,
  124. MappingKernelManager,
  125. )
  126. from jupyter_server.services.sessions.sessionmanager import SessionManager
  127. from jupyter_server.utils import (
  128. JupyterServerAuthWarning,
  129. check_pid,
  130. fetch,
  131. unix_socket_in_use,
  132. url_escape,
  133. url_path_join,
  134. urlencode_unix_socket_path,
  135. )
  136. try:
  137. import resource
  138. except ImportError:
  139. # Windows
  140. resource = None # type:ignore[assignment]
  141. from jinja2 import Environment, FileSystemLoader
  142. from jupyter_core.paths import secure_write
  143. from jupyter_core.utils import ensure_async
  144. from jupyter_server.transutils import _i18n, trans
  145. from jupyter_server.utils import pathname2url, urljoin
  146. # the minimum viable tornado version: needs to be kept in sync with setup.py
  147. MIN_TORNADO = (6, 1, 0)
  148. try:
  149. import tornado
  150. assert tornado.version_info >= MIN_TORNADO
  151. except (ImportError, AttributeError, AssertionError) as e: # pragma: no cover
  152. raise ImportError(_i18n("The Jupyter Server requires tornado >=%s.%s.%s") % MIN_TORNADO) from e
  153. try:
  154. import resource
  155. except ImportError:
  156. # Windows
  157. resource = None # type:ignore[assignment]
  158. # -----------------------------------------------------------------------------
  159. # Module globals
  160. # -----------------------------------------------------------------------------
  161. _examples = """
  162. jupyter server # start the server
  163. jupyter server --certfile=mycert.pem # use SSL/TLS certificate
  164. jupyter server password # enter a password to protect the server
  165. """
  166. JUPYTER_SERVICE_HANDLERS = {
  167. "auth": None,
  168. "api": ["jupyter_server.services.api.handlers"],
  169. "config": ["jupyter_server.services.config.handlers"],
  170. "contents": ["jupyter_server.services.contents.handlers"],
  171. "files": ["jupyter_server.files.handlers"],
  172. "kernels": [
  173. "jupyter_server.services.kernels.handlers",
  174. ],
  175. "kernelspecs": [
  176. "jupyter_server.kernelspecs.handlers",
  177. "jupyter_server.services.kernelspecs.handlers",
  178. ],
  179. "nbconvert": [
  180. "jupyter_server.nbconvert.handlers",
  181. "jupyter_server.services.nbconvert.handlers",
  182. ],
  183. "security": ["jupyter_server.services.security.handlers"],
  184. "sessions": ["jupyter_server.services.sessions.handlers"],
  185. "shutdown": ["jupyter_server.services.shutdown"],
  186. "view": ["jupyter_server.view.handlers"],
  187. "events": ["jupyter_server.services.events.handlers"],
  188. }
  189. # Added for backwards compatibility from classic notebook server.
  190. DEFAULT_SERVER_PORT = DEFAULT_JUPYTER_SERVER_PORT
  191. # -----------------------------------------------------------------------------
  192. # Helper functions
  193. # -----------------------------------------------------------------------------
  194. def random_ports(port: int, n: int) -> t.Generator[int, None, None]:
  195. """Generate a list of n random ports near the given port.
  196. The first 5 ports will be sequential, and the remaining n-5 will be
  197. randomly selected in the range [port-2*n, port+2*n].
  198. """
  199. for i in range(min(5, n)):
  200. yield port + i
  201. for _ in range(n - 5):
  202. yield max(1, port + random.randint(-2 * n, 2 * n)) # noqa: S311
  203. def load_handlers(name: str) -> t.Any:
  204. """Load the (URL pattern, handler) tuples for each component."""
  205. mod = __import__(name, fromlist=["default_handlers"])
  206. return mod.default_handlers
  207. # -----------------------------------------------------------------------------
  208. # The Tornado web application
  209. # -----------------------------------------------------------------------------
  210. class ServerWebApplication(web.Application):
  211. """A server web application."""
  212. def __init__(
  213. self,
  214. jupyter_app,
  215. default_services,
  216. kernel_manager,
  217. contents_manager,
  218. session_manager,
  219. kernel_spec_manager,
  220. config_manager,
  221. event_logger,
  222. extra_services,
  223. log,
  224. base_url,
  225. default_url,
  226. settings_overrides,
  227. jinja_env_options,
  228. *,
  229. authorizer=None,
  230. identity_provider=None,
  231. kernel_websocket_connection_class=None,
  232. websocket_ping_interval=None,
  233. websocket_ping_timeout=None,
  234. ):
  235. """Initialize a server web application."""
  236. if identity_provider is None:
  237. warnings.warn(
  238. "identity_provider unspecified. Using default IdentityProvider."
  239. " Specify an identity_provider to avoid this message.",
  240. RuntimeWarning,
  241. stacklevel=2,
  242. )
  243. identity_provider = IdentityProvider(parent=jupyter_app)
  244. if authorizer is None:
  245. warnings.warn(
  246. "authorizer unspecified. Using permissive AllowAllAuthorizer."
  247. " Specify an authorizer to avoid this message.",
  248. JupyterServerAuthWarning,
  249. stacklevel=2,
  250. )
  251. authorizer = AllowAllAuthorizer(parent=jupyter_app, identity_provider=identity_provider)
  252. settings = self.init_settings(
  253. jupyter_app,
  254. kernel_manager,
  255. contents_manager,
  256. session_manager,
  257. kernel_spec_manager,
  258. config_manager,
  259. event_logger,
  260. extra_services,
  261. log,
  262. base_url,
  263. default_url,
  264. settings_overrides,
  265. jinja_env_options,
  266. authorizer=authorizer,
  267. identity_provider=identity_provider,
  268. kernel_websocket_connection_class=kernel_websocket_connection_class,
  269. websocket_ping_interval=websocket_ping_interval,
  270. websocket_ping_timeout=websocket_ping_timeout,
  271. )
  272. handlers = self.init_handlers(default_services, settings)
  273. undecorated_methods = []
  274. for matcher, handler, *_ in handlers:
  275. undecorated_methods.extend(self._check_handler_auth(matcher, handler))
  276. if undecorated_methods:
  277. message = (
  278. "Core endpoints without @allow_unauthenticated, @ws_authenticated, nor @web.authenticated:\n"
  279. + "\n".join(undecorated_methods)
  280. )
  281. if jupyter_app.allow_unauthenticated_access:
  282. warnings.warn(
  283. message,
  284. JupyterServerAuthWarning,
  285. stacklevel=2,
  286. )
  287. else:
  288. raise Exception(message)
  289. super().__init__(handlers, **settings)
  290. def add_handlers(self, host_pattern, host_handlers):
  291. undecorated_methods = []
  292. for rule in host_handlers:
  293. if isinstance(rule, Rule):
  294. matcher = rule.matcher
  295. handler = rule.target
  296. else:
  297. matcher, handler, *_ = rule
  298. undecorated_methods.extend(self._check_handler_auth(matcher, handler))
  299. if undecorated_methods and not self.settings["allow_unauthenticated_access"]:
  300. message = (
  301. "Extension endpoints without @allow_unauthenticated, @ws_authenticated, nor @web.authenticated:\n"
  302. + "\n".join(undecorated_methods)
  303. )
  304. warnings.warn(
  305. message,
  306. JupyterServerAuthWarning,
  307. stacklevel=2,
  308. )
  309. return super().add_handlers(host_pattern, host_handlers)
  310. def init_settings(
  311. self,
  312. jupyter_app,
  313. kernel_manager,
  314. contents_manager,
  315. session_manager,
  316. kernel_spec_manager,
  317. config_manager,
  318. event_logger,
  319. extra_services,
  320. log,
  321. base_url,
  322. default_url,
  323. settings_overrides,
  324. jinja_env_options=None,
  325. *,
  326. authorizer=None,
  327. identity_provider=None,
  328. kernel_websocket_connection_class=None,
  329. websocket_ping_interval=None,
  330. websocket_ping_timeout=None,
  331. ):
  332. """Initialize settings for the web application."""
  333. _template_path = settings_overrides.get(
  334. "template_path",
  335. jupyter_app.template_file_path,
  336. )
  337. if isinstance(_template_path, str):
  338. _template_path = (_template_path,)
  339. template_path = [os.path.expanduser(path) for path in _template_path]
  340. jenv_opt: dict[str, t.Any] = {"autoescape": True}
  341. jenv_opt.update(jinja_env_options if jinja_env_options else {})
  342. env = Environment( # noqa: S701
  343. loader=FileSystemLoader(template_path), extensions=["jinja2.ext.i18n"], **jenv_opt
  344. )
  345. sys_info = get_sys_info()
  346. base_dir = os.path.realpath(os.path.join(__file__, "..", ".."))
  347. nbui = gettext.translation(
  348. "nbui",
  349. localedir=os.path.join(base_dir, "jupyter_server/i18n"),
  350. fallback=True,
  351. )
  352. env.install_gettext_translations(nbui, newstyle=False)
  353. if sys_info["commit_source"] == "repository":
  354. # don't cache (rely on 304) when working from master
  355. version_hash = ""
  356. else:
  357. # reset the cache on server restart
  358. utc = datetime.timezone.utc
  359. version_hash = datetime.datetime.now(tz=utc).strftime("%Y%m%d%H%M%S")
  360. now = utcnow()
  361. root_dir = contents_manager.root_dir
  362. home = os.path.expanduser("~")
  363. if root_dir.startswith(home + os.path.sep):
  364. # collapse $HOME to ~
  365. root_dir = "~" + root_dir[len(home) :]
  366. settings = {
  367. # basics
  368. "log_function": partial(
  369. log_request, record_prometheus_metrics=jupyter_app.record_http_request_metrics
  370. ),
  371. "base_url": base_url,
  372. "default_url": default_url,
  373. "template_path": template_path,
  374. "static_path": jupyter_app.static_file_path,
  375. "static_custom_path": jupyter_app.static_custom_path,
  376. "static_handler_class": FileFindHandler,
  377. "static_url_prefix": url_path_join(base_url, "/static/"),
  378. "static_handler_args": {
  379. # don't cache custom.js
  380. "no_cache_paths": [url_path_join(base_url, "static", "custom")],
  381. },
  382. "version_hash": version_hash,
  383. # kernel message protocol over websocket
  384. "kernel_ws_protocol": jupyter_app.kernel_ws_protocol,
  385. # rate limits
  386. "limit_rate": jupyter_app.limit_rate,
  387. "iopub_msg_rate_limit": jupyter_app.iopub_msg_rate_limit,
  388. "iopub_data_rate_limit": jupyter_app.iopub_data_rate_limit,
  389. "rate_limit_window": jupyter_app.rate_limit_window,
  390. # authentication
  391. "cookie_secret": jupyter_app.cookie_secret,
  392. "login_url": url_path_join(base_url, "/login"),
  393. "xsrf_cookies": True,
  394. "disable_check_xsrf": jupyter_app.disable_check_xsrf,
  395. "allow_unauthenticated_access": jupyter_app.allow_unauthenticated_access,
  396. "allow_remote_access": jupyter_app.allow_remote_access,
  397. "local_hostnames": jupyter_app.local_hostnames,
  398. "authenticate_prometheus": jupyter_app.authenticate_prometheus,
  399. "extra_log_scrub_param_keys": jupyter_app.extra_log_scrub_param_keys,
  400. # managers
  401. "kernel_manager": kernel_manager,
  402. "contents_manager": contents_manager,
  403. "session_manager": session_manager,
  404. "kernel_spec_manager": kernel_spec_manager,
  405. "config_manager": config_manager,
  406. "authorizer": authorizer,
  407. "identity_provider": identity_provider,
  408. "event_logger": event_logger,
  409. "kernel_websocket_connection_class": kernel_websocket_connection_class,
  410. "websocket_ping_interval": websocket_ping_interval,
  411. "websocket_ping_timeout": websocket_ping_timeout,
  412. # handlers
  413. "extra_services": extra_services,
  414. # Jupyter stuff
  415. "started": now,
  416. # place for extensions to register activity
  417. # so that they can prevent idle-shutdown
  418. "last_activity_times": {},
  419. "jinja_template_vars": jupyter_app.jinja_template_vars,
  420. "websocket_url": jupyter_app.websocket_url,
  421. "shutdown_button": jupyter_app.quit_button,
  422. "config": jupyter_app.config,
  423. "config_dir": jupyter_app.config_dir,
  424. "allow_password_change": jupyter_app.allow_password_change,
  425. "server_root_dir": root_dir,
  426. "jinja2_env": env,
  427. "serverapp": jupyter_app,
  428. }
  429. # allow custom overrides for the tornado web app.
  430. settings.update(settings_overrides)
  431. if base_url and "xsrf_cookie_kwargs" not in settings:
  432. # default: set xsrf cookie on base_url
  433. settings["xsrf_cookie_kwargs"] = {"path": base_url}
  434. return settings
  435. def init_handlers(self, default_services, settings):
  436. """Load the (URL pattern, handler) tuples for each component."""
  437. # Order matters. The first handler to match the URL will handle the request.
  438. handlers = []
  439. # load extra services specified by users before default handlers
  440. for service in settings["extra_services"]:
  441. handlers.extend(load_handlers(service))
  442. # Load default services. Raise exception if service not
  443. # found in JUPYTER_SERVICE_HANLDERS.
  444. for service in default_services:
  445. if service in JUPYTER_SERVICE_HANDLERS:
  446. locations = JUPYTER_SERVICE_HANDLERS[service]
  447. if locations is not None:
  448. for loc in locations:
  449. handlers.extend(load_handlers(loc))
  450. else:
  451. msg = (
  452. f"{service} is not recognized as a jupyter_server "
  453. "service. If this is a custom service, "
  454. "try adding it to the "
  455. "`extra_services` list."
  456. )
  457. raise Exception(msg)
  458. # Add extra handlers from contents manager.
  459. handlers.extend(settings["contents_manager"].get_extra_handlers())
  460. # And from identity provider
  461. handlers.extend(settings["identity_provider"].get_handlers())
  462. # register base handlers last
  463. handlers.extend(load_handlers("jupyter_server.base.handlers"))
  464. if settings["default_url"] != settings["base_url"]:
  465. # set the URL that will be redirected from `/`
  466. handlers.append(
  467. (
  468. r"/?",
  469. RedirectWithParams,
  470. {
  471. "url": settings["default_url"],
  472. "permanent": False, # want 302, not 301
  473. },
  474. )
  475. )
  476. else:
  477. handlers.append((r"/", MainHandler))
  478. # prepend base_url onto the patterns that we match
  479. new_handlers = []
  480. for handler in handlers:
  481. pattern = url_path_join(settings["base_url"], handler[0])
  482. new_handler = (pattern, *list(handler[1:]))
  483. new_handlers.append(new_handler)
  484. # add 404 on the end, which will catch everything that falls through
  485. new_handlers.append((r"(.*)", Template404))
  486. return new_handlers
  487. def last_activity(self):
  488. """Get a UTC timestamp for when the server last did something.
  489. Includes: API activity, kernel activity, kernel shutdown, and terminal
  490. activity.
  491. """
  492. sources = [
  493. self.settings["started"],
  494. self.settings["kernel_manager"].last_kernel_activity,
  495. ]
  496. # Any setting that ends with a key that ends with `_last_activity` is
  497. # counted here. This provides a hook for extensions to add a last activity
  498. # setting to the server.
  499. sources.extend(
  500. [val for key, val in self.settings.items() if key.endswith("_last_activity")]
  501. )
  502. sources.extend(self.settings["last_activity_times"].values())
  503. return max(sources)
  504. def _check_handler_auth(
  505. self, matcher: t.Union[str, Matcher], handler: type[web.RequestHandler]
  506. ):
  507. missing_authentication = []
  508. for method_name in handler.SUPPORTED_METHODS:
  509. method = getattr(handler, method_name.lower())
  510. is_unimplemented = method == web.RequestHandler._unimplemented_method
  511. is_allowlisted = hasattr(method, "__allow_unauthenticated")
  512. is_blocklisted = _has_tornado_web_authenticated(method)
  513. if not is_unimplemented and not is_allowlisted and not is_blocklisted:
  514. missing_authentication.append(
  515. f"- {method_name} of {handler.__name__} registered for {matcher}"
  516. )
  517. return missing_authentication
  518. def _has_tornado_web_authenticated(method: t.Callable[..., t.Any]) -> bool:
  519. """Check if given method was decorated with @web.authenticated.
  520. Note: it is ok if we reject on @authorized @web.authenticated
  521. because the correct order is @web.authenticated @authorized.
  522. """
  523. if not hasattr(method, "__wrapped__"):
  524. return False
  525. if not hasattr(method, "__code__"):
  526. return False
  527. code = method.__code__
  528. if hasattr(code, "co_qualname"):
  529. # new in 3.11
  530. return code.co_qualname.startswith("authenticated") # type:ignore[no-any-return]
  531. elif hasattr(code, "co_filename"):
  532. return code.co_filename.replace("\\", "/").endswith("tornado/web.py")
  533. return False
  534. class JupyterPasswordApp(JupyterApp):
  535. """Set a password for the Jupyter server.
  536. Setting a password secures the Jupyter server
  537. and removes the need for token-based authentication.
  538. """
  539. description: str = __doc__
  540. def _config_file_default(self):
  541. """the default config file."""
  542. return os.path.join(self.config_dir, "jupyter_server_config.json")
  543. def start(self):
  544. """Start the password app."""
  545. from jupyter_server.auth.security import set_password
  546. set_password(config_file=self.config_file)
  547. self.log.info("Wrote hashed password to %s" % self.config_file)
  548. def shutdown_server(server_info, timeout=5, log=None):
  549. """Shutdown a Jupyter server in a separate process.
  550. *server_info* should be a dictionary as produced by list_running_servers().
  551. Will first try to request shutdown using /api/shutdown .
  552. On Unix, if the server is still running after *timeout* seconds, it will
  553. send SIGTERM. After another timeout, it escalates to SIGKILL.
  554. Returns True if the server was stopped by any means, False if stopping it
  555. failed (on Windows).
  556. """
  557. url = server_info["url"]
  558. pid = server_info["pid"]
  559. try:
  560. shutdown_url = urljoin(url, "api/shutdown")
  561. if log:
  562. log.debug("POST request to %s", shutdown_url)
  563. fetch(
  564. shutdown_url,
  565. method="POST",
  566. body=b"",
  567. headers={"Authorization": "token " + server_info["token"]},
  568. )
  569. except Exception as ex:
  570. if not str(ex) == "Unknown URL scheme.":
  571. raise ex
  572. if log:
  573. log.debug("Was not a HTTP scheme. Treating as socket instead.")
  574. log.debug("POST request to %s", url)
  575. fetch(
  576. url,
  577. method="POST",
  578. body=b"",
  579. headers={"Authorization": "token " + server_info["token"]},
  580. )
  581. # Poll to see if it shut down.
  582. for _ in range(timeout * 10):
  583. if not check_pid(pid):
  584. if log:
  585. log.debug("Server PID %s is gone", pid)
  586. return True
  587. time.sleep(0.1)
  588. if sys.platform.startswith("win"):
  589. return False
  590. if log:
  591. log.debug("SIGTERM to PID %s", pid)
  592. os.kill(pid, signal.SIGTERM)
  593. # Poll to see if it shut down.
  594. for _ in range(timeout * 10):
  595. if not check_pid(pid):
  596. if log:
  597. log.debug("Server PID %s is gone", pid)
  598. return True
  599. time.sleep(0.1)
  600. if log:
  601. log.debug("SIGKILL to PID %s", pid)
  602. os.kill(pid, signal.SIGKILL)
  603. return True # SIGKILL cannot be caught
  604. class JupyterServerStopApp(JupyterApp):
  605. """An application to stop a Jupyter server."""
  606. version: str = __version__
  607. description: str = "Stop currently running Jupyter server for a given port"
  608. port = Integer(
  609. DEFAULT_JUPYTER_SERVER_PORT,
  610. config=True,
  611. help="Port of the server to be killed. Default %s" % DEFAULT_JUPYTER_SERVER_PORT,
  612. )
  613. sock = Unicode("", config=True, help="UNIX socket of the server to be killed.")
  614. def parse_command_line(self, argv=None):
  615. """Parse command line options."""
  616. super().parse_command_line(argv)
  617. if self.extra_args:
  618. try:
  619. self.port = int(self.extra_args[0])
  620. except ValueError:
  621. # self.extra_args[0] was not an int, so it must be a string (unix socket).
  622. self.sock = self.extra_args[0]
  623. def shutdown_server(self, server):
  624. """Shut down a server."""
  625. return shutdown_server(server, log=self.log)
  626. def _shutdown_or_exit(self, target_endpoint, server):
  627. """Handle a shutdown."""
  628. self.log.info("Shutting down server on %s..." % target_endpoint)
  629. if not self.shutdown_server(server):
  630. sys.exit("Could not stop server on %s" % target_endpoint)
  631. @staticmethod
  632. def _maybe_remove_unix_socket(socket_path):
  633. """Try to remove a socket path."""
  634. try:
  635. os.unlink(socket_path)
  636. except OSError:
  637. pass
  638. def start(self):
  639. """Start the server stop app."""
  640. info = self.log.info
  641. servers = list(list_running_servers(self.runtime_dir, log=self.log))
  642. if not servers:
  643. self.exit("There are no running servers (per %s)" % self.runtime_dir)
  644. for server in servers:
  645. if self.sock:
  646. sock = server.get("sock", None)
  647. if sock and sock == self.sock:
  648. self._shutdown_or_exit(sock, server)
  649. # Attempt to remove the UNIX socket after stopping.
  650. self._maybe_remove_unix_socket(sock)
  651. return
  652. elif self.port:
  653. port = server.get("port", None)
  654. if port == self.port:
  655. self._shutdown_or_exit(port, server)
  656. return
  657. current_endpoint = self.sock or self.port
  658. info(f"There is currently no server running on {current_endpoint}")
  659. info("Ports/sockets currently in use:")
  660. for server in servers:
  661. info(" - {}".format(server.get("sock") or server["port"]))
  662. self.exit(1)
  663. class JupyterServerListApp(JupyterApp):
  664. """An application to list running Jupyter servers."""
  665. version: str = __version__
  666. description: str = _i18n("List currently running Jupyter servers.")
  667. flags = {
  668. "jsonlist": (
  669. {"JupyterServerListApp": {"jsonlist": True}},
  670. _i18n("Produce machine-readable JSON list output."),
  671. ),
  672. "json": (
  673. {"JupyterServerListApp": {"json": True}},
  674. _i18n("Produce machine-readable JSON object on each line of output."),
  675. ),
  676. }
  677. jsonlist = Bool(
  678. False,
  679. config=True,
  680. help=_i18n(
  681. "If True, the output will be a JSON list of objects, one per "
  682. "active Jupyer server, each with the details from the "
  683. "relevant server info file."
  684. ),
  685. )
  686. json = Bool(
  687. False,
  688. config=True,
  689. help=_i18n(
  690. "If True, each line of output will be a JSON object with the "
  691. "details from the server info file. For a JSON list output, "
  692. "see the JupyterServerListApp.jsonlist configuration value"
  693. ),
  694. )
  695. def start(self):
  696. """Start the server list application."""
  697. serverinfo_list = list(list_running_servers(self.runtime_dir, log=self.log))
  698. if self.jsonlist:
  699. print(json.dumps(serverinfo_list, indent=2))
  700. elif self.json:
  701. for serverinfo in serverinfo_list:
  702. print(json.dumps(serverinfo))
  703. else:
  704. print("Currently running servers:")
  705. for serverinfo in serverinfo_list:
  706. url = serverinfo["url"]
  707. if serverinfo.get("token"):
  708. url = url + "?token=%s" % serverinfo["token"]
  709. print(url, "::", serverinfo["root_dir"])
  710. # -----------------------------------------------------------------------------
  711. # Aliases and Flags
  712. # -----------------------------------------------------------------------------
  713. flags = dict(base_flags)
  714. flags["allow-root"] = (
  715. {"ServerApp": {"allow_root": True}},
  716. _i18n("Allow the server to be run from root user."),
  717. )
  718. flags["no-browser"] = (
  719. {"ServerApp": {"open_browser": False}, "ExtensionApp": {"open_browser": False}},
  720. _i18n("Prevent the opening of the default url in the browser."),
  721. )
  722. flags["debug"] = (
  723. {"ServerApp": {"log_level": "DEBUG"}, "ExtensionApp": {"log_level": "DEBUG"}},
  724. _i18n("Set debug level for the extension and underlying server applications."),
  725. )
  726. flags["autoreload"] = (
  727. {"ServerApp": {"autoreload": True}},
  728. """Autoreload the webapp
  729. Enable reloading of the tornado webapp and all imported Python packages
  730. when any changes are made to any Python src files in server or
  731. extensions.
  732. """,
  733. )
  734. # Add notebook manager flags
  735. flags.update(
  736. boolean_flag(
  737. "script",
  738. "FileContentsManager.save_script",
  739. "DEPRECATED, IGNORED",
  740. "DEPRECATED, IGNORED",
  741. )
  742. )
  743. aliases = dict(base_aliases)
  744. aliases.update(
  745. {
  746. "ip": "ServerApp.ip",
  747. "port": "ServerApp.port",
  748. "port-retries": "ServerApp.port_retries",
  749. "sock": "ServerApp.sock",
  750. "sock-mode": "ServerApp.sock_mode",
  751. "transport": "KernelManager.transport",
  752. "keyfile": "ServerApp.keyfile",
  753. "certfile": "ServerApp.certfile",
  754. "client-ca": "ServerApp.client_ca",
  755. "notebook-dir": "ServerApp.root_dir",
  756. "preferred-dir": "ServerApp.preferred_dir",
  757. "browser": "ServerApp.browser",
  758. "pylab": "ServerApp.pylab",
  759. "gateway-url": "GatewayClient.url",
  760. }
  761. )
  762. # -----------------------------------------------------------------------------
  763. # ServerApp
  764. # -----------------------------------------------------------------------------
  765. class ServerApp(JupyterApp):
  766. """The Jupyter Server application class."""
  767. name = "jupyter-server"
  768. version: str = __version__
  769. description: str = _i18n(
  770. """The Jupyter Server.
  771. This launches a Tornado-based Jupyter Server."""
  772. )
  773. examples = _examples
  774. flags = Dict(flags) # type:ignore[assignment]
  775. aliases = Dict(aliases) # type:ignore[assignment]
  776. classes = [
  777. KernelManager,
  778. Session,
  779. MappingKernelManager,
  780. KernelSpecManager,
  781. AsyncMappingKernelManager,
  782. ContentsManager,
  783. FileContentsManager,
  784. AsyncContentsManager,
  785. AsyncFileContentsManager,
  786. NotebookNotary,
  787. GatewayMappingKernelManager,
  788. GatewayKernelSpecManager,
  789. GatewaySessionManager,
  790. GatewayWebSocketConnection,
  791. GatewayClient,
  792. Authorizer,
  793. EventLogger,
  794. ZMQChannelsWebsocketConnection,
  795. ]
  796. subcommands: dict[str, t.Any] = {
  797. "list": (
  798. JupyterServerListApp,
  799. JupyterServerListApp.description.splitlines()[0],
  800. ),
  801. "stop": (
  802. JupyterServerStopApp,
  803. JupyterServerStopApp.description.splitlines()[0],
  804. ),
  805. "password": (
  806. JupyterPasswordApp,
  807. JupyterPasswordApp.description.splitlines()[0],
  808. ),
  809. "extension": (
  810. ServerExtensionApp,
  811. ServerExtensionApp.description.splitlines()[0],
  812. ),
  813. }
  814. # A list of services whose handlers will be exposed.
  815. # Subclasses can override this list to
  816. # expose a subset of these handlers.
  817. default_services = (
  818. "api",
  819. "auth",
  820. "config",
  821. "contents",
  822. "files",
  823. "kernels",
  824. "kernelspecs",
  825. "nbconvert",
  826. "security",
  827. "sessions",
  828. "shutdown",
  829. "view",
  830. "events",
  831. )
  832. _log_formatter_cls = LogFormatter # type:ignore[assignment]
  833. _stopping = Bool(False, help="Signal that we've begun stopping.")
  834. @default("log_level")
  835. def _default_log_level(self) -> int:
  836. return logging.INFO
  837. @default("log_format")
  838. def _default_log_format(self) -> str:
  839. """override default log format to include date & time"""
  840. return (
  841. "%(color)s[%(levelname)1.1s %(asctime)s.%(msecs).03d %(name)s]%(end_color)s %(message)s"
  842. )
  843. # file to be opened in the Jupyter server
  844. file_to_run = Unicode("", help="Open the named file when the application is launched.").tag(
  845. config=True
  846. )
  847. file_url_prefix = Unicode(
  848. "notebooks", help="The URL prefix where files are opened directly."
  849. ).tag(config=True)
  850. # Network related information
  851. allow_origin = Unicode(
  852. "",
  853. config=True,
  854. help="""Set the Access-Control-Allow-Origin header
  855. Use '*' to allow any origin to access your server.
  856. Takes precedence over allow_origin_pat.
  857. """,
  858. )
  859. allow_origin_pat = Unicode(
  860. "",
  861. config=True,
  862. help="""Use a regular expression for the Access-Control-Allow-Origin header
  863. Requests from an origin matching the expression will get replies with:
  864. Access-Control-Allow-Origin: origin
  865. where `origin` is the origin of the request.
  866. Ignored if allow_origin is set.
  867. """,
  868. )
  869. allow_credentials = Bool(
  870. False,
  871. config=True,
  872. help=_i18n("Set the Access-Control-Allow-Credentials: true header"),
  873. )
  874. allow_root = Bool(
  875. False,
  876. config=True,
  877. help=_i18n("Whether to allow the user to run the server as root."),
  878. )
  879. autoreload = Bool(
  880. False,
  881. config=True,
  882. help=_i18n("Reload the webapp when changes are made to any Python src files."),
  883. )
  884. default_url = Unicode("/", config=True, help=_i18n("The default URL to redirect to from `/`"))
  885. ip = Unicode(
  886. "localhost",
  887. config=True,
  888. help=_i18n("The IP address the Jupyter server will listen on."),
  889. )
  890. @default("ip")
  891. def _default_ip(self) -> str:
  892. """Return localhost if available, 127.0.0.1 otherwise.
  893. On some (horribly broken) systems, localhost cannot be bound.
  894. """
  895. s = socket.socket()
  896. try:
  897. s.bind(("localhost", 0))
  898. except OSError as e:
  899. self.log.warning(
  900. _i18n("Cannot bind to localhost, using 127.0.0.1 as default ip\n%s"), e
  901. )
  902. return "127.0.0.1"
  903. else:
  904. s.close()
  905. return "localhost"
  906. @validate("ip")
  907. def _validate_ip(self, proposal: t.Any) -> str:
  908. value = t.cast(str, proposal["value"])
  909. if value == "*":
  910. value = ""
  911. return value
  912. custom_display_url = Unicode(
  913. "",
  914. config=True,
  915. help=_i18n(
  916. """Override URL shown to users.
  917. Replace actual URL, including protocol, address, port and base URL,
  918. with the given value when displaying URL to the users. Do not change
  919. the actual connection URL. If authentication token is enabled, the
  920. token is added to the custom URL automatically.
  921. This option is intended to be used when the URL to display to the user
  922. cannot be determined reliably by the Jupyter server (proxified
  923. or containerized setups for example)."""
  924. ),
  925. )
  926. port_env = "JUPYTER_PORT"
  927. port_default_value = DEFAULT_JUPYTER_SERVER_PORT
  928. port = Integer(
  929. config=True,
  930. help=_i18n("The port the server will listen on (env: JUPYTER_PORT)."),
  931. )
  932. @default("port")
  933. def _port_default(self) -> int:
  934. return int(os.getenv(self.port_env, self.port_default_value))
  935. port_retries_env = "JUPYTER_PORT_RETRIES"
  936. port_retries_default_value = 50
  937. port_retries = Integer(
  938. port_retries_default_value,
  939. config=True,
  940. help=_i18n(
  941. "The number of additional ports to try if the specified port is not "
  942. "available (env: JUPYTER_PORT_RETRIES)."
  943. ),
  944. )
  945. @default("port_retries")
  946. def _port_retries_default(self) -> int:
  947. return int(os.getenv(self.port_retries_env, self.port_retries_default_value))
  948. sock = Unicode("", config=True, help="The UNIX socket the Jupyter server will listen on.")
  949. sock_mode = Unicode(
  950. "0600",
  951. config=True,
  952. help="The permissions mode for UNIX socket creation (default: 0600).",
  953. )
  954. @validate("sock_mode")
  955. def _validate_sock_mode(self, proposal: t.Any) -> t.Any:
  956. value = proposal["value"]
  957. try:
  958. converted_value = int(value.encode(), 8)
  959. assert all(
  960. (
  961. # Ensure the mode is at least user readable/writable.
  962. bool(converted_value & stat.S_IRUSR),
  963. bool(converted_value & stat.S_IWUSR),
  964. # And isn't out of bounds.
  965. converted_value <= 2**12,
  966. )
  967. )
  968. except ValueError as e:
  969. raise TraitError(
  970. 'invalid --sock-mode value: %s, please specify as e.g. "0600"' % value
  971. ) from e
  972. except AssertionError as e:
  973. raise TraitError(
  974. "invalid --sock-mode value: %s, must have u+rw (0600) at a minimum" % value
  975. ) from e
  976. return value
  977. certfile = Unicode(
  978. "",
  979. config=True,
  980. help=_i18n("""The full path to an SSL/TLS certificate file."""),
  981. )
  982. keyfile = Unicode(
  983. "",
  984. config=True,
  985. help=_i18n("""The full path to a private key file for usage with SSL/TLS."""),
  986. )
  987. client_ca = Unicode(
  988. "",
  989. config=True,
  990. help=_i18n(
  991. """The full path to a certificate authority certificate for SSL/TLS client authentication."""
  992. ),
  993. )
  994. cookie_secret_file = Unicode(
  995. config=True, help=_i18n("""The file where the cookie secret is stored.""")
  996. )
  997. @default("cookie_secret_file")
  998. def _default_cookie_secret_file(self) -> str:
  999. return os.path.join(self.runtime_dir, "jupyter_cookie_secret")
  1000. cookie_secret = Bytes(
  1001. b"",
  1002. config=True,
  1003. help="""The random bytes used to secure cookies.
  1004. By default this is generated on first start of the server and persisted across server
  1005. sessions by writing the cookie secret into the `cookie_secret_file` file.
  1006. When using an executable config file you can override this to be random at each server restart.
  1007. Note: Cookie secrets should be kept private, do not share config files with
  1008. cookie_secret stored in plaintext (you can read the value from a file).
  1009. """,
  1010. )
  1011. @default("cookie_secret")
  1012. def _default_cookie_secret(self) -> bytes:
  1013. if os.path.exists(self.cookie_secret_file):
  1014. with open(self.cookie_secret_file, "rb") as f:
  1015. key = f.read()
  1016. else:
  1017. key = encodebytes(os.urandom(32))
  1018. self._write_cookie_secret_file(key)
  1019. h = hmac.new(key, digestmod=hashlib.sha256)
  1020. h.update(self.password.encode())
  1021. return h.digest()
  1022. def _write_cookie_secret_file(self, secret: bytes) -> None:
  1023. """write my secret to my secret_file"""
  1024. self.log.info(_i18n("Writing Jupyter server cookie secret to %s"), self.cookie_secret_file)
  1025. try:
  1026. with secure_write(self.cookie_secret_file, True) as f:
  1027. f.write(secret)
  1028. except OSError as e:
  1029. self.log.error(
  1030. _i18n("Failed to write cookie secret to %s: %s"),
  1031. self.cookie_secret_file,
  1032. e,
  1033. )
  1034. _token_set = False
  1035. token = Unicode("<DEPRECATED>", help=_i18n("""DEPRECATED. Use IdentityProvider.token""")).tag(
  1036. config=True
  1037. )
  1038. @observe("token")
  1039. def _deprecated_token(self, change: t.Any) -> None:
  1040. self._warn_deprecated_config(change, "IdentityProvider")
  1041. @default("token")
  1042. def _deprecated_token_access(self) -> str:
  1043. warnings.warn(
  1044. "ServerApp.token config is deprecated in jupyter-server 2.0. Use IdentityProvider.token",
  1045. DeprecationWarning,
  1046. stacklevel=3,
  1047. )
  1048. return self.identity_provider.token
  1049. min_open_files_limit = Integer(
  1050. config=True,
  1051. help="""
  1052. Gets or sets a lower bound on the open file handles process resource
  1053. limit. This may need to be increased if you run into an
  1054. OSError: [Errno 24] Too many open files.
  1055. This is not applicable when running on Windows.
  1056. """,
  1057. allow_none=True,
  1058. )
  1059. @default("min_open_files_limit")
  1060. def _default_min_open_files_limit(self) -> t.Optional[int]:
  1061. if resource is None:
  1062. # Ignoring min_open_files_limit because the limit cannot be adjusted (for example, on Windows)
  1063. return None # type:ignore[unreachable]
  1064. soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
  1065. default_soft = 4096
  1066. if hard >= default_soft:
  1067. return default_soft
  1068. self.log.debug(
  1069. "Default value for min_open_files_limit is ignored (hard=%r, soft=%r)",
  1070. hard,
  1071. soft,
  1072. )
  1073. return soft
  1074. max_body_size = Integer(
  1075. 512 * 1024 * 1024,
  1076. config=True,
  1077. help="""
  1078. Sets the maximum allowed size of the client request body, specified in
  1079. the Content-Length request header field. If the size in a request
  1080. exceeds the configured value, a malformed HTTP message is returned to
  1081. the client.
  1082. Note: max_body_size is applied even in streaming mode.
  1083. """,
  1084. )
  1085. max_buffer_size = Integer(
  1086. 512 * 1024 * 1024,
  1087. config=True,
  1088. help="""
  1089. Gets or sets the maximum amount of memory, in bytes, that is allocated
  1090. for use by the buffer manager.
  1091. """,
  1092. )
  1093. password = Unicode(
  1094. "",
  1095. config=True,
  1096. help="""DEPRECATED in 2.0. Use PasswordIdentityProvider.hashed_password""",
  1097. )
  1098. password_required = Bool(
  1099. False,
  1100. config=True,
  1101. help="""DEPRECATED in 2.0. Use PasswordIdentityProvider.password_required""",
  1102. )
  1103. allow_password_change = Bool(
  1104. True,
  1105. config=True,
  1106. help="""DEPRECATED in 2.0. Use PasswordIdentityProvider.allow_password_change""",
  1107. )
  1108. def _warn_deprecated_config(
  1109. self, change: t.Any, clsname: str, new_name: t.Optional[str] = None
  1110. ) -> None:
  1111. """Warn on deprecated config."""
  1112. if new_name is None:
  1113. new_name = change.name
  1114. if clsname not in self.config or new_name not in self.config[clsname]:
  1115. # Deprecated config used, new config not used.
  1116. # Use deprecated config, warn about new name.
  1117. self.log.warning(
  1118. f"ServerApp.{change.name} config is deprecated in 2.0. Use {clsname}.{new_name}."
  1119. )
  1120. self.config[clsname][new_name] = change.new
  1121. # Deprecated config used, new config also used.
  1122. # Warn only if the values differ.
  1123. # If the values are the same, assume intentional backward-compatible config.
  1124. elif self.config[clsname][new_name] != change.new:
  1125. self.log.warning(
  1126. f"Ignoring deprecated ServerApp.{change.name} config. Using {clsname}.{new_name}."
  1127. )
  1128. @observe("password")
  1129. def _deprecated_password(self, change: t.Any) -> None:
  1130. self._warn_deprecated_config(change, "PasswordIdentityProvider", new_name="hashed_password")
  1131. @observe("password_required", "allow_password_change")
  1132. def _deprecated_password_config(self, change: t.Any) -> None:
  1133. self._warn_deprecated_config(change, "PasswordIdentityProvider")
  1134. disable_check_xsrf = Bool(
  1135. False,
  1136. config=True,
  1137. help="""Disable cross-site-request-forgery protection
  1138. Jupyter server includes protection from cross-site request forgeries,
  1139. requiring API requests to either:
  1140. - originate from pages served by this server (validated with XSRF cookie and token), or
  1141. - authenticate with a token
  1142. Some anonymous compute resources still desire the ability to run code,
  1143. completely without authentication.
  1144. These services can disable all authentication and security checks,
  1145. with the full knowledge of what that implies.
  1146. """,
  1147. )
  1148. _allow_unauthenticated_access_env = "JUPYTER_SERVER_ALLOW_UNAUTHENTICATED_ACCESS"
  1149. allow_unauthenticated_access = Bool(
  1150. True,
  1151. config=True,
  1152. help=f"""Allow unauthenticated access to endpoints without authentication rule.
  1153. When set to `True` (default in jupyter-server 2.0, subject to change
  1154. in the future), any request to an endpoint without an authentication rule
  1155. (either `@tornado.web.authenticated`, or `@allow_unauthenticated`)
  1156. will be permitted, regardless of whether user has logged in or not.
  1157. When set to `False`, logging in will be required for access to each endpoint,
  1158. excluding the endpoints marked with `@allow_unauthenticated` decorator.
  1159. This option can be configured using `{_allow_unauthenticated_access_env}`
  1160. environment variable: any non-empty value other than "true" and "yes" will
  1161. prevent unauthenticated access to endpoints without `@allow_unauthenticated`.
  1162. """,
  1163. )
  1164. @default("allow_unauthenticated_access")
  1165. def _allow_unauthenticated_access_default(self):
  1166. if os.getenv(self._allow_unauthenticated_access_env):
  1167. return os.environ[self._allow_unauthenticated_access_env].lower() in ["true", "yes"]
  1168. return True
  1169. allow_remote_access = Bool(
  1170. config=True,
  1171. help="""Allow requests where the Host header doesn't point to a local server
  1172. By default, requests get a 403 forbidden response if the 'Host' header
  1173. shows that the browser thinks it's on a non-local domain.
  1174. Setting this option to True disables this check.
  1175. This protects against 'DNS rebinding' attacks, where a remote web server
  1176. serves you a page and then changes its DNS to send later requests to a
  1177. local IP, bypassing same-origin checks.
  1178. Local IP addresses (such as 127.0.0.1 and ::1) are allowed as local,
  1179. along with hostnames configured in local_hostnames.
  1180. """,
  1181. )
  1182. @default("allow_remote_access")
  1183. def _default_allow_remote(self) -> bool:
  1184. """Disallow remote access if we're listening only on loopback addresses"""
  1185. # if blank, self.ip was configured to "*" meaning bind to all interfaces,
  1186. # see _valdate_ip
  1187. if self.ip == "":
  1188. return True
  1189. try:
  1190. addr = ipaddress.ip_address(self.ip)
  1191. except ValueError:
  1192. # Address is a hostname
  1193. for info in socket.getaddrinfo(self.ip, self.port, 0, socket.SOCK_STREAM):
  1194. addr = info[4][0] # type:ignore[assignment]
  1195. try:
  1196. parsed = ipaddress.ip_address(addr.split("%")[0]) # type:ignore[union-attr]
  1197. except ValueError:
  1198. self.log.warning("Unrecognised IP address: %r", addr)
  1199. continue
  1200. # Macs map localhost to 'fe80::1%lo0', a link local address
  1201. # scoped to the loopback interface. For now, we'll assume that
  1202. # any scoped link-local address is effectively local.
  1203. if not (
  1204. parsed.is_loopback or (("%" in addr) and parsed.is_link_local) # type:ignore[operator]
  1205. ):
  1206. return True
  1207. return False
  1208. else:
  1209. return not addr.is_loopback
  1210. use_redirect_file = Bool(
  1211. True,
  1212. config=True,
  1213. help="""Disable launching browser by redirect file
  1214. For versions of notebook > 5.7.2, a security feature measure was added that
  1215. prevented the authentication token used to launch the browser from being visible.
  1216. This feature makes it difficult for other users on a multi-user system from
  1217. running code in your Jupyter session as you.
  1218. However, some environments (like Windows Subsystem for Linux (WSL) and Chromebooks),
  1219. launching a browser using a redirect file can lead the browser failing to load.
  1220. This is because of the difference in file structures/paths between the runtime and
  1221. the browser.
  1222. Disabling this setting to False will disable this behavior, allowing the browser
  1223. to launch by using a URL and visible token (as before).
  1224. """,
  1225. )
  1226. local_hostnames = List(
  1227. Unicode(),
  1228. ["localhost"],
  1229. config=True,
  1230. help="""Hostnames to allow as local when allow_remote_access is False.
  1231. Local IP addresses (such as 127.0.0.1 and ::1) are automatically accepted
  1232. as local as well.
  1233. """,
  1234. )
  1235. open_browser = Bool(
  1236. False,
  1237. config=True,
  1238. help="""Whether to open in a browser after starting.
  1239. The specific browser used is platform dependent and
  1240. determined by the python standard library `webbrowser`
  1241. module, unless it is overridden using the --browser
  1242. (ServerApp.browser) configuration option.
  1243. """,
  1244. )
  1245. browser = Unicode(
  1246. "",
  1247. config=True,
  1248. help="""Specify what command to use to invoke a web
  1249. browser when starting the server. If not specified, the
  1250. default browser will be determined by the `webbrowser`
  1251. standard library module, which allows setting of the
  1252. BROWSER environment variable to override it.
  1253. """,
  1254. )
  1255. webbrowser_open_new = Integer(
  1256. 2,
  1257. config=True,
  1258. help=_i18n(
  1259. """Specify where to open the server on startup. This is the
  1260. `new` argument passed to the standard library method `webbrowser.open`.
  1261. The behaviour is not guaranteed, but depends on browser support. Valid
  1262. values are:
  1263. - 2 opens a new tab,
  1264. - 1 opens a new window,
  1265. - 0 opens in an existing window.
  1266. See the `webbrowser.open` documentation for details.
  1267. """
  1268. ),
  1269. )
  1270. tornado_settings = Dict(
  1271. config=True,
  1272. help=_i18n(
  1273. "Supply overrides for the tornado.web.Application that the Jupyter server uses."
  1274. ),
  1275. )
  1276. websocket_compression_options = Any(
  1277. None,
  1278. config=True,
  1279. help=_i18n(
  1280. """
  1281. Set the tornado compression options for websocket connections.
  1282. This value will be returned from :meth:`WebSocketHandler.get_compression_options`.
  1283. None (default) will disable compression.
  1284. A dict (even an empty one) will enable compression.
  1285. See the tornado docs for WebSocketHandler.get_compression_options for details.
  1286. """
  1287. ),
  1288. )
  1289. terminado_settings = Dict(
  1290. Union([List(), Unicode()]),
  1291. config=True,
  1292. help=_i18n('Supply overrides for terminado. Currently only supports "shell_command".'),
  1293. )
  1294. cookie_options = Dict(
  1295. config=True,
  1296. help=_i18n("DEPRECATED. Use IdentityProvider.cookie_options"),
  1297. )
  1298. get_secure_cookie_kwargs = Dict(
  1299. config=True,
  1300. help=_i18n("DEPRECATED. Use IdentityProvider.get_secure_cookie_kwargs"),
  1301. )
  1302. @observe("cookie_options", "get_secure_cookie_kwargs")
  1303. def _deprecated_cookie_config(self, change: t.Any) -> None:
  1304. self._warn_deprecated_config(change, "IdentityProvider")
  1305. ssl_options = Dict(
  1306. allow_none=True,
  1307. config=True,
  1308. help=_i18n(
  1309. """Supply SSL options for the tornado HTTPServer.
  1310. See the tornado docs for details."""
  1311. ),
  1312. )
  1313. jinja_environment_options = Dict(
  1314. config=True,
  1315. help=_i18n("Supply extra arguments that will be passed to Jinja environment."),
  1316. )
  1317. jinja_template_vars = Dict(
  1318. config=True,
  1319. help=_i18n("Extra variables to supply to jinja templates when rendering."),
  1320. )
  1321. base_url = Unicode(
  1322. "/",
  1323. config=True,
  1324. help="""The base URL for the Jupyter server.
  1325. Leading and trailing slashes can be omitted,
  1326. and will automatically be added.
  1327. """,
  1328. )
  1329. @validate("base_url")
  1330. def _update_base_url(self, proposal: t.Any) -> str:
  1331. value = t.cast(str, proposal["value"])
  1332. if not value.startswith("/"):
  1333. value = "/" + value
  1334. if not value.endswith("/"):
  1335. value = value + "/"
  1336. return value
  1337. extra_static_paths = List(
  1338. Unicode(),
  1339. config=True,
  1340. help="""Extra paths to search for serving static files.
  1341. This allows adding javascript/css to be available from the Jupyter server machine,
  1342. or overriding individual files in the IPython""",
  1343. )
  1344. @property
  1345. def static_file_path(self) -> list[str]:
  1346. """return extra paths + the default location"""
  1347. return [*self.extra_static_paths, DEFAULT_STATIC_FILES_PATH]
  1348. static_custom_path = List(Unicode(), help=_i18n("""Path to search for custom.js, css"""))
  1349. @default("static_custom_path")
  1350. def _default_static_custom_path(self) -> list[str]:
  1351. return [os.path.join(d, "custom") for d in (self.config_dir, DEFAULT_STATIC_FILES_PATH)]
  1352. extra_template_paths = List(
  1353. Unicode(),
  1354. config=True,
  1355. help=_i18n(
  1356. """Extra paths to search for serving jinja templates.
  1357. Can be used to override templates from jupyter_server.templates."""
  1358. ),
  1359. )
  1360. @property
  1361. def template_file_path(self) -> list[str]:
  1362. """return extra paths + the default locations"""
  1363. return self.extra_template_paths + DEFAULT_TEMPLATE_PATH_LIST
  1364. extra_services = List(
  1365. Unicode(),
  1366. config=True,
  1367. help=_i18n(
  1368. """handlers that should be loaded at higher priority than the default services"""
  1369. ),
  1370. )
  1371. websocket_url = Unicode(
  1372. "",
  1373. config=True,
  1374. help="""The base URL for websockets,
  1375. if it differs from the HTTP server (hint: it almost certainly doesn't).
  1376. Should be in the form of an HTTP origin: ws[s]://hostname[:port]
  1377. """,
  1378. )
  1379. quit_button = Bool(
  1380. True,
  1381. config=True,
  1382. help="""If True, display controls to shut down the Jupyter server, such as menu items or buttons.""",
  1383. )
  1384. contents_manager_class = Type(
  1385. default_value=AsyncLargeFileManager,
  1386. klass=ContentsManager,
  1387. config=True,
  1388. help=_i18n("The content manager class to use."),
  1389. )
  1390. kernel_manager_class = Type(
  1391. klass=MappingKernelManager,
  1392. config=True,
  1393. help=_i18n("The kernel manager class to use."),
  1394. )
  1395. @default("kernel_manager_class")
  1396. def _default_kernel_manager_class(self) -> t.Union[str, type[AsyncMappingKernelManager]]:
  1397. if self.gateway_config.gateway_enabled:
  1398. return "jupyter_server.gateway.managers.GatewayMappingKernelManager"
  1399. return AsyncMappingKernelManager
  1400. session_manager_class = Type(
  1401. config=True,
  1402. help=_i18n("The session manager class to use."),
  1403. )
  1404. @default("session_manager_class")
  1405. def _default_session_manager_class(self) -> t.Union[str, type[SessionManager]]:
  1406. if self.gateway_config.gateway_enabled:
  1407. return "jupyter_server.gateway.managers.GatewaySessionManager"
  1408. return SessionManager
  1409. kernel_websocket_connection_class = Type(
  1410. klass=BaseKernelWebsocketConnection,
  1411. config=True,
  1412. help=_i18n("The kernel websocket connection class to use."),
  1413. )
  1414. @default("kernel_websocket_connection_class")
  1415. def _default_kernel_websocket_connection_class(
  1416. self,
  1417. ) -> t.Union[str, type[ZMQChannelsWebsocketConnection]]:
  1418. if self.gateway_config.gateway_enabled:
  1419. return "jupyter_server.gateway.connections.GatewayWebSocketConnection"
  1420. return ZMQChannelsWebsocketConnection
  1421. websocket_ping_interval = Integer(
  1422. config=True,
  1423. help="""
  1424. Configure the websocket ping interval in seconds.
  1425. Websockets are long-lived connections that are used by some Jupyter
  1426. Server extensions.
  1427. Periodic pings help to detect disconnected clients and keep the
  1428. connection active. If this is set to None, then no pings will be
  1429. performed.
  1430. When a ping is sent, the client has ``websocket_ping_timeout``
  1431. seconds to respond. If no response is received within this period,
  1432. the connection will be closed from the server side.
  1433. """,
  1434. )
  1435. websocket_ping_timeout = Integer(
  1436. config=True,
  1437. help="""
  1438. Configure the websocket ping timeout in seconds.
  1439. See ``websocket_ping_interval`` for details.
  1440. """,
  1441. )
  1442. config_manager_class = Type(
  1443. default_value=ConfigManager,
  1444. config=True,
  1445. help=_i18n("The config manager class to use"),
  1446. )
  1447. kernel_spec_manager = Instance(KernelSpecManager, allow_none=True)
  1448. kernel_spec_manager_class = Type(
  1449. config=True,
  1450. help="""
  1451. The kernel spec manager class to use. Should be a subclass
  1452. of `jupyter_client.kernelspec.KernelSpecManager`.
  1453. The Api of KernelSpecManager is provisional and might change
  1454. without warning between this version of Jupyter and the next stable one.
  1455. """,
  1456. )
  1457. @default("kernel_spec_manager_class")
  1458. def _default_kernel_spec_manager_class(self) -> t.Union[str, type[KernelSpecManager]]:
  1459. if self.gateway_config.gateway_enabled:
  1460. return "jupyter_server.gateway.managers.GatewayKernelSpecManager"
  1461. return KernelSpecManager
  1462. login_handler_class = Type(
  1463. default_value=LoginHandler,
  1464. klass=web.RequestHandler,
  1465. allow_none=True,
  1466. config=True,
  1467. help=_i18n("The login handler class to use."),
  1468. )
  1469. logout_handler_class = Type(
  1470. default_value=LogoutHandler,
  1471. klass=web.RequestHandler,
  1472. allow_none=True,
  1473. config=True,
  1474. help=_i18n("The logout handler class to use."),
  1475. )
  1476. # TODO: detect deprecated login handler config
  1477. authorizer_class = Type(
  1478. default_value=AllowAllAuthorizer,
  1479. klass=Authorizer,
  1480. config=True,
  1481. help=_i18n("The authorizer class to use."),
  1482. )
  1483. identity_provider_class = Type(
  1484. default_value=PasswordIdentityProvider,
  1485. klass=IdentityProvider,
  1486. config=True,
  1487. help=_i18n("The identity provider class to use."),
  1488. )
  1489. trust_xheaders = Bool(
  1490. False,
  1491. config=True,
  1492. help=(
  1493. _i18n(
  1494. "Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-For headers"
  1495. "sent by the upstream reverse proxy. Necessary if the proxy handles SSL"
  1496. )
  1497. ),
  1498. )
  1499. event_logger = Instance(
  1500. EventLogger,
  1501. allow_none=True,
  1502. help="An EventLogger for emitting structured event data from Jupyter Server and extensions.",
  1503. )
  1504. info_file = Unicode()
  1505. @default("info_file")
  1506. def _default_info_file(self) -> str:
  1507. info_file = "jpserver-%s.json" % os.getpid()
  1508. return os.path.join(self.runtime_dir, info_file)
  1509. no_browser_open_file = Bool(
  1510. False, help="If True, do not write redirect HTML file disk, or show in messages."
  1511. )
  1512. browser_open_file = Unicode()
  1513. @default("browser_open_file")
  1514. def _default_browser_open_file(self) -> str:
  1515. basename = "jpserver-%s-open.html" % os.getpid()
  1516. return os.path.join(self.runtime_dir, basename)
  1517. browser_open_file_to_run = Unicode()
  1518. @default("browser_open_file_to_run")
  1519. def _default_browser_open_file_to_run(self) -> str:
  1520. basename = "jpserver-file-to-run-%s-open.html" % os.getpid()
  1521. return os.path.join(self.runtime_dir, basename)
  1522. pylab = Unicode(
  1523. "disabled",
  1524. config=True,
  1525. help=_i18n(
  1526. """
  1527. DISABLED: use %pylab or %matplotlib in the notebook to enable matplotlib.
  1528. """
  1529. ),
  1530. )
  1531. @observe("pylab")
  1532. def _update_pylab(self, change: t.Any) -> None:
  1533. """when --pylab is specified, display a warning and exit"""
  1534. backend = " %s" % change["new"] if change["new"] != "warn" else ""
  1535. self.log.error(
  1536. _i18n("Support for specifying --pylab on the command line has been removed.")
  1537. )
  1538. self.log.error(
  1539. _i18n("Please use `%pylab{0}` or `%matplotlib{0}` in the notebook itself.").format(
  1540. backend
  1541. )
  1542. )
  1543. self.exit(1)
  1544. notebook_dir = Unicode(config=True, help=_i18n("DEPRECATED, use root_dir."))
  1545. @observe("notebook_dir")
  1546. def _update_notebook_dir(self, change: t.Any) -> None:
  1547. if self._root_dir_set:
  1548. # only use deprecated config if new config is not set
  1549. return
  1550. self.log.warning(_i18n("notebook_dir is deprecated, use root_dir"))
  1551. self.root_dir = change["new"]
  1552. external_connection_dir = Unicode(
  1553. None,
  1554. allow_none=True,
  1555. config=True,
  1556. help=_i18n(
  1557. "The directory to look at for external kernel connection files, if allow_external_kernels is True. "
  1558. "Defaults to Jupyter runtime_dir/external_kernels. "
  1559. "Make sure that this directory is not filled with left-over connection files, "
  1560. "that could result in unnecessary kernel manager creations."
  1561. ),
  1562. )
  1563. allow_external_kernels = Bool(
  1564. False,
  1565. config=True,
  1566. help=_i18n(
  1567. "Whether or not to allow external kernels, whose connection files are placed in external_connection_dir."
  1568. ),
  1569. )
  1570. root_dir = Unicode(config=True, help=_i18n("The directory to use for notebooks and kernels."))
  1571. _root_dir_set = False
  1572. @default("root_dir")
  1573. def _default_root_dir(self) -> str:
  1574. if self.file_to_run:
  1575. self._root_dir_set = True
  1576. return os.path.dirname(os.path.abspath(self.file_to_run))
  1577. else:
  1578. return os.getcwd()
  1579. def _normalize_dir(self, value: str) -> str:
  1580. """Normalize a directory."""
  1581. # Strip any trailing slashes
  1582. # *except* if it's root
  1583. _, path = os.path.splitdrive(value)
  1584. if path == os.sep:
  1585. return value
  1586. value = value.rstrip(os.sep)
  1587. if not os.path.isabs(value):
  1588. # If we receive a non-absolute path, make it absolute.
  1589. value = os.path.abspath(value)
  1590. return value
  1591. @validate("root_dir")
  1592. def _root_dir_validate(self, proposal: t.Any) -> str:
  1593. value = self._normalize_dir(proposal["value"])
  1594. if not os.path.isdir(value):
  1595. raise TraitError(trans.gettext("No such directory: '%r'") % value)
  1596. return value
  1597. @observe("root_dir")
  1598. def _root_dir_changed(self, change: t.Any) -> None:
  1599. # record that root_dir is set,
  1600. # which affects loading of deprecated notebook_dir
  1601. self._root_dir_set = True
  1602. preferred_dir = Unicode(
  1603. config=True,
  1604. help=trans.gettext(
  1605. "Preferred starting directory to use for notebooks and kernels. ServerApp.preferred_dir is deprecated in jupyter-server 2.0. Use FileContentsManager.preferred_dir instead"
  1606. ),
  1607. )
  1608. @default("preferred_dir")
  1609. def _default_prefered_dir(self) -> str:
  1610. return self.root_dir
  1611. @validate("preferred_dir")
  1612. def _preferred_dir_validate(self, proposal: t.Any) -> str:
  1613. value = self._normalize_dir(proposal["value"])
  1614. if not os.path.isdir(value):
  1615. raise TraitError(trans.gettext("No such preferred dir: '%r'") % value)
  1616. return value
  1617. @observe("server_extensions")
  1618. def _update_server_extensions(self, change: t.Any) -> None:
  1619. self.log.warning(_i18n("server_extensions is deprecated, use jpserver_extensions"))
  1620. self.server_extensions = change["new"]
  1621. jpserver_extensions = Dict(
  1622. default_value={},
  1623. value_trait=Bool(),
  1624. config=True,
  1625. help=(
  1626. _i18n(
  1627. "Dict of Python modules to load as Jupyter server extensions."
  1628. "Entry values can be used to enable and disable the loading of"
  1629. "the extensions. The extensions will be loaded in alphabetical "
  1630. "order."
  1631. )
  1632. ),
  1633. )
  1634. reraise_server_extension_failures = Bool(
  1635. False,
  1636. config=True,
  1637. help=_i18n("Reraise exceptions encountered loading server extensions?"),
  1638. )
  1639. kernel_ws_protocol = Unicode(
  1640. allow_none=True,
  1641. config=True,
  1642. help=_i18n("DEPRECATED. Use ZMQChannelsWebsocketConnection.kernel_ws_protocol"),
  1643. )
  1644. @observe("kernel_ws_protocol")
  1645. def _deprecated_kernel_ws_protocol(self, change: t.Any) -> None:
  1646. self._warn_deprecated_config(change, "ZMQChannelsWebsocketConnection")
  1647. limit_rate = Bool(
  1648. allow_none=True,
  1649. config=True,
  1650. help=_i18n("DEPRECATED. Use ZMQChannelsWebsocketConnection.limit_rate"),
  1651. )
  1652. @observe("limit_rate")
  1653. def _deprecated_limit_rate(self, change: t.Any) -> None:
  1654. self._warn_deprecated_config(change, "ZMQChannelsWebsocketConnection")
  1655. iopub_msg_rate_limit = Float(
  1656. allow_none=True,
  1657. config=True,
  1658. help=_i18n("DEPRECATED. Use ZMQChannelsWebsocketConnection.iopub_msg_rate_limit"),
  1659. )
  1660. @observe("iopub_msg_rate_limit")
  1661. def _deprecated_iopub_msg_rate_limit(self, change: t.Any) -> None:
  1662. self._warn_deprecated_config(change, "ZMQChannelsWebsocketConnection")
  1663. iopub_data_rate_limit = Float(
  1664. allow_none=True,
  1665. config=True,
  1666. help=_i18n("DEPRECATED. Use ZMQChannelsWebsocketConnection.iopub_data_rate_limit"),
  1667. )
  1668. @observe("iopub_data_rate_limit")
  1669. def _deprecated_iopub_data_rate_limit(self, change: t.Any) -> None:
  1670. self._warn_deprecated_config(change, "ZMQChannelsWebsocketConnection")
  1671. rate_limit_window = Float(
  1672. allow_none=True,
  1673. config=True,
  1674. help=_i18n("DEPRECATED. Use ZMQChannelsWebsocketConnection.rate_limit_window"),
  1675. )
  1676. @observe("rate_limit_window")
  1677. def _deprecated_rate_limit_window(self, change: t.Any) -> None:
  1678. self._warn_deprecated_config(change, "ZMQChannelsWebsocketConnection")
  1679. shutdown_no_activity_timeout = Integer(
  1680. 0,
  1681. config=True,
  1682. help=(
  1683. "Shut down the server after N seconds with no kernels"
  1684. "running and no activity. "
  1685. "This can be used together with culling idle kernels "
  1686. "(MappingKernelManager.cull_idle_timeout) to "
  1687. "shutdown the Jupyter server when it's not in use. This is not "
  1688. "precisely timed: it may shut down up to a minute later. "
  1689. "0 (the default) disables this automatic shutdown."
  1690. ),
  1691. )
  1692. terminals_enabled = Bool(
  1693. config=True,
  1694. help=_i18n(
  1695. """Set to False to disable terminals.
  1696. This does *not* make the server more secure by itself.
  1697. Anything the user can in a terminal, they can also do in a notebook.
  1698. Terminals may also be automatically disabled if the terminado package
  1699. is not available.
  1700. """
  1701. ),
  1702. )
  1703. @default("terminals_enabled")
  1704. def _default_terminals_enabled(self) -> bool:
  1705. return True
  1706. authenticate_prometheus = Bool(
  1707. True,
  1708. help=""""
  1709. Require authentication to access prometheus metrics.
  1710. """,
  1711. config=True,
  1712. )
  1713. record_http_request_metrics = Bool(
  1714. True,
  1715. help="""
  1716. Record http_request_duration_seconds metric in the metrics endpoint.
  1717. Since a histogram is exposed for each request handler, this can create a
  1718. *lot* of metrics, creating operational challenges for multitenant deployments.
  1719. Set to False to disable recording the http_request_duration_seconds metric.
  1720. """,
  1721. )
  1722. extra_log_scrub_param_keys = List(
  1723. Unicode(),
  1724. default_value=[],
  1725. config=True,
  1726. help="""
  1727. Additional URL parameter keys to scrub from logs.
  1728. These will be added to the default list of scrubbed parameter keys.
  1729. Any URL parameter whose key contains one of these substrings will have
  1730. its value replaced with '[secret]' in the logs. This is to prevent
  1731. sensitive information like authentication tokens from being leaked
  1732. in log files.
  1733. Default scrubbed keys: ["token", "auth", "key", "code", "state", "xsrf"]
  1734. """,
  1735. )
  1736. static_immutable_cache = List(
  1737. Unicode(),
  1738. help="""
  1739. Paths to set up static files as immutable.
  1740. This allow setting up the cache control of static files as immutable.
  1741. It should be used for static file named with a hash for instance.
  1742. """,
  1743. config=True,
  1744. )
  1745. _starter_app = Instance(
  1746. default_value=None,
  1747. allow_none=True,
  1748. klass="jupyter_server.extension.application.ExtensionApp",
  1749. )
  1750. @property
  1751. def starter_app(self) -> t.Any:
  1752. """Get the Extension that started this server."""
  1753. return self._starter_app
  1754. def parse_command_line(self, argv: t.Optional[list[str]] = None) -> None:
  1755. """Parse the command line options."""
  1756. super().parse_command_line(argv)
  1757. if self.extra_args:
  1758. arg0 = self.extra_args[0]
  1759. f = os.path.abspath(arg0)
  1760. self.argv.remove(arg0)
  1761. if not os.path.exists(f):
  1762. self.log.critical(_i18n("No such file or directory: %s"), f)
  1763. self.exit(1)
  1764. # Use config here, to ensure that it takes higher priority than
  1765. # anything that comes from the config dirs.
  1766. c = Config()
  1767. if os.path.isdir(f):
  1768. c.ServerApp.root_dir = f
  1769. elif os.path.isfile(f):
  1770. c.ServerApp.file_to_run = f
  1771. self.update_config(c)
  1772. def init_configurables(self) -> None:
  1773. """Initialize configurables."""
  1774. # If gateway server is configured, replace appropriate managers to perform redirection. To make
  1775. # this determination, instantiate the GatewayClient config singleton.
  1776. self.gateway_config = GatewayClient.instance(parent=self)
  1777. if not issubclass(
  1778. self.kernel_manager_class,
  1779. AsyncMappingKernelManager,
  1780. ):
  1781. warnings.warn(
  1782. "The synchronous MappingKernelManager class is deprecated and will not be supported in Jupyter Server 3.0",
  1783. DeprecationWarning,
  1784. stacklevel=2,
  1785. )
  1786. if not issubclass(
  1787. self.contents_manager_class,
  1788. AsyncContentsManager,
  1789. ):
  1790. warnings.warn(
  1791. "The synchronous ContentsManager classes are deprecated and will not be supported in Jupyter Server 3.0",
  1792. DeprecationWarning,
  1793. stacklevel=2,
  1794. )
  1795. self.kernel_spec_manager = self.kernel_spec_manager_class(
  1796. parent=self,
  1797. )
  1798. kwargs = {
  1799. "parent": self,
  1800. "log": self.log,
  1801. "connection_dir": self.runtime_dir,
  1802. "kernel_spec_manager": self.kernel_spec_manager,
  1803. }
  1804. if jupyter_client.version_info > (8, 3, 0): # type:ignore[attr-defined]
  1805. if self.allow_external_kernels:
  1806. external_connection_dir = self.external_connection_dir
  1807. if external_connection_dir is None:
  1808. external_connection_dir = str(Path(self.runtime_dir) / "external_kernels")
  1809. kwargs["external_connection_dir"] = external_connection_dir
  1810. elif self.allow_external_kernels:
  1811. self.log.warning(
  1812. "Although allow_external_kernels=True, external kernels are not supported "
  1813. "because jupyter-client's version does not allow them (should be >8.3.0)."
  1814. )
  1815. self.kernel_manager = self.kernel_manager_class(**kwargs)
  1816. self.contents_manager = self.contents_manager_class(
  1817. parent=self,
  1818. log=self.log,
  1819. )
  1820. # Trigger a default/validation here explicitly while we still support the
  1821. # deprecated trait on ServerApp (FIXME remove when deprecation finalized)
  1822. self.contents_manager.preferred_dir # noqa: B018
  1823. self.session_manager = self.session_manager_class(
  1824. parent=self,
  1825. log=self.log,
  1826. kernel_manager=self.kernel_manager,
  1827. contents_manager=self.contents_manager,
  1828. )
  1829. self.config_manager = self.config_manager_class(
  1830. parent=self,
  1831. log=self.log,
  1832. )
  1833. identity_provider_kwargs = {"parent": self, "log": self.log}
  1834. if (
  1835. self.login_handler_class is not LoginHandler
  1836. and self.identity_provider_class is PasswordIdentityProvider
  1837. ):
  1838. # default identity provider, non-default LoginHandler
  1839. # this indicates legacy custom LoginHandler config.
  1840. # enable LegacyIdentityProvider, which defers to the LoginHandler for pre-2.0 behavior.
  1841. self.identity_provider_class = LegacyIdentityProvider
  1842. self.log.warning(
  1843. f"Customizing authentication via ServerApp.login_handler_class={self.login_handler_class}"
  1844. " is deprecated in Jupyter Server 2.0."
  1845. " Use ServerApp.identity_provider_class."
  1846. " Falling back on legacy authentication.",
  1847. )
  1848. identity_provider_kwargs["login_handler_class"] = self.login_handler_class
  1849. if self.logout_handler_class:
  1850. identity_provider_kwargs["logout_handler_class"] = self.logout_handler_class
  1851. elif self.login_handler_class is not LoginHandler:
  1852. # non-default login handler ignored because also explicitly set identity provider
  1853. self.log.warning(
  1854. f"Ignoring deprecated config ServerApp.login_handler_class={self.login_handler_class}."
  1855. " Superseded by ServerApp.identity_provider_class={self.identity_provider_class}."
  1856. )
  1857. self.identity_provider = self.identity_provider_class(**identity_provider_kwargs)
  1858. if self.identity_provider_class is LegacyIdentityProvider:
  1859. # legacy config stored the password in tornado_settings
  1860. self.tornado_settings["password"] = self.identity_provider.hashed_password # type:ignore[attr-defined]
  1861. self.tornado_settings["token"] = self.identity_provider.token
  1862. if self._token_set:
  1863. self.log.warning(
  1864. "ServerApp.token config is deprecated in jupyter-server 2.0. Use IdentityProvider.token"
  1865. )
  1866. if self.identity_provider.token_generated:
  1867. # default behavior: generated default token
  1868. # preserve deprecated ServerApp.token config
  1869. self.identity_provider.token_generated = False
  1870. self.identity_provider.token = self.token
  1871. else:
  1872. # identity_provider didn't generate a default token,
  1873. # that means it has some config that should take higher priority than deprecated ServerApp.token
  1874. self.log.warning("Ignoring deprecated ServerApp.token config")
  1875. self.authorizer = self.authorizer_class(
  1876. parent=self, log=self.log, identity_provider=self.identity_provider
  1877. )
  1878. def init_logging(self) -> None:
  1879. """Initialize logging."""
  1880. # This prevents double log messages because tornado use a root logger that
  1881. # self.log is a child of. The logging module dipatches log messages to a log
  1882. # and all of its ancenstors until propagate is set to False.
  1883. self.log.propagate = False
  1884. for log in app_log, access_log, gen_log:
  1885. # consistent log output name (ServerApp instead of tornado.access, etc.)
  1886. log.name = self.log.name
  1887. # hook up tornado 3's loggers to our app handlers
  1888. logger = logging.getLogger("tornado")
  1889. logger.propagate = True
  1890. logger.parent = self.log
  1891. logger.setLevel(self.log.level)
  1892. def init_event_logger(self) -> None:
  1893. """Initialize the Event Bus."""
  1894. self.event_logger = EventLogger(parent=self)
  1895. # Load the core Jupyter Server event schemas
  1896. # All event schemas must start with Jupyter Server's
  1897. # events URI, `JUPYTER_SERVER_EVENTS_URI`.
  1898. schema_ids = [
  1899. "https://events.jupyter.org/jupyter_server/contents_service/v1",
  1900. "https://events.jupyter.org/jupyter_server/gateway_client/v1",
  1901. "https://events.jupyter.org/jupyter_server/kernel_actions/v1",
  1902. ]
  1903. for schema_id in schema_ids:
  1904. # Get the schema path from the schema ID.
  1905. rel_schema_path = schema_id.replace(JUPYTER_SERVER_EVENTS_URI + "/", "") + ".yaml"
  1906. schema_path = DEFAULT_EVENTS_SCHEMA_PATH / rel_schema_path
  1907. # Use this pathlib object to register the schema
  1908. self.event_logger.register_event_schema(schema_path)
  1909. def init_webapp(self) -> None:
  1910. """initialize tornado webapp"""
  1911. self.tornado_settings["allow_origin"] = self.allow_origin
  1912. self.tornado_settings["websocket_compression_options"] = self.websocket_compression_options
  1913. if self.allow_origin_pat:
  1914. self.tornado_settings["allow_origin_pat"] = re.compile(self.allow_origin_pat)
  1915. self.tornado_settings["allow_credentials"] = self.allow_credentials
  1916. self.tornado_settings["autoreload"] = self.autoreload
  1917. # deprecate accessing these directly, in favor of identity_provider?
  1918. self.tornado_settings["cookie_options"] = self.identity_provider.cookie_options
  1919. self.tornado_settings["get_secure_cookie_kwargs"] = (
  1920. self.identity_provider.get_secure_cookie_kwargs
  1921. )
  1922. self.tornado_settings["token"] = self.identity_provider.token
  1923. if self.static_immutable_cache:
  1924. self.tornado_settings["static_immutable_cache"] = self.static_immutable_cache
  1925. # ensure default_url starts with base_url
  1926. if not self.default_url.startswith(self.base_url):
  1927. self.default_url = url_path_join(self.base_url, self.default_url)
  1928. # Socket options validation.
  1929. if self.sock:
  1930. if self.port != DEFAULT_JUPYTER_SERVER_PORT:
  1931. self.log.critical(
  1932. ("Options --port and --sock are mutually exclusive. Aborting."),
  1933. )
  1934. sys.exit(1)
  1935. else:
  1936. # Reset the default port if we're using a UNIX socket.
  1937. self.port = 0
  1938. if self.open_browser:
  1939. # If we're bound to a UNIX socket, we can't reliably connect from a browser.
  1940. self.log.info(
  1941. ("Ignoring --ServerApp.open_browser due to --sock being used."),
  1942. )
  1943. if self.file_to_run:
  1944. self.log.critical(
  1945. ("Options --ServerApp.file_to_run and --sock are mutually exclusive."),
  1946. )
  1947. sys.exit(1)
  1948. if sys.platform.startswith("win"):
  1949. self.log.critical(
  1950. (
  1951. "Option --sock is not supported on Windows, but got value of %s. Aborting."
  1952. % self.sock
  1953. ),
  1954. )
  1955. sys.exit(1)
  1956. self.web_app = ServerWebApplication(
  1957. self,
  1958. self.default_services,
  1959. self.kernel_manager,
  1960. self.contents_manager,
  1961. self.session_manager,
  1962. self.kernel_spec_manager,
  1963. self.config_manager,
  1964. self.event_logger,
  1965. self.extra_services,
  1966. self.log,
  1967. self.base_url,
  1968. self.default_url,
  1969. self.tornado_settings,
  1970. self.jinja_environment_options,
  1971. authorizer=self.authorizer,
  1972. identity_provider=self.identity_provider,
  1973. kernel_websocket_connection_class=self.kernel_websocket_connection_class,
  1974. websocket_ping_interval=self.websocket_ping_interval,
  1975. websocket_ping_timeout=self.websocket_ping_timeout,
  1976. )
  1977. if self.certfile:
  1978. self.ssl_options["certfile"] = self.certfile
  1979. if self.keyfile:
  1980. self.ssl_options["keyfile"] = self.keyfile
  1981. if self.client_ca:
  1982. self.ssl_options["ca_certs"] = self.client_ca
  1983. if not self.ssl_options:
  1984. # could be an empty dict or None
  1985. # None indicates no SSL config
  1986. self.ssl_options = None # type:ignore[assignment]
  1987. else:
  1988. # SSL may be missing, so only import it if it's to be used
  1989. import ssl
  1990. # PROTOCOL_TLS selects the highest ssl/tls protocol version that both the client and
  1991. # server support. When PROTOCOL_TLS is not available use PROTOCOL_SSLv23.
  1992. self.ssl_options.setdefault(
  1993. "ssl_version", getattr(ssl, "PROTOCOL_TLS", ssl.PROTOCOL_SSLv23)
  1994. )
  1995. if self.ssl_options.get("ca_certs", False):
  1996. self.ssl_options.setdefault("cert_reqs", ssl.CERT_REQUIRED)
  1997. self.identity_provider.validate_security(self, ssl_options=self.ssl_options)
  1998. if isinstance(self.identity_provider, LegacyIdentityProvider):
  1999. # LegacyIdentityProvider needs access to the tornado settings dict
  2000. self.identity_provider.settings = self.web_app.settings
  2001. def init_resources(self) -> None:
  2002. """initialize system resources"""
  2003. if resource is None:
  2004. self.log.debug( # type:ignore[unreachable]
  2005. "Ignoring min_open_files_limit because the limit cannot be adjusted (for example, on Windows)"
  2006. )
  2007. return
  2008. old_soft, old_hard = resource.getrlimit(resource.RLIMIT_NOFILE)
  2009. soft = self.min_open_files_limit
  2010. hard = old_hard
  2011. if soft is not None and old_soft < soft:
  2012. if hard < soft:
  2013. hard = soft
  2014. self.log.debug(
  2015. f"Raising open file limit: soft {old_soft}->{soft}; hard {old_hard}->{hard}"
  2016. )
  2017. resource.setrlimit(resource.RLIMIT_NOFILE, (soft, hard))
  2018. def _get_urlparts(
  2019. self, path: t.Optional[str] = None, include_token: bool = False
  2020. ) -> urllib.parse.ParseResult:
  2021. """Constructs a urllib named tuple, ParseResult,
  2022. with default values set by server config.
  2023. The returned tuple can be manipulated using the `_replace` method.
  2024. """
  2025. if self.sock:
  2026. scheme = "http+unix"
  2027. netloc = urlencode_unix_socket_path(self.sock)
  2028. else:
  2029. if not self.ip:
  2030. ip = "localhost"
  2031. # Handle nonexplicit hostname.
  2032. elif self.ip in ("0.0.0.0", "::"): # noqa: S104
  2033. ip = "%s" % socket.gethostname()
  2034. else:
  2035. ip = f"[{self.ip}]" if ":" in self.ip else self.ip
  2036. netloc = f"{ip}:{self.port}"
  2037. scheme = "https" if self.certfile else "http"
  2038. if not path:
  2039. path = self.default_url
  2040. query = None
  2041. # Don't log full token if it came from config
  2042. if include_token and self.identity_provider.token:
  2043. token = (
  2044. self.identity_provider.token if self.identity_provider.token_generated else "..."
  2045. )
  2046. query = urllib.parse.urlencode({"token": token})
  2047. # Build the URL Parts to dump.
  2048. urlparts = urllib.parse.ParseResult(
  2049. scheme=scheme, netloc=netloc, path=path, query=query or "", params="", fragment=""
  2050. )
  2051. return urlparts
  2052. @property
  2053. def public_url(self) -> str:
  2054. parts = self._get_urlparts(include_token=True)
  2055. # Update with custom pieces.
  2056. if self.custom_display_url:
  2057. # Parse custom display_url
  2058. custom = urllib.parse.urlparse(self.custom_display_url)._asdict()
  2059. # Get pieces that are matter (non None)
  2060. custom_updates = {key: item for key, item in custom.items() if item}
  2061. # Update public URL parts with custom pieces.
  2062. parts = parts._replace(**custom_updates)
  2063. return parts.geturl()
  2064. @property
  2065. def local_url(self) -> str:
  2066. parts = self._get_urlparts(include_token=True)
  2067. # Update with custom pieces.
  2068. if not self.sock:
  2069. localhost = "[::1]" if ":" in self.ip else "127.0.0.1"
  2070. parts = parts._replace(netloc=f"{localhost}:{self.port}")
  2071. return parts.geturl()
  2072. @property
  2073. def display_url(self) -> str:
  2074. """Human readable string with URLs for interacting
  2075. with the running Jupyter Server
  2076. """
  2077. url = self.public_url
  2078. if self.public_url != self.local_url:
  2079. url = f"{url}\n {self.local_url}"
  2080. return url
  2081. @property
  2082. def connection_url(self) -> str:
  2083. urlparts = self._get_urlparts(path=self.base_url)
  2084. return urlparts.geturl()
  2085. def init_signal(self) -> None:
  2086. """Initialize signal handlers."""
  2087. if (
  2088. not sys.platform.startswith("win")
  2089. and sys.stdin # type:ignore[truthy-bool]
  2090. and sys.stdin.isatty()
  2091. ):
  2092. signal.signal(signal.SIGINT, self._handle_sigint)
  2093. signal.signal(signal.SIGTERM, self._signal_stop)
  2094. if hasattr(signal, "SIGUSR1"):
  2095. # Windows doesn't support SIGUSR1
  2096. signal.signal(signal.SIGUSR1, self._signal_info)
  2097. if hasattr(signal, "SIGINFO"):
  2098. # only on BSD-based systems
  2099. signal.signal(signal.SIGINFO, self._signal_info)
  2100. def _handle_sigint(self, sig: t.Any, frame: t.Any) -> None:
  2101. """SIGINT handler spawns confirmation dialog
  2102. Note:
  2103. JupyterHub replaces this method with _signal_stop
  2104. in order to bypass the interactive prompt.
  2105. https://github.com/jupyterhub/jupyterhub/pull/4864
  2106. """
  2107. # register more forceful signal handler for ^C^C case
  2108. signal.signal(signal.SIGINT, self._signal_stop)
  2109. # request confirmation dialog in bg thread, to avoid
  2110. # blocking the App
  2111. thread = threading.Thread(target=self._confirm_exit)
  2112. thread.daemon = True
  2113. thread.start()
  2114. def _restore_sigint_handler(self) -> None:
  2115. """callback for restoring original SIGINT handler"""
  2116. signal.signal(signal.SIGINT, self._handle_sigint)
  2117. def _confirm_exit(self) -> None:
  2118. """confirm shutdown on ^C
  2119. A second ^C, or answering 'y' within 5s will cause shutdown,
  2120. otherwise original SIGINT handler will be restored.
  2121. This doesn't work on Windows.
  2122. """
  2123. info = self.log.info
  2124. info(_i18n("interrupted"))
  2125. # Check if answer_yes is set
  2126. if self.answer_yes:
  2127. self.log.critical(_i18n("Shutting down..."))
  2128. # schedule stop on the main thread,
  2129. # since this might be called from a signal handler
  2130. self.stop(from_signal=True)
  2131. return
  2132. info(self.running_server_info())
  2133. yes = _i18n("y")
  2134. no = _i18n("n")
  2135. sys.stdout.write(_i18n("Shut down this Jupyter server (%s/[%s])? ") % (yes, no))
  2136. sys.stdout.flush()
  2137. r, w, x = select.select([sys.stdin], [], [], 5)
  2138. if r:
  2139. line = sys.stdin.readline()
  2140. if line.lower().startswith(yes) and no not in line.lower():
  2141. self.log.critical(_i18n("Shutdown confirmed"))
  2142. # schedule stop on the main thread,
  2143. # since this might be called from a signal handler
  2144. self.stop(from_signal=True)
  2145. return
  2146. else:
  2147. if self._stopping:
  2148. # don't show 'no answer' if we're actually stopping,
  2149. # e.g. ctrl-C ctrl-C
  2150. return
  2151. info(_i18n("No answer for 5s:"))
  2152. info(_i18n("resuming operation..."))
  2153. # no answer, or answer is no:
  2154. # set it back to original SIGINT handler
  2155. # use IOLoop.add_callback because signal.signal must be called
  2156. # from main thread
  2157. self.io_loop.add_callback_from_signal(self._restore_sigint_handler)
  2158. def _signal_stop(self, sig: t.Any, frame: t.Any) -> None:
  2159. """Handle a stop signal.
  2160. Note:
  2161. JupyterHub configures this method to be called for SIGINT.
  2162. https://github.com/jupyterhub/jupyterhub/pull/4864
  2163. """
  2164. self.log.critical(_i18n("received signal %s, stopping"), sig)
  2165. self.stop(from_signal=True)
  2166. def _signal_info(self, sig: t.Any, frame: t.Any) -> None:
  2167. """Handle an info signal."""
  2168. self.log.info(self.running_server_info())
  2169. def init_components(self) -> None:
  2170. """Check the components submodule, and warn if it's unclean"""
  2171. # TODO: this should still check, but now we use bower, not git submodule
  2172. def find_server_extensions(self) -> None:
  2173. """
  2174. Searches Jupyter paths for jpserver_extensions.
  2175. """
  2176. # Walk through all config files looking for jpserver_extensions.
  2177. #
  2178. # Each extension will likely have a JSON config file enabling itself in
  2179. # the "jupyter_server_config.d" directory. Find each of these and
  2180. # merge there results in order of precedence.
  2181. #
  2182. # Load server extensions with ConfigManager.
  2183. # This enables merging on keys, which we want for extension enabling.
  2184. # Regular config loading only merges at the class level,
  2185. # so each level clobbers the previous.
  2186. manager = ExtensionConfigManager(read_config_path=self.config_file_paths)
  2187. extensions = manager.get_jpserver_extensions()
  2188. for modulename, enabled in sorted(extensions.items()):
  2189. if modulename not in self.jpserver_extensions:
  2190. self.config.ServerApp.jpserver_extensions.update({modulename: enabled})
  2191. self.jpserver_extensions.update({modulename: enabled})
  2192. def init_server_extensions(self) -> None:
  2193. """
  2194. If an extension's metadata includes an 'app' key,
  2195. the value must be a subclass of ExtensionApp. An instance
  2196. of the class will be created at this step. The config for
  2197. this instance will inherit the ServerApp's config object
  2198. and load its own config.
  2199. """
  2200. # Create an instance of the ExtensionManager.
  2201. self.extension_manager = ExtensionManager(log=self.log, serverapp=self)
  2202. self.extension_manager.from_jpserver_extensions(self.jpserver_extensions)
  2203. self.extension_manager.link_all_extensions()
  2204. def load_server_extensions(self) -> None:
  2205. """Load any extensions specified by config.
  2206. Import the module, then call the load_jupyter_server_extension function,
  2207. if one exists.
  2208. The extension API is experimental, and may change in future releases.
  2209. """
  2210. self.extension_manager.load_all_extensions()
  2211. def init_mime_overrides(self) -> None:
  2212. # On some Windows machines, an application has registered incorrect
  2213. # mimetypes in the registry.
  2214. # Tornado uses this when serving .css and .js files, causing browsers to
  2215. # reject these files. We know the mimetype always needs to be text/css for css
  2216. # and application/javascript for JS, so we override it here
  2217. # and explicitly tell the mimetypes to not trust the Windows registry
  2218. if os.name == "nt":
  2219. # do not trust windows registry, which regularly has bad info
  2220. mimetypes.init(files=[])
  2221. # ensure css, js are correct, which are required for pages to function
  2222. mimetypes.add_type("text/css", ".css")
  2223. mimetypes.add_type("application/javascript", ".js")
  2224. def shutdown_no_activity(self) -> None:
  2225. """Shutdown server on timeout when there are no kernels or terminals."""
  2226. km = self.kernel_manager
  2227. if len(km) != 0:
  2228. return # Kernels still running
  2229. if self.extension_manager.any_activity():
  2230. return
  2231. seconds_since_active = (utcnow() - self.web_app.last_activity()).total_seconds()
  2232. self.log.debug("No activity for %d seconds.", seconds_since_active)
  2233. if seconds_since_active > self.shutdown_no_activity_timeout:
  2234. self.log.info(
  2235. "No kernels for %d seconds; shutting down.",
  2236. seconds_since_active,
  2237. )
  2238. self.stop()
  2239. def init_shutdown_no_activity(self) -> None:
  2240. """Initialize a shutdown on no activity."""
  2241. if self.shutdown_no_activity_timeout > 0:
  2242. self.log.info(
  2243. "Will shut down after %d seconds with no kernels.",
  2244. self.shutdown_no_activity_timeout,
  2245. )
  2246. pc = ioloop.PeriodicCallback(self.shutdown_no_activity, 60000)
  2247. pc.start()
  2248. @property
  2249. def http_server(self) -> httpserver.HTTPServer:
  2250. """An instance of Tornado's HTTPServer class for the Server Web Application."""
  2251. try:
  2252. return self._http_server
  2253. except AttributeError:
  2254. msg = (
  2255. "An HTTPServer instance has not been created for the "
  2256. "Server Web Application. To create an HTTPServer for this "
  2257. "application, call `.init_httpserver()`."
  2258. )
  2259. raise AttributeError(msg) from None
  2260. def init_httpserver(self) -> None:
  2261. """Creates an instance of a Tornado HTTPServer for the Server Web Application
  2262. and sets the http_server attribute.
  2263. """
  2264. # Check that a web_app has been initialized before starting a server.
  2265. if not hasattr(self, "web_app"):
  2266. msg = (
  2267. "A tornado web application has not be initialized. "
  2268. "Try calling `.init_webapp()` first."
  2269. )
  2270. raise AttributeError(msg)
  2271. # Create an instance of the server.
  2272. self._http_server = httpserver.HTTPServer(
  2273. self.web_app,
  2274. ssl_options=self.ssl_options,
  2275. xheaders=self.trust_xheaders,
  2276. max_body_size=self.max_body_size,
  2277. max_buffer_size=self.max_buffer_size,
  2278. )
  2279. # binding sockets must be called from inside an event loop
  2280. if not self.sock:
  2281. self._find_http_port()
  2282. self.io_loop.add_callback(self._bind_http_server)
  2283. def _bind_http_server(self) -> None:
  2284. """Bind our http server."""
  2285. success = self._bind_http_server_unix() if self.sock else self._bind_http_server_tcp()
  2286. if not success:
  2287. self.log.critical(
  2288. _i18n(
  2289. "ERROR: the Jupyter server could not be started because "
  2290. "no available port could be found."
  2291. )
  2292. )
  2293. self.exit(1)
  2294. def _bind_http_server_unix(self) -> bool:
  2295. """Bind an http server on unix."""
  2296. if unix_socket_in_use(self.sock):
  2297. self.log.warning(_i18n("The socket %s is already in use.") % self.sock)
  2298. return False
  2299. try:
  2300. sock = bind_unix_socket(self.sock, mode=int(self.sock_mode.encode(), 8))
  2301. self.http_server.add_socket(sock)
  2302. except OSError as e:
  2303. if e.errno == errno.EADDRINUSE:
  2304. self.log.warning(_i18n("The socket %s is already in use.") % self.sock)
  2305. return False
  2306. elif e.errno in (errno.EACCES, getattr(errno, "WSAEACCES", errno.EACCES)):
  2307. self.log.warning(_i18n("Permission to listen on sock %s denied") % self.sock)
  2308. return False
  2309. else:
  2310. raise
  2311. else:
  2312. return True
  2313. def _bind_http_server_tcp(self) -> bool:
  2314. """Bind a tcp server."""
  2315. self.http_server.listen(self.port, self.ip)
  2316. return True
  2317. def _find_http_port(self) -> None:
  2318. """Find an available http port."""
  2319. success = False
  2320. port = self.port
  2321. for port in random_ports(self.port, self.port_retries + 1):
  2322. try:
  2323. sockets = bind_sockets(port, self.ip)
  2324. sockets[0].close()
  2325. except OSError as e:
  2326. if e.errno == errno.EADDRINUSE:
  2327. if self.port_retries:
  2328. self.log.info(
  2329. _i18n("The port %i is already in use, trying another port.") % port
  2330. )
  2331. else:
  2332. self.log.info(_i18n("The port %i is already in use.") % port)
  2333. continue
  2334. if e.errno in (
  2335. errno.EACCES,
  2336. getattr(errno, "WSAEACCES", errno.EACCES),
  2337. ):
  2338. self.log.warning(_i18n("Permission to listen on port %i denied.") % port)
  2339. continue
  2340. raise
  2341. else:
  2342. success = True
  2343. self.port = port
  2344. break
  2345. if not success:
  2346. if self.port_retries:
  2347. self.log.critical(
  2348. _i18n(
  2349. "ERROR: the Jupyter server could not be started because "
  2350. "no available port could be found."
  2351. )
  2352. )
  2353. else:
  2354. self.log.critical(
  2355. _i18n(
  2356. "ERROR: the Jupyter server could not be started because "
  2357. "port %i is not available."
  2358. )
  2359. % port
  2360. )
  2361. self.exit(1)
  2362. @staticmethod
  2363. def _init_asyncio_patch() -> None:
  2364. """set default asyncio policy to be compatible with tornado
  2365. Tornado 6.0 is not compatible with default asyncio
  2366. ProactorEventLoop, which lacks basic *_reader methods.
  2367. Tornado 6.1 adds a workaround to add these methods in a thread,
  2368. but SelectorEventLoop should still be preferred
  2369. to avoid the extra thread for ~all of our events,
  2370. at least until asyncio adds *_reader methods
  2371. to proactor.
  2372. """
  2373. if sys.platform.startswith("win"):
  2374. import asyncio
  2375. try:
  2376. from asyncio import WindowsProactorEventLoopPolicy, WindowsSelectorEventLoopPolicy
  2377. except ImportError:
  2378. pass
  2379. # not affected
  2380. else:
  2381. if type(asyncio.get_event_loop_policy()) is WindowsProactorEventLoopPolicy:
  2382. # prefer Selector to Proactor for tornado + pyzmq
  2383. asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy())
  2384. def init_metrics(self) -> None:
  2385. """
  2386. Initialize any prometheus metrics that need to be set up on server startup
  2387. """
  2388. SERVER_INFO.info({"version": __version__})
  2389. for ext in self.extension_manager.extensions.values():
  2390. SERVER_EXTENSION_INFO.labels(
  2391. name=ext.name, version=ext.version, enabled=str(ext.enabled).lower()
  2392. )
  2393. started = self.web_app.settings["started"]
  2394. SERVER_STARTED.set(started.timestamp())
  2395. LAST_ACTIVITY.set_function(lambda: self.web_app.last_activity().timestamp())
  2396. ACTIVE_DURATION.set_function(
  2397. lambda: (
  2398. self.web_app.last_activity() - self.web_app.settings["started"]
  2399. ).total_seconds()
  2400. )
  2401. @catch_config_error
  2402. def initialize(
  2403. self,
  2404. argv: t.Optional[list[str]] = None,
  2405. find_extensions: bool = True,
  2406. new_httpserver: bool = True,
  2407. starter_extension: t.Any = None,
  2408. ) -> None:
  2409. """Initialize the Server application class, configurables, web application, and http server.
  2410. Parameters
  2411. ----------
  2412. argv : list or None
  2413. CLI arguments to parse.
  2414. find_extensions : bool
  2415. If True, find and load extensions listed in Jupyter config paths. If False,
  2416. only load extensions that are passed to ServerApp directly through
  2417. the `argv`, `config`, or `jpserver_extensions` arguments.
  2418. new_httpserver : bool
  2419. If True, a tornado HTTPServer instance will be created and configured for the Server Web
  2420. Application. This will set the http_server attribute of this class.
  2421. starter_extension : str
  2422. If given, it references the name of an extension point that started the Server.
  2423. We will try to load configuration from extension point
  2424. """
  2425. self._init_asyncio_patch()
  2426. # Parse command line, load ServerApp config files,
  2427. # and update ServerApp config.
  2428. # preserve jpserver_extensions, which may have been set by starter_extension
  2429. # don't let config clobber this value
  2430. jpserver_extensions = self.jpserver_extensions.copy()
  2431. super().initialize(argv=argv)
  2432. self.jpserver_extensions.update(jpserver_extensions)
  2433. if self._dispatching:
  2434. return
  2435. # initialize io loop as early as possible,
  2436. # so configurables, extensions may reference the event loop
  2437. self.init_ioloop()
  2438. # Then, use extensions' config loading mechanism to
  2439. # update config. ServerApp config takes precedence.
  2440. if find_extensions:
  2441. self.find_server_extensions()
  2442. self.init_logging()
  2443. self.init_event_logger()
  2444. self.init_server_extensions()
  2445. # Special case the starter extension and load
  2446. # any server configuration is provides.
  2447. if starter_extension:
  2448. # Configure ServerApp based on named extension.
  2449. point = self.extension_manager.extension_points[starter_extension]
  2450. # Set starter_app property.
  2451. if point.app:
  2452. self._starter_app = point.app
  2453. # Load any configuration that comes from the Extension point.
  2454. self.update_config(Config(point.config))
  2455. # Initialize other pieces of the server.
  2456. self.init_resources()
  2457. self.init_configurables()
  2458. self.init_components()
  2459. self.init_webapp()
  2460. self.init_signal()
  2461. self.load_server_extensions()
  2462. self.init_mime_overrides()
  2463. self.init_shutdown_no_activity()
  2464. self.init_metrics()
  2465. if new_httpserver:
  2466. self.init_httpserver()
  2467. async def cleanup_kernels(self) -> None:
  2468. """Shutdown all kernels.
  2469. The kernels will shutdown themselves when this process no longer exists,
  2470. but explicit shutdown allows the KernelManagers to cleanup the connection files.
  2471. """
  2472. if not getattr(self, "kernel_manager", None):
  2473. return
  2474. n_kernels = len(self.kernel_manager.list_kernel_ids())
  2475. kernel_msg = trans.ngettext(
  2476. "Shutting down %d kernel", "Shutting down %d kernels", n_kernels
  2477. )
  2478. self.log.info(kernel_msg % n_kernels)
  2479. await ensure_async(self.kernel_manager.shutdown_all())
  2480. async def cleanup_extensions(self) -> None:
  2481. """Call shutdown hooks in all extensions."""
  2482. if not getattr(self, "extension_manager", None):
  2483. return
  2484. n_extensions = len(self.extension_manager.extension_apps)
  2485. extension_msg = trans.ngettext(
  2486. "Shutting down %d extension", "Shutting down %d extensions", n_extensions
  2487. )
  2488. self.log.info(extension_msg % n_extensions)
  2489. await ensure_async(self.extension_manager.stop_all_extensions())
  2490. def running_server_info(self, kernel_count: bool = True) -> str:
  2491. """Return the current working directory and the server url information"""
  2492. info = t.cast(str, self.contents_manager.info_string()) + "\n"
  2493. if kernel_count:
  2494. n_kernels = len(self.kernel_manager.list_kernel_ids())
  2495. kernel_msg = trans.ngettext("%d active kernel", "%d active kernels", n_kernels)
  2496. info += kernel_msg % n_kernels
  2497. info += "\n"
  2498. # Format the info so that the URL fits on a single line in 80 char display
  2499. info += _i18n("Jupyter Server {version} is running at:\n{url}").format(
  2500. version=ServerApp.version, url=self.display_url
  2501. )
  2502. if self.gateway_config.gateway_enabled:
  2503. info += (
  2504. _i18n("\nKernels will be managed by the Gateway server running at:\n%s")
  2505. % self.gateway_config.url
  2506. )
  2507. return info
  2508. def server_info(self) -> dict[str, t.Any]:
  2509. """Return a JSONable dict of information about this server."""
  2510. return {
  2511. "url": self.connection_url,
  2512. "hostname": self.ip if self.ip else "localhost",
  2513. "port": self.port,
  2514. "sock": self.sock,
  2515. "secure": bool(self.certfile),
  2516. "base_url": self.base_url,
  2517. "token": self.identity_provider.token,
  2518. "root_dir": os.path.abspath(self.root_dir),
  2519. "password": bool(self.password),
  2520. "pid": os.getpid(),
  2521. "version": ServerApp.version,
  2522. }
  2523. def write_server_info_file(self) -> None:
  2524. """Write the result of server_info() to the JSON file info_file."""
  2525. try:
  2526. with secure_write(self.info_file) as f:
  2527. json.dump(self.server_info(), f, indent=2, sort_keys=True)
  2528. except OSError as e:
  2529. self.log.error(_i18n("Failed to write server-info to %s: %r"), self.info_file, e)
  2530. def remove_server_info_file(self) -> None:
  2531. """Remove the jpserver-<pid>.json file created for this server.
  2532. Ignores the error raised when the file has already been removed.
  2533. """
  2534. try:
  2535. os.unlink(self.info_file)
  2536. except OSError as e:
  2537. if e.errno != errno.ENOENT:
  2538. raise
  2539. def _resolve_file_to_run_and_root_dir(self) -> str:
  2540. """Returns a relative path from file_to_run
  2541. to root_dir. If root_dir and file_to_run
  2542. are incompatible, i.e. on different subtrees,
  2543. crash the app and log a critical message. Note
  2544. that if root_dir is not configured and file_to_run
  2545. is configured, root_dir will be set to the parent
  2546. directory of file_to_run.
  2547. """
  2548. rootdir_abspath = pathlib.Path(self.root_dir).absolute()
  2549. file_rawpath = pathlib.Path(self.file_to_run)
  2550. combined_path = (rootdir_abspath / file_rawpath).absolute()
  2551. is_child = str(combined_path).startswith(str(rootdir_abspath))
  2552. if is_child:
  2553. if combined_path.parent != rootdir_abspath:
  2554. self.log.debug(
  2555. "The `root_dir` trait is set to a directory that's not "
  2556. "the immediate parent directory of `file_to_run`. Note that "
  2557. "the server will start at `root_dir` and open the "
  2558. "the file from the relative path to the `root_dir`."
  2559. )
  2560. return str(combined_path.relative_to(rootdir_abspath))
  2561. self.log.critical(
  2562. "`root_dir` and `file_to_run` are incompatible. They "
  2563. "don't share the same subtrees. Make sure `file_to_run` "
  2564. "is on the same path as `root_dir`."
  2565. )
  2566. self.exit(1)
  2567. return ""
  2568. def _write_browser_open_file(self, url: str, fh: t.Any) -> None:
  2569. """Write the browser open file."""
  2570. if self.identity_provider.token:
  2571. url = url_concat(url, {"token": self.identity_provider.token})
  2572. url = url_path_join(self.connection_url, url)
  2573. jinja2_env = self.web_app.settings["jinja2_env"]
  2574. template = jinja2_env.get_template("browser-open.html")
  2575. fh.write(template.render(open_url=url, base_url=self.base_url))
  2576. def write_browser_open_files(self) -> None:
  2577. """Write an `browser_open_file` and `browser_open_file_to_run` files
  2578. This can be used to open a file directly in a browser.
  2579. """
  2580. # default_url contains base_url, but so does connection_url
  2581. self.write_browser_open_file()
  2582. # Create a second browser open file if
  2583. # file_to_run is set.
  2584. if self.file_to_run:
  2585. # Make sure file_to_run and root_dir are compatible.
  2586. file_to_run_relpath = self._resolve_file_to_run_and_root_dir()
  2587. file_open_url = url_escape(
  2588. url_path_join(self.file_url_prefix, *file_to_run_relpath.split(os.sep))
  2589. )
  2590. with open(self.browser_open_file_to_run, "w", encoding="utf-8") as f:
  2591. self._write_browser_open_file(file_open_url, f)
  2592. def write_browser_open_file(self) -> None:
  2593. """Write an jpserver-<pid>-open.html file
  2594. This can be used to open the notebook in a browser
  2595. """
  2596. # default_url contains base_url, but so does connection_url
  2597. open_url = self.default_url[len(self.base_url) :]
  2598. with open(self.browser_open_file, "w", encoding="utf-8") as f:
  2599. self._write_browser_open_file(open_url, f)
  2600. def remove_browser_open_files(self) -> None:
  2601. """Remove the `browser_open_file` and `browser_open_file_to_run` files
  2602. created for this server.
  2603. Ignores the error raised when the file has already been removed.
  2604. """
  2605. self.remove_browser_open_file()
  2606. try:
  2607. os.unlink(self.browser_open_file_to_run)
  2608. except OSError as e:
  2609. if e.errno != errno.ENOENT:
  2610. raise
  2611. def remove_browser_open_file(self) -> None:
  2612. """Remove the jpserver-<pid>-open.html file created for this server.
  2613. Ignores the error raised when the file has already been removed.
  2614. """
  2615. try:
  2616. os.unlink(self.browser_open_file)
  2617. except OSError as e:
  2618. if e.errno != errno.ENOENT:
  2619. raise
  2620. def _prepare_browser_open(self) -> tuple[str, t.Optional[str]]:
  2621. """Prepare to open the browser."""
  2622. if not self.use_redirect_file:
  2623. uri = self.default_url[len(self.base_url) :]
  2624. if self.identity_provider.token:
  2625. uri = url_concat(uri, {"token": self.identity_provider.token})
  2626. if self.file_to_run: # noqa: SIM108
  2627. # Create a separate, temporary open-browser-file
  2628. # pointing at a specific file.
  2629. open_file = self.browser_open_file_to_run
  2630. else:
  2631. # otherwise, just return the usual open browser file.
  2632. open_file = self.browser_open_file
  2633. if self.use_redirect_file:
  2634. assembled_url = urljoin("file:", pathname2url(open_file))
  2635. else:
  2636. assembled_url = url_path_join(self.connection_url, uri)
  2637. return assembled_url, open_file
  2638. def launch_browser(self) -> None:
  2639. """Launch the browser."""
  2640. # Deferred import for environments that do not have
  2641. # the webbrowser module.
  2642. import webbrowser
  2643. try:
  2644. browser = webbrowser.get(self.browser or None)
  2645. except webbrowser.Error as e:
  2646. self.log.warning(_i18n("No web browser found: %r.") % e)
  2647. browser = None
  2648. if not browser:
  2649. return
  2650. assembled_url, _ = self._prepare_browser_open()
  2651. def target():
  2652. assert browser is not None
  2653. browser.open(assembled_url, new=self.webbrowser_open_new)
  2654. threading.Thread(target=target).start()
  2655. def start_app(self) -> None:
  2656. """Start the Jupyter Server application."""
  2657. super().start()
  2658. if not self.allow_root:
  2659. # check if we are running as root, and abort if it's not allowed
  2660. try:
  2661. uid = os.geteuid()
  2662. except AttributeError:
  2663. uid = -1 # anything nonzero here, since we can't check UID assume non-root
  2664. if uid == 0:
  2665. self.log.critical(
  2666. _i18n("Running as root is not recommended. Use --allow-root to bypass.")
  2667. )
  2668. self.exit(1)
  2669. info = self.log.info
  2670. for line in self.running_server_info(kernel_count=False).split("\n"):
  2671. info(line)
  2672. info(
  2673. _i18n(
  2674. "Use Control-C to stop this server and shut down all kernels (twice to skip confirmation)."
  2675. )
  2676. )
  2677. if "dev" in __version__:
  2678. info(
  2679. _i18n(
  2680. "Welcome to Project Jupyter! Explore the various tools available"
  2681. " and their corresponding documentation. If you are interested"
  2682. " in contributing to the platform, please visit the community"
  2683. " resources section at https://jupyter.org/community.html."
  2684. )
  2685. )
  2686. self.write_server_info_file()
  2687. if not self.no_browser_open_file:
  2688. self.write_browser_open_files()
  2689. # Handle the browser opening.
  2690. if self.open_browser and not self.sock:
  2691. self.launch_browser()
  2692. if self.identity_provider.token and self.identity_provider.token_generated:
  2693. # log full URL with generated token, so there's a copy/pasteable link
  2694. # with auth info.
  2695. if self.sock:
  2696. self.log.critical(
  2697. "\n".join(
  2698. [
  2699. "\n",
  2700. "Jupyter Server is listening on %s" % self.display_url,
  2701. "",
  2702. (
  2703. "UNIX sockets are not browser-connectable, but you can tunnel to "
  2704. f"the instance via e.g.`ssh -L 8888:{self.sock} -N user@this_host` and then "
  2705. f"open e.g. {self.connection_url} in a browser."
  2706. ),
  2707. ]
  2708. )
  2709. )
  2710. else:
  2711. if self.no_browser_open_file:
  2712. message = [
  2713. "\n",
  2714. _i18n("To access the server, copy and paste one of these URLs:"),
  2715. " %s" % self.display_url,
  2716. ]
  2717. else:
  2718. message = [
  2719. "\n",
  2720. _i18n(
  2721. "To access the server, open this file in a browser:",
  2722. ),
  2723. " %s" % urljoin("file:", pathname2url(self.browser_open_file)),
  2724. _i18n(
  2725. "Or copy and paste one of these URLs:",
  2726. ),
  2727. " %s" % self.display_url,
  2728. ]
  2729. self.log.critical("\n".join(message))
  2730. async def _cleanup(self) -> None:
  2731. """General cleanup of files, extensions and kernels created
  2732. by this instance ServerApp.
  2733. """
  2734. self.remove_server_info_file()
  2735. self.remove_browser_open_files()
  2736. await self.cleanup_extensions()
  2737. await self.cleanup_kernels()
  2738. try:
  2739. await self.kernel_websocket_connection_class.close_all() # type:ignore[attr-defined]
  2740. except AttributeError:
  2741. # This can happen in two different scenarios:
  2742. #
  2743. # 1. During tests, where the _cleanup method is invoked without
  2744. # the corresponding initialize method having been invoked.
  2745. # 2. If the provided `kernel_websocket_connection_class` does not
  2746. # implement the `close_all` class method.
  2747. #
  2748. # In either case, we don't need to do anything and just want to treat
  2749. # the raised error as a no-op.
  2750. pass
  2751. if getattr(self, "kernel_manager", None):
  2752. self.kernel_manager.__del__()
  2753. if getattr(self, "session_manager", None):
  2754. self.session_manager.close()
  2755. if hasattr(self, "http_server"):
  2756. # Stop a server if its set.
  2757. self.http_server.stop()
  2758. def start_ioloop(self) -> None:
  2759. """Start the IO Loop."""
  2760. if sys.platform.startswith("win"):
  2761. # add no-op to wake every 5s
  2762. # to handle signals that may be ignored by the inner loop
  2763. pc = ioloop.PeriodicCallback(lambda: None, 5000)
  2764. pc.start()
  2765. try:
  2766. self.io_loop.add_callback(self._post_start)
  2767. self.io_loop.start()
  2768. except KeyboardInterrupt:
  2769. self.log.info(_i18n("Interrupted..."))
  2770. def init_ioloop(self) -> None:
  2771. """init self.io_loop so that an extension can use it by io_loop.call_later() to create background tasks"""
  2772. self.io_loop = ioloop.IOLoop.current()
  2773. async def _post_start(self):
  2774. """Add an async hook to start tasks after the event loop is running.
  2775. This will also attempt to start all tasks found in
  2776. the `start_extension` method in Extension Apps.
  2777. """
  2778. try:
  2779. await self.extension_manager.start_all_extensions()
  2780. except Exception as err:
  2781. self.log.error(err)
  2782. def start(self) -> None:
  2783. """Start the Jupyter server app, after initialization
  2784. This method takes no arguments so all configuration and initialization
  2785. must be done prior to calling this method."""
  2786. self.start_app()
  2787. self.start_ioloop()
  2788. async def _stop(self) -> None:
  2789. """Cleanup resources and stop the IO Loop."""
  2790. await self._cleanup()
  2791. if getattr(self, "io_loop", None):
  2792. self.io_loop.stop()
  2793. def stop(self, from_signal: bool = False) -> None:
  2794. """Cleanup resources and stop the server."""
  2795. # signal that stopping has begun
  2796. self._stopping = True
  2797. if hasattr(self, "http_server"):
  2798. # Stop a server if its set.
  2799. self.http_server.stop()
  2800. if getattr(self, "io_loop", None):
  2801. # use IOLoop.add_callback because signal.signal must be called
  2802. # from main thread
  2803. if from_signal:
  2804. self.io_loop.add_callback_from_signal(self._stop)
  2805. else:
  2806. self.io_loop.add_callback(self._stop)
  2807. def list_running_servers(
  2808. runtime_dir: t.Optional[str] = None, log: t.Optional[logging.Logger] = None
  2809. ) -> t.Generator[t.Any, None, None]:
  2810. """Iterate over the server info files of running Jupyter servers.
  2811. Given a runtime directory, find jpserver-* files in the security directory,
  2812. and yield dicts of their information, each one pertaining to
  2813. a currently running Jupyter server instance.
  2814. """
  2815. if runtime_dir is None:
  2816. runtime_dir = jupyter_runtime_dir()
  2817. # The runtime dir might not exist
  2818. if not os.path.isdir(runtime_dir):
  2819. return
  2820. for file_name in os.listdir(runtime_dir):
  2821. if re.match("jpserver-(.+).json", file_name):
  2822. with open(os.path.join(runtime_dir, file_name), encoding="utf-8") as f:
  2823. # Handle race condition where file is being written.
  2824. try:
  2825. info = json.load(f)
  2826. except json.JSONDecodeError:
  2827. continue
  2828. # Simple check whether that process is really still running
  2829. # Also remove leftover files from IPython 2.x without a pid field
  2830. if ("pid" in info) and check_pid(info["pid"]):
  2831. yield info
  2832. else:
  2833. # If the process has died, try to delete its info file
  2834. try:
  2835. os.unlink(os.path.join(runtime_dir, file_name))
  2836. except OSError as e:
  2837. if log:
  2838. log.warning(_i18n("Deleting server info file failed: %s.") % e)
  2839. # -----------------------------------------------------------------------------
  2840. # Main entry point
  2841. # -----------------------------------------------------------------------------
  2842. main = launch_new_instance = ServerApp.launch_instance