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