]> granicus.if.org Git - icinga2/blob - lib/icinga/notification.cpp
Implement status updates for contacts.
[icinga2] / lib / icinga / notification.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012 Icinga Development Team (http://www.icinga.org/)        *
4  *                                                                            *
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.                     *
9  *                                                                            *
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.                               *
14  *                                                                            *
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  ******************************************************************************/
19
20 #include "icinga/notification.h"
21 #include "icinga/notificationcommand.h"
22 #include "icinga/macroprocessor.h"
23 #include "icinga/service.h"
24 #include "icinga/notificationmessage.h"
25 #include "remoting/endpointmanager.h"
26 #include "base/dynamictype.h"
27 #include "base/objectlock.h"
28 #include "base/logger_fwd.h"
29 #include "base/utility.h"
30 #include "base/convert.h"
31 #include <boost/tuple/tuple.hpp>
32 #include <boost/foreach.hpp>
33 #include <boost/exception/diagnostic_information.hpp>
34
35 using namespace icinga;
36
37 REGISTER_TYPE(Notification);
38
39 Notification::Notification(const Dictionary::Ptr& serializedUpdate)
40         : DynamicObject(serializedUpdate)
41 {
42         RegisterAttribute("notification_command", Attribute_Config, &m_NotificationCommand);
43         RegisterAttribute("notification_interval", Attribute_Config, &m_NotificationInterval);
44         RegisterAttribute("notification_period", Attribute_Config, &m_NotificationPeriod);
45         RegisterAttribute("last_notification", Attribute_Replicated, &m_LastNotification);
46         RegisterAttribute("next_notification", Attribute_Replicated, &m_NextNotification);
47         RegisterAttribute("notification_number", Attribute_Replicated, &m_NotificationNumber);
48         RegisterAttribute("macros", Attribute_Config, &m_Macros);
49         RegisterAttribute("users", Attribute_Config, &m_Users);
50         RegisterAttribute("groups", Attribute_Config, &m_Groups);
51         RegisterAttribute("times", Attribute_Config, &m_Times);
52         RegisterAttribute("notification_type_filter", Attribute_Config, &m_NotificationTypeFilter);
53         RegisterAttribute("notification_state_filter", Attribute_Config, &m_NotificationStateFilter);
54         RegisterAttribute("host_name", Attribute_Config, &m_HostName);
55         RegisterAttribute("service", Attribute_Config, &m_Service);
56         RegisterAttribute("export_macros", Attribute_Config, &m_ExportMacros);
57 }
58
59 Notification::~Notification(void)
60 {
61         Service::InvalidateNotificationsCache();
62 }
63
64 Notification::Ptr Notification::GetByName(const String& name)
65 {
66         DynamicObject::Ptr configObject = DynamicObject::GetObject("Notification", name);
67
68         return dynamic_pointer_cast<Notification>(configObject);
69 }
70
71 Service::Ptr Notification::GetService(void) const
72 {
73         Host::Ptr host = Host::GetByName(m_HostName);
74
75         if (!host)
76                 return Service::Ptr();
77
78         if (m_Service.IsEmpty())
79                 return host->GetHostCheckService();
80         else
81                 return host->GetServiceByShortName(m_Service);
82 }
83
84 NotificationCommand::Ptr Notification::GetNotificationCommand(void) const
85 {
86         return NotificationCommand::GetByName(m_NotificationCommand);
87 }
88
89 Dictionary::Ptr Notification::GetMacros(void) const
90 {
91         return m_Macros;
92 }
93
94 Array::Ptr Notification::GetExportMacros(void) const
95 {
96         return m_ExportMacros;
97 }
98
99 std::set<User::Ptr> Notification::GetUsers(void) const
100 {
101         std::set<User::Ptr> result;
102
103         Array::Ptr users = m_Users;
104
105         if (users) {
106                 ObjectLock olock(users);
107
108                 BOOST_FOREACH(const String& name, users) {
109                         User::Ptr user = User::GetByName(name);
110
111                         if (!user)
112                                 continue;
113
114                         result.insert(user);
115                 }
116         }
117
118         return result;
119 }
120
121 std::set<UserGroup::Ptr> Notification::GetGroups(void) const
122 {
123         std::set<UserGroup::Ptr> result;
124
125         Array::Ptr groups = m_Groups;
126
127         if (groups) {
128                 ObjectLock olock(groups);
129
130                 BOOST_FOREACH(const String& name, groups) {
131                         UserGroup::Ptr ug = UserGroup::GetByName(name);
132
133                         if (!ug)
134                                 continue;
135
136                         result.insert(ug);
137                 }
138         }
139
140         return result;
141 }
142
143 Dictionary::Ptr Notification::GetTimes(void) const
144 {
145         return m_Times;
146 }
147
148 unsigned long Notification::GetNotificationTypeFilter(void) const
149 {
150         if (m_NotificationTypeFilter.IsEmpty())
151                 return ~(unsigned long)0; /* All states. */
152         else
153                 return m_NotificationTypeFilter;
154 }
155
156 unsigned long Notification::GetNotificationStateFilter(void) const
157 {
158         if (m_NotificationStateFilter.IsEmpty())
159                 return ~(unsigned long)0; /* All states. */
160         else
161                 return m_NotificationStateFilter;
162 }
163
164 double Notification::GetNotificationInterval(void) const
165 {
166         if (m_NotificationInterval.IsEmpty())
167                 return 300;
168         else
169                 return m_NotificationInterval;
170 }
171
172 TimePeriod::Ptr Notification::GetNotificationPeriod(void) const
173 {
174         return TimePeriod::GetByName(m_NotificationPeriod);
175 }
176
177 double Notification::GetLastNotification(void) const
178 {
179         if (m_LastNotification.IsEmpty())
180                 return 0;
181         else
182                 return m_LastNotification;
183 }
184
185 /**
186  * Sets the timestamp when the last notification was sent.
187  */
188 void Notification::SetLastNotification(double time)
189 {
190         m_LastNotification = time;
191         Touch("last_notification");
192 }
193
194 double Notification::GetNextNotification(void) const
195 {
196         if (m_NextNotification.IsEmpty())
197                 return 0;
198         else
199                 return m_NextNotification;
200 }
201
202 /**
203  * Sets the timestamp when the next periodical notification should be sent.
204  * This does not affect notifications that are sent for state changes.
205  */
206 void Notification::SetNextNotification(double time)
207 {
208         m_NextNotification = time;
209         Touch("next_notification");
210 }
211
212 int Notification::GetNotificationNumber(void) const
213 {
214         if (m_NotificationNumber.IsEmpty())
215                 return 0;
216         else
217                 return m_NotificationNumber;
218 }
219
220 void Notification::UpdateNotificationNumber(void)
221 {
222         m_NotificationNumber = m_NotificationNumber + 1;
223         Touch("notification_number");
224 }
225
226 void Notification::ResetNotificationNumber(void)
227 {
228         m_NotificationNumber = 0;
229         Touch("notification_number");
230 }
231
232 String Notification::NotificationTypeToString(NotificationType type)
233 {
234         switch (type) {
235                 case NotificationDowntimeStart:
236                         return "DOWNTIMESTART";
237                 case NotificationDowntimeEnd:
238                         return "DOWNTIMEEND";
239                 case NotificationDowntimeRemoved:
240                         return "DOWNTIMECANCELLED";
241                 case NotificationCustom:
242                         return "CUSTOM";
243                 case NotificationAcknowledgement:
244                         return "ACKNOWLEDGEMENT";
245                 case NotificationProblem:
246                         return "PROBLEM";
247                 case NotificationRecovery:
248                         return "RECOVERY";
249                 case NotificationFlappingStart:
250                         return "FLAPPINGSTART";
251                 case NotificationFlappingEnd:
252                         return "FLAPPINGEND";
253                 default:
254                         return "UNKNOWN_NOTIFICATION";
255         }
256 }
257
258 void Notification::BeginExecuteNotification(NotificationType type, const Dictionary::Ptr& cr, bool force, const String& author, const String& text)
259 {
260         ASSERT(!OwnsLock());
261
262         if (!force) {
263                 TimePeriod::Ptr tp = GetNotificationPeriod();
264
265                 if (tp && !tp->IsInside(Utility::GetTime())) {
266                         Log(LogInformation, "icinga", "Not sending notifications for notification object '" + GetName() + "': not in timeperiod");
267                         return;
268                 }
269
270                 double now = Utility::GetTime();
271                 Dictionary::Ptr times = GetTimes();
272                 Service::Ptr service = GetService();
273
274                 if (type == NotificationProblem) {
275                         if (times && times->Contains("begin") && now < service->GetLastHardStateChange() + times->Get("begin")) {
276                                 Log(LogInformation, "icinga", "Not sending notifications for notification object '" + GetName() + "': before escalation range");
277                                 return;
278                         }
279
280                         if (times && times->Contains("end") && now > service->GetLastHardStateChange() + times->Get("end")) {
281                                 Log(LogInformation, "icinga", "Not sending notifications for notification object '" + GetName() + "': after escalation range");
282                                 return;
283                         }
284                 }
285
286                 unsigned long ftype = 1 << type;
287
288                 Log(LogDebug, "icinga", "FType=" + Convert::ToString(ftype) + ", TypeFilter=" + Convert::ToString(GetNotificationTypeFilter()));
289
290                 if (!(ftype & GetNotificationTypeFilter())) {
291                         Log(LogInformation, "icinga", "Not sending notifications for notification object '" + GetName() + "': type filter does not match");
292                         return;
293                 }
294
295                 unsigned long fstate = 1 << GetService()->GetState();
296
297                 if (!(fstate & GetNotificationStateFilter())) {
298                         Log(LogInformation, "icinga", "Not sending notifications for notification object '" + GetName() + "': state filter does not match");
299                         return;
300                 }
301         }
302
303         {
304                 ObjectLock olock(this);
305
306                 SetLastNotification(Utility::GetTime());
307         }
308
309         std::set<User::Ptr> allUsers;
310
311         std::set<User::Ptr> users = GetUsers();
312         std::copy(users.begin(), users.end(), std::inserter(allUsers, allUsers.begin()));
313
314         BOOST_FOREACH(const UserGroup::Ptr& ug, GetGroups()) {
315                 std::set<User::Ptr> members = ug->GetMembers();
316                 std::copy(members.begin(), members.end(), std::inserter(allUsers, allUsers.begin()));
317         }
318
319         BOOST_FOREACH(const User::Ptr& user, allUsers) {
320                 Log(LogDebug, "icinga", "Sending notification for user '" + user->GetName() + "'");
321                 Utility::QueueAsyncCallback(boost::bind(&Notification::ExecuteNotificationHelper, this, type, user, cr, force, author, text));
322         }
323 }
324
325 void Notification::ExecuteNotificationHelper(NotificationType type, const User::Ptr& user, const Dictionary::Ptr& cr, bool force, const String& author, const String& text)
326 {
327         ASSERT(!OwnsLock());
328
329         if (!force) {
330                 TimePeriod::Ptr tp = user->GetNotificationPeriod();
331
332                 if (tp && !tp->IsInside(Utility::GetTime())) {
333                         Log(LogInformation, "icinga", "Not sending notifications for notification object '" +
334                             GetName() + " and user '" + user->GetName() + "': user not in timeperiod");
335                         return;
336                 }
337
338                 unsigned long ftype = 1 << type;
339
340                 if (!(ftype & user->GetNotificationTypeFilter())) {
341                         Log(LogInformation, "icinga", "Not sending notifications for notification object '" +
342                             GetName() + " and user '" + user->GetName() + "': type filter does not match");
343                         return;
344                 }
345
346                 unsigned long fstate = 1 << GetService()->GetState();
347
348                 if (!(fstate & user->GetNotificationStateFilter())) {
349                         Log(LogInformation, "icinga", "Not sending notifications for notification object '" +
350                             GetName() + " and user '" + user->GetName() + "': state filter does not match");
351                         return;
352                 }
353         }
354
355         try {
356                 GetNotificationCommand()->Execute(GetSelf(), user, cr, type);
357
358                 {
359                         ObjectLock olock(this);
360                         UpdateNotificationNumber();
361                         SetLastNotification(Utility::GetTime());
362                 }
363
364                 RequestMessage rm;
365                 rm.SetMethod("icinga::NotificationSent");
366
367                 NotificationMessage params;
368
369                 params.SetService(GetService()->GetName());
370                 params.SetUser(user->GetName());
371                 params.SetType(type);
372                 params.SetAuthor(author);
373                 params.SetCommentText(text);
374                 params.SetCheckResult(cr);
375
376                 rm.SetParams(params);
377
378                 EndpointManager::GetInstance()->SendMulticastMessage(rm);
379
380                 Log(LogInformation, "icinga", "Completed sending notification for service '" + GetService()->GetName() + "'");
381         } catch (const std::exception& ex) {
382                 std::ostringstream msgbuf;
383                 msgbuf << "Exception occured during notification for service '"
384                        << GetService()->GetName() << "': " << boost::diagnostic_information(ex);
385                 String message = msgbuf.str();
386
387                 Log(LogWarning, "icinga", message);
388         }
389 }
390
391 void Notification::OnAttributeChanged(const String& name)
392 {
393         ASSERT(!OwnsLock());
394
395         if (name == "host_name" || name == "service")
396                 Service::InvalidateNotificationsCache();
397 }
398
399 bool Notification::ResolveMacro(const String& macro, const Dictionary::Ptr&, String *result) const
400 {
401         Dictionary::Ptr macros = GetMacros();
402
403         if (macros && macros->Contains(macro)) {
404                 *result = macros->Get(macro);
405                 return true;
406         }
407
408         return false;
409 }