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 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");
231 ExpressionList::Ptr host_exprl = boost::make_shared<ExpressionList>();
232 item->GetLinkedExpressionList()->ExtractFiltered(keys, host_exprl);
233 builder->AddExpressionList(host_exprl);
235 /* Clone attributes from the service expression list. */
236 std::vector<String> path;
237 path.push_back("services");
238 path.push_back(svcname);
240 ExpressionList::Ptr svc_exprl = boost::make_shared<ExpressionList>();
241 item->GetLinkedExpressionList()->ExtractPath(path, svc_exprl);
242 builder->AddExpressionList(svc_exprl);
244 ConfigItem::Ptr serviceItem = builder->Compile();
245 DynamicObject::Ptr dobj = serviceItem->Commit();
247 newServices->Set(name, serviceItem);
252 ObjectLock olock(oldServices);
254 ConfigItem::Ptr service;
255 BOOST_FOREACH(boost::tie(boost::tuples::ignore, service), oldServices) {
259 if (!newServices->Contains(service->GetName()))
260 service->Unregister();
266 Set("slave_services", newServices);
269 void Host::OnAttributeChanged(const String& name)
273 if (name == "hostgroups")
274 HostGroup::InvalidateMembersCache();
275 else if (name == "services") {
276 UpdateSlaveServices();
277 } else if (name == "notifications") {
278 BOOST_FOREACH(const Service::Ptr& service, GetServices()) {
279 service->UpdateSlaveNotifications();
284 std::set<Service::Ptr> Host::GetServices(void) const
286 std::set<Service::Ptr> services;
288 boost::mutex::scoped_lock lock(l_ServiceMutex);
290 Service::WeakPtr wservice;
291 BOOST_FOREACH(boost::tie(boost::tuples::ignore, wservice), l_ServicesCache[GetName()]) {
292 Service::Ptr service = wservice.lock();
297 services.insert(service);
303 void Host::InvalidateServicesCache(void)
306 boost::mutex::scoped_lock lock(l_ServiceMutex);
308 if (l_ServicesCacheNeedsUpdate)
309 return; /* Someone else has already requested a refresh. */
311 if (!l_ServicesCacheTimer) {
312 l_ServicesCacheTimer = boost::make_shared<Timer>();
313 l_ServicesCacheTimer->SetInterval(0.5);
314 l_ServicesCacheTimer->OnTimerExpired.connect(boost::bind(&Host::RefreshServicesCache));
315 l_ServicesCacheTimer->Start();
318 l_ServicesCacheNeedsUpdate = true;
322 void Host::RefreshServicesCache(void)
325 boost::mutex::scoped_lock lock(l_ServiceMutex);
327 if (!l_ServicesCacheNeedsUpdate)
330 l_ServicesCacheNeedsUpdate = false;
333 Log(LogDebug, "icinga", "Updating Host services cache.");
335 std::map<String, std::map<String, Service::WeakPtr> > newServicesCache;
337 BOOST_FOREACH(const DynamicObject::Ptr& object, DynamicType::GetObjects("Service")) {
338 const Service::Ptr& service = static_pointer_cast<Service>(object);
340 Host::Ptr host = service->GetHost();
345 // TODO: assert for duplicate short_names
347 newServicesCache[host->GetName()][service->GetShortName()] = service;
350 boost::mutex::scoped_lock lock(l_ServiceMutex);
351 l_ServicesCache.swap(newServicesCache);
354 void Host::ValidateServiceDictionary(const ScriptTask::Ptr& task, const std::vector<Value>& arguments)
356 if (arguments.size() < 1)
357 BOOST_THROW_EXCEPTION(std::invalid_argument("Missing argument: Location must be specified."));
359 if (arguments.size() < 2)
360 BOOST_THROW_EXCEPTION(std::invalid_argument("Missing argument: Attribute dictionary must be specified."));
362 String location = arguments[0];
363 Dictionary::Ptr attrs = arguments[1];
364 ObjectLock olock(attrs);
368 BOOST_FOREACH(boost::tie(key, value), attrs) {
369 std::vector<String> templates;
371 if (!value.IsObjectType<Dictionary>())
372 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be a dictionary."));
374 Dictionary::Ptr serviceDesc = value;
376 Array::Ptr templatesArray = serviceDesc->Get("templates");
378 if (templatesArray) {
379 ObjectLock tlock(templatesArray);
381 BOOST_FOREACH(const Value& tmpl, templatesArray) {
382 templates.push_back(tmpl);
386 BOOST_FOREACH(const String& name, templates) {
387 ConfigItem::Ptr item;
389 ConfigCompilerContext *context = ConfigCompilerContext::GetContext();
392 item = context->GetItem("Service", name);
394 /* ignore already active objects while we're in the compiler
395 * context and linking to existing items is disabled. */
396 if (!item && (!context || (context->GetFlags() & CompilerLinkExisting)))
397 item = ConfigItem::GetObject("Service", name);
400 ConfigCompilerContext::GetContext()->AddError(false, "Validation failed for " +
401 location + ": Template '" + name + "' not found.");
406 task->FinishResult(Empty);
409 Service::Ptr Host::GetServiceByShortName(const Value& name) const
411 if (name.IsScalar()) {
413 boost::mutex::scoped_lock lock(l_ServiceMutex);
415 std::map<String, Service::WeakPtr>& services = l_ServicesCache[GetName()];
416 std::map<String, Service::WeakPtr>::iterator it = services.find(name);
418 if (it != services.end()) {
419 Service::Ptr service = it->second.lock();
425 return Service::Ptr();
426 } else if (name.IsObjectType<Dictionary>()) {
427 Dictionary::Ptr dict = name;
430 ASSERT(dict->IsSealed());
432 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
434 BOOST_THROW_EXCEPTION(std::invalid_argument("Host/Service name pair is invalid."));
438 std::set<Host::Ptr> Host::GetParentHosts(void) const
440 std::set<Host::Ptr> parents;
442 Array::Ptr dependencies = GetHostDependencies();
445 ObjectLock olock(dependencies);
447 BOOST_FOREACH(const Value& value, dependencies) {
448 if (value == GetName())
451 Host::Ptr host = GetByName(value);
456 parents.insert(host);
463 Service::Ptr Host::GetHostCheckService(void) const
465 String host_check = GetHostCheck();
467 if (host_check.IsEmpty())
468 return Service::Ptr();
470 return GetServiceByShortName(host_check);
473 std::set<Service::Ptr> Host::GetParentServices(void) const
475 std::set<Service::Ptr> parents;
477 Array::Ptr dependencies = GetServiceDependencies();
480 ObjectLock olock(dependencies);
482 BOOST_FOREACH(const Value& value, dependencies) {
483 parents.insert(GetServiceByShortName(value));
490 HostState Host::CalculateState(ServiceState state, bool reachable)
493 return HostUnreachable;
504 HostState Host::GetLastState(void) const
509 return HostUnreachable;
511 Service::Ptr hc = GetHostCheckService();
516 switch (hc->GetLastState()) {
525 StateType Host::GetLastStateType(void) const
527 Service::Ptr hc = GetHostCheckService();
530 return StateTypeHard;
532 return hc->GetLastStateType();
535 String Host::StateToString(HostState state)
542 case HostUnreachable:
543 return "UNREACHABLE";
549 Dictionary::Ptr Host::CalculateDynamicMacros(void) const
553 Dictionary::Ptr macros = boost::make_shared<Dictionary>();
556 ObjectLock olock(this);
558 macros->Set("HOSTNAME", GetName());
559 macros->Set("HOSTDISPLAYNAME", GetDisplayName());
560 macros->Set("HOSTALIAS", GetName());
565 Service::Ptr hc = GetHostCheckService();
568 ObjectLock olock(hc);
570 ServiceState state = hc->GetState();
571 bool reachable = IsReachable();
573 macros->Set("HOSTSTATE", CalculateState(state, reachable));
574 macros->Set("HOSTSTATEID", state);
575 macros->Set("HOSTSTATETYPE", Service::StateTypeToString(hc->GetStateType()));
576 macros->Set("HOSTATTEMPT", hc->GetCurrentCheckAttempt());
577 macros->Set("MAXHOSTATTEMPT", hc->GetMaxCheckAttempts());
579 macros->Set("LASTHOSTSTATE", StateToString(GetLastState()));
580 macros->Set("LASTHOSTSTATEID", GetLastState());
581 macros->Set("LASTHOSTSTATETYPE", Service::StateTypeToString(GetLastStateType()));
582 macros->Set("LASTHOSTSTATECHANGE", (long)hc->GetLastStateChange());
584 cr = hc->GetLastCheckResult();
588 macros->Set("HOSTLATENCY", Service::CalculateLatency(cr));
589 macros->Set("HOSTEXECUTIONTIME", Service::CalculateExecutionTime(cr));
591 macros->Set("HOSTOUTPUT", cr->Get("output"));
592 macros->Set("HOSTPERFDATA", cr->Get("performance_data_raw"));
594 macros->Set("LASTHOSTCHECK", (long)cr->Get("schedule_start"));