| 1 | package guestos |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | _ "embed" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | |
| 10 | "github.com/google/uuid" |
| 11 | ) |
| 12 | |
| 13 | |
| 14 | var hyperVInstanceQuery string |
| 15 | |
| 16 | |
| 17 | |
| 18 | func InspectHyperV(ctx context.Context, id uuid.UUID) (HyperVInspection, error) { |
| 19 | if id == uuid.Nil { |
| 20 | return HyperVInspection{}, errors.New("expected a non-empty Hyper-V VM GUID") |
| 21 | } |
| 22 | report := HyperVInspection{Inspection: Inspect(ctx), VMID: id.String(), Lookup: "unavailable"} |
| 23 | if !report.HostCheckPassed { |
| 24 | return report, nil |
| 25 | } |
| 26 | var actual HyperVInspection |
| 27 | if err := windowsHostManagerCall(ctx, id, "inspect", 0, 0, &actual); err != nil { |
| 28 | if ctx.Err() != nil { |
| 29 | return report, ctx.Err() |
| 30 | } |
| 31 | report.LookupDetail = err.Error() |
| 32 | return report, nil |
| 33 | } |
| 34 | if actual.VMID != id.String() || actual.Lookup != "found" || actual.VM == nil { |
| 35 | return report, errors.New("Windows 系统管理助手返回的虚拟机身份无效") |
| 36 | } |
| 37 | actual.Inspection = report.Inspection |
| 38 | return actual, nil |
| 39 | } |
| 40 | |
| 41 | func inspectHyperVNative(ctx context.Context, id uuid.UUID) (HyperVInspection, error) { |
| 42 | if id == uuid.Nil { |
| 43 | return HyperVInspection{}, errors.New("expected a non-empty Hyper-V VM GUID") |
| 44 | } |
| 45 | report := HyperVInspection{Inspection: Inspection{Guest: Windows11, HostCheckPassed: true, WorkbenchSupport: nativeWorkbenchSupport(Windows11, true)}, VMID: id.String(), Lookup: "unavailable"} |
| 46 | |
| 47 | query := fmt.Sprintf("$targetId = [guid]'%s'\n", id.String()) + hyperVInstanceQuery |
| 48 | cmd, err := systemPowerShellQuery(ctx, query) |
| 49 | if err != nil { |
| 50 | return report, err |
| 51 | } |
| 52 | output, err := cmd.Output() |
| 53 | if ctx.Err() != nil { |
| 54 | return report, ctx.Err() |
| 55 | } |
| 56 | if err != nil { |
| 57 | report.LookupDetail = "无法读取该虚拟机的 Hyper-V 配置,请核对当前用户权限与虚拟机状态。" |
| 58 | return report, nil |
| 59 | } |
| 60 | if err := json.Unmarshal(output, &report.VM); err != nil { |
| 61 | return report, errors.New("Hyper-V 返回了无法识别的虚拟机配置") |
| 62 | } |
| 63 | if report.VM == nil { |
| 64 | report.Lookup = "not-found" |
| 65 | report.LookupDetail = "当前用户未查询到此标识的本机 Hyper-V 虚拟机。" |
| 66 | } else { |
| 67 | report.Lookup = "found" |
| 68 | } |
| 69 | return report, nil |
| 70 | } |