| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | _ "embed" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "net/http" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "sync" |
| 12 | "time" |
| 13 | |
| 14 | "al.essio.dev/pkg/shellescape" |
| 15 | "github.com/docker/go-units" |
| 16 | "github.com/sylvinus/agent-vm/internal/cage" |
| 17 | "github.com/sylvinus/agent-vm/internal/vm" |
| 18 | "go.yaml.in/yaml/v3" |
| 19 | ) |
| 20 | |
| 21 | |
| 22 | var macOSResourceProbe string |
| 23 | |
| 24 | type macOSResourceSample struct { |
| 25 | Version int `json:"version"` |
| 26 | Total uint64 `json:"total_bytes"` |
| 27 | Available uint64 `json:"available_bytes"` |
| 28 | Free uint64 `json:"free_bytes"` |
| 29 | Inactive uint64 `json:"inactive_bytes"` |
| 30 | Wired uint64 `json:"wired_bytes"` |
| 31 | Compressed uint64 `json:"compressed_bytes"` |
| 32 | SwapTotal *uint64 `json:"swap_total_bytes,omitempty"` |
| 33 | SwapFree *uint64 `json:"swap_free_bytes,omitempty"` |
| 34 | CPUs int `json:"cpus"` |
| 35 | CPUTicks [4]uint32 `json:"cpu_ticks"` |
| 36 | Boot int64 `json:"boot_seconds"` |
| 37 | Pressure *uint32 `json:"pressure_level,omitempty"` |
| 38 | } |
| 39 | |
| 40 | type macOSResourceObserver struct { |
| 41 | mu sync.Mutex |
| 42 | previous macOSResourceSample |
| 43 | observedAt time.Time |
| 44 | } |
| 45 | |
| 46 | func parseMacOSResourceSample(data []byte, memory uint64, cpus int) (macOSResourceSample, error) { |
| 47 | var sample macOSResourceSample |
| 48 | if json.Unmarshal(data, &sample) != nil || sample.Version != 1 || sample.Total != memory || sample.CPUs != cpus || sample.Boot <= 0 || |
| 49 | sample.Available > sample.Total || sample.Free > sample.Total || sample.Inactive > sample.Total-sample.Free || |
| 50 | sample.Available != sample.Free+sample.Inactive || sample.Wired > sample.Total || sample.Compressed > sample.Total || |
| 51 | (sample.SwapTotal == nil) != (sample.SwapFree == nil) || sample.SwapTotal != nil && *sample.SwapFree > *sample.SwapTotal { |
| 52 | return sample, errors.New("macOS 客机返回的资源用量不完整或与启动配置不一致") |
| 53 | } |
| 54 | return sample, nil |
| 55 | } |
| 56 | |
| 57 | func (observer *macOSResourceObserver) observation(sample macOSResourceSample, now time.Time) map[string]any { |
| 58 | var percent *float64 |
| 59 | previous := observer.previous |
| 60 | if previous.Boot == sample.Boot && previous.CPUs == sample.CPUs && now.Sub(observer.observedAt) <= 10*time.Second { |
| 61 | var total, idle uint64 |
| 62 | valid := true |
| 63 | for index, value := range sample.CPUTicks { |
| 64 | if value < previous.CPUTicks[index] { |
| 65 | valid = false |
| 66 | break |
| 67 | } |
| 68 | delta := uint64(value - previous.CPUTicks[index]) |
| 69 | total += delta |
| 70 | if index == 2 { |
| 71 | idle = delta |
| 72 | } |
| 73 | } |
| 74 | if valid && total > 0 { |
| 75 | value := 100 * float64(total-idle) / float64(total) |
| 76 | percent = &value |
| 77 | } |
| 78 | } |
| 79 | observer.previous, observer.observedAt = sample, now |
| 80 | result := map[string]any{"version": 1, "observed_at": now, "cpus": sample.CPUs, "cpu_percent": percent, "guest": sample} |
| 81 | if sample.Pressure != nil { |
| 82 | result["pressure"] = *sample.Pressure > 1 |
| 83 | } |
| 84 | return result |
| 85 | } |
| 86 | |
| 87 | func (s *Server) readMacOSResources(ctx context.Context, memory uint64, cpus int) (map[string]any, error) { |
| 88 | observer := &s.macResources |
| 89 | observer.mu.Lock() |
| 90 | defer observer.mu.Unlock() |
| 91 | ctx, cancel := context.WithTimeout(ctx, 4*time.Second) |
| 92 | defer cancel() |
| 93 | command := "exec " + shellescape.QuoteCommand([]string{macCLIInstall + "/bin/python3", "-I", "-c", macOSResourceProbe}) |
| 94 | data, err := s.guestControl(ctx, command, "macos-resources") |
| 95 | if err != nil { |
| 96 | return nil, errors.New("暂时无法读取 macOS 客机资源用量,请确认客机已启动并完成组件安装") |
| 97 | } |
| 98 | sample, err := parseMacOSResourceSample(data, memory, cpus) |
| 99 | if err != nil { |
| 100 | return nil, err |
| 101 | } |
| 102 | return observer.observation(sample, time.Now()), nil |
| 103 | } |
| 104 | |
| 105 | func (s *Server) resourceAllocationLimits(allocation cage.ResourceAllocation) (int, int, error) { |
| 106 | if s.macosGuest == nil { |
| 107 | return allocation.Limits() |
| 108 | } |
| 109 | requirements, err := vm.ReadMacOSResourceRequirements(s.instanceDir()) |
| 110 | if err != nil { |
| 111 | return 0, 0, err |
| 112 | } |
| 113 | return requirements.Limits(allocation) |
| 114 | } |
| 115 | |
| 116 | func (s *Server) macOSResourceStatus(w http.ResponseWriter, r *http.Request) { |
| 117 | requirements, err := vm.ReadMacOSResourceRequirements(s.instanceDir()) |
| 118 | if err != nil { |
| 119 | requestError(w, err) |
| 120 | return |
| 121 | } |
| 122 | allocation, err := cage.LoadResourceAllocation(s.configPath) |
| 123 | if err != nil { |
| 124 | requestError(w, err) |
| 125 | return |
| 126 | } |
| 127 | memory, cpus, allocationErr := allocation.Limits() |
| 128 | if allocationErr == nil { |
| 129 | _, _, allocationErr = requirements.Limits(allocation) |
| 130 | } else { |
| 131 | memory, cpus = allocation.MemoryGiB, allocation.CPUs |
| 132 | } |
| 133 | var configured struct { |
| 134 | Memory string `yaml:"memory"` |
| 135 | CPUs int `yaml:"cpus"` |
| 136 | } |
| 137 | data, err := os.ReadFile(filepath.Join(s.instanceDir(), "lima.yaml")) |
| 138 | if err != nil || yaml.Unmarshal(data, &configured) != nil { |
| 139 | requestError(w, errors.New("无法读取 macOS 客机启动配置")) |
| 140 | return |
| 141 | } |
| 142 | maximum, err := units.RAMInBytes(configured.Memory) |
| 143 | if err != nil || maximum < 1<<30 || configured.CPUs < 1 { |
| 144 | requestError(w, errors.New("macOS 客机启动资源配置无效")) |
| 145 | return |
| 146 | } |
| 147 | running := s.vmRunning() |
| 148 | var observation map[string]any |
| 149 | if running { |
| 150 | observation, err = s.readMacOSResources(r.Context(), uint64(maximum), configured.CPUs) |
| 151 | allocationErr = errors.Join(allocationErr, err) |
| 152 | } |
| 153 | resourceError := "" |
| 154 | if allocationErr != nil { |
| 155 | resourceError = allocationErr.Error() |
| 156 | } |
| 157 | maxMemory, maxCPUs := cage.ResourceLimits() |
| 158 | jsonReply(w, map[string]any{"runtime": "vz-macos", "memory_policy": "fixed", "automatic_reclaim": false, |
| 159 | "running": running, "automatic": allocation.Automatic, "memory_gib": memory, "cpus": cpus, |
| 160 | "min_memory_gib": requirements.MemoryGiB, "min_cpus": requirements.CPUs, "minimum_requirements": requirements, |
| 161 | "max_memory_gib": maxMemory, "max_cpus": maxCPUs, "recommended_memory_bytes": uint64(maxMemory) << 30, "recommended_cpus": maxCPUs, |
| 162 | "configured_memory_bytes": maximum, "configured_cpus": configured.CPUs, "resource_error": resourceError, |
| 163 | "restart_required": running && (maximum != int64(memory)<<30 || configured.CPUs != cpus), "observation": observation, |
| 164 | "unavailable_observations": []string{"balloon_bytes", "oom_kills", "memory_stall_percent", "host_pressure"}}) |
| 165 | } |