1 /******************************************************************************
3 * Copyright (C) 2012-2013 Icinga Development Team (http://www.icinga.org/) *
5 * This program is free software; you can redistribute it and/or *
6 * modify it under the terms of the GNU General Public License *
7 * as published by the Free Software Foundation; either version 2 *
8 * of the License, or (at your option) any later version. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the Free Software Foundation *
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
18 ******************************************************************************/
20 #include "perfdata/graphitewriter.h"
21 #include "icinga/service.h"
22 #include "icinga/macroprocessor.h"
23 #include "icinga/icingaapplication.h"
24 #include "icinga/compatutility.h"
25 #include "base/tcpsocket.h"
26 #include "base/dynamictype.h"
27 #include "base/objectlock.h"
28 #include "base/logger_fwd.h"
29 #include "base/convert.h"
30 #include "base/utility.h"
31 #include "base/application.h"
32 #include "base/stream.h"
33 #include "base/networkstream.h"
34 #include "base/bufferedstream.h"
35 #include <boost/algorithm/string/classification.hpp>
36 #include <boost/smart_ptr/make_shared.hpp>
37 #include <boost/foreach.hpp>
38 #include <boost/algorithm/string/split.hpp>
39 #include <boost/algorithm/string/replace.hpp>
40 #include <boost/exception/diagnostic_information.hpp>
42 using namespace icinga;
44 REGISTER_TYPE(GraphiteWriter);
46 void GraphiteWriter::Start(void)
48 DynamicObject::Start();
50 m_ReconnectTimer = boost::make_shared<Timer>();
51 m_ReconnectTimer->SetInterval(10);
52 m_ReconnectTimer->OnTimerExpired.connect(boost::bind(&GraphiteWriter::ReconnectTimerHandler, this));
53 m_ReconnectTimer->Start();
54 m_ReconnectTimer->Reschedule(0);
56 Service::OnNewCheckResult.connect(boost::bind(&GraphiteWriter::CheckResultHandler, this, _1, _2));
59 String GraphiteWriter::GetHost(void) const
67 String GraphiteWriter::GetPort(void) const
75 void GraphiteWriter::ReconnectTimerHandler(void)
79 m_Stream->Write("\n", 1);
80 Log(LogWarning, "perfdata", "GraphiteWriter already connected on socket on host '" + GetHost() + "' port '" + GetPort() + "'.");
83 } catch (const std::exception& ex) {
84 Log(LogWarning, "perfdata", "GraphiteWriter socket on host '" + GetHost() + "' port '" + GetPort() + "' gone. Attempting to reconnect.");
87 TcpSocket::Ptr socket = boost::make_shared<TcpSocket>();
89 Log(LogInformation, "perfdata", "GraphiteWriter: Reconnect to tcp socket on host '" + GetHost() + "' port '" + GetPort() + "'.");
90 socket->Connect(GetHost(), GetPort());
92 NetworkStream::Ptr net_stream = boost::make_shared<NetworkStream>(socket);
93 m_Stream = boost::make_shared<BufferedStream>(net_stream);
96 void GraphiteWriter::CheckResultHandler(const Service::Ptr& service, const Dictionary::Ptr& cr)
98 if (!IcingaApplication::GetInstance()->GetEnablePerfdata() || !service->GetEnablePerfdata())
101 Host::Ptr host = service->GetHost();
106 /* service metrics */
107 std::vector<String> metrics;
112 AddServiceMetric(metrics, service, "current_attempt", service->GetCurrentCheckAttempt());
113 AddServiceMetric(metrics, service, "max_check_attempts", service->GetMaxCheckAttempts());
114 AddServiceMetric(metrics, service, "state_type", service->GetStateType());
115 AddServiceMetric(metrics, service, "state", service->GetState());
116 AddServiceMetric(metrics, service, "latency", Service::CalculateLatency(cr));
117 AddServiceMetric(metrics, service, "execution_time", Service::CalculateExecutionTime(cr));
119 /* performance data metrics */
120 String perfdata = CompatUtility::GetCheckResultPerfdata(cr);
122 if (!perfdata.IsEmpty()) {
123 Log(LogDebug, "perfdata", "GraphiteWriter: Processing perfdata: '" + perfdata + "'.");
126 * 'foo bar'=0;;; baz=0.0;;;
127 * 'label'=value[UOM];[warn];[crit];[min];[max]
129 std::vector<String> tokens;
130 boost::algorithm::split(tokens, perfdata, boost::is_any_of(" "));
132 /* TODO deal with 'foo bar'=0;;; 'baz'=1.0;;; */
133 BOOST_FOREACH(const String& token, tokens) {
134 std::vector<String> key_val;
135 boost::algorithm::split(key_val, token, boost::is_any_of("="));
137 if (key_val.size() == 0) {
138 Log(LogWarning, "perfdata", "GraphiteWriter: Invalid performance data: '" + token + "'.");
142 String metricName = key_val[0];
144 if (key_val.size() == 1) {
145 Log(LogWarning, "perfdata", "GraphiteWriter: Invalid performance data: '" + token + "'.");
149 std::vector<String> perfdata_values;
150 boost::algorithm::split(perfdata_values, key_val[1], boost::is_any_of(";"));
152 if (perfdata_values.size() == 0) {
153 Log(LogWarning, "perfdata", "GraphiteWriter: Invalid performance data: '" + token + "'.");
157 /* TODO remove UOM from value */
158 String metricValue = perfdata_values[0];
160 /* //TODO: Figure out how graphite handles warn/crit/min/max
161 String metricValueWarn, metricValueCrit, metricValueMin, metricValueMax;
163 if (perfdata_values.size() > 1)
164 metricValueWarn = perfdata_values[1];
165 if (perfdata_values.size() > 2)
166 metricValueCrit = perfdata_values[2];
167 if (perfdata_values.size() > 3)
168 metricValueMin = perfdata_values[3];
169 if (perfdata_values.size() > 4)
170 metricValueMax = perfdata_values[4];
173 AddServiceMetric(metrics, service, metricName, metricValue);
177 SendMetrics(metrics);
180 void GraphiteWriter::AddServiceMetric(std::vector<String>& metrics, const Service::Ptr& service, const String& name, const Value& value)
182 /* TODO: sanitize host and service names */
183 String hostName = service->GetHost()->GetName();
184 String serviceName = service->GetShortName();
185 String metricPrefix = hostName + "." + serviceName;
187 boost::replace_all(metricPrefix, " ", "_");
188 boost::replace_all(metricPrefix, "-", "_");
189 boost::replace_all(metricPrefix, ".", "_");
190 boost::replace_all(metricPrefix, "\\", "_");
191 boost::replace_all(metricPrefix, "/", "_");
193 String graphitePrefix = "icinga";
195 String metric = graphitePrefix + "." + metricPrefix + "." + name + " " + Convert::ToString(value) + " " + Convert::ToString(static_cast<long>(Utility::GetTime())) + "\n";
196 Log(LogDebug, "perfdata", "GraphiteWriter: Add to metric list:'" + metric + "'.");
197 metrics.push_back(metric);
200 void GraphiteWriter::SendMetrics(const std::vector<String>& metrics)
202 BOOST_FOREACH(const String& metric, metrics) {
203 if (metric.IsEmpty())
206 Log(LogDebug, "perfdata", "GraphiteWriter: Sending metric '" + metric + "'.");
208 ObjectLock olock(this);
214 m_Stream->Write(metric.CStr(), metric.GetLength());
215 } catch (const std::exception& ex) {
216 std::ostringstream msgbuf;
217 msgbuf << "Exception thrown while writing to the Graphite socket: " << std::endl
218 << boost::diagnostic_information(ex);
220 Log(LogCritical, "base", msgbuf.str());
227 void GraphiteWriter::InternalSerialize(const Dictionary::Ptr& bag, int attributeTypes) const
229 DynamicObject::InternalSerialize(bag, attributeTypes);
231 if (attributeTypes & Attribute_Config) {
232 bag->Set("host", m_Host);
233 bag->Set("port", m_Port);
237 void GraphiteWriter::InternalDeserialize(const Dictionary::Ptr& bag, int attributeTypes)
239 DynamicObject::InternalDeserialize(bag, attributeTypes);
241 if (attributeTypes & Attribute_Config) {
242 m_Host = bag->Get("host");
243 m_Port = bag->Get("port");