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 "i2-icinga.h"
21 #include "base/dynamictype.h"
22 #include "base/objectlock.h"
23 #include "base/logger_fwd.h"
24 #include <boost/tuple/tuple.hpp>
25 #include <boost/smart_ptr/make_shared.hpp>
26 #include <boost/foreach.hpp>
28 using namespace icinga;
30 boost::mutex Host::m_ServiceMutex;
31 std::map<String, std::map<String, Service::WeakPtr> > Host::m_ServicesCache;
32 bool Host::m_ServicesCacheNeedsUpdate = false;
33 Timer::Ptr Host::m_ServicesCacheTimer;
35 REGISTER_SCRIPTFUNCTION(ValidateServiceDictionary, &Host::ValidateServiceDictionary);
39 Host::Host(const Dictionary::Ptr& serializedUpdate)
40 : DynamicObject(serializedUpdate)
42 RegisterAttribute("display_name", Attribute_Config, &m_DisplayName);
43 RegisterAttribute("hostgroups", Attribute_Config, &m_HostGroups);
44 RegisterAttribute("macros", Attribute_Config, &m_Macros);
45 RegisterAttribute("hostdependencies", Attribute_Config, &m_HostDependencies);
46 RegisterAttribute("servicedependencies", Attribute_Config, &m_ServiceDependencies);
47 RegisterAttribute("hostcheck", Attribute_Config, &m_HostCheck);
53 HostGroup::InvalidateMembersCache();
55 if (m_SlaveServices) {
56 ConfigItem::Ptr service;
57 BOOST_FOREACH(boost::tie(boost::tuples::ignore, service), m_SlaveServices) {
58 service->Unregister();
63 void Host::OnRegistrationCompleted(void)
67 DynamicObject::OnRegistrationCompleted();
69 Host::InvalidateServicesCache();
70 UpdateSlaveServices();
73 String Host::GetDisplayName(void) const
75 if (!m_DisplayName.IsEmpty())
82 * @threadsafety Always.
84 Host::Ptr Host::GetByName(const String& name)
86 DynamicObject::Ptr configObject = DynamicObject::GetObject("Host", name);
88 return dynamic_pointer_cast<Host>(configObject);
91 Array::Ptr Host::GetGroups(void) const
96 Dictionary::Ptr Host::GetMacros(void) const
101 Array::Ptr Host::GetHostDependencies(void) const
103 return m_HostDependencies;;
106 Array::Ptr Host::GetServiceDependencies(void) const
108 return m_ServiceDependencies;
111 String Host::GetHostCheck(void) const
116 bool Host::IsReachable(void) const
120 std::set<Service::Ptr> parentServices = GetParentServices();
122 BOOST_FOREACH(const Service::Ptr& service, parentServices) {
123 ObjectLock olock(service);
125 /* ignore pending services */
126 if (!service->GetLastCheckResult())
129 /* ignore soft states */
130 if (service->GetStateType() == StateTypeSoft)
133 /* ignore services states OK and Warning */
134 if (service->GetState() == StateOK ||
135 service->GetState() == StateWarning)
141 std::set<Host::Ptr> parentHosts = GetParentHosts();
143 BOOST_FOREACH(const Host::Ptr& host, parentHosts) {
144 Service::Ptr hc = host->GetHostCheckService();
146 /* ignore hosts that don't have a hostcheck */
150 ObjectLock olock(hc);
152 /* ignore soft states */
153 if (hc->GetStateType() == StateTypeSoft)
156 /* ignore hosts that are up */
157 if (hc->GetState() == StateOK)
166 template<bool copyServiceAttrs, typename TDict>
167 static void CopyServiceAttributes(TDict serviceDesc, const ConfigItemBuilder::Ptr& builder)
169 /* TODO: we only need to copy macros if this is an inline definition,
170 * i.e. "typeid(serviceDesc)" != Service, however for now we just
171 * copy them anyway. */
172 Value macros = serviceDesc->Get("macros");
173 if (!macros.IsEmpty())
174 builder->AddExpression("macros", OperatorPlus, macros);
176 Value checkInterval = serviceDesc->Get("check_interval");
177 if (!checkInterval.IsEmpty())
178 builder->AddExpression("check_interval", OperatorSet, checkInterval);
180 Value retryInterval = serviceDesc->Get("retry_interval");
181 if (!retryInterval.IsEmpty())
182 builder->AddExpression("retry_interval", OperatorSet, retryInterval);
184 Value sgroups = serviceDesc->Get("servicegroups");
185 if (!sgroups.IsEmpty())
186 builder->AddExpression("servicegroups", OperatorPlus, sgroups);
188 Value checkers = serviceDesc->Get("checkers");
189 if (!checkers.IsEmpty())
190 builder->AddExpression("checkers", OperatorSet, checkers);
192 Value short_name = serviceDesc->Get("short_name");
193 if (!short_name.IsEmpty())
194 builder->AddExpression("short_name", OperatorSet, short_name);
196 Value notification_interval = serviceDesc->Get("notification_interval");
197 if (!notification_interval.IsEmpty())
198 builder->AddExpression("notification_interval", OperatorSet, notification_interval);
200 Value check_period = serviceDesc->Get("check_period");
201 if (!check_period.IsEmpty())
202 builder->AddExpression("check_period", OperatorSet, check_period);
204 if (copyServiceAttrs) {
205 Value servicedependencies = serviceDesc->Get("servicedependencies");
206 if (!servicedependencies.IsEmpty())
207 builder->AddExpression("servicedependencies", OperatorPlus, servicedependencies);
209 Value hostdependencies = serviceDesc->Get("hostdependencies");
210 if (!hostdependencies.IsEmpty())
211 builder->AddExpression("hostdependencies", OperatorPlus, hostdependencies);
215 void Host::UpdateSlaveServices(void)
219 ConfigItem::Ptr item = ConfigItem::GetObject("Host", GetName());
221 /* Don't create slave services unless we own this object */
225 Dictionary::Ptr oldServices = m_SlaveServices;
226 Dictionary::Ptr serviceDescs = Get("services");
228 Dictionary::Ptr newServices = boost::make_shared<Dictionary>();
231 ObjectLock olock(serviceDescs);
234 BOOST_FOREACH(boost::tie(svcname, svcdesc), serviceDescs) {
235 if (svcdesc.IsScalar())
238 std::ostringstream namebuf;
239 namebuf << GetName() << "-" << svcname;
240 String name = namebuf.str();
242 ConfigItemBuilder::Ptr builder = boost::make_shared<ConfigItemBuilder>(item->GetDebugInfo());
243 builder->SetType("Service");
244 builder->SetName(name);
245 builder->AddExpression("host_name", OperatorSet, GetName());
246 builder->AddExpression("display_name", OperatorSet, svcname);
247 builder->AddExpression("short_name", OperatorSet, svcname);
249 CopyServiceAttributes<false>(this, builder);
251 if (!svcdesc.IsObjectType<Dictionary>())
252 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be either a string or a dictionary."));
254 Dictionary::Ptr service = svcdesc;
256 Array::Ptr templates = service->Get("templates");
259 ObjectLock olock(templates);
261 BOOST_FOREACH(const Value& tmpl, templates) {
262 builder->AddParent(tmpl);
266 CopyServiceAttributes<true>(service, builder);
268 ConfigItem::Ptr serviceItem = builder->Compile();
269 DynamicObject::Ptr dobj = serviceItem->Commit();
271 newServices->Set(name, serviceItem);
276 ObjectLock olock(oldServices);
278 ConfigItem::Ptr service;
279 BOOST_FOREACH(boost::tie(boost::tuples::ignore, service), oldServices) {
283 if (!newServices->Contains(service->GetName()))
284 service->Unregister();
290 Set("slave_services", newServices);
293 void Host::OnAttributeChanged(const String& name)
297 if (name == "hostgroups")
298 HostGroup::InvalidateMembersCache();
299 else if (name == "services") {
300 UpdateSlaveServices();
301 } else if (name == "notifications") {
302 BOOST_FOREACH(const Service::Ptr& service, GetServices()) {
303 service->UpdateSlaveNotifications();
308 std::set<Service::Ptr> Host::GetServices(void) const
310 std::set<Service::Ptr> services;
312 boost::mutex::scoped_lock lock(m_ServiceMutex);
314 Service::WeakPtr wservice;
315 BOOST_FOREACH(boost::tie(boost::tuples::ignore, wservice), m_ServicesCache[GetName()]) {
316 Service::Ptr service = wservice.lock();
321 services.insert(service);
327 void Host::InvalidateServicesCache(void)
330 boost::mutex::scoped_lock lock(m_ServiceMutex);
332 if (m_ServicesCacheNeedsUpdate)
333 return; /* Someone else has already requested a refresh. */
335 if (!m_ServicesCacheTimer) {
336 m_ServicesCacheTimer = boost::make_shared<Timer>();
337 m_ServicesCacheTimer->SetInterval(0.5);
338 m_ServicesCacheTimer->OnTimerExpired.connect(boost::bind(&Host::RefreshServicesCache));
339 m_ServicesCacheTimer->Start();
342 m_ServicesCacheNeedsUpdate = true;
346 void Host::RefreshServicesCache(void)
349 boost::mutex::scoped_lock lock(m_ServiceMutex);
351 if (!m_ServicesCacheNeedsUpdate)
354 m_ServicesCacheNeedsUpdate = false;
357 Log(LogDebug, "icinga", "Updating Host services cache.");
359 std::map<String, std::map<String, Service::WeakPtr> > newServicesCache;
361 BOOST_FOREACH(const DynamicObject::Ptr& object, DynamicType::GetObjects("Service")) {
362 const Service::Ptr& service = static_pointer_cast<Service>(object);
364 Host::Ptr host = service->GetHost();
369 // TODO: assert for duplicate short_names
371 newServicesCache[host->GetName()][service->GetShortName()] = service;
374 boost::mutex::scoped_lock lock(m_ServiceMutex);
375 m_ServicesCache.swap(newServicesCache);
378 void Host::ValidateServiceDictionary(const ScriptTask::Ptr& task, const std::vector<Value>& arguments)
380 if (arguments.size() < 1)
381 BOOST_THROW_EXCEPTION(std::invalid_argument("Missing argument: Location must be specified."));
383 if (arguments.size() < 2)
384 BOOST_THROW_EXCEPTION(std::invalid_argument("Missing argument: Attribute dictionary must be specified."));
386 String location = arguments[0];
387 Dictionary::Ptr attrs = arguments[1];
388 ObjectLock olock(attrs);
392 BOOST_FOREACH(boost::tie(key, value), attrs) {
393 std::vector<String> templates;
395 if (!value.IsObjectType<Dictionary>())
396 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be a dictionary."));
398 Dictionary::Ptr serviceDesc = value;
400 Array::Ptr templatesArray = serviceDesc->Get("templates");
402 if (templatesArray) {
403 ObjectLock tlock(templatesArray);
405 BOOST_FOREACH(const Value& tmpl, templatesArray) {
406 templates.push_back(tmpl);
410 BOOST_FOREACH(const String& name, templates) {
411 ConfigItem::Ptr item;
413 ConfigCompilerContext *context = ConfigCompilerContext::GetContext();
416 item = context->GetItem("Service", name);
418 /* ignore already active objects while we're in the compiler
419 * context and linking to existing items is disabled. */
420 if (!item && (!context || (context->GetFlags() & CompilerLinkExisting)))
421 item = ConfigItem::GetObject("Service", name);
424 ConfigCompilerContext::GetContext()->AddError(false, "Validation failed for " +
425 location + ": Template '" + name + "' not found.");
430 task->FinishResult(Empty);
433 Service::Ptr Host::GetServiceByShortName(const Value& name) const
435 if (name.IsScalar()) {
437 boost::mutex::scoped_lock lock(m_ServiceMutex);
439 std::map<String, Service::WeakPtr>& services = m_ServicesCache[GetName()];
440 std::map<String, Service::WeakPtr>::iterator it = services.find(name);
442 if (it != services.end()) {
443 Service::Ptr service = it->second.lock();
449 return Service::Ptr();
450 } else if (name.IsObjectType<Dictionary>()) {
451 Dictionary::Ptr dict = name;
454 ASSERT(dict->IsSealed());
456 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
458 BOOST_THROW_EXCEPTION(std::invalid_argument("Host/Service name pair is invalid."));
462 std::set<Host::Ptr> Host::GetParentHosts(void) const
464 std::set<Host::Ptr> parents;
466 Array::Ptr dependencies = GetHostDependencies();
469 ObjectLock olock(dependencies);
471 BOOST_FOREACH(const Value& value, dependencies) {
472 if (value == GetName())
475 Host::Ptr host = GetByName(value);
480 parents.insert(host);
487 Service::Ptr Host::GetHostCheckService(void) const
489 String host_check = GetHostCheck();
491 if (host_check.IsEmpty())
492 return Service::Ptr();
494 return GetServiceByShortName(host_check);
497 std::set<Service::Ptr> Host::GetParentServices(void) const
499 std::set<Service::Ptr> parents;
501 Array::Ptr dependencies = GetServiceDependencies();
504 ObjectLock olock(dependencies);
506 BOOST_FOREACH(const Value& value, dependencies) {
507 parents.insert(GetServiceByShortName(value));
514 HostState Host::GetState(void) const
517 return HostUnreachable;
519 Service::Ptr hc = GetHostCheckService();
524 switch (hc->GetState()) {
533 StateType Host::GetStateType(void) const
535 Service::Ptr hc = GetHostCheckService();
538 return StateTypeHard;
540 return hc->GetStateType();
543 HostState Host::GetLastState(void) const
548 return HostUnreachable;
550 Service::Ptr hc = GetHostCheckService();
555 switch (hc->GetLastState()) {
564 StateType Host::GetLastStateType(void) const
566 Service::Ptr hc = GetHostCheckService();
569 return StateTypeHard;
571 return hc->GetLastStateType();
574 String Host::HostStateToString(HostState state)
581 case HostUnreachable:
582 return "UNREACHABLE";
588 Dictionary::Ptr Host::CalculateDynamicMacros(void) const
592 Dictionary::Ptr macros = boost::make_shared<Dictionary>();
595 ObjectLock olock(this);
597 macros->Set("HOSTNAME", GetName());
598 macros->Set("HOSTDISPLAYNAME", GetDisplayName());
599 macros->Set("HOSTALIAS", GetName());
604 Service::Ptr hc = GetHostCheckService();
607 ObjectLock olock(hc);
609 macros->Set("HOSTSTATE", HostStateToString(GetState()));
610 macros->Set("HOSTSTATEID", GetState());
611 macros->Set("HOSTSTATETYPE", Service::StateTypeToString(hc->GetStateType()));
612 macros->Set("HOSTATTEMPT", hc->GetCurrentCheckAttempt());
613 macros->Set("MAXHOSTATTEMPT", hc->GetMaxCheckAttempts());
615 macros->Set("LASTHOSTSTATE", HostStateToString(GetLastState()));
616 macros->Set("LASTHOSTSTATEID", GetLastState());
617 macros->Set("LASTHOSTSTATETYPE", Service::StateTypeToString(GetLastStateType()));
618 macros->Set("LASTHOSTSTATECHANGE", (long)hc->GetLastStateChange());
620 cr = hc->GetLastCheckResult();
624 macros->Set("HOSTLATENCY", Service::CalculateLatency(cr));
625 macros->Set("HOSTEXECUTIONTIME", Service::CalculateExecutionTime(cr));
627 macros->Set("HOSTOUTPUT", cr->Get("output"));
628 macros->Set("HOSTPERFDATA", cr->Get("performance_data_raw"));
630 macros->Set("LASTHOSTCHECK", (long)cr->Get("schedule_start"));