From 0915b3ef56dfac3113cce55a59a5765dc94976be Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 28 Apr 2024 14:34:54 +0200 Subject: Adding upstream version 2.13.6. Signed-off-by: Daniel Baumann --- lib/compat/CMakeLists.txt | 47 ++ lib/compat/checkresultreader.cpp | 166 ++++++ lib/compat/checkresultreader.hpp | 38 ++ lib/compat/checkresultreader.ti | 20 + lib/compat/compatlogger.cpp | 612 ++++++++++++++++++++++ lib/compat/compatlogger.hpp | 60 +++ lib/compat/compatlogger.ti | 23 + lib/compat/externalcommandlistener.cpp | 150 ++++++ lib/compat/externalcommandlistener.hpp | 41 ++ lib/compat/externalcommandlistener.ti | 20 + lib/compat/statusdatawriter.cpp | 897 +++++++++++++++++++++++++++++++++ lib/compat/statusdatawriter.hpp | 89 ++++ lib/compat/statusdatawriter.ti | 26 + 13 files changed, 2189 insertions(+) create mode 100644 lib/compat/CMakeLists.txt create mode 100644 lib/compat/checkresultreader.cpp create mode 100644 lib/compat/checkresultreader.hpp create mode 100644 lib/compat/checkresultreader.ti create mode 100644 lib/compat/compatlogger.cpp create mode 100644 lib/compat/compatlogger.hpp create mode 100644 lib/compat/compatlogger.ti create mode 100644 lib/compat/externalcommandlistener.cpp create mode 100644 lib/compat/externalcommandlistener.hpp create mode 100644 lib/compat/externalcommandlistener.ti create mode 100644 lib/compat/statusdatawriter.cpp create mode 100644 lib/compat/statusdatawriter.hpp create mode 100644 lib/compat/statusdatawriter.ti (limited to 'lib/compat') diff --git a/lib/compat/CMakeLists.txt b/lib/compat/CMakeLists.txt new file mode 100644 index 0000000..84225c4 --- /dev/null +++ b/lib/compat/CMakeLists.txt @@ -0,0 +1,47 @@ +# Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ + +mkclass_target(checkresultreader.ti checkresultreader-ti.cpp checkresultreader-ti.hpp) +mkclass_target(compatlogger.ti compatlogger-ti.cpp compatlogger-ti.hpp) +mkclass_target(externalcommandlistener.ti externalcommandlistener-ti.cpp externalcommandlistener-ti.hpp) +mkclass_target(statusdatawriter.ti statusdatawriter-ti.cpp statusdatawriter-ti.hpp) + +set(compat_SOURCES + checkresultreader.cpp checkresultreader.hpp checkresultreader-ti.hpp + compatlogger.cpp compatlogger.hpp compatlogger-ti.hpp + externalcommandlistener.cpp externalcommandlistener.hpp externalcommandlistener-ti.hpp + statusdatawriter.cpp statusdatawriter.hpp statusdatawriter-ti.hpp +) + +if(ICINGA2_UNITY_BUILD) + mkunity_target(compat compat compat_SOURCES) +endif() + +add_library(compat OBJECT ${compat_SOURCES}) + +add_dependencies(compat base config icinga) + +set_target_properties ( + compat PROPERTIES + FOLDER Components +) + +install_if_not_exists( + ${PROJECT_SOURCE_DIR}/etc/icinga2/features-available/command.conf + ${ICINGA2_CONFIGDIR}/features-available +) + +install_if_not_exists( + ${PROJECT_SOURCE_DIR}/etc/icinga2/features-available/compatlog.conf + ${ICINGA2_CONFIGDIR}/features-available +) + +install_if_not_exists( + ${PROJECT_SOURCE_DIR}/etc/icinga2/features-available/statusdata.conf + ${ICINGA2_CONFIGDIR}/features-available +) + +install(CODE "file(MAKE_DIRECTORY \"\$ENV{DESTDIR}${ICINGA2_FULL_LOGDIR}/compat/archives\")") +install(CODE "file(MAKE_DIRECTORY \"\$ENV{DESTDIR}${ICINGA2_FULL_SPOOLDIR}\")") +install(CODE "file(MAKE_DIRECTORY \"\$ENV{DESTDIR}${ICINGA2_FULL_INITRUNDIR}/cmd\")") + +set(CPACK_NSIS_EXTRA_INSTALL_COMMANDS "${CPACK_NSIS_EXTRA_INSTALL_COMMANDS}" PARENT_SCOPE) diff --git a/lib/compat/checkresultreader.cpp b/lib/compat/checkresultreader.cpp new file mode 100644 index 0000000..e4516a3 --- /dev/null +++ b/lib/compat/checkresultreader.cpp @@ -0,0 +1,166 @@ +/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */ + +#include "icinga/compatutility.hpp" +#include "compat/checkresultreader.hpp" +#include "compat/checkresultreader-ti.cpp" +#include "icinga/service.hpp" +#include "icinga/pluginutility.hpp" +#include "icinga/icingaapplication.hpp" +#include "base/configtype.hpp" +#include "base/objectlock.hpp" +#include "base/logger.hpp" +#include "base/convert.hpp" +#include "base/application.hpp" +#include "base/utility.hpp" +#include "base/exception.hpp" +#include "base/context.hpp" +#include "base/statsfunction.hpp" +#include + +using namespace icinga; + +REGISTER_TYPE(CheckResultReader); + +REGISTER_STATSFUNCTION(CheckResultReader, &CheckResultReader::StatsFunc); + +void CheckResultReader::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) +{ + DictionaryData nodes; + + for (const CheckResultReader::Ptr& checkresultreader : ConfigType::GetObjectsByType()) { + nodes.emplace_back(checkresultreader->GetName(), 1); //add more stats + } + + status->Set("checkresultreader", new Dictionary(std::move(nodes))); +} + +/** + * @threadsafety Always. + */ +void CheckResultReader::Start(bool runtimeCreated) +{ + ObjectImpl::Start(runtimeCreated); + + Log(LogInformation, "CheckResultReader") + << "'" << GetName() << "' started."; + + Log(LogWarning, "CheckResultReader") + << "This feature is DEPRECATED and may be removed in future releases. Check the roadmap at https://github.com/Icinga/icinga2/milestones"; + +#ifndef _WIN32 + m_ReadTimer = new Timer(); + m_ReadTimer->OnTimerExpired.connect([this](const Timer * const&) { ReadTimerHandler(); }); + m_ReadTimer->SetInterval(5); + m_ReadTimer->Start(); +#endif /* _WIN32 */ +} + +/** + * @threadsafety Always. + */ +void CheckResultReader::Stop(bool runtimeRemoved) +{ + Log(LogInformation, "CheckResultReader") + << "'" << GetName() << "' stopped."; + + ObjectImpl::Stop(runtimeRemoved); +} + +/** + * @threadsafety Always. + */ +void CheckResultReader::ReadTimerHandler() const +{ + CONTEXT("Processing check result files in '" + GetSpoolDir() + "'"); + + Utility::Glob(GetSpoolDir() + "/c??????.ok", [this](const String& path) { ProcessCheckResultFile(path); }, GlobFile); +} + +void CheckResultReader::ProcessCheckResultFile(const String& path) const +{ + CONTEXT("Processing check result file '" + path + "'"); + + String crfile = String(path.Begin(), path.End() - 3); /* Remove the ".ok" extension. */ + + std::ifstream fp; + fp.exceptions(std::ifstream::badbit); + fp.open(crfile.CStr()); + + std::map attrs; + + while (fp.good()) { + std::string line; + std::getline(fp, line); + + if (line.empty() || line[0] == '#') + continue; /* Ignore comments and empty lines. */ + + size_t pos = line.find_first_of('='); + + if (pos == std::string::npos) + continue; /* Ignore invalid lines. */ + + String key = line.substr(0, pos); + String value = line.substr(pos + 1); + + attrs[key] = value; + } + + /* Remove the checkresult files. */ + Utility::Remove(path); + + Utility::Remove(crfile); + + Checkable::Ptr checkable; + + Host::Ptr host = Host::GetByName(attrs["host_name"]); + + if (!host) { + Log(LogWarning, "CheckResultReader") + << "Ignoring checkresult file for host '" << attrs["host_name"] << "': Host does not exist."; + + return; + } + + if (attrs.find("service_description") != attrs.end()) { + Service::Ptr service = host->GetServiceByShortName(attrs["service_description"]); + + if (!service) { + Log(LogWarning, "CheckResultReader") + << "Ignoring checkresult file for host '" << attrs["host_name"] + << "', service '" << attrs["service_description"] << "': Service does not exist."; + + return; + } + + checkable = service; + } else + checkable = host; + + CheckResult::Ptr result = new CheckResult(); + String output = CompatUtility::UnEscapeString(attrs["output"]); + std::pair co = PluginUtility::ParseCheckOutput(output); + result->SetOutput(co.first); + result->SetPerformanceData(PluginUtility::SplitPerfdata(co.second)); + result->SetState(PluginUtility::ExitStatusToState(Convert::ToLong(attrs["return_code"]))); + + if (attrs.find("start_time") != attrs.end()) + result->SetExecutionStart(Convert::ToDouble(attrs["start_time"])); + else + result->SetExecutionStart(Utility::GetTime()); + + if (attrs.find("finish_time") != attrs.end()) + result->SetExecutionEnd(Convert::ToDouble(attrs["finish_time"])); + else + result->SetExecutionEnd(result->GetExecutionStart()); + + checkable->ProcessCheckResult(result); + + Log(LogDebug, "CheckResultReader") + << "Processed checkresult file for object '" << checkable->GetName() << "'"; + + /* Reschedule the next check. The side effect of this is that for as long + * as we receive check result files for a host/service we won't execute any + * active checks. */ + checkable->SetNextCheck(Utility::GetTime() + checkable->GetCheckInterval()); +} diff --git a/lib/compat/checkresultreader.hpp b/lib/compat/checkresultreader.hpp new file mode 100644 index 0000000..6cd28e3 --- /dev/null +++ b/lib/compat/checkresultreader.hpp @@ -0,0 +1,38 @@ +/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */ + +#ifndef CHECKRESULTREADER_H +#define CHECKRESULTREADER_H + +#include "compat/checkresultreader-ti.hpp" +#include "base/timer.hpp" +#include + +namespace icinga +{ + +/** + * An Icinga checkresult reader. + * + * @ingroup compat + */ +class CheckResultReader final : public ObjectImpl +{ +public: + DECLARE_OBJECT(CheckResultReader); + DECLARE_OBJECTNAME(CheckResultReader); + + static void StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata); + +protected: + void Start(bool runtimeCreated) override; + void Stop(bool runtimeRemoved) override; + +private: + Timer::Ptr m_ReadTimer; + void ReadTimerHandler() const; + void ProcessCheckResultFile(const String& path) const; +}; + +} + +#endif /* CHECKRESULTREADER_H */ diff --git a/lib/compat/checkresultreader.ti b/lib/compat/checkresultreader.ti new file mode 100644 index 0000000..0132818 --- /dev/null +++ b/lib/compat/checkresultreader.ti @@ -0,0 +1,20 @@ +/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */ + +#include "base/configobject.hpp" +#include "base/application.hpp" + +library compat; + +namespace icinga +{ + +class CheckResultReader : ConfigObject +{ + activation_priority 100; + + [config] String spool_dir { + default {{{ return Configuration::DataDir + "/spool/checkresults/"; }}} + }; +}; + +} diff --git a/lib/compat/compatlogger.cpp b/lib/compat/compatlogger.cpp new file mode 100644 index 0000000..5427298 --- /dev/null +++ b/lib/compat/compatlogger.cpp @@ -0,0 +1,612 @@ +/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */ + +#include "compat/compatlogger.hpp" +#include "compat/compatlogger-ti.cpp" +#include "icinga/service.hpp" +#include "icinga/checkcommand.hpp" +#include "icinga/eventcommand.hpp" +#include "icinga/notification.hpp" +#include "icinga/macroprocessor.hpp" +#include "icinga/externalcommandprocessor.hpp" +#include "icinga/compatutility.hpp" +#include "base/configtype.hpp" +#include "base/objectlock.hpp" +#include "base/logger.hpp" +#include "base/exception.hpp" +#include "base/convert.hpp" +#include "base/application.hpp" +#include "base/utility.hpp" +#include "base/statsfunction.hpp" +#include + +using namespace icinga; + +REGISTER_TYPE(CompatLogger); + +REGISTER_STATSFUNCTION(CompatLogger, &CompatLogger::StatsFunc); + +void CompatLogger::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) +{ + DictionaryData nodes; + + for (const CompatLogger::Ptr& compat_logger : ConfigType::GetObjectsByType()) { + nodes.emplace_back(compat_logger->GetName(), 1); // add more stats + } + + status->Set("compatlogger", new Dictionary(std::move(nodes))); +} + +/** + * @threadsafety Always. + */ +void CompatLogger::Start(bool runtimeCreated) +{ + ObjectImpl::Start(runtimeCreated); + + Log(LogInformation, "CompatLogger") + << "'" << GetName() << "' started."; + + Log(LogWarning, "CompatLogger") + << "This feature is DEPRECATED and may be removed in future releases. Check the roadmap at https://github.com/Icinga/icinga2/milestones"; + + Checkable::OnNewCheckResult.connect([this](const Checkable::Ptr& checkable, const CheckResult::Ptr& cr, const MessageOrigin::Ptr&) { + CheckResultHandler(checkable, cr); + }); + Checkable::OnNotificationSentToUser.connect([this](const Notification::Ptr& notification, const Checkable::Ptr& checkable, + const User::Ptr& user, const NotificationType& type, const CheckResult::Ptr& cr, const String& author, + const String& commentText, const String& commandName, const MessageOrigin::Ptr&) { + NotificationSentHandler(notification, checkable, user, type, cr, author, commentText, commandName); + }); + + Downtime::OnDowntimeTriggered.connect([this](const Downtime::Ptr& downtime) { TriggerDowntimeHandler(downtime); }); + Downtime::OnDowntimeRemoved.connect([this](const Downtime::Ptr& downtime) { RemoveDowntimeHandler(downtime); }); + Checkable::OnEventCommandExecuted.connect([this](const Checkable::Ptr& checkable) { EventCommandHandler(checkable); }); + + Checkable::OnFlappingChanged.connect([this](const Checkable::Ptr& checkable, const Value&) { FlappingChangedHandler(checkable); }); + Checkable::OnEnableFlappingChanged.connect([this](const Checkable::Ptr& checkable, const Value&) { EnableFlappingChangedHandler(checkable); }); + + ExternalCommandProcessor::OnNewExternalCommand.connect([this](double, const String& command, const std::vector& arguments) { + ExternalCommandHandler(command, arguments); + }); + + m_RotationTimer = new Timer(); + m_RotationTimer->OnTimerExpired.connect([this](const Timer * const&) { RotationTimerHandler(); }); + m_RotationTimer->Start(); + + ReopenFile(false); + ScheduleNextRotation(); +} + +/** + * @threadsafety Always. + */ +void CompatLogger::Stop(bool runtimeRemoved) +{ + Log(LogInformation, "CompatLogger") + << "'" << GetName() << "' stopped."; + + ObjectImpl::Stop(runtimeRemoved); +} + +/** + * @threadsafety Always. + */ +void CompatLogger::CheckResultHandler(const Checkable::Ptr& checkable, const CheckResult::Ptr &cr) +{ + Host::Ptr host; + Service::Ptr service; + tie(host, service) = GetHostService(checkable); + + Dictionary::Ptr vars_after = cr->GetVarsAfter(); + + long state_after = vars_after->Get("state"); + long stateType_after = vars_after->Get("state_type"); + long attempt_after = vars_after->Get("attempt"); + bool reachable_after = vars_after->Get("reachable"); + + Dictionary::Ptr vars_before = cr->GetVarsBefore(); + + if (vars_before) { + long state_before = vars_before->Get("state"); + long stateType_before = vars_before->Get("state_type"); + long attempt_before = vars_before->Get("attempt"); + bool reachable_before = vars_before->Get("reachable"); + + if (state_before == state_after && stateType_before == stateType_after && + attempt_before == attempt_after && reachable_before == reachable_after) + return; /* Nothing changed, ignore this checkresult. */ + } + + String output; + if (cr) + output = CompatUtility::GetCheckResultOutput(cr); + + std::ostringstream msgbuf; + + if (service) { + msgbuf << "SERVICE ALERT: " + << host->GetName() << ";" + << service->GetShortName() << ";" + << Service::StateToString(service->GetState()) << ";" + << Service::StateTypeToString(service->GetStateType()) << ";" + << attempt_after << ";" + << output << "" + << ""; + } else { + String state = Host::StateToString(Host::CalculateState(static_cast(state_after))); + + msgbuf << "HOST ALERT: " + << host->GetName() << ";" + << GetHostStateString(host) << ";" + << Host::StateTypeToString(host->GetStateType()) << ";" + << attempt_after << ";" + << output << "" + << ""; + + } + + { + ObjectLock olock(this); + WriteLine(msgbuf.str()); + Flush(); + } +} + +/** + * @threadsafety Always. + */ +void CompatLogger::TriggerDowntimeHandler(const Downtime::Ptr& downtime) +{ + Host::Ptr host; + Service::Ptr service; + tie(host, service) = GetHostService(downtime->GetCheckable()); + + if (!downtime) + return; + + std::ostringstream msgbuf; + + if (service) { + msgbuf << "SERVICE DOWNTIME ALERT: " + << host->GetName() << ";" + << service->GetShortName() << ";" + << "STARTED" << "; " + << "Checkable has entered a period of scheduled downtime." + << ""; + } else { + msgbuf << "HOST DOWNTIME ALERT: " + << host->GetName() << ";" + << "STARTED" << "; " + << "Checkable has entered a period of scheduled downtime." + << ""; + } + + { + ObjectLock oLock(this); + WriteLine(msgbuf.str()); + Flush(); + } +} + +/** + * @threadsafety Always. + */ +void CompatLogger::RemoveDowntimeHandler(const Downtime::Ptr& downtime) +{ + Host::Ptr host; + Service::Ptr service; + tie(host, service) = GetHostService(downtime->GetCheckable()); + + if (!downtime) + return; + + String downtime_output; + String downtime_state_str; + + if (downtime->GetWasCancelled()) { + downtime_output = "Scheduled downtime for service has been cancelled."; + downtime_state_str = "CANCELLED"; + } else { + downtime_output = "Checkable has exited from a period of scheduled downtime."; + downtime_state_str = "STOPPED"; + } + + std::ostringstream msgbuf; + + if (service) { + msgbuf << "SERVICE DOWNTIME ALERT: " + << host->GetName() << ";" + << service->GetShortName() << ";" + << downtime_state_str << "; " + << downtime_output + << ""; + } else { + msgbuf << "HOST DOWNTIME ALERT: " + << host->GetName() << ";" + << downtime_state_str << "; " + << downtime_output + << ""; + } + + { + ObjectLock oLock(this); + WriteLine(msgbuf.str()); + Flush(); + } +} + +/** + * @threadsafety Always. + */ +void CompatLogger::NotificationSentHandler(const Notification::Ptr& notification, const Checkable::Ptr& checkable, + const User::Ptr& user, NotificationType notification_type, CheckResult::Ptr const& cr, + const String& author, const String& comment_text, const String& command_name) +{ + Host::Ptr host; + Service::Ptr service; + tie(host, service) = GetHostService(checkable); + + String notification_type_str = Notification::NotificationTypeToStringCompat(notification_type); + + /* override problem notifications with their current state string */ + if (notification_type == NotificationProblem) { + if (service) + notification_type_str = Service::StateToString(service->GetState()); + else + notification_type_str = GetHostStateString(host); + } + + String author_comment = ""; + if (notification_type == NotificationCustom || notification_type == NotificationAcknowledgement) { + author_comment = author + ";" + comment_text; + } + + if (!cr) + return; + + String output; + if (cr) + output = CompatUtility::GetCheckResultOutput(cr); + + std::ostringstream msgbuf; + + if (service) { + msgbuf << "SERVICE NOTIFICATION: " + << user->GetName() << ";" + << host->GetName() << ";" + << service->GetShortName() << ";" + << notification_type_str << ";" + << command_name << ";" + << output << ";" + << author_comment + << ""; + } else { + msgbuf << "HOST NOTIFICATION: " + << user->GetName() << ";" + << host->GetName() << ";" + << notification_type_str << " " + << "(" << GetHostStateString(host) << ");" + << command_name << ";" + << output << ";" + << author_comment + << ""; + } + + { + ObjectLock oLock(this); + WriteLine(msgbuf.str()); + Flush(); + } +} + +/** + * @threadsafety Always. + */ +void CompatLogger::FlappingChangedHandler(const Checkable::Ptr& checkable) +{ + Host::Ptr host; + Service::Ptr service; + tie(host, service) = GetHostService(checkable); + + String flapping_state_str; + String flapping_output; + + if (checkable->IsFlapping()) { + flapping_output = "Checkable appears to have started flapping (" + Convert::ToString(checkable->GetFlappingCurrent()) + "% change >= " + Convert::ToString(checkable->GetFlappingThresholdHigh()) + "% threshold)"; + flapping_state_str = "STARTED"; + } else { + flapping_output = "Checkable appears to have stopped flapping (" + Convert::ToString(checkable->GetFlappingCurrent()) + "% change < " + Convert::ToString(checkable->GetFlappingThresholdLow()) + "% threshold)"; + flapping_state_str = "STOPPED"; + } + + std::ostringstream msgbuf; + + if (service) { + msgbuf << "SERVICE FLAPPING ALERT: " + << host->GetName() << ";" + << service->GetShortName() << ";" + << flapping_state_str << "; " + << flapping_output + << ""; + } else { + msgbuf << "HOST FLAPPING ALERT: " + << host->GetName() << ";" + << flapping_state_str << "; " + << flapping_output + << ""; + } + + { + ObjectLock oLock(this); + WriteLine(msgbuf.str()); + Flush(); + } +} + +void CompatLogger::EnableFlappingChangedHandler(const Checkable::Ptr& checkable) +{ + Host::Ptr host; + Service::Ptr service; + tie(host, service) = GetHostService(checkable); + + if (checkable->GetEnableFlapping()) + return; + + String flapping_output = "Flap detection has been disabled"; + String flapping_state_str = "DISABLED"; + + std::ostringstream msgbuf; + + if (service) { + msgbuf << "SERVICE FLAPPING ALERT: " + << host->GetName() << ";" + << service->GetShortName() << ";" + << flapping_state_str << "; " + << flapping_output + << ""; + } else { + msgbuf << "HOST FLAPPING ALERT: " + << host->GetName() << ";" + << flapping_state_str << "; " + << flapping_output + << ""; + } + + { + ObjectLock oLock(this); + WriteLine(msgbuf.str()); + Flush(); + } +} + +void CompatLogger::ExternalCommandHandler(const String& command, const std::vector& arguments) +{ + std::ostringstream msgbuf; + msgbuf << "EXTERNAL COMMAND: " + << command << ";" + << boost::algorithm::join(arguments, ";") + << ""; + + { + ObjectLock oLock(this); + WriteLine(msgbuf.str()); + Flush(); + } +} + +void CompatLogger::EventCommandHandler(const Checkable::Ptr& checkable) +{ + Host::Ptr host; + Service::Ptr service; + tie(host, service) = GetHostService(checkable); + + EventCommand::Ptr event_command = checkable->GetEventCommand(); + String event_command_name = event_command->GetName(); + long current_attempt = checkable->GetCheckAttempt(); + + std::ostringstream msgbuf; + + if (service) { + msgbuf << "SERVICE EVENT HANDLER: " + << host->GetName() << ";" + << service->GetShortName() << ";" + << Service::StateToString(service->GetState()) << ";" + << Service::StateTypeToString(service->GetStateType()) << ";" + << current_attempt << ";" + << event_command_name; + } else { + msgbuf << "HOST EVENT HANDLER: " + << host->GetName() << ";" + << GetHostStateString(host) << ";" + << Host::StateTypeToString(host->GetStateType()) << ";" + << current_attempt << ";" + << event_command_name; + } + + { + ObjectLock oLock(this); + WriteLine(msgbuf.str()); + Flush(); + } +} + +String CompatLogger::GetHostStateString(const Host::Ptr& host) +{ + if (host->GetState() != HostUp && !host->IsReachable()) + return "UNREACHABLE"; /* hardcoded compat state */ + + return Host::StateToString(host->GetState()); +} + +void CompatLogger::WriteLine(const String& line) +{ + ASSERT(OwnsLock()); + + if (!m_OutputFile.good()) + return; + + m_OutputFile << "[" << (long)Utility::GetTime() << "] " << line << "\n"; +} + +void CompatLogger::Flush() +{ + ASSERT(OwnsLock()); + + if (!m_OutputFile.good()) + return; + + m_OutputFile << std::flush; +} + +/** + * @threadsafety Always. + */ +void CompatLogger::ReopenFile(bool rotate) +{ + ObjectLock olock(this); + + String tempFile = GetLogDir() + "/icinga.log"; + + if (m_OutputFile) { + m_OutputFile.close(); + + if (rotate) { + String archiveFile = GetLogDir() + "/archives/icinga-" + Utility::FormatDateTime("%m-%d-%Y-%H", Utility::GetTime()) + ".log"; + + Log(LogNotice, "CompatLogger") + << "Rotating compat log file '" << tempFile << "' -> '" << archiveFile << "'"; + + (void) rename(tempFile.CStr(), archiveFile.CStr()); + } + } + + m_OutputFile.open(tempFile.CStr(), std::ofstream::app); + + if (!m_OutputFile) { + Log(LogWarning, "CompatLogger") + << "Could not open compat log file '" << tempFile << "' for writing. Log output will be lost."; + + return; + } + + WriteLine("LOG ROTATION: " + GetRotationMethod()); + WriteLine("LOG VERSION: 2.0"); + + for (const Host::Ptr& host : ConfigType::GetObjectsByType()) { + String output; + CheckResult::Ptr cr = host->GetLastCheckResult(); + + if (cr) + output = CompatUtility::GetCheckResultOutput(cr); + + std::ostringstream msgbuf; + msgbuf << "CURRENT HOST STATE: " + << host->GetName() << ";" + << GetHostStateString(host) << ";" + << Host::StateTypeToString(host->GetStateType()) << ";" + << host->GetCheckAttempt() << ";" + << output << ""; + + WriteLine(msgbuf.str()); + } + + for (const Service::Ptr& service : ConfigType::GetObjectsByType()) { + Host::Ptr host = service->GetHost(); + + String output; + CheckResult::Ptr cr = service->GetLastCheckResult(); + + if (cr) + output = CompatUtility::GetCheckResultOutput(cr); + + std::ostringstream msgbuf; + msgbuf << "CURRENT SERVICE STATE: " + << host->GetName() << ";" + << service->GetShortName() << ";" + << Service::StateToString(service->GetState()) << ";" + << Service::StateTypeToString(service->GetStateType()) << ";" + << service->GetCheckAttempt() << ";" + << output << ""; + + WriteLine(msgbuf.str()); + } + + Flush(); +} + +void CompatLogger::ScheduleNextRotation() +{ + auto now = (time_t)Utility::GetTime(); + String method = GetRotationMethod(); + + tm tmthen; + +#ifdef _MSC_VER + tm *temp = localtime(&now); + + if (!temp) { + BOOST_THROW_EXCEPTION(posix_error() + << boost::errinfo_api_function("localtime") + << boost::errinfo_errno(errno)); + } + + tmthen = *temp; +#else /* _MSC_VER */ + if (!localtime_r(&now, &tmthen)) { + BOOST_THROW_EXCEPTION(posix_error() + << boost::errinfo_api_function("localtime_r") + << boost::errinfo_errno(errno)); + } +#endif /* _MSC_VER */ + + tmthen.tm_min = 0; + tmthen.tm_sec = 0; + + if (method == "HOURLY") { + tmthen.tm_hour++; + } else if (method == "DAILY") { + tmthen.tm_mday++; + tmthen.tm_hour = 0; + } else if (method == "WEEKLY") { + tmthen.tm_mday += 7 - tmthen.tm_wday; + tmthen.tm_hour = 0; + } else if (method == "MONTHLY") { + tmthen.tm_mon++; + tmthen.tm_mday = 1; + tmthen.tm_hour = 0; + } + + time_t ts = mktime(&tmthen); + + Log(LogNotice, "CompatLogger") + << "Rescheduling rotation timer for compat log '" + << GetName() << "' to '" << Utility::FormatDateTime("%Y/%m/%d %H:%M:%S %z", ts) << "'"; + + m_RotationTimer->Reschedule(ts); +} + +/** + * @threadsafety Always. + */ +void CompatLogger::RotationTimerHandler() +{ + try { + ReopenFile(true); + } catch (...) { + ScheduleNextRotation(); + + throw; + } + + ScheduleNextRotation(); +} + +void CompatLogger::ValidateRotationMethod(const Lazy& lvalue, const ValidationUtils& utils) +{ + ObjectImpl::ValidateRotationMethod(lvalue, utils); + + if (lvalue() != "HOURLY" && lvalue() != "DAILY" && + lvalue() != "WEEKLY" && lvalue() != "MONTHLY" && lvalue() != "NONE") { + BOOST_THROW_EXCEPTION(ValidationError(this, { "rotation_method" }, "Rotation method '" + lvalue() + "' is invalid.")); + } +} diff --git a/lib/compat/compatlogger.hpp b/lib/compat/compatlogger.hpp new file mode 100644 index 0000000..9fb0b29 --- /dev/null +++ b/lib/compat/compatlogger.hpp @@ -0,0 +1,60 @@ +/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */ + +#ifndef COMPATLOGGER_H +#define COMPATLOGGER_H + +#include "compat/compatlogger-ti.hpp" +#include "icinga/service.hpp" +#include "base/timer.hpp" +#include + +namespace icinga +{ + +/** + * An Icinga compat log writer. + * + * @ingroup compat + */ +class CompatLogger final : public ObjectImpl +{ +public: + DECLARE_OBJECT(CompatLogger); + DECLARE_OBJECTNAME(CompatLogger); + + static void StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata); + + void ValidateRotationMethod(const Lazy& lvalue, const ValidationUtils& utils) override; + +protected: + void Start(bool runtimeCreated) override; + void Stop(bool runtimeRemoved) override; + +private: + void WriteLine(const String& line); + void Flush(); + + void CheckResultHandler(const Checkable::Ptr& service, const CheckResult::Ptr& cr); + void NotificationSentHandler(const Notification::Ptr& notification, const Checkable::Ptr& service, + const User::Ptr& user, NotificationType notification_type, CheckResult::Ptr const& cr, + const String& author, const String& comment_text, const String& command_name); + void FlappingChangedHandler(const Checkable::Ptr& checkable); + void EnableFlappingChangedHandler(const Checkable::Ptr& checkable); + void TriggerDowntimeHandler(const Downtime::Ptr& downtime); + void RemoveDowntimeHandler(const Downtime::Ptr& downtime); + void ExternalCommandHandler(const String& command, const std::vector& arguments); + void EventCommandHandler(const Checkable::Ptr& service); + + static String GetHostStateString(const Host::Ptr& host); + + Timer::Ptr m_RotationTimer; + void RotationTimerHandler(); + void ScheduleNextRotation(); + + std::ofstream m_OutputFile; + void ReopenFile(bool rotate); +}; + +} + +#endif /* COMPATLOGGER_H */ diff --git a/lib/compat/compatlogger.ti b/lib/compat/compatlogger.ti new file mode 100644 index 0000000..56431ec --- /dev/null +++ b/lib/compat/compatlogger.ti @@ -0,0 +1,23 @@ +/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */ + +#include "base/configobject.hpp" +#include "base/application.hpp" + +library compat; + +namespace icinga +{ + +class CompatLogger : ConfigObject +{ + activation_priority 100; + + [config] String log_dir { + default {{{ return Configuration::LogDir + "/compat"; }}} + }; + [config] String rotation_method { + default {{{ return "HOURLY"; }}} + }; +}; + +} diff --git a/lib/compat/externalcommandlistener.cpp b/lib/compat/externalcommandlistener.cpp new file mode 100644 index 0000000..b61813b --- /dev/null +++ b/lib/compat/externalcommandlistener.cpp @@ -0,0 +1,150 @@ +/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */ + +#include "compat/externalcommandlistener.hpp" +#include "compat/externalcommandlistener-ti.cpp" +#include "icinga/externalcommandprocessor.hpp" +#include "base/configtype.hpp" +#include "base/logger.hpp" +#include "base/exception.hpp" +#include "base/application.hpp" +#include "base/statsfunction.hpp" + +using namespace icinga; + +REGISTER_TYPE(ExternalCommandListener); + +REGISTER_STATSFUNCTION(ExternalCommandListener, &ExternalCommandListener::StatsFunc); + +void ExternalCommandListener::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) +{ + DictionaryData nodes; + + for (const ExternalCommandListener::Ptr& externalcommandlistener : ConfigType::GetObjectsByType()) { + nodes.emplace_back(externalcommandlistener->GetName(), 1); //add more stats + } + + status->Set("externalcommandlistener", new Dictionary(std::move(nodes))); +} + +/** + * Starts the component. + */ +void ExternalCommandListener::Start(bool runtimeCreated) +{ + ObjectImpl::Start(runtimeCreated); + + Log(LogInformation, "ExternalCommandListener") + << "'" << GetName() << "' started."; + + Log(LogWarning, "ExternalCommandListener") + << "This feature is DEPRECATED and may be removed in future releases. Check the roadmap at https://github.com/Icinga/icinga2/milestones"; +#ifndef _WIN32 + String path = GetCommandPath(); + m_CommandThread = std::thread([this, path]() { CommandPipeThread(path); }); + m_CommandThread.detach(); +#endif /* _WIN32 */ +} + +/** + * Stops the component. + */ +void ExternalCommandListener::Stop(bool runtimeRemoved) +{ + Log(LogInformation, "ExternalCommandListener") + << "'" << GetName() << "' stopped."; + + ObjectImpl::Stop(runtimeRemoved); +} + +#ifndef _WIN32 +void ExternalCommandListener::CommandPipeThread(const String& commandPath) +{ + Utility::SetThreadName("Command Pipe"); + + struct stat statbuf; + bool fifo_ok = false; + + if (lstat(commandPath.CStr(), &statbuf) >= 0) { + if (S_ISFIFO(statbuf.st_mode) && access(commandPath.CStr(), R_OK) >= 0) { + fifo_ok = true; + } else { + Utility::Remove(commandPath); + } + } + + mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP; + + if (!fifo_ok && mkfifo(commandPath.CStr(), S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) < 0) { + Log(LogCritical, "ExternalCommandListener") + << "mkfifo() for fifo path '" << commandPath << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; + return; + } + + /* mkfifo() uses umask to mask off some bits, which means we need to chmod() the + * fifo to get the right mask. */ + if (chmod(commandPath.CStr(), mode) < 0) { + Log(LogCritical, "ExternalCommandListener") + << "chmod() on fifo '" << commandPath << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; + return; + } + + for (;;) { + int fd = open(commandPath.CStr(), O_RDWR | O_NONBLOCK); + + if (fd < 0) { + Log(LogCritical, "ExternalCommandListener") + << "open() for fifo path '" << commandPath << "' failed with error code " << errno << ", \"" << Utility::FormatErrorNumber(errno) << "\""; + return; + } + + FIFO::Ptr fifo = new FIFO(); + Socket::Ptr sock = new Socket(fd); + StreamReadContext src; + + for (;;) { + sock->Poll(true, false); + + char buffer[8192]; + size_t rc; + + try { + rc = sock->Read(buffer, sizeof(buffer)); + } catch (const std::exception& ex) { + /* We have read all data. */ + if (errno == EAGAIN) + continue; + + Log(LogWarning, "ExternalCommandListener") + << "Cannot read from command pipe." << DiagnosticInformation(ex); + break; + } + + /* Empty pipe (EOF) */ + if (rc == 0) + continue; + + fifo->Write(buffer, rc); + + for (;;) { + String command; + StreamReadStatus srs = fifo->ReadLine(&command, src); + + if (srs != StatusNewItem) + break; + + try { + Log(LogInformation, "ExternalCommandListener") + << "Executing external command: " << command; + + ExternalCommandProcessor::Execute(command); + } catch (const std::exception& ex) { + Log(LogWarning, "ExternalCommandListener") + << "External command failed: " << DiagnosticInformation(ex, false); + Log(LogNotice, "ExternalCommandListener") + << "External command failed: " << DiagnosticInformation(ex, true); + } + } + } + } +} +#endif /* _WIN32 */ diff --git a/lib/compat/externalcommandlistener.hpp b/lib/compat/externalcommandlistener.hpp new file mode 100644 index 0000000..895531f --- /dev/null +++ b/lib/compat/externalcommandlistener.hpp @@ -0,0 +1,41 @@ +/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */ + +#ifndef EXTERNALCOMMANDLISTENER_H +#define EXTERNALCOMMANDLISTENER_H + +#include "compat/externalcommandlistener-ti.hpp" +#include "base/objectlock.hpp" +#include "base/timer.hpp" +#include "base/utility.hpp" +#include +#include + +namespace icinga +{ + +/** + * @ingroup compat + */ +class ExternalCommandListener final : public ObjectImpl +{ +public: + DECLARE_OBJECT(ExternalCommandListener); + DECLARE_OBJECTNAME(ExternalCommandListener); + + static void StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata); + +protected: + void Start(bool runtimeCreated) override; + void Stop(bool runtimeRemoved) override; + +private: +#ifndef _WIN32 + std::thread m_CommandThread; + + void CommandPipeThread(const String& commandPath); +#endif /* _WIN32 */ +}; + +} + +#endif /* EXTERNALCOMMANDLISTENER_H */ diff --git a/lib/compat/externalcommandlistener.ti b/lib/compat/externalcommandlistener.ti new file mode 100644 index 0000000..5b52944 --- /dev/null +++ b/lib/compat/externalcommandlistener.ti @@ -0,0 +1,20 @@ +/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */ + +#include "base/configobject.hpp" +#include "base/application.hpp" + +library compat; + +namespace icinga +{ + +class ExternalCommandListener : ConfigObject +{ + activation_priority 100; + + [config] String command_path { + default {{{ return Configuration::InitRunDir + "/cmd/icinga2.cmd"; }}} + }; +}; + +} diff --git a/lib/compat/statusdatawriter.cpp b/lib/compat/statusdatawriter.cpp new file mode 100644 index 0000000..2c6a666 --- /dev/null +++ b/lib/compat/statusdatawriter.cpp @@ -0,0 +1,897 @@ +/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */ + +#include "compat/statusdatawriter.hpp" +#include "compat/statusdatawriter-ti.cpp" +#include "icinga/icingaapplication.hpp" +#include "icinga/cib.hpp" +#include "icinga/hostgroup.hpp" +#include "icinga/servicegroup.hpp" +#include "icinga/checkcommand.hpp" +#include "icinga/eventcommand.hpp" +#include "icinga/timeperiod.hpp" +#include "icinga/notificationcommand.hpp" +#include "icinga/compatutility.hpp" +#include "icinga/pluginutility.hpp" +#include "icinga/dependency.hpp" +#include "base/configtype.hpp" +#include "base/objectlock.hpp" +#include "base/json.hpp" +#include "base/convert.hpp" +#include "base/logger.hpp" +#include "base/exception.hpp" +#include "base/application.hpp" +#include "base/context.hpp" +#include "base/statsfunction.hpp" +#include +#include +#include + +using namespace icinga; + +REGISTER_TYPE(StatusDataWriter); + +REGISTER_STATSFUNCTION(StatusDataWriter, &StatusDataWriter::StatsFunc); + +void StatusDataWriter::StatsFunc(const Dictionary::Ptr& status, const Array::Ptr&) +{ + DictionaryData nodes; + + for (const StatusDataWriter::Ptr& statusdatawriter : ConfigType::GetObjectsByType()) { + nodes.emplace_back(statusdatawriter->GetName(), 1); //add more stats + } + + status->Set("statusdatawriter", new Dictionary(std::move(nodes))); +} + +/** + * Hint: The reason why we're using "\n" rather than std::endl is because + * std::endl also _flushes_ the output stream which severely degrades + * performance (see https://stackoverflow.com/questions/213907/c-stdendl-vs-n). + */ + +/** + * Starts the component. + */ +void StatusDataWriter::Start(bool runtimeCreated) +{ + ObjectImpl::Start(runtimeCreated); + + Log(LogInformation, "StatusDataWriter") + << "'" << GetName() << "' started."; + + Log(LogWarning, "StatusDataWriter") + << "This feature is DEPRECATED and may be removed in future releases. Check the roadmap at https://github.com/Icinga/icinga2/milestones"; + + m_ObjectsCacheOutdated = true; + + m_StatusTimer = new Timer(); + m_StatusTimer->SetInterval(GetUpdateInterval()); + m_StatusTimer->OnTimerExpired.connect([this](const Timer * const&){ StatusTimerHandler(); }); + m_StatusTimer->Start(); + m_StatusTimer->Reschedule(0); + + ConfigObject::OnVersionChanged.connect([this](const ConfigObject::Ptr&, const Value&) { ObjectHandler(); }); + ConfigObject::OnActiveChanged.connect([this](const ConfigObject::Ptr&, const Value&) { ObjectHandler(); }); +} + +/** + * Stops the component. + */ +void StatusDataWriter::Stop(bool runtimeRemoved) +{ + Log(LogInformation, "StatusDataWriter") + << "'" << GetName() << "' stopped."; + + ObjectImpl::Stop(runtimeRemoved); +} + +void StatusDataWriter::DumpComments(std::ostream& fp, const Checkable::Ptr& checkable) +{ + Host::Ptr host; + Service::Ptr service; + tie(host, service) = GetHostService(checkable); + + for (const Comment::Ptr& comment : checkable->GetComments()) { + if (comment->IsExpired()) + continue; + + if (service) + fp << "servicecomment {" << "\n" + << "\t" << "service_description=" << service->GetShortName() << "\n"; + else + fp << "hostcomment {" << "\n"; + + fp << "\t" "host_name=" << host->GetName() << "\n" + "\t" "comment_id=" << comment->GetLegacyId() << "\n" + "\t" "entry_time=" << comment->GetEntryTime() << "\n" + "\t" "entry_type=" << comment->GetEntryType() << "\n" + "\t" "persistent=" "1" "\n" + "\t" "author=" << comment->GetAuthor() << "\n" + "\t" "comment_data=" << comment->GetText() << "\n" + "\t" "expires=" << (comment->GetExpireTime() != 0 ? 1 : 0) << "\n" + "\t" "expire_time=" << comment->GetExpireTime() << "\n" + "\t" "}" "\n" + "\n"; + } +} + +void StatusDataWriter::DumpTimePeriod(std::ostream& fp, const TimePeriod::Ptr& tp) +{ + fp << "define timeperiod {" "\n" + "\t" "timeperiod_name" "\t" << tp->GetName() << "\n" + "\t" "alias" "\t" << tp->GetName() << "\n"; + + Dictionary::Ptr ranges = tp->GetRanges(); + + if (ranges) { + ObjectLock olock(ranges); + for (const Dictionary::Pair& kv : ranges) { + fp << "\t" << kv.first << "\t" << kv.second << "\n"; + } + } + + fp << "\t" "}" "\n" "\n"; +} + +void StatusDataWriter::DumpCommand(std::ostream& fp, const Command::Ptr& command) +{ + fp << "define command {" "\n" + "\t" "command_name\t"; + + fp << CompatUtility::GetCommandName(command) << "\n"; + + fp << "\t" "command_line" "\t" << CompatUtility::GetCommandLine(command); + + fp << "\n"; + + DumpCustomAttributes(fp, command); + + fp << "\n" "\t" "}" "\n" "\n"; +} + +void StatusDataWriter::DumpDowntimes(std::ostream& fp, const Checkable::Ptr& checkable) +{ + Host::Ptr host; + Service::Ptr service; + tie(host, service) = GetHostService(checkable); + + for (const Downtime::Ptr& downtime : checkable->GetDowntimes()) { + if (downtime->IsExpired()) + continue; + + if (service) + fp << "servicedowntime {" << "\n" + "\t" "service_description=" << service->GetShortName() << "\n"; + else + fp << "hostdowntime {" "\n"; + + Downtime::Ptr triggeredByObj = Downtime::GetByName(downtime->GetTriggeredBy()); + int triggeredByLegacy = 0; + if (triggeredByObj) + triggeredByLegacy = triggeredByObj->GetLegacyId(); + + fp << "\t" << "host_name=" << host->GetName() << "\n" + "\t" "downtime_id=" << downtime->GetLegacyId() << "\n" + "\t" "entry_time=" << downtime->GetEntryTime() << "\n" + "\t" "start_time=" << downtime->GetStartTime() << "\n" + "\t" "end_time=" << downtime->GetEndTime() << "\n" + "\t" "triggered_by=" << triggeredByLegacy << "\n" + "\t" "fixed=" << static_cast(downtime->GetFixed()) << "\n" + "\t" "duration=" << static_cast(downtime->GetDuration()) << "\n" + "\t" "is_in_effect=" << (downtime->IsInEffect() ? 1 : 0) << "\n" + "\t" "author=" << downtime->GetAuthor() << "\n" + "\t" "comment=" << downtime->GetComment() << "\n" + "\t" "trigger_time=" << downtime->GetTriggerTime() << "\n" + "\t" "}" "\n" + "\n"; + } +} + +void StatusDataWriter::DumpHostStatus(std::ostream& fp, const Host::Ptr& host) +{ + fp << "hoststatus {" "\n" "\t" "host_name=" << host->GetName() << "\n"; + + { + ObjectLock olock(host); + DumpCheckableStatusAttrs(fp, host); + } + + /* ugly but cgis parse only that */ + fp << "\t" "last_time_up=" << host->GetLastStateUp() << "\n" + "\t" "last_time_down=" << host->GetLastStateDown() << "\n" + "\t" "last_time_unreachable=" << host->GetLastStateUnreachable() << "\n"; + + fp << "\t" "}" "\n" "\n"; + + DumpDowntimes(fp, host); + DumpComments(fp, host); +} + +void StatusDataWriter::DumpHostObject(std::ostream& fp, const Host::Ptr& host) +{ + String notes = host->GetNotes(); + String notes_url = host->GetNotesUrl(); + String action_url = host->GetActionUrl(); + String icon_image = host->GetIconImage(); + String icon_image_alt = host->GetIconImageAlt(); + String display_name = host->GetDisplayName(); + String address = host->GetAddress(); + String address6 = host->GetAddress6(); + + fp << "define host {" "\n" + "\t" "host_name" "\t" << host->GetName() << "\n"; + if (!display_name.IsEmpty()) { + fp << "\t" "display_name" "\t" << host->GetDisplayName() << "\n" + "\t" "alias" "\t" << host->GetDisplayName() << "\n"; + } + if (!address.IsEmpty()) + fp << "\t" "address" "\t" << address << "\n"; + if (!address6.IsEmpty()) + fp << "\t" "address6" "\t" << address6 << "\n"; + if (!notes.IsEmpty()) + fp << "\t" "notes" "\t" << notes << "\n"; + if (!notes_url.IsEmpty()) + fp << "\t" "notes_url" "\t" << notes_url << "\n"; + if (!action_url.IsEmpty()) + fp << "\t" "action_url" "\t" << action_url << "\n"; + if (!icon_image.IsEmpty()) + fp << "\t" "icon_image" "\t" << icon_image << "\n"; + if (!icon_image_alt.IsEmpty()) + fp << "\t" "icon_image_alt" "\t" << icon_image_alt << "\n"; + + std::set parents = host->GetParents(); + + if (!parents.empty()) { + fp << "\t" "parents" "\t"; + DumpNameList(fp, parents); + fp << "\n"; + } + + ObjectLock olock(host); + + fp << "\t" "check_interval" "\t" << (host->GetCheckInterval() / 60.0) << "\n" + "\t" "retry_interval" "\t" << (host->GetRetryInterval() / 60.0) << "\n" + "\t" "max_check_attempts" "\t" << host->GetMaxCheckAttempts() << "\n" + "\t" "active_checks_enabled" "\t" << Convert::ToLong(host->GetEnableActiveChecks()) << "\n" + "\t" "passive_checks_enabled" "\t" << Convert::ToLong(host->GetEnablePassiveChecks()) << "\n" + "\t" "notifications_enabled" "\t" << Convert::ToLong(host->GetEnableNotifications()) << "\n" + "\t" "notification_options" "\t" << GetNotificationOptions(host) << "\n" + "\t" "notification_interval" "\t" << CompatUtility::GetCheckableNotificationNotificationInterval(host) << "\n" + "\t" "event_handler_enabled" "\t" << Convert::ToLong(host->GetEnableEventHandler()) << "\n"; + + CheckCommand::Ptr checkcommand = host->GetCheckCommand(); + if (checkcommand) + fp << "\t" "check_command" "\t" << CompatUtility::GetCommandName(checkcommand) << "!" << CompatUtility::GetCheckableCommandArgs(host) << "\n"; + + EventCommand::Ptr eventcommand = host->GetEventCommand(); + if (eventcommand && host->GetEnableEventHandler()) + fp << "\t" "event_handler" "\t" << CompatUtility::GetCommandName(eventcommand) << "\n"; + + TimePeriod::Ptr checkPeriod = host->GetCheckPeriod(); + if (checkPeriod) + fp << "\t" "check_period" "\t" << checkPeriod->GetName() << "\n"; + + fp << "\t" "contacts" "\t"; + DumpNameList(fp, CompatUtility::GetCheckableNotificationUsers(host)); + fp << "\n"; + + fp << "\t" "contact_groups" "\t"; + DumpNameList(fp, CompatUtility::GetCheckableNotificationUserGroups(host)); + fp << "\n"; + + fp << "\t" << "initial_state" "\t" "o" "\n" + "\t" "low_flap_threshold" "\t" << host->GetFlappingThresholdLow() << "\n" + "\t" "high_flap_threshold" "\t" << host->GetFlappingThresholdHigh() << "\n" + "\t" "process_perf_data" "\t" << Convert::ToLong(host->GetEnablePerfdata()) << "\n" + "\t" "check_freshness" "\t" "1" "\n"; + + fp << "\t" "host_groups" "\t"; + bool first = true; + + Array::Ptr groups = host->GetGroups(); + + if (groups) { + ObjectLock olock(groups); + + for (const String& name : groups) { + HostGroup::Ptr hg = HostGroup::GetByName(name); + + if (hg) { + if (!first) + fp << ","; + else + first = false; + + fp << hg->GetName(); + } + } + } + + fp << "\n"; + + DumpCustomAttributes(fp, host); + + fp << "\t" "}" "\n" "\n"; +} + +void StatusDataWriter::DumpCheckableStatusAttrs(std::ostream& fp, const Checkable::Ptr& checkable) +{ + CheckResult::Ptr cr = checkable->GetLastCheckResult(); + + EventCommand::Ptr eventcommand = checkable->GetEventCommand(); + CheckCommand::Ptr checkcommand = checkable->GetCheckCommand(); + + fp << "\t" << "check_command=" << CompatUtility::GetCommandName(checkcommand) << "!" << CompatUtility::GetCheckableCommandArgs(checkable) << "\n" + "\t" "event_handler=" << CompatUtility::GetCommandName(eventcommand) << "\n" + "\t" "check_interval=" << (checkable->GetCheckInterval() / 60.0) << "\n" + "\t" "retry_interval=" << (checkable->GetRetryInterval() / 60.0) << "\n" + "\t" "has_been_checked=" << Convert::ToLong(checkable->HasBeenChecked()) << "\n" + "\t" "should_be_scheduled=" << checkable->GetEnableActiveChecks() << "\n" + "\t" "event_handler_enabled=" << Convert::ToLong(checkable->GetEnableEventHandler()) << "\n"; + + TimePeriod::Ptr checkPeriod = checkable->GetCheckPeriod(); + if (checkPeriod) + fp << "\t" "check_period" "\t" << checkPeriod->GetName() << "\n"; + + if (cr) { + fp << "\t" << "check_execution_time=" << Convert::ToString(cr->CalculateExecutionTime()) << "\n" + "\t" "check_latency=" << Convert::ToString(cr->CalculateLatency()) << "\n"; + } + + Host::Ptr host; + Service::Ptr service; + tie(host, service) = GetHostService(checkable); + + if (service) { + fp << "\t" "current_state=" << service->GetState() << "\n" + "\t" "last_hard_state=" << service->GetLastHardState() << "\n" + "\t" "last_time_ok=" << static_cast(service->GetLastStateOK()) << "\n" + "\t" "last_time_warn=" << static_cast(service->GetLastStateWarning()) << "\n" + "\t" "last_time_critical=" << static_cast(service->GetLastStateCritical()) << "\n" + "\t" "last_time_unknown=" << static_cast(service->GetLastStateUnknown()) << "\n"; + } else { + int currentState = host->GetState(); + + if (currentState != HostUp && !host->IsReachable()) + currentState = 2; /* hardcoded compat state */ + + fp << "\t" "current_state=" << currentState << "\n" + "\t" "last_hard_state=" << host->GetLastHardState() << "\n" + "\t" "last_time_up=" << static_cast(host->GetLastStateUp()) << "\n" + "\t" "last_time_down=" << static_cast(host->GetLastStateDown()) << "\n"; + } + + fp << "\t" "state_type=" << checkable->GetStateType() << "\n" + "\t" "last_check=" << static_cast(host->GetLastCheck()) << "\n"; + + if (cr) { + fp << "\t" "plugin_output=" << CompatUtility::GetCheckResultOutput(cr) << "\n" + "\t" "long_plugin_output=" << CompatUtility::GetCheckResultLongOutput(cr) << "\n" + "\t" "performance_data=" << PluginUtility::FormatPerfdata(cr->GetPerformanceData()) << "\n"; + } + + fp << "\t" << "next_check=" << static_cast(checkable->GetNextCheck()) << "\n" + "\t" "current_attempt=" << checkable->GetCheckAttempt() << "\n" + "\t" "max_attempts=" << checkable->GetMaxCheckAttempts() << "\n" + "\t" "last_state_change=" << static_cast(checkable->GetLastStateChange()) << "\n" + "\t" "last_hard_state_change=" << static_cast(checkable->GetLastHardStateChange()) << "\n" + "\t" "last_update=" << static_cast(Utility::GetTime()) << "\n" + "\t" "notifications_enabled=" << Convert::ToLong(checkable->GetEnableNotifications()) << "\n" + "\t" "active_checks_enabled=" << Convert::ToLong(checkable->GetEnableActiveChecks()) << "\n" + "\t" "passive_checks_enabled=" << Convert::ToLong(checkable->GetEnablePassiveChecks()) << "\n" + "\t" "flap_detection_enabled=" << Convert::ToLong(checkable->GetEnableFlapping()) << "\n" + "\t" "is_flapping=" << Convert::ToLong(checkable->IsFlapping()) << "\n" + "\t" "percent_state_change=" << checkable->GetFlappingCurrent() << "\n" + "\t" "problem_has_been_acknowledged=" << (checkable->GetAcknowledgement() != AcknowledgementNone ? 1 : 0) << "\n" + "\t" "acknowledgement_type=" << checkable->GetAcknowledgement() << "\n" + "\t" "acknowledgement_end_time=" << checkable->GetAcknowledgementExpiry() << "\n" + "\t" "scheduled_downtime_depth=" << checkable->GetDowntimeDepth() << "\n" + "\t" "last_notification=" << CompatUtility::GetCheckableNotificationLastNotification(checkable) << "\n" + "\t" "next_notification=" << CompatUtility::GetCheckableNotificationNextNotification(checkable) << "\n" + "\t" "current_notification_number=" << CompatUtility::GetCheckableNotificationNotificationNumber(checkable) << "\n" + "\t" "is_reachable=" << Convert::ToLong(checkable->IsReachable()) << "\n"; +} + +void StatusDataWriter::DumpServiceStatus(std::ostream& fp, const Service::Ptr& service) +{ + Host::Ptr host = service->GetHost(); + + fp << "servicestatus {" "\n" + "\t" "host_name=" << host->GetName() << "\n" + "\t" "service_description=" << service->GetShortName() << "\n"; + + { + ObjectLock olock(service); + DumpCheckableStatusAttrs(fp, service); + } + + fp << "\t" "}" "\n" "\n"; + + DumpDowntimes(fp, service); + DumpComments(fp, service); +} + +void StatusDataWriter::DumpServiceObject(std::ostream& fp, const Service::Ptr& service) +{ + Host::Ptr host = service->GetHost(); + + { + ObjectLock olock(service); + + fp << "define service {" "\n" + "\t" "host_name" "\t" << host->GetName() << "\n" + "\t" "service_description" "\t" << service->GetShortName() << "\n" + "\t" "display_name" "\t" << service->GetDisplayName() << "\n" + "\t" "check_interval" "\t" << (service->GetCheckInterval() / 60.0) << "\n" + "\t" "retry_interval" "\t" << (service->GetRetryInterval() / 60.0) << "\n" + "\t" "max_check_attempts" "\t" << service->GetMaxCheckAttempts() << "\n" + "\t" "active_checks_enabled" "\t" << Convert::ToLong(service->GetEnableActiveChecks()) << "\n" + "\t" "passive_checks_enabled" "\t" << Convert::ToLong(service->GetEnablePassiveChecks()) << "\n" + "\t" "flap_detection_enabled" "\t" << Convert::ToLong(service->GetEnableFlapping()) << "\n" + "\t" "is_volatile" "\t" << Convert::ToLong(service->GetVolatile()) << "\n" + "\t" "notifications_enabled" "\t" << Convert::ToLong(service->GetEnableNotifications()) << "\n" + "\t" "notification_options" "\t" << GetNotificationOptions(service) << "\n" + "\t" "notification_interval" "\t" << CompatUtility::GetCheckableNotificationNotificationInterval(service) << "\n" + "\t" "notification_period" "\t" << "" << "\n" + "\t" "event_handler_enabled" "\t" << Convert::ToLong(service->GetEnableEventHandler()) << "\n"; + + CheckCommand::Ptr checkcommand = service->GetCheckCommand(); + if (checkcommand) + fp << "\t" "check_command" "\t" << CompatUtility::GetCommandName(checkcommand) << "!" << CompatUtility::GetCheckableCommandArgs(service)<< "\n"; + + EventCommand::Ptr eventcommand = service->GetEventCommand(); + if (eventcommand && service->GetEnableEventHandler()) + fp << "\t" "event_handler" "\t" << CompatUtility::GetCommandName(eventcommand) << "\n"; + + TimePeriod::Ptr checkPeriod = service->GetCheckPeriod(); + if (checkPeriod) + fp << "\t" "check_period" "\t" << checkPeriod->GetName() << "\n"; + + fp << "\t" "contacts" "\t"; + DumpNameList(fp, CompatUtility::GetCheckableNotificationUsers(service)); + fp << "\n"; + + fp << "\t" "contact_groups" "\t"; + DumpNameList(fp, CompatUtility::GetCheckableNotificationUserGroups(service)); + fp << "\n"; + + String notes = service->GetNotes(); + String notes_url = service->GetNotesUrl(); + String action_url = service->GetActionUrl(); + String icon_image = service->GetIconImage(); + String icon_image_alt = service->GetIconImageAlt(); + + fp << "\t" "initial_state" "\t" "o" "\n" + "\t" "low_flap_threshold" "\t" << service->GetFlappingThresholdLow() << "\n" + "\t" "high_flap_threshold" "\t" << service->GetFlappingThresholdHigh() << "\n" + "\t" "process_perf_data" "\t" << Convert::ToLong(service->GetEnablePerfdata()) << "\n" + "\t" "check_freshness" << "\t" "1" "\n"; + + if (!notes.IsEmpty()) + fp << "\t" "notes" "\t" << notes << "\n"; + if (!notes_url.IsEmpty()) + fp << "\t" "notes_url" "\t" << notes_url << "\n"; + if (!action_url.IsEmpty()) + fp << "\t" "action_url" "\t" << action_url << "\n"; + if (!icon_image.IsEmpty()) + fp << "\t" "icon_image" "\t" << icon_image << "\n"; + if (!icon_image_alt.IsEmpty()) + fp << "\t" "icon_image_alt" "\t" << icon_image_alt << "\n"; + } + + fp << "\t" "service_groups" "\t"; + bool first = true; + + Array::Ptr groups = service->GetGroups(); + + if (groups) { + ObjectLock olock(groups); + + for (const String& name : groups) { + ServiceGroup::Ptr sg = ServiceGroup::GetByName(name); + + if (sg) { + if (!first) + fp << ","; + else + first = false; + + fp << sg->GetName(); + } + } + } + + fp << "\n"; + + DumpCustomAttributes(fp, service); + + fp << "\t" "}" "\n" "\n"; +} + +void StatusDataWriter::DumpCustomAttributes(std::ostream& fp, const CustomVarObject::Ptr& object) +{ + Dictionary::Ptr vars = object->GetVars(); + + if (!vars) + return; + + bool is_json = false; + + ObjectLock olock(vars); + for (const Dictionary::Pair& kv : vars) { + if (kv.first.IsEmpty()) + continue; + + Value value; + + if (kv.second.IsObjectType() || kv.second.IsObjectType()) { + value = JsonEncode(kv.second); + is_json = true; + } else + value = CompatUtility::EscapeString(kv.second); + + fp << "\t" "_" << kv.first << "\t" << value << "\n"; + } + + if (is_json) + fp << "\t" "_is_json" "\t" "1" "\n"; +} + +void StatusDataWriter::UpdateObjectsCache() +{ + CONTEXT("Writing objects.cache file"); + + /* Use the compat path here from the .ti generated class. */ + String objectsPath = GetObjectsPath(); + + std::fstream objectfp; + String tempObjectsPath = Utility::CreateTempFile(objectsPath + ".XXXXXX", 0644, objectfp); + + objectfp << std::fixed; + + objectfp << "# Icinga objects cache file" "\n" + "# This file is auto-generated. Do not modify this file." "\n" + "\n"; + + for (const Host::Ptr& host : ConfigType::GetObjectsByType()) { + std::ostringstream tempobjectfp; + tempobjectfp << std::fixed; + DumpHostObject(tempobjectfp, host); + objectfp << tempobjectfp.str(); + + for (const Service::Ptr& service : host->GetServices()) { + std::ostringstream tempobjectfp; + tempobjectfp << std::fixed; + DumpServiceObject(tempobjectfp, service); + objectfp << tempobjectfp.str(); + } + } + + for (const HostGroup::Ptr& hg : ConfigType::GetObjectsByType()) { + std::ostringstream tempobjectfp; + tempobjectfp << std::fixed; + + String display_name = hg->GetDisplayName(); + String notes = hg->GetNotes(); + String notes_url = hg->GetNotesUrl(); + String action_url = hg->GetActionUrl(); + + tempobjectfp << "define hostgroup {" "\n" + "\t" "hostgroup_name" "\t" << hg->GetName() << "\n"; + + if (!display_name.IsEmpty()) + tempobjectfp << "\t" "alias" "\t" << display_name << "\n"; + if (!notes.IsEmpty()) + tempobjectfp << "\t" "notes" "\t" << notes << "\n"; + if (!notes_url.IsEmpty()) + tempobjectfp << "\t" "notes_url" "\t" << notes_url << "\n"; + if (!action_url.IsEmpty()) + tempobjectfp << "\t" "action_url" "\t" << action_url << "\n"; + + DumpCustomAttributes(tempobjectfp, hg); + + tempobjectfp << "\t" "members" "\t"; + DumpNameList(tempobjectfp, hg->GetMembers()); + tempobjectfp << "\n" "\t" "}" "\n"; + + objectfp << tempobjectfp.str(); + } + + for (const ServiceGroup::Ptr& sg : ConfigType::GetObjectsByType()) { + std::ostringstream tempobjectfp; + tempobjectfp << std::fixed; + + String display_name = sg->GetDisplayName(); + String notes = sg->GetNotes(); + String notes_url = sg->GetNotesUrl(); + String action_url = sg->GetActionUrl(); + + tempobjectfp << "define servicegroup {" "\n" + "\t" "servicegroup_name" "\t" << sg->GetName() << "\n"; + + if (!display_name.IsEmpty()) + tempobjectfp << "\t" "alias" "\t" << display_name << "\n"; + if (!notes.IsEmpty()) + tempobjectfp << "\t" "notes" "\t" << notes << "\n"; + if (!notes_url.IsEmpty()) + tempobjectfp << "\t" "notes_url" "\t" << notes_url << "\n"; + if (!action_url.IsEmpty()) + tempobjectfp << "\t" "action_url" "\t" << action_url << "\n"; + + DumpCustomAttributes(tempobjectfp, sg); + + tempobjectfp << "\t" "members" "\t"; + + std::vector sglist; + for (const Service::Ptr& service : sg->GetMembers()) { + Host::Ptr host = service->GetHost(); + + sglist.emplace_back(host->GetName()); + sglist.emplace_back(service->GetShortName()); + } + + DumpStringList(tempobjectfp, sglist); + + tempobjectfp << "\n" "}" "\n"; + + objectfp << tempobjectfp.str(); + } + + for (const User::Ptr& user : ConfigType::GetObjectsByType()) { + std::ostringstream tempobjectfp; + tempobjectfp << std::fixed; + + String email = user->GetEmail(); + String pager = user->GetPager(); + String alias = user->GetDisplayName(); + + tempobjectfp << "define contact {" "\n" + "\t" "contact_name" "\t" << user->GetName() << "\n"; + + if (!alias.IsEmpty()) + tempobjectfp << "\t" "alias" "\t" << alias << "\n"; + if (!email.IsEmpty()) + tempobjectfp << "\t" "email" "\t" << email << "\n"; + if (!pager.IsEmpty()) + tempobjectfp << "\t" "pager" "\t" << pager << "\n"; + + tempobjectfp << "\t" "service_notification_options" "\t" "w,u,c,r,f,s" "\n" + "\t" "host_notification_options""\t" "d,u,r,f,s" "\n" + "\t" "host_notifications_enabled" "\t" "1" "\n" + "\t" "service_notifications_enabled" "\t" "1" "\n" + "\t" "}" "\n" + "\n"; + + objectfp << tempobjectfp.str(); + } + + for (const UserGroup::Ptr& ug : ConfigType::GetObjectsByType()) { + std::ostringstream tempobjectfp; + tempobjectfp << std::fixed; + + tempobjectfp << "define contactgroup {" "\n" + "\t" "contactgroup_name" "\t" << ug->GetName() << "\n" + "\t" "alias" "\t" << ug->GetDisplayName() << "\n"; + + tempobjectfp << "\t" "members" "\t"; + DumpNameList(tempobjectfp, ug->GetMembers()); + tempobjectfp << "\n" + "\t" "}" "\n"; + + objectfp << tempobjectfp.str(); + } + + for (const Command::Ptr& command : ConfigType::GetObjectsByType()) { + DumpCommand(objectfp, command); + } + + for (const Command::Ptr& command : ConfigType::GetObjectsByType()) { + DumpCommand(objectfp, command); + } + + for (const Command::Ptr& command : ConfigType::GetObjectsByType()) { + DumpCommand(objectfp, command); + } + + for (const TimePeriod::Ptr& tp : ConfigType::GetObjectsByType()) { + DumpTimePeriod(objectfp, tp); + } + + for (const Dependency::Ptr& dep : ConfigType::GetObjectsByType()) { + Checkable::Ptr parent = dep->GetParent(); + + if (!parent) { + Log(LogDebug, "StatusDataWriter") + << "Missing parent for dependency '" << dep->GetName() << "'."; + continue; + } + + Host::Ptr parent_host; + Service::Ptr parent_service; + tie(parent_host, parent_service) = GetHostService(parent); + + Checkable::Ptr child = dep->GetChild(); + + if (!child) { + Log(LogDebug, "StatusDataWriter") + << "Missing child for dependency '" << dep->GetName() << "'."; + continue; + } + + Host::Ptr child_host; + Service::Ptr child_service; + tie(child_host, child_service) = GetHostService(child); + + int state_filter = dep->GetStateFilter(); + std::vector failure_criteria; + if (state_filter & StateFilterOK || state_filter & StateFilterUp) + failure_criteria.emplace_back("o"); + if (state_filter & StateFilterWarning) + failure_criteria.emplace_back("w"); + if (state_filter & StateFilterCritical) + failure_criteria.emplace_back("c"); + if (state_filter & StateFilterUnknown) + failure_criteria.emplace_back("u"); + if (state_filter & StateFilterDown) + failure_criteria.emplace_back("d"); + + String criteria = boost::algorithm::join(failure_criteria, ","); + + /* Icinga 1.x only allows host->host, service->service dependencies */ + if (!child_service && !parent_service) { + objectfp << "define hostdependency {" "\n" + "\t" "dependent_host_name" "\t" << child_host->GetName() << "\n" + "\t" "host_name" "\t" << parent_host->GetName() << "\n" + "\t" "execution_failure_criteria" "\t" << criteria << "\n" + "\t" "notification_failure_criteria" "\t" << criteria << "\n" + "\t" "}" "\n" + "\n"; + } else if (child_service && parent_service){ + + objectfp << "define servicedependency {" "\n" + "\t" "dependent_host_name" "\t" << child_service->GetHost()->GetName() << "\n" + "\t" "dependent_service_description" "\t" << child_service->GetShortName() << "\n" + "\t" "host_name" "\t" << parent_service->GetHost()->GetName() << "\n" + "\t" "service_description" "\t" << parent_service->GetShortName() << "\n" + "\t" "execution_failure_criteria" "\t" << criteria << "\n" + "\t" "notification_failure_criteria" "\t" << criteria << "\n" + "\t" "}" "\n" + "\n"; + } + } + + objectfp.close(); + + Utility::RenameFile(tempObjectsPath, objectsPath); +} + +/** + * Periodically writes the status.dat and objects.cache files. + */ +void StatusDataWriter::StatusTimerHandler() +{ + if (m_ObjectsCacheOutdated) { + UpdateObjectsCache(); + m_ObjectsCacheOutdated = false; + } + + double start = Utility::GetTime(); + + String statusPath = GetStatusPath(); + + std::fstream statusfp; + String tempStatusPath = Utility::CreateTempFile(statusPath + ".XXXXXX", 0644, statusfp); + + statusfp << std::fixed; + + statusfp << "# Icinga status file" "\n" + "# This file is auto-generated. Do not modify this file." "\n" + "\n"; + + statusfp << "info {" "\n" + "\t" "created=" << Utility::GetTime() << "\n" + "\t" "version=" << Application::GetAppVersion() << "\n" + "\t" "}" "\n" + "\n"; + + statusfp << "programstatus {" "\n" + "\t" "icinga_pid=" << Utility::GetPid() << "\n" + "\t" "daemon_mode=1" "\n" + "\t" "program_start=" << static_cast(Application::GetStartTime()) << "\n" + "\t" "active_host_checks_enabled=" << Convert::ToLong(IcingaApplication::GetInstance()->GetEnableHostChecks()) << "\n" + "\t" "passive_host_checks_enabled=1" "\n" + "\t" "active_service_checks_enabled=" << Convert::ToLong(IcingaApplication::GetInstance()->GetEnableServiceChecks()) << "\n" + "\t" "passive_service_checks_enabled=1" "\n" + "\t" "check_service_freshness=1" "\n" + "\t" "check_host_freshness=1" "\n" + "\t" "enable_notifications=" << Convert::ToLong(IcingaApplication::GetInstance()->GetEnableNotifications()) << "\n" + "\t" "enable_event_handlers=" << Convert::ToLong(IcingaApplication::GetInstance()->GetEnableEventHandlers()) << "\n" + "\t" "enable_flap_detection=" << Convert::ToLong(IcingaApplication::GetInstance()->GetEnableFlapping()) << "\n" + "\t" "enable_failure_prediction=0" "\n" + "\t" "process_performance_data=" << Convert::ToLong(IcingaApplication::GetInstance()->GetEnablePerfdata()) << "\n" + "\t" "active_scheduled_host_check_stats=" << CIB::GetActiveHostChecksStatistics(60) << "," << CIB::GetActiveHostChecksStatistics(5 * 60) << "," << CIB::GetActiveHostChecksStatistics(15 * 60) << "\n" + "\t" "passive_host_check_stats=" << CIB::GetPassiveHostChecksStatistics(60) << "," << CIB::GetPassiveHostChecksStatistics(5 * 60) << "," << CIB::GetPassiveHostChecksStatistics(15 * 60) << "\n" + "\t" "active_scheduled_service_check_stats=" << CIB::GetActiveServiceChecksStatistics(60) << "," << CIB::GetActiveServiceChecksStatistics(5 * 60) << "," << CIB::GetActiveServiceChecksStatistics(15 * 60) << "\n" + "\t" "passive_service_check_stats=" << CIB::GetPassiveServiceChecksStatistics(60) << "," << CIB::GetPassiveServiceChecksStatistics(5 * 60) << "," << CIB::GetPassiveServiceChecksStatistics(15 * 60) << "\n" + "\t" "next_downtime_id=" << Downtime::GetNextDowntimeID() << "\n" + "\t" "next_comment_id=" << Comment::GetNextCommentID() << "\n"; + + statusfp << "\t" "}" "\n" + "\n"; + + for (const Host::Ptr& host : ConfigType::GetObjectsByType()) { + std::ostringstream tempstatusfp; + tempstatusfp << std::fixed; + DumpHostStatus(tempstatusfp, host); + statusfp << tempstatusfp.str(); + + for (const Service::Ptr& service : host->GetServices()) { + std::ostringstream tempstatusfp; + tempstatusfp << std::fixed; + DumpServiceStatus(tempstatusfp, service); + statusfp << tempstatusfp.str(); + } + } + + statusfp.close(); + + Utility::RenameFile(tempStatusPath, statusPath); + + Log(LogNotice, "StatusDataWriter") + << "Writing status.dat file took " << Utility::FormatDuration(Utility::GetTime() - start); +} + +void StatusDataWriter::ObjectHandler() +{ + m_ObjectsCacheOutdated = true; +} + +String StatusDataWriter::GetNotificationOptions(const Checkable::Ptr& checkable) +{ + Host::Ptr host; + Service::Ptr service; + tie(host, service) = GetHostService(checkable); + + unsigned long notification_type_filter = 0; + unsigned long notification_state_filter = 0; + + for (const Notification::Ptr& notification : checkable->GetNotifications()) { + notification_type_filter |= notification->GetTypeFilter(); + notification_state_filter |= notification->GetStateFilter(); + } + + std::vector notification_options; + + /* notification state filters */ + if (service) { + if (notification_state_filter & ServiceWarning) { + notification_options.push_back("w"); + } + if (notification_state_filter & ServiceUnknown) { + notification_options.push_back("u"); + } + if (notification_state_filter & ServiceCritical) { + notification_options.push_back("c"); + } + } else { + if (notification_state_filter & HostDown) { + notification_options.push_back("d"); + } + } + + /* notification type filters */ + if (notification_type_filter & NotificationRecovery) { + notification_options.push_back("r"); + } + if ((notification_type_filter & NotificationFlappingStart) || + (notification_type_filter & NotificationFlappingEnd)) { + notification_options.push_back("f"); + } + if ((notification_type_filter & NotificationDowntimeStart) || + (notification_type_filter & NotificationDowntimeEnd) || + (notification_type_filter & NotificationDowntimeRemoved)) { + notification_options.push_back("s"); + } + + return boost::algorithm::join(notification_options, ","); +} diff --git a/lib/compat/statusdatawriter.hpp b/lib/compat/statusdatawriter.hpp new file mode 100644 index 0000000..31a5efe --- /dev/null +++ b/lib/compat/statusdatawriter.hpp @@ -0,0 +1,89 @@ +/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */ + +#ifndef STATUSDATAWRITER_H +#define STATUSDATAWRITER_H + +#include "compat/statusdatawriter-ti.hpp" +#include "icinga/customvarobject.hpp" +#include "icinga/host.hpp" +#include "icinga/service.hpp" +#include "icinga/command.hpp" +#include "icinga/compatutility.hpp" +#include "base/timer.hpp" +#include "base/utility.hpp" +#include + +namespace icinga +{ + +/** + * @ingroup compat + */ +class StatusDataWriter final : public ObjectImpl +{ +public: + DECLARE_OBJECT(StatusDataWriter); + DECLARE_OBJECTNAME(StatusDataWriter); + + static void StatsFunc(const Dictionary::Ptr& status, const Array::Ptr& perfdata); + +protected: + void Start(bool runtimeCreated) override; + void Stop(bool runtimeRemoved) override; + +private: + Timer::Ptr m_StatusTimer; + bool m_ObjectsCacheOutdated; + + void DumpCommand(std::ostream& fp, const Command::Ptr& command); + void DumpTimePeriod(std::ostream& fp, const TimePeriod::Ptr& tp); + void DumpDowntimes(std::ostream& fp, const Checkable::Ptr& owner); + void DumpComments(std::ostream& fp, const Checkable::Ptr& owner); + void DumpHostStatus(std::ostream& fp, const Host::Ptr& host); + void DumpHostObject(std::ostream& fp, const Host::Ptr& host); + + void DumpCheckableStatusAttrs(std::ostream& fp, const Checkable::Ptr& checkable); + + template + void DumpNameList(std::ostream& fp, const T& list) + { + bool first = true; + for (const auto& obj : list) { + if (!first) + fp << ","; + else + first = false; + + fp << obj->GetName(); + } + } + + template + void DumpStringList(std::ostream& fp, const T& list) + { + bool first = true; + for (const auto& str : list) { + if (!first) + fp << ","; + else + first = false; + + fp << str; + } + } + + void DumpServiceStatus(std::ostream& fp, const Service::Ptr& service); + void DumpServiceObject(std::ostream& fp, const Service::Ptr& service); + + void DumpCustomAttributes(std::ostream& fp, const CustomVarObject::Ptr& object); + + void UpdateObjectsCache(); + void StatusTimerHandler(); + void ObjectHandler(); + + static String GetNotificationOptions(const Checkable::Ptr& checkable); +}; + +} + +#endif /* STATUSDATAWRITER_H */ diff --git a/lib/compat/statusdatawriter.ti b/lib/compat/statusdatawriter.ti new file mode 100644 index 0000000..cc7eb11 --- /dev/null +++ b/lib/compat/statusdatawriter.ti @@ -0,0 +1,26 @@ +/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */ + +#include "base/configobject.hpp" +#include "base/application.hpp" + +library compat; + +namespace icinga +{ + +class StatusDataWriter : ConfigObject +{ + activation_priority 100; + + [config] String status_path { + default {{{ return Configuration::CacheDir + "/status.dat"; }}} + }; + [config] String objects_path { + default {{{ return Configuration::CacheDir + "/objects.cache"; }}} + }; + [config] double update_interval { + default {{{ return 15; }}} + }; +}; + +} -- cgit v1.2.3