forked from skydive-project/skydive
-
Notifications
You must be signed in to change notification settings - Fork 1
/
table.go
454 lines (390 loc) · 10.3 KB
/
table.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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/*
* Copyright (C) 2016 Red Hat, Inc.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 flow
import (
"encoding/json"
"fmt"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/mitchellh/mapstructure"
"github.com/skydive-project/skydive/common"
"github.com/skydive-project/skydive/logging"
)
type TableQuery struct {
Obj interface{}
}
type TableReply struct {
Status int
Obj json.RawMessage
}
type FlowSearchQuery struct {
NodeUUIDs []string
}
type FlowSearchReply struct {
FlowSet *FlowSet
}
type sortByLast []*Flow
type FlowQueryFilter struct {
// TODO add more filter elements
NodeUUIDs []string
}
type ExpireUpdateFunc func(f []*Flow)
type FlowHandler struct {
callback ExpireUpdateFunc
every time.Duration
duration time.Duration
}
func NewFlowHandler(callback ExpireUpdateFunc, every time.Duration, duration time.Duration) *FlowHandler {
return &FlowHandler{
callback: callback,
every: every,
duration: duration,
}
}
type Table struct {
sync.RWMutex
table map[string]*Flow
defaultFunc func()
flush chan bool
flushDone chan bool
query chan *TableQuery
reply chan *TableReply
state int64
lockState sync.RWMutex
wg sync.WaitGroup
updateHandler *FlowHandler
expireHandler *FlowHandler
tableClock int64
}
func NewTable(updateHandler *FlowHandler, expireHandler *FlowHandler) *Table {
t := &Table{
table: make(map[string]*Flow),
flush: make(chan bool),
flushDone: make(chan bool),
state: common.StoppedState,
updateHandler: updateHandler,
expireHandler: expireHandler,
}
atomic.StoreInt64(&t.tableClock, time.Now().Unix())
return t
}
func NewTableFromFlows(flows []*Flow, updateHandler *FlowHandler, expireHandler *FlowHandler) *Table {
nft := NewTable(updateHandler, expireHandler)
nft.Update(flows)
return nft
}
func (ft *Table) String() string {
ft.RLock()
defer ft.RUnlock()
return fmt.Sprintf("%d flows", len(ft.table))
}
func (ft *Table) Update(flows []*Flow) {
ft.Lock()
for _, f := range flows {
if _, ok := ft.table[f.UUID]; !ok {
ft.table[f.UUID] = f
} else {
ft.table[f.UUID].Statistics = f.Statistics
}
}
ft.Unlock()
}
func matchQueryFilter(f *Flow, filter *FlowQueryFilter) bool {
for _, u := range filter.NodeUUIDs {
if f.ProbeNodeUUID == u || f.IfSrcNodeUUID == u || f.IfDstNodeUUID == u {
return true
}
}
return false
}
func (ft *Table) GetTime() int64 {
return atomic.LoadInt64(&ft.tableClock)
}
func (ft *Table) GetFlows(filters ...FlowQueryFilter) *FlowSet {
ft.RLock()
defer ft.RUnlock()
flowset := NewFlowSet()
for _, f := range ft.table {
if len(filters) == 0 || matchQueryFilter(f, &filters[0]) {
if flowset.Start == 0 || flowset.Start > f.Statistics.Start {
flowset.Start = f.Statistics.Start
}
if flowset.End == 0 || flowset.Start < f.Statistics.Last {
flowset.End = f.Statistics.Last
}
flowset.Flows = append(flowset.Flows, f)
}
}
return flowset
}
func (ft *Table) GetFlow(key string) *Flow {
ft.RLock()
defer ft.RUnlock()
if flow, found := ft.table[key]; found {
return flow
}
return nil
}
func (ft *Table) GetOrCreateFlow(key string) (*Flow, bool) {
ft.Lock()
defer ft.Unlock()
if flow, found := ft.table[key]; found {
return flow, false
}
new := &Flow{Statistics: &FlowStatistics{}}
ft.table[key] = new
return new, true
}
/* Return a new flow.Table that contain <last> active flows */
func (ft *Table) FilterLast(last time.Duration) []*Flow {
var flows []*Flow
selected := time.Now().Unix() - int64((last).Seconds())
ft.RLock()
defer ft.RUnlock()
for _, f := range ft.table {
fs := f.GetStatistics()
if fs.Last >= selected {
flows = append(flows, f)
}
}
return flows
}
func (ft *Table) SelectLayer(endpointType FlowEndpointType, list []string) *FlowSet {
meth := make(map[string][]*Flow)
ft.RLock()
for _, f := range ft.table {
layerFlow := f.GetStatistics().GetEndpointsType(endpointType)
if layerFlow == nil || layerFlow.AB.Value == "ff:ff:ff:ff:ff:ff" || layerFlow.BA.Value == "ff:ff:ff:ff:ff:ff" {
continue
}
meth[layerFlow.AB.Value] = append(meth[layerFlow.AB.Value], f)
meth[layerFlow.BA.Value] = append(meth[layerFlow.BA.Value], f)
}
ft.RUnlock()
mflows := make(map[*Flow]struct{})
flowset := NewFlowSet()
for _, eth := range list {
if flist, ok := meth[eth]; ok {
for _, f := range flist {
if _, found := mflows[f]; !found {
mflows[f] = struct{}{}
if flowset.Start == 0 || flowset.Start > f.Statistics.Start {
flowset.Start = f.Statistics.Start
}
if flowset.End == 0 || flowset.Start < f.Statistics.Last {
flowset.End = f.Statistics.Last
}
flowset.Flows = append(flowset.Flows, f)
}
}
}
}
return flowset
}
/* Internal call only, Must be called under ft.Lock() */
func (ft *Table) expired(expireBefore int64) {
var expiredFlows []*Flow
flowTableSzBefore := len(ft.table)
for _, f := range ft.table {
fs := f.GetStatistics()
if fs.Last < expireBefore {
duration := time.Duration(fs.Last - fs.Start)
logging.GetLogger().Debugf("Expire flow %s Duration %v", f.UUID, duration)
expiredFlows = append(expiredFlows, f)
}
}
/* Advise Clients */
if ft.expireHandler != nil {
ft.expireHandler.callback(expiredFlows)
}
for _, f := range expiredFlows {
delete(ft.table, f.UUID)
}
flowTableSz := len(ft.table)
logging.GetLogger().Debugf("Expire Flow : removed %v ; new size %v", flowTableSzBefore-flowTableSz, flowTableSz)
}
func (ft *Table) Updated(now time.Time) {
timepoint := now.Unix() - int64((ft.updateHandler.duration).Seconds())
ft.RLock()
ft.updated(timepoint)
ft.RUnlock()
}
/* Internal call only, Must be called under ft.RLock() */
func (ft *Table) updated(updateFrom int64) {
var updatedFlows []*Flow
for _, f := range ft.table {
fs := f.GetStatistics()
if fs.Last > updateFrom {
updatedFlows = append(updatedFlows, f)
}
}
/* Advise Clients */
if ft.updateHandler != nil {
ft.updateHandler.callback(updatedFlows)
}
logging.GetLogger().Debugf("Send updated Flow %d", len(updatedFlows))
}
func (ft *Table) expireNow() {
const Now = int64(^uint64(0) >> 1)
ft.Lock()
ft.expired(Now)
ft.Unlock()
}
func (ft *Table) Expire(now time.Time) {
timepoint := now.Unix() - int64((ft.expireHandler.duration).Seconds())
ft.Lock()
ft.expired(timepoint)
ft.Unlock()
}
func (ft *Table) RegisterDefault(fn func()) {
ft.Lock()
ft.defaultFunc = fn
ft.Unlock()
}
/* Need to Rlock the table before calling. Returned flows may not be unique */
// TODO need to be merge with GetFlows using filters
func (ft *Table) Window(start, end int64) *FlowSet {
flowset := NewFlowSet()
if start > end {
return flowset
}
flowset.Start = start
flowset.End = end
for _, f := range ft.table {
fstart := f.GetStatistics().Start
fend := f.GetStatistics().Last
if fstart < end && (fend == 0 || fend > start) {
flowset.Flows = append(flowset.Flows, f)
}
}
return flowset
}
func (ft *Table) Flush() {
ft.flush <- true
<-ft.flushDone
}
func (s sortByLast) Len() int {
return len(s)
}
func (s sortByLast) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s sortByLast) Less(i, j int) bool {
return s[i].GetStatistics().Last > s[j].GetStatistics().Last
}
func (ft *Table) onFlowSearchQueryMessage(o interface{}) (*FlowSearchReply, int) {
var fq FlowSearchQuery
err := mapstructure.Decode(o, &fq)
if err != nil {
logging.GetLogger().Errorf("Unable to decode flow search message %v", o)
return nil, 500
}
flowset := ft.GetFlows(FlowQueryFilter{
NodeUUIDs: fq.NodeUUIDs,
})
if len(flowset.Flows) == 0 {
return &FlowSearchReply{
FlowSet: flowset,
}, 404
}
sort.Sort(sortByLast(flowset.Flows))
return &FlowSearchReply{
FlowSet: flowset,
}, 200
}
func (ft *Table) onQuery(q *TableQuery) *TableReply {
var obj interface{}
status := 500
switch q.Obj.(type) {
case *FlowSearchQuery:
obj, status = ft.onFlowSearchQueryMessage(q.Obj)
}
// return the json version here to avoid touching the flow outside this
// goroutine leading in race
b, _ := json.Marshal(obj)
raw := json.RawMessage(b)
return &TableReply{
Status: status,
Obj: raw,
}
}
func (ft *Table) Query(query *TableQuery) *TableReply {
ft.lockState.Lock()
defer ft.lockState.Unlock()
if atomic.LoadInt64(&ft.state) == common.RunningState {
ft.query <- query
r := <-ft.reply
return r
}
return nil
}
func (ft *Table) Start() {
ft.wg.Add(1)
defer ft.wg.Done()
updateTicker := time.NewTicker(ft.updateHandler.every)
defer updateTicker.Stop()
expireTicker := time.NewTicker(ft.expireHandler.every)
defer expireTicker.Stop()
nowTicker := time.NewTicker(time.Second * 1)
defer nowTicker.Stop()
ft.query = make(chan *TableQuery)
ft.reply = make(chan *TableReply)
atomic.StoreInt64(&ft.state, common.RunningState)
for atomic.LoadInt64(&ft.state) == common.RunningState {
select {
case now := <-expireTicker.C:
ft.Expire(now)
case now := <-updateTicker.C:
ft.Updated(now)
case <-ft.flush:
ft.expireNow()
ft.flushDone <- true
case query, ok := <-ft.query:
if ok {
ft.reply <- ft.onQuery(query)
}
case now := <-nowTicker.C:
atomic.StoreInt64(&ft.tableClock, now.Unix())
default:
if ft.defaultFunc != nil {
ft.defaultFunc()
} else {
time.Sleep(20 * time.Millisecond)
}
}
}
}
func (ft *Table) Stop() {
ft.lockState.Lock()
if atomic.CompareAndSwapInt64(&ft.state, common.RunningState, common.StoppingState) {
ft.wg.Wait()
}
ft.lockState.Unlock()
close(ft.query)
close(ft.reply)
// FIX trigger deadlock since Stop is called from a place where the graph
// is locked and usually the enhance pipeline lock the graph as well.
// expireNow calls the enhance.
//ft.expireNow()
}