| 1 | package host |
| 2 | |
| 3 | import ( |
| 4 | "strconv" |
| 5 | "strings" |
| 6 | |
| 7 | "github.com/carlosframework/platform/internal/registry" |
| 8 | ) |
| 9 | |
| 10 | // headroomFor is the reading the edges loop publishes: nil unless the box |
| 11 | // has the region-HA capability. A box that publishes headroom is rewritten |
| 12 | // on every timed pass, so a one-box region (flag off) must not carry one. |
| 13 | func headroomFor(caps []string, dataDir string, reg *registry.Registry) *edgeHeadroom { |
| 14 | if len(caps) == 0 { |
| 15 | return nil |
| 16 | } |
| 17 | h := readHeadroom(dataDir, awakeCount(reg)) |
| 18 | h.MemTotalMiB, h.DiskTotalMiB = capacityMiB(readMemBytes, func() (uint64, uint64, error) { return diskBytes(dataDir) }) |
| 19 | return h |
| 20 | } |
| 21 | |
| 22 | // capacityMiB is the box's total memory and its data volume's size, in |
| 23 | // MiB: the totals region HA spec 2's placement policy judges the free |
| 24 | // figures against (§7). A reading that fails is 0, which the policy reads |
| 25 | // as a box it cannot judge, and so does not place on. |
| 26 | func capacityMiB(mem func() (total, avail *int64), disk func() (total, avail uint64, err error)) (memMiB, diskMiB int64) { |
| 27 | if total, _ := mem(); total != nil && *total > 0 { |
| 28 | memMiB = *total / (1 << 20) |
| 29 | } |
| 30 | if total, _, err := disk(); err == nil { |
| 31 | diskMiB = int64(total / (1 << 20)) |
| 32 | } |
| 33 | return memMiB, diskMiB |
| 34 | } |
| 35 | |
| 36 | // parseMemAvailableMiB returns the MemAvailable line in MiB, or 0. |
| 37 | func parseMemAvailableMiB(meminfo string) int64 { |
| 38 | for _, line := range strings.Split(meminfo, "\n") { |
| 39 | rest, ok := strings.CutPrefix(line, "MemAvailable:") |
| 40 | if !ok { |
| 41 | continue |
| 42 | } |
| 43 | fields := strings.Fields(rest) |
| 44 | if len(fields) == 0 { |
| 45 | return 0 |
| 46 | } |
| 47 | kb, err := strconv.ParseInt(fields[0], 10, 64) |
| 48 | if err != nil { |
| 49 | return 0 |
| 50 | } |
| 51 | return kb / 1024 |
| 52 | } |
| 53 | return 0 |
| 54 | } |
| 55 | |