]> granicus.if.org Git - icinga2/blob - plugins/check_nscp_api.cpp
Always reset Boost beast buffer in HttpServerConnection#ProcessMessages
[icinga2] / plugins / check_nscp_api.cpp
1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
2
3 #include "icinga-version.h" /* include VERSION */
4
5 // ensure to include base first
6 #include "base/i2-base.hpp"
7 #include "base/application.hpp"
8 #include "base/json.hpp"
9 #include "base/string.hpp"
10 #include "base/logger.hpp"
11 #include "base/exception.hpp"
12 #include "base/utility.hpp"
13 #include "base/defer.hpp"
14 #include "base/io-engine.hpp"
15 #include "base/stream.hpp"
16 #include "base/tcpsocket.hpp" /* include global icinga::Connect */
17 #include "base/tlsstream.hpp"
18 #include "base/base64.hpp"
19 #include "remote/url.hpp"
20 #include <remote/url-characters.hpp>
21 #include <boost/program_options.hpp>
22 #include <boost/algorithm/string/split.hpp>
23 #include <boost/range/algorithm/remove_if.hpp>
24 #include <boost/asio/buffer.hpp>
25 #include <boost/asio/ssl/context.hpp>
26 #include <boost/beast.hpp>
27 #include <cstddef>
28 #include <cstring>
29 #include <iostream>
30
31 using namespace icinga;
32 namespace po = boost::program_options;
33
34 static bool l_Debug;
35
36 /**
37  * Prints an Icinga plugin API compliant output, including error handling.
38  *
39  * @param result
40  *
41  * @return Status code for exit()
42  */
43 static int FormatOutput(const Dictionary::Ptr& result)
44 {
45         if (!result) {
46                 std::cerr << "UNKNOWN: No data received.\n";
47                 return 3;
48         }
49
50         if (l_Debug)
51                 std::cout << "\tJSON Body:\n" << result->ToString() << '\n';
52
53         Array::Ptr payloads = result->Get("payload");
54         if (!payloads) {
55                 std::cerr << "UNKNOWN: Answer format error: Answer is missing 'payload'.\n";
56                 return 3;
57         }
58
59         if (payloads->GetLength() == 0) {
60                 std::cerr << "UNKNOWN: Answer format error: 'payload' was empty.\n";
61                 return 3;
62         }
63
64         if (payloads->GetLength() > 1) {
65                 std::cerr << "UNKNOWN: Answer format error: Multiple payloads are not supported.";
66                 return 3;
67         }
68
69         Dictionary::Ptr payload;
70
71         try {
72                 payload = payloads->Get(0);
73         } catch (const std::exception&) {
74                 std::cerr << "UNKNOWN: Answer format error: 'payload' was not a Dictionary.\n";
75                 return 3;
76         }
77
78         Array::Ptr lines;
79
80         try {
81                 lines = payload->Get("lines");
82         } catch (const std::exception&) {
83                 std::cerr << "UNKNOWN: Answer format error: 'payload' is missing 'lines'.\n";
84                 return 3;
85         }
86
87         if (!lines) {
88                 std::cerr << "UNKNOWN: Answer format error: 'lines' is Null.\n";
89                 return 3;
90         }
91
92         std::stringstream ssout;
93
94         ObjectLock olock(lines);
95
96         for (const Value& vline : lines) {
97                 Dictionary::Ptr line;
98
99                 try {
100                         line = vline;
101                 } catch (const std::exception&) {
102                         std::cerr << "UNKNOWN: Answer format error: 'lines' entry was not a Dictionary.\n";
103                         return 3;
104                 }
105
106                 if (!line) {
107                         std::cerr << "UNKNOWN: Answer format error: 'lines' entry was Null.\n";
108                         return 3;
109                 }
110
111                 ssout << payload->Get("command") << ' ' << line->Get("message") << " | ";
112
113                 if (!line->Contains("perf")) {
114                         ssout << '\n';
115                         break;
116                 }
117
118                 Array::Ptr perfs = line->Get("perf");
119
120                 ObjectLock olock(perfs);
121
122                 for (const Dictionary::Ptr& perf : perfs) {
123                         ssout << "'" << perf->Get("alias") << "'=";
124
125                         Dictionary::Ptr values = perf->Get("float_value");
126
127                         if (perf->Contains("int_value"))
128                                 values = perf->Get("int_value");
129
130                         ssout << values->Get("value") << values->Get("unit") << ';' << values->Get("warning") << ';' << values->Get("critical");
131
132                         if (values->Contains("minimum") || values->Contains("maximum")) {
133                                 ssout << ';';
134
135                                 if (values->Contains("minimum"))
136                                         ssout << values->Get("minimum");
137
138                                 if (values->Contains("maximum"))
139                                         ssout << ';' << values->Get("maximum");
140                         }
141
142                         ssout << ' ';
143                 }
144
145                 ssout << '\n';
146         }
147
148         std::map<String, unsigned int> stateMap = {
149                 { "OK", 0 },
150                 { "WARNING", 1},
151                 { "CRITICAL", 2},
152                 { "UNKNOWN", 3}
153         };
154
155         String state = static_cast<String>(payload->Get("result")).ToUpper();
156
157         auto it = stateMap.find(state);
158
159         if (it == stateMap.end()) {
160                 std::cerr << "UNKNOWN Answer format error: 'result' was not a known state.\n";
161                 return 3;
162         }
163
164         std::cout << ssout.rdbuf();
165
166         return it->second;
167 }
168
169 /**
170  * Connects to host:port and performs a TLS shandshake
171  *
172  * @param host To connect to.
173  * @param port To connect to.
174  *
175  * @returns AsioTlsStream pointer for future HTTP connections.
176  */
177 static std::shared_ptr<AsioTlsStream> Connect(const String& host, const String& port)
178 {
179         std::shared_ptr<boost::asio::ssl::context> sslContext;
180
181         try {
182                 sslContext = MakeAsioSslContext(Empty, Empty, Empty); //TODO: Add support for cert, key, ca parameters
183         } catch(const std::exception& ex) {
184                 Log(LogCritical, "DebugConsole")
185                         << "Cannot make SSL context: " << ex.what();
186                 throw;
187         }
188
189         std::shared_ptr<AsioTlsStream> stream = std::make_shared<AsioTlsStream>(IoEngine::Get().GetIoService(), *sslContext, host);
190
191         try {
192                 icinga::Connect(stream->lowest_layer(), host, port);
193         } catch (const std::exception& ex) {
194                 Log(LogWarning, "DebugConsole")
195                         << "Cannot connect to REST API on host '" << host << "' port '" << port << "': " << ex.what();
196                 throw;
197         }
198
199         auto& tlsStream (stream->next_layer());
200
201         try {
202                 tlsStream.handshake(tlsStream.client);
203         } catch (const std::exception& ex) {
204                 Log(LogWarning, "DebugConsole")
205                         << "TLS handshake with host '" << host << "' failed: " << ex.what();
206                 throw;
207         }
208
209         return std::move(stream);
210 }
211
212 static const char l_ReasonToInject[2] = {' ', 'X'};
213
214 template<class MutableBufferSequence>
215 static inline
216 boost::asio::mutable_buffer GetFirstNonZeroBuffer(const MutableBufferSequence& mbs)
217 {
218         namespace asio = boost::asio;
219
220         auto end (asio::buffer_sequence_end(mbs));
221
222         for (auto current (asio::buffer_sequence_begin(mbs)); current != end; ++current) {
223                 asio::mutable_buffer buf (*current);
224
225                 if (buf.size() > 0u) {
226                         return std::move(buf);
227                 }
228         }
229
230         return {};
231 }
232
233 /**
234  * Workaround for <https://github.com/mickem/nscp/issues/610>.
235  */
236 template<class SyncReadStream>
237 class HttpResponseReasonInjector
238 {
239 public:
240         inline HttpResponseReasonInjector(SyncReadStream& stream)
241                 : m_Stream(stream), m_ReasonHasBeenInjected(false), m_StashedData(nullptr)
242         {
243         }
244
245         HttpResponseReasonInjector(const HttpResponseReasonInjector&) = delete;
246         HttpResponseReasonInjector(HttpResponseReasonInjector&&) = delete;
247         HttpResponseReasonInjector& operator=(const HttpResponseReasonInjector&) = delete;
248         HttpResponseReasonInjector& operator=(HttpResponseReasonInjector&&) = delete;
249
250         template<class MutableBufferSequence>
251         size_t read_some(const MutableBufferSequence& mbs)
252         {
253                 boost::system::error_code ec;
254                 size_t amount = read_some(mbs, ec);
255
256                 if (ec) {
257                         throw boost::system::system_error(ec);
258                 }
259
260                 return amount;
261         }
262
263         template<class MutableBufferSequence>
264         size_t read_some(const MutableBufferSequence& mbs, boost::system::error_code& ec)
265         {
266                 auto mb (GetFirstNonZeroBuffer(mbs));
267
268                 if (m_StashedData) {
269                         size_t amount = 0;
270                         auto end ((char*)mb.data() + mb.size());
271
272                         for (auto current ((char*)mb.data()); current < end; ++current) {
273                                 *current = *m_StashedData;
274
275                                 ++m_StashedData;
276                                 ++amount;
277
278                                 if (m_StashedData == (char*)m_StashedDataBuf + (sizeof(m_StashedDataBuf) / sizeof(m_StashedDataBuf[0]))) {
279                                         m_StashedData = nullptr;
280                                         break;
281                                 }
282                         }
283
284                         return amount;
285                 }
286
287                 size_t amount = m_Stream.read_some(mb, ec);
288
289                 if (!ec && !m_ReasonHasBeenInjected) {
290                         auto end ((char*)mb.data() + amount);
291
292                         for (auto current ((char*)mb.data()); current < end; ++current) {
293                                 if (*current == '\r') {
294                                         auto last (end - 1);
295
296                                         for (size_t i = sizeof(l_ReasonToInject) / sizeof(l_ReasonToInject[0]); i;) {
297                                                 m_StashedDataBuf[--i] = *last;
298
299                                                 if (last > current) {
300                                                         memmove(current + 1, current, last - current);
301                                                 }
302
303                                                 *current = l_ReasonToInject[i];
304                                         }
305
306                                         m_ReasonHasBeenInjected = true;
307                                         m_StashedData = m_StashedDataBuf;
308
309                                         break;
310                                 }
311                         }
312                 }
313
314                 return amount;
315         }
316
317 private:
318         SyncReadStream& m_Stream;
319         bool m_ReasonHasBeenInjected;
320         char m_StashedDataBuf[sizeof(l_ReasonToInject) / sizeof(l_ReasonToInject[0])];
321         char* m_StashedData;
322 };
323
324 /**
325  * Queries the given endpoint and host:port and retrieves data.
326  *
327  * @param host To connect to.
328  * @param port To connect to.
329  * @param password For auth header (required).
330  * @param endpoint Caller must construct the full endpoint including the command query.
331  *
332  * @return Dictionary de-serialized from JSON data.
333  */
334
335 static Dictionary::Ptr FetchData(const String& host, const String& port, const String& password,
336         const String& endpoint)
337 {
338         namespace beast = boost::beast;
339         namespace http = beast::http;
340
341         std::shared_ptr<AsioTlsStream> tlsStream;
342
343         try {
344                 tlsStream = Connect(host, port);
345         } catch (const std::exception& ex) {
346                 std::cerr << "Connection error: " << ex.what();
347                 throw ex;
348         }
349
350         Url::Ptr url;
351
352         try {
353                 url = new Url(endpoint);
354         } catch (const std::exception& ex) {
355                 std::cerr << "URL error: " << ex.what();
356                 throw ex;
357         }
358
359         url->SetScheme("https");
360         url->SetHost(host);
361         url->SetPort(port);
362
363         // NSClient++ uses `time=1m&time=5m` instead of `time[]=1m&time[]=5m`
364         url->SetArrayFormatUseBrackets(false);
365
366         http::request<http::string_body> request (http::verb::get, std::string(url->Format(true)), 10);
367
368         request.set(http::field::user_agent, "Icinga/check_nscp_api/" + String(VERSION));
369         request.set(http::field::host, host + ":" + port);
370
371         request.set(http::field::accept, "application/json");
372         request.set("password", password);
373
374         if (l_Debug) {
375                 std::cout << "Sending request to " << url->Format(false, false) << "'.\n";
376         }
377
378         try {
379                 http::write(*tlsStream, request);
380                 tlsStream->flush();
381         } catch (const std::exception& ex) {
382                 std::cerr << "Cannot write HTTP request to REST API at URL '" << url->Format(false, false) << "': " << ex.what();
383                 throw ex;
384         }
385
386         beast::flat_buffer buffer;
387         http::parser<false, http::string_body> p;
388
389         try {
390                 HttpResponseReasonInjector<decltype(*tlsStream)> reasonInjector (*tlsStream);
391                 http::read(reasonInjector, buffer, p);
392         } catch (const std::exception &ex) {
393                 BOOST_THROW_EXCEPTION(ScriptError(String("Error reading HTTP response data: ") + ex.what()));
394         }
395
396         String body (std::move(p.get().body()));
397
398         if (l_Debug)
399                 std::cout << "Received body from NSCP: '" << body << "'." << std::endl;
400
401         // Add some rudimentary error handling.
402         if (body.IsEmpty()) {
403                 String message = "No body received. Ensure that connection parameters are good and check the NSCP logs.";
404                 BOOST_THROW_EXCEPTION(ScriptError(message));
405         }
406
407         Dictionary::Ptr jsonResponse;
408
409         try {
410                 jsonResponse = JsonDecode(body);
411         } catch (const std::exception& ex) {
412                 String message = "Cannot parse JSON response body '" + body + "', error: " + ex.what();
413                 BOOST_THROW_EXCEPTION(ScriptError(message));
414         }
415
416         return jsonResponse;
417 }
418
419 /**
420  * Main function
421  *
422  * @param argc
423  * @param argv
424  * @return exit code
425  */
426 int main(int argc, char **argv)
427 {
428         po::variables_map vm;
429         po::options_description desc("Options");
430
431         desc.add_options()
432                 ("help,h", "Print usage message and exit")
433                 ("version,V", "Print version and exit")
434                 ("debug,d", "Verbose/Debug output")
435                 ("host,H", po::value<std::string>()->required(), "REQUIRED: NSCP API Host")
436                 ("port,P", po::value<std::string>()->default_value("8443"), "NSCP API Port (Default: 8443)")
437                 ("password", po::value<std::string>()->required(), "REQUIRED: NSCP API Password")
438                 ("query,q", po::value<std::string>()->required(), "REQUIRED: NSCP API Query endpoint")
439                 ("arguments,a", po::value<std::vector<std::string>>()->multitoken(), "NSCP API Query arguments for the endpoint");
440
441         po::command_line_parser parser(argc, argv);
442
443         try {
444                 po::store(
445                         parser
446                         .options(desc)
447                         .style(
448                                 po::command_line_style::unix_style |
449                                 po::command_line_style::allow_long_disguise)
450                         .run(),
451                         vm);
452
453                 if (vm.count("version")) {
454                         std::cout << "Version: " << VERSION << '\n';
455                         Application::Exit(0);
456                 }
457
458                 if (vm.count("help")) {
459                         std::cout << argv[0] << " Help\n\tVersion: " << VERSION << '\n';
460                         std::cout << "check_nscp_api is a program used to query the NSClient++ API.\n";
461                         std::cout << desc;
462                         std::cout << "For detailed information on possible queries and their arguments refer to the NSClient++ documentation.\n";
463                         Application::Exit(0);
464                 }
465
466                 vm.notify();
467         } catch (const std::exception& e) {
468                 std::cout << e.what() << '\n' << desc << '\n';
469                 Application::Exit(3);
470         }
471
472         l_Debug = vm.count("debug") > 0;
473
474         // Initialize logger
475         if (l_Debug)
476                 Logger::SetConsoleLogSeverity(LogDebug);
477         else
478                 Logger::SetConsoleLogSeverity(LogWarning);
479
480         // Create the URL string and escape certain characters since Url() follows RFC 3986
481         String endpoint = "/query/" + vm["query"].as<std::string>();
482         if (!vm.count("arguments"))
483                 endpoint += '/';
484         else {
485                 endpoint += '?';
486                 for (const String& argument : vm["arguments"].as<std::vector<std::string>>()) {
487                         String::SizeType pos = argument.FindFirstOf("=");
488                         if (pos == String::NPos)
489                                 endpoint += Utility::EscapeString(argument, ACQUERY_ENCODE, false);
490                         else {
491                                 String key = argument.SubStr(0, pos);
492                                 String val = argument.SubStr(pos + 1);
493                                 endpoint += Utility::EscapeString(key, ACQUERY_ENCODE, false) + "=" + Utility::EscapeString(val, ACQUERY_ENCODE, false);
494                         }
495                         endpoint += '&';
496                 }
497         }
498
499         Dictionary::Ptr result;
500
501         try {
502                 result = FetchData(vm["host"].as<std::string>(), vm["port"].as<std::string>(),
503                    vm["password"].as<std::string>(), endpoint);
504         } catch (const std::exception& ex) {
505                 std::cerr << "UNKNOWN - " << ex.what();
506                 exit(3);
507         }
508
509         // Application::Exit() is the clean way to exit after calling InitializeBase()
510         Application::Exit(FormatOutput(result));
511         return 255;
512 }