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("hostdependencies", Attribute_Config, &m_HostDependencies);
55 RegisterAttribute("servicedependencies", Attribute_Config, &m_ServiceDependencies);
56 RegisterAttribute("hostcheck", Attribute_Config, &m_HostCheck);
62 HostGroup::InvalidateMembersCache();
64 if (m_SlaveServices) {
65 ConfigItem::Ptr service;
66 BOOST_FOREACH(boost::tie(boost::tuples::ignore, service), m_SlaveServices) {
67 service->Unregister();
72 void Host::OnRegistrationCompleted(void)
76 DynamicObject::OnRegistrationCompleted();
78 Host::InvalidateServicesCache();
79 UpdateSlaveServices();
82 String Host::GetDisplayName(void) const
84 if (!m_DisplayName.IsEmpty())
90 Host::Ptr Host::GetByName(const String& name)
92 DynamicObject::Ptr configObject = DynamicObject::GetObject("Host", name);
94 return dynamic_pointer_cast<Host>(configObject);
97 Array::Ptr Host::GetGroups(void) const
102 Dictionary::Ptr Host::GetMacros(void) const
107 Array::Ptr Host::GetHostDependencies(void) const
109 return m_HostDependencies;;
112 Array::Ptr Host::GetServiceDependencies(void) const
114 return m_ServiceDependencies;
117 String Host::GetHostCheck(void) const
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 Dictionary::Ptr oldServices = m_SlaveServices;
183 Dictionary::Ptr serviceDescs = Get("services");
185 Dictionary::Ptr newServices = boost::make_shared<Dictionary>();
188 ObjectLock olock(serviceDescs);
191 BOOST_FOREACH(boost::tie(svcname, svcdesc), serviceDescs) {
192 if (svcdesc.IsScalar())
195 std::ostringstream namebuf;
196 namebuf << GetName() << ":" << svcname;
197 String name = namebuf.str();
199 ConfigItemBuilder::Ptr builder = boost::make_shared<ConfigItemBuilder>(item->GetDebugInfo());
200 builder->SetType("Service");
201 builder->SetName(name);
202 builder->AddExpression("host_name", OperatorSet, GetName());
203 builder->AddExpression("display_name", OperatorSet, svcname);
204 builder->AddExpression("short_name", OperatorSet, svcname);
206 if (!svcdesc.IsObjectType<Dictionary>())
207 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be either a string or a dictionary."));
209 Dictionary::Ptr service = svcdesc;
211 Array::Ptr templates = service->Get("templates");
214 ObjectLock olock(templates);
216 BOOST_FOREACH(const Value& tmpl, templates) {
217 builder->AddParent(tmpl);
221 /* Clone attributes from the host object. */
222 std::set<String, string_iless> keys;
223 keys.insert("check_interval");
224 keys.insert("retry_interval");
225 keys.insert("servicegroups");
226 keys.insert("checkers");
227 keys.insert("notification_interval");
228 keys.insert("notification_type_filter");
229 keys.insert("notification_state_filter");
230 keys.insert("check_period");
231 keys.insert("servicedependencies");
232 keys.insert("hostdependencies");
233 keys.insert("export_macros");
234 keys.insert("macros");
235 keys.insert("custom");
237 ExpressionList::Ptr host_exprl = boost::make_shared<ExpressionList>();
238 item->GetLinkedExpressionList()->ExtractFiltered(keys, host_exprl);
239 builder->AddExpressionList(host_exprl);
241 /* Clone attributes from the service expression list. */
242 std::vector<String> path;
243 path.push_back("services");
244 path.push_back(svcname);
246 ExpressionList::Ptr svc_exprl = boost::make_shared<ExpressionList>();
247 item->GetLinkedExpressionList()->ExtractPath(path, svc_exprl);
248 builder->AddExpressionList(svc_exprl);
250 ConfigItem::Ptr serviceItem = builder->Compile();
251 DynamicObject::Ptr dobj = serviceItem->Commit();
253 newServices->Set(name, serviceItem);
258 ObjectLock olock(oldServices);
260 ConfigItem::Ptr service;
261 BOOST_FOREACH(boost::tie(boost::tuples::ignore, service), oldServices) {
265 if (!newServices->Contains(service->GetName()))
266 service->Unregister();
272 Set("slave_services", newServices);
275 void Host::OnAttributeChanged(const String& name)
279 if (name == "hostgroups")
280 HostGroup::InvalidateMembersCache();
281 else if (name == "services") {
282 UpdateSlaveServices();
283 } else if (name == "notifications") {
284 BOOST_FOREACH(const Service::Ptr& service, GetServices()) {
285 service->UpdateSlaveNotifications();
290 std::set<Service::Ptr> Host::GetServices(void) const
292 std::set<Service::Ptr> services;
294 boost::mutex::scoped_lock lock(l_ServiceMutex);
296 Service::WeakPtr wservice;
297 BOOST_FOREACH(boost::tie(boost::tuples::ignore, wservice), l_ServicesCache[GetName()]) {
298 Service::Ptr service = wservice.lock();
303 services.insert(service);
309 int Host::GetTotalServices(void) const
311 return GetServices().size();
314 void Host::InvalidateServicesCache(void)
317 boost::mutex::scoped_lock lock(l_ServiceMutex);
319 if (l_ServicesCacheNeedsUpdate)
320 return; /* Someone else has already requested a refresh. */
322 if (!l_ServicesCacheTimer) {
323 l_ServicesCacheTimer = boost::make_shared<Timer>();
324 l_ServicesCacheTimer->SetInterval(0.5);
325 l_ServicesCacheTimer->OnTimerExpired.connect(boost::bind(&Host::RefreshServicesCache));
326 l_ServicesCacheTimer->Start();
329 l_ServicesCacheNeedsUpdate = true;
333 void Host::RefreshServicesCache(void)
336 boost::mutex::scoped_lock lock(l_ServiceMutex);
338 if (!l_ServicesCacheNeedsUpdate)
341 l_ServicesCacheNeedsUpdate = false;
344 Log(LogDebug, "icinga", "Updating Host services cache.");
346 std::map<String, std::map<String, Service::WeakPtr> > newServicesCache;
348 BOOST_FOREACH(const DynamicObject::Ptr& object, DynamicType::GetObjects("Service")) {
349 const Service::Ptr& service = static_pointer_cast<Service>(object);
351 Host::Ptr host = service->GetHost();
356 // TODO: assert for duplicate short_names
358 newServicesCache[host->GetName()][service->GetShortName()] = service;
361 boost::mutex::scoped_lock lock(l_ServiceMutex);
362 l_ServicesCache.swap(newServicesCache);
365 Value Host::ValidateServiceDictionary(const String& location, const Dictionary::Ptr& attrs)
367 ObjectLock olock(attrs);
371 BOOST_FOREACH(boost::tie(key, value), attrs) {
372 std::vector<String> templates;
374 if (!value.IsObjectType<Dictionary>())
375 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be a dictionary."));
377 Dictionary::Ptr serviceDesc = value;
379 Array::Ptr templatesArray = serviceDesc->Get("templates");
381 if (templatesArray) {
382 ObjectLock tlock(templatesArray);
384 BOOST_FOREACH(const Value& tmpl, templatesArray) {
385 templates.push_back(tmpl);
389 BOOST_FOREACH(const String& name, templates) {
390 ConfigItem::Ptr item;
392 ConfigCompilerContext *context = ConfigCompilerContext::GetContext();
395 item = context->GetItem("Service", name);
397 /* ignore already active objects while we're in the compiler
398 * context and linking to existing items is disabled. */
399 if (!item && (!context || (context->GetFlags() & CompilerLinkExisting)))
400 item = ConfigItem::GetObject("Service", name);
403 ConfigCompilerContext::GetContext()->AddError(false, "Validation failed for " +
404 location + ": Template '" + name + "' not found.");
412 Service::Ptr Host::GetServiceByShortName(const Value& name) const
414 if (name.IsScalar()) {
416 boost::mutex::scoped_lock lock(l_ServiceMutex);
418 std::map<String, Service::WeakPtr>& services = l_ServicesCache[GetName()];
419 std::map<String, Service::WeakPtr>::iterator it = services.find(name);
421 if (it != services.end()) {
422 Service::Ptr service = it->second.lock();
428 return Service::Ptr();
429 } else if (name.IsObjectType<Dictionary>()) {
430 Dictionary::Ptr dict = name;
433 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
435 BOOST_THROW_EXCEPTION(std::invalid_argument("Host/Service name pair is invalid: " + name.Serialize()));
439 std::set<Host::Ptr> Host::GetParentHosts(void) const
441 std::set<Host::Ptr> parents;
443 Array::Ptr dependencies = GetHostDependencies();
446 ObjectLock olock(dependencies);
448 BOOST_FOREACH(const Value& value, dependencies) {
449 if (value == GetName())
452 Host::Ptr host = GetByName(value);
457 parents.insert(host);
464 Service::Ptr Host::GetHostCheckService(void) const
466 String host_check = GetHostCheck();
468 if (host_check.IsEmpty())
469 return Service::Ptr();
471 return GetServiceByShortName(host_check);
474 std::set<Service::Ptr> Host::GetParentServices(void) const
476 std::set<Service::Ptr> parents;
478 Array::Ptr dependencies = GetServiceDependencies();
481 ObjectLock olock(dependencies);
483 BOOST_FOREACH(const Value& value, dependencies) {
484 parents.insert(GetServiceByShortName(value));
491 HostState Host::CalculateState(ServiceState state, bool reachable)
494 return HostUnreachable;
505 HostState Host::GetState(void) const
510 return HostUnreachable;
512 Service::Ptr hc = GetHostCheckService();
517 switch (hc->GetState()) {
527 HostState Host::GetLastState(void) const
532 return HostUnreachable;
534 Service::Ptr hc = GetHostCheckService();
539 switch (hc->GetLastState()) {
548 HostState Host::GetLastHardState(void) const
553 return HostUnreachable;
555 Service::Ptr hc = GetHostCheckService();
560 switch (hc->GetLastHardState()) {
569 double Host::GetLastStateChange(void) const
571 Service::Ptr hc = GetHostCheckService();
574 return IcingaApplication::GetInstance()->GetStartTime();
576 return hc->GetLastStateChange();
580 double Host::GetLastHardStateChange(void) const
582 Service::Ptr hc = GetHostCheckService();
585 return IcingaApplication::GetInstance()->GetStartTime();
587 return hc->GetLastHardStateChange();
590 StateType Host::GetLastStateType(void) const
592 Service::Ptr hc = GetHostCheckService();
595 return StateTypeHard;
597 return hc->GetLastStateType();
600 StateType Host::GetStateType(void) const
602 Service::Ptr hc = GetHostCheckService();
605 return StateTypeHard;
607 return hc->GetStateType();
610 String Host::StateToString(HostState state)
617 case HostUnreachable:
618 return "UNREACHABLE";
624 bool Host::ResolveMacro(const String& macro, const Dictionary::Ptr&, String *result) const
626 if (macro == "HOSTNAME") {
630 else if (macro == "HOSTDISPLAYNAME" || macro == "HOSTALIAS") {
631 *result = GetDisplayName();
635 Service::Ptr hc = GetHostCheckService();
636 Dictionary::Ptr hccr;
639 ServiceState state = hc->GetState();
640 bool reachable = IsReachable();
642 if (macro == "HOSTSTATE") {
643 *result = Convert::ToString(CalculateState(state, reachable));
645 } else if (macro == "HOSTSTATEID") {
646 *result = Convert::ToString(state);
648 } else if (macro == "HOSTSTATETYPE") {
649 *result = Service::StateTypeToString(hc->GetStateType());
651 } else if (macro == "HOSTATTEMPT") {
652 *result = Convert::ToString(hc->GetCurrentCheckAttempt());
654 } else if (macro == "MAXHOSTATTEMPT") {
655 *result = Convert::ToString(hc->GetMaxCheckAttempts());
657 } else if (macro == "LASTHOSTSTATE") {
658 *result = StateToString(GetLastState());
660 } else if (macro == "LASTHOSTSTATEID") {
661 *result = Convert::ToString(GetLastState());
663 } else if (macro == "LASTHOSTSTATETYPE") {
664 *result = Service::StateTypeToString(GetLastStateType());
666 } else if (macro == "LASTHOSTSTATECHANGE") {
667 *result = Convert::ToString((long)hc->GetLastStateChange());
671 hccr = hc->GetLastCheckResult();
675 if (macro == "HOSTLATENCY") {
676 *result = Convert::ToString(Service::CalculateLatency(hccr));
678 } else if (macro == "HOSTEXECUTIONTIME") {
679 *result = Convert::ToString(Service::CalculateExecutionTime(hccr));
681 } else if (macro == "HOSTOUTPUT") {
682 *result = hccr->Get("output");
684 } else if (macro == "HOSTPERFDATA") {
685 *result = hccr->Get("performance_data_raw");
687 } else if (macro == "LASTHOSTCHECK") {
688 *result = Convert::ToString((long)hccr->Get("schedule_start"));
693 Dictionary::Ptr macros = GetMacros();
697 if (name == "HOSTADDRESS")
699 else if (macro == "HOSTADDRESS6")
702 if (macros && macros->Contains(name)) {
703 *result = macros->Get(name);
707 if (macro == "HOSTADDRESS" || macro == "HOSTADDRESS6") {