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 "base/dynamictype.h"
24 #include "base/objectlock.h"
25 #include "base/logger_fwd.h"
26 #include "base/timer.h"
27 #include "base/convert.h"
28 #include "base/scriptfunction.h"
29 #include "base/utility.h"
30 #include "config/configitembuilder.h"
31 #include "config/configcompilercontext.h"
32 #include <boost/tuple/tuple.hpp>
33 #include <boost/smart_ptr/make_shared.hpp>
34 #include <boost/foreach.hpp>
36 using namespace icinga;
38 static boost::mutex l_ServiceMutex;
39 static std::map<String, std::map<String, Service::WeakPtr> > l_ServicesCache;
40 static bool l_ServicesCacheNeedsUpdate = false;
41 static Timer::Ptr l_ServicesCacheTimer;
43 REGISTER_SCRIPTFUNCTION(ValidateServiceDictionary, &Host::ValidateServiceDictionary);
47 Host::Host(const Dictionary::Ptr& serializedUpdate)
48 : DynamicObject(serializedUpdate)
50 RegisterAttribute("display_name", Attribute_Config, &m_DisplayName);
51 RegisterAttribute("hostgroups", Attribute_Config, &m_HostGroups);
52 RegisterAttribute("macros", Attribute_Config, &m_Macros);
53 RegisterAttribute("hostdependencies", Attribute_Config, &m_HostDependencies);
54 RegisterAttribute("servicedependencies", Attribute_Config, &m_ServiceDependencies);
55 RegisterAttribute("hostcheck", Attribute_Config, &m_HostCheck);
61 HostGroup::InvalidateMembersCache();
63 if (m_SlaveServices) {
64 ConfigItem::Ptr service;
65 BOOST_FOREACH(boost::tie(boost::tuples::ignore, service), m_SlaveServices) {
66 service->Unregister();
71 void Host::OnRegistrationCompleted(void)
75 DynamicObject::OnRegistrationCompleted();
77 Host::InvalidateServicesCache();
78 UpdateSlaveServices();
81 String Host::GetDisplayName(void) const
83 if (!m_DisplayName.IsEmpty())
89 Host::Ptr Host::GetByName(const String& name)
91 DynamicObject::Ptr configObject = DynamicObject::GetObject("Host", name);
93 return dynamic_pointer_cast<Host>(configObject);
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 bool Host::IsReachable(void) const
125 std::set<Service::Ptr> parentServices = GetParentServices();
127 BOOST_FOREACH(const Service::Ptr& service, parentServices) {
128 ObjectLock olock(service);
130 /* ignore pending services */
131 if (!service->GetLastCheckResult())
134 /* ignore soft states */
135 if (service->GetStateType() == StateTypeSoft)
138 /* ignore services states OK and Warning */
139 if (service->GetState() == StateOK ||
140 service->GetState() == StateWarning)
146 std::set<Host::Ptr> parentHosts = GetParentHosts();
148 BOOST_FOREACH(const Host::Ptr& host, parentHosts) {
149 Service::Ptr hc = host->GetHostCheckService();
151 /* ignore hosts that don't have a hostcheck */
155 ObjectLock olock(hc);
157 /* ignore soft states */
158 if (hc->GetStateType() == StateTypeSoft)
161 /* ignore hosts that are up */
162 if (hc->GetState() == StateOK)
171 void Host::UpdateSlaveServices(void)
175 ConfigItem::Ptr item = ConfigItem::GetObject("Host", GetName());
177 /* Don't create slave services unless we own this object */
181 Dictionary::Ptr oldServices = m_SlaveServices;
182 Dictionary::Ptr serviceDescs = Get("services");
184 Dictionary::Ptr newServices = boost::make_shared<Dictionary>();
187 ObjectLock olock(serviceDescs);
190 BOOST_FOREACH(boost::tie(svcname, svcdesc), serviceDescs) {
191 if (svcdesc.IsScalar())
194 std::ostringstream namebuf;
195 namebuf << GetName() << ":" << svcname;
196 String name = namebuf.str();
198 ConfigItemBuilder::Ptr builder = boost::make_shared<ConfigItemBuilder>(item->GetDebugInfo());
199 builder->SetType("Service");
200 builder->SetName(name);
201 builder->AddExpression("host_name", OperatorSet, GetName());
202 builder->AddExpression("display_name", OperatorSet, svcname);
203 builder->AddExpression("short_name", OperatorSet, svcname);
205 if (!svcdesc.IsObjectType<Dictionary>())
206 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be either a string or a dictionary."));
208 Dictionary::Ptr service = svcdesc;
210 Array::Ptr templates = service->Get("templates");
213 ObjectLock olock(templates);
215 BOOST_FOREACH(const Value& tmpl, templates) {
216 builder->AddParent(tmpl);
220 /* Clone attributes from the host object. */
221 std::set<String, string_iless> keys;
222 keys.insert("check_interval");
223 keys.insert("retry_interval");
224 keys.insert("servicegroups");
225 keys.insert("checkers");
226 keys.insert("notification_interval");
227 keys.insert("check_period");
228 keys.insert("servicedependencies");
229 keys.insert("hostdependencies");
230 keys.insert("export_macros");
232 ExpressionList::Ptr host_exprl = boost::make_shared<ExpressionList>();
233 item->GetLinkedExpressionList()->ExtractFiltered(keys, host_exprl);
234 builder->AddExpressionList(host_exprl);
236 /* Clone attributes from the service expression list. */
237 std::vector<String> path;
238 path.push_back("services");
239 path.push_back(svcname);
241 ExpressionList::Ptr svc_exprl = boost::make_shared<ExpressionList>();
242 item->GetLinkedExpressionList()->ExtractPath(path, svc_exprl);
243 builder->AddExpressionList(svc_exprl);
245 ConfigItem::Ptr serviceItem = builder->Compile();
246 DynamicObject::Ptr dobj = serviceItem->Commit();
248 newServices->Set(name, serviceItem);
253 ObjectLock olock(oldServices);
255 ConfigItem::Ptr service;
256 BOOST_FOREACH(boost::tie(boost::tuples::ignore, service), oldServices) {
260 if (!newServices->Contains(service->GetName()))
261 service->Unregister();
267 Set("slave_services", newServices);
270 void Host::OnAttributeChanged(const String& name)
274 if (name == "hostgroups")
275 HostGroup::InvalidateMembersCache();
276 else if (name == "services") {
277 UpdateSlaveServices();
278 } else if (name == "notifications") {
279 BOOST_FOREACH(const Service::Ptr& service, GetServices()) {
280 service->UpdateSlaveNotifications();
285 std::set<Service::Ptr> Host::GetServices(void) const
287 std::set<Service::Ptr> services;
289 boost::mutex::scoped_lock lock(l_ServiceMutex);
291 Service::WeakPtr wservice;
292 BOOST_FOREACH(boost::tie(boost::tuples::ignore, wservice), l_ServicesCache[GetName()]) {
293 Service::Ptr service = wservice.lock();
298 services.insert(service);
304 void Host::InvalidateServicesCache(void)
307 boost::mutex::scoped_lock lock(l_ServiceMutex);
309 if (l_ServicesCacheNeedsUpdate)
310 return; /* Someone else has already requested a refresh. */
312 if (!l_ServicesCacheTimer) {
313 l_ServicesCacheTimer = boost::make_shared<Timer>();
314 l_ServicesCacheTimer->SetInterval(0.5);
315 l_ServicesCacheTimer->OnTimerExpired.connect(boost::bind(&Host::RefreshServicesCache));
316 l_ServicesCacheTimer->Start();
319 l_ServicesCacheNeedsUpdate = true;
323 void Host::RefreshServicesCache(void)
326 boost::mutex::scoped_lock lock(l_ServiceMutex);
328 if (!l_ServicesCacheNeedsUpdate)
331 l_ServicesCacheNeedsUpdate = false;
334 Log(LogDebug, "icinga", "Updating Host services cache.");
336 std::map<String, std::map<String, Service::WeakPtr> > newServicesCache;
338 BOOST_FOREACH(const DynamicObject::Ptr& object, DynamicType::GetObjects("Service")) {
339 const Service::Ptr& service = static_pointer_cast<Service>(object);
341 Host::Ptr host = service->GetHost();
346 // TODO: assert for duplicate short_names
348 newServicesCache[host->GetName()][service->GetShortName()] = service;
351 boost::mutex::scoped_lock lock(l_ServiceMutex);
352 l_ServicesCache.swap(newServicesCache);
355 Value Host::ValidateServiceDictionary(const String& location, const Dictionary::Ptr& attrs)
357 ObjectLock olock(attrs);
361 BOOST_FOREACH(boost::tie(key, value), attrs) {
362 std::vector<String> templates;
364 if (!value.IsObjectType<Dictionary>())
365 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be a dictionary."));
367 Dictionary::Ptr serviceDesc = value;
369 Array::Ptr templatesArray = serviceDesc->Get("templates");
371 if (templatesArray) {
372 ObjectLock tlock(templatesArray);
374 BOOST_FOREACH(const Value& tmpl, templatesArray) {
375 templates.push_back(tmpl);
379 BOOST_FOREACH(const String& name, templates) {
380 ConfigItem::Ptr item;
382 ConfigCompilerContext *context = ConfigCompilerContext::GetContext();
385 item = context->GetItem("Service", name);
387 /* ignore already active objects while we're in the compiler
388 * context and linking to existing items is disabled. */
389 if (!item && (!context || (context->GetFlags() & CompilerLinkExisting)))
390 item = ConfigItem::GetObject("Service", name);
393 ConfigCompilerContext::GetContext()->AddError(false, "Validation failed for " +
394 location + ": Template '" + name + "' not found.");
402 Service::Ptr Host::GetServiceByShortName(const Value& name) const
404 if (name.IsScalar()) {
406 boost::mutex::scoped_lock lock(l_ServiceMutex);
408 std::map<String, Service::WeakPtr>& services = l_ServicesCache[GetName()];
409 std::map<String, Service::WeakPtr>::iterator it = services.find(name);
411 if (it != services.end()) {
412 Service::Ptr service = it->second.lock();
418 return Service::Ptr();
419 } else if (name.IsObjectType<Dictionary>()) {
420 Dictionary::Ptr dict = name;
423 ASSERT(dict->IsSealed());
425 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
427 BOOST_THROW_EXCEPTION(std::invalid_argument("Host/Service name pair is invalid: " + name.Serialize()));
431 std::set<Host::Ptr> Host::GetParentHosts(void) const
433 std::set<Host::Ptr> parents;
435 Array::Ptr dependencies = GetHostDependencies();
438 ObjectLock olock(dependencies);
440 BOOST_FOREACH(const Value& value, dependencies) {
441 if (value == GetName())
444 Host::Ptr host = GetByName(value);
449 parents.insert(host);
456 Service::Ptr Host::GetHostCheckService(void) const
458 String host_check = GetHostCheck();
460 if (host_check.IsEmpty())
461 return Service::Ptr();
463 return GetServiceByShortName(host_check);
466 std::set<Service::Ptr> Host::GetParentServices(void) const
468 std::set<Service::Ptr> parents;
470 Array::Ptr dependencies = GetServiceDependencies();
473 ObjectLock olock(dependencies);
475 BOOST_FOREACH(const Value& value, dependencies) {
476 parents.insert(GetServiceByShortName(value));
483 HostState Host::CalculateState(ServiceState state, bool reachable)
486 return HostUnreachable;
497 HostState Host::GetLastState(void) const
502 return HostUnreachable;
504 Service::Ptr hc = GetHostCheckService();
509 switch (hc->GetLastState()) {
518 StateType Host::GetLastStateType(void) const
520 Service::Ptr hc = GetHostCheckService();
523 return StateTypeHard;
525 return hc->GetLastStateType();
528 String Host::StateToString(HostState state)
535 case HostUnreachable:
536 return "UNREACHABLE";
542 bool Host::ResolveMacro(const String& macro, const Dictionary::Ptr&, String *result) const
544 if (macro == "HOSTNAME" || macro == "HOSTALIAS") {
548 else if (macro == "HOSTDISPLAYNAME") {
549 *result = GetDisplayName();
553 Service::Ptr hc = GetHostCheckService();
554 Dictionary::Ptr hccr;
557 ServiceState state = hc->GetState();
558 bool reachable = IsReachable();
560 if (macro == "HOSTSTATE") {
561 *result = Convert::ToString(CalculateState(state, reachable));
563 } else if (macro == "HOSTSTATEID") {
564 *result = Convert::ToString(state);
566 } else if (macro == "HOSTSTATETYPE") {
567 *result = Service::StateTypeToString(hc->GetStateType());
569 } else if (macro == "HOSTATTEMPT") {
570 *result = Convert::ToString(hc->GetCurrentCheckAttempt());
572 } else if (macro == "MAXHOSTATTEMPT") {
573 *result = Convert::ToString(hc->GetMaxCheckAttempts());
575 } else if (macro == "LASTHOSTSTATE") {
576 *result = StateToString(GetLastState());
578 } else if (macro == "LASTHOSTSTATEID") {
579 *result = Convert::ToString(GetLastState());
581 } else if (macro == "LASTHOSTSTATETYPE") {
582 *result = Service::StateTypeToString(GetLastStateType());
584 } else if (macro == "LASTHOSTSTATECHANGE") {
585 *result = Convert::ToString((long)hc->GetLastStateChange());
589 hccr = hc->GetLastCheckResult();
593 if (macro == "HOSTLATENCY") {
594 *result = Convert::ToString(Service::CalculateLatency(hccr));
596 } else if (macro == "HOSTEXECUTIONTIME") {
597 *result = Convert::ToString(Service::CalculateExecutionTime(hccr));
599 } else if (macro == "HOSTOUTPUT") {
600 *result = hccr->Get("output");
602 } else if (macro == "HOSTPERFDATA") {
603 *result = hccr->Get("performance_data_raw");
605 } else if (macro == "LASTHOSTCHECK") {
606 *result = Convert::ToString((long)hccr->Get("schedule_start"));
611 Dictionary::Ptr macros = GetMacros();
613 if (macros && macros->Contains(macro)) {
614 *result = macros->Get(macro);