Translation(s): none


What is sbuild

What is sbuild:

sbuild is fundamentally a tool for making binary builds. None of its isolation and testing features are actually relevant for making source-only uploads.

The alternative to sbuild are

This main part of this page is intended as a short guide to sbuild. It documents how to set up sbuild and build packages with it. The later parts of the page document optional enhancements to the simple setup described in the first section.

Setup

We assume you are running at least Debian 11 bullseye (testing) using a type=directory chroot.

Automatic setup using sbuild-debian-developer-setup

sbuild provides the package sbuild-debian-developer-setup which helps you setup an sbuild environment easily, if you're interested, make sure to take a look at the manpage at https://manpages.debian.org/unstable/sbuild/sbuild-debian-developer-setup.1

You may still want to further customize setting manually as the following to enjoy additional optional features.

Manual setup of sbuild

This ~/.sbuildrc sets up sbuild in a way compatible with most contemporary Debian practices.

   1 sudo apt-get install sbuild schroot debootstrap apt-cacher-ng devscripts piuparts
   2 sudo tee ~/.sbuildrc << EOF
   3 ##############################################################################
   4 # PACKAGE BUILD RELATED (additionally produce _source.changes)
   5 ##############################################################################
   6 # -d
   7 $distribution = 'unstable';
   8 # -A
   9 $build_arch_all = 1;
  10 # -s
  11 $build_source = 1;
  12 # --source-only-changes (applicable for dput. irrelevant for dgit push-source).
  13 $source_only_changes = 1;
  14 # -v
  15 $verbose = 1;
  16 # parallel build
  17 $ENV{'DEB_BUILD_OPTIONS'} = 'parallel=5';
  18 ##############################################################################
  19 # POST-BUILD RELATED (turn off functionality by setting variables to 0)
  20 ##############################################################################
  21 $run_lintian = 1;
  22 $lintian_opts = ['-i', '-I'];
  23 $run_piuparts = 1;
  24 $piuparts_opts = ['--schroot', 'unstable-amd64-sbuild', '--no-eatmydata'];
  25 $run_autopkgtest = 1;
  26 $autopkgtest_root_args = '';
  27 $autopkgtest_opts = [ '--', 'schroot', '%r-%a-sbuild' ];
  28 
  29 ##############################################################################
  30 # PERL MAGIC
  31 ##############################################################################
  32 1;
  33 EOF
  34 sudo sbuild-adduser $LOGNAME
  35 sudo ln -sf ~/.sbuildrc /root/.sbuildrc

... *logout* and *re-login* or use newgrp sbuild in your current shell

   1 sudo sbuild-createchroot --include=eatmydata,ccache unstable /srv/chroot/unstable-amd64-sbuild http://127.0.0.1:3142/ftp.us.debian.org/debian

This invokes debootstrap with --variant=buildd option to install required, apt ,fakeroot and build-essential packages in addition to specified eatmydata, and ccache packages. This also configures /etc/hosts, /usr/sbin/policy-rc.d, and /etc/apt/sources.list in the newly created chroot environment. The schroot configuration /etc/schroot/chroot.d/sid-amd64-sbuild-$suffix for this newly created chroot is created in the host system as:

[sid-amd64-sbuild]
description=Debian sid/amd64 autobuilder
groups=root,sbuild
root-groups=root,sbuild
profile=sbuild
type=directory
directory=/srv/chroot/sbuild-createchroot
union-type=overlay

Now for a brief explanation on what these commands do.

  1. Install sbuild and other useful packages onto the system.
  2. Create the sbuild template configuration to your home folder. (This example is setting up sbuild for personal use, instead of as part of a build server.)
    1. This setting allows you to avoid long commandline options for typical workflow needs and run all post-build tests.
    2. Adjust parallel=5 to match your system resources.

    3. Setting the $run_lintian variable to 0 instead will disable running of lintian.

    4. Setting the $run_piuparts variable to 0 instead will disable running piuparts.

      1. '--no-eatmydata' for piuparts is needed when you configure schroot with "command-prefix=eatmydata" in /etc/schroot/chroot.d/unstable-amd64-sbuild-*.

    5. Setting the $run_autopkgtest variable to 0 instead will disable running autopkgtest.

    6. See the sbuild.conf manpage for more options.

  3. Update the active user group set to include sbuild.
    1. This will add your username so that it may use the sbuild command. Additional users may be added by running sudo sbuild-adduser USER1 USER2 .... sbuild-adduser will prompt you to copy the template sbuild configuration in /usr/share/doc/sbuild/examples/example.sbuildrc to each user's ~/.sbuildrc, to be used as their user sbuild configuration. You can customize sbuild settings here, but you usually won't need to customize anything. This should be done once per user.

  4. Use sbuild-createchroot to create a chroot used by sbuild meant for building packages targeting Debian unstable main and configured to be compatible with apt-cacher-ng. (See AptCacherNg )

    • Use of classic mirror server URLs such as http://ftp.us.debian.org instead of its modern http://deb.debian.org is intentional choice to avoid 986356 for apt-cacher-ng.

      • The chroot is saved in /srv/chroot/unstable-amd64-sbuild. It installs the packages ccache and eatmydata in the chroot in case you want to use some of the enhancements detailed below. The apt repository used is the mirror service http://ftp.us.debian.org/debian through apt-cacher-ng which will choose a suitable local mirror automatically. This can be changed to use a URL for a different mirror of the Debian archive. You can run this command once per distribution you want, and pass # --arch=i386 to create a chroot for a different architecture (the default is your host architecture).

        Each post build package test feature can be turned off by changing the corresponding variable to 0 .

Updating chroot manually

The chroot should be up-to-date before building packages. Use the sbuild-update to perform updates.

   1 sudo sbuild-update -udcar u

The arguments '-udcar' will tell sbuild-update to run an apt-get update, dist-upgrade, clean, autoclean, and autoremove in the chroot. "u" stands for unstable

All sbuild chroots built with sbuild-createchroot are created by schroot and will have a suffix of '-sbuild'. Thus to find the names of all sbuild chroots, run the following.

   1 schroot -l | grep sbuild

You can also pass --apt-update --apt-distupgrade to the individual sbuild invocation to update the temporary copy of the build chroot, but this won't cause any changes to happen in the persistent copy of the chroot (in the .tar.gz file). So if you are building more than once, you should run sbuild-update instead of relying on this.

Building packages

With properly configured ~/.sbuildrc as above, you can imply run the following to build a package from the source directory of a debianized package.

   1 sbuild

Alternatively, you may pass in the '.dsc' file of a package generated by dpkg-buildpackage, git-buildpackage, and so forth so that it may be built with sbuild. For example, to build sbuild from its '.dsc' file, do the following.

   1 sbuild sbuild_*.dsc

Integration with gbp (gbp-buildpackage)

Sbuild can be integrated into gbp's workflow with little effort with properly configured ~/.sbuildrc as above with ~/.gbp.conf which includes:

[DEFAULT]
# the default build command:
builder = sbuild

(You can alternatively specify --git-builder=sbuild option to gbp command.)

Then, you can build package for normal source only upload and for source and binary upload just with:

   1 gbp buildpackage

More information on git packaging at PackagingWithGit

Speeding up build process

Consider configuring sbuild/schroot with tmpfs or eatmydata. Otherwise, running dpkg especially by adt-run will slow the build a lot. (If modern fast NVMe SSD is used as storage device, you may not see much speed differences as you see with HDD.)

sbuild with eatmydata

Edit the corresponding /etc/schroot/chroot.d/$dist-$arch-sbuild-$suffix to append the line to use eatmydata:

command-prefix=eatmydata

Note that piuparts invokes eatmydata by default and nested eatmydata invocations don't work. To deal with this pass --no-eatmydata to piuparts in your ~/.sbuildrc, or set up a separate schroot profile for piuparts as described above.

sbuild with tmpfs

You could configure /etc/fstab to mount all short term contents on tmpfs. (Added bonus: less access to precious SSD.)

# For speeding up sbuild/schroot and prevent SSD wear-out
none /var/lib/schroot/session        tmpfs uid=root,gid=root,mode=0755 0 0
none /var/lib/schroot/union/overlay  tmpfs uid=root,gid=root,mode=0755 0 0
none /var/lib/sbuild/build           tmpfs uid=sbuild,gid=sbuild,mode=2770 0 0

Using "ccache" with sbuild

ccache is a compiler wrapper that will cache compilation results (produced object files) from gcc and g++; if you repeatedly compile the same source code (or parts of it), ccache will greatly shorten compilation times by avoiding recompilation of files that it has cached earlier.

This is especially useful during package development, when you might have to rebuild a package with a long compilation phase several times. It is also effective with packages that are frequently updated, because often only a few files actually change during updates to a software.

In order to prepare your sbuild environment for ccache, first perform the following setup in the host environment (i.e., outside the chroot), as user root:

   1 dir=/var/cache/ccache-sbuild
   2 install --group=sbuild --mode=2775 -d $dir
   3 env CCACHE_DIR=$dir ccache --max-size 4G
   4 cat >>/etc/schroot/sbuild/fstab <<END
   5 $dir $dir none rw,bind 0 0
   6 END

This assumes that you trust all members of the sbuild group.

It is perfectly fine to share the cache among chroots, even for different architectures. ccache honours the compiler name, size and timestamp as well as the command line when calculating hash values. At least one of these will differ between builds of the same file for different architectures.

Next place the following script into $dir/sbuild-setup:

   1 cat >$dir/sbuild-setup <<END
   2 #!/bin/sh
   3 export CCACHE_DIR=$dir
   4 export CCACHE_UMASK=002
   5 export CCACHE_COMPRESS=1
   6 unset CCACHE_HARDLINK
   7 export PATH="/usr/lib/ccache:\$PATH"
   8 exec "\$@"
   9 END

and make it executable:

   1 chmod a+rx $dir/sbuild-setup

Then for each chroot ($dist-$arch-sbuild) where you want to enable ccache

  1. Install ccache inside the chroot by running

       1  sudo sbuild-shell $dist-$arch
       2  apt-get install ccache
       3  exit
    
  2. and edit the corresponding configuration file in /etc/schroot/chroot.d/ by appending the line

     command-prefix=/var/cache/ccache-sbuild/sbuild-setup

    (Multiple command-prefix can be joined with commas, in case you already have one configured; see eatmydata below.)

Using eatmydata and ccache with sbuild

If you want to combine eatmydata with the ccache instructions from above then use:

command-prefix=/var/cache/ccache-sbuild/sbuild-setup,eatmydata

Basic tips

Delete a chroot

   1 sudo rm -r /srv/chroot/unstable-amd64-sbuild/
   2 sudo rm /etc/schroot/chroot.d/unstable-amd64-sbuild-* /etc/sbuild/chroot/unstable-amd64-sbuild

Also see sbuild-destroychroot(1).

Cleaning up schroot session

Sometimes you can end up with dangling chroot sessions potentially taking up valuable system resources (find them with `schroot -l --all`). This command is useful:

   1 sudo schroot --end-session --all-sessions

Customizations of sbuild chroots

Sometimes it is desirable to further customize your sbuild chroot environment (type=directory) permanently. Typical customizations done are installing more packages inside the chroot, modifying /etc/apt/sources.list, and installing custom scripts to be run inside the chroot.

You start a root shell prompt inside the unstable chroot.

   1 sudo sbuild-shell u

Here, "u" is short for "unstable". You can specify longer form such as unstable-amd64 here, too.

This starts a schroot session for source:unstable-$arch-sbuild. Any modifications done inside the chroot will be saved upon exiting. Inside this chroot, you may run apt-get commands to install or remove packages as desired. For example, to install ccache, do the following in the chroot session.

   1 apt-get install ccache
   2 exit

Modifications to /etc/apt/sources.list inside the unstable chroot can be done from outside the chroot with root privileges using your favorite editor as:

   1 sudo -e /srv/chroot/unstable-amd64-sbuild/etc/apt/sources.list

Proceed to edit the sources.list file as you see fit, then save.

To add scripts inside the chroot, simply place the scripts in the directory /srv/chroot/unstable-amd64-sbuild/usr/local/bin/

Be sure to make the scripts executable.

   1 sudo chmod a+x /srv/chroot/unstable-amd64-sbuild/usr/local/bin/*

Other modifications may be done to the chroot, either by running commands available within the chroot session, or by running commands with root privileges via the secondary terminal session. Once you are done making modifications to the chroot, simply exit the session. Inside the chroot session, do the following.

   1 exit

After exiting, your modifications will be saved and made available for every new chroot session created afterwards.

Think negative impacts of modifications to the chroot environment used by the sbuild command before making modifications to it. If you simply want to have a chroot environment with many pre-loaded packages for debugging packages, it is better to set up a custom chroot environment using Schroot directly and use it.

Advanced Tips

Cross compiling

sbuild also supports cross-compiling a package to build for a different processor architecture e.g arm64 or ppc64el etc( if a package has an arch:all package option, then there's no point trying to cross build, since that's already arch independent): to build a package which is e.g. only buildable on mips, in the amd64 chroot from the above example, you can use:

   1 sbuild --host=mips

To build packages available from the apt repositories used in the sbuild chroot, just pass in a package name (older versions of sbuild required $package_$version). For example to build the latest sbuild:

   1 sbuild -d unstable sbuild

Everything needed to build the latest sbuild version will be downloaded from the repositories and will be saved in your current directory after building of the packages is finished.

External Commands

sbuild supports running external commands at various stages of the build process. This is useful for cases such as running a script inside the chroot after it has been setup. As an example, to run a script in /usr/local/bin/myscript, edit the $external_commands in the sbuild configuration file ~/.sbuildrc as follows.

   1 $external_commands = {
   2                         'post-build-commands' => [],
   3                         'chroot-setup-commands' => ['/usr/local/bin/myscript'],
   4                         'chroot-cleanup-commands' => [],
   5                         'pre-build-commands' => []
   6                       };

sbuild can also translate certain percent escaped keywords for external commands during certain portions of a build. For example, in post build commands, %SBUILD_CHANGES is changed to the path of the '.changes' file for a successfully built package.

Here is an example of adding a post build command to run /usr/local/bin/postbuildscript with %SBUILD_CHANGES as an argument.

   1 $external_commands = {
   2                         'post-build-commands' => ['/usr/local/bin/postbuildscript', '%SBUILD_CHANGES'],
   3                         'chroot-setup-commands' => ['/usr/local/bin/myscript'],
   4                         'chroot-cleanup-commands' => [],
   5                         'pre-build-commands' => []
   6                       };

See the 'EXTERNAL COMMANDS' section of the sbuild man page for more information on external commands.

Enabling experimental

The Debian experimental repository can be added dynamically on top of an existing unstable chroot during each sbuild run that requires experimental. You can use either the aspcud resolver (in use on the experimental buildds) or aptitude (used by *-backports).

   1 sbuild --extra-repository='deb http://deb.debian.org/debian experimental main' --build-dep-resolver=aspcud mypkg.dsc

or

   1 sbuild --extra-repository='deb http://deb.debian.org/debian experimental main' --build-dep-resolver=aptitude mypkg.dsc

Another possibility is to have a dedicated ~/.sbuildrc.experimental configuration file and run sbuild via

   1 SBUILD_CONFIG=~/.sbuildrc.experimental sbuild mypkg.dsc

with ~/.sbuildrc.experimental containing for example:

   1 $extra_repositories = [ 'deb http://deb.debian.org/debian experimental main' ];
   2 $build_dep_resolver = 'aptitude'; 

If you need to test a build against a versioned Build-Depends from experimental, you can add --add-depends:

   1 sbuild --extra-repository='deb http://deb.debian.org/debian experimental main' --build-dep-resolver=aspcud --add-depends='foo-dev (>= 1.2.3-4)' mypkg.dsc

Build for experimental

If you want to build for unstable but upload to experimental. Use schroot -l --all-source-chroots to get the name of the chroot (unstable-amd64-sbuild in this case).

   1 sbuild -d experimental -c unstable-amd64-sbuild mypkg.dsc

Alternatively, if you know that you always want to build your packages for experimental in a sid chroot, just add experimental as an alias of your sid schroot to your sid schroot configuration:

aliases=experimental

Enabling incoming.debian.org

Another useful repository to add as --extra-repository option is deb http://incoming.debian.org/debian-buildd/ buildd-unstable main in case you want to build or do a new upload before the next dinstall

   1 sbuild --extra-repository='deb http://incoming.debian.org/debian-buildd/ buildd-unstable main' mypkg.dsc

Disabling network access for dpkg-buildpackage

Using iptables

<!> This doesn't seem to work with recent sbuild (2016/05)

Source packages must be buildable without accessing any remote machines. On the other hand, the build process needs network access for the installation of the build dependencies. Conveniently, the build dependencies are installed by the "root" user while dpkg-buildpackage is run under fakeroot by the user running sbuild. So the following will deny any network access during the build process through blocking traffic originating from any process owned by the sbuild group while the root user will still have network access:

   1 sudo iptables -I OUTPUT -m owner --gid-owner sbuild ! -d 127.0.0.0/8 -j DROP
   2 sudo -u sbuild sbuild mypkg.dsc

A better fix would be if schroot allowed to unshare the network namespace for the dpkg-buildpackage invocation. See bugs 802850 and 802849

Using linux network namespaces

As an alternative, you can also use linux network namespace to isolate sbuild. In its most basic form, it will create a namespace with only the loopback interface (in a down state). This means no network access outside the namespace. Your dependencies must already be installed in the chroot. The main drawback of this method is that it requires root privileges.

Run the following to build your package without network access:

   1 sudo ip netns add no-net
   2 sudo ip netns exec no-net sbuild --no-apt-update --no-apt-upgrade --no-apt-distupgrade mypkg.dsc

A more elaborate setup could include a pair of peer interfaces, shared between the main and no-net namespace, without default routes, fetching packages from a local proxy.

Using aliases

In Debian, an unstable chroot is used for building in a number of situations like building an unpacked source package with UNRELEASED in debian/changelog or building packages for experimental. Furthermore, distributions have alternative names like sid/unstable or experimental/rc-buggy. Sbuild selects the chroot to use either from debian/changelog (so it would be nice if UNRELEASED would trigger a build in an unstable chroot) or through the -d option which also sets the Distribution value in the resulting .changes file (so it would be handy if saying -d sid were enough and one wouldn't have to use the -c option to type unstable-amd64-sbuild manually). All of this can be solved by using schroot aliases. My sid schroot config says:

aliases=UNRELEASED,sid,rc-buggy,experimental

This means, that this schroot will be used for packages having UNRELEASED in their debian/changelog, for packages I build with -d sid (because writing out unstable is too long) as well as for packages I build for experimental.

Adding extra packages

It is often necessary to add extra binary packages as build dependencies. For example, you might want to make a package available as a build dependency that is waiting in the NEW queue and so isn't available from the mirrors. To do this, use the --extra-package=./foo.deb option to sbuild.

You might find that the output from the resolver is not helpful in determining which extra package you need to make available. In this case, it can be useful to pass --build-dep-resolver=aptitude which tends to provide more useful output (though you should remove it once you've figured out the problem).

Remote build servers

One advantage of cowbuilder over sbuild is that it supports offloading builds to a remote server with cowpoke. Unfortunately, that command is specifically crafted for cowbuilder, so you need something else for sbuild.

The trick is to create a source package and transfer it to the remote machine for building. The latter can be done with dcmd. Example:

   1 dpkg-buildpackage -S
   2 dcmd scp ../foo-1.0.dsc example.net:build-area
   3 ssh example.net sbuild build-area/foo-1.0.dsc

Validate package cleanup

Packages will fail to build twice in a row if the clean target of debian/rules do not restore the source directory to its initial state. Adding the following to your ~/.sbuildrc will help you to detect modifications:

$external_commands = {
    "starting-build-commands" => [
        'bash -c \'find %SBUILD_PKGBUILD_DIR -print0 |
                  sort -z |
                  while read -d $\'\\\'\'\0\'\\\'\' file; do
                      echo -n "$(stat -c "%n %F %%s" "${file}") "
                      if [ -f "${file}" ]; then
                          sha256sum "${file}" |
                              cut -d " " -f 1
                      else
                              echo
                      fi
                  done > /tmp/file-list.pre-build\''
    ],
    "chroot-cleanup-commands" => [
        'cd %SBUILD_PKGBUILD_DIR && ./debian/rules clean',
        'bash -c \'find %SBUILD_PKGBUILD_DIR -print0 |
                  sort -z |
                  while read -d $\'\\\'\'\0\'\\\'\' file; do
                      echo -n "$(stat -c "%n %F %%s" "${file}") "
                      if [ -f "${file}" ]; then
                          sha256sum "${file}" |
                              cut -d " " -f 1
                      else
                              echo
                      fi
                  done > /tmp/file-list.post-build\'',
        'diff /tmp/file-list.pre-build /tmp/file-list.post-build'
    ]
};

Associated schroot environment for development

For development, creating the latest minimal unstable chroot environment to execute programs in unstable environment as sbuild does is time consuming. Let’s create an associated package pre-loaded unstable chroot shell environment and use it directly from the schroot command. (This assumes you have already created chroot environment as above.)

   1 $ sudo cp -a /srv/chroot/unstable-amd64-sbuild-$suffix /srv/chroot/unstable-amd64-dev
   2 $ sudo cp -a /etc/schroot/desktop /etc/schroot/dev
   3 $ sudo tee /etc/schroot/chroot.d/unstable-amd64-dev << EOF
   4 [unstable-dev]
   5 description=Debian unstable/amd64 chroot development environment
   6 groups=root,sbuild
   7 root-groups=root,sbuild
   8 source-groups=root,sbuild
   9 source-root-groups=root,sbuild
  10 profile=dev
  11 type=directory
  12 preserve-environment=true
  13 directory=/srv/chroot/unstable-amd64-dev
  14 union-type=overlay
  15 command-prefix=eatmydata
  16 EOF

Let’s install basic build environment packages to this chroot in /srv/chroot/unstable-amd64-dev.

   1 $ cd /
   2 $ sudo schroot -c source:unstable-dev -u root
   3 (unstable-dev)root@hostname:/# apt update; apt full-upgrade
   4 (unstable-dev)root@hostname:/# apt install aptitude vim nano- mc devscripts sudo gitk
   5 (unstable-dev)root@hostname:/# exit

Let's further customize mount points by editing /etc/schroot/osamu/fstab as needed. Let's also copy setting from the host PC to the chroot as needed.

Let's add 2 shell alias definitions to ~/.bashrc on the host system as follows and enable convenient access to this chroot environment.

alias devs="schroot -c source:unstable-dev"
alias devx="xhost +si:localuser:$(id -un) ; schroot -c chroot:unstable-dev ; xhost -"

Missing space in /build and /srv/chroot

It is possible that you lack space for builds even if /srv/chroot has plenty of space. This can happen at build time on large packages (e.g. Libreoffice) because sbuild decompresses the packages in /build in the chroot, which is a bind mount to /var/lib/sbuild/build. If you are on a workstation where /var is shared with the root partition, you may sometimes not have enough space for the largest packages. The symptom will be an error message like this:

E: Disc space is probably not sufficient for building.
I: Source needs 2703644 KiB, while 4089748 KiB is free.)

But then when you actually look at the df, you have plenty of space! This happens because sbuild cleans up after itself on failure and gives back the disk space. If you follow disk space usage more closely during the build, you will notice that /var will take up more and more space until that failure.

A workaround for this is to change the configuration of the /build bind mount. This is done in /etc/schroot/sbuild/fstab. For example, the following configuration uses /home/build instead:

# Mount a large scratch space for the build, so we don't use up
# space of the chroot itself.
#/var/lib/sbuild/build  /build   none    rw,bind         0       0
/home/build  /build   none    rw,bind         0       0

If /srv/chroot lacks space but some other directory has plenty of space, you can make space by adding the similar bind mount from the other directory to /srv/chroot.


CategoryPackaging