| 1 | |
| 2 | |
| 3 | package guestos |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | |
| 11 | "github.com/google/uuid" |
| 12 | ) |
| 13 | |
| 14 | func windowsVMResources(ctx context.Context, root string, memoryGiB, cpus int) (WindowsVMResourceState, error) { |
| 15 | if (memoryGiB == 0) != (cpus == 0) || memoryGiB < 0 || memoryGiB > 1024 || cpus < 0 || cpus > 1024 { |
| 16 | return WindowsVMResourceState{}, errors.New("Windows 客机资源参数无效") |
| 17 | } |
| 18 | binding, err := LoadWindowsProfile(root) |
| 19 | if err != nil { |
| 20 | return WindowsVMResourceState{}, err |
| 21 | } |
| 22 | if binding == nil { |
| 23 | return WindowsVMResourceState{}, errors.New("此配置尚未绑定Windows客机") |
| 24 | } |
| 25 | var result WindowsVMResourceState |
| 26 | if err := windowsHostManagerCall(ctx, binding.VMID, "resources", memoryGiB, cpus, &result); err != nil { |
| 27 | return result, err |
| 28 | } |
| 29 | if result.CPUs < 1 || result.MemoryStartup < 2<<30 || result.State == "" { |
| 30 | return result, errors.New("Windows 客机资源状态无效") |
| 31 | } |
| 32 | if memoryGiB != 0 && !result.MatchesAllocation(memoryGiB, cpus) { |
| 33 | return result, errors.New("Windows 客机资源未达到请求值") |
| 34 | } |
| 35 | return result, nil |
| 36 | } |
| 37 | |
| 38 | func windowsVMResourcesNative(ctx context.Context, id uuid.UUID, memoryGiB, cpus int) (WindowsVMResourceState, error) { |
| 39 | if id == uuid.Nil || (memoryGiB == 0) != (cpus == 0) || memoryGiB < 0 || memoryGiB > 1024 || cpus < 0 || cpus > 1024 { |
| 40 | return WindowsVMResourceState{}, errors.New("Windows 客机资源参数无效") |
| 41 | } |
| 42 | script := fmt.Sprintf("$targetId=[guid]'%s'\n$memoryGiB=%d\n$cpus=%d\n", id.String(), memoryGiB, cpus) + windowsVMResourcesScript |
| 43 | cmd, err := systemPowerShellQuery(ctx, script) |
| 44 | if err != nil { |
| 45 | return WindowsVMResourceState{}, err |
| 46 | } |
| 47 | data, err := cmd.Output() |
| 48 | if ctx.Err() != nil { |
| 49 | return WindowsVMResourceState{}, ctx.Err() |
| 50 | } |
| 51 | if err != nil { |
| 52 | return WindowsVMResourceState{}, errors.New("Windows 客机资源操作未完成,请核对虚拟机状态与管理权限") |
| 53 | } |
| 54 | var result WindowsVMResourceState |
| 55 | if json.Unmarshal(data, &result) != nil || result.CPUs < 1 || result.MemoryStartup < 2<<30 { |
| 56 | return result, errors.New("Windows 客机资源状态无效") |
| 57 | } |
| 58 | if memoryGiB != 0 && !result.MatchesAllocation(memoryGiB, cpus) { |
| 59 | return result, errors.New("Windows 客机资源未达到请求值") |
| 60 | } |
| 61 | return result, nil |
| 62 | } |