Skip to content

Commit 5e93914

Browse files
committed
pkg/leakybucket: simpler timer logic, remove defer call from loop
1 parent 073a35d commit 5e93914

File tree

1 file changed

+22
-14
lines changed

1 file changed

+22
-14
lines changed

pkg/leakybucket/bucket.go

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -204,11 +204,7 @@ func FromFactory(bucketFactory BucketFactory) *Leaky {
204204
/* for now mimic a leak routine */
205205
//LeakRoutine us the life of a bucket. It dies when the bucket underflows or overflows
206206
func LeakRoutine(leaky *Leaky) error {
207-
var (
208-
durationTickerChan = make(<-chan time.Time)
209-
durationTicker *time.Ticker
210-
firstEvent = true
211-
)
207+
firstEvent := true
212208

213209
defer trace.CatchPanic(fmt.Sprintf("crowdsec/LeakRoutine/%s", leaky.Name))
214210

@@ -233,11 +229,29 @@ func LeakRoutine(leaky *Leaky) error {
233229
if err != nil {
234230
leaky.logger.Errorf("Problem at bucket initializiation. Bail out %T : %v", f, err)
235231
close(leaky.Signal)
236-
return fmt.Errorf("Problem at bucket initializiation. Bail out %T : %v", f, err)
232+
return fmt.Errorf("problem at bucket initializiation. Bail out %T : %v", f, err)
237233
}
238234
}
239235

240236
leaky.logger.Debugf("Leaky routine starting, lifetime : %s", leaky.Duration)
237+
238+
timer := time.NewTimer(leaky.Duration)
239+
defer timer.Stop()
240+
241+
drain := func() {
242+
select {
243+
case <-timer.C:
244+
default:
245+
}
246+
}
247+
248+
reset := func() {
249+
if !timer.Stop() {
250+
drain()
251+
}
252+
timer.Reset(leaky.Duration)
253+
}
254+
241255
for {
242256
select {
243257
/*receiving an event*/
@@ -276,13 +290,7 @@ func LeakRoutine(leaky *Leaky) error {
276290

277291
// reinitialize the durationTicker when it's not a counter bucket
278292
if !leaky.timedOverflow || firstEvent {
279-
if firstEvent {
280-
durationTicker = time.NewTicker(leaky.Duration)
281-
durationTickerChan = durationTicker.C
282-
defer durationTicker.Stop()
283-
} else {
284-
durationTicker.Reset(leaky.Duration)
285-
}
293+
reset()
286294
}
287295
firstEvent = false
288296
/*we overflowed*/
@@ -301,7 +309,7 @@ func LeakRoutine(leaky *Leaky) error {
301309
leaky.logger.Tracef("Returning from leaky routine.")
302310
return nil
303311
/*we underflow or reach bucket deadline (timers)*/
304-
case <-durationTickerChan:
312+
case <-timer.C:
305313
var (
306314
alert types.RuntimeAlert
307315
err error

0 commit comments

Comments
 (0)