/* Gate Specific Code -- BEGIN */
/*
 * Copyright 1998-2002 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 */

#pragma ident "@(#)xfs.c 1.41 02/02/20 SMI"

/* Gate Specific Code -- END */
/* Sun Cluster Data Services Builder template version 1.0 */
/*
 * xfs.c - Common utilities for XFS
 *
 * This utility has the methods for performing the validation, starting and
 * stopping the data service and the fault monitor. It also contains the method
 * to probe the health of the data service.  The probe just returns either
 * success or failure. Action is taken based on this returned value in the
 * method found in the file xfs_probe.c
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <scha.h>
#include <rgm/libdsdev.h>
#include <errno.h>
#include <dlfcn.h>
#include "xfs.h"
/* User added code -- BEGIN vvvvvvvvvvvvvvv */
/* User added code -- END   ^^^^^^^^^^^^^^^ */

/* Network aware applications code -- BEGIN */
/*
 * The initial timeout allowed  for the XFS dataservice to
 * be fully up and running. We will wait for for 3 % (SVC_WAIT_PCT)
 * of the start_timeout time before probing the service.
 */
#define	SVC_WAIT_PCT		3

/*
 * We need to use 95% of probe_timeout to connect to the port and the
 * remaining time is used to disconnect from port in the svc_probe function.
 */
#define	SVC_CONNECT_TIMEOUT_PCT		95

/*
 * We need to wait for SVC_WAIT_TIME ( 2 secs) for pmf
 * to send the failure message before probing the service
 */

#define	SVC_WAIT_TIME		2

/*
 * This value will be used as disconnect timeout, if there is no
 * time left from the probe_timeout.
 */

#define	SVC_DISCONNECT_TIMEOUT_SECONDS		2

/* Network aware applications code -- END */

#define	SVC_SMOOTH_PCT		80

#define	SVC_HARD_PCT		15


/* GDS Specific Code -- BEGIN */
#define	GDS
/* GDS Specific Code -- END */

/* This is the same as a pointer to the scds_hasp_check api */
typedef scha_err_t (*scds_hasp_check_t)(scds_handle_t, scds_hasp_status_t *);

/*
 * svc_validate():
 *
 * Do XFS specific validation of the resource configuration.
 *
 */

int
svc_validate(scds_handle_t scds_handle)
{
	struct stat statbuf;
	char *start_cmd_prog[] = {
	""
	};
	int no_start_cmd = 0;
	int i, err;
	char stop_cmd_prog[SCDS_CMD_SIZE] = "";
	char probe_cmd_prog[SCDS_CMD_SIZE] = "";
	int rc = 0, do_cmd_checks = 1;
	char cmd[SCDS_CMD_SIZE];
	scds_hasp_status_t hasp_status;
	scds_hasp_check_t scds_hasp_check_p;

	/* Network aware applications code -- BEGIN */
	scds_net_resource_list_t *snrlp = NULL;
	scds_port_list_t *portlist = NULL;
	/* Network aware applications code -- END */

	/* GDS Specific Code -- BEGIN */
	scha_extprop_value_t *start_commands = NULL;
	scha_extprop_value_t *stop_command = NULL;
	scha_extprop_value_t *probe_command = NULL;
	char **gds_start_cmds = NULL;
	/* GDS Specific Code -- END */

	/* Are we running with a libdsdev that does not have scds_hasp_check? */
	scds_hasp_check_p = (scds_hasp_check_t)dlsym(RTLD_DEFAULT,
	    "scds_hasp_check");
	if (scds_hasp_check_p == NULL) {
		/* fake a call to scds_hasp_check() */
		err = SCHA_ERR_NOERR;
		hasp_status = SCDS_HASP_NO_RESOURCE;
	} else {
		/* actually check for HAStoragePlus resources */
		err = (*scds_hasp_check_p)(scds_handle, &hasp_status);
	}

	if (err != SCHA_ERR_NOERR) {
		/* scha_hasp_check() logs a message to syslog when it fails */
		rc = 1;
		/*
		 * validation has failed for this resource
		 */
		goto finished;
	}

	switch (hasp_status) {

	case SCDS_HASP_NO_RESOURCE:
		/*
		 * We do not depend on any SUNW.HAStoragePlus resources
		 */
		scds_syslog(LOG_INFO,
		    "This resource does not depend on any SUNW.HAStoragePlus "
		    "resources. Proceeding with normal checks.");
		do_cmd_checks = 1;
		break;

	case SCDS_HASP_ERR_CONFIG:
		/*
		 * Configuration error, SUNW.HAStoragePlus resource is
		 * in a different RG. Fail the validation.
		 */
		scds_syslog(LOG_ERR,
		    "One or more of the SUNW.HAStoragePlus resources that "
		    "this resource depends on is in a different resource "
		    "group. Failing validate method configuration checks.");
		rc = 1;
		goto finished;

	case SCDS_HASP_NOT_ONLINE:
		/*
		 * There is at least one SUNW.HAStoragePlus resource not
		 * online anywhere.
		 */
		scds_syslog(LOG_ERR,
		    "One or more of the SUNW.HAStoragePlus resources that "
		    "this resource depends on is not online anywhere. "
		    "Failing validate method.");
		rc = 1;
		goto finished;

	case SCDS_HASP_ONLINE_NOT_LOCAL:
		/*
		 * Not all SUNW.HAStoragePlus we need, are online locally.
		 */
		scds_syslog(LOG_INFO,
		    "All the SUNW.HAStoragePlus resources that this resource "
		    "depends on are not online on the local node. "
		    "Skipping the checks for the existence and permissions "
		    "of the start/stop/probe commands.");
		do_cmd_checks = 0;
		break;

	case SCDS_HASP_ONLINE_LOCAL:
		/*
		 * All SUNW.HAStoragePlus resources we need are available on
		 * this node.
		 */
		scds_syslog(LOG_INFO,
		    "All the SUNW.HAStoragePlus resources that this resource "
		    "depends on are online on the local node. "
		    "Proceeding with the checks for the existence and "
		    "permissions of the start/stop/probe commands.");
		do_cmd_checks = 1;
		break;

	default:
		/* Unknown status code */
		scds_syslog(LOG_ERR, "Unknown status code %d.", hasp_status);
		rc = 1;
		break;
	}

	/*
	 * If we got here and do_cmd_checks is not set, it means that
	 * the SUNW.HAStorage resource is online but not on this node.
	 * Therefore, skip the checks for the existence and permissions
	 * of the start/stop/probe commands and jump (goto) straight to
	 * "global_checks".
	 */

	if (!do_cmd_checks) {
		goto global_checks;
	}

	/*
	 * If do_cmd_checks is set, it means that the SUNW.HAStorage
	 * resource is online on the local node. Therefore, proceed with
	 * the checks for the existence and permissions of the
	 * start/stop/probe commands.
	 */

	/* GDS Specific Code -- BEGIN */
	if ((rc = scds_get_ext_property(scds_handle, "Start_command",
	    SCHA_PTYPE_STRINGARRAY, &start_commands)) != SCHA_ERR_NOERR) {
		scds_syslog(LOG_ERR,
		    "Failed to retrieve resource <%s> extension property <%s>",
		    scds_get_resource_name(scds_handle), "Start_command");
		goto finished;
	}

	no_start_cmd = start_commands->val.val_strarray->array_cnt;

	gds_start_cmds = (char **)malloc(no_start_cmd * sizeof (char *));
	if (gds_start_cmds == NULL) {
		scds_syslog(LOG_ERR, "Out of memory.");
		rc = SCHA_ERR_NOMEM;
		goto finished;
	}

	for (i = 0; i < no_start_cmd; i++) {
		gds_start_cmds[i] =
		    start_commands->val.val_strarray->str_array[i];
	}

	if ((rc = scds_get_ext_property(scds_handle, "Stop_command",
	    SCHA_PTYPE_STRING, &stop_command)) != SCHA_ERR_NOERR) {
		scds_syslog(LOG_ERR,
		    "Failed to retrieve resource <%s> extension property <%s>",
		    scds_get_resource_name(scds_handle), "Stop_command");
		goto finished;
	}

	if ((stop_command->val.val_str != NULL) &&
	    (strcmp(stop_command->val.val_str, "") != 0)) {
		(void) strcpy(stop_cmd_prog, stop_command->val.val_str);
		(void) strtok(stop_cmd_prog, " ");
	}

	if ((rc = scds_get_ext_property(scds_handle, "Probe_command",
	    SCHA_PTYPE_STRING, &probe_command)) != SCHA_ERR_NOERR) {
		scds_syslog(LOG_ERR,
		    "Failed to retrieve resource <%s> extension property <%s>",
		    scds_get_resource_name(scds_handle), "Probe_command");
		goto finished;
	}

	if ((probe_command->val.val_str != NULL) &&
	    (strcmp(probe_command->val.val_str, "") != 0)) {
		(void) strcpy(probe_cmd_prog, probe_command->val.val_str);
		(void) strtok(probe_cmd_prog, " ");
	}
	/* GDS Specific Code -- END */

	/* User added code -- BEGIN vvvvvvvvvvvvvvv */
	/* User added code -- END   ^^^^^^^^^^^^^^^ */

	for (i = 0; i < no_start_cmd; i++) {
		/*
		 * Make sure that xfs start command exists and that the
		 * permissions are correct.
		 */
		/* GDS Specific Code -- BEGIN */
#ifdef GDS
		(void) strcpy(cmd, gds_start_cmds[i]);
		(void) strtok(cmd, " ");
#else
		/* GDS Specific Code -- END */
		(void) strcpy(cmd, start_cmd_prog[i]);
		/* GDS Specific Code -- BEGIN */
#endif
		/* GDS Specific Code -- END */

		if (stat(cmd, &statbuf) != 0) {
			scds_syslog(LOG_ERR,
			    "Cannot access the %s command <%s> : <%s>",
			    "start", cmd, strerror(errno));
			rc = 1;
			goto finished;
		}

		if (!(statbuf.st_mode & S_IXUSR)) {
			scds_syslog(LOG_ERR,
			    "The %s command does not have execute "
			    "permissions: <%s>", "start", cmd);
			rc = 1;
			goto finished;
		}
	}

	/*
	 * Make sure that if xfs stop command is specified, then it exists
	 * and that the permissions are correct.
	 */
	if (strcmp(stop_cmd_prog, "") != 0) {
		if (stat(stop_cmd_prog, &statbuf) != 0) {
			scds_syslog(LOG_ERR,
			    "Cannot access the %s command <%s> : <%s>",
			    "stop", stop_cmd_prog, strerror(errno));
			rc = 1;
			goto finished;
		}

		if (!(statbuf.st_mode & S_IXUSR)) {
			scds_syslog(LOG_ERR,
			    "The %s command does not have execute "
			    "permissions: <%s>", "stop", cmd);
			rc = 1;
			goto finished;
		}
	}

	/*
	 * Make sure that if xfs probe command is specified, then it exists
	 * and that the permissions are correct.
	 */
	if (strcmp(probe_cmd_prog, "") != 0) {
		if (stat(probe_cmd_prog, &statbuf) != 0) {
			scds_syslog(LOG_ERR,
			    "Cannot access the %s command <%s> : <%s>",
			    "probe", probe_cmd_prog, strerror(errno));
			rc = 1;
			goto finished;
		}

		if (!(statbuf.st_mode & S_IXUSR)) {
			scds_syslog(LOG_ERR,
			    "The %s command does not have execute "
			    "permissions: <%s>", "probe", probe_cmd_prog);
			rc = 1;
			goto finished;
		}
	}

global_checks:

	/* Network aware applications code -- BEGIN */

	/*
	 * Network aware service should have at least one port specified
	 */

	rc = scds_get_port_list(scds_handle, &portlist);
	if (rc != SCHA_ERR_NOERR) {
		scds_syslog(LOG_ERR,
		    "Failed to retrieve the resource property %s: %s.",
		    SCHA_PORT_LIST, scds_error_string(rc));
		goto finished;
	}

	if (portlist == NULL || portlist->num_ports < 1) {
		scds_syslog(LOG_ERR,
		    "Property %s is not set.", SCHA_PORT_LIST);
		rc = 1;
		goto finished;
	}

	/*
	 * Return an error if there is an error when trying to get the
	 * available network address resources for this resource
	 */
	if ((rc = scds_get_rs_hostnames(scds_handle, &snrlp))
		!= SCHA_ERR_NOERR) {
		scds_syslog(LOG_ERR,
		    "Error in trying to access the configured network "
		    "resources : %s.", scds_error_string(rc));
		goto finished;
	}

	/* Return an error if there are no network address resources */
	if (snrlp == NULL || snrlp->num_netresources == 0) {
		scds_syslog(LOG_ERR,
		    "No network address resource in resource group.");
		rc = 1;
		goto finished;
	}

	/* Check to make sure other important extension props are set */
	if (scds_get_ext_monitor_retry_count(scds_handle) <= 0) {
		scds_syslog(LOG_ERR,
		"Monitor_retry_count or Monitor_retry_interval is not set.");
		rc = 1; /* Validation Failure */
		goto finished;
	}
	if (scds_get_ext_monitor_retry_interval(scds_handle) <= 0) {
		scds_syslog(LOG_ERR,
		"Monitor_retry_count or Monitor_retry_interval is not set.");
		rc = 1; /* Validation Failure */
		goto finished;
	}

	/* User added code -- BEGIN vvvvvvvvvvvvvvv */
	/* User added code -- END   ^^^^^^^^^^^^^^^ */

	/* All validation checks were successful */

	/* Network aware applications code -- END */

finished:
	/* GDS Specific Code -- BEGIN */
	if (start_commands)
		scds_free_ext_property(start_commands);
	if (stop_command)
		scds_free_ext_property(stop_command);
	if (probe_command)
		scds_free_ext_property(probe_command);

	free(gds_start_cmds);
	/* GDS Specific Code -- END */

	/* Network aware applications code -- BEGIN */
	scds_free_net_list(snrlp);
	scds_free_port_list(portlist);
	/* Network aware applications code -- END */

	/* User added code -- BEGIN vvvvvvvvvvvvvvv */
	/* User added code -- END   ^^^^^^^^^^^^^^^ */

	return (rc); /* return result of validation */
}

/*
 * svc_start():
 *
 */

int
svc_start(scds_handle_t scds_handle)
{
	int rc = 0;
	char *service_start_cmd[] = {
	""
	};
	int no_start_cmd = 0;
	int i;
	char cmd[SCDS_CMD_SIZE];
	/* GDS Specific Code -- BEGIN */
	scha_extprop_value_t *start_commands = NULL;
	char **gds_start_cmds = NULL;
	/* GDS Specific Code -- END */

	/* User added code -- BEGIN vvvvvvvvvvvvvvv */
	/* User added code -- END   ^^^^^^^^^^^^^^^ */

	/* GDS Specific Code -- BEGIN */
	if ((rc = scds_get_ext_property(scds_handle, "Start_command",
	    SCHA_PTYPE_STRINGARRAY, &start_commands)) != SCHA_ERR_NOERR) {
		scds_syslog(LOG_ERR,
		    "Failed to retrieve resource <%s> extension property <%s>",
		    scds_get_resource_name(scds_handle), "Start_command");
		goto finished;
	}

	no_start_cmd = start_commands->val.val_strarray->array_cnt;

	gds_start_cmds = (char **)malloc(no_start_cmd * sizeof (char *));
	if (gds_start_cmds == NULL) {
		scds_syslog(LOG_ERR,
		    "Out of memory.");
		rc = SCHA_ERR_NOMEM;
		goto finished;
	}

	for (i = 0; i < no_start_cmd; i++) {
		gds_start_cmds[i] =
		    start_commands->val.val_strarray->str_array[i];
	}
	/* GDS Specific Code -- END */

	for (i = 0; i < no_start_cmd; i++) {
		/*
		 * Start XFS under PMF.
		 */

		/* GDS Specific Code -- BEGIN */
#ifdef GDS
		(void) strcpy(cmd, gds_start_cmds[i]);
#else
		/* GDS Specific Code -- END */
		(void) strcpy(cmd, service_start_cmd[i]);
		/* GDS Specific Code -- BEGIN */
#endif
		/* GDS Specific Code -- END */

		if ((rc = preprocess_cmd(scds_handle, cmd)) != 0) {
			scds_syslog(LOG_ERR,
			    "Failed to form the %s command.", "start");
			goto finished;
		}

		/* User added code -- BEGIN vvvvvvvvvvvvvvv */
		/* User added code -- END   ^^^^^^^^^^^^^^^ */

		rc = scds_pmf_start(scds_handle, SCDS_PMF_TYPE_SVC, i, cmd,
		    -1);

		if (rc == SCHA_ERR_NOERR) {
			scds_syslog(LOG_INFO,
			    "Start of %s completed successfully.", cmd);
		} else {
			scds_syslog(LOG_ERR,
			    "Failed to start %s.", cmd);
			goto finished;
		}

		/* User added code -- BEGIN vvvvvvvvvvvvvvv */
		/* User added code -- END   ^^^^^^^^^^^^^^^ */
	}

finished:
	/* GDS Specific Code -- BEGIN */
	scds_free_ext_property(start_commands);
	free(gds_start_cmds);
	/* GDS Specific Code -- END */

	/* User added code -- BEGIN vvvvvvvvvvvvvvv */
	/* User added code -- END   ^^^^^^^^^^^^^^^ */
	return (rc); /* return Success/failure status */
}

/*
 * svc_stop():
 *
 * Stop the XFS server
 * Return 0 on success, > 0 on failures.
 *
 */
int
svc_stop(scds_handle_t scds_handle)
{
	int no_start_cmd = 0;
	int i;
	int rc = 0, cmd_exit_code = 0;
	char service_stop_cmd[SCDS_CMD_SIZE] = "";
	int stop_smooth_timeout =
	    (scds_get_rs_stop_timeout(scds_handle) * SVC_SMOOTH_PCT) / 100;
	int stop_hard_timeout =
	    (scds_get_rs_stop_timeout(scds_handle) * SVC_HARD_PCT) / 100;
	char cmd[SCDS_CMD_SIZE];
	scha_extprop_value_t *stop_signal_prop = NULL;
	int stop_signal = SIGTERM;

	/* GDS Specific Code -- BEGIN */
	scha_extprop_value_t *start_commands = NULL;
	scha_extprop_value_t *stop_command = NULL;

	if ((rc = scds_get_ext_property(scds_handle, "Start_command",
	    SCHA_PTYPE_STRINGARRAY, &start_commands)) != SCHA_ERR_NOERR) {
		scds_syslog(LOG_ERR,
		    "Failed to retrieve resource <%s> extension property <%s>",
		    scds_get_resource_name(scds_handle), "Start_command");
		/*
		 * In this case, we bail out right away. This may seem somewhat
		 * harsh. However, considering that in this case we don't even
		 * know how many start commands there are. So we won't know
		 * how many times the loop at "send_kill" should iterate and
		 * might end up leaving some pmf tags hanging behind.
		 */
		goto finished;
	}

	no_start_cmd = start_commands->val.val_strarray->array_cnt;

	if ((rc = scds_get_ext_property(scds_handle, "Stop_command",
	    SCHA_PTYPE_STRING, &stop_command)) != SCHA_ERR_NOERR) {
		scds_syslog(LOG_ERR,
		    "Failed to retrieve resource <%s> extension property <%s>",
		    scds_get_resource_name(scds_handle), "Stop_command");
		/*
		 * This error is less severe than the previous one. We do know
		 * how many start commands there were, but are not able to
		 * retrieve the stop command. Therefore, we goto send_kill.
		 * Also, notice that "rc" will get overwritten in the loop at
		 * send_kill.
		 */
		goto send_kill;
	}

	if ((stop_command->val.val_str != NULL) &&
	    (strcmp(stop_command->val.val_str, "") != 0)) {
		(void) strcpy(service_stop_cmd, stop_command->val.val_str);
	}
	/* GDS Specific Code -- END */

	/* User added code -- BEGIN vvvvvvvvvvvvvvv */
	/* User added code -- END   ^^^^^^^^^^^^^^^ */

	rc = scds_get_ext_property(scds_handle, "Stop_signal", SCHA_PTYPE_INT,
	    &stop_signal_prop);

	if (rc == SCHA_ERR_NOERR) {
		stop_signal = stop_signal_prop->val.val_int;
		scds_syslog(LOG_INFO,
		    "Extension property <stop_signal> has a value of <%d>",
		    stop_signal);
	} else {
		scds_syslog(LOG_INFO,
		    "Either extension property <stop_signal> is not defined, "
		    "or an error occurred while retrieving this property; "
		    "using the default value of SIGTERM.");
	}

	if (strcmp(service_stop_cmd, "") != 0) {
		for (i = 0; i < no_start_cmd; i++) {

			/* User added code -- BEGIN vvvvvvvvvvvvvvv */
			/* User added code -- END   ^^^^^^^^^^^^^^^ */

			/*
			 * First take the command out of PMF monitoring,
			 * so that it doesn't keep restarting it.
			 */
			rc = scds_pmf_stop_monitoring(scds_handle,
			    SCDS_PMF_TYPE_SVC, i);
			if (rc != SCHA_ERR_NOERR) {
				scds_syslog(LOG_ERR, "Failed to take "
				    "the resource out of PMF control. "
				    "Sending SIGKILL now.");
				goto send_kill;
			}
		}

		/* User added code -- BEGIN vvvvvvvvvvvvvvv */
		/* User added code -- END   ^^^^^^^^^^^^^^^ */

		/*
		 * First try to stop the application using the stop command
		 * provided.
		 */
		(void) strcpy(cmd, service_stop_cmd);
		if ((rc = preprocess_cmd(scds_handle, cmd)) != 0) {
			scds_syslog(LOG_ERR,
			    "Failed to form the %s command.", "stop");
			/*
			 * We failed to preprocess the stop command so can't
			 * use that. We still proceed to send KILL signal and
			 * try to stop the application anyway.
			 */
			goto send_kill;
		}

		rc = scds_timerun(scds_handle, cmd, stop_smooth_timeout,
		    SIGKILL, &cmd_exit_code);

		if (rc != 0 || cmd_exit_code != 0) {
			scds_syslog(LOG_ERR,
			    "The stop command <%s> failed to stop the "
			    "application. Will now use SIGKILL to stop the "
			    "application.",  cmd);
		}

		/*
		 * Regardless of whether the command succeeded or not we
		 * send KILL signal to the pmf tag. This will ensure that
		 * the process tree goes away if it still exists. If it
		 * doesn't exist by then, we return NOERR.
		 */
		goto send_kill;
	} else {
		for (i = 0; i < no_start_cmd; i++) {
			/* User added code -- BEGIN vvvvvvvvvvvvvvv */
			/* User added code -- END   ^^^^^^^^^^^^^^^ */

			/*
			 * If no stop command is specified, we use
			 * scds_pmf_stop to stop the application.
			 */
			if ((rc = scds_pmf_stop(scds_handle, SCDS_PMF_TYPE_SVC,
			    i, stop_signal,
			    scds_get_rs_stop_timeout(scds_handle))) !=
			    SCHA_ERR_NOERR) {
				scds_syslog(LOG_ERR,
				    "Failed to stop %s.", "the application");
				/*
				 * Since the Data service did not stop with a
				 * scds_pmf_stop, we return non-zero.
				 */
				goto finished;
			}
		}
		goto finished;
	}

send_kill:
	for (i = 0; i < no_start_cmd; i++) {
		/* User added code -- BEGIN vvvvvvvvvvvvvvv */
		/* User added code -- END   ^^^^^^^^^^^^^^^ */

		/*
		 * Since all else failed, send SIGKILL to stop the application.
		 * Notice that this call will return with success, even if
		 * the tag does not exist by now.
		 */
		if ((rc = scds_pmf_stop(scds_handle, SCDS_PMF_TYPE_SVC, i,
		    SIGKILL, stop_hard_timeout)) != SCHA_ERR_NOERR) {
			/*
			 * Failed to stop the application even with SIGKILL,
			 * bail out now.
			 */
			scds_syslog(LOG_ERR,
			    "Failed to stop the application with SIGKILL. "
			    "Returning with failure from stop method.");
			goto finished;
		}
	}

	/* User added code -- BEGIN vvvvvvvvvvvvvvv */
	/* User added code -- END   ^^^^^^^^^^^^^^^ */

finished:
	/* GDS Specific Code -- BEGIN */

	scds_free_ext_property(start_commands);
	scds_free_ext_property(stop_command);

	/* GDS Specific Code -- END */

	scds_free_ext_property(stop_signal_prop);

	if (rc == SCHA_ERR_NOERR)
		scds_syslog(LOG_INFO, "Successfully stopped the application");

	return (rc); /* Successfully stopped */
}

/* Network aware applications code -- BEGIN */
/*
 * svc_wait():
 *
 * wait for the data service to start up fully and make sure it is running
 * healthy
 */

int
svc_wait(scds_handle_t scds_handle)
{
	int rc, svc_start_timeout, probe_timeout;
	scds_netaddr_list_t	*netaddr;
	scds_pmf_status_t	status;
	scha_err_t err;

	/* obtain the network resource to use for probing */
	if (scds_get_netaddr_list(scds_handle, &netaddr)) {
		scds_syslog(LOG_ERR,
		    "No network address resource in resource group.");
		return (1);
	}

	/* Return an error if there are no network resources */
	if (netaddr == NULL || netaddr->num_netaddrs == 0) {
		scds_syslog(LOG_ERR,
		    "No network address resource in resource group.");
		return (1);
	}

	/*
	 * Get the Start method timeout, port number on which to probe,
	 * the Probe timeout value
	 */
	svc_start_timeout = scds_get_rs_start_timeout(scds_handle);
	probe_timeout = scds_get_ext_probe_timeout(scds_handle);

	/*
	 * sleep for SVC_WAIT_PCT percentage of start_timeout time
	 * before actually probing the dataservice. This is to allow
	 * the dataservice to be fully up in order to reply to the
	 * probe. NOTE: the value for SVC_WAIT_PCT could be different
	 * for different dataservices.
	 */
	if (scds_svc_wait(scds_handle, (svc_start_timeout * SVC_WAIT_PCT)/100)
	    != SCHA_ERR_NOERR) {
		scds_syslog(LOG_ERR, "Failed to start service.");
		return (1);
	}

	do {
		/*
		 * probe the data service on the IP address of the
		 * network resource and the portname
		 */
		rc = svc_probe(scds_handle,
		    netaddr->netaddrs[0].hostname,
		    netaddr->netaddrs[0].port_proto.port, probe_timeout);
		if (rc == SCHA_ERR_NOERR) {
			/* Success. Free up resources and return */
			scds_free_netaddr_list(netaddr);
			return (SCHA_ERR_NOERR);
		}

		err = scds_pmf_get_status(scds_handle,
		    SCDS_PMF_TYPE_SVC, SCDS_PMF_SINGLE_INSTANCE, &status);
		if (err != SCHA_ERR_NOERR) {
			scds_syslog(LOG_ERR,
			    "Failed to retrieve process monitor facility tag.");
			return (1);
		}

		/* Check if the dataservice is still up and running */
		if (status != SCDS_PMF_MONITORED) {
			scds_syslog(LOG_ERR,
			    "Application failed to stay up. "
			    "Start method Failure.");
			return (1);
		}

		/*
		 * Dataservice is still trying to come up. Sleep for a while
		 * before probing again.
		 */
		(void) sleep(SVC_WAIT_TIME);

	/* We rely on RGM to timeout and terminate the program */
	} while (1);

}
/* Network aware applications code -- END */

/*
 * This function starts the fault monitor for a XFS resource.
 * This is done by starting the probe under PMF. The PMF tag
 * is derived as <RG-name,RS-name,instance_number.mon>. The restart option
 * of PMF is used but not the "infinite restart". Instead
 * interval/retry_time is obtained from the RTR file.
 */

int
mon_start(scds_handle_t scds_handle)
{
	scha_err_t	err;
	/* User added code -- BEGIN vvvvvvvvvvvvvvv */
	/* User added code -- END   ^^^^^^^^^^^^^^^ */

	scds_syslog_debug(DBG_LEVEL_HIGH,
	    "Calling MONITOR_START method for resource <%s>.",
	    scds_get_resource_name(scds_handle));

	/*
	 * The probe xfs_probe is assumed to be available in the same
	 * subdirectory where the other callback methods for the RT are
	 * installed. The last parameter to scds_pmf_start denotes the
	 * child monitor level. Since we are starting the probe under PMF
	 * we need to monitor the probe process only and hence we are using
	 * a value of 0.
	 */

	/* GDS Specific Code -- BEGIN */
#ifdef GDS
	err = scds_pmf_start(scds_handle, SCDS_PMF_TYPE_MON,
	    SCDS_PMF_SINGLE_INSTANCE, "gds_probe", 0);
#else
	/* GDS Specific Code -- END */
	err = scds_pmf_start(scds_handle, SCDS_PMF_TYPE_MON,
	    SCDS_PMF_SINGLE_INSTANCE, "xfs_probe", 0);
	/* GDS Specific Code -- BEGIN */
#endif
	/* GDS Specific Code -- END */

	if (err != SCHA_ERR_NOERR) {
		scds_syslog(LOG_ERR, "Failed to start fault monitor.");
		return (err);
	}

	/* User added code -- BEGIN vvvvvvvvvvvvvvv */
	/* User added code -- END   ^^^^^^^^^^^^^^^ */

	scds_syslog(LOG_INFO, "Started the fault monitor.");

	return (SCHA_ERR_NOERR); /* Successfully started Monitor */
}


/*
 * This function stops the fault monitor for a XFS resource.
 * This is done via PMF. The PMF tag for the fault monitor is
 * constructed based on <RG-name_RS-name,instance_number.mon>.
 */

int
mon_stop(scds_handle_t scds_handle)
{
	scha_err_t	err;
	/* User added code -- BEGIN vvvvvvvvvvvvvvv */
	/* User added code -- END   ^^^^^^^^^^^^^^^ */

	scds_syslog_debug(DBG_LEVEL_HIGH, "Calling scds_pmf_stop method");

	err = scds_pmf_stop(scds_handle, SCDS_PMF_TYPE_MON,
	    SCDS_PMF_SINGLE_INSTANCE, SIGKILL,
	    scds_get_rs_monitor_stop_timeout(scds_handle));

	if (err != SCHA_ERR_NOERR) {
		scds_syslog(LOG_ERR, "Failed to stop fault monitor.");
		return (err);
	}

	/* User added code -- BEGIN vvvvvvvvvvvvvvv */
	/* User added code -- END   ^^^^^^^^^^^^^^^ */

	scds_syslog(LOG_INFO, "Stopped the fault monitor.");

	return (SCHA_ERR_NOERR); /* Successfully stopped monitor */
}


/* Network aware applications code -- BEGIN */
/*
 * svc_probe(): Do data service specific probing. Return a float value
 * between 0 (success) and 100(complete failure).
 *
 * The probe does a simple socket connection to the XFS server on the specified
 * port which is configured as the resource extension property (Port_list) and
 * pings the dataservice. If the probe fails to connect to the port, we return
 * a value of 100 indicating that there is a total failure. If the connection
 * goes through and the disconnect to the port fails, then a value of 50 is
 * returned indicating a partial failure.
 *
 */
int
svc_probe(scds_handle_t scds_handle, char *hostname, int port, int timeout)
{
	int  rc = 0;
	int probe_status = 0;
	ulong_t	t1, t2;
	int 	sock;
	int 	time_used, time_remaining;
	ulong_t		connect_timeout;
	int cmd_exit_status = 0;
	char service_probe_cmd[SCDS_CMD_SIZE] = "";
	char cmd[SCDS_CMD_SIZE];
	/* GDS Specific Code -- BEGIN */
	scha_extprop_value_t *probe_command = NULL;

	if ((rc = scds_get_ext_property(scds_handle, "Probe_command",
	    SCHA_PTYPE_STRING, &probe_command)) != SCHA_ERR_NOERR) {
		scds_syslog(LOG_ERR,
		    "Failed to retrieve the probe command with error <%d>. "
		    "Will continue to do the simple probe.", rc);
		/*
		 * If we fail to retrieve the user specified probe command,
		 * we log an error message and proceed to do the simple probe,
		 * i.e. the tcp connect/disconnect probing.
		 */
		goto simple_probe;
	}

	if ((probe_command->val.val_str != NULL) &&
	    (strcmp(probe_command->val.val_str, "") != 0)) {
		(void) strcpy(service_probe_cmd, probe_command->val.val_str);
	}
	/* GDS Specific Code -- END */

	/* User added code -- BEGIN vvvvvvvvvvvvvvv */
	/* User added code -- END   ^^^^^^^^^^^^^^^ */

	if (strcmp(service_probe_cmd, "") != 0) {

		/*
		 * probe command is specified; so use that to probe the
		 * application.
		 */
		(void) strcpy(cmd, service_probe_cmd);
		if ((rc = preprocess_cmd(scds_handle, cmd)) != 0) {
			scds_syslog(LOG_ERR,
			    "Failed to form the %s command.", "probe");

			/*
			 * If we fail to preprocess the user specified probe
			 * command we log an error message and proceed to do
			 * the simple probe, i.e. the tcp connect/disconnect
			 * probing.
			 */
			goto simple_probe;
		}

		rc = scds_timerun(scds_handle, cmd, timeout, SIGKILL,
		    &cmd_exit_status);
		if (rc == SCHA_ERR_TIMEOUT) {
			scds_syslog(LOG_ERR,
			    "The probe command <%s> timed out", cmd);

			/*
			 * We return half of the SCDS_PROBE_COMPLETE_FAILURE,
			 * so that two failures in a row will be required
			 * for any action to be taken.
			 */
			probe_status = SCDS_PROBE_COMPLETE_FAILURE/2;
			goto finished;
		}
		if (rc == SCHA_ERR_INTERNAL) {
			char internal_err_str[SCDS_CMD_SIZE];

			(void) snprintf(internal_err_str,
			    SCDS_CMD_SIZE,
			    "error occurred while launching "
			    "the probe command <%s>", cmd);

			scds_syslog(LOG_ERR,
			    "INTERNAL ERROR: %s.",
			    internal_err_str);

			/*
			 * An internal error is likely to be caused by some
			 * system level problem (out of swap space etc.).
			 * Since most of these problems are transient, we
			 * return half of the SCDS_PROBE_COMPLETE_FAILURE,
			 * so that two failures in a row will be required
			 * for any action to be taken.
			 */
			probe_status = SCDS_PROBE_COMPLETE_FAILURE/2;
			goto finished;
		}
		if (rc == SCHA_ERR_INVAL) {
			scds_syslog(LOG_ERR,
			    "Cannot execute %s: %s.", cmd, cmd_exit_status);
			probe_status = SCDS_PROBE_COMPLETE_FAILURE;
			goto finished;
		}

		/*
		 * return the exit status of the command.
		 */
		probe_status = cmd_exit_status;
		goto finished;
	}

simple_probe:
	/*
	 * If the probe command is not specified we use the normal probe
	 * which simply connects to the port and disconnects.
	 */

	/*
	 * probe the dataservice by doing a socket connection to the port
	 * specified in the port_list property to the host that is
	 * serving the XFS dataservice. If the XFS service which is configured
	 * to listen on the specified port, replies to the connection, then
	 * the probe is successful. Else we will wait for a time period set
	 * in probe_timeout property before concluding that the probe failed.
	 */

	/*
	 * Use the SVC_CONNECT_TIMEOUT_PCT percentage of timeout
	 * to connect to the port
	 */
	connect_timeout = (SVC_CONNECT_TIMEOUT_PCT * timeout)/100;
	t1 = gethrtime()/1E9;

	/*
	 * the probe makes a connection to the specified hostname and port.
	 * The connection is timed for 95% of the actual probe_timeout.
	 */
	rc = scds_fm_tcp_connect(scds_handle, &sock, hostname, port,
	    connect_timeout);
	if (rc) {
		scds_syslog(LOG_ERR,
		    "Failed to connect to the host <%s> and port <%d>.",
		    hostname, port);
		/* this is a complete failure */
		probe_status = SCDS_PROBE_COMPLETE_FAILURE;
		goto finished;
	}

	t2 = gethrtime()/1E9;

	/*
	 * Compute the actual time it took to connect. This should be less than
	 * or equal to connect_timeout, the time allocated to connect.
	 * If the connect uses all the time that is allocated for it,
	 * then the remaining value from the probe_timeout that is passed to
	 * this function will be used as disconnect timeout. Otherwise, the
	 * the remaining time from the connect call will also be added to
	 * the disconnect timeout.
	 *
	 */

	time_used = t2 -t1;

	/*
	 * Use the remaining time(timeout - time_took_to_connect) to disconnect
	 */

	time_remaining = timeout - (int)time_used;

	/*
	 * If all the time is used up, use a small hardcoded timeout
	 * to still try to disconnect. This will avoid the fd leak.
	 */
	if (time_remaining <= 0) {
		scds_syslog_debug(DBG_LEVEL_LOW,
		    "svc_probe used entire timeout of "
		    "%d seconds during connect operation and exceeded the "
		    "timeout by %d seconds. Attempting disconnect with timeout"
		    " %d ",
		    connect_timeout,
		    abs(time_used),
		    SVC_DISCONNECT_TIMEOUT_SECONDS);

		time_remaining = SVC_DISCONNECT_TIMEOUT_SECONDS;
	}

	/*
	 * Return partial failure in case of disconnection failure.
	 * Reason: The connect call is successful, which means
	 * the application is alive. A disconnection failure
	 * could happen due to a hung application or heavy load.
	 * If it is the later case, don't declare the application
	 * as dead by returning complete failure. Instead, declare
	 * it as partial failure. If this situation persists, the
	 * disconnect call will fail again and the application will be
	 * restarted.
	 */
	rc = scds_fm_tcp_disconnect(scds_handle, sock, time_remaining);
	if (rc != SCHA_ERR_NOERR) {
		scds_syslog(LOG_ERR,
		    "Failed to disconnect from port %d of resource %s.",
		    port, scds_get_resource_name(scds_handle));
		/* this is a partial failure */
		probe_status = SCDS_PROBE_COMPLETE_FAILURE/2;
		goto finished;
	}

	t2 = gethrtime()/1E9;
	time_used = t2 -t1;
	time_remaining = timeout - time_used;

	/*
	 * If there is no time left, don't do the full test with
	 * fsinfo. Return SCDS_PROBE_COMPLETE_FAILURE/2
	 * instead. This will make sure that if this timeout
	 * persists, server will be restarted.
	 */
	if (time_remaining <= 0) {
		scds_syslog(LOG_ERR, "Probe timed out.");
		probe_status = SCDS_PROBE_COMPLETE_FAILURE/2;
		goto finished;
	}

	/* User added code -- BEGIN vvvvvvvvvvvvvvv */
	/* User added code -- END   ^^^^^^^^^^^^^^^ */

finished:
	/* GDS Specific Code -- BEGIN */

	scds_free_ext_property(probe_command);

	/* GDS Specific Code -- END */

	return (probe_status);
}
/* Network aware applications code -- END */

/* The following are utility routines */

/*
 * This utility routine computes the list of hostnames being used by
 * the given "resource".
 * The list of network resources is put in env_var_hostnames.
 */
int
compute_hostnames(scds_handle_t scds_handle, char *env_var_hostnames)
{
	scds_net_resource_list_t *snrlp;
	scds_net_resource_t snrp;
	int rs, ip;

	/* Network aware applications code -- BEGIN */

	if (scds_get_rs_hostnames(scds_handle, &snrlp)) {
		scds_syslog(LOG_ERR,
		    "No network address resource in resource group.");
		return (1);
	}

	/*
	 * Iterate through all resources to get the hostnames
	 */
	for (rs = 0; rs < snrlp->num_netresources; rs++) {
		snrp = snrlp->netresources[rs];
		for (ip = 0; ip < snrp.num_hostnames; ip++) {

			if (rs != 0 || ip != 0)
				(void) strlcat(env_var_hostnames, ",",
					SCDS_CMD_SIZE);

			(void) strlcat(env_var_hostnames, snrp.hostnames[ip],
			    SCDS_CMD_SIZE);
		}
	}

	scds_free_net_list(snrlp);
	/* Network aware applications code -- END */

	return (0);
}

/*
 * This utility routine replaces all occurrences of "var_name" with "var_val"
 * in orig_cmd and puts the output back in orig_cmd. In that sense orig_cmd
 * is an in/out parameter.
 */
int
substitute_var(char *orig_cmd, char *var_name, char *var_val)
{
	char dest[SCDS_CMD_SIZE];
	int var_len = strlen(var_name);
	int value_len = strlen(var_val);
	int first_part_len = 0;
	int end_part_len = 0;
	const char *var_occurence = NULL;

	while (var_occurence = strstr(orig_cmd, var_name)) {
		first_part_len = var_occurence - orig_cmd;
		end_part_len = orig_cmd + strlen(orig_cmd) -
		    (var_occurence + var_len);

		(void) strncpy(dest, orig_cmd, first_part_len);
		dest[first_part_len] = '\0';

		if (value_len > (SCDS_CMD_SIZE - strlen(dest) - end_part_len)) {
			return (1);
		}

		(void) strcat(dest, var_val);

		(void) strcat(dest, var_occurence + var_len);
		(void) strcpy(orig_cmd, dest);
	}

	return (0);
}

/*
 * This utility routine searches a given string, typically the commands
 * input to the Builder, for the occurrence of specific Builder defined
 * variables, e.g. $hostnames, and replace them with their appropriate value.
 * Currently, only $hostnames is supported as a Builder defined variable.
 */
int
preprocess_cmd(scds_handle_t scds_handle, char *orig_cmd)
{
	char hostnames[SCDS_CMD_SIZE];
	int rc = 0;

	(void) memset(hostnames, '\0', SCDS_CMD_SIZE);
	if ((rc = compute_hostnames(scds_handle, hostnames)) != 0)
		return (rc);

	if ((rc = substitute_var(orig_cmd, "$hostnames", hostnames)) != 0)
		return (rc);

	return (rc);
}
