blob: b36c70d361d8c2137855356947ee6cbd5a0f4b1c [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// This package runs the installer image in a VM provided with an empty block
18// device. It then examines the installer console output and the blok device to
19// determine whether the installation process completed without issue.
20package main
21
22import (
Serge Bazanskie2e03712021-12-17 12:47:03 +010023 "context"
Mateusz Zalega43e21072021-10-08 18:05:29 +020024 "fmt"
25 "io"
26 "log"
27 "os"
28 "os/exec"
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010029 "path/filepath"
Serge Bazanskie2e03712021-12-17 12:47:03 +010030 "strings"
Mateusz Zalega43e21072021-10-08 18:05:29 +020031 "syscall"
32 "testing"
33
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010034 "github.com/bazelbuild/rules_go/go/tools/bazel"
Mateusz Zalega43e21072021-10-08 18:05:29 +020035 diskfs "github.com/diskfs/go-diskfs"
36 "github.com/diskfs/go-diskfs/disk"
37 "github.com/diskfs/go-diskfs/partition/gpt"
Lorenz Brun0b93c8d2021-11-09 03:58:40 +010038
Mateusz Zalega43e21072021-10-08 18:05:29 +020039 mctl "source.monogon.dev/metropolis/cli/metroctl/core"
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010040 "source.monogon.dev/metropolis/node/build/mkimage/osimage"
Serge Bazanskie2e03712021-12-17 12:47:03 +010041 "source.monogon.dev/metropolis/pkg/logbuffer"
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010042 "source.monogon.dev/metropolis/proto/api"
Mateusz Zalega43e21072021-10-08 18:05:29 +020043)
44
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010045// Each variable in this block points to either a test dependency or a side
46// effect. These variables are initialized in TestMain using Bazel.
47var (
48 // installerEFIPayload is a filesystem path pointing at the unified kernel
49 // image dependency.
50 installerEFIPayload string
51 // testOSBundle is a filesystem path pointing at the Metropolis installation
52 // bundle.
53 testOSBundle string
54 // installerImage is a filesystem path pointing at the installer image that
55 // is generated during the test, and is removed afterwards.
56 installerImage string
57 // nodeStorage is a filesystem path pointing at the VM block device image
58 // Metropolis is installed to during the test. The file is removed afterwards.
59 nodeStorage string
Mateusz Zalega43e21072021-10-08 18:05:29 +020060)
61
Serge Bazanskie2e03712021-12-17 12:47:03 +010062// runQemu starts a QEMU process and waits until it either finishes or the given
63// expectedOutput appears in a line emitted to stdout or stderr. It returns true
64// if it was found, false otherwise.
65//
66// The qemu process will be killed when the context cancels or the function
67// exits.
68func runQemu(ctx context.Context, args []string, expectedOutput string) (bool, error) {
Mateusz Zalega43e21072021-10-08 18:05:29 +020069 // Prepare the default parameter list.
70 defaultArgs := []string{
71 "-machine", "q35", "-accel", "kvm", "-nographic", "-nodefaults",
72 "-m", "512",
73 "-smp", "2",
74 "-cpu", "host",
75 "-drive", "if=pflash,format=raw,readonly,file=external/edk2/OVMF_CODE.fd",
76 "-drive", "if=pflash,format=raw,snapshot=on,file=external/edk2/OVMF_VARS.fd",
Mateusz Zalega43e21072021-10-08 18:05:29 +020077 "-serial", "stdio",
78 "-no-reboot",
79 }
Serge Bazanskie2e03712021-12-17 12:47:03 +010080
81 // Make a sub-context to ensure that qemu exits when this function is done.
82 ctxQ, ctxC := context.WithCancel(ctx)
83 defer ctxC()
84
Mateusz Zalega43e21072021-10-08 18:05:29 +020085 // Join the parameter lists and prepare the Qemu command, but don't run it
86 // just yet.
87 qemuArgs := append(defaultArgs, args...)
Serge Bazanskie2e03712021-12-17 12:47:03 +010088 qemuCmd := exec.CommandContext(ctxQ, "external/qemu/qemu-x86_64-softmmu", qemuArgs...)
Mateusz Zalega43e21072021-10-08 18:05:29 +020089
Serge Bazanskie2e03712021-12-17 12:47:03 +010090 // Copy the stdout and stderr output to a single channel of lines so that they
91 // can then be matched against expectedOutput.
92 lineC := make(chan string)
93 outBuffer := logbuffer.NewLineBuffer(1024, func(l *logbuffer.Line) {
94 lineC <- l.Data
95 })
96 defer outBuffer.Close()
97 errBuffer := logbuffer.NewLineBuffer(1024, func(l *logbuffer.Line) {
98 lineC <- l.Data
99 })
100 defer errBuffer.Close()
101
102 // Tee std{out,err} into the linebuffers above and the process' std{out,err}, to
103 // allow easier debugging.
104 qemuCmd.Stdout = io.MultiWriter(os.Stdout, outBuffer)
105 qemuCmd.Stderr = io.MultiWriter(os.Stderr, errBuffer)
106 if err := qemuCmd.Start(); err != nil {
Mateusz Zalega43e21072021-10-08 18:05:29 +0200107 return false, fmt.Errorf("couldn't start QEMU: %w", err)
108 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200109
110 // Try matching against expectedOutput and return the result.
Serge Bazanskie2e03712021-12-17 12:47:03 +0100111 for {
112 select {
113 case <-ctx.Done():
114 return false, ctx.Err()
115 case line := <-lineC:
116 if strings.Contains(line, expectedOutput) {
117 return true, nil
118 }
119 }
120 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200121}
122
Serge Bazanskie2e03712021-12-17 12:47:03 +0100123// runQemuWithInstaller runs the Metropolis Installer in a qemu, performing the
124// same search-through-std{out,err} as runQemu.
125func runQemuWithInstaller(ctx context.Context, args []string, expectedOutput string) (bool, error) {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100126 args = append(args, "-drive", "if=virtio,format=raw,snapshot=on,cache=unsafe,file="+installerImage)
Serge Bazanskie2e03712021-12-17 12:47:03 +0100127 return runQemu(ctx, args, expectedOutput)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100128}
129
Mateusz Zalega43e21072021-10-08 18:05:29 +0200130// getStorage creates a sparse file, given a size expressed in mebibytes, and
131// returns a path to that file. It may return an error.
132func getStorage(size int64) (string, error) {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100133 image, err := os.Create(nodeStorage)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200134 if err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100135 return "", fmt.Errorf("couldn't create the block device image at %q: %w", nodeStorage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200136 }
137 if err := syscall.Ftruncate(int(image.Fd()), size*1024*1024); err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100138 return "", fmt.Errorf("couldn't resize the block device image at %q: %w", nodeStorage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200139 }
140 image.Close()
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100141 return nodeStorage, nil
Mateusz Zalega43e21072021-10-08 18:05:29 +0200142}
143
144// qemuDriveParam returns QEMU parameters required to run it with a
145// raw-format image at path.
146func qemuDriveParam(path string) []string {
147 return []string{"-drive", "if=virtio,format=raw,snapshot=off,cache=unsafe,file=" + path}
148}
149
150// checkEspContents verifies the presence of the EFI payload inside of image's
151// first partition. It returns nil on success.
152func checkEspContents(image *disk.Disk) error {
153 // Get the ESP.
154 fs, err := image.GetFilesystem(1)
155 if err != nil {
156 return fmt.Errorf("couldn't read the installer ESP: %w", err)
157 }
158 // Make sure the EFI payload exists by attempting to open it.
159 efiPayload, err := fs.OpenFile(osimage.EFIPayloadPath, os.O_RDONLY)
160 if err != nil {
161 return fmt.Errorf("couldn't open the installer's EFI Payload at %q: %w", osimage.EFIPayloadPath, err)
162 }
163 efiPayload.Close()
164 return nil
165}
166
167func TestMain(m *testing.M) {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100168 // Initialize global variables holding filesystem paths pointing to runtime
169 // dependencies and side effects.
170 paths := []struct {
171 // res is a pointer to the global variable initialized.
172 res *string
173 // dep states whether the path should be resolved as a dependency, rather
174 // than a side effect.
175 dep bool
176 // src is a source path, based on which res is resolved. In case of
177 // dependencies it must be a path relative to the repository root. For
178 // side effects, it must be just a filename.
179 src string
180 }{
Mateusz Zalega098a8632021-12-08 15:51:24 +0100181 {&installerEFIPayload, true, "metropolis/test/installer/kernel.efi"},
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100182 {&testOSBundle, true, "metropolis/test/installer/testos/testos_bundle.zip"},
183 {&installerImage, false, "installer.img"},
184 {&nodeStorage, false, "stor.img"},
185 }
186 for _, p := range paths {
187 if p.dep {
188 res, err := bazel.Runfile(p.src)
189 if err != nil {
190 log.Fatal(err)
191 }
192 *p.res = res
193 } else {
194 od := os.Getenv("TEST_TMPDIR")
195 // If od is empty, just use the working directory, which is set according
196 // to the rundir attribute of go_test.
197 *p.res = filepath.Join(od, p.src)
198 }
199 }
200
Mateusz Zalega43e21072021-10-08 18:05:29 +0200201 // Build the installer image with metroctl, given the EFI executable
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100202 // generated by Metropolis buildsystem.
203 installer, err := os.Open(installerEFIPayload)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200204 if err != nil {
Mateusz Zalega8f72b5d2021-12-03 17:08:59 +0100205 log.Fatalf("Couldn't open the installer EFI executable at %q: %v", installerEFIPayload, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200206 }
207 info, err := installer.Stat()
208 if err != nil {
Mateusz Zalega8f72b5d2021-12-03 17:08:59 +0100209 log.Fatalf("Couldn't stat the installer EFI executable: %v", err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200210 }
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100211 bundle, err := os.Open(testOSBundle)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100212 if err != nil {
Mateusz Zalega8f72b5d2021-12-03 17:08:59 +0100213 log.Fatalf("Failed to open TestOS bundle: %v", err)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100214 }
215 bundleStat, err := bundle.Stat()
216 if err != nil {
Mateusz Zalega8f72b5d2021-12-03 17:08:59 +0100217 log.Fatalf("Failed to stat() TestOS bundle: %v", err)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100218 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200219 iargs := mctl.MakeInstallerImageArgs{
220 Installer: installer,
221 InstallerSize: uint64(info.Size()),
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100222 TargetPath: installerImage,
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100223 NodeParams: &api.NodeParameters{},
224 Bundle: bundle,
225 BundleSize: uint64(bundleStat.Size()),
Mateusz Zalega43e21072021-10-08 18:05:29 +0200226 }
227 if err := mctl.MakeInstallerImage(iargs); err != nil {
Mateusz Zalega8f72b5d2021-12-03 17:08:59 +0100228 log.Fatalf("Couldn't create the installer image at %q: %v", installerImage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200229 }
230 // With common dependencies set up, run the tests.
231 code := m.Run()
232 // Clean up.
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100233 os.Remove(installerImage)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200234 os.Exit(code)
235}
236
237func TestInstallerImage(t *testing.T) {
238 // This test examines the installer image, making sure that the GPT and the
239 // ESP contents are in order.
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100240 image, err := diskfs.OpenWithMode(installerImage, diskfs.ReadOnly)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200241 if err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100242 t.Errorf("Couldn't open the installer image at %q: %s", installerImage, err.Error())
Mateusz Zalega43e21072021-10-08 18:05:29 +0200243 }
244 // Verify that GPT exists.
245 ti, err := image.GetPartitionTable()
246 if ti.Type() != "gpt" {
247 t.Error("Couldn't verify that the installer image contains a GPT.")
248 }
249 // Check that the first partition is likely to be a valid ESP.
250 pi := ti.GetPartitions()
251 esp := (pi[0]).(*gpt.Partition)
252 if esp.Start == 0 || esp.End == 0 {
253 t.Error("The installer's ESP GPT entry looks off.")
254 }
255 // Verify that the image contains only one partition.
256 second := (pi[1]).(*gpt.Partition)
257 if second.Name != "" || second.Start != 0 || second.End != 0 {
258 t.Error("It appears the installer image contains more than one partition.")
259 }
260 // Verify the ESP contents.
261 if err := checkEspContents(image); err != nil {
262 t.Error(err.Error())
263 }
264}
265
266func TestNoBlockDevices(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100267 ctx, ctxC := context.WithCancel(context.Background())
268 defer ctxC()
269
Mateusz Zalega43e21072021-10-08 18:05:29 +0200270 // No block devices are passed to QEMU aside from the install medium. Expect
271 // the installer to fail at the device probe stage rather than attempting to
272 // use the medium as the target device.
273 expectedOutput := "couldn't find a suitable block device"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100274 result, err := runQemuWithInstaller(ctx, nil, expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200275 if err != nil {
276 t.Error(err.Error())
277 }
278 if result != true {
279 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
280 }
281}
282
283func TestBlockDeviceTooSmall(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100284 ctx, ctxC := context.WithCancel(context.Background())
285 defer ctxC()
286
Mateusz Zalega43e21072021-10-08 18:05:29 +0200287 // Prepare the block device the installer will install to. This time the
288 // target device is too small to host a Metropolis installation.
289 imagePath, err := getStorage(64)
290 defer os.Remove(imagePath)
291 if err != nil {
292 t.Errorf(err.Error())
293 }
294
295 // Run QEMU. Expect the installer to fail with a predefined error string.
296 expectedOutput := "couldn't find a suitable block device"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100297 result, err := runQemuWithInstaller(ctx, qemuDriveParam(imagePath), expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200298 if err != nil {
299 t.Error(err.Error())
300 }
301 if result != true {
302 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
303 }
304}
305
306func TestInstall(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100307 ctx, ctxC := context.WithCancel(context.Background())
308 defer ctxC()
309
Mateusz Zalega43e21072021-10-08 18:05:29 +0200310 // Prepare the block device image the installer will install to.
311 storagePath, err := getStorage(4096 + 128 + 128 + 1)
312 defer os.Remove(storagePath)
313 if err != nil {
314 t.Errorf(err.Error())
315 }
316
317 // Run QEMU. Expect the installer to succeed.
318 expectedOutput := "Installation completed"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100319 result, err := runQemuWithInstaller(ctx, qemuDriveParam(storagePath), expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200320 if err != nil {
321 t.Error(err.Error())
322 }
323 if result != true {
324 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
325 }
326
327 // Verify the resulting node image. Check whether the node GPT was created.
328 storage, err := diskfs.OpenWithMode(storagePath, diskfs.ReadOnly)
329 if err != nil {
330 t.Errorf("Couldn't open the resulting node image at %q: %s", storagePath, err.Error())
331 }
332 // Verify that GPT exists.
333 ti, err := storage.GetPartitionTable()
334 if ti.Type() != "gpt" {
335 t.Error("Couldn't verify that the resulting node image contains a GPT.")
336 }
337 // Check that the first partition is likely to be a valid ESP.
338 pi := ti.GetPartitions()
339 esp := (pi[0]).(*gpt.Partition)
340 if esp.Name != osimage.ESPVolumeLabel || esp.Start == 0 || esp.End == 0 {
341 t.Error("The node's ESP GPT entry looks off.")
342 }
343 // Verify the system partition's GPT entry.
344 system := (pi[1]).(*gpt.Partition)
345 if system.Name != osimage.SystemVolumeLabel || system.Start == 0 || system.End == 0 {
346 t.Error("The node's system partition GPT entry looks off.")
347 }
348 // Verify the data partition's GPT entry.
349 data := (pi[2]).(*gpt.Partition)
350 if data.Name != osimage.DataVolumeLabel || data.Start == 0 || data.End == 0 {
351 t.Errorf("The node's data partition GPT entry looks off.")
352 }
353 // Verify that there are no more partitions.
354 fourth := (pi[3]).(*gpt.Partition)
355 if fourth.Name != "" || fourth.Start != 0 || fourth.End != 0 {
356 t.Error("The resulting node image contains more partitions than expected.")
357 }
358 // Verify the ESP contents.
359 if err := checkEspContents(storage); err != nil {
360 t.Error(err.Error())
361 }
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100362 // Run QEMU again. Expect TestOS to launch successfully.
363 expectedOutput = "_TESTOS_LAUNCH_SUCCESS_"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100364 result, err = runQemu(ctx, qemuDriveParam(storagePath), expectedOutput)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100365 if err != nil {
366 t.Error(err.Error())
367 }
368 if result != true {
369 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
370 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200371}