]> granicus.if.org Git - icinga2/blob - components/perfdata/graphitewriter.cpp
Remove TODO comment.
[icinga2] / components / perfdata / graphitewriter.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2014 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 "base/exception.h"
37 #include "base/statsfunction.h"
38 #include <boost/algorithm/string.hpp>
39 #include <boost/algorithm/string/classification.hpp>
40 #include <boost/foreach.hpp>
41 #include <boost/algorithm/string/split.hpp>
42 #include <boost/algorithm/string/replace.hpp>
43
44 using namespace icinga;
45
46 REGISTER_TYPE(GraphiteWriter);
47
48 REGISTER_STATSFUNCTION(GraphiteWriterStats, &GraphiteWriter::StatsFunc);
49
50 Value GraphiteWriter::StatsFunc(Dictionary::Ptr& status, Dictionary::Ptr& perfdata)
51 {
52         Dictionary::Ptr nodes = make_shared<Dictionary>();
53
54         BOOST_FOREACH(const GraphiteWriter::Ptr& graphitewriter, DynamicType::GetObjects<GraphiteWriter>()) {
55                 nodes->Set(graphitewriter->GetName(), 1); //add more stats
56         }
57
58         status->Set("graphitewriter", nodes);
59
60         return 0;
61 }
62
63 void GraphiteWriter::Start(void)
64 {
65         DynamicObject::Start();
66
67         m_ReconnectTimer = make_shared<Timer>();
68         m_ReconnectTimer->SetInterval(10);
69         m_ReconnectTimer->OnTimerExpired.connect(boost::bind(&GraphiteWriter::ReconnectTimerHandler, this));
70         m_ReconnectTimer->Start();
71         m_ReconnectTimer->Reschedule(0);
72
73         Service::OnNewCheckResult.connect(boost::bind(&GraphiteWriter::CheckResultHandler, this, _1, _2));
74 }
75
76 void GraphiteWriter::ReconnectTimerHandler(void)
77 {
78         try {
79                 if (m_Stream) {
80                         m_Stream->Write("\n", 1);
81                         Log(LogWarning, "perfdata", "GraphiteWriter already connected on socket on host '" + GetHost() + "' port '" + GetPort() + "'.");
82                         return;
83                 }
84         } catch (const std::exception& ex) {
85                 Log(LogWarning, "perfdata", "GraphiteWriter socket on host '" + GetHost() + "' port '" + GetPort() + "' gone. Attempting to reconnect.");
86         }
87
88         TcpSocket::Ptr socket = make_shared<TcpSocket>();
89
90         Log(LogDebug, "perfdata", "GraphiteWriter: Reconnect to tcp socket on host '" + GetHost() + "' port '" + GetPort() + "'.");
91         socket->Connect(GetHost(), GetPort());
92
93         NetworkStream::Ptr net_stream = make_shared<NetworkStream>(socket);
94         m_Stream = make_shared<BufferedStream>(net_stream);
95 }
96
97 void GraphiteWriter::CheckResultHandler(const Service::Ptr& service, const CheckResult::Ptr& cr)
98 {
99         if (!IcingaApplication::GetInstance()->GetEnablePerfdata() || !service->GetEnablePerfdata())
100                 return;
101
102         Host::Ptr host = service->GetHost();
103
104         String hostName = host->GetName();
105         String serviceName = service->GetShortName();
106
107         SanitizeMetric(hostName);
108         SanitizeMetric(serviceName);
109
110         String prefix = "icinga." + hostName + "." + serviceName;
111
112         /* service metrics */
113         SendMetric(prefix, "current_attempt", service->GetCheckAttempt());
114         SendMetric(prefix, "max_check_attempts", service->GetMaxCheckAttempts());
115         SendMetric(prefix, "state_type", service->GetStateType());
116         SendMetric(prefix, "state", service->GetState());
117         SendMetric(prefix, "latency", Service::CalculateLatency(cr));
118         SendMetric(prefix, "execution_time", Service::CalculateExecutionTime(cr));
119
120         SendPerfdata(prefix, cr);
121
122         if (service == host->GetCheckService()) {
123                 prefix = "icinga." + hostName;
124
125                 /* host metrics */
126                 SendMetric(prefix, "current_attempt", service->GetCheckAttempt());
127                 SendMetric(prefix, "max_check_attempts", service->GetMaxCheckAttempts());
128                 SendMetric(prefix, "state_type", host->GetStateType());
129                 SendMetric(prefix, "state", host->GetState());
130                 SendMetric(prefix, "latency", Service::CalculateLatency(cr));
131                 SendMetric(prefix, "execution_time", Service::CalculateExecutionTime(cr));
132
133                 SendPerfdata(prefix, cr);
134         }
135 }
136
137 void GraphiteWriter::SendPerfdata(const String& prefix, const CheckResult::Ptr& cr)
138 {
139         Value pdv = cr->GetPerformanceData();
140
141         if (!pdv.IsObjectType<Dictionary>())
142                 return;
143
144         Dictionary::Ptr perfdata = pdv;
145
146         ObjectLock olock(perfdata);
147         BOOST_FOREACH(const Dictionary::Pair& kv, perfdata) {
148                 double valueNum;
149
150                 if (!kv.second.IsObjectType<PerfdataValue>())
151                         valueNum = kv.second;
152                 else
153                         valueNum = static_cast<PerfdataValue::Ptr>(kv.second)->GetValue();
154
155                 String escaped_key = kv.first;
156                 SanitizeMetric(escaped_key);
157                 boost::algorithm::replace_all(escaped_key, "::", ".");
158
159                 SendMetric(prefix, escaped_key, valueNum);
160         }
161 }
162
163 void GraphiteWriter::SendMetric(const String& prefix, const String& name, double value)
164 {
165         std::ostringstream msgbuf;
166         msgbuf << prefix << "." << name << " " << value << " " << static_cast<long>(Utility::GetTime()) << "\n";
167
168         String metric = msgbuf.str();
169         Log(LogDebug, "perfdata", "GraphiteWriter: Add to metric list:'" + metric + "'.");
170
171         ObjectLock olock(this);
172
173         if (!m_Stream)
174                 return;
175
176         try {
177                 m_Stream->Write(metric.CStr(), metric.GetLength());
178         } catch (const std::exception& ex) {
179                 std::ostringstream msgbuf;
180                 msgbuf << "Exception thrown while writing to the Graphite socket: " << std::endl
181                        << DiagnosticInformation(ex);
182
183                 Log(LogCritical, "base", msgbuf.str());
184
185                 m_Stream.reset();
186         }
187 }
188
189 void GraphiteWriter::SanitizeMetric(String& str)
190 {
191         boost::replace_all(str, " ", "_");
192         boost::replace_all(str, ".", "_");
193         boost::replace_all(str, "-", "_");
194         boost::replace_all(str, "\\", "_");
195         boost::replace_all(str, "/", "_");
196 }