blob: 356247a8807edf5d2fa8c21aec5a6da2b6b2b215 [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 (
23 "fmt"
24 "io"
25 "log"
26 "os"
27 "path/filepath"
28 "strings"
29 "syscall"
30
31 "golang.org/x/sys/unix"
32 "source.monogon.dev/metropolis/node/build/mkimage/osimage"
33 "source.monogon.dev/metropolis/pkg/efivarfs"
34 "source.monogon.dev/metropolis/pkg/sysfs"
35)
36
37const mib = 1024 * 1024
38
39// mountPseudoFS mounts efivarfs, devtmpfs and sysfs, used by the installer in
40// the block device discovery stage.
41func mountPseudoFS() error {
42 for _, m := range []struct {
43 dir string
44 fs string
45 flags uintptr
46 }{
47 {"/sys", "sysfs", unix.MS_NOEXEC | unix.MS_NOSUID | unix.MS_NODEV},
48 {efivarfs.Path, "efivarfs", unix.MS_NOEXEC | unix.MS_NOSUID | unix.MS_NODEV},
49 {"/dev", "devtmpfs", unix.MS_NOEXEC | unix.MS_NOSUID},
50 } {
51 if err := unix.Mkdir(m.dir, 0700); err != nil && !os.IsExist(err) {
52 return fmt.Errorf("couldn't create the mountpoint at %q: %w", m.dir, err)
53 }
54 if err := unix.Mount(m.fs, m.dir, m.fs, m.flags, ""); err != nil {
55 return fmt.Errorf("couldn't mount %q at %q: %w", m.fs, m.dir, err)
56 }
57 }
58 return nil
59}
60
61// mountInstallerESP mounts the filesystem the installer was loaded from based
62// on espPath, which must point to the appropriate partition block device. The
63// filesystem is mounted at /installer.
64func mountInstallerESP(espPath string) error {
65 // Create the mountpoint.
66 if err := unix.Mkdir("/installer", 0700); err != nil {
67 return fmt.Errorf("couldn't create the installer mountpoint: %w", err)
68 }
69 // Mount the filesystem.
70 if err := unix.Mount(espPath, "/installer", "vfat", unix.MS_NOEXEC|unix.MS_RDONLY, ""); err != nil {
71 return fmt.Errorf("couldn't mount the installer ESP (%q -> %q): %w", espPath, "/installer", err)
72 }
73 return nil
74}
75
76// findInstallableBlockDevices returns names of all the block devices suitable
77// for hosting a Metropolis installation, limited by the size expressed in
78// bytes minSize. The install medium espDev will be excluded from the result.
79func findInstallableBlockDevices(espDev string, minSize uint64) ([]string, error) {
80 // Use the partition's name to find and return the name of its parent
81 // device. It will be excluded from the list of suitable target devices.
82 srcDev, err := sysfs.ParentBlockDevice(espDev)
83 // Build the exclusion list containing forbidden handle prefixes.
84 exclude := []string{"dm-", "zram", "ram", "loop", srcDev}
85
86 // Get the block device handles by looking up directory contents.
87 const blkDirPath = "/sys/class/block"
88 blkDevs, err := os.ReadDir(blkDirPath)
89 if err != nil {
90 return nil, fmt.Errorf("couldn't read %q: %w", blkDirPath, err)
91 }
92 // Iterate over the handles, skipping any block device that either points to
93 // a partition, matches the exclusion list, or is smaller than minSize.
94 var suitable []string
95probeLoop:
96 for _, devInfo := range blkDevs {
97 // Skip devices according to the exclusion list.
98 for _, prefix := range exclude {
99 if strings.HasPrefix(devInfo.Name(), prefix) {
100 continue probeLoop
101 }
102 }
103
104 // Skip partition symlinks.
105 if _, err := os.Stat(filepath.Join(blkDirPath, devInfo.Name(), "partition")); err == nil {
106 continue
107 } else if !os.IsNotExist(err) {
108 return nil, fmt.Errorf("while probing sysfs: %w", err)
109 }
110
111 // Skip devices of insufficient size.
112 devPath := filepath.Join("/dev", devInfo.Name())
113 dev, err := os.Open(devPath)
114 if err != nil {
115 return nil, fmt.Errorf("couldn't open a block device at %q: %w", devPath, err)
116 }
117 size, err := unix.IoctlGetInt(int(dev.Fd()), unix.BLKGETSIZE64)
118 dev.Close()
119 if err != nil {
120 return nil, fmt.Errorf("couldn't probe the size of %q: %w", devPath, err)
121 }
122 if uint64(size) < minSize {
123 continue
124 }
125
126 suitable = append(suitable, devInfo.Name())
127 }
128 return suitable, nil
129}
130
131// rereadPartitionTable causes the kernel to read the partition table present
132// in the block device at blkdevPath. It may return an error.
133func rereadPartitionTable(blkdevPath string) error {
134 dev, err := os.Open(blkdevPath)
135 if err != nil {
136 return fmt.Errorf("couldn't open the block device at %q: %w", blkdevPath, err)
137 }
138 defer dev.Close()
139 ret, err := unix.IoctlRetInt(int(dev.Fd()), unix.BLKRRPART)
140 if err != nil {
141 return fmt.Errorf("while doing an ioctl: %w", err)
142 }
143 if syscall.Errno(ret) == unix.EINVAL {
144 return fmt.Errorf("got an EINVAL from BLKRRPART ioctl")
145 }
146 return nil
147}
148
149// initializeSystemPartition writes image contents to the node's system
150// partition using the block device abstraction layer as opposed to slower
151// go-diskfs. tgtBlkdev must contain a path pointing to the block device
152// associated with the system partition. It may return an error.
153func initializeSystemPartition(image io.Reader, tgtBlkdev string) error {
154 // Check that tgtBlkdev points at an actual block device.
155 info, err := os.Stat(tgtBlkdev)
156 if err != nil {
157 return fmt.Errorf("couldn't stat the system partition at %q: %w", tgtBlkdev, err)
158 }
159 if info.Mode()&os.ModeDevice == 0 {
160 return fmt.Errorf("system partition path %q doesn't point to a block device", tgtBlkdev)
161 }
162
163 // Get the system partition's file descriptor.
164 sys, err := os.OpenFile(tgtBlkdev, os.O_WRONLY, 0600)
165 if err != nil {
166 return fmt.Errorf("couldn't open the system partition at %q: %w", tgtBlkdev, err)
167 }
168 defer sys.Close()
169 // Copy the system partition contents. Use a bigger buffer to optimize disk
170 // writes.
171 buf := make([]byte, mib)
172 if _, err := io.CopyBuffer(sys, image, buf); err != nil {
173 return fmt.Errorf("couldn't copy partition contents: %w", err)
174 }
175 return nil
176}
177
178func main() {
179 // Mount sysfs, devtmpfs and efivarfs.
180 if err := mountPseudoFS(); err != nil {
181 log.Fatalf("while mounting pseudo-filesystems: %s", err.Error())
182 }
183 // Read the installer ESP UUID from efivarfs.
184 espUuid, err := efivarfs.ReadLoaderDevicePartUUID()
185 if err != nil {
186 log.Fatalf("while reading the installer ESP UUID: %s", err.Error())
187 }
188 // Look up the installer partition based on espUuid.
189 espDev, err := sysfs.DeviceByPartUUID(espUuid)
190 espPath := filepath.Join("/dev", espDev)
191 if err != nil {
192 log.Fatalf("while resolving the installer device handle: %s", err.Error())
193 }
194 // Mount the installer partition. The installer bundle will be read from it.
195 if err := mountInstallerESP(espPath); err != nil {
196 log.Fatalf("while mounting the installer ESP: %s", err.Error())
197 }
198
199 // Build the osimage parameters.
200 installParams := osimage.Params{
201 PartitionSize: osimage.PartitionSizeInfo{
202 // ESP is the size of the node ESP partition, expressed in mebibytes.
203 ESP: 128,
204 // System is the size of the node system partition, expressed in
205 // mebibytes.
206 System: 4096,
207 // Data must be nonzero in order for the data partition to be created.
208 // osimage will extend the data partition to fill all the available space
209 // whenever it's writing to block devices, such as now.
210 Data: 128,
211 },
212 // Due to a bug in go-diskfs causing slow writes, SystemImage is explicitly
213 // marked unused here, as system partition contents will be written using
214 // a workaround below instead.
215 // TODO(mateusz@monogon.tech): Address that bug either by patching go-diskfs
216 // or rewriting osimage.
217 SystemImage: nil,
218 // TODO(mateusz@monogon.tech): Plug in.
219 EFIPayload: strings.NewReader("TODO"),
220 NodeParameters: strings.NewReader("TODO"),
221 }
222 // Calculate the minimum target size based on the installation parameters.
223 minSize := uint64((installParams.PartitionSize.ESP +
224 installParams.PartitionSize.System +
225 installParams.PartitionSize.Data + 1) * mib)
226
227 // Look for suitable block devices, given the minimum size.
228 blkDevs, err := findInstallableBlockDevices(espDev, minSize)
229 if err != nil {
230 log.Fatal(err.Error())
231 }
232 if len(blkDevs) == 0 {
233 log.Fatal("couldn't find a suitable block device.")
234 }
235 // Set the first suitable block device found as the installation target.
236 tgtBlkdevName := blkDevs[0]
237 // Update the osimage parameters with a path pointing at the target device.
238 tgtBlkdevPath := filepath.Join("/dev", tgtBlkdevName)
239 installParams.OutputPath = tgtBlkdevPath
240
241 // Use osimage to partition the target block device and set up its ESP.
242 // Create will return an EFI boot entry on success.
243 log.Printf("Installing to %s\n", tgtBlkdevPath)
244 be, err := osimage.Create(&installParams)
245 if err != nil {
246 log.Fatalf("while installing: %s", err.Error())
247 }
248 // The target device's partition table has just been updated. Re-read it to
249 // make the node system partition reachable through /dev.
250 if err := rereadPartitionTable(tgtBlkdevPath); err != nil {
251 log.Fatalf("while re-reading the partition table of %q: %s", tgtBlkdevPath, err.Error())
252 }
253 // Look up the node's system partition path to be later used in the
254 // initialization step. It's always the second partition, right after
255 // the ESP.
256 sysBlkdevName, err := sysfs.PartitionBlockDevice(tgtBlkdevName, 2)
257 if err != nil {
258 log.Fatalf("while looking up the system partition: %s", err.Error())
259 }
260 sysBlkdevPath := filepath.Join("/dev", sysBlkdevName)
261 // Copy the system partition contents.
262 contents := strings.NewReader("TODO") // TODO(mz): plug in
263 if err := initializeSystemPartition(contents, sysBlkdevPath); err != nil {
264 log.Fatalf("while initializing the system partition at %q: %s", sysBlkdevPath, err.Error())
265 }
266
267 // Create an EFI boot entry for Metropolis.
268 en, err := efivarfs.CreateBootEntry(be)
269 if err != nil {
270 log.Fatalf("while creating a boot entry: %s", err.Error())
271 }
272 // Erase the preexisting boot order, leaving Metropolis as the only option.
273 if err := efivarfs.SetBootOrder(&efivarfs.BootOrder{uint16(en)}); err != nil {
274 log.Fatalf("while adjusting the boot order: %s", err.Error())
275 }
276
277 // Reboot.
278 unix.Sync()
279 log.Print("Installation completed. Rebooting.")
280 unix.Reboot(unix.LINUX_REBOOT_CMD_RESTART)
281}