forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
150 lines (125 loc) · 2.04 KB
/
util.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
package flows
import (
"sync"
"time"
"github.com/elastic/beats/libbeat/beat"
"github.com/elastic/beats/libbeat/logp"
)
type worker struct {
wg sync.WaitGroup
done chan struct{}
run func(*worker)
}
type spool struct {
pub Reporter
events []beat.Event
}
func newWorker(fn func(w *worker)) *worker {
return &worker{
done: make(chan struct{}),
run: fn,
}
}
func (w *worker) Start() {
debugf("start flows worker")
w.wg.Add(1)
go func() {
defer w.finished()
w.run(w)
}()
}
func (w *worker) Stop() {
debugf("stop flows worker")
close(w.done)
w.wg.Wait()
debugf("stopped flows worker")
}
func (w *worker) finished() {
w.wg.Done()
logp.Info("flows worker loop stopped")
}
func (w *worker) sleep(d time.Duration) bool {
select {
case <-w.done:
return false
case <-time.After(d):
return true
}
}
func (w *worker) tick(t *time.Ticker) bool {
select {
case <-w.done:
return false
case <-t.C:
return true
}
}
func (w *worker) periodically(tick time.Duration, fn func() error) {
defer debugf("stop periodic loop")
ticker := time.NewTicker(tick)
for {
cont := w.tick(ticker)
if !cont {
return
}
err := fn()
if err != nil {
return
}
}
}
func (s *spool) init(pub Reporter, sz int) {
s.pub = pub
s.events = make([]beat.Event, 0, sz)
}
func (s *spool) publish(event beat.Event) {
s.events = append(s.events, event)
if len(s.events) == cap(s.events) {
s.flush()
}
}
func (s *spool) flush() {
if len(s.events) == 0 {
return
}
s.pub(s.events)
s.events = make([]beat.Event, 0, cap(s.events))
}
func gcd(a, b int64) int64 {
if a < 0 || b < 0 {
return 0
}
switch {
case a == b:
return a
case a == 0:
return b
case b == 0:
return a
}
shift := uint(0)
for (a&1) == 0 && (b&1) == 0 {
shift++
a /= 2
b /= 2
}
for (a & 1) == 0 {
a = a / 2
}
// a is always odd
for {
for (b & 1) == 0 {
b = b / 2
}
// both a and b are odd. guaranteed b >= a
if a > b {
a, b = b, a
}
b -= a
if b == 0 {
break
}
}
// restore common factors of 2
return a << shift
}