/******************************************************************************
* Icinga 2 *
- * Copyright (C) 2012 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 *
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
******************************************************************************/
-#include "i2-icinga.h"
+#include "icinga/notification.h"
+#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 "base/exception.h"
+#include "base/initialize.h"
+#include "base/scriptvariable.h"
+#include "base/scriptfunction.h"
+#include <boost/foreach.hpp>
using namespace icinga;
-REGISTER_TYPE(Notification, NULL);
+REGISTER_TYPE(Notification);
+REGISTER_SCRIPTFUNCTION(ValidateNotificationFilters, &Notification::ValidateFilters);
+INITIALIZE_ONCE(&Notification::StaticInitialize);
-Notification::Notification(const Dictionary::Ptr& properties)
- : DynamicObject(properties)
+boost::signals2::signal<void (const Notification::Ptr&, double, const String&)> Notification::OnNextNotificationChanged;
+
+String NotificationNameComposer::MakeName(const String& shortName, const Dictionary::Ptr props) const
{
- Service::InvalidateNotificationsCache();
+ if (!props)
+ return "";
+
+ String name = props->Get("host_name");
+
+ if (props->Contains("service_name"))
+ name += "!" + props->Get("service_name");
+
+ name += "!" + shortName;
+
+ return name;
}
-Notification::~Notification(void)
+void Notification::StaticInitialize(void)
{
- Service::InvalidateNotificationsCache();
+ 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);
}
-bool Notification::Exists(const String& name)
+void Notification::OnConfigLoaded(void)
{
- return (DynamicObject::GetObject("Notification", name));
+ SetNotificationTypeFilter(FilterArrayToInt(GetNotificationTypeFilterRaw(), 0));
+ SetNotificationStateFilter(FilterArrayToInt(GetNotificationStateFilterRaw(), 0));
+
+ GetCheckable()->AddNotification(GetSelf());
}
-Notification::Ptr Notification::GetByName(const String& name)
+void Notification::Start(void)
{
- DynamicObject::Ptr configObject = DynamicObject::GetObject("Notification", name);
+ DynamicObject::Start();
+
+ GetCheckable()->AddNotification(GetSelf());
+}
- if (!configObject)
- BOOST_THROW_EXCEPTION(invalid_argument("Notification '" + name + "' does not exist."));
+void Notification::Stop(void)
+{
+ DynamicObject::Stop();
- return dynamic_pointer_cast<Notification>(configObject);
+ GetCheckable()->RemoveNotification(GetSelf());
}
-Service::Ptr Notification::GetService(void) const
+Checkable::Ptr Notification::GetCheckable(void) const
{
- Host::Ptr host = Host::GetByName(Get("host_name"));
- String service = Get("service");
+ Host::Ptr host = Host::GetByName(GetHostName());
- if (service.IsEmpty())
- return host->GetHostCheckService();
+ if (GetServiceName().IsEmpty())
+ return host;
else
- return host->GetServiceByShortName(service);
+ return host->GetServiceByShortName(GetServiceName());
}
-Value Notification::GetNotificationCommand(void) const
+NotificationCommand::Ptr Notification::GetNotificationCommand(void) const
{
- return Get("notification_command");
+ return NotificationCommand::GetByName(GetNotificationCommandRaw());
}
-Dictionary::Ptr Notification::GetMacros(void) const
+std::set<User::Ptr> Notification::GetUsers(void) const
{
- return Get("macros");
+ std::set<User::Ptr> result;
+
+ Array::Ptr users = GetUsersRaw();
+
+ if (users) {
+ ObjectLock olock(users);
+
+ BOOST_FOREACH(const String& name, users) {
+ User::Ptr user = User::GetByName(name);
+
+ if (!user)
+ continue;
+
+ result.insert(user);
+ }
+ }
+
+ return result;
}
-set<User::Ptr> Notification::GetUsers(void) const
+std::set<UserGroup::Ptr> Notification::GetUserGroups(void) const
{
- set<User::Ptr> result;
+ std::set<UserGroup::Ptr> result;
- Dictionary::Ptr users = Get("users");
+ Array::Ptr groups = GetUserGroupsRaw();
- if (users) {
- String name;
- BOOST_FOREACH(tie(tuples::ignore, name), users) {
- result.insert(User::GetByName(name));
+ if (groups) {
+ ObjectLock olock(groups);
+
+ BOOST_FOREACH(const String& name, groups) {
+ UserGroup::Ptr ug = UserGroup::GetByName(name);
+
+ if (!ug)
+ continue;
+
+ result.insert(ug);
}
}
return result;
}
+TimePeriod::Ptr Notification::GetNotificationPeriod(void) const
+{
+ return TimePeriod::GetByName(GetNotificationPeriodRaw());
+}
+
+double Notification::GetNextNotification(void) const
+{
+ return GetNextNotificationRaw();
+}
+
+/**
+ * Sets the timestamp when the next periodical notification should be sent.
+ * This does not affect notifications that are sent for state changes.
+ */
+void Notification::SetNextNotification(double time, const String& authority)
+{
+ SetNextNotificationRaw(time);
+
+ OnNextNotificationChanged(GetSelf(), time, authority);
+}
+
+void Notification::UpdateNotificationNumber(void)
+{
+ SetNotificationNumber(GetNotificationNumber() + 1);
+}
+
+void Notification::ResetNotificationNumber(void)
+{
+ SetNotificationNumber(0);
+}
+
String Notification::NotificationTypeToString(NotificationType type)
{
switch (type) {
case NotificationDowntimeRemoved:
return "DOWNTIMECANCELLED";
case NotificationCustom:
- return "DOWNTIMECUSTOM";
+ return "CUSTOM";
+ case NotificationAcknowledgement:
+ return "ACKNOWLEDGEMENT";
case NotificationProblem:
return "PROBLEM";
case NotificationRecovery:
return "RECOVERY";
+ case NotificationFlappingStart:
+ return "FLAPPINGSTART";
+ case NotificationFlappingEnd:
+ return "FLAPPINGEND";
default:
return "UNKNOWN_NOTIFICATION";
}
}
-void Notification::BeginExecuteNotification(const Notification::Ptr& self, NotificationType type)
+void Notification::BeginExecuteNotification(NotificationType type, const CheckResult::Ptr& cr, bool force, const String& author, const String& text)
{
+ ASSERT(!OwnsLock());
- vector<Dictionary::Ptr> macroDicts;
+ Checkable::Ptr checkable = GetCheckable();
- Dictionary::Ptr notificationMacros = boost::make_shared<Dictionary>();
- notificationMacros->Set("NOTIFICATIONTYPE", NotificationTypeToString(type));
- macroDicts.push_back(notificationMacros);
+ if (!force) {
+ TimePeriod::Ptr tp = GetNotificationPeriod();
- Service::Ptr service;
- set<User::Ptr> users;
+ if (tp && !tp->IsInside(Utility::GetTime())) {
+ Log(LogInformation, "icinga", "Not sending notifications for notification object '" + GetName() + "': not in timeperiod");
+ return;
+ }
- {
- ObjectLock olock(self);
- macroDicts.push_back(self->GetMacros());
- service = self->GetService();
- users = self->GetUsers();
- }
+ double now = Utility::GetTime();
+ Dictionary::Ptr times = GetTimes();
- Host::Ptr host;
- String service_name;
+ if (type == NotificationProblem) {
+ 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;
+ }
- {
- ObjectLock olock(service);
- macroDicts.push_back(service->GetMacros());
- service_name = service->GetName();
- host = service->GetHost();
- }
+ 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;
+ }
+ }
- macroDicts.push_back(Service::CalculateDynamicMacros(service));
+ unsigned long ftype = 1 << type;
+
+ Log(LogDebug, "icinga", "FType=" + Convert::ToString(ftype) + ", TypeFilter=" + Convert::ToString(GetNotificationTypeFilter()));
+
+ if (!(ftype & GetNotificationTypeFilter())) {
+ Log(LogInformation, "icinga", "Not sending notifications for notification object '" + GetName() + "': type filter does not match");
+ return;
+ }
+
+ 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");
+ return;
+ }
+ }
{
- ObjectLock olock(host);
- macroDicts.push_back(host->GetMacros());
- macroDicts.push_back(Host::CalculateDynamicMacros(host));
+ ObjectLock olock(this);
+
+ double now = Utility::GetTime();
+ SetLastNotification(now);
+
+ if (type == NotificationProblem)
+ SetLastProblemNotification(now);
}
- IcingaApplication::Ptr app = IcingaApplication::GetInstance();
+ std::set<User::Ptr> allUsers;
- {
- ObjectLock olock(app);
- macroDicts.push_back(app->GetMacros());
+ std::set<User::Ptr> users = GetUsers();
+ std::copy(users.begin(), users.end(), std::inserter(allUsers, allUsers.begin()));
+
+ 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()));
}
- macroDicts.push_back(IcingaApplication::CalculateDynamicMacros(app));
+ Service::OnNotificationSendStart(GetSelf(), checkable, allUsers, type, cr, author, text);
- Dictionary::Ptr macros = MacroProcessor::MergeMacroDicts(macroDicts);
+ std::set<User::Ptr> allNotifiedUsers;
+ BOOST_FOREACH(const User::Ptr& user, allUsers) {
+ if (!CheckNotificationUserFilters(type, user, force))
+ continue;
- int count = 0;
+ Log(LogDebug, "icinga", "Sending notification for user '" + user->GetName() + "'");
+ Utility::QueueAsyncCallback(boost::bind(&Notification::ExecuteNotificationHelper, this, type, user, cr, force, author, text));
- BOOST_FOREACH(const User::Ptr& user, users) {
- BeginExecuteNotificationHelper(self, macros, type, user);
- count++;
+ /* collect all notified users */
+ allNotifiedUsers.insert(user);
}
- if (count == 0) {
- /* Send a notification even if there are no users specified. */
- BeginExecuteNotificationHelper(self, macros, type, User::Ptr());
- }
+ /* used in db_ido for notification history */
+ Service::OnNotificationSentToAllUsers(GetSelf(), checkable, allNotifiedUsers, type, cr, author, text);
}
-void Notification::BeginExecuteNotificationHelper(const Notification::Ptr& self, const Dictionary::Ptr& notificationMacros, NotificationType type, const User::Ptr& user)
+bool Notification::CheckNotificationUserFilters(NotificationType type, const User::Ptr& user, bool force)
{
- vector<Dictionary::Ptr> macroDicts;
+ ASSERT(!OwnsLock());
- if (user) {
- {
- ObjectLock olock(self);
- macroDicts.push_back(user->GetMacros());
- }
+ if (!force) {
+ TimePeriod::Ptr tp = user->GetNotificationPeriod();
- macroDicts.push_back(User::CalculateDynamicMacros(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 false;
+ }
- macroDicts.push_back(notificationMacros);
+ unsigned long ftype = 1 << type;
- Dictionary::Ptr macros = MacroProcessor::MergeMacroDicts(macroDicts);
+ if (!(ftype & user->GetNotificationTypeFilter())) {
+ Log(LogInformation, "icinga", "Not sending notifications for notification object '" +
+ GetName() + " and user '" + user->GetName() + "': type filter does not match");
+ return false;
+ }
- ScriptTask::Ptr task;
+ Checkable::Ptr checkable = GetCheckable();
+ Service::Ptr service = dynamic_pointer_cast<Service>(checkable);
+ Host::Ptr host;
- {
- ObjectLock olock(self);
+ if (service)
+ host = service->GetHost();
+ else
+ host = static_pointer_cast<Host>(checkable);
- vector<Value> arguments;
- arguments.push_back(self);
- arguments.push_back(macros);
- arguments.push_back(type);
- task = self->MakeMethodTask("notify", arguments);
+ unsigned long fstate;
- if (!task) {
- Logger::Write(LogWarning, "icinga", "Notification object '" + self->GetName() + "' doesn't have a 'notify' method.");
+ if (service)
+ fstate = ServiceStateToFilter(service->GetState());
+ else
+ fstate = HostStateToFilter(host->GetState());
- return;
+ if (!(fstate & user->GetNotificationStateFilter())) {
+ Log(LogInformation, "icinga", "Not sending notifications for notification object '" +
+ GetName() + " and user '" + user->GetName() + "': state filter does not match");
+ return false;
}
-
- /* We need to keep the task object alive until the completion handler is called. */
- self->m_Tasks.insert(task);
}
- task->Start(boost::bind(&Notification::NotificationCompletedHandler, self, _1));
+ return true;
}
-void Notification::NotificationCompletedHandler(const ScriptTask::Ptr& task)
+void Notification::ExecuteNotificationHelper(NotificationType type, const User::Ptr& user, const CheckResult::Ptr& cr, bool force, const String& author, const String& text)
{
- m_Tasks.erase(task);
+ ASSERT(!OwnsLock());
try {
+ NotificationCommand::Ptr command = GetNotificationCommand();
+
+ if (!command) {
+ Log(LogDebug, "icinga", "No notification_command found for notification '" + GetName() + "'. Skipping execution.");
+ return;
+ }
+
+ command->Execute(GetSelf(), user, cr, type, author, text);
+
{
- ObjectLock tlock(task);
- (void) task->GetResult();
+ ObjectLock olock(this);
+ UpdateNotificationNumber();
+ SetLastNotification(Utility::GetTime());
}
- Logger::Write(LogInformation, "icinga", "Completed sending notification for service '" + GetService()->GetName() + "'");
- } catch (const exception& ex) {
- stringstream msgbuf;
- msgbuf << "Exception occured during notification for service '"
- << GetService()->GetName() << "': " << diagnostic_information(ex);
- String message = msgbuf.str();
+ /* required by compatlogger */
+ Service::OnNotificationSentToUser(GetSelf(), GetCheckable(), user, type, cr, author, text, command->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 object '"
+ << GetCheckable()->GetName() << "': " << DiagnosticInformation(ex);
+ Log(LogWarning, "icinga", msgbuf.str());
+ }
+}
+
+int icinga::ServiceStateToFilter(ServiceState state)
+{
+ switch (state) {
+ case StateOK:
+ return StateFilterOK;
+ case StateWarning:
+ return StateFilterWarning;
+ case StateCritical:
+ return StateFilterCritical;
+ case StateUnknown:
+ return StateFilterUnknown;
+ default:
+ VERIFY(!"Invalid state type.");
+ }
+}
+
+int icinga::HostStateToFilter(HostState state)
+{
+ switch (state) {
+ case HostUp:
+ return StateFilterUp;
+ case HostDown:
+ return StateFilterDown;
+ default:
+ VERIFY(!"Invalid state type.");
+ }
+}
+
+int icinga::FilterArrayToInt(const Array::Ptr& typeFilters, int defaultValue)
+{
+ Value resultTypeFilter;
+
+ if (!typeFilters || typeFilters->GetLength() == 0)
+ return defaultValue;
+
+ resultTypeFilter = 0;
- Logger::Write(LogWarning, "icinga", message);
+ ObjectLock olock(typeFilters);
+ BOOST_FOREACH(const Value& typeFilter, typeFilters) {
+ resultTypeFilter = resultTypeFilter | typeFilter;
}
+
+ return resultTypeFilter;
}
-void Notification::OnAttributeChanged(const String& name, const Value& oldValue)
+void Notification::ValidateFilters(const String& location, const Dictionary::Ptr& attrs)
{
- if (name == "host_name" || name == "service")
- Service::InvalidateNotificationsCache();
+ 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 (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.");
+ }
+}
+
+bool Notification::ResolveMacro(const String& macro, const CheckResult::Ptr&, String *result) const
+{
+ Dictionary::Ptr vars = GetVars();
+
+ if (macro.SubStr(0, 13) == "notification.") {
+ String key = vars->Get(macro.SubStr(13));
+
+ if (vars && vars->Contains(key)) {
+ *result = vars->Get(key);
+ return true;
+ }
+ }
+
+ return false;
}