]> granicus.if.org Git - icinga2/blob - lib/icinga/host.cpp
Implemented stacktrace support for Windows.
[icinga2] / lib / icinga / host.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 "i2-icinga.h"
21
22 using namespace icinga;
23
24 boost::mutex Host::m_ServiceMutex;
25 map<String, map<String, Service::WeakPtr> > Host::m_ServicesCache;
26 bool Host::m_ServicesCacheNeedsUpdate = false;
27 Timer::Ptr Host::m_ServicesCacheTimer;
28
29 REGISTER_SCRIPTFUNCTION("ValidateServiceDictionary", &Host::ValidateServiceDictionary);
30
31 REGISTER_TYPE(Host);
32
33 Host::Host(const Dictionary::Ptr& properties)
34         : DynamicObject(properties)
35 {
36         RegisterAttribute("display_name", Attribute_Config, &m_DisplayName);
37         RegisterAttribute("hostgroups", Attribute_Config, &m_HostGroups);
38         RegisterAttribute("macros", Attribute_Config, &m_Macros);
39         RegisterAttribute("hostdependencies", Attribute_Config, &m_HostDependencies);
40         RegisterAttribute("servicedependencies", Attribute_Config, &m_ServiceDependencies);
41         RegisterAttribute("hostcheck", Attribute_Config, &m_HostCheck);
42
43 }
44
45 Host::~Host(void)
46 {
47         HostGroup::InvalidateMembersCache();
48
49         if (m_SlaveServices) {
50                 ConfigItem::Ptr service;
51                 BOOST_FOREACH(tie(tuples::ignore, service), m_SlaveServices) {
52                         service->Unregister();
53                 }
54         }
55 }
56
57 void Host::OnRegistrationCompleted(void)
58 {
59         assert(!OwnsLock());
60
61         DynamicObject::OnRegistrationCompleted();
62
63         Host::InvalidateServicesCache();
64         UpdateSlaveServices();
65 }
66
67 String Host::GetDisplayName(void) const
68 {
69         if (!m_DisplayName.IsEmpty())
70                 return m_DisplayName;
71         else
72                 return GetName();
73 }
74
75 /**
76  * @threadsafety Always.
77  */
78 Host::Ptr Host::GetByName(const String& name)
79 {
80         DynamicObject::Ptr configObject = DynamicObject::GetObject("Host", name);
81
82         return dynamic_pointer_cast<Host>(configObject);
83 }
84
85 Dictionary::Ptr Host::GetGroups(void) const
86 {
87         return m_HostGroups;;
88 }
89
90 Dictionary::Ptr Host::GetMacros(void) const
91 {
92         return m_Macros;
93 }
94
95 Dictionary::Ptr Host::GetHostDependencies(void) const
96 {
97         return m_HostDependencies;;
98 }
99
100 Dictionary::Ptr Host::GetServiceDependencies(void) const
101 {
102         return m_ServiceDependencies;
103 }
104
105 String Host::GetHostCheck(void) const
106 {
107         return m_HostCheck;
108 }
109
110 bool Host::IsReachable(void) const
111 {
112         assert(!OwnsLock());
113
114         set<Service::Ptr> parentServices = GetParentServices();
115
116         BOOST_FOREACH(const Service::Ptr& service, parentServices) {
117                 ObjectLock olock(service);
118
119                 /* ignore pending services */
120                 if (!service->GetLastCheckResult())
121                         continue;
122
123                 /* ignore soft states */
124                 if (service->GetStateType() == StateTypeSoft)
125                         continue;
126
127                 /* ignore services states OK and Warning */
128                 if (service->GetState() == StateOK ||
129                     service->GetState() == StateWarning)
130                         continue;
131
132                 return false;
133         }
134
135         set<Host::Ptr> parentHosts = GetParentHosts();
136
137         BOOST_FOREACH(const Host::Ptr& host, parentHosts) {
138                 Service::Ptr hc = host->GetHostCheckService();
139
140                 /* ignore hosts that don't have a hostcheck */
141                 if (!hc)
142                         continue;
143
144                 ObjectLock olock(hc);
145
146                 /* ignore soft states */
147                 if (hc->GetStateType() == StateTypeSoft)
148                         continue;
149
150                 /* ignore hosts that are up */
151                 if (hc->GetState() == StateOK)
152                         continue;
153
154                 return false;
155         }
156
157         return true;
158 }
159
160 template<bool copyServiceAttrs, typename TDict>
161 static void CopyServiceAttributes(TDict serviceDesc, const ConfigItemBuilder::Ptr& builder)
162 {
163         /* TODO: we only need to copy macros if this is an inline definition,
164          * i.e. "typeid(serviceDesc)" != Service, however for now we just
165          * copy them anyway. */
166         Value macros = serviceDesc->Get("macros");
167         if (!macros.IsEmpty())
168                 builder->AddExpression("macros", OperatorPlus, macros);
169
170         Value checkInterval = serviceDesc->Get("check_interval");
171         if (!checkInterval.IsEmpty())
172                 builder->AddExpression("check_interval", OperatorSet, checkInterval);
173
174         Value retryInterval = serviceDesc->Get("retry_interval");
175         if (!retryInterval.IsEmpty())
176                 builder->AddExpression("retry_interval", OperatorSet, retryInterval);
177
178         Value sgroups = serviceDesc->Get("servicegroups");
179         if (!sgroups.IsEmpty())
180                 builder->AddExpression("servicegroups", OperatorPlus, sgroups);
181
182         Value checkers = serviceDesc->Get("checkers");
183         if (!checkers.IsEmpty())
184                 builder->AddExpression("checkers", OperatorSet, checkers);
185
186         Value short_name = serviceDesc->Get("short_name");
187         if (!short_name.IsEmpty())
188                 builder->AddExpression("short_name", OperatorSet, short_name);
189
190         Value notification_interval = serviceDesc->Get("notification_interval");
191         if (!notification_interval.IsEmpty())
192                 builder->AddExpression("notification_interval", OperatorSet, notification_interval);
193
194         if (copyServiceAttrs) {
195                 Value servicedependencies = serviceDesc->Get("servicedependencies");
196                 if (!servicedependencies.IsEmpty())
197                         builder->AddExpression("servicedependencies", OperatorPlus, servicedependencies);
198
199                 Value hostdependencies = serviceDesc->Get("hostdependencies");
200                 if (!hostdependencies.IsEmpty())
201                         builder->AddExpression("hostdependencies", OperatorPlus, hostdependencies);
202         }
203 }
204
205 void Host::UpdateSlaveServices(void)
206 {
207         assert(!OwnsLock());
208
209         ConfigItem::Ptr item = ConfigItem::GetObject("Host", GetName());
210
211         /* Don't create slave services unless we own this object
212          * and it's not a template. */
213         if (!item || IsAbstract())
214                 return;
215
216         Dictionary::Ptr oldServices = m_SlaveServices;
217         Dictionary::Ptr serviceDescs = Get("services");
218
219         Dictionary::Ptr newServices = boost::make_shared<Dictionary>();
220
221         if (serviceDescs) {
222                 ObjectLock olock(serviceDescs);
223                 String svcname;
224                 Value svcdesc;
225                 BOOST_FOREACH(tie(svcname, svcdesc), serviceDescs) {
226                         if (svcdesc.IsScalar())
227                                 svcname = svcdesc;
228
229                         stringstream namebuf;
230                         namebuf << GetName() << "-" << svcname;
231                         String name = namebuf.str();
232
233                         ConfigItemBuilder::Ptr builder = boost::make_shared<ConfigItemBuilder>(item->GetDebugInfo());
234                         builder->SetType("Service");
235                         builder->SetName(name);
236                         builder->AddExpression("host_name", OperatorSet, GetName());
237                         builder->AddExpression("display_name", OperatorSet, svcname);
238                         builder->AddExpression("short_name", OperatorSet, svcname);
239
240                         CopyServiceAttributes<false>(this, builder);
241
242                         if (svcdesc.IsScalar()) {
243                                 builder->AddParent(svcdesc);
244                         } else if (svcdesc.IsObjectType<Dictionary>()) {
245                                 Dictionary::Ptr service = svcdesc;
246
247                                 Dictionary::Ptr templates = service->Get("templates");
248
249                                 if (templates) {
250                                         ObjectLock olock(templates);
251
252                                         String tmpl;
253                                         BOOST_FOREACH(tie(tuples::ignore, tmpl), templates) {
254                                                 builder->AddParent(tmpl);
255                                         }
256                                 } else {
257                                         builder->AddParent(svcname);
258                                 }
259
260                                 CopyServiceAttributes<true>(service, builder);
261                         } else {
262                                 BOOST_THROW_EXCEPTION(invalid_argument("Service description must be either a string or a dictionary."));
263                         }
264
265                         ConfigItem::Ptr serviceItem = builder->Compile();
266                         DynamicObject::Ptr dobj = serviceItem->Commit();
267
268                         newServices->Set(name, serviceItem);
269                 }
270         }
271
272         if (oldServices) {
273                 ObjectLock olock(oldServices);
274
275                 ConfigItem::Ptr service;
276                 BOOST_FOREACH(tie(tuples::ignore, service), oldServices) {
277                         if (!service)
278                                 continue;
279
280                         if (!newServices->Contains(service->GetName()))
281                                 service->Unregister();
282                 }
283         }
284
285         newServices->Seal();
286
287         Set("slave_services", newServices);
288 }
289
290 void Host::OnAttributeChanged(const String& name)
291 {
292         assert(!OwnsLock());
293
294         if (name == "hostgroups")
295                 HostGroup::InvalidateMembersCache();
296         else if (name == "services") {
297                 UpdateSlaveServices();
298         } else if (name == "notifications") {
299                 BOOST_FOREACH(const Service::Ptr& service, GetServices()) {
300                         service->UpdateSlaveNotifications();
301                 }
302         }
303 }
304
305 set<Service::Ptr> Host::GetServices(void) const
306 {
307         set<Service::Ptr> services;
308
309         boost::mutex::scoped_lock lock(m_ServiceMutex);
310
311         Service::WeakPtr wservice;
312         BOOST_FOREACH(tie(tuples::ignore, wservice), m_ServicesCache[GetName()]) {
313                 Service::Ptr service = wservice.lock();
314
315                 if (!service)
316                         continue;
317
318                 services.insert(service);
319         }
320
321         return services;
322 }
323
324 void Host::InvalidateServicesCache(void)
325 {
326         {
327                 boost::mutex::scoped_lock lock(m_ServiceMutex);
328
329                 if (m_ServicesCacheNeedsUpdate)
330                         return; /* Someone else has already requested a refresh. */
331
332                 if (!m_ServicesCacheTimer) {
333                         m_ServicesCacheTimer = boost::make_shared<Timer>();
334                         m_ServicesCacheTimer->SetInterval(0.5);
335                         m_ServicesCacheTimer->OnTimerExpired.connect(boost::bind(&Host::RefreshServicesCache));
336                         m_ServicesCacheTimer->Start();
337                 }
338
339                 m_ServicesCacheNeedsUpdate = true;
340         }
341 }
342
343 void Host::RefreshServicesCache(void)
344 {
345         {
346                 boost::mutex::scoped_lock lock(m_ServiceMutex);
347
348                 if (!m_ServicesCacheNeedsUpdate)
349                         return;
350
351                 m_ServicesCacheNeedsUpdate = false;
352         }
353
354         Logger::Write(LogInformation, "icinga", "Updating Host services cache.");
355
356         map<String, map<String, Service::WeakPtr> > newServicesCache;
357
358         BOOST_FOREACH(const DynamicObject::Ptr& object, DynamicType::GetObjects("Service")) {
359                 const Service::Ptr& service = static_pointer_cast<Service>(object);
360
361                 Host::Ptr host = service->GetHost();
362
363                 if (!host)
364                         continue;
365
366                 // TODO: assert for duplicate short_names
367
368                 newServicesCache[host->GetName()][service->GetShortName()] = service;
369         }
370
371         boost::mutex::scoped_lock lock(m_ServiceMutex);
372         m_ServicesCache.swap(newServicesCache);
373 }
374
375 void Host::ValidateServiceDictionary(const ScriptTask::Ptr& task, const vector<Value>& arguments)
376 {
377         if (arguments.size() < 1)
378                 BOOST_THROW_EXCEPTION(invalid_argument("Missing argument: Location must be specified."));
379
380         if (arguments.size() < 2)
381                 BOOST_THROW_EXCEPTION(invalid_argument("Missing argument: Attribute dictionary must be specified."));
382
383         String location = arguments[0];
384         Dictionary::Ptr attrs = arguments[1];
385         ObjectLock olock(attrs);
386
387         String key;
388         Value value;
389         BOOST_FOREACH(tie(key, value), attrs) {
390                 String name;
391
392                 if (value.IsScalar()) {
393                         name = value;
394                 } else if (value.IsObjectType<Dictionary>()) {
395                         Dictionary::Ptr serviceDesc = value;
396
397                         name = serviceDesc->Get("service");
398
399                         if (name.IsEmpty())
400                                 name = key;
401                 } else {
402                         continue;
403                 }
404
405                 ConfigItem::Ptr item;
406
407                 ConfigCompilerContext *context = ConfigCompilerContext::GetContext();
408
409                 if (context)
410                         item = context->GetItem("Service", name);
411
412                 /* ignore already active objects while we're in the compiler
413                  * context and linking to existing items is disabled. */
414                 if (!item && (!context || (context->GetFlags() & CompilerLinkExisting)))
415                         item = ConfigItem::GetObject("Service", name);
416
417                 if (!item) {
418                         ConfigCompilerContext::GetContext()->AddError(false, "Validation failed for " +
419                             location + ": Service '" + name + "' not found.");
420                 }
421         }
422
423         task->FinishResult(Empty);
424 }
425
426 Service::Ptr Host::GetServiceByShortName(const Value& name) const
427 {
428         if (name.IsScalar()) {
429                 {
430                         boost::mutex::scoped_lock lock(m_ServiceMutex);
431
432                         map<String, Service::WeakPtr>& services = m_ServicesCache[GetName()];
433                         map<String, Service::WeakPtr>::iterator it = services.find(name);
434
435                         if (it != services.end()) {
436                                 Service::Ptr service = it->second.lock();
437                                 assert(service);
438                                 return service;
439                         }
440                 }
441
442                 return Service::Ptr();
443         } else if (name.IsObjectType<Dictionary>()) {
444                 Dictionary::Ptr dict = name;
445                 String short_name;
446
447                 assert(dict->IsSealed());
448
449                 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
450         } else {
451                 BOOST_THROW_EXCEPTION(invalid_argument("Host/Service name pair is invalid."));
452         }
453 }
454
455 set<Host::Ptr> Host::GetParentHosts(void) const
456 {
457         set<Host::Ptr> parents;
458
459         Dictionary::Ptr dependencies = GetHostDependencies();
460
461         if (dependencies) {
462                 ObjectLock olock(dependencies);
463
464                 Value value;
465                 BOOST_FOREACH(tie(tuples::ignore, value), dependencies) {
466                         if (value == GetName())
467                                 continue;
468
469                         Host::Ptr host = GetByName(value);
470
471                         if (!host)
472                                 continue;
473
474                         parents.insert(host);
475                 }
476         }
477
478         return parents;
479 }
480
481 Service::Ptr Host::GetHostCheckService(void) const
482 {
483         String host_check = GetHostCheck();
484
485         if (host_check.IsEmpty())
486                 return Service::Ptr();
487
488         return GetServiceByShortName(host_check);
489 }
490
491 set<Service::Ptr> Host::GetParentServices(void) const
492 {
493         set<Service::Ptr> parents;
494
495         Dictionary::Ptr dependencies = GetServiceDependencies();
496
497         if (dependencies) {
498                 ObjectLock olock(dependencies);
499
500                 Value value;
501                 BOOST_FOREACH(tie(tuples::ignore, value), dependencies) {
502                         parents.insert(GetServiceByShortName(value));
503                 }
504         }
505
506         return parents;
507 }
508
509 HostState Host::GetState(void) const
510 {
511         if (!IsReachable())
512                 return HostUnreachable;
513
514         Service::Ptr hc = GetHostCheckService();
515
516         if (!hc)
517                 return HostUp;
518
519         switch (hc->GetState()) {
520                 case StateOK:
521                 case StateWarning:
522                         return HostUp;
523                 default:
524                         return HostDown;
525         }
526 }
527
528 StateType Host::GetStateType(void) const
529 {
530         Service::Ptr hc = GetHostCheckService();
531
532         if (!hc)
533                 return StateTypeHard;
534
535         return hc->GetStateType();
536 }
537
538 HostState Host::GetLastState(void) const
539 {
540         assert(!OwnsLock());
541
542         if (!IsReachable())
543                 return HostUnreachable;
544
545         Service::Ptr hc = GetHostCheckService();
546
547         if (!hc)
548                 return HostUp;
549
550         switch (hc->GetLastState()) {
551                 case StateOK:
552                 case StateWarning:
553                         return HostUp;
554                 default:
555                         return HostDown;
556         }
557 }
558
559 StateType Host::GetLastStateType(void) const
560 {
561         Service::Ptr hc = GetHostCheckService();
562
563         if (!hc)
564                 return StateTypeHard;
565
566         return hc->GetLastStateType();
567 }
568
569 String Host::HostStateToString(HostState state)
570 {
571         switch (state) {
572                 case HostUp:
573                         return "UP";
574                 case HostDown:
575                         return "DOWN";
576                 case HostUnreachable:
577                         return "UNREACHABLE";
578                 default:
579                         return "INVALID";
580         }
581 }
582
583 Dictionary::Ptr Host::CalculateDynamicMacros(void) const
584 {
585         assert(!OwnsLock());
586
587         Dictionary::Ptr macros = boost::make_shared<Dictionary>();
588
589         {
590                 ObjectLock olock(this);
591
592                 macros->Set("HOSTNAME", GetName());
593                 macros->Set("HOSTDISPLAYNAME", GetDisplayName());
594                 macros->Set("HOSTALIAS", GetName());
595         }
596
597         Dictionary::Ptr cr;
598
599         Service::Ptr hc = GetHostCheckService();
600
601         if (hc) {
602                 ObjectLock olock(hc);
603
604                 macros->Set("HOSTSTATE", HostStateToString(GetState()));
605                 macros->Set("HOSTSTATEID", GetState());
606                 macros->Set("HOSTSTATETYPE", Service::StateTypeToString(hc->GetStateType()));
607                 macros->Set("HOSTATTEMPT", hc->GetCurrentCheckAttempt());
608                 macros->Set("MAXHOSTATTEMPT", hc->GetMaxCheckAttempts());
609
610                 macros->Set("LASTHOSTSTATE", HostStateToString(GetLastState()));
611                 macros->Set("LASTHOSTSTATEID", GetLastState());
612                 macros->Set("LASTHOSTSTATETYPE", Service::StateTypeToString(GetLastStateType()));
613                 macros->Set("LASTHOSTSTATECHANGE", (long)hc->GetLastStateChange());
614
615                 cr = hc->GetLastCheckResult();
616         }
617
618         if (cr) {
619                 macros->Set("HOSTLATENCY", Service::CalculateLatency(cr));
620                 macros->Set("HOSTEXECUTIONTIME", Service::CalculateExecutionTime(cr));
621
622                 macros->Set("HOSTOUTPUT", cr->Get("output"));
623                 macros->Set("HOSTPERFDATA", cr->Get("performance_data_raw"));
624
625                 macros->Set("LASTHOSTCHECK", (long)cr->Get("schedule_start"));
626         }
627
628         macros->Seal();
629
630         return macros;
631 }