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 BOOST_FOREACH(const String& name, groups) {
53 HostGroup::Ptr hg = HostGroup::GetByName(name);
56 hg->AddMember(GetSelf());
60 UpdateSlaveServices();
65 DynamicObject::Stop();
67 Array::Ptr groups = GetGroups();
70 BOOST_FOREACH(const String& name, groups) {
71 HostGroup::Ptr hg = HostGroup::GetByName(name);
74 hg->RemoveMember(GetSelf());
78 // TODO: unregister slave services/notifications?
81 String Host::GetDisplayName(void) const
83 if (!m_DisplayName.IsEmpty())
89 Array::Ptr Host::GetGroups(void) const
94 Dictionary::Ptr Host::GetMacros(void) const
99 Array::Ptr Host::GetHostDependencies(void) const
101 return m_HostDependencies;;
104 Array::Ptr Host::GetServiceDependencies(void) const
106 return m_ServiceDependencies;
109 String Host::GetHostCheck(void) const
114 Dictionary::Ptr Host::GetNotificationDescriptions(void) const
116 return m_NotificationDescriptions;
119 bool Host::IsReachable(void) const
123 std::set<Service::Ptr> parentServices = GetParentServices();
125 BOOST_FOREACH(const Service::Ptr& service, parentServices) {
126 ObjectLock olock(service);
128 /* ignore pending services */
129 if (!service->GetLastCheckResult())
132 /* ignore soft states */
133 if (service->GetStateType() == StateTypeSoft)
136 /* ignore services states OK and Warning */
137 if (service->GetState() == StateOK ||
138 service->GetState() == StateWarning)
144 std::set<Host::Ptr> parentHosts = GetParentHosts();
146 BOOST_FOREACH(const Host::Ptr& host, parentHosts) {
147 Service::Ptr hc = host->GetHostCheckService();
149 /* ignore hosts that don't have a hostcheck */
153 ObjectLock olock(hc);
155 /* ignore soft states */
156 if (hc->GetStateType() == StateTypeSoft)
159 /* ignore hosts that are up */
160 if (hc->GetState() == StateOK)
169 void Host::UpdateSlaveServices(void)
173 ConfigItem::Ptr item = ConfigItem::GetObject("Host", GetName());
175 /* Don't create slave services unless we own this object */
179 if (!m_ServiceDescriptions)
182 ObjectLock olock(m_ServiceDescriptions);
185 BOOST_FOREACH(boost::tie(svcname, svcdesc), m_ServiceDescriptions) {
186 if (svcdesc.IsScalar())
189 std::ostringstream namebuf;
190 namebuf << GetName() << ":" << svcname;
191 String name = namebuf.str();
193 ConfigItemBuilder::Ptr builder = boost::make_shared<ConfigItemBuilder>(item->GetDebugInfo());
194 builder->SetType("Service");
195 builder->SetName(name);
196 builder->AddExpression("host_name", OperatorSet, GetName());
197 builder->AddExpression("display_name", OperatorSet, svcname);
198 builder->AddExpression("short_name", OperatorSet, svcname);
200 if (!svcdesc.IsObjectType<Dictionary>())
201 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be either a string or a dictionary."));
203 Dictionary::Ptr service = svcdesc;
205 Array::Ptr templates = service->Get("templates");
208 ObjectLock olock(templates);
210 BOOST_FOREACH(const Value& tmpl, templates) {
211 builder->AddParent(tmpl);
215 /* Clone attributes from the host object. */
216 std::set<String, string_iless> keys;
217 keys.insert("check_interval");
218 keys.insert("retry_interval");
219 keys.insert("servicegroups");
220 keys.insert("checkers");
221 keys.insert("notification_interval");
222 keys.insert("notification_type_filter");
223 keys.insert("notification_state_filter");
224 keys.insert("check_period");
225 keys.insert("servicedependencies");
226 keys.insert("hostdependencies");
227 keys.insert("export_macros");
228 keys.insert("macros");
229 keys.insert("custom");
231 ExpressionList::Ptr host_exprl = boost::make_shared<ExpressionList>();
232 item->GetLinkedExpressionList()->ExtractFiltered(keys, host_exprl);
233 builder->AddExpressionList(host_exprl);
235 /* Clone attributes from the service expression list. */
236 std::vector<String> path;
237 path.push_back("services");
238 path.push_back(svcname);
240 ExpressionList::Ptr svc_exprl = boost::make_shared<ExpressionList>();
241 item->GetLinkedExpressionList()->ExtractPath(path, svc_exprl);
242 builder->AddExpressionList(svc_exprl);
244 ConfigItem::Ptr serviceItem = builder->Compile();
245 DynamicObject::Ptr dobj = serviceItem->Commit();
249 std::set<Service::Ptr> Host::GetServices(void) const
251 boost::mutex::scoped_lock lock(m_ServicesMutex);
253 std::set<Service::Ptr> services;
254 Service::WeakPtr wservice;
255 BOOST_FOREACH(boost::tie(boost::tuples::ignore, wservice), m_Services) {
256 Service::Ptr service = wservice.lock();
261 services.insert(service);
267 void Host::AddService(const Service::Ptr& service)
269 boost::mutex::scoped_lock lock(m_ServicesMutex);
271 m_Services[service->GetShortName()] = service;
274 void Host::RemoveService(const Service::Ptr& service)
276 boost::mutex::scoped_lock lock(m_ServicesMutex);
278 m_Services.erase(service->GetShortName());
281 int Host::GetTotalServices(void) const
283 return GetServices().size();
286 Value Host::ValidateServiceDictionary(const String& location, const Dictionary::Ptr& attrs)
288 ObjectLock olock(attrs);
292 BOOST_FOREACH(boost::tie(key, value), attrs) {
293 std::vector<String> templates;
295 if (!value.IsObjectType<Dictionary>())
296 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be a dictionary."));
298 Dictionary::Ptr serviceDesc = value;
300 Array::Ptr templatesArray = serviceDesc->Get("templates");
302 if (templatesArray) {
303 ObjectLock tlock(templatesArray);
305 BOOST_FOREACH(const Value& tmpl, templatesArray) {
306 templates.push_back(tmpl);
310 BOOST_FOREACH(const String& name, templates) {
311 ConfigItem::Ptr item = ConfigItem::GetObject("Service", name);
314 ConfigCompilerContext::GetInstance()->AddError(false, "Validation failed for " +
315 location + ": Template '" + name + "' not found.");
322 Service::Ptr Host::GetServiceByShortName(const Value& name) const
324 if (name.IsScalar()) {
326 boost::mutex::scoped_lock lock(m_ServicesMutex);
328 std::map<String, Service::Ptr>::const_iterator it = m_Services.find(name);
330 if (it != m_Services.end())
334 return Service::Ptr();
335 } else if (name.IsObjectType<Dictionary>()) {
336 Dictionary::Ptr dict = name;
339 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
341 BOOST_THROW_EXCEPTION(std::invalid_argument("Host/Service name pair is invalid: " + name.Serialize()));
345 std::set<Host::Ptr> Host::GetParentHosts(void) const
347 std::set<Host::Ptr> parents;
349 Array::Ptr dependencies = GetHostDependencies();
352 ObjectLock olock(dependencies);
354 BOOST_FOREACH(const Value& value, dependencies) {
355 if (value == GetName())
358 Host::Ptr host = GetByName(value);
363 parents.insert(host);
370 std::set<Host::Ptr> Host::GetChildHosts(void) const
372 std::set<Host::Ptr> childs;
374 BOOST_FOREACH(const Host::Ptr& host, DynamicType::GetObjects<Host>()) {
375 Array::Ptr dependencies = host->GetHostDependencies();
378 ObjectLock olock(dependencies);
380 BOOST_FOREACH(const Value& value, dependencies) {
381 if (value == GetName())
391 Service::Ptr Host::GetHostCheckService(void) const
393 String host_check = GetHostCheck();
395 if (host_check.IsEmpty())
396 return Service::Ptr();
398 return GetServiceByShortName(host_check);
401 std::set<Service::Ptr> Host::GetParentServices(void) const
403 std::set<Service::Ptr> parents;
405 Array::Ptr dependencies = GetServiceDependencies();
408 ObjectLock olock(dependencies);
410 BOOST_FOREACH(const Value& value, dependencies) {
411 parents.insert(GetServiceByShortName(value));
418 HostState Host::CalculateState(ServiceState state, bool reachable)
421 return HostUnreachable;
432 HostState Host::GetState(void) const
437 return HostUnreachable;
439 Service::Ptr hc = GetHostCheckService();
444 switch (hc->GetState()) {
454 HostState Host::GetLastState(void) const
459 return HostUnreachable;
461 Service::Ptr hc = GetHostCheckService();
466 switch (hc->GetLastState()) {
475 HostState Host::GetLastHardState(void) const
480 return HostUnreachable;
482 Service::Ptr hc = GetHostCheckService();
487 switch (hc->GetLastHardState()) {
496 double Host::GetLastStateUp(void) const
500 Service::Ptr hc = GetHostCheckService();
505 if (hc->GetLastStateOK() > hc->GetLastStateWarning())
506 return hc->GetLastStateOK();
508 return hc->GetLastStateWarning();
511 double Host::GetLastStateDown(void) const
515 Service::Ptr hc = GetHostCheckService();
520 return hc->GetLastStateCritical();
523 double Host::GetLastStateUnreachable(void) const
527 Service::Ptr hc = GetHostCheckService();
532 return hc->GetLastStateUnreachable();
535 double Host::GetLastStateChange(void) const
537 Service::Ptr hc = GetHostCheckService();
540 return IcingaApplication::GetInstance()->GetStartTime();
542 return hc->GetLastStateChange();
546 double Host::GetLastHardStateChange(void) const
548 Service::Ptr hc = GetHostCheckService();
551 return IcingaApplication::GetInstance()->GetStartTime();
553 return hc->GetLastHardStateChange();
556 StateType Host::GetLastStateType(void) const
558 Service::Ptr hc = GetHostCheckService();
561 return StateTypeHard;
563 return hc->GetLastStateType();
566 StateType Host::GetStateType(void) const
568 Service::Ptr hc = GetHostCheckService();
571 return StateTypeHard;
573 return hc->GetStateType();
576 String Host::StateToString(HostState state)
583 case HostUnreachable:
584 return "UNREACHABLE";
590 bool Host::ResolveMacro(const String& macro, const Dictionary::Ptr&, String *result) const
592 if (macro == "HOSTNAME") {
596 else if (macro == "HOSTDISPLAYNAME" || macro == "HOSTALIAS") {
597 *result = GetDisplayName();
601 Service::Ptr hc = GetHostCheckService();
602 Dictionary::Ptr hccr;
605 ServiceState state = hc->GetState();
606 bool reachable = IsReachable();
608 if (macro == "HOSTSTATE") {
609 *result = Convert::ToString(CalculateState(state, reachable));
611 } else if (macro == "HOSTSTATEID") {
612 *result = Convert::ToString(state);
614 } else if (macro == "HOSTSTATETYPE") {
615 *result = Service::StateTypeToString(hc->GetStateType());
617 } else if (macro == "HOSTATTEMPT") {
618 *result = Convert::ToString(hc->GetCurrentCheckAttempt());
620 } else if (macro == "MAXHOSTATTEMPT") {
621 *result = Convert::ToString(hc->GetMaxCheckAttempts());
623 } else if (macro == "LASTHOSTSTATE") {
624 *result = StateToString(GetLastState());
626 } else if (macro == "LASTHOSTSTATEID") {
627 *result = Convert::ToString(GetLastState());
629 } else if (macro == "LASTHOSTSTATETYPE") {
630 *result = Service::StateTypeToString(GetLastStateType());
632 } else if (macro == "LASTHOSTSTATECHANGE") {
633 *result = Convert::ToString((long)hc->GetLastStateChange());
637 hccr = hc->GetLastCheckResult();
641 if (macro == "HOSTLATENCY") {
642 *result = Convert::ToString(Service::CalculateLatency(hccr));
644 } else if (macro == "HOSTEXECUTIONTIME") {
645 *result = Convert::ToString(Service::CalculateExecutionTime(hccr));
647 } else if (macro == "HOSTOUTPUT") {
648 *result = hccr->Get("output");
650 } else if (macro == "HOSTPERFDATA") {
651 *result = hccr->Get("performance_data_raw");
653 } else if (macro == "LASTHOSTCHECK") {
654 *result = Convert::ToString((long)hccr->Get("schedule_start"));
659 Dictionary::Ptr macros = GetMacros();
663 if (name == "HOSTADDRESS")
665 else if (macro == "HOSTADDRESS6")
668 if (macros && macros->Contains(name)) {
669 *result = macros->Get(name);
673 if (macro == "HOSTADDRESS" || macro == "HOSTADDRESS6") {
681 void Host::InternalSerialize(const Dictionary::Ptr& bag, int attributeTypes) const
683 DynamicObject::InternalSerialize(bag, attributeTypes);
685 if (attributeTypes & Attribute_Config) {
686 bag->Set("display_name", m_DisplayName);
687 bag->Set("hostgroups", m_HostGroups);
688 bag->Set("macros", m_Macros);
689 bag->Set("hostdependencies", m_HostDependencies);
690 bag->Set("servicedependencies", m_ServiceDependencies);
691 bag->Set("hostcheck", m_HostCheck);
692 bag->Set("services", m_ServiceDescriptions);
693 bag->Set("notifications", m_NotificationDescriptions);
697 void Host::InternalDeserialize(const Dictionary::Ptr& bag, int attributeTypes)
699 DynamicObject::InternalDeserialize(bag, attributeTypes);
701 if (attributeTypes & Attribute_Config) {
702 m_DisplayName = bag->Get("display_name");
703 m_HostGroups = bag->Get("hostgroups");
704 m_Macros = bag->Get("macros");
705 m_HostDependencies = bag->Get("hostdependencies");
706 m_ServiceDependencies = bag->Get("servicedependencies");
707 m_HostCheck = bag->Get("hostcheck");
708 m_ServiceDescriptions = bag->Get("services");
709 m_NotificationDescriptions = bag->Get("notifications");