-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwww.py
154 lines (136 loc) · 4.18 KB
/
www.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
import os
import json
import shutil
import hashlib
import datetime
from urllib.parse import urlparse
import docker
import requests
from sparkpost import SparkPost
from slugify import slugify
from flask import Flask, request
from flask_slack import Slack
from concurrent.futures import ThreadPoolExecutor
app = Flask(__name__)
slack = Slack(app)
app.add_url_rule('/slack', view_func=slack.dispatch)
executor = ThreadPoolExecutor(2)
client = docker.from_env()
# sparkpost
sp = SparkPost()
@slack.command(
'interview',
token=os.getenv('SLACK_SLASH_TOKEN'),
team_id=os.getenv('SLACK_SLASH_TEAM_ID'),
methods=['POST']
)
def interview(**kwargs):
hostname = urlparse(request.url_root).hostname
text = kwargs.get('text')
options = text.split()
responseText = None
if options[0] == 'list':
responseText = ls()
elif options[0] == 'start':
responseText = 'Starting %s\'s interview.' % options[1]
executor.submit(start, options[1], hostname)
elif options[0] == 'stop':
if len(options) == 1:
responseText = stop()
else:
responseText = stop(options[1])
else:
responseText = 'Invalid action.'
return slack.response(responseText)
def notify(text):
requests.post(
os.getenv('SLACK_INCOMING_HOOK'),
data=json.dumps({'text': text}),
headers={'Content-Type': 'application/json'}
)
def ls():
containers = client.containers.list(filters={
'ancestor': 'jupyter/datascience-notebook'
})
if len(containers):
responseText = '\n'.join([c.name for c in containers])
else:
responseText = 'No any interview.'
return responseText
def stop(user_id=None):
if user_id:
container_name = slugify(user_id)
container = client.containers.get(container_name)
containers = [container]
else:
containers = client.containers.list(
all=True,
filters={
'ancestor': 'jupyter/datascience-notebook'
}
)
responseText = ""
for container in containers:
container.remove(force=True)
responseText += '%s stopped.\n' % container.name
return responseText
def start(user_id, hostname):
container_name = slugify(user_id)
try:
container = client.containers.get(container_name)
except docker.errors.NotFound:
abspath = os.path.dirname(os.path.abspath(__file__))
if user_id == 'admin':
folder = abspath
else:
folder = '%s/jupyter/%s' % (abspath, user_id)
try:
shutil.copytree('%s/exam' % abspath, folder)
except OSError as e:
pass
# notify('`%s` has already taken' % user_id)
except Exception as e:
notify(str(e))
try:
os.chown(folder, 0, 100)
os.chmod(folder, int('775', 8))
except Exception as e:
notify(str(e))
try:
container = client.containers.run(
'jupyter/datascience-notebook',
name=container_name,
cpuset_cpus="0",
mem_limit="2500M",
detach=True,
publish_all_ports=True,
volumes={folder: {'bind': '/home/jovyan/work', 'mode': 'rw'}}
)
container = client.containers.get(container.id)
except Exception as e:
notify(str(e))
token = None
ports = container.attrs['NetworkSettings']['Ports']
port = ports['8888/tcp'][0]['HostPort']
for line in container.logs(stream=True):
pos = line.find(b'token=')
if pos >= 0:
pos += 6
token = line[pos:pos + 48].decode("utf-8")
break
url = 'http://%s:%s/?token=%s' % (hostname, port, token)
notify('%s\n%s' % (user_id, url))
try:
sp.transmissions.send(
recipients=[user_id],
template='data-science-online-assessment-url',
substitution_data={
'name': user_id,
'url': url,
}
)
except Exception as e:
notify(str(e))
return url
if __name__ == "__main__":
app.run()