Пример #1
0
/******************************************************************************
 *                                                                            *
 * Function: process_values                                                   *
 *                                                                            *
 * Purpose: process new item values                                           *
 *                                                                            *
 * Parameters:                                                                *
 *                                                                            *
 * Return value:                                                              *
 *                                                                            *
 * Author: Alexei Vladishev, Alexander Vladishev                              *
 *                                                                            *
 * Comments:                                                                  *
 *                                                                            *
 ******************************************************************************/
static void	process_values(icmpitem_t *items, int first_index, int last_index, ZBX_FPING_HOST *hosts,
		int hosts_count, zbx_timespec_t *ts, int ping_result, char *error)
{
	const char	*__function_name = "process_values";
	int		i, h;
	zbx_uint64_t	value_uint64;
	double		value_dbl;

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

	for (h = 0; h < hosts_count; h++)
	{
		if (NOTSUPPORTED == ping_result)
			zabbix_log(LOG_LEVEL_DEBUG, "Host [%s] %s",
					hosts[h].addr, error);
		else
			zabbix_log(LOG_LEVEL_DEBUG, "Host [%s] cnt=%d rcv=%d min/max/avg=" ZBX_FS_DBL "/" ZBX_FS_DBL "/" ZBX_FS_DBL,
					hosts[h].addr, hosts[h].cnt, hosts[h].rcv, hosts[h].min, hosts[h].max, hosts[h].avg);

		for (i = first_index; i < last_index; i++)
		{
			if (0 == strcmp(items[i].addr, hosts[h].addr))
			{
				switch (items[i].icmpping)
				{
					case ICMPPING:
						value_uint64 = hosts[h].rcv ? 1 : 0;
						process_value(items[i].itemid, &value_uint64, NULL, ts, ping_result, error);
						break;
					case ICMPPINGSEC:
						switch (items[i].type)
						{
							case ICMPPINGSEC_MIN:
								value_dbl = hosts[h].min;
								break;
							case ICMPPINGSEC_MAX:
								value_dbl = hosts[h].max;
								break;
							case ICMPPINGSEC_AVG:
								value_dbl = hosts[h].avg;
								break;
						}
						process_value(items[i].itemid, NULL, &value_dbl, ts, ping_result, error);
						break;
					case ICMPPINGLOSS:
						if (0 == hosts[h].cnt)
							value_dbl = 0;
						else
							value_dbl = 100 * (1 - (double)hosts[h].rcv / (double)hosts[h].cnt);
						process_value(items[i].itemid, NULL, &value_dbl, ts, ping_result, error);
						break;
				}
			}
		}
	}

	dc_flush_history();

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
}
Пример #2
0
static void	process_test_data(zbx_uint64_t httptestid, ZBX_HTTPSTAT *stat)
{
	const char	*__function_name = "process_test_data";

	DB_RESULT	result;
	DB_ROW		row;
	DB_HTTPTESTITEM	httptestitem;

	AGENT_RESULT    value;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s() httptestid:" ZBX_FS_UI64 " total_time:" ZBX_FS_DBL " last_step:%d",
			__function_name, httptestid, stat->test_total_time, stat->test_last_step);

	result = DBselect("select httptestitemid,httptestid,itemid,type"
				" from httptestitem"
				" where httptestid=" ZBX_FS_UI64,
				httptestid);

	while (NULL != (row = DBfetch(result)))
	{
		ZBX_STR2UINT64(httptestitem.httptestitemid, row[0]);
		ZBX_STR2UINT64(httptestitem.httptestid, row[1]);
		ZBX_STR2UINT64(httptestitem.itemid, row[2]);
		httptestitem.type = atoi(row[3]);

		init_result(&value);

		switch (httptestitem.type)
		{
			case ZBX_HTTPITEM_TYPE_TIME:
				SET_DBL_RESULT(&value, stat->test_total_time);
				process_value(httptestitem.itemid, &value);
				break;
			case ZBX_HTTPITEM_TYPE_LASTSTEP:
				SET_UI64_RESULT(&value, stat->test_last_step);
				process_value(httptestitem.itemid, &value);
				break;
			case ZBX_HTTPITEM_TYPE_SPEED:
				SET_UI64_RESULT(&value, stat->speed_download);
				process_value(httptestitem.itemid, &value);
				break;
			default:
				break;
		}

		free_result(&value);
	}

	DBfree_result(result);

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
}
Пример #3
0
/*
 * process_object - process an object
 *    return: 1 - object has changed
 *	      0 - object has not changed
 *	     -1 - object failed
 *    upd_scancache(in):
 *    attr_info(in):
 *    oid(in): the oid of the object to process
 */
static int
process_object (THREAD_ENTRY * thread_p, HEAP_SCANCACHE * upd_scancache,
		HEAP_CACHE_ATTRINFO * attr_info, OID * oid)
{
  int i, result = 0;
  int updated_flag = 0;
  HEAP_ATTRVALUE *value = NULL;
  int force_count = 0, updated_n_attrs_id = 0;
  int *atts_id = NULL;

  if (upd_scancache == NULL || attr_info == NULL || oid == NULL)
    {
      return -1;
    }

  atts_id = (int *) db_private_alloc (thread_p,
				      attr_info->num_values * sizeof (int));
  if (atts_id == NULL)
    {
      return -1;
    }

  for (i = 0, value = attr_info->values;
       i < attr_info->num_values; i++, value++)
    {
      if (process_value (&value->dbvalue))
	{
	  value->state = HEAP_WRITTEN_ATTRVALUE;
	  atts_id[updated_n_attrs_id] = value->attrid;
	  updated_n_attrs_id++;
	}
    }

  if ((updated_n_attrs_id > 0) ||
      (attr_info->read_classrepr != NULL && attr_info->last_classrepr != NULL
       && attr_info->read_classrepr->id != attr_info->last_classrepr->id))
    {
      if (locator_attribute_info_force
	  (thread_p, &upd_scancache->hfid, oid, 0, attr_info, atts_id,
	   updated_n_attrs_id, LC_FLUSH_UPDATE, SINGLE_ROW_UPDATE,
	   upd_scancache, &force_count, false,
	   REPL_INFO_TYPE_STMT_NORMAL) != NO_ERROR)
	{
	  result = -1;
	}

      result = 1;
    }

  if (atts_id)
    {
      db_private_free (thread_p, atts_id);
      atts_id = NULL;
    }

  return result;
}
Пример #4
0
/*
 ft_thread_await(evt);
 ft_thread_generate(evt);
*/
void process (void *args)
{
  while (1) {
    if (size(in) > 0) {
       process_value(get(&in), *((int *) args));
    } else {
       ft_thread_await (new_input);
       if (size(in) == 0) ft_thread_cooperate();
    }
  }
}
Пример #5
0
bool console_argument_parser_c::parse(abstract_settings_parser_c &parser_object) {
    console_argument_parser_c::parser_object = &parser_object;
    last_state = argument_error_state;
    if (process_argument(parser_object.get_next_argument()) == argument_error_state) {
        return false;
    }
    while (last_state == argument_started_state) {
        process_value(parser_object.get_next_argument());
    }
    return last_state == argument_ok_state;
}
Пример #6
0
static void process_array(json_value* value, int depth)
{
        int length, x;
        if (value == NULL) {
                return;
        }
        length = value->u.array.length;
        DEBUG("array\n");
        for (x = 0; x < length; x++) {
                process_value(value->u.array.values[x], depth);
        }
}
Пример #7
0
static void process_object(json_value* value, int depth)
{
        int length, x;
        if (value == NULL) {
                return;
        }
        length = value->u.object.length;
        for (x = 0; x < length; x++) {
                print_depth_shift(depth);
                DEBUG("object[%d].name = %s\n", x, value->u.object.values[x].name);
                process_value(value->u.object.values[x].value, depth+1);
        }
}
Пример #8
0
/*
 * process_set - process one set
 *    return: whether the object should be updated.
 *    set(in): the set to process
 */
static int
process_set (DB_SET * set)
{
  SET_ITERATOR *it;
  DB_VALUE *element_value;
  int return_value = 0;

  it = set_iterate (set);
  while ((element_value = set_iterator_value (it)) != NULL)
    {
      return_value += process_value (element_value);
      set_iterator_next (it);
    }
  set_iterator_free (it);

  return return_value;
}
Пример #9
0
void process (void *args)
{
  while (1) {
    if (size(file) > 0){
      int res = get (&file);
      if (res == CYCLES) {
	PRINT("result: %d\n",res);
	processed++;
	if (processed == PRODUCED) exit (0);
      }else{
	process_value(res);
      }
    }else{
      ft_thread_await (new_elem);
      if (size (file) == 0) ft_thread_cooperate ();
    }
  }
}
Пример #10
0
console_argument_parser_c::parsing_state_e console_argument_parser_c::process_argument(const char *argument) {
    //check if in the dictionary
    if (!argument) {
        return last_state = argument_error_state;
    }
    std::string s = argument;
    std::string left, right;
    if (is_flag.find(std::string(argument)) != is_flag.end()) {
        value = "1";
        current_argument_parser = parameters[argument];
        last_state = argument_ok_state;
        return last_state;
    }
    size_t length = s.length();
    size_t divider_length = 0;
    for (auto i = parser_object->dividers.begin(); i != parser_object->dividers.end(); i++) {
        size_t pos = s.find(*i);
        length = min_def(length, pos);
        if (length == pos) {
            divider_length = max_def(divider_length, (*i).length());
        }
    }
    left = s.substr(0, length);
    //check left
    if (parameters.find(left) == parameters.end()) {
        return argument_error_state;
    } else if (is_flag.find(left) != is_flag.end()) {
        return argument_error_state;
    }
    current_argument_parser = parameters[left];
    last_state = argument_started_state;
    if (length < s.length()) {
        right = s.substr(length + divider_length, s.length() - length - divider_length);
        return process_value(right.c_str());
    }
    return last_state;
}
Пример #11
0
static void	process_active_checks(char *server, unsigned short port)
{
	register int	i, s_count, p_count;
	char		**pvalue;
	int		now, send_err = SUCCEED, ret;
	unsigned long	timestamp;
	char		*source = NULL;
	char		*value = NULL;
	unsigned short	severity;
	long		lastlogsize;
	char		params[MAX_STRING_LEN];
	char		filename[MAX_STRING_LEN];
	char		pattern[MAX_STRING_LEN];

	AGENT_RESULT	result;

	zabbix_log( LOG_LEVEL_DEBUG, "In process_active_checks('%s',%u)",server, port);

	init_result(&result);

	now = (int)time(NULL);

	for(i=0; NULL != active_metrics[i].key && SUCCEED == send_err; i++)
	{
		if(active_metrics[i].nextcheck > now)			continue;
		if(active_metrics[i].status != ITEM_STATUS_ACTIVE)	continue;

		/* Special processing for log files */
		if(strncmp(active_metrics[i].key,"log[",4) == 0)
		{
			do{ /* simple try realization */
				if (parse_command(active_metrics[i].key, NULL, 0, params, MAX_STRING_LEN) != 2)
					break;
				
				if (num_param(params) > 2)
					break;

				if (get_param(params, 1, filename, sizeof(filename)) != 0)
					break;

				if (get_param(params, 2, pattern, sizeof(pattern)) != 0)
					*pattern = '\0';

				s_count = 0;
				p_count = 0;
				lastlogsize = active_metrics[i].lastlogsize;
				while (SUCCEED == (ret = process_log(filename, &lastlogsize, &value))) {
					if (!value) /* EOF */
						break;

					if (SUCCEED == regexp_match_ex(regexps, regexps_num, value, pattern, ZBX_CASE_SENSITIVE)) {
						send_err = process_value(
									server,
									port,
									CONFIG_HOSTNAME,
									active_metrics[i].key_orig,
									value,
									&lastlogsize,
									NULL,
									NULL,
									NULL
								);
						s_count++;
					}
					p_count++;

					zbx_free(value);

					if (SUCCEED == send_err)
						active_metrics[i].lastlogsize = lastlogsize;
					else
						lastlogsize = active_metrics[i].lastlogsize;

					/* Do not flood ZABBIX server if file grows too fast */
					if(s_count >= (MAX_LINES_PER_SECOND * active_metrics[i].refresh))	break;

					/* Do not flood local system if file grows too fast */
					if(p_count >= (4 * MAX_LINES_PER_SECOND * active_metrics[i].refresh))	break;
				}

				if( FAIL == ret )
				{
					active_metrics[i].status = ITEM_STATUS_NOTSUPPORTED;
					zabbix_log( LOG_LEVEL_WARNING, "Active check [%s] is not supported. Disabled.",
						active_metrics[i].key);

					send_err = process_value(
								server,
								port,
								CONFIG_HOSTNAME,
								active_metrics[i].key_orig,
								"ZBX_NOTSUPPORTED",
								&active_metrics[i].lastlogsize,
								NULL,
								NULL,
								NULL
							);
				}

			}while(0); /* simple try realization */
		}
		/* Special processing for eventlog */
		else if(strncmp(active_metrics[i].key,"eventlog[",9) == 0)
		{
			do{ /* simple try realization */
				if (parse_command(active_metrics[i].key, NULL, 0, params, MAX_STRING_LEN) != 2)
					break;
				
				if (num_param(params) > 2)
					break;

				if (get_param(params, 1, filename, sizeof(filename)) != 0)
					break;

				if (get_param(params, 2, pattern, sizeof(pattern)) != 0)
					*pattern = '\0';

				s_count = 0;
				p_count = 0;
				lastlogsize = active_metrics[i].lastlogsize;
				while (SUCCEED == (ret = process_eventlog(filename, &lastlogsize,
					&timestamp, &source, &severity, &value)))
				{
					if (!value) /* EOF */
						break;

					if (SUCCEED == regexp_match_ex(regexps, regexps_num, value, pattern, ZBX_CASE_SENSITIVE)) {
						send_err = process_value(
									server,
									port,
									CONFIG_HOSTNAME,
									active_metrics[i].key_orig,
									value,
									&lastlogsize,
									&timestamp,
									source,
									&severity
								);
						s_count++;
					}
					p_count++;

					zbx_free(source);
					zbx_free(value);

					if (SUCCEED == send_err)
						active_metrics[i].lastlogsize = lastlogsize;
					else
						lastlogsize = active_metrics[i].lastlogsize;

					/* Do not flood ZABBIX server if file grows too fast */
					if(s_count >= (MAX_LINES_PER_SECOND * active_metrics[i].refresh))	break;

					/* Do not flood local system if file grows too fast */
					if(p_count >= (4 * MAX_LINES_PER_SECOND * active_metrics[i].refresh))	break;
				}

				if( FAIL == ret )
				{
					active_metrics[i].status = ITEM_STATUS_NOTSUPPORTED;
					zabbix_log( LOG_LEVEL_WARNING, "Active check [%s] is not supported. Disabled.",
						active_metrics[i].key);

					send_err = process_value(
								server,
								port,
								CONFIG_HOSTNAME,
								active_metrics[i].key_orig,
								"ZBX_NOTSUPPORTED",
								&active_metrics[i].lastlogsize,
								NULL,
								NULL,
								NULL
							);
				}
			}while(0); /* simple try realization NOTE: never loop */
		}
		else
		{
			
			process(active_metrics[i].key, 0, &result);

			if( NULL == (pvalue = GET_TEXT_RESULT(&result)) )
				pvalue = GET_MSG_RESULT(&result);

			if(pvalue)
			{
				zabbix_log( LOG_LEVEL_DEBUG, "For key [%s] received value [%s]", active_metrics[i].key, *pvalue);

				send_err = process_value(
						server,
						port,
						CONFIG_HOSTNAME,
						active_metrics[i].key_orig,
						*pvalue,
						NULL,
						NULL,
						NULL,
						NULL
					);
				
				if( 0 == strcmp(*pvalue,"ZBX_NOTSUPPORTED") )
				{
					active_metrics[i].status = ITEM_STATUS_NOTSUPPORTED;
					zabbix_log( LOG_LEVEL_WARNING, "Active check [%s] is not supported. Disabled.", active_metrics[i].key);
				}
			}

			free_result(&result);
		}
		active_metrics[i].nextcheck = (int)time(NULL)+active_metrics[i].refresh;
	}
}
Пример #12
0
/*
 *	Initialize the dictionary.
 */
static int my_dict_init(const char *dir, const char *fn,
			const char *src_file, int src_line)
{
	FILE	*fp;
	char 	dirtmp[256];
	char	buf[256];
	char	*p;
	int	line = 0;
	int	vendor;
	int	block_vendor;
	struct stat statbuf;
	char	*argv[MAX_ARGV];
	int	argc;
	DICT_ATTR *da, *block_tlv = NULL;

	if (strlen(fn) >= sizeof(dirtmp) / 2 ||
	    strlen(dir) >= sizeof(dirtmp) / 2) {
		fr_strerror_printf("dict_init: filename name too long");
		return -1;
	}

	/*
	 *	First see if fn is relative to dir. If so, create
	 *	new filename. If not, remember the absolute dir.
	 */
	if ((p = strrchr(fn, FR_DIR_SEP)) != NULL) {
		strcpy(dirtmp, fn);
		dirtmp[p - fn] = 0;
		dir = dirtmp;
	} else if (dir && dir[0] && strcmp(dir, ".") != 0) {
		snprintf(dirtmp, sizeof(dirtmp), "%s/%s", dir, fn);
		fn = dirtmp;
	}

	if ((fp = fopen(fn, "r")) == NULL) {
		if (!src_file) {
			fr_strerror_printf("dict_init: Couldn't open dictionary \"%s\": %s",
				   fn, strerror(errno));
		} else {
			fr_strerror_printf("dict_init: %s[%d]: Couldn't open dictionary \"%s\": %s",
				   src_file, src_line, fn, strerror(errno));
		}
		return -1;
	}

	stat(fn, &statbuf); /* fopen() guarantees this will succeed */
	if (!S_ISREG(statbuf.st_mode)) {
		fclose(fp);
		fr_strerror_printf("dict_init: Dictionary \"%s\" is not a regular file",
			   fn);
		return -1;
	}

	/*
	 *	Globally writable dictionaries means that users can control
	 *	the server configuration with little difficulty.
	 */
#ifdef S_IWOTH
	if ((statbuf.st_mode & S_IWOTH) != 0) {
		fclose(fp);
		fr_strerror_printf("dict_init: Dictionary \"%s\" is globally writable.  Refusing to start due to insecure configuration.",
			   fn);
		return -1;
	}
#endif

	dict_stat_add(fn, &statbuf);

	/*
	 *	Seed the random pool with data.
	 */
	fr_rand_seed(&statbuf, sizeof(statbuf));

	block_vendor = 0;

	while (fgets(buf, sizeof(buf), fp) != NULL) {
		line++;
		if (buf[0] == '#' || buf[0] == 0 ||
		    buf[0] == '\n' || buf[0] == '\r')
			continue;

		/*
		 *  Comment characters should NOT be appearing anywhere but
		 *  as start of a comment;
		 */
		p = strchr(buf, '#');
		if (p) *p = '\0';

		argc = str2argv(buf, argv, MAX_ARGV);
		if (argc == 0) continue;

		if (argc == 1) {
			fr_strerror_printf( "dict_init: %s[%d] invalid entry",
				    fn, line);
			fclose(fp);
			return -1;
		}

		/*
		 *	Process VALUE lines.
		 */
		if (strcasecmp(argv[0], "VALUE") == 0) {
			if (process_value(fn, line,
					  argv + 1, argc - 1) == -1) {
				fclose(fp);
				return -1;
			}
			continue;
		}

		/*
		 *	Perhaps this is an attribute.
		 */
		if (strcasecmp(argv[0], "ATTRIBUTE") == 0) {
			if (process_attribute(fn, line, block_vendor,
					      block_tlv,
					      argv + 1, argc - 1) == -1) {
				fclose(fp);
				return -1;
			}
			continue;
		}

		/*
		 *	See if we need to import another dictionary.
		 */
		if (strcasecmp(argv[0], "$INCLUDE") == 0) {
			if (my_dict_init(dir, argv[1], fn, line) < 0) {
				fclose(fp);
				return -1;
			}
			continue;
		} /* $INCLUDE */

		if (strcasecmp(argv[0], "VALUE-ALIAS") == 0) {
			if (process_value_alias(fn, line,
						argv + 1, argc - 1) == -1) {
				fclose(fp);
				return -1;
			}
			continue;
		}

		/*
		 *	Process VENDOR lines.
		 */
		if (strcasecmp(argv[0], "VENDOR") == 0) {
			if (process_vendor(fn, line,
					   argv + 1, argc - 1) == -1) {
				fclose(fp);
				return -1;
			}
			continue;
		}

		if (strcasecmp(argv[0], "BEGIN-TLV") == 0) {
			if (argc != 2) {
				fr_strerror_printf(
				"dict_init: %s[%d] invalid BEGIN-TLV entry",
					fn, line);
				fclose(fp);
				return -1;
			}

			da = dict_attrbyname(argv[1]);
			if (!da) {
				fr_strerror_printf(
					"dict_init: %s[%d]: unknown attribute %s",
					fn, line, argv[1]);
				fclose(fp);
				return -1;
			}

			if (da->type != PW_TYPE_TLV) {
				fr_strerror_printf(
					"dict_init: %s[%d]: attribute %s is not of type tlv",
					fn, line, argv[1]);
				fclose(fp);
				return -1;
			}

			if (block_tlv) {
				fr_strerror_printf(
					"dict_init: %s[%d]: Cannot nest TLVs",
					fn, line);
				fclose(fp);
				return -1;
			}

			block_tlv = da;
			continue;
		} /* BEGIN-TLV */

		if (strcasecmp(argv[0], "END-TLV") == 0) {
			if (argc != 2) {
				fr_strerror_printf(
				"dict_init: %s[%d] invalid END-TLV entry",
					fn, line);
				fclose(fp);
				return -1;
			}

			da = dict_attrbyname(argv[1]);
			if (!da) {
				fr_strerror_printf(
					"dict_init: %s[%d]: unknown attribute %s",
					fn, line, argv[1]);
				fclose(fp);
				return -1;
			}

			if (da != block_tlv) {
				fr_strerror_printf(
					"dict_init: %s[%d]: END-TLV %s does not match any previous BEGIN-TLV",
					fn, line, argv[1]);
				fclose(fp);
				return -1;
			}
			block_tlv = NULL;
			continue;
		} /* END-VENDOR */

		if (strcasecmp(argv[0], "BEGIN-VENDOR") == 0) {
			if (argc != 2) {
				fr_strerror_printf(
				"dict_init: %s[%d] invalid BEGIN-VENDOR entry",
					fn, line);
				fclose(fp);
				return -1;
			}

			vendor = dict_vendorbyname(argv[1]);
			if (!vendor) {
				fr_strerror_printf(
					"dict_init: %s[%d]: unknown vendor %s",
					fn, line, argv[1]);
				fclose(fp);
				return -1;
			}
			block_vendor = vendor;
			continue;
		} /* BEGIN-VENDOR */

		if (strcasecmp(argv[0], "END-VENDOR") == 0) {
			if (argc != 2) {
				fr_strerror_printf(
				"dict_init: %s[%d] invalid END-VENDOR entry",
					fn, line);
				fclose(fp);
				return -1;
			}

			vendor = dict_vendorbyname(argv[1]);
			if (!vendor) {
				fr_strerror_printf(
					"dict_init: %s[%d]: unknown vendor %s",
					fn, line, argv[1]);
				fclose(fp);
				return -1;
			}

			if (vendor != block_vendor) {
				fr_strerror_printf(
					"dict_init: %s[%d]: END-VENDOR %s does not match any previous BEGIN-VENDOR",
					fn, line, argv[1]);
				fclose(fp);
				return -1;
			}
			block_vendor = 0;
			continue;
		} /* END-VENDOR */

		/*
		 *	Any other string: We don't recognize it.
		 */
		fr_strerror_printf("dict_init: %s[%d] invalid keyword \"%s\"",
			   fn, line, argv[0]);
		fclose(fp);
		return -1;
	}
	fclose(fp);
	return 0;
}
Пример #13
0
/******************************************************************************
 *                                                                            *
 * Function: process_values                                                   *
 *                                                                            *
 * Purpose: process new item values                                           *
 *                                                                            *
 * Parameters:                                                                *
 *                                                                            *
 * Return value:                                                              *
 *                                                                            *
 * Author: Alexei Vladishev, Alexander Vladishev                              *
 *                                                                            *
 * Comments:                                                                  *
 *                                                                            *
 ******************************************************************************/
static void	process_values(icmpitem_t *items, int first_index, int last_index, ZBX_FPING_HOST *hosts,
		int hosts_count, zbx_timespec_t *ts, int ping_result, char *error)
{
	const char	*__function_name = "process_values";
	int		i, h;
	zbx_uint64_t	value_uint64;
	double		value_dbl;

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

	for (h = 0; h < hosts_count; h++)
	{
		const ZBX_FPING_HOST	*host = &hosts[h];

		if (NOTSUPPORTED == ping_result)
		{
			zabbix_log(LOG_LEVEL_DEBUG, "host [%s] %s", host->addr, error);
		}
		else
		{
			zabbix_log(LOG_LEVEL_DEBUG, "host [%s] cnt=%d rcv=%d"
					" min=" ZBX_FS_DBL " max=" ZBX_FS_DBL " sum=" ZBX_FS_DBL,
					host->addr, host->cnt, host->rcv, host->min, host->max, host->sum);
		}

		for (i = first_index; i < last_index; i++)
		{
			const icmpitem_t	*item = &items[i];

			if (0 != strcmp(item->addr, host->addr))
				continue;

			if (NOTSUPPORTED == ping_result)
			{
				process_value(item->itemid, NULL, NULL, ts, NOTSUPPORTED, error);
				continue;
			}

			if (0 == host->cnt)
			{
				process_value(item->itemid, NULL, NULL, ts, NOTSUPPORTED,
						"Cannot send ICMP ping packets to this host.");
				continue;
			}

			switch (item->icmpping)
			{
				case ICMPPING:
					value_uint64 = (0 != host->rcv ? 1 : 0);
					process_value(item->itemid, &value_uint64, NULL, ts, SUCCEED, NULL);
					break;
				case ICMPPINGSEC:
					switch (item->type)
					{
						case ICMPPINGSEC_MIN:
							value_dbl = host->min;
							break;
						case ICMPPINGSEC_MAX:
							value_dbl = host->max;
							break;
						case ICMPPINGSEC_AVG:
							value_dbl = (0 != host->rcv ? host->sum / host->rcv : 0);
							break;
					}
					process_value(item->itemid, NULL, &value_dbl, ts, SUCCEED, NULL);
					break;
				case ICMPPINGLOSS:
					value_dbl = (100 * (host->cnt - host->rcv)) / (double)host->cnt;
					process_value(item->itemid, NULL, &value_dbl, ts, SUCCEED, NULL);
					break;
			}
		}
	}

	dc_flush_history();

	zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name);
}
Пример #14
0
static void	process_active_checks(char *server, unsigned short port)
{
	const char	*__function_name = "process_active_checks";
	register int	i, s_count, p_count;
	char		**pvalue;
	int		now, send_err = SUCCEED, ret;
	char		*value = NULL, *item_value = NULL;
	zbx_uint64_t	lastlogsize;
	int		mtime;
	char		params[MAX_STRING_LEN], filename[MAX_STRING_LEN];
	char		pattern[MAX_STRING_LEN], output_template[MAX_STRING_LEN];
	/* checks `log', `eventlog', `logrt' may contain parameter, which overrides CONFIG_MAX_LINES_PER_SECOND */
	char		maxlines_persec_str[16];
	int		maxlines_persec;
#ifdef _WINDOWS
	unsigned long	timestamp, logeventid;
	unsigned short	severity;
	char		key_severity[MAX_STRING_LEN], str_severity[32] /* for `regex_match_ex' */;
	char		key_source[MAX_STRING_LEN], *provider = NULL, *source = NULL;
	char		key_logeventid[MAX_STRING_LEN], str_logeventid[8] /* for `regex_match_ex' */;
	OSVERSIONINFO	versionInfo;
	zbx_uint64_t	keywords;
	EVT_HANDLE	eventlog6_render_context = NULL;
	EVT_HANDLE	eventlog6_query = NULL;
	zbx_uint64_t	eventlog6_firstid = 0;
	zbx_uint64_t	eventlog6_lastid = 0;
#endif
	char		encoding[32];
	char		tmp[16];

	AGENT_RESULT	result;

	zabbix_log(LOG_LEVEL_DEBUG, "In %s('%s',%hu)", __function_name, server, port);

	init_result(&result);

	now = (int)time(NULL);

	for (i = 0; NULL != active_metrics[i].key && SUCCEED == send_err; i++)
	{
		if (active_metrics[i].nextcheck > now)
			continue;

		if (ITEM_STATE_NORMAL != active_metrics[i].state)
			continue;

		/* special processing for log files without rotation */
		if (0 == strncmp(active_metrics[i].key, "log[", 4))
		{
			ret = FAIL;

			do
			{
				/* simple try realization */
				if (ZBX_COMMAND_WITH_PARAMS != parse_command(active_metrics[i].key, NULL, 0,
						params, sizeof(params)))
				{
					break;
				}

				if (6 < num_param(params))
					break;

				if (0 != get_param(params, 1, filename, sizeof(filename)))
					break;

				if (0 != get_param(params, 2, pattern, sizeof(pattern)))
					*pattern = '\0';

				if (0 != get_param(params, 3, encoding, sizeof(encoding)))
					*encoding = '\0';

				zbx_strupper(encoding);

				if (0 != get_param(params, 4, maxlines_persec_str, sizeof(maxlines_persec_str)) ||
						'\0' == *maxlines_persec_str)
					maxlines_persec = CONFIG_MAX_LINES_PER_SECOND;
				else if (MIN_VALUE_LINES > (maxlines_persec = atoi(maxlines_persec_str)) ||
						MAX_VALUE_LINES < maxlines_persec)
					break;

				if (0 != get_param(params, 5, tmp, sizeof(tmp)))
					*tmp = '\0';

				if ('\0' == *tmp || 0 == strcmp(tmp, "all"))
					active_metrics[i].skip_old_data = 0;
				else if (0 != strcmp(tmp, "skip"))
					break;

				if (0 != get_param(params, 6, output_template, sizeof(output_template)))
					*output_template = '\0';

				s_count = 0;
				p_count = 0;
				lastlogsize = active_metrics[i].lastlogsize;

				while (SUCCEED == (ret = process_log(filename, &lastlogsize, &value, encoding,
						active_metrics[i].skip_old_data)))
				{
					active_metrics[i].skip_old_data = 0;

					/* End of file. The file could become empty, must save `lastlogsize'. */
					if (NULL == value)
					{
						active_metrics[i].lastlogsize = lastlogsize;
						break;
					}

					if (SUCCEED == regexp_sub_ex(&regexps, value, pattern, ZBX_CASE_SENSITIVE,
							output_template, &item_value))
					{
						send_err = process_value(server, port, CONFIG_HOSTNAME,
								active_metrics[i].key_orig, item_value, &lastlogsize,
								NULL, NULL, NULL, NULL,	NULL, 1);

						zbx_free(item_value);

						s_count++;
					}
					p_count++;

					zbx_free(value);

					if (SUCCEED == send_err)
						active_metrics[i].lastlogsize = lastlogsize;
					else
					{
						/* buffer is full, stop processing active checks */
						/* till the buffer is cleared */
						lastlogsize = active_metrics[i].lastlogsize;
						goto ret;
					}

					/* do not flood Zabbix server if file grows too fast */
					if (s_count >= (maxlines_persec * active_metrics[i].refresh))
						break;

					/* do not flood local system if file grows too fast */
					if (p_count >= (4 * maxlines_persec * active_metrics[i].refresh))
						break;
				} /* while processing a log */

			}
			while (0); /* simple try realization */

			if (FAIL == ret)
			{
				active_metrics[i].state = ITEM_STATE_NOTSUPPORTED;
				zabbix_log(LOG_LEVEL_WARNING, "active check \"%s\" is not supported",
						active_metrics[i].key);

				process_value(server, port, CONFIG_HOSTNAME, active_metrics[i].key_orig, NULL,
						&active_metrics[i].lastlogsize, NULL, NULL, NULL, NULL, NULL, 0);
			}
		}
		/* special processing for log files with rotation */
		else if (0 == strncmp(active_metrics[i].key, "logrt[", 6))
		{
			ret = FAIL;

			do
			{
				/* simple try realization */
				if (ZBX_COMMAND_WITH_PARAMS != parse_command(active_metrics[i].key, NULL, 0,
						params, sizeof(params)))
				{
					break;
				}

				if (6 < num_param(params))
					break;

				if (0 != get_param(params, 1, filename, sizeof(filename)))
					break;

				if (0 != get_param(params, 2, pattern, sizeof(pattern)))
					*pattern = '\0';

				if (0 != get_param(params, 3, encoding, sizeof(encoding)))
					*encoding = '\0';

				zbx_strupper(encoding);

				if (0 != get_param(params, 4, maxlines_persec_str, sizeof(maxlines_persec_str)) ||
						'\0' == *maxlines_persec_str)
					maxlines_persec = CONFIG_MAX_LINES_PER_SECOND;
				else if (MIN_VALUE_LINES > (maxlines_persec = atoi(maxlines_persec_str)) ||
						MAX_VALUE_LINES < maxlines_persec)
					break;

				if (0 != get_param(params, 5, tmp, sizeof(tmp)))
					*tmp = '\0';

				if ('\0' == *tmp || 0 == strcmp(tmp, "all"))
					active_metrics[i].skip_old_data = 0;
				else if (0 != strcmp(tmp, "skip"))
					break;

				if (0 != get_param(params, 6, output_template, sizeof(output_template)))
					*output_template = '\0';

				s_count = 0;
				p_count = 0;
				lastlogsize = active_metrics[i].lastlogsize;
				mtime = active_metrics[i].mtime;

				while (SUCCEED == (ret = process_logrt(filename, &lastlogsize, &mtime, &value,
						encoding, active_metrics[i].skip_old_data)))
				{
					active_metrics[i].skip_old_data = 0;

					/* End of file. The file could become empty,*/
					/* must save `lastlogsize' and `mtime'. */
					if (NULL == value)
					{
						active_metrics[i].lastlogsize = lastlogsize;
						active_metrics[i].mtime	= mtime;
						break;
					}

					if (SUCCEED == regexp_sub_ex(&regexps, value, pattern, ZBX_CASE_SENSITIVE,
							output_template, &item_value))
					{
						send_err = process_value(server, port, CONFIG_HOSTNAME,
								active_metrics[i].key_orig, item_value, &lastlogsize,
								&mtime, NULL, NULL, NULL, NULL, 1);

						zbx_free(item_value);

						s_count++;
					}
					p_count++;

					zbx_free(value);

					if (SUCCEED == send_err)
					{
						active_metrics[i].lastlogsize = lastlogsize;
						active_metrics[i].mtime = mtime;
					}
					else
					{
						/* buffer is full, stop processing active checks */
						/* till the buffer is cleared */
						lastlogsize = active_metrics[i].lastlogsize;
						mtime = active_metrics[i].mtime;
						goto ret;
					}

					/* do not flood Zabbix server if file grows too fast */
					if (s_count >= (maxlines_persec * active_metrics[i].refresh))
						break;

					/* do not flood local system if file grows too fast */
					if (p_count >= (4 * maxlines_persec * active_metrics[i].refresh))
						break;
				} /* while processing a log */
			}
			while (0); /* simple try realization */

			if (FAIL == ret)
			{
				active_metrics[i].state = ITEM_STATE_NOTSUPPORTED;
				zabbix_log(LOG_LEVEL_WARNING, "active check \"%s\" is not supported",
						active_metrics[i].key);

				process_value(server, port, CONFIG_HOSTNAME, active_metrics[i].key_orig, NULL,
						&active_metrics[i].lastlogsize, &active_metrics[i].mtime,
						NULL, NULL, NULL, NULL, 0);
			}
		}
		/* special processing for eventlog */
		else if (0 == strncmp(active_metrics[i].key, "eventlog[", 9))
		{
			ret = FAIL;
#ifdef _WINDOWS
			do
			{
				/* simple try realization */
				if (ZBX_COMMAND_WITH_PARAMS != parse_command(active_metrics[i].key, NULL, 0,
						params, sizeof(params)))
				{
					break;
				}

				if (7 < num_param(params))
					break;

				if (0 != get_param(params, 1, filename, sizeof(filename)))
					break;

				if (0 != get_param(params, 2, pattern, sizeof(pattern)))
					*pattern = '\0';

				if (0 != get_param(params, 3, key_severity, sizeof(key_severity)))
					*key_severity = '\0';

				if (0 != get_param(params, 4, key_source, sizeof(key_source)))
					*key_source = '\0';

				if (0 != get_param(params, 5, key_logeventid, sizeof(key_logeventid)))
					*key_logeventid = '\0';

				if (0 != get_param(params, 6, maxlines_persec_str, sizeof(maxlines_persec_str)) ||
						'\0' == *maxlines_persec_str)
					maxlines_persec = CONFIG_MAX_LINES_PER_SECOND;
				else if (MIN_VALUE_LINES > (maxlines_persec = atoi(maxlines_persec_str)) ||
						MAX_VALUE_LINES < maxlines_persec)
					break;

				if (0 != get_param(params, 7, tmp, sizeof(tmp)))
					*tmp = '\0';

				if ('\0' == *tmp || 0 == strcmp(tmp, "all"))
					active_metrics[i].skip_old_data = 0;
				else if (0 != strcmp(tmp, "skip"))
					break;

				s_count = 0;
				p_count = 0;
				lastlogsize = active_metrics[i].lastlogsize;

				versionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
				GetVersionEx(&versionInfo);

				if (versionInfo.dwMajorVersion >= 6)	/* Windows Vista, 7 or Server 2008 */
				{
					__try
					{
						if (SUCCEED != initialize_eventlog6(filename, &lastlogsize,
								&eventlog6_firstid, &eventlog6_lastid,
								&eventlog6_render_context, &eventlog6_query))
						{
							finalize_eventlog6(&eventlog6_render_context, &eventlog6_query);
							break;
						}

						while (SUCCEED == (ret = process_eventlog6(filename, &lastlogsize,
								&timestamp, &provider, &source, &severity, &value,
								&logeventid, &eventlog6_firstid, &eventlog6_lastid,
								&eventlog6_render_context, &eventlog6_query,
								&keywords, active_metrics[i].skip_old_data)))
						{
							active_metrics[i].skip_old_data = 0;

							/* End of file. */
							/* The eventlog could become empty, must save `lastlogsize'. */
							if (NULL == value)
							{
								active_metrics[i].lastlogsize = lastlogsize;
								break;
							}

							switch (severity)
							{
								case WINEVENT_LEVEL_LOG_ALWAYS:
								case WINEVENT_LEVEL_INFO:
									if (0 != (keywords &
											WINEVENT_KEYWORD_AUDIT_FAILURE))
									{
										severity = ITEM_LOGTYPE_FAILURE_AUDIT;
										strscpy(str_severity, AUDIT_FAILURE);
										break;
									}
									else if (0 != (keywords &
											WINEVENT_KEYWORD_AUDIT_SUCCESS))
									{
										severity = ITEM_LOGTYPE_SUCCESS_AUDIT;
										strscpy(str_severity, AUDIT_SUCCESS);
										break;
									}
									else
										severity = ITEM_LOGTYPE_INFORMATION;
										strscpy(str_severity, INFORMATION_TYPE);
										break;
								case WINEVENT_LEVEL_WARNING:
									severity = ITEM_LOGTYPE_WARNING;
									strscpy(str_severity, WARNING_TYPE);
									break;
								case WINEVENT_LEVEL_ERROR:
									severity = ITEM_LOGTYPE_ERROR;
									strscpy(str_severity, ERROR_TYPE);
									break;
								case WINEVENT_LEVEL_CRITICAL:
									severity = ITEM_LOGTYPE_CRITICAL;
									strscpy(str_severity, CRITICAL_TYPE);
									break;
								case WINEVENT_LEVEL_VERBOSE:
									severity = ITEM_LOGTYPE_VERBOSE;
									strscpy(str_severity, VERBOSE_TYPE);
									break;
							}

							zbx_snprintf(str_logeventid, sizeof(str_logeventid), "%lu",
									logeventid);

							if (SUCCEED == regexp_match_ex(&regexps, value, pattern, ZBX_CASE_SENSITIVE) &&
								SUCCEED == regexp_match_ex(&regexps, str_severity, key_severity,
										ZBX_IGNORE_CASE) &&
								SUCCEED == regexp_match_ex(&regexps, provider, key_source,
										ZBX_IGNORE_CASE) &&
								SUCCEED == regexp_match_ex(&regexps, str_logeventid,
										key_logeventid, ZBX_CASE_SENSITIVE))
							{
								send_err = process_value(server, port, CONFIG_HOSTNAME,
										active_metrics[i].key_orig, value, &lastlogsize,
										NULL, &timestamp, provider, &severity, &logeventid, 1);
								s_count++;
							}
							p_count++;

							zbx_free(source);
							zbx_free(provider);
							zbx_free(value);

							if (SUCCEED == send_err)
								active_metrics[i].lastlogsize = lastlogsize;
							else
							{
								/* buffer is full, stop processing active checks*/
								/* till the buffer is cleared */
								lastlogsize = active_metrics[i].lastlogsize;
								goto ret;
							}

							/* do not flood Zabbix server if file grows too fast */
							if (s_count >= (maxlines_persec * active_metrics[i].refresh))
								break;

							/* do not flood local system if file grows too fast */
							if (p_count >= (4 * maxlines_persec * active_metrics[i].refresh))
								break;

						} /* while processing an eventlog */

						finalize_eventlog6(&eventlog6_render_context, &eventlog6_query);
					}
					__except (DelayLoadDllExceptionFilter(GetExceptionInformation()))
					{
						zabbix_log(LOG_LEVEL_WARNING, "failed to process eventlog");
						break;
					}
				}
				else if (versionInfo.dwMajorVersion < 6)    /* Windows versions before Vista */
				{
					while (SUCCEED == (ret = process_eventlog(filename, &lastlogsize,
							&timestamp, &source, &severity, &value, &logeventid,
							active_metrics[i].skip_old_data)))
					{
						active_metrics[i].skip_old_data = 0;

						/* End of file. */
						/* The eventlog could become empty, must save `lastlogsize'. */
						if (NULL == value)
						{
							active_metrics[i].lastlogsize = lastlogsize;
							break;
						}

						switch (severity)
						{
							case EVENTLOG_SUCCESS:
							case EVENTLOG_INFORMATION_TYPE:
								severity = ITEM_LOGTYPE_INFORMATION;
								strscpy(str_severity, INFORMATION_TYPE);
								break;
							case EVENTLOG_WARNING_TYPE:
								severity = ITEM_LOGTYPE_WARNING;
								strscpy(str_severity, WARNING_TYPE);
								break;
							case EVENTLOG_ERROR_TYPE:
								severity = ITEM_LOGTYPE_ERROR;
								strscpy(str_severity, ERROR_TYPE);
								break;
							case EVENTLOG_AUDIT_FAILURE:
								severity = ITEM_LOGTYPE_FAILURE_AUDIT;
								strscpy(str_severity, AUDIT_FAILURE);
								break;
							case EVENTLOG_AUDIT_SUCCESS:
								severity = ITEM_LOGTYPE_SUCCESS_AUDIT;
								strscpy(str_severity, AUDIT_SUCCESS);
								break;
						}

						zbx_snprintf(str_logeventid, sizeof(str_logeventid), "%lu", logeventid);

						if (SUCCEED == regexp_match_ex(&regexps, value, pattern, ZBX_CASE_SENSITIVE) &&
								SUCCEED == regexp_match_ex(&regexps, str_severity, key_severity,
										ZBX_IGNORE_CASE) &&
								SUCCEED == regexp_match_ex(&regexps, source, key_source,
										ZBX_IGNORE_CASE) &&
								SUCCEED == regexp_match_ex(&regexps, str_logeventid,
										key_logeventid, ZBX_CASE_SENSITIVE))
						{
							send_err = process_value(server, port, CONFIG_HOSTNAME,
									active_metrics[i].key_orig, value, &lastlogsize,
									NULL, &timestamp, source, &severity, &logeventid, 1);
							s_count++;
						}
						p_count++;

						zbx_free(source);
						zbx_free(value);

						if (SUCCEED == send_err)
							active_metrics[i].lastlogsize = lastlogsize;
						else
						{
							/* buffer is full, stop processing active checks */
							/* till the buffer is cleared */
							lastlogsize = active_metrics[i].lastlogsize;
							goto ret;
						}

						/* do not flood Zabbix server if file grows too fast */
						if (s_count >= (maxlines_persec * active_metrics[i].refresh))
							break;

						/* do not flood local system if file grows too fast */
						if (p_count >= (4 * maxlines_persec * active_metrics[i].refresh))
							break;
					} /* while processing an eventlog */
				}
				break;
			}
			while (0); /* simple try realization */
#endif	/* _WINDOWS */

			if (FAIL == ret)
			{
				active_metrics[i].state = ITEM_STATE_NOTSUPPORTED;
				zabbix_log(LOG_LEVEL_WARNING, "active check \"%s\" is not supported",
						active_metrics[i].key);

				process_value(server, port, CONFIG_HOSTNAME, active_metrics[i].key_orig, NULL,
						&active_metrics[i].lastlogsize, NULL, NULL, NULL, NULL, NULL, 0);
			}
		}
Пример #15
0
int main(int argc, const char *argv[])
{
	uint8_t ret;
	uint8_t init = 1;
	cfg_t *cfg;

       	int32_t adc_channel = -1;
	uint32_t val_cur[MCP32XX_MAX_CHANNEL], val_old[MCP32XX_MAX_CHANNEL];
	int32_t diff;

	struct mcp32xx_dev mcp_dev;
	struct volume_handle v_handle = {0};
	struct mpd_handle m_handle = {0};
	struct lcd_handle l_handle = {0};

	useconds_t sleep_usec;
	uint8_t song_update_count_max;
	uint8_t song_update_count = 0;

	cfg_opt_t opts[] = {
		CFG_INT("UpdateInterval", 300000, CFGF_NONE),
		CFG_INT("SongUpdateInterval", 2000000, CFGF_NONE),
		CFG_INT("ChannelUsed", 2, CFGF_NONE),
		CFG_INT("VolumeChannel", 0, CFGF_NONE),
		CFG_INT("TunerChannel", 1, CFGF_NONE),
		CFG_INT("MaxLineChar", 16, CFGF_NONE),
		CFG_INT("MaxLineBuf", 80, CFGF_NONE),
		CFG_STR("HostName", "localhost", CFGF_NONE),
		CFG_INT("Port", 6600, CFGF_NONE),
		CFG_INT("MaxTunerPos", 12, CFGF_NONE),
		CFG_INT("MaxVolSteps", 50, CFGF_NONE),
		CFG_STR("RadioPlaylistName", "stations", CFGF_NONE),
		CFG_INT("LCD-Pin_RS", 25, CFGF_NONE),
		CFG_INT("LCD-Pin_E", 24, CFGF_NONE),
		CFG_INT("LCD-Pin_DB4", 23, CFGF_NONE),
		CFG_INT("LCD-Pin_DB5", 17, CFGF_NONE),
		CFG_INT("LCD-Pin_DB6", 27, CFGF_NONE),
		CFG_INT("LCD-Pin_DB7", 22, CFGF_NONE),
		CFG_STR("FillPatternFirstLine", " ++ ", CFGF_NONE),
		CFG_STR("FillPatternSecondLine", " ** ", CFGF_NONE),
		CFG_INT("MaxLineLength", 16, CFGF_NONE),
		CFG_INT("MaxLineBufferLength", 80, CFGF_NONE),
        	CFG_END()
	};

	cfg = cfg_init(opts, CFGF_NONE);

	ret = cfg_parse(cfg, "/etc/radioberry.conf");
	if(ret == CFG_FILE_ERROR) {
		perror("/etc/radioberry.conf");
		printf("WARN: could not read /etc/radioberry.conf,"
				" process with default values\n");
	} else if (ret == CFG_PARSE_ERROR) {
		printf("configuration parse error\n");
		goto out;
	}

	/* get configuration values */
	channel_used = (uint8_t)cfg_getint(cfg, "ChannelUsed");
	volume_chan = (uint8_t)cfg_getint(cfg, "VolumeChannel");
	tuner_chan = (uint8_t)cfg_getint(cfg, "TunerChannel");

	sleep_usec = cfg_getint(cfg, "UpdateInterval") / channel_used;
	printf("sleep_usec %d\n", sleep_usec);
	song_update_count_max = cfg_getint(cfg, "SongUpdateInterval")
		/ sleep_usec;
	/* pass over pointer to handles of mpd, lcd and volume */
	m_handle.lh = &l_handle;
	v_handle.mh = &m_handle;

	m_handle.cfg = cfg;
	l_handle.cfg = cfg;

	signal(SIGINT, sigintterm_handler);
	signal(SIGTERM, sigintterm_handler);

	ret = lcd_init(&l_handle);
	if (ret) {
		printf("failed to initialize lcd, lcd control disabled \n");
		lcd_control_enabled = 0;
	}

	if (lcd_control_enabled) {
		lcd_print_string("Radioberry");
		lcd_move_cursor_down();
		lcd_print_string("=== Welcome ===");
	}

	ret = mcp32xx_init(&mcp_dev);
	if (ret) {
		printf("failed to initialize spi device, analog control"
				" devices disabled\n");
		tuner_control_enabled = 0;
		vol_control_enabled = 0;
	}

	ret = init_mpd_handle(&m_handle);
	if (ret) {
		printf("could not initialize mpd client,"
				" tuner control disabled\n");
		tuner_control_enabled = 0;
	}

	/* disable tuner control if we cannot get any station at all. If one
	 * station fails, let's process and wait for tuner changes */
	ret = load_stations_playlist(&m_handle);
	if (ret == 1) {
		printf("could not load radio stations list,"
				" tuner control disabled\n");
		tuner_control_enabled = 0;
	}

	ret = init_vol_control(&v_handle);
	if (ret) {
		printf("could not initialize volume control,"
				" volumen control disabled\n");
		vol_control_enabled = 0;
	}

	running = 1;

	while ( running ) {
		usleep(sleep_usec);

		if (adc_channel + 1 == channel_used) {
			adc_channel = 0;
			mpd_status_update(m_handle.mpd_obj);
			/* detect if initial loop is done. Start update lcd
			 * after initial loop */
			if (init)
				init = 0;
			else {
				if (lcd_control_enabled)
					lcd_update_screen(&l_handle);
			}
		} else
			adc_channel++;

		if (song_update_count == song_update_count_max) {
			update_song_info(&m_handle);
			song_update_count = 0;
		} else
			song_update_count++;

		/* loop over all channels in singel ended mode
		 * and reset counter in the last loop. */
		val_cur[adc_channel] = mcp32xx_get_val(&mcp_dev, adc_channel);

		/* fill the old value buffer and intialize the player with
		 * current settings*/
		if (init) {
			val_old[adc_channel] = val_cur[adc_channel];

			ret = process_value(&v_handle, &m_handle,
					val_cur[adc_channel], adc_channel);

			/* skip comparing old/new values while intializing */
			if (ret) {
				printf("unrecoverable error, quit now\n");
				break;
			}
			else
				continue;
		}

		diff = val_old[adc_channel] - val_cur[adc_channel];

#ifdef DEBUG
		printf("adc_channel: %u, old %u, new %u, diff %d\n",
				adc_channel, val_cur[adc_channel],
			       	val_old[adc_channel], diff);
#endif

		if (abs(diff) < TOLERANT_THRESHOLD)
			continue;
#ifdef DEBUG
		if (diff > 0)
			printf("Poti %u was turned left, current val: %d\n",
				adc_channel + 1, val_cur[adc_channel]);
		else
			printf("Poti %u was turned right, current Pos: %d\n",
				adc_channel + 1, val_cur[adc_channel]);
#endif
		process_value(&v_handle, &m_handle, val_cur[adc_channel],
				adc_channel);
		val_old[adc_channel] = val_cur[adc_channel];
	}
out:
	lcd_clear_screen();
	lcd_close(&l_handle);
	mcp32xx_close(&mcp_dev);
	close_vol_ctl(&v_handle);
	close_mpd_handle(&m_handle);

	exit(ret);
}