jupygate 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- jupygate/__init__.py +1 -0
- jupygate/_modidx.py +70 -0
- jupygate/core.py +519 -0
- jupygate-0.0.1.dist-info/METADATA +79 -0
- jupygate-0.0.1.dist-info/RECORD +9 -0
- jupygate-0.0.1.dist-info/WHEEL +5 -0
- jupygate-0.0.1.dist-info/entry_points.txt +5 -0
- jupygate-0.0.1.dist-info/licenses/LICENSE +201 -0
- jupygate-0.0.1.dist-info/top_level.txt +1 -0
jupygate/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.0.1"
|
jupygate/_modidx.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# Autogenerated by nbdev
|
|
2
|
+
|
|
3
|
+
d = { 'settings': { 'branch': 'main',
|
|
4
|
+
'doc_baseurl': '/jupygate',
|
|
5
|
+
'doc_host': 'https://AnswerDotAI.github.io',
|
|
6
|
+
'git_url': 'https://github.com/AnswerDotAI/jupygate',
|
|
7
|
+
'lib_path': 'jupygate'},
|
|
8
|
+
'syms': { 'jupygate.core': { 'jupygate.core.ClientQueue': ('core.html#clientqueue', 'jupygate/core.py'),
|
|
9
|
+
'jupygate.core.ClientQueue.__init__': ('core.html#clientqueue.__init__', 'jupygate/core.py'),
|
|
10
|
+
'jupygate.core.ClientQueue._writer': ('core.html#clientqueue._writer', 'jupygate/core.py'),
|
|
11
|
+
'jupygate.core.ClientQueue.attach': ('core.html#clientqueue.attach', 'jupygate/core.py'),
|
|
12
|
+
'jupygate.core.ClientQueue.close': ('core.html#clientqueue.close', 'jupygate/core.py'),
|
|
13
|
+
'jupygate.core.ClientQueue.detach': ('core.html#clientqueue.detach', 'jupygate/core.py'),
|
|
14
|
+
'jupygate.core.ClientQueue.detached': ('core.html#clientqueue.detached', 'jupygate/core.py'),
|
|
15
|
+
'jupygate.core.ClientQueue.force': ('core.html#clientqueue.force', 'jupygate/core.py'),
|
|
16
|
+
'jupygate.core.ClientQueue.put': ('core.html#clientqueue.put', 'jupygate/core.py'),
|
|
17
|
+
'jupygate.core.ClientQueue.put_frame': ('core.html#clientqueue.put_frame', 'jupygate/core.py'),
|
|
18
|
+
'jupygate.core.GatewayKernel': ('core.html#gatewaykernel', 'jupygate/core.py'),
|
|
19
|
+
'jupygate.core.GatewayKernel.__init__': ('core.html#gatewaykernel.__init__', 'jupygate/core.py'),
|
|
20
|
+
'jupygate.core.GatewayKernel._watch': ('core.html#gatewaykernel._watch', 'jupygate/core.py'),
|
|
21
|
+
'jupygate.core.GatewayKernel.interrupt': ('core.html#gatewaykernel.interrupt', 'jupygate/core.py'),
|
|
22
|
+
'jupygate.core.GatewayKernel.model': ('core.html#gatewaykernel.model', 'jupygate/core.py'),
|
|
23
|
+
'jupygate.core.GatewayKernel.restart': ('core.html#gatewaykernel.restart', 'jupygate/core.py'),
|
|
24
|
+
'jupygate.core.GatewayKernel.shutdown': ('core.html#gatewaykernel.shutdown', 'jupygate/core.py'),
|
|
25
|
+
'jupygate.core.GatewayKernel.start': ('core.html#gatewaykernel.start', 'jupygate/core.py'),
|
|
26
|
+
'jupygate.core.KernelChannels': ('core.html#kernelchannels', 'jupygate/core.py'),
|
|
27
|
+
'jupygate.core.KernelChannels.__init__': ('core.html#kernelchannels.__init__', 'jupygate/core.py'),
|
|
28
|
+
'jupygate.core.KernelChannels.close': ('core.html#kernelchannels.close', 'jupygate/core.py'),
|
|
29
|
+
'jupygate.core.KernelChannels.recv': ('core.html#kernelchannels.recv', 'jupygate/core.py'),
|
|
30
|
+
'jupygate.core.KernelChannels.send': ('core.html#kernelchannels.send', 'jupygate/core.py'),
|
|
31
|
+
'jupygate.core.KernelMux': ('core.html#kernelmux', 'jupygate/core.py'),
|
|
32
|
+
'jupygate.core.KernelMux.__init__': ('core.html#kernelmux.__init__', 'jupygate/core.py'),
|
|
33
|
+
'jupygate.core.KernelMux._pump': ('core.html#kernelmux._pump', 'jupygate/core.py'),
|
|
34
|
+
'jupygate.core.KernelMux._reaper': ('core.html#kernelmux._reaper', 'jupygate/core.py'),
|
|
35
|
+
'jupygate.core.KernelMux.add': ('core.html#kernelmux.add', 'jupygate/core.py'),
|
|
36
|
+
'jupygate.core.KernelMux.close': ('core.html#kernelmux.close', 'jupygate/core.py'),
|
|
37
|
+
'jupygate.core.KernelMux.drop': ('core.html#kernelmux.drop', 'jupygate/core.py'),
|
|
38
|
+
'jupygate.core.KernelMux.handle_frame': ('core.html#kernelmux.handle_frame', 'jupygate/core.py'),
|
|
39
|
+
'jupygate.core.KernelMux.n_attached': ('core.html#kernelmux.n_attached', 'jupygate/core.py'),
|
|
40
|
+
'jupygate.core.KernelMux.synthesize_status': ('core.html#kernelmux.synthesize_status', 'jupygate/core.py'),
|
|
41
|
+
'jupygate.core.KernelProc': ('core.html#kernelproc', 'jupygate/core.py'),
|
|
42
|
+
'jupygate.core.KernelProc.__init__': ('core.html#kernelproc.__init__', 'jupygate/core.py'),
|
|
43
|
+
'jupygate.core.KernelProc.alive': ('core.html#kernelproc.alive', 'jupygate/core.py'),
|
|
44
|
+
'jupygate.core.KernelProc.interrupt': ('core.html#kernelproc.interrupt', 'jupygate/core.py'),
|
|
45
|
+
'jupygate.core.KernelProc.pid': ('core.html#kernelproc.pid', 'jupygate/core.py'),
|
|
46
|
+
'jupygate.core.KernelProc.terminate': ('core.html#kernelproc.terminate', 'jupygate/core.py'),
|
|
47
|
+
'jupygate.core.Kernels': ('core.html#kernels', 'jupygate/core.py'),
|
|
48
|
+
'jupygate.core.Kernels.__getitem__': ('core.html#kernels.__getitem__', 'jupygate/core.py'),
|
|
49
|
+
'jupygate.core.Kernels.__init__': ('core.html#kernels.__init__', 'jupygate/core.py'),
|
|
50
|
+
'jupygate.core.Kernels.__len__': ('core.html#kernels.__len__', 'jupygate/core.py'),
|
|
51
|
+
'jupygate.core.Kernels.create': ('core.html#kernels.create', 'jupygate/core.py'),
|
|
52
|
+
'jupygate.core.Kernels.delete': ('core.html#kernels.delete', 'jupygate/core.py'),
|
|
53
|
+
'jupygate.core.Kernels.get': ('core.html#kernels.get', 'jupygate/core.py'),
|
|
54
|
+
'jupygate.core.Kernels.shutdown': ('core.html#kernels.shutdown', 'jupygate/core.py'),
|
|
55
|
+
'jupygate.core.Kernels.values': ('core.html#kernels.values', 'jupygate/core.py'),
|
|
56
|
+
'jupygate.core._authed': ('core.html#_authed', 'jupygate/core.py'),
|
|
57
|
+
'jupygate.core._env_app': ('core.html#_env_app', 'jupygate/core.py'),
|
|
58
|
+
'jupygate.core._reload_file': ('core.html#_reload_file', 'jupygate/core.py'),
|
|
59
|
+
'jupygate.core._sudo': ('core.html#_sudo', 'jupygate/core.py'),
|
|
60
|
+
'jupygate.core.create_app': ('core.html#create_app', 'jupygate/core.py'),
|
|
61
|
+
'jupygate.core.dumps': ('core.html#dumps', 'jupygate/core.py'),
|
|
62
|
+
'jupygate.core.dumps_binary': ('core.html#dumps_binary', 'jupygate/core.py'),
|
|
63
|
+
'jupygate.core.from_frame': ('core.html#from_frame', 'jupygate/core.py'),
|
|
64
|
+
'jupygate.core.loads': ('core.html#loads', 'jupygate/core.py'),
|
|
65
|
+
'jupygate.core.loads_binary': ('core.html#loads_binary', 'jupygate/core.py'),
|
|
66
|
+
'jupygate.core.main': ('core.html#main', 'jupygate/core.py'),
|
|
67
|
+
'jupygate.core.make_connection': ('core.html#make_connection', 'jupygate/core.py'),
|
|
68
|
+
'jupygate.core.serve': ('core.html#serve', 'jupygate/core.py'),
|
|
69
|
+
'jupygate.core.to_frame': ('core.html#to_frame', 'jupygate/core.py'),
|
|
70
|
+
'jupygate.core.wait_ready': ('core.html#wait_ready', 'jupygate/core.py')}}}
|
jupygate/core.py
ADDED
|
@@ -0,0 +1,519 @@
|
|
|
1
|
+
"""Kernel processes, channels, routing, and the gateway server
|
|
2
|
+
|
|
3
|
+
Docs: https://AnswerDotAI.github.io/jupygate/core.html.md"""
|
|
4
|
+
|
|
5
|
+
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_core.ipynb.
|
|
6
|
+
|
|
7
|
+
# %% auto #0
|
|
8
|
+
__all__ = ['log', 'IPYMINI_ARGV', 'CHANNELS', 'dumps', 'loads', 'dumps_binary', 'loads_binary', 'to_frame', 'from_frame',
|
|
9
|
+
'make_connection', 'KernelProc', 'KernelChannels', 'wait_ready', 'ClientQueue', 'KernelMux', 'GatewayKernel',
|
|
10
|
+
'Kernels', 'create_app', 'serve', 'main']
|
|
11
|
+
|
|
12
|
+
# %% ../nbs/00_core.ipynb #98c8671f
|
|
13
|
+
import asyncio, json, logging, os, signal, subprocess, sys, time, uuid
|
|
14
|
+
from collections import deque
|
|
15
|
+
from contextlib import asynccontextmanager
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from tempfile import mkdtemp
|
|
18
|
+
import zmq, zmq.asyncio
|
|
19
|
+
from jupywire.connect import write_connection_file
|
|
20
|
+
from fastcore.basics import xdumps, revive_dates
|
|
21
|
+
from jupywire.session import Session, pack_frames, unpack_frames
|
|
22
|
+
from starlette.applications import Starlette
|
|
23
|
+
from starlette.responses import JSONResponse, Response
|
|
24
|
+
from starlette.routing import Route, WebSocketRoute
|
|
25
|
+
from starlette.websockets import WebSocketDisconnect
|
|
26
|
+
|
|
27
|
+
# %% ../nbs/00_core.ipynb #82539e9e
|
|
28
|
+
log = logging.getLogger('jupygate')
|
|
29
|
+
|
|
30
|
+
# %% ../nbs/00_core.ipynb #99c479c2
|
|
31
|
+
def dumps(msg:dict)->str:
|
|
32
|
+
"Encode a Jupyter message dict (no buffers) as a websocket text frame."
|
|
33
|
+
return xdumps(msg)
|
|
34
|
+
|
|
35
|
+
def loads(s:str|bytes)->dict:
|
|
36
|
+
"Decode a websocket text frame back into a message dict, reviving header dates."
|
|
37
|
+
msg = json.loads(s)
|
|
38
|
+
for k in ('header','parent_header'):
|
|
39
|
+
if isinstance(msg.get(k), dict): msg[k] = revive_dates(msg[k])
|
|
40
|
+
return msg
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# %% ../nbs/00_core.ipynb #dd69572d
|
|
44
|
+
def dumps_binary(msg:dict)->bytes:
|
|
45
|
+
"Encode a message with `buffers` as a legacy-protocol binary frame."
|
|
46
|
+
msg = dict(msg)
|
|
47
|
+
buffers = msg.pop('buffers')
|
|
48
|
+
return pack_frames(dumps(msg).encode('utf-8'), buffers)
|
|
49
|
+
|
|
50
|
+
def loads_binary(bmsg:bytes)->dict:
|
|
51
|
+
"Decode a legacy-protocol binary frame back into a message dict with `buffers`."
|
|
52
|
+
body, buffers = unpack_frames(bmsg)
|
|
53
|
+
msg = loads(body)
|
|
54
|
+
msg['buffers'] = buffers
|
|
55
|
+
return msg
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# %% ../nbs/00_core.ipynb #c2512b33
|
|
59
|
+
def to_frame(msg:dict)->str|bytes:
|
|
60
|
+
"Encode `msg` for the websocket: JSON text frame, or binary frame if it carries buffers."
|
|
61
|
+
return dumps_binary(msg) if msg.get('buffers') else dumps({k:v for k,v in msg.items() if k!='buffers'})
|
|
62
|
+
|
|
63
|
+
def from_frame(data:str|bytes)->dict:
|
|
64
|
+
"Decode a websocket frame (text or binary) into a message dict; `buffers` is always present."
|
|
65
|
+
msg = loads_binary(data) if isinstance(data, (bytes,bytearray)) else loads(data)
|
|
66
|
+
msg.setdefault('buffers', [])
|
|
67
|
+
return msg
|
|
68
|
+
|
|
69
|
+
# %% ../nbs/00_core.ipynb #b9033343
|
|
70
|
+
def make_connection(dir:str|None=None)->tuple[str,dict]:
|
|
71
|
+
"Write a connection file with random free ports and a fresh key; returns `(path, info)`."
|
|
72
|
+
dir = dir or mkdtemp(prefix='jupygate-')
|
|
73
|
+
fname = str(Path(dir)/f"kernel-{uuid.uuid4().hex[:8]}.json")
|
|
74
|
+
return write_connection_file(fname, ip='127.0.0.1', key=uuid.uuid4().hex.encode())
|
|
75
|
+
|
|
76
|
+
# %% ../nbs/00_core.ipynb #79fa398b
|
|
77
|
+
def _sudo(username):
|
|
78
|
+
helper = os.environ.get('JUPYGATE_SUDO')
|
|
79
|
+
return [helper, username] if helper else ['/usr/bin/sudo','-n','-E','-u',username]
|
|
80
|
+
|
|
81
|
+
class KernelProc:
|
|
82
|
+
"One kernel process: spawn from an argv template, watch, terminate."
|
|
83
|
+
def __init__(self, argv:list[str], env:dict|None=None, appendenv:dict|None=None, cwd:str|None=None, username:str|None=None):
|
|
84
|
+
self.cfile, self.info = make_connection()
|
|
85
|
+
cmd = [a.format(connection_file=self.cfile) for a in argv]
|
|
86
|
+
if username:
|
|
87
|
+
os.chmod(self.cfile, 0o644)
|
|
88
|
+
cmd = [*_sudo(username), *cmd]
|
|
89
|
+
full_env = dict(os.environ if env is None else env) | (appendenv or {}) # `env` replaces the inherited environment; `appendenv` overlays the base
|
|
90
|
+
full_env['JPY_PARENT_PID'] = str(os.getpid())
|
|
91
|
+
self.proc = subprocess.Popen(cmd, env=full_env, cwd=cwd, start_new_session=True)
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def pid(self): return self.proc.pid
|
|
95
|
+
def alive(self)->bool: return self.proc.poll() is None
|
|
96
|
+
def interrupt(self): os.kill(self.pid, signal.SIGINT)
|
|
97
|
+
|
|
98
|
+
def terminate(self, timeout:float=5.0):
|
|
99
|
+
"SIGTERM then SIGKILL; reaps the process and removes the connection file."
|
|
100
|
+
if self.alive():
|
|
101
|
+
self.proc.terminate()
|
|
102
|
+
try: self.proc.wait(timeout)
|
|
103
|
+
except subprocess.TimeoutExpired:
|
|
104
|
+
self.proc.kill()
|
|
105
|
+
self.proc.wait(timeout)
|
|
106
|
+
Path(self.cfile).unlink(missing_ok=True)
|
|
107
|
+
|
|
108
|
+
# %% ../nbs/00_core.ipynb #924c967d
|
|
109
|
+
IPYMINI_ARGV = [sys.executable, '-m', 'ipymini', '-f', '{connection_file}']
|
|
110
|
+
|
|
111
|
+
# %% ../nbs/00_core.ipynb #c2ac6fa1
|
|
112
|
+
CHANNELS = ('shell','control','stdin','iopub')
|
|
113
|
+
|
|
114
|
+
class KernelChannels:
|
|
115
|
+
"One persistent set of zmq.asyncio sockets connected to a kernel."
|
|
116
|
+
def __init__(self, info:dict):
|
|
117
|
+
self.session = Session(key=info['key'].encode() if isinstance(info['key'],str) else info['key'])
|
|
118
|
+
self.ctx = zmq.asyncio.Context()
|
|
119
|
+
addr = lambda port: f"{info['transport']}://{info['ip']}:{port}"
|
|
120
|
+
self.socks = {}
|
|
121
|
+
for name in CHANNELS:
|
|
122
|
+
kind = zmq.SUB if name=='iopub' else zmq.DEALER
|
|
123
|
+
s = self.ctx.socket(kind)
|
|
124
|
+
s.linger = 0
|
|
125
|
+
if kind==zmq.DEALER: s.setsockopt(zmq.IDENTITY, self.session.bsession)
|
|
126
|
+
else:
|
|
127
|
+
s.subscribe(b'')
|
|
128
|
+
s.rcvhwm = 0 # before connect. Lossless hop: libzmq's HWM drops silently (statuses included); shedding belongs to ClientQueue alone
|
|
129
|
+
s.connect(addr(info[f'{name}_port']))
|
|
130
|
+
self.socks[name] = s
|
|
131
|
+
|
|
132
|
+
async def send(self, channel:str, msg:dict):
|
|
133
|
+
"Sign, serialize, and send a message dict on `channel`, awaiting the socket send so errors and backpressure surface here."
|
|
134
|
+
m = dict(header=msg['header'], parent_header=msg.get('parent_header') or {}, metadata=msg.get('metadata') or {}, content=msg.get('content') or {})
|
|
135
|
+
await self.socks[channel].send_multipart(self.session.serialize(m) + [memoryview(b) for b in msg.get('buffers') or []])
|
|
136
|
+
|
|
137
|
+
async def recv(self, channel:str)->dict:
|
|
138
|
+
"Receive and verify one message from `channel` (iopub topic frames are handled)."
|
|
139
|
+
parts = await self.socks[channel].recv_multipart()
|
|
140
|
+
idents, msg_list = self.session.feed_identities(parts)
|
|
141
|
+
return self.session.deserialize(msg_list)
|
|
142
|
+
|
|
143
|
+
def close(self):
|
|
144
|
+
for s in self.socks.values(): s.close()
|
|
145
|
+
self.ctx.term()
|
|
146
|
+
|
|
147
|
+
# %% ../nbs/00_core.ipynb #34e7a2c1
|
|
148
|
+
async def wait_ready(ch:KernelChannels, timeout:float=30.0, probe_every:float=0.5)->dict:
|
|
149
|
+
"Block until the kernel answers `kernel_info` and iopub is proven live; returns the kernel_info reply content, leaving both channels clean."
|
|
150
|
+
loop = asyncio.get_running_loop()
|
|
151
|
+
end = loop.time() + timeout
|
|
152
|
+
def left(cap=1.0):
|
|
153
|
+
t = end - loop.time()
|
|
154
|
+
if t <= 0: raise TimeoutError(f"kernel not ready after {timeout}s")
|
|
155
|
+
return min(t, cap)
|
|
156
|
+
async def recv_or_none(channel, cap=1.0):
|
|
157
|
+
if await ch.socks[channel].poll(int(left(cap)*1000)): return await ch.recv(channel)
|
|
158
|
+
return None
|
|
159
|
+
probes = set()
|
|
160
|
+
async def probe():
|
|
161
|
+
m = ch.session.msg('kernel_info_request')
|
|
162
|
+
probes.add(m['header']['msg_id'])
|
|
163
|
+
await ch.send('shell', m)
|
|
164
|
+
return m['header']['msg_id']
|
|
165
|
+
msg = None
|
|
166
|
+
while msg is None:
|
|
167
|
+
await probe()
|
|
168
|
+
msg = await recv_or_none('iopub', probe_every)
|
|
169
|
+
if msg['header']['msg_type'] == 'iopub_welcome':
|
|
170
|
+
mid = await probe() # end marker: replies are FIFO, so once its reply and idle arrive, every earlier probe's traffic is consumed
|
|
171
|
+
while (reply := await recv_or_none('shell')) is None or reply['parent_header'].get('msg_id') != mid: pass
|
|
172
|
+
while not (msg['header']['msg_type']=='status' and msg['parent_header'].get('msg_id')==mid and msg['content']['execution_state']=='idle'):
|
|
173
|
+
while (msg := await recv_or_none('iopub')) is None: pass
|
|
174
|
+
else:
|
|
175
|
+
while (reply := await recv_or_none('shell')) is None or reply['header']['msg_type'] != 'kernel_info_reply': pass
|
|
176
|
+
outstanding = len(probes) - 1 # every probe gets a reply; one was consumed above
|
|
177
|
+
while outstanding and await ch.socks['shell'].poll(1000):
|
|
178
|
+
m = await ch.recv('shell')
|
|
179
|
+
if m['parent_header'].get('msg_id') in probes: outstanding -= 1
|
|
180
|
+
while await ch.socks['iopub'].poll(200): await ch.recv('iopub') # then drain iopub until 0.2s of silence
|
|
181
|
+
return reply['content']
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
# %% ../nbs/00_core.ipynb #41d52e28
|
|
185
|
+
class ClientQueue:
|
|
186
|
+
"Outbound queue of encoded frames for one client. The bound governs iopub only, and never drops `status` while attached."
|
|
187
|
+
def __init__(self, session_id:str, send, qmax:int=1000, buffer:bool=True):
|
|
188
|
+
self.session_id, self.qmax, self.buffer = session_id, qmax, buffer
|
|
189
|
+
self.q, self.dropped, self._drop_mark, self._wake = deque(), 0, 0, asyncio.Event()
|
|
190
|
+
self.task = self.detached_at = None
|
|
191
|
+
self.attach(send)
|
|
192
|
+
|
|
193
|
+
@property
|
|
194
|
+
def detached(self): return self.detached_at is not None
|
|
195
|
+
|
|
196
|
+
def attach(self, send):
|
|
197
|
+
"(Re)bind the queue to a live websocket: install `send` and start a fresh writer."
|
|
198
|
+
if self.task: self.task.cancel()
|
|
199
|
+
self._send, self.detached_at = send, None
|
|
200
|
+
self.task = asyncio.create_task(self._writer())
|
|
201
|
+
|
|
202
|
+
def detach(self):
|
|
203
|
+
"Park the queue as a ring: stop the writer, remember when and how much was already dropped."
|
|
204
|
+
if self.task: self.task.cancel()
|
|
205
|
+
self.task, self.detached_at, self._drop_mark = None, time.monotonic(), self.dropped
|
|
206
|
+
|
|
207
|
+
def put(self, msg:dict): self.put_frame(msg['header']['msg_type'], to_frame(msg), iopub=msg.get('channel')=='iopub')
|
|
208
|
+
|
|
209
|
+
def put_frame(self, msg_type:str, frame:str|bytes, iopub:bool=True):
|
|
210
|
+
if len(self.q) >= self.qmax and (self.detached or (iopub and msg_type!='status')):
|
|
211
|
+
self.dropped += 1
|
|
212
|
+
if self.dropped==1 or self.dropped%1000==0: log.warning("client %s queue full; dropped=%d", self.session_id, self.dropped)
|
|
213
|
+
if not self.detached: return # attached: the newcomer is dropped
|
|
214
|
+
self.q.popleft() # detached ring: the oldest is evicted, the newcomer kept
|
|
215
|
+
self.q.append((msg_type, frame))
|
|
216
|
+
self._wake.set()
|
|
217
|
+
|
|
218
|
+
def force(self, msg:dict):
|
|
219
|
+
"Queue `msg` past the bound (reattach synthesis: exactly two messages, never more)."
|
|
220
|
+
self.q.append((msg['header']['msg_type'], to_frame(msg)))
|
|
221
|
+
self._wake.set()
|
|
222
|
+
|
|
223
|
+
async def _writer(self):
|
|
224
|
+
while True:
|
|
225
|
+
if not self.q:
|
|
226
|
+
self._wake.clear()
|
|
227
|
+
await self._wake.wait()
|
|
228
|
+
try: await self._send(self.q[0][1])
|
|
229
|
+
except Exception: return # connection gone; the frame stays queued for a reattach
|
|
230
|
+
self.q.popleft()
|
|
231
|
+
await asyncio.sleep(0) # a buffered transport can complete sends without suspending; yield so cancel and disconnect can land
|
|
232
|
+
|
|
233
|
+
def close(self):
|
|
234
|
+
if self.task: self.task.cancel()
|
|
235
|
+
|
|
236
|
+
# %% ../nbs/00_core.ipynb #01adae60
|
|
237
|
+
class KernelMux:
|
|
238
|
+
"Fan kernel traffic out to clients; route client frames back to kernel channels."
|
|
239
|
+
def __init__(self, ch:KernelChannels, qmax:int=1000, buffer_secs:float=3600.0):
|
|
240
|
+
self.ch, self.qmax, self.buffer_secs = ch, qmax, buffer_secs
|
|
241
|
+
self.clients, self.pending_stdin, self.exec_state = {}, {}, 'starting'
|
|
242
|
+
self.tasks = [asyncio.create_task(self._pump(c)) for c in CHANNELS]
|
|
243
|
+
if buffer_secs: self.tasks.append(asyncio.create_task(self._reaper()))
|
|
244
|
+
|
|
245
|
+
@property
|
|
246
|
+
def n_attached(self): return sum(1 for cq in self.clients.values() if not cq.detached)
|
|
247
|
+
|
|
248
|
+
def add(self, session_id:str, send, buffer:bool=True)->ClientQueue:
|
|
249
|
+
"Register a client, or reattach a returning session to its surviving queue."
|
|
250
|
+
cq = self.clients.get(session_id)
|
|
251
|
+
if cq is None:
|
|
252
|
+
self.clients[session_id] = cq = ClientQueue(session_id, send, self.qmax, buffer=buffer)
|
|
253
|
+
return cq
|
|
254
|
+
missed = cq.dropped - cq._drop_mark if cq.detached else 0
|
|
255
|
+
cq.attach(send)
|
|
256
|
+
if missed:
|
|
257
|
+
warn = self.ch.session.msg('stream', dict(name='stderr', text=f'[jupygate] {missed} messages dropped while disconnected\n'))
|
|
258
|
+
for m in (warn, self.ch.session.msg('status', dict(execution_state=self.exec_state))):
|
|
259
|
+
m['channel'] = 'iopub'
|
|
260
|
+
cq.force(m)
|
|
261
|
+
return cq
|
|
262
|
+
|
|
263
|
+
def drop(self, session_id:str):
|
|
264
|
+
"A websocket went away: park the queue if the session is bufferable, else discard it."
|
|
265
|
+
cq = self.clients.get(session_id)
|
|
266
|
+
if cq is None: return
|
|
267
|
+
if self.buffer_secs and cq.buffer: cq.detach()
|
|
268
|
+
else:
|
|
269
|
+
self.clients.pop(session_id)
|
|
270
|
+
cq.close()
|
|
271
|
+
|
|
272
|
+
async def _reaper(self):
|
|
273
|
+
while True:
|
|
274
|
+
await asyncio.sleep(min(self.buffer_secs, 60))
|
|
275
|
+
cutoff = time.monotonic() - self.buffer_secs
|
|
276
|
+
for sid, cq in list(self.clients.items()):
|
|
277
|
+
if cq.detached and cq.detached_at < cutoff:
|
|
278
|
+
self.clients.pop(sid)
|
|
279
|
+
cq.close()
|
|
280
|
+
|
|
281
|
+
async def _pump(self, channel:str):
|
|
282
|
+
while True:
|
|
283
|
+
msg = await self.ch.recv(channel)
|
|
284
|
+
await asyncio.sleep(0) # zmq recv on a buffered socket completes without suspending; yield so writers and handlers run mid-flood
|
|
285
|
+
msg['channel'] = channel
|
|
286
|
+
if channel=='iopub':
|
|
287
|
+
if msg['header']['msg_type']=='status': self.exec_state = msg['content']['execution_state']
|
|
288
|
+
mt, frame = msg['header']['msg_type'], to_frame(msg)
|
|
289
|
+
for cq in self.clients.values(): cq.put_frame(mt, frame)
|
|
290
|
+
continue
|
|
291
|
+
sid = msg['parent_header'].get('session')
|
|
292
|
+
if channel=='stdin' and msg['header']['msg_type']=='input_request': self.pending_stdin[sid] = msg['header']
|
|
293
|
+
if (cq := self.clients.get(sid)): cq.put(msg)
|
|
294
|
+
|
|
295
|
+
async def handle_frame(self, session_id:str, data:str|bytes):
|
|
296
|
+
"One frame from a client websocket: decode, repair stdin parents, send to the kernel."
|
|
297
|
+
msg = from_frame(data)
|
|
298
|
+
channel = msg.pop('channel', 'shell')
|
|
299
|
+
if channel=='stdin' and not msg.get('parent_header') and (hdr := self.pending_stdin.pop(session_id, None)):
|
|
300
|
+
msg['parent_header'] = hdr
|
|
301
|
+
await self.ch.send(channel, msg)
|
|
302
|
+
|
|
303
|
+
def synthesize_status(self, state:str):
|
|
304
|
+
"Broadcast a gateway-made status (`restarting`/`dead`): kernels cannot announce their own death."
|
|
305
|
+
self.exec_state = state
|
|
306
|
+
msg = self.ch.session.msg('status', dict(execution_state=state))
|
|
307
|
+
msg['channel'] = 'iopub'
|
|
308
|
+
mt, frame = 'status', to_frame(msg)
|
|
309
|
+
for cq in self.clients.values(): cq.put_frame(mt, frame)
|
|
310
|
+
|
|
311
|
+
def close(self):
|
|
312
|
+
for t in self.tasks: t.cancel()
|
|
313
|
+
for cq in self.clients.values(): cq.close()
|
|
314
|
+
self.clients.clear()
|
|
315
|
+
|
|
316
|
+
# %% ../nbs/00_core.ipynb #16b3d9b0
|
|
317
|
+
class GatewayKernel:
|
|
318
|
+
"A kernel process plus its channel set and mux, as one lifecycle."
|
|
319
|
+
def __init__(self, argv:list[str], env:dict|None=None, appendenv:dict|None=None, cwd:str|None=None,
|
|
320
|
+
username:str|None=None, qmax:int=1000, buffer_secs:float=3600.0):
|
|
321
|
+
self.spec = dict(argv=argv, env=env, appendenv=appendenv, cwd=cwd, username=username)
|
|
322
|
+
self.qmax, self.buffer_secs = qmax, buffer_secs
|
|
323
|
+
self.id = uuid.uuid4().hex
|
|
324
|
+
self.proc = self.ch = self.mux = self._watcher = None
|
|
325
|
+
self.state = 'starting'
|
|
326
|
+
|
|
327
|
+
async def start(self, timeout:float=60.0):
|
|
328
|
+
self.proc = KernelProc(**self.spec)
|
|
329
|
+
self.ch = KernelChannels(self.proc.info)
|
|
330
|
+
await wait_ready(self.ch, timeout)
|
|
331
|
+
self.mux = KernelMux(self.ch, qmax=self.qmax, buffer_secs=self.buffer_secs)
|
|
332
|
+
self.state = 'alive'
|
|
333
|
+
self._watcher = asyncio.create_task(self._watch())
|
|
334
|
+
return self
|
|
335
|
+
|
|
336
|
+
async def _watch(self):
|
|
337
|
+
while self.proc.alive(): await asyncio.sleep(0.5)
|
|
338
|
+
if self.state=='alive':
|
|
339
|
+
self.state = 'dead'
|
|
340
|
+
self.mux.synthesize_status('dead')
|
|
341
|
+
|
|
342
|
+
def model(self)->dict: return dict(id=self.id, name='', execution_state=self.state, connections=self.mux.n_attached if self.mux else 0)
|
|
343
|
+
def interrupt(self): self.proc.interrupt()
|
|
344
|
+
|
|
345
|
+
async def restart(self, timeout:float=60.0):
|
|
346
|
+
self.state = 'restarting'
|
|
347
|
+
self.mux.synthesize_status('restarting')
|
|
348
|
+
old_mux = self.mux
|
|
349
|
+
clients, old_mux.clients = old_mux.clients, {}
|
|
350
|
+
await self.shutdown(keep_state=True)
|
|
351
|
+
old_mux.close()
|
|
352
|
+
await self.start(timeout)
|
|
353
|
+
self.mux.clients = clients
|
|
354
|
+
self.mux.synthesize_status('starting')
|
|
355
|
+
|
|
356
|
+
async def shutdown(self, keep_state:bool=False):
|
|
357
|
+
if self._watcher: self._watcher.cancel()
|
|
358
|
+
if not keep_state:
|
|
359
|
+
self.state = 'dead'
|
|
360
|
+
if self.mux: self.mux.close()
|
|
361
|
+
if self.ch: self.ch.close()
|
|
362
|
+
if self.proc: await asyncio.to_thread(self.proc.terminate)
|
|
363
|
+
|
|
364
|
+
# %% ../nbs/00_core.ipynb #94e4031d
|
|
365
|
+
class Kernels:
|
|
366
|
+
"Kernel registry: create, look up, and reap `GatewayKernel`s. The HTTP app and embedders both drive this."
|
|
367
|
+
def __init__(self, argv:list[str]=IPYMINI_ARGV, qmax:int=1000, buffer_secs:float=3600.0):
|
|
368
|
+
self.argv, self.qmax, self.buffer_secs = argv, qmax, buffer_secs
|
|
369
|
+
self.kernels = {}
|
|
370
|
+
|
|
371
|
+
async def create(self, argv:list[str]|None=None, env:dict|None=None, appendenv:dict|None=None,
|
|
372
|
+
cwd:str|None=None, username:str|None=None, timeout:float=60.0)->GatewayKernel:
|
|
373
|
+
gk = GatewayKernel(argv=argv or self.argv, env=env, appendenv=appendenv, cwd=cwd, username=username, qmax=self.qmax, buffer_secs=self.buffer_secs)
|
|
374
|
+
self.kernels[gk.id] = gk
|
|
375
|
+
try: await gk.start(timeout)
|
|
376
|
+
except Exception:
|
|
377
|
+
self.kernels.pop(gk.id, None)
|
|
378
|
+
await gk.shutdown()
|
|
379
|
+
raise
|
|
380
|
+
return gk
|
|
381
|
+
|
|
382
|
+
async def delete(self, kid:str):
|
|
383
|
+
gk = self.kernels.pop(kid)
|
|
384
|
+
await gk.shutdown()
|
|
385
|
+
|
|
386
|
+
async def shutdown(self):
|
|
387
|
+
"Reap every kernel; nothing survives the registry."
|
|
388
|
+
await asyncio.gather(*[k.shutdown() for k in self.kernels.values()], return_exceptions=True)
|
|
389
|
+
self.kernels.clear()
|
|
390
|
+
|
|
391
|
+
def get(self, kid:str)->GatewayKernel|None: return self.kernels.get(kid)
|
|
392
|
+
def values(self): return self.kernels.values()
|
|
393
|
+
def __getitem__(self, kid:str)->GatewayKernel: return self.kernels[kid]
|
|
394
|
+
def __len__(self): return len(self.kernels)
|
|
395
|
+
|
|
396
|
+
# %% ../nbs/00_core.ipynb #32c30a8f
|
|
397
|
+
def _authed(request, token):
|
|
398
|
+
if not token: return True
|
|
399
|
+
hdr = request.headers.get('authorization', '')
|
|
400
|
+
return hdr == f'token {token}' or request.query_params.get('token') == token
|
|
401
|
+
|
|
402
|
+
def create_app(argv:list[str]=IPYMINI_ARGV, auth_token:str|None=None, qmax:int=1000, buffer_secs:float=3600.0)->Starlette:
|
|
403
|
+
"The gateway app. `argv` is the default kernel command; creation requests may override it."
|
|
404
|
+
kernels = Kernels(argv, qmax=qmax, buffer_secs=buffer_secs)
|
|
405
|
+
|
|
406
|
+
def _kernel(request):
|
|
407
|
+
k = kernels.get(request.path_params['kid'])
|
|
408
|
+
if k is None: raise KeyError
|
|
409
|
+
return k
|
|
410
|
+
|
|
411
|
+
async def list_kernels(request): return JSONResponse([k.model() for k in kernels.values()])
|
|
412
|
+
|
|
413
|
+
async def create_kernel(request):
|
|
414
|
+
body = await request.json() if await request.body() else {}
|
|
415
|
+
try: gk = await kernels.create(argv=body.get('argv'), env=body.get('env'), appendenv=body.get('appendenv'), cwd=body.get('cwd'), username=body.get('username'))
|
|
416
|
+
except Exception as e: return JSONResponse(dict(message=f'kernel failed to start: {e}'), status_code=500)
|
|
417
|
+
return JSONResponse(gk.model(), status_code=201)
|
|
418
|
+
|
|
419
|
+
async def get_kernel(request): return JSONResponse(_kernel(request).model())
|
|
420
|
+
|
|
421
|
+
async def delete_kernel(request):
|
|
422
|
+
await kernels.delete(request.path_params['kid'])
|
|
423
|
+
return Response(status_code=204)
|
|
424
|
+
|
|
425
|
+
async def interrupt(request):
|
|
426
|
+
_kernel(request).interrupt()
|
|
427
|
+
return Response(status_code=204)
|
|
428
|
+
|
|
429
|
+
async def restart(request):
|
|
430
|
+
gk = _kernel(request)
|
|
431
|
+
await gk.restart()
|
|
432
|
+
return JSONResponse(gk.model())
|
|
433
|
+
|
|
434
|
+
async def channels(ws):
|
|
435
|
+
if not _authed(ws, auth_token): return await ws.close(code=4403)
|
|
436
|
+
gk = kernels.get(ws.path_params['kid'])
|
|
437
|
+
if gk is None or gk.mux is None: return await ws.close(code=4404)
|
|
438
|
+
sid = ws.query_params.get('session_id')
|
|
439
|
+
sid, buffer = sid or uuid.uuid4().hex, sid is not None
|
|
440
|
+
await ws.accept()
|
|
441
|
+
async def send(frame):
|
|
442
|
+
if isinstance(frame, bytes): await ws.send_bytes(frame)
|
|
443
|
+
else: await ws.send_text(frame)
|
|
444
|
+
gk.mux.add(sid, send, buffer=buffer)
|
|
445
|
+
try:
|
|
446
|
+
while True:
|
|
447
|
+
event = await ws.receive()
|
|
448
|
+
if event['type']=='websocket.disconnect': break
|
|
449
|
+
try: await gk.mux.handle_frame(sid, event.get('bytes') or event['text'])
|
|
450
|
+
except Exception as e: log.warning('dropped frame from %s: %s', sid, e)
|
|
451
|
+
except WebSocketDisconnect: pass
|
|
452
|
+
finally: gk.mux.drop(sid)
|
|
453
|
+
|
|
454
|
+
def guard(fn):
|
|
455
|
+
async def inner(request):
|
|
456
|
+
if not _authed(request, auth_token): return JSONResponse(dict(message='forbidden'), status_code=403)
|
|
457
|
+
try: return await fn(request)
|
|
458
|
+
except KeyError: return JSONResponse(dict(message='no such kernel'), status_code=404)
|
|
459
|
+
return inner
|
|
460
|
+
|
|
461
|
+
@asynccontextmanager
|
|
462
|
+
async def lifespan(app):
|
|
463
|
+
yield
|
|
464
|
+
await kernels.shutdown()
|
|
465
|
+
|
|
466
|
+
r = lambda p,meth,f: Route('/api/kernels'+p, guard(f), methods=[meth])
|
|
467
|
+
app = Starlette(lifespan=lifespan, routes=[r('','GET',list_kernels), r('','POST',create_kernel), r('/{kid}','GET',get_kernel),
|
|
468
|
+
r('/{kid}','DELETE',delete_kernel), r('/{kid}/interrupt','POST',interrupt), r('/{kid}/restart','POST',restart),
|
|
469
|
+
WebSocketRoute('/api/kernels/{kid}/channels', channels)])
|
|
470
|
+
app.state.kernels = kernels
|
|
471
|
+
return app
|
|
472
|
+
|
|
473
|
+
# %% ../nbs/00_core.ipynb #2515195d
|
|
474
|
+
def serve(app, host:str='127.0.0.1', port:int=8787, log_level:str='warning', in_thread:bool=False):
|
|
475
|
+
"Run the gateway under uvicorn; `in_thread=True` waits until it is listening and returns the server with `server.url` set (`port=0` picks a free port)."
|
|
476
|
+
import threading, time, uvicorn
|
|
477
|
+
server = uvicorn.Server(uvicorn.Config(app, host=host, port=port, log_level=log_level, ws_max_size=64*2**20))
|
|
478
|
+
if not in_thread:
|
|
479
|
+
server.run()
|
|
480
|
+
return server
|
|
481
|
+
server.thread = threading.Thread(target=server.run, daemon=True)
|
|
482
|
+
server.thread.start()
|
|
483
|
+
end = time.monotonic() + 10
|
|
484
|
+
while not server.started:
|
|
485
|
+
if time.monotonic() > end: raise TimeoutError('uvicorn did not start')
|
|
486
|
+
time.sleep(0.01)
|
|
487
|
+
server.url = f'http://{host}:{server.servers[0].sockets[0].getsockname()[1]}'
|
|
488
|
+
return server
|
|
489
|
+
|
|
490
|
+
def _env_app():
|
|
491
|
+
"App factory for the reloader: its fresh workers re-import this module, so config rides in the environment; the token is popped so spawned kernels never inherit it"
|
|
492
|
+
return create_app(auth_token=os.environ.pop('JUPYGATE_TOKEN', None))
|
|
493
|
+
|
|
494
|
+
def _reload_file():
|
|
495
|
+
"The restart lever: touching this file restarts the gateway, killing all kernels; created at startup so it is always touchable"
|
|
496
|
+
from fastcore.xdg import xdg_state_home
|
|
497
|
+
p = xdg_state_home()/'jupygate'/'reload'/'r.py'
|
|
498
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
499
|
+
p.touch()
|
|
500
|
+
return p
|
|
501
|
+
|
|
502
|
+
def main():
|
|
503
|
+
"Console entry point: `jupygate [--port N] [--token T] [--reload]`."
|
|
504
|
+
import argparse, uvicorn
|
|
505
|
+
from uvicorn.supervisors import ChangeReload
|
|
506
|
+
p = argparse.ArgumentParser(description='Websocket gateway for Jupyter kernels')
|
|
507
|
+
p.add_argument('--host', default='127.0.0.1')
|
|
508
|
+
p.add_argument('--port', type=int, default=8787)
|
|
509
|
+
p.add_argument('--token', default=None)
|
|
510
|
+
p.add_argument('--reload', action='store_true', help='also restart on package source changes (dev)')
|
|
511
|
+
args = p.parse_args()
|
|
512
|
+
if args.token: os.environ['JUPYGATE_TOKEN'] = args.token
|
|
513
|
+
reload_dirs = [str(_reload_file().parent)]
|
|
514
|
+
if args.reload: reload_dirs.append(str(Path(__file__).parent))
|
|
515
|
+
config = uvicorn.Config('jupygate.core:_env_app', factory=True, reload=True, reload_dirs=reload_dirs,
|
|
516
|
+
host=args.host, port=args.port, log_level='warning', ws_max_size=64*2**20, timeout_graceful_shutdown=5)
|
|
517
|
+
server = uvicorn.Server(config)
|
|
518
|
+
try: ChangeReload(config, target=server.run, sockets=[config.bind_socket()]).run()
|
|
519
|
+
except KeyboardInterrupt: pass
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: jupygate
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Websocket gateway for Jupyter kernels
|
|
5
|
+
Author-email: Jeremy Howard <github@jhoward.fastmail.fm>
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Repository, https://github.com/AnswerDotAI/jupygate
|
|
8
|
+
Project-URL: Documentation, https://AnswerDotAI.github.io/jupygate/
|
|
9
|
+
Keywords: nbdev
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: pyzmq>=26
|
|
16
|
+
Requires-Dist: jupywire>=0.0.1
|
|
17
|
+
Requires-Dist: fastcore>=2.1.17
|
|
18
|
+
Requires-Dist: starlette>=1.0
|
|
19
|
+
Requires-Dist: uvicorn>=0.30
|
|
20
|
+
Provides-Extra: test
|
|
21
|
+
Requires-Dist: pytest>=7.4; extra == "test"
|
|
22
|
+
Requires-Dist: pytest-timeout; extra == "test"
|
|
23
|
+
Requires-Dist: ipymini>=0.1.17; extra == "test"
|
|
24
|
+
Requires-Dist: httpx>=0.27; extra == "test"
|
|
25
|
+
Requires-Dist: websockets>=13; extra == "test"
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# jupygate
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
|
|
32
|
+
|
|
33
|
+
jupygate starts, stops, and restarts Jupyter kernels over a small HTTP API, and muxes each kernel’s zmq channels over one websocket per client. It speaks the standard Jupyter kernels REST shape and the legacy Jupyter websocket message protocol, so existing Jupyter-compatible clients work unchanged. It deliberately has no files API (manage files by running Python in a kernel), no kernelspecs (clients say exactly what to launch), and no HTML.
|
|
34
|
+
|
|
35
|
+
It is a small, readable alternative to running jupyter_server or kernel_gateway for the one job of hosting kernels. kernel_gateway is a thin skin over jupyter_server’s websocket bridge; jupygate replaces the bridge itself with a simpler architecture:
|
|
36
|
+
|
|
37
|
+
- **One persistent zmq channel set per kernel**, owned by the gateway, instead of fresh streams per websocket connection. Clients connect and drop without touching zmq, which deletes jupyter_server’s per-connect “nudge” dance, buffering handoffs, and reconnect races.
|
|
38
|
+
- **Welcome-based readiness**: kernels that implement JEP 65 (ipymini, modern ipykernel) greet each iopub subscription with `iopub_welcome`, so readiness is one bounded wait plus one `kernel_info` round trip. Kernels without it get jupyter_client-style retries - same loop, it just can’t short-circuit.
|
|
39
|
+
- **Replies route by session**: each client signs with its own session id; `parent_header.session` routes shell, control, and stdin traffic back to the requester. iopub is broadcast. The kernel’s HMAC key never leaves the gateway - client auth is a bearer token at the HTTP/websocket layer.
|
|
40
|
+
- **Explicit overflow policy**: each client has a bounded queue that never drops `status`, so a flooded client still sees a truthful busy/idle picture.
|
|
41
|
+
|
|
42
|
+
One nbdev notebook, [`core`](00_core.ipynb), builds it bottom-up - wire formats (the two websocket encodings), kernel processes, channels (the zmq side and the ready-wait), the mux (routing and fan-out), and the gateway server (the HTTP/websocket surface) - and is source, docs, and tests at once.
|
|
43
|
+
|
|
44
|
+
## Install
|
|
45
|
+
|
|
46
|
+
``` sh
|
|
47
|
+
pip install jupygate
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Plus at least one kernel; the examples use [ipymini](https://github.com/AnswerDotAI/ipymini).
|
|
51
|
+
|
|
52
|
+
## Use
|
|
53
|
+
|
|
54
|
+
Serve a gateway:
|
|
55
|
+
|
|
56
|
+
``` sh
|
|
57
|
+
jupygate --port 8787 # open, for localhost use
|
|
58
|
+
jupygate --port 8787 --token S # every request must carry the token
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The gateway watches a touch file, `~/.local/state/jupygate/reload/r.py` (created at startup): touching it restarts the gateway with new code, killing all kernels - the deliberate restart lever after upgrading jupygate or a kernel package. `--reload` additionally restarts on package source changes, for development.
|
|
62
|
+
|
|
63
|
+
Then from any HTTP client:
|
|
64
|
+
|
|
65
|
+
``` sh
|
|
66
|
+
curl -X POST localhost:8787/api/kernels # -> {"id": "...", ...}
|
|
67
|
+
curl localhost:8787/api/kernels # list
|
|
68
|
+
curl -X POST localhost:8787/api/kernels/ID/interrupt
|
|
69
|
+
curl -X DELETE localhost:8787/api/kernels/ID
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
and connect a websocket to `/api/kernels/ID/channels?session_id=...` speaking the standard Jupyter message dicts with a `channel` key (see the wire-formats section of [`core`](00_core.ipynb)). Kernel creation accepts explicit launch parameters in the POST body - `argv` (with `{connection_file}` placeholder), `env`, `cwd`, and `username` for a sudo/gosu wrap - which is also why a non-localhost deployment should set a token: this API runs arbitrary commands by design, exactly like any Jupyter kernel server.
|
|
73
|
+
|
|
74
|
+
In Python, the same thing programmatically:
|
|
75
|
+
|
|
76
|
+
``` python
|
|
77
|
+
from jupygate.core import create_app, serve
|
|
78
|
+
serve(create_app(auth_token='S'), port=8787)
|
|
79
|
+
```
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
jupygate/__init__.py,sha256=sXLh7g3KC4QCFxcZGBTpG2scR7hmmBsMjq6LqRptkRg,22
|
|
2
|
+
jupygate/_modidx.py,sha256=oUS7T-ozqbOlphiDu4TRggWGDr6Mdo5pNqMeCtm1Bxo,7543
|
|
3
|
+
jupygate/core.py,sha256=a_rauoMesu85EmSHREgr9DFJTrCCvoxhbYy0qvmk8B8,24510
|
|
4
|
+
jupygate-0.0.1.dist-info/licenses/LICENSE,sha256=xV8xoN4VOL0uw9X8RSs2IMuD_Ss_a9yAbtGNeBWZwnw,11337
|
|
5
|
+
jupygate-0.0.1.dist-info/METADATA,sha256=ky6zz9Z1t6UNiu39xoG_tz5w9zoskMo8ECAG5FmJvVo,4586
|
|
6
|
+
jupygate-0.0.1.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
|
|
7
|
+
jupygate-0.0.1.dist-info/entry_points.txt,sha256=e-pAEYLlBq5HgiR7Nm268bS6evrx9F2HF2p8_2h4m-s,87
|
|
8
|
+
jupygate-0.0.1.dist-info/top_level.txt,sha256=xZFFAfMvKg2xwUSlUT-_vZMtC7Va90kkw-ceWtyAJ3I,9
|
|
9
|
+
jupygate-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2022, fastai
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
jupygate
|