forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.go
311 lines (263 loc) · 7.09 KB
/
worker.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
package flows
import (
"encoding/base64"
"encoding/binary"
"errors"
"net"
"time"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/packetbeat/publish"
)
type flowsProcessor struct {
spool spool
table *flowMetaTable
counters *counterReg
timeout time.Duration
}
var (
ErrInvalidTimeout = errors.New("timeout must not >= 1s")
ErrInvalidPeriod = errors.New("report period must be -1 or >= 1s")
)
func newFlowsWorker(
pub publish.Flows,
table *flowMetaTable,
counters *counterReg,
timeout, period time.Duration,
) (*worker, error) {
oneSecond := 1 * time.Second
if timeout < oneSecond {
return nil, ErrInvalidTimeout
}
if 0 < period && period < oneSecond {
return nil, ErrInvalidPeriod
}
tickDuration := timeout
ticksTimeout := 1
ticksPeriod := -1
if period > 0 {
tickDuration = time.Duration(gcd(int64(timeout), int64(period)))
if tickDuration < oneSecond {
tickDuration = oneSecond
}
ticksTimeout = int(timeout / tickDuration)
if ticksTimeout == 0 {
ticksTimeout = 1
}
ticksPeriod = int(period / tickDuration)
if ticksPeriod == 0 {
ticksPeriod = 1
}
}
debugf("new flows worker. timeout=%v, period=%v, tick=%v, ticksTO=%v, ticksP=%v",
timeout, period, tickDuration, ticksTimeout, ticksPeriod)
defaultBatchSize := 1024
processor := &flowsProcessor{
table: table,
counters: counters,
timeout: timeout,
}
processor.spool.init(pub, defaultBatchSize)
return makeWorker(processor, tickDuration, ticksTimeout, ticksPeriod, 10)
}
func makeWorker(
processor *flowsProcessor,
tickDuration time.Duration,
ticksTimeout, ticksPeriod int,
align int64,
) (*worker, error) {
return newWorker(func(w *worker) {
defer processor.execute(w, false, true, true)
if align > 0 {
// round time to nearest 10 seconds for alignment
aligned := time.Unix(((time.Now().Unix()+(align-1))/align)*align, 0)
waitStart := aligned.Sub(time.Now())
debugf("worker wait start(%v): %v", aligned, waitStart)
if cont := w.sleep(waitStart); !cont {
return
}
}
nTimeout := ticksTimeout
nPeriod := ticksPeriod
reportPeriodically := ticksPeriod > 0
debugf("start flows worker loop")
w.periodicaly(tickDuration, func() error {
nTimeout--
nPeriod--
debugf("worker tick, nTimeout=%v, nPeriod=%v", nTimeout, nPeriod)
handleTimeout := nTimeout == 0
handleReports := reportPeriodically && nPeriod == 0
if handleTimeout {
nTimeout = ticksTimeout
}
if nPeriod <= 0 {
nPeriod = ticksPeriod
}
processor.execute(w, handleTimeout, handleReports, false)
return nil
})
}), nil
}
func (fw *flowsProcessor) execute(w *worker, checkTimeout, handleReports, lastReport bool) {
if !checkTimeout && !handleReports {
return
}
debugf("exec tick, timeout=%v, report=%v", checkTimeout, handleReports)
// get counter names snapshot if reports must be generated
fw.counters.mutex.Lock()
intNames := fw.counters.ints.getNames()
uintNames := fw.counters.uints.getNames()
floatNames := fw.counters.floats.getNames()
fw.counters.mutex.Unlock()
fw.table.Lock()
defer fw.table.Unlock()
ts := time.Now()
// TODO: create snapshot inside flows/tables, so deletion of timedout flows
// and reporting flows stats can be done more concurrent to packet
// processing.
for table := fw.table.tables.head; table != nil; table = table.next {
var next *biFlow
for flow := table.flows.head; flow != nil; flow = next {
next = flow.next
debugf("handle flow: %v, %v", flow.id.flowIDMeta, flow.id.flowID)
reportFlow := handleReports
isOver := lastReport
if checkTimeout {
if ts.Sub(flow.ts) > fw.timeout {
debugf("kill flow")
reportFlow = true
flow.kill() // mark flow as killed
isOver = true
table.remove(flow)
}
}
if reportFlow {
debugf("report flow")
fw.report(w, ts, flow, isOver, intNames, uintNames, floatNames)
}
}
}
fw.spool.flush()
}
func (fw *flowsProcessor) report(
w *worker,
ts time.Time,
flow *biFlow,
isOver bool,
intNames, uintNames, floatNames []string,
) {
event := createEvent(ts, flow, isOver, intNames, uintNames, floatNames)
if event != nil {
debugf("add event: %v", event)
fw.spool.publish(event)
}
}
func createEvent(
ts time.Time, f *biFlow,
isOver bool,
intNames, uintNames, floatNames []string,
) common.MapStr {
event := common.MapStr{
"@timestamp": common.Time(ts),
"start_time": common.Time(f.createTS),
"last_time": common.Time(f.ts),
"type": "flow",
"flow_id": common.NetString(f.id.Serialize()),
"final": isOver,
}
source := common.MapStr{}
dest := common.MapStr{}
// add ethernet layer meta data
if src, dst, ok := f.id.EthAddr(); ok {
source["mac"] = net.HardwareAddr(src).String()
dest["mac"] = net.HardwareAddr(dst).String()
}
// add vlan
if vlan := f.id.OutterVLan(); vlan != nil {
event["outer_vlan"] = binary.LittleEndian.Uint16(vlan)
}
if vlan := f.id.VLan(); vlan != nil {
event["vlan"] = binary.LittleEndian.Uint16(vlan)
}
// add icmp
if icmp := f.id.ICMPv4(); icmp != nil {
event["icmp_id"] = binary.LittleEndian.Uint16(icmp)
} else if icmp := f.id.ICMPv6(); icmp != nil {
event["icmp_id"] = binary.LittleEndian.Uint16(icmp)
}
// ipv4 layer meta data
if src, dst, ok := f.id.OutterIPv4Addr(); ok {
source["outer_ip"] = net.IP(src).String()
dest["outer_ip"] = net.IP(dst).String()
}
if src, dst, ok := f.id.IPv4Addr(); ok {
source["ip"] = net.IP(src).String()
dest["ip"] = net.IP(dst).String()
}
// ipv6 layer meta data
if src, dst, ok := f.id.OutterIPv6Addr(); ok {
source["outer_ipv6"] = net.IP(src).String()
dest["outer_ipv6"] = net.IP(dst).String()
}
if src, dst, ok := f.id.IPv6Addr(); ok {
source["ipv6"] = net.IP(src).String()
dest["ipv6"] = net.IP(dst).String()
}
// udp layer meta data
if src, dst, ok := f.id.UDPAddr(); ok {
source["port"] = binary.LittleEndian.Uint16(src)
dest["port"] = binary.LittleEndian.Uint16(dst)
event["transport"] = "udp"
}
// tcp layer meta data
if src, dst, ok := f.id.TCPAddr(); ok {
source["port"] = binary.LittleEndian.Uint16(src)
dest["port"] = binary.LittleEndian.Uint16(dst)
event["transport"] = "tcp"
}
if id := f.id.ConnectionID(); id != nil {
event["connection_id"] = base64.StdEncoding.EncodeToString(id)
}
if f.stats[0] != nil {
source["stats"] = encodeStats(f.stats[0], intNames, uintNames, floatNames)
}
if f.stats[1] != nil {
dest["stats"] = encodeStats(f.stats[1], intNames, uintNames, floatNames)
}
event["source"] = source
event["dest"] = dest
return event
}
func encodeStats(
stats *flowStats,
ints, uints, floats []string,
) map[string]interface{} {
report := make(map[string]interface{})
i := 0
for _, mask := range stats.intFlags {
for m := mask; m != 0; m >>= 1 {
if (m & 1) == 1 {
report[ints[i]] = stats.ints[i]
}
i++
}
}
i = 0
for _, mask := range stats.uintFlags {
for m := mask; m != 0; m >>= 1 {
if (m & 1) == 1 {
report[uints[i]] = stats.uints[i]
}
i++
}
}
i = 0
for _, mask := range stats.floatFlags {
for m := mask; m != 0; m >>= 1 {
if (m & 1) == 1 {
report[floats[i]] = stats.floats[i]
}
i++
}
}
return report
}