2017-10-06 05:38:33 +08:00
|
|
|
from flask import Flask
|
|
|
|
from flask_restful import Resource, Api
|
2017-10-06 16:20:40 +08:00
|
|
|
from flask import jsonify
|
|
|
|
import docker
|
2017-10-06 05:38:33 +08:00
|
|
|
|
2017-10-06 16:20:40 +08:00
|
|
|
docker_client = docker.DockerClient(base_url='unix://var/run/docker.sock')
|
2017-10-06 05:38:33 +08:00
|
|
|
app = Flask(__name__)
|
|
|
|
api = Api(app)
|
|
|
|
|
2017-10-06 16:20:40 +08:00
|
|
|
class containers_get(Resource):
|
2017-10-06 05:38:33 +08:00
|
|
|
def get(self):
|
2017-10-06 16:20:40 +08:00
|
|
|
containers = {}
|
|
|
|
for container in docker_client.containers.list(all=True):
|
|
|
|
containers.update({container.attrs['Id']: container.attrs})
|
|
|
|
return containers
|
2017-10-06 05:38:33 +08:00
|
|
|
|
2017-10-06 16:20:40 +08:00
|
|
|
class container_get(Resource):
|
2017-10-06 05:38:33 +08:00
|
|
|
def get(self, container_id):
|
2017-10-06 16:20:40 +08:00
|
|
|
if container_id and container_id.isalnum():
|
|
|
|
for container in docker_client.containers.list(all=True, filters={"id": container_id}):
|
|
|
|
return container.attrs
|
2017-10-06 05:38:33 +08:00
|
|
|
else:
|
2017-10-06 16:20:40 +08:00
|
|
|
return jsonify(message='No or invalid id defined')
|
2017-10-06 05:38:33 +08:00
|
|
|
|
2017-10-06 16:20:40 +08:00
|
|
|
class container_post(Resource):
|
|
|
|
def post(self, container_id, post_action):
|
|
|
|
if container_id and container_id.isalnum() and post_action:
|
|
|
|
if post_action == 'stop':
|
|
|
|
try:
|
|
|
|
for container in docker_client.containers.list(all=True, filters={"id": container_id}):
|
|
|
|
container.stop()
|
|
|
|
except:
|
|
|
|
return 'Error'
|
|
|
|
else:
|
|
|
|
return 'OK'
|
|
|
|
elif post_action == 'start':
|
|
|
|
try:
|
|
|
|
for container in docker_client.containers.list(all=True, filters={"id": container_id}):
|
|
|
|
container.start()
|
|
|
|
except:
|
|
|
|
return 'Error'
|
|
|
|
else:
|
|
|
|
return 'OK'
|
2017-10-06 19:32:49 +08:00
|
|
|
elif post_action == 'restart':
|
|
|
|
try:
|
|
|
|
for container in docker_client.containers.list(all=True, filters={"id": container_id}):
|
|
|
|
container.restart()
|
|
|
|
except:
|
|
|
|
return 'Error'
|
|
|
|
else:
|
|
|
|
return 'OK'
|
2017-10-06 16:20:40 +08:00
|
|
|
else:
|
|
|
|
return jsonify(message='Invalid action')
|
2017-10-06 05:38:33 +08:00
|
|
|
else:
|
2017-10-06 16:20:40 +08:00
|
|
|
return jsonify(message='Invalid container id or missing action')
|
2017-10-06 05:38:33 +08:00
|
|
|
|
2017-10-06 16:20:40 +08:00
|
|
|
api.add_resource(containers_get, '/containers/json')
|
|
|
|
api.add_resource(container_get, '/containers/<string:container_id>/json')
|
|
|
|
api.add_resource(container_post, '/containers/<string:container_id>/<string:post_action>')
|
2017-10-06 05:38:33 +08:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
app.run(debug=False, host='0.0.0.0', port='8080')
|