forked from rancher/host-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aggregated_stats.go
92 lines (81 loc) · 2.47 KB
/
aggregated_stats.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package stats
import (
"encoding/json"
"io"
"strings"
info "github.com/google/cadvisor/info/v1"
)
type AggregatedStats []AggregatedStat
type AggregatedStat struct {
Id string `json:"id,omitempty"`
ResourceType string `json:"resourceType,omitempty"`
MemLimit uint64 `json:"memLimit,omitempty"`
*info.ContainerStats
}
func convertToAggregatedStats(id string, containerIds map[string]string, resourceType string, stats []info.ContainerInfo, memLimit uint64) []AggregatedStats {
totalAggregatedStats := []AggregatedStats{}
if len(stats) == 0 {
return totalAggregatedStats
}
maxDataPoints := len(stats[0].Stats)
for i := 0; i < maxDataPoints; i++ {
aggregatedStats := []AggregatedStat{}
for _, stat := range stats {
if len(stat.Stats) > i {
statPoint := convertCadvisorStatToAggregatedStat(id, stat.Aliases, stat.Name, containerIds, resourceType, memLimit, stat.Stats[i])
if statPoint.Id == "" {
continue
}
aggregatedStats = append(aggregatedStats, statPoint)
}
}
totalAggregatedStats = append(totalAggregatedStats, aggregatedStats)
}
return totalAggregatedStats
}
func convertCadvisorStatToAggregatedStat(id string, aliases []string, name string, containerIds map[string]string, resourceType string, memLimit uint64, stat *info.ContainerStats) AggregatedStat {
if resourceType == "container" {
if id == "" {
id = name
}
//Use last index because in case of running this nested inside a docker container, then the container Id of the containers becomes /docker/id-root/docker/id-of-container
index := strings.LastIndex(id, "/docker/")
if index != -1 {
id = id[index+len("/docker/"):]
}
if idVal, ok := containerIds[id]; ok {
id = idVal
} else {
found := false
for _, alias := range aliases {
if idVal, ok := containerIds[alias]; ok {
id = idVal
found = true
break
}
}
if !found {
return AggregatedStat{}
}
}
}
return AggregatedStat{id, resourceType, memLimit, stat}
}
func writeAggregatedStats(id string, containerIds map[string]string, resourceType string, infos []info.ContainerInfo, memLimit uint64, writer io.Writer) error {
aggregatedStats := convertToAggregatedStats(id, containerIds, resourceType, infos, memLimit)
for _, stat := range aggregatedStats {
data, err := json.Marshal(stat)
if err != nil {
return err
}
_, err = writer.Write(data)
if err != nil {
return err
}
_, err = writer.Write([]byte("\n"))
if err != nil {
return err
}
}
return nil
}