method.c revision dfe5735016dd804901e28c9585549f5aa15bb63b
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#pragma ident "%Z%%M% %I% %E% SMI"
/*
* method.c - method execution functions
*
* This file contains the routines needed to run a method: a fork(2)-exec(2)
* invocation monitored using either the contract filesystem or waitpid(2).
* (Plain fork1(2) support is provided in fork.c.)
*
* Contract Transfer
* When we restart a service, we want to transfer any contracts that the old
* service's contract inherited. This means that (a) we must not abandon the
* old contract when the service dies and (b) we must write the id of the old
* contract into the terms of the new contract. There should be limits to
* (a), though, since we don't want to keep the contract around forever. To
* this end we'll say that services in the offline state may have a contract
* to be transfered and services in the disabled or maintenance states cannot.
* This means that when a service transitions from online (or degraded) to
* offline, the contract should be preserved, and when the service transitions
* from offline to online (i.e., the start method), we'll transfer inherited
* contracts.
*/
#include <alloca.h>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <libcontract.h>
#include <libcontract_priv.h>
#include <libgen.h>
#include <librestart.h>
#include <libscf.h>
#include <limits.h>
#include <port.h>
#include <sac.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <atomic.h>
#include <poll.h>
#include "startd.h"
/*
* Used to tell if contracts are in the process of being
* stored into the svc.startd internal hash table.
*/
volatile uint16_t storing_contract = 0;
/*
* Mapping from restart_on method-type to contract events. Must correspond to
* enum method_restart_t.
*/
static uint_t method_events[] = {
/* METHOD_RESTART_ALL */
/* METHOD_RESTART_EXTERNAL_FAULT */
/* METHOD_RESTART_ANY_FAULT */
};
/*
* method_record_start(restarter_inst_t *)
* Record a service start for rate limiting. Place the current time
* in the circular array of instance starts.
*/
static void
{
}
/*
* method_rate_critical(restarter_inst_t *)
* Return true if the average start interval is less than the permitted
* interval. Implicit success if insufficient measurements for an
* average exist.
*/
static int
{
return (0);
avg_ns =
(RINST_START_TIMES - 1);
return (avg_ns < RINST_FAILURE_RATE_NS);
}
/*
* int method_is_transient()
* Determine if the method for the given instance is transient,
* from a contract perspective. Return 1 if it is, and 0 if it isn't.
*/
static int
{
return (1);
else
return (0);
}
/*
* void method_store_contract()
* Store the newly created contract id into local structures and
* the repository. If the repository connection is broken it is rebound.
*/
static void
{
int r;
if (!primary) {
"%s: transient ctid expected to be 0 but "
}
} else {
/*
* There was an old contract that we transferred.
* Remove it.
*/
}
"%s: primary ctid expected to be 0 but "
}
}
if (inst->ri_mi_deleted)
return;
switch (r) {
case 0:
break;
case ECANCELED:
break;
case ECONNABORTED:
/* FALLTHROUGH */
case EBADF:
goto again;
case ENOMEM:
case EPERM:
case EACCES:
case EROFS:
uu_die("%s: Couldn't store contract id %ld",
/* NOTREACHED */
case EINVAL:
default:
bad_error("restarter_store_contract", r);
}
}
/*
* void method_remove_contract()
* Remove any non-permanent contracts from internal structures and
* the repository, then abandon them.
* Returns
* 0 - success
* ECANCELED - inst was deleted from the repository
*
* If the repository connection was broken, it is rebound.
*/
void
{
int r;
if (abandon)
if (inst->ri_mi_deleted) {
r = ECANCELED;
goto out;
}
switch (r) {
case 0:
break;
case ECANCELED:
break;
case ECONNABORTED:
/* FALLTHROUGH */
case EBADF:
goto again;
case ENOMEM:
case EPERM:
case EACCES:
case EROFS:
break;
case EINVAL:
default:
bad_error("restarter_remove_contract", r);
}
out:
if (primary)
*ctidp = 0;
}
/*
* int method_ready_contract(restarter_inst_t *, int, method_restart_t, int)
*
* Activate a contract template for the type method of inst. type,
* restart_on, and cte_mask dictate the critical events term of the contract.
* Returns
* 0 - success
* ECANCELED - inst has been deleted from the repository
*/
static int
{
/*
* Correctly supporting wait-style services is tricky without
* rearchitecting startd to cope with multiple event sources
* simultaneously trying to stop an instance. Until a better
* solution is implemented, we avoid this problem for
* wait-style services by making contract events fatal and
* letting the wait code alone handle stopping the service.
*/
if (tmpl == -1)
uu_die("Could not create contract template");
/*
* We assume non-login processes are unlikely to create
* multiple process groups, and set CT_PR_PGRPONLY for all
* wait-style services' contracts.
*/
(iswait ? CT_PR_PGRPONLY : 0));
if (istrans) {
cevents = 0;
fevents = 0;
} else {
assert(restart_on >= 0);
0;
}
switch (ret) {
case 0:
break;
case ENOTEMPTY:
/* No contracts for you! */
if (inst->ri_mi_deleted) {
goto out;
}
break;
case EINVAL:
case ESRCH:
case EACCES:
default:
}
}
ret = 0;
out:
return (ret);
}
static void
{
char *cmd;
const char *errf;
char **nenv;
if (need_session)
(void) setpgrp();
/* Set credentials. */
if (errno != 0) {
stderr);
if (errno == -1) {
(void) fputs("Could not set corefile path.\n",
stderr);
"assignment failed\n", errf);
"occurred\n", errf);
} else {
#ifndef NDEBUG
uu_warn("%s:%d: Bad function name \"%s\" for "
"error %d from "
"restarter_set_method_context().\n",
#endif
abort();
}
exit(1);
}
switch (errno) {
case ENOENT:
"be found\n", errf);
break;
case EBADF:
"is invalid\n", errf);
break;
case EINVAL:
break;
default:
#ifndef NDEBUG
uu_warn("%s:%d: Bad error %d for function %s "
"in restarter_set_method_context().\n",
#endif
abort();
}
}
switch (errno) {
case EINVAL:
case EPERM:
case ENOENT:
case ENAMETOOLONG:
case ERANGE:
case ESRCH:
/* NOTREACHED */
default:
exit(1);
}
}
switch (errno) {
case ENOMEM:
exit(1);
/* NOTREACHED */
case ENOENT:
(void) fputs("Missing passwd entry for user.\n",
stderr);
/* NOTREACHED */
default:
#ifndef NDEBUG
uu_warn("%s:%d: Bad miscellaneous error %d from "
"restarter_set_method_context().\n", __FILE__,
#endif
abort();
}
}
log_preexec();
exit(10);
}
static void
{
int r;
if (inst->ri_mi_deleted)
return;
switch (r) {
case 0:
break;
case ECONNABORTED:
goto again;
case ECANCELED:
break;
case EPERM:
case EACCES:
case EROFS:
"for %s method of %s: %s.\n", mname,
break;
case ENAMETOOLONG:
default:
bad_error("libscf_write_method_status", r);
}
}
/*
* int method_run()
* Execute the type method of instp. If it requires a fork(), wait for it
* to return and return its exit code in *exit_code. Otherwise set
* *exit_code to 0 if the method succeeds & -1 if it fails. If the
* repository connection is broken, it is rebound, but inst may not be
* reset.
* Returns
* 0 - success
* EINVAL - A correct method or method context couldn't be retrieved.
* EIO - Contract kill failed.
* EFAULT - Method couldn't be executed successfully.
* ELOOP - Retry threshold exceeded.
* ECANCELED - inst was deleted from the repository before method was run
* ERANGE - Timeout retry threshold exceeded.
* EAGAIN - Failed due to external cause, retry.
*/
int
{
char *method;
int ret_status;
scf_handle_t *h;
const char *mname;
const char *errstr;
struct method_context *mcp;
int result = 0, timeout_fired = 0;
int sig, r;
int ctfd = -1;
int forkerr;
if (inst->ri_mi_deleted)
return (ECANCELED);
*exit_code = 0;
if (type == METHOD_START)
snap = scf_snapshot_create(h);
"Could not get running snapshot for %s. "
"Using editing version to run method %s.\n",
}
/*
* After this point, we may be logging to the instance log.
* Make sure we've noted where that log is as a property of
* the instance.
*/
inst->ri_logstem);
if (r != 0) {
"%s: couldn't note log location: %s\n",
}
if (errno == LIBSCF_PGROUP_ABSENT) {
"%s: instance has no method property group '%s'.\n",
if (type == METHOD_REFRESH)
"defined. Treating as :true.", mname);
else
"group '%s' is not present.", mname);
return (0);
} else if (errno == LIBSCF_PROPERTY_ABSENT) {
"is not present.", mname);
return (0);
} else {
"%s: instance libscf_get_method failed\n",
return (EINVAL);
}
}
/* open service contract if stopping a non-transient service */
/* service is not running, nothing to stop */
"contract, no service to stop.\n",
return (0);
}
"events", O_RDONLY)) < 0) {
"contract %ld. Stop method not run.\n",
goto out;
}
}
if (restarter_is_null_method(method)) {
if (type == METHOD_START)
goto out;
}
if (sig >= 0) {
goto out;
}
"%s: :killing contract with signal %d\n",
mname);
goto out;
} else
goto assured_kill;
}
goto out;
}
if (r != 0) {
goto out;
}
/*
* Validate safety of method contexts, to save children work.
*/
if (!restarter_rm_libs_loadable())
/*
* If the service is restarting too quickly, send it to
* maintenance.
*/
if (type == METHOD_START) {
if (method_rate_critical(inst)) {
"changing state to maintenance");
goto out;
}
}
if (pid == 0)
if (pid == -1) {
else
"%s: Couldn't fork to execute method %s: %s\n",
goto out;
}
/*
* Get the contract id, decide whether it is primary or transient, and
* stash it in inst & the repository.
*/
/*
* Similarly for the start method PID.
*/
/* Wait style instances don't get timeouts on start methods. */
"%s: couldn't register %ld for wait\n",
goto contract_out;
}
} else {
int r, err;
/*
* Because on upgrade/live-upgrade we may have no chance
* to override faulty timeout values on the way to
* manifest import, all services on the path to manifest
* import are treated the same as INFINITE timeout services.
*/
else
/* Unlock the instance while waiting for the method. */
do
if (r == -1)
/* Re-grab the lock. */
/*
* inst can't be removed, as the removal thread waits
* for completion of this one.
*/
timeout_fired = 1;
"%s method for %s exited with status %d.\n", mname,
if (r == -1) {
"Couldn't waitpid() for %s method of %s (%s).\n",
goto contract_out;
}
if (type == METHOD_START)
/* return ERANGE if this service doesn't retry on timeout */
goto contract_out;
}
if (!WIFEXITED(ret_status)) {
/*
* If method didn't exit itself (it was killed by an
* external entity, etc.), consider the entire
* method_run as failed.
*/
if (WIFSIGNALED(ret_status)) {
char buf[SIG2STR_MAX];
"failed due to signal %s.\n",
} else {
"failed with exit status %d.\n",
"failed with exit status %d", mname,
}
goto contract_out;
}
if (*exit_code != 0) {
"%s: Method \"%s\" failed with exit status %d.\n",
}
if (*exit_code != 0)
goto contract_out;
/* Give service contract remaining seconds to empty */
if (timeout != METHOD_TIMEOUT_INFINITE)
}
/*
* For stop methods, assure that the service contract has emptied
* before returning.
*/
if (timeout != METHOD_TIMEOUT_INFINITE)
timeout);
for (;;) {
break;
}
if (r) {
}
if (timeout != METHOD_TIMEOUT_INFINITE)
}
/* Abandon contracts for transient methods & methods that fail. */
(restarter_is_kill_method(method) < 0))
out:
if (ctfd >= 0)
return (result);
}
/*
* The method thread executes a service method to effect a state transition.
* The next_state of info->sf_id should be non-_NONE on entrance, and it will
* be _NONE on exit (state will either be what next_state was (on success), or
* it will be _MAINT (on error)).
*
* There are six classes of methods to consider: start & other (stop, refresh)
* for each of "normal" services, wait services, and transient services. For
* each, the method must be fetched from the repository & executed. fork()ed
* methods must be waited on, except for the start method of wait services
* (which must be registered with the wait subsystem via wait_register()). If
* the method succeeded (returned 0), then for start methods its contract
* should be recorded as the primary contract for the service. For other
* methods, it should be abandoned. If the method fails, then depending on
* the failure, either the method should be reexecuted or the service should
* be put into maintenance. Either way the contract should be abandoned.
*/
void *
method_thread(void *arg)
{
int r, exit_code;
const char *aux;
/* Get (and lock) the restarter_inst_t. */
/*
* We cannot leave this function with inst in transition, because
* protocol.c withholds messages for inst otherwise.
*/
/* get scf_instance_t */
&s_inst)) {
case 0:
break;
case ECONNABORTED:
goto rebind_retry;
case ENOENT:
/*
* It's not there, but we need to call this so protocol.c
* doesn't think it's in transition anymore.
*/
NULL);
goto out;
case EINVAL:
case ENOTSUP:
default:
bad_error("libscf_fmri_get_instance", r);
}
if (r == 0 && exit_code == 0) {
/* Success! */
/*
* When a stop method succeeds, remove the primary contract of
* the service, unless we're going to offline, in which case
* retain the contract so we can transfer inherited contracts to
* the replacement service.
*/
else
}
/*
* We don't care whether the handle was rebound because this is
* the last thing we do with it.
*/
goto out;
}
/* Failure. Retry or go to maintenance. */
if (r != 0 && r != EAGAIN) {
} else {
switch (exit_code) {
case SMF_EXIT_ERR_CONFIG:
case SMF_EXIT_ERR_NOSMF:
case SMF_EXIT_ERR_PERM:
case SMF_EXIT_ERR_FATAL:
break;
default:
}
}
goto retry;
/* maintenance */
if (r == ELOOP)
else if (r == ERANGE)
else if (exit_code == SMF_EXIT_ERR_CONFIG)
else if (exit_code == SMF_EXIT_ERR_FATAL)
else
if (r == ELOOP)
aux = "restarting_too_quickly";
else if (retryable)
aux = "fault_threshold_reached";
else
aux = "method_failed";
(char *)aux);
out:
inst->ri_method_thread = 0;
return (NULL);
}