]> granicus.if.org Git - icinga2/blob - components/compat/statusdatawriter.cpp
Implement host checks.
[icinga2] / components / compat / statusdatawriter.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2014 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 "compat/statusdatawriter.h"
21 #include "icinga/icingaapplication.h"
22 #include "icinga/cib.h"
23 #include "icinga/hostgroup.h"
24 #include "icinga/servicegroup.h"
25 #include "icinga/checkcommand.h"
26 #include "icinga/eventcommand.h"
27 #include "icinga/timeperiod.h"
28 #include "icinga/notificationcommand.h"
29 #include "icinga/compatutility.h"
30 #include "icinga/dependency.h"
31 #include "base/dynamictype.h"
32 #include "base/objectlock.h"
33 #include "base/convert.h"
34 #include "base/logger_fwd.h"
35 #include "base/exception.h"
36 #include "base/application.h"
37 #include "base/context.h"
38 #include "base/statsfunction.h"
39 #include <boost/foreach.hpp>
40 #include <boost/tuple/tuple.hpp>
41 #include <boost/algorithm/string/replace.hpp>
42 #include <fstream>
43
44 using namespace icinga;
45
46 REGISTER_TYPE(StatusDataWriter);
47
48 REGISTER_STATSFUNCTION(StatusDataWriterStats, &StatusDataWriter::StatsFunc);
49
50 Value StatusDataWriter::StatsFunc(Dictionary::Ptr& status, Dictionary::Ptr& perfdata)
51 {
52         Dictionary::Ptr nodes = make_shared<Dictionary>();
53
54         BOOST_FOREACH(const StatusDataWriter::Ptr& statusdatawriter, DynamicType::GetObjects<StatusDataWriter>()) {
55                 nodes->Set(statusdatawriter->GetName(), 1); //add more stats
56         }
57
58         status->Set("statusdatawriter", nodes);
59
60         return 0;
61 }
62
63 /**
64  * Hint: The reason why we're using "\n" rather than std::endl is because
65  * std::endl also _flushes_ the output stream which severely degrades
66  * performance (see http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt11ch25s02.html).
67  */
68
69 /**
70  * Starts the component.
71  */
72 void StatusDataWriter::Start(void)
73 {
74         DynamicObject::Start();
75
76         m_StatusTimer = make_shared<Timer>();
77         m_StatusTimer->SetInterval(GetUpdateInterval());
78         m_StatusTimer->OnTimerExpired.connect(boost::bind(&StatusDataWriter::StatusTimerHandler, this));
79         m_StatusTimer->Start();
80         m_StatusTimer->Reschedule(0);
81
82         Utility::QueueAsyncCallback(boost::bind(&StatusDataWriter::UpdateObjectsCache, this));
83 }
84
85 void StatusDataWriter::DumpComments(std::ostream& fp, const Checkable::Ptr& checkable)
86 {
87         Dictionary::Ptr comments = checkable->GetComments();
88
89         Host::Ptr host;
90         Service::Ptr service;
91         tie(host, service) = GetHostService(checkable);
92
93         ObjectLock olock(comments);
94
95         BOOST_FOREACH(const Dictionary::Pair& kv, comments) {
96                 Comment::Ptr comment = kv.second;
97
98                 if (comment->IsExpired())
99                         continue;
100
101                 if (service)
102                         fp << "servicecomment {" << "\n"
103                            << "\t" << "service_description=" << service->GetShortName() << "\n";
104                 else
105                         fp << "hostcomment {" << "\n";
106
107                 fp << "\t" "host_name=" << host->GetName() << "\n"
108                       "\t" "comment_id=" << comment->GetLegacyId() << "\n"
109                       "\t" "entry_time=" << comment->GetEntryTime() << "\n"
110                       "\t" "entry_type=" << comment->GetEntryType() << "\n"
111                       "\t" "persistent=" "1" "\n"
112                       "\t" "author=" << comment->GetAuthor() << "\n"
113                       "\t" "comment_data=" << comment->GetText() << "\n"
114                       "\t" "expires=" << (comment->GetExpireTime() != 0 ? 1 : 0) << "\n"
115                       "\t" "expire_time=" << comment->GetExpireTime() << "\n"
116                       "\t" "}" "\n"
117                       "\n";
118         }
119 }
120
121 void StatusDataWriter::DumpTimePeriod(std::ostream& fp, const TimePeriod::Ptr& tp)
122 {
123         fp << "define timeperiod {" "\n"
124               "\t" "timeperiod_name" "\t" << tp->GetName() << "\n"
125               "\t" "alias" "\t" << tp->GetName() << "\n";
126
127         Dictionary::Ptr ranges = tp->GetRanges();
128
129         if (ranges) {
130                 ObjectLock olock(ranges);
131                 BOOST_FOREACH(const Dictionary::Pair& kv, ranges) {
132                         fp << "\t" << kv.first << "\t" << kv.second << "\n";
133                 }
134         }
135
136         fp << "\t" "}" "\n"
137               "\n";
138 }
139
140 void StatusDataWriter::DumpCommand(std::ostream& fp, const Command::Ptr& command)
141 {
142         fp << "define command {" "\n"
143               "\t" "command_name\t";
144
145
146         if (command->GetType() == DynamicType::GetByName("CheckCommand"))
147                 fp << "check_";
148         else if (command->GetType() == DynamicType::GetByName("NotificationCommand"))
149                 fp << "notification_";
150         else if (command->GetType() == DynamicType::GetByName("EventCommand"))
151                 fp << "event_";
152
153         fp << command->GetName() << "\n";
154
155         fp << "\t" "command_line" "\t" << CompatUtility::GetCommandLine(command);
156
157         fp << "\n" "\t" "}" "\n"
158               "\n";
159 }
160
161 void StatusDataWriter::DumpDowntimes(std::ostream& fp, const Checkable::Ptr& checkable)
162 {
163         Dictionary::Ptr downtimes = checkable->GetDowntimes();
164
165         Host::Ptr host;
166         Service::Ptr service;
167         tie(host, service) = GetHostService(checkable);
168
169         ObjectLock olock(downtimes);
170
171         BOOST_FOREACH(const Dictionary::Pair& kv, downtimes) {
172                 Downtime::Ptr downtime = kv.second;
173
174                 if (downtime->IsExpired())
175                         continue;
176
177                 if (service)
178                         fp << "servicedowntime {" << "\n"
179                               "\t" "service_description=" << service->GetShortName() << "\n";
180                 else
181                         fp << "hostdowntime {" "\n";
182
183                 Downtime::Ptr triggeredByObj = Service::GetDowntimeByID(downtime->GetTriggeredBy());
184                 int triggeredByLegacy = 0;
185                 if (triggeredByObj)
186                         triggeredByLegacy = triggeredByObj->GetLegacyId();
187
188                 fp << "\t" << "host_name=" << host->GetName() << "\n"
189                       "\t" "downtime_id=" << downtime->GetLegacyId() << "\n"
190                       "\t" "entry_time=" << downtime->GetEntryTime() << "\n"
191                       "\t" "start_time=" << downtime->GetStartTime() << "\n"
192                       "\t" "end_time=" << downtime->GetEndTime() << "\n"
193                       "\t" "triggered_by=" << triggeredByLegacy << "\n"
194                       "\t" "fixed=" << static_cast<long>(downtime->GetFixed()) << "\n"
195                       "\t" "duration=" << static_cast<long>(downtime->GetDuration()) << "\n"
196                       "\t" "is_in_effect=" << (downtime->IsActive() ? 1 : 0) << "\n"
197                       "\t" "author=" << downtime->GetAuthor() << "\n"
198                       "\t" "comment=" << downtime->GetComment() << "\n"
199                       "\t" "trigger_time=" << downtime->GetTriggerTime() << "\n"
200                       "\t" "}" "\n"
201                       "\n";
202         }
203 }
204
205 void StatusDataWriter::DumpHostStatus(std::ostream& fp, const Host::Ptr& host)
206 {
207         fp << "hoststatus {" << "\n"
208            << "\t" << "host_name=" << host->GetName() << "\n";
209
210         {
211                 ObjectLock olock(host);
212                 DumpCheckableStatusAttrs(fp, host);
213         }
214
215         /* ugly but cgis parse only that */
216         fp << "\t" "last_time_up=" << host->GetLastStateUp() << "\n"
217               "\t" "last_time_down=" << host->GetLastStateDown() << "\n"
218               "\t" "last_time_unreachable=" << host->GetLastStateUnreachable() << "\n";
219
220         fp << "\t" "}" "\n"
221               "\n";
222
223         DumpDowntimes(fp, host);
224         DumpComments(fp, host);
225 }
226
227 void StatusDataWriter::DumpHostObject(std::ostream& fp, const Host::Ptr& host)
228 {
229         String notes = CompatUtility::GetCustomAttributeConfig(host, "notes");
230         String notes_url = CompatUtility::GetCustomAttributeConfig(host, "notes_url");
231         String action_url = CompatUtility::GetCustomAttributeConfig(host, "action_url");
232         String icon_image = CompatUtility::GetCustomAttributeConfig(host, "icon_image");
233         String icon_image_alt = CompatUtility::GetCustomAttributeConfig(host, "icon_image_alt");
234         String statusmap_image = CompatUtility::GetCustomAttributeConfig(host, "statusmap_image");
235
236         fp << "define host {" "\n"
237               "\t" "host_name" "\t" << host->GetName() << "\n"
238               "\t" "display_name" "\t" << host->GetDisplayName() << "\n"
239               "\t" "alias" "\t" << host->GetDisplayName() << "\n"
240               "\t" "address" "\t" << CompatUtility::GetHostAddress(host) << "\n"
241               "\t" "address6" "\t" << CompatUtility::GetHostAddress6(host) << "\n";
242         if (!notes.IsEmpty())
243               fp << "\t" "notes" "\t" << notes << "\n";
244         if (!notes_url.IsEmpty())
245               fp << "\t" "notes_url" "\t" << notes_url << "\n";
246         if (!action_url.IsEmpty())
247               fp << "\t" "action_url" "\t" << action_url << "\n";
248         if (!icon_image.IsEmpty())
249               fp << "\t" "icon_image" "\t" << icon_image << "\n";
250         if (!icon_image_alt.IsEmpty())
251               fp << "\t" "icon_image_alt" "\t" << icon_image_alt << "\n";
252         if (!statusmap_image.IsEmpty())
253               fp << "\t" "statusmap_image" "\t" << statusmap_image << "\n";
254
255         std::set<Checkable::Ptr> parents = host->GetParents();
256
257         if (!parents.empty()) {
258                 fp << "\t" "parents" "\t";
259                 DumpNameList(fp, parents);
260                 fp << "\n";
261         }
262
263         ObjectLock olock(host);
264
265         fp << "\t" "check_interval" "\t" << CompatUtility::GetCheckableCheckInterval(host) << "\n"
266               "\t" "retry_interval" "\t" << CompatUtility::GetCheckableRetryInterval(host) << "\n"
267               "\t" "max_check_attempts" "\t" << host->GetMaxCheckAttempts() << "\n"
268               "\t" "active_checks_enabled" "\t" << CompatUtility::GetCheckableActiveChecksEnabled(host) << "\n"
269               "\t" "passive_checks_enabled" "\t" << CompatUtility::GetCheckablePassiveChecksEnabled(host) << "\n"
270               "\t" "notifications_enabled" "\t" << CompatUtility::GetCheckableNotificationsEnabled(host) << "\n"
271               "\t" "notification_options" "\t" << "d,u,r" << "\n"
272               "\t" "notification_interval" "\t" << CompatUtility::GetCheckableNotificationNotificationInterval(host) << "\n"
273               "\t" "event_handler_enabled" "\t" << CompatUtility::GetCheckableEventHandlerEnabled(host) << "\n";
274
275         CheckCommand::Ptr checkcommand = host->GetCheckCommand();
276         if (checkcommand)
277                 fp << "\t" "check_command" "\t" "check_" << checkcommand->GetName() << "\n";
278
279         EventCommand::Ptr eventcommand = host->GetEventCommand();
280         if (eventcommand)
281                 fp << "\t" "event_handler" "\t" "event_" << eventcommand->GetName() << "\n";
282
283         fp << "\t" "check_period" "\t" << CompatUtility::GetCheckableCheckPeriod(host) << "\n";
284
285         fp << "\t" "contacts" "\t";
286         DumpNameList(fp, CompatUtility::GetCheckableNotificationUsers(host));
287         fp << "\n";
288
289         fp << "\t" "contact_groups" "\t";
290         DumpNameList(fp, CompatUtility::GetCheckableNotificationUserGroups(host));
291         fp << "\n";
292
293         fp << "\t" << "initial_state" "\t" "o" "\n"
294               "\t" "low_flap_threshold" "\t" << host->GetFlappingThreshold() << "\n"
295               "\t" "high_flap_threshold" "\t" << host->GetFlappingThreshold() << "\n"
296               "\t" "process_perf_data" "\t" << CompatUtility::GetCheckableProcessPerformanceData(host) << "\n"
297               "\t" "check_freshness" "\t" "1" "\n";
298
299         fp << "\t" "host_groups" "\t";
300         bool first = true;
301
302         Array::Ptr groups = host->GetGroups();
303
304         if (groups) {
305                 ObjectLock olock(groups);
306
307                 BOOST_FOREACH(const String& name, groups) {
308                         HostGroup::Ptr hg = HostGroup::GetByName(name);
309
310                         if (hg) {
311                                 if (!first)
312                                         fp << ",";
313                                 else
314                                         first = false;
315
316                                 fp << hg->GetName();
317                         }
318                 }
319         }
320
321         fp << "\n";
322
323         DumpCustomAttributes(fp, host);
324
325         fp << "\t" "}" "\n"
326               "\n";
327 }
328
329 void StatusDataWriter::DumpCheckableStatusAttrs(std::ostream& fp, const Checkable::Ptr& checkable)
330 {
331         CheckResult::Ptr cr = checkable->GetLastCheckResult();
332
333         fp << "\t" << "check_command=check_" << CompatUtility::GetCheckableCheckCommand(checkable) << "\n"
334               "\t" "event_handler=event_" << CompatUtility::GetCheckableEventHandler(checkable) << "\n"
335               "\t" "check_period=" << CompatUtility::GetCheckableCheckPeriod(checkable) << "\n"
336               "\t" "check_interval=" << CompatUtility::GetCheckableCheckInterval(checkable) << "\n"
337               "\t" "retry_interval=" << CompatUtility::GetCheckableRetryInterval(checkable) << "\n"
338               "\t" "has_been_checked=" << CompatUtility::GetCheckableHasBeenChecked(checkable) << "\n"
339               "\t" "should_be_scheduled=" << CompatUtility::GetCheckableShouldBeScheduled(checkable) << "\n";
340
341         if (cr) {
342            fp << "\t" << "check_execution_time=" << Convert::ToString(Service::CalculateExecutionTime(cr)) << "\n"
343                  "\t" "check_latency=" << Convert::ToString(Service::CalculateLatency(cr)) << "\n";
344         }
345
346         Host::Ptr host;
347         Service::Ptr service;
348         tie(host, service) = GetHostService(checkable);
349
350         if (service)
351                 fp << "\t" << "current_state=" << service->GetState() << "\n";
352         else
353                 fp << "\t" << "current_state=" << host->GetState() << "\n";
354
355         fp << "\t" "state_type=" << checkable->GetStateType() << "\n"
356               "\t" "plugin_output=" << CompatUtility::GetCheckResultOutput(cr) << "\n"
357               "\t" "long_plugin_output=" << CompatUtility::GetCheckResultLongOutput(cr) << "\n"
358               "\t" "performance_data=" << CompatUtility::GetCheckResultPerfdata(cr) << "\n";
359
360         if (cr) {
361            fp << "\t" << "check_source=" << cr->GetCheckSource() << "\n"
362                  "\t" "last_check=" << static_cast<long>(cr->GetScheduleEnd()) << "\n";
363         }
364
365         fp << "\t" << "next_check=" << static_cast<long>(checkable->GetNextCheck()) << "\n"
366               "\t" "current_attempt=" << checkable->GetCheckAttempt() << "\n"
367               "\t" "max_attempts=" << checkable->GetMaxCheckAttempts() << "\n"
368               "\t" "last_state_change=" << static_cast<long>(checkable->GetLastStateChange()) << "\n"
369               "\t" "last_hard_state_change=" << static_cast<long>(checkable->GetLastHardStateChange()) << "\n"
370               "\t" "last_time_ok=" << static_cast<int>(checkable->GetLastStateOK()) << "\n"
371               "\t" "last_time_warn=" << static_cast<int>(checkable->GetLastStateWarning()) << "\n"
372               "\t" "last_time_critical=" << static_cast<int>(checkable->GetLastStateCritical()) << "\n"
373               "\t" "last_time_unknown=" << static_cast<int>(checkable->GetLastStateUnknown()) << "\n"
374               "\t" "last_update=" << static_cast<long>(time(NULL)) << "\n"
375               "\t" "notifications_enabled=" << CompatUtility::GetCheckableNotificationsEnabled(checkable) << "\n"
376               "\t" "active_checks_enabled=" << CompatUtility::GetCheckableActiveChecksEnabled(checkable) << "\n"
377               "\t" "passive_checks_enabled=" << CompatUtility::GetCheckablePassiveChecksEnabled(checkable) << "\n"
378               "\t" "flap_detection_enabled=" << CompatUtility::GetCheckableFlapDetectionEnabled(checkable) << "\n"
379               "\t" "is_flapping=" << CompatUtility::GetCheckableIsFlapping(checkable) << "\n"
380               "\t" "percent_state_change=" << CompatUtility::GetCheckablePercentStateChange(checkable) << "\n"
381               "\t" "problem_has_been_acknowledged=" << CompatUtility::GetCheckableProblemHasBeenAcknowledged(checkable) << "\n"
382               "\t" "acknowledgement_type=" << CompatUtility::GetCheckableAcknowledgementType(checkable) << "\n"
383               "\t" "acknowledgement_end_time=" << checkable->GetAcknowledgementExpiry() << "\n"
384               "\t" "scheduled_downtime_depth=" << checkable->GetDowntimeDepth() << "\n"
385               "\t" "last_notification=" << CompatUtility::GetCheckableNotificationLastNotification(checkable) << "\n"
386               "\t" "next_notification=" << CompatUtility::GetCheckableNotificationNextNotification(checkable) << "\n"
387               "\t" "current_notification_number=" << CompatUtility::GetCheckableNotificationNotificationNumber(checkable) << "\n"
388               "\t" "modified_attributes=" << checkable->GetModifiedAttributes() << "\n";
389 }
390
391 void StatusDataWriter::DumpServiceStatus(std::ostream& fp, const Service::Ptr& service)
392 {
393         Host::Ptr host = service->GetHost();
394
395         fp << "servicestatus {" "\n"
396               "\t" "host_name=" << host->GetName() << "\n"
397               "\t" "service_description=" << service->GetShortName() << "\n";
398
399         {
400                 ObjectLock olock(service);
401                 DumpCheckableStatusAttrs(fp, service);
402         }
403
404         fp << "\t" "}" "\n"
405               "\n";
406
407         DumpDowntimes(fp, service);
408         DumpComments(fp, service);
409 }
410
411 void StatusDataWriter::DumpServiceObject(std::ostream& fp, const Service::Ptr& service)
412 {
413         Host::Ptr host = service->GetHost();
414
415         {
416                 ObjectLock olock(service);
417
418                 fp << "define service {" "\n"
419                       "\t" "host_name" "\t" << host->GetName() << "\n"
420                       "\t" "service_description" "\t" << service->GetShortName() << "\n"
421                       "\t" "display_name" "\t" << service->GetDisplayName() << "\n"
422                       "\t" "check_period" "\t" << CompatUtility::GetCheckableCheckPeriod(service) << "\n"
423                       "\t" "check_interval" "\t" << CompatUtility::GetCheckableCheckInterval(service) << "\n"
424                       "\t" "retry_interval" "\t" << CompatUtility::GetCheckableRetryInterval(service) << "\n"
425                       "\t" "max_check_attempts" "\t" << service->GetMaxCheckAttempts() << "\n"
426                       "\t" "active_checks_enabled" "\t" << CompatUtility::GetCheckableActiveChecksEnabled(service) << "\n"
427                       "\t" "passive_checks_enabled" "\t" << CompatUtility::GetCheckablePassiveChecksEnabled(service) << "\n"
428                       "\t" "flap_detection_enabled" "\t" << CompatUtility::GetCheckableFlapDetectionEnabled(service) << "\n"
429                       "\t" "is_volatile" "\t" << CompatUtility::GetCheckableIsVolatile(service) << "\n"
430                       "\t" "notifications_enabled" "\t" << CompatUtility::GetCheckableNotificationsEnabled(service) << "\n"
431                       "\t" "notification_options" "\t" << CompatUtility::GetCheckableNotificationNotificationOptions(service) << "\n"
432                       "\t" "notification_interval" "\t" << CompatUtility::GetCheckableNotificationNotificationInterval(service) << "\n"
433                       "\t" "notification_period" "\t" << CompatUtility::GetCheckableNotificationNotificationPeriod(service) << "\n"
434                       "\t" "event_handler_enabled" "\t" << CompatUtility::GetCheckableEventHandlerEnabled(service) << "\n";
435
436                 CheckCommand::Ptr checkcommand = service->GetCheckCommand();
437                 if (checkcommand)
438                         fp << "\t" "check_command" "\t" "check_" << checkcommand->GetName() << "\n";
439
440                 EventCommand::Ptr eventcommand = service->GetEventCommand();
441                 if (eventcommand)
442                         fp << "\t" "event_handler" "\t" "event_" << eventcommand->GetName() << "\n";
443
444                 fp << "\t" "contacts" "\t";
445                 DumpNameList(fp, CompatUtility::GetCheckableNotificationUsers(service));
446                 fp << "\n";
447
448                 fp << "\t" "contact_groups" "\t";
449                 DumpNameList(fp, CompatUtility::GetCheckableNotificationUserGroups(service));
450                 fp << "\n";
451
452                 String notes = CompatUtility::GetCustomAttributeConfig(service, "notes");
453                 String notes_url = CompatUtility::GetCustomAttributeConfig(service, "notes_url");
454                 String action_url = CompatUtility::GetCustomAttributeConfig(service, "action_url");
455                 String icon_image = CompatUtility::GetCustomAttributeConfig(service, "icon_image");
456                 String icon_image_alt = CompatUtility::GetCustomAttributeConfig(service, "icon_image_alt");
457
458                 fp << "\t" "initial_state" "\t" "o" "\n"
459                       "\t" "low_flap_threshold" "\t" << service->GetFlappingThreshold() << "\n"
460                       "\t" "high_flap_threshold" "\t" << service->GetFlappingThreshold() << "\n"
461                       "\t" "process_perf_data" "\t" << CompatUtility::GetCheckableProcessPerformanceData(service) << "\n"
462                       "\t" "check_freshness" << "\t" "1" "\n";
463                 if (!notes.IsEmpty())
464                       fp << "\t" "notes" "\t" << notes << "\n";
465                 if (!notes_url.IsEmpty())
466                       fp << "\t" "notes_url" "\t" << notes_url << "\n";
467                 if (!action_url.IsEmpty())
468                       fp << "\t" "action_url" "\t" << action_url << "\n";
469                 if (!icon_image.IsEmpty())
470                       fp << "\t" "icon_image" "\t" << icon_image << "\n";
471                 if (!icon_image_alt.IsEmpty())
472                       fp << "\t" "icon_image_alt" "\t" << icon_image_alt << "\n";
473         }
474
475         fp << "\t" "service_groups" "\t";
476         bool first = true;
477
478         Array::Ptr groups = service->GetGroups();
479
480         if (groups) {
481                 ObjectLock olock(groups);
482
483                 BOOST_FOREACH(const String& name, groups) {
484                         ServiceGroup::Ptr sg = ServiceGroup::GetByName(name);
485
486                         if (sg) {
487                                 if (!first)
488                                         fp << ",";
489                                 else
490                                         first = false;
491
492                                 fp << sg->GetName();
493                         }
494                 }
495         }
496
497         fp << "\n";
498
499         DumpCustomAttributes(fp, service);
500
501         fp << "\t" "}" "\n"
502               "\n";
503 }
504
505 void StatusDataWriter::DumpCustomAttributes(std::ostream& fp, const DynamicObject::Ptr& object)
506 {
507         Dictionary::Ptr vars = object->GetVars();
508
509         if (!vars)
510                 return;
511
512         ObjectLock olock(vars);
513         BOOST_FOREACH(const Dictionary::Pair& kv, vars) {
514                 if (!kv.first.IsEmpty()) {
515                         fp << "\t";
516
517                         if (kv.first != "notes" && kv.first != "action_url" && kv.first != "notes_url" &&
518                             kv.first != "icon_image" && kv.first != "icon_image_alt" && kv.first != "statusmap_image" && kv.first != "2d_coords")
519                                 fp << "_";
520
521                         fp << kv.first << "\t" << kv.second << "\n";
522                 }
523         }
524 }
525
526 void StatusDataWriter::UpdateObjectsCache(void)
527 {
528         CONTEXT("Writing objects.cache file");
529
530         String objectspath = GetObjectsPath();
531         String objectspathtmp = objectspath + ".tmp";
532
533         std::ofstream objectfp;
534         objectfp.open(objectspathtmp.CStr(), std::ofstream::out | std::ofstream::trunc);
535
536         objectfp << std::fixed;
537
538         objectfp << "# Icinga objects cache file" "\n"
539                     "# This file is auto-generated. Do not modify this file." "\n"
540                     "\n";
541
542         BOOST_FOREACH(const Host::Ptr& host, DynamicType::GetObjects<Host>()) {
543                 std::ostringstream tempobjectfp;
544                 tempobjectfp << std::fixed;
545                 DumpHostObject(tempobjectfp, host);
546                 objectfp << tempobjectfp.str();
547
548                 BOOST_FOREACH(const Service::Ptr& service, host->GetServices()) {
549                         std::ostringstream tempobjectfp;
550                         tempobjectfp << std::fixed;
551                         DumpServiceObject(tempobjectfp, service);
552                         objectfp << tempobjectfp.str();
553                 }
554         }
555
556         BOOST_FOREACH(const HostGroup::Ptr& hg, DynamicType::GetObjects<HostGroup>()) {
557                 std::ostringstream tempobjectfp;
558                 tempobjectfp << std::fixed;
559
560                 tempobjectfp << "define hostgroup {" "\n"
561                                 "\t" "hostgroup_name" "\t" << hg->GetName() << "\n";
562
563                 DumpCustomAttributes(tempobjectfp, hg);
564
565                 tempobjectfp << "\t" "members" "\t";
566                 DumpNameList(tempobjectfp, hg->GetMembers());
567                 tempobjectfp << "\n"
568                                 "\t" "}" "\n";
569
570                 objectfp << tempobjectfp.str();
571         }
572
573         BOOST_FOREACH(const ServiceGroup::Ptr& sg, DynamicType::GetObjects<ServiceGroup>()) {
574                 std::ostringstream tempobjectfp;
575                 tempobjectfp << std::fixed;
576
577                 tempobjectfp << "define servicegroup {" "\n"
578                                 "\t" "servicegroup_name" "\t" << sg->GetName() << "\n";
579
580                 DumpCustomAttributes(tempobjectfp, sg);
581
582                 tempobjectfp << "\t" "members" "\t";
583
584                 std::vector<String> sglist;
585                 BOOST_FOREACH(const Service::Ptr& service, sg->GetMembers()) {
586                         Host::Ptr host = service->GetHost();
587
588                         sglist.push_back(host->GetName());
589                         sglist.push_back(service->GetShortName());
590                 }
591
592                 DumpStringList(tempobjectfp, sglist);
593
594                 tempobjectfp << "\n"
595                                 "}" "\n";
596
597                 objectfp << tempobjectfp.str();
598         }
599
600         BOOST_FOREACH(const User::Ptr& user, DynamicType::GetObjects<User>()) {
601                 std::ostringstream tempobjectfp;
602                 tempobjectfp << std::fixed;
603
604                 tempobjectfp << "define contact {" "\n"
605                                 "\t" "contact_name" "\t" << user->GetName() << "\n"
606                                 "\t" "alias" "\t" << user->GetDisplayName() << "\n"
607                                 "\t" "service_notification_options" "\t" "w,u,c,r,f,s" "\n"
608                                 "\t" "host_notification_options""\t" "d,u,r,f,s" "\n"
609                                 "\t" "host_notifications_enabled" "\t" "1" "\n"
610                                 "\t" "service_notifications_enabled" "\t" "1" "\n"
611                                 "\t" "}" "\n"
612                                 "\n";
613
614                 objectfp << tempobjectfp.str();
615         }
616
617         BOOST_FOREACH(const UserGroup::Ptr& ug, DynamicType::GetObjects<UserGroup>()) {
618                 std::ostringstream tempobjectfp;
619                 tempobjectfp << std::fixed;
620
621                 tempobjectfp << "define contactgroup {" "\n"
622                                 "\t" "contactgroup_name" "\t" << ug->GetName() << "\n"
623                                 "\t" "alias" "\t" << ug->GetDisplayName() << "\n";
624
625                 tempobjectfp << "\t" "members" "\t";
626                 DumpNameList(tempobjectfp, ug->GetMembers());
627                 tempobjectfp << "\n"
628                                 "\t" "}" "\n";
629
630                 objectfp << tempobjectfp.str();
631         }
632
633         BOOST_FOREACH(const Command::Ptr& command, DynamicType::GetObjects<CheckCommand>()) {
634                 DumpCommand(objectfp, command);
635         }
636
637         BOOST_FOREACH(const Command::Ptr& command, DynamicType::GetObjects<NotificationCommand>()) {
638                 DumpCommand(objectfp, command);
639         }
640
641         BOOST_FOREACH(const Command::Ptr& command, DynamicType::GetObjects<EventCommand>()) {
642                 DumpCommand(objectfp, command);
643         }
644
645         BOOST_FOREACH(const TimePeriod::Ptr& tp, DynamicType::GetObjects<TimePeriod>()) {
646                 DumpTimePeriod(objectfp, tp);
647         }
648
649         BOOST_FOREACH(const Dependency::Ptr& dep, DynamicType::GetObjects<Dependency>()) {
650                 Checkable::Ptr parent = dep->GetParent();
651
652                 if (!parent)
653                         continue;
654
655                 Host::Ptr parent_host;
656                 Service::Ptr parent_service;
657                 tie(parent_host, parent_service) = GetHostService(parent);
658
659                 if (!parent_service)
660                         continue;
661
662                 Checkable::Ptr child = dep->GetChild();
663
664                 if (!child)
665                         continue;
666
667                 Host::Ptr child_host;
668                 Service::Ptr child_service;
669                 tie(child_host, child_service) = GetHostService(child);
670
671                 if (!child_service)
672                         continue;
673
674                 objectfp << "define servicedependency {" "\n"
675                             "\t" "dependent_host_name" "\t" << child_service->GetHost()->GetName() << "\n"
676                             "\t" "dependent_service_description" "\t" << child_service->GetShortName() << "\n"
677                             "\t" "host_name" "\t" << parent_service->GetHost()->GetName() << "\n"
678                             "\t" "service_description" "\t" << parent_service->GetShortName() << "\n"
679                             "\t" "execution_failure_criteria" "\t" "n" "\n"
680                             "\t" "notification_failure_criteria" "\t" "w,u,c" "\n"
681                             "\t" "}" "\n"
682                             "\n";
683         }
684
685         objectfp.close();
686
687 #ifdef _WIN32
688         _unlink(objectspath.CStr());
689 #endif /* _WIN32 */
690
691         if (rename(objectspathtmp.CStr(), objectspath.CStr()) < 0) {
692                 BOOST_THROW_EXCEPTION(posix_error()
693                     << boost::errinfo_api_function("rename")
694                     << boost::errinfo_errno(errno)
695                     << boost::errinfo_file_name(objectspathtmp));
696         }
697 }
698
699 /**
700  * Periodically writes the status.dat and objects.cache files.
701  */
702 void StatusDataWriter::StatusTimerHandler(void)
703 {
704         Log(LogInformation, "compat", "Writing status.dat file");
705
706         String statuspath = GetStatusPath();
707         String statuspathtmp = statuspath + ".tmp"; /* XXX make this a global definition */
708
709         std::ofstream statusfp;
710         statusfp.open(statuspathtmp.CStr(), std::ofstream::out | std::ofstream::trunc);
711
712         statusfp << std::fixed;
713
714         statusfp << "# Icinga status file" "\n"
715                     "# This file is auto-generated. Do not modify this file." "\n"
716                     "\n";
717
718         statusfp << "info {" "\n"
719                     "\t" "created=" << Utility::GetTime() << "\n"
720                     "\t" "version=" << Application::GetVersion() << "\n"
721                     "\t" "}" "\n"
722                     "\n";
723
724         statusfp << "programstatus {" "\n"
725                     "\t" "icinga_pid=" << Utility::GetPid() << "\n"
726                     "\t" "daemon_mode=1" "\n"
727                     "\t" "program_start=" << static_cast<long>(Application::GetStartTime()) << "\n"
728                     "\t" "active_service_checks_enabled=" << (IcingaApplication::GetInstance()->GetEnableChecks() ? 1 : 0) << "\n"
729                     "\t" "passive_service_checks_enabled=1" "\n"
730                     "\t" "active_host_checks_enabled=1" "\n"
731                     "\t" "passive_host_checks_enabled=1" "\n"
732                     "\t" "check_service_freshness=1" "\n"
733                     "\t" "check_host_freshness=1" "\n"
734                     "\t" "enable_notifications=" << (IcingaApplication::GetInstance()->GetEnableNotifications() ? 1 : 0) << "\n"
735                     "\t" "enable_flap_detection=" << (IcingaApplication::GetInstance()->GetEnableFlapping() ? 1 : 0) << "\n"
736                     "\t" "enable_failure_prediction=0" "\n"
737                     "\t" "process_performance_data=" << (IcingaApplication::GetInstance()->GetEnablePerfdata() ? 1 : 0) << "\n"
738                     "\t" "active_scheduled_service_check_stats=" << CIB::GetActiveChecksStatistics(60) << "," << CIB::GetActiveChecksStatistics(5 * 60) << "," << CIB::GetActiveChecksStatistics(15 * 60) << "\n"
739                     "\t" "passive_service_check_stats=" << CIB::GetPassiveChecksStatistics(60) << "," << CIB::GetPassiveChecksStatistics(5 * 60) << "," << CIB::GetPassiveChecksStatistics(15 * 60) << "\n"
740                     "\t" "next_downtime_id=" << Service::GetNextDowntimeID() << "\n"
741                     "\t" "next_comment_id=" << Service::GetNextCommentID() << "\n"
742                     "\t" "}" "\n"
743                     "\n";
744
745         BOOST_FOREACH(const Host::Ptr& host, DynamicType::GetObjects<Host>()) {
746                 std::ostringstream tempstatusfp;
747                 tempstatusfp << std::fixed;
748                 DumpHostStatus(tempstatusfp, host);
749                 statusfp << tempstatusfp.str();
750
751                 BOOST_FOREACH(const Service::Ptr& service, host->GetServices()) {
752                         std::ostringstream tempstatusfp;
753                         tempstatusfp << std::fixed;
754                         DumpServiceStatus(tempstatusfp, service);
755                         statusfp << tempstatusfp.str();
756                 }
757         }
758
759         statusfp.close();
760
761 #ifdef _WIN32
762         _unlink(statuspath.CStr());
763 #endif /* _WIN32 */
764
765         if (rename(statuspathtmp.CStr(), statuspath.CStr()) < 0) {
766                 BOOST_THROW_EXCEPTION(posix_error()
767                     << boost::errinfo_api_function("rename")
768                     << boost::errinfo_errno(errno)
769                     << boost::errinfo_file_name(statuspathtmp));
770         }
771
772         Log(LogInformation, "compat", "Finished writing status.dat file");
773 }
774