| 1 | package vm |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "path/filepath" |
| 7 | "strings" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/lima-vm/lima/v2/pkg/limatype" |
| 11 | "github.com/lima-vm/lima/v2/pkg/store" |
| 12 | "github.com/sylvinus/agent-vm/internal/host" |
| 13 | "golang.org/x/sys/windows" |
| 14 | ) |
| 15 | |
| 16 | func stopInstance(ctx context.Context, inst *limatype.Instance) error { |
| 17 | requested, err := host.RequestInstanceStop(inst.Dir) |
| 18 | if err != nil { |
| 19 | return err |
| 20 | } |
| 21 | if !requested { |
| 22 | return fmt.Errorf("Cage 环境的停止通知不可用;保留环境,请查看 hostagent 日志") |
| 23 | } |
| 24 | ctx, cancel := context.WithTimeout(ctx, 3*time.Minute+10*time.Second) |
| 25 | defer cancel() |
| 26 | ticker := time.NewTicker(250 * time.Millisecond) |
| 27 | defer ticker.Stop() |
| 28 | for { |
| 29 | select { |
| 30 | case <-ctx.Done(): |
| 31 | return fmt.Errorf("等待 Cage 环境保存并停止超时: %w", ctx.Err()) |
| 32 | case <-ticker.C: |
| 33 | current, err := store.Inspect(ctx, inst.Name) |
| 34 | if err != nil { |
| 35 | return err |
| 36 | } |
| 37 | if current.Status == limatype.StatusStopped { |
| 38 | return nil |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | func stopOrphanedInstance(_ context.Context, inst *limatype.Instance) error { |
| 45 | if inst.VMType != limatype.QEMU || inst.DriverPID <= 0 { |
| 46 | return fmt.Errorf("unsupported orphaned VM driver") |
| 47 | } |
| 48 | handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.PROCESS_TERMINATE|windows.SYNCHRONIZE, false, uint32(inst.DriverPID)) |
| 49 | if err != nil { |
| 50 | return err |
| 51 | } |
| 52 | defer windows.CloseHandle(handle) |
| 53 | image := make([]uint16, 32768) |
| 54 | size := uint32(len(image)) |
| 55 | if err := windows.QueryFullProcessImageName(handle, 0, &image[0], &size); err != nil { |
| 56 | return err |
| 57 | } |
| 58 | if !strings.EqualFold(filepath.Base(windows.UTF16ToString(image[:size])), "qemu-system-x86_64.exe") || !isQEMU(inst.DriverPID, inst.Dir, inst.Name) { |
| 59 | return fmt.Errorf("orphaned VM process identity changed; no process was stopped") |
| 60 | } |
| 61 | if err := windows.TerminateProcess(handle, 1); err != nil { |
| 62 | return err |
| 63 | } |
| 64 | state, err := windows.WaitForSingleObject(handle, 5000) |
| 65 | if err != nil { |
| 66 | return err |
| 67 | } |
| 68 | if state != windows.WAIT_OBJECT_0 { |
| 69 | return fmt.Errorf("orphaned QEMU did not stop") |
| 70 | } |
| 71 | return nil |
| 72 | } |