Debian Codegraph @

container

raw symbols SCIP
1 #!/usr/bin/python3
2 # SPDX-License-Identifier: AGPL-3.0-or-later
3 """Script to manage a container or a VM for FreedomBox development.
4
5 This script creates either a simple container using systemd-nspawn or a virtual
6 machine using libvirt for developing FreedomBox. Containers have many
7 advantages over running a VM. RAM is allocated to processes in the container as
8 needed without any fixed limit. Also RAM does not have to be statically
9 allocated so it is typically much lighter than running an VM. There is no
10 hardware emulation when running a container with same architecture, so
11 processes run as fast as they would on the host machine. On the other hand, VMs
12 have the advantage of full machine emulation. They allow full permissions as
13 required for mounting filesystems, USB passthrough of Wi-Fi devices, emulation
14 of multiple disks, etc. as required for testing some of the features of
15 FreedomBox.
16
17 Environment: The script will run only run on hosts having systemd-nspawn,
18 virsh, and network-manager installed, typical GNU/Linux distributions. It has
19 been primarily developed and tested on Debian Buster but should work on most
20 modern GNU/Linux distributions.
21
22 Disk image: For a container, systemd-nspawn accepts not only a directory for
23 starting a container but also a disk image. This disk image is loop-back
24 mounted and container is started from that mounted directory. The partition to
25 use is determined by looking at the boot flag in the partition table. This
26 happens to work well with all existing FreedomBox images. In future, we may be
27 able to run different architectures in this manner.
28
29 For a VM, a disk drive is created that is backed by the image file. The image
30 is a bootable image using GRUB as built by freedom-maker.
31
32 After downloading, the disk image is expanded along with the partition and file
33 system inside so that development can be done without running into disk space
34 issues. Expanding the disk does not immediately consume disk space because it
35 will be a sparse file. As data is written to the disk, it will occupy more and
36 more space but the upper limit is the size to which disk has been expanded.
37
38 Downloading images: Images are downloaded from FreedomBox download server using
39 fixed URLs for each distribution. Signature is verified for the download
40 images. The fingerprint of the allowed signing key is hard-coded in this
41 script. Downloaded images are kept even after destroying the extracted raw
42 image along with container. This allows for quickly resetting the container
43 without downloading again.
44
45 Booting: For a container, systemd-nspawn is run in 'boot' mode. This means that
46 init process (happens to be systemd) is started inside the container. It then
47 spawns all the other necessary daemons including openssh-server, firewalld and
48 network-manager. A login terminal can be opened using 'machinectl login'
49 because container is running systemd. SSH into the container is possible
50 because network is up, configured by network-manager, and openssh server is
51 running.
52
53 For a VM, when the virtual machine is started, the firmware of the machine
54 boots the machine from the attached disk. The boot process is similar to a
55 physical machine.
56
57 Shared folder: For a container, using systemd-nspawn, the project directory is
58 mounted as /freedombox inside the container. The project directory is
59 determined as directory in which this script resides. The project folder from
60 the container point of view will be read-only. Container should be able to
61 write various files such as build files into the /freedombox folder. To enable
62 writing, an additional read-write folder is overlayed onto /freedombox folder
63 in the container. This directory can't be created under the project folder and
64 is created instead in
65 $XDG_DATA_HOME/freedombox-container/overlay/$DISTRIBUTION. If XDG_DATA_HOME is
66 not set, it is assumed to be $HOME/.local/shared/. Whenever data is written
67 into /freedombox directory inside the container, this directory on the host
68 receives the changes. See documentation for Overlay filesystem for further
69 details. When container is destroyed, this overlay folder is destroyed to
70 ensure clean state after bringing up the container again.
71
72 For a VM, the project directory is exposed into the virtual machine with the
73 mount token 'freedombox' using virtiofs. This is done as part of virtual
74 machine configuration. Inside the virtual machine, a systemd .mount unit will
75 mount the virtiofs filesystem using the 'freedombox' token onto the folder
76 /freedombox. The folder is read-write.
77
78 Users: In container, PrivateUsers configuration flag for systemd-nspawn is
79 currently off. This means that each user's UID on the host is also the same UID
80 in the container as along as there is an entry in the container's password
81 database. In future, we may explore using private users inside the container.
82
83 'fbx' is the development user and its UID is changed during setup phase to
84 10000 hoping it would not match anything on the host system. 'fbx' user has
85 full sudo access inside the container without needing a password. Password for
86 this user is not set by default, but can be set if needed. If there is no
87 access to the container in any way, one can run 'sudo machinectl shell' and
88 then run 'passwd fbx' to set the password for the 'fbx' user.
89
90 'plinth' user's UID in the container is also changed and set to the UID of
91 whichever user owns the project directory. This allows the files to written by
92 'plinth' container user in the project directory because UID of the owner of
93 the directory is same as the 'plinth' user's UID in container.
94
95 Network: For a container, a private network is created inside the container
96 using systemd-nspawn feature. Network interfaces from the host are not
97 available inside the container. A new network interface called 'host0' is
98 configured inside the container which is automatically configured by
99 network-manager. On the host a new network interface is created. This script
100 creates configuration for a 'shared' network using network-manager. When
101 bringing up the container, this network connection is also brought up. A DHCP
102 server and a DNS server are started network-manager on the host side so that
103 DHCP and DNS client functions work inside the container. Traffic from the
104 container is also masqueraded so that Internet connectivity inside the
105 container works if the host has one.
106
107 If necessary, the network interface on host side can be differently configured.
108 For example, it can be bridged with another interface to expose the container
109 on a network that the host machine participates in.
110
111 The network IP address inside the container can be queried using machinectl.
112 This script queries that IP address and presents the address in its console
113 messages. All ports in the container can be reached from the host using this IP
114 address as long as the firewall inside the container allows it. There is no
115 need to perform port forwarding or mapping.
116
117 For a VM, the network device is fully emulated. On the host it is exposed as
118 network interface that is bridged with the default libvirt bridge. The bridge
119 interface is configured by libvirt and it listens for DHCP requests from the
120 guests and also has a DNS server running. All traffic from the guest is NATed
121 and, as a result, the guest has full network access. The guest is accessible
122 from the host using the guest IP address which can be retrieved by asking
123 libvirt.
124
125 SSH: It is assumed that openssh-server is installed inside the container. SSH
126 server keys in the container are created if missing. Client side keys are
127 created in .container/ssh directory and the public key is installed in the
128 authorized keys file of the 'fbx' user. The 'ssh' sub-command to this script is
129 simply a convenience mechanism for quick launch of ssh with the right IP
130 address, user name and identity file.
131
132 Role of machinectl: For a container, most of the work is done by
133 systemd-nspawn. machinectl is useful for running systemd-nspawn in the
134 background and querying its current state. It also helps with providing the IP
135 address of the container. machinectl is made to recognize the container by
136 creating a link in /var/lib/machines/ to the image file. systemd-nspawn options
137 are added by creating a temporary file in /run/systemd/nspawn. All machinectl
138 commands should work.
139
140 """
141
142 import argparse
143 import datetime
144 import ipaddress
145 import itertools
146 import json
147 import logging
148 import os
149 import pathlib
150 import platform
151 import re
152 import shlex
153 import shutil
154 import subprocess
155 import sys
156 import tempfile
157 import time
158 import urllib.parse
159 from typing import Callable
160 from urllib.request import urlopen
161
162 URLS_AMD64 = {
163 'oldstable': 'https://ftp.freedombox.org/pub/freedombox/hardware/'
164 'amd64/bookworm/freedombox-bookworm_all-amd64.img.xz',
165 'stable': 'https://ftp.freedombox.org/pub/freedombox/hardware/'
166 'amd64/trixie/freedombox-trixie_all-amd64.img.xz',
167 'testing': 'https://ftp.freedombox.org/pub/freedombox/hardware/'
168 'amd64/testing/freedombox-testing_dev_all-amd64.img.xz',
169 'unstable': 'https://ftp.freedombox.org/pub/freedombox/hardware/'
170 'amd64/nightly/freedombox-unstable_dev_all-amd64.img.xz',
171 }
172
173 URLS_ARM64 = {
174 'oldstable': 'https://ftp.freedombox.org/pub/freedombox/hardware/'
175 'arm64/bookworm/freedombox-bookworm_all-arm64.img.xz',
176 'stable': 'https://ftp.freedombox.org/pub/freedombox/hardware/'
177 'arm64/trixie/freedombox-trixie_all-arm64.img.xz',
178 'testing': 'https://ftp.freedombox.org/pub/freedombox/hardware/'
179 'arm64/testing/freedombox-testing_dev_all-arm64.img.xz',
180 'unstable': 'https://ftp.freedombox.org/pub/freedombox/hardware/'
181 'arm64/nightly/freedombox-unstable_dev_all-arm64.img.xz',
182 }
183
184 URLS = URLS_AMD64
185
186 TRUSTED_KEYS = ['D4B069124FCF43AA1FCD7FBC2ACFC1E15AF82D8C']
187 KEY_SERVER = 'keyserver.ubuntu.com'
188 KEY_SERVER_HTTPS_API = \
189 'https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x{key_id}'
190
191 PROVISION_SCRIPT = '''
192 set -xe pipefail
193
194 cd /freedombox/
195
196 sudo apt-get -y install make
197 sudo make provision-dev
198
199 # Make some pytest related files and directories writable to the fbx user
200 sudo touch geckodriver.log
201 sudo chmod a+rw geckodriver.log
202 sudo mkdir -p .pytest_cache/
203 sudo chmod --recursive a+rw .pytest_cache/
204 sudo chmod a+w /freedombox
205 sudo chmod --recursive --silent a+w htmlcov || true
206 sudo chmod --silent a+w .coverage || true
207
208 exit 0
209 ''' # noqa
210
211 SETUP_AND_RUN_TESTS_SCRIPT = '''
212 set -x
213
214 BACKPORTS_SOURCES_LIST=/etc/apt/sources.list.d/freedombox2.list
215 LDAPSCRIPTS_CONF=/etc/ldapscripts/freedombox-ldapscripts.conf
216
217 # Remount /freedoombox to be up to date
218 echo "> In machine: Remounting /freedombox"
219 mount -o remount /freedombox
220
221 # Activate backports if Debian stable
222 if [[ "{distribution}" == "stable" && ! -e $BACKPORTS_SOURCES_LIST ]]
223 then
224 echo "> In machine: Enable backports"
225 /freedombox/bin/freedombox-cmd upgrades activate_backports --no-args
226 fi
227
228 echo "> In machine: Upgrade packages"
229 apt-get update
230 apt-mark hold freedombox freedombox-doc-en freedombox-doc-es
231 DEBIAN_FRONTEND=noninteractive apt-get -yq --with-new-pkgs upgrade
232
233 # Install requirements for tests if not already installed as root
234 if ! [[ -e /usr/local/bin/geckodriver ]]
235 then
236 /freedombox/plinth/tests/functional/install.sh
237 fi
238
239 # Run the plinth server if functional tests are requested
240 if [[ "{pytest_command}" =~ "--include-functional" ]]
241 then
242 make -C /freedombox wait-while-first-setup
243
244 if [[ "{pytest_command}" != *"--splinter-headless"* ]]
245 then
246 # Use the X11 authority file from the fbx user to run GUI programs
247 xauth merge /home/fbx/.Xauthority
248 fi
249 fi
250
251 # Run pytest
252 cd /freedombox
253 export FREEDOMBOX_URL=https://localhost
254 export FREEDOMBOX_SSH_PORT=22
255 export FREEDOMBOX_SAMBA_PORT=445
256 {pytest_command}
257
258 # Make pytest cache files writable to the fbx user
259 chmod --recursive --silent a+rw .pytest_cache/
260 chmod --recursive --silent a+w htmlcov
261 chmod --silent a+w .coverage
262
263 exit 0
264 '''
265
266 LIBVIRT_DOMAIN_XML_TEMPLATE = '''<domain type="kvm">
267 <name>{domain_name}</name>
268 <metadata>
269 <libosinfo:libosinfo xmlns:libosinfo="http://libosinfo.org/xmlns/libvirt/domain/1.0">
270 <libosinfo:os id="http://debian.org/debian/testing"/>
271 </libosinfo:libosinfo>
272 </metadata>
273 <memory unit="MiB">{memory_mib}</memory>
274 <currentMemory unit="MiB">{memory_mib}</currentMemory>
275 <memoryBacking>
276 <source type="memfd"/>
277 <access mode="shared"/>
278 </memoryBacking>
279 <vcpu placement="static">{cpus}</vcpu>
280 <os {firmware}>
281 <type arch="x86_64" machine="pc-q35-7.2">hvm</type>
282 <boot dev="hd"/>
283 </os>
284 <features>
285 <acpi/>
286 <apic/>
287 <vmport state="off"/>
288 </features>
289 <cpu mode="host-passthrough" check="none" migratable="on"/>
290 <clock offset="utc">
291 <timer name="rtc" tickpolicy="catchup"/>
292 <timer name="pit" tickpolicy="delay"/>
293 <timer name="hpet" present="no"/>
294 </clock>
295 <on_poweroff>destroy</on_poweroff>
296 <on_reboot>restart</on_reboot>
297 <on_crash>destroy</on_crash>
298 <pm>
299 <suspend-to-mem enabled="no"/>
300 <suspend-to-disk enabled="no"/>
301 </pm>
302 <devices>
303 <emulator>/usr/bin/qemu-system-x86_64</emulator>
304 <disk type="file" device="disk">
305 <driver name="qemu" type="qcow2"/>
306 <source file="{image_file}"/>
307 <target dev="vda" bus="virtio"/>
308 <address type="pci" domain="0x0000" bus="0x04" slot="0x00" function="0x0"/>
309 </disk>
310 <controller type="usb" index="0" model="qemu-xhci" ports="15">
311 <address type="pci" domain="0x0000" bus="0x02" slot="0x00" function="0x0"/>
312 </controller>
313 <controller type="pci" index="0" model="pcie-root"/>
314 <controller type="pci" index="1" model="pcie-root-port">
315 <model name="pcie-root-port"/>
316 <target chassis="1" port="0x10"/>
317 <address type="pci" domain="0x0000" bus="0x00" slot="0x02" function="0x0" multifunction="on"/>
318 </controller>
319 <controller type="pci" index="2" model="pcie-root-port">
320 <model name="pcie-root-port"/>
321 <target chassis="2" port="0x11"/>
322 <address type="pci" domain="0x0000" bus="0x00" slot="0x02" function="0x1"/>
323 </controller>
324 <controller type="pci" index="3" model="pcie-root-port">
325 <model name="pcie-root-port"/>
326 <target chassis="3" port="0x12"/>
327 <address type="pci" domain="0x0000" bus="0x00" slot="0x02" function="0x2"/>
328 </controller>
329 <controller type="pci" index="4" model="pcie-root-port">
330 <model name="pcie-root-port"/>
331 <target chassis="4" port="0x13"/>
332 <address type="pci" domain="0x0000" bus="0x00" slot="0x02" function="0x3"/>
333 </controller>
334 <controller type="pci" index="5" model="pcie-root-port">
335 <model name="pcie-root-port"/>
336 <target chassis="5" port="0x14"/>
337 <address type="pci" domain="0x0000" bus="0x00" slot="0x02" function="0x4"/>
338 </controller>
339 <controller type="pci" index="6" model="pcie-root-port">
340 <model name="pcie-root-port"/>
341 <target chassis="6" port="0x15"/>
342 <address type="pci" domain="0x0000" bus="0x00" slot="0x02" function="0x5"/>
343 </controller>
344 <controller type="pci" index="7" model="pcie-root-port">
345 <model name="pcie-root-port"/>
346 <target chassis="7" port="0x16"/>
347 <address type="pci" domain="0x0000" bus="0x00" slot="0x02" function="0x6"/>
348 </controller>
349 <controller type="pci" index="8" model="pcie-root-port">
350 <model name="pcie-root-port"/>
351 <target chassis="8" port="0x17"/>
352 <address type="pci" domain="0x0000" bus="0x00" slot="0x02" function="0x7"/>
353 </controller>
354 <controller type="pci" index="9" model="pcie-root-port">
355 <model name="pcie-root-port"/>
356 <target chassis="9" port="0x18"/>
357 <address type="pci" domain="0x0000" bus="0x00" slot="0x03" function="0x0" multifunction="on"/>
358 </controller>
359 <controller type="pci" index="10" model="pcie-root-port">
360 <model name="pcie-root-port"/>
361 <target chassis="10" port="0x19"/>
362 <address type="pci" domain="0x0000" bus="0x00" slot="0x03" function="0x1"/>
363 </controller>
364 <controller type="pci" index="11" model="pcie-root-port">
365 <model name="pcie-root-port"/>
366 <target chassis="11" port="0x1a"/>
367 <address type="pci" domain="0x0000" bus="0x00" slot="0x03" function="0x2"/>
368 </controller>
369 <controller type="pci" index="12" model="pcie-root-port">
370 <model name="pcie-root-port"/>
371 <target chassis="12" port="0x1b"/>
372 <address type="pci" domain="0x0000" bus="0x00" slot="0x03" function="0x3"/>
373 </controller>
374 <controller type="pci" index="13" model="pcie-root-port">
375 <model name="pcie-root-port"/>
376 <target chassis="13" port="0x1c"/>
377 <address type="pci" domain="0x0000" bus="0x00" slot="0x03" function="0x4"/>
378 </controller>
379 <controller type="pci" index="14" model="pcie-root-port">
380 <model name="pcie-root-port"/>
381 <target chassis="14" port="0x1d"/>
382 <address type="pci" domain="0x0000" bus="0x00" slot="0x03" function="0x5"/>
383 </controller>
384 <controller type="sata" index="0">
385 <address type="pci" domain="0x0000" bus="0x00" slot="0x1f" function="0x2"/>
386 </controller>
387 <controller type="virtio-serial" index="0">
388 <address type="pci" domain="0x0000" bus="0x03" slot="0x00" function="0x0"/>
389 </controller>
390 <filesystem type="mount" accessmode="passthrough">
391 <driver type="virtiofs"/>
392 <source dir="{source_dir}"/>
393 <target dir="freedombox"/>
394 <address type="pci" domain="0x0000" bus="0x07" slot="0x00" function="0x0"/>
395 </filesystem>
396 <interface type="network">
397 <source network="default"/>
398 <model type="virtio"/>
399 <address type="pci" domain="0x0000" bus="0x01" slot="0x00" function="0x0"/>
400 </interface>
401 <serial type="pty">
402 <target type="isa-serial" port="0">
403 <model name="isa-serial"/>
404 </target>
405 </serial>
406 <console type="pty">
407 <target type="serial" port="0"/>
408 </console>
409 <channel type="unix">
410 <target type="virtio" name="org.qemu.guest_agent.0"/>
411 <address type="virtio-serial" controller="0" bus="0" port="1"/>
412 </channel>
413 <channel type="spicevmc">
414 <target type="virtio" name="com.redhat.spice.0"/>
415 <address type="virtio-serial" controller="0" bus="0" port="2"/>
416 </channel>
417 <input type="tablet" bus="usb">
418 <address type="usb" bus="0" port="1"/>
419 </input>
420 <input type="mouse" bus="ps2"/>
421 <input type="keyboard" bus="ps2"/>
422 <graphics type="spice" autoport="yes">
423 <listen type="address"/>
424 <image compression="off"/>
425 </graphics>
426 <sound model="ich9">
427 <address type="pci" domain="0x0000" bus="0x00" slot="0x1b" function="0x0"/>
428 </sound>
429 <audio id="1" type="spice"/>
430 <video>
431 <model type="virtio" heads="1" primary="yes"/>
432 <address type="pci" domain="0x0000" bus="0x00" slot="0x01" function="0x0"/>
433 </video>
434 <redirdev bus="usb" type="spicevmc">
435 <address type="usb" bus="0" port="2"/>
436 </redirdev>
437 <redirdev bus="usb" type="spicevmc">
438 <address type="usb" bus="0" port="3"/>
439 </redirdev>
440 <memballoon model="virtio">
441 <address type="pci" domain="0x0000" bus="0x05" slot="0x00" function="0x0"/>
442 </memballoon>
443 <rng model="virtio">
444 <backend model="random">/dev/urandom</backend>
445 <address type="pci" domain="0x0000" bus="0x06" slot="0x00" function="0x0"/>
446 </rng>
447 </devices>
448 </domain>
449 ''' # noqa: E501
450
451 logger = logging.getLogger(__name__)
452
453
454 def parse_arguments() -> argparse.Namespace:
455 """Return parsed command line arguments as dictionary."""
456 parser = argparse.ArgumentParser(
457 formatter_class=argparse.ArgumentDefaultsHelpFormatter)
458 subparsers = parser.add_subparsers(dest='subcommand', help='Sub command')
459
460 distributions = list(URLS.keys())
461
462 distribution = os.environ.get('DISTRIBUTION')
463
464 formatter_class = argparse.ArgumentDefaultsHelpFormatter
465 default_distribution = 'testing'
466 if distribution and distribution in distributions:
467 default_distribution = distribution
468
469 def _add_common_args(subparser):
470 subparser.add_argument('--distribution', choices=distributions,
471 default=default_distribution,
472 help='Distribution to work with')
473 subparser.add_argument(
474 '--machine-type', choices=('container', 'vm'), default='container',
475 help='Type of the machine, container to virtual machine, to run '
476 'operation on')
477
478 # Start
479 subparser = subparsers.add_parser('start', help='Bring up the container',
480 formatter_class=formatter_class,
481 aliases=['up'])
482 _add_common_args(subparser)
483 subparser.add_argument('--image-size', default='16G',
484 help='Disk image size to resize to after download')
485 subparser.add_argument('--hkp-client', choices=('gpg', 'wget'),
486 default='gpg', help='Client for key retrieval')
487 subparser.add_argument(
488 '--skip-install', action='store_true',
489 help='Skip running make provision-dev in the container')
490
491 # Print IP address
492 subparser = subparsers.add_parser(
493 'ip', help='Print the IP address of the container.',
494 formatter_class=formatter_class)
495 _add_common_args(subparser)
496
497 # ssh
498 subparser = subparsers.add_parser('ssh', help='SSH into the container',
499 formatter_class=formatter_class)
500 _add_common_args(subparser)
501
502 # Run tests
503 subparser = subparsers.add_parser('run-tests',
504 help='Run tests in the container',
505 formatter_class=formatter_class)
506 _add_common_args(subparser)
507 subparser.add_argument(
508 '--pytest-args', nargs='...',
509 help='Additional arguments to pass to the pytest command')
510
511 # Stop
512 subparser = subparsers.add_parser('stop', help='Stop the container',
513 formatter_class=formatter_class,
514 aliases=['down'])
515 _add_common_args(subparser)
516
517 # Destroy
518 subparser = subparsers.add_parser('destroy',
519 help='Destroy the container image',
520 formatter_class=formatter_class)
521 _add_common_args(subparser)
522
523 # Update
524 subparser = subparsers.add_parser(
525 'update', help='Update the container image to the latest version',
526 formatter_class=formatter_class)
527 _add_common_args(subparser)
528 subparser.add_argument('--hkp-client', choices=('gpg', 'wget'),
529 default='gpg', help='Client for key retrieval')
530
531 # Display help message when no args are passed
532 if len(sys.argv) == 1:
533 parser.print_help()
534 sys.exit()
535
536 return parser.parse_args()
537
538
539 def _get_work_directory() -> pathlib.Path:
540 """Return script's working directory."""
541 return pathlib.Path(__file__).parent / '.container'
542
543
544 def _check_command(command) -> bool:
545 """Check that a command is present in PATH."""
546 if command == 'sudo':
547 which = ['which', command]
548 else:
549 which = ['sudo', 'which', command]
550
551 process = subprocess.run(which, stdout=subprocess.DEVNULL, check=False)
552 return process.returncode == 0
553
554
555 def _verify_dependencies() -> None:
556 """Ensure that all the dependencies are present."""
557 if not _check_command('sudo'):
558 logger.info('sudo command is needed. Run `apt install sudo`.')
559 sys.exit(1)
560
561 # Old versions of machinectl can't modprobe loop driver and immediately use
562 # it leading to machinectl start failing first time after boot. See
563 # https://github.com/systemd/systemd/issues/13130 . Workaround for old
564 # versions of machinectl. Ignore errors.
565 subprocess.run(['sudo', 'modprobe', '--all', '--quiet', 'loop'],
566 check=False)
567
568 dependencies = {
569 'systemd-nspawn': 'systemd-container',
570 'machinectl': 'systemd-container',
571 'kpartx': 'kpartx',
572 'wget': 'wget',
573 'gpg': 'gpg',
574 'xz': 'xz-utils',
575 'parted': 'parted',
576 'sgdisk': 'gdisk',
577 'btrfs': 'btrfs-progs',
578 'nmcli': 'network-manager',
579 'dnsmasq': 'dnsmasq',
580 'ssh': 'openssh-client',
581 'ssh-keygen': 'openssh-client',
582 'virsh': 'libvirt-clients',
583 }
584 missing_commands = []
585 missing_packages = []
586 for command, package in dependencies.items():
587 if not _check_command(command):
588 missing_commands.append(command)
589 missing_packages.append(package)
590
591 if not missing_commands:
592 return
593
594 logger.info('You need to install the following commands: %s',
595 ' '.join(missing_commands))
596
597 process = subprocess.run(['lsb_release', '--id', '--short'],
598 stdout=subprocess.PIPE, check=False)
599 if process.stdout.decode().strip() != 'Debian':
600 sys.exit(1)
601
602 logger.info('Running apt for missing packages: %s',
603 ' '.join(missing_packages))
604 subprocess.run(['sudo', 'apt', 'install'] + missing_packages, check=True)
605
606
607 def _download_file(url: str, target_file: pathlib.Path, force: bool = False):
608 """Download a file from remote URL."""
609 if target_file.exists():
610 if force:
611 os.remove(target_file)
612 else:
613 return
614
615 partial_file = target_file.with_suffix(target_file.suffix + '.partial')
616
617 logger.info('Downloading %s', target_file)
618 subprocess.run([
619 'wget', '--quiet', '--show-progress', '--continue',
620 '--output-document',
621 str(partial_file), url
622 ], check=True)
623 partial_file.rename(target_file)
624
625
626 def _receive_keys_with_gpg(gpg_home: pathlib.Path, key_ids: list[str]):
627 """Use gpg to retrieve and import a list of keys."""
628 subprocess.run([
629 'gpg', '--quiet', '--homedir',
630 str(gpg_home), '--keyserver', KEY_SERVER, '--recv-keys'
631 ] + key_ids, check=True)
632
633
634 def _receive_keys_with_wget(gpg_home: pathlib.Path, key_ids: list[str]):
635 """Use wget to retrieve a list of keys and import them."""
636 for key_id in key_ids:
637 # Download public key
638 logger.info('Getting public key %s', key_id)
639 url = KEY_SERVER_HTTPS_API.format(key_id=key_id)
640 wget_result = subprocess.run(
641 ['wget', '--quiet', '--output-document=-', url], check=True,
642 capture_output=True)
643 public_key = wget_result.stdout
644 subprocess.run(
645 ['gpg', '--quiet', '--homedir',
646 str(gpg_home), '--import=-'], input=public_key, check=True)
647
648
649 def _verify_signature(hkp_client: str, data_file: pathlib.Path,
650 signature_file: pathlib.Path):
651 """Verify the detached signature on a file using GPG."""
652 verified_file = signature_file.with_suffix(signature_file.suffix +
653 '.verified')
654 if verified_file.exists():
655 return
656
657 gpg_home = _get_work_directory() / 'gpg'
658 gpg_home.mkdir(exist_ok=True)
659 gpg_home.chmod(0o700)
660
661 logger.info('Receiving GPG keys')
662 if hkp_client == 'wget':
663 _receive_keys_with_wget(gpg_home, TRUSTED_KEYS)
664 else:
665 _receive_keys_with_gpg(gpg_home, TRUSTED_KEYS)
666
667 process = subprocess.run(
668 ['gpg', '--quiet', '--homedir',
669 str(gpg_home), '--armor', '--export'] + TRUSTED_KEYS, check=True,
670 stdout=subprocess.PIPE)
671 exported_keys = process.stdout
672 trusted_keys = gpg_home / 'trustedkeys.gpg'
673 subprocess.run([
674 'gpg', '--quiet', '--homedir',
675 str(gpg_home), '--no-default-keyring', '--keyring',
676 str(trusted_keys), '--import', '-'
677 ], check=True, input=exported_keys)
678
679 logger.info('Verify GPG signature')
680 subprocess.run([
681 'gpgv', '--quiet', '--homedir',
682 str(gpg_home),
683 str(signature_file),
684 str(data_file)
685 ], check=True)
686
687 verified_file.touch()
688
689
690 def _extract_image(compressed_file: pathlib.Path):
691 """Extract the image file."""
692 # Strip the .xz extension, then replace .img with .raw
693 decompressed_file = compressed_file.with_suffix('').with_suffix('.raw')
694 older_image = compressed_file.with_suffix('')
695
696 if decompressed_file.exists():
697 return decompressed_file
698
699 # Rename older image and its corresponding state files.
700 if older_image.exists():
701 logger.info('Renaming .img file to .raw')
702 older_image.rename(decompressed_file)
703
704 for ext in ['.setup', '.provisioned']:
705 old_state = older_image.with_suffix(older_image.suffix + ext)
706 new_state = decompressed_file.with_suffix(
707 decompressed_file.suffix + ext)
708 if old_state.exists():
709 old_state.rename(new_state)
710
711 return decompressed_file
712
713 logger.info('Decompressing file %s', compressed_file)
714 partial_file = compressed_file.with_suffix('.partial')
715 with partial_file.open('w', encoding='utf-8') as file_handle:
716 subprocess.run([
717 'xz', '--verbose', '--decompress', '--keep', '--to-stdout',
718 str(compressed_file)
719 ], check=True, stdout=file_handle)
720 partial_file.rename(decompressed_file)
721 return decompressed_file
722
723
724 def _get_compressed_image_path(distribution: str) -> pathlib.Path:
725 """Return the path of the compressed image."""
726 url = URLS[distribution]
727 result = urllib.parse.urlparse(url)
728
729 return _get_work_directory() / pathlib.Path(result.path).name
730
731
732 def _get_image_file(distribution: str) -> pathlib.Path:
733 """Return the path of the image file."""
734 compressed_image = _get_compressed_image_path(distribution)
735 # Strip the .xz extension, then replace .img with .raw
736 return compressed_image.with_suffix('').with_suffix('.raw')
737
738
739 def _get_project_folder() -> pathlib.Path:
740 """Return the read-only folder that should be exposed into container."""
741 return _get_work_directory().parent.resolve()
742
743
744 def _get_overlay_folder(distribution: str) -> pathlib.Path:
745 """Return the writable folder that should be exposed into container."""
746 default_data_dir = pathlib.Path.home() / '.local' / 'share'
747 data_folder = os.environ.get('XDG_DATA_HOME', default_data_dir)
748 folder = pathlib.Path(data_folder) / \
749 'freedombox-container' / 'overlay' / distribution
750 return folder.resolve()
751
752
753 def _download_disk_image(distribution: str, hkp_client: str,
754 force: bool = False) -> pathlib.Path:
755 """Download and unpack FreedomBox disk image."""
756 _get_work_directory().mkdir(exist_ok=True)
757
758 url = URLS[distribution]
759
760 target_file = _get_compressed_image_path(distribution)
761 _download_file(url, target_file, force=force)
762
763 signature_file = target_file.with_suffix(target_file.suffix + '.sig')
764 _download_file(url + '.sig', signature_file, force=force)
765
766 _verify_signature(hkp_client, target_file, signature_file)
767
768 return _extract_image(target_file)
769
770
771 def _get_partition_info(image_file: pathlib.Path) -> tuple[str, str]:
772 """Return the number of the final partition in the image file."""
773 process = subprocess.run(
774 ['sudo', 'parted', '--script',
775 str(image_file), 'print'], stdout=subprocess.PIPE, check=True)
776 lines = process.stdout.decode().splitlines()
777 last_partition_number = lines[-2].split()[0]
778 partition_table_type = 'msdos'
779 for line in lines:
780 if line.startswith('Partition Table:'):
781 partition_table_type = line.partition(': ')[2]
782
783 logger.info('Main partition: %s', last_partition_number)
784 return partition_table_type, last_partition_number
785
786
787 def _resize_disk_image(image_file: pathlib.Path, new_size: str,
788 distribution: str):
789 """Resize the disk image if has not already been."""
790 if new_size[-1] != 'G':
791 raise ValueError(f'Invalid size: {new_size}')
792
793 new_size_bytes = int(new_size.strip('G')) * 1024 * 1024 * 1024
794 image_size = image_file.stat().st_size
795 if image_size >= new_size_bytes:
796 return
797
798 logger.info('Resizing disk image to %s', new_size)
799
800 disk_free = shutil.disk_usage(_get_work_directory()).free
801 if disk_free < new_size_bytes - image_size:
802 raise ValueError(f'Not enough free space on disk: {disk_free} bytes')
803
804 subprocess.run(
805 ['truncate', '--size',
806 str(new_size_bytes),
807 str(image_file)], check=True)
808 partition_table_type, last_partition_number = _get_partition_info(
809 image_file)
810 if partition_table_type == 'gpt':
811 subprocess.run(
812 ['sudo', 'sgdisk', '--move-second-header',
813 str(image_file)], check=True)
814
815 subprocess.run([
816 'sudo', 'parted', '--align=optimal', '--script',
817 str(image_file), 'resizepart', last_partition_number, '100%'
818 ], check=True)
819 process = subprocess.run(
820 ['sudo', 'kpartx', '-avs', str(image_file)], stdout=subprocess.PIPE,
821 check=True)
822 last_line = process.stdout.decode().splitlines()[-1]
823 partition = '/dev/mapper/' + last_line.split()[2]
824 old_fsid = _get_fsid(partition)
825 subprocess.run(['sudo', 'btrfstune', '-uf', partition], check=True)
826 new_fsid = _get_fsid(partition)
827
828 with tempfile.TemporaryDirectory(
829 dir=_get_work_directory().resolve()) as mount_point:
830 subprocess.run(['sudo', 'mount', partition, mount_point], check=True)
831 time.sleep(2) # Mount may trigger some re-balancing
832 subprocess.run(
833 ['sudo', 'btrfs', 'filesystem', 'resize', 'max', mount_point],
834 check=True, stdout=subprocess.DEVNULL)
835 _update_fsid(mount_point, partition, old_fsid, new_fsid, distribution)
836 subprocess.run(['sudo', 'umount', mount_point], check=True)
837
838 subprocess.run(
839 ['sudo', 'kpartx', '-ds', str(image_file)], check=True,
840 stderr=subprocess.DEVNULL)
841
842
843 def _get_fsid(partition: str) -> str:
844 """Return the btrfs filesystem ID for a device."""
845 # Find the new FSID
846 process = subprocess.run(
847 ['sudo', 'btrfs', 'filesystem', 'show', partition], check=True,
848 stdout=subprocess.PIPE)
849 return process.stdout.decode().splitlines()[0].rpartition(' ')[2]
850
851
852 def _update_fsid(mount_point: str, partition: str, old_fsid: str,
853 new_fsid: str, distribution: str):
854 """After changing btrfs fsid, run grub-install to keep image bootable."""
855 is_efi = (platform.machine() in ('aarch64', 'arm64')
856 or distribution != 'oldstable')
857
858 # Guess the loopback device for the filesystem
859 matches = re.match(r'^/dev/mapper/loop(\d+)p(\d+)$', partition)
860 assert matches
861 loop_device = f'/dev/loop{matches[1]}'
862 if is_efi:
863 efi_device = f'/dev/mapper/loop{matches[1]}p{int(matches[2]) - 1}'
864
865 # Mount /dev, /proc and run grub commands in chroot
866 grub_args = []
867 if platform.machine() in ('aarch64', 'arm64'):
868 grub_args += ['--no-nvram']
869 elif distribution != 'oldstable':
870 grub_args += [
871 '--target=x86_64-efi', '--no-nvram', '--uefi-secure-boot'
872 ]
873
874 subprocess.run(
875 ['sudo', 'mount', '-o', 'bind', '/dev/', f'{mount_point}/dev'],
876 check=True)
877 subprocess.run(
878 ['sudo', 'mount', '-o', 'bind', '/proc/', f'{mount_point}/proc'],
879 check=True)
880 if is_efi:
881 subprocess.run(
882 ['sudo', 'mount', efi_device, f'{mount_point}/boot/efi'],
883 check=True)
884
885 subprocess.run(['sudo', 'chroot', mount_point, 'update-grub'], check=True)
886 subprocess.run(
887 ['sudo', 'chroot', mount_point, 'grub-install', loop_device] +
888 grub_args, check=True)
889 subprocess.run([
890 'sudo', 'chroot', mount_point, 'sed', '-ie',
891 f's|UUID={old_fsid}|UUID={new_fsid}|', '/etc/fstab'
892 ], check=True)
893 if is_efi:
894 subprocess.run(['sudo', 'umount', f'{mount_point}/boot/efi'],
895 check=True)
896
897 subprocess.run(['sudo', 'umount', f'{mount_point}/proc'], check=True)
898 subprocess.run(['sudo', 'umount', f'{mount_point}/dev'], check=True)
899
900
901 def _runc(image_file: pathlib.Path, command: list[str], **kwargs):
902 """Run a command inside the container."""
903 subprocess.run([
904 'sudo', 'systemd-nspawn', '--image',
905 str(image_file), '--console=autopipe', '--quiet'
906 ] + command, check=True, **kwargs)
907
908
909 def _setup_users(image_file: pathlib.Path):
910 """Change UID, GID and password of fbx user in container."""
911 folder = _get_project_folder()
912
913 uid = 10000
914 gid = 10000
915 logger.info('In image: Setting UID/GID of "fbx" to %s/%s', uid, gid)
916 _runc(image_file, ['groupmod', '--gid', str(gid), 'fbx'])
917 _runc(image_file, ['usermod', '--uid',
918 str(uid), '--gid',
919 str(gid), 'fbx'], stdout=subprocess.DEVNULL)
920
921 uid = folder.stat().st_uid
922 gid = folder.stat().st_gid
923 logger.info(
924 'In image: Setting UID/GID of "plinth" to %s/%s to match %s/%s', uid,
925 gid, folder.owner(), folder.group())
926 _runc(image_file, ['groupmod', '--gid', str(gid), 'plinth'])
927 _runc(image_file,
928 ['usermod', '--uid',
929 str(uid), '--gid',
930 str(gid), 'plinth'], stdout=subprocess.DEVNULL)
931
932 logger.info('In image: Setting up sudo for users "fbx" and "plinth"')
933 sudo_config = 'fbx ALL=(ALL:ALL) NOPASSWD : ALL\n'
934 _runc(image_file, ['tee', '/etc/sudoers.d/01-freedombox-development'],
935 input=sudo_config.encode(), stdout=subprocess.DEVNULL)
936
937
938 def _setup_ssh(image_file: pathlib.Path):
939 """Setup SSH server and client keys."""
940 logger.info('In image: Generating SSH server keys')
941 _runc(image_file, ['dpkg-reconfigure', 'openssh-server'],
942 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
943
944 ssh_directory = _get_work_directory() / 'ssh'
945 ssh_directory.mkdir(exist_ok=True)
946 ssh_directory.chmod(0o700)
947
948 key_file = ssh_directory / 'id_ed25519'
949 if not key_file.exists():
950 logger.info('Generating SSH client key %s', key_file)
951 subprocess.run(
952 ['ssh-keygen', '-t', 'ed25519', '-N', '', '-f',
953 str(key_file)], stdout=subprocess.DEVNULL, check=True)
954
955 public_key_file = key_file.with_suffix('.pub')
956 public_key = public_key_file.read_bytes()
957 if not public_key:
958 logger.error('Unable to read SSH public key from %s', public_key_file)
959 sys.exit(1)
960
961 logger.info(
962 'Adding SSH client key to "fbx" user authorized keys in container')
963 _runc(image_file, ['mkdir', '--parents', '/home/fbx/.ssh'])
964 _runc(image_file, ['tee', '--append', '/home/fbx/.ssh/authorized_keys'],
965 input=public_key, stdout=subprocess.DEVNULL)
966 _runc(image_file, ['chmod', '600', '/home/fbx/.ssh/authorized_keys'])
967 _runc(image_file, ['chown', 'fbx:fbx', '/home/fbx/.ssh/authorized_keys'])
968
969
970 def _setup_image(image_file: pathlib.Path, skip_install: bool = False):
971 """Prepare the image for execution."""
972 setup_file = image_file.with_suffix(image_file.suffix + '.setup')
973 if setup_file.exists():
974 return
975
976 logger.info('In image: Disabling automatic updates temporarily')
977 contents = 'APT::Periodic::Update-Package-Lists "0";\n' \
978 'APT::Periodic::Unattended-Upgrade "0";\n'
979 _runc(image_file, ['tee', '/etc/apt/apt.conf.d/20auto-upgrades'],
980 input=contents.encode())
981
982 if not skip_install:
983 logger.info('In image: Disabling FreedomBox service')
984 _runc(image_file, ['systemctl', 'disable', 'plinth'],
985 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
986
987 logger.info('In image: Creating virtiofs mount at /freedombox')
988 mount = '''[Unit]
989 Description=FreedomBox development directory on host
990 ConditionVirtualization=kvm
991
992 [Mount]
993 What=freedombox
994 Where=/freedombox
995 Type=virtiofs
996
997 [Install]
998 WantedBy=multi-user.target
999 '''
1000 _runc(image_file, ['tee', '/usr/lib/systemd/system/freedombox.mount'],
1001 input=mount.encode(), stdout=subprocess.DEVNULL)
1002 _runc(image_file, ['systemctl', 'enable', 'freedombox.mount'],
1003 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
1004
1005 _setup_ssh(image_file)
1006
1007 _setup_users(image_file)
1008
1009 setup_file.touch()
1010 logger.info('Setup completed')
1011
1012
1013 def _destroy_image(distribution: str):
1014 """Remove all traces of the machine and its image."""
1015 image_file = _get_image_file(distribution)
1016 logger.info('Removing image file %s', image_file)
1017 try:
1018 image_file.with_suffix(image_file.suffix + '.provisioned').unlink()
1019 except FileNotFoundError:
1020 pass
1021
1022 try:
1023 image_file.with_suffix(image_file.suffix + '.setup').unlink()
1024 except FileNotFoundError:
1025 pass
1026
1027 try:
1028 image_file.unlink()
1029 except FileNotFoundError:
1030 pass
1031
1032 logger.info('Keeping downloaded image: %s',
1033 _get_compressed_image_path(distribution))
1034
1035
1036 def _is_provisioned(distribution: str) -> bool:
1037 """Return the container has been provisioned fully."""
1038 image_file = _get_image_file(distribution)
1039 provision_file = image_file.with_suffix(image_file.suffix + '.provisioned')
1040 return provision_file.exists()
1041
1042
1043 def _provision(image_file: pathlib.Path, machine_type: str, distribution: str,
1044 skip_install: bool = False):
1045 """Run app setup inside the container."""
1046 if _is_provisioned(distribution):
1047 return
1048
1049 if skip_install:
1050 logger.info('Skipping provision step (--skip-install)')
1051 else:
1052 machine = Machine.get_instance(machine_type, distribution)
1053 ssh_command = machine.get_ssh_command()
1054 subprocess.run(ssh_command + ['bash'], check=True,
1055 input=PROVISION_SCRIPT.encode())
1056
1057 provision_file = image_file.with_suffix(image_file.suffix + '.provisioned')
1058 provision_file.touch()
1059 logger.info('Provision completed')
1060
1061
1062 def _print_banner(machine_type: str, distribution: str):
1063 """Print a friendly message on how to use."""
1064 machine = Machine.get_instance(machine_type, distribution)
1065 ip_address = _wait_for(lambda: machine.get_ip_address())
1066
1067 _get_work_directory().owner()
1068 script = sys.argv[0]
1069 options = ''
1070 if distribution != 'testing':
1071 options = f'--distribution={distribution}'
1072
1073 project_folder = _get_project_folder()
1074 overlay_folder = _get_overlay_folder(distribution)
1075 message = f'''==== Ready ====
1076
1077 Development user : fbx
1078 Plinth user : (host){project_folder.owner()} -> (container)plinth
1079 Folder overlay : (host, read-only){project_folder}
1080 + (host, read-write){overlay_folder}
1081 -> (container)/freedombox
1082
1083 SSH easily : {script} ssh {options}
1084 Run tests : {script} run-tests {options} [ --pytest-args ... ]
1085 Watch FreedomBox logs : sudo freedombox-logs
1086
1087 Web access : https://{ip_address}/
1088 Ports access : Any port on {ip_address}
1089
1090 Terminal login : sudo machinectl login fbx-{distribution}
1091 Open a root shell : sudo machinectl shell fbx-{distribution}
1092 Shutdown : {script} stop {options}
1093 Destroy : {script} destroy {options}
1094 Reset : {script} destroy {options}; {script} start {options}'''
1095 logger.info(message)
1096
1097
1098 def _wait_for(method: Callable[[], None | object]):
1099 """Wait until a condition is satisfied or finally give up."""
1100 for _ in range(60):
1101 return_value = method()
1102 if return_value:
1103 return return_value
1104
1105 logger.info('Waiting for machine')
1106 time.sleep(3)
1107
1108 logger.error('Failed')
1109 sys.exit(1)
1110
1111
1112 def _get_latest_image_timestamp(distribution: str) -> float:
1113 """Get the timestamp of the latest available image."""
1114 url = URLS[distribution]
1115 response = urlopen(url[0:url.rindex('/')])
1116 page_contents = response.read().decode()
1117 str_time = re.findall(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}', page_contents)[0]
1118 return datetime.datetime.strptime(str_time, '%Y-%m-%d %H:%M').timestamp()
1119
1120
1121 def _is_update_required(distribution: str) -> bool:
1122 """Compare local image timestamp against the latest image timestamp."""
1123 file_path = _get_work_directory() / URLS[distribution].split('/')[-1]
1124
1125 if not file_path.exists():
1126 return True
1127
1128 local_image_timestamp = os.path.getmtime(file_path)
1129 one_day = datetime.timedelta(days=1).total_seconds()
1130 latest_image_timestamp = _get_latest_image_timestamp(distribution)
1131 return latest_image_timestamp - local_image_timestamp > one_day
1132
1133
1134 class Machine:
1135 """Base class for different types of machines."""
1136
1137 def __init__(self, distribution: str):
1138 """Initialize the machine object."""
1139 machine_name = f'fbx-{distribution}'
1140 self.machine_name = machine_name
1141 self.distribution = distribution
1142
1143 @staticmethod
1144 def get_instance(machine_type: str, distribution: str):
1145 """Return instance of a concrete machine class based on type."""
1146 if machine_type == 'container':
1147 return Container(distribution)
1148
1149 if machine_type == 'vm':
1150 return VM(distribution)
1151
1152 raise ValueError('Unknown machine type')
1153
1154 def get_status(self) -> bool:
1155 """Return whether the machine is currently running."""
1156 return False
1157
1158 def setup(self) -> None:
1159 """Setup the infrastructure needed for the machine."""
1160
1161 def launch(self) -> None:
1162 """Start the machine."""
1163
1164 def stop(self) -> None:
1165 """Stop the machine."""
1166
1167 def terminate(self) -> None:
1168 """Terminate, i.e., force stop the machine."""
1169
1170 def destroy(self) -> None:
1171 """Remove all traces of the machine from the host."""
1172
1173 def get_ip_address(self) -> str | None:
1174 """Return the IP address assigned to the machine."""
1175
1176 def get_ssh_command(self) -> list[str]:
1177 """Return the SSH command to execute for the machine."""
1178 return []
1179
1180
1181 class Container(Machine):
1182 """Handle container specific operations."""
1183
1184 def get_status(self) -> bool:
1185 """Return the running status of a container."""
1186 process = subprocess.run(
1187 ['sudo', 'machinectl', 'status', self.machine_name],
1188 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
1189 return process.returncode == 0
1190
1191 def setup(self) -> None:
1192 """Setup the infrastructure needed for the container."""
1193 self._setup_nm_connection()
1194
1195 def launch(self) -> None:
1196 """Start the container."""
1197 self._create_nspawn_machine()
1198
1199 logger.info('Running `machinectl start %s`', self.machine_name)
1200 subprocess.run(['sudo', 'machinectl', 'start', self.machine_name],
1201 check=True)
1202
1203 logger.info('Bringing up host network connection: %s',
1204 f'fbx-{self.distribution}-shared')
1205 # This command requires dnsmasq
1206 subprocess.run([
1207 'sudo', 'nmcli', 'connection', 'up',
1208 f'fbx-{self.distribution}-shared'
1209 ], stdout=subprocess.DEVNULL, check=True)
1210
1211 def stop(self) -> None:
1212 """Stop the container."""
1213 logger.info('Running `machinectl stop %s`', self.machine_name)
1214 subprocess.run(['sudo', 'machinectl', 'stop', self.machine_name],
1215 check=False)
1216
1217 def terminate(self) -> None:
1218 """Terminate, i.e., force stop the container."""
1219 logger.info('Running `machinectl terminate %s`', self.machine_name)
1220 subprocess.run(['sudo', 'machinectl', 'terminate', self.machine_name],
1221 check=False)
1222
1223 def destroy(self) -> None:
1224 """Remove all traces of the machine from the host."""
1225 image_link = pathlib.Path(f'/var/lib/machines/{self.machine_name}.raw')
1226
1227 logger.info('Removing link to systemd-nspawn image %s', image_link)
1228 subprocess.run(['sudo', 'rm', '--force', str(image_link)], check=False)
1229 nspawn_file = f'/run/systemd/nspawn/{self.machine_name}.nspawn'
1230
1231 logger.info('Removing systemd-nspawn configuration: %s', nspawn_file)
1232 subprocess.run(['sudo', 'rm', '--force', nspawn_file], check=False)
1233
1234 overlay_folder = _get_overlay_folder(self.distribution)
1235 logger.info('Removing overlay folder with container written data: %s',
1236 overlay_folder)
1237 subprocess.run(['sudo', 'rm', '-r', '--force', overlay_folder],
1238 check=False)
1239
1240 connection_name = f'fbx-{self.distribution}-shared'
1241 logger.info('Removing Network Manager connection %s', connection_name)
1242 result = subprocess.run(
1243 ['sudo', 'nmcli', 'connection', 'delete', connection_name],
1244 capture_output=True, check=False)
1245 if result.returncode not in (0, 10):
1246 # nmcli failed and not due to 'Connection, device, or access point
1247 # does not exist.' See
1248 # https://developer-old.gnome.org/NetworkManager/stable/nmcli.html
1249 logger.error('nmcli returned code %d', result.returncode)
1250 logger.error('Error message:\n%s', result.stderr.decode())
1251 logger.error('Output:\n%s', result.stdout.decode())
1252
1253 def get_ip_address(self) -> str | None:
1254 """Return the IPv4 address assigned to the container or None."""
1255 process = subprocess.run(
1256 ['machinectl', 'list', '--output=json', '--max-addresses=all'],
1257 stdout=subprocess.PIPE, check=True)
1258 output = process.stdout.decode()
1259 if not output:
1260 return None
1261
1262 machines = json.loads(output)
1263 for machine in machines:
1264 if (machine['machine'] == f'fbx-{self.distribution}'
1265 and machine['addresses'] not in (None, '-')):
1266 for address in machine['addresses'].split():
1267 if ipaddress.ip_address(address).version == 4:
1268 return address
1269
1270 return None
1271
1272 def get_ssh_command(self) -> list[str]:
1273 """Return the SSH command to execute for the container."""
1274 ip_address = _wait_for(lambda: self.get_ip_address())
1275 public_key = _get_work_directory() / 'ssh' / 'id_ed25519'
1276 if ipaddress.ip_address(ip_address).is_link_local:
1277 ip_address = f'{ip_address}%' + self._get_interface_name()
1278
1279 return [
1280 'ssh', '-Y', '-C', '-t', '-i',
1281 str(public_key), '-o', 'LogLevel=error', '-o',
1282 'StrictHostKeyChecking=no', '-o', 'UserKnownHostsFile=/dev/null',
1283 '-o', 'IdentitiesOnly=yes', f'fbx@{ip_address}'
1284 ]
1285
1286 def _get_interface_name(self) -> str:
1287 """Return the name of the interface."""
1288 return f've-fbx-{self.distribution}'
1289
1290 def _setup_nm_connection(self) -> None:
1291 """Create a NM conn. on host for DHCP/DNS with container."""
1292 connection_name = f'fbx-{self.distribution}-shared'
1293 process = subprocess.run(
1294 ['sudo', 'nmcli', 'connection', 'show', connection_name],
1295 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
1296 if not process.returncode:
1297 return
1298
1299 logger.info('Creating Network Manager connection in host: %s',
1300 connection_name)
1301 properties = {
1302 'connection.id': connection_name,
1303 'connection.type': '802-3-ethernet',
1304 'connection.interface-name': self._get_interface_name(),
1305 'connection.autoconnect': 'yes',
1306 'connection.zone': 'trusted',
1307 'ipv4.method': 'shared',
1308 }
1309 subprocess.run(['sudo', 'nmcli', 'connection', 'add'] +
1310 list(itertools.chain(*properties.items())), check=True)
1311 subprocess.run(['sudo', 'nmcli', 'connection', 'up', connection_name],
1312 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
1313 check=False)
1314
1315 def _create_nspawn_machine(self) -> None:
1316 """Create systemd-nspawn options/image used by machinectl."""
1317 image_file = _get_image_file(self.distribution)
1318 overlay_folder = _get_overlay_folder(self.distribution)
1319 logger.info('Creating overlay folder %s', overlay_folder)
1320 overlay_folder.mkdir(parents=True, exist_ok=True)
1321
1322 nspawn_dir = pathlib.Path('/run/systemd/nspawn/')
1323 if not nspawn_dir.exists():
1324 subprocess.run(['sudo', 'mkdir', '--mode=700',
1325 str(nspawn_dir)], check=True)
1326
1327 nspawn_options = f'''[Exec]
1328 Boot=yes
1329 PrivateUsers=no
1330 # Allow all system calls to enable podman containers inside the nspawn
1331 # container.
1332 SystemCallFilter=@known
1333
1334 [Files]
1335 Overlay={_get_project_folder()}:{overlay_folder}:/freedombox
1336
1337 [Network]
1338 VirtualEthernet=yes
1339 '''
1340 nspawn_file = f'/run/systemd/nspawn/{self.machine_name}.nspawn'
1341 logger.info('Creating systemd-nspawn configuration: %s', nspawn_file)
1342 subprocess.run(['sudo', 'rm', '--force', nspawn_file], check=False)
1343 subprocess.run(['sudo', 'tee', nspawn_file],
1344 input=nspawn_options.encode(),
1345 stdout=subprocess.DEVNULL, check=True)
1346
1347 image_link = pathlib.Path(f'/var/lib/machines/{self.machine_name}.raw')
1348 logger.info('Linking systemd-nspawn image %s -> %s', image_link,
1349 image_file)
1350 result = subprocess.run(
1351 ['sudo', 'test', '-e', str(image_link)], check=False)
1352 if not result.returncode:
1353 result = subprocess.run(
1354 ['sudo', 'test', '-L', str(image_link)], check=False)
1355 if result.returncode:
1356 raise Exception(f'Image file {image_link} is not a symlink.')
1357
1358 # May be linked to wrong place (such as old .img file)
1359 subprocess.run(['sudo', 'rm', '--force', str(image_link)], check=False)
1360 subprocess.run([
1361 'sudo', 'ln', '--symbolic',
1362 str(image_file.resolve()),
1363 str(image_link)
1364 ], check=False)
1365
1366
1367 class VM(Machine):
1368 """Handle VM specific operations."""
1369
1370 def get_status(self) -> bool:
1371 """Return whether the VM is currently running."""
1372 process = self._virsh(['domstate', self.machine_name], check=False,
1373 stdout=subprocess.PIPE,
1374 stderr=subprocess.DEVNULL)
1375 return process.stdout.decode().splitlines()[0] not in ('shut off', '')
1376
1377 def setup(self) -> None:
1378 """Setup the infrastructure needed for the VM."""
1379 try:
1380 self._virsh(['dominfo', self.machine_name],
1381 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
1382 return # Already exists
1383 except subprocess.CalledProcessError:
1384 pass
1385
1386 qcow_image = self._create_qcow_image()
1387 firmware = 'firmware="efi"' if self.distribution != 'oldstable' else ''
1388 domain_xml = LIBVIRT_DOMAIN_XML_TEMPLATE.format(
1389 domain_name=self.machine_name, memory_mib='2048', cpus='4',
1390 firmware=firmware, image_file=qcow_image,
1391 source_dir=_get_project_folder())
1392
1393 with tempfile.NamedTemporaryFile() as file_handle:
1394 file_handle.write(domain_xml.encode())
1395 logger.info('Running `virsh define %s`', file_handle.name)
1396 self._virsh(['define', file_handle.name],
1397 stdout=subprocess.DEVNULL)
1398
1399 def launch(self) -> None:
1400 """Start the VM."""
1401 if self.get_status():
1402 return
1403
1404 logger.info('Running `virsh start %s`', self.machine_name)
1405 self._virsh(['start', self.machine_name], stdout=subprocess.DEVNULL)
1406
1407 def stop(self) -> None:
1408 """Stop the VM."""
1409 if not self.get_status(): # Already shut off
1410 return
1411
1412 logger.info('Running `virsh shutdown %s`', self.machine_name)
1413 self._virsh(['shutdown', self.machine_name], stdout=subprocess.DEVNULL)
1414
1415 def terminate(self) -> None:
1416 """Terminate, i.e., force stop the VM."""
1417 if not self.get_status(): # Already shut off
1418 return
1419
1420 logger.info('Running `virsh destroy %s`', self.machine_name)
1421 try:
1422 self._virsh(['undefine', '--nvram', self.machine_name],
1423 stdout=subprocess.DEVNULL)
1424 except subprocess.CalledProcessError:
1425 pass
1426
1427 def destroy(self) -> None:
1428 """Remove all traces of the VM from the host."""
1429 logger.info('Running `virsh undefine %s`', self.machine_name)
1430 try:
1431 self._virsh(['undefine', '--nvram', self.machine_name],
1432 stdout=subprocess.DEVNULL)
1433 except subprocess.CalledProcessError:
1434 pass
1435
1436 self._destroy_qcow_image()
1437
1438 def get_ip_address(self) -> str | None:
1439 """Return the IP address assigned to the VM."""
1440 try:
1441 process = self._virsh(['domifaddr', self.machine_name],
1442 stdout=subprocess.PIPE)
1443 except subprocess.CalledProcessError:
1444 return None
1445
1446 lines = process.stdout.decode().splitlines()
1447 if len(lines) < 3: # First two lines are header
1448 return None
1449
1450 # Example: 'vnet12 52:54:00:55:8c:68 ipv4 192.168.122.203/24'
1451 return lines[2].rpartition(' ')[2].partition('/')[0]
1452
1453 def get_ssh_command(self) -> list[str]:
1454 """Return the SSH command to execute for the VM."""
1455 ip_address = _wait_for(lambda: self.get_ip_address())
1456 public_key = _get_work_directory() / 'ssh' / 'id_ed25519'
1457 return [
1458 'ssh', '-Y', '-C', '-t', '-i',
1459 str(public_key), '-o', 'LogLevel=error', '-o',
1460 'StrictHostKeyChecking=no', '-o', 'UserKnownHostsFile=/dev/null',
1461 '-o', 'IdentitiesOnly=yes', f'fbx@{ip_address}'
1462 ]
1463
1464 def _virsh(self, args: list[str], check=True, **kwargs):
1465 """Run virsh to control the virtual machine."""
1466 return subprocess.run(['sudo', 'virsh'] + args, check=check, **kwargs)
1467
1468 def _create_qcow_image(self) -> pathlib.Path:
1469 """Convert raw image into qcow2 image.
1470
1471 qcow2 image format allows snapshots of VM.
1472 """
1473 image_file = _get_image_file(self.distribution)
1474 qcow_image = image_file.with_suffix('.qcow2')
1475 logger.info('Creating qcow2 image: %s', qcow_image)
1476 subprocess.run([
1477 'sudo', 'qemu-img', 'convert', '-f', 'raw', '-O', 'qcow2',
1478 image_file, qcow_image
1479 ], check=True)
1480 return qcow_image
1481
1482 def _destroy_qcow_image(self) -> None:
1483 """Delete the qcow image."""
1484 image_file = _get_image_file(self.distribution)
1485 qcow_image = image_file.with_suffix('.qcow2')
1486 logger.info('Removing qcow2 image: %s', qcow_image)
1487 qcow_image.unlink(missing_ok=True)
1488
1489
1490 def subcommand_start(arguments: argparse.Namespace):
1491 """Download, setup and bring up the container."""
1492 machine = Machine.get_instance(arguments.machine_type,
1493 arguments.distribution)
1494 if machine.get_status() and _is_provisioned(arguments.distribution):
1495 logger.info('Container is already running')
1496 _print_banner(arguments.machine_type, arguments.distribution)
1497 return
1498
1499 _verify_dependencies()
1500 image_file = _download_disk_image(arguments.distribution,
1501 arguments.hkp_client)
1502 _resize_disk_image(image_file, arguments.image_size,
1503 arguments.distribution)
1504 _setup_image(image_file, arguments.skip_install)
1505 machine.setup()
1506 machine.launch()
1507 _provision(image_file, arguments.machine_type, arguments.distribution,
1508 arguments.skip_install)
1509 _print_banner(arguments.machine_type, arguments.distribution)
1510
1511
1512 def subcommand_ip(arguments: argparse.Namespace):
1513 """Print the IP address of the container."""
1514 machine = Machine.get_instance(arguments.machine_type,
1515 arguments.distribution)
1516 print(machine.get_ip_address() or '')
1517
1518
1519 def subcommand_ssh(arguments: argparse.Namespace):
1520 """Open an SSH shell into the container."""
1521 machine = Machine.get_instance(arguments.machine_type,
1522 arguments.distribution)
1523 command = machine.get_ssh_command()
1524 logger.info('Running command: %s', ' '.join(command))
1525 os.execlp('ssh', *command)
1526
1527
1528 def subcommand_run_tests(arguments: argparse.Namespace):
1529 """Run tests in the container."""
1530 distribution = arguments.distribution
1531 machine = Machine.get_instance(arguments.machine_type, distribution)
1532 pytest_args_list = arguments.pytest_args or []
1533 pytest_args = ' '.join((shlex.quote(arg) for arg in pytest_args_list))
1534
1535 ssh_command = machine.get_ssh_command()
1536
1537 pytest_command = f'py.test-3 --color=yes {pytest_args}'
1538 logger.info('Pytest command: %s', pytest_command)
1539
1540 test_script = SETUP_AND_RUN_TESTS_SCRIPT.format(
1541 pytest_command=pytest_command, distribution=distribution)
1542 command = ssh_command + ['sudo', 'bash']
1543 process = subprocess.run(command, input=test_script.encode(), check=False)
1544 sys.exit(process.returncode)
1545
1546
1547 def subcommand_stop(arguments: argparse.Namespace):
1548 """Stop the container."""
1549 machine = Machine.get_instance(arguments.machine_type,
1550 arguments.distribution)
1551 machine.stop()
1552 _wait_for(lambda: not machine.get_status())
1553
1554
1555 def subcommand_destroy(arguments: argparse.Namespace):
1556 """Destroy the disk image."""
1557 machine = Machine.get_instance(arguments.machine_type,
1558 arguments.distribution)
1559 machine.terminate()
1560 _wait_for(lambda: not machine.get_status())
1561
1562 machine.destroy()
1563 _destroy_image(arguments.distribution)
1564
1565
1566 def subcommand_update(arguments: argparse.Namespace):
1567 """Update the disk image."""
1568 if _is_update_required(arguments.distribution):
1569 logger.info('Updating...')
1570 _download_disk_image(arguments.distribution, arguments.hkp_client,
1571 force=True)
1572 else:
1573 logger.info('Already using the latest image')
1574
1575
1576 def set_URLs() -> None:
1577 global URLS
1578 arch = platform.machine()
1579 if arch == 'x86_64' or arch == 'amd64':
1580 URLS = URLS_AMD64
1581 elif arch == 'aarch64' or arch == 'arm64':
1582 URLS = URLS_ARM64
1583 else:
1584 logger.error('Unsupported architecture:', arch)
1585 sys.exit(1)
1586
1587
1588 def main():
1589 """Parse arguments and perform operations."""
1590 set_URLs()
1591
1592 logging.basicConfig(level='INFO', format='> %(message)s')
1593 arguments = parse_arguments()
1594
1595 aliases = {
1596 'up': 'start',
1597 'down': 'stop',
1598 }
1599
1600 subcommand: str = arguments.subcommand.replace('-', '_')
1601 subcommand = aliases.get(subcommand, subcommand)
1602 subcommand_method = globals()['subcommand_' + subcommand]
1603 subcommand_method(arguments)
1604
1605
1606 if __name__ == '__main__':
1607 main()