blob: 5e37b7d91c1b6fa6c5e29b7d12b9b3ae8ca7ba22 [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"
Mateusz Zalega43e21072021-10-08 18:05:29 +020026 "log"
27 "os"
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010028 "path/filepath"
Mateusz Zalega43e21072021-10-08 18:05:29 +020029 "syscall"
30 "testing"
31
32 diskfs "github.com/diskfs/go-diskfs"
33 "github.com/diskfs/go-diskfs/disk"
34 "github.com/diskfs/go-diskfs/partition/gpt"
Lorenz Brun0b93c8d2021-11-09 03:58:40 +010035
Mateusz Zalega43e21072021-10-08 18:05:29 +020036 mctl "source.monogon.dev/metropolis/cli/metroctl/core"
Serge Bazanski97783222021-12-14 16:04:26 +010037 "source.monogon.dev/metropolis/cli/pkg/datafile"
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010038 "source.monogon.dev/metropolis/node/build/mkimage/osimage"
Mateusz Zalegaf1234a92022-06-22 13:57:38 +020039 "source.monogon.dev/metropolis/pkg/cmd"
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010040 "source.monogon.dev/metropolis/proto/api"
Mateusz Zalega43e21072021-10-08 18:05:29 +020041)
42
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010043// Each variable in this block points to either a test dependency or a side
44// effect. These variables are initialized in TestMain using Bazel.
45var (
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010046 // installerImage is a filesystem path pointing at the installer image that
47 // is generated during the test, and is removed afterwards.
48 installerImage string
49 // nodeStorage is a filesystem path pointing at the VM block device image
50 // Metropolis is installed to during the test. The file is removed afterwards.
51 nodeStorage string
Mateusz Zalega43e21072021-10-08 18:05:29 +020052)
53
Mateusz Zalegaf1234a92022-06-22 13:57:38 +020054// runQemu starts a new QEMU process, expecting the given output to appear
55// in any line printed. It returns true, if the expected string was found,
56// and false otherwise.
Serge Bazanskie2e03712021-12-17 12:47:03 +010057//
Mateusz Zalegaf1234a92022-06-22 13:57:38 +020058// QEMU is killed shortly after the string is found, or when the context is
59// cancelled.
Serge Bazanskie2e03712021-12-17 12:47:03 +010060func runQemu(ctx context.Context, args []string, expectedOutput string) (bool, error) {
Mateusz Zalega43e21072021-10-08 18:05:29 +020061 defaultArgs := []string{
62 "-machine", "q35", "-accel", "kvm", "-nographic", "-nodefaults",
63 "-m", "512",
64 "-smp", "2",
65 "-cpu", "host",
66 "-drive", "if=pflash,format=raw,readonly,file=external/edk2/OVMF_CODE.fd",
67 "-drive", "if=pflash,format=raw,snapshot=on,file=external/edk2/OVMF_VARS.fd",
Mateusz Zalega43e21072021-10-08 18:05:29 +020068 "-serial", "stdio",
69 "-no-reboot",
70 }
Mateusz Zalega43e21072021-10-08 18:05:29 +020071 qemuArgs := append(defaultArgs, args...)
Mateusz Zalegab838e052022-08-12 18:08:10 +020072 pf := cmd.TerminateIfFound(expectedOutput, nil)
Mateusz Zalega6cdc9762022-08-03 17:15:01 +020073 return cmd.RunCommand(ctx, "external/qemu/qemu-x86_64-softmmu", qemuArgs, pf)
Mateusz Zalega43e21072021-10-08 18:05:29 +020074}
75
Serge Bazanskie2e03712021-12-17 12:47:03 +010076// runQemuWithInstaller runs the Metropolis Installer in a qemu, performing the
77// same search-through-std{out,err} as runQemu.
78func runQemuWithInstaller(ctx context.Context, args []string, expectedOutput string) (bool, error) {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010079 args = append(args, "-drive", "if=virtio,format=raw,snapshot=on,cache=unsafe,file="+installerImage)
Serge Bazanskie2e03712021-12-17 12:47:03 +010080 return runQemu(ctx, args, expectedOutput)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +010081}
82
Mateusz Zalega43e21072021-10-08 18:05:29 +020083// getStorage creates a sparse file, given a size expressed in mebibytes, and
84// returns a path to that file. It may return an error.
85func getStorage(size int64) (string, error) {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010086 image, err := os.Create(nodeStorage)
Mateusz Zalega43e21072021-10-08 18:05:29 +020087 if err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010088 return "", fmt.Errorf("couldn't create the block device image at %q: %w", nodeStorage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +020089 }
90 if err := syscall.Ftruncate(int(image.Fd()), size*1024*1024); err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010091 return "", fmt.Errorf("couldn't resize the block device image at %q: %w", nodeStorage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +020092 }
93 image.Close()
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010094 return nodeStorage, nil
Mateusz Zalega43e21072021-10-08 18:05:29 +020095}
96
97// qemuDriveParam returns QEMU parameters required to run it with a
98// raw-format image at path.
99func qemuDriveParam(path string) []string {
100 return []string{"-drive", "if=virtio,format=raw,snapshot=off,cache=unsafe,file=" + path}
101}
102
103// checkEspContents verifies the presence of the EFI payload inside of image's
104// first partition. It returns nil on success.
105func checkEspContents(image *disk.Disk) error {
106 // Get the ESP.
107 fs, err := image.GetFilesystem(1)
108 if err != nil {
109 return fmt.Errorf("couldn't read the installer ESP: %w", err)
110 }
111 // Make sure the EFI payload exists by attempting to open it.
112 efiPayload, err := fs.OpenFile(osimage.EFIPayloadPath, os.O_RDONLY)
113 if err != nil {
114 return fmt.Errorf("couldn't open the installer's EFI Payload at %q: %w", osimage.EFIPayloadPath, err)
115 }
116 efiPayload.Close()
117 return nil
118}
119
120func TestMain(m *testing.M) {
Serge Bazanski97783222021-12-14 16:04:26 +0100121 installerImage = filepath.Join(os.Getenv("TEST_TMPDIR"), "installer.img")
122 nodeStorage = filepath.Join(os.Getenv("TEST_TMPDIR"), "stor.img")
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100123
Mateusz Zalegaedffbb52022-01-11 15:27:22 +0100124 installer := datafile.MustGet("metropolis/installer/test/kernel.efi")
125 bundle := datafile.MustGet("metropolis/installer/test/testos/testos_bundle.zip")
Mateusz Zalega43e21072021-10-08 18:05:29 +0200126 iargs := mctl.MakeInstallerImageArgs{
Serge Bazanski97783222021-12-14 16:04:26 +0100127 Installer: bytes.NewBuffer(installer),
128 InstallerSize: uint64(len(installer)),
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100129 TargetPath: installerImage,
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100130 NodeParams: &api.NodeParameters{},
Serge Bazanski97783222021-12-14 16:04:26 +0100131 Bundle: bytes.NewBuffer(bundle),
132 BundleSize: uint64(len(bundle)),
Mateusz Zalega43e21072021-10-08 18:05:29 +0200133 }
134 if err := mctl.MakeInstallerImage(iargs); err != nil {
Mateusz Zalega8f72b5d2021-12-03 17:08:59 +0100135 log.Fatalf("Couldn't create the installer image at %q: %v", installerImage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200136 }
137 // With common dependencies set up, run the tests.
138 code := m.Run()
139 // Clean up.
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100140 os.Remove(installerImage)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200141 os.Exit(code)
142}
143
144func TestInstallerImage(t *testing.T) {
145 // This test examines the installer image, making sure that the GPT and the
146 // ESP contents are in order.
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100147 image, err := diskfs.OpenWithMode(installerImage, diskfs.ReadOnly)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200148 if err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100149 t.Errorf("Couldn't open the installer image at %q: %s", installerImage, err.Error())
Mateusz Zalega43e21072021-10-08 18:05:29 +0200150 }
151 // Verify that GPT exists.
152 ti, err := image.GetPartitionTable()
153 if ti.Type() != "gpt" {
154 t.Error("Couldn't verify that the installer image contains a GPT.")
155 }
156 // Check that the first partition is likely to be a valid ESP.
157 pi := ti.GetPartitions()
158 esp := (pi[0]).(*gpt.Partition)
159 if esp.Start == 0 || esp.End == 0 {
160 t.Error("The installer's ESP GPT entry looks off.")
161 }
162 // Verify that the image contains only one partition.
163 second := (pi[1]).(*gpt.Partition)
164 if second.Name != "" || second.Start != 0 || second.End != 0 {
165 t.Error("It appears the installer image contains more than one partition.")
166 }
167 // Verify the ESP contents.
168 if err := checkEspContents(image); err != nil {
169 t.Error(err.Error())
170 }
171}
172
173func TestNoBlockDevices(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100174 ctx, ctxC := context.WithCancel(context.Background())
175 defer ctxC()
176
Mateusz Zalega43e21072021-10-08 18:05:29 +0200177 // No block devices are passed to QEMU aside from the install medium. Expect
178 // the installer to fail at the device probe stage rather than attempting to
179 // use the medium as the target device.
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100180 expectedOutput := "Couldn't find a suitable block device"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100181 result, err := runQemuWithInstaller(ctx, nil, expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200182 if err != nil {
183 t.Error(err.Error())
184 }
185 if result != true {
186 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
187 }
188}
189
190func TestBlockDeviceTooSmall(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100191 ctx, ctxC := context.WithCancel(context.Background())
192 defer ctxC()
193
Mateusz Zalega43e21072021-10-08 18:05:29 +0200194 // Prepare the block device the installer will install to. This time the
195 // target device is too small to host a Metropolis installation.
196 imagePath, err := getStorage(64)
197 defer os.Remove(imagePath)
198 if err != nil {
199 t.Errorf(err.Error())
200 }
201
202 // Run QEMU. Expect the installer to fail with a predefined error string.
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100203 expectedOutput := "Couldn't find a suitable block device"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100204 result, err := runQemuWithInstaller(ctx, qemuDriveParam(imagePath), expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200205 if err != nil {
206 t.Error(err.Error())
207 }
208 if result != true {
209 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
210 }
211}
212
213func TestInstall(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100214 ctx, ctxC := context.WithCancel(context.Background())
215 defer ctxC()
216
Mateusz Zalega43e21072021-10-08 18:05:29 +0200217 // Prepare the block device image the installer will install to.
218 storagePath, err := getStorage(4096 + 128 + 128 + 1)
219 defer os.Remove(storagePath)
220 if err != nil {
221 t.Errorf(err.Error())
222 }
223
224 // Run QEMU. Expect the installer to succeed.
225 expectedOutput := "Installation completed"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100226 result, err := runQemuWithInstaller(ctx, qemuDriveParam(storagePath), expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200227 if err != nil {
228 t.Error(err.Error())
229 }
230 if result != true {
231 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
232 }
233
234 // Verify the resulting node image. Check whether the node GPT was created.
235 storage, err := diskfs.OpenWithMode(storagePath, diskfs.ReadOnly)
236 if err != nil {
237 t.Errorf("Couldn't open the resulting node image at %q: %s", storagePath, err.Error())
238 }
239 // Verify that GPT exists.
240 ti, err := storage.GetPartitionTable()
241 if ti.Type() != "gpt" {
242 t.Error("Couldn't verify that the resulting node image contains a GPT.")
243 }
244 // Check that the first partition is likely to be a valid ESP.
245 pi := ti.GetPartitions()
246 esp := (pi[0]).(*gpt.Partition)
247 if esp.Name != osimage.ESPVolumeLabel || esp.Start == 0 || esp.End == 0 {
248 t.Error("The node's ESP GPT entry looks off.")
249 }
250 // Verify the system partition's GPT entry.
251 system := (pi[1]).(*gpt.Partition)
252 if system.Name != osimage.SystemVolumeLabel || system.Start == 0 || system.End == 0 {
253 t.Error("The node's system partition GPT entry looks off.")
254 }
255 // Verify the data partition's GPT entry.
256 data := (pi[2]).(*gpt.Partition)
257 if data.Name != osimage.DataVolumeLabel || data.Start == 0 || data.End == 0 {
258 t.Errorf("The node's data partition GPT entry looks off.")
259 }
260 // Verify that there are no more partitions.
261 fourth := (pi[3]).(*gpt.Partition)
262 if fourth.Name != "" || fourth.Start != 0 || fourth.End != 0 {
263 t.Error("The resulting node image contains more partitions than expected.")
264 }
265 // Verify the ESP contents.
266 if err := checkEspContents(storage); err != nil {
267 t.Error(err.Error())
268 }
Mateusz Zalega4f6fad32022-05-25 16:34:30 +0200269 storage.File.Close()
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100270 // Run QEMU again. Expect TestOS to launch successfully.
271 expectedOutput = "_TESTOS_LAUNCH_SUCCESS_"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100272 result, err = runQemu(ctx, qemuDriveParam(storagePath), expectedOutput)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100273 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 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200279}