]> granicus.if.org Git - icinga2/blob - lib/icinga/host.cpp
Implement timeperiods.
[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         Value check_period = serviceDesc->Get("check_period");
195         if (!check_period.IsEmpty())
196                 builder->AddExpression("check_period", OperatorSet, check_period);
197
198         if (copyServiceAttrs) {
199                 Value servicedependencies = serviceDesc->Get("servicedependencies");
200                 if (!servicedependencies.IsEmpty())
201                         builder->AddExpression("servicedependencies", OperatorPlus, servicedependencies);
202
203                 Value hostdependencies = serviceDesc->Get("hostdependencies");
204                 if (!hostdependencies.IsEmpty())
205                         builder->AddExpression("hostdependencies", OperatorPlus, hostdependencies);
206         }
207 }
208
209 void Host::UpdateSlaveServices(void)
210 {
211         ASSERT(!OwnsLock());
212
213         ConfigItem::Ptr item = ConfigItem::GetObject("Host", GetName());
214
215         /* Don't create slave services unless we own this object */
216         if (!item)
217                 return;
218
219         Dictionary::Ptr oldServices = m_SlaveServices;
220         Dictionary::Ptr serviceDescs = Get("services");
221
222         Dictionary::Ptr newServices = boost::make_shared<Dictionary>();
223
224         if (serviceDescs) {
225                 ObjectLock olock(serviceDescs);
226                 String svcname;
227                 Value svcdesc;
228                 BOOST_FOREACH(tie(svcname, svcdesc), serviceDescs) {
229                         if (svcdesc.IsScalar())
230                                 svcname = svcdesc;
231
232                         stringstream namebuf;
233                         namebuf << GetName() << "-" << svcname;
234                         String name = namebuf.str();
235
236                         ConfigItemBuilder::Ptr builder = boost::make_shared<ConfigItemBuilder>(item->GetDebugInfo());
237                         builder->SetType("Service");
238                         builder->SetName(name);
239                         builder->AddExpression("host_name", OperatorSet, GetName());
240                         builder->AddExpression("display_name", OperatorSet, svcname);
241                         builder->AddExpression("short_name", OperatorSet, svcname);
242
243                         CopyServiceAttributes<false>(this, builder);
244
245                         if (svcdesc.IsScalar()) {
246                                 builder->AddParent(svcdesc);
247                         } else if (svcdesc.IsObjectType<Dictionary>()) {
248                                 Dictionary::Ptr service = svcdesc;
249
250                                 Dictionary::Ptr templates = service->Get("templates");
251
252                                 if (templates) {
253                                         ObjectLock olock(templates);
254
255                                         String tmpl;
256                                         BOOST_FOREACH(tie(tuples::ignore, tmpl), templates) {
257                                                 builder->AddParent(tmpl);
258                                         }
259                                 } else {
260                                         builder->AddParent(svcname);
261                                 }
262
263                                 CopyServiceAttributes<true>(service, builder);
264                         } else {
265                                 BOOST_THROW_EXCEPTION(invalid_argument("Service description must be either a string or a dictionary."));
266                         }
267
268                         ConfigItem::Ptr serviceItem = builder->Compile();
269                         DynamicObject::Ptr dobj = serviceItem->Commit();
270
271                         newServices->Set(name, serviceItem);
272                 }
273         }
274
275         if (oldServices) {
276                 ObjectLock olock(oldServices);
277
278                 ConfigItem::Ptr service;
279                 BOOST_FOREACH(tie(tuples::ignore, service), oldServices) {
280                         if (!service)
281                                 continue;
282
283                         if (!newServices->Contains(service->GetName()))
284                                 service->Unregister();
285                 }
286         }
287
288         newServices->Seal();
289
290         Set("slave_services", newServices);
291 }
292
293 void Host::OnAttributeChanged(const String& name)
294 {
295         ASSERT(!OwnsLock());
296
297         if (name == "hostgroups")
298                 HostGroup::InvalidateMembersCache();
299         else if (name == "services") {
300                 UpdateSlaveServices();
301         } else if (name == "notifications") {
302                 BOOST_FOREACH(const Service::Ptr& service, GetServices()) {
303                         service->UpdateSlaveNotifications();
304                 }
305         }
306 }
307
308 set<Service::Ptr> Host::GetServices(void) const
309 {
310         set<Service::Ptr> services;
311
312         boost::mutex::scoped_lock lock(m_ServiceMutex);
313
314         Service::WeakPtr wservice;
315         BOOST_FOREACH(tie(tuples::ignore, wservice), m_ServicesCache[GetName()]) {
316                 Service::Ptr service = wservice.lock();
317
318                 if (!service)
319                         continue;
320
321                 services.insert(service);
322         }
323
324         return services;
325 }
326
327 void Host::InvalidateServicesCache(void)
328 {
329         {
330                 boost::mutex::scoped_lock lock(m_ServiceMutex);
331
332                 if (m_ServicesCacheNeedsUpdate)
333                         return; /* Someone else has already requested a refresh. */
334
335                 if (!m_ServicesCacheTimer) {
336                         m_ServicesCacheTimer = boost::make_shared<Timer>();
337                         m_ServicesCacheTimer->SetInterval(0.5);
338                         m_ServicesCacheTimer->OnTimerExpired.connect(boost::bind(&Host::RefreshServicesCache));
339                         m_ServicesCacheTimer->Start();
340                 }
341
342                 m_ServicesCacheNeedsUpdate = true;
343         }
344 }
345
346 void Host::RefreshServicesCache(void)
347 {
348         {
349                 boost::mutex::scoped_lock lock(m_ServiceMutex);
350
351                 if (!m_ServicesCacheNeedsUpdate)
352                         return;
353
354                 m_ServicesCacheNeedsUpdate = false;
355         }
356
357         Logger::Write(LogInformation, "icinga", "Updating Host services cache.");
358
359         map<String, map<String, Service::WeakPtr> > newServicesCache;
360
361         BOOST_FOREACH(const DynamicObject::Ptr& object, DynamicType::GetObjects("Service")) {
362                 const Service::Ptr& service = static_pointer_cast<Service>(object);
363
364                 Host::Ptr host = service->GetHost();
365
366                 if (!host)
367                         continue;
368
369                 // TODO: assert for duplicate short_names
370
371                 newServicesCache[host->GetName()][service->GetShortName()] = service;
372         }
373
374         boost::mutex::scoped_lock lock(m_ServiceMutex);
375         m_ServicesCache.swap(newServicesCache);
376 }
377
378 void Host::ValidateServiceDictionary(const ScriptTask::Ptr& task, const vector<Value>& arguments)
379 {
380         if (arguments.size() < 1)
381                 BOOST_THROW_EXCEPTION(invalid_argument("Missing argument: Location must be specified."));
382
383         if (arguments.size() < 2)
384                 BOOST_THROW_EXCEPTION(invalid_argument("Missing argument: Attribute dictionary must be specified."));
385
386         String location = arguments[0];
387         Dictionary::Ptr attrs = arguments[1];
388         ObjectLock olock(attrs);
389
390         String key;
391         Value value;
392         BOOST_FOREACH(tie(key, value), attrs) {
393                 vector<String> templates;
394
395                 if (value.IsScalar()) {
396                         templates.push_back(value);
397                 } else if (value.IsObjectType<Dictionary>()) {
398                         Dictionary::Ptr serviceDesc = value;
399
400                         Dictionary::Ptr templatesDict = serviceDesc->Get("templates");
401                         ObjectLock tlock(templatesDict);
402
403                         Value tmpl;
404                         BOOST_FOREACH(tie(tuples::ignore, tmpl), templatesDict) {
405                                 templates.push_back(tmpl);
406                         }
407                 } else {
408                         continue;
409                 }
410
411                 BOOST_FOREACH(const String& name, templates) {
412                         ConfigItem::Ptr item;
413
414                         ConfigCompilerContext *context = ConfigCompilerContext::GetContext();
415
416                         if (context)
417                                 item = context->GetItem("Service", name);
418
419                         /* ignore already active objects while we're in the compiler
420                          * context and linking to existing items is disabled. */
421                         if (!item && (!context || (context->GetFlags() & CompilerLinkExisting)))
422                                 item = ConfigItem::GetObject("Service", name);
423
424                         if (!item) {
425                                 ConfigCompilerContext::GetContext()->AddError(false, "Validation failed for " +
426                                     location + ": Template '" + name + "' not found.");
427                         }
428                 }
429         }
430
431         task->FinishResult(Empty);
432 }
433
434 Service::Ptr Host::GetServiceByShortName(const Value& name) const
435 {
436         if (name.IsScalar()) {
437                 {
438                         boost::mutex::scoped_lock lock(m_ServiceMutex);
439
440                         map<String, Service::WeakPtr>& services = m_ServicesCache[GetName()];
441                         map<String, Service::WeakPtr>::iterator it = services.find(name);
442
443                         if (it != services.end()) {
444                                 Service::Ptr service = it->second.lock();
445                                 ASSERT(service);
446                                 return service;
447                         }
448                 }
449
450                 return Service::Ptr();
451         } else if (name.IsObjectType<Dictionary>()) {
452                 Dictionary::Ptr dict = name;
453                 String short_name;
454
455                 ASSERT(dict->IsSealed());
456
457                 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
458         } else {
459                 BOOST_THROW_EXCEPTION(invalid_argument("Host/Service name pair is invalid."));
460         }
461 }
462
463 set<Host::Ptr> Host::GetParentHosts(void) const
464 {
465         set<Host::Ptr> parents;
466
467         Dictionary::Ptr dependencies = GetHostDependencies();
468
469         if (dependencies) {
470                 ObjectLock olock(dependencies);
471
472                 Value value;
473                 BOOST_FOREACH(tie(tuples::ignore, value), dependencies) {
474                         if (value == GetName())
475                                 continue;
476
477                         Host::Ptr host = GetByName(value);
478
479                         if (!host)
480                                 continue;
481
482                         parents.insert(host);
483                 }
484         }
485
486         return parents;
487 }
488
489 Service::Ptr Host::GetHostCheckService(void) const
490 {
491         String host_check = GetHostCheck();
492
493         if (host_check.IsEmpty())
494                 return Service::Ptr();
495
496         return GetServiceByShortName(host_check);
497 }
498
499 set<Service::Ptr> Host::GetParentServices(void) const
500 {
501         set<Service::Ptr> parents;
502
503         Dictionary::Ptr dependencies = GetServiceDependencies();
504
505         if (dependencies) {
506                 ObjectLock olock(dependencies);
507
508                 Value value;
509                 BOOST_FOREACH(tie(tuples::ignore, value), dependencies) {
510                         parents.insert(GetServiceByShortName(value));
511                 }
512         }
513
514         return parents;
515 }
516
517 HostState Host::GetState(void) const
518 {
519         if (!IsReachable())
520                 return HostUnreachable;
521
522         Service::Ptr hc = GetHostCheckService();
523
524         if (!hc)
525                 return HostUp;
526
527         switch (hc->GetState()) {
528                 case StateOK:
529                 case StateWarning:
530                         return HostUp;
531                 default:
532                         return HostDown;
533         }
534 }
535
536 StateType Host::GetStateType(void) const
537 {
538         Service::Ptr hc = GetHostCheckService();
539
540         if (!hc)
541                 return StateTypeHard;
542
543         return hc->GetStateType();
544 }
545
546 HostState Host::GetLastState(void) const
547 {
548         ASSERT(!OwnsLock());
549
550         if (!IsReachable())
551                 return HostUnreachable;
552
553         Service::Ptr hc = GetHostCheckService();
554
555         if (!hc)
556                 return HostUp;
557
558         switch (hc->GetLastState()) {
559                 case StateOK:
560                 case StateWarning:
561                         return HostUp;
562                 default:
563                         return HostDown;
564         }
565 }
566
567 StateType Host::GetLastStateType(void) const
568 {
569         Service::Ptr hc = GetHostCheckService();
570
571         if (!hc)
572                 return StateTypeHard;
573
574         return hc->GetLastStateType();
575 }
576
577 String Host::HostStateToString(HostState state)
578 {
579         switch (state) {
580                 case HostUp:
581                         return "UP";
582                 case HostDown:
583                         return "DOWN";
584                 case HostUnreachable:
585                         return "UNREACHABLE";
586                 default:
587                         return "INVALID";
588         }
589 }
590
591 Dictionary::Ptr Host::CalculateDynamicMacros(void) const
592 {
593         ASSERT(!OwnsLock());
594
595         Dictionary::Ptr macros = boost::make_shared<Dictionary>();
596
597         {
598                 ObjectLock olock(this);
599
600                 macros->Set("HOSTNAME", GetName());
601                 macros->Set("HOSTDISPLAYNAME", GetDisplayName());
602                 macros->Set("HOSTALIAS", GetName());
603         }
604
605         Dictionary::Ptr cr;
606
607         Service::Ptr hc = GetHostCheckService();
608
609         if (hc) {
610                 ObjectLock olock(hc);
611
612                 macros->Set("HOSTSTATE", HostStateToString(GetState()));
613                 macros->Set("HOSTSTATEID", GetState());
614                 macros->Set("HOSTSTATETYPE", Service::StateTypeToString(hc->GetStateType()));
615                 macros->Set("HOSTATTEMPT", hc->GetCurrentCheckAttempt());
616                 macros->Set("MAXHOSTATTEMPT", hc->GetMaxCheckAttempts());
617
618                 macros->Set("LASTHOSTSTATE", HostStateToString(GetLastState()));
619                 macros->Set("LASTHOSTSTATEID", GetLastState());
620                 macros->Set("LASTHOSTSTATETYPE", Service::StateTypeToString(GetLastStateType()));
621                 macros->Set("LASTHOSTSTATECHANGE", (long)hc->GetLastStateChange());
622
623                 cr = hc->GetLastCheckResult();
624         }
625
626         if (cr) {
627                 macros->Set("HOSTLATENCY", Service::CalculateLatency(cr));
628                 macros->Set("HOSTEXECUTIONTIME", Service::CalculateExecutionTime(cr));
629
630                 macros->Set("HOSTOUTPUT", cr->Get("output"));
631                 macros->Set("HOSTPERFDATA", cr->Get("performance_data_raw"));
632
633                 macros->Set("LASTHOSTCHECK", (long)cr->Get("schedule_start"));
634         }
635
636         macros->Seal();
637
638         return macros;
639 }