Skip to content
Merged
8 changes: 5 additions & 3 deletions evetest/Dockerfile.broker
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion evetest/Dockerfile.evetest
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion evetest/VERSION
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
# Evetest version. Increment this manually whenever changes are made to the evetest framework.
1.6
1.7
90 changes: 84 additions & 6 deletions evetest/broker/broker.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down Expand Up @@ -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(
Expand Down
158 changes: 158 additions & 0 deletions evetest/broker/diskedit.go
Original file line number Diff line number Diff line change
@@ -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
}
47 changes: 47 additions & 0 deletions evetest/devconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading