aboutsummaryrefslogtreecommitdiff
path: root/src/genrc.c
blob: 92b0fac78a1989238863a6ca1891a966dccd74ac (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
/* This file is part of genrc
Copyryght (C) 2018 Sergey Poznyakoff
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
*/
#include "genrc.h"
#include <sys/ioctl.h>

char *genrc_command;
char *genrc_program;
char *genrc_pid_from;
unsigned genrc_timeout = 5;
int genrc_no_reload;
int genrc_signal_stop = SIGTERM;
int genrc_signal_reload = SIGHUP;
GENRC_PID_CLOSURE *genrc_pid_closure;
char *genrc_create_pidfile;
int genrc_verbose;


enum {
	OPT_USAGE = 256,
	OPT_VERSION,
	OPT_SIGNAL_RELOAD,
	OPT_NO_RELOAD,
	OPT_SIGNAL_STOP,
	OPT_CREATE_PIDFILE
};

struct option longopts[] = {
	{ "help",           no_argument,       0, 'h' },
	{ "usage",          no_argument,       0, OPT_USAGE },
	{ "command",        required_argument, 0, 'c' },
	{ "program",        required_argument, 0, 'p' },
	{ "pid-from",       required_argument, 0, 'P' },
	{ "pidfile",        required_argument, 0, 'F' },
	{ "timeout",        required_argument, 0, 't' },
	{ "signal-reload",  required_argument, 0, OPT_SIGNAL_RELOAD },
	{ "no-reload",      no_argument,       0, OPT_NO_RELOAD },
	{ "signal-stop",    required_argument, 0, OPT_SIGNAL_STOP },
	{ "sentinel",       no_argument,       0, 'S' },
	{ "create-pidfile", required_argument, 0, OPT_CREATE_PIDFILE },
	{ "version",        no_argument,       0, OPT_VERSION },
	{ "verbose",        no_argument,       0, 'v' },
	{ NULL }
};
char shortopts[] = "c:hF:P:p:St:v";

struct sigdefn {
	char const *sig_name;
	int sig_no;
};

#define S(s) { #s, s }	
static struct sigdefn sigdefn[] = {
  S (SIGHUP),
  S (SIGINT),
  S (SIGQUIT),
  S (SIGILL),
  S (SIGTRAP),
  S (SIGABRT),
  S (SIGIOT),
  S (SIGBUS),
  S (SIGFPE),
  S (SIGKILL),
  S (SIGUSR1),
  S (SIGSEGV),
  S (SIGUSR2),
  S (SIGPIPE),
  S (SIGALRM),
  S (SIGTERM),
#ifdef SIGSTKFLT
  S (SIGSTKFLT),
#endif
  S (SIGCHLD),
  S (SIGCONT),
  S (SIGSTOP),
  S (SIGTSTP),
  S (SIGTTIN),
  S (SIGTTOU),
#ifdef SIGURG
  S (SIGURG),
#endif
#ifdef SIGXCPU
  S (SIGXCPU),
#endif
#ifdef SIGXFSZ
  S (SIGXFSZ),
#endif
#ifdef SIGVTALRM
  S (SIGVTALRM),
#endif
#ifdef SIGPROF
  S (SIGPROF),
#endif
#ifdef SIGWINCH
  S (SIGWINCH),
#endif
#ifdef SIGPOLL
  S (SIGPOLL),
#endif
#ifdef SIGIO
  S (SIGIO),
#endif
#ifdef SIGPWR
  S (SIGPWR),
#endif
#ifdef SIGSYS
  S (SIGSYS),
#endif
  {NULL}
};
#undef S

static int
is_numeric_str(char const *s)
{
	while (*s) {
		if (!isdigit(*s))
			return 0;
		s++;
	}
	return 1;
}

int
sig_name_to_str(char const *s)
{
	if (is_numeric_str(s)) {
		char *end;
		unsigned long n;
		errno = 0;
		n = strtoul(s, &end, 10);
		if (errno || *end || n > UINT_MAX)
			return -1;
		return n;
	} else {
		struct sigdefn *sd;

		for (sd = sigdefn; sd->sig_name; sd++) {
			if (s[0] == 's' || s[0] == 'S') {
				if (strcasecmp(sd->sig_name, s) == 0)
					return sd->sig_no;
			} else if (strcasecmp(sd->sig_name + 3, s) == 0)
				return sd->sig_no;
		}
	}
	return -1;
}

char const *help_msg[] = {
	"Usage: genrc [OPTIONS] COMMAND",
	"generic system initialization script helper\n",
	"COMMANDs are:\n",
	"  start                    start the program",
	"  stop                     stop the program",
	"  restart                  restart the running program",
	"  reload                   send a reload signal to the program",
	"  status                   display the program status",
	"",
	"OPTIONs are:\n",
	"  -h, --help               display this help list",
	"      --usage              display short usage information",
	"  -c, --command=COMMAND    command line to run",
	"  -p, --program=PROGRAM    name of the program to run",
	"  -P, --pid-from=SOURCE    where to look for PIDs of the running programs",
	"  -F, --pidfile=NAME       name of the PID file",
	"                           (same as --pid-from=FILE:NAME)",
	"  -t, --timeout=SECONDS    time to wait for the program to start up or",
	"                           terminate",
	"      --signal-reload=SIG  signal to send on reload (default: SIGHUP)",
	"                           setting to 0 is equivalent to --no-reload",
	"      --no-reload          makes reload equivalent to restart",
	"      --signal-stop=SIG    signal to send in order to terminate the program",
	"                           (default: SIGTERM)",
	"      --sentinel           PROGRAM runs in foreground; disconnect from the",
	"                           controlling terminal, run it and act as a sentinel",
	"      --version            display program version and exist",
	"",
	"Influential environment variables and corresponding options:",
	"",
	"   GENRC_COMMAND=COMMAND  --command=COMMAND",
	"   GENRC_PROGRAM=NAME     --program=NAME",
	"   GENRC_PID_FROM=SOURCE  --pid-from=SOURCE",
	"   GENRC_TIMEOUT=SECONDS  --timeout=SECONDS",
	"   GENRC_SENTINEL=1       --sentinel",
	"",
	"   At least one of COMMAND or PROGRAM must be given.",
	"   If PROGRAM is supplied, but COMMAND is not, COMMAND is set to PROGRAM",
	"   Otherwise, if COMMAND is set, but PROGRAM is not, PROGRAM is set to the",
	"   first word (in the shell sense) in COMMAND.",
	"",
	"PID sources:",
	"",
	"   FILE:<NAME>",
	"      Read PID from the file <NAME>",
	"",
	"   CONFIG:<LANG>:<FILENAME>:<FQRN>",
	"      Name of the PID file is stored in relation <FQRN> of the configuration",
	"      file <FILENAME>, written in language <LANG>",
	"",
	"   GREP:<FILE>:s/<RX>/<REPL>/[<FLAGS>][;...]",
	"      Grep for the first line in <FILE> that matches <RX>. If found, process",
	"      replace the matched portion according to <REPL> and <FLAGS>. Use",
	"      the resulting string as PID. More sed expressions can be supplied",
	"      separated with semicolons.",
	"",
	"   PROC[:[<EXE>][:<FLAGS>]]",
	"      Look for matching program in /proc/<PID>/*. If <EXE> is not supplied",
	"      or empty, program name from --program will be used. <FLAGS> are:",
	"        e  exact match",
	"        g  glob pattern match",
	"        x  extended POSIX regexp match (default)",
	"        p  PCRE match",
	"        i  case-insensitive match",
	"",
	"        c  match entire command line",
        "        r  match real executable name (instead of argv0)",
	"        a  signal all matching PIDs",
	"",
	"   PS:[:[<EXE>][:<FLAGS>]]",
	"      Look for matching program in the output of 'ps -ef'. <EXE> and <FLAGS>",
	"      as described above",
	"",
	NULL
};

void
help(void)
{
	int i;

	for (i = 0; help_msg[i]; i++)
		puts(help_msg[i]);
}

char const *usage_msg[] = {
	"genrc",
	"[-h]",
	"[-F PIDFILE]",
	"[-P SOURCE]",
	"[-c COMMAND]",
	"[-p PROGRAM]",
	"[-t SECONDS]",
	"[--command=COMMAND]",
	"[--help]",
	"[--no-reload]",
	"[--pid-from=SOURCE]",
	"[--pidfile=PIDFILE]",
	"[--program=PROGRAM]",
	"[--sentinel]",
	"[--signal-reload=SIG]",
	"[--signal-stop=SIG]",
	"[--timeout=SECONDS]",
	"[--usage]",
	"{",
	"start",
	"|",
	"stop",
	"|",
	"restart",
	"|",
	"reload",
	"|",
	"status",
	"}",
	NULL
};

static int
screen_width(void)
{
	struct winsize ws;
	ws.ws_col = ws.ws_row = 0;
	if ((ioctl(1, TIOCGWINSZ, (char *) &ws) < 0) || ws.ws_col == 0) {
		char *p = getenv("COLUMNS");
		if (p)
			ws.ws_col = atoi(p);
		if (ws.ws_col == 0)
			ws.ws_col = 80;
	}
	return ws.ws_col;
}

void
usage(void)
{
	int i, j, pos = 0;
	int width = screen_width();
	if (width > 4)
		width -= 4;
	for (i = j = 0; usage_msg[i]; i++) {
		int len = strlen(usage_msg[i]);
		if (j > 0)
			len++;
		if (pos + len > width) {
			putchar('\n');
			pos = strlen(usage_msg[0]) + 1;
			printf("%*s", pos, "");
			j = 0;
		} else if (j > 0)
			putchar(' ');
		j++;
		printf("%s", usage_msg[i]);
		pos += len;
	}
	putchar('\n');
}

static const char gplv3[] =
	"License GPLv3+: GNU GPL version 3 or later "
	"<http://gnu.org/licenses/gpl.html>\n"
	"This is free software: you are free to change and redistribute it.\n"
	"There is NO WARRANTY, to the extent permitted by law.\n\n";

void
version(void)
{
	printf("%s\n", PACKAGE_STRING);
	printf("Copyryght (C) 2018 Sergey Poznyakoff\n");
	printf("%s", gplv3);
}


typedef int (*GENRC_COMMAND)(void);

struct comtab {
	char const *com_name;
	GENRC_COMMAND com_fun;
};

static struct comtab comtab[] = {
	{ "start",   com_start },
	{ "stop",    com_stop },
	{ "restart", com_restart },
	{ "reload",  com_reload },
	{ "status",  com_status },
	{ NULL, NULL }
};

GENRC_COMMAND
find_command(char const *s)
{
	struct comtab *c;
	for (c = comtab; c->com_name; c++)
		if (strcmp(c->com_name, s) == 0)
			break;
	return c->com_fun;
}	

int
main(int argc, char **argv)
{
	int c;
	char *p;
	int no_reload = 0;
	GENRC_COMMAND command;
		
	setprogname(argv[0]);
	
	while ((c = getopt_long(argc, argv, shortopts, longopts, NULL))
	       != EOF) {
		switch (c) {
		case 'h':
			help();
			exit(0);
		case OPT_USAGE:
			usage();
			exit(0);
		case OPT_VERSION:
			version();
			exit(0);
		case 'c':
			setenv("GENRC_COMMAND", optarg, 1);
			break;
		case 'p':
			setenv("GENRC_PROGRAM", optarg, 1);
			break;
		case 'P':
			setenv("GENRC_PID_FROM", optarg, 1);
			break;
		case 'F':
			p = xmalloc(6 + strlen(optarg));
			strcat(strcpy(p, "FILE:"), optarg);
			setenv("GENRC_PID_FROM", p, 1);
			free(p);
			break;
		case OPT_CREATE_PIDFILE:
			setenv("GENRC_CREATE_PIDFILE", optarg, 1);
			break;
		case 't':
			setenv("GENRC_TIMEOUT", optarg, 1);
			break;
		case 'S':
			setenv("GENRC_SENTINEL", "1", 1);
			break;
		case OPT_NO_RELOAD:
			no_reload = 1;
			break;
		case OPT_SIGNAL_RELOAD:
			setenv("GENRC_SIGNAL_RELOAD", optarg, 1);
			break;
		case OPT_SIGNAL_STOP:
			setenv("GENRC_SIGNAL_STOP", optarg, 1);
			break;
		case 'v':
			genrc_verbose++;
			break;
		default:
			exit(1);
		}
	}

	if ((p = getenv("GENRC_COMMAND")) != NULL)
		genrc_command = p;
	if ((p = getenv("GENRC_PROGRAM")) != NULL)
		genrc_program = p;

	if (no_reload)
		genrc_no_reload = 1;
	else if ((p = getenv("GENRC_SIGNAL_RELOAD")) != NULL) {
		genrc_signal_reload = sig_name_to_str(p);
		if (genrc_signal_reload == -1)
			usage_error("%s: invalid signal number", p);
		else if (genrc_signal_reload == 0)
			genrc_no_reload = 1;
	}

	if ((p = getenv("GENRC_SIGNAL_STOP")) != NULL) {
		genrc_signal_stop = sig_name_to_str(p);
		if (genrc_signal_stop <= 0)
			usage_error("%s: invalid signal number", p);
	}

	if ((p = getenv("GENRC_TIMEOUT")) != NULL) {
		char *end;
		unsigned long n;
		errno = 0;
		n = strtoul(p, &end, 10);
		if (errno || *p || n > UINT_MAX)
			usage_error("%s: invalid timeout", p);
		if (n == 0)
			genrc_no_reload = 1;
		else
			genrc_timeout = n;
	}
		
	if (!genrc_command) {
		if (genrc_program) {
			genrc_command = xstrdup(genrc_program);
		} else {
			usage_error("either --command (GENRC_COMMAND) or --program (GENRC_PROGRAM) must be given");
		}
	} else if (!genrc_program) {
		struct wordsplit ws;
		ws.ws_error = genrc_error;
		if (wordsplit(genrc_command, &ws,
			      WRDSF_NOCMD|WRDSF_NOVAR|
			      WRDSF_ENOMEMABRT|WRDSF_SHOWERR|WRDSF_ERROR))
			exit(1);
		genrc_program = xstrdup(ws.ws_wordv[0]);
		wordsplit_free(&ws);
	}

	genrc_create_pidfile = getenv("GENRC_CREATE_PIDFILE");
	
	if ((p = getenv("GENRC_PID_FROM")) != NULL) {
		genrc_pid_closure = get_pid_closure(p);
	} else if (genrc_create_pidfile) {
		p = xmalloc(6 + strlen(genrc_create_pidfile));
		strcat(strcpy(p, "FILE:"), genrc_create_pidfile);
		genrc_pid_closure = get_pid_closure(p);
		free(p);
	} else {
		genrc_pid_closure = get_pid_closure(DEFAULT_PID_SOURCE);
	}

	argc -= optind;
	if (argc == 0)
		usage_error("missing command verb");
	if (argc > 1)
		usage_error("too many arguments");
	argv += optind;

	command = find_command(argv[0]);
	if (!command)
		usage_error("unrecognized command: %s", argv[0]);
	exit(command());
}

Return to:

Send suggestions and report system problems to the System administrator.