| 1 | package cage |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | ) |
| 10 | |
| 11 | |
| 12 | |
| 13 | type ResourceAllocation struct { |
| 14 | Automatic bool `json:"automatic"` |
| 15 | MemoryGiB int `json:"memory_gib"` |
| 16 | CPUs int `json:"cpus"` |
| 17 | } |
| 18 | |
| 19 | func ResourceAllocationPath(configPath string) string { |
| 20 | return filepath.Join(filepath.Dir(configPath), "resource-limits.json") |
| 21 | } |
| 22 | |
| 23 | func (a ResourceAllocation) Limits() (memory, cpus int, err error) { |
| 24 | memory, cpus = ResourceLimits() |
| 25 | if a.Automatic { |
| 26 | return memory, cpus, nil |
| 27 | } |
| 28 | if a.MemoryGiB < 2 || a.MemoryGiB > memory || a.CPUs < 1 || a.CPUs > cpus { |
| 29 | return 0, 0, fmt.Errorf("内存上限须为 2–%d GiB,CPU 须为 1–%d 个逻辑核心", memory, cpus) |
| 30 | } |
| 31 | return a.MemoryGiB, a.CPUs, nil |
| 32 | } |
| 33 | |
| 34 | func LoadResourceAllocation(configPath string) (ResourceAllocation, error) { |
| 35 | a := ResourceAllocation{Automatic: true} |
| 36 | b, err := os.ReadFile(ResourceAllocationPath(configPath)) |
| 37 | if errors.Is(err, os.ErrNotExist) { |
| 38 | return a, nil |
| 39 | } |
| 40 | if err != nil { |
| 41 | return a, err |
| 42 | } |
| 43 | if err = json.Unmarshal(b, &a); err != nil { |
| 44 | return a, err |
| 45 | } |
| 46 | return a, nil |
| 47 | } |
| 48 | |
| 49 | func ConfiguredResourceLimits(configPath string) (int, int, error) { |
| 50 | a, err := LoadResourceAllocation(configPath) |
| 51 | if err != nil { |
| 52 | return 0, 0, err |
| 53 | } |
| 54 | return a.Limits() |
| 55 | } |