1 /******************************************************************************
3 * Copyright (C) 2012-2014 Icinga Development Team (http://www.icinga.org) *
5 * This program is free software; you can redistribute it and/or *
6 * modify it under the terms of the GNU General Public License *
7 * as published by the Free Software Foundation; either version 2 *
8 * of the License, or (at your option) any later version. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the Free Software Foundation *
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
18 ******************************************************************************/
20 #include "icinga/notification.h"
21 #include "icinga/notificationcommand.h"
22 #include "icinga/macroprocessor.h"
23 #include "icinga/service.h"
24 #include "config/configcompilercontext.h"
25 #include "base/dynamictype.h"
26 #include "base/objectlock.h"
27 #include "base/logger_fwd.h"
28 #include "base/utility.h"
29 #include "base/convert.h"
30 #include "base/exception.h"
31 #include "base/initialize.h"
32 #include "base/scriptvariable.h"
33 #include "base/scriptfunction.h"
34 #include <boost/foreach.hpp>
36 using namespace icinga;
38 REGISTER_TYPE(Notification);
39 REGISTER_SCRIPTFUNCTION(ValidateNotificationFilters, &Notification::ValidateFilters);
40 INITIALIZE_ONCE(&Notification::StaticInitialize);
42 boost::signals2::signal<void (const Notification::Ptr&, double, const String&)> Notification::OnNextNotificationChanged;
44 String NotificationNameComposer::MakeName(const String& shortName, const Dictionary::Ptr props) const
49 String name = props->Get("host_name");
51 if (props->Contains("service_name"))
52 name += "!" + props->Get("service_name");
54 name += "!" + shortName;
59 void Notification::StaticInitialize(void)
61 ScriptVariable::Set("OK", StateFilterOK, true, true);
62 ScriptVariable::Set("Warning", StateFilterWarning, true, true);
63 ScriptVariable::Set("Critical", StateCritical, true, true);
64 ScriptVariable::Set("Unknown", StateUnknown, true, true);
65 ScriptVariable::Set("Up", StateFilterUp, true, true);
66 ScriptVariable::Set("Down", StateFilterDown, true, true);
68 ScriptVariable::Set("DowntimeStart", 1 << NotificationDowntimeStart, true, true);
69 ScriptVariable::Set("DowntimeEnd", 1 << NotificationDowntimeEnd, true, true);
70 ScriptVariable::Set("DowntimeRemoved", 1 << NotificationDowntimeRemoved, true, true);
71 ScriptVariable::Set("Custom", 1 << NotificationCustom, true, true);
72 ScriptVariable::Set("Acknowledgement", 1 << NotificationAcknowledgement, true, true);
73 ScriptVariable::Set("Problem", 1 << NotificationProblem, true, true);
74 ScriptVariable::Set("Recovery", 1 << NotificationRecovery, true, true);
75 ScriptVariable::Set("FlappingStart", 1 << NotificationFlappingStart, true, true);
76 ScriptVariable::Set("FlappingEnd", 1 << NotificationFlappingEnd, true, true);
79 void Notification::OnConfigLoaded(void)
81 SetNotificationTypeFilter(FilterArrayToInt(GetNotificationTypeFilterRaw(), 0));
82 SetNotificationStateFilter(FilterArrayToInt(GetNotificationStateFilterRaw(), 0));
84 GetCheckable()->AddNotification(GetSelf());
87 void Notification::Start(void)
89 DynamicObject::Start();
91 GetCheckable()->AddNotification(GetSelf());
94 void Notification::Stop(void)
96 DynamicObject::Stop();
98 GetCheckable()->RemoveNotification(GetSelf());
101 Checkable::Ptr Notification::GetCheckable(void) const
103 Host::Ptr host = Host::GetByName(GetHostName());
105 if (GetServiceName().IsEmpty())
108 return host->GetServiceByShortName(GetServiceName());
111 NotificationCommand::Ptr Notification::GetNotificationCommand(void) const
113 return NotificationCommand::GetByName(GetNotificationCommandRaw());
116 std::set<User::Ptr> Notification::GetUsers(void) const
118 std::set<User::Ptr> result;
120 Array::Ptr users = GetUsersRaw();
123 ObjectLock olock(users);
125 BOOST_FOREACH(const String& name, users) {
126 User::Ptr user = User::GetByName(name);
138 std::set<UserGroup::Ptr> Notification::GetUserGroups(void) const
140 std::set<UserGroup::Ptr> result;
142 Array::Ptr groups = GetUserGroupsRaw();
145 ObjectLock olock(groups);
147 BOOST_FOREACH(const String& name, groups) {
148 UserGroup::Ptr ug = UserGroup::GetByName(name);
160 TimePeriod::Ptr Notification::GetNotificationPeriod(void) const
162 return TimePeriod::GetByName(GetNotificationPeriodRaw());
165 double Notification::GetNextNotification(void) const
167 return GetNextNotificationRaw();
171 * Sets the timestamp when the next periodical notification should be sent.
172 * This does not affect notifications that are sent for state changes.
174 void Notification::SetNextNotification(double time, const String& authority)
176 SetNextNotificationRaw(time);
178 OnNextNotificationChanged(GetSelf(), time, authority);
181 void Notification::UpdateNotificationNumber(void)
183 SetNotificationNumber(GetNotificationNumber() + 1);
186 void Notification::ResetNotificationNumber(void)
188 SetNotificationNumber(0);
191 String Notification::NotificationTypeToString(NotificationType type)
194 case NotificationDowntimeStart:
195 return "DOWNTIMESTART";
196 case NotificationDowntimeEnd:
197 return "DOWNTIMEEND";
198 case NotificationDowntimeRemoved:
199 return "DOWNTIMECANCELLED";
200 case NotificationCustom:
202 case NotificationAcknowledgement:
203 return "ACKNOWLEDGEMENT";
204 case NotificationProblem:
206 case NotificationRecovery:
208 case NotificationFlappingStart:
209 return "FLAPPINGSTART";
210 case NotificationFlappingEnd:
211 return "FLAPPINGEND";
213 return "UNKNOWN_NOTIFICATION";
217 void Notification::BeginExecuteNotification(NotificationType type, const CheckResult::Ptr& cr, bool force, const String& author, const String& text)
221 Checkable::Ptr checkable = GetCheckable();
224 TimePeriod::Ptr tp = GetNotificationPeriod();
226 if (tp && !tp->IsInside(Utility::GetTime())) {
227 Log(LogInformation, "icinga", "Not sending notifications for notification object '" + GetName() + "': not in timeperiod");
231 double now = Utility::GetTime();
232 Dictionary::Ptr times = GetTimes();
234 if (type == NotificationProblem) {
235 if (times && times->Contains("begin") && now < checkable->GetLastHardStateChange() + times->Get("begin")) {
236 Log(LogInformation, "icinga", "Not sending notifications for notification object '" + GetName() + "': before escalation range");
240 if (times && times->Contains("end") && now > checkable->GetLastHardStateChange() + times->Get("end")) {
241 Log(LogInformation, "icinga", "Not sending notifications for notification object '" + GetName() + "': after escalation range");
246 unsigned long ftype = 1 << type;
248 Log(LogDebug, "icinga", "FType=" + Convert::ToString(ftype) + ", TypeFilter=" + Convert::ToString(GetNotificationTypeFilter()));
250 if (!(ftype & GetNotificationTypeFilter())) {
251 Log(LogInformation, "icinga", "Not sending notifications for notification object '" + GetName() + "': type filter does not match");
255 Service::Ptr service = dynamic_pointer_cast<Service>(checkable);
259 host = service->GetHost();
261 host = static_pointer_cast<Host>(checkable);
263 unsigned long fstate;
266 fstate = ServiceStateToFilter(service->GetState());
268 fstate = HostStateToFilter(host->GetState());
270 if (!(fstate & GetNotificationStateFilter())) {
271 Log(LogInformation, "icinga", "Not sending notifications for notification object '" + GetName() + "': state filter does not match");
277 ObjectLock olock(this);
279 double now = Utility::GetTime();
280 SetLastNotification(now);
282 if (type == NotificationProblem)
283 SetLastProblemNotification(now);
286 std::set<User::Ptr> allUsers;
288 std::set<User::Ptr> users = GetUsers();
289 std::copy(users.begin(), users.end(), std::inserter(allUsers, allUsers.begin()));
291 BOOST_FOREACH(const UserGroup::Ptr& ug, GetUserGroups()) {
292 std::set<User::Ptr> members = ug->GetMembers();
293 std::copy(members.begin(), members.end(), std::inserter(allUsers, allUsers.begin()));
296 Service::OnNotificationSendStart(GetSelf(), checkable, allUsers, type, cr, author, text);
298 std::set<User::Ptr> allNotifiedUsers;
299 BOOST_FOREACH(const User::Ptr& user, allUsers) {
300 if (!CheckNotificationUserFilters(type, user, force))
303 Log(LogDebug, "icinga", "Sending notification for user '" + user->GetName() + "'");
304 Utility::QueueAsyncCallback(boost::bind(&Notification::ExecuteNotificationHelper, this, type, user, cr, force, author, text));
306 /* collect all notified users */
307 allNotifiedUsers.insert(user);
310 /* used in db_ido for notification history */
311 Service::OnNotificationSentToAllUsers(GetSelf(), checkable, allNotifiedUsers, type, cr, author, text);
314 bool Notification::CheckNotificationUserFilters(NotificationType type, const User::Ptr& user, bool force)
319 TimePeriod::Ptr tp = user->GetNotificationPeriod();
321 if (tp && !tp->IsInside(Utility::GetTime())) {
322 Log(LogInformation, "icinga", "Not sending notifications for notification object '" +
323 GetName() + " and user '" + user->GetName() + "': user not in timeperiod");
327 unsigned long ftype = 1 << type;
329 if (!(ftype & user->GetNotificationTypeFilter())) {
330 Log(LogInformation, "icinga", "Not sending notifications for notification object '" +
331 GetName() + " and user '" + user->GetName() + "': type filter does not match");
335 Checkable::Ptr checkable = GetCheckable();
336 Service::Ptr service = dynamic_pointer_cast<Service>(checkable);
340 host = service->GetHost();
342 host = static_pointer_cast<Host>(checkable);
344 unsigned long fstate;
347 fstate = ServiceStateToFilter(service->GetState());
349 fstate = HostStateToFilter(host->GetState());
351 if (!(fstate & user->GetNotificationStateFilter())) {
352 Log(LogInformation, "icinga", "Not sending notifications for notification object '" +
353 GetName() + " and user '" + user->GetName() + "': state filter does not match");
361 void Notification::ExecuteNotificationHelper(NotificationType type, const User::Ptr& user, const CheckResult::Ptr& cr, bool force, const String& author, const String& text)
366 NotificationCommand::Ptr command = GetNotificationCommand();
369 Log(LogDebug, "icinga", "No notification_command found for notification '" + GetName() + "'. Skipping execution.");
373 command->Execute(GetSelf(), user, cr, type, author, text);
376 ObjectLock olock(this);
377 UpdateNotificationNumber();
378 SetLastNotification(Utility::GetTime());
381 /* required by compatlogger */
382 Service::OnNotificationSentToUser(GetSelf(), GetCheckable(), user, type, cr, author, text, command->GetName());
384 Log(LogInformation, "icinga", "Completed sending notification for object '" + GetCheckable()->GetName() + "'");
385 } catch (const std::exception& ex) {
386 std::ostringstream msgbuf;
387 msgbuf << "Exception occured during notification for object '"
388 << GetCheckable()->GetName() << "': " << DiagnosticInformation(ex);
389 Log(LogWarning, "icinga", msgbuf.str());
393 int icinga::ServiceStateToFilter(ServiceState state)
397 return StateFilterOK;
399 return StateFilterWarning;
401 return StateFilterCritical;
403 return StateFilterUnknown;
405 VERIFY(!"Invalid state type.");
409 int icinga::HostStateToFilter(HostState state)
413 return StateFilterUp;
414 case HostDown: /* fall through */
415 case HostUnreachable:
416 return StateFilterDown;
418 VERIFY(!"Invalid state type.");
422 int icinga::FilterArrayToInt(const Array::Ptr& typeFilters, int defaultValue)
424 Value resultTypeFilter;
426 if (!typeFilters || typeFilters->GetLength() == 0)
429 resultTypeFilter = 0;
431 ObjectLock olock(typeFilters);
432 BOOST_FOREACH(const Value& typeFilter, typeFilters) {
433 resultTypeFilter = resultTypeFilter | typeFilter;
436 return resultTypeFilter;
439 void Notification::ValidateFilters(const String& location, const Dictionary::Ptr& attrs)
441 int sfilter = FilterArrayToInt(attrs->Get("notification_state_filter"), 0);
443 if (!attrs->Contains("service_name") && (sfilter & ~(StateFilterUp | StateFilterDown)) != 0) {
444 ConfigCompilerContext::GetInstance()->AddMessage(true, "Validation failed for " +
445 location + ": State filter is invalid.");
448 if (attrs->Contains("service_name") && (sfilter & ~(StateFilterOK | StateFilterWarning | StateFilterCritical | StateFilterUnknown)) != 0) {
449 ConfigCompilerContext::GetInstance()->AddMessage(true, "Validation failed for " +
450 location + ": State filter is invalid.");
453 int tfilter = FilterArrayToInt(attrs->Get("notification_type_filter"), 0);
455 if ((tfilter & ~(1 << NotificationDowntimeStart | 1 << NotificationDowntimeEnd | 1 << NotificationDowntimeRemoved |
456 1 << NotificationCustom | 1 << NotificationAcknowledgement | 1 << NotificationProblem | 1 << NotificationRecovery |
457 1 << NotificationFlappingStart | 1 << NotificationFlappingEnd)) != 0) {
458 ConfigCompilerContext::GetInstance()->AddMessage(true, "Validation failed for " +
459 location + ": Type filter is invalid.");
463 bool Notification::ResolveMacro(const String& macro, const CheckResult::Ptr&, String *result) const
465 Dictionary::Ptr vars = GetVars();
467 if (macro.SubStr(0, 13) == "notification.") {
468 String key = vars->Get(macro.SubStr(13));
470 if (vars && vars->Contains(key)) {
471 *result = vars->Get(key);