forked from rancher/host-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
host_stats.go
118 lines (96 loc) · 2.43 KB
/
host_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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package stats
import (
"bufio"
"io"
"net/url"
"time"
log "github.com/Sirupsen/logrus"
"github.com/google/cadvisor/client"
info "github.com/google/cadvisor/info/v1"
"github.com/rancher/host-api/config"
"github.com/rancher/websocket-proxy/backend"
"github.com/rancher/websocket-proxy/common"
)
type HostStatsHandler struct {
}
func (s *HostStatsHandler) Handle(key string, initialMessage string, incomingMessages <-chan string, response chan<- common.Message) {
defer backend.SignalHandlerClosed(key, response)
c, err := client.NewClient(config.Config.CAdvisorUrl)
if err != nil {
log.WithFields(log.Fields{"error": err}).Error("Couldn't get CAdvisor client.")
return
}
requestUrl, err := url.Parse(initialMessage)
if err != nil {
log.WithFields(log.Fields{"error": err, "message": initialMessage}).Error("Couldn't parse url from message.")
return
}
tokenString := requestUrl.Query().Get("token")
resourceId := ""
token, err := parseRequestToken(tokenString, config.Config.ParsedPublicKey)
if err == nil {
resourceIdInterface, found := token.Claims["resourceId"]
if found {
resourceIdVal, ok := resourceIdInterface.(string)
if ok {
resourceId = resourceIdVal
}
}
}
reader, writer := io.Pipe()
go func(w *io.PipeWriter) {
for {
_, ok := <-incomingMessages
if !ok {
w.Close()
return
}
}
}(writer)
go func(r *io.PipeReader) {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
text := scanner.Text()
message := common.Message{
Key: key,
Type: common.Body,
Body: text,
}
response <- message
}
if err := scanner.Err(); err != nil {
log.WithFields(log.Fields{"error": err}).Error("Error with the container stat scanner.")
}
}(reader)
count := config.Config.NumStats
for {
machineInfo, err := c.MachineInfo()
if err != nil {
log.WithFields(log.Fields{"error": err}).Error("Error getting machine info.")
return
}
memLimit := machineInfo.MemoryCapacity
infos := []info.ContainerInfo{}
cInfo, err := c.ContainerInfo("", &info.ContainerInfoRequest{
NumStats: count,
})
if err != nil {
return
}
infos = append(infos, *cInfo)
if count == 1 {
for i := range infos {
if len(infos[i].Stats) > 0 {
infos[i].Stats[0].Timestamp = time.Now()
}
}
}
err = writeAggregatedStats(resourceId, nil, "host", infos, uint64(memLimit), writer)
if err != nil {
return
}
time.Sleep(1 * time.Second)
count = 1
}
return
}