summaryrefslogtreecommitdiff
path: root/ratelimit.c
blob: d9eb493496510b6dfe57dee179791f1e71f2f9e1 (plain)
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
/*-*- Mode: C; c-basic-offset: 8 -*-*/

#include <assert.h>

#include "ratelimit.h"
#include "log.h"

/* Modelled after Linux' lib/ratelimit.c by Dave Young
 * <hidave.darkstar@gmail.com>, which is licensed GPLv2. */

bool ratelimit_test(RateLimit *r) {
        usec_t timestamp;

        timestamp = now(CLOCK_MONOTONIC);

        assert(r);
        assert(r->interval > 0);
        assert(r->burst > 0);

        if (r->begin <= 0 ||
            r->begin + r->interval < timestamp) {

                if (r->n_missed > 0)
                        log_warning("%u events suppressed", r->n_missed);

                r->begin = timestamp;

                /* Reset counters */
                r->n_printed = 0;
                r->n_missed = 0;
                goto good;
        }

        if (r->n_printed <= r->burst)
                goto good;

        r->n_missed++;
        return false;

good:
        r->n_printed++;
        return true;
}