forked from tsaikd/gogstash
/
logloop.go
108 lines (95 loc) · 2.51 KB
/
logloop.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
package inputdockerstats
import (
"context"
"reflect"
"strings"
"time"
"github.com/fsouza/go-dockerclient"
"github.com/tsaikd/gogstash/config/logevent"
"github.com/tsaikd/gogstash/input/dockerlog/dockertool"
)
var (
containerMap = map[string]interface{}{}
)
func (t *InputConfig) containerLogLoop(ctx context.Context, container interface{}, since *time.Time, msgChan chan<- logevent.LogEvent) (err error) {
id, name, err := dockertool.GetContainerInfo(container)
if err != nil {
return ErrorGetContainerInfoFailed.New(err)
}
if t.containerExist.Exist(id) {
return ErrorContainerLoopRunning1.New(nil, id)
}
t.containerExist.Add(id)
defer t.containerExist.Remove(id)
retry := 5
statsChan := make(chan *docker.Stats, 100)
for err == nil || retry > 0 {
go func() {
for {
select {
case <-ctx.Done():
return
case stats := <-statsChan:
if time.Now().Add(-time.Duration(float64(t.StatInterval)-0.5) * time.Second).Before(*since) {
continue
}
filterStatsByMode(stats, t.LogMode)
event := logevent.LogEvent{
Timestamp: time.Now(),
Extra: map[string]interface{}{
"host": t.hostname,
"containerid": id,
"containername": name,
"stats": *stats,
},
}
*since = time.Now()
msgChan <- event
}
}
}()
err = t.client.Stats(docker.StatsOptions{
ID: id,
Stats: statsChan,
Stream: true,
Context: ctx,
})
if err != nil && strings.Contains(err.Error(), "connection refused") {
retry--
time.Sleep(50 * time.Millisecond)
continue
}
break
}
return
}
func filterStatsByMode(stats *docker.Stats, mode Mode) {
switch mode {
case ModeSimple:
clearNetworkStats(&stats.Network)
for name, network := range stats.Networks {
clearNetworkStats(&network)
stats.Networks[name] = network
}
clear(&stats.MemoryStats.Stats)
clear(&stats.BlkioStats)
clear(&stats.CPUStats.CPUUsage.PercpuUsage)
clear(&stats.CPUStats.CPUUsage.UsageInKernelmode)
clear(&stats.CPUStats.CPUUsage.UsageInUsermode)
clear(&stats.CPUStats.SystemCPUUsage)
clear(&stats.PreCPUStats.CPUUsage.PercpuUsage)
clear(&stats.PreCPUStats.CPUUsage.UsageInKernelmode)
clear(&stats.PreCPUStats.CPUUsage.UsageInUsermode)
clear(&stats.PreCPUStats.SystemCPUUsage)
}
}
func clearNetworkStats(network *docker.NetworkStats) {
*network = docker.NetworkStats{
RxBytes: network.RxBytes,
TxBytes: network.TxBytes,
}
}
func clear(v interface{}) {
p := reflect.ValueOf(v).Elem()
p.Set(reflect.Zero(p.Type()))
}