xref: /illumos-gate/usr/src/cmd/svc/startd/method.c (revision 79033acb)
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 (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * method.c - method execution functions
30  *
31  * This file contains the routines needed to run a method:  a fork(2)-exec(2)
32  * invocation monitored using either the contract filesystem or waitpid(2).
33  * (Plain fork1(2) support is provided in fork.c.)
34  *
35  * Contract Transfer
36  *   When we restart a service, we want to transfer any contracts that the old
37  *   service's contract inherited.  This means that (a) we must not abandon the
38  *   old contract when the service dies and (b) we must write the id of the old
39  *   contract into the terms of the new contract.  There should be limits to
40  *   (a), though, since we don't want to keep the contract around forever.  To
41  *   this end we'll say that services in the offline state may have a contract
42  *   to be transfered and services in the disabled or maintenance states cannot.
43  *   This means that when a service transitions from online (or degraded) to
44  *   offline, the contract should be preserved, and when the service transitions
45  *   from offline to online (i.e., the start method), we'll transfer inherited
46  *   contracts.
47  */
48 
49 #include <sys/contract/process.h>
50 #include <sys/ctfs.h>
51 #include <sys/stat.h>
52 #include <sys/time.h>
53 #include <sys/types.h>
54 #include <sys/uio.h>
55 #include <sys/wait.h>
56 #include <alloca.h>
57 #include <assert.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <libcontract.h>
61 #include <libcontract_priv.h>
62 #include <libgen.h>
63 #include <librestart.h>
64 #include <libscf.h>
65 #include <limits.h>
66 #include <port.h>
67 #include <sac.h>
68 #include <signal.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <strings.h>
72 #include <unistd.h>
73 
74 #include "startd.h"
75 
76 #define	SBIN_SH		"/sbin/sh"
77 
78 /*
79  * Mapping from restart_on method-type to contract events.  Must correspond to
80  * enum method_restart_t.
81  */
82 static uint_t method_events[] = {
83 	/* METHOD_RESTART_ALL */
84 	CT_PR_EV_HWERR | CT_PR_EV_SIGNAL | CT_PR_EV_CORE | CT_PR_EV_EMPTY,
85 	/* METHOD_RESTART_EXTERNAL_FAULT */
86 	CT_PR_EV_HWERR | CT_PR_EV_SIGNAL,
87 	/* METHOD_RESTART_ANY_FAULT */
88 	CT_PR_EV_HWERR | CT_PR_EV_SIGNAL | CT_PR_EV_CORE
89 };
90 
91 /*
92  * method_record_start(restarter_inst_t *)
93  *   Record a service start for rate limiting.  Place the current time
94  *   in the circular array of instance starts.
95  */
96 static void
97 method_record_start(restarter_inst_t *inst)
98 {
99 	int index = inst->ri_start_index++ % RINST_START_TIMES;
100 
101 	inst->ri_start_time[index] = gethrtime();
102 }
103 
104 /*
105  * method_rate_critical(restarter_inst_t *)
106  *    Return true if the average start interval is less than the permitted
107  *    interval.  Implicit success if insufficient measurements for an
108  *    average exist.
109  */
110 static int
111 method_rate_critical(restarter_inst_t *inst)
112 {
113 	uint_t n = inst->ri_start_index;
114 	hrtime_t avg_ns = 0;
115 
116 	if (inst->ri_start_index < RINST_START_TIMES)
117 		return (0);
118 
119 	avg_ns =
120 	    (inst->ri_start_time[(n - 1) % RINST_START_TIMES] -
121 	    inst->ri_start_time[n % RINST_START_TIMES]) /
122 	    (RINST_START_TIMES - 1);
123 
124 	return (avg_ns < RINST_FAILURE_RATE_NS);
125 }
126 
127 /*
128  * int method_is_transient()
129  *   Determine if the method for the given instance is transient,
130  *   from a contract perspective. Return 1 if it is, and 0 if it isn't.
131  */
132 static int
133 method_is_transient(restarter_inst_t *inst, int type)
134 {
135 	if (instance_is_transient_style(inst) || type != METHOD_START)
136 		return (1);
137 	else
138 		return (0);
139 }
140 
141 /*
142  * void method_store_contract()
143  *   Store the newly created contract id into local structures and
144  *   the repository.  If the repository connection is broken it is rebound.
145  */
146 static void
147 method_store_contract(restarter_inst_t *inst, int type, ctid_t *cid)
148 {
149 	int r;
150 	boolean_t primary;
151 
152 	if (errno = contract_latest(cid))
153 		uu_die("%s: Couldn't get new contract's id", inst->ri_i.i_fmri);
154 
155 	primary = !method_is_transient(inst, type);
156 
157 	if (!primary) {
158 		if (inst->ri_i.i_transient_ctid != 0) {
159 			log_framework(LOG_INFO,
160 			    "%s: transient ctid expected to be 0 but "
161 			    "was set to %ld\n", inst->ri_i.i_fmri,
162 			    inst->ri_i.i_transient_ctid);
163 		}
164 
165 		inst->ri_i.i_transient_ctid = *cid;
166 	} else {
167 		if (inst->ri_i.i_primary_ctid != 0) {
168 			/*
169 			 * There was an old contract that we transferred.
170 			 * Remove it.
171 			 */
172 			method_remove_contract(inst, B_TRUE, B_FALSE);
173 		}
174 
175 		if (inst->ri_i.i_primary_ctid != 0) {
176 			log_framework(LOG_INFO,
177 			    "%s: primary ctid expected to be 0 but "
178 			    "was set to %ld\n", inst->ri_i.i_fmri,
179 			    inst->ri_i.i_primary_ctid);
180 		}
181 
182 		inst->ri_i.i_primary_ctid = *cid;
183 		inst->ri_i.i_primary_ctid_stopped = 0;
184 
185 		contract_hash_store(*cid, inst->ri_id);
186 	}
187 
188 again:
189 	if (inst->ri_mi_deleted)
190 		return;
191 
192 	r = restarter_store_contract(inst->ri_m_inst, *cid, primary ?
193 	    RESTARTER_CONTRACT_PRIMARY : RESTARTER_CONTRACT_TRANSIENT);
194 	switch (r) {
195 	case 0:
196 		break;
197 
198 	case ECANCELED:
199 		inst->ri_mi_deleted = B_TRUE;
200 		break;
201 
202 	case ECONNABORTED:
203 		libscf_handle_rebind(scf_instance_handle(inst->ri_m_inst));
204 		/* FALLTHROUGH */
205 
206 	case EBADF:
207 		libscf_reget_instance(inst);
208 		goto again;
209 
210 	case ENOMEM:
211 	case EPERM:
212 	case EACCES:
213 	case EROFS:
214 		uu_die("%s: Couldn't store contract id %ld",
215 		    inst->ri_i.i_fmri, *cid);
216 		/* NOTREACHED */
217 
218 	case EINVAL:
219 	default:
220 		bad_error("restarter_store_contract", r);
221 	}
222 }
223 
224 /*
225  * void method_remove_contract()
226  *   Remove any non-permanent contracts from internal structures and
227  *   the repository, then abandon them.
228  *   Returns
229  *     0 - success
230  *     ECANCELED - inst was deleted from the repository
231  *
232  *   If the repository connection was broken, it is rebound.
233  */
234 void
235 method_remove_contract(restarter_inst_t *inst, boolean_t primary,
236     boolean_t abandon)
237 {
238 	ctid_t * const ctidp = primary ? &inst->ri_i.i_primary_ctid :
239 	    &inst->ri_i.i_transient_ctid;
240 
241 	int r;
242 
243 	assert(*ctidp != 0);
244 
245 	log_framework(LOG_DEBUG, "Removing %s contract %lu for %s.\n",
246 	    primary ? "primary" : "transient", *ctidp, inst->ri_i.i_fmri);
247 
248 	if (abandon)
249 		contract_abandon(*ctidp);
250 
251 again:
252 	if (inst->ri_mi_deleted) {
253 		r = ECANCELED;
254 		goto out;
255 	}
256 
257 	r = restarter_remove_contract(inst->ri_m_inst, *ctidp, primary ?
258 	    RESTARTER_CONTRACT_PRIMARY : RESTARTER_CONTRACT_TRANSIENT);
259 	switch (r) {
260 	case 0:
261 		break;
262 
263 	case ECANCELED:
264 		inst->ri_mi_deleted = B_TRUE;
265 		break;
266 
267 	case ECONNABORTED:
268 		libscf_handle_rebind(scf_instance_handle(inst->ri_m_inst));
269 		/* FALLTHROUGH */
270 
271 	case EBADF:
272 		libscf_reget_instance(inst);
273 		goto again;
274 
275 	case ENOMEM:
276 	case EPERM:
277 	case EACCES:
278 	case EROFS:
279 		log_error(LOG_INFO, "%s: Couldn't remove contract id %ld: "
280 		    "%s.\n", inst->ri_i.i_fmri, *ctidp, strerror(r));
281 		break;
282 
283 	case EINVAL:
284 	default:
285 		bad_error("restarter_remove_contract", r);
286 	}
287 
288 out:
289 	if (primary)
290 		contract_hash_remove(*ctidp);
291 
292 	*ctidp = 0;
293 }
294 
295 /*
296  * int method_ready_contract(restarter_inst_t *, int, method_restart_t, int)
297  *
298  *   Activate a contract template for the type method of inst.  type,
299  *   restart_on, and cte_mask dictate the critical events term of the contract.
300  *   Returns
301  *     0 - success
302  *     ECANCELED - inst has been deleted from the repository
303  */
304 static int
305 method_ready_contract(restarter_inst_t *inst, int type,
306     method_restart_t restart_on, uint_t cte_mask)
307 {
308 	int tmpl, err, istrans, iswait, ret;
309 	uint_t cevents, fevents;
310 
311 	/*
312 	 * Correctly supporting wait-style services is tricky without
313 	 * rearchitecting startd to cope with multiple event sources
314 	 * simultaneously trying to stop an instance.  Until a better
315 	 * solution is implemented, we avoid this problem for
316 	 * wait-style services by making contract events fatal and
317 	 * letting the wait code alone handle stopping the service.
318 	 */
319 	iswait = instance_is_wait_style(inst);
320 	istrans = method_is_transient(inst, type);
321 
322 	tmpl = open64(CTFS_ROOT "/process/template", O_RDWR);
323 	if (tmpl == -1)
324 		uu_die("Could not create contract template");
325 
326 	/*
327 	 * We assume non-login processes are unlikely to create
328 	 * multiple process groups, and set CT_PR_PGRPONLY for all
329 	 * wait-style services' contracts.
330 	 */
331 	err = ct_pr_tmpl_set_param(tmpl, CT_PR_INHERIT | CT_PR_REGENT |
332 	    (iswait ? CT_PR_PGRPONLY : 0));
333 	assert(err == 0);
334 
335 	if (istrans) {
336 		cevents = 0;
337 		fevents = 0;
338 	} else {
339 		assert(restart_on >= 0);
340 		assert(restart_on <= METHOD_RESTART_ANY_FAULT);
341 		cevents = method_events[restart_on] & ~cte_mask;
342 		fevents = iswait ?
343 		    (method_events[restart_on] & ~cte_mask & CT_PR_ALLFATAL) :
344 		    0;
345 	}
346 
347 	err = ct_tmpl_set_critical(tmpl, cevents);
348 	assert(err == 0);
349 
350 	err = ct_tmpl_set_informative(tmpl, 0);
351 	assert(err == 0);
352 	err = ct_pr_tmpl_set_fatal(tmpl, fevents);
353 	assert(err == 0);
354 
355 	err = ct_tmpl_set_cookie(tmpl, istrans ?  METHOD_OTHER_COOKIE :
356 	    METHOD_START_COOKIE);
357 	assert(err == 0);
358 
359 	if (type == METHOD_START && inst->ri_i.i_primary_ctid != 0) {
360 		ret = ct_pr_tmpl_set_transfer(tmpl, inst->ri_i.i_primary_ctid);
361 		switch (ret) {
362 		case 0:
363 			break;
364 
365 		case ENOTEMPTY:
366 			/* No contracts for you! */
367 			method_remove_contract(inst, B_TRUE, B_TRUE);
368 			if (inst->ri_mi_deleted) {
369 				ret = ECANCELED;
370 				goto out;
371 			}
372 			break;
373 
374 		case EINVAL:
375 		case ESRCH:
376 		case EACCES:
377 		default:
378 			bad_error("ct_pr_tmpl_set_transfer", ret);
379 		}
380 	}
381 
382 	err = ct_tmpl_activate(tmpl);
383 	assert(err == 0);
384 
385 	ret = 0;
386 
387 out:
388 	err = close(tmpl);
389 	assert(err == 0);
390 
391 	return (ret);
392 }
393 
394 static const char *method_names[] = { "start", "stop", "refresh" };
395 
396 static void
397 exec_method(const restarter_inst_t *inst, int type, const char *method,
398     struct method_context *mcp, uint8_t need_session)
399 {
400 	char *cmd;
401 	const char *errf;
402 	char **nenv;
403 
404 	cmd = uu_msprintf("exec %s", method);
405 
406 	if (inst->ri_utmpx_prefix[0] != '\0' && inst->ri_utmpx_prefix != NULL)
407 		(void) utmpx_mark_init(getpid(), inst->ri_utmpx_prefix);
408 
409 	setlog(inst->ri_logstem);
410 	log_instance(inst, B_FALSE, "Executing %s method (\"%s\")",
411 	    method_names[type], method);
412 
413 	if (need_session)
414 		(void) setpgrp();
415 
416 	/* Set credentials. */
417 	errno = restarter_set_method_context(mcp, &errf);
418 	if (errno != 0) {
419 		(void) fputs("svc.startd could not set context for method: ",
420 		    stderr);
421 
422 		if (errno == -1) {
423 			if (strcmp(errf, "core_set_process_path") == 0) {
424 				(void) fputs("Could not set corefile path.\n",
425 				    stderr);
426 			} else if (strcmp(errf, "setproject") == 0) {
427 				(void) fprintf(stderr, "%s: a resource control "
428 				    "assignment failed\n", errf);
429 			} else if (strcmp(errf, "pool_set_binding") == 0) {
430 				(void) fprintf(stderr, "%s: a system error "
431 				    "occurred\n", errf);
432 			} else {
433 #ifndef NDEBUG
434 				uu_warn("%s:%d: Bad function name \"%s\" for "
435 				    "error %d from "
436 				    "restarter_set_method_context().\n",
437 				    __FILE__, __LINE__, errf, errno);
438 #endif
439 				abort();
440 			}
441 
442 			exit(1);
443 		}
444 
445 		if (errf != NULL && strcmp(errf, "pool_set_binding") == 0) {
446 			switch (errno) {
447 			case ENOENT:
448 				(void) fprintf(stderr, "%s: the pool could not "
449 				    "be found\n", errf);
450 				break;
451 
452 			case EBADF:
453 				(void) fprintf(stderr, "%s: the configuration "
454 				    "is invalid\n", errf);
455 				break;
456 
457 			case EINVAL:
458 				(void) fprintf(stderr, "%s: pool name \"%s\" "
459 				    "is invalid\n", errf, mcp->resource_pool);
460 				break;
461 
462 			default:
463 #ifndef NDEBUG
464 				uu_warn("%s:%d: Bad error %d for function %s "
465 				    "in restarter_set_method_context().\n",
466 				    __FILE__, __LINE__, errno, errf);
467 #endif
468 				abort();
469 			}
470 
471 			exit(SMF_EXIT_ERR_CONFIG);
472 		}
473 
474 		if (errf != NULL) {
475 			perror(errf);
476 
477 			switch (errno) {
478 			case EINVAL:
479 			case EPERM:
480 			case ENOENT:
481 			case ENAMETOOLONG:
482 			case ERANGE:
483 			case ESRCH:
484 				exit(SMF_EXIT_ERR_CONFIG);
485 				/* NOTREACHED */
486 
487 			default:
488 				exit(1);
489 			}
490 		}
491 
492 		switch (errno) {
493 		case ENOMEM:
494 			(void) fputs("Out of memory.\n", stderr);
495 			exit(1);
496 			/* NOTREACHED */
497 
498 		case ENOENT:
499 			(void) fputs("Missing passwd entry for user.\n",
500 			    stderr);
501 			exit(SMF_EXIT_ERR_CONFIG);
502 			/* NOTREACHED */
503 
504 		default:
505 #ifndef NDEBUG
506 			uu_warn("%s:%d: Bad miscellaneous error %d from "
507 			    "restarter_set_method_context().\n", __FILE__,
508 			    __LINE__, errno);
509 #endif
510 			abort();
511 		}
512 	}
513 
514 	nenv = set_smf_env(mcp->env, mcp->env_sz, NULL, inst, method);
515 
516 	log_preexec();
517 
518 	(void) execle(SBIN_SH, SBIN_SH, "-c", cmd, NULL, nenv);
519 
520 	exit(10);
521 }
522 
523 static void
524 write_status(restarter_inst_t *inst, const char *mname, int stat)
525 {
526 	int r;
527 
528 again:
529 	if (inst->ri_mi_deleted)
530 		return;
531 
532 	r = libscf_write_method_status(inst->ri_m_inst, mname, stat);
533 	switch (r) {
534 	case 0:
535 		break;
536 
537 	case ECONNABORTED:
538 		libscf_reget_instance(inst);
539 		goto again;
540 
541 	case ECANCELED:
542 		inst->ri_mi_deleted = 1;
543 		break;
544 
545 	case EPERM:
546 	case EACCES:
547 	case EROFS:
548 		log_framework(LOG_INFO, "Could not write exit status "
549 		    "for %s method of %s: %s.\n", mname,
550 		    inst->ri_i.i_fmri, strerror(r));
551 		break;
552 
553 	case ENAMETOOLONG:
554 	default:
555 		bad_error("libscf_write_method_status", r);
556 	}
557 }
558 
559 /*
560  * int method_run()
561  *   Execute the type method of instp.  If it requires a fork(), wait for it
562  *   to return and return its exit code in *exit_code.  Otherwise set
563  *   *exit_code to 0 if the method succeeds & -1 if it fails.  If the
564  *   repository connection is broken, it is rebound, but inst may not be
565  *   reset.
566  *   Returns
567  *     0 - success
568  *     EINVAL - A correct method or method context couldn't be retrieved.
569  *     EIO - Contract kill failed.
570  *     EFAULT - Method couldn't be executed successfully.
571  *     ELOOP - Retry threshold exceeded.
572  *     ECANCELED - inst was deleted from the repository before method was run
573  *     ERANGE - Timeout retry threshold exceeded.
574  *     EAGAIN - Failed due to external cause, retry.
575  */
576 int
577 method_run(restarter_inst_t **instp, int type, int *exit_code)
578 {
579 	char *method;
580 	int ret_status;
581 	pid_t pid;
582 	method_restart_t restart_on;
583 	uint_t cte_mask;
584 	uint8_t need_session;
585 	scf_handle_t *h;
586 	scf_snapshot_t *snap;
587 	const char *mname;
588 	const char *errstr;
589 	struct method_context *mcp;
590 	int result = 0, timeout_fired = 0;
591 	int sig, r;
592 	boolean_t transient;
593 	uint64_t timeout;
594 	uint8_t timeout_retry;
595 	ctid_t ctid;
596 	int ctfd = -1;
597 	ct_evthdl_t ctev;
598 	uint_t evtype;
599 	restarter_inst_t *inst = *instp;
600 	int id = inst->ri_id;
601 	int forkerr;
602 
603 	assert(PTHREAD_MUTEX_HELD(&inst->ri_lock));
604 	assert(instance_in_transition(inst));
605 
606 	if (inst->ri_mi_deleted)
607 		return (ECANCELED);
608 
609 	*exit_code = 0;
610 
611 	assert(0 <= type && type <= 2);
612 	mname = method_names[type];
613 
614 	if (type == METHOD_START)
615 		inst->ri_pre_online_hook();
616 
617 	h = scf_instance_handle(inst->ri_m_inst);
618 
619 	snap = scf_snapshot_create(h);
620 	if (snap == NULL ||
621 	    scf_instance_get_snapshot(inst->ri_m_inst, "running", snap) != 0) {
622 		log_framework(LOG_DEBUG,
623 		    "Could not get running snapshot for %s.  "
624 		    "Using editing version to run method %s.\n",
625 		    inst->ri_i.i_fmri, mname);
626 		scf_snapshot_destroy(snap);
627 		snap = NULL;
628 	}
629 
630 	/*
631 	 * After this point, we may be logging to the instance log.
632 	 * Make sure we've noted where that log is as a property of
633 	 * the instance.
634 	 */
635 	r = libscf_note_method_log(inst->ri_m_inst, st->st_log_prefix,
636 	    inst->ri_logstem);
637 	if (r != 0) {
638 		log_framework(LOG_WARNING,
639 		    "%s: couldn't note log location: %s\n",
640 		    inst->ri_i.i_fmri, strerror(r));
641 	}
642 
643 	if ((method = libscf_get_method(h, type, inst, snap, &restart_on,
644 	    &cte_mask, &need_session, &timeout, &timeout_retry)) == NULL) {
645 		if (errno == LIBSCF_PGROUP_ABSENT)  {
646 			log_framework(LOG_DEBUG,
647 			    "%s: instance has no method property group '%s'.\n",
648 			    inst->ri_i.i_fmri, mname);
649 			if (type == METHOD_REFRESH)
650 				log_instance(inst, B_TRUE, "No '%s' method "
651 				    "defined.  Treating as :true.", mname);
652 			else
653 				log_instance(inst, B_TRUE, "Method property "
654 				    "group '%s' is not present.", mname);
655 			scf_snapshot_destroy(snap);
656 			return (0);
657 		} else if (errno == LIBSCF_PROPERTY_ABSENT)  {
658 			log_framework(LOG_DEBUG,
659 			    "%s: instance has no '%s/exec' method property.\n",
660 			    inst->ri_i.i_fmri, mname);
661 			log_instance(inst, B_TRUE, "Method property '%s/exec "
662 			    "is not present.", mname);
663 			scf_snapshot_destroy(snap);
664 			return (0);
665 		} else {
666 			log_error(LOG_WARNING,
667 			    "%s: instance libscf_get_method failed\n",
668 			    inst->ri_i.i_fmri);
669 			scf_snapshot_destroy(snap);
670 			return (EINVAL);
671 		}
672 	}
673 
674 	/* open service contract if stopping a non-transient service */
675 	if (type == METHOD_STOP && (!instance_is_transient_style(inst))) {
676 		if (inst->ri_i.i_primary_ctid == 0) {
677 			/* service is not running, nothing to stop */
678 			log_framework(LOG_DEBUG, "%s: instance has no primary "
679 			    "contract, no service to stop.\n",
680 			    inst->ri_i.i_fmri);
681 			scf_snapshot_destroy(snap);
682 			return (0);
683 		}
684 		if ((ctfd = contract_open(inst->ri_i.i_primary_ctid, "process",
685 		    "events", O_RDONLY)) < 0) {
686 			result = EFAULT;
687 			log_instance(inst, B_TRUE, "Could not open service "
688 			    "contract %ld.  Stop method not run.\n",
689 			    inst->ri_i.i_primary_ctid);
690 			goto out;
691 		}
692 	}
693 
694 	if (restarter_is_null_method(method)) {
695 		log_framework(LOG_DEBUG, "%s: null method succeeds\n",
696 		    inst->ri_i.i_fmri);
697 
698 		log_instance(inst, B_TRUE, "Executing %s method (null)", mname);
699 
700 		if (type == METHOD_START)
701 			write_status(inst, mname, 0);
702 		goto out;
703 	}
704 
705 	sig = restarter_is_kill_method(method);
706 	if (sig >= 0) {
707 
708 		if (inst->ri_i.i_primary_ctid == 0) {
709 			log_error(LOG_ERR, "%s: :kill with no contract\n",
710 			    inst->ri_i.i_fmri);
711 			result = EINVAL;
712 			goto out;
713 		}
714 
715 		log_framework(LOG_DEBUG,
716 		    "%s: :killing contract with signal %d\n",
717 		    inst->ri_i.i_fmri, sig);
718 
719 		log_instance(inst, B_TRUE, "Executing %s method (:kill)",
720 		    mname);
721 
722 		if (contract_kill(inst->ri_i.i_primary_ctid, sig,
723 		    inst->ri_i.i_fmri) != 0) {
724 			result = EIO;
725 			goto out;
726 		} else
727 			goto assured_kill;
728 	}
729 
730 	log_framework(LOG_DEBUG, "%s: forking to run method %s\n",
731 	    inst->ri_i.i_fmri, method);
732 
733 	errstr = restarter_get_method_context(RESTARTER_METHOD_CONTEXT_VERSION,
734 	    inst->ri_m_inst, snap, mname, method, &mcp);
735 
736 	if (errstr != NULL) {
737 		log_error(LOG_WARNING, "%s: %s\n", inst->ri_i.i_fmri, errstr);
738 		result = EINVAL;
739 		goto out;
740 	}
741 
742 	r = method_ready_contract(inst, type, restart_on, cte_mask);
743 	if (r != 0) {
744 		assert(r == ECANCELED);
745 		assert(inst->ri_mi_deleted);
746 		restarter_free_method_context(mcp);
747 		result = ECANCELED;
748 		goto out;
749 	}
750 
751 	/*
752 	 * Validate safety of method contexts, to save children work.
753 	 */
754 	if (!restarter_rm_libs_loadable())
755 		log_framework(LOG_DEBUG, "%s: method contexts limited "
756 		    "to root-accessible libraries\n", inst->ri_i.i_fmri);
757 
758 	/*
759 	 * If the service is restarting too quickly, send it to
760 	 * maintenance.
761 	 */
762 	if (type == METHOD_START) {
763 		method_record_start(inst);
764 		if (method_rate_critical(inst)) {
765 			log_instance(inst, B_TRUE, "Restarting too quickly, "
766 			    "changing state to maintenance");
767 			result = ELOOP;
768 			goto out;
769 		}
770 	}
771 
772 	pid = startd_fork1(&forkerr);
773 	if (pid == 0)
774 		exec_method(inst, type, method, mcp, need_session);
775 
776 	if (pid == -1) {
777 		if (forkerr == EAGAIN)
778 			result = EAGAIN;
779 		else
780 			result = EFAULT;
781 
782 		log_error(LOG_WARNING,
783 		    "%s: Couldn't fork to execute method %s: %s\n",
784 		    inst->ri_i.i_fmri, method, strerror(forkerr));
785 
786 		goto out;
787 	}
788 
789 	restarter_free_method_context(mcp);
790 
791 	/*
792 	 * Get the contract id, decide whether it is primary or transient, and
793 	 * stash it in inst & the repository.
794 	 */
795 	method_store_contract(inst, type, &ctid);
796 
797 	/*
798 	 * Similarly for the start method PID.
799 	 */
800 	if (type == METHOD_START && !inst->ri_mi_deleted)
801 		(void) libscf_write_start_pid(inst->ri_m_inst, pid);
802 
803 	if (instance_is_wait_style(inst) && type == METHOD_START) {
804 		/* Wait style instances don't get timeouts on start methods. */
805 		if (wait_register(pid, inst->ri_i.i_fmri, 1, 0)) {
806 			log_error(LOG_WARNING,
807 			    "%s: couldn't register %ld for wait\n",
808 			    inst->ri_i.i_fmri, pid);
809 			result = EFAULT;
810 			goto contract_out;
811 		}
812 		write_status(inst, mname, 0);
813 
814 	} else {
815 		int r, err;
816 		time_t start_time;
817 		time_t end_time;
818 
819 		/*
820 		 * Because on upgrade/live-upgrade we may have no chance
821 		 * to override faulty timeout values on the way to
822 		 * manifest import, all services on the path to manifest
823 		 * import are treated the same as INFINITE timeout services.
824 		 */
825 
826 		start_time = time(NULL);
827 		if (timeout != METHOD_TIMEOUT_INFINITE && !is_timeout_ovr(inst))
828 			timeout_insert(inst, ctid, timeout);
829 		else
830 			timeout = METHOD_TIMEOUT_INFINITE;
831 
832 		/* Unlock the instance while waiting for the method. */
833 		MUTEX_UNLOCK(&inst->ri_lock);
834 
835 		do
836 			r = waitpid(pid, &ret_status, NULL);
837 		while (r == -1 && errno == EINTR);
838 		if (r == -1)
839 			err = errno;
840 
841 		/* Re-grab the lock. */
842 		inst = inst_lookup_by_id(id);
843 
844 		/*
845 		 * inst can't be removed, as the removal thread waits
846 		 * for completion of this one.
847 		 */
848 		assert(inst != NULL);
849 		*instp = inst;
850 
851 		if (inst->ri_timeout != NULL && inst->ri_timeout->te_fired)
852 			timeout_fired = 1;
853 
854 		timeout_remove(inst, ctid);
855 
856 		log_framework(LOG_DEBUG,
857 		    "%s method for %s exited with status %d.\n", mname,
858 		    inst->ri_i.i_fmri, WEXITSTATUS(ret_status));
859 
860 		if (r == -1) {
861 			log_error(LOG_WARNING,
862 			    "Couldn't waitpid() for %s method of %s (%s).\n",
863 			    mname, inst->ri_i.i_fmri, strerror(err));
864 			result = EFAULT;
865 			goto contract_out;
866 		}
867 
868 		if (type == METHOD_START)
869 			write_status(inst, mname, ret_status);
870 
871 		/* return ERANGE if this service doesn't retry on timeout */
872 		if (timeout_fired == 1 && timeout_retry == 0) {
873 			result = ERANGE;
874 			goto contract_out;
875 		}
876 
877 		if (!WIFEXITED(ret_status)) {
878 			/*
879 			 * If method didn't exit itself (it was killed by an
880 			 * external entity, etc.), consider the entire
881 			 * method_run as failed.
882 			 */
883 			if (WIFSIGNALED(ret_status)) {
884 				char buf[SIG2STR_MAX];
885 				(void) sig2str(WTERMSIG(ret_status), buf);
886 
887 				log_error(LOG_WARNING, "%s: Method \"%s\" "
888 				    "failed due to signal %s.\n",
889 				    inst->ri_i.i_fmri, method, buf);
890 				log_instance(inst, B_TRUE, "Method \"%s\" "
891 				    "failed due to signal %s", mname, buf);
892 			} else {
893 				log_error(LOG_WARNING, "%s: Method \"%s\" "
894 				    "failed with exit status %d.\n",
895 				    inst->ri_i.i_fmri, method,
896 				    WEXITSTATUS(ret_status));
897 				log_instance(inst, B_TRUE, "Method \"%s\" "
898 				    "failed with exit status %d", mname,
899 				    WEXITSTATUS(ret_status));
900 			}
901 			result = EAGAIN;
902 			goto contract_out;
903 		}
904 
905 		*exit_code = WEXITSTATUS(ret_status);
906 		if (*exit_code != 0) {
907 			log_error(LOG_WARNING,
908 			    "%s: Method \"%s\" failed with exit status %d.\n",
909 			    inst->ri_i.i_fmri, method, WEXITSTATUS(ret_status));
910 		}
911 
912 		log_instance(inst, B_TRUE, "Method \"%s\" exited with status "
913 		    "%d", mname, *exit_code);
914 
915 		if (*exit_code != 0)
916 			goto contract_out;
917 
918 		end_time = time(NULL);
919 
920 		/* Give service contract remaining seconds to empty */
921 		if (timeout != METHOD_TIMEOUT_INFINITE)
922 			timeout -= (end_time - start_time);
923 	}
924 
925 assured_kill:
926 	/*
927 	 * For stop methods, assure that the service contract has emptied
928 	 * before returning.
929 	 */
930 	if (type == METHOD_STOP && (!instance_is_transient_style(inst)) &&
931 	    !(contract_is_empty(inst->ri_i.i_primary_ctid))) {
932 
933 		if (timeout != METHOD_TIMEOUT_INFINITE)
934 			timeout_insert(inst, inst->ri_i.i_primary_ctid,
935 			    timeout);
936 
937 		for (;;) {
938 			do {
939 				r = ct_event_read_critical(ctfd, &ctev);
940 			} while (r == EINTR);
941 			if (r != 0)
942 				break;
943 
944 			evtype = ct_event_get_type(ctev);
945 			ct_event_free(ctev);
946 			if (evtype == CT_PR_EV_EMPTY)
947 				break;
948 		}
949 		if (r) {
950 			result = EFAULT;
951 			log_instance(inst, B_TRUE, "Error reading service "
952 			    "contract %ld.\n", inst->ri_i.i_primary_ctid);
953 		}
954 
955 		if (timeout != METHOD_TIMEOUT_INFINITE)
956 			if (inst->ri_timeout->te_fired)
957 				result = EFAULT;
958 
959 		timeout_remove(inst, inst->ri_i.i_primary_ctid);
960 	}
961 
962 contract_out:
963 	/* Abandon contracts for transient methods & methods that fail. */
964 	transient = method_is_transient(inst, type);
965 	if ((transient || *exit_code != 0 || result != 0) &&
966 	    (restarter_is_kill_method(method) < 0))
967 		method_remove_contract(inst, !transient, B_TRUE);
968 
969 out:
970 	if (ctfd >= 0)
971 		(void) close(ctfd);
972 	scf_snapshot_destroy(snap);
973 	free(method);
974 	return (result);
975 }
976 
977 /*
978  * The method thread executes a service method to effect a state transition.
979  * The next_state of info->sf_id should be non-_NONE on entrance, and it will
980  * be _NONE on exit (state will either be what next_state was (on success), or
981  * it will be _MAINT (on error)).
982  *
983  * There are six classes of methods to consider: start & other (stop, refresh)
984  * for each of "normal" services, wait services, and transient services.  For
985  * each, the method must be fetched from the repository & executed.  fork()ed
986  * methods must be waited on, except for the start method of wait services
987  * (which must be registered with the wait subsystem via wait_register()).  If
988  * the method succeeded (returned 0), then for start methods its contract
989  * should be recorded as the primary contract for the service.  For other
990  * methods, it should be abandoned.  If the method fails, then depending on
991  * the failure, either the method should be reexecuted or the service should
992  * be put into maintenance.  Either way the contract should be abandoned.
993  */
994 void *
995 method_thread(void *arg)
996 {
997 	fork_info_t *info = arg;
998 	restarter_inst_t *inst;
999 	scf_handle_t	*local_handle;
1000 	scf_instance_t	*s_inst = NULL;
1001 	int r, exit_code;
1002 	boolean_t retryable;
1003 	const char *aux;
1004 
1005 	assert(0 <= info->sf_method_type && info->sf_method_type <= 2);
1006 
1007 	/* Get (and lock) the restarter_inst_t. */
1008 	inst = inst_lookup_by_id(info->sf_id);
1009 
1010 	assert(inst->ri_method_thread != 0);
1011 	assert(instance_in_transition(inst) == 1);
1012 
1013 	/*
1014 	 * We cannot leave this function with inst in transition, because
1015 	 * protocol.c withholds messages for inst otherwise.
1016 	 */
1017 
1018 	log_framework(LOG_DEBUG, "method_thread() running %s method for %s.\n",
1019 	    method_names[info->sf_method_type], inst->ri_i.i_fmri);
1020 
1021 	local_handle = libscf_handle_create_bound_loop();
1022 
1023 rebind_retry:
1024 	/* get scf_instance_t */
1025 	switch (r = libscf_fmri_get_instance(local_handle, inst->ri_i.i_fmri,
1026 	    &s_inst)) {
1027 	case 0:
1028 		break;
1029 
1030 	case ECONNABORTED:
1031 		libscf_handle_rebind(local_handle);
1032 		goto rebind_retry;
1033 
1034 	case ENOENT:
1035 		/*
1036 		 * It's not there, but we need to call this so protocol.c
1037 		 * doesn't think it's in transition anymore.
1038 		 */
1039 		(void) restarter_instance_update_states(local_handle, inst,
1040 		    inst->ri_i.i_state, RESTARTER_STATE_NONE, RERR_NONE,
1041 		    NULL);
1042 		goto out;
1043 
1044 	case EINVAL:
1045 	case ENOTSUP:
1046 	default:
1047 		bad_error("libscf_fmri_get_instance", r);
1048 	}
1049 
1050 	inst->ri_m_inst = s_inst;
1051 	inst->ri_mi_deleted = B_FALSE;
1052 
1053 retry:
1054 	if (info->sf_method_type == METHOD_START)
1055 		log_transition(inst, START_REQUESTED);
1056 
1057 	r = method_run(&inst, info->sf_method_type, &exit_code);
1058 
1059 	if (r == 0 && exit_code == 0) {
1060 		/* Success! */
1061 		assert(inst->ri_i.i_next_state != RESTARTER_STATE_NONE);
1062 
1063 		/*
1064 		 * When a stop method succeeds, remove the primary contract of
1065 		 * the service, unless we're going to offline, in which case
1066 		 * retain the contract so we can transfer inherited contracts to
1067 		 * the replacement service.
1068 		 */
1069 
1070 		if (info->sf_method_type == METHOD_STOP &&
1071 		    inst->ri_i.i_primary_ctid != 0) {
1072 			if (inst->ri_i.i_next_state == RESTARTER_STATE_OFFLINE)
1073 				inst->ri_i.i_primary_ctid_stopped = 1;
1074 			else
1075 				method_remove_contract(inst, B_TRUE, B_TRUE);
1076 		}
1077 		/*
1078 		 * We don't care whether the handle was rebound because this is
1079 		 * the last thing we do with it.
1080 		 */
1081 		(void) restarter_instance_update_states(local_handle, inst,
1082 		    inst->ri_i.i_next_state, RESTARTER_STATE_NONE,
1083 		    info->sf_event_type, NULL);
1084 
1085 		(void) update_fault_count(inst, FAULT_COUNT_RESET);
1086 
1087 		goto out;
1088 	}
1089 
1090 	/* Failure.  Retry or go to maintenance. */
1091 
1092 	if (r != 0 && r != EAGAIN) {
1093 		retryable = B_FALSE;
1094 	} else {
1095 		switch (exit_code) {
1096 		case SMF_EXIT_ERR_CONFIG:
1097 		case SMF_EXIT_ERR_NOSMF:
1098 		case SMF_EXIT_ERR_PERM:
1099 		case SMF_EXIT_ERR_FATAL:
1100 			retryable = B_FALSE;
1101 			break;
1102 
1103 		default:
1104 			retryable = B_TRUE;
1105 		}
1106 	}
1107 
1108 	if (retryable && update_fault_count(inst, FAULT_COUNT_INCR) != 1)
1109 		goto retry;
1110 
1111 	/* maintenance */
1112 	if (r == ELOOP)
1113 		log_transition(inst, START_FAILED_REPEATEDLY);
1114 	else if (r == ERANGE)
1115 		log_transition(inst, START_FAILED_TIMEOUT_FATAL);
1116 	else if (exit_code == SMF_EXIT_ERR_CONFIG)
1117 		log_transition(inst, START_FAILED_CONFIGURATION);
1118 	else if (exit_code == SMF_EXIT_ERR_FATAL)
1119 		log_transition(inst, START_FAILED_FATAL);
1120 	else
1121 		log_transition(inst, START_FAILED_OTHER);
1122 
1123 	if (r == ELOOP)
1124 		aux = "restarting_too_quickly";
1125 	else if (retryable)
1126 		aux = "fault_threshold_reached";
1127 	else
1128 		aux = "method_failed";
1129 
1130 	(void) restarter_instance_update_states(local_handle, inst,
1131 	    RESTARTER_STATE_MAINT, RESTARTER_STATE_NONE, RERR_FAULT,
1132 	    (char *)aux);
1133 
1134 	if (!method_is_transient(inst, info->sf_method_type) &&
1135 	    inst->ri_i.i_primary_ctid != 0)
1136 		method_remove_contract(inst, B_TRUE, B_TRUE);
1137 
1138 out:
1139 	inst->ri_method_thread = 0;
1140 	MUTEX_UNLOCK(&inst->ri_lock);
1141 	(void) pthread_cond_broadcast(&inst->ri_method_cv);
1142 
1143 	scf_instance_destroy(s_inst);
1144 	scf_handle_destroy(local_handle);
1145 	startd_free(info, sizeof (fork_info_t));
1146 	return (NULL);
1147 }
1148