1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
3 #include "icinga-version.h" /* include VERSION */
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>
31 using namespace icinga;
32 namespace po = boost::program_options;
37 * Prints an Icinga plugin API compliant output, including error handling.
41 * @return Status code for exit()
43 static int FormatOutput(const Dictionary::Ptr& result)
46 std::cerr << "UNKNOWN: No data received.\n";
51 std::cout << "\tJSON Body:\n" << result->ToString() << '\n';
53 Array::Ptr payloads = result->Get("payload");
55 std::cerr << "UNKNOWN: Answer format error: Answer is missing 'payload'.\n";
59 if (payloads->GetLength() == 0) {
60 std::cerr << "UNKNOWN: Answer format error: 'payload' was empty.\n";
64 if (payloads->GetLength() > 1) {
65 std::cerr << "UNKNOWN: Answer format error: Multiple payloads are not supported.";
69 Dictionary::Ptr payload;
72 payload = payloads->Get(0);
73 } catch (const std::exception&) {
74 std::cerr << "UNKNOWN: Answer format error: 'payload' was not a Dictionary.\n";
81 lines = payload->Get("lines");
82 } catch (const std::exception&) {
83 std::cerr << "UNKNOWN: Answer format error: 'payload' is missing 'lines'.\n";
88 std::cerr << "UNKNOWN: Answer format error: 'lines' is Null.\n";
92 std::stringstream ssout;
94 ObjectLock olock(lines);
96 for (const Value& vline : lines) {
101 } catch (const std::exception&) {
102 std::cerr << "UNKNOWN: Answer format error: 'lines' entry was not a Dictionary.\n";
107 std::cerr << "UNKNOWN: Answer format error: 'lines' entry was Null.\n";
111 ssout << payload->Get("command") << ' ' << line->Get("message") << " | ";
113 if (!line->Contains("perf")) {
118 Array::Ptr perfs = line->Get("perf");
120 ObjectLock olock(perfs);
122 for (const Dictionary::Ptr& perf : perfs) {
123 ssout << "'" << perf->Get("alias") << "'=";
125 Dictionary::Ptr values = perf->Get("float_value");
127 if (perf->Contains("int_value"))
128 values = perf->Get("int_value");
130 ssout << values->Get("value") << values->Get("unit") << ';' << values->Get("warning") << ';' << values->Get("critical");
132 if (values->Contains("minimum") || values->Contains("maximum")) {
135 if (values->Contains("minimum"))
136 ssout << values->Get("minimum");
138 if (values->Contains("maximum"))
139 ssout << ';' << values->Get("maximum");
148 std::map<String, unsigned int> stateMap = {
155 String state = static_cast<String>(payload->Get("result")).ToUpper();
157 auto it = stateMap.find(state);
159 if (it == stateMap.end()) {
160 std::cerr << "UNKNOWN Answer format error: 'result' was not a known state.\n";
164 std::cout << ssout.rdbuf();
170 * Connects to host:port and performs a TLS shandshake
172 * @param host To connect to.
173 * @param port To connect to.
175 * @returns AsioTlsStream pointer for future HTTP connections.
177 static std::shared_ptr<AsioTlsStream> Connect(const String& host, const String& port)
179 std::shared_ptr<boost::asio::ssl::context> sslContext;
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();
189 std::shared_ptr<AsioTlsStream> stream = std::make_shared<AsioTlsStream>(IoEngine::Get().GetIoService(), *sslContext, host);
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();
199 auto& tlsStream (stream->next_layer());
202 tlsStream.handshake(tlsStream.client);
203 } catch (const std::exception& ex) {
204 Log(LogWarning, "DebugConsole")
205 << "TLS handshake with host '" << host << "' failed: " << ex.what();
209 return std::move(stream);
212 static const char l_ReasonToInject[2] = {' ', 'X'};
214 template<class MutableBufferSequence>
216 boost::asio::mutable_buffer GetFirstNonZeroBuffer(const MutableBufferSequence& mbs)
218 namespace asio = boost::asio;
220 auto end (asio::buffer_sequence_end(mbs));
222 for (auto current (asio::buffer_sequence_begin(mbs)); current != end; ++current) {
223 asio::mutable_buffer buf (*current);
225 if (buf.size() > 0u) {
226 return std::move(buf);
234 * Workaround for <https://github.com/mickem/nscp/issues/610>.
236 template<class SyncReadStream>
237 class HttpResponseReasonInjector
240 inline HttpResponseReasonInjector(SyncReadStream& stream)
241 : m_Stream(stream), m_ReasonHasBeenInjected(false), m_StashedData(nullptr)
245 HttpResponseReasonInjector(const HttpResponseReasonInjector&) = delete;
246 HttpResponseReasonInjector(HttpResponseReasonInjector&&) = delete;
247 HttpResponseReasonInjector& operator=(const HttpResponseReasonInjector&) = delete;
248 HttpResponseReasonInjector& operator=(HttpResponseReasonInjector&&) = delete;
250 template<class MutableBufferSequence>
251 size_t read_some(const MutableBufferSequence& mbs)
253 boost::system::error_code ec;
254 size_t amount = read_some(mbs, ec);
257 throw boost::system::system_error(ec);
263 template<class MutableBufferSequence>
264 size_t read_some(const MutableBufferSequence& mbs, boost::system::error_code& ec)
266 auto mb (GetFirstNonZeroBuffer(mbs));
270 auto end ((char*)mb.data() + mb.size());
272 for (auto current ((char*)mb.data()); current < end; ++current) {
273 *current = *m_StashedData;
278 if (m_StashedData == (char*)m_StashedDataBuf + (sizeof(m_StashedDataBuf) / sizeof(m_StashedDataBuf[0]))) {
279 m_StashedData = nullptr;
287 size_t amount = m_Stream.read_some(mb, ec);
289 if (!ec && !m_ReasonHasBeenInjected) {
290 auto end ((char*)mb.data() + amount);
292 for (auto current ((char*)mb.data()); current < end; ++current) {
293 if (*current == '\r') {
296 for (size_t i = sizeof(l_ReasonToInject) / sizeof(l_ReasonToInject[0]); i;) {
297 m_StashedDataBuf[--i] = *last;
299 if (last > current) {
300 memmove(current + 1, current, last - current);
303 *current = l_ReasonToInject[i];
306 m_ReasonHasBeenInjected = true;
307 m_StashedData = m_StashedDataBuf;
318 SyncReadStream& m_Stream;
319 bool m_ReasonHasBeenInjected;
320 char m_StashedDataBuf[sizeof(l_ReasonToInject) / sizeof(l_ReasonToInject[0])];
325 * Queries the given endpoint and host:port and retrieves data.
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.
332 * @return Dictionary de-serialized from JSON data.
335 static Dictionary::Ptr FetchData(const String& host, const String& port, const String& password,
336 const String& endpoint)
338 namespace beast = boost::beast;
339 namespace http = beast::http;
341 std::shared_ptr<AsioTlsStream> tlsStream;
344 tlsStream = Connect(host, port);
345 } catch (const std::exception& ex) {
346 std::cerr << "Connection error: " << ex.what();
353 url = new Url(endpoint);
354 } catch (const std::exception& ex) {
355 std::cerr << "URL error: " << ex.what();
359 url->SetScheme("https");
363 // NSClient++ uses `time=1m&time=5m` instead of `time[]=1m&time[]=5m`
364 url->SetArrayFormatUseBrackets(false);
366 http::request<http::string_body> request (http::verb::get, std::string(url->Format(true)), 10);
368 request.set(http::field::user_agent, "Icinga/check_nscp_api/" + String(VERSION));
369 request.set(http::field::host, host + ":" + port);
371 request.set(http::field::accept, "application/json");
372 request.set("password", password);
375 std::cout << "Sending request to " << url->Format(false, false) << "'.\n";
379 http::write(*tlsStream, request);
381 } catch (const std::exception& ex) {
382 std::cerr << "Cannot write HTTP request to REST API at URL '" << url->Format(false, false) << "': " << ex.what();
386 beast::flat_buffer buffer;
387 http::parser<false, http::string_body> p;
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()));
396 String body (std::move(p.get().body()));
399 std::cout << "Received body from NSCP: '" << body << "'." << std::endl;
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));
407 Dictionary::Ptr jsonResponse;
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));
426 int main(int argc, char **argv)
428 po::variables_map vm;
429 po::options_description desc("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");
441 po::command_line_parser parser(argc, argv);
448 po::command_line_style::unix_style |
449 po::command_line_style::allow_long_disguise)
453 if (vm.count("version")) {
454 std::cout << "Version: " << VERSION << '\n';
455 Application::Exit(0);
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";
462 std::cout << "For detailed information on possible queries and their arguments refer to the NSClient++ documentation.\n";
463 Application::Exit(0);
467 } catch (const std::exception& e) {
468 std::cout << e.what() << '\n' << desc << '\n';
469 Application::Exit(3);
472 l_Debug = vm.count("debug") > 0;
476 Logger::SetConsoleLogSeverity(LogDebug);
478 Logger::SetConsoleLogSeverity(LogWarning);
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"))
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);
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);
499 Dictionary::Ptr result;
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();
509 // Application::Exit() is the clean way to exit after calling InitializeBase()
510 Application::Exit(FormatOutput(result));