| 1 | package cage |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "io" |
| 9 | "math" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "strconv" |
| 13 | "strings" |
| 14 | "time" |
| 15 | |
| 16 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 17 | "github.com/sylvinus/agent-vm/internal/host" |
| 18 | "github.com/sylvinus/agent-vm/internal/usererror" |
| 19 | ) |
| 20 | |
| 21 | |
| 22 | |
| 23 | func ResourceLimits() (memoryGiB, cpus int) { |
| 24 | memoryGiB, cpus = host.MemGiB(), host.CPUs() |
| 25 | if memoryGiB <= 0 { |
| 26 | memoryGiB = 4 |
| 27 | } |
| 28 | if cpus <= 0 { |
| 29 | cpus = 2 |
| 30 | } |
| 31 | return host.Cap("memory", memoryGiB, io.Discard), host.Cap("cpus", cpus, io.Discard) |
| 32 | } |
| 33 | |
| 34 | const resourceProbe = `LC_ALL=C; export LC_ALL |
| 35 | awk '/^(MemTotal|MemAvailable|SwapTotal|SwapFree):/ {print $1,$2}' /proc/meminfo |
| 36 | awk '/^(oom_kill|balloon_inflate|balloon_deflate) / {print $1,$2}' /proc/vmstat |
| 37 | printf 'page_size '; getconf PAGESIZE |
| 38 | cat /proc/pressure/memory |
| 39 | head -n 1 /proc/stat |
| 40 | printf 'boot '; cat /proc/sys/kernel/random/boot_id` |
| 41 | |
| 42 | type ResourceSample struct { |
| 43 | Total uint64 `json:"total_bytes"` |
| 44 | Available uint64 `json:"available_bytes"` |
| 45 | SwapTotal uint64 `json:"swap_total_bytes"` |
| 46 | SwapFree uint64 `json:"swap_free_bytes"` |
| 47 | OOMKills uint64 `json:"oom_kills"` |
| 48 | Balloon uint64 `json:"balloon_bytes"` |
| 49 | Stall float64 `json:"memory_stall_percent"` |
| 50 | Boot string `json:"boot_id"` |
| 51 | cpuTotal, cpuIdle uint64 |
| 52 | } |
| 53 | |
| 54 | func parseResources(data []byte) (ResourceSample, error) { |
| 55 | var s ResourceSample |
| 56 | var inflated, deflated, pageSize uint64 |
| 57 | seen := map[string]bool{} |
| 58 | for _, line := range strings.Split(string(data), "\n") { |
| 59 | f := strings.Fields(line) |
| 60 | if len(f) < 2 { |
| 61 | continue |
| 62 | } |
| 63 | key := strings.TrimSuffix(f[0], ":") |
| 64 | n, err := strconv.ParseUint(f[1], 10, 64) |
| 65 | switch key { |
| 66 | case "balloon_inflate", "balloon_deflate", "page_size": |
| 67 | if err != nil || n > 1<<40 { |
| 68 | return s, errors.New("invalid balloon observation") |
| 69 | } |
| 70 | if key == "balloon_inflate" { |
| 71 | inflated = n |
| 72 | } |
| 73 | if key == "balloon_deflate" { |
| 74 | deflated = n |
| 75 | } |
| 76 | if key == "page_size" { |
| 77 | pageSize = n |
| 78 | } |
| 79 | case "MemTotal", "MemAvailable", "SwapTotal", "SwapFree", "oom_kill": |
| 80 | if err != nil || n > 1<<40 { |
| 81 | return s, errors.New("invalid guest resource observation") |
| 82 | } |
| 83 | seen[key] = true |
| 84 | switch key { |
| 85 | case "MemTotal": |
| 86 | s.Total = n << 10 |
| 87 | case "MemAvailable": |
| 88 | s.Available = n << 10 |
| 89 | case "SwapTotal": |
| 90 | s.SwapTotal = n << 10 |
| 91 | case "SwapFree": |
| 92 | s.SwapFree = n << 10 |
| 93 | case "oom_kill": |
| 94 | s.OOMKills = n |
| 95 | } |
| 96 | case "some": |
| 97 | for _, value := range f[1:] { |
| 98 | if strings.HasPrefix(value, "avg10=") { |
| 99 | s.Stall, _ = strconv.ParseFloat(strings.TrimPrefix(value, "avg10="), 64) |
| 100 | } |
| 101 | } |
| 102 | case "boot": |
| 103 | s.Boot = f[1] |
| 104 | case "cpu": |
| 105 | |
| 106 | for i := 1; i < len(f) && i <= 8; i++ { |
| 107 | v, e := strconv.ParseUint(f[i], 10, 64) |
| 108 | if e != nil { |
| 109 | return s, e |
| 110 | } |
| 111 | s.cpuTotal += v |
| 112 | if i == 4 || i == 5 { |
| 113 | s.cpuIdle += v |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | } |
| 118 | if !seen["MemAvailable"] || !seen["oom_kill"] || s.Total < 256<<20 || s.Available > s.Total || s.SwapFree > s.SwapTotal || len(s.Boot) != 36 || math.IsNaN(s.Stall) || s.Stall < 0 || s.Stall > 100 { |
| 119 | return s, errors.New("incomplete guest resource observation") |
| 120 | } |
| 121 | if inflated != 0 || deflated != 0 { |
| 122 | if inflated < deflated || pageSize < 4096 || pageSize > 65536 || pageSize&(pageSize-1) != 0 { |
| 123 | return s, errors.New("invalid balloon counters") |
| 124 | } |
| 125 | s.Balloon = (inflated - deflated) * pageSize |
| 126 | } |
| 127 | return s, nil |
| 128 | } |
| 129 | |
| 130 | type ResourceStatus struct { |
| 131 | Version int `json:"version"` |
| 132 | PID int `json:"pid"` |
| 133 | UpdatedAt time.Time `json:"updated_at"` |
| 134 | ObservedAt time.Time `json:"observed_at"` |
| 135 | Maximum uint64 `json:"maximum_bytes"` |
| 136 | Target uint64 `json:"target_bytes"` |
| 137 | CPUs int `json:"cpus"` |
| 138 | CPUPercent float64 `json:"cpu_percent"` |
| 139 | Guest *ResourceSample `json:"guest,omitempty"` |
| 140 | Pressure bool `json:"pressure"` |
| 141 | HostPressure bool `json:"host_pressure"` |
| 142 | Error string `json:"error,omitempty"` |
| 143 | } |
| 144 | |
| 145 | |
| 146 | |
| 147 | type memoryPolicy struct { |
| 148 | maximum, target uint64 |
| 149 | idleSince time.Time |
| 150 | } |
| 151 | |
| 152 | func (p *memoryPolicy) next(now time.Time, s ResourceSample, hostPressure bool) uint64 { |
| 153 | const mib = uint64(1 << 20) |
| 154 | used := s.Total - s.Available + s.SwapTotal - s.SwapFree |
| 155 | reserve := max(uint64(1<<30), used/4) |
| 156 | |
| 157 | desired := min(p.maximum, max(min(uint64(2<<30), p.maximum), ((used+reserve+256*mib+255*mib)/(256*mib))*(256*mib))) |
| 158 | pressure := s.Available < max(uint64(512*mib), s.Total/8) || s.Stall >= 1 |
| 159 | if pressure || desired > p.target { |
| 160 | p.idleSince = time.Time{} |
| 161 | if hostPressure { |
| 162 | return p.target |
| 163 | } |
| 164 | |
| 165 | if pressure { |
| 166 | return p.maximum |
| 167 | } |
| 168 | return desired |
| 169 | } |
| 170 | if desired+512*mib > p.target { |
| 171 | p.idleSince = time.Time{} |
| 172 | return p.target |
| 173 | } |
| 174 | if p.idleSince.IsZero() { |
| 175 | p.idleSince = now |
| 176 | } |
| 177 | if now.Sub(p.idleSince) < 30*time.Second { |
| 178 | return p.target |
| 179 | } |
| 180 | |
| 181 | if s.Balloon < p.maximum-p.target { |
| 182 | return p.target |
| 183 | } |
| 184 | return max(desired, p.target-256*mib) |
| 185 | } |
| 186 | |
| 187 | |
| 188 | |
| 189 | func StartResourceManager(parent context.Context, dir string, maximum uint64, cpus int, read func(context.Context, string) ([]byte, error), set func(context.Context, uint64) error) func() { |
| 190 | ctx, cancel := context.WithCancel(parent) |
| 191 | done := make(chan struct{}) |
| 192 | go func() { |
| 193 | defer close(done) |
| 194 | p := memoryPolicy{maximum: maximum, target: maximum} |
| 195 | status := ResourceStatus{Version: 1, PID: os.Getpid(), Maximum: maximum, Target: maximum, CPUs: cpus} |
| 196 | var previous ResourceSample |
| 197 | var bootTotal uint64 |
| 198 | var lastError string |
| 199 | ticker := time.NewTicker(2 * time.Second) |
| 200 | defer ticker.Stop() |
| 201 | for { |
| 202 | select { |
| 203 | case <-ctx.Done(): |
| 204 | return |
| 205 | case <-ticker.C: |
| 206 | } |
| 207 | probeCtx, finish := context.WithTimeout(ctx, 3*time.Second) |
| 208 | data, err := read(probeCtx, resourceProbe) |
| 209 | finish() |
| 210 | var sample ResourceSample |
| 211 | if err == nil { |
| 212 | sample, err = parseResources(data) |
| 213 | if err == nil && sample.Total > maximum { |
| 214 | err = errors.New("guest memory exceeds VM capacity") |
| 215 | } |
| 216 | if err == nil { |
| 217 | if previous.Boot != sample.Boot { |
| 218 | bootTotal = sample.Total |
| 219 | } |
| 220 | |
| 221 | |
| 222 | |
| 223 | if sample.Balloon >= bootTotal { |
| 224 | err = errors.New("invalid balloon size") |
| 225 | } else { |
| 226 | sample.Total = min(sample.Total, bootTotal-sample.Balloon) |
| 227 | if sample.Available > sample.Total { |
| 228 | err = errors.New("inconsistent available memory") |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | now := time.Now() |
| 234 | detail := "" |
| 235 | status.UpdatedAt, status.HostPressure = now, host.MemoryPressure() |
| 236 | target := p.target |
| 237 | if err != nil { |
| 238 | p.idleSince = time.Time{} |
| 239 | cause := usererror.Reason(err) |
| 240 | if cause == "" { |
| 241 | cause = "环境未能返回完整有效的内存与 CPU 数据" |
| 242 | } |
| 243 | status.Error = "读取资源用量失败:" + cause + "。自动回收内存已暂停;若持续出现,请在设置中导出诊断包。" |
| 244 | detail = fmt.Sprintf("%s: %v", status.Error, err) |
| 245 | |
| 246 | |
| 247 | if !status.HostPressure { |
| 248 | target = maximum |
| 249 | } |
| 250 | } else { |
| 251 | status.Error = "" |
| 252 | status.ObservedAt, status.Guest = now, &sample |
| 253 | status.Pressure = sample.Available < max(uint64(512<<20), sample.Total/8) || sample.Stall >= 1 |
| 254 | if previous.Boot == sample.Boot && sample.cpuTotal > previous.cpuTotal && sample.cpuIdle >= previous.cpuIdle { |
| 255 | total, idle := sample.cpuTotal-previous.cpuTotal, sample.cpuIdle-previous.cpuIdle |
| 256 | status.CPUPercent = 100 * float64(total-min(idle, total)) / float64(total) |
| 257 | } |
| 258 | if previous.Boot == sample.Boot && sample.OOMKills > previous.OOMKills { |
| 259 | diagnostics.Log("warn", "resources", fmt.Sprintf("guest OOM kills increased by %d; available=%d target=%d maximum=%d", sample.OOMKills-previous.OOMKills, sample.Available, p.target, maximum)) |
| 260 | } |
| 261 | if previous.Boot != sample.Boot { |
| 262 | p.idleSince = time.Time{} |
| 263 | } |
| 264 | target = p.next(now, sample, status.HostPressure) |
| 265 | previous = sample |
| 266 | } |
| 267 | if ctx.Err() != nil { |
| 268 | return |
| 269 | } |
| 270 | if target != p.target { |
| 271 | changeCtx, finish := context.WithTimeout(ctx, 3*time.Second) |
| 272 | e := set(changeCtx, target) |
| 273 | finish() |
| 274 | if e != nil { |
| 275 | status.Error = "调整环境内存失败:虚拟机没有接受新的内存目标,当前分配保持不变。请在设置中导出诊断包。" |
| 276 | detail = fmt.Sprintf("%s: %v", status.Error, e) |
| 277 | } else { |
| 278 | p.target, status.Target = target, target |
| 279 | diagnostics.Log("info", "resources", fmt.Sprintf("memory target=%d maximum=%d", target, maximum)) |
| 280 | } |
| 281 | } |
| 282 | if detail != lastError { |
| 283 | if detail != "" { |
| 284 | diagnostics.Log("warn", "resources", detail) |
| 285 | } |
| 286 | lastError = detail |
| 287 | } |
| 288 | if e := writeResourceStatus(dir, status); e != nil && lastError != "status write failed" { |
| 289 | diagnostics.Log("warn", "resources", "resource status write failed") |
| 290 | lastError = "status write failed" |
| 291 | } |
| 292 | } |
| 293 | }() |
| 294 | return func() { cancel(); <-done } |
| 295 | } |
| 296 | |
| 297 | func writeResourceStatus(dir string, status ResourceStatus) error { |
| 298 | data, err := json.Marshal(status) |
| 299 | if err != nil { |
| 300 | return err |
| 301 | } |
| 302 | f, err := os.CreateTemp(dir, ".resources-*") |
| 303 | if err != nil { |
| 304 | return err |
| 305 | } |
| 306 | defer os.Remove(f.Name()) |
| 307 | if err = host.ProtectFile(f.Name()); err != nil { |
| 308 | f.Close() |
| 309 | return err |
| 310 | } |
| 311 | _, err = f.Write(data) |
| 312 | err = errors.Join(err, f.Close()) |
| 313 | if err != nil { |
| 314 | return err |
| 315 | } |
| 316 | return os.Rename(f.Name(), filepath.Join(dir, "cage-resources.json")) |
| 317 | } |
| 318 | |
| 319 | func ReadResourceStatus(dir string) (ResourceStatus, error) { |
| 320 | var status ResourceStatus |
| 321 | f, err := os.Open(filepath.Join(dir, "cage-resources.json")) |
| 322 | if err != nil { |
| 323 | return status, err |
| 324 | } |
| 325 | defer f.Close() |
| 326 | err = json.NewDecoder(io.LimitReader(f, 16384)).Decode(&status) |
| 327 | if err == nil && (status.Version != 1 || time.Since(status.UpdatedAt) > 10*time.Second || time.Until(status.UpdatedAt) > 5*time.Second) { |
| 328 | err = errors.New("resource observation expired") |
| 329 | } |
| 330 | return status, err |
| 331 | } |