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