forked from jupyter/tmpnb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
orchestrate.py
372 lines (311 loc) · 12.9 KB
/
orchestrate.py
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import json
import os
import re
import uuid
from concurrent.futures import ThreadPoolExecutor
import tornado
import tornado.options
from tornado.log import app_log
from tornado.web import RequestHandler, HTTPError, RedirectHandler
from tornado import gen, web
import dockworker
import spawnpool
class BaseHandler(RequestHandler):
# REGEX to test the path specifies a user container
user_path_regex = re.compile("^/?user/\w+")
def is_user_path(self, path):
return path is not None and BaseHandler.user_path_regex.match(path)
def write_error(self, status_code, **kwargs):
if status_code == 404:
self.render("error/404.html", status_code = status_code)
else:
self.render("error/500.html", status_code = status_code)
def prepare(self):
if self.allow_origin:
self.set_header("Access-Control-Allow-Origin", self.allow_origin)
if self.expose_headers:
self.set_header("Access-Control-Expose-Headers", self.expose_headers)
if self.max_age:
self.set_header("Access-Control-Max-Age", self.max_age)
if self.allow_credentials:
self.set_header("Access-Control-Allow-Credentials", self.allow_credentials)
if self.allow_methods:
self.set_header("Access-Control-Allow-Methods", self.allow_methods)
if self.allow_headers:
self.set_header("Access-Control-Allow-Headers", self.allow_headers)
@property
def allow_origin(self):
return self.settings['allow_origin']
@property
def expose_headers(self):
return self.settings['expose_headers']
@property
def max_age(self):
return self.settings['max_age']
@property
def allow_credentials(self):
return self.settings['allow_credentials']
@property
def allow_methods(self):
return self.settings['allow_methods']
@property
def allow_headers(self):
return self.settings['allow_headers']
class LoadingHandler(BaseHandler):
def get(self, path=None):
self.render("loading.html", is_user_path=self.is_user_path(path))
class APIStatsHandler(BaseHandler):
def get(self):
'''Returns some statistics/metadata about the tmpnb server'''
self.set_header("Content-Type", 'application/json')
response = {
'available': len(self.pool.available),
'capacity': self.pool.capacity,
'version': '0.1.0',
'container_image': self.pool.container_config.image,
}
self.write(response)
@property
def pool(self):
return self.settings['pool']
class InfoHandler(BaseHandler):
def get(self):
self.render("stats.html")
@property
def pool(self):
return self.settings['pool']
class SpawnHandler(BaseHandler):
@gen.coroutine
def get(self, path=None):
'''Spawns a brand new server'''
try:
if self.is_user_path(path):
# Path is trying to get back to a previously existing container
# Split /user/{some_user}/long/url/path and acquire {some_user}
path_parts = path.lstrip('/').split('/', 2)
user = path_parts[1]
# Scrap a container from the pool and replace it with an ad-hoc replacement.
# This takes longer, but is necessary to support ad-hoc containers
yield self.pool.adhoc(user)
url = path
else:
# There is no path or it represents a subpath of the notebook server
# Assign a prelaunched container from the pool and redirect to it.
container_path = self.pool.acquire().path
app_log.info("Allocated [%s] from the pool.", container_path)
# If no path is set, append self.redirect_uri to the redirect target, else
# redirect to specified path.
if path is None:
redirect_path = self.redirect_uri
else:
redirect_path = path.lstrip('/')
url = "/{}/{}".format(container_path, redirect_path)
app_log.debug("Redirecting [%s] -> [%s].", self.request.path, url)
self.redirect(url, permanent=False)
except spawnpool.EmptyPoolError:
app_log.warning("The container pool is empty!")
self.render("full.html", cull_period=self.cull_period)
@property
def pool(self):
return self.settings['pool']
@property
def cull_period(self):
return self.settings['cull_period']
@property
def redirect_uri(self):
return self.settings['redirect_uri']
class APISpawnHandler(BaseHandler):
@gen.coroutine
def post(self):
'''Spawns a brand new server programatically'''
try:
url = self.pool.acquire().path
app_log.info("Allocated [%s] from the pool.", url)
app_log.debug("Responding with container url [%s].", url)
self.write({'url': url})
except spawnpool.EmptyPoolError:
app_log.warning("The container pool is empty!")
self.write({'status': 'full'})
@property
def pool(self):
return self.settings['pool']
def main():
tornado.options.define('cull_period', default=600,
help="Interval (s) for culling idle containers."
)
tornado.options.define('cull_timeout', default=3600,
help="Timeout (s) for culling idle containers."
)
tornado.options.define('container_ip', default='127.0.0.1',
help="""Host IP address for containers to bind to. If host_network=True,
the host IP address for notebook servers to bind to."""
)
tornado.options.define('container_port', default='8888',
help="""Within container port for notebook servers to bind to.
If host_network=True, the starting port assigned to notebook servers on the host."""
)
command_default = (
'ipython notebook --no-browser'
' --port {port} --ip=0.0.0.0'
' --NotebookApp.base_url=/{base_path}'
' --NotebookApp.port_retries=0'
)
tornado.options.define('command', default=command_default,
help="""Command to run when booting the image. A placeholder for
{base_path} should be provided. A placeholder for {port} and {ip} can be provided."""
)
tornado.options.define('port', default=9999,
help="port for the main server to listen on"
)
tornado.options.define('ip', default=None,
help="ip for the main server to listen on [default: all interfaces]"
)
tornado.options.define('max_dock_workers', default=2,
help="Maximum number of docker workers"
)
tornado.options.define('mem_limit', default="512m",
help="Limit on Memory, per container"
)
tornado.options.define('cpu_shares', default=None,
help="Limit CPU shares, per container"
)
tornado.options.define('image', default="jupyter/minimal",
help="Docker container to spawn for new users. Must be on the system already"
)
tornado.options.define('docker_version', default="auto",
help="Version of the Docker API to use"
)
tornado.options.define('redirect_uri', default="/tree",
help="URI to redirect users to upon initial notebook launch"
)
tornado.options.define('pool_size', default=10,
help="Capacity for containers on this system. Will be prelaunched at startup."
)
tornado.options.define('pool_name', default=None,
help="Container name fragment used to identity containers that belong to this instance."
)
tornado.options.define('static_files', default=None,
help="Static files to extract from the initial container launch"
)
tornado.options.define('allow_origin', default=None,
help="Set the Access-Control-Allow-Origin header. Use '*' to allow any origin to access."
)
tornado.options.define('expose_headers', default=None,
help="Sets the Access-Control-Expose-Headers header."
)
tornado.options.define('max_age', default=None,
help="Sets the Access-Control-Max-Age header."
)
tornado.options.define('allow_credentials', default=None,
help="Sets the Access-Control-Allow-Credentials header."
)
tornado.options.define('allow_methods', default=None,
help="Sets the Access-Control-Allow-Methods header."
)
tornado.options.define('allow_headers', default=None,
help="Sets the Access-Control-Allow-Headers header."
)
tornado.options.define('assert_hostname', default=False,
help="Verify hostname of Docker daemon."
)
tornado.options.define('container_user', default=None,
help="User to run container command as"
)
tornado.options.define('host_network', default=False,
help="""Attaches the containers to the host networking instead of the
default docker bridge. Affects the semantics of container_port and container_ip."""
)
tornado.options.parse_command_line()
opts = tornado.options.options
handlers = [
(r"/", LoadingHandler),
(r"/spawn/?(/user/\w+(?:/.*)?)?", SpawnHandler),
(r"/spawn/((?:notebooks|tree)(?:/.*)?)", SpawnHandler),
(r"/api/spawn/?", APISpawnHandler),
(r"/(user/\w+)(?:/.*)?", LoadingHandler),
(r"/((?:notebooks|tree)(?:/.*)?)", LoadingHandler),
(r"/api/stats/?", APIStatsHandler),
(r"/stats/?", RedirectHandler, {"url": "/api/stats"}),
(r"/info/?", InfoHandler)
]
proxy_token = os.environ['CONFIGPROXY_AUTH_TOKEN']
proxy_endpoint = os.environ.get('CONFIGPROXY_ENDPOINT', "http://127.0.0.1:8001")
docker_host = os.environ.get('DOCKER_HOST', 'unix://var/run/docker.sock')
max_age = datetime.timedelta(seconds=opts.cull_timeout)
pool_name = opts.pool_name
if pool_name is None:
# Derive a valid container name from the image name by default.
pool_name = re.sub('[^a-zA-Z0_.-]+', '', opts.image.split(':')[0])
container_config = dockworker.ContainerConfig(
image=opts.image,
command=opts.command,
mem_limit=opts.mem_limit,
cpu_shares=opts.cpu_shares,
container_ip=opts.container_ip,
container_port=opts.container_port,
container_user=opts.container_user,
host_network=opts.host_network,
)
spawner = dockworker.DockerSpawner(docker_host,
timeout=30,
version=opts.docker_version,
max_workers=opts.max_dock_workers,
assert_hostname=opts.assert_hostname,
)
static_path = os.path.join(os.path.dirname(__file__), "static")
pool = spawnpool.SpawnPool(proxy_endpoint=proxy_endpoint,
proxy_token=proxy_token,
spawner=spawner,
container_config=container_config,
capacity=opts.pool_size,
max_age=max_age,
static_files=opts.static_files,
static_dump_path=static_path,
pool_name=pool_name,
)
ioloop = tornado.ioloop.IOLoop().instance()
settings = dict(
default_handler_class=BaseHandler,
static_path=static_path,
cookie_secret=uuid.uuid4(),
xsrf_cookies=False,
debug=True,
cull_period=opts.cull_period,
allow_origin=opts.allow_origin,
expose_headers=opts.expose_headers,
max_age=opts.max_age,
allow_credentials=opts.allow_credentials,
allow_methods=opts.allow_methods,
allow_headers=opts.allow_headers,
spawner=spawner,
pool=pool,
autoescape=None,
proxy_token=proxy_token,
template_path=os.path.join(os.path.dirname(__file__), 'templates'),
proxy_endpoint=proxy_endpoint,
redirect_uri=opts.redirect_uri.lstrip('/'),
)
# Cleanup on a fresh state (likely a restart)
ioloop.run_sync(pool.cleanout)
# Synchronously cull any existing, inactive containers, and pre-launch a set number of
# containers, ready to serve.
ioloop.run_sync(pool.heartbeat)
if(opts.static_files):
ioloop.run_sync(pool.copy_static)
# Periodically execute a heartbeat function to cull used containers and regenerated failed
# ones, self-healing the cluster.
cull_ms = opts.cull_period * 1e3
app_log.info("Culling containers unused for %i seconds every %i seconds.",
opts.cull_timeout,
opts.cull_period)
culler = tornado.ioloop.PeriodicCallback(pool.heartbeat, cull_ms)
culler.start()
app_log.info("Listening on {}:{}".format(opts.ip or '*', opts.port))
application = tornado.web.Application(handlers, **settings)
application.listen(opts.port, opts.ip)
ioloop.start()
if __name__ == "__main__":
main()