]> granicus.if.org Git - icinga2/blob - components/perfdata/graphitewriter.cpp
Use PluginUtility::{Parse,Format}Perfdata for check results.
[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 "icinga/perfdatavalue.h"
26 #include "base/tcpsocket.h"
27 #include "base/dynamictype.h"
28 #include "base/objectlock.h"
29 #include "base/logger_fwd.h"
30 #include "base/convert.h"
31 #include "base/utility.h"
32 #include "base/application.h"
33 #include "base/stream.h"
34 #include "base/networkstream.h"
35 #include "base/bufferedstream.h"
36 #include <boost/algorithm/string.hpp>
37 #include <boost/algorithm/string/classification.hpp>
38 #include <boost/foreach.hpp>
39 #include <boost/algorithm/string/split.hpp>
40 #include <boost/algorithm/string/replace.hpp>
41 #include <boost/exception/diagnostic_information.hpp>
42
43 using namespace icinga;
44
45 REGISTER_TYPE(GraphiteWriter);
46
47 void GraphiteWriter::Start(void)
48 {
49         DynamicObject::Start();
50
51         m_ReconnectTimer = make_shared<Timer>();
52         m_ReconnectTimer->SetInterval(10);
53         m_ReconnectTimer->OnTimerExpired.connect(boost::bind(&GraphiteWriter::ReconnectTimerHandler, this));
54         m_ReconnectTimer->Start();
55         m_ReconnectTimer->Reschedule(0);
56
57         Service::OnNewCheckResult.connect(boost::bind(&GraphiteWriter::CheckResultHandler, this, _1, _2));
58 }
59
60 void GraphiteWriter::ReconnectTimerHandler(void)
61 {
62         try {
63                 if (m_Stream) {
64                         m_Stream->Write("\n", 1);
65                         Log(LogWarning, "perfdata", "GraphiteWriter already connected on socket on host '" + GetHost() + "' port '" + GetPort() + "'.");
66                         return;
67                 }
68         } catch (const std::exception& ex) {
69                 Log(LogWarning, "perfdata", "GraphiteWriter socket on host '" + GetHost() + "' port '" + GetPort() + "' gone. Attempting to reconnect.");       
70         }
71
72         TcpSocket::Ptr socket = make_shared<TcpSocket>();
73
74         Log(LogDebug, "perfdata", "GraphiteWriter: Reconnect to tcp socket on host '" + GetHost() + "' port '" + GetPort() + "'.");
75         socket->Connect(GetHost(), GetPort());
76
77         NetworkStream::Ptr net_stream = make_shared<NetworkStream>(socket);
78         m_Stream = make_shared<BufferedStream>(net_stream);
79 }
80
81 void GraphiteWriter::CheckResultHandler(const Service::Ptr& service, const Dictionary::Ptr& cr)
82 {
83         if (!IcingaApplication::GetInstance()->GetEnablePerfdata() || !service->GetEnablePerfdata())
84                 return;
85
86         /* basic metrics */
87         SendMetric(service, "current_attempt", service->GetCheckAttempt());
88         SendMetric(service, "max_check_attempts", service->GetMaxCheckAttempts());
89         SendMetric(service, "state_type", service->GetStateType());
90         SendMetric(service, "state", service->GetState());
91         SendMetric(service, "latency", Service::CalculateLatency(cr));
92         SendMetric(service, "execution_time", Service::CalculateExecutionTime(cr));
93
94         Value pdv = cr->Get("performance_data");
95
96         if (!pdv.IsObjectType<Dictionary>())
97                 return;
98
99         Dictionary::Ptr perfdata = pdv;
100
101         String key;
102         Value value;
103         BOOST_FOREACH(boost::tie(key, value), perfdata) {
104                 double valueNum;
105
106                 if (!value.IsObjectType<PerfdataValue>())
107                         valueNum = value;
108                 else
109                         valueNum = static_cast<PerfdataValue::Ptr>(value)->GetValue();
110
111                 SendMetric(service, key, valueNum);
112         }
113 }
114
115 void GraphiteWriter::SendMetric(const Service::Ptr& service, const String& name, double value)
116 {
117         /* TODO: sanitize host and service names */
118         String hostName = service->GetHost()->GetName();
119         String serviceName = service->GetShortName();   
120
121         SanitizeMetric(hostName);
122         SanitizeMetric(serviceName);
123
124         String metricPrefix = hostName + "." + serviceName;
125         String graphitePrefix = "icinga";
126
127         String metric = graphitePrefix + "." + metricPrefix + "." + name + " " + Convert::ToString(value) + " " + Convert::ToString(static_cast<long>(Utility::GetTime())) + "\n";
128         Log(LogDebug, "perfdata", "GraphiteWriter: Add to metric list:'" + metric + "'.");
129
130         ObjectLock olock(this);
131
132         if (!m_Stream)
133                 return;
134
135         try {
136                 m_Stream->Write(metric.CStr(), metric.GetLength());
137         } catch (const std::exception& ex) {
138                 std::ostringstream msgbuf;
139                 msgbuf << "Exception thrown while writing to the Graphite socket: " << std::endl
140                        << boost::diagnostic_information(ex);
141
142                 Log(LogCritical, "base", msgbuf.str());
143
144                 m_Stream.reset();
145         }
146 }
147
148 void GraphiteWriter::SanitizeMetric(String& str)
149 {
150         boost::replace_all(str, " ", "_");
151         boost::replace_all(str, ".", "_");
152         boost::replace_all(str, "-", "_");
153         boost::replace_all(str, "\\", "_");
154         boost::replace_all(str, "/", "_");
155 }