Immutable root with atomic upgrades: Difference between revisions

From Alpine Linux
No edit summary
mNo edit summary
(26 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{|style="width: 33em; padding:2px; margin:0; margin-bottom:10px; background-color:#f6f6f6; border:1px solid #aaa; -moz-border-radius-bottomright: 0.5em; -moz-border-radius-bottomleft: 1em; border-radius-bottomright: 0.5em; border-radius-bottomleft: 1em; -webkit-border-bottom-right-radius: 0.5em; -webkit-border-bottom-left-radius: 1em;"
|<div style="font-size: 1.5em; font-weight:bold;"> [[Image:Underconstruction_clock_icon_gray.svg‎|64px|left|link=]] This page is a work in progress ... </div><p style="text-align: center; font-size: 87%;">This page is still being developed.</p>
|}
=== What? ===
=== What? ===
This article provides a basic guide to setting up a read-only-root-based Alpine Linux system with several boot environments and atomic upgrades using rEFInd and btrfs.
This article provides a basic guide to setting up a read-only-root-based Alpine Linux system with several boot environments and atomic upgrades using rEFInd and btrfs.
=== Why? ===
=== Why? ===
Read-only root and atomic upgrades with ability to easily rollback or boot previous configurations is a concept that got some popularity recently. Distributions providing and promoting such features, for example, are [https://silverblue.fedoraproject.org/ Fedora Silverblue], [https://microos.opensuse.org/ Opensuse MicroOS], [https://nixos.org NixOS] and [https://guix.gnu.org GNU Guix].
Read-only root and atomic upgrades with ability to easily rollback or boot previous configurations is a concept that got some popularity recently. Distributions providing and promoting such features, for example, are [https://silverblue.fedoraproject.org/ Fedora Silverblue], [https://microos.opensuse.org/ Opensuse MicroOS], [https://nixos.org NixOS] and [https://guix.gnu.org GNU Guix].
While Alpine Linux has it's killer features it lacks mentioned above ones on default setup. This is a proof of concept that it's possible to implement them in a minimal way on a minimal system.
While Alpine Linux has it's killer features it lacks mentioned above ones on default setup. This is a proof of concept that it's possible to implement them in a minimal way on a minimal system.
{{Note|Alpine Linux can also boot from RAM in '''diskless mode''' (see [[Installation]]) which supports preserving changes between reboots using [[lbu]].}}
= Preparation =
You should have bootable Alpine media. The process to obtain it decribed on the [[Installation|installation page.]]
{{Warning|Since version available in Alpine repositories lacks btrfs driver you should download rEFInd on [https://www.rodsbooks.com/refind/getting.html the official website] and copy it to installation media}}
= Partitioning disks =
= Partitioning disks =
In this guide it is assumed that you have a fresh UEFI system without OS and just managed to boot into live Alpine using USB flash drive or CD.
In this guide it is assumed that you have a fresh UEFI system without OS and just managed to boot into live Alpine using USB flash drive or CD.
Line 42: Line 45:
Start with following directories:<br>
Start with following directories:<br>
<pre># mkdir /mnt/next</pre>
<pre># mkdir /mnt/next</pre>
Stores next <code>current</code> link.<br>
Stores next <code>current</code> link, is necessary due to how busybox <code>mv</code> does atomic link replacement.<br>
<pre># mkdir /mnt/commons</pre>
<pre># mkdir /mnt/commons</pre>
Stores common non-snapshotting subvolumes, is necessary due to how busybox <code>mv</code> does atomic link replacement.<br>
Stores common non-snapshotting subvolumes.<br>
We may populate it right away:
We may populate it right away:
<pre># btrfs subvolume create /mnt/commons/@var@tmp
<pre># btrfs subvolume create /mnt/commons/@var@tmp
Line 52: Line 55:
If you use flatpak, you may also want to keep it's directory separate:
If you use flatpak, you may also want to keep it's directory separate:
<pre># btrfs subvolume create /mnt/commons/@var@lib@flatpak</pre>
<pre># btrfs subvolume create /mnt/commons/@var@lib@flatpak</pre>
Include anything else in <code>/var</code> that should be mutable, for example:
<pre># btrfs subvolume create /mnt/commons/@var@lib@iwd</pre>
Next, most important directories:
Next, most important directories:
<pre># mkdir /mnt/snapshots</pre>
<pre># mkdir /mnt/snapshots</pre>
Line 59: Line 64:
Let's create first generation and populate it with one OS root snapshot <code>@</code>:
Let's create first generation and populate it with one OS root snapshot <code>@</code>:
<pre># NEWSNAPSHOTS="$(date -u +"%Y%m%d%H%M%S")$(cat /dev/urandom | tr -dc 'a-zA-Z' | fold -w 8 | head -n 1)"
<pre># NEWSNAPSHOTS="$(date -u +"%Y%m%d%H%M%S")$(cat /dev/urandom | tr -dc 'a-zA-Z' | fold -w 8 | head -n 1)"
# mkdir "/mnt/$NEWSNAPSHOTS"
# mkdir "/mnt/snapshots/$NEWSNAPSHOTS"
# btrfs subvolume create /mnt/$NEWSNAPSHOTS/@</pre>
# btrfs subvolume create /mnt/snapshots/$NEWSNAPSHOTS/@</pre>
Populate <code>links</code>:
Populate <code>links</code>:
<pre># NEWLINKS="$(date -u +"%Y%m%d%H%M%S")$(cat /dev/urandom | tr -dc 'a-zA-Z' | fold -w 8 | head -n 1)"
<pre># NEWLINKS="$(date -u +"%Y%m%d%H%M%S")$(cat /dev/urandom | tr -dc 'a-zA-Z' | fold -w 8 | head -n 1)"
Line 84: Line 89:
UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 /var/log btrfs subvol=/commons/@var@log,rw,noatime 0 0
UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 /var/log btrfs subvol=/commons/@var@log,rw,noatime 0 0
UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 /var/lib/flatpak btrfs subvol=/commons/@var@lib@flatpak,rw,noatime 0 0
UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 /var/lib/flatpak btrfs subvol=/commons/@var@lib@flatpak,rw,noatime 0 0
UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 /var/lib/iwd btrfs subvol=/commons/@var@lib@iwd,rw,noatime 0 0
UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 /home btrfs subvol=/commons/@home,rw,noatime 0 0
UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 /home btrfs subvol=/commons/@home,rw,noatime 0 0
# UUID=2FE6-837A /boot/efi vfat rw,noatime,discard 0 2
# UUID=2FE6-837A /boot/efi vfat rw,noatime,discard 0 2
Line 96: Line 102:
| | |--@var@log
| | |--@var@log
| | |--@var@lib@flatpak
| | |--@var@lib@flatpak
| | |--@var@lib@iwd
| | |--@home
| | |--@home
| |--current
| |--current
Line 109: Line 116:
| | |--20210411212549sdBXyLxg
| | |--20210411212549sdBXyLxg
| | | |--@</pre>
| | | |--@</pre>
= Base system install =
= Base system install =
With the directory strtucture prepared we can start installation of a basic Alpine Linux system.<br>
With the directory strtucture prepared we can start installation of a basic Alpine Linux system.<br>
Line 118: Line 126:
# mount -o bind /dev $SNP/dev
# mount -o bind /dev $SNP/dev
# mount -t proc none $SNP/proc
# mount -t proc none $SNP/proc
# mount -o bind /sys $SNP/sys
# mount -t sysfs sys $SNP/sys
 
# sed "s#CURRENT_SNAPSHOTS_PATH#/snapshots/20210411212549sdBXyLxg#g" /mnt/fstab > "/mnt/snapshots/20210411212549sdBXyLxg/@/etc/fstab"
 
# cp -L /etc/resolv.conf /mnt/etc/
# chroot /mnt /bin/sh
 
# mount -a
 
# mv /etc/resolv.conf /tmp/
# ln -s /tmp/resolv.conf /etc/resolv.conf</pre>
 
As soon as you in chroot, define repositories:
<pre># echo "https://dl-cdn.alpinelinux.org/alpine/latest-stable/main" > /etc/apk/repositories</pre>
Example shows only <code>main</code>, but you should also add <code>testing</code> and <code>community</code> if you need any packages in those.<br>
Now it's time for firmware, kernel and btrfs packages:
<pre># apk add -U linux-firmware linux-lts btrfs-progs</pre>
You may want to change <code>linux-firmware</code> to a custom set of firmware packages suitable for you system, for example <code>linux-firmware-amd linux-firmware-amd-ucode linux-firmware-amdgpu linux-firmware-ath10k linux-firmware-qca</code> for typical AMD laptop.<br>
It is also important to add <code>btrfs</code> feature to <code>mkinitfs.conf</code> and run <code>mkinitfs</code> manually:
<pre># vi /etc/mkinitfs/mkinitfs.conf
# mkinitfs</pre>
These steps prepare kernel and generate <code>initramfs</code> which later will be used to boot from our first snapshot.<br>
After that you should install any package you may need on first boot.
 
{{Warning|In case your PC only has wireless connection you should also install any suitable networking software, like <code>iwd</code> in this example, so you will not end up severed from network on your first boot.}}
 
{{Note|Due to root being immutable during operation, it's recommended to install package <code>openresolv</code> to support changing network connection. In this case <code>/etc/resolvconf.conf</code> should have <code>resolv_conf{{=}}/tmp/resolv.conf</code>, <code>/etc/resolv.conf</code> should be moved to <code>/tmp/resolv.conf</code> and a link to the new resolv.conf location should be created: <code>ln -sfn /tmp/resolv.conf /etc/resolv.conf</code>.
You may also use static DNS, but this would make your network activity directly identifiable to the DNS server provider, therefore it's not recommended.
}}
 
Now, configure the system, start with setting a password for the root:
<pre># passwd root</pre>
 
With the snapshot prepared and configured we can chroot out of it and unmount everything:
<pre># umount -a
# exit</pre>
 
Finish editing snapshot by setting <code>ro</code> flag and unmounting root volume:
<pre># btrfs property set -ts "/mnt/snapshots/20210411212549sdBXyLxg/@" ro true
# umount /mnt</pre>
 
= Bootloader installation =
{{Note|The example demonstrated here only make use of rEFInd bootloader as it is relatively easy to install manually and generally easy to use. You may however setup any prefered bootloader given it supports btrfs and can be configured to boot specific snapshot.}}
Mount the EFI partition:
<pre># mount -t vfat /dev/sda1 /mnt
# mkdir /mnt/EFI</pre>
Unpack prepared rEFInd archive and copy relevant files to <code>/mnt/EFI/</code>
<pre># unzip refind-bin-version.zip
# cp -r refind-bin-version/refind /mnt/EFI/
# cd /mnt/EFI/refind</pre>
Delete all unnecessary files - everything that is not for your CPU architecture:
<pre># rm -r drivers_aa64 drivers_ia32 tools_aa64 tools_ia32 refind_aa64.efi refind_ia32.efi</pre>
Rename config file and edit it:
<pre># mv refind.conf-sample refind.conf
# vi refind.conf</pre>
And append following to the end of the file, remember to replace example UUIDs with your own for <code>root</code> (btrfs partition) and <code>resume</code> (swap partition):
<pre>
menuentry "Alpine Linux" {
    icon /EFI/refind/icons/os_linux.png
    volume "ROOT"
    loader /current/0/@/boot/vmlinuz-lts
    initrd /current/0/@/boot/initramfs-lts
    options "root=UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 rootfstype=btrfs rootflags=subvol=/current/0/@ resume=UUID=f0239163-9d46-47c1-67a4-3ee1d63d0676 ro,noatime quiet splash"
 
    submenuentry "Boot fallback 1" {
        loader /current/1/@/boot/vmlinuz-lts
        initrd /current/1/@/boot/initramfs-lts
        options "root=UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 rootfstype=btrfs rootflags=subvol=/current/1/@ resume=UUID=f0239163-9d46-47c1-67a4-3ee1d63d0676 ro,noatime quiet splash"
    }
 
    submenuentry "Boot fallback 2" {
        loader /current/2/@/boot/vmlinuz-lts
        initrd /current/2/@/boot/initramfs-lts
        options "root=UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 rootfstype=btrfs rootflags=subvol=/current/2/@ resume=UUID=f0239163-9d46-47c1-67a4-3ee1d63d0676 ro,noatime quiet splash"
    }
 
    submenuentry "Boot fallback 3" {
        loader /current/3/@/boot/vmlinuz-lts
        initrd /current/3/@/boot/initramfs-lts
        options "root=UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 rootfstype=btrfs rootflags=subvol=/current/3/@ resume=UUID=f0239163-9d46-47c1-67a4-3ee1d63d0676 ro,noatime quiet splash"
    }
}</pre>
{{Note|<code>"ROOT"</code> is the <code>PARTLABEL</code> of the btrfs partition. You may also use <code>PARTUUID</code> instead. To get both <code>blkid</code> from <code>blkid</code> package can be used. <code>blkid</code> included in busybox does not provide this information. }}
To add rEFInd to UEFI, <code>efibootmgr</code> is a suitable tool:
<pre># apk add efibootmgr
# efibootmgr --create --disk /dev/sda --part 1 --loader /EFI/refind/refind_x64.efi --label "rEFInd" --verbose</pre>
<code>/dev/sda</code> is our disk device and <code>1</code> is the number of partition containing <code>rEFInd</code>.
 
= Updating or altering the system =
<pre># touch /sbin/sysmut
# chmod +x /sbin/sysmut
# vi /sbin/sysmut</pre>
 
Example script to mutate the the system:


# mkdir -p $SNP/var/tmp
<pre>#!/bin/sh
# mount /mnt/commons/@var@tmp $SNP/var/tmp
ROOTVOLMNT="/vol/root" && \
mkdir -p "$ROOTVOLMNT" && \
mount -t btrfs -o rw,noatime UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 "$ROOTVOLMNT" && \
NEWSNAPSHOTS="$(date -u +"%Y%m%d%H%M%S")$(cat /dev/urandom | tr -dc 'a-zA-Z' | fold -w 8 | head -n 1)" && \
mkdir -p "$ROOTVOLMNT/snapshots/$NEWSNAPSHOTS" && \
btrfs subvolume snapshot "$ROOTVOLMNT/current/0/@" "$ROOTVOLMNT/snapshots/$NEWSNAPSHOTS/@" && \
sed "s#CURRENT_SNAPSHOTS_PATH#/snapshots/$NEWSNAPSHOTS#g" "$ROOTVOLMNT/fstab" > "$ROOTVOLMNT/snapshots/$NEWSNAPSHOTS/@/etc/fstab" && \
mount -t proc none "$ROOTVOLMNT/snapshots/$NEWSNAPSHOTS/@/proc" && \
mount -t sysfs sys "$ROOTVOLMNT/snapshots/$NEWSNAPSHOTS/@/sys" && \
mount -o bind /dev "$ROOTVOLMNT/snapshots/$NEWSNAPSHOTS/@/dev" && \
chroot "$ROOTVOLMNT/snapshots/$NEWSNAPSHOTS/@" /bin/sh -c 'mount -a; sh; APPLY=$?; umount -a; exit $APPLY' && \
btrfs property set -ts "$ROOTVOLMNT/snapshots/$NEWSNAPSHOTS/@" ro true && \
NEWLINKS="$(date -u +"%Y%m%d%H%M%S")$(cat /dev/urandom | tr -dc 'a-zA-Z' | fold -w 8 | head -n 1)" && \
mkdir -p "$ROOTVOLMNT/links/$NEWLINKS" && \
ln -s "../../snapshots/$NEWSNAPSHOTS" "$ROOTVOLMNT/links/$NEWLINKS/0" && \
cp -P "$ROOTVOLMNT/current/0" "$ROOTVOLMNT/links/$NEWLINKS/1" && \
cp -P "$ROOTVOLMNT/current/1" "$ROOTVOLMNT/links/$NEWLINKS/2" && \
cp -P "$ROOTVOLMNT/current/2" "$ROOTVOLMNT/links/$NEWLINKS/3" && \
mkdir -p "$ROOTVOLMNT/next" && \
ln -sfn "./links/$NEWLINKS" "$ROOTVOLMNT/next/current" && \
mv "$ROOTVOLMNT/next/current" "$ROOTVOLMNT/" \
&& echo "Switched to the new snapshots" \
|| echo "Changes discarded"
umount "$ROOTVOLMNT"</pre>


# mkdir -p $SNP/var/cache
It will get you into the root shell chrooted into the new snapshot, where you can apply any change you like.<br>
# mount /mnt/commons/@var@cache $SNP/var/cache
If chroot shell exits with an error, there will be no switch to the new snapshots. This means you can manually discard changes while in the chroot by:


# mkdir -p $SNP/var/log
<pre># exit 1</pre>
# mount /mnt/commons/@var@log $SNP/var/log


# mkdir -p $SNP/var/lib/flatpak
= Deleting unused snapshots =
# mount /mnt/commons/@var@lib@flatpak $SNP/var/lib/flatpak
Unused snapshots can be garbage-collected by:


# mkdir -p $SNP/home
<pre># touch /sbin/syscln
# mount /mnt/commons/@home $SNP/home
# chmod +x /sbin/syscln
# vi /sbin/syscln</pre>


# cp -L /etc/resolv.conf /mnt/etc/
<pre>#!/bin/sh
# chroot /mnt /bin/sh</pre>
ROOTVOLMNT="/vol/root"
mkdir -p "$ROOTVOLMNT"
mount -t btrfs -o rw,noatime UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 "$ROOTVOLMNT"
 
SNAPSHOTS=$({ \
    find "$ROOTVOLMNT/snapshots/" -maxdepth 1 -mindepth 1
    find "$ROOTVOLMNT/current/" -maxdepth 1 -mindepth 1 \
        | xargs -n 1 readlink -f
} | sort | uniq -u)
 
if [ -z "$SNAPSHOTS" ]; then
    echo "Nothing to remove"
else
    printf %s\\n "$SNAPSHOTS" \
        | tr \\n \\0 \
        | xargs -r -0 -n 1 -I {} find {} -maxdepth 1 -mindepth 1 \
        | tr \\n \\0 \
        | xargs -r -0 btrfs subvolume delete
    printf %s\\n "$SNAPSHOTS" \
        | tr \\n \\0 \
        | xargs -r -0 rm -r
fi
 
umount "$ROOTVOLMNT"</pre>

Revision as of 07:47, 3 September 2021

What?

This article provides a basic guide to setting up a read-only-root-based Alpine Linux system with several boot environments and atomic upgrades using rEFInd and btrfs.

Why?

Read-only root and atomic upgrades with ability to easily rollback or boot previous configurations is a concept that got some popularity recently. Distributions providing and promoting such features, for example, are Fedora Silverblue, Opensuse MicroOS, NixOS and GNU Guix.

While Alpine Linux has it's killer features it lacks mentioned above ones on default setup. This is a proof of concept that it's possible to implement them in a minimal way on a minimal system.

Note: Alpine Linux can also boot from RAM in diskless mode (see Installation) which supports preserving changes between reboots using lbu.

Preparation

You should have bootable Alpine media. The process to obtain it decribed on the installation page.

Warning: Since version available in Alpine repositories lacks btrfs driver you should download rEFInd on the official website and copy it to installation media


Partitioning disks

In this guide it is assumed that you have a fresh UEFI system without OS and just managed to boot into live Alpine using USB flash drive or CD. The first step is creating partition table on your HDD/SSD target device (/dev/sda here):

# apk add gptfdisk
# gdisk /dev/sda
> o ↵
> y ↵
> w ↵
> y ↵

Now we can define the partitions:

# cgdisk /dev/sda

Partition creation process consists of several steps:

  1. Start sector - you can safely use default value by pressing ↵
  2. Size
  3. Type (as hex code) - EFI is ef00, Linux filesystem is 8300, Swap is 8200.

Result table:

Part.     #     Size        Partition Type            Partition Name
----------------------------------------------------------------
1               200.0 MiB   EFI System                EFI
2               200.0 GiB   Linux filesystem          ROOT
3               32.0 GiB    Linux swap                SWAP

ROOT partition name will later be used in rEFInd configuration to identify boot volume. Next step is creating filesystems:

# mkfs.vfat -F32 /dev/sda1
# mkfs.btrfs /dev/sda2
# mkswap /dev/sda3

Now we can mount our root volume:

# mount -t btrfs /dev/sda2 /mnt

File system structure

Now we should create file structure that would provide reliable atomic system upgrades.
Start with following directories:

# mkdir /mnt/next

Stores next current link, is necessary due to how busybox mv does atomic link replacement.

# mkdir /mnt/commons

Stores common non-snapshotting subvolumes.
We may populate it right away:

# btrfs subvolume create /mnt/commons/@var@tmp
# btrfs subvolume create /mnt/commons/@var@cache
# btrfs subvolume create /mnt/commons/@var@log
# btrfs subvolume create /mnt/commons/@home

If you use flatpak, you may also want to keep it's directory separate:

# btrfs subvolume create /mnt/commons/@var@lib@flatpak

Include anything else in /var that should be mutable, for example:

# btrfs subvolume create /mnt/commons/@var@lib@iwd

Next, most important directories:

# mkdir /mnt/snapshots

Stores directories containing snapshots belonging to one generation.

# mkdir /mnt/links

Stores generations of directories containing links to snapshot generations.
Let's create first generation and populate it with one OS root snapshot @:

# NEWSNAPSHOTS="$(date -u +"%Y%m%d%H%M%S")$(cat /dev/urandom | tr -dc 'a-zA-Z' | fold -w 8 | head -n 1)"
# mkdir "/mnt/snapshots/$NEWSNAPSHOTS"
# btrfs subvolume create /mnt/snapshots/$NEWSNAPSHOTS/@

Populate links:

# NEWLINKS="$(date -u +"%Y%m%d%H%M%S")$(cat /dev/urandom | tr -dc 'a-zA-Z' | fold -w 8 | head -n 1)"
# mkdir "/mnt/links/$NEWLINKS"
# ln -s "../../snapshots/$NEWSNAPSHOTS" "/mnt/links/$NEWLINKS/0"
# ln -s "../../snapshots/$NEWSNAPSHOTS" "/mnt/links/$NEWLINKS/1"
# ln -s "../../snapshots/$NEWSNAPSHOTS" "/mnt/links/$NEWLINKS/2"
# ln -s "../../snapshots/$NEWSNAPSHOTS" "/mnt/links/$NEWLINKS/3"

You can have as many links as you like, just apply changes to rEFInd config and upgrade scripts described below accordingly.
Link that will point to latest links generation:

# ln -s "./links/$NEWLINKS" /mnt/current

This setup allows us to just have static rEFInd config that points to to /current/0/@, /current/1/@, etc. while the actual underlying boot environment will change with each upgrade.
But how will fs mounting services know which snapshot generation is currently loaded?
The answer is common fstab in the btrfs root.
Get UUIDs of the partitions first:

# blkid > /mnt/fstab

Now edit fstab accordingly:

# vi /mnt/fstab

Example:

UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 / btrfs subvol=CURRENT_SNAPSHOTS_PATH/@,ro,noatime 0 0
UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 /var/tmp btrfs subvol=/commons/@var@tmp,rw,noatime 0 0
UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 /var/cache btrfs subvol=/commons/@var@cache,rw,noatime 0 0
UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 /var/log btrfs subvol=/commons/@var@log,rw,noatime 0 0
UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 /var/lib/flatpak btrfs subvol=/commons/@var@lib@flatpak,rw,noatime 0 0
UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 /var/lib/iwd btrfs subvol=/commons/@var@lib@iwd,rw,noatime 0 0
UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 /home btrfs subvol=/commons/@home,rw,noatime 0 0
# UUID=2FE6-837A /boot/efi vfat rw,noatime,discard 0 2
tmpfs /tmp tmpfs mode=1777,noatime,nosuid,nodev,size=2G 0 0
UUID=f0239163-9d46-47c1-67a4-3ee1d63d0676 swap swap rw,noatime,discard 0 0

CURRENT_SNAPSHOTS_PATH will be replaced by scripts with, for example, /snapshots/20210411212549sdBXyLxg, and the result will be piped into /etc/fstab of a created @ snapshot during new generation preparations.
Root btrfs volume structure mounted on /mnt:

|--mnt
| |--commons
| | |--@var@tmp
| | |--@var@cache
| | |--@var@log
| | |--@var@lib@flatpak
| | |--@var@lib@iwd
| | |--@home
| |--current
| |--fstab
| |--links
| | |--20210411213742qwrXAJBz
| | | |--0
| | | |--1
| | | |--2
| | | |--3
| |--next
| |--snapshots
| | |--20210411212549sdBXyLxg
| | | |--@

Base system install

With the directory strtucture prepared we can start installation of a basic Alpine Linux system.
Considering that installation is done from Alpine system, we only need following parts of the process:

# apk -X https://dl-cdn.alpinelinux.org/alpine/latest-stable/main -U --allow-untrusted -p /mnt/snapshots/20210411212549sdBXyLxg/@ --initdb add alpine-base

Now we can setup basic chroot to complete the installation process:

# export SNP="/mnt/snapshots/20210411212549sdBXyLxg/@"

# mount -o bind /dev $SNP/dev
# mount -t proc none $SNP/proc
# mount -t sysfs sys $SNP/sys

# sed "s#CURRENT_SNAPSHOTS_PATH#/snapshots/20210411212549sdBXyLxg#g" /mnt/fstab > "/mnt/snapshots/20210411212549sdBXyLxg/@/etc/fstab"

# cp -L /etc/resolv.conf /mnt/etc/
# chroot /mnt /bin/sh

# mount -a

# mv /etc/resolv.conf /tmp/
# ln -s /tmp/resolv.conf /etc/resolv.conf

As soon as you in chroot, define repositories:

# echo "https://dl-cdn.alpinelinux.org/alpine/latest-stable/main" > /etc/apk/repositories

Example shows only main, but you should also add testing and community if you need any packages in those.
Now it's time for firmware, kernel and btrfs packages:

# apk add -U linux-firmware linux-lts btrfs-progs

You may want to change linux-firmware to a custom set of firmware packages suitable for you system, for example linux-firmware-amd linux-firmware-amd-ucode linux-firmware-amdgpu linux-firmware-ath10k linux-firmware-qca for typical AMD laptop.
It is also important to add btrfs feature to mkinitfs.conf and run mkinitfs manually:

# vi /etc/mkinitfs/mkinitfs.conf
# mkinitfs

These steps prepare kernel and generate initramfs which later will be used to boot from our first snapshot.
After that you should install any package you may need on first boot.

Warning: In case your PC only has wireless connection you should also install any suitable networking software, like iwd in this example, so you will not end up severed from network on your first boot.


Note: Due to root being immutable during operation, it's recommended to install package openresolv to support changing network connection. In this case /etc/resolvconf.conf should have resolv_conf=/tmp/resolv.conf, /etc/resolv.conf should be moved to /tmp/resolv.conf and a link to the new resolv.conf location should be created: ln -sfn /tmp/resolv.conf /etc/resolv.conf.

You may also use static DNS, but this would make your network activity directly identifiable to the DNS server provider, therefore it's not recommended.

Now, configure the system, start with setting a password for the root:

# passwd root

With the snapshot prepared and configured we can chroot out of it and unmount everything:

# umount -a
# exit

Finish editing snapshot by setting ro flag and unmounting root volume:

# btrfs property set -ts "/mnt/snapshots/20210411212549sdBXyLxg/@" ro true
# umount /mnt

Bootloader installation

Note: The example demonstrated here only make use of rEFInd bootloader as it is relatively easy to install manually and generally easy to use. You may however setup any prefered bootloader given it supports btrfs and can be configured to boot specific snapshot.

Mount the EFI partition:

# mount -t vfat /dev/sda1 /mnt
# mkdir /mnt/EFI

Unpack prepared rEFInd archive and copy relevant files to /mnt/EFI/

# unzip refind-bin-version.zip
# cp -r refind-bin-version/refind /mnt/EFI/
# cd /mnt/EFI/refind

Delete all unnecessary files - everything that is not for your CPU architecture:

# rm -r drivers_aa64 drivers_ia32 tools_aa64 tools_ia32 refind_aa64.efi refind_ia32.efi

Rename config file and edit it:

# mv refind.conf-sample refind.conf
# vi refind.conf

And append following to the end of the file, remember to replace example UUIDs with your own for root (btrfs partition) and resume (swap partition):

menuentry "Alpine Linux" {
    icon /EFI/refind/icons/os_linux.png
    volume "ROOT"
    loader /current/0/@/boot/vmlinuz-lts
    initrd /current/0/@/boot/initramfs-lts
    options "root=UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 rootfstype=btrfs rootflags=subvol=/current/0/@ resume=UUID=f0239163-9d46-47c1-67a4-3ee1d63d0676 ro,noatime quiet splash"

    submenuentry "Boot fallback 1" {
        loader /current/1/@/boot/vmlinuz-lts
        initrd /current/1/@/boot/initramfs-lts
        options "root=UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 rootfstype=btrfs rootflags=subvol=/current/1/@ resume=UUID=f0239163-9d46-47c1-67a4-3ee1d63d0676 ro,noatime quiet splash"
    }

    submenuentry "Boot fallback 2" {
        loader /current/2/@/boot/vmlinuz-lts
        initrd /current/2/@/boot/initramfs-lts
        options "root=UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 rootfstype=btrfs rootflags=subvol=/current/2/@ resume=UUID=f0239163-9d46-47c1-67a4-3ee1d63d0676 ro,noatime quiet splash"
    }

    submenuentry "Boot fallback 3" {
        loader /current/3/@/boot/vmlinuz-lts
        initrd /current/3/@/boot/initramfs-lts
        options "root=UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 rootfstype=btrfs rootflags=subvol=/current/3/@ resume=UUID=f0239163-9d46-47c1-67a4-3ee1d63d0676 ro,noatime quiet splash"
    }
}
Note: "ROOT" is the PARTLABEL of the btrfs partition. You may also use PARTUUID instead. To get both blkid from blkid package can be used. blkid included in busybox does not provide this information.

To add rEFInd to UEFI, efibootmgr is a suitable tool:

# apk add efibootmgr
# efibootmgr --create --disk /dev/sda --part 1 --loader /EFI/refind/refind_x64.efi --label "rEFInd" --verbose

/dev/sda is our disk device and 1 is the number of partition containing rEFInd.

Updating or altering the system

# touch /sbin/sysmut
# chmod +x /sbin/sysmut
# vi /sbin/sysmut

Example script to mutate the the system:

#!/bin/sh
ROOTVOLMNT="/vol/root" && \
mkdir -p "$ROOTVOLMNT" && \
mount -t btrfs -o rw,noatime UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 "$ROOTVOLMNT" && \
NEWSNAPSHOTS="$(date -u +"%Y%m%d%H%M%S")$(cat /dev/urandom | tr -dc 'a-zA-Z' | fold -w 8 | head -n 1)" && \
mkdir -p "$ROOTVOLMNT/snapshots/$NEWSNAPSHOTS" && \
btrfs subvolume snapshot "$ROOTVOLMNT/current/0/@" "$ROOTVOLMNT/snapshots/$NEWSNAPSHOTS/@" && \
sed "s#CURRENT_SNAPSHOTS_PATH#/snapshots/$NEWSNAPSHOTS#g" "$ROOTVOLMNT/fstab" > "$ROOTVOLMNT/snapshots/$NEWSNAPSHOTS/@/etc/fstab" && \
mount -t proc none "$ROOTVOLMNT/snapshots/$NEWSNAPSHOTS/@/proc" && \
mount -t sysfs sys "$ROOTVOLMNT/snapshots/$NEWSNAPSHOTS/@/sys" && \
mount -o bind /dev "$ROOTVOLMNT/snapshots/$NEWSNAPSHOTS/@/dev" && \
chroot "$ROOTVOLMNT/snapshots/$NEWSNAPSHOTS/@" /bin/sh -c 'mount -a; sh; APPLY=$?; umount -a; exit $APPLY' && \
btrfs property set -ts "$ROOTVOLMNT/snapshots/$NEWSNAPSHOTS/@" ro true && \
NEWLINKS="$(date -u +"%Y%m%d%H%M%S")$(cat /dev/urandom | tr -dc 'a-zA-Z' | fold -w 8 | head -n 1)" && \
mkdir -p "$ROOTVOLMNT/links/$NEWLINKS" && \
ln -s "../../snapshots/$NEWSNAPSHOTS" "$ROOTVOLMNT/links/$NEWLINKS/0" && \
cp -P "$ROOTVOLMNT/current/0" "$ROOTVOLMNT/links/$NEWLINKS/1" && \
cp -P "$ROOTVOLMNT/current/1" "$ROOTVOLMNT/links/$NEWLINKS/2" && \
cp -P "$ROOTVOLMNT/current/2" "$ROOTVOLMNT/links/$NEWLINKS/3" && \
mkdir -p "$ROOTVOLMNT/next" && \
ln -sfn "./links/$NEWLINKS" "$ROOTVOLMNT/next/current" && \
mv "$ROOTVOLMNT/next/current" "$ROOTVOLMNT/" \
&& echo "Switched to the new snapshots" \
|| echo "Changes discarded"
umount "$ROOTVOLMNT"

It will get you into the root shell chrooted into the new snapshot, where you can apply any change you like.
If chroot shell exits with an error, there will be no switch to the new snapshots. This means you can manually discard changes while in the chroot by:

# exit 1

Deleting unused snapshots

Unused snapshots can be garbage-collected by:

# touch /sbin/syscln
# chmod +x /sbin/syscln
# vi /sbin/syscln
#!/bin/sh
ROOTVOLMNT="/vol/root"
mkdir -p "$ROOTVOLMNT"
mount -t btrfs -o rw,noatime UUID=b9ff5e7b-e128-4e64-861a-2fdd794a9828 "$ROOTVOLMNT"

SNAPSHOTS=$({ \
    find "$ROOTVOLMNT/snapshots/" -maxdepth 1 -mindepth 1
    find "$ROOTVOLMNT/current/" -maxdepth 1 -mindepth 1 \
        | xargs -n 1 readlink -f
} | sort | uniq -u)

if [ -z "$SNAPSHOTS" ]; then
    echo "Nothing to remove"
else
    printf %s\\n "$SNAPSHOTS" \
        | tr \\n \\0 \
        | xargs -r -0 -n 1 -I {} find {} -maxdepth 1 -mindepth 1 \
        | tr \\n \\0 \
        | xargs -r -0 btrfs subvolume delete
    printf %s\\n "$SNAPSHOTS" \
        | tr \\n \\0 \
        | xargs -r -0 rm -r
fi

umount "$ROOTVOLMNT"