Files
Reims-Go/internal/macos/macosdriver/clone.go
T
Nwflower d74868589d fix(macos): give CoW clones their own SSH port forward
CloneCoW built reims.CreateOpts without SSHPort even though the field and
the --ssh-port argument both exist, so every CoW clone came up with no host
SSH forward. MCP temporary sessions and any other clone then failed every
SSH-based guest tool (guest_exec, guest_wait_ready, test_run) with a port
that nothing listened on.

Pick the next free port after the source VM's forward and pass it to create;
a source without forwarding still yields a clone without one. Add
TestCloneSSHPort for the selection logic.

model: deepseek/deepseek-v4.1-flash
agent: lead (DeepSeek Harness)
2026-12-04 05:39:40 -07:00

194 lines
7.1 KiB
Go

package macosdriver
import (
"context"
"errors"
"fmt"
"io"
"net"
"os"
"path/filepath"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/vmstart"
)
var _ driver.CloneDriver = (*ReimsMacOSDriver)(nil)
var _ driver.CloneResultDriver = (*ReimsMacOSDriver)(nil)
// portInUse reports whether a TCP port is already bound on the loopback
// interface, so a clone picks a forward that will not collide.
func portInUse(port int) bool {
l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
if err != nil {
return true
}
_ = l.Close()
return false
}
// cloneSSHPort gives a clone a host SSH forward of its own. The source VM's
// forward is still bound, so reusing its number would fail to start, and a
// clone without a forward rejects every SSH-based guest tool. A source without
// forwarding stays without one.
func cloneSSHPort(sourcePort int, inUse func(int) bool) int {
if sourcePort <= 0 {
return 0
}
for port := sourcePort + 1; port < 65535; port++ {
if !inUse(port) {
return port
}
}
return sourcePort + 1
}
func (d *ReimsMacOSDriver) CloneCoWWithInfo(ctx context.Context, sourceName, cloneName string, stdout, stderr io.Writer) (driver.VMInfo, error) {
cloneName = strings.TrimSpace(cloneName)
if err := d.CloneCoW(ctx, sourceName, cloneName, stdout, stderr); err != nil {
return driver.VMInfo{}, err
}
cloned, err := d.Show(ctx, cloneName)
if err != nil {
return driver.VMInfo{}, d.cleanupFailedClone(ctx, cloneName, err, stdout, stderr)
}
return cloned, nil
}
func (d *ReimsMacOSDriver) cleanupFailedClone(ctx context.Context, cloneName string, cause error, stdout, stderr io.Writer) error {
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
if cleanupErr := d.Delete(cleanupCtx, cloneName, false, stdout, stderr); cleanupErr != nil {
return errors.Join(cause, fmt.Errorf("clean up incomplete clone %q: %w", cloneName, cleanupErr))
}
return cause
}
func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName string, stdout, stderr io.Writer) (resultErr error) {
c, active, err := d.startClient()
if err != nil {
return err
}
cfg := d.getConfig()
cloneName = strings.TrimSpace(cloneName)
if cloneName == "" {
return fmt.Errorf("clone name is required")
}
if strings.EqualFold(sourceName, cloneName) {
return fmt.Errorf("clone name must differ from source")
}
src, release, err := startprep.LockVM(ctx, c, sourceName)
if err != nil {
return err
}
defer release()
if reims.HasSuspendState(src.Directory) {
return i18n.NewCodedError(c.Locale, "E_VM_CLONE_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": sourceName}, nil)
}
if src.HasInstaller {
return fmt.Errorf("exit recovery mode before cloning %s", sourceName)
}
srcDisk := src.DiskPath()
if srcDisk == "" {
return fmt.Errorf("VM %s has no disk path", sourceName)
}
if _, err := os.Stat(srcDisk); err != nil {
return fmt.Errorf("source disk %s: %w", srcDisk, err)
}
rep := host.Inspect(cfg.DataRoot)
for _, issue := range reims.ValidateCreate(reims.CreateOpts{Name: cloneName, CPUs: max(src.CPUs, 1), Memory: src.Memory}, rep, cfg.Locale) {
if issue.Field == "name" {
return fmt.Errorf("invalid clone name %q: %s", cloneName, issue.Message)
}
}
overlayPath, err := c.NewCoWImagePath(cloneName)
if err != nil {
return err
}
releaseDisks, err := c.LockCoWDisks(ctx, srcDisk, overlayPath)
if err != nil {
return err
}
cloneRegistered := false
defer func() {
releaseDisks()
if resultErr != nil && cloneRegistered {
resultErr = d.cleanupFailedClone(ctx, cloneName, resultErr, stdout, stderr)
}
}()
if err := c.CheckCoWCloneSource(ctx, sourceName, srcDisk, cloneName); err != nil {
return err
}
cloneTargetOpts := reims.CreateOpts{Name: cloneName}
registered, err := c.List(ctx)
if err != nil {
return fmt.Errorf("check clone target directory: %w", err)
}
if issue := reims.ValidateCreateTargetDir(cfg.XDGDataDir(), cloneTargetOpts, registered, cfg.Locale); issue != nil {
return errors.New(issue.Message)
}
if _, err := os.Lstat(overlayPath); err == nil {
return fmt.Errorf("clone overlay already exists: %s", overlayPath)
} else if !os.IsNotExist(err) {
return err
}
env := rt.BuildChildEnv(&cfg, active)
_, _ = fmt.Fprintf(stdout, "Creating CoW overlay for %s backed by %s...\n", cloneName, filepath.Base(srcDisk))
if err := reims.CreateCoWOverlay(ctx, active.QemuImgPath(), env, srcDisk, overlayPath, stdout, stderr); err != nil {
return err
}
audio, network, logs, capture := src.Audio, src.Network, src.Logs, src.Capture
// 克隆默认回到 NAT,不能复用源虚拟机的独立帧端口。
if src.NetworkMode == "bridge" {
network = true
}
// The clone needs its own host SSH forward: an MCP test run starts it and
// reaches the guest over SSH, while the source VM's own forward is still
// bound. Reusing the source port would fail to start, and dropping the
// forward leaves the clone with no ssh_port so every guest tool fails.
// Keep forwarding on when the source has it and pick the next free port.
createOpts := reims.CreateOpts{Name: cloneName, SourceMode: "disk", Disk: overlayPath, DiskMode: "in-place", DiskController: src.DiskController, CPUs: src.CPUs, Memory: src.Memory, Graphics: src.Graphics, GPU: src.GPU, Resolution: src.Resolution, Displays: src.Displays, Capture: &capture, Audio: &audio, Network: &network, SSHPort: cloneSSHPort(src.SSHPort, portInUse), Logs: &logs, Start: false}
if err := c.RegisterCoWClone(ctx, createOpts, stdout, stderr); err != nil {
return err
}
cloneRegistered = true
if postSet, ok := reims.PostCreateSetOpts(createOpts); ok {
if err := c.Set(ctx, postSet, stdout, stderr); err != nil {
_, _ = fmt.Fprintf(stdout, "Warning: could not apply clone settings: %v\n", err)
}
}
cloned, err := c.Show(ctx, cloneName)
if err != nil {
return err
}
if err := driver.WriteOwnerDriver(cloned.Directory, d.ID()); err != nil {
return err
}
if src.GuestLang != "" {
prep, prepErr := startprep.New(cfg, func(line string) { _, _ = fmt.Fprintln(stdout, line) })
if prepErr == nil {
prepErr = prep.ApplyGuestLang(ctx, cloned.Directory, src.GuestLang, false)
}
if prepErr != nil {
_, _ = fmt.Fprintf(stdout, "Warning: could not apply clone language (%s): %v\n", src.GuestLang, prepErr)
}
}
if err := reims.WriteReleaseRecord(cloned.Directory, reims.ReadReleaseRecord(src.Directory)); err != nil {
_, _ = fmt.Fprintf(stdout, "Warning: could not copy macOS release: %v\n", err)
}
if vmstart.HasSavedVMAffinity(src.Directory) {
if _, err := vmstart.SaveVMAffinity(cloned.Directory, vmstart.ReadVMAffinity(src.Directory), rep.LogicalCPUs); err != nil {
_, _ = fmt.Fprintf(stdout, "Warning: could not copy CPU affinity setting: %v\n", err)
}
}
_, _ = fmt.Fprintf(stdout, "CoW clone %s ready (backing image %s untouched)\n", cloneName, srcDisk)
return nil
}