Commit cc01a8da authored by Simon McVittie's avatar Simon McVittie
Browse files

Use debos to build runtimes

parent 8636f816
#!/usr/bin/python3
# flatdeb — build Flatpak runtimes from Debian packages
#
# Copyright © 2016-2017 Simon McVittie
# Copyright © 2017-2018 Collabora Ltd.
#
# 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.
"""
Fetch source code for packages installed in the given sysroot.
"""
import argparse
import logging
import os
import re
import subprocess
import sys
logger = logging.getLogger('flatdeb.collect-source-code')
class InstalledPackage:
def __init__(self, fields):
self.binary = fields[0]
self.binary_version = fields[1]
self.source = fields[2]
if self.source.endswith(')'):
self.source, self.source_version = self.source.rstrip(')').split(' (')
else:
self.source_version = self.binary_version
if not self.source:
self.source = self.binary
self.installed_size = fields[3]
def __str__(self):
return '{}_{}'.format(self.binary, self.binary_version)
def __hash__(self):
return hash(self.binary) ^ hash(self.binary_version)
def __eq__(self, other):
if isinstance(other, InstalledPackage):
return (
self.binary,
self.binary_version,
) == (
other.binary,
other.binary_version,
)
else:
return NotImplemented
class SourceRequired:
def __init__(self, source, source_version):
self.source = source
self.source_version = source_version
def __str__(self):
return 'src:{}_{}'.format(self.source, self.source_version)
def __hash__(self):
return hash(self.source) ^ hash(self.source_version)
def __eq__(self, other):
if isinstance(other, SourceRequired):
return (
self.source,
self.source_version,
) == (
other.source,
other.source_version,
)
else:
return NotImplemented
def read_manifest(path):
ret = []
with open(path, encoding='utf-8') as reader:
for line in reader:
line = line.rstrip('\n')
if not line:
continue
if line.startswith('#'):
continue
assert '\t' in line, repr(line)
ret.append(InstalledPackage(line.rstrip('\n').split('\t')))
return ret
def read_built_using(path):
ret = set()
with open(path, encoding='utf-8') as reader:
for line in reader:
line = line.rstrip('\n')
if line.startswith('#'):
continue
package, source, version = line.split('\t')
s = SourceRequired(source, version)
logger.info(
'%s was Built-Using %s',
package, s)
ret.add(s)
return ret
def main():
parser = argparse.ArgumentParser(
description='Collect source code',
)
parser.add_argument('--strip-source-version-suffix', default='')
parser.add_argument('sysroot')
args = parser.parse_args()
strip_source_version_suffix = None
if args.strip_source_version_suffix:
strip_source_version_suffix = re.compile(
'(?:' + args.strip_source_version_suffix + ')$')
in_chroot = [
'systemd-nspawn',
'--directory={}'.format(args.sysroot),
'--as-pid2',
'env',
]
manifest = os.path.join(args.sysroot, 'usr', 'manifest.dpkg')
platform_manifest = os.path.join(
args.sysroot, 'usr', 'manifest.dpkg.platform')
built_using = os.path.join(
args.sysroot, 'usr', 'manifest.dpkg.built-using')
platform_built_using = os.path.join(
args.sysroot, 'usr', 'manifest.dpkg.built-using.platform')
sdk_packages = read_manifest(manifest)
packages = sdk_packages[:]
sources_required = set()
if os.path.exists(platform_manifest):
platform_packages = read_manifest(manifest)
else:
platform_packages = []
for p in platform_packages:
logger.info('Package in Platform: %s', p)
if p not in sdk_packages:
logger.warning('Package in Platform but not SDK: %s', p)
packages.append(p)
for p in sdk_packages:
if p not in platform_packages:
logger.info('Additional package in SDK: %s', p)
for p in packages:
sources_required.add(SourceRequired(p.source, p.source_version))
sources_required |= read_built_using(built_using)
if os.path.exists(platform_built_using):
sources_required |= read_built_using(platform_built_using)
sources = []
missing_sources = set()
for s in sources_required:
source = s.source
source_version = s.source_version
# TODO: Is this necessary any more?
source = source.split(':', 1)[0]
if strip_source_version_suffix is not None:
source_version = strip_source_version_suffix.sub(
'', source_version)
sources.append('{}={}'.format(source, source_version))
try:
subprocess.check_call(in_chroot + [
'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:
subprocess.check_call(in_chroot + [
'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)
missing_sources.add(source)
source_package = source.split('=', 1)[0]
subprocess.call(in_chroot + [
'apt-cache', 'showsrc', source_package,
])
if missing_sources:
logger.warning('Missing source packages:')
for p in sorted(missing_sources):
logger.warning('- %s', p)
logger.warning('Check that this runtime is GPL-compliant!')
if __name__ == '__main__':
if sys.stderr.isatty():
try:
import colorlog
except ImportError:
pass
else:
formatter = colorlog.ColoredFormatter(
'%(log_color)s%(levelname)s:%(name)s:%(reset)s %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logging.getLogger().addHandler(handler)
else:
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
try:
main()
except KeyboardInterrupt:
raise SystemExit(130)
except subprocess.CalledProcessError as e:
logger.error('%s', e)
raise SystemExit(1)
{{- $architecture := or .architecture "amd64" -}}
{{- $suite := or .suite "stretch" -}}
{{- $flatpak_arch := or .flatpak_arch $architecture -}}
{{- $packages := or .packages "" -}}
{{- $post_script := or .post_script "" -}}
{{- $sdk := or .sdk "" -}}
{{- $sdk_packages := or .sdk_packages "" -}}
{{- $sdk_post_script := or .sdk_post_script "" -}}
{{- $platform_post_script := or .platform_post_script "" -}}
{{- $strip_source_version_suffix := or .strip_source_version_suffix "" -}}
{{- $version := or .version "0" -}}
{{- $ospack := or .ospack (printf "base_%s_%s_%s.tar.gz" $suite $version $architecture) -}}
{{- $runtime := .runtime -}}
{{- $runtime_branch := or .runtime_branch "master" -}}
{{- $ostree_tarball := or .ostree_tarball (printf "ostree_%s_%s_%s.tar.gz" $runtime $flatpak_arch $runtime_branch) -}}
{{- $sources_tarball := or .sources_tarball (printf "sources_%s_%s_%s.tar.gz" $runtime $flatpak_arch $runtime_branch) -}}
{{- $repo := or .repo "repo" -}}
architecture: {{ $architecture }}
actions:
- action: unpack
compression: gz
file: {{ $ospack }}
# TODO: This duplicates what we should have done in debos-base.yaml
- action: run
chroot: false
command: '"$RECIPEDIR/disable-services" "$ROOTDIR"'
# TODO: This duplicates what we should have done in debos-base.yaml
- action: run
chroot: false
command: '"$RECIPEDIR/clean-up-base" "$ROOTDIR"'
- action: run
chroot: false
command: '"$RECIPEDIR/prepare-runtime" "$ROOTDIR"'
{{ if $packages }}
- action: apt
recommends: false
packages: {{ $packages }}
{{ end }}
# We do this as a separate step in case it involves removing any
# of the common packages
{{ if and $sdk $sdk_packages }}
- action: apt
recommends: false
packages: {{ $sdk_packages }}
{{ end }}
{{ if not $sdk }}
- action: run
chroot: false
command: '"$RECIPEDIR/platformize" "$ROOTDIR"'
{{ end }}
{{ if $post_script }}
- action: run
chroot: true
script: '{{ $post_script }}'
{{ end }}
{{ if $sdk }}
{{ if $sdk_post_script }}
- action: run
chroot: true
script: '{{ $sdk_post_script }}'
{{ end }}
{{ else }}
{{ if $platform_post_script }}
- action: run
chroot: true
script: '{{ $platform_post_script }}'
{{ end }}
{{ end }}
- action: run
chroot: false
command: '"$RECIPEDIR/write-manifest" "$ROOTDIR"'
{{ if $sdk }}
- action: run
chroot: false
command: 'cp "$RECIPEDIR/manifest.dpkg.platform" "$ROOTDIR/usr"'
- action: run
chroot: false
command: 'cp "$RECIPEDIR/manifest.dpkg.built-using.platform" "$ROOTDIR/usr"'
- action: run
chroot: false
command: '"$RECIPEDIR/collect-source-code" --strip-source-version-suffix="{{ $strip_source_version_suffix }}" "$ROOTDIR"'
{{ else }}
- action: run
chroot: false
command: 'cp "$ROOTDIR/usr/manifest.dpkg" "$RECIPEDIR/manifest.dpkg.platform"'
- action: run
chroot: false
command: 'cp "$ROOTDIR/usr/manifest.dpkg.built-using" "$RECIPEDIR/manifest.dpkg.built-using.platform"'
- action: run
chroot: true
command: 'dpkg --purge --force-remove-essential --force-depends dpkg'
{{ end }}
- action: run
chroot: true
script: hard-link-alternatives
- action: run
chroot: false
command: '"$RECIPEDIR/usrmerge" "$ROOTDIR"'
- action: run
chroot: true
script: put-ldconfig-in-path
{{ if $sdk }}
- action: run
chroot: false
command: '"$RECIPEDIR/make-flatpak-friendly" --sdk "$ROOTDIR"'
{{ else }}
- action: run
chroot: false
command: '"$RECIPEDIR/make-flatpak-friendly" "$ROOTDIR"'
{{ end }}
# TODO: Move lib/debug, zoneinfo, locales into extensions
# TODO: Hook point for GL, instead of just Mesa
# TODO: GStreamer extension
# TODO: Icon theme, Gtk theme extension
# TODO: VAAPI extension
# TODO: SDK extension
# TODO: ca-certificates extension to get newer certs?
- action: overlay
source: runtimes/{{ $runtime }}/overlay
- action: run
chroot: false
command: 'install -d "$ROOTDIR/ostree/main"'
- action: run
chroot: false
command: 'mv "$ROOTDIR/usr" "$ROOTDIR/ostree/main/files"'
- action: run
chroot: false
command: 'tar -zcf "$ARTIFACTDIR/{{ $ostree_tarball }}" -C "$ROOTDIR/ostree/main" files metadata'
{{ if $sdk }}
- action: run
chroot: false
command: 'tar -zcf "$ARTIFACTDIR/{{ $sources_tarball }}" -C "$ROOTDIR/ostree/source" .'
- action: run
chroot: false
command: 'ostree --repo="$ARTIFACTDIR/{{ $repo }}" commit --branch="runtime/{{ $runtime }}.Sources/{{ $flatpak_arch }}/{{ $runtime_branch }}" --subject=Update --tree=dir="$ROOTDIR/ostree/source" --fsync=false'
{{ end }}
- action: run
chroot: false
command: 'ostree --repo="$ARTIFACTDIR/{{ $repo }}" commit --branch="runtime/{{ $runtime }}/{{ $flatpak_arch }}/{{ $runtime_branch }}" --subject=Update --tree=dir="$ROOTDIR/ostree/main" --fsync=false'
#!/bin/bash
# Copyright © 2016-2017 Simon McVittie
# Copyright © 2017-2018 Collabora Ltd.
#
# 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.
set -e
set -u
set -x
set -o pipefail
me="$(basename "$0")"
NULL=
if [ "$#" != 0 ] || [ "x$(id -u)" != x0 ]; then
echo "$me: Usage:" >&2
echo " $me" >&2
echo "" >&2
echo "Run this script as root, in the container." >&2
exit 2
fi
find / -xdev '(' \
-lname '/etc/alternatives/*' -o \
-lname '/etc/locale.alias' \
')' -exec sh -euc '
while [ $# -gt 0 ]; do
old="$(readlink "$1")"
if target="$(readlink -f "$1")"; then
echo "Making $1 a hard link to $target (was $old)"
rm -f "$1"
cp -al "$target" "$1"
fi
shift
done
' \
'sh' \
'{}' '+'
# In the above, 'sh' before '{}' is argv[0]
# vim:set sw=4 sts=4 et:
#!/bin/bash
# Copyright © 2016-2017 Simon McVittie
# Copyright © 2017-2018 Collabora Ltd.
#
# 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.
set -e
set -u
set -o pipefail
me="$(basename "$0")"
NULL=
sdk=
if [ "${1-}" = '--sdk' ]; then
sdk=yes
shift
fi
if [ "$#" != 1 ] || [ "$1" = '--help' ] || [ "x$(id -u)" != x0 ] ||
! [ -d "$1" ]; then
echo "$me: Usage:" >&2
echo " $me SYSROOT" >&2
echo "" >&2
echo "Run this script as root." >&2
exit 2
fi
set -x
sysroot="$1"
cd "$sysroot"
chmod -R --changes "a-s,o-t,u=rwX,og=rX" .
chown -R --changes "root:root" .
rm -fr --one-file-system usr/local
rm -fr --one-file-system \
etc/apparmor \
etc/apparmor.d \
etc/console-setup \
etc/cron.daily \
etc/cron.hourly \
etc/cron.monthly \
etc/cron.weekly \
etc/dbus-1/system.d \
etc/depmod.d \
etc/dhcp \
etc/emacs \
etc/fstab \
etc/fstab.d \
etc/group- \
etc/gshadow- \
etc/hostname \
etc/hosts \
etc/hosts.allow \
etc/hosts.deny \
etc/init \
etc/init.d \
etc/initramfs-tools \
etc/insserv \
etc/insserv.conf \
etc/insserv.conf.d \
etc/iproute2 \
etc/issue \
etc/issue.net \
etc/kbd \
etc/kernel \
etc/localtime \
etc/logcheck \
etc/login.defs \
etc/logrotate.d \
etc/lsb-base \
etc/lsb-base-logging.sh \
etc/machine-id \
etc/mailname \
etc/modprobe.d \
etc/modules \
etc/network \
etc/networks \
etc/nologin \
etc/opt \
etc/pam.conf \
etc/pam.d \
etc/passwd- \
etc/ppp \
"etc/rc.local" \
etc/rc0.d \
etc/rc1/d \
etc/rc2.d \
etc/rc3.d \
etc/rc4.d \
etc/rc5.d \
etc/rc6.d \
etc/resolv.conf \