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