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
|
#! /usr/bin/python -u
# Copyright 2015 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""A script that builds a snap."""
from __future__ import print_function
__metaclass__ = type
import base64
from optparse import OptionParser
import os
import subprocess
import sys
import traceback
import urllib2
from urlparse import urlparse
from lpbuildd.util import (
set_personality,
shell_escape,
)
RETCODE_SUCCESS = 0
RETCODE_FAILURE_INSTALL = 200
RETCODE_FAILURE_BUILD = 201
def get_build_path(build_id, *extra):
"""Generate a path within the build directory.
:param build_id: the build id to use.
:param extra: the extra path segments within the build directory.
:return: the generated path.
"""
return os.path.join(os.environ["HOME"], "build-" + build_id, *extra)
class SnapBuilder:
"""Builds a snap."""
def __init__(self, options, name):
self.options = options
self.name = name
self.chroot_path = get_build_path(
self.options.build_id, 'chroot-autobuild')
# Set to False for local testing if your chroot doesn't have an
# appropriate certificate for your codehosting system.
self.ssl_verify = True
def chroot(self, args, echo=False):
"""Run a command in the chroot.
:param args: the command and arguments to run.
:param echo: if True, print the command before executing it.
"""
args = set_personality(self.options.arch, args)
if echo:
print(
"Running in chroot: %s" % ' '.join(
"'%s'" % arg for arg in args))
sys.stdout.flush()
subprocess.check_call([
"/usr/bin/sudo", "/usr/sbin/chroot", self.chroot_path] + args)
def run_build_command(self, args, path="/build", env=None, echo=False):
"""Run a build command in the chroot.
This is unpleasant because we need to run it in /build under sudo
chroot, and there's no way to do this without either a helper
program in the chroot or unpleasant quoting. We go for the
unpleasant quoting.
:param args: the command and arguments to run.
:param path: the working directory to use in the chroot.
:param env: dictionary of additional environment variables to set.
:param echo: if True, print the command before executing it.
"""
args = [shell_escape(arg) for arg in args]
path = shell_escape(path)
full_env = {
"LANG": "C.UTF-8",
}
if env:
full_env.update(env)
args = ["env"] + [
"%s=%s" % (key, shell_escape(value))
for key, value in full_env.items()] + args
command = "cd %s && %s" % (path, " ".join(args))
self.chroot(["/bin/sh", "-c", command], echo=echo)
def install(self):
print("Running install phase...")
deps = ["snapcraft"]
if self.options.branch is not None:
deps.append("bzr")
else:
deps.append("git")
self.chroot(["apt-get", "-y", "install"] + deps)
def repo(self):
"""Collect git or bzr branch."""
print("Running repo phase...")
env = {}
if self.options.proxy_url:
env["http_proxy"] = self.options.proxy_url
env["https_proxy"] = self.options.proxy_url
if self.options.branch is not None:
self.run_build_command(['ls', '/build'])
cmd = ["bzr", "branch", self.options.branch, self.name]
if not self.ssl_verify:
cmd.insert(1, "-Ossl.cert_reqs=none")
else:
assert self.options.git_repository is not None
cmd = ["git", "clone"]
if self.options.git_path is not None:
cmd.extend(["-b", self.options.git_path])
cmd.extend([self.options.git_repository, self.name])
if not self.ssl_verify:
env["GIT_SSL_NO_VERIFY"] = "1"
self.run_build_command(cmd, env=env)
def pull(self):
"""Run pull phase."""
print("Running pull phase...")
env = {
"SNAPCRAFT_LOCAL_SOURCES": "1",
"SNAPCRAFT_SETUP_CORE": "1",
}
if self.options.proxy_url:
env["http_proxy"] = self.options.proxy_url
env["https_proxy"] = self.options.proxy_url
self.run_build_command(
["snapcraft", "pull"],
path=os.path.join("/build", self.name),
env=env)
def build(self):
"""Run all build, stage and snap phases."""
print("Running build phase...")
env = {}
if self.options.proxy_url:
env["http_proxy"] = self.options.proxy_url
env["https_proxy"] = self.options.proxy_url
self.run_build_command(
["snapcraft"], path=os.path.join("/build", self.name), env=env)
def revoke_token(self):
"""Revoke builder proxy token."""
print("Revoking proxy token...")
url = urlparse(self.options.proxy_url)
auth = '{}:{}'.format(url.username, url.password)
headers = {
'Authorization': 'Basic {}'.format(base64.b64encode(auth))
}
req = urllib2.Request(self.options.revocation_endpoint, None, headers)
req.get_method = lambda: 'DELETE'
try:
urllib2.urlopen(req)
except (urllib2.HTTPError, urllib2.URLError) as e:
print('Unable to revoke token for %s: %s' % (url.username, e))
def main():
parser = OptionParser("%prog [options] NAME")
parser.add_option("--build-id", help="build identifier")
parser.add_option(
"--arch", metavar="ARCH", help="build for architecture ARCH")
parser.add_option(
"--branch", metavar="BRANCH", help="build from this Bazaar branch")
parser.add_option(
"--git-repository", metavar="REPOSITORY",
help="build from this Git repository")
parser.add_option(
"--git-path", metavar="REF-PATH",
help="build from this ref path in REPOSITORY")
parser.add_option("--proxy-url", help="builder proxy url")
parser.add_option("--revocation-endpoint",
help="builder proxy token revocation endpoint")
options, args = parser.parse_args()
if options.git_repository is None and options.git_path is not None:
parser.error("--git-path requires --git-repository")
if (options.branch is None) == (options.git_repository is None):
parser.error(
"must provide exactly one of --branch and --git-repository")
if len(args) != 1:
parser.error(
"must provide a package name and no other positional arguments")
[name] = args
builder = SnapBuilder(options, name)
try:
builder.install()
except Exception:
traceback.print_exc()
return RETCODE_FAILURE_INSTALL
try:
builder.repo()
builder.pull()
builder.build()
except Exception:
traceback.print_exc()
return RETCODE_FAILURE_BUILD
finally:
if options.revocation_endpoint is not None:
builder.revoke_token()
return RETCODE_SUCCESS
if __name__ == "__main__":
sys.exit(main())
|