1 /******************************************************************************
3 * Copyright (C) 2012 Icinga Development Team (http://www.icinga.org/) *
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. *
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. *
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 ******************************************************************************/
20 #include "icinga/host.h"
21 #include "icinga/service.h"
22 #include "icinga/hostgroup.h"
23 #include "icinga/icingaapplication.h"
24 #include "base/dynamictype.h"
25 #include "base/objectlock.h"
26 #include "base/logger_fwd.h"
27 #include "base/timer.h"
28 #include "base/convert.h"
29 #include "base/scriptfunction.h"
30 #include "base/utility.h"
31 #include "config/configitembuilder.h"
32 #include "config/configcompilercontext.h"
33 #include <boost/tuple/tuple.hpp>
34 #include <boost/smart_ptr/make_shared.hpp>
35 #include <boost/foreach.hpp>
37 using namespace icinga;
39 static boost::mutex l_ServiceMutex;
40 static std::map<String, std::map<String, Service::WeakPtr> > l_ServicesCache;
41 static bool l_ServicesCacheNeedsUpdate = false;
42 static Timer::Ptr l_ServicesCacheTimer;
44 REGISTER_SCRIPTFUNCTION(ValidateServiceDictionary, &Host::ValidateServiceDictionary);
48 Host::Host(const Dictionary::Ptr& serializedUpdate)
49 : DynamicObject(serializedUpdate)
51 RegisterAttribute("display_name", Attribute_Config, &m_DisplayName);
52 RegisterAttribute("hostgroups", Attribute_Config, &m_HostGroups);
53 RegisterAttribute("macros", Attribute_Config, &m_Macros);
54 RegisterAttribute("hostdependencies", Attribute_Config, &m_HostDependencies);
55 RegisterAttribute("servicedependencies", Attribute_Config, &m_ServiceDependencies);
56 RegisterAttribute("hostcheck", Attribute_Config, &m_HostCheck);
62 HostGroup::InvalidateMembersCache();
64 if (m_SlaveServices) {
65 ConfigItem::Ptr service;
66 BOOST_FOREACH(boost::tie(boost::tuples::ignore, service), m_SlaveServices) {
67 service->Unregister();
72 void Host::OnRegistrationCompleted(void)
76 DynamicObject::OnRegistrationCompleted();
78 Host::InvalidateServicesCache();
79 UpdateSlaveServices();
82 String Host::GetDisplayName(void) const
84 if (!m_DisplayName.IsEmpty())
90 Host::Ptr Host::GetByName(const String& name)
92 DynamicObject::Ptr configObject = DynamicObject::GetObject("Host", name);
94 return dynamic_pointer_cast<Host>(configObject);
97 Array::Ptr Host::GetGroups(void) const
102 Dictionary::Ptr Host::GetMacros(void) const
107 Array::Ptr Host::GetHostDependencies(void) const
109 return m_HostDependencies;;
112 Array::Ptr Host::GetServiceDependencies(void) const
114 return m_ServiceDependencies;
117 String Host::GetHostCheck(void) const
122 bool Host::IsReachable(void) const
126 std::set<Service::Ptr> parentServices = GetParentServices();
128 BOOST_FOREACH(const Service::Ptr& service, parentServices) {
129 ObjectLock olock(service);
131 /* ignore pending services */
132 if (!service->GetLastCheckResult())
135 /* ignore soft states */
136 if (service->GetStateType() == StateTypeSoft)
139 /* ignore services states OK and Warning */
140 if (service->GetState() == StateOK ||
141 service->GetState() == StateWarning)
147 std::set<Host::Ptr> parentHosts = GetParentHosts();
149 BOOST_FOREACH(const Host::Ptr& host, parentHosts) {
150 Service::Ptr hc = host->GetHostCheckService();
152 /* ignore hosts that don't have a hostcheck */
156 ObjectLock olock(hc);
158 /* ignore soft states */
159 if (hc->GetStateType() == StateTypeSoft)
162 /* ignore hosts that are up */
163 if (hc->GetState() == StateOK)
172 void Host::UpdateSlaveServices(void)
176 ConfigItem::Ptr item = ConfigItem::GetObject("Host", GetName());
178 /* Don't create slave services unless we own this object */
182 Dictionary::Ptr oldServices = m_SlaveServices;
183 Dictionary::Ptr serviceDescs = Get("services");
185 Dictionary::Ptr newServices = boost::make_shared<Dictionary>();
188 ObjectLock olock(serviceDescs);
191 BOOST_FOREACH(boost::tie(svcname, svcdesc), serviceDescs) {
192 if (svcdesc.IsScalar())
195 std::ostringstream namebuf;
196 namebuf << GetName() << ":" << svcname;
197 String name = namebuf.str();
199 ConfigItemBuilder::Ptr builder = boost::make_shared<ConfigItemBuilder>(item->GetDebugInfo());
200 builder->SetType("Service");
201 builder->SetName(name);
202 builder->AddExpression("host_name", OperatorSet, GetName());
203 builder->AddExpression("display_name", OperatorSet, svcname);
204 builder->AddExpression("short_name", OperatorSet, svcname);
206 if (!svcdesc.IsObjectType<Dictionary>())
207 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be either a string or a dictionary."));
209 Dictionary::Ptr service = svcdesc;
211 Array::Ptr templates = service->Get("templates");
214 ObjectLock olock(templates);
216 BOOST_FOREACH(const Value& tmpl, templates) {
217 builder->AddParent(tmpl);
221 /* Clone attributes from the host object. */
222 std::set<String, string_iless> keys;
223 keys.insert("check_interval");
224 keys.insert("retry_interval");
225 keys.insert("servicegroups");
226 keys.insert("checkers");
227 keys.insert("notification_interval");
228 keys.insert("notification_type_filter");
229 keys.insert("notification_state_filter");
230 keys.insert("check_period");
231 keys.insert("servicedependencies");
232 keys.insert("hostdependencies");
233 keys.insert("export_macros");
235 ExpressionList::Ptr host_exprl = boost::make_shared<ExpressionList>();
236 item->GetLinkedExpressionList()->ExtractFiltered(keys, host_exprl);
237 builder->AddExpressionList(host_exprl);
239 /* Clone attributes from the service expression list. */
240 std::vector<String> path;
241 path.push_back("services");
242 path.push_back(svcname);
244 ExpressionList::Ptr svc_exprl = boost::make_shared<ExpressionList>();
245 item->GetLinkedExpressionList()->ExtractPath(path, svc_exprl);
246 builder->AddExpressionList(svc_exprl);
248 ConfigItem::Ptr serviceItem = builder->Compile();
249 DynamicObject::Ptr dobj = serviceItem->Commit();
251 newServices->Set(name, serviceItem);
256 ObjectLock olock(oldServices);
258 ConfigItem::Ptr service;
259 BOOST_FOREACH(boost::tie(boost::tuples::ignore, service), oldServices) {
263 if (!newServices->Contains(service->GetName()))
264 service->Unregister();
270 Set("slave_services", newServices);
273 void Host::OnAttributeChanged(const String& name)
277 if (name == "hostgroups")
278 HostGroup::InvalidateMembersCache();
279 else if (name == "services") {
280 UpdateSlaveServices();
281 } else if (name == "notifications") {
282 BOOST_FOREACH(const Service::Ptr& service, GetServices()) {
283 service->UpdateSlaveNotifications();
288 std::set<Service::Ptr> Host::GetServices(void) const
290 std::set<Service::Ptr> services;
292 boost::mutex::scoped_lock lock(l_ServiceMutex);
294 Service::WeakPtr wservice;
295 BOOST_FOREACH(boost::tie(boost::tuples::ignore, wservice), l_ServicesCache[GetName()]) {
296 Service::Ptr service = wservice.lock();
301 services.insert(service);
307 int Host::GetTotalServices(void) const
309 return GetServices().size();
312 void Host::InvalidateServicesCache(void)
315 boost::mutex::scoped_lock lock(l_ServiceMutex);
317 if (l_ServicesCacheNeedsUpdate)
318 return; /* Someone else has already requested a refresh. */
320 if (!l_ServicesCacheTimer) {
321 l_ServicesCacheTimer = boost::make_shared<Timer>();
322 l_ServicesCacheTimer->SetInterval(0.5);
323 l_ServicesCacheTimer->OnTimerExpired.connect(boost::bind(&Host::RefreshServicesCache));
324 l_ServicesCacheTimer->Start();
327 l_ServicesCacheNeedsUpdate = true;
331 void Host::RefreshServicesCache(void)
334 boost::mutex::scoped_lock lock(l_ServiceMutex);
336 if (!l_ServicesCacheNeedsUpdate)
339 l_ServicesCacheNeedsUpdate = false;
342 Log(LogDebug, "icinga", "Updating Host services cache.");
344 std::map<String, std::map<String, Service::WeakPtr> > newServicesCache;
346 BOOST_FOREACH(const DynamicObject::Ptr& object, DynamicType::GetObjects("Service")) {
347 const Service::Ptr& service = static_pointer_cast<Service>(object);
349 Host::Ptr host = service->GetHost();
354 // TODO: assert for duplicate short_names
356 newServicesCache[host->GetName()][service->GetShortName()] = service;
359 boost::mutex::scoped_lock lock(l_ServiceMutex);
360 l_ServicesCache.swap(newServicesCache);
363 Value Host::ValidateServiceDictionary(const String& location, const Dictionary::Ptr& attrs)
365 ObjectLock olock(attrs);
369 BOOST_FOREACH(boost::tie(key, value), attrs) {
370 std::vector<String> templates;
372 if (!value.IsObjectType<Dictionary>())
373 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be a dictionary."));
375 Dictionary::Ptr serviceDesc = value;
377 Array::Ptr templatesArray = serviceDesc->Get("templates");
379 if (templatesArray) {
380 ObjectLock tlock(templatesArray);
382 BOOST_FOREACH(const Value& tmpl, templatesArray) {
383 templates.push_back(tmpl);
387 BOOST_FOREACH(const String& name, templates) {
388 ConfigItem::Ptr item;
390 ConfigCompilerContext *context = ConfigCompilerContext::GetContext();
393 item = context->GetItem("Service", name);
395 /* ignore already active objects while we're in the compiler
396 * context and linking to existing items is disabled. */
397 if (!item && (!context || (context->GetFlags() & CompilerLinkExisting)))
398 item = ConfigItem::GetObject("Service", name);
401 ConfigCompilerContext::GetContext()->AddError(false, "Validation failed for " +
402 location + ": Template '" + name + "' not found.");
410 Service::Ptr Host::GetServiceByShortName(const Value& name) const
412 if (name.IsScalar()) {
414 boost::mutex::scoped_lock lock(l_ServiceMutex);
416 std::map<String, Service::WeakPtr>& services = l_ServicesCache[GetName()];
417 std::map<String, Service::WeakPtr>::iterator it = services.find(name);
419 if (it != services.end()) {
420 Service::Ptr service = it->second.lock();
426 return Service::Ptr();
427 } else if (name.IsObjectType<Dictionary>()) {
428 Dictionary::Ptr dict = name;
431 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
433 BOOST_THROW_EXCEPTION(std::invalid_argument("Host/Service name pair is invalid: " + name.Serialize()));
437 std::set<Host::Ptr> Host::GetParentHosts(void) const
439 std::set<Host::Ptr> parents;
441 Array::Ptr dependencies = GetHostDependencies();
444 ObjectLock olock(dependencies);
446 BOOST_FOREACH(const Value& value, dependencies) {
447 if (value == GetName())
450 Host::Ptr host = GetByName(value);
455 parents.insert(host);
462 Service::Ptr Host::GetHostCheckService(void) const
464 String host_check = GetHostCheck();
466 if (host_check.IsEmpty())
467 return Service::Ptr();
469 return GetServiceByShortName(host_check);
472 std::set<Service::Ptr> Host::GetParentServices(void) const
474 std::set<Service::Ptr> parents;
476 Array::Ptr dependencies = GetServiceDependencies();
479 ObjectLock olock(dependencies);
481 BOOST_FOREACH(const Value& value, dependencies) {
482 parents.insert(GetServiceByShortName(value));
489 HostState Host::CalculateState(ServiceState state, bool reachable)
492 return HostUnreachable;
503 HostState Host::GetState(void) const
508 return HostUnreachable;
510 Service::Ptr hc = GetHostCheckService();
515 switch (hc->GetState()) {
525 HostState Host::GetLastState(void) const
530 return HostUnreachable;
532 Service::Ptr hc = GetHostCheckService();
537 switch (hc->GetLastState()) {
546 HostState Host::GetLastHardState(void) const
551 return HostUnreachable;
553 Service::Ptr hc = GetHostCheckService();
558 switch (hc->GetLastHardState()) {
567 double Host::GetLastStateChange(void) const
569 Service::Ptr hc = GetHostCheckService();
572 return IcingaApplication::GetInstance()->GetStartTime();
574 return hc->GetLastStateChange();
578 double Host::GetLastHardStateChange(void) const
580 Service::Ptr hc = GetHostCheckService();
583 return IcingaApplication::GetInstance()->GetStartTime();
585 return hc->GetLastHardStateChange();
588 StateType Host::GetLastStateType(void) const
590 Service::Ptr hc = GetHostCheckService();
593 return StateTypeHard;
595 return hc->GetLastStateType();
598 StateType Host::GetStateType(void) const
600 Service::Ptr hc = GetHostCheckService();
603 return StateTypeHard;
605 return hc->GetStateType();
608 String Host::StateToString(HostState state)
615 case HostUnreachable:
616 return "UNREACHABLE";
622 bool Host::ResolveMacro(const String& macro, const Dictionary::Ptr&, String *result) const
624 if (macro == "HOSTNAME") {
628 else if (macro == "HOSTDISPLAYNAME" || macro == "HOSTALIAS") {
629 *result = GetDisplayName();
633 Service::Ptr hc = GetHostCheckService();
634 Dictionary::Ptr hccr;
637 ServiceState state = hc->GetState();
638 bool reachable = IsReachable();
640 if (macro == "HOSTSTATE") {
641 *result = Convert::ToString(CalculateState(state, reachable));
643 } else if (macro == "HOSTSTATEID") {
644 *result = Convert::ToString(state);
646 } else if (macro == "HOSTSTATETYPE") {
647 *result = Service::StateTypeToString(hc->GetStateType());
649 } else if (macro == "HOSTATTEMPT") {
650 *result = Convert::ToString(hc->GetCurrentCheckAttempt());
652 } else if (macro == "MAXHOSTATTEMPT") {
653 *result = Convert::ToString(hc->GetMaxCheckAttempts());
655 } else if (macro == "LASTHOSTSTATE") {
656 *result = StateToString(GetLastState());
658 } else if (macro == "LASTHOSTSTATEID") {
659 *result = Convert::ToString(GetLastState());
661 } else if (macro == "LASTHOSTSTATETYPE") {
662 *result = Service::StateTypeToString(GetLastStateType());
664 } else if (macro == "LASTHOSTSTATECHANGE") {
665 *result = Convert::ToString((long)hc->GetLastStateChange());
669 hccr = hc->GetLastCheckResult();
673 if (macro == "HOSTLATENCY") {
674 *result = Convert::ToString(Service::CalculateLatency(hccr));
676 } else if (macro == "HOSTEXECUTIONTIME") {
677 *result = Convert::ToString(Service::CalculateExecutionTime(hccr));
679 } else if (macro == "HOSTOUTPUT") {
680 *result = hccr->Get("output");
682 } else if (macro == "HOSTPERFDATA") {
683 *result = hccr->Get("performance_data_raw");
685 } else if (macro == "LASTHOSTCHECK") {
686 *result = Convert::ToString((long)hccr->Get("schedule_start"));
691 Dictionary::Ptr macros = GetMacros();
695 if (name == "HOSTADDRESS")
697 else if (macro == "HOSTADDRESS6")
700 if (macros && macros->Contains(name)) {
701 *result = macros->Get(name);
705 if (macro == "HOSTADDRESS" || macro == "HOSTADDRESS6") {