-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
149 lines (121 loc) · 3.55 KB
/
app.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
#!/usr/bin/env python
from flask import Flask, request
import docker
import tarfile
import json
import time
import sys
import io
import os
app = Flask(__name__)
client = docker.from_env()
with open(os.getenv('RUNTIMES_JSON', 'runtimes.json')) as f:
RUNTIME_CONFIG = json.load(f)
if os.fork() == 0:
for _, config in RUNTIME_CONFIG.items():
print(f' * Pulling {config["image"]}...')
client.images.pull(config['image'])
print(' * Needed docker images are ready.')
sys.exit(0)
def get_tar_bytes(filename, text):
buf = io.BytesIO()
text_bytes = text.encode('utf-8')
tar = tarfile.TarFile(mode='w', fileobj=buf)
f = tarfile.TarInfo(filename)
f.uid = 1000
f.gid = 1000
f.size = len(text_bytes)
tar.addfile(f, io.BytesIO(text_bytes))
tar.close()
return buf.getvalue()
@app.route('/')
def list_containers():
labels = [
'whalebox.created=true'
]
if request.args.get('user'):
labels.append(f'whalebox.user={request.args.get("user")}')
containers = client.containers.list(all=True, filters={'label': labels})
return {
'containers': [
{
'id': c.short_id,
'status': c.status,
'labels': c.labels
} for c in containers
]
}
@app.route('/', methods=['POST'])
def create_container():
runtime = request.json['runtime']
code = request.json['code']
extra = request.json.get('extra', {})
labels = {
'whalebox.created': 'true',
'whalebox.runtime': runtime
}
if request.args.get('user'):
labels['whalebox.user'] = request.args.get('user')
config = RUNTIME_CONFIG[runtime]
try:
client.images.get(config['image'])
except docker.errors.ImageNotFound:
client.images.pull(config['image'])
container = client.containers.create(
image=config['image'],
entrypoint=config['entrypoint'],
command=config['command'],
cpu_shares=1000,
network_disabled=True,
oom_kill_disable=False,
pids_limit=10,
shm_size='1M',
mem_limit='16M',
stdin_open=True,
tty=True,
user=1000,
environment={
'TERM': 'dumb'
},
labels=labels
)
container.put_archive('/', get_tar_bytes(config['file'], code))
for k, v in extra.items():
container.put_archive('/', get_tar_bytes(k, v))
while container.status == 'created':
container.start()
time.sleep(0.5)
container.reload()
return {
'id': container.short_id,
'status': container.status,
'labels': container.labels
}
@app.route('/<container_id>', methods=['DELETE'])
def delete_container(container_id):
container = client.containers.get(containerid)
container.remove(force=True)
return ''
@app.route('/<container_id>', methods=['POST'])
def write_to_container(container_id):
s = client.api.attach_socket(
container_id, params={'stdin': 1, 'stream': 1})
data = request.get_data()
s._sock.send(data)
if request.args.get('nl'):
s._sock.send(b"\n")
s.close()
return ''
@app.route('/<container_id>', methods=['GET'])
def read_from_container(container_id):
kwargs = {
'stdout': True,
'stderr': False,
'tail': 128
}
if request.args.get('stderr'):
kwargs['stderr'] = True
if request.args.get('tail'):
kwargs['tail'] = int(request.args.get('tail'))
container = client.containers.get(container_id)
return container.logs(**kwargs)