/*
** SellaNMS
** $Id: watchdog.h,v 1.8 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
*/

#ifndef __DGS_WATCHDOG_H
#define __DGS_WATCHDOG_H

#ifdef HAVE_CONFIG_H
	#include "config.h"
#endif

#include "defaults.h"
#include "common/util.h"
#include "common/storagedata.h"
#include "storage/storage.h"
#include <values.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stl/queue>
#include <stl/utility>

#define WATCHDOG_NICE_DEF 5
#define WATCHDOG_DELAY_DEF 60
#define WATCHDOG_DELAY_MIN 1
#define WATCHDOG_DELAY_MAX 32000
#define WATCHDOG_LAUNCHDELAY_DEF 2
#define WATCHDOG_LAUNCHDELAY_MIN 1
#define WATCHDOG_LAUNCHDELAY_MAX 60
#define WATCHDOG_LAUNCHDELAY_MLT 1000000
#define WATCHDOG_RESTARTLIMIT_DEF ULONG_MAX
#define WATCHDOG_RESTARTLIMIT_MIN 1
#define WATCHDOG_RESTARTLIMIT_MAX ULONG_MAX
#define WATCHDOG_CHECK_INTERVAL (1000000 * 3)
#define WATCHDOG_CLEANUP_DELAY 10

#define STATE_IDLE		0
#define STATE_PENDING	1
#define STATE_RUNNING	2
#define STATE_DISABLED	3

typedef struct limit_t {
	bool kill;
	int cpu;
	int memory;
	int timeout;
};

typedef struct daemon_t {
	int state;
	time_t start;
	pid_t pid;
	unsigned long restart_count;
	unsigned long restart_limit;

	char parent[64];
	char executable[255];
	char dir[255];
	char description[255];
	bool disable;
	bool restart;
	unsigned long delay;
	unsigned long launch_delay;
	long nice;
	bool startup;
	long order;
	long debug;
	char user[32];
	char group[32];
	char chroot[255];
	char pid_file[255];
	char stat_file[255];
	char log_file[255];
	char config_file[255];
	char facility[16];
	long umask;
	char cron[64];
};

class Watchdog {
	public:
		Watchdog();
		~Watchdog();
		virtual RESULT execute();
		virtual RESULT readConfig();
		virtual void killAllDaemons(int sig);

	protected:

	private:
		virtual void printConfig();
		void scheduler();

		slist<struct daemon_t*> daemons;
		struct daemon_t daemonDefault;
		int getTempFile(char* buf, size_t len);
		pid_t launchDaemon(const daemon_t *d);
		time_t nextStartTime(daemon_t *d);

		bool checkRunning(const daemon_t *d);
		bool checkWarn(const daemon_t *d);
		bool checkKill(const daemon_t *d);
		bool killDaemon(const daemon_t *d);
		long cronAdj(long val, long val_max, char *str);
		bool readCron(ConfigNode &node, char *cron, size_t len);

		Storage storage;
};

#endif

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