Implement host checks.

Refs #5919
This commit is contained in:
Gunnar Beutner 2014-04-03 15:36:13 +02:00
parent 5c58eb368c
commit 23e9630682
82 changed files with 3478 additions and 4042 deletions

View File

@ -40,8 +40,8 @@ Value CheckerComponent::StatsFunc(Dictionary::Ptr& status, Dictionary::Ptr& perf
Dictionary::Ptr nodes = make_shared<Dictionary>(); Dictionary::Ptr nodes = make_shared<Dictionary>();
BOOST_FOREACH(const CheckerComponent::Ptr& checker, DynamicType::GetObjects<CheckerComponent>()) { BOOST_FOREACH(const CheckerComponent::Ptr& checker, DynamicType::GetObjects<CheckerComponent>()) {
unsigned long idle = checker->GetIdleServices(); unsigned long idle = checker->GetIdleCheckables();
unsigned long pending = checker->GetPendingServices(); unsigned long pending = checker->GetPendingCheckables();
Dictionary::Ptr stats = make_shared<Dictionary>(); Dictionary::Ptr stats = make_shared<Dictionary>();
stats->Set("idle", idle); stats->Set("idle", idle);
@ -65,7 +65,7 @@ void CheckerComponent::OnConfigLoaded(void)
DynamicObject::OnStopped.connect(bind(&CheckerComponent::ObjectHandler, this, _1)); DynamicObject::OnStopped.connect(bind(&CheckerComponent::ObjectHandler, this, _1));
DynamicObject::OnAuthorityChanged.connect(bind(&CheckerComponent::ObjectHandler, this, _1)); DynamicObject::OnAuthorityChanged.connect(bind(&CheckerComponent::ObjectHandler, this, _1));
Service::OnNextCheckChanged.connect(bind(&CheckerComponent::NextCheckChangedHandler, this, _1)); Checkable::OnNextCheckChanged.connect(bind(&CheckerComponent::NextCheckChangedHandler, this, _1));
} }
void CheckerComponent::Start(void) void CheckerComponent::Start(void)
@ -103,8 +103,8 @@ void CheckerComponent::CheckThreadProc(void)
boost::mutex::scoped_lock lock(m_Mutex); boost::mutex::scoped_lock lock(m_Mutex);
for (;;) { for (;;) {
typedef boost::multi_index::nth_index<ServiceSet, 1>::type CheckTimeView; typedef boost::multi_index::nth_index<CheckableSet, 1>::type CheckTimeView;
CheckTimeView& idx = boost::get<1>(m_IdleServices); CheckTimeView& idx = boost::get<1>(m_IdleCheckables);
while (idx.begin() == idx.end() && !m_Stopped) while (idx.begin() == idx.end() && !m_Stopped)
m_CV.wait(lock); m_CV.wait(lock);
@ -113,10 +113,10 @@ void CheckerComponent::CheckThreadProc(void)
break; break;
CheckTimeView::iterator it = idx.begin(); CheckTimeView::iterator it = idx.begin();
Service::Ptr service = *it; Checkable::Ptr service = *it;
if (!service->HasAuthority("checker")) { if (!service->HasAuthority("checker")) {
m_IdleServices.erase(service); m_IdleCheckables.erase(service);
continue; continue;
} }
@ -130,7 +130,7 @@ void CheckerComponent::CheckThreadProc(void)
continue; continue;
} }
m_IdleServices.erase(service); m_IdleCheckables.erase(service);
bool forced = service->GetForceNextCheck(); bool forced = service->GetForceNextCheck();
bool check = true; bool check = true;
@ -156,7 +156,7 @@ void CheckerComponent::CheckThreadProc(void)
/* reschedule the service if checks are disabled */ /* reschedule the service if checks are disabled */
if (!check) { if (!check) {
m_IdleServices.insert(service); m_IdleCheckables.insert(service);
lock.unlock(); lock.unlock();
service->UpdateNextCheck(); service->UpdateNextCheck();
@ -166,7 +166,7 @@ void CheckerComponent::CheckThreadProc(void)
continue; continue;
} }
m_PendingServices.insert(service); m_PendingCheckables.insert(service);
lock.unlock(); lock.unlock();
@ -184,7 +184,7 @@ void CheckerComponent::CheckThreadProc(void)
} }
} }
void CheckerComponent::ExecuteCheckHelper(const Service::Ptr& service) void CheckerComponent::ExecuteCheckHelper(const Checkable::Ptr& service)
{ {
try { try {
service->ExecuteCheck(); service->ExecuteCheck();
@ -198,19 +198,19 @@ void CheckerComponent::ExecuteCheckHelper(const Service::Ptr& service)
/* remove the service from the list of pending services; if it's not in the /* remove the service from the list of pending services; if it's not in the
* list this was a manual (i.e. forced) check and we must not re-add the * list this was a manual (i.e. forced) check and we must not re-add the
* service to the services list because it's already there. */ * service to the services list because it's already there. */
CheckerComponent::ServiceSet::iterator it; CheckerComponent::CheckableSet::iterator it;
it = m_PendingServices.find(service); it = m_PendingCheckables.find(service);
if (it != m_PendingServices.end()) { if (it != m_PendingCheckables.end()) {
m_PendingServices.erase(it); m_PendingCheckables.erase(it);
if (service->IsActive() && service->HasAuthority("checker")) if (service->IsActive() && service->HasAuthority("checker"))
m_IdleServices.insert(service); m_IdleCheckables.insert(service);
m_CV.notify_all(); m_CV.notify_all();
} }
} }
Log(LogDebug, "checker", "Check finished for service '" + service->GetName() + "'"); Log(LogDebug, "checker", "Check finished for object '" + service->GetName() + "'");
} }
void CheckerComponent::ResultTimerHandler(void) void CheckerComponent::ResultTimerHandler(void)
@ -222,7 +222,7 @@ void CheckerComponent::ResultTimerHandler(void)
{ {
boost::mutex::scoped_lock lock(m_Mutex); boost::mutex::scoped_lock lock(m_Mutex);
msgbuf << "Pending services: " << m_PendingServices.size() << "; Idle services: " << m_IdleServices.size() << "; Checks/s: " << CIB::GetActiveChecksStatistics(5) / 5.0; msgbuf << "Pending services: " << m_PendingCheckables.size() << "; Idle services: " << m_IdleCheckables.size() << "; Checks/s: " << CIB::GetActiveChecksStatistics(5) / 5.0;
} }
Log(LogInformation, "checker", msgbuf.str()); Log(LogInformation, "checker", msgbuf.str());
@ -230,37 +230,37 @@ void CheckerComponent::ResultTimerHandler(void)
void CheckerComponent::ObjectHandler(const DynamicObject::Ptr& object) void CheckerComponent::ObjectHandler(const DynamicObject::Ptr& object)
{ {
if (object->GetType() != DynamicType::GetByName("Service")) if (!Type::GetByName("Checkable")->IsAssignableFrom(object->GetReflectionType()))
return; return;
Service::Ptr service = static_pointer_cast<Service>(object); Checkable::Ptr service = static_pointer_cast<Checkable>(object);
{ {
boost::mutex::scoped_lock lock(m_Mutex); boost::mutex::scoped_lock lock(m_Mutex);
if (object->IsActive() && object->HasAuthority("checker")) { if (object->IsActive() && object->HasAuthority("checker")) {
if (m_PendingServices.find(service) != m_PendingServices.end()) if (m_PendingCheckables.find(service) != m_PendingCheckables.end())
return; return;
m_IdleServices.insert(service); m_IdleCheckables.insert(service);
} else { } else {
m_IdleServices.erase(service); m_IdleCheckables.erase(service);
m_PendingServices.erase(service); m_PendingCheckables.erase(service);
} }
m_CV.notify_all(); m_CV.notify_all();
} }
} }
void CheckerComponent::NextCheckChangedHandler(const Service::Ptr& service) void CheckerComponent::NextCheckChangedHandler(const Checkable::Ptr& service)
{ {
boost::mutex::scoped_lock lock(m_Mutex); boost::mutex::scoped_lock lock(m_Mutex);
/* remove and re-insert the service from the set in order to force an index update */ /* remove and re-insert the service from the set in order to force an index update */
typedef boost::multi_index::nth_index<ServiceSet, 0>::type ServiceView; typedef boost::multi_index::nth_index<CheckableSet, 0>::type CheckableView;
ServiceView& idx = boost::get<0>(m_IdleServices); CheckableView& idx = boost::get<0>(m_IdleCheckables);
ServiceView::iterator it = idx.find(service); CheckableView::iterator it = idx.find(service);
if (it == idx.end()) if (it == idx.end())
return; return;
@ -269,16 +269,16 @@ void CheckerComponent::NextCheckChangedHandler(const Service::Ptr& service)
m_CV.notify_all(); m_CV.notify_all();
} }
unsigned long CheckerComponent::GetIdleServices(void) unsigned long CheckerComponent::GetIdleCheckables(void)
{ {
boost::mutex::scoped_lock lock(m_Mutex); boost::mutex::scoped_lock lock(m_Mutex);
return m_IdleServices.size(); return m_IdleCheckables.size();
} }
unsigned long CheckerComponent::GetPendingServices(void) unsigned long CheckerComponent::GetPendingCheckables(void)
{ {
boost::mutex::scoped_lock lock(m_Mutex); boost::mutex::scoped_lock lock(m_Mutex);
return m_PendingServices.size(); return m_PendingCheckables.size();
} }

View File

@ -38,14 +38,14 @@ namespace icinga
/** /**
* @ingroup checker * @ingroup checker
*/ */
struct ServiceNextCheckExtractor struct CheckableNextCheckExtractor
{ {
typedef double result_type; typedef double result_type;
/** /**
* @threadsafety Always. * @threadsafety Always.
*/ */
double operator()(const Service::Ptr& service) double operator()(const Checkable::Ptr& service)
{ {
return service->GetNextCheck(); return service->GetNextCheck();
} }
@ -61,20 +61,20 @@ public:
DECLARE_TYPENAME(CheckerComponent); DECLARE_TYPENAME(CheckerComponent);
typedef boost::multi_index_container< typedef boost::multi_index_container<
Service::Ptr, Checkable::Ptr,
boost::multi_index::indexed_by< boost::multi_index::indexed_by<
boost::multi_index::ordered_unique<boost::multi_index::identity<Service::Ptr> >, boost::multi_index::ordered_unique<boost::multi_index::identity<Checkable::Ptr> >,
boost::multi_index::ordered_non_unique<ServiceNextCheckExtractor> boost::multi_index::ordered_non_unique<CheckableNextCheckExtractor>
> >
> ServiceSet; > CheckableSet;
virtual void OnConfigLoaded(void); virtual void OnConfigLoaded(void);
virtual void Start(void); virtual void Start(void);
virtual void Stop(void); virtual void Stop(void);
static Value StatsFunc(Dictionary::Ptr& status, Dictionary::Ptr& perfdata); static Value StatsFunc(Dictionary::Ptr& status, Dictionary::Ptr& perfdata);
unsigned long GetIdleServices(void); unsigned long GetIdleCheckables(void);
unsigned long GetPendingServices(void); unsigned long GetPendingCheckables(void);
private: private:
boost::mutex m_Mutex; boost::mutex m_Mutex;
@ -82,20 +82,20 @@ private:
bool m_Stopped; bool m_Stopped;
boost::thread m_Thread; boost::thread m_Thread;
ServiceSet m_IdleServices; CheckableSet m_IdleCheckables;
ServiceSet m_PendingServices; CheckableSet m_PendingCheckables;
Timer::Ptr m_ResultTimer; Timer::Ptr m_ResultTimer;
void CheckThreadProc(void); void CheckThreadProc(void);
void ResultTimerHandler(void); void ResultTimerHandler(void);
void ExecuteCheckHelper(const Service::Ptr& service); void ExecuteCheckHelper(const Checkable::Ptr& service);
void AdjustCheckTimer(void); void AdjustCheckTimer(void);
void ObjectHandler(const DynamicObject::Ptr& object); void ObjectHandler(const DynamicObject::Ptr& object);
void NextCheckChangedHandler(const Service::Ptr& service); void NextCheckChangedHandler(const Checkable::Ptr& service);
void RescheduleCheckTimer(void); void RescheduleCheckTimer(void);

View File

@ -35,7 +35,7 @@ using namespace icinga;
REGISTER_SCRIPTFUNCTION(ClusterCheck, &ClusterCheckTask::ScriptFunc); REGISTER_SCRIPTFUNCTION(ClusterCheck, &ClusterCheckTask::ScriptFunc);
void ClusterCheckTask::ScriptFunc(const Service::Ptr& service, const CheckResult::Ptr& cr) void ClusterCheckTask::ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr)
{ {
/* fetch specific cluster status */ /* fetch specific cluster status */
std::pair<Dictionary::Ptr, Dictionary::Ptr> stats; std::pair<Dictionary::Ptr, Dictionary::Ptr> stats;

View File

@ -33,7 +33,7 @@ namespace icinga
class ClusterCheckTask class ClusterCheckTask
{ {
public: public:
static void ScriptFunc(const Service::Ptr& service, const CheckResult::Ptr& cr); static void ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr);
private: private:
ClusterCheckTask(void); ClusterCheckTask(void);

View File

@ -99,21 +99,21 @@ void ClusterListener::Start(void)
m_MessageQueue.SetExceptionCallback(&ClusterListener::MessageExceptionHandler); m_MessageQueue.SetExceptionCallback(&ClusterListener::MessageExceptionHandler);
Service::OnNewCheckResult.connect(boost::bind(&ClusterListener::CheckResultHandler, this, _1, _2, _3)); Checkable::OnNewCheckResult.connect(boost::bind(&ClusterListener::CheckResultHandler, this, _1, _2, _3));
Service::OnNextCheckChanged.connect(boost::bind(&ClusterListener::NextCheckChangedHandler, this, _1, _2, _3)); Checkable::OnNextCheckChanged.connect(boost::bind(&ClusterListener::NextCheckChangedHandler, this, _1, _2, _3));
Notification::OnNextNotificationChanged.connect(boost::bind(&ClusterListener::NextNotificationChangedHandler, this, _1, _2, _3)); Notification::OnNextNotificationChanged.connect(boost::bind(&ClusterListener::NextNotificationChangedHandler, this, _1, _2, _3));
Service::OnForceNextCheckChanged.connect(boost::bind(&ClusterListener::ForceNextCheckChangedHandler, this, _1, _2, _3)); Checkable::OnForceNextCheckChanged.connect(boost::bind(&ClusterListener::ForceNextCheckChangedHandler, this, _1, _2, _3));
Service::OnForceNextNotificationChanged.connect(boost::bind(&ClusterListener::ForceNextNotificationChangedHandler, this, _1, _2, _3)); Checkable::OnForceNextNotificationChanged.connect(boost::bind(&ClusterListener::ForceNextNotificationChangedHandler, this, _1, _2, _3));
Service::OnEnableActiveChecksChanged.connect(boost::bind(&ClusterListener::EnableActiveChecksChangedHandler, this, _1, _2, _3)); Checkable::OnEnableActiveChecksChanged.connect(boost::bind(&ClusterListener::EnableActiveChecksChangedHandler, this, _1, _2, _3));
Service::OnEnablePassiveChecksChanged.connect(boost::bind(&ClusterListener::EnablePassiveChecksChangedHandler, this, _1, _2, _3)); Checkable::OnEnablePassiveChecksChanged.connect(boost::bind(&ClusterListener::EnablePassiveChecksChangedHandler, this, _1, _2, _3));
Service::OnEnableNotificationsChanged.connect(boost::bind(&ClusterListener::EnableNotificationsChangedHandler, this, _1, _2, _3)); Checkable::OnEnableNotificationsChanged.connect(boost::bind(&ClusterListener::EnableNotificationsChangedHandler, this, _1, _2, _3));
Service::OnEnableFlappingChanged.connect(boost::bind(&ClusterListener::EnableFlappingChangedHandler, this, _1, _2, _3)); Checkable::OnEnableFlappingChanged.connect(boost::bind(&ClusterListener::EnableFlappingChangedHandler, this, _1, _2, _3));
Service::OnCommentAdded.connect(boost::bind(&ClusterListener::CommentAddedHandler, this, _1, _2, _3)); Checkable::OnCommentAdded.connect(boost::bind(&ClusterListener::CommentAddedHandler, this, _1, _2, _3));
Service::OnCommentRemoved.connect(boost::bind(&ClusterListener::CommentRemovedHandler, this, _1, _2, _3)); Checkable::OnCommentRemoved.connect(boost::bind(&ClusterListener::CommentRemovedHandler, this, _1, _2, _3));
Service::OnDowntimeAdded.connect(boost::bind(&ClusterListener::DowntimeAddedHandler, this, _1, _2, _3)); Checkable::OnDowntimeAdded.connect(boost::bind(&ClusterListener::DowntimeAddedHandler, this, _1, _2, _3));
Service::OnDowntimeRemoved.connect(boost::bind(&ClusterListener::DowntimeRemovedHandler, this, _1, _2, _3)); Checkable::OnDowntimeRemoved.connect(boost::bind(&ClusterListener::DowntimeRemovedHandler, this, _1, _2, _3));
Service::OnAcknowledgementSet.connect(boost::bind(&ClusterListener::AcknowledgementSetHandler, this, _1, _2, _3, _4, _5, _6)); Checkable::OnAcknowledgementSet.connect(boost::bind(&ClusterListener::AcknowledgementSetHandler, this, _1, _2, _3, _4, _5, _6));
Service::OnAcknowledgementCleared.connect(boost::bind(&ClusterListener::AcknowledgementClearedHandler, this, _1, _2)); Checkable::OnAcknowledgementCleared.connect(boost::bind(&ClusterListener::AcknowledgementClearedHandler, this, _1, _2));
Endpoint::OnMessageReceived.connect(boost::bind(&ClusterListener::AsyncMessageHandler, this, _1, _2)); Endpoint::OnMessageReceived.connect(boost::bind(&ClusterListener::AsyncMessageHandler, this, _1, _2));
@ -712,7 +712,7 @@ void ClusterListener::SetSecurityInfo(const Dictionary::Ptr& message, const Dyna
message->Set("security", security); message->Set("security", security);
} }
void ClusterListener::CheckResultHandler(const Service::Ptr& service, const CheckResult::Ptr& cr, const String& authority) void ClusterListener::CheckResultHandler(const Checkable::Ptr& service, const CheckResult::Ptr& cr, const String& authority)
{ {
if (!authority.IsEmpty() && authority != GetIdentity()) if (!authority.IsEmpty() && authority != GetIdentity())
return; return;
@ -731,7 +731,7 @@ void ClusterListener::CheckResultHandler(const Service::Ptr& service, const Chec
AsyncRelayMessage(Endpoint::Ptr(), message, true); AsyncRelayMessage(Endpoint::Ptr(), message, true);
} }
void ClusterListener::NextCheckChangedHandler(const Service::Ptr& service, double nextCheck, const String& authority) void ClusterListener::NextCheckChangedHandler(const Checkable::Ptr& service, double nextCheck, const String& authority)
{ {
if (!authority.IsEmpty() && authority != GetIdentity()) if (!authority.IsEmpty() && authority != GetIdentity())
return; return;
@ -764,12 +764,12 @@ void ClusterListener::NextNotificationChangedHandler(const Notification::Ptr& no
message->Set("method", "cluster::SetNextNotification"); message->Set("method", "cluster::SetNextNotification");
message->Set("params", params); message->Set("params", params);
SetSecurityInfo(message, notification->GetService(), DomainPrivRead); SetSecurityInfo(message, notification->GetCheckable(), DomainPrivRead);
AsyncRelayMessage(Endpoint::Ptr(), message, true); AsyncRelayMessage(Endpoint::Ptr(), message, true);
} }
void ClusterListener::ForceNextCheckChangedHandler(const Service::Ptr& service, bool forced, const String& authority) void ClusterListener::ForceNextCheckChangedHandler(const Checkable::Ptr& service, bool forced, const String& authority)
{ {
if (!authority.IsEmpty() && authority != GetIdentity()) if (!authority.IsEmpty() && authority != GetIdentity())
return; return;
@ -788,7 +788,7 @@ void ClusterListener::ForceNextCheckChangedHandler(const Service::Ptr& service,
AsyncRelayMessage(Endpoint::Ptr(), message, true); AsyncRelayMessage(Endpoint::Ptr(), message, true);
} }
void ClusterListener::ForceNextNotificationChangedHandler(const Service::Ptr& service, bool forced, const String& authority) void ClusterListener::ForceNextNotificationChangedHandler(const Checkable::Ptr& service, bool forced, const String& authority)
{ {
if (!authority.IsEmpty() && authority != GetIdentity()) if (!authority.IsEmpty() && authority != GetIdentity())
return; return;
@ -807,7 +807,7 @@ void ClusterListener::ForceNextNotificationChangedHandler(const Service::Ptr& se
AsyncRelayMessage(Endpoint::Ptr(), message, true); AsyncRelayMessage(Endpoint::Ptr(), message, true);
} }
void ClusterListener::EnableActiveChecksChangedHandler(const Service::Ptr& service, bool enabled, const String& authority) void ClusterListener::EnableActiveChecksChangedHandler(const Checkable::Ptr& service, bool enabled, const String& authority)
{ {
if (!authority.IsEmpty() && authority != GetIdentity()) if (!authority.IsEmpty() && authority != GetIdentity())
return; return;
@ -826,7 +826,7 @@ void ClusterListener::EnableActiveChecksChangedHandler(const Service::Ptr& servi
AsyncRelayMessage(Endpoint::Ptr(), message, true); AsyncRelayMessage(Endpoint::Ptr(), message, true);
} }
void ClusterListener::EnablePassiveChecksChangedHandler(const Service::Ptr& service, bool enabled, const String& authority) void ClusterListener::EnablePassiveChecksChangedHandler(const Checkable::Ptr& service, bool enabled, const String& authority)
{ {
if (!authority.IsEmpty() && authority != GetIdentity()) if (!authority.IsEmpty() && authority != GetIdentity())
return; return;
@ -845,7 +845,7 @@ void ClusterListener::EnablePassiveChecksChangedHandler(const Service::Ptr& serv
AsyncRelayMessage(Endpoint::Ptr(), message, true); AsyncRelayMessage(Endpoint::Ptr(), message, true);
} }
void ClusterListener::EnableNotificationsChangedHandler(const Service::Ptr& service, bool enabled, const String& authority) void ClusterListener::EnableNotificationsChangedHandler(const Checkable::Ptr& service, bool enabled, const String& authority)
{ {
if (!authority.IsEmpty() && authority != GetIdentity()) if (!authority.IsEmpty() && authority != GetIdentity())
return; return;
@ -864,7 +864,7 @@ void ClusterListener::EnableNotificationsChangedHandler(const Service::Ptr& serv
AsyncRelayMessage(Endpoint::Ptr(), message, true); AsyncRelayMessage(Endpoint::Ptr(), message, true);
} }
void ClusterListener::EnableFlappingChangedHandler(const Service::Ptr& service, bool enabled, const String& authority) void ClusterListener::EnableFlappingChangedHandler(const Checkable::Ptr& service, bool enabled, const String& authority)
{ {
if (!authority.IsEmpty() && authority != GetIdentity()) if (!authority.IsEmpty() && authority != GetIdentity())
return; return;
@ -883,7 +883,7 @@ void ClusterListener::EnableFlappingChangedHandler(const Service::Ptr& service,
AsyncRelayMessage(Endpoint::Ptr(), message, true); AsyncRelayMessage(Endpoint::Ptr(), message, true);
} }
void ClusterListener::CommentAddedHandler(const Service::Ptr& service, const Comment::Ptr& comment, const String& authority) void ClusterListener::CommentAddedHandler(const Checkable::Ptr& service, const Comment::Ptr& comment, const String& authority)
{ {
if (!authority.IsEmpty() && authority != GetIdentity()) if (!authority.IsEmpty() && authority != GetIdentity())
return; return;
@ -902,7 +902,7 @@ void ClusterListener::CommentAddedHandler(const Service::Ptr& service, const Com
AsyncRelayMessage(Endpoint::Ptr(), message, true); AsyncRelayMessage(Endpoint::Ptr(), message, true);
} }
void ClusterListener::CommentRemovedHandler(const Service::Ptr& service, const Comment::Ptr& comment, const String& authority) void ClusterListener::CommentRemovedHandler(const Checkable::Ptr& service, const Comment::Ptr& comment, const String& authority)
{ {
if (!authority.IsEmpty() && authority != GetIdentity()) if (!authority.IsEmpty() && authority != GetIdentity())
return; return;
@ -921,7 +921,7 @@ void ClusterListener::CommentRemovedHandler(const Service::Ptr& service, const C
AsyncRelayMessage(Endpoint::Ptr(), message, true); AsyncRelayMessage(Endpoint::Ptr(), message, true);
} }
void ClusterListener::DowntimeAddedHandler(const Service::Ptr& service, const Downtime::Ptr& downtime, const String& authority) void ClusterListener::DowntimeAddedHandler(const Checkable::Ptr& service, const Downtime::Ptr& downtime, const String& authority)
{ {
if (!authority.IsEmpty() && authority != GetIdentity()) if (!authority.IsEmpty() && authority != GetIdentity())
return; return;
@ -940,7 +940,7 @@ void ClusterListener::DowntimeAddedHandler(const Service::Ptr& service, const Do
AsyncRelayMessage(Endpoint::Ptr(), message, true); AsyncRelayMessage(Endpoint::Ptr(), message, true);
} }
void ClusterListener::DowntimeRemovedHandler(const Service::Ptr& service, const Downtime::Ptr& downtime, const String& authority) void ClusterListener::DowntimeRemovedHandler(const Checkable::Ptr& service, const Downtime::Ptr& downtime, const String& authority)
{ {
if (!authority.IsEmpty() && authority != GetIdentity()) if (!authority.IsEmpty() && authority != GetIdentity())
return; return;
@ -959,7 +959,7 @@ void ClusterListener::DowntimeRemovedHandler(const Service::Ptr& service, const
AsyncRelayMessage(Endpoint::Ptr(), message, true); AsyncRelayMessage(Endpoint::Ptr(), message, true);
} }
void ClusterListener::AcknowledgementSetHandler(const Service::Ptr& service, const String& author, const String& comment, AcknowledgementType type, double expiry, const String& authority) void ClusterListener::AcknowledgementSetHandler(const Checkable::Ptr& service, const String& author, const String& comment, AcknowledgementType type, double expiry, const String& authority)
{ {
if (!authority.IsEmpty() && authority != GetIdentity()) if (!authority.IsEmpty() && authority != GetIdentity())
return; return;
@ -981,7 +981,7 @@ void ClusterListener::AcknowledgementSetHandler(const Service::Ptr& service, con
AsyncRelayMessage(Endpoint::Ptr(), message, true); AsyncRelayMessage(Endpoint::Ptr(), message, true);
} }
void ClusterListener::AcknowledgementClearedHandler(const Service::Ptr& service, const String& authority) void ClusterListener::AcknowledgementClearedHandler(const Checkable::Ptr& service, const String& authority)
{ {
if (!authority.IsEmpty() && authority != GetIdentity()) if (!authority.IsEmpty() && authority != GetIdentity())
return; return;
@ -1061,7 +1061,7 @@ void ClusterListener::MessageHandler(const Endpoint::Ptr& sender, const Dictiona
String svc = params->Get("service"); String svc = params->Get("service");
Service::Ptr service = Service::GetByName(svc); Checkable::Ptr service = Checkable::GetByName(svc);
if (!service) if (!service)
return; return;
@ -1085,7 +1085,7 @@ void ClusterListener::MessageHandler(const Endpoint::Ptr& sender, const Dictiona
String svc = params->Get("service"); String svc = params->Get("service");
Service::Ptr service = Service::GetByName(svc); Checkable::Ptr service = Checkable::GetByName(svc);
if (!service) if (!service)
return; return;
@ -1106,7 +1106,7 @@ void ClusterListener::MessageHandler(const Endpoint::Ptr& sender, const Dictiona
String svc = params->Get("service"); String svc = params->Get("service");
Service::Ptr service = Service::GetByName(svc); Checkable::Ptr service = Checkable::GetByName(svc);
if (!service) if (!service)
return; return;
@ -1127,7 +1127,7 @@ void ClusterListener::MessageHandler(const Endpoint::Ptr& sender, const Dictiona
String svc = params->Get("service"); String svc = params->Get("service");
Service::Ptr service = Service::GetByName(svc); Checkable::Ptr service = Checkable::GetByName(svc);
if (!service) if (!service)
return; return;
@ -1148,7 +1148,7 @@ void ClusterListener::MessageHandler(const Endpoint::Ptr& sender, const Dictiona
String svc = params->Get("service"); String svc = params->Get("service");
Service::Ptr service = Service::GetByName(svc); Checkable::Ptr service = Checkable::GetByName(svc);
if (!service) if (!service)
return; return;
@ -1169,7 +1169,7 @@ void ClusterListener::MessageHandler(const Endpoint::Ptr& sender, const Dictiona
String svc = params->Get("service"); String svc = params->Get("service");
Service::Ptr service = Service::GetByName(svc); Checkable::Ptr service = Checkable::GetByName(svc);
if (!service) if (!service)
return; return;
@ -1190,7 +1190,7 @@ void ClusterListener::MessageHandler(const Endpoint::Ptr& sender, const Dictiona
String svc = params->Get("service"); String svc = params->Get("service");
Service::Ptr service = Service::GetByName(svc); Checkable::Ptr service = Checkable::GetByName(svc);
if (!service) if (!service)
return; return;
@ -1211,7 +1211,7 @@ void ClusterListener::MessageHandler(const Endpoint::Ptr& sender, const Dictiona
String svc = params->Get("service"); String svc = params->Get("service");
Service::Ptr service = Service::GetByName(svc); Checkable::Ptr service = Checkable::GetByName(svc);
if (!service) if (!service)
return; return;
@ -1237,7 +1237,7 @@ void ClusterListener::MessageHandler(const Endpoint::Ptr& sender, const Dictiona
if (!notification) if (!notification)
return; return;
Service::Ptr service = notification->GetService(); Checkable::Ptr service = notification->GetCheckable();
if (!service->HasPrivileges(sender->GetName(), DomainPrivCommand)) { if (!service->HasPrivileges(sender->GetName(), DomainPrivCommand)) {
Log(LogDebug, "cluster", "Not accepting cluster::SetNextNotification message from endpoint '" + sender->GetName() + "' for service '" + service->GetName() + "': Insufficient privileges."); Log(LogDebug, "cluster", "Not accepting cluster::SetNextNotification message from endpoint '" + sender->GetName() + "' for service '" + service->GetName() + "': Insufficient privileges.");
@ -1255,7 +1255,7 @@ void ClusterListener::MessageHandler(const Endpoint::Ptr& sender, const Dictiona
String svc = params->Get("service"); String svc = params->Get("service");
Service::Ptr service = Service::GetByName(svc); Checkable::Ptr service = Checkable::GetByName(svc);
if (!service) if (!service)
return; return;
@ -1277,7 +1277,7 @@ void ClusterListener::MessageHandler(const Endpoint::Ptr& sender, const Dictiona
String svc = params->Get("service"); String svc = params->Get("service");
Service::Ptr service = Service::GetByName(svc); Checkable::Ptr service = Checkable::GetByName(svc);
if (!service) if (!service)
return; return;
@ -1298,7 +1298,7 @@ void ClusterListener::MessageHandler(const Endpoint::Ptr& sender, const Dictiona
String svc = params->Get("service"); String svc = params->Get("service");
Service::Ptr service = Service::GetByName(svc); Checkable::Ptr service = Checkable::GetByName(svc);
if (!service) if (!service)
return; return;
@ -1323,7 +1323,7 @@ void ClusterListener::MessageHandler(const Endpoint::Ptr& sender, const Dictiona
String svc = params->Get("service"); String svc = params->Get("service");
Service::Ptr service = Service::GetByName(svc); Checkable::Ptr service = Checkable::GetByName(svc);
if (!service) if (!service)
return; return;
@ -1344,7 +1344,7 @@ void ClusterListener::MessageHandler(const Endpoint::Ptr& sender, const Dictiona
String svc = params->Get("service"); String svc = params->Get("service");
Service::Ptr service = Service::GetByName(svc); Checkable::Ptr service = Checkable::GetByName(svc);
if (!service) if (!service)
return; return;
@ -1368,7 +1368,7 @@ void ClusterListener::MessageHandler(const Endpoint::Ptr& sender, const Dictiona
String svc = params->Get("service"); String svc = params->Get("service");
Service::Ptr service = Service::GetByName(svc); Checkable::Ptr service = Checkable::GetByName(svc);
if (!service) if (!service)
return; return;

View File

@ -87,21 +87,21 @@ private:
Stream::Ptr m_LogFile; Stream::Ptr m_LogFile;
size_t m_LogMessageCount; size_t m_LogMessageCount;
void CheckResultHandler(const Service::Ptr& service, const CheckResult::Ptr& cr, const String& authority); void CheckResultHandler(const Checkable::Ptr& service, const CheckResult::Ptr& cr, const String& authority);
void NextCheckChangedHandler(const Service::Ptr& service, double nextCheck, const String& authority); void NextCheckChangedHandler(const Checkable::Ptr& service, double nextCheck, const String& authority);
void NextNotificationChangedHandler(const Notification::Ptr& notification, double nextCheck, const String& authority); void NextNotificationChangedHandler(const Notification::Ptr& notification, double nextCheck, const String& authority);
void ForceNextCheckChangedHandler(const Service::Ptr& service, bool forced, const String& authority); void ForceNextCheckChangedHandler(const Checkable::Ptr& service, bool forced, const String& authority);
void ForceNextNotificationChangedHandler(const Service::Ptr& service, bool forced, const String& authority); void ForceNextNotificationChangedHandler(const Checkable::Ptr& service, bool forced, const String& authority);
void EnableActiveChecksChangedHandler(const Service::Ptr& service, bool enabled, const String& authority); void EnableActiveChecksChangedHandler(const Checkable::Ptr& service, bool enabled, const String& authority);
void EnablePassiveChecksChangedHandler(const Service::Ptr& service, bool enabled, const String& authority); void EnablePassiveChecksChangedHandler(const Checkable::Ptr& service, bool enabled, const String& authority);
void EnableNotificationsChangedHandler(const Service::Ptr& service, bool enabled, const String& authority); void EnableNotificationsChangedHandler(const Checkable::Ptr& service, bool enabled, const String& authority);
void EnableFlappingChangedHandler(const Service::Ptr& service, bool enabled, const String& authority); void EnableFlappingChangedHandler(const Checkable::Ptr& service, bool enabled, const String& authority);
void CommentAddedHandler(const Service::Ptr& service, const Comment::Ptr& comment, const String& authority); void CommentAddedHandler(const Checkable::Ptr& service, const Comment::Ptr& comment, const String& authority);
void CommentRemovedHandler(const Service::Ptr& service, const Comment::Ptr& comment, const String& authority); void CommentRemovedHandler(const Checkable::Ptr& service, const Comment::Ptr& comment, const String& authority);
void DowntimeAddedHandler(const Service::Ptr& service, const Downtime::Ptr& downtime, const String& authority); void DowntimeAddedHandler(const Checkable::Ptr& service, const Downtime::Ptr& downtime, const String& authority);
void DowntimeRemovedHandler(const Service::Ptr& service, const Downtime::Ptr& downtime, const String& authority); void DowntimeRemovedHandler(const Checkable::Ptr& service, const Downtime::Ptr& downtime, const String& authority);
void AcknowledgementSetHandler(const Service::Ptr& service, const String& author, const String& comment, AcknowledgementType type, double expiry, const String& authority); void AcknowledgementSetHandler(const Checkable::Ptr& service, const String& author, const String& comment, AcknowledgementType type, double expiry, const String& authority);
void AcknowledgementClearedHandler(const Service::Ptr& service, const String& authority); void AcknowledgementClearedHandler(const Checkable::Ptr& service, const String& authority);
void AsyncMessageHandler(const Endpoint::Ptr& sender, const Dictionary::Ptr& message); void AsyncMessageHandler(const Endpoint::Ptr& sender, const Dictionary::Ptr& message);
void MessageHandler(const Endpoint::Ptr& sender, const Dictionary::Ptr& message); void MessageHandler(const Endpoint::Ptr& sender, const Dictionary::Ptr& message);

View File

@ -65,12 +65,12 @@ void CompatLogger::Start(void)
{ {
DynamicObject::Start(); DynamicObject::Start();
Service::OnNewCheckResult.connect(bind(&CompatLogger::CheckResultHandler, this, _1, _2)); Checkable::OnNewCheckResult.connect(bind(&CompatLogger::CheckResultHandler, this, _1, _2));
Service::OnNotificationSentToUser.connect(bind(&CompatLogger::NotificationSentHandler, this, _1, _2, _3, _4, _5, _6, _7, _8)); Checkable::OnNotificationSentToUser.connect(bind(&CompatLogger::NotificationSentHandler, this, _1, _2, _3, _4, _5, _6, _7, _8));
Service::OnFlappingChanged.connect(bind(&CompatLogger::FlappingHandler, this, _1, _2)); Checkable::OnFlappingChanged.connect(bind(&CompatLogger::FlappingHandler, this, _1, _2));
Service::OnDowntimeTriggered.connect(boost::bind(&CompatLogger::TriggerDowntimeHandler, this, _1, _2)); Checkable::OnDowntimeTriggered.connect(boost::bind(&CompatLogger::TriggerDowntimeHandler, this, _1, _2));
Service::OnDowntimeRemoved.connect(boost::bind(&CompatLogger::RemoveDowntimeHandler, this, _1, _2)); Checkable::OnDowntimeRemoved.connect(boost::bind(&CompatLogger::RemoveDowntimeHandler, this, _1, _2));
Service::OnEventCommandExecuted.connect(bind(&CompatLogger::EventCommandHandler, this, _1)); Checkable::OnEventCommandExecuted.connect(bind(&CompatLogger::EventCommandHandler, this, _1));
ExternalCommandProcessor::OnNewExternalCommand.connect(boost::bind(&CompatLogger::ExternalCommandHandler, this, _2, _3)); ExternalCommandProcessor::OnNewExternalCommand.connect(boost::bind(&CompatLogger::ExternalCommandHandler, this, _2, _3));
m_RotationTimer = make_shared<Timer>(); m_RotationTimer = make_shared<Timer>();
@ -84,9 +84,17 @@ void CompatLogger::Start(void)
/** /**
* @threadsafety Always. * @threadsafety Always.
*/ */
void CompatLogger::CheckResultHandler(const Service::Ptr& service, const CheckResult::Ptr &cr) void CompatLogger::CheckResultHandler(const Checkable::Ptr& checkable, const CheckResult::Ptr &cr)
{ {
Host::Ptr host = service->GetHost(); bool is_service = checkable->GetType() == DynamicType::GetByName("Service");
Host::Ptr host;
Service::Ptr service;
if (is_service) {
service = static_pointer_cast<Service>(checkable);
host = static_pointer_cast<Service>(checkable)->GetHost();
} else
host = static_pointer_cast<Host>(checkable);
Dictionary::Ptr vars_after = cr->GetVarsAfter(); Dictionary::Ptr vars_after = cr->GetVarsAfter();
@ -114,39 +122,30 @@ void CompatLogger::CheckResultHandler(const Service::Ptr& service, const CheckRe
output = CompatUtility::GetCheckResultOutput(cr); output = CompatUtility::GetCheckResultOutput(cr);
std::ostringstream msgbuf; std::ostringstream msgbuf;
msgbuf << "SERVICE ALERT: "
<< host->GetName() << ";"
<< service->GetShortName() << ";"
<< Service::StateToString(static_cast<ServiceState>(state_after)) << ";"
<< Service::StateTypeToString(static_cast<StateType>(stateType_after)) << ";"
<< attempt_after << ";"
<< output << ""
<< "";
{ if (is_service) {
ObjectLock olock(this); msgbuf << "SERVICE ALERT: "
WriteLine(msgbuf.str());
}
if (service == host->GetCheckService()) {
std::ostringstream msgbuf;
msgbuf << "HOST ALERT: "
<< host->GetName() << ";" << host->GetName() << ";"
<< Host::StateToString(Host::CalculateState(static_cast<ServiceState>(state_after), host_reachable_after)) << ";" << service->GetShortName() << ";"
<< Service::StateToString(static_cast<ServiceState>(state_after)) << ";"
<< Service::StateTypeToString(static_cast<StateType>(stateType_after)) << ";" << Service::StateTypeToString(static_cast<StateType>(stateType_after)) << ";"
<< attempt_after << ";" << attempt_after << ";"
<< output << "" << output << ""
<< ""; << "";
} else {
{ msgbuf << "HOST ALERT: "
ObjectLock olock(this); << host->GetName() << ";"
WriteLine(msgbuf.str()); << Host::StateToString(Host::CalculateState(static_cast<ServiceState>(state_after), host_reachable_after)) << ";"
} << Host::StateTypeToString(static_cast<StateType>(stateType_after)) << ";"
<< attempt_after << ";"
<< output << ""
<< "";
} }
{ {
ObjectLock olock(this); ObjectLock olock(this);
WriteLine(msgbuf.str());
Flush(); Flush();
} }
} }
@ -154,42 +153,41 @@ void CompatLogger::CheckResultHandler(const Service::Ptr& service, const CheckRe
/** /**
* @threadsafety Always. * @threadsafety Always.
*/ */
void CompatLogger::TriggerDowntimeHandler(const Service::Ptr& service, const Downtime::Ptr& downtime) void CompatLogger::TriggerDowntimeHandler(const Checkable::Ptr& checkable, const Downtime::Ptr& downtime)
{ {
Host::Ptr host = service->GetHost(); bool is_service = checkable->GetType() == DynamicType::GetByName("Service");
Host::Ptr host;
Service::Ptr service;
if (is_service) {
service = static_pointer_cast<Service>(checkable);
host = static_pointer_cast<Service>(checkable)->GetHost();
} else
host = static_pointer_cast<Host>(checkable);
if (!downtime) if (!downtime)
return; return;
std::ostringstream msgbuf; std::ostringstream msgbuf;
msgbuf << "SERVICE DOWNTIME ALERT: "
<< host->GetName() << ";" if (is_service) {
<< service->GetShortName() << ";" msgbuf << "SERVICE DOWNTIME ALERT: "
<< "STARTED" << "; " << host->GetName() << ";"
<< "Service has entered a period of scheduled downtime." << 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); ObjectLock oLock(this);
WriteLine(msgbuf.str()); WriteLine(msgbuf.str());
}
if (service == host->GetCheckService()) {
std::ostringstream msgbuf;
msgbuf << "HOST DOWNTIME ALERT: "
<< host->GetName() << ";"
<< "STARTED" << "; "
<< "Service has entered a period of scheduled downtime."
<< "";
{
ObjectLock oLock(this);
WriteLine(msgbuf.str());
}
}
{
ObjectLock oLock(this);
Flush(); Flush();
} }
} }
@ -197,9 +195,17 @@ void CompatLogger::TriggerDowntimeHandler(const Service::Ptr& service, const Dow
/** /**
* @threadsafety Always. * @threadsafety Always.
*/ */
void CompatLogger::RemoveDowntimeHandler(const Service::Ptr& service, const Downtime::Ptr& downtime) void CompatLogger::RemoveDowntimeHandler(const Checkable::Ptr& checkable, const Downtime::Ptr& downtime)
{ {
Host::Ptr host = service->GetHost(); bool is_service = checkable->GetType() == DynamicType::GetByName("Service");
Host::Ptr host;
Service::Ptr service;
if (is_service) {
service = static_pointer_cast<Service>(checkable);
host = static_pointer_cast<Service>(checkable)->GetHost();
} else
host = static_pointer_cast<Host>(checkable);
if (!downtime) if (!downtime)
return; return;
@ -211,39 +217,30 @@ void CompatLogger::RemoveDowntimeHandler(const Service::Ptr& service, const Down
downtime_output = "Scheduled downtime for service has been cancelled."; downtime_output = "Scheduled downtime for service has been cancelled.";
downtime_state_str = "CANCELLED"; downtime_state_str = "CANCELLED";
} else { } else {
downtime_output = "Service has exited from a period of scheduled downtime."; downtime_output = "Checkable has exited from a period of scheduled downtime.";
downtime_state_str = "STOPPED"; downtime_state_str = "STOPPED";
} }
std::ostringstream msgbuf; std::ostringstream msgbuf;
msgbuf << "SERVICE DOWNTIME ALERT: "
<< host->GetName() << ";"
<< service->GetShortName() << ";"
<< downtime_state_str << "; "
<< downtime_output
<< "";
{ if (is_service) {
ObjectLock oLock(this); msgbuf << "SERVICE DOWNTIME ALERT: "
WriteLine(msgbuf.str()); << host->GetName() << ";"
} << service->GetShortName() << ";"
<< downtime_state_str << "; "
if (service == host->GetCheckService()) { << downtime_output
std::ostringstream msgbuf; << "";
} else {
msgbuf << "HOST DOWNTIME ALERT: " msgbuf << "HOST DOWNTIME ALERT: "
<< host->GetName() << ";" << host->GetName() << ";"
<< downtime_state_str << "; " << downtime_state_str << "; "
<< downtime_output << downtime_output
<< ""; << "";
{
ObjectLock oLock(this);
WriteLine(msgbuf.str());
}
} }
{ {
ObjectLock oLock(this); ObjectLock oLock(this);
WriteLine(msgbuf.str());
Flush(); Flush();
} }
} }
@ -251,17 +248,29 @@ void CompatLogger::RemoveDowntimeHandler(const Service::Ptr& service, const Down
/** /**
* @threadsafety Always. * @threadsafety Always.
*/ */
void CompatLogger::NotificationSentHandler(const Notification::Ptr& notification, const Service::Ptr& service, void CompatLogger::NotificationSentHandler(const Notification::Ptr& notification, const Checkable::Ptr& checkable,
const User::Ptr& user, NotificationType const& notification_type, CheckResult::Ptr const& cr, const User::Ptr& user, NotificationType const& notification_type, CheckResult::Ptr const& cr,
const String& author, const String& comment_text, const String& command_name) const String& author, const String& comment_text, const String& command_name)
{ {
Host::Ptr host = service->GetHost(); bool is_service = checkable->GetType() == DynamicType::GetByName("Service");
Host::Ptr host;
Service::Ptr service;
if (is_service) {
service = static_pointer_cast<Service>(checkable);
host = static_pointer_cast<Service>(checkable)->GetHost();
} else
host = static_pointer_cast<Host>(checkable);
String notification_type_str = Notification::NotificationTypeToString(notification_type); String notification_type_str = Notification::NotificationTypeToString(notification_type);
/* override problem notifications with their current state string */ /* override problem notifications with their current state string */
if (notification_type == NotificationProblem) if (notification_type == NotificationProblem) {
notification_type_str = Service::StateToString(service->GetState()); if (is_service)
notification_type_str = Service::StateToString(service->GetState());
else
notification_type_str = Host::StateToString(host->GetState());
}
String author_comment = ""; String author_comment = "";
if (notification_type == NotificationCustom || notification_type == NotificationAcknowledgement) { if (notification_type == NotificationCustom || notification_type == NotificationAcknowledgement) {
@ -276,41 +285,32 @@ void CompatLogger::NotificationSentHandler(const Notification::Ptr& notification
output = CompatUtility::GetCheckResultOutput(cr); output = CompatUtility::GetCheckResultOutput(cr);
std::ostringstream msgbuf; std::ostringstream msgbuf;
msgbuf << "SERVICE NOTIFICATION: "
<< user->GetName() << ";"
<< host->GetName() << ";"
<< service->GetShortName() << ";"
<< notification_type_str << ";"
<< command_name << ";"
<< output << ";"
<< author_comment
<< "";
{ if (is_service) {
ObjectLock oLock(this); msgbuf << "SERVICE NOTIFICATION: "
WriteLine(msgbuf.str()); << user->GetName() << ";"
} << host->GetName() << ";"
<< service->GetShortName() << ";"
if (service == host->GetCheckService()) { << notification_type_str << ";"
std::ostringstream msgbuf; << command_name << ";"
<< output << ";"
<< author_comment
<< "";
} else {
msgbuf << "HOST NOTIFICATION: " msgbuf << "HOST NOTIFICATION: "
<< user->GetName() << ";" << user->GetName() << ";"
<< host->GetName() << ";" << host->GetName() << ";"
<< notification_type_str << " " << notification_type_str << " "
<< "(" << Service::StateToString(service->GetState()) << ");" << "(" << Host::StateToString(host->GetState()) << ");"
<< command_name << ";" << command_name << ";"
<< output << ";" << output << ";"
<< author_comment << author_comment
<< ""; << "";
}
{ {
ObjectLock oLock(this); ObjectLock oLock(this);
WriteLine(msgbuf.str()); WriteLine(msgbuf.str());
}
}
{
ObjectLock oLock(this);
Flush(); Flush();
} }
} }
@ -318,20 +318,28 @@ void CompatLogger::NotificationSentHandler(const Notification::Ptr& notification
/** /**
* @threadsafety Always. * @threadsafety Always.
*/ */
void CompatLogger::FlappingHandler(const Service::Ptr& service, FlappingState flapping_state) void CompatLogger::FlappingHandler(const Checkable::Ptr& checkable, FlappingState flapping_state)
{ {
Host::Ptr host = service->GetHost(); bool is_service = checkable->GetType() == DynamicType::GetByName("Service");
Host::Ptr host;
Service::Ptr service;
if (is_service) {
service = static_pointer_cast<Service>(checkable);
host = static_pointer_cast<Service>(checkable)->GetHost();
} else
host = static_pointer_cast<Host>(checkable);
String flapping_state_str; String flapping_state_str;
String flapping_output; String flapping_output;
switch (flapping_state) { switch (flapping_state) {
case FlappingStarted: case FlappingStarted:
flapping_output = "Service appears to have started flapping (" + Convert::ToString(service->GetFlappingCurrent()) + "% change >= " + Convert::ToString(service->GetFlappingThreshold()) + "% threshold)"; flapping_output = "Checkable appears to have started flapping (" + Convert::ToString(service->GetFlappingCurrent()) + "% change >= " + Convert::ToString(service->GetFlappingThreshold()) + "% threshold)";
flapping_state_str = "STARTED"; flapping_state_str = "STARTED";
break; break;
case FlappingStopped: case FlappingStopped:
flapping_output = "Service appears to have stopped flapping (" + Convert::ToString(service->GetFlappingCurrent()) + "% change < " + Convert::ToString(service->GetFlappingThreshold()) + "% threshold)"; flapping_output = "Checkable appears to have stopped flapping (" + Convert::ToString(service->GetFlappingCurrent()) + "% change < " + Convert::ToString(service->GetFlappingThreshold()) + "% threshold)";
flapping_state_str = "STOPPED"; flapping_state_str = "STOPPED";
break; break;
case FlappingDisabled: case FlappingDisabled:
@ -344,34 +352,25 @@ void CompatLogger::FlappingHandler(const Service::Ptr& service, FlappingState fl
} }
std::ostringstream msgbuf; std::ostringstream msgbuf;
msgbuf << "SERVICE FLAPPING ALERT: "
<< host->GetName() << ";"
<< service->GetShortName() << ";"
<< flapping_state_str << "; "
<< flapping_output
<< "";
{ if (is_service) {
ObjectLock oLock(this); msgbuf << "SERVICE FLAPPING ALERT: "
WriteLine(msgbuf.str()); << host->GetName() << ";"
} << service->GetShortName() << ";"
<< flapping_state_str << "; "
if (service == host->GetCheckService()) { << flapping_output
std::ostringstream msgbuf; << "";
} else {
msgbuf << "HOST FLAPPING ALERT: " msgbuf << "HOST FLAPPING ALERT: "
<< host->GetName() << ";" << host->GetName() << ";"
<< flapping_state_str << "; " << flapping_state_str << "; "
<< flapping_output << flapping_output
<< ""; << "";
}
{ {
ObjectLock oLock(this); ObjectLock oLock(this);
WriteLine(msgbuf.str()); WriteLine(msgbuf.str());
}
}
{
ObjectLock oLock(this);
Flush(); Flush();
} }
} }
@ -390,48 +389,44 @@ void CompatLogger::ExternalCommandHandler(const String& command, const std::vect
} }
} }
void CompatLogger::EventCommandHandler(const Service::Ptr& service) void CompatLogger::EventCommandHandler(const Checkable::Ptr& checkable)
{ {
Host::Ptr host = service->GetHost(); bool is_service = checkable->GetType() == DynamicType::GetByName("Service");
Host::Ptr host;
Service::Ptr service;
if (is_service) {
service = static_pointer_cast<Service>(checkable);
host = static_pointer_cast<Service>(checkable)->GetHost();
} else
host = static_pointer_cast<Host>(checkable);
EventCommand::Ptr event_command = service->GetEventCommand(); EventCommand::Ptr event_command = service->GetEventCommand();
String event_command_name = event_command->GetName(); String event_command_name = event_command->GetName();
String state = Service::StateToString(service->GetState());
String state_type = Service::StateTypeToString(service->GetStateType());
long current_attempt = service->GetCheckAttempt(); long current_attempt = service->GetCheckAttempt();
std::ostringstream msgbuf; std::ostringstream msgbuf;
msgbuf << "SERVICE EVENT HANDLER: " if (is_service) {
<< host->GetName() << ";" msgbuf << "SERVICE EVENT HANDLER: "
<< service->GetShortName() << ";" << host->GetName() << ";"
<< state << ";" << service->GetShortName() << ";"
<< state_type << ";" << Service::StateToString(service->GetState()) << ";"
<< current_attempt << ";" << Service::StateTypeToString(service->GetStateType()) << ";"
<< event_command_name;
{
ObjectLock oLock(this);
WriteLine(msgbuf.str());
}
if (service == host->GetCheckService()) {
std::ostringstream msgbuf;
msgbuf << "HOST EVENT HANDLER: "
<< host->GetName() << ";"
<< state << ";"
<< state_type << ";"
<< current_attempt << ";" << current_attempt << ";"
<< event_command_name; << event_command_name;
} else {
msgbuf << "HOST EVENT HANDLER: "
<< host->GetName() << ";"
<< Host::StateToString(host->GetState()) << ";"
<< Host::StateTypeToString(host->GetStateType()) << ";"
<< current_attempt << ";"
<< event_command_name;
}
{ {
ObjectLock oLock(this); ObjectLock oLock(this);
WriteLine(msgbuf.str()); WriteLine(msgbuf.str());
}
}
{
ObjectLock oLock(this);
Flush(); Flush();
} }
} }
@ -488,17 +483,8 @@ void CompatLogger::ReopenFile(bool rotate)
WriteLine("LOG VERSION: 2.0"); WriteLine("LOG VERSION: 2.0");
BOOST_FOREACH(const Host::Ptr& host, DynamicType::GetObjects<Host>()) { BOOST_FOREACH(const Host::Ptr& host, DynamicType::GetObjects<Host>()) {
Service::Ptr hc = host->GetCheckService();
if (!hc)
continue;
bool reachable = host->IsReachable();
ObjectLock olock(hc);
String output; String output;
CheckResult::Ptr cr = hc->GetLastCheckResult(); CheckResult::Ptr cr = host->GetLastCheckResult();
if (cr) if (cr)
output = CompatUtility::GetCheckResultOutput(cr); output = CompatUtility::GetCheckResultOutput(cr);
@ -506,9 +492,9 @@ void CompatLogger::ReopenFile(bool rotate)
std::ostringstream msgbuf; std::ostringstream msgbuf;
msgbuf << "CURRENT HOST STATE: " msgbuf << "CURRENT HOST STATE: "
<< host->GetName() << ";" << host->GetName() << ";"
<< Host::StateToString(Host::CalculateState(hc->GetState(), reachable)) << ";" << Host::StateToString(host->GetState()) << ";"
<< Service::StateTypeToString(hc->GetStateType()) << ";" << Host::StateTypeToString(host->GetStateType()) << ";"
<< hc->GetCheckAttempt() << ";" << host->GetCheckAttempt() << ";"
<< output << ""; << output << "";
WriteLine(msgbuf.str()); WriteLine(msgbuf.str());

View File

@ -50,15 +50,15 @@ private:
void WriteLine(const String& line); void WriteLine(const String& line);
void Flush(void); void Flush(void);
void CheckResultHandler(const Service::Ptr& service, const CheckResult::Ptr& cr); void CheckResultHandler(const Checkable::Ptr& service, const CheckResult::Ptr& cr);
void NotificationSentHandler(const Notification::Ptr& notification, const Service::Ptr& service, void NotificationSentHandler(const Notification::Ptr& notification, const Checkable::Ptr& service,
const User::Ptr& user, NotificationType const& notification_type, CheckResult::Ptr const& cr, const User::Ptr& user, NotificationType const& notification_type, CheckResult::Ptr const& cr,
const String& author, const String& comment_text, const String& command_name); const String& author, const String& comment_text, const String& command_name);
void FlappingHandler(const Service::Ptr& service, FlappingState flapping_state); void FlappingHandler(const Checkable::Ptr& service, FlappingState flapping_state);
void TriggerDowntimeHandler(const Service::Ptr& service, const Downtime::Ptr& downtime); void TriggerDowntimeHandler(const Checkable::Ptr& service, const Downtime::Ptr& downtime);
void RemoveDowntimeHandler(const Service::Ptr& service, const Downtime::Ptr& downtime); void RemoveDowntimeHandler(const Checkable::Ptr& service, const Downtime::Ptr& downtime);
void ExternalCommandHandler(const String& command, const std::vector<String>& arguments); void ExternalCommandHandler(const String& command, const std::vector<String>& arguments);
void EventCommandHandler(const Service::Ptr& service); void EventCommandHandler(const Checkable::Ptr& service);
Timer::Ptr m_RotationTimer; Timer::Ptr m_RotationTimer;
void RotationTimerHandler(void); void RotationTimerHandler(void);

View File

@ -82,12 +82,13 @@ void StatusDataWriter::Start(void)
Utility::QueueAsyncCallback(boost::bind(&StatusDataWriter::UpdateObjectsCache, this)); Utility::QueueAsyncCallback(boost::bind(&StatusDataWriter::UpdateObjectsCache, this));
} }
void StatusDataWriter::DumpComments(std::ostream& fp, const Service::Ptr& owner, CompatObjectType type) void StatusDataWriter::DumpComments(std::ostream& fp, const Checkable::Ptr& checkable)
{ {
Service::Ptr service; Dictionary::Ptr comments = checkable->GetComments();
Dictionary::Ptr comments = owner->GetComments();
Host::Ptr host = owner->GetHost(); Host::Ptr host;
Service::Ptr service;
tie(host, service) = GetHostService(checkable);
ObjectLock olock(comments); ObjectLock olock(comments);
@ -97,11 +98,11 @@ void StatusDataWriter::DumpComments(std::ostream& fp, const Service::Ptr& owner,
if (comment->IsExpired()) if (comment->IsExpired())
continue; continue;
if (type == CompatTypeHost) if (service)
fp << "hostcomment {" << "\n";
else
fp << "servicecomment {" << "\n" fp << "servicecomment {" << "\n"
<< "\t" << "service_description=" << owner->GetShortName() << "\n"; << "\t" << "service_description=" << service->GetShortName() << "\n";
else
fp << "hostcomment {" << "\n";
fp << "\t" "host_name=" << host->GetName() << "\n" fp << "\t" "host_name=" << host->GetName() << "\n"
"\t" "comment_id=" << comment->GetLegacyId() << "\n" "\t" "comment_id=" << comment->GetLegacyId() << "\n"
@ -157,11 +158,13 @@ void StatusDataWriter::DumpCommand(std::ostream& fp, const Command::Ptr& command
"\n"; "\n";
} }
void StatusDataWriter::DumpDowntimes(std::ostream& fp, const Service::Ptr& owner, CompatObjectType type) void StatusDataWriter::DumpDowntimes(std::ostream& fp, const Checkable::Ptr& checkable)
{ {
Host::Ptr host = owner->GetHost(); Dictionary::Ptr downtimes = checkable->GetDowntimes();
Dictionary::Ptr downtimes = owner->GetDowntimes(); Host::Ptr host;
Service::Ptr service;
tie(host, service) = GetHostService(checkable);
ObjectLock olock(downtimes); ObjectLock olock(downtimes);
@ -171,11 +174,11 @@ void StatusDataWriter::DumpDowntimes(std::ostream& fp, const Service::Ptr& owner
if (downtime->IsExpired()) if (downtime->IsExpired())
continue; continue;
if (type == CompatTypeHost) if (service)
fp << "hostdowntime {" "\n";
else
fp << "servicedowntime {" << "\n" fp << "servicedowntime {" << "\n"
"\t" "service_description=" << owner->GetShortName() << "\n"; "\t" "service_description=" << service->GetShortName() << "\n";
else
fp << "hostdowntime {" "\n";
Downtime::Ptr triggeredByObj = Service::GetDowntimeByID(downtime->GetTriggeredBy()); Downtime::Ptr triggeredByObj = Service::GetDowntimeByID(downtime->GetTriggeredBy());
int triggeredByLegacy = 0; int triggeredByLegacy = 0;
@ -204,13 +207,9 @@ void StatusDataWriter::DumpHostStatus(std::ostream& fp, const Host::Ptr& host)
fp << "hoststatus {" << "\n" fp << "hoststatus {" << "\n"
<< "\t" << "host_name=" << host->GetName() << "\n"; << "\t" << "host_name=" << host->GetName() << "\n";
Service::Ptr hc = host->GetCheckService(); {
ObjectLock olock(hc); ObjectLock olock(host);
DumpCheckableStatusAttrs(fp, host);
if (hc) {
/* only dump status data information for Classic UI */
fp << "\t" "check_service=" << hc->GetShortName() << "\n";
DumpServiceStatusAttrs(fp, hc, CompatTypeHost);
} }
/* ugly but cgis parse only that */ /* ugly but cgis parse only that */
@ -221,10 +220,8 @@ void StatusDataWriter::DumpHostStatus(std::ostream& fp, const Host::Ptr& host)
fp << "\t" "}" "\n" fp << "\t" "}" "\n"
"\n"; "\n";
if (hc) { DumpDowntimes(fp, host);
DumpDowntimes(fp, hc, CompatTypeHost); DumpComments(fp, host);
DumpComments(fp, hc, CompatTypeHost);
}
} }
void StatusDataWriter::DumpHostObject(std::ostream& fp, const Host::Ptr& host) void StatusDataWriter::DumpHostObject(std::ostream& fp, const Host::Ptr& host)
@ -255,7 +252,7 @@ void StatusDataWriter::DumpHostObject(std::ostream& fp, const Host::Ptr& host)
if (!statusmap_image.IsEmpty()) if (!statusmap_image.IsEmpty())
fp << "\t" "statusmap_image" "\t" << statusmap_image << "\n"; fp << "\t" "statusmap_image" "\t" << statusmap_image << "\n";
std::set<Host::Ptr> parents = host->GetParentHosts(); std::set<Checkable::Ptr> parents = host->GetParents();
if (!parents.empty()) { if (!parents.empty()) {
fp << "\t" "parents" "\t"; fp << "\t" "parents" "\t";
@ -263,53 +260,41 @@ void StatusDataWriter::DumpHostObject(std::ostream& fp, const Host::Ptr& host)
fp << "\n"; fp << "\n";
} }
Service::Ptr hc = host->GetCheckService(); ObjectLock olock(host);
if (hc) {
ObjectLock olock(hc);
fp << "\t" "check_interval" "\t" << CompatUtility::GetServiceCheckInterval(hc) << "\n" fp << "\t" "check_interval" "\t" << CompatUtility::GetCheckableCheckInterval(host) << "\n"
"\t" "retry_interval" "\t" << CompatUtility::GetServiceRetryInterval(hc) << "\n" "\t" "retry_interval" "\t" << CompatUtility::GetCheckableRetryInterval(host) << "\n"
"\t" "max_check_attempts" "\t" << hc->GetMaxCheckAttempts() << "\n" "\t" "max_check_attempts" "\t" << host->GetMaxCheckAttempts() << "\n"
"\t" "active_checks_enabled" "\t" << CompatUtility::GetServiceActiveChecksEnabled(hc) << "\n" "\t" "active_checks_enabled" "\t" << CompatUtility::GetCheckableActiveChecksEnabled(host) << "\n"
"\t" "passive_checks_enabled" "\t" << CompatUtility::GetServicePassiveChecksEnabled(hc) << "\n" "\t" "passive_checks_enabled" "\t" << CompatUtility::GetCheckablePassiveChecksEnabled(host) << "\n"
"\t" "notifications_enabled" "\t" << CompatUtility::GetServiceNotificationsEnabled(hc) << "\n" "\t" "notifications_enabled" "\t" << CompatUtility::GetCheckableNotificationsEnabled(host) << "\n"
"\t" "notification_options" "\t" << "d,u,r" << "\n" "\t" "notification_options" "\t" << "d,u,r" << "\n"
"\t" "notification_interval" "\t" << CompatUtility::GetServiceNotificationNotificationInterval(hc) << "\n" "\t" "notification_interval" "\t" << CompatUtility::GetCheckableNotificationNotificationInterval(host) << "\n"
"\t" "event_handler_enabled" "\t" << CompatUtility::GetServiceEventHandlerEnabled(hc) << "\n"; "\t" "event_handler_enabled" "\t" << CompatUtility::GetCheckableEventHandlerEnabled(host) << "\n";
CheckCommand::Ptr checkcommand = hc->GetCheckCommand(); CheckCommand::Ptr checkcommand = host->GetCheckCommand();
if (checkcommand) if (checkcommand)
fp << "\t" "check_command" "\t" "check_" << checkcommand->GetName() << "\n"; fp << "\t" "check_command" "\t" "check_" << checkcommand->GetName() << "\n";
EventCommand::Ptr eventcommand = hc->GetEventCommand(); EventCommand::Ptr eventcommand = host->GetEventCommand();
if (eventcommand) if (eventcommand)
fp << "\t" "event_handler" "\t" "event_" << eventcommand->GetName() << "\n"; fp << "\t" "event_handler" "\t" "event_" << eventcommand->GetName() << "\n";
fp << "\t" "check_period" "\t" << CompatUtility::GetServiceCheckPeriod(hc) << "\n"; fp << "\t" "check_period" "\t" << CompatUtility::GetCheckableCheckPeriod(host) << "\n";
fp << "\t" "contacts" "\t"; fp << "\t" "contacts" "\t";
DumpNameList(fp, CompatUtility::GetServiceNotificationUsers(hc)); DumpNameList(fp, CompatUtility::GetCheckableNotificationUsers(host));
fp << "\n"; fp << "\n";
fp << "\t" "contact_groups" "\t"; fp << "\t" "contact_groups" "\t";
DumpNameList(fp, CompatUtility::GetServiceNotificationUserGroups(hc)); DumpNameList(fp, CompatUtility::GetCheckableNotificationUserGroups(host));
fp << "\n"; fp << "\n";
fp << "\t" << "initial_state" "\t" "o" "\n" fp << "\t" << "initial_state" "\t" "o" "\n"
"\t" "low_flap_threshold" "\t" << hc->GetFlappingThreshold() << "\n" "\t" "low_flap_threshold" "\t" << host->GetFlappingThreshold() << "\n"
"\t" "high_flap_threshold" "\t" << hc->GetFlappingThreshold() << "\n" "\t" "high_flap_threshold" "\t" << host->GetFlappingThreshold() << "\n"
"\t" "process_perf_data" "\t" << CompatUtility::GetServiceProcessPerformanceData(hc) << "\n" "\t" "process_perf_data" "\t" << CompatUtility::GetCheckableProcessPerformanceData(host) << "\n"
"\t" "check_freshness" "\t" "1" "\n"; "\t" "check_freshness" "\t" "1" "\n";
} else {
fp << "\t" << "check_interval" "\t" "60" "\n"
"\t" "retry_interval" "\t" "60" "\n"
"\t" "max_check_attempts" "\t" "1" "\n"
"\t" "active_checks_enabled" "\t" "0" << "\n"
"\t" "passive_checks_enabled" "\t" "0" "\n"
"\t" "notifications_enabled" "\t" "0" "\n";
}
fp << "\t" "host_groups" "\t"; fp << "\t" "host_groups" "\t";
bool first = true; bool first = true;
@ -341,30 +326,33 @@ void StatusDataWriter::DumpHostObject(std::ostream& fp, const Host::Ptr& host)
"\n"; "\n";
} }
void StatusDataWriter::DumpServiceStatusAttrs(std::ostream& fp, const Service::Ptr& service, CompatObjectType type) void StatusDataWriter::DumpCheckableStatusAttrs(std::ostream& fp, const Checkable::Ptr& checkable)
{ {
CheckResult::Ptr cr = service->GetLastCheckResult(); CheckResult::Ptr cr = checkable->GetLastCheckResult();
fp << "\t" << "check_command=check_" << CompatUtility::GetServiceCheckCommand(service) << "\n" fp << "\t" << "check_command=check_" << CompatUtility::GetCheckableCheckCommand(checkable) << "\n"
"\t" "event_handler=event_" << CompatUtility::GetServiceEventHandler(service) << "\n" "\t" "event_handler=event_" << CompatUtility::GetCheckableEventHandler(checkable) << "\n"
"\t" "check_period=" << CompatUtility::GetServiceCheckPeriod(service) << "\n" "\t" "check_period=" << CompatUtility::GetCheckableCheckPeriod(checkable) << "\n"
"\t" "check_interval=" << CompatUtility::GetServiceCheckInterval(service) << "\n" "\t" "check_interval=" << CompatUtility::GetCheckableCheckInterval(checkable) << "\n"
"\t" "retry_interval=" << CompatUtility::GetServiceRetryInterval(service) << "\n" "\t" "retry_interval=" << CompatUtility::GetCheckableRetryInterval(checkable) << "\n"
"\t" "has_been_checked=" << CompatUtility::GetServiceHasBeenChecked(service) << "\n" "\t" "has_been_checked=" << CompatUtility::GetCheckableHasBeenChecked(checkable) << "\n"
"\t" "should_be_scheduled=" << CompatUtility::GetServiceShouldBeScheduled(service) << "\n"; "\t" "should_be_scheduled=" << CompatUtility::GetCheckableShouldBeScheduled(checkable) << "\n";
if (cr) { if (cr) {
fp << "\t" << "check_execution_time=" << Convert::ToString(Service::CalculateExecutionTime(cr)) << "\n" fp << "\t" << "check_execution_time=" << Convert::ToString(Service::CalculateExecutionTime(cr)) << "\n"
"\t" "check_latency=" << Convert::ToString(Service::CalculateLatency(cr)) << "\n"; "\t" "check_latency=" << Convert::ToString(Service::CalculateLatency(cr)) << "\n";
} }
if (type == CompatTypeHost && service->IsHostCheck()) { Host::Ptr host;
fp << "\t" << "current_state=" << service->GetHost()->GetState() << "\n"; Service::Ptr service;
} else { tie(host, service) = GetHostService(checkable);
fp << "\t" << "current_state=" << CompatUtility::GetServiceCurrentState(service) << "\n";
}
fp << "\t" "state_type=" << service->GetStateType() << "\n" if (service)
fp << "\t" << "current_state=" << service->GetState() << "\n";
else
fp << "\t" << "current_state=" << host->GetState() << "\n";
fp << "\t" "state_type=" << checkable->GetStateType() << "\n"
"\t" "plugin_output=" << CompatUtility::GetCheckResultOutput(cr) << "\n" "\t" "plugin_output=" << CompatUtility::GetCheckResultOutput(cr) << "\n"
"\t" "long_plugin_output=" << CompatUtility::GetCheckResultLongOutput(cr) << "\n" "\t" "long_plugin_output=" << CompatUtility::GetCheckResultLongOutput(cr) << "\n"
"\t" "performance_data=" << CompatUtility::GetCheckResultPerfdata(cr) << "\n"; "\t" "performance_data=" << CompatUtility::GetCheckResultPerfdata(cr) << "\n";
@ -374,30 +362,30 @@ void StatusDataWriter::DumpServiceStatusAttrs(std::ostream& fp, const Service::P
"\t" "last_check=" << static_cast<long>(cr->GetScheduleEnd()) << "\n"; "\t" "last_check=" << static_cast<long>(cr->GetScheduleEnd()) << "\n";
} }
fp << "\t" << "next_check=" << static_cast<long>(service->GetNextCheck()) << "\n" fp << "\t" << "next_check=" << static_cast<long>(checkable->GetNextCheck()) << "\n"
"\t" "current_attempt=" << service->GetCheckAttempt() << "\n" "\t" "current_attempt=" << checkable->GetCheckAttempt() << "\n"
"\t" "max_attempts=" << service->GetMaxCheckAttempts() << "\n" "\t" "max_attempts=" << checkable->GetMaxCheckAttempts() << "\n"
"\t" "last_state_change=" << static_cast<long>(service->GetLastStateChange()) << "\n" "\t" "last_state_change=" << static_cast<long>(checkable->GetLastStateChange()) << "\n"
"\t" "last_hard_state_change=" << static_cast<long>(service->GetLastHardStateChange()) << "\n" "\t" "last_hard_state_change=" << static_cast<long>(checkable->GetLastHardStateChange()) << "\n"
"\t" "last_time_ok=" << static_cast<int>(service->GetLastStateOK()) << "\n" "\t" "last_time_ok=" << static_cast<int>(checkable->GetLastStateOK()) << "\n"
"\t" "last_time_warn=" << static_cast<int>(service->GetLastStateWarning()) << "\n" "\t" "last_time_warn=" << static_cast<int>(checkable->GetLastStateWarning()) << "\n"
"\t" "last_time_critical=" << static_cast<int>(service->GetLastStateCritical()) << "\n" "\t" "last_time_critical=" << static_cast<int>(checkable->GetLastStateCritical()) << "\n"
"\t" "last_time_unknown=" << static_cast<int>(service->GetLastStateUnknown()) << "\n" "\t" "last_time_unknown=" << static_cast<int>(checkable->GetLastStateUnknown()) << "\n"
"\t" "last_update=" << static_cast<long>(time(NULL)) << "\n" "\t" "last_update=" << static_cast<long>(time(NULL)) << "\n"
"\t" "notifications_enabled=" << CompatUtility::GetServiceNotificationsEnabled(service) << "\n" "\t" "notifications_enabled=" << CompatUtility::GetCheckableNotificationsEnabled(checkable) << "\n"
"\t" "active_checks_enabled=" << CompatUtility::GetServiceActiveChecksEnabled(service) << "\n" "\t" "active_checks_enabled=" << CompatUtility::GetCheckableActiveChecksEnabled(checkable) << "\n"
"\t" "passive_checks_enabled=" << CompatUtility::GetServicePassiveChecksEnabled(service) << "\n" "\t" "passive_checks_enabled=" << CompatUtility::GetCheckablePassiveChecksEnabled(checkable) << "\n"
"\t" "flap_detection_enabled=" << CompatUtility::GetServiceFlapDetectionEnabled(service) << "\n" "\t" "flap_detection_enabled=" << CompatUtility::GetCheckableFlapDetectionEnabled(checkable) << "\n"
"\t" "is_flapping=" << CompatUtility::GetServiceIsFlapping(service) << "\n" "\t" "is_flapping=" << CompatUtility::GetCheckableIsFlapping(checkable) << "\n"
"\t" "percent_state_change=" << CompatUtility::GetServicePercentStateChange(service) << "\n" "\t" "percent_state_change=" << CompatUtility::GetCheckablePercentStateChange(checkable) << "\n"
"\t" "problem_has_been_acknowledged=" << CompatUtility::GetServiceProblemHasBeenAcknowledged(service) << "\n" "\t" "problem_has_been_acknowledged=" << CompatUtility::GetCheckableProblemHasBeenAcknowledged(checkable) << "\n"
"\t" "acknowledgement_type=" << CompatUtility::GetServiceAcknowledgementType(service) << "\n" "\t" "acknowledgement_type=" << CompatUtility::GetCheckableAcknowledgementType(checkable) << "\n"
"\t" "acknowledgement_end_time=" << service->GetAcknowledgementExpiry() << "\n" "\t" "acknowledgement_end_time=" << checkable->GetAcknowledgementExpiry() << "\n"
"\t" "scheduled_downtime_depth=" << service->GetDowntimeDepth() << "\n" "\t" "scheduled_downtime_depth=" << checkable->GetDowntimeDepth() << "\n"
"\t" "last_notification=" << CompatUtility::GetServiceNotificationLastNotification(service) << "\n" "\t" "last_notification=" << CompatUtility::GetCheckableNotificationLastNotification(checkable) << "\n"
"\t" "next_notification=" << CompatUtility::GetServiceNotificationNextNotification(service) << "\n" "\t" "next_notification=" << CompatUtility::GetCheckableNotificationNextNotification(checkable) << "\n"
"\t" "current_notification_number=" << CompatUtility::GetServiceNotificationNotificationNumber(service) << "\n" "\t" "current_notification_number=" << CompatUtility::GetCheckableNotificationNotificationNumber(checkable) << "\n"
"\t" "modified_attributes=" << service->GetModifiedAttributes() << "\n"; "\t" "modified_attributes=" << checkable->GetModifiedAttributes() << "\n";
} }
void StatusDataWriter::DumpServiceStatus(std::ostream& fp, const Service::Ptr& service) void StatusDataWriter::DumpServiceStatus(std::ostream& fp, const Service::Ptr& service)
@ -410,14 +398,14 @@ void StatusDataWriter::DumpServiceStatus(std::ostream& fp, const Service::Ptr& s
{ {
ObjectLock olock(service); ObjectLock olock(service);
DumpServiceStatusAttrs(fp, service, CompatTypeService); DumpCheckableStatusAttrs(fp, service);
} }
fp << "\t" "}" "\n" fp << "\t" "}" "\n"
"\n"; "\n";
DumpDowntimes(fp, service, CompatTypeService); DumpDowntimes(fp, service);
DumpComments(fp, service, CompatTypeService); DumpComments(fp, service);
} }
void StatusDataWriter::DumpServiceObject(std::ostream& fp, const Service::Ptr& service) void StatusDataWriter::DumpServiceObject(std::ostream& fp, const Service::Ptr& service)
@ -431,19 +419,19 @@ void StatusDataWriter::DumpServiceObject(std::ostream& fp, const Service::Ptr& s
"\t" "host_name" "\t" << host->GetName() << "\n" "\t" "host_name" "\t" << host->GetName() << "\n"
"\t" "service_description" "\t" << service->GetShortName() << "\n" "\t" "service_description" "\t" << service->GetShortName() << "\n"
"\t" "display_name" "\t" << service->GetDisplayName() << "\n" "\t" "display_name" "\t" << service->GetDisplayName() << "\n"
"\t" "check_period" "\t" << CompatUtility::GetServiceCheckPeriod(service) << "\n" "\t" "check_period" "\t" << CompatUtility::GetCheckableCheckPeriod(service) << "\n"
"\t" "check_interval" "\t" << CompatUtility::GetServiceCheckInterval(service) << "\n" "\t" "check_interval" "\t" << CompatUtility::GetCheckableCheckInterval(service) << "\n"
"\t" "retry_interval" "\t" << CompatUtility::GetServiceRetryInterval(service) << "\n" "\t" "retry_interval" "\t" << CompatUtility::GetCheckableRetryInterval(service) << "\n"
"\t" "max_check_attempts" "\t" << service->GetMaxCheckAttempts() << "\n" "\t" "max_check_attempts" "\t" << service->GetMaxCheckAttempts() << "\n"
"\t" "active_checks_enabled" "\t" << CompatUtility::GetServiceActiveChecksEnabled(service) << "\n" "\t" "active_checks_enabled" "\t" << CompatUtility::GetCheckableActiveChecksEnabled(service) << "\n"
"\t" "passive_checks_enabled" "\t" << CompatUtility::GetServicePassiveChecksEnabled(service) << "\n" "\t" "passive_checks_enabled" "\t" << CompatUtility::GetCheckablePassiveChecksEnabled(service) << "\n"
"\t" "flap_detection_enabled" "\t" << CompatUtility::GetServiceFlapDetectionEnabled(service) << "\n" "\t" "flap_detection_enabled" "\t" << CompatUtility::GetCheckableFlapDetectionEnabled(service) << "\n"
"\t" "is_volatile" "\t" << CompatUtility::GetServiceIsVolatile(service) << "\n" "\t" "is_volatile" "\t" << CompatUtility::GetCheckableIsVolatile(service) << "\n"
"\t" "notifications_enabled" "\t" << CompatUtility::GetServiceNotificationsEnabled(service) << "\n" "\t" "notifications_enabled" "\t" << CompatUtility::GetCheckableNotificationsEnabled(service) << "\n"
"\t" "notification_options" "\t" << CompatUtility::GetServiceNotificationNotificationOptions(service) << "\n" "\t" "notification_options" "\t" << CompatUtility::GetCheckableNotificationNotificationOptions(service) << "\n"
"\t" "notification_interval" "\t" << CompatUtility::GetServiceNotificationNotificationInterval(service) << "\n" "\t" "notification_interval" "\t" << CompatUtility::GetCheckableNotificationNotificationInterval(service) << "\n"
"\t" "notification_period" "\t" << CompatUtility::GetServiceNotificationNotificationPeriod(service) << "\n" "\t" "notification_period" "\t" << CompatUtility::GetCheckableNotificationNotificationPeriod(service) << "\n"
"\t" "event_handler_enabled" "\t" << CompatUtility::GetServiceEventHandlerEnabled(service) << "\n"; "\t" "event_handler_enabled" "\t" << CompatUtility::GetCheckableEventHandlerEnabled(service) << "\n";
CheckCommand::Ptr checkcommand = service->GetCheckCommand(); CheckCommand::Ptr checkcommand = service->GetCheckCommand();
if (checkcommand) if (checkcommand)
@ -454,11 +442,11 @@ void StatusDataWriter::DumpServiceObject(std::ostream& fp, const Service::Ptr& s
fp << "\t" "event_handler" "\t" "event_" << eventcommand->GetName() << "\n"; fp << "\t" "event_handler" "\t" "event_" << eventcommand->GetName() << "\n";
fp << "\t" "contacts" "\t"; fp << "\t" "contacts" "\t";
DumpNameList(fp, CompatUtility::GetServiceNotificationUsers(service)); DumpNameList(fp, CompatUtility::GetCheckableNotificationUsers(service));
fp << "\n"; fp << "\n";
fp << "\t" "contact_groups" "\t"; fp << "\t" "contact_groups" "\t";
DumpNameList(fp, CompatUtility::GetServiceNotificationUserGroups(service)); DumpNameList(fp, CompatUtility::GetCheckableNotificationUserGroups(service));
fp << "\n"; fp << "\n";
String notes = CompatUtility::GetCustomAttributeConfig(service, "notes"); String notes = CompatUtility::GetCustomAttributeConfig(service, "notes");
@ -470,7 +458,7 @@ void StatusDataWriter::DumpServiceObject(std::ostream& fp, const Service::Ptr& s
fp << "\t" "initial_state" "\t" "o" "\n" fp << "\t" "initial_state" "\t" "o" "\n"
"\t" "low_flap_threshold" "\t" << service->GetFlappingThreshold() << "\n" "\t" "low_flap_threshold" "\t" << service->GetFlappingThreshold() << "\n"
"\t" "high_flap_threshold" "\t" << service->GetFlappingThreshold() << "\n" "\t" "high_flap_threshold" "\t" << service->GetFlappingThreshold() << "\n"
"\t" "process_perf_data" "\t" << CompatUtility::GetServiceProcessPerformanceData(service) << "\n" "\t" "process_perf_data" "\t" << CompatUtility::GetCheckableProcessPerformanceData(service) << "\n"
"\t" "check_freshness" << "\t" "1" "\n"; "\t" "check_freshness" << "\t" "1" "\n";
if (!notes.IsEmpty()) if (!notes.IsEmpty())
fp << "\t" "notes" "\t" << notes << "\n"; fp << "\t" "notes" "\t" << notes << "\n";
@ -659,12 +647,26 @@ void StatusDataWriter::UpdateObjectsCache(void)
} }
BOOST_FOREACH(const Dependency::Ptr& dep, DynamicType::GetObjects<Dependency>()) { BOOST_FOREACH(const Dependency::Ptr& dep, DynamicType::GetObjects<Dependency>()) {
Service::Ptr parent_service = dep->GetParentService(); Checkable::Ptr parent = dep->GetParent();
if (!parent)
continue;
Host::Ptr parent_host;
Service::Ptr parent_service;
tie(parent_host, parent_service) = GetHostService(parent);
if (!parent_service) if (!parent_service)
continue; continue;
Service::Ptr child_service = dep->GetChildService(); Checkable::Ptr child = dep->GetChild();
if (!child)
continue;
Host::Ptr child_host;
Service::Ptr child_service;
tie(child_host, child_service) = GetHostService(child);
if (!child_service) if (!child_service)
continue; continue;

View File

@ -53,12 +53,12 @@ private:
void DumpCommand(std::ostream& fp, const Command::Ptr& command); void DumpCommand(std::ostream& fp, const Command::Ptr& command);
void DumpTimePeriod(std::ostream& fp, const TimePeriod::Ptr& tp); void DumpTimePeriod(std::ostream& fp, const TimePeriod::Ptr& tp);
void DumpDowntimes(std::ostream& fp, const Service::Ptr& owner, CompatObjectType type); void DumpDowntimes(std::ostream& fp, const Checkable::Ptr& owner);
void DumpComments(std::ostream& fp, const Service::Ptr& owner, CompatObjectType type); void DumpComments(std::ostream& fp, const Checkable::Ptr& owner);
void DumpHostStatus(std::ostream& fp, const Host::Ptr& host); void DumpHostStatus(std::ostream& fp, const Host::Ptr& host);
void DumpHostObject(std::ostream& fp, const Host::Ptr& host); void DumpHostObject(std::ostream& fp, const Host::Ptr& host);
void DumpServiceStatusAttrs(std::ostream& fp, const Service::Ptr& service, CompatObjectType type); void DumpCheckableStatusAttrs(std::ostream& fp, const Checkable::Ptr& checkable);
template<typename T> template<typename T>
void DumpNameList(std::ostream& fp, const T& list) void DumpNameList(std::ostream& fp, const T& list)

View File

@ -57,6 +57,18 @@ String CommentsTable::GetName(void) const
void CommentsTable::FetchRows(const AddRowFunction& addRowFn) void CommentsTable::FetchRows(const AddRowFunction& addRowFn)
{ {
BOOST_FOREACH(const Host::Ptr& host, DynamicType::GetObjects<Host>()) {
Dictionary::Ptr comments = host->GetComments();
ObjectLock olock(comments);
String id;
Comment::Ptr comment;
BOOST_FOREACH(tie(id, comment), comments) {
addRowFn(comment);
}
}
BOOST_FOREACH(const Service::Ptr& service, DynamicType::GetObjects<Service>()) { BOOST_FOREACH(const Service::Ptr& service, DynamicType::GetObjects<Service>()) {
Dictionary::Ptr comments = service->GetComments(); Dictionary::Ptr comments = service->GetComments();
@ -64,9 +76,8 @@ void CommentsTable::FetchRows(const AddRowFunction& addRowFn)
String id; String id;
Comment::Ptr comment; Comment::Ptr comment;
BOOST_FOREACH(boost::tie(id, comment), comments) { BOOST_FOREACH(tie(id, comment), comments) {
if (Service::GetOwnerByCommentID(id) == service) addRowFn(comment);
addRowFn(comment);
} }
} }
} }
@ -74,7 +85,7 @@ void CommentsTable::FetchRows(const AddRowFunction& addRowFn)
Object::Ptr CommentsTable::ServiceAccessor(const Value& row, const Column::ObjectAccessor& parentObjectAccessor) Object::Ptr CommentsTable::ServiceAccessor(const Value& row, const Column::ObjectAccessor& parentObjectAccessor)
{ {
Comment::Ptr comment = static_cast<Comment::Ptr>(row); Comment::Ptr comment = static_cast<Comment::Ptr>(row);
return Service::GetOwnerByCommentID(comment->GetId()); return Checkable::GetOwnerByCommentID(comment->GetId()); // XXX: this might return a Host object
} }
Value CommentsTable::AuthorAccessor(const Value& row) Value CommentsTable::AuthorAccessor(const Value& row)
@ -120,23 +131,26 @@ Value CommentsTable::EntryTimeAccessor(const Value& row)
Value CommentsTable::TypeAccessor(const Value& row) Value CommentsTable::TypeAccessor(const Value& row)
{ {
Comment::Ptr comment = static_cast<Comment::Ptr>(row); Comment::Ptr comment = static_cast<Comment::Ptr>(row);
Service::Ptr svc = Service::GetOwnerByCommentID(comment->GetId()); Checkable::Ptr checkable = Checkable::GetOwnerByCommentID(comment->GetId());
if (!svc) if (!checkable)
return Empty; return Empty;
return (svc->IsHostCheck() ? 1 : 2); if (dynamic_pointer_cast<Host>(checkable))
return 1;
else
return 2;
} }
Value CommentsTable::IsServiceAccessor(const Value& row) Value CommentsTable::IsServiceAccessor(const Value& row)
{ {
Comment::Ptr comment = static_cast<Comment::Ptr>(row); Comment::Ptr comment = static_cast<Comment::Ptr>(row);
Service::Ptr svc = Service::GetOwnerByCommentID(comment->GetId()); Checkable::Ptr checkable = Checkable::GetOwnerByCommentID(comment->GetId());
if (!svc) if (!checkable)
return Empty; return Empty;
return (svc->IsHostCheck() ? 0 : 1); return (dynamic_pointer_cast<Host>(checkable) ? 0 : 1);
} }
Value CommentsTable::EntryTypeAccessor(const Value& row) Value CommentsTable::EntryTypeAccessor(const Value& row)

View File

@ -115,9 +115,9 @@ Value DowntimesTable::TypeAccessor(const Value& row)
Value DowntimesTable::IsServiceAccessor(const Value& row) Value DowntimesTable::IsServiceAccessor(const Value& row)
{ {
Downtime::Ptr downtime = static_cast<Downtime::Ptr>(row); Downtime::Ptr downtime = static_cast<Downtime::Ptr>(row);
Service::Ptr svc = Service::GetOwnerByDowntimeID(downtime->GetId()); Checkable::Ptr checkable = Checkable::GetOwnerByDowntimeID(downtime->GetId());
return (svc->IsHostCheck() ? 0 : 1); return (dynamic_pointer_cast<Host>(checkable) ? 0 : 1);
} }
Value DowntimesTable::StartTimeAccessor(const Value& row) Value DowntimesTable::StartTimeAccessor(const Value& row)

View File

@ -160,10 +160,8 @@ Value HostGroupsTable::NumHostsPendingAccessor(const Value& row)
int num_hosts = 0; int num_hosts = 0;
BOOST_FOREACH(const Host::Ptr& host, static_cast<HostGroup::Ptr>(row)->GetMembers()) { BOOST_FOREACH(const Host::Ptr& host, static_cast<HostGroup::Ptr>(row)->GetMembers()) {
Service::Ptr hc = host->GetCheckService(); /* no checkresult */
if (!host->GetLastCheckResult())
/* no hostcheck service or no checkresult */
if (!hc || !hc->GetLastCheckResult())
num_hosts++; num_hosts++;
} }

View File

@ -157,7 +157,6 @@ void HostsTable::AddColumns(Table *table, const String& prefix,
table->AddColumn(prefix + "services", Column(&HostsTable::ServicesAccessor, objectAccessor)); table->AddColumn(prefix + "services", Column(&HostsTable::ServicesAccessor, objectAccessor));
table->AddColumn(prefix + "services_with_state", Column(&HostsTable::ServicesWithStateAccessor, objectAccessor)); table->AddColumn(prefix + "services_with_state", Column(&HostsTable::ServicesWithStateAccessor, objectAccessor));
table->AddColumn(prefix + "services_with_info", Column(&HostsTable::ServicesWithInfoAccessor, objectAccessor)); table->AddColumn(prefix + "services_with_info", Column(&HostsTable::ServicesWithInfoAccessor, objectAccessor));
table->AddColumn(prefix + "check_service", Column(&HostsTable::CheckServiceAccessor, objectAccessor));
} }
String HostsTable::GetName(void) const String HostsTable::GetName(void) const
@ -220,13 +219,7 @@ Value HostsTable::CheckCommandAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
/* use hostcheck service */ CheckCommand::Ptr checkcommand = host->GetCheckCommand();
Service::Ptr hc = host->GetCheckService();
if (!hc)
return Empty;
CheckCommand::Ptr checkcommand = hc->GetCheckCommand();
if (checkcommand) if (checkcommand)
return checkcommand->GetName(); /* this is the name without '!' args */ return checkcommand->GetName(); /* this is the name without '!' args */
@ -241,12 +234,7 @@ Value HostsTable::CheckCommandExpandedAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); CheckCommand::Ptr checkcommand = host->GetCheckCommand();
if (!hc)
return Empty;
CheckCommand::Ptr checkcommand = hc->GetCheckCommand();
if (checkcommand) if (checkcommand)
return checkcommand->GetName(); /* this is the name without '!' args */ return checkcommand->GetName(); /* this is the name without '!' args */
@ -261,12 +249,7 @@ Value HostsTable::EventHandlerAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); EventCommand::Ptr eventcommand = host->GetEventCommand();
if (!hc)
return Empty;
EventCommand::Ptr eventcommand = hc->GetEventCommand();
if (eventcommand) if (eventcommand)
return eventcommand->GetName(); return eventcommand->GetName();
@ -281,12 +264,7 @@ Value HostsTable::NotificationPeriodAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableNotificationNotificationPeriod(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceNotificationNotificationPeriod(hc);
} }
Value HostsTable::CheckPeriodAccessor(const Value& row) Value HostsTable::CheckPeriodAccessor(const Value& row)
@ -297,12 +275,7 @@ Value HostsTable::CheckPeriodAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableCheckPeriod(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceCheckPeriod(hc);
} }
Value HostsTable::NotesAccessor(const Value& row) Value HostsTable::NotesAccessor(const Value& row)
@ -322,16 +295,8 @@ Value HostsTable::NotesExpandedAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr service = host->GetCheckService();
if (!service)
return Empty;
std::vector<MacroResolver::Ptr> resolvers; std::vector<MacroResolver::Ptr> resolvers;
if (service)
resolvers.push_back(service);
resolvers.push_back(host); resolvers.push_back(host);
resolvers.push_back(IcingaApplication::GetInstance()); resolvers.push_back(IcingaApplication::GetInstance());
@ -357,16 +322,8 @@ Value HostsTable::NotesUrlExpandedAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr service = host->GetCheckService();
if (!service)
return Empty;
std::vector<MacroResolver::Ptr> resolvers; std::vector<MacroResolver::Ptr> resolvers;
if (service)
resolvers.push_back(service);
resolvers.push_back(host); resolvers.push_back(host);
resolvers.push_back(IcingaApplication::GetInstance()); resolvers.push_back(IcingaApplication::GetInstance());
@ -392,16 +349,8 @@ Value HostsTable::ActionUrlExpandedAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr service = host->GetCheckService();
if (!service)
return Empty;
std::vector<MacroResolver::Ptr> resolvers; std::vector<MacroResolver::Ptr> resolvers;
if (service)
resolvers.push_back(service);
resolvers.push_back(host); resolvers.push_back(host);
resolvers.push_back(IcingaApplication::GetInstance()); resolvers.push_back(IcingaApplication::GetInstance());
@ -418,15 +367,11 @@ Value HostsTable::PluginOutputAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService();
String output; String output;
CheckResult::Ptr cr = host->GetLastCheckResult();
if(hc) { if (cr)
CheckResult::Ptr cr = hc->GetLastCheckResult(); output = CompatUtility::GetCheckResultOutput(cr);
if (cr)
output = CompatUtility::GetCheckResultOutput(cr);
}
return output; return output;
} }
@ -454,16 +399,8 @@ Value HostsTable::IconImageExpandedAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr service = host->GetCheckService();
if (!service)
return Empty;
std::vector<MacroResolver::Ptr> resolvers; std::vector<MacroResolver::Ptr> resolvers;
if (service)
resolvers.push_back(service);
resolvers.push_back(host); resolvers.push_back(host);
resolvers.push_back(IcingaApplication::GetInstance()); resolvers.push_back(IcingaApplication::GetInstance());
@ -500,15 +437,11 @@ Value HostsTable::LongPluginOutputAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService();
String long_output; String long_output;
CheckResult::Ptr cr = host->GetLastCheckResult();
if (hc) { if (cr)
CheckResult::Ptr cr = hc->GetLastCheckResult(); long_output = CompatUtility::GetCheckResultLongOutput(cr);
if (cr)
long_output = CompatUtility::GetCheckResultLongOutput(cr);
}
return long_output; return long_output;
} }
@ -521,12 +454,7 @@ Value HostsTable::MaxCheckAttemptsAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return host->GetMaxCheckAttempts();
if (!hc)
return Empty;
return hc->GetMaxCheckAttempts();
} }
Value HostsTable::FlapDetectionEnabledAccessor(const Value& row) Value HostsTable::FlapDetectionEnabledAccessor(const Value& row)
@ -537,12 +465,7 @@ Value HostsTable::FlapDetectionEnabledAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableFlapDetectionEnabled(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceFlapDetectionEnabled(hc);
} }
Value HostsTable::AcceptPassiveChecksAccessor(const Value& row) Value HostsTable::AcceptPassiveChecksAccessor(const Value& row)
@ -553,12 +476,7 @@ Value HostsTable::AcceptPassiveChecksAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckablePassiveChecksEnabled(host);
if (!hc)
return Empty;
return CompatUtility::GetServicePassiveChecksEnabled(hc);
} }
Value HostsTable::EventHandlerEnabledAccessor(const Value& row) Value HostsTable::EventHandlerEnabledAccessor(const Value& row)
@ -569,12 +487,7 @@ Value HostsTable::EventHandlerEnabledAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableEventHandlerEnabled(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceEventHandlerEnabled(hc);
} }
Value HostsTable::AcknowledgementTypeAccessor(const Value& row) Value HostsTable::AcknowledgementTypeAccessor(const Value& row)
@ -585,12 +498,7 @@ Value HostsTable::AcknowledgementTypeAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableAcknowledgementType(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceAcknowledgementType(hc);
} }
Value HostsTable::CheckTypeAccessor(const Value& row) Value HostsTable::CheckTypeAccessor(const Value& row)
@ -601,12 +509,7 @@ Value HostsTable::CheckTypeAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableCheckType(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceCheckType(hc);
} }
Value HostsTable::LastStateAccessor(const Value& row) Value HostsTable::LastStateAccessor(const Value& row)
@ -637,12 +540,7 @@ Value HostsTable::CurrentAttemptAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return host->GetCheckAttempt();
if (!hc)
return Empty;
return hc->GetCheckAttempt();
} }
Value HostsTable::LastNotificationAccessor(const Value& row) Value HostsTable::LastNotificationAccessor(const Value& row)
@ -653,12 +551,7 @@ Value HostsTable::LastNotificationAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableNotificationLastNotification(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceNotificationLastNotification(hc);
} }
Value HostsTable::NextNotificationAccessor(const Value& row) Value HostsTable::NextNotificationAccessor(const Value& row)
@ -669,12 +562,7 @@ Value HostsTable::NextNotificationAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableNotificationNextNotification(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceNotificationNextNotification(hc);
} }
Value HostsTable::NextCheckAccessor(const Value& row) Value HostsTable::NextCheckAccessor(const Value& row)
@ -685,12 +573,7 @@ Value HostsTable::NextCheckAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return static_cast<int>(host->GetNextCheck());
if (!hc)
return Empty;
return static_cast<int>(hc->GetNextCheck());
} }
Value HostsTable::LastHardStateChangeAccessor(const Value& row) Value HostsTable::LastHardStateChangeAccessor(const Value& row)
@ -701,12 +584,7 @@ Value HostsTable::LastHardStateChangeAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return static_cast<int>(host->GetLastHardStateChange());
if (!hc)
return Empty;
return static_cast<int>(hc->GetLastHardStateChange());
} }
Value HostsTable::HasBeenCheckedAccessor(const Value& row) Value HostsTable::HasBeenCheckedAccessor(const Value& row)
@ -717,12 +595,7 @@ Value HostsTable::HasBeenCheckedAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableHasBeenChecked(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceHasBeenChecked(hc);
} }
Value HostsTable::CurrentNotificationNumberAccessor(const Value& row) Value HostsTable::CurrentNotificationNumberAccessor(const Value& row)
@ -733,12 +606,7 @@ Value HostsTable::CurrentNotificationNumberAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableNotificationNotificationNumber(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceNotificationNotificationNumber(hc);
} }
Value HostsTable::TotalServicesAccessor(const Value& row) Value HostsTable::TotalServicesAccessor(const Value& row)
@ -759,12 +627,7 @@ Value HostsTable::ChecksEnabledAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableActiveChecksEnabled(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceActiveChecksEnabled(hc);
} }
Value HostsTable::NotificationsEnabledAccessor(const Value& row) Value HostsTable::NotificationsEnabledAccessor(const Value& row)
@ -775,12 +638,7 @@ Value HostsTable::NotificationsEnabledAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableNotificationsEnabled(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceNotificationsEnabled(hc);
} }
Value HostsTable::AcknowledgedAccessor(const Value& row) Value HostsTable::AcknowledgedAccessor(const Value& row)
@ -791,12 +649,7 @@ Value HostsTable::AcknowledgedAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableIsAcknowledged(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceIsAcknowledged(hc);
} }
Value HostsTable::StateAccessor(const Value& row) Value HostsTable::StateAccessor(const Value& row)
@ -829,12 +682,7 @@ Value HostsTable::NoMoreNotificationsAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableNoMoreNotifications(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceNoMoreNotifications(hc);
} }
Value HostsTable::LastCheckAccessor(const Value& row) Value HostsTable::LastCheckAccessor(const Value& row)
@ -845,12 +693,7 @@ Value HostsTable::LastCheckAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return static_cast<int>(host->GetLastCheck());
if (!hc)
return Empty;
return static_cast<int>(hc->GetLastCheck());
} }
Value HostsTable::LastStateChangeAccessor(const Value& row) Value HostsTable::LastStateChangeAccessor(const Value& row)
@ -905,12 +748,7 @@ Value HostsTable::IsFlappingAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return host->IsFlapping();
if (!hc)
return Empty;
return hc->IsFlapping();
} }
Value HostsTable::ScheduledDowntimeDepthAccessor(const Value& row) Value HostsTable::ScheduledDowntimeDepthAccessor(const Value& row)
@ -921,12 +759,7 @@ Value HostsTable::ScheduledDowntimeDepthAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return host->GetDowntimeDepth();
if (!hc)
return Empty;
return hc->GetDowntimeDepth();
} }
Value HostsTable::ActiveChecksEnabledAccessor(const Value& row) Value HostsTable::ActiveChecksEnabledAccessor(const Value& row)
@ -938,12 +771,7 @@ Value HostsTable::ActiveChecksEnabledAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableActiveChecksEnabled(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceActiveChecksEnabled(hc);
} }
Value HostsTable::CheckOptionsAccessor(const Value& row) Value HostsTable::CheckOptionsAccessor(const Value& row)
@ -960,12 +788,7 @@ Value HostsTable::ModifiedAttributesAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return host->GetModifiedAttributes();
if (!hc)
return Empty;
return hc->GetModifiedAttributes();
} }
Value HostsTable::ModifiedAttributesListAccessor(const Value& row) Value HostsTable::ModifiedAttributesListAccessor(const Value& row)
@ -982,12 +805,7 @@ Value HostsTable::CheckIntervalAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableCheckInterval(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceCheckInterval(hc);
} }
Value HostsTable::RetryIntervalAccessor(const Value& row) Value HostsTable::RetryIntervalAccessor(const Value& row)
@ -998,12 +816,7 @@ Value HostsTable::RetryIntervalAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableRetryInterval(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceRetryInterval(hc);
} }
Value HostsTable::NotificationIntervalAccessor(const Value& row) Value HostsTable::NotificationIntervalAccessor(const Value& row)
@ -1014,12 +827,7 @@ Value HostsTable::NotificationIntervalAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableNotificationNotificationInterval(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceNotificationNotificationInterval(hc);
} }
Value HostsTable::LowFlapThresholdAccessor(const Value& row) Value HostsTable::LowFlapThresholdAccessor(const Value& row)
@ -1030,12 +838,7 @@ Value HostsTable::LowFlapThresholdAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableLowFlapThreshold(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceLowFlapThreshold(hc);
} }
Value HostsTable::HighFlapThresholdAccessor(const Value& row) Value HostsTable::HighFlapThresholdAccessor(const Value& row)
@ -1046,12 +849,7 @@ Value HostsTable::HighFlapThresholdAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableHighFlapThreshold(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceHighFlapThreshold(hc);
} }
Value HostsTable::X2dAccessor(const Value& row) Value HostsTable::X2dAccessor(const Value& row)
@ -1082,12 +880,7 @@ Value HostsTable::LatencyAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return (Service::CalculateLatency(host->GetLastCheckResult()));
if (!hc)
return Empty;
return (Service::CalculateLatency(hc->GetLastCheckResult()));
} }
Value HostsTable::ExecutionTimeAccessor(const Value& row) Value HostsTable::ExecutionTimeAccessor(const Value& row)
@ -1098,12 +891,7 @@ Value HostsTable::ExecutionTimeAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return (Service::CalculateExecutionTime(host->GetLastCheckResult()));
if (!hc)
return Empty;
return (Service::CalculateExecutionTime(hc->GetLastCheckResult()));
} }
Value HostsTable::PercentStateChangeAccessor(const Value& row) Value HostsTable::PercentStateChangeAccessor(const Value& row)
@ -1114,12 +902,7 @@ Value HostsTable::PercentStateChangeAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckablePercentStateChange(host);
if (!hc)
return Empty;
return CompatUtility::GetServicePercentStateChange(hc);
} }
Value HostsTable::InNotificationPeriodAccessor(const Value& row) Value HostsTable::InNotificationPeriodAccessor(const Value& row)
@ -1130,12 +913,7 @@ Value HostsTable::InNotificationPeriodAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableInNotificationPeriod(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceInNotificationPeriod(hc);
} }
Value HostsTable::InCheckPeriodAccessor(const Value& row) Value HostsTable::InCheckPeriodAccessor(const Value& row)
@ -1146,12 +924,7 @@ Value HostsTable::InCheckPeriodAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableInCheckPeriod(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceInCheckPeriod(hc);
} }
Value HostsTable::ContactsAccessor(const Value& row) Value HostsTable::ContactsAccessor(const Value& row)
@ -1162,14 +935,9 @@ Value HostsTable::ContactsAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService();
if (!hc)
return Empty;
Array::Ptr contact_names = make_shared<Array>(); Array::Ptr contact_names = make_shared<Array>();
BOOST_FOREACH(const User::Ptr& user, CompatUtility::GetServiceNotificationUsers(hc)) { BOOST_FOREACH(const User::Ptr& user, CompatUtility::GetCheckableNotificationUsers(host)) {
contact_names->Add(user->GetName()); contact_names->Add(user->GetName());
} }
@ -1184,12 +952,7 @@ Value HostsTable::DowntimesAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); Dictionary::Ptr downtimes = host->GetDowntimes();
if (!hc)
return Empty;
Dictionary::Ptr downtimes = hc->GetDowntimes();
Array::Ptr ids = make_shared<Array>(); Array::Ptr ids = make_shared<Array>();
@ -1197,7 +960,7 @@ Value HostsTable::DowntimesAccessor(const Value& row)
String id; String id;
Downtime::Ptr downtime; Downtime::Ptr downtime;
BOOST_FOREACH(boost::tie(id, downtime), downtimes) { BOOST_FOREACH(tie(id, downtime), downtimes) {
if (!downtime) if (!downtime)
continue; continue;
@ -1219,12 +982,7 @@ Value HostsTable::DowntimesWithInfoAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); Dictionary::Ptr downtimes = host->GetDowntimes();
if (!hc)
return Empty;
Dictionary::Ptr downtimes = hc->GetDowntimes();
Array::Ptr ids = make_shared<Array>(); Array::Ptr ids = make_shared<Array>();
@ -1232,7 +990,7 @@ Value HostsTable::DowntimesWithInfoAccessor(const Value& row)
String id; String id;
Downtime::Ptr downtime; Downtime::Ptr downtime;
BOOST_FOREACH(boost::tie(id, downtime), downtimes) { BOOST_FOREACH(tie(id, downtime), downtimes) {
if (!downtime) if (!downtime)
continue; continue;
@ -1258,12 +1016,7 @@ Value HostsTable::CommentsAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); Dictionary::Ptr comments = host->GetComments();
if (!hc)
return Empty;
Dictionary::Ptr comments = hc->GetComments();
Array::Ptr ids = make_shared<Array>(); Array::Ptr ids = make_shared<Array>();
@ -1271,7 +1024,7 @@ Value HostsTable::CommentsAccessor(const Value& row)
String id; String id;
Comment::Ptr comment; Comment::Ptr comment;
BOOST_FOREACH(boost::tie(id, comment), comments) { BOOST_FOREACH(tie(id, comment), comments) {
if (!comment) if (!comment)
continue; continue;
@ -1293,12 +1046,7 @@ Value HostsTable::CommentsWithInfoAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); Dictionary::Ptr comments = host->GetComments();
if (!hc)
return Empty;
Dictionary::Ptr comments = hc->GetComments();
Array::Ptr ids = make_shared<Array>(); Array::Ptr ids = make_shared<Array>();
@ -1306,7 +1054,7 @@ Value HostsTable::CommentsWithInfoAccessor(const Value& row)
String id; String id;
Comment::Ptr comment; Comment::Ptr comment;
BOOST_FOREACH(boost::tie(id, comment), comments) { BOOST_FOREACH(tie(id, comment), comments) {
if (!comment) if (!comment)
continue; continue;
@ -1332,12 +1080,7 @@ Value HostsTable::CommentsWithExtraInfoAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); Dictionary::Ptr comments = host->GetComments();
if (!hc)
return Empty;
Dictionary::Ptr comments = hc->GetComments();
Array::Ptr ids = make_shared<Array>(); Array::Ptr ids = make_shared<Array>();
@ -1345,7 +1088,7 @@ Value HostsTable::CommentsWithExtraInfoAccessor(const Value& row)
String id; String id;
Comment::Ptr comment; Comment::Ptr comment;
BOOST_FOREACH(boost::tie(id, comment), comments) { BOOST_FOREACH(tie(id, comment), comments) {
if (!comment) if (!comment)
continue; continue;
@ -1386,7 +1129,7 @@ Value HostsTable::CustomVariableNamesAccessor(const Value& row)
String key; String key;
Value value; Value value;
BOOST_FOREACH(boost::tie(key, value), vars) { BOOST_FOREACH(tie(key, value), vars) {
cv->Add(key); cv->Add(key);
} }
@ -1414,7 +1157,7 @@ Value HostsTable::CustomVariableValuesAccessor(const Value& row)
String key; String key;
Value value; Value value;
BOOST_FOREACH(boost::tie(key, value), vars) { BOOST_FOREACH(tie(key, value), vars) {
cv->Add(value); cv->Add(value);
} }
@ -1442,7 +1185,7 @@ Value HostsTable::CustomVariablesAccessor(const Value& row)
String key; String key;
Value value; Value value;
BOOST_FOREACH(boost::tie(key, value), vars) { BOOST_FOREACH(tie(key, value), vars) {
Array::Ptr key_val = make_shared<Array>(); Array::Ptr key_val = make_shared<Array>();
key_val->Add(key); key_val->Add(key);
key_val->Add(value); key_val->Add(value);
@ -1461,8 +1204,13 @@ Value HostsTable::ParentsAccessor(const Value& row)
Array::Ptr parents = make_shared<Array>(); Array::Ptr parents = make_shared<Array>();
BOOST_FOREACH(const Host::Ptr& parent, host->GetParentHosts()) { BOOST_FOREACH(const Checkable::Ptr& parent, host->GetParents()) {
parents->Add(parent->GetName()); Host::Ptr parent_host = dynamic_pointer_cast<Host>(parent);
if (!parent_host)
continue;
parents->Add(parent_host->GetName());
} }
return parents; return parents;
@ -1477,8 +1225,13 @@ Value HostsTable::ChildsAccessor(const Value& row)
Array::Ptr childs = make_shared<Array>(); Array::Ptr childs = make_shared<Array>();
BOOST_FOREACH(const Host::Ptr& child, host->GetChildHosts()) { BOOST_FOREACH(const Checkable::Ptr& child, host->GetChildren()) {
childs->Add(child->GetName()); Host::Ptr child_host = dynamic_pointer_cast<Host>(child);
if (!child_host)
continue;
childs->Add(child_host->GetName());
} }
return childs; return childs;
@ -1692,17 +1445,12 @@ Value HostsTable::HardStateAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); if (host->GetState() == HostUp)
return HostUp;
else if (host->GetStateType() == StateTypeHard)
return host->GetState();
if (!hc) return host->GetLastHardState();
return Empty;
if (hc->GetState() == StateOK)
return StateOK;
if (hc->GetStateType() == StateTypeHard)
return hc->GetState();
return hc->GetLastHardState();
} }
Value HostsTable::StalenessAccessor(const Value& row) Value HostsTable::StalenessAccessor(const Value& row)
@ -1713,12 +1461,7 @@ Value HostsTable::StalenessAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService(); return CompatUtility::GetCheckableStaleness(host);
if (!hc)
return Empty;
return CompatUtility::GetServiceStaleness(hc);
} }
Value HostsTable::GroupsAccessor(const Value& row) Value HostsTable::GroupsAccessor(const Value& row)
@ -1744,14 +1487,9 @@ Value HostsTable::ContactGroupsAccessor(const Value& row)
if (!host) if (!host)
return Empty; return Empty;
Service::Ptr hc = host->GetCheckService();
if (!hc)
return Empty;
Array::Ptr contactgroup_names = make_shared<Array>(); Array::Ptr contactgroup_names = make_shared<Array>();
BOOST_FOREACH(const UserGroup::Ptr& usergroup, CompatUtility::GetServiceNotificationUserGroups(hc)) { BOOST_FOREACH(const UserGroup::Ptr& usergroup, CompatUtility::GetCheckableNotificationUserGroups(host)) {
contactgroup_names->Add(usergroup->GetName()); contactgroup_names->Add(usergroup->GetName());
} }
@ -1823,21 +1561,3 @@ Value HostsTable::ServicesWithInfoAccessor(const Value& row)
return services; return services;
} }
Value HostsTable::CheckServiceAccessor(const Value& row)
{
Host::Ptr host = static_cast<Host::Ptr>(row);
if (!host)
return Empty;
Service::Ptr hc = host->GetCheckService();
Array::Ptr services = make_shared<Array>();
if (!hc)
return Empty;
return hc->GetShortName();
}

View File

@ -143,7 +143,6 @@ protected:
static Value ServicesAccessor(const Value& row); static Value ServicesAccessor(const Value& row);
static Value ServicesWithStateAccessor(const Value& row); static Value ServicesWithStateAccessor(const Value& row);
static Value ServicesWithInfoAccessor(const Value& row); static Value ServicesWithInfoAccessor(const Value& row);
static Value CheckServiceAccessor(const Value& row);
}; };
} }

View File

@ -48,7 +48,7 @@ static int l_ExternalCommands = 0;
static boost::mutex l_QueryMutex; static boost::mutex l_QueryMutex;
Query::Query(const std::vector<String>& lines, const String& compat_log_path) Query::Query(const std::vector<String>& lines, const String& compat_log_path)
: m_KeepAlive(false), m_OutputFormat("csv"), m_ColumnHeaders(true), m_Limit(-1), : m_KeepAlive(false), m_OutputFormat("csv"), m_ColumnHeaders(true),
m_LogTimeFrom(0), m_LogTimeUntil(static_cast<long>(Utility::GetTime())) m_LogTimeFrom(0), m_LogTimeUntil(static_cast<long>(Utility::GetTime()))
{ {
if (lines.size() == 0) { if (lines.size() == 0) {

View File

@ -68,7 +68,6 @@ private:
String m_OutputFormat; String m_OutputFormat;
bool m_ColumnHeaders; bool m_ColumnHeaders;
int m_Limit;
String m_ResponseHeader; String m_ResponseHeader;

View File

@ -280,7 +280,7 @@ Value ServicesTable::NotificationPeriodAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceNotificationNotificationPeriod(service); return CompatUtility::GetCheckableNotificationNotificationPeriod(service);
} }
Value ServicesTable::CheckPeriodAccessor(const Value& row) Value ServicesTable::CheckPeriodAccessor(const Value& row)
@ -290,7 +290,7 @@ Value ServicesTable::CheckPeriodAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceCheckPeriod(service); return CompatUtility::GetCheckableCheckPeriod(service);
} }
Value ServicesTable::NotesAccessor(const Value& row) Value ServicesTable::NotesAccessor(const Value& row)
@ -438,7 +438,7 @@ Value ServicesTable::StateAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceCurrentState(service); return service->GetState();
} }
Value ServicesTable::HasBeenCheckedAccessor(const Value& row) Value ServicesTable::HasBeenCheckedAccessor(const Value& row)
@ -448,7 +448,7 @@ Value ServicesTable::HasBeenCheckedAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceHasBeenChecked(service); return CompatUtility::GetCheckableHasBeenChecked(service);
} }
Value ServicesTable::LastStateAccessor(const Value& row) Value ServicesTable::LastStateAccessor(const Value& row)
@ -488,7 +488,7 @@ Value ServicesTable::CheckTypeAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceCheckType(service); return CompatUtility::GetCheckableCheckType(service);
} }
Value ServicesTable::AcknowledgedAccessor(const Value& row) Value ServicesTable::AcknowledgedAccessor(const Value& row)
@ -499,7 +499,7 @@ Value ServicesTable::AcknowledgedAccessor(const Value& row)
return Empty; return Empty;
return CompatUtility::GetServiceIsAcknowledged(service); return CompatUtility::GetCheckableIsAcknowledged(service);
} }
Value ServicesTable::AcknowledgementTypeAccessor(const Value& row) Value ServicesTable::AcknowledgementTypeAccessor(const Value& row)
@ -522,7 +522,7 @@ Value ServicesTable::NoMoreNotificationsAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceNoMoreNotifications(service); return CompatUtility::GetCheckableNoMoreNotifications(service);
} }
Value ServicesTable::LastTimeOkAccessor(const Value& row) Value ServicesTable::LastTimeOkAccessor(const Value& row)
@ -592,7 +592,7 @@ Value ServicesTable::LastNotificationAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceNotificationLastNotification(service); return CompatUtility::GetCheckableNotificationLastNotification(service);
} }
Value ServicesTable::NextNotificationAccessor(const Value& row) Value ServicesTable::NextNotificationAccessor(const Value& row)
@ -602,7 +602,7 @@ Value ServicesTable::NextNotificationAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceNotificationNextNotification(service); return CompatUtility::GetCheckableNotificationNextNotification(service);
} }
Value ServicesTable::CurrentNotificationNumberAccessor(const Value& row) Value ServicesTable::CurrentNotificationNumberAccessor(const Value& row)
@ -612,7 +612,7 @@ Value ServicesTable::CurrentNotificationNumberAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceNotificationNotificationNumber(service); return CompatUtility::GetCheckableNotificationNotificationNumber(service);
} }
Value ServicesTable::LastStateChangeAccessor(const Value& row) Value ServicesTable::LastStateChangeAccessor(const Value& row)
@ -662,7 +662,7 @@ Value ServicesTable::ChecksEnabledAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceActiveChecksEnabled(service); return CompatUtility::GetCheckableActiveChecksEnabled(service);
} }
Value ServicesTable::AcceptPassiveChecksAccessor(const Value& row) Value ServicesTable::AcceptPassiveChecksAccessor(const Value& row)
@ -672,7 +672,7 @@ Value ServicesTable::AcceptPassiveChecksAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServicePassiveChecksEnabled(service); return CompatUtility::GetCheckablePassiveChecksEnabled(service);
} }
Value ServicesTable::EventHandlerEnabledAccessor(const Value& row) Value ServicesTable::EventHandlerEnabledAccessor(const Value& row)
@ -682,7 +682,7 @@ Value ServicesTable::EventHandlerEnabledAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceEventHandlerEnabled(service); return CompatUtility::GetCheckableEventHandlerEnabled(service);
} }
Value ServicesTable::NotificationsEnabledAccessor(const Value& row) Value ServicesTable::NotificationsEnabledAccessor(const Value& row)
@ -692,7 +692,7 @@ Value ServicesTable::NotificationsEnabledAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceNotificationsEnabled(service); return CompatUtility::GetCheckableNotificationsEnabled(service);
} }
Value ServicesTable::ProcessPerformanceDataAccessor(const Value& row) Value ServicesTable::ProcessPerformanceDataAccessor(const Value& row)
@ -702,7 +702,7 @@ Value ServicesTable::ProcessPerformanceDataAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceProcessPerformanceData(service); return CompatUtility::GetCheckableProcessPerformanceData(service);
} }
Value ServicesTable::ActiveChecksEnabledAccessor(const Value& row) Value ServicesTable::ActiveChecksEnabledAccessor(const Value& row)
@ -712,7 +712,7 @@ Value ServicesTable::ActiveChecksEnabledAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceActiveChecksEnabled(service); return CompatUtility::GetCheckableActiveChecksEnabled(service);
} }
Value ServicesTable::CheckOptionsAccessor(const Value& row) Value ServicesTable::CheckOptionsAccessor(const Value& row)
@ -728,7 +728,7 @@ Value ServicesTable::FlapDetectionEnabledAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceFlapDetectionEnabled(service); return CompatUtility::GetCheckableFlapDetectionEnabled(service);
} }
Value ServicesTable::CheckFreshnessAccessor(const Value& row) Value ServicesTable::CheckFreshnessAccessor(const Value& row)
@ -738,7 +738,7 @@ Value ServicesTable::CheckFreshnessAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceFreshnessChecksEnabled(service); return CompatUtility::GetCheckableFreshnessChecksEnabled(service);
} }
Value ServicesTable::ModifiedAttributesAccessor(const Value& row) Value ServicesTable::ModifiedAttributesAccessor(const Value& row)
@ -764,7 +764,7 @@ Value ServicesTable::StalenessAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceStaleness(service); return CompatUtility::GetCheckableStaleness(service);
} }
Value ServicesTable::CheckIntervalAccessor(const Value& row) Value ServicesTable::CheckIntervalAccessor(const Value& row)
@ -774,7 +774,7 @@ Value ServicesTable::CheckIntervalAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceCheckInterval(service); return CompatUtility::GetCheckableCheckInterval(service);
} }
Value ServicesTable::RetryIntervalAccessor(const Value& row) Value ServicesTable::RetryIntervalAccessor(const Value& row)
@ -784,7 +784,7 @@ Value ServicesTable::RetryIntervalAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceRetryInterval(service); return CompatUtility::GetCheckableRetryInterval(service);
} }
Value ServicesTable::NotificationIntervalAccessor(const Value& row) Value ServicesTable::NotificationIntervalAccessor(const Value& row)
@ -794,7 +794,7 @@ Value ServicesTable::NotificationIntervalAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceNotificationNotificationInterval(service); return CompatUtility::GetCheckableNotificationNotificationInterval(service);
} }
Value ServicesTable::LowFlapThresholdAccessor(const Value& row) Value ServicesTable::LowFlapThresholdAccessor(const Value& row)
@ -804,7 +804,7 @@ Value ServicesTable::LowFlapThresholdAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceLowFlapThreshold(service); return CompatUtility::GetCheckableLowFlapThreshold(service);
} }
Value ServicesTable::HighFlapThresholdAccessor(const Value& row) Value ServicesTable::HighFlapThresholdAccessor(const Value& row)
@ -814,7 +814,7 @@ Value ServicesTable::HighFlapThresholdAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceHighFlapThreshold(service); return CompatUtility::GetCheckableHighFlapThreshold(service);
} }
Value ServicesTable::LatencyAccessor(const Value& row) Value ServicesTable::LatencyAccessor(const Value& row)
@ -844,7 +844,7 @@ Value ServicesTable::PercentStateChangeAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServicePercentStateChange(service); return CompatUtility::GetCheckablePercentStateChange(service);
} }
Value ServicesTable::InCheckPeriodAccessor(const Value& row) Value ServicesTable::InCheckPeriodAccessor(const Value& row)
@ -854,7 +854,7 @@ Value ServicesTable::InCheckPeriodAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceInCheckPeriod(service); return CompatUtility::GetCheckableInCheckPeriod(service);
} }
Value ServicesTable::InNotificationPeriodAccessor(const Value& row) Value ServicesTable::InNotificationPeriodAccessor(const Value& row)
@ -864,7 +864,7 @@ Value ServicesTable::InNotificationPeriodAccessor(const Value& row)
if (!service) if (!service)
return Empty; return Empty;
return CompatUtility::GetServiceInNotificationPeriod(service); return CompatUtility::GetCheckableInNotificationPeriod(service);
} }
Value ServicesTable::ContactsAccessor(const Value& row) Value ServicesTable::ContactsAccessor(const Value& row)
@ -876,7 +876,7 @@ Value ServicesTable::ContactsAccessor(const Value& row)
Array::Ptr contact_names = make_shared<Array>(); Array::Ptr contact_names = make_shared<Array>();
BOOST_FOREACH(const User::Ptr& user, CompatUtility::GetServiceNotificationUsers(service)) { BOOST_FOREACH(const User::Ptr& user, CompatUtility::GetCheckableNotificationUsers(service)) {
contact_names->Add(user->GetName()); contact_names->Add(user->GetName());
} }
@ -898,7 +898,7 @@ Value ServicesTable::DowntimesAccessor(const Value& row)
String id; String id;
Downtime::Ptr downtime; Downtime::Ptr downtime;
BOOST_FOREACH(boost::tie(id, downtime), downtimes) { BOOST_FOREACH(tie(id, downtime), downtimes) {
if (!downtime) if (!downtime)
continue; continue;
@ -927,7 +927,7 @@ Value ServicesTable::DowntimesWithInfoAccessor(const Value& row)
String id; String id;
Downtime::Ptr downtime; Downtime::Ptr downtime;
BOOST_FOREACH(boost::tie(id, downtime), downtimes) { BOOST_FOREACH(tie(id, downtime), downtimes) {
if (!downtime) if (!downtime)
continue; continue;
@ -960,7 +960,7 @@ Value ServicesTable::CommentsAccessor(const Value& row)
String id; String id;
Comment::Ptr comment; Comment::Ptr comment;
BOOST_FOREACH(boost::tie(id, comment), comments) { BOOST_FOREACH(tie(id, comment), comments) {
if (!comment) if (!comment)
continue; continue;
@ -989,7 +989,7 @@ Value ServicesTable::CommentsWithInfoAccessor(const Value& row)
String id; String id;
Comment::Ptr comment; Comment::Ptr comment;
BOOST_FOREACH(boost::tie(id, comment), comments) { BOOST_FOREACH(tie(id, comment), comments) {
if (!comment) if (!comment)
continue; continue;
@ -1022,7 +1022,7 @@ Value ServicesTable::CommentsWithExtraInfoAccessor(const Value& row)
String id; String id;
Comment::Ptr comment; Comment::Ptr comment;
BOOST_FOREACH(boost::tie(id, comment), comments) { BOOST_FOREACH(tie(id, comment), comments) {
if (!comment) if (!comment)
continue; continue;
@ -1063,7 +1063,7 @@ Value ServicesTable::CustomVariableNamesAccessor(const Value& row)
String key; String key;
Value value; Value value;
BOOST_FOREACH(boost::tie(key, value), vars) { BOOST_FOREACH(tie(key, value), vars) {
cv->Add(key); cv->Add(key);
} }
@ -1091,7 +1091,7 @@ Value ServicesTable::CustomVariableValuesAccessor(const Value& row)
String key; String key;
Value value; Value value;
BOOST_FOREACH(boost::tie(key, value), vars) { BOOST_FOREACH(tie(key, value), vars) {
cv->Add(value); cv->Add(value);
} }
@ -1119,7 +1119,7 @@ Value ServicesTable::CustomVariablesAccessor(const Value& row)
String key; String key;
Value value; Value value;
BOOST_FOREACH(boost::tie(key, value), vars) { BOOST_FOREACH(tie(key, value), vars) {
Array::Ptr key_val = make_shared<Array>(); Array::Ptr key_val = make_shared<Array>();
key_val->Add(key); key_val->Add(key);
key_val->Add(value); key_val->Add(value);
@ -1153,7 +1153,7 @@ Value ServicesTable::ContactGroupsAccessor(const Value& row)
Array::Ptr contactgroup_names = make_shared<Array>(); Array::Ptr contactgroup_names = make_shared<Array>();
BOOST_FOREACH(const UserGroup::Ptr& usergroup, CompatUtility::GetServiceNotificationUserGroups(service)) { BOOST_FOREACH(const UserGroup::Ptr& usergroup, CompatUtility::GetCheckableNotificationUserGroups(service)) {
contactgroup_names->Add(usergroup->GetName()); contactgroup_names->Add(usergroup->GetName());
} }

View File

@ -68,23 +68,15 @@ void StateHistTable::UpdateLogEntries(const Dictionary::Ptr& log_entry_attrs, in
String state_type = log_entry_attrs->Get("state_type"); //SOFT, HARD, STARTED, STOPPED, ... String state_type = log_entry_attrs->Get("state_type"); //SOFT, HARD, STARTED, STOPPED, ...
String log_line = log_entry_attrs->Get("message"); /* use message from log table */ String log_line = log_entry_attrs->Get("message"); /* use message from log table */
Service::Ptr state_hist_service; Checkable::Ptr checkable;
/* host alert == get service check */ if (service_description.IsEmpty())
if (service_description.IsEmpty()) { checkable = Host::GetByName(host_name);
Host::Ptr state_host = Host::GetByName(host_name); else
checkable = Service::GetByNamePair(host_name, service_description);
if (!state_host)
return;
state_hist_service = state_host->GetCheckService();
} else {
/* assign service ptr as key */
state_hist_service = Service::GetByNamePair(host_name, service_description);
}
/* invalid log line for state history */ /* invalid log line for state history */
if (!state_hist_service) if (!checkable)
return; return;
Array::Ptr state_hist_service_states; Array::Ptr state_hist_service_states;
@ -92,14 +84,25 @@ void StateHistTable::UpdateLogEntries(const Dictionary::Ptr& log_entry_attrs, in
unsigned long query_part = m_TimeUntil - m_TimeFrom; unsigned long query_part = m_TimeUntil - m_TimeFrom;
/* insert new service states array with values if not existing */ /* insert new service states array with values if not existing */
if (m_ServicesCache.find(state_hist_service) == m_ServicesCache.end()) { if (m_CheckablesCache.find(checkable) == m_CheckablesCache.end()) {
/* create new values */ /* create new values */
state_hist_service_states = make_shared<Array>(); state_hist_service_states = make_shared<Array>();
state_hist_bag = make_shared<Dictionary>(); state_hist_bag = make_shared<Dictionary>();
state_hist_bag->Set("host_name", state_hist_service->GetHost()->GetName()); Service::Ptr service = dynamic_pointer_cast<Service>(checkable);
state_hist_bag->Set("service_description", state_hist_service->GetShortName()); Host::Ptr host;
if (service)
host = service->GetHost();
else
host = static_pointer_cast<Host>(checkable);
state_hist_bag->Set("host_name", host->GetName());
if (service)
state_hist_bag->Set("service_description", service->GetShortName());
state_hist_bag->Set("state", state); state_hist_bag->Set("state", state);
state_hist_bag->Set("in_downtime", 0); state_hist_bag->Set("in_downtime", 0);
state_hist_bag->Set("in_host_downtime", 0); state_hist_bag->Set("in_host_downtime", 0);
@ -114,9 +117,9 @@ void StateHistTable::UpdateLogEntries(const Dictionary::Ptr& log_entry_attrs, in
state_hist_service_states->Add(state_hist_bag); state_hist_service_states->Add(state_hist_bag);
Log(LogDebug, "livestatus", "statehist: Adding new service '" + state_hist_service->GetName() + "' to services cache."); Log(LogDebug, "livestatus", "statehist: Adding new object '" + checkable->GetName() + "' to services cache.");
} else { } else {
state_hist_service_states = m_ServicesCache[state_hist_service]; state_hist_service_states = m_CheckablesCache[checkable];
state_hist_bag = state_hist_service_states->Get(state_hist_service_states->GetLength()-1); /* fetch latest state from history */ state_hist_bag = state_hist_service_states->Get(state_hist_service_states->GetLength()-1); /* fetch latest state from history */
/* state duration */ /* state duration */
@ -124,7 +127,7 @@ void StateHistTable::UpdateLogEntries(const Dictionary::Ptr& log_entry_attrs, in
/* determine service notifications notification_period and compare against current timestamp */ /* determine service notifications notification_period and compare against current timestamp */
bool in_notification_period = true; bool in_notification_period = true;
String notification_period_name; String notification_period_name;
BOOST_FOREACH(const Notification::Ptr& notification, state_hist_service->GetNotifications()) { BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) {
TimePeriod::Ptr notification_period = notification->GetNotificationPeriod(); TimePeriod::Ptr notification_period = notification->GetNotificationPeriod();
if (notification_period) { if (notification_period) {
@ -170,8 +173,8 @@ void StateHistTable::UpdateLogEntries(const Dictionary::Ptr& log_entry_attrs, in
state_hist_service_states->Add(state_hist_bag_new); state_hist_service_states->Add(state_hist_bag_new);
Log(LogDebug, "livestatus", "statehist: State change detected for service '" + Log(LogDebug, "livestatus", "statehist: State change detected for object '" +
state_hist_service->GetName() + "' in '" + log_line + "'."); checkable->GetName() + "' in '" + log_line + "'.");
} }
break; break;
case LogEntryTypeHostFlapping: case LogEntryTypeHostFlapping:
@ -202,7 +205,7 @@ void StateHistTable::UpdateLogEntries(const Dictionary::Ptr& log_entry_attrs, in
} }
m_ServicesCache[state_hist_service] = state_hist_service_states; m_CheckablesCache[checkable] = state_hist_service_states;
/* TODO find a way to directly call addRowFn() - right now m_ServicesCache depends on historical lines ("already seen service") */ /* TODO find a way to directly call addRowFn() - right now m_ServicesCache depends on historical lines ("already seen service") */
} }
@ -257,10 +260,10 @@ void StateHistTable::FetchRows(const AddRowFunction& addRowFn)
/* generate log cache */ /* generate log cache */
LogUtility::CreateLogCache(m_LogFileIndex, this, m_TimeFrom, m_TimeUntil, addRowFn); LogUtility::CreateLogCache(m_LogFileIndex, this, m_TimeFrom, m_TimeUntil, addRowFn);
Service::Ptr state_hist_service; Checkable::Ptr checkable;
BOOST_FOREACH(boost::tie(state_hist_service, boost::tuples::ignore), m_ServicesCache) { BOOST_FOREACH(boost::tie(checkable, boost::tuples::ignore), m_CheckablesCache) {
BOOST_FOREACH(const Dictionary::Ptr& state_hist_bag, m_ServicesCache[state_hist_service]) { BOOST_FOREACH(const Dictionary::Ptr& state_hist_bag, m_CheckablesCache[checkable]) {
/* pass a dictionary from state history array */ /* pass a dictionary from state history array */
addRowFn(state_hist_bag); addRowFn(state_hist_bag);
} }

View File

@ -81,7 +81,7 @@ protected:
private: private:
std::map<time_t, String> m_LogFileIndex; std::map<time_t, String> m_LogFileIndex;
std::map<Service::Ptr, Array::Ptr> m_ServicesCache; std::map<Checkable::Ptr, Array::Ptr> m_CheckablesCache;
time_t m_TimeFrom; time_t m_TimeFrom;
time_t m_TimeUntil; time_t m_TimeUntil;
String m_CompatLogPath; String m_CompatLogPath;

View File

@ -53,7 +53,7 @@ void NotificationComponent::Start(void)
{ {
DynamicObject::Start(); DynamicObject::Start();
Service::OnNotificationsRequested.connect(boost::bind(&NotificationComponent::SendNotificationsHandler, this, _1, Checkable::OnNotificationsRequested.connect(boost::bind(&NotificationComponent::SendNotificationsHandler, this, _1,
_2, _3, _4, _5)); _2, _3, _4, _5));
m_NotificationTimer = make_shared<Timer>(); m_NotificationTimer = make_shared<Timer>();
@ -72,15 +72,15 @@ void NotificationComponent::NotificationTimerHandler(void)
double now = Utility::GetTime(); double now = Utility::GetTime();
BOOST_FOREACH(const Notification::Ptr& notification, DynamicType::GetObjects<Notification>()) { BOOST_FOREACH(const Notification::Ptr& notification, DynamicType::GetObjects<Notification>()) {
Service::Ptr service = notification->GetService(); Checkable::Ptr checkable = notification->GetCheckable();
if (notification->GetNotificationInterval() <= 0 && notification->GetLastProblemNotification() < service->GetLastHardStateChange()) if (notification->GetNotificationInterval() <= 0 && notification->GetLastProblemNotification() < checkable->GetLastHardStateChange())
continue; continue;
if (notification->GetNextNotification() > now) if (notification->GetNextNotification() > now)
continue; continue;
bool reachable = service->IsReachable(); bool reachable = checkable->IsReachable();
{ {
ObjectLock olock(notification); ObjectLock olock(notification);
@ -88,24 +88,33 @@ void NotificationComponent::NotificationTimerHandler(void)
} }
{ {
ObjectLock olock(service); ObjectLock olock(checkable);
if (service->GetStateType() == StateTypeSoft) if (checkable->GetStateType() == StateTypeSoft)
continue; continue;
if (service->GetState() == StateOK) Service::Ptr service = dynamic_pointer_cast<Service>(checkable);
continue;
if (!reachable || service->IsInDowntime() || service->IsAcknowledged()) if (service) {
if (service->GetState() == StateOK)
continue;
} else {
Host::Ptr host = static_pointer_cast<Host>(checkable);
if (host->GetState() == HostUp)
continue;
}
if (!reachable || checkable->IsInDowntime() || checkable->IsAcknowledged())
continue; continue;
} }
try { try {
Log(LogInformation, "notification", "Sending reminder notification for service '" + service->GetName() + "'"); Log(LogInformation, "notification", "Sending reminder notification for object '" + checkable->GetName() + "'");
notification->BeginExecuteNotification(NotificationProblem, service->GetLastCheckResult(), false); notification->BeginExecuteNotification(NotificationProblem, checkable->GetLastCheckResult(), false);
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
std::ostringstream msgbuf; std::ostringstream msgbuf;
msgbuf << "Exception occured during notification for service '" msgbuf << "Exception occured during notification for object '"
<< GetName() << "': " << DiagnosticInformation(ex); << GetName() << "': " << DiagnosticInformation(ex);
String message = msgbuf.str(); String message = msgbuf.str();
@ -117,8 +126,8 @@ void NotificationComponent::NotificationTimerHandler(void)
/** /**
* Processes icinga::SendNotifications messages. * Processes icinga::SendNotifications messages.
*/ */
void NotificationComponent::SendNotificationsHandler(const Service::Ptr& service, NotificationType type, void NotificationComponent::SendNotificationsHandler(const Checkable::Ptr& checkable, NotificationType type,
const CheckResult::Ptr& cr, const String& author, const String& text) const CheckResult::Ptr& cr, const String& author, const String& text)
{ {
service->SendNotifications(type, cr, author, text); checkable->SendNotifications(type, cr, author, text);
} }

View File

@ -45,7 +45,7 @@ private:
Timer::Ptr m_NotificationTimer; Timer::Ptr m_NotificationTimer;
void NotificationTimerHandler(void); void NotificationTimerHandler(void);
void SendNotificationsHandler(const Service::Ptr& service, NotificationType type, void SendNotificationsHandler(const Checkable::Ptr& checkable, NotificationType type,
const CheckResult::Ptr& cr, const String& author, const String& text); const CheckResult::Ptr& cr, const String& author, const String& text);
}; };

View File

@ -94,44 +94,42 @@ void GraphiteWriter::ReconnectTimerHandler(void)
m_Stream = make_shared<BufferedStream>(net_stream); m_Stream = make_shared<BufferedStream>(net_stream);
} }
void GraphiteWriter::CheckResultHandler(const Service::Ptr& service, const CheckResult::Ptr& cr) void GraphiteWriter::CheckResultHandler(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr)
{ {
if (!IcingaApplication::GetInstance()->GetEnablePerfdata() || !service->GetEnablePerfdata()) if (!IcingaApplication::GetInstance()->GetEnablePerfdata() || !checkable->GetEnablePerfdata())
return; return;
Host::Ptr host = service->GetHost(); Service::Ptr service = dynamic_pointer_cast<Service>(checkable);
Host::Ptr host;
if (service)
host = service->GetHost();
else
host = static_pointer_cast<Host>(checkable);
String hostName = host->GetName(); String hostName = host->GetName();
String serviceName = service->GetShortName();
SanitizeMetric(hostName); SanitizeMetric(hostName);
SanitizeMetric(serviceName);
String prefix = "icinga." + hostName + "." + serviceName; String prefix;
/* service metrics */ if (service) {
SendMetric(prefix, "current_attempt", service->GetCheckAttempt()); String serviceName = service->GetShortName();
SendMetric(prefix, "max_check_attempts", service->GetMaxCheckAttempts()); SanitizeMetric(serviceName);
SendMetric(prefix, "state_type", service->GetStateType()); prefix = "icinga." + hostName + "." + serviceName;
SendMetric(prefix, "state", service->GetState());
SendMetric(prefix, "latency", Service::CalculateLatency(cr));
SendMetric(prefix, "execution_time", Service::CalculateExecutionTime(cr));
SendPerfdata(prefix, cr); SendMetric(prefix, "state", service->GetState());
} else {
if (service == host->GetCheckService()) {
prefix = "icinga." + hostName; prefix = "icinga." + hostName;
/* host metrics */
SendMetric(prefix, "current_attempt", service->GetCheckAttempt());
SendMetric(prefix, "max_check_attempts", service->GetMaxCheckAttempts());
SendMetric(prefix, "state_type", host->GetStateType());
SendMetric(prefix, "state", host->GetState()); SendMetric(prefix, "state", host->GetState());
SendMetric(prefix, "latency", Service::CalculateLatency(cr));
SendMetric(prefix, "execution_time", Service::CalculateExecutionTime(cr));
SendPerfdata(prefix, cr);
} }
SendMetric(prefix, "current_attempt", checkable->GetCheckAttempt());
SendMetric(prefix, "max_check_attempts", checkable->GetMaxCheckAttempts());
SendMetric(prefix, "state_type", checkable->GetStateType());
SendMetric(prefix, "latency", Service::CalculateLatency(cr));
SendMetric(prefix, "execution_time", Service::CalculateExecutionTime(cr));
SendPerfdata(prefix, cr);
} }
void GraphiteWriter::SendPerfdata(const String& prefix, const CheckResult::Ptr& cr) void GraphiteWriter::SendPerfdata(const String& prefix, const CheckResult::Ptr& cr)

View File

@ -51,7 +51,7 @@ private:
Timer::Ptr m_ReconnectTimer; Timer::Ptr m_ReconnectTimer;
void CheckResultHandler(const Service::Ptr& service, const CheckResult::Ptr& cr); void CheckResultHandler(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr);
void SendMetric(const String& prefix, const String& name, double value); void SendMetric(const String& prefix, const String& name, double value);
void SendPerfdata(const String& prefix, const CheckResult::Ptr& cr); void SendPerfdata(const String& prefix, const CheckResult::Ptr& cr);
static void SanitizeMetric(String& str); static void SanitizeMetric(String& str);

View File

@ -53,7 +53,7 @@ void PerfdataWriter::Start(void)
{ {
DynamicObject::Start(); DynamicObject::Start();
Service::OnNewCheckResult.connect(boost::bind(&PerfdataWriter::CheckResultHandler, this, _1, _2)); Checkable::OnNewCheckResult.connect(boost::bind(&PerfdataWriter::CheckResultHandler, this, _1, _2));
m_RotationTimer = make_shared<Timer>(); m_RotationTimer = make_shared<Timer>();
m_RotationTimer->OnTimerExpired.connect(boost::bind(&PerfdataWriter::RotationTimerHandler, this)); m_RotationTimer->OnTimerExpired.connect(boost::bind(&PerfdataWriter::RotationTimerHandler, this));
@ -64,35 +64,39 @@ void PerfdataWriter::Start(void)
RotateFile(m_HostOutputFile, GetHostTempPath(), GetHostPerfdataPath()); RotateFile(m_HostOutputFile, GetHostTempPath(), GetHostPerfdataPath());
} }
void PerfdataWriter::CheckResultHandler(const Service::Ptr& service, const CheckResult::Ptr& cr) void PerfdataWriter::CheckResultHandler(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr)
{ {
CONTEXT("Writing performance data for service '" + service->GetShortName() + "' on host '" + service->GetHost()->GetName() + "'"); CONTEXT("Writing performance data for object '" + checkable->GetName() + "'");
if (!IcingaApplication::GetInstance()->GetEnablePerfdata() || !service->GetEnablePerfdata()) if (!IcingaApplication::GetInstance()->GetEnablePerfdata() || !checkable->GetEnablePerfdata())
return; return;
Host::Ptr host = service->GetHost(); Service::Ptr service = dynamic_pointer_cast<Service>(checkable);
Host::Ptr host;
if (service)
host = service->GetHost();
else
host = static_pointer_cast<Host>(checkable);
std::vector<MacroResolver::Ptr> resolvers; std::vector<MacroResolver::Ptr> resolvers;
resolvers.push_back(service); if (service)
resolvers.push_back(service);
resolvers.push_back(host); resolvers.push_back(host);
resolvers.push_back(IcingaApplication::GetInstance()); resolvers.push_back(IcingaApplication::GetInstance());
String line = MacroProcessor::ResolveMacros(GetServiceFormatTemplate(), resolvers, cr); if (service) {
String line = MacroProcessor::ResolveMacros(GetServiceFormatTemplate(), resolvers, cr);
{ {
ObjectLock olock(this); ObjectLock olock(this);
if (!m_ServiceOutputFile.good()) if (!m_ServiceOutputFile.good())
return; return;
m_ServiceOutputFile << line << "\n"; m_ServiceOutputFile << line << "\n";
} }
} else {
if (service == host->GetCheckService()) { String line = MacroProcessor::ResolveMacros(GetHostFormatTemplate(), resolvers, cr);
resolvers.clear();
resolvers.push_back(host);
resolvers.push_back(IcingaApplication::GetInstance());
line = MacroProcessor::ResolveMacros(GetHostFormatTemplate(), resolvers, cr);
{ {
ObjectLock olock(this); ObjectLock olock(this);

View File

@ -46,7 +46,7 @@ protected:
virtual void Start(void); virtual void Start(void);
private: private:
void CheckResultHandler(const Service::Ptr& service, const CheckResult::Ptr& cr); void CheckResultHandler(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr);
Timer::Ptr m_RotationTimer; Timer::Ptr m_RotationTimer;
void RotationTimerHandler(void); void RotationTimerHandler(void);

View File

@ -34,6 +34,7 @@
#include <boost/smart_ptr/weak_ptr.hpp> #include <boost/smart_ptr/weak_ptr.hpp>
#include <boost/smart_ptr/enable_shared_from_this.hpp> #include <boost/smart_ptr/enable_shared_from_this.hpp>
#include <boost/smart_ptr/make_shared.hpp> #include <boost/smart_ptr/make_shared.hpp>
#include <boost/tuple/tuple.hpp>
using boost::shared_ptr; using boost::shared_ptr;
using boost::weak_ptr; using boost::weak_ptr;
@ -41,6 +42,7 @@ using boost::enable_shared_from_this;
using boost::dynamic_pointer_cast; using boost::dynamic_pointer_cast;
using boost::static_pointer_cast; using boost::static_pointer_cast;
using boost::make_shared; using boost::make_shared;
using boost::tie;
namespace icinga namespace icinga
{ {

View File

@ -21,7 +21,7 @@ mkembedconfig_target(db_ido-type.conf db_ido-type.cpp)
add_library(db_ido SHARED add_library(db_ido SHARED
commanddbobject.cpp dbconnection.cpp dbconnection.th dbconnection.th commanddbobject.cpp dbconnection.cpp dbconnection.th dbconnection.th
db_ido-type.cpp dbobject.cpp dbquery.cpp dbreference.cpp dbtype.cpp db_ido-type.cpp dbevents.cpp dbobject.cpp dbquery.cpp dbreference.cpp dbtype.cpp
dbvalue.cpp endpointdbobject.cpp hostdbobject.cpp hostgroupdbobject.cpp dbvalue.cpp endpointdbobject.cpp hostdbobject.cpp hostgroupdbobject.cpp
servicedbobject.cpp servicegroupdbobject.cpp timeperioddbobject.cpp servicedbobject.cpp servicegroupdbobject.cpp timeperioddbobject.cpp
userdbobject.cpp usergroupdbobject.cpp userdbobject.cpp usergroupdbobject.cpp

1078
lib/db_ido/dbevents.cpp Normal file

File diff suppressed because it is too large Load Diff

120
lib/db_ido/dbevents.h Normal file
View File

@ -0,0 +1,120 @@
/******************************************************************************
* Icinga 2 *
* Copyright (C) 2012-2014 Icinga Development Team (http://www.icinga.org) *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software Foundation *
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
******************************************************************************/
#ifndef DBEVENTS_H
#define DBEVENTS_H
#include "db_ido/dbobject.h"
#include "base/dynamicobject.h"
#include "icinga/service.h"
namespace icinga
{
enum LogEntryType
{
LogEntryTypeRuntimeError = 1,
LogEntryTypeRuntimeWarning = 2,
LogEntryTypeVerificationError = 4,
LogEntryTypeVerificationWarning = 8,
LogEntryTypeConfigError = 16,
LogEntryTypeConfigWarning = 32,
LogEntryTypeProcessInfo = 64,
LogEntryTypeEventHandler = 128,
LogEntryTypeExternalCommand = 512,
LogEntryTypeHostUp = 1024,
LogEntryTypeHostDown = 2048,
LogEntryTypeHostUnreachable = 4096,
LogEntryTypeServiceOk = 8192,
LogEntryTypeServiceUnknown = 16384,
LogEntryTypeServiceWarning = 32768,
LogEntryTypeServiceCritical = 65536,
LogEntryTypePassiveCheck = 1231072,
LogEntryTypeInfoMessage = 262144,
LogEntryTypeHostNotification = 524288,
LogEntryTypeServiceNotification = 1048576
};
/**
* IDO events
*
* @ingroup ido
*/
class DbEvents
{
public:
static void StaticInitialize(void);
static void AddCommentByType(const DynamicObject::Ptr& object, const Comment::Ptr& comment, bool historical);
static void AddComments(const Checkable::Ptr& checkable);
static void RemoveComments(const Checkable::Ptr& checkable);
static void AddDowntimeByType(const Checkable::Ptr& checkable, const Downtime::Ptr& downtime, bool historical);
static void AddDowntimes(const Checkable::Ptr& checkable);
static void RemoveDowntimes(const Checkable::Ptr& checkable);
static void AddLogHistory(const Checkable::Ptr& checkable, String buffer, LogEntryType type);
/* Status */
static void AddComment(const Checkable::Ptr& checkable, const Comment::Ptr& comment);
static void RemoveComment(const Checkable::Ptr& checkable, const Comment::Ptr& comment);
static void AddDowntime(const Checkable::Ptr& checkable, const Downtime::Ptr& downtime);
static void RemoveDowntime(const Checkable::Ptr& checkable, const Downtime::Ptr& downtime);
static void TriggerDowntime(const Checkable::Ptr& checkable, const Downtime::Ptr& downtime);
/* comment, downtime, acknowledgement history */
static void AddCommentHistory(const Checkable::Ptr& checkable, const Comment::Ptr& comment);
static void AddDowntimeHistory(const Checkable::Ptr& checkable, const Downtime::Ptr& downtime);
static void AddAcknowledgementHistory(const Checkable::Ptr& checkable, const String& author, const String& comment,
AcknowledgementType type, double expiry);
/* notification & contactnotification history */
static void AddNotificationHistory(const Notification::Ptr& notification, const Checkable::Ptr& checkable,
const std::set<User::Ptr>& users, NotificationType type, const CheckResult::Ptr& cr, const String& author,
const String& text);
/* statehistory */
static void AddStateChangeHistory(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr, StateType type);
/* logentries */
static void AddCheckResultLogHistory(const Checkable::Ptr& checkable, const CheckResult::Ptr &cr);
static void AddTriggerDowntimeLogHistory(const Checkable::Ptr& checkable, const Downtime::Ptr& downtime);
static void AddRemoveDowntimeLogHistory(const Checkable::Ptr& checkable, const Downtime::Ptr& downtime);
static void AddNotificationSentLogHistory(const Notification::Ptr& notification, const Checkable::Ptr& checkable,
const User::Ptr& user, NotificationType notification_type, const CheckResult::Ptr& cr, const String& author,
const String& comment_text);
static void AddFlappingLogHistory(const Checkable::Ptr& checkable, FlappingState flapping_state);
/* other history */
static void AddFlappingHistory(const Checkable::Ptr& checkable, FlappingState flapping_state);
static void AddServiceCheckHistory(const Checkable::Ptr& checkable, const CheckResult::Ptr &cr);
static void AddEventHandlerHistory(const Checkable::Ptr& checkable);
static void AddExternalCommandHistory(double time, const String& command, const std::vector<String>& arguments);
private:
DbEvents(void);
static void AddCommentInternal(const Checkable::Ptr& checkable, const Comment::Ptr& comment, bool historical);
static void AddDowntimeInternal(const Checkable::Ptr& checkable, const Downtime::Ptr& downtime, bool historical);
};
}
#endif /* DBEVENTS_H */

View File

@ -43,64 +43,56 @@ Dictionary::Ptr HostDbObject::GetConfigFields(void) const
Dictionary::Ptr fields = make_shared<Dictionary>(); Dictionary::Ptr fields = make_shared<Dictionary>();
Host::Ptr host = static_pointer_cast<Host>(GetObject()); Host::Ptr host = static_pointer_cast<Host>(GetObject());
Service::Ptr service = host->GetCheckService();
fields->Set("alias", CompatUtility::GetHostAlias(host)); fields->Set("alias", CompatUtility::GetHostAlias(host));
fields->Set("display_name", host->GetDisplayName()); fields->Set("display_name", host->GetDisplayName());
fields->Set("address", CompatUtility::GetHostAddress(host)); fields->Set("address", CompatUtility::GetHostAddress(host));
fields->Set("address6", CompatUtility::GetHostAddress6(host)); fields->Set("address6", CompatUtility::GetHostAddress6(host));
if (service) { fields->Set("check_service_object_id", host);
fields->Set("check_service_object_id", service); fields->Set("check_command_object_id", host->GetCheckCommand());
fields->Set("check_command_object_id", service->GetCheckCommand()); fields->Set("check_command_args", Empty);
fields->Set("check_command_args", Empty); fields->Set("eventhandler_command_object_id", host->GetEventCommand());
fields->Set("eventhandler_command_object_id", service->GetEventCommand()); fields->Set("eventhandler_command_args", Empty);
fields->Set("eventhandler_command_args", Empty); fields->Set("notification_timeperiod_object_id", Notification::GetByName(CompatUtility::GetCheckableNotificationNotificationPeriod(host)));
fields->Set("notification_timeperiod_object_id", Notification::GetByName(CompatUtility::GetServiceNotificationNotificationPeriod(service))); fields->Set("check_timeperiod_object_id", host->GetCheckPeriod());
fields->Set("check_timeperiod_object_id", service->GetCheckPeriod()); fields->Set("failure_prediction_options", Empty);
fields->Set("failure_prediction_options", Empty); fields->Set("check_interval", CompatUtility::GetCheckableCheckInterval(host));
fields->Set("check_interval", CompatUtility::GetServiceCheckInterval(service)); fields->Set("retry_interval", CompatUtility::GetCheckableRetryInterval(host));
fields->Set("retry_interval", CompatUtility::GetServiceRetryInterval(service)); fields->Set("max_check_attempts", host->GetMaxCheckAttempts());
fields->Set("max_check_attempts", service->GetMaxCheckAttempts());
fields->Set("first_notification_delay", Empty); fields->Set("first_notification_delay", Empty);
fields->Set("notification_interval", CompatUtility::GetServiceNotificationNotificationInterval(service)); fields->Set("notification_interval", CompatUtility::GetCheckableNotificationNotificationInterval(host));
/* requires host check service */ fields->Set("notify_on_down", CompatUtility::GetHostNotifyOnDown(host));
fields->Set("notify_on_down", CompatUtility::GetHostNotifyOnDown(host)); fields->Set("notify_on_unreachable", CompatUtility::GetHostNotifyOnDown(host));
fields->Set("notify_on_unreachable", CompatUtility::GetHostNotifyOnDown(host));
fields->Set("notify_on_recovery", CompatUtility::GetServiceNotifyOnRecovery(service)); fields->Set("notify_on_recovery", CompatUtility::GetCheckableNotifyOnRecovery(host));
fields->Set("notify_on_flapping", CompatUtility::GetServiceNotifyOnFlapping(service)); fields->Set("notify_on_flapping", CompatUtility::GetCheckableNotifyOnFlapping(host));
fields->Set("notify_on_downtime", CompatUtility::GetServiceNotifyOnDowntime(service)); fields->Set("notify_on_downtime", CompatUtility::GetCheckableNotifyOnDowntime(host));
fields->Set("stalk_on_up", Empty); fields->Set("stalk_on_up", Empty);
fields->Set("stalk_on_down", Empty); fields->Set("stalk_on_down", Empty);
fields->Set("stalk_on_unreachable", Empty); fields->Set("stalk_on_unreachable", Empty);
fields->Set("flap_detection_enabled", CompatUtility::GetServiceFlapDetectionEnabled(service)); fields->Set("flap_detection_enabled", CompatUtility::GetCheckableFlapDetectionEnabled(host));
fields->Set("flap_detection_on_up", Empty); fields->Set("flap_detection_on_up", Empty);
fields->Set("flap_detection_on_down", Empty); fields->Set("flap_detection_on_down", Empty);
fields->Set("flap_detection_on_unreachable", Empty); fields->Set("flap_detection_on_unreachable", Empty);
fields->Set("low_flap_threshold", CompatUtility::GetServiceLowFlapThreshold(service)); fields->Set("low_flap_threshold", CompatUtility::GetCheckableLowFlapThreshold(host));
fields->Set("high_flap_threshold", CompatUtility::GetServiceHighFlapThreshold(service)); fields->Set("high_flap_threshold", CompatUtility::GetCheckableHighFlapThreshold(host));
}
fields->Set("process_performance_data", 0); fields->Set("process_performance_data", 0);
if (service) { fields->Set("freshness_checks_enabled", CompatUtility::GetCheckableFreshnessChecksEnabled(host));
fields->Set("freshness_checks_enabled", CompatUtility::GetServiceFreshnessChecksEnabled(service)); fields->Set("freshness_threshold", CompatUtility::GetCheckableFreshnessThreshold(host));
fields->Set("freshness_threshold", CompatUtility::GetServiceFreshnessThreshold(service)); fields->Set("passive_checks_enabled", CompatUtility::GetCheckablePassiveChecksEnabled(host));
fields->Set("passive_checks_enabled", CompatUtility::GetServicePassiveChecksEnabled(service)); fields->Set("event_handler_enabled", CompatUtility::GetCheckableEventHandlerEnabled(host));
fields->Set("event_handler_enabled", CompatUtility::GetServiceEventHandlerEnabled(service)); fields->Set("active_checks_enabled", CompatUtility::GetCheckableActiveChecksEnabled(host));
fields->Set("active_checks_enabled", CompatUtility::GetServiceActiveChecksEnabled(service));
}
fields->Set("retain_status_information", 1); fields->Set("retain_status_information", 1);
fields->Set("retain_nonstatus_information", 1); fields->Set("retain_nonstatus_information", 1);
if (service) fields->Set("notifications_enabled", CompatUtility::GetCheckableNotificationsEnabled(host));
fields->Set("notifications_enabled", CompatUtility::GetServiceNotificationsEnabled(service));
fields->Set("obsess_over_host", 0); fields->Set("obsess_over_host", 0);
fields->Set("failure_prediction_enabled", 0); fields->Set("failure_prediction_enabled", 0);
@ -131,72 +123,63 @@ Dictionary::Ptr HostDbObject::GetStatusFields(void) const
{ {
Dictionary::Ptr fields = make_shared<Dictionary>(); Dictionary::Ptr fields = make_shared<Dictionary>();
Host::Ptr host = static_pointer_cast<Host>(GetObject()); Host::Ptr host = static_pointer_cast<Host>(GetObject());
Service::Ptr service = host->GetCheckService();
/* fetch service status, or dump a pending hoststatus */ CheckResult::Ptr cr = host->GetLastCheckResult();
if (service) {
CheckResult::Ptr cr = service->GetLastCheckResult();
if (cr) { if (cr) {
fields->Set("output", CompatUtility::GetCheckResultOutput(cr)); fields->Set("output", CompatUtility::GetCheckResultOutput(cr));
fields->Set("long_output", CompatUtility::GetCheckResultLongOutput(cr)); fields->Set("long_output", CompatUtility::GetCheckResultLongOutput(cr));
fields->Set("perfdata", CompatUtility::GetCheckResultPerfdata(cr)); fields->Set("perfdata", CompatUtility::GetCheckResultPerfdata(cr));
fields->Set("check_source", cr->GetCheckSource()); fields->Set("check_source", cr->GetCheckSource());
}
fields->Set("current_state", host->GetState());
fields->Set("has_been_checked", CompatUtility::GetServiceHasBeenChecked(service));
fields->Set("should_be_scheduled", CompatUtility::GetServiceShouldBeScheduled(service));
fields->Set("current_check_attempt", service->GetCheckAttempt());
fields->Set("max_check_attempts", service->GetMaxCheckAttempts());
if (cr)
fields->Set("last_check", DbValue::FromTimestamp(cr->GetScheduleEnd()));
fields->Set("next_check", DbValue::FromTimestamp(service->GetNextCheck()));
fields->Set("check_type", CompatUtility::GetServiceCheckType(service));
fields->Set("last_state_change", DbValue::FromTimestamp(service->GetLastStateChange()));
fields->Set("last_hard_state_change", DbValue::FromTimestamp(service->GetLastHardStateChange()));
fields->Set("last_time_up", DbValue::FromTimestamp(static_cast<int>(host->GetLastStateUp())));
fields->Set("last_time_down", DbValue::FromTimestamp(static_cast<int>(host->GetLastStateDown())));
fields->Set("last_time_unreachable", DbValue::FromTimestamp(static_cast<int>(host->GetLastStateUnreachable())));
fields->Set("state_type", service->GetStateType());
fields->Set("last_notification", DbValue::FromTimestamp(CompatUtility::GetServiceNotificationLastNotification(service)));
fields->Set("next_notification", DbValue::FromTimestamp(CompatUtility::GetServiceNotificationNextNotification(service)));
fields->Set("no_more_notifications", Empty);
fields->Set("notifications_enabled", CompatUtility::GetServiceNotificationsEnabled(service));
fields->Set("problem_has_been_acknowledged", CompatUtility::GetServiceProblemHasBeenAcknowledged(service));
fields->Set("acknowledgement_type", CompatUtility::GetServiceAcknowledgementType(service));
fields->Set("current_notification_number", CompatUtility::GetServiceNotificationNotificationNumber(service));
fields->Set("passive_checks_enabled", CompatUtility::GetServicePassiveChecksEnabled(service));
fields->Set("active_checks_enabled", CompatUtility::GetServiceActiveChecksEnabled(service));
fields->Set("event_handler_enabled", CompatUtility::GetServiceEventHandlerEnabled(service));
fields->Set("flap_detection_enabled", CompatUtility::GetServiceFlapDetectionEnabled(service));
fields->Set("is_flapping", CompatUtility::GetServiceIsFlapping(service));
fields->Set("percent_state_change", CompatUtility::GetServicePercentStateChange(service));
if (cr) {
fields->Set("latency", Convert::ToString(Service::CalculateLatency(cr)));
fields->Set("execution_time", Convert::ToString(Service::CalculateExecutionTime(cr)));
}
fields->Set("scheduled_downtime_depth", service->GetDowntimeDepth());
fields->Set("failure_prediction_enabled", Empty);
fields->Set("process_performance_data", 0); /* this is a host which does not process any perf data */
fields->Set("obsess_over_host", Empty);
fields->Set("modified_host_attributes", service->GetModifiedAttributes());
fields->Set("event_handler", CompatUtility::GetServiceEventHandler(service));
fields->Set("check_command", CompatUtility::GetServiceCheckCommand(service));
fields->Set("normal_check_interval", CompatUtility::GetServiceCheckInterval(service));
fields->Set("retry_check_interval", CompatUtility::GetServiceRetryInterval(service));
fields->Set("check_timeperiod_object_id", service->GetCheckPeriod());
} }
else {
fields->Set("has_been_checked", 0); fields->Set("current_state", host->GetState());
fields->Set("last_check", DbValue::FromTimestamp(0)); fields->Set("has_been_checked", CompatUtility::GetCheckableHasBeenChecked(host));
fields->Set("next_check", DbValue::FromTimestamp(0)); fields->Set("should_be_scheduled", CompatUtility::GetCheckableShouldBeScheduled(host));
fields->Set("active_checks_enabled", 0); fields->Set("current_check_attempt", host->GetCheckAttempt());
fields->Set("max_check_attempts", host->GetMaxCheckAttempts());
if (cr)
fields->Set("last_check", DbValue::FromTimestamp(cr->GetScheduleEnd()));
fields->Set("next_check", DbValue::FromTimestamp(host->GetNextCheck()));
fields->Set("check_type", CompatUtility::GetCheckableCheckType(host));
fields->Set("last_state_change", DbValue::FromTimestamp(host->GetLastStateChange()));
fields->Set("last_hard_state_change", DbValue::FromTimestamp(host->GetLastHardStateChange()));
fields->Set("last_time_up", DbValue::FromTimestamp(static_cast<int>(host->GetLastStateUp())));
fields->Set("last_time_down", DbValue::FromTimestamp(static_cast<int>(host->GetLastStateDown())));
fields->Set("last_time_unreachable", DbValue::FromTimestamp(static_cast<int>(host->GetLastStateUnreachable())));
fields->Set("state_type", host->GetStateType());
fields->Set("last_notification", DbValue::FromTimestamp(CompatUtility::GetCheckableNotificationLastNotification(host)));
fields->Set("next_notification", DbValue::FromTimestamp(CompatUtility::GetCheckableNotificationNextNotification(host)));
fields->Set("no_more_notifications", Empty);
fields->Set("notifications_enabled", CompatUtility::GetCheckableNotificationsEnabled(host));
fields->Set("problem_has_been_acknowledged", CompatUtility::GetCheckableProblemHasBeenAcknowledged(host));
fields->Set("acknowledgement_type", CompatUtility::GetCheckableAcknowledgementType(host));
fields->Set("current_notification_number", CompatUtility::GetCheckableNotificationNotificationNumber(host));
fields->Set("passive_checks_enabled", CompatUtility::GetCheckablePassiveChecksEnabled(host));
fields->Set("active_checks_enabled", CompatUtility::GetCheckableActiveChecksEnabled(host));
fields->Set("event_handler_enabled", CompatUtility::GetCheckableEventHandlerEnabled(host));
fields->Set("flap_detection_enabled", CompatUtility::GetCheckableFlapDetectionEnabled(host));
fields->Set("is_flapping", CompatUtility::GetCheckableIsFlapping(host));
fields->Set("percent_state_change", CompatUtility::GetCheckablePercentStateChange(host));
if (cr) {
fields->Set("latency", Convert::ToString(Service::CalculateLatency(cr)));
fields->Set("execution_time", Convert::ToString(Service::CalculateExecutionTime(cr)));
} }
fields->Set("scheduled_downtime_depth", host->GetDowntimeDepth());
fields->Set("failure_prediction_enabled", Empty);
fields->Set("process_performance_data", 0); /* this is a host which does not process any perf data */
fields->Set("obsess_over_host", Empty);
fields->Set("modified_host_attributes", host->GetModifiedAttributes());
fields->Set("event_handler", CompatUtility::GetCheckableEventHandler(host));
fields->Set("check_command", CompatUtility::GetCheckableCheckCommand(host));
fields->Set("normal_check_interval", CompatUtility::GetCheckableCheckInterval(host));
fields->Set("retry_check_interval", CompatUtility::GetCheckableRetryInterval(host));
fields->Set("check_timeperiod_object_id", host->GetCheckPeriod());
return fields; return fields;
} }
@ -205,7 +188,12 @@ void HostDbObject::OnConfigUpdate(void)
Host::Ptr host = static_pointer_cast<Host>(GetObject()); Host::Ptr host = static_pointer_cast<Host>(GetObject());
/* parents, host dependencies */ /* parents, host dependencies */
BOOST_FOREACH(const Host::Ptr& parent, host->GetParentHosts()) { BOOST_FOREACH(const Checkable::Ptr& checkable, host->GetParents()) {
Host::Ptr parent = dynamic_pointer_cast<Host>(checkable);
if (!parent)
continue;
Log(LogDebug, "db_ido", "host parents: " + parent->GetName()); Log(LogDebug, "db_ido", "host parents: " + parent->GetName());
/* parents: host_id, parent_host_object_id */ /* parents: host_id, parent_host_object_id */
@ -235,45 +223,40 @@ void HostDbObject::OnConfigUpdate(void)
OnQuery(query2); OnQuery(query2);
} }
/* host contacts, contactgroups */ Log(LogDebug, "db_ido", "host contacts: " + host->GetName());
Service::Ptr service = host->GetCheckService();
if (service) { BOOST_FOREACH(const User::Ptr& user, CompatUtility::GetCheckableNotificationUsers(host)) {
Log(LogDebug, "db_ido", "host contacts: " + host->GetName()); Log(LogDebug, "db_ido", "host contacts: " + user->GetName());
BOOST_FOREACH(const User::Ptr& user, CompatUtility::GetServiceNotificationUsers(service)) { Dictionary::Ptr fields_contact = make_shared<Dictionary>();
Log(LogDebug, "db_ido", "host contacts: " + user->GetName()); fields_contact->Set("host_id", DbValue::FromObjectInsertID(host));
fields_contact->Set("contact_object_id", user);
fields_contact->Set("instance_id", 0); /* DbConnection class fills in real ID */
Dictionary::Ptr fields_contact = make_shared<Dictionary>(); DbQuery query_contact;
fields_contact->Set("host_id", DbValue::FromObjectInsertID(host)); query_contact.Table = GetType()->GetTable() + "_contacts";
fields_contact->Set("contact_object_id", user); query_contact.Type = DbQueryInsert;
fields_contact->Set("instance_id", 0); /* DbConnection class fills in real ID */ query_contact.Category = DbCatConfig;
query_contact.Fields = fields_contact;
OnQuery(query_contact);
}
DbQuery query_contact; Log(LogDebug, "db_ido", "host contactgroups: " + host->GetName());
query_contact.Table = GetType()->GetTable() + "_contacts";
query_contact.Type = DbQueryInsert;
query_contact.Category = DbCatConfig;
query_contact.Fields = fields_contact;
OnQuery(query_contact);
}
Log(LogDebug, "db_ido", "host contactgroups: " + host->GetName()); BOOST_FOREACH(const UserGroup::Ptr& usergroup, CompatUtility::GetCheckableNotificationUserGroups(host)) {
Log(LogDebug, "db_ido", "host contactgroups: " + usergroup->GetName());
BOOST_FOREACH(const UserGroup::Ptr& usergroup, CompatUtility::GetServiceNotificationUserGroups(service)) { Dictionary::Ptr fields_contact = make_shared<Dictionary>();
Log(LogDebug, "db_ido", "host contactgroups: " + usergroup->GetName()); fields_contact->Set("host_id", DbValue::FromObjectInsertID(host));
fields_contact->Set("contactgroup_object_id", usergroup);
fields_contact->Set("instance_id", 0); /* DbConnection class fills in real ID */
Dictionary::Ptr fields_contact = make_shared<Dictionary>(); DbQuery query_contact;
fields_contact->Set("host_id", DbValue::FromObjectInsertID(host)); query_contact.Table = GetType()->GetTable() + "_contactgroups";
fields_contact->Set("contactgroup_object_id", usergroup); query_contact.Type = DbQueryInsert;
fields_contact->Set("instance_id", 0); /* DbConnection class fills in real ID */ query_contact.Category = DbCatConfig;
query_contact.Fields = fields_contact;
DbQuery query_contact; OnQuery(query_contact);
query_contact.Table = GetType()->GetTable() + "_contactgroups";
query_contact.Type = DbQueryInsert;
query_contact.Category = DbCatConfig;
query_contact.Fields = fields_contact;
OnQuery(query_contact);
}
} }
/* custom variables */ /* custom variables */

File diff suppressed because it is too large Load Diff

View File

@ -27,30 +27,6 @@
namespace icinga namespace icinga
{ {
enum LogEntryType
{
LogEntryTypeRuntimeError = 1,
LogEntryTypeRuntimeWarning = 2,
LogEntryTypeVerificationError = 4,
LogEntryTypeVerificationWarning = 8,
LogEntryTypeConfigError = 16,
LogEntryTypeConfigWarning = 32,
LogEntryTypeProcessInfo = 64,
LogEntryTypeEventHandler = 128,
LogEntryTypeExternalCommand = 512,
LogEntryTypeHostUp = 1024,
LogEntryTypeHostDown = 2048,
LogEntryTypeHostUnreachable = 4096,
LogEntryTypeServiceOk = 8192,
LogEntryTypeServiceUnknown = 16384,
LogEntryTypeServiceWarning = 32768,
LogEntryTypeServiceCritical = 65536,
LogEntryTypePassiveCheck = 1231072,
LogEntryTypeInfoMessage = 262144,
LogEntryTypeHostNotification = 524288,
LogEntryTypeServiceNotification = 1048576
};
/** /**
* A Service database object. * A Service database object.
* *
@ -73,56 +49,6 @@ protected:
virtual void OnConfigUpdate(void); virtual void OnConfigUpdate(void);
virtual void OnStatusUpdate(void); virtual void OnStatusUpdate(void);
private:
static void AddCommentInternal(const Service::Ptr& service, const Comment::Ptr& comment, bool historical);
static void AddCommentByType(const DynamicObject::Ptr& object, const Comment::Ptr& comment, bool historical);
static void AddComments(const Service::Ptr& service);
static void RemoveComments(const Service::Ptr& service);
static void AddDowntimeInternal(const Service::Ptr& service, const Downtime::Ptr& downtime, bool historical);
static void AddDowntimeByType(const DynamicObject::Ptr& object, const Downtime::Ptr& downtime, bool historical);
static void AddDowntimes(const Service::Ptr& service);
static void RemoveDowntimes(const Service::Ptr& service);
static void AddLogHistory(const Service::Ptr& service, String buffer, LogEntryType type);
/* Status */
static void AddComment(const Service::Ptr& service, const Comment::Ptr& comment);
static void RemoveComment(const Service::Ptr& service, const Comment::Ptr& comment);
static void AddDowntime(const Service::Ptr& service, const Downtime::Ptr& downtime);
static void RemoveDowntime(const Service::Ptr& service, const Downtime::Ptr& downtime);
static void TriggerDowntime(const Service::Ptr& service, const Downtime::Ptr& downtime);
/* comment, downtime, acknowledgement history */
static void AddCommentHistory(const Service::Ptr& service, const Comment::Ptr& comment);
static void AddDowntimeHistory(const Service::Ptr& service, const Downtime::Ptr& downtime);
static void AddAcknowledgementHistory(const Service::Ptr& service, const String& author, const String& comment,
AcknowledgementType type, double expiry);
/* notification & contactnotification history */
static void AddNotificationHistory(const Notification::Ptr& notification, const Service::Ptr& service,
const std::set<User::Ptr>& users, NotificationType type, const CheckResult::Ptr& cr, const String& author,
const String& text);
/* statehistory */
static void AddStateChangeHistory(const Service::Ptr& service, const CheckResult::Ptr& cr, StateType type);
/* logentries */
static void AddCheckResultLogHistory(const Service::Ptr& service, const CheckResult::Ptr &cr);
static void AddTriggerDowntimeLogHistory(const Service::Ptr& service, const Downtime::Ptr& downtime);
static void AddRemoveDowntimeLogHistory(const Service::Ptr& service, const Downtime::Ptr& downtime);
static void AddNotificationSentLogHistory(const Notification::Ptr& notification, const Service::Ptr& service,
const User::Ptr& user, NotificationType notification_type, const CheckResult::Ptr& cr, const String& author,
const String& comment_text);
static void AddFlappingLogHistory(const Service::Ptr& service, FlappingState flapping_state);
/* other history */
static void AddFlappingHistory(const Service::Ptr& service, FlappingState flapping_state);
static void AddServiceCheckHistory(const Service::Ptr& service, const CheckResult::Ptr &cr);
static void AddEventHandlerHistory(const Service::Ptr& service);
static void AddExternalCommandHistory(double time, const String& command, const std::vector<String>& arguments);
}; };
} }

View File

@ -15,6 +15,7 @@
# along with this program; if not, write to the Free Software Foundation # along with this program; if not, write to the Free Software Foundation
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. # Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
mkclass_target(checkable.ti checkable.th)
mkclass_target(checkcommand.ti checkcommand.th) mkclass_target(checkcommand.ti checkcommand.th)
mkclass_target(checkresult.ti checkresult.th) mkclass_target(checkresult.ti checkresult.th)
mkclass_target(command.ti command.th) mkclass_target(command.ti command.th)
@ -40,7 +41,8 @@ mkclass_target(user.ti user.th)
mkembedconfig_target(icinga-type.conf icinga-type.cpp) mkembedconfig_target(icinga-type.conf icinga-type.cpp)
add_library(icinga SHARED add_library(icinga SHARED
api.cpp api.h checkcommand.cpp checkcommand.th checkresult.cpp checkresult.th api.cpp checkable.cpp checkable.th checkable-dependency.cpp checkable-downtime.cpp checkable-event.cpp
checkable-flapping.cpp checkcommand.cpp checkcommand.th checkresult.cpp checkresult.th
cib.cpp command.cpp command.th comment.cpp comment.th compatutility.cpp dependency.cpp dependency.th cib.cpp command.cpp command.th comment.cpp comment.th compatutility.cpp dependency.cpp dependency.th
dependency-apply.cpp domain.cpp domain.th downtime.cpp downtime.th eventcommand.cpp eventcommand.th dependency-apply.cpp domain.cpp domain.th downtime.cpp downtime.th eventcommand.cpp eventcommand.th
externalcommandprocessor.cpp host.cpp host.th hostgroup.cpp hostgroup.th externalcommandprocessor.cpp host.cpp host.th hostgroup.cpp hostgroup.th
@ -49,9 +51,8 @@ add_library(icinga SHARED
macroprocessor.cpp macroresolver.cpp notificationcommand.cpp notificationcommand.th macroprocessor.cpp macroresolver.cpp notificationcommand.cpp notificationcommand.th
notification.cpp notification.th notification-apply.cpp perfdatavalue.cpp perfdatavalue.th notification.cpp notification.th notification-apply.cpp perfdatavalue.cpp perfdatavalue.th
pluginutility.cpp scheduleddowntime.cpp scheduleddowntime.th scheduleddowntime-apply.cpp pluginutility.cpp scheduleddowntime.cpp scheduleddowntime.th scheduleddowntime-apply.cpp
service-apply.cpp service-check.cpp service-comment.cpp service.cpp service-dependency.cpp service-apply.cpp checkable-check.cpp checkable-comment.cpp service.cpp service.th
service-downtime.cpp service-event.cpp service-flapping.cpp service.th servicegroup.cpp servicegroup.th servicegroup.cpp servicegroup.th checkable-notification.cpp timeperiod.cpp timeperiod.th user.cpp user.th
service-notification.cpp timeperiod.cpp timeperiod.th user.cpp user.th
usergroup.cpp usergroup.th icinga-type.cpp usergroup.cpp usergroup.th icinga-type.cpp
) )

View File

@ -33,19 +33,19 @@
using namespace icinga; using namespace icinga;
boost::signals2::signal<void (const Service::Ptr&, const CheckResult::Ptr&, const String&)> Service::OnNewCheckResult; boost::signals2::signal<void (const Checkable::Ptr&, const CheckResult::Ptr&, const String&)> Checkable::OnNewCheckResult;
boost::signals2::signal<void (const Service::Ptr&, const CheckResult::Ptr&, StateType, const String&)> Service::OnStateChange; boost::signals2::signal<void (const Checkable::Ptr&, const CheckResult::Ptr&, StateType, const String&)> Checkable::OnStateChange;
boost::signals2::signal<void (const Service::Ptr&, NotificationType, const CheckResult::Ptr&, const String&, const String&)> Service::OnNotificationsRequested; boost::signals2::signal<void (const Checkable::Ptr&, NotificationType, const CheckResult::Ptr&, const String&, const String&)> Checkable::OnNotificationsRequested;
boost::signals2::signal<void (const Service::Ptr&, double, const String&)> Service::OnNextCheckChanged; boost::signals2::signal<void (const Checkable::Ptr&, double, const String&)> Checkable::OnNextCheckChanged;
boost::signals2::signal<void (const Service::Ptr&, bool, const String&)> Service::OnForceNextCheckChanged; boost::signals2::signal<void (const Checkable::Ptr&, bool, const String&)> Checkable::OnForceNextCheckChanged;
boost::signals2::signal<void (const Service::Ptr&, bool, const String&)> Service::OnForceNextNotificationChanged; boost::signals2::signal<void (const Checkable::Ptr&, bool, const String&)> Checkable::OnForceNextNotificationChanged;
boost::signals2::signal<void (const Service::Ptr&, bool, const String&)> Service::OnEnableActiveChecksChanged; boost::signals2::signal<void (const Checkable::Ptr&, bool, const String&)> Checkable::OnEnableActiveChecksChanged;
boost::signals2::signal<void (const Service::Ptr&, bool, const String&)> Service::OnEnablePassiveChecksChanged; boost::signals2::signal<void (const Checkable::Ptr&, bool, const String&)> Checkable::OnEnablePassiveChecksChanged;
boost::signals2::signal<void (const Service::Ptr&, bool, const String&)> Service::OnEnableNotificationsChanged; boost::signals2::signal<void (const Checkable::Ptr&, bool, const String&)> Checkable::OnEnableNotificationsChanged;
boost::signals2::signal<void (const Service::Ptr&, bool, const String&)> Service::OnEnableFlappingChanged; boost::signals2::signal<void (const Checkable::Ptr&, bool, const String&)> Checkable::OnEnableFlappingChanged;
boost::signals2::signal<void (const Service::Ptr&, FlappingState)> Service::OnFlappingChanged; boost::signals2::signal<void (const Checkable::Ptr&, FlappingState)> Checkable::OnFlappingChanged;
CheckCommand::Ptr Service::GetCheckCommand(void) const CheckCommand::Ptr Checkable::GetCheckCommand(void) const
{ {
String command; String command;
@ -57,12 +57,12 @@ CheckCommand::Ptr Service::GetCheckCommand(void) const
return CheckCommand::GetByName(command); return CheckCommand::GetByName(command);
} }
void Service::SetCheckCommand(const CheckCommand::Ptr& command) void Checkable::SetCheckCommand(const CheckCommand::Ptr& command)
{ {
SetOverrideCheckCommand(command->GetName()); SetOverrideCheckCommand(command->GetName());
} }
TimePeriod::Ptr Service::GetCheckPeriod(void) const TimePeriod::Ptr Checkable::GetCheckPeriod(void) const
{ {
String tp; String tp;
@ -74,12 +74,12 @@ TimePeriod::Ptr Service::GetCheckPeriod(void) const
return TimePeriod::GetByName(tp); return TimePeriod::GetByName(tp);
} }
void Service::SetCheckPeriod(const TimePeriod::Ptr& tp) void Checkable::SetCheckPeriod(const TimePeriod::Ptr& tp)
{ {
SetOverrideCheckPeriod(tp->GetName()); SetOverrideCheckPeriod(tp->GetName());
} }
double Service::GetCheckInterval(void) const double Checkable::GetCheckInterval(void) const
{ {
if (!GetOverrideCheckInterval().IsEmpty()) if (!GetOverrideCheckInterval().IsEmpty())
return GetOverrideCheckInterval(); return GetOverrideCheckInterval();
@ -87,12 +87,12 @@ double Service::GetCheckInterval(void) const
return GetCheckIntervalRaw(); return GetCheckIntervalRaw();
} }
void Service::SetCheckInterval(double interval) void Checkable::SetCheckInterval(double interval)
{ {
SetOverrideCheckInterval(interval); SetOverrideCheckInterval(interval);
} }
double Service::GetRetryInterval(void) const double Checkable::GetRetryInterval(void) const
{ {
if (!GetOverrideRetryInterval().IsEmpty()) if (!GetOverrideRetryInterval().IsEmpty())
return GetOverrideRetryInterval(); return GetOverrideRetryInterval();
@ -100,34 +100,34 @@ double Service::GetRetryInterval(void) const
return GetRetryIntervalRaw(); return GetRetryIntervalRaw();
} }
void Service::SetRetryInterval(double interval) void Checkable::SetRetryInterval(double interval)
{ {
SetOverrideRetryInterval(interval); SetOverrideRetryInterval(interval);
} }
void Service::SetSchedulingOffset(long offset) void Checkable::SetSchedulingOffset(long offset)
{ {
m_SchedulingOffset = offset; m_SchedulingOffset = offset;
} }
long Service::GetSchedulingOffset(void) long Checkable::GetSchedulingOffset(void)
{ {
return m_SchedulingOffset; return m_SchedulingOffset;
} }
void Service::SetNextCheck(double nextCheck, const String& authority) void Checkable::SetNextCheck(double nextCheck, const String& authority)
{ {
SetNextCheckRaw(nextCheck); SetNextCheckRaw(nextCheck);
OnNextCheckChanged(GetSelf(), nextCheck, authority); OnNextCheckChanged(GetSelf(), nextCheck, authority);
} }
double Service::GetNextCheck(void) double Checkable::GetNextCheck(void)
{ {
return GetNextCheckRaw(); return GetNextCheckRaw();
} }
void Service::UpdateNextCheck(void) void Checkable::UpdateNextCheck(void)
{ {
ObjectLock olock(this); ObjectLock olock(this);
@ -147,12 +147,12 @@ void Service::UpdateNextCheck(void)
SetNextCheck(now - adj + interval); SetNextCheck(now - adj + interval);
} }
bool Service::HasBeenChecked(void) const bool Checkable::HasBeenChecked(void) const
{ {
return GetLastCheckResult() != NULL; return GetLastCheckResult() != NULL;
} }
double Service::GetLastCheck(void) const double Checkable::GetLastCheck(void) const
{ {
CheckResult::Ptr cr = GetLastCheckResult(); CheckResult::Ptr cr = GetLastCheckResult();
double schedule_end = -1; double schedule_end = -1;
@ -163,7 +163,7 @@ double Service::GetLastCheck(void) const
return schedule_end; return schedule_end;
} }
bool Service::GetEnableActiveChecks(void) const bool Checkable::GetEnableActiveChecks(void) const
{ {
if (!GetOverrideEnableActiveChecks().IsEmpty()) if (!GetOverrideEnableActiveChecks().IsEmpty())
return GetOverrideEnableActiveChecks(); return GetOverrideEnableActiveChecks();
@ -171,14 +171,14 @@ bool Service::GetEnableActiveChecks(void) const
return GetEnableActiveChecksRaw(); return GetEnableActiveChecksRaw();
} }
void Service::SetEnableActiveChecks(bool enabled, const String& authority) void Checkable::SetEnableActiveChecks(bool enabled, const String& authority)
{ {
SetOverrideEnableActiveChecks(enabled); SetOverrideEnableActiveChecks(enabled);
OnEnableActiveChecksChanged(GetSelf(), enabled, authority); OnEnableActiveChecksChanged(GetSelf(), enabled, authority);
} }
bool Service::GetEnablePassiveChecks(void) const bool Checkable::GetEnablePassiveChecks(void) const
{ {
if (!GetOverrideEnablePassiveChecks().IsEmpty()) if (!GetOverrideEnablePassiveChecks().IsEmpty())
return GetOverrideEnablePassiveChecks(); return GetOverrideEnablePassiveChecks();
@ -186,26 +186,26 @@ bool Service::GetEnablePassiveChecks(void) const
return GetEnablePassiveChecksRaw(); return GetEnablePassiveChecksRaw();
} }
void Service::SetEnablePassiveChecks(bool enabled, const String& authority) void Checkable::SetEnablePassiveChecks(bool enabled, const String& authority)
{ {
SetOverrideEnablePassiveChecks(enabled); SetOverrideEnablePassiveChecks(enabled);
OnEnablePassiveChecksChanged(GetSelf(), enabled, authority); OnEnablePassiveChecksChanged(GetSelf(), enabled, authority);
} }
bool Service::GetForceNextCheck(void) const bool Checkable::GetForceNextCheck(void) const
{ {
return GetForceNextCheckRaw(); return GetForceNextCheckRaw();
} }
void Service::SetForceNextCheck(bool forced, const String& authority) void Checkable::SetForceNextCheck(bool forced, const String& authority)
{ {
SetForceNextCheckRaw(forced); SetForceNextCheckRaw(forced);
OnForceNextCheckChanged(GetSelf(), forced, authority); OnForceNextCheckChanged(GetSelf(), forced, authority);
} }
int Service::GetMaxCheckAttempts(void) const int Checkable::GetMaxCheckAttempts(void) const
{ {
if (!GetOverrideMaxCheckAttempts().IsEmpty()) if (!GetOverrideMaxCheckAttempts().IsEmpty())
return GetOverrideMaxCheckAttempts(); return GetOverrideMaxCheckAttempts();
@ -213,12 +213,12 @@ int Service::GetMaxCheckAttempts(void) const
return GetMaxCheckAttemptsRaw(); return GetMaxCheckAttemptsRaw();
} }
void Service::SetMaxCheckAttempts(int attempts) void Checkable::SetMaxCheckAttempts(int attempts)
{ {
SetOverrideMaxCheckAttempts(attempts); SetOverrideMaxCheckAttempts(attempts);
} }
void Service::ProcessCheckResult(const CheckResult::Ptr& cr, const String& authority) void Checkable::ProcessCheckResult(const CheckResult::Ptr& cr, const String& authority)
{ {
{ {
ObjectLock olock(this); ObjectLock olock(this);
@ -245,13 +245,11 @@ void Service::ProcessCheckResult(const CheckResult::Ptr& cr, const String& autho
bool reachable = IsReachable(); bool reachable = IsReachable();
bool notification_reachable = IsReachable(DependencyNotification); bool notification_reachable = IsReachable(DependencyNotification);
bool host_reachable = GetHost()->IsReachable();
ASSERT(!OwnsLock()); ASSERT(!OwnsLock());
ObjectLock olock(this); ObjectLock olock(this);
CheckResult::Ptr old_cr = GetLastCheckResult(); CheckResult::Ptr old_cr = GetLastCheckResult();
ServiceState old_state = GetState(); ServiceState old_state = GetStateRaw();
StateType old_stateType = GetStateType(); StateType old_stateType = GetStateType();
long old_attempt = GetCheckAttempt(); long old_attempt = GetCheckAttempt();
bool recovery; bool recovery;
@ -261,7 +259,7 @@ void Service::ProcessCheckResult(const CheckResult::Ptr& cr, const String& autho
/* The ExecuteCheck function already sets the old state, but we need to do it again /* The ExecuteCheck function already sets the old state, but we need to do it again
* in case this was a passive check result. */ * in case this was a passive check result. */
SetLastState(old_state); SetLastStateRaw(old_state);
SetLastStateType(old_stateType); SetLastStateType(old_stateType);
SetLastReachable(reachable); SetLastReachable(reachable);
@ -279,7 +277,7 @@ void Service::ProcessCheckResult(const CheckResult::Ptr& cr, const String& autho
} else { } else {
if (old_attempt >= GetMaxCheckAttempts()) { if (old_attempt >= GetMaxCheckAttempts()) {
SetStateType(StateTypeHard); SetStateType(StateTypeHard);
} else if (GetStateType() == StateTypeSoft || GetState() == StateOK) { } else if (old_stateType == StateTypeSoft || old_state == StateOK) {
SetStateType(StateTypeSoft); SetStateType(StateTypeSoft);
attempt = old_attempt + 1; attempt = old_attempt + 1;
} else { } else {
@ -309,33 +307,27 @@ void Service::ProcessCheckResult(const CheckResult::Ptr& cr, const String& autho
SetCheckAttempt(attempt); SetCheckAttempt(attempt);
SetState(cr->GetState()); ServiceState new_state = cr->GetState();
SetStateRaw(new_state);
bool stateChange = (old_state != GetState()); bool stateChange = (old_state != new_state);
if (stateChange) { if (stateChange) {
SetLastStateChange(now); SetLastStateChange(now);
/* remove acknowledgements */ /* remove acknowledgements */
if (GetAcknowledgement() == AcknowledgementNormal || if (GetAcknowledgement() == AcknowledgementNormal ||
(GetAcknowledgement() == AcknowledgementSticky && GetState() == StateOK)) { (GetAcknowledgement() == AcknowledgementSticky && new_state == StateOK)) {
ClearAcknowledgement(); ClearAcknowledgement();
} }
/* reschedule service dependencies */ /* reschedule direct parents */
BOOST_FOREACH(const Service::Ptr& parent, GetParentServices()) { BOOST_FOREACH(const Checkable::Ptr& parent, GetParents()) {
if (parent.get() == this)
continue;
ObjectLock olock(parent); ObjectLock olock(parent);
parent->SetNextCheck(Utility::GetTime()); parent->SetNextCheck(Utility::GetTime());
} }
/* reschedule host dependencies */
BOOST_FOREACH(const Host::Ptr& parent, GetParentHosts()) {
Service::Ptr service = parent->GetCheckService();
if (service && service->GetName() != GetName()) {
ObjectLock olock(service);
service->SetNextCheck(Utility::GetTime());
}
}
} }
bool remove_acknowledgement_comments = false; bool remove_acknowledgement_comments = false;
@ -345,21 +337,21 @@ void Service::ProcessCheckResult(const CheckResult::Ptr& cr, const String& autho
bool hardChange = (GetStateType() == StateTypeHard && old_stateType == StateTypeSoft); bool hardChange = (GetStateType() == StateTypeHard && old_stateType == StateTypeSoft);
if (old_state != GetState() && old_stateType == StateTypeHard && GetStateType() == StateTypeHard) if (stateChange && old_stateType == StateTypeHard && GetStateType() == StateTypeHard)
hardChange = true; hardChange = true;
if (GetVolatile()) if (GetVolatile())
hardChange = true; hardChange = true;
if (hardChange) { if (hardChange) {
SetLastHardState(GetState()); SetLastHardStateRaw(new_state);
SetLastHardStateChange(now); SetLastHardStateChange(now);
} }
if (GetState() != StateOK) if (new_state != StateOK)
TriggerDowntimes(); TriggerDowntimes();
Service::UpdateStatistics(cr); Checkable::UpdateStatistics(cr);
bool in_downtime = IsInDowntime(); bool in_downtime = IsInDowntime();
bool send_notification = hardChange && notification_reachable && !in_downtime && !IsAcknowledged(); bool send_notification = hardChange && notification_reachable && !in_downtime && !IsAcknowledged();
@ -379,11 +371,10 @@ void Service::ProcessCheckResult(const CheckResult::Ptr& cr, const String& autho
RemoveCommentsByType(CommentAcknowledgement); RemoveCommentsByType(CommentAcknowledgement);
Dictionary::Ptr vars_after = make_shared<Dictionary>(); Dictionary::Ptr vars_after = make_shared<Dictionary>();
vars_after->Set("state", GetState()); vars_after->Set("state", new_state);
vars_after->Set("state_type", GetStateType()); vars_after->Set("state_type", GetStateType());
vars_after->Set("attempt", GetCheckAttempt()); vars_after->Set("attempt", GetCheckAttempt());
vars_after->Set("reachable", reachable); vars_after->Set("reachable", reachable);
vars_after->Set("host_reachable", host_reachable);
if (old_cr) if (old_cr)
cr->SetVarsBefore(old_cr->GetVarsAfter()); cr->SetVarsBefore(old_cr->GetVarsAfter());
@ -402,7 +393,7 @@ void Service::ProcessCheckResult(const CheckResult::Ptr& cr, const String& autho
olock.Unlock(); olock.Unlock();
// Log(LogDebug, "icinga", "Flapping: Service " + GetName() + // Log(LogDebug, "icinga", "Flapping: Checkable " + GetName() +
// " was: " + Convert::ToString(was_flapping) + // " was: " + Convert::ToString(was_flapping) +
// " is: " + Convert::ToString(is_flapping) + // " is: " + Convert::ToString(is_flapping) +
// " threshold: " + Convert::ToString(GetFlappingThreshold()) + // " threshold: " + Convert::ToString(GetFlappingThreshold()) +
@ -427,63 +418,20 @@ void Service::ProcessCheckResult(const CheckResult::Ptr& cr, const String& autho
if (!was_flapping && is_flapping) { if (!was_flapping && is_flapping) {
OnNotificationsRequested(GetSelf(), NotificationFlappingStart, cr, "", ""); OnNotificationsRequested(GetSelf(), NotificationFlappingStart, cr, "", "");
Log(LogDebug, "icinga", "Flapping: Service " + GetName() + " started flapping (" + Convert::ToString(GetFlappingThreshold()) + "% < " + Convert::ToString(GetFlappingCurrent()) + "%)."); Log(LogDebug, "icinga", "Flapping: Checkable " + GetName() + " started flapping (" + Convert::ToString(GetFlappingThreshold()) + "% < " + Convert::ToString(GetFlappingCurrent()) + "%).");
OnFlappingChanged(GetSelf(), FlappingStarted); OnFlappingChanged(GetSelf(), FlappingStarted);
} else if (was_flapping && !is_flapping) { } else if (was_flapping && !is_flapping) {
OnNotificationsRequested(GetSelf(), NotificationFlappingEnd, cr, "", ""); OnNotificationsRequested(GetSelf(), NotificationFlappingEnd, cr, "", "");
Log(LogDebug, "icinga", "Flapping: Service " + GetName() + " stopped flapping (" + Convert::ToString(GetFlappingThreshold()) + "% >= " + Convert::ToString(GetFlappingCurrent()) + "%)."); Log(LogDebug, "icinga", "Flapping: Checkable " + GetName() + " stopped flapping (" + Convert::ToString(GetFlappingThreshold()) + "% >= " + Convert::ToString(GetFlappingCurrent()) + "%).");
OnFlappingChanged(GetSelf(), FlappingStopped); OnFlappingChanged(GetSelf(), FlappingStopped);
} else if (send_notification) } else if (send_notification)
OnNotificationsRequested(GetSelf(), recovery ? NotificationRecovery : NotificationProblem, cr, "", ""); OnNotificationsRequested(GetSelf(), recovery ? NotificationRecovery : NotificationProblem, cr, "", "");
} }
ServiceState Service::StateFromString(const String& state) void Checkable::ExecuteCheck(void)
{ {
if (state == "OK") CONTEXT("Executing check for object '" + GetName() + "'");
return StateOK;
else if (state == "WARNING")
return StateWarning;
else if (state == "CRITICAL")
return StateCritical;
else
return StateUnknown;
}
String Service::StateToString(ServiceState state)
{
switch (state) {
case StateOK:
return "OK";
case StateWarning:
return "WARNING";
case StateCritical:
return "CRITICAL";
case StateUnknown:
default:
return "UNKNOWN";
}
}
StateType Service::StateTypeFromString(const String& type)
{
if (type == "SOFT")
return StateTypeSoft;
else
return StateTypeHard;
}
String Service::StateTypeToString(StateType type)
{
if (type == StateTypeSoft)
return "SOFT";
else
return "HARD";
}
void Service::ExecuteCheck(void)
{
CONTEXT("Executing service check for service '" + GetShortName() + "' on host '" + GetHost()->GetName() + "'");
ASSERT(!OwnsLock()); ASSERT(!OwnsLock());
@ -500,7 +448,7 @@ void Service::ExecuteCheck(void)
m_CheckRunning = true; m_CheckRunning = true;
SetLastState(GetState()); SetLastStateRaw(GetStateRaw());
SetLastStateType(GetLastStateType()); SetLastStateType(GetLastStateType());
SetLastReachable(reachable); SetLastReachable(reachable);
} }
@ -509,7 +457,7 @@ void Service::ExecuteCheck(void)
double scheduled_start = GetNextCheck(); double scheduled_start = GetNextCheck();
double before_check = Utility::GetTime(); double before_check = Utility::GetTime();
Service::Ptr self = GetSelf(); Checkable::Ptr self = GetSelf();
CheckResult::Ptr result = make_shared<CheckResult>(); CheckResult::Ptr result = make_shared<CheckResult>();
@ -519,7 +467,7 @@ void Service::ExecuteCheck(void)
GetCheckCommand()->Execute(GetSelf(), result); GetCheckCommand()->Execute(GetSelf(), result);
} }
void Service::UpdateStatistics(const CheckResult::Ptr& cr) void Checkable::UpdateStatistics(const CheckResult::Ptr& cr)
{ {
time_t ts = cr->GetScheduleEnd(); time_t ts = cr->GetScheduleEnd();
@ -529,7 +477,7 @@ void Service::UpdateStatistics(const CheckResult::Ptr& cr)
CIB::UpdatePassiveChecksStatistics(ts, 1); CIB::UpdatePassiveChecksStatistics(ts, 1);
} }
double Service::CalculateExecutionTime(const CheckResult::Ptr& cr) double Checkable::CalculateExecutionTime(const CheckResult::Ptr& cr)
{ {
if (!cr) if (!cr)
return 0; return 0;
@ -537,7 +485,7 @@ double Service::CalculateExecutionTime(const CheckResult::Ptr& cr)
return cr->GetExecutionEnd() - cr->GetExecutionStart(); return cr->GetExecutionEnd() - cr->GetExecutionStart();
} }
double Service::CalculateLatency(const CheckResult::Ptr& cr) double Checkable::CalculateLatency(const CheckResult::Ptr& cr)
{ {
if (!cr) if (!cr)
return 0; return 0;

View File

@ -30,20 +30,20 @@ using namespace icinga;
static int l_NextCommentID = 1; static int l_NextCommentID = 1;
static boost::mutex l_CommentMutex; static boost::mutex l_CommentMutex;
static std::map<int, String> l_LegacyCommentsCache; static std::map<int, String> l_LegacyCommentsCache;
static std::map<String, Service::WeakPtr> l_CommentsCache; static std::map<String, Checkable::WeakPtr> l_CommentsCache;
static Timer::Ptr l_CommentsExpireTimer; static Timer::Ptr l_CommentsExpireTimer;
boost::signals2::signal<void (const Service::Ptr&, const Comment::Ptr&, const String&)> Service::OnCommentAdded; boost::signals2::signal<void (const Checkable::Ptr&, const Comment::Ptr&, const String&)> Checkable::OnCommentAdded;
boost::signals2::signal<void (const Service::Ptr&, const Comment::Ptr&, const String&)> Service::OnCommentRemoved; boost::signals2::signal<void (const Checkable::Ptr&, const Comment::Ptr&, const String&)> Checkable::OnCommentRemoved;
int Service::GetNextCommentID(void) int Checkable::GetNextCommentID(void)
{ {
boost::mutex::scoped_lock lock(l_CommentMutex); boost::mutex::scoped_lock lock(l_CommentMutex);
return l_NextCommentID; return l_NextCommentID;
} }
String Service::AddComment(CommentType entryType, const String& author, String Checkable::AddComment(CommentType entryType, const String& author,
const String& text, double expireTime, const String& id, const String& authority) const String& text, double expireTime, const String& id, const String& authority)
{ {
String uid; String uid;
@ -83,7 +83,7 @@ String Service::AddComment(CommentType entryType, const String& author,
return uid; return uid;
} }
void Service::RemoveAllComments(void) void Checkable::RemoveAllComments(void)
{ {
std::vector<String> ids; std::vector<String> ids;
Dictionary::Ptr comments = GetComments(); Dictionary::Ptr comments = GetComments();
@ -100,9 +100,9 @@ void Service::RemoveAllComments(void)
} }
} }
void Service::RemoveComment(const String& id, const String& authority) void Checkable::RemoveComment(const String& id, const String& authority)
{ {
Service::Ptr owner = GetOwnerByCommentID(id); Checkable::Ptr owner = GetOwnerByCommentID(id);
if (!owner) if (!owner)
return; return;
@ -129,7 +129,7 @@ void Service::RemoveComment(const String& id, const String& authority)
OnCommentRemoved(owner, comment, authority); OnCommentRemoved(owner, comment, authority);
} }
String Service::GetCommentIDFromLegacyID(int id) String Checkable::GetCommentIDFromLegacyID(int id)
{ {
boost::mutex::scoped_lock lock(l_CommentMutex); boost::mutex::scoped_lock lock(l_CommentMutex);
@ -141,16 +141,16 @@ String Service::GetCommentIDFromLegacyID(int id)
return it->second; return it->second;
} }
Service::Ptr Service::GetOwnerByCommentID(const String& id) Checkable::Ptr Checkable::GetOwnerByCommentID(const String& id)
{ {
boost::mutex::scoped_lock lock(l_CommentMutex); boost::mutex::scoped_lock lock(l_CommentMutex);
return l_CommentsCache[id].lock(); return l_CommentsCache[id].lock();
} }
Comment::Ptr Service::GetCommentByID(const String& id) Comment::Ptr Checkable::GetCommentByID(const String& id)
{ {
Service::Ptr owner = GetOwnerByCommentID(id); Checkable::Ptr owner = GetOwnerByCommentID(id);
if (!owner) if (!owner)
return Comment::Ptr(); return Comment::Ptr();
@ -163,10 +163,10 @@ Comment::Ptr Service::GetCommentByID(const String& id)
return Comment::Ptr(); return Comment::Ptr();
} }
void Service::AddCommentsToCache(void) void Checkable::AddCommentsToCache(void)
{ {
#ifdef _DEBUG #ifdef _DEBUG
Log(LogDebug, "icinga", "Updating Service comments cache."); Log(LogDebug, "icinga", "Updating Checkable comments cache.");
#endif /* _DEBUG */ #endif /* _DEBUG */
Dictionary::Ptr comments = GetComments(); Dictionary::Ptr comments = GetComments();
@ -188,7 +188,7 @@ void Service::AddCommentsToCache(void)
} }
} }
void Service::RemoveCommentsByType(int type) void Checkable::RemoveCommentsByType(int type)
{ {
Dictionary::Ptr comments = GetComments(); Dictionary::Ptr comments = GetComments();
@ -210,7 +210,7 @@ void Service::RemoveCommentsByType(int type)
} }
} }
void Service::RemoveExpiredComments(void) void Checkable::RemoveExpiredComments(void)
{ {
Dictionary::Ptr comments = GetComments(); Dictionary::Ptr comments = GetComments();
@ -232,8 +232,12 @@ void Service::RemoveExpiredComments(void)
} }
} }
void Service::CommentsExpireTimerHandler(void) void Checkable::CommentsExpireTimerHandler(void)
{ {
BOOST_FOREACH(const Host::Ptr& host, DynamicType::GetObjects<Host>()) {
host->RemoveExpiredComments();
}
BOOST_FOREACH(const Service::Ptr& service, DynamicType::GetObjects<Service>()) { BOOST_FOREACH(const Service::Ptr& service, DynamicType::GetObjects<Service>()) {
service->RemoveExpiredComments(); service->RemoveExpiredComments();
} }

View File

@ -30,43 +30,43 @@
using namespace icinga; using namespace icinga;
void Service::AddDependency(const Dependency::Ptr& dep) void Checkable::AddDependency(const Dependency::Ptr& dep)
{ {
boost::mutex::scoped_lock lock(m_DependencyMutex); boost::mutex::scoped_lock lock(m_DependencyMutex);
m_Dependencies.insert(dep); m_Dependencies.insert(dep);
} }
void Service::RemoveDependency(const Dependency::Ptr& dep) void Checkable::RemoveDependency(const Dependency::Ptr& dep)
{ {
boost::mutex::scoped_lock lock(m_DependencyMutex); boost::mutex::scoped_lock lock(m_DependencyMutex);
m_Dependencies.erase(dep); m_Dependencies.erase(dep);
} }
std::set<Dependency::Ptr> Service::GetDependencies(void) const std::set<Dependency::Ptr> Checkable::GetDependencies(void) const
{ {
boost::mutex::scoped_lock lock(m_DependencyMutex); boost::mutex::scoped_lock lock(m_DependencyMutex);
return m_Dependencies; return m_Dependencies;
} }
void Service::AddReverseDependency(const Dependency::Ptr& dep) void Checkable::AddReverseDependency(const Dependency::Ptr& dep)
{ {
boost::mutex::scoped_lock lock(m_DependencyMutex); boost::mutex::scoped_lock lock(m_DependencyMutex);
m_ReverseDependencies.insert(dep); m_ReverseDependencies.insert(dep);
} }
void Service::RemoveReverseDependency(const Dependency::Ptr& dep) void Checkable::RemoveReverseDependency(const Dependency::Ptr& dep)
{ {
boost::mutex::scoped_lock lock(m_DependencyMutex); boost::mutex::scoped_lock lock(m_DependencyMutex);
m_ReverseDependencies.erase(dep); m_ReverseDependencies.erase(dep);
} }
std::set<Dependency::Ptr> Service::GetReverseDependencies(void) const std::set<Dependency::Ptr> Checkable::GetReverseDependencies(void) const
{ {
boost::mutex::scoped_lock lock(m_DependencyMutex); boost::mutex::scoped_lock lock(m_DependencyMutex);
return m_ReverseDependencies; return m_ReverseDependencies;
} }
bool Service::IsReachable(DependencyType dt, Dependency::Ptr *failedDependency, int rstack) const bool Checkable::IsReachable(DependencyType dt, Dependency::Ptr *failedDependency, int rstack) const
{ {
if (rstack > 20) { if (rstack > 20) {
Log(LogWarning, "icinga", "Too many nested dependencies for service '" + GetName() + "': Dependency failed."); Log(LogWarning, "icinga", "Too many nested dependencies for service '" + GetName() + "': Dependency failed.");
@ -74,16 +74,17 @@ bool Service::IsReachable(DependencyType dt, Dependency::Ptr *failedDependency,
return false; return false;
} }
BOOST_FOREACH(const Service::Ptr& service, GetParentServices()) { BOOST_FOREACH(const Checkable::Ptr& service, GetParents()) {
if (!service->IsReachable(dt, failedDependency, rstack + 1)) if (!service->IsReachable(dt, failedDependency, rstack + 1))
return false; return false;
} }
/* implicit dependency on host's check service */ /* implicit dependency on host if this is a service */
if (dt == DependencyState || dt == DependencyNotification) { const Service *service = dynamic_cast<const Service *>(this);
Service::Ptr hc = GetHost()->GetCheckService(); if (service && (dt == DependencyState || dt == DependencyNotification)) {
Host::Ptr host = service->GetHost();
if (hc && hc->GetState() == StateCritical && hc->GetStateType() == StateTypeHard) { if (host && host->GetState() != HostUp && host->GetStateType() == StateTypeHard) {
if (failedDependency) if (failedDependency)
*failedDependency = Dependency::Ptr(); *failedDependency = Dependency::Ptr();
@ -106,46 +107,26 @@ bool Service::IsReachable(DependencyType dt, Dependency::Ptr *failedDependency,
return true; return true;
} }
std::set<Host::Ptr> Service::GetParentHosts(void) const std::set<Checkable::Ptr> Checkable::GetParents(void) const
{ {
std::set<Host::Ptr> result; std::set<Checkable::Ptr> parents;
BOOST_FOREACH(const Service::Ptr& svc, GetParentServices())
result.insert(svc->GetHost());
return result;
}
std::set<Host::Ptr> Service::GetChildHosts(void) const
{
std::set<Host::Ptr> result;
BOOST_FOREACH(const Service::Ptr& svc, GetChildServices())
result.insert(svc->GetHost());
return result;
}
std::set<Service::Ptr> Service::GetParentServices(void) const
{
std::set<Service::Ptr> parents;
BOOST_FOREACH(const Dependency::Ptr& dep, GetDependencies()) { BOOST_FOREACH(const Dependency::Ptr& dep, GetDependencies()) {
Service::Ptr service = dep->GetParentService(); Checkable::Ptr parent = dep->GetParent();
if (service) if (parent)
parents.insert(service); parents.insert(parent);
} }
return parents; return parents;
} }
std::set<Service::Ptr> Service::GetChildServices(void) const std::set<Checkable::Ptr> Checkable::GetChildren(void) const
{ {
std::set<Service::Ptr> parents; std::set<Checkable::Ptr> parents;
BOOST_FOREACH(const Dependency::Ptr& dep, GetReverseDependencies()) { BOOST_FOREACH(const Dependency::Ptr& dep, GetReverseDependencies()) {
Service::Ptr service = dep->GetChildService(); Checkable::Ptr service = dep->GetChild();
if (service) if (service)
parents.insert(service); parents.insert(service);
@ -153,4 +134,3 @@ std::set<Service::Ptr> Service::GetChildServices(void) const
return parents; return parents;
} }

View File

@ -32,21 +32,21 @@ using namespace icinga;
static int l_NextDowntimeID = 1; static int l_NextDowntimeID = 1;
static boost::mutex l_DowntimeMutex; static boost::mutex l_DowntimeMutex;
static std::map<int, String> l_LegacyDowntimesCache; static std::map<int, String> l_LegacyDowntimesCache;
static std::map<String, Service::WeakPtr> l_DowntimesCache; static std::map<String, Checkable::WeakPtr> l_DowntimesCache;
static Timer::Ptr l_DowntimesExpireTimer; static Timer::Ptr l_DowntimesExpireTimer;
boost::signals2::signal<void (const Service::Ptr&, const Downtime::Ptr&, const String&)> Service::OnDowntimeAdded; boost::signals2::signal<void (const Checkable::Ptr&, const Downtime::Ptr&, const String&)> Checkable::OnDowntimeAdded;
boost::signals2::signal<void (const Service::Ptr&, const Downtime::Ptr&, const String&)> Service::OnDowntimeRemoved; boost::signals2::signal<void (const Checkable::Ptr&, const Downtime::Ptr&, const String&)> Checkable::OnDowntimeRemoved;
boost::signals2::signal<void (const Service::Ptr&, const Downtime::Ptr&)> Service::OnDowntimeTriggered; boost::signals2::signal<void (const Checkable::Ptr&, const Downtime::Ptr&)> Checkable::OnDowntimeTriggered;
int Service::GetNextDowntimeID(void) int Checkable::GetNextDowntimeID(void)
{ {
boost::mutex::scoped_lock lock(l_DowntimeMutex); boost::mutex::scoped_lock lock(l_DowntimeMutex);
return l_NextDowntimeID; return l_NextDowntimeID;
} }
String Service::AddDowntime(const String& author, const String& comment, String Checkable::AddDowntime(const String& author, const String& comment,
double startTime, double endTime, bool fixed, double startTime, double endTime, bool fixed,
const String& triggeredBy, double duration, const String& scheduledBy, const String& triggeredBy, double duration, const String& scheduledBy,
const String& id, const String& authority) const String& id, const String& authority)
@ -87,7 +87,7 @@ String Service::AddDowntime(const String& author, const String& comment,
downtime->SetLegacyId(legacy_id); downtime->SetLegacyId(legacy_id);
if (!triggeredBy.IsEmpty()) { if (!triggeredBy.IsEmpty()) {
Service::Ptr otherOwner = GetOwnerByDowntimeID(triggeredBy); Checkable::Ptr otherOwner = GetOwnerByDowntimeID(triggeredBy);
Dictionary::Ptr otherDowntimes = otherOwner->GetDowntimes(); Dictionary::Ptr otherDowntimes = otherOwner->GetDowntimes();
Downtime::Ptr otherDowntime = otherDowntimes->Get(triggeredBy); Downtime::Ptr otherDowntime = otherDowntimes->Get(triggeredBy);
Dictionary::Ptr triggers = otherDowntime->GetTriggers(); Dictionary::Ptr triggers = otherDowntime->GetTriggers();
@ -111,9 +111,9 @@ String Service::AddDowntime(const String& author, const String& comment,
return uid; return uid;
} }
void Service::RemoveDowntime(const String& id, bool cancelled, const String& authority) void Checkable::RemoveDowntime(const String& id, bool cancelled, const String& authority)
{ {
Service::Ptr owner = GetOwnerByDowntimeID(id); Checkable::Ptr owner = GetOwnerByDowntimeID(id);
if (!owner) if (!owner)
return; return;
@ -142,7 +142,7 @@ void Service::RemoveDowntime(const String& id, bool cancelled, const String& aut
OnDowntimeRemoved(owner, downtime, authority); OnDowntimeRemoved(owner, downtime, authority);
} }
void Service::TriggerDowntimes(void) void Checkable::TriggerDowntimes(void)
{ {
Dictionary::Ptr downtimes = GetDowntimes(); Dictionary::Ptr downtimes = GetDowntimes();
@ -161,9 +161,9 @@ void Service::TriggerDowntimes(void)
} }
} }
void Service::TriggerDowntime(const String& id) void Checkable::TriggerDowntime(const String& id)
{ {
Service::Ptr owner = GetOwnerByDowntimeID(id); Checkable::Ptr owner = GetOwnerByDowntimeID(id);
Downtime::Ptr downtime = GetDowntimeByID(id); Downtime::Ptr downtime = GetDowntimeByID(id);
if (!downtime) if (!downtime)
@ -193,7 +193,7 @@ void Service::TriggerDowntime(const String& id)
OnDowntimeTriggered(owner, downtime); OnDowntimeTriggered(owner, downtime);
} }
String Service::GetDowntimeIDFromLegacyID(int id) String Checkable::GetDowntimeIDFromLegacyID(int id)
{ {
boost::mutex::scoped_lock lock(l_DowntimeMutex); boost::mutex::scoped_lock lock(l_DowntimeMutex);
@ -205,15 +205,15 @@ String Service::GetDowntimeIDFromLegacyID(int id)
return it->second; return it->second;
} }
Service::Ptr Service::GetOwnerByDowntimeID(const String& id) Checkable::Ptr Checkable::GetOwnerByDowntimeID(const String& id)
{ {
boost::mutex::scoped_lock lock(l_DowntimeMutex); boost::mutex::scoped_lock lock(l_DowntimeMutex);
return l_DowntimesCache[id].lock(); return l_DowntimesCache[id].lock();
} }
Downtime::Ptr Service::GetDowntimeByID(const String& id) Downtime::Ptr Checkable::GetDowntimeByID(const String& id)
{ {
Service::Ptr owner = GetOwnerByDowntimeID(id); Checkable::Ptr owner = GetOwnerByDowntimeID(id);
if (!owner) if (!owner)
return Downtime::Ptr(); return Downtime::Ptr();
@ -226,18 +226,18 @@ Downtime::Ptr Service::GetDowntimeByID(const String& id)
return Downtime::Ptr(); return Downtime::Ptr();
} }
void Service::StartDowntimesExpiredTimer(void) void Checkable::StartDowntimesExpiredTimer(void)
{ {
l_DowntimesExpireTimer = make_shared<Timer>(); l_DowntimesExpireTimer = make_shared<Timer>();
l_DowntimesExpireTimer->SetInterval(60); l_DowntimesExpireTimer->SetInterval(60);
l_DowntimesExpireTimer->OnTimerExpired.connect(boost::bind(&Service::DowntimesExpireTimerHandler)); l_DowntimesExpireTimer->OnTimerExpired.connect(boost::bind(&Checkable::DowntimesExpireTimerHandler));
l_DowntimesExpireTimer->Start(); l_DowntimesExpireTimer->Start();
} }
void Service::AddDowntimesToCache(void) void Checkable::AddDowntimesToCache(void)
{ {
#ifdef _DEBUG #ifdef _DEBUG
Log(LogDebug, "icinga", "Updating Service downtimes cache."); Log(LogDebug, "icinga", "Updating Checkable downtimes cache.");
#endif /* _DEBUG */ #endif /* _DEBUG */
Dictionary::Ptr downtimes = GetDowntimes(); Dictionary::Ptr downtimes = GetDowntimes();
@ -259,7 +259,7 @@ void Service::AddDowntimesToCache(void)
} }
} }
void Service::RemoveExpiredDowntimes(void) void Checkable::RemoveExpiredDowntimes(void)
{ {
Dictionary::Ptr downtimes = GetDowntimes(); Dictionary::Ptr downtimes = GetDowntimes();
@ -281,14 +281,18 @@ void Service::RemoveExpiredDowntimes(void)
} }
} }
void Service::DowntimesExpireTimerHandler(void) void Checkable::DowntimesExpireTimerHandler(void)
{ {
BOOST_FOREACH(const Host::Ptr& host, DynamicType::GetObjects<Host>()) {
host->RemoveExpiredDowntimes();
}
BOOST_FOREACH(const Service::Ptr& service, DynamicType::GetObjects<Service>()) { BOOST_FOREACH(const Service::Ptr& service, DynamicType::GetObjects<Service>()) {
service->RemoveExpiredDowntimes(); service->RemoveExpiredDowntimes();
} }
} }
bool Service::IsInDowntime(void) const bool Checkable::IsInDowntime(void) const
{ {
Dictionary::Ptr downtimes = GetDowntimes(); Dictionary::Ptr downtimes = GetDowntimes();
@ -304,7 +308,7 @@ bool Service::IsInDowntime(void) const
return false; return false;
} }
int Service::GetDowntimeDepth(void) const int Checkable::GetDowntimeDepth(void) const
{ {
int downtime_depth = 0; int downtime_depth = 0;
Dictionary::Ptr downtimes = GetDowntimes(); Dictionary::Ptr downtimes = GetDowntimes();

View File

@ -24,9 +24,9 @@
using namespace icinga; using namespace icinga;
boost::signals2::signal<void (const Service::Ptr&)> Service::OnEventCommandExecuted; boost::signals2::signal<void (const Checkable::Ptr&)> Checkable::OnEventCommandExecuted;
bool Service::GetEnableEventHandler(void) const bool Checkable::GetEnableEventHandler(void) const
{ {
if (!GetOverrideEnableEventHandler().IsEmpty()) if (!GetOverrideEnableEventHandler().IsEmpty())
return GetOverrideEnableEventHandler(); return GetOverrideEnableEventHandler();
@ -34,12 +34,12 @@ bool Service::GetEnableEventHandler(void) const
return GetEnableEventHandlerRaw(); return GetEnableEventHandlerRaw();
} }
void Service::SetEnableEventHandler(bool enabled) void Checkable::SetEnableEventHandler(bool enabled)
{ {
SetOverrideEnableEventHandler(enabled); SetOverrideEnableEventHandler(enabled);
} }
EventCommand::Ptr Service::GetEventCommand(void) const EventCommand::Ptr Checkable::GetEventCommand(void) const
{ {
String command; String command;
@ -51,14 +51,14 @@ EventCommand::Ptr Service::GetEventCommand(void) const
return EventCommand::GetByName(command); return EventCommand::GetByName(command);
} }
void Service::SetEventCommand(const EventCommand::Ptr& command) void Checkable::SetEventCommand(const EventCommand::Ptr& command)
{ {
SetOverrideEventCommand(command->GetName()); SetOverrideEventCommand(command->GetName());
} }
void Service::ExecuteEventHandler(void) void Checkable::ExecuteEventHandler(void)
{ {
CONTEXT("Executing event handler for service '" + GetShortName() + "' on host '" + GetHost()->GetName() + "'"); CONTEXT("Executing event handler for object '" + GetName() + "'");
if (!IcingaApplication::GetInstance()->GetEnableEventHandlers() || !GetEnableEventHandler()) if (!IcingaApplication::GetInstance()->GetEnableEventHandlers() || !GetEnableEventHandler())
return; return;

View File

@ -31,7 +31,7 @@ using namespace icinga;
#define FLAPPING_INTERVAL (30 * 60) #define FLAPPING_INTERVAL (30 * 60)
double Service::GetFlappingCurrent(void) const double Checkable::GetFlappingCurrent(void) const
{ {
if (GetFlappingPositive() + GetFlappingNegative() <= 0) if (GetFlappingPositive() + GetFlappingNegative() <= 0)
return 0; return 0;
@ -39,7 +39,7 @@ double Service::GetFlappingCurrent(void) const
return 100 * GetFlappingPositive() / (GetFlappingPositive() + GetFlappingNegative()); return 100 * GetFlappingPositive() / (GetFlappingPositive() + GetFlappingNegative());
} }
bool Service::GetEnableFlapping(void) const bool Checkable::GetEnableFlapping(void) const
{ {
if (!GetOverrideEnableFlapping().IsEmpty()) if (!GetOverrideEnableFlapping().IsEmpty())
return GetOverrideEnableFlapping(); return GetOverrideEnableFlapping();
@ -47,7 +47,7 @@ bool Service::GetEnableFlapping(void) const
return GetEnableFlappingRaw(); return GetEnableFlappingRaw();
} }
void Service::SetEnableFlapping(bool enabled, const String& authority) void Checkable::SetEnableFlapping(bool enabled, const String& authority)
{ {
SetOverrideEnableFlapping(enabled); SetOverrideEnableFlapping(enabled);
@ -55,7 +55,7 @@ void Service::SetEnableFlapping(bool enabled, const String& authority)
OnEnableFlappingChanged(GetSelf(), enabled, authority); OnEnableFlappingChanged(GetSelf(), enabled, authority);
} }
void Service::UpdateFlappingStatus(bool stateChange) void Checkable::UpdateFlappingStatus(bool stateChange)
{ {
double ts, now; double ts, now;
long positive, negative; long positive, negative;
@ -92,7 +92,7 @@ void Service::UpdateFlappingStatus(bool stateChange)
SetFlappingNegative(negative); SetFlappingNegative(negative);
} }
bool Service::IsFlapping(void) const bool Checkable::IsFlapping(void) const
{ {
if (!GetEnableFlapping() || !IcingaApplication::GetInstance()->GetEnableFlapping()) if (!GetEnableFlapping() || !IcingaApplication::GetInstance()->GetEnableFlapping())
return false; return false;

View File

@ -32,14 +32,14 @@
using namespace icinga; using namespace icinga;
boost::signals2::signal<void (const Notification::Ptr&, const Service::Ptr&, const std::set<User::Ptr>&, boost::signals2::signal<void (const Notification::Ptr&, const Checkable::Ptr&, const std::set<User::Ptr>&,
const NotificationType&, const CheckResult::Ptr&, const String&, const String&)> Service::OnNotificationSentToAllUsers; const NotificationType&, const CheckResult::Ptr&, const String&, const String&)> Checkable::OnNotificationSentToAllUsers;
boost::signals2::signal<void (const Notification::Ptr&, const Service::Ptr&, const std::set<User::Ptr>&, boost::signals2::signal<void (const Notification::Ptr&, const Checkable::Ptr&, const std::set<User::Ptr>&,
const NotificationType&, const CheckResult::Ptr&, const String&, const String&)> Service::OnNotificationSendStart; const NotificationType&, const CheckResult::Ptr&, const String&, const String&)> Checkable::OnNotificationSendStart;
boost::signals2::signal<void (const Notification::Ptr&, const Service::Ptr&, const User::Ptr&, boost::signals2::signal<void (const Notification::Ptr&, const Checkable::Ptr&, const User::Ptr&,
const NotificationType&, const CheckResult::Ptr&, const String&, const String&, const String&)> Service::OnNotificationSentToUser; const NotificationType&, const CheckResult::Ptr&, const String&, const String&, const String&)> Checkable::OnNotificationSentToUser;
void Service::ResetNotificationNumbers(void) void Checkable::ResetNotificationNumbers(void)
{ {
BOOST_FOREACH(const Notification::Ptr& notification, GetNotifications()) { BOOST_FOREACH(const Notification::Ptr& notification, GetNotifications()) {
ObjectLock olock(notification); ObjectLock olock(notification);
@ -47,9 +47,9 @@ void Service::ResetNotificationNumbers(void)
} }
} }
void Service::SendNotifications(NotificationType type, const CheckResult::Ptr& cr, const String& author, const String& text) void Checkable::SendNotifications(NotificationType type, const CheckResult::Ptr& cr, const String& author, const String& text)
{ {
CONTEXT("Sending notifications for service '" + GetShortName() + "' on host '" + GetHost()->GetName() + "'"); CONTEXT("Sending notifications for object '" + GetName() + "'");
bool force = GetForceNextNotification(); bool force = GetForceNextNotification();
@ -62,14 +62,14 @@ void Service::SendNotifications(NotificationType type, const CheckResult::Ptr& c
SetForceNextNotification(false); SetForceNextNotification(false);
} }
Log(LogInformation, "icinga", "Sending notifications for service '" + GetName() + "'"); Log(LogInformation, "icinga", "Sending notifications for object '" + GetName() + "'");
std::set<Notification::Ptr> notifications = GetNotifications(); std::set<Notification::Ptr> notifications = GetNotifications();
if (notifications.empty()) if (notifications.empty())
Log(LogInformation, "icinga", "Service '" + GetName() + "' does not have any notifications."); Log(LogInformation, "icinga", "Checkable '" + GetName() + "' does not have any notifications.");
Log(LogDebug, "icinga", "Service '" + GetName() + "' has " + Convert::ToString(notifications.size()) + " notification(s)."); Log(LogDebug, "icinga", "Checkable '" + GetName() + "' has " + Convert::ToString(notifications.size()) + " notification(s).");
BOOST_FOREACH(const Notification::Ptr& notification, notifications) { BOOST_FOREACH(const Notification::Ptr& notification, notifications) {
try { try {
@ -85,22 +85,22 @@ void Service::SendNotifications(NotificationType type, const CheckResult::Ptr& c
} }
} }
std::set<Notification::Ptr> Service::GetNotifications(void) const std::set<Notification::Ptr> Checkable::GetNotifications(void) const
{ {
return m_Notifications; return m_Notifications;
} }
void Service::AddNotification(const Notification::Ptr& notification) void Checkable::AddNotification(const Notification::Ptr& notification)
{ {
m_Notifications.insert(notification); m_Notifications.insert(notification);
} }
void Service::RemoveNotification(const Notification::Ptr& notification) void Checkable::RemoveNotification(const Notification::Ptr& notification)
{ {
m_Notifications.erase(notification); m_Notifications.erase(notification);
} }
bool Service::GetEnableNotifications(void) const bool Checkable::GetEnableNotifications(void) const
{ {
if (!GetOverrideEnableNotifications().IsEmpty()) if (!GetOverrideEnableNotifications().IsEmpty())
return GetOverrideEnableNotifications(); return GetOverrideEnableNotifications();
@ -108,19 +108,19 @@ bool Service::GetEnableNotifications(void) const
return GetEnableNotificationsRaw(); return GetEnableNotificationsRaw();
} }
void Service::SetEnableNotifications(bool enabled, const String& authority) void Checkable::SetEnableNotifications(bool enabled, const String& authority)
{ {
SetOverrideEnableNotifications(enabled); SetOverrideEnableNotifications(enabled);
OnEnableNotificationsChanged(GetSelf(), enabled, authority); OnEnableNotificationsChanged(GetSelf(), enabled, authority);
} }
bool Service::GetForceNextNotification(void) const bool Checkable::GetForceNextNotification(void) const
{ {
return GetForceNextNotificationRaw(); return GetForceNextNotificationRaw();
} }
void Service::SetForceNextNotification(bool forced, const String& authority) void Checkable::SetForceNextNotification(bool forced, const String& authority)
{ {
SetForceNextNotificationRaw(forced); SetForceNextNotificationRaw(forced);

233
lib/icinga/checkable.cpp Normal file
View File

@ -0,0 +1,233 @@
/******************************************************************************
* Icinga 2 *
* Copyright (C) 2012-2014 Icinga Development Team (http://www.icinga.org) *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software Foundation *
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
******************************************************************************/
#include "icinga/service.h"
#include "icinga/servicegroup.h"
#include "icinga/checkcommand.h"
#include "icinga/icingaapplication.h"
#include "icinga/macroprocessor.h"
#include "icinga/pluginutility.h"
#include "icinga/dependency.h"
#include "config/configitembuilder.h"
#include "base/dynamictype.h"
#include "base/objectlock.h"
#include "base/convert.h"
#include "base/utility.h"
#include "base/initialize.h"
#include <boost/foreach.hpp>
#include <boost/bind/apply.hpp>
using namespace icinga;
REGISTER_TYPE(Checkable);
INITIALIZE_ONCE(&Checkable::StartDowntimesExpiredTimer);
boost::signals2::signal<void (const Checkable::Ptr&, const String&, const String&, AcknowledgementType, double, const String&)> Checkable::OnAcknowledgementSet;
boost::signals2::signal<void (const Checkable::Ptr&, const String&)> Checkable::OnAcknowledgementCleared;
Checkable::Checkable(void)
: m_CheckRunning(false)
{ }
void Checkable::Start(void)
{
double now = Utility::GetTime();
if (GetNextCheck() < now + 300)
UpdateNextCheck();
DynamicObject::Start();
}
void Checkable::OnConfigLoaded(void)
{
DynamicObject::OnConfigLoaded();
SetSchedulingOffset(Utility::Random());
}
void Checkable::OnStateLoaded(void)
{
AddDowntimesToCache();
AddCommentsToCache();
std::vector<String> ids;
Dictionary::Ptr downtimes = GetDowntimes();
{
ObjectLock dlock(downtimes);
BOOST_FOREACH(const Dictionary::Pair& kv, downtimes) {
Downtime::Ptr downtime = kv.second;
if (downtime->GetScheduledBy().IsEmpty())
continue;
ids.push_back(kv.first);
}
}
BOOST_FOREACH(const String& id, ids) {
RemoveDowntime(id, true);
}
}
AcknowledgementType Checkable::GetAcknowledgement(void)
{
ASSERT(OwnsLock());
AcknowledgementType avalue = static_cast<AcknowledgementType>(GetAcknowledgementRaw());
if (avalue != AcknowledgementNone) {
double expiry = GetAcknowledgementExpiry();
if (expiry != 0 && expiry < Utility::GetTime()) {
avalue = AcknowledgementNone;
ClearAcknowledgement();
}
}
return avalue;
}
bool Checkable::IsAcknowledged(void)
{
return GetAcknowledgement() != AcknowledgementNone;
}
void Checkable::AcknowledgeProblem(const String& author, const String& comment, AcknowledgementType type, double expiry, const String& authority)
{
{
ObjectLock olock(this);
SetAcknowledgementRaw(type);
SetAcknowledgementExpiry(expiry);
}
OnNotificationsRequested(GetSelf(), NotificationAcknowledgement, GetLastCheckResult(), author, comment);
OnAcknowledgementSet(GetSelf(), author, comment, type, expiry, authority);
}
void Checkable::ClearAcknowledgement(const String& authority)
{
ASSERT(OwnsLock());
SetAcknowledgementRaw(AcknowledgementNone);
SetAcknowledgementExpiry(0);
OnAcknowledgementCleared(GetSelf(), authority);
}
bool Checkable::GetEnablePerfdata(void) const
{
if (!GetOverrideEnablePerfdata().IsEmpty())
return GetOverrideEnablePerfdata();
else
return GetEnablePerfdataRaw();
}
void Checkable::SetEnablePerfdata(bool enabled, const String& authority)
{
SetOverrideEnablePerfdata(enabled);
}
int Checkable::GetModifiedAttributes(void) const
{
int attrs = 0;
if (!GetOverrideEnableNotifications().IsEmpty())
attrs |= ModAttrNotificationsEnabled;
if (!GetOverrideEnableActiveChecks().IsEmpty())
attrs |= ModAttrActiveChecksEnabled;
if (!GetOverrideEnablePassiveChecks().IsEmpty())
attrs |= ModAttrPassiveChecksEnabled;
if (!GetOverrideEnableFlapping().IsEmpty())
attrs |= ModAttrFlapDetectionEnabled;
if (!GetOverrideEnableEventHandler().IsEmpty())
attrs |= ModAttrEventHandlerEnabled;
if (!GetOverrideEnablePerfdata().IsEmpty())
attrs |= ModAttrPerformanceDataEnabled;
if (!GetOverrideCheckInterval().IsEmpty())
attrs |= ModAttrNormalCheckInterval;
if (!GetOverrideRetryInterval().IsEmpty())
attrs |= ModAttrRetryCheckInterval;
if (!GetOverrideEventCommand().IsEmpty())
attrs |= ModAttrEventHandlerCommand;
if (!GetOverrideCheckCommand().IsEmpty())
attrs |= ModAttrCheckCommand;
if (!GetOverrideMaxCheckAttempts().IsEmpty())
attrs |= ModAttrMaxCheckAttempts;
if (!GetOverrideCheckPeriod().IsEmpty())
attrs |= ModAttrCheckTimeperiod;
// TODO: finish
return attrs;
}
void Checkable::SetModifiedAttributes(int flags)
{
if ((flags & ModAttrNotificationsEnabled) == 0)
SetOverrideEnableNotifications(Empty);
if ((flags & ModAttrActiveChecksEnabled) == 0)
SetOverrideEnableActiveChecks(Empty);
if ((flags & ModAttrPassiveChecksEnabled) == 0)
SetOverrideEnablePassiveChecks(Empty);
if ((flags & ModAttrFlapDetectionEnabled) == 0)
SetOverrideEnableFlapping(Empty);
if ((flags & ModAttrEventHandlerEnabled) == 0)
SetOverrideEnableEventHandler(Empty);
if ((flags & ModAttrPerformanceDataEnabled) == 0)
SetOverrideEnablePerfdata(Empty);
if ((flags & ModAttrNormalCheckInterval) == 0)
SetOverrideCheckInterval(Empty);
if ((flags & ModAttrRetryCheckInterval) == 0)
SetOverrideRetryInterval(Empty);
if ((flags & ModAttrEventHandlerCommand) == 0)
SetOverrideEventCommand(Empty);
if ((flags & ModAttrCheckCommand) == 0)
SetOverrideCheckCommand(Empty);
if ((flags & ModAttrMaxCheckAttempts) == 0)
SetOverrideMaxCheckAttempts(Empty);
if ((flags & ModAttrCheckTimeperiod) == 0)
SetOverrideCheckPeriod(Empty);
}

310
lib/icinga/checkable.h Normal file
View File

@ -0,0 +1,310 @@
/******************************************************************************
* Icinga 2 *
* Copyright (C) 2012-2014 Icinga Development Team (http://www.icinga.org) *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software Foundation *
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
******************************************************************************/
#ifndef CHECKABLE_H
#define CHECKABLE_H
#include "icinga/i2-icinga.h"
#include "icinga/checkable.th"
#include "icinga/macroresolver.h"
#include "icinga/timeperiod.h"
#include "icinga/notification.h"
#include "icinga/comment.h"
#include "icinga/downtime.h"
#include "base/i2-base.h"
#include "base/array.h"
#include <boost/signals2.hpp>
#include <boost/thread/once.hpp>
namespace icinga
{
/**
* The state of service flapping.
*
* @ingroup icinga
*/
enum FlappingState
{
FlappingStarted = 0,
FlappingDisabled = 1,
FlappingStopped = 2,
FlappingEnabled = 3
};
/**
* Modified attributes.
*
* @ingroup icinga
*/
enum ModifiedAttributeType
{
ModAttrNotificationsEnabled = 1,
ModAttrActiveChecksEnabled = 2,
ModAttrPassiveChecksEnabled = 4,
ModAttrEventHandlerEnabled = 8,
ModAttrFlapDetectionEnabled = 16,
ModAttrFailurePredictionEnabled = 32,
ModAttrPerformanceDataEnabled = 64,
ModAttrObsessiveHandlerEnabled = 128,
ModAttrEventHandlerCommand = 256,
ModAttrCheckCommand = 512,
ModAttrNormalCheckInterval = 1024,
ModAttrRetryCheckInterval = 2048,
ModAttrMaxCheckAttempts = 4096,
ModAttrFreshnessChecksEnabled = 8192,
ModAttrCheckTimeperiod = 16384,
ModAttrCustomVariable = 32768,
ModAttrNotificationTimeperiod = 65536
};
/**
* @ingroup icinga
*/
enum DependencyType
{
DependencyState,
DependencyCheckExecution,
DependencyNotification
};
class CheckCommand;
class EventCommand;
class Dependency;
/**
* An Icinga service.
*
* @ingroup icinga
*/
class I2_ICINGA_API Checkable : public ObjectImpl<Checkable>
{
public:
DECLARE_PTR_TYPEDEFS(Checkable);
DECLARE_TYPENAME(Checkable);
Checkable(void);
std::set<Checkable::Ptr> GetParents(void) const;
std::set<Checkable::Ptr> GetChildren(void) const;
//bool IsHostCheck(void) const;
bool IsReachable(DependencyType dt = DependencyState, shared_ptr<Dependency> *failedDependency = NULL, int rstack = 0) const;
AcknowledgementType GetAcknowledgement(void);
void AcknowledgeProblem(const String& author, const String& comment, AcknowledgementType type, double expiry = 0, const String& authority = String());
void ClearAcknowledgement(const String& authority = String());
/* Checks */
shared_ptr<CheckCommand> GetCheckCommand(void) const;
void SetCheckCommand(const shared_ptr<CheckCommand>& command);
TimePeriod::Ptr GetCheckPeriod(void) const;
void SetCheckPeriod(const TimePeriod::Ptr& tp);
double GetCheckInterval(void) const;
void SetCheckInterval(double interval);
double GetRetryInterval(void) const;
void SetRetryInterval(double interval);
int GetMaxCheckAttempts(void) const;
void SetMaxCheckAttempts(int attempts);
long GetSchedulingOffset(void);
void SetSchedulingOffset(long offset);
void SetNextCheck(double nextCheck, const String& authority = String());
double GetNextCheck(void);
void UpdateNextCheck(void);
bool HasBeenChecked(void) const;
double GetLastCheck(void) const;
bool GetEnableActiveChecks(void) const;
void SetEnableActiveChecks(bool enabled, const String& authority = String());
bool GetEnablePassiveChecks(void) const;
void SetEnablePassiveChecks(bool enabled, const String& authority = String());
bool GetForceNextCheck(void) const;
void SetForceNextCheck(bool forced, const String& authority = String());
static void UpdateStatistics(const CheckResult::Ptr& cr);
void ExecuteCheck(void);
void ProcessCheckResult(const CheckResult::Ptr& cr, const String& authority = String());
int GetModifiedAttributes(void) const;
void SetModifiedAttributes(int flags);
static double CalculateExecutionTime(const CheckResult::Ptr& cr);
static double CalculateLatency(const CheckResult::Ptr& cr);
static boost::signals2::signal<void (const Checkable::Ptr&, double, const String&)> OnNextCheckChanged;
static boost::signals2::signal<void (const Checkable::Ptr&, bool, const String&)> OnForceNextCheckChanged;
static boost::signals2::signal<void (const Checkable::Ptr&, bool, const String&)> OnForceNextNotificationChanged;
static boost::signals2::signal<void (const Checkable::Ptr&, bool, const String&)> OnEnableActiveChecksChanged;
static boost::signals2::signal<void (const Checkable::Ptr&, bool, const String&)> OnEnablePassiveChecksChanged;
static boost::signals2::signal<void (const Checkable::Ptr&, bool, const String&)> OnEnableNotificationsChanged;
static boost::signals2::signal<void (const Checkable::Ptr&, bool, const String&)> OnEnableFlappingChanged;
static boost::signals2::signal<void (const Checkable::Ptr&, const CheckResult::Ptr&, const String&)> OnNewCheckResult;
static boost::signals2::signal<void (const Checkable::Ptr&, const CheckResult::Ptr&, StateType, const String&)> OnStateChange;
static boost::signals2::signal<void (const Checkable::Ptr&, NotificationType, const CheckResult::Ptr&,
const String&, const String&)> OnNotificationsRequested;
static boost::signals2::signal<void (const Notification::Ptr&, const Checkable::Ptr&, const std::set<User::Ptr>&,
const NotificationType&, const CheckResult::Ptr&, const String&,
const String&)> OnNotificationSendStart;
static boost::signals2::signal<void (const Notification::Ptr&, const Checkable::Ptr&, const User::Ptr&,
const NotificationType&, const CheckResult::Ptr&, const String&,
const String&, const String&)> OnNotificationSentToUser;
static boost::signals2::signal<void (const Notification::Ptr&, const Checkable::Ptr&, const std::set<User::Ptr>&,
const NotificationType&, const CheckResult::Ptr&, const String&,
const String&)> OnNotificationSentToAllUsers;
static boost::signals2::signal<void (const Checkable::Ptr&, const Comment::Ptr&, const String&)> OnCommentAdded;
static boost::signals2::signal<void (const Checkable::Ptr&, const Comment::Ptr&, const String&)> OnCommentRemoved;
static boost::signals2::signal<void (const Checkable::Ptr&, const Downtime::Ptr&, const String&)> OnDowntimeAdded;
static boost::signals2::signal<void (const Checkable::Ptr&, const Downtime::Ptr&, const String&)> OnDowntimeRemoved;
static boost::signals2::signal<void (const Checkable::Ptr&, FlappingState)> OnFlappingChanged;
static boost::signals2::signal<void (const Checkable::Ptr&, const Downtime::Ptr&)> OnDowntimeTriggered;
static boost::signals2::signal<void (const Checkable::Ptr&, const String&, const String&, AcknowledgementType,
double, const String&)> OnAcknowledgementSet;
static boost::signals2::signal<void (const Checkable::Ptr&, const String&)> OnAcknowledgementCleared;
static boost::signals2::signal<void (const Checkable::Ptr&)> OnEventCommandExecuted;
/* Downtimes */
static int GetNextDowntimeID(void);
int GetDowntimeDepth(void) const;
String AddDowntime(const String& author, const String& comment,
double startTime, double endTime, bool fixed,
const String& triggeredBy, double duration,
const String& scheduledBy = String(), const String& id = String(),
const String& authority = String());
static void RemoveDowntime(const String& id, bool cancelled, const String& = String());
void TriggerDowntimes(void);
static void TriggerDowntime(const String& id);
static String GetDowntimeIDFromLegacyID(int id);
static Checkable::Ptr GetOwnerByDowntimeID(const String& id);
static Downtime::Ptr GetDowntimeByID(const String& id);
static void StartDowntimesExpiredTimer(void);
bool IsInDowntime(void) const;
bool IsAcknowledged(void);
/* Comments */
static int GetNextCommentID(void);
String AddComment(CommentType entryType, const String& author,
const String& text, double expireTime, const String& id = String(), const String& authority = String());
void RemoveAllComments(void);
void RemoveCommentsByType(int type);
static void RemoveComment(const String& id, const String& authority = String());
static String GetCommentIDFromLegacyID(int id);
static Checkable::Ptr GetOwnerByCommentID(const String& id);
static Comment::Ptr GetCommentByID(const String& id);
/* Notifications */
bool GetEnableNotifications(void) const;
void SetEnableNotifications(bool enabled, const String& authority = String());
void SendNotifications(NotificationType type, const CheckResult::Ptr& cr, const String& author = "", const String& text = "");
std::set<Notification::Ptr> GetNotifications(void) const;
void AddNotification(const Notification::Ptr& notification);
void RemoveNotification(const Notification::Ptr& notification);
void SetForceNextNotification(bool force, const String& authority = String());
bool GetForceNextNotification(void) const;
void ResetNotificationNumbers(void);
/* Event Handler */
void ExecuteEventHandler(void);
shared_ptr<EventCommand> GetEventCommand(void) const;
void SetEventCommand(const shared_ptr<EventCommand>& command);
bool GetEnableEventHandler(void) const;
void SetEnableEventHandler(bool enabled);
/* Flapping Detection */
double GetFlappingCurrent(void) const;
bool GetEnableFlapping(void) const;
void SetEnableFlapping(bool enabled, const String& authority = String());
bool IsFlapping(void) const;
void UpdateFlappingStatus(bool stateChange);
/* Performance data */
bool GetEnablePerfdata(void) const;
void SetEnablePerfdata(bool enabled, const String& authority = String());
/* Dependencies */
void AddDependency(const shared_ptr<Dependency>& dep);
void RemoveDependency(const shared_ptr<Dependency>& dep);
std::set<shared_ptr<Dependency> > GetDependencies(void) const;
void AddReverseDependency(const shared_ptr<Dependency>& dep);
void RemoveReverseDependency(const shared_ptr<Dependency>& dep);
std::set<shared_ptr<Dependency> > GetReverseDependencies(void) const;
protected:
virtual void Start(void);
virtual void OnConfigLoaded(void);
virtual void OnStateLoaded(void);
private:
bool m_CheckRunning;
long m_SchedulingOffset;
/* Downtimes */
static void DowntimesExpireTimerHandler(void);
void RemoveExpiredDowntimes(void);
void AddDowntimesToCache(void);
/* Comments */
static void CommentsExpireTimerHandler(void);
void RemoveExpiredComments(void);
void AddCommentsToCache(void);
/* Notifications */
std::set<Notification::Ptr> m_Notifications;
/* Dependencies */
mutable boost::mutex m_DependencyMutex;
std::set<shared_ptr<Dependency> > m_Dependencies;
std::set<shared_ptr<Dependency> > m_ReverseDependencies;
};
}
#endif /* CHECKABLE_H */

123
lib/icinga/checkable.ti Normal file
View File

@ -0,0 +1,123 @@
#include "icinga/icingaapplication.h"
#include "base/dynamicobject.h"
namespace icinga
{
code {{{
/**
* The acknowledgement type of a service.
*
* @ingroup icinga
*/
enum AcknowledgementType
{
AcknowledgementNone = 0,
AcknowledgementNormal = 1,
AcknowledgementSticky = 2
};
}}}
abstract class Checkable : DynamicObject
{
[config] Array::Ptr groups;
[config, protected] String check_command (CheckCommandRaw);
[config] int max_check_attempts (MaxCheckAttemptsRaw) {
default {{{ return 3; }}}
};
[config, protected] String check_period (CheckPeriodRaw);
[config] double check_interval (CheckIntervalRaw) {
default {{{ return 5 * 60; }}}
};
[config] double retry_interval (RetryIntervalRaw) {
default {{{ return 60; }}}
};
[config] String event_command (EventCommandRaw);
[config] bool volatile;
[config] double flapping_threshold {
default {{{ return 30; }}}
};
[config] bool enable_active_checks (EnableActiveChecksRaw) {
default {{{ return true; }}}
};
[config] bool enable_passive_checks (EnablePassiveChecksRaw) {
default {{{ return true; }}}
};
[config] bool enable_event_handler (EnableEventHandlerRaw) {
default {{{ return true; }}}
};
[config] bool enable_notifications (EnableNotificationsRaw) {
default {{{ return true; }}}
};
[config] bool enable_flapping (EnableFlappingRaw) {
default {{{ return true; }}}
};
[config] bool enable_perfdata (EnablePerfdataRaw) {
default {{{ return true; }}}
};
[state] double next_check (NextCheckRaw);
[state] int check_attempt {
default {{{ return 1; }}}
};
[state, enum] ServiceState state_raw {
default {{{ return StateUnknown; }}}
};
[state, enum] StateType state_type {
default {{{ return StateTypeSoft; }}}
};
[state, enum] ServiceState last_state_raw {
default {{{ return StateUnknown; }}}
};
[state, enum] ServiceState last_hard_state_raw {
default {{{ return StateUnknown; }}}
};
[state, enum] StateType last_state_type {
default {{{ return StateTypeSoft; }}}
};
[state] bool last_reachable {
default {{{ return true; }}}
};
[state] CheckResult::Ptr last_check_result;
[state] double last_state_change {
default {{{ return Application::GetStartTime(); }}}
};
[state] double last_hard_state_change {
default {{{ return Application::GetStartTime(); }}}
};
[state] double last_state_ok (LastStateOK);
[state] double last_state_warning;
[state] double last_state_critical;
[state] double last_state_unknown;
[state] double last_state_unreachable;
[state] bool last_in_downtime;
[state] bool force_next_check (ForceNextCheckRaw);
[state] int acknowledgement (AcknowledgementRaw) {
default {{{ return AcknowledgementNone; }}}
};
[state] double acknowledgement_expiry;
[state] Dictionary::Ptr comments {
default {{{ return make_shared<Dictionary>(); }}}
};
[state] Dictionary::Ptr downtimes {
default {{{ return make_shared<Dictionary>(); }}}
};
[state] bool force_next_notification (ForceNextNotificationRaw);
[state] int flapping_positive;
[state] int flapping_negative;
[state] double flapping_last_change;
[state] Value override_enable_notifications;
[state] Value override_enable_active_checks;
[state] Value override_enable_passive_checks;
[state] Value override_enable_flapping;
[state] Value override_enable_perfdata;
[state] Value override_check_interval;
[state] Value override_retry_interval;
[state] Value override_enable_event_handler;
[state] Value override_event_command;
[state] Value override_check_command;
[state] Value override_max_check_attempts;
[state] Value override_check_period;
};
}

View File

@ -24,10 +24,10 @@ using namespace icinga;
REGISTER_TYPE(CheckCommand); REGISTER_TYPE(CheckCommand);
void CheckCommand::Execute(const Service::Ptr& service, const CheckResult::Ptr& cr) void CheckCommand::Execute(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr)
{ {
std::vector<Value> arguments; std::vector<Value> arguments;
arguments.push_back(service); arguments.push_back(checkable);
arguments.push_back(cr); arguments.push_back(cr);
InvokeMethod("execute", arguments); InvokeMethod("execute", arguments);
} }

View File

@ -37,7 +37,7 @@ public:
DECLARE_PTR_TYPEDEFS(CheckCommand); DECLARE_PTR_TYPEDEFS(CheckCommand);
DECLARE_TYPENAME(CheckCommand); DECLARE_TYPENAME(CheckCommand);
virtual void Execute(const Service::Ptr& service, const CheckResult::Ptr& cr); virtual void Execute(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr);
}; };
} }

View File

@ -24,7 +24,6 @@
#include "base/dynamictype.h" #include "base/dynamictype.h"
#include "base/statsfunction.h" #include "base/statsfunction.h"
#include <boost/foreach.hpp> #include <boost/foreach.hpp>
#include <boost/tuple/tuple.hpp>
using namespace icinga; using namespace icinga;
@ -148,21 +147,14 @@ HostStatistics CIB::CalculateHostStats(void)
if (host->GetState() == HostUnreachable) if (host->GetState() == HostUnreachable)
hs.hosts_unreachable++; hs.hosts_unreachable++;
Service::Ptr hc = host->GetCheckService(); if (!host->GetLastCheckResult())
if (!hc) {
hs.hosts_pending++;
continue; /* skip host service check counting */
}
if (!hc->GetLastCheckResult())
hs.hosts_pending++; hs.hosts_pending++;
if (hc->IsFlapping()) if (host->IsFlapping())
hs.hosts_flapping++; hs.hosts_flapping++;
if (hc->IsInDowntime()) if (host->IsInDowntime())
hs.hosts_in_downtime++; hs.hosts_in_downtime++;
if (hc->IsAcknowledged()) if (host->IsAcknowledged())
hs.hosts_acknowledged++; hs.hosts_acknowledged++;
} }
@ -180,7 +172,7 @@ std::pair<Dictionary::Ptr, Dictionary::Ptr> CIB::GetFeatureStats(void)
String name; String name;
Value ret; Value ret;
BOOST_FOREACH(boost::tie(name, boost::tuples::ignore), StatsFunctionRegistry::GetInstance()->GetItems()) { BOOST_FOREACH(tie(name, boost::tuples::ignore), StatsFunctionRegistry::GetInstance()->GetItems()) {
StatsFunction::Ptr func = StatsFunctionRegistry::GetInstance()->GetItem(name); StatsFunction::Ptr func = StatsFunctionRegistry::GetInstance()->GetItem(name);
if (!func) if (!func)

View File

@ -155,12 +155,7 @@ int CompatUtility::GetHostNotifyOnDown(const Host::Ptr& host)
{ {
ASSERT(host->OwnsLock()); ASSERT(host->OwnsLock());
Service::Ptr service = host->GetCheckService(); unsigned long notification_state_filter = GetCheckableNotificationStateFilter(host);
if (!service)
return 0;
unsigned long notification_state_filter = GetServiceNotificationStateFilter(service);
if (notification_state_filter & (1<<StateCritical) || if (notification_state_filter & (1<<StateCritical) ||
notification_state_filter & (1<<StateWarning)) notification_state_filter & (1<<StateWarning))
@ -173,12 +168,7 @@ int CompatUtility::GetHostNotifyOnUnreachable(const Host::Ptr& host)
{ {
ASSERT(host->OwnsLock()); ASSERT(host->OwnsLock());
Service::Ptr service = host->GetCheckService(); unsigned long notification_state_filter = GetCheckableNotificationStateFilter(host);
if (!service)
return 0;
unsigned long notification_state_filter = GetServiceNotificationStateFilter(service);
if (notification_state_filter & (1<<StateUnknown)) if (notification_state_filter & (1<<StateUnknown))
return 1; return 1;
@ -187,134 +177,122 @@ int CompatUtility::GetHostNotifyOnUnreachable(const Host::Ptr& host)
} }
/* service */ /* service */
int CompatUtility::GetServiceCurrentState(const Service::Ptr& service) int CompatUtility::GetCheckableShouldBeScheduled(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
int state = service->GetState(); return (checkable->GetEnableActiveChecks() ? 1 : 0);
if (state > StateUnknown)
return StateUnknown;
return state;
} }
int CompatUtility::GetServiceShouldBeScheduled(const Service::Ptr& service) int CompatUtility::GetCheckableCheckType(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return (service->GetEnableActiveChecks() ? 1 : 0); return (checkable->GetEnableActiveChecks() ? 0 : 1);
} }
int CompatUtility::GetServiceCheckType(const Service::Ptr& service) double CompatUtility::GetCheckableCheckInterval(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return (service->GetEnableActiveChecks() ? 0 : 1); return checkable->GetCheckInterval() / 60.0;
} }
double CompatUtility::GetServiceCheckInterval(const Service::Ptr& service) double CompatUtility::GetCheckableRetryInterval(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return service->GetCheckInterval() / 60.0; return checkable->GetRetryInterval() / 60.0;
} }
double CompatUtility::GetServiceRetryInterval(const Service::Ptr& service) String CompatUtility::GetCheckableCheckPeriod(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return service->GetRetryInterval() / 60.0; TimePeriod::Ptr check_period = checkable->GetCheckPeriod();
}
String CompatUtility::GetServiceCheckPeriod(const Service::Ptr& service)
{
ASSERT(service->OwnsLock());
TimePeriod::Ptr check_period = service->GetCheckPeriod();
if (check_period) if (check_period)
return check_period->GetName(); return check_period->GetName();
else else
return "24x7"; return "24x7";
} }
int CompatUtility::GetServiceHasBeenChecked(const Service::Ptr& service) int CompatUtility::GetCheckableHasBeenChecked(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return (service->GetLastCheckResult() ? 1 : 0); return (checkable->GetLastCheckResult() ? 1 : 0);
} }
int CompatUtility::GetServiceProblemHasBeenAcknowledged(const Service::Ptr& service) int CompatUtility::GetCheckableProblemHasBeenAcknowledged(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return (service->GetAcknowledgement() != AcknowledgementNone ? 1 : 0); return (checkable->GetAcknowledgement() != AcknowledgementNone ? 1 : 0);
} }
int CompatUtility::GetServiceAcknowledgementType(const Service::Ptr& service) int CompatUtility::GetCheckableAcknowledgementType(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return static_cast<int>(service->GetAcknowledgement()); return static_cast<int>(checkable->GetAcknowledgement());
} }
int CompatUtility::GetServicePassiveChecksEnabled(const Service::Ptr& service) int CompatUtility::GetCheckablePassiveChecksEnabled(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return (service->GetEnablePassiveChecks() ? 1 : 0); return (checkable->GetEnablePassiveChecks() ? 1 : 0);
} }
int CompatUtility::GetServiceActiveChecksEnabled(const Service::Ptr& service) int CompatUtility::GetCheckableActiveChecksEnabled(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return (service->GetEnableActiveChecks() ? 1 : 0); return (checkable->GetEnableActiveChecks() ? 1 : 0);
} }
int CompatUtility::GetServiceEventHandlerEnabled(const Service::Ptr& service) int CompatUtility::GetCheckableEventHandlerEnabled(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return (service->GetEventCommand() ? 1 : 0); return (checkable->GetEventCommand() ? 1 : 0);
} }
int CompatUtility::GetServiceFlapDetectionEnabled(const Service::Ptr& service) int CompatUtility::GetCheckableFlapDetectionEnabled(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return (service->GetEnableFlapping() ? 1 : 0); return (checkable->GetEnableFlapping() ? 1 : 0);
} }
int CompatUtility::GetServiceIsFlapping(const Service::Ptr& service) int CompatUtility::GetCheckableIsFlapping(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return (service->IsFlapping() ? 1 : 0); return (checkable->IsFlapping() ? 1 : 0);
} }
String CompatUtility::GetServicePercentStateChange(const Service::Ptr& service) String CompatUtility::GetCheckablePercentStateChange(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return Convert::ToString(service->GetFlappingCurrent()); return Convert::ToString(checkable->GetFlappingCurrent());
} }
int CompatUtility::GetServiceProcessPerformanceData(const Service::Ptr& service) int CompatUtility::GetCheckableProcessPerformanceData(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return (service->GetEnablePerfdata() ? 1 : 0); return (checkable->GetEnablePerfdata() ? 1 : 0);
} }
String CompatUtility::GetServiceEventHandler(const Service::Ptr& service) String CompatUtility::GetCheckableEventHandler(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
String event_command_str; String event_command_str;
EventCommand::Ptr eventcommand = service->GetEventCommand(); EventCommand::Ptr eventcommand = checkable->GetEventCommand();
if (eventcommand) if (eventcommand)
event_command_str = eventcommand->GetName(); event_command_str = eventcommand->GetName();
@ -322,12 +300,12 @@ String CompatUtility::GetServiceEventHandler(const Service::Ptr& service)
return event_command_str; return event_command_str;
} }
String CompatUtility::GetServiceCheckCommand(const Service::Ptr& service) String CompatUtility::GetCheckableCheckCommand(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
String check_command_str; String check_command_str;
CheckCommand::Ptr checkcommand = service->GetCheckCommand(); CheckCommand::Ptr checkcommand = checkable->GetCheckCommand();
if (checkcommand) if (checkcommand)
check_command_str = checkcommand->GetName(); check_command_str = checkcommand->GetName();
@ -335,73 +313,73 @@ String CompatUtility::GetServiceCheckCommand(const Service::Ptr& service)
return check_command_str; return check_command_str;
} }
int CompatUtility::GetServiceIsVolatile(const Service::Ptr& service) int CompatUtility::GetCheckableIsVolatile(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return (service->GetVolatile() ? 1 : 0); return (checkable->GetVolatile() ? 1 : 0);
} }
double CompatUtility::GetServiceLowFlapThreshold(const Service::Ptr& service) double CompatUtility::GetCheckableLowFlapThreshold(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return service->GetFlappingThreshold(); return checkable->GetFlappingThreshold();
} }
double CompatUtility::GetServiceHighFlapThreshold(const Service::Ptr& service) double CompatUtility::GetCheckableHighFlapThreshold(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return service->GetFlappingThreshold(); return checkable->GetFlappingThreshold();
} }
int CompatUtility::GetServiceFreshnessChecksEnabled(const Service::Ptr& service) int CompatUtility::GetCheckableFreshnessChecksEnabled(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return (service->GetCheckInterval() > 0 ? 1 : 0); return (checkable->GetCheckInterval() > 0 ? 1 : 0);
} }
int CompatUtility::GetServiceFreshnessThreshold(const Service::Ptr& service) int CompatUtility::GetCheckableFreshnessThreshold(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return static_cast<int>(service->GetCheckInterval()); return static_cast<int>(checkable->GetCheckInterval());
} }
double CompatUtility::GetServiceStaleness(const Service::Ptr& service) double CompatUtility::GetCheckableStaleness(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
if (service->HasBeenChecked() && service->GetLastCheck() > 0) if (checkable->HasBeenChecked() && checkable->GetLastCheck() > 0)
return (Utility::GetTime() - service->GetLastCheck()) / (service->GetCheckInterval() * 3600); return (Utility::GetTime() - checkable->GetLastCheck()) / (checkable->GetCheckInterval() * 3600);
return 0.0; return 0.0;
} }
int CompatUtility::GetServiceIsAcknowledged(const Service::Ptr& service) int CompatUtility::GetCheckableIsAcknowledged(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return (service->IsAcknowledged() ? 1 : 0); return (checkable->IsAcknowledged() ? 1 : 0);
} }
int CompatUtility::GetServiceNoMoreNotifications(const Service::Ptr& service) int CompatUtility::GetCheckableNoMoreNotifications(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
if (CompatUtility::GetServiceNotificationNotificationInterval(service) == 0 && !service->GetVolatile()) if (CompatUtility::GetCheckableNotificationNotificationInterval(checkable) == 0 && !checkable->GetVolatile())
return 1; return 1;
return 0; return 0;
} }
int CompatUtility::GetServiceInCheckPeriod(const Service::Ptr& service) int CompatUtility::GetCheckableInCheckPeriod(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
TimePeriod::Ptr timeperiod = service->GetCheckPeriod(); TimePeriod::Ptr timeperiod = checkable->GetCheckPeriod();
/* none set means always checked */ /* none set means always checked */
if (!timeperiod) if (!timeperiod)
@ -410,11 +388,11 @@ int CompatUtility::GetServiceInCheckPeriod(const Service::Ptr& service)
return (timeperiod->IsInside(Utility::GetTime()) ? 1 : 0); return (timeperiod->IsInside(Utility::GetTime()) ? 1 : 0);
} }
int CompatUtility::GetServiceInNotificationPeriod(const Service::Ptr& service) int CompatUtility::GetCheckableInNotificationPeriod(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
BOOST_FOREACH(const Notification::Ptr& notification, service->GetNotifications()) { BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) {
ObjectLock olock(notification); ObjectLock olock(notification);
TimePeriod::Ptr timeperiod = notification->GetNotificationPeriod(); TimePeriod::Ptr timeperiod = notification->GetNotificationPeriod();
@ -433,18 +411,7 @@ Dictionary::Ptr CompatUtility::GetCustomAttributeConfig(const DynamicObject::Ptr
{ {
ASSERT(object->OwnsLock()); ASSERT(object->OwnsLock());
Dictionary::Ptr vars; Dictionary::Ptr vars = object->GetVars();
if (object->GetType() == DynamicType::GetByName("Host")) {
vars = static_pointer_cast<Host>(object)->GetVars();
} else if (object->GetType() == DynamicType::GetByName("Service")) {
vars = static_pointer_cast<Service>(object)->GetVars();
} else if (object->GetType() == DynamicType::GetByName("User")) {
vars = static_pointer_cast<User>(object)->GetVars();
} else {
Log(LogDebug, "icinga", "unknown object type for vars vars");
return Dictionary::Ptr();
}
Dictionary::Ptr varsvars = make_shared<Dictionary>(); Dictionary::Ptr varsvars = make_shared<Dictionary>();
@ -476,18 +443,7 @@ String CompatUtility::GetCustomAttributeConfig(const DynamicObject::Ptr& object,
{ {
ASSERT(object->OwnsLock()); ASSERT(object->OwnsLock());
Dictionary::Ptr vars; Dictionary::Ptr vars = object->GetVars();
if (object->GetType() == DynamicType::GetByName("Host")) {
vars = static_pointer_cast<Host>(object)->GetVars();
} else if (object->GetType() == DynamicType::GetByName("Service")) {
vars = static_pointer_cast<Service>(object)->GetVars();
} else if (object->GetType() == DynamicType::GetByName("User")) {
vars = static_pointer_cast<User>(object)->GetVars();
} else {
Log(LogDebug, "icinga", "unknown object type for vars attributes");
return Empty;
}
if (!vars) if (!vars)
return Empty; return Empty;
@ -496,19 +452,19 @@ String CompatUtility::GetCustomAttributeConfig(const DynamicObject::Ptr& object,
} }
/* notifications */ /* notifications */
int CompatUtility::GetServiceNotificationsEnabled(const Service::Ptr& service) int CompatUtility::GetCheckableNotificationsEnabled(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
return (service->GetEnableNotifications() ? 1 : 0); return (checkable->GetEnableNotifications() ? 1 : 0);
} }
int CompatUtility::GetServiceNotificationLastNotification(const Service::Ptr& service) int CompatUtility::GetCheckableNotificationLastNotification(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
double last_notification = 0.0; double last_notification = 0.0;
BOOST_FOREACH(const Notification::Ptr& notification, service->GetNotifications()) { BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) {
if (notification->GetLastNotification() > last_notification) if (notification->GetLastNotification() > last_notification)
last_notification = notification->GetLastNotification(); last_notification = notification->GetLastNotification();
} }
@ -516,25 +472,25 @@ int CompatUtility::GetServiceNotificationLastNotification(const Service::Ptr& se
return static_cast<int>(last_notification); return static_cast<int>(last_notification);
} }
int CompatUtility::GetServiceNotificationNextNotification(const Service::Ptr& service) int CompatUtility::GetCheckableNotificationNextNotification(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
double next_notification = 0.0; double next_notification = 0.0;
BOOST_FOREACH(const Notification::Ptr& notification, service->GetNotifications()) { BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) {
if (notification->GetNextNotification() < next_notification) if (next_notification == 0 || notification->GetNextNotification() < next_notification)
next_notification = notification->GetNextNotification(); next_notification = notification->GetNextNotification();
} }
return static_cast<int>(next_notification); return static_cast<int>(next_notification);
} }
int CompatUtility::GetServiceNotificationNotificationNumber(const Service::Ptr& service) int CompatUtility::GetCheckableNotificationNotificationNumber(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
int notification_number = 0; int notification_number = 0;
BOOST_FOREACH(const Notification::Ptr& notification, service->GetNotifications()) { BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) {
if (notification->GetNotificationNumber() > notification_number) if (notification->GetNotificationNumber() > notification_number)
notification_number = notification->GetNotificationNumber(); notification_number = notification->GetNotificationNumber();
} }
@ -542,13 +498,13 @@ int CompatUtility::GetServiceNotificationNotificationNumber(const Service::Ptr&
return notification_number; return notification_number;
} }
double CompatUtility::GetServiceNotificationNotificationInterval(const Service::Ptr& service) double CompatUtility::GetCheckableNotificationNotificationInterval(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
double notification_interval = -1; double notification_interval = -1;
BOOST_FOREACH(const Notification::Ptr& notification, service->GetNotifications()) { BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) {
if (notification_interval == -1 || notification->GetNotificationInterval() < notification_interval) if (notification_interval == -1 || notification->GetNotificationInterval() < notification_interval)
notification_interval = notification->GetNotificationInterval(); notification_interval = notification->GetNotificationInterval();
} }
@ -559,13 +515,13 @@ double CompatUtility::GetServiceNotificationNotificationInterval(const Service::
return notification_interval / 60.0; return notification_interval / 60.0;
} }
String CompatUtility::GetServiceNotificationNotificationPeriod(const Service::Ptr& service) String CompatUtility::GetCheckableNotificationNotificationPeriod(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
TimePeriod::Ptr notification_period; TimePeriod::Ptr notification_period;
BOOST_FOREACH(const Notification::Ptr& notification, service->GetNotifications()) { BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) {
if (notification->GetNotificationPeriod()) if (notification->GetNotificationPeriod())
notification_period = notification->GetNotificationPeriod(); notification_period = notification->GetNotificationPeriod();
@ -577,14 +533,14 @@ String CompatUtility::GetServiceNotificationNotificationPeriod(const Service::Pt
return notification_period->GetName(); return notification_period->GetName();
} }
String CompatUtility::GetServiceNotificationNotificationOptions(const Service::Ptr& service) String CompatUtility::GetCheckableNotificationNotificationOptions(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
unsigned long notification_type_filter = 0; unsigned long notification_type_filter = 0;
unsigned long notification_state_filter = 0; unsigned long notification_state_filter = 0;
BOOST_FOREACH(const Notification::Ptr& notification, service->GetNotifications()) { BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) {
if (notification->GetNotificationTypeFilter()) if (notification->GetNotificationTypeFilter())
notification_type_filter = notification->GetNotificationTypeFilter(); notification_type_filter = notification->GetNotificationTypeFilter();
@ -622,13 +578,13 @@ String CompatUtility::GetServiceNotificationNotificationOptions(const Service::P
return boost::algorithm::join(notification_options, ","); return boost::algorithm::join(notification_options, ",");
} }
int CompatUtility::GetServiceNotificationTypeFilter(const Service::Ptr& service) int CompatUtility::GetCheckableNotificationTypeFilter(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
unsigned long notification_type_filter = 0; unsigned long notification_type_filter = 0;
BOOST_FOREACH(const Notification::Ptr& notification, service->GetNotifications()) { BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) {
ObjectLock olock(notification); ObjectLock olock(notification);
if (notification->GetNotificationTypeFilter()) if (notification->GetNotificationTypeFilter())
@ -638,13 +594,13 @@ int CompatUtility::GetServiceNotificationTypeFilter(const Service::Ptr& service)
return notification_type_filter; return notification_type_filter;
} }
int CompatUtility::GetServiceNotificationStateFilter(const Service::Ptr& service) int CompatUtility::GetCheckableNotificationStateFilter(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
unsigned long notification_state_filter = 0; unsigned long notification_state_filter = 0;
BOOST_FOREACH(const Notification::Ptr& notification, service->GetNotifications()) { BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) {
ObjectLock olock(notification); ObjectLock olock(notification);
if (notification->GetNotificationStateFilter()) if (notification->GetNotificationStateFilter())
@ -654,51 +610,51 @@ int CompatUtility::GetServiceNotificationStateFilter(const Service::Ptr& service
return notification_state_filter; return notification_state_filter;
} }
int CompatUtility::GetServiceNotifyOnWarning(const Service::Ptr& service) int CompatUtility::GetCheckableNotifyOnWarning(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
if (GetServiceNotificationStateFilter(service) & (1<<StateWarning)) if (GetCheckableNotificationStateFilter(checkable) & (1<<StateWarning))
return 1; return 1;
return 0; return 0;
} }
int CompatUtility::GetServiceNotifyOnCritical(const Service::Ptr& service) int CompatUtility::GetCheckableNotifyOnCritical(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
if (GetServiceNotificationStateFilter(service) & (1<<StateCritical)) if (GetCheckableNotificationStateFilter(checkable) & (1<<StateCritical))
return 1; return 1;
return 0; return 0;
} }
int CompatUtility::GetServiceNotifyOnUnknown(const Service::Ptr& service) int CompatUtility::GetCheckableNotifyOnUnknown(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
if (GetServiceNotificationStateFilter(service) & (1<<StateUnknown)) if (GetCheckableNotificationStateFilter(checkable) & (1<<StateUnknown))
return 1; return 1;
return 0; return 0;
} }
int CompatUtility::GetServiceNotifyOnRecovery(const Service::Ptr& service) int CompatUtility::GetCheckableNotifyOnRecovery(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
if (GetServiceNotificationTypeFilter(service) & (1<<NotificationRecovery)) if (GetCheckableNotificationTypeFilter(checkable) & (1<<NotificationRecovery))
return 1; return 1;
return 0; return 0;
} }
int CompatUtility::GetServiceNotifyOnFlapping(const Service::Ptr& service) int CompatUtility::GetCheckableNotifyOnFlapping(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
unsigned long notification_type_filter = GetServiceNotificationTypeFilter(service); unsigned long notification_type_filter = GetCheckableNotificationTypeFilter(checkable);
if (notification_type_filter & (1<<NotificationFlappingStart) || if (notification_type_filter & (1<<NotificationFlappingStart) ||
notification_type_filter & (1<<NotificationFlappingEnd)) notification_type_filter & (1<<NotificationFlappingEnd))
@ -707,11 +663,11 @@ int CompatUtility::GetServiceNotifyOnFlapping(const Service::Ptr& service)
return 0; return 0;
} }
int CompatUtility::GetServiceNotifyOnDowntime(const Service::Ptr& service) int CompatUtility::GetCheckableNotifyOnDowntime(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
unsigned long notification_type_filter = GetServiceNotificationTypeFilter(service); unsigned long notification_type_filter = GetCheckableNotificationTypeFilter(checkable);
if (notification_type_filter & (1<<NotificationDowntimeStart) || if (notification_type_filter & (1<<NotificationDowntimeStart) ||
notification_type_filter & (1<<NotificationDowntimeEnd) || notification_type_filter & (1<<NotificationDowntimeEnd) ||
@ -721,15 +677,15 @@ int CompatUtility::GetServiceNotifyOnDowntime(const Service::Ptr& service)
return 0; return 0;
} }
std::set<User::Ptr> CompatUtility::GetServiceNotificationUsers(const Service::Ptr& service) std::set<User::Ptr> CompatUtility::GetCheckableNotificationUsers(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
/* Service -> Notifications -> (Users + UserGroups -> Users) */ /* Service -> Notifications -> (Users + UserGroups -> Users) */
std::set<User::Ptr> allUsers; std::set<User::Ptr> allUsers;
std::set<User::Ptr> users; std::set<User::Ptr> users;
BOOST_FOREACH(const Notification::Ptr& notification, service->GetNotifications()) { BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) {
ObjectLock olock(notification); ObjectLock olock(notification);
users = notification->GetUsers(); users = notification->GetUsers();
@ -745,13 +701,13 @@ std::set<User::Ptr> CompatUtility::GetServiceNotificationUsers(const Service::Pt
return allUsers; return allUsers;
} }
std::set<UserGroup::Ptr> CompatUtility::GetServiceNotificationUserGroups(const Service::Ptr& service) std::set<UserGroup::Ptr> CompatUtility::GetCheckableNotificationUserGroups(const Checkable::Ptr& checkable)
{ {
ASSERT(service->OwnsLock()); ASSERT(checkable->OwnsLock());
std::set<UserGroup::Ptr> usergroups; std::set<UserGroup::Ptr> usergroups;
/* Service -> Notifications -> UserGroups */ /* Service -> Notifications -> UserGroups */
BOOST_FOREACH(const Notification::Ptr& notification, service->GetNotifications()) { BOOST_FOREACH(const Notification::Ptr& notification, checkable->GetNotifications()) {
ObjectLock olock(notification); ObjectLock olock(notification);
BOOST_FOREACH(const UserGroup::Ptr& ug, notification->GetUserGroups()) { BOOST_FOREACH(const UserGroup::Ptr& ug, notification->GetUserGroups()) {

View File

@ -33,17 +33,11 @@ namespace icinga
/** /**
* @ingroup icinga * @ingroup icinga
*/ */
enum CompatObjectType struct Host2dCoords {
{
CompatTypeService,
CompatTypeHost
};
typedef struct {
int have_2d_coords; int have_2d_coords;
String x_2d; String x_2d;
String y_2d; String y_2d;
} Host2dCoords; };
/** /**
* Compatibility utility functions. * Compatibility utility functions.
@ -65,56 +59,55 @@ public:
static int GetHostNotifyOnUnreachable(const Host::Ptr& host); static int GetHostNotifyOnUnreachable(const Host::Ptr& host);
/* service */ /* service */
static int GetServiceCurrentState(const Service::Ptr& service); static int GetCheckableShouldBeScheduled(const Checkable::Ptr& checkable);
static int GetServiceShouldBeScheduled(const Service::Ptr& service); static int GetCheckableCheckType(const Checkable::Ptr& checkable);
static int GetServiceCheckType(const Service::Ptr& service); static double GetCheckableCheckInterval(const Checkable::Ptr& checkable);
static double GetServiceCheckInterval(const Service::Ptr& service); static double GetCheckableRetryInterval(const Checkable::Ptr& checkable);
static double GetServiceRetryInterval(const Service::Ptr& service); static String GetCheckableCheckPeriod(const Checkable::Ptr& checkable);
static String GetServiceCheckPeriod(const Service::Ptr& service); static int GetCheckableHasBeenChecked(const Checkable::Ptr& checkable);
static int GetServiceHasBeenChecked(const Service::Ptr& service); static int GetCheckableProblemHasBeenAcknowledged(const Checkable::Ptr& checkable);
static int GetServiceProblemHasBeenAcknowledged(const Service::Ptr& service); static int GetCheckableAcknowledgementType(const Checkable::Ptr& checkable);
static int GetServiceAcknowledgementType(const Service::Ptr& service); static int GetCheckablePassiveChecksEnabled(const Checkable::Ptr& checkable);
static int GetServicePassiveChecksEnabled(const Service::Ptr& service); static int GetCheckableActiveChecksEnabled(const Checkable::Ptr& checkable);
static int GetServiceActiveChecksEnabled(const Service::Ptr& service); static int GetCheckableEventHandlerEnabled(const Checkable::Ptr& checkable);
static int GetServiceEventHandlerEnabled(const Service::Ptr& service); static int GetCheckableFlapDetectionEnabled(const Checkable::Ptr& checkable);
static int GetServiceFlapDetectionEnabled(const Service::Ptr& service); static int GetCheckableIsFlapping(const Checkable::Ptr& checkable);
static int GetServiceIsFlapping(const Service::Ptr& service); static String GetCheckablePercentStateChange(const Checkable::Ptr& checkable);
static String GetServicePercentStateChange(const Service::Ptr& service); static int GetCheckableProcessPerformanceData(const Checkable::Ptr& checkable);
static int GetServiceProcessPerformanceData(const Service::Ptr& service);
static String GetServiceEventHandler(const Service::Ptr& service); static String GetCheckableEventHandler(const Checkable::Ptr& checkable);
static String GetServiceCheckCommand(const Service::Ptr& service); static String GetCheckableCheckCommand(const Checkable::Ptr& checkable);
static int GetServiceIsVolatile(const Service::Ptr& service); static int GetCheckableIsVolatile(const Checkable::Ptr& checkable);
static double GetServiceLowFlapThreshold(const Service::Ptr& service); static double GetCheckableLowFlapThreshold(const Checkable::Ptr& checkable);
static double GetServiceHighFlapThreshold(const Service::Ptr& service); static double GetCheckableHighFlapThreshold(const Checkable::Ptr& checkable);
static int GetServiceFreshnessChecksEnabled(const Service::Ptr& service); static int GetCheckableFreshnessChecksEnabled(const Checkable::Ptr& checkable);
static int GetServiceFreshnessThreshold(const Service::Ptr& service); static int GetCheckableFreshnessThreshold(const Checkable::Ptr& checkable);
static double GetServiceStaleness(const Service::Ptr& service); static double GetCheckableStaleness(const Checkable::Ptr& checkable);
static int GetServiceIsAcknowledged(const Service::Ptr& service); static int GetCheckableIsAcknowledged(const Checkable::Ptr& checkable);
static int GetServiceNoMoreNotifications(const Service::Ptr& service); static int GetCheckableNoMoreNotifications(const Checkable::Ptr& checkable);
static int GetServiceInCheckPeriod(const Service::Ptr& service); static int GetCheckableInCheckPeriod(const Checkable::Ptr& checkable);
static int GetServiceInNotificationPeriod(const Service::Ptr& service); static int GetCheckableInNotificationPeriod(const Checkable::Ptr& checkable);
/* notification */ /* notification */
static int GetServiceNotificationsEnabled(const Service::Ptr& service); static int GetCheckableNotificationsEnabled(const Checkable::Ptr& checkable);
static int GetServiceNotificationLastNotification(const Service::Ptr& service); static int GetCheckableNotificationLastNotification(const Checkable::Ptr& checkable);
static int GetServiceNotificationNextNotification(const Service::Ptr& service); static int GetCheckableNotificationNextNotification(const Checkable::Ptr& checkable);
static int GetServiceNotificationNotificationNumber(const Service::Ptr& service); static int GetCheckableNotificationNotificationNumber(const Checkable::Ptr& checkable);
static double GetServiceNotificationNotificationInterval(const Service::Ptr& service); static double GetCheckableNotificationNotificationInterval(const Checkable::Ptr& checkable);
static String GetServiceNotificationNotificationPeriod(const Service::Ptr& service); static String GetCheckableNotificationNotificationPeriod(const Checkable::Ptr& checkable);
static String GetServiceNotificationNotificationOptions(const Service::Ptr& service); static String GetCheckableNotificationNotificationOptions(const Checkable::Ptr& checkable);
static int GetServiceNotificationTypeFilter(const Service::Ptr& service); static int GetCheckableNotificationTypeFilter(const Checkable::Ptr& checkable);
static int GetServiceNotificationStateFilter(const Service::Ptr& service); static int GetCheckableNotificationStateFilter(const Checkable::Ptr& checkable);
static int GetServiceNotifyOnWarning(const Service::Ptr& service); static int GetCheckableNotifyOnWarning(const Checkable::Ptr& checkable);
static int GetServiceNotifyOnCritical(const Service::Ptr& service); static int GetCheckableNotifyOnCritical(const Checkable::Ptr& checkable);
static int GetServiceNotifyOnUnknown(const Service::Ptr& service); static int GetCheckableNotifyOnUnknown(const Checkable::Ptr& checkable);
static int GetServiceNotifyOnRecovery(const Service::Ptr& service); static int GetCheckableNotifyOnRecovery(const Checkable::Ptr& checkable);
static int GetServiceNotifyOnFlapping(const Service::Ptr& service); static int GetCheckableNotifyOnFlapping(const Checkable::Ptr& checkable);
static int GetServiceNotifyOnDowntime(const Service::Ptr& service); static int GetCheckableNotifyOnDowntime(const Checkable::Ptr& checkable);
static std::set<User::Ptr> GetServiceNotificationUsers(const Service::Ptr& service); static std::set<User::Ptr> GetCheckableNotificationUsers(const Checkable::Ptr& checkable);
static std::set<UserGroup::Ptr> GetServiceNotificationUserGroups(const Service::Ptr& service); static std::set<UserGroup::Ptr> GetCheckableNotificationUserGroups(const Checkable::Ptr& checkable);
/* command */ /* command */
static String GetCommandLine(const Command::Ptr& command); static String GetCommandLine(const Command::Ptr& command);

View File

@ -18,6 +18,7 @@
******************************************************************************/ ******************************************************************************/
#include "icinga/dependency.h" #include "icinga/dependency.h"
#include "icinga/service.h"
#include "config/configitembuilder.h" #include "config/configitembuilder.h"
#include "base/initialize.h" #include "base/initialize.h"
#include "base/dynamictype.h" #include "base/dynamictype.h"

View File

@ -18,6 +18,7 @@
******************************************************************************/ ******************************************************************************/
#include "icinga/dependency.h" #include "icinga/dependency.h"
#include "icinga/service.h"
#include "base/dynamictype.h" #include "base/dynamictype.h"
#include "base/objectlock.h" #include "base/objectlock.h"
#include "base/logger_fwd.h" #include "base/logger_fwd.h"
@ -33,56 +34,64 @@ void Dependency::OnStateLoaded(void)
ASSERT(!OwnsLock()); ASSERT(!OwnsLock());
if (!GetChildService()) if (!GetChild())
Log(LogWarning, "icinga", "Dependency '" + GetName() + "' references an invalid child service and will be ignored."); Log(LogWarning, "icinga", "Dependency '" + GetName() + "' references an invalid child service and will be ignored.");
else else
GetChildService()->AddDependency(GetSelf()); GetChild()->AddDependency(GetSelf());
if (!GetParentService()) if (!GetParent())
Log(LogWarning, "icinga", "Dependency '" + GetName() + "' references an invalid parent service and will always fail."); Log(LogWarning, "icinga", "Dependency '" + GetName() + "' references an invalid parent service and will always fail.");
else else
GetParentService()->AddReverseDependency(GetSelf()); GetParent()->AddReverseDependency(GetSelf());
} }
void Dependency::Stop(void) void Dependency::Stop(void)
{ {
DynamicObject::Stop(); DynamicObject::Stop();
if (GetChildService()) if (GetChild())
GetChildService()->RemoveDependency(GetSelf()); GetChild()->RemoveDependency(GetSelf());
if (GetParentService()) if (GetParent())
GetParentService()->RemoveReverseDependency(GetSelf()); GetParent()->RemoveReverseDependency(GetSelf());
} }
bool Dependency::IsAvailable(DependencyType dt) const bool Dependency::IsAvailable(DependencyType dt) const
{ {
Service::Ptr service = GetParentService(); Checkable::Ptr parent = GetParent();
if (!service) if (!parent)
return false; return false;
/* ignore if it's the same service */ /* ignore if it's the same service */
if (service == GetChildService()) { if (parent == GetChild()) {
Log(LogDebug, "icinga", "Dependency '" + GetName() + "' passed: Parent and child service are identical."); Log(LogDebug, "icinga", "Dependency '" + GetName() + "' passed: Parent and child service are identical.");
return true; return true;
} }
/* ignore pending services */ /* ignore pending services */
if (!service->GetLastCheckResult()) { if (!parent->GetLastCheckResult()) {
Log(LogDebug, "icinga", "Dependency '" + GetName() + "' passed: Service hasn't been checked yet."); Log(LogDebug, "icinga", "Dependency '" + GetName() + "' passed: Service hasn't been checked yet.");
return true; return true;
} }
/* ignore soft states */ /* ignore soft states */
if (service->GetStateType() == StateTypeSoft) { if (parent->GetStateType() == StateTypeSoft) {
Log(LogDebug, "icinga", "Dependency '" + GetName() + "' passed: Service is in a soft state."); Log(LogDebug, "icinga", "Dependency '" + GetName() + "' passed: Service is in a soft state.");
return true; return true;
} }
bool is_service = parent->GetType() == DynamicType::GetByName("Service");
int state;
if (is_service)
state = static_cast<int>(static_pointer_cast<Service>(parent)->GetState());
else
state = static_cast<int>(static_pointer_cast<Host>(parent)->GetState());
/* check state */ /* check state */
if ((1 << static_cast<int>(service->GetState())) & GetStateFilter()) { if ((1 << state) & GetStateFilter()) {
Log(LogDebug, "icinga", "Dependency '" + GetName() + "' passed: Service matches state filter."); Log(LogDebug, "icinga", "Dependency '" + GetName() + "' passed: Object matches state filter.");
return true; return true;
} }
@ -105,7 +114,7 @@ bool Dependency::IsAvailable(DependencyType dt) const
return false; return false;
} }
Service::Ptr Dependency::GetChildService(void) const Checkable::Ptr Dependency::GetChild(void) const
{ {
Host::Ptr host = Host::GetByName(GetChildHostRaw()); Host::Ptr host = Host::GetByName(GetChildHostRaw());
@ -113,12 +122,12 @@ Service::Ptr Dependency::GetChildService(void) const
return Service::Ptr(); return Service::Ptr();
if (GetChildServiceRaw().IsEmpty()) if (GetChildServiceRaw().IsEmpty())
return host->GetCheckService(); return host;
else
return host->GetServiceByShortName(GetChildServiceRaw()); return host->GetServiceByShortName(GetChildServiceRaw());
} }
Service::Ptr Dependency::GetParentService(void) const Checkable::Ptr Dependency::GetParent(void) const
{ {
Host::Ptr host = Host::GetByName(GetParentHostRaw()); Host::Ptr host = Host::GetByName(GetParentHostRaw());
@ -126,9 +135,9 @@ Service::Ptr Dependency::GetParentService(void) const
return Service::Ptr(); return Service::Ptr();
if (GetParentServiceRaw().IsEmpty()) if (GetParentServiceRaw().IsEmpty())
return host->GetCheckService(); return host;
else
return host->GetServiceByShortName(GetParentServiceRaw()); return host->GetServiceByShortName(GetParentServiceRaw());
} }
TimePeriod::Ptr Dependency::GetPeriod(void) const TimePeriod::Ptr Dependency::GetPeriod(void) const

View File

@ -22,7 +22,6 @@
#include "icinga/i2-icinga.h" #include "icinga/i2-icinga.h"
#include "icinga/dependency.th" #include "icinga/dependency.th"
#include "icinga/service.h"
#include "config/applyrule.h" #include "config/applyrule.h"
#include "base/array.h" #include "base/array.h"
#include "base/dictionary.h" #include "base/dictionary.h"
@ -41,8 +40,8 @@ public:
DECLARE_PTR_TYPEDEFS(Dependency); DECLARE_PTR_TYPEDEFS(Dependency);
DECLARE_TYPENAME(Dependency); DECLARE_TYPENAME(Dependency);
Service::Ptr GetParentService(void) const; shared_ptr<Checkable> GetParent(void) const;
Service::Ptr GetChildService(void) const; shared_ptr<Checkable> GetChild(void) const;
TimePeriod::Ptr GetPeriod(void) const; TimePeriod::Ptr GetPeriod(void) const;

View File

@ -1,5 +1,5 @@
#include "base/dynamicobject.h" #include "base/dynamicobject.h"
#include "icinga/service.h" #include "icinga/checkable.h"
namespace icinga namespace icinga
{ {

View File

@ -24,9 +24,9 @@ using namespace icinga;
REGISTER_TYPE(EventCommand); REGISTER_TYPE(EventCommand);
void EventCommand::Execute(const Service::Ptr& service) void EventCommand::Execute(const Checkable::Ptr& checkable)
{ {
std::vector<Value> arguments; std::vector<Value> arguments;
arguments.push_back(service); arguments.push_back(checkable);
InvokeMethod("execute", arguments); InvokeMethod("execute", arguments);
} }

View File

@ -37,7 +37,7 @@ public:
DECLARE_PTR_TYPEDEFS(EventCommand); DECLARE_PTR_TYPEDEFS(EventCommand);
DECLARE_TYPENAME(EventCommand); DECLARE_TYPENAME(EventCommand);
virtual void Execute(const Service::Ptr& context); virtual void Execute(const Checkable::Ptr& checkable);
}; };
} }

View File

@ -225,12 +225,7 @@ void ExternalCommandProcessor::ProcessHostCheckResult(double time, const std::ve
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot process passive host check result for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot process passive host check result for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService(); if (!host->GetEnablePassiveChecks())
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot process passive host check result for host '" + arguments[0] + "' which has no check service."));
if (!hc->GetEnablePassiveChecks())
BOOST_THROW_EXCEPTION(std::invalid_argument("Got passive check result for host '" + arguments[0] + "' which has passive checks disabled.")); BOOST_THROW_EXCEPTION(std::invalid_argument("Got passive check result for host '" + arguments[0] + "' which has passive checks disabled."));
int exitStatus = Convert::ToDouble(arguments[1]); int exitStatus = Convert::ToDouble(arguments[1]);
@ -257,15 +252,15 @@ void ExternalCommandProcessor::ProcessHostCheckResult(double time, const std::ve
result->SetActive(false); result->SetActive(false);
Log(LogInformation, "icinga", "Processing passive check result for host '" + arguments[0] + "'"); Log(LogInformation, "icinga", "Processing passive check result for host '" + arguments[0] + "'");
hc->ProcessCheckResult(result); host->ProcessCheckResult(result);
{ {
ObjectLock olock(hc); ObjectLock olock(host);
/* Reschedule the next check. The side effect of this is that for as long /* Reschedule the next check. The side effect of this is that for as long
* as we receive passive results for a service we won't execute any * as we receive passive results for a service we won't execute any
* active checks. */ * active checks. */
hc->SetNextCheck(Utility::GetTime() + hc->GetCheckInterval()); host->SetNextCheck(Utility::GetTime() + host->GetCheckInterval());
} }
} }
@ -318,14 +313,9 @@ void ExternalCommandProcessor::ScheduleHostCheck(double, const std::vector<Strin
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot reschedule host check for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot reschedule host check for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot reschedule host check for host '" + arguments[0] + "' which has no check service."));
double planned_check = Convert::ToDouble(arguments[1]); double planned_check = Convert::ToDouble(arguments[1]);
if (planned_check > hc->GetNextCheck()) { if (planned_check > host->GetNextCheck()) {
Log(LogInformation, "icinga", "Ignoring reschedule request for host '" + Log(LogInformation, "icinga", "Ignoring reschedule request for host '" +
arguments[0] + "' (next check is already sooner than requested check time)"); arguments[0] + "' (next check is already sooner than requested check time)");
return; return;
@ -337,9 +327,9 @@ void ExternalCommandProcessor::ScheduleHostCheck(double, const std::vector<Strin
planned_check = Utility::GetTime(); planned_check = Utility::GetTime();
{ {
ObjectLock olock(hc); ObjectLock olock(host);
hc->SetNextCheck(planned_check); host->SetNextCheck(planned_check);
} }
} }
@ -353,18 +343,13 @@ void ExternalCommandProcessor::ScheduleForcedHostCheck(double, const std::vector
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot reschedule forced host check for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot reschedule forced host check for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot reschedule forced host check for host '" + arguments[0] + "' which has no check service."));
Log(LogInformation, "icinga", "Rescheduling next check for host '" + arguments[0] + "'"); Log(LogInformation, "icinga", "Rescheduling next check for host '" + arguments[0] + "'");
{ {
ObjectLock olock(hc); ObjectLock olock(host);
hc->SetForceNextCheck(true); host->SetForceNextCheck(true);
hc->SetNextCheck(Convert::ToDouble(arguments[1])); host->SetNextCheck(Convert::ToDouble(arguments[1]));
} }
} }
@ -428,17 +413,12 @@ void ExternalCommandProcessor::EnableHostCheck(double, const std::vector<String>
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable host checks for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable host checks for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable host checks for host '" + arguments[0] + "' which has no check service."));
Log(LogInformation, "icinga", "Enabling active checks for host '" + arguments[0] + "'"); Log(LogInformation, "icinga", "Enabling active checks for host '" + arguments[0] + "'");
{ {
ObjectLock olock(hc); ObjectLock olock(host);
hc->SetEnableActiveChecks(true); host->SetEnableActiveChecks(true);
} }
} }
@ -452,17 +432,12 @@ void ExternalCommandProcessor::DisableHostCheck(double, const std::vector<String
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable host check non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable host check non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable host checks for host '" + arguments[0] + "' which has no check service."));
Log(LogInformation, "icinga", "Disabling active checks for host '" + arguments[0] + "'"); Log(LogInformation, "icinga", "Disabling active checks for host '" + arguments[0] + "'");
{ {
ObjectLock olock(hc); ObjectLock olock(host);
hc->SetEnableActiveChecks(false); host->SetEnableActiveChecks(false);
} }
} }
@ -685,14 +660,12 @@ void ExternalCommandProcessor::AcknowledgeHostProblem(double, const std::vector<
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot acknowledge host problem for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot acknowledge host problem for non-existent host '" + arguments[0] + "'"));
Log(LogInformation, "icinga", "Setting acknowledgement for host '" + host->GetName() + "'"); Log(LogInformation, "icinga", "Setting acknowledgement for host '" + host->GetName() + "'");
Service::Ptr service = host->GetCheckService();
if (service) {
if (service->GetState() == StateOK)
BOOST_THROW_EXCEPTION(std::invalid_argument("The host '" + arguments[0] + "' is OK."));
service->AddComment(CommentAcknowledgement, arguments[4], arguments[5], 0); if (host->GetState() == HostUp)
service->AcknowledgeProblem(arguments[4], arguments[5], sticky ? AcknowledgementSticky : AcknowledgementNormal); BOOST_THROW_EXCEPTION(std::invalid_argument("The host '" + arguments[0] + "' is OK."));
}
host->AddComment(CommentAcknowledgement, arguments[4], arguments[5], 0);
host->AcknowledgeProblem(arguments[4], arguments[5], sticky ? AcknowledgementSticky : AcknowledgementNormal);
} }
void ExternalCommandProcessor::AcknowledgeHostProblemExpire(double, const std::vector<String>& arguments) void ExternalCommandProcessor::AcknowledgeHostProblemExpire(double, const std::vector<String>& arguments)
@ -709,14 +682,12 @@ void ExternalCommandProcessor::AcknowledgeHostProblemExpire(double, const std::v
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot acknowledge host problem with expire time for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot acknowledge host problem with expire time for non-existent host '" + arguments[0] + "'"));
Log(LogInformation, "icinga", "Setting timed acknowledgement for host '" + host->GetName() + "'"); Log(LogInformation, "icinga", "Setting timed acknowledgement for host '" + host->GetName() + "'");
Service::Ptr service = host->GetCheckService();
if (service) {
if (service->GetState() == StateOK)
BOOST_THROW_EXCEPTION(std::invalid_argument("The host '" + arguments[0] + "' is OK."));
service->AddComment(CommentAcknowledgement, arguments[5], arguments[6], 0); if (host->GetState() == HostUp)
service->AcknowledgeProblem(arguments[5], arguments[6], sticky ? AcknowledgementSticky : AcknowledgementNormal, timestamp); BOOST_THROW_EXCEPTION(std::invalid_argument("The host '" + arguments[0] + "' is OK."));
}
host->AddComment(CommentAcknowledgement, arguments[5], arguments[6], 0);
host->AcknowledgeProblem(arguments[5], arguments[6], sticky ? AcknowledgementSticky : AcknowledgementNormal, timestamp);
} }
void ExternalCommandProcessor::RemoveHostAcknowledgement(double, const std::vector<String>& arguments) void ExternalCommandProcessor::RemoveHostAcknowledgement(double, const std::vector<String>& arguments)
@ -730,14 +701,12 @@ void ExternalCommandProcessor::RemoveHostAcknowledgement(double, const std::vect
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot remove acknowledgement for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot remove acknowledgement for non-existent host '" + arguments[0] + "'"));
Log(LogInformation, "icinga", "Removing acknowledgement for host '" + host->GetName() + "'"); Log(LogInformation, "icinga", "Removing acknowledgement for host '" + host->GetName() + "'");
Service::Ptr service = host->GetCheckService();
if (service) { {
{ ObjectLock olock(host);
ObjectLock olock(service); host->ClearAcknowledgement();
service->ClearAcknowledgement();
}
service->RemoveCommentsByType(CommentAcknowledgement);
} }
host->RemoveCommentsByType(CommentAcknowledgement);
} }
void ExternalCommandProcessor::EnableHostgroupSvcChecks(double, const std::vector<String>& arguments) void ExternalCommandProcessor::EnableHostgroupSvcChecks(double, const std::vector<String>& arguments)
@ -838,17 +807,12 @@ void ExternalCommandProcessor::EnablePassiveHostChecks(double, const std::vector
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable passive host checks for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable passive host checks for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable passive host checks for host '" + arguments[0] + "' which has no check service."));
Log(LogInformation, "icinga", "Enabling passive checks for host '" + arguments[0] + "'"); Log(LogInformation, "icinga", "Enabling passive checks for host '" + arguments[0] + "'");
{ {
ObjectLock olock(hc); ObjectLock olock(host);
hc->SetEnablePassiveChecks(true); host->SetEnablePassiveChecks(true);
} }
} }
@ -862,17 +826,12 @@ void ExternalCommandProcessor::DisablePassiveHostChecks(double, const std::vecto
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable passive host checks for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable passive host checks for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable passive host checks for host '" + arguments[0] + "' which has no check service."));
Log(LogInformation, "icinga", "Disabling passive checks for host '" + arguments[0] + "'"); Log(LogInformation, "icinga", "Disabling passive checks for host '" + arguments[0] + "'");
{ {
ObjectLock olock(hc); ObjectLock olock(host);
hc->SetEnablePassiveChecks(false); host->SetEnablePassiveChecks(false);
} }
} }
@ -1084,12 +1043,10 @@ void ExternalCommandProcessor::ScheduleHostDowntime(double, const std::vector<St
triggeredBy = Service::GetDowntimeIDFromLegacyID(triggeredByLegacy); triggeredBy = Service::GetDowntimeIDFromLegacyID(triggeredByLegacy);
Log(LogInformation, "icinga", "Creating downtime for host " + host->GetName()); Log(LogInformation, "icinga", "Creating downtime for host " + host->GetName());
Service::Ptr service = host->GetCheckService();
if (service) { (void) host->AddDowntime(arguments[6], arguments[7],
(void) service->AddDowntime(arguments[6], arguments[7], Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]), Convert::ToBool(arguments[3]), triggeredBy, Convert::ToDouble(arguments[5]));
Convert::ToBool(arguments[3]), triggeredBy, Convert::ToDouble(arguments[5]));
}
} }
void ExternalCommandProcessor::DelHostDowntime(double, const std::vector<String>& arguments) void ExternalCommandProcessor::DelHostDowntime(double, const std::vector<String>& arguments)
@ -1143,12 +1100,10 @@ void ExternalCommandProcessor::ScheduleHostgroupHostDowntime(double, const std::
BOOST_FOREACH(const Host::Ptr& host, hg->GetMembers()) { BOOST_FOREACH(const Host::Ptr& host, hg->GetMembers()) {
Log(LogInformation, "icinga", "Creating downtime for host " + host->GetName()); Log(LogInformation, "icinga", "Creating downtime for host " + host->GetName());
Service::Ptr service = host->GetCheckService();
if (service) { (void) host->AddDowntime(arguments[6], arguments[7],
(void) service->AddDowntime(arguments[6], arguments[7], Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]), Convert::ToBool(arguments[3]), triggeredBy, Convert::ToDouble(arguments[5]));
Convert::ToBool(arguments[3]), triggeredBy, Convert::ToDouble(arguments[5]));
}
} }
} }
@ -1206,18 +1161,16 @@ void ExternalCommandProcessor::ScheduleServicegroupHostDowntime(double, const st
* over all services in the service group - otherwise we might end up creating multiple * over all services in the service group - otherwise we might end up creating multiple
* downtimes for some hosts. */ * downtimes for some hosts. */
std::set<Service::Ptr> services; std::set<Host::Ptr> hosts;
BOOST_FOREACH(const Service::Ptr& service, sg->GetMembers()) { BOOST_FOREACH(const Service::Ptr& service, sg->GetMembers()) {
Host::Ptr host = service->GetHost(); Host::Ptr host = service->GetHost();
Service::Ptr hcService = host->GetCheckService(); hosts.insert(host);
if (hcService)
services.insert(hcService);
} }
BOOST_FOREACH(const Service::Ptr& service, services) { BOOST_FOREACH(const Host::Ptr& host, hosts) {
Log(LogInformation, "icinga", "Creating downtime for service " + service->GetName()); Log(LogInformation, "icinga", "Creating downtime for host " + host->GetName());
(void) service->AddDowntime(arguments[6], arguments[7], (void) host->AddDowntime(arguments[6], arguments[7],
Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]), Convert::ToDouble(arguments[1]), Convert::ToDouble(arguments[2]),
Convert::ToBool(arguments[3]), triggeredBy, Convert::ToDouble(arguments[5])); Convert::ToBool(arguments[3]), triggeredBy, Convert::ToDouble(arguments[5]));
} }
@ -1257,9 +1210,7 @@ void ExternalCommandProcessor::AddHostComment(double, const std::vector<String>&
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot add host comment for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot add host comment for non-existent host '" + arguments[0] + "'"));
Log(LogInformation, "icinga", "Creating comment for host " + host->GetName()); Log(LogInformation, "icinga", "Creating comment for host " + host->GetName());
Service::Ptr service = host->GetCheckService(); (void) host->AddComment(CommentUser, arguments[2], arguments[3], 0);
if (service)
(void) service->AddComment(CommentUser, arguments[2], arguments[3], 0);
} }
void ExternalCommandProcessor::DelHostComment(double, const std::vector<String>& arguments) void ExternalCommandProcessor::DelHostComment(double, const std::vector<String>& arguments)
@ -1310,9 +1261,7 @@ void ExternalCommandProcessor::DelAllHostComments(double, const std::vector<Stri
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot delete all host comments for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot delete all host comments for non-existent host '" + arguments[0] + "'"));
Log(LogInformation, "icinga", "Removing all comments for host " + host->GetName()); Log(LogInformation, "icinga", "Removing all comments for host " + host->GetName());
Service::Ptr service = host->GetCheckService(); host->RemoveAllComments();
if (service)
service->RemoveAllComments();
} }
void ExternalCommandProcessor::DelAllSvcComments(double, const std::vector<String>& arguments) void ExternalCommandProcessor::DelAllSvcComments(double, const std::vector<String>& arguments)
@ -1342,15 +1291,12 @@ void ExternalCommandProcessor::SendCustomHostNotification(double, const std::vec
int options = Convert::ToLong(arguments[1]); int options = Convert::ToLong(arguments[1]);
Log(LogInformation, "icinga", "Sending custom notification for host " + host->GetName()); Log(LogInformation, "icinga", "Sending custom notification for host " + host->GetName());
Service::Ptr service = host->GetCheckService(); if (options & 2) {
if (service) { ObjectLock olock(host);
if (options & 2) { host->SetForceNextNotification(true);
ObjectLock olock(service);
service->SetForceNextNotification(true);
}
Service::OnNotificationsRequested(service, NotificationCustom, service->GetLastCheckResult(), arguments[2], arguments[3]);
} }
Checkable::OnNotificationsRequested(host, NotificationCustom, host->GetLastCheckResult(), arguments[2], arguments[3]);
} }
void ExternalCommandProcessor::SendCustomSvcNotification(double, const std::vector<String>& arguments) void ExternalCommandProcessor::SendCustomSvcNotification(double, const std::vector<String>& arguments)
@ -1385,14 +1331,9 @@ void ExternalCommandProcessor::DelayHostNotification(double, const std::vector<S
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot delay host notification for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot delay host notification for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot delay host notification for host '" + arguments[0] + "' which has no check service."));
Log(LogInformation, "icinga", "Delaying notifications for host '" + host->GetName() + "'"); Log(LogInformation, "icinga", "Delaying notifications for host '" + host->GetName() + "'");
BOOST_FOREACH(const Notification::Ptr& notification, hc->GetNotifications()) { BOOST_FOREACH(const Notification::Ptr& notification, host->GetNotifications()) {
ObjectLock olock(notification); ObjectLock olock(notification);
notification->SetNextNotification(Convert::ToDouble(arguments[1])); notification->SetNextNotification(Convert::ToDouble(arguments[1]));
@ -1428,17 +1369,12 @@ void ExternalCommandProcessor::EnableHostNotifications(double, const std::vector
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable host notifications for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable host notifications for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable host notifications for host '" + arguments[0] + "' which has no check service."));
Log(LogInformation, "icinga", "Enabling notifications for host '" + arguments[0] + "'"); Log(LogInformation, "icinga", "Enabling notifications for host '" + arguments[0] + "'");
{ {
ObjectLock olock(hc); ObjectLock olock(host);
hc->SetEnableNotifications(true); host->SetEnableNotifications(true);
} }
} }
@ -1452,17 +1388,12 @@ void ExternalCommandProcessor::DisableHostNotifications(double, const std::vecto
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable host notifications for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable host notifications for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable host notifications for host '" + arguments[0] + "' which has no check service."));
Log(LogInformation, "icinga", "Disabling notifications for host '" + arguments[0] + "'"); Log(LogInformation, "icinga", "Disabling notifications for host '" + arguments[0] + "'");
{ {
ObjectLock olock(hc); ObjectLock olock(host);
hc->SetEnableNotifications(false); host->SetEnableNotifications(false);
} }
} }
@ -1515,18 +1446,12 @@ void ExternalCommandProcessor::DisableHostgroupHostChecks(double, const std::vec
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable hostgroup host checks for non-existent hostgroup '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable hostgroup host checks for non-existent hostgroup '" + arguments[0] + "'"));
BOOST_FOREACH(const Host::Ptr& host, hg->GetMembers()) { BOOST_FOREACH(const Host::Ptr& host, hg->GetMembers()) {
Service::Ptr hc = host->GetCheckService(); Log(LogInformation, "icinga", "Disabling active checks for host '" + host->GetName() + "'");
if (!hc) { {
Log(LogInformation, "icinga", "Cannot disable active checks for host '" + host->GetName() + "' which has no check service."); ObjectLock olock(host);
} else {
Log(LogInformation, "icinga", "Disabling active checks for host '" + host->GetName() + "'");
{ host->SetEnableActiveChecks(false);
ObjectLock olock(hc);
hc->SetEnableActiveChecks(false);
}
} }
} }
} }
@ -1542,18 +1467,12 @@ void ExternalCommandProcessor::DisableHostgroupPassiveHostChecks(double, const s
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable hostgroup passive host checks for non-existent hostgroup '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable hostgroup passive host checks for non-existent hostgroup '" + arguments[0] + "'"));
BOOST_FOREACH(const Host::Ptr& host, hg->GetMembers()) { BOOST_FOREACH(const Host::Ptr& host, hg->GetMembers()) {
Service::Ptr hc = host->GetCheckService(); Log(LogInformation, "icinga", "Disabling passive checks for host '" + host->GetName() + "'");
if (!hc) { {
Log(LogInformation, "icinga", "Cannot disable passive checks for host '" + host->GetName() + "' which has no check service."); ObjectLock olock(host);
} else {
Log(LogInformation, "icinga", "Disabling passive checks for host '" + host->GetName() + "'");
{ host->SetEnablePassiveChecks(false);
ObjectLock olock(hc);
hc->SetEnablePassiveChecks(false);
}
} }
} }
} }
@ -1571,18 +1490,12 @@ void ExternalCommandProcessor::DisableServicegroupHostChecks(double, const std::
BOOST_FOREACH(const Service::Ptr& service, sg->GetMembers()) { BOOST_FOREACH(const Service::Ptr& service, sg->GetMembers()) {
Host::Ptr host = service->GetHost(); Host::Ptr host = service->GetHost();
Service::Ptr hc = host->GetCheckService(); Log(LogInformation, "icinga", "Disabling active checks for host '" + host->GetName() + "'");
if (!hc) { {
Log(LogInformation, "icinga", "Cannot disable active checks for host '" + host->GetName() + "' which has no check service."); ObjectLock olock(host);
} else {
Log(LogInformation, "icinga", "Disabling active checks for host '" + host->GetName() + "'");
{ host->SetEnableActiveChecks(false);
ObjectLock olock(hc);
hc->SetEnableActiveChecks(false);
}
} }
} }
} }
@ -1600,18 +1513,12 @@ void ExternalCommandProcessor::DisableServicegroupPassiveHostChecks(double, cons
BOOST_FOREACH(const Service::Ptr& service, sg->GetMembers()) { BOOST_FOREACH(const Service::Ptr& service, sg->GetMembers()) {
Host::Ptr host = service->GetHost(); Host::Ptr host = service->GetHost();
Service::Ptr hc = host->GetCheckService(); Log(LogInformation, "icinga", "Disabling passive checks for host '" + host->GetName() + "'");
if (!hc) { {
Log(LogInformation, "icinga", "Cannot disable passive checks for host '" + host->GetName() + "' which has no check service."); ObjectLock olock(host);
} else {
Log(LogInformation, "icinga", "Disabling passive checks for host '" + host->GetName() + "'");
{ host->SetEnablePassiveChecks(false);
ObjectLock olock(hc);
hc->SetEnablePassiveChecks(false);
}
} }
} }
} }
@ -1627,18 +1534,12 @@ void ExternalCommandProcessor::EnableHostgroupHostChecks(double, const std::vect
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable hostgroup host checks for non-existent hostgroup '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable hostgroup host checks for non-existent hostgroup '" + arguments[0] + "'"));
BOOST_FOREACH(const Host::Ptr& host, hg->GetMembers()) { BOOST_FOREACH(const Host::Ptr& host, hg->GetMembers()) {
Service::Ptr hc = host->GetCheckService(); Log(LogInformation, "icinga", "Enabling active checks for host '" + host->GetName() + "'");
if (!hc) { {
Log(LogInformation, "icinga", "Cannot enable active checks for host '" + host->GetName() + "' which has no check service."); ObjectLock olock(host);
} else {
Log(LogInformation, "icinga", "Enabling active checks for host '" + host->GetName() + "'");
{ host->SetEnableActiveChecks(true);
ObjectLock olock(hc);
hc->SetEnableActiveChecks(true);
}
} }
} }
} }
@ -1654,18 +1555,12 @@ void ExternalCommandProcessor::EnableHostgroupPassiveHostChecks(double, const st
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable hostgroup passive host checks for non-existent hostgroup '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable hostgroup passive host checks for non-existent hostgroup '" + arguments[0] + "'"));
BOOST_FOREACH(const Host::Ptr& host, hg->GetMembers()) { BOOST_FOREACH(const Host::Ptr& host, hg->GetMembers()) {
Service::Ptr hc = host->GetCheckService(); Log(LogInformation, "icinga", "Enabling passive checks for host '" + host->GetName() + "'");
if (!hc) { {
Log(LogInformation, "icinga", "Cannot enable passive checks for host '" + host->GetName() + "' which has no check service."); ObjectLock olock(host);
} else {
Log(LogInformation, "icinga", "Enabling passive checks for host '" + host->GetName() + "'");
{ host->SetEnablePassiveChecks(true);
ObjectLock olock(hc);
hc->SetEnablePassiveChecks(true);
}
} }
} }
} }
@ -1683,18 +1578,12 @@ void ExternalCommandProcessor::EnableServicegroupHostChecks(double, const std::v
BOOST_FOREACH(const Service::Ptr& service, sg->GetMembers()) { BOOST_FOREACH(const Service::Ptr& service, sg->GetMembers()) {
Host::Ptr host = service->GetHost(); Host::Ptr host = service->GetHost();
Service::Ptr hc = host->GetCheckService(); Log(LogInformation, "icinga", "Enabling active checks for host '" + host->GetName() + "'");
if (!hc) { {
Log(LogInformation, "icinga", "Cannot enable active checks for host '" + host->GetName() + "' which has no check service."); ObjectLock olock(host);
} else {
Log(LogInformation, "icinga", "Enabling active checks for host '" + host->GetName() + "'");
{ host->SetEnableActiveChecks(true);
ObjectLock olock(hc);
hc->SetEnableActiveChecks(true);
}
} }
} }
} }
@ -1712,18 +1601,12 @@ void ExternalCommandProcessor::EnableServicegroupPassiveHostChecks(double, const
BOOST_FOREACH(const Service::Ptr& service, sg->GetMembers()) { BOOST_FOREACH(const Service::Ptr& service, sg->GetMembers()) {
Host::Ptr host = service->GetHost(); Host::Ptr host = service->GetHost();
Service::Ptr hc = host->GetCheckService(); Log(LogInformation, "icinga", "Enabling passive checks for host '" + host->GetName() + "'");
if (!hc) { {
Log(LogInformation, "icinga", "Cannot enable passive host checks for host '" + host->GetName() + "' which has no check service."); ObjectLock olock(host);
} else {
Log(LogInformation, "icinga", "Enabling passive checks for host '" + host->GetName() + "'");
{ host->SetEnablePassiveChecks(true);
ObjectLock olock(hc);
hc->SetEnablePassiveChecks(true);
}
} }
} }
} }
@ -1738,17 +1621,12 @@ void ExternalCommandProcessor::EnableHostFlapping(double, const std::vector<Stri
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable host flapping for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable host flapping for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable host flapping for host '" + arguments[0] + "' which has no check service."));
Log(LogInformation, "icinga", "Enabling flapping detection for host '" + arguments[0] + "'"); Log(LogInformation, "icinga", "Enabling flapping detection for host '" + arguments[0] + "'");
{ {
ObjectLock olock(hc); ObjectLock olock(host);
hc->SetEnableFlapping(true); host->SetEnableFlapping(true);
} }
} }
@ -1762,17 +1640,12 @@ void ExternalCommandProcessor::DisableHostFlapping(double, const std::vector<Str
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable host flapping for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable host flapping for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable host flapping for host '" + arguments[0] + "' which has no check service."));
Log(LogInformation, "icinga", "Disabling flapping detection for host '" + arguments[0] + "'"); Log(LogInformation, "icinga", "Disabling flapping detection for host '" + arguments[0] + "'");
{ {
ObjectLock olock(hc); ObjectLock olock(host);
hc->SetEnableFlapping(false); host->SetEnableFlapping(false);
} }
} }
@ -1915,19 +1788,14 @@ void ExternalCommandProcessor::ChangeHostModattr(double time, const std::vector<
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot update modified attributes for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot update modified attributes for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot update modified attributes for host '" + arguments[0] + "' which has no check service."));
Log(LogInformation, "icinga", "Updating modified attributes for host '" + arguments[0] + "'"); Log(LogInformation, "icinga", "Updating modified attributes for host '" + arguments[0] + "'");
int modifiedAttributes = Convert::ToLong(arguments[1]); int modifiedAttributes = Convert::ToLong(arguments[1]);
{ {
ObjectLock olock(hc); ObjectLock olock(host);
hc->SetModifiedAttributes(modifiedAttributes); host->SetModifiedAttributes(modifiedAttributes);
} }
} }
@ -1962,19 +1830,14 @@ void ExternalCommandProcessor::ChangeNormalHostCheckInterval(double time, const
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot update check interval for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot update check interval for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot update check interval for host '" + arguments[0] + "' which has no check service."));
Log(LogInformation, "icinga", "Updating check interval for host '" + arguments[0] + "'"); Log(LogInformation, "icinga", "Updating check interval for host '" + arguments[0] + "'");
double interval = Convert::ToDouble(arguments[1]); double interval = Convert::ToDouble(arguments[1]);
{ {
ObjectLock olock(hc); ObjectLock olock(host);
hc->SetCheckInterval(interval * 60); host->SetCheckInterval(interval * 60);
} }
} }
@ -2009,19 +1872,14 @@ void ExternalCommandProcessor::ChangeRetryHostCheckInterval(double time, const s
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot update retry interval for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot update retry interval for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot update retry interval for host '" + arguments[0] + "' which has no check service."));
Log(LogInformation, "icinga", "Updating retry interval for host '" + arguments[0] + "'"); Log(LogInformation, "icinga", "Updating retry interval for host '" + arguments[0] + "'");
double interval = Convert::ToDouble(arguments[1]); double interval = Convert::ToDouble(arguments[1]);
{ {
ObjectLock olock(hc); ObjectLock olock(host);
hc->SetRetryInterval(interval * 60); host->SetRetryInterval(interval * 60);
} }
} }
@ -2035,17 +1893,12 @@ void ExternalCommandProcessor::EnableHostEventHandler(double time, const std::ve
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable event handler for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable event handler for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable event handler for host '" + arguments[0] + "' which has no check service."));
Log(LogInformation, "icinga", "Enabling event handler for host '" + arguments[0] + "'"); Log(LogInformation, "icinga", "Enabling event handler for host '" + arguments[0] + "'");
{ {
ObjectLock olock(hc); ObjectLock olock(host);
hc->SetEnableEventHandler(true); host->SetEnableEventHandler(true);
} }
} }
@ -2059,17 +1912,12 @@ void ExternalCommandProcessor::DisableHostEventHandler(double time, const std::v
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable event handler for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable event handler for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable event handler for host '" + arguments[0] + "' which has no check service."));
Log(LogInformation, "icinga", "Disabling event handler for host '" + arguments[0] + "'"); Log(LogInformation, "icinga", "Disabling event handler for host '" + arguments[0] + "'");
{ {
ObjectLock olock(hc); ObjectLock olock(host);
hc->SetEnableEventHandler(false); host->SetEnableEventHandler(false);
} }
} }
@ -2121,14 +1969,9 @@ void ExternalCommandProcessor::ChangeHostEventHandler(double time, const std::ve
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot change event handler for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot change event handler for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot change event handler for host '" + arguments[0] + "' which has no check service."));
/* empty command string implicitely disables event handler */ /* empty command string implicitely disables event handler */
if (arguments[1].IsEmpty()) { if (arguments[1].IsEmpty()) {
hc->SetEnableEventHandler(false); host->SetEnableEventHandler(false);
} else { } else {
EventCommand::Ptr command = EventCommand::GetByName(arguments[1]); EventCommand::Ptr command = EventCommand::GetByName(arguments[1]);
@ -2138,9 +1981,9 @@ void ExternalCommandProcessor::ChangeHostEventHandler(double time, const std::ve
Log(LogInformation, "icinga", "Changing event handler for host '" + arguments[0] + "' to '" + arguments[1] + "'"); Log(LogInformation, "icinga", "Changing event handler for host '" + arguments[0] + "' to '" + arguments[1] + "'");
{ {
ObjectLock olock(hc); ObjectLock olock(host);
hc->SetEventCommand(command); host->SetEventCommand(command);
} }
} }
} }
@ -2184,11 +2027,6 @@ void ExternalCommandProcessor::ChangeHostCheckCommand(double time, const std::ve
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot change check command for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot change check command for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot change check command for host '" + arguments[0] + "' which has no check service."));
CheckCommand::Ptr command = CheckCommand::GetByName(arguments[1]); CheckCommand::Ptr command = CheckCommand::GetByName(arguments[1]);
if (!command) if (!command)
@ -2197,9 +2035,9 @@ void ExternalCommandProcessor::ChangeHostCheckCommand(double time, const std::ve
Log(LogInformation, "icinga", "Changing check command for host '" + arguments[0] + "' to '" + arguments[1] + "'"); Log(LogInformation, "icinga", "Changing check command for host '" + arguments[0] + "' to '" + arguments[1] + "'");
{ {
ObjectLock olock(hc); ObjectLock olock(host);
hc->SetCheckCommand(command); host->SetCheckCommand(command);
} }
} }
@ -2237,19 +2075,14 @@ void ExternalCommandProcessor::ChangeMaxHostCheckAttempts(double time, const std
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot change max check attempts for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot change max check attempts for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot change max check attempts for host '" + arguments[0] + "' which has no check service."));
int attempts = Convert::ToLong(arguments[1]); int attempts = Convert::ToLong(arguments[1]);
Log(LogInformation, "icinga", "Changing max check attempts for host '" + arguments[0] + "' to '" + arguments[1] + "'"); Log(LogInformation, "icinga", "Changing max check attempts for host '" + arguments[0] + "' to '" + arguments[1] + "'");
{ {
ObjectLock olock(hc); ObjectLock olock(host);
hc->SetMaxCheckAttempts(attempts); host->SetMaxCheckAttempts(attempts);
} }
} }
@ -2284,11 +2117,6 @@ void ExternalCommandProcessor::ChangeHostCheckTimeperiod(double time, const std:
if (!host) if (!host)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot change check period for non-existent host '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot change check period for non-existent host '" + arguments[0] + "'"));
Service::Ptr hc = host->GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot change check period for host '" + arguments[0] + "' which has no check service."));
TimePeriod::Ptr tp = TimePeriod::GetByName(arguments[1]); TimePeriod::Ptr tp = TimePeriod::GetByName(arguments[1]);
if (!tp) if (!tp)
@ -2297,9 +2125,9 @@ void ExternalCommandProcessor::ChangeHostCheckTimeperiod(double time, const std:
Log(LogInformation, "icinga", "Changing check period for host '" + arguments[0] + "' to '" + arguments[1] + "'"); Log(LogInformation, "icinga", "Changing check period for host '" + arguments[0] + "' to '" + arguments[1] + "'");
{ {
ObjectLock olock(hc); ObjectLock olock(host);
hc->SetCheckPeriod(tp); host->SetCheckPeriod(tp);
} }
} }
@ -2338,18 +2166,12 @@ void ExternalCommandProcessor::EnableHostgroupHostNotifications(double time, con
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable host notifications for non-existent hostgroup '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot enable host notifications for non-existent hostgroup '" + arguments[0] + "'"));
BOOST_FOREACH(const Host::Ptr& host, hg->GetMembers()) { BOOST_FOREACH(const Host::Ptr& host, hg->GetMembers()) {
Service::Ptr hc = host->GetCheckService(); Log(LogInformation, "icinga", "Enabling notifications for host '" + host->GetName() + "'");
if (!hc) { {
Log(LogInformation, "icinga", "Cannot enable notifications for host '" + host->GetName() + "' which has no check service."); ObjectLock olock(host);
} else {
Log(LogInformation, "icinga", "Enabling notifications for host '" + host->GetName() + "'");
{ host->SetEnableNotifications(true);
ObjectLock olock(hc);
hc->SetEnableNotifications(true);
}
} }
} }
} }
@ -2388,18 +2210,12 @@ void ExternalCommandProcessor::DisableHostgroupHostNotifications(double time, co
BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable host notifications for non-existent hostgroup '" + arguments[0] + "'")); BOOST_THROW_EXCEPTION(std::invalid_argument("Cannot disable host notifications for non-existent hostgroup '" + arguments[0] + "'"));
BOOST_FOREACH(const Host::Ptr& host, hg->GetMembers()) { BOOST_FOREACH(const Host::Ptr& host, hg->GetMembers()) {
Service::Ptr hc = host->GetCheckService(); Log(LogInformation, "icinga", "Disabling notifications for host '" + host->GetName() + "'");
if (!hc) { {
Log(LogInformation, "icinga", "Cannot disable notifications for host '" + host->GetName() + "' which has no check service."); ObjectLock olock(host);
} else {
Log(LogInformation, "icinga", "Disabling notifications for host '" + host->GetName() + "'");
{ host->SetEnableNotifications(false);
ObjectLock olock(hc);
hc->SetEnableNotifications(false);
}
} }
} }
} }
@ -2440,18 +2256,12 @@ void ExternalCommandProcessor::EnableServicegroupHostNotifications(double time,
BOOST_FOREACH(const Service::Ptr& service, sg->GetMembers()) { BOOST_FOREACH(const Service::Ptr& service, sg->GetMembers()) {
Host::Ptr host = service->GetHost(); Host::Ptr host = service->GetHost();
Service::Ptr hc = host->GetCheckService(); Log(LogInformation, "icinga", "Enabling notifications for host '" + host->GetName() + "'");
if (!hc) { {
Log(LogInformation, "icinga", "Cannot enable notifications for host '" + host->GetName() + "' which has no check service."); ObjectLock olock(host);
} else {
Log(LogInformation, "icinga", "Enabling notifications for host '" + host->GetName() + "'");
{ host->SetEnableNotifications(true);
ObjectLock olock(hc);
hc->SetEnableNotifications(true);
}
} }
} }
} }
@ -2490,18 +2300,12 @@ void ExternalCommandProcessor::DisableServicegroupHostNotifications(double time,
BOOST_FOREACH(const Service::Ptr& service, sg->GetMembers()) { BOOST_FOREACH(const Service::Ptr& service, sg->GetMembers()) {
Host::Ptr host = service->GetHost(); Host::Ptr host = service->GetHost();
Service::Ptr hc = host->GetCheckService(); Log(LogInformation, "icinga", "Disabling notifications for host '" + host->GetName() + "'");
if (!hc) { {
Log(LogInformation, "icinga", "Cannot disable notifications for host '" + host->GetName() + "' which has no check service."); ObjectLock olock(host);
} else {
Log(LogInformation, "icinga", "Disabling notifications for host '" + host->GetName() + "'");
{ host->SetEnableNotifications(false);
ObjectLock olock(hc);
hc->SetEnableNotifications(false);
}
} }
} }
} }

View File

@ -79,17 +79,6 @@ void Host::Stop(void)
// TODO: unregister slave services/notifications? // TODO: unregister slave services/notifications?
} }
bool Host::IsReachable(DependencyType dt, shared_ptr<Dependency> *failedDependency) const
{
ASSERT(!OwnsLock());
Service::Ptr hc = GetCheckService();
if (!hc)
return true;
return hc->IsReachable(dt, failedDependency);
}
std::set<Service::Ptr> Host::GetServices(void) const std::set<Service::Ptr> Host::GetServices(void) const
{ {
boost::mutex::scoped_lock lock(m_ServicesMutex); boost::mutex::scoped_lock lock(m_ServicesMutex);
@ -122,16 +111,9 @@ int Host::GetTotalServices(void) const
return GetServices().size(); return GetServices().size();
} }
Service::Ptr Host::GetServiceByShortName(const Value& name) const Service::Ptr Host::GetServiceByShortName(const Value& name)
{ {
if (name.IsEmpty()) { if (name.IsScalar()) {
Service::Ptr hc = GetCheckService();
if (!hc)
BOOST_THROW_EXCEPTION(std::invalid_argument("Host does not have a host check service: " + GetName()));
return hc;
} else if (name.IsScalar()) {
{ {
boost::mutex::scoped_lock lock(m_ServicesMutex); boost::mutex::scoped_lock lock(m_ServicesMutex);
@ -152,60 +134,6 @@ Service::Ptr Host::GetServiceByShortName(const Value& name) const
} }
} }
Service::Ptr Host::GetCheckService(void) const
{
String host_check = GetCheck();
if (host_check.IsEmpty())
return Service::Ptr();
return GetServiceByShortName(host_check);
}
std::set<Host::Ptr> Host::GetParentHosts(void) const
{
std::set<Host::Ptr> result;
Service::Ptr hc = GetCheckService();
if (hc)
result = hc->GetParentHosts();
return result;
}
std::set<Host::Ptr> Host::GetChildHosts(void) const
{
std::set<Host::Ptr> result;
Service::Ptr hc = GetCheckService();
if (hc)
result = hc->GetChildHosts();
return result;
}
std::set<Service::Ptr> Host::GetParentServices(void) const
{
std::set<Service::Ptr> result;
Service::Ptr hc = GetCheckService();
if (hc)
result = hc->GetParentServices();
return result;
}
std::set<Service::Ptr> Host::GetChildServices(void) const
{
std::set<Service::Ptr> result;
Service::Ptr hc = GetCheckService();
if (hc)
result = hc->GetChildServices();
return result;
}
HostState Host::CalculateState(ServiceState state, bool reachable) HostState Host::CalculateState(ServiceState state, bool reachable)
{ {
if (!reachable) if (!reachable)
@ -227,12 +155,7 @@ HostState Host::GetState(void) const
if (!IsReachable()) if (!IsReachable())
return HostUnreachable; return HostUnreachable;
Service::Ptr hc = GetCheckService(); switch (GetStateRaw()) {
if (!hc)
return HostUp;
switch (hc->GetState()) {
case StateOK: case StateOK:
case StateWarning: case StateWarning:
return HostUp; return HostUp;
@ -249,12 +172,7 @@ HostState Host::GetLastState(void) const
if (!IsReachable()) if (!IsReachable())
return HostUnreachable; return HostUnreachable;
Service::Ptr hc = GetCheckService(); switch (GetLastStateRaw()) {
if (!hc)
return HostUp;
switch (hc->GetLastState()) {
case StateOK: case StateOK:
case StateWarning: case StateWarning:
return HostUp; return HostUp;
@ -270,12 +188,7 @@ HostState Host::GetLastHardState(void) const
if (!IsReachable()) if (!IsReachable())
return HostUnreachable; return HostUnreachable;
Service::Ptr hc = GetCheckService(); switch (GetLastHardStateRaw()) {
if (!hc)
return HostUp;
switch (hc->GetLastHardState()) {
case StateOK: case StateOK:
case StateWarning: case StateWarning:
return HostUp; return HostUp;
@ -288,80 +201,17 @@ double Host::GetLastStateUp(void) const
{ {
ASSERT(!OwnsLock()); ASSERT(!OwnsLock());
Service::Ptr hc = GetCheckService(); if (GetLastStateOK() > GetLastStateWarning())
return GetLastStateOK();
if (!hc)
return 0;
if (hc->GetLastStateOK() > hc->GetLastStateWarning())
return hc->GetLastStateOK();
else else
return hc->GetLastStateWarning(); return GetLastStateWarning();
} }
double Host::GetLastStateDown(void) const double Host::GetLastStateDown(void) const
{ {
ASSERT(!OwnsLock()); ASSERT(!OwnsLock());
Service::Ptr hc = GetCheckService(); return GetLastStateCritical();
if (!hc)
return 0;
return hc->GetLastStateCritical();
}
double Host::GetLastStateUnreachable(void) const
{
ASSERT(!OwnsLock());
Service::Ptr hc = GetCheckService();
if (!hc)
return 0;
return hc->GetLastStateUnreachable();
}
double Host::GetLastStateChange(void) const
{
Service::Ptr hc = GetCheckService();
if (!hc)
return Application::GetStartTime();
return hc->GetLastStateChange();
}
double Host::GetLastHardStateChange(void) const
{
Service::Ptr hc = GetCheckService();
if (!hc)
return Application::GetStartTime();
return hc->GetLastHardStateChange();
}
StateType Host::GetLastStateType(void) const
{
Service::Ptr hc = GetCheckService();
if (!hc)
return StateTypeHard;
return hc->GetLastStateType();
}
StateType Host::GetStateType(void) const
{
Service::Ptr hc = GetCheckService();
if (!hc)
return StateTypeHard;
return hc->GetStateType();
} }
HostState Host::StateFromString(const String& state) HostState Host::StateFromString(const String& state)
@ -417,87 +267,78 @@ bool Host::ResolveMacro(const String& macro, const CheckResult::Ptr&, String *re
return true; return true;
} }
Service::Ptr hc = GetCheckService(); CheckResult::Ptr cr = GetLastCheckResult();
CheckResult::Ptr hccr;
if (hc) { if (macro == "HOSTSTATE") {
ServiceState state = hc->GetState(); switch (GetState()) {
bool reachable = IsReachable(); case HostUnreachable:
*result = "UNREACHABLE";
if (macro == "HOSTSTATE") { break;
HostState hstate = CalculateState(state, reachable); case HostUp:
*result = "UP";
switch (hstate) { break;
case HostUnreachable: case HostDown:
*result = "UNREACHABLE"; *result = "DOWN";
break; break;
case HostUp: default:
*result = "UP"; ASSERT(0);
break;
case HostDown:
*result = "DOWN";
break;
default:
ASSERT(0);
}
return true;
} else if (macro == "HOSTSTATEID") {
*result = Convert::ToString(state);
return true;
} else if (macro == "HOSTSTATETYPE") {
*result = Service::StateTypeToString(hc->GetStateType());
return true;
} else if (macro == "HOSTATTEMPT") {
*result = Convert::ToString(hc->GetCheckAttempt());
return true;
} else if (macro == "MAXHOSTATTEMPT") {
*result = Convert::ToString(hc->GetMaxCheckAttempts());
return true;
} else if (macro == "LASTHOSTSTATE") {
*result = StateToString(GetLastState());
return true;
} else if (macro == "LASTHOSTSTATEID") {
*result = Convert::ToString(GetLastState());
return true;
} else if (macro == "LASTHOSTSTATETYPE") {
*result = Service::StateTypeToString(GetLastStateType());
return true;
} else if (macro == "LASTHOSTSTATECHANGE") {
*result = Convert::ToString((long)hc->GetLastStateChange());
return true;
} else if (macro == "HOSTDURATIONSEC") {
*result = Convert::ToString((long)(Utility::GetTime() - hc->GetLastStateChange()));
return true;
} }
hccr = hc->GetLastCheckResult(); return true;
} else if (macro == "HOSTSTATEID") {
*result = Convert::ToString(GetState());
return true;
} else if (macro == "HOSTSTATETYPE") {
*result = StateTypeToString(GetStateType());
return true;
} else if (macro == "HOSTATTEMPT") {
*result = Convert::ToString(GetCheckAttempt());
return true;
} else if (macro == "MAXHOSTATTEMPT") {
*result = Convert::ToString(GetMaxCheckAttempts());
return true;
} else if (macro == "LASTHOSTSTATE") {
*result = StateToString(GetLastState());
return true;
} else if (macro == "LASTHOSTSTATEID") {
*result = Convert::ToString(GetLastState());
return true;
} else if (macro == "LASTHOSTSTATETYPE") {
*result = StateTypeToString(GetLastStateType());
return true;
} else if (macro == "LASTHOSTSTATECHANGE") {
*result = Convert::ToString((long)GetLastStateChange());
return true;
} else if (macro == "HOSTDURATIONSEC") {
*result = Convert::ToString((long)(Utility::GetTime() - GetLastStateChange()));
return true;
} else if (macro == "HOSTCHECKCOMMAND") {
CheckCommand::Ptr commandObj = GetCheckCommand();
if (commandObj)
*result = commandObj->GetName();
else
*result = "";
return true;
} }
if (hccr) {
if (cr) {
if (macro == "HOSTLATENCY") { if (macro == "HOSTLATENCY") {
*result = Convert::ToString(Service::CalculateLatency(hccr)); *result = Convert::ToString(Service::CalculateLatency(cr));
return true; return true;
} else if (macro == "HOSTEXECUTIONTIME") { } else if (macro == "HOSTEXECUTIONTIME") {
*result = Convert::ToString(Service::CalculateExecutionTime(hccr)); *result = Convert::ToString(Service::CalculateExecutionTime(cr));
return true; return true;
} else if (macro == "HOSTOUTPUT") { } else if (macro == "HOSTOUTPUT") {
*result = hccr->GetOutput(); *result = cr->GetOutput();
return true; return true;
} else if (macro == "HOSTPERFDATA") { } else if (macro == "HOSTPERFDATA") {
*result = PluginUtility::FormatPerfdata(hccr->GetPerformanceData()); *result = PluginUtility::FormatPerfdata(cr->GetPerformanceData());
return true;
} else if (macro == "HOSTCHECKCOMMAND") {
CheckCommand::Ptr commandObj = hc->GetCheckCommand();
if (commandObj)
*result = commandObj->GetName();
else
*result = "";
return true; return true;
} else if (macro == "LASTHOSTCHECK") { } else if (macro == "LASTHOSTCHECK") {
*result = Convert::ToString((long)hccr->GetScheduleStart()); *result = Convert::ToString((long)cr->GetScheduleStart());
return true; return true;
} }
} }
@ -509,7 +350,6 @@ bool Host::ResolveMacro(const String& macro, const CheckResult::Ptr&, String *re
return true; return true;
} }
String name = macro; String name = macro;
if (name == "HOSTADDRESS") if (name == "HOSTADDRESS")

View File

@ -46,13 +46,6 @@ enum HostState
HostUnreachable = 2 HostUnreachable = 2
}; };
enum DependencyType
{
DependencyState,
DependencyCheckExecution,
DependencyNotification
};
/** /**
* An Icinga host. * An Icinga host.
* *
@ -64,16 +57,7 @@ public:
DECLARE_PTR_TYPEDEFS(Host); DECLARE_PTR_TYPEDEFS(Host);
DECLARE_TYPENAME(Host); DECLARE_TYPENAME(Host);
shared_ptr<Service> GetCheckService(void) const; shared_ptr<Service> GetServiceByShortName(const Value& name);
std::set<Host::Ptr> GetParentHosts(void) const;
std::set<Host::Ptr> GetChildHosts(void) const;
std::set<shared_ptr<Service> > GetParentServices(void) const;
std::set<shared_ptr<Service> > GetChildServices(void) const;
bool IsReachable(DependencyType dt = DependencyState, shared_ptr<Dependency> *failedDependency = NULL) const;
shared_ptr<Service> GetServiceByShortName(const Value& name) const;
std::set<shared_ptr<Service> > GetServices(void) const; std::set<shared_ptr<Service> > GetServices(void) const;
void AddService(const shared_ptr<Service>& service); void AddService(const shared_ptr<Service>& service);
@ -84,15 +68,10 @@ public:
static HostState CalculateState(ServiceState state, bool reachable); static HostState CalculateState(ServiceState state, bool reachable);
HostState GetState(void) const; HostState GetState(void) const;
StateType GetStateType(void) const;
HostState GetLastState(void) const; HostState GetLastState(void) const;
HostState GetLastHardState(void) const; HostState GetLastHardState(void) const;
StateType GetLastStateType(void) const;
double GetLastStateChange(void) const;
double GetLastHardStateChange(void) const;
double GetLastStateUp(void) const; double GetLastStateUp(void) const;
double GetLastStateDown(void) const; double GetLastStateDown(void) const;
double GetLastStateUnreachable(void) const;
static HostState StateFromString(const String& state); static HostState StateFromString(const String& state);
static String StateToString(HostState state); static String StateToString(HostState state);

View File

@ -1,9 +1,10 @@
#include "icinga/checkable.h"
#include "base/dynamicobject.h" #include "base/dynamicobject.h"
namespace icinga namespace icinga
{ {
class Host : DynamicObject class Host : Checkable
{ {
[config] String display_name { [config] String display_name {
get {{{ get {{{
@ -14,9 +15,6 @@ class Host : DynamicObject
}}} }}}
}; };
[config] Array::Ptr groups; [config] Array::Ptr groups;
[config] String check;
[config, protected] Dictionary::Ptr services (ServiceDescriptions);
[config] Dictionary::Ptr dependencies (DependencyDescriptions);
}; };
} }

View File

@ -17,18 +17,6 @@
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
******************************************************************************/ ******************************************************************************/
%type Host {
%attribute %string "display_name",
%attribute %string "check",
%attribute %array "groups" {
%attribute %name(HostGroup) "*"
},
}
%type HostGroup {
%attribute %string "display_name"
}
%type IcingaApplication { %type IcingaApplication {
} }
@ -37,12 +25,7 @@
%attribute %number "update_interval" %attribute %number "update_interval"
} }
%type Service { %type Checkable {
%require "host",
%attribute %name(Host) "host",
%attribute %string "short_name",
%attribute %string "display_name", %attribute %string "display_name",
%require "check_command", %require "check_command",
@ -66,15 +49,34 @@
%attribute %number "volatile", %attribute %number "volatile",
%attribute %array "groups" {
%attribute %name(ServiceGroup) "*"
},
%attribute %array "authorities" { %attribute %array "authorities" {
%attribute %name(Endpoint) "*" %attribute %name(Endpoint) "*"
}, },
} }
%type Host %inherits Checkable {
%attribute %string "display_name",
%attribute %array "groups" {
%attribute %name(HostGroup) "*"
},
}
%type HostGroup {
%attribute %string "display_name"
}
%type Service %inherits Checkable {
%require "host",
%attribute %name(Host) "host",
%attribute %string "short_name",
%attribute %array "groups" {
%attribute %name(ServiceGroup) "*"
},
}
%type ServiceGroup { %type ServiceGroup {
%attribute %string "display_name" %attribute %string "display_name"
} }

View File

@ -36,7 +36,6 @@
#include "base/context.h" #include "base/context.h"
#include "base/statsfunction.h" #include "base/statsfunction.h"
#include <boost/foreach.hpp> #include <boost/foreach.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/algorithm/string/replace.hpp> #include <boost/algorithm/string/replace.hpp>
#include <fstream> #include <fstream>

View File

@ -65,22 +65,22 @@ void Notification::Start(void)
{ {
DynamicObject::Start(); DynamicObject::Start();
GetService()->AddNotification(GetSelf()); GetCheckable()->AddNotification(GetSelf());
} }
void Notification::Stop(void) void Notification::Stop(void)
{ {
DynamicObject::Stop(); DynamicObject::Stop();
GetService()->RemoveNotification(GetSelf()); GetCheckable()->RemoveNotification(GetSelf());
} }
Service::Ptr Notification::GetService(void) const Checkable::Ptr Notification::GetCheckable(void) const
{ {
Host::Ptr host = Host::GetByName(GetHostRaw()); Host::Ptr host = Host::GetByName(GetHostRaw());
if (GetServiceRaw().IsEmpty()) if (GetServiceRaw().IsEmpty())
return host->GetCheckService(); return host;
else else
return host->GetServiceByShortName(GetServiceRaw()); return host->GetServiceByShortName(GetServiceRaw());
} }
@ -195,6 +195,8 @@ void Notification::BeginExecuteNotification(NotificationType type, const CheckRe
{ {
ASSERT(!OwnsLock()); ASSERT(!OwnsLock());
Checkable::Ptr checkable = GetCheckable();
if (!force) { if (!force) {
TimePeriod::Ptr tp = GetNotificationPeriod(); TimePeriod::Ptr tp = GetNotificationPeriod();
@ -205,15 +207,14 @@ void Notification::BeginExecuteNotification(NotificationType type, const CheckRe
double now = Utility::GetTime(); double now = Utility::GetTime();
Dictionary::Ptr times = GetTimes(); Dictionary::Ptr times = GetTimes();
Service::Ptr service = GetService();
if (type == NotificationProblem) { if (type == NotificationProblem) {
if (times && times->Contains("begin") && now < service->GetLastHardStateChange() + times->Get("begin")) { if (times && times->Contains("begin") && now < checkable->GetLastHardStateChange() + times->Get("begin")) {
Log(LogInformation, "icinga", "Not sending notifications for notification object '" + GetName() + "': before escalation range"); Log(LogInformation, "icinga", "Not sending notifications for notification object '" + GetName() + "': before escalation range");
return; return;
} }
if (times && times->Contains("end") && now > service->GetLastHardStateChange() + times->Get("end")) { if (times && times->Contains("end") && now > checkable->GetLastHardStateChange() + times->Get("end")) {
Log(LogInformation, "icinga", "Not sending notifications for notification object '" + GetName() + "': after escalation range"); Log(LogInformation, "icinga", "Not sending notifications for notification object '" + GetName() + "': after escalation range");
return; return;
} }
@ -228,7 +229,20 @@ void Notification::BeginExecuteNotification(NotificationType type, const CheckRe
return; return;
} }
unsigned long fstate = 1 << GetService()->GetState(); Service::Ptr service = dynamic_pointer_cast<Service>(checkable);
Host::Ptr host;
if (service)
host = service->GetHost();
else
host = static_pointer_cast<Host>(checkable);
unsigned long fstate;
if (service)
fstate = 1 << service->GetState();
else
fstate = 1 << host->GetState();
if (!(fstate & GetNotificationStateFilter())) { if (!(fstate & GetNotificationStateFilter())) {
Log(LogInformation, "icinga", "Not sending notifications for notification object '" + GetName() + "': state filter does not match"); Log(LogInformation, "icinga", "Not sending notifications for notification object '" + GetName() + "': state filter does not match");
@ -256,7 +270,7 @@ void Notification::BeginExecuteNotification(NotificationType type, const CheckRe
std::copy(members.begin(), members.end(), std::inserter(allUsers, allUsers.begin())); std::copy(members.begin(), members.end(), std::inserter(allUsers, allUsers.begin()));
} }
Service::OnNotificationSendStart(GetSelf(), GetService(), allUsers, type, cr, author, text); Service::OnNotificationSendStart(GetSelf(), checkable, allUsers, type, cr, author, text);
std::set<User::Ptr> allNotifiedUsers; std::set<User::Ptr> allNotifiedUsers;
BOOST_FOREACH(const User::Ptr& user, allUsers) { BOOST_FOREACH(const User::Ptr& user, allUsers) {
@ -271,7 +285,7 @@ void Notification::BeginExecuteNotification(NotificationType type, const CheckRe
} }
/* used in db_ido for notification history */ /* used in db_ido for notification history */
Service::OnNotificationSentToAllUsers(GetSelf(), GetService(), allNotifiedUsers, type, cr, author, text); Service::OnNotificationSentToAllUsers(GetSelf(), checkable, allNotifiedUsers, type, cr, author, text);
} }
bool Notification::CheckNotificationUserFilters(NotificationType type, const User::Ptr& user, bool force) bool Notification::CheckNotificationUserFilters(NotificationType type, const User::Ptr& user, bool force)
@ -295,7 +309,21 @@ bool Notification::CheckNotificationUserFilters(NotificationType type, const Use
return false; return false;
} }
unsigned long fstate = 1 << GetService()->GetState(); Checkable::Ptr checkable = GetCheckable();
Service::Ptr service = dynamic_pointer_cast<Service>(checkable);
Host::Ptr host;
if (service)
host = service->GetHost();
else
host = static_pointer_cast<Host>(checkable);
unsigned long fstate;
if (service)
fstate = 1 << service->GetState();
else
fstate = 1 << host->GetState();
if (!(fstate & user->GetNotificationStateFilter())) { if (!(fstate & user->GetNotificationStateFilter())) {
Log(LogInformation, "icinga", "Not sending notifications for notification object '" + Log(LogInformation, "icinga", "Not sending notifications for notification object '" +
@ -328,13 +356,13 @@ void Notification::ExecuteNotificationHelper(NotificationType type, const User::
} }
/* required by compatlogger */ /* required by compatlogger */
Service::OnNotificationSentToUser(GetSelf(), GetService(), user, type, cr, author, text, command->GetName()); Service::OnNotificationSentToUser(GetSelf(), GetCheckable(), user, type, cr, author, text, command->GetName());
Log(LogInformation, "icinga", "Completed sending notification for service '" + GetService()->GetName() + "'"); Log(LogInformation, "icinga", "Completed sending notification for object '" + GetCheckable()->GetName() + "'");
} catch (const std::exception& ex) { } catch (const std::exception& ex) {
std::ostringstream msgbuf; std::ostringstream msgbuf;
msgbuf << "Exception occured during notification for service '" msgbuf << "Exception occured during notification for object '"
<< GetService()->GetName() << "': " << DiagnosticInformation(ex); << GetCheckable()->GetName() << "': " << DiagnosticInformation(ex);
Log(LogWarning, "icinga", msgbuf.str()); Log(LogWarning, "icinga", msgbuf.str());
} }
} }

View File

@ -49,8 +49,8 @@ enum NotificationType
NotificationFlappingEnd = 8, NotificationFlappingEnd = 8,
}; };
class Service;
class NotificationCommand; class NotificationCommand;
class Checkable;
/** /**
* An Icinga notification specification. * An Icinga notification specification.
@ -65,7 +65,7 @@ public:
static void StaticInitialize(void); static void StaticInitialize(void);
shared_ptr<Service> GetService(void) const; shared_ptr<Checkable> GetCheckable(void) const;
shared_ptr<NotificationCommand> GetNotificationCommand(void) const; shared_ptr<NotificationCommand> GetNotificationCommand(void) const;
TimePeriod::Ptr GetNotificationPeriod(void) const; TimePeriod::Ptr GetNotificationPeriod(void) const;
std::set<User::Ptr> GetUsers(void) const; std::set<User::Ptr> GetUsers(void) const;

View File

@ -59,12 +59,12 @@ void ScheduledDowntime::TimerProc(void)
} }
} }
Service::Ptr ScheduledDowntime::GetService(void) const Checkable::Ptr ScheduledDowntime::GetCheckable(void) const
{ {
Host::Ptr host = Host::GetByName(GetHostRaw()); Host::Ptr host = Host::GetByName(GetHostRaw());
if (GetServiceRaw().IsEmpty()) if (GetServiceRaw().IsEmpty())
return host->GetCheckService(); return host;
else else
return host->GetServiceByShortName(GetServiceRaw()); return host->GetServiceByShortName(GetServiceRaw());
} }
@ -110,7 +110,7 @@ std::pair<double, double> ScheduledDowntime::FindNextSegment(void)
void ScheduledDowntime::CreateNextDowntime(void) void ScheduledDowntime::CreateNextDowntime(void)
{ {
Dictionary::Ptr downtimes = GetService()->GetDowntimes(); Dictionary::Ptr downtimes = GetCheckable()->GetDowntimes();
{ {
ObjectLock dlock(downtimes); ObjectLock dlock(downtimes);
@ -138,7 +138,7 @@ void ScheduledDowntime::CreateNextDowntime(void)
return; return;
} }
GetService()->AddDowntime(GetAuthor(), GetComment(), GetCheckable()->AddDowntime(GetAuthor(), GetComment(),
segment.first, segment.second, segment.first, segment.second,
GetFixed(), String(), GetDuration(), GetName()); GetFixed(), String(), GetDuration(), GetName());
} }

View File

@ -42,7 +42,7 @@ public:
static void StaticInitialize(void); static void StaticInitialize(void);
Service::Ptr GetService(void) const; Checkable::Ptr GetCheckable(void) const;
static void RegisterApplyRuleHandler(void); static void RegisterApplyRuleHandler(void);
static void EvaluateApplyRules(const std::vector<ApplyRule>& rules); static void EvaluateApplyRules(const std::vector<ApplyRule>& rules);

View File

@ -37,25 +37,8 @@ using namespace icinga;
REGISTER_TYPE(Service); REGISTER_TYPE(Service);
boost::signals2::signal<void (const Service::Ptr&, const String&, const String&, AcknowledgementType, double, const String&)> Service::OnAcknowledgementSet;
boost::signals2::signal<void (const Service::Ptr&, const String&)> Service::OnAcknowledgementCleared;
INITIALIZE_ONCE(&Service::StartDowntimesExpiredTimer); INITIALIZE_ONCE(&Service::StartDowntimesExpiredTimer);
Service::Service(void)
: m_CheckRunning(false)
{ }
void Service::Start(void)
{
double now = Utility::GetTime();
if (GetNextCheck() < now + 300)
UpdateNextCheck();
DynamicObject::Start();
}
void Service::OnConfigLoaded(void) void Service::OnConfigLoaded(void)
{ {
Array::Ptr groups = GetGroups(); Array::Ptr groups = GetGroups();
@ -77,31 +60,8 @@ void Service::OnConfigLoaded(void)
m_Host->AddService(GetSelf()); m_Host->AddService(GetSelf());
SetSchedulingOffset(Utility::Random()); SetSchedulingOffset(Utility::Random());
}
void Service::OnStateLoaded(void) Checkable::OnConfigLoaded();
{
AddDowntimesToCache();
AddCommentsToCache();
std::vector<String> ids;
Dictionary::Ptr downtimes = GetDowntimes();
{
ObjectLock dlock(downtimes);
BOOST_FOREACH(const Dictionary::Pair& kv, downtimes) {
Downtime::Ptr downtime = kv.second;
if (downtime->GetScheduledBy().IsEmpty())
continue;
ids.push_back(kv.first);
}
}
BOOST_FOREACH(const String& id, ids) {
RemoveDowntime(id, true);
}
} }
Service::Ptr Service::GetByNamePair(const String& hostName, const String& serviceName) Service::Ptr Service::GetByNamePair(const String& hostName, const String& serviceName)
@ -123,161 +83,47 @@ Host::Ptr Service::GetHost(void) const
return m_Host; return m_Host;
} }
bool Service::IsHostCheck(void) const ServiceState Service::StateFromString(const String& state)
{ {
ASSERT(!OwnsLock()); if (state == "OK")
return StateOK;
Service::Ptr hc = GetHost()->GetCheckService(); else if (state == "WARNING")
return StateWarning;
if (!hc) else if (state == "CRITICAL")
return false; return StateCritical;
return (hc->GetName() == GetName());
}
AcknowledgementType Service::GetAcknowledgement(void)
{
ASSERT(OwnsLock());
AcknowledgementType avalue = static_cast<AcknowledgementType>(GetAcknowledgementRaw());
if (avalue != AcknowledgementNone) {
double expiry = GetAcknowledgementExpiry();
if (expiry != 0 && expiry < Utility::GetTime()) {
avalue = AcknowledgementNone;
ClearAcknowledgement();
}
}
return avalue;
}
bool Service::IsAcknowledged(void)
{
return GetAcknowledgement() != AcknowledgementNone;
}
void Service::AcknowledgeProblem(const String& author, const String& comment, AcknowledgementType type, double expiry, const String& authority)
{
{
ObjectLock olock(this);
SetAcknowledgementRaw(type);
SetAcknowledgementExpiry(expiry);
}
OnNotificationsRequested(GetSelf(), NotificationAcknowledgement, GetLastCheckResult(), author, comment);
OnAcknowledgementSet(GetSelf(), author, comment, type, expiry, authority);
}
void Service::ClearAcknowledgement(const String& authority)
{
ASSERT(OwnsLock());
SetAcknowledgementRaw(AcknowledgementNone);
SetAcknowledgementExpiry(0);
OnAcknowledgementCleared(GetSelf(), authority);
}
bool Service::GetEnablePerfdata(void) const
{
if (!GetOverrideEnablePerfdata().IsEmpty())
return GetOverrideEnablePerfdata();
else else
return GetEnablePerfdataRaw(); return StateUnknown;
} }
void Service::SetEnablePerfdata(bool enabled, const String& authority) String Service::StateToString(ServiceState state)
{ {
SetOverrideEnablePerfdata(enabled); switch (state) {
case StateOK:
return "OK";
case StateWarning:
return "WARNING";
case StateCritical:
return "CRITICAL";
case StateUnknown:
default:
return "UNKNOWN";
}
} }
int Service::GetModifiedAttributes(void) const StateType Service::StateTypeFromString(const String& type)
{ {
int attrs = 0; if (type == "SOFT")
return StateTypeSoft;
if (!GetOverrideEnableNotifications().IsEmpty()) else
attrs |= ModAttrNotificationsEnabled; return StateTypeHard;
if (!GetOverrideEnableActiveChecks().IsEmpty())
attrs |= ModAttrActiveChecksEnabled;
if (!GetOverrideEnablePassiveChecks().IsEmpty())
attrs |= ModAttrPassiveChecksEnabled;
if (!GetOverrideEnableFlapping().IsEmpty())
attrs |= ModAttrFlapDetectionEnabled;
if (!GetOverrideEnableEventHandler().IsEmpty())
attrs |= ModAttrEventHandlerEnabled;
if (!GetOverrideEnablePerfdata().IsEmpty())
attrs |= ModAttrPerformanceDataEnabled;
if (!GetOverrideCheckInterval().IsEmpty())
attrs |= ModAttrNormalCheckInterval;
if (!GetOverrideRetryInterval().IsEmpty())
attrs |= ModAttrRetryCheckInterval;
if (!GetOverrideEventCommand().IsEmpty())
attrs |= ModAttrEventHandlerCommand;
if (!GetOverrideCheckCommand().IsEmpty())
attrs |= ModAttrCheckCommand;
if (!GetOverrideMaxCheckAttempts().IsEmpty())
attrs |= ModAttrMaxCheckAttempts;
if (!GetOverrideCheckPeriod().IsEmpty())
attrs |= ModAttrCheckTimeperiod;
// TODO: finish
return attrs;
} }
void Service::SetModifiedAttributes(int flags) String Service::StateTypeToString(StateType type)
{ {
if ((flags & ModAttrNotificationsEnabled) == 0) if (type == StateTypeSoft)
SetOverrideEnableNotifications(Empty); return "SOFT";
else
if ((flags & ModAttrActiveChecksEnabled) == 0) return "HARD";
SetOverrideEnableActiveChecks(Empty);
if ((flags & ModAttrPassiveChecksEnabled) == 0)
SetOverrideEnablePassiveChecks(Empty);
if ((flags & ModAttrFlapDetectionEnabled) == 0)
SetOverrideEnableFlapping(Empty);
if ((flags & ModAttrEventHandlerEnabled) == 0)
SetOverrideEnableEventHandler(Empty);
if ((flags & ModAttrPerformanceDataEnabled) == 0)
SetOverrideEnablePerfdata(Empty);
if ((flags & ModAttrNormalCheckInterval) == 0)
SetOverrideCheckInterval(Empty);
if ((flags & ModAttrRetryCheckInterval) == 0)
SetOverrideRetryInterval(Empty);
if ((flags & ModAttrEventHandlerCommand) == 0)
SetOverrideEventCommand(Empty);
if ((flags & ModAttrCheckCommand) == 0)
SetOverrideCheckCommand(Empty);
if ((flags & ModAttrMaxCheckAttempts) == 0)
SetOverrideMaxCheckAttempts(Empty);
if ((flags & ModAttrCheckTimeperiod) == 0)
SetOverrideCheckPeriod(Empty);
} }
bool Service::ResolveMacro(const String& macro, const CheckResult::Ptr& cr, String *result) const bool Service::ResolveMacro(const String& macro, const CheckResult::Ptr& cr, String *result) const
@ -388,3 +234,14 @@ bool Service::ResolveMacro(const String& macro, const CheckResult::Ptr& cr, Stri
return false; return false;
} }
boost::tuple<Host::Ptr, Service::Ptr> icinga::GetHostService(const Checkable::Ptr& checkable)
{
Service::Ptr service = dynamic_pointer_cast<Service>(checkable);
if (service)
return boost::make_tuple(service->GetHost(), service);
else
return boost::make_tuple(static_pointer_cast<Host>(checkable), Service::Ptr());
}

View File

@ -36,48 +36,6 @@
namespace icinga namespace icinga
{ {
/**
* The state of service flapping.
*
* @ingroup icinga
*/
enum FlappingState
{
FlappingStarted = 0,
FlappingDisabled = 1,
FlappingStopped = 2,
FlappingEnabled = 3
};
/**
* Modified attributes.
*
* @ingroup icinga
*/
enum ModifiedAttributeType
{
ModAttrNotificationsEnabled = 1,
ModAttrActiveChecksEnabled = 2,
ModAttrPassiveChecksEnabled = 4,
ModAttrEventHandlerEnabled = 8,
ModAttrFlapDetectionEnabled = 16,
ModAttrFailurePredictionEnabled = 32,
ModAttrPerformanceDataEnabled = 64,
ModAttrObsessiveHandlerEnabled = 128,
ModAttrEventHandlerCommand = 256,
ModAttrCheckCommand = 512,
ModAttrNormalCheckInterval = 1024,
ModAttrRetryCheckInterval = 2048,
ModAttrMaxCheckAttempts = 4096,
ModAttrFreshnessChecksEnabled = 8192,
ModAttrCheckTimeperiod = 16384,
ModAttrCustomVariable = 32768,
ModAttrNotificationTimeperiod = 65536
};
class CheckCommand;
class EventCommand;
/** /**
* An Icinga service. * An Icinga service.
* *
@ -89,72 +47,11 @@ public:
DECLARE_PTR_TYPEDEFS(Service); DECLARE_PTR_TYPEDEFS(Service);
DECLARE_TYPENAME(Service); DECLARE_TYPENAME(Service);
Service(void);
static Service::Ptr GetByNamePair(const String& hostName, const String& serviceName); static Service::Ptr GetByNamePair(const String& hostName, const String& serviceName);
Host::Ptr GetHost(void) const; Host::Ptr GetHost(void) const;
std::set<Host::Ptr> GetParentHosts(void) const; virtual bool ResolveMacro(const String& macro, const CheckResult::Ptr& cr, String *result) const;
std::set<Host::Ptr> GetChildHosts(void) const;
std::set<Service::Ptr> GetParentServices(void) const;
std::set<Service::Ptr> GetChildServices(void) const;
bool IsHostCheck(void) const;
bool IsReachable(DependencyType dt = DependencyState, shared_ptr<Dependency> *failedDependency = NULL, int rstack = 0) const;
AcknowledgementType GetAcknowledgement(void);
void AcknowledgeProblem(const String& author, const String& comment, AcknowledgementType type, double expiry = 0, const String& authority = String());
void ClearAcknowledgement(const String& authority = String());
/* Checks */
shared_ptr<CheckCommand> GetCheckCommand(void) const;
void SetCheckCommand(const shared_ptr<CheckCommand>& command);
TimePeriod::Ptr GetCheckPeriod(void) const;
void SetCheckPeriod(const TimePeriod::Ptr& tp);
double GetCheckInterval(void) const;
void SetCheckInterval(double interval);
double GetRetryInterval(void) const;
void SetRetryInterval(double interval);
int GetMaxCheckAttempts(void) const;
void SetMaxCheckAttempts(int attempts);
long GetSchedulingOffset(void);
void SetSchedulingOffset(long offset);
void SetNextCheck(double nextCheck, const String& authority = String());
double GetNextCheck(void);
void UpdateNextCheck(void);
bool HasBeenChecked(void) const;
double GetLastCheck(void) const;
bool GetEnableActiveChecks(void) const;
void SetEnableActiveChecks(bool enabled, const String& authority = String());
bool GetEnablePassiveChecks(void) const;
void SetEnablePassiveChecks(bool enabled, const String& authority = String());
bool GetForceNextCheck(void) const;
void SetForceNextCheck(bool forced, const String& authority = String());
static void UpdateStatistics(const CheckResult::Ptr& cr);
void ExecuteCheck(void);
void ProcessCheckResult(const CheckResult::Ptr& cr, const String& authority = String());
int GetModifiedAttributes(void) const;
void SetModifiedAttributes(int flags);
static double CalculateExecutionTime(const CheckResult::Ptr& cr);
static double CalculateLatency(const CheckResult::Ptr& cr);
static ServiceState StateFromString(const String& state); static ServiceState StateFromString(const String& state);
static String StateToString(ServiceState state); static String StateToString(ServiceState state);
@ -162,158 +59,18 @@ public:
static StateType StateTypeFromString(const String& state); static StateType StateTypeFromString(const String& state);
static String StateTypeToString(StateType state); static String StateTypeToString(StateType state);
static boost::signals2::signal<void (const Service::Ptr&, double, const String&)> OnNextCheckChanged;
static boost::signals2::signal<void (const Service::Ptr&, bool, const String&)> OnForceNextCheckChanged;
static boost::signals2::signal<void (const Service::Ptr&, bool, const String&)> OnForceNextNotificationChanged;
static boost::signals2::signal<void (const Service::Ptr&, bool, const String&)> OnEnableActiveChecksChanged;
static boost::signals2::signal<void (const Service::Ptr&, bool, const String&)> OnEnablePassiveChecksChanged;
static boost::signals2::signal<void (const Service::Ptr&, bool, const String&)> OnEnableNotificationsChanged;
static boost::signals2::signal<void (const Service::Ptr&, bool, const String&)> OnEnableFlappingChanged;
static boost::signals2::signal<void (const Service::Ptr&, const CheckResult::Ptr&, const String&)> OnNewCheckResult;
static boost::signals2::signal<void (const Service::Ptr&, const CheckResult::Ptr&, StateType, const String&)> OnStateChange;
static boost::signals2::signal<void (const Service::Ptr&, NotificationType, const CheckResult::Ptr&,
const String&, const String&)> OnNotificationsRequested;
static boost::signals2::signal<void (const Notification::Ptr&, const Service::Ptr&, const std::set<User::Ptr>&,
const NotificationType&, const CheckResult::Ptr&, const String&,
const String&)> OnNotificationSendStart;
static boost::signals2::signal<void (const Notification::Ptr&, const Service::Ptr&, const User::Ptr&,
const NotificationType&, const CheckResult::Ptr&, const String&,
const String&, const String&)> OnNotificationSentToUser;
static boost::signals2::signal<void (const Notification::Ptr&, const Service::Ptr&, const std::set<User::Ptr>&,
const NotificationType&, const CheckResult::Ptr&, const String&,
const String&)> OnNotificationSentToAllUsers;
static boost::signals2::signal<void (const Service::Ptr&, const Comment::Ptr&, const String&)> OnCommentAdded;
static boost::signals2::signal<void (const Service::Ptr&, const Comment::Ptr&, const String&)> OnCommentRemoved;
static boost::signals2::signal<void (const Service::Ptr&, const Downtime::Ptr&, const String&)> OnDowntimeAdded;
static boost::signals2::signal<void (const Service::Ptr&, const Downtime::Ptr&, const String&)> OnDowntimeRemoved;
static boost::signals2::signal<void (const Service::Ptr&, FlappingState)> OnFlappingChanged;
static boost::signals2::signal<void (const Service::Ptr&, const Downtime::Ptr&)> OnDowntimeTriggered;
static boost::signals2::signal<void (const Service::Ptr&, const String&, const String&, AcknowledgementType,
double, const String&)> OnAcknowledgementSet;
static boost::signals2::signal<void (const Service::Ptr&, const String&)> OnAcknowledgementCleared;
static boost::signals2::signal<void (const Service::Ptr&)> OnEventCommandExecuted;
virtual bool ResolveMacro(const String& macro, const CheckResult::Ptr& cr, String *result) const;
/* Downtimes */
static int GetNextDowntimeID(void);
int GetDowntimeDepth(void) const;
String AddDowntime(const String& author, const String& comment,
double startTime, double endTime, bool fixed,
const String& triggeredBy, double duration,
const String& scheduledBy = String(), const String& id = String(),
const String& authority = String());
static void RemoveDowntime(const String& id, bool cancelled, const String& = String());
void TriggerDowntimes(void);
static void TriggerDowntime(const String& id);
static String GetDowntimeIDFromLegacyID(int id);
static Service::Ptr GetOwnerByDowntimeID(const String& id);
static Downtime::Ptr GetDowntimeByID(const String& id);
static void StartDowntimesExpiredTimer(void);
bool IsInDowntime(void) const;
bool IsAcknowledged(void);
/* Comments */
static int GetNextCommentID(void);
String AddComment(CommentType entryType, const String& author,
const String& text, double expireTime, const String& id = String(), const String& authority = String());
void RemoveAllComments(void);
void RemoveCommentsByType(int type);
static void RemoveComment(const String& id, const String& authority = String());
static String GetCommentIDFromLegacyID(int id);
static Service::Ptr GetOwnerByCommentID(const String& id);
static Comment::Ptr GetCommentByID(const String& id);
/* Notifications */
bool GetEnableNotifications(void) const;
void SetEnableNotifications(bool enabled, const String& authority = String());
void SendNotifications(NotificationType type, const CheckResult::Ptr& cr, const String& author = "", const String& text = "");
std::set<Notification::Ptr> GetNotifications(void) const;
void AddNotification(const Notification::Ptr& notification);
void RemoveNotification(const Notification::Ptr& notification);
void SetForceNextNotification(bool force, const String& authority = String());
bool GetForceNextNotification(void) const;
void ResetNotificationNumbers(void);
/* Event Handler */
void ExecuteEventHandler(void);
shared_ptr<EventCommand> GetEventCommand(void) const;
void SetEventCommand(const shared_ptr<EventCommand>& command);
bool GetEnableEventHandler(void) const;
void SetEnableEventHandler(bool enabled);
/* Flapping Detection */
double GetFlappingCurrent(void) const;
bool GetEnableFlapping(void) const;
void SetEnableFlapping(bool enabled, const String& authority = String());
bool IsFlapping(void) const;
void UpdateFlappingStatus(bool stateChange);
/* Performance data */
bool GetEnablePerfdata(void) const;
void SetEnablePerfdata(bool enabled, const String& authority = String());
/* Dependencies */
void AddDependency(const shared_ptr<Dependency>& dep);
void RemoveDependency(const shared_ptr<Dependency>& dep);
std::set<shared_ptr<Dependency> > GetDependencies(void) const;
void AddReverseDependency(const shared_ptr<Dependency>& dep);
void RemoveReverseDependency(const shared_ptr<Dependency>& dep);
std::set<shared_ptr<Dependency> > GetReverseDependencies(void) const;
static void RegisterApplyRuleHandler(void); static void RegisterApplyRuleHandler(void);
static void EvaluateApplyRules(const std::vector<ApplyRule>& rules); static void EvaluateApplyRules(const std::vector<ApplyRule>& rules);
protected: protected:
virtual void Start(void);
virtual void OnConfigLoaded(void); virtual void OnConfigLoaded(void);
virtual void OnStateLoaded(void);
private: private:
Host::Ptr m_Host; Host::Ptr m_Host;
bool m_CheckRunning;
long m_SchedulingOffset;
/* Downtimes */
static void DowntimesExpireTimerHandler(void);
void RemoveExpiredDowntimes(void);
void AddDowntimesToCache(void);
/* Comments */
static void CommentsExpireTimerHandler(void);
void RemoveExpiredComments(void);
void AddCommentsToCache(void);
/* Notifications */
std::set<Notification::Ptr> m_Notifications;
/* Dependencies */
mutable boost::mutex m_DependencyMutex;
std::set<shared_ptr<Dependency> > m_Dependencies;
std::set<shared_ptr<Dependency> > m_ReverseDependencies;
}; };
I2_ICINGA_API boost::tuple<Host::Ptr, Service::Ptr> GetHostService(const Checkable::Ptr& checkable);
} }
#endif /* SERVICE_H */ #endif /* SERVICE_H */

View File

@ -1,3 +1,4 @@
#include "icinga/checkable.h"
#include "icinga/host.h" #include "icinga/host.h"
#include "icinga/icingaapplication.h" #include "icinga/icingaapplication.h"
#include "base/dynamicobject.h" #include "base/dynamicobject.h"
@ -5,21 +6,7 @@
namespace icinga namespace icinga
{ {
code {{{ class Service : Checkable
/**
* The acknowledgement type of a service.
*
* @ingroup icinga
*/
enum AcknowledgementType
{
AcknowledgementNone = 0,
AcknowledgementNormal = 1,
AcknowledgementSticky = 2
};
}}}
class Service : DynamicObject
{ {
[config] String display_name { [config] String display_name {
get {{{ get {{{
@ -29,20 +16,6 @@ class Service : DynamicObject
return m_DisplayName; return m_DisplayName;
}}} }}}
}; };
[config] Array::Ptr groups;
[config, protected] String check_command (CheckCommandRaw);
[config] int max_check_attempts (MaxCheckAttemptsRaw) {
default {{{ return 3; }}}
};
[config, protected] String check_period (CheckPeriodRaw);
[config] double check_interval (CheckIntervalRaw) {
default {{{ return 5 * 60; }}}
};
[config] double retry_interval (RetryIntervalRaw) {
default {{{ return 60; }}}
};
[config] String event_command (EventCommandRaw);
[config] bool volatile;
[config] String short_name { [config] String short_name {
get {{{ get {{{
if (m_ShortName.IsEmpty()) if (m_ShortName.IsEmpty())
@ -52,93 +25,21 @@ class Service : DynamicObject
}}} }}}
}; };
[config] String host (HostRaw); [config] String host (HostRaw);
[config] double flapping_threshold { [enum] ServiceState "state" {
default {{{ return 30; }}} get {{{
return GetStateRaw();
}}}
}; };
[config] Dictionary::Ptr notifications (NotificationDescriptions); [enum] ServiceState last_state {
[config] Dictionary::Ptr scheduled_downtimes (ScheduledDowntimeDescriptions); get {{{
[config] Dictionary::Ptr dependencies (DependencyDescriptions); return GetLastStateRaw();
[config] bool enable_active_checks (EnableActiveChecksRaw) { }}}
default {{{ return true; }}}
}; };
[config] bool enable_passive_checks (EnablePassiveChecksRaw) { [enum] ServiceState last_hard_state {
default {{{ return true; }}} get {{{
return GetLastHardStateRaw();
}}}
}; };
[config] bool enable_event_handler (EnableEventHandlerRaw) {
default {{{ return true; }}}
};
[config] bool enable_notifications (EnableNotificationsRaw) {
default {{{ return true; }}}
};
[config] bool enable_flapping (EnableFlappingRaw) {
default {{{ return true; }}}
};
[config] bool enable_perfdata (EnablePerfdataRaw) {
default {{{ return true; }}}
};
[state] double next_check (NextCheckRaw);
[state] int check_attempt {
default {{{ return 1; }}}
};
[state, enum] ServiceState "state" {
default {{{ return StateUnknown; }}}
};
[state, enum] StateType state_type {
default {{{ return StateTypeSoft; }}}
};
[state, enum] ServiceState last_state {
default {{{ return StateUnknown; }}}
};
[state, enum] ServiceState last_hard_state {
default {{{ return StateUnknown; }}}
};
[state, enum] StateType last_state_type {
default {{{ return StateTypeSoft; }}}
};
[state] bool last_reachable {
default {{{ return true; }}}
};
[state] CheckResult::Ptr last_check_result;
[state] double last_state_change {
default {{{ return Application::GetStartTime(); }}}
};
[state] double last_hard_state_change {
default {{{ return Application::GetStartTime(); }}}
};
[state] double last_state_ok (LastStateOK);
[state] double last_state_warning;
[state] double last_state_critical;
[state] double last_state_unknown;
[state] double last_state_unreachable;
[state] bool last_in_downtime;
[state] bool force_next_check (ForceNextCheckRaw);
[state] int acknowledgement (AcknowledgementRaw) {
default {{{ return AcknowledgementNone; }}}
};
[state] double acknowledgement_expiry;
[state] Dictionary::Ptr comments {
default {{{ return make_shared<Dictionary>(); }}}
};
[state] Dictionary::Ptr downtimes {
default {{{ return make_shared<Dictionary>(); }}}
};
[state] bool force_next_notification (ForceNextNotificationRaw);
[state] int flapping_positive;
[state] int flapping_negative;
[state] double flapping_last_change;
[state] Value override_enable_notifications;
[state] Value override_enable_active_checks;
[state] Value override_enable_passive_checks;
[state] Value override_enable_flapping;
[state] Value override_enable_perfdata;
[state] Value override_check_interval;
[state] Value override_retry_interval;
[state] Value override_enable_event_handler;
[state] Value override_event_command;
[state] Value override_check_command;
[state] Value override_max_check_attempts;
[state] Value override_check_period;
}; };
} }

View File

@ -31,7 +31,7 @@ using namespace icinga;
REGISTER_SCRIPTFUNCTION(IcingaCheck, &IcingaCheckTask::ScriptFunc); REGISTER_SCRIPTFUNCTION(IcingaCheck, &IcingaCheckTask::ScriptFunc);
void IcingaCheckTask::ScriptFunc(const Service::Ptr& service, const CheckResult::Ptr& cr) void IcingaCheckTask::ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr)
{ {
double interval = Utility::GetTime() - Application::GetStartTime(); double interval = Utility::GetTime() - Application::GetStartTime();

View File

@ -34,7 +34,7 @@ namespace icinga
class I2_METHODS_API IcingaCheckTask class I2_METHODS_API IcingaCheckTask
{ {
public: public:
static void ScriptFunc(const Service::Ptr& service, const CheckResult::Ptr& cr); static void ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr);
private: private:
IcingaCheckTask(void); IcingaCheckTask(void);

View File

@ -30,7 +30,7 @@ using namespace icinga;
REGISTER_SCRIPTFUNCTION(NullCheck, &NullCheckTask::ScriptFunc); REGISTER_SCRIPTFUNCTION(NullCheck, &NullCheckTask::ScriptFunc);
void NullCheckTask::ScriptFunc(const Service::Ptr& service, const CheckResult::Ptr& cr) void NullCheckTask::ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr)
{ {
String output = "Hello from "; String output = "Hello from ";
output += Utility::GetHostName(); output += Utility::GetHostName();

View File

@ -35,7 +35,7 @@ namespace icinga
class I2_METHODS_API NullCheckTask class I2_METHODS_API NullCheckTask
{ {
public: public:
static void ScriptFunc(const Service::Ptr& service, const CheckResult::Ptr& cr); static void ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr);
private: private:
NullCheckTask(void); NullCheckTask(void);

View File

@ -25,5 +25,5 @@ using namespace icinga;
REGISTER_SCRIPTFUNCTION(NullEvent, &NullEventTask::ScriptFunc); REGISTER_SCRIPTFUNCTION(NullEvent, &NullEventTask::ScriptFunc);
void NullEventTask::ScriptFunc(const Service::Ptr&) void NullEventTask::ScriptFunc(const Checkable::Ptr&)
{ } { }

View File

@ -35,7 +35,7 @@ namespace icinga
class I2_METHODS_API NullEventTask class I2_METHODS_API NullEventTask
{ {
public: public:
static void ScriptFunc(const Service::Ptr& service); static void ScriptFunc(const Checkable::Ptr& service);
private: private:
NullEventTask(void); NullEventTask(void);

View File

@ -35,18 +35,29 @@ using namespace icinga;
REGISTER_SCRIPTFUNCTION(PluginCheck, &PluginCheckTask::ScriptFunc); REGISTER_SCRIPTFUNCTION(PluginCheck, &PluginCheckTask::ScriptFunc);
void PluginCheckTask::ScriptFunc(const Service::Ptr& service, const CheckResult::Ptr& cr) void PluginCheckTask::ScriptFunc(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr)
{ {
CheckCommand::Ptr commandObj = service->GetCheckCommand(); CheckCommand::Ptr commandObj = checkable->GetCheckCommand();
Value raw_command = commandObj->GetCommandLine(); Value raw_command = commandObj->GetCommandLine();
bool is_service = checkable->GetType() == DynamicType::GetByName("Service");
Host::Ptr host;
Service::Ptr service;
if (is_service) {
service = static_pointer_cast<Service>(checkable);
host = service->GetHost();
} else
host = static_pointer_cast<Host>(checkable);
std::vector<MacroResolver::Ptr> resolvers; std::vector<MacroResolver::Ptr> resolvers;
resolvers.push_back(service); if (is_service)
resolvers.push_back(service->GetHost()); resolvers.push_back(service);
resolvers.push_back(host);
resolvers.push_back(commandObj); resolvers.push_back(commandObj);
resolvers.push_back(IcingaApplication::GetInstance()); resolvers.push_back(IcingaApplication::GetInstance());
Value command = MacroProcessor::ResolveMacros(raw_command, resolvers, service->GetLastCheckResult(), Utility::EscapeShellCmd, commandObj->GetEscapeMacros()); Value command = MacroProcessor::ResolveMacros(raw_command, resolvers, checkable->GetLastCheckResult(), Utility::EscapeShellCmd, commandObj->GetEscapeMacros());
Dictionary::Ptr envMacros = make_shared<Dictionary>(); Dictionary::Ptr envMacros = make_shared<Dictionary>();
@ -56,7 +67,7 @@ void PluginCheckTask::ScriptFunc(const Service::Ptr& service, const CheckResult:
BOOST_FOREACH(const String& macro, export_macros) { BOOST_FOREACH(const String& macro, export_macros) {
String value; String value;
if (!MacroProcessor::ResolveMacro(macro, resolvers, service->GetLastCheckResult(), &value)) { if (!MacroProcessor::ResolveMacro(macro, resolvers, checkable->GetLastCheckResult(), &value)) {
Log(LogWarning, "icinga", "export_macros for service '" + service->GetName() + "' refers to unknown macro '" + macro + "'"); Log(LogWarning, "icinga", "export_macros for service '" + service->GetName() + "' refers to unknown macro '" + macro + "'");
continue; continue;
} }
@ -71,11 +82,11 @@ void PluginCheckTask::ScriptFunc(const Service::Ptr& service, const CheckResult:
process->SetTimeout(commandObj->GetTimeout()); process->SetTimeout(commandObj->GetTimeout());
process->Run(boost::bind(&PluginCheckTask::ProcessFinishedHandler, service, cr, _1)); process->Run(boost::bind(&PluginCheckTask::ProcessFinishedHandler, checkable, cr, _1));
} }
void PluginCheckTask::ProcessFinishedHandler(const Service::Ptr& service, const CheckResult::Ptr& cr, const ProcessResult& pr) void PluginCheckTask::ProcessFinishedHandler(const Checkable::Ptr& checkable, const CheckResult::Ptr& cr, const ProcessResult& pr)
{ {
String output = pr.Output; String output = pr.Output;
output.Trim(); output.Trim();
@ -87,5 +98,5 @@ void PluginCheckTask::ProcessFinishedHandler(const Service::Ptr& service, const
cr->SetExecutionStart(pr.ExecutionStart); cr->SetExecutionStart(pr.ExecutionStart);
cr->SetExecutionEnd(pr.ExecutionEnd); cr->SetExecutionEnd(pr.ExecutionEnd);
service->ProcessCheckResult(cr); checkable->ProcessCheckResult(cr);
} }

View File

@ -35,12 +35,12 @@ namespace icinga
class I2_METHODS_API PluginCheckTask class I2_METHODS_API PluginCheckTask
{ {
public: public:
static void ScriptFunc(const Service::Ptr& service, const CheckResult::Ptr& cr); static void ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr);
private: private:
PluginCheckTask(void); PluginCheckTask(void);
static void ProcessFinishedHandler(const Service::Ptr& service, const CheckResult::Ptr& cr, const ProcessResult& pr); static void ProcessFinishedHandler(const Checkable::Ptr& service, const CheckResult::Ptr& cr, const ProcessResult& pr);
}; };

View File

@ -32,18 +32,29 @@ using namespace icinga;
REGISTER_SCRIPTFUNCTION(PluginEvent, &PluginEventTask::ScriptFunc); REGISTER_SCRIPTFUNCTION(PluginEvent, &PluginEventTask::ScriptFunc);
void PluginEventTask::ScriptFunc(const Service::Ptr& service) void PluginEventTask::ScriptFunc(const Checkable::Ptr& checkable)
{ {
EventCommand::Ptr commandObj = service->GetEventCommand(); EventCommand::Ptr commandObj = checkable->GetEventCommand();
Value raw_command = commandObj->GetCommandLine(); Value raw_command = commandObj->GetCommandLine();
bool is_service = checkable->GetType() == DynamicType::GetByName("Service");
Host::Ptr host;
Service::Ptr service;
if (is_service) {
service = static_pointer_cast<Service>(checkable);
host = service->GetHost();
} else
host = static_pointer_cast<Host>(checkable);
std::vector<MacroResolver::Ptr> resolvers; std::vector<MacroResolver::Ptr> resolvers;
resolvers.push_back(service); if (is_service)
resolvers.push_back(service->GetHost()); resolvers.push_back(service);
resolvers.push_back(host);
resolvers.push_back(commandObj); resolvers.push_back(commandObj);
resolvers.push_back(IcingaApplication::GetInstance()); resolvers.push_back(IcingaApplication::GetInstance());
Value command = MacroProcessor::ResolveMacros(raw_command, resolvers, service->GetLastCheckResult(), Utility::EscapeShellCmd, commandObj->GetEscapeMacros()); Value command = MacroProcessor::ResolveMacros(raw_command, resolvers, checkable->GetLastCheckResult(), Utility::EscapeShellCmd, commandObj->GetEscapeMacros());
Dictionary::Ptr envMacros = make_shared<Dictionary>(); Dictionary::Ptr envMacros = make_shared<Dictionary>();
@ -53,7 +64,7 @@ void PluginEventTask::ScriptFunc(const Service::Ptr& service)
BOOST_FOREACH(const String& macro, export_macros) { BOOST_FOREACH(const String& macro, export_macros) {
String value; String value;
if (!MacroProcessor::ResolveMacro(macro, resolvers, service->GetLastCheckResult(), &value)) { if (!MacroProcessor::ResolveMacro(macro, resolvers, checkable->GetLastCheckResult(), &value)) {
Log(LogWarning, "icinga", "export_macros for command '" + commandObj->GetName() + "' refers to unknown macro '" + macro + "'"); Log(LogWarning, "icinga", "export_macros for command '" + commandObj->GetName() + "' refers to unknown macro '" + macro + "'");
continue; continue;
} }

View File

@ -34,7 +34,7 @@ namespace icinga
class I2_METHODS_API PluginEventTask class I2_METHODS_API PluginEventTask
{ {
public: public:
static void ScriptFunc(const Service::Ptr& service); static void ScriptFunc(const Checkable::Ptr& service);
private: private:
PluginEventTask(void); PluginEventTask(void);

View File

@ -40,7 +40,7 @@ void PluginNotificationTask::ScriptFunc(const Notification::Ptr& notification, c
NotificationType type = static_cast<NotificationType>(itype); NotificationType type = static_cast<NotificationType>(itype);
Service::Ptr service = notification->GetService(); Checkable::Ptr checkable = notification->GetCheckable();
Value raw_command = commandObj->GetCommandLine(); Value raw_command = commandObj->GetCommandLine();
@ -50,12 +50,17 @@ void PluginNotificationTask::ScriptFunc(const Notification::Ptr& notification, c
notificationMacroResolver->Add("NOTIFICATIONAUTHORNAME", author); notificationMacroResolver->Add("NOTIFICATIONAUTHORNAME", author);
notificationMacroResolver->Add("NOTIFICATIONCOMMENT", comment); notificationMacroResolver->Add("NOTIFICATIONCOMMENT", comment);
Host::Ptr host;
Service::Ptr service;
tie(host, service) = GetHostService(checkable);
std::vector<MacroResolver::Ptr> resolvers; std::vector<MacroResolver::Ptr> resolvers;
resolvers.push_back(user); resolvers.push_back(user);
resolvers.push_back(notificationMacroResolver); resolvers.push_back(notificationMacroResolver);
resolvers.push_back(notification); resolvers.push_back(notification);
resolvers.push_back(service); if (service)
resolvers.push_back(service->GetHost()); resolvers.push_back(service);
resolvers.push_back(host);;
resolvers.push_back(commandObj); resolvers.push_back(commandObj);
resolvers.push_back(IcingaApplication::GetInstance()); resolvers.push_back(IcingaApplication::GetInstance());
@ -82,16 +87,16 @@ void PluginNotificationTask::ScriptFunc(const Notification::Ptr& notification, c
process->SetTimeout(commandObj->GetTimeout()); process->SetTimeout(commandObj->GetTimeout());
process->Run(boost::bind(&PluginNotificationTask::ProcessFinishedHandler, service, command, _1)); process->Run(boost::bind(&PluginNotificationTask::ProcessFinishedHandler, checkable, command, _1));
} }
void PluginNotificationTask::ProcessFinishedHandler(const Service::Ptr& service, const Value& command, const ProcessResult& pr) void PluginNotificationTask::ProcessFinishedHandler(const Checkable::Ptr& checkable, const Value& command, const ProcessResult& pr)
{ {
if (pr.ExitStatus != 0) { if (pr.ExitStatus != 0) {
std::ostringstream msgbuf; std::ostringstream msgbuf;
msgbuf << "Notification command '" << command << "' for service '" msgbuf << "Notification command '" << command << "' for object '"
<< service->GetName() << "' failed; exit status: " << checkable->GetName() << "' failed; exit status: "
<< pr.ExitStatus << ", output: " << pr.Output; << pr.ExitStatus << ", output: " << pr.Output;
Log(LogWarning, "icinga", msgbuf.str()); Log(LogWarning, "icinga", msgbuf.str());
} }
} }

View File

@ -43,7 +43,7 @@ public:
private: private:
PluginNotificationTask(void); PluginNotificationTask(void);
static void ProcessFinishedHandler(const Service::Ptr& service, const Value& command, const ProcessResult& pr); static void ProcessFinishedHandler(const Checkable::Ptr& checkable, const Value& command, const ProcessResult& pr);
}; };
} }

View File

@ -31,7 +31,7 @@ using namespace icinga;
REGISTER_SCRIPTFUNCTION(RandomCheck, &RandomCheckTask::ScriptFunc); REGISTER_SCRIPTFUNCTION(RandomCheck, &RandomCheckTask::ScriptFunc);
void RandomCheckTask::ScriptFunc(const Service::Ptr& service, const CheckResult::Ptr& cr) void RandomCheckTask::ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr)
{ {
String output = "Hello from "; String output = "Hello from ";
output += Utility::GetHostName(); output += Utility::GetHostName();

View File

@ -34,7 +34,7 @@ namespace icinga
class RandomCheckTask class RandomCheckTask
{ {
public: public:
static void ScriptFunc(const Service::Ptr& service, const CheckResult::Ptr& cr); static void ScriptFunc(const Checkable::Ptr& service, const CheckResult::Ptr& cr);
private: private:
RandomCheckTask(void); RandomCheckTask(void);