1 /******************************************************************************
3 * Copyright (C) 2012-2017 Icinga Development Team (https://www.icinga.com/) *
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 #define VERSION "1.0.0"
22 #include "remote/httpclientconnection.hpp"
23 #include "remote/httprequest.hpp"
24 #include "remote/url-characters.hpp"
25 #include "base/application.hpp"
26 #include "base/json.hpp"
27 #include "base/string.hpp"
28 #include "base/exception.hpp"
29 #include <boost/program_options.hpp>
30 #include <boost/algorithm/string/split.hpp>
33 using namespace icinga;
34 namespace po = boost::program_options;
39 * This function is called by an 'HttpRequest' once the server answers. After doing a short check on the 'response' it
40 * decodes it to a Dictionary and then tells 'QueryEndpoint()' that it's done
42 static void ResultHttpCompletionCallback(const HttpRequest& request, HttpResponse& response, bool& ready,
43 boost::condition_variable& cv, boost::mutex& mtx, Dictionary::Ptr& result)
49 while ((count = response.ReadBody(buffer, sizeof(buffer))) > 0)
50 body += String(buffer, buffer + count);
53 std::cout << "Received answer\n"
54 << "\tHTTP code: " << response.StatusCode << "\n"
55 << "\tHTTP message: '" << response.StatusMessage << "'\n"
56 << "\tHTTP body: '" << body << "'.\n";
59 // Only try to decode the body if the 'HttpRequest' was successful
60 if (response.StatusCode != 200)
61 result = Dictionary::Ptr();
63 result = JsonDecode(body);
65 // Unlock our mutex, set ready and notify 'QueryEndpoint()'
66 boost::mutex::scoped_lock lock(mtx);
72 * This function takes all the information required to query an nscp instance on
73 * 'host':'port' with 'password'. The String 'endpoint' contains the specific
74 * query name and all the arguments formatted as an URL.
76 static Dictionary::Ptr QueryEndpoint(const String& host, const String& port, const String& password,
77 const String& endpoint)
79 HttpClientConnection::Ptr m_Connection = new HttpClientConnection(host, port, true);
83 boost::condition_variable cv;
85 Dictionary::Ptr result;
86 boost::shared_ptr<HttpRequest> req = m_Connection->NewRequest();
87 req->RequestMethod = "GET";
89 // Url() will call Utillity::UnescapeString() which will thrown an exception if it finds a lonely %
90 req->RequestUrl = new Url(endpoint);
91 req->AddHeader("password", password);
93 std::cout << "Sending request to 'https://" << host << ":" << port << req->RequestUrl->Format() << "'\n";
95 // Submits the request. The 'ResultHttpCompletionCallback' is called once the HttpRequest receives an answer,
96 // which then sets 'ready' to true
97 m_Connection->SubmitRequest(req, boost::bind(ResultHttpCompletionCallback, _1, _2,
98 boost::ref(ready), boost::ref(cv), boost::ref(mtx), boost::ref(result)));
100 // We need to spinlock here because our 'HttpRequest' works asynchronous
101 boost::mutex::scoped_lock lock(mtx);
108 catch (const std::exception& ex) {
109 // Exceptions should only happen in extreme edge cases we can't recover from
110 std::cout << "Caught exception: " << DiagnosticInformation(ex, false) << '\n';
111 return Dictionary::Ptr();
116 * Takes a Dictionary 'result' and constructs an icinga compliant output string.
117 * If 'result' is not in the expected format it returns 3 ("UNKNOWN") and prints an informative, icinga compliant,
120 static int FormatOutput(const Dictionary::Ptr& result)
123 std::cout << "UNKNOWN: No data received.\n";
128 std::cout << "\tJSON Body:\n" << result->ToString() << '\n';
130 Array::Ptr payloads = result->Get("payload");
132 std::cout << "UNKNOWN: Answer format error: Answer is missing 'payload'.\n";
136 if (payloads->GetLength() == 0) {
137 std::cout << "UNKNOWN: Answer format error: 'payload' was empty.\n";
141 if (payloads->GetLength() > 1) {
142 std::cout << "UNKNOWN: Answer format error: Multiple payloads are not supported.";
146 Dictionary::Ptr payload;
148 payload = payloads->Get(0);
149 } catch (const std::exception& ex) {
150 std::cout << "UNKNOWN: Answer format error: 'payload' was not a Dictionary.\n";
156 lines = payload->Get("lines");
157 } catch (const std::exception&) {
158 std::cout << "UNKNOWN: Answer format error: 'payload' is missing 'lines'.\n";
163 std::cout << "UNKNOWN: Answer format error: 'lines' is Null.\n";
167 std::stringstream ssout;
168 ObjectLock olock(lines);
170 for (const Value& vline : lines) {
171 Dictionary::Ptr line;
174 } catch (const std::exception& ex) {
175 std::cout << "UNKNOWN: Answer format error: 'lines' entry was not a Dictionary.\n";
179 std::cout << "UNKNOWN: Answer format error: 'lines' entry was Null.\n";
183 ssout << payload->Get("command") << ' ' << line->Get("message") << " | ";
185 if (!line->Contains("perf")) {
190 Array::Ptr perfs = line->Get("perf");
191 ObjectLock olock(perfs);
193 for (const Dictionary::Ptr& perf : perfs) {
194 ssout << "'" << perf->Get("alias") << "'=";
195 Dictionary::Ptr values = perf->Contains("int_value") ? perf->Get("int_value") : perf->Get("float_value");
196 ssout << values->Get("value") << values->Get("unit") << ';' << values->Get("warning") << ';' << values->Get("critical");
198 if (values->Contains("minimum") || values->Contains("maximum")) {
201 if (values->Contains("minimum"))
202 ssout << values->Get("minimum");
204 if (values->Contains("maximum"))
205 ssout << ';' << values->Get("maximum");
215 String state = static_cast<String>(payload->Get("result")).ToUpper();
216 int creturn = state == "OK" ? 0 :
217 state == "WARNING" ? 1 :
218 state == "CRITICAL" ? 2 :
219 state == "UNKNOWN" ? 3 : 4;
222 std::cout << "check_nscp UNKNOWN Answer format error: 'result' was not a known state.\n";
226 std::cout << ssout.rdbuf();
231 * Process arguments, initialize environment and shut down gracefully.
233 int main(int argc, char **argv)
235 po::variables_map vm;
236 po::options_description desc("Options");
239 ("help,h", "Print usage message and exit")
240 ("version,V", "Print version and exit")
241 ("debug,d", "Verbose/Debug output")
242 ("host,H", po::value<std::string>()->required(), "REQUIRED: NSCP API Host")
243 ("port,P", po::value<std::string>()->default_value("8443"), "NSCP API Port (Default: 8443)")
244 ("password", po::value<std::string>()->required(), "REQUIRED: NSCP API Password")
245 ("query,q", po::value<std::string>()->required(), "REQUIRED: NSCP API Query endpoint")
246 ("arguments,a", po::value<std::vector<std::string>>()->multitoken(), "NSCP API Query arguments for the endpoint");
248 po::basic_command_line_parser<char> parser(argc, argv);
255 po::command_line_style::unix_style |
256 po::command_line_style::allow_long_disguise)
260 if (vm.count("version")) {
261 std::cout << "Version: " << VERSION << '\n';
262 Application::Exit(0);
265 if (vm.count("help")) {
266 std::cout << argv[0] << " Help\n\tVersion: " << VERSION << '\n';
267 std::cout << "check_nscp_api is a program used to query the NSClient++ API.\n";
269 std::cout << "For detailed information on possible queries and their arguments refer to the NSClient++ documentation.\n";
270 Application::Exit(0);
274 } catch (std::exception& e) {
275 std::cout << e.what() << '\n' << desc << '\n';
276 Application::Exit(3);
279 if (vm.count("debug")) {
283 // Create the URL string and escape certain characters since Url() follows RFC 3986
284 String endpoint = "/query/" + vm["query"].as<std::string>();
285 if (!vm.count("arguments"))
289 for (const String& argument : vm["arguments"].as<std::vector<std::string>>()) {
290 String::SizeType pos = argument.FindFirstOf("=");
291 if (pos == String::NPos)
292 endpoint += Utility::EscapeString(argument, ACQUERY_ENCODE, false);
294 String key = argument.SubStr(0, pos);
295 String val = argument.SubStr(pos + 1);
296 endpoint += Utility::EscapeString(key, ACQUERY_ENCODE, false) + "=" + Utility::EscapeString(val, ACQUERY_ENCODE, false);
302 // This needs to happen for HttpRequest to work
303 Application::InitializeBase();
305 Dictionary::Ptr result = QueryEndpoint(vm["host"].as<std::string>(), vm["port"].as<std::string>(),
306 vm["password"].as<std::string>(), endpoint);
308 // Application::Exit() is the clean way to exit after calling InitializeBase()
309 Application::Exit(FormatOutput(result));