forked from tsaikd/gogstash
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlogloop.go
More file actions
115 lines (101 loc) · 2.49 KB
/
logloop.go
File metadata and controls
115 lines (101 loc) · 2.49 KB
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
package inputdockerstats
import (
"reflect"
"strings"
"time"
"github.com/Sirupsen/logrus"
"github.com/fsouza/go-dockerclient"
"github.com/tsaikd/KDGoLib/errutil"
"github.com/tsaikd/gogstash/config"
"github.com/tsaikd/gogstash/config/logevent"
"github.com/tsaikd/gogstash/input/dockerlog"
)
var (
containerMap = map[string]interface{}{}
)
func (t *InputConfig) containerLogLoop(container interface{}, since *time.Time, inchan config.InChan, logger *logrus.Logger) (err error) {
defer func() {
if err != nil {
logger.Errorln(err)
}
if recov := recover(); recov != nil {
logger.Errorln(recov)
}
}()
id, name, err := inputdockerlog.GetContainerInfo(container)
if err != nil {
return errutil.New("get container info failed", err)
}
if containerMap[id] != nil {
return &ErrorContainerLoopRunning{id}
}
containerMap[id] = true
defer delete(containerMap, id)
retry := 5
for err == nil || retry > 0 {
statsChan := make(chan *docker.Stats)
go func() {
for {
select {
case stats, ok := <-statsChan:
if !ok {
return
}
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()
inchan <- event
}
}
}()
err = t.client.Stats(docker.StatsOptions{
ID: id,
Stats: statsChan,
Stream: true,
})
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)
}
}
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()))
}