summaryrefslogtreecommitdiffstats
path: root/lib/icinga/clusterevents-check.cpp
blob: 40325b4c0e4acfef9eee24225e34271b22ea18e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */

#include "icinga/clusterevents.hpp"
#include "icinga/icingaapplication.hpp"
#include "remote/apilistener.hpp"
#include "base/configuration.hpp"
#include "base/defer.hpp"
#include "base/serializer.hpp"
#include "base/exception.hpp"
#include <boost/thread/once.hpp>
#include <thread>

using namespace icinga;

std::mutex ClusterEvents::m_Mutex;
std::deque<std::function<void ()>> ClusterEvents::m_CheckRequestQueue;
bool ClusterEvents::m_CheckSchedulerRunning;
int ClusterEvents::m_ChecksExecutedDuringInterval;
int ClusterEvents::m_ChecksDroppedDuringInterval;
Timer::Ptr ClusterEvents::m_LogTimer;

void ClusterEvents::RemoteCheckThreadProc()
{
	Utility::SetThreadName("Remote Check Scheduler");

	int maxConcurrentChecks = IcingaApplication::GetInstance()->GetMaxConcurrentChecks();

	std::unique_lock<std::mutex> lock(m_Mutex);

	for(;;) {
		if (m_CheckRequestQueue.empty())
			break;

		lock.unlock();
		Checkable::AquirePendingCheckSlot(maxConcurrentChecks);
		lock.lock();

		auto callback = m_CheckRequestQueue.front();
		m_CheckRequestQueue.pop_front();
		m_ChecksExecutedDuringInterval++;
		lock.unlock();

		callback();
		Checkable::DecreasePendingChecks();

		lock.lock();
	}

	m_CheckSchedulerRunning = false;
}

void ClusterEvents::EnqueueCheck(const MessageOrigin::Ptr& origin, const Dictionary::Ptr& params)
{
	static boost::once_flag once = BOOST_ONCE_INIT;

	boost::call_once(once, []() {
		m_LogTimer = Timer::Create();
		m_LogTimer->SetInterval(10);
		m_LogTimer->OnTimerExpired.connect([](const Timer * const&) { LogRemoteCheckQueueInformation(); });
		m_LogTimer->Start();
	});

	std::unique_lock<std::mutex> lock(m_Mutex);

	if (m_CheckRequestQueue.size() >= 25000) {
		m_ChecksDroppedDuringInterval++;
		return;
	}

	m_CheckRequestQueue.emplace_back([origin, params]() { ExecuteCheckFromQueue(origin, params); });

	if (!m_CheckSchedulerRunning) {
		std::thread t(ClusterEvents::RemoteCheckThreadProc);
		t.detach();
		m_CheckSchedulerRunning = true;
	}
}

static void SendEventExecutedCommand(const Dictionary::Ptr& params, long exitStatus, const String& output,
	double start, double end, const ApiListener::Ptr& listener, const MessageOrigin::Ptr& origin,
	const Endpoint::Ptr& sourceEndpoint)
{
	Dictionary::Ptr executedParams = new Dictionary();
	executedParams->Set("execution", params->Get("source"));
	executedParams->Set("host", params->Get("host"));

	if (params->Contains("service"))
		executedParams->Set("service", params->Get("service"));

	executedParams->Set("exit", exitStatus);
	executedParams->Set("output", output);
	executedParams->Set("start", start);
	executedParams->Set("end", end);

	if (origin->IsLocal()) {
		ClusterEvents::ExecutedCommandAPIHandler(origin, executedParams);
	} else {
		Dictionary::Ptr executedMessage = new Dictionary();
		executedMessage->Set("jsonrpc", "2.0");
		executedMessage->Set("method", "event::ExecutedCommand");
		executedMessage->Set("params", executedParams);

		listener->SyncSendMessage(sourceEndpoint, executedMessage);
	}
}

void ClusterEvents::ExecuteCheckFromQueue(const MessageOrigin::Ptr& origin, const Dictionary::Ptr& params) {

	Endpoint::Ptr sourceEndpoint;

	if (origin->FromClient) {
		sourceEndpoint = origin->FromClient->GetEndpoint();
	} else if (origin->IsLocal()){
		sourceEndpoint = Endpoint::GetLocalEndpoint();
	}

	if (!sourceEndpoint || (origin->FromZone && !Zone::GetLocalZone()->IsChildOf(origin->FromZone))) {
		Log(LogNotice, "ClusterEvents")
			<< "Discarding 'execute command' message from '" << origin->FromClient->GetIdentity() << "': Invalid endpoint origin (client not allowed).";
		return;
	}

	ApiListener::Ptr listener = ApiListener::GetInstance();

	if (!listener) {
		Log(LogCritical, "ApiListener") << "No instance available.";
		return;
	}

	Defer resetExecuteCommandProcessFinishedHandler ([]() {
		Checkable::ExecuteCommandProcessFinishedHandler = nullptr;
	});

	if (params->Contains("source")) {
		String uuid = params->Get("source");

		String checkableName = params->Get("host");

		if (params->Contains("service"))
			checkableName += "!" + params->Get("service");

		/* Check deadline */
		double deadline = params->Get("deadline");

		if (Utility::GetTime() > deadline) {
			Log(LogNotice, "ApiListener")
				<< "Discarding 'ExecuteCheckFromQueue' event for checkable '" << checkableName
				<< "' from '" << origin->FromClient->GetIdentity() << "': Deadline has expired.";
			return;
		}

		Checkable::ExecuteCommandProcessFinishedHandler = [checkableName, listener, sourceEndpoint, origin, params] (const Value& commandLine, const ProcessResult& pr) {
			if (params->Get("command_type") == "check_command") {
				Checkable::CurrentConcurrentChecks.fetch_sub(1);
				Checkable::DecreasePendingChecks();
			}

			if (pr.ExitStatus > 3) {
				Process::Arguments parguments = Process::PrepareCommand(commandLine);
				Log(LogWarning, "ApiListener")
					<< "Command for object '" << checkableName << "' (PID: " << pr.PID
					<< ", arguments: " << Process::PrettyPrintArguments(parguments) << ") terminated with exit code "
					<< pr.ExitStatus << ", output: " << pr.Output;
			}

			SendEventExecutedCommand(params, pr.ExitStatus, pr.Output, pr.ExecutionStart, pr.ExecutionEnd, listener,
									origin, sourceEndpoint);
		};
	}

	if (!listener->GetAcceptCommands() && !origin->IsLocal()) {
		Log(LogWarning, "ApiListener")
			<< "Ignoring command. '" << listener->GetName() << "' does not accept commands.";

		String output = "Endpoint '" + Endpoint::GetLocalEndpoint()->GetName() + "' does not accept commands.";

		if (params->Contains("source")) {
			double now = Utility::GetTime();
			SendEventExecutedCommand(params, 126, output, now, now, listener, origin, sourceEndpoint);
		} else {
			Host::Ptr host = new Host();
			Dictionary::Ptr attrs = new Dictionary();

			attrs->Set("__name", params->Get("host"));
			attrs->Set("type", "Host");
			attrs->Set("enable_active_checks", false);

			Deserialize(host, attrs, false, FAConfig);

			if (params->Contains("service"))
				host->SetExtension("agent_service_name", params->Get("service"));

			CheckResult::Ptr cr = new CheckResult();
			cr->SetState(ServiceUnknown);
			cr->SetOutput(output);

			Dictionary::Ptr message = MakeCheckResultMessage(host, cr);
			listener->SyncSendMessage(sourceEndpoint, message);
		}

		return;
	}

	/* use a virtual host object for executing the command */
	Host::Ptr host = new Host();
	Dictionary::Ptr attrs = new Dictionary();

	attrs->Set("__name", params->Get("host"));
	attrs->Set("type", "Host");

	/*
	 * Override the check timeout if the parent caller provided the value. Compatible with older versions not
	 * passing this inside the cluster message.
	 * This happens with host/service command_endpoint agents and the 'check_timeout' attribute being specified.
	 */
	if (params->Contains("check_timeout"))
		attrs->Set("check_timeout", params->Get("check_timeout"));

	Deserialize(host, attrs, false, FAConfig);

	if (params->Contains("service"))
		host->SetExtension("agent_service_name", params->Get("service"));

	String command = params->Get("command");
	String command_type = params->Get("command_type");

	if (command_type == "check_command") {
		if (!CheckCommand::GetByName(command)) {
			ServiceState state = ServiceUnknown;
			String output = "Check command '" + command + "' does not exist.";
			double now = Utility::GetTime();
			
			if (params->Contains("source")) {
				SendEventExecutedCommand(params, state, output, now, now, listener, origin, sourceEndpoint);
			} else {
				CheckResult::Ptr cr = new CheckResult();
				cr->SetState(state);
				cr->SetOutput(output);
				Dictionary::Ptr message = MakeCheckResultMessage(host, cr);
				listener->SyncSendMessage(sourceEndpoint, message);
			}

			return;
		}
	} else if (command_type == "event_command") {
		if (!EventCommand::GetByName(command)) {
			String output = "Event command '" + command + "' does not exist.";
			Log(LogWarning, "ClusterEvents") << output;

			if (params->Contains("source")) {
				double now = Utility::GetTime();
				SendEventExecutedCommand(params, ServiceUnknown, output, now, now, listener, origin, sourceEndpoint);
			}

			return;
		}
	} else if (command_type == "notification_command") {
		if (!NotificationCommand::GetByName(command)) {
			String output = "Notification command '" + command + "' does not exist.";
			Log(LogWarning, "ClusterEvents") << output;

			if (params->Contains("source")) {
				double now = Utility::GetTime();
				SendEventExecutedCommand(params, ServiceUnknown, output, now, now, listener, origin, sourceEndpoint);
			}

			return;
		}
	}

	attrs->Set(command_type, params->Get("command"));
	attrs->Set("command_endpoint", sourceEndpoint->GetName());

	Deserialize(host, attrs, false, FAConfig);

	host->SetExtension("agent_check", true);

	Dictionary::Ptr macros = params->Get("macros");

	if (command_type == "check_command") {
		try {
			host->ExecuteRemoteCheck(macros);
		} catch (const std::exception& ex) {
			String output = "Exception occurred while checking '" + host->GetName() + "': " + DiagnosticInformation(ex);
			ServiceState state = ServiceUnknown;
			double now = Utility::GetTime();

			if (params->Contains("source")) {
				SendEventExecutedCommand(params, state, output, now, now, listener, origin, sourceEndpoint);
			} else {
				CheckResult::Ptr cr = new CheckResult();
				cr->SetState(state);
				cr->SetOutput(output);
				cr->SetScheduleStart(now);
				cr->SetScheduleEnd(now);
				cr->SetExecutionStart(now);
				cr->SetExecutionEnd(now);

				Dictionary::Ptr message = MakeCheckResultMessage(host, cr);
				listener->SyncSendMessage(sourceEndpoint, message);
			}

			Log(LogCritical, "checker", output);
		}
	} else if (command_type == "event_command") {
		try {
			host->ExecuteEventHandler(macros, true);
		} catch (const std::exception& ex) {
			if (params->Contains("source")) {
				String output = "Exception occurred while executing event command '" + command + "' for '" +
					host->GetName() + "': " + DiagnosticInformation(ex);

				double now = Utility::GetTime();
				SendEventExecutedCommand(params, ServiceUnknown, output, now, now, listener, origin, sourceEndpoint);
			} else {
				throw;
			}
		}
	} else if (command_type == "notification_command" && params->Contains("source")) {
		/* Get user */
		User::Ptr user = new User();
		Dictionary::Ptr attrs = new Dictionary();
		attrs->Set("__name", params->Get("user"));
		attrs->Set("type", User::GetTypeName());

		Deserialize(user, attrs, false, FAConfig);

		/* Get notification */
		Notification::Ptr notification = new Notification();
		attrs->Clear();
		attrs->Set("__name", params->Get("notification"));
		attrs->Set("type", Notification::GetTypeName());
		attrs->Set("command", command);

		Deserialize(notification, attrs, false, FAConfig);

		try {
			CheckResult::Ptr cr = new CheckResult();
			String author = macros->Get("notification_author");
			NotificationCommand::Ptr notificationCommand = NotificationCommand::GetByName(command);

			notificationCommand->Execute(notification, user, cr, NotificationType::NotificationCustom,
				author, "");
		} catch (const std::exception& ex) {
			String output = "Exception occurred during notification '" + notification->GetName()
				+ "' for checkable '" + notification->GetCheckable()->GetName()
				+ "' and user '" + user->GetName() + "' using command '" + command + "': "
				+ DiagnosticInformation(ex, false);
			double now = Utility::GetTime();
			SendEventExecutedCommand(params, ServiceUnknown, output, now, now, listener, origin, sourceEndpoint);
		}
	}
}

int ClusterEvents::GetCheckRequestQueueSize()
{
	return m_CheckRequestQueue.size();
}

void ClusterEvents::LogRemoteCheckQueueInformation() {
	if (m_ChecksDroppedDuringInterval > 0) {
		Log(LogCritical, "ClusterEvents")
			<< "Remote check queue ran out of slots. "
			<< m_ChecksDroppedDuringInterval << " checks dropped.";
		m_ChecksDroppedDuringInterval = 0;
	}

	if (m_ChecksExecutedDuringInterval == 0)
		return;

	Log(LogInformation, "RemoteCheckQueue")
		<< "items: " << m_CheckRequestQueue.size()
		<< ", rate: " << m_ChecksExecutedDuringInterval / 10 << "/s "
		<< "(" << m_ChecksExecutedDuringInterval * 6 << "/min "
		<< m_ChecksExecutedDuringInterval * 6 * 5 << "/5min "
		<< m_ChecksExecutedDuringInterval * 6 * 15 << "/15min" << ");";

	m_ChecksExecutedDuringInterval = 0;
}