blob: 0a5e5aaaa7b8133c7dd7cd99c364c7f5083d0cc6 [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
34 diskfs "github.com/diskfs/go-diskfs"
35 "github.com/diskfs/go-diskfs/disk"
36 "github.com/diskfs/go-diskfs/partition/gpt"
Lorenz Brun0b93c8d2021-11-09 03:58:40 +010037
Mateusz Zalega43e21072021-10-08 18:05:29 +020038 mctl "source.monogon.dev/metropolis/cli/metroctl/core"
Serge Bazanski97783222021-12-14 16:04:26 +010039 "source.monogon.dev/metropolis/cli/pkg/datafile"
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 (
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010048 // installerImage is a filesystem path pointing at the installer image that
49 // is generated during the test, and is removed afterwards.
50 installerImage string
51 // nodeStorage is a filesystem path pointing at the VM block device image
52 // Metropolis is installed to during the test. The file is removed afterwards.
53 nodeStorage string
Mateusz Zalega43e21072021-10-08 18:05:29 +020054)
55
Serge Bazanskie2e03712021-12-17 12:47:03 +010056// runQemu starts a QEMU process and waits until it either finishes or the given
57// expectedOutput appears in a line emitted to stdout or stderr. It returns true
58// if it was found, false otherwise.
59//
60// The qemu process will be killed when the context cancels or the function
61// exits.
62func runQemu(ctx context.Context, args []string, expectedOutput string) (bool, error) {
Mateusz Zalega43e21072021-10-08 18:05:29 +020063 // Prepare the default parameter list.
64 defaultArgs := []string{
65 "-machine", "q35", "-accel", "kvm", "-nographic", "-nodefaults",
66 "-m", "512",
67 "-smp", "2",
68 "-cpu", "host",
69 "-drive", "if=pflash,format=raw,readonly,file=external/edk2/OVMF_CODE.fd",
70 "-drive", "if=pflash,format=raw,snapshot=on,file=external/edk2/OVMF_VARS.fd",
Mateusz Zalega43e21072021-10-08 18:05:29 +020071 "-serial", "stdio",
72 "-no-reboot",
73 }
Serge Bazanskie2e03712021-12-17 12:47:03 +010074
75 // Make a sub-context to ensure that qemu exits when this function is done.
76 ctxQ, ctxC := context.WithCancel(ctx)
77 defer ctxC()
78
Mateusz Zalega43e21072021-10-08 18:05:29 +020079 // Join the parameter lists and prepare the Qemu command, but don't run it
80 // just yet.
81 qemuArgs := append(defaultArgs, args...)
Serge Bazanskie2e03712021-12-17 12:47:03 +010082 qemuCmd := exec.CommandContext(ctxQ, "external/qemu/qemu-x86_64-softmmu", qemuArgs...)
Mateusz Zalega43e21072021-10-08 18:05:29 +020083
Serge Bazanskie2e03712021-12-17 12:47:03 +010084 // Copy the stdout and stderr output to a single channel of lines so that they
85 // can then be matched against expectedOutput.
86 lineC := make(chan string)
87 outBuffer := logbuffer.NewLineBuffer(1024, func(l *logbuffer.Line) {
88 lineC <- l.Data
89 })
90 defer outBuffer.Close()
91 errBuffer := logbuffer.NewLineBuffer(1024, func(l *logbuffer.Line) {
92 lineC <- l.Data
93 })
94 defer errBuffer.Close()
95
96 // Tee std{out,err} into the linebuffers above and the process' std{out,err}, to
97 // allow easier debugging.
98 qemuCmd.Stdout = io.MultiWriter(os.Stdout, outBuffer)
99 qemuCmd.Stderr = io.MultiWriter(os.Stderr, errBuffer)
100 if err := qemuCmd.Start(); err != nil {
Mateusz Zalega43e21072021-10-08 18:05:29 +0200101 return false, fmt.Errorf("couldn't start QEMU: %w", err)
102 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200103
104 // Try matching against expectedOutput and return the result.
Serge Bazanskie2e03712021-12-17 12:47:03 +0100105 for {
106 select {
107 case <-ctx.Done():
108 return false, ctx.Err()
109 case line := <-lineC:
110 if strings.Contains(line, expectedOutput) {
111 return true, nil
112 }
113 }
114 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200115}
116
Serge Bazanskie2e03712021-12-17 12:47:03 +0100117// runQemuWithInstaller runs the Metropolis Installer in a qemu, performing the
118// same search-through-std{out,err} as runQemu.
119func runQemuWithInstaller(ctx context.Context, args []string, expectedOutput string) (bool, error) {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100120 args = append(args, "-drive", "if=virtio,format=raw,snapshot=on,cache=unsafe,file="+installerImage)
Serge Bazanskie2e03712021-12-17 12:47:03 +0100121 return runQemu(ctx, args, expectedOutput)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100122}
123
Mateusz Zalega43e21072021-10-08 18:05:29 +0200124// getStorage creates a sparse file, given a size expressed in mebibytes, and
125// returns a path to that file. It may return an error.
126func getStorage(size int64) (string, error) {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100127 image, err := os.Create(nodeStorage)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200128 if err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100129 return "", fmt.Errorf("couldn't create the block device image at %q: %w", nodeStorage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200130 }
131 if err := syscall.Ftruncate(int(image.Fd()), size*1024*1024); err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100132 return "", fmt.Errorf("couldn't resize the block device image at %q: %w", nodeStorage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200133 }
134 image.Close()
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100135 return nodeStorage, nil
Mateusz Zalega43e21072021-10-08 18:05:29 +0200136}
137
138// qemuDriveParam returns QEMU parameters required to run it with a
139// raw-format image at path.
140func qemuDriveParam(path string) []string {
141 return []string{"-drive", "if=virtio,format=raw,snapshot=off,cache=unsafe,file=" + path}
142}
143
144// checkEspContents verifies the presence of the EFI payload inside of image's
145// first partition. It returns nil on success.
146func checkEspContents(image *disk.Disk) error {
147 // Get the ESP.
148 fs, err := image.GetFilesystem(1)
149 if err != nil {
150 return fmt.Errorf("couldn't read the installer ESP: %w", err)
151 }
152 // Make sure the EFI payload exists by attempting to open it.
153 efiPayload, err := fs.OpenFile(osimage.EFIPayloadPath, os.O_RDONLY)
154 if err != nil {
155 return fmt.Errorf("couldn't open the installer's EFI Payload at %q: %w", osimage.EFIPayloadPath, err)
156 }
157 efiPayload.Close()
158 return nil
159}
160
161func TestMain(m *testing.M) {
Serge Bazanski97783222021-12-14 16:04:26 +0100162 installerImage = filepath.Join(os.Getenv("TEST_TMPDIR"), "installer.img")
163 nodeStorage = filepath.Join(os.Getenv("TEST_TMPDIR"), "stor.img")
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100164
Serge Bazanski97783222021-12-14 16:04:26 +0100165 installer := datafile.MustGet("metropolis/test/installer/kernel.efi")
166 bundle := datafile.MustGet("metropolis/test/installer/testos/testos_bundle.zip")
Mateusz Zalega43e21072021-10-08 18:05:29 +0200167 iargs := mctl.MakeInstallerImageArgs{
Serge Bazanski97783222021-12-14 16:04:26 +0100168 Installer: bytes.NewBuffer(installer),
169 InstallerSize: uint64(len(installer)),
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100170 TargetPath: installerImage,
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100171 NodeParams: &api.NodeParameters{},
Serge Bazanski97783222021-12-14 16:04:26 +0100172 Bundle: bytes.NewBuffer(bundle),
173 BundleSize: uint64(len(bundle)),
Mateusz Zalega43e21072021-10-08 18:05:29 +0200174 }
175 if err := mctl.MakeInstallerImage(iargs); err != nil {
Mateusz Zalega8f72b5d2021-12-03 17:08:59 +0100176 log.Fatalf("Couldn't create the installer image at %q: %v", installerImage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200177 }
178 // With common dependencies set up, run the tests.
179 code := m.Run()
180 // Clean up.
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100181 os.Remove(installerImage)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200182 os.Exit(code)
183}
184
185func TestInstallerImage(t *testing.T) {
186 // This test examines the installer image, making sure that the GPT and the
187 // ESP contents are in order.
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100188 image, err := diskfs.OpenWithMode(installerImage, diskfs.ReadOnly)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200189 if err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100190 t.Errorf("Couldn't open the installer image at %q: %s", installerImage, err.Error())
Mateusz Zalega43e21072021-10-08 18:05:29 +0200191 }
192 // Verify that GPT exists.
193 ti, err := image.GetPartitionTable()
194 if ti.Type() != "gpt" {
195 t.Error("Couldn't verify that the installer image contains a GPT.")
196 }
197 // Check that the first partition is likely to be a valid ESP.
198 pi := ti.GetPartitions()
199 esp := (pi[0]).(*gpt.Partition)
200 if esp.Start == 0 || esp.End == 0 {
201 t.Error("The installer's ESP GPT entry looks off.")
202 }
203 // Verify that the image contains only one partition.
204 second := (pi[1]).(*gpt.Partition)
205 if second.Name != "" || second.Start != 0 || second.End != 0 {
206 t.Error("It appears the installer image contains more than one partition.")
207 }
208 // Verify the ESP contents.
209 if err := checkEspContents(image); err != nil {
210 t.Error(err.Error())
211 }
212}
213
214func TestNoBlockDevices(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100215 ctx, ctxC := context.WithCancel(context.Background())
216 defer ctxC()
217
Mateusz Zalega43e21072021-10-08 18:05:29 +0200218 // No block devices are passed to QEMU aside from the install medium. Expect
219 // the installer to fail at the device probe stage rather than attempting to
220 // use the medium as the target device.
221 expectedOutput := "couldn't find a suitable block device"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100222 result, err := runQemuWithInstaller(ctx, nil, expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200223 if err != nil {
224 t.Error(err.Error())
225 }
226 if result != true {
227 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
228 }
229}
230
231func TestBlockDeviceTooSmall(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100232 ctx, ctxC := context.WithCancel(context.Background())
233 defer ctxC()
234
Mateusz Zalega43e21072021-10-08 18:05:29 +0200235 // Prepare the block device the installer will install to. This time the
236 // target device is too small to host a Metropolis installation.
237 imagePath, err := getStorage(64)
238 defer os.Remove(imagePath)
239 if err != nil {
240 t.Errorf(err.Error())
241 }
242
243 // Run QEMU. Expect the installer to fail with a predefined error string.
244 expectedOutput := "couldn't find a suitable block device"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100245 result, err := runQemuWithInstaller(ctx, qemuDriveParam(imagePath), expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200246 if err != nil {
247 t.Error(err.Error())
248 }
249 if result != true {
250 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
251 }
252}
253
254func TestInstall(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100255 ctx, ctxC := context.WithCancel(context.Background())
256 defer ctxC()
257
Mateusz Zalega43e21072021-10-08 18:05:29 +0200258 // Prepare the block device image the installer will install to.
259 storagePath, err := getStorage(4096 + 128 + 128 + 1)
260 defer os.Remove(storagePath)
261 if err != nil {
262 t.Errorf(err.Error())
263 }
264
265 // Run QEMU. Expect the installer to succeed.
266 expectedOutput := "Installation completed"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100267 result, err := runQemuWithInstaller(ctx, qemuDriveParam(storagePath), expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200268 if err != nil {
269 t.Error(err.Error())
270 }
271 if result != true {
272 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
273 }
274
275 // Verify the resulting node image. Check whether the node GPT was created.
276 storage, err := diskfs.OpenWithMode(storagePath, diskfs.ReadOnly)
277 if err != nil {
278 t.Errorf("Couldn't open the resulting node image at %q: %s", storagePath, err.Error())
279 }
280 // Verify that GPT exists.
281 ti, err := storage.GetPartitionTable()
282 if ti.Type() != "gpt" {
283 t.Error("Couldn't verify that the resulting node image contains a GPT.")
284 }
285 // Check that the first partition is likely to be a valid ESP.
286 pi := ti.GetPartitions()
287 esp := (pi[0]).(*gpt.Partition)
288 if esp.Name != osimage.ESPVolumeLabel || esp.Start == 0 || esp.End == 0 {
289 t.Error("The node's ESP GPT entry looks off.")
290 }
291 // Verify the system partition's GPT entry.
292 system := (pi[1]).(*gpt.Partition)
293 if system.Name != osimage.SystemVolumeLabel || system.Start == 0 || system.End == 0 {
294 t.Error("The node's system partition GPT entry looks off.")
295 }
296 // Verify the data partition's GPT entry.
297 data := (pi[2]).(*gpt.Partition)
298 if data.Name != osimage.DataVolumeLabel || data.Start == 0 || data.End == 0 {
299 t.Errorf("The node's data partition GPT entry looks off.")
300 }
301 // Verify that there are no more partitions.
302 fourth := (pi[3]).(*gpt.Partition)
303 if fourth.Name != "" || fourth.Start != 0 || fourth.End != 0 {
304 t.Error("The resulting node image contains more partitions than expected.")
305 }
306 // Verify the ESP contents.
307 if err := checkEspContents(storage); err != nil {
308 t.Error(err.Error())
309 }
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100310 // Run QEMU again. Expect TestOS to launch successfully.
311 expectedOutput = "_TESTOS_LAUNCH_SUCCESS_"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100312 result, err = runQemu(ctx, qemuDriveParam(storagePath), expectedOutput)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100313 if err != nil {
314 t.Error(err.Error())
315 }
316 if result != true {
317 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
318 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200319}