forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
influxdb.go
369 lines (326 loc) · 9.54 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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package influxdb
import (
"fmt"
"net/url"
"os"
"sync"
"time"
info "github.com/google/cadvisor/info/v1"
"github.com/google/cadvisor/storage"
"github.com/google/cadvisor/version"
influxdb "github.com/influxdb/influxdb/client"
)
func init() {
storage.RegisterStorageDriver("influxdb", new)
}
type influxdbStorage struct {
client *influxdb.Client
machineName string
database string
retentionPolicy string
bufferDuration time.Duration
lastWrite time.Time
points []*influxdb.Point
lock sync.Mutex
readyToFlush func() bool
}
// Series names
const (
// Cumulative CPU usage
serCpuUsageTotal string = "cpu_usage_total"
serCpuUsageSystem string = "cpu_usage_system"
serCpuUsageUser string = "cpu_usage_user"
serCpuUsagePerCpu string = "cpu_usage_per_cpu"
// Smoothed average of number of runnable threads x 1000.
serLoadAverage string = "load_average"
// Memory Usage
serMemoryUsage string = "memory_usage"
// Working set size
serMemoryWorkingSet string = "memory_working_set"
// Cumulative count of bytes received.
serRxBytes string = "rx_bytes"
// Cumulative count of receive errors encountered.
serRxErrors string = "rx_errors"
// Cumulative count of bytes transmitted.
serTxBytes string = "tx_bytes"
// Cumulative count of transmit errors encountered.
serTxErrors string = "tx_errors"
// Filesystem device.
serFsDevice string = "fs_device"
// Filesystem limit.
serFsLimit string = "fs_limit"
// Filesystem usage.
serFsUsage string = "fs_usage"
)
func new() (storage.StorageDriver, error) {
hostname, err := os.Hostname()
if err != nil {
return nil, err
}
return newStorage(
hostname,
*storage.ArgDbTable,
*storage.ArgDbName,
*storage.ArgDbUsername,
*storage.ArgDbPassword,
*storage.ArgDbHost,
*storage.ArgDbIsSecure,
*storage.ArgDbBufferDuration,
)
}
// Field names
const (
fieldValue string = "value"
fieldType string = "type"
fieldDevice string = "device"
)
// Tag names
const (
tagMachineName string = "machine"
tagContainerName string = "container_name"
)
func (self *influxdbStorage) containerFilesystemStatsToPoints(
ref info.ContainerReference,
stats *info.ContainerStats) (points []*influxdb.Point) {
if len(stats.Filesystem) == 0 {
return points
}
for _, fsStat := range stats.Filesystem {
tagsFsUsage := map[string]string{
fieldDevice: fsStat.Device,
fieldType: "usage",
}
fieldsFsUsage := map[string]interface{}{
fieldValue: int64(fsStat.Usage),
}
pointFsUsage := &influxdb.Point{
Measurement: serFsUsage,
Tags: tagsFsUsage,
Fields: fieldsFsUsage,
}
tagsFsLimit := map[string]string{
fieldDevice: fsStat.Device,
fieldType: "limit",
}
fieldsFsLimit := map[string]interface{}{
fieldValue: int64(fsStat.Limit),
}
pointFsLimit := &influxdb.Point{
Measurement: serFsLimit,
Tags: tagsFsLimit,
Fields: fieldsFsLimit,
}
points = append(points, pointFsUsage, pointFsLimit)
}
self.tagPoints(ref, stats, points)
return points
}
// Set tags and timestamp for all points of the batch.
// Points should inherit the tags that are set for BatchPoints, but that does not seem to work.
func (self *influxdbStorage) tagPoints(ref info.ContainerReference, stats *info.ContainerStats, points []*influxdb.Point) {
// Use container alias if possible
var containerName string
if len(ref.Aliases) > 0 {
containerName = ref.Aliases[0]
} else {
containerName = ref.Name
}
commonTags := map[string]string{
tagMachineName: self.machineName,
tagContainerName: containerName,
}
for i := 0; i < len(points); i++ {
// merge with existing tags if any
addTagsToPoint(points[i], commonTags)
points[i].Time = stats.Timestamp
}
}
func (self *influxdbStorage) containerStatsToPoints(
ref info.ContainerReference,
stats *info.ContainerStats,
) (points []*influxdb.Point) {
// CPU usage: Total usage in nanoseconds
points = append(points, makePoint(serCpuUsageTotal, stats.Cpu.Usage.Total))
// CPU usage: Time spend in system space (in nanoseconds)
points = append(points, makePoint(serCpuUsageSystem, stats.Cpu.Usage.System))
// CPU usage: Time spent in user space (in nanoseconds)
points = append(points, makePoint(serCpuUsageUser, stats.Cpu.Usage.User))
// CPU usage per CPU
for i := 0; i < len(stats.Cpu.Usage.PerCpu); i++ {
point := makePoint(serCpuUsagePerCpu, stats.Cpu.Usage.PerCpu[i])
tags := map[string]string{"instance": fmt.Sprintf("%v", i)}
addTagsToPoint(point, tags)
points = append(points, point)
}
// Load Average
points = append(points, makePoint(serLoadAverage, stats.Cpu.LoadAverage))
// Memory Usage
points = append(points, makePoint(serMemoryUsage, stats.Memory.Usage))
// Working Set Size
points = append(points, makePoint(serMemoryWorkingSet, stats.Memory.WorkingSet))
// Network Stats
points = append(points, makePoint(serRxBytes, stats.Network.RxBytes))
points = append(points, makePoint(serRxErrors, stats.Network.RxErrors))
points = append(points, makePoint(serTxBytes, stats.Network.TxBytes))
points = append(points, makePoint(serTxErrors, stats.Network.TxErrors))
self.tagPoints(ref, stats, points)
return points
}
func (self *influxdbStorage) OverrideReadyToFlush(readyToFlush func() bool) {
self.readyToFlush = readyToFlush
}
func (self *influxdbStorage) defaultReadyToFlush() bool {
return time.Since(self.lastWrite) >= self.bufferDuration
}
func (self *influxdbStorage) AddStats(ref info.ContainerReference, stats *info.ContainerStats) error {
if stats == nil {
return nil
}
var pointsToFlush []*influxdb.Point
func() {
// AddStats will be invoked simultaneously from multiple threads and only one of them will perform a write.
self.lock.Lock()
defer self.lock.Unlock()
self.points = append(self.points, self.containerStatsToPoints(ref, stats)...)
self.points = append(self.points, self.containerFilesystemStatsToPoints(ref, stats)...)
if self.readyToFlush() {
pointsToFlush = self.points
self.points = make([]*influxdb.Point, 0)
self.lastWrite = time.Now()
}
}()
if len(pointsToFlush) > 0 {
points := make([]influxdb.Point, len(pointsToFlush))
for i, p := range pointsToFlush {
points[i] = *p
}
batchTags := map[string]string{tagMachineName: self.machineName}
bp := influxdb.BatchPoints{
Points: points,
Database: self.database,
Tags: batchTags,
Time: stats.Timestamp,
}
response, err := self.client.Write(bp)
if err != nil || checkResponseForErrors(response) != nil {
return fmt.Errorf("failed to write stats to influxDb - %s", err)
}
}
return nil
}
func (self *influxdbStorage) Close() error {
self.client = nil
return nil
}
// machineName: A unique identifier to identify the host that current cAdvisor
// instance is running on.
// influxdbHost: The host which runs influxdb (host:port)
func newStorage(
machineName,
tablename,
database,
username,
password,
influxdbHost string,
isSecure bool,
bufferDuration time.Duration,
) (*influxdbStorage, error) {
url := &url.URL{
Scheme: "http",
Host: influxdbHost,
}
if isSecure {
url.Scheme = "https"
}
config := &influxdb.Config{
URL: *url,
Username: username,
Password: password,
UserAgent: fmt.Sprintf("%v/%v", "cAdvisor", version.Info["version"]),
}
client, err := influxdb.NewClient(*config)
if err != nil {
return nil, err
}
ret := &influxdbStorage{
client: client,
machineName: machineName,
database: database,
bufferDuration: bufferDuration,
lastWrite: time.Now(),
points: make([]*influxdb.Point, 0),
}
ret.readyToFlush = ret.defaultReadyToFlush
return ret, nil
}
// Creates a measurement point with a single value field
func makePoint(name string, value interface{}) *influxdb.Point {
fields := map[string]interface{}{
fieldValue: toSignedIfUnsigned(value),
}
return &influxdb.Point{
Measurement: name,
Fields: fields,
}
}
// Adds additional tags to the existing tags of a point
func addTagsToPoint(point *influxdb.Point, tags map[string]string) {
if point.Tags == nil {
point.Tags = tags
} else {
for k, v := range tags {
point.Tags[k] = v
}
}
}
// Checks response for possible errors
func checkResponseForErrors(response *influxdb.Response) error {
const msg = "failed to write stats to influxDb - %s"
if response != nil && response.Err != nil {
return fmt.Errorf(msg, response.Err)
}
if response != nil && response.Results != nil {
for _, result := range response.Results {
if result.Err != nil {
return fmt.Errorf(msg, result.Err)
}
if result.Series != nil {
for _, row := range result.Series {
if row.Err != nil {
return fmt.Errorf(msg, row.Err)
}
}
}
}
}
return nil
}
// Some stats have type unsigned integer, but the InfluxDB client accepts only signed integers.
func toSignedIfUnsigned(value interface{}) interface{} {
switch v := value.(type) {
case uint64:
return int64(v)
case uint32:
return int32(v)
case uint16:
return int16(v)
case uint8:
return int8(v)
case uint:
return int(v)
}
return value
}