1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
3 #include "perfdata/influxdbwriter.hpp"
4 #include "perfdata/influxdbwriter-ti.cpp"
5 #include "remote/url.hpp"
6 #include "remote/httprequest.hpp"
7 #include "remote/httpresponse.hpp"
8 #include "icinga/service.hpp"
9 #include "icinga/macroprocessor.hpp"
10 #include "icinga/icingaapplication.hpp"
11 #include "icinga/checkcommand.hpp"
12 #include "base/application.hpp"
13 #include "base/defer.hpp"
14 #include "base/io-engine.hpp"
15 #include "base/tcpsocket.hpp"
16 #include "base/configtype.hpp"
17 #include "base/objectlock.hpp"
18 #include "base/logger.hpp"
19 #include "base/convert.hpp"
20 #include "base/utility.hpp"
21 #include "base/perfdatavalue.hpp"
22 #include "base/stream.hpp"
23 #include "base/json.hpp"
24 #include "base/networkstream.hpp"
25 #include "base/exception.hpp"
26 #include "base/statsfunction.hpp"
27 #include "base/tlsutility.hpp"
28 #include <boost/algorithm/string.hpp>
29 #include <boost/algorithm/string/replace.hpp>
30 #include <boost/asio/ssl/context.hpp>
31 #include <boost/beast/core/flat_buffer.hpp>
32 #include <boost/beast/http/field.hpp>
33 #include <boost/beast/http/message.hpp>
34 #include <boost/beast/http/parser.hpp>
35 #include <boost/beast/http/read.hpp>
36 #include <boost/beast/http/status.hpp>
37 #include <boost/beast/http/string_body.hpp>
38 #include <boost/beast/http/verb.hpp>
39 #include <boost/beast/http/write.hpp>
40 #include <boost/math/special_functions/fpclassify.hpp>
41 #include <boost/regex.hpp>
42 #include <boost/scoped_array.hpp>
47 using namespace icinga;
49 class InfluxdbInteger final : public Object
52 DECLARE_PTR_TYPEDEFS(InfluxdbInteger);
54 InfluxdbInteger(int value)
67 REGISTER_TYPE(InfluxdbWriter);
69 REGISTER_STATSFUNCTION(InfluxdbWriter, &InfluxdbWriter::StatsFunc);
71 void InfluxdbWriter::OnConfigLoaded()
73 ObjectImpl<InfluxdbWriter>::OnConfigLoaded();
75 m_WorkQueue.SetName("InfluxdbWriter, " + GetName());
78 Log(LogDebug, "InfluxdbWriter")
79 << "HA functionality disabled. Won't pause connection: " << GetName();
81 SetHAMode(HARunEverywhere);
87 void InfluxdbWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata)
91 for (const InfluxdbWriter::Ptr& influxdbwriter : ConfigType::GetObjectsByType<InfluxdbWriter>()) {
92 size_t workQueueItems = influxdbwriter->m_WorkQueue.GetLength();
93 double workQueueItemRate = influxdbwriter->m_WorkQueue.GetTaskCount(60) / 60.0;
94 size_t dataBufferItems = influxdbwriter->m_DataBuffer.size();
96 nodes.emplace_back(influxdbwriter->GetName(), new Dictionary({
97 { "work_queue_items", workQueueItems },
98 { "work_queue_item_rate", workQueueItemRate },
99 { "data_buffer_items", dataBufferItems }
102 perfdata->Add(new PerfdataValue("influxdbwriter_" + influxdbwriter->GetName() + "_work_queue_items", workQueueItems));
103 perfdata->Add(new PerfdataValue("influxdbwriter_" + influxdbwriter->GetName() + "_work_queue_item_rate", workQueueItemRate));
104 perfdata->Add(new PerfdataValue("influxdbwriter_" + influxdbwriter->GetName() + "_data_queue_items", dataBufferItems));
107 status->Set("influxdbwriter", new Dictionary(std::move(nodes)));
110 void InfluxdbWriter::Resume()
112 ObjectImpl<InfluxdbWriter>::Resume();
114 Log(LogInformation, "InfluxdbWriter")
115 << "'" << GetName() << "' resumed.";
117 /* Register exception handler for WQ tasks. */
118 m_WorkQueue.SetExceptionCallback(std::bind(&InfluxdbWriter::ExceptionHandler, this, _1));
120 /* Setup timer for periodically flushing m_DataBuffer */
121 m_FlushTimer = new Timer();
122 m_FlushTimer->SetInterval(GetFlushInterval());
123 m_FlushTimer->OnTimerExpired.connect(std::bind(&InfluxdbWriter::FlushTimeout, this));
124 m_FlushTimer->Start();
125 m_FlushTimer->Reschedule(0);
127 /* Register for new metrics. */
128 Checkable::OnNewCheckResult.connect(std::bind(&InfluxdbWriter::CheckResultHandler, this, _1, _2));
131 /* Pause is equivalent to Stop, but with HA capabilities to resume at runtime. */
132 void InfluxdbWriter::Pause()
135 Log(LogDebug, "InfluxdbWriter")
136 << "Flushing pending data buffers.";
140 /* Work on the missing tasks. TODO: Find a way to cache them on disk. */
141 Log(LogDebug, "InfluxdbWriter")
142 << "Joining existing WQ tasks.";
146 /* Flush again after the WQ tasks have filled the data buffer. */
147 Log(LogDebug, "InfluxdbWriter")
148 << "Flushing data buffers from WQ tasks.";
152 Log(LogInformation, "InfluxdbWriter")
153 << "'" << GetName() << "' paused.";
155 ObjectImpl<InfluxdbWriter>::Pause();
158 void InfluxdbWriter::AssertOnWorkQueue()
160 ASSERT(m_WorkQueue.IsWorkerThread());
163 void InfluxdbWriter::ExceptionHandler(boost::exception_ptr exp)
165 Log(LogCritical, "InfluxdbWriter", "Exception during InfluxDB operation: Verify that your backend is operational!");
167 Log(LogDebug, "InfluxdbWriter")
168 << "Exception during InfluxDB operation: " << DiagnosticInformation(std::move(exp));
170 //TODO: Close the connection, if we keep it open.
173 OptionalTlsStream InfluxdbWriter::Connect()
175 Log(LogNotice, "InfluxdbWriter")
176 << "Reconnecting to InfluxDB on host '" << GetHost() << "' port '" << GetPort() << "'.";
178 OptionalTlsStream stream;
179 bool ssl = GetSslEnable();
182 std::shared_ptr<boost::asio::ssl::context> sslContext;
185 sslContext = MakeAsioSslContext(GetSslCert(), GetSslKey(), GetSslCaCert());
186 } catch (const std::exception& ex) {
187 Log(LogWarning, "InfluxdbWriter")
188 << "Unable to create SSL context.";
192 stream.first = std::make_shared<AsioTlsStream>(IoEngine::Get().GetIoService(), *sslContext, GetHost());
194 stream.second = std::make_shared<AsioTcpStream>(IoEngine::Get().GetIoService());
198 icinga::Connect(ssl ? stream.first->lowest_layer() : stream.second->lowest_layer(), GetHost(), GetPort());
199 } catch (const std::exception& ex) {
200 Log(LogWarning, "InfluxdbWriter")
201 << "Can't connect to InfluxDB on host '" << GetHost() << "' port '" << GetPort() << "'.";
206 auto& tlsStream (stream.first->next_layer());
209 tlsStream.handshake(tlsStream.client);
210 } catch (const std::exception& ex) {
211 Log(LogWarning, "InfluxdbWriter")
212 << "TLS handshake with host '" << GetHost() << "' failed.";
217 return std::move(stream);
220 void InfluxdbWriter::CheckResultHandler(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr)
225 m_WorkQueue.Enqueue(std::bind(&InfluxdbWriter::CheckResultHandlerWQ, this, checkable, cr), PriorityLow);
228 void InfluxdbWriter::CheckResultHandlerWQ(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr)
232 CONTEXT("Processing check result for '" + checkable->GetName() + "'");
234 if (!IcingaApplication::GetInstance()->GetEnablePerfdata() || !checkable->GetEnablePerfdata())
238 Service::Ptr service;
239 tie(host, service) = GetHostService(checkable);
241 MacroProcessor::ResolverList resolvers;
243 resolvers.emplace_back("service", service);
244 resolvers.emplace_back("host", host);
245 resolvers.emplace_back("icinga", IcingaApplication::GetInstance());
249 double ts = cr->GetExecutionEnd();
251 // Clone the template and perform an in-place macro expansion of measurement and tag values
252 Dictionary::Ptr tmpl_clean = service ? GetServiceTemplate() : GetHostTemplate();
253 Dictionary::Ptr tmpl = static_pointer_cast<Dictionary>(tmpl_clean->Clone());
254 tmpl->Set("measurement", MacroProcessor::ResolveMacros(tmpl->Get("measurement"), resolvers, cr));
256 Dictionary::Ptr tags = tmpl->Get("tags");
258 ObjectLock olock(tags);
259 for (const Dictionary::Pair& pair : tags) {
260 String missing_macro;
261 Value value = MacroProcessor::ResolveMacros(pair.second, resolvers, cr, &missing_macro);
263 if (!missing_macro.IsEmpty())
266 tags->Set(pair.first, value);
270 CheckCommand::Ptr checkCommand = checkable->GetCheckCommand();
272 Array::Ptr perfdata = cr->GetPerformanceData();
275 ObjectLock olock(perfdata);
276 for (const Value& val : perfdata) {
277 PerfdataValue::Ptr pdv;
279 if (val.IsObjectType<PerfdataValue>())
283 pdv = PerfdataValue::Parse(val);
284 } catch (const std::exception&) {
285 Log(LogWarning, "InfluxdbWriter")
286 << "Ignoring invalid perfdata for checkable '"
287 << checkable->GetName() << "' and command '"
288 << checkCommand->GetName() << "' with value: " << val;
293 Dictionary::Ptr fields = new Dictionary();
294 fields->Set("value", pdv->GetValue());
296 if (GetEnableSendThresholds()) {
298 fields->Set("crit", pdv->GetCrit());
300 fields->Set("warn", pdv->GetWarn());
302 fields->Set("min", pdv->GetMin());
304 fields->Set("max", pdv->GetMax());
306 if (!pdv->GetUnit().IsEmpty()) {
307 fields->Set("unit", pdv->GetUnit());
310 SendMetric(checkable, tmpl, pdv->GetLabel(), fields, ts);
314 if (GetEnableSendMetadata()) {
316 Service::Ptr service;
317 tie(host, service) = GetHostService(checkable);
319 Dictionary::Ptr fields = new Dictionary();
322 fields->Set("state", new InfluxdbInteger(service->GetState()));
324 fields->Set("state", new InfluxdbInteger(host->GetState()));
326 fields->Set("current_attempt", new InfluxdbInteger(checkable->GetCheckAttempt()));
327 fields->Set("max_check_attempts", new InfluxdbInteger(checkable->GetMaxCheckAttempts()));
328 fields->Set("state_type", new InfluxdbInteger(checkable->GetStateType()));
329 fields->Set("reachable", checkable->IsReachable());
330 fields->Set("downtime_depth", new InfluxdbInteger(checkable->GetDowntimeDepth()));
331 fields->Set("acknowledgement", new InfluxdbInteger(checkable->GetAcknowledgement()));
332 fields->Set("latency", cr->CalculateLatency());
333 fields->Set("execution_time", cr->CalculateExecutionTime());
335 SendMetric(checkable, tmpl, Empty, fields, ts);
339 String InfluxdbWriter::EscapeKeyOrTagValue(const String& str)
341 // Iterate over the key name and escape commas and spaces with a backslash
343 boost::algorithm::replace_all(result, "\"", "\\\"");
344 boost::algorithm::replace_all(result, "=", "\\=");
345 boost::algorithm::replace_all(result, ",", "\\,");
346 boost::algorithm::replace_all(result, " ", "\\ ");
348 // InfluxDB 'feature': although backslashes are allowed in keys they also act
349 // as escape sequences when followed by ',' or ' '. When your tag is like
350 // 'metric=C:\' bad things happen. Backslashes themselves cannot be escaped
351 // and through experimentation they also escape '='. To be safe we replace
352 // trailing backslashes with and underscore.
353 // See https://github.com/influxdata/influxdb/issues/8587 for more info
354 size_t length = result.GetLength();
355 if (result[length - 1] == '\\')
356 result[length - 1] = '_';
361 String InfluxdbWriter::EscapeValue(const Value& value)
363 if (value.IsObjectType<InfluxdbInteger>()) {
364 std::ostringstream os;
365 os << static_cast<InfluxdbInteger::Ptr>(value)->GetValue() << "i";
369 if (value.IsBoolean())
370 return value ? "true" : "false";
372 if (value.IsString())
373 return "\"" + EscapeKeyOrTagValue(value) + "\"";
378 void InfluxdbWriter::SendMetric(const Checkable::Ptr& checkable, const Dictionary::Ptr& tmpl,
379 const String& label, const Dictionary::Ptr& fields, double ts)
381 std::ostringstream msgbuf;
382 msgbuf << EscapeKeyOrTagValue(tmpl->Get("measurement"));
384 Dictionary::Ptr tags = tmpl->Get("tags");
386 ObjectLock olock(tags);
387 for (const Dictionary::Pair& pair : tags) {
388 // Empty macro expansion, no tag
389 if (!pair.second.IsEmpty()) {
390 msgbuf << "," << EscapeKeyOrTagValue(pair.first) << "=" << EscapeKeyOrTagValue(pair.second);
395 // Label may be empty in the case of metadata
396 if (!label.IsEmpty())
397 msgbuf << ",metric=" << EscapeKeyOrTagValue(label);
404 ObjectLock fieldLock(fields);
405 for (const Dictionary::Pair& pair : fields) {
411 msgbuf << EscapeKeyOrTagValue(pair.first) << "=" << EscapeValue(pair.second);
415 msgbuf << " " << static_cast<unsigned long>(ts);
417 Log(LogDebug, "InfluxdbWriter")
418 << "Checkable '" << checkable->GetName() << "' adds to metric list:'" << msgbuf.str() << "'.";
420 // Buffer the data point
421 m_DataBuffer.emplace_back(msgbuf.str());
423 // Flush if we've buffered too much to prevent excessive memory use
424 if (static_cast<int>(m_DataBuffer.size()) >= GetFlushThreshold()) {
425 Log(LogDebug, "InfluxdbWriter")
426 << "Data buffer overflow writing " << m_DataBuffer.size() << " data points";
436 void InfluxdbWriter::FlushTimeout()
438 m_WorkQueue.Enqueue(boost::bind(&InfluxdbWriter::FlushTimeoutWQ, this), PriorityHigh);
441 void InfluxdbWriter::FlushTimeoutWQ()
445 Log(LogDebug, "InfluxdbWriter")
446 << "Timer expired writing " << m_DataBuffer.size() << " data points";
451 void InfluxdbWriter::Flush()
453 namespace beast = boost::beast;
454 namespace http = beast::http;
456 /* Flush can be called from 1) Timeout 2) Threshold 3) on shutdown/reload. */
457 if (m_DataBuffer.empty())
460 Log(LogDebug, "InfluxdbWriter")
461 << "Flushing data buffer to InfluxDB.";
463 String body = boost::algorithm::join(m_DataBuffer, "\n");
464 m_DataBuffer.clear();
466 OptionalTlsStream stream;
470 } catch (const std::exception& ex) {
471 Log(LogWarning, "InfluxDbWriter")
472 << "Flush failed, cannot connect to InfluxDB: " << DiagnosticInformation(ex, false);
476 Defer s ([&stream]() {
478 stream.first->next_layer().shutdown();
482 Url::Ptr url = new Url();
483 url->SetScheme(GetSslEnable() ? "https" : "http");
484 url->SetHost(GetHost());
485 url->SetPort(GetPort());
487 std::vector<String> path;
488 path.emplace_back("write");
491 url->AddQueryElement("db", GetDatabase());
492 url->AddQueryElement("precision", "s");
493 if (!GetUsername().IsEmpty())
494 url->AddQueryElement("u", GetUsername());
495 if (!GetPassword().IsEmpty())
496 url->AddQueryElement("p", GetPassword());
498 http::request<http::string_body> request (http::verb::post, std::string(url->Format(true)), 10);
500 request.set(http::field::user_agent, "Icinga/" + Application::GetAppVersion());
501 request.set(http::field::host, url->GetHost() + ":" + url->GetPort());
503 request.body() = body;
504 request.set(http::field::content_length, request.body().size());
508 http::write(*stream.first, request);
509 stream.first->flush();
511 http::write(*stream.second, request);
512 stream.second->flush();
514 } catch (const std::exception& ex) {
515 Log(LogWarning, "InfluxdbWriter")
516 << "Cannot write to TCP socket on host '" << GetHost() << "' port '" << GetPort() << "'.";
520 http::parser<false, http::string_body> parser;
521 beast::flat_buffer buf;
525 http::read(*stream.first, buf, parser);
527 http::read(*stream.second, buf, parser);
529 } catch (const std::exception& ex) {
530 Log(LogWarning, "InfluxdbWriter")
531 << "Failed to parse HTTP response from host '" << GetHost() << "' port '" << GetPort() << "': " << DiagnosticInformation(ex);
535 auto& response (parser.get());
537 if (response.result() != http::status::no_content) {
538 Log(LogWarning, "InfluxdbWriter")
539 << "Unexpected response code: " << response.result();
541 auto& contentType (response[http::field::content_type]);
542 if (contentType != "application/json") {
543 Log(LogWarning, "InfluxdbWriter")
544 << "Unexpected Content-Type: " << contentType;
548 Dictionary::Ptr jsonResponse;
549 auto& body (response.body());
552 jsonResponse = JsonDecode(body);
554 Log(LogWarning, "InfluxdbWriter")
555 << "Unable to parse JSON response:\n" << body;
559 String error = jsonResponse->Get("error");
561 Log(LogCritical, "InfluxdbWriter")
562 << "InfluxDB error message:\n" << error;
566 void InfluxdbWriter::ValidateHostTemplate(const Lazy<Dictionary::Ptr>& lvalue, const ValidationUtils& utils)
568 ObjectImpl<InfluxdbWriter>::ValidateHostTemplate(lvalue, utils);
570 String measurement = lvalue()->Get("measurement");
571 if (!MacroProcessor::ValidateMacroString(measurement))
572 BOOST_THROW_EXCEPTION(ValidationError(this, { "host_template", "measurement" }, "Closing $ not found in macro format string '" + measurement + "'."));
574 Dictionary::Ptr tags = lvalue()->Get("tags");
576 ObjectLock olock(tags);
577 for (const Dictionary::Pair& pair : tags) {
578 if (!MacroProcessor::ValidateMacroString(pair.second))
579 BOOST_THROW_EXCEPTION(ValidationError(this, { "host_template", "tags", pair.first }, "Closing $ not found in macro format string '" + pair.second));
584 void InfluxdbWriter::ValidateServiceTemplate(const Lazy<Dictionary::Ptr>& lvalue, const ValidationUtils& utils)
586 ObjectImpl<InfluxdbWriter>::ValidateServiceTemplate(lvalue, utils);
588 String measurement = lvalue()->Get("measurement");
589 if (!MacroProcessor::ValidateMacroString(measurement))
590 BOOST_THROW_EXCEPTION(ValidationError(this, { "service_template", "measurement" }, "Closing $ not found in macro format string '" + measurement + "'."));
592 Dictionary::Ptr tags = lvalue()->Get("tags");
594 ObjectLock olock(tags);
595 for (const Dictionary::Pair& pair : tags) {
596 if (!MacroProcessor::ValidateMacroString(pair.second))
597 BOOST_THROW_EXCEPTION(ValidationError(this, { "service_template", "tags", pair.first }, "Closing $ not found in macro format string '" + pair.second));