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"
22 using namespace icinga;
24 boost::mutex Host::m_ServiceMutex;
25 map<String, map<String, Service::WeakPtr> > Host::m_ServicesCache;
26 bool Host::m_ServicesCacheNeedsUpdate = false;
27 Timer::Ptr Host::m_ServicesCacheTimer;
29 REGISTER_SCRIPTFUNCTION(ValidateServiceDictionary, &Host::ValidateServiceDictionary);
33 Host::Host(const Dictionary::Ptr& serializedUpdate)
34 : DynamicObject(serializedUpdate)
36 RegisterAttribute("display_name", Attribute_Config, &m_DisplayName);
37 RegisterAttribute("hostgroups", Attribute_Config, &m_HostGroups);
38 RegisterAttribute("macros", Attribute_Config, &m_Macros);
39 RegisterAttribute("hostdependencies", Attribute_Config, &m_HostDependencies);
40 RegisterAttribute("servicedependencies", Attribute_Config, &m_ServiceDependencies);
41 RegisterAttribute("hostcheck", Attribute_Config, &m_HostCheck);
47 HostGroup::InvalidateMembersCache();
49 if (m_SlaveServices) {
50 ConfigItem::Ptr service;
51 BOOST_FOREACH(tie(tuples::ignore, service), m_SlaveServices) {
52 service->Unregister();
57 void Host::OnRegistrationCompleted(void)
61 DynamicObject::OnRegistrationCompleted();
63 Host::InvalidateServicesCache();
64 UpdateSlaveServices();
67 String Host::GetDisplayName(void) const
69 if (!m_DisplayName.IsEmpty())
76 * @threadsafety Always.
78 Host::Ptr Host::GetByName(const String& name)
80 DynamicObject::Ptr configObject = DynamicObject::GetObject("Host", name);
82 return dynamic_pointer_cast<Host>(configObject);
85 Array::Ptr Host::GetGroups(void) const
90 Dictionary::Ptr Host::GetMacros(void) const
95 Array::Ptr Host::GetHostDependencies(void) const
97 return m_HostDependencies;;
100 Array::Ptr Host::GetServiceDependencies(void) const
102 return m_ServiceDependencies;
105 String Host::GetHostCheck(void) const
110 bool Host::IsReachable(void) const
114 set<Service::Ptr> parentServices = GetParentServices();
116 BOOST_FOREACH(const Service::Ptr& service, parentServices) {
117 ObjectLock olock(service);
119 /* ignore pending services */
120 if (!service->GetLastCheckResult())
123 /* ignore soft states */
124 if (service->GetStateType() == StateTypeSoft)
127 /* ignore services states OK and Warning */
128 if (service->GetState() == StateOK ||
129 service->GetState() == StateWarning)
135 set<Host::Ptr> parentHosts = GetParentHosts();
137 BOOST_FOREACH(const Host::Ptr& host, parentHosts) {
138 Service::Ptr hc = host->GetHostCheckService();
140 /* ignore hosts that don't have a hostcheck */
144 ObjectLock olock(hc);
146 /* ignore soft states */
147 if (hc->GetStateType() == StateTypeSoft)
150 /* ignore hosts that are up */
151 if (hc->GetState() == StateOK)
160 template<bool copyServiceAttrs, typename TDict>
161 static void CopyServiceAttributes(TDict serviceDesc, const ConfigItemBuilder::Ptr& builder)
163 /* TODO: we only need to copy macros if this is an inline definition,
164 * i.e. "typeid(serviceDesc)" != Service, however for now we just
165 * copy them anyway. */
166 Value macros = serviceDesc->Get("macros");
167 if (!macros.IsEmpty())
168 builder->AddExpression("macros", OperatorPlus, macros);
170 Value checkInterval = serviceDesc->Get("check_interval");
171 if (!checkInterval.IsEmpty())
172 builder->AddExpression("check_interval", OperatorSet, checkInterval);
174 Value retryInterval = serviceDesc->Get("retry_interval");
175 if (!retryInterval.IsEmpty())
176 builder->AddExpression("retry_interval", OperatorSet, retryInterval);
178 Value sgroups = serviceDesc->Get("servicegroups");
179 if (!sgroups.IsEmpty())
180 builder->AddExpression("servicegroups", OperatorPlus, sgroups);
182 Value checkers = serviceDesc->Get("checkers");
183 if (!checkers.IsEmpty())
184 builder->AddExpression("checkers", OperatorSet, checkers);
186 Value short_name = serviceDesc->Get("short_name");
187 if (!short_name.IsEmpty())
188 builder->AddExpression("short_name", OperatorSet, short_name);
190 Value notification_interval = serviceDesc->Get("notification_interval");
191 if (!notification_interval.IsEmpty())
192 builder->AddExpression("notification_interval", OperatorSet, notification_interval);
194 Value check_period = serviceDesc->Get("check_period");
195 if (!check_period.IsEmpty())
196 builder->AddExpression("check_period", OperatorSet, check_period);
198 if (copyServiceAttrs) {
199 Value servicedependencies = serviceDesc->Get("servicedependencies");
200 if (!servicedependencies.IsEmpty())
201 builder->AddExpression("servicedependencies", OperatorPlus, servicedependencies);
203 Value hostdependencies = serviceDesc->Get("hostdependencies");
204 if (!hostdependencies.IsEmpty())
205 builder->AddExpression("hostdependencies", OperatorPlus, hostdependencies);
209 void Host::UpdateSlaveServices(void)
213 ConfigItem::Ptr item = ConfigItem::GetObject("Host", GetName());
215 /* Don't create slave services unless we own this object */
219 Dictionary::Ptr oldServices = m_SlaveServices;
220 Dictionary::Ptr serviceDescs = Get("services");
222 Dictionary::Ptr newServices = boost::make_shared<Dictionary>();
225 ObjectLock olock(serviceDescs);
228 BOOST_FOREACH(tie(svcname, svcdesc), serviceDescs) {
229 if (svcdesc.IsScalar())
232 stringstream namebuf;
233 namebuf << GetName() << "-" << svcname;
234 String name = namebuf.str();
236 ConfigItemBuilder::Ptr builder = boost::make_shared<ConfigItemBuilder>(item->GetDebugInfo());
237 builder->SetType("Service");
238 builder->SetName(name);
239 builder->AddExpression("host_name", OperatorSet, GetName());
240 builder->AddExpression("display_name", OperatorSet, svcname);
241 builder->AddExpression("short_name", OperatorSet, svcname);
243 CopyServiceAttributes<false>(this, builder);
245 if (!svcdesc.IsObjectType<Dictionary>())
246 BOOST_THROW_EXCEPTION(invalid_argument("Service description must be either a string or a dictionary."));
248 Dictionary::Ptr service = svcdesc;
250 Array::Ptr templates = service->Get("templates");
253 ObjectLock olock(templates);
255 BOOST_FOREACH(const Value& tmpl, templates) {
256 builder->AddParent(tmpl);
260 CopyServiceAttributes<true>(service, builder);
262 ConfigItem::Ptr serviceItem = builder->Compile();
263 DynamicObject::Ptr dobj = serviceItem->Commit();
265 newServices->Set(name, serviceItem);
270 ObjectLock olock(oldServices);
272 ConfigItem::Ptr service;
273 BOOST_FOREACH(tie(tuples::ignore, service), oldServices) {
277 if (!newServices->Contains(service->GetName()))
278 service->Unregister();
284 Set("slave_services", newServices);
287 void Host::OnAttributeChanged(const String& name)
291 if (name == "hostgroups")
292 HostGroup::InvalidateMembersCache();
293 else if (name == "services") {
294 UpdateSlaveServices();
295 } else if (name == "notifications") {
296 BOOST_FOREACH(const Service::Ptr& service, GetServices()) {
297 service->UpdateSlaveNotifications();
302 set<Service::Ptr> Host::GetServices(void) const
304 set<Service::Ptr> services;
306 boost::mutex::scoped_lock lock(m_ServiceMutex);
308 Service::WeakPtr wservice;
309 BOOST_FOREACH(tie(tuples::ignore, wservice), m_ServicesCache[GetName()]) {
310 Service::Ptr service = wservice.lock();
315 services.insert(service);
321 void Host::InvalidateServicesCache(void)
324 boost::mutex::scoped_lock lock(m_ServiceMutex);
326 if (m_ServicesCacheNeedsUpdate)
327 return; /* Someone else has already requested a refresh. */
329 if (!m_ServicesCacheTimer) {
330 m_ServicesCacheTimer = boost::make_shared<Timer>();
331 m_ServicesCacheTimer->SetInterval(0.5);
332 m_ServicesCacheTimer->OnTimerExpired.connect(boost::bind(&Host::RefreshServicesCache));
333 m_ServicesCacheTimer->Start();
336 m_ServicesCacheNeedsUpdate = true;
340 void Host::RefreshServicesCache(void)
343 boost::mutex::scoped_lock lock(m_ServiceMutex);
345 if (!m_ServicesCacheNeedsUpdate)
348 m_ServicesCacheNeedsUpdate = false;
351 Logger::Write(LogDebug, "icinga", "Updating Host services cache.");
353 map<String, map<String, Service::WeakPtr> > newServicesCache;
355 BOOST_FOREACH(const DynamicObject::Ptr& object, DynamicType::GetObjects("Service")) {
356 const Service::Ptr& service = static_pointer_cast<Service>(object);
358 Host::Ptr host = service->GetHost();
363 // TODO: assert for duplicate short_names
365 newServicesCache[host->GetName()][service->GetShortName()] = service;
368 boost::mutex::scoped_lock lock(m_ServiceMutex);
369 m_ServicesCache.swap(newServicesCache);
372 void Host::ValidateServiceDictionary(const ScriptTask::Ptr& task, const vector<Value>& arguments)
374 if (arguments.size() < 1)
375 BOOST_THROW_EXCEPTION(invalid_argument("Missing argument: Location must be specified."));
377 if (arguments.size() < 2)
378 BOOST_THROW_EXCEPTION(invalid_argument("Missing argument: Attribute dictionary must be specified."));
380 String location = arguments[0];
381 Dictionary::Ptr attrs = arguments[1];
382 ObjectLock olock(attrs);
386 BOOST_FOREACH(tie(key, value), attrs) {
387 vector<String> templates;
389 if (!value.IsObjectType<Dictionary>())
390 BOOST_THROW_EXCEPTION(invalid_argument("Service description must be a dictionary."));
392 Dictionary::Ptr serviceDesc = value;
394 Array::Ptr templatesArray = serviceDesc->Get("templates");
396 if (templatesArray) {
397 ObjectLock tlock(templatesArray);
399 BOOST_FOREACH(const Value& tmpl, templatesArray) {
400 templates.push_back(tmpl);
404 BOOST_FOREACH(const String& name, templates) {
405 ConfigItem::Ptr item;
407 ConfigCompilerContext *context = ConfigCompilerContext::GetContext();
410 item = context->GetItem("Service", name);
412 /* ignore already active objects while we're in the compiler
413 * context and linking to existing items is disabled. */
414 if (!item && (!context || (context->GetFlags() & CompilerLinkExisting)))
415 item = ConfigItem::GetObject("Service", name);
418 ConfigCompilerContext::GetContext()->AddError(false, "Validation failed for " +
419 location + ": Template '" + name + "' not found.");
424 task->FinishResult(Empty);
427 Service::Ptr Host::GetServiceByShortName(const Value& name) const
429 if (name.IsScalar()) {
431 boost::mutex::scoped_lock lock(m_ServiceMutex);
433 map<String, Service::WeakPtr>& services = m_ServicesCache[GetName()];
434 map<String, Service::WeakPtr>::iterator it = services.find(name);
436 if (it != services.end()) {
437 Service::Ptr service = it->second.lock();
443 return Service::Ptr();
444 } else if (name.IsObjectType<Dictionary>()) {
445 Dictionary::Ptr dict = name;
448 ASSERT(dict->IsSealed());
450 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
452 BOOST_THROW_EXCEPTION(invalid_argument("Host/Service name pair is invalid."));
456 set<Host::Ptr> Host::GetParentHosts(void) const
458 set<Host::Ptr> parents;
460 Array::Ptr dependencies = GetHostDependencies();
463 ObjectLock olock(dependencies);
465 BOOST_FOREACH(const Value& value, dependencies) {
466 if (value == GetName())
469 Host::Ptr host = GetByName(value);
474 parents.insert(host);
481 Service::Ptr Host::GetHostCheckService(void) const
483 String host_check = GetHostCheck();
485 if (host_check.IsEmpty())
486 return Service::Ptr();
488 return GetServiceByShortName(host_check);
491 set<Service::Ptr> Host::GetParentServices(void) const
493 set<Service::Ptr> parents;
495 Array::Ptr dependencies = GetServiceDependencies();
498 ObjectLock olock(dependencies);
500 BOOST_FOREACH(const Value& value, dependencies) {
501 parents.insert(GetServiceByShortName(value));
508 HostState Host::GetState(void) const
511 return HostUnreachable;
513 Service::Ptr hc = GetHostCheckService();
518 switch (hc->GetState()) {
527 StateType Host::GetStateType(void) const
529 Service::Ptr hc = GetHostCheckService();
532 return StateTypeHard;
534 return hc->GetStateType();
537 HostState Host::GetLastState(void) const
542 return HostUnreachable;
544 Service::Ptr hc = GetHostCheckService();
549 switch (hc->GetLastState()) {
558 StateType Host::GetLastStateType(void) const
560 Service::Ptr hc = GetHostCheckService();
563 return StateTypeHard;
565 return hc->GetLastStateType();
568 String Host::HostStateToString(HostState state)
575 case HostUnreachable:
576 return "UNREACHABLE";
582 Dictionary::Ptr Host::CalculateDynamicMacros(void) const
586 Dictionary::Ptr macros = boost::make_shared<Dictionary>();
589 ObjectLock olock(this);
591 macros->Set("HOSTNAME", GetName());
592 macros->Set("HOSTDISPLAYNAME", GetDisplayName());
593 macros->Set("HOSTALIAS", GetName());
598 Service::Ptr hc = GetHostCheckService();
601 ObjectLock olock(hc);
603 macros->Set("HOSTSTATE", HostStateToString(GetState()));
604 macros->Set("HOSTSTATEID", GetState());
605 macros->Set("HOSTSTATETYPE", Service::StateTypeToString(hc->GetStateType()));
606 macros->Set("HOSTATTEMPT", hc->GetCurrentCheckAttempt());
607 macros->Set("MAXHOSTATTEMPT", hc->GetMaxCheckAttempts());
609 macros->Set("LASTHOSTSTATE", HostStateToString(GetLastState()));
610 macros->Set("LASTHOSTSTATEID", GetLastState());
611 macros->Set("LASTHOSTSTATETYPE", Service::StateTypeToString(GetLastStateType()));
612 macros->Set("LASTHOSTSTATECHANGE", (long)hc->GetLastStateChange());
614 cr = hc->GetLastCheckResult();
618 macros->Set("HOSTLATENCY", Service::CalculateLatency(cr));
619 macros->Set("HOSTEXECUTIONTIME", Service::CalculateExecutionTime(cr));
621 macros->Set("HOSTOUTPUT", cr->Get("output"));
622 macros->Set("HOSTPERFDATA", cr->Get("performance_data_raw"));
624 macros->Set("LASTHOSTCHECK", (long)cr->Get("schedule_start"));