Example #1
0
static int	zbx_execute_script_on_agent(DC_HOST *host, const char *command, char **result,
		char *error, size_t max_error_len)
{
	const char	*__function_name = "zbx_execute_script_on_agent";
	int		ret;
	AGENT_RESULT	agent_result;
	char		*param, *port = NULL;
	DC_ITEM		item;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);

	*error = '\0';
	memset(&item, 0, sizeof(item));
	memcpy(&item.host, host, sizeof(item.host));

	if (SUCCEED != (ret = DCconfig_get_interface_by_type(&item.interface, host->hostid, INTERFACE_TYPE_AGENT)))
	{
		zbx_snprintf(error, max_error_len, "Whatap agent interface is not defined for host [%s]", host->host);
		goto fail;
	}

	port = zbx_strdup(port, item.interface.port_orig);
	substitute_simple_macros(NULL, NULL, NULL, NULL, &host->hostid, NULL, NULL, &port, MACRO_TYPE_COMMON, NULL, 0);

	if (SUCCEED != (ret = is_ushort(port, &item.interface.port)))
	{
		zbx_snprintf(error, max_error_len, "Invalid port number [%s]", item.interface.port_orig);
		goto fail;
	}

	param = zbx_dyn_escape_string(command, "\"");
	item.key = zbx_dsprintf(item.key, "system.run[\"%s\",\"%s\"]", param, NULL == result ? "nowait" : "wait");
	item.value_type = ITEM_VALUE_TYPE_TEXT;
	zbx_free(param);

	init_result(&agent_result);

	alarm(CONFIG_TIMEOUT);

	if (SUCCEED != (ret = get_value_agent(&item, &agent_result)))
	{
		if (ISSET_MSG(&agent_result))
			zbx_strlcpy(error, agent_result.msg, max_error_len);
		ret = FAIL;
	}
	else if (NULL != result && ISSET_TEXT(&agent_result))
		*result = zbx_strdup(*result, agent_result.text);

	alarm(0);

	free_result(&agent_result);

	zbx_free(item.key);
fail:
	zbx_free(port);

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));

	return ret;
}
Example #2
0
static int	calcitem_parse_expression(DC_ITEM *dc_item, expression_t *exp,
		char *error, int max_error_len)
{
	const char	*__function_name = "calcitem_parse_expression";
	char		*e, *f, *func = NULL, *params = NULL;
	int		functionid, exp_alloc = 128, exp_offset = 0, ret;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s() expression:'%s'", __function_name, dc_item->params_orig);

	assert(dc_item);
	assert(exp);

	exp->exp = zbx_malloc(exp->exp, exp_alloc);

	for (e = dc_item->params_orig; '\0' != *e; e++)
	{
		if (NULL != strchr(" \t\r\n", *e))
			continue;

		f = e;
		if (FAIL == parse_function(&e, &func, &params))
		{
			e = f;
			calcitem_exp_addchr(&exp->exp, &exp_alloc, &exp_offset, 128, *f);

			continue;
		}
		else
			e--;

		functionid = calcitem_add_function(exp, func, params);

		zabbix_log(LOG_LEVEL_DEBUG, "%s() functionid:%d function:'%s(%s)'",
				__function_name, functionid, func, params);

		func = NULL;
		params = NULL;

		zbx_snprintf_alloc(&exp->exp, &exp_alloc, &exp_offset, 16, "{%d}", functionid);
	}

	calcitem_exp_addchr(&exp->exp, &exp_alloc, &exp_offset, 1, '\0');

	zabbix_log(LOG_LEVEL_DEBUG, "%s() expression:'%s'", __function_name, exp->exp);

	if (FAIL == (ret = substitute_simple_macros(NULL, NULL, NULL, dc_item, NULL,
				&exp->exp, MACRO_TYPE_ITEM_EXPRESSION, error, max_error_len)))
		ret = NOTSUPPORTED;

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));

	return ret;
}
Example #3
0
File: ipmi.c Project: zabbix/zabbix
/******************************************************************************
 *                                                                            *
 * Function: zbx_ipmi_port_expand_macros                                      *
 *                                                                            *
 * Purpose: expands user macros in IPMI port value and converts the result to *
 *          to unsigned short value                                           *
 *                                                                            *
 * Parameters: hostid    - [IN] the host identifier                           *
 *             port_orig - [IN] the original port value                       *
 *             port      - [OUT] the resulting port value                     *
 *             error     - [OUT] the error message                            *
 *                                                                            *
 * Return value: SUCCEED - the value was converted successfully               *
 *               FAIL    - otherwise                                          *
 *                                                                            *
 ******************************************************************************/
int	zbx_ipmi_port_expand_macros(zbx_uint64_t hostid, const char *port_orig, unsigned short *port, char **error)
{
	char	*tmp;
	int	ret = SUCCEED;

	tmp = zbx_strdup(NULL, port_orig);
	substitute_simple_macros(NULL, NULL, NULL, NULL, &hostid, NULL, NULL, NULL, NULL,
			&tmp, MACRO_TYPE_COMMON, NULL, 0);

	if (FAIL == is_ushort(tmp, port) || 0 == *port)
	{
		*error = zbx_dsprintf(*error, "Invalid port value \"%s\"", port_orig);
		ret = FAIL;
	}

	zbx_free(tmp);

	return ret;
}
Example #4
0
static int	zbx_execute_ipmi_command(DC_HOST *host, const char *command, char *error, size_t max_error_len)
{
	const char	*__function_name = "zbx_execute_ipmi_command";
	int		val, ret;
	char		*port = NULL;
	DC_ITEM		item;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);

	*error = '\0';
	memset(&item, 0, sizeof(item));
	memcpy(&item.host, host, sizeof(item.host));

	if (SUCCEED != (ret = DCconfig_get_interface_by_type(&item.interface, host->hostid, INTERFACE_TYPE_IPMI)))
	{
		zbx_snprintf(error, max_error_len, "IPMI interface is not defined for host [%s]", host->host);
		goto fail;
	}

	port = zbx_strdup(port, item.interface.port_orig);
	substitute_simple_macros(NULL, NULL, NULL, NULL, &host->hostid, NULL, NULL, &port, MACRO_TYPE_COMMON, NULL, 0);

	if (SUCCEED != (ret = is_ushort(port, &item.interface.port)))
	{
		zbx_snprintf(error, max_error_len, "invalid port number [%s]", item.interface.port_orig);
		goto fail;
	}

	if (SUCCEED == (ret = parse_ipmi_command(command, item.ipmi_sensor, &val, error, max_error_len)))
	{
		if (SUCCEED != (ret = set_ipmi_control_value(&item, val, error, max_error_len)))
			ret = FAIL;
	}
fail:
	zbx_free(port);

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));

	return ret;
}
Example #5
0
/******************************************************************************
 *                                                                            *
 * Function: zbx_execute_script                                               *
 *                                                                            *
 * Purpose: executing user scripts or remote commands                         *
 *                                                                            *
 * Return value:  SUCCEED - processed successfully                            *
 *                FAIL - an error occurred                                    *
 *                TIMEOUT_ERROR - a timeout occurred                          *
 *                                                                            *
 * Comments: !!! always call 'zbx_script_clean' function after                *
 *           'zbx_execute_script' to clear allocated memory                   *
 *                                                                            *
 ******************************************************************************/
int	zbx_execute_script(DC_HOST *host, zbx_script_t *script, char **result, char *error, size_t max_error_len)
{
	const char	*__function_name = "zbx_execute_script";
	int		ret = FAIL;
	zbx_uint64_t	groupid;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);

	*error = '\0';

	switch (script->type)
	{
		case ZBX_SCRIPT_TYPE_CUSTOM_SCRIPT:
			dos2unix(script->command);	/* CR+LF (Windows) => LF (Unix) */

			switch (script->execute_on)
			{
				case ZBX_SCRIPT_EXECUTE_ON_AGENT:
					ret = zbx_execute_script_on_agent(host, script->command, result,
							error, max_error_len);
					break;
				case ZBX_SCRIPT_EXECUTE_ON_SERVER:
					ret = zbx_execute(script->command, result, error, max_error_len,
							CONFIG_TRAPPER_TIMEOUT);
					break;
				default:
					zbx_snprintf(error, max_error_len, "Invalid 'Execute on' option [%d]",
							(int)script->execute_on);
			}
			break;
		case ZBX_SCRIPT_TYPE_IPMI:
#ifdef HAVE_OPENIPMI
			if (SUCCEED == (ret = zbx_execute_ipmi_command(host, script->command, error, max_error_len)))
			{
				if (NULL != result)
					*result = zbx_strdup(*result, "IPMI command successfully executed");
			}
#else
			zbx_strlcpy(error, "Support for IPMI commands was not compiled in", max_error_len);
#endif
			break;
		case ZBX_SCRIPT_TYPE_SSH:
#ifdef HAVE_SSH2
			substitute_simple_macros(NULL, NULL, NULL, NULL, &host->hostid, NULL, NULL,
					&script->publickey, MACRO_TYPE_COMMON, NULL, 0);
			substitute_simple_macros(NULL, NULL, NULL, NULL, &host->hostid, NULL, NULL,
					&script->privatekey, MACRO_TYPE_COMMON, NULL, 0);
			/* break; is not missing here */
#else
			zbx_strlcpy(error, "Support for SSH script was not compiled in", max_error_len);
			break;
#endif
		case ZBX_SCRIPT_TYPE_TELNET:
			substitute_simple_macros(NULL, NULL, NULL, NULL, &host->hostid, NULL, NULL,
					&script->username, MACRO_TYPE_COMMON, NULL, 0);
			substitute_simple_macros(NULL, NULL, NULL, NULL, &host->hostid, NULL, NULL,
					&script->password, MACRO_TYPE_COMMON, NULL, 0);

			ret = zbx_execute_script_on_terminal(host, script, result, error, max_error_len);
			break;
		case ZBX_SCRIPT_TYPE_GLOBAL_SCRIPT:
			if (SUCCEED != DBget_script_by_scriptid(script->scriptid, script, &groupid))
			{
				zbx_snprintf(error, max_error_len,
						"Unknown Script ID [" ZBX_FS_UI64 "]", script->scriptid);
				break;
			}

			if (SUCCEED == check_script_permissions(groupid, host->hostid, error, max_error_len))
			{
				substitute_simple_macros(NULL, NULL, NULL, NULL, NULL, host, NULL,
						&script->command, MACRO_TYPE_SCRIPT, NULL, 0);

				ret = zbx_execute_script(host, script, result, error, max_error_len);	/* recursion */
			}
			break;
		default:
			zbx_snprintf(error, max_error_len, "Invalid command type [%d]", (int)script->type);
	}

	if (SUCCEED != ret && NULL != result)
		*result = zbx_strdup(*result, "");

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));

	return ret;
}
Example #6
0
static int	zbx_execute_script_on_terminal(DC_HOST *host, zbx_script_t *script, char **result,
		char *error, size_t max_error_len)
{
	const char	*__function_name = "zbx_execute_script_on_terminal";
	int		ret;
	AGENT_RESULT	agent_result;
	DC_ITEM		item;
	int             (*function)();

#ifdef HAVE_SSH2
	assert(ZBX_SCRIPT_TYPE_SSH == script->type || ZBX_SCRIPT_TYPE_TELNET == script->type);
#else
	assert(ZBX_SCRIPT_TYPE_TELNET == script->type);
#endif

	zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);

	*error = '\0';
	memset(&item, 0, sizeof(item));
	memcpy(&item.host, host, sizeof(item.host));

	if (SUCCEED != (ret = DCconfig_get_interface_by_type(&item.interface, host->hostid, INTERFACE_TYPE_AGENT)))
	{
		zbx_snprintf(error, max_error_len, "Whatap agent interface is not defined for host [%s]", host->host);
		goto fail;
	}

	switch (script->type)
	{
		case ZBX_SCRIPT_TYPE_SSH:
			item.authtype = script->authtype;
			item.publickey = script->publickey;
			item.privatekey = script->privatekey;
			/* break; is not missing here */
		case ZBX_SCRIPT_TYPE_TELNET:
			item.username = script->username;
			item.password = script->password;
			break;
	}

	substitute_simple_macros(NULL, NULL, NULL, NULL, &host->hostid, NULL, NULL,
			&script->port, MACRO_TYPE_COMMON, NULL, 0);

	if ('\0' != *script->port && SUCCEED != (ret = is_ushort(script->port, NULL)))
	{
		zbx_snprintf(error, max_error_len, "Invalid port number [%s]", script->port);
		goto fail;
	}

#ifdef HAVE_SSH2
	if (ZBX_SCRIPT_TYPE_SSH == script->type)
	{
		item.key = zbx_dsprintf(item.key, "ssh.run[,,%s]", script->port);
		function = get_value_ssh;
	}
	else
	{
#endif
		item.key = zbx_dsprintf(item.key, "telnet.run[,,%s]", script->port);
		function = get_value_telnet;
#ifdef HAVE_SSH2
	}
#endif
	item.value_type = ITEM_VALUE_TYPE_TEXT;
	item.params = zbx_strdup(item.params, script->command);

	init_result(&agent_result);

	alarm(CONFIG_TIMEOUT);

	if (SUCCEED != (ret = function(&item, &agent_result)))
	{
		if (ISSET_MSG(&agent_result))
			zbx_strlcpy(error, agent_result.msg, max_error_len);
		ret = FAIL;
	}
	else if (NULL != result && ISSET_TEXT(&agent_result))
		*result = zbx_strdup(*result, agent_result.text);

	alarm(0);

	free_result(&agent_result);

	zbx_free(item.params);
	zbx_free(item.key);
fail:
	zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));

	return ret;
}
static int	calcitem_parse_expression(DC_ITEM *dc_item, expression_t *exp, char *error, int max_error_len)
{
	const char	*__function_name = "calcitem_parse_expression";
	char		*e, *f, *func = NULL, *params = NULL;
	size_t		exp_alloc = 128, exp_offset = 0, len;
	int		functionid, ret;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s() expression:'%s'", __function_name, dc_item->params);

	assert(dc_item);
	assert(exp);

	exp->exp = zbx_malloc(exp->exp, exp_alloc);

	for (e = dc_item->params; '\0' != *e; e++)
	{
		if (SUCCEED != is_function_char(*e))
		{
			zbx_chrcpy_alloc(&exp->exp, &exp_alloc, &exp_offset, *e);
			continue;
		}

		if ((0 == strncmp("and", e, len = 3) || 0 == strncmp("not", e, 3) || 0 == strncmp("or", e, len = 2)) &&
				NULL != strchr("()" ZBX_WHITESPACE, e[len]))
		{
			zbx_strncpy_alloc(&exp->exp, &exp_alloc, &exp_offset, e, len);
			e += len - 1;
			continue;
		}

		f = e;
		if (SUCCEED != parse_function(&e, &func, &params))
		{
			e = f;
			zbx_chrcpy_alloc(&exp->exp, &exp_alloc, &exp_offset, *f);
			continue;
		}
		else
			e--;

		functionid = calcitem_add_function(exp, func, params);

		zabbix_log(LOG_LEVEL_DEBUG, "%s() functionid:%d function:'%s(%s)'",
				__function_name, functionid, func, params);

		func = NULL;
		params = NULL;

		zbx_snprintf_alloc(&exp->exp, &exp_alloc, &exp_offset, "{%d}", functionid);
	}

	zabbix_log(LOG_LEVEL_DEBUG, "%s() expression:'%s'", __function_name, exp->exp);

	if (FAIL == (ret = substitute_simple_macros(NULL, NULL, NULL, NULL, NULL, &dc_item->host, NULL, NULL,
				&exp->exp, MACRO_TYPE_ITEM_EXPRESSION, error, max_error_len)))
		ret = NOTSUPPORTED;

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));

	return ret;
}
Example #8
0
/******************************************************************************
 *                                                                            *
 * Function: process_httptests                                                *
 *                                                                            *
 * Purpose: process httptests                                                 *
 *                                                                            *
 * Parameters: now - current timestamp                                        *
 *                                                                            *
 * Return value:                                                              *
 *                                                                            *
 * Author: Alexei Vladishev                                                   *
 *                                                                            *
 * Comments: always SUCCEED                                                   *
 *                                                                            *
 ******************************************************************************/
int	process_httptests(int httppoller_num, int now)
{
    const char	*__function_name = "process_httptests";

    DB_RESULT	result;
    DB_ROW		row;
    zbx_httptest_t	httptest;
    DC_HOST		host;
    int		httptests_count = 0;

    zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);

    /* create macro cache to use in http tests */
    zbx_vector_ptr_pair_create(&httptest.macros);

    result = DBselect(
                 "select h.hostid,h.host,h.name,t.httptestid,t.name,t.variables,t.agent,"
                 "t.authentication,t.http_user,t.http_password,t.http_proxy,t.retries"
                 " from httptest t,hosts h"
                 " where t.hostid=h.hostid"
                 " and t.nextcheck<=%d"
                 " and " ZBX_SQL_MOD(t.httptestid,%d) "=%d"
                 " and t.status=%d"
                 " and h.proxy_hostid is null"
                 " and h.status=%d"
                 " and (h.maintenance_status=%d or h.maintenance_type=%d)"
                 ZBX_SQL_NODE,
                 now,
                 CONFIG_HTTPPOLLER_FORKS, httppoller_num - 1,
                 HTTPTEST_STATUS_MONITORED,
                 HOST_STATUS_MONITORED,
                 HOST_MAINTENANCE_STATUS_OFF, MAINTENANCE_TYPE_NORMAL,
                 DBand_node_local("t.httptestid"));

    while (NULL != (row = DBfetch(result)))
    {
        ZBX_STR2UINT64(host.hostid, row[0]);
        strscpy(host.host, row[1]);
        strscpy(host.name, row[2]);

        ZBX_STR2UINT64(httptest.httptest.httptestid, row[3]);
        httptest.httptest.name = row[4];

        httptest.httptest.variables = zbx_strdup(NULL, row[5]);
        substitute_simple_macros(NULL, NULL, NULL, NULL, NULL, &host, NULL,
                                 &httptest.httptest.variables, MACRO_TYPE_HTTPTEST_FIELD, NULL, 0);

        httptest.httptest.agent = zbx_strdup(NULL, row[6]);
        substitute_simple_macros(NULL, NULL, NULL, NULL, &host.hostid, NULL, NULL,
                                 &httptest.httptest.agent, MACRO_TYPE_COMMON, NULL, 0);

        if (HTTPTEST_AUTH_NONE != (httptest.httptest.authentication = atoi(row[7])))
        {
            httptest.httptest.http_user = zbx_strdup(NULL, row[8]);
            substitute_simple_macros(NULL, NULL, NULL, NULL, &host.hostid, NULL, NULL,
                                     &httptest.httptest.http_user, MACRO_TYPE_COMMON, NULL, 0);

            httptest.httptest.http_password = zbx_strdup(NULL, row[9]);
            substitute_simple_macros(NULL, NULL, NULL, NULL, &host.hostid, NULL, NULL,
                                     &httptest.httptest.http_password, MACRO_TYPE_COMMON, NULL, 0);
        }

        httptest.httptest.http_proxy = zbx_strdup(NULL, row[10]);
        substitute_simple_macros(NULL, NULL, NULL, NULL, &host.hostid, NULL, NULL,
                                 &httptest.httptest.http_proxy, MACRO_TYPE_COMMON, NULL, 0);

        httptest.httptest.retries = atoi(row[11]);

        /* add httptest varriables to the current test macro cache */
        http_process_variables(&httptest, httptest.httptest.variables, NULL, NULL);

        process_httptest(&host, &httptest);

        zbx_free(httptest.httptest.http_proxy);
        if (HTTPTEST_AUTH_NONE != httptest.httptest.authentication)
        {
            zbx_free(httptest.httptest.http_password);
            zbx_free(httptest.httptest.http_user);
        }
        zbx_free(httptest.httptest.agent);
        zbx_free(httptest.httptest.variables);

        /* clear the macro cache used in this http test */
        httptest_remove_macros(&httptest);

        httptests_count++;	/* performance metric */
    }
    /* destroy the macro cache used in http tests */
    zbx_vector_ptr_pair_destroy(&httptest.macros);

    DBfree_result(result);

    zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);

    return httptests_count;
}
Example #9
0
/******************************************************************************
 *                                                                            *
 * Function: lld_filter_load                                                  *
 *                                                                            *
 * Purpose: loads lld filter data                                             *
 *                                                                            *
 * Parameters: filter     - [IN] the lld filter                               *
 *             lld_ruleid - [IN] the lld rule id                              *
 *             error      - [OUT] the error description                       *
 *                                                                            *
 ******************************************************************************/
static int	lld_filter_load(lld_filter_t *filter, zbx_uint64_t lld_ruleid, char **error)
{
	DB_RESULT	result;
	DB_ROW		row;
	lld_condition_t	*condition;
	DC_ITEM		item;
	int		errcode, ret = SUCCEED;

	DCconfig_get_items_by_itemids(&item, &lld_ruleid, &errcode, 1);

	if (SUCCEED != errcode)
	{
		*error = zbx_dsprintf(*error, "Invalid discovery rule ID [" ZBX_FS_UI64 "].",
				lld_ruleid);
		ret = FAIL;
		goto out;
	}

	result = DBselect(
			"select item_conditionid,macro,value"
			" from item_condition"
			" where itemid=" ZBX_FS_UI64,
			lld_ruleid);

	while (NULL != (row = DBfetch(result)))
	{
		condition = zbx_malloc(NULL, sizeof(lld_condition_t));
		ZBX_STR2UINT64(condition->id, row[0]);
		condition->macro = zbx_strdup(NULL, row[1]);
		condition->regexp = zbx_strdup(NULL, row[2]);

		zbx_vector_ptr_create(&condition->regexps);

		zbx_vector_ptr_append(&filter->conditions, condition);

		if ('@' == *condition->regexp)
		{
			DCget_expressions_by_name(&condition->regexps, condition->regexp + 1);

			if (0 == condition->regexps.values_num)
			{
				*error = zbx_dsprintf(*error, "Global regular expression \"%s\" does not exist.",
						condition->regexp + 1);
				ret = FAIL;
				break;
			}
		}
		else
		{
			substitute_simple_macros(NULL, NULL, NULL, NULL, NULL, NULL, &item, NULL,
					&condition->regexp, MACRO_TYPE_LLD_FILTER, NULL, 0);
		}
	}
	DBfree_result(result);

	if (SUCCEED != ret)
		lld_conditions_free(&filter->conditions);
	else if (CONDITION_EVAL_TYPE_AND_OR == filter->evaltype)
		zbx_vector_ptr_sort(&filter->conditions, lld_condition_compare_by_macro);
out:
	DCconfig_clean_items(&item, &errcode, 1);

	return ret;
}
Example #10
0
/******************************************************************************
 *                                                                            *
 * Function: lld_process_discovery_rule                                       *
 *                                                                            *
 * Purpose: add or update items, triggers and graphs for discovery item       *
 *                                                                            *
 * Parameters: lld_ruleid - [IN] discovery item identificator from database   *
 *             value      - [IN] received value from agent                    *
 *                                                                            *
 ******************************************************************************/
void	lld_process_discovery_rule(zbx_uint64_t lld_ruleid, char *value, zbx_timespec_t *ts)
{
	const char		*__function_name = "lld_process_discovery_rule";

	DB_RESULT		result;
	DB_ROW			row;
	zbx_uint64_t		hostid = 0;
	char			*discovery_key = NULL, *filter = NULL, *error = NULL, *db_error = NULL, *error_esc;
	unsigned char		state = 0;
	unsigned short		lifetime;
	zbx_vector_ptr_t	lld_rows;
	char			*sql = NULL;
	size_t			sql_alloc = 128, sql_offset = 0;
	const char		*sql_start = "update items set ", *sql_continue = ",";

	zabbix_log(LOG_LEVEL_DEBUG, "In %s() itemid:" ZBX_FS_UI64, __function_name, lld_ruleid);

	zbx_vector_ptr_create(&lld_rows);
	sql = zbx_malloc(sql, sql_alloc);

	result = DBselect(
			"select hostid,key_,state,filter,error,lifetime"
			" from items"
			" where itemid=" ZBX_FS_UI64,
			lld_ruleid);

	if (NULL != (row = DBfetch(result)))
	{
		char	*lifetime_str;

		ZBX_STR2UINT64(hostid, row[0]);
		discovery_key = zbx_strdup(discovery_key, row[1]);
		state = (unsigned char)atoi(row[2]);
		filter = zbx_strdup(filter, row[3]);
		db_error = zbx_strdup(db_error, row[4]);

		lifetime_str = zbx_strdup(NULL, row[5]);
		substitute_simple_macros(NULL, NULL, NULL, NULL, &hostid, NULL, NULL,
				&lifetime_str, MACRO_TYPE_COMMON, NULL, 0);
		if (SUCCEED != is_ushort(lifetime_str, &lifetime))
		{
			zabbix_log(LOG_LEVEL_WARNING, "cannot process lost resources for the discovery rule \"%s:%s\":"
					" \"%s\" is not a valid value",
					zbx_host_string(hostid), discovery_key, lifetime_str);
			lifetime = 3650;	/* max value for the field */
		}
		zbx_free(lifetime_str);
	}
	else
		zabbix_log(LOG_LEVEL_WARNING, "invalid discovery rule ID [" ZBX_FS_UI64 "]", lld_ruleid);
	DBfree_result(result);

	if (0 == hostid)
		goto clean;

	if (SUCCEED != lld_rows_get(value, filter, &lld_rows, &error))
		goto error;

	error = zbx_strdup(error, "");

	lld_update_items(hostid, lld_ruleid, &lld_rows, &error, lifetime, ts->sec);
	lld_update_triggers(hostid, lld_ruleid, &lld_rows, &error);
	lld_update_graphs(hostid, lld_ruleid, &lld_rows, &error);
	lld_update_hosts(lld_ruleid, &lld_rows, &error, lifetime, ts->sec);

	if (ITEM_STATE_NOTSUPPORTED == state)
	{
		zabbix_log(LOG_LEVEL_WARNING,  "discovery rule [" ZBX_FS_UI64 "][%s] became supported",
				lld_ruleid, zbx_host_key_string(lld_ruleid));

		add_event(0, EVENT_SOURCE_INTERNAL, EVENT_OBJECT_LLDRULE, lld_ruleid, ts, ITEM_STATE_NORMAL,
				NULL, NULL, 0, 0);
		process_events();

		zbx_snprintf_alloc(&sql, &sql_alloc, &sql_offset, "%sstate=%d", sql_start, ITEM_STATE_NORMAL);
		sql_start = sql_continue;
	}
error:
	if (NULL != error && 0 != strcmp(error, db_error))
	{
		error_esc = DBdyn_escape_string_len(error, ITEM_ERROR_LEN);

		zbx_snprintf_alloc(&sql, &sql_alloc, &sql_offset, "%serror='%s'", sql_start, error_esc);
		sql_start = sql_continue;

		zbx_free(error_esc);
	}

	if (sql_start == sql_continue)
	{
		zbx_snprintf_alloc(&sql, &sql_alloc, &sql_offset, " where itemid=" ZBX_FS_UI64, lld_ruleid);

		DBbegin();

		DBexecute("%s", sql);

		DBcommit();
	}
clean:
	zbx_free(error);
	zbx_free(db_error);
	zbx_free(filter);
	zbx_free(discovery_key);
	zbx_free(sql);

	zbx_vector_ptr_clean(&lld_rows, (zbx_mem_free_func_t)lld_row_free);
	zbx_vector_ptr_destroy(&lld_rows);

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
}
Example #11
0
/******************************************************************************
 *                                                                            *
 * Function: get_values                                                       *
 *                                                                            *
 * Purpose: retrieve values of metrics from monitored hosts                   *
 *                                                                            *
 * Parameters:                                                                *
 *                                                                            *
 * Return value:                                                              *
 *                                                                            *
 * Author: Alexei Vladishev                                                   *
 *                                                                            *
 * Comments: always SUCCEED                                                   *
 *                                                                            *
 ******************************************************************************/
static int	get_values(unsigned char poller_type)
{
	const char	*__function_name = "get_values";
	DC_ITEM		items[MAX_REACHABLE_ITEMS];
	AGENT_RESULT	agent;
	zbx_uint64_t	*ids = NULL, *snmpids = NULL, *ipmiids = NULL;
	int		ids_alloc = 0, snmpids_alloc = 0, ipmiids_alloc = 0,
			ids_num = 0, snmpids_num = 0, ipmiids_num = 0,
			i, now, num, res;
	static char	*key = NULL, *ipmi_ip = NULL, *params = NULL,
			*username = NULL, *publickey = NULL, *privatekey = NULL,
			*password = NULL, *snmp_community = NULL, *snmp_oid = NULL,
			*snmpv3_securityname = NULL, *snmpv3_authpassphrase = NULL,
			*snmpv3_privpassphrase = NULL;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);

	num = DCconfig_get_poller_items(poller_type, items, ZBX_POLLER_TYPE_UNREACHABLE != poller_type
								? MAX_REACHABLE_ITEMS : MAX_UNREACHABLE_ITEMS);

	for (i = 0; i < num; i++)
	{
		zbx_free(key);
		key = strdup(items[i].key_orig);
		substitute_simple_macros(NULL, NULL, NULL, &items[i], NULL,
				&key, MACRO_TYPE_ITEM_KEY, NULL, 0);
		items[i].key = key;

		switch (items[i].type)
		{
			case ITEM_TYPE_SNMPv3:
				zbx_free(snmpv3_securityname);
				zbx_free(snmpv3_authpassphrase);
				zbx_free(snmpv3_privpassphrase);

				snmpv3_securityname = strdup(items[i].snmpv3_securityname_orig);
				snmpv3_authpassphrase = strdup(items[i].snmpv3_authpassphrase_orig);
				snmpv3_privpassphrase = strdup(items[i].snmpv3_privpassphrase_orig);

				substitute_simple_macros(NULL, NULL, NULL, &items[i], NULL,
						&snmpv3_securityname, MACRO_TYPE_ITEM_FIELD, NULL, 0);
				substitute_simple_macros(NULL, NULL, NULL, &items[i], NULL,
						&snmpv3_authpassphrase, MACRO_TYPE_ITEM_FIELD, NULL, 0);
				substitute_simple_macros(NULL, NULL, NULL, &items[i], NULL,
						&snmpv3_privpassphrase, MACRO_TYPE_ITEM_FIELD, NULL, 0);

				items[i].snmpv3_securityname = snmpv3_securityname;
				items[i].snmpv3_authpassphrase = snmpv3_authpassphrase;
				items[i].snmpv3_privpassphrase = snmpv3_privpassphrase;
			case ITEM_TYPE_SNMPv1:
			case ITEM_TYPE_SNMPv2c:
				zbx_free(snmp_community);
				zbx_free(snmp_oid);

				snmp_community = strdup(items[i].snmp_community_orig);
				snmp_oid = strdup(items[i].snmp_oid_orig);

				substitute_simple_macros(NULL, NULL, NULL, &items[i], NULL,
						&snmp_community, MACRO_TYPE_ITEM_FIELD, NULL, 0);
				substitute_simple_macros(NULL, NULL, NULL, &items[i], NULL,
						&snmp_oid, MACRO_TYPE_ITEM_FIELD, NULL, 0);

				items[i].snmp_community = snmp_community;
				items[i].snmp_oid = snmp_oid;
				break;
			case ITEM_TYPE_IPMI:
				zbx_free(ipmi_ip);
				ipmi_ip = strdup(items[i].host.ipmi_ip_orig);
				substitute_simple_macros(NULL, NULL, NULL, &items[i], NULL,
						&ipmi_ip, MACRO_TYPE_HOST_IPMI_IP, NULL, 0);
				items[i].host.ipmi_ip = ipmi_ip;
				break;
			case ITEM_TYPE_DB_MONITOR:
				zbx_free(params);
				params = strdup(items[i].params_orig);
				substitute_simple_macros(NULL, NULL, NULL, &items[i], NULL,
						&params, MACRO_TYPE_ITEM_FIELD, NULL, 0);
				items[i].params = params;
				break;
			case ITEM_TYPE_SSH:
				zbx_free(username);
				zbx_free(publickey);
				zbx_free(privatekey);
				zbx_free(password);
				zbx_free(params);

				username = strdup(items[i].username_orig);
				publickey = strdup(items[i].publickey_orig);
				privatekey = strdup(items[i].privatekey_orig);
				password = strdup(items[i].password_orig);
				params = strdup(items[i].params_orig);

				substitute_simple_macros(NULL, NULL, NULL, &items[i], NULL,
						&username, MACRO_TYPE_ITEM_FIELD, NULL, 0);
				substitute_simple_macros(NULL, NULL, NULL, &items[i], NULL,
						&publickey, MACRO_TYPE_ITEM_FIELD, NULL, 0);
				substitute_simple_macros(NULL, NULL, NULL, &items[i], NULL,
						&privatekey, MACRO_TYPE_ITEM_FIELD, NULL, 0);
				substitute_simple_macros(NULL, NULL, NULL, &items[i], NULL,
						&password, MACRO_TYPE_ITEM_FIELD, NULL, 0);
				substitute_simple_macros(NULL, NULL, NULL, &items[i], NULL,
						&params, MACRO_TYPE_ITEM_FIELD, NULL, 0);

				items[i].username = username;
				items[i].publickey = publickey;
				items[i].privatekey = privatekey;
				items[i].password = password;
				items[i].params = params;
				break;
			case ITEM_TYPE_TELNET:
				zbx_free(username);
				zbx_free(password);
				zbx_free(params);

				username = strdup(items[i].username_orig);
				password = strdup(items[i].password_orig);
				params = strdup(items[i].params_orig);

				substitute_simple_macros(NULL, NULL, NULL, &items[i], NULL,
						&username, MACRO_TYPE_ITEM_FIELD, NULL, 0);
				substitute_simple_macros(NULL, NULL, NULL, &items[i], NULL,
						&password, MACRO_TYPE_ITEM_FIELD, NULL, 0);
				substitute_simple_macros(NULL, NULL, NULL, &items[i], NULL,
						&params, MACRO_TYPE_ITEM_FIELD, NULL, 0);

				items[i].username = username;
				items[i].password = password;
				items[i].params = params;
				break;
		}

		/* Skip unreachable hosts but do not break the loop. */
		switch (items[i].type)
		{
			case ITEM_TYPE_ZABBIX:
				if (SUCCEED == uint64_array_exists(ids, ids_num, items[i].host.hostid))
				{
					DCrequeue_unreachable_item(items[i].itemid);
					zabbix_log(LOG_LEVEL_DEBUG, "Zabbix Host " ZBX_FS_UI64 " is unreachable. Skipping [%s]",
							items[i].host.hostid, items[i].key_orig);
					continue;
				}
				break;
			case ITEM_TYPE_SNMPv1:
			case ITEM_TYPE_SNMPv2c:
			case ITEM_TYPE_SNMPv3:
				if (SUCCEED == uint64_array_exists(snmpids, snmpids_num, items[i].host.hostid))
				{
					DCrequeue_unreachable_item(items[i].itemid);
					zabbix_log(LOG_LEVEL_DEBUG, "SNMP Host " ZBX_FS_UI64 " is unreachable. Skipping [%s]",
							items[i].host.hostid, items[i].key_orig);
					continue;
				}
				break;
			case ITEM_TYPE_IPMI:
				if (SUCCEED == uint64_array_exists(ipmiids, ipmiids_num, items[i].host.hostid))
				{
					DCrequeue_unreachable_item(items[i].itemid);
					zabbix_log(LOG_LEVEL_DEBUG, "IPMI Host " ZBX_FS_UI64 " is unreachable. Skipping [%s]",
							items[i].host.hostid, items[i].key_orig);
					continue;
				}
				break;
			default:
				/* nothing to do */;
		}

		init_result(&agent);

		res = get_value(&items[i], &agent);
		now = time(NULL);

		if (res == SUCCEED)
		{
			activate_host(&items[i], now);

			dc_add_history(items[i].itemid, items[i].value_type, &agent, now,
					ITEM_STATUS_ACTIVE, NULL, 0, NULL, 0, 0, 0, 0);

			DCrequeue_reachable_item(items[i].itemid, ITEM_STATUS_ACTIVE, now);
		}
		else if (res == NOTSUPPORTED || res == AGENT_ERROR)
		{
			activate_host(&items[i], now);

			dc_add_history(items[i].itemid, items[i].value_type, NULL, now,
					ITEM_STATUS_NOTSUPPORTED, agent.msg, 0, NULL, 0, 0, 0, 0);

			DCrequeue_reachable_item(items[i].itemid, ITEM_STATUS_NOTSUPPORTED, now);
		}
		else if (res == NETWORK_ERROR)
		{
			deactivate_host(&items[i], now, agent.msg);

			switch (items[i].type)
			{
				case ITEM_TYPE_ZABBIX:
					uint64_array_add(&ids, &ids_alloc, &ids_num, items[i].host.hostid, 1);
					break;
				case ITEM_TYPE_SNMPv1:
				case ITEM_TYPE_SNMPv2c:
				case ITEM_TYPE_SNMPv3:
					uint64_array_add(&snmpids, &snmpids_alloc, &snmpids_num, items[i].host.hostid, 1);
					break;
				case ITEM_TYPE_IPMI:
					uint64_array_add(&ipmiids, &ipmiids_alloc, &ipmiids_num, items[i].host.hostid, 1);
					break;
				default:
					/* nothing to do */;
			}

			DCrequeue_unreachable_item(items[i].itemid);
		}
		else
		{
			zbx_error("unknown response code returned: %d", res);
			assert(0);
		}

		free_result(&agent);
	}

	zbx_free(key);
	zbx_free(ipmi_ip);
	zbx_free(params);
	zbx_free(username);
	zbx_free(publickey);
	zbx_free(privatekey);
	zbx_free(password);
	zbx_free(snmp_community);
	zbx_free(snmp_oid);
	zbx_free(snmpv3_securityname);
	zbx_free(snmpv3_authpassphrase);
	zbx_free(snmpv3_privpassphrase);

	zbx_free(ids);
	zbx_free(snmpids);
	zbx_free(ipmiids);

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);

	return num;
}
Example #12
0
/******************************************************************************
 *                                                                            *
 * Function: execute_script                                                   *
 *                                                                            *
 * Purpose: executing command                                                 *
 *                                                                            *
 * Parameters:                                                                *
 *                                                                            *
 * Return value:  SUCCEED - processed successfully                            *
 *                FAIL - an error occurred                                    *
 *                                                                            *
 * Author: Alexander Vladishev                                                *
 *                                                                            *
 * Comments:                                                                  *
 *                                                                            *
 ******************************************************************************/
static int	execute_script(zbx_uint64_t scriptid, zbx_uint64_t hostid, char **result)
{
	char		*p, *command, error[MAX_STRING_LEN];
	int		ret = FAIL;
	DC_HOST		host;
#ifdef HAVE_OPENIPMI
	DB_RESULT	db_result;
	DB_ROW		db_row;
	DC_ITEM		item;
	int		val;
#endif

	zabbix_log(LOG_LEVEL_DEBUG, "In execute_script() scriptid:" ZBX_FS_UI64
			" hostid:" ZBX_FS_UI64, scriptid, hostid);

	if (FAIL == DCget_host_by_hostid(&host, hostid))
	{
		*result = zbx_dsprintf(*result, "NODE %d: Unknown Host ID [" ZBX_FS_UI64 "]",
				CONFIG_NODEID, hostid);
		return ret;
	}

	if (NULL == (command = get_command_by_scriptid(scriptid)))
	{
		*result = zbx_dsprintf(*result, "NODE %d: Unknown Script ID [" ZBX_FS_UI64 "]",
				CONFIG_NODEID, scriptid);
		return ret;
	}

	substitute_simple_macros(NULL, NULL, &host, NULL, NULL,
			&command, MACRO_TYPE_SCRIPT, NULL, 0);

	zabbix_log(LOG_LEVEL_WARNING, "NODE %d: Executing command: '%s'",
			CONFIG_NODEID, command);

	p = command;
	while (*p == ' ' && *p != '\0')
		p++;

#ifdef HAVE_OPENIPMI
	if (0 == strncmp(p, "IPMI", 4))
	{
		db_result = DBselect(
				"select hostid,host,useip,ip,dns,port,useipmi,ipmi_ip,ipmi_port,ipmi_authtype,"
					"ipmi_privilege,ipmi_username,ipmi_password"
				" from hosts"
				" where hostid=" ZBX_FS_UI64
					DB_NODE,
				hostid,
				DBnode_local("hostid"));

		if (NULL != (db_row = DBfetch(db_result)))
		{
			memset(&item, 0, sizeof(item));

			ZBX_STR2UINT64(item.host.hostid, db_row[0]);
			zbx_strlcpy(item.host.host, db_row[1], sizeof(item.host.host));
			item.host.useip = (unsigned char)atoi(db_row[2]);
			zbx_strlcpy(item.host.ip, db_row[3], sizeof(item.host.ip));
			zbx_strlcpy(item.host.dns, db_row[4], sizeof(item.host.dns));
			item.host.port = (unsigned short)atoi(db_row[5]);

			if (1 == atoi(db_row[6]))
			{
				zbx_strlcpy(item.host.ipmi_ip_orig, db_row[7], sizeof(item.host.ipmi_ip));
				item.host.ipmi_port = (unsigned short)atoi(db_row[8]);
				item.host.ipmi_authtype = atoi(db_row[9]);
				item.host.ipmi_privilege = atoi(db_row[10]);
				zbx_strlcpy(item.host.ipmi_username, db_row[11], sizeof(item.host.ipmi_username));
				zbx_strlcpy(item.host.ipmi_password, db_row[12], sizeof(item.host.ipmi_password));
			}

			if (SUCCEED == (ret = parse_ipmi_command(p, item.ipmi_sensor, &val)))
			{
				if (SUCCEED == (ret = set_ipmi_control_value(&item, val, error, sizeof(error))))
				{
					*result = zbx_dsprintf(*result, "NODE %d: IPMI command successfully executed",
							CONFIG_NODEID);
				}
				else
				{
					*result = zbx_dsprintf(*result, "NODE %d: Cannot execute IPMI command: %s",
							CONFIG_NODEID, error);
				}
			}
			else
			{
				 *result = zbx_dsprintf(*result, "NODE %d: Cannot parse IPMI command",
						CONFIG_NODEID);
			}
		}
		else
		{
			*result = zbx_dsprintf(*result, "NODE %d: Unknown Host ID [" ZBX_FS_UI64 "]",
					CONFIG_NODEID, hostid);
		}

		DBfree_result(db_result);
	}
	else
	{
#endif	/* HAVE_OPENIPMI */
		if (SUCCEED != (ret = zbx_execute(p, result, error, sizeof(error), CONFIG_TRAPPER_TIMEOUT)))
			*result = zbx_dsprintf(*result, "NODE %d: Cannot execute command: %s", CONFIG_NODEID, error);

#ifdef HAVE_OPENIPMI
	}
#endif

	zbx_free(command);

	return ret;
}
/******************************************************************************
 *                                                                            *
 * Function: discover_service                                                 *
 *                                                                            *
 * Purpose: check if service is available and update database                 *
 *                                                                            *
 * Parameters: service type, ip address, port number                          *
 *                                                                            *
 * Author: Alexei Vladishev                                                   *
 *                                                                            *
 ******************************************************************************/
static int	discover_service(DB_DCHECK *dcheck, char *ip, int port, char *value)
{
	const char	*__function_name = "discover_service";
	int		ret = SUCCEED;
	char		key[MAX_STRING_LEN], error[ITEM_ERROR_LEN_MAX];
	const char	*service = NULL;
	AGENT_RESULT 	result;
	DC_ITEM		item;
	ZBX_FPING_HOST	host;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);

	init_result(&result);
	*value = '\0';

	switch (dcheck->type)
	{
		case SVC_SSH:
			service = "ssh";
			break;
		case SVC_LDAP:
			service = "ldap";
			break;
		case SVC_SMTP:
			service = "smtp";
			break;
		case SVC_FTP:
			service = "ftp";
			break;
		case SVC_HTTP:
			service = "http";
			break;
		case SVC_POP:
			service = "pop";
			break;
		case SVC_NNTP:
			service = "nntp";
			break;
		case SVC_IMAP:
			service = "imap";
			break;
		case SVC_TCP:
			service = "tcp";
			break;
		case SVC_HTTPS:
			service = "https";
			break;
		case SVC_TELNET:
			service = "telnet";
			break;
		case SVC_AGENT:
		case SVC_SNMPv1:
		case SVC_SNMPv2c:
		case SVC_SNMPv3:
		case SVC_ICMPPING:
			break;
		default:
			ret = FAIL;
			break;
	}

	if (SUCCEED == ret)
	{
		alarm(CONFIG_TIMEOUT);

		switch (dcheck->type)
		{
			/* simple checks */
			case SVC_SSH:
			case SVC_LDAP:
			case SVC_SMTP:
			case SVC_FTP:
			case SVC_HTTP:
			case SVC_POP:
			case SVC_NNTP:
			case SVC_IMAP:
			case SVC_TCP:
			case SVC_HTTPS:
			case SVC_TELNET:
				zbx_snprintf(key, sizeof(key), "net.tcp.service[%s,%s,%d]", service, ip, port);

				if (SUCCEED != process(key, 0, &result) || NULL == GET_UI64_RESULT(&result) ||
						0 == result.ui64)
				{
					ret = FAIL;
				}
				break;
			/* agent and SNMP checks */
			case SVC_AGENT:
			case SVC_SNMPv1:
			case SVC_SNMPv2c:
			case SVC_SNMPv3:
				memset(&item, 0, sizeof(DC_ITEM));

				strscpy(item.key_orig, dcheck->key_);
				item.key = item.key_orig;

				item.interface.useip = 1;
				item.interface.addr = ip;
				item.interface.port = port;

				item.value_type	= ITEM_VALUE_TYPE_STR;

				switch (dcheck->type)
				{
					case SVC_SNMPv1:
						item.type = ITEM_TYPE_SNMPv1;
						break;
					case SVC_SNMPv2c:
						item.type = ITEM_TYPE_SNMPv2c;
						break;
					case SVC_SNMPv3:
						item.type = ITEM_TYPE_SNMPv3;
						break;
					default:
						item.type = ITEM_TYPE_ZABBIX;
						break;
				}

				if (SVC_AGENT == dcheck->type)
				{
					if (SUCCEED == get_value_agent(&item, &result) && NULL != GET_STR_RESULT(&result))
						zbx_strlcpy(value, result.str, DSERVICE_VALUE_LEN_MAX);
					else
						ret = FAIL;
				}
				else
#ifdef HAVE_SNMP
				{
					item.snmp_community = strdup(dcheck->snmp_community);
					item.snmp_oid = strdup(dcheck->key_);

					substitute_simple_macros(NULL, NULL, NULL, NULL, NULL, NULL,
							&item.snmp_community, MACRO_TYPE_ITEM_FIELD, NULL, 0);
					substitute_key_macros(&item.snmp_oid, NULL, NULL, NULL,
							MACRO_TYPE_SNMP_OID, NULL, 0);

					if (ITEM_TYPE_SNMPv3 == item.type)
					{
						item.snmpv3_securityname = strdup(dcheck->snmpv3_securityname);
						item.snmpv3_securitylevel = dcheck->snmpv3_securitylevel;
						item.snmpv3_authpassphrase = strdup(dcheck->snmpv3_authpassphrase);
						item.snmpv3_privpassphrase = strdup(dcheck->snmpv3_privpassphrase);

						substitute_simple_macros(NULL, NULL, NULL, NULL, NULL, NULL,
								&item.snmpv3_securityname, MACRO_TYPE_ITEM_FIELD, NULL, 0);
						substitute_simple_macros(NULL, NULL, NULL, NULL, NULL, NULL,
								&item.snmpv3_authpassphrase, MACRO_TYPE_ITEM_FIELD, NULL, 0);
						substitute_simple_macros(NULL, NULL, NULL, NULL, NULL, NULL,
								&item.snmpv3_privpassphrase, MACRO_TYPE_ITEM_FIELD, NULL, 0);
					}

					if (SUCCEED == get_value_snmp(&item, &result) && NULL != GET_STR_RESULT(&result))
						zbx_strlcpy(value, result.str, DSERVICE_VALUE_LEN_MAX);
					else
						ret = FAIL;

					zbx_free(item.snmp_community);
					zbx_free(item.snmp_oid);

					if (ITEM_TYPE_SNMPv3 == item.type)
					{
						zbx_free(item.snmpv3_securityname);
						zbx_free(item.snmpv3_authpassphrase);
						zbx_free(item.snmpv3_privpassphrase);
					}
				}
#else
					ret = FAIL;
#endif	/* HAVE_SNMP */

				if (FAIL == ret && ISSET_MSG(&result))
				{
					zabbix_log(LOG_LEVEL_DEBUG, "discovery: item [%s] error: %s",
							item.key, result.msg);
				}
				break;
			case SVC_ICMPPING:
				memset(&host, 0, sizeof(host));
				host.addr = strdup(ip);

				if (SUCCEED != do_ping(&host, 1, 3, 0, 0, 0, error, sizeof(error)) || 0 == host.rcv)
					ret = FAIL;

				zbx_free(host.addr);
				break;
			default:
				break;
		}

		alarm(0);
	}
	free_result(&result);

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));

	return ret;
}
Example #14
0
/******************************************************************************
 *                                                                            *
 * Function: check_trigger_condition                                          *
 *                                                                            *
 * Purpose: check if event matches single condition                           *
 *                                                                            *
 * Parameters: event - trigger event to check                                 *
 *                                  (event->source == EVENT_SOURCE_TRIGGERS)  *
 *             condition - condition for matching                             *
 *                                                                            *
 * Return value: SUCCEED - matches, FAIL - otherwise                          *
 *                                                                            *
 * Author: Alexei Vladishev                                                   *
 *                                                                            *
 * Comments:                                                                  *
 *                                                                            *
 ******************************************************************************/
static int	check_trigger_condition(DB_EVENT *event, DB_CONDITION *condition)
{
	const char	*__function_name = "check_trigger_condition";
	DB_RESULT	result;
	DB_ROW		row;
	zbx_uint64_t	condition_value;
	int		nodeid;
	char		*tmp_str = NULL;
	int		ret = FAIL;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);

	if (condition->conditiontype == CONDITION_TYPE_HOST_GROUP)
	{
		ZBX_STR2UINT64(condition_value, condition->value);

		result = DBselect(
				"select distinct hg.groupid"
				" from hosts_groups hg,hosts h,items i,functions f,triggers t"
				" where hg.hostid=h.hostid"
					" and h.hostid=i.hostid"
					" and i.itemid=f.itemid"
					" and f.triggerid=t.triggerid"
					" and t.triggerid=" ZBX_FS_UI64
					" and hg.groupid=" ZBX_FS_UI64,
				event->objectid,
				condition_value);

		switch (condition->operator)
		{
		case CONDITION_OPERATOR_EQUAL:
			if (NULL != DBfetch(result))
				ret = SUCCEED;
			break;
		case CONDITION_OPERATOR_NOT_EQUAL:
			if (NULL == DBfetch(result))
				ret = SUCCEED;
			break;
		default:
			zabbix_log(LOG_LEVEL_ERR, "Unsupported operator [%d] for condition id [" ZBX_FS_UI64 "]",
					condition->operator,
					condition->conditionid);
		}
		DBfree_result(result);
	}
	else if (condition->conditiontype == CONDITION_TYPE_HOST_TEMPLATE)
	{
		zbx_uint64_t	hostid, triggerid;

		ZBX_STR2UINT64(condition_value, condition->value);

		switch (condition->operator)
		{
		case CONDITION_OPERATOR_EQUAL:
		case CONDITION_OPERATOR_NOT_EQUAL:
			triggerid = event->objectid;

			do
			{
				result = DBselect(
						"select distinct i.hostid,t.templateid"
						" from items i,functions f,triggers t"
						" where i.itemid=f.itemid"
							" and f.triggerid=t.templateid"
							" and t.triggerid=" ZBX_FS_UI64,
						triggerid);

				if (NULL != (row = DBfetch(result)))
				{
					ZBX_STR2UINT64(hostid, row[0]);
					ZBX_STR2UINT64(triggerid, row[1]);

					if (hostid == condition_value)
					{
						ret = SUCCEED;
						break;
					}
				}
				else
					triggerid = 0;
				DBfree_result(result);
			} while (SUCCEED != ret && 0 != triggerid);

			if (CONDITION_OPERATOR_NOT_EQUAL == condition->operator)
				ret = (SUCCEED == ret) ? FAIL : SUCCEED;
			break;
		default:
			zabbix_log(LOG_LEVEL_ERR, "Unsupported operator [%d] for condition id [" ZBX_FS_UI64 "]",
					condition->operator,
					condition->conditionid);
		}
	}
	else if (condition->conditiontype == CONDITION_TYPE_HOST)
	{
		ZBX_STR2UINT64(condition_value, condition->value);

		switch (condition->operator)
		{
		case CONDITION_OPERATOR_EQUAL:
		case CONDITION_OPERATOR_NOT_EQUAL:
			result = DBselect(
					"select distinct i.hostid"
					" from items i,functions f,triggers t"
					" where i.itemid=f.itemid"
						" and f.triggerid=t.triggerid"
						" and t.triggerid=" ZBX_FS_UI64
						" and i.hostid=" ZBX_FS_UI64,
					event->objectid,
					condition_value);

			if (NULL != DBfetch(result))
				ret = SUCCEED;
			DBfree_result(result);

			if (CONDITION_OPERATOR_NOT_EQUAL == condition->operator)
				ret = (SUCCEED == ret) ? FAIL : SUCCEED;
			break;
		default:
			zabbix_log(LOG_LEVEL_ERR, "Unsupported operator [%d] for condition id [" ZBX_FS_UI64 "]",
					condition->operator, condition->conditionid);
		}
	}
	else if (condition->conditiontype == CONDITION_TYPE_TRIGGER)
	{
		zbx_uint64_t	triggerid;

		ZBX_STR2UINT64(condition_value, condition->value);

		switch (condition->operator)
		{
		case CONDITION_OPERATOR_EQUAL:
		case CONDITION_OPERATOR_NOT_EQUAL:
			if (event->objectid == condition_value)
				ret = SUCCEED;
			/* Processing of templated triggers */
			else
			{
				for (triggerid = event->objectid; 0 != triggerid && FAIL == ret;)
				{
					result = DBselect(
							"select templateid"
							" from triggers"
							" where triggerid=" ZBX_FS_UI64,
							triggerid);

					if (NULL == (row = DBfetch(result)))
						triggerid = 0;
					else
					{
						ZBX_STR2UINT64(triggerid, row[0]);
						if (triggerid == condition_value)
							ret = SUCCEED;
					}
					DBfree_result(result);
				}
			}

			if (CONDITION_OPERATOR_NOT_EQUAL == condition->operator)
				ret = (SUCCEED == ret) ? FAIL : SUCCEED;
			break;
		default:
			zabbix_log(LOG_LEVEL_ERR, "Unsupported operator [%d] for condition id [" ZBX_FS_UI64 "]",
					condition->operator, condition->conditionid);
		}
	}
	else if (condition->conditiontype == CONDITION_TYPE_TRIGGER_NAME)
	{
		tmp_str = zbx_strdup(tmp_str, event->trigger.description);

		substitute_simple_macros(event, NULL, NULL, NULL, NULL, &tmp_str, MACRO_TYPE_TRIGGER_DESCRIPTION, NULL, 0);

		switch (condition->operator)
		{
		case CONDITION_OPERATOR_LIKE:
			if (NULL != strstr(tmp_str, condition->value))
				ret = SUCCEED;
			break;
		case CONDITION_OPERATOR_NOT_LIKE:
			if (NULL == strstr(tmp_str, condition->value))
				ret = SUCCEED;
			break;
		default:
			zabbix_log(LOG_LEVEL_ERR, "Unsupported operator [%d] for condition id [" ZBX_FS_UI64 "]",
					condition->operator,
					condition->conditionid);
		}
		zbx_free(tmp_str);
	}
	else if (condition->conditiontype == CONDITION_TYPE_TRIGGER_SEVERITY)
	{
		condition_value = atoi(condition->value);

		switch (condition->operator)
		{
		case CONDITION_OPERATOR_EQUAL:
			if (event->trigger.priority == condition_value)
				ret = SUCCEED;
			break;
		case CONDITION_OPERATOR_NOT_EQUAL:
			if (event->trigger.priority != condition_value)
				ret = SUCCEED;
			break;
		case CONDITION_OPERATOR_MORE_EQUAL:
			if (event->trigger.priority >= condition_value)
				ret = SUCCEED;
			break;
		case CONDITION_OPERATOR_LESS_EQUAL:
			if (event->trigger.priority <= condition_value)
				ret = SUCCEED;
			break;
		default:
			zabbix_log(LOG_LEVEL_ERR, "Unsupported operator [%d] for condition id [" ZBX_FS_UI64 "]",
					condition->operator,
					condition->conditionid);
		}
	}
	else if (condition->conditiontype == CONDITION_TYPE_TRIGGER_VALUE)
	{
		condition_value = atoi(condition->value);

		switch (condition->operator)
		{
		case CONDITION_OPERATOR_EQUAL:
			if (event->value == condition_value)
				ret = SUCCEED;
			break;
		default:
			zabbix_log(LOG_LEVEL_ERR, "Unsupported operator [%d] for condition id [" ZBX_FS_UI64 "]",
					condition->operator,
					condition->conditionid);
		}
	}
	else if (condition->conditiontype == CONDITION_TYPE_TIME_PERIOD)
	{
		switch (condition->operator)
		{
		case CONDITION_OPERATOR_IN:
			if (SUCCEED == check_time_period(condition->value, (time_t)NULL))
				ret = SUCCEED;
			break;
		case CONDITION_OPERATOR_NOT_IN:
			if (FAIL == check_time_period(condition->value, (time_t)NULL))
				ret = SUCCEED;
			break;
		default:
			zabbix_log(LOG_LEVEL_ERR, "Unsupported operator [%d] for condition id [" ZBX_FS_UI64 "]",
					condition->operator,
					condition->conditionid);
		}
	}
	else if (condition->conditiontype == CONDITION_TYPE_MAINTENANCE)
	{
		switch (condition->operator) {
		case CONDITION_OPERATOR_IN:
			result = DBselect(
					"select count(*)"
					" from hosts h,items i,functions f,triggers t"
					" where h.hostid=i.hostid"
						" and h.maintenance_status=%d"
						" and i.itemid=f.itemid"
						" and f.triggerid=t.triggerid"
						" and t.triggerid=" ZBX_FS_UI64,
					HOST_MAINTENANCE_STATUS_ON,
					event->objectid);

			if (NULL != (row = DBfetch(result)) && FAIL == DBis_null(row[0]) && 0 != atoi(row[0]))
				ret = SUCCEED;
			DBfree_result(result);
			break;
		case CONDITION_OPERATOR_NOT_IN:
			result = DBselect(
					"select count(*)"
					" from hosts h,items i,functions f,triggers t"
					" where h.hostid=i.hostid"
						" and h.maintenance_status=%d"
						" and i.itemid=f.itemid"
						" and f.triggerid=t.triggerid"
						" and t.triggerid=" ZBX_FS_UI64,
					HOST_MAINTENANCE_STATUS_OFF,
					event->objectid);

			if (NULL != (row = DBfetch(result)) && FAIL == DBis_null(row[0]) && 0 != atoi(row[0]))
				ret = SUCCEED;
			DBfree_result(result);
			break;
		default:
			zabbix_log(LOG_LEVEL_ERR, "Unsupported operator [%d] for condition id [" ZBX_FS_UI64 "]",
					condition->operator,
					condition->conditionid);
		}
	}
	else if (condition->conditiontype == CONDITION_TYPE_NODE)
	{
		nodeid = get_nodeid_by_id(event->objectid);
		condition_value = atoi(condition->value);

		switch (condition->operator) {
		case CONDITION_OPERATOR_EQUAL:
			if (nodeid == condition_value)
				ret = SUCCEED;
			break;
		case CONDITION_OPERATOR_NOT_EQUAL:
			if (nodeid != condition_value)
				ret = SUCCEED;
			break;
		default:
			zabbix_log(LOG_LEVEL_ERR, "Unsupported operator [%d] for condition id [" ZBX_FS_UI64 "]",
					condition->operator,
					condition->conditionid);
		}
	}
	else if (condition->conditiontype == CONDITION_TYPE_EVENT_ACKNOWLEDGED)
	{
		result = DBselect(
				"select acknowledged"
				" from events"
				" where acknowledged=%d"
					" and eventid=" ZBX_FS_UI64,
				atoi(condition->value),
				event->eventid);


		switch (condition->operator)
		{
		case CONDITION_OPERATOR_EQUAL:
			if (NULL != (row = DBfetch(result)))
				ret = SUCCEED;
			break;
		default:
			zabbix_log(LOG_LEVEL_ERR, "Unsupported operator [%d] for condition id [" ZBX_FS_UI64 "]",
					condition->operator,
					condition->conditionid);
		}
		DBfree_result(result);
	}
	else if (condition->conditiontype == CONDITION_TYPE_APPLICATION)
	{
		result = DBselect(
				"select distinct a.name"
				" from applications a,items_applications i,functions f,triggers t"
				" where a.applicationid=i.applicationid"
					" and i.itemid=f.itemid"
					" and f.triggerid=t.triggerid"
					" and t.triggerid=" ZBX_FS_UI64,
				event->objectid);

		switch (condition->operator) {
		case CONDITION_OPERATOR_EQUAL:
			while (NULL != (row = DBfetch(result)))
			{
				if (0 == strcmp(row[0], condition->value))
				{
					ret = SUCCEED;
					break;
				}
			}
			break;
		case CONDITION_OPERATOR_LIKE:
			while (NULL != (row = DBfetch(result)))
			{
				if (NULL != strstr(row[0], condition->value))
				{
					ret = SUCCEED;
					break;
				}
			}
			break;
		case CONDITION_OPERATOR_NOT_LIKE:
			ret = SUCCEED;
			while (NULL != (row = DBfetch(result)))
			{
				if (NULL != strstr(row[0], condition->value))
				{
					ret = FAIL;
					break;
				}
			}
			break;
		default:
			zabbix_log(LOG_LEVEL_ERR, "Unsupported operator [%d] for condition id [" ZBX_FS_UI64 "]",
					condition->operator,
					condition->conditionid);
		}
		DBfree_result(result);
	}
	else
	{
		zabbix_log(LOG_LEVEL_ERR, "Unsupported condition type [%d] for condition id [" ZBX_FS_UI64 "]",
				condition->conditiontype,
				condition->conditionid);
	}

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s():%s", __function_name, zbx_result_string(ret));

	return ret;
}
static void	execute_commands(DB_EVENT *event, zbx_uint64_t actionid, zbx_uint64_t operationid, int esc_step)
{
	const char	*__function_name = "execute_commands";
	DB_RESULT	result;
	DB_ROW		row;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);

	result = DBselect(
			"select distinct h.hostid,h.host,o.type,o.scriptid,o.execute_on,o.port"
				",o.authtype,o.username,o.password,o.publickey,o.privatekey,o.command"
#ifdef HAVE_OPENIPMI
				",h.ipmi_authtype,h.ipmi_privilege,h.ipmi_username,h.ipmi_password"
#endif
			" from opcommand o,opcommand_grp og,hosts_groups hg,hosts h"
			" where o.operationid=og.operationid"
				" and og.groupid=hg.groupid"
				" and hg.hostid=h.hostid"
				" and o.operationid=" ZBX_FS_UI64
				" and h.status=%d"
			" union "
			"select distinct h.hostid,h.host,o.type,o.scriptid,o.execute_on,o.port"
				",o.authtype,o.username,o.password,o.publickey,o.privatekey,o.command"
#ifdef HAVE_OPENIPMI
				",h.ipmi_authtype,h.ipmi_privilege,h.ipmi_username,h.ipmi_password"
#endif
			" from opcommand o,opcommand_hst oh,hosts h"
			" where o.operationid=oh.operationid"
				" and oh.hostid=h.hostid"
				" and o.operationid=" ZBX_FS_UI64
				" and h.status=%d"
			" union "
			"select distinct 0,null,o.type,o.scriptid,o.execute_on,o.port"
				",o.authtype,o.username,o.password,o.publickey,o.privatekey,o.command"
#ifdef HAVE_OPENIPMI
				",0,2,null,null"
#endif
			" from opcommand o,opcommand_hst oh"
			" where o.operationid=oh.operationid"
				" and o.operationid=" ZBX_FS_UI64
				" and oh.hostid is null",
			operationid, HOST_STATUS_MONITORED,
			operationid, HOST_STATUS_MONITORED,
			operationid);

	while (NULL != (row = DBfetch(result)))
	{
		int			rc = SUCCEED;
		char			error[ALERT_ERROR_LEN_MAX];
		DC_HOST			host;
		zbx_script_t		script;
		zbx_alert_status_t	status;

		*error = '\0';
		memset(&host, 0, sizeof(host));
		zbx_script_init(&script);

		ZBX_STR2UINT64(host.hostid, row[0]);

		if (0 != host.hostid)
		{
			strscpy(host.host, row[1]);
#ifdef HAVE_OPENIPMI
			host.ipmi_authtype = (signed char)atoi(row[12]);
			host.ipmi_privilege = (unsigned char)atoi(row[13]);
			strscpy(host.ipmi_username, row[14]);
			strscpy(host.ipmi_password, row[15]);
#endif
		}
		else
			rc = get_dynamic_hostid(event, &host, error, sizeof(error));

		script.type = (unsigned char)atoi(row[2]);

		if (ZBX_SCRIPT_TYPE_GLOBAL_SCRIPT != script.type)
		{
			script.command = zbx_strdup(script.command, row[11]);
			substitute_simple_macros(event, NULL, NULL, NULL, NULL, NULL,
					&script.command, MACRO_TYPE_MESSAGE, NULL, 0);
		}

		if (SUCCEED == rc)
		{
			switch (script.type)
			{
				case ZBX_SCRIPT_TYPE_CUSTOM_SCRIPT:
					script.execute_on = (unsigned char)atoi(row[4]);
					break;
				case ZBX_SCRIPT_TYPE_SSH:
					script.authtype = (unsigned char)atoi(row[6]);
					script.publickey = zbx_strdup(script.publickey, row[9]);
					script.privatekey = zbx_strdup(script.privatekey, row[10]);
					/* break; is not missing here */
				case ZBX_SCRIPT_TYPE_TELNET:
					script.port = zbx_strdup(script.port, row[5]);
					script.username = zbx_strdup(script.username, row[7]);
					script.password = zbx_strdup(script.password, row[8]);
					break;
				case ZBX_SCRIPT_TYPE_GLOBAL_SCRIPT:
					ZBX_DBROW2UINT64(script.scriptid, row[3]);
					break;
			}

			rc = zbx_execute_script(&host, &script, NULL, error, sizeof(error));
		}

		status = (SUCCEED != rc ? ALERT_STATUS_FAILED : ALERT_STATUS_SENT);

		add_command_alert(&host, event->eventid, actionid, esc_step, script.command, status, error);

		zbx_script_clean(&script);
	}
	DBfree_result(result);

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
}
Example #16
0
/******************************************************************************
 *                                                                            *
 * Function: process_httptest                                                 *
 *                                                                            *
 * Purpose: process single scenario of http test                              *
 *                                                                            *
 * Parameters:                                                                *
 *                                                                            *
 * Return value:                                                              *
 *                                                                            *
 * Author: Alexei Vladishev                                                   *
 *                                                                            *
 * Comments:                                                                  *
 *                                                                            *
 ******************************************************************************/
static void	process_httptest(DC_HOST *host, zbx_httptest_t *httptest)
{
    const char	*__function_name = "process_httptest";

    DB_RESULT	result;
    DB_ROW		row;
    DB_HTTPSTEP	httpstep;
    char		*err_str = NULL;
    int		lastfailedstep;
    zbx_timespec_t	ts;
    zbx_httpstat_t	stat;
    double		speed_download = 0;
    int		speed_download_num = 0;
#ifdef HAVE_LIBCURL
    int		err;
    char		auth[HTTPTEST_HTTP_USER_LEN_MAX + HTTPTEST_HTTP_PASSWORD_LEN_MAX];
    CURL            *easyhandle = NULL;
#endif

    zabbix_log(LOG_LEVEL_DEBUG, "In %s() httptestid:" ZBX_FS_UI64 " name:'%s'",
               __function_name, httptest->httptest.httptestid, httptest->httptest.name);

    lastfailedstep = 0;

    result = DBselect(
                 "select httpstepid,no,name,url,timeout,posts,required,status_codes,variables"
                 " from httpstep"
                 " where httptestid=" ZBX_FS_UI64
                 " order by no",
                 httptest->httptest.httptestid);

#ifdef HAVE_LIBCURL
    if (NULL == (easyhandle = curl_easy_init()))
    {
        err_str = zbx_strdup(err_str, "cannot initialize cURL library");
        goto clean;
    }

    if (CURLE_OK != (err = curl_easy_setopt(easyhandle, CURLOPT_PROXY, httptest->httptest.http_proxy)) ||
            CURLE_OK != (err = curl_easy_setopt(easyhandle, CURLOPT_COOKIEFILE, "")) ||
            CURLE_OK != (err = curl_easy_setopt(easyhandle, CURLOPT_USERAGENT, httptest->httptest.agent)) ||
            CURLE_OK != (err = curl_easy_setopt(easyhandle, CURLOPT_FOLLOWLOCATION, 1L)) ||
            CURLE_OK != (err = curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, WRITEFUNCTION2)) ||
            CURLE_OK != (err = curl_easy_setopt(easyhandle, CURLOPT_HEADERFUNCTION, HEADERFUNCTION2)) ||
            CURLE_OK != (err = curl_easy_setopt(easyhandle, CURLOPT_SSL_VERIFYPEER, 0L)) ||
            CURLE_OK != (err = curl_easy_setopt(easyhandle, CURLOPT_SSL_VERIFYHOST, 0L)))
    {
        err_str = zbx_strdup(err_str, curl_easy_strerror(err));
        goto clean;
    }

    while (NULL != (row = DBfetch(result)))
    {
        /* NOTE: do not break or return from this block! */
        /*       process_step_data() call is required! */

        ZBX_STR2UINT64(httpstep.httpstepid, row[0]);
        httpstep.httptestid = httptest->httptest.httptestid;
        httpstep.no = atoi(row[1]);
        httpstep.name = row[2];

        httpstep.url = zbx_strdup(NULL, row[3]);
        substitute_simple_macros(NULL, NULL, NULL, NULL, NULL, host, NULL,
                                 &httpstep.url, MACRO_TYPE_HTTPTEST_FIELD, NULL, 0);

        httpstep.timeout = atoi(row[4]);

        httpstep.posts = zbx_strdup(NULL, row[5]);
        substitute_simple_macros(NULL, NULL, NULL, NULL, NULL, host, NULL,
                                 &httpstep.posts, MACRO_TYPE_HTTPTEST_FIELD, NULL, 0);

        httpstep.required = zbx_strdup(NULL, row[6]);
        substitute_simple_macros(NULL, NULL, NULL, NULL, NULL, host, NULL,
                                 &httpstep.required, MACRO_TYPE_HTTPTEST_FIELD, NULL, 0);

        httpstep.status_codes = zbx_strdup(NULL, row[7]);
        substitute_simple_macros(NULL, NULL, NULL, NULL, &host->hostid, NULL, NULL,
                                 &httpstep.status_codes, MACRO_TYPE_COMMON, NULL, 0);

        httpstep.variables = row[8];

        memset(&stat, 0, sizeof(stat));

        http_substitute_variables(httptest, &httpstep.url);
        http_substitute_variables(httptest, &httpstep.posts);

        zabbix_log(LOG_LEVEL_DEBUG, "%s() use step \"%s\"", __function_name, httpstep.name);

        if (CURLE_OK != (err = curl_easy_setopt(easyhandle, CURLOPT_POSTFIELDS, httpstep.posts)))
        {
            err_str = zbx_strdup(err_str, curl_easy_strerror(err));
            goto httpstep_error;
        }

        if ('\0' != *httpstep.posts)
            zabbix_log(LOG_LEVEL_DEBUG, "%s() use post \"%s\"", __function_name, httpstep.posts);

        if (CURLE_OK != (err = curl_easy_setopt(easyhandle, CURLOPT_POST, '\0' != *httpstep.posts ? 1L : 0L)))
        {
            err_str = zbx_strdup(err_str, curl_easy_strerror(err));
            goto httpstep_error;
        }

        if (HTTPTEST_AUTH_NONE != httptest->httptest.authentication)
        {
            long	curlauth = 0;

            zabbix_log(LOG_LEVEL_DEBUG, "%s() setting HTTPAUTH [%d]",
                       __function_name, httptest->httptest.authentication);
            zabbix_log(LOG_LEVEL_DEBUG, "%s() setting USERPWD for authentication", __function_name);

            switch (httptest->httptest.authentication)
            {
            case HTTPTEST_AUTH_BASIC:
                curlauth = CURLAUTH_BASIC;
                break;
            case HTTPTEST_AUTH_NTLM:
                curlauth = CURLAUTH_NTLM;
                break;
            default:
                THIS_SHOULD_NEVER_HAPPEN;
                break;
            }

            zbx_snprintf(auth, sizeof(auth), "%s:%s", httptest->httptest.http_user,
                         httptest->httptest.http_password);

            if (CURLE_OK != (err = curl_easy_setopt(easyhandle, CURLOPT_HTTPAUTH, curlauth)) ||
                    CURLE_OK != (err = curl_easy_setopt(easyhandle, CURLOPT_USERPWD, auth)))
            {
                err_str = zbx_strdup(err_str, curl_easy_strerror(err));
                goto httpstep_error;
            }
        }

        zabbix_log(LOG_LEVEL_DEBUG, "%s() go to URL \"%s\"", __function_name, httpstep.url);

        if (CURLE_OK != (err = curl_easy_setopt(easyhandle, CURLOPT_TIMEOUT, (long)httpstep.timeout)) ||
                CURLE_OK != (err = curl_easy_setopt(easyhandle, CURLOPT_URL, httpstep.url)))
        {
            err_str = zbx_strdup(err_str, curl_easy_strerror(err));
            goto httpstep_error;
        }

        /* try to retrieve page several times depending on number of retries */
        do
        {
            memset(&page, 0, sizeof(page));

            if (CURLE_OK == (err = curl_easy_perform(easyhandle)))
                break;
        }
        while (0 != --httptest->httptest.retries);

        if (CURLE_OK == err)
        {
            char	*var_err_str = NULL;

            /* first get the data that is needed even if step fails */
            if (CURLE_OK != (err = curl_easy_getinfo(easyhandle, CURLINFO_RESPONSE_CODE, &stat.rspcode)))
            {
                err_str = zbx_strdup(err_str, curl_easy_strerror(err));
            }
            else if ('\0' != *httpstep.status_codes &&
                     FAIL == int_in_list(httpstep.status_codes, stat.rspcode))
            {
                err_str = zbx_strdup(err_str, "status code did not match");
            }

            if (CURLE_OK != (err = curl_easy_getinfo(easyhandle, CURLINFO_TOTAL_TIME, &stat.total_time)) &&
                    NULL == err_str)
            {
                err_str = zbx_strdup(err_str, curl_easy_strerror(err));
            }

            if (CURLE_OK != (err = curl_easy_getinfo(easyhandle, CURLINFO_SPEED_DOWNLOAD,
                                   &stat.speed_download)) && NULL == err_str)
            {
                err_str = zbx_strdup(err_str, curl_easy_strerror(err));
            }
            else
            {
                speed_download += stat.speed_download;
                speed_download_num++;
            }

            /* required pattern */
            if (NULL == err_str && '\0' != *httpstep.required && NULL == zbx_regexp_match(page.data,
                    httpstep.required, NULL))
            {
                err_str = zbx_strdup(err_str, "required pattern not found");
            }

            /* variables defined in scenario */
            if (NULL == err_str && FAIL == http_process_variables(httptest, httptest->httptest.variables,
                    page.data, &var_err_str))
            {
                char	*variables;

                variables = string_replace(httptest->httptest.variables, "\r\n", " ");
                err_str = zbx_dsprintf(err_str, "error in scenario variables \"%s\": %s",
                                       variables, var_err_str);
                zbx_free(variables);
            }

            /* variables defined in a step */
            if (NULL == err_str && FAIL == http_process_variables(httptest, httpstep.variables, page.data,
                    &var_err_str))
            {
                char	*variables;

                variables = string_replace(httpstep.variables, "\r\n", " ");
                err_str = zbx_dsprintf(err_str, "error in step variables \"%s\": %s",
                                       variables, var_err_str);
                zbx_free(variables);
            }

            zbx_free(var_err_str);
        }
        else
            err_str = zbx_strdup(err_str, curl_easy_strerror(err));

        zbx_free(page.data);
httpstep_error:
        zbx_free(httpstep.status_codes);
        zbx_free(httpstep.required);
        zbx_free(httpstep.posts);
        zbx_free(httpstep.url);

        zbx_timespec(&ts);
        process_step_data(httpstep.httpstepid, &stat, &ts);

        if (NULL != err_str)
        {
            lastfailedstep = httpstep.no;
            break;
        }
    }
clean:
    curl_easy_cleanup(easyhandle);
#else
    err_str = zbx_strdup(err_str, "cURL library is required for Web monitoring support");
#endif	/* HAVE_LIBCURL */

    zbx_timespec(&ts);

    if (NULL != err_str)
    {
        if (0 == lastfailedstep)
        {
            /* we are here either because cURL initialization failed */
            /* or we have been compiled without cURL library */

            lastfailedstep = 1;

            if (NULL != (row = DBfetch(result)))
            {
                ZBX_STR2UINT64(httpstep.httpstepid, row[0]);
                httpstep.name = row[2];

                memset(&stat, 0, sizeof(stat));

                process_step_data(httpstep.httpstepid, &stat, &ts);
            }
            else
                THIS_SHOULD_NEVER_HAPPEN;
        }

        zabbix_log(LOG_LEVEL_WARNING, "cannot process step \"%s\" of web scenario \"%s\" on host \"%s\": %s",
                   httpstep.name, httptest->httptest.name, host->name, err_str);
    }
    DBfree_result(result);

    DBexecute("update httptest set nextcheck=%d+delay where httptestid=" ZBX_FS_UI64,
              ts.sec, httptest->httptest.httptestid);

    if (0 != speed_download_num)
        speed_download /= speed_download_num;

    process_test_data(httptest->httptest.httptestid, lastfailedstep, speed_download, err_str, &ts);

    zbx_free(err_str);

    dc_flush_history();

    zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
}
static void	add_message_alert(DB_ESCALATION *escalation, DB_EVENT *event, DB_ACTION *action,
		zbx_uint64_t userid, zbx_uint64_t mediatypeid, const char *subject, const char *message)
{
	const char	*__function_name = "add_message_alert";

	DB_RESULT	result;
	DB_ROW		row;
	zbx_uint64_t	alertid;
	int		now, severity, medias = 0;
	char		*subject_dyn, *message_dyn, *sendto_esc, *subject_esc, *message_esc, *error_esc;
	char		error[MAX_STRING_LEN];

	zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);

	subject_dyn = zbx_strdup(NULL, subject);
	message_dyn = zbx_strdup(NULL, message);

	substitute_simple_macros(event, &userid, NULL, NULL, NULL, NULL, &subject_dyn, MACRO_TYPE_MESSAGE, NULL, 0);
	substitute_simple_macros(event, &userid, NULL, NULL, NULL, NULL, &message_dyn, MACRO_TYPE_MESSAGE, NULL, 0);

	now = time(NULL);
	subject_esc = DBdyn_escape_string_len(subject_dyn, ALERT_SUBJECT_LEN);
	message_esc = DBdyn_escape_string_len(message_dyn, ALERT_MESSAGE_LEN);

	zbx_free(subject_dyn);
	zbx_free(message_dyn);

	if (0 == mediatypeid)
	{
		result = DBselect(
				"select m.mediatypeid,m.sendto,m.severity,m.period,mt.status"
				" from media m,media_type mt"
				" where m.mediatypeid=mt.mediatypeid"
					" and m.active=%d"
					" and m.userid=" ZBX_FS_UI64,
				MEDIA_STATUS_ACTIVE, userid);
	}
	else
	{
		result = DBselect(
				"select m.mediatypeid,m.sendto,m.severity,m.period,mt.status"
				" from media m,media_type mt"
				" where m.mediatypeid=mt.mediatypeid"
					" and m.active=%d"
					" and m.userid=" ZBX_FS_UI64
					" and m.mediatypeid=" ZBX_FS_UI64,
				MEDIA_STATUS_ACTIVE, userid, mediatypeid);
	}

	while (NULL != (row = DBfetch(result)))
	{
		medias		= 1;

		ZBX_STR2UINT64(mediatypeid, row[0]);
		severity	= atoi(row[2]);

		zabbix_log(LOG_LEVEL_DEBUG, "Trigger severity [%d] Media severity [%d] Period [%s]",
				(int)event->trigger.priority, severity, row[3]);

		if (((1 << event->trigger.priority) & severity) == 0)
		{
			zabbix_log(LOG_LEVEL_DEBUG, "Won't send message (severity)");
			continue;
		}

		if (FAIL == check_time_period(row[3], (time_t)NULL))
		{
			zabbix_log(LOG_LEVEL_DEBUG, "Won't send message (period)");
			continue;
		}

		alertid		= DBget_maxid("alerts");
		sendto_esc	= DBdyn_escape_string_len(row[1], ALERT_SENDTO_LEN);

		if (MEDIA_TYPE_STATUS_ACTIVE == atoi(row[4]))
		{
			DBexecute("insert into alerts (alertid,actionid,eventid,userid,clock"
					",mediatypeid,sendto,subject,message,status,alerttype,esc_step)"
					" values (" ZBX_FS_UI64 "," ZBX_FS_UI64 "," ZBX_FS_UI64 "," ZBX_FS_UI64 ",%d"
					"," ZBX_FS_UI64 ",'%s','%s','%s',%d,%d,%d)",
					alertid,
					action->actionid,
					event->eventid,
					userid,
					now,
					mediatypeid,
					sendto_esc,
					subject_esc,
					message_esc,
					ALERT_STATUS_NOT_SENT,
					ALERT_TYPE_MESSAGE,
					escalation->esc_step);
		}
		else
		{
			error_esc = DBdyn_escape_string("Media type disabled");

			DBexecute("insert into alerts (alertid,actionid,eventid,userid,clock"
					",mediatypeid,sendto,subject,message,status,alerttype,esc_step,error)"
					" values (" ZBX_FS_UI64 "," ZBX_FS_UI64 "," ZBX_FS_UI64 "," ZBX_FS_UI64 ",%d"
					"," ZBX_FS_UI64 ",'%s','%s','%s',%d,%d,%d,'%s')",
					alertid,
					action->actionid,
					event->eventid,
					userid,
					now,
					mediatypeid,
					sendto_esc,
					subject_esc,
					message_esc,
					ALERT_STATUS_FAILED,
					ALERT_TYPE_MESSAGE,
					escalation->esc_step,
					error_esc);

			zbx_free(error_esc);
		}

		zbx_free(sendto_esc);
	}

	DBfree_result(result);

	if (0 == medias)
	{
		zbx_snprintf(error, sizeof(error), "No media defined for user \"%s\"",
				zbx_user_string(userid));

		alertid		= DBget_maxid("alerts");
		error_esc	= DBdyn_escape_string(error);

		DBexecute("insert into alerts (alertid,actionid,eventid,userid,retries,clock"
				",subject,message,status,alerttype,error,esc_step)"
				" values (" ZBX_FS_UI64 "," ZBX_FS_UI64 "," ZBX_FS_UI64 "," ZBX_FS_UI64 ",%d,%d"
				",'%s','%s',%d,%d,'%s',%d)",
				alertid,
				action->actionid,
				event->eventid,
				userid,
				ALERT_MAX_RETRIES,
				now,
				subject_esc,
				message_esc,
				ALERT_STATUS_FAILED,
				ALERT_TYPE_MESSAGE,
				error_esc,
				escalation->esc_step);

		zbx_free(error_esc);
	}

	zbx_free(subject_esc);
	zbx_free(message_esc);

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
}
Example #18
0
/******************************************************************************
 *                                                                            *
 * Function: process_proxy                                                    *
 *                                                                            *
 * Purpose: retrieve values of metrics from monitored hosts                   *
 *                                                                            *
 * Parameters:                                                                *
 *                                                                            *
 * Return value:                                                              *
 *                                                                            *
 * Author: Alexei Vladishev                                                   *
 *                                                                            *
 * Comments:                                                                  *
 *                                                                            *
 ******************************************************************************/
static int	process_proxy(void)
{
	const char		*__function_name = "process_proxy";
	DC_PROXY		proxy;
	int			num, i, ret;
	struct zbx_json		j;
	struct zbx_json_parse	jp, jp_data;
	zbx_socket_t		s;
	char			*answer = NULL, *port = NULL;
	time_t			now;
	unsigned char		update_nextcheck;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name);

	if (0 == (num = DCconfig_get_proxypoller_hosts(&proxy, 1)))
		goto exit;

	now = time(NULL);

	zbx_json_init(&j, 512 * 1024);

	for (i = 0; i < num; i++)
	{
		update_nextcheck = 0;

		if (proxy.proxy_config_nextcheck <= now)
			update_nextcheck |= 0x01;
		if (proxy.proxy_data_nextcheck <= now)
			update_nextcheck |= 0x02;

		proxy.addr = proxy.addr_orig;

		port = zbx_strdup(port, proxy.port_orig);
		substitute_simple_macros(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
				&port, MACRO_TYPE_COMMON, NULL, 0);
		if (FAIL == is_ushort(port, &proxy.port))
		{
			zabbix_log(LOG_LEVEL_ERR, "invalid proxy \"%s\" port: \"%s\"", proxy.host, port);
			goto network_error;
		}

		if (proxy.proxy_config_nextcheck <= now)
		{
			char	*error = NULL;

			zbx_json_clean(&j);

			zbx_json_addstring(&j, ZBX_PROTO_TAG_REQUEST,
					ZBX_PROTO_VALUE_PROXY_CONFIG, ZBX_JSON_TYPE_STRING);
			zbx_json_addobject(&j, ZBX_PROTO_TAG_DATA);

			if (SUCCEED != (ret = get_proxyconfig_data(proxy.hostid, &j, &error)))
			{
				zabbix_log(LOG_LEVEL_ERR, "cannot collect configuration data for proxy \"%s\": %s",
						proxy.host, error);
				zbx_free(error);

				goto network_error;
			}

			if (SUCCEED == (ret = connect_to_proxy(&proxy, &s, CONFIG_TRAPPER_TIMEOUT)))
			{
				zabbix_log(LOG_LEVEL_WARNING, "sending configuration data to proxy \"%s\" at \"%s\","
						" datalen " ZBX_FS_SIZE_T,
						proxy.host, get_ip_by_socket(&s), (zbx_fs_size_t)j.buffer_size);

				if (SUCCEED == (ret = send_data_to_proxy(&proxy, &s, j.buffer)))
				{
					char	*error = NULL;

					if (SUCCEED != (ret = zbx_recv_response(&s, 0, &error)))
					{
						zabbix_log(LOG_LEVEL_WARNING, "cannot send configuration data to proxy"
								" \"%s\" at \"%s\": %s",
								proxy.host, get_ip_by_socket(&s), error);
					}
					zbx_free(error);
				}

				disconnect_proxy(&s);
			}

			if (SUCCEED != ret)
				goto network_error;
		}

		if (proxy.proxy_data_nextcheck <= now)
		{
			if (SUCCEED == get_data_from_proxy(&proxy,
					ZBX_PROTO_VALUE_HOST_AVAILABILITY, &answer))
			{
				if (SUCCEED == zbx_json_open(answer, &jp))
					process_host_availability(&jp);

				zbx_free(answer);
			}
			else
				goto network_error;
retry_history:
			if (SUCCEED == get_data_from_proxy(&proxy,
					ZBX_PROTO_VALUE_HISTORY_DATA, &answer))
			{
				if (SUCCEED == zbx_json_open(answer, &jp))
				{
					process_hist_data(NULL, &jp, proxy.hostid, NULL, 0);

					if (SUCCEED == zbx_json_brackets_by_name(&jp, ZBX_PROTO_TAG_DATA, &jp_data))
					{
						if (ZBX_MAX_HRECORDS <= zbx_json_count(&jp_data))
						{
							zbx_free(answer);
							goto retry_history;
						}
					}
				}
				zbx_free(answer);
			}
			else
				goto network_error;
retry_dhistory:
			if (SUCCEED == get_data_from_proxy(&proxy,
					ZBX_PROTO_VALUE_DISCOVERY_DATA, &answer))
			{
				if (SUCCEED == zbx_json_open(answer, &jp))
				{
					process_dhis_data(&jp);

					if (SUCCEED == zbx_json_brackets_by_name(&jp, ZBX_PROTO_TAG_DATA, &jp_data))
					{
						if (ZBX_MAX_HRECORDS <= zbx_json_count(&jp_data))
						{
							zbx_free(answer);
							goto retry_dhistory;
						}
					}
				}
				zbx_free(answer);
			}
			else
				goto network_error;
retry_autoreg_host:
			if (SUCCEED == get_data_from_proxy(&proxy,
					ZBX_PROTO_VALUE_AUTO_REGISTRATION_DATA, &answer))
			{
				if (SUCCEED == zbx_json_open(answer, &jp))
				{
					process_areg_data(&jp, proxy.hostid);

					if (SUCCEED == zbx_json_brackets_by_name(&jp, ZBX_PROTO_TAG_DATA, &jp_data))
					{
						if (ZBX_MAX_HRECORDS <= zbx_json_count(&jp_data))
						{
							zbx_free(answer);
							goto retry_autoreg_host;
						}
					}
				}
				zbx_free(answer);
			}
			else
				goto network_error;
		}

		DBbegin();
		update_proxy_lastaccess(proxy.hostid);
		DBcommit();
network_error:
		DCrequeue_proxy(proxy.hostid, update_nextcheck);
	}

	zbx_free(port);

	zbx_json_free(&j);
exit:
	zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);

	return num;
}