@@ -204,11 +204,7 @@ func FromFactory(bucketFactory BucketFactory) *Leaky {
204
204
/* for now mimic a leak routine */
205
205
//LeakRoutine us the life of a bucket. It dies when the bucket underflows or overflows
206
206
func LeakRoutine (leaky * Leaky ) error {
207
- var (
208
- durationTickerChan = make (<- chan time.Time )
209
- durationTicker * time.Ticker
210
- firstEvent = true
211
- )
207
+ firstEvent := true
212
208
213
209
defer trace .CatchPanic (fmt .Sprintf ("crowdsec/LeakRoutine/%s" , leaky .Name ))
214
210
@@ -233,11 +229,29 @@ func LeakRoutine(leaky *Leaky) error {
233
229
if err != nil {
234
230
leaky .logger .Errorf ("Problem at bucket initializiation. Bail out %T : %v" , f , err )
235
231
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 )
237
233
}
238
234
}
239
235
240
236
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
+
241
255
for {
242
256
select {
243
257
/*receiving an event*/
@@ -276,13 +290,7 @@ func LeakRoutine(leaky *Leaky) error {
276
290
277
291
// reinitialize the durationTicker when it's not a counter bucket
278
292
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 ()
286
294
}
287
295
firstEvent = false
288
296
/*we overflowed*/
@@ -301,7 +309,7 @@ func LeakRoutine(leaky *Leaky) error {
301
309
leaky .logger .Tracef ("Returning from leaky routine." )
302
310
return nil
303
311
/*we underflow or reach bucket deadline (timers)*/
304
- case <- durationTickerChan :
312
+ case <- timer . C :
305
313
var (
306
314
alert types.RuntimeAlert
307
315
err error
0 commit comments