| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "net/http" |
| 11 | "time" |
| 12 | |
| 13 | "github.com/sylvinus/agent-vm/internal/cage" |
| 14 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 15 | "github.com/sylvinus/agent-vm/internal/host" |
| 16 | ) |
| 17 | |
| 18 | func windowsResourceMaximum() (int, int) { |
| 19 | shareMemory, shareCPUs := cage.ResourceLimits() |
| 20 | managerMemory, managerCPUs := guestos.WindowsVMResourceCeiling(host.MemGiB(), host.CPUs()) |
| 21 | return min(shareMemory, managerMemory), min(shareCPUs, managerCPUs) |
| 22 | } |
| 23 | |
| 24 | func windowsAllocationLimits(allocation cage.ResourceAllocation, maxMemory, maxCPUs int) (int, int, error) { |
| 25 | if maxMemory < 4 || maxCPUs < 2 { |
| 26 | return 0, 0, errors.New("主机可分配的资源不足,Windows 11 客机至少需要 4 GiB 内存与 2 个逻辑核心") |
| 27 | } |
| 28 | if allocation.Automatic { |
| 29 | return maxMemory, maxCPUs, nil |
| 30 | } |
| 31 | if allocation.MemoryGiB < 4 || allocation.MemoryGiB > maxMemory || allocation.CPUs < 2 || allocation.CPUs > maxCPUs { |
| 32 | return 0, 0, fmt.Errorf("Windows 客机内存须为 4–%d GiB,CPU 须为 2–%d 个逻辑核心", maxMemory, maxCPUs) |
| 33 | } |
| 34 | return allocation.MemoryGiB, allocation.CPUs, nil |
| 35 | } |
| 36 | |
| 37 | func (s *Server) configuredWindowsResources() (int, int, error) { |
| 38 | allocation, err := cage.LoadResourceAllocation(s.configPath) |
| 39 | if err != nil { |
| 40 | return 0, 0, err |
| 41 | } |
| 42 | maxMemory, maxCPUs := windowsResourceMaximum() |
| 43 | return windowsAllocationLimits(allocation, maxMemory, maxCPUs) |
| 44 | } |
| 45 | |
| 46 | func (s *Server) windowsResourceSample(ctx context.Context, state guestos.WindowsVMResourceState) (map[string]any, error) { |
| 47 | cmd, err := guestos.WindowsRelayCommand(ctx, s.profile, "resources") |
| 48 | if err != nil { |
| 49 | return nil, err |
| 50 | } |
| 51 | cmd.Stdin = bytes.NewBufferString("{\"action\":\"sample\"}\n") |
| 52 | cmd.Stderr = io.Discard |
| 53 | var buffer bytes.Buffer |
| 54 | cmd.Stdout = &boundedWindowsStatusWriter{buffer: &buffer, remaining: 16384} |
| 55 | if err = cmd.Run(); err != nil { |
| 56 | return nil, errors.New("Windows 客机资源观测尚未连接") |
| 57 | } |
| 58 | var observation map[string]any |
| 59 | decoder := json.NewDecoder(&buffer) |
| 60 | if decoder.Decode(&observation) != nil || decoder.Decode(new(any)) != io.EOF || observation["version"] != float64(1) || observation["cpus"] != float64(state.CPUs) { |
| 61 | return nil, errors.New("Windows 客机资源观测与配置不一致") |
| 62 | } |
| 63 | guest, ok := observation["guest"].(map[string]any) |
| 64 | if !ok { |
| 65 | return nil, errors.New("Windows 客机内存观测无效") |
| 66 | } |
| 67 | total, tok := guest["total_bytes"].(float64) |
| 68 | available, aok := guest["available_bytes"].(float64) |
| 69 | if !tok || !aok || total < 2<<30 || available < 0 || available > total { |
| 70 | return nil, errors.New("Windows 客机内存观测无效") |
| 71 | } |
| 72 | maximum := state.MemoryStartup |
| 73 | if state.DynamicMemory { |
| 74 | maximum = state.MemoryMaximum |
| 75 | } |
| 76 | observation["maximum_bytes"] = maximum |
| 77 | observation["target_bytes"] = state.MemoryAssigned |
| 78 | return observation, nil |
| 79 | } |
| 80 | func (s *Server) windowsResourceStatus(w http.ResponseWriter, r *http.Request) { |
| 81 | ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) |
| 82 | defer cancel() |
| 83 | state, err := guestos.WindowsVMResources(ctx, s.profile, 0, 0) |
| 84 | if err != nil { |
| 85 | requestError(w, err) |
| 86 | return |
| 87 | } |
| 88 | allocation, err := cage.LoadResourceAllocation(s.configPath) |
| 89 | if err != nil { |
| 90 | requestError(w, err) |
| 91 | return |
| 92 | } |
| 93 | maxMemory, maxCPUs := windowsResourceMaximum() |
| 94 | memory, cpus, err := windowsAllocationLimits(allocation, maxMemory, maxCPUs) |
| 95 | allocationError := "" |
| 96 | if err != nil { |
| 97 | allocationError = err.Error() |
| 98 | if !allocation.Automatic { |
| 99 | memory, cpus = allocation.MemoryGiB, allocation.CPUs |
| 100 | } |
| 101 | } |
| 102 | maximum := state.MemoryStartup |
| 103 | if state.DynamicMemory { |
| 104 | maximum = state.MemoryMaximum |
| 105 | } |
| 106 | running := state.State == "Running" |
| 107 | var observation map[string]any |
| 108 | if running { |
| 109 | if sample, sampleErr := s.windowsResourceSample(ctx, state); sampleErr == nil { |
| 110 | observation = sample |
| 111 | } else if allocationError == "" { |
| 112 | allocationError = sampleErr.Error() |
| 113 | } |
| 114 | } |
| 115 | jsonReply(w, map[string]any{"runtime": "hyperv", "running": running, "automatic": allocation.Automatic, "memory_gib": memory, "cpus": cpus, "min_memory_gib": 4, "min_cpus": 2, "max_memory_gib": maxMemory, "max_cpus": maxCPUs, "resource_error": allocationError, "recommended_memory_bytes": uint64(maxMemory) << 30, "recommended_cpus": maxCPUs, "configured_memory_bytes": maximum, "configured_cpus": state.CPUs, "dynamic_memory": state.DynamicMemory, "resources_verified": allocationError == "", "restart_required": running && err == nil && !state.MatchesAllocation(memory, cpus), "observation": observation, "unavailable_observations": []string{"oom_kills", "memory_stall_percent", "swap_total_bytes", "swap_free_bytes", "host_pressure"}}) |
| 116 | } |
| 117 | func (s *Server) applyWindowsResources(w http.ResponseWriter, r *http.Request) { |
| 118 | var input struct { |
| 119 | Allocation *cage.ResourceAllocation `json:"allocation"` |
| 120 | } |
| 121 | if !readJSON(w, r, &input) { |
| 122 | return |
| 123 | } |
| 124 | if input.Allocation != nil { |
| 125 | maxMemory, maxCPUs := windowsResourceMaximum() |
| 126 | _, _, err := windowsAllocationLimits(*input.Allocation, maxMemory, maxCPUs) |
| 127 | if err != nil { |
| 128 | requestError(w, err) |
| 129 | return |
| 130 | } |
| 131 | if !s.op.TryLock() { |
| 132 | http.Error(w, "另一个操作仍在进行,请稍候", http.StatusConflict) |
| 133 | return |
| 134 | } |
| 135 | err = writePrivate(cage.ResourceAllocationPath(s.configPath), input.Allocation) |
| 136 | s.op.Unlock() |
| 137 | if err != nil { |
| 138 | requestError(w, err) |
| 139 | return |
| 140 | } |
| 141 | jsonReply(w, map[string]bool{"ok": true}) |
| 142 | return |
| 143 | } |
| 144 | s.launch(w, "resources", func() error { |
| 145 | memory, cpus, err := s.configuredWindowsResources() |
| 146 | if err != nil { |
| 147 | return err |
| 148 | } |
| 149 | ctx, cancel := context.WithTimeout(s.operationContext(), 5*time.Minute) |
| 150 | defer cancel() |
| 151 | state, err := guestos.WindowsVMResources(ctx, s.profile, 0, 0) |
| 152 | if err != nil { |
| 153 | return err |
| 154 | } |
| 155 | if state.State == "Running" { |
| 156 | if err = s.stopWindowsGuest(); err != nil { |
| 157 | return err |
| 158 | } |
| 159 | } |
| 160 | if _, err = guestos.WindowsVMResources(ctx, s.profile, memory, cpus); err != nil { |
| 161 | return err |
| 162 | } |
| 163 | return s.startWindowsGuest() |
| 164 | }) |
| 165 | } |