61 lines
1.3 KiB
Go
61 lines
1.3 KiB
Go
package local
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"os"
|
|
"runtime"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"slackerbot/internal/model"
|
|
)
|
|
|
|
type Capacity struct {
|
|
Total model.Size
|
|
Usable model.Size
|
|
}
|
|
|
|
func DetectCapacity(reserve model.Size) (Capacity, error) {
|
|
memMB, err := totalMemoryMB()
|
|
if err != nil {
|
|
return Capacity{}, err
|
|
}
|
|
total := model.Size{MemoryMB: memMB, CPUs: float64(runtime.NumCPU())}
|
|
usable := total.Sub(reserve)
|
|
if usable.MemoryMB <= 0 || usable.CPUs <= 0 {
|
|
return Capacity{}, fmt.Errorf("host_reserve (%s) leaves nothing on this node (%s)", reserve, total)
|
|
}
|
|
return Capacity{Total: total, Usable: usable}, nil
|
|
}
|
|
|
|
func (c Capacity) Room(used, want model.Size) bool {
|
|
return used.Add(want).Fits(c.Usable)
|
|
}
|
|
|
|
func (c Capacity) Slots(size model.Size) int {
|
|
byMem := c.Usable.MemoryMB / size.MemoryMB
|
|
byCPU := int(c.Usable.CPUs/size.CPUs + 1e-9)
|
|
return min(byMem, byCPU)
|
|
}
|
|
|
|
func totalMemoryMB() (int, error) {
|
|
f, err := os.Open("/proc/meminfo")
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
defer f.Close()
|
|
sc := bufio.NewScanner(f)
|
|
for sc.Scan() {
|
|
fields := strings.Fields(sc.Text())
|
|
if len(fields) >= 2 && fields[0] == "MemTotal:" {
|
|
kb, err := strconv.Atoi(fields[1])
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return kb / 1024, nil
|
|
}
|
|
}
|
|
return 0, fmt.Errorf("MemTotal not found in /proc/meminfo")
|
|
}
|