Importing all of DRL, including ulogd and all of its files.
[distributedratelimiting.git] / drl / simple.c
1 /* See the DRL-LICENSE file for this file's software license. */
2
3 #include <arpa/inet.h>
4 #include <assert.h>
5 #include <inttypes.h>
6 #include <netinet/in.h>
7 #include <pthread.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <sys/time.h>
12 #include <sys/types.h>
13 #include <time.h>
14
15 #include "common_accounting.h"
16 #include "simple.h"
17 #include "logging.h"
18
19 simple_flow_table simple_table_create(common_accounting_t *common) {
20     simple_flow_table table = malloc(sizeof(struct sim_flow_table));
21
22     if (table == NULL) {
23         return NULL;
24     }
25
26     memset(table, 0, sizeof(struct sim_flow_table));
27     table->common = common;
28     table->hash_function = NULL;
29
30     gettimeofday(&table->common->last_update, NULL);
31
32     return table;
33 }
34
35 void simple_table_destroy(simple_flow_table table) {
36     free(table);
37 }
38
39 int simple_table_sample(simple_flow_table table, const key_flow *key) {
40     /* Update aggregate. */
41     table->common->bytes_since += key->packet_size;
42
43     return 0;
44 }
45
46 int simple_table_cleanup(simple_flow_table table) {
47     return 0;
48 }
49
50 void simple_table_update_flows(simple_flow_table table, struct timeval now, double ewma_weight) {
51     double time_delta;
52     double unweighted_rate;
53
54     time_delta = timeval_subtract(now, table->common->last_update);
55
56     if (time_delta <= 0) {
57         unweighted_rate = 0;
58     } else {
59         unweighted_rate = table->common->bytes_since / time_delta;
60     }
61
62     table->common->last_inst_rate = table->common->inst_rate;
63     table->common->inst_rate = unweighted_rate;
64
65     table->common->last_rate = table->common->rate;
66
67     /* If the rate is zero, then we don't know anything yet.  Don't apply EWMA
68      * in that case. */
69     if (table->common->rate == 0) {
70         table->common->rate = unweighted_rate;
71     } else {
72         table->common->rate = table->common->rate * ewma_weight +
73                               unweighted_rate * (1 - ewma_weight);
74     }
75
76     table->common->bytes_since = 0;
77     table->common->last_update = now;
78
79     /* We don't track flow rates in this table. (Not suitable for FPS) */
80     table->common->max_flow_rate = 0;
81 }