-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
113 lines (95 loc) · 3.46 KB
/
app.py
File metadata and controls
113 lines (95 loc) · 3.46 KB
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
# -*- coding: utf-8 -*-
"""Autodeployment service for docker swarm.
This application allows to automatically update swarm services, whenever
a new image is built/pushed to the Docker Hub.
Example:
Application assumes that the access is secured with a token, which is
passed via path argument.
# If Docker Hub webhook is pointed to:
# https://deploy.example.app/?token=my_secret_token
$ export HUB_TOKEN=my_secret_token
$ python app.py
Todo:
* Add tests
* Integrate with CirceCI
"""
from concurrent.futures import ThreadPoolExecutor
import json
import logging
import os
import requests
import tornado.ioloop
import tornado.web
import tornado.escape
import tornado.httpclient
import tornado.log
import docker
HUB_TOKEN = os.environ.get('HUB_TOKEN', 'set_me')
class DockerHubHandler(tornado.web.RequestHandler):
"""Endpoint handling POST requests from Docker Hub."""
executor = ThreadPoolExecutor(max_workers=2)
def set_default_headers(self):
"""Set default headers."""
self.set_header('Access-Control-Allow-Headers', 'x-requested-with')
self.set_header('Access-Control-Allow-Methods', 'POST')
def head(self):
"""Set default HEAD response."""
self.set_status(204)
self.finish()
def options(self):
"""Set default OPTIONS response."""
self.set_status(204)
self.finish()
@tornado.concurrent.run_on_executor
def redeploy_stack(self, payload):
"""Update service using POST's payload."""
logging.info(payload)
repo = payload['repository']
tag = payload['push_data']['tag']
new_image = '{}:{}'.format(repo['repo_name'], tag)
logging.info('Got image {}'.format(new_image))
cli = docker.from_env(version='1.28')
services = {}
for s in cli.services.list():
service_image = \
s.attrs['Spec']['TaskTemplate']['ContainerSpec']['Image']
service_image = service_image.split('@')[0]
services[service_image] = s.id
try:
service = cli.services.get(services[new_image])
service.update(image=new_image, force_update=True)
logging.info('Updated {}'.format(service.name))
except KeyError:
pass
@tornado.gen.coroutine
def post(self):
"""Accept and validate Docker Hub's webhook payload."""
try:
data = tornado.escape.json_decode(self.request.body)
except json.decoder.JSONDecodeError:
self.write("Invalid payload")
self.set_status(400)
self.finish()
return
if self.get_argument('token') == HUB_TOKEN:
self.redeploy_stack(data)
try:
requests.post(
data['callback_url'],
data=json.dumps({'state': 'success'}),
headers={'Content-type': 'application/json',
'Accept': 'text/plain'})
except KeyError:
logging.warn('No callback_url which is weird')
self.write("OK")
self.set_status(200)
else:
self.write("Not authorized")
self.set_status(401)
self.finish()
if __name__ == "__main__":
logging.getLogger().setLevel(logging.INFO)
tornado.log.enable_pretty_logging()
app = tornado.web.Application([(r"/", DockerHubHandler, {})])
app.listen(8081)
tornado.ioloop.IOLoop.current().start()