forked from kubernetes-retired/heapster
-
Notifications
You must be signed in to change notification settings - Fork 0
/
influxdb.go
207 lines (179 loc) · 6.08 KB
/
influxdb.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package sinks
import (
"flag"
"fmt"
"strings"
"time"
"github.com/GoogleCloudPlatform/heapster/sources"
"github.com/golang/glog"
cadvisor "github.com/google/cadvisor/info"
influxdb "github.com/influxdb/influxdb/client"
)
var (
argBufferDuration = flag.Duration("sink_influxdb_buffer_duration", 10*time.Second, "Time duration for which stats should be buffered in influxdb sink before being written as a single transaction")
argDbUsername = flag.String("sink_influxdb_username", "root", "InfluxDB username")
argDbPassword = flag.String("sink_influxdb_password", "root", "InfluxDB password")
argDbHost = flag.String("sink_influxdb_host", "localhost:8086", "InfluxDB host:port")
argDbName = flag.String("sink_influxdb_name", "k8s", "Influxdb database name")
)
const (
statsTable string = "stats"
colTimestamp string = "time"
colPodName string = "pod"
colPodStatus string = "pod_status"
colPodIP string = "pod_ip"
colLabels string = "labels"
colHostName string = "hostname"
colContainerName string = "container_name"
colCpuCumulativeUsage string = "cpu_cumulative_usage"
colMemoryUsage string = "memory_usage"
colMemoryWorkingSet string = "memory_working_set"
colMemoryPgFaults string = "page_faults"
colCpuInstantUsage string = "cpu_instant_usage"
colRxBytes string = "rx_bytes"
colRxErrors string = "rx_errors"
colTxBytes string = "tx_bytes"
colTxErrors string = "tx_errors"
)
type InfluxdbSink struct {
client *influxdb.Client
series []*influxdb.Series
dbName string
bufferDuration time.Duration
lastWrite time.Time
}
func (self *InfluxdbSink) containerStatsToValues(pod *sources.Pod, containerName string, stat *cadvisor.ContainerStats) (columns []string, values []interface{}) {
// Timestamp
columns = append(columns, colTimestamp)
values = append(values, stat.Timestamp.Unix())
if pod != nil {
// Pod name
columns = append(columns, colPodName)
values = append(values, pod.Name)
// Hostname
columns = append(columns, colHostName)
values = append(values, pod.Hostname)
// Pod Status
columns = append(columns, colPodStatus)
values = append(values, pod.Status)
// Pod IP
columns = append(columns, colPodIP)
values = append(values, pod.PodIP)
labels := []string{}
for key, value := range pod.Labels {
labels = append(labels, fmt.Sprintf("%s:%s", key, value))
}
columns = append(columns, colLabels)
values = append(values, strings.Join(labels, ","))
}
// Container name
columns = append(columns, colContainerName)
values = append(values, containerName)
if stat.Cpu != nil {
// Cumulative Cpu Usage
columns = append(columns, colCpuCumulativeUsage)
values = append(values, stat.Cpu.Usage.Total)
}
if stat.Memory != nil {
// Memory Usage
columns = append(columns, colMemoryUsage)
values = append(values, stat.Memory.Usage)
// Memory Page Faults
columns = append(columns, colMemoryPgFaults)
values = append(values, stat.Memory.ContainerData.Pgfault)
// Working set size
columns = append(columns, colMemoryWorkingSet)
values = append(values, stat.Memory.WorkingSet)
}
// Optional: Network stats.
if stat.Network != nil {
columns = append(columns, colRxBytes)
values = append(values, stat.Network.RxBytes)
columns = append(columns, colRxErrors)
values = append(values, stat.Network.RxErrors)
columns = append(columns, colTxBytes)
values = append(values, stat.Network.TxBytes)
columns = append(columns, colTxErrors)
values = append(values, stat.Network.TxErrors)
}
return
}
// Returns a new influxdb series.
func (self *InfluxdbSink) newSeries(tableName string, columns []string, points []interface{}) *influxdb.Series {
out := &influxdb.Series{
Name: tableName,
Columns: columns,
// There's only one point for each stats
Points: make([][]interface{}, 1),
}
out.Points[0] = points
return out
}
func (self *InfluxdbSink) handlePods(pods []sources.Pod) {
for _, pod := range pods {
for _, container := range pod.Containers {
for _, stat := range container.Stats {
col, val := self.containerStatsToValues(&pod, container.Name, stat)
self.series = append(self.series, self.newSeries(statsTable, col, val))
}
}
}
}
func (self *InfluxdbSink) handleContainers(container sources.AnonContainer) {
for _, stat := range container.Stats {
col, val := self.containerStatsToValues(nil, container.Name, stat)
self.series = append(self.series, self.newSeries(statsTable, col, val))
}
}
func (self *InfluxdbSink) readyToFlush() bool {
return time.Since(self.lastWrite) >= self.bufferDuration
}
func (self *InfluxdbSink) StoreData(ip Data) error {
var seriesToFlush []*influxdb.Series
if data, ok := ip.([]sources.Pod); ok {
self.handlePods(data)
} else if data, ok := ip.(sources.AnonContainer); ok {
self.handleContainers(data)
} else {
return fmt.Errorf("Requesting unrecognized type to be stored in InfluxDB")
}
if self.readyToFlush() {
seriesToFlush = self.series
self.series = make([]*influxdb.Series, 0)
self.lastWrite = time.Now()
}
if len(seriesToFlush) > 0 {
glog.V(2).Info("flushed data to influxdb sink")
// TODO(vishh): Do writes in a separate thread.
err := self.client.WriteSeriesWithTimePrecision(seriesToFlush, influxdb.Second)
if err != nil {
glog.Errorf("failed to write stats to influxDb - %s", err)
}
}
return nil
}
func NewInfluxdbSink() (Sink, error) {
config := &influxdb.ClientConfig{
Host: *argDbHost,
Username: *argDbUsername,
Password: *argDbPassword,
Database: *argDbName,
IsSecure: false,
}
client, err := influxdb.NewClient(config)
if err != nil {
return nil, err
}
client.DisableCompression()
if err := client.CreateDatabase(*argDbName); err != nil {
glog.Infof("Database creation failed - %s", err)
}
// Create the database if it does not already exist. Ignore errors.
return &InfluxdbSink{
client: client,
series: make([]*influxdb.Series, 0),
dbName: *argDbName,
bufferDuration: *argBufferDuration,
lastWrite: time.Now(),
}, nil
}