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());
61 void Host::OnConfigLoaded(void)
63 UpdateSlaveServices();
68 DynamicObject::Stop();
70 Array::Ptr groups = GetGroups();
73 BOOST_FOREACH(const String& name, groups) {
74 HostGroup::Ptr hg = HostGroup::GetByName(name);
77 hg->RemoveMember(GetSelf());
81 // TODO: unregister slave services/notifications?
84 String Host::GetDisplayName(void) const
86 if (!m_DisplayName.IsEmpty())
92 Array::Ptr Host::GetGroups(void) const
97 Dictionary::Ptr Host::GetMacros(void) const
102 Array::Ptr Host::GetHostDependencies(void) const
104 return m_HostDependencies;;
107 Array::Ptr Host::GetServiceDependencies(void) const
109 return m_ServiceDependencies;
112 String Host::GetHostCheck(void) const
117 Dictionary::Ptr Host::GetNotificationDescriptions(void) const
119 return m_NotificationDescriptions;
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 if (!m_ServiceDescriptions)
185 ObjectLock olock(m_ServiceDescriptions);
188 BOOST_FOREACH(boost::tie(svcname, svcdesc), m_ServiceDescriptions) {
189 if (svcdesc.IsScalar())
192 std::ostringstream namebuf;
193 namebuf << GetName() << ":" << svcname;
194 String name = namebuf.str();
196 ConfigItemBuilder::Ptr builder = boost::make_shared<ConfigItemBuilder>(item->GetDebugInfo());
197 builder->SetType("Service");
198 builder->SetName(name);
199 builder->AddExpression("host_name", OperatorSet, GetName());
200 builder->AddExpression("display_name", OperatorSet, svcname);
201 builder->AddExpression("short_name", OperatorSet, svcname);
203 if (!svcdesc.IsObjectType<Dictionary>())
204 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be either a string or a dictionary."));
206 Dictionary::Ptr service = svcdesc;
208 Array::Ptr templates = service->Get("templates");
211 ObjectLock olock(templates);
213 BOOST_FOREACH(const Value& tmpl, templates) {
214 builder->AddParent(tmpl);
218 /* Clone attributes from the host object. */
219 std::set<String, string_iless> keys;
220 keys.insert("check_interval");
221 keys.insert("retry_interval");
222 keys.insert("servicegroups");
223 keys.insert("checkers");
224 keys.insert("notification_interval");
225 keys.insert("notification_type_filter");
226 keys.insert("notification_state_filter");
227 keys.insert("check_period");
228 keys.insert("servicedependencies");
229 keys.insert("hostdependencies");
230 keys.insert("export_macros");
231 keys.insert("macros");
232 keys.insert("custom");
234 ExpressionList::Ptr host_exprl = boost::make_shared<ExpressionList>();
235 item->GetLinkedExpressionList()->ExtractFiltered(keys, host_exprl);
236 builder->AddExpressionList(host_exprl);
238 /* Clone attributes from the service expression list. */
239 std::vector<String> path;
240 path.push_back("services");
241 path.push_back(svcname);
243 ExpressionList::Ptr svc_exprl = boost::make_shared<ExpressionList>();
244 item->GetLinkedExpressionList()->ExtractPath(path, svc_exprl);
245 builder->AddExpressionList(svc_exprl);
247 ConfigItem::Ptr serviceItem = builder->Compile();
248 serviceItem->Register();
249 DynamicObject::Ptr dobj = serviceItem->Commit();
250 dobj->OnConfigLoaded();
254 std::set<Service::Ptr> Host::GetServices(void) const
256 boost::mutex::scoped_lock lock(m_ServicesMutex);
258 std::set<Service::Ptr> services;
259 Service::WeakPtr wservice;
260 BOOST_FOREACH(boost::tie(boost::tuples::ignore, wservice), m_Services) {
261 Service::Ptr service = wservice.lock();
266 services.insert(service);
272 void Host::AddService(const Service::Ptr& service)
274 boost::mutex::scoped_lock lock(m_ServicesMutex);
276 m_Services[service->GetShortName()] = service;
279 void Host::RemoveService(const Service::Ptr& service)
281 boost::mutex::scoped_lock lock(m_ServicesMutex);
283 m_Services.erase(service->GetShortName());
286 int Host::GetTotalServices(void) const
288 return GetServices().size();
291 Value Host::ValidateServiceDictionary(const String& location, const Dictionary::Ptr& attrs)
293 ObjectLock olock(attrs);
297 BOOST_FOREACH(boost::tie(key, value), attrs) {
298 std::vector<String> templates;
300 if (!value.IsObjectType<Dictionary>())
301 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be a dictionary."));
303 Dictionary::Ptr serviceDesc = value;
305 Array::Ptr templatesArray = serviceDesc->Get("templates");
307 if (templatesArray) {
308 ObjectLock tlock(templatesArray);
310 BOOST_FOREACH(const Value& tmpl, templatesArray) {
311 templates.push_back(tmpl);
315 BOOST_FOREACH(const String& name, templates) {
316 ConfigItem::Ptr item = ConfigItem::GetObject("Service", name);
319 ConfigCompilerContext::GetInstance()->AddError(false, "Validation failed for " +
320 location + ": Template '" + name + "' not found.");
327 Service::Ptr Host::GetServiceByShortName(const Value& name) const
329 if (name.IsScalar()) {
331 boost::mutex::scoped_lock lock(m_ServicesMutex);
333 std::map<String, Service::Ptr>::const_iterator it = m_Services.find(name);
335 if (it != m_Services.end())
339 return Service::Ptr();
340 } else if (name.IsObjectType<Dictionary>()) {
341 Dictionary::Ptr dict = name;
344 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
346 BOOST_THROW_EXCEPTION(std::invalid_argument("Host/Service name pair is invalid: " + name.Serialize()));
350 std::set<Host::Ptr> Host::GetParentHosts(void) const
352 std::set<Host::Ptr> parents;
354 Array::Ptr dependencies = GetHostDependencies();
357 ObjectLock olock(dependencies);
359 BOOST_FOREACH(const Value& value, dependencies) {
360 if (value == GetName())
363 Host::Ptr host = GetByName(value);
368 parents.insert(host);
375 std::set<Host::Ptr> Host::GetChildHosts(void) const
377 std::set<Host::Ptr> childs;
379 BOOST_FOREACH(const Host::Ptr& host, DynamicType::GetObjects<Host>()) {
380 Array::Ptr dependencies = host->GetHostDependencies();
383 ObjectLock olock(dependencies);
385 BOOST_FOREACH(const Value& value, dependencies) {
386 if (value == GetName())
396 Service::Ptr Host::GetHostCheckService(void) const
398 String host_check = GetHostCheck();
400 if (host_check.IsEmpty())
401 return Service::Ptr();
403 return GetServiceByShortName(host_check);
406 std::set<Service::Ptr> Host::GetParentServices(void) const
408 std::set<Service::Ptr> parents;
410 Array::Ptr dependencies = GetServiceDependencies();
413 ObjectLock olock(dependencies);
415 BOOST_FOREACH(const Value& value, dependencies) {
416 parents.insert(GetServiceByShortName(value));
423 HostState Host::CalculateState(ServiceState state, bool reachable)
426 return HostUnreachable;
437 HostState Host::GetState(void) const
442 return HostUnreachable;
444 Service::Ptr hc = GetHostCheckService();
449 switch (hc->GetState()) {
459 HostState Host::GetLastState(void) const
464 return HostUnreachable;
466 Service::Ptr hc = GetHostCheckService();
471 switch (hc->GetLastState()) {
480 HostState Host::GetLastHardState(void) const
485 return HostUnreachable;
487 Service::Ptr hc = GetHostCheckService();
492 switch (hc->GetLastHardState()) {
501 double Host::GetLastStateUp(void) const
505 Service::Ptr hc = GetHostCheckService();
510 if (hc->GetLastStateOK() > hc->GetLastStateWarning())
511 return hc->GetLastStateOK();
513 return hc->GetLastStateWarning();
516 double Host::GetLastStateDown(void) const
520 Service::Ptr hc = GetHostCheckService();
525 return hc->GetLastStateCritical();
528 double Host::GetLastStateUnreachable(void) const
532 Service::Ptr hc = GetHostCheckService();
537 return hc->GetLastStateUnreachable();
540 double Host::GetLastStateChange(void) const
542 Service::Ptr hc = GetHostCheckService();
545 return IcingaApplication::GetInstance()->GetStartTime();
547 return hc->GetLastStateChange();
551 double Host::GetLastHardStateChange(void) const
553 Service::Ptr hc = GetHostCheckService();
556 return IcingaApplication::GetInstance()->GetStartTime();
558 return hc->GetLastHardStateChange();
561 StateType Host::GetLastStateType(void) const
563 Service::Ptr hc = GetHostCheckService();
566 return StateTypeHard;
568 return hc->GetLastStateType();
571 StateType Host::GetStateType(void) const
573 Service::Ptr hc = GetHostCheckService();
576 return StateTypeHard;
578 return hc->GetStateType();
581 String Host::StateToString(HostState state)
588 case HostUnreachable:
589 return "UNREACHABLE";
595 bool Host::ResolveMacro(const String& macro, const Dictionary::Ptr&, String *result) const
597 if (macro == "HOSTNAME") {
601 else if (macro == "HOSTDISPLAYNAME" || macro == "HOSTALIAS") {
602 *result = GetDisplayName();
606 Service::Ptr hc = GetHostCheckService();
607 Dictionary::Ptr hccr;
610 ServiceState state = hc->GetState();
611 bool reachable = IsReachable();
613 if (macro == "HOSTSTATE") {
614 *result = Convert::ToString(CalculateState(state, reachable));
616 } else if (macro == "HOSTSTATEID") {
617 *result = Convert::ToString(state);
619 } else if (macro == "HOSTSTATETYPE") {
620 *result = Service::StateTypeToString(hc->GetStateType());
622 } else if (macro == "HOSTATTEMPT") {
623 *result = Convert::ToString(hc->GetCurrentCheckAttempt());
625 } else if (macro == "MAXHOSTATTEMPT") {
626 *result = Convert::ToString(hc->GetMaxCheckAttempts());
628 } else if (macro == "LASTHOSTSTATE") {
629 *result = StateToString(GetLastState());
631 } else if (macro == "LASTHOSTSTATEID") {
632 *result = Convert::ToString(GetLastState());
634 } else if (macro == "LASTHOSTSTATETYPE") {
635 *result = Service::StateTypeToString(GetLastStateType());
637 } else if (macro == "LASTHOSTSTATECHANGE") {
638 *result = Convert::ToString((long)hc->GetLastStateChange());
642 hccr = hc->GetLastCheckResult();
646 if (macro == "HOSTLATENCY") {
647 *result = Convert::ToString(Service::CalculateLatency(hccr));
649 } else if (macro == "HOSTEXECUTIONTIME") {
650 *result = Convert::ToString(Service::CalculateExecutionTime(hccr));
652 } else if (macro == "HOSTOUTPUT") {
653 *result = hccr->Get("output");
655 } else if (macro == "HOSTPERFDATA") {
656 *result = hccr->Get("performance_data_raw");
658 } else if (macro == "LASTHOSTCHECK") {
659 *result = Convert::ToString((long)hccr->Get("schedule_start"));
664 Dictionary::Ptr macros = GetMacros();
668 if (name == "HOSTADDRESS")
670 else if (macro == "HOSTADDRESS6")
673 if (macros && macros->Contains(name)) {
674 *result = macros->Get(name);
678 if (macro == "HOSTADDRESS" || macro == "HOSTADDRESS6") {
686 void Host::InternalSerialize(const Dictionary::Ptr& bag, int attributeTypes) const
688 DynamicObject::InternalSerialize(bag, attributeTypes);
690 if (attributeTypes & Attribute_Config) {
691 bag->Set("display_name", m_DisplayName);
692 bag->Set("hostgroups", m_HostGroups);
693 bag->Set("macros", m_Macros);
694 bag->Set("hostdependencies", m_HostDependencies);
695 bag->Set("servicedependencies", m_ServiceDependencies);
696 bag->Set("hostcheck", m_HostCheck);
697 bag->Set("services", m_ServiceDescriptions);
698 bag->Set("notifications", m_NotificationDescriptions);
702 void Host::InternalDeserialize(const Dictionary::Ptr& bag, int attributeTypes)
704 DynamicObject::InternalDeserialize(bag, attributeTypes);
706 if (attributeTypes & Attribute_Config) {
707 m_DisplayName = bag->Get("display_name");
708 m_HostGroups = bag->Get("hostgroups");
709 m_Macros = bag->Get("macros");
710 m_HostDependencies = bag->Get("hostdependencies");
711 m_ServiceDependencies = bag->Get("servicedependencies");
712 m_HostCheck = bag->Get("hostcheck");
713 m_ServiceDescriptions = bag->Get("services");
714 m_NotificationDescriptions = bag->Get("notifications");