Merge branch 'LOffice' into 'master'
[f-droid:fdroidserver.git] / makebuildserver
1 #!/usr/bin/env python2
2
3 import os
4 import sys
5 import subprocess
6 import time
7 import hashlib
8 from optparse import OptionParser
9
10
11 def vagrant(params, cwd=None, printout=False):
12     """Run vagrant.
13
14     :param: list of parameters to pass to vagrant
15     :cwd: directory to run in, or None for current directory
16     :printout: True to print output in realtime, False to just
17                return it
18     :returns: (ret, out) where ret is the return code, and out
19                is the stdout (and stderr) from vagrant
20     """
21     p = subprocess.Popen(['vagrant'] + params, cwd=cwd,
22                          stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
23     out = ''
24     if printout:
25         while True:
26             line = p.stdout.readline()
27             if len(line) == 0:
28                 break
29             print line,
30             out += line
31         p.wait()
32     else:
33         out = p.communicate()[0]
34     return (p.returncode, out)
35
36 boxfile = 'buildserver.box'
37 serverdir = 'buildserver'
38
39 parser = OptionParser()
40 parser.add_option("-v", "--verbose", action="store_true", default=False,
41                   help="Spew out even more information than normal")
42 parser.add_option("-c", "--clean", action="store_true", default=False,
43                   help="Build from scratch, rather than attempting to update the existing server")
44 options, args = parser.parse_args()
45
46 config = {}
47 execfile('makebs.config.py', config)
48
49 if not os.path.exists('makebuildserver') or not os.path.exists(serverdir):
50     print 'This must be run from the correct directory!'
51     sys.exit(1)
52
53 if os.path.exists(boxfile):
54     os.remove(boxfile)
55
56 if options.clean:
57     vagrant(['destroy', '-f'], cwd=serverdir, printout=options.verbose)
58
59 # Update cached files.
60 cachedir = os.path.join('buildserver', 'cache')
61 if not os.path.exists(cachedir):
62     os.mkdir(cachedir)
63
64 cachefiles = [
65     ('android-sdk_r24.0.1-linux.tgz',
66      'https://dl.google.com/android/android-sdk_r24.0.1-linux.tgz',
67      'bb3754524a8f6700c2898617c9d8836a987a8aa43d0e922885cd7a98ca79b281'),
68     ('gradle-1.4-bin.zip',
69      'https://services.gradle.org/distributions/gradle-1.4-bin.zip',
70      'cd99e85fbcd0ae8b99e81c9992a2f10cceb7b5f009c3720ef3a0078f4f92e94e'),
71     ('gradle-1.6-bin.zip',
72      'https://services.gradle.org/distributions/gradle-1.6-bin.zip',
73      'de3e89d2113923dcc2e0def62d69be0947ceac910abd38b75ec333230183fac4'),
74     ('gradle-1.7-bin.zip',
75      'https://services.gradle.org/distributions/gradle-1.7-bin.zip',
76      '360c97d51621b5a1ecf66748c718594e5f790ae4fbc1499543e0c006033c9d30'),
77     ('gradle-1.8-bin.zip',
78      'https://services.gradle.org/distributions/gradle-1.8-bin.zip',
79      'a342bbfa15fd18e2482287da4959588f45a41b60910970a16e6d97959aea5703'),
80     ('gradle-1.9-bin.zip',
81      'https://services.gradle.org/distributions/gradle-1.9-bin.zip',
82      '097ddc2bcbc9da2bb08cbf6bf8079585e35ad088bafd42e8716bc96405db98e9'),
83     ('gradle-1.10-bin.zip',
84      'https://services.gradle.org/distributions/gradle-1.10-bin.zip',
85      '6e6db4fc595f27ceda059d23693b6f6848583950606112b37dfd0e97a0a0a4fe'),
86     ('gradle-1.11-bin.zip',
87      'https://services.gradle.org/distributions/gradle-1.11-bin.zip',
88      '07e235df824964f0e19e73ea2327ce345c44bcd06d44a0123d29ab287fc34091'),
89     ('gradle-1.12-bin.zip',
90      'https://services.gradle.org/distributions/gradle-1.12-bin.zip',
91      '8734b13a401f4311ee418173ed6ca8662d2b0a535be8ff2a43ecb1c13cd406ea'),
92     ('gradle-2.1-bin.zip',
93      'https://services.gradle.org/distributions/gradle-2.1-bin.zip',
94      '3eee4f9ea2ab0221b89f8e4747a96d4554d00ae46d8d633f11cfda60988bf878'),
95     ('gradle-2.2.1-bin.zip',
96      'https://services.gradle.org/distributions/gradle-2.2.1-bin.zip',
97      '420aa50738299327b611c10b8304b749e8d3a579407ee9e755b15921d95ff418'),
98     ('Kivy-1.7.2.tar.gz',
99      'https://pypi.python.org/packages/source/K/Kivy/Kivy-1.7.2.tar.gz',
100      '0485e2ef97b5086df886eb01f8303cb542183d2d71a159466f99ad6c8a1d03f1'),
101 ]
102
103 if config['arch64']:
104     cachefiles.extend([
105         ('android-ndk-r10d-linux-x86_64.bin',
106          'https://dl.google.com/android/ndk/android-ndk-r10d-linux-x86_64.bin',
107          '812949f9299afd4b91890863054dc42f6547b6d485211d5f0faca9f286685df6'),
108         ('android-ndk-r9b-linux-x86_64.tar.bz2',
109          'https://dl.google.com/android/ndk/android-ndk-r9b-linux-x86_64.tar.bz2',
110          '8956e9efeea95f49425ded8bb697013b66e162b064b0f66b5c75628f76e0f532'),
111         ('android-ndk-r9b-linux-x86_64-legacy-toolchains.tar.bz2',
112          'https://dl.google.com/android/ndk/android-ndk-r9b-linux-x86_64-legacy-toolchains.tar.bz2',
113          'de93a394f7c8f3436db44568648f87738a8d09801a52f459dcad3fc047e045a1')])
114 else:
115     cachefiles.extend([
116         ('android-ndk-r10d-linux-x86.bin',
117          'https://dl.google.com/android/ndk/android-ndk-r10d-linux-x86.bin',
118          'c0d07e5ce2fff13b5eb456c10e99527184c9139e798cb7fd1adfadafa65cb696'),
119         ('android-ndk-r9b-linux-x86.tar.bz2',
120          'https://dl.google.com/android/ndk/android-ndk-r9b-linux-x86.tar.bz2',
121          '748104b829dd12afb2fdb3044634963abb24cdb0aad3b26030abe2e9e65bfc81'),
122         ('android-ndk-r9b-linux-x86-legacy-toolchains.tar.bz2',
123          'https://dl.google.com/android/ndk/android-ndk-r9b-linux-x86-legacy-toolchains.tar.bz2',
124          '606aadf815ae28cc7b0154996247c70d609f111b14e44bcbcd6cad4c87fefb6f')])
125 wanted = []
126
127
128 def sha256_for_file(path):
129     with open(path, 'r') as f:
130         s = hashlib.sha256()
131         while True:
132             data = f.read(4096)
133             if not data:
134                 break
135             s.update(data)
136         return s.hexdigest()
137
138 for f, src, shasum in cachefiles:
139     relpath = os.path.join(cachedir, f)
140     if not os.path.exists(relpath):
141         print "Downloading " + f + " to cache"
142         if subprocess.call(['wget', src], cwd=cachedir) != 0:
143             print "...download of " + f + " failed."
144             sys.exit(1)
145     if shasum:
146         v = sha256_for_file(relpath)
147         if v != shasum:
148             print "Invalid shasum of '" + v + "' detected for " + f
149             sys.exit(1)
150         else:
151             print "...shasum verified for " + f
152
153     wanted.append(f)
154
155
156 # Generate an appropriate Vagrantfile for the buildserver, based on our
157 # settings...
158 vagrantfile = """
159 Vagrant.configure("2") do |config|
160
161   config.vm.box = "{0}"
162   config.vm.box_url = "{1}"
163
164   config.vm.provider "virtualbox" do |v|
165     v.customize ["modifyvm", :id, "--memory", "{2}"]
166     v.customize ["modifyvm", :id, "--cpus", "{3}"]
167   end
168
169   config.vm.provision :shell, :path => "fixpaths.sh"
170 """.format(config['basebox'],
171            config['baseboxurl'],
172            config['memory'],
173            config['cpus'] or 1)
174 if 'aptproxy' in config and config['aptproxy']:
175     vagrantfile += """
176   config.vm.provision :shell, :inline => 'sudo echo "Acquire::http {{ Proxy \\"{0}\\"; }};" > /etc/apt/apt.conf.d/02proxy && sudo apt-get update'
177 """.format(config['aptproxy'])
178 vagrantfile += """
179   config.vm.provision :chef_solo do |chef|
180     chef.cookbooks_path = "cookbooks"
181     chef.log_level = :debug
182     chef.json = {
183       :settings => {
184         :sdk_loc => "/home/vagrant/android-sdk",
185         :ndk_loc => "/home/vagrant/android-ndk",
186         :user => "vagrant"
187       }
188     }
189     chef.add_recipe "fdroidbuild-general"
190     chef.add_recipe "android-sdk"
191     chef.add_recipe "android-ndk"
192     chef.add_recipe "gradle"
193     chef.add_recipe "kivy"
194   end
195 end
196 """
197
198 # Check against the existing Vagrantfile, and if they differ, we need to
199 # create a new box:
200 vf = os.path.join(serverdir, 'Vagrantfile')
201 writevf = True
202 if os.path.exists(vf):
203     vagrant(['halt'], serverdir)
204     with open(vf, 'r') as f:
205         oldvf = f.read()
206     if oldvf != vagrantfile:
207         print "Server configuration has changed, rebuild from scratch is required"
208         vagrant(['destroy', '-f'], serverdir)
209     else:
210         print "Re-provisioning existing server"
211         writevf = False
212 else:
213     print "No existing server - building from scratch"
214 if writevf:
215     with open(vf, 'w') as f:
216         f.write(vagrantfile)
217
218
219 print "Configuring build server VM"
220 returncode, out = vagrant(['up'], serverdir, printout=True)
221 with open(os.path.join(serverdir, 'up.log'), 'w') as log:
222     log.write(out)
223 if returncode != 0:
224     print "Failed to configure server"
225     sys.exit(1)
226
227 print "Writing buildserver ID"
228 p = subprocess.Popen(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE)
229 buildserverid = p.communicate()[0].strip()
230 print "...ID is " + buildserverid
231 subprocess.call(
232     ['vagrant', 'ssh', '-c', 'sh -c "echo {0} >/home/vagrant/buildserverid"'
233         .format(buildserverid)],
234     cwd=serverdir)
235
236 print "Stopping build server VM"
237 vagrant(['halt'], serverdir)
238
239 print "Waiting for build server VM to be finished"
240 ready = False
241 while not ready:
242     time.sleep(2)
243     returncode, out = vagrant(['status'], serverdir)
244     if returncode != 0:
245         print "Error while checking status"
246         sys.exit(1)
247     for line in out.splitlines():
248         if line.startswith("default"):
249             if line.find("poweroff") != -1:
250                 ready = True
251             else:
252                 print "Status: " + line
253
254 print "Packaging"
255 vagrant(['package', '--output', os.path.join('..', boxfile)], serverdir,
256         printout=options.verbose)
257 print "Adding box"
258 vagrant(['box', 'add', 'buildserver', boxfile, '-f'],
259         printout=options.verbose)
260
261 os.remove(boxfile)