]> granicus.if.org Git - icinga2/blob - lib/icinga/host.cpp
Merge branch 'feature/tp-contention-5327' 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/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         Dictionary::Ptr service_descriptions = GetServiceDescriptions();
142
143         if (!service_descriptions ||service_descriptions->GetLength() == 0)
144                 return;
145
146         ConfigItem::Ptr item = ConfigItem::GetObject("Host", GetName());
147
148         ObjectLock olock(service_descriptions);
149         BOOST_FOREACH(const Dictionary::Pair& kv, service_descriptions) {
150                 std::ostringstream namebuf;
151                 namebuf << GetName() << "!" << kv.first;
152                 String name = namebuf.str();
153
154                 std::vector<String> path;
155                 path.push_back("services");
156                 path.push_back(kv.first);
157
158                 DebugInfo di;
159                 item->GetLinkedExpressionList()->FindDebugInfoPath(path, di);
160
161                 if (di.Path.IsEmpty())
162                         di = item->GetDebugInfo();
163
164                 ConfigItemBuilder::Ptr builder = make_shared<ConfigItemBuilder>(di);
165                 builder->SetType("Service");
166                 builder->SetName(name);
167                 builder->AddExpression("host", OperatorSet, GetName());
168                 builder->AddExpression("display_name", OperatorSet, kv.first);
169                 builder->AddExpression("short_name", OperatorSet, kv.first);
170
171                 if (!kv.second.IsObjectType<Dictionary>())
172                         BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be either a string or a dictionary."));
173
174                 Dictionary::Ptr service = kv.second;
175
176                 Array::Ptr templates = service->Get("templates");
177
178                 if (templates) {
179                         ObjectLock olock(templates);
180
181                         BOOST_FOREACH(const Value& tmpl, templates) {
182                                 builder->AddParent(tmpl);
183                         }
184                 }
185
186                 /* Clone attributes from the service expression list. */
187                 ExpressionList::Ptr svc_exprl = make_shared<ExpressionList>();
188                 item->GetLinkedExpressionList()->ExtractPath(path, svc_exprl);
189
190                 builder->AddExpressionList(svc_exprl);
191
192                 ConfigItem::Ptr serviceItem = builder->Compile();
193                 serviceItem->Register();
194                 DynamicObject::Ptr dobj = serviceItem->Commit();
195                 dobj->OnConfigLoaded();
196         }
197 }
198
199 std::set<Service::Ptr> Host::GetServices(void) const
200 {
201         boost::mutex::scoped_lock lock(m_ServicesMutex);
202
203         std::set<Service::Ptr> services;
204         typedef std::pair<String, Service::Ptr> ServicePair;
205         BOOST_FOREACH(const ServicePair& kv, m_Services) {
206                 services.insert(kv.second);
207         }
208
209         return services;
210 }
211
212 void Host::AddService(const Service::Ptr& service)
213 {
214         boost::mutex::scoped_lock lock(m_ServicesMutex);
215
216         m_Services[service->GetShortName()] = service;
217 }
218
219 void Host::RemoveService(const Service::Ptr& service)
220 {
221         boost::mutex::scoped_lock lock(m_ServicesMutex);
222
223         m_Services.erase(service->GetShortName());
224 }
225
226 int Host::GetTotalServices(void) const
227 {
228         return GetServices().size();
229 }
230
231 Service::Ptr Host::GetServiceByShortName(const Value& name) const
232 {
233         if (name.IsScalar()) {
234                 {
235                         boost::mutex::scoped_lock lock(m_ServicesMutex);
236
237                         std::map<String, Service::Ptr>::const_iterator it = m_Services.find(name);
238
239                         if (it != m_Services.end())
240                                 return it->second;
241                 }
242
243                 return Service::Ptr();
244         } else if (name.IsObjectType<Dictionary>()) {
245                 Dictionary::Ptr dict = name;
246                 String short_name;
247
248                 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
249         } else {
250                 BOOST_THROW_EXCEPTION(std::invalid_argument("Host/Service name pair is invalid: " + JsonSerialize(name)));
251         }
252 }
253
254 std::set<Host::Ptr> Host::GetParentHosts(void) const
255 {
256         std::set<Host::Ptr> parents;
257
258         Array::Ptr dependencies = GetHostDependencies();
259
260         if (dependencies) {
261                 ObjectLock olock(dependencies);
262
263                 BOOST_FOREACH(const Value& value, dependencies) {
264                         if (value == GetName())
265                                 continue;
266
267                         Host::Ptr host = GetByName(value);
268
269                         parents.insert(host);
270                 }
271         }
272
273         return parents;
274 }
275
276 std::set<Host::Ptr> Host::GetChildHosts(void) const
277 {
278         std::set<Host::Ptr> children;
279
280         BOOST_FOREACH(const Host::Ptr& host, DynamicType::GetObjects<Host>()) {
281                 Array::Ptr dependencies = host->GetHostDependencies();
282
283                 if (dependencies) {
284                         ObjectLock olock(dependencies);
285
286                         BOOST_FOREACH(const Value& value, dependencies) {
287                                 if (value == GetName())
288                                         children.insert(host);
289                         }
290                 }
291         }
292
293         return children;
294 }
295
296 Service::Ptr Host::GetCheckService(void) const
297 {
298         String host_check = GetCheck();
299
300         if (host_check.IsEmpty())
301                 return Service::Ptr();
302
303         return GetServiceByShortName(host_check);
304 }
305
306 std::set<Service::Ptr> Host::GetParentServices(void) const
307 {
308         std::set<Service::Ptr> parents;
309
310         Array::Ptr dependencies = GetServiceDependencies();
311
312         if (dependencies) {
313                 ObjectLock olock(dependencies);
314
315                 BOOST_FOREACH(const Value& value, dependencies) {
316                         parents.insert(GetServiceByShortName(value));
317                 }
318         }
319
320         return parents;
321 }
322
323 HostState Host::CalculateState(ServiceState state, bool reachable)
324 {
325         if (!reachable)
326                 return HostUnreachable;
327
328         switch (state) {
329                 case StateOK:
330                 case StateWarning:
331                         return HostUp;
332                 default:
333                         return HostDown;
334         }
335 }
336
337 HostState Host::GetState(void) const
338 {
339         ASSERT(!OwnsLock());
340
341         if (!IsReachable())
342                 return HostUnreachable;
343
344         Service::Ptr hc = GetCheckService();
345
346         if (!hc)
347                 return HostUp;
348
349         switch (hc->GetState()) {
350                 case StateOK:
351                 case StateWarning:
352                         return HostUp;
353                 default:
354                         return HostDown;
355         }
356
357 }
358
359 HostState Host::GetLastState(void) const
360 {
361         ASSERT(!OwnsLock());
362
363         if (!IsReachable())
364                 return HostUnreachable;
365
366         Service::Ptr hc = GetCheckService();
367
368         if (!hc)
369                 return HostUp;
370
371         switch (hc->GetLastState()) {
372                 case StateOK:
373                 case StateWarning:
374                         return HostUp;
375                 default:
376                         return HostDown;
377         }
378 }
379
380 HostState Host::GetLastHardState(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->GetLastHardState()) {
393                 case StateOK:
394                 case StateWarning:
395                         return HostUp;
396                 default:
397                         return HostDown;
398         }
399 }
400
401 double Host::GetLastStateUp(void) const
402 {
403         ASSERT(!OwnsLock());
404
405         Service::Ptr hc = GetCheckService();
406
407         if (!hc)
408                 return 0;
409
410         if (hc->GetLastStateOK() > hc->GetLastStateWarning())
411                 return hc->GetLastStateOK();
412         else
413                 return hc->GetLastStateWarning();
414 }
415
416 double Host::GetLastStateDown(void) const
417 {
418         ASSERT(!OwnsLock());
419
420         Service::Ptr hc = GetCheckService();
421
422         if (!hc)
423                 return 0;
424
425         return hc->GetLastStateCritical();
426 }
427
428 double Host::GetLastStateUnreachable(void) const
429 {
430         ASSERT(!OwnsLock());
431
432         Service::Ptr hc = GetCheckService();
433
434         if (!hc)
435                 return 0;
436
437         return hc->GetLastStateUnreachable();
438 }
439
440 double Host::GetLastStateChange(void) const
441 {
442         Service::Ptr hc = GetCheckService();
443
444         if (!hc)
445                 return Application::GetStartTime();
446
447         return hc->GetLastStateChange();
448 }
449
450
451 double Host::GetLastHardStateChange(void) const
452 {
453         Service::Ptr hc = GetCheckService();
454
455         if (!hc)
456                 return Application::GetStartTime();
457
458         return hc->GetLastHardStateChange();
459 }
460
461 StateType Host::GetLastStateType(void) const
462 {
463         Service::Ptr hc = GetCheckService();
464
465         if (!hc)
466                 return StateTypeHard;
467
468         return hc->GetLastStateType();
469 }
470
471 StateType Host::GetStateType(void) const
472 {
473         Service::Ptr hc = GetCheckService();
474
475         if (!hc)
476                 return StateTypeHard;
477
478         return hc->GetStateType();
479 }
480
481 HostState Host::StateFromString(const String& state)
482 {
483         if (state == "UP")
484                 return HostUp;
485         else if (state == "DOWN")
486                 return HostDown;
487         else if (state == "UNREACHABLE")
488                 return HostUnreachable;
489         else
490                 return HostUnreachable;
491 }
492
493 String Host::StateToString(HostState state)
494 {
495         switch (state) {
496                 case HostUp:
497                         return "UP";
498                 case HostDown:
499                         return "DOWN";
500                 case HostUnreachable:
501                         return "UNREACHABLE";
502                 default:
503                         return "INVALID";
504         }
505 }
506
507 StateType Host::StateTypeFromString(const String& type)
508 {
509         if (type == "SOFT")
510                 return StateTypeSoft;
511         else
512                 return StateTypeHard;
513 }
514
515 String Host::StateTypeToString(StateType type)
516 {
517         if (type == StateTypeSoft)
518                 return "SOFT";
519         else
520                 return "HARD";
521 }
522
523 bool Host::ResolveMacro(const String& macro, const CheckResult::Ptr&, String *result) const
524 {
525         if (macro == "HOSTNAME") {
526                 *result = GetName();
527                 return true;
528         }
529         else if (macro == "HOSTDISPLAYNAME" || macro == "HOSTALIAS") {
530                 *result = GetDisplayName();
531                 return true;
532         }
533
534         Service::Ptr hc = GetCheckService();
535         CheckResult::Ptr hccr;
536
537         if (hc) {
538                 ServiceState state = hc->GetState();
539                 bool reachable = IsReachable();
540
541                 if (macro == "HOSTSTATE") {
542                         HostState hstate = CalculateState(state, reachable);
543
544                         switch (hstate) {
545                                 case HostUnreachable:
546                                         *result = "UNREACHABLE";
547                                         break;
548                                 case HostUp:
549                                         *result = "UP";
550                                         break;
551                                 case HostDown:
552                                         *result = "DOWN";
553                                         break;
554                                 default:
555                                         ASSERT(0);
556                         }
557
558                         return true;
559                 } else if (macro == "HOSTSTATEID") {
560                         *result = Convert::ToString(state);
561                         return true;
562                 } else if (macro == "HOSTSTATETYPE") {
563                         *result = Service::StateTypeToString(hc->GetStateType());
564                         return true;
565                 } else if (macro == "HOSTATTEMPT") {
566                         *result = Convert::ToString(hc->GetCheckAttempt());
567                         return true;
568                 } else if (macro == "MAXHOSTATTEMPT") {
569                         *result = Convert::ToString(hc->GetMaxCheckAttempts());
570                         return true;
571                 } else if (macro == "LASTHOSTSTATE") {
572                         *result = StateToString(GetLastState());
573                         return true;
574                 } else if (macro == "LASTHOSTSTATEID") {
575                         *result = Convert::ToString(GetLastState());
576                         return true;
577                 } else if (macro == "LASTHOSTSTATETYPE") {
578                         *result = Service::StateTypeToString(GetLastStateType());
579                         return true;
580                 } else if (macro == "LASTHOSTSTATECHANGE") {
581                         *result = Convert::ToString((long)hc->GetLastStateChange());
582                         return true;
583                 } else if (macro == "HOSTDURATIONSEC") {
584                         *result = Convert::ToString((long)(Utility::GetTime() - hc->GetLastStateChange()));
585                         return true;
586                 }
587
588                 hccr = hc->GetLastCheckResult();
589         }
590
591         if (hccr) {
592                 if (macro == "HOSTLATENCY") {
593                         *result = Convert::ToString(Service::CalculateLatency(hccr));
594                         return true;
595                 } else if (macro == "HOSTEXECUTIONTIME") {
596                         *result = Convert::ToString(Service::CalculateExecutionTime(hccr));
597                         return true;
598                 } else if (macro == "HOSTOUTPUT") {
599                         *result = hccr->GetOutput();
600                         return true;
601                 } else if (macro == "HOSTPERFDATA") {
602                         *result = PluginUtility::FormatPerfdata(hccr->GetPerformanceData());
603                         return true;
604                 } else if (macro == "LASTHOSTCHECK") {
605                         *result = Convert::ToString((long)hccr->GetScheduleStart());
606                         return true;
607                 }
608         }
609
610         Dictionary::Ptr macros = GetMacros();
611
612         String name = macro;
613
614         if (name == "HOSTADDRESS")
615                 name = "address";
616         else if (macro == "HOSTADDRESS6")
617                 name = "address6";
618
619         if (macros && macros->Contains(name)) {
620                 *result = macros->Get(name);
621                 return true;
622         }
623
624         if (macro == "HOSTADDRESS" || macro == "HOSTADDRESS6") {
625                 *result = GetName();
626                 return true;
627         }
628
629         return false;
630 }