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