]> granicus.if.org Git - icinga2/blobdiff - lib/icinga/notification.cpp
Remove the HostUnreachable state.
[icinga2] / lib / icinga / notification.cpp
index 586ba6c4a805df79179990db269dd2d5a6963dbf..c143ee4d787958edfb15f65812ef688156a5e80a 100644 (file)
@@ -1,6 +1,6 @@
 /******************************************************************************
  * Icinga 2                                                                   *
- * Copyright (C) 2012-2013 Icinga Development Team (http://www.icinga.org/)   *
+ * 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                *
 #include "icinga/notificationcommand.h"
 #include "icinga/macroprocessor.h"
 #include "icinga/service.h"
+#include "config/configcompilercontext.h"
 #include "base/dynamictype.h"
 #include "base/objectlock.h"
 #include "base/logger_fwd.h"
 #include "base/utility.h"
 #include "base/convert.h"
-#include <boost/tuple/tuple.hpp>
+#include "base/exception.h"
+#include "base/initialize.h"
+#include "base/scriptvariable.h"
+#include "base/scriptfunction.h"
 #include <boost/foreach.hpp>
-#include <boost/exception/diagnostic_information.hpp>
 
 using namespace icinga;
 
 REGISTER_TYPE(Notification);
+REGISTER_SCRIPTFUNCTION(ValidateNotificationFilters, &Notification::ValidateFilters);
+INITIALIZE_ONCE(&Notification::StaticInitialize);
 
 boost::signals2::signal<void (const Notification::Ptr&, double, const String&)> Notification::OnNextNotificationChanged;
 
-void Notification::Start(void)
+String NotificationNameComposer::MakeName(const String& shortName, const Dictionary::Ptr props) const
 {
-       DynamicObject::Start();
+       if (!props)
+               return "";
+
+       String name = props->Get("host_name");
 
-       GetService()->AddNotification(GetSelf());
+       if (props->Contains("service_name"))
+               name += "!" + props->Get("service_name");
+
+       name += "!" + shortName;
+
+       return name;
 }
 
-void Notification::Stop(void)
+void Notification::StaticInitialize(void)
 {
-       DynamicObject::Stop();
-
-       GetService()->RemoveNotification(GetSelf());
+       ScriptVariable::Set("OK", StateFilterOK, true, true);
+       ScriptVariable::Set("Warning", StateFilterWarning, true, true);
+       ScriptVariable::Set("Critical", StateCritical, true, true);
+       ScriptVariable::Set("Unknown", StateUnknown, true, true);
+       ScriptVariable::Set("Up", StateFilterUp, true, true);
+       ScriptVariable::Set("Down", StateFilterDown, true, true);
+
+       ScriptVariable::Set("DowntimeStart", 1 << NotificationDowntimeStart, true, true);
+       ScriptVariable::Set("DowntimeEnd", 1 << NotificationDowntimeEnd, true, true);
+       ScriptVariable::Set("DowntimeRemoved", 1 << NotificationDowntimeRemoved, true, true);
+       ScriptVariable::Set("Custom", 1 << NotificationCustom, true, true);
+       ScriptVariable::Set("Acknowledgement", 1 << NotificationAcknowledgement, true, true);
+       ScriptVariable::Set("Problem", 1 << NotificationProblem, true, true);
+       ScriptVariable::Set("Recovery", 1 << NotificationRecovery, true, true);
+       ScriptVariable::Set("FlappingStart", 1 << NotificationFlappingStart, true, true);
+       ScriptVariable::Set("FlappingEnd", 1 << NotificationFlappingEnd, true, true);
 }
 
-Service::Ptr Notification::GetService(void) const
+void Notification::OnConfigLoaded(void)
 {
-       Host::Ptr host = Host::GetByName(m_HostName);
+       SetNotificationTypeFilter(FilterArrayToInt(GetNotificationTypeFilterRaw(), 0));
+       SetNotificationStateFilter(FilterArrayToInt(GetNotificationStateFilterRaw(), 0));
 
-       if (!host)
-               return Service::Ptr();
+       GetCheckable()->AddNotification(GetSelf());
+}
 
-       if (m_Service.IsEmpty())
-               return host->GetCheckService();
-       else
-               return host->GetServiceByShortName(m_Service);
+void Notification::Start(void)
+{
+       DynamicObject::Start();
+
+       GetCheckable()->AddNotification(GetSelf());
 }
 
-NotificationCommand::Ptr Notification::GetNotificationCommand(void) const
+void Notification::Stop(void)
 {
-       return NotificationCommand::GetByName(m_NotificationCommand);
+       DynamicObject::Stop();
+
+       GetCheckable()->RemoveNotification(GetSelf());
 }
 
-Dictionary::Ptr Notification::GetMacros(void) const
+Checkable::Ptr Notification::GetCheckable(void) const
 {
-       return m_Macros;
+       Host::Ptr host = Host::GetByName(GetHostName());
+
+       if (GetServiceName().IsEmpty())
+               return host;
+       else
+               return host->GetServiceByShortName(GetServiceName());
 }
 
-Array::Ptr Notification::GetExportMacros(void) const
+NotificationCommand::Ptr Notification::GetNotificationCommand(void) const
 {
-       return m_ExportMacros;
+       return NotificationCommand::GetByName(GetNotificationCommandRaw());
 }
 
 std::set<User::Ptr> Notification::GetUsers(void) const
 {
        std::set<User::Ptr> result;
 
-       Array::Ptr users = m_Users;
+       Array::Ptr users = GetUsersRaw();
 
        if (users) {
                ObjectLock olock(users);
@@ -100,11 +135,11 @@ std::set<User::Ptr> Notification::GetUsers(void) const
        return result;
 }
 
-std::set<UserGroup::Ptr> Notification::GetGroups(void) const
+std::set<UserGroup::Ptr> Notification::GetUserGroups(void) const
 {
        std::set<UserGroup::Ptr> result;
 
-       Array::Ptr groups = m_Groups;
+       Array::Ptr groups = GetUserGroupsRaw();
 
        if (groups) {
                ObjectLock olock(groups);
@@ -122,62 +157,14 @@ std::set<UserGroup::Ptr> Notification::GetGroups(void) const
        return result;
 }
 
-Dictionary::Ptr Notification::GetTimes(void) const
-{
-       return m_Times;
-}
-
-unsigned long Notification::GetNotificationTypeFilter(void) const
-{
-       if (m_NotificationTypeFilter.IsEmpty())
-               return ~(unsigned long)0; /* All states. */
-       else
-               return m_NotificationTypeFilter;
-}
-
-unsigned long Notification::GetNotificationStateFilter(void) const
-{
-       if (m_NotificationStateFilter.IsEmpty())
-               return ~(unsigned long)0; /* All states. */
-       else
-               return m_NotificationStateFilter;
-}
-
-double Notification::GetNotificationInterval(void) const
-{
-       if (m_NotificationInterval.IsEmpty())
-               return 300;
-       else
-               return m_NotificationInterval;
-}
-
 TimePeriod::Ptr Notification::GetNotificationPeriod(void) const
 {
-       return TimePeriod::GetByName(m_NotificationPeriod);
-}
-
-double Notification::GetLastNotification(void) const
-{
-       if (m_LastNotification.IsEmpty())
-               return 0;
-       else
-               return m_LastNotification;
-}
-
-/**
- * Sets the timestamp when the last notification was sent.
- */
-void Notification::SetLastNotification(double time)
-{
-       m_LastNotification = time;
+       return TimePeriod::GetByName(GetNotificationPeriodRaw());
 }
 
 double Notification::GetNextNotification(void) const
 {
-       if (m_NextNotification.IsEmpty())
-               return 0;
-       else
-               return m_NextNotification;
+       return GetNextNotificationRaw();
 }
 
 /**
@@ -186,27 +173,19 @@ double Notification::GetNextNotification(void) const
  */
 void Notification::SetNextNotification(double time, const String& authority)
 {
-       m_NextNotification = time;
+       SetNextNotificationRaw(time);
 
-       Utility::QueueAsyncCallback(boost::bind(boost::ref(OnNextNotificationChanged), GetSelf(), time, authority));
-}
-
-long Notification::GetNotificationNumber(void) const
-{
-       if (m_NotificationNumber.IsEmpty())
-               return 0;
-       else
-               return m_NotificationNumber;
+       OnNextNotificationChanged(GetSelf(), time, authority);
 }
 
 void Notification::UpdateNotificationNumber(void)
 {
-       m_NotificationNumber = m_NotificationNumber + 1;
+       SetNotificationNumber(GetNotificationNumber() + 1);
 }
 
 void Notification::ResetNotificationNumber(void)
 {
-       m_NotificationNumber = 0;
+       SetNotificationNumber(0);
 }
 
 String Notification::NotificationTypeToString(NotificationType type)
@@ -235,10 +214,12 @@ String Notification::NotificationTypeToString(NotificationType type)
        }
 }
 
-void Notification::BeginExecuteNotification(NotificationType type, const Dictionary::Ptr& cr, bool force, const String& author, const String& text)
+void Notification::BeginExecuteNotification(NotificationType type, const CheckResult::Ptr& cr, bool force, const String& author, const String& text)
 {
        ASSERT(!OwnsLock());
 
+       Checkable::Ptr checkable = GetCheckable();
+
        if (!force) {
                TimePeriod::Ptr tp = GetNotificationPeriod();
 
@@ -249,15 +230,14 @@ void Notification::BeginExecuteNotification(NotificationType type, const Diction
 
                double now = Utility::GetTime();
                Dictionary::Ptr times = GetTimes();
-               Service::Ptr service = GetService();
 
                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");
                                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");
                                return;
                        }
@@ -272,7 +252,20 @@ void Notification::BeginExecuteNotification(NotificationType type, const Diction
                        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 = ServiceStateToFilter(service->GetState());
+               else
+                       fstate = HostStateToFilter(host->GetState());
 
                if (!(fstate & GetNotificationStateFilter())) {
                        Log(LogInformation, "icinga", "Not sending notifications for notification object '" + GetName() + "': state filter does not match");
@@ -283,7 +276,11 @@ void Notification::BeginExecuteNotification(NotificationType type, const Diction
        {
                ObjectLock olock(this);
 
-               SetLastNotification(Utility::GetTime());
+               double now = Utility::GetTime();
+               SetLastNotification(now);
+
+               if (type == NotificationProblem)
+                       SetLastProblemNotification(now);
        }
 
        std::set<User::Ptr> allUsers;
@@ -291,22 +288,30 @@ void Notification::BeginExecuteNotification(NotificationType type, const Diction
        std::set<User::Ptr> users = GetUsers();
        std::copy(users.begin(), users.end(), std::inserter(allUsers, allUsers.begin()));
 
-       BOOST_FOREACH(const UserGroup::Ptr& ug, GetGroups()) {
+       BOOST_FOREACH(const UserGroup::Ptr& ug, GetUserGroups()) {
                std::set<User::Ptr> members = ug->GetMembers();
                std::copy(members.begin(), members.end(), std::inserter(allUsers, allUsers.begin()));
        }
 
-       unsigned long notified_users = 0;
+       Service::OnNotificationSendStart(GetSelf(), checkable, allUsers, type, cr, author, text);
+
+       std::set<User::Ptr> allNotifiedUsers;
        BOOST_FOREACH(const User::Ptr& user, allUsers) {
+               if (!CheckNotificationUserFilters(type, user, force))
+                       continue;
+
                Log(LogDebug, "icinga", "Sending notification for user '" + user->GetName() + "'");
                Utility::QueueAsyncCallback(boost::bind(&Notification::ExecuteNotificationHelper, this, type, user, cr, force, author, text));
-               notified_users++;
+
+               /* collect all notified users */
+               allNotifiedUsers.insert(user);
        }
 
-       Service::OnNotificationSentToAllUsers(GetService(), allUsers, type, cr, author, text, notified_users);
+       /* used in db_ido for notification history */
+       Service::OnNotificationSentToAllUsers(GetSelf(), checkable, allNotifiedUsers, type, cr, author, text);
 }
 
-void Notification::ExecuteNotificationHelper(NotificationType type, const User::Ptr& user, const Dictionary::Ptr& cr, bool force, const String& author, const String& text)
+bool Notification::CheckNotificationUserFilters(NotificationType type, const User::Ptr& user, bool force)
 {
        ASSERT(!OwnsLock());
 
@@ -316,7 +321,7 @@ void Notification::ExecuteNotificationHelper(NotificationType type, const User::
                if (tp && !tp->IsInside(Utility::GetTime())) {
                        Log(LogInformation, "icinga", "Not sending notifications for notification object '" +
                            GetName() + " and user '" + user->GetName() + "': user not in timeperiod");
-                       return;
+                       return false;
                }
 
                unsigned long ftype = 1 << type;
@@ -324,18 +329,39 @@ void Notification::ExecuteNotificationHelper(NotificationType type, const User::
                if (!(ftype & user->GetNotificationTypeFilter())) {
                        Log(LogInformation, "icinga", "Not sending notifications for notification object '" +
                            GetName() + " and user '" + user->GetName() + "': type filter does not match");
-                       return;
+                       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 = ServiceStateToFilter(service->GetState());
+               else
+                               fstate = HostStateToFilter(host->GetState());
 
                if (!(fstate & user->GetNotificationStateFilter())) {
                        Log(LogInformation, "icinga", "Not sending notifications for notification object '" +
                            GetName() + " and user '" + user->GetName() + "': state filter does not match");
-                       return;
+                       return false;
                }
        }
 
+       return true;
+}
+
+void Notification::ExecuteNotificationHelper(NotificationType type, const User::Ptr& user, const CheckResult::Ptr& cr, bool force, const String& author, const String& text)
+{
+       ASSERT(!OwnsLock());
+
        try {
                NotificationCommand::Ptr command = GetNotificationCommand();
 
@@ -344,7 +370,7 @@ void Notification::ExecuteNotificationHelper(NotificationType type, const User::
                        return;
                }
 
-               command->Execute(GetSelf(), user, cr, type);
+               command->Execute(GetSelf(), user, cr, type, author, text);
 
                {
                        ObjectLock olock(this);
@@ -352,77 +378,99 @@ void Notification::ExecuteNotificationHelper(NotificationType type, const User::
                        SetLastNotification(Utility::GetTime());
                }
 
-               Service::OnNotificationSentToUser(GetService(), user, type, cr, author, text);
+               /* required by compatlogger */
+               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) {
                std::ostringstream msgbuf;
-               msgbuf << "Exception occured during notification for service '"
-                      << GetService()->GetName() << "': " << boost::diagnostic_information(ex);
+               msgbuf << "Exception occured during notification for object '"
+                      << GetCheckable()->GetName() << "': " << DiagnosticInformation(ex);
                Log(LogWarning, "icinga", msgbuf.str());
        }
 }
 
-bool Notification::ResolveMacro(const String& macro, const Dictionary::Ptr&, String *result) const
+int icinga::ServiceStateToFilter(ServiceState state)
 {
-       Dictionary::Ptr macros = GetMacros();
+       switch (state) {
+               case StateOK:
+                       return StateFilterOK;
+               case StateWarning:
+                       return StateFilterWarning;
+               case StateCritical:
+                       return StateFilterCritical;
+               case StateUnknown:
+                       return StateFilterUnknown;
+               default:
+                       VERIFY(!"Invalid state type.");
+       }
+}
 
-       if (macros && macros->Contains(macro)) {
-               *result = macros->Get(macro);
-               return true;
+int icinga::HostStateToFilter(HostState state)
+{
+       switch (state) {
+               case HostUp:
+                       return StateFilterUp;
+               case HostDown:
+                       return StateFilterDown;
+               default:
+                       VERIFY(!"Invalid state type.");
        }
+}
 
-       return false;
+int icinga::FilterArrayToInt(const Array::Ptr& typeFilters, int defaultValue)
+{
+       Value resultTypeFilter;
+
+       if (!typeFilters || typeFilters->GetLength() == 0)
+               return defaultValue;
+
+       resultTypeFilter = 0;
+
+       ObjectLock olock(typeFilters);
+       BOOST_FOREACH(const Value& typeFilter, typeFilters) {
+               resultTypeFilter = resultTypeFilter | typeFilter;
+       }
+
+       return resultTypeFilter;
 }
 
-void Notification::InternalSerialize(const Dictionary::Ptr& bag, int attributeTypes) const
+void Notification::ValidateFilters(const String& location, const Dictionary::Ptr& attrs)
 {
-       DynamicObject::InternalSerialize(bag, attributeTypes);
-
-       if (attributeTypes & Attribute_Config) {
-               bag->Set("notification_command", m_NotificationCommand);
-               bag->Set("notification_interval", m_NotificationInterval);
-               bag->Set("notification_period", m_NotificationPeriod);
-               bag->Set("macros", m_Macros);
-               bag->Set("users", m_Users);
-               bag->Set("groups", m_Groups);
-               bag->Set("times", m_Times);
-               bag->Set("notification_type_filter", m_NotificationTypeFilter);
-               bag->Set("notification_state_filter", m_NotificationStateFilter);
-               bag->Set("host", m_HostName);
-               bag->Set("export_macros", m_ExportMacros);
-               bag->Set("service", m_Service);
+       int sfilter = FilterArrayToInt(attrs->Get("notification_state_filter"), 0);
+
+       if (!attrs->Contains("service_name") && (sfilter & ~(StateFilterUp | StateFilterDown)) != 0) {
+               ConfigCompilerContext::GetInstance()->AddMessage(true, "Validation failed for " +
+                   location + ": State filter is invalid.");
        }
 
-       if (attributeTypes & Attribute_State) {
-               bag->Set("last_notification", m_LastNotification);
-               bag->Set("next_notification", m_NextNotification);
-               bag->Set("notification_number", m_NotificationNumber);
+       if (attrs->Contains("service_name") && (sfilter & ~(StateFilterOK | StateFilterWarning | StateFilterCritical | StateFilterUnknown)) != 0) {
+               ConfigCompilerContext::GetInstance()->AddMessage(true, "Validation failed for " +
+                   location + ": State filter is invalid.");
+       }
+
+       int tfilter = FilterArrayToInt(attrs->Get("notification_type_filter"), 0);
+
+       if ((tfilter & ~(1 << NotificationDowntimeStart | 1 << NotificationDowntimeEnd | 1 << NotificationDowntimeRemoved |
+           1 << NotificationCustom | 1 << NotificationAcknowledgement | 1 << NotificationProblem | 1 << NotificationRecovery |
+           1 << NotificationFlappingStart | 1 << NotificationFlappingEnd)) != 0) {
+               ConfigCompilerContext::GetInstance()->AddMessage(true, "Validation failed for " +
+                   location + ": Type filter is invalid.");
        }
 }
 
-void Notification::InternalDeserialize(const Dictionary::Ptr& bag, int attributeTypes)
+bool Notification::ResolveMacro(const String& macro, const CheckResult::Ptr&, String *result) const
 {
-       DynamicObject::InternalDeserialize(bag, attributeTypes);
-
-       if (attributeTypes & Attribute_Config) {
-               m_NotificationCommand = bag->Get("notification_command");
-               m_NotificationInterval = bag->Get("notification_interval");
-               m_NotificationPeriod = bag->Get("notification_period");
-               m_Macros = bag->Get("macros");
-               m_Users = bag->Get("users");
-               m_Groups = bag->Get("groups");
-               m_Times = bag->Get("times");
-               m_NotificationTypeFilter = bag->Get("notification_type_filter");
-               m_NotificationStateFilter = bag->Get("notification_state_filter");
-               m_HostName = bag->Get("host");
-               m_ExportMacros = bag->Get("export_macros");
-               m_Service = bag->Get("service");
-       }
+       Dictionary::Ptr vars = GetVars();
+
+       if (macro.SubStr(0, 13) == "notification.") {
+               String key = vars->Get(macro.SubStr(13));
 
-       if (attributeTypes & Attribute_State) {
-               m_LastNotification = bag->Get("last_notification");
-               m_NextNotification = bag->Get("next_notification");
-               m_NotificationNumber = bag->Get("notification_number");
+               if (vars && vars->Contains(key)) {
+                       *result = vars->Get(key);
+                       return true;
+               }
        }
+
+       return false;
 }