BlueGit

timfa bluegit

Files

bluegit / internal / runnercfg / hardware.go

hardware.go

hardware.go 2.2 KiB Download Raw
1package runnercfg
2
3import (
4 "bufio"
5 "math"
6 "os"
7 "runtime"
8 "strconv"
9 "strings"
10 "syscall"
11)
12
13// Hardware is wat de runner van zijn machine ziet.
14type Hardware struct {
15 CPUs int
16 MemoryMB int
17 DiskFree int // GB vrij op de werkmap
18 DiskSize int // GB totaal
19}
20
21// Detect leest CPU's, /proc/meminfo en de schijf onder dir.
22func Detect(dir string) Hardware {
23 h := Hardware{CPUs: runtime.NumCPU()}
24 if f, err := os.Open("/proc/meminfo"); err == nil {
25 sc := bufio.NewScanner(f)
26 for sc.Scan() {
27 fields := strings.Fields(sc.Text())
28 if len(fields) >= 2 && fields[0] == "MemTotal:" {
29 kb, _ := strconv.Atoi(fields[1])
30 h.MemoryMB = kb / 1024
31 }
32 }
33 f.Close()
34 }
35 for d := dir; d != ""; {
36 var st syscall.Statfs_t
37 if err := syscall.Statfs(d, &st); err == nil {
38 h.DiskFree = int(st.Bavail * uint64(st.Bsize) >> 30)
39 h.DiskSize = int(st.Blocks * uint64(st.Bsize) >> 30)
40 break
41 }
42 if d == "/" {
43 break
44 }
45 if i := strings.LastIndex(d, "/"); i > 0 {
46 d = d[:i]
47 } else {
48 d = "/"
49 }
50 }
51 return h
52}
53
54// Recommend geeft logische waarden voor deze hardware. Uitgangspunt: een
55// CI-job wil ~2 kernen en ~2 GB; de host houdt 1 kern en 1 GB voor zichzelf,
56// en per job ~10 GB schijf voor images, checkout en cache.
57func Recommend(h Hardware) Settings {
58 r := Defaults()
59 cpu := h.CPUs
60 if cpu < 1 {
61 cpu = 1
62 }
63 mem := h.MemoryMB
64 byCPU := int(math.Max(1, float64((cpu-1)/2)))
65 byMem := 1
66 if mem > 0 {
67 byMem = int(math.Max(1, float64((mem-1024)/2048)))
68 }
69 byDisk := 64
70 if h.DiskFree > 0 {
71 byDisk = int(math.Max(1, float64(h.DiskFree/10)))
72 }
73 r.Concurrency = minInt(byCPU, byMem, byDisk, 8)
74 if r.Concurrency < 1 {
75 r.Concurrency = 1
76 }
77 share := float64(cpu-1) / float64(r.Concurrency)
78 if share < 1 {
79 share = 1
80 }
81 r.CPUs = math.Floor(share*2) / 2
82 if mem > 0 {
83 m := (mem - 1024) / r.Concurrency
84 if m < 512 {
85 m = 512
86 }
87 r.MemoryMB = m / 256 * 256
88 }
89 r.PidsLimit = 4096
90 if h.DiskFree > 0 {
91 r.MaxImages = minInt(maxInt(5, h.DiskFree/2), 50)
92 r.MaxDiskGB = maxInt(5, h.DiskFree*6/10)
93 r.PruneCacheGB = maxInt(2, h.DiskFree/10)
94 }
95 return r
96}
97
98func minInt(v ...int) int {
99 m := v[0]
100 for _, x := range v[1:] {
101 if x < m {
102 m = x
103 }
104 }
105 return m
106}
107
108func maxInt(a, b int) int {
109 if a > b {
110 return a
111 }
112 return b
113}