]> granicus.if.org Git - icinga2/blob - lib/icinga/host.cpp
Change log level for some debug messages.
[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& serializedUpdate)
34         : DynamicObject(serializedUpdate)
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 Array::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 Array::Ptr Host::GetHostDependencies(void) const
96 {
97         return m_HostDependencies;;
98 }
99
100 Array::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.IsObjectType<Dictionary>())
246                                 BOOST_THROW_EXCEPTION(invalid_argument("Service description must be either a string or a dictionary."));
247
248                         Dictionary::Ptr service = svcdesc;
249
250                         Array::Ptr templates = service->Get("templates");
251
252                         if (templates) {
253                                 ObjectLock olock(templates);
254
255                                 BOOST_FOREACH(const Value& tmpl, templates) {
256                                         builder->AddParent(tmpl);
257                                 }
258                         }
259
260                         CopyServiceAttributes<true>(service, builder);
261
262                         ConfigItem::Ptr serviceItem = builder->Compile();
263                         DynamicObject::Ptr dobj = serviceItem->Commit();
264
265                         newServices->Set(name, serviceItem);
266                 }
267         }
268
269         if (oldServices) {
270                 ObjectLock olock(oldServices);
271
272                 ConfigItem::Ptr service;
273                 BOOST_FOREACH(tie(tuples::ignore, service), oldServices) {
274                         if (!service)
275                                 continue;
276
277                         if (!newServices->Contains(service->GetName()))
278                                 service->Unregister();
279                 }
280         }
281
282         newServices->Seal();
283
284         Set("slave_services", newServices);
285 }
286
287 void Host::OnAttributeChanged(const String& name)
288 {
289         ASSERT(!OwnsLock());
290
291         if (name == "hostgroups")
292                 HostGroup::InvalidateMembersCache();
293         else if (name == "services") {
294                 UpdateSlaveServices();
295         } else if (name == "notifications") {
296                 BOOST_FOREACH(const Service::Ptr& service, GetServices()) {
297                         service->UpdateSlaveNotifications();
298                 }
299         }
300 }
301
302 set<Service::Ptr> Host::GetServices(void) const
303 {
304         set<Service::Ptr> services;
305
306         boost::mutex::scoped_lock lock(m_ServiceMutex);
307
308         Service::WeakPtr wservice;
309         BOOST_FOREACH(tie(tuples::ignore, wservice), m_ServicesCache[GetName()]) {
310                 Service::Ptr service = wservice.lock();
311
312                 if (!service)
313                         continue;
314
315                 services.insert(service);
316         }
317
318         return services;
319 }
320
321 void Host::InvalidateServicesCache(void)
322 {
323         {
324                 boost::mutex::scoped_lock lock(m_ServiceMutex);
325
326                 if (m_ServicesCacheNeedsUpdate)
327                         return; /* Someone else has already requested a refresh. */
328
329                 if (!m_ServicesCacheTimer) {
330                         m_ServicesCacheTimer = boost::make_shared<Timer>();
331                         m_ServicesCacheTimer->SetInterval(0.5);
332                         m_ServicesCacheTimer->OnTimerExpired.connect(boost::bind(&Host::RefreshServicesCache));
333                         m_ServicesCacheTimer->Start();
334                 }
335
336                 m_ServicesCacheNeedsUpdate = true;
337         }
338 }
339
340 void Host::RefreshServicesCache(void)
341 {
342         {
343                 boost::mutex::scoped_lock lock(m_ServiceMutex);
344
345                 if (!m_ServicesCacheNeedsUpdate)
346                         return;
347
348                 m_ServicesCacheNeedsUpdate = false;
349         }
350
351         Logger::Write(LogDebug, "icinga", "Updating Host services cache.");
352
353         map<String, map<String, Service::WeakPtr> > newServicesCache;
354
355         BOOST_FOREACH(const DynamicObject::Ptr& object, DynamicType::GetObjects("Service")) {
356                 const Service::Ptr& service = static_pointer_cast<Service>(object);
357
358                 Host::Ptr host = service->GetHost();
359
360                 if (!host)
361                         continue;
362
363                 // TODO: assert for duplicate short_names
364
365                 newServicesCache[host->GetName()][service->GetShortName()] = service;
366         }
367
368         boost::mutex::scoped_lock lock(m_ServiceMutex);
369         m_ServicesCache.swap(newServicesCache);
370 }
371
372 void Host::ValidateServiceDictionary(const ScriptTask::Ptr& task, const vector<Value>& arguments)
373 {
374         if (arguments.size() < 1)
375                 BOOST_THROW_EXCEPTION(invalid_argument("Missing argument: Location must be specified."));
376
377         if (arguments.size() < 2)
378                 BOOST_THROW_EXCEPTION(invalid_argument("Missing argument: Attribute dictionary must be specified."));
379
380         String location = arguments[0];
381         Dictionary::Ptr attrs = arguments[1];
382         ObjectLock olock(attrs);
383
384         String key;
385         Value value;
386         BOOST_FOREACH(tie(key, value), attrs) {
387                 vector<String> templates;
388
389                 if (!value.IsObjectType<Dictionary>())
390                         BOOST_THROW_EXCEPTION(invalid_argument("Service description must be a dictionary."));
391
392                 Dictionary::Ptr serviceDesc = value;
393
394                 Array::Ptr templatesArray = serviceDesc->Get("templates");
395
396                 if (templatesArray) {
397                         ObjectLock tlock(templatesArray);
398
399                         BOOST_FOREACH(const Value& tmpl, templatesArray) {
400                                 templates.push_back(tmpl);
401                         }
402                 }
403
404                 BOOST_FOREACH(const String& name, templates) {
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 + ": Template '" + name + "' not found.");
420                         }
421                 }
422         }
423
424         task->FinishResult(Empty);
425 }
426
427 Service::Ptr Host::GetServiceByShortName(const Value& name) const
428 {
429         if (name.IsScalar()) {
430                 {
431                         boost::mutex::scoped_lock lock(m_ServiceMutex);
432
433                         map<String, Service::WeakPtr>& services = m_ServicesCache[GetName()];
434                         map<String, Service::WeakPtr>::iterator it = services.find(name);
435
436                         if (it != services.end()) {
437                                 Service::Ptr service = it->second.lock();
438                                 ASSERT(service);
439                                 return service;
440                         }
441                 }
442
443                 return Service::Ptr();
444         } else if (name.IsObjectType<Dictionary>()) {
445                 Dictionary::Ptr dict = name;
446                 String short_name;
447
448                 ASSERT(dict->IsSealed());
449
450                 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
451         } else {
452                 BOOST_THROW_EXCEPTION(invalid_argument("Host/Service name pair is invalid."));
453         }
454 }
455
456 set<Host::Ptr> Host::GetParentHosts(void) const
457 {
458         set<Host::Ptr> parents;
459
460         Array::Ptr dependencies = GetHostDependencies();
461
462         if (dependencies) {
463                 ObjectLock olock(dependencies);
464
465                 BOOST_FOREACH(const Value& 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         Array::Ptr dependencies = GetServiceDependencies();
496
497         if (dependencies) {
498                 ObjectLock olock(dependencies);
499
500                 BOOST_FOREACH(const Value& value, dependencies) {
501                         parents.insert(GetServiceByShortName(value));
502                 }
503         }
504
505         return parents;
506 }
507
508 HostState Host::GetState(void) const
509 {
510         if (!IsReachable())
511                 return HostUnreachable;
512
513         Service::Ptr hc = GetHostCheckService();
514
515         if (!hc)
516                 return HostUp;
517
518         switch (hc->GetState()) {
519                 case StateOK:
520                 case StateWarning:
521                         return HostUp;
522                 default:
523                         return HostDown;
524         }
525 }
526
527 StateType Host::GetStateType(void) const
528 {
529         Service::Ptr hc = GetHostCheckService();
530
531         if (!hc)
532                 return StateTypeHard;
533
534         return hc->GetStateType();
535 }
536
537 HostState Host::GetLastState(void) const
538 {
539         ASSERT(!OwnsLock());
540
541         if (!IsReachable())
542                 return HostUnreachable;
543
544         Service::Ptr hc = GetHostCheckService();
545
546         if (!hc)
547                 return HostUp;
548
549         switch (hc->GetLastState()) {
550                 case StateOK:
551                 case StateWarning:
552                         return HostUp;
553                 default:
554                         return HostDown;
555         }
556 }
557
558 StateType Host::GetLastStateType(void) const
559 {
560         Service::Ptr hc = GetHostCheckService();
561
562         if (!hc)
563                 return StateTypeHard;
564
565         return hc->GetLastStateType();
566 }
567
568 String Host::HostStateToString(HostState state)
569 {
570         switch (state) {
571                 case HostUp:
572                         return "UP";
573                 case HostDown:
574                         return "DOWN";
575                 case HostUnreachable:
576                         return "UNREACHABLE";
577                 default:
578                         return "INVALID";
579         }
580 }
581
582 Dictionary::Ptr Host::CalculateDynamicMacros(void) const
583 {
584         ASSERT(!OwnsLock());
585
586         Dictionary::Ptr macros = boost::make_shared<Dictionary>();
587
588         {
589                 ObjectLock olock(this);
590
591                 macros->Set("HOSTNAME", GetName());
592                 macros->Set("HOSTDISPLAYNAME", GetDisplayName());
593                 macros->Set("HOSTALIAS", GetName());
594         }
595
596         Dictionary::Ptr cr;
597
598         Service::Ptr hc = GetHostCheckService();
599
600         if (hc) {
601                 ObjectLock olock(hc);
602
603                 macros->Set("HOSTSTATE", HostStateToString(GetState()));
604                 macros->Set("HOSTSTATEID", GetState());
605                 macros->Set("HOSTSTATETYPE", Service::StateTypeToString(hc->GetStateType()));
606                 macros->Set("HOSTATTEMPT", hc->GetCurrentCheckAttempt());
607                 macros->Set("MAXHOSTATTEMPT", hc->GetMaxCheckAttempts());
608
609                 macros->Set("LASTHOSTSTATE", HostStateToString(GetLastState()));
610                 macros->Set("LASTHOSTSTATEID", GetLastState());
611                 macros->Set("LASTHOSTSTATETYPE", Service::StateTypeToString(GetLastStateType()));
612                 macros->Set("LASTHOSTSTATECHANGE", (long)hc->GetLastStateChange());
613
614                 cr = hc->GetLastCheckResult();
615         }
616
617         if (cr) {
618                 macros->Set("HOSTLATENCY", Service::CalculateLatency(cr));
619                 macros->Set("HOSTEXECUTIONTIME", Service::CalculateExecutionTime(cr));
620
621                 macros->Set("HOSTOUTPUT", cr->Get("output"));
622                 macros->Set("HOSTPERFDATA", cr->Get("performance_data_raw"));
623
624                 macros->Set("LASTHOSTCHECK", (long)cr->Get("schedule_start"));
625         }
626
627         macros->Seal();
628
629         return macros;
630 }