]> granicus.if.org Git - icinga2/blob - lib/icinga/host.cpp
Merge remote-tracking branch 'origin/feature/release-5051' into next
[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                         if (!host)
285                                 continue;
286
287                         parents.insert(host);
288                 }
289         }
290
291         return parents;
292 }
293
294 std::set<Host::Ptr> Host::GetChildHosts(void) const
295 {
296         std::set<Host::Ptr> children;
297
298         BOOST_FOREACH(const Host::Ptr& host, DynamicType::GetObjects<Host>()) {
299                 Array::Ptr dependencies = host->GetHostDependencies();
300
301                 if (dependencies) {
302                         ObjectLock olock(dependencies);
303
304                         BOOST_FOREACH(const Value& value, dependencies) {
305                                 if (value == GetName())
306                                         children.insert(host);
307                         }
308                 }
309         }
310
311         return children;
312 }
313
314 Service::Ptr Host::GetCheckService(void) const
315 {
316         String host_check = GetCheck();
317
318         if (host_check.IsEmpty())
319                 return Service::Ptr();
320
321         return GetServiceByShortName(host_check);
322 }
323
324 std::set<Service::Ptr> Host::GetParentServices(void) const
325 {
326         std::set<Service::Ptr> parents;
327
328         Array::Ptr dependencies = GetServiceDependencies();
329
330         if (dependencies) {
331                 ObjectLock olock(dependencies);
332
333                 BOOST_FOREACH(const Value& value, dependencies) {
334                         parents.insert(GetServiceByShortName(value));
335                 }
336         }
337
338         return parents;
339 }
340
341 HostState Host::CalculateState(ServiceState state, bool reachable)
342 {
343         if (!reachable)
344                 return HostUnreachable;
345
346         switch (state) {
347                 case StateOK:
348                 case StateWarning:
349                         return HostUp;
350                 default:
351                         return HostDown;
352         }
353 }
354
355 HostState Host::GetState(void) const
356 {
357         ASSERT(!OwnsLock());
358
359         if (!IsReachable())
360                 return HostUnreachable;
361
362         Service::Ptr hc = GetCheckService();
363
364         if (!hc)
365                 return HostUp;
366
367         switch (hc->GetState()) {
368                 case StateOK:
369                 case StateWarning:
370                         return HostUp;
371                 default:
372                         return HostDown;
373         }
374
375 }
376
377 HostState Host::GetLastState(void) const
378 {
379         ASSERT(!OwnsLock());
380
381         if (!IsReachable())
382                 return HostUnreachable;
383
384         Service::Ptr hc = GetCheckService();
385
386         if (!hc)
387                 return HostUp;
388
389         switch (hc->GetLastState()) {
390                 case StateOK:
391                 case StateWarning:
392                         return HostUp;
393                 default:
394                         return HostDown;
395         }
396 }
397
398 HostState Host::GetLastHardState(void) const
399 {
400         ASSERT(!OwnsLock());
401
402         if (!IsReachable())
403                 return HostUnreachable;
404
405         Service::Ptr hc = GetCheckService();
406
407         if (!hc)
408                 return HostUp;
409
410         switch (hc->GetLastHardState()) {
411                 case StateOK:
412                 case StateWarning:
413                         return HostUp;
414                 default:
415                         return HostDown;
416         }
417 }
418
419 double Host::GetLastStateUp(void) const
420 {
421         ASSERT(!OwnsLock());
422
423         Service::Ptr hc = GetCheckService();
424
425         if (!hc)
426                 return 0;
427
428         if (hc->GetLastStateOK() > hc->GetLastStateWarning())
429                 return hc->GetLastStateOK();
430         else
431                 return hc->GetLastStateWarning();
432 }
433
434 double Host::GetLastStateDown(void) const
435 {
436         ASSERT(!OwnsLock());
437
438         Service::Ptr hc = GetCheckService();
439
440         if (!hc)
441                 return 0;
442
443         return hc->GetLastStateCritical();
444 }
445
446 double Host::GetLastStateUnreachable(void) const
447 {
448         ASSERT(!OwnsLock());
449
450         Service::Ptr hc = GetCheckService();
451
452         if (!hc)
453                 return 0;
454
455         return hc->GetLastStateUnreachable();
456 }
457
458 double Host::GetLastStateChange(void) const
459 {
460         Service::Ptr hc = GetCheckService();
461
462         if (!hc)
463                 return Application::GetStartTime();
464
465         return hc->GetLastStateChange();
466 }
467
468
469 double Host::GetLastHardStateChange(void) const
470 {
471         Service::Ptr hc = GetCheckService();
472
473         if (!hc)
474                 return Application::GetStartTime();
475
476         return hc->GetLastHardStateChange();
477 }
478
479 StateType Host::GetLastStateType(void) const
480 {
481         Service::Ptr hc = GetCheckService();
482
483         if (!hc)
484                 return StateTypeHard;
485
486         return hc->GetLastStateType();
487 }
488
489 StateType Host::GetStateType(void) const
490 {
491         Service::Ptr hc = GetCheckService();
492
493         if (!hc)
494                 return StateTypeHard;
495
496         return hc->GetStateType();
497 }
498
499 HostState Host::StateFromString(const String& state)
500 {
501         if (state == "UP")
502                 return HostUp;
503         else if (state == "DOWN")
504                 return HostDown;
505         else if (state == "UNREACHABLE")
506                 return HostUnreachable;
507         else
508                 return HostUnreachable;
509 }
510
511 String Host::StateToString(HostState state)
512 {
513         switch (state) {
514                 case HostUp:
515                         return "UP";
516                 case HostDown:
517                         return "DOWN";
518                 case HostUnreachable:
519                         return "UNREACHABLE";
520                 default:
521                         return "INVALID";
522         }
523 }
524
525 StateType Host::StateTypeFromString(const String& type)
526 {
527         if (type == "SOFT")
528                 return StateTypeSoft;
529         else
530                 return StateTypeHard;
531 }
532
533 String Host::StateTypeToString(StateType type)
534 {
535         if (type == StateTypeSoft)
536                 return "SOFT";
537         else
538                 return "HARD";
539 }
540
541 bool Host::ResolveMacro(const String& macro, const CheckResult::Ptr&, String *result) const
542 {
543         if (macro == "HOSTNAME") {
544                 *result = GetName();
545                 return true;
546         }
547         else if (macro == "HOSTDISPLAYNAME" || macro == "HOSTALIAS") {
548                 *result = GetDisplayName();
549                 return true;
550         }
551
552         Service::Ptr hc = GetCheckService();
553         CheckResult::Ptr hccr;
554
555         if (hc) {
556                 ServiceState state = hc->GetState();
557                 bool reachable = IsReachable();
558
559                 if (macro == "HOSTSTATE") {
560                         HostState hstate = CalculateState(state, reachable);
561
562                         switch (hstate) {
563                                 case HostUnreachable:
564                                         *result = "UNREACHABLE";
565                                         break;
566                                 case HostUp:
567                                         *result = "UP";
568                                         break;
569                                 case HostDown:
570                                         *result = "DOWN";
571                                         break;
572                                 default:
573                                         ASSERT(0);
574                         }
575
576                         return true;
577                 } else if (macro == "HOSTSTATEID") {
578                         *result = Convert::ToString(state);
579                         return true;
580                 } else if (macro == "HOSTSTATETYPE") {
581                         *result = Service::StateTypeToString(hc->GetStateType());
582                         return true;
583                 } else if (macro == "HOSTATTEMPT") {
584                         *result = Convert::ToString(hc->GetCheckAttempt());
585                         return true;
586                 } else if (macro == "MAXHOSTATTEMPT") {
587                         *result = Convert::ToString(hc->GetMaxCheckAttempts());
588                         return true;
589                 } else if (macro == "LASTHOSTSTATE") {
590                         *result = StateToString(GetLastState());
591                         return true;
592                 } else if (macro == "LASTHOSTSTATEID") {
593                         *result = Convert::ToString(GetLastState());
594                         return true;
595                 } else if (macro == "LASTHOSTSTATETYPE") {
596                         *result = Service::StateTypeToString(GetLastStateType());
597                         return true;
598                 } else if (macro == "LASTHOSTSTATECHANGE") {
599                         *result = Convert::ToString((long)hc->GetLastStateChange());
600                         return true;
601                 } else if (macro == "HOSTDURATIONSEC") {
602                         *result = Convert::ToString((long)(Utility::GetTime() - hc->GetLastStateChange()));
603                         return true;
604                 }
605
606                 hccr = hc->GetLastCheckResult();
607         }
608
609         if (hccr) {
610                 if (macro == "HOSTLATENCY") {
611                         *result = Convert::ToString(Service::CalculateLatency(hccr));
612                         return true;
613                 } else if (macro == "HOSTEXECUTIONTIME") {
614                         *result = Convert::ToString(Service::CalculateExecutionTime(hccr));
615                         return true;
616                 } else if (macro == "HOSTOUTPUT") {
617                         *result = hccr->GetOutput();
618                         return true;
619                 } else if (macro == "HOSTPERFDATA") {
620                         *result = PluginUtility::FormatPerfdata(hccr->GetPerformanceData());
621                         return true;
622                 } else if (macro == "LASTHOSTCHECK") {
623                         *result = Convert::ToString((long)hccr->GetScheduleStart());
624                         return true;
625                 }
626         }
627
628         Dictionary::Ptr macros = GetMacros();
629
630         String name = macro;
631
632         if (name == "HOSTADDRESS")
633                 name = "address";
634         else if (macro == "HOSTADDRESS6")
635                 name = "address6";
636
637         if (macros && macros->Contains(name)) {
638                 *result = macros->Get(name);
639                 return true;
640         }
641
642         if (macro == "HOSTADDRESS" || macro == "HOSTADDRESS6") {
643                 *result = GetName();
644                 return true;
645         }
646
647         return false;
648 }