]> granicus.if.org Git - icinga2/blob - lib/icinga/service-notification.cpp
compatlog: refactor custom/acknowledgement notifications with author/commenttext
[icinga2] / lib / icinga / service-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/service.h"
21 #include "icinga/notificationrequestmessage.h"
22 #include "remoting/endpointmanager.h"
23 #include "base/dynamictype.h"
24 #include "base/objectlock.h"
25 #include "base/logger_fwd.h"
26 #include "config/configitembuilder.h"
27 #include <boost/tuple/tuple.hpp>
28 #include <boost/smart_ptr/make_shared.hpp>
29 #include <boost/foreach.hpp>
30 #include <boost/exception/diagnostic_information.hpp>
31
32 using namespace icinga;
33
34 static boost::mutex l_NotificationMutex;
35 static std::map<String, std::set<Notification::WeakPtr> > l_NotificationsCache;
36 static bool l_NotificationsCacheNeedsUpdate = false;
37 static Timer::Ptr l_NotificationsCacheTimer;
38
39 void Service::RequestNotifications(NotificationType type, const Dictionary::Ptr& cr, const String& author, const String& text)
40 {
41         RequestMessage msg;
42         msg.SetMethod("icinga::SendNotifications");
43
44         NotificationRequestMessage params;
45         msg.SetParams(params);
46
47         params.SetService(GetName());
48         params.SetType(type);
49         params.SetCheckResult(cr);
50         params.SetAuthor(author);
51         params.SetText(text);
52
53         Log(LogDebug, "icinga", "Sending notification anycast request for service '" + GetName() + "'");
54         EndpointManager::GetInstance()->SendAnycastMessage(Endpoint::Ptr(), msg);
55 }
56
57 void Service::SendNotifications(NotificationType type, const Dictionary::Ptr& cr, const String& author, const String& text)
58 {
59         bool force = false;
60
61         if (!GetEnableNotifications()) {
62                 if (!GetForceNextNotification()) {
63                         Log(LogInformation, "icinga", "Notifications are disabled for service '" + GetName() + "'.");
64                         return;
65                 }
66
67                 force = true;
68                 SetForceNextNotification(false);
69         }
70
71         Log(LogInformation, "icinga", "Sending notifications for service '" + GetName() + "'");
72
73         std::set<Notification::Ptr> notifications = GetNotifications();
74
75         if (notifications.empty())
76                 Log(LogInformation, "icinga", "Service '" + GetName() + "' does not have any notifications.");
77
78         BOOST_FOREACH(const Notification::Ptr& notification, notifications) {
79                 try {
80                         notification->BeginExecuteNotification(type, cr, force, author, text);
81                 } catch (const std::exception& ex) {
82                         std::ostringstream msgbuf;
83                         msgbuf << "Exception occured during notification for service '"
84                                << GetName() << "': " << boost::diagnostic_information(ex);
85                         String message = msgbuf.str();
86
87                         Log(LogWarning, "icinga", message);
88                 }
89         }
90 }
91
92 void Service::InvalidateNotificationsCache(void)
93 {
94         boost::mutex::scoped_lock lock(l_NotificationMutex);
95
96         if (l_NotificationsCacheNeedsUpdate)
97                 return; /* Someone else has already requested a refresh. */
98
99         if (!l_NotificationsCacheTimer) {
100                 l_NotificationsCacheTimer = boost::make_shared<Timer>();
101                 l_NotificationsCacheTimer->SetInterval(0.5);
102                 l_NotificationsCacheTimer->OnTimerExpired.connect(boost::bind(&Service::RefreshNotificationsCache));
103                 l_NotificationsCacheTimer->Start();
104         }
105
106         l_NotificationsCacheNeedsUpdate = true;
107 }
108
109 void Service::RefreshNotificationsCache(void)
110 {
111         {
112                 boost::mutex::scoped_lock lock(l_NotificationMutex);
113
114                 if (!l_NotificationsCacheNeedsUpdate)
115                         return;
116
117                 l_NotificationsCacheNeedsUpdate = false;
118         }
119
120         Log(LogDebug, "icinga", "Updating Service notifications cache.");
121
122         std::map<String, std::set<Notification::WeakPtr> > newNotificationsCache;
123
124         BOOST_FOREACH(const DynamicObject::Ptr& object, DynamicType::GetObjects("Notification")) {
125                 const Notification::Ptr& notification = static_pointer_cast<Notification>(object);
126
127                 Service::Ptr service = notification->GetService();
128
129                 if (!service)
130                         continue;
131
132                 newNotificationsCache[service->GetName()].insert(notification);
133         }
134
135         boost::mutex::scoped_lock lock(l_NotificationMutex);
136         l_NotificationsCache.swap(newNotificationsCache);
137 }
138
139 std::set<Notification::Ptr> Service::GetNotifications(void) const
140 {
141         std::set<Notification::Ptr> notifications;
142
143         {
144                 boost::mutex::scoped_lock lock(l_NotificationMutex);
145
146                 BOOST_FOREACH(const Notification::WeakPtr& wservice, l_NotificationsCache[GetName()]) {
147                         Notification::Ptr notification = wservice.lock();
148
149                         if (!notification)
150                                 continue;
151
152                         notifications.insert(notification);
153                 }
154         }
155
156         return notifications;
157 }
158
159 void Service::UpdateSlaveNotifications(void)
160 {
161         Dictionary::Ptr oldNotifications;
162         ConfigItem::Ptr serviceItem, hostItem;
163
164         serviceItem = ConfigItem::GetObject("Service", GetName());
165
166         /* Don't create slave notifications unless we own this object */
167         if (!serviceItem)
168                 return;
169
170         Host::Ptr host = GetHost();
171
172         if (!host)
173                 return;
174
175         hostItem = ConfigItem::GetObject("Host", host->GetName());
176
177         /* Don't create slave notifications unless we own the host */
178         if (!hostItem)
179                 return;
180
181         {
182                 ObjectLock olock(this);
183                 oldNotifications = m_SlaveNotifications;
184         }
185
186         std::vector<Dictionary::Ptr> descLists;
187
188         descLists.push_back(Get("notifications"));
189
190         Dictionary::Ptr newNotifications;
191         newNotifications = boost::make_shared<Dictionary>();
192
193         descLists.push_back(host->Get("notifications"));
194
195         for (int i = 0; i < 2; i++) {
196                 Dictionary::Ptr descs;
197                 ConfigItem::Ptr item;
198
199                 if (i == 0) {
200                         /* Host notification descs */
201                         descs = host->Get("notifications");
202                         item = hostItem;
203                 } else {
204                         /* Service notification descs */
205                         descs = Get("notifications");
206                         item = serviceItem;
207                 }
208
209                 if (!descs)
210                         continue;
211
212                 ObjectLock olock(descs);
213
214                 String nfcname;
215                 Value nfcdesc;
216                 BOOST_FOREACH(boost::tie(nfcname, nfcdesc), descs) {
217                         std::ostringstream namebuf;
218                         namebuf << GetName() << ":" << nfcname;
219                         String name = namebuf.str();
220
221                         ConfigItemBuilder::Ptr builder = boost::make_shared<ConfigItemBuilder>(item->GetDebugInfo());
222                         builder->SetType("Notification");
223                         builder->SetName(name);
224                         builder->AddExpression("host_name", OperatorSet, host->GetName());
225                         builder->AddExpression("service", OperatorSet, GetShortName());
226
227                         if (!nfcdesc.IsObjectType<Dictionary>())
228                                 BOOST_THROW_EXCEPTION(std::invalid_argument("Notification description must be a dictionary."));
229
230                         Dictionary::Ptr notification = nfcdesc;
231
232                         Array::Ptr templates = notification->Get("templates");
233
234                         if (templates) {
235                                 ObjectLock tlock(templates);
236
237                                 BOOST_FOREACH(const Value& tmpl, templates) {
238                                         builder->AddParent(tmpl);
239                                 }
240                         }
241
242                         /* Clone attributes from the host/service object. */
243                         std::set<String, string_iless> keys;
244                         keys.insert("users");
245                         keys.insert("groups");
246                         keys.insert("notification_interval");
247                         keys.insert("notification_period");
248                         keys.insert("notification_type_filter");
249                         keys.insert("notification_state_filter");
250                         keys.insert("export_macros");
251
252                         ExpressionList::Ptr svc_exprl = boost::make_shared<ExpressionList>();
253                         item->GetLinkedExpressionList()->ExtractFiltered(keys, svc_exprl);
254                         builder->AddExpressionList(svc_exprl);
255
256                         /* Clone attributes from the notification expression list. */
257                         std::vector<String> path;
258                         path.push_back("notifications");
259                         path.push_back(nfcname);
260
261                         ExpressionList::Ptr nfc_exprl = boost::make_shared<ExpressionList>();
262                         item->GetLinkedExpressionList()->ExtractPath(path, nfc_exprl);
263                         builder->AddExpressionList(nfc_exprl);
264
265                         ConfigItem::Ptr notificationItem = builder->Compile();
266                         notificationItem->Commit();
267
268                         newNotifications->Set(name, notificationItem);
269                 }
270         }
271
272         if (oldNotifications) {
273                 ObjectLock olock(oldNotifications);
274
275                 ConfigItem::Ptr notification;
276                 BOOST_FOREACH(boost::tie(boost::tuples::ignore, notification), oldNotifications) {
277                         if (!notification)
278                                 continue;
279
280                         if (!newNotifications->Contains(notification->GetName()))
281                                 notification->Unregister();
282                 }
283         }
284
285         {
286                 ObjectLock olock(this);
287                 m_SlaveNotifications = newNotifications;
288         }
289 }
290
291 bool Service::GetEnableNotifications(void) const
292 {
293         if (m_EnableNotifications.IsEmpty())
294                 return true;
295         else
296                 return m_EnableNotifications;
297 }
298
299 void Service::SetEnableNotifications(bool enabled)
300 {
301         m_EnableNotifications = enabled;
302         Touch("enable_notifications");
303 }
304
305 bool Service::GetForceNextNotification(void) const
306 {
307         if (m_ForceNextNotification.IsEmpty())
308                 return false;
309
310         return static_cast<bool>(m_ForceNextNotification);
311 }
312
313 void Service::SetForceNextNotification(bool forced)
314 {
315         m_ForceNextNotification = forced ? 1 : 0;
316         Touch("force_next_notification");
317 }