| 1 | package containerenv |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "strconv" |
| 7 | "strings" |
| 8 | ) |
| 9 | |
| 10 | const PIDLimit = 1024 |
| 11 | |
| 12 | type resourceEvidence struct { |
| 13 | MemoryBytes int64 `json:"memory_bytes"` |
| 14 | CPUs int `json:"cpus"` |
| 15 | PIDs int64 `json:"pids"` |
| 16 | } |
| 17 | |
| 18 | func (r *Runtime) resourceSlice() string { return "cage" + r.identity + ".slice" } |
| 19 | |
| 20 | |
| 21 | |
| 22 | func (r *Runtime) verifyResources(ctx context.Context, containerID string) (resourceEvidence, error) { |
| 23 | return r.verifyHostResources(ctx, containerID) |
| 24 | } |
| 25 | |
| 26 | func parseResourceEvidence(data string, configuration Config) (resourceEvidence, error) { |
| 27 | lines := strings.SplitN(strings.TrimSpace(data), "\n", 4) |
| 28 | if len(lines) != 4 { |
| 29 | return resourceEvidence{}, errors.New("容器未返回完整 cgroup 资源限额") |
| 30 | } |
| 31 | memory, memoryErr := strconv.ParseInt(strings.TrimSpace(lines[0]), 10, 64) |
| 32 | cpu := strings.Fields(lines[1]) |
| 33 | pids, pidErr := strconv.ParseInt(strings.TrimSpace(lines[2]), 10, 64) |
| 34 | if memoryErr != nil || pidErr != nil || len(cpu) != 2 { |
| 35 | return resourceEvidence{}, errors.New("容器 CPU、内存或进程数限额未生效") |
| 36 | } |
| 37 | quota, quotaErr := strconv.ParseInt(cpu[0], 10, 64) |
| 38 | period, periodErr := strconv.ParseInt(cpu[1], 10, 64) |
| 39 | if quotaErr != nil || periodErr != nil || period < 1000 || period > 1000000 || quota != int64(configuration.CPUs)*period || memory != configuration.MemoryBytes || pids != PIDLimit { |
| 40 | return resourceEvidence{}, errors.New("容器内核资源限额与配置不一致,拒绝继续启动") |
| 41 | } |
| 42 | cgroup2 := false |
| 43 | for _, mount := range strings.Split(lines[3], "\n") { |
| 44 | fields := strings.Fields(mount) |
| 45 | if len(fields) > 6 && fields[4] == "/sys/fs/cgroup" && strings.Contains(mount, " - cgroup2 ") { |
| 46 | cgroup2 = true |
| 47 | } |
| 48 | } |
| 49 | if !cgroup2 { |
| 50 | return resourceEvidence{}, errors.New("容器资源限额缺少 cgroup v2 内核挂载证据") |
| 51 | } |
| 52 | return resourceEvidence{MemoryBytes: memory, CPUs: configuration.CPUs, PIDs: pids}, nil |
| 53 | } |