/*
** SellaNMS
** $Id: watchdog.cxx,v 1.19 2005/11/06 05:03:02 sella Exp $
** Copyright (c) 2001-2005 Digital Genesis Software, LLC. All Rights Reserved.
** Released under the GPL Version 2 License.
** http://www.digitalgenesis.com
*/

static char rcsid[] = "$Id: watchdog.cxx,v 1.19 2005/11/06 05:03:02 sella Exp $";

#include "daemon.h"
#include "watchdog.h"
#include "common/ip_util.h"
#include "storage/storage.h"
#include <fcntl.h>
#include <netdb.h>
#include <ctype.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/poll.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <linux/if.h>
#include <vector>
#include <errno.h>

#define BUF_SIZE 2024

extern ConfigNode* config;
extern bool interrupt;

Watchdog::Watchdog() {
}

Watchdog::~Watchdog() {
	/* Free the daemons. */
	for (slist<struct daemon_t*>::iterator it = daemons.begin(); it != daemons.end(); ++it) {
		delete *it;
	}
	daemons.clear();
}

RESULT Watchdog::readConfig() {
	RESULT result = SUCCESS;
	char buf[512];
	string str;
	vector<string> v, dv;
	vector<string>::iterator v_it, dv_it;
	ConfigNode node, subnode;
	daemon_t *d;
	struct stat stat_buf;

	config->assignNode("system module default", node);

	/* Read default daemon options. */
	memset(&daemonDefault, 0, sizeof(daemon_t));
	node.assignValue("nice", daemonDefault.nice, WATCHDOG_NICE_DEF);
	node.assignValue("order", daemonDefault.order, 0);
	node.assignValue("restart-limit", daemonDefault.restart_limit, WATCHDOG_RESTARTLIMIT_DEF, WATCHDOG_RESTARTLIMIT_MIN, WATCHDOG_RESTARTLIMIT_MAX);
	daemonDefault.disable = node.isNode("disable");
	node.assignValue("launch-delay", daemonDefault.launch_delay, WATCHDOG_LAUNCHDELAY_DEF, WATCHDOG_LAUNCHDELAY_MIN, WATCHDOG_LAUNCHDELAY_MAX, WATCHDOG_LAUNCHDELAY_MLT);
	daemonDefault.startup = node.isNode("schedule startup");
	node.assignValue("schedule delay", daemonDefault.delay, WATCHDOG_DELAY_DEF, WATCHDOG_DELAY_MIN, WATCHDOG_DELAY_MAX);
	readCron(node, daemonDefault.cron, sizeof(daemonDefault.cron));

	if (node.isNode("no-restart")) {
		daemonDefault.restart = false;
	} else {
		daemonDefault.restart = true;
	}

	if (node.assignValue("user", str)) {
		strncpy(daemonDefault.user, str.c_str(), sizeof(daemonDefault.user));
	}

	if (node.assignValue("group", str)) {
		strncpy(daemonDefault.group, str.c_str(), sizeof(daemonDefault.group));
	}

	if (node.assignValue("directory", str)) {
		strncpy(daemonDefault.dir, str.c_str(), sizeof(daemonDefault.dir));
	}

	if (subnode.assignValue("config", str)) {
		strncpy(daemonDefault.config_file, str.c_str(), sizeof(daemonDefault.config_file));
	}

	if (node.assignValue("executable", str)) {
		strncpy(daemonDefault.executable, str.c_str(), sizeof(daemonDefault.executable));
	}

	if (node.assignValue("description", str)) {
		strncpy(daemonDefault.description, str.c_str(), sizeof(daemonDefault.description));
	}

	/* Build list of daemons. */
	config->assignValues("system module", v);
	if (daemons.size() > 0) LMSG("DEBUG: Shouldn't we stop or clear the old set before adding them again?");
	for (v_it = v.begin(); v_it != v.end(); ++v_it) {
		/* Ignore the default section. */
		if (!v_it->compare("default")) {
			continue;
		}

		config->assignValues("system module " + *v_it, dv);
		for (dv_it = dv.begin(); dv_it != dv.end(); ++dv_it) {
			d = new daemon_t;
			memset(d, 0, sizeof(daemon_t));
			strncpy(d->parent, v_it->c_str(), sizeof(d->parent));

			str = "system module ";
			str.append(v_it->c_str());
			config->assignNode(str, subnode);

			/* Check for disable keyword at parents level. */
			d->disable = subnode.isNode("disable");

			/* Check for launch_delay keyword at parents level. */
			subnode.assignValue("launch-delay", d->launch_delay, daemonDefault.launch_delay);

			/* Check for delay keyword at parents level. */
			subnode.assignValue("schedule delay", d->delay, daemonDefault.delay);

			/* Check for startup keyword at parents level. */
			d->startup = subnode.isNode("schedule startup");

			/* Attempt to pull scheduler from parents level. */
			if (!readCron(subnode, d->cron, sizeof(d->cron))) {
				strncpy(d->cron, daemonDefault.cron, sizeof(d->cron));
			}

			str.append(" ");
			str.append(dv_it->c_str());
			config->assignNode(str, subnode);

			/* Use local scheduler, if available. */
			readCron(subnode, d->cron, sizeof(d->cron));

			if (subnode.assignValue("directory", str)) {
				strncpy(d->dir, str.c_str(), sizeof(d->dir));
			} else {
				strcpy(d->dir, daemonDefault.dir);
			}

			if (subnode.assignValue("executable", str)) {
				strncpy(d->executable, str.c_str(), sizeof(d->executable));
			} else {
				strcpy(d->executable, daemonDefault.executable);
			}

			/* Verify this is a valid daemon, before continuing on. */
			if (strlen(d->executable) < 1) {
				/* No executable specified. Skipping. */
				SAFE_DELETE(d);
				continue;
			} else {
				snprintf(buf, sizeof(buf), "%s/%s", d->dir, d->executable);
				if (stat(buf, &stat_buf) == 0) {
					if (!S_ISREG(stat_buf.st_mode)) {
						/* Disallow non-regular files as daemons. */
						LMSG("executable %s is not regular file", buf);

						SAFE_DELETE(d);
						continue;
					}
				} else {
					/* Not a valid filename. */
					LMSG("failed to stat %s", buf);

					SAFE_DELETE(d);
					continue;
				}
			}

			if (subnode.assignValue("config", str)) {
				strncpy(d->config_file, str.c_str(), sizeof(d->config_file));
			} else if (strlen(daemonDefault.config_file) > 0) {
				strcpy(d->config_file, daemonDefault.config_file);
			} else {
				strncpy(d->config_file, DEFAULT_CONFIG_FILE, sizeof(d->config_file));
			}

			if (subnode.assignValue("pid-file", str)) {
				strncpy(d->pid_file, str.c_str(), sizeof(d->pid_file));
			}

			if (subnode.assignValue("stat-file", str)) {
				strncpy(d->stat_file, str.c_str(), sizeof(d->stat_file));
			}

			if (subnode.assignValue("description", str)) {
				strncpy(d->description, str.c_str(), sizeof(d->description));
			} else {
				strcpy(d->description, daemonDefault.description);
			}

			if (subnode.assignValue("user", str)) {
				strncpy(d->user, str.c_str(), sizeof(d->user));
			} else {
				strcpy(d->user, daemonDefault.user);
			}

			if (subnode.assignValue("group", str)) {
				strncpy(d->group, str.c_str(), sizeof(d->group));
			} else {
				strcpy(d->group, daemonDefault.group);
			}

			if (!subnode.assignValue("nice", d->nice)) {
				d->nice = daemonDefault.nice;
			}

			subnode.assignValue("order", d->order, daemonDefault.order);

			subnode.assignValue("restart-limit", d->restart_limit, daemonDefault.restart_limit);

			if (!d->disable && !(d->disable = subnode.isNode("disable"))) {
				d->disable = daemonDefault.disable;
			}

			subnode.assignValue("schedule delay", d->delay, d->delay);

			if (!d->startup && !(d->startup = subnode.isNode("schedule startup"))) {
				d->startup = daemonDefault.startup;
			}

			if (subnode.isNode("no-restart")) {
				d->restart = false;
			} else {
				d->restart = daemonDefault.restart;
			}

			/* Set the initial start time. */
			d->start = nextStartTime(d);

			daemons.push_front(d);
		}
	}

	/* Configure Storage */
	if (storage.setConfig(*config) != SUCCESS) {
		result = FAILURE;
	}

	printConfig();

	return result;
}

bool Watchdog::readCron(ConfigNode &node, char *cron, size_t len) {
	int count = 0;
	string str, buf;

	if (!(count = (int) node.assignValue("schedule cron", buf))) {
		count = (int) node.assignValue("schedule second", str, "*");
		buf.append(str + " ");

		count += (int) node.assignValue("schedule minute", str, "*");
		buf.append(str + " ");

		count += (int) node.assignValue("schedule hour", str, "*");
		buf.append(str + " ");

		count += (int) node.assignValue("schedule dayofmonth", str, "*");
		buf.append(str + " ");

		count += (int) node.assignValue("schedule month", str, "*");
		buf.append(str + " ");

		count += (int) node.assignValue("schedule dayofweek", str, "*");
		buf.append(str);
	}

	if (count > 0) {
		strncpy(cron, buf.c_str(), len);
		return true;
	}

	return false;
}

void Watchdog::printConfig() {
	string str;
	vector<string> v;
	vector<string>::iterator v_it;

	slist<struct daemon_t*>::iterator it;

	if (!TRACE_ISSET(TRACE_CONFIG)) {
		return;
	}

	TRACE(TRACE_CONFIG, "default nice: %lu", daemonDefault.nice);
	TRACE(TRACE_CONFIG, "default order: %lu", daemonDefault.order);
	TRACE(TRACE_CONFIG, "default launch-delay: %lu sec", daemonDefault.launch_delay / WATCHDOG_LAUNCHDELAY_MLT);
	TRACE(TRACE_CONFIG, "default restart-limit: %lu", daemonDefault.restart_limit);
	TRACE(TRACE_CONFIG, "default disable: %s", daemonDefault.disable == false ? "false" : "true");
	TRACE(TRACE_CONFIG, "default schedule delay: %lu sec", daemonDefault.delay);
	TRACE(TRACE_CONFIG, "default schedule startup: %lu", daemonDefault.startup);
	TRACE(TRACE_CONFIG, "default no-restart: %s", daemonDefault.restart == false ? "false" : "true");
	TRACE(TRACE_CONFIG, "default user: %s", daemonDefault.user);
	TRACE(TRACE_CONFIG, "default group: %s", daemonDefault.group);
	TRACE(TRACE_CONFIG, "default directory: %s", daemonDefault.dir);
	TRACE(TRACE_CONFIG, "default config: %s", daemonDefault.config_file);
	TRACE(TRACE_CONFIG, "default executable: %s", daemonDefault.executable);
	TRACE(TRACE_CONFIG, "default description: %s", daemonDefault.description);

	if (config->assignValues("policy input", v)) {
		str.erase();
		for (v_it = v.begin(); v_it != v.end(); ++v_it) {
			str.append(*v_it + " ");
		}
		TRACE(TRACE_CONFIG, "policy input: %s", str.c_str());
	} else {
		TRACE(TRACE_CONFIG, "policy input: none");
	}

	if (config->assignValues("policy output", v)) {
		str.erase();
		for (v_it = v.begin(); v_it != v.end(); ++v_it) {
			str.append(*v_it + " ");
		}
		TRACE(TRACE_CONFIG, "policy output: %s", str.c_str());
	} else {
		TRACE(TRACE_CONFIG, "policy output: none");
	}

	return;
}

RESULT Watchdog::execute() {
	RESULT result = SUCCESS;

	TRACE(TRACE_THREAD, "Watchdog::execute() starting");

	scheduler();

	TRACE(TRACE_THREAD, "Watchdog::execute() exiting");

	return result;
}

void Watchdog::scheduler() {
	pid_t pid;
	time_t now;
	int status;
	hash_map<string, long> order;
	slist<struct daemon_t*>::iterator it;

	/* Initialize order structure to 0 for all parents. */
	for (it = daemons.begin(); it != daemons.end(); ++it) {
		order[(*it)->parent] = 0;
	}

	while (!interrupt && daemons.size() > 0) {
		now = time(NULL);

		/* Print out all daemon states. */
		if (TRACE_ISSET(TRACE_DUMP)) {
			TRACE(TRACE_DUMP, "[daemon states]");
			for (it = daemons.begin(); it != daemons.end(); ++it) {
				TRACE(TRACE_DUMP, "daemon: %s order: %d state: %d start: %d", (*it)->executable, (*it)->order, (*it)->state, (*it)->start);
			}
		}

		/* Examine RUNNING daemons */
		for (it = daemons.begin(); it != daemons.end(); ++it) {
			/* Identify failed daemons. */
			if ((*it)->state == STATE_RUNNING) {
				if (!checkRunning(*it)) {
					TRACE(TRACE_DEBUG, "'%s' is no longer running", (*it)->description);

					(*it)->state = STATE_IDLE;
				} else if (!checkWarn(*it)) {
					LMSG("'%s' has reached warning level", (*it)->description);
				} else if (!checkKill(*it)) {
					LMSG("'%s' has reached kill level", (*it)->description);

					if (!killDaemon(*it)) {
						LMSG("failed to kill %s pid %d", (*it)->description, (*it)->pid);
					} else {
						(*it)->state = STATE_IDLE;
					}
				}
			}
		}

		/* Update order */
		for (hash_map<string, long>::iterator h_it = order.begin(); h_it != order.end(); ++h_it) {
			bool order_done = true;
			int order_count = 0, order_new = MAXINT;
			TRACE(TRACE_INTERNAL, "parent '%s' moved to order %d", h_it->first.c_str(), h_it->second);

			/* Verify all daemons (for this parent) at the current order are IDLE. */
			for (it = daemons.begin(); it != daemons.end(); ++it) {
				if (!h_it->first.compare((*it)->parent) && h_it->second == (*it)->order && h_it->second > 0) {
					if ((*it)->state != STATE_DISABLED) {
						order_count++;

						/* Check for non-IDLE daemons. */
						if ((*it)->state != STATE_IDLE) {
							order_done = false;
						}
					}
				}
			}

			/* If the order was complete, or there are no daemons at this order. */
			if (order_done || order_count < 1) {
				/* Find next order, for this parent. */
				for (it = daemons.begin(); it != daemons.end(); ++it) {
					if (!h_it->first.compare((*it)->parent) && (*it)->state == STATE_IDLE) {
						if ((*it)->order > h_it->second && (*it)->order < order_new) {
							order_new = (*it)->order;
						}
					}
				}

				if (order_new == MAXINT) {
					h_it->second = 0;
				} else {
					h_it->second = order_new;
				}
			}
		}

		/* Update daemon state. Move from IDLE to PENDING or DISABLED. */
		for (it = daemons.begin(); it != daemons.end(); ++it) {
			if ((*it)->state == STATE_IDLE) {
				if ((*it)->disable) { /* Daemon is confiugred as disabled */
					(*it)->state = STATE_DISABLED;
				} else if ((*it)->restart && (*it)->restart_count >= (*it)->restart_limit) { /* restart limit reached */
					(*it)->state = STATE_DISABLED;
				} else if (!(*it)->restart && (*it)->restart_count >= 1) { /* non-restartable daemon */
					(*it)->state = STATE_DISABLED;
				} else if ((*it)->order == 0 || (*it)->order == order[(*it)->parent]) { /* If order 0 or current order, consider for PENDING state. */
					(*it)->state = STATE_PENDING;
				}
			}
		}

		/* Start all PENDING daemons. */
		for (it = daemons.begin(); it != daemons.end(); ++it) {
			/* If pending, and scheduled to start, start daemon. */
			if ((*it)->state == STATE_PENDING && now >= (*it)->start) {
				(*it)->restart_count++;
				(*it)->start = nextStartTime(*it); /* Set next start time. */

				if (((*it)->pid = launchDaemon(*it)) > 0) {
					LMSG("%s pid %d started", (*it)->description, (*it)->pid);

					(*it)->state = STATE_RUNNING;

					/* Provide daemon a delay before starting the next. */
					usleep((*it)->launch_delay);
				} else {
					LMSG("failed to start %s (disabling)", (*it)->description);

					(*it)->state = STATE_DISABLED;
				}
			}
		}

		if (!interrupt) {
			usleep(WATCHDOG_CHECK_INTERVAL);
		}
	}

	/* Cleanup children. */
	LMSG("asking children to shutdown (waiting up to %d sec)...", WATCHDOG_CLEANUP_DELAY);

#if 1
	killAllDaemons(SIGTERM);
	time_t wait = time(NULL) + WATCHDOG_CLEANUP_DELAY;
	while ((pid = waitpid(0, &status, WNOHANG)) != -1 && wait >= time(NULL)) {
		usleep(250000);
	}

	if (pid != -1) {
		LMSG("slaughtering children that failed to shutdown...");
		killAllDaemons(SIGKILL);
	}
#else
	#error "This doesn't work correctly... fix me."
	killAllDaemons(SIGTERM);
	time_t wait = time(NULL) + WATCHDOG_CLEANUP_DELAY;
	while (wait >= time(NULL)) {
		for (it = daemons.begin(); it != daemons.end(); ++it) {
			if ((*it)->state == STATE_RUNNING && !checkRunning(*it)) {
				LMSG("%s pid %d has shutdown", (*it)->description, (*it)->pid);
				(*it)->state = STATE_IDLE;
			}
		}
		usleep(250000);
	}

	int count = 0;
	for (it = daemons.begin(); it != daemons.end(); ++it) {
		if ((*it)->state == STATE_RUNNING) {
			LMSG("%s (%d) failed to shutdown", (*it)->description, (*it)->pid);
			count++;
		}
	}

	if (count > 0) {
		LMSG("slaughtering children that failed to shutdown...");
		killAllDaemons(SIGKILL);
	}
#endif
}

pid_t Watchdog::launchDaemon(const daemon_t *d) {
	pid_t pid;
	int err, arg = 0;
	char cmd[512], *args[32], buf[255];

	snprintf(buf, sizeof(buf), "%s [%s]", basename(d->executable), d->parent);
	args[arg++] = strdup(buf);
	args[arg++] = strdup("-f");

	if (d->nice != 0) {
		snprintf(buf, sizeof(buf), "%d", d->nice);
		args[arg++] = strdup("-n");
		args[arg++] = strdup(buf);
	}

	if (d->umask != 0) {
		snprintf(buf, sizeof(buf), "%d", d->umask);
		args[arg++] = strdup("-m");
		args[arg++] = strdup(buf);
	}

	if (strlen(d->user) > 0) {
		args[arg++] = strdup("-u");
		args[arg++] = strdup(d->user);
	}

	if (strlen(d->group) > 0) {
		args[arg++] = strdup("-g");
		args[arg++] = strdup(d->group);
	}

	if (strlen(d->config_file) > 0) {
		args[arg++] = strdup("-c");
		args[arg++] = strdup(d->config_file);
	}

	if (strlen(d->pid_file) > 0) {
		args[arg++] = strdup("-p");
		args[arg++] = strdup(d->pid_file);
	}

	if (strlen(d->stat_file) > 0) {
		args[arg++] = strdup("-s");
		args[arg++] = strdup(d->stat_file);
	}

	if (strlen(d->chroot) > 0) {
		args[arg++] = strdup("-r");
		args[arg++] = strdup(d->chroot);
	}

	if (strlen(d->facility) > 0) {
		args[arg++] = strdup("-F");
		args[arg++] = strdup(d->facility);
	}

	if (strlen(d->log_file) > 0) {
		args[arg++] = strdup("-l");
		args[arg++] = strdup(d->log_file);
	}

	if (d->debug != 0) {
		snprintf(buf, sizeof(buf), "%d", d->debug);
		args[arg++] = strdup("-d");
		args[arg++] = strdup(buf);
	}

	args[arg] = NULL;

	/* Base command line. */
	snprintf(cmd, sizeof(cmd), "%s/%s", d->dir, d->executable);

	TRACE(TRACE_DEBUG, "executing: '%s'", cmd);
	if (TRACE_ISSET(TRACE_DEBUG)) {
		TRACE(TRACE_DEBUG, "[arguments]");
		for (int i = 0; i < arg; i++) {
			TRACE(TRACE_DEBUG, " arg[%d]: %s", i, args[i]);
		}
	}

	if ((pid = fork()) == 0) {
#if 0
		fclose(stdin); /* Will no longer accept input (ie: Ctrl-C) */
		fclose(stdout); /* Our output to stdout will go unheard. */
		fclose(stderr); /* Our output to stderr will go unheard. */
#endif

		if ((err = execv(cmd, args)) == -1) {
			LMSG("failed to execute '%s'", cmd);

			for (int i = 0; i < arg; i++) {
				SAFE_FREE(args[i]);
			}

			exit(EXIT_FAILURE);
		}

		/* execv should never return. */
		abort();
	} else if (pid == -1) {
		LMSG("failed to fork() - aborting");
		abort();
	}

	/* Free args memory. */
	for (int i = 0; i < arg; i++) {
		SAFE_FREE(args[i]);
	}

	return pid;
}

time_t Watchdog::nextStartTime(daemon_t *d) {
	struct tm go_tm;
	time_t next_start;
	char buf[64], *ptr, *end;

	if (d->startup) {
		d->startup = false; /* Only use 'startup' once. */
		next_start = 0;
	} else if (strlen(d->cron) >= 11) { /* Minimum valid cron is 11 chars. */
      next_start = time(NULL);
      localtime_r(&(next_start), &go_tm);

      memset(buf, 0, sizeof(buf));
      strncpy(buf, d->cron, sizeof(buf));
      ptr = end = buf;
      for (int i = 0; i < 6 && end != NULL; i++) {
         if (end = strchr(ptr, ' ')) {
            *end = '\0';
         }

         switch (i) {
            case 0: /* second */
               go_tm.tm_sec = cronAdj(go_tm.tm_sec, 60, ptr);
               break;
            case 1: /* minute */
               go_tm.tm_min = cronAdj(go_tm.tm_min, 60, ptr);
               break;
            case 2: /* hour */
               go_tm.tm_hour = cronAdj(go_tm.tm_hour, 24, ptr);
               break;
            case 3: /* dayofmonth */
               go_tm.tm_mday = cronAdj(go_tm.tm_mday + 1, 31, ptr) - 1;
               break;
            case 4: /* month */
               go_tm.tm_mon = cronAdj(go_tm.tm_mon + 1, 12, ptr) - 1;
               break;
            case 5: /* dayofweek - Special since mktime ignores this one. */
               go_tm.tm_mday += cronAdj(go_tm.tm_wday, 7, ptr) - go_tm.tm_wday;
               break;
         }

         /* Normalize the structure, so things don't get whacked. */
         if (mktime(&go_tm) == -1) {
				LMSG("invalid schedule '%s' - using delay", d->cron);
				
				d->cron[0] = '\0'; /* Wipe cron. */
				next_start = time(NULL) + d->delay;

				return next_start;
			}

         /* Increment to next token. */
         ptr = end + 1;
      }

      /* Set next start based on cron. */
      next_start = 1 + mktime(&go_tm) + d->delay;

      /* Zero out delay so we don't use it again. */
      d->delay = 0;
	} else if (d->delay > 0 && d->restart_count > 0) {
		next_start = time(NULL) + d->delay;
	} else {
		next_start = 0;
	}

	return next_start;
}

void Watchdog::killAllDaemons(int sig) {
	slist<struct daemon_t*>::iterator it;
	for (it = daemons.begin(); it != daemons.end(); ++it) {
		if ((*it)->state == STATE_RUNNING) {
			kill((*it)->pid, sig);
		}
	}
}

bool Watchdog::checkRunning(const daemon_t *d) {
	pid_t pid;
	int err, status = 0;

	if (d->pid < 1) {
		LMSG("invalid pid passed to checkRunning()");
		return false;
	}

	pid = waitpid(d->pid, &status, WNOHANG);
	if (pid == -1) {
		switch (errno) {
			case EINVAL:
				LMSG("invalid option specified");
				break;

			case ECHILD:
				LMSG("process does not exist (or isn't mine)");
				break;

			default:
				LMSG("unknown error");
		}

		return false;
	} else if (pid > 0) {
		if (WIFEXITED(status)) {
			LMSG("%s pid %d exited with status %d", d->description, d->pid, WEXITSTATUS(status));
#ifdef WCOREDUMP
		} else if (WCOREDUMP(status)) {
			if (WIFSIGNALED(status)) {
				LMSG("%s pid %d exited with a core dump (signal %d)", d->description, d->pid, WTERMSIG(status));
			} else {
				LMSG("%s pid %d exited with a core dump", d->description, d->pid);
			}
#endif
		} else if (WIFSTOPPED(status)) {
			LMSG("%s pid %d has stopped with signal %d", d->description, d->pid, WSTOPSIG(status));

		} else if (WIFSIGNALED(status)) {
			LMSG("%s pid %d exited due to uncaught signal %d", d->description, d->pid, WTERMSIG(status));
		} else {
			LMSG("%s pid %d exited (unknown reason - status %d)", d->description, d->pid, status);
		}

		return false;
	}

	TRACE(TRACE_INTERNAL, "%s pid %d still running", d->description, d->pid);

	return true;
}

bool Watchdog::checkWarn(const daemon_t *d) {
	return true;
}

bool Watchdog::checkKill(const daemon_t *d) {
	return true;
}

bool Watchdog::killDaemon(const daemon_t *d) {
	return true;
}

int Watchdog::getTempFile(char* buf, size_t len) {
	if (getenv("TMPDIR") != NULL) {
		snprintf(buf, len, "%s/%s-XXXXXX", getenv("TMPDIR"), "sella_nms");
	} else {
		snprintf(buf, len, "%s/%s-XXXXXX", P_tmpdir, "sella_nms");
	}

	return mkstemp(buf);
}

long Watchdog::cronAdj(long val, long val_max, char *str) {
	char *ptr;
	long ret_val, tmp, tmp2;

	assert(str != NULL);

	if (!strcmp(str, "*")) { /* All values. */
		ret_val = val;
	} else if (!strncmp(str, "*/", 2)) { /* Every X interval. */
		tmp = atol(str + 2);
		ret_val = (tmp > 0 && val % tmp > 0) ? (val + tmp) - (val % tmp) : val;
	} else if ((ptr = index(str, '-')) != NULL && str[0] != '-') { /* Ranged */
		ptr++;
		tmp = atol(str);
		tmp2 = atol(ptr);

		if (val >= tmp && val <= tmp2) {
			ret_val = val;
		} else if (val < tmp) {
			ret_val = tmp;
		} else {
			ret_val = val_max + tmp;
		}
	} else if ((ptr = index(str, ',')) != NULL && str[0] != ',') { /* Comma seperated. */
		*ptr = '\0';
		tmp = atol(str);
		tmp2 = val_max;
		do {
			/* Grab the first thats greater than val. */
			if (tmp >= val) {
				ret_val = tmp;
				break;
			}

			/* Track smallest value. */
			if (tmp < tmp2)
				tmp2 = tmp;

			/* Get next available time. */
			if ((ptr = index(ptr + 1, ',')) != NULL) {
				*ptr = '\0';
				tmp = atol(ptr + 1);
			} else {
				ret_val = val_max + tmp2;
			}
		} while (ptr);
	} else { /* Raw number: Set occurance of passed time. */
		tmp = atol(str);
		ret_val = (val > tmp) ? val_max + tmp : tmp;
	}

	assert(ret_val >= 0);

	return ret_val;
}

/*
** Local Variables:
** c-basic-offset: 3
** tab-width: 3
** End:
** vim600: fdm=marker
** vim: noet ts=3 sw=3
*/
