blob: 5481c3ff524effa1fe0ad21b0669732e69f3d6dd [file] [log] [blame]
Mateusz Zalega43e21072021-10-08 18:05:29 +02001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17// Installer creates a Metropolis image at a suitable block device based on the
18// installer bundle present in the installation medium's ESP, after which it
19// reboots. It's meant to be used as an init process.
20package main
21
22import (
Lorenz Brun0b93c8d2021-11-09 03:58:40 +010023 "archive/zip"
Lorenz Brun57d06a72022-01-13 14:12:27 +010024 "errors"
Mateusz Zalega43e21072021-10-08 18:05:29 +020025 "fmt"
Lorenz Brunad131882023-06-28 16:42:20 +020026 "io/fs"
Mateusz Zalega43e21072021-10-08 18:05:29 +020027 "os"
28 "path/filepath"
29 "strings"
30 "syscall"
Lorenz Brun57d06a72022-01-13 14:12:27 +010031 "time"
Mateusz Zalega43e21072021-10-08 18:05:29 +020032
33 "golang.org/x/sys/unix"
Serge Bazanski97783222021-12-14 16:04:26 +010034
Mateusz Zalega43e21072021-10-08 18:05:29 +020035 "source.monogon.dev/metropolis/node/build/mkimage/osimage"
Lorenz Brunad131882023-06-28 16:42:20 +020036 "source.monogon.dev/metropolis/pkg/blockdev"
Mateusz Zalega43e21072021-10-08 18:05:29 +020037 "source.monogon.dev/metropolis/pkg/efivarfs"
38 "source.monogon.dev/metropolis/pkg/sysfs"
39)
40
41const mib = 1024 * 1024
42
43// mountPseudoFS mounts efivarfs, devtmpfs and sysfs, used by the installer in
44// the block device discovery stage.
45func mountPseudoFS() error {
46 for _, m := range []struct {
47 dir string
48 fs string
49 flags uintptr
50 }{
51 {"/sys", "sysfs", unix.MS_NOEXEC | unix.MS_NOSUID | unix.MS_NODEV},
52 {efivarfs.Path, "efivarfs", unix.MS_NOEXEC | unix.MS_NOSUID | unix.MS_NODEV},
53 {"/dev", "devtmpfs", unix.MS_NOEXEC | unix.MS_NOSUID},
54 } {
55 if err := unix.Mkdir(m.dir, 0700); err != nil && !os.IsExist(err) {
56 return fmt.Errorf("couldn't create the mountpoint at %q: %w", m.dir, err)
57 }
58 if err := unix.Mount(m.fs, m.dir, m.fs, m.flags, ""); err != nil {
59 return fmt.Errorf("couldn't mount %q at %q: %w", m.fs, m.dir, err)
60 }
61 }
62 return nil
63}
64
65// mountInstallerESP mounts the filesystem the installer was loaded from based
66// on espPath, which must point to the appropriate partition block device. The
67// filesystem is mounted at /installer.
68func mountInstallerESP(espPath string) error {
69 // Create the mountpoint.
70 if err := unix.Mkdir("/installer", 0700); err != nil {
71 return fmt.Errorf("couldn't create the installer mountpoint: %w", err)
72 }
73 // Mount the filesystem.
74 if err := unix.Mount(espPath, "/installer", "vfat", unix.MS_NOEXEC|unix.MS_RDONLY, ""); err != nil {
75 return fmt.Errorf("couldn't mount the installer ESP (%q -> %q): %w", espPath, "/installer", err)
76 }
77 return nil
78}
79
80// findInstallableBlockDevices returns names of all the block devices suitable
81// for hosting a Metropolis installation, limited by the size expressed in
82// bytes minSize. The install medium espDev will be excluded from the result.
83func findInstallableBlockDevices(espDev string, minSize uint64) ([]string, error) {
84 // Use the partition's name to find and return the name of its parent
85 // device. It will be excluded from the list of suitable target devices.
86 srcDev, err := sysfs.ParentBlockDevice(espDev)
87 // Build the exclusion list containing forbidden handle prefixes.
88 exclude := []string{"dm-", "zram", "ram", "loop", srcDev}
89
90 // Get the block device handles by looking up directory contents.
91 const blkDirPath = "/sys/class/block"
92 blkDevs, err := os.ReadDir(blkDirPath)
93 if err != nil {
94 return nil, fmt.Errorf("couldn't read %q: %w", blkDirPath, err)
95 }
96 // Iterate over the handles, skipping any block device that either points to
97 // a partition, matches the exclusion list, or is smaller than minSize.
98 var suitable []string
99probeLoop:
100 for _, devInfo := range blkDevs {
101 // Skip devices according to the exclusion list.
102 for _, prefix := range exclude {
103 if strings.HasPrefix(devInfo.Name(), prefix) {
104 continue probeLoop
105 }
106 }
107
108 // Skip partition symlinks.
109 if _, err := os.Stat(filepath.Join(blkDirPath, devInfo.Name(), "partition")); err == nil {
110 continue
111 } else if !os.IsNotExist(err) {
112 return nil, fmt.Errorf("while probing sysfs: %w", err)
113 }
114
115 // Skip devices of insufficient size.
116 devPath := filepath.Join("/dev", devInfo.Name())
Lorenz Brunad131882023-06-28 16:42:20 +0200117 dev, err := blockdev.Open(devPath)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200118 if err != nil {
119 return nil, fmt.Errorf("couldn't open a block device at %q: %w", devPath, err)
120 }
Lorenz Brunad131882023-06-28 16:42:20 +0200121 devSize := uint64(dev.BlockCount() * dev.BlockSize())
Mateusz Zalega43e21072021-10-08 18:05:29 +0200122 dev.Close()
Lorenz Brunad131882023-06-28 16:42:20 +0200123 if devSize < minSize {
Mateusz Zalega43e21072021-10-08 18:05:29 +0200124 continue
125 }
126
127 suitable = append(suitable, devInfo.Name())
128 }
129 return suitable, nil
130}
131
Lorenz Brunad131882023-06-28 16:42:20 +0200132// FileSizedReader is a small adapter from fs.File to fs.SizedReader
133// Panics on Stat() failure, so should only be used with sources where Stat()
134// cannot fail.
135type FileSizedReader struct {
136 fs.File
Mateusz Zalega43e21072021-10-08 18:05:29 +0200137}
138
Lorenz Brunad131882023-06-28 16:42:20 +0200139func (f FileSizedReader) Size() int64 {
140 stat, err := f.Stat()
Mateusz Zalega43e21072021-10-08 18:05:29 +0200141 if err != nil {
Lorenz Brunad131882023-06-28 16:42:20 +0200142 panic(err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200143 }
Lorenz Brunad131882023-06-28 16:42:20 +0200144 return stat.Size()
Mateusz Zalega43e21072021-10-08 18:05:29 +0200145}
146
147func main() {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100148 // Reboot on panic after a delay. The error string will have been printed
149 // before recover is called.
150 defer func() {
151 if r := recover(); r != nil {
Serge Bazanskif71fe922023-03-22 01:10:37 +0100152 logf("Fatal error: %v", r)
153 logf("The installation could not be finalized. Please reboot to continue.")
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100154 syscall.Pause()
155 }
156 }()
157
Mateusz Zalega43e21072021-10-08 18:05:29 +0200158 // Mount sysfs, devtmpfs and efivarfs.
159 if err := mountPseudoFS(); err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100160 panicf("While mounting pseudo-filesystems: %v", err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200161 }
Serge Bazanskif71fe922023-03-22 01:10:37 +0100162
163 go logPiper()
164 logf("Metropolis Installer")
165 logf("Copyright (c) 2023 The Monogon Project Authors")
166 logf("")
167
Mateusz Zalega43e21072021-10-08 18:05:29 +0200168 // Read the installer ESP UUID from efivarfs.
169 espUuid, err := efivarfs.ReadLoaderDevicePartUUID()
170 if err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100171 panicf("While reading the installer ESP UUID: %v", err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200172 }
Lorenz Brun57d06a72022-01-13 14:12:27 +0100173 // Wait for up to 30 tries @ 1s (30s) for the ESP to show up
174 var espDev string
175 var retries = 30
176 for {
177 // Look up the installer partition based on espUuid.
178 espDev, err = sysfs.DeviceByPartUUID(espUuid)
179 if err == nil {
180 break
181 } else if errors.Is(err, sysfs.ErrDevNotFound) && retries > 0 {
182 time.Sleep(1 * time.Second)
183 retries--
184 } else {
185 panicf("While resolving the installer device handle: %v", err)
186 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200187 }
Lorenz Brun57d06a72022-01-13 14:12:27 +0100188 espPath := filepath.Join("/dev", espDev)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200189 // Mount the installer partition. The installer bundle will be read from it.
190 if err := mountInstallerESP(espPath); err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100191 panicf("While mounting the installer ESP: %v", err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200192 }
193
Lorenz Brun6c35e972021-12-14 03:08:23 +0100194 nodeParameters, err := os.Open("/installer/metropolis-installer/nodeparams.pb")
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100195 if err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100196 panicf("Failed to open node parameters from ESP: %v", err)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100197 }
198
199 // TODO(lorenz): Replace with proper bundles
Lorenz Brun6c35e972021-12-14 03:08:23 +0100200 bundle, err := zip.OpenReader("/installer/metropolis-installer/bundle.bin")
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100201 if err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100202 panicf("Failed to open node bundle from ESP: %v", err)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100203 }
204 defer bundle.Close()
205 efiPayload, err := bundle.Open("kernel_efi.efi")
206 if err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100207 panicf("Cannot open EFI payload in bundle: %v", err)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100208 }
209 defer efiPayload.Close()
Mateusz Zalega8c2c7712022-01-25 19:42:21 +0100210 systemImage, err := bundle.Open("verity_rootfs.img")
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100211 if err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100212 panicf("Cannot open system image in bundle: %v", err)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100213 }
214 defer systemImage.Close()
215
Mateusz Zalega43e21072021-10-08 18:05:29 +0200216 // Build the osimage parameters.
217 installParams := osimage.Params{
218 PartitionSize: osimage.PartitionSizeInfo{
219 // ESP is the size of the node ESP partition, expressed in mebibytes.
Lorenz Brun35fcf032023-06-29 04:15:58 +0200220 ESP: 384,
Mateusz Zalega43e21072021-10-08 18:05:29 +0200221 // System is the size of the node system partition, expressed in
222 // mebibytes.
223 System: 4096,
224 // Data must be nonzero in order for the data partition to be created.
225 // osimage will extend the data partition to fill all the available space
226 // whenever it's writing to block devices, such as now.
227 Data: 128,
228 },
Lorenz Brunad131882023-06-28 16:42:20 +0200229 SystemImage: systemImage,
230 EFIPayload: FileSizedReader{efiPayload},
231 NodeParameters: FileSizedReader{nodeParameters},
Mateusz Zalega43e21072021-10-08 18:05:29 +0200232 }
233 // Calculate the minimum target size based on the installation parameters.
234 minSize := uint64((installParams.PartitionSize.ESP +
235 installParams.PartitionSize.System +
236 installParams.PartitionSize.Data + 1) * mib)
237
238 // Look for suitable block devices, given the minimum size.
239 blkDevs, err := findInstallableBlockDevices(espDev, minSize)
240 if err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100241 panicf(err.Error())
Mateusz Zalega43e21072021-10-08 18:05:29 +0200242 }
243 if len(blkDevs) == 0 {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100244 panicf("Couldn't find a suitable block device.")
Mateusz Zalega43e21072021-10-08 18:05:29 +0200245 }
246 // Set the first suitable block device found as the installation target.
247 tgtBlkdevName := blkDevs[0]
248 // Update the osimage parameters with a path pointing at the target device.
249 tgtBlkdevPath := filepath.Join("/dev", tgtBlkdevName)
Lorenz Brunad131882023-06-28 16:42:20 +0200250
251 tgtBlockDev, err := blockdev.Open(tgtBlkdevPath)
252 if err != nil {
253 panicf("error opening target device: %v", err)
254 }
255 installParams.Output = tgtBlockDev
Mateusz Zalega43e21072021-10-08 18:05:29 +0200256
257 // Use osimage to partition the target block device and set up its ESP.
258 // Create will return an EFI boot entry on success.
Serge Bazanskif71fe922023-03-22 01:10:37 +0100259 logf("Installing to %s...", tgtBlkdevPath)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200260 be, err := osimage.Create(&installParams)
261 if err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100262 panicf("While installing: %v", err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200263 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200264
265 // Create an EFI boot entry for Metropolis.
Lorenz Brunca1cff02023-06-26 17:52:44 +0200266 en, err := efivarfs.AddBootEntry(be)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200267 if err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100268 panicf("While creating a boot entry: %v", err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200269 }
270 // Erase the preexisting boot order, leaving Metropolis as the only option.
Lorenz Brun9933ef02023-07-06 18:28:29 +0200271 if err := efivarfs.SetBootOrder(efivarfs.BootOrder{uint16(en)}); err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100272 panicf("While adjusting the boot order: %v", err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200273 }
274
275 // Reboot.
Lorenz Brunad131882023-06-28 16:42:20 +0200276 tgtBlockDev.Close()
Mateusz Zalega43e21072021-10-08 18:05:29 +0200277 unix.Sync()
Serge Bazanskif71fe922023-03-22 01:10:37 +0100278 logf("Installation completed. Rebooting.")
Mateusz Zalega43e21072021-10-08 18:05:29 +0200279 unix.Reboot(unix.LINUX_REBOOT_CMD_RESTART)
280}