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