22// SPDX-License-Identifier: GPL-2.0-or-later
33
44#include " perfdata/opentsdbwriter.hpp"
5+ #include " base/defer.hpp"
56#include " perfdata/opentsdbwriter-ti.cpp"
67#include " icinga/service.hpp"
78#include " icinga/checkcommand.hpp"
@@ -88,6 +89,13 @@ void OpenTsdbWriter::Resume()
8889 << " Exception during OpenTsdb operation: " << DiagnosticInformation (exp);
8990 });
9091
92+ /* Setup timer for periodically flushing m_DataBuffer */
93+ m_FlushTimer = Timer::Create ();
94+ m_FlushTimer->SetInterval (GetFlushInterval ());
95+ m_FlushTimer->OnTimerExpired .connect ([this ](const Timer * const &) { FlushTimeout (); });
96+ m_FlushTimer->Start ();
97+ m_FlushTimer->Reschedule (0 );
98+
9199 ReadConfigTemplate ();
92100
93101 m_Connection = new PerfdataWriterConnection{this , GetHost (), GetPort ()};
@@ -282,7 +290,9 @@ void OpenTsdbWriter::CheckResultHandler(const Checkable::Ptr& checkable, const C
282290 AddMetric (checkable, metric + " .latency" , tags, cr->CalculateLatency (), ts);
283291 AddMetric (checkable, metric + " .execution_time" , tags, cr->CalculateExecutionTime (), ts);
284292
285- SendMsgBuffer ();
293+ if (GetFlushThreshold () <= m_MsgBuf.GetLength ()) {
294+ SendMsgBuffer ();
295+ }
286296 }
287297 );
288298}
@@ -387,7 +397,22 @@ void OpenTsdbWriter::AddMetric(const Checkable::Ptr& checkable, const String& me
387397
388398 /* do not send \n to debug log */
389399 msgbuf << " \n " ;
390- m_MsgBuf.append (msgbuf.str ());
400+ m_MsgBuf += msgbuf.str ();
401+ }
402+
403+ /* *
404+ * Queues a Flush on the work-queue if none is queued yet.
405+ */
406+ void OpenTsdbWriter::FlushTimeout ()
407+ {
408+ if (m_FlushTimerInQueue.exchange (true , std::memory_order_relaxed)) {
409+ return ;
410+ }
411+
412+ m_WorkQueue.Enqueue ([&]() {
413+ Defer resetFlushTimer{[&]() { m_FlushTimerInQueue.store (false , std::memory_order_relaxed); }};
414+ SendMsgBuffer ();
415+ });
391416}
392417
393418void OpenTsdbWriter::SendMsgBuffer ()
@@ -398,7 +423,7 @@ void OpenTsdbWriter::SendMsgBuffer()
398423 << " Flushing data buffer to OpenTsdb." ;
399424
400425 try {
401- m_Connection->Send (boost::asio::buffer (std::exchange (m_MsgBuf, std::string {})));
426+ m_Connection->Send (boost::asio::buffer (std::exchange (m_MsgBuf. GetData (), {})));
402427 } catch (const PerfdataWriterConnection::Stopped& ex) {
403428 Log (LogDebug, " OpenTsdbWriter" ) << ex.what ();
404429 return ;
0 commit comments