Use PluginUtility::{Parse,Format}Perfdata for check results.

Refs #2710
This commit is contained in:
Gunnar Beutner 2013-11-07 14:38:37 +01:00
parent 2af388e4ef
commit 5aba175e18
8 changed files with 53 additions and 146 deletions

View File

@ -22,6 +22,7 @@
#include "icinga/macroprocessor.h" #include "icinga/macroprocessor.h"
#include "icinga/icingaapplication.h" #include "icinga/icingaapplication.h"
#include "icinga/compatutility.h" #include "icinga/compatutility.h"
#include "icinga/perfdatavalue.h"
#include "base/tcpsocket.h" #include "base/tcpsocket.h"
#include "base/dynamictype.h" #include "base/dynamictype.h"
#include "base/objectlock.h" #include "base/objectlock.h"
@ -82,122 +83,36 @@ void GraphiteWriter::CheckResultHandler(const Service::Ptr& service, const Dicti
if (!IcingaApplication::GetInstance()->GetEnablePerfdata() || !service->GetEnablePerfdata()) if (!IcingaApplication::GetInstance()->GetEnablePerfdata() || !service->GetEnablePerfdata())
return; return;
Host::Ptr host = service->GetHost(); /* basic metrics */
SendMetric(service, "current_attempt", service->GetCheckAttempt());
SendMetric(service, "max_check_attempts", service->GetMaxCheckAttempts());
SendMetric(service, "state_type", service->GetStateType());
SendMetric(service, "state", service->GetState());
SendMetric(service, "latency", Service::CalculateLatency(cr));
SendMetric(service, "execution_time", Service::CalculateExecutionTime(cr));
if (!host) Value pdv = cr->Get("performance_data");
if (!pdv.IsObjectType<Dictionary>())
return; return;
/* service metrics */ Dictionary::Ptr perfdata = pdv;
std::vector<String> metrics;
String metricName;
Value metricValue;
/* basic metrics */ String key;
AddServiceMetric(metrics, service, "current_attempt", service->GetCheckAttempt()); Value value;
AddServiceMetric(metrics, service, "max_check_attempts", service->GetMaxCheckAttempts()); BOOST_FOREACH(boost::tie(key, value), perfdata) {
AddServiceMetric(metrics, service, "state_type", service->GetStateType()); double valueNum;
AddServiceMetric(metrics, service, "state", service->GetState());
AddServiceMetric(metrics, service, "latency", Service::CalculateLatency(cr));
AddServiceMetric(metrics, service, "execution_time", Service::CalculateExecutionTime(cr));
/* performance data metrics */ if (!value.IsObjectType<PerfdataValue>())
String perfdata = CompatUtility::GetCheckResultPerfdata(cr); valueNum = value;
else
valueNum = static_cast<PerfdataValue::Ptr>(value)->GetValue();
if (!perfdata.IsEmpty()) { SendMetric(service, key, valueNum);
perfdata.Trim();
Log(LogDebug, "perfdata", "GraphiteWriter: Processing perfdata: '" + perfdata + "'.");
/*
* 'foo bar'=0;;; baz=0.0;;;
* 'label'=value[UOM];[warn];[crit];[min];[max]
*/
std::vector<String> tokens;
boost::algorithm::split(tokens, perfdata, boost::is_any_of(" "));
/* TODO deal with white spaces in single quoted labels: 'foo bar'=0;;; 'baz'=1.0;;;
* 1. find first ', find second ' -> if no '=' in between, this is a label
* 2. two single quotes define an escaped single quite
* 3. warn/crit/min/max may be null and semicolon delimiter omitted
* https://www.nagios-plugins.org/doc/guidelines.html#AEN200
*/
BOOST_FOREACH(const String& token, tokens) {
String metricKeyVal = token;
metricKeyVal.Trim();
std::vector<String> key_val;
boost::algorithm::split(key_val, metricKeyVal, boost::is_any_of("="));
if (key_val.size() == 0) {
Log(LogWarning, "perfdata", "GraphiteWriter: Invalid performance data. No assignment operator found in :'" + metricKeyVal + "'.");
return;
}
String metricName = key_val[0];
metricName.Trim();
if (key_val.size() == 1) {
Log(LogWarning, "perfdata", "GraphiteWriter: Invalid performance data: '" + metricKeyVal + "' with key: '" + metricName + "'.");
return;
}
String metricValues = key_val[1];
metricValues.Trim();
std::vector<String> perfdata_values;
boost::algorithm::split(perfdata_values, metricValues, boost::is_any_of(";"));
if (perfdata_values.size() == 0) {
Log(LogWarning, "perfdata", "GraphiteWriter: Invalid performance data: '" + metricKeyVal +
"' with key: '" + metricName + "' and values: '" + metricValues + "'.");
return;
}
String metricValue = perfdata_values[0];
metricValue.Trim();
Log(LogDebug, "perfdata", "GraphiteWriter: Trimmed metric value: '" + metricValue + "'.");
/* extract raw value (digit number digit as double) and uom
* http://en.highscore.de/cpp/boost/stringhandling.html
*/
String metricValueRaw = boost::algorithm::trim_right_copy_if(metricValue, (!boost::algorithm::is_digit() && !boost::algorithm::is_any_of(".,")));
String metricValueUom = boost::algorithm::trim_left_copy_if(metricValue, (boost::algorithm::is_digit() || boost::algorithm::is_any_of(".,")));
Log(LogDebug, "perfdata", "GraphiteWriter: Raw metric value: '" + metricValueRaw + "' with UOM: '" + metricValueUom + "'.");
/* TODO: Normalize raw value based on UOM
* a. empty - assume a number
* b. 's' - seconds (us, ms)
* c. '%' - percentage
* d. 'B' - bytes (KB, MB, GB, TB)
* e. 'c' - continous counter (snmp)
*/
/* //TODO: Figure out how graphite handles warn/crit/min/max
String metricValueWarn, metricValueCrit, metricValueMin, metricValueMax;
if (perfdata_values.size() > 1)
metricValueWarn = perfdata_values[1];
if (perfdata_values.size() > 2)
metricValueCrit = perfdata_values[2];
if (perfdata_values.size() > 3)
metricValueMin = perfdata_values[3];
if (perfdata_values.size() > 4)
metricValueMax = perfdata_values[4];
*/
/* sanitize invalid metric characters */
SanitizeMetric(metricName);
AddServiceMetric(metrics, service, metricName, metricValueRaw);
}
} }
SendMetrics(metrics);
} }
void GraphiteWriter::AddServiceMetric(std::vector<String>& metrics, const Service::Ptr& service, const String& name, const Value& value) void GraphiteWriter::SendMetric(const Service::Ptr& service, const String& name, double value)
{ {
/* TODO: sanitize host and service names */ /* TODO: sanitize host and service names */
String hostName = service->GetHost()->GetName(); String hostName = service->GetHost()->GetName();
@ -211,33 +126,22 @@ void GraphiteWriter::AddServiceMetric(std::vector<String>& metrics, const Servic
String metric = graphitePrefix + "." + metricPrefix + "." + name + " " + Convert::ToString(value) + " " + Convert::ToString(static_cast<long>(Utility::GetTime())) + "\n"; String metric = graphitePrefix + "." + metricPrefix + "." + name + " " + Convert::ToString(value) + " " + Convert::ToString(static_cast<long>(Utility::GetTime())) + "\n";
Log(LogDebug, "perfdata", "GraphiteWriter: Add to metric list:'" + metric + "'."); Log(LogDebug, "perfdata", "GraphiteWriter: Add to metric list:'" + metric + "'.");
metrics.push_back(metric);
}
void GraphiteWriter::SendMetrics(const std::vector<String>& metrics) ObjectLock olock(this);
{
BOOST_FOREACH(const String& metric, metrics) {
if (metric.IsEmpty())
continue;
Log(LogDebug, "perfdata", "GraphiteWriter: Sending metric '" + metric + "'."); if (!m_Stream)
return;
ObjectLock olock(this); try {
m_Stream->Write(metric.CStr(), metric.GetLength());
} catch (const std::exception& ex) {
std::ostringstream msgbuf;
msgbuf << "Exception thrown while writing to the Graphite socket: " << std::endl
<< boost::diagnostic_information(ex);
if (!m_Stream) Log(LogCritical, "base", msgbuf.str());
return;
try { m_Stream.reset();
m_Stream->Write(metric.CStr(), metric.GetLength());
} catch (const std::exception& ex) {
std::ostringstream msgbuf;
msgbuf << "Exception thrown while writing to the Graphite socket: " << std::endl
<< boost::diagnostic_information(ex);
Log(LogCritical, "base", msgbuf.str());
m_Stream.reset();
}
} }
} }
@ -249,4 +153,3 @@ void GraphiteWriter::SanitizeMetric(String& str)
boost::replace_all(str, "\\", "_"); boost::replace_all(str, "\\", "_");
boost::replace_all(str, "/", "_"); boost::replace_all(str, "/", "_");
} }

View File

@ -50,10 +50,9 @@ private:
Timer::Ptr m_ReconnectTimer; Timer::Ptr m_ReconnectTimer;
void CheckResultHandler(const Service::Ptr& service, const Dictionary::Ptr& cr); void CheckResultHandler(const Service::Ptr& service, const Dictionary::Ptr& cr);
static void AddServiceMetric(std::vector<String>& metrics, const Service::Ptr& service, const String& name, const Value& value); void SendMetric(const Service::Ptr& service, const String& name, double value);
void SendMetrics(const std::vector<String>& metrics);
static void SanitizeMetric(String& str); static void SanitizeMetric(String& str);
void ReconnectTimerHandler(void); void ReconnectTimerHandler(void);
}; };

View File

@ -17,13 +17,14 @@
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
******************************************************************************/ ******************************************************************************/
#include "base/convert.h"
#include "icinga/compatutility.h" #include "icinga/compatutility.h"
#include "icinga/checkcommand.h" #include "icinga/checkcommand.h"
#include "icinga/eventcommand.h" #include "icinga/eventcommand.h"
#include "icinga/pluginutility.h"
#include "base/dynamictype.h" #include "base/dynamictype.h"
#include "base/objectlock.h" #include "base/objectlock.h"
#include "base/debug.h" #include "base/debug.h"
#include "base/convert.h"
#include <boost/foreach.hpp> #include <boost/foreach.hpp>
#include <boost/tuple/tuple.hpp> #include <boost/tuple/tuple.hpp>
#include <boost/algorithm/string/replace.hpp> #include <boost/algorithm/string/replace.hpp>
@ -556,12 +557,10 @@ Dictionary::Ptr CompatUtility::GetCheckResultOutput(const Dictionary::Ptr& cr)
String CompatUtility::GetCheckResultPerfdata(const Dictionary::Ptr& cr) String CompatUtility::GetCheckResultPerfdata(const Dictionary::Ptr& cr)
{ {
if (!cr) if (!cr)
return Empty; return String();
String perfdata = EscapeString(cr->Get("performance_data_raw")); Dictionary::Ptr perfdata = cr->Get("performance_data");
perfdata.Trim(); return PluginUtility::FormatPerfdata(perfdata);
return perfdata;
} }
String CompatUtility::EscapeString(const String& str) String CompatUtility::EscapeString(const String& str)

View File

@ -21,6 +21,7 @@
#include "icinga/service.h" #include "icinga/service.h"
#include "icinga/hostgroup.h" #include "icinga/hostgroup.h"
#include "icinga/icingaapplication.h" #include "icinga/icingaapplication.h"
#include "icinga/pluginutility.h"
#include "base/dynamictype.h" #include "base/dynamictype.h"
#include "base/objectlock.h" #include "base/objectlock.h"
#include "base/logger_fwd.h" #include "base/logger_fwd.h"
@ -619,7 +620,7 @@ bool Host::ResolveMacro(const String& macro, const Dictionary::Ptr&, String *res
*result = hccr->Get("output"); *result = hccr->Get("output");
return true; return true;
} else if (macro == "HOSTPERFDATA") { } else if (macro == "HOSTPERFDATA") {
*result = hccr->Get("performance_data_raw"); *result = PluginUtility::FormatPerfdata(hccr->Get("performance_data"));
return true; return true;
} else if (macro == "LASTHOSTCHECK") { } else if (macro == "LASTHOSTCHECK") {
*result = Convert::ToString((long)hccr->Get("schedule_start")); *result = Convert::ToString((long)hccr->Get("schedule_start"));

View File

@ -76,7 +76,7 @@ Dictionary::Ptr PluginUtility::ParseCheckOutput(const String& output)
} }
result->Set("output", text); result->Set("output", text);
result->Set("performance_data_raw", perfdata); result->Set("performance_data", ParsePerfdata(perfdata));
return result; return result;
} }

View File

@ -22,6 +22,7 @@
#include "icinga/checkcommand.h" #include "icinga/checkcommand.h"
#include "icinga/icingaapplication.h" #include "icinga/icingaapplication.h"
#include "icinga/macroprocessor.h" #include "icinga/macroprocessor.h"
#include "icinga/pluginutility.h"
#include "config/configitembuilder.h" #include "config/configitembuilder.h"
#include "base/dynamictype.h" #include "base/dynamictype.h"
#include "base/objectlock.h" #include "base/objectlock.h"
@ -393,7 +394,7 @@ bool Service::ResolveMacro(const String& macro, const Dictionary::Ptr& cr, Strin
*result = cr->Get("output"); *result = cr->Get("output");
return true; return true;
} else if (macro == "SERVICEPERFDATA") { } else if (macro == "SERVICEPERFDATA") {
*result = cr->Get("performance_data_raw"); *result = PluginUtility::FormatPerfdata(cr->Get("performance_data"));
return true; return true;
} else if (macro == "LASTSERVICECHECK") { } else if (macro == "LASTSERVICECHECK") {
*result = Convert::ToString((long)cr->Get("execution_end")); *result = Convert::ToString((long)cr->Get("execution_end"));

View File

@ -39,11 +39,13 @@ Dictionary::Ptr NullCheckTask::ScriptFunc(const Service::Ptr&)
String output = "Hello from "; String output = "Hello from ";
output += name; output += name;
String perfdata = "time=" + Convert::ToString(static_cast<double>(Utility::GetTime()));
Dictionary::Ptr perfdata = make_shared<Dictionary>();
perfdata->Set("time", Utility::GetTime());
Dictionary::Ptr cr = make_shared<Dictionary>(); Dictionary::Ptr cr = make_shared<Dictionary>();
cr->Set("output", output); cr->Set("output", output);
cr->Set("performance_data_raw", perfdata); cr->Set("performance_data", perfdata);
cr->Set("state", StateOK); cr->Set("state", StateOK);
return cr; return cr;

View File

@ -39,11 +39,13 @@ Dictionary::Ptr RandomCheckTask::ScriptFunc(const Service::Ptr&)
String output = "Hello from "; String output = "Hello from ";
output += name; output += name;
String perfdata = "time=" + Convert::ToString(static_cast<double>(Utility::GetTime()));
Dictionary::Ptr perfdata = make_shared<Dictionary>();
perfdata->Set("time", Utility::GetTime());
Dictionary::Ptr cr = make_shared<Dictionary>(); Dictionary::Ptr cr = make_shared<Dictionary>();
cr->Set("output", output); cr->Set("output", output);
cr->Set("performance_data_raw", perfdata); cr->Set("performance_data", perfdata);
cr->Set("state", static_cast<ServiceState>(Utility::Random() % 4)); cr->Set("state", static_cast<ServiceState>(Utility::Random() % 4));
return cr; return cr;