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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
|
/* This file is part of vmod-tbf
Copyright (C) 2013 Sergey Poznyakoff
Vmod-tbf is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
Vmod-tbf is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with vmod-tbf. If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <syslog.h>
#include <inttypes.h>
#include <db.h>
#include "vrt.h"
#include "vcc_if.h"
#include "bin/varnishd/cache.h"
#ifdef VMODDEBUG
# include <stdarg.h>
static void
debugprt(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vsyslog(LOG_DAEMON|LOG_DEBUG, fmt, ap);
va_end(ap);
}
#define debug(c) debugprt c
#else
# define debug(c)
#endif
#ifndef USEC_PER_SEC
# define USEC_PER_SEC 1000000L
#endif
static char *dbname;
static DB *db;
static uint64_t autosync_max;
static uint64_t autosync_count;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
#define DBFILEMODE 0640
static void
tbf_set_db_name(const char *file_name)
{
if (dbname)
free(dbname);
dbname = strdup(file_name);
if (!dbname)
abort();
}
struct mode_kw {
char *mkw_str;
int mkw_len;
int mkw_tok;
};
enum {
MKW_TRUNCATE,
MKW_MODE,
MKW_SYNC
};
static struct mode_kw mode_kw_tab[] = {
#define S(s) #s, sizeof(#s)-1
{ S(truncate), MKW_TRUNCATE },
{ S(trunc), MKW_TRUNCATE },
{ S(mode=), MKW_MODE },
{ S(sync=), MKW_SYNC },
{ NULL }
#undef S
};
static void
tbf_open_internal(const char *mode)
{
int rc;
int flags = DB_CREATE|DB_THREAD;
int filemode = DBFILEMODE;
uint64_t n;
char *p;
if (!dbname)
tbf_set_db_name(LOCALSTATEDIR "/tbf.db");
debug(("opening database %s", dbname));
rc = db_create(&db, NULL, 0);
if (rc) {
syslog(LOG_DAEMON|LOG_ERR, "cannot create db struct");
return;
}
while (*mode) {
struct mode_kw *mkw;
for (mkw = mode_kw_tab; mkw->mkw_str; mkw++) {
if (strncmp(mode, mkw->mkw_str, mkw->mkw_len) == 0)
break;
}
if (!mkw->mkw_str) {
syslog(LOG_DAEMON|LOG_ERR, "invalid keyword %s", mode);
break;
}
mode += mkw->mkw_len;
switch (mkw->mkw_tok) {
case MKW_TRUNCATE:
flags |= DB_TRUNCATE;
break;
case MKW_MODE:
errno = 0;
n = strtoul(mode, &p, 8);
if (errno || (n & ~0777) || !(*p == 0 || *p == ';')) {
syslog(LOG_DAEMON|LOG_ERR,
"invalid file mode near %s", p);
mode += strlen(mode);
} else {
filemode = n;
mode = p;
}
break;
case MKW_SYNC:
errno = 0;
n = strtoul(mode, &p, 10);
if (errno || !(*p == 0 || *p == ';')) {
syslog(LOG_DAEMON|LOG_ERR,
"invalid count near %s", p);
mode += strlen(mode);
} else {
autosync_max = n;
autosync_count = 0;
}
break;
}
if (*mode == 0)
break;
else if (*mode == ';')
mode++;
else {
syslog(LOG_DAEMON|LOG_ERR,
"expected ';' near %s", mode);
break;
}
}
rc = db->open(db, NULL, dbname, NULL, DB_HASH, flags, filemode);
if (rc) {
syslog(LOG_DAEMON|LOG_ERR, "cannot open %s: %s",
dbname, db_strerror (rc));
db->close(db, 0);
db = NULL;
}
}
static DB *
tbf_open(const char *mode)
{
pthread_mutex_lock(&mutex);
if (!db)
tbf_open_internal(mode ? mode : "truncate");
pthread_mutex_unlock(&mutex);
return db;
}
int
tbf_init(struct vmod_priv *priv, const struct VCL_conf *vclconf)
{
}
void
vmod_open(struct sess *sp, const char *file_name, const char *mode)
{
if (db) {
syslog(LOG_DAEMON|LOG_ERR, "tbf.open called twice");
return;
}
tbf_set_db_name(file_name);
tbf_open(mode);
}
void
vmod_close(struct sess *sp)
{
if (db) {
debug(("closing database %s", dbname));
db->close(db, 0);
db = NULL;
}
}
void
vmod_sync(struct sess *sp)
{
if (db) {
debug(("synchronizing database"));
db->sync(db, 0);
}
}
/* Algorithm:
* A token is added to the bucket at a constant rate of 1 token per INTERVAL
microseconds.
* A bucket can hold at most BURST_SIZE tokens. If a token arrives when the
bucket is full, that token is discarded.
* When COST items of data arrive, COST tokens are removed
from the bucket and the data are accepted.
* If fewer than COST tokens are available, no tokens are removed from
the bucket and the data are not accepted.
This keeps the data traffic at a constant rate INTERVAL with bursts of
up to BURST_SIZE data items. Such bursts occur when no data was being
arrived for BURST_SIZE*INTERVAL or more microseconds.
*/
struct tbf_bucket {
uint64_t timestamp; /* microseconds since epoch */
size_t tokens; /* tokens available */
};
unsigned
vmod_rate(struct sess *sp, const char *key, int cost, double t, int burst_size)
{
DB *db;
DBT keydat, content;
struct timeval tv;
uint64_t now;
uint64_t elapsed;
uint64_t tokens;
struct tbf_bucket *bkt, init_bkt;
int rc, res;
unsigned long interval = t * USEC_PER_SEC;
debug(("entering rate(%s,%d,%g,%d)", key, cost, t, burst_size));
if (interval == 0 || burst_size == 0)
return false;
if (!cost) {
/* cost free, so don't waste time on database access */
return true;
}
if (cost > burst_size) {
/* impossibly expensive, so don't waste time on
database access */
return false;
}
db = tbf_open(NULL);
if (!db)
return false;
memset(&keydat, 0, sizeof keydat);
keydat.data = (void*) key;
keydat.size = strlen(key);
gettimeofday(&tv, NULL);
now = (uint64_t) tv.tv_sec * USEC_PER_SEC + (uint64_t)tv.tv_usec;
memset(&content, 0, sizeof content);
content.flags = DB_DBT_MALLOC;
rc = db->get(db, NULL, &keydat, &content, 0);
switch (rc) {
case 0:
bkt = (struct tbf_bucket *) content.data;
/* calculate elapsed time and number of new tokens since
last add */;
elapsed = now - bkt->timestamp;
tokens = elapsed / interval; /* partial tokens ignored */
/* timestamp set to time of most recent token */
bkt->timestamp += tokens * interval;
/* add existing tokens to 64bit counter to prevent overflow
in range check */
tokens += bkt->tokens;
if (tokens >= burst_size)
bkt->tokens = burst_size;
else
bkt->tokens = (size_t)tokens;
debug(("found, elapsed time: %"PRIu64" us, "
"new tokens: %"PRIu64", total: %lu ",
elapsed, tokens, (unsigned long) bkt->tokens));
break;
case DB_NOTFOUND:
/* Initialize the structure */
init_bkt.timestamp = now;
init_bkt.tokens = burst_size;
bkt = &init_bkt;
break;
default:
syslog(LOG_DAEMON|LOG_ERR, "cannot fetch data %s: %s",
key, db_strerror(rc));
return false;
}
if (cost <= bkt->tokens) {
res = 1;
bkt->tokens -= cost;
debug(("tbf_rate matched %s", key));
} else {
res = 0;
debug(("tbf_rate overlimit on %s", key));
}
/* Update the db */
content.data = (void*) bkt;
content.size = sizeof(*bkt);
rc = db->put (db, NULL, &keydat, &content, 0);
if (rc) {
syslog(LOG_DAEMON|LOG_ERR, "error updating key %s: %s",
key, db_strerror(rc));
}
if (bkt != &init_bkt)
free(bkt);
if (autosync_max && ++autosync_count >= autosync_max) {
debug(("synchronizing database"));
db->sync(db, 0);
autosync_count = 0;
}
return res;
}
|