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/debug.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 REGISTER_SCRIPTFUNCTION(ValidateServiceDictionary, &Host::ValidateServiceDictionary);
43 void Host::Start(void)
45 DynamicObject::Start();
49 Array::Ptr groups = GetGroups();
52 ObjectLock olock(groups);
54 BOOST_FOREACH(const String& name, groups) {
55 HostGroup::Ptr hg = HostGroup::GetByName(name);
58 hg->AddMember(GetSelf());
63 void Host::OnConfigLoaded(void)
65 UpdateSlaveServices();
70 DynamicObject::Stop();
72 Array::Ptr groups = GetGroups();
75 ObjectLock olock(groups);
77 BOOST_FOREACH(const String& name, groups) {
78 HostGroup::Ptr hg = HostGroup::GetByName(name);
81 hg->RemoveMember(GetSelf());
85 // TODO: unregister slave services/notifications?
88 String Host::GetDisplayName(void) const
90 if (!m_DisplayName.IsEmpty())
96 Array::Ptr Host::GetGroups(void) const
101 Dictionary::Ptr Host::GetMacros(void) const
106 Array::Ptr Host::GetHostDependencies(void) const
108 return m_HostDependencies;;
111 Array::Ptr Host::GetServiceDependencies(void) const
113 return m_ServiceDependencies;
116 String Host::GetHostCheck(void) const
121 Dictionary::Ptr Host::GetNotificationDescriptions(void) const
123 return m_NotificationDescriptions;
126 bool Host::IsReachable(void) const
130 std::set<Service::Ptr> parentServices = GetParentServices();
132 BOOST_FOREACH(const Service::Ptr& service, parentServices) {
133 ObjectLock olock(service);
135 /* ignore pending services */
136 if (!service->GetLastCheckResult())
139 /* ignore soft states */
140 if (service->GetStateType() == StateTypeSoft)
143 /* ignore services states OK and Warning */
144 if (service->GetState() == StateOK ||
145 service->GetState() == StateWarning)
151 std::set<Host::Ptr> parentHosts = GetParentHosts();
153 BOOST_FOREACH(const Host::Ptr& host, parentHosts) {
154 Service::Ptr hc = host->GetHostCheckService();
156 /* ignore hosts that don't have a hostcheck */
160 ObjectLock olock(hc);
162 /* ignore soft states */
163 if (hc->GetStateType() == StateTypeSoft)
166 /* ignore hosts that are up */
167 if (hc->GetState() == StateOK)
176 void Host::UpdateSlaveServices(void)
180 ConfigItem::Ptr item = ConfigItem::GetObject("Host", GetName());
182 /* Don't create slave services unless we own this object */
186 if (!m_ServiceDescriptions)
189 ObjectLock olock(m_ServiceDescriptions);
192 BOOST_FOREACH(boost::tie(svcname, svcdesc), m_ServiceDescriptions) {
193 if (svcdesc.IsScalar())
196 std::ostringstream namebuf;
197 namebuf << GetName() << ":" << svcname;
198 String name = namebuf.str();
200 ConfigItemBuilder::Ptr builder = boost::make_shared<ConfigItemBuilder>(item->GetDebugInfo());
201 builder->SetType("Service");
202 builder->SetName(name);
203 builder->AddExpression("host_name", OperatorSet, GetName());
204 builder->AddExpression("display_name", OperatorSet, svcname);
205 builder->AddExpression("short_name", OperatorSet, svcname);
207 if (!svcdesc.IsObjectType<Dictionary>())
208 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be either a string or a dictionary."));
210 Dictionary::Ptr service = svcdesc;
212 Array::Ptr templates = service->Get("templates");
215 ObjectLock olock(templates);
217 BOOST_FOREACH(const Value& tmpl, templates) {
218 builder->AddParent(tmpl);
222 /* Clone attributes from the host object. */
223 std::set<String, string_iless> keys;
224 keys.insert("check_interval");
225 keys.insert("retry_interval");
226 keys.insert("servicegroups");
227 keys.insert("checkers");
228 keys.insert("notification_interval");
229 keys.insert("notification_type_filter");
230 keys.insert("notification_state_filter");
231 keys.insert("check_period");
232 keys.insert("servicedependencies");
233 keys.insert("hostdependencies");
234 keys.insert("export_macros");
235 keys.insert("macros");
236 keys.insert("custom");
238 ExpressionList::Ptr host_exprl = boost::make_shared<ExpressionList>();
239 item->GetLinkedExpressionList()->ExtractFiltered(keys, host_exprl);
240 builder->AddExpressionList(host_exprl);
242 /* Clone attributes from the service expression list. */
243 std::vector<String> path;
244 path.push_back("services");
245 path.push_back(svcname);
247 ExpressionList::Ptr svc_exprl = boost::make_shared<ExpressionList>();
248 item->GetLinkedExpressionList()->ExtractPath(path, svc_exprl);
249 builder->AddExpressionList(svc_exprl);
251 ConfigItem::Ptr serviceItem = builder->Compile();
252 serviceItem->Register();
253 DynamicObject::Ptr dobj = serviceItem->Commit();
254 dobj->OnConfigLoaded();
258 std::set<Service::Ptr> Host::GetServices(void) const
260 boost::mutex::scoped_lock lock(m_ServicesMutex);
262 std::set<Service::Ptr> services;
263 Service::WeakPtr wservice;
264 BOOST_FOREACH(boost::tie(boost::tuples::ignore, wservice), m_Services) {
265 Service::Ptr service = wservice.lock();
270 services.insert(service);
276 void Host::AddService(const Service::Ptr& service)
278 boost::mutex::scoped_lock lock(m_ServicesMutex);
280 m_Services[service->GetShortName()] = service;
283 void Host::RemoveService(const Service::Ptr& service)
285 boost::mutex::scoped_lock lock(m_ServicesMutex);
287 m_Services.erase(service->GetShortName());
290 int Host::GetTotalServices(void) const
292 return GetServices().size();
295 Value Host::ValidateServiceDictionary(const String& location, const Dictionary::Ptr& attrs)
297 ObjectLock olock(attrs);
301 BOOST_FOREACH(boost::tie(key, value), attrs) {
302 std::vector<String> templates;
304 if (!value.IsObjectType<Dictionary>())
305 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be a dictionary."));
307 Dictionary::Ptr serviceDesc = value;
309 Array::Ptr templatesArray = serviceDesc->Get("templates");
311 if (templatesArray) {
312 ObjectLock tlock(templatesArray);
314 BOOST_FOREACH(const Value& tmpl, templatesArray) {
315 templates.push_back(tmpl);
319 BOOST_FOREACH(const String& name, templates) {
320 ConfigItem::Ptr item = ConfigItem::GetObject("Service", name);
323 ConfigCompilerContext::GetInstance()->AddError(false, "Validation failed for " +
324 location + ": Template '" + name + "' not found.");
331 Service::Ptr Host::GetServiceByShortName(const Value& name) const
333 if (name.IsScalar()) {
335 boost::mutex::scoped_lock lock(m_ServicesMutex);
337 std::map<String, Service::Ptr>::const_iterator it = m_Services.find(name);
339 if (it != m_Services.end())
343 return Service::Ptr();
344 } else if (name.IsObjectType<Dictionary>()) {
345 Dictionary::Ptr dict = name;
348 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
350 BOOST_THROW_EXCEPTION(std::invalid_argument("Host/Service name pair is invalid: " + name.Serialize()));
354 std::set<Host::Ptr> Host::GetParentHosts(void) const
356 std::set<Host::Ptr> parents;
358 Array::Ptr dependencies = GetHostDependencies();
361 ObjectLock olock(dependencies);
363 BOOST_FOREACH(const Value& value, dependencies) {
364 if (value == GetName())
367 Host::Ptr host = GetByName(value);
372 parents.insert(host);
379 std::set<Host::Ptr> Host::GetChildHosts(void) const
381 std::set<Host::Ptr> childs;
383 BOOST_FOREACH(const Host::Ptr& host, DynamicType::GetObjects<Host>()) {
384 Array::Ptr dependencies = host->GetHostDependencies();
387 ObjectLock olock(dependencies);
389 BOOST_FOREACH(const Value& value, dependencies) {
390 if (value == GetName())
400 Service::Ptr Host::GetHostCheckService(void) const
402 String host_check = GetHostCheck();
404 if (host_check.IsEmpty())
405 return Service::Ptr();
407 return GetServiceByShortName(host_check);
410 std::set<Service::Ptr> Host::GetParentServices(void) const
412 std::set<Service::Ptr> parents;
414 Array::Ptr dependencies = GetServiceDependencies();
417 ObjectLock olock(dependencies);
419 BOOST_FOREACH(const Value& value, dependencies) {
420 parents.insert(GetServiceByShortName(value));
427 HostState Host::CalculateState(ServiceState state, bool reachable)
430 return HostUnreachable;
441 HostState Host::GetState(void) const
446 return HostUnreachable;
448 Service::Ptr hc = GetHostCheckService();
453 switch (hc->GetState()) {
463 HostState Host::GetLastState(void) const
468 return HostUnreachable;
470 Service::Ptr hc = GetHostCheckService();
475 switch (hc->GetLastState()) {
484 HostState Host::GetLastHardState(void) const
489 return HostUnreachable;
491 Service::Ptr hc = GetHostCheckService();
496 switch (hc->GetLastHardState()) {
505 double Host::GetLastStateUp(void) const
509 Service::Ptr hc = GetHostCheckService();
514 if (hc->GetLastStateOK() > hc->GetLastStateWarning())
515 return hc->GetLastStateOK();
517 return hc->GetLastStateWarning();
520 double Host::GetLastStateDown(void) const
524 Service::Ptr hc = GetHostCheckService();
529 return hc->GetLastStateCritical();
532 double Host::GetLastStateUnreachable(void) const
536 Service::Ptr hc = GetHostCheckService();
541 return hc->GetLastStateUnreachable();
544 double Host::GetLastStateChange(void) const
546 Service::Ptr hc = GetHostCheckService();
549 return IcingaApplication::GetInstance()->GetStartTime();
551 return hc->GetLastStateChange();
555 double Host::GetLastHardStateChange(void) const
557 Service::Ptr hc = GetHostCheckService();
560 return IcingaApplication::GetInstance()->GetStartTime();
562 return hc->GetLastHardStateChange();
565 StateType Host::GetLastStateType(void) const
567 Service::Ptr hc = GetHostCheckService();
570 return StateTypeHard;
572 return hc->GetLastStateType();
575 StateType Host::GetStateType(void) const
577 Service::Ptr hc = GetHostCheckService();
580 return StateTypeHard;
582 return hc->GetStateType();
585 String Host::StateToString(HostState state)
592 case HostUnreachable:
593 return "UNREACHABLE";
599 bool Host::ResolveMacro(const String& macro, const Dictionary::Ptr&, String *result) const
601 if (macro == "HOSTNAME") {
605 else if (macro == "HOSTDISPLAYNAME" || macro == "HOSTALIAS") {
606 *result = GetDisplayName();
610 Service::Ptr hc = GetHostCheckService();
611 Dictionary::Ptr hccr;
614 ServiceState state = hc->GetState();
615 bool reachable = IsReachable();
617 if (macro == "HOSTSTATE") {
618 HostState hstate = CalculateState(state, reachable);
621 case HostUnreachable:
622 *result = "UNREACHABLE";
635 } else if (macro == "HOSTSTATEID") {
636 *result = Convert::ToString(state);
638 } else if (macro == "HOSTSTATETYPE") {
639 *result = Service::StateTypeToString(hc->GetStateType());
641 } else if (macro == "HOSTATTEMPT") {
642 *result = Convert::ToString(hc->GetCurrentCheckAttempt());
644 } else if (macro == "MAXHOSTATTEMPT") {
645 *result = Convert::ToString(hc->GetMaxCheckAttempts());
647 } else if (macro == "LASTHOSTSTATE") {
648 *result = StateToString(GetLastState());
650 } else if (macro == "LASTHOSTSTATEID") {
651 *result = Convert::ToString(GetLastState());
653 } else if (macro == "LASTHOSTSTATETYPE") {
654 *result = Service::StateTypeToString(GetLastStateType());
656 } else if (macro == "LASTHOSTSTATECHANGE") {
657 *result = Convert::ToString((long)hc->GetLastStateChange());
661 hccr = hc->GetLastCheckResult();
665 if (macro == "HOSTLATENCY") {
666 *result = Convert::ToString(Service::CalculateLatency(hccr));
668 } else if (macro == "HOSTEXECUTIONTIME") {
669 *result = Convert::ToString(Service::CalculateExecutionTime(hccr));
671 } else if (macro == "HOSTOUTPUT") {
672 *result = hccr->Get("output");
674 } else if (macro == "HOSTPERFDATA") {
675 *result = hccr->Get("performance_data_raw");
677 } else if (macro == "LASTHOSTCHECK") {
678 *result = Convert::ToString((long)hccr->Get("schedule_start"));
683 Dictionary::Ptr macros = GetMacros();
687 if (name == "HOSTADDRESS")
689 else if (macro == "HOSTADDRESS6")
692 if (macros && macros->Contains(name)) {
693 *result = macros->Get(name);
697 if (macro == "HOSTADDRESS" || macro == "HOSTADDRESS6") {
705 void Host::InternalSerialize(const Dictionary::Ptr& bag, int attributeTypes) const
707 DynamicObject::InternalSerialize(bag, attributeTypes);
709 if (attributeTypes & Attribute_Config) {
710 bag->Set("display_name", m_DisplayName);
711 bag->Set("hostgroups", m_HostGroups);
712 bag->Set("macros", m_Macros);
713 bag->Set("hostdependencies", m_HostDependencies);
714 bag->Set("servicedependencies", m_ServiceDependencies);
715 bag->Set("hostcheck", m_HostCheck);
716 bag->Set("services", m_ServiceDescriptions);
717 bag->Set("notifications", m_NotificationDescriptions);
721 void Host::InternalDeserialize(const Dictionary::Ptr& bag, int attributeTypes)
723 DynamicObject::InternalDeserialize(bag, attributeTypes);
725 if (attributeTypes & Attribute_Config) {
726 m_DisplayName = bag->Get("display_name");
727 m_HostGroups = bag->Get("hostgroups");
728 m_Macros = bag->Get("macros");
729 m_HostDependencies = bag->Get("hostdependencies");
730 m_ServiceDependencies = bag->Get("servicedependencies");
731 m_HostCheck = bag->Get("hostcheck");
732 m_ServiceDescriptions = bag->Get("services");
733 m_NotificationDescriptions = bag->Get("notifications");