From c1e13d3dbe5bd743d1dae9610ec8cc369b0e539c Mon Sep 17 00:00:00 2001 From: Jean Flach Date: Mon, 23 Mar 2015 13:07:02 +0100 Subject: [PATCH] Refactor plugin code --- plugins/CMakeLists.txt | 34 +++---- plugins/check_disk.cpp | 184 +++++++++++++++-------------------- plugins/check_disk.h | 51 ++++++++++ plugins/check_load.cpp | 81 +++++++--------- plugins/check_load.h | 35 +++++++ plugins/check_memory.cpp | 86 +++++++---------- plugins/check_memory.h | 37 +++++++ plugins/check_network.cpp | 196 +++++++++++++++++++++++++------------- plugins/check_network.h | 47 +++++++++ plugins/check_ping.cpp | 147 ++++++++++++---------------- plugins/check_ping.h | 46 +++++++++ plugins/check_procs.cpp | 116 ++++++++++------------ plugins/check_procs.h | 36 +++++++ plugins/check_service.cpp | 71 ++++++-------- plugins/check_service.h | 36 +++++++ plugins/check_swap.cpp | 80 +++++++--------- plugins/check_swap.h | 36 +++++++ plugins/check_update.cpp | 76 ++++++--------- plugins/check_update.h | 36 +++++++ plugins/check_uptime.cpp | 84 +++++++--------- plugins/check_uptime.h | 36 +++++++ plugins/check_users.cpp | 91 ++++++++---------- plugins/check_users.h | 15 +++ plugins/thresholds.cpp | 79 ++++++++------- plugins/thresholds.h | 76 ++++++++------- 25 files changed, 1061 insertions(+), 751 deletions(-) create mode 100644 plugins/check_disk.h create mode 100644 plugins/check_load.h create mode 100644 plugins/check_memory.h create mode 100644 plugins/check_network.h create mode 100644 plugins/check_ping.h create mode 100644 plugins/check_procs.h create mode 100644 plugins/check_service.h create mode 100644 plugins/check_swap.h create mode 100644 plugins/check_update.h create mode 100644 plugins/check_uptime.h create mode 100644 plugins/check_users.h diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt index 049cabad3..dd8cc5012 100644 --- a/plugins/CMakeLists.txt +++ b/plugins/CMakeLists.txt @@ -17,43 +17,43 @@ if ( WIN32 ) - add_definitions( -DUNICODE -D_UNICODE ) + add_definitions ( -DUNICODE -D_UNICODE ) - add_library( thresholds thresholds ) + add_library ( thresholds thresholds ) set_target_properties ( thresholds PROPERTIES INSTALL_RPATH ${CMAKE_INSTALL_FULL_LIBDIR}/icinga2 FOLDER Plugins ) - list( APPEND check_SOURCES - check_disk.cpp check_load.cpp check_memory.cpp check_network.cpp check_ping.cpp check_perfmon.cpp + list ( APPEND check_SOURCES + check_disk.cpp check_load.cpp check_memory.cpp check_network.cpp check_ping.cpp check_procs.cpp check_service.cpp check_swap.cpp check_update.cpp check_uptime.cpp check_users.cpp ) foreach ( source ${check_SOURCES} ) string ( REGEX REPLACE ".cpp\$" "" check_OUT "${source}" ) + string ( REGEX REPLACE ".cpp\$" ".h" check_HEADER "${source}" ) - add_executable ( ${check_OUT} ${source} ) - target_link_libraries( ${check_OUT} thresholds Shlwapi.lib ${Boost_PROGRAM_OPTIONS_LIBRARY} ) + add_executable ( ${check_OUT} ${source} ${check_HEADER} ) + target_link_libraries ( ${check_OUT} thresholds Shlwapi.lib ${Boost_PROGRAM_OPTIONS_LIBRARY} ) set_target_properties ( ${check_OUT} PROPERTIES INSTALL_RPATH ${CMAKE_INSTALL_FULL_LIBDIR}/icinga2 DEFINE_SYMBOL I2_PLUGINS_BUILD - FOLDER Plugins) - endforeach(source) + FOLDER Plugins ) + endforeach ( source ) - target_link_libraries( check_load Pdh.lib ) - target_link_libraries( check_network Pdh.lib ) - target_link_libraries ( check_perfmon Pdh.lib ) - target_link_libraries( check_ping Ntdll.lib iphlpapi.lib Ws2_32.lib ) - target_link_libraries( check_procs Pdh.lib ) - target_link_libraries( check_uptime ${Boost_SYSTEM_LIBRARY} ) - target_link_libraries( check_users wtsapi32.lib ) + target_link_libraries ( check_load Pdh.lib ) + target_link_libraries ( check_network Pdh.lib Iphlpapi.lib) + target_link_libraries ( check_ping Ntdll.lib iphlpapi.lib Ws2_32.lib ) + target_link_libraries ( check_procs Pdh.lib ) + target_link_libraries ( check_uptime ${Boost_SYSTEM_LIBRARY} ) + target_link_libraries ( check_users wtsapi32.lib ) install ( - TARGETS check_disk check_load check_memory check_network check_procs check_perfmon + TARGETS check_disk check_load check_memory check_network check_procs check_ping check_service check_swap check_update check_uptime check_users RUNTIME DESTINATION ${CMAKE_INSTALL_SBINDIR} ) -endif() +endif ( ) diff --git a/plugins/check_disk.cpp b/plugins/check_disk.cpp index bb1d81482..7523f15aa 100644 --- a/plugins/check_disk.cpp +++ b/plugins/check_disk.cpp @@ -16,55 +16,26 @@ * along with this program; if not, write to the Free Software Foundation * * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * ******************************************************************************/ -#include #include #include -#include #include #include -#include "thresholds.h" - -#include "boost/program_options.hpp" +#include "check_disk.h" #define VERSION 1.1 namespace po = boost::program_options; -using std::cout; using std::endl; using std::set; -using std::vector; using std::wstring; using std::wcout; - static BOOL debug = FALSE; -struct drive +INT wmain(INT argc, WCHAR **argv) { - wstring name; - double cap, free; - drive(wstring p) - : name(p) - {} -}; - -struct printInfoStruct -{ - threshold warn, crit; - vector drives; - Bunit unit; -}; - -static int parseArguments(int, wchar_t **, po::variables_map&, printInfoStruct&); -static int printOutput(printInfoStruct&, vector&); -static int check_drives(vector&); -static int check_drives(vector&, printInfoStruct&); -static bool getFreeAndCap(drive&, const Bunit&); - -int wmain(int argc, wchar_t **argv) -{ - vector vDrives; + std::vector vDrives; printInfoStruct printInfo{ }; po::variables_map vm; - int ret; + INT ret; ret = parseArguments(argc, argv, vm, printInfo); if (ret != -1) @@ -81,9 +52,9 @@ int wmain(int argc, wchar_t **argv) if (ret != -1) return ret; - for (vector::iterator it = vDrives.begin(); it != vDrives.end(); ++it) { + for (std::vector::iterator it = vDrives.begin(); it != vDrives.end(); ++it) { if (!getFreeAndCap(*it, printInfo.unit)) { - wcout << L"Failed to access drive at " << it->name << endl; + std::wcout << "Failed to access drive at " << it->name << '\n'; return 3; } } @@ -91,32 +62,32 @@ int wmain(int argc, wchar_t **argv) return printOutput(printInfo, vDrives); } -int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& printInfo) +INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo) { - wchar_t namePath[MAX_PATH]; + WCHAR namePath[MAX_PATH]; GetModuleFileName(NULL, namePath, MAX_PATH); - wchar_t *progName = PathFindFileName(namePath); + WCHAR *progName = PathFindFileName(namePath); po::options_description desc("Options"); desc.add_options() - ("help,h", "print usage message and exit") - ("version,V", "print version and exit") + ("help,h", "Print usage message and exit") + ("version,V", "Print version and exit") ("debug,d", "Verbose/Debug output") - ("warning,w", po::wvalue(), "warning threshold") - ("critical,c", po::wvalue(), "critical threshold") - ("path,p", po::wvalue>()->multitoken(), "declare explicitly which drives to check (default checks all)") - ("unit,u", po::wvalue(), "assign unit possible are: B, kB, MB, GB, TB") + ("warning,w", po::wvalue(), "Warning threshold") + ("critical,c", po::wvalue(), "Critical threshold") + ("path,p", po::wvalue>()->multitoken(), "Declare explicitly which drives to check (default checks all)") + ("unit,u", po::wvalue(), "Assign unit possible are: B, kB, MB, GB, TB") ; - po::basic_command_line_parser parser(ac, av); + po::basic_command_line_parser parser(ac, av); try { po::options_description allDesc; allDesc.add(desc); allDesc.add_options() - ("exclude-type,X", po::wvalue>()->multitoken(), "exclude partition types (ignored)") + ("exclude-type,X", po::wvalue>()->multitoken(), "exclude partition types (ignored)") ("megabytes,m", "use megabytes") ; @@ -130,16 +101,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& vm); vm.notify(); } catch (std::exception& e) { - cout << e.what() << endl << desc << endl; + std::cout << e.what() << '\n' << desc << '\n'; return 3; } if (vm.count("help")) { - wcout << progName << " Help\n\tVersion: " << VERSION << endl; + std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n'; wprintf( L"%s is a simple program to check a machines free disk space.\n" L"You can use the following options to define its behaviour:\n\n", progName); - cout << desc; + std::cout << desc; wprintf( L"\nIt will then output a string looking something like this:\n\n" L"\tDISK WARNING 29GB | disk=29GB;50%%;5;0;120\n\n" @@ -153,7 +124,7 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& L" 0\tOK,\n\tNo Thresholds were broken or the programs check part was not executed\n" L" 1\tWARNING,\n\tThe warning, but not the critical threshold was broken\n" L" 2\tCRITICAL,\n\tThe critical threshold was broken\n" - L" 3\tUNKNOWN, \n\tThe program experienced an internal or input error\n\n" + L" 3\tUNKNOWN, \n\tThe program experienced an INTernal or input error\n\n" L"Threshold syntax:\n\n" L"-w THRESHOLD\n" L"warn if threshold is broken, which means VALUE < THRESHOLD\n\n" @@ -170,38 +141,38 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& L"to end with a percentage sign.\n\n" L"All of these options work with the critical threshold \"-c\" too." , progName); - cout << endl; + std::cout << '\n'; return 0; } if (vm.count("version")) - cout << "Version: " << VERSION << endl; + std::cout << "Version: " << VERSION << '\n'; if (vm.count("warning")) { try { - printInfo.warn = threshold(vm["warning"].as()); + printInfo.warn = threshold(vm["warning"].as()); } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } } if (vm.count("critical")) { try { - printInfo.crit = threshold(vm["critical"].as()); + printInfo.crit = threshold(vm["critical"].as()); } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } } if (vm.count("path")) - printInfo.drives = vm["path"].as>(); + printInfo.drives = vm["path"].as>(); if (vm.count("unit")) { try { - printInfo.unit = parseBUnit(vm["unit"].as()); + printInfo.unit = parseBUnit(vm["unit"].as()); } catch (std::invalid_argument) { - wcout << L"Unknown unit Type " << vm["unit"].as() << endl; + std::wcout << "Unknown unit Type " << vm["unit"].as() << '\n'; return 3; } } else @@ -213,19 +184,19 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& return -1; } -int printOutput(printInfoStruct& printInfo, vector& vDrives) +INT printOutput(printInfoStruct& printInfo, std::vector& vDrives) { if (debug) - wcout << L"Constructing output string" << endl; + std::wcout << "Constructing output string\n"; - vector wsDrives, wsPerf; - wstring unit = BunitStr(printInfo.unit); + std::vector wsDrives, wsPerf; + std::wstring unit = BunitStr(printInfo.unit); state state = OK; - wstring output = L"DISK OK - free space:"; + std::wstring output = L"DISK OK - free space:"; double tCap = 0, tFree = 0; - for (vector::iterator it = vDrives.begin(); it != vDrives.end(); it++) { + for (std::vector::iterator it = vDrives.begin(); it != vDrives.end(); it++) { tCap += it->cap; tFree += it->free; wsDrives.push_back(it->name + L" " + removeZero(it->free) + L" " + unit + L" (" + @@ -245,94 +216,93 @@ int printOutput(printInfoStruct& printInfo, vector& vDrives) output = L"DISK CRITICAL - free space:"; } - wcout << output; + std::wcout << output; if (vDrives.size() > 1) - wcout << L"Total " << tFree << unit << L" (" << removeZero(std::round(tFree/tCap * 100.0)) << L"%); "; + std::wcout << "Total " << tFree << unit << " (" << removeZero(std::round(tFree/tCap * 100.0)) << "%); "; - for (vector::const_iterator it = wsDrives.begin(); it != wsDrives.end(); it++) - wcout << *it; - wcout << L"|"; + for (std::vector::const_iterator it = wsDrives.begin(); it != wsDrives.end(); it++) + std::wcout << *it; + std::wcout << "|"; - for (vector::const_iterator it = wsPerf.begin(); it != wsPerf.end(); it++) - wcout << *it; + for (std::vector::const_iterator it = wsPerf.begin(); it != wsPerf.end(); it++) + std::wcout << *it; - wcout << endl; + std::wcout << '\n'; return state; } -int check_drives(vector& vDrives) +INT check_drives(std::vector& vDrives) { DWORD dwResult, dwSize = 0, dwVolumePathNamesLen = MAX_PATH + 1; - wchar_t szLogicalDrives[1024], szVolumeName[MAX_PATH], *szVolumePathNames = NULL; + WCHAR szLogicalDrives[1024], szVolumeName[MAX_PATH], *szVolumePathNames = NULL; HANDLE hVolume = NULL; - wstring wsLogicalDrives; + std::wstring wsLogicalDrives; size_t volumeNameEnd = 0; - set sDrives; + std::set sDrives; if (debug) - wcout << L"Getting logic drive string (includes network drives)" << endl; + std::wcout << "Getting logic drive string (includes network drives)\n"; dwResult = GetLogicalDriveStrings(MAX_PATH, szLogicalDrives); if (dwResult > MAX_PATH) goto die; if (debug) - wcout << L"Splitting string into single drive names" << endl; + std::wcout << "Splitting string INTo single drive names\n"; LPTSTR szSingleDrive = szLogicalDrives; while (*szSingleDrive) { - wstring drname = szSingleDrive; + std::wstring drname = szSingleDrive; sDrives.insert(drname); szSingleDrive += wcslen(szSingleDrive) + 1; if (debug) - wcout << "Got: " << drname << endl; + std::wcout << "Got: " << drname << '\n'; } if (debug) - wcout << L"Getting volume mountpoints (includes NTFS folders)" << endl - << L"Getting first volume" << endl; + std::wcout << "Getting volume mountpoINTs (includes NTFS folders)\n" + << "Getting first volume\n"; hVolume = FindFirstVolume(szVolumeName, MAX_PATH); if (hVolume == INVALID_HANDLE_VALUE) goto die; if (debug) - wcout << L"Traversing through list of drives" << endl; + std::wcout << "Traversing through list of drives\n"; while (GetLastError() != ERROR_NO_MORE_FILES) { if (debug) - wcout << L"Path name for " << szVolumeName << L"= \""; + std::wcout << "Path name for " << szVolumeName << "= \""; volumeNameEnd = wcslen(szVolumeName) - 1; - szVolumePathNames = reinterpret_cast(new WCHAR[dwVolumePathNamesLen]); + szVolumePathNames = reinterpret_cast(new WCHAR[dwVolumePathNamesLen]); while (!GetVolumePathNamesForVolumeName(szVolumeName, szVolumePathNames, dwVolumePathNamesLen, &dwVolumePathNamesLen)) { if (GetLastError() != ERROR_MORE_DATA) break; - delete[] reinterpret_cast(szVolumePathNames); - szVolumePathNames = reinterpret_cast(new WCHAR[dwVolumePathNamesLen]); + delete[] reinterpret_cast(szVolumePathNames); + szVolumePathNames = reinterpret_cast(new WCHAR[dwVolumePathNamesLen]); } if (debug) - wcout << szVolumePathNames << L"\"" << endl; + std::wcout << szVolumePathNames << "\"\n"; - //.insert() does the dublicate checking - sDrives.insert(wstring(szVolumePathNames)); + sDrives.insert(std::wstring(szVolumePathNames)); FindNextVolume(hVolume, szVolumeName, MAX_PATH); } if (debug) - wcout << L"Creating vector from found volumes, ignoring cd drives etc.:" << endl; - for (set::iterator it = sDrives.begin(); it != sDrives.end(); ++it) { + std::wcout << "Creating vector from found volumes, ignoring cd drives etc.:\n"; + for (std::set::iterator it = sDrives.begin(); it != sDrives.end(); ++it) { UINT type = GetDriveType(it->c_str()); if (type == DRIVE_FIXED || type == DRIVE_REMOTE) { if (debug) - wcout << L"\t" << *it << endl; + std::wcout << "\t" << *it << '\n'; vDrives.push_back(drive(*it)); } } FindVolumeClose(hVolume); if (szVolumePathNames) - delete[] reinterpret_cast(szVolumePathNames); + delete[] reinterpret_cast(szVolumePathNames); return -1; die: @@ -342,45 +312,45 @@ die: return 3; } -int check_drives(vector& vDrives, printInfoStruct& printInfo) +INT check_drives(std::vector& vDrives, printInfoStruct& printInfo) { - wchar_t *slash = L"\\"; + WCHAR *slash = L"\\"; if (debug) - wcout << L"Parsing user input drive names" << endl; + std::wcout << "Parsing user input drive names\n"; - for (vector::iterator it = printInfo.drives.begin(); + for (std::vector::iterator it = printInfo.drives.begin(); it != printInfo.drives.end(); ++it) { if (it->at(it->length() - 1) != *slash) it->append(slash); if (std::wstring::npos == it->find(L":\\")) { - wcout << "A \":\" is required after the drive name of " << *it << endl; + std::wcout << "A \":\" is required after the drive name of " << *it << '\n'; return 3; } if (debug) - wcout << L"Added " << *it << endl; + std::wcout << "Added " << *it << '\n'; vDrives.push_back(drive(*it)); } return -1; } -bool getFreeAndCap(drive& drive, const Bunit& unit) +BOOL getFreeAndCap(drive& drive, const Bunit& unit) { if (debug) - wcout << L"Getting free disk space for drive " << drive.name << endl; + std::wcout << "Getting free disk space for drive " << drive.name << '\n'; ULARGE_INTEGER tempFree, tempTotal; if (!GetDiskFreeSpaceEx(drive.name.c_str(), NULL, &tempTotal, &tempFree)) { return FALSE; } if (debug) - wcout << L"\tcap: " << tempFree.QuadPart << endl; + std::wcout << "\tcap: " << tempFree.QuadPart << '\n'; drive.cap = round((tempTotal.QuadPart / pow(1024.0, unit))); if (debug) - wcout << L"\tAfter conversion: " << drive.cap << endl - << L"\tfree: " << tempFree.QuadPart << endl; + std::wcout << "\tAfter conversion: " << drive.cap << '\n' + << "\tfree: " << tempFree.QuadPart << '\n'; drive.free = round((tempFree.QuadPart / pow(1024.0, unit))); if (debug) - wcout << L"\tAfter conversion: " << drive.free << endl << endl; + std::wcout << "\tAfter conversion: " << drive.free << '\n' << '\n'; return TRUE; } diff --git a/plugins/check_disk.h b/plugins/check_disk.h new file mode 100644 index 000000000..6f0a4dccf --- /dev/null +++ b/plugins/check_disk.h @@ -0,0 +1,51 @@ +/****************************************************************************** + * Icinga 2 * + * Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.org) * + * * + * This program is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2 * + * of the License, or (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the Free Software Foundation * + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * + ******************************************************************************/ + +#ifndef CHECK_DISK_H +#define CHECK_DISK_H + +#include +#include + +#include "boost/program_options.hpp" +#include "thresholds.h" + +struct drive +{ + std::wstring name; + double cap, free; + drive(std::wstring p) + : name(p) + { + } +}; + +struct printInfoStruct +{ + threshold warn, crit; + std::vector drives; + Bunit unit; +}; + +INT parseArguments(int, wchar_t **, boost::program_options::variables_map&, printInfoStruct&); +INT printOutput(printInfoStruct&, std::vector&); +INT check_drives(std::vector&); +INT check_drives(std::vector&, printInfoStruct&); +BOOL getFreeAndCap(drive&, const Bunit&); +#endif /*CHECK_DISK_H*/ \ No newline at end of file diff --git a/plugins/check_load.cpp b/plugins/check_load.cpp index b0fa3ff54..f741cd24e 100644 --- a/plugins/check_load.cpp +++ b/plugins/check_load.cpp @@ -17,40 +17,29 @@ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * ******************************************************************************/ -#include "thresholds.h" -#include -#include -#include #include #include #include #include +#include "check_load.h" + +#include "boost/algorithm/string/split.hpp" +#include "boost/algorithm/string/classification.hpp" + #define VERSION 1.0 namespace po = boost::program_options; -using std::endl; using std::cout; using std::wstring; -using std::wcout; - static BOOL debug = FALSE; -struct printInfoStruct -{ - threshold warn, crit; - double load; -}; -static int parseArguments(int, wchar_t **, po::variables_map&, printInfoStruct&); -static int printOutput(printInfoStruct&); -static int check_load(printInfoStruct&); - -int wmain(int argc, wchar_t **argv) +INT wmain(INT argc, WCHAR **argv) { printInfoStruct printInfo{ }; po::variables_map vm; - int ret = parseArguments(argc, argv, vm, printInfo); + INT ret = parseArguments(argc, argv, vm, printInfo); if (ret != -1) return ret; @@ -61,7 +50,7 @@ int wmain(int argc, wchar_t **argv) return printOutput(printInfo); } -int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& printInfo) { +INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo) { wchar_t namePath[MAX_PATH]; GetModuleFileName(NULL, namePath, MAX_PATH); wchar_t *progName = PathFindFileName(namePath); @@ -69,11 +58,11 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& po::options_description desc; desc.add_options() - ("help,h", "print usage message and exit") - ("version,V", "print version and exit") + ("help,h", "Print usage message and exit") + ("version,V", "Print version and exit") ("debug,d", "Verbose/Debug output") - ("warning,w", po::wvalue(), "warning value (in percent)") - ("critical,c", po::wvalue(), "critical value (in percent)") + ("warning,w", po::wvalue(), "Warning value (in percent)") + ("critical,c", po::wvalue(), "Critical value (in percent)") ; po::basic_command_line_parser parser(ac, av); @@ -89,16 +78,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& vm); vm.notify(); } catch (std::exception& e) { - cout << e.what() << endl << desc << endl; + std::cout << e.what() << '\n' << desc << '\n'; return 3; } if (vm.count("help")) { - wcout << progName << " Help\n\tVersion: " << VERSION << endl; + std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n'; wprintf( L"%s is a simple program to check a machines CPU load.\n" L"You can use the following options to define its behaviour:\n\n", progName); - cout << desc; + std::cout << desc; wprintf( L"\nIt will then output a string looking something like this:\n\n" L"\tLOAD WARNING 67%% | load=67%%;50%%;90%%;0;100\n\n" @@ -129,32 +118,32 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& L"to end with a percentage sign.\n\n" L"All of these options work with the critical threshold \"-c\" too." , progName); - cout << endl; + std::cout << '\n'; return 0; } if (vm.count("version")) - cout << "Version: " << VERSION << endl; + std::cout << "Version: " << VERSION << '\n'; if (vm.count("warning")) { try { - std::wstring wthreshold = vm["warning"].as(); + std::wstring wthreshold = vm["warning"].as(); std::vector tokens; boost::algorithm::split(tokens, wthreshold, boost::algorithm::is_any_of(",")); printInfo.warn = threshold(tokens[0]); } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } } if (vm.count("critical")) { try { - std::wstring cthreshold = vm["critical"].as(); + std::wstring cthreshold = vm["critical"].as(); std::vector tokens; boost::algorithm::split(tokens, cthreshold, boost::algorithm::is_any_of(",")); printInfo.crit = threshold(tokens[0]); } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } } @@ -165,10 +154,10 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& return -1; } -int printOutput(printInfoStruct& printInfo) +INT printOutput(printInfoStruct& printInfo) { if (debug) - wcout << L"Constructing output string" << endl; + std::wcout << L"Constructing output string" << '\n'; state state = OK; @@ -180,24 +169,24 @@ int printOutput(printInfoStruct& printInfo) std::wstringstream perf; perf << L"% | load=" << printInfo.load << L"%;" << printInfo.warn.pString() << L";" - << printInfo.crit.pString() << L";0;100" << endl; + << printInfo.crit.pString() << L";0;100" << '\n'; switch (state) { case OK: - wcout << L"LOAD OK " << printInfo.load << perf.str(); + std::wcout << L"LOAD OK " << printInfo.load << perf.str(); break; case WARNING: - wcout << L"LOAD WARNING " << printInfo.load << perf.str(); + std::wcout << L"LOAD WARNING " << printInfo.load << perf.str(); break; case CRITICAL: - wcout << L"LOAD CRITICAL " << printInfo.load << perf.str(); + std::wcout << L"LOAD CRITICAL " << printInfo.load << perf.str(); break; } return state; } -int check_load(printInfoStruct& printInfo) +INT check_load(printInfoStruct& printInfo) { PDH_HQUERY phQuery = NULL; PDH_HCOUNTER phCounter; @@ -209,7 +198,7 @@ int check_load(printInfoStruct& printInfo) LPCWSTR path = L"\\Processor(_Total)\\% Idle Time"; if (debug) - wcout << L"Creating query and adding counter" << endl; + std::wcout << L"Creating query and adding counter" << '\n'; err = PdhOpenQuery(NULL, NULL, &phQuery); if (!SUCCEEDED(err)) @@ -220,37 +209,37 @@ int check_load(printInfoStruct& printInfo) goto die; if (debug) - wcout << L"Collecting first batch of query data" << endl; + std::wcout << L"Collecting first batch of query data" << '\n'; err = PdhCollectQueryData(phQuery); if (!SUCCEEDED(err)) goto die; if (debug) - wcout << L"Sleep for one second" << endl; + std::wcout << L"Sleep for one second" << '\n'; Sleep(1000); if (debug) - wcout << L"Collecting second batch of query data" << endl; + std::wcout << L"Collecting second batch of query data" << '\n'; err = PdhCollectQueryData(phQuery); if (!SUCCEEDED(err)) goto die; if (debug) - wcout << L"Creating formatted counter array" << endl; + std::wcout << L"Creating formatted counter array" << '\n'; err = PdhGetFormattedCounterValue(phCounter, PDH_FMT_DOUBLE, &CounterType, &DisplayValue); if (SUCCEEDED(err)) { if (DisplayValue.CStatus == PDH_CSTATUS_VALID_DATA) { if (debug) - wcout << L"Recieved Value of " << DisplayValue.doubleValue << L" (idle)" << endl; + std::wcout << L"Recieved Value of " << DisplayValue.doubleValue << L" (idle)" << '\n'; printInfo.load = 100.0 - DisplayValue.doubleValue; } if (debug) - wcout << L"Finished collection. Cleaning up and returning" << endl; + std::wcout << L"Finished collection. Cleaning up and returning" << '\n'; PdhCloseQuery(phQuery); return -1; diff --git a/plugins/check_load.h b/plugins/check_load.h new file mode 100644 index 000000000..f480f10b9 --- /dev/null +++ b/plugins/check_load.h @@ -0,0 +1,35 @@ +/****************************************************************************** + * Icinga 2 * + * Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.org) * + * * + * This program is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2 * + * of the License, or (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the Free Software Foundation * + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * + ******************************************************************************/ + +#ifndef CHECK_LOAD_H +#define CHECK_LOAD_H + +#include "thresholds.h" +#include "boost/program_options.hpp" + +struct printInfoStruct +{ + threshold warn, crit; + DOUBLE load; +}; + +INT parseArguments(INT, WCHAR **, boost::program_options::variables_map&, printInfoStruct&); +INT printOutput(printInfoStruct&); +INT check_load(printInfoStruct&); +#endif // !CHECK_LOAD_H diff --git a/plugins/check_memory.cpp b/plugins/check_memory.cpp index 229d5243c..ef8c10eec 100644 --- a/plugins/check_memory.cpp +++ b/plugins/check_memory.cpp @@ -20,36 +20,20 @@ #include #include -#include "thresholds.h" - -#include "boost/program_options.hpp" +#include "check_memory.h" #define VERSION 1.0 namespace po = boost::program_options; -using std::endl; using std::wcout; using std::wstring; -using std::cout; - static BOOL debug = FALSE; -struct printInfoStruct -{ - threshold warn, crit; - DWORDLONG tRam, aRam; - Bunit unit = BunitMB; -}; - -static int parseArguments(int, wchar_t **, po::variables_map&, printInfoStruct&); -static int printOutput(printInfoStruct&); -static int check_memory(printInfoStruct&); - -int wmain(int argc, wchar_t **argv) +INT wmain(INT argc, WCHAR **argv) { printInfoStruct printInfo = {}; po::variables_map vm; - int ret = parseArguments(argc, argv, vm, printInfo); + INT ret = parseArguments(argc, argv, vm, printInfo); if (ret != -1) return ret; @@ -60,24 +44,24 @@ int wmain(int argc, wchar_t **argv) return printOutput(printInfo); } -int parseArguments(int ac, wchar_t ** av, po::variables_map& vm, printInfoStruct& printInfo) +INT parseArguments(INT ac, WCHAR ** av, po::variables_map& vm, printInfoStruct& printInfo) { - wchar_t namePath[MAX_PATH]; + WCHAR namePath[MAX_PATH]; GetModuleFileName(NULL, namePath, MAX_PATH); - wchar_t *progName = PathFindFileName(namePath); + WCHAR *progName = PathFindFileName(namePath); po::options_description desc; desc.add_options() - ("help,h", "print help message and exit") - ("version,V", "print version and exit") + ("help,h", "Print help message and exit") + ("version,V", "Print version and exit") ("debug,d", "Verbose/Debug output") - ("warning,w", po::wvalue(), "warning threshold") - ("critical,c", po::wvalue(), "critical threshold") - ("unit,u", po::wvalue(), "the unit to use for display (default MB)") + ("warning,w", po::wvalue(), "Warning threshold") + ("critical,c", po::wvalue(), "Critical threshold") + ("unit,u", po::wvalue(), "The unit to use for display (default MB)") ; - po::basic_command_line_parser parser(ac, av); + po::basic_command_line_parser parser(ac, av); try { po::store( @@ -90,16 +74,16 @@ int parseArguments(int ac, wchar_t ** av, po::variables_map& vm, printInfoStruct vm); vm.notify(); } catch (std::exception& e) { - cout << e.what() << endl << desc << endl; + std::cout << e.what() << '\n' << desc << '\n'; return 3; } if (vm.count("help")) { - wcout << progName << " Help\n\tVersion: " << VERSION << endl; + std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n'; wprintf( L"%s is a simple program to check a machines physical memory.\n" L"You can use the following options to define its behaviour:\n\n", progName); - cout << desc; + std::cout << desc; wprintf( L"\nIt will then output a string looking something like this:\n\n" L"\tMEMORY WARNING - 50%% free | memory=2024MB;3000;500;0;4096\n\n" @@ -131,18 +115,18 @@ int parseArguments(int ac, wchar_t ** av, po::variables_map& vm, printInfoStruct L"to end with a percentage sign.\n\n" L"All of these options work with the critical threshold \"-c\" too.\n" , progName); - cout << endl; + std::cout << '\n'; return 0; } if (vm.count("version")) - wcout << L"Version: " << VERSION << endl; + std::wcout << L"Version: " << VERSION << '\n'; if (vm.count("warning")) { try { - printInfo.warn = threshold(vm["warning"].as()); + printInfo.warn = threshold(vm["warning"].as()); } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } printInfo.warn.legal = !printInfo.warn.legal; @@ -150,9 +134,9 @@ int parseArguments(int ac, wchar_t ** av, po::variables_map& vm, printInfoStruct if (vm.count("critical")) { try { - printInfo.crit = threshold(vm["critical"].as()); + printInfo.crit = threshold(vm["critical"].as()); } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } printInfo.crit.legal = !printInfo.crit.legal; @@ -163,9 +147,9 @@ int parseArguments(int ac, wchar_t ** av, po::variables_map& vm, printInfoStruct if (vm.count("unit")) { try { - printInfo.unit = parseBUnit(vm["unit"].as()); + printInfo.unit = parseBUnit(vm["unit"].as()); } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } } @@ -173,10 +157,10 @@ int parseArguments(int ac, wchar_t ** av, po::variables_map& vm, printInfoStruct return -1; } -int printOutput(printInfoStruct& printInfo) +INT printOutput(printInfoStruct& printInfo) { if (debug) - wcout << L"Constructing output string" << endl; + std::wcout << L"Constructing output string" << '\n'; state state = OK; double fswap = ((double)printInfo.aRam / (double)printInfo.tRam) * 100.0; @@ -189,29 +173,29 @@ int printOutput(printInfoStruct& printInfo) switch (state) { case OK: - wcout << L"MEMORY OK - " << fswap << L"% free | memory=" << printInfo.aRam << BunitStr(printInfo.unit) << L";" + std::wcout << L"MEMORY OK - " << fswap << L"% free | memory=" << printInfo.aRam << BunitStr(printInfo.unit) << L";" << printInfo.warn.pString(printInfo.tRam) << L";" << printInfo.crit.pString(printInfo.tRam) - << L";0;" << printInfo.tRam << endl; + << L";0;" << printInfo.tRam << '\n'; break; case WARNING: - wcout << L"MEMORY WARNING - " << fswap << L"% free | memory=" << printInfo.aRam << BunitStr(printInfo.unit) << L";" + std::wcout << L"MEMORY WARNING - " << fswap << L"% free | memory=" << printInfo.aRam << BunitStr(printInfo.unit) << L";" << printInfo.warn.pString(printInfo.tRam) << L";" << printInfo.crit.pString(printInfo.tRam) - << L";0;" << printInfo.tRam << endl; + << L";0;" << printInfo.tRam << '\n'; break; case CRITICAL: - wcout << L"MEMORY CRITICAL - " << fswap << L"% free | memory=" << printInfo.aRam << BunitStr(printInfo.unit) << L";" + std::wcout << L"MEMORY CRITICAL - " << fswap << L"% free | memory=" << printInfo.aRam << BunitStr(printInfo.unit) << L";" << printInfo.warn.pString(printInfo.tRam) << L";" << printInfo.crit.pString(printInfo.tRam) - << L";0;" << printInfo.tRam << endl; + << L";0;" << printInfo.tRam << '\n'; break; } return state; } -int check_memory(printInfoStruct& printInfo) +INT check_memory(printInfoStruct& printInfo) { if (debug) - wcout << L"Accessing memory statistics via MemoryStatus" << endl; + std::wcout << L"Accessing memory statistics via MemoryStatus" << '\n'; _MEMORYSTATUSEX *pMemBuf = new _MEMORYSTATUSEX; @@ -223,8 +207,8 @@ int check_memory(printInfoStruct& printInfo) printInfo.aRam = round(pMemBuf->ullAvailPhys / pow(1024.0, printInfo.unit)); if (debug) - wcout << L"Found pMemBuf->dwTotalPhys: " << pMemBuf->ullTotalPhys << endl - << L"Found pMemBuf->dwAvailPhys: " << pMemBuf->ullAvailPhys << endl; + std::wcout << L"Found pMemBuf->dwTotalPhys: " << pMemBuf->ullTotalPhys << '\n' + << L"Found pMemBuf->dwAvailPhys: " << pMemBuf->ullAvailPhys << '\n'; delete pMemBuf; diff --git a/plugins/check_memory.h b/plugins/check_memory.h new file mode 100644 index 000000000..8940a387c --- /dev/null +++ b/plugins/check_memory.h @@ -0,0 +1,37 @@ +/****************************************************************************** + * Icinga 2 * + * Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.org) * + * * + * This program is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2 * + * of the License, or (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the Free Software Foundation * + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * + ******************************************************************************/ + +#ifndef CHECK_MEMORY_H +#define CHECK_MEMORY_H + +#include "thresholds.h" +#include "boost/program_options.hpp" + +struct printInfoStruct +{ + threshold warn, crit; + DWORDLONG tRam, aRam; + Bunit unit = BunitMB; +}; + +INT parseArguments(INT, WCHAR **, boost::program_options::variables_map&, printInfoStruct&); +INT printOutput(printInfoStruct&); +INT check_memory(printInfoStruct&); + +#endif // !CHECK_MEMORY_H diff --git a/plugins/check_network.cpp b/plugins/check_network.cpp index dbed25d0a..d1e9d1937 100644 --- a/plugins/check_network.cpp +++ b/plugins/check_network.cpp @@ -16,63 +16,54 @@ * along with this program; if not, write to the Free Software Foundation * * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * ******************************************************************************/ + +#define WIN32_LEAN_AND_MEAN + #include #include #include #include #include +#include +#include -#include "thresholds.h" +#include -#include "boost/program_options.hpp" +#include "check_network.h" + +#define VERSION 1.1 -#define VERSION 1.0 namespace po = boost::program_options; -using std::endl; using std::vector; using std::wstring; -using std::wcout; using std::cout; - static BOOL debug = FALSE; -struct nInterface +INT wmain(INT argc, WCHAR **argv) { - wstring name; - long BytesInSec, BytesOutSec; - nInterface(wstring p) - : name(p) - {} -}; - -struct printInfoStruct -{ - threshold warn, crit; -}; - -static int parseArguments(int, TCHAR **, po::variables_map&, printInfoStruct&); -static int printOutput(printInfoStruct&, const vector&); -static int check_network(vector&); - -int wmain(int argc, wchar_t **argv) -{ - vector vInterfaces; - printInfoStruct printInfo{ }; + std::vector vInterfaces; + std::map mapNames; + printInfoStruct printInfo{}; po::variables_map vm; - int ret = parseArguments(argc, argv, vm, printInfo); + + INT ret = parseArguments(argc, argv, vm, printInfo); + if (ret != -1) return ret; + if (!mapSystemNamesToFamiliarNames(mapNames)) + return 3; + ret = check_network(vInterfaces); if (ret != -1) return ret; - return printOutput(printInfo, vInterfaces); + return printOutput(printInfo, vInterfaces, mapNames); } -int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& printInfo) +INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo) { - wchar_t namePath[MAX_PATH]; + WCHAR namePath[MAX_PATH]; GetModuleFileName(NULL, namePath, MAX_PATH); - wchar_t *progName = PathFindFileName(namePath); + WCHAR *progName = PathFindFileName(namePath); po::options_description desc("Options"); @@ -80,11 +71,11 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& ("help,h", "print usage and exit") ("version,V", "print version and exit") ("debug,d", "Verbose/Debug output") - ("warning,w", po::wvalue(), "warning value") - ("critical,c", po::wvalue(), "critical value") + ("warning,w", po::wvalue(), "warning value") + ("critical,c", po::wvalue(), "critical value") ; - po::basic_command_line_parser parser(ac, av); + po::basic_command_line_parser parser(ac, av); try { po::store( @@ -97,20 +88,20 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& vm); vm.notify(); } catch (std::exception& e) { - cout << e.what() << endl << desc << endl; + std::cout << e.what() << '\n' << desc << '\n'; return 3; } if (vm.count("help")) { - wcout << progName << " Help\n\tVersion: " << VERSION << endl; + std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n'; wprintf( L"%s is a simple program to check a machines network performance.\n" L"You can use the following options to define its behaviour:\n\n", progName); - cout << desc; + std::cout << desc; wprintf( L"\nIt will then output a string looking something like this:\n\n" L"\tNETWORK WARNING 1131B/s | network=1131B/s;1000;7000;0\n\n" - L"\"DISK\" being the type of the check, \"WARNING\" the returned status\n" + L"\"NETWORK\" being the type of the check, \"WARNING\" the returned status\n" L"and \"1131B/s\" is the returned value.\n" L"The performance data is found behind the \"|\", in order:\n" L"returned value, warning threshold, critical threshold, minimal value and,\n" @@ -140,26 +131,26 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& L"to end with a percentage sign.\n\n" L"All of these options work with the critical threshold \"-c\" too." , progName); - cout << endl; + std::cout << '\n'; return 0; } if (vm.count("version")) - cout << "Version: " << VERSION << endl; + std::cout << "Version: " << VERSION << '\n'; if (vm.count("warning")) { try { - printInfo.warn = threshold(vm["warning"].as()); + printInfo.warn = threshold(vm["warning"].as()); } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } } if (vm.count("critical")) { try { - printInfo.crit = threshold(vm["critical"].as()); + printInfo.crit = threshold(vm["critical"].as()); } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } } @@ -170,47 +161,62 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& return -1; } -int printOutput(printInfoStruct& printInfo, const vector& vInterfaces) +INT printOutput(printInfoStruct& printInfo, CONST std::vector& vInterfaces, CONST std::map& mapNames) { if (debug) - wcout << L"Constructing output string" << endl; + std::wcout << L"Constructing output string" << '\n'; long tIn = 0, tOut = 0; std::wstringstream tss, perfDataFirst; state state = OK; - for (vector::const_iterator it = vInterfaces.begin(); it != vInterfaces.end(); ++it) { + std::map::const_iterator mapIt; + std::wstring wsFriendlyName; + + for (std::vector::const_iterator it = vInterfaces.begin(); it != vInterfaces.end(); ++it) { tIn += it->BytesInSec; tOut += it->BytesOutSec; - tss << L"netI=\"" << it->name << L"\";in=" << it->BytesInSec << L"B/s;out=" << it->BytesOutSec << L"B/s "; + if (debug) + std::wcout << "Getting friendly name of " << it->name << '\n'; + mapIt = mapNames.find(it->name); + if (mapIt != mapNames.end()) { + if (debug) + std::wcout << "\tIs " << mapIt->second << '\n'; + wsFriendlyName = mapIt->second; + } else { + if (debug) + std::wcout << "\tNo friendly name found, using adapter name\n"; + wsFriendlyName = it->name; + } + tss << L"netI=\"" << wsFriendlyName << L"\";in=" << it->BytesInSec << "B/s;out=" << it->BytesOutSec << L"B/s "; } if (printInfo.warn.rend(tIn + tOut)) state = WARNING; if (printInfo.crit.rend(tIn + tOut)) state = CRITICAL; - + perfDataFirst << L"network=" << tIn + tOut << L"B/s;" << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";" << L"0; "; switch (state) { case OK: - wcout << L"NETWORK OK " << tIn + tOut << L"B/s | " << perfDataFirst.str() << tss.str() << endl; + std::wcout << L"NETWORK OK " << tIn + tOut << L"B/s | " << perfDataFirst.str() << tss.str() << '\n'; break; case WARNING: - wcout << L"NETWORK WARNING " << tIn + tOut << L"B/s | " << perfDataFirst.str() << tss.str() << endl; + std::wcout << L"NETWORK WARNING " << tIn + tOut << L"B/s | " << perfDataFirst.str() << tss.str() << '\n'; break; case CRITICAL: - wcout << L"NETWORK CRITICAL " << tIn + tOut << L"B/s | " << perfDataFirst.str() << tss.str() << endl; + std::wcout << L"NETWORK CRITICAL " << tIn + tOut << L"B/s | " << perfDataFirst.str() << tss.str() << '\n'; break; } return state; } -int check_network(vector & vInterfaces) +INT check_network(std::vector & vInterfaces) { - const wchar_t *perfIn = L"\\Network Interface(*)\\Bytes Received/sec"; - const wchar_t *perfOut = L"\\Network Interface(*)\\Bytes Sent/sec"; + CONST WCHAR *perfIn = L"\\Network Interface(*)\\Bytes Received/sec"; + CONST WCHAR *perfOut = L"\\Network Interface(*)\\Bytes Sent/sec"; PDH_HQUERY phQuery = NULL; PDH_HCOUNTER phCounterIn, phCounterOut; @@ -219,7 +225,7 @@ int check_network(vector & vInterfaces) PDH_STATUS err; if (debug) - wcout << L"Creating Query and adding counters" << endl; + std::wcout << L"Creating Query and adding counters" << '\n'; err = PdhOpenQuery(NULL, NULL, &phQuery); if (!SUCCEEDED(err)) @@ -234,26 +240,26 @@ int check_network(vector & vInterfaces) goto die; if (debug) - wcout << L"Collecting first batch of query data" << endl; + std::wcout << L"Collecting first batch of query data" << '\n'; err = PdhCollectQueryData(phQuery); if (!SUCCEEDED(err)) goto die; if (debug) - wcout << L"Sleep for one second" << endl; + std::wcout << L"Sleep for one second" << '\n'; Sleep(1000); if (debug) - wcout << L"Collecting second batch of query data" << endl; + std::wcout << L"Collecting second batch of query data" << '\n'; err = PdhCollectQueryData(phQuery); if (!SUCCEEDED(err)) goto die; if (debug) - wcout << L"Creating formatted counter arrays" << endl; + std::wcout << L"Creating formatted counter arrays" << '\n'; err = PdhGetFormattedCounterArray(phCounterIn, PDH_FMT_LONG, &dwBufferSizeIn, &dwItemCount, pDisplayValuesIn); if (err == PDH_MORE_DATA || SUCCEEDED(err)) @@ -276,18 +282,18 @@ int check_network(vector & vInterfaces) goto die; if (debug) - wcout << L"Going over counter array" << endl; + std::wcout << L"Going over counter array" << '\n'; for (DWORD i = 0; i < dwItemCount; i++) { - nInterface *iface = new nInterface(wstring(pDisplayValuesIn[i].szName)); + nInterface *iface = new nInterface(std::wstring(pDisplayValuesIn[i].szName)); iface->BytesInSec = pDisplayValuesIn[i].FmtValue.longValue; iface->BytesOutSec = pDisplayValuesOut[i].FmtValue.longValue; vInterfaces.push_back(*iface); if (debug) - wcout << L"Collected interface " << pDisplayValuesIn[i].szName << endl; + std::wcout << L"Collected interface " << pDisplayValuesIn[i].szName << '\n'; } if (debug) - wcout << L"Finished collection. Cleaning up and returning" << endl; + std::wcout << L"Finished collection. Cleaning up and returning" << '\n'; if (phQuery) PdhCloseQuery(phQuery); @@ -305,4 +311,62 @@ die: if (pDisplayValuesOut) delete reinterpret_cast(pDisplayValuesOut); return 3; -} \ No newline at end of file +} + +BOOL mapSystemNamesToFamiliarNames(std::map& mapNames) +{ + DWORD dwSize = 0, dwRetVal = 0; + + ULONG family = AF_UNSPEC, flags = GAA_FLAG_INCLUDE_PREFIX, + outBufLen = 0, Iterations = 0; + LPVOID lpMsgBuf = NULL; + + PIP_ADAPTER_ADDRESSES pAddresses = NULL; + PIP_ADAPTER_ADDRESSES pCurrAddresses = NULL; + /* + PIP_ADAPTER_UNICAST_ADDRESS pUnicast = NULL; + PIP_ADAPTER_ANYCAST_ADDRESS pAnycast = NULL; + PIP_ADAPTER_MULTICAST_ADDRESS pMulticast = NULL; + PIP_ADAPTER_DNS_SERVER_ADDRESS pDnsServer = NULL; + PIP_ADAPTER_PREFIX pPrefix = NULL; + */ + outBufLen = 15000; //15KB as suggestet by msdn of GetAdaptersAddresses + + if (debug) + std::wcout << "Mapping adapter system names to friendly names\n"; + + do { + pAddresses = reinterpret_cast(new BYTE[outBufLen]); + + dwRetVal = GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen); + + if (dwRetVal == ERROR_BUFFER_OVERFLOW) { + delete[]pAddresses; + pAddresses = NULL; + } else + break; + } while (++Iterations < 3); + + if (dwRetVal != NO_ERROR) { + std::wcout << "Failed to collect friendly adapter names\n"; + delete[]pAddresses; + return FALSE; + } + + pCurrAddresses = pAddresses; + std::wstringstream wssAdapterName; + std::wstringstream wssFriendlyName; + for (pCurrAddresses = pAddresses; pCurrAddresses; pCurrAddresses = pCurrAddresses->Next) { + wssAdapterName.str(std::wstring()); + wssFriendlyName.str(std::wstring()); + wssAdapterName << pCurrAddresses->Description; + wssFriendlyName << pCurrAddresses->FriendlyName; + if (debug) + std::wcout << "Got: " << wssAdapterName.str() << " -- " << wssFriendlyName.str() << '\n'; + + mapNames.insert(std::pair(wssAdapterName.str(), wssFriendlyName.str())); + } + + delete[]pAddresses; + return TRUE; +} diff --git a/plugins/check_network.h b/plugins/check_network.h new file mode 100644 index 000000000..b560bd8dc --- /dev/null +++ b/plugins/check_network.h @@ -0,0 +1,47 @@ +/****************************************************************************** + * Icinga 2 * + * Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.org) * + * * + * This program is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2 * + * of the License, or (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the Free Software Foundation * + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * + ******************************************************************************/ + +#ifndef CHECK_NETWORK_H +#define CHECK_NETWORK_H +#include + +#include "thresholds.h" +#include "boost/program_options.hpp" + +struct nInterface +{ + std::wstring name; + LONG BytesInSec, BytesOutSec; + nInterface(std::wstring p) + : name(p) + { + } +}; + +struct printInfoStruct +{ + threshold warn, crit; +}; + +INT parseArguments(INT, WCHAR **, boost::program_options::variables_map&, printInfoStruct&); +INT printOutput(printInfoStruct&, CONST std::vector&, CONST std::map&); +INT check_network(std::vector&); +BOOL mapSystemNamesToFamiliarNames(std::map&); + +#endif // !CHECK_NETWORK_H diff --git a/plugins/check_ping.cpp b/plugins/check_ping.cpp index 99b7c8714..96cc37e78 100644 --- a/plugins/check_ping.cpp +++ b/plugins/check_ping.cpp @@ -31,39 +31,15 @@ #include -#include "thresholds.h" -#include "boost/program_options.hpp" +#include "check_ping.h" #define VERSION 1.0 namespace po = boost::program_options; -using std::cout; using std::endl; using std::wcout; -using std::wstring; using std::string; static BOOL debug = FALSE; -struct response -{ - double avg; - UINT pMin = 0, pMax = 0, dropped = 0; -}; - -struct printInfoStruct -{ - threshold warn, crit; - threshold wpl, cpl; - wstring host; - BOOL ipv4 = TRUE; - DWORD timeout = 1000; - int num = 5; -}; - -static int printOutput(printInfoStruct&, response&); -static int parseArguments(int, wchar_t **, po::variables_map&, printInfoStruct&); -static int check_ping4(const printInfoStruct&, response&); -static int check_ping6(const printInfoStruct&, response&); - -int wmain(int argc, wchar_t **argv) +INT wmain(INT argc, WCHAR **argv) { po::variables_map vm; printInfoStruct printInfo; @@ -88,28 +64,28 @@ int wmain(int argc, wchar_t **argv) return printOutput(printInfo, response); } -int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& printInfo) +INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo) { - wchar_t namePath[MAX_PATH]; + WCHAR namePath[MAX_PATH]; GetModuleFileName(NULL, namePath, MAX_PATH); - wchar_t *progName = PathFindFileName(namePath); + WCHAR *progName = PathFindFileName(namePath); po::options_description desc; desc.add_options() - ("help,h", "print usage message and exit") - ("version,V", "print version and exit") + ("help,h", "Print usage message and exit") + ("version,V", "Print version and exit") ("debug,d", "Verbose/Debug output") - ("host,H", po::wvalue()->required(), "host ip to ping") - (",4", "--host is an ipv4 address (default)") - (",6", "--host is an ipv6 address") - ("timeout,T", po::value(), "specify timeout for requests in ms (default=1000)") - ("ncount,n", po::value(), "declare ping count (default=5)") - ("warning,w", po::wvalue(), "warning values: rtt,package loss") - ("critical,c", po::wvalue(), "critical values: rtt,package loss") + ("host,H", po::wvalue()->required(), "Host ip to ping") + (",4", "--Host is an ipv4 address (default)") + (",6", "--Host is an ipv6 address") + ("timeout,t", po::value(), "Specify timeout for requests in ms (default=1000)") + ("packets,p", po::value(), "Declare ping count (default=5)") + ("warning,w", po::wvalue(), "Warning values: rtt,package loss") + ("critical,c", po::wvalue(), "Critical values: rtt,package loss") ; - po::basic_command_line_parser parser(ac, av); + po::basic_command_line_parser parser(ac, av); try { po::store( @@ -124,16 +100,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& vm); vm.notify(); } catch (std::exception& e) { - cout << e.what() << endl << desc << endl; + std::cout << e.what() << '\n' << desc << '\n'; return 3; } if (vm.count("help")) { - wcout << progName << " Help\n\tVersion: " << VERSION << endl; + std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n'; wprintf( L"%s is a simple program to ping an ip4 address.\n" L"You can use the following options to define its behaviour:\n\n", progName); - cout << desc; + std::cout << desc; wprintf( L"\nIt will take at least timeout times number of pings to run\n" L"Then it will output a string looking something like this:\n\n" @@ -165,65 +141,65 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& L"to end with a percentage sign.\n\n" L"All of these options work with the critical threshold \"-c\" too." , progName); - cout << endl; + std::cout << '\n'; return 0; } if (vm.count("version")) { - cout << progName << " Version: " << VERSION << endl; + std::cout << progName << " Version: " << VERSION << '\n'; return 0; } if (vm.count("-4") && vm.count("-6")) { - cout << "Conflicting options \"4\" and \"6\"" << endl; + std::cout << "Conflicting options \"4\" and \"6\"" << '\n'; return 3; } if (vm.count("warning")) { - std::vector sVec = splitMultiOptions(vm["warning"].as()); + std::vector sVec = splitMultiOptions(vm["warning"].as()); if (sVec.size() != 2) { - cout << "Wrong format for warning thresholds" << endl; + std::cout << "Wrong format for warning thresholds" << '\n'; return 3; } try { printInfo.warn = threshold(*sVec.begin()); printInfo.wpl = threshold(sVec.back()); if (!printInfo.wpl.perc) { - cout << "Packet loss must be percentage" << endl; + std::cout << "Packet loss must be percentage" << '\n'; return 3; } } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } } if (vm.count("critical")) { - std::vector sVec = splitMultiOptions(vm["critical"].as()); + std::vector sVec = splitMultiOptions(vm["critical"].as()); if (sVec.size() != 2) { - cout << "Wrong format for critical thresholds" << endl; + std::cout << "Wrong format for critical thresholds" << '\n'; return 3; } try { printInfo.crit = threshold(*sVec.begin()); printInfo.cpl = threshold(sVec.back()); if (!printInfo.wpl.perc) { - cout << "Packet loss must be percentage" << endl; + std::cout << "Packet loss must be percentage" << '\n'; return 3; } } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } } if (vm.count("timeout")) - printInfo.timeout = vm["timeout"].as(); + printInfo.timeout = vm["timeout"].as(); if (vm.count("count")) - printInfo.num = vm["count"].as(); + printInfo.num = vm["count"].as(); if (vm.count("-6")) printInfo.ipv4 = FALSE; - printInfo.host = vm["host"].as(); + printInfo.host = vm["host"].as(); if (vm.count("debug")) debug = TRUE; @@ -231,10 +207,10 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& return -1; } -int printOutput(printInfoStruct& printInfo, response& response) +INT printOutput(printInfoStruct& printInfo, response& response) { if (debug) - wcout << L"Constructing output string" << endl; + std::wcout << L"Constructing output string" << '\n'; state state = OK; @@ -252,51 +228,51 @@ int printOutput(printInfoStruct& printInfo, response& response) << printInfo.wpl.pString() << ";" << printInfo.cpl.pString() << ";0;100"; if (response.dropped == printInfo.num) { - wcout << L"PING CRITICAL ALL CONNECTIONS DROPPED | " << perf.str() << endl; + std::wcout << L"PING CRITICAL ALL CONNECTIONS DROPPED | " << perf.str() << '\n'; return 3; } switch (state) { case OK: - wcout << L"PING OK RTA: " << response.avg << L"ms Packet loss: " << removeZero(plp) << "% | " << perf.str() << endl; + std::wcout << L"PING OK RTA: " << response.avg << L"ms Packet loss: " << removeZero(plp) << "% | " << perf.str() << '\n'; break; case WARNING: - wcout << L"PING WARNING RTA: " << response.avg << L"ms Packet loss: " << removeZero(plp) << "% | " << perf.str() << endl; + std::wcout << L"PING WARNING RTA: " << response.avg << L"ms Packet loss: " << removeZero(plp) << "% | " << perf.str() << '\n'; break; case CRITICAL: - wcout << L"PING CRITICAL RTA: " << response.avg << L"ms Packet loss: " << removeZero(plp) << "% | " << perf.str() << endl; + std::wcout << L"PING CRITICAL RTA: " << response.avg << L"ms Packet loss: " << removeZero(plp) << "% | " << perf.str() << '\n'; break; } return state; } -int check_ping4(const printInfoStruct& pi, response& response) +INT check_ping4(const printInfoStruct& pi, response& response) { in_addr ipDest4; HANDLE hIcmp; DWORD dwRet = 0, dwRepSize = 0; LPVOID repBuf = NULL; UINT rtt = 0; - int num = pi.num; + INT num = pi.num; LARGE_INTEGER frequency, timer1, timer2; LPCWSTR term; if (debug) - wcout << L"Parsing ip address" << endl; + std::wcout << L"Parsing ip address" << '\n'; if (RtlIpv4StringToAddress(pi.host.c_str(), TRUE, &term, &ipDest4) == STATUS_INVALID_PARAMETER) { - std::wcout << pi.host << " is not a valid ip address" << std::endl; + std::wcout << pi.host << " is not a valid ip address\n"; return 3; } if (*term != L'\0') { - std::wcout << pi.host << " is not a valid ip address" << std::endl; + std::wcout << pi.host << " is not a valid ip address\n"; return 3; } if (debug) - wcout << L"Creating Icmp File" << endl; + std::wcout << L"Creating Icmp File\n"; if ((hIcmp = IcmpCreateFile()) == INVALID_HANDLE_VALUE) goto die; @@ -312,30 +288,30 @@ int check_ping4(const printInfoStruct& pi, response& response) QueryPerformanceCounter(&timer1); if (debug) - wcout << L"Sending Icmp echo" << endl; + std::wcout << L"Sending Icmp echo\n"; if (!IcmpSendEcho2(hIcmp, NULL, NULL, NULL, ipDest4.S_un.S_addr, NULL, 0, NULL, repBuf, dwRepSize, pi.timeout)) { response.dropped++; if (debug) - wcout << L"Dropped: Response was 0" << endl; + std::wcout << L"Dropped: Response was 0" << '\n'; continue; } if (debug) - wcout << "Ping recieved" << endl; + std::wcout << "Ping recieved" << '\n'; PICMP_ECHO_REPLY pEchoReply = static_cast(repBuf); if (pEchoReply->Status != IP_SUCCESS) { response.dropped++; if (debug) - wcout << L"Dropped: echo reply status " << pEchoReply->Status << endl; + std::wcout << L"Dropped: echo reply status " << pEchoReply->Status << '\n'; continue; } if (debug) - wcout << L"Recorded rtt of " << pEchoReply->RoundTripTime << endl; + std::wcout << L"Recorded rtt of " << pEchoReply->RoundTripTime << '\n'; rtt += pEchoReply->RoundTripTime; if (response.pMin == 0 || pEchoReply->RoundTripTime < response.pMin) @@ -349,7 +325,7 @@ int check_ping4(const printInfoStruct& pi, response& response) } while (--num); if (debug) - wcout << L"All pings sent. Cleaning up and returning" << endl; + std::wcout << L"All pings sent. Cleaning up and returning" << '\n'; if (hIcmp) IcmpCloseHandle(hIcmp); @@ -370,9 +346,8 @@ die: return 3; } -int check_ping6(const printInfoStruct& pi, response& response) +INT check_ping6(const printInfoStruct& pi, response& response) { - PCWSTR term; sockaddr_in6 ipDest6, ipSource6; IP_OPTION_INFORMATION ipInfo = { 30, 0, 0, 0, NULL }; DWORD dwRepSize = sizeof(ICMPV6_ECHO_REPLY) + 8; @@ -380,14 +355,14 @@ int check_ping6(const printInfoStruct& pi, response& response) HANDLE hIcmp = NULL; LARGE_INTEGER frequency, timer1, timer2; - int num = pi.num; + INT num = pi.num; UINT rtt = 0; if (debug) - wcout << L"Parsing ip address" << endl; + std::wcout << L"Parsing ip address" << '\n'; if (RtlIpv6StringToAddressEx(pi.host.c_str(), &ipDest6.sin6_addr, &ipDest6.sin6_scope_id, &ipDest6.sin6_port)) { - std::wcout << pi.host << " is not a valid ipv6 address" << std::endl; + std::wcout << pi.host << " is not a valid ipv6 address" << '\n'; return 3; } @@ -399,7 +374,7 @@ int check_ping6(const printInfoStruct& pi, response& response) ipSource6.sin6_port = 0; if (debug) - wcout << L"Creating Icmp File" << endl; + std::wcout << L"Creating Icmp File" << '\n'; hIcmp = Icmp6CreateFile(); if (hIcmp == INVALID_HANDLE_VALUE) { @@ -411,18 +386,18 @@ int check_ping6(const printInfoStruct& pi, response& response) QueryPerformanceCounter(&timer1); if (debug) - wcout << L"Sending Icmp echo" << endl; + std::wcout << L"Sending Icmp echo" << '\n'; if (!Icmp6SendEcho2(hIcmp, NULL, NULL, NULL, &ipSource6, &ipDest6, NULL, 0, &ipInfo, repBuf, dwRepSize, pi.timeout)) { response.dropped++; if (debug) - wcout << L"Dropped: Response was 0" << endl; + std::wcout << L"Dropped: Response was 0" << '\n'; continue; } if (debug) - wcout << "Ping recieved" << endl; + std::wcout << "Ping recieved" << '\n'; Icmp6ParseReplies(repBuf, dwRepSize); @@ -431,14 +406,14 @@ int check_ping6(const printInfoStruct& pi, response& response) if (pEchoReply->Status != IP_SUCCESS) { response.dropped++; if (debug) - wcout << L"Dropped: echo reply status " << pEchoReply->Status << endl; + std::wcout << L"Dropped: echo reply status " << pEchoReply->Status << '\n'; continue; } rtt += pEchoReply->RoundTripTime; if (debug) - wcout << L"Recorded rtt of " << pEchoReply->RoundTripTime << endl; + std::wcout << L"Recorded rtt of " << pEchoReply->RoundTripTime << '\n'; if (response.pMin == 0 || pEchoReply->RoundTripTime < response.pMin) response.pMin = pEchoReply->RoundTripTime; @@ -451,7 +426,7 @@ int check_ping6(const printInfoStruct& pi, response& response) } while (--num); if (debug) - wcout << L"All pings sent. Cleaning up and returning" << endl; + std::wcout << L"All pings sent. Cleaning up and returning" << '\n'; if (hIcmp) IcmpCloseHandle(hIcmp); diff --git a/plugins/check_ping.h b/plugins/check_ping.h new file mode 100644 index 000000000..77bac1e9d --- /dev/null +++ b/plugins/check_ping.h @@ -0,0 +1,46 @@ +/****************************************************************************** + * Icinga 2 * + * Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.org) * + * * + * This program is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2 * + * of the License, or (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the Free Software Foundation * + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * + ******************************************************************************/ + +#ifndef CHECK_PING_H +#define CHECK_PING_H +#include "thresholds.h" +#include "boost/program_options.hpp" + +struct response +{ + DOUBLE avg; + UINT pMin = 0, pMax = 0, dropped = 0; +}; + +struct printInfoStruct +{ + threshold warn, crit; + threshold wpl, cpl; + std::wstring host; + BOOL ipv4 = TRUE; + DWORD timeout = 1000; + INT num = 5; +}; + +INT printOutput(printInfoStruct&, response&); +INT parseArguments(INT, WCHAR **, boost::program_options::variables_map&, printInfoStruct&); +INT check_ping4(CONST printInfoStruct&, response&); +INT check_ping6(CONST printInfoStruct&, response&); + +#endif // !CHECK_PING_H diff --git a/plugins/check_procs.cpp b/plugins/check_procs.cpp index 8747cb66c..679f53e25 100644 --- a/plugins/check_procs.cpp +++ b/plugins/check_procs.cpp @@ -21,36 +21,20 @@ #include #include -#include "thresholds.h" - -#include "boost/program_options.hpp" +#include "check_procs.h" #define VERSION 1.0 namespace po = boost::program_options; -using std::endl; using std::wstring; using std::wcout; -using std::cout; - static BOOL debug = FALSE; -struct printInfoStruct -{ - threshold warn, crit; - wstring user; -}; - -static int countProcs(); -static int countProcs(const wstring); -static int parseArguments(int, wchar_t **, po::variables_map&, printInfoStruct&); -static int printOutput(const int, printInfoStruct&); - -int wmain(int argc, wchar_t **argv) +INT wmain(INT argc, WCHAR **argv) { po::variables_map vm; printInfoStruct printInfo = { }; - int r = parseArguments(argc, argv, vm, printInfo); + INT r = parseArguments(argc, argv, vm, printInfo); if (r != -1) return r; @@ -61,24 +45,24 @@ int wmain(int argc, wchar_t **argv) return printOutput(countProcs(), printInfo); } -int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& printInfo) +INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo) { - wchar_t namePath[MAX_PATH]; + WCHAR namePath[MAX_PATH]; GetModuleFileName(NULL, namePath, MAX_PATH); - wchar_t *progName = PathFindFileName(namePath); + WCHAR *progName = PathFindFileName(namePath); po::options_description desc; desc.add_options() - ("help,h", "print help message and exit") - ("version,V", "print version and exit") + ("help,h", "Print help message and exit") + ("version,V", "Print version and exit") ("debug,d", "Verbose/Debug output") - ("user,u", po::wvalue(), "count only processes by user [arg]") - ("warning,w", po::wvalue(), "warning threshold") - ("critical,c", po::wvalue(), "critical threshold") + ("user,u", po::wvalue(), "Count only processes of user") + ("warning,w", po::wvalue(), "Warning threshold") + ("critical,c", po::wvalue(), "Critical threshold") ; - po::basic_command_line_parser parser(ac, av); + po::basic_command_line_parser parser(ac, av); try { po::store( @@ -91,16 +75,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& vm); vm.notify(); } catch (std::exception& e) { - std::cout << e.what() << endl << desc << endl; + std::cout << e.what() << '\n' << desc << '\n'; return 3; } if (vm.count("help")) { - wcout << progName << " Help\n\tVersion: " << VERSION << endl; + std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n'; wprintf( L"%s is a simple program to check a machines processes.\n" L"You can use the following options to define its behaviour:\n\n", progName); - cout << desc; + std::cout << desc; wprintf( L"\nIt will then output a string looking something like this:\n\n" L"\tPROCS WARNING 67 | load=67;50;90;0\n\n" @@ -133,34 +117,34 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& L"to end with a percentage sign.\n\n" L"All of these options work with the critical threshold \"-c\" too." , progName); - cout << endl; + std::cout << '\n'; return 0; } if (vm.count("version")) { - std::cout << "Version: " << VERSION << endl; + std::wcout << "Version: " << VERSION << '\n'; return 0; } if (vm.count("warning")) { try { - printInfo.warn = threshold(vm["warning"].as()); + printInfo.warn = threshold(vm["warning"].as()); } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } } if (vm.count("critical")) { try { - printInfo.crit = threshold(vm["critical"].as()); + printInfo.crit = threshold(vm["critical"].as()); } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } } if (vm.count("user")) - printInfo.user = vm["user"].as(); + printInfo.user = vm["user"].as(); if (vm.count("debug")) debug = TRUE; @@ -168,10 +152,10 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& return -1; } -int printOutput(const int numProcs, printInfoStruct& printInfo) +INT printOutput(CONST INT numProcs, printInfoStruct& printInfo) { if (debug) - wcout << L"Constructing output string" << endl; + std::wcout << L"Constructing output string" << '\n'; state state = OK; @@ -181,38 +165,38 @@ int printOutput(const int numProcs, printInfoStruct& printInfo) if (printInfo.crit.rend(numProcs)) state = CRITICAL; - wstring user = L""; + std::wstring user = L""; if (!printInfo.user.empty()) user.append(L" processes of user ").append(printInfo.user); switch (state) { case OK: - wcout << L"PROCS OK " << numProcs << user << L" | procs=" << numProcs << L";" - << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << endl; + std::wcout << L"PROCS OK " << numProcs << user << L" | procs=" << numProcs << L";" + << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << '\n'; break; case WARNING: - wcout << L"PROCS WARNING " << numProcs << user << L" | procs=" << numProcs << L";" - << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << endl; + std::wcout << L"PROCS WARNING " << numProcs << user << L" | procs=" << numProcs << L";" + << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << '\n'; break; case CRITICAL: - wcout << L"PROCS CRITICAL " << numProcs << user << L" | procs=" << numProcs << L";" - << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << endl; + std::wcout << L"PROCS CRITICAL " << numProcs << user << L" | procs=" << numProcs << L";" + << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << '\n'; break; } return state; } -int countProcs() +INT countProcs() { if (debug) - wcout << L"Counting all processes" << endl; + std::wcout << L"Counting all processes" << '\n'; HANDLE hProcessSnap = NULL; PROCESSENTRY32 pe32; if (debug) - wcout << L"Creating snapshot" << endl; + std::wcout << L"Creating snapshot" << '\n'; hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcessSnap == INVALID_HANDLE_VALUE) @@ -221,37 +205,37 @@ int countProcs() pe32.dwSize = sizeof(PROCESSENTRY32); if (debug) - wcout << L"Grabbing first proccess" << endl; + std::wcout << L"Grabbing first proccess" << '\n'; if (!Process32First(hProcessSnap, &pe32)) { CloseHandle(hProcessSnap); return -1; } - int numProcs = 0; + INT numProcs = 0; if (debug) - wcout << L"Counting processes..." << endl; + std::wcout << L"Counting processes..." << '\n'; do { ++numProcs; } while (Process32Next(hProcessSnap, &pe32)); if (debug) - wcout << L"Found " << numProcs << L" processes. Cleaning up udn returning" << endl; + std::wcout << L"Found " << numProcs << L" processes. Cleaning up udn returning" << '\n'; if (hProcessSnap) CloseHandle(hProcessSnap); return numProcs; } -int countProcs(const wstring user) +INT countProcs(CONST std::wstring user) { if (debug) - wcout << L"Counting all processes of user" << user << endl; + std::wcout << L"Counting all processes of user" << user << '\n'; - const wchar_t *wuser = user.c_str(); - int numProcs = 0; + CONST WCHAR *wuser = user.c_str(); + INT numProcs = 0; HANDLE hProcessSnap, hProcess = NULL, hToken = NULL; PROCESSENTRY32 pe32; @@ -261,7 +245,7 @@ int countProcs(const wstring user) LPWSTR AcctName, DomainName; if (debug) - wcout << L"Creating snapshot" << endl; + std::wcout << L"Creating snapshot" << '\n'; hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcessSnap == INVALID_HANDLE_VALUE) @@ -270,17 +254,17 @@ int countProcs(const wstring user) pe32.dwSize = sizeof(PROCESSENTRY32); if (debug) - wcout << L"Grabbing first proccess" << endl; + std::wcout << L"Grabbing first proccess" << '\n'; if (!Process32First(hProcessSnap, &pe32)) goto die; if (debug) - wcout << L"Counting processes..." << endl; + std::wcout << L"Counting processes..." << '\n'; do { if (debug) - wcout << L"Getting process token" << endl; + std::wcout << L"Getting process token" << '\n'; //get ProcessToken hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pe32.th32ProcessID); @@ -298,7 +282,7 @@ int countProcs(const wstring user) memset(pSIDTokenUser, 0, dwReturnLength); if (debug) - wcout << L"Received token, saving information" << endl; + std::wcout << L"Received token, saving information" << '\n'; //write Info in pSIDTokenUser if (!GetTokenInformation(hToken, TokenUser, pSIDTokenUser, dwReturnLength, NULL)) @@ -310,7 +294,7 @@ int countProcs(const wstring user) dwDomainName = 1; if (debug) - wcout << L"Looking up SID" << endl; + std::wcout << L"Looking up SID" << '\n'; //get dwAcctName and dwDomainName size if (!LookupAccountSid(NULL, pSIDTokenUser->User.Sid, AcctName, @@ -326,11 +310,11 @@ int countProcs(const wstring user) continue; if (debug) - wcout << L"Comparing " << AcctName << L" to " << wuser << endl; + std::wcout << L"Comparing " << AcctName << L" to " << wuser << '\n'; if (!wcscmp(AcctName, wuser)) { ++numProcs; if (debug) - wcout << L"Is process of " << wuser << L" (" << numProcs << L")" << endl; + std::wcout << L"Is process of " << wuser << L" (" << numProcs << L")" << '\n'; } delete[] reinterpret_cast(AcctName); diff --git a/plugins/check_procs.h b/plugins/check_procs.h new file mode 100644 index 000000000..6337975cc --- /dev/null +++ b/plugins/check_procs.h @@ -0,0 +1,36 @@ +/****************************************************************************** + * Icinga 2 * + * Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.org) * + * * + * This program is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2 * + * of the License, or (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the Free Software Foundation * + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * + ******************************************************************************/ + +#ifndef CHECK_PROCS_H +#define CHECK_PROCS_H +#include "thresholds.h" +#include "boost/program_options.hpp" + +struct printInfoStruct +{ + threshold warn, crit; + std::wstring user; +}; + +INT countProcs(); +INT countProcs(CONST std::wstring); +INT parseArguments(INT, WCHAR **, boost::program_options::variables_map&, printInfoStruct&); +INT printOutput(CONST INT, printInfoStruct&); + +#endif // !CHECK_PROCS_H diff --git a/plugins/check_service.cpp b/plugins/check_service.cpp index 5ff4af1df..018f8b89f 100644 --- a/plugins/check_service.cpp +++ b/plugins/check_service.cpp @@ -20,36 +20,21 @@ #include #include -#include "thresholds.h" +#include "check_service.h" -#include "boost/program_options.hpp" #define VERSION 1.1 namespace po = boost::program_options; -using std::wcout; using std::endl; -using std::cout; using std::wstring; - static BOOL debug; -struct printInfoStruct -{ - bool warn; - DWORD ServiceState; - wstring service; -}; - -static int parseArguments(int, wchar_t **, po::variables_map&, printInfoStruct&); -static int printOutput(const printInfoStruct&); -static DWORD ServiceStatus(const printInfoStruct&); - -int wmain(int argc, wchar_t **argv) +INT wmain(INT argc, WCHAR **argv) { po::variables_map vm; printInfoStruct printInfo = { false, 0, L"" }; - int ret = parseArguments(argc, argv, vm, printInfo); + INT ret = parseArguments(argc, argv, vm, printInfo); if (ret != -1) return ret; @@ -60,23 +45,23 @@ int wmain(int argc, wchar_t **argv) return printOutput(printInfo); } -int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& printInfo) +INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo) { - wchar_t namePath[MAX_PATH]; + WCHAR namePath[MAX_PATH]; GetModuleFileName(NULL, namePath, MAX_PATH); - wchar_t *progName = PathFindFileName(namePath); + WCHAR *progName = PathFindFileName(namePath); po::options_description desc; desc.add_options() - ("help,h", "print help message and exit") - ("version,V", "print version and exit") + ("help,h", "Print help message and exit") + ("version,V", "Print version and exit") ("debug,d", "Verbose/Debug output") - ("service,s", po::wvalue(), "service to check (required)") - ("warn,w", "return warning (1) instead of critical (2),\n when service is not running") + ("service,s", po::wvalue(), "Service to check (required)") + ("warn,w", "Return warning (1) instead of critical (2),\n when service is not running") ; - po::basic_command_line_parser parser(ac, av); + po::basic_command_line_parser parser(ac, av); try { po::store( @@ -89,16 +74,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& vm); vm.notify(); } catch (std::exception& e) { - cout << e.what() << endl << desc << endl; + std::cout << e.what() << '\n' << desc << '\n'; return 3; } if (vm.count("help")) { - wcout << progName << " Help\n\tVersion: " << VERSION << endl; + std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n'; wprintf( L"%s is a simple program to check the status of a service.\n" L"You can use the following options to define its behaviour:\n\n", progName); - cout << desc; + std::cout << desc; wprintf( L"\nIt will then output a string looking something like this:\n\n" L"\tSERVICE CRITICAL NOT_RUNNING | service=4;!4;!4;1;7\n\n" @@ -115,24 +100,24 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& L"all \"-w\" and \"-c\" do is say whether a not running service is a warning\n" L"or critical state respectively.\n\n" , progName, progName); - cout << endl; + std::cout << '\n'; return 0; } if (vm.count("version")) { - cout << "Version: " << VERSION << endl; + std::cout << "Version: " << VERSION << '\n'; return 0; } if (!vm.count("service")) { - cout << "Missing argument: service" << endl << desc << endl; + std::cout << "Missing argument: service" << '\n' << desc << '\n'; return 3; } if (vm.count("warn")) printInfo.warn = true; - printInfo.service = vm["service"].as(); + printInfo.service = vm["service"].as(); if (vm.count("debug")) debug = TRUE; @@ -140,16 +125,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& return -1; } -int printOutput(const printInfoStruct& printInfo) +INT printOutput(CONST printInfoStruct& printInfo) { if (debug) - wcout << L"Constructing output string" << endl; + std::wcout << L"Constructing output string" << '\n'; - wstring perf; + std::wstring perf; state state = OK; if (!printInfo.ServiceState) { - wcout << L"SERVICE CRITICAL NOTFOUND | service=" << printInfo.ServiceState << ";!4;!4;1;7" << endl; + std::wcout << L"SERVICE CRITICAL NOTFOUND | service=" << printInfo.ServiceState << ";!4;!4;1;7" << '\n'; return 3; } @@ -158,20 +143,20 @@ int printOutput(const printInfoStruct& printInfo) switch (state) { case OK: - wcout << L"SERVICE OK RUNNING | service=4;!4;!4;1;7" << endl; + std::wcout << L"SERVICE OK RUNNING | service=4;!4;!4;1;7" << '\n'; break; case WARNING: - wcout << L"SERVICE WARNING NOT RUNNING | service=" << printInfo.ServiceState << ";!4;!4;1;7" << endl; + std::wcout << L"SERVICE WARNING NOT RUNNING | service=" << printInfo.ServiceState << ";!4;!4;1;7" << '\n'; break; case CRITICAL: - wcout << L"SERVICE CRITICAL NOT RUNNING | service=" << printInfo.ServiceState << ";!4;!4;1;7" << endl; + std::wcout << L"SERVICE CRITICAL NOT RUNNING | service=" << printInfo.ServiceState << ";!4;!4;1;7" << '\n'; break; } return state; } -DWORD ServiceStatus(const printInfoStruct& printInfo) +DWORD ServiceStatus(CONST printInfoStruct& printInfo) { SC_HANDLE hSCM; SC_HANDLE hService; @@ -179,14 +164,14 @@ DWORD ServiceStatus(const printInfoStruct& printInfo) LPBYTE lpBuf = NULL; if (debug) - wcout << L"Opening SC Manager" << endl; + std::wcout << L"Opening SC Manager" << '\n'; hSCM = OpenSCManager(NULL, NULL, GENERIC_READ); if (hSCM == NULL) goto die; if (debug) - wcout << L"Getting Service Information" << endl; + std::wcout << L"Getting Service Information" << '\n'; hService = OpenService(hSCM, printInfo.service.c_str(), SERVICE_QUERY_STATUS); if (hService == NULL) diff --git a/plugins/check_service.h b/plugins/check_service.h new file mode 100644 index 000000000..6692d59ea --- /dev/null +++ b/plugins/check_service.h @@ -0,0 +1,36 @@ +/****************************************************************************** + * Icinga 2 * + * Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.org) * + * * + * This program is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2 * + * of the License, or (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the Free Software Foundation * + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * + ******************************************************************************/ + +#ifndef CHECK_SERVICE_H +#define CHECK_SERVICE_H +#include "thresholds.h" +#include "boost/program_options.hpp" + +struct printInfoStruct +{ + BOOL warn; + DWORD ServiceState; + std::wstring service; +}; + +INT parseArguments(INT, WCHAR **, boost::program_options::variables_map&, printInfoStruct&); +INT printOutput(CONST printInfoStruct&); +DWORD ServiceStatus(CONST printInfoStruct&); + +#endif // !CHECK_SERVICE_H diff --git a/plugins/check_swap.cpp b/plugins/check_swap.cpp index 111ad33e4..fde4e1752 100644 --- a/plugins/check_swap.cpp +++ b/plugins/check_swap.cpp @@ -20,36 +20,20 @@ #include #include -#include "thresholds.h" - -#include "boost/program_options.hpp" +#include "check_swap.h" #define VERSION 1.0 namespace po = boost::program_options; -using std::endl; using std::wcout; using std::wstring; -using std::cout; - static BOOL debug = FALSE; -struct printInfoStruct -{ - threshold warn, crit; - double tSwap, aSwap; - Bunit unit = BunitMB; -}; - -static int parseArguments(int, wchar_t **, po::variables_map&, printInfoStruct&); -static int printOutput(printInfoStruct&); -static int check_swap(printInfoStruct&); - -int wmain(int argc, wchar_t **argv) +INT wmain(INT argc, WCHAR **argv) { printInfoStruct printInfo = { }; po::variables_map vm; - int ret = parseArguments(argc, argv, vm, printInfo); + INT ret = parseArguments(argc, argv, vm, printInfo); if (ret != -1) return ret; @@ -60,24 +44,24 @@ int wmain(int argc, wchar_t **argv) return printOutput(printInfo); } -int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& printInfo) +INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo) { - wchar_t namePath[MAX_PATH]; + WCHAR namePath[MAX_PATH]; GetModuleFileName(NULL, namePath, MAX_PATH); - wchar_t *progName = PathFindFileName(namePath); + WCHAR *progName = PathFindFileName(namePath); po::options_description desc; desc.add_options() - ("help,h", "print help message and exit") - ("version,V", "print version and exit") + ("help,h", "Print help message and exit") + ("version,V", "Print version and exit") ("debug,d", "Verbose/Debug output") - ("warning,w", po::wvalue(), "warning threshold") - ("critical,c", po::wvalue(), "critical threshold") - ("unit,u", po::wvalue(), "the unit to use for display (default MB)") + ("warning,w", po::wvalue(), "Warning threshold") + ("critical,c", po::wvalue(), "Critical threshold") + ("unit,u", po::wvalue(), "The unit to use for display (default MB)") ; - po::basic_command_line_parser parser(ac, av); + po::basic_command_line_parser parser(ac, av); try { po::store( @@ -90,16 +74,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& vm); vm.notify(); } catch (std::exception& e) { - cout << e.what() << endl << desc << endl; + std::cout << e.what() << '\n' << desc << '\n'; return 3; } if (vm.count("help")) { - wcout << progName << " Help\n\tVersion: " << VERSION << endl; + std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n'; wprintf( L"%s is a simple program to check a machines swap in percent.\n" L"You can use the following options to define its behaviour:\n\n", progName); - cout << desc; + std::cout << desc; wprintf( L"\nIt will then output a string looking something like this:\n\n" L"\tSWAP WARNING - 20%% free | swap=2000B;3000;500;0;10000\n\n" @@ -131,18 +115,18 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& L"to end with a percentage sign.\n\n" L"All of these options work with the critical threshold \"-c\" too.\n" , progName); - cout << endl; + std::cout << '\n'; return 0; } if (vm.count("version")) - wcout << L"Version: " << VERSION << endl; + std::wcout << L"Version: " << VERSION << '\n'; if (vm.count("warning")) { try { - printInfo.warn = threshold(vm["warning"].as()); + printInfo.warn = threshold(vm["warning"].as()); } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } printInfo.warn.legal = !printInfo.warn.legal; @@ -150,9 +134,9 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& if (vm.count("critical")) { try { - printInfo.crit = threshold(vm["critical"].as()); + printInfo.crit = threshold(vm["critical"].as()); } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } printInfo.crit.legal = !printInfo.crit.legal; @@ -163,9 +147,9 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& if (vm.count("unit")) { try { - printInfo.unit = parseBUnit(vm["unit"].as()); + printInfo.unit = parseBUnit(vm["unit"].as()); } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } } @@ -173,10 +157,10 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& return -1; } -int printOutput(printInfoStruct& printInfo) +INT printOutput(printInfoStruct& printInfo) { if (debug) - wcout << L"Constructing output string" << endl; + std::wcout << L"Constructing output string" << '\n'; state state = OK; double fswap = ((double)printInfo.aSwap / (double)printInfo.tSwap) * 100.0; @@ -189,26 +173,26 @@ int printOutput(printInfoStruct& printInfo) switch (state) { case OK: - wcout << L"SWAP OK - " << fswap << L"% free | swap=" << printInfo.aSwap << BunitStr(printInfo.unit) << L";" + std::wcout << L"SWAP OK - " << fswap << L"% free | swap=" << printInfo.aSwap << BunitStr(printInfo.unit) << L";" << printInfo.warn.pString(printInfo.tSwap) << L";" << printInfo.crit.pString(printInfo.tSwap) - << L";0;" << printInfo.tSwap << endl; + << L";0;" << printInfo.tSwap << '\n'; break; case WARNING: - wcout << L"SWAP WARNING - " << fswap << L"% free | swap=" << printInfo.aSwap << BunitStr(printInfo.unit) << L";" + std::wcout << L"SWAP WARNING - " << fswap << L"% free | swap=" << printInfo.aSwap << BunitStr(printInfo.unit) << L";" << printInfo.warn.pString(printInfo.tSwap) << L";" << printInfo.crit.pString(printInfo.tSwap) - << L";0;" << printInfo.tSwap << endl; + << L";0;" << printInfo.tSwap << '\n'; break; case CRITICAL: - wcout << L"SWAP CRITICAL - " << fswap << L"% free | swap=" << printInfo.aSwap << BunitStr(printInfo.unit) << L";" + std::wcout << L"SWAP CRITICAL - " << fswap << L"% free | swap=" << printInfo.aSwap << BunitStr(printInfo.unit) << L";" << printInfo.warn.pString(printInfo.tSwap) << L";" << printInfo.crit.pString(printInfo.tSwap) - << L";0;" << printInfo.tSwap << endl; + << L";0;" << printInfo.tSwap << '\n'; break; } return state; } -int check_swap(printInfoStruct& printInfo) +INT check_swap(printInfoStruct& printInfo) { MEMORYSTATUSEX MemBuf; MemBuf.dwLength = sizeof(MemBuf); diff --git a/plugins/check_swap.h b/plugins/check_swap.h new file mode 100644 index 000000000..fff7acf71 --- /dev/null +++ b/plugins/check_swap.h @@ -0,0 +1,36 @@ +/****************************************************************************** + * Icinga 2 * + * Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.org) * + * * + * This program is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2 * + * of the License, or (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the Free Software Foundation * + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * + ******************************************************************************/ + +#ifndef CHECK_SWAP_H +#define CHECK_SWAP_H +#include "thresholds.h" +#include "boost/program_options.hpp" + +struct printInfoStruct +{ + threshold warn, crit; + DOUBLE tSwap, aSwap; + Bunit unit = BunitMB; +}; + +INT parseArguments(INT, WCHAR **, boost::program_options::variables_map&, printInfoStruct&); +INT printOutput(printInfoStruct&); +INT check_swap(printInfoStruct&); + +#endif // !CHECK_SWAP_H diff --git a/plugins/check_update.cpp b/plugins/check_update.cpp index fe1de9217..d17406559 100644 --- a/plugins/check_update.cpp +++ b/plugins/check_update.cpp @@ -22,9 +22,7 @@ #include #include -#include "thresholds.h" - -#include "boost/program_options.hpp" +#include "check_update.h" #define VERSION 1.0 @@ -32,28 +30,14 @@ namespace po = boost::program_options; -using std::wcout; using std::endl; -using std::wstring; using std::cout; - static BOOL debug = FALSE; -struct printInfoStruct -{ - BOOL warn, crit; - LONG numUpdates; - BOOL important, reboot, careForCanRequest; -}; - -static int parseArguments(int, wchar_t **, po::variables_map&, printInfoStruct&); -static int printOutput(const printInfoStruct&); -static int check_update(printInfoStruct&); - -int wmain(int argc, wchar_t **argv) +INT wmain(INT argc, WCHAR **argv) { printInfoStruct printInfo = { FALSE, FALSE, 0, FALSE, FALSE, FALSE }; po::variables_map vm; - int ret = parseArguments(argc, argv, vm, printInfo); + INT ret = parseArguments(argc, argv, vm, printInfo); if (ret != -1) return ret; @@ -64,24 +48,24 @@ int wmain(int argc, wchar_t **argv) return printOutput(printInfo); } -int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& printInfo) +INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo) { - wchar_t namePath[MAX_PATH]; + WCHAR namePath[MAX_PATH]; GetModuleFileName(NULL, namePath, MAX_PATH); - wchar_t *progName = PathFindFileName(namePath); + WCHAR *progName = PathFindFileName(namePath); po::options_description desc; desc.add_options() - ("help,h", "print help message and exit") - ("version,V", "print version and exit") + ("help,h", "Print help message and exit") + ("version,V", "Print version and exit") ("debug,d", "Verbose/Debug output") - ("warning,w", "warn if there are important updates available") - ("critical,c", "critical if there are important updates that require a reboot") - ("possible-reboot", "treat \"update may need reboot\" as \"update needs reboot\"") + ("warning,w", "Warn if there are important updates available") + ("critical,c", "Critical if there are important updates that require a reboot") + ("possible-reboot", "Treat \"update may need reboot\" as \"update needs reboot\"") ; - po::basic_command_line_parser parser(ac, av); + po::basic_command_line_parser parser(ac, av); try { po::store( @@ -94,16 +78,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& vm); vm.notify(); } catch (std::exception& e) { - cout << e.what() << endl << desc << endl; + std::cout << e.what() << '\n' << desc << '\n'; return 3; } if (vm.count("help")) { - wcout << progName << " Help\n\tVersion: " << VERSION << endl; + std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n'; wprintf( L"%s is a simple program to check a machines required updates.\n" L"You can use the following options to define its behaviour:\n\n", progName); - cout << desc; + std::cout << desc; wprintf( L"\nAfter some time, it will then output a string like this one:\n\n" L"\tUPDATE WARNING 8 | updates=8;1;1;0\n\n" @@ -128,10 +112,10 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& L"The \"possible-reboot\" option is not recommended since this true for nearly\n" L"every update." , progName, progName); - cout << endl; + std::cout << '\n'; return 0; } if (vm.count("version")) { - cout << "Version: " << VERSION << endl; + std::cout << "Version: " << VERSION << '\n'; return 0; } @@ -150,13 +134,13 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& return -1; } -int printOutput(const printInfoStruct& printInfo) +INT printOutput(const printInfoStruct& printInfo) { if (debug) - wcout << L"Constructing output string" << endl; + std::wcout << L"Constructing output string" << '\n'; state state = OK; - wstring output = L"UPDATE "; + std::wstring output = L"UPDATE "; if (printInfo.important) state = WARNING; @@ -176,16 +160,16 @@ int printOutput(const printInfoStruct& printInfo) break; } - wcout << output << printInfo.numUpdates << L" | update=" << printInfo.numUpdates << L";" - << printInfo.warn << L";" << printInfo.crit << L";0;" << endl; + std::wcout << output << printInfo.numUpdates << L" | update=" << printInfo.numUpdates << L";" + << printInfo.warn << L";" << printInfo.crit << L";0;" << '\n'; return state; } -int check_update(printInfoStruct& printInfo) +INT check_update(printInfoStruct& printInfo) { if (debug) - wcout << "Initializing COM library" << endl; + std::wcout << "Initializing COM library" << '\n'; CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); ISearchResult *pResult; IUpdateSession *pSession; @@ -194,7 +178,7 @@ int check_update(printInfoStruct& printInfo) HRESULT err; if (debug) - wcout << "Creating UpdateSession and UpdateSearcher" << endl; + std::wcout << "Creating UpdateSession and UpdateSearcher" << '\n'; CoCreateInstance(CLSID_UpdateSession, NULL, CLSCTX_INPROC_SERVER, IID_IUpdateSession, (LPVOID*)&pSession); pSession->CreateUpdateSearcher(&pSearcher); @@ -210,7 +194,7 @@ int check_update(printInfoStruct& printInfo) // http://msdn.microsoft.com/en-us/library/ff357803%28v=vs.85%29.aspx if (debug) - wcout << L"Querrying updates from server" << endl; + std::wcout << L"Querrying updates from server" << '\n'; err = pSearcher->Search(criteria, &pResult); if (!SUCCEEDED(err)) @@ -236,24 +220,24 @@ int check_update(printInfoStruct& printInfo) for (LONG i = 0; i < updateSize; i++) { pCollection->get_Item(i, &pUpdate); if (debug) { - wcout << L"Checking reboot behaviour of update number " << i << endl; + std::wcout << L"Checking reboot behaviour of update number " << i << '\n'; } pUpdate->get_InstallationBehavior(&pIbehav); pIbehav->get_RebootBehavior(&updateReboot); if (updateReboot == irbAlwaysRequiresReboot) { printInfo.reboot = TRUE; if (debug) - wcout << L"It requires reboot" << endl; + std::wcout << L"It requires reboot" << '\n'; continue; } if (printInfo.careForCanRequest && updateReboot == irbCanRequestReboot) if (debug) - wcout << L"It requires reboot" << endl; + std::wcout << L"It requires reboot" << '\n'; printInfo.reboot = TRUE; } if (debug) - wcout << L"Cleaning up and returning" << endl; + std::wcout << L"Cleaning up and returning" << '\n'; SysFreeString(criteria); CoUninitialize(); diff --git a/plugins/check_update.h b/plugins/check_update.h new file mode 100644 index 000000000..56cc7e19a --- /dev/null +++ b/plugins/check_update.h @@ -0,0 +1,36 @@ +/****************************************************************************** + * Icinga 2 * + * Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.org) * + * * + * This program is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2 * + * of the License, or (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the Free Software Foundation * + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * + ******************************************************************************/ + +#ifndef CHECK_UPDATE_H +#define CHECK_UPDATE_H +#include "thresholds.h" +#include "boost/program_options.hpp" + +struct printInfoStruct +{ + BOOL warn, crit; + LONG numUpdates; + BOOL important, reboot, careForCanRequest; +}; + +INT parseArguments(INT, WCHAR **, boost::program_options::variables_map&, printInfoStruct&); +INT printOutput(CONST printInfoStruct&); +INT check_update(printInfoStruct&); + +#endif // !CHECK_UPDATE_H diff --git a/plugins/check_uptime.cpp b/plugins/check_uptime.cpp index 0dc0fde13..96a25fe5c 100644 --- a/plugins/check_uptime.cpp +++ b/plugins/check_uptime.cpp @@ -20,37 +20,21 @@ #include #include -#include "thresholds.h" +#include "check_uptime.h" #include "boost/chrono.hpp" -#include "boost/program_options.hpp" #define VERSION 1.0 namespace po = boost::program_options; -using std::cout; using std::endl; -using std::wcout; using std::wstring; - static BOOL debug; -struct printInfoStruct -{ - threshold warn, crit; - long long time; - Tunit unit; -}; - - -static int parseArguments(int, wchar_t **, po::variables_map&, printInfoStruct&); -static int printOutput(printInfoStruct&); -static void getUptime(printInfoStruct&); - -int wmain(int argc, wchar_t **argv) +INT wmain(INT argc, WCHAR **argv) { po::variables_map vm; printInfoStruct printInfo = { }; - int ret = parseArguments(argc, argv, vm, printInfo); + INT ret = parseArguments(argc, argv, vm, printInfo); if (ret != -1) return ret; @@ -60,24 +44,24 @@ int wmain(int argc, wchar_t **argv) return printOutput(printInfo); } -int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& printInfo) +INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo) { - wchar_t namePath[MAX_PATH]; + WCHAR namePath[MAX_PATH]; GetModuleFileName(NULL, namePath, MAX_PATH); - wchar_t *progName = PathFindFileName(namePath); + WCHAR *progName = PathFindFileName(namePath); po::options_description desc; desc.add_options() - ("help,h", "print help message and exit") - ("version,V", "print version and exit") - ("warning,w", po::wvalue(), "warning threshold (Uses -unit)") + ("help,h", "Print help message and exit") + ("version,V", "Print version and exit") ("debug,d", "Verbose/Debug output") - ("critical,c", po::wvalue(), "critical threshold (Uses -unit)") - ("unit,u", po::wvalue(), "desired unit of output\nh\t- hours\nm\t- minutes\ns\t- seconds (default)\nms\t- milliseconds") + ("warning,w", po::wvalue(), "Warning threshold (Uses -unit)") + ("critical,c", po::wvalue(), "Critical threshold (Uses -unit)") + ("unit,u", po::wvalue(), "Unit to use:\nh\t- hours\nm\t- minutes\ns\t- seconds (default)\nms\t- milliseconds") ; - po::basic_command_line_parser parser(ac, av); + po::basic_command_line_parser parser(ac, av); try { po::store( @@ -90,16 +74,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& vm); vm.notify(); } catch (std::exception& e) { - cout << e.what() << endl << desc << endl; + std::cout << e.what() << '\n' << desc << '\n'; return 3; } if (vm.count("help")) { - wcout << progName << " Help\n\tVersion: " << VERSION << endl; + std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n'; wprintf( L"%s is a simple program to check a machines uptime.\n" L"You can use the following options to define its behaviour:\n\n", progName); - cout << desc; + std::cout << desc; wprintf( L"\nIt will then output a string looking something like this:\n\n" L"\tUPTIME WARNING 712h | uptime=712h;700;1800;0\n\n" @@ -133,37 +117,37 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& L"to end with a percentage sign.\n\n" L"All of these options work with the critical threshold \"-c\" too.\n" , progName); - cout << endl; + std::cout << '\n'; return 0; } if (vm.count("version")) { - cout << VERSION << endl; + std::cout << VERSION << '\n'; return 0; } if (vm.count("warning")) { try { - printInfo.warn = threshold(vm["warning"].as()); + printInfo.warn = threshold(vm["warning"].as()); } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } } if (vm.count("critical")) { try { - printInfo.crit = threshold(vm["critical"].as()); + printInfo.crit = threshold(vm["critical"].as()); } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } } if (vm.count("unit")) { try{ - printInfo.unit = parseTUnit(vm["unit"].as()); + printInfo.unit = parseTUnit(vm["unit"].as()); } catch (std::invalid_argument) { - wcout << L"Unknown unit type " << vm["unit"].as() << endl; + std::wcout << L"Unknown unit type " << vm["unit"].as() << '\n'; return 3; } } else @@ -175,10 +159,10 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& return -1; } -static int printOutput(printInfoStruct& printInfo) +INT printOutput(printInfoStruct& printInfo) { if (debug) - wcout << L"Constructing output string" << endl; + std::wcout << L"Constructing output string" << '\n'; state state = OK; @@ -189,34 +173,34 @@ static int printOutput(printInfoStruct& printInfo) switch (state) { case OK: - wcout << L"UPTIME OK " << printInfo.time << TunitStr(printInfo.unit) << L" | uptime=" << printInfo.time + std::wcout << L"UPTIME OK " << printInfo.time << TunitStr(printInfo.unit) << L" | uptime=" << printInfo.time << TunitStr(printInfo.unit) << L";" << printInfo.warn.pString() << L";" - << printInfo.crit.pString() << L";0;" << endl; + << printInfo.crit.pString() << L";0;" << '\n'; break; case WARNING: - wcout << L"UPTIME WARNING " << printInfo.time << TunitStr(printInfo.unit) << L" | uptime=" << printInfo.time + std::wcout << L"UPTIME WARNING " << printInfo.time << TunitStr(printInfo.unit) << L" | uptime=" << printInfo.time << TunitStr(printInfo.unit) << L";" << printInfo.warn.pString() << L";" - << printInfo.crit.pString() << L";0;" << endl; + << printInfo.crit.pString() << L";0;" << '\n'; break; case CRITICAL: - wcout << L"UPTIME CRITICAL " << printInfo.time << TunitStr(printInfo.unit) << L" | uptime=" << printInfo.time + std::wcout << L"UPTIME CRITICAL " << printInfo.time << TunitStr(printInfo.unit) << L" | uptime=" << printInfo.time << TunitStr(printInfo.unit) << L";" << printInfo.warn.pString() << L";" - << printInfo.crit.pString() << L";0;" << endl; + << printInfo.crit.pString() << L";0;" << '\n'; break; } return state; } -void getUptime(printInfoStruct& printInfo) +VOID getUptime(printInfoStruct& printInfo) { if (debug) - wcout << L"Getting uptime in milliseconds" << endl; + std::wcout << L"Getting uptime in milliseconds" << '\n'; boost::chrono::milliseconds uptime = boost::chrono::milliseconds(GetTickCount64()); if (debug) - wcout << L"Converting requested unit (default: seconds)" << endl; + std::wcout << L"Converting requested unit (default: seconds)" << '\n'; switch (printInfo.unit) { case TunitH: diff --git a/plugins/check_uptime.h b/plugins/check_uptime.h new file mode 100644 index 000000000..b38e1c234 --- /dev/null +++ b/plugins/check_uptime.h @@ -0,0 +1,36 @@ +/****************************************************************************** + * Icinga 2 * + * Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.org) * + * * + * This program is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License * + * as published by the Free Software Foundation; either version 2 * + * of the License, or (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the Free Software Foundation * + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * + ******************************************************************************/ + +#ifndef CHECK_UPTIME_H +#define CHECK_UPTIME_H +#include "thresholds.h" +#include "boost/program_options.hpp" + +struct printInfoStruct +{ + threshold warn, crit; + long long time; + Tunit unit; +}; + +INT parseArguments(INT, WCHAR **, boost::program_options::variables_map&, printInfoStruct&); +INT printOutput(printInfoStruct&); +VOID getUptime(printInfoStruct&); + +#endif // !CHECK_UPTIME_H diff --git a/plugins/check_users.cpp b/plugins/check_users.cpp index ef3dc04b2..e5bdd69d3 100644 --- a/plugins/check_users.cpp +++ b/plugins/check_users.cpp @@ -21,35 +21,20 @@ #include #include -#include "thresholds.h" - -#include "boost/program_options.hpp" +#include "check_users.h" #define VERSION 1.0 namespace po = boost::program_options; -using std::endl; using std::wcout; -using std::cout; using std::wstring; - static BOOL debug = FALSE; -struct printInfoStruct -{ - threshold warn, crit; - double users; -}; - -static int parseArguments(int, wchar_t **, po::variables_map&, printInfoStruct&); -static int printOutput(printInfoStruct&); -static int check_users(printInfoStruct&); - -int wmain(int argc, wchar_t **argv) +INT wmain(INT argc, WCHAR **argv) { printInfoStruct printInfo = { }; po::variables_map vm; - int ret = parseArguments(argc, argv, vm, printInfo); + INT ret = parseArguments(argc, argv, vm, printInfo); if (ret != -1) return ret; @@ -60,23 +45,23 @@ int wmain(int argc, wchar_t **argv) return printOutput(printInfo); } -int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& printInfo) +INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo) { - wchar_t namePath[MAX_PATH]; + WCHAR namePath[MAX_PATH]; GetModuleFileName(NULL, namePath, MAX_PATH); - wchar_t *progName = PathFindFileName(namePath); + WCHAR *progName = PathFindFileName(namePath); po::options_description desc; desc.add_options() - ("help,h", "print help message and exit") - ("version,V", "print version and exit") + ("help,h", "Print help message and exit") + ("version,V", "Print version and exit") ("debug,d", "Verbose/Debug output") - ("warning,w", po::wvalue(), "warning threshold") - ("critical,c", po::wvalue(), "critical threshold") + ("warning,w", po::wvalue(), "Warning threshold") + ("critical,c", po::wvalue(), "Critical threshold") ; - po::basic_command_line_parser parser(ac, av); + po::basic_command_line_parser parser(ac, av); try { po::store( @@ -89,16 +74,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& vm); vm.notify(); } catch (std::exception& e) { - cout << e.what() << endl << desc << endl; + std::cout << e.what() << '\n' << desc << '\n'; return 3; } if (vm.count("help")) { - wcout << progName << " Help\n\tVersion: " << VERSION << endl; + std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n'; wprintf( L"%s is a simple program to check a machines logged in users.\n" L"You can use the following options to define its behaviour:\n\n", progName); - cout << desc; + std::cout << desc; wprintf( L"\nIt will then output a string looking something like this:\n\n" L"\tUSERS WARNING 48 | users=48;10;50;0\n\n" @@ -130,26 +115,26 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& L"to end with a percentage sign.\n\n" L"All of these options work with the critical threshold \"-c\" too." , progName); - cout << endl; + std::cout << '\n'; return 0; } if (vm.count("version")) - wcout << L"Version: " << VERSION << endl; + std::wcout << L"Version: " << VERSION << '\n'; if (vm.count("warning")) { try { - printInfo.warn = threshold(vm["warning"].as()); + printInfo.warn = threshold(vm["warning"].as()); } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } } if (vm.count("critical")) { try { - printInfo.crit = threshold(vm["critical"].as()); + printInfo.crit = threshold(vm["critical"].as()); } catch (std::invalid_argument& e) { - cout << e.what() << endl; + std::cout << e.what() << '\n'; return 3; } } @@ -160,10 +145,10 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& return -1; } -int printOutput(printInfoStruct& printInfo) +INT printOutput(printInfoStruct& printInfo) { if (debug) - wcout << L"Constructing output string" << endl; + std::wcout << L"Constructing output string" << '\n'; state state = OK; @@ -175,34 +160,34 @@ int printOutput(printInfoStruct& printInfo) switch (state) { case OK: - wcout << L"USERS OK " << printInfo.users << L" User(s) logged in | users=" << printInfo.users << L";" - << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << endl; + std::wcout << L"USERS OK " << printInfo.users << L" User(s) logged in | users=" << printInfo.users << L";" + << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << '\n'; break; case WARNING: - wcout << L"USERS WARNING " << printInfo.users << L" User(s) logged in | users=" << printInfo.users << L";" - << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << endl; + std::wcout << L"USERS WARNING " << printInfo.users << L" User(s) logged in | users=" << printInfo.users << L";" + << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << '\n'; break; case CRITICAL: - wcout << L"USERS CRITICAL " << printInfo.users << L" User(s) logged in | users=" << printInfo.users << L";" - << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << endl; + std::wcout << L"USERS CRITICAL " << printInfo.users << L" User(s) logged in | users=" << printInfo.users << L";" + << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << '\n'; break; } return state; } -int check_users(printInfoStruct& printInfo) +INT check_users(printInfoStruct& printInfo) { - double users = 0; + DOUBLE users = 0; WTS_SESSION_INFOW *pSessionInfo = NULL; DWORD count; DWORD index; if (debug) - wcout << L"Trying to enumerate terminal sessions" << endl; + std::wcout << L"Trying to enumerate terminal sessions" << '\n'; if (!WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pSessionInfo, &count)) { - wcout << L"Failed to enumerate terminal sessions" << endl; + std::wcout << L"Failed to enumerate terminal sessions" << '\n'; die(); if (pSessionInfo) WTSFreeMemory(pSessionInfo); @@ -210,22 +195,22 @@ int check_users(printInfoStruct& printInfo) } if (debug) - wcout << L"Got all sessions (" << count << L"), traversing and counting active ones" << endl; + std::wcout << L"Got all sessions (" << count << L"), traversing and counting active ones" << '\n'; for (index = 0; index < count; index++) { LPWSTR name; DWORD size; - int len; + INT len; if (debug) - wcout << L"Querrying session number " << index << endl; + std::wcout << L"Querrying session number " << index << '\n'; if (!WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, pSessionInfo[index].SessionId, WTSUserName, &name, &size)) continue; if (debug) - wcout << L"Found \"" << name << L"\". Checking whether it's a real session" << endl; + std::wcout << L"Found \"" << name << L"\". Checking whether it's a real session" << '\n'; len = lstrlenW(name); @@ -237,12 +222,12 @@ int check_users(printInfoStruct& printInfo) if (pSessionInfo[index].State == WTSActive || pSessionInfo[index].State == WTSDisconnected) { users++; if (debug) - wcout << L"\"" << name << L"\" is a real session, counting it. Now " << users << endl; + std::wcout << L"\"" << name << L"\" is a real session, counting it. Now " << users << '\n'; } } if (debug) - wcout << "Finished coutning user sessions (" << users << "). Freeing memory and returning" << endl; + std::wcout << "Finished coutning user sessions (" << users << "). Freeing memory and returning" << '\n'; WTSFreeMemory(pSessionInfo); printInfo.users = users; diff --git a/plugins/check_users.h b/plugins/check_users.h new file mode 100644 index 000000000..1cd151454 --- /dev/null +++ b/plugins/check_users.h @@ -0,0 +1,15 @@ +#ifndef CHECK_USERS_H +#define CHECK_USERS_H +#include "thresholds.h" +#include "boost/program_options.hpp" +struct printInfoStruct +{ + threshold warn, crit; + DOUBLE users; +}; + +INT parseArguments(INT, WCHAR **, boost::program_options::variables_map&, printInfoStruct&); +INT printOutput(printInfoStruct&); +INT check_users(printInfoStruct&); + +#endif // !CHECK_USERS_H diff --git a/plugins/thresholds.cpp b/plugins/thresholds.cpp index 82e4973d2..83fa0239c 100644 --- a/plugins/thresholds.cpp +++ b/plugins/thresholds.cpp @@ -20,80 +20,77 @@ #include "thresholds.h" #include #include -#include #include using namespace boost::algorithm; -using std::wstring; - threshold::threshold() : set(false) {} -threshold::threshold(const wstring& stri) +threshold::threshold(CONST std::wstring& stri) { if (stri.empty()) throw std::invalid_argument("Threshold must not be empty"); - wstring str = stri; + std::wstring str = stri; //kill whitespace boost::algorithm::trim(str); bool low = (str.at(0) == L'!'); if (low) - str = wstring(str.begin() + 1, str.end()); + str = std::wstring(str.begin() + 1, str.end()); bool pc = false; if (str.at(0) == L'[' && str.at(str.length() - 1) == L']') {//is range - str = wstring(str.begin() + 1, str.end() - 1); - std::vector svec; + str = std::wstring(str.begin() + 1, str.end() - 1); + std::vector svec; boost::split(svec, str, boost::is_any_of(L"-")); if (svec.size() != 2) throw std::invalid_argument("Threshold range requires two arguments"); - wstring str1 = svec.at(0), str2 = svec.at(1); + std::wstring str1 = svec.at(0), str2 = svec.at(1); if (str1.at(str1.length() - 1) == L'%' && str2.at(str2.length() - 1) == L'%') { pc = true; - str1 = wstring(str1.begin(), str1.end() - 1); - str2 = wstring(str2.begin(), str2.end() - 1); + str1 = std::wstring(str1.begin(), str1.end() - 1); + str2 = std::wstring(str2.begin(), str2.end() - 1); } try { boost::algorithm::trim(str1); - lower = boost::lexical_cast(str1); + lower = boost::lexical_cast(str1); boost::algorithm::trim(str2); - upper = boost::lexical_cast(str2); + upper = boost::lexical_cast(str2); legal = !low; perc = pc; set = true; - } catch (const boost::bad_lexical_cast&) { + } catch (CONST boost::bad_lexical_cast&) { throw std::invalid_argument("Unknown Threshold type"); } } else { //not range if (str.at(str.length() - 1) == L'%') { pc = true; - str = wstring(str.begin(), str.end() - 1); + str = std::wstring(str.begin(), str.end() - 1); } try { boost::algorithm::trim(str); - lower = upper = boost::lexical_cast(str); + lower = upper = boost::lexical_cast(str); legal = !low; perc = pc; set = true; - } catch (const boost::bad_lexical_cast&) { + } catch (CONST boost::bad_lexical_cast&) { throw std::invalid_argument("Unknown Threshold type"); } } } //return TRUE if the threshold is broken -bool threshold::rend(const double val, const double max) +BOOL threshold::rend(CONST DOUBLE val, CONST DOUBLE max) { - double upperAbs = upper; - double lowerAbs = lower; + DOUBLE upperAbs = upper; + DOUBLE lowerAbs = lower; if (perc) { - upperAbs = upper / 100 * max; - lowerAbs = lower / 100 * max; + upperAbs = upper / 100.0 * max; + lowerAbs = lower / 100.0 * max; } if (!set) @@ -105,16 +102,16 @@ bool threshold::rend(const double val, const double max) } //returns a printable string of the threshold -std::wstring threshold::pString(const double max) +std::wstring threshold::pString(CONST DOUBLE max) { if (!set) return L""; //transform percentages to abolute values - double lowerAbs = lower; - double upperAbs = upper; + DOUBLE lowerAbs = lower; + DOUBLE upperAbs = upper; if (perc) { - lowerAbs = lower / 100 * max; - upperAbs = upper / 100 * max; + lowerAbs = lower / 100.0 * max; + upperAbs = upper / 100.0 * max; } std::wstring s, lowerStr = removeZero(lowerAbs), @@ -129,10 +126,10 @@ std::wstring threshold::pString(const double max) return s; } -std::wstring removeZero(double val) +std::wstring removeZero(DOUBLE val) { std::wstring ret = boost::lexical_cast(val); - int pos = ret.length(); + INT pos = ret.length(); if (ret.find_first_of(L".") == std::string::npos) return ret; for (std::wstring::reverse_iterator rit = ret.rbegin(); rit != ret.rend(); ++rit) { @@ -149,14 +146,14 @@ std::wstring removeZero(double val) std::vector splitMultiOptions(std::wstring str) { - std::vector sVec; + std::vector sVec; boost::split(sVec, str, boost::is_any_of(L",")); return sVec; } -Bunit parseBUnit(const wstring& str) +Bunit parseBUnit(CONST std::wstring& str) { - wstring wstr = to_upper_copy(str); + std::wstring wstr = to_upper_copy(str); if (wstr == L"B") return BunitB; @@ -172,7 +169,7 @@ Bunit parseBUnit(const wstring& str) throw std::invalid_argument("Unknown unit type"); } -wstring BunitStr(const Bunit& unit) +std::wstring BunitStr(CONST Bunit& unit) { switch (unit) { case BunitB: @@ -189,8 +186,8 @@ wstring BunitStr(const Bunit& unit) return NULL; } -Tunit parseTUnit(const wstring& str) { - wstring wstr = to_lower_copy(str); +Tunit parseTUnit(CONST std::wstring& str) { + std::wstring wstr = to_lower_copy(str); if (wstr == L"ms") return TunitMS; @@ -204,7 +201,7 @@ Tunit parseTUnit(const wstring& str) { throw std::invalid_argument("Unknown unit type"); } -wstring TunitStr(const Tunit& unit) +std::wstring TunitStr(CONST Tunit& unit) { switch (unit) { case TunitMS: @@ -219,12 +216,14 @@ wstring TunitStr(const Tunit& unit) return NULL; } -void die(DWORD err) +VOID die(DWORD err) { if (!err) err = GetLastError(); LPWSTR mBuf = NULL; - size_t mS = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&mBuf, 0, NULL); - std::wcout << mBuf << std::endl; + if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&mBuf, 0, NULL)) + std::wcout << "Failed to format error message, last error was: " << err << '\n'; + else + std::wcout << mBuf << std::endl; } \ No newline at end of file diff --git a/plugins/thresholds.h b/plugins/thresholds.h index 099517bae..039b22d58 100644 --- a/plugins/thresholds.h +++ b/plugins/thresholds.h @@ -1,58 +1,70 @@ /****************************************************************************** - * Icinga 2 * - * Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.org) * - * * - * This program is free software; you can redistribute it and/or * - * modify it under the terms of the GNU General Public License * - * as published by the Free Software Foundation; either version 2 * - * of the License, or (at your option) any later version. * - * * - * This program is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU General Public License for more details. * - * * - * You should have received a copy of the GNU General Public License * - * along with this program; if not, write to the Free Software Foundation * - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * - ******************************************************************************/ +* Icinga 2 * +* Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.org) * +* * +* This program is free software; you can redistribute it and/or * +* modify it under the terms of the GNU General Public License * +* as published by the Free Software Foundation; either version 2 * +* of the License, or (at your option) any later version. * +* * +* This program is distributed in the hope that it will be useful, * +* but WITHOUT ANY WARRANTY; without even the implied warranty of * +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +* GNU General Public License for more details. * +* * +* You should have received a copy of the GNU General Public License * +* along with this program; if not, write to the Free Software Foundation * +* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * +******************************************************************************/ #ifndef THRESHOLDS_H #define THRESHOLDS_H #include #include #include -enum Bunit { BunitB = 0, BunitkB = 1, BunitMB = 2, BunitGB = 3, BunitTB = 4 }; -enum Tunit { TunitMS, TunitS, TunitM, TunitH }; -enum state { OK = 0, WARNING = 1, CRITICAL = 2 }; +enum Bunit +{ + BunitB = 0, BunitkB = 1, BunitMB = 2, BunitGB = 3, BunitTB = 4 +}; + +enum Tunit +{ + TunitMS, TunitS, TunitM, TunitH +}; + +enum state +{ + OK = 0, WARNING = 1, CRITICAL = 2 +}; class threshold { public: - double lower, upper; + //DOUBLEs are always enough for ANY 64 bit value + DOUBLE lower, upper; //TRUE means everything BELOW upper/outside [lower-upper] is fine - bool legal, perc, set; + BOOL legal, perc, set; threshold(); - threshold(const double v, const double c, bool l = true, bool p = false); + threshold(CONST DOUBLE v, CONST DOUBLE c, BOOL l = TRUE, BOOL p = FALSE); - threshold(const std::wstring&); + threshold(CONST std::wstring&); //return TRUE if the threshold is broken - bool rend(const double val, const double max = 100); + BOOL rend(CONST DOUBLE val, CONST DOUBLE max = 100.0); //returns a printable string of the threshold - std::wstring pString(const double max = 100); + std::wstring pString(CONST DOUBLE max = 100.0); }; -std::wstring removeZero(double); +std::wstring removeZero(DOUBLE); std::vector splitMultiOptions(std::wstring); -Bunit parseBUnit(const std::wstring&); -std::wstring BunitStr(const Bunit&); -Tunit parseTUnit(const std::wstring&); -std::wstring TunitStr(const Tunit&); +Bunit parseBUnit(CONST std::wstring&); +std::wstring BunitStr(CONST Bunit&); +Tunit parseTUnit(CONST std::wstring&); +std::wstring TunitStr(CONST Tunit&); -void die(DWORD err = 0); +VOID die(DWORD err = 0); #endif \ No newline at end of file