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