]> granicus.if.org Git - icinga2/blob - components/perfdata/graphitewriter.cpp
Fix: GraphiteWriter: reconnect on broken socket.
[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 #include <boost/algorithm/string/replace.hpp>
40 #include <boost/exception/diagnostic_information.hpp>
41
42 using namespace icinga;
43
44 REGISTER_TYPE(GraphiteWriter);
45
46 void GraphiteWriter::Start(void)
47 {
48         DynamicObject::Start();
49
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);
55
56         Service::OnNewCheckResult.connect(boost::bind(&GraphiteWriter::CheckResultHandler, this, _1, _2));
57 }
58
59 String GraphiteWriter::GetHost(void) const
60 {
61         if (m_Host.IsEmpty())
62                 return "127.0.0.1";
63         else
64                 return m_Host;
65 }
66
67 String GraphiteWriter::GetPort(void) const
68 {
69         if (m_Port.IsEmpty())
70                 return "2003";
71         else
72                 return m_Port;
73 }
74
75 void GraphiteWriter::ReconnectTimerHandler(void)
76 {
77         try {
78                 if (m_Stream) {
79                         m_Stream->Write("\n", 1);
80                         Log(LogWarning, "perfdata", "GraphiteWriter already connected on socket on host '" + GetHost() + "' port '" + GetPort() + "'.");
81                         return;
82                 }
83         } catch (const std::exception& ex) {
84                 Log(LogWarning, "perfdata", "GraphiteWriter socket on host '" + GetHost() + "' port '" + GetPort() + "' gone. Attempting to reconnect.");       
85         }
86
87         TcpSocket::Ptr socket = boost::make_shared<TcpSocket>();
88
89         Log(LogInformation, "perfdata", "GraphiteWriter: Reconnect to tcp socket on host '" + GetHost() + "' port '" + GetPort() + "'.");
90         socket->Connect(GetHost(), GetPort());
91
92         NetworkStream::Ptr net_stream = boost::make_shared<NetworkStream>(socket);
93         m_Stream = boost::make_shared<BufferedStream>(net_stream);
94 }
95
96 void GraphiteWriter::CheckResultHandler(const Service::Ptr& service, const Dictionary::Ptr& cr)
97 {
98         if (!IcingaApplication::GetInstance()->GetEnablePerfdata() || !service->GetEnablePerfdata())
99                 return;
100
101         Host::Ptr host = service->GetHost();
102
103         if (!host)
104                 return;
105
106         /* service metrics */
107         std::vector<String> metrics;
108         String metricName;
109         Value metricValue;
110
111         /* basic 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));
118
119         /* performance data metrics */
120         String perfdata = CompatUtility::GetCheckResultPerfdata(cr);
121
122         if (!perfdata.IsEmpty()) {
123                 Log(LogDebug, "perfdata", "GraphiteWriter: Processing perfdata: '" + perfdata + "'.");
124
125                 /*
126                  * 'foo bar'=0;;; baz=0.0;;;
127                  * 'label'=value[UOM];[warn];[crit];[min];[max]
128                 */
129                 std::vector<String> tokens;
130                 boost::algorithm::split(tokens, perfdata, boost::is_any_of(" "));
131
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("="));
136
137                         if (key_val.size() == 0) {
138                                 Log(LogWarning, "perfdata", "GraphiteWriter: Invalid performance data: '" + token + "'.");
139                                 return;
140                         }
141
142                         String metricName = key_val[0];
143
144                         if (key_val.size() == 1) {
145                                 Log(LogWarning, "perfdata", "GraphiteWriter: Invalid performance data: '" + token + "'.");
146                                 return;
147                         }
148
149                         std::vector<String> perfdata_values;
150                         boost::algorithm::split(perfdata_values, key_val[1], boost::is_any_of(";"));
151
152                         if (perfdata_values.size() == 0) {
153                                 Log(LogWarning, "perfdata", "GraphiteWriter: Invalid performance data: '" + token + "'.");
154                                 return;
155                         }
156
157                         /* TODO remove UOM from value */
158                         String metricValue = perfdata_values[0];
159
160                         /* //TODO: Figure out how graphite handles warn/crit/min/max
161                         String metricValueWarn, metricValueCrit, metricValueMin, metricValueMax;
162
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];
171                         */
172
173                         AddServiceMetric(metrics, service, metricName, metricValue);
174                 }
175         }
176
177         SendMetrics(metrics);
178 }
179
180 void GraphiteWriter::AddServiceMetric(std::vector<String>& metrics, const Service::Ptr& service, const String& name, const Value& value)
181 {
182         /* TODO: sanitize host and service names */
183         String hostName = service->GetHost()->GetName();
184         String serviceName = service->GetShortName();   
185         String metricPrefix = hostName + "." + serviceName;
186         
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, "/", "_");
192         
193         String graphitePrefix = "icinga";
194
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);
198 }
199
200 void GraphiteWriter::SendMetrics(const std::vector<String>& metrics)
201 {
202         BOOST_FOREACH(const String& metric, metrics) {
203                 if (metric.IsEmpty())
204                         continue;
205
206                 Log(LogDebug, "perfdata", "GraphiteWriter: Sending metric '" + metric + "'.");
207
208                 ObjectLock olock(this);
209
210                 if (!m_Stream)
211                         return;
212
213                 try {
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);
219
220                         Log(LogCritical, "base", msgbuf.str());
221
222                         m_Stream.reset();
223                 }
224         }
225 }
226
227 void GraphiteWriter::InternalSerialize(const Dictionary::Ptr& bag, int attributeTypes) const
228 {
229         DynamicObject::InternalSerialize(bag, attributeTypes);
230
231         if (attributeTypes & Attribute_Config) {
232                 bag->Set("host", m_Host);
233                 bag->Set("port", m_Port);
234         }
235 }
236
237 void GraphiteWriter::InternalDeserialize(const Dictionary::Ptr& bag, int attributeTypes)
238 {
239         DynamicObject::InternalDeserialize(bag, attributeTypes);
240
241         if (attributeTypes & Attribute_Config) {
242                 m_Host = bag->Get("host");
243                 m_Port = bag->Get("port");
244         }
245 }