forked from schickling/docker-hook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker-hook
More file actions
executable file
·122 lines (107 loc) · 4.59 KB
/
docker-hook
File metadata and controls
executable file
·122 lines (107 loc) · 4.59 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
114
115
116
117
118
119
120
121
122
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Automatic Docker Deployment via Webhooks"""
import json
import os
from subprocess import Popen
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
try:
# For Python 3.0 and later
from http.server import HTTPServer
from http.server import BaseHTTPRequestHandler
except ImportError:
# Fall back to Python 2
from BaseHTTPServer import BaseHTTPRequestHandler
from BaseHTTPServer import HTTPServer as HTTPServer
import sys
import logging
import requests
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
level=logging.DEBUG,
stream=sys.stdout)
class RequestHandler(BaseHTTPRequestHandler):
"""A POST request handler which expects a token in its path."""
def do_POST(self):
logging.info("Path: %s", self.path)
header_length = int(self.headers.getheader('content-length', "0"))
json_payload = self.rfile.read(header_length)
env = dict(os.environ)
json_params = {}
if len(json_payload) > 0:
json_params = json.loads(json_payload)
if json_params['repository'] and hasattr(json_params['repository'], 'items'):
env.update(('REPOSITORY_' + var.upper(), str(val))
for var, val in json_params['repository'].items())
# Check if the secret URL was called
if self.path in hooks:
cmd = ["sh", hooks[self.path]]
logging.info("Start executing '%s'" % cmd)
try:
Popen(cmd, env=env).wait()
logging.info("Removing None Docker Images")
remove_cmd = "/usr/bin/docker rmi $(docker images -a | grep \"^<none>\" | awk '{print $3}')"
Popen(remove_cmd, shell=True).wait()
self.send_response(200, "OK")
if 'callback_url' in json_params:
# Make a callback to Docker Hub
data = {'state': 'success'}
headers = {'Content-type': 'application/json',
'Accept': 'text/plain'}
requests.post(json_params['callback_url'],
data=json.dumps(data),
headers=headers)
except OSError as err:
self.send_response(500, "OSError")
logging.error("You probably didn't use 'sh ./script.sh'.")
logging.error(err)
if 'callback_url' in json_params:
# Make a callback to Docker Hub
data = {'state': 'failure',
'description': str(err)}
headers = {'Content-type': 'application/json',
'Accept': 'text/plain'}
requests.post(json_params['callback_url'],
data=json.dumps(data),
headers=headers)
else:
self.send_response(401, "Not authorized")
self.end_headers()
def get_parser():
"""Get a command line parser for docker-hook."""
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument("-l", "--listhooks",
dest="list_hooks",
nargs="*",
required=True,
default=[],
help=("List of Hook options for tokens and paths e.g.: token1:/path1 token2:/path2"))
parser.add_argument("--addr",
dest="addr",
default="0.0.0.0",
help="address where it listens")
parser.add_argument("--port",
dest="port",
type=int,
default=8686,
metavar="PORT",
help="port where it listens")
return parser
def main(addr, port):
"""Start a HTTPServer which waits for requests."""
httpd = HTTPServer((addr, port), RequestHandler)
httpd.serve_forever()
if __name__ == '__main__':
parser = get_parser()
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
try:
hooks = {}
for hook in args.list_hooks:
options = hook.split(':')
hooks['/' + options[0]] = options[1]
except Exception as e:
print 'Cannot parse the hook options. They should be in format token:/path_of_deploy_file.sh and seperated by spaces'
main(args.addr, args.port)