]> granicus.if.org Git - icinga2/blob - plugins/check_network.cpp
Auto-sanitize data before en-/decoding JSON
[icinga2] / plugins / check_network.cpp
1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
2
3 #define WIN32_LEAN_AND_MEAN
4
5 #include "plugins/thresholds.hpp"
6 #include <boost/program_options.hpp>
7 #include <boost/algorithm/string/replace.hpp>
8 #include <vector>
9 #include <map>
10 #include <windows.h>
11 #include <pdh.h>
12 #include <shlwapi.h>
13 #include <iostream>
14 #include <pdhmsg.h>
15 #include <winsock2.h>
16 #include <iphlpapi.h>
17
18 #define VERSION 1.2
19
20 namespace po = boost::program_options;
21
22 struct nInterface
23 {
24         std::wstring name;
25         LONG BytesInSec, BytesOutSec;
26         nInterface(std::wstring p)
27                 : name(p)
28         { }
29 };
30
31 struct printInfoStruct
32 {
33         threshold warn;
34         threshold crit;
35 };
36
37 static bool l_Debug;
38 static bool l_NoISATAP;
39
40 static int parseArguments(int ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo)
41 {
42         WCHAR namePath[MAX_PATH];
43         GetModuleFileName(NULL, namePath, MAX_PATH);
44         WCHAR *progName = PathFindFileName(namePath);
45
46         po::options_description desc("Options");
47
48         desc.add_options()
49                 ("help,h", "print usage and exit")
50                 ("version,V", "print version and exit")
51                 ("debug,d", "Verbose/Debug output")
52                 ("noisatap,n", "Don't show ISATAP interfaces in output")
53                 ("warning,w", po::wvalue<std::wstring>(), "warning value")
54                 ("critical,c", po::wvalue<std::wstring>(), "critical value")
55                 ;
56
57         po::wcommand_line_parser parser(ac, av);
58
59         try {
60                 po::store(
61                         parser
62                         .options(desc)
63                         .style(
64                                 po::command_line_style::unix_style |
65                                 po::command_line_style::allow_long_disguise)
66                         .run(),
67                         vm);
68                 vm.notify();
69         } catch (const std::exception& e) {
70                 std::cout << e.what() << '\n' << desc << '\n';
71                 return 3;
72         }
73
74         if (vm.count("help")) {
75                 std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n';
76                 wprintf(
77                         L"%s is a simple program to check a machines network performance.\n"
78                         L"You can use the following options to define its behaviour:\n\n", progName);
79                 std::cout << desc;
80                 wprintf(
81                         L"\nIt will then output a string looking something like this:\n\n"
82                         L"\tNETWORK WARNING 1131B/s | network=1131B;1000;7000;0\n\n"
83                         L"\"NETWORK\" being the type of the check, \"WARNING\" the returned status\n"
84                         L"and \"1131B/s\" is the returned value.\n"
85                         L"The performance data is found behind the \"|\", in order:\n"
86                         L"returned value, warning threshold, critical threshold, minimal value and,\n"
87                         L"if applicable, the maximal value. Performance data will only be displayed when\n"
88                         L"you set at least one threshold\n\n"
89                         L"This program will also print out additional performance data interface\n"
90                         L"by interface\n\n"
91                         L"%s' exit codes denote the following:\n"
92                         L" 0\tOK,\n\tNo Thresholds were broken or the programs check part was not executed\n"
93                         L" 1\tWARNING,\n\tThe warning, but not the critical threshold was broken\n"
94                         L" 2\tCRITICAL,\n\tThe critical threshold was broken\n"
95                         L" 3\tUNKNOWN, \n\tThe program experienced an internal or input error\n\n"
96                         L"Threshold syntax:\n\n"
97                         L"-w THRESHOLD\n"
98                         L"warn if threshold is broken, which means VALUE > THRESHOLD\n"
99                         L"(unless stated differently)\n\n"
100                         L"-w !THRESHOLD\n"
101                         L"inverts threshold check, VALUE < THRESHOLD (analogous to above)\n\n"
102                         L"-w [THR1-THR2]\n"
103                         L"warn is VALUE is inside the range spanned by THR1 and THR2\n\n"
104                         L"-w ![THR1-THR2]\n"
105                         L"warn if VALUE is outside the range spanned by THR1 and THR2\n\n"
106                         L"-w THRESHOLD%%\n"
107                         L"if the plugin accepts percentage based thresholds those will be used.\n"
108                         L"Does nothing if the plugin does not accept percentages, or only uses\n"
109                         L"percentage thresholds. Ranges can be used with \"%%\", but both range values need\n"
110                         L"to end with a percentage sign.\n\n"
111                         L"All of these options work with the critical threshold \"-c\" too."
112                         , progName);
113                 std::cout << '\n';
114                 return 0;
115         }
116
117         if (vm.count("version"))
118                 std::cout << "Version: " << VERSION << '\n';
119
120         if (vm.count("warning")) {
121                 try {
122                         printInfo.warn = threshold(vm["warning"].as<std::wstring>());
123                 } catch (const std::invalid_argument& e) {
124                         std::cout << e.what() << '\n';
125                         return 3;
126                 }
127         }
128         if (vm.count("critical")) {
129                 try {
130                         printInfo.crit = threshold(vm["critical"].as<std::wstring>());
131                 } catch (const std::invalid_argument& e) {
132                         std::cout << e.what() << '\n';
133                         return 3;
134                 }
135         }
136
137         l_Debug = vm.count("debug") > 0;
138         l_NoISATAP = vm.count("noisatap") > 0;
139
140         return -1;
141 }
142
143 static int printOutput(printInfoStruct& printInfo, const std::vector<nInterface>& vInterfaces, const std::map<std::wstring, std::wstring>& mapNames)
144 {
145         if (l_Debug)
146                 std::wcout << L"Constructing output string" << '\n';
147
148         long tIn = 0, tOut = 0;
149         std::wstringstream tss;
150         state state = OK;
151
152         std::map<std::wstring, std::wstring>::const_iterator mapIt;
153         std::wstring wsFriendlyName;
154
155         for (std::vector<nInterface>::const_iterator it = vInterfaces.begin(); it != vInterfaces.end(); ++it) {
156                 tIn += it->BytesInSec;
157                 tOut += it->BytesOutSec;
158                 if (l_Debug)
159                         std::wcout << "Getting friendly name of " << it->name << '\n';
160                 mapIt = mapNames.find(it->name);
161                 if (mapIt != mapNames.end()) {
162                         if (l_Debug)
163                                 std::wcout << "\tIs " << mapIt->second << '\n';
164                         wsFriendlyName = mapIt->second;
165                 } else {
166                         if (l_Debug)
167                                 std::wcout << "\tNo friendly name found, using adapter name\n";
168                         wsFriendlyName = it->name;
169                 }
170                 if (wsFriendlyName.find(L"isatap") != std::wstring::npos && l_NoISATAP) {
171                         if (l_Debug)
172                                 std::wcout << "\tSkipping isatap interface " << wsFriendlyName << "\n";
173                         continue;
174                 } else {
175                         boost::algorithm::replace_all(wsFriendlyName, "'", "''");
176                         tss << L"'" << wsFriendlyName << L"_in'=" << it->BytesInSec << L"B '" << wsFriendlyName << L"_out'=" << it->BytesOutSec << L"B ";
177                 }
178         }
179
180         if (printInfo.warn.rend(tIn + tOut))
181                 state = WARNING;
182         if (printInfo.crit.rend(tIn + tOut))
183                 state = CRITICAL;
184
185         std::wcout << "NETWORK ";
186
187         switch (state) {
188         case OK:
189                 std::wcout << L"OK";
190                 break;
191         case WARNING:
192                 std::wcout << L"WARNING";
193                 break;
194         case CRITICAL:
195                 std::wcout << L"CRITICAL";
196                 break;
197         }
198
199         std::wcout << " " << tIn + tOut << L"B/s | "
200                 << L"'network'=" << tIn + tOut << L"B;" << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";" << L"0; "
201                 << tss.str() << '\n';
202
203         return state;
204 }
205
206 static int check_network(std::vector<nInterface>& vInterfaces)
207 {
208
209         if (l_Debug)
210                 std::wcout << L"Creating Query and adding counters" << '\n';
211
212         PDH_FMT_COUNTERVALUE_ITEM *pDisplayValuesIn = NULL, *pDisplayValuesOut = NULL;
213
214         PDH_HQUERY phQuery;
215         PDH_STATUS err = PdhOpenQuery(NULL, NULL, &phQuery);
216         if (!SUCCEEDED(err))
217                 goto die;
218
219         const WCHAR *perfIn = L"\\Network Interface(*)\\Bytes Received/sec";
220         PDH_HCOUNTER phCounterIn;
221         err = PdhAddEnglishCounter(phQuery, perfIn, NULL, &phCounterIn);
222         if (!SUCCEEDED(err))
223                 goto die;
224
225         const WCHAR *perfOut = L"\\Network Interface(*)\\Bytes Sent/sec";
226         PDH_HCOUNTER phCounterOut;
227         err = PdhAddEnglishCounter(phQuery, perfOut, NULL, &phCounterOut);
228         if (!SUCCEEDED(err))
229                 goto die;
230
231         if (l_Debug)
232                 std::wcout << L"Collecting first batch of query data" << '\n';
233
234         err = PdhCollectQueryData(phQuery);
235         if (!SUCCEEDED(err))
236                 goto die;
237
238         if (l_Debug)
239                 std::wcout << L"Sleep for one second" << '\n';
240
241         Sleep(1000);
242
243         if (l_Debug)
244                 std::wcout << L"Collecting second batch of query data" << '\n';
245
246         err = PdhCollectQueryData(phQuery);
247         if (!SUCCEEDED(err))
248                 goto die;
249
250         if (l_Debug)
251                 std::wcout << L"Creating formatted counter arrays" << '\n';
252
253         DWORD dwItemCount;
254         DWORD dwBufferSizeIn = 0;
255         err = PdhGetFormattedCounterArray(phCounterIn, PDH_FMT_LONG, &dwBufferSizeIn, &dwItemCount, pDisplayValuesIn);
256         if (err == PDH_MORE_DATA || SUCCEEDED(err))
257                 pDisplayValuesIn = reinterpret_cast<PDH_FMT_COUNTERVALUE_ITEM*>(new BYTE[dwItemCount*dwBufferSizeIn]);
258         else
259                 goto die;
260
261         DWORD dwBufferSizeOut = 0;
262         err = PdhGetFormattedCounterArray(phCounterOut, PDH_FMT_LONG, &dwBufferSizeOut, &dwItemCount, pDisplayValuesOut);
263         if (err == PDH_MORE_DATA || SUCCEEDED(err))
264                 pDisplayValuesOut = reinterpret_cast<PDH_FMT_COUNTERVALUE_ITEM*>(new BYTE[dwItemCount*dwBufferSizeIn]);
265         else
266                 goto die;
267
268         err = PdhGetFormattedCounterArray(phCounterIn, PDH_FMT_LONG, &dwBufferSizeIn, &dwItemCount, pDisplayValuesIn);
269         if (!SUCCEEDED(err))
270                 goto die;
271
272         err = PdhGetFormattedCounterArray(phCounterOut, PDH_FMT_LONG, &dwBufferSizeOut, &dwItemCount, pDisplayValuesOut);
273         if (!SUCCEEDED(err))
274                 goto die;
275
276         if (l_Debug)
277                 std::wcout << L"Going over counter array" << '\n';
278
279         for (DWORD i = 0; i < dwItemCount; i++) {
280                 nInterface iface{pDisplayValuesIn[i].szName};
281                 iface.BytesInSec = pDisplayValuesIn[i].FmtValue.longValue;
282                 iface.BytesOutSec = pDisplayValuesOut[i].FmtValue.longValue;
283                 vInterfaces.push_back(iface);
284
285                 if (l_Debug)
286                         std::wcout << L"Collected interface " << pDisplayValuesIn[i].szName << '\n';
287         }
288
289         if (l_Debug)
290                 std::wcout << L"Finished collection. Cleaning up and returning" << '\n';
291
292         if (phQuery)
293                 PdhCloseQuery(phQuery);
294
295         delete reinterpret_cast<BYTE *>(pDisplayValuesIn);
296         delete reinterpret_cast<BYTE *>(pDisplayValuesOut);
297
298         return -1;
299 die:
300         printErrorInfo(err);
301         if (phQuery)
302                 PdhCloseQuery(phQuery);
303
304         delete reinterpret_cast<BYTE *>(pDisplayValuesIn);
305         delete reinterpret_cast<BYTE *>(pDisplayValuesOut);
306
307         return 3;
308 }
309
310 static bool mapSystemNamesToFamiliarNames(std::map<std::wstring, std::wstring>& mapNames)
311 {
312         /*
313         PIP_ADAPTER_UNICAST_ADDRESS pUnicast = NULL;
314         PIP_ADAPTER_ANYCAST_ADDRESS pAnycast = NULL;
315         PIP_ADAPTER_MULTICAST_ADDRESS pMulticast = NULL;
316         PIP_ADAPTER_DNS_SERVER_ADDRESS pDnsServer = NULL;
317         PIP_ADAPTER_PREFIX pPrefix = NULL;
318         */
319         ULONG outBufLen = 15000; //15KB as suggestet by msdn of GetAdaptersAddresses
320
321         if (l_Debug)
322                 std::wcout << "Mapping adapter system names to friendly names\n";
323
324         PIP_ADAPTER_ADDRESSES pAddresses;
325
326         unsigned int Iterations = 0;
327         DWORD dwRetVal = 0;
328
329         do {
330                 pAddresses = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(new BYTE[outBufLen]);
331
332                 dwRetVal = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, pAddresses, &outBufLen);
333
334                 if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
335                         delete[]pAddresses;
336                         pAddresses = NULL;
337                 } else
338                         break;
339         } while (++Iterations < 3);
340
341         if (dwRetVal != NO_ERROR) {
342                 std::wcout << "Failed to collect friendly adapter names\n";
343                 delete[]pAddresses;
344                 return false;
345         }
346
347         for (PIP_ADAPTER_ADDRESSES pCurrAddresses = pAddresses; pCurrAddresses; pCurrAddresses = pCurrAddresses->Next) {
348                 if (l_Debug)
349                         std::wcout << "Got: " << pCurrAddresses->Description << " -- " << pCurrAddresses->FriendlyName << '\n';
350
351                 mapNames[pCurrAddresses->Description] = pCurrAddresses->FriendlyName;
352         }
353
354         delete[]pAddresses;
355         return true;
356 }
357
358 int wmain(int argc, WCHAR **argv)
359 {
360         std::vector<nInterface> vInterfaces;
361         std::map<std::wstring, std::wstring> mapNames;
362         printInfoStruct printInfo;
363         po::variables_map vm;
364
365         int ret = parseArguments(argc, argv, vm, printInfo);
366
367         if (ret != -1)
368                 return ret;
369
370         if (!mapSystemNamesToFamiliarNames(mapNames))
371                 return 3;
372
373         ret = check_network(vInterfaces);
374         if (ret != -1)
375                 return ret;
376
377         return printOutput(printInfo, vInterfaces, mapNames);
378 }