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");
234 keys.insert("macros");
235 keys.insert("custom");
237 ExpressionList::Ptr host_exprl = boost::make_shared<ExpressionList>();
238 item->GetLinkedExpressionList()->ExtractFiltered(keys, host_exprl);
239 builder->AddExpressionList(host_exprl);
241 /* Clone attributes from the service expression list. */
242 std::vector<String> path;
243 path.push_back("services");
244 path.push_back(svcname);
246 ExpressionList::Ptr svc_exprl = boost::make_shared<ExpressionList>();
247 item->GetLinkedExpressionList()->ExtractPath(path, svc_exprl);
248 builder->AddExpressionList(svc_exprl);
250 ConfigItem::Ptr serviceItem = builder->Compile();
251 DynamicObject::Ptr dobj = serviceItem->Commit();
253 newServices->Set(name, serviceItem);
258 ObjectLock olock(oldServices);
260 ConfigItem::Ptr service;
261 BOOST_FOREACH(boost::tie(boost::tuples::ignore, service), oldServices) {
265 if (!newServices->Contains(service->GetName()))
266 service->Unregister();
272 Set("slave_services", newServices);
275 void Host::OnAttributeChanged(const String& name)
279 if (name == "hostgroups")
280 HostGroup::InvalidateMembersCache();
281 else if (name == "services") {
282 UpdateSlaveServices();
283 } else if (name == "notifications") {
284 BOOST_FOREACH(const Service::Ptr& service, GetServices()) {
285 service->UpdateSlaveNotifications();
290 std::set<Service::Ptr> Host::GetServices(void) const
292 std::set<Service::Ptr> services;
294 boost::mutex::scoped_lock lock(l_ServiceMutex);
296 Service::WeakPtr wservice;
297 BOOST_FOREACH(boost::tie(boost::tuples::ignore, wservice), l_ServicesCache[GetName()]) {
298 Service::Ptr service = wservice.lock();
303 services.insert(service);
309 int Host::GetTotalServices(void) const
311 return GetServices().size();
314 void Host::InvalidateServicesCache(void)
317 boost::mutex::scoped_lock lock(l_ServiceMutex);
319 if (l_ServicesCacheNeedsUpdate)
320 return; /* Someone else has already requested a refresh. */
322 if (!l_ServicesCacheTimer) {
323 l_ServicesCacheTimer = boost::make_shared<Timer>();
324 l_ServicesCacheTimer->SetInterval(0.5);
325 l_ServicesCacheTimer->OnTimerExpired.connect(boost::bind(&Host::RefreshServicesCache));
326 l_ServicesCacheTimer->Start();
329 l_ServicesCacheNeedsUpdate = true;
333 void Host::RefreshServicesCache(void)
336 boost::mutex::scoped_lock lock(l_ServiceMutex);
338 if (!l_ServicesCacheNeedsUpdate)
341 l_ServicesCacheNeedsUpdate = false;
344 Log(LogDebug, "icinga", "Updating Host services cache.");
346 std::map<String, std::map<String, Service::WeakPtr> > newServicesCache;
348 BOOST_FOREACH(const DynamicObject::Ptr& object, DynamicType::GetObjects("Service")) {
349 const Service::Ptr& service = static_pointer_cast<Service>(object);
351 Host::Ptr host = service->GetHost();
356 // TODO: assert for duplicate short_names
358 newServicesCache[host->GetName()][service->GetShortName()] = service;
361 boost::mutex::scoped_lock lock(l_ServiceMutex);
362 l_ServicesCache.swap(newServicesCache);
365 Value Host::ValidateServiceDictionary(const String& location, const Dictionary::Ptr& attrs)
367 ObjectLock olock(attrs);
371 BOOST_FOREACH(boost::tie(key, value), attrs) {
372 std::vector<String> templates;
374 if (!value.IsObjectType<Dictionary>())
375 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be a dictionary."));
377 Dictionary::Ptr serviceDesc = value;
379 Array::Ptr templatesArray = serviceDesc->Get("templates");
381 if (templatesArray) {
382 ObjectLock tlock(templatesArray);
384 BOOST_FOREACH(const Value& tmpl, templatesArray) {
385 templates.push_back(tmpl);
389 BOOST_FOREACH(const String& name, templates) {
390 ConfigItem::Ptr item;
392 ConfigCompilerContext *context = ConfigCompilerContext::GetContext();
395 item = context->GetItem("Service", name);
397 /* ignore already active objects while we're in the compiler
398 * context and linking to existing items is disabled. */
399 if (!item && (!context || (context->GetFlags() & CompilerLinkExisting)))
400 item = ConfigItem::GetObject("Service", name);
403 ConfigCompilerContext::GetContext()->AddError(false, "Validation failed for " +
404 location + ": Template '" + name + "' not found.");
412 Service::Ptr Host::GetServiceByShortName(const Value& name) const
414 if (name.IsScalar()) {
416 boost::mutex::scoped_lock lock(l_ServiceMutex);
418 std::map<String, Service::WeakPtr>& services = l_ServicesCache[GetName()];
419 std::map<String, Service::WeakPtr>::iterator it = services.find(name);
421 if (it != services.end()) {
422 Service::Ptr service = it->second.lock();
428 return Service::Ptr();
429 } else if (name.IsObjectType<Dictionary>()) {
430 Dictionary::Ptr dict = name;
433 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
435 BOOST_THROW_EXCEPTION(std::invalid_argument("Host/Service name pair is invalid: " + name.Serialize()));
439 std::set<Host::Ptr> Host::GetParentHosts(void) const
441 std::set<Host::Ptr> parents;
443 Array::Ptr dependencies = GetHostDependencies();
446 ObjectLock olock(dependencies);
448 BOOST_FOREACH(const Value& value, dependencies) {
449 if (value == GetName())
452 Host::Ptr host = GetByName(value);
457 parents.insert(host);
464 std::set<Host::Ptr> Host::GetChildHosts(void) const
466 std::set<Host::Ptr> childs;
468 BOOST_FOREACH(const DynamicObject::Ptr& object, DynamicType::GetObjects("Host")) {
469 const Host::Ptr& host = static_pointer_cast<Host>(object);
471 Array::Ptr dependencies = host->GetHostDependencies();
474 ObjectLock olock(dependencies);
476 BOOST_FOREACH(const Value& value, dependencies) {
477 if (value == GetName())
487 Service::Ptr Host::GetHostCheckService(void) const
489 String host_check = GetHostCheck();
491 if (host_check.IsEmpty())
492 return Service::Ptr();
494 return GetServiceByShortName(host_check);
497 std::set<Service::Ptr> Host::GetParentServices(void) const
499 std::set<Service::Ptr> parents;
501 Array::Ptr dependencies = GetServiceDependencies();
504 ObjectLock olock(dependencies);
506 BOOST_FOREACH(const Value& value, dependencies) {
507 parents.insert(GetServiceByShortName(value));
514 HostState Host::CalculateState(ServiceState state, bool reachable)
517 return HostUnreachable;
528 HostState Host::GetState(void) const
533 return HostUnreachable;
535 Service::Ptr hc = GetHostCheckService();
540 switch (hc->GetState()) {
550 HostState Host::GetLastState(void) const
555 return HostUnreachable;
557 Service::Ptr hc = GetHostCheckService();
562 switch (hc->GetLastState()) {
571 HostState Host::GetLastHardState(void) const
576 return HostUnreachable;
578 Service::Ptr hc = GetHostCheckService();
583 switch (hc->GetLastHardState()) {
592 double Host::GetLastStateUp(void) const
596 Service::Ptr hc = GetHostCheckService();
601 if (hc->GetLastStateOK() > hc->GetLastStateWarning())
602 return hc->GetLastStateOK();
604 return hc->GetLastStateWarning();
607 double Host::GetLastStateDown(void) const
611 Service::Ptr hc = GetHostCheckService();
616 return hc->GetLastStateCritical();
619 double Host::GetLastStateUnreachable(void) const
623 Service::Ptr hc = GetHostCheckService();
628 return hc->GetLastStateUnreachable();
631 double Host::GetLastStateChange(void) const
633 Service::Ptr hc = GetHostCheckService();
636 return IcingaApplication::GetInstance()->GetStartTime();
638 return hc->GetLastStateChange();
642 double Host::GetLastHardStateChange(void) const
644 Service::Ptr hc = GetHostCheckService();
647 return IcingaApplication::GetInstance()->GetStartTime();
649 return hc->GetLastHardStateChange();
652 StateType Host::GetLastStateType(void) const
654 Service::Ptr hc = GetHostCheckService();
657 return StateTypeHard;
659 return hc->GetLastStateType();
662 StateType Host::GetStateType(void) const
664 Service::Ptr hc = GetHostCheckService();
667 return StateTypeHard;
669 return hc->GetStateType();
672 String Host::StateToString(HostState state)
679 case HostUnreachable:
680 return "UNREACHABLE";
686 bool Host::ResolveMacro(const String& macro, const Dictionary::Ptr&, String *result) const
688 if (macro == "HOSTNAME") {
692 else if (macro == "HOSTDISPLAYNAME" || macro == "HOSTALIAS") {
693 *result = GetDisplayName();
697 Service::Ptr hc = GetHostCheckService();
698 Dictionary::Ptr hccr;
701 ServiceState state = hc->GetState();
702 bool reachable = IsReachable();
704 if (macro == "HOSTSTATE") {
705 *result = Convert::ToString(CalculateState(state, reachable));
707 } else if (macro == "HOSTSTATEID") {
708 *result = Convert::ToString(state);
710 } else if (macro == "HOSTSTATETYPE") {
711 *result = Service::StateTypeToString(hc->GetStateType());
713 } else if (macro == "HOSTATTEMPT") {
714 *result = Convert::ToString(hc->GetCurrentCheckAttempt());
716 } else if (macro == "MAXHOSTATTEMPT") {
717 *result = Convert::ToString(hc->GetMaxCheckAttempts());
719 } else if (macro == "LASTHOSTSTATE") {
720 *result = StateToString(GetLastState());
722 } else if (macro == "LASTHOSTSTATEID") {
723 *result = Convert::ToString(GetLastState());
725 } else if (macro == "LASTHOSTSTATETYPE") {
726 *result = Service::StateTypeToString(GetLastStateType());
728 } else if (macro == "LASTHOSTSTATECHANGE") {
729 *result = Convert::ToString((long)hc->GetLastStateChange());
733 hccr = hc->GetLastCheckResult();
737 if (macro == "HOSTLATENCY") {
738 *result = Convert::ToString(Service::CalculateLatency(hccr));
740 } else if (macro == "HOSTEXECUTIONTIME") {
741 *result = Convert::ToString(Service::CalculateExecutionTime(hccr));
743 } else if (macro == "HOSTOUTPUT") {
744 *result = hccr->Get("output");
746 } else if (macro == "HOSTPERFDATA") {
747 *result = hccr->Get("performance_data_raw");
749 } else if (macro == "LASTHOSTCHECK") {
750 *result = Convert::ToString((long)hccr->Get("schedule_start"));
755 Dictionary::Ptr macros = GetMacros();
759 if (name == "HOSTADDRESS")
761 else if (macro == "HOSTADDRESS6")
764 if (macros && macros->Contains(name)) {
765 *result = macros->Get(name);
769 if (macro == "HOSTADDRESS" || macro == "HOSTADDRESS6") {