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 "config/configitembuilder.h"
27 #include "config/configcompilercontext.h"
28 #include <boost/tuple/tuple.hpp>
29 #include <boost/smart_ptr/make_shared.hpp>
30 #include <boost/foreach.hpp>
32 using namespace icinga;
34 boost::mutex Host::m_ServiceMutex;
35 std::map<String, std::map<String, Service::WeakPtr> > Host::m_ServicesCache;
36 bool Host::m_ServicesCacheNeedsUpdate = false;
37 Timer::Ptr Host::m_ServicesCacheTimer;
39 REGISTER_SCRIPTFUNCTION(ValidateServiceDictionary, &Host::ValidateServiceDictionary);
43 Host::Host(const Dictionary::Ptr& serializedUpdate)
44 : DynamicObject(serializedUpdate)
46 RegisterAttribute("display_name", Attribute_Config, &m_DisplayName);
47 RegisterAttribute("hostgroups", Attribute_Config, &m_HostGroups);
48 RegisterAttribute("macros", Attribute_Config, &m_Macros);
49 RegisterAttribute("hostdependencies", Attribute_Config, &m_HostDependencies);
50 RegisterAttribute("servicedependencies", Attribute_Config, &m_ServiceDependencies);
51 RegisterAttribute("hostcheck", Attribute_Config, &m_HostCheck);
57 HostGroup::InvalidateMembersCache();
59 if (m_SlaveServices) {
60 ConfigItem::Ptr service;
61 BOOST_FOREACH(boost::tie(boost::tuples::ignore, service), m_SlaveServices) {
62 service->Unregister();
67 void Host::OnRegistrationCompleted(void)
71 DynamicObject::OnRegistrationCompleted();
73 Host::InvalidateServicesCache();
74 UpdateSlaveServices();
77 String Host::GetDisplayName(void) const
79 if (!m_DisplayName.IsEmpty())
86 * @threadsafety Always.
88 Host::Ptr Host::GetByName(const String& name)
90 DynamicObject::Ptr configObject = DynamicObject::GetObject("Host", name);
92 return dynamic_pointer_cast<Host>(configObject);
95 Array::Ptr Host::GetGroups(void) const
100 Dictionary::Ptr Host::GetMacros(void) const
105 Array::Ptr Host::GetHostDependencies(void) const
107 return m_HostDependencies;;
110 Array::Ptr Host::GetServiceDependencies(void) const
112 return m_ServiceDependencies;
115 String Host::GetHostCheck(void) const
120 bool Host::IsReachable(void) const
124 std::set<Service::Ptr> parentServices = GetParentServices();
126 BOOST_FOREACH(const Service::Ptr& service, parentServices) {
127 ObjectLock olock(service);
129 /* ignore pending services */
130 if (!service->GetLastCheckResult())
133 /* ignore soft states */
134 if (service->GetStateType() == StateTypeSoft)
137 /* ignore services states OK and Warning */
138 if (service->GetState() == StateOK ||
139 service->GetState() == StateWarning)
145 std::set<Host::Ptr> parentHosts = GetParentHosts();
147 BOOST_FOREACH(const Host::Ptr& host, parentHosts) {
148 Service::Ptr hc = host->GetHostCheckService();
150 /* ignore hosts that don't have a hostcheck */
154 ObjectLock olock(hc);
156 /* ignore soft states */
157 if (hc->GetStateType() == StateTypeSoft)
160 /* ignore hosts that are up */
161 if (hc->GetState() == StateOK)
170 template<bool copyServiceAttrs, typename TDict>
171 static void CopyServiceAttributes(TDict serviceDesc, const ConfigItemBuilder::Ptr& builder)
173 /* TODO: we only need to copy macros if this is an inline definition,
174 * i.e. "typeid(serviceDesc)" != Service, however for now we just
175 * copy them anyway. */
176 Value macros = serviceDesc->Get("macros");
177 if (!macros.IsEmpty())
178 builder->AddExpression("macros", OperatorPlus, macros);
180 Value checkInterval = serviceDesc->Get("check_interval");
181 if (!checkInterval.IsEmpty())
182 builder->AddExpression("check_interval", OperatorSet, checkInterval);
184 Value retryInterval = serviceDesc->Get("retry_interval");
185 if (!retryInterval.IsEmpty())
186 builder->AddExpression("retry_interval", OperatorSet, retryInterval);
188 Value sgroups = serviceDesc->Get("servicegroups");
189 if (!sgroups.IsEmpty())
190 builder->AddExpression("servicegroups", OperatorPlus, sgroups);
192 Value checkers = serviceDesc->Get("checkers");
193 if (!checkers.IsEmpty())
194 builder->AddExpression("checkers", OperatorSet, checkers);
196 Value short_name = serviceDesc->Get("short_name");
197 if (!short_name.IsEmpty())
198 builder->AddExpression("short_name", OperatorSet, short_name);
200 Value notification_interval = serviceDesc->Get("notification_interval");
201 if (!notification_interval.IsEmpty())
202 builder->AddExpression("notification_interval", OperatorSet, notification_interval);
204 Value check_period = serviceDesc->Get("check_period");
205 if (!check_period.IsEmpty())
206 builder->AddExpression("check_period", OperatorSet, check_period);
208 if (copyServiceAttrs) {
209 Value servicedependencies = serviceDesc->Get("servicedependencies");
210 if (!servicedependencies.IsEmpty())
211 builder->AddExpression("servicedependencies", OperatorPlus, servicedependencies);
213 Value hostdependencies = serviceDesc->Get("hostdependencies");
214 if (!hostdependencies.IsEmpty())
215 builder->AddExpression("hostdependencies", OperatorPlus, hostdependencies);
219 void Host::UpdateSlaveServices(void)
223 ConfigItem::Ptr item = ConfigItem::GetObject("Host", GetName());
225 /* Don't create slave services unless we own this object */
229 Dictionary::Ptr oldServices = m_SlaveServices;
230 Dictionary::Ptr serviceDescs = Get("services");
232 Dictionary::Ptr newServices = boost::make_shared<Dictionary>();
235 ObjectLock olock(serviceDescs);
238 BOOST_FOREACH(boost::tie(svcname, svcdesc), serviceDescs) {
239 if (svcdesc.IsScalar())
242 std::ostringstream namebuf;
243 namebuf << GetName() << "-" << svcname;
244 String name = namebuf.str();
246 ConfigItemBuilder::Ptr builder = boost::make_shared<ConfigItemBuilder>(item->GetDebugInfo());
247 builder->SetType("Service");
248 builder->SetName(name);
249 builder->AddExpression("host_name", OperatorSet, GetName());
250 builder->AddExpression("display_name", OperatorSet, svcname);
251 builder->AddExpression("short_name", OperatorSet, svcname);
253 CopyServiceAttributes<false>(this, builder);
255 if (!svcdesc.IsObjectType<Dictionary>())
256 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be either a string or a dictionary."));
258 Dictionary::Ptr service = svcdesc;
260 Array::Ptr templates = service->Get("templates");
263 ObjectLock olock(templates);
265 BOOST_FOREACH(const Value& tmpl, templates) {
266 builder->AddParent(tmpl);
270 CopyServiceAttributes<true>(service, builder);
272 ConfigItem::Ptr serviceItem = builder->Compile();
273 DynamicObject::Ptr dobj = serviceItem->Commit();
275 newServices->Set(name, serviceItem);
280 ObjectLock olock(oldServices);
282 ConfigItem::Ptr service;
283 BOOST_FOREACH(boost::tie(boost::tuples::ignore, service), oldServices) {
287 if (!newServices->Contains(service->GetName()))
288 service->Unregister();
294 Set("slave_services", newServices);
297 void Host::OnAttributeChanged(const String& name)
301 if (name == "hostgroups")
302 HostGroup::InvalidateMembersCache();
303 else if (name == "services") {
304 UpdateSlaveServices();
305 } else if (name == "notifications") {
306 BOOST_FOREACH(const Service::Ptr& service, GetServices()) {
307 service->UpdateSlaveNotifications();
312 std::set<Service::Ptr> Host::GetServices(void) const
314 std::set<Service::Ptr> services;
316 boost::mutex::scoped_lock lock(m_ServiceMutex);
318 Service::WeakPtr wservice;
319 BOOST_FOREACH(boost::tie(boost::tuples::ignore, wservice), m_ServicesCache[GetName()]) {
320 Service::Ptr service = wservice.lock();
325 services.insert(service);
331 void Host::InvalidateServicesCache(void)
334 boost::mutex::scoped_lock lock(m_ServiceMutex);
336 if (m_ServicesCacheNeedsUpdate)
337 return; /* Someone else has already requested a refresh. */
339 if (!m_ServicesCacheTimer) {
340 m_ServicesCacheTimer = boost::make_shared<Timer>();
341 m_ServicesCacheTimer->SetInterval(0.5);
342 m_ServicesCacheTimer->OnTimerExpired.connect(boost::bind(&Host::RefreshServicesCache));
343 m_ServicesCacheTimer->Start();
346 m_ServicesCacheNeedsUpdate = true;
350 void Host::RefreshServicesCache(void)
353 boost::mutex::scoped_lock lock(m_ServiceMutex);
355 if (!m_ServicesCacheNeedsUpdate)
358 m_ServicesCacheNeedsUpdate = false;
361 Log(LogDebug, "icinga", "Updating Host services cache.");
363 std::map<String, std::map<String, Service::WeakPtr> > newServicesCache;
365 BOOST_FOREACH(const DynamicObject::Ptr& object, DynamicType::GetObjects("Service")) {
366 const Service::Ptr& service = static_pointer_cast<Service>(object);
368 Host::Ptr host = service->GetHost();
373 // TODO: assert for duplicate short_names
375 newServicesCache[host->GetName()][service->GetShortName()] = service;
378 boost::mutex::scoped_lock lock(m_ServiceMutex);
379 m_ServicesCache.swap(newServicesCache);
382 void Host::ValidateServiceDictionary(const ScriptTask::Ptr& task, const std::vector<Value>& arguments)
384 if (arguments.size() < 1)
385 BOOST_THROW_EXCEPTION(std::invalid_argument("Missing argument: Location must be specified."));
387 if (arguments.size() < 2)
388 BOOST_THROW_EXCEPTION(std::invalid_argument("Missing argument: Attribute dictionary must be specified."));
390 String location = arguments[0];
391 Dictionary::Ptr attrs = arguments[1];
392 ObjectLock olock(attrs);
396 BOOST_FOREACH(boost::tie(key, value), attrs) {
397 std::vector<String> templates;
399 if (!value.IsObjectType<Dictionary>())
400 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be a dictionary."));
402 Dictionary::Ptr serviceDesc = value;
404 Array::Ptr templatesArray = serviceDesc->Get("templates");
406 if (templatesArray) {
407 ObjectLock tlock(templatesArray);
409 BOOST_FOREACH(const Value& tmpl, templatesArray) {
410 templates.push_back(tmpl);
414 BOOST_FOREACH(const String& name, templates) {
415 ConfigItem::Ptr item;
417 ConfigCompilerContext *context = ConfigCompilerContext::GetContext();
420 item = context->GetItem("Service", name);
422 /* ignore already active objects while we're in the compiler
423 * context and linking to existing items is disabled. */
424 if (!item && (!context || (context->GetFlags() & CompilerLinkExisting)))
425 item = ConfigItem::GetObject("Service", name);
428 ConfigCompilerContext::GetContext()->AddError(false, "Validation failed for " +
429 location + ": Template '" + name + "' not found.");
434 task->FinishResult(Empty);
437 Service::Ptr Host::GetServiceByShortName(const Value& name) const
439 if (name.IsScalar()) {
441 boost::mutex::scoped_lock lock(m_ServiceMutex);
443 std::map<String, Service::WeakPtr>& services = m_ServicesCache[GetName()];
444 std::map<String, Service::WeakPtr>::iterator it = services.find(name);
446 if (it != services.end()) {
447 Service::Ptr service = it->second.lock();
453 return Service::Ptr();
454 } else if (name.IsObjectType<Dictionary>()) {
455 Dictionary::Ptr dict = name;
458 ASSERT(dict->IsSealed());
460 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
462 BOOST_THROW_EXCEPTION(std::invalid_argument("Host/Service name pair is invalid."));
466 std::set<Host::Ptr> Host::GetParentHosts(void) const
468 std::set<Host::Ptr> parents;
470 Array::Ptr dependencies = GetHostDependencies();
473 ObjectLock olock(dependencies);
475 BOOST_FOREACH(const Value& value, dependencies) {
476 if (value == GetName())
479 Host::Ptr host = GetByName(value);
484 parents.insert(host);
491 Service::Ptr Host::GetHostCheckService(void) const
493 String host_check = GetHostCheck();
495 if (host_check.IsEmpty())
496 return Service::Ptr();
498 return GetServiceByShortName(host_check);
501 std::set<Service::Ptr> Host::GetParentServices(void) const
503 std::set<Service::Ptr> parents;
505 Array::Ptr dependencies = GetServiceDependencies();
508 ObjectLock olock(dependencies);
510 BOOST_FOREACH(const Value& value, dependencies) {
511 parents.insert(GetServiceByShortName(value));
518 HostState Host::GetState(void) const
521 return HostUnreachable;
523 Service::Ptr hc = GetHostCheckService();
528 switch (hc->GetState()) {
537 StateType Host::GetStateType(void) const
539 Service::Ptr hc = GetHostCheckService();
542 return StateTypeHard;
544 return hc->GetStateType();
547 HostState Host::GetLastState(void) const
552 return HostUnreachable;
554 Service::Ptr hc = GetHostCheckService();
559 switch (hc->GetLastState()) {
568 StateType Host::GetLastStateType(void) const
570 Service::Ptr hc = GetHostCheckService();
573 return StateTypeHard;
575 return hc->GetLastStateType();
578 String Host::HostStateToString(HostState state)
585 case HostUnreachable:
586 return "UNREACHABLE";
592 Dictionary::Ptr Host::CalculateDynamicMacros(void) const
596 Dictionary::Ptr macros = boost::make_shared<Dictionary>();
599 ObjectLock olock(this);
601 macros->Set("HOSTNAME", GetName());
602 macros->Set("HOSTDISPLAYNAME", GetDisplayName());
603 macros->Set("HOSTALIAS", GetName());
608 Service::Ptr hc = GetHostCheckService();
611 ObjectLock olock(hc);
613 macros->Set("HOSTSTATE", HostStateToString(GetState()));
614 macros->Set("HOSTSTATEID", GetState());
615 macros->Set("HOSTSTATETYPE", Service::StateTypeToString(hc->GetStateType()));
616 macros->Set("HOSTATTEMPT", hc->GetCurrentCheckAttempt());
617 macros->Set("MAXHOSTATTEMPT", hc->GetMaxCheckAttempts());
619 macros->Set("LASTHOSTSTATE", HostStateToString(GetLastState()));
620 macros->Set("LASTHOSTSTATEID", GetLastState());
621 macros->Set("LASTHOSTSTATETYPE", Service::StateTypeToString(GetLastStateType()));
622 macros->Set("LASTHOSTSTATECHANGE", (long)hc->GetLastStateChange());
624 cr = hc->GetLastCheckResult();
628 macros->Set("HOSTLATENCY", Service::CalculateLatency(cr));
629 macros->Set("HOSTEXECUTIONTIME", Service::CalculateExecutionTime(cr));
631 macros->Set("HOSTOUTPUT", cr->Get("output"));
632 macros->Set("HOSTPERFDATA", cr->Get("performance_data_raw"));
634 macros->Set("LASTHOSTCHECK", (long)cr->Get("schedule_start"));