blob: 39636548d7fa201ab7ed3883b651620e699a794a [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"
Serge Bazanski05cf33d2023-03-16 20:50:59 +010031 "time"
Mateusz Zalega43e21072021-10-08 18:05:29 +020032
33 diskfs "github.com/diskfs/go-diskfs"
34 "github.com/diskfs/go-diskfs/disk"
35 "github.com/diskfs/go-diskfs/partition/gpt"
Lorenz Brun0b93c8d2021-11-09 03:58:40 +010036
Mateusz Zalega43e21072021-10-08 18:05:29 +020037 mctl "source.monogon.dev/metropolis/cli/metroctl/core"
Serge Bazanski97783222021-12-14 16:04:26 +010038 "source.monogon.dev/metropolis/cli/pkg/datafile"
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010039 "source.monogon.dev/metropolis/node/build/mkimage/osimage"
Mateusz Zalegaf1234a92022-06-22 13:57:38 +020040 "source.monogon.dev/metropolis/pkg/cmd"
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010041 "source.monogon.dev/metropolis/proto/api"
Mateusz Zalega43e21072021-10-08 18:05:29 +020042)
43
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010044// Each variable in this block points to either a test dependency or a side
45// effect. These variables are initialized in TestMain using Bazel.
46var (
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010047 // installerImage is a filesystem path pointing at the installer image that
48 // is generated during the test, and is removed afterwards.
49 installerImage string
Mateusz Zalega43e21072021-10-08 18:05:29 +020050)
51
Mateusz Zalegaf1234a92022-06-22 13:57:38 +020052// runQemu starts a new QEMU process, expecting the given output to appear
53// in any line printed. It returns true, if the expected string was found,
54// and false otherwise.
Serge Bazanskie2e03712021-12-17 12:47:03 +010055//
Mateusz Zalegaf1234a92022-06-22 13:57:38 +020056// QEMU is killed shortly after the string is found, or when the context is
57// cancelled.
Serge Bazanskie2e03712021-12-17 12:47:03 +010058func runQemu(ctx context.Context, args []string, expectedOutput string) (bool, error) {
Mateusz Zalega43e21072021-10-08 18:05:29 +020059 defaultArgs := []string{
60 "-machine", "q35", "-accel", "kvm", "-nographic", "-nodefaults",
61 "-m", "512",
62 "-smp", "2",
63 "-cpu", "host",
64 "-drive", "if=pflash,format=raw,readonly,file=external/edk2/OVMF_CODE.fd",
65 "-drive", "if=pflash,format=raw,snapshot=on,file=external/edk2/OVMF_VARS.fd",
Mateusz Zalega43e21072021-10-08 18:05:29 +020066 "-serial", "stdio",
67 "-no-reboot",
68 }
Mateusz Zalega43e21072021-10-08 18:05:29 +020069 qemuArgs := append(defaultArgs, args...)
Mateusz Zalegab838e052022-08-12 18:08:10 +020070 pf := cmd.TerminateIfFound(expectedOutput, nil)
Mateusz Zalega6cdc9762022-08-03 17:15:01 +020071 return cmd.RunCommand(ctx, "external/qemu/qemu-x86_64-softmmu", qemuArgs, pf)
Mateusz Zalega43e21072021-10-08 18:05:29 +020072}
73
Serge Bazanskie2e03712021-12-17 12:47:03 +010074// runQemuWithInstaller runs the Metropolis Installer in a qemu, performing the
75// same search-through-std{out,err} as runQemu.
76func runQemuWithInstaller(ctx context.Context, args []string, expectedOutput string) (bool, error) {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010077 args = append(args, "-drive", "if=virtio,format=raw,snapshot=on,cache=unsafe,file="+installerImage)
Serge Bazanskie2e03712021-12-17 12:47:03 +010078 return runQemu(ctx, args, expectedOutput)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +010079}
80
Mateusz Zalega43e21072021-10-08 18:05:29 +020081// getStorage creates a sparse file, given a size expressed in mebibytes, and
82// returns a path to that file. It may return an error.
83func getStorage(size int64) (string, error) {
Serge Bazanski05cf33d2023-03-16 20:50:59 +010084 nodeStorageDir, err := os.MkdirTemp(os.Getenv("TEST_TMPDIR"), "storage")
85 if err != nil {
86 return "", err
87 }
88 nodeStorage := filepath.Join(nodeStorageDir, "stor.img")
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010089 image, err := os.Create(nodeStorage)
Mateusz Zalega43e21072021-10-08 18:05:29 +020090 if err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010091 return "", fmt.Errorf("couldn't create the block device image at %q: %w", nodeStorage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +020092 }
93 if err := syscall.Ftruncate(int(image.Fd()), size*1024*1024); err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010094 return "", fmt.Errorf("couldn't resize the block device image at %q: %w", nodeStorage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +020095 }
96 image.Close()
Mateusz Zalega8cde8e72021-11-30 16:22:20 +010097 return nodeStorage, nil
Mateusz Zalega43e21072021-10-08 18:05:29 +020098}
99
100// qemuDriveParam returns QEMU parameters required to run it with a
101// raw-format image at path.
102func qemuDriveParam(path string) []string {
103 return []string{"-drive", "if=virtio,format=raw,snapshot=off,cache=unsafe,file=" + path}
104}
105
106// checkEspContents verifies the presence of the EFI payload inside of image's
107// first partition. It returns nil on success.
108func checkEspContents(image *disk.Disk) error {
109 // Get the ESP.
110 fs, err := image.GetFilesystem(1)
111 if err != nil {
112 return fmt.Errorf("couldn't read the installer ESP: %w", err)
113 }
114 // Make sure the EFI payload exists by attempting to open it.
115 efiPayload, err := fs.OpenFile(osimage.EFIPayloadPath, os.O_RDONLY)
116 if err != nil {
117 return fmt.Errorf("couldn't open the installer's EFI Payload at %q: %w", osimage.EFIPayloadPath, err)
118 }
119 efiPayload.Close()
120 return nil
121}
122
123func TestMain(m *testing.M) {
Serge Bazanski97783222021-12-14 16:04:26 +0100124 installerImage = filepath.Join(os.Getenv("TEST_TMPDIR"), "installer.img")
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100125
Mateusz Zalegaedffbb52022-01-11 15:27:22 +0100126 installer := datafile.MustGet("metropolis/installer/test/kernel.efi")
127 bundle := datafile.MustGet("metropolis/installer/test/testos/testos_bundle.zip")
Mateusz Zalega43e21072021-10-08 18:05:29 +0200128 iargs := mctl.MakeInstallerImageArgs{
Serge Bazanski97783222021-12-14 16:04:26 +0100129 Installer: bytes.NewBuffer(installer),
130 InstallerSize: uint64(len(installer)),
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100131 TargetPath: installerImage,
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100132 NodeParams: &api.NodeParameters{},
Serge Bazanski97783222021-12-14 16:04:26 +0100133 Bundle: bytes.NewBuffer(bundle),
134 BundleSize: uint64(len(bundle)),
Mateusz Zalega43e21072021-10-08 18:05:29 +0200135 }
136 if err := mctl.MakeInstallerImage(iargs); err != nil {
Mateusz Zalega8f72b5d2021-12-03 17:08:59 +0100137 log.Fatalf("Couldn't create the installer image at %q: %v", installerImage, err)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200138 }
139 // With common dependencies set up, run the tests.
140 code := m.Run()
141 // Clean up.
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100142 os.Remove(installerImage)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200143 os.Exit(code)
144}
145
146func TestInstallerImage(t *testing.T) {
147 // This test examines the installer image, making sure that the GPT and the
148 // ESP contents are in order.
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100149 image, err := diskfs.OpenWithMode(installerImage, diskfs.ReadOnly)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200150 if err != nil {
Mateusz Zalega8cde8e72021-11-30 16:22:20 +0100151 t.Errorf("Couldn't open the installer image at %q: %s", installerImage, err.Error())
Mateusz Zalega43e21072021-10-08 18:05:29 +0200152 }
153 // Verify that GPT exists.
154 ti, err := image.GetPartitionTable()
155 if ti.Type() != "gpt" {
156 t.Error("Couldn't verify that the installer image contains a GPT.")
157 }
158 // Check that the first partition is likely to be a valid ESP.
159 pi := ti.GetPartitions()
160 esp := (pi[0]).(*gpt.Partition)
161 if esp.Start == 0 || esp.End == 0 {
162 t.Error("The installer's ESP GPT entry looks off.")
163 }
164 // Verify that the image contains only one partition.
165 second := (pi[1]).(*gpt.Partition)
166 if second.Name != "" || second.Start != 0 || second.End != 0 {
167 t.Error("It appears the installer image contains more than one partition.")
168 }
169 // Verify the ESP contents.
170 if err := checkEspContents(image); err != nil {
171 t.Error(err.Error())
172 }
173}
174
175func TestNoBlockDevices(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100176 ctx, ctxC := context.WithCancel(context.Background())
177 defer ctxC()
178
Mateusz Zalega43e21072021-10-08 18:05:29 +0200179 // No block devices are passed to QEMU aside from the install medium. Expect
180 // the installer to fail at the device probe stage rather than attempting to
181 // use the medium as the target device.
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100182 expectedOutput := "Couldn't find a suitable block device"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100183 result, err := runQemuWithInstaller(ctx, nil, expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200184 if err != nil {
185 t.Error(err.Error())
186 }
187 if result != true {
188 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
189 }
190}
191
192func TestBlockDeviceTooSmall(t *testing.T) {
Serge Bazanskie2e03712021-12-17 12:47:03 +0100193 ctx, ctxC := context.WithCancel(context.Background())
194 defer ctxC()
195
Mateusz Zalega43e21072021-10-08 18:05:29 +0200196 // Prepare the block device the installer will install to. This time the
197 // target device is too small to host a Metropolis installation.
198 imagePath, err := getStorage(64)
199 defer os.Remove(imagePath)
200 if err != nil {
201 t.Errorf(err.Error())
202 }
203
204 // Run QEMU. Expect the installer to fail with a predefined error string.
Mateusz Zalegacdcc7392021-12-08 15:34:53 +0100205 expectedOutput := "Couldn't find a suitable block device"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100206 result, err := runQemuWithInstaller(ctx, qemuDriveParam(imagePath), expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200207 if err != nil {
208 t.Error(err.Error())
209 }
210 if result != true {
211 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
212 }
213}
214
215func TestInstall(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 // Prepare the block device image the installer will install to.
220 storagePath, err := getStorage(4096 + 128 + 128 + 1)
221 defer os.Remove(storagePath)
222 if err != nil {
223 t.Errorf(err.Error())
224 }
225
226 // Run QEMU. Expect the installer to succeed.
227 expectedOutput := "Installation completed"
Serge Bazanskie2e03712021-12-17 12:47:03 +0100228 result, err := runQemuWithInstaller(ctx, qemuDriveParam(storagePath), expectedOutput)
Mateusz Zalega43e21072021-10-08 18:05:29 +0200229 if err != nil {
230 t.Error(err.Error())
231 }
232 if result != true {
233 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
234 }
235
236 // Verify the resulting node image. Check whether the node GPT was created.
237 storage, err := diskfs.OpenWithMode(storagePath, diskfs.ReadOnly)
238 if err != nil {
239 t.Errorf("Couldn't open the resulting node image at %q: %s", storagePath, err.Error())
240 }
241 // Verify that GPT exists.
242 ti, err := storage.GetPartitionTable()
243 if ti.Type() != "gpt" {
244 t.Error("Couldn't verify that the resulting node image contains a GPT.")
245 }
246 // Check that the first partition is likely to be a valid ESP.
247 pi := ti.GetPartitions()
248 esp := (pi[0]).(*gpt.Partition)
249 if esp.Name != osimage.ESPVolumeLabel || esp.Start == 0 || esp.End == 0 {
250 t.Error("The node's ESP GPT entry looks off.")
251 }
252 // Verify the system partition's GPT entry.
253 system := (pi[1]).(*gpt.Partition)
254 if system.Name != osimage.SystemVolumeLabel || system.Start == 0 || system.End == 0 {
255 t.Error("The node's system partition GPT entry looks off.")
256 }
257 // Verify the data partition's GPT entry.
258 data := (pi[2]).(*gpt.Partition)
259 if data.Name != osimage.DataVolumeLabel || data.Start == 0 || data.End == 0 {
260 t.Errorf("The node's data partition GPT entry looks off.")
261 }
262 // Verify that there are no more partitions.
263 fourth := (pi[3]).(*gpt.Partition)
264 if fourth.Name != "" || fourth.Start != 0 || fourth.End != 0 {
265 t.Error("The resulting node image contains more partitions than expected.")
266 }
267 // Verify the ESP contents.
268 if err := checkEspContents(storage); err != nil {
269 t.Error(err.Error())
270 }
Serge Bazanski05cf33d2023-03-16 20:50:59 +0100271 //storage.File.Close()
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100272 // Run QEMU again. Expect TestOS to launch successfully.
273 expectedOutput = "_TESTOS_LAUNCH_SUCCESS_"
Serge Bazanski05cf33d2023-03-16 20:50:59 +0100274 time.Sleep(time.Second)
Serge Bazanskie2e03712021-12-17 12:47:03 +0100275 result, err = runQemu(ctx, qemuDriveParam(storagePath), expectedOutput)
Lorenz Brun0b93c8d2021-11-09 03:58:40 +0100276 if err != nil {
277 t.Error(err.Error())
278 }
279 if result != true {
280 t.Errorf("QEMU didn't produce the expected output %q", expectedOutput)
281 }
Mateusz Zalega43e21072021-10-08 18:05:29 +0200282}