Skip to content
Snippets Groups Projects
run.py 65.1 KiB
Newer Older
Simon McVittie's avatar
Simon McVittie committed
#!/usr/bin/python3

# flatdeb — build Flatpak runtimes from Debian packages
#
# Copyright © 2016-2017 Simon McVittie
# Copyright © 2017 Collabora Ltd.
#
# Partially derived from vectis, copyright © 2015-2017 Simon McVittie
#
# SPDX-License-Identifier: MIT
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
Create Flatpak runtimes from Debian packages.
"""

import argparse
import json
Simon McVittie's avatar
Simon McVittie committed
import logging
Simon McVittie's avatar
Simon McVittie committed
import os
import re
import subprocess
Simon McVittie's avatar
Simon McVittie committed
import sys
import urllib.parse
Simon McVittie's avatar
Simon McVittie committed
from contextlib import ExitStack, suppress
from tempfile import TemporaryDirectory

import yaml
from gi.repository import GLib

from flatdeb.worker import HostWorker, NspawnWorker, SudoWorker
Simon McVittie's avatar
Simon McVittie committed
logger = logging.getLogger('flatdeb')


# TODO: When flatdeb is packaged/released, replace this with the released
# version in packages/releases
VERSION = None

if VERSION is None:
    _git_version = subprocess.check_output([
        'sh', '-c',
        'cd "$(dirname "$1")" && '
        'git describe '
        '--always '
        '--dirty '
        '--first-parent '
        '--long '
        '--tags '
        '--match="v[0-9]*" '
        '2>/dev/null || :',
        'sh',
        sys.argv[0],
    ])[1:].decode('utf-8').strip()
    VERSION = _git_version

_CLEAN_UP_BASE = os.path.join(
    os.path.dirname(__file__), 'flatdeb', 'clean-up-base')
_DISABLE_SERVICES = os.path.join(
    os.path.dirname(__file__), 'flatdeb', 'disable-services')
_USRMERGE = os.path.join(
    os.path.dirname(__file__), 'flatdeb', 'usrmerge')
Simon McVittie's avatar
Simon McVittie committed
class Builder:

    """
    Main object
    """

    __multiarch_tuple_cache = {}

Simon McVittie's avatar
Simon McVittie committed
    def __init__(self):
        #: The Debian suite to use
        self.apt_suite = 'stretch'
        #: The Flatpak branch to use for the runtime, or None for apt_suite
        self.runtime_branch = None
        #: The Flatpak branch to use for the app
        self.app_branch = None
Simon McVittie's avatar
Simon McVittie committed
        #: The freedesktop.org cache directory
        self.xdg_cache_dir = os.getenv(
            'XDG_CACHE_HOME', os.path.expanduser('~/.cache'))
Simon McVittie's avatar
Simon McVittie committed
        #: Where to write output
        self.build_area = os.path.join(
            self.xdg_cache_dir, 'flatdeb',
        )
        self.repo = os.path.join(self.build_area, 'repo')

        self.__dpkg_archs = []
Simon McVittie's avatar
Simon McVittie committed
        self.flatpak_arch = None

        self.__primary_dpkg_arch_matches_cache = {}
Simon McVittie's avatar
Simon McVittie committed
        self.suite_details = {}
        self.runtime_details = {}
        self.root_worker = None
        self.worker = None
        self.host_worker = HostWorker()
        self.ostree_mode = 'archive-z2'
        self.export_bundles = False
        self.strip_source_version_suffix = None
        self.platform_packages = []
Simon McVittie's avatar
Simon McVittie committed

Simon McVittie's avatar
Simon McVittie committed
        self.logger = logger.getChild('Builder')

Simon McVittie's avatar
Simon McVittie committed
    @staticmethod
    def get_flatpak_arch(arch=None):
        """
        Return the Flatpak architecture name corresponding to uname
        result arch.

        If arch is None, return the Flatpak architecture name
        corresponding to the machine where this script is running.
        """

        if arch is None:
            arch = os.uname()[4]

        if re.match(r'^i.86$', arch):
            return 'i386'
        elif re.match(r'^arm.*', arch):
            if arch.endswith('b'):
                return 'armeb'
            else:
                return 'arm'
        elif arch in ('mips', 'mips64'):
            import struct
            if struct.pack('i', 1).startswith(b'\x01'):
                return arch + 'el'

        return arch

Simon McVittie's avatar
Simon McVittie committed
    @staticmethod
    def other_multiarch(arch):
        """
        Return the other architecture that accompanies the given Debian
        architecture in a multiarch setup, or None.
        """

        if arch == 'amd64':
            return 'i386'
        elif arch == 'arm64':
            return 'armhf'
        else:
            return None

    @staticmethod
    def multiarch_tuple(arch):
        """
        Return the multiarch tuple for the given dpkg architecture name.
        """

        if arch not in Builder.__multiarch_tuple_cache:
            Builder.__multiarch_tuple_cache[arch] = subprocess.check_output([
                'dpkg-architecture',
                '-qDEB_HOST_MULTIARCH',
                '-a{}'.format(arch),
            ]).decode('utf-8').strip()

        return Builder.__multiarch_tuple_cache[arch]

Simon McVittie's avatar
Simon McVittie committed
    @staticmethod
    def dpkg_to_flatpak_arch(arch):
        """
        Return the Flatpak architecture name corresponding to the given
        dpkg architecture name.
        """

        if arch == 'amd64':
            return 'x86_64'
        elif arch == 'arm64':
            return 'aarch64'
        elif arch in ('armel', 'armhf'):
            return 'arm'
        elif arch == 'powerpc':
            return 'ppc'
        elif arch == 'powerpc64':
            return 'ppc64'
        elif arch == 'powerpcel':
            return 'ppcle'
        elif arch == 'ppc64el':
            return 'ppc64le'

        return arch

    @property
    def primary_dpkg_arch(self):
Simon McVittie's avatar
Simon McVittie committed
        """
        The Debian architecture we are building a runtime for, such as
        i386 or amd64.
        """
        return self.__dpkg_archs[0]
Simon McVittie's avatar
Simon McVittie committed

    @property
    def dpkg_archs(self):
        """
        The Debian architectures we support via multiarch, such as
        ['amd64', 'i386'].
        """
        return self.__dpkg_archs
Simon McVittie's avatar
Simon McVittie committed

    @dpkg_archs.setter
    def dpkg_archs(self, value):
        self.__primary_dpkg_arch_matches_cache = {}
        self.__dpkg_archs = value

    def primary_dpkg_arch_matches(self, arch_spec):
Simon McVittie's avatar
Simon McVittie committed
        """
        Return True if arch_spec matches primary_dpkg_arch (or
        equivalently, if primary_dpkg_arch is one of the architectures
Simon McVittie's avatar
Simon McVittie committed
        described by arch_spec). For example, any-amd64 matches amd64
        but not i386.
        """
        if arch_spec not in self.__primary_dpkg_arch_matches_cache:
Simon McVittie's avatar
Simon McVittie committed
            exit_code = self.worker.call(
                ['dpkg-architecture', '--host-arch', self.primary_dpkg_arch,
Simon McVittie's avatar
Simon McVittie committed
                 '--is', arch_spec])
            self.__primary_dpkg_arch_matches_cache[arch_spec] = (exit_code == 0)
Simon McVittie's avatar
Simon McVittie committed

        return self.__primary_dpkg_arch_matches_cache[arch_spec]
Simon McVittie's avatar
Simon McVittie committed

    def run_command_line(self):
        """
        Run appropriate commands for the command-line arguments
        """
        parser = argparse.ArgumentParser(
            description='Build Flatpak runtimes',
        )
        parser.add_argument(
            '--in-fakemachine', action='store_true', default=False)
        parser.add_argument('--chdir', default=None)
        parser.add_argument(
            '--ostree-mode', default=self.ostree_mode,
        )
        parser.add_argument(
            '--export-bundles', action='store_true', default=False,
        )
Simon McVittie's avatar
Simon McVittie committed
        parser.add_argument('--build-area', default=self.build_area)
        parser.add_argument('--repo', default=self.repo)
        parser.add_argument('--suite', '-d', default=self.apt_suite)
        parser.add_argument('--architecture', '--arch', '-a')
        parser.add_argument('--runtime-branch', default=self.runtime_branch)
Simon McVittie's avatar
Simon McVittie committed
        subparsers = parser.add_subparsers(dest='command', metavar='command')

        subparser = subparsers.add_parser(
            'base',
            help='Build a fresh base tarball',
        )

        subparser = subparsers.add_parser(
            'runtimes',
            help='Build runtimes',
        )
        subparser.add_argument('yaml_file')
Simon McVittie's avatar
Simon McVittie committed

        subparser = subparsers.add_parser(
            'app',
            help='Build an app',
        )
        subparser.add_argument('--app-branch', default=self.app_branch)
        subparser.add_argument('yaml_manifest')
Simon McVittie's avatar
Simon McVittie committed

        subparser = subparsers.add_parser(
            'print-flatpak-architecture',
            help='Print the Flatpak architecture',
        )

        args = parser.parse_args()

        if args.in_fakemachine:
            # Avoid weird terminal settings inherited from the firmware
            # and boot loader of the VM
            subprocess.check_call(['env', 'TERM=xterm', 'reset'])

        if args.chdir is not None:
            os.chdir(args.chdir)

Simon McVittie's avatar
Simon McVittie committed
        self.build_area = args.build_area
        self.apt_suite = args.suite
        self.runtime_branch = args.runtime_branch
Simon McVittie's avatar
Simon McVittie committed
        self.repo = args.repo
        self.export_bundles = args.export_bundles
        self.ostree_mode = args.ostree_mode
        self.worker = HostWorker()
Simon McVittie's avatar
Simon McVittie committed

        if os.geteuid() == 0 and os.getuid() == 0:
            self.root_worker = self.worker
Simon McVittie's avatar
Simon McVittie committed

        if args.architecture is None:
            self.dpkg_archs = [
                self.worker.check_output(
                    ['dpkg-architecture', '-q', 'DEB_HOST_ARCH'],
                ).decode('utf-8').rstrip('\n')
            ]
Simon McVittie's avatar
Simon McVittie committed
        else:
            self.dpkg_archs = args.architecture.split(',')
Simon McVittie's avatar
Simon McVittie committed

        self.flatpak_arch = self.dpkg_to_flatpak_arch(self.primary_dpkg_arch)
Simon McVittie's avatar
Simon McVittie committed

        os.makedirs(self.build_area, exist_ok=True)
        os.makedirs(os.path.dirname(self.repo), exist_ok=True)

        if args.command is None:
            parser.error('A command is required')

        with open(
                os.path.join('suites', self.apt_suite + '.yaml'),
                encoding='utf-8') as reader:
Simon McVittie's avatar
Simon McVittie committed
            self.suite_details = yaml.safe_load(reader)

        if 'strip_source_version_suffix' in self.suite_details:
            self.strip_source_version_suffix = re.compile(
                '(?:' +
                self.suite_details['strip_source_version_suffix'] +
                ')$')

Simon McVittie's avatar
Simon McVittie committed
        getattr(
            self, 'command_' + args.command.replace('-', '_'))(**vars(args))

    def command_print_flatpak_architecture(self, **kwargs):
        print(self.flatpak_arch)

    @property
    def apt_uris(self):
        for source in self.suite_details['sources']:
            yield source['apt_uri']

    def ensure_build_area(self):
        self.worker.check_call([
            'sh', '-euc',
            'mkdir -p "${XDG_CACHE_HOME:="$HOME/.cache"}/flatdeb"',
        ])
Simon McVittie's avatar
Simon McVittie committed
    def command_base(self, **kwargs):
        with ExitStack() as stack:
            stack.enter_context(self.worker)
            self.ensure_build_area()
            stack.enter_context(self.ensure_root_worker())
Simon McVittie's avatar
Simon McVittie committed

            base_chroot = '{}/base'.format(self.root_worker.scratch)

            # Try to make sure Ubuntu precise doesn't try to migrate /run
            self.root_worker.check_call(['install', '-d', base_chroot])
            self.root_worker.check_call([
                'install', '-d', base_chroot + '/run'])
            self.root_worker.check_call([
                'install', '-d', base_chroot + '/var'])
            self.root_worker.check_call([
                'ln', '-fns', '/run', base_chroot + '/var/run'])
            self.root_worker.check_call([
                'ln', '-fns', '/dev/shm', base_chroot + '/run/shm'])

Simon McVittie's avatar
Simon McVittie committed
            argv = [
                'env',
                'DEBIAN_FRONTEND=noninteractive',
Simon McVittie's avatar
Simon McVittie committed
                'http_proxy=http://192.168.122.1:3142',
                'debootstrap',
                '--variant=minbase',
                '--arch={}'.format(self.primary_dpkg_arch),
                '--include=apt-transport-https',
            if self.suite_details.get('can_merge_usr', False) is True:
Simon McVittie's avatar
Simon McVittie committed
                argv.append('--merged-usr')

            keyring = self.suite_details['sources'][0].get('keyring')

            if keyring is not None:
                if os.path.exists(os.path.join('suites', keyring)):
                    keyring = os.path.join('suites', keyring)
                elif os.path.exists(keyring):
                    pass
                else:
                    raise RuntimeError('Cannot open {}'.format(keyring))

Simon McVittie's avatar
Simon McVittie committed
                dest = '{}/{}'.format(
                    self.root_worker.scratch,
                    os.path.basename(keyring),
                )
                self.root_worker.install_file(os.path.abspath(keyring), dest)
                argv.append('--keyring=' + dest)

            argv.append(self.suite_details['sources'][0].get(
                'apt_suite', self.apt_suite,
            ))
            argv.append(base_chroot)
            argv.append(self.suite_details['sources'][0]['apt_uri'])

            script = self.suite_details.get('debootstrap_script')

            if script is not None:
                argv.append('/usr/share/debootstrap/scripts/' + script)

            try:
                self.root_worker.check_call(argv)
            except:
                with suppress(Exception):
                    self.root_worker.check_call([
                        'cat',
                        '{}/debootstrap/debootstrap.log'.format(base_chroot),
                    ])
                raise

            self.configure_base(base_chroot)
            self.configure_apt(base_chroot)

            if self.suite_details.get('can_merge_usr', False) == 'after_debootstrap':
                self.usrmerge(base_chroot)

Simon McVittie's avatar
Simon McVittie committed
            tarball = 'base-{}-{}.tar.gz'.format(
                self.apt_suite,
                ','.join(self.dpkg_archs),
Simon McVittie's avatar
Simon McVittie committed
            )

            self.root_worker.check_call([
                'time',
Simon McVittie's avatar
Simon McVittie committed
                'tar', '-zcf', '{}/{}'.format(
                    self.build_area, tarball,
Simon McVittie's avatar
Simon McVittie committed
                ),
                '-C', base_chroot,
                '--exclude=./etc/.pwd.lock',
                '--exclude=./etc/group-',
                '--exclude=./etc/passwd-',
                '--exclude=./etc/shadow-',
                '--exclude=./home',
                '--exclude=./root',
                '--exclude=./tmp',
                '--exclude=./var/cache',
                '--exclude=./var/lock',
                '--exclude=./var/tmp',
                '.',
            ])

    def ensure_root_worker(self):
        if self.root_worker is None:
            id_u = self.worker.check_output(['id', '-u']).strip()

            if id_u == b'0':
                self.root_worker = self.worker
            else:
                self.root_worker = SudoWorker(self.worker)

        return self.root_worker

    def ensure_local_repo(self):
        self.host_worker.check_call([
            'install',
            '-d',
            os.path.dirname(self.repo),
        ])
        self.host_worker.check_call([
            'ostree',
            '--repo=' + self.repo,
            'init',
            '--mode={}'.format(self.ostree_mode),
Simon McVittie's avatar
Simon McVittie committed
        ])

    def command_runtimes(self, *, yaml_file, **kwargs):
        self.ensure_local_repo()
Simon McVittie's avatar
Simon McVittie committed

        if self.runtime_branch is None:
            self.runtime_branch = self.apt_suite

        with open(yaml_file, encoding='utf-8') as reader:
Simon McVittie's avatar
Simon McVittie committed
            self.runtime_details = yaml.safe_load(reader)

        tarball = 'base-{}-{}.tar.gz'.format(
            self.apt_suite,
            ','.join(self.dpkg_archs),
Simon McVittie's avatar
Simon McVittie committed
        )

        with ExitStack() as stack:
            stack.enter_context(self.worker)
            self.ensure_build_area()
            stack.enter_context(self.ensure_root_worker())
Simon McVittie's avatar
Simon McVittie committed

            base_chroot = '{}/base'.format(self.root_worker.scratch)
            self.root_worker.check_call([
                'install', '-d', base_chroot,
            ])
            self.root_worker.check_call([
                'time',
Simon McVittie's avatar
Simon McVittie committed
                'tar', '-zxf',
Simon McVittie's avatar
Simon McVittie committed
                '-C', base_chroot,
                '.',
            ], stdin=open(os.path.join(self.build_area, tarball), 'rb'))
Simon McVittie's avatar
Simon McVittie committed

            # We do common steps for both the Platform and the Sdk
            # in the base directory, then copy it.
            self.configure_base(base_chroot)
            self.configure_base_runtime(base_chroot)
Simon McVittie's avatar
Simon McVittie committed

            platform_chroot = '{}/platform'.format(self.root_worker.scratch)
            sdk_chroot = '{}/sdk'.format(self.root_worker.scratch)

            self.root_worker.check_call([
                'time',
Simon McVittie's avatar
Simon McVittie committed
                'cp', '-a', '--reflink=auto', base_chroot, platform_chroot,
            ])
            self.root_worker.check_call([
                'mv', base_chroot, sdk_chroot,
            ])

            prefix = self.runtime_details['id_prefix']

            # Do the Platform first, because we download its source
            # packages as part of preparing the Sdk
Simon McVittie's avatar
Simon McVittie committed
            self.ostreeify(
                prefix,
                platform_chroot,
            )
            self.ostreeify(
                prefix,
                sdk_chroot,
                sdk=True,
            )

            self.worker.check_call([
                'time',
Simon McVittie's avatar
Simon McVittie committed
                'flatpak',
                'build-update-repo',
                self.repo,
Simon McVittie's avatar
Simon McVittie committed
            ])

            if self.export_bundles:
                for suffix in ('.Platform', '.Sdk'):
                    bundle = '{}-{}-{}.bundle'.format(
                        prefix + suffix,
                        self.flatpak_arch,
                        self.runtime_branch,
                    )
                    output = os.path.join(self.build_area, bundle)

Simon McVittie's avatar
Simon McVittie committed
                    self.worker.check_call([
                        'time',
                        'flatpak',
                        'build-bundle',
                        '--runtime',
                        self.repo,
                        output + '.new',
                        prefix + suffix,
                        self.runtime_branch,
Simon McVittie's avatar
Simon McVittie committed

                    os.rename(output + '.new', output)
Simon McVittie's avatar
Simon McVittie committed

        if self.missing_sources:
            logger.warning('Missing source packages:')

            for p in sorted(self.missing_sources):
                logger.warning('- %s', p)

            logger.warning('Check that this runtime is GPL-compliant!')

Simon McVittie's avatar
Simon McVittie committed
    def configure_apt(self, base_chroot):
        """
        Configure apt. We only do this once, so that all chroots
        created from the same base have their version numbers
        aligned.
        """
        with TemporaryDirectory(prefix='flatdeb-apt.') as t:
Simon McVittie's avatar
Simon McVittie committed
            # Set up the apt sources

            to_copy = os.path.join(t, 'sources.list')

            with open(to_copy, 'w', encoding='utf-8') as writer:
Simon McVittie's avatar
Simon McVittie committed
                for source in self.suite_details['sources']:
                    suite = source.get('apt_suite', self.apt_suite)
                    suite = suite.replace('*', self.apt_suite)
                    components = source.get(
                        'apt_components',
                        self.suite_details.get(
                            'apt_components',
                            ['main']))

                    options = []

                    if source.get('apt_trusted', False):
                        options.append('trusted=yes')

                    if options:
                        options_str = ' [' + ' '.join(options) + ']'
                    else:
                        options_str = ''

Simon McVittie's avatar
Simon McVittie committed
                    for prefix in ('deb', 'deb-src'):
                        writer.write('{}{} {} {} {}\n'.format(
Simon McVittie's avatar
Simon McVittie committed
                            prefix,
Simon McVittie's avatar
Simon McVittie committed
                            source['apt_uri'],
                            suite,
                            ' '.join(components),
                        ))

                    keyring = source.get('keyring')

                    if keyring is not None:
                        if os.path.exists(os.path.join('suites', keyring)):
                            keyring = os.path.join('suites', keyring)
                        elif os.path.exists(keyring):
                            pass
                        else:
                            raise RuntimeError('Cannot open {}'.format(keyring))

Simon McVittie's avatar
Simon McVittie committed
                        self.root_worker.install_file(
                            os.path.abspath(keyring),
                            '{}/etc/apt/trusted.gpg.d/{}'.format(
                                base_chroot,
                                os.path.basename(keyring),
                            ),
                        )

            self.root_worker.install_file(
                to_copy,
                '{}/etc/apt/sources.list'.format(base_chroot),
            )
            self.root_worker.check_call([
                'rm', '-fr',
                '{}/etc/apt/sources.list.d'.format(base_chroot),
            ])

        with NspawnWorker(
            self.root_worker,
            base_chroot,
            env=[
                'DEBIAN_FRONTEND=noninteractive',
                'http_proxy=http://192.168.122.1:3142',
            ],
Simon McVittie's avatar
Simon McVittie committed
        ) as nspawn:
            for other_arch in self.dpkg_archs[1:]:
                try:
                    nspawn.check_call([
                        'dpkg', '--add-architecture', other_arch,
                    ])
                except subprocess.CalledProcessError:
                    # Older syntax for Ubuntu precise
                    # https://wiki.debian.org/Multiarch/HOWTO
                    nspawn.check_call([
                        'sh', '-euc',
                        'echo "foreign-architecture $1" > ' +
                        '/etc/dpkg/dpkg.cfg.d/architectures',
                        'sh', # argv[0]
                        other_arch,
                    ])

Simon McVittie's avatar
Simon McVittie committed
            nspawn.check_call([
                'apt-get', '-y', '-q', 'update',
            ])
            nspawn.check_call([
                'DEBIAN_FRONTEND=noninteractive',
Simon McVittie's avatar
Simon McVittie committed
                'apt-get', '-y', '-q', 'dist-upgrade',
            ])

    def configure_base(self, base_chroot):
        """
        Configure the common chroot that will be copied to make both the
        Platform and the Sdk.
        """
        self.root_worker.install_file(
            _DISABLE_SERVICES,
            '{}/disable-services'.format(self.root_worker.scratch),
            permissions=0o755,
        )
        self.root_worker.check_call([
            '{}/disable-services'.format(self.root_worker.scratch),
            base_chroot,
        ])
        self.root_worker.install_file(
            _CLEAN_UP_BASE,
            '{}/clean-up-base'.format(self.root_worker.scratch),
            permissions=0o755,
        )
        self.root_worker.check_call([
            '{}/clean-up-base'.format(self.root_worker.scratch),
            base_chroot,
        ])
Simon McVittie's avatar
Simon McVittie committed

    def configure_base_runtime(self, base_chroot):
        """
        Configure the common chroot that will be copied to make both the
        Platform and the Sdk.
        """
Simon McVittie's avatar
Simon McVittie committed
        with NspawnWorker(
            self.root_worker,
            base_chroot,
            env=[
                'http_proxy=http://192.168.122.1:3142',
                'DEBIAN_FRONTEND=noninteractive',
            ],
Simon McVittie's avatar
Simon McVittie committed
        ) as nspawn:
            nspawn.check_call([
                'install', '-d',
                '/var/cache/apt/archives/partial',
                '/var/lock',
            ])

            # We use aptitude to help prepare the Platform runtime, and
            # it's a useful thing to have in the Sdk runtime
            nspawn.check_call([
                'apt-get', '-q', '-y',
                '--no-install-recommends',
                'install', 'aptitude',
Simon McVittie's avatar
Simon McVittie committed
            ])

            # All packages will be removed from the platform runtime
            # unless they are Essential, depended-on, or in the
            # add_packages list.
            nspawn.check_call([
                'aptitude', '-y', 'markauto', '?installed'
            ])
            # Ubuntu precise doesn't like apt being up for autoremoval.
            nspawn.check_call([
                'aptitude', '-y', 'unmarkauto', 'apt'
            ])

            packages = list(self.runtime_details.get('add_packages', []))
            for p in self.runtime_details.get('add_packages_multiarch', []):
                for a in self.dpkg_archs:
                    packages.append(p + ':' + a)
Simon McVittie's avatar
Simon McVittie committed

            if packages:
                nspawn.check_call([
                    'apt-get', '-q', '-y', 'install',
                    '--no-install-recommends',
Simon McVittie's avatar
Simon McVittie committed
                ] + packages)

Simon McVittie's avatar
Simon McVittie committed
    def sdkize(self, sdk_chroot):
        """
        Transform a copy of the chroot into a Sdk runtime.
        """
Simon McVittie's avatar
Simon McVittie committed
        logger = self.logger.getChild('sdkize')

Simon McVittie's avatar
Simon McVittie committed
        sdk_details = self.runtime_details.get('sdk', {})

        with NspawnWorker(
            self.root_worker,
            sdk_chroot,
            env=[
                'http_proxy=http://192.168.122.1:3142',
                'DEBIAN_FRONTEND=noninteractive',
            ],
Simon McVittie's avatar
Simon McVittie committed
        ) as nspawn:
            packages = list(sdk_details.get('add_packages', []))

            for p in sdk_details.get('add_packages_multiarch', []):
                for a in self.dpkg_archs:
                    packages.append(p + ':' + a)
Simon McVittie's avatar
Simon McVittie committed

            if packages:
Simon McVittie's avatar
Simon McVittie committed
                logger.info('Installing extra packages for SDK:')

                for p in sorted(packages):
                    logger.info('- %s', p)

Simon McVittie's avatar
Simon McVittie committed
                nspawn.check_call([
                    'apt-get', '-q', '-y', 'install',
                    '--no-install-recommends',
Simon McVittie's avatar
Simon McVittie committed
                ] + packages)

            script = self.runtime_details.get('post_script', '')

            if script:
                logger.info('Running custom script...')
                nspawn.check_call([
                    'sh', '-c', script,
                ])
                logger.info('... done')

            script = sdk_details.get('post_script', '')
Simon McVittie's avatar
Simon McVittie committed
                logger.info('Running custom SDK script...')
                nspawn.check_call([
                    'sh', '-c', script,
                ])
Simon McVittie's avatar
Simon McVittie committed
                logger.info('... done')
            logger.info('Listing additional packages in SDK...')

            sdk_packages = nspawn.write_manifest()

            for package in sdk_packages:
                if package in self.platform_packages:
                    continue
                logger.info(
                    '- %s from %s_%s',
                    package.binary, package.source, package.source_version)
                self.sources_required.add((package.source, package.source_version))

            for package in self.platform_packages:
                if package not in sdk_packages:
                    logger.warning(
                        'Package found in Platform but not Sdk: %s/%s',
                        package.binary, package.binary_version)

            logger.info('Listing Built-Using fields for SDK...')

            for package, source, version in nspawn.list_built_using():
                logger.info(
                    '- %s was Built-Using %s_%s',
                    package, source, version)
                self.sources_required.add((source, version))

            installed = nspawn.list_packages_ignore_arch()
Simon McVittie's avatar
Simon McVittie committed

            if 'apt-forktracer' in installed:
                logger.info('Checking which packages came from other sources:')
                nspawn.call(['apt-forktracer'])

            logger.info('Source code required for GPL compliance:')
Simon McVittie's avatar
Simon McVittie committed

                package = package.split(':', 1)[0]

                if self.strip_source_version_suffix is not None:
                    version = self.strip_source_version_suffix.sub('', version)

                logger.info('- %s_%s', package, version)
                sources.append('{}={}'.format(package, version))

            try:
                nspawn.check_call(['sh', '-euc',
                    'dir="$1"; shift; mkdir -p "$dir"; cd "$dir"; "$@"',
                    'sh',                       # argv[0]
                    '/ostree/source/files',     # working directory
                    'apt-get', '-y', '--download-only',
                    '-oAPT::Get::Only-Source=true', 'source',
                ] + sources)
            except subprocess.CalledProcessError:
                logger.warning(
                    'Unable to download some sources as a batch, trying '
                    'to download sources individually')

                for source in sources:
                    try:
                        nspawn.check_call(['sh', '-euc',
                            'dir="$1"; shift; mkdir -p "$dir"; cd "$dir"; "$@"',
                            'sh',                       # argv[0]
                            '/ostree/source/files',     # working directory
                            'apt-get', '-y', '--download-only',
                            '-oAPT::Get::Only-Source=true', 'source',
                            source,
                        ])
                    except subprocess.CalledProcessError:
                        # Non-fatal for now
                        logger.warning(
                            'Unable to get source code for %s', source)
                        self.missing_sources.add(source)
                        source_package = source.split('=', 1)[0]
                        nspawn.call(['apt-cache', 'showsrc', source_package])
Simon McVittie's avatar
Simon McVittie committed

Simon McVittie's avatar
Simon McVittie committed
        return installed

    def platformize(self, platform_chroot):
        """
        Transform a copy of the chroot into a Platform runtime.
        """
Simon McVittie's avatar
Simon McVittie committed
        logger = self.logger.getChild('platformize')
Simon McVittie's avatar
Simon McVittie committed
        platform_details = self.runtime_details.get('platform', {})

        with NspawnWorker(
            self.root_worker,
            platform_chroot,
            env=[
                'DEBIAN_FRONTEND=noninteractive',
Simon McVittie's avatar
Simon McVittie committed
                'SUDO_FORCE_REMOVE=yes',
                'http_proxy=http://192.168.122.1:3142',
Simon McVittie's avatar
Simon McVittie committed
            ],
        ) as nspawn:
Simon McVittie's avatar
Simon McVittie committed
            # TODO: For the SteamRuntime this removes dbus,
            # libsasl2-modules and python-debian and I have no idea why
            #nspawn.check_call([
            #    'aptitude', '-y', 'purge',
            #    '?and(?installed,?section(devel))',
            #    '?and(?installed,?section(libdevel))',
            #])
Simon McVittie's avatar
Simon McVittie committed

            installed = nspawn.list_packages_ignore_arch()

Simon McVittie's avatar
Simon McVittie committed
            logger.info('Packages installed at the moment:')

            for p in sorted(installed):
                logger.info('- %s', p)

Simon McVittie's avatar
Simon McVittie committed
            unwanted = []

            for package in [
                    'aptitude',
                    'fakeroot',
                    'libfakeroot',
            ]:
                if package in installed:
                    unwanted.append(package)

            if unwanted:
Simon McVittie's avatar
Simon McVittie committed
                logger.info('Removing unwanted packages')

Simon McVittie's avatar
Simon McVittie committed
                nspawn.check_call([
                    'apt-get', '-y', 'purge',
                ] + unwanted)
Simon McVittie's avatar
Simon McVittie committed

Simon McVittie's avatar
Simon McVittie committed
            logger.info('Autoremoving packages')
Simon McVittie's avatar
Simon McVittie committed
            nspawn.check_call([
                'apt-get', '-y', '--purge', 'autoremove',
            ])

            installed = nspawn.list_packages_ignore_arch()
Simon McVittie's avatar
Simon McVittie committed

Simon McVittie's avatar
Simon McVittie committed
            logger.info('Packages installed before destroying Essential set:')

            for p in sorted(installed):
                logger.info('- %s', p)

Simon McVittie's avatar
Simon McVittie committed
            # These are Essential (or at least important) but serve no
            # purpose in an immutable runtime with no init. Note that
            # order is important: adduser needs to be removed before
            # debconf. We remove these particular packages first because
            # they try to invoke other packages we want to remove in
            # their postrm maintainer scripts.
Simon McVittie's avatar
Simon McVittie committed
            for package in [
                    'adduser',
                    'apt',
                    'gnupg',
                    'ifupdown',
                    'initramfs-tools',
                    'initramfs-tools-bin',
                    'initscripts',
                    'lsb-base',
                    'module-init-tools',
                    'plymouth',
                    'tcpd',
            ]:
                if package in installed:
                    unwanted.append(package)

            if 'python' not in installed:
                unwanted.append('python-minimal')
                unwanted.append('python2.7-minimal')

            logger.info('Packages we will forcibly remove (first round):')

            for p in sorted(unwanted):
                logger.info('- %s', p)

            if unwanted:
                nspawn.check_call([
                    'dpkg', '--purge', '--force-remove-essential',
                    '--force-depends',
                ] + unwanted)

            # Second round of removals.
            for package in [
Simon McVittie's avatar
Simon McVittie committed
                    'busybox-initramfs',
                    'debconf',
                    'debian-archive-keyring',
                    'e2fsprogs',
                    'init',
                    'init-system-helpers',
                    'insserv',
                    'iproute',
                    'login',
                    'mount',
                    'mountall',
                    'passwd',
                    'systemd',
                    'systemd-sysv',
                    'sysv-rc',
                    'ubuntu-archive-keyring',
                    'ubuntu-keyring',
                    'udev',