chiark / gitweb /
buildserver: replace custom code with python-vagrant
[fdroidserver.git] / makebuildserver
index 439910cf7c403d5210695e3d45fcc35295cbf3a3..4c196ff040e4c995d526b45a74f2f6fe27aada00 100755 (executable)
@@ -1,43 +1,24 @@
 #!/usr/bin/env python3
 
 import os
+import pathlib
 import requests
+import stat
 import sys
 import subprocess
-import time
+import vagrant
 import hashlib
 import yaml
 from clint.textui import progress
 from optparse import OptionParser
 
 
-def vagrant(params, cwd=None, printout=False):
-    """Run vagrant.
-
-    :param: list of parameters to pass to vagrant
-    :cwd: directory to run in, or None for current directory
-    :printout: True to print output in realtime, False to just
-               return it
-    :returns: (ret, out) where ret is the return code, and out
-               is the stdout (and stderr) from vagrant
-    """
-    p = subprocess.Popen(['vagrant'] + params, cwd=cwd,
-                         stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
-                         universal_newlines=True)
-    out = ''
-    if printout:
-        while True:
-            line = p.stdout.readline()
-            if len(line) == 0:
-                break
-            print(line.rstrip())
-            out += line
-        p.wait()
-    else:
-        out = p.communicate()[0]
-    return (p.returncode, out)
+if not os.path.exists('makebuildserver') and not os.path.exists('buildserver'):
+    print('This must be run as ./makebuildserver in fdroidserver.git!')
+    sys.exit(1)
+
 
-boxfile = 'buildserver.box'
+boxfile = os.path.join(os.getcwd(), 'buildserver.box')
 serverdir = 'buildserver'
 
 parser = OptionParser()
@@ -51,9 +32,8 @@ options, args = parser.parse_args()
 cachedir = os.path.join(os.getenv('HOME'), '.cache', 'fdroidserver')
 config = {
     'basebox': 'jessie64',
-    # TODO in py3, convert this to pathlib.Path(absolute_path_string).as_uri()
     'baseboxurl': [
-        'file://' + os.path.join(cachedir, 'jessie64.box'),
+        pathlib.Path(os.path.join(cachedir, 'jessie64.box')).as_uri(),
         'https://f-droid.org/jessie64.box',
     ],
     'debian_mirror': 'http://http.debian.net/debian/',
@@ -63,41 +43,55 @@ config = {
     'cpus': 1,
     'memory': 1024,
     'hwvirtex': 'off',
+    'vm_provider': 'virtualbox',
 }
 
+if os.path.isfile('/usr/bin/systemd-detect-virt'):
+    try:
+        virt = subprocess.check_output('/usr/bin/systemd-detect-virt').strip().decode('utf-8')
+    except subprocess.CalledProcessError as e:
+        virt = 'none'
+    if virt == 'qemu' or virt == 'kvm' or virt == 'bochs':
+        print('Running in a VM guest, defaulting to QEMU/KVM via libvirt')
+        config['vm_provider'] = 'libvirt'
+    elif virt != 'none':
+        print('Running in an unsupported VM guest (' + virt + ')!')
+
 # load config file, if present
 if os.path.exists('makebuildserver.config.py'):
     exec(compile(open('makebuildserver.config.py').read(), 'makebuildserver.config.py', 'exec'), config)
 elif os.path.exists('makebs.config.py'):
     # this is the old name for the config file
     exec(compile(open('makebs.config.py').read(), 'makebs.config.py', 'exec'), config)
-del(config['__builtins__'])  # added by compile/exec
-
-if not os.path.exists('makebuildserver') or not os.path.exists(serverdir):
-    print('This must be run from the correct directory!')
-    sys.exit(1)
+if '__builtins__' in config:
+    del(config['__builtins__'])  # added by compile/exec
 
 if os.path.exists(boxfile):
     os.remove(boxfile)
 
-if options.clean:
-    vagrant(['destroy', '-f'], cwd=serverdir, printout=options.verbose)
-
 # Update cached files.
 cachedir = config['cachedir']
 if not os.path.exists(cachedir):
     os.makedirs(cachedir, 0o755)
 
+if config['vm_provider'] == 'libvirt':
+    tmp = cachedir
+    while tmp != '/':
+        mode = os.stat(tmp).st_mode
+        if not (stat.S_IXUSR & mode and stat.S_IXGRP & mode and stat.S_IXOTH & mode):
+            print('ERROR:', tmp, 'will not be accessible to the VM!  To fix, run:')
+            print('  chmod a+X', tmp)
+            sys.exit(1)
+        tmp = os.path.dirname(tmp)
+
 if config['apt_package_cache']:
     config['aptcachedir'] = cachedir + '/apt/archives'
 
 cachefiles = [
-    ('https://dl.google.com/android/repository/tools_r25.1.7-linux.zip',
-     '3ca053600a86a5a64d5571edfbb1dad27f2bda3bfd2d38e2fe54322610b1ef0b'),
-    ('https://dl.google.com/android/repository/platform-tools_r24-linux.zip',
-     '076368b337d042d163364594dda63b7e778835f636fafb2c8af4d4a604175c32'),
-    ('https://dl.google.com/android/repository/android_m2repository_r33.zip',
-     'be9bb4a27aeefb1c9adb0cade8771f764447c4cbde74426303db2ac6bde1879c'),
+    ('https://dl.google.com/android/repository/tools_r25.2.3-linux.zip',
+     '1b35bcb94e9a686dff6460c8bca903aa0281c6696001067f34ec00093145b560'),
+    ('https://dl.google.com/android/repository/android_m2repository_r47.zip',
+     'a3f91808dce50c1717737de90c18479ed3a78b147e06985247d138e7ab5123d0'),
     ('https://dl.google.com/android/repository/android-1.5_r04-linux.zip',
      '85b6c8f9797e56aa415d3a282428bb640c96b0acb17c11d41621bb2a5302fe64'),
     ('https://dl.google.com/android/repository/android-1.6_r03-linux.zip',
@@ -140,8 +134,10 @@ cachefiles = [
      '45eb581bbe53c9256f34c26b2cea919543c0079140897ac721cf88c0b9f6789e'),
     ('https://dl.google.com/android/repository/platform-23_r03.zip',
      '4b4bcddead3319708275c54c76294707bfaa953d767e34f1a5b599f3edd0076c'),
-    ('https://dl.google.com/android/repository/platform-24_r01.zip',
-     '292e556e9ec84b4134e4126c835e4ac467f6950924fec3684792af0fcf426091'),
+    ('https://dl.google.com/android/repository/platform-24_r02.zip',
+     'f268f5945c6ece7ea95c1c252067280854d2a20da924e22ae4720287df8bdbc9'),
+    ('https://dl.google.com/android/repository/platform-25_r01.zip',
+     'da519dc3e07b8cb879265c94f798262c1f90791dfaa8b745d34883891378438e'),
     ('https://dl.google.com/android/repository/build-tools_r17-linux.zip',
      '4c8444972343a19045236f6924bd7f12046287c70dace96ab88b2159c8ec0e74'),
     ('https://dl.google.com/android/repository/build-tools_r18.0.1-linux.zip',
@@ -188,6 +184,18 @@ cachefiles = [
      'd961663d4a9e128841751c0156548a347c882c081c83942e53788d8949bf34e1'),
     ('https://dl.google.com/android/repository/build-tools_r24-linux.zip',
      'b4871f357224c5f660fd2bbee04d8c7d1c187eeddfd9702cc84503529e3b3724'),
+    ('https://dl.google.com/android/repository/build-tools_r24.0.1-linux.zip',
+     'a38ac637db357a31e33e38248399cb0edcc15040dca041370da38b6daf50c84d'),
+    ('https://dl.google.com/android/repository/build-tools_r24.0.2-linux.zip',
+     '924e29b8a189afbd119d44eae450fc0c9f197ed6f835df223931e45007987d95'),
+    ('https://dl.google.com/android/repository/build-tools_r24.0.3-linux.zip',
+     'f2c02eb1d7e41ce314b5dac50440e7595380c4dd45b41ea1d7b0f86e49516927'),
+    ('https://dl.google.com/android/repository/build-tools_r25-linux.zip',
+     '74eb6931fd7a56859bd8e35d8d73ca8fe7ba6bfd4b7ffe560fe58b7354f2e3aa'),
+    ('https://dl.google.com/android/repository/build-tools_r25.0.1-linux.zip',
+     '671b4e00f5b986c7355507c7024b725a4b4cadf11ca61fa5b1334ec6ea57d94f'),
+    ('https://dl.google.com/android/repository/build-tools_r25.0.2-linux.zip',
+     '1d7ac9b6def16fb0254ec23c135c02dd9f6908073352a20315a017e4b2a904b0'),
     # the binaries that Google uses are here:
     # https://android.googlesource.com/platform/tools/external/gradle/+/studio-1.5/
     ('https://services.gradle.org/distributions/gradle-1.4-bin.zip',
@@ -236,16 +244,40 @@ cachefiles = [
      '0f665ec6a5a67865faf7ba0d825afb19c26705ea0597cec80dd191b0f2cbb664'),
     ('https://services.gradle.org/distributions/gradle-2.14-bin.zip',
      '993b4f33b652c689e9721917d8e021cab6bbd3eae81b39ab2fd46fdb19a928d5'),
-    ('https://pypi.python.org/packages/source/K/Kivy/Kivy-1.7.2.tar.gz',
-     '0485e2ef97b5086df886eb01f8303cb542183d2d71a159466f99ad6c8a1d03f1'),
+    ('https://services.gradle.org/distributions/gradle-2.14.1-bin.zip',
+     'cfc61eda71f2d12a572822644ce13d2919407595c2aec3e3566d2aab6f97ef39'),
+    ('https://services.gradle.org/distributions/gradle-3.0-bin.zip',
+     '39c906941a474444afbddc38144ed44166825acb0a57b0551dddb04bbf157f80'),
+    ('https://services.gradle.org/distributions/gradle-3.1-bin.zip',
+     'c7de3442432253525902f7e8d7eac8b5fd6ce1623f96d76916af6d0e383010fc'),
+    ('https://services.gradle.org/distributions/gradle-3.2-bin.zip',
+     '5321b36837226dc0377047a328f12010f42c7bf88ee4a3b1cee0c11040082935'),
+    ('https://services.gradle.org/distributions/gradle-3.2.1-bin.zip',
+     '9843a3654d3e57dce54db06d05f18b664b95c22bf90c6becccb61fc63ce60689'),
+    ('https://services.gradle.org/distributions/gradle-3.3-bin.zip',
+     'c58650c278d8cf0696cab65108ae3c8d95eea9c1938e0eb8b997095d5ca9a292'),
+    ('https://services.gradle.org/distributions/gradle-3.4-bin.zip',
+     '72d0cd4dcdd5e3be165eb7cd7bbd25cf8968baf400323d9ab1bba622c3f72205'),
+    ('https://services.gradle.org/distributions/gradle-3.4.1-bin.zip',
+     'db1db193d479cc1202be843f17e4526660cfb0b21b57d62f3a87f88c878af9b2'),
+    ('https://services.gradle.org/distributions/gradle-3.5-bin.zip',
+     '0b7450798c190ff76b9f9a3d02e18b33d94553f708ebc08ebe09bdf99111d110'),
     ('https://dl.google.com/android/ndk/android-ndk-r10e-linux-x86_64.bin',
      '102d6723f67ff1384330d12c45854315d6452d6510286f4e5891e00a5a8f1d5a'),
     ('https://dl.google.com/android/ndk/android-ndk-r9b-linux-x86_64.tar.bz2',
      '8956e9efeea95f49425ded8bb697013b66e162b064b0f66b5c75628f76e0f532'),
     ('https://dl.google.com/android/ndk/android-ndk-r9b-linux-x86_64-legacy-toolchains.tar.bz2',
      'de93a394f7c8f3436db44568648f87738a8d09801a52f459dcad3fc047e045a1'),
+    ('https://dl.google.com/android/repository/android-ndk-r11c-linux-x86_64.zip',
+     'ba85dbe4d370e4de567222f73a3e034d85fc3011b3cbd90697f3e8dcace3ad94'),
     ('https://dl.google.com/android/repository/android-ndk-r12b-linux-x86_64.zip',
      'eafae2d614e5475a3bcfd7c5f201db5b963cc1290ee3e8ae791ff0c66757781e'),
+    ('https://dl.google.com/android/repository/android-ndk-r13b-linux-x86_64.zip',
+     '3524d7f8fca6dc0d8e7073a7ab7f76888780a22841a6641927123146c3ffd29c'),
+    ('https://dl.google.com/android/repository/android-ndk-r14-linux-x86_64.zip',
+     '3e622c2c9943964ea44cd56317d0769ed4c811bb4b40dc45b1f6965e4db9aa44'),
+    ('https://download.qt.io/official_releases/qt/5.7/5.7.0/qt-opensource-linux-x64-android-5.7.0.run',
+     'f7e55b7970e59bdaabb88cb7afc12e9061e933992bda2f076f52600358644586'),
 ]
 
 
@@ -259,6 +291,7 @@ def sha256_for_file(path):
             s.update(data)
         return s.hexdigest()
 
+
 for srcurl, shasum in cachefiles:
     filename = os.path.basename(srcurl)
     local_filename = os.path.join(cachedir, filename)
@@ -311,6 +344,10 @@ for srcurl, shasum in cachefiles:
         os.remove(local_filename)
         sys.exit(1)
 
+local_qt_filename = os.path.join(cachedir, 'qt-opensource-linux-x64-android-5.7.0.run')
+print("Setting executable bit for " + local_qt_filename)
+os.chmod(local_qt_filename, 0o755)
+
 # use VirtualBox software virtualization if hardware is not available,
 # like if this is being run in kvm or some other VM platform, like
 # http://jenkins.debian.net, the values are 'on' or 'off'
@@ -324,17 +361,28 @@ elif os.path.exists('/proc/cpuinfo'):
     if 'vmx' in contents or 'svm' in contents:
         config['hwvirtex'] = 'on'
 
+logfilename = os.path.join(serverdir, 'up.log')
+log_cm = vagrant.make_file_cm(logfilename)
+v = vagrant.Vagrant(root=serverdir, out_cm=log_cm, err_cm=log_cm)
+
+if options.clean:
+    v.destroy()
+    if config['vm_provider'] == 'libvirt':
+        subprocess.call(['virsh', 'undefine', 'buildserver_default'])
+        subprocess.call(['virsh', 'vol-delete', '/var/lib/libvirt/images/buildserver_default.img'])
+
 # Check against the existing Vagrantfile.yaml, and if they differ, we
 # need to create a new box:
 vf = os.path.join(serverdir, 'Vagrantfile.yaml')
 writevf = True
 if os.path.exists(vf):
-    vagrant(['halt'], serverdir)
+    print('Halting', serverdir)
+    v.halt()
     with open(vf, 'r', encoding='utf-8') as f:
         oldconfig = yaml.load(f)
     if config != oldconfig:
         print("Server configuration has changed, rebuild from scratch is required")
-        vagrant(['destroy', '-f'], serverdir)
+        v.destroy()
     else:
         print("Re-provisioning existing server")
         writevf = False
@@ -344,13 +392,31 @@ if writevf:
     with open(vf, 'w', encoding='utf-8') as f:
         yaml.dump(config, f)
 
+if config['vm_provider'] == 'libvirt':
+    found_basebox = False
+    needs_mutate = False
+    for box in v.box_list():
+        if box.name == config['basebox']:
+            found_basebox = True
+            if box.provider != 'libvirt':
+                needs_mutate = True
+            continue
+    if not found_basebox:
+        if isinstance(config['baseboxurl'], str):
+            baseboxurl = config['baseboxurl']
+        else:
+            baseboxurl = config['baseboxurl'][0]
+        print('Adding', config['basebox'], 'from', baseboxurl)
+        v.box_add(config['basebox'], baseboxurl)
+        needs_mutate = True
+    if needs_mutate:
+        print('Converting', config['basebox'], 'to libvirt format')
+        v._call_vagrant_command(['mutate', config['basebox'], 'libvirt'])
+        print('Removing virtualbox format copy of', config['basebox'])
+        v.box_remove(config['basebox'], 'virtualbox')
+
 print("Configuring build server VM")
-returncode, out = vagrant(['up', '--provision'], serverdir, printout=True)
-with open(os.path.join(serverdir, 'up.log'), 'w') as log:
-    log.write(out)
-if returncode != 0:
-    print("Failed to configure server")
-    sys.exit(1)
+v.up(provision=True)
 
 print("Writing buildserver ID")
 p = subprocess.Popen(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE,
@@ -363,28 +429,12 @@ subprocess.call(
     cwd=serverdir)
 
 print("Stopping build server VM")
-vagrant(['halt'], serverdir)
-
-print("Waiting for build server VM to be finished")
-ready = False
-while not ready:
-    time.sleep(2)
-    returncode, out = vagrant(['status'], serverdir)
-    if returncode != 0:
-        print("Error while checking status")
-        sys.exit(1)
-    for line in out.splitlines():
-        if line.startswith("default"):
-            if line.find("poweroff") != -1:
-                ready = True
-            else:
-                print("Status: " + line)
+v.halt()
 
 print("Packaging")
-vagrant(['package', '--output', os.path.join('..', boxfile)], serverdir,
-        printout=options.verbose)
+v.package(output=boxfile)
+
 print("Adding box")
-vagrant(['box', 'add', 'buildserver', boxfile, '-f'],
-        printout=options.verbose)
+v.box_add('buildserver', boxfile, force=True)
 
 os.remove(boxfile)