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("custom", Attribute_Config, &m_Custom);
55 RegisterAttribute("hostdependencies", Attribute_Config, &m_HostDependencies);
56 RegisterAttribute("servicedependencies", Attribute_Config, &m_ServiceDependencies);
57 RegisterAttribute("hostcheck", Attribute_Config, &m_HostCheck);
63 HostGroup::InvalidateMembersCache();
65 if (m_SlaveServices) {
66 ConfigItem::Ptr service;
67 BOOST_FOREACH(boost::tie(boost::tuples::ignore, service), m_SlaveServices) {
68 service->Unregister();
73 void Host::OnRegistrationCompleted(void)
77 DynamicObject::OnRegistrationCompleted();
79 Host::InvalidateServicesCache();
80 UpdateSlaveServices();
83 String Host::GetDisplayName(void) const
85 if (!m_DisplayName.IsEmpty())
91 Host::Ptr Host::GetByName(const String& name)
93 DynamicObject::Ptr configObject = DynamicObject::GetObject("Host", name);
95 return dynamic_pointer_cast<Host>(configObject);
98 Array::Ptr Host::GetGroups(void) const
103 Dictionary::Ptr Host::GetMacros(void) const
108 Dictionary::Ptr Host::GetCustom(void) const
113 Array::Ptr Host::GetHostDependencies(void) const
115 return m_HostDependencies;;
118 Array::Ptr Host::GetServiceDependencies(void) const
120 return m_ServiceDependencies;
123 String Host::GetHostCheck(void) const
128 bool Host::IsReachable(void) const
132 std::set<Service::Ptr> parentServices = GetParentServices();
134 BOOST_FOREACH(const Service::Ptr& service, parentServices) {
135 ObjectLock olock(service);
137 /* ignore pending services */
138 if (!service->GetLastCheckResult())
141 /* ignore soft states */
142 if (service->GetStateType() == StateTypeSoft)
145 /* ignore services states OK and Warning */
146 if (service->GetState() == StateOK ||
147 service->GetState() == StateWarning)
153 std::set<Host::Ptr> parentHosts = GetParentHosts();
155 BOOST_FOREACH(const Host::Ptr& host, parentHosts) {
156 Service::Ptr hc = host->GetHostCheckService();
158 /* ignore hosts that don't have a hostcheck */
162 ObjectLock olock(hc);
164 /* ignore soft states */
165 if (hc->GetStateType() == StateTypeSoft)
168 /* ignore hosts that are up */
169 if (hc->GetState() == StateOK)
178 void Host::UpdateSlaveServices(void)
182 ConfigItem::Ptr item = ConfigItem::GetObject("Host", GetName());
184 /* Don't create slave services unless we own this object */
188 Dictionary::Ptr oldServices = m_SlaveServices;
189 Dictionary::Ptr serviceDescs = Get("services");
191 Dictionary::Ptr newServices = boost::make_shared<Dictionary>();
194 ObjectLock olock(serviceDescs);
197 BOOST_FOREACH(boost::tie(svcname, svcdesc), serviceDescs) {
198 if (svcdesc.IsScalar())
201 std::ostringstream namebuf;
202 namebuf << GetName() << ":" << svcname;
203 String name = namebuf.str();
205 ConfigItemBuilder::Ptr builder = boost::make_shared<ConfigItemBuilder>(item->GetDebugInfo());
206 builder->SetType("Service");
207 builder->SetName(name);
208 builder->AddExpression("host_name", OperatorSet, GetName());
209 builder->AddExpression("display_name", OperatorSet, svcname);
210 builder->AddExpression("short_name", OperatorSet, svcname);
212 if (!svcdesc.IsObjectType<Dictionary>())
213 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be either a string or a dictionary."));
215 Dictionary::Ptr service = svcdesc;
217 Array::Ptr templates = service->Get("templates");
220 ObjectLock olock(templates);
222 BOOST_FOREACH(const Value& tmpl, templates) {
223 builder->AddParent(tmpl);
227 /* Clone attributes from the host object. */
228 std::set<String, string_iless> keys;
229 keys.insert("check_interval");
230 keys.insert("retry_interval");
231 keys.insert("servicegroups");
232 keys.insert("checkers");
233 keys.insert("notification_interval");
234 keys.insert("notification_type_filter");
235 keys.insert("notification_state_filter");
236 keys.insert("check_period");
237 keys.insert("servicedependencies");
238 keys.insert("hostdependencies");
239 keys.insert("export_macros");
241 ExpressionList::Ptr host_exprl = boost::make_shared<ExpressionList>();
242 item->GetLinkedExpressionList()->ExtractFiltered(keys, host_exprl);
243 builder->AddExpressionList(host_exprl);
245 /* Clone attributes from the service expression list. */
246 std::vector<String> path;
247 path.push_back("services");
248 path.push_back(svcname);
250 ExpressionList::Ptr svc_exprl = boost::make_shared<ExpressionList>();
251 item->GetLinkedExpressionList()->ExtractPath(path, svc_exprl);
252 builder->AddExpressionList(svc_exprl);
254 ConfigItem::Ptr serviceItem = builder->Compile();
255 DynamicObject::Ptr dobj = serviceItem->Commit();
257 newServices->Set(name, serviceItem);
262 ObjectLock olock(oldServices);
264 ConfigItem::Ptr service;
265 BOOST_FOREACH(boost::tie(boost::tuples::ignore, service), oldServices) {
269 if (!newServices->Contains(service->GetName()))
270 service->Unregister();
276 Set("slave_services", newServices);
279 void Host::OnAttributeChanged(const String& name)
283 if (name == "hostgroups")
284 HostGroup::InvalidateMembersCache();
285 else if (name == "services") {
286 UpdateSlaveServices();
287 } else if (name == "notifications") {
288 BOOST_FOREACH(const Service::Ptr& service, GetServices()) {
289 service->UpdateSlaveNotifications();
294 std::set<Service::Ptr> Host::GetServices(void) const
296 std::set<Service::Ptr> services;
298 boost::mutex::scoped_lock lock(l_ServiceMutex);
300 Service::WeakPtr wservice;
301 BOOST_FOREACH(boost::tie(boost::tuples::ignore, wservice), l_ServicesCache[GetName()]) {
302 Service::Ptr service = wservice.lock();
307 services.insert(service);
313 int Host::GetTotalServices(void) const
315 return GetServices().size();
317 void Host::InvalidateServicesCache(void)
320 boost::mutex::scoped_lock lock(l_ServiceMutex);
322 if (l_ServicesCacheNeedsUpdate)
323 return; /* Someone else has already requested a refresh. */
325 if (!l_ServicesCacheTimer) {
326 l_ServicesCacheTimer = boost::make_shared<Timer>();
327 l_ServicesCacheTimer->SetInterval(0.5);
328 l_ServicesCacheTimer->OnTimerExpired.connect(boost::bind(&Host::RefreshServicesCache));
329 l_ServicesCacheTimer->Start();
332 l_ServicesCacheNeedsUpdate = true;
336 void Host::RefreshServicesCache(void)
339 boost::mutex::scoped_lock lock(l_ServiceMutex);
341 if (!l_ServicesCacheNeedsUpdate)
344 l_ServicesCacheNeedsUpdate = false;
347 Log(LogDebug, "icinga", "Updating Host services cache.");
349 std::map<String, std::map<String, Service::WeakPtr> > newServicesCache;
351 BOOST_FOREACH(const DynamicObject::Ptr& object, DynamicType::GetObjects("Service")) {
352 const Service::Ptr& service = static_pointer_cast<Service>(object);
354 Host::Ptr host = service->GetHost();
359 // TODO: assert for duplicate short_names
361 newServicesCache[host->GetName()][service->GetShortName()] = service;
364 boost::mutex::scoped_lock lock(l_ServiceMutex);
365 l_ServicesCache.swap(newServicesCache);
368 Value Host::ValidateServiceDictionary(const String& location, const Dictionary::Ptr& attrs)
370 ObjectLock olock(attrs);
374 BOOST_FOREACH(boost::tie(key, value), attrs) {
375 std::vector<String> templates;
377 if (!value.IsObjectType<Dictionary>())
378 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be a dictionary."));
380 Dictionary::Ptr serviceDesc = value;
382 Array::Ptr templatesArray = serviceDesc->Get("templates");
384 if (templatesArray) {
385 ObjectLock tlock(templatesArray);
387 BOOST_FOREACH(const Value& tmpl, templatesArray) {
388 templates.push_back(tmpl);
392 BOOST_FOREACH(const String& name, templates) {
393 ConfigItem::Ptr item;
395 ConfigCompilerContext *context = ConfigCompilerContext::GetContext();
398 item = context->GetItem("Service", name);
400 /* ignore already active objects while we're in the compiler
401 * context and linking to existing items is disabled. */
402 if (!item && (!context || (context->GetFlags() & CompilerLinkExisting)))
403 item = ConfigItem::GetObject("Service", name);
406 ConfigCompilerContext::GetContext()->AddError(false, "Validation failed for " +
407 location + ": Template '" + name + "' not found.");
415 Service::Ptr Host::GetServiceByShortName(const Value& name) const
417 if (name.IsScalar()) {
419 boost::mutex::scoped_lock lock(l_ServiceMutex);
421 std::map<String, Service::WeakPtr>& services = l_ServicesCache[GetName()];
422 std::map<String, Service::WeakPtr>::iterator it = services.find(name);
424 if (it != services.end()) {
425 Service::Ptr service = it->second.lock();
431 return Service::Ptr();
432 } else if (name.IsObjectType<Dictionary>()) {
433 Dictionary::Ptr dict = name;
436 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
438 BOOST_THROW_EXCEPTION(std::invalid_argument("Host/Service name pair is invalid: " + name.Serialize()));
442 std::set<Host::Ptr> Host::GetParentHosts(void) const
444 std::set<Host::Ptr> parents;
446 Array::Ptr dependencies = GetHostDependencies();
449 ObjectLock olock(dependencies);
451 BOOST_FOREACH(const Value& value, dependencies) {
452 if (value == GetName())
455 Host::Ptr host = GetByName(value);
460 parents.insert(host);
467 Service::Ptr Host::GetHostCheckService(void) const
469 String host_check = GetHostCheck();
471 if (host_check.IsEmpty())
472 return Service::Ptr();
474 return GetServiceByShortName(host_check);
477 std::set<Service::Ptr> Host::GetParentServices(void) const
479 std::set<Service::Ptr> parents;
481 Array::Ptr dependencies = GetServiceDependencies();
484 ObjectLock olock(dependencies);
486 BOOST_FOREACH(const Value& value, dependencies) {
487 parents.insert(GetServiceByShortName(value));
494 HostState Host::CalculateState(ServiceState state, bool reachable)
497 return HostUnreachable;
508 HostState Host::GetState(void) const
513 return HostUnreachable;
515 Service::Ptr hc = GetHostCheckService();
520 switch (hc->GetState()) {
530 HostState Host::GetLastState(void) const
535 return HostUnreachable;
537 Service::Ptr hc = GetHostCheckService();
542 switch (hc->GetLastState()) {
551 HostState Host::GetLastHardState(void) const
556 return HostUnreachable;
558 Service::Ptr hc = GetHostCheckService();
563 switch (hc->GetLastHardState()) {
572 double Host::GetLastStateChange(void) const
574 Service::Ptr hc = GetHostCheckService();
577 return IcingaApplication::GetInstance()->GetStartTime();
579 return hc->GetLastStateChange();
583 double Host::GetLastHardStateChange(void) const
585 Service::Ptr hc = GetHostCheckService();
588 return IcingaApplication::GetInstance()->GetStartTime();
590 return hc->GetLastHardStateChange();
593 StateType Host::GetLastStateType(void) const
595 Service::Ptr hc = GetHostCheckService();
598 return StateTypeHard;
600 return hc->GetLastStateType();
603 StateType Host::GetStateType(void) const
605 Service::Ptr hc = GetHostCheckService();
608 return StateTypeHard;
610 return hc->GetStateType();
613 String Host::StateToString(HostState state)
620 case HostUnreachable:
621 return "UNREACHABLE";
627 bool Host::ResolveMacro(const String& macro, const Dictionary::Ptr&, String *result) const
629 if (macro == "HOSTNAME") {
633 else if (macro == "HOSTDISPLAYNAME" || macro == "HOSTALIAS") {
634 *result = GetDisplayName();
638 Service::Ptr hc = GetHostCheckService();
639 Dictionary::Ptr hccr;
642 ServiceState state = hc->GetState();
643 bool reachable = IsReachable();
645 if (macro == "HOSTSTATE") {
646 *result = Convert::ToString(CalculateState(state, reachable));
648 } else if (macro == "HOSTSTATEID") {
649 *result = Convert::ToString(state);
651 } else if (macro == "HOSTSTATETYPE") {
652 *result = Service::StateTypeToString(hc->GetStateType());
654 } else if (macro == "HOSTATTEMPT") {
655 *result = Convert::ToString(hc->GetCurrentCheckAttempt());
657 } else if (macro == "MAXHOSTATTEMPT") {
658 *result = Convert::ToString(hc->GetMaxCheckAttempts());
660 } else if (macro == "LASTHOSTSTATE") {
661 *result = StateToString(GetLastState());
663 } else if (macro == "LASTHOSTSTATEID") {
664 *result = Convert::ToString(GetLastState());
666 } else if (macro == "LASTHOSTSTATETYPE") {
667 *result = Service::StateTypeToString(GetLastStateType());
669 } else if (macro == "LASTHOSTSTATECHANGE") {
670 *result = Convert::ToString((long)hc->GetLastStateChange());
674 hccr = hc->GetLastCheckResult();
678 if (macro == "HOSTLATENCY") {
679 *result = Convert::ToString(Service::CalculateLatency(hccr));
681 } else if (macro == "HOSTEXECUTIONTIME") {
682 *result = Convert::ToString(Service::CalculateExecutionTime(hccr));
684 } else if (macro == "HOSTOUTPUT") {
685 *result = hccr->Get("output");
687 } else if (macro == "HOSTPERFDATA") {
688 *result = hccr->Get("performance_data_raw");
690 } else if (macro == "LASTHOSTCHECK") {
691 *result = Convert::ToString((long)hccr->Get("schedule_start"));
696 Dictionary::Ptr macros = GetMacros();
700 if (name == "HOSTADDRESS")
702 else if (macro == "HOSTADDRESS6")
705 if (macros && macros->Contains(name)) {
706 *result = macros->Get(name);
710 if (macro == "HOSTADDRESS" || macro == "HOSTADDRESS6") {