xref: /illumos-gate/usr/src/cmd/ctrun/ctrun.c (revision 7a1306a70fee0e017a445bde1dcfd1997f691cf4)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/types.h>
30 #include <sys/wait.h>
31 #include <sys/ctfs.h>
32 #include <sys/contract.h>
33 #include <sys/contract/process.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <unistd.h>
37 #include <fcntl.h>
38 #include <string.h>
39 #include <errno.h>
40 #include <signal.h>
41 #include <limits.h>
42 #include <libuutil.h>
43 #include <libcontract.h>
44 #include <libcontract_priv.h>
45 
46 #include <locale.h>
47 #include <langinfo.h>
48 
49 static int opt_verbose;
50 static int opt_Verbose;
51 
52 #define	OPT_NORMAL	0x1
53 #define	OPT_FATAL	0x2
54 
55 typedef struct optvect {
56 	const char	*opt_name;
57 	uint_t		opt_value;
58 	uint_t		opt_flags;
59 } optvect_t;
60 
61 static optvect_t option_params[] = {
62 	{ "noorphan", CT_PR_NOORPHAN },
63 	{ "pgrponly", CT_PR_PGRPONLY },
64 	{ "regent", CT_PR_REGENT },
65 	{ "inherit", CT_PR_INHERIT },
66 	{ NULL }
67 };
68 
69 static optvect_t option_events[] = {
70 	{ "core", CT_PR_EV_CORE, OPT_NORMAL | OPT_FATAL },
71 	{ "signal", CT_PR_EV_SIGNAL, OPT_NORMAL | OPT_FATAL },
72 	{ "hwerr", CT_PR_EV_HWERR, OPT_NORMAL | OPT_FATAL },
73 	{ "empty", CT_PR_EV_EMPTY, OPT_NORMAL },
74 	{ "fork", CT_PR_EV_FORK, OPT_NORMAL },
75 	{ "exit", CT_PR_EV_EXIT, OPT_NORMAL },
76 	{ NULL }
77 };
78 
79 typedef enum lifetime {
80 	LT_NONE,
81 	LT_CHILD,
82 	LT_CONTRACT
83 } lifetime_t;
84 
85 /*
86  * Exit code to use when the child exited abnormally (i.e. exited with
87  * a status we are unable to emulate).
88  */
89 #define	EXIT_BADCHILD	123
90 
91 #define	USAGESTR	\
92 	"Usage: %s [-i eventlist] [-f eventlist] [-l lifetime] \n" \
93 	"\t[-o optionlist] [-r count [-t]] [-v] command\n"
94 
95 /*
96  * usage
97  *
98  * Educate the user.
99  */
100 static void
101 usage(void)
102 {
103 	(void) fprintf(stderr, gettext(USAGESTR), uu_getpname());
104 	exit(UU_EXIT_USAGE);
105 }
106 
107 /*
108  * bit2str
109  *
110  * Convert a bit into its string representation.
111  */
112 static const char *
113 bit2str(optvect_t *options, uint_t bit)
114 {
115 	for (; options->opt_name; options++)
116 		if (options->opt_value == bit)
117 			return (options->opt_name);
118 	return (NULL);
119 }
120 
121 /*
122  * str2bit
123  *
124  * Convert a string into its bit representation.  If match is set, only
125  * look at those options with the match bit set in its opt_flags
126  * field.
127  */
128 static uint_t
129 str2bit(optvect_t *options, int match, const char *str, int len)
130 {
131 	for (; options->opt_name; options++) {
132 		if (match && (options->opt_flags & match) == 0)
133 			continue;
134 		if (strncmp(str, options->opt_name, len) == 0)
135 			return (options->opt_value);
136 	}
137 	return (0);
138 }
139 
140 /*
141  * opt2bits
142  *
143  * Given a set of textual options separated by commas or spaces,
144  * convert them to a set of bits.  Errors are fatal, except for empty
145  * options (which are ignored) and duplicate options (which are
146  * idempotent).
147  */
148 static void
149 opt2bits(optvect_t *options, int match, const char *str, uint_t *bits, char c)
150 {
151 	const char *ptr, *next = str;
152 	uint_t result = 0;
153 	uint_t bit;
154 	int none = 0;
155 
156 	while (*str) {
157 		int len;
158 
159 		ptr = strpbrk(str, ", ");
160 		if (ptr != NULL) {
161 			len = ptr - str;
162 			next = ptr + 1;
163 		} else {
164 			len = strlen(str);
165 			next = str + len;
166 		}
167 		if (len == 0) {
168 			uu_warn(gettext("empty option\n"));
169 			bit = 0;
170 		} else {
171 			bit = str2bit(options, match, str, len);
172 			if (bit == 0 && strncmp(str, "none", len) == 0) {
173 				none = 1;
174 				if (result)
175 					goto noneerr;
176 			} else if (bit == 0) {
177 				uu_warn(gettext("unrecognized option '%.*s'\n"),
178 				    len, str);
179 				uu_warn(gettext("error parsing '-%c' option\n"),
180 				    c);
181 				usage();
182 			} else if (none) {
183 				goto noneerr;
184 			}
185 			if (result & bit)
186 				uu_warn(gettext("option '%.*s' "
187 				    "specified twice\n"), len, str);
188 		}
189 		result |= bit;
190 		str = next;
191 	}
192 
193 	*bits = result;
194 	return;
195 
196 noneerr:
197 	uu_warn(gettext("option is incompatible with others: '%s'\n"), "none");
198 	usage();
199 }
200 
201 /*
202  * close_on_exec
203  *
204  * Given a fd, marks it close-on-exec.
205  */
206 static int
207 close_on_exec(int fd)
208 {
209 	int flags = fcntl(fd, F_GETFD, 0);
210 	if ((flags != -1) && (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) != -1))
211 		return (0);
212 	return (-1);
213 }
214 
215 /*
216  * v_printf
217  *
218  * Output routine for messages printed only when -v is specified.
219  */
220 /* PRINTFLIKE1 */
221 static void
222 v_printf(const char *format, ...)
223 {
224 	va_list va;
225 
226 	if (opt_verbose) {
227 		(void) printf("%s(%ld): ", uu_getpname(), getpid());
228 		va_start(va, format);
229 		(void) vprintf(format, va);
230 		va_end(va);
231 	}
232 }
233 
234 /*
235  * get_event
236  *
237  * Reads and acknowledges an event.  Returns the event type.
238  */
239 static uint_t
240 get_event(int fd, int ctfd, ctid_t ctid)
241 {
242 	ct_evthdl_t ev;
243 	uint_t result;
244 	ctevid_t evid;
245 
246 	for (;;) {
247 		int efd;
248 
249 		/*
250 		 * Normally we only need to look at critical messages.
251 		 * If we are displaying contract events, however, we
252 		 * have to read them all.
253 		 */
254 		errno = opt_verbose ? ct_event_read(fd, &ev) :
255 		    ct_event_read_critical(fd, &ev);
256 		if (errno != 0)
257 			uu_die(gettext("failed to listen to contract events"));
258 
259 		/*
260 		 * If requested, display the event.
261 		 */
262 		if (opt_verbose) {
263 			v_printf(gettext("event from contract %ld: "),
264 			    ct_event_get_ctid(ev));
265 			contract_event_dump(stdout, ev, opt_Verbose);
266 			if ((ct_event_get_flags(ev) & CTE_INFO) != 0) {
267 				ct_event_free(ev);
268 				continue;
269 			}
270 		}
271 
272 		/*
273 		 * We're done if this event is one of ours.
274 		 */
275 		evid = ct_event_get_evid(ev);
276 		if (ct_event_get_ctid(ev) == ctid)
277 			break;
278 
279 		/*
280 		 * ACK events from other contracts.
281 		 * This shouldn't happen, but it could.
282 		 */
283 		efd = contract_open(ct_event_get_ctid(ev), "process", "ctl",
284 		    O_WRONLY);
285 		if (efd != -1) {
286 			(void) ct_ctl_ack(efd, evid);
287 			(void) close(efd);
288 		}
289 		ct_event_free(ev);
290 	}
291 
292 	/*
293 	 * Note that if we want to use ctrun as a simple restarter, we
294 	 * need persistently keep track of fatal events so we can
295 	 * properly handle the death of the contract.  Rather than keep
296 	 * a file or somesuch lying around, it might make more sense to
297 	 * leave the significant fatal event sitting in the queue so
298 	 * that a restarted instance of ctrun can pick it up.  For now
299 	 * we'll just ACK all events.
300 	 */
301 	(void) ct_ctl_ack(ctfd, evid);
302 
303 	result = ct_event_get_type(ev);
304 	ct_event_free(ev);
305 
306 	return (result);
307 }
308 
309 /*
310  * abandon
311  *
312  * Given an fd for a contract's ctl file, abandon the contract and
313  * close the file.
314  */
315 static void
316 abandon(int ctfd)
317 {
318 	if (ct_ctl_abandon(ctfd) == -1)
319 		uu_die(gettext("failed to abandon contract %d"), ctfd);
320 
321 	(void) close(ctfd);
322 }
323 
324 static int chldstat;
325 static int chldexited;
326 
327 /*
328  * sigchld
329  *
330  * Our SIGCHLD handler.  Sets chldstat and chldexited so the
331  * interrupted code knows what happened.
332  */
333 /*ARGSUSED*/
334 static void
335 sigchld(int sig, struct siginfo *si, void *ucp)
336 {
337 	int err = errno;
338 
339 	if (si->si_code == CLD_EXITED)
340 		chldstat = si->si_status;
341 	else
342 		chldstat = EXIT_BADCHILD;
343 	chldexited = 1;
344 	while (waitpid(si->si_pid, NULL, 0) == -1 && errno == EINTR)
345 		;
346 	errno = err;
347 }
348 
349 /*
350  * dowait
351  *
352  * Waits for the specified child to exit.  Returns the exit code ctrun
353  * should return.
354  */
355 static int
356 dowait(int pid)
357 {
358 	pid_t wpid;
359 	int wstatus;
360 
361 	do
362 		wpid = waitpid(pid, &wstatus, 0);
363 	while (wpid == -1 && errno == EINTR);
364 
365 	if (wpid == -1)
366 		uu_die(gettext("wait failed"));
367 
368 	if (WIFEXITED(wstatus))
369 		return (WEXITSTATUS(wstatus));
370 	else
371 		return (EXIT_BADCHILD);
372 }
373 
374 int
375 main(int argc, char **argv)
376 {
377 	int	fd, efd;
378 	pid_t	pid;
379 	ctid_t	ctid = 0;
380 	int	ctfd;
381 	int	pipefds[2];
382 	struct sigaction osact;
383 
384 	int	s;
385 	ctid_t	opt_adopt = 0;
386 	int	opt_transfer = 0;
387 	int	opt_count = -1;
388 	uint_t	opt_info = CT_PR_EV_CORE;
389 	uint_t	opt_crit = 0;
390 	uint_t	eff_fatal, opt_fatal = CT_PR_EV_HWERR;
391 	uint_t	eff_param, opt_param = 0;
392 	lifetime_t opt_life = LT_CONTRACT;
393 
394 	(void) setlocale(LC_ALL, "");
395 	(void) textdomain(TEXT_DOMAIN);
396 	uu_alt_exit(UU_PROFILE_LAUNCHER);
397 
398 	(void) uu_setpname(argv[0]);
399 
400 	while ((s = getopt(argc, argv, "a:l:o:i:c:f:r:tvV")) != EOF) {
401 		switch (s) {
402 		case 'a':
403 			if (uu_strtoint(optarg, &opt_adopt, sizeof (opt_adopt),
404 			    0, 0, INT32_MAX) == -1) {
405 				uu_warn(gettext("invalid contract ID '%s'\n"),
406 				    optarg);
407 				usage();
408 			}
409 			break;
410 		case 'v':
411 			opt_verbose = 1;
412 			break;
413 		case 'V':
414 			opt_Verbose = 1;
415 			opt_verbose = 1;
416 			break;
417 		case 't':
418 			opt_transfer = 1;
419 			break;
420 		case 'r':
421 			if (uu_strtoint(optarg, &opt_count, sizeof (opt_adopt),
422 			    0, 0, INT32_MAX) == -1) {
423 				uu_warn(gettext("invalid count '%s'\n"),
424 				    optarg);
425 				usage();
426 			}
427 			break;
428 		case 'l':
429 			if (strcmp(optarg, "none") == 0) {
430 				opt_life = LT_NONE;
431 			} else if (strcmp(optarg, "child") == 0) {
432 				opt_life = LT_CHILD;
433 			} else if (strcmp(optarg, "contract") == 0) {
434 				opt_life = LT_CONTRACT;
435 			} else {
436 				uu_warn(gettext("invalid lifetime '%s'\n"),
437 				    optarg);
438 				usage();
439 			}
440 
441 			break;
442 		case 'o':
443 			opt2bits(option_params, 0, optarg, &opt_param,
444 			    optopt);
445 			break;
446 		case 'i':
447 			opt2bits(option_events, OPT_NORMAL, optarg, &opt_info,
448 			    optopt);
449 			break;
450 		case 'c':
451 			opt2bits(option_events, OPT_NORMAL, optarg, &opt_crit,
452 			    optopt);
453 			break;
454 		case 'f':
455 			opt2bits(option_events, OPT_FATAL, optarg, &opt_fatal,
456 			    optopt);
457 			break;
458 		default:
459 			usage();
460 		}
461 	}
462 	argc -= optind;
463 	argv += optind;
464 
465 	/*
466 	 * Basic argument sanity checks.
467 	 */
468 	if ((opt_life == LT_NONE) && (opt_param & CT_PR_NOORPHAN)) {
469 		uu_warn(gettext("cannot use option '%s' with lifetime '%s'\n"),
470 		    bit2str(option_params, CT_PR_NOORPHAN), "none");
471 		usage();
472 	}
473 
474 	if ((opt_life != LT_CONTRACT) && (opt_count >= 0)) {
475 		uu_warn(gettext("cannot restart with lifetime '%s'\n"),
476 		    opt_life == LT_NONE ? "none" : "child");
477 		usage();
478 	}
479 
480 	if ((opt_param & CT_PR_PGRPONLY) && (opt_count >= 0)) {
481 		uu_warn(gettext("cannot restart with option '%s'\n"),
482 		    bit2str(option_params, CT_PR_PGRPONLY));
483 		usage();
484 	}
485 
486 	if (opt_transfer && (opt_count == -1)) {
487 		uu_warn(gettext("cannot transfer when not restarting\n"));
488 		usage();
489 	}
490 
491 	if (argc <= 0)
492 		usage();
493 
494 	/*
495 	 * Create a process contract template and our process's process
496 	 * contract bundle endpoint.  Mark them close-on-exec so we
497 	 * don't have to worry about closing them in our child.
498 	 */
499 	fd = open64(CTFS_ROOT "/process/template", O_RDWR);
500 	if (fd == -1)
501 		uu_die(gettext("template open failed"));
502 
503 	efd = open64(CTFS_ROOT "/process/pbundle", O_RDONLY);
504 	if (efd == -1)
505 		uu_die(gettext("process bundle open failed"));
506 
507 	if (close_on_exec(fd) || close_on_exec(efd))
508 		uu_die(gettext("could not set FD_CLOEXEC"));
509 
510 	/*
511 	 * Set the process contract's terms based on our arguments.
512 	 */
513 	if (errno = ct_pr_tmpl_set_param(fd, opt_param))
514 		uu_die(gettext("set param failed"));
515 
516 	if (errno = ct_tmpl_set_informative(fd, opt_info))
517 		uu_die(gettext("set notify failed"));
518 
519 	if (errno = ct_pr_tmpl_set_fatal(fd, opt_fatal))
520 		uu_die(gettext("set fatal failed"));
521 
522 	if (opt_param & CT_PR_PGRPONLY)
523 		opt_crit = CT_PR_EV_EMPTY;
524 	else
525 		opt_crit |= opt_fatal | CT_PR_EV_EMPTY;
526 	if (errno = ct_tmpl_set_critical(fd, opt_crit))
527 		uu_die(gettext("set critical failed"));
528 
529 	/*
530 	 * Activate the template.
531 	 */
532 	if (errno = ct_tmpl_activate(fd))
533 		uu_die(gettext("template activate failed"));
534 
535 restart:
536 	if (opt_adopt) {
537 		/*
538 		 * Adopt a specific contract.
539 		 */
540 		ct_stathdl_t st;
541 		int stfd;
542 
543 		if ((ctfd = contract_open(opt_adopt, "process", "ctl",
544 		    O_WRONLY)) == -1)
545 			uu_die(gettext("could not open contract %ld"),
546 			    opt_adopt);
547 
548 		/*
549 		 * Read the contract's terms so that we interpret its
550 		 * events properly.
551 		 */
552 		if (((stfd = contract_open(opt_adopt, "process", "status",
553 		    O_RDONLY)) == -1) ||
554 		    (errno = ct_status_read(stfd, CTD_FIXED, &st)) ||
555 		    (errno = ct_pr_status_get_fatal(st, &eff_fatal)) ||
556 		    (errno = ct_pr_status_get_param(st, &eff_param)))
557 			uu_die(gettext("could not stat contract %ld"),
558 			    opt_adopt);
559 		ct_status_free(st);
560 		(void) close(stfd);
561 
562 		if (errno = ct_ctl_adopt(ctfd))
563 			uu_die(gettext("could not adopt contract %ld"),
564 			    opt_adopt);
565 
566 		ctid = opt_adopt;
567 		opt_adopt = 0;
568 		v_printf(gettext("adopted contract id %ld\n"), ctid);
569 	} else {
570 		/*
571 		 * Create a new process.
572 		 */
573 		if (opt_life == LT_CONTRACT) {
574 			struct sigaction sact;
575 
576 			/*
577 			 * Since we are going to be waiting for and
578 			 * reacting to contract events, install a
579 			 * signal handler so we capture the exit status
580 			 * of our child.
581 			 */
582 			chldstat = UU_EXIT_OK;
583 			chldexited = 0;
584 			sact.sa_sigaction = sigchld;
585 			sact.sa_flags = SA_SIGINFO | SA_RESTART |
586 			    SA_NOCLDSTOP;
587 			(void) sigemptyset(&sact.sa_mask);
588 			if (sigaction(SIGCHLD, &sact, &osact) == -1)
589 				uu_die(gettext("failed to install "
590 				    "sigchld handler"));
591 		} else if (opt_life == LT_NONE) {
592 			/*
593 			 * Though we aren't waiting for our child to
594 			 * exit, as a well-behaved command launcher we
595 			 * must wait for it to exec.  On success the
596 			 * pipe will simply close, and on failure the
597 			 * proper exit status will be sent.
598 			 */
599 			if (pipe(pipefds) == -1 ||
600 			    close_on_exec(pipefds[0]) == -1 ||
601 			    close_on_exec(pipefds[1]) == -1)
602 				uu_die(gettext("failed to create pipe"));
603 		}
604 
605 		if ((pid = fork()) == -1) {
606 			uu_die(gettext("fork failed"));
607 		} else if (pid == 0) {
608 			int result = execvp(argv[0], argv);
609 			if (opt_life == LT_NONE) {
610 				char a = 1;
611 				int err = errno;
612 
613 				(void) write(pipefds[1], &a, sizeof (a));
614 				errno = err;
615 			}
616 			if (result == -1)
617 				uu_xdie(errno == ENOENT ? 127 : 126,
618 				    gettext("exec failed"));
619 			uu_die(gettext("exec returned!\n"));
620 		}
621 
622 		/*
623 		 * Get the newly-created contract's id and ctl fd.
624 		 */
625 		if (errno = contract_latest(&ctid))
626 			uu_die(gettext("could not get new contract's id"));
627 		if ((ctfd = contract_open(ctid, "process", "ctl",
628 		    O_WRONLY)) == -1)
629 			uu_die(gettext("could not open contract"));
630 
631 		/*
632 		 * Clear the transfer parameter so that the contract
633 		 * will be freed sooner and admins won't get nervous.
634 		 */
635 		if (opt_transfer) {
636 			(void) ct_pr_tmpl_set_transfer(fd, 0);
637 			(void) ct_tmpl_activate(fd);
638 		}
639 
640 		v_printf(gettext("created contract id %ld\n"), ctid);
641 		eff_param = opt_param;
642 		eff_fatal = opt_fatal;
643 	}
644 
645 	if (opt_life == LT_CONTRACT) {
646 		uint_t event, errevent = 0;
647 
648 		/*
649 		 * Wait until the contract empties out.
650 		 */
651 		do {
652 			event = get_event(efd, ctfd, ctid);
653 			if (event & eff_fatal) {
654 				if ((eff_param & CT_PR_PGRPONLY) == 0)
655 					errevent = event;
656 				v_printf(gettext(
657 				    "fatal \"%s\" event from contract %ld\n"),
658 				    bit2str(option_events, event), ctid);
659 			}
660 		} while ((event & CT_PR_EV_EMPTY) == 0);
661 
662 		/*
663 		 * If we encountered a fatal error event, and we
664 		 * haven't expended our maximum loop count, restart.
665 		 */
666 		if ((errevent != 0) &&
667 		    ((opt_count == 0) || (opt_count-- > 1))) {
668 			v_printf(gettext("failure in contract %ld, "
669 			    "restarting command\n"), ctid);
670 			if (opt_transfer) {
671 				/*
672 				 * Add the failed contract to the new
673 				 * contract's terms so that its
674 				 * inherited subcontracts can be
675 				 * adopted by the new process.
676 				 */
677 				if (errno = ct_pr_tmpl_set_transfer(fd, ctid))
678 					uu_die(gettext("set transfer failed"));
679 				if (errno = ct_tmpl_activate(fd))
680 					uu_die(gettext(
681 					    "template activate failed"));
682 				(void) close(ctfd);
683 			} else {
684 				abandon(ctfd);
685 			}
686 			goto restart;
687 		}
688 
689 		/*
690 		 * At this point we are done with the contract; we
691 		 * don't want it to be inherited when we exit.
692 		 */
693 		abandon(ctfd);
694 
695 		/*
696 		 * In case there was a race between SIGCHLD delivery
697 		 * and contract event delivery, disable the signal
698 		 * handler and look for the child.
699 		 */
700 		(void) sigaction(SIGCHLD, &osact, NULL);
701 		if (chldexited == 0)
702 			chldstat = dowait(pid);
703 	} else if (opt_life == LT_NONE) {
704 		char a;
705 		int result;
706 
707 		chldstat = UU_EXIT_OK;
708 		(void) close(pipefds[1]);
709 		do {
710 			result = read(pipefds[0], &a, sizeof (a));
711 			if (result == -1 && errno != EINTR)
712 				uu_die(gettext("read failed"));
713 			if (result == 1)
714 				chldstat = dowait(pid);
715 		} while (result == -1);
716 	} else {
717 		chldstat = dowait(pid);
718 	}
719 
720 	return (chldstat);
721 }
722