]> granicus.if.org Git - icinga2/blob - lib/icinga/host.cpp
Remove redundant checks.
[icinga2] / lib / icinga / host.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2013 Icinga Development Team (http://www.icinga.org/)   *
4  *                                                                            *
5  * This program is free software; you can redistribute it and/or              *
6  * modify it under the terms of the GNU General Public License                *
7  * as published by the Free Software Foundation; either version 2             *
8  * of the License, or (at your option) any later version.                     *
9  *                                                                            *
10  * This program is distributed in the hope that it will be useful,            *
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
13  * GNU General Public License for more details.                               *
14  *                                                                            *
15  * You should have received a copy of the GNU General Public License          *
16  * along with this program; if not, write to the Free Software Foundation     *
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.             *
18  ******************************************************************************/
19
20 #include "icinga/host.h"
21 #include "icinga/service.h"
22 #include "icinga/hostgroup.h"
23 #include "icinga/icingaapplication.h"
24 #include "icinga/pluginutility.h"
25 #include "base/dynamictype.h"
26 #include "base/objectlock.h"
27 #include "base/logger_fwd.h"
28 #include "base/timer.h"
29 #include "base/convert.h"
30 #include "base/utility.h"
31 #include "base/scriptfunction.h"
32 #include "base/debug.h"
33 #include "base/serializer.h"
34 #include "config/configitembuilder.h"
35 #include "config/configcompilercontext.h"
36 #include <boost/tuple/tuple.hpp>
37 #include <boost/foreach.hpp>
38
39 using namespace icinga;
40
41 REGISTER_TYPE(Host);
42
43 void Host::Start(void)
44 {
45         DynamicObject::Start();
46
47         ASSERT(!OwnsLock());
48
49         Array::Ptr groups = GetGroups();
50
51         if (groups) {
52                 ObjectLock olock(groups);
53
54                 BOOST_FOREACH(const String& name, groups) {
55                         HostGroup::Ptr hg = HostGroup::GetByName(name);
56
57                         if (hg)
58                                 hg->AddMember(GetSelf());
59                 }
60         }
61 }
62
63 void Host::OnConfigLoaded(void)
64 {
65         UpdateSlaveServices();
66 }
67
68 void Host::Stop(void)
69 {
70         DynamicObject::Stop();
71
72         Array::Ptr groups = GetGroups();
73
74         if (groups) {
75                 ObjectLock olock(groups);
76
77                 BOOST_FOREACH(const String& name, groups) {
78                         HostGroup::Ptr hg = HostGroup::GetByName(name);
79
80                         if (hg)
81                                 hg->RemoveMember(GetSelf());
82                 }
83         }
84
85         // TODO: unregister slave services/notifications?
86 }
87
88 bool Host::IsReachable(void) const
89 {
90         ASSERT(!OwnsLock());
91
92         std::set<Service::Ptr> parentServices = GetParentServices();
93
94         BOOST_FOREACH(const Service::Ptr& service, parentServices) {
95                 ObjectLock olock(service);
96
97                 /* ignore pending services */
98                 if (!service->GetLastCheckResult())
99                         continue;
100
101                 /* ignore soft states */
102                 if (service->GetStateType() == StateTypeSoft)
103                         continue;
104
105                 /* ignore services states OK and Warning */
106                 if (service->GetState() == StateOK ||
107                     service->GetState() == StateWarning)
108                         continue;
109
110                 return false;
111         }
112
113         std::set<Host::Ptr> parentHosts = GetParentHosts();
114
115         BOOST_FOREACH(const Host::Ptr& host, parentHosts) {
116                 Service::Ptr hc = host->GetCheckService();
117
118                 /* ignore hosts that don't have a check */
119                 if (!hc)
120                         continue;
121
122                 ObjectLock olock(hc);
123
124                 /* ignore soft states */
125                 if (hc->GetStateType() == StateTypeSoft)
126                         continue;
127
128                 /* ignore hosts that are up */
129                 if (hc->GetState() == StateOK)
130                         continue;
131
132                 return false;
133         }
134
135         return true;
136 }
137
138 void Host::UpdateSlaveServices(void)
139 {
140         ASSERT(!OwnsLock());
141
142         ConfigItem::Ptr item = ConfigItem::GetObject("Host", GetName());
143
144         /* Don't create slave services unless we own this object */
145         if (!item)
146                 return;
147
148         Dictionary::Ptr service_descriptions = GetServiceDescriptions();
149
150         if (!service_descriptions)
151                 return;
152
153         ObjectLock olock(service_descriptions);
154         String svcname;
155         Value svcdesc;
156         BOOST_FOREACH(boost::tie(svcname, svcdesc), service_descriptions) {
157                 if (svcdesc.IsScalar())
158                         svcname = svcdesc;
159
160                 std::ostringstream namebuf;
161                 namebuf << GetName() << ":" << svcname;
162                 String name = namebuf.str();
163
164                 std::vector<String> path;
165                 path.push_back("services");
166                 path.push_back(svcname);
167
168                 DebugInfo di;
169                 item->GetLinkedExpressionList()->FindDebugInfoPath(path, di);
170
171                 if (di.Path.IsEmpty())
172                         di = item->GetDebugInfo();
173
174                 ConfigItemBuilder::Ptr builder = make_shared<ConfigItemBuilder>(di);
175                 builder->SetType("Service");
176                 builder->SetName(name);
177                 builder->AddExpression("host", OperatorSet, GetName());
178                 builder->AddExpression("display_name", OperatorSet, svcname);
179                 builder->AddExpression("short_name", OperatorSet, svcname);
180
181                 if (!svcdesc.IsObjectType<Dictionary>())
182                         BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be either a string or a dictionary."));
183
184                 Dictionary::Ptr service = svcdesc;
185
186                 Array::Ptr templates = service->Get("templates");
187
188                 if (templates) {
189                         ObjectLock olock(templates);
190
191                         BOOST_FOREACH(const Value& tmpl, templates) {
192                                 builder->AddParent(tmpl);
193                         }
194                 }
195
196                 /* Clone attributes from the service expression list. */
197                 ExpressionList::Ptr svc_exprl = make_shared<ExpressionList>();
198                 item->GetLinkedExpressionList()->ExtractPath(path, svc_exprl);
199
200                 builder->AddExpressionList(svc_exprl);
201
202                 ConfigItem::Ptr serviceItem = builder->Compile();
203                 serviceItem->Register();
204                 DynamicObject::Ptr dobj = serviceItem->Commit();
205                 dobj->OnConfigLoaded();
206         }
207 }
208
209 std::set<Service::Ptr> Host::GetServices(void) const
210 {
211         boost::mutex::scoped_lock lock(m_ServicesMutex);
212
213         std::set<Service::Ptr> services;
214         Service::WeakPtr wservice;
215         BOOST_FOREACH(boost::tie(boost::tuples::ignore, wservice), m_Services) {
216                 Service::Ptr service = wservice.lock();
217
218                 if (!service)
219                         continue;
220
221                 services.insert(service);
222         }
223
224         return services;
225 }
226
227 void Host::AddService(const Service::Ptr& service)
228 {
229         boost::mutex::scoped_lock lock(m_ServicesMutex);
230
231         m_Services[service->GetShortName()] = service;
232 }
233
234 void Host::RemoveService(const Service::Ptr& service)
235 {
236         boost::mutex::scoped_lock lock(m_ServicesMutex);
237
238         m_Services.erase(service->GetShortName());
239 }
240
241 int Host::GetTotalServices(void) const
242 {
243         return GetServices().size();
244 }
245
246 Service::Ptr Host::GetServiceByShortName(const Value& name) const
247 {
248         if (name.IsScalar()) {
249                 {
250                         boost::mutex::scoped_lock lock(m_ServicesMutex);
251
252                         std::map<String, Service::Ptr>::const_iterator it = m_Services.find(name);
253
254                         if (it != m_Services.end())
255                                 return it->second;
256                 }
257
258                 return Service::Ptr();
259         } else if (name.IsObjectType<Dictionary>()) {
260                 Dictionary::Ptr dict = name;
261                 String short_name;
262
263                 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
264         } else {
265                 BOOST_THROW_EXCEPTION(std::invalid_argument("Host/Service name pair is invalid: " + JsonSerialize(name)));
266         }
267 }
268
269 std::set<Host::Ptr> Host::GetParentHosts(void) const
270 {
271         std::set<Host::Ptr> parents;
272
273         Array::Ptr dependencies = GetHostDependencies();
274
275         if (dependencies) {
276                 ObjectLock olock(dependencies);
277
278                 BOOST_FOREACH(const Value& value, dependencies) {
279                         if (value == GetName())
280                                 continue;
281
282                         Host::Ptr host = GetByName(value);
283
284                         parents.insert(host);
285                 }
286         }
287
288         return parents;
289 }
290
291 std::set<Host::Ptr> Host::GetChildHosts(void) const
292 {
293         std::set<Host::Ptr> children;
294
295         BOOST_FOREACH(const Host::Ptr& host, DynamicType::GetObjects<Host>()) {
296                 Array::Ptr dependencies = host->GetHostDependencies();
297
298                 if (dependencies) {
299                         ObjectLock olock(dependencies);
300
301                         BOOST_FOREACH(const Value& value, dependencies) {
302                                 if (value == GetName())
303                                         children.insert(host);
304                         }
305                 }
306         }
307
308         return children;
309 }
310
311 Service::Ptr Host::GetCheckService(void) const
312 {
313         String host_check = GetCheck();
314
315         if (host_check.IsEmpty())
316                 return Service::Ptr();
317
318         return GetServiceByShortName(host_check);
319 }
320
321 std::set<Service::Ptr> Host::GetParentServices(void) const
322 {
323         std::set<Service::Ptr> parents;
324
325         Array::Ptr dependencies = GetServiceDependencies();
326
327         if (dependencies) {
328                 ObjectLock olock(dependencies);
329
330                 BOOST_FOREACH(const Value& value, dependencies) {
331                         parents.insert(GetServiceByShortName(value));
332                 }
333         }
334
335         return parents;
336 }
337
338 HostState Host::CalculateState(ServiceState state, bool reachable)
339 {
340         if (!reachable)
341                 return HostUnreachable;
342
343         switch (state) {
344                 case StateOK:
345                 case StateWarning:
346                         return HostUp;
347                 default:
348                         return HostDown;
349         }
350 }
351
352 HostState Host::GetState(void) const
353 {
354         ASSERT(!OwnsLock());
355
356         if (!IsReachable())
357                 return HostUnreachable;
358
359         Service::Ptr hc = GetCheckService();
360
361         if (!hc)
362                 return HostUp;
363
364         switch (hc->GetState()) {
365                 case StateOK:
366                 case StateWarning:
367                         return HostUp;
368                 default:
369                         return HostDown;
370         }
371
372 }
373
374 HostState Host::GetLastState(void) const
375 {
376         ASSERT(!OwnsLock());
377
378         if (!IsReachable())
379                 return HostUnreachable;
380
381         Service::Ptr hc = GetCheckService();
382
383         if (!hc)
384                 return HostUp;
385
386         switch (hc->GetLastState()) {
387                 case StateOK:
388                 case StateWarning:
389                         return HostUp;
390                 default:
391                         return HostDown;
392         }
393 }
394
395 HostState Host::GetLastHardState(void) const
396 {
397         ASSERT(!OwnsLock());
398
399         if (!IsReachable())
400                 return HostUnreachable;
401
402         Service::Ptr hc = GetCheckService();
403
404         if (!hc)
405                 return HostUp;
406
407         switch (hc->GetLastHardState()) {
408                 case StateOK:
409                 case StateWarning:
410                         return HostUp;
411                 default:
412                         return HostDown;
413         }
414 }
415
416 double Host::GetLastStateUp(void) const
417 {
418         ASSERT(!OwnsLock());
419
420         Service::Ptr hc = GetCheckService();
421
422         if (!hc)
423                 return 0;
424
425         if (hc->GetLastStateOK() > hc->GetLastStateWarning())
426                 return hc->GetLastStateOK();
427         else
428                 return hc->GetLastStateWarning();
429 }
430
431 double Host::GetLastStateDown(void) const
432 {
433         ASSERT(!OwnsLock());
434
435         Service::Ptr hc = GetCheckService();
436
437         if (!hc)
438                 return 0;
439
440         return hc->GetLastStateCritical();
441 }
442
443 double Host::GetLastStateUnreachable(void) const
444 {
445         ASSERT(!OwnsLock());
446
447         Service::Ptr hc = GetCheckService();
448
449         if (!hc)
450                 return 0;
451
452         return hc->GetLastStateUnreachable();
453 }
454
455 double Host::GetLastStateChange(void) const
456 {
457         Service::Ptr hc = GetCheckService();
458
459         if (!hc)
460                 return Application::GetStartTime();
461
462         return hc->GetLastStateChange();
463 }
464
465
466 double Host::GetLastHardStateChange(void) const
467 {
468         Service::Ptr hc = GetCheckService();
469
470         if (!hc)
471                 return Application::GetStartTime();
472
473         return hc->GetLastHardStateChange();
474 }
475
476 StateType Host::GetLastStateType(void) const
477 {
478         Service::Ptr hc = GetCheckService();
479
480         if (!hc)
481                 return StateTypeHard;
482
483         return hc->GetLastStateType();
484 }
485
486 StateType Host::GetStateType(void) const
487 {
488         Service::Ptr hc = GetCheckService();
489
490         if (!hc)
491                 return StateTypeHard;
492
493         return hc->GetStateType();
494 }
495
496 HostState Host::StateFromString(const String& state)
497 {
498         if (state == "UP")
499                 return HostUp;
500         else if (state == "DOWN")
501                 return HostDown;
502         else if (state == "UNREACHABLE")
503                 return HostUnreachable;
504         else
505                 return HostUnreachable;
506 }
507
508 String Host::StateToString(HostState state)
509 {
510         switch (state) {
511                 case HostUp:
512                         return "UP";
513                 case HostDown:
514                         return "DOWN";
515                 case HostUnreachable:
516                         return "UNREACHABLE";
517                 default:
518                         return "INVALID";
519         }
520 }
521
522 StateType Host::StateTypeFromString(const String& type)
523 {
524         if (type == "SOFT")
525                 return StateTypeSoft;
526         else
527                 return StateTypeHard;
528 }
529
530 String Host::StateTypeToString(StateType type)
531 {
532         if (type == StateTypeSoft)
533                 return "SOFT";
534         else
535                 return "HARD";
536 }
537
538 bool Host::ResolveMacro(const String& macro, const CheckResult::Ptr&, String *result) const
539 {
540         if (macro == "HOSTNAME") {
541                 *result = GetName();
542                 return true;
543         }
544         else if (macro == "HOSTDISPLAYNAME" || macro == "HOSTALIAS") {
545                 *result = GetDisplayName();
546                 return true;
547         }
548
549         Service::Ptr hc = GetCheckService();
550         CheckResult::Ptr hccr;
551
552         if (hc) {
553                 ServiceState state = hc->GetState();
554                 bool reachable = IsReachable();
555
556                 if (macro == "HOSTSTATE") {
557                         HostState hstate = CalculateState(state, reachable);
558
559                         switch (hstate) {
560                                 case HostUnreachable:
561                                         *result = "UNREACHABLE";
562                                         break;
563                                 case HostUp:
564                                         *result = "UP";
565                                         break;
566                                 case HostDown:
567                                         *result = "DOWN";
568                                         break;
569                                 default:
570                                         ASSERT(0);
571                         }
572
573                         return true;
574                 } else if (macro == "HOSTSTATEID") {
575                         *result = Convert::ToString(state);
576                         return true;
577                 } else if (macro == "HOSTSTATETYPE") {
578                         *result = Service::StateTypeToString(hc->GetStateType());
579                         return true;
580                 } else if (macro == "HOSTATTEMPT") {
581                         *result = Convert::ToString(hc->GetCheckAttempt());
582                         return true;
583                 } else if (macro == "MAXHOSTATTEMPT") {
584                         *result = Convert::ToString(hc->GetMaxCheckAttempts());
585                         return true;
586                 } else if (macro == "LASTHOSTSTATE") {
587                         *result = StateToString(GetLastState());
588                         return true;
589                 } else if (macro == "LASTHOSTSTATEID") {
590                         *result = Convert::ToString(GetLastState());
591                         return true;
592                 } else if (macro == "LASTHOSTSTATETYPE") {
593                         *result = Service::StateTypeToString(GetLastStateType());
594                         return true;
595                 } else if (macro == "LASTHOSTSTATECHANGE") {
596                         *result = Convert::ToString((long)hc->GetLastStateChange());
597                         return true;
598                 } else if (macro == "HOSTDURATIONSEC") {
599                         *result = Convert::ToString((long)(Utility::GetTime() - hc->GetLastStateChange()));
600                         return true;
601                 }
602
603                 hccr = hc->GetLastCheckResult();
604         }
605
606         if (hccr) {
607                 if (macro == "HOSTLATENCY") {
608                         *result = Convert::ToString(Service::CalculateLatency(hccr));
609                         return true;
610                 } else if (macro == "HOSTEXECUTIONTIME") {
611                         *result = Convert::ToString(Service::CalculateExecutionTime(hccr));
612                         return true;
613                 } else if (macro == "HOSTOUTPUT") {
614                         *result = hccr->GetOutput();
615                         return true;
616                 } else if (macro == "HOSTPERFDATA") {
617                         *result = PluginUtility::FormatPerfdata(hccr->GetPerformanceData());
618                         return true;
619                 } else if (macro == "LASTHOSTCHECK") {
620                         *result = Convert::ToString((long)hccr->GetScheduleStart());
621                         return true;
622                 }
623         }
624
625         Dictionary::Ptr macros = GetMacros();
626
627         String name = macro;
628
629         if (name == "HOSTADDRESS")
630                 name = "address";
631         else if (macro == "HOSTADDRESS6")
632                 name = "address6";
633
634         if (macros && macros->Contains(name)) {
635                 *result = macros->Get(name);
636                 return true;
637         }
638
639         if (macro == "HOSTADDRESS" || macro == "HOSTADDRESS6") {
640                 *result = GetName();
641                 return true;
642         }
643
644         return false;
645 }