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& properties)
34 : DynamicObject(properties)
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 Dictionary::Ptr Host::GetGroups(void) const
90 Dictionary::Ptr Host::GetMacros(void) const
95 Dictionary::Ptr Host::GetHostDependencies(void) const
97 return m_HostDependencies;;
100 Dictionary::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.IsScalar()) {
246 builder->AddParent(svcdesc);
247 } else if (svcdesc.IsObjectType<Dictionary>()) {
248 Dictionary::Ptr service = svcdesc;
250 Dictionary::Ptr templates = service->Get("templates");
253 ObjectLock olock(templates);
256 BOOST_FOREACH(tie(tuples::ignore, tmpl), templates) {
257 builder->AddParent(tmpl);
260 builder->AddParent(svcname);
263 CopyServiceAttributes<true>(service, builder);
265 BOOST_THROW_EXCEPTION(invalid_argument("Service description must be either a string or a dictionary."));
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(tie(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 set<Service::Ptr> Host::GetServices(void) const
310 set<Service::Ptr> services;
312 boost::mutex::scoped_lock lock(m_ServiceMutex);
314 Service::WeakPtr wservice;
315 BOOST_FOREACH(tie(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 Logger::Write(LogInformation, "icinga", "Updating Host services cache.");
359 map<String, 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 vector<Value>& arguments)
380 if (arguments.size() < 1)
381 BOOST_THROW_EXCEPTION(invalid_argument("Missing argument: Location must be specified."));
383 if (arguments.size() < 2)
384 BOOST_THROW_EXCEPTION(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(tie(key, value), attrs) {
393 vector<String> templates;
395 if (value.IsScalar()) {
396 templates.push_back(value);
397 } else if (value.IsObjectType<Dictionary>()) {
398 Dictionary::Ptr serviceDesc = value;
400 Dictionary::Ptr templatesDict = serviceDesc->Get("templates");
401 ObjectLock tlock(templatesDict);
404 BOOST_FOREACH(tie(tuples::ignore, tmpl), templatesDict) {
405 templates.push_back(tmpl);
411 BOOST_FOREACH(const String& name, templates) {
412 ConfigItem::Ptr item;
414 ConfigCompilerContext *context = ConfigCompilerContext::GetContext();
417 item = context->GetItem("Service", name);
419 /* ignore already active objects while we're in the compiler
420 * context and linking to existing items is disabled. */
421 if (!item && (!context || (context->GetFlags() & CompilerLinkExisting)))
422 item = ConfigItem::GetObject("Service", name);
425 ConfigCompilerContext::GetContext()->AddError(false, "Validation failed for " +
426 location + ": Template '" + name + "' not found.");
431 task->FinishResult(Empty);
434 Service::Ptr Host::GetServiceByShortName(const Value& name) const
436 if (name.IsScalar()) {
438 boost::mutex::scoped_lock lock(m_ServiceMutex);
440 map<String, Service::WeakPtr>& services = m_ServicesCache[GetName()];
441 map<String, Service::WeakPtr>::iterator it = services.find(name);
443 if (it != services.end()) {
444 Service::Ptr service = it->second.lock();
450 return Service::Ptr();
451 } else if (name.IsObjectType<Dictionary>()) {
452 Dictionary::Ptr dict = name;
455 ASSERT(dict->IsSealed());
457 return Service::GetByNamePair(dict->Get("host"), dict->Get("service"));
459 BOOST_THROW_EXCEPTION(invalid_argument("Host/Service name pair is invalid."));
463 set<Host::Ptr> Host::GetParentHosts(void) const
465 set<Host::Ptr> parents;
467 Dictionary::Ptr dependencies = GetHostDependencies();
470 ObjectLock olock(dependencies);
473 BOOST_FOREACH(tie(tuples::ignore, value), dependencies) {
474 if (value == GetName())
477 Host::Ptr host = GetByName(value);
482 parents.insert(host);
489 Service::Ptr Host::GetHostCheckService(void) const
491 String host_check = GetHostCheck();
493 if (host_check.IsEmpty())
494 return Service::Ptr();
496 return GetServiceByShortName(host_check);
499 set<Service::Ptr> Host::GetParentServices(void) const
501 set<Service::Ptr> parents;
503 Dictionary::Ptr dependencies = GetServiceDependencies();
506 ObjectLock olock(dependencies);
509 BOOST_FOREACH(tie(tuples::ignore, value), dependencies) {
510 parents.insert(GetServiceByShortName(value));
517 HostState Host::GetState(void) const
520 return HostUnreachable;
522 Service::Ptr hc = GetHostCheckService();
527 switch (hc->GetState()) {
536 StateType Host::GetStateType(void) const
538 Service::Ptr hc = GetHostCheckService();
541 return StateTypeHard;
543 return hc->GetStateType();
546 HostState Host::GetLastState(void) const
551 return HostUnreachable;
553 Service::Ptr hc = GetHostCheckService();
558 switch (hc->GetLastState()) {
567 StateType Host::GetLastStateType(void) const
569 Service::Ptr hc = GetHostCheckService();
572 return StateTypeHard;
574 return hc->GetLastStateType();
577 String Host::HostStateToString(HostState state)
584 case HostUnreachable:
585 return "UNREACHABLE";
591 Dictionary::Ptr Host::CalculateDynamicMacros(void) const
595 Dictionary::Ptr macros = boost::make_shared<Dictionary>();
598 ObjectLock olock(this);
600 macros->Set("HOSTNAME", GetName());
601 macros->Set("HOSTDISPLAYNAME", GetDisplayName());
602 macros->Set("HOSTALIAS", GetName());
607 Service::Ptr hc = GetHostCheckService();
610 ObjectLock olock(hc);
612 macros->Set("HOSTSTATE", HostStateToString(GetState()));
613 macros->Set("HOSTSTATEID", GetState());
614 macros->Set("HOSTSTATETYPE", Service::StateTypeToString(hc->GetStateType()));
615 macros->Set("HOSTATTEMPT", hc->GetCurrentCheckAttempt());
616 macros->Set("MAXHOSTATTEMPT", hc->GetMaxCheckAttempts());
618 macros->Set("LASTHOSTSTATE", HostStateToString(GetLastState()));
619 macros->Set("LASTHOSTSTATEID", GetLastState());
620 macros->Set("LASTHOSTSTATETYPE", Service::StateTypeToString(GetLastStateType()));
621 macros->Set("LASTHOSTSTATECHANGE", (long)hc->GetLastStateChange());
623 cr = hc->GetLastCheckResult();
627 macros->Set("HOSTLATENCY", Service::CalculateLatency(cr));
628 macros->Set("HOSTEXECUTIONTIME", Service::CalculateExecutionTime(cr));
630 macros->Set("HOSTOUTPUT", cr->Get("output"));
631 macros->Set("HOSTPERFDATA", cr->Get("performance_data_raw"));
633 macros->Set("LASTHOSTCHECK", (long)cr->Get("schedule_start"));