From 0c5c4544f535b6dad0b4f7a0accb28a5e531d147 Mon Sep 17 00:00:00 2001 From: eriknordmark Date: Wed, 9 Sep 2026 22:56:27 +0200 Subject: [PATCH 01/10] evetest: framework support for the conversion tests Four additions the EVE-kvm/EVE-K conversion tests need and the framework did not have. A ContentTree can now be declared on its own, with no Volume referencing it. A test whose subject is the image blobs themselves -- that they survive an event, or that a later deployment reuses them -- wants them on the device without a PVC or a CDI import in the picture, which going through AddVolume would drag in. A powered-off device's boot disk can be edited in place: grown, leaving the added space unallocated past the last partition, or made to lose the filesystem on one of its partitions. The first is the precondition for EVE's in-field repartition to grow into slack rather than shrink /persist, and cannot be arranged at creation time because EVE's image generator sizes partitions to fill whatever disk it is given; the second is the data loss a backup-and-restore path has to survive. Both rewrite the file the device boots from, so the broker requires the device to be powered off rather than letting qemu-img discover it, and advertises CAPABILITY_EDIT_DEVICE_DISK only for the overlay disk strategy, where it still owns that file. RAM and vCPU count join the shared test parameters, since sizing a device is not particular to these tests. Finally, a base-OS update can be applied that EVE is expected to reject. A rejection is not a failed upgrade: EVE refuses in place, before it writes a partition and before it reboots, so there is nothing to wait for and no reboot to account for -- and the reboot audit is an equality check, so booking one that cannot happen fails the run at teardown. The expected outcome is now explicit inside the upgrade path, and UpgradeEVE's own signature is unchanged. Signed-off-by: eriknordmark Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01NZEoFvMK2UHByU3LAeXsxA --- evetest/Dockerfile.broker | 8 +- evetest/Dockerfile.evetest | 4 +- evetest/VERSION | 2 +- evetest/broker/broker.go | 90 +++++- evetest/broker/diskedit.go | 158 +++++++++++ evetest/devconfig.go | 47 ++++ evetest/edgedevice.go | 145 ++++++++-- evetest/grpcapi/go/broker.pb.go | 401 ++++++++++++++++++++++----- evetest/grpcapi/go/broker_grpc.pb.go | 42 +++ evetest/grpcapi/go/common.pb.go | 12 +- evetest/grpcapi/proto/broker.proto | 37 +++ evetest/grpcapi/proto/common.proto | 5 + evetest/harness.go | 3 + evetest/testparam.go | 44 +++ 14 files changed, 897 insertions(+), 101 deletions(-) create mode 100644 evetest/broker/diskedit.go diff --git a/evetest/Dockerfile.broker b/evetest/Dockerfile.broker index bc2e7a5b5a2..b325278c81d 100644 --- a/evetest/Dockerfile.broker +++ b/evetest/Dockerfile.broker @@ -75,10 +75,12 @@ FROM alpine:${ALPINE_VERSION} # Install runtime dependencies. # qemu-img provides qemu-img/qemu-io/qemu-nbd; mtools provides mcopy, used to # overlay a device's config files onto the EVE config partition image exactly -# as pkg/eve/runme.sh does. bash is not used by the broker itself -- it is for -# interactive debugging via `docker exec`, where BusyBox ash is painful. +# as pkg/eve/runme.sh does. sgdisk relocates the backup GPT after a disk is +# grown -- without it the added space is not usable. bash is +# not used by the broker itself -- it is for interactive debugging via +# `docker exec`, where BusyBox ash is painful. # hadolint ignore=DL3018 -RUN apk add --no-cache libvirt iptables ip6tables qemu-img mtools bash +RUN apk add --no-cache libvirt iptables ip6tables qemu-img sgdisk mtools bash # Copy the built broker binary from builder COPY --from=builder /go/bin/evetest-broker /usr/local/bin/evetest-broker diff --git a/evetest/Dockerfile.evetest b/evetest/Dockerfile.evetest index 97c486baa05..8a955928b0f 100644 --- a/evetest/Dockerfile.evetest +++ b/evetest/Dockerfile.evetest @@ -68,11 +68,13 @@ RUN apk add --no-cache iptables dnsmasq radvd swtpm # Install QEMU. qemu-img also provides qemu-io/qemu-nbd; mtools provides mcopy, # used together to assemble a device's config partition and write it into a -# template-backed disk image (see Dockerfile.broker). +# template-backed disk image (see Dockerfile.broker). sgdisk relocates the backup +# GPT after a disk is grown -- without it the added space is not usable. # hadolint ignore=DL3018 RUN apk add --no-cache \ qemu \ qemu-img \ + sgdisk \ mtools \ qemu-system-x86_64 \ qemu-system-aarch64 diff --git a/evetest/VERSION b/evetest/VERSION index b30db2346d7..88bd734e71e 100644 --- a/evetest/VERSION +++ b/evetest/VERSION @@ -1,2 +1,2 @@ # Evetest version. Increment this manually whenever changes are made to the evetest framework. -1.6 +1.7 diff --git a/evetest/broker/broker.go b/evetest/broker/broker.go index 8c865587442..077d840bd99 100644 --- a/evetest/broker/broker.go +++ b/evetest/broker/broker.go @@ -147,18 +147,23 @@ type device struct { } // brokerCapabilities composes the full capability set advertised to clients: -// the provider's own capabilities plus CAPABILITY_LOCAL_LIVE_IMAGE whenever -// diskStrategy is not DiskImageLegacyBuild. A provider never builds or -// receives an EVE image, so whether an uploaded live image can be consumed is -// the broker's determination; it depends on the provider only through its -// disk image strategy, which is why that decision lives here rather than in -// provider.Capabilities(). +// the provider's own capabilities plus the two the broker decides itself. +// A provider never builds, receives or edits an EVE image, so both depend on +// the provider only through its disk image strategy, which is why they live +// here rather than in provider.Capabilities(). func brokerCapabilities( providerCaps []api.Capability, diskStrategy provider.DiskImageStrategy) []api.Capability { caps := append([]api.Capability{}, providerCaps...) if diskStrategy != provider.DiskImageLegacyBuild { caps = append(caps, api.Capability_CAPABILITY_LOCAL_LIVE_IMAGE) } + // Editing a device's disk means reading and writing the very file that + // device boots from, which the broker can only do while the file stays + // where it put it. The overlay strategy is exactly that case; a standalone + // disk may since have been handed to a node the broker cannot reach. + if diskStrategy == provider.DiskImageOverlay { + caps = append(caps, api.Capability_CAPABILITY_EDIT_DEVICE_DISK) + } return caps } @@ -1655,6 +1660,79 @@ func (b *broker) PowerOffDevice( return &api.DeviceControlResponse{}, nil } +// EditDeviceDisk edits a powered-off device's boot disk in place: it grows the +// disk, or destroys the filesystem on one of its partitions. +// +// Both edits rewrite the file the device boots from, so a running device would +// see its disk change underneath it and, for the grow, qemu-img would be +// writing an image QEMU still has mapped. The device is therefore required to +// be powered off, and that is checked rather than left to the tools to notice. +func (b *broker) EditDeviceDisk( + ctx context.Context, req *api.EditDeviceDiskRequest) (*api.EditDeviceDiskResponse, error) { + b.mutex.Lock() + clientSession, exists := b.sessions[req.ClientId] + b.mutex.Unlock() + if !exists { + err := clientNotFoundErr(req.ClientId) + b.globalLog.Error(err) + return nil, err + } + + clientSession.mutex.Lock() + log := clientSession.log + eveDevice, exists := clientSession.eveDevices[req.DeviceName] + clientSession.mutex.Unlock() + if !exists { + err := eveDevNotFoundErr(req.DeviceName) + log.Error(err) + return nil, err + } + ctx = logger.WithLogger(ctx, log) + + if len(eveDevice.disks) == 0 { + err := fmt.Errorf("EVE device %q has no disk to edit", eveDevice.deviceName) + log.Error(err) + return nil, err + } + bootDisk := eveDevice.disks[0] + if bootDisk.Format != provider.DiskImageFormatQcow2 { + err := fmt.Errorf("boot disk of EVE device %q is not QCOW2; cannot edit it", + eveDevice.deviceName) + log.Error(err) + return nil, err + } + + status, err := b.provider.GetDeviceStatus(ctx, eveDevice.providerDevName) + if err != nil { + err = fmt.Errorf("failed to read status of EVE device %q: %w", + eveDevice.deviceName, err) + log.Error(err) + return nil, err + } + if status != provider.DeviceStatusStopped { + err = fmt.Errorf( + "EVE device %q is %s; power it off before editing its disk", + eveDevice.deviceName, status) + log.Error(err) + return nil, err + } + + switch edit := req.GetEdit().(type) { + case *api.EditDeviceDiskRequest_Grow: + err = growDisk(ctx, log, bootDisk.Path, edit.Grow.GetNewSizeBytes()) + case *api.EditDeviceDiskRequest_DestroyPartitionFs: + err = destroyPartitionFilesystem(ctx, log, bootDisk.Path, + edit.DestroyPartitionFs.GetPartitionLabel()) + default: + err = fmt.Errorf("no edit requested for EVE device %q", eveDevice.deviceName) + } + if err != nil { + log.Error(err) + return nil, err + } + return &api.EditDeviceDiskResponse{}, nil +} + // RebootDevice reboots a specific EVE device. The provider call runs without // holding clientSession.mutex; see PowerOffDevice's doc comment. func (b *broker) RebootDevice( diff --git a/evetest/broker/diskedit.go b/evetest/broker/diskedit.go new file mode 100644 index 00000000000..5d0d07d5d67 --- /dev/null +++ b/evetest/broker/diskedit.go @@ -0,0 +1,158 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "encoding/json" + "fmt" + "os" + "os/exec" + + "github.com/sirupsen/logrus" +) + +// fsWipeBytes is how much of a partition is zeroed at each end to make its +// filesystem unrecoverable. Five MiB at the front covers ext4's primary +// superblock and its group descriptor table, which is what stops fsck +// recovering from a backup superblock; the same at the back mirrors the scrub +// EVE's own installer performs. +const fsWipeBytes = int64(5) << 20 + +// growDisk enlarges a QCOW2 disk to newSizeBytes and leaves the added space +// unallocated past the last partition. +// +// No partition is created or resized, but the partition table is not left +// alone: the backup GPT has to follow the end of the disk, or the added space +// is not usable. See relocateBackupGPT. +// +// The device must be powered off: qemu-img refuses to resize an image a +// running VM holds open, but only when that VM took a lock, so the caller +// checks rather than relying on it. +func growDisk(ctx context.Context, log *logrus.Entry, + diskPath string, newSizeBytes uint64) error { + current, err := diskVirtualSizeBytes(ctx, diskPath) + if err != nil { + return err + } + if int64(newSizeBytes) < current { + return fmt.Errorf( + "cannot grow disk %q to %d bytes: it is already %d bytes, and shrinking is not supported", + diskPath, newSizeBytes, current) + } + if int64(newSizeBytes) == current { + log.Infof("Disk %q is already %d bytes; nothing to grow", diskPath, current) + return nil + } + out, err := exec.CommandContext(ctx, "qemu-img", "resize", + "-f", "qcow2", diskPath, fmt.Sprintf("%d", newSizeBytes)).CombinedOutput() + if err != nil { + return fmt.Errorf("qemu-img resize of %q to %d bytes failed: %v: %s", + diskPath, newSizeBytes, err, out) + } + if err := relocateBackupGPT(ctx, log, diskPath); err != nil { + return err + } + log.Infof("Grew disk %q from %d to %d bytes (added space left unallocated)", + diskPath, current, newSizeBytes) + return nil +} + +// relocateBackupGPT moves the backup GPT to the new end of a disk that has just +// been grown, and extends the last-usable-LBA to match. +// +// Growing the image alone is not enough and leaves the disk worse than it +// started: the backup header stays where the old end was, the partition table +// still says the disk ends there, and the added space is not usable. EVE sees +// an inconsistent table -- a device given one has been observed rebooting under +// its own watchdog rather than failing outright, which is a slow way to find +// out. +// +// sgdisk cannot operate on a QCOW2, so the image is round-tripped through a raw +// copy, as eden does for the same job. That flattens a backing-file overlay +// into a standalone image, which costs space but nothing else: the device boots +// from this path either way. +func relocateBackupGPT(ctx context.Context, log *logrus.Entry, diskPath string) error { + raw := diskPath + ".gptfix.raw" + defer func() { _ = os.Remove(raw) }() + + steps := []struct { + what string + args []string + }{ + {"export to raw", []string{"qemu-img", "convert", "-f", "qcow2", "-O", "raw", diskPath, raw}}, + {"relocate the backup GPT", []string{"sgdisk", "-e", raw}}, + {"verify the partition table", []string{"sgdisk", "-v", raw}}, + {"import from raw", []string{"qemu-img", "convert", "-f", "raw", "-O", "qcow2", raw, diskPath}}, + } + for _, step := range steps { + out, err := exec.CommandContext(ctx, step.args[0], step.args[1:]...).CombinedOutput() + if err != nil { + return fmt.Errorf("could not %s for %q: %v: %s", step.what, diskPath, err, out) + } + } + log.Infof("Relocated the backup GPT of %q to the new end of the disk", diskPath) + return nil +} + +// destroyPartitionFilesystem makes the filesystem on the named GPT partition +// unrecoverable, so that EVE reformats it on the next boot. The partition +// table is deliberately left intact: that is the state a real filesystem loss +// leaves behind, and the partition still has to be found afterwards. +// +// The device must be powered off. +func destroyPartitionFilesystem(ctx context.Context, log *logrus.Entry, + diskPath, partitionLabel string) error { + head, err := readDiskHead(ctx, diskPath) + if err != nil { + return err + } + part, err := findGPTPartition(head, partitionLabel) + if err != nil { + return fmt.Errorf("cannot destroy the filesystem on partition %q of %q: %w", + partitionLabel, diskPath, err) + } + + // A partition too small to hold two separate wipe regions is zeroed whole, + // which is strictly more destructive and therefore still correct. + ranges := [][2]int64{} + if part.Length <= 2*fsWipeBytes { + ranges = append(ranges, [2]int64{part.Offset, part.Length}) + } else { + ranges = append(ranges, + [2]int64{part.Offset, fsWipeBytes}, + [2]int64{part.Offset + part.Length - fsWipeBytes, fsWipeBytes}) + } + for _, r := range ranges { + script := fmt.Sprintf("write -z %d %d", r[0], r[1]) + out, err := exec.CommandContext(ctx, "qemu-io", + "-f", "qcow2", "-c", script, diskPath).CombinedOutput() + if err != nil { + return fmt.Errorf("qemu-io zeroing %d bytes at offset %d of %q failed: %v: %s", + r[1], r[0], diskPath, err, out) + } + } + log.Infof("Destroyed the filesystem on partition %q (offset %d, length %d) of %q", + partitionLabel, part.Offset, part.Length, diskPath) + return nil +} + +// diskVirtualSizeBytes reports the virtual size of a QCOW2 disk. +func diskVirtualSizeBytes(ctx context.Context, diskPath string) (int64, error) { + out, err := exec.CommandContext(ctx, "qemu-img", "info", + "-f", "qcow2", "--output=json", diskPath).Output() + if err != nil { + return 0, fmt.Errorf("qemu-img info of %q failed: %w", diskPath, err) + } + var info struct { + VirtualSize int64 `json:"virtual-size"` + } + if err := json.Unmarshal(out, &info); err != nil { + return 0, fmt.Errorf("failed to parse qemu-img info output for %q: %w", diskPath, err) + } + if info.VirtualSize <= 0 { + return 0, fmt.Errorf("qemu-img info reported no virtual size for %q", diskPath) + } + return info.VirtualSize, nil +} diff --git a/evetest/devconfig.go b/evetest/devconfig.go index 32a2a2e1d37..4fe17753a9e 100644 --- a/evetest/devconfig.go +++ b/evetest/devconfig.go @@ -2515,15 +2515,26 @@ func (dc *EdgeDeviceConfig) deleteVolumeAndDeps(volUUID string) bool { if !found || contentTreeID == "" { return found } + dc.deleteContentTreeAndDeps(contentTreeID) + return true +} +// deleteContentTreeAndDeps removes the ContentTree with the given UUID and the +// Datastores it referenced. Reports whether the ContentTree was found. +func (dc *EdgeDeviceConfig) deleteContentTreeAndDeps(contentTreeID string) bool { var datastoreIDs []string + var found bool for i, contentTree := range dc.ContentInfo { if contentTree.Uuid == contentTreeID { datastoreIDs = append(datastoreIDs, contentTree.DsIdsList...) dc.ContentInfo = append(dc.ContentInfo[:i], dc.ContentInfo[i+1:]...) + found = true break } } + if !found { + return false + } for _, datastoreID := range datastoreIDs { for i, datastore := range dc.Datastores { if datastore.Id == datastoreID { @@ -2598,6 +2609,42 @@ func (dc *EdgeDeviceConfig) AddVolume( return volumeUUID } +// AddContentTree adds a ContentTree that no Volume and no application refers to, +// and returns its UUID. +// +// volumemgr downloads a ContentTree eagerly, so the image blobs land in the +// content-addressable store without a Volume, a PVC or a CDI import ever being +// created. A test whose subject is the blobs themselves -- that they survive an +// event, or that a later deployment reuses them instead of downloading again -- +// wants exactly that, since going through AddVolume would drag the storage +// pipeline into the result. +func (dc *EdgeDeviceConfig) AddContentTree( + displayName string, image ApplicationImageStorage) uuid.UUID { + contentTreeUUID := dc.th.newUUID("content tree") + datastoreUUID := dc.th.newUUID("content tree datastore") + contentTree, dsConfig := image.toProto(dc.th, dc.log, dc.DeviceName, + contentTreeUUID, datastoreUUID, displayName) + dc.ContentInfo = append(dc.ContentInfo, contentTree) + dc.Datastores = append(dc.Datastores, dsConfig) + return contentTreeUUID +} + +// DeleteContentTree removes a ContentTree added by AddContentTree, and the +// Datastore it referenced, from the device configuration. +func (dc *EdgeDeviceConfig) DeleteContentTree(contentTreeUUID uuid.UUID) { + uuidStr := contentTreeUUID.String() + for _, volume := range dc.Volumes { + if volume.GetOrigin().GetDownloadContentTreeID() == uuidStr { + dc.th.t.Fatalf( + "Cannot delete content tree %q: still referenced by volume %q", + uuidStr, volume.GetDisplayName()) + } + } + if !dc.deleteContentTreeAndDeps(uuidStr) { + dc.th.t.Fatalf("Content tree with UUID %q was not found", uuidStr) + } +} + // DeleteVolume removes a standalone volume (created via AddVolume or // AddBlankVolume) and its associated ContentTree/Datastore, if any, from the // device configuration. The volume must not currently be referenced by any diff --git a/evetest/edgedevice.go b/evetest/edgedevice.go index 7e51e6d1667..b8d3ce58069 100644 --- a/evetest/edgedevice.go +++ b/evetest/edgedevice.go @@ -462,6 +462,58 @@ func (t *BaseOSDatastoreType) FromString(s string) error { // revert), so the expected reboot count is incremented accordingly. func (d *EdgeDevice) UpgradeEVE(targetEVEVersion string, targetEVEHypervisor Hypervisor, datastoreType BaseOSDatastoreType, waitUntilUpgraded bool, expectRevert bool) { + outcome := upgradeSucceeds + if expectRevert { + outcome = upgradeReverts + } + d.upgradeEVE(targetEVEVersion, targetEVEHypervisor, datastoreType, + waitUntilUpgraded, outcome) +} + +// RequestRefusedEVEUpgrade applies a base-OS update that EVE is expected to +// reject outright, and returns as soon as the configuration is applied. +// +// A rejection is not a failed upgrade. EVE refuses in place -- before it writes +// a partition and before it reboots -- so there is nothing to wait for and no +// reboot to account for, which is what separates this from UpgradeEVE's +// expectRevert: that one waits out two reboots for an image that was installed +// and then rolled back. What the rejection looks like is the caller's to assert: +// the reported error, and that the device is still running what it was. +func (d *EdgeDevice) RequestRefusedEVEUpgrade(targetEVEVersion string, + targetEVEHypervisor Hypervisor, datastoreType BaseOSDatastoreType) { + d.upgradeEVE(targetEVEVersion, targetEVEHypervisor, datastoreType, + false, upgradeRefused) +} + +// upgradeOutcome is what the test expects EVE to do with a base-OS update. It +// decides how many reboots the harness books and what, if anything, it waits +// for. +type upgradeOutcome int + +const ( + // upgradeSucceeds: EVE installs the image and boots it. One reboot. + upgradeSucceeds upgradeOutcome = iota + // upgradeReverts: EVE installs the image, fails to confirm it, and rolls + // back. Two reboots -- one into the new image, one back. + upgradeReverts + // upgradeRefused: EVE rejects the update without installing it. No reboot. + upgradeRefused +) + +// expectedReboots is how many reboots an outcome causes. +func (o upgradeOutcome) expectedReboots() int { + switch o { + case upgradeReverts: + return 2 + case upgradeRefused: + return 0 + default: + return 1 + } +} + +func (d *EdgeDevice) upgradeEVE(targetEVEVersion string, targetEVEHypervisor Hypervisor, + datastoreType BaseOSDatastoreType, waitUntilUpgraded bool, outcome upgradeOutcome) { // Read current device arch (set during Setup). d.th.devicesM.Lock() @@ -493,7 +545,7 @@ func (d *EdgeDevice) UpgradeEVE(targetEVEVersion string, targetEVEHypervisor Hyp // honoured (and must be built locally) while an unset one means the newest. if datastoreType == BaseOSDatastoreHTTP && LocalLiveImageRequested() { d.upgradeEVEFromLocalBuild(targetEVEVersion, currentImageRef.Arch, - currentImageRef.Hypervisor, waitUntilUpgraded, expectRevert) + currentImageRef.Hypervisor, waitUntilUpgraded, outcome) return } @@ -547,7 +599,7 @@ func (d *EdgeDevice) UpgradeEVE(targetEVEVersion string, targetEVEHypervisor Hyp "Configuring EVE to pull rootfs %s from evetest's local OCI registry", imageName) config := d.GetConfig() config.SetBaseOS(dockerContainer, shortVersion) - d.applyUpgradeConfig(config, shortVersion, waitUntilUpgraded, expectRevert) + d.applyUpgradeConfig(config, shortVersion, waitUntilUpgraded, outcome) return } @@ -573,7 +625,7 @@ func (d *EdgeDevice) UpgradeEVE(targetEVEVersion string, targetEVEHypervisor Hyp } d.applyUpgradeOverHTTP(rootfsPath, rootfsFilename, shortVersion, - waitUntilUpgraded, expectRevert) + waitUntilUpgraded, outcome) } // upgradeEVEFromLocalBuild delivers an upgrade from a local build's own @@ -583,7 +635,7 @@ func (d *EdgeDevice) UpgradeEVE(targetEVEVersion string, targetEVEHypervisor Hyp // as it was built. func (d *EdgeDevice) upgradeEVEFromLocalBuild(targetEVEVersion string, arch api.ArchType, runningHypervisor api.HypervisorType, - waitUntilUpgraded, expectRevert bool) { + waitUntilUpgraded bool, outcome upgradeOutcome) { zarch, err := zarchDirName(arch) if err != nil { @@ -637,7 +689,7 @@ func (d *EdgeDevice) upgradeEVEFromLocalBuild(targetEVEVersion string, } d.applyUpgradeOverHTTP(rootfsPath, rootfsFilename, img.ShortVersion, - waitUntilUpgraded, expectRevert) + waitUntilUpgraded, outcome) } // applyUpgradeOverHTTP points the device's BaseOS config at a rootfs image @@ -645,7 +697,7 @@ func (d *EdgeDevice) upgradeEVEFromLocalBuild(targetEVEVersion string, // for the outcome. Shared by the two HTTP-serving transports (registry-pulled // and local-build): they differ only in how rootfsPath got there. func (d *EdgeDevice) applyUpgradeOverHTTP(rootfsPath, rootfsFilename, shortVersion string, - waitUntilUpgraded, expectRevert bool) { + waitUntilUpgraded bool, outcome upgradeOutcome) { sha256hex, fileSize, err := utils.FileHashAndSize(rootfsPath) if err != nil { @@ -663,20 +715,17 @@ func (d *EdgeDevice) applyUpgradeOverHTTP(rootfsPath, rootfsFilename, shortVersi ServerPort: GetImageServerPort(), }, shortVersion) - d.applyUpgradeConfig(config, shortVersion, waitUntilUpgraded, expectRevert) + d.applyUpgradeConfig(config, shortVersion, waitUntilUpgraded, outcome) } // applyUpgradeConfig applies an already-built upgrade device config and, // optionally, waits for the outcome. Shared by all datastore transports: // they differ only in how the BaseOS config gets built. func (d *EdgeDevice) applyUpgradeConfig(config *EdgeDeviceConfig, shortVersion string, - waitUntilUpgraded, expectRevert bool) { + waitUntilUpgraded bool, outcome upgradeOutcome) { d.th.log.Infof("Applying EVE upgrade config (target=%s)", shortVersion) - // A successful upgrade reboots once; a reverted upgrade reboots twice - // (once to try the new version, once to revert to the previous one). - d.th.incExpectedRebootCount(d.devName) - if expectRevert { + for i := 0; i < outcome.expectedReboots(); i++ { d.th.incExpectedRebootCount(d.devName) } d.th.devicesM.Lock() @@ -684,12 +733,16 @@ func (d *EdgeDevice) applyUpgradeConfig(config *EdgeDeviceConfig, shortVersion s d.th.devicesM.Unlock() d.ApplyConfig(config, false, false) - if waitUntilUpgraded { - if expectRevert { - d.waitForRevert(shortVersion) - } else { - d.waitForUpgrade(shortVersion) - } + if !waitUntilUpgraded { + return + } + switch outcome { + case upgradeReverts: + d.waitForRevert(shortVersion) + case upgradeRefused: + // Nothing to wait for: the caller asserts what the rejection looks like. + default: + d.waitForUpgrade(shortVersion) } } @@ -947,6 +1000,62 @@ func (d *EdgeDevice) PowerOn(waitUntilOnline bool) { }) } +// GrowDisk enlarges the device's boot disk to newSizeBytes, leaving the added +// space unallocated past the last partition rather than extending any +// partition into it. +// +// That free tail is the precondition for EVE's in-field repartition to grow +// into slack instead of shrinking /persist to make room, and it cannot be +// arranged at device creation: EVE's own image generator sizes the partitions +// to fill whatever disk it is given. +// +// The device must be powered off (PowerOff), and the test must have declared +// RequireCapabilities{CAPABILITY_EDIT_DEVICE_DISK}. +func (d *EdgeDevice) GrowDisk(newSizeBytes uint64) { + req := d.editDiskRequest() + req.Edit = &api.EditDeviceDiskRequest_Grow{ + Grow: &api.GrowDisk{NewSizeBytes: newSizeBytes}, + } + d.editDisk("GrowDisk", req) +} + +// DestroyPartitionFilesystem makes the filesystem on the named GPT partition +// (e.g. "P3", EVE's /persist) unrecoverable, so that EVE reformats it on the +// next boot. The partition table is left intact, which is the state a real +// filesystem loss leaves behind. +// +// The device must be powered off (PowerOff), and the test must have declared +// RequireCapabilities{CAPABILITY_EDIT_DEVICE_DISK}. +func (d *EdgeDevice) DestroyPartitionFilesystem(partitionLabel string) { + req := d.editDiskRequest() + req.Edit = &api.EditDeviceDiskRequest_DestroyPartitionFs{ + DestroyPartitionFs: &api.DestroyPartitionFilesystem{ + PartitionLabel: partitionLabel, + }, + } + d.editDisk("DestroyPartitionFilesystem", req) +} + +// editDiskRequest builds the addressing half of a disk-edit request; the +// caller fills in which edit it wants. +func (d *EdgeDevice) editDiskRequest() *api.EditDeviceDiskRequest { + return &api.EditDeviceDiskRequest{ + ClientId: d.th.brokerClientID, + DeviceName: d.devName, + } +} + +// editDisk sends one disk edit to the broker, failing the test if it is +// refused. caller names the exported method for the failure message. +func (d *EdgeDevice) editDisk(caller string, req *api.EditDeviceDiskRequest) { + ctx, cancel := context.WithTimeout(d.th.ctx, brokerEditDeviceDiskTimeout) + defer cancel() + if _, err := d.th.brokerClient.EditDeviceDisk(ctx, req); err != nil { + d.th.t.Fatalf("%s: broker failed to edit the disk of device %q: %v", + caller, d.devName, err) + } +} + // rebootAndWait executes triggerFn to initiate a device reboot and, if // wait is true, blocks until the device confirms the reboot by reporting // a ZInfoDevice.lastRebootTime strictly after the moment triggerFn was called. diff --git a/evetest/grpcapi/go/broker.pb.go b/evetest/grpcapi/go/broker.pb.go index 830486efc5d..8f4e93382cd 100644 --- a/evetest/grpcapi/go/broker.pb.go +++ b/evetest/grpcapi/go/broker.pb.go @@ -1463,6 +1463,242 @@ func (*DeviceControlResponse) Descriptor() ([]byte, []int) { return file_broker_proto_rawDescGZIP(), []int{23} } +// Request to edit a powered-off device's boot disk in place. +type EditDeviceDiskRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + ClientId string `protobuf:"bytes,1,opt,name=client_id,json=clientId,proto3" json:"client_id,omitempty"` + DeviceName string `protobuf:"bytes,2,opt,name=device_name,json=deviceName,proto3" json:"device_name,omitempty"` + // Types that are valid to be assigned to Edit: + // + // *EditDeviceDiskRequest_Grow + // *EditDeviceDiskRequest_DestroyPartitionFs + Edit isEditDeviceDiskRequest_Edit `protobuf_oneof:"edit"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *EditDeviceDiskRequest) Reset() { + *x = EditDeviceDiskRequest{} + mi := &file_broker_proto_msgTypes[24] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *EditDeviceDiskRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*EditDeviceDiskRequest) ProtoMessage() {} + +func (x *EditDeviceDiskRequest) ProtoReflect() protoreflect.Message { + mi := &file_broker_proto_msgTypes[24] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use EditDeviceDiskRequest.ProtoReflect.Descriptor instead. +func (*EditDeviceDiskRequest) Descriptor() ([]byte, []int) { + return file_broker_proto_rawDescGZIP(), []int{24} +} + +func (x *EditDeviceDiskRequest) GetClientId() string { + if x != nil { + return x.ClientId + } + return "" +} + +func (x *EditDeviceDiskRequest) GetDeviceName() string { + if x != nil { + return x.DeviceName + } + return "" +} + +func (x *EditDeviceDiskRequest) GetEdit() isEditDeviceDiskRequest_Edit { + if x != nil { + return x.Edit + } + return nil +} + +func (x *EditDeviceDiskRequest) GetGrow() *GrowDisk { + if x != nil { + if x, ok := x.Edit.(*EditDeviceDiskRequest_Grow); ok { + return x.Grow + } + } + return nil +} + +func (x *EditDeviceDiskRequest) GetDestroyPartitionFs() *DestroyPartitionFilesystem { + if x != nil { + if x, ok := x.Edit.(*EditDeviceDiskRequest_DestroyPartitionFs); ok { + return x.DestroyPartitionFs + } + } + return nil +} + +type isEditDeviceDiskRequest_Edit interface { + isEditDeviceDiskRequest_Edit() +} + +type EditDeviceDiskRequest_Grow struct { + Grow *GrowDisk `protobuf:"bytes,3,opt,name=grow,proto3,oneof"` +} + +type EditDeviceDiskRequest_DestroyPartitionFs struct { + DestroyPartitionFs *DestroyPartitionFilesystem `protobuf:"bytes,4,opt,name=destroy_partition_fs,json=destroyPartitionFs,proto3,oneof"` +} + +func (*EditDeviceDiskRequest_Grow) isEditDeviceDiskRequest_Edit() {} + +func (*EditDeviceDiskRequest_DestroyPartitionFs) isEditDeviceDiskRequest_Edit() {} + +// GrowDisk enlarges the device's boot disk without touching its partition +// table, so the added space is left unallocated past the last partition. That +// free tail is what a test needs to make EVE's in-field repartition grow into +// slack rather than shrink an existing partition to make room. +type GrowDisk struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Total size the disk should have afterwards. Must be larger than its + // current size; shrinking a disk is not supported. + NewSizeBytes uint64 `protobuf:"varint,1,opt,name=new_size_bytes,json=newSizeBytes,proto3" json:"new_size_bytes,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GrowDisk) Reset() { + *x = GrowDisk{} + mi := &file_broker_proto_msgTypes[25] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GrowDisk) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GrowDisk) ProtoMessage() {} + +func (x *GrowDisk) ProtoReflect() protoreflect.Message { + mi := &file_broker_proto_msgTypes[25] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GrowDisk.ProtoReflect.Descriptor instead. +func (*GrowDisk) Descriptor() ([]byte, []int) { + return file_broker_proto_rawDescGZIP(), []int{25} +} + +func (x *GrowDisk) GetNewSizeBytes() uint64 { + if x != nil { + return x.NewSizeBytes + } + return 0 +} + +// DestroyPartitionFilesystem makes the filesystem on one partition +// unrecoverable, so that EVE reformats it on the next boot. It is the +// fault-injection half of a data-loss test, and deliberately not a "delete the +// partition" operation: the partition table is left intact, which is the state +// a real filesystem loss leaves behind. +type DestroyPartitionFilesystem struct { + state protoimpl.MessageState `protogen:"open.v1"` + // GPT partition name, e.g. "P3" for EVE's /persist partition. + PartitionLabel string `protobuf:"bytes,1,opt,name=partition_label,json=partitionLabel,proto3" json:"partition_label,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DestroyPartitionFilesystem) Reset() { + *x = DestroyPartitionFilesystem{} + mi := &file_broker_proto_msgTypes[26] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DestroyPartitionFilesystem) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DestroyPartitionFilesystem) ProtoMessage() {} + +func (x *DestroyPartitionFilesystem) ProtoReflect() protoreflect.Message { + mi := &file_broker_proto_msgTypes[26] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DestroyPartitionFilesystem.ProtoReflect.Descriptor instead. +func (*DestroyPartitionFilesystem) Descriptor() ([]byte, []int) { + return file_broker_proto_rawDescGZIP(), []int{26} +} + +func (x *DestroyPartitionFilesystem) GetPartitionLabel() string { + if x != nil { + return x.PartitionLabel + } + return "" +} + +// Generic response to a disk edit. +type EditDeviceDiskResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *EditDeviceDiskResponse) Reset() { + *x = EditDeviceDiskResponse{} + mi := &file_broker_proto_msgTypes[27] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *EditDeviceDiskResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*EditDeviceDiskResponse) ProtoMessage() {} + +func (x *EditDeviceDiskResponse) ProtoReflect() protoreflect.Message { + mi := &file_broker_proto_msgTypes[27] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use EditDeviceDiskResponse.ProtoReflect.Descriptor instead. +func (*EditDeviceDiskResponse) Descriptor() ([]byte, []int) { + return file_broker_proto_rawDescGZIP(), []int{27} +} + // ConnectConsoleRequest carries data sent from the client to the broker // during a console session. type ConnectConsoleRequest struct { @@ -1478,7 +1714,7 @@ type ConnectConsoleRequest struct { func (x *ConnectConsoleRequest) Reset() { *x = ConnectConsoleRequest{} - mi := &file_broker_proto_msgTypes[24] + mi := &file_broker_proto_msgTypes[28] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1490,7 +1726,7 @@ func (x *ConnectConsoleRequest) String() string { func (*ConnectConsoleRequest) ProtoMessage() {} func (x *ConnectConsoleRequest) ProtoReflect() protoreflect.Message { - mi := &file_broker_proto_msgTypes[24] + mi := &file_broker_proto_msgTypes[28] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1503,7 +1739,7 @@ func (x *ConnectConsoleRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ConnectConsoleRequest.ProtoReflect.Descriptor instead. func (*ConnectConsoleRequest) Descriptor() ([]byte, []int) { - return file_broker_proto_rawDescGZIP(), []int{24} + return file_broker_proto_rawDescGZIP(), []int{28} } func (x *ConnectConsoleRequest) GetPayload() isConnectConsoleRequest_Payload { @@ -1565,7 +1801,7 @@ type ConnectConsoleResponse struct { func (x *ConnectConsoleResponse) Reset() { *x = ConnectConsoleResponse{} - mi := &file_broker_proto_msgTypes[25] + mi := &file_broker_proto_msgTypes[29] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1577,7 +1813,7 @@ func (x *ConnectConsoleResponse) String() string { func (*ConnectConsoleResponse) ProtoMessage() {} func (x *ConnectConsoleResponse) ProtoReflect() protoreflect.Message { - mi := &file_broker_proto_msgTypes[25] + mi := &file_broker_proto_msgTypes[29] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1590,7 +1826,7 @@ func (x *ConnectConsoleResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ConnectConsoleResponse.ProtoReflect.Descriptor instead. func (*ConnectConsoleResponse) Descriptor() ([]byte, []int) { - return file_broker_proto_rawDescGZIP(), []int{25} + return file_broker_proto_rawDescGZIP(), []int{29} } func (x *ConnectConsoleResponse) GetPayload() isConnectConsoleResponse_Payload { @@ -1736,7 +1972,19 @@ const file_broker_proto_rawDesc = "" + "\tclient_id\x18\x01 \x01(\tR\bclientId\x12\x1f\n" + "\vdevice_name\x18\x02 \x01(\tR\n" + "deviceName\"\x17\n" + - "\x15DeviceControlResponse\"~\n" + + "\x15DeviceControlResponse\"\xf5\x01\n" + + "\x15EditDeviceDiskRequest\x12\x1b\n" + + "\tclient_id\x18\x01 \x01(\tR\bclientId\x12\x1f\n" + + "\vdevice_name\x18\x02 \x01(\tR\n" + + "deviceName\x122\n" + + "\x04grow\x18\x03 \x01(\v2\x1c.org.lfedge.evetest.GrowDiskH\x00R\x04grow\x12b\n" + + "\x14destroy_partition_fs\x18\x04 \x01(\v2..org.lfedge.evetest.DestroyPartitionFilesystemH\x00R\x12destroyPartitionFsB\x06\n" + + "\x04edit\"0\n" + + "\bGrowDisk\x12$\n" + + "\x0enew_size_bytes\x18\x01 \x01(\x04R\fnewSizeBytes\"E\n" + + "\x1aDestroyPartitionFilesystem\x12'\n" + + "\x0fpartition_label\x18\x01 \x01(\tR\x0epartitionLabel\"\x18\n" + + "\x16EditDeviceDiskResponse\"~\n" + "\x15ConnectConsoleRequest\x12D\n" + "\aconnect\x18\x01 \x01(\v2(.org.lfedge.evetest.DeviceControlRequestH\x00R\aconnect\x12\x14\n" + "\x04data\x18\x02 \x01(\fH\x00R\x04dataB\t\n" + @@ -1744,7 +1992,7 @@ const file_broker_proto_rawDesc = "" + "\x16ConnectConsoleResponse\x12L\n" + "\rconnect_reply\x18\x01 \x01(\v2%.org.lfedge.evetest.ConsolePropertiesH\x00R\fconnectReply\x12\x14\n" + "\x04data\x18\x02 \x01(\fH\x00R\x04dataB\t\n" + - "\apayload2\xdc\v\n" + + "\apayload2\xc5\f\n" + "\x06Broker\x12R\n" + "\aConnect\x12\".org.lfedge.evetest.ConnectRequest\x1a#.org.lfedge.evetest.ConnectResponse\x12L\n" + "\x05Close\x12 .org.lfedge.evetest.CloseRequest\x1a!.org.lfedge.evetest.CloseResponse\x12U\n" + @@ -1759,7 +2007,8 @@ const file_broker_proto_rawDesc = "" + "\x0fTeardownDevices\x12*.org.lfedge.evetest.TeardownDevicesRequest\x1a+.org.lfedge.evetest.TeardownDevicesResponse\x12d\n" + "\rPowerOnDevice\x12(.org.lfedge.evetest.DeviceControlRequest\x1a).org.lfedge.evetest.DeviceControlResponse\x12e\n" + "\x0ePowerOffDevice\x12(.org.lfedge.evetest.DeviceControlRequest\x1a).org.lfedge.evetest.DeviceControlResponse\x12c\n" + - "\fRebootDevice\x12(.org.lfedge.evetest.DeviceControlRequest\x1a).org.lfedge.evetest.DeviceControlResponse\x12m\n" + + "\fRebootDevice\x12(.org.lfedge.evetest.DeviceControlRequest\x1a).org.lfedge.evetest.DeviceControlResponse\x12g\n" + + "\x0eEditDeviceDisk\x12).org.lfedge.evetest.EditDeviceDiskRequest\x1a*.org.lfedge.evetest.EditDeviceDiskResponse\x12m\n" + "\x16GetDeviceConsoleOutput\x12(.org.lfedge.evetest.DeviceControlRequest\x1a).org.lfedge.evetest.ConsoleOutputResponse\x12s\n" + "\x16ConnectConsoleToDevice\x12).org.lfedge.evetest.ConnectConsoleRequest\x1a*.org.lfedge.evetest.ConnectConsoleResponse(\x010\x01\x12w\n" + "\x12ConnectTunnelToSDN\x12-.org.lfedge.evetest.ConnectTunnelToSDNRequest\x1a..org.lfedge.evetest.ConnectTunnelToSDNResponse(\x010\x01B+Z)github.com/lf-edge/eve/evetest/grpcapi/gob\x06proto3" @@ -1776,7 +2025,7 @@ func file_broker_proto_rawDescGZIP() []byte { return file_broker_proto_rawDescData } -var file_broker_proto_msgTypes = make([]protoimpl.MessageInfo, 26) +var file_broker_proto_msgTypes = make([]protoimpl.MessageInfo, 30) var file_broker_proto_goTypes = []any{ (*ConnectRequest)(nil), // 0: org.lfedge.evetest.ConnectRequest (*ConnectResponse)(nil), // 1: org.lfedge.evetest.ConnectResponse @@ -1802,71 +2051,79 @@ var file_broker_proto_goTypes = []any{ (*TeardownDevicesResponse)(nil), // 21: org.lfedge.evetest.TeardownDevicesResponse (*DeviceControlRequest)(nil), // 22: org.lfedge.evetest.DeviceControlRequest (*DeviceControlResponse)(nil), // 23: org.lfedge.evetest.DeviceControlResponse - (*ConnectConsoleRequest)(nil), // 24: org.lfedge.evetest.ConnectConsoleRequest - (*ConnectConsoleResponse)(nil), // 25: org.lfedge.evetest.ConnectConsoleResponse - (ArchType)(0), // 26: org.lfedge.evetest.ArchType - (Capability)(0), // 27: org.lfedge.evetest.Capability - (*ImageRef)(nil), // 28: org.lfedge.evetest.ImageRef - (*LiveImageRef)(nil), // 29: org.lfedge.evetest.LiveImageRef - (*EVEDevice)(nil), // 30: org.lfedge.evetest.EVEDevice - (*SDNConfig)(nil), // 31: org.lfedge.evetest.SDNConfig - (*ConsoleProperties)(nil), // 32: org.lfedge.evetest.ConsoleProperties - (*ConnectTunnelToSDNRequest)(nil), // 33: org.lfedge.evetest.ConnectTunnelToSDNRequest - (*LogMessage)(nil), // 34: org.lfedge.evetest.LogMessage - (*ConsoleOutputResponse)(nil), // 35: org.lfedge.evetest.ConsoleOutputResponse - (*ConnectTunnelToSDNResponse)(nil), // 36: org.lfedge.evetest.ConnectTunnelToSDNResponse + (*EditDeviceDiskRequest)(nil), // 24: org.lfedge.evetest.EditDeviceDiskRequest + (*GrowDisk)(nil), // 25: org.lfedge.evetest.GrowDisk + (*DestroyPartitionFilesystem)(nil), // 26: org.lfedge.evetest.DestroyPartitionFilesystem + (*EditDeviceDiskResponse)(nil), // 27: org.lfedge.evetest.EditDeviceDiskResponse + (*ConnectConsoleRequest)(nil), // 28: org.lfedge.evetest.ConnectConsoleRequest + (*ConnectConsoleResponse)(nil), // 29: org.lfedge.evetest.ConnectConsoleResponse + (ArchType)(0), // 30: org.lfedge.evetest.ArchType + (Capability)(0), // 31: org.lfedge.evetest.Capability + (*ImageRef)(nil), // 32: org.lfedge.evetest.ImageRef + (*LiveImageRef)(nil), // 33: org.lfedge.evetest.LiveImageRef + (*EVEDevice)(nil), // 34: org.lfedge.evetest.EVEDevice + (*SDNConfig)(nil), // 35: org.lfedge.evetest.SDNConfig + (*ConsoleProperties)(nil), // 36: org.lfedge.evetest.ConsoleProperties + (*ConnectTunnelToSDNRequest)(nil), // 37: org.lfedge.evetest.ConnectTunnelToSDNRequest + (*LogMessage)(nil), // 38: org.lfedge.evetest.LogMessage + (*ConsoleOutputResponse)(nil), // 39: org.lfedge.evetest.ConsoleOutputResponse + (*ConnectTunnelToSDNResponse)(nil), // 40: org.lfedge.evetest.ConnectTunnelToSDNResponse } var file_broker_proto_depIdxs = []int32{ - 26, // 0: org.lfedge.evetest.ConnectResponse.supported_archs:type_name -> org.lfedge.evetest.ArchType - 27, // 1: org.lfedge.evetest.ConnectResponse.provider_capabilities:type_name -> org.lfedge.evetest.Capability + 30, // 0: org.lfedge.evetest.ConnectResponse.supported_archs:type_name -> org.lfedge.evetest.ArchType + 31, // 1: org.lfedge.evetest.ConnectResponse.provider_capabilities:type_name -> org.lfedge.evetest.Capability 2, // 2: org.lfedge.evetest.ConnectResponse.registry_mirrors:type_name -> org.lfedge.evetest.RegistryMirror - 28, // 3: org.lfedge.evetest.BuildImageRequest.image:type_name -> org.lfedge.evetest.ImageRef + 32, // 3: org.lfedge.evetest.BuildImageRequest.image:type_name -> org.lfedge.evetest.ImageRef 8, // 4: org.lfedge.evetest.BuildImageRequest.config:type_name -> org.lfedge.evetest.EveConfig - 29, // 5: org.lfedge.evetest.BuildImageRequest.live_image:type_name -> org.lfedge.evetest.LiveImageRef + 33, // 5: org.lfedge.evetest.BuildImageRequest.live_image:type_name -> org.lfedge.evetest.LiveImageRef 10, // 6: org.lfedge.evetest.BuildImageRequest.live_image_source:type_name -> org.lfedge.evetest.LocalLiveImageSource 13, // 7: org.lfedge.evetest.PushImageChunk.request:type_name -> org.lfedge.evetest.PushImageRequest - 28, // 8: org.lfedge.evetest.PushImageRequest.image:type_name -> org.lfedge.evetest.ImageRef + 32, // 8: org.lfedge.evetest.PushImageRequest.image:type_name -> org.lfedge.evetest.ImageRef 16, // 9: org.lfedge.evetest.PushLiveImageChunk.request:type_name -> org.lfedge.evetest.PushLiveImageRequest - 29, // 10: org.lfedge.evetest.PushLiveImageRequest.live_image:type_name -> org.lfedge.evetest.LiveImageRef - 30, // 11: org.lfedge.evetest.SetupDevicesRequest.devices:type_name -> org.lfedge.evetest.EVEDevice - 31, // 12: org.lfedge.evetest.SetupDevicesRequest.sdn_config:type_name -> org.lfedge.evetest.SDNConfig - 22, // 13: org.lfedge.evetest.ConnectConsoleRequest.connect:type_name -> org.lfedge.evetest.DeviceControlRequest - 32, // 14: org.lfedge.evetest.ConnectConsoleResponse.connect_reply:type_name -> org.lfedge.evetest.ConsoleProperties - 0, // 15: org.lfedge.evetest.Broker.Connect:input_type -> org.lfedge.evetest.ConnectRequest - 3, // 16: org.lfedge.evetest.Broker.Close:input_type -> org.lfedge.evetest.CloseRequest - 5, // 17: org.lfedge.evetest.Broker.KeepAlive:input_type -> org.lfedge.evetest.KeepAlivePing - 7, // 18: org.lfedge.evetest.Broker.StreamLogs:input_type -> org.lfedge.evetest.LogsRequest - 9, // 19: org.lfedge.evetest.Broker.BuildImage:input_type -> org.lfedge.evetest.BuildImageRequest - 12, // 20: org.lfedge.evetest.Broker.PushEVEContainerImage:input_type -> org.lfedge.evetest.PushImageChunk - 15, // 21: org.lfedge.evetest.Broker.PushEVELiveImage:input_type -> org.lfedge.evetest.PushLiveImageChunk - 18, // 22: org.lfedge.evetest.Broker.SetupDevices:input_type -> org.lfedge.evetest.SetupDevicesRequest - 20, // 23: org.lfedge.evetest.Broker.TeardownDevices:input_type -> org.lfedge.evetest.TeardownDevicesRequest - 22, // 24: org.lfedge.evetest.Broker.PowerOnDevice:input_type -> org.lfedge.evetest.DeviceControlRequest - 22, // 25: org.lfedge.evetest.Broker.PowerOffDevice:input_type -> org.lfedge.evetest.DeviceControlRequest - 22, // 26: org.lfedge.evetest.Broker.RebootDevice:input_type -> org.lfedge.evetest.DeviceControlRequest - 22, // 27: org.lfedge.evetest.Broker.GetDeviceConsoleOutput:input_type -> org.lfedge.evetest.DeviceControlRequest - 24, // 28: org.lfedge.evetest.Broker.ConnectConsoleToDevice:input_type -> org.lfedge.evetest.ConnectConsoleRequest - 33, // 29: org.lfedge.evetest.Broker.ConnectTunnelToSDN:input_type -> org.lfedge.evetest.ConnectTunnelToSDNRequest - 1, // 30: org.lfedge.evetest.Broker.Connect:output_type -> org.lfedge.evetest.ConnectResponse - 4, // 31: org.lfedge.evetest.Broker.Close:output_type -> org.lfedge.evetest.CloseResponse - 6, // 32: org.lfedge.evetest.Broker.KeepAlive:output_type -> org.lfedge.evetest.KeepAlivePong - 34, // 33: org.lfedge.evetest.Broker.StreamLogs:output_type -> org.lfedge.evetest.LogMessage - 11, // 34: org.lfedge.evetest.Broker.BuildImage:output_type -> org.lfedge.evetest.BuildImageResponse - 14, // 35: org.lfedge.evetest.Broker.PushEVEContainerImage:output_type -> org.lfedge.evetest.PushImageResponse - 17, // 36: org.lfedge.evetest.Broker.PushEVELiveImage:output_type -> org.lfedge.evetest.PushLiveImageResponse - 19, // 37: org.lfedge.evetest.Broker.SetupDevices:output_type -> org.lfedge.evetest.SetupDevicesResponse - 21, // 38: org.lfedge.evetest.Broker.TeardownDevices:output_type -> org.lfedge.evetest.TeardownDevicesResponse - 23, // 39: org.lfedge.evetest.Broker.PowerOnDevice:output_type -> org.lfedge.evetest.DeviceControlResponse - 23, // 40: org.lfedge.evetest.Broker.PowerOffDevice:output_type -> org.lfedge.evetest.DeviceControlResponse - 23, // 41: org.lfedge.evetest.Broker.RebootDevice:output_type -> org.lfedge.evetest.DeviceControlResponse - 35, // 42: org.lfedge.evetest.Broker.GetDeviceConsoleOutput:output_type -> org.lfedge.evetest.ConsoleOutputResponse - 25, // 43: org.lfedge.evetest.Broker.ConnectConsoleToDevice:output_type -> org.lfedge.evetest.ConnectConsoleResponse - 36, // 44: org.lfedge.evetest.Broker.ConnectTunnelToSDN:output_type -> org.lfedge.evetest.ConnectTunnelToSDNResponse - 30, // [30:45] is the sub-list for method output_type - 15, // [15:30] is the sub-list for method input_type - 15, // [15:15] is the sub-list for extension type_name - 15, // [15:15] is the sub-list for extension extendee - 0, // [0:15] is the sub-list for field type_name + 33, // 10: org.lfedge.evetest.PushLiveImageRequest.live_image:type_name -> org.lfedge.evetest.LiveImageRef + 34, // 11: org.lfedge.evetest.SetupDevicesRequest.devices:type_name -> org.lfedge.evetest.EVEDevice + 35, // 12: org.lfedge.evetest.SetupDevicesRequest.sdn_config:type_name -> org.lfedge.evetest.SDNConfig + 25, // 13: org.lfedge.evetest.EditDeviceDiskRequest.grow:type_name -> org.lfedge.evetest.GrowDisk + 26, // 14: org.lfedge.evetest.EditDeviceDiskRequest.destroy_partition_fs:type_name -> org.lfedge.evetest.DestroyPartitionFilesystem + 22, // 15: org.lfedge.evetest.ConnectConsoleRequest.connect:type_name -> org.lfedge.evetest.DeviceControlRequest + 36, // 16: org.lfedge.evetest.ConnectConsoleResponse.connect_reply:type_name -> org.lfedge.evetest.ConsoleProperties + 0, // 17: org.lfedge.evetest.Broker.Connect:input_type -> org.lfedge.evetest.ConnectRequest + 3, // 18: org.lfedge.evetest.Broker.Close:input_type -> org.lfedge.evetest.CloseRequest + 5, // 19: org.lfedge.evetest.Broker.KeepAlive:input_type -> org.lfedge.evetest.KeepAlivePing + 7, // 20: org.lfedge.evetest.Broker.StreamLogs:input_type -> org.lfedge.evetest.LogsRequest + 9, // 21: org.lfedge.evetest.Broker.BuildImage:input_type -> org.lfedge.evetest.BuildImageRequest + 12, // 22: org.lfedge.evetest.Broker.PushEVEContainerImage:input_type -> org.lfedge.evetest.PushImageChunk + 15, // 23: org.lfedge.evetest.Broker.PushEVELiveImage:input_type -> org.lfedge.evetest.PushLiveImageChunk + 18, // 24: org.lfedge.evetest.Broker.SetupDevices:input_type -> org.lfedge.evetest.SetupDevicesRequest + 20, // 25: org.lfedge.evetest.Broker.TeardownDevices:input_type -> org.lfedge.evetest.TeardownDevicesRequest + 22, // 26: org.lfedge.evetest.Broker.PowerOnDevice:input_type -> org.lfedge.evetest.DeviceControlRequest + 22, // 27: org.lfedge.evetest.Broker.PowerOffDevice:input_type -> org.lfedge.evetest.DeviceControlRequest + 22, // 28: org.lfedge.evetest.Broker.RebootDevice:input_type -> org.lfedge.evetest.DeviceControlRequest + 24, // 29: org.lfedge.evetest.Broker.EditDeviceDisk:input_type -> org.lfedge.evetest.EditDeviceDiskRequest + 22, // 30: org.lfedge.evetest.Broker.GetDeviceConsoleOutput:input_type -> org.lfedge.evetest.DeviceControlRequest + 28, // 31: org.lfedge.evetest.Broker.ConnectConsoleToDevice:input_type -> org.lfedge.evetest.ConnectConsoleRequest + 37, // 32: org.lfedge.evetest.Broker.ConnectTunnelToSDN:input_type -> org.lfedge.evetest.ConnectTunnelToSDNRequest + 1, // 33: org.lfedge.evetest.Broker.Connect:output_type -> org.lfedge.evetest.ConnectResponse + 4, // 34: org.lfedge.evetest.Broker.Close:output_type -> org.lfedge.evetest.CloseResponse + 6, // 35: org.lfedge.evetest.Broker.KeepAlive:output_type -> org.lfedge.evetest.KeepAlivePong + 38, // 36: org.lfedge.evetest.Broker.StreamLogs:output_type -> org.lfedge.evetest.LogMessage + 11, // 37: org.lfedge.evetest.Broker.BuildImage:output_type -> org.lfedge.evetest.BuildImageResponse + 14, // 38: org.lfedge.evetest.Broker.PushEVEContainerImage:output_type -> org.lfedge.evetest.PushImageResponse + 17, // 39: org.lfedge.evetest.Broker.PushEVELiveImage:output_type -> org.lfedge.evetest.PushLiveImageResponse + 19, // 40: org.lfedge.evetest.Broker.SetupDevices:output_type -> org.lfedge.evetest.SetupDevicesResponse + 21, // 41: org.lfedge.evetest.Broker.TeardownDevices:output_type -> org.lfedge.evetest.TeardownDevicesResponse + 23, // 42: org.lfedge.evetest.Broker.PowerOnDevice:output_type -> org.lfedge.evetest.DeviceControlResponse + 23, // 43: org.lfedge.evetest.Broker.PowerOffDevice:output_type -> org.lfedge.evetest.DeviceControlResponse + 23, // 44: org.lfedge.evetest.Broker.RebootDevice:output_type -> org.lfedge.evetest.DeviceControlResponse + 27, // 45: org.lfedge.evetest.Broker.EditDeviceDisk:output_type -> org.lfedge.evetest.EditDeviceDiskResponse + 39, // 46: org.lfedge.evetest.Broker.GetDeviceConsoleOutput:output_type -> org.lfedge.evetest.ConsoleOutputResponse + 29, // 47: org.lfedge.evetest.Broker.ConnectConsoleToDevice:output_type -> org.lfedge.evetest.ConnectConsoleResponse + 40, // 48: org.lfedge.evetest.Broker.ConnectTunnelToSDN:output_type -> org.lfedge.evetest.ConnectTunnelToSDNResponse + 33, // [33:49] is the sub-list for method output_type + 17, // [17:33] is the sub-list for method input_type + 17, // [17:17] is the sub-list for extension type_name + 17, // [17:17] is the sub-list for extension extendee + 0, // [0:17] is the sub-list for field type_name } func init() { file_broker_proto_init() } @@ -1885,10 +2142,14 @@ func file_broker_proto_init() { (*PushLiveImageChunk_DataChunk)(nil), } file_broker_proto_msgTypes[24].OneofWrappers = []any{ + (*EditDeviceDiskRequest_Grow)(nil), + (*EditDeviceDiskRequest_DestroyPartitionFs)(nil), + } + file_broker_proto_msgTypes[28].OneofWrappers = []any{ (*ConnectConsoleRequest_Connect)(nil), (*ConnectConsoleRequest_Data)(nil), } - file_broker_proto_msgTypes[25].OneofWrappers = []any{ + file_broker_proto_msgTypes[29].OneofWrappers = []any{ (*ConnectConsoleResponse_ConnectReply)(nil), (*ConnectConsoleResponse_Data)(nil), } @@ -1898,7 +2159,7 @@ func file_broker_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_broker_proto_rawDesc), len(file_broker_proto_rawDesc)), NumEnums: 0, - NumMessages: 26, + NumMessages: 30, NumExtensions: 0, NumServices: 1, }, diff --git a/evetest/grpcapi/go/broker_grpc.pb.go b/evetest/grpcapi/go/broker_grpc.pb.go index 9241cd62698..e5efdc9c4c6 100644 --- a/evetest/grpcapi/go/broker_grpc.pb.go +++ b/evetest/grpcapi/go/broker_grpc.pb.go @@ -34,6 +34,7 @@ const ( Broker_PowerOnDevice_FullMethodName = "/org.lfedge.evetest.Broker/PowerOnDevice" Broker_PowerOffDevice_FullMethodName = "/org.lfedge.evetest.Broker/PowerOffDevice" Broker_RebootDevice_FullMethodName = "/org.lfedge.evetest.Broker/RebootDevice" + Broker_EditDeviceDisk_FullMethodName = "/org.lfedge.evetest.Broker/EditDeviceDisk" Broker_GetDeviceConsoleOutput_FullMethodName = "/org.lfedge.evetest.Broker/GetDeviceConsoleOutput" Broker_ConnectConsoleToDevice_FullMethodName = "/org.lfedge.evetest.Broker/ConnectConsoleToDevice" Broker_ConnectTunnelToSDN_FullMethodName = "/org.lfedge.evetest.Broker/ConnectTunnelToSDN" @@ -75,6 +76,9 @@ type BrokerClient interface { PowerOffDevice(ctx context.Context, in *DeviceControlRequest, opts ...grpc.CallOption) (*DeviceControlResponse, error) // Reboot a specific EVE device. RebootDevice(ctx context.Context, in *DeviceControlRequest, opts ...grpc.CallOption) (*DeviceControlResponse, error) + // Edit a powered-off device's boot disk in place. Requires + // CAPABILITY_EDIT_DEVICE_DISK. + EditDeviceDisk(ctx context.Context, in *EditDeviceDiskRequest, opts ...grpc.CallOption) (*EditDeviceDiskResponse, error) // Get the console output from the device. GetDeviceConsoleOutput(ctx context.Context, in *DeviceControlRequest, opts ...grpc.CallOption) (*ConsoleOutputResponse, error) // ConnectConsoleToDevice establishes a bidirectional gRPC tunnel between @@ -240,6 +244,16 @@ func (c *brokerClient) RebootDevice(ctx context.Context, in *DeviceControlReques return out, nil } +func (c *brokerClient) EditDeviceDisk(ctx context.Context, in *EditDeviceDiskRequest, opts ...grpc.CallOption) (*EditDeviceDiskResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(EditDeviceDiskResponse) + err := c.cc.Invoke(ctx, Broker_EditDeviceDisk_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *brokerClient) GetDeviceConsoleOutput(ctx context.Context, in *DeviceControlRequest, opts ...grpc.CallOption) (*ConsoleOutputResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(ConsoleOutputResponse) @@ -312,6 +326,9 @@ type BrokerServer interface { PowerOffDevice(context.Context, *DeviceControlRequest) (*DeviceControlResponse, error) // Reboot a specific EVE device. RebootDevice(context.Context, *DeviceControlRequest) (*DeviceControlResponse, error) + // Edit a powered-off device's boot disk in place. Requires + // CAPABILITY_EDIT_DEVICE_DISK. + EditDeviceDisk(context.Context, *EditDeviceDiskRequest) (*EditDeviceDiskResponse, error) // Get the console output from the device. GetDeviceConsoleOutput(context.Context, *DeviceControlRequest) (*ConsoleOutputResponse, error) // ConnectConsoleToDevice establishes a bidirectional gRPC tunnel between @@ -375,6 +392,9 @@ func (UnimplementedBrokerServer) PowerOffDevice(context.Context, *DeviceControlR func (UnimplementedBrokerServer) RebootDevice(context.Context, *DeviceControlRequest) (*DeviceControlResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method RebootDevice not implemented") } +func (UnimplementedBrokerServer) EditDeviceDisk(context.Context, *EditDeviceDiskRequest) (*EditDeviceDiskResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method EditDeviceDisk not implemented") +} func (UnimplementedBrokerServer) GetDeviceConsoleOutput(context.Context, *DeviceControlRequest) (*ConsoleOutputResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method GetDeviceConsoleOutput not implemented") } @@ -581,6 +601,24 @@ func _Broker_RebootDevice_Handler(srv interface{}, ctx context.Context, dec func return interceptor(ctx, in, info, handler) } +func _Broker_EditDeviceDisk_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(EditDeviceDiskRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(BrokerServer).EditDeviceDisk(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Broker_EditDeviceDisk_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(BrokerServer).EditDeviceDisk(ctx, req.(*EditDeviceDiskRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _Broker_GetDeviceConsoleOutput_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DeviceControlRequest) if err := dec(in); err != nil { @@ -652,6 +690,10 @@ var Broker_ServiceDesc = grpc.ServiceDesc{ MethodName: "RebootDevice", Handler: _Broker_RebootDevice_Handler, }, + { + MethodName: "EditDeviceDisk", + Handler: _Broker_EditDeviceDisk_Handler, + }, { MethodName: "GetDeviceConsoleOutput", Handler: _Broker_GetDeviceConsoleOutput_Handler, diff --git a/evetest/grpcapi/go/common.pb.go b/evetest/grpcapi/go/common.pb.go index a025ce71c1b..918d4b0cb32 100644 --- a/evetest/grpcapi/go/common.pb.go +++ b/evetest/grpcapi/go/common.pb.go @@ -162,6 +162,11 @@ const ( // firmware only falls through to network when the disk has nothing // bootable. Capability_CAPABILITY_NETBOOT Capability = 6 + // Editing a powered-off device's boot disk in place: growing it, or + // destroying the filesystem on one of its partitions. Requires a provider + // that keeps the disk as a file it can still reach after setup, so a + // provider that hands the image to a remote node does not have it. + Capability_CAPABILITY_EDIT_DEVICE_DISK Capability = 7 ) // Enum value maps for Capability. @@ -174,6 +179,7 @@ var ( 4: "CAPABILITY_TPM", 5: "CAPABILITY_LOCAL_LIVE_IMAGE", 6: "CAPABILITY_NETBOOT", + 7: "CAPABILITY_EDIT_DEVICE_DISK", } Capability_value = map[string]int32{ "CAPABILITY_UNSPECIFIED": 0, @@ -183,6 +189,7 @@ var ( "CAPABILITY_TPM": 4, "CAPABILITY_LOCAL_LIVE_IMAGE": 5, "CAPABILITY_NETBOOT": 6, + "CAPABILITY_EDIT_DEVICE_DISK": 7, } ) @@ -1071,7 +1078,7 @@ const file_common_proto_rawDesc = "" + "\x06HV_KVM\x10\x01\x12\n" + "\n" + "\x06HV_XEN\x10\x02\x12\x0f\n" + - "\vHV_KUBEVIRT\x10\x03*\xcd\x01\n" + + "\vHV_KUBEVIRT\x10\x03*\xee\x01\n" + "\n" + "Capability\x12\x1a\n" + "\x16CAPABILITY_UNSPECIFIED\x10\x00\x12\x1b\n" + @@ -1080,7 +1087,8 @@ const file_common_proto_rawDesc = "" + "\x17CAPABILITY_FORWARD_LLDP\x10\x03\x12\x12\n" + "\x0eCAPABILITY_TPM\x10\x04\x12\x1f\n" + "\x1bCAPABILITY_LOCAL_LIVE_IMAGE\x10\x05\x12\x16\n" + - "\x12CAPABILITY_NETBOOT\x10\x06*g\n" + + "\x12CAPABILITY_NETBOOT\x10\x06\x12\x1f\n" + + "\x1bCAPABILITY_EDIT_DEVICE_DISK\x10\a*g\n" + "\vLogSeverity\x12\x0f\n" + "\vLOG_UNKNOWN\x10\x00\x12\r\n" + "\tLOG_DEBUG\x10\x01\x12\f\n" + diff --git a/evetest/grpcapi/proto/broker.proto b/evetest/grpcapi/proto/broker.proto index d5840c2d45e..4bbe32da396 100644 --- a/evetest/grpcapi/proto/broker.proto +++ b/evetest/grpcapi/proto/broker.proto @@ -46,6 +46,10 @@ service Broker { // Reboot a specific EVE device. rpc RebootDevice(DeviceControlRequest) returns (DeviceControlResponse); + // Edit a powered-off device's boot disk in place. Requires + // CAPABILITY_EDIT_DEVICE_DISK. + rpc EditDeviceDisk(EditDeviceDiskRequest) returns (EditDeviceDiskResponse); + // Get the console output from the device. rpc GetDeviceConsoleOutput(DeviceControlRequest) returns (ConsoleOutputResponse); // ConnectConsoleToDevice establishes a bidirectional gRPC tunnel between @@ -268,6 +272,39 @@ message DeviceControlRequest { // Generic response to a device control operation. message DeviceControlResponse {} +// Request to edit a powered-off device's boot disk in place. +message EditDeviceDiskRequest { + string client_id = 1; + string device_name = 2; + oneof edit { + GrowDisk grow = 3; + DestroyPartitionFilesystem destroy_partition_fs = 4; + } +} + +// GrowDisk enlarges the device's boot disk without touching its partition +// table, so the added space is left unallocated past the last partition. That +// free tail is what a test needs to make EVE's in-field repartition grow into +// slack rather than shrink an existing partition to make room. +message GrowDisk { + // Total size the disk should have afterwards. Must be larger than its + // current size; shrinking a disk is not supported. + uint64 new_size_bytes = 1; +} + +// DestroyPartitionFilesystem makes the filesystem on one partition +// unrecoverable, so that EVE reformats it on the next boot. It is the +// fault-injection half of a data-loss test, and deliberately not a "delete the +// partition" operation: the partition table is left intact, which is the state +// a real filesystem loss leaves behind. +message DestroyPartitionFilesystem { + // GPT partition name, e.g. "P3" for EVE's /persist partition. + string partition_label = 1; +} + +// Generic response to a disk edit. +message EditDeviceDiskResponse {} + // ConnectConsoleRequest carries data sent from the client to the broker // during a console session. message ConnectConsoleRequest { diff --git a/evetest/grpcapi/proto/common.proto b/evetest/grpcapi/proto/common.proto index 38688a4ec69..acc33307344 100644 --- a/evetest/grpcapi/proto/common.proto +++ b/evetest/grpcapi/proto/common.proto @@ -56,6 +56,11 @@ enum Capability { // firmware only falls through to network when the disk has nothing // bootable. CAPABILITY_NETBOOT = 6; + // Editing a powered-off device's boot disk in place: growing it, or + // destroying the filesystem on one of its partitions. Requires a provider + // that keeps the disk as a file it can still reach after setup, so a + // provider that hands the image to a remote node does not have it. + CAPABILITY_EDIT_DEVICE_DISK = 7; } // Reference to a specific EVE image used for provisioning or testing. diff --git a/evetest/harness.go b/evetest/harness.go index ca56f093965..49deaedb2b3 100644 --- a/evetest/harness.go +++ b/evetest/harness.go @@ -80,6 +80,9 @@ const ( // provider confirms the VM is stopped, so this must accommodate a // graceful ACPI-less hard power-off, not just issuing the request. brokerPowerOffEVEDeviceTimeout = time.Minute + // Editing a disk rewrites megabytes through qemu-img/qemu-io on a + // possibly busy host, so it gets more room than a power operation. + brokerEditDeviceDiskTimeout = 5 * time.Minute // Timeout for triggering an EVE VM reboot (not for waiting for it to boot). brokerRebootEVEDeviceTimeout = time.Minute diff --git a/evetest/testparam.go b/evetest/testparam.go index 09f1a4252c0..f30a28b7a89 100644 --- a/evetest/testparam.go +++ b/evetest/testparam.go @@ -325,3 +325,47 @@ func TPMParameter() TestParameterDefinition { func GetTPMParameterValue() (useTPM bool) { return GetTestParameter[bool](TPMParameterKey) } + +// RAMSizeMiBParameterKey is the key used for the RAMSizeMiB parameter. +const RAMSizeMiBParameterKey = "RAM_SIZE_MB" + +// RAMSizeMiBParameter is a predefined TestParameterDefinition for the device RAM size. +// A value of 0 means the framework default (8192 MiB) is used, unless the test +// raises it to a floor of its own. +func RAMSizeMiBParameter() TestParameterDefinition { + return TestParameterDefinition{ + Key: RAMSizeMiBParameterKey, + DefaultValue: uint32(0), + Description: TestParameterDescription{ + Summary: "Device RAM size in MiB", + Default: "0 (use framework default 8192 MiB)", + }, + } +} + +// GetRAMSizeMiBParameterValue returns the value set for the RAMSizeMiB parameter. +func GetRAMSizeMiBParameterValue() uint32 { + return GetTestParameter[uint32](RAMSizeMiBParameterKey) +} + +// CPUsParameterKey is the key used for the CPUs parameter. +const CPUsParameterKey = "CPUS" + +// CPUsParameter is a predefined TestParameterDefinition for the device vCPU count. +// A value of 0 means the framework default (4 vCPUs) is used, unless the test +// raises it to a floor of its own. +func CPUsParameter() TestParameterDefinition { + return TestParameterDefinition{ + Key: CPUsParameterKey, + DefaultValue: uint8(0), + Description: TestParameterDescription{ + Summary: "Number of virtual CPUs for the EVE device", + Default: "0 (use framework default 4 vCPUs)", + }, + } +} + +// GetCPUsParameterValue returns the value set for the CPUs parameter. +func GetCPUsParameterValue() uint8 { + return GetTestParameter[uint8](CPUsParameterKey) +} From e13e48b63f90f3c5f556541f9b5b37ad45831200 Mon Sep 17 00:00:00 2001 From: eriknordmark Date: Wed, 9 Sep 2026 22:59:01 +0200 Subject: [PATCH 02/10] evetest: cross-flavor EVE-kvm to EVE-K upgrade test A base-OS update that changes hypervisor flavor is normally refused: /persist is laid out differently for EVE-K, so baseosmgr blocks the switch rather than meet a layout it cannot read. Allowing it while the device holds no volume is the first step towards the in-field conversion, and this is the happy path of it -- both images released, no repartition, the flavor the only variable. The reverse is then pushed and must be refused. EVE-K is a one-way door: docs/EVE-K.md states an upgrade from HV=k to another HV type is not supported, and baseosmgr blocks it unconditionally, with none of the conditions that let the forward direction through. Asserting that keeps a future relaxation from going unnoticed. Carries the suite and the helpers the rest of the conversion tests build on, which is why it is larger than the tests that follow it. Signed-off-by: eriknordmark Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01NZEoFvMK2UHByU3LAeXsxA --- evetest/tests/konvert/app_helpers_test.go | 206 +++++++ evetest/tests/konvert/cluster_helpers_test.go | 77 +++ evetest/tests/konvert/decline_helpers_test.go | 97 ++++ evetest/tests/konvert/device_helpers_test.go | 204 +++++++ evetest/tests/konvert/diag_helpers_test.go | 83 +++ .../tests/konvert/download_helpers_test.go | 85 +++ .../tests/konvert/geometry_helpers_test.go | 523 ++++++++++++++++++ evetest/tests/konvert/restore_helpers_test.go | 349 ++++++++++++ evetest/tests/konvert/shell_helpers_test.go | 58 ++ evetest/tests/konvert/testsuite_test.go | 134 +++++ evetest/tests/konvert/upgrade_helpers_test.go | 81 +++ evetest/tests/konvert/upgrade_test.go | 79 +++ evetest/tests/konvert/vault_helpers_test.go | 243 ++++++++ 13 files changed, 2219 insertions(+) create mode 100644 evetest/tests/konvert/app_helpers_test.go create mode 100644 evetest/tests/konvert/cluster_helpers_test.go create mode 100644 evetest/tests/konvert/decline_helpers_test.go create mode 100644 evetest/tests/konvert/device_helpers_test.go create mode 100644 evetest/tests/konvert/diag_helpers_test.go create mode 100644 evetest/tests/konvert/download_helpers_test.go create mode 100644 evetest/tests/konvert/geometry_helpers_test.go create mode 100644 evetest/tests/konvert/restore_helpers_test.go create mode 100644 evetest/tests/konvert/shell_helpers_test.go create mode 100644 evetest/tests/konvert/testsuite_test.go create mode 100644 evetest/tests/konvert/upgrade_helpers_test.go create mode 100644 evetest/tests/konvert/upgrade_test.go create mode 100644 evetest/tests/konvert/vault_helpers_test.go diff --git a/evetest/tests/konvert/app_helpers_test.go b/evetest/tests/konvert/app_helpers_test.go new file mode 100644 index 00000000000..468bc332c11 --- /dev/null +++ b/evetest/tests/konvert/app_helpers_test.go @@ -0,0 +1,206 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + "fmt" + "strings" + "time" + + // revive:disable:dot-imports + . "github.com/onsi/gomega" + + uuid "github.com/satori/go.uuid" + + eveconfig "github.com/lf-edge/eve-api/go/config" + eveinfo "github.com/lf-edge/eve-api/go/info" + "github.com/lf-edge/eve/evetest" +) + +// The container app the escripts deploy, and how to get into it. +const ( + appSSHUser = "root" + appSSHPassword = "testpassword" + appSSHFwdPort = 2222 + sshTimeout = 20 * time.Second + + // appImageName is the container image the escripts use as their test app + // (eden's eclient equivalent for evetest). + appImageName = "lfedge/evetest-ubuntu-ctr" + appImageTag = "1.0" + + // appMemoryBytes and appCPUs match what the escripts give the container + // app (`--memory=512MB`). + appMemoryBytes = 512 * evetest.MiB + appCPUs = 1 + + // dataMountDir is where a container app's data volume is mounted on + // EVE-kvm. On EVE-K it is not auto-mounted there (lf-edge/eve#6145), which + // is why the marker is read back off the raw device instead. + dataMountDir = "/mnt/data" +) + +// appAuth is how every app in this package is logged into. +var appAuth = evetest.UsernamePasswordAuth{Username: appSSHUser, Password: appSSHPassword} + +// addTestApp adds the standard container app on a switch network instance. +// +// A SWITCH (bridged L2) network instance rather than a local one: across the +// conversion, a local NI does not reconverge onto the kubevirt VMI, so a +// carried app never regains an address, while a switch NI does. The port +// forward is kept as a second way in for the case where the app's own address +// is not yet routable. +func addTestApp(devConfig *evetest.EdgeDeviceConfig, displayName string, + niUUID uuid.UUID) uuid.UUID { + return devConfig.AddApplication(testAppConfig(displayName, niUUID)) +} + +// addTestAppWithVolume is addTestApp with a data volume mounted at +// dataMountDir. +func addTestAppWithVolume(devConfig *evetest.EdgeDeviceConfig, displayName string, + niUUID, dataVolUUID uuid.UUID) uuid.UUID { + appConfig := testAppConfig(displayName, niUUID) + appConfig.Mounts = []evetest.MountConfig{ + {VolumeUUID: dataVolUUID, MountDir: dataMountDir}, + } + return devConfig.AddApplication(appConfig) +} + +// testAppConfig is the app both forms share. +func testAppConfig(displayName string, niUUID uuid.UUID) evetest.ApplicationInstanceConfig { + return evetest.ApplicationInstanceConfig{ + DisplayName: displayName, + Activate: true, + Image: evetest.DockerContainer{ImageName: appImageName, Tag: appImageTag}, + VirtualizationMode: eveconfig.VmMode_HVM, + CPUs: appCPUs, + MemoryBytes: appMemoryBytes, + NetworkAdapters: []evetest.AppNetworkAdapter{ + evetest.VirtualNetworkAdapter{ + LogicalLabel: "vif0", + NetworkInstanceUUID: niUUID, + PortFwdRules: []evetest.PortFwdRule{ + {Protocol: evetest.NetworkProtocolTCP, EdgeNodePort: appSSHFwdPort, AppPort: 22}, + }, + ACLAllowRules: []evetest.ACLAllowRule{ + {Protocol: evetest.NetworkProtocolAny, RemoteSubnet: evetest.IPSubnet("0.0.0.0/0")}, + }, + }, + }, + } +} + +// assertAppSSH asserts the app answers over SSH, retrying long enough to absorb +// the app's network reconvergence as well as SSH itself. +// +// No separate wait for a routable address first: the escripts do not have one, +// and folding both into a single retry means a slow reconvergence still passes +// while a genuinely stuck app fails here with the network capture attached. +func assertAppSSH(t Gomega, device *evetest.EdgeDevice, appUUID uuid.UUID) { + t.Eventually(func(g Gomega) { + out, _, err := device.RunShellScriptInsideApp(appUUID, appAuth, "hostname", sshTimeout, 0) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(strings.TrimSpace(out)).NotTo(BeEmpty()) + }, appSSHTimeout, 10*time.Second).Should(Succeed()) +} + +// assertAppReady waits for an app to be usable end to end: running, then +// answering SSH. The caller chooses the running budget, which the escripts set +// per scenario. +func assertAppReady(t Gomega, device *evetest.EdgeDevice, appUUID uuid.UUID, + runningTimeout time.Duration) { + device.WaitUntilAppIsRunning(appUUID, runningTimeout) + assertAppSSH(t, device, appUUID) +} + +// assertContentTreeAvailable asserts a content tree's blobs are on the device: +// downloaded, verified, and available to anything that asks for them. +// +// DELIVERED is the success state, and the one to assert on. A content tree that +// has finished loading its blobs into the content-addressable store reaches +// pillar's internal LOADED, which is reported to the controller as +// ZSwState_DELIVERED -- pkg/pillar/types/types.go maps it that way behind a +// standing "TBD return info.ZSwState_LOADED". So ZSwState_LOADED is a value +// pillar does not currently send for a content tree, and waiting for it waits +// forever. LOADED is accepted too, so this keeps holding if that TBD is ever +// resolved. +func assertContentTreeAvailable(t Gomega, device *evetest.EdgeDevice, + ctUUID uuid.UUID, timeout time.Duration) { + t.Eventually(func(g Gomega) { + info := device.GetContentTreeInfo(ctUUID) + g.Expect(info).NotTo(BeNil(), "the device reports no such content tree") + g.Expect(info.GetState()).To(BeElementOf( + eveinfo.ZSwState_DELIVERED, eveinfo.ZSwState_LOADED), + "content tree is %s; its blobs are not on the device", info.GetState()) + }, timeout, 10*time.Second).Should(Succeed()) +} + +// assertNoLiveVolumes asserts the device holds no volume that would block a +// cross-flavor upgrade. Volumes on their way out are tolerated -- the check is +// retried, so a delete still settling passes once it completes. +func assertNoLiveVolumes(t Gomega, device *evetest.EdgeDevice) { + t.Eventually(func(g Gomega) { + out, err := runEVE(device, + "eve exec pillar sh -c 'ls /run/volumemgr/VolumeStatus/*.json 2>/dev/null | wc -l'") + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(strings.TrimSpace(out)).To(Equal("0"), + "the device still has live volumes; this test needs none") + }, 2*time.Minute, 5*time.Second).Should(Succeed()) +} + +// writeVolumeMarker writes a marker into the app's mounted data volume and +// flushes it, failing if the volume is not mounted where it should be. +// +// Run before the conversion, on EVE-kvm, where the shim does mount a blank +// volume at its MountDir. +func writeVolumeMarker(t Gomega, device *evetest.EdgeDevice, appUUID uuid.UUID, + mountDir, marker string) { + script := fmt.Sprintf( + "grep -q ' %s ' /proc/mounts || { echo NOT-MOUNTED; cat /proc/mounts; exit 1; }; "+ + "echo %q > %s/marker && sync && echo WROTE-OK", + mountDir, marker, mountDir) + t.Eventually(func(g Gomega) { + out, _, err := device.RunShellScriptInsideApp(appUUID, appAuth, script, 60*time.Second, 0) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(out).To(ContainSubstring("WROTE-OK")) + }, 2*time.Minute, 5*time.Second).Should(Succeed()) +} + +// assertVolumeMarker asserts the marker survived, by scanning the volume's raw +// block device from inside the app. +// +// Not by reading the mount point: on EVE-K the data volume is not auto-mounted +// at its MountDir (lf-edge/eve#6145), so a mount-based check would report the +// data lost when the volume is merely unmounted -- which is a different outcome +// entirely from the one this is meant to catch. The volume appears as a virtio +// disk after the rootfs. +func assertVolumeMarker(t Gomega, device *evetest.EdgeDevice, appUUID uuid.UUID, marker string) { + script := fmt.Sprintf( + "for d in /dev/vd[b-z] /dev/sd[b-z]; do [ -b \"$d\" ] || continue; "+ + "grep -aq %q \"$d\" 2>/dev/null && { echo FOUND-ON $d; exit 0; }; done; "+ + "echo NOT-FOUND; ls -l /dev/vd* /dev/sd* 2>/dev/null; lsblk 2>/dev/null; blkid 2>/dev/null; exit 1", + marker) + t.Eventually(func(g Gomega) { + out, _, err := device.RunShellScriptInsideApp(appUUID, appAuth, script, 90*time.Second, 0) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(out).To(ContainSubstring("FOUND-ON")) + }, 3*time.Minute, 10*time.Second).Should(Succeed()) +} + +// assertVolumeCreated asserts a volume reaches CREATED_VOLUME, the state in +// which it is backed by real storage and an app can be started on it. +// +// Asserted separately from the app that uses it: an app that never starts +// because its volume was never created is a different finding from one that +// fails for its own reasons, and waiting on the app alone cannot tell them +// apart. +func assertVolumeCreated(t Gomega, device *evetest.EdgeDevice, + volumeUUID uuid.UUID, timeout time.Duration) { + t.Eventually(func(g Gomega) { + info := device.GetVolumeInfo(volumeUUID) + g.Expect(info).NotTo(BeNil(), "the device reports no such volume") + g.Expect(info.GetState()).To(Equal(eveinfo.ZSwState_CREATED_VOLUME), + "the volume is %s, not created", info.GetState()) + }, timeout, 15*time.Second).Should(Succeed()) +} diff --git a/evetest/tests/konvert/cluster_helpers_test.go b/evetest/tests/konvert/cluster_helpers_test.go new file mode 100644 index 00000000000..13944e158a6 --- /dev/null +++ b/evetest/tests/konvert/cluster_helpers_test.go @@ -0,0 +1,77 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + "time" + + // revive:disable:dot-imports + . "github.com/onsi/gomega" + + "github.com/lf-edge/eve/evetest" +) + +// EVE-K's storage stack comes up in stages, and each stage's budget is set by +// how long the stage below it can block rather than by how long it usually +// takes. They are waited on in order so that a failure names the stage that +// stalled instead of surfacing as an app that never started. +// Budgets taken from the eden escripts these tests are ported from, which are +// the only calibration anyone has for how long EVE-K actually takes here. +const ( + // volumemgrReadyTimeout must exceed volumemgr's own pre-publish block: it + // waits up to 20 minutes in WaitForKubernetes and up to 20 more in + // storageWait before publishing any status at all. + volumemgrReadyTimeout = 90 * time.Minute + // longhornSCTimeout covers Longhorn installing its StorageClass. + longhornSCTimeout = 50 * time.Minute + // appRunningAfterRepartitionTimeout is what the repartition escript allows + // an app after the conversion; the flavor switch alone gets less, because + // no offline resize preceded it. + appRunningAfterRepartitionTimeout = 65 * time.Minute + // appRunningAfterSwitchTimeout is the budget the cross-flavor and + // volume-migration escripts use. + appRunningAfterSwitchTimeout = 45 * time.Minute + // appSSHTimeout absorbs the app's network reconvergence as well as SSH + // itself, which is what the escripts do -- their marker script retries for + // about twelve minutes rather than gating on an address first. + appSSHTimeout = 12 * time.Minute +) + +// waitVolumemgrReady blocks until volumemgr reports itself initialized, which +// is the point after which a volume request is acted on rather than queued. +func waitVolumemgrReady(t Gomega, device *evetest.EdgeDevice) { + t.Eventually(func() string { + out, _, _ := device.RunShellScript( + "eve exec pillar cat /run/volumemgr/VolumeMgrStatus/volumemgr.json 2>/dev/null", + eveShellTimeout, 0) + return out + }, volumemgrReadyTimeout, 15*time.Second).Should(ContainSubstring(`"Initialized":true`), + "volumemgr never reported Initialized") +} + +// waitLonghornSC blocks until Longhorn's StorageClass exists, without which a +// PVC has nothing to bind to. +func waitLonghornSC(t Gomega, device *evetest.EdgeDevice) { + t.Eventually(func() string { + out, _, _ := device.RunShellScript("eve exec kube kubectl get sc 2>/dev/null", + eveShellTimeout, 0) + return out + }, longhornSCTimeout, 30*time.Second).Should(ContainSubstring("longhorn"), + "Longhorn's StorageClass never appeared") +} + +// waitClusterStorageReady runs the EVE-K storage gates in order. Order is the +// point: each can only be reached once the one before it has passed, so waiting +// on them in sequence turns a stall into a named stage. +// +// No k3s-readiness gate, deliberately: none of the escripts has one, and +// volumemgr will not report itself initialized until the cluster is up anyway, +// so gating on node health first only moves where a stall is reported. +func waitClusterStorageReady(t Gomega, device *evetest.EdgeDevice) { + log := evetest.Logger() + log.Infof("waiting for volumemgr to initialize") + waitVolumemgrReady(t, device) + log.Infof("waiting for Longhorn's StorageClass") + waitLonghornSC(t, device) +} diff --git a/evetest/tests/konvert/decline_helpers_test.go b/evetest/tests/konvert/decline_helpers_test.go new file mode 100644 index 00000000000..dae441d2c57 --- /dev/null +++ b/evetest/tests/konvert/decline_helpers_test.go @@ -0,0 +1,97 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + "encoding/json" + "strings" + "time" + + // revive:disable:dot-imports + . "github.com/onsi/gomega" + + "github.com/lf-edge/eve/evetest" +) + +// assertConversionDeclined asserts EVE refused the conversion and is no worse +// off for it. +// +// Three things have to hold together, and each rules out a different way of +// "refusing" that would not be acceptable: an error must be reported, so the +// refusal is a decision and not a silent stall; the device must still be running +// the image it was, so nothing was installed; and it must still answer its +// controller, so a refused conversion has not cost remote management -- which is +// the whole reason to refuse rather than attempt. +func assertConversionDeclined(t Gomega, device *evetest.EdgeDevice, kvmVersion string) { + log := evetest.Logger() + + // While waiting for the error, a device that leaves the kvm image has + // already failed: it accepted the update. Watching for that during the wait + // turns an eight-minute timeout into an immediate, accurate failure. + var reported string + t.Eventually(func(g Gomega) { + running, err := runEVE(device, "cat /run/eve-release") + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(strings.TrimSpace(running)).To(Equal(kvmVersion), + "the device left the kvm image, so the conversion was not declined") + reported = baseOSError(device) + g.Expect(reported).NotTo(BeEmpty(), + "no error reported yet; a decline must be reported, not a silent stall") + }, 8*time.Minute, 10*time.Second).Should(Succeed()) + log.Infof("EVE declined the conversion: %s", reported) + + running, err := runEVE(device, "cat /run/eve-release") + t.Expect(err).NotTo(HaveOccurred()) + t.Expect(strings.TrimSpace(running)).To(Equal(kvmVersion), + "the device is not on the kvm image after declining") + + log.Infof("the device must still reach its controller") + assertControllerReachable(t, device) +} + +// baseOSError returns the errors baseosmgr is reporting for the base-OS +// updates it knows about, joined, or "" while it reports none. +func baseOSError(device *evetest.EdgeDevice) string { + out, err := runEVE(device, + `eve exec pillar sh -c "cat /run/baseosmgr/BaseOsStatus/*.json 2>/dev/null"`) + if err != nil { + return "" + } + var errors []string + for _, status := range decodeJSONStream(out) { + if msg, _ := status["Error"].(string); msg != "" { + errors = append(errors, msg) + } + } + return strings.Join(errors, " | ") +} + +// decodeJSONStream decodes back-to-back JSON objects, which is what +// concatenating a directory of pubsub files produces. +func decodeJSONStream(raw string) []map[string]any { + var out []map[string]any + decoder := json.NewDecoder(strings.NewReader(raw)) + for { + var obj map[string]any + if err := decoder.Decode(&obj); err != nil { + return out + } + out = append(out, obj) + } +} + +// assertControllerReachable asserts EVE can still reach its controller, which is +// what "still manageable" means in practice: a device that declined a conversion +// but lost its way back would need a truck roll all the same. +func assertControllerReachable(t Gomega, device *evetest.EdgeDevice) { + const pingController = `eve exec pillar curl -sk --max-time 5 ` + + `https://$(tr -d "\r\n" < /config/server)/api/v2/edgedevice/ping ` + + `-o /dev/null -w "%{http_code}"` + t.Eventually(func(g Gomega) { + out, err := runEVE(device, pingController) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(strings.TrimSpace(out)).To(HaveSuffix("200"), + "the device cannot reach its controller after declining the conversion") + }, 5*time.Minute, 15*time.Second).Should(Succeed()) +} diff --git a/evetest/tests/konvert/device_helpers_test.go b/evetest/tests/konvert/device_helpers_test.go new file mode 100644 index 00000000000..5eb9f254400 --- /dev/null +++ b/evetest/tests/konvert/device_helpers_test.go @@ -0,0 +1,204 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + "time" + + // revive:disable:dot-imports + . "github.com/onsi/gomega" + + evecommon "github.com/lf-edge/eve-api/go/evecommon" + "github.com/lf-edge/eve/evetest" + "github.com/lf-edge/eve/evetest/netmodels" +) + +// devName is the single device every test in this package drives. +const devName = "edge-dev" + +// deviceParams are the axes every test in this package resolves before Setup. +type deviceParams struct { + initialVersion string + initialRepo string + initialHypervisor evetest.Hypervisor + targetVersion string + targetHypervisor evetest.Hypervisor + withTPM bool + ramMiB uint32 + cpus uint8 + diskMiB uint32 +} + +// defineSharedParameters declares the parameters every test in this package +// understands, for a test that starts the device on a release. Tests add their +// own on top. +func defineSharedParameters(extra ...evetest.TestParameterDefinition) { + defineParameters(evetest.TestParameterDefinition{ + Key: initialEVEVersionParamKey, + DefaultValue: defaultInitialEVEVersion, + Description: evetest.TestParameterDescription{ + Summary: "Released EVE version the device boots before the conversion", + Default: defaultInitialEVEVersion, + }, + }, extra...) +} + +// defineCrossFlavorParameters declares them for a test that hops between the +// two flavors of one version, which has to be the build under test: the +// relaxation that lets a flavor switch through is in no release, and no release +// publishes both flavors. +func defineCrossFlavorParameters() { + defineParameters(evetest.TestParameterDefinition{ + Key: initialEVEVersionParamKey, + DefaultValue: "", + Description: evetest.TestParameterDescription{ + Summary: "EVE version the device boots before the flavor switch", + Default: "\"\" (the build under test)", + }, + }, altParameterDefinitions()...) +} + +// defineParameters declares the shared set around the given initial-version +// axis, which is the one axis the two entry points above differ on. +func defineParameters(initialVersion evetest.TestParameterDefinition, + extra ...evetest.TestParameterDefinition) { + shared := []evetest.TestParameterDefinition{ + evetest.EVEVersionParameter(), + evetest.HypervisorParameter(), + evetest.TPMParameter(), + evetest.DiskSizeMiBParameter(), + evetest.RAMSizeMiBParameter(), + evetest.CPUsParameter(), + initialVersion, + { + Key: initialEVERepoParamKey, + DefaultValue: "", + Description: evetest.TestParameterDescription{ + Summary: "Repository the initial EVE version is pulled from", + Default: "\"\" (the repo under test)", + }, + }, + { + Key: initialHypervisorParamKey, + DefaultValue: evetest.HypervisorKVM, + Description: evetest.TestParameterDescription{ + Summary: "Hypervisor flavor the device starts on", + Default: "kvm", + AllowedValues: "kvm|xen|kubevirt", + }, + }, + } + evetest.DefineTestParameters(append(shared, extra...)...) +} + +// resolveDeviceParams reads the shared parameters and applies this package's +// defaults, which are eden's: 4 vCPUs, 8 GiB of RAM, a 64 GiB boot disk. +func resolveDeviceParams(t Gomega) deviceParams { + p := deviceParams{ + initialVersion: evetest.GetTestParameter[string](initialEVEVersionParamKey), + initialRepo: evetest.GetTestParameter[string](initialEVERepoParamKey), + initialHypervisor: evetest.GetTestParameter[evetest.Hypervisor](initialHypervisorParamKey), + targetVersion: evetest.GetEVEVersionParameterValue(), + targetHypervisor: evetest.GetHypervisorParameterValue(), + withTPM: evetest.GetTPMParameterValue(), + ramMiB: evetest.GetRAMSizeMiBParameterValue(), + cpus: evetest.GetCPUsParameterValue(), + diskMiB: evetest.GetDiskSizeMiBParameterValue(), + } + if p.ramMiB == 0 { + p.ramMiB = deviceRAMMiB + } + if p.cpus == 0 { + p.cpus = deviceCPUs + } + if p.diskMiB == 0 { + p.diskMiB = bootDiskMiB + } + return p +} + +// requirePinnedInitialVersion asserts the test was given a release to start +// from. Tests that convert a released image need one; a test that converts the +// build under test deliberately leaves it unset. +func requirePinnedInitialVersion(t Gomega, p deviceParams) { + t.Expect(p.initialVersion).NotTo(BeEmpty(), + "this test needs a released EVE version to start from (%s)", + initialEVEVersionParamKey) +} + +// setupDevice brings up one device on the initial released image and returns +// it, with a management network applied. +// +// filesystem selects /persist's format, and extraDisks attaches additional +// blank disks; both default to the plain single-ext4-disk case a caller that +// passes their zero values gets. +func setupDevice(t Gomega, p deviceParams, filesystem evetest.Filesystem, + extraDisks []uint64, reusePolicy evetest.ExistingEdgeDeviceReusePolicy, + extraRequirements ...evetest.Requirement) *evetest.EdgeDevice { + + requirements := []evetest.Requirement{ + evetest.RequireEdgeDevice{ + Name: devName, + WithEVEVersion: p.initialVersion, + WithEVERepo: p.initialRepo, + WithHypervisor: p.initialHypervisor, + WithTPM: p.withTPM, + WithFilesystem: filesystem, + MinDiskSizeInMiB: p.diskMiB, + MinRAMInMiB: p.ramMiB, + MinCPUs: p.cpus, + ExtraDisks: extraDisks, + DeviceReusePolicy: reusePolicy, + }, + evetest.RequireNetworkModel{NetworkModel: netmodels.SingleEthWithDHCP}, + } + evetest.Setup(append(requirements, extraRequirements...)...) + return evetest.GetEdgeDevice(devName) +} + +// applyMgmtNetwork gives the device its management port, which everything else +// depends on. +func applyMgmtNetwork(device *evetest.EdgeDevice, + devConfig *evetest.EdgeDeviceConfig) { + networkUUID := devConfig.AddNetwork(evetest.DHCPNetworkConfig{ + NetworkType: evecommon.NetworkType_V4, + }) + devConfig.AddNetworkAdapter(evetest.NetworkAdapterConfig{ + LogicalLabel: "eth0", + PhysicalLabel: "eth0", + InterfaceName: "eth0", + NetworkUUID: networkUUID, + Usage: evecommon.PhyIoMemberUsage_PhyIoUsageMgmtAndApps, + }) + device.ApplyConfig(devConfig, false, false) +} + +// growBootDiskTail powers the device down, enlarges its boot disk so there is +// unallocated space past the last partition, and brings it back. +// +// The tail cannot be arranged when the device is created: EVE's image generator +// sizes the partitions to fill whatever disk it is handed, so the space has to +// be added once the layout is already written. +func growBootDiskTail(t Gomega, device *evetest.EdgeDevice, totalMiB uint32) { + evetest.Logger().Infof("growing the boot disk to %d MiB to leave a free tail", totalMiB) + device.SyncDisks() + device.PowerOff() + device.GrowDisk(uint64(totalMiB) << 20) + // PowerOn does not wait here: nodeagent does not reliably republish + // LastRebootTime after an external power cycle, which is the signal that + // wait watches for, so it can time out on a device that came back fine. + // Waiting for the device to answer is the signal that does hold. + device.PowerOn(false) + waitDeviceResponds(t, device) +} + +// waitDeviceResponds blocks until EVE answers a trivial command, which is how a +// device that was power-cycled rather than rebooted is confirmed back. +func waitDeviceResponds(t Gomega, device *evetest.EdgeDevice) { + t.Eventually(func(g Gomega) { + out, err := runEVE(device, "echo device-is-up") + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(out).To(ContainSubstring("device-is-up")) + }, 15*time.Minute, 15*time.Second).Should(Succeed()) +} diff --git a/evetest/tests/konvert/diag_helpers_test.go b/evetest/tests/konvert/diag_helpers_test.go new file mode 100644 index 00000000000..46b8feeb22c --- /dev/null +++ b/evetest/tests/konvert/diag_helpers_test.go @@ -0,0 +1,83 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + "github.com/lf-edge/eve/evetest" +) + +// Everything here is best-effort: it runs when an assertion is already about to +// fail, and must never turn a diagnosable failure into a second one. Each probe +// logs whatever it gets, including its error. + +// probe is one diagnostic command and the label its output is filed under. +type probe struct { + what string + script string +} + +// runProbes logs each probe's output under label. Errors are logged, not +// raised. +func runProbes(device *evetest.EdgeDevice, label string, probes []probe) { + log := evetest.Logger() + log.Errorf("=== %s ===", label) + for _, p := range probes { + out, errOut, err := device.RunShellScript(p.script, eveShellTimeout, 0) + log.Errorf("[%s] %s:\n%s%s(err=%v)", label, p.what, out, errOut, err) + } +} + +// dumpConversionFailure captures why EVE marked the conversion failed. By the +// time this runs the device is back online on the unconverted partition, so it +// can still be asked directly -- which is the only window in which the resizer's +// own verdict is readable. +func dumpConversionFailure(device *evetest.EdgeDevice) { + runProbes(device, "conversion FAILED", []probe{ + {"resize-failed.json", "cat /config/resize-failed.json 2>/dev/null || echo NONE"}, + {"resize flags", "echo repartition-inprogress=$(cat /config/repartition-inprogress 2>/dev/null); " + + "echo resize-reboots=$(cat /config/resize-reboots 2>/dev/null)"}, + {"zboot status", "zboot status 2>&1 || true"}, + {"BaseOsStatus", "eve exec pillar sh -c 'cat /run/baseosmgr/BaseOsStatus/*.json 2>/dev/null' || echo NONE"}, + {"partitions", partsLsblk}, + }) +} + +// dumpAppNetwork snapshots what stands between the controller and the app: the +// port-forward rules, the app's own network status, and the node's addresses. +// Taken on both flavors so a working baseline can be diffed against a failure. +func dumpAppNetwork(device *evetest.EdgeDevice, label string) { + runProbes(device, "app network: "+label, []probe{ + {"NAT port map", "eve exec pillar iptables -t nat -S 2>/dev/null | grep -aiE '2222|DNAT|to-destination' || echo none"}, + {"AppNetworkStatus", "eve exec pillar sh -c 'cat /run/zedrouter/AppNetworkStatus/*.json 2>/dev/null' || echo none"}, + {"addresses", "eve exec pillar ip -br addr 2>/dev/null || echo none"}, + }) +} + +// dumpClusterStorage captures the EVE-K storage stack when an app is stuck +// waiting for a volume: which stage is not ready, and what Longhorn and CDI +// think of the PVC. +func dumpClusterStorage(device *evetest.EdgeDevice) { + runProbes(device, "EVE-K cluster storage", []probe{ + {"volumemgr", "eve exec pillar cat /run/volumemgr/VolumeMgrStatus/volumemgr.json 2>/dev/null || echo NONE"}, + {"storage classes", "eve exec kube kubectl get sc 2>&1 || true"}, + {"PVCs", "eve exec kube kubectl get pvc -A 2>&1 || true"}, + {"pods", "eve exec kube kubectl get pods -A 2>&1 || true"}, + {"longhorn volumes", "eve exec kube kubectl get volumes.longhorn.io -A 2>&1 || true"}, + {"persist usage", "df -h /persist 2>&1 || true"}, + }) +} + +// dumpRestoreState captures what early boot made of a damaged /persist: whether +// the backup was there to restore from, and what came back. +func dumpRestoreState(device *evetest.EdgeDevice) { + runProbes(device, "identity restore", []probe{ + {"config backup", "ls -lR /config/backup-persist 2>&1 || echo NONE"}, + {"restore flag", "ls -l /config/repartition-inprogress 2>&1 || echo NONE"}, + {"uuid", "cat /persist/status/uuid 2>/dev/null || echo NONE"}, + {"certs", "ls -l /persist/certs 2>&1 || echo NONE"}, + {"checkpoint", "ls -l /persist/checkpoint 2>&1 || echo NONE"}, + {"onboarding", "eve exec pillar sh -c 'cat /persist/status/zedclient/OnboardingStatus/global.json 2>/dev/null' || echo NONE"}, + {"cipher status", "eve exec pillar sh -c 'cat /run/nim/CipherBlockStatus/*.json 2>/dev/null' || echo NONE"}, + }) +} diff --git a/evetest/tests/konvert/download_helpers_test.go b/evetest/tests/konvert/download_helpers_test.go new file mode 100644 index 00000000000..17cbfbd6212 --- /dev/null +++ b/evetest/tests/konvert/download_helpers_test.go @@ -0,0 +1,85 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + "encoding/json" + "time" + + // revive:disable:dot-imports + . "github.com/onsi/gomega" + + "github.com/lf-edge/eve/evetest" +) + +// blobReuseAllowanceBytes is how much the downloader may still pull and have +// the deployment count as a reuse. It is not zero because a redeploy re-reads +// small metadata -- a manifest, a tag resolution -- even when every layer is +// already in the store; an actual layer download is orders of magnitude larger. +const blobReuseAllowanceBytes = int64(1) << 20 + +// downloaderRecvBytes totals what the downloader has pulled since boot. +// +// The counter lives under /run, so it resets on every boot. Both readings of a +// before/after pair therefore have to be taken within the same boot, and a +// second reading lower than the first means the device rebooted in between +// rather than that nothing was downloaded. +func downloaderRecvBytes(device *evetest.EdgeDevice) (int64, error) { + out, err := runEVE(device, + "eve exec pillar cat /run/downloader/MetricsMap/global.json 2>/dev/null") + if err != nil { + return 0, err + } + if out == "" { + return 0, nil + } + var metrics map[string]struct { + URLCounters map[string]struct { + RecvByteCount int64 `json:"RecvByteCount"` + } `json:"URLCounters"` + } + if err := json.Unmarshal([]byte(out), &metrics); err != nil { + return 0, err + } + var total int64 + for _, conn := range metrics { + for _, counter := range conn.URLCounters { + total += counter.RecvByteCount + } + } + return total, nil +} + +// snapshotDownloaderBytes takes the "before" reading of a blob-reuse check. +func snapshotDownloaderBytes(t Gomega, device *evetest.EdgeDevice) int64 { + var total int64 + t.Eventually(func(g Gomega) { + var err error + total, err = downloaderRecvBytes(device) + g.Expect(err).NotTo(HaveOccurred()) + }, 3*time.Minute, 10*time.Second).Should(Succeed()) + evetest.Logger().Infof("downloader has received %d bytes so far this boot", total) + return total +} + +// assertBlobsReused asserts the downloader pulled essentially nothing since +// before, i.e. that whatever was deployed came out of the content store the +// conversion carried over. +// +// Measured in bytes rather than by comparing digests: a redeploy that fetches +// the same layers again ends up holding the same digests it started with, so a +// digest comparison would call that a reuse. +func assertBlobsReused(t Gomega, device *evetest.EdgeDevice, before int64) { + after, err := downloaderRecvBytes(device) + t.Expect(err).NotTo(HaveOccurred()) + t.Expect(after).To(BeNumerically(">=", before), + "the downloader's byte counter went backwards (%d -> %d), so the device "+ + "rebooted between the two readings and they cannot be compared", + before, after) + delta := after - before + evetest.Logger().Infof("downloader received %d bytes across the deployment", delta) + t.Expect(delta).To(BeNumerically("<", blobReuseAllowanceBytes), + "the deployment downloaded %d bytes, so it did not reuse the blobs the "+ + "conversion carried over", delta) +} diff --git a/evetest/tests/konvert/geometry_helpers_test.go b/evetest/tests/konvert/geometry_helpers_test.go new file mode 100644 index 00000000000..71ee1a93ef8 --- /dev/null +++ b/evetest/tests/konvert/geometry_helpers_test.go @@ -0,0 +1,523 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + "encoding/json" + "fmt" + "regexp" + "strconv" + "strings" + "time" + + // revive:disable:dot-imports + . "github.com/onsi/gomega" + + "github.com/lf-edge/eve/evetest" +) + +// Reasons the conversion cannot go ahead, as the escripts name them. +const ( + // refuseZFS is a ZFS /persist with no free tail. ZFS cannot be shrunk, so + // with nothing to grow into there is no way to free the space. + refuseZFS = "zfs" + // refuseTooFull is an ext4 /persist holding too much to give up what the + // EVE-K layout needs while staying under the resizer's fullness limit. + refuseTooFull = "too-full" +) + +// Decisions storage-resizer's pre-flight check can reach, as they appear in its +// --json output. +const ( + // decisionShrink frees the space the EVE-K layout needs by shrinking + // /persist, which is what a boot disk with no free tail requires. This is + // the field layout. + decisionShrink = "shrink" + // decisionGrow takes the space from an unallocated tail instead, leaving + // /persist alone. + decisionGrow = "grow" + // decisionInsufficient is the refusal: no room can be freed either way. + decisionInsufficient = "insufficient" +) + +const ( + miB = int64(1) << 20 + giB = int64(1) << 30 + + // The released layout: a 36 MiB ESP and 512 MiB IMGA/IMGB. The ceilings sit + // well above those so that alignment jitter cannot fail the check, while + // staying far below anything the conversion produces. + smallESPCeiling = 256 * miB + smallImgCeiling = giB + + // The EVE-K layout: a 2 GiB ESP, a reserved 2 GiB ESP-B, and 10 GiB + // IMGA/IMGB. The floors sit below each target for the same reason. + largeESPFloor = giB + largeImgFloor = 8 * giB + largeESPBFloor = giB + + // espBPartitionNumber is where the conversion must place the reserved + // second ESP, so that a converted disk has the same partition numbering as + // a fresh EVE-K install. + espBPartitionNumber = 7 + + // freeTailNeeded is the unallocated space past the last partition below + // which storage-resizer will not choose to grow. + freeTailNeeded = 22 * giB + // gptSectorSize is the logical sector size EVE's images are built with. + gptSectorSize = 512 +) + +// fillPersistTimeout bounds the pre-conversion fill. It is generous because the +// work is proportional to the fill size and runs against a virtual disk. +const fillPersistTimeout = 40 * time.Minute + +// espBGUIDSuffix identifies the reserved second ESP. Both ESPs carry the same +// "EFI System" partition label, so the fresh-install GUID is what tells them +// apart -- and a partition that is an ESP-B in every way except its GUID is not +// one, because that is what EVE itself keys on. +const espBGUIDSuffix = "30056" + +// partsLsblk dumps the partition table in a form every field the geometry +// assertions need can be read out of in one call. +const partsLsblk = "eve exec pillar lsblk -b -P -o NAME,TYPE,PARTLABEL,PARTUUID,SIZE" + +// geometry is the boot disk's partition sizes in bytes, keyed the way the +// conversion talks about them. A partition that is absent reads as zero, which +// is meaningful for P3: the two-disk layouts have none. +type geometry struct { + esp int64 + espB int64 + espBName string + imgA int64 + imgB int64 + p3 int64 + // diskSize and partitionSum give the unallocated tail. + diskSize int64 + partitionSum int64 +} + +// freeTail is the unallocated space past the last partition. +func (g geometry) freeTail() int64 { return g.diskSize - g.partitionSum } + +// String renders the geometry for a failure message, since every assertion +// here wants to show what it actually saw. +func (g geometry) String() string { + return fmt.Sprintf( + "ESP=%d ESP-B=%d(%s) IMGA=%d IMGB=%d P3=%d disk=%d freeTail=%d", + g.esp, g.espB, g.espBName, g.imgA, g.imgB, g.p3, g.diskSize, g.freeTail()) +} + +// lsblkFieldRE matches the KEY="value" pairs `lsblk -P` emits. +var lsblkFieldRE = regexp.MustCompile(`(\w+)="([^"]*)"`) + +// parseGeometry reads an `lsblk -b -P` dump into a geometry. +func parseGeometry(dump string) geometry { + var g geometry + for _, line := range strings.Split(dump, "\n") { + fields := map[string]string{} + for _, m := range lsblkFieldRE.FindAllStringSubmatch(line, -1) { + fields[m[1]] = m[2] + } + size, err := strconv.ParseInt(fields["SIZE"], 10, 64) + if err != nil { + continue + } + switch fields["TYPE"] { + case "disk": + if size > g.diskSize { + g.diskSize = size + } + continue + case "part": + g.partitionSum += size + default: + continue + } + switch fields["PARTLABEL"] { + case "EFI System": + if strings.HasSuffix(strings.ToLower(fields["PARTUUID"]), espBGUIDSuffix) { + g.espB = size + g.espBName = fields["NAME"] + } else { + g.esp = size + } + case "IMGA": + g.imgA = size + case "IMGB": + g.imgB = size + case "P3": + g.p3 = size + } + } + return g +} + +// readGeometry returns the device's current boot-disk geometry, retrying while +// EVE's SSH and pillar come back after a reboot. +func readGeometry(t Gomega, device *evetest.EdgeDevice) geometry { + var g geometry + t.Eventually(func(g2 Gomega) { + out, err := runEVE(device, partsLsblk) + g2.Expect(err).NotTo(HaveOccurred()) + g = parseGeometry(out) + g2.Expect(g.imgA).To(BeNumerically(">", 0), "could not read IMGA size:\n%s", out) + }, 5*time.Minute, 10*time.Second).Should(Succeed()) + return g +} + +// assertSmallGeometry asserts the device is still on the released layout, which +// is the precondition for the conversion being worth running: on a disk that is +// already large there is nothing to repartition and a passing test would prove +// nothing. +func assertSmallGeometry(t Gomega, device *evetest.EdgeDevice) geometry { + g := readGeometry(t, device) + t.Expect(g.esp).To(BeNumerically("<", smallESPCeiling), + "ESP is not the released size: %s", g) + t.Expect(g.imgA).To(BeNumerically("<", smallImgCeiling), + "IMGA is not the released size: %s", g) + t.Expect(g.imgB).To(BeNumerically("<", smallImgCeiling), + "IMGB is not the released size: %s", g) + t.Expect(g.espB).To(BeZero(), + "the released layout already has an ESP-B, so the conversion has run before: %s", g) + return g +} + +// sgdiskPrint dumps the partition table the way the GPT itself describes it, +// including where usable space actually ends. +const sgdiskPrint = "eve exec pillar sgdisk -p " + +var ( + // lastUsableRE reads the last sector the GPT will let a partition occupy. + lastUsableRE = regexp.MustCompile(`last usable sector is (\d+)`) + // partitionRowRE reads a partition row's start and end sector. + partitionRowRE = regexp.MustCompile(`^\s*\d+\s+(\d+)\s+(\d+)\s`) +) + +// assertFreeTail asserts the GPT exposes enough unallocated space past the last +// partition for storage-resizer to choose the grow. +// +// Asked of the GPT rather than computed from the disk's size, because those are +// different questions and only the GPT's answer matters. Growing an image moves +// the end of the disk but leaves the table describing the old one, so +// subtracting the partition sizes from the disk size reports a healthy tail +// that nothing can allocate from -- a check that passes in exactly the case it +// exists to catch. +func assertFreeTail(t Gomega, device *evetest.EdgeDevice) { + var tail int64 + t.Eventually(func(g Gomega) { + disk, err := bootDiskPath(device) + g.Expect(err).NotTo(HaveOccurred()) + out, err := runEVE(device, sgdiskPrint+disk) + g.Expect(err).NotTo(HaveOccurred()) + + m := lastUsableRE.FindStringSubmatch(out) + g.Expect(m).NotTo(BeNil(), "could not read the last usable sector:\n%s", out) + lastUsable, err := strconv.ParseInt(m[1], 10, 64) + g.Expect(err).NotTo(HaveOccurred()) + + var lastPartitionEnd int64 + for _, line := range strings.Split(out, "\n") { + if row := partitionRowRE.FindStringSubmatch(line); row != nil { + end, convErr := strconv.ParseInt(row[2], 10, 64) + g.Expect(convErr).NotTo(HaveOccurred()) + if end > lastPartitionEnd { + lastPartitionEnd = end + } + } + } + g.Expect(lastPartitionEnd).To(BeNumerically(">", 0), + "could not read any partition row:\n%s", out) + tail = (lastUsable - lastPartitionEnd) * gptSectorSize + }, 3*time.Minute, 10*time.Second).Should(Succeed()) + + evetest.Logger().Infof("the GPT exposes %d bytes of usable free tail", tail) + t.Expect(tail).To(BeNumerically(">=", freeTailNeeded), + "the GPT exposes only %d bytes past the last partition; the conversion needs %d to grow into", + tail, freeTailNeeded) +} + +// assertLargeGeometry asserts the conversion reached the EVE-K layout, given +// the geometry it started from. +// +// wantP3 says what must have happened to /persist, which is the part that +// differs by route: the shrink takes its space from P3, the grow takes it from +// the free tail and must leave P3 alone. Comparing against the baseline rather +// than against a fixed size is what makes that distinguishable at all. +func assertLargeGeometry(t Gomega, device *evetest.EdgeDevice, before geometry, wantP3 p3Expectation) { + g := readGeometry(t, device) + + t.Expect(g.esp).To(BeNumerically(">", before.esp), "ESP did not grow: %s", g) + t.Expect(g.imgA).To(BeNumerically(">", before.imgA), "IMGA did not grow: %s", g) + t.Expect(g.imgB).To(BeNumerically(">", before.imgB), "IMGB did not grow: %s", g) + t.Expect(g.esp).To(BeNumerically(">=", largeESPFloor), "ESP is below the EVE-K size: %s", g) + t.Expect(g.imgA).To(BeNumerically(">=", largeImgFloor), "IMGA is below the EVE-K size: %s", g) + t.Expect(g.imgB).To(BeNumerically(">=", largeImgFloor), "IMGB is below the EVE-K size: %s", g) + + t.Expect(g.espB).NotTo(BeZero(), + "the conversion did not create the reserved ESP-B: %s", g) + t.Expect(g.espB).To(BeNumerically(">=", largeESPBFloor), + "the reserved ESP-B is below its EVE-K size: %s", g) + t.Expect(g.espBName).To(HaveSuffix(strconv.Itoa(espBPartitionNumber)), + "the reserved ESP-B is not partition #%d, so a converted disk is numbered "+ + "differently from a fresh EVE-K install: %s", espBPartitionNumber, g) + + switch wantP3 { + case p3MustShrink: + t.Expect(g.p3).To(BeNumerically("<", before.p3), + "/persist did not shrink, so the space came from somewhere else: %s", g) + case p3MustBeUnchanged: + // A megabyte of tolerance for GPT alignment; anything more is a shrink. + t.Expect(g.p3).To(BeNumerically(">=", before.p3-miB), + "/persist shrank on a path that should have grown into the free tail: %s", g) + case p3MustBeAbsent: + t.Expect(g.p3).To(BeZero(), + "the boot disk has a /persist partition, but this layout keeps it on another disk: %s", g) + } +} + +// p3Expectation is what the conversion must have done to /persist, which is +// how the two routes to the same geometry are told apart. +type p3Expectation int + +const ( + // p3MustShrink is the shrink route: the space came out of /persist. + p3MustShrink p3Expectation = iota + // p3MustBeUnchanged is the grow route: the space came from the free tail. + p3MustBeUnchanged + // p3MustBeAbsent is a layout that keeps /persist on another disk entirely. + p3MustBeAbsent +) + +// bootDiskPath resolves the boot disk as the parent of the IMGA partition, +// e.g. /dev/vda under evetest's virtio QEMU. +func bootDiskPath(device *evetest.EdgeDevice) (string, error) { + out, err := runEVE(device, + `eve exec pillar sh -c 'lsblk -ndo pkname $(findfs PARTLABEL=IMGA)'`) + if err != nil { + return "", err + } + name := strings.TrimSpace(out) + if name == "" { + return "", fmt.Errorf("could not resolve the boot disk (IMGA's parent)") + } + return "/dev/" + name, nil +} + +// assertCheckDecision asserts storage-resizer's pre-flight check reaches the +// expected decision on the live boot disk. +// +// This is what separates a conversion that took the intended route from one +// that reached the same geometry another way, and it has to be asserted before +// the conversion: afterwards the inputs it decided on are gone. +func assertCheckDecision(t Gomega, device *evetest.EdgeDevice, want string) { + t.Eventually(func(g Gomega) { + disk, err := bootDiskPath(device) + g.Expect(err).NotTo(HaveOccurred()) + out, err := runEVEWithTimeout(device, + "eve exec pillar /usr/bin/storage-resizer check --disk "+disk+" --json", + 2*time.Minute) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(out).To(ContainSubstring(fmt.Sprintf("%q", want)), + "storage-resizer check did not decide %q:\n%s", want, out) + }, 3*time.Minute, 10*time.Second).Should(Succeed()) +} + +// fillPersist writes gib GiB into /persist so that the offline shrink has real +// blocks to relocate rather than free space to discard. +// +// Without it the shrink is a much weaker test: resize2fs has nothing to move, +// so the relocation path -- the part that can lose data if it is interrupted -- +// is never exercised. +func fillPersist(t Gomega, device *evetest.EdgeDevice, gib int) { + if gib <= 0 { + return + } + log := evetest.Logger() + log.Infof("pre-filling /persist with %d GiB so the shrink has blocks to relocate", gib) + script := fmt.Sprintf(`set -e +mkdir -p /persist/konvert-fill +i=0 +while [ "$i" -lt %d ]; do + dd if=/dev/zero of=/persist/konvert-fill/blk.$i bs=1M count=1024 2>/dev/null || break + i=$((i + 1)) +done +sync +echo "FILLED=$i" +df -k /persist | awk 'NR==2{print "PERSIST used="$5}'`, gib) + // One attempt, not a retry: this writes tens of gigabytes, and a second + // pass would start over rather than continue. + out, err := runEVEWithTimeout(device, script, fillPersistTimeout) + t.Expect(err).NotTo(HaveOccurred(), "could not fill /persist:\n%s", out) + t.Expect(out).To(ContainSubstring("FILLED="), "could not fill /persist:\n%s", out) + log.Infof("pre-fill result: %s", strings.TrimSpace(out)) +} + +// assertGeometryUnchanged asserts every partition still has the size it had. +// +// ESP-B is compared like any other partition rather than required to be absent: +// a device that is already on the EVE-K layout has one, and for it "unchanged" +// means the ESP-B it started with is still there. Where the caller starts on a +// released image the comparison is against zero anyway, so a conversion that +// rewrote the table is still caught. +// +// Compared partition by partition rather than as whole text: lsblk also prints +// device names, which a reboot can renumber without anything having moved. +func assertGeometryUnchanged(t Gomega, device *evetest.EdgeDevice, before geometry) { + after := readGeometry(t, device) + t.Expect(after.esp).To(Equal(before.esp), "ESP changed size: %s", after) + t.Expect(after.imgA).To(Equal(before.imgA), "IMGA changed size: %s", after) + t.Expect(after.imgB).To(Equal(before.imgB), "IMGB changed size: %s", after) + t.Expect(after.p3).To(Equal(before.p3), "/persist changed size: %s", after) + t.Expect(after.espB).To(Equal(before.espB), + "the ESP-B changed, so the partition table was rewritten: %s", after) +} + +// persistTypeFile is where EVE records what /persist was formatted as. +const persistTypeFile = "/run/eve.persist_type" + +// assertPersistType waits for EVE to report the expected /persist filesystem. +// +// A precondition, not an observation: the filesystem decides which way the +// conversion can free space, so a device that came up ext4 when the test meant +// ZFS would exercise a different path and could still satisfy the test's other +// assertions for the wrong reason. +func assertPersistType(t Gomega, device *evetest.EdgeDevice, want string) { + t.Eventually(func(g Gomega) { + out, err := runEVE(device, "cat "+persistTypeFile) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(strings.TrimSpace(out)).To(Equal(want), + "/persist is not %s, so this variant would refuse for the wrong reason", want) + }, 10*time.Minute, 15*time.Second).Should(Succeed()) +} + +// fillPersistToPercent fills /persist until it is at least pct percent used, so +// that no shrink can free what the EVE-K layout needs. +// +// Sized as a proportion of the filesystem rather than as an absolute, because +// what makes a shrink impossible is how full /persist is relative to itself. +func fillPersistToPercent(t Gomega, device *evetest.EdgeDevice, pct int) { + log := evetest.Logger() + log.Infof("filling /persist to %d%% so no shrink can free enough", pct) + script := fmt.Sprintf(`set -e +target=%d +size=$(df -k /persist | awk 'NR==2{print $2}') +used=$(df -k /persist | awk 'NR==2{print $3}') +avail=$(df -k /persist | awk 'NR==2{print $4}') +need=$(( size * target / 100 - used )) +if [ "$need" -le 0 ]; then echo "ALREADY-FULL"; else + [ "$need" -lt "$avail" ] || need=$(( avail - 1048576 )) + mkdir -p /persist/konvert-fill + dd if=/dev/zero of=/persist/konvert-fill/fill bs=1M count=$(( need / 1024 )) 2>/dev/null + sync +fi +df -k /persist | awk 'NR==2{print "PERSIST used="$5}'`, pct) + out, err := runEVEWithTimeout(device, script, fillPersistTimeout) + t.Expect(err).NotTo(HaveOccurred(), "could not fill /persist:\n%s", out) + t.Expect(out).To(ContainSubstring("PERSIST used="), "could not fill /persist:\n%s", out) + log.Infof("fill result: %s", strings.TrimSpace(out)) +} + +// resizerCheck is what storage-resizer's pre-flight check reports, limited to +// the fields that say whether the conversion can go ahead and why not. +type resizerCheck struct { + Decision string `json:"decision"` + DecisionReason string `json:"decisionReason"` + PersistType string `json:"persistType"` + // ShrinkApplicable is whether a shrink was even considered; it is false for + // a filesystem that cannot be shrunk at all. + ShrinkApplicable bool `json:"shrinkApplicable"` + SpaceToShrinkExt struct { + OK bool `json:"ok"` + } `json:"spaceToShrinkExt"` +} + +// readResizerCheck runs the pre-flight check and decodes its verdict. +func readResizerCheck(device *evetest.EdgeDevice) (resizerCheck, error) { + var check resizerCheck + disk, err := bootDiskPath(device) + if err != nil { + return check, err + } + out, err := runEVEWithTimeout(device, + "eve exec pillar /usr/bin/storage-resizer check --disk "+disk+" --json", + 2*time.Minute) + if err != nil { + return check, err + } + if err := json.Unmarshal([]byte(out), &check); err != nil { + return check, fmt.Errorf("could not decode the check's verdict %q: %w", out, err) + } + return check, nil +} + +// assertCheckRefuses asserts the pre-flight check declines, and declines for the +// reason this variant set up. +// +// The reason matters as much as the refusal. Both variants end at the same +// verdict, so a test that only checked for a refusal would pass on a device that +// refused for some third reason entirely -- and would keep passing if the +// condition it meant to create had quietly stopped happening. +func assertCheckRefuses(t Gomega, device *evetest.EdgeDevice, reason string) { + t.Eventually(func(g Gomega) { + check, err := readResizerCheck(device) + g.Expect(err).NotTo(HaveOccurred()) + evetest.Logger().Infof( + "resizer check: decision=%s persistType=%s shrinkApplicable=%t shrink.ok=%t reason=%q", + check.Decision, check.PersistType, check.ShrinkApplicable, + check.SpaceToShrinkExt.OK, check.DecisionReason) + + g.Expect(check.Decision).To(Equal(decisionInsufficient), + "the check did not refuse: %+v", check) + switch reason { + case refuseZFS: + g.Expect(check.PersistType).To(Equal("zfs"), + "the refusal is not the ZFS one: %+v", check) + case refuseTooFull: + g.Expect(check.ShrinkApplicable).To(BeTrue(), + "a shrink was never considered, so this is not the too-full refusal: %+v", check) + g.Expect(check.SpaceToShrinkExt.OK).To(BeFalse(), + "the shrink would have fit, so /persist is not too full: %+v", check) + } + }, 3*time.Minute, 10*time.Second).Should(Succeed()) +} + +// The absolute EVE-K target layout, which every conversion must reach whatever +// it started from: two 2 GiB ESPs (ESP-A and the reserved ESP-B) and 10 GiB +// IMGA/IMGB -- "2+2+10+10". The floors sit below each target to tolerate GPT +// alignment while staying unambiguous about which layout is present. +const ( + targetESPFloor = 3 * giB / 2 + targetImgFloor = 9 * giB +) + +// isEVEKLayout reports whether a geometry is already the EVE-K target. +func isEVEKLayout(g geometry) bool { + return g.espB >= targetESPFloor && g.esp >= targetESPFloor && + g.imgA >= targetImgFloor && g.imgB >= targetImgFloor +} + +// assertFinalEVEKLayout asserts the boot disk reached the EVE-K target layout +// in absolute terms, rather than relative to where it started. +// +// This is the stricter of the two geometry checks and the one that pins the +// contract: a conversion that grew every partition but stopped short of the +// target would satisfy a relative check and still leave a disk that is not +// laid out like a fresh EVE-K install. +func assertFinalEVEKLayout(t Gomega, device *evetest.EdgeDevice) { + g := readGeometry(t, device) + evetest.Logger().Infof("final geometry: %s", g) + t.Expect(g.espB).NotTo(BeZero(), + "the conversion did not create the reserved ESP-B: %s", g) + t.Expect(g.esp).To(BeNumerically(">=", targetESPFloor), + "ESP-A is below the 2 GiB target: %s", g) + t.Expect(g.espB).To(BeNumerically(">=", targetESPFloor), + "the reserved ESP-B is below the 2 GiB target: %s", g) + t.Expect(g.imgA).To(BeNumerically(">=", targetImgFloor), + "IMGA is below the 10 GiB target: %s", g) + t.Expect(g.imgB).To(BeNumerically(">=", targetImgFloor), + "IMGB is below the 10 GiB target: %s", g) + t.Expect(g.espBName).To(HaveSuffix(strconv.Itoa(espBPartitionNumber)), + "the reserved ESP-B is not partition #%d: %s", espBPartitionNumber, g) +} diff --git a/evetest/tests/konvert/restore_helpers_test.go b/evetest/tests/konvert/restore_helpers_test.go new file mode 100644 index 00000000000..324760c54f1 --- /dev/null +++ b/evetest/tests/konvert/restore_helpers_test.go @@ -0,0 +1,349 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + "fmt" + "strings" + "time" + + // revive:disable:dot-imports + . "github.com/onsi/gomega" + + "google.golang.org/protobuf/proto" + + evecommon "github.com/lf-edge/eve-api/go/evecommon" + api "github.com/lf-edge/eve/evetest/grpcapi/go" + + "github.com/lf-edge/eve/evetest" + "github.com/lf-edge/eve/evetest/netmodels" +) + +// The wireless port used to prove an encrypted credential can be decrypted +// after a restore. +// +// A device-network credential rather than, say, application user-data: network +// credentials are decrypted by nim while it reconciles the port configuration, +// which happens on every boot and needs neither a controller nor a running +// application. Application user-data is only decrypted when a domain is +// instantiated, which on a wiped device cannot happen -- the image is gone too. +const ( + restoreWiFiPort = "wlan0" + restoreWiFiSSID = "konvert-restore-ssid" + // restoreWiFiIdentity is the EAP identity. It is what makes the credential + // an encrypted one: evetest builds a CipherBlock for a WiFi network only + // when an identity is set, and sends the network unauthenticated otherwise. + restoreWiFiIdentity = "konvert-restore-identity" + // restoreWiFiPassword is the secret that has to survive. Its value is never + // used to associate with a radio here -- only to be encrypted by the + // controller and decrypted again afterwards -- so any opaque secret does. + restoreWiFiPassword = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" +) + +// resizeTargetSize is the boot-disk size the backup is taken against. These +// tests never run a real resize, so it only has to be a size the tool accepts. +const resizeTargetSize = "78G" + +// backupScriptPath is where the backup script is staged for pillar to run. On +// /persist because that is visible from both the host and the pillar container; +// removed again as soon as it has run. +const backupScriptPath = "/persist/konvert-restore-backup.sh" + +// addEncryptedWiFiPort adds a wireless port whose credentials the controller +// encrypts, which is the thing a restore has to be able to decrypt afterwards. +// +// The radio need not exist. What is being tested is that the credential can be +// unwrapped from the restored key, and nim tries to decrypt it while +// reconciling the port whether or not any hardware answers. +func addEncryptedWiFiPort(devConfig *evetest.EdgeDeviceConfig) { + wifiNet := devConfig.AddNetwork(evetest.WiFiNetworkConfig{ + DHCPNetworkConfig: evetest.DHCPNetworkConfig{ + NetworkType: evecommon.NetworkType_V4, + }, + SSID: restoreWiFiSSID, + // EAP rather than PSK: the identity and password travel together in the + // CipherBlock, which is the object the restore has to be able to unwrap. + KeyScheme: evecommon.WiFiKeyScheme_WPAEAP, + Identity: restoreWiFiIdentity, + Password: restoreWiFiPassword, + }) + devConfig.AddNetworkAdapter(evetest.NetworkAdapterConfig{ + LogicalLabel: restoreWiFiPort, + PhysicalLabel: restoreWiFiPort, + InterfaceName: restoreWiFiPort, + WirelessType: evecommon.WirelessType_WiFi, + NetworkUUID: wifiNet, + Usage: evecommon.PhyIoMemberUsage_PhyIoUsageMgmtAndApps, + // Costlier than the wired port, so the device keeps talking to its + // controller over ethernet and the wireless port is only ever + // configured -- which is all this needs. + Cost: 10, + }) +} + +// assertWiFiCredentialsDecrypted asserts the device holds the wireless port's +// configuration and was able to decrypt its credentials. +// +// Both halves are needed. The port configuration proves the last known +// configuration was recovered and re-applied; the decrypted cipher block proves +// the key that unwraps it was recovered too. Either alone would pass on a +// device that had lost the other. +func assertWiFiCredentialsDecrypted(t Gomega, device *evetest.EdgeDevice, timeout time.Duration) { + t.Eventually(func(g Gomega) { + portConfig, err := runEVE(device, catGlob(devicePortConfigDir+"/*.json")) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(portConfig).To(ContainSubstring(restoreWiFiSSID), + "the device does not have the wireless port configuration back; %s holds:\n%s", + devicePortConfigDir, describeDir(device, devicePortConfigDir)) + + cipherStatus, err := runEVE(device, catGlob(cipherBlockStatusDir+"/*.json")) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(anyCipherBlockDecrypted(cipherStatus)).To(BeTrue(), + "no cipher block was decrypted successfully; %s holds:\n%s\n%s", + cipherBlockStatusDir, describeDir(device, cipherBlockStatusDir), cipherStatus) + }, timeout, 15*time.Second).Should(Succeed()) +} + +// Where the two agents publish what this assertion reads. Both are ephemeral +// publications, so they live under /run rather than /persist. +const ( + devicePortConfigDir = "/run/zedagent/DevicePortConfig" + cipherBlockStatusDir = "/run/nim/CipherBlockStatus" +) + +// catGlob builds a command that prints every file matching a glob and succeeds +// with no output when nothing matches. +// +// A bare `cat ` exits 1 in that case, which reports an absent file as an +// SSH failure and buries the assertion the caller actually wrote. +func catGlob(pattern string) string { + return `eve exec pillar sh -c "cat ` + pattern + ` 2>/dev/null || true"` +} + +// describeDir lists a pubsub directory, so that a failure says what the device +// does have rather than only what it was missing. +func describeDir(device *evetest.EdgeDevice, dir string) string { + out, err := runEVE(device, `eve exec pillar sh -c "ls -la `+dir+` 2>&1 || true"`) + if err != nil { + return fmt.Sprintf("(could not list %s: %v)", dir, err) + } + return out +} + +// anyCipherBlockDecrypted reports whether at least one cipher block was +// unwrapped without error. +func anyCipherBlockDecrypted(raw string) bool { + for _, status := range decodeJSONStream(raw) { + isCipher, _ := status["IsCipher"].(bool) + errMsg, _ := status["Error"].(string) + if isCipher && errMsg == "" { + return true + } + } + return false +} + +// backupIdentityToConfig copies the identity and connectivity files onto the +// CONFIG partition, and arms the flag that makes early boot restore them. +// +// Retried until the backup demonstrably contains the wireless credential and an +// ecdh certificate, rather than run once and trusted: the checkpoint is written +// asynchronously, so a backup taken too early captures a configuration that +// predates the credential and the restore afterwards would be judged against +// something that was never in it. +func backupIdentityToConfig(t Gomega, device *evetest.EdgeDevice) { + script := fmt.Sprintf(`set -u +CFGP=$(findfs PARTLABEL=CONFIG) || { echo "FAIL: no CONFIG partition"; exit 1; } +mkdir -p /tmp/restore-cfg +mountpoint -q /tmp/restore-cfg || mount -t vfat -o rw,iocharset=iso8859-1 "$CFGP" /tmp/restore-cfg \ + || { echo "FAIL: could not mount CONFIG"; exit 1; } +LC=/tmp/restore-cfg/backup-persist/checkpoint/lastconfig +rc=0 +i=0 +while [ $i -lt 18 ]; do + i=$((i+1)) + /usr/bin/storage-resizer backup --persist /persist \ + --backup-dir /tmp/restore-cfg/backup-persist \ + --flag-file /tmp/restore-cfg/repartition-inprogress \ + --target %s > /tmp/restore-backup.out 2>&1 + rc=$? + if [ -f "$LC" ] && tr -d '\0' < "$LC" | grep -q %q \ + && ls /tmp/restore-cfg/backup-persist/certs/ecdh.*.pem >/dev/null 2>&1; then + echo "BACKUP-OK after $i attempt(s)" + break + fi + sync; sleep 10 +done +if [ ! -f "$LC" ] || ! tr -d '\0' < "$LC" | grep -q %q; then + echo "FAIL: the backup never captured the wireless credential" + echo "--- storage-resizer backup (rc=$rc) ---" + cat /tmp/restore-backup.out 2>&1 + echo "--- /persist/checkpoint ---" + ls -la /persist/checkpoint 2>&1 + echo "--- backup dir ---" + ls -laR /tmp/restore-cfg/backup-persist 2>&1 + umount /tmp/restore-cfg 2>/dev/null + exit 1 +fi +# Pillar rotates the previous primary into .bak, so the fallback still predates +# the credential; the corruption step keeps .bak intact and expects to recover +# from it, which only works if it is at least as new as what it replaces. +cp /persist/checkpoint/lastconfig /persist/checkpoint/lastconfig.bak 2>/dev/null || true +sync +umount /tmp/restore-cfg 2>/dev/null +echo "BACKUP-DONE"`, resizeTargetSize, restoreWiFiSSID, restoreWiFiSSID) + + // Run inside pillar: storage-resizer ships in that container, and the + // CONFIG mount has to live in the same mount namespace as the tool writing + // through it. Handed over as a file on /persist, which both the host and + // pillar see, rather than quoted into `sh -c`. + wrapper := fmt.Sprintf(`set -u +cat > %s <<'KONVERT_BACKUP_EOS' +%s +KONVERT_BACKUP_EOS +eve exec pillar sh %s +rc=$? +rm -f %s +exit $rc`, backupScriptPath, script, backupScriptPath, backupScriptPath) + + out, err := runEVEWithTimeout(device, wrapper, 8*time.Minute) + t.Expect(err).NotTo(HaveOccurred(), "the identity backup failed:\n%s", out) + t.Expect(out).To(ContainSubstring("BACKUP-DONE"), "the identity backup failed:\n%s", out) + evetest.Logger().Infof("identity backup: %s", strings.TrimSpace(out)) + device.SyncDisks() +} + +// isolateFromController drops every packet from the device to the controller, +// so that what happens next has to happen without one. +// +// This is the point of both restore tests: a device that can reach its +// controller can simply be told everything again, which proves nothing about +// what it recovered on its own. Done with a firewall rule rather than by +// stopping the controller, so only this device is affected and the harness +// keeps working. +// +// The network model is deep-copied first: the models are package-level values +// shared with every other test in the process. +func isolateFromController(baseModel *api.NetworkModel) { + isolated := proto.CloneOf(baseModel) + if isolated.Firewall == nil { + isolated.Firewall = &api.Firewall{} + } + isolated.Firewall.Rules = append(isolated.Firewall.Rules, &api.FwRule{ + SrcSubnet: "0.0.0.0/0", + DstSubnet: evetest.GetControllerIPv4().String() + "/32", + Action: api.FwAction_FW_DROP, + }) + evetest.Logger().Infof("cutting the device off from the controller at %s", + evetest.GetControllerIPv4()) + evetest.UpdateNetworkModel(isolated) +} + +// restoreControllerAccess puts the network back the way it was and waits for the +// device to check in again. +// +// The wait is not tidiness. Reboots are counted from what the device reports, +// and while it was isolated it could report nothing; the harness audits the +// count as it tears down, so returning before the device has been heard from +// would race that audit and fail the run over a reboot the test asked for. +func restoreControllerAccess(t Gomega, device *evetest.EdgeDevice, baseModel *api.NetworkModel) { + evetest.Logger().Infof("restoring the device's path to the controller") + evetest.UpdateNetworkModel(proto.CloneOf(baseModel)) + + updates, stop := device.WatchDeviceInfo() + defer stop() + t.Eventually(updates, 10*time.Minute).Should(Receive(), + "the device did not report to the controller after its path was restored") +} + +// restoreBaseNetworkModel is the model both restore tests start from and return +// to. +var restoreBaseNetworkModel = netmodels.SingleEthWithDHCP + +// snapshotIdentity records the identity files whose loss would cost the device +// its identity and its way back to a controller. +// +// Recorded by content, not by presence: a file restored empty, or recreated +// blank, would satisfy an existence check and still leave the device unable to +// talk to anything. +func snapshotIdentity(t Gomega, device *evetest.EdgeDevice) map[string]string { + snapshot := make(map[string]string, len(identityFiles)) + for _, path := range identityFiles { + var sum string + t.Eventually(func(g Gomega) { + out, err := runEVE(device, + "eve exec pillar sh -c 'sha256sum "+path+" 2>/dev/null || echo MISSING'") + g.Expect(err).NotTo(HaveOccurred()) + fields := strings.Fields(strings.TrimSpace(out)) + g.Expect(fields).NotTo(BeEmpty(), "could not read %s", path) + sum = fields[0] + }, 2*time.Minute, 5*time.Second).Should(Succeed()) + snapshot[path] = sum + } + return snapshot +} + +// identityFiles are what a device needs to still be itself after /persist is +// lost or damaged. They are compared byte for byte because nothing on the +// device rewrites them: a difference means the restore produced something other +// than what it saved. +var identityFiles = []string{ + "/persist/status/uuid", + "/persist/certs/device.cert.pem", + "/persist/certs/ecdh.cert.pem", + "/persist/status/zedclient/OnboardingStatus/global.json", +} + +// dpcListPath is the port-configuration list, which is restored but cannot be +// compared by content: nim rewrites it as it tests ports, so the copy on disk +// is overtaken as soon as the device runs, and a byte difference is "an +// ordinary newer version" rather than a failed restore (pkg/pillar/docs/ +// diskconvert.md). Whether the configuration really came back is settled by the +// credential assertion in phase 4, which needs it to be both present and valid. +const dpcListPath = "/persist/status/nim/DevicePortConfigList/global.json" + +// assertPortConfigRestored asserts the port-configuration list came back at all. +func assertPortConfigRestored(t Gomega, device *evetest.EdgeDevice) { + t.Eventually(func(g Gomega) { + out, err := runEVE(device, catGlob(dpcListPath)) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(strings.TrimSpace(out)).NotTo(BeEmpty(), + "the port-configuration list did not come back: %s", dpcListPath) + }, 5*time.Minute, 15*time.Second).Should(Succeed()) +} + +// assertIdentityRestored asserts every identity file came back with the content +// it had. Files that were absent to begin with are skipped, since there is +// nothing for them to come back as. +func assertIdentityRestored(t Gomega, device *evetest.EdgeDevice, before map[string]string) { + after := snapshotIdentity(t, device) + for path, want := range before { + if want == "MISSING" { + continue + } + t.Expect(after[path]).To(Equal(want), + "%s did not come back with the content it had", path) + } + assertPortConfigRestored(t, device) +} + +// assertDeviceUUIDUnchanged asserts the device kept the identity it was +// onboarded with, which is the difference between recovering and starting over. +func assertDeviceUUIDUnchanged(t Gomega, device *evetest.EdgeDevice, before string) { + after := readDeviceUUID(t, device) + t.Expect(after).To(Equal(before), + "the device came back with a different UUID, so it did not recover its identity") +} + +// readDeviceUUID returns the UUID the device is running as. +func readDeviceUUID(t Gomega, device *evetest.EdgeDevice) string { + var id string + t.Eventually(func(g Gomega) { + out, err := runEVE(device, "cat /persist/status/uuid") + g.Expect(err).NotTo(HaveOccurred()) + id = strings.TrimSpace(out) + g.Expect(id).NotTo(BeEmpty(), "the device reports no UUID") + }, 5*time.Minute, 10*time.Second).Should(Succeed()) + return id +} diff --git a/evetest/tests/konvert/shell_helpers_test.go b/evetest/tests/konvert/shell_helpers_test.go new file mode 100644 index 00000000000..10cf1e1b454 --- /dev/null +++ b/evetest/tests/konvert/shell_helpers_test.go @@ -0,0 +1,58 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + "strings" + "time" + + // revive:disable:dot-imports + . "github.com/onsi/gomega" + + "github.com/lf-edge/eve/evetest" +) + +// eveShellTimeout bounds a single command run on EVE. +const eveShellTimeout = 30 * time.Second + +// runEVE runs a short command on EVE and returns its stdout with empty and +// logger lines dropped, WITHOUT asserting -- so callers can retry, since EVE's +// SSH and pillar are briefly unavailable after a reboot or across the +// conversion. +// +// Output is returned even when the command failed: for a script that reports +// why it is giving up before exiting non-zero, that output is the whole +// explanation, and discarding it leaves a caller with only an exit status. +func runEVE(device *evetest.EdgeDevice, script string) (string, error) { + return runEVEWithTimeout(device, script, eveShellTimeout) +} + +// runEVEWithTimeout is runEVE for a command that legitimately takes longer than +// a status read -- writing gigabytes, or reading the whole log archive. +func runEVEWithTimeout(device *evetest.EdgeDevice, script string, + timeout time.Duration) (string, error) { + stdout, _, err := device.RunShellScript(script, timeout, 0) + var lines []string + for _, l := range strings.Split(stdout, "\n") { + if strings.TrimSpace(l) == "" || strings.Contains(l, "level=") { + continue + } + lines = append(lines, l) + } + return strings.Join(lines, "\n"), err +} + +// readRunningVersion returns the EVE version the device is running, exactly as +// EVE spells it -- which is what the log records this test later reads back are +// keyed on. +func readRunningVersion(t Gomega, device *evetest.EdgeDevice) string { + var version string + t.Eventually(func(g Gomega) { + out, err := runEVE(device, "cat /run/eve-release") + g.Expect(err).NotTo(HaveOccurred()) + version = strings.TrimSpace(out) + g.Expect(version).NotTo(BeEmpty(), "the device did not report a version") + }, 3*time.Minute, 10*time.Second).Should(Succeed()) + return version +} diff --git a/evetest/tests/konvert/testsuite_test.go b/evetest/tests/konvert/testsuite_test.go new file mode 100644 index 00000000000..e93c145cffe --- /dev/null +++ b/evetest/tests/konvert/testsuite_test.go @@ -0,0 +1,134 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +// Package konvert_test covers the EVE-kvm ↔ EVE-K conversion: the cross-flavor +// base-OS upgrade, and the in-field boot-disk repartition (small → large GPT +// geometry) that the cross-flavor seam arms. +// +// It is a suite of its own rather than part of TestUpgradeSuite because a +// conversion leg is not a single upgrade. Reaching the repartition takes a +// released small-geometry kvm image, a kvm→kvm hop to land the conversion code +// without moving the geometry, and only then the kvm→k hop -- with an offline +// resize and several reboots in between. Folding that into the upgrade suite +// would make a suite worth gating on as expensive as the scenario it is not +// about. +// +// Test files are named for the stage of the conversion they cover: +// +// - upgrade_test.go -- the flavor switch itself +// - repartition_test.go -- the boot-disk conversion, both routes to the space +// - repartition_refused_test.go -- the repartition declined, both reasons +// - repartition_geometry_test.go -- the resulting partition layout, on its own +// - volmig_test.go -- an app volume carried across the conversion +// - firstboot_test.go -- a volume asked for before EVE-K storage exists +// - restore_test.go -- /persist lost or corrupted, recovered offline +// +// Helper files are named for the state they observe: +// +// - device_helpers_test.go -- shared parameters, device setup, disk sizing +// - shell_helpers_test.go -- running a command on EVE +// - geometry_helpers_test.go -- partition table, storage-resizer decisions +// - vault_helpers_test.go -- vault unlock method and the TPM seal +// - restore_helpers_test.go -- identity backup, controller isolation +// - cluster_helpers_test.go -- EVE-K bring-up: k3s, volumemgr, Longhorn +// - app_helpers_test.go -- app deployment, SSH, volume markers, blob reuse +// - download_helpers_test.go -- what the downloader pulled, for blob reuse +// - diag_helpers_test.go -- best-effort captures taken when an assertion +// is about to fail +// +// Every test here needs an EVE that carries the conversion work (lf-edge/eve#6036 +// and #6063). On a stock build baseosmgr refuses a kvm↔k base-OS update outright +// (handlebaseos.go, "Upgrade to EVE-k ... is not supported"), so the cross-flavor +// hop fails before any of this is exercised. +// +// Device sizing matches the eden escripts these are ported from +// (lf-edge/eden#1209): 4 vCPUs and 8 GiB of RAM, eden's own defaults, which +// those escripts never override. Raising it makes EVE-K and Longhorn converge +// more easily and stops the tests covering the envelope the escripts cover, so +// the floors stay where eden put them and move only through RAM_SIZE_MB / CPUS. +package konvert_test + +import ( + "testing" + + "github.com/lf-edge/eve/evetest" +) + +// Parameters shared by every test in the package. The conversion has two +// version axes (where the device starts, and the build under test) and two +// hypervisor axes (the flavor it starts on, and the flavor it converts to), and +// each test selects points on them rather than carrying its own copy. +const ( + // initialEVEVersionParamKey names the image the device boots first. For the + // repartition tests it must be a SMALL-geometry release, or the conversion + // is a no-op that proves nothing; for the flavor-switch tests it defaults to + // the build under test. + initialEVEVersionParamKey = "INITIAL_EVE_VERSION" + // initialEVERepoParamKey overrides the repo the initial image comes from. + initialEVERepoParamKey = "INITIAL_EVE_REPO" + // initialHypervisorParamKey is the flavor the device starts on. + initialHypervisorParamKey = "INITIAL_HYPERVISOR" + // altEVEVersionParamKey names the version of the *other* flavor, for the + // tests that switch flavor without repartitioning. + altEVEVersionParamKey = "ALT_EVE_VERSION" + // expectDecisionParamKey selects which way the repartition must free the + // space the EVE-K layout needs. + expectDecisionParamKey = "EXPECT_DECISION" + // fillPersistGiBParamKey sizes the pre-conversion fill that gives a shrink + // real blocks to relocate. + fillPersistGiBParamKey = "FILL_PERSIST_GIB" + // refuseReasonParamKey selects why the conversion must be refused. + refuseReasonParamKey = "REFUSE_REASON" +) + +// Defaults shared across the package, reproducing the eden escripts' own, so +// that a run with nothing set matches what eden runs. +const ( + // defaultInitialEVEVersion is the release the device is brought up on + // before the conversion. It has to land inside assertSmallGeometry's window + // -- ESP under 256 MiB, IMGA and IMGB under 1 GiB, no ESP-B -- or a run + // fails at the baseline assert rather than converting anything. + // + // Releases do not all lay the boot disk out the same way. In + // mkimage-raw-efi's make-raw the rootfs partition is a fixed 300 MiB up to + // 10.1.0 and a fixed 512 MiB at 10.2.0; 12.1.0 turned it into a floor the + // actual rootfs may exceed, and 14.5 raises that floor to 1 GiB. 10.1.0 is + // the smallest layout inside the window, and its size is fixed rather than + // a floor, so the baseline geometry cannot drift with rootfs content. + defaultInitialEVEVersion = "10.1.0" + + // bootDiskMiB is the single-boot-disk size the escripts use, and the size + // EVE-K plus Longhorn needs (prep-kvm-to-k-topology.sh BOOT_DISK_MB). + bootDiskMiB = 65536 + // splitBootDiskMiB is the boot disk the grow route starts on; the rest of + // bootDiskMiB is added afterwards as a free tail + // (prep-kvm-to-k-topology.sh EVE_DISK_MB). + splitBootDiskMiB = 32768 + // defaultFillPersistGiB matches the escripts' FILL_PERSIST_GIB. It must stay + // below the post-shrink size of /persist, or the shrink cannot fit what the + // fill put there. + defaultFillPersistGiB = 33 + // deviceRAMMiB and deviceCPUs are eden's defaults + // (pkg/defaults/defaults.go DefaultMemory / DefaultCpus), which the + // escripts do not override. + deviceRAMMiB = 8192 + deviceCPUs = 4 +) + +// TestKonvertSuite runs the conversion tests in an order that lets the +// framework reuse a device where it can: the flavor-switch tests need no +// repartition, so they share one device. +func TestKonvertSuite(test *testing.T) { + evetest.Init(test) + defer evetest.Close() + + evetest.DefineTestParameters( + evetest.TPMParameter(), + evetest.RAMSizeMiBParameter(), + evetest.CPUsParameter(), + ) + + evetest.RunTestSuite( + evetest.TestCase{Test: TestKvmToKUpgrade}, + ) +} diff --git a/evetest/tests/konvert/upgrade_helpers_test.go b/evetest/tests/konvert/upgrade_helpers_test.go new file mode 100644 index 00000000000..150d252d865 --- /dev/null +++ b/evetest/tests/konvert/upgrade_helpers_test.go @@ -0,0 +1,81 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + // revive:disable:dot-imports + . "github.com/onsi/gomega" + + pillartypes "github.com/lf-edge/eve/pkg/pillar/types" + + "github.com/lf-edge/eve/evetest" +) + +// altHypervisor returns the flavor on the other side of the cross-flavor seam. +func altHypervisor(h evetest.Hypervisor) evetest.Hypervisor { + if h == evetest.HypervisorKubevirt { + return evetest.HypervisorKVM + } + return evetest.HypervisorKubevirt +} + +// resolveCrossFlavorParams resolves the shared axes for a flavor-switch test, +// starting the device on the build under test unless the operator named a +// version themselves. +func resolveCrossFlavorParams(t Gomega) deviceParams { + p := resolveDeviceParams(t) + if p.initialVersion == "" { + p.initialVersion = p.targetVersion + } + return p +} + +// resolveAltVersion reads the alternate-flavor version, defaulting to the +// initial one: the cross-flavor tests hop between two flavors of the *same* +// version, so that the flavor is the only thing that changed. +func resolveAltVersion(p deviceParams) string { + version := evetest.GetTestParameter[string](altEVEVersionParamKey) + if version == "" { + version = p.initialVersion + } + return version +} + +// altParameterDefinitions declares the alternate-flavor axes. +func altParameterDefinitions() []evetest.TestParameterDefinition { + return []evetest.TestParameterDefinition{ + { + Key: altEVEVersionParamKey, + DefaultValue: "", + Description: evetest.TestParameterDescription{ + Summary: "Released EVE version of the alternate flavor", + Default: "\"\" (the same version the device started on)", + }, + }, + } +} + +// shortBaseImageCooldown cuts the wait EVE imposes before it commits a new base +// image, which is dead time for a test that is not measuring it. +// +// Built from an empty map, not a defaulted one: applying a fully populated map +// sets every property the device did not ask about back to its default, which +// includes clearing the SSH authorized key the harness injected -- leaving the +// device up, addressable, and refusing every connection on port 22. +func shortBaseImageCooldown() *pillartypes.ConfigItemValueMap { + props := pillartypes.NewConfigItemValueMap() + props.SetGlobalValueInt(pillartypes.MintimeUpdateSuccess, 30) + return props +} + +// upgradeAcrossFlavors drives one cross-flavor base-OS update and waits for the +// device to report itself running it. +// +// Which repository the target is pulled from is EVETEST_EVE_REPO's to decide, +// the same as for any other upgrade; only the initial device can be pointed +// somewhere else, through RequireEdgeDevice.WithEVERepo. +func upgradeAcrossFlavors(device *evetest.EdgeDevice, + version string, hypervisor evetest.Hypervisor) { + device.UpgradeEVE(version, hypervisor, evetest.BaseOSDatastoreHTTP, true, false) +} diff --git a/evetest/tests/konvert/upgrade_test.go b/evetest/tests/konvert/upgrade_test.go new file mode 100644 index 00000000000..7809c8e7b27 --- /dev/null +++ b/evetest/tests/konvert/upgrade_test.go @@ -0,0 +1,79 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + "testing" + + // revive:disable:dot-imports + . "github.com/onsi/gomega" + + "github.com/lf-edge/eve/evetest" +) + +// TestKvmToKUpgrade asserts EVE accepts a base-OS image of the other flavor +// when the device holds no volumes, and comes back on it. +// +// The flavor switch is normally refused outright: /persist is laid out +// differently for EVE-K, so baseosmgr blocks a kvm↔k update rather than risk +// meeting a layout it cannot read. Relaxing that to "allowed while no volume +// exists" is the first step towards the in-field conversion, and this is the +// happy path of it -- no repartition involved, the flavor the only variable. +// Both images are the build under test: the relaxation is in no release, so a +// released source would refuse the update whatever it was offered. +// +// Phases: +// 1. Assert the device holds no live volumes, which is the precondition the +// relaxation is conditioned on. +// 2. Upgrade across the flavor seam and wait for the device to report itself +// active on the new flavor. +// 3. Push the reverse update and assert it is refused. EVE-K is a one-way +// door -- docs/EVE-K.md states an upgrade from HV=k to another HV type is +// not supported, and baseosmgr blocks it unconditionally, with none of the +// conditions that let the forward direction through. Asserting the refusal +// pins that, and keeps a future relaxation from going unnoticed. +func TestKvmToKUpgrade(test *testing.T) { + evetestT := evetest.Init(test) + t := NewGomegaWithT(evetestT) + defer evetest.Close() + + defineCrossFlavorParameters() + p := resolveCrossFlavorParams(t) + altVersion := resolveAltVersion(p) + altHV := altHypervisor(p.initialHypervisor) + + device := setupDevice(t, p, evetest.FilesystemEXT4, nil, + evetest.CreateFromScratchWithLiveImage) + log := evetest.Logger() + + devConfig := evetest.NewEdgeDeviceConfig(devName) + applyMgmtNetwork(device, devConfig) + devConfig.SetConfigProperties(shortBaseImageCooldown()) + device.ApplyConfig(devConfig, true, true) + + log.Infof("pre-flight: the device must hold no live volumes") + assertNoLiveVolumes(t, device) + evetest.Checkpoint("no-volumes") + + conversionOK := false + defer func() { + if !conversionOK { + dumpConversionFailure(device) + } + }() + + log.Infof("crossing the flavor seam: %s → %s at %s", p.initialHypervisor, altHV, altVersion) + upgradeAcrossFlavors(device, altVersion, altHV) + conversionOK = true + evetest.Checkpoint("crossed-to-alt-flavor") + + // The reverse is not a supported upgrade, so it is pushed as one that must + // be refused rather than one that must succeed. + altRunningVersion := readRunningVersion(t, device) + log.Infof("the reverse update (%s → %s) must be refused", altHV, p.initialHypervisor) + device.RequestRefusedEVEUpgrade(p.initialVersion, p.initialHypervisor, + evetest.BaseOSDatastoreHTTP) + assertConversionDeclined(t, device, altRunningVersion) + evetest.Checkpoint("reverse-refused") +} diff --git a/evetest/tests/konvert/vault_helpers_test.go b/evetest/tests/konvert/vault_helpers_test.go new file mode 100644 index 00000000000..3cf09f19dab --- /dev/null +++ b/evetest/tests/konvert/vault_helpers_test.go @@ -0,0 +1,243 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + "regexp" + "sort" + "strconv" + "strings" + "time" + + // revive:disable:dot-imports + . "github.com/onsi/gomega" + + "github.com/lf-edge/eve/evetest" +) + +// How vaultmgr reports the vault was unlocked, as the VaultStatus.UnlockMethod +// values appear on the wire. +const ( + unlockLocal = "local" + unlockController = "controller" + unlockNoTPM = "no-tpm" +) + +// settleVaultLocal reboots until the vault unlocks from its own TPM seal rather +// than from the controller's key. +// +// A new rootfs moves the PCRs the seal is bound to, so the first boot after an +// upgrade necessarily falls back to the controller key and re-seals against the +// new measurements; only the boot after that can unlock locally. The conversion +// has to start from the settled state, because a local unlock on the last +// pre-conversion boot is exactly what the seal assertion afterwards looks for. +func settleVaultLocal(t Gomega, device *evetest.EdgeDevice) { + log := evetest.Logger() + const maxReboots = 4 + for attempt := 1; attempt <= maxReboots; attempt++ { + var decided string + t.Eventually(func() string { + decided = readVaultUnlockMethod(device) + return decided + }, 12*time.Minute, 10*time.Second).ShouldNot(BeEmpty(), + "the vault never reported an unlock method") + + switch decided { + case unlockLocal: + log.Infof("vault settled on a local TPM unlock") + return + case unlockNoTPM: + t.Expect(decided).NotTo(Equal(unlockNoTPM), + "the vault reports no TPM; this test needs one") + return + default: + log.Infof("vault unlocked from the controller key (attempt %d/%d); rebooting to re-seal", + attempt, maxReboots) + device.RequestReboot(true) + } + } + t.Expect(false).To(BeTrue(), + "the vault did not settle on a local unlock within %d reboots", maxReboots) +} + +// readVaultUnlockMethod returns how the vault was unlocked, or "" while +// vaultmgr has not published yet. +func readVaultUnlockMethod(device *evetest.EdgeDevice) string { + out, _, err := device.RunShellScript( + `eve exec pillar sh -c "cat /run/vaultmgr/VaultStatus/*.json 2>/dev/null"`, + eveShellTimeout, 0) + if err != nil { + return "" + } + switch { + case strings.Contains(out, `"UnlockMethod":1`): + return unlockLocal + case strings.Contains(out, `"UnlockMethod":2`): + return unlockController + case strings.Contains(out, `"UnlockMethod":3`): + return unlockNoTPM + } + return "" +} + +// newlogUnlockScan pulls every per-boot version marker and vault-unlock line out +// of the device's own log archive. +// +// It reads the whole of /persist/newlog, not just collect/: newlogd rotates a +// stream out of collect/ after about five minutes or 550 KB, so by the time the +// conversion has finished the boots this needs are in the gzipped queues. One +// zcat per file because busybox find has no `-exec ... +`, and -f so the same +// command handles the plaintext chunks in collect/. +const newlogUnlockScan = `eve exec pillar sh -c "find /persist/newlog -name \"dev.log.*\" -exec zcat -f {} \; 2>/dev/null | grep -aE \"EVE version: |unlocked: method=|local TPM unseal FAILED\""` + +// newlogScanTimeout bounds that scan: it decompresses the whole archive, which +// is thousands of files on a device that has been up for a while. +const newlogScanTimeout = 3 * time.Minute + +// vaultUnlock is one unlock event, attributed to the EVE version that was +// running when it happened. +type vaultUnlock struct { + version string + method string + // pcrs are the PCRs that failed to match, for a controller-key unlock or a + // failed unseal; empty for a local one. + pcrs []string +} + +// assertSealSurvivedRepartition asserts the boot-disk repartition did not break +// the TPM seal, judged after the fact from the device's own logs. +// +// It has to be judged this way. The live window in which the post-conversion +// unlock is readable is a minute or two, and racing it makes the test flaky; +// /persist survives the repartition, so the record of every boot is still there +// afterwards. Two independent gates: +// +// 1. The last boot on the conversion-capable kvm image must have unsealed +// locally. That is the boot after the repartition and before EVE-K, on which +// only PCR5 changed -- and PCR5 is excluded from the seal precisely so that +// a repartition does not invalidate it. Keyed on that exact version rather +// than "any kvm boot", so a future baseline that also unlocks locally cannot +// satisfy it by accident. +// 2. No controller-key or failed unseal anywhere lists PCR5 among its +// mismatches. A PCR5-driven re-seal means the repartition did break the +// seal, whatever gate 1 saw. +// +// The EVE-K boot unlocking from the controller key is expected and not a +// failure: a new rootfs moves PCRs 8, 9 and 13. +func assertSealSurvivedRepartition(t Gomega, device *evetest.EdgeDevice, kvmVersion string) { + log := evetest.Logger() + var raw string + t.Eventually(func(g Gomega) { + var err error + raw, err = runEVEWithTimeout(device, newlogUnlockScan, newlogScanTimeout) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(raw).NotTo(BeEmpty(), "found no unlock records in /persist/newlog") + }, 5*time.Minute, 15*time.Second).Should(Succeed()) + + unlocks := parseVaultUnlocks(raw) + for _, u := range unlocks { + log.Infof("unlock: version=%s method=%s pcrs=%v", u.version, u.method, u.pcrs) + } + t.Expect(unlocks).NotTo(BeEmpty(), + "no vault unlock was recorded in /persist/newlog, so the seal cannot be judged") + + var pcr5Reseals []vaultUnlock + var onKVM []vaultUnlock + for _, u := range unlocks { + for _, p := range u.pcrs { + if p == "5" { + pcr5Reseals = append(pcr5Reseals, u) + break + } + } + if u.version == kvmVersion { + onKVM = append(onKVM, u) + } + } + + t.Expect(pcr5Reseals).To(BeEmpty(), + "PCR5 appears in a re-seal or failed unseal, so the repartition broke the TPM seal: %v", + pcr5Reseals) + t.Expect(onKVM).NotTo(BeEmpty(), + "no vault unlock was recorded on %s, so the post-repartition boot cannot be judged", + kvmVersion) + t.Expect(onKVM[len(onKVM)-1].method).To(Equal(unlockLocal), + "the last boot on %s did not unseal locally, so the repartition cost the seal: %v", + kvmVersion, onKVM[len(onKVM)-1]) +} + +var ( + // logSecondsRE and logNanosRE order the records; newlog lines carry the + // timestamp as a structured field rather than in message order. + logSecondsRE = regexp.MustCompile(`"seconds":(\d+)`) + logNanosRE = regexp.MustCompile(`"nanos":(\d+)`) + // eveVersionRE reads the per-boot version marker. + eveVersionRE = regexp.MustCompile(`EVE version: ([0-9][A-Za-z0-9._+-]*)`) + // mismatchPCRsRE reads the PCR list off a controller-key or failed unseal. + mismatchPCRsRE = regexp.MustCompile(`mismatching ?PCRs=\[([0-9 ]*)\]`) +) + +// parseVaultUnlocks turns the scanned log lines into unlock events, each +// attributed to the version marker that preceded it. +// +// The version marker has to come from pillar.out: baseosmgr also logs a +// "to EVE version X" line naming the version being installed, which is a +// different thing entirely and would attribute an unlock to the image the +// device was moving to rather than the one it was running. +func parseVaultUnlocks(raw string) []vaultUnlock { + type event struct { + seconds, nanos int64 + kind string + value string + pcrs []string + } + var events []event + for _, line := range strings.Split(raw, "\n") { + var secs, nanos int64 + if m := logSecondsRE.FindStringSubmatch(line); m != nil { + secs, _ = strconv.ParseInt(m[1], 10, 64) + } + if m := logNanosRE.FindStringSubmatch(line); m != nil { + nanos, _ = strconv.ParseInt(m[1], 10, 64) + } + switch { + case strings.Contains(line, "pillar.out") && strings.Contains(line, "EVE version:"): + if m := eveVersionRE.FindStringSubmatch(line); m != nil { + events = append(events, event{secs, nanos, "version", m[1], nil}) + } + case strings.Contains(line, "unlocked: method=tpm-local-sealed"): + events = append(events, event{secs, nanos, "unlock", unlockLocal, nil}) + case strings.Contains(line, "method=controller-key"): + events = append(events, event{secs, nanos, "unlock", unlockController, mismatchedPCRs(line)}) + case strings.Contains(line, "unseal FAILED"): + events = append(events, event{secs, nanos, "unlock", "failed", mismatchedPCRs(line)}) + } + } + sort.SliceStable(events, func(i, j int) bool { + if events[i].seconds != events[j].seconds { + return events[i].seconds < events[j].seconds + } + return events[i].nanos < events[j].nanos + }) + + var unlocks []vaultUnlock + current := "" + for _, e := range events { + if e.kind == "version" { + current = e.value + continue + } + unlocks = append(unlocks, vaultUnlock{version: current, method: e.value, pcrs: e.pcrs}) + } + return unlocks +} + +// mismatchedPCRs reads the PCR list off an unlock line, or nil when it has none. +func mismatchedPCRs(line string) []string { + m := mismatchPCRsRE.FindStringSubmatch(line) + if m == nil { + return nil + } + return strings.Fields(m[1]) +} From 95e3e876e79d879ec6438441b28153faa8093e1f Mon Sep 17 00:00:00 2001 From: eriknordmark Date: Wed, 9 Sep 2026 22:59:02 +0200 Subject: [PATCH 03/10] evetest: blobs survive the flavor switch Image blobs already on the device must outlive the flavor switch, and a deployment afterwards must reuse them rather than download again. Staged as a bare ContentTree rather than a volume so the answer is about the blobs alone. A volume would pull in the PVC and CDI machinery EVE-K stands up behind it, and a failure there would look identical to the blobs having been lost -- a different and much less interesting answer. Signed-off-by: eriknordmark Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01NZEoFvMK2UHByU3LAeXsxA --- evetest/tests/konvert/contenttree_test.go | 97 +++++++++++++++++++++++ evetest/tests/konvert/testsuite_test.go | 4 + 2 files changed, 101 insertions(+) create mode 100644 evetest/tests/konvert/contenttree_test.go diff --git a/evetest/tests/konvert/contenttree_test.go b/evetest/tests/konvert/contenttree_test.go new file mode 100644 index 00000000000..1737c26742c --- /dev/null +++ b/evetest/tests/konvert/contenttree_test.go @@ -0,0 +1,97 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + "testing" + "time" + + // revive:disable:dot-imports + . "github.com/onsi/gomega" + + "github.com/lf-edge/eve/evetest" +) + +// TestKvmToKContentTree asserts image blobs already on the device survive the +// flavor switch, and that deploying from them afterwards downloads nothing. +// +// The point of staging a bare ContentTree rather than a volume is to ask only +// about the blobs. A volume would drag in the PVC and CDI machinery that EVE-K +// stands up after the switch, and a failure there would look identical to the +// blobs having been lost -- which is a different, and much less interesting, +// answer. +// +// Phases: +// 1. Stage a ContentTree on the starting flavor and wait for its blobs to land. +// 2. Cross the flavor seam. +// 3. Assert the ContentTree is still there, and that deploying an app from +// the same image introduces no content the device did not already hold. +func TestKvmToKContentTree(test *testing.T) { + evetestT := evetest.Init(test) + t := NewGomegaWithT(evetestT) + defer evetest.Close() + + defineCrossFlavorParameters() + p := resolveCrossFlavorParams(t) + altVersion := resolveAltVersion(p) + altHV := altHypervisor(p.initialHypervisor) + + device := setupDevice(t, p, evetest.FilesystemEXT4, nil, + evetest.CreateFromScratchWithLiveImage) + log := evetest.Logger() + + devConfig := evetest.NewEdgeDeviceConfig(devName) + applyMgmtNetwork(device, devConfig) + devConfig.SetConfigProperties(shortBaseImageCooldown()) + device.ApplyConfig(devConfig, true, true) + + log.Infof("staging a ContentTree on %s", p.initialHypervisor) + ctUUID := devConfig.AddContentTree("konvert-staged-image", + evetest.DockerContainer{ImageName: appImageName, Tag: appImageTag}) + device.ApplyConfig(devConfig, true, true) + assertContentTreeAvailable(t, device, ctUUID, 20*time.Minute) + evetest.Checkpoint("contenttree-staged") + + conversionOK := false + defer func() { + if !conversionOK { + dumpConversionFailure(device) + } + }() + log.Infof("crossing the flavor seam: %s → %s", p.initialHypervisor, altHV) + upgradeAcrossFlavors(device, altVersion, altHV) + conversionOK = true + + log.Infof("the staged ContentTree must still be on %s", altHV) + assertContentTreeAvailable(t, device, ctUUID, 20*time.Minute) + evetest.Checkpoint("contenttree-survived") + + if altHV == evetest.HypervisorKubevirt { + waitClusterStorageReady(t, device) + } + + // Snapshotted here, after the crossing's reboot: the downloader's byte + // counter lives under /run and starts again at zero on every boot, so a + // reading taken before the crossing could not be compared with one after. + beforeBytes := snapshotDownloaderBytes(t, device) + log.Infof("deploying from the staged image must download nothing") + niUUID := devConfig.AddNetworkInstance(evetest.SwitchNetworkInstanceConfig{ + DisplayName: "switch-ni", + Port: "eth0", + }) + appUUID := addTestApp(devConfig, "konvert-reuse-app", niUUID) + device.ApplyConfig(devConfig, false, false) + + appOK := false + defer func() { + if !appOK { + dumpClusterStorage(device) + dumpAppNetwork(device, "after the flavor switch") + } + }() + assertAppReady(t, device, appUUID, appRunningAfterSwitchTimeout) + appOK = true + assertBlobsReused(t, device, beforeBytes) + evetest.Checkpoint("blobs-reused") +} diff --git a/evetest/tests/konvert/testsuite_test.go b/evetest/tests/konvert/testsuite_test.go index e93c145cffe..b161f8fbc69 100644 --- a/evetest/tests/konvert/testsuite_test.go +++ b/evetest/tests/konvert/testsuite_test.go @@ -129,6 +129,10 @@ func TestKonvertSuite(test *testing.T) { ) evetest.RunTestSuite( + // Grouped by what each test needs of its device, so the framework can + // reuse one where the requirements match: the flavor-switch ext4 tests + // first, then the ones that need a different disk or filesystem. evetest.TestCase{Test: TestKvmToKUpgrade}, + evetest.TestCase{Test: TestKvmToKContentTree}, ) } From cd36febecb8de13642bc5bb5822d9ce0d2db711e Mon Sep 17 00:00:00 2001 From: eriknordmark Date: Wed, 9 Sep 2026 22:59:02 +0200 Subject: [PATCH 04/10] evetest: an app taken across the flavor switch Deleting an application before the switch and redeploying it after is the recipe that works today: carrying a live app through depends on machinery a single-node EVE-K cannot yet schedule, while delete-and-redeploy needs only the cached blobs to outlive the gap. They do, but only because the deferred content delete is stretched past the length of the gap first. Otherwise EVE reclaims them as soon as the app that referenced them is gone, and the redeploy quietly pays for a full download -- which would still pass a test that only checked the app came back. Signed-off-by: eriknordmark Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01NZEoFvMK2UHByU3LAeXsxA --- evetest/tests/konvert/apprecreate_test.go | 122 ++++++++++++++++++++++ evetest/tests/konvert/testsuite_test.go | 1 + 2 files changed, 123 insertions(+) create mode 100644 evetest/tests/konvert/apprecreate_test.go diff --git a/evetest/tests/konvert/apprecreate_test.go b/evetest/tests/konvert/apprecreate_test.go new file mode 100644 index 00000000000..ad9fa24611a --- /dev/null +++ b/evetest/tests/konvert/apprecreate_test.go @@ -0,0 +1,122 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + "testing" + "time" + + // revive:disable:dot-imports + . "github.com/onsi/gomega" + + pillartypes "github.com/lf-edge/eve/pkg/pillar/types" + + "github.com/lf-edge/eve/evetest" +) + +// TestKvmToKAppRecreate asserts an app can be taken across the flavor seam by +// deleting it before the switch and redeploying it after, without its image +// being downloaded a second time. +// +// This is the recipe that works today: carrying a live app and its volume +// through the switch depends on machinery that a single-node EVE-K cannot yet +// schedule, whereas delete-and-redeploy only needs the cached blobs to outlive +// the gap. They do, but only because the deferred content delete is stretched +// past the length of the gap first -- otherwise EVE reclaims them as soon as +// the app that referenced them is gone, and the redeploy pays for a full +// download. +// +// Phases: +// 1. Deploy the app on the starting flavor and confirm it works. +// 2. Stretch the deferred content delete, then delete the app and its network. +// 3. Cross the flavor seam. +// 4. Redeploy the same app and assert it works and downloaded nothing. +func TestKvmToKAppRecreate(test *testing.T) { + evetestT := evetest.Init(test) + t := NewGomegaWithT(evetestT) + defer evetest.Close() + + defineCrossFlavorParameters() + p := resolveCrossFlavorParams(t) + altVersion := resolveAltVersion(p) + altHV := altHypervisor(p.initialHypervisor) + + device := setupDevice(t, p, evetest.FilesystemEXT4, nil, + evetest.CreateFromScratchWithLiveImage) + log := evetest.Logger() + + devConfig := evetest.NewEdgeDeviceConfig(devName) + applyMgmtNetwork(device, devConfig) + devConfig.SetConfigProperties(shortBaseImageCooldown()) + device.ApplyConfig(devConfig, true, true) + + log.Infof("deploying the app on %s", p.initialHypervisor) + niUUID := devConfig.AddNetworkInstance(evetest.SwitchNetworkInstanceConfig{ + DisplayName: "switch-ni", + Port: "eth0", + }) + appUUID := addTestApp(devConfig, "konvert-recreate-app", niUUID) + device.ApplyConfig(devConfig, false, false) + assertAppReady(t, device, appUUID, 15*time.Minute) + dumpAppNetwork(device, "before the flavor switch (working)") + evetest.Checkpoint("app-running-before") + + // Without this the blobs are collected the moment the app is deleted, and + // the redeploy below measures a fresh download instead of a reuse. + log.Infof("stretching the deferred content delete past the switch") + props := shortBaseImageCooldown() + props.SetGlobalValueInt(pillartypes.DeferContentDelete, 24*60*60) + devConfig.SetConfigProperties(props) + device.ApplyConfig(devConfig, true, true) + + log.Infof("deleting the app and its network") + devConfig.DeleteApplication(appUUID) + device.ApplyConfig(devConfig, true, true) + devConfig.DeleteNetworkInstance(niUUID) + device.ApplyConfig(devConfig, true, true) + assertNoLiveVolumes(t, device) + evetest.Checkpoint("app-deleted") + + conversionOK := false + defer func() { + if !conversionOK { + dumpConversionFailure(device) + } + }() + log.Infof("crossing the flavor seam: %s → %s", p.initialHypervisor, altHV) + upgradeAcrossFlavors(device, altVersion, altHV) + conversionOK = true + evetest.Checkpoint("crossed-to-alt-flavor") + + if altHV == evetest.HypervisorKubevirt { + waitClusterStorageReady(t, device) + } + + // After the crossing's reboot, for the reason snapshotDownloaderBytes gives. + beforeBytes := snapshotDownloaderBytes(t, device) + log.Infof("redeploying the same app on %s", altHV) + newNIUUID := devConfig.AddNetworkInstance(evetest.SwitchNetworkInstanceConfig{ + DisplayName: "switch-ni", + Port: "eth0", + }) + newAppUUID := addTestApp(devConfig, "konvert-recreate-app", newNIUUID) + device.ApplyConfig(devConfig, false, false) + + appOK := false + defer func() { + if !appOK { + dumpClusterStorage(device) + dumpAppNetwork(device, "after the flavor switch (app FAILED)") + } + }() + assertAppReady(t, device, newAppUUID, appRunningAfterSwitchTimeout) + appOK = true + assertBlobsReused(t, device, beforeBytes) + evetest.Checkpoint("app-recreated") + + // Put the collector back the way it was, so a device reused by the next + // test in the suite is not left holding blobs for a day. + devConfig.SetConfigProperties(shortBaseImageCooldown()) + device.ApplyConfig(devConfig, true, true) +} diff --git a/evetest/tests/konvert/testsuite_test.go b/evetest/tests/konvert/testsuite_test.go index b161f8fbc69..3e2d5d0a867 100644 --- a/evetest/tests/konvert/testsuite_test.go +++ b/evetest/tests/konvert/testsuite_test.go @@ -134,5 +134,6 @@ func TestKonvertSuite(test *testing.T) { // first, then the ones that need a different disk or filesystem. evetest.TestCase{Test: TestKvmToKUpgrade}, evetest.TestCase{Test: TestKvmToKContentTree}, + evetest.TestCase{Test: TestKvmToKAppRecreate}, ) } From c4cacb4da40786e105678cc868a262bdafea5bf4 Mon Sep 17 00:00:00 2001 From: eriknordmark Date: Wed, 9 Sep 2026 22:59:03 +0200 Subject: [PATCH 05/10] evetest: in-field boot-disk repartition test Drives the conversion the way a fielded device reaches it: a released small-geometry EVE-kvm image, a same-flavor hop that lands the conversion code without moving the disk, and only then the flavor change whose cross-flavor seam arms the offline resize. Going straight to EVE-K would exercise a path no device in the field can take. The route to the space is the axis. With a full boot disk /persist must shrink, which is the field layout and the harder path, since resize2fs relocates live blocks; with an unallocated tail the partitions grow into it and /persist is untouched. Both routes end at the same layout, so the route is asserted before the conversion from storage-resizer's own pre-flight decision, and confirmed after by what became of /persist. The shrink variant fills /persist first, so there are real blocks to move rather than free space to discard. Whether the repartition cost the TPM seal is judged from the device's own logs rather than live: the window in which the post-conversion unlock is readable is a minute or two, and /persist carries the record across the reboots anyway. The last boot on the conversion-capable image must have unsealed locally, and no re-seal anywhere may name PCR5 -- the measurement the repartition moves, and the one the seal deliberately excludes. The EVE-K boot falling back to the controller key is expected, since a new rootfs moves other PCRs. Signed-off-by: eriknordmark Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01NZEoFvMK2UHByU3LAeXsxA --- .../tests/konvert/geometry_helpers_test.go | 86 ++++-- evetest/tests/konvert/repartition_test.go | 257 ++++++++++++++++++ evetest/tests/konvert/testsuite_test.go | 17 ++ evetest/tests/konvert/vault_helpers_test.go | 46 ++-- 4 files changed, 361 insertions(+), 45 deletions(-) create mode 100644 evetest/tests/konvert/repartition_test.go diff --git a/evetest/tests/konvert/geometry_helpers_test.go b/evetest/tests/konvert/geometry_helpers_test.go index 71ee1a93ef8..0130196b80a 100644 --- a/evetest/tests/konvert/geometry_helpers_test.go +++ b/evetest/tests/konvert/geometry_helpers_test.go @@ -69,6 +69,10 @@ const ( gptSectorSize = 512 ) +// persistFillDir is where the pre-conversion fill is written, so the fill and +// the cleanup that frees it cannot drift apart. +const persistFillDir = "/persist/konvert-fill" + // fillPersistTimeout bounds the pre-conversion fill. It is generous because the // work is proportional to the fill size and runs against a virtual disk. const fillPersistTimeout = 40 * time.Minute @@ -324,33 +328,64 @@ func assertCheckDecision(t Gomega, device *evetest.EdgeDevice, want string) { }, 3*time.Minute, 10*time.Second).Should(Succeed()) } -// fillPersist writes gib GiB into /persist so that the offline shrink has real -// blocks to relocate rather than free space to discard. +// Shaping constants for the pre-conversion fill. peakFillPercent is how full +// /persist is driven before trimming, and fillChunkMiB the size of each numbered +// file -- large enough that the loop is not dominated by process startup, small +// enough that the trim can approach the target closely. +const ( + peakFillPercent = 90 + fillChunkMiB = 1024 +) + +// fillPersist leaves /persist holding data ABOVE where the shrink boundary will +// fall, so the offline resize2fs has to relocate it. // -// Without it the shrink is a much weaker test: resize2fs has nothing to move, -// so the relocation path -- the part that can lose data if it is interrupted -- -// is never exercised. +// Filling straight to the target size does not work, and that is why this is +// more than a single dd: a freshly formatted ext4 allocates sequentially created +// files from low blocks upward, so data written directly to the target sits +// below the boundary and the shrink moves nothing. Writing zeros compounds it, +// since they cost almost nothing to store on a sparse image. +// +// So: fill to peakFillPercent of the filesystem with equal-size numbered files of +// incompressible bytes, pushing allocation into the high block groups, then +// delete the earliest -- lowest-block -- files until usage falls back to the +// target. What survives is concentrated above the boundary, which is exactly +// what resize2fs then has to move down. func fillPersist(t Gomega, device *evetest.EdgeDevice, gib int) { if gib <= 0 { return } log := evetest.Logger() - log.Infof("pre-filling /persist with %d GiB so the shrink has blocks to relocate", gib) - script := fmt.Sprintf(`set -e -mkdir -p /persist/konvert-fill + log.Infof("filling /persist to %d%% then trimming to %d GiB, so the shrink has high blocks to relocate", + peakFillPercent, gib) + script := fmt.Sprintf(`set -u +DIR=%[2]s +rm -rf "$DIR"; mkdir -p "$DIR" +used_kb() { df -k /persist | awk 'NR==2{print $3}'; } +size_kb=$(df -k /persist | awk 'NR==2{print $2}') +peak_kb=$(( size_kb * %[4]d / 100 )) +target_kb=$(( %[1]d * 1024 * 1024 )) +n=0 +while [ "$(used_kb)" -lt "$peak_kb" ]; do + dd if=/dev/urandom of="$DIR/$(printf %%06d $n)" bs=1M count=%[3]d 2>/dev/null || break + n=$((n + 1)) +done +sync +echo "PEAK files=$n used=$(df -k /persist | awk 'NR==2{print $5}')" i=0 -while [ "$i" -lt %d ]; do - dd if=/dev/zero of=/persist/konvert-fill/blk.$i bs=1M count=1024 2>/dev/null || break +while [ "$i" -lt "$n" ] && [ "$(used_kb)" -gt "$target_kb" ]; do + rm -f "$DIR/$(printf %%06d $i)" i=$((i + 1)) done sync -echo "FILLED=$i" -df -k /persist | awk 'NR==2{print "PERSIST used="$5}'`, gib) +echo "FILLED trimmed=$i kept=$(( n - i ))" +df -k /persist | awk 'NR==2{print "PERSIST used="$5}'`, gib, persistFillDir, fillChunkMiB, peakFillPercent) + // One attempt, not a retry: this writes tens of gigabytes, and a second // pass would start over rather than continue. out, err := runEVEWithTimeout(device, script, fillPersistTimeout) t.Expect(err).NotTo(HaveOccurred(), "could not fill /persist:\n%s", out) - t.Expect(out).To(ContainSubstring("FILLED="), "could not fill /persist:\n%s", out) + t.Expect(out).To(ContainSubstring("FILLED"), "could not fill /persist:\n%s", out) log.Infof("pre-fill result: %s", strings.TrimSpace(out)) } @@ -401,24 +436,41 @@ func fillPersistToPercent(t Gomega, device *evetest.EdgeDevice, pct int) { log := evetest.Logger() log.Infof("filling /persist to %d%% so no shrink can free enough", pct) script := fmt.Sprintf(`set -e -target=%d +target=%[1]d size=$(df -k /persist | awk 'NR==2{print $2}') used=$(df -k /persist | awk 'NR==2{print $3}') avail=$(df -k /persist | awk 'NR==2{print $4}') need=$(( size * target / 100 - used )) if [ "$need" -le 0 ]; then echo "ALREADY-FULL"; else [ "$need" -lt "$avail" ] || need=$(( avail - 1048576 )) - mkdir -p /persist/konvert-fill - dd if=/dev/zero of=/persist/konvert-fill/fill bs=1M count=$(( need / 1024 )) 2>/dev/null + mkdir -p %[2]s + dd if=/dev/zero of=%[2]s/fill bs=1M count=$(( need / 1024 )) 2>/dev/null sync fi -df -k /persist | awk 'NR==2{print "PERSIST used="$5}'`, pct) +df -k /persist | awk 'NR==2{print "PERSIST used="$5}'`, pct, persistFillDir) out, err := runEVEWithTimeout(device, script, fillPersistTimeout) t.Expect(err).NotTo(HaveOccurred(), "could not fill /persist:\n%s", out) t.Expect(out).To(ContainSubstring("PERSIST used="), "could not fill /persist:\n%s", out) log.Infof("fill result: %s", strings.TrimSpace(out)) } +// freePersistFill removes the pre-conversion filler. +// +// It exists only to give the offline shrink real blocks to relocate, and once +// the resize is done it is actively harmful: the shrink leaves /persist smaller +// than it found it, so the same filler now occupies most of what remains, and +// EVE-K's storage never reports healthy because Longhorn has nowhere to place a +// replica. Freed here rather than left for teardown, because the cluster comes +// up in between. +func freePersistFill(t Gomega, device *evetest.EdgeDevice) { + log := evetest.Logger() + out, err := runEVEWithTimeout(device, + "eve exec pillar sh -c 'rm -rf "+persistFillDir+"; sync; df -h /persist | tail -1'", + 5*time.Minute) + t.Expect(err).NotTo(HaveOccurred(), "could not free the fill:\n%s", out) + log.Infof("freed the pre-conversion fill; /persist is now: %s", strings.TrimSpace(out)) +} + // resizerCheck is what storage-resizer's pre-flight check reports, limited to // the fields that say whether the conversion can go ahead and why not. type resizerCheck struct { diff --git a/evetest/tests/konvert/repartition_test.go b/evetest/tests/konvert/repartition_test.go new file mode 100644 index 00000000000..c610a5a511f --- /dev/null +++ b/evetest/tests/konvert/repartition_test.go @@ -0,0 +1,257 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + "testing" + "time" + + // revive:disable:dot-imports + . "github.com/onsi/gomega" + + pillartypes "github.com/lf-edge/eve/pkg/pillar/types" + + api "github.com/lf-edge/eve/evetest/grpcapi/go" + + "github.com/lf-edge/eve/evetest" +) + +// deferContentDeleteSeconds keeps a deleted app's blobs alive across the +// conversion. Without it EVE reclaims them as soon as the app referencing them +// goes away, and the redeploy afterwards measures a fresh download rather than +// the reuse the test is about. +const deferContentDeleteSeconds = 24 * 60 * 60 + +// TestKvmToKRepartition drives the in-field boot-disk conversion end to end: +// a released small-geometry EVE-kvm image, a kvm→kvm hop that lands the +// conversion code without moving the geometry, and then the kvm→k hop whose +// cross-flavor seam arms the offline repartition. +// +// Three hops rather than one because that is the shape of the real thing. A +// device in the field is on an old release that has no conversion code, so the +// code has to arrive first, on an image of the same flavor that leaves the disk +// alone; only then can the flavor change, and it is the flavor change that +// triggers the repartition. Going straight to EVE-K would test an upgrade path +// no fielded device can take. +// +// The route the conversion takes to free the space is the axis: +// +// - EXPECT_DECISION=shrink -- the boot disk is full, so /persist must shrink to +// make room. This is the field layout, and the harder path: resize2fs has to +// relocate live blocks, which is where data can be lost. +// - EXPECT_DECISION=grow -- the boot disk has unallocated space past the last +// partition, so the new partitions grow into it and /persist is untouched. +// +// Both routes end at the same 2+2+10+10 EVE-K layout, which is why the decision +// is asserted before the conversion: afterwards the geometry alone cannot say +// which way it got there. The P3 assertion afterwards is the second half of that +// -- shrunk for one route, untouched for the other. +// +// Phases: +// 1. Baseline: the boot disk is on the released layout, and (grow only) has a +// free tail to grow into. +// 2. kvm→kvm hop: the geometry must be unchanged, and the pre-flight check must +// now decide the expected route. +// 3. Settle the vault to a local TPM unlock, so the seal assertion afterwards +// has a settled boot to look at. +// 4. (shrink only) Fill /persist so the shrink has real blocks to relocate. +// 5. Deploy an app, confirm it works, then delete it with the content-delete +// timer stretched so its blobs outlive the conversion. +// 6. kvm→k hop: the conversion runs offline across reboots. +// 7. Assert the geometry, and that the repartition did not cost the TPM seal. +// 8. Free the fill, which the shrink has now made into most of a smaller +// /persist, so EVE-K's storage has room to come up. +// 9. Redeploy the same app and assert it downloaded nothing. +// +// Needs an EVE build carrying the conversion (lf-edge/eve#6036, #6063); on a +// stock build the kvm→k hop is refused outright. +func TestKvmToKRepartition(test *testing.T) { + evetestT := evetest.Init(test) + t := NewGomegaWithT(evetestT) + defer evetest.Close() + + defineSharedParameters(repartitionParameterDefinitions()...) + p := resolveDeviceParams(t) + requirePinnedInitialVersion(t, p) + decision := evetest.GetTestParameter[string](expectDecisionParamKey) + fillGiB := int(evetest.GetTestParameter[uint32](fillPersistGiBParamKey)) + t.Expect(decision).To(BeElementOf(decisionShrink, decisionGrow), + "%s must be %q or %q", expectDecisionParamKey, decisionShrink, decisionGrow) + + // The grow route needs unallocated space past the last partition, and EVE's + // image generator sizes the partitions to fill whatever disk it is given -- + // so the device is built on a smaller disk and the tail is added afterwards. + // That also makes the disk edit a requirement only this route declares. + var requirements []evetest.Requirement + diskParams := p + if decision == decisionGrow { + diskParams.diskMiB = splitBootDiskMiB + requirements = append(requirements, evetest.RequireCapabilities{ + Capabilities: []api.Capability{api.Capability_CAPABILITY_EDIT_DEVICE_DISK}, + }) + } + + device := setupDevice(t, diskParams, evetest.FilesystemEXT4, nil, + evetest.CreateFromScratchWithLiveImage, requirements...) + log := evetest.Logger() + + devConfig := evetest.NewEdgeDeviceConfig(devName) + applyMgmtNetwork(device, devConfig) + devConfig.SetConfigProperties(shortBaseImageCooldown()) + device.ApplyConfig(devConfig, true, true) + + if decision == decisionGrow { + growBootDiskTail(t, device, bootDiskMiB) + } + + // Phase 1. + log.Infof("baseline: the boot disk must be on the released layout") + smallGeometry := assertSmallGeometry(t, device) + log.Infof("baseline geometry: %s", smallGeometry) + if decision == decisionGrow { + log.Infof("baseline: the boot disk must have a free tail to grow into") + assertFreeTail(t, device) + } + evetest.Checkpoint("baseline-small") + + // Phase 2. + log.Infof("kvm→kvm hop: landing the conversion code at %s", p.targetVersion) + device.UpgradeEVE(p.targetVersion, evetest.HypervisorKVM, + evetest.BaseOSDatastoreHTTP, true, false) + log.Infof("the hop must not have moved the geometry") + assertSmallGeometry(t, device) + log.Infof("the pre-flight check must decide %q", decision) + assertCheckDecision(t, device, decision) + evetest.Checkpoint("conversion-code-landed") + + // Phase 3. + // Also the pre-conversion half of the seal check: this establishes live that + // the last boot before the conversion unsealed from the device's own TPM. + log.Infof("settling the vault on a local TPM unlock") + settleVaultLocal(t, device) + evetest.Checkpoint("vault-settled") + + // Phase 4. + if decision == decisionShrink { + fillPersist(t, device, fillGiB) + evetest.Checkpoint("persist-filled") + } + + // Phase 5. + log.Infof("deploying the app before the conversion") + niUUID := devConfig.AddNetworkInstance(evetest.SwitchNetworkInstanceConfig{ + DisplayName: "switch-ni", + Port: "eth0", + }) + appUUID := addTestApp(devConfig, "konvert-repartition-app", niUUID) + device.ApplyConfig(devConfig, false, false) + assertAppReady(t, device, appUUID, 15*time.Minute) + dumpAppNetwork(device, "before the conversion (working)") + + log.Infof("stretching the deferred content delete past the conversion") + props := shortBaseImageCooldown() + props.SetGlobalValueInt(pillartypes.DeferContentDelete, deferContentDeleteSeconds) + devConfig.SetConfigProperties(props) + device.ApplyConfig(devConfig, true, true) + + // The conversion's cross-flavor gate refuses to run while a volume exists, + // so the app goes first; its blobs stay behind under the stretched timer, + // and its network instance stays in the configuration to be redeployed onto. + log.Infof("deleting the app, keeping its network and blobs") + devConfig.DeleteApplication(appUUID) + device.ApplyConfig(devConfig, true, true) + assertNoLiveVolumes(t, device) + evetest.Checkpoint("app-deleted") + + // Phase 6. + conversionOK := false + defer func() { + if !conversionOK { + dumpConversionFailure(device) + } + }() + // The offline repartition boots once more than an upgrade does: its + // intermediate resize boot is invisible to the controller, so the audit at + // teardown would see one reboot the upgrade did not account for. Declared + // before the update that causes it, so the declaration cannot race it. + device.ExpectReboots(1) + log.Infof("kvm→k hop: arming the offline %s", decision) + device.UpgradeEVE(p.targetVersion, evetest.HypervisorKubevirt, + evetest.BaseOSDatastoreHTTP, true, false) + conversionOK = true + evetest.Checkpoint("conversion-complete") + + // Phase 7. + wantP3 := p3MustShrink + if decision == decisionGrow { + wantP3 = p3MustBeUnchanged + } + log.Infof("asserting the boot disk reached the EVE-K layout via the %s route", decision) + assertLargeGeometry(t, device, smallGeometry, wantP3) + evetest.Checkpoint("geometry-converted") + + log.Infof("asserting the repartition preserved the TPM seal") + assertSealSurvivedRepartition(t, device) + evetest.Checkpoint("seal-preserved") + + // The fill has done its job now that the resize is over, and it has to go + // before EVE-K brings its storage up: the shrink left /persist smaller, so + // what was a third of it is now nearly all of it, and Longhorn reports + // unhealthy storage forever rather than place a replica with no room. + if decision == decisionShrink { + freePersistFill(t, device) + evetest.Checkpoint("fill-freed") + } + + // Phase 8. The snapshot is taken before the redeploy and after the + // conversion's last reboot, so both readings belong to the same boot. + beforeBytes := snapshotDownloaderBytes(t, device) + // Redeployed onto the network instance the device already has. Only the + // app was deleted; adding a second switch instance on the same port here + // would leave two of them bound to eth0, and the app never starts. + log.Infof("redeploying the app on EVE-K") + newAppUUID := addTestApp(devConfig, "konvert-repartition-app", niUUID) + device.ApplyConfig(devConfig, false, false) + + appOK := false + defer func() { + if !appOK { + dumpClusterStorage(device) + dumpAppNetwork(device, "after the conversion (app FAILED)") + } + }() + waitClusterStorageReady(t, device) + assertAppReady(t, device, newAppUUID, appRunningAfterRepartitionTimeout) + appOK = true + assertBlobsReused(t, device, beforeBytes) + evetest.Checkpoint("app-redeployed") + + // Leave the collector as it was found, so a device reused by the next test + // in the suite is not holding blobs for a day. + devConfig.SetConfigProperties(shortBaseImageCooldown()) + device.ApplyConfig(devConfig, true, true) +} + +// repartitionParameterDefinitions declares the axes this test adds. +func repartitionParameterDefinitions() []evetest.TestParameterDefinition { + return []evetest.TestParameterDefinition{ + { + Key: expectDecisionParamKey, + DefaultValue: decisionShrink, + Description: evetest.TestParameterDescription{ + Summary: "Which way the conversion must free the space it needs", + Default: "shrink", + AllowedValues: "shrink|grow", + }, + }, + { + Key: fillPersistGiBParamKey, + DefaultValue: uint32(defaultFillPersistGiB), + Description: evetest.TestParameterDescription{ + Summary: "GiB written into /persist before a shrink, so it has blocks to relocate (0 disables)", + Default: "33", + }, + }, + } +} diff --git a/evetest/tests/konvert/testsuite_test.go b/evetest/tests/konvert/testsuite_test.go index 3e2d5d0a867..1e4e0b8fb06 100644 --- a/evetest/tests/konvert/testsuite_test.go +++ b/evetest/tests/konvert/testsuite_test.go @@ -135,5 +135,22 @@ func TestKonvertSuite(test *testing.T) { evetest.TestCase{Test: TestKvmToKUpgrade}, evetest.TestCase{Test: TestKvmToKContentTree}, evetest.TestCase{Test: TestKvmToKAppRecreate}, + evetest.TestCase{ + Test: TestKvmToKRepartition, + Variants: []evetest.TestVariant{ + { + Name: "Shrink", + Parameters: []evetest.TestParameterValue{ + {Key: expectDecisionParamKey, Value: decisionShrink}, + }, + }, + { + Name: "Grow", + Parameters: []evetest.TestParameterValue{ + {Key: expectDecisionParamKey, Value: decisionGrow}, + }, + }, + }, + }, ) } diff --git a/evetest/tests/konvert/vault_helpers_test.go b/evetest/tests/konvert/vault_helpers_test.go index 3cf09f19dab..9c229a7af68 100644 --- a/evetest/tests/konvert/vault_helpers_test.go +++ b/evetest/tests/konvert/vault_helpers_test.go @@ -106,26 +106,27 @@ type vaultUnlock struct { } // assertSealSurvivedRepartition asserts the boot-disk repartition did not break -// the TPM seal, judged after the fact from the device's own logs. +// the TPM seal. // -// It has to be judged this way. The live window in which the post-conversion -// unlock is readable is a minute or two, and racing it makes the test flaky; -// /persist survives the repartition, so the record of every boot is still there -// afterwards. Two independent gates: +// The question is whether the repartition invalidated the seal, and PCR5 is what +// answers it: the repartition moves that measurement, and the seal deliberately +// excludes it. So a controller-key fallback or a failed unseal naming PCR5 means +// the repartition cost the seal, while one naming only 8, 9 and 13 is the +// ordinary consequence of booting a new rootfs and is expected here. // -// 1. The last boot on the conversion-capable kvm image must have unsealed -// locally. That is the boot after the repartition and before EVE-K, on which -// only PCR5 changed -- and PCR5 is excluded from the seal precisely so that -// a repartition does not invalidate it. Keyed on that exact version rather -// than "any kvm boot", so a future baseline that also unlocks locally cannot -// satisfy it by accident. -// 2. No controller-key or failed unseal anywhere lists PCR5 among its -// mismatches. A PCR5-driven re-seal means the repartition did break the -// seal, whatever gate 1 saw. +// Judged after the fact from the device's own logs, because the live window in +// which a post-conversion unlock is readable is a minute or two and racing it +// makes the test flaky. // -// The EVE-K boot unlocking from the controller key is expected and not a -// failure: a new rootfs moves PCRs 8, 9 and 13. -func assertSealSurvivedRepartition(t Gomega, device *evetest.EdgeDevice, kvmVersion string) { +// What is deliberately NOT asserted from these logs is that the pre-conversion +// boot unsealed locally. On the shrink path the offline resize can lose +// /persist content -- storage-resize.sh restores what it lost from the CONFIG +// backup, and that backup carries identity and connectivity files, not the log +// archive. So the pre-conversion records may simply not be there afterwards. +// That claim is established live instead, before the conversion, by +// settleVaultLocal reading VaultStatus directly, which is stronger evidence +// than parsing a log for it would be. +func assertSealSurvivedRepartition(t Gomega, device *evetest.EdgeDevice) { log := evetest.Logger() var raw string t.Eventually(func(g Gomega) { @@ -143,7 +144,6 @@ func assertSealSurvivedRepartition(t Gomega, device *evetest.EdgeDevice, kvmVers "no vault unlock was recorded in /persist/newlog, so the seal cannot be judged") var pcr5Reseals []vaultUnlock - var onKVM []vaultUnlock for _, u := range unlocks { for _, p := range u.pcrs { if p == "5" { @@ -151,20 +151,10 @@ func assertSealSurvivedRepartition(t Gomega, device *evetest.EdgeDevice, kvmVers break } } - if u.version == kvmVersion { - onKVM = append(onKVM, u) - } } - t.Expect(pcr5Reseals).To(BeEmpty(), "PCR5 appears in a re-seal or failed unseal, so the repartition broke the TPM seal: %v", pcr5Reseals) - t.Expect(onKVM).NotTo(BeEmpty(), - "no vault unlock was recorded on %s, so the post-repartition boot cannot be judged", - kvmVersion) - t.Expect(onKVM[len(onKVM)-1].method).To(Equal(unlockLocal), - "the last boot on %s did not unseal locally, so the repartition cost the seal: %v", - kvmVersion, onKVM[len(onKVM)-1]) } var ( From 28c96d8c0e42b8d190bab1c51e928bc59449bf1b Mon Sep 17 00:00:00 2001 From: eriknordmark Date: Wed, 9 Sep 2026 22:59:04 +0200 Subject: [PATCH 06/10] evetest: declined boot-disk repartition test A conversion that fails halfway leaves a device with a half-written partition table and no way back, so EVE has to work out beforehand that it cannot free the space, refuse, say why, and carry on unchanged. Two ways to get there, failing at different points in the resizer's reasoning: a ZFS /persist cannot be shrunk at all, so with no free tail a shrink is never considered; an ext4 /persist filled past what it could give back is considered and does not fit. The reason is asserted, not just the refusal -- both end at the same verdict, so a refusal-only check would pass on a device that declined for a third reason, and would keep passing once the condition it meant to create had stopped happening. The decline is three assertions that hold together, each ruling out a different unacceptable way to refuse: an error is reported, so it is a decision rather than a silent stall; the device still runs the image it did, so nothing was installed; and it still answers its controller, since losing remote management is the outcome refusing exists to avoid. Signed-off-by: eriknordmark Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01NZEoFvMK2UHByU3LAeXsxA --- .../tests/konvert/repartition_refused_test.go | 134 ++++++++++++++++++ evetest/tests/konvert/testsuite_test.go | 17 +++ 2 files changed, 151 insertions(+) create mode 100644 evetest/tests/konvert/repartition_refused_test.go diff --git a/evetest/tests/konvert/repartition_refused_test.go b/evetest/tests/konvert/repartition_refused_test.go new file mode 100644 index 00000000000..80cc9a662ce --- /dev/null +++ b/evetest/tests/konvert/repartition_refused_test.go @@ -0,0 +1,134 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + "testing" + + // revive:disable:dot-imports + . "github.com/onsi/gomega" + + "github.com/lf-edge/eve/evetest" +) + +// tooFullPercent is how full /persist is made for the too-full case. The +// resizer will not shrink a filesystem past its own fullness limit, so filling +// well beyond what the conversion would need to free is what makes the refusal +// certain rather than marginal. +const tooFullPercent = 70 + +// TestKvmToKRepartitionRefused asserts that a device which cannot be repartitioned declines +// the conversion cleanly, rather than attempting it and stranding itself. +// +// This is the sibling of TestKvmToKRepartition, and the more important of the +// two to get right: a conversion that fails halfway leaves a device with a +// half-written partition table and no way back. The contract is that EVE works +// out beforehand that it cannot free the space, refuses, says why, and carries +// on exactly as it was. +// +// Two ways to arrive there, both real: +// +// - REFUSE_REASON=zfs -- /persist is ZFS, which cannot be shrunk at all, and +// the boot disk has no free tail to take the space from instead. +// - REFUSE_REASON=too-full -- /persist is ext4 and could in principle shrink, +// but holds too much to give up what is needed. +// +// They matter separately because they fail at different points in the resizer's +// reasoning: the ZFS case never gets as far as considering a shrink, while the +// too-full case considers one and finds it does not fit. +// +// Phases: +// 1. Baseline: the released layout, and /persist is the filesystem this +// variant is about. +// 2. (too-full only) Fill /persist past what a shrink could give back. +// 3. kvm→kvm hop, then assert the pre-flight check refuses for this reason. +// 4. Push the kvm→k update and assert it is declined: an error is reported, +// the device is still on the kvm image, and it is still reachable. +// 5. Assert the partition table was not touched. +// +// Needs an EVE build carrying the conversion (lf-edge/eve#6036, #6063). +func TestKvmToKRepartitionRefused(test *testing.T) { + evetestT := evetest.Init(test) + t := NewGomegaWithT(evetestT) + defer evetest.Close() + + defineSharedParameters(refusedParameterDefinitions()...) + p := resolveDeviceParams(t) + requirePinnedInitialVersion(t, p) + reason := evetest.GetTestParameter[string](refuseReasonParamKey) + t.Expect(reason).To(BeElementOf(refuseZFS, refuseTooFull), + "%s must be %q or %q", refuseReasonParamKey, refuseZFS, refuseTooFull) + + // Both variants need a boot disk with no free tail, which is what a device + // gets by default: EVE's image generator fills whatever disk it is given. + filesystem := evetest.FilesystemEXT4 + wantPersistType := "ext4" + if reason == refuseZFS { + filesystem = evetest.FilesystemZFS + wantPersistType = "zfs" + } + + device := setupDevice(t, p, filesystem, nil, evetest.CreateFromScratchWithLiveImage) + log := evetest.Logger() + + devConfig := evetest.NewEdgeDeviceConfig(devName) + applyMgmtNetwork(device, devConfig) + devConfig.SetConfigProperties(shortBaseImageCooldown()) + device.ApplyConfig(devConfig, true, true) + + // Phase 1. The filesystem is checked rather than assumed: a device that came + // up ext4 when the test meant ZFS would refuse for the wrong reason, and the + // refusal assertion alone could not tell the difference. + log.Infof("baseline: /persist must be %s", wantPersistType) + assertPersistType(t, device, wantPersistType) + log.Infof("baseline: the boot disk must be on the released layout") + smallGeometry := assertSmallGeometry(t, device) + log.Infof("baseline geometry: %s", smallGeometry) + evetest.Checkpoint("baseline-small") + + // Phase 2. + if reason == refuseTooFull { + fillPersistToPercent(t, device, tooFullPercent) + evetest.Checkpoint("persist-filled") + } + + // Phase 3. + log.Infof("kvm→kvm hop: landing the conversion code at %s", p.targetVersion) + device.UpgradeEVE(p.targetVersion, evetest.HypervisorKVM, + evetest.BaseOSDatastoreHTTP, true, false) + assertSmallGeometry(t, device) + kvmHopVersion := readRunningVersion(t, device) + log.Infof("the pre-flight check must refuse, for the %q reason", reason) + assertCheckRefuses(t, device, reason) + evetest.Checkpoint("check-refuses") + + // Phase 4. Not UpgradeEVE: a refusal installs nothing and reboots not at + // all, so there is neither an upgrade nor a revert to wait for, and booking + // a reboot that cannot happen would fail the run at teardown. + log.Infof("pushing the kvm→k update, which must be declined") + device.RequestRefusedEVEUpgrade(p.targetVersion, evetest.HypervisorKubevirt, + evetest.BaseOSDatastoreHTTP) + assertConversionDeclined(t, device, kvmHopVersion) + evetest.Checkpoint("conversion-declined") + + // Phase 5. The whole point of refusing early is that nothing was touched. + log.Infof("the partition table must be exactly as it was") + assertGeometryUnchanged(t, device, smallGeometry) + evetest.Checkpoint("geometry-untouched") +} + +// refusedParameterDefinitions declares the axis this test adds. +func refusedParameterDefinitions() []evetest.TestParameterDefinition { + return []evetest.TestParameterDefinition{ + { + Key: refuseReasonParamKey, + DefaultValue: refuseZFS, + Description: evetest.TestParameterDescription{ + Summary: "Why the conversion must be refused", + Default: "zfs", + AllowedValues: "zfs|too-full", + }, + }, + } +} diff --git a/evetest/tests/konvert/testsuite_test.go b/evetest/tests/konvert/testsuite_test.go index 1e4e0b8fb06..fa2f872c2e5 100644 --- a/evetest/tests/konvert/testsuite_test.go +++ b/evetest/tests/konvert/testsuite_test.go @@ -152,5 +152,22 @@ func TestKonvertSuite(test *testing.T) { }, }, }, + evetest.TestCase{ + Test: TestKvmToKRepartitionRefused, + Variants: []evetest.TestVariant{ + { + Name: "PersistTooFull", + Parameters: []evetest.TestParameterValue{ + {Key: refuseReasonParamKey, Value: refuseTooFull}, + }, + }, + { + Name: "ZFSPersist", + Parameters: []evetest.TestParameterValue{ + {Key: refuseReasonParamKey, Value: refuseZFS}, + }, + }, + }, + }, ) } From c85a88f121c74e15e5ca6ab3b9e19e992c055aaa Mon Sep 17 00:00:00 2001 From: eriknordmark Date: Wed, 9 Sep 2026 22:59:04 +0200 Subject: [PATCH 07/10] evetest: the repartitioned boot-disk layout Asserts only that the boot disk ends at the full EVE-K layout, whatever it started on, and deliberately deploys nothing: mixing an application in would let a layout regression be masked by, or mistaken for, a storage failure. The target is stated absolutely rather than relative to the starting sizes. A conversion that grew every partition but stopped short would satisfy a relative check and still leave a disk unlike a fresh EVE-K install. The starting layout is observed rather than declared, and only has to differ from the target -- a device already laid out correctly would pass without the conversion having done anything. Signed-off-by: eriknordmark Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01NZEoFvMK2UHByU3LAeXsxA --- .../konvert/repartition_geometry_test.go | 84 +++++++++++++++++++ evetest/tests/konvert/testsuite_test.go | 1 + 2 files changed, 85 insertions(+) create mode 100644 evetest/tests/konvert/repartition_geometry_test.go diff --git a/evetest/tests/konvert/repartition_geometry_test.go b/evetest/tests/konvert/repartition_geometry_test.go new file mode 100644 index 00000000000..10c24e0ecbf --- /dev/null +++ b/evetest/tests/konvert/repartition_geometry_test.go @@ -0,0 +1,84 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + "testing" + + // revive:disable:dot-imports + . "github.com/onsi/gomega" + + "github.com/lf-edge/eve/evetest" +) + +// TestKvmToKRepartitionGeometry asserts that the conversion ends at the full EVE-K +// partition layout -- ESP-A 2 GiB, the reserved ESP-B 2 GiB, IMGA and IMGB +// 10 GiB each -- whatever layout the device started on. +// +// It deliberately does nothing else. No app, no data volume, no vault settle, +// no blob-reuse check: those all belong to TestKvmToKRepartition, and mixing +// them in here would mean a geometry regression could be masked by, or mistaken +// for, an app or storage failure. What is left is one claim, stated absolutely +// rather than relative to the starting sizes, because a conversion that grew +// every partition but stopped short of the target would pass a relative check +// and still leave a disk unlike a fresh EVE-K install. +// +// The axis is INITIAL_EVE_VERSION: point it at each release whose geometry +// matters and the same claim must hold from all of them. The starting layout is +// observed rather than declared, and only has to differ from the target -- a +// device that is already laid out correctly would pass without the conversion +// having done anything. +// +// Needs an EVE build carrying the conversion (lf-edge/eve#6036, #6063). +func TestKvmToKRepartitionGeometry(test *testing.T) { + evetestT := evetest.Init(test) + t := NewGomegaWithT(evetestT) + defer evetest.Close() + + defineSharedParameters() + p := resolveDeviceParams(t) + requirePinnedInitialVersion(t, p) + + device := setupDevice(t, p, evetest.FilesystemEXT4, nil, + evetest.CreateFromScratchWithLiveImage) + log := evetest.Logger() + + devConfig := evetest.NewEdgeDeviceConfig(devName) + applyMgmtNetwork(device, devConfig) + devConfig.SetConfigProperties(shortBaseImageCooldown()) + device.ApplyConfig(devConfig, true, true) + + startGeometry := readGeometry(t, device) + log.Infof("starting geometry on %s: %s", p.initialVersion, startGeometry) + t.Expect(isEVEKLayout(startGeometry)).To(BeFalse(), + "%s is already laid out like EVE-K, so a conversion from it would prove nothing: %s", + p.initialVersion, startGeometry) + evetest.Checkpoint("baseline-captured") + + log.Infof("kvm→kvm hop: landing the conversion code at %s", p.targetVersion) + device.UpgradeEVE(p.targetVersion, evetest.HypervisorKVM, + evetest.BaseOSDatastoreHTTP, true, false) + log.Infof("the hop must not have moved the geometry") + assertGeometryUnchanged(t, device, startGeometry) + evetest.Checkpoint("conversion-code-landed") + + conversionOK := false + defer func() { + if !conversionOK { + dumpConversionFailure(device) + } + }() + // The offline repartition boots once more than an upgrade does; declared + // before the update that causes it. + device.ExpectReboots(1) + log.Infof("kvm→k hop: running the repartition") + device.UpgradeEVE(p.targetVersion, evetest.HypervisorKubevirt, + evetest.BaseOSDatastoreHTTP, true, false) + conversionOK = true + evetest.Checkpoint("conversion-complete") + + log.Infof("the boot disk must be at the full EVE-K layout") + assertFinalEVEKLayout(t, device) + evetest.Checkpoint("layout-final") +} diff --git a/evetest/tests/konvert/testsuite_test.go b/evetest/tests/konvert/testsuite_test.go index fa2f872c2e5..fd8f161e772 100644 --- a/evetest/tests/konvert/testsuite_test.go +++ b/evetest/tests/konvert/testsuite_test.go @@ -135,6 +135,7 @@ func TestKonvertSuite(test *testing.T) { evetest.TestCase{Test: TestKvmToKUpgrade}, evetest.TestCase{Test: TestKvmToKContentTree}, evetest.TestCase{Test: TestKvmToKAppRecreate}, + evetest.TestCase{Test: TestKvmToKRepartitionGeometry}, evetest.TestCase{ Test: TestKvmToKRepartition, Variants: []evetest.TestVariant{ From 9053163711b93dd018ca94591d3e295f0e8667b5 Mon Sep 17 00:00:00 2001 From: eriknordmark Date: Wed, 9 Sep 2026 22:59:05 +0200 Subject: [PATCH 08/10] evetest: app volume carried across the conversion The case the other conversion tests avoid. They delete the application first, because the cross-flavor gate refuses to convert while a volume exists; here the device already has the EVE-K layout, so no repartition is needed, the gate allows the conversion with volumes present, and the volume must be carried over rather than recreated. The marker is read back off the volume's raw block device rather than from where it was written. On EVE-K a container's data volume is not auto-mounted at its MountDir (lf-edge/eve#6145), so a mount-based check would report the data lost when it is merely unmounted -- the exact false failure this test exists to tell apart from a real one. The escript this is ported from also carries a VM application's disk volume across. evetest has no VM application image and no cloud-init plumbing to reach a VM guest, so that half needs a new test app and UserData support first. Signed-off-by: eriknordmark Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01NZEoFvMK2UHByU3LAeXsxA --- .../tests/konvert/download_helpers_test.go | 17 ++ evetest/tests/konvert/testsuite_test.go | 1 + evetest/tests/konvert/volmig_test.go | 167 ++++++++++++++++++ 3 files changed, 185 insertions(+) create mode 100644 evetest/tests/konvert/volmig_test.go diff --git a/evetest/tests/konvert/download_helpers_test.go b/evetest/tests/konvert/download_helpers_test.go index 17cbfbd6212..55a66f54309 100644 --- a/evetest/tests/konvert/download_helpers_test.go +++ b/evetest/tests/konvert/download_helpers_test.go @@ -83,3 +83,20 @@ func assertBlobsReused(t Gomega, device *evetest.EdgeDevice, before int64) { "the deployment downloaded %d bytes, so it did not reuse the blobs the "+ "conversion carried over", delta) } + +// assertNothingDownloadedThisBoot asserts the downloader has pulled essentially +// nothing since the device booted. +// +// For a check spanning the conversion there is no before/after pair to take: +// the counter lives in /run and the conversion reboots, so the reading from +// before it no longer exists to compare against. The absolute reading answers +// the same question more directly, and more strictly -- the app came back +// during this boot, so anything refetched to bring it back is counted here. +func assertNothingDownloadedThisBoot(t Gomega, device *evetest.EdgeDevice) { + total, err := downloaderRecvBytes(device) + t.Expect(err).NotTo(HaveOccurred()) + evetest.Logger().Infof("downloader received %d bytes since the device booted", total) + t.Expect(total).To(BeNumerically("<", blobReuseAllowanceBytes), + "the downloader pulled %d bytes since boot, so the app did not come back "+ + "from the content store the conversion carried over", total) +} diff --git a/evetest/tests/konvert/testsuite_test.go b/evetest/tests/konvert/testsuite_test.go index fd8f161e772..8c9f8e64d83 100644 --- a/evetest/tests/konvert/testsuite_test.go +++ b/evetest/tests/konvert/testsuite_test.go @@ -170,5 +170,6 @@ func TestKonvertSuite(test *testing.T) { }, }, }, + evetest.TestCase{Test: TestKvmToKVolumeMigration}, ) } diff --git a/evetest/tests/konvert/volmig_test.go b/evetest/tests/konvert/volmig_test.go new file mode 100644 index 00000000000..de850feb28d --- /dev/null +++ b/evetest/tests/konvert/volmig_test.go @@ -0,0 +1,167 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + "testing" + "time" + + // revive:disable:dot-imports + . "github.com/onsi/gomega" + + "github.com/lf-edge/eve/evetest" +) + +const ( + // dataVolumeSize is the app data volume carried across the conversion. + // Small on purpose: what is being tested is that the data survives, and a + // larger volume only lengthens the storage work between the assertions. + dataVolumeSize = 256 * evetest.MiB + // volumeMarker is written into that volume before the conversion and looked + // for afterwards. Distinctive enough to be found by scanning a raw device. + volumeMarker = "KONVERT-VOLMIG-MARKER-9f3a1c7e" +) + +// TestKvmToKVolumeMigration asserts an application volume survives the +// cross-flavor conversion with its contents intact, without the app being +// deleted and redeployed around it. +// +// This is the case the other conversion tests deliberately avoid. They delete +// the app first, because the cross-flavor gate refuses to convert while a volume +// exists; here the device already has the EVE-K partition layout, so no +// repartition is needed, the gate allows the conversion with volumes present, +// and the volume has to be carried over rather than recreated. The code that +// does the carrying is what this test is about: upgradeconverter moves the +// volume out of the directory Longhorn takes ownership of on EVE-K, and +// volumemgr later rolls it into a PVC. +// +// Because no repartition is involved, the device starts on the build under test +// rather than a released image -- there is no old geometry to convert, and +// pinning a release would only add an upgrade this test is not about. +// +// The marker is read back off the volume's raw block device rather than from +// where it was written. On EVE-K a container's data volume is not auto-mounted +// at its MountDir (lf-edge/eve#6145), so a mount-based check would report the +// data lost when it is merely unmounted -- the exact false failure this test +// exists to distinguish from a real one. +// +// Phases: +// 1. The vault must be TPM-backed, and the layout already EVE-K's. +// 2. Deploy the app with a data volume and write a marker into it. +// 3. Convert to EVE-K with the app and volume kept in place. +// 4. Assert the layout is unchanged and the app comes back. +// 5. Assert the marker is still there, and that nothing was re-downloaded. +// +// Not covered: the escript this is ported from also carries a VM application's +// disk volume across the conversion. evetest has no VM application image and no +// cloud-init plumbing to reach a VM guest, so that half is not portable yet; +// adding it means a new test app and UserData support in the framework. +// +// Needs an EVE build carrying the conversion (lf-edge/eve#6036, #6063). +func TestKvmToKVolumeMigration(test *testing.T) { + evetestT := evetest.Init(test) + t := NewGomegaWithT(evetestT) + defer evetest.Close() + + defineSharedParameters() + p := resolveDeviceParams(t) + // The build under test, not a release: this conversion needs a device that + // is already on the EVE-K layout, which is what that build lays down. + p.initialVersion = "" + p.initialRepo = "" + p.initialHypervisor = evetest.HypervisorKVM + t.Expect(p.withTPM).To(BeTrue(), + "this test needs a TPM: the volume it carries over is inside the vault") + + device := setupDevice(t, p, evetest.FilesystemEXT4, nil, + evetest.CreateFromScratchWithLiveImage) + log := evetest.Logger() + + devConfig := evetest.NewEdgeDeviceConfig(devName) + applyMgmtNetwork(device, devConfig) + devConfig.SetConfigProperties(shortBaseImageCooldown()) + device.ApplyConfig(devConfig, true, true) + + // Phase 1. A vault that fell back to no-TPM would still hold the volume, so + // the carry-over would appear to work while proving nothing about the + // encrypted path the real thing takes. + log.Infof("the vault must be TPM-backed") + assertVaultIsTPMBacked(t, device) + startGeometry := readGeometry(t, device) + log.Infof("starting geometry: %s", startGeometry) + t.Expect(isEVEKLayout(startGeometry)).To(BeTrue(), + "this test needs a device already on the EVE-K layout, so that the "+ + "conversion takes the no-repartition path: %s", startGeometry) + evetest.Checkpoint("baseline-ready") + + // Phase 2. Encrypted, not clear text: a clear-text volume sidesteps the + // vault entirely, and the vault transition is half of what makes the + // carry-over difficult. + log.Infof("deploying the app with a data volume") + niUUID := devConfig.AddNetworkInstance(evetest.SwitchNetworkInstanceConfig{ + DisplayName: "switch-ni", + Port: "eth0", + }) + dataVolUUID := devConfig.AddBlankVolume("konvert-volmig-data", dataVolumeSize, false) + appUUID := addTestAppWithVolume(devConfig, "konvert-volmig-app", niUUID, dataVolUUID) + device.ApplyConfig(devConfig, false, false) + assertAppReady(t, device, appUUID, 20*time.Minute) + + log.Infof("writing a marker into the data volume") + writeVolumeMarker(t, device, appUUID, dataMountDir, volumeMarker) + dumpAppNetwork(device, "before the conversion (working)") + evetest.Checkpoint("marker-written") + + // Phase 3. The app and its volume stay in the configuration across the + // conversion; that is the whole point. + conversionOK := false + defer func() { + if !conversionOK { + dumpConversionFailure(device) + } + }() + log.Infof("converting to EVE-K with the app and volume in place") + device.UpgradeEVE(p.targetVersion, evetest.HypervisorKubevirt, + evetest.BaseOSDatastoreHTTP, true, false) + conversionOK = true + evetest.Checkpoint("conversion-complete") + + // Phase 4. Unchanged rather than grown: there was nothing to repartition, + // so a layout that moved would mean the conversion did work it should have + // skipped. + log.Infof("the layout must be unchanged") + assertGeometryUnchanged(t, device, startGeometry) + + appOK := false + defer func() { + if !appOK { + dumpClusterStorage(device) + dumpAppNetwork(device, "after the conversion (app FAILED)") + } + }() + waitClusterStorageReady(t, device) + assertAppReady(t, device, appUUID, appRunningAfterSwitchTimeout) + appOK = true + evetest.Checkpoint("app-back") + + // Phase 5. + log.Infof("the marker must still be in the volume") + assertVolumeMarker(t, device, appUUID, volumeMarker) + assertNothingDownloadedThisBoot(t, device) + evetest.Checkpoint("volume-survived") +} + +// assertVaultIsTPMBacked asserts the vault is sealed to a TPM at all, whichever +// key opened it this boot. +// +// Deliberately weaker than settleVaultLocal: this test does not need the seal to +// have settled, only for there to be one. A device that came up without a TPM +// would carry the volume over just as happily and prove nothing about the +// encrypted path. +func assertVaultIsTPMBacked(t Gomega, device *evetest.EdgeDevice) { + t.Eventually(func() string { + return readVaultUnlockMethod(device) + }, 12*time.Minute, 10*time.Second).Should(BeElementOf(unlockLocal, unlockController), + "the vault is not TPM-backed, so the volume it holds is not encrypted") +} From 460931804fb7841b9aaf0b3d30aa3db258df30dd Mon Sep 17 00:00:00 2001 From: eriknordmark Date: Wed, 9 Sep 2026 22:59:05 +0200 Subject: [PATCH 09/10] evetest: first-boot EVE-K deferred app volume EVE-K cannot create a volume until k3s, Longhorn and CDI are up, roughly a quarter of an hour from a cold boot. A device handed an application in its very first configuration therefore asks for a volume that cannot be satisfied yet, and volumemgr has to defer the request and retry it when storage arrives, with creation idempotent so a retry does not trip over its own earlier attempt. Without that the volume sits at CREATING_VOLUME and the application never starts. The timing is the test: the application is deployed immediately after onboarding, not after waiting for storage, which would test nothing because by then the request is one that can simply be granted. Everything else -- a native EVE-K boot, no conversion, no prior volumes -- exists to make that one window real. A device that reboots its way out of the problem has not solved it either. Nothing here asks for a reboot, and the framework audits observed reboots against expected ones, so that case fails without a separate assertion. Signed-off-by: eriknordmark Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01NZEoFvMK2UHByU3LAeXsxA --- evetest/tests/konvert/firstboot_test.go | 118 ++++++++++++++++++++++++ evetest/tests/konvert/testsuite_test.go | 1 + 2 files changed, 119 insertions(+) create mode 100644 evetest/tests/konvert/firstboot_test.go diff --git a/evetest/tests/konvert/firstboot_test.go b/evetest/tests/konvert/firstboot_test.go new file mode 100644 index 00000000000..ae3696b2433 --- /dev/null +++ b/evetest/tests/konvert/firstboot_test.go @@ -0,0 +1,118 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + "testing" + "time" + + // revive:disable:dot-imports + . "github.com/onsi/gomega" + + pillartypes "github.com/lf-edge/eve/pkg/pillar/types" + + "github.com/lf-edge/eve/evetest" +) + +// TestFirstBootEVEKAppVolume asserts that an application volume asked for +// before EVE-K's cluster storage exists eventually gets created, rather than +// parking forever. +// +// EVE-K cannot create a volume until k3s, Longhorn and CDI are up, which takes +// somewhere around a quarter of an hour from a cold boot. A device that is +// handed an application in its very first configuration therefore asks for a +// volume that cannot be satisfied yet, and the question is what happens next: +// volumemgr has to defer the request and retry it when storage arrives, and +// creation has to be idempotent so a retry does not trip over its own earlier +// attempt. Without that the volume sits at CREATING_VOLUME and the app never +// starts. +// +// The timing is the test. The app is deployed immediately after onboarding, +// while cluster storage is still minutes away -- deliberately not after waiting +// for storage to be ready, which would test nothing, since by then the request +// is one that can simply be granted. Everything else here exists to make that +// one window real: a native EVE-K boot with no conversion, no upgrade and no +// prior volumes. +// +// A device that reboots its way out of the problem has not solved it either. +// Nothing here asks for a reboot, and the framework audits observed reboots +// against expected ones at teardown, so a device that restarts to recover fails +// the run without a separate assertion. +// +// Phases: +// 1. A native EVE-K device, on the EVE-K layout, holding no volumes. +// 2. Deploy an app with a volume at once, before storage can exist. +// 3. Cluster storage comes up. +// 4. The volume is created and the app runs and answers. +func TestFirstBootEVEKAppVolume(test *testing.T) { + evetestT := evetest.Init(test) + t := NewGomegaWithT(evetestT) + defer evetest.Close() + + defineSharedParameters() + p := resolveDeviceParams(t) + // A native EVE-K boot of the build under test: no release to start from and + // no conversion, because the subject is the first configuration a fresh + // EVE-K device ever receives. + p.initialVersion = "" + p.initialRepo = "" + p.initialHypervisor = evetest.HypervisorKubevirt + + device := setupDevice(t, p, evetest.FilesystemEXT4, nil, + evetest.CreateFromScratchWithLiveImage) + log := evetest.Logger() + + // Phase 1. Checked before anything is deployed, so that a device which was + // not actually a clean EVE-K boot is caught here rather than misread later + // as a volume that failed to converge. + log.Infof("the device must be a clean EVE-K boot") + assertNoLiveVolumes(t, device) + startGeometry := readGeometry(t, device) + t.Expect(isEVEKLayout(startGeometry)).To(BeTrue(), + "this is not an EVE-K boot disk: %s", startGeometry) + evetest.Checkpoint("fresh-evek-boot") + + // Phase 2. The management network and the app go out together, so the + // volume request reaches the device as early as it possibly can. Shortening + // the config poll only narrows the gap further. + devConfig := evetest.NewEdgeDeviceConfig(devName) + props := pillartypes.NewConfigItemValueMap() + props.SetGlobalValueInt(pillartypes.ConfigInterval, 10) + devConfig.SetConfigProperties(props) + applyMgmtNetwork(device, devConfig) + + log.Infof("deploying an app with a volume immediately, before cluster storage exists") + niUUID := devConfig.AddNetworkInstance(evetest.SwitchNetworkInstanceConfig{ + DisplayName: "switch-ni", + Port: "eth0", + }) + dataVolUUID := devConfig.AddBlankVolume("firstboot-data", dataVolumeSize, false) + appUUID := addTestAppWithVolume(devConfig, "firstboot-app", niUUID, dataVolUUID) + device.ApplyConfig(devConfig, false, false) + evetest.Checkpoint("app-requested-before-storage") + + appOK := false + defer func() { + if !appOK { + dumpClusterStorage(device) + dumpAppNetwork(device, "first boot (app FAILED)") + } + }() + + // Phase 3. + log.Infof("waiting for EVE-K cluster storage to come up") + waitClusterStorageReady(t, device) + evetest.Checkpoint("cluster-storage-ready") + + // Phase 4. The volume is asserted in its own right before the app: an app + // that never starts because its volume was never created is a different + // finding from one that fails for its own reasons, and waiting on the app + // alone would not separate them. + log.Infof("the deferred volume must now be created") + assertVolumeCreated(t, device, dataVolUUID, 45*time.Minute) + log.Infof("and the app must run on it") + assertAppReady(t, device, appUUID, appRunningAfterSwitchTimeout) + appOK = true + evetest.Checkpoint("app-running-on-deferred-volume") +} diff --git a/evetest/tests/konvert/testsuite_test.go b/evetest/tests/konvert/testsuite_test.go index 8c9f8e64d83..b0b6a1b65c7 100644 --- a/evetest/tests/konvert/testsuite_test.go +++ b/evetest/tests/konvert/testsuite_test.go @@ -171,5 +171,6 @@ func TestKonvertSuite(test *testing.T) { }, }, evetest.TestCase{Test: TestKvmToKVolumeMigration}, + evetest.TestCase{Test: TestFirstBootEVEKAppVolume}, ) } From 0d9656cae2972b8e545cbc27d279363550bfda42 Mon Sep 17 00:00:00 2001 From: eriknordmark Date: Wed, 9 Sep 2026 22:59:06 +0200 Subject: [PATCH 10/10] evetest: identity restore after losing /persist Before the conversion repartitions a boot disk it copies the files a device cannot be itself without -- its UUID, its certificates, its last configuration -- onto the CONFIG partition, and restores them at early boot. These two tests exercise that fail-safe on its own, with no resize: /persist is destroyed outright in one, and in the other each critical file is truncated to half its length. Partial corruption is the harder case. An empty /persist is unambiguous; a /persist full of half-written files is not, and the restore has to judge each file on whether it is still valid for its own type, while files it has no validator for fall back to the copies pillar keeps beside them. Restoring too little strands the device, restoring too much discards state it did not need to. The load-bearing assertion in both is not that files reappeared but that a controller-encrypted credential is decrypted from the restored key: files can come back empty or mismatched and satisfy every other check. It has to happen offline, or the device is simply told everything again, so the controller is cut off with an SDN firewall rule rather than by stopping it -- that isolates one device and leaves the harness working. Restoring the path afterwards waits for the device to check in, since reboots are counted from what it reports and the audit runs at teardown. Signed-off-by: eriknordmark Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01NZEoFvMK2UHByU3LAeXsxA --- evetest/tests/konvert/restore_test.go | 228 ++++++++++++++++++++++++ evetest/tests/konvert/testsuite_test.go | 2 + 2 files changed, 230 insertions(+) create mode 100644 evetest/tests/konvert/restore_test.go diff --git a/evetest/tests/konvert/restore_test.go b/evetest/tests/konvert/restore_test.go new file mode 100644 index 00000000000..cdd47433b5a --- /dev/null +++ b/evetest/tests/konvert/restore_test.go @@ -0,0 +1,228 @@ +// Copyright (c) 2026 Zededa, Inc. +// SPDX-License-Identifier: Apache-2.0 + +package konvert_test + +import ( + "testing" + "time" + + // revive:disable:dot-imports + . "github.com/onsi/gomega" + + api "github.com/lf-edge/eve/evetest/grpcapi/go" + + "github.com/lf-edge/eve/evetest" +) + +// TestPersistWipeRestore asserts a device survives losing /persist outright, +// recovering its identity and its last known configuration with no controller +// to ask. +// +// Before the conversion repartitions a boot disk it copies the files a device +// cannot be itself without -- its UUID, its certificates, its last +// configuration -- onto the CONFIG partition, and restores them at early boot +// if /persist comes back empty. This is that fail-safe on its own: no shrink is +// run, /persist is simply destroyed, and the question is whether the device +// comes back as itself. +// +// The load-bearing assertion is not that files reappeared but that a +// controller-encrypted credential can still be decrypted, offline, from the +// restored key. That is a much stronger statement: it means the certificate +// came back intact and usable, the last configuration came back and was +// re-applied, and the two still belong together. Files can be restored empty or +// mismatched and satisfy every other check. +// +// Offline is essential. A device that can reach its controller is simply told +// everything again, so the whole test would pass on a device that recovered +// nothing. The controller is cut off at the network before the device comes +// back up. +// +// Phases: +// 1. Configure an encrypted wireless credential and confirm it decrypts. +// 2. Snapshot the identity, and back it up to the CONFIG partition. +// 3. Cut off the controller, destroy /persist, and boot. +// 4. Assert the identity came back and the credential decrypts again. +// +// Needs an EVE build carrying the conversion (lf-edge/eve#6036, #6063), a TPM, +// and a provider that can edit the device's disk. +func TestPersistWipeRestore(test *testing.T) { + runRestoreTest(test, damagePersistWipe) +} + +// TestBackupCorruptRestore asserts the same recovery when /persist is not lost +// but partly corrupted. +// +// Partial corruption is the harder case, and the one a naive restore gets +// wrong. An empty /persist is unambiguous -- restore everything. A /persist +// full of half-written files is not: the restore has to judge each file on +// whether it is still valid for its own type, replacing the certificates and +// JSON it can tell are broken, while the files it has no validator for fall +// back to the copies pillar keeps alongside them. Restoring too little strands +// the device; restoring too much discards state it did not need to. +// +// The .bak fallbacks are deliberately left intact, because they are what the +// no-validator files recover from. +// +// Same assertions as the wipe: identity back, and the encrypted credential +// decrypted offline from the restored key. +// +// Needs an EVE build carrying the conversion (lf-edge/eve#6036, #6063) and a +// TPM. Unlike the wipe, the damage is done on the running device, so no disk +// editing is required. +func TestBackupCorruptRestore(test *testing.T) { + runRestoreTest(test, damagePersistCorrupt) +} + +// persistDamage is how a restore test breaks /persist. It returns once the +// device is back up with the damage in place. +type persistDamage struct { + name string + // needsDiskEditing is true for damage that can only be done with the device + // powered off. + needsDiskEditing bool + apply func(t Gomega, device *evetest.EdgeDevice) +} + +// damagePersistWipe destroys the filesystem on /persist while the device is +// off, so that EVE reformats it empty on the next boot. +// +// Done to the partition rather than by deleting files: the fail-safe is meant +// to survive a filesystem that is gone, and emptying it from inside would leave +// the filesystem itself -- and everything EVE infers from finding one -- intact. +var damagePersistWipe = persistDamage{ + name: "wiping /persist", + needsDiskEditing: true, + apply: func(t Gomega, device *evetest.EdgeDevice) { + device.SyncDisks() + device.PowerOff() + device.DestroyPartitionFilesystem("P3") + // Not waiting on the reboot signal: the device comes back to a + // controller it cannot reach, so nothing will be reported to watch for. + device.PowerOn(false) + waitDeviceResponds(t, device) + }, +} + +// damagePersistCorrupt truncates each critical file on /persist to half its +// length on the running device, then reboots. +// +// Truncated in place rather than replaced with garbage, because that is what a +// torn write looks like: a file that starts out correct and stops. The .bak +// copies are left alone -- they are the fallback the files without a validator +// recover through, and destroying them would test a different, unrecoverable +// scenario. +var damagePersistCorrupt = persistDamage{ + name: "corrupting the files on /persist", + needsDiskEditing: false, + apply: func(t Gomega, device *evetest.EdgeDevice) { + const script = `set -u +TRUNCATED=0 +for f in checkpoint/lastconfig checkpoint/controllercerts \ + certs/ecdh.cert.pem certs/attest.cert.pem certs/ek.cert.pem \ + status/nim/DevicePortConfigList/global.json \ + status/zedclient/OnboardingStatus/global.json; do + p=/persist/$f + [ -f "$p" ] || { echo "absent, skipping: $f"; continue; } + size=$(stat -c%s "$p") + if truncate -s $((size / 2)) "$p"; then + echo "truncated $f: $size -> $((size / 2))" + TRUNCATED=$((TRUNCATED + 1)) + else + echo "FAIL: could not truncate $f"; exit 1 + fi +done +for b in checkpoint/lastconfig.bak checkpoint/controllercerts.bak; do + [ -f /persist/$b ] && echo "kept intact: $b" || echo "WARN: no fallback: $b" +done +sync +[ "$TRUNCATED" -ge 1 ] || { echo "FAIL: nothing was truncated"; exit 1; } +echo "CORRUPTED=$TRUNCATED"` + out, err := runEVEWithTimeout(device, script, 3*time.Minute) + t.Expect(err).NotTo(HaveOccurred(), "could not corrupt /persist:\n%s", out) + t.Expect(out).To(ContainSubstring("CORRUPTED="), + "could not corrupt /persist:\n%s", out) + evetest.Logger().Infof("corruption: %s", out) + device.SyncDisks() + device.PowerOff() + device.PowerOn(false) + waitDeviceResponds(t, device) + }, +} + +// runRestoreTest is the body both restore tests share; they differ only in how +// /persist is broken. +func runRestoreTest(test *testing.T, damage persistDamage) { + evetestT := evetest.Init(test) + t := NewGomegaWithT(evetestT) + defer evetest.Close() + + defineSharedParameters() + p := resolveDeviceParams(t) + requirePinnedInitialVersion(t, p) + t.Expect(p.withTPM).To(BeTrue(), + "this test needs a TPM: the key that must survive is TPM-resident") + + var extra []evetest.Requirement + if damage.needsDiskEditing { + extra = append(extra, evetest.RequireCapabilities{ + Capabilities: []api.Capability{api.Capability_CAPABILITY_EDIT_DEVICE_DISK}, + }) + } + device := setupDevice(t, p, evetest.FilesystemEXT4, nil, + evetest.CreateFromScratchWithLiveImage, extra...) + log := evetest.Logger() + + devConfig := evetest.NewEdgeDeviceConfig(devName) + applyMgmtNetwork(device, devConfig) + devConfig.SetConfigProperties(shortBaseImageCooldown()) + device.ApplyConfig(devConfig, true, true) + + // The restore code ships with the conversion, so the device has to be on a + // build that carries it before anything is broken. + log.Infof("landing the restore code at %s", p.targetVersion) + device.UpgradeEVE(p.targetVersion, evetest.HypervisorKVM, + evetest.BaseOSDatastoreHTTP, true, false) + evetest.Checkpoint("restore-code-landed") + + // Phase 1. Confirmed working before the damage, so that a failure afterwards + // is the restore's and not a credential that never decrypted at all. + log.Infof("configuring an encrypted wireless credential") + addEncryptedWiFiPort(devConfig) + device.ApplyConfig(devConfig, true, true) + assertWiFiCredentialsDecrypted(t, device, 5*time.Minute) + evetest.Checkpoint("credential-decrypts") + + // Phase 2. + deviceUUID := readDeviceUUID(t, device) + identity := snapshotIdentity(t, device) + log.Infof("device UUID before the damage: %s", deviceUUID) + log.Infof("backing identity up to the CONFIG partition") + backupIdentityToConfig(t, device) + evetest.Checkpoint("identity-backed-up") + + // Phase 3. The controller goes away first: the device must come back up + // with no way to be told anything, or it would be handed back what it was + // supposed to recover. + isolateFromController(restoreBaseNetworkModel) + defer restoreControllerAccess(t, device, restoreBaseNetworkModel) + + log.Infof("%s", damage.name) + damage.apply(t, device) + evetest.Checkpoint("damaged-and-rebooted") + + // Phase 4. + restoreOK := false + defer func() { + if !restoreOK { + dumpRestoreState(device) + } + }() + log.Infof("the device must have recovered its identity offline") + assertDeviceUUIDUnchanged(t, device, deviceUUID) + assertIdentityRestored(t, device, identity) + log.Infof("and must decrypt the credential from the restored key, still offline") + assertWiFiCredentialsDecrypted(t, device, 8*time.Minute) + restoreOK = true + evetest.Checkpoint("recovered-offline") +} diff --git a/evetest/tests/konvert/testsuite_test.go b/evetest/tests/konvert/testsuite_test.go index b0b6a1b65c7..20604bbf3bb 100644 --- a/evetest/tests/konvert/testsuite_test.go +++ b/evetest/tests/konvert/testsuite_test.go @@ -136,6 +136,8 @@ func TestKonvertSuite(test *testing.T) { evetest.TestCase{Test: TestKvmToKContentTree}, evetest.TestCase{Test: TestKvmToKAppRecreate}, evetest.TestCase{Test: TestKvmToKRepartitionGeometry}, + evetest.TestCase{Test: TestPersistWipeRestore}, + evetest.TestCase{Test: TestBackupCorruptRestore}, evetest.TestCase{ Test: TestKvmToKRepartition, Variants: []evetest.TestVariant{