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