blob: c4faf818ea8499135fe82497ccbc14efdbc70e9b [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.
Mateusz Zalegaedffbb52022-01-11 15:27:22 +010020package installer
Mateusz Zalega43e21072021-10-08 18:05:29 +020021
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.
Mateusz Zalegacdcc7392021-12-08 15:34:53 +010087
88 // Since LineBuffer can write its buffered contents on a deferred Close,
89 // after the reader loop is broken, avoid deadlocks by making lineC a
90 // buffered channel.
91 lineC := make(chan string, 2)
Serge Bazanskie2e03712021-12-17 12:47:03 +010092 outBuffer := logbuffer.NewLineBuffer(1024, func(l *logbuffer.Line) {
93 lineC <- l.Data
94 })
95 defer outBuffer.Close()
96 errBuffer := logbuffer.NewLineBuffer(1024, func(l *logbuffer.Line) {
97 lineC <- l.Data
98 })
99 defer errBuffer.Close()
100
101 // Tee std{out,err} into the linebuffers above and the process' std{out,err}, to
102 // allow easier debugging.
103 qemuCmd.Stdout = io.MultiWriter(os.Stdout, outBuffer)
104 qemuCmd.Stderr = io.MultiWriter(os.Stderr, errBuffer)
105 if err := qemuCmd.Start(); err != nil {
Mateusz Zalega43e21072021-10-08 18:05:29 +0200106 return false, fmt.Errorf("couldn't start QEMU: %w", err)
107 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200108
109 // Try matching against expectedOutput and return the result.
Serge Bazanskie2e03712021-12-17 12:47:03 +0100110 for {
111 select {
112 case <-ctx.Done():
113 return false, ctx.Err()
114 case line := <-lineC:
115 if strings.Contains(line, expectedOutput) {
116 return true, nil
117 }
118 }
119 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200120}
121
Serge Bazanskie2e03712021-12-17 12:47:03 +0100122// runQemuWithInstaller runs the Metropolis Installer in a qemu, performing the
123// same search-through-std{out,err} as runQemu.
124func runQemuWithInstaller(ctx context.Context, args []string, expectedOutput string) (bool, error) {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100125 args = append(args, "-drive", "if=virtio,format=raw,snapshot=on,cache=unsafe,file="+installerImage)
Serge Bazanskie2e03712021-12-17 12:47:03 +0100126 return runQemu(ctx, args, expectedOutput)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100127}
128
Mateusz Zalega43e21072021-10-08 18:05:29 +0200129// getStorage creates a sparse file, given a size expressed in mebibytes, and
130// returns a path to that file. It may return an error.
131func getStorage(size int64) (string, error) {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100132 image, err := os.Create(nodeStorage)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200133 if err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100134 return "", fmt.Errorf("couldn't create the block device image at %q: %w", nodeStorage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200135 }
136 if err := syscall.Ftruncate(int(image.Fd()), size*1024*1024); err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100137 return "", fmt.Errorf("couldn't resize the block device image at %q: %w", nodeStorage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200138 }
139 image.Close()
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100140 return nodeStorage, nil
Mateusz Zalega43e21072021-10-08 18:05:29 +0200141}
142
143// qemuDriveParam returns QEMU parameters required to run it with a
144// raw-format image at path.
145func qemuDriveParam(path string) []string {
146 return []string{"-drive", "if=virtio,format=raw,snapshot=off,cache=unsafe,file=" + path}
147}
148
149// checkEspContents verifies the presence of the EFI payload inside of image's
150// first partition. It returns nil on success.
151func checkEspContents(image *disk.Disk) error {
152 // Get the ESP.
153 fs, err := image.GetFilesystem(1)
154 if err != nil {
155 return fmt.Errorf("couldn't read the installer ESP: %w", err)
156 }
157 // Make sure the EFI payload exists by attempting to open it.
158 efiPayload, err := fs.OpenFile(osimage.EFIPayloadPath, os.O_RDONLY)
159 if err != nil {
160 return fmt.Errorf("couldn't open the installer's EFI Payload at %q: %w", osimage.EFIPayloadPath, err)
161 }
162 efiPayload.Close()
163 return nil
164}
165
166func TestMain(m *testing.M) {
Serge Bazanski97783222021-12-14 16:04:26 +0100167 installerImage = filepath.Join(os.Getenv("TEST_TMPDIR"), "installer.img")
168 nodeStorage = filepath.Join(os.Getenv("TEST_TMPDIR"), "stor.img")
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100169
Mateusz Zalegaedffbb52022-01-11 15:27:22 +0100170 installer := datafile.MustGet("metropolis/installer/test/kernel.efi")
171 bundle := datafile.MustGet("metropolis/installer/test/testos/testos_bundle.zip")
Mateusz Zalega43e21072021-10-08 18:05:29 +0200172 iargs := mctl.MakeInstallerImageArgs{
Serge Bazanski97783222021-12-14 16:04:26 +0100173 Installer: bytes.NewBuffer(installer),
174 InstallerSize: uint64(len(installer)),
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100175 TargetPath: installerImage,
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100176 NodeParams: &api.NodeParameters{},
Serge Bazanski97783222021-12-14 16:04:26 +0100177 Bundle: bytes.NewBuffer(bundle),
178 BundleSize: uint64(len(bundle)),
Mateusz Zalega43e21072021-10-08 18:05:29 +0200179 }
180 if err := mctl.MakeInstallerImage(iargs); err != nil {
Mateusz Zalega8f72b5d2021-12-03 17:08:59 +0100181 log.Fatalf("Couldn't create the installer image at %q: %v", installerImage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200182 }
183 // With common dependencies set up, run the tests.
184 code := m.Run()
185 // Clean up.
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100186 os.Remove(installerImage)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200187 os.Exit(code)
188}
189
190func TestInstallerImage(t *testing.T) {
191 // This test examines the installer image, making sure that the GPT and the
192 // ESP contents are in order.
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100193 image, err := diskfs.OpenWithMode(installerImage, diskfs.ReadOnly)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200194 if err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100195 t.Errorf("Couldn't open the installer image at %q: %s", installerImage, err.Error())
Mateusz Zalega43e21072021-10-08 18:05:29 +0200196 }
197 // Verify that GPT exists.
198 ti, err := image.GetPartitionTable()
199 if ti.Type() != "gpt" {
200 t.Error("Couldn't verify that the installer image contains a GPT.")
201 }
202 // Check that the first partition is likely to be a valid ESP.
203 pi := ti.GetPartitions()
204 esp := (pi[0]).(*gpt.Partition)
205 if esp.Start == 0 || esp.End == 0 {
206 t.Error("The installer's ESP GPT entry looks off.")
207 }
208 // Verify that the image contains only one partition.
209 second := (pi[1]).(*gpt.Partition)
210 if second.Name != "" || second.Start != 0 || second.End != 0 {
211 t.Error("It appears the installer image contains more than one partition.")
212 }
213 // Verify the ESP contents.
214 if err := checkEspContents(image); err != nil {
215 t.Error(err.Error())
216 }
217}
218
219func TestNoBlockDevices(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100220 ctx, ctxC := context.WithCancel(context.Background())
221 defer ctxC()
222
Mateusz Zalega43e21072021-10-08 18:05:29 +0200223 // No block devices are passed to QEMU aside from the install medium. Expect
224 // the installer to fail at the device probe stage rather than attempting to
225 // use the medium as the target device.
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100226 expectedOutput := "Couldn't find a suitable block device"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100227 result, err := runQemuWithInstaller(ctx, nil, expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200228 if err != nil {
229 t.Error(err.Error())
230 }
231 if result != true {
232 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
233 }
234}
235
236func TestBlockDeviceTooSmall(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100237 ctx, ctxC := context.WithCancel(context.Background())
238 defer ctxC()
239
Mateusz Zalega43e21072021-10-08 18:05:29 +0200240 // Prepare the block device the installer will install to. This time the
241 // target device is too small to host a Metropolis installation.
242 imagePath, err := getStorage(64)
243 defer os.Remove(imagePath)
244 if err != nil {
245 t.Errorf(err.Error())
246 }
247
248 // Run QEMU. Expect the installer to fail with a predefined error string.
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100249 expectedOutput := "Couldn't find a suitable block device"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100250 result, err := runQemuWithInstaller(ctx, qemuDriveParam(imagePath), expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200251 if err != nil {
252 t.Error(err.Error())
253 }
254 if result != true {
255 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
256 }
257}
258
259func TestInstall(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100260 ctx, ctxC := context.WithCancel(context.Background())
261 defer ctxC()
262
Mateusz Zalega43e21072021-10-08 18:05:29 +0200263 // Prepare the block device image the installer will install to.
264 storagePath, err := getStorage(4096 + 128 + 128 + 1)
265 defer os.Remove(storagePath)
266 if err != nil {
267 t.Errorf(err.Error())
268 }
269
270 // Run QEMU. Expect the installer to succeed.
271 expectedOutput := "Installation completed"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100272 result, err := runQemuWithInstaller(ctx, qemuDriveParam(storagePath), expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200273 if err != nil {
274 t.Error(err.Error())
275 }
276 if result != true {
277 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
278 }
279
280 // Verify the resulting node image. Check whether the node GPT was created.
281 storage, err := diskfs.OpenWithMode(storagePath, diskfs.ReadOnly)
282 if err != nil {
283 t.Errorf("Couldn't open the resulting node image at %q: %s", storagePath, err.Error())
284 }
285 // Verify that GPT exists.
286 ti, err := storage.GetPartitionTable()
287 if ti.Type() != "gpt" {
288 t.Error("Couldn't verify that the resulting node image contains a GPT.")
289 }
290 // Check that the first partition is likely to be a valid ESP.
291 pi := ti.GetPartitions()
292 esp := (pi[0]).(*gpt.Partition)
293 if esp.Name != osimage.ESPVolumeLabel || esp.Start == 0 || esp.End == 0 {
294 t.Error("The node's ESP GPT entry looks off.")
295 }
296 // Verify the system partition's GPT entry.
297 system := (pi[1]).(*gpt.Partition)
298 if system.Name != osimage.SystemVolumeLabel || system.Start == 0 || system.End == 0 {
299 t.Error("The node's system partition GPT entry looks off.")
300 }
301 // Verify the data partition's GPT entry.
302 data := (pi[2]).(*gpt.Partition)
303 if data.Name != osimage.DataVolumeLabel || data.Start == 0 || data.End == 0 {
304 t.Errorf("The node's data partition GPT entry looks off.")
305 }
306 // Verify that there are no more partitions.
307 fourth := (pi[3]).(*gpt.Partition)
308 if fourth.Name != "" || fourth.Start != 0 || fourth.End != 0 {
309 t.Error("The resulting node image contains more partitions than expected.")
310 }
311 // Verify the ESP contents.
312 if err := checkEspContents(storage); err != nil {
313 t.Error(err.Error())
314 }
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100315 // Run QEMU again. Expect TestOS to launch successfully.
316 expectedOutput = "_TESTOS_LAUNCH_SUCCESS_"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100317 result, err = runQemu(ctx, qemuDriveParam(storagePath), expectedOutput)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100318 if err != nil {
319 t.Error(err.Error())
320 }
321 if result != true {
322 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
323 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200324}