]> granicus.if.org Git - icinga2/blob - plugins/check_nscp_api.cpp
Merge branch 'support/2.8'
[icinga2] / plugins / check_nscp_api.cpp
1 /******************************************************************************
2  * Icinga 2                                                                   *
3  * Copyright (C) 2012-2018 Icinga Development Team (https://www.icinga.com/)  *
4  *                                                                            *
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.                     *
9  *                                                                            *
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.                               *
14  *                                                                            *
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  ******************************************************************************/
19
20 #define VERSION "1.0.1"
21
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>
31 #include <iostream>
32
33 using namespace icinga;
34 namespace po = boost::program_options;
35
36 static bool l_Debug;
37
38 /*
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
41  */
42 static void ResultHttpCompletionCallback(const HttpRequest& request, HttpResponse& response, bool& ready,
43         boost::condition_variable& cv, boost::mutex& mtx, Dictionary::Ptr& result)
44 {
45         String body;
46         char buffer[1024];
47         size_t count;
48
49         while ((count = response.ReadBody(buffer, sizeof(buffer))) > 0)
50                 body += String(buffer, buffer + count);
51
52         if (l_Debug) {
53                 std::cout << "Received answer\n"
54                         << "\tHTTP code: " << response.StatusCode << "\n"
55                         << "\tHTTP message: '" << response.StatusMessage << "'\n"
56                         << "\tHTTP body: '" << body << "'.\n";
57         }
58
59         // Only try to decode the body if the 'HttpRequest' was successful
60         if (response.StatusCode != 200)
61                 result = Dictionary::Ptr();
62         else
63                 result = JsonDecode(body);
64
65         // Unlock our mutex, set ready and notify 'QueryEndpoint()'
66         boost::mutex::scoped_lock lock(mtx);
67         ready = true;
68         cv.notify_all();
69 }
70
71 /*
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.
75  */
76 static Dictionary::Ptr QueryEndpoint(const String& host, const String& port, const String& password,
77         const String& endpoint)
78 {
79         HttpClientConnection::Ptr m_Connection = new HttpClientConnection(host, port, true);
80
81         try {
82                 bool ready = false;
83                 boost::condition_variable cv;
84                 boost::mutex mtx;
85                 Dictionary::Ptr result;
86                 std::shared_ptr<HttpRequest> req = m_Connection->NewRequest();
87                 req->RequestMethod = "GET";
88
89                 // Url() will call Utillity::UnescapeString() which will thrown an exception if it finds a lonely %
90                 req->RequestUrl = new Url(endpoint);
91
92                 // NSClient++ uses `time=1m&time=5m` instead of `time[]=1m&time[]=5m`
93                 req->RequestUrl->SetArrayFormatUseBrackets(false);
94
95                 req->AddHeader("password", password);
96                 if (l_Debug)
97                         std::cout << "Sending request to 'https://" << host << ":" << port << req->RequestUrl->Format(false, false) << "'\n";
98
99                 // Submits the request. The 'ResultHttpCompletionCallback' is called once the HttpRequest receives an answer,
100                 // which then sets 'ready' to true
101                 m_Connection->SubmitRequest(req, std::bind(ResultHttpCompletionCallback, _1, _2,
102                         boost::ref(ready), boost::ref(cv), boost::ref(mtx), boost::ref(result)));
103
104                 // We need to spinlock here because our 'HttpRequest' works asynchronous
105                 boost::mutex::scoped_lock lock(mtx);
106                 while (!ready) {
107                         cv.wait(lock);
108                 }
109
110                 return result;
111         }
112         catch (const std::exception& ex) {
113                 // Exceptions should only happen in extreme edge cases we can't recover from
114                 std::cout << "Caught exception: " << DiagnosticInformation(ex, false) << '\n';
115                 return Dictionary::Ptr();
116         }
117 }
118
119 /*
120  * Takes a Dictionary 'result' and constructs an icinga compliant output string.
121  * If 'result' is not in the expected format it returns 3 ("UNKNOWN") and prints an informative, icinga compliant,
122  * output string.
123  */
124 static int FormatOutput(const Dictionary::Ptr& result)
125 {
126         if (!result) {
127                 std::cout << "UNKNOWN: No data received.\n";
128                 return 3;
129         }
130
131         if (l_Debug)
132                 std::cout << "\tJSON Body:\n" << result->ToString() << '\n';
133
134         Array::Ptr payloads = result->Get("payload");
135         if (!payloads) {
136                 std::cout << "UNKNOWN: Answer format error: Answer is missing 'payload'.\n";
137                 return 3;
138         }
139
140         if (payloads->GetLength() == 0) {
141                 std::cout << "UNKNOWN: Answer format error: 'payload' was empty.\n";
142                 return 3;
143         }
144
145         if (payloads->GetLength() > 1) {
146                 std::cout << "UNKNOWN: Answer format error: Multiple payloads are not supported.";
147                 return 3;
148         }
149
150         Dictionary::Ptr payload;
151         try {
152                 payload = payloads->Get(0);
153         } catch (const std::exception&) {
154                 std::cout << "UNKNOWN: Answer format error: 'payload' was not a Dictionary.\n";
155                 return 3;
156         }
157
158         Array::Ptr lines;
159         try {
160                 lines = payload->Get("lines");
161         } catch (const std::exception&) {
162                 std::cout << "UNKNOWN: Answer format error: 'payload' is missing 'lines'.\n";
163                 return 3;
164         }
165
166         if (!lines) {
167                 std::cout << "UNKNOWN: Answer format error: 'lines' is Null.\n";
168                 return 3;
169         }
170
171         std::stringstream ssout;
172         ObjectLock olock(lines);
173
174         for (const Value& vline : lines) {
175                 Dictionary::Ptr line;
176                 try {
177                         line = vline;
178                 } catch (const std::exception&) {
179                         std::cout << "UNKNOWN: Answer format error: 'lines' entry was not a Dictionary.\n";
180                         return 3;
181                 }
182                 if (!line) {
183                         std::cout << "UNKNOWN: Answer format error: 'lines' entry was Null.\n";
184                         return 3;
185                 }
186
187                 ssout << payload->Get("command") << ' ' << line->Get("message") << " | ";
188
189                 if (!line->Contains("perf")) {
190                         ssout << '\n';
191                         break;
192                 }
193
194                 Array::Ptr perfs = line->Get("perf");
195                 ObjectLock olock(perfs);
196
197                 for (const Dictionary::Ptr& perf : perfs) {
198                         ssout << "'" << perf->Get("alias") << "'=";
199                         Dictionary::Ptr values = perf->Contains("int_value") ? perf->Get("int_value") : perf->Get("float_value");
200                         ssout << values->Get("value") << values->Get("unit") << ';' << values->Get("warning") << ';' << values->Get("critical");
201
202                         if (values->Contains("minimum") || values->Contains("maximum")) {
203                                 ssout << ';';
204
205                                 if (values->Contains("minimum"))
206                                         ssout << values->Get("minimum");
207
208                                 if (values->Contains("maximum"))
209                                         ssout << ';' << values->Get("maximum");
210                         }
211
212                         ssout << ' ';
213                 }
214
215                 ssout << '\n';
216         }
217
218         //TODO: Fix
219         String state = static_cast<String>(payload->Get("result")).ToUpper();
220         int creturn = state == "OK" ? 0 :
221                 state == "WARNING" ? 1 :
222                 state == "CRITICAL" ? 2 :
223                 state == "UNKNOWN" ? 3 : 4;
224
225         if (creturn == 4) {
226                 std::cout << "check_nscp UNKNOWN Answer format error: 'result' was not a known state.\n";
227                 return 3;
228         }
229
230         std::cout << ssout.rdbuf();
231         return creturn;
232 }
233
234 /*
235  *  Process arguments, initialize environment and shut down gracefully.
236  */
237 int main(int argc, char **argv)
238 {
239         po::variables_map vm;
240         po::options_description desc("Options");
241
242         desc.add_options()
243                 ("help,h", "Print usage message and exit")
244                 ("version,V", "Print version and exit")
245                 ("debug,d", "Verbose/Debug output")
246                 ("host,H", po::value<std::string>()->required(), "REQUIRED: NSCP API Host")
247                 ("port,P", po::value<std::string>()->default_value("8443"), "NSCP API Port (Default: 8443)")
248                 ("password", po::value<std::string>()->required(), "REQUIRED: NSCP API Password")
249                 ("query,q", po::value<std::string>()->required(), "REQUIRED: NSCP API Query endpoint")
250                 ("arguments,a", po::value<std::vector<std::string>>()->multitoken(), "NSCP API Query arguments for the endpoint");
251
252         po::command_line_parser parser(argc, argv);
253
254         try {
255                 po::store(
256                         parser
257                         .options(desc)
258                         .style(
259                                 po::command_line_style::unix_style |
260                                 po::command_line_style::allow_long_disguise)
261                         .run(),
262                         vm);
263
264                 if (vm.count("version")) {
265                         std::cout << "Version: " << VERSION << '\n';
266                         Application::Exit(0);
267                 }
268
269                 if (vm.count("help")) {
270                         std::cout << argv[0] << " Help\n\tVersion: " << VERSION << '\n';
271                         std::cout << "check_nscp_api is a program used to query the NSClient++ API.\n";
272                         std::cout << desc;
273                         std::cout << "For detailed information on possible queries and their arguments refer to the NSClient++ documentation.\n";
274                         Application::Exit(0);
275                 }
276
277                 vm.notify();
278         } catch (const std::exception& e) {
279                 std::cout << e.what() << '\n' << desc << '\n';
280                 Application::Exit(3);
281         }
282
283         l_Debug = vm.count("debug") > 0;
284
285         // Create the URL string and escape certain characters since Url() follows RFC 3986
286         String endpoint = "/query/" + vm["query"].as<std::string>();
287         if (!vm.count("arguments"))
288                 endpoint += '/';
289         else {
290                 endpoint += '?';
291                 for (const String& argument : vm["arguments"].as<std::vector<std::string>>()) {
292                         String::SizeType pos = argument.FindFirstOf("=");
293                         if (pos == String::NPos)
294                                 endpoint += Utility::EscapeString(argument, ACQUERY_ENCODE, false);
295                         else {
296                                 String key = argument.SubStr(0, pos);
297                                 String val = argument.SubStr(pos + 1);
298                                 endpoint += Utility::EscapeString(key, ACQUERY_ENCODE, false) + "=" + Utility::EscapeString(val, ACQUERY_ENCODE, false);
299                         }
300                         endpoint += '&';
301                 }
302         }
303
304         // This needs to happen for HttpRequest to work
305         Application::InitializeBase();
306
307         Dictionary::Ptr result = QueryEndpoint(vm["host"].as<std::string>(), vm["port"].as<std::string>(),
308                 vm["password"].as<std::string>(), endpoint);
309
310         // Application::Exit() is the clean way to exit after calling InitializeBase()
311         Application::Exit(FormatOutput(result));
312         return 255;
313 }