]> granicus.if.org Git - icinga2/blob - components/perfdata/graphitewriter.cpp
Add GraphiteWriter.
[icinga2] / components / perfdata / graphitewriter.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2013 Icinga Development Team (http://www.icinga.org/)   *
4  *                                                                            *
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.                     *
9  *                                                                            *
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.                               *
14  *                                                                            *
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  ******************************************************************************/
19
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
40 using namespace icinga;
41
42 REGISTER_TYPE(GraphiteWriter);
43
44 void GraphiteWriter::Start(void)
45 {
46         DynamicObject::Start();
47
48         m_ReconnectTimer = boost::make_shared<Timer>();
49         m_ReconnectTimer->SetInterval(10);
50         m_ReconnectTimer->OnTimerExpired.connect(boost::bind(&GraphiteWriter::ReconnectTimerHandler, this));
51         m_ReconnectTimer->Start();
52         m_ReconnectTimer->Reschedule(0);
53
54         Service::OnNewCheckResult.connect(boost::bind(&GraphiteWriter::CheckResultHandler, this, _1, _2));
55 }
56
57 String GraphiteWriter::GetHost(void) const
58 {
59         if (m_Host.IsEmpty())
60                 return "127.0.0.1";
61         else
62                 return m_Host;
63 }
64
65 String GraphiteWriter::GetPort(void) const
66 {
67         if (m_Port.IsEmpty())
68                 return "2003";
69         else
70                 return m_Port;
71 }
72
73 void GraphiteWriter::ReconnectTimerHandler(void)
74 {
75         /* TODO try to write the stream, and catch the exception - not connected */
76         if (m_Stream)
77                 return;
78
79         TcpSocket::Ptr socket = boost::make_shared<TcpSocket>();
80
81         Log(LogInformation, "icinga", "GraphiteWriter: Reconnect to tcp socket on host '" + GetHost() + "' port '" + GetPort() + "'.");
82         socket->Connect(GetHost(), GetPort());
83
84         NetworkStream::Ptr net_stream = boost::make_shared<NetworkStream>(socket);
85         m_Stream = boost::make_shared<BufferedStream>(net_stream);
86 }
87
88 void GraphiteWriter::CheckResultHandler(const Service::Ptr& service, const Dictionary::Ptr& cr)
89 {
90         if (!IcingaApplication::GetInstance()->GetEnablePerfdata())
91                 return;
92
93         Host::Ptr host = service->GetHost();
94
95         if (!host)
96                 return;
97
98         /* service metrics */
99         std::vector<String> metrics;
100         String metricName;
101         Value metricValue;
102
103         /* basic metrics */
104         AddServiceMetric(metrics, service, "current_attempt", service->GetCurrentCheckAttempt());
105         AddServiceMetric(metrics, service, "max_check_attempts", service->GetMaxCheckAttempts());
106         AddServiceMetric(metrics, service, "state_type", service->GetStateType());
107         AddServiceMetric(metrics, service, "state", service->GetState());
108         AddServiceMetric(metrics, service, "latency", Service::CalculateLatency(cr));
109         AddServiceMetric(metrics, service, "execution_time", Service::CalculateExecutionTime(cr));
110
111         /* performance data metrics */
112         String perfdata = CompatUtility::GetCheckResultPerfdata(cr);
113
114         if (!perfdata.IsEmpty()) {
115                 Log(LogDebug, "icinga", "GraphiteWriter: Processing perfdata: '" + perfdata + "'.");
116
117                 /*
118                  * 'foo bar'=0;;; baz=0.0;;;
119                  * 'label'=value[UOM];[warn];[crit];[min];[max]
120                 */
121                 std::vector<String> tokens;
122                 boost::algorithm::split(tokens, perfdata, boost::is_any_of(" "));
123
124                 /* TODO deal with 'foo bar'=0;;; 'baz'=1.0;;; */
125                 BOOST_FOREACH(const String& token, tokens) {
126                         std::vector<String> key_val;
127                         boost::algorithm::split(key_val, token, boost::is_any_of("="));
128
129                         if (key_val.size() == 0) {
130                                 Log(LogWarning, "icinga", "GraphiteWriter: Invalid performance data: '" + token + "'.");
131                                 return;
132                         }
133
134                         String metricName = key_val[0];
135
136                         if (key_val.size() == 1) {
137                                 Log(LogWarning, "icinga", "GraphiteWriter: Invalid performance data: '" + token + "'.");
138                                 return;
139                         }
140
141                         std::vector<String> perfdata_values;
142                         boost::algorithm::split(perfdata_values, key_val[1], boost::is_any_of(";"));
143
144                         if (perfdata_values.size() == 0) {
145                                 Log(LogWarning, "icinga", "GraphiteWriter: Invalid performance data: '" + token + "'.");
146                                 return;
147                         }
148
149                         /* TODO remove UOM from value */
150                         String metricValue = perfdata_values[0];
151
152                         /* //TODO: Figure out how graphite handles warn/crit/min/max
153                         String metricValueWarn, metricValueCrit, metricValueMin, metricValueMax;
154
155                         if (perfdata_values.size() > 1)
156                                 metricValueWarn = perfdata_values[1];
157                         if (perfdata_values.size() > 2)
158                                 metricValueCrit = perfdata_values[2];
159                         if (perfdata_values.size() > 3)
160                                 metricValueMin = perfdata_values[3];
161                         if (perfdata_values.size() > 4)
162                                 metricValueMax = perfdata_values[4];
163                         */
164
165                         AddServiceMetric(metrics, service, metricName, metricValue);
166                 }
167         }
168
169         SendMetrics(metrics);
170 }
171
172 void GraphiteWriter::AddServiceMetric(std::vector<String>& metrics, const Service::Ptr& service, const String& name, const Value& value)
173 {
174         /* TODO: sanitize host and service names */
175         String hostName = service->GetHost()->GetName();
176         String serviceName = service->GetShortName();   
177         String metricPrefix = hostName + "." + serviceName;
178         String graphitePrefix = "icinga";
179
180         String metric = graphitePrefix + ".service." + metricPrefix + "." + name + " " + Convert::ToString(value) + " " + Convert::ToString(static_cast<long>(Utility::GetTime())) + "\n";
181         Log(LogDebug, "icinga", "GraphiteWriter: Add to metric list:'" + metric + "'.");
182         metrics.push_back(metric);
183 }
184
185 void GraphiteWriter::SendMetrics(const std::vector<String>& metrics)
186 {
187         if (!m_Stream) {
188                 Log(LogWarning, "icinga", "GraphiteWriter not connected!");
189                 return;
190         }
191
192         BOOST_FOREACH(const String& metric, metrics) {
193                 if (metric.IsEmpty())
194                         continue;
195
196                 Log(LogDebug, "icinga", "GraphiteWriter: Sending metric '" + metric + "'.");
197                 m_Stream->Write(metric.CStr(), metric.GetLength());
198         }
199 }
200
201 void GraphiteWriter::InternalSerialize(const Dictionary::Ptr& bag, int attributeTypes) const
202 {
203         DynamicObject::InternalSerialize(bag, attributeTypes);
204
205         if (attributeTypes & Attribute_Config) {
206                 bag->Set("host", m_Host);
207                 bag->Set("port", m_Port);
208         }
209 }
210
211 void GraphiteWriter::InternalDeserialize(const Dictionary::Ptr& bag, int attributeTypes)
212 {
213         DynamicObject::InternalDeserialize(bag, attributeTypes);
214
215         if (attributeTypes & Attribute_Config) {
216                 m_Host = bag->Get("host");
217                 m_Port = bag->Get("port");
218         }
219 }