Пример #1
0
void setup (void) {

	init_event_queue();
	setup_objects();

	retain_state_information = TRUE;
	retention_file = nm_strdup("/tmp/retention.dat");
	temp_file = nm_strdup("/tmp/retention.tmp");

	initialize_retention_data();

}
Пример #2
0
host *create_host(const char *name)
{
	host *new_host = NULL;

	if (name == NULL || !strcmp(name, "")) {
		nm_log(NSLOG_CONFIG_ERROR, "Error: Host name is NULL\n");
		return NULL;
	}

	if (contains_illegal_object_chars(name) == TRUE) {
		nm_log(NSLOG_VERIFICATION_ERROR, "Error: The name of host '%s' contains one or more illegal characters.", name);
		return NULL;
	}

	new_host = nm_calloc(1, sizeof(*new_host));

	new_host->name = new_host->display_name = new_host->alias = new_host->address = nm_strdup(name);
	new_host->child_hosts = g_tree_new_full((GCompareDataFunc)g_strcmp0, NULL, g_free, NULL);
	new_host->parent_hosts = g_tree_new_full((GCompareDataFunc)g_strcmp0, NULL, g_free, NULL);
	new_host->check_type = CHECK_TYPE_ACTIVE;
	new_host->state_type = HARD_STATE;
	new_host->acknowledgement_type = ACKNOWLEDGEMENT_NONE;
	new_host->check_options = CHECK_OPTION_NONE;


	return new_host;
}
Пример #3
0
/* send event handler data to broker */
int broker_event_handler(int type, int flags, int attr, int eventhandler_type, void *data, int state, int state_type, struct timeval start_time, struct timeval end_time, double exectime, int timeout, int early_timeout, int retcode, char *cmd, char *cmdline, char *output)
{
	service *temp_service = NULL;
	host *temp_host = NULL;
	char *command_buf = NULL;
	char *command_name = NULL;
	char *command_args = NULL;
	nebstruct_event_handler_data ds;
	int return_code = OK;

	if (!(event_broker_options & BROKER_EVENT_HANDLERS))
		return return_code;

	if (data == NULL)
		return ERROR;

	/* get command name/args */
	if (cmd != NULL) {
		command_buf = nm_strdup(cmd);
		command_name = strtok(command_buf, "!");
		command_args = strtok(NULL, "\x0");
	}

	/* fill struct with relevant data */
	ds.type = type;
	ds.flags = flags;
	ds.attr = attr;
	get_broker_timestamp(&ds.timestamp);

	ds.eventhandler_type = eventhandler_type;
	if (eventhandler_type == SERVICE_EVENTHANDLER || eventhandler_type == GLOBAL_SERVICE_EVENTHANDLER) {
		temp_service = (service *)data;
		ds.host_name = temp_service->host_name;
		ds.service_description = temp_service->description;
	} else {
		temp_host = (host *)data;
		ds.host_name = temp_host->name;
		ds.service_description = NULL;
	}
	ds.object_ptr = data;
	ds.state = state;
	ds.state_type = state_type;
	ds.start_time = start_time;
	ds.end_time = end_time;
	ds.timeout = timeout;
	ds.command_name = command_name;
	ds.command_args = command_args;
	ds.command_line = cmdline;
	ds.early_timeout = early_timeout;
	ds.execution_time = exectime;
	ds.return_code = retcode;
	ds.output = output;

	/* make callbacks */
	return_code = neb_make_callbacks(NEBCALLBACK_EVENT_HANDLER_DATA, (void *)&ds);

	nm_free(command_buf);

	return return_code;
}
Пример #4
0
/* send contact notification data to broker */
int broker_contact_notification_method_data(int type, int flags, int attr, int notification_type, int reason_type, struct timeval start_time, struct timeval end_time, void *data, contact *cntct, char *cmd, char *ack_author, char *ack_data, int escalated)
{
	nebstruct_contact_notification_method_data ds;
	host *temp_host = NULL;
	service *temp_service = NULL;
	char *command_buf = NULL;
	char *command_name = NULL;
	char *command_args = NULL;
	int return_code = OK;

	if (!(event_broker_options & BROKER_NOTIFICATIONS))
		return return_code;

	/* get command name/args */
	if (cmd != NULL) {
		command_buf = nm_strdup(cmd);
		command_name = strtok(command_buf, "!");
		command_args = strtok(NULL, "\x0");
	}

	/* fill struct with relevant data */
	ds.type = type;
	ds.flags = flags;
	ds.attr = attr;
	get_broker_timestamp(&ds.timestamp);

	ds.notification_type = notification_type;
	ds.start_time = start_time;
	ds.end_time = end_time;
	ds.reason_type = reason_type;
	ds.contact_name = cntct->name;
	ds.command_name = command_name;
	ds.command_args = command_args;
	if (notification_type == SERVICE_NOTIFICATION) {
		temp_service = (service *)data;
		ds.host_name = temp_service->host_name;
		ds.service_description = temp_service->description;
		ds.state = temp_service->current_state;
		ds.output = temp_service->plugin_output;
	} else {
		temp_host = (host *)data;
		ds.host_name = temp_host->name;
		ds.service_description = NULL;
		ds.state = temp_host->current_state;
		ds.output = temp_host->plugin_output;
	}
	ds.object_ptr = data;
	ds.contact_ptr = (void *)cntct;
	ds.ack_author = ack_author;
	ds.ack_data = ack_data;
	ds.escalated = escalated;

	/* make callbacks */
	return_code = neb_make_callbacks(NEBCALLBACK_CONTACT_NOTIFICATION_METHOD_DATA, (void *)&ds);

	nm_free(command_buf);

	return return_code;
}
Пример #5
0
/* send service check data to broker */
int broker_service_check(int type, int flags, int attr, service *svc, int check_type, struct timeval start_time, struct timeval end_time, char *cmd, double latency, double exectime, int timeout, int early_timeout, int retcode, char *cmdline, check_result *cr)
{
	char *command_buf = NULL;
	char *command_name = NULL;
	char *command_args = NULL;
	nebstruct_service_check_data ds;
	int return_code = OK;

	if (!(event_broker_options & BROKER_SERVICE_CHECKS))
		return OK;

	if (svc == NULL)
		return ERROR;

	/* get command name/args */
	if (cmd != NULL) {
		command_buf = nm_strdup(cmd);
		command_name = strtok(command_buf, "!");
		command_args = strtok(NULL, "\x0");
	}

	/* fill struct with relevant data */
	ds.type = type;
	ds.flags = flags;
	ds.attr = attr;
	get_broker_timestamp(&ds.timestamp);

	ds.host_name = svc->host_name;
	ds.service_description = svc->description;
	ds.object_ptr = (void *)svc;
	ds.check_type = check_type;
	ds.current_attempt = svc->current_attempt;
	ds.max_attempts = svc->max_attempts;
	ds.state = svc->current_state;
	ds.state_type = svc->state_type;
	ds.timeout = timeout;
	ds.command_name = command_name;
	ds.command_args = command_args;
	ds.command_line = cmdline;
	ds.start_time = start_time;
	ds.end_time = end_time;
	ds.early_timeout = early_timeout;
	ds.execution_time = exectime;
	ds.latency = latency;
	ds.return_code = retcode;
	ds.output = svc->plugin_output;
	ds.long_output = svc->long_plugin_output;
	ds.perf_data = svc->perf_data;
	ds.check_result_ptr = cr;

	/* make callbacks */
	return_code = neb_make_callbacks(NEBCALLBACK_SERVICE_CHECK_DATA, (void *)&ds);

	/* free data */
	nm_free(command_buf);

	return return_code;
}
Пример #6
0
timeperiod *create_timeperiod(const char *name, const char *alias)
{
	timeperiod *new_timeperiod = NULL;

	/* make sure we have the data we need */
	if ((name == NULL || !strcmp(name, "")) || (alias == NULL || !strcmp(alias, ""))) {
		nm_log(NSLOG_CONFIG_ERROR, "Error: Name or alias for timeperiod is NULL\n");
		return NULL;
	}
	if (contains_illegal_object_chars(name) == TRUE) {
		nm_log(NSLOG_VERIFICATION_ERROR, "Error: The name of time period '%s' contains one or more illegal characters.", name);
		return NULL;
	}

	new_timeperiod = nm_calloc(1, sizeof(*new_timeperiod));

	/* copy string vars */
	new_timeperiod->name = nm_strdup(name);
	new_timeperiod->alias = alias ? nm_strdup(alias) : new_timeperiod->name;

	return new_timeperiod;
}
Пример #7
0
/* initialize status data */
int xsddefault_initialize_status_data(const char *cfgfile)
{
	nagios_macros *mac;

	/* initialize locations if necessary */
	if (!status_file)
		status_file = nm_strdup(get_default_status_file());

	/* make sure we have what we need */
	if (status_file == NULL)
		return ERROR;

	mac = get_global_macros();
	/* save the status file macro */
	nm_free(mac->x[MACRO_STATUSDATAFILE]);
	mac->x[MACRO_STATUSDATAFILE] = nm_strdup(status_file);
	strip(mac->x[MACRO_STATUSDATAFILE]);

	/* delete the old status log (it might not exist) */
	if (status_file)
		unlink(status_file);

	return OK;
}
Пример #8
0
service *create_service(host *hst, const char *description)
{
    service *new_service = NULL;
    servicesmember *new_servicesmember = NULL;

    if (!hst) {
        nm_log(NSLOG_CONFIG_ERROR, "Error: No host provided for service '%s'\n",
               description);
        return NULL;
    }

    if (description == NULL || !*description) {
        nm_log(NSLOG_CONFIG_ERROR, "Error: Found service on host '%s' with no service description\n", hst->name);
        return NULL;
    }

    if (contains_illegal_object_chars(description) == TRUE) {
        nm_log(NSLOG_VERIFICATION_ERROR, "Error: The description string for service '%s' on host '%s' contains one or more illegal characters.", description, hst->name);
        return NULL;
    }

    /* allocate memory */
    new_service = nm_calloc(1, sizeof(*new_service));

    new_service->host_ptr = hst;
    new_service->host_name = hst->name;

    new_servicesmember = nm_calloc(1, sizeof(servicesmember));
    new_servicesmember->host_name = new_service->host_name;
    new_servicesmember->service_description = new_service->description;
    new_servicesmember->service_ptr = new_service;
    new_servicesmember->next = hst->services;
    hst->services = new_servicesmember;
    hst->total_services++;

    new_service->description = nm_strdup(description);
    new_service->display_name = new_service->description;
    new_service->acknowledgement_type = ACKNOWLEDGEMENT_NONE;
    new_service->check_type = CHECK_TYPE_ACTIVE;
    new_service->state_type = HARD_STATE;
    new_service->check_options = CHECK_OPTION_NONE;

    return new_service;
}
Пример #9
0
int qh_register_handler(const char *name, const char *description, unsigned int options, qh_handler handler)
{

	struct query_handler *qh;

	g_return_val_if_fail(qh_table != NULL, -1);
	g_return_val_if_fail(name != NULL, -1);

	if (!handler) {
		nm_log(NSLOG_RUNTIME_ERROR, "qh: Failed to register handler '%s': No handler function specified\n", name);
		return -1;
	}

	if (strlen(name) > 128) {
		nm_log(NSLOG_RUNTIME_ERROR, "qh: Failed to register handler '%s': Name too long\n", name);
		return -ENAMETOOLONG;
	}

	/* names must be unique */
	if (qh_find_handler(name)) {
		nm_log(NSLOG_RUNTIME_WARNING, "qh: Handler '%s' registered more than once\n", name);
		return -1;
	}

	qh = nm_calloc(1, sizeof(*qh));
	qh->name = name;
	qh->description = description;
	qh->handler = handler;
	qh->options = options;
	qh->next_qh = qhandlers;
	if (qhandlers)
		qhandlers->prev_qh = qh;
	qhandlers = qh;

	g_hash_table_insert(qh_table, nm_strdup(qh->name), qh);

	return 0;
}
Пример #10
0
/* adds a new exclusion to a timeperiod */
timeperiodexclusion *add_exclusion_to_timeperiod(timeperiod *period, char *name)
{
	timeperiodexclusion *new_timeperiodexclusion = NULL;
	timeperiod *temp_timeperiod2;

	/* make sure we have enough data */
	if (period == NULL || name == NULL)
		return NULL;

	temp_timeperiod2 = find_timeperiod(name);
	if (temp_timeperiod2 == NULL) {
		nm_log(NSLOG_VERIFICATION_ERROR, "Error: Excluded time period '%s' specified in timeperiod '%s' is not defined anywhere!", name, period->name);
		return NULL;
	}

	new_timeperiodexclusion = nm_malloc(sizeof(timeperiodexclusion));
	new_timeperiodexclusion->timeperiod_name = nm_strdup(name);
	new_timeperiodexclusion->timeperiod_ptr = temp_timeperiod2;

	new_timeperiodexclusion->next = period->exclusions;
	period->exclusions = new_timeperiodexclusion;

	return new_timeperiodexclusion;
}
Пример #11
0
int setup_service_variables(service *new_service, const char *display_name, const char *check_command, const char *check_period, int initial_state, int max_attempts, int accept_passive_checks, double check_interval, double retry_interval, double notification_interval, double first_notification_delay, char *notification_period, int notification_options, int notifications_enabled, int is_volatile, const char *event_handler, int event_handler_enabled, int checks_enabled, int flap_detection_enabled, double low_flap_threshold, double high_flap_threshold, int flap_detection_options, int stalking_options, int process_perfdata, int check_freshness, int freshness_threshold, const char *notes, const char *notes_url, const char *action_url, const char *icon_image, const char *icon_image_alt, int retain_status_information, int retain_nonstatus_information, int obsess, unsigned int hourly_value)
{
    timeperiod *cp = NULL, *np = NULL;
    command *cmd;

    /* make sure we have everything we need */
    if (notification_period && !(np = find_timeperiod(notification_period))) {
        nm_log(NSLOG_CONFIG_ERROR, "Error: notification_period '%s' for service '%s' on host '%s' could not be found!\n", notification_period, new_service->description, new_service->host_name);
        return -1;
    }
    if (check_period && !(cp = find_timeperiod(check_period))) {
        nm_log(NSLOG_CONFIG_ERROR, "Error: check_period '%s' for service '%s' on host '%s' not found!\n",
               check_period, new_service->description, new_service->host_name);
        return -1;
    }

    if (check_command == NULL || !*check_command) {
        nm_log(NSLOG_CONFIG_ERROR, "Error: No check command provided for service '%s' on host '%s'\n", new_service->check_command, new_service->description);
        return -1;
    }
    cmd = find_bang_command(check_command);
    if (cmd == NULL) {
        nm_log(NSLOG_VERIFICATION_ERROR, "Error: Service check command '%s' specified in service '%s' for host '%s' not defined anywhere!", check_command, new_service->description, new_service->host_name);
        return -1;
    }


    if (max_attempts <= 0) {
        nm_log(NSLOG_CONFIG_ERROR, "Error: max_check_attempts must be a positive integer for service '%s' on host '%s'\n", new_service->description, new_service->host_name);
        return -1;
    }
    if (check_interval < 0) {
        nm_log(NSLOG_CONFIG_ERROR, "Error: check_interval must be a non-negative integer for service '%s' on host '%s'\n", new_service->description, new_service->host_name);
        return -1;
    }
    if (retry_interval <= 0) {
        nm_log(NSLOG_CONFIG_ERROR, "Error: retry_interval must be a positive integer for service '%s' on host '%s'\n", new_service->description, new_service->host_name);
        return -1;
    }
    if (notification_interval < 0) {
        nm_log(NSLOG_CONFIG_ERROR, "Error: notification_interval must be a non-negative integer for service '%s' on host '%s'\n", new_service->description, new_service->host_name);
        return -1;
    }
    if (first_notification_delay < 0) {
        nm_log(NSLOG_CONFIG_ERROR, "Error: first_notification_delay must be a non-negative integer for service '%s' on host '%s'\n", new_service->description, new_service->host_name);
        return -1;
    }

    /* duplicate vars, but assign what we can */
    new_service->notification_period_ptr = np;
    new_service->check_period_ptr = cp;
    new_service->check_period = cp ? cp->name : NULL;
    new_service->notification_period = np ? np->name : NULL;
    new_service->check_command = nm_strdup(check_command);
    new_service->check_command_ptr = cmd;
    if (display_name) {
        new_service->display_name = nm_strdup(display_name);
    }
    if (event_handler) {
        new_service->event_handler = nm_strdup(event_handler);
        new_service->event_handler_ptr = find_bang_command(event_handler);
        if (new_service->event_handler_ptr == NULL) {
            nm_log(NSLOG_VERIFICATION_ERROR, "Error: Event handler command '%s' specified in service '%s' for host '%s' not defined anywhere", new_service->event_handler, new_service->description, new_service->host_name);
            return -1;
        }
    }
    if (notes) {
        new_service->notes = nm_strdup(notes);
    }
    if (notes_url) {
        new_service->notes_url = nm_strdup(notes_url);
    }
    if (action_url) {
        new_service->action_url = nm_strdup(action_url);
    }
    if (icon_image) {
        new_service->icon_image = nm_strdup(icon_image);
    }
    if (icon_image_alt) {
        new_service->icon_image_alt = nm_strdup(icon_image_alt);
    }

    new_service->hourly_value = hourly_value;
    new_service->check_interval = check_interval;
    new_service->retry_interval = retry_interval;
    new_service->max_attempts = max_attempts;
    new_service->notification_interval = notification_interval;
    new_service->first_notification_delay = first_notification_delay;
    new_service->notification_options = notification_options;
    new_service->is_volatile = (is_volatile > 0) ? TRUE : FALSE;
    new_service->flap_detection_enabled = (flap_detection_enabled > 0) ? TRUE : FALSE;
    new_service->low_flap_threshold = low_flap_threshold;
    new_service->high_flap_threshold = high_flap_threshold;
    new_service->flap_detection_options = flap_detection_options;
    new_service->stalking_options = stalking_options;
    new_service->process_performance_data = (process_perfdata > 0) ? TRUE : FALSE;
    new_service->check_freshness = (check_freshness > 0) ? TRUE : FALSE;
    new_service->freshness_threshold = freshness_threshold;
    new_service->accept_passive_checks = (accept_passive_checks > 0) ? TRUE : FALSE;
    new_service->event_handler_enabled = (event_handler_enabled > 0) ? TRUE : FALSE;
    new_service->checks_enabled = (checks_enabled > 0) ? TRUE : FALSE;
    new_service->retain_status_information = (retain_status_information > 0) ? TRUE : FALSE;
    new_service->retain_nonstatus_information = (retain_nonstatus_information > 0) ? TRUE : FALSE;
    new_service->notifications_enabled = (notifications_enabled > 0) ? TRUE : FALSE;
    new_service->obsess = (obsess > 0) ? TRUE : FALSE;
    new_service->current_attempt = (initial_state == STATE_OK) ? 1 : max_attempts;
    new_service->current_state = initial_state;
    new_service->last_state = initial_state;
    new_service->last_hard_state = initial_state;

    /* check the service check_command */

    return 0;
}
Пример #12
0
/* reset all system-wide variables, so when we've receive a SIGHUP we can restart cleanly */
int reset_variables(void)
{

	log_file = nm_strdup(get_default_log_file());
	temp_file = nm_strdup(get_default_temp_file());
	temp_path = nm_strdup(get_default_temp_path());
	check_result_path = nm_strdup(get_default_check_result_path());
	command_file = nm_strdup(get_default_command_file());
	qh_socket_path = nm_strdup(get_default_query_socket());
	if (lock_file) /* this is kept across restarts */
		free(lock_file);
	lock_file = nm_strdup(get_default_lock_file());
	log_archive_path = nm_strdup(get_default_log_archive_path());
	debug_file = nm_strdup(get_default_debug_file());

	object_cache_file = nm_strdup(get_default_object_cache_file());
	object_precache_file = nm_strdup(get_default_precached_object_file());

	use_regexp_matches = FALSE;
	use_true_regexp_matching = FALSE;

	use_syslog = DEFAULT_USE_SYSLOG;
	log_service_retries = DEFAULT_LOG_SERVICE_RETRIES;
	log_host_retries = DEFAULT_LOG_HOST_RETRIES;
	log_initial_states = DEFAULT_LOG_INITIAL_STATES;

	enable_notification_suppression_reason_logging = DEFAULT_NSR_LOGGING;
	log_notifications = DEFAULT_NOTIFICATION_LOGGING;
	log_event_handlers = DEFAULT_LOG_EVENT_HANDLERS;
	log_external_commands = DEFAULT_LOG_EXTERNAL_COMMANDS;
	log_passive_checks = DEFAULT_LOG_PASSIVE_CHECKS;

	logging_options = NSLOG_RUNTIME_ERROR | NSLOG_RUNTIME_WARNING | NSLOG_VERIFICATION_ERROR | NSLOG_VERIFICATION_WARNING | NSLOG_CONFIG_ERROR | NSLOG_CONFIG_WARNING | NSLOG_PROCESS_INFO | NSLOG_HOST_NOTIFICATION | NSLOG_SERVICE_NOTIFICATION | NSLOG_EVENT_HANDLER | NSLOG_EXTERNAL_COMMAND | NSLOG_PASSIVE_CHECK | NSLOG_HOST_UP | NSLOG_HOST_DOWN | NSLOG_HOST_UNREACHABLE | NSLOG_SERVICE_OK | NSLOG_SERVICE_WARNING | NSLOG_SERVICE_UNKNOWN | NSLOG_SERVICE_CRITICAL | NSLOG_INFO_MESSAGE;

	syslog_options = NSLOG_RUNTIME_ERROR | NSLOG_RUNTIME_WARNING | NSLOG_VERIFICATION_ERROR | NSLOG_VERIFICATION_WARNING | NSLOG_CONFIG_ERROR | NSLOG_CONFIG_WARNING | NSLOG_PROCESS_INFO | NSLOG_HOST_NOTIFICATION | NSLOG_SERVICE_NOTIFICATION | NSLOG_EVENT_HANDLER | NSLOG_EXTERNAL_COMMAND | NSLOG_PASSIVE_CHECK | NSLOG_HOST_UP | NSLOG_HOST_DOWN | NSLOG_HOST_UNREACHABLE | NSLOG_SERVICE_OK | NSLOG_SERVICE_WARNING | NSLOG_SERVICE_UNKNOWN | NSLOG_SERVICE_CRITICAL | NSLOG_INFO_MESSAGE;

	service_check_timeout = DEFAULT_SERVICE_CHECK_TIMEOUT;
	host_check_timeout = DEFAULT_HOST_CHECK_TIMEOUT;
	event_handler_timeout = DEFAULT_EVENT_HANDLER_TIMEOUT;
	notification_timeout = DEFAULT_NOTIFICATION_TIMEOUT;
	ocsp_timeout = DEFAULT_OCSP_TIMEOUT;
	ochp_timeout = DEFAULT_OCHP_TIMEOUT;

	interval_length = DEFAULT_INTERVAL_LENGTH;

	use_aggressive_host_checking = DEFAULT_AGGRESSIVE_HOST_CHECKING;
	cached_host_check_horizon = DEFAULT_CACHED_HOST_CHECK_HORIZON;
	cached_service_check_horizon = DEFAULT_CACHED_SERVICE_CHECK_HORIZON;
	enable_predictive_host_dependency_checks = DEFAULT_ENABLE_PREDICTIVE_HOST_DEPENDENCY_CHECKS;
	enable_predictive_service_dependency_checks = DEFAULT_ENABLE_PREDICTIVE_SERVICE_DEPENDENCY_CHECKS;

	soft_state_dependencies = FALSE;

	retain_state_information = FALSE;
	retention_update_interval = DEFAULT_RETENTION_UPDATE_INTERVAL;
	use_retained_program_state = TRUE;
	use_retained_scheduling_info = FALSE;
	retention_scheduling_horizon = DEFAULT_RETENTION_SCHEDULING_HORIZON;
	modified_host_process_attributes = MODATTR_NONE;
	modified_service_process_attributes = MODATTR_NONE;
	retained_host_attribute_mask = 0L;
	retained_service_attribute_mask = 0L;
	retained_process_host_attribute_mask = 0L;
	retained_process_service_attribute_mask = 0L;
	retained_contact_host_attribute_mask = 0L;
	retained_contact_service_attribute_mask = 0L;

	check_reaper_interval = DEFAULT_CHECK_REAPER_INTERVAL;
	max_check_reaper_time = DEFAULT_MAX_REAPER_TIME;
	max_check_result_file_age = DEFAULT_MAX_CHECK_RESULT_AGE;
	service_freshness_check_interval = DEFAULT_FRESHNESS_CHECK_INTERVAL;
	host_freshness_check_interval = DEFAULT_FRESHNESS_CHECK_INTERVAL;

	check_external_commands = DEFAULT_CHECK_EXTERNAL_COMMANDS;
	check_orphaned_services = DEFAULT_CHECK_ORPHANED_SERVICES;
	check_orphaned_hosts = DEFAULT_CHECK_ORPHANED_HOSTS;
	check_service_freshness = DEFAULT_CHECK_SERVICE_FRESHNESS;
	check_host_freshness = DEFAULT_CHECK_HOST_FRESHNESS;

	log_rotation_method = LOG_ROTATION_NONE;

	last_log_rotation = 0L;

	max_parallel_service_checks = DEFAULT_MAX_PARALLEL_SERVICE_CHECKS;
	currently_running_service_checks = 0;

	enable_notifications = TRUE;
	execute_service_checks = TRUE;
	accept_passive_service_checks = TRUE;
	execute_host_checks = TRUE;
	accept_passive_service_checks = TRUE;
	enable_event_handlers = TRUE;
	obsess_over_services = FALSE;
	obsess_over_hosts = FALSE;

	next_comment_id = 0L; /* comment and downtime id get initialized to nonzero elsewhere */
	next_downtime_id = 0L;
	next_event_id = 1;
	next_notification_id = 1;

	status_update_interval = DEFAULT_STATUS_UPDATE_INTERVAL;

	event_broker_options = BROKER_NOTHING;

	time_change_threshold = DEFAULT_TIME_CHANGE_THRESHOLD;

	enable_flap_detection = DEFAULT_ENABLE_FLAP_DETECTION;
	low_service_flap_threshold = DEFAULT_LOW_SERVICE_FLAP_THRESHOLD;
	high_service_flap_threshold = DEFAULT_HIGH_SERVICE_FLAP_THRESHOLD;
	low_host_flap_threshold = DEFAULT_LOW_HOST_FLAP_THRESHOLD;
	high_host_flap_threshold = DEFAULT_HIGH_HOST_FLAP_THRESHOLD;

	process_performance_data = DEFAULT_PROCESS_PERFORMANCE_DATA;

	translate_passive_host_checks = DEFAULT_TRANSLATE_PASSIVE_HOST_CHECKS;
	passive_host_checks_are_soft = DEFAULT_PASSIVE_HOST_CHECKS_SOFT;

	additional_freshness_latency = DEFAULT_ADDITIONAL_FRESHNESS_LATENCY;

	debug_level = DEFAULT_DEBUG_LEVEL;
	debug_verbosity = DEFAULT_DEBUG_VERBOSITY;
	max_debug_file_size = DEFAULT_MAX_DEBUG_FILE_SIZE;

	date_format = DATE_FORMAT_US;

	/* initialize macros */
	init_macros();

	global_host_event_handler = NULL;
	global_service_event_handler = NULL;
	global_host_event_handler_ptr = NULL;
	global_service_event_handler_ptr = NULL;

	ocsp_command = NULL;
	ochp_command = NULL;
	ocsp_command_ptr = NULL;
	ochp_command_ptr = NULL;

	/* reset umask */
	umask(S_IWGRP | S_IWOTH);

	return OK;
}
Пример #13
0
int main(int argc, char **argv)
{
	int result;
	int error = FALSE;
	int display_license = FALSE;
	int display_help = FALSE;
	int c = 0;
	int allow_root = FALSE;
	struct tm *tm, tm_s;
	time_t now;
	char datestring[256];
	nagios_macros *mac;
	const char *worker_socket = NULL;
	int i;

#ifdef HAVE_GETOPT_H
	int option_index = 0;
	static struct option long_options[] = {
		{"help", no_argument, 0, 'h'},
		{"version", no_argument, 0, 'V'},
		{"license", no_argument, 0, 'V'},
		{"verify-config", no_argument, 0, 'v'},
		{"daemon", no_argument, 0, 'd'},
		{"precache-objects", no_argument, 0, 'p'},
		{"use-precached-objects", no_argument, 0, 'u'},
		{"enable-timing-point", no_argument, 0, 'T'},
		{"worker", required_argument, 0, 'W'},
		{"allow-root", no_argument, 0, 'R'},
		{0, 0, 0, 0}
	};
#define getopt(argc, argv, o) getopt_long(argc, argv, o, long_options, &option_index)
#endif

	/* make sure we have the correct number of command line arguments */
	if (argc < 2)
		error = TRUE;

	/* get all command line arguments */
	while (1) {
		c = getopt(argc, argv, "+hVvdspuxTW");

		if (c == -1 || c == EOF)
			break;

		switch (c) {

		case '?': /* usage */
		case 'h':
			display_help = TRUE;
			break;

		case 'V': /* version */
			display_license = TRUE;
			break;

		case 'v': /* verify */
			verify_config++;
			break;

		case 's': /* scheduling check */
			printf("Warning: -s is deprecated and will be removed\n");
			break;

		case 'd': /* daemon mode */
			daemon_mode = TRUE;
			break;

		case 'p': /* precache object config */
			precache_objects = TRUE;
			break;

		case 'u': /* use precached object config */
			use_precached_objects = TRUE;
			break;
		case 'T':
			enable_timing_point = TRUE;
			break;
		case 'W':
			worker_socket = optarg;
			break;
		case 'R':
			allow_root = TRUE;
			break;

		case 'x':
			printf("Warning: -x is deprecated and will be removed\n");
			break;

		default:
			break;
		}

	}

	/* Make all GLib domain messages go to the usual places. This also maps
	 * GLib levels to an approximation of their corresponding Naemon levels
	 * (including debug).
	 *
	 * Note that because of the GLib domain restriction, log messages from
	 * other domains (such as if we did g_message(...) ourselves from inside
	 * Naemon) do not currently go to this handler.
	 **/
	nm_g_log_handler_id = g_log_set_handler("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL |
			G_LOG_FLAG_RECURSION, nm_g_log_handler, NULL);
	mac = get_global_macros();

	/* if we're a worker we can skip everything below */
	if (worker_socket) {
		exit(nm_core_worker(worker_socket));
	}

	if (daemon_mode == FALSE) {
		printf("\nNaemon Core " VERSION "\n");
		printf("Copyright (c) 2013-present Naemon Core Development Team and Community Contributors\n");
		printf("Copyright (c) 2009-2013 Nagios Core Development Team and Community Contributors\n");
		printf("Copyright (c) 1999-2009 Ethan Galstad\n");
		printf("License: GPL\n\n");
		printf("Website: http://www.naemon.org\n");
	}

	/* just display the license */
	if (display_license == TRUE) {

		printf("This program is free software; you can redistribute it and/or modify\n");
		printf("it under the terms of the GNU General Public License version 2 as\n");
		printf("published by the Free Software Foundation.\n\n");
		printf("This program is distributed in the hope that it will be useful,\n");
		printf("but WITHOUT ANY WARRANTY; without even the implied warranty of\n");
		printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n");
		printf("GNU General Public License for more details.\n\n");
		printf("You should have received a copy of the GNU General Public License\n");
		printf("along with this program; if not, write to the Free Software\n");
		printf("Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n\n");

		exit(OK);
	}

	/* make sure we got the main config file on the command line... */
	if (optind >= argc)
		error = TRUE;

	/* if there are no command line options (or if we encountered an error), print usage */
	if (error == TRUE || display_help == TRUE) {

		printf("Usage: %s [options] <main_config_file>\n", argv[0]);
		printf("\n");
		printf("Options:\n");
		printf("\n");
		printf("  -v, --verify-config          Verify all configuration data (-v -v for more info)\n");
		printf("  -T, --enable-timing-point    Enable timed commentary on initialization\n");
		printf("  -x, --dont-verify-paths      Deprecated (Don't check for circular object paths)\n");
		printf("  -p, --precache-objects       Precache object configuration\n");
		printf("  -u, --use-precached-objects  Use precached object config file\n");
		printf("  -d, --daemon                 Starts Naemon in daemon mode, instead of as a foreground process\n");
		printf("  -W, --worker /path/to/socket Act as a worker for an already running daemon\n");
		printf("  --allow-root                 Let naemon run as root. THIS IS NOT RECOMMENDED AT ALL.\n");
		printf("\n");
		printf("Visit the Naemon website at http://www.naemon.org/ for bug fixes, new\n");
		printf("releases, online documentation, FAQs and more...\n");
		printf("\n");

		exit(ERROR);
	}

	if (getuid() == 0) {
		if (allow_root == FALSE) {
			printf("ERROR: do not start naemon as root user.\n");
			exit(EXIT_FAILURE);
		} else {
			printf("WARNING: you are running as root which is not recommended.\n");
		}
	}



	/*
	 * config file is last argument specified.
	 * Make sure it uses an absolute path
	 */
	config_file = nspath_absolute(argv[optind], NULL);
	if (config_file == NULL) {
		printf("Error allocating memory.\n");
		exit(ERROR);
	}

	config_file_dir = nspath_absolute_dirname(config_file, NULL);

	/*
	 * Set the signal handler for the SIGXFSZ signal here because
	 * we may encounter this signal before the other signal handlers
	 * are set.
	 */
	signal(SIGXFSZ, sighandler);


	/*
	 * Setup rand and srand. Don't bother with better resolution than second
	 */
	srand(time(NULL));

	/*
	 * let's go to town. We'll be noisy if we're verifying config
	 * or running scheduling tests.
	 */
	if (verify_config || precache_objects) {
		reset_variables();

		if (verify_config)
			printf("Reading configuration data...\n");

		/* read our config file */
		result = read_main_config_file(config_file);
		if (result != OK) {
			printf("   Error processing main config file!\n\n");
			exit(EXIT_FAILURE);
		}

		if (verify_config)
			printf("   Read main config file okay...\n");

		/*
		 * this must come after dropping privileges, so we make
		 * sure to test access permissions as the right user.
		 */
		if (test_configured_paths() == ERROR) {
			printf("   One or more path problems detected. Aborting.\n");
			exit(EXIT_FAILURE);
		}

		/* read object config files */
		result = read_all_object_data(config_file);
		if (result != OK) {
			printf("   Error processing object config files!\n\n");
			/* if the config filename looks fishy, warn the user */
			if (!strstr(config_file, "naemon.cfg")) {
				printf("\n***> The name of the main configuration file looks suspicious...\n");
				printf("\n");
				printf("     Make sure you are specifying the name of the MAIN configuration file on\n");
				printf("     the command line and not the name of another configuration file.  The\n");
				printf("     main configuration file is typically '%s'\n", get_default_config_file());
			}

			printf("\n***> One or more problems was encountered while processing the config files...\n");
			printf("\n");
			printf("     Check your configuration file(s) to ensure that they contain valid\n");
			printf("     directives and data definitions.  If you are upgrading from a previous\n");
			printf("     version of Naemon, you should be aware that some variables/definitions\n");
			printf("     may have been removed or modified in this version.  Make sure to read\n");
			printf("     the HTML documentation regarding the config files, as well as the\n");
			printf("     'Whats New' section to find out what has changed.\n\n");
			exit(EXIT_FAILURE);
		}

		if (verify_config) {
			printf("   Read object config files okay...\n\n");
			printf("Running pre-flight check on configuration data...\n\n");
		}

		/* run the pre-flight check to make sure things look okay... */
		result = pre_flight_check();

		if (result != OK) {
			printf("\n***> One or more problems was encountered while running the pre-flight check...\n");
			printf("\n");
			printf("     Check your configuration file(s) to ensure that they contain valid\n");
			printf("     directives and data definitions.  If you are upgrading from a previous\n");
			printf("     version of Naemon, you should be aware that some variables/definitions\n");
			printf("     may have been removed or modified in this version.  Make sure to read\n");
			printf("     the HTML documentation regarding the config files, as well as the\n");
			printf("     'Whats New' section to find out what has changed.\n\n");
			exit(EXIT_FAILURE);
		}

		if (verify_config) {
			printf("\nThings look okay - No serious problems were detected during the pre-flight check\n");
		}

		if (precache_objects) {
			result = fcache_objects(object_precache_file);
			timing_point("Done precaching objects\n");
			if (result == OK) {
				printf("Object precache file created:\n%s\n", object_precache_file);
			} else {
				printf("Failed to precache objects to '%s': %s\n", object_precache_file, strerror(errno));
			}
		}

		/* clean up after ourselves */
		cleanup();

		/* exit */
		timing_point("Exiting\n");

		/* make valgrind shut up about still reachable memory */
		neb_free_module_list();
		free(config_file_dir);
		free(config_file);

		exit(result);
	}


	/* start to monitor things... */

	/*
	 * if we're called with a relative path we must make
	 * it absolute so we can launch our workers.
	 * If not, we needn't bother, as we're using execvp()
	 */
	if (strchr(argv[0], '/'))
		naemon_binary_path = nspath_absolute(argv[0], NULL);
	else
		naemon_binary_path = nm_strdup(argv[0]);

	if (!(nagios_iobs = iobroker_create())) {
		nm_log(NSLOG_RUNTIME_ERROR, "Error: Failed to create IO broker set: %s\n",
		       strerror(errno));
		exit(EXIT_FAILURE);
	}

	/* keep monitoring things until we get a shutdown command */
	sigshutdown = sigrestart = FALSE;
	do {
		/* reset internal book-keeping (in case we're restarting) */
		wproc_num_workers_spawned = wproc_num_workers_online = 0;

		/* reset program variables */
		timing_point("Reseting variables\n");
		reset_variables();
		timing_point("Reset variables\n");

		/* get PID */
		nagios_pid = (int)getpid();

		/* read in the configuration files (main and resource config files) */
		timing_point("Reading main config file\n");
		result = read_main_config_file(config_file);
		if (result != OK) {
			nm_log(NSLOG_CONFIG_ERROR, "Error: Failed to process config file '%s'. Aborting\n", config_file);
			exit(EXIT_FAILURE);
		}
		timing_point("Read main config file\n");

		/* NOTE 11/06/07 EG moved to after we read config files, as user may have overridden timezone offset */
		/* get program (re)start time and save as macro */
		program_start = time(NULL);
		nm_free(mac->x[MACRO_PROCESSSTARTTIME]);
		nm_asprintf(&mac->x[MACRO_PROCESSSTARTTIME], "%lu", (unsigned long)program_start);

		if (test_path_access(naemon_binary_path, X_OK)) {
			nm_log(NSLOG_RUNTIME_ERROR, "Error: failed to access() %s: %s\n", naemon_binary_path, strerror(errno));
			nm_log(NSLOG_RUNTIME_ERROR, "Error: Spawning workers will be impossible. Aborting.\n");
			exit(EXIT_FAILURE);
		}

		if (test_configured_paths() == ERROR) {
			/* error has already been logged */
			exit(EXIT_FAILURE);
		}
		/* enter daemon mode (unless we're restarting...) */
		if (daemon_mode == TRUE && sigrestart == FALSE) {

			result = daemon_init();

			/* we had an error daemonizing, so bail... */
			if (result == ERROR) {
				nm_log(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR, "Bailing out due to failure to daemonize. (PID=%d)", (int)getpid());
				cleanup();
				exit(EXIT_FAILURE);
			}

			/* get new PID */
			nagios_pid = (int)getpid();
		}

		/* this must be logged after we read config data, as user may have changed location of main log file */
		nm_log(NSLOG_PROCESS_INFO, "Naemon "VERSION" starting... (PID=%d)\n", (int)getpid());

		/* log the local time - may be different than clock time due to timezone offset */
		now = time(NULL);
		tm = localtime_r(&now, &tm_s);
		strftime(datestring, sizeof(datestring), "%a %b %d %H:%M:%S %Z %Y", tm);
		nm_log(NSLOG_PROCESS_INFO, "Local time is %s", datestring);

		/* write log version/info */
		write_log_file_info(NULL);

		/* open debug log now that we're the right user */
		open_debug_log();

		/* initialize modules */
		timing_point("Initializing NEB module API\n");
		neb_init_modules();
		neb_init_callback_list();
		timing_point("Initialized NEB module API\n");

		/* handle signals (interrupts) before we do any socket I/O */
		setup_sighandler();

		/*
		 * Initialize query handler and event subscription service.
		 * This must be done before modules are initialized, so
		 * the modules can use our in-core stuff properly
		 */
		timing_point("Initializing Query handler\n");
		if (qh_init(qh_socket_path) != OK) {
			nm_log(NSLOG_RUNTIME_ERROR, "Error: Failed to initialize query handler. Aborting\n");
			exit(EXIT_FAILURE);
		}
		timing_point("Initialized Query handler\n");

		timing_point("Initializing NERD\n");
		nerd_init();
		timing_point("Initialized NERD\n");

		/* initialize check workers */
		timing_point("Spawning %u workers\n", wproc_num_workers_spawned);
		if (init_workers(num_check_workers) < 0) {
			nm_log(NSLOG_RUNTIME_ERROR, "Failed to spawn workers. Aborting\n");
			exit(EXIT_FAILURE);
		}
		timing_point("Spawned %u workers\n", wproc_num_workers_spawned);

		timing_point("Connecting %u workers\n", wproc_num_workers_online);
		i = 0;
		while (i < 50 && wproc_num_workers_online < wproc_num_workers_spawned) {
			iobroker_poll(nagios_iobs, 50);
			i++;
		}
		timing_point("Connected %u workers\n", wproc_num_workers_online);

		/* read in all object config data */
		if (result == OK) {
			timing_point("Reading all object data\n");
			result = read_all_object_data(config_file);
			timing_point("Read all object data\n");
		}

		/*
		 * the queue has to be initialized before loading the neb modules
		 * to give them the chance to register user events.
		 * (initializing event queue requires number of objects, so do
		 * this after parsing the objects)
		 */
		timing_point("Initializing Event queue\n");
		init_event_queue();
		timing_point("Initialized Event queue\n");

		/* load modules */
		timing_point("Loading modules\n");
		if (neb_load_all_modules() != OK) {
			nm_log(NSLOG_CONFIG_ERROR, "Error: Module loading failed. Aborting.\n");
			/* give already loaded modules a chance to deinitialize */
			neb_unload_all_modules(NEBMODULE_FORCE_UNLOAD, NEBMODULE_NEB_SHUTDOWN);
			exit(EXIT_FAILURE);
		}
		timing_point("Loaded modules\n");

		timing_point("Making first callback\n");
		broker_program_state(NEBTYPE_PROCESS_PRELAUNCH, NEBFLAG_NONE, NEBATTR_NONE);
		timing_point("Made first callback\n");

		/* there was a problem reading the config files */
		if (result != OK) {
			nm_log(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_CONFIG_ERROR, "Bailing out due to one or more errors encountered in the configuration files. Run Naemon from the command line with the -v option to verify your config before restarting. (PID=%d)", (int)getpid());
		} else {
			/* run the pre-flight check to make sure everything looks okay*/
			timing_point("Running pre flight check\n");
			if ((result = pre_flight_check()) != OK) {
				nm_log(NSLOG_PROCESS_INFO | NSLOG_RUNTIME_ERROR | NSLOG_VERIFICATION_ERROR, "Bailing out due to errors encountered while running the pre-flight check.  Run Naemon from the command line with the -v option to verify your config before restarting. (PID=%d)\n", (int)getpid());
			}
			timing_point("Ran pre flight check\n");
		}

		/* an error occurred that prevented us from (re)starting */
		if (result != OK) {

			/* if we were restarting, we need to cleanup from the previous run */
			if (sigrestart == TRUE) {

				/* clean up the status data */
				cleanup_status_data(TRUE);
			}

			broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_PROCESS_INITIATED, NEBATTR_SHUTDOWN_ABNORMAL);

			cleanup();
			exit(ERROR);
		}

		/* write the objects.cache file */
		timing_point("Caching objects\n");
		fcache_objects(object_cache_file);
		timing_point("Cached objects\n");

		broker_program_state(NEBTYPE_PROCESS_START, NEBFLAG_NONE, NEBATTR_NONE);

		timing_point("Initializing status data\n");
		initialize_status_data(config_file);
		timing_point("Initialized status data\n");

		/* initialize scheduled downtime data */
		timing_point("Initializing downtime data\n");
		initialize_downtime_data();
		timing_point("Initialized downtime data\n");

		/* read initial service and host state information  */
		timing_point("Initializing retention data\n");
		initialize_retention_data();
		timing_point("Initialized retention data\n");

		timing_point("Reading initial state information\n");
		read_initial_state_information();
		timing_point("Read initial state information\n");

		/* initialize comment data */
		timing_point("Initializing comment data\n");
		initialize_comment_data();
		timing_point("Initialized comment data\n");

		/* initialize performance data */
		timing_point("Initializing performance data\n");
		initialize_performance_data(config_file);
		timing_point("Initialized performance data\n");

		/* initialize the check execution subsystem */
		timing_point("Initializing check execution scheduling\n");
		checks_init();
		timing_point("Initialized check execution scheduling\n");

		/* initialize check statistics */
		timing_point("Initializing check stats\n");
		init_check_stats();
		timing_point("Initialized check stats\n");

		/* update all status data (with retained information) */
		timing_point("Updating status data\n");
		update_all_status_data();
		timing_point("Updated status data\n");

		/* log initial host and service state */
		timing_point("Logging initial states\n");
		log_host_states(INITIAL_STATES, NULL);
		log_service_states(INITIAL_STATES, NULL);
		timing_point("Logged initial states\n");

		registered_commands_init(200);
		register_core_commands();
		/* fire up command file worker */
		timing_point("Launching command file worker\n");
		launch_command_file_worker();
		timing_point("Launched command file worker\n");

		broker_program_state(NEBTYPE_PROCESS_EVENTLOOPSTART, NEBFLAG_NONE, NEBATTR_NONE);

		/* get event start time and save as macro */
		event_start = time(NULL);
		nm_free(mac->x[MACRO_EVENTSTARTTIME]);
		nm_asprintf(&mac->x[MACRO_EVENTSTARTTIME], "%lu", (unsigned long)event_start);

		/* let the parent know we're good to go and that it can let go */
		if (daemon_mode == TRUE && sigrestart == FALSE) {
			if ((result = signal_parent(OK)) != OK) {
				broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_PROCESS_INITIATED, NEBATTR_SHUTDOWN_ABNORMAL);
				cleanup();
				exit(ERROR);
			}
		}

		timing_point("Entering event execution loop\n");
		/***** start monitoring all services *****/
		/* (doesn't return until a restart or shutdown signal is encountered) */
		sigshutdown = sigrestart = FALSE;
		event_execution_loop();

		/*
		 * immediately deinitialize the query handler so it
		 * can remove modules that have stashed data with it
		 */
		qh_deinit(qh_socket_path);

		/*
		 * handle any incoming signals
		 */
		signal_react();

		broker_program_state(NEBTYPE_PROCESS_EVENTLOOPEND, NEBFLAG_NONE, NEBATTR_NONE);
		if (sigshutdown == TRUE)
			broker_program_state(NEBTYPE_PROCESS_SHUTDOWN, NEBFLAG_USER_INITIATED, NEBATTR_SHUTDOWN_NORMAL);
		else if (sigrestart == TRUE)
			broker_program_state(NEBTYPE_PROCESS_RESTART, NEBFLAG_USER_INITIATED, NEBATTR_RESTART_NORMAL);

		disconnect_command_file_worker();

		/* save service and host state information */
		save_state_information(FALSE);
		cleanup_retention_data();

		/* clean up performance data */
		cleanup_performance_data();

		/* clean up the scheduled downtime data */
		cleanup_downtime_data();

		/* clean up the status data unless we're restarting */
		cleanup_status_data(!sigrestart);

		registered_commands_deinit();
		free_worker_memory(WPROC_FORCE);
		/* shutdown stuff... */
		if (sigshutdown == TRUE) {
			iobroker_destroy(nagios_iobs, IOBROKER_CLOSE_SOCKETS);
			nagios_iobs = NULL;

			/* log a shutdown message */
			nm_log(NSLOG_PROCESS_INFO, "Successfully shutdown... (PID=%d)\n", (int)getpid());
		}

		/* clean up after ourselves */
		cleanup();

		/* close debug log */
		close_debug_log();

	} while (sigrestart == TRUE && sigshutdown == FALSE);

	shutdown_command_file_worker();

	if (daemon_mode == TRUE)
		unlink(lock_file);

	/* free misc memory */
	nm_free(lock_file);
	nm_free(config_file);
	nm_free(config_file_dir);
	nm_free(naemon_binary_path);

	return OK;
}
Пример #14
0
int setup_host_variables(host *new_host, const char *display_name, const char *alias, const char *address, const char *check_period, int initial_state, double check_interval, double retry_interval, int max_attempts, int notification_options, double notification_interval, double first_notification_delay, const char *notification_period, int notifications_enabled, const char *check_command, int checks_enabled, int accept_passive_checks, const char *event_handler, int event_handler_enabled, int flap_detection_enabled, double low_flap_threshold, double high_flap_threshold, int flap_detection_options, int stalking_options, int process_perfdata, int check_freshness, int freshness_threshold, const char *notes, const char *notes_url, const char *action_url, const char *icon_image, const char *icon_image_alt, const char *vrml_image, const char *statusmap_image, int x_2d, int y_2d, int have_2d_coords, double x_3d, double y_3d, double z_3d, int have_3d_coords, int retain_status_information, int retain_nonstatus_information, int obsess, unsigned int hourly_value)
{
	timeperiod *check_tp = NULL, *notify_tp = NULL;

	if (check_period && !(check_tp = find_timeperiod(check_period))) {
		nm_log(NSLOG_CONFIG_ERROR, "Error: Failed to locate check_period '%s' for host '%s'!\n",
		       check_period, new_host->name);
		return -1;
	}
	if (notification_period && !(notify_tp = find_timeperiod(notification_period))) {
		nm_log(NSLOG_CONFIG_ERROR, "Error: Failed to locate notification_period '%s' for host '%s'!\n",
		       notification_period, new_host->name);
		return -1;
	}
	/* check values */
	if (max_attempts <= 0) {
		nm_log(NSLOG_CONFIG_ERROR, "Error: max_check_attempts must be a positive integer host '%s'\n", new_host->name);
		return -1;
	}
	if (check_interval < 0) {
		nm_log(NSLOG_CONFIG_ERROR, "Error: Invalid check_interval value for host '%s'\n", new_host->name);
		return -1;
	}
	if (notification_interval < 0) {
		nm_log(NSLOG_CONFIG_ERROR, "Error: Invalid notification_interval value for host '%s'\n", new_host->name);
		return -1;
	}
	if (first_notification_delay < 0) {
		nm_log(NSLOG_CONFIG_ERROR, "Error: Invalid first_notification_delay value for host '%s'\n", new_host->name);
		return -1;
	}
	if (freshness_threshold < 0) {
		nm_log(NSLOG_CONFIG_ERROR, "Error: Invalid freshness_threshold value for host '%s'\n", new_host->name);
		return -1;
	}

	/* assign string vars */
	if (display_name)
		new_host->display_name = nm_strdup(display_name);
	if (alias)
		new_host->alias = nm_strdup(alias);
	if (address)
		new_host->address = nm_strdup(address);
	if (check_tp) {
		new_host->check_period = check_tp->name;
		new_host->check_period_ptr = check_tp;
	}
	new_host->notification_period = notify_tp ? notify_tp->name : NULL;
	new_host->notification_period_ptr = notify_tp;
	if (check_command) {
		new_host->check_command = nm_strdup(check_command);
		new_host->check_command_ptr = find_bang_command(check_command);
		if (new_host->check_command_ptr == NULL) {
			nm_log(NSLOG_VERIFICATION_ERROR, "Error: Host check command '%s' specified for host '%s' is not defined anywhere!", new_host->check_command, new_host->name);
			return -1;
		}
	}
	if (event_handler) {
		new_host->event_handler = nm_strdup(event_handler);
		new_host->event_handler_ptr = find_bang_command(event_handler);
		if (new_host->event_handler_ptr == NULL) {
			nm_log(NSLOG_VERIFICATION_ERROR, "Error: Event handler command '%s' specified for host '%s' not defined anywhere", new_host->event_handler, new_host->name);
			return -1;
		}
	}
	new_host->notes = notes ? nm_strdup(notes) : NULL;
	new_host->notes_url = notes_url ? nm_strdup(notes_url) : NULL;
	new_host->action_url = action_url ? nm_strdup(action_url) : NULL;
	new_host->icon_image = icon_image ? nm_strdup(icon_image) : NULL;
	new_host->icon_image_alt = icon_image_alt ? nm_strdup(icon_image_alt) : NULL;
	new_host->vrml_image = vrml_image ? nm_strdup(vrml_image) : NULL;
	new_host->statusmap_image = statusmap_image ? nm_strdup(statusmap_image) : NULL;

	/* duplicate non-string vars */
	new_host->hourly_value = hourly_value;
	new_host->max_attempts = max_attempts;
	new_host->check_interval = check_interval;
	new_host->retry_interval = retry_interval;
	new_host->notification_interval = notification_interval;
	new_host->first_notification_delay = first_notification_delay;
	new_host->notification_options = notification_options;
	new_host->flap_detection_enabled = (flap_detection_enabled > 0) ? TRUE : FALSE;
	new_host->low_flap_threshold = low_flap_threshold;
	new_host->high_flap_threshold = high_flap_threshold;
	new_host->flap_detection_options = flap_detection_options;
	new_host->stalking_options = stalking_options;
	new_host->process_performance_data = (process_perfdata > 0) ? TRUE : FALSE;
	new_host->check_freshness = (check_freshness > 0) ? TRUE : FALSE;
	new_host->freshness_threshold = freshness_threshold;
	new_host->checks_enabled = (checks_enabled > 0) ? TRUE : FALSE;
	new_host->accept_passive_checks = (accept_passive_checks > 0) ? TRUE : FALSE;
	new_host->event_handler_enabled = (event_handler_enabled > 0) ? TRUE : FALSE;
	new_host->x_2d = x_2d;
	new_host->y_2d = y_2d;
	new_host->have_2d_coords = (have_2d_coords > 0) ? TRUE : FALSE;
	new_host->x_3d = x_3d;
	new_host->y_3d = y_3d;
	new_host->z_3d = z_3d;
	new_host->have_3d_coords = (have_3d_coords > 0) ? TRUE : FALSE;
	new_host->obsess = (obsess > 0) ? TRUE : FALSE;
	new_host->retain_status_information = (retain_status_information > 0) ? TRUE : FALSE;
	new_host->retain_nonstatus_information = (retain_nonstatus_information > 0) ? TRUE : FALSE;
	new_host->current_state = initial_state;
	new_host->last_state = initial_state;
	new_host->last_hard_state = initial_state;
	new_host->current_attempt = (initial_state == STATE_UP) ? 1 : max_attempts;
	new_host->notifications_enabled = (notifications_enabled > 0) ? TRUE : FALSE;

	return 0;
}
Пример #15
0
/* initializes performance data */
int initialize_performance_data(const char *cfgfile)
{
	char *buffer = NULL;
	char *temp_buffer = NULL;
	command *temp_command = NULL;
	time_t current_time;
	nagios_macros *mac;

	mac = get_global_macros();
	time(&current_time);

	/* reset vars */
	host_perfdata_command_ptr = NULL;
	service_perfdata_command_ptr = NULL;
	host_perfdata_file_processing_command_ptr = NULL;
	service_perfdata_file_processing_command_ptr = NULL;

	/* make sure we have some templates defined */
	if (host_perfdata_file_template == NULL)
		host_perfdata_file_template = nm_strdup(DEFAULT_HOST_PERFDATA_FILE_TEMPLATE);
	if (service_perfdata_file_template == NULL)
		service_perfdata_file_template = nm_strdup(DEFAULT_SERVICE_PERFDATA_FILE_TEMPLATE);

	/* process special chars in templates */
	xpddefault_preprocess_file_templates(host_perfdata_file_template);
	xpddefault_preprocess_file_templates(service_perfdata_file_template);

	/* open the performance data caches */
	host_perfdata_bq = nm_bufferqueue_create();
	host_perfdata_fd = xpddefault_open_perfdata_file(
		host_perfdata_file,
		host_perfdata_file_pipe,
		host_perfdata_file_append);
	service_perfdata_bq = nm_bufferqueue_create();
	service_perfdata_fd = xpddefault_open_perfdata_file(
		service_perfdata_file,
		service_perfdata_file_pipe,
		service_perfdata_file_append);

	/* verify that performance data commands are valid */
	if (host_perfdata_command != NULL) {
		temp_buffer = nm_strdup(host_perfdata_command);
		if ((temp_command = find_bang_command(temp_buffer)) == NULL) {
			nm_log(NSLOG_RUNTIME_WARNING, "Warning: Host performance command '%s' was not found - host performance data will not be processed!\n", host_perfdata_command);
			nm_free(host_perfdata_command);
		}

		nm_free(temp_buffer);

		/* save the command pointer for later */
		host_perfdata_command_ptr = temp_command;
	}

	if (service_perfdata_command != NULL) {
		temp_buffer = nm_strdup(service_perfdata_command);
		if ((temp_command = find_bang_command(temp_buffer)) == NULL) {
			nm_log(NSLOG_RUNTIME_WARNING, "Warning: Service performance command '%s' was not found - service performance data will not be processed!\n", service_perfdata_command);
			nm_free(service_perfdata_command);
		}

		nm_free(temp_buffer);

		/* save the command pointer for later */
		service_perfdata_command_ptr = temp_command;
	}

	if (host_perfdata_file_processing_command != NULL) {
		temp_buffer = nm_strdup(host_perfdata_file_processing_command);
		if ((temp_command = find_bang_command(temp_buffer)) == NULL) {
			nm_log(NSLOG_RUNTIME_WARNING, "Warning: Host performance file processing command '%s' was not found - host performance data file will not be processed!\n", host_perfdata_file_processing_command);
			nm_free(host_perfdata_file_processing_command);
		}

		nm_free(temp_buffer);

		/* save the command pointer for later */
		host_perfdata_file_processing_command_ptr = temp_command;
	}

	if (service_perfdata_file_processing_command != NULL) {
		temp_buffer = nm_strdup(service_perfdata_file_processing_command);
		if ((temp_command = find_bang_command(temp_buffer)) == NULL) {
			nm_log(NSLOG_RUNTIME_WARNING, "Warning: Service performance file processing command '%s' was not found - service performance data file will not be processed!\n", service_perfdata_file_processing_command);
			nm_free(service_perfdata_file_processing_command);
		}

		/* save the command pointer for later */
		service_perfdata_file_processing_command_ptr = temp_command;
	}

	/* periodically process the host perfdata file */
	if (host_perfdata_file_processing_interval > 0 && host_perfdata_file_processing_command != NULL) {
		if (host_perfdata_file_pipe)
			nm_log(NSLOG_RUNTIME_WARNING, "Warning: Host performance file is configured to be a pipe - ignoring host_perfdata_file_processing_interval");
		else
			schedule_event(host_perfdata_file_processing_interval, xpddefault_process_host_perfdata_file, NULL);
	}

	/* periodically process the service perfdata file */
	if (service_perfdata_file_processing_interval > 0 && service_perfdata_file_processing_command != NULL) {
		if (service_perfdata_file_pipe)
			nm_log(NSLOG_RUNTIME_WARNING, "Warning: Service performance file is configured to be a pipe - ignoring service_perfdata_file_processing_interval");
		else
			schedule_event(service_perfdata_file_processing_interval, xpddefault_process_service_perfdata_file, NULL);
	}

	/* save the host perf data file macro */
	nm_free(mac->x[MACRO_HOSTPERFDATAFILE]);
	if (host_perfdata_file != NULL) {
		mac->x[MACRO_HOSTPERFDATAFILE] = nm_strdup(host_perfdata_file);
		strip(mac->x[MACRO_HOSTPERFDATAFILE]);
	}

	/* save the service perf data file macro */
	nm_free(mac->x[MACRO_SERVICEPERFDATAFILE]);
	if (service_perfdata_file != NULL) {
		mac->x[MACRO_SERVICEPERFDATAFILE] = nm_strdup(service_perfdata_file);
		strip(mac->x[MACRO_SERVICEPERFDATAFILE]);
	}

	nm_free(temp_buffer);
	nm_free(buffer);

	return OK;
}