aboutsummaryrefslogtreecommitdiff
path: root/src/slb.c
blob: b456626b7880af2b344be0cdb14caf2b4b5937ec (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
/* This file is part of SLB
   Copyright (C) 2011 Sergey Poznyakoff

   SLB 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.

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

#include "slb.h"

char *conffile = SYSCONFDIR "/slb.conf" ;
int lint_mode;
int debug_level[_SLB_DEBCAT_MAX];
int dry_run_mode;
int preprocess_only = 0;
int standalone_mode = 1;
int foreground;
int foreground_option;
int cron_option;
char *pidfile = "/var/run/slb.pid";
time_t wakeup_interval = 5*60;
char *eval_option;
int asgn_index;
int test_option;
char *output_file_option;
char *eval_output_format = "%g\n";

char **x_argv;


struct debug_trans {
	const char *name;
	size_t length;
	int cat;
};

static struct debug_trans debug_trans[] = {
#define S(s) #s, sizeof(#s)-1
	{ S(main), SLB_DEBCAT_MAIN },
	{ S(eval), SLB_DEBCAT_EVAL },
	{ S(egram), SLB_DEBCAT_EGRAM },
	{ S(elex), SLB_DEBCAT_ELEX },
	{ S(snmp), SLB_DEBCAT_SNMP },
	{ S(output), SLB_DEBCAT_OUTPUT },
	{ S(cfgram), SLB_DEBCAT_CFGRAM },
	{ S(cflex), SLB_DEBCAT_CFLEX },
	{ S(conf), SLB_DEBCAT_CONF },
	{ NULL }
};

static int
parse_debug_level(const char *arg)
{
	unsigned long cat, lev;
	char *p;

	if (isascii(*arg) && isdigit(*arg)) {
		cat = strtoul(arg, &p, 10);
		if (cat > _SLB_DEBCAT_MAX)
			return -1;
	} else {
		size_t len = strcspn(arg, ".");
		struct debug_trans *dp;

		for (dp = debug_trans; dp->name; dp++)
			if (dp->length == len &&
			    memcmp(dp->name, arg, len) == 0)
				break;

		if (!dp->name)
			return -1;
		cat = dp->cat;
		p = (char*) arg + len;
	}

	if (*p == 0)
		lev = 100;
	else if (*p != '.')
		return -1;
	else {
		lev = strtoul(p + 1, &p, 10);
		if (*p)
			return -1;
	}
	debug_level[cat] = lev;
	return 0;
}


#include "cmdline.h"


static int
logger_callback(int majorID, int minorID, void *serverarg, void *clientarg)
{
	struct snmp_log_message *msg = serverarg;
	int len;
	
	len = strcspn(msg->msg, "\n");
	logmsg(msg->priority, "%.*s", len, msg->msg);
	return 0;
}

void
slb_snmp_setup()
{
	if (netsnmp_register_callback(SNMP_CALLBACK_LIBRARY,
				      SNMP_CALLBACK_LOGGING,
				      logger_callback,
				      NULL,
				      NETSNMP_CALLBACK_DEFAULT_PRIORITY)
	    != SNMPERR_SUCCESS) {
		logmsg(LOG_CRIT, "cannot register logger");
		exit(EX_SOFTWARE);
	}
	snmp_enable_calllog();
	/* This informs value formatting functions that only the value
	   itself should be printed, without the type prefix and quotes */
	netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID,
			       NETSNMP_DS_LIB_QUICK_PRINT, 1);
	netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID,
			       NETSNMP_DS_LIB_NUMERIC_TIMETICKS, 1);
}


int slb_sigtab[] = { SIGCHLD, SIGTERM, SIGQUIT, SIGINT, SIGHUP,
		     SIGALRM, SIGPIPE };
size_t slb_sigcount = sizeof(slb_sigtab)/sizeof(slb_sigtab[0]);

void
set_signals(void (*handler)(int signo), int *sigv, int sigc)
{
	int i;
	struct sigaction act;
	
	act.sa_flags = 0;
	sigemptyset(&act.sa_mask);
	for (i = 0; i < sigc; i++)
		sigaddset(&act.sa_mask, i);
	
	for (i = 0; i < sigc; i++) {
		act.sa_handler = handler;
		sigaction(sigv[i], &act, NULL);
	}
}


/* Check whether pidfile NAME exists and if so, whether its PID is still
   active. Exit if it is. */
void
check_pidfile(char *name)
{
	unsigned long pid;
	FILE *fp;

	if (!name)
		return;
	
	fp = fopen(name, "r");
	
	if (!fp) {
		if (errno == ENOENT)
			return;
		logmsg(LOG_ERR, _("cannot open pidfile `%s': %s"),
		       name, strerror(errno));
		exit(EX_TEMPFAIL);
	}
	if (fscanf(fp, "%lu", &pid) != 1) {
		logmsg(LOG_ERR, ("cannot get pid from pidfile `%s'"), name);
	} else {
		if (kill(pid, 0) == 0) {
			logmsg(LOG_ERR,
			       _("%s appears to run with pid %lu. "
				 "If it does not, remove `%s' and retry."),
				program_name, pid, name);
			exit(EX_USAGE);
		}
	}
		
	fclose(fp);
	if (unlink(pidfile)) {
		logmsg(LOG_ERR, _("cannot unlink pidfile `%s': %s"),
		       name, strerror(errno));
		exit(EX_USAGE);
	}
}

void
create_pidfile(char *name)
{
	FILE *fp;

	if (!name)
		return;
	
	fp = fopen(name, "w");
	if (!fp) {
		logmsg(LOG_ERR, _("cannot create pidfile `%s': %s"),
			name, strerror(errno));
		exit(EX_TEMPFAIL);
	}
	fprintf(fp, "%lu", (unsigned long) getpid());
	fclose(fp);
}

void
remove_pidfile(char *name)
{
	if (name && unlink(name))
		logmsg(LOG_ERR, _("cannot unlink pidfile `%s': %s"),
		       name, strerror(errno));
}


#define ACT_NONE   0
#define ACT_WAKEUP 1
#define ACT_RECONF 2
#define ACT_STOP   3

static int action = ACT_NONE;

static void
slbsighan(int sig)
{
	switch (sig) {
	case SIGALRM:
		action = ACT_WAKEUP;
		break;

	case SIGHUP:
		action = ACT_RECONF;
		break;

	case SIGPIPE:
		action = ACT_NONE;
		break;
		
	default:
		action = ACT_STOP;
	}
}
		
int
slb_daemon()
{
	check_pidfile(pidfile);
	if (!foreground) {
		if (daemon(0, 0) == -1) {
			logmsg(LOG_CRIT,
				"cannot become a daemon: %s",
				strerror(errno));
			exit(EX_SOFTWARE);
		}
		close_fds(NULL);
		log_to_stderr = 0;
		logger_setup();
	}
	logmsg(LOG_INFO, _("%s starting"), program_version);

	create_pidfile(pidfile);
	if (x_argv[0][0] != '/') {
		logmsg(LOG_NOTICE,
		       "not started as an absolute pathname; "
		       "SIGHUP will not work");
	}
	
	set_signals(slbsighan, slb_sigtab, slb_sigcount);
	slb_open_output();
	action = ACT_WAKEUP;
	while (action == ACT_NONE || action == ACT_WAKEUP) {
		if (action == ACT_WAKEUP) {
			time_t delta;
			snmploop();
			slb_fmtout();
			delta = wakeup_interval - time(NULL) % wakeup_interval;
			debug(SLB_DEBCAT_MAIN, 2,
			      ("scheduled wake-up after %lu seconds",
			       (unsigned long) delta));
			alarm(delta);
		}
		pause();
	}
	slb_close_output();

	remove_pidfile(pidfile);

	if (action == ACT_RECONF && x_argv[0][0] == '/') {
		logmsg(LOG_INFO, _("%s restarting"), program_version);
		if (log_to_stderr) {
			fd_set fdset;
			FD_ZERO(&fdset);
			FD_SET(0, &fdset);
			FD_SET(1, &fdset);
			FD_SET(2, &fdset);
			close_fds(&fdset);
		} else
			close_fds(NULL);
		set_signals(SIG_DFL, slb_sigtab, slb_sigcount);
		execv(x_argv[0], x_argv);
	}
	logmsg(LOG_INFO, _("%s terminated"), program_version);
	exit(EX_OK);
}


static int
_next_val(void *item, void *data)
{
	struct slb_varinstance *inst = item;
	int *np = data;

	if (inst->vi_extra) {
		char *p;
		
		inst->vi_value = strtod(inst->vi_extra, &p);
		if (*p == ',')
			inst->vi_extra = p + 1;
		else if (*p) {
			logmsg(LOG_CRIT,
			       _("not a valid floating point number: %s"),
				inst->vi_extra);
			return EX_DATAERR;
		} else
			inst->vi_extra = NULL;
		*np = 1;
	}
	return 0;
}
	
static int
test_eval(int argc, char **argv)
{
	int i;
	struct grecs_symtab *syminst;
	struct slb_expression *expr = expression_lookupz(eval_option);
	struct slb_node_state *state = NULL;
	double result;
	int rc, next_loop;
	
	if (!expr) {
		logmsg(LOG_CRIT, "no such expression: %s", eval_option);
		return EX_USAGE;
	}
	syminst = grecs_symtab_create_default(sizeof(struct slb_varinstance));

	for (i = 0; i < argc; i++) {
		int install = 1;
		struct slb_varinstance *inst;
		char *p;
		char *arg = argv[i];
		size_t len = strcspn(arg, "=");

		inst = varinst_lookup(syminst, arg, len, &install);
		if (!install)
			logmsg(LOG_NOTICE,
			       _("redefinition of %s"), inst->vi_sym.name);

		if (arg[len] == '=') {
			inst->vi_value = strtod(arg + len + 1, &p);
			if (*p == ',')
				inst->vi_extra = p + 1;
			else if (*p) {
				logmsg(LOG_CRIT,
				       _("not a valid floating point number: %s"),
				       arg + len + 1);
				return EX_DATAERR;
			}
			inst->vi_flags = SLV_VIF_CONST | SLV_VIF_SET;
		} else
			inst->vi_flags = 0;
	}
	if (fixup_expression(expr, syminst))
		return EX_DATAERR;
	slb_loop_ts = 0;
	slb_loop_serial = 0;
	do {
		if (eval_expression(expr, &state, &result))
			continue;
		printf(eval_output_format, result);
	} while (slb_loop_serial++, slb_loop_ts += wakeup_interval,
		 next_loop = 0,
		 (rc = grecs_symtab_enumerate(syminst, _next_val,
					      &next_loop)) == 0 && next_loop);
	return rc;
}


int
main(int argc, char **argv)
{
	struct grecs_node *tree;
	
	x_argv = argv;
	
	set_program_name(argv[0]);
	slb_snmp_setup();
	init_snmp(program_name);
	config_init();
	parse_options(argc, argv);

	grecs_gram_trace(debug_level[SLB_DEBCAT_CFGRAM]);
	grecs_lex_trace(debug_level[SLB_DEBCAT_CFLEX]);
	
	if (preprocess_only)
		exit(grecs_preproc_run(conffile, grecs_preprocessor) ?
		      EX_CONFIG : 0);

	tree = grecs_parse(conffile);
	if (!tree)
		exit(EX_CONFIG);
	config_finish(tree);
	/* Prevent texttab from being freed by grecs_tree_free.
	   FIXME: A dirty kludge, needed to preserve file names
	   in locus structures. A proper solution would be to have
	   our own texttab for that purpose. */
	tree->v.texttab = NULL;
	grecs_tree_free(tree);

	if (lint_mode)
		exit(0);

	if (cron_option)
		standalone_mode = 0;
	    
	if (eval_option)
		exit(test_eval(argc - asgn_index, argv + asgn_index));
	if (test_option) {
		int rc;
		
		if (output_file_option)
			output_file = output_file_option;
		else
			slb_set_output_defaults();
		slb_open_output();
		rc = slb_test(argv[asgn_index]);
		slb_close_output();
		exit(rc);
	}
	
	if (dry_run_mode) {
		slb_set_output_defaults();
		pidfile = NULL;
		foreground = 1;
	}
	if (foreground_option)
		foreground = foreground_option;
	if (output_file_option)
		output_file = output_file_option;
	
	if (standalone_mode) {
		slb_daemon();
	} else {
		if (log_to_stderr == -1) {
			log_to_stderr = (!standalone_mode || foreground) &&
				        isatty(0);
			logger_setup();
		}
		slb_open_output();
		snmploop();
		slb_fmtout();
		slb_close_output();
	}
	return 0;
}

Return to:

Send suggestions and report system problems to the System administrator.