-
Notifications
You must be signed in to change notification settings - Fork 479
/
Copy pathcheck_mkevents.cc
398 lines (355 loc) · 12.5 KB
/
check_mkevents.cc
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
// Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2
// This file is part of Checkmk (https://checkmk.com). It is subject to the
// terms and conditions defined in the file COPYING, which is part of this
// source code package.
// NOTE: We really need <sstream>, IWYU bug?
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/un.h>
#include <unistd.h>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
enum class State { ok = 0, warn = 1, crit = 2, unknown = 3 };
std::ostream &operator<<(std::ostream &os, const State &state) {
switch (state) {
case State::ok:
return os << "OK";
case State::warn:
return os << "WARN";
case State::crit:
return os << "CRIT";
case State::unknown:
return os << "UNKNOWN";
}
return os; // make compilers happy
}
void print_line(const std::string &output) {
// Make sure that plugin output does not contain a vertical bar. If that is
// the case then replace it with a Uniocode "Light vertical bar". Same as in
// Check_MK.
for (char i : output) {
if (i == '|') {
// \u2758 (utf-8 encoded light vertical bar)
std::cout << "\xe2\x94\x82"; // NOLINT
} else {
std::cout << i;
}
}
std::cout << std::endl;
}
[[noreturn]] void exit(State state) {
::exit(static_cast<int>(state));
}
[[noreturn]] void reply_and_exit(State state, const std::string &output) {
std::cout << state << " - ";
print_line(output);
exit(state);
}
[[noreturn]] void ioError(const std::string &message) {
reply_and_exit(State::unknown, message + " (" + strerror(errno) + ")");
}
[[noreturn]] void missingHeader(const std::string &header,
const std::string &query,
const std::stringstream &response) {
auto resp = response.str();
reply_and_exit(State::unknown,
"Event console answered with incorrect header (missing " + header +
")\nQuery was:\n" + query + "\nReceived " +
std::to_string(resp.size()) + " byte response:\n" + resp);
}
void usage() {
reply_and_exit(
State::unknown,
"Usage: check_mkevents [-s SOCKETPATH] [-H REMOTE:PORT] [-a] [-l|-L] HOST [APPLICATION]\n"
" -a do not take acknowledged events into account.\n"
" -l show last log message in summary/short output\n"
" -L show last log message in details/long output\n"
" HOST may be a hostname, and IP address or hostname/IP-address.");
}
std::string prepare_host_match_list(const char *s) {
const char *scan = s;
std::string result;
while (*scan != 0) {
if (*scan == '/') {
result += " ";
} else {
result += *scan;
}
scan++;
}
return result;
}
int main(int argc, char **argv) {
// Parse arguments
char *host = nullptr;
char *remote_host = nullptr;
char *application = nullptr;
bool ignore_acknowledged = false;
bool last_log_in_summary = false;
bool last_log_in_details = false;
std::string unixsocket_path;
int argc_count = argc;
for (int i = 1; i < argc; i++) {
if (i < argc + 1 && strcmp("-H", argv[i]) == 0) {
remote_host = argv[i + 1];
i++;
argc_count -= 2;
} else if (i < argc + 1 && strcmp("-s", argv[i]) == 0) {
unixsocket_path = argv[i + 1];
i++;
argc_count -= 2;
} else if (strcmp("-a", argv[i]) == 0) {
ignore_acknowledged = true;
argc_count--;
} else if (strcmp("-l", argv[i]) == 0) {
last_log_in_summary = true;
argc_count--;
} else if (strcmp("-L", argv[i]) == 0) {
last_log_in_details = true;
argc_count--;
} else if (argc_count > 2) {
host = argv[i];
application = argv[i + 1];
break;
} else if (argc_count > 1) {
host = argv[i];
break;
}
}
if (host == nullptr) {
usage();
}
int sock;
if (remote_host != nullptr) {
char *remote_hostaddress = strtok(remote_host, ":");
struct hostent *he = gethostbyname(remote_hostaddress);
if (he == nullptr) {
reply_and_exit(State::unknown, "Unable to resolve remote host address: " +
std::string(remote_hostaddress));
}
auto addr_list = reinterpret_cast<struct in_addr **>(he->h_addr_list);
std::string remote_hostipaddress;
for (int i = 0; addr_list[i] != nullptr; i++) {
remote_hostipaddress = std::string{inet_ntoa(*addr_list[i])};
}
char *port_str = strtok(nullptr, ":");
uint16_t remote_port = port_str != nullptr ? atoi(port_str) : 6558;
sock = ::socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
ioError("Cannot create client socket");
}
struct timeval tv;
tv.tv_sec = 10;
tv.tv_usec = 0;
if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv,
sizeof(struct timeval)) == -1) {
ioError("Cannot set socket reveive timeout");
}
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
inet_aton(remote_hostipaddress.c_str(), &addr.sin_addr);
addr.sin_port = htons(remote_port);
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
if (::connect(sock, reinterpret_cast<struct sockaddr *>(&addr),
sizeof(struct sockaddr_in)) == -1) {
ioError("Cannot connect to event console at " +
remote_hostipaddress + ":" + std::to_string(remote_port));
}
} else {
// Get omd environment
if (unixsocket_path.empty()) {
char *omd_path = getenv("OMD_ROOT");
if (omd_path == nullptr) {
reply_and_exit(State::unknown,
"OMD_ROOT is not set, no socket path is defined.");
}
unixsocket_path =
std::string(omd_path) + "/tmp/run/mkeventd/status";
}
sock = ::socket(PF_UNIX, SOCK_STREAM, 0);
if (sock == -1) {
ioError("Cannot create client socket");
}
struct timeval tv;
tv.tv_sec = 10;
tv.tv_usec = 0;
if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv,
sizeof(struct timeval)) == -1) {
ioError("Cannot set socket reveive timeout");
}
struct sockaddr_un addr {
.sun_family = AF_UNIX, .sun_path = ""
};
unixsocket_path.copy(&addr.sun_path[0], sizeof(addr.sun_path) - 1);
addr.sun_path[sizeof(addr.sun_path) - 1] = '\0';
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
if (::connect(sock, reinterpret_cast<struct sockaddr *>(&addr),
sizeof(addr)) == -1) {
ioError("Cannot connect to event daemon via UNIX socket " +
unixsocket_path);
}
}
// Create query message
std::string query_message;
query_message += "GET events\n";
query_message += "Columns: event_phase event_state event_text\n";
query_message += "Filter: event_host ";
if (strchr(host, '/') != nullptr) {
query_message += "in ";
query_message += prepare_host_match_list(host);
} else {
query_message += "=~ ";
query_message += host;
}
query_message += "\nFilter: event_phase in open ack\n";
query_message += "OutputFormat: plain\n";
if (application != nullptr) {
query_message += "Filter: event_application ~~ ";
query_message += application;
query_message += "\n";
}
// Send message
{
const char *buffer = query_message.c_str();
size_t bytes_to_write = query_message.size();
while (bytes_to_write > 0) {
ssize_t bytes_written = ::write(sock, buffer, bytes_to_write);
if (bytes_written == -1) {
ioError("Cannot send query to event console");
}
buffer += bytes_written;
bytes_to_write -= bytes_written;
}
if (shutdown(sock, SHUT_WR) == -1) {
ioError("Cannot shutdown socket to event console");
}
}
// Get response
std::stringstream response_stream;
while (true) {
char response_chunk[4096];
memset(response_chunk, 0, sizeof(response_chunk));
ssize_t bytes_read =
::read(sock, response_chunk, sizeof(response_chunk));
if (bytes_read == -1) {
if (errno != EINTR) {
ioError("Error while reading response");
}
} else if (bytes_read == 0) {
break;
} else {
for (int i = 0; i < bytes_read; i++) {
if (response_chunk[i] == 0) {
response_chunk[i] = ' ';
}
}
response_stream << std::string(response_chunk, bytes_read);
}
}
if (::close(sock) == -1) {
ioError("Error while closing connection");
}
// Start processing data
std::string line;
getline(response_stream, line);
std::stringstream linestream;
linestream << line;
// Get headers
std::string token;
int idx_event_phase = -1;
int idx_event_state = -1;
int idx_event_text = -1;
int current_index = 0;
std::vector<std::string> headers;
while (getline(linestream, token, '\t')) {
if (strcmp(token.c_str(), "event_phase") == 0) {
idx_event_phase = current_index;
} else if (strcmp(token.c_str(), "event_state") == 0) {
idx_event_state = current_index;
} else if (strcmp(token.c_str(), "event_text") == 0) {
idx_event_text = current_index;
}
headers.push_back(token);
current_index++;
}
// Basic header validation
if (idx_event_phase == -1) {
missingHeader("event_phase", query_message, response_stream);
}
if (idx_event_state == -1) {
missingHeader("event_state", query_message, response_stream);
}
if (idx_event_text == -1) {
missingHeader("event_text", query_message, response_stream);
}
// Get data
std::vector<std::vector<std::string> > data;
while (getline(response_stream, line)) {
if (line.size() < headers.size()) {
break; // broken / empty line
}
linestream.str("");
linestream.clear();
linestream << line;
std::vector<std::string> data_line;
bool has_data = false;
while (getline(linestream, token, '\t')) {
has_data = true;
data_line.push_back(token);
}
if (has_data) {
data.push_back(data_line);
}
}
// Generate output
std::string worst_row_event_text;
State worst_state = State::ok;
int count = 0;
int unhandled = 0;
for (auto &it : data) {
count++;
const char *p = it.at(idx_event_phase).c_str();
if (strcmp(p, "open") == 0 || !ignore_acknowledged) {
auto s = static_cast<State>(atoi(it.at(idx_event_state).c_str()));
if (s == State::unknown) {
if (worst_state < State::crit) {
worst_state = State::unknown;
worst_row_event_text = it.at(idx_event_text);
}
} else if (s >= worst_state) {
worst_state = s;
worst_row_event_text = it.at(idx_event_text);
}
}
if (strcmp(p, "open") == 0) {
unhandled++;
}
}
if (count == 0) {
std::string app =
application == nullptr ? "" : (std::string(application) + " on ");
reply_and_exit(State::ok, "no events for " + app + host);
}
std::cout << worst_state << " - ";
std::stringstream output;
output << count << " events (" << unhandled << " unacknowledged)";
if (!worst_row_event_text.empty() && last_log_in_summary) {
output << ", Last line: " << worst_row_event_text;
}
print_line(output.str());
if (!worst_row_event_text.empty() && last_log_in_details) {
print_line("Last line: " + worst_row_event_text);
}
exit(worst_state);
return 0; // never reached
}