-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmatching.go
73 lines (65 loc) · 1.7 KB
/
matching.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"math"
"os"
"path/filepath"
)
var (
templates Templates
)
// Templates todo
type Templates struct {
Templates []Template `json:"templates"`
}
// Template todo
type Template struct {
Name string `json:"name"`
CPU int `json:"cpu"`
Memory int `json:"memory"`
}
func loadTemplate() error {
filePath := filepath.Join(os.Getenv("HOME"), ".config", "exporter", "templates.json")
if os.Getenv("TEMPLATES_FILE") != "" {
filePath = os.Getenv("TEMPLATES_FILE")
}
data, err := ioutil.ReadFile(filePath)
if err != nil {
return fmt.Errorf("The templates cannot be read - %s", err.Error())
}
if err := json.Unmarshal(data, &templates); err != nil {
return fmt.Errorf("The templates cannot be unmarshalled - %s", err.Error())
}
return nil
}
func match(gabarit NodeGabarit) *Template {
if len(templates.Templates) == 0 {
loadTemplate()
}
for i := range templates.Templates {
if templates.Templates[i].CPU == gabarit.CPU && float64(templates.Templates[i].Memory) == math.Ceil(float64(gabarit.Memory)/1024/1024/1024) {
return &templates.Templates[i]
}
}
DisplayLog("WARNING", fmt.Sprintf("No template matching the NodeGabarit %s", gabarit.Name))
return nil
}
// MatchAll todo
func MatchAll(gabarits []NodeGabarit) (map[*Template]int, error) {
repartition := make(map[*Template]int)
if len(templates.Templates) == 0 {
if err := loadTemplate(); err != nil {
return repartition, fmt.Errorf("Failed to load the templates - %s", err.Error())
}
}
for _, gabarit := range gabarits {
if gabarit.Readiness != "Unknown" {
if template := match(gabarit); template != nil {
repartition[template]++
}
}
}
return repartition, nil
}