-
Notifications
You must be signed in to change notification settings - Fork 0
/
container-server.py
226 lines (204 loc) · 7.48 KB
/
container-server.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
rom flask import Flask, Response, render_template, request
import json
from subprocess import Popen, PIPE
import os
from tempfile import mkdtemp
from werkzeug import secure_filename
app = Flask(__name__)
@app.route("/")
def index():
return """
Available API endpoints:
GET /containers List all containers
GET /containers?state=running List running containers (only)
GET /containers/<id> Inspect a specific container
GET /containers/<id>/logs Dump specific container logs
GET /images List all images
POST /images Create a new image
POST /containers Create a new container
PATCH /containers/<id> Change a container's state
PATCH /images/<id> Change a specific image's attributes
DELETE /containers/<id> Delete a specific container
DELETE /containers Delete all containers (including running)
DELETE /images/<id> Delete a specific image
DELETE /images Delete all images
"""
@app.route('/containers', methods=['GET'])
def containers_index():
"""
List all containers
curl -s -X GET -H 'Accept: application/json' http://localhost:8080/containers | python -mjson.tool
curl -s -X GET -H 'Accept: application/json' http://localhost:8080/containers?state=running | python -mjson.tool
"""
if request.args.get('state') == 'running':
output = docker('ps')
resp = json.dumps(docker_ps_to_array(output))
else:
output = docker('ps', '-a')
resp = json.dumps(docker_ps_to_array(output))
return Response(response=resp, mimetype="application/json")
@app.route('/images', methods=['GET'])
def images_index():
"""
List all images
Complete the code below generating a valid response.
"""
output = docker('images', '-a')
resp = json.dumps(docker_images_to_array(output))
return Response(response=resp, mimetype="application/json")
@app.route('/containers/<id>', methods=['GET'])
def containers_show(id):
"""
Inspect specific container
"""
output = docker('ps -f',id)
resp = json.dumps(docker_ps_to_array(output))
return Response(response=resp, mimetype="application/json")
@app.route('/containers/<id>/logs', methods=['GET'])
def containers_log(id):
"""
Dump specific container logs
"""
output = docker('logs -f', id )
resp = json.dumps(docker_logs_to_object(output))
return Response(response=resp, mimetype="application/json")
@app.route('/images/<id>', methods=['DELETE'])
def images_remove(id):
"""
Delete a specific image
"""
docker ('rmi', id)
resp = '{"id": "%s"}' % id
return Response(response=resp, mimetype="application/json")
@app.route('/containers/<id>', methods=['DELETE'])
def containers_remove(id):
"""
Delete a specific container - must be already stopped/killed
"""
container.stop(id)
docker ('rm',id)
resp = '{"id": "%s"}' % id
return Response(response=resp, mimetype="application/json")
@app.route('/containers', methods=['DELETE'])
def containers_remove_all():
"""
Force remove all containers - dangrous!
"""
client = docker.from_env()
for container in client.containers.list():
container.stop()
docker ('rm -a')
# resp = ''
return Response(response=resp, mimetype="application/json")
@app.route('/images', methods=['DELETE'])
def images_remove_all():
"""
Force remove all images - dangrous!
"""
docker ('rmi -a')
# resp = ''
return Response(response=resp, mimetype="application/json")
@app.route('/containers', methods=['POST'])
def containers_create():
"""
Create container (from existing image using id or name)
curl -X POST -H 'Content-Type: application/json' http://localhost:8080/containers -d '{"image": "my-app"}'
curl -X POST -H 'Content-Type: application/json' http://localhost:8080/containers -d '{"image": "b14752a6590e"}'
curl -X POST -H 'Content-Type: application/json' http://localhost:8080/containers -d '{"image": "b14752a6590e","publish":"8081:22"}'
"""
body = request.get_json(force=True)
image = body['image']
args = ('run', '-d')
id = docker(*(args + (image,)))[0:12]
return Response(response='{"id": "%s"}' % id, mimetype="application/json")
def images_create():
"""
Create image (from uploaded Dockerfile)
curl -H 'Accept: application/json' -F file=@Dockerfile http://localhost:8080/images
"""
dockerfile = request.files['file']
# resp = ''
return Response(response=resp, mimetype="application/json")
@app.route('/containers/<id>', methods=['PATCH'])
def containers_update(id):
"""
Update container attributes (support: state=running|stopped)
curl -X PATCH -H 'Content-Type: application/json' http://localhost:8080/containers/b6cd8ea512c8 -d '{"state": "running"}'
curl -X PATCH -H 'Content-Type: application/json' http://localhost:8080/containers/b6cd8ea512c8 -d '{"state": "stopped"}'
"""
body = request.get_json(force=True)
try:
state = body['state']
if state == 'running':
docker('restart', id)
except:
pass
resp = '{"id": "%s"}' % id
return Response(response=resp, mimetype="application/json")
@app.route('/images/<id>', methods=['PATCH'])
def images_update(id):
"""
Update image attributes (support: name[:tag]) tag name should be lowercase only
curl -s -X PATCH -H 'Content-Type: application/json' http://localhost:8080/images/7f2619ed1768 -d '{"tag": "test:1.0"}'
"""
# resp = ''
return Response(response=resp, mimetype="application/json")
@app.route('/containers', methods=['GET'])
def swarm_index():
"""
List all nodes in the swarm
"""
output = docker'(docker node ls'')
resp = json.dumps(docker_ps_to_array(output))
return Response(response=resp, mimetype="application/json")
def docker(*args):
cmd = ['docker']
for sub in args:
cmd.append(sub)
process = Popen(cmd, stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
if stderr.startswith('Error'):
print 'Error: {0} -> {1}'.format(' '.join(cmd), stderr)
return stderr + stdout
#
# Docker output parsing helpers
#
#
# Parses the output of a Docker PS command to a python List
#
def docker_ps_to_array(output):
all = []
for c in [line.split() for line in output.splitlines()[1:]]:
each = {}
each['id'] = c[0]
each['image'] = c[1]
each['name'] = c[-1]
each['ports'] = c[-2]
all.append(each)
return all
#
# Parses the output of a Docker logs command to a python Dictionary
# (Key Value Pair object)
def docker_logs_to_object(id, output):
logs = {}
logs['id'] = id
all = []
for line in output.splitlines():
for line in output.splitlines():
all.append(line)
logs['logs'] = all
return logs
#
# Parses the output of a Docker image command to a python List
#
def docker_images_to_array(output):
all = []
for c in [line.split() for line in output.splitlines()[1:]]:
each = {}
each['id'] = c[2]
each['tag'] = c[1]
each['name'] = c[0]
all.append(each)
return all
if __name__ == "__main__":
app.run(host="0.0.0.0",port=8080, debug=True)