-
Notifications
You must be signed in to change notification settings - Fork 3
/
tag-change-callback.go
151 lines (132 loc) · 4.15 KB
/
tag-change-callback.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
package steps
import (
"fmt"
"sync"
"time"
"github.com/antongulenko/golib"
"github.com/bitflow-stream/go-bitflow/bitflow"
"github.com/bitflow-stream/go-bitflow/script/reg"
log "github.com/sirupsen/logrus"
)
func AddTagChangeListenerParams(step *reg.RegisteredStep) {
step.
Required("tag", reg.String()).
Optional("update-after", reg.Duration(), 2*time.Minute).
Optional("expire-after", reg.Duration(), 15*time.Second).
Optional("expire-on-close", reg.Bool(), false)
}
type TagChangeCallback interface {
Expired(value string, allValues []string) error
Updated(value string, sample *bitflow.Sample, allValues []string) error
}
type TagChangeListener struct {
bitflow.AbstractSampleProcessor
Tag string
UpdateInterval time.Duration
ExpirationTimeout time.Duration
ExpireOnClose bool
Callback TagChangeCallback
loop golib.LoopTask
lastUpdated map[string]time.Time
lastSeen map[string]time.Time
lock sync.Mutex
}
func (t *TagChangeListener) ReadParameters(params map[string]interface{}) {
t.Tag = params["tag"].(string)
t.UpdateInterval = params["update-after"].(time.Duration)
t.ExpirationTimeout = params["expire-after"].(time.Duration)
t.ExpireOnClose = params["expire-on-close"].(bool)
}
func (t *TagChangeListener) String() string {
return fmt.Sprintf("TagChangeListener (tag: %v, expiration: %v)", t.Tag, t.ExpirationTimeout)
}
func (t *TagChangeListener) Start(wg *sync.WaitGroup) golib.StopChan {
t.lastUpdated = make(map[string]time.Time)
t.lastSeen = make(map[string]time.Time)
t.loop.Description = "Loop task of " + t.String()
t.loop.Loop = t.loopExpireTagValues
if t.ExpireOnClose {
t.loop.StopHook = t.expireAllTagValues
}
return t.loop.Start(wg)
}
func (t *TagChangeListener) Close() {
t.loop.Stop()
t.AbstractSampleProcessor.CloseSink()
}
func (t *TagChangeListener) Sample(sample *bitflow.Sample, header *bitflow.Header) error {
value := sample.Tag(t.Tag)
if value != "" {
// TODO instead of doing this here (potentially long-running), put it into a separate Goroutine
t.handleTagValueUpdated(value, sample)
}
return t.AbstractSampleProcessor.GetSink().Sample(sample, header)
}
func (t *TagChangeListener) loopExpireTagValues(stop golib.StopChan) error {
t.expireTagValues(stop)
stop.WaitTimeout(t.ExpirationTimeout)
return nil
}
func (t *TagChangeListener) expireTagValues(stop golib.StopChan) {
t.lock.Lock()
defer t.lock.Unlock()
now := time.Now()
for val, lastSeen := range t.lastSeen {
diff := now.Sub(lastSeen)
if diff >= t.ExpirationTimeout {
log.Printf("Samples with tag %v=%v have not been seen for %v, expiring...", t.Tag, val, diff)
t.handleTagValueExpired(val)
}
if stop.Stopped() {
return
}
}
}
func (t *TagChangeListener) expireAllTagValues() {
t.lock.Lock()
defer t.lock.Unlock()
log.Printf("Expiring %v value(s) of tag %v...", len(t.lastSeen), t.Tag)
for val := range t.lastSeen {
log.Printf("Expiring tag value %v=%v...", t.Tag, val)
t.handleTagValueExpired(val)
}
}
// t.lock must be locked when calling this
func (t *TagChangeListener) handleTagValueExpired(tagValue string) {
if err := t.Callback.Expired(tagValue, t.getCurrentTags(tagValue, false)); err != nil {
log.Errorf("Failed to handle expiration of tag %v=%v: %v", t.Tag, tagValue, err)
} else {
delete(t.lastUpdated, tagValue)
delete(t.lastSeen, tagValue)
}
}
func (t *TagChangeListener) handleTagValueUpdated(tagValue string, sample *bitflow.Sample) {
last, ok := t.lastUpdated[tagValue]
now := time.Now()
updating := !ok || t.UpdateInterval <= 0 || now.Sub(last) > t.UpdateInterval
if updating {
err := t.Callback.Updated(tagValue, sample, t.getCurrentTags(tagValue, true))
if err != nil {
log.Errorln(err)
}
}
t.lock.Lock()
defer t.lock.Unlock()
t.lastSeen[tagValue] = now
if updating {
t.lastUpdated[tagValue] = now
}
}
func (t *TagChangeListener) getCurrentTags(newTag string, added bool) []string {
result := make([]string, 0, len(t.lastSeen)+1)
for tag := range t.lastSeen {
if !added && tag == newTag {
continue
}
result = append(result, tag)
}
if _, seen := t.lastSeen[newTag]; !seen && added {
result = append(result, newTag)
}
return result
}