blob: 9f38b4d9816fe48f7d7392678bf393a97f65828e [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) {
Mateusz Zalega4f6fad32022-05-25 16:34:30 +0200116 qemuCmd.Process.Kill()
117 qemuCmd.Wait()
Serge Bazanskie2e03712021-12-17 12:47:03 +0100118 return true, nil
119 }
120 }
121 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200122}
123
Serge Bazanskie2e03712021-12-17 12:47:03 +0100124// runQemuWithInstaller runs the Metropolis Installer in a qemu, performing the
125// same search-through-std{out,err} as runQemu.
126func runQemuWithInstaller(ctx context.Context, args []string, expectedOutput string) (bool, error) {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100127 args = append(args, "-drive", "if=virtio,format=raw,snapshot=on,cache=unsafe,file="+installerImage)
Serge Bazanskie2e03712021-12-17 12:47:03 +0100128 return runQemu(ctx, args, expectedOutput)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100129}
130
Mateusz Zalega43e21072021-10-08 18:05:29 +0200131// getStorage creates a sparse file, given a size expressed in mebibytes, and
132// returns a path to that file. It may return an error.
133func getStorage(size int64) (string, error) {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100134 image, err := os.Create(nodeStorage)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200135 if err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100136 return "", fmt.Errorf("couldn't create the block device image at %q: %w", nodeStorage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200137 }
138 if err := syscall.Ftruncate(int(image.Fd()), size*1024*1024); err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100139 return "", fmt.Errorf("couldn't resize the block device image at %q: %w", nodeStorage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200140 }
141 image.Close()
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100142 return nodeStorage, nil
Mateusz Zalega43e21072021-10-08 18:05:29 +0200143}
144
145// qemuDriveParam returns QEMU parameters required to run it with a
146// raw-format image at path.
147func qemuDriveParam(path string) []string {
148 return []string{"-drive", "if=virtio,format=raw,snapshot=off,cache=unsafe,file=" + path}
149}
150
151// checkEspContents verifies the presence of the EFI payload inside of image's
152// first partition. It returns nil on success.
153func checkEspContents(image *disk.Disk) error {
154 // Get the ESP.
155 fs, err := image.GetFilesystem(1)
156 if err != nil {
157 return fmt.Errorf("couldn't read the installer ESP: %w", err)
158 }
159 // Make sure the EFI payload exists by attempting to open it.
160 efiPayload, err := fs.OpenFile(osimage.EFIPayloadPath, os.O_RDONLY)
161 if err != nil {
162 return fmt.Errorf("couldn't open the installer's EFI Payload at %q: %w", osimage.EFIPayloadPath, err)
163 }
164 efiPayload.Close()
165 return nil
166}
167
168func TestMain(m *testing.M) {
Serge Bazanski97783222021-12-14 16:04:26 +0100169 installerImage = filepath.Join(os.Getenv("TEST_TMPDIR"), "installer.img")
170 nodeStorage = filepath.Join(os.Getenv("TEST_TMPDIR"), "stor.img")
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100171
Mateusz Zalegaedffbb52022-01-11 15:27:22 +0100172 installer := datafile.MustGet("metropolis/installer/test/kernel.efi")
173 bundle := datafile.MustGet("metropolis/installer/test/testos/testos_bundle.zip")
Mateusz Zalega43e21072021-10-08 18:05:29 +0200174 iargs := mctl.MakeInstallerImageArgs{
Serge Bazanski97783222021-12-14 16:04:26 +0100175 Installer: bytes.NewBuffer(installer),
176 InstallerSize: uint64(len(installer)),
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100177 TargetPath: installerImage,
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100178 NodeParams: &api.NodeParameters{},
Serge Bazanski97783222021-12-14 16:04:26 +0100179 Bundle: bytes.NewBuffer(bundle),
180 BundleSize: uint64(len(bundle)),
Mateusz Zalega43e21072021-10-08 18:05:29 +0200181 }
182 if err := mctl.MakeInstallerImage(iargs); err != nil {
Mateusz Zalega8f72b5d2021-12-03 17:08:59 +0100183 log.Fatalf("Couldn't create the installer image at %q: %v", installerImage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200184 }
185 // With common dependencies set up, run the tests.
186 code := m.Run()
187 // Clean up.
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100188 os.Remove(installerImage)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200189 os.Exit(code)
190}
191
192func TestInstallerImage(t *testing.T) {
193 // This test examines the installer image, making sure that the GPT and the
194 // ESP contents are in order.
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100195 image, err := diskfs.OpenWithMode(installerImage, diskfs.ReadOnly)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200196 if err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100197 t.Errorf("Couldn't open the installer image at %q: %s", installerImage, err.Error())
Mateusz Zalega43e21072021-10-08 18:05:29 +0200198 }
199 // Verify that GPT exists.
200 ti, err := image.GetPartitionTable()
201 if ti.Type() != "gpt" {
202 t.Error("Couldn't verify that the installer image contains a GPT.")
203 }
204 // Check that the first partition is likely to be a valid ESP.
205 pi := ti.GetPartitions()
206 esp := (pi[0]).(*gpt.Partition)
207 if esp.Start == 0 || esp.End == 0 {
208 t.Error("The installer's ESP GPT entry looks off.")
209 }
210 // Verify that the image contains only one partition.
211 second := (pi[1]).(*gpt.Partition)
212 if second.Name != "" || second.Start != 0 || second.End != 0 {
213 t.Error("It appears the installer image contains more than one partition.")
214 }
215 // Verify the ESP contents.
216 if err := checkEspContents(image); err != nil {
217 t.Error(err.Error())
218 }
219}
220
221func TestNoBlockDevices(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100222 ctx, ctxC := context.WithCancel(context.Background())
223 defer ctxC()
224
Mateusz Zalega43e21072021-10-08 18:05:29 +0200225 // No block devices are passed to QEMU aside from the install medium. Expect
226 // the installer to fail at the device probe stage rather than attempting to
227 // use the medium as the target device.
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100228 expectedOutput := "Couldn't find a suitable block device"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100229 result, err := runQemuWithInstaller(ctx, nil, expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200230 if err != nil {
231 t.Error(err.Error())
232 }
233 if result != true {
234 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
235 }
236}
237
238func TestBlockDeviceTooSmall(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100239 ctx, ctxC := context.WithCancel(context.Background())
240 defer ctxC()
241
Mateusz Zalega43e21072021-10-08 18:05:29 +0200242 // Prepare the block device the installer will install to. This time the
243 // target device is too small to host a Metropolis installation.
244 imagePath, err := getStorage(64)
245 defer os.Remove(imagePath)
246 if err != nil {
247 t.Errorf(err.Error())
248 }
249
250 // Run QEMU. Expect the installer to fail with a predefined error string.
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100251 expectedOutput := "Couldn't find a suitable block device"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100252 result, err := runQemuWithInstaller(ctx, qemuDriveParam(imagePath), expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200253 if err != nil {
254 t.Error(err.Error())
255 }
256 if result != true {
257 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
258 }
259}
260
261func TestInstall(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100262 ctx, ctxC := context.WithCancel(context.Background())
263 defer ctxC()
264
Mateusz Zalega43e21072021-10-08 18:05:29 +0200265 // Prepare the block device image the installer will install to.
266 storagePath, err := getStorage(4096 + 128 + 128 + 1)
267 defer os.Remove(storagePath)
268 if err != nil {
269 t.Errorf(err.Error())
270 }
271
272 // Run QEMU. Expect the installer to succeed.
273 expectedOutput := "Installation completed"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100274 result, err := runQemuWithInstaller(ctx, qemuDriveParam(storagePath), 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 // Verify the resulting node image. Check whether the node GPT was created.
283 storage, err := diskfs.OpenWithMode(storagePath, diskfs.ReadOnly)
284 if err != nil {
285 t.Errorf("Couldn't open the resulting node image at %q: %s", storagePath, err.Error())
286 }
287 // Verify that GPT exists.
288 ti, err := storage.GetPartitionTable()
289 if ti.Type() != "gpt" {
290 t.Error("Couldn't verify that the resulting node image contains a GPT.")
291 }
292 // Check that the first partition is likely to be a valid ESP.
293 pi := ti.GetPartitions()
294 esp := (pi[0]).(*gpt.Partition)
295 if esp.Name != osimage.ESPVolumeLabel || esp.Start == 0 || esp.End == 0 {
296 t.Error("The node's ESP GPT entry looks off.")
297 }
298 // Verify the system partition's GPT entry.
299 system := (pi[1]).(*gpt.Partition)
300 if system.Name != osimage.SystemVolumeLabel || system.Start == 0 || system.End == 0 {
301 t.Error("The node's system partition GPT entry looks off.")
302 }
303 // Verify the data partition's GPT entry.
304 data := (pi[2]).(*gpt.Partition)
305 if data.Name != osimage.DataVolumeLabel || data.Start == 0 || data.End == 0 {
306 t.Errorf("The node's data partition GPT entry looks off.")
307 }
308 // Verify that there are no more partitions.
309 fourth := (pi[3]).(*gpt.Partition)
310 if fourth.Name != "" || fourth.Start != 0 || fourth.End != 0 {
311 t.Error("The resulting node image contains more partitions than expected.")
312 }
313 // Verify the ESP contents.
314 if err := checkEspContents(storage); err != nil {
315 t.Error(err.Error())
316 }
Mateusz Zalega4f6fad32022-05-25 16:34:30 +0200317 storage.File.Close()
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100318 // Run QEMU again. Expect TestOS to launch successfully.
319 expectedOutput = "_TESTOS_LAUNCH_SUCCESS_"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100320 result, err = runQemu(ctx, qemuDriveParam(storagePath), expectedOutput)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100321 if err != nil {
322 t.Error(err.Error())
323 }
324 if result != true {
325 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
326 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200327}