build-inside-vm.sh 7.46 KB
Newer Older
1
#!/bin/bash
2
# build-inside-vm.sh builds the images (cloud image, vagrant boxes)
Kristian Klausen's avatar
Kristian Klausen committed
3
4
5

# nounset: "Treat unset variables and parameters [...] as an error when performing parameter expansion."
# errexit: "Exit immediately if [...] command exits with a non-zero status."
6
set -o nounset -o errexit
7
8
readonly DISK_SIZE="2G"
readonly IMAGE="image.img"
9
# shellcheck disable=SC2016
10
readonly MIRROR='https://mirror.pkgbuild.com/$repo/os/$arch'
11

12
13
14
15
16
17
18
19
20
function init() {
  readonly ORIG_PWD="${PWD}"
  readonly OUTPUT="${PWD}/output"
  readonly TMPDIR="$(mktemp --dry-run --directory --tmpdir="${PWD}/tmp")"
  mkdir -p "${OUTPUT}" "${TMPDIR}"
  if [ -n "${SUDO_UID:-}" ]; then
    chown "${SUDO_UID}:${SUDO_GID}" "${OUTPUT}" "${TMPDIR}"
  fi
  cd "${TMPDIR}"
21

22
23
24
  readonly MOUNT="${PWD}/mount"
  mkdir "${MOUNT}"
}
25

Kristian Klausen's avatar
Kristian Klausen committed
26
# Do some cleanup when the script exits
27
function cleanup() {
Kristian Klausen's avatar
Kristian Klausen committed
28
  # We want all the commands to run, even if one of them fails.
29
30
31
32
33
34
35
36
37
38
39
40
41
42
  set +o errexit
  if [ -n "${LOOPDEV:-}" ]; then
    losetup -d "${LOOPDEV}"
  fi
  if [ -n "${MOUNT:-}" ] && mountpoint -q "${MOUNT}"; then
    # We do not want risking deleting ex: the package cache
    umount --recursive "${MOUNT}" || exit 1
  fi
  if [ -n "${TMPDIR:-}" ]; then
    rm -rf "${TMPDIR}"
  fi
}
trap cleanup EXIT

43
44
45
46
47
48
49
50
51
# Helper function: wait until a file path exists
# ${1} - file path
function wait_until_exists() {
  until test -e "${1}"; do
      echo "${1} doesn't exist yet..."
      sleep 1
  done
}

Kristian Klausen's avatar
Kristian Klausen committed
52
# Create the disk, partitions it, format the partition and mount the filesystem
53
54
55
56
57
58
59
60
function setup_disk() {
  truncate -s "${DISK_SIZE}" "${IMAGE}"
  sgdisk --clear \
    --new 1::+1M --typecode=1:ef02 \
    --new 2::-0 --typecode=2:8300 \
    "${IMAGE}"

  LOOPDEV=$(losetup --find --partscan --show "${IMAGE}")
61
  # Partscan is racy
62
  blockdev --rereadpt ${LOOPDEV}
63
  wait_until_exists "${LOOPDEV}p2"
64
65
66
67
  mkfs.btrfs "${LOOPDEV}p2"
  mount -o compress-force=zstd "${LOOPDEV}p2" "${MOUNT}"
}

Kristian Klausen's avatar
Kristian Klausen committed
68
# Install Arch Linux to the filesystem (bootstrap)
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
function bootstrap() {
  cat <<EOF >pacman.conf
[options]
Architecture = auto

[core]
Include = mirrorlist

[extra]
Include = mirrorlist

[community]
Include = mirrorlist
EOF
  echo "Server = ${MIRROR}" >mirrorlist

  # We use the hosts package cache
86
  pacstrap -c -C pacman.conf -M "${MOUNT}" base linux grub openssh sudo polkit haveged btrfs-progs reflector
87
88
89
  cp mirrorlist "${MOUNT}/etc/pacman.d/"
}

Kristian Klausen's avatar
Kristian Klausen committed
90
# Misc "tweaks" done after bootstrapping
91
function postinstall() {
Kristian Klausen's avatar
Kristian Klausen committed
92
93
94
95
96
97
98
  arch-chroot "${MOUNT}" /usr/bin/btrfs subvolume create /swap
  chattr +C "${MOUNT}/swap"
  chmod 0700 "${MOUNT}/swap"
  fallocate -l 512M "${MOUNT}/swap/swapfile"
  mkswap "${MOUNT}/swap/swapfile"
  echo -e "/swap/swapfile none swap defaults 0 0" >>"${MOUNT}/etc/fstab"

99
100
101
102
103
  echo "archlinux" >"${MOUNT}/etc/hostname"
  echo "KEYMAP=us" >"${MOUNT}/etc/vconsole.conf"
  ln -sf /var/run/systemd/resolve/resolv.conf "${MOUNT}/etc/resolv.conf"
}

Kristian Klausen's avatar
Kristian Klausen committed
104
# Cleanup the image and trim it
105
106
107
108
109
110
111
112
function image_cleanup() {
  # Remove pacman key ring for re-initialization
  rm -rf "${MOUNT}/etc/pacman.d/gnupg/"

  sync -f "${MOUNT}/etc/os-release"
  fstrim --verbose "${MOUNT}"
}

Kristian Klausen's avatar
Kristian Klausen committed
113
# Mount image helper (loop device + mount)
114
115
function mount_image() {
  LOOPDEV=$(losetup --find --partscan --show "${1:-${IMAGE}}")
116
  # Partscan is racy
117
  blockdev --rereadpt ${LOOPDEV}
118
  wait_until_exists "${LOOPDEV}p2"
119
120
121
122
123
  mount -o compress-force=zstd "${LOOPDEV}p2" "${MOUNT}"
  # Setup bind mount to package cache
  mount --bind "/var/cache/pacman/pkg" "${MOUNT}/var/cache/pacman/pkg"
}

Kristian Klausen's avatar
Kristian Klausen committed
124
# Unmount image helper (umount + detach loop device)
125
126
127
128
129
130
function unmount_image() {
  umount --recursive "${MOUNT}"
  losetup -d "${LOOPDEV}"
  LOOPDEV=""
}

Kristian Klausen's avatar
Kristian Klausen committed
131
# Copy image and mount the copied image
132
133
134
135
136
function copy_and_mount_image() {
  cp -a "${IMAGE}" "${1}"
  mount_image "${1}"
}

Kristian Klausen's avatar
Kristian Klausen committed
137
# Compute SHA256, adjust owner to $SUDO_UID:$SUDO_UID and move to output/
138
139
140
141
142
143
144
145
function mv_to_output() {
  sha256sum "${1}" >"${1}.SHA256"
  if [ -n "${SUDO_UID:-}" ]; then
    chown "${SUDO_UID}:${SUDO_GID}" "${1}"{,.SHA256}
  fi
  mv "${1}"{,.SHA256} "${OUTPUT}/"
}

Kristian Klausen's avatar
Kristian Klausen committed
146
# Helper function: create a new image from the "base" image
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# ${1} - new image file
# ${2} - final file
# ${3} - pre
# ${4} - post
function create_image() {
  copy_and_mount_image "${1}"
  "${3}"
  image_cleanup
  unmount_image
  "${4}" "${1}" "${2}"
  mv_to_output "${2}"
}

function cloud_image() {
  arch-chroot "${MOUNT}" /bin/bash < <(cat "${ORIG_PWD}"/http/install-{cloud,common}.sh)
162
  arch-chroot "${MOUNT}" /usr/bin/pacman -S --noconfirm qemu-guest-agent cloud-init
163
164
165
166
  arch-chroot "${MOUNT}" /usr/bin/systemctl enable cloud-init-local.service cloud-init.service cloud-config.service cloud-final.service
}

function cloud_image_post() {
Kristian Klausen's avatar
Kristian Klausen committed
167
  qemu-img convert -c -f raw -O qcow2 "${1}" "${2}"
168
169
170
  rm "${1}"
}

171
172
function vagrant_qemu() {
  arch-chroot "${MOUNT}" /bin/bash < <(cat "${ORIG_PWD}"/http/install-{chroot,common}.sh)
173
  arch-chroot "${MOUNT}" /usr/bin/pacman -S --noconfirm netctl qemu-guest-agent
174
175
176
177
178
}

function vagrant_qemu_post() {
  # Create vagrant box
  cat <<EOF >Vagrantfile
179
180
181
182
183
184
Vagrant.configure("2") do |config|
  config.vm.provider :libvirt do |libvirt|
    libvirt.driver = "kvm"
  end
end
EOF
185
186
187
  local virtual_size
  virtual_size="$(grep -o "^[0-9]*" <<<"${DISK_SIZE}")"
  echo '{"format":"qcow2","provider":"libvirt","virtual_size":'"${virtual_size}"'}' >metadata.json
188
189
  qemu-img convert -f raw -O qcow2 "${1}" box.img
  rm "${1}"
190

191
192
  tar -czf "${2}" Vagrantfile metadata.json box.img
  rm Vagrantfile metadata.json box.img
193
194
195
196
}

function vagrant_virtualbox() {
  arch-chroot "${MOUNT}" /bin/bash < <(cat "${ORIG_PWD}"/http/install-{chroot,common}.sh)
197
  arch-chroot "${MOUNT}" /usr/bin/pacman -S --noconfirm netctl virtualbox-guest-utils-nox
198
199
200
201
  arch-chroot "${MOUNT}" /usr/bin/systemctl enable vboxservice
}

function vagrant_virtualbox_post() {
202
203
  # Create vagrant box
  # VirtualBox-6.1.12 src/VBox/NetworkServices/Dhcpd/Config.cpp line 276
204
205
  local mac_address
  mac_address="080027$(openssl rand -hex 3 | tr '[:lower:]' '[:upper:]')"
206
207
  cat <<EOF >Vagrantfile
Vagrant.configure("2") do |config|
208
  config.vm.base_mac = "${mac_address}"
209
210
211
212
213
214
215
216
217
end
EOF
  echo '{"provider":"virtualbox"}' >metadata.json
  qemu-img convert -f raw -O vmdk "${1}" "packer-virtualbox.vmdk"
  rm "${1}"

  cp "${ORIG_PWD}/box.ovf" .
  sed -e "s/MACHINE_UUID/$(uuidgen)/" \
    -e "s/DISK_UUID/$(uuidgen)/" \
218
    -e "s/DISK_CAPACITY/$(qemu-img info --output=json "packer-virtualbox.vmdk" | jq '."virtual-size"')/" \
219
    -e "s/UNIX/$(date +%s)/" \
220
    -e "s/MAC_ADDRESS/${mac_address}/" \
221
222
223
224
    -i box.ovf

  tar -czf "${2}" Vagrantfile metadata.json packer-virtualbox.vmdk box.ovf
  rm Vagrantfile metadata.json packer-virtualbox.vmdk box.ovf
225
226
}

227
# ${1} - Optional build version. If not set, will generate a default based on date.
228
229
230
231
232
function main() {
  if [ "$(id -u)" -ne 0 ]; then
    echo "root is required"
    exit 1
  fi
Kristian Klausen's avatar
Kristian Klausen committed
233
  init
234

235
236
237
238
239
240
241
  setup_disk
  bootstrap
  postinstall
  # We run it here as it is the easiest solution and we do not want anything to go wrong!
  arch-chroot "${MOUNT}" grub-install --target=i386-pc "${LOOPDEV}"
  unmount_image

242
243
244
245
246
247
248
  local build_version
  if [ -z "${1:-}" ]; then
    build_version="$(date +%Y.%m.%d)"
    echo "WARNING: BUILD_VERSION wasn't set!"
    echo "Falling back to $build_version"
  else
    build_version="${1}"
249
  fi
250
251
252
  create_image "cloud-img.img" "Arch-Linux-x86_64-cloudimg-${build_version}.qcow2" cloud_image cloud_image_post
  create_image "vagrant-qemu.img" "Arch-Linux-x86_64-libvirt-${build_version}.box" vagrant_qemu vagrant_qemu_post
  create_image "vagrant-virtualbox.img" "Arch-Linux-x86_64-virtualbox-${build_version}.box" vagrant_qemu vagrant_virtualbox_post
253
}
254
main "$@"