blob: e2d0d5523249809b57f5d95d33441fefeb3e25e8 [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 Brun54a5a052023-10-02 16:40:11 +020024 "bytes"
25 _ "embed"
Lorenz Brun57d06a72022-01-13 14:12:27 +010026 "errors"
Mateusz Zalega43e21072021-10-08 18:05:29 +020027 "fmt"
Lorenz Brunad131882023-06-28 16:42:20 +020028 "io/fs"
Mateusz Zalega43e21072021-10-08 18:05:29 +020029 "os"
30 "path/filepath"
31 "strings"
32 "syscall"
Lorenz Brun57d06a72022-01-13 14:12:27 +010033 "time"
Mateusz Zalega43e21072021-10-08 18:05:29 +020034
35 "golang.org/x/sys/unix"
Serge Bazanski97783222021-12-14 16:04:26 +010036
Tim Windelschmidt9f21f532024-05-07 15:14:20 +020037 "source.monogon.dev/osbase/blockdev"
Tim Windelschmidtc2290c22024-08-15 19:56:00 +020038 "source.monogon.dev/osbase/build/mkimage/osimage"
Tim Windelschmidt9f21f532024-05-07 15:14:20 +020039 "source.monogon.dev/osbase/efivarfs"
40 "source.monogon.dev/osbase/sysfs"
Mateusz Zalega43e21072021-10-08 18:05:29 +020041)
42
Lorenz Brun54a5a052023-10-02 16:40:11 +020043//go:embed metropolis/node/core/abloader/abloader_bin.efi
44var abloader []byte
45
Mateusz Zalega43e21072021-10-08 18:05:29 +020046const mib = 1024 * 1024
47
48// mountPseudoFS mounts efivarfs, devtmpfs and sysfs, used by the installer in
49// the block device discovery stage.
50func mountPseudoFS() error {
51 for _, m := range []struct {
52 dir string
53 fs string
54 flags uintptr
55 }{
56 {"/sys", "sysfs", unix.MS_NOEXEC | unix.MS_NOSUID | unix.MS_NODEV},
57 {efivarfs.Path, "efivarfs", unix.MS_NOEXEC | unix.MS_NOSUID | unix.MS_NODEV},
58 {"/dev", "devtmpfs", unix.MS_NOEXEC | unix.MS_NOSUID},
59 } {
60 if err := unix.Mkdir(m.dir, 0700); err != nil && !os.IsExist(err) {
61 return fmt.Errorf("couldn't create the mountpoint at %q: %w", m.dir, err)
62 }
63 if err := unix.Mount(m.fs, m.dir, m.fs, m.flags, ""); err != nil {
64 return fmt.Errorf("couldn't mount %q at %q: %w", m.fs, m.dir, err)
65 }
66 }
67 return nil
68}
69
70// mountInstallerESP mounts the filesystem the installer was loaded from based
71// on espPath, which must point to the appropriate partition block device. The
72// filesystem is mounted at /installer.
73func mountInstallerESP(espPath string) error {
74 // Create the mountpoint.
75 if err := unix.Mkdir("/installer", 0700); err != nil {
76 return fmt.Errorf("couldn't create the installer mountpoint: %w", err)
77 }
78 // Mount the filesystem.
79 if err := unix.Mount(espPath, "/installer", "vfat", unix.MS_NOEXEC|unix.MS_RDONLY, ""); err != nil {
80 return fmt.Errorf("couldn't mount the installer ESP (%q -> %q): %w", espPath, "/installer", err)
81 }
82 return nil
83}
84
85// findInstallableBlockDevices returns names of all the block devices suitable
86// for hosting a Metropolis installation, limited by the size expressed in
87// bytes minSize. The install medium espDev will be excluded from the result.
88func findInstallableBlockDevices(espDev string, minSize uint64) ([]string, error) {
89 // Use the partition's name to find and return the name of its parent
90 // device. It will be excluded from the list of suitable target devices.
91 srcDev, err := sysfs.ParentBlockDevice(espDev)
Tim Windelschmidtcc27faa2024-08-01 02:18:35 +020092 if err != nil {
Tim Windelschmidt096654a2024-04-18 23:10:19 +020093 return nil, fmt.Errorf("failed to fetch parent device: %w", err)
94 }
Mateusz Zalega43e21072021-10-08 18:05:29 +020095 // Build the exclusion list containing forbidden handle prefixes.
96 exclude := []string{"dm-", "zram", "ram", "loop", srcDev}
97
98 // Get the block device handles by looking up directory contents.
99 const blkDirPath = "/sys/class/block"
100 blkDevs, err := os.ReadDir(blkDirPath)
101 if err != nil {
102 return nil, fmt.Errorf("couldn't read %q: %w", blkDirPath, err)
103 }
104 // Iterate over the handles, skipping any block device that either points to
105 // a partition, matches the exclusion list, or is smaller than minSize.
106 var suitable []string
107probeLoop:
108 for _, devInfo := range blkDevs {
109 // Skip devices according to the exclusion list.
110 for _, prefix := range exclude {
111 if strings.HasPrefix(devInfo.Name(), prefix) {
112 continue probeLoop
113 }
114 }
115
116 // Skip partition symlinks.
117 if _, err := os.Stat(filepath.Join(blkDirPath, devInfo.Name(), "partition")); err == nil {
118 continue
119 } else if !os.IsNotExist(err) {
120 return nil, fmt.Errorf("while probing sysfs: %w", err)
121 }
122
123 // Skip devices of insufficient size.
124 devPath := filepath.Join("/dev", devInfo.Name())
Lorenz Brunad131882023-06-28 16:42:20 +0200125 dev, err := blockdev.Open(devPath)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200126 if err != nil {
127 return nil, fmt.Errorf("couldn't open a block device at %q: %w", devPath, err)
128 }
Lorenz Brunad131882023-06-28 16:42:20 +0200129 devSize := uint64(dev.BlockCount() * dev.BlockSize())
Mateusz Zalega43e21072021-10-08 18:05:29 +0200130 dev.Close()
Lorenz Brunad131882023-06-28 16:42:20 +0200131 if devSize < minSize {
Mateusz Zalega43e21072021-10-08 18:05:29 +0200132 continue
133 }
134
135 suitable = append(suitable, devInfo.Name())
136 }
137 return suitable, nil
138}
139
Lorenz Brunad131882023-06-28 16:42:20 +0200140// FileSizedReader is a small adapter from fs.File to fs.SizedReader
141// Panics on Stat() failure, so should only be used with sources where Stat()
142// cannot fail.
143type FileSizedReader struct {
144 fs.File
Mateusz Zalega43e21072021-10-08 18:05:29 +0200145}
146
Lorenz Brunad131882023-06-28 16:42:20 +0200147func (f FileSizedReader) Size() int64 {
148 stat, err := f.Stat()
Mateusz Zalega43e21072021-10-08 18:05:29 +0200149 if err != nil {
Lorenz Brunad131882023-06-28 16:42:20 +0200150 panic(err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200151 }
Lorenz Brunad131882023-06-28 16:42:20 +0200152 return stat.Size()
Mateusz Zalega43e21072021-10-08 18:05:29 +0200153}
154
155func main() {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100156 // Reboot on panic after a delay. The error string will have been printed
157 // before recover is called.
158 defer func() {
159 if r := recover(); r != nil {
Serge Bazanskif71fe922023-03-22 01:10:37 +0100160 logf("Fatal error: %v", r)
161 logf("The installation could not be finalized. Please reboot to continue.")
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100162 syscall.Pause()
163 }
164 }()
165
Mateusz Zalega43e21072021-10-08 18:05:29 +0200166 // Mount sysfs, devtmpfs and efivarfs.
167 if err := mountPseudoFS(); err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100168 panicf("While mounting pseudo-filesystems: %v", err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200169 }
Serge Bazanskif71fe922023-03-22 01:10:37 +0100170
171 go logPiper()
172 logf("Metropolis Installer")
173 logf("Copyright (c) 2023 The Monogon Project Authors")
174 logf("")
175
Mateusz Zalega43e21072021-10-08 18:05:29 +0200176 // Read the installer ESP UUID from efivarfs.
177 espUuid, err := efivarfs.ReadLoaderDevicePartUUID()
178 if err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100179 panicf("While reading the installer ESP UUID: %v", err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200180 }
Lorenz Brun57d06a72022-01-13 14:12:27 +0100181 // Wait for up to 30 tries @ 1s (30s) for the ESP to show up
182 var espDev string
183 var retries = 30
184 for {
185 // Look up the installer partition based on espUuid.
186 espDev, err = sysfs.DeviceByPartUUID(espUuid)
187 if err == nil {
188 break
189 } else if errors.Is(err, sysfs.ErrDevNotFound) && retries > 0 {
190 time.Sleep(1 * time.Second)
191 retries--
192 } else {
193 panicf("While resolving the installer device handle: %v", err)
194 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200195 }
Lorenz Brun57d06a72022-01-13 14:12:27 +0100196 espPath := filepath.Join("/dev", espDev)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200197 // Mount the installer partition. The installer bundle will be read from it.
198 if err := mountInstallerESP(espPath); err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100199 panicf("While mounting the installer ESP: %v", err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200200 }
201
Lorenz Brun6c35e972021-12-14 03:08:23 +0100202 nodeParameters, err := os.Open("/installer/metropolis-installer/nodeparams.pb")
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100203 if err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100204 panicf("Failed to open node parameters from ESP: %v", err)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100205 }
206
207 // TODO(lorenz): Replace with proper bundles
Lorenz Brun6c35e972021-12-14 03:08:23 +0100208 bundle, err := zip.OpenReader("/installer/metropolis-installer/bundle.bin")
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100209 if err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100210 panicf("Failed to open node bundle from ESP: %v", err)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100211 }
212 defer bundle.Close()
213 efiPayload, err := bundle.Open("kernel_efi.efi")
214 if err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100215 panicf("Cannot open EFI payload in bundle: %v", err)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100216 }
217 defer efiPayload.Close()
Mateusz Zalega8c2c7712022-01-25 19:42:21 +0100218 systemImage, err := bundle.Open("verity_rootfs.img")
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100219 if err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100220 panicf("Cannot open system image in bundle: %v", err)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100221 }
222 defer systemImage.Close()
223
Mateusz Zalega43e21072021-10-08 18:05:29 +0200224 // Build the osimage parameters.
225 installParams := osimage.Params{
226 PartitionSize: osimage.PartitionSizeInfo{
227 // ESP is the size of the node ESP partition, expressed in mebibytes.
Lorenz Brun35fcf032023-06-29 04:15:58 +0200228 ESP: 384,
Mateusz Zalega43e21072021-10-08 18:05:29 +0200229 // System is the size of the node system partition, expressed in
230 // mebibytes.
231 System: 4096,
232 // Data must be nonzero in order for the data partition to be created.
233 // osimage will extend the data partition to fill all the available space
234 // whenever it's writing to block devices, such as now.
235 Data: 128,
236 },
Lorenz Brunad131882023-06-28 16:42:20 +0200237 SystemImage: systemImage,
238 EFIPayload: FileSizedReader{efiPayload},
Lorenz Brun54a5a052023-10-02 16:40:11 +0200239 ABLoader: bytes.NewReader(abloader),
Lorenz Brunad131882023-06-28 16:42:20 +0200240 NodeParameters: FileSizedReader{nodeParameters},
Mateusz Zalega43e21072021-10-08 18:05:29 +0200241 }
242 // Calculate the minimum target size based on the installation parameters.
243 minSize := uint64((installParams.PartitionSize.ESP +
Jan Schär42ef7c72024-03-18 15:09:51 +0100244 installParams.PartitionSize.System*2 +
Mateusz Zalega43e21072021-10-08 18:05:29 +0200245 installParams.PartitionSize.Data + 1) * mib)
246
247 // Look for suitable block devices, given the minimum size.
248 blkDevs, err := findInstallableBlockDevices(espDev, minSize)
249 if err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100250 panicf(err.Error())
Mateusz Zalega43e21072021-10-08 18:05:29 +0200251 }
252 if len(blkDevs) == 0 {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100253 panicf("Couldn't find a suitable block device.")
Mateusz Zalega43e21072021-10-08 18:05:29 +0200254 }
255 // Set the first suitable block device found as the installation target.
256 tgtBlkdevName := blkDevs[0]
257 // Update the osimage parameters with a path pointing at the target device.
258 tgtBlkdevPath := filepath.Join("/dev", tgtBlkdevName)
Lorenz Brunad131882023-06-28 16:42:20 +0200259
260 tgtBlockDev, err := blockdev.Open(tgtBlkdevPath)
261 if err != nil {
262 panicf("error opening target device: %v", err)
263 }
264 installParams.Output = tgtBlockDev
Mateusz Zalega43e21072021-10-08 18:05:29 +0200265
266 // Use osimage to partition the target block device and set up its ESP.
Tim Windelschmidtcc27faa2024-08-01 02:18:35 +0200267 // Write will return an EFI boot entry on success.
Serge Bazanskif71fe922023-03-22 01:10:37 +0100268 logf("Installing to %s...", tgtBlkdevPath)
Tim Windelschmidtcc27faa2024-08-01 02:18:35 +0200269 be, err := osimage.Write(&installParams)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200270 if err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100271 panicf("While installing: %v", err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200272 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200273
274 // Create an EFI boot entry for Metropolis.
Lorenz Brunca1cff02023-06-26 17:52:44 +0200275 en, err := efivarfs.AddBootEntry(be)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200276 if err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100277 panicf("While creating a boot entry: %v", err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200278 }
279 // Erase the preexisting boot order, leaving Metropolis as the only option.
Lorenz Brun9933ef02023-07-06 18:28:29 +0200280 if err := efivarfs.SetBootOrder(efivarfs.BootOrder{uint16(en)}); err != nil {
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100281 panicf("While adjusting the boot order: %v", err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200282 }
283
284 // Reboot.
Lorenz Brunad131882023-06-28 16:42:20 +0200285 tgtBlockDev.Close()
Mateusz Zalega43e21072021-10-08 18:05:29 +0200286 unix.Sync()
Serge Bazanskif71fe922023-03-22 01:10:37 +0100287 logf("Installation completed. Rebooting.")
Mateusz Zalega43e21072021-10-08 18:05:29 +0200288 unix.Reboot(unix.LINUX_REBOOT_CMD_RESTART)
289}