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 "base/convert.h"
28 #include "config/configitembuilder.h"
29 #include "config/configcompilercontext.h"
30 #include <boost/tuple/tuple.hpp>
31 #include <boost/smart_ptr/make_shared.hpp>
32 #include <boost/foreach.hpp>
34 using namespace icinga;
36 static boost::mutex l_ServiceMutex;
37 static std::map<String, std::map<String, Service::WeakPtr> > l_ServicesCache;
38 static bool l_ServicesCacheNeedsUpdate = false;
39 static Timer::Ptr l_ServicesCacheTimer;
41 REGISTER_SCRIPTFUNCTION(ValidateServiceDictionary, &Host::ValidateServiceDictionary);
45 Host::Host(const Dictionary::Ptr& serializedUpdate)
46 : DynamicObject(serializedUpdate)
48 RegisterAttribute("display_name", Attribute_Config, &m_DisplayName);
49 RegisterAttribute("hostgroups", Attribute_Config, &m_HostGroups);
50 RegisterAttribute("macros", Attribute_Config, &m_Macros);
51 RegisterAttribute("hostdependencies", Attribute_Config, &m_HostDependencies);
52 RegisterAttribute("servicedependencies", Attribute_Config, &m_ServiceDependencies);
53 RegisterAttribute("hostcheck", Attribute_Config, &m_HostCheck);
59 HostGroup::InvalidateMembersCache();
61 if (m_SlaveServices) {
62 ConfigItem::Ptr service;
63 BOOST_FOREACH(boost::tie(boost::tuples::ignore, service), m_SlaveServices) {
64 service->Unregister();
69 void Host::OnRegistrationCompleted(void)
73 DynamicObject::OnRegistrationCompleted();
75 Host::InvalidateServicesCache();
76 UpdateSlaveServices();
79 String Host::GetDisplayName(void) const
81 if (!m_DisplayName.IsEmpty())
87 Host::Ptr Host::GetByName(const String& name)
89 DynamicObject::Ptr configObject = DynamicObject::GetObject("Host", name);
91 return dynamic_pointer_cast<Host>(configObject);
94 Array::Ptr Host::GetGroups(void) const
99 Dictionary::Ptr Host::GetMacros(void) const
104 Array::Ptr Host::GetHostDependencies(void) const
106 return m_HostDependencies;;
109 Array::Ptr Host::GetServiceDependencies(void) const
111 return m_ServiceDependencies;
114 String Host::GetHostCheck(void) const
119 bool Host::IsReachable(void) const
123 std::set<Service::Ptr> parentServices = GetParentServices();
125 BOOST_FOREACH(const Service::Ptr& service, parentServices) {
126 ObjectLock olock(service);
128 /* ignore pending services */
129 if (!service->GetLastCheckResult())
132 /* ignore soft states */
133 if (service->GetStateType() == StateTypeSoft)
136 /* ignore services states OK and Warning */
137 if (service->GetState() == StateOK ||
138 service->GetState() == StateWarning)
144 std::set<Host::Ptr> parentHosts = GetParentHosts();
146 BOOST_FOREACH(const Host::Ptr& host, parentHosts) {
147 Service::Ptr hc = host->GetHostCheckService();
149 /* ignore hosts that don't have a hostcheck */
153 ObjectLock olock(hc);
155 /* ignore soft states */
156 if (hc->GetStateType() == StateTypeSoft)
159 /* ignore hosts that are up */
160 if (hc->GetState() == StateOK)
169 void Host::UpdateSlaveServices(void)
173 ConfigItem::Ptr item = ConfigItem::GetObject("Host", GetName());
175 /* Don't create slave services unless we own this object */
179 Dictionary::Ptr oldServices = m_SlaveServices;
180 Dictionary::Ptr serviceDescs = Get("services");
182 Dictionary::Ptr newServices = boost::make_shared<Dictionary>();
185 ObjectLock olock(serviceDescs);
188 BOOST_FOREACH(boost::tie(svcname, svcdesc), serviceDescs) {
189 if (svcdesc.IsScalar())
192 std::ostringstream namebuf;
193 namebuf << GetName() << "-" << svcname;
194 String name = namebuf.str();
196 ConfigItemBuilder::Ptr builder = boost::make_shared<ConfigItemBuilder>(item->GetDebugInfo());
197 builder->SetType("Service");
198 builder->SetName(name);
199 builder->AddExpression("host_name", OperatorSet, GetName());
200 builder->AddExpression("display_name", OperatorSet, svcname);
201 builder->AddExpression("short_name", OperatorSet, svcname);
203 if (!svcdesc.IsObjectType<Dictionary>())
204 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be either a string or a dictionary."));
206 Dictionary::Ptr service = svcdesc;
208 Array::Ptr templates = service->Get("templates");
211 ObjectLock olock(templates);
213 BOOST_FOREACH(const Value& tmpl, templates) {
214 builder->AddParent(tmpl);
218 /* Clone attributes from the host object. */
219 std::set<String, string_iless> keys;
220 keys.insert("check_interval");
221 keys.insert("retry_interval");
222 keys.insert("servicegroups");
223 keys.insert("checkers");
224 keys.insert("notification_interval");
225 keys.insert("check_period");
226 keys.insert("servicedependencies");
227 keys.insert("hostdependencies");
228 keys.insert("export_macros");
230 ExpressionList::Ptr host_exprl = boost::make_shared<ExpressionList>();
231 item->GetLinkedExpressionList()->ExtractFiltered(keys, host_exprl);
232 builder->AddExpressionList(host_exprl);
234 /* Clone attributes from the service expression list. */
235 std::vector<String> path;
236 path.push_back("services");
237 path.push_back(svcname);
239 ExpressionList::Ptr svc_exprl = boost::make_shared<ExpressionList>();
240 item->GetLinkedExpressionList()->ExtractPath(path, svc_exprl);
241 builder->AddExpressionList(svc_exprl);
243 ConfigItem::Ptr serviceItem = builder->Compile();
244 DynamicObject::Ptr dobj = serviceItem->Commit();
246 newServices->Set(name, serviceItem);
251 ObjectLock olock(oldServices);
253 ConfigItem::Ptr service;
254 BOOST_FOREACH(boost::tie(boost::tuples::ignore, service), oldServices) {
258 if (!newServices->Contains(service->GetName()))
259 service->Unregister();
265 Set("slave_services", newServices);
268 void Host::OnAttributeChanged(const String& name)
272 if (name == "hostgroups")
273 HostGroup::InvalidateMembersCache();
274 else if (name == "services") {
275 UpdateSlaveServices();
276 } else if (name == "notifications") {
277 BOOST_FOREACH(const Service::Ptr& service, GetServices()) {
278 service->UpdateSlaveNotifications();
283 std::set<Service::Ptr> Host::GetServices(void) const
285 std::set<Service::Ptr> services;
287 boost::mutex::scoped_lock lock(l_ServiceMutex);
289 Service::WeakPtr wservice;
290 BOOST_FOREACH(boost::tie(boost::tuples::ignore, wservice), l_ServicesCache[GetName()]) {
291 Service::Ptr service = wservice.lock();
296 services.insert(service);
302 void Host::InvalidateServicesCache(void)
305 boost::mutex::scoped_lock lock(l_ServiceMutex);
307 if (l_ServicesCacheNeedsUpdate)
308 return; /* Someone else has already requested a refresh. */
310 if (!l_ServicesCacheTimer) {
311 l_ServicesCacheTimer = boost::make_shared<Timer>();
312 l_ServicesCacheTimer->SetInterval(0.5);
313 l_ServicesCacheTimer->OnTimerExpired.connect(boost::bind(&Host::RefreshServicesCache));
314 l_ServicesCacheTimer->Start();
317 l_ServicesCacheNeedsUpdate = true;
321 void Host::RefreshServicesCache(void)
324 boost::mutex::scoped_lock lock(l_ServiceMutex);
326 if (!l_ServicesCacheNeedsUpdate)
329 l_ServicesCacheNeedsUpdate = false;
332 Log(LogDebug, "icinga", "Updating Host services cache.");
334 std::map<String, std::map<String, Service::WeakPtr> > newServicesCache;
336 BOOST_FOREACH(const DynamicObject::Ptr& object, DynamicType::GetObjects("Service")) {
337 const Service::Ptr& service = static_pointer_cast<Service>(object);
339 Host::Ptr host = service->GetHost();
344 // TODO: assert for duplicate short_names
346 newServicesCache[host->GetName()][service->GetShortName()] = service;
349 boost::mutex::scoped_lock lock(l_ServiceMutex);
350 l_ServicesCache.swap(newServicesCache);
353 void Host::ValidateServiceDictionary(const ScriptTask::Ptr& task, const std::vector<Value>& arguments)
355 if (arguments.size() < 1)
356 BOOST_THROW_EXCEPTION(std::invalid_argument("Missing argument: Location must be specified."));
358 if (arguments.size() < 2)
359 BOOST_THROW_EXCEPTION(std::invalid_argument("Missing argument: Attribute dictionary must be specified."));
361 String location = arguments[0];
362 Dictionary::Ptr attrs = arguments[1];
363 ObjectLock olock(attrs);
367 BOOST_FOREACH(boost::tie(key, value), attrs) {
368 std::vector<String> templates;
370 if (!value.IsObjectType<Dictionary>())
371 BOOST_THROW_EXCEPTION(std::invalid_argument("Service description must be a dictionary."));
373 Dictionary::Ptr serviceDesc = value;
375 Array::Ptr templatesArray = serviceDesc->Get("templates");
377 if (templatesArray) {
378 ObjectLock tlock(templatesArray);
380 BOOST_FOREACH(const Value& tmpl, templatesArray) {
381 templates.push_back(tmpl);
385 BOOST_FOREACH(const String& name, templates) {
386 ConfigItem::Ptr item;
388 ConfigCompilerContext *context = ConfigCompilerContext::GetContext();
391 item = context->GetItem("Service", name);
393 /* ignore already active objects while we're in the compiler
394 * context and linking to existing items is disabled. */
395 if (!item && (!context || (context->GetFlags() & CompilerLinkExisting)))
396 item = ConfigItem::GetObject("Service", name);
399 ConfigCompilerContext::GetContext()->AddError(false, "Validation failed for " +
400 location + ": Template '" + name + "' not found.");
405 task->FinishResult(Empty);
408 Service::Ptr Host::GetServiceByShortName(const Value& name) const
410 if (name.IsScalar()) {
412 boost::mutex::scoped_lock lock(l_ServiceMutex);
414 std::map<String, Service::WeakPtr>& services = l_ServicesCache[GetName()];
415 std::map<String, Service::WeakPtr>::iterator it = services.find(name);
417 if (it != services.end()) {
418 Service::Ptr service = it->second.lock();
424 return Service::Ptr();
425 } else if (name.IsObjectType<Dictionary>()) {
426 Dictionary::Ptr dict = name;
429 ASSERT(dict->IsSealed());
431 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
433 BOOST_THROW_EXCEPTION(std::invalid_argument("Host/Service name pair is invalid."));
437 std::set<Host::Ptr> Host::GetParentHosts(void) const
439 std::set<Host::Ptr> parents;
441 Array::Ptr dependencies = GetHostDependencies();
444 ObjectLock olock(dependencies);
446 BOOST_FOREACH(const Value& value, dependencies) {
447 if (value == GetName())
450 Host::Ptr host = GetByName(value);
455 parents.insert(host);
462 Service::Ptr Host::GetHostCheckService(void) const
464 String host_check = GetHostCheck();
466 if (host_check.IsEmpty())
467 return Service::Ptr();
469 return GetServiceByShortName(host_check);
472 std::set<Service::Ptr> Host::GetParentServices(void) const
474 std::set<Service::Ptr> parents;
476 Array::Ptr dependencies = GetServiceDependencies();
479 ObjectLock olock(dependencies);
481 BOOST_FOREACH(const Value& value, dependencies) {
482 parents.insert(GetServiceByShortName(value));
489 HostState Host::CalculateState(ServiceState state, bool reachable)
492 return HostUnreachable;
503 HostState Host::GetLastState(void) const
508 return HostUnreachable;
510 Service::Ptr hc = GetHostCheckService();
515 switch (hc->GetLastState()) {
524 StateType Host::GetLastStateType(void) const
526 Service::Ptr hc = GetHostCheckService();
529 return StateTypeHard;
531 return hc->GetLastStateType();
534 String Host::StateToString(HostState state)
541 case HostUnreachable:
542 return "UNREACHABLE";
548 bool Host::ResolveMacro(const String& macro, const Dictionary::Ptr& cr, String *result) const
550 if (macro == "HOSTNAME" || macro == "HOSTALIAS") {
554 else if (macro == "HOSTDISPLAYNAME") {
555 *result = GetDisplayName();
559 Service::Ptr hc = GetHostCheckService();
560 Dictionary::Ptr hccr;
563 ServiceState state = hc->GetState();
564 bool reachable = IsReachable();
566 if (macro == "HOSTSTATE") {
567 *result = Convert::ToString(CalculateState(state, reachable));
569 } else if (macro == "HOSTSTATEID") {
570 *result = Convert::ToString(state);
572 } else if (macro == "HOSTSTATETYPE") {
573 *result = Service::StateTypeToString(hc->GetStateType());
575 } else if (macro == "HOSTATTEMPT") {
576 *result = Convert::ToString(hc->GetCurrentCheckAttempt());
578 } else if (macro == "MAXHOSTATTEMPT") {
579 *result = Convert::ToString(hc->GetMaxCheckAttempts());
581 } else if (macro == "LASTHOSTSTATE") {
582 *result = StateToString(GetLastState());
584 } else if (macro == "LASTHOSTSTATEID") {
585 *result = Convert::ToString(GetLastState());
587 } else if (macro == "LASTHOSTSTATETYPE") {
588 *result = Service::StateTypeToString(GetLastStateType());
590 } else if (macro == "LASTHOSTSTATECHANGE") {
591 *result = Convert::ToString((long)hc->GetLastStateChange());
595 hccr = hc->GetLastCheckResult();
599 if (macro == "HOSTLATENCY") {
600 *result = Convert::ToString(Service::CalculateLatency(hccr));
602 } else if (macro == "HOSTEXECUTIONTIME") {
603 *result = Convert::ToString(Service::CalculateExecutionTime(hccr));
605 } else if (macro == "HOSTOUTPUT") {
606 *result = hccr->Get("output");
608 } else if (macro == "HOSTPERFDATA") {
609 *result = hccr->Get("performance_data_raw");
611 } else if (macro == "LASTHOSTCHECK") {
612 *result = Convert::ToString((long)hccr->Get("schedule_start"));
617 Dictionary::Ptr macros = GetMacros();
619 if (macros && macros->Contains(macro)) {
620 *result = macros->Get(macro);