-
Notifications
You must be signed in to change notification settings - Fork 433
Expand file tree
/
Copy pathjupyter.py
More file actions
291 lines (233 loc) · 8.37 KB
/
jupyter.py
File metadata and controls
291 lines (233 loc) · 8.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import os
import sys
import re
import json
import stat
import pprint
import uuid
import signal
import subprocess
from socketserver import TCPServer, StreamRequestHandler
try:
from socketserver import UnixStreamServer
except:
pass
from log import log_init, log, log_error, trace
from notebook import notebook_execute, RestartKernel
from nbclient.exceptions import CellExecutionError
import asyncio
if sys.platform == 'win32':
from asyncio.windows_events import *
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
class ExecuteHandler(StreamRequestHandler):
def handle(self):
try:
trace('handling server request')
# read input
input = str(self.rfile.readline().strip(), 'utf-8')
input = json.loads(input)
# validate secret
if not self.server.validate_secret(input["secret"]):
trace('invalid secret (exiting server)')
self.server.request_exit()
return
if input["command"] == "file":
filename = input["options"]["file"]
input = json.load(open(filename, "r", encoding="utf8"))
os.unlink(filename)
# if this is an abort command then request exit
command = input["command"]
if command == "abort":
trace('abort command received (exiting server)')
self.server.request_exit()
return
# options
options = input["options"]
# stream status back to client
def status(msg):
self.message("status", msg)
# execute the notebook
trace('executing notebook')
persist = notebook_execute(options, status)
if not persist:
trace('notebook not persistable (exiting server)')
self.server.request_exit()
else:
self.server.record_success()
except RestartKernel:
trace('notebook restart request recived (exiting server)')
self.message("restart")
self.server.request_exit()
except Exception as e:
self.message("error", "\n\n" + str(e))
self.server.record_error(e)
# write a message back to the client
def message(self, type, data = ""):
message = {
"type": type,
"data": data
}
self.wfile.write(bytearray(json.dumps(message) + "\n", 'utf-8'))
self.wfile.flush()
def execute_server(options):
# determine server type
is_tcp = options["type"] == "tcp"
if is_tcp:
base = TCPServer
else:
base = UnixStreamServer
class ExecuteServer(base):
allow_reuse_address = True
exit_pending = False
consecutive_errors = 0
def __init__(self, options):
trace('creating notebook server (' +
options["type"] + ': ' + options["transport"]
+ ')')
# set secret for tcp
if is_tcp:
self.secret = str(uuid.uuid4())
else:
self.secret = ""
# server params
self.transport = options["transport"]
self.timeout = options["timeout"]
# initialize with address (based on server type) and handler
if is_tcp:
server_address = ("localhost",0)
else:
server_address = self.transport
super().__init__(server_address, ExecuteHandler)
# if we are a tcp server then get the port number and write it
# to the transport file. change file permissions to user r/w
# for both tcp and unix domain sockets
if is_tcp:
port = self.socket.getsockname()[1]
trace('notebook server bound to port ' + str(port))
with open(self.transport,"w") as file:
file.write("")
os.chmod(self.transport, stat.S_IRUSR | stat.S_IWUSR)
with open(self.transport,"w") as file:
file.write(json.dumps(dict({
"port": port,
"secret": self.secret
})))
else:
os.chmod(self.transport, stat.S_IRUSR | stat.S_IWUSR)
def handle_request(self):
if self.exit_pending:
self.exit()
super().handle_request()
def handle_timeout(self):
trace('request timeout (exiting server)')
self.exit()
def validate_secret(self, secret):
return self.secret == secret
def record_success(self):
self.consecutive_errors = 0
def record_error(self, e):
# exit for 5 consecutive errors
self.consecutive_errors += 1
if self.consecutive_errors >= 5:
self.exit()
def request_exit(self):
self.exit_pending = True
def exit(self):
try:
trace('cleaning up server resources')
self.server_close()
self.remove_transport()
finally:
trace('exiting server')
sys.exit(0)
def remove_transport(self):
try:
if os.path.exists(self.transport):
os.remove(self.transport)
except:
pass
return ExecuteServer(options)
def run_server(options):
try:
with execute_server(options) as server:
while True:
server.handle_request()
except Exception as e:
log_error("Unable to run server", exc_info = e)
# run a server as a detached subprocess
def run_server_subprocess(options, status):
# python executable
python_exe = sys.executable
# detached process flags for windows
flags = 0
if sys.platform == 'win32':
python_exe = re.sub('python\\.exe$', 'pythonw.exe', python_exe)
flags |= 0x00000008 # DETACHED_PROCESS
flags |= 0x00000200 # CREATE_NEW_PROCESS_GROUP
flags |= 0x08000000 # CREATE_NO_WINDOW
flags |= 0x01000000 # CREATE_BREAKAWAY_FROM_JOB
# forward options via env vars
os.environ["QUARTO_JUPYTER_OPTIONS"] = json.dumps(options)
# create subprocess
subprocess.Popen([python_exe] + sys.argv + ["serve"],
stdin = subprocess.DEVNULL,
stdout = subprocess.DEVNULL,
stderr = subprocess.DEVNULL,
creationflags = flags,
close_fds = True,
start_new_session = True
)
# run a notebook directly (not a server)
def run_notebook(options, status):
# run notebook w/ some special exception handling. note that we don't
# log exceptions here b/c they are considered normal course of execution
# for errors that occur in notebook cells
try:
trace('Running notebook_execute')
notebook_execute(options, status)
except Exception as e:
trace(f'run_notebook caught exception: {type(e).__name__}')
# CellExecutionError for execution at the terminal includes a bunch
# of extra stack frames internal to this script. remove them
msg = str(e)
kCellExecutionError = "nbclient.exceptions.CellExecutionError: "
loc = msg.find(kCellExecutionError)
if loc != -1:
msg = msg[loc + len(kCellExecutionError):]
status("\n\n" + msg + "\n")
sys.exit(1)
if __name__ == "__main__":
# stream status to stderr
def status(msg):
sys.stderr.write(msg)
sys.stderr.flush()
try:
# read command from cmd line if it's there (in that case
# options are passed via environment variable)
if len(sys.argv) > 1:
command = sys.argv[1]
options = json.loads(os.getenv("QUARTO_JUPYTER_OPTIONS"))
del os.environ["QUARTO_JUPYTER_OPTIONS"]
# otherwise read from stdin
else:
input = json.load(sys.stdin)
command = input["command"]
options = input["options"]
# initialize log
log_init(options["log"], options["debug"])
# start the server (creates a new detached process, we implement this here
# only b/c Deno doesn't currently support detaching spawned processes)
if command == "start":
trace('starting notebook server subprocess')
run_server_subprocess(options, status)
# serve a notebook (invoked by run_server_subprocess)
elif command == "serve":
trace('running notebook server subprocess')
run_server(options)
# execute a notebook and then quit
elif command == "execute":
trace('running notebook without keepalive')
run_notebook(options, status)
except Exception as e:
log_error("Unable to run notebook", exc_info = e)
sys.exit(1)