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 "config/configitembuilder.h"
28 #include "config/configcompilercontext.h"
29 #include <boost/tuple/tuple.hpp>
30 #include <boost/smart_ptr/make_shared.hpp>
31 #include <boost/foreach.hpp>
33 using namespace icinga;
35 static boost::mutex l_ServiceMutex;
36 static std::map<String, std::map<String, Service::WeakPtr> > l_ServicesCache;
37 static bool l_ServicesCacheNeedsUpdate = false;
38 static Timer::Ptr l_ServicesCacheTimer;
40 REGISTER_SCRIPTFUNCTION(ValidateServiceDictionary, &Host::ValidateServiceDictionary);
44 Host::Host(const Dictionary::Ptr& serializedUpdate)
45 : DynamicObject(serializedUpdate)
47 RegisterAttribute("display_name", Attribute_Config, &m_DisplayName);
48 RegisterAttribute("hostgroups", Attribute_Config, &m_HostGroups);
49 RegisterAttribute("macros", Attribute_Config, &m_Macros);
50 RegisterAttribute("hostdependencies", Attribute_Config, &m_HostDependencies);
51 RegisterAttribute("servicedependencies", Attribute_Config, &m_ServiceDependencies);
52 RegisterAttribute("hostcheck", Attribute_Config, &m_HostCheck);
58 HostGroup::InvalidateMembersCache();
60 if (m_SlaveServices) {
61 ConfigItem::Ptr service;
62 BOOST_FOREACH(boost::tie(boost::tuples::ignore, service), m_SlaveServices) {
63 service->Unregister();
68 void Host::OnRegistrationCompleted(void)
72 DynamicObject::OnRegistrationCompleted();
74 Host::InvalidateServicesCache();
75 UpdateSlaveServices();
78 String Host::GetDisplayName(void) const
80 if (!m_DisplayName.IsEmpty())
87 * @threadsafety Always.
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 template<bool copyServiceAttrs, typename TDict>
172 static void CopyServiceAttributes(TDict serviceDesc, const ConfigItemBuilder::Ptr& builder)
174 /* TODO: we only need to copy macros if this is an inline definition,
175 * i.e. "typeid(serviceDesc)" != Service, however for now we just
176 * copy them anyway. */
177 Value macros = serviceDesc->Get("macros");
178 if (!macros.IsEmpty())
179 builder->AddExpression("macros", OperatorPlus, macros);
181 Value checkInterval = serviceDesc->Get("check_interval");
182 if (!checkInterval.IsEmpty())
183 builder->AddExpression("check_interval", OperatorSet, checkInterval);
185 Value retryInterval = serviceDesc->Get("retry_interval");
186 if (!retryInterval.IsEmpty())
187 builder->AddExpression("retry_interval", OperatorSet, retryInterval);
189 Value sgroups = serviceDesc->Get("servicegroups");
190 if (!sgroups.IsEmpty())
191 builder->AddExpression("servicegroups", OperatorPlus, sgroups);
193 Value checkers = serviceDesc->Get("checkers");
194 if (!checkers.IsEmpty())
195 builder->AddExpression("checkers", OperatorSet, checkers);
197 Value short_name = serviceDesc->Get("short_name");
198 if (!short_name.IsEmpty())
199 builder->AddExpression("short_name", OperatorSet, short_name);
201 Value notification_interval = serviceDesc->Get("notification_interval");
202 if (!notification_interval.IsEmpty())
203 builder->AddExpression("notification_interval", OperatorSet, notification_interval);
205 Value check_period = serviceDesc->Get("check_period");
206 if (!check_period.IsEmpty())
207 builder->AddExpression("check_period", OperatorSet, check_period);
209 if (copyServiceAttrs) {
210 Value servicedependencies = serviceDesc->Get("servicedependencies");
211 if (!servicedependencies.IsEmpty())
212 builder->AddExpression("servicedependencies", OperatorPlus, servicedependencies);
214 Value hostdependencies = serviceDesc->Get("hostdependencies");
215 if (!hostdependencies.IsEmpty())
216 builder->AddExpression("hostdependencies", OperatorPlus, hostdependencies);
220 void Host::UpdateSlaveServices(void)
224 ConfigItem::Ptr item = ConfigItem::GetObject("Host", GetName());
226 /* Don't create slave services unless we own this object */
230 Dictionary::Ptr oldServices = m_SlaveServices;
231 Dictionary::Ptr serviceDescs = Get("services");
233 Dictionary::Ptr newServices = boost::make_shared<Dictionary>();
236 ObjectLock olock(serviceDescs);
239 BOOST_FOREACH(boost::tie(svcname, svcdesc), serviceDescs) {
240 if (svcdesc.IsScalar())
243 std::ostringstream namebuf;
244 namebuf << GetName() << "-" << svcname;
245 String name = namebuf.str();
247 ConfigItemBuilder::Ptr builder = boost::make_shared<ConfigItemBuilder>(item->GetDebugInfo());
248 builder->SetType("Service");
249 builder->SetName(name);
250 builder->AddExpression("host_name", OperatorSet, GetName());
251 builder->AddExpression("display_name", OperatorSet, svcname);
252 builder->AddExpression("short_name", OperatorSet, svcname);
254 CopyServiceAttributes<false>(this, builder);
256 if (!svcdesc.IsObjectType<Dictionary>())
257 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be either a string or a dictionary."));
259 Dictionary::Ptr service = svcdesc;
261 Array::Ptr templates = service->Get("templates");
264 ObjectLock olock(templates);
266 BOOST_FOREACH(const Value& tmpl, templates) {
267 builder->AddParent(tmpl);
271 CopyServiceAttributes<true>(service, builder);
273 ConfigItem::Ptr serviceItem = builder->Compile();
274 DynamicObject::Ptr dobj = serviceItem->Commit();
276 newServices->Set(name, serviceItem);
281 ObjectLock olock(oldServices);
283 ConfigItem::Ptr service;
284 BOOST_FOREACH(boost::tie(boost::tuples::ignore, service), oldServices) {
288 if (!newServices->Contains(service->GetName()))
289 service->Unregister();
295 Set("slave_services", newServices);
298 void Host::OnAttributeChanged(const String& name)
302 if (name == "hostgroups")
303 HostGroup::InvalidateMembersCache();
304 else if (name == "services") {
305 UpdateSlaveServices();
306 } else if (name == "notifications") {
307 BOOST_FOREACH(const Service::Ptr& service, GetServices()) {
308 service->UpdateSlaveNotifications();
313 std::set<Service::Ptr> Host::GetServices(void) const
315 std::set<Service::Ptr> services;
317 boost::mutex::scoped_lock lock(l_ServiceMutex);
319 Service::WeakPtr wservice;
320 BOOST_FOREACH(boost::tie(boost::tuples::ignore, wservice), l_ServicesCache[GetName()]) {
321 Service::Ptr service = wservice.lock();
326 services.insert(service);
332 void Host::InvalidateServicesCache(void)
335 boost::mutex::scoped_lock lock(l_ServiceMutex);
337 if (l_ServicesCacheNeedsUpdate)
338 return; /* Someone else has already requested a refresh. */
340 if (!l_ServicesCacheTimer) {
341 l_ServicesCacheTimer = boost::make_shared<Timer>();
342 l_ServicesCacheTimer->SetInterval(0.5);
343 l_ServicesCacheTimer->OnTimerExpired.connect(boost::bind(&Host::RefreshServicesCache));
344 l_ServicesCacheTimer->Start();
347 l_ServicesCacheNeedsUpdate = true;
351 void Host::RefreshServicesCache(void)
354 boost::mutex::scoped_lock lock(l_ServiceMutex);
356 if (!l_ServicesCacheNeedsUpdate)
359 l_ServicesCacheNeedsUpdate = false;
362 Log(LogDebug, "icinga", "Updating Host services cache.");
364 std::map<String, std::map<String, Service::WeakPtr> > newServicesCache;
366 BOOST_FOREACH(const DynamicObject::Ptr& object, DynamicType::GetObjects("Service")) {
367 const Service::Ptr& service = static_pointer_cast<Service>(object);
369 Host::Ptr host = service->GetHost();
374 // TODO: assert for duplicate short_names
376 newServicesCache[host->GetName()][service->GetShortName()] = service;
379 boost::mutex::scoped_lock lock(l_ServiceMutex);
380 l_ServicesCache.swap(newServicesCache);
383 void Host::ValidateServiceDictionary(const ScriptTask::Ptr& task, const std::vector<Value>& arguments)
385 if (arguments.size() < 1)
386 BOOST_THROW_EXCEPTION(std::invalid_argument("Missing argument: Location must be specified."));
388 if (arguments.size() < 2)
389 BOOST_THROW_EXCEPTION(std::invalid_argument("Missing argument: Attribute dictionary must be specified."));
391 String location = arguments[0];
392 Dictionary::Ptr attrs = arguments[1];
393 ObjectLock olock(attrs);
397 BOOST_FOREACH(boost::tie(key, value), attrs) {
398 std::vector<String> templates;
400 if (!value.IsObjectType<Dictionary>())
401 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be a dictionary."));
403 Dictionary::Ptr serviceDesc = value;
405 Array::Ptr templatesArray = serviceDesc->Get("templates");
407 if (templatesArray) {
408 ObjectLock tlock(templatesArray);
410 BOOST_FOREACH(const Value& tmpl, templatesArray) {
411 templates.push_back(tmpl);
415 BOOST_FOREACH(const String& name, templates) {
416 ConfigItem::Ptr item;
418 ConfigCompilerContext *context = ConfigCompilerContext::GetContext();
421 item = context->GetItem("Service", name);
423 /* ignore already active objects while we're in the compiler
424 * context and linking to existing items is disabled. */
425 if (!item && (!context || (context->GetFlags() & CompilerLinkExisting)))
426 item = ConfigItem::GetObject("Service", name);
429 ConfigCompilerContext::GetContext()->AddError(false, "Validation failed for " +
430 location + ": Template '" + name + "' not found.");
435 task->FinishResult(Empty);
438 Service::Ptr Host::GetServiceByShortName(const Value& name) const
440 if (name.IsScalar()) {
442 boost::mutex::scoped_lock lock(l_ServiceMutex);
444 std::map<String, Service::WeakPtr>& services = l_ServicesCache[GetName()];
445 std::map<String, Service::WeakPtr>::iterator it = services.find(name);
447 if (it != services.end()) {
448 Service::Ptr service = it->second.lock();
454 return Service::Ptr();
455 } else if (name.IsObjectType<Dictionary>()) {
456 Dictionary::Ptr dict = name;
459 ASSERT(dict->IsSealed());
461 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
463 BOOST_THROW_EXCEPTION(std::invalid_argument("Host/Service name pair is invalid."));
467 std::set<Host::Ptr> Host::GetParentHosts(void) const
469 std::set<Host::Ptr> parents;
471 Array::Ptr dependencies = GetHostDependencies();
474 ObjectLock olock(dependencies);
476 BOOST_FOREACH(const Value& value, dependencies) {
477 if (value == GetName())
480 Host::Ptr host = GetByName(value);
485 parents.insert(host);
492 Service::Ptr Host::GetHostCheckService(void) const
494 String host_check = GetHostCheck();
496 if (host_check.IsEmpty())
497 return Service::Ptr();
499 return GetServiceByShortName(host_check);
502 std::set<Service::Ptr> Host::GetParentServices(void) const
504 std::set<Service::Ptr> parents;
506 Array::Ptr dependencies = GetServiceDependencies();
509 ObjectLock olock(dependencies);
511 BOOST_FOREACH(const Value& value, dependencies) {
512 parents.insert(GetServiceByShortName(value));
519 HostState Host::CalculateState(ServiceState state, bool reachable)
522 return HostUnreachable;
533 HostState Host::GetLastState(void) const
538 return HostUnreachable;
540 Service::Ptr hc = GetHostCheckService();
545 switch (hc->GetLastState()) {
554 StateType Host::GetLastStateType(void) const
556 Service::Ptr hc = GetHostCheckService();
559 return StateTypeHard;
561 return hc->GetLastStateType();
564 String Host::StateToString(HostState state)
571 case HostUnreachable:
572 return "UNREACHABLE";
578 Dictionary::Ptr Host::CalculateDynamicMacros(void) const
582 Dictionary::Ptr macros = boost::make_shared<Dictionary>();
585 ObjectLock olock(this);
587 macros->Set("HOSTNAME", GetName());
588 macros->Set("HOSTDISPLAYNAME", GetDisplayName());
589 macros->Set("HOSTALIAS", GetName());
594 Service::Ptr hc = GetHostCheckService();
597 ObjectLock olock(hc);
599 ServiceState state = hc->GetState();
600 bool reachable = IsReachable();
602 macros->Set("HOSTSTATE", CalculateState(state, reachable));
603 macros->Set("HOSTSTATEID", state);
604 macros->Set("HOSTSTATETYPE", Service::StateTypeToString(hc->GetStateType()));
605 macros->Set("HOSTATTEMPT", hc->GetCurrentCheckAttempt());
606 macros->Set("MAXHOSTATTEMPT", hc->GetMaxCheckAttempts());
608 macros->Set("LASTHOSTSTATE", StateToString(GetLastState()));
609 macros->Set("LASTHOSTSTATEID", GetLastState());
610 macros->Set("LASTHOSTSTATETYPE", Service::StateTypeToString(GetLastStateType()));
611 macros->Set("LASTHOSTSTATECHANGE", (long)hc->GetLastStateChange());
613 cr = hc->GetLastCheckResult();
617 macros->Set("HOSTLATENCY", Service::CalculateLatency(cr));
618 macros->Set("HOSTEXECUTIONTIME", Service::CalculateExecutionTime(cr));
620 macros->Set("HOSTOUTPUT", cr->Get("output"));
621 macros->Set("HOSTPERFDATA", cr->Get("performance_data_raw"));
623 macros->Set("LASTHOSTCHECK", (long)cr->Get("schedule_start"));