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");
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 serviceItem->Register();
250 DynamicObject::Ptr dobj = serviceItem->Commit();
251 dobj->OnConfigLoaded();
255 std::set<Service::Ptr> Host::GetServices(void) const
257 boost::mutex::scoped_lock lock(m_ServicesMutex);
259 std::set<Service::Ptr> services;
260 Service::WeakPtr wservice;
261 BOOST_FOREACH(boost::tie(boost::tuples::ignore, wservice), m_Services) {
262 Service::Ptr service = wservice.lock();
267 services.insert(service);
273 void Host::AddService(const Service::Ptr& service)
275 boost::mutex::scoped_lock lock(m_ServicesMutex);
277 m_Services[service->GetShortName()] = service;
280 void Host::RemoveService(const Service::Ptr& service)
282 boost::mutex::scoped_lock lock(m_ServicesMutex);
284 m_Services.erase(service->GetShortName());
287 int Host::GetTotalServices(void) const
289 return GetServices().size();
292 Value Host::ValidateServiceDictionary(const String& location, const Dictionary::Ptr& attrs)
294 ObjectLock olock(attrs);
298 BOOST_FOREACH(boost::tie(key, value), attrs) {
299 std::vector<String> templates;
301 if (!value.IsObjectType<Dictionary>())
302 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be a dictionary."));
304 Dictionary::Ptr serviceDesc = value;
306 Array::Ptr templatesArray = serviceDesc->Get("templates");
308 if (templatesArray) {
309 ObjectLock tlock(templatesArray);
311 BOOST_FOREACH(const Value& tmpl, templatesArray) {
312 templates.push_back(tmpl);
316 BOOST_FOREACH(const String& name, templates) {
317 ConfigItem::Ptr item = ConfigItem::GetObject("Service", name);
320 ConfigCompilerContext::GetInstance()->AddError(false, "Validation failed for " +
321 location + ": Template '" + name + "' not found.");
328 Service::Ptr Host::GetServiceByShortName(const Value& name) const
330 if (name.IsScalar()) {
332 boost::mutex::scoped_lock lock(m_ServicesMutex);
334 std::map<String, Service::Ptr>::const_iterator it = m_Services.find(name);
336 if (it != m_Services.end())
340 return Service::Ptr();
341 } else if (name.IsObjectType<Dictionary>()) {
342 Dictionary::Ptr dict = name;
345 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
347 BOOST_THROW_EXCEPTION(std::invalid_argument("Host/Service name pair is invalid: " + name.Serialize()));
351 std::set<Host::Ptr> Host::GetParentHosts(void) const
353 std::set<Host::Ptr> parents;
355 Array::Ptr dependencies = GetHostDependencies();
358 ObjectLock olock(dependencies);
360 BOOST_FOREACH(const Value& value, dependencies) {
361 if (value == GetName())
364 Host::Ptr host = GetByName(value);
369 parents.insert(host);
376 std::set<Host::Ptr> Host::GetChildHosts(void) const
378 std::set<Host::Ptr> childs;
380 BOOST_FOREACH(const Host::Ptr& host, DynamicType::GetObjects<Host>()) {
381 Array::Ptr dependencies = host->GetHostDependencies();
384 ObjectLock olock(dependencies);
386 BOOST_FOREACH(const Value& value, dependencies) {
387 if (value == GetName())
397 Service::Ptr Host::GetHostCheckService(void) const
399 String host_check = GetHostCheck();
401 if (host_check.IsEmpty())
402 return Service::Ptr();
404 return GetServiceByShortName(host_check);
407 std::set<Service::Ptr> Host::GetParentServices(void) const
409 std::set<Service::Ptr> parents;
411 Array::Ptr dependencies = GetServiceDependencies();
414 ObjectLock olock(dependencies);
416 BOOST_FOREACH(const Value& value, dependencies) {
417 parents.insert(GetServiceByShortName(value));
424 HostState Host::CalculateState(ServiceState state, bool reachable)
427 return HostUnreachable;
438 HostState Host::GetState(void) const
443 return HostUnreachable;
445 Service::Ptr hc = GetHostCheckService();
450 switch (hc->GetState()) {
460 HostState Host::GetLastState(void) const
465 return HostUnreachable;
467 Service::Ptr hc = GetHostCheckService();
472 switch (hc->GetLastState()) {
481 HostState Host::GetLastHardState(void) const
486 return HostUnreachable;
488 Service::Ptr hc = GetHostCheckService();
493 switch (hc->GetLastHardState()) {
502 double Host::GetLastStateUp(void) const
506 Service::Ptr hc = GetHostCheckService();
511 if (hc->GetLastStateOK() > hc->GetLastStateWarning())
512 return hc->GetLastStateOK();
514 return hc->GetLastStateWarning();
517 double Host::GetLastStateDown(void) const
521 Service::Ptr hc = GetHostCheckService();
526 return hc->GetLastStateCritical();
529 double Host::GetLastStateUnreachable(void) const
533 Service::Ptr hc = GetHostCheckService();
538 return hc->GetLastStateUnreachable();
541 double Host::GetLastStateChange(void) const
543 Service::Ptr hc = GetHostCheckService();
546 return IcingaApplication::GetInstance()->GetStartTime();
548 return hc->GetLastStateChange();
552 double Host::GetLastHardStateChange(void) const
554 Service::Ptr hc = GetHostCheckService();
557 return IcingaApplication::GetInstance()->GetStartTime();
559 return hc->GetLastHardStateChange();
562 StateType Host::GetLastStateType(void) const
564 Service::Ptr hc = GetHostCheckService();
567 return StateTypeHard;
569 return hc->GetLastStateType();
572 StateType Host::GetStateType(void) const
574 Service::Ptr hc = GetHostCheckService();
577 return StateTypeHard;
579 return hc->GetStateType();
582 String Host::StateToString(HostState state)
589 case HostUnreachable:
590 return "UNREACHABLE";
596 bool Host::ResolveMacro(const String& macro, const Dictionary::Ptr&, String *result) const
598 if (macro == "HOSTNAME") {
602 else if (macro == "HOSTDISPLAYNAME" || macro == "HOSTALIAS") {
603 *result = GetDisplayName();
607 Service::Ptr hc = GetHostCheckService();
608 Dictionary::Ptr hccr;
611 ServiceState state = hc->GetState();
612 bool reachable = IsReachable();
614 if (macro == "HOSTSTATE") {
615 HostState hstate = CalculateState(state, reachable);
618 case HostUnreachable:
619 *result = "UNREACHABLE";
632 } else if (macro == "HOSTSTATEID") {
633 *result = Convert::ToString(state);
635 } else if (macro == "HOSTSTATETYPE") {
636 *result = Service::StateTypeToString(hc->GetStateType());
638 } else if (macro == "HOSTATTEMPT") {
639 *result = Convert::ToString(hc->GetCurrentCheckAttempt());
641 } else if (macro == "MAXHOSTATTEMPT") {
642 *result = Convert::ToString(hc->GetMaxCheckAttempts());
644 } else if (macro == "LASTHOSTSTATE") {
645 *result = StateToString(GetLastState());
647 } else if (macro == "LASTHOSTSTATEID") {
648 *result = Convert::ToString(GetLastState());
650 } else if (macro == "LASTHOSTSTATETYPE") {
651 *result = Service::StateTypeToString(GetLastStateType());
653 } else if (macro == "LASTHOSTSTATECHANGE") {
654 *result = Convert::ToString((long)hc->GetLastStateChange());
658 hccr = hc->GetLastCheckResult();
662 if (macro == "HOSTLATENCY") {
663 *result = Convert::ToString(Service::CalculateLatency(hccr));
665 } else if (macro == "HOSTEXECUTIONTIME") {
666 *result = Convert::ToString(Service::CalculateExecutionTime(hccr));
668 } else if (macro == "HOSTOUTPUT") {
669 *result = hccr->Get("output");
671 } else if (macro == "HOSTPERFDATA") {
672 *result = hccr->Get("performance_data_raw");
674 } else if (macro == "LASTHOSTCHECK") {
675 *result = Convert::ToString((long)hccr->Get("schedule_start"));
680 Dictionary::Ptr macros = GetMacros();
684 if (name == "HOSTADDRESS")
686 else if (macro == "HOSTADDRESS6")
689 if (macros && macros->Contains(name)) {
690 *result = macros->Get(name);
694 if (macro == "HOSTADDRESS" || macro == "HOSTADDRESS6") {
702 void Host::InternalSerialize(const Dictionary::Ptr& bag, int attributeTypes) const
704 DynamicObject::InternalSerialize(bag, attributeTypes);
706 if (attributeTypes & Attribute_Config) {
707 bag->Set("display_name", m_DisplayName);
708 bag->Set("hostgroups", m_HostGroups);
709 bag->Set("macros", m_Macros);
710 bag->Set("hostdependencies", m_HostDependencies);
711 bag->Set("servicedependencies", m_ServiceDependencies);
712 bag->Set("hostcheck", m_HostCheck);
713 bag->Set("services", m_ServiceDescriptions);
714 bag->Set("notifications", m_NotificationDescriptions);
718 void Host::InternalDeserialize(const Dictionary::Ptr& bag, int attributeTypes)
720 DynamicObject::InternalDeserialize(bag, attributeTypes);
722 if (attributeTypes & Attribute_Config) {
723 m_DisplayName = bag->Get("display_name");
724 m_HostGroups = bag->Get("hostgroups");
725 m_Macros = bag->Get("macros");
726 m_HostDependencies = bag->Get("hostdependencies");
727 m_ServiceDependencies = bag->Get("servicedependencies");
728 m_HostCheck = bag->Get("hostcheck");
729 m_ServiceDescriptions = bag->Get("services");
730 m_NotificationDescriptions = bag->Get("notifications");