blob: dafa28838dc3c695964284afa9d65097144389c4 [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 (
Mateusz Zalega367f7592021-12-20 18:13:31 +010023 "bytes"
Serge Bazanskie2e03712021-12-17 12:47:03 +010024 "context"
Mateusz Zalega43e21072021-10-08 18:05:29 +020025 "fmt"
26 "io"
27 "log"
28 "os"
29 "os/exec"
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010030 "path/filepath"
Serge Bazanskie2e03712021-12-17 12:47:03 +010031 "strings"
Mateusz Zalega43e21072021-10-08 18:05:29 +020032 "syscall"
33 "testing"
34
35 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"
Serge Bazanski97783222021-12-14 16:04:26 +010040 "source.monogon.dev/metropolis/cli/pkg/datafile"
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010041 "source.monogon.dev/metropolis/node/build/mkimage/osimage"
Serge Bazanskie2e03712021-12-17 12:47:03 +010042 "source.monogon.dev/metropolis/pkg/logbuffer"
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010043 "source.monogon.dev/metropolis/proto/api"
Mateusz Zalega43e21072021-10-08 18:05:29 +020044)
45
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010046// Each variable in this block points to either a test dependency or a side
47// effect. These variables are initialized in TestMain using Bazel.
48var (
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010049 // installerImage is a filesystem path pointing at the installer image that
50 // is generated during the test, and is removed afterwards.
51 installerImage string
52 // nodeStorage is a filesystem path pointing at the VM block device image
53 // Metropolis is installed to during the test. The file is removed afterwards.
54 nodeStorage string
Mateusz Zalega43e21072021-10-08 18:05:29 +020055)
56
Serge Bazanskie2e03712021-12-17 12:47:03 +010057// runQemu starts a QEMU process and waits until it either finishes or the given
58// expectedOutput appears in a line emitted to stdout or stderr. It returns true
59// if it was found, false otherwise.
60//
61// The qemu process will be killed when the context cancels or the function
62// exits.
63func runQemu(ctx context.Context, args []string, expectedOutput string) (bool, error) {
Mateusz Zalega43e21072021-10-08 18:05:29 +020064 // Prepare the default parameter list.
65 defaultArgs := []string{
66 "-machine", "q35", "-accel", "kvm", "-nographic", "-nodefaults",
67 "-m", "512",
68 "-smp", "2",
69 "-cpu", "host",
70 "-drive", "if=pflash,format=raw,readonly,file=external/edk2/OVMF_CODE.fd",
71 "-drive", "if=pflash,format=raw,snapshot=on,file=external/edk2/OVMF_VARS.fd",
Mateusz Zalega43e21072021-10-08 18:05:29 +020072 "-serial", "stdio",
73 "-no-reboot",
74 }
Serge Bazanskie2e03712021-12-17 12:47:03 +010075
76 // Make a sub-context to ensure that qemu exits when this function is done.
77 ctxQ, ctxC := context.WithCancel(ctx)
78 defer ctxC()
79
Mateusz Zalega43e21072021-10-08 18:05:29 +020080 // Join the parameter lists and prepare the Qemu command, but don't run it
81 // just yet.
82 qemuArgs := append(defaultArgs, args...)
Serge Bazanskie2e03712021-12-17 12:47:03 +010083 qemuCmd := exec.CommandContext(ctxQ, "external/qemu/qemu-x86_64-softmmu", qemuArgs...)
Mateusz Zalega43e21072021-10-08 18:05:29 +020084
Serge Bazanskie2e03712021-12-17 12:47:03 +010085 // Copy the stdout and stderr output to a single channel of lines so that they
86 // can then be matched against expectedOutput.
87 lineC := make(chan string)
88 outBuffer := logbuffer.NewLineBuffer(1024, func(l *logbuffer.Line) {
89 lineC <- l.Data
90 })
91 defer outBuffer.Close()
92 errBuffer := logbuffer.NewLineBuffer(1024, func(l *logbuffer.Line) {
93 lineC <- l.Data
94 })
95 defer errBuffer.Close()
96
97 // Tee std{out,err} into the linebuffers above and the process' std{out,err}, to
98 // allow easier debugging.
99 qemuCmd.Stdout = io.MultiWriter(os.Stdout, outBuffer)
100 qemuCmd.Stderr = io.MultiWriter(os.Stderr, errBuffer)
101 if err := qemuCmd.Start(); err != nil {
Mateusz Zalega43e21072021-10-08 18:05:29 +0200102 return false, fmt.Errorf("couldn't start QEMU: %w", err)
103 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200104
105 // Try matching against expectedOutput and return the result.
Serge Bazanskie2e03712021-12-17 12:47:03 +0100106 for {
107 select {
108 case <-ctx.Done():
109 return false, ctx.Err()
110 case line := <-lineC:
111 if strings.Contains(line, expectedOutput) {
112 return true, nil
113 }
114 }
115 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200116}
117
Serge Bazanskie2e03712021-12-17 12:47:03 +0100118// runQemuWithInstaller runs the Metropolis Installer in a qemu, performing the
119// same search-through-std{out,err} as runQemu.
120func runQemuWithInstaller(ctx context.Context, args []string, expectedOutput string) (bool, error) {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100121 args = append(args, "-drive", "if=virtio,format=raw,snapshot=on,cache=unsafe,file="+installerImage)
Serge Bazanskie2e03712021-12-17 12:47:03 +0100122 return runQemu(ctx, args, expectedOutput)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100123}
124
Mateusz Zalega43e21072021-10-08 18:05:29 +0200125// getStorage creates a sparse file, given a size expressed in mebibytes, and
126// returns a path to that file. It may return an error.
127func getStorage(size int64) (string, error) {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100128 image, err := os.Create(nodeStorage)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200129 if err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100130 return "", fmt.Errorf("couldn't create the block device image at %q: %w", nodeStorage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200131 }
132 if err := syscall.Ftruncate(int(image.Fd()), size*1024*1024); err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100133 return "", fmt.Errorf("couldn't resize the block device image at %q: %w", nodeStorage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200134 }
135 image.Close()
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100136 return nodeStorage, nil
Mateusz Zalega43e21072021-10-08 18:05:29 +0200137}
138
139// qemuDriveParam returns QEMU parameters required to run it with a
140// raw-format image at path.
141func qemuDriveParam(path string) []string {
142 return []string{"-drive", "if=virtio,format=raw,snapshot=off,cache=unsafe,file=" + path}
143}
144
145// checkEspContents verifies the presence of the EFI payload inside of image's
146// first partition. It returns nil on success.
147func checkEspContents(image *disk.Disk) error {
148 // Get the ESP.
149 fs, err := image.GetFilesystem(1)
150 if err != nil {
151 return fmt.Errorf("couldn't read the installer ESP: %w", err)
152 }
153 // Make sure the EFI payload exists by attempting to open it.
154 efiPayload, err := fs.OpenFile(osimage.EFIPayloadPath, os.O_RDONLY)
155 if err != nil {
156 return fmt.Errorf("couldn't open the installer's EFI Payload at %q: %w", osimage.EFIPayloadPath, err)
157 }
158 efiPayload.Close()
159 return nil
160}
161
162func TestMain(m *testing.M) {
Serge Bazanski97783222021-12-14 16:04:26 +0100163 installerImage = filepath.Join(os.Getenv("TEST_TMPDIR"), "installer.img")
164 nodeStorage = filepath.Join(os.Getenv("TEST_TMPDIR"), "stor.img")
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100165
Serge Bazanski97783222021-12-14 16:04:26 +0100166 installer := datafile.MustGet("metropolis/test/installer/kernel.efi")
167 bundle := datafile.MustGet("metropolis/test/installer/testos/testos_bundle.zip")
Mateusz Zalega43e21072021-10-08 18:05:29 +0200168 iargs := mctl.MakeInstallerImageArgs{
Serge Bazanski97783222021-12-14 16:04:26 +0100169 Installer: bytes.NewBuffer(installer),
170 InstallerSize: uint64(len(installer)),
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100171 TargetPath: installerImage,
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100172 NodeParams: &api.NodeParameters{},
Serge Bazanski97783222021-12-14 16:04:26 +0100173 Bundle: bytes.NewBuffer(bundle),
174 BundleSize: uint64(len(bundle)),
Mateusz Zalega43e21072021-10-08 18:05:29 +0200175 }
176 if err := mctl.MakeInstallerImage(iargs); err != nil {
Mateusz Zalega8f72b5d2021-12-03 17:08:59 +0100177 log.Fatalf("Couldn't create the installer image at %q: %v", installerImage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200178 }
179 // With common dependencies set up, run the tests.
180 code := m.Run()
181 // Clean up.
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100182 os.Remove(installerImage)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200183 os.Exit(code)
184}
185
186func TestInstallerImage(t *testing.T) {
187 // This test examines the installer image, making sure that the GPT and the
188 // ESP contents are in order.
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100189 image, err := diskfs.OpenWithMode(installerImage, diskfs.ReadOnly)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200190 if err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100191 t.Errorf("Couldn't open the installer image at %q: %s", installerImage, err.Error())
Mateusz Zalega43e21072021-10-08 18:05:29 +0200192 }
193 // Verify that GPT exists.
194 ti, err := image.GetPartitionTable()
195 if ti.Type() != "gpt" {
196 t.Error("Couldn't verify that the installer image contains a GPT.")
197 }
198 // Check that the first partition is likely to be a valid ESP.
199 pi := ti.GetPartitions()
200 esp := (pi[0]).(*gpt.Partition)
201 if esp.Start == 0 || esp.End == 0 {
202 t.Error("The installer's ESP GPT entry looks off.")
203 }
204 // Verify that the image contains only one partition.
205 second := (pi[1]).(*gpt.Partition)
206 if second.Name != "" || second.Start != 0 || second.End != 0 {
207 t.Error("It appears the installer image contains more than one partition.")
208 }
209 // Verify the ESP contents.
210 if err := checkEspContents(image); err != nil {
211 t.Error(err.Error())
212 }
213}
214
215func TestNoBlockDevices(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100216 ctx, ctxC := context.WithCancel(context.Background())
217 defer ctxC()
218
Mateusz Zalega43e21072021-10-08 18:05:29 +0200219 // No block devices are passed to QEMU aside from the install medium. Expect
220 // the installer to fail at the device probe stage rather than attempting to
221 // use the medium as the target device.
222 expectedOutput := "couldn't find a suitable block device"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100223 result, err := runQemuWithInstaller(ctx, nil, expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200224 if err != nil {
225 t.Error(err.Error())
226 }
227 if result != true {
228 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
229 }
230}
231
232func TestBlockDeviceTooSmall(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100233 ctx, ctxC := context.WithCancel(context.Background())
234 defer ctxC()
235
Mateusz Zalega43e21072021-10-08 18:05:29 +0200236 // Prepare the block device the installer will install to. This time the
237 // target device is too small to host a Metropolis installation.
238 imagePath, err := getStorage(64)
239 defer os.Remove(imagePath)
240 if err != nil {
241 t.Errorf(err.Error())
242 }
243
244 // Run QEMU. Expect the installer to fail with a predefined error string.
245 expectedOutput := "couldn't find a suitable block device"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100246 result, err := runQemuWithInstaller(ctx, qemuDriveParam(imagePath), expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200247 if err != nil {
248 t.Error(err.Error())
249 }
250 if result != true {
251 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
252 }
253}
254
255func TestInstall(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100256 ctx, ctxC := context.WithCancel(context.Background())
257 defer ctxC()
258
Mateusz Zalega43e21072021-10-08 18:05:29 +0200259 // Prepare the block device image the installer will install to.
260 storagePath, err := getStorage(4096 + 128 + 128 + 1)
261 defer os.Remove(storagePath)
262 if err != nil {
263 t.Errorf(err.Error())
264 }
265
266 // Run QEMU. Expect the installer to succeed.
267 expectedOutput := "Installation completed"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100268 result, err := runQemuWithInstaller(ctx, qemuDriveParam(storagePath), expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200269 if err != nil {
270 t.Error(err.Error())
271 }
272 if result != true {
273 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
274 }
275
276 // Verify the resulting node image. Check whether the node GPT was created.
277 storage, err := diskfs.OpenWithMode(storagePath, diskfs.ReadOnly)
278 if err != nil {
279 t.Errorf("Couldn't open the resulting node image at %q: %s", storagePath, err.Error())
280 }
281 // Verify that GPT exists.
282 ti, err := storage.GetPartitionTable()
283 if ti.Type() != "gpt" {
284 t.Error("Couldn't verify that the resulting node image contains a GPT.")
285 }
286 // Check that the first partition is likely to be a valid ESP.
287 pi := ti.GetPartitions()
288 esp := (pi[0]).(*gpt.Partition)
289 if esp.Name != osimage.ESPVolumeLabel || esp.Start == 0 || esp.End == 0 {
290 t.Error("The node's ESP GPT entry looks off.")
291 }
292 // Verify the system partition's GPT entry.
293 system := (pi[1]).(*gpt.Partition)
294 if system.Name != osimage.SystemVolumeLabel || system.Start == 0 || system.End == 0 {
295 t.Error("The node's system partition GPT entry looks off.")
296 }
297 // Verify the data partition's GPT entry.
298 data := (pi[2]).(*gpt.Partition)
299 if data.Name != osimage.DataVolumeLabel || data.Start == 0 || data.End == 0 {
300 t.Errorf("The node's data partition GPT entry looks off.")
301 }
302 // Verify that there are no more partitions.
303 fourth := (pi[3]).(*gpt.Partition)
304 if fourth.Name != "" || fourth.Start != 0 || fourth.End != 0 {
305 t.Error("The resulting node image contains more partitions than expected.")
306 }
307 // Verify the ESP contents.
308 if err := checkEspContents(storage); err != nil {
309 t.Error(err.Error())
310 }
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100311 // Run QEMU again. Expect TestOS to launch successfully.
312 expectedOutput = "_TESTOS_LAUNCH_SUCCESS_"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100313 result, err = runQemu(ctx, qemuDriveParam(storagePath), expectedOutput)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100314 if err != nil {
315 t.Error(err.Error())
316 }
317 if result != true {
318 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
319 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200320}