aboutsummaryrefslogtreecommitdiff
path: root/src/binlog.c
blob: b2d9f871390e3950984456db4ec0a4b0969c6881 (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
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
/* This file is part of vmod-binlog
   Copyright (C) 2013 Sergey Poznyakoff

   Vmod-binlog 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-binlog 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-binlog.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <config.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <syslog.h>
#include <stddef.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#include "vrt.h"
#include "vcc_if.h"
#include "bin/varnishd/cache.h"
#include "vmod-binlog.h"
#include "pack.h"

#ifndef O_SEARCH
# define O_SEARCH 0
#endif

#define BLF_ROUNDTS 0x01

enum binlog_state {
	state_init,
	state_start,
	state_pack
};

struct binlog_config {
	size_t size;         /* maximum file size */
	unsigned interval;   /* file rotation interval */
	char *pattern;       /* file name pattern */
	int umask;           /* umask for new files and directories */
	char *dir;           /* root storage directory */      
	int dd;              /* directory descriptor */
	char *fname;         /* current file name */
	int fd;              /* current file descriptor */
	struct binlog_file_header *base;     /* mmap base */
	char *recbase;       /* record base */
	size_t recnum;       /* number of records in recbase */
	size_t recsize;      /* record size */
	time_t stoptime;     /* when to rotate the current file */
	pthread_mutex_t mutex;
	int debug;
	int flags;

	char *dataspec;
	struct packinst *inst_head;
	struct packinst *inst_cur;
	struct packenv *env;
	enum binlog_state state;
	time_t timestamp;
};

static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void
binlog_error(const char *fmt, ...)
{
	va_list ap;
	va_start(ap, fmt);
	vsyslog(LOG_DAEMON|LOG_ERR, fmt, ap);
	va_end(ap);
}

void
binlog_debug(const char *fmt, ...)
{
	va_list ap;
	va_start(ap, fmt);
	vsyslog(LOG_DAEMON|LOG_DEBUG, fmt, ap);
	va_end(ap);
}

#define debug(c,l,s) do { if ((c)->debug>=(l)) binlog_debug s; } while(0)

int
module_init(struct vmod_priv *priv, const struct VCL_conf *vclconf)
{
	struct binlog_config *conf = calloc(1, sizeof(*conf));
	AN(conf);
	priv->priv = conf;
	return 0;
}

static char *
findparam(const char *param, char *name)
{
	const char *p;
	char *q;

	while (*param) {
		for (p = param, q = name; *p && *q && *p == *q; p++, q++);
		for (param = p; *param && *param != ';'; param++);
		if (*q == 0 && *p == '=') {
			size_t len = param - p - 1;
			q = malloc(len + 1);
			AN(q);
			memcpy(q, p + 1, len);
			q[len] = 0;
			return q;
		}
		if (*param)
			++param;
	}
	return NULL;
}

static unsigned long
getinterval(char *p, char **endp)
{
	int n;
	unsigned long hours = 0, minutes = 0, seconds = 0;
    
	for (;;) {
		n = 0;
		while (*p && isdigit(*p)) {
			n = 10*n + *p - '0';
			p++;
		}
    
		switch (*p) {
		case 'h':
		case 'H':
			if (hours) {
				*endp = p;
				return -1;
			}
			hours = n;
			break;
		case 'm':
		case 'M':
			if (minutes) {
				*endp = p;
				return -1;
			}
			minutes = n;
			break;
		case 's':
		case 'S':
			if (seconds) {
				*endp = p;
				return -1;
			}
			seconds = n;
			break;
		default:
			*endp = p;
			if (!hours && !minutes && !seconds)
				return n;
			return (hours*60 + minutes)*60 + seconds;
		}
		p++;
	}
}

void
vmod_init(struct sess *sp, struct vmod_priv *priv,
	  const char *dir, const char *dataspec, const char *param)
{
	struct binlog_config *conf = priv->priv;
	struct stat st;
	char *p, *q;
	unsigned long n;

	p = findparam(param, "debug");
	if (p) {
		conf->debug = atoi(p);
		free(p);
	}

	if (stat(dir, &st)) {
		if (errno == ENOENT)
			binlog_error("logging directory does not exist");
		else
			binlog_error("cannot stat logging directory %s: %s",
				     dir, strerror(errno));
		abort();
	}
	if (!S_ISDIR(st.st_mode)) {
		binlog_error("%s exists, but is not a directory");
		abort();
	}
	conf->dd = open(dir, O_SEARCH | O_DIRECTORY);
	if (conf->dd == -1) {
		binlog_error("cannot open directory %s: %s",
			     dir, strerror(errno));
		abort();
	}
	conf->dir = strdup(dir);
	AN(conf->dir);

	conf->inst_head = packcomp(dataspec, &p);
	AN(conf->inst_head);
	if (*p) {
		binlog_error("cannot compile data format near %s", p);
		abort();
	}
	conf->recsize = packsize(conf->inst_head);
	conf->env = packenv_create(conf->recsize);
	AN(conf->env);
	conf->recsize += offsetof(struct binlog_record,data);
	conf->dataspec = strdup(dataspec);
	AN(conf->dataspec);
		
	p = findparam(param, "pattern");
	if (!p) {
		p = strdup(BINLOG_PATTERN);
		AN(p);
	}
	conf->pattern = p;
	
	p = findparam(param, "size");
	if (p) {
		uintmax_t u;
		
		errno = 0;
		u = strtoul(p, &q, 10);
		if (errno) {
			binlog_error("invalid size value");
			abort();
		}
		free(p);
		switch (*q) {
		case 'g':
		case 'G':
			u <<= 10;
		case 'm':
		case 'M':
			u <<= 10;
		case 'k':
		case 'K':
			u <<= 10;
		}
		if (u > SIZE_T_MAX) {
			binlog_error("invalid size value");
			abort();
		}
		conf->size = u;
	} else
		conf->size = BINLOG_SIZE;

	p = findparam(param, "interval");
	if (p) {
		conf->interval = getinterval(p, &q);
		free(p);
		if (*q) {
			binlog_error("invalid interval (near \"%s\")", q);
			abort();
		}
	} else
		conf->interval = BINLOG_INTERVAL;

	p = findparam(param, "umask");
	if (p) {
		n = strtoul(p, &q, 8);
		free(p);
		if (n & ~0777) {
			binlog_error("umask out of range");
			abort();
		}
		if (*q) {
			binlog_error("invalid umask (near \"%s\")", q);
			abort();
		}
	} else
		conf->umask = BINLOG_UMASK;
	
	p = findparam(param, "roundts");
	if (p) {
		if (atoi(p))
			conf->flags |= BLF_ROUNDTS;
		else
			conf->flags &= ~BLF_ROUNDTS;
		free(p);
	}
	
	conf->fd = -1;
	conf->base = NULL;
	conf->stoptime = time(NULL);
	pthread_mutex_init(&conf->mutex, NULL);
}

static char *
mkfilename(struct sess *sp, struct binlog_config *conf)
{
	time_t ts = time(NULL);
	size_t u, n;
	char *p, *q;

	if (conf->flags & BLF_ROUNDTS)
		ts -= ts % conf->interval;
	u = WS_Reserve(sp->wrk->ws, 0);
        p = sp->wrk->ws->f;
        n = strftime(p, u, conf->pattern, gmtime(&ts));
	if (n == 0) {
		WS_Release(sp->wrk->ws, 0);
		return NULL;
	}
	q = strdup(p);
	AN(q);
	WS_Release(sp->wrk->ws, 0);
	return q;
}

static int
mkdir_p(struct binlog_config *conf, char *dir)
{
	int rc = 0;
	char *p;
	struct stat st;
	
	for (p = dir; rc == 0 && *p; p++) {
		if (*p != '/')
			continue;
		*p = 0;
		rc = fstatat(conf->dd, dir, &st, 0);
		if (rc) {
			if (errno == ENOENT) {
				rc = mkdirat(conf->dd, dir,
					     0777 & ~conf->umask);
				if (rc)
					binlog_error("cannot create %s: %s",
						     dir,
						     strerror(errno));
			} else
				binlog_error("cannot stat %s: %s", dir,
					     strerror(errno));
		} else if (!S_ISDIR(st.st_mode)) {
			binlog_error("component \"%s\" is not a directory",
				     dir);
			rc = -1;
		}
		*p = '/';
	}
	return rc;
}

static int
createfile(struct sess *sp, struct binlog_config *conf)
{
	char *fname;
	int fd;

	conf->fname = NULL;
	conf->fd = -1;
	
	fname = mkfilename(sp, conf);
	if (!fname)
		return -1;
	if (mkdir_p(conf, fname)) {
		free(fname);
		return -1;
	}

	fd = openat(conf->dd, fname, O_CREAT|O_RDWR|O_TRUNC,
		    0666 & ~conf->umask);
	if (fd == -1) {
		binlog_error("cannot create log file %s/%s: %s",
			     conf->dir, fname, strerror(errno));
		free(fname);
	}

	conf->fname = fname;
	conf->fd = fd;
	return 0;
}

static void
reset(struct binlog_config *conf)
{
	conf->fname = NULL;
	conf->fd = -1;
	conf->base = NULL;
	conf->recbase = NULL;
	conf->recnum = 0;
}

static int
setstoptime(struct binlog_config *conf)
{
	time_t ts;
	
	ts = time(NULL);
	conf->stoptime = ts - ts % conf->interval + conf->interval;
}

#define binlog_recnum(conf) \
	(((conf)->size - (conf)->base->hdrsize) / (conf)->base->recsize)

static int
newfile(struct sess *sp, struct binlog_config *conf)
{
	int c;
	void *base;	
	size_t n;
	
	setstoptime(conf);
		
	if (createfile(sp, conf))
		return -1;
	if (lseek(conf->fd, conf->size, SEEK_SET) == -1) {
		binlog_error("seek in log file %s/%s failed: %s",
			     conf->dir, conf->fname, strerror(errno));
		unlinkat(conf->dd, conf->fname, 0);
		close(conf->fd);
		free(conf->fname);
		reset(conf);
		return -1;
	}
	c = 0;
	write(conf->fd, &c, 1);
	base = mmap((caddr_t)0, conf->size,
		    PROT_READ|PROT_WRITE, MAP_SHARED,
		    conf->fd, 0);
	if (base == MAP_FAILED) {
		binlog_error("mmap: %s", strerror(errno));
		unlinkat(conf->dd, conf->fname, 0);
		close(conf->fd);
		free(conf->fname);
		reset(conf);
		return -1;
	}

	conf->base = base;
	memcpy(conf->base->magic, BINLOG_MAGIC_STR, BINLOG_MAGIC_LEN);
	conf->base->version = BINLOG_VERSION;
	conf->base->recsize = conf->recsize;
	conf->base->recnum = 0;
	strcpy((char*)(conf->base + 1), conf->dataspec);

	n = (sizeof(struct binlog_file_header) + strlen(conf->dataspec) +
	     conf->recsize - 1) / conf->recsize;
	conf->base->hdrsize = n * conf->recsize;

	conf->recbase = (char *) conf->base + conf->base->hdrsize;
	conf->recnum = binlog_recnum(conf);

	debug(conf,1,("created new log file %s",conf->fname));
	return 0;
}
	
static void
closefile(struct sess *sp, struct binlog_config *conf)
{
	size_t size;
	
	if (conf->fd == -1)
		return;
	debug(conf,1,("closing log file %s",conf->fname));
	size = binlog_size(conf->base);
	munmap(conf->base, conf->size);
	if (ftruncate(conf->fd, size))
		binlog_error("error truncating \"%s/%s\": %s",
			     conf->dir, conf->fname, strerror(errno));
	close(conf->fd);
	free(conf->fname);
	reset(conf);
}

void
vmod_start(struct sess *sp, struct vmod_priv *priv)
{
	struct binlog_config *conf = priv->priv;
	time_t ts;

	if (!conf)
		return;

	ts = time(NULL);

	if (ts >= conf->stoptime) {
		AZ(pthread_mutex_lock(&conf->mutex));
		closefile(sp, conf);
		newfile(sp, conf);
		AZ(pthread_mutex_unlock(&conf->mutex));
	}

	packenv_init(conf->env);
	conf->state = state_start;
	conf->inst_cur = conf->inst_head;
	conf->timestamp = ts;
}

void
vmod_pack(struct sess *sp, struct vmod_priv *priv, const char *str)
{
	struct binlog_config *conf = priv->priv;
	char *argv[2];
	
	if (!conf)
		return;

	switch (conf->state) {
	case state_start:
	case state_pack:
		break;
	default:
		binlog_error("pack called in wrong state (%d)", conf->state);
		return;
	}

	if (!conf->inst_cur) {
		binlog_error("format spec exhausted");
		return;
	}
	
	argv[0] = (char*) str;
	argv[1] = NULL;
	conf->env->argv = argv;
	conf->env->argc = 2;
	conf->env->argi = 0;

	conf->inst_cur = packinnext(conf->inst_cur, conf->env);
	
	conf->state = state_pack;
}

void
vmod_commit(struct sess *sp, struct vmod_priv *priv)
{
	struct binlog_config *conf = priv->priv;

	if (!conf)
		return;
	if (conf->fd == -1)
		return;

	switch (conf->state) {
	case state_start:
		binlog_error("committing empty binlog record");
		break;
	case state_pack:
		if (conf->inst_cur)
			binlog_error("committing incomplete binlog record");
		break;
	default:
		binlog_error("pack called in wrong state (%d)", conf->state);
		return;
	}

	AZ(pthread_mutex_lock(&conf->mutex));
	if (conf->base->recnum == conf->recnum) {
		binlog_error("overflow of %s/%s", conf->dir, conf->fname);
	} else {
		struct binlog_record *p =
			(struct binlog_record *)(conf->recbase +
						 conf->base->recnum *
						 conf->recsize);
		p->ts = conf->timestamp;
		memcpy(p->data, conf->env->buf_base, conf->env->buf_size);
		conf->base->recnum++;
	}
	AZ(pthread_mutex_unlock(&conf->mutex));
	conf->state = state_init;
}

void
vmod_sync(struct sess *sp, struct vmod_priv *priv)
{
	struct binlog_config *conf = priv->priv;

	if (!conf)
		return;

	AZ(pthread_mutex_lock(&conf->mutex));
	if (conf->base)
		msync(conf->base, binlog_size(conf->base), 0);
	AZ(pthread_mutex_unlock(&conf->mutex));
}	

void
vmod_close(struct sess *sp, struct vmod_priv *priv)
{
	struct binlog_config *conf = priv->priv;
	
	if (!conf)
		return;

	mutex = conf->mutex;
	AZ(pthread_mutex_lock(&mutex));
	closefile(sp, conf);
	close(conf->dd);
	free(conf->dir);
	free(conf->pattern);
	free(conf);
	AZ(pthread_mutex_unlock(&mutex));
}	
	

Return to:

Send suggestions and report system problems to the System administrator.