-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathbuilder
More file actions
executable file
·173 lines (167 loc) · 7.71 KB
/
builder
File metadata and controls
executable file
·173 lines (167 loc) · 7.71 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
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
#!/usr/bin/env python
#
# builder hook called on every git receive-pack
# NOTE: this script must be run as root (for docker access)
#
import hashlib
import json
import os
import requests
import shutil
import subprocess
import sys
import tarfile
import tempfile
import uuid
import yaml
def parse_args():
if len(sys.argv) < 3:
print('Usage: {} [user] [repo] [branch]'.format(sys.argv[0]))
sys.exit(1)
user, repo, branch = sys.argv[1], sys.argv[2], sys.argv[3]
app = repo.split('.')[0]
return user, repo, branch, app
DOCKERFILE_SHIM = """FROM deis/slugrunner
RUN mkdir -p /app
ADD slug.tgz /app
ENTRYPOINT ["/runner/init"]
"""
if __name__ == '__main__':
user, repo, branch, app = parse_args()
# create required directories
repo_dir = os.path.join(os.getcwd(), repo)
build_dir = os.path.join(repo_dir, 'build')
cache_dir = os.path.join(repo_dir, 'cache')
# get sha of branch
with open(os.path.join(repo_dir, branch)) as f:
sha = f.read().strip('\n')
short_sha = sha[:8]
# define image names
tmp_image = "{app}:git-{short_sha}".format(**locals())
target_image = "{{ .deis_registry_host }}:{{ .deis_registry_port }}/{app}".format(**locals())
for d in (cache_dir, build_dir):
if not os.path.exists(d):
os.mkdir(d)
try:
# create temporary directory
temp_dir = tempfile.mkdtemp(dir=build_dir)
# extract git branch
p = subprocess.Popen(
'git archive {branch} | tar -x -C {temp_dir}'.format(**locals()),
shell=True, cwd=repo_dir)
rc = p.wait()
if rc != 0:
raise Exception('Could not extract git archive')
dockerfile = os.path.join(temp_dir, 'Dockerfile')
procfile = os.path.join(temp_dir, 'Procfile')
# pull config to be used during build
body = {}
body['receive_user'], body['receive_repo'] = user, app
url = "{{ .deis_controller_protocol }}://{{ .deis_controller_host }}:{{ .deis_controller_port }}/api/hooks/config"
headers = {'Content-Type': 'application/json', 'X-Deis-Builder-Auth': '{{ .deis_controller_builderKey }}'}
r = requests.post(url, headers=headers, data=json.dumps(body))
if r.status_code != 200:
raise Exception('Config hook error: {} {}'.format(r.status_code, r.text))
config_env = " ".join([ "-e {}='{}'".format(*kv) for kv in json.loads(r.json().get('values', '{}')).items()])
# some applications do not have a Procfile, so only check for a Dockerfile
if not os.path.exists(dockerfile):
if os.path.exists('/buildpacks'):
build_cmd = "docker run -i -a stdin {config_env} -v {cache_dir}:/tmp/cache:rw -v /buildpacks:/tmp/buildpacks deis/slugbuilder".format(**locals())
else:
build_cmd = "docker run -i -a stdin {config_env} -v {cache_dir}:/tmp/cache:rw deis/slugbuilder".format(**locals())
# run slugbuilder in the background
p = subprocess.Popen("git archive {branch} | ".format(**locals()) + build_cmd, shell=True, cwd=repo_dir, stdout=subprocess.PIPE)
container = p.stdout.read().strip('\n')
# attach to slugbuilder output
p = subprocess.Popen('docker attach {container}'.format(**locals()), shell=True, cwd=temp_dir)
rc = p.wait()
if rc != 0:
raise Exception('Slugbuilder returned error code')
# extract slug
p = subprocess.Popen('docker cp {container}:/tmp/slug.tgz .'.format(**locals()), shell=True, cwd=temp_dir)
rc = p.wait()
if rc != 0:
raise Exception('Could not extract slug from container')
slug_path = os.path.join(temp_dir, 'slug.tgz')
# write out a dockerfile shim for slugbuilder
with open(dockerfile, 'w') as f:
f.write(DOCKERFILE_SHIM)
# build the docker image
print('-----> Building Docker image')
sys.stdout.flush(), sys.stderr.flush()
p = subprocess.Popen('docker build -t {tmp_image} .'.format(**locals()), shell=True, cwd=temp_dir)
rc = p.wait()
if rc != 0:
raise Exception('Could not build Docker image')
# tag the image
p = subprocess.Popen('docker tag {tmp_image} {target_image}'.format(**locals()), shell=True)
rc = p.wait()
if rc != 0:
raise Exception('Could not tag Docker image')
# push the image, output to /dev/null
print('-----> Pushing image to private registry')
sys.stdout.flush(), sys.stderr.flush()
p = subprocess.Popen('docker push {target_image}'.format(**locals()), shell=True,
stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w'))
rc = p.wait()
if rc != 0:
raise Exception('Could not push Docker image')
# construct json body for posting to the build hook
body = {}
body['sha'] = sha
body['receive_user'] = user
body['receive_repo'] = app
body['image'] = target_image
# use sha of branch
with open(os.path.join(repo_dir, branch)) as f:
body['sha'] = f.read().strip('\n')
# extract the user-defined Procfile and any default_process_types
procfile_dict = {}
p = subprocess.Popen('tar --to-stdout -xzf {temp_dir}/slug.tgz ./.release'.format(**locals()), shell=True, cwd=temp_dir,
stdout=subprocess.PIPE, stderr=open(os.devnull, 'w'))
rc = p.wait()
if rc == 0:
stdout = p.stdout.read()
default_process_types = yaml.safe_load(stdout).get('default_process_types', {})
procfile_dict.update(default_process_types)
if os.path.exists(procfile):
with open(procfile) as f:
raw_procfile = f.read()
procfile_dict.update(yaml.safe_load(raw_procfile))
if procfile_dict:
body['procfile'] = json.dumps(procfile_dict)
# extract Dockerfile
if os.path.exists(dockerfile):
with open(dockerfile) as f:
body['dockerfile'] = f.read()
# trigger build hook
sys.stdout.write('\n Launching... ')
sys.stdout.flush()
url = "{{ .deis_controller_protocol }}://{{ .deis_controller_host }}:{{ .deis_controller_port }}/api/hooks/build"
headers = {'Content-Type': 'application/json', 'X-Deis-Builder-Auth': '{{ .deis_controller_builderKey }}'}
r = requests.post(url, headers=headers, data=json.dumps(body))
if r.status_code != 200:
raise Exception('Build hook error: {} {}'.format(r.status_code, r.text))
# write out results for git user
response = r.json()
sys.stdout.write('done, v{version}\n\n'.format(**response['release']))
print("-----> {app} deployed to Deis".format(**locals()))
domains = response.get('domains', [])
if domains:
for domain in domains:
print(" http://{domain}".format(**locals()))
else:
print(' No domains found for this application')
print('\n To learn more, use `deis help` or visit http://deis.io\n')
except Exception as e:
print(e.message)
sys.exit(1)
finally:
l = locals()
shutil.rmtree(temp_dir)
if 'container' in l:
subprocess.Popen('docker rm -f {container}'.format(**l), shell=True,
stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w'))
if 'tmp_image' in l and 'target_image' in l:
subprocess.Popen('docker rmi -f {tmp_image} {target_image}'.format(**l), shell=True,
stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w'))