Refactor plugin code

This commit is contained in:
Jean Flach 2015-03-23 13:07:02 +01:00 committed by Jean-Marcel Flach
parent a90e2fb1a9
commit c1e13d3dbe
25 changed files with 1061 additions and 751 deletions

View File

@ -17,43 +17,43 @@
if ( WIN32 ) if ( WIN32 )
add_definitions( -DUNICODE -D_UNICODE ) add_definitions ( -DUNICODE -D_UNICODE )
add_library( thresholds thresholds ) add_library ( thresholds thresholds )
set_target_properties ( set_target_properties (
thresholds PROPERTIES thresholds PROPERTIES
INSTALL_RPATH ${CMAKE_INSTALL_FULL_LIBDIR}/icinga2 INSTALL_RPATH ${CMAKE_INSTALL_FULL_LIBDIR}/icinga2
FOLDER Plugins FOLDER Plugins
) )
list( APPEND check_SOURCES list ( APPEND check_SOURCES
check_disk.cpp check_load.cpp check_memory.cpp check_network.cpp check_ping.cpp check_perfmon.cpp 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 ) check_procs.cpp check_service.cpp check_swap.cpp check_update.cpp check_uptime.cpp check_users.cpp )
foreach ( source ${check_SOURCES} ) foreach ( source ${check_SOURCES} )
string ( REGEX REPLACE ".cpp\$" "" check_OUT "${source}" ) string ( REGEX REPLACE ".cpp\$" "" check_OUT "${source}" )
string ( REGEX REPLACE ".cpp\$" ".h" check_HEADER "${source}" )
add_executable ( ${check_OUT} ${source} ) add_executable ( ${check_OUT} ${source} ${check_HEADER} )
target_link_libraries( ${check_OUT} thresholds Shlwapi.lib ${Boost_PROGRAM_OPTIONS_LIBRARY} ) target_link_libraries ( ${check_OUT} thresholds Shlwapi.lib ${Boost_PROGRAM_OPTIONS_LIBRARY} )
set_target_properties ( set_target_properties (
${check_OUT} PROPERTIES ${check_OUT} PROPERTIES
INSTALL_RPATH ${CMAKE_INSTALL_FULL_LIBDIR}/icinga2 INSTALL_RPATH ${CMAKE_INSTALL_FULL_LIBDIR}/icinga2
DEFINE_SYMBOL I2_PLUGINS_BUILD DEFINE_SYMBOL I2_PLUGINS_BUILD
FOLDER Plugins) FOLDER Plugins )
endforeach(source) endforeach ( source )
target_link_libraries( check_load Pdh.lib ) target_link_libraries ( check_load Pdh.lib )
target_link_libraries( check_network Pdh.lib ) target_link_libraries ( check_network Pdh.lib Iphlpapi.lib)
target_link_libraries ( check_perfmon Pdh.lib ) target_link_libraries ( check_ping Ntdll.lib iphlpapi.lib Ws2_32.lib )
target_link_libraries( check_ping Ntdll.lib iphlpapi.lib Ws2_32.lib ) target_link_libraries ( check_procs Pdh.lib )
target_link_libraries( check_procs Pdh.lib ) target_link_libraries ( check_uptime ${Boost_SYSTEM_LIBRARY} )
target_link_libraries( check_uptime ${Boost_SYSTEM_LIBRARY} ) target_link_libraries ( check_users wtsapi32.lib )
target_link_libraries( check_users wtsapi32.lib )
install ( 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 check_ping check_service check_swap check_update check_uptime check_users
RUNTIME DESTINATION ${CMAKE_INSTALL_SBINDIR} ) RUNTIME DESTINATION ${CMAKE_INSTALL_SBINDIR} )
endif() endif ( )

View File

@ -16,55 +16,26 @@
* along with this program; if not, write to the Free Software Foundation * * along with this program; if not, write to the Free Software Foundation *
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
******************************************************************************/ ******************************************************************************/
#include <Windows.h>
#include <set> #include <set>
#include <Shlwapi.h> #include <Shlwapi.h>
#include <vector>
#include <iostream> #include <iostream>
#include <math.h> #include <math.h>
#include "thresholds.h" #include "check_disk.h"
#include "boost/program_options.hpp"
#define VERSION 1.1 #define VERSION 1.1
namespace po = boost::program_options; 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; static BOOL debug = FALSE;
struct drive INT wmain(INT argc, WCHAR **argv)
{ {
wstring name; std::vector<drive> vDrives;
double cap, free;
drive(wstring p)
: name(p)
{}
};
struct printInfoStruct
{
threshold warn, crit;
vector<wstring> drives;
Bunit unit;
};
static int parseArguments(int, wchar_t **, po::variables_map&, printInfoStruct&);
static int printOutput(printInfoStruct&, vector<drive>&);
static int check_drives(vector<drive>&);
static int check_drives(vector<drive>&, printInfoStruct&);
static bool getFreeAndCap(drive&, const Bunit&);
int wmain(int argc, wchar_t **argv)
{
vector<drive> vDrives;
printInfoStruct printInfo{ }; printInfoStruct printInfo{ };
po::variables_map vm; po::variables_map vm;
int ret; INT ret;
ret = parseArguments(argc, argv, vm, printInfo); ret = parseArguments(argc, argv, vm, printInfo);
if (ret != -1) if (ret != -1)
@ -81,9 +52,9 @@ int wmain(int argc, wchar_t **argv)
if (ret != -1) if (ret != -1)
return ret; return ret;
for (vector<drive>::iterator it = vDrives.begin(); it != vDrives.end(); ++it) { for (std::vector<drive>::iterator it = vDrives.begin(); it != vDrives.end(); ++it) {
if (!getFreeAndCap(*it, printInfo.unit)) { 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; return 3;
} }
} }
@ -91,32 +62,32 @@ int wmain(int argc, wchar_t **argv)
return printOutput(printInfo, vDrives); 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); GetModuleFileName(NULL, namePath, MAX_PATH);
wchar_t *progName = PathFindFileName(namePath); WCHAR *progName = PathFindFileName(namePath);
po::options_description desc("Options"); po::options_description desc("Options");
desc.add_options() desc.add_options()
("help,h", "print usage message and exit") ("help,h", "Print usage message and exit")
("version,V", "print version and exit") ("version,V", "Print version and exit")
("debug,d", "Verbose/Debug output") ("debug,d", "Verbose/Debug output")
("warning,w", po::wvalue<wstring>(), "warning threshold") ("warning,w", po::wvalue<std::wstring>(), "Warning threshold")
("critical,c", po::wvalue<wstring>(), "critical threshold") ("critical,c", po::wvalue<std::wstring>(), "Critical threshold")
("path,p", po::wvalue<vector<std::wstring>>()->multitoken(), "declare explicitly which drives to check (default checks all)") ("path,p", po::wvalue<std::vector<std::wstring>>()->multitoken(), "Declare explicitly which drives to check (default checks all)")
("unit,u", po::wvalue<wstring>(), "assign unit possible are: B, kB, MB, GB, TB") ("unit,u", po::wvalue<std::wstring>(), "Assign unit possible are: B, kB, MB, GB, TB")
; ;
po::basic_command_line_parser<wchar_t> parser(ac, av); po::basic_command_line_parser<WCHAR> parser(ac, av);
try { try {
po::options_description allDesc; po::options_description allDesc;
allDesc.add(desc); allDesc.add(desc);
allDesc.add_options() allDesc.add_options()
("exclude-type,X", po::wvalue<vector<std::wstring>>()->multitoken(), "exclude partition types (ignored)") ("exclude-type,X", po::wvalue<std::vector<std::wstring>>()->multitoken(), "exclude partition types (ignored)")
("megabytes,m", "use megabytes") ("megabytes,m", "use megabytes")
; ;
@ -130,16 +101,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
vm); vm);
vm.notify(); vm.notify();
} catch (std::exception& e) { } catch (std::exception& e) {
cout << e.what() << endl << desc << endl; std::cout << e.what() << '\n' << desc << '\n';
return 3; return 3;
} }
if (vm.count("help")) { if (vm.count("help")) {
wcout << progName << " Help\n\tVersion: " << VERSION << endl; std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n';
wprintf( wprintf(
L"%s is a simple program to check a machines free disk space.\n" 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); L"You can use the following options to define its behaviour:\n\n", progName);
cout << desc; std::cout << desc;
wprintf( wprintf(
L"\nIt will then output a string looking something like this:\n\n" 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" 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" 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" 1\tWARNING,\n\tThe warning, but not the critical threshold was broken\n"
L" 2\tCRITICAL,\n\tThe 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"Threshold syntax:\n\n"
L"-w THRESHOLD\n" L"-w THRESHOLD\n"
L"warn if threshold is broken, which means VALUE < THRESHOLD\n\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"to end with a percentage sign.\n\n"
L"All of these options work with the critical threshold \"-c\" too." L"All of these options work with the critical threshold \"-c\" too."
, progName); , progName);
cout << endl; std::cout << '\n';
return 0; return 0;
} }
if (vm.count("version")) if (vm.count("version"))
cout << "Version: " << VERSION << endl; std::cout << "Version: " << VERSION << '\n';
if (vm.count("warning")) { if (vm.count("warning")) {
try { try {
printInfo.warn = threshold(vm["warning"].as<wstring>()); printInfo.warn = threshold(vm["warning"].as<std::wstring>());
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
} }
if (vm.count("critical")) { if (vm.count("critical")) {
try { try {
printInfo.crit = threshold(vm["critical"].as<wstring>()); printInfo.crit = threshold(vm["critical"].as<std::wstring>());
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
} }
if (vm.count("path")) if (vm.count("path"))
printInfo.drives = vm["path"].as<vector<wstring>>(); printInfo.drives = vm["path"].as<std::vector<std::wstring>>();
if (vm.count("unit")) { if (vm.count("unit")) {
try { try {
printInfo.unit = parseBUnit(vm["unit"].as<wstring>()); printInfo.unit = parseBUnit(vm["unit"].as<std::wstring>());
} catch (std::invalid_argument) { } catch (std::invalid_argument) {
wcout << L"Unknown unit Type " << vm["unit"].as<wstring>() << endl; std::wcout << "Unknown unit Type " << vm["unit"].as<std::wstring>() << '\n';
return 3; return 3;
} }
} else } else
@ -213,19 +184,19 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
return -1; return -1;
} }
int printOutput(printInfoStruct& printInfo, vector<drive>& vDrives) INT printOutput(printInfoStruct& printInfo, std::vector<drive>& vDrives)
{ {
if (debug) if (debug)
wcout << L"Constructing output string" << endl; std::wcout << "Constructing output string\n";
vector<wstring> wsDrives, wsPerf; std::vector<std::wstring> wsDrives, wsPerf;
wstring unit = BunitStr(printInfo.unit); std::wstring unit = BunitStr(printInfo.unit);
state state = OK; state state = OK;
wstring output = L"DISK OK - free space:"; std::wstring output = L"DISK OK - free space:";
double tCap = 0, tFree = 0; double tCap = 0, tFree = 0;
for (vector<drive>::iterator it = vDrives.begin(); it != vDrives.end(); it++) { for (std::vector<drive>::iterator it = vDrives.begin(); it != vDrives.end(); it++) {
tCap += it->cap; tCap += it->cap;
tFree += it->free; tFree += it->free;
wsDrives.push_back(it->name + L" " + removeZero(it->free) + L" " + unit + L" (" + wsDrives.push_back(it->name + L" " + removeZero(it->free) + L" " + unit + L" (" +
@ -245,94 +216,93 @@ int printOutput(printInfoStruct& printInfo, vector<drive>& vDrives)
output = L"DISK CRITICAL - free space:"; output = L"DISK CRITICAL - free space:";
} }
wcout << output; std::wcout << output;
if (vDrives.size() > 1) 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<wstring>::const_iterator it = wsDrives.begin(); it != wsDrives.end(); it++) for (std::vector<std::wstring>::const_iterator it = wsDrives.begin(); it != wsDrives.end(); it++)
wcout << *it; std::wcout << *it;
wcout << L"|"; std::wcout << "|";
for (vector<wstring>::const_iterator it = wsPerf.begin(); it != wsPerf.end(); it++) for (std::vector<std::wstring>::const_iterator it = wsPerf.begin(); it != wsPerf.end(); it++)
wcout << *it; std::wcout << *it;
wcout << endl; std::wcout << '\n';
return state; return state;
} }
int check_drives(vector<drive>& vDrives) INT check_drives(std::vector<drive>& vDrives)
{ {
DWORD dwResult, dwSize = 0, dwVolumePathNamesLen = MAX_PATH + 1; 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; HANDLE hVolume = NULL;
wstring wsLogicalDrives; std::wstring wsLogicalDrives;
size_t volumeNameEnd = 0; size_t volumeNameEnd = 0;
set<wstring> sDrives; std::set<std::wstring> sDrives;
if (debug) 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); dwResult = GetLogicalDriveStrings(MAX_PATH, szLogicalDrives);
if (dwResult > MAX_PATH) if (dwResult > MAX_PATH)
goto die; goto die;
if (debug) if (debug)
wcout << L"Splitting string into single drive names" << endl; std::wcout << "Splitting string INTo single drive names\n";
LPTSTR szSingleDrive = szLogicalDrives; LPTSTR szSingleDrive = szLogicalDrives;
while (*szSingleDrive) { while (*szSingleDrive) {
wstring drname = szSingleDrive; std::wstring drname = szSingleDrive;
sDrives.insert(drname); sDrives.insert(drname);
szSingleDrive += wcslen(szSingleDrive) + 1; szSingleDrive += wcslen(szSingleDrive) + 1;
if (debug) if (debug)
wcout << "Got: " << drname << endl; std::wcout << "Got: " << drname << '\n';
} }
if (debug) if (debug)
wcout << L"Getting volume mountpoints (includes NTFS folders)" << endl std::wcout << "Getting volume mountpoINTs (includes NTFS folders)\n"
<< L"Getting first volume" << endl; << "Getting first volume\n";
hVolume = FindFirstVolume(szVolumeName, MAX_PATH); hVolume = FindFirstVolume(szVolumeName, MAX_PATH);
if (hVolume == INVALID_HANDLE_VALUE) if (hVolume == INVALID_HANDLE_VALUE)
goto die; goto die;
if (debug) if (debug)
wcout << L"Traversing through list of drives" << endl; std::wcout << "Traversing through list of drives\n";
while (GetLastError() != ERROR_NO_MORE_FILES) { while (GetLastError() != ERROR_NO_MORE_FILES) {
if (debug) if (debug)
wcout << L"Path name for " << szVolumeName << L"= \""; std::wcout << "Path name for " << szVolumeName << "= \"";
volumeNameEnd = wcslen(szVolumeName) - 1; volumeNameEnd = wcslen(szVolumeName) - 1;
szVolumePathNames = reinterpret_cast<wchar_t*>(new WCHAR[dwVolumePathNamesLen]); szVolumePathNames = reinterpret_cast<WCHAR*>(new WCHAR[dwVolumePathNamesLen]);
while (!GetVolumePathNamesForVolumeName(szVolumeName, szVolumePathNames, dwVolumePathNamesLen, &dwVolumePathNamesLen)) { while (!GetVolumePathNamesForVolumeName(szVolumeName, szVolumePathNames, dwVolumePathNamesLen, &dwVolumePathNamesLen)) {
if (GetLastError() != ERROR_MORE_DATA) if (GetLastError() != ERROR_MORE_DATA)
break; break;
delete[] reinterpret_cast<wchar_t*>(szVolumePathNames); delete[] reinterpret_cast<WCHAR*>(szVolumePathNames);
szVolumePathNames = reinterpret_cast<wchar_t*>(new WCHAR[dwVolumePathNamesLen]); szVolumePathNames = reinterpret_cast<WCHAR*>(new WCHAR[dwVolumePathNamesLen]);
} }
if (debug) if (debug)
wcout << szVolumePathNames << L"\"" << endl; std::wcout << szVolumePathNames << "\"\n";
//.insert() does the dublicate checking sDrives.insert(std::wstring(szVolumePathNames));
sDrives.insert(wstring(szVolumePathNames));
FindNextVolume(hVolume, szVolumeName, MAX_PATH); FindNextVolume(hVolume, szVolumeName, MAX_PATH);
} }
if (debug) if (debug)
wcout << L"Creating vector from found volumes, ignoring cd drives etc.:" << endl; std::wcout << "Creating vector from found volumes, ignoring cd drives etc.:\n";
for (set<wstring>::iterator it = sDrives.begin(); it != sDrives.end(); ++it) { for (std::set<std::wstring>::iterator it = sDrives.begin(); it != sDrives.end(); ++it) {
UINT type = GetDriveType(it->c_str()); UINT type = GetDriveType(it->c_str());
if (type == DRIVE_FIXED || type == DRIVE_REMOTE) { if (type == DRIVE_FIXED || type == DRIVE_REMOTE) {
if (debug) if (debug)
wcout << L"\t" << *it << endl; std::wcout << "\t" << *it << '\n';
vDrives.push_back(drive(*it)); vDrives.push_back(drive(*it));
} }
} }
FindVolumeClose(hVolume); FindVolumeClose(hVolume);
if (szVolumePathNames) if (szVolumePathNames)
delete[] reinterpret_cast<wchar_t*>(szVolumePathNames); delete[] reinterpret_cast<WCHAR*>(szVolumePathNames);
return -1; return -1;
die: die:
@ -342,45 +312,45 @@ die:
return 3; return 3;
} }
int check_drives(vector<drive>& vDrives, printInfoStruct& printInfo) INT check_drives(std::vector<drive>& vDrives, printInfoStruct& printInfo)
{ {
wchar_t *slash = L"\\"; WCHAR *slash = L"\\";
if (debug) if (debug)
wcout << L"Parsing user input drive names" << endl; std::wcout << "Parsing user input drive names\n";
for (vector<wstring>::iterator it = printInfo.drives.begin(); for (std::vector<std::wstring>::iterator it = printInfo.drives.begin();
it != printInfo.drives.end(); ++it) { it != printInfo.drives.end(); ++it) {
if (it->at(it->length() - 1) != *slash) if (it->at(it->length() - 1) != *slash)
it->append(slash); it->append(slash);
if (std::wstring::npos == it->find(L":\\")) { 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; return 3;
} }
if (debug) if (debug)
wcout << L"Added " << *it << endl; std::wcout << "Added " << *it << '\n';
vDrives.push_back(drive(*it)); vDrives.push_back(drive(*it));
} }
return -1; return -1;
} }
bool getFreeAndCap(drive& drive, const Bunit& unit) BOOL getFreeAndCap(drive& drive, const Bunit& unit)
{ {
if (debug) 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; ULARGE_INTEGER tempFree, tempTotal;
if (!GetDiskFreeSpaceEx(drive.name.c_str(), NULL, &tempTotal, &tempFree)) { if (!GetDiskFreeSpaceEx(drive.name.c_str(), NULL, &tempTotal, &tempFree)) {
return FALSE; return FALSE;
} }
if (debug) if (debug)
wcout << L"\tcap: " << tempFree.QuadPart << endl; std::wcout << "\tcap: " << tempFree.QuadPart << '\n';
drive.cap = round((tempTotal.QuadPart / pow(1024.0, unit))); drive.cap = round((tempTotal.QuadPart / pow(1024.0, unit)));
if (debug) if (debug)
wcout << L"\tAfter conversion: " << drive.cap << endl std::wcout << "\tAfter conversion: " << drive.cap << '\n'
<< L"\tfree: " << tempFree.QuadPart << endl; << "\tfree: " << tempFree.QuadPart << '\n';
drive.free = round((tempFree.QuadPart / pow(1024.0, unit))); drive.free = round((tempFree.QuadPart / pow(1024.0, unit)));
if (debug) if (debug)
wcout << L"\tAfter conversion: " << drive.free << endl << endl; std::wcout << "\tAfter conversion: " << drive.free << '\n' << '\n';
return TRUE; return TRUE;
} }

51
plugins/check_disk.h Normal file
View File

@ -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 <Windows.h>
#include <vector>
#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<std::wstring> drives;
Bunit unit;
};
INT parseArguments(int, wchar_t **, boost::program_options::variables_map&, printInfoStruct&);
INT printOutput(printInfoStruct&, std::vector<drive>&);
INT check_drives(std::vector<drive>&);
INT check_drives(std::vector<drive>&, printInfoStruct&);
BOOL getFreeAndCap(drive&, const Bunit&);
#endif /*CHECK_DISK_H*/

View File

@ -17,40 +17,29 @@
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
******************************************************************************/ ******************************************************************************/
#include "thresholds.h"
#include <boost/program_options.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <Pdh.h> #include <Pdh.h>
#include <Shlwapi.h> #include <Shlwapi.h>
#include <pdhmsg.h> #include <pdhmsg.h>
#include <iostream> #include <iostream>
#include "check_load.h"
#include "boost/algorithm/string/split.hpp"
#include "boost/algorithm/string/classification.hpp"
#define VERSION 1.0 #define VERSION 1.0
namespace po = boost::program_options; namespace po = boost::program_options;
using std::endl; using std::cout; using std::wstring;
using std::wcout;
static BOOL debug = FALSE; static BOOL debug = FALSE;
struct printInfoStruct
{
threshold warn, crit;
double load;
};
static int parseArguments(int, wchar_t **, po::variables_map&, printInfoStruct&); INT wmain(INT argc, WCHAR **argv)
static int printOutput(printInfoStruct&);
static int check_load(printInfoStruct&);
int wmain(int argc, wchar_t **argv)
{ {
printInfoStruct printInfo{ }; printInfoStruct printInfo{ };
po::variables_map vm; po::variables_map vm;
int ret = parseArguments(argc, argv, vm, printInfo); INT ret = parseArguments(argc, argv, vm, printInfo);
if (ret != -1) if (ret != -1)
return ret; return ret;
@ -61,7 +50,7 @@ int wmain(int argc, wchar_t **argv)
return printOutput(printInfo); 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_t namePath[MAX_PATH];
GetModuleFileName(NULL, namePath, MAX_PATH); GetModuleFileName(NULL, namePath, MAX_PATH);
wchar_t *progName = PathFindFileName(namePath); 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; po::options_description desc;
desc.add_options() desc.add_options()
("help,h", "print usage message and exit") ("help,h", "Print usage message and exit")
("version,V", "print version and exit") ("version,V", "Print version and exit")
("debug,d", "Verbose/Debug output") ("debug,d", "Verbose/Debug output")
("warning,w", po::wvalue<wstring>(), "warning value (in percent)") ("warning,w", po::wvalue<std::wstring>(), "Warning value (in percent)")
("critical,c", po::wvalue<wstring>(), "critical value (in percent)") ("critical,c", po::wvalue<std::wstring>(), "Critical value (in percent)")
; ;
po::basic_command_line_parser<wchar_t> parser(ac, av); po::basic_command_line_parser<wchar_t> parser(ac, av);
@ -89,16 +78,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
vm); vm);
vm.notify(); vm.notify();
} catch (std::exception& e) { } catch (std::exception& e) {
cout << e.what() << endl << desc << endl; std::cout << e.what() << '\n' << desc << '\n';
return 3; return 3;
} }
if (vm.count("help")) { if (vm.count("help")) {
wcout << progName << " Help\n\tVersion: " << VERSION << endl; std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n';
wprintf( wprintf(
L"%s is a simple program to check a machines CPU load.\n" 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); L"You can use the following options to define its behaviour:\n\n", progName);
cout << desc; std::cout << desc;
wprintf( wprintf(
L"\nIt will then output a string looking something like this:\n\n" 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" 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"to end with a percentage sign.\n\n"
L"All of these options work with the critical threshold \"-c\" too." L"All of these options work with the critical threshold \"-c\" too."
, progName); , progName);
cout << endl; std::cout << '\n';
return 0; return 0;
} }
if (vm.count("version")) if (vm.count("version"))
cout << "Version: " << VERSION << endl; std::cout << "Version: " << VERSION << '\n';
if (vm.count("warning")) { if (vm.count("warning")) {
try { try {
std::wstring wthreshold = vm["warning"].as<wstring>(); std::wstring wthreshold = vm["warning"].as<std::wstring>();
std::vector<std::wstring> tokens; std::vector<std::wstring> tokens;
boost::algorithm::split(tokens, wthreshold, boost::algorithm::is_any_of(",")); boost::algorithm::split(tokens, wthreshold, boost::algorithm::is_any_of(","));
printInfo.warn = threshold(tokens[0]); printInfo.warn = threshold(tokens[0]);
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
} }
if (vm.count("critical")) { if (vm.count("critical")) {
try { try {
std::wstring cthreshold = vm["critical"].as<wstring>(); std::wstring cthreshold = vm["critical"].as<std::wstring>();
std::vector<std::wstring> tokens; std::vector<std::wstring> tokens;
boost::algorithm::split(tokens, cthreshold, boost::algorithm::is_any_of(",")); boost::algorithm::split(tokens, cthreshold, boost::algorithm::is_any_of(","));
printInfo.crit = threshold(tokens[0]); printInfo.crit = threshold(tokens[0]);
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
} }
@ -165,10 +154,10 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
return -1; return -1;
} }
int printOutput(printInfoStruct& printInfo) INT printOutput(printInfoStruct& printInfo)
{ {
if (debug) if (debug)
wcout << L"Constructing output string" << endl; std::wcout << L"Constructing output string" << '\n';
state state = OK; state state = OK;
@ -180,24 +169,24 @@ int printOutput(printInfoStruct& printInfo)
std::wstringstream perf; std::wstringstream perf;
perf << L"% | load=" << printInfo.load << L"%;" << printInfo.warn.pString() << L";" 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) { switch (state) {
case OK: case OK:
wcout << L"LOAD OK " << printInfo.load << perf.str(); std::wcout << L"LOAD OK " << printInfo.load << perf.str();
break; break;
case WARNING: case WARNING:
wcout << L"LOAD WARNING " << printInfo.load << perf.str(); std::wcout << L"LOAD WARNING " << printInfo.load << perf.str();
break; break;
case CRITICAL: case CRITICAL:
wcout << L"LOAD CRITICAL " << printInfo.load << perf.str(); std::wcout << L"LOAD CRITICAL " << printInfo.load << perf.str();
break; break;
} }
return state; return state;
} }
int check_load(printInfoStruct& printInfo) INT check_load(printInfoStruct& printInfo)
{ {
PDH_HQUERY phQuery = NULL; PDH_HQUERY phQuery = NULL;
PDH_HCOUNTER phCounter; PDH_HCOUNTER phCounter;
@ -209,7 +198,7 @@ int check_load(printInfoStruct& printInfo)
LPCWSTR path = L"\\Processor(_Total)\\% Idle Time"; LPCWSTR path = L"\\Processor(_Total)\\% Idle Time";
if (debug) if (debug)
wcout << L"Creating query and adding counter" << endl; std::wcout << L"Creating query and adding counter" << '\n';
err = PdhOpenQuery(NULL, NULL, &phQuery); err = PdhOpenQuery(NULL, NULL, &phQuery);
if (!SUCCEEDED(err)) if (!SUCCEEDED(err))
@ -220,37 +209,37 @@ int check_load(printInfoStruct& printInfo)
goto die; goto die;
if (debug) if (debug)
wcout << L"Collecting first batch of query data" << endl; std::wcout << L"Collecting first batch of query data" << '\n';
err = PdhCollectQueryData(phQuery); err = PdhCollectQueryData(phQuery);
if (!SUCCEEDED(err)) if (!SUCCEEDED(err))
goto die; goto die;
if (debug) if (debug)
wcout << L"Sleep for one second" << endl; std::wcout << L"Sleep for one second" << '\n';
Sleep(1000); Sleep(1000);
if (debug) if (debug)
wcout << L"Collecting second batch of query data" << endl; std::wcout << L"Collecting second batch of query data" << '\n';
err = PdhCollectQueryData(phQuery); err = PdhCollectQueryData(phQuery);
if (!SUCCEEDED(err)) if (!SUCCEEDED(err))
goto die; goto die;
if (debug) 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); err = PdhGetFormattedCounterValue(phCounter, PDH_FMT_DOUBLE, &CounterType, &DisplayValue);
if (SUCCEEDED(err)) { if (SUCCEEDED(err)) {
if (DisplayValue.CStatus == PDH_CSTATUS_VALID_DATA) { if (DisplayValue.CStatus == PDH_CSTATUS_VALID_DATA) {
if (debug) 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; printInfo.load = 100.0 - DisplayValue.doubleValue;
} }
if (debug) if (debug)
wcout << L"Finished collection. Cleaning up and returning" << endl; std::wcout << L"Finished collection. Cleaning up and returning" << '\n';
PdhCloseQuery(phQuery); PdhCloseQuery(phQuery);
return -1; return -1;

35
plugins/check_load.h Normal file
View File

@ -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

View File

@ -20,36 +20,20 @@
#include <iostream> #include <iostream>
#include <WinBase.h> #include <WinBase.h>
#include "thresholds.h" #include "check_memory.h"
#include "boost/program_options.hpp"
#define VERSION 1.0 #define VERSION 1.0
namespace po = boost::program_options; namespace po = boost::program_options;
using std::endl; using std::wcout; using std::wstring;
using std::cout;
static BOOL debug = FALSE; static BOOL debug = FALSE;
struct printInfoStruct INT wmain(INT argc, WCHAR **argv)
{
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)
{ {
printInfoStruct printInfo = {}; printInfoStruct printInfo = {};
po::variables_map vm; po::variables_map vm;
int ret = parseArguments(argc, argv, vm, printInfo); INT ret = parseArguments(argc, argv, vm, printInfo);
if (ret != -1) if (ret != -1)
return ret; return ret;
@ -60,24 +44,24 @@ int wmain(int argc, wchar_t **argv)
return printOutput(printInfo); 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); GetModuleFileName(NULL, namePath, MAX_PATH);
wchar_t *progName = PathFindFileName(namePath); WCHAR *progName = PathFindFileName(namePath);
po::options_description desc; po::options_description desc;
desc.add_options() desc.add_options()
("help,h", "print help message and exit") ("help,h", "Print help message and exit")
("version,V", "print version and exit") ("version,V", "Print version and exit")
("debug,d", "Verbose/Debug output") ("debug,d", "Verbose/Debug output")
("warning,w", po::wvalue<wstring>(), "warning threshold") ("warning,w", po::wvalue<std::wstring>(), "Warning threshold")
("critical,c", po::wvalue<wstring>(), "critical threshold") ("critical,c", po::wvalue<std::wstring>(), "Critical threshold")
("unit,u", po::wvalue<wstring>(), "the unit to use for display (default MB)") ("unit,u", po::wvalue<std::wstring>(), "The unit to use for display (default MB)")
; ;
po::basic_command_line_parser<wchar_t> parser(ac, av); po::basic_command_line_parser<WCHAR> parser(ac, av);
try { try {
po::store( po::store(
@ -90,16 +74,16 @@ int parseArguments(int ac, wchar_t ** av, po::variables_map& vm, printInfoStruct
vm); vm);
vm.notify(); vm.notify();
} catch (std::exception& e) { } catch (std::exception& e) {
cout << e.what() << endl << desc << endl; std::cout << e.what() << '\n' << desc << '\n';
return 3; return 3;
} }
if (vm.count("help")) { if (vm.count("help")) {
wcout << progName << " Help\n\tVersion: " << VERSION << endl; std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n';
wprintf( wprintf(
L"%s is a simple program to check a machines physical memory.\n" 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); L"You can use the following options to define its behaviour:\n\n", progName);
cout << desc; std::cout << desc;
wprintf( wprintf(
L"\nIt will then output a string looking something like this:\n\n" 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" 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"to end with a percentage sign.\n\n"
L"All of these options work with the critical threshold \"-c\" too.\n" L"All of these options work with the critical threshold \"-c\" too.\n"
, progName); , progName);
cout << endl; std::cout << '\n';
return 0; return 0;
} }
if (vm.count("version")) if (vm.count("version"))
wcout << L"Version: " << VERSION << endl; std::wcout << L"Version: " << VERSION << '\n';
if (vm.count("warning")) { if (vm.count("warning")) {
try { try {
printInfo.warn = threshold(vm["warning"].as<wstring>()); printInfo.warn = threshold(vm["warning"].as<std::wstring>());
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
printInfo.warn.legal = !printInfo.warn.legal; 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")) { if (vm.count("critical")) {
try { try {
printInfo.crit = threshold(vm["critical"].as<wstring>()); printInfo.crit = threshold(vm["critical"].as<std::wstring>());
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
printInfo.crit.legal = !printInfo.crit.legal; 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")) { if (vm.count("unit")) {
try { try {
printInfo.unit = parseBUnit(vm["unit"].as<wstring>()); printInfo.unit = parseBUnit(vm["unit"].as<std::wstring>());
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
} }
@ -173,10 +157,10 @@ int parseArguments(int ac, wchar_t ** av, po::variables_map& vm, printInfoStruct
return -1; return -1;
} }
int printOutput(printInfoStruct& printInfo) INT printOutput(printInfoStruct& printInfo)
{ {
if (debug) if (debug)
wcout << L"Constructing output string" << endl; std::wcout << L"Constructing output string" << '\n';
state state = OK; state state = OK;
double fswap = ((double)printInfo.aRam / (double)printInfo.tRam) * 100.0; double fswap = ((double)printInfo.aRam / (double)printInfo.tRam) * 100.0;
@ -189,29 +173,29 @@ int printOutput(printInfoStruct& printInfo)
switch (state) { switch (state) {
case OK: 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) << printInfo.warn.pString(printInfo.tRam) << L";" << printInfo.crit.pString(printInfo.tRam)
<< L";0;" << printInfo.tRam << endl; << L";0;" << printInfo.tRam << '\n';
break; break;
case WARNING: 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) << printInfo.warn.pString(printInfo.tRam) << L";" << printInfo.crit.pString(printInfo.tRam)
<< L";0;" << printInfo.tRam << endl; << L";0;" << printInfo.tRam << '\n';
break; break;
case CRITICAL: 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) << printInfo.warn.pString(printInfo.tRam) << L";" << printInfo.crit.pString(printInfo.tRam)
<< L";0;" << printInfo.tRam << endl; << L";0;" << printInfo.tRam << '\n';
break; break;
} }
return state; return state;
} }
int check_memory(printInfoStruct& printInfo) INT check_memory(printInfoStruct& printInfo)
{ {
if (debug) if (debug)
wcout << L"Accessing memory statistics via MemoryStatus" << endl; std::wcout << L"Accessing memory statistics via MemoryStatus" << '\n';
_MEMORYSTATUSEX *pMemBuf = new _MEMORYSTATUSEX; _MEMORYSTATUSEX *pMemBuf = new _MEMORYSTATUSEX;
@ -223,8 +207,8 @@ int check_memory(printInfoStruct& printInfo)
printInfo.aRam = round(pMemBuf->ullAvailPhys / pow(1024.0, printInfo.unit)); printInfo.aRam = round(pMemBuf->ullAvailPhys / pow(1024.0, printInfo.unit));
if (debug) if (debug)
wcout << L"Found pMemBuf->dwTotalPhys: " << pMemBuf->ullTotalPhys << endl std::wcout << L"Found pMemBuf->dwTotalPhys: " << pMemBuf->ullTotalPhys << '\n'
<< L"Found pMemBuf->dwAvailPhys: " << pMemBuf->ullAvailPhys << endl; << L"Found pMemBuf->dwAvailPhys: " << pMemBuf->ullAvailPhys << '\n';
delete pMemBuf; delete pMemBuf;

37
plugins/check_memory.h Normal file
View File

@ -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

View File

@ -16,63 +16,54 @@
* along with this program; if not, write to the Free Software Foundation * * along with this program; if not, write to the Free Software Foundation *
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
******************************************************************************/ ******************************************************************************/
#define WIN32_LEAN_AND_MEAN
#include <Windows.h> #include <Windows.h>
#include <Pdh.h> #include <Pdh.h>
#include <Shlwapi.h> #include <Shlwapi.h>
#include <iostream> #include <iostream>
#include <pdhmsg.h> #include <pdhmsg.h>
#include <WinSock2.h>
#include <map>
#include "thresholds.h" #include <IPHlpApi.h>
#include "boost/program_options.hpp" #include "check_network.h"
#define VERSION 1.1
#define VERSION 1.0
namespace po = boost::program_options; namespace po = boost::program_options;
using std::endl; using std::vector; using std::wstring;
using std::wcout; using std::cout;
static BOOL debug = FALSE; static BOOL debug = FALSE;
struct nInterface INT wmain(INT argc, WCHAR **argv)
{ {
wstring name; std::vector<nInterface> vInterfaces;
long BytesInSec, BytesOutSec; std::map<std::wstring, std::wstring> mapNames;
nInterface(wstring p) printInfoStruct printInfo{};
: name(p)
{}
};
struct printInfoStruct
{
threshold warn, crit;
};
static int parseArguments(int, TCHAR **, po::variables_map&, printInfoStruct&);
static int printOutput(printInfoStruct&, const vector<nInterface>&);
static int check_network(vector<nInterface>&);
int wmain(int argc, wchar_t **argv)
{
vector<nInterface> vInterfaces;
printInfoStruct printInfo{ };
po::variables_map vm; po::variables_map vm;
int ret = parseArguments(argc, argv, vm, printInfo);
INT ret = parseArguments(argc, argv, vm, printInfo);
if (ret != -1) if (ret != -1)
return ret; return ret;
if (!mapSystemNamesToFamiliarNames(mapNames))
return 3;
ret = check_network(vInterfaces); ret = check_network(vInterfaces);
if (ret != -1) if (ret != -1)
return ret; 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); GetModuleFileName(NULL, namePath, MAX_PATH);
wchar_t *progName = PathFindFileName(namePath); WCHAR *progName = PathFindFileName(namePath);
po::options_description desc("Options"); 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") ("help,h", "print usage and exit")
("version,V", "print version and exit") ("version,V", "print version and exit")
("debug,d", "Verbose/Debug output") ("debug,d", "Verbose/Debug output")
("warning,w", po::wvalue<wstring>(), "warning value") ("warning,w", po::wvalue<std::wstring>(), "warning value")
("critical,c", po::wvalue<wstring>(), "critical value") ("critical,c", po::wvalue<std::wstring>(), "critical value")
; ;
po::basic_command_line_parser<wchar_t> parser(ac, av); po::basic_command_line_parser<WCHAR> parser(ac, av);
try { try {
po::store( po::store(
@ -97,20 +88,20 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
vm); vm);
vm.notify(); vm.notify();
} catch (std::exception& e) { } catch (std::exception& e) {
cout << e.what() << endl << desc << endl; std::cout << e.what() << '\n' << desc << '\n';
return 3; return 3;
} }
if (vm.count("help")) { if (vm.count("help")) {
wcout << progName << " Help\n\tVersion: " << VERSION << endl; std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n';
wprintf( wprintf(
L"%s is a simple program to check a machines network performance.\n" 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); L"You can use the following options to define its behaviour:\n\n", progName);
cout << desc; std::cout << desc;
wprintf( wprintf(
L"\nIt will then output a string looking something like this:\n\n" 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"\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"and \"1131B/s\" is the returned value.\n"
L"The performance data is found behind the \"|\", in order:\n" L"The performance data is found behind the \"|\", in order:\n"
L"returned value, warning threshold, critical threshold, minimal value and,\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"to end with a percentage sign.\n\n"
L"All of these options work with the critical threshold \"-c\" too." L"All of these options work with the critical threshold \"-c\" too."
, progName); , progName);
cout << endl; std::cout << '\n';
return 0; return 0;
} }
if (vm.count("version")) if (vm.count("version"))
cout << "Version: " << VERSION << endl; std::cout << "Version: " << VERSION << '\n';
if (vm.count("warning")) { if (vm.count("warning")) {
try { try {
printInfo.warn = threshold(vm["warning"].as<wstring>()); printInfo.warn = threshold(vm["warning"].as<std::wstring>());
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
} }
if (vm.count("critical")) { if (vm.count("critical")) {
try { try {
printInfo.crit = threshold(vm["critical"].as<wstring>()); printInfo.crit = threshold(vm["critical"].as<std::wstring>());
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
} }
@ -170,19 +161,34 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
return -1; return -1;
} }
int printOutput(printInfoStruct& printInfo, const vector<nInterface>& vInterfaces) INT printOutput(printInfoStruct& printInfo, CONST std::vector<nInterface>& vInterfaces, CONST std::map<std::wstring, std::wstring>& mapNames)
{ {
if (debug) if (debug)
wcout << L"Constructing output string" << endl; std::wcout << L"Constructing output string" << '\n';
long tIn = 0, tOut = 0; long tIn = 0, tOut = 0;
std::wstringstream tss, perfDataFirst; std::wstringstream tss, perfDataFirst;
state state = OK; state state = OK;
for (vector<nInterface>::const_iterator it = vInterfaces.begin(); it != vInterfaces.end(); ++it) { std::map<std::wstring, std::wstring>::const_iterator mapIt;
std::wstring wsFriendlyName;
for (std::vector<nInterface>::const_iterator it = vInterfaces.begin(); it != vInterfaces.end(); ++it) {
tIn += it->BytesInSec; tIn += it->BytesInSec;
tOut += it->BytesOutSec; 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)) if (printInfo.warn.rend(tIn + tOut))
@ -194,23 +200,23 @@ int printOutput(printInfoStruct& printInfo, const vector<nInterface>& vInterface
switch (state) { switch (state) {
case OK: 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; break;
case WARNING: 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; break;
case CRITICAL: 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; break;
} }
return state; return state;
} }
int check_network(vector <nInterface>& vInterfaces) INT check_network(std::vector <nInterface>& vInterfaces)
{ {
const wchar_t *perfIn = L"\\Network Interface(*)\\Bytes Received/sec"; CONST WCHAR *perfIn = L"\\Network Interface(*)\\Bytes Received/sec";
const wchar_t *perfOut = L"\\Network Interface(*)\\Bytes Sent/sec"; CONST WCHAR *perfOut = L"\\Network Interface(*)\\Bytes Sent/sec";
PDH_HQUERY phQuery = NULL; PDH_HQUERY phQuery = NULL;
PDH_HCOUNTER phCounterIn, phCounterOut; PDH_HCOUNTER phCounterIn, phCounterOut;
@ -219,7 +225,7 @@ int check_network(vector <nInterface>& vInterfaces)
PDH_STATUS err; PDH_STATUS err;
if (debug) if (debug)
wcout << L"Creating Query and adding counters" << endl; std::wcout << L"Creating Query and adding counters" << '\n';
err = PdhOpenQuery(NULL, NULL, &phQuery); err = PdhOpenQuery(NULL, NULL, &phQuery);
if (!SUCCEEDED(err)) if (!SUCCEEDED(err))
@ -234,26 +240,26 @@ int check_network(vector <nInterface>& vInterfaces)
goto die; goto die;
if (debug) if (debug)
wcout << L"Collecting first batch of query data" << endl; std::wcout << L"Collecting first batch of query data" << '\n';
err = PdhCollectQueryData(phQuery); err = PdhCollectQueryData(phQuery);
if (!SUCCEEDED(err)) if (!SUCCEEDED(err))
goto die; goto die;
if (debug) if (debug)
wcout << L"Sleep for one second" << endl; std::wcout << L"Sleep for one second" << '\n';
Sleep(1000); Sleep(1000);
if (debug) if (debug)
wcout << L"Collecting second batch of query data" << endl; std::wcout << L"Collecting second batch of query data" << '\n';
err = PdhCollectQueryData(phQuery); err = PdhCollectQueryData(phQuery);
if (!SUCCEEDED(err)) if (!SUCCEEDED(err))
goto die; goto die;
if (debug) 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); err = PdhGetFormattedCounterArray(phCounterIn, PDH_FMT_LONG, &dwBufferSizeIn, &dwItemCount, pDisplayValuesIn);
if (err == PDH_MORE_DATA || SUCCEEDED(err)) if (err == PDH_MORE_DATA || SUCCEEDED(err))
@ -276,18 +282,18 @@ int check_network(vector <nInterface>& vInterfaces)
goto die; goto die;
if (debug) if (debug)
wcout << L"Going over counter array" << endl; std::wcout << L"Going over counter array" << '\n';
for (DWORD i = 0; i < dwItemCount; i++) { 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->BytesInSec = pDisplayValuesIn[i].FmtValue.longValue;
iface->BytesOutSec = pDisplayValuesOut[i].FmtValue.longValue; iface->BytesOutSec = pDisplayValuesOut[i].FmtValue.longValue;
vInterfaces.push_back(*iface); vInterfaces.push_back(*iface);
if (debug) if (debug)
wcout << L"Collected interface " << pDisplayValuesIn[i].szName << endl; std::wcout << L"Collected interface " << pDisplayValuesIn[i].szName << '\n';
} }
if (debug) if (debug)
wcout << L"Finished collection. Cleaning up and returning" << endl; std::wcout << L"Finished collection. Cleaning up and returning" << '\n';
if (phQuery) if (phQuery)
PdhCloseQuery(phQuery); PdhCloseQuery(phQuery);
@ -306,3 +312,61 @@ die:
delete reinterpret_cast<PDH_FMT_COUNTERVALUE_ITEM*>(pDisplayValuesOut); delete reinterpret_cast<PDH_FMT_COUNTERVALUE_ITEM*>(pDisplayValuesOut);
return 3; return 3;
} }
BOOL mapSystemNamesToFamiliarNames(std::map<std::wstring, std::wstring>& 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<PIP_ADAPTER_ADDRESSES>(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<std::wstring, std::wstring>(wssAdapterName.str(), wssFriendlyName.str()));
}
delete[]pAddresses;
return TRUE;
}

47
plugins/check_network.h Normal file
View File

@ -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 <vector>
#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<nInterface>&, CONST std::map<std::wstring, std::wstring>&);
INT check_network(std::vector<nInterface>&);
BOOL mapSystemNamesToFamiliarNames(std::map<std::wstring, std::wstring>&);
#endif // !CHECK_NETWORK_H

View File

@ -31,39 +31,15 @@
#include <iostream> #include <iostream>
#include "thresholds.h" #include "check_ping.h"
#include "boost/program_options.hpp"
#define VERSION 1.0 #define VERSION 1.0
namespace po = boost::program_options; namespace po = boost::program_options;
using std::cout; using std::endl; using std::wcout;
using std::wstring; using std::string;
static BOOL debug = FALSE; static BOOL debug = FALSE;
struct response INT wmain(INT argc, WCHAR **argv)
{
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)
{ {
po::variables_map vm; po::variables_map vm;
printInfoStruct printInfo; printInfoStruct printInfo;
@ -88,28 +64,28 @@ int wmain(int argc, wchar_t **argv)
return printOutput(printInfo, response); 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); GetModuleFileName(NULL, namePath, MAX_PATH);
wchar_t *progName = PathFindFileName(namePath); WCHAR *progName = PathFindFileName(namePath);
po::options_description desc; po::options_description desc;
desc.add_options() desc.add_options()
("help,h", "print usage message and exit") ("help,h", "Print usage message and exit")
("version,V", "print version and exit") ("version,V", "Print version and exit")
("debug,d", "Verbose/Debug output") ("debug,d", "Verbose/Debug output")
("host,H", po::wvalue<wstring>()->required(), "host ip to ping") ("host,H", po::wvalue<std::wstring>()->required(), "Host ip to ping")
(",4", "--host is an ipv4 address (default)") (",4", "--Host is an ipv4 address (default)")
(",6", "--host is an ipv6 address") (",6", "--Host is an ipv6 address")
("timeout,T", po::value<int>(), "specify timeout for requests in ms (default=1000)") ("timeout,t", po::value<INT>(), "Specify timeout for requests in ms (default=1000)")
("ncount,n", po::value<int>(), "declare ping count (default=5)") ("packets,p", po::value<INT>(), "Declare ping count (default=5)")
("warning,w", po::wvalue<wstring>(), "warning values: rtt,package loss") ("warning,w", po::wvalue<std::wstring>(), "Warning values: rtt,package loss")
("critical,c", po::wvalue<wstring>(), "critical values: rtt,package loss") ("critical,c", po::wvalue<std::wstring>(), "Critical values: rtt,package loss")
; ;
po::basic_command_line_parser<wchar_t> parser(ac, av); po::basic_command_line_parser<WCHAR> parser(ac, av);
try { try {
po::store( po::store(
@ -124,16 +100,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
vm); vm);
vm.notify(); vm.notify();
} catch (std::exception& e) { } catch (std::exception& e) {
cout << e.what() << endl << desc << endl; std::cout << e.what() << '\n' << desc << '\n';
return 3; return 3;
} }
if (vm.count("help")) { if (vm.count("help")) {
wcout << progName << " Help\n\tVersion: " << VERSION << endl; std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n';
wprintf( wprintf(
L"%s is a simple program to ping an ip4 address.\n" 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); L"You can use the following options to define its behaviour:\n\n", progName);
cout << desc; std::cout << desc;
wprintf( wprintf(
L"\nIt will take at least timeout times number of pings to run\n" 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" 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"to end with a percentage sign.\n\n"
L"All of these options work with the critical threshold \"-c\" too." L"All of these options work with the critical threshold \"-c\" too."
, progName); , progName);
cout << endl; std::cout << '\n';
return 0; return 0;
} }
if (vm.count("version")) { if (vm.count("version")) {
cout << progName << " Version: " << VERSION << endl; std::cout << progName << " Version: " << VERSION << '\n';
return 0; return 0;
} }
if (vm.count("-4") && vm.count("-6")) { if (vm.count("-4") && vm.count("-6")) {
cout << "Conflicting options \"4\" and \"6\"" << endl; std::cout << "Conflicting options \"4\" and \"6\"" << '\n';
return 3; return 3;
} }
if (vm.count("warning")) { if (vm.count("warning")) {
std::vector<wstring> sVec = splitMultiOptions(vm["warning"].as<wstring>()); std::vector<std::wstring> sVec = splitMultiOptions(vm["warning"].as<std::wstring>());
if (sVec.size() != 2) { if (sVec.size() != 2) {
cout << "Wrong format for warning thresholds" << endl; std::cout << "Wrong format for warning thresholds" << '\n';
return 3; return 3;
} }
try { try {
printInfo.warn = threshold(*sVec.begin()); printInfo.warn = threshold(*sVec.begin());
printInfo.wpl = threshold(sVec.back()); printInfo.wpl = threshold(sVec.back());
if (!printInfo.wpl.perc) { if (!printInfo.wpl.perc) {
cout << "Packet loss must be percentage" << endl; std::cout << "Packet loss must be percentage" << '\n';
return 3; return 3;
} }
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
} }
if (vm.count("critical")) { if (vm.count("critical")) {
std::vector<wstring> sVec = splitMultiOptions(vm["critical"].as<wstring>()); std::vector<std::wstring> sVec = splitMultiOptions(vm["critical"].as<std::wstring>());
if (sVec.size() != 2) { if (sVec.size() != 2) {
cout << "Wrong format for critical thresholds" << endl; std::cout << "Wrong format for critical thresholds" << '\n';
return 3; return 3;
} }
try { try {
printInfo.crit = threshold(*sVec.begin()); printInfo.crit = threshold(*sVec.begin());
printInfo.cpl = threshold(sVec.back()); printInfo.cpl = threshold(sVec.back());
if (!printInfo.wpl.perc) { if (!printInfo.wpl.perc) {
cout << "Packet loss must be percentage" << endl; std::cout << "Packet loss must be percentage" << '\n';
return 3; return 3;
} }
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
} }
if (vm.count("timeout")) if (vm.count("timeout"))
printInfo.timeout = vm["timeout"].as<int>(); printInfo.timeout = vm["timeout"].as<INT>();
if (vm.count("count")) if (vm.count("count"))
printInfo.num = vm["count"].as<int>(); printInfo.num = vm["count"].as<INT>();
if (vm.count("-6")) if (vm.count("-6"))
printInfo.ipv4 = FALSE; printInfo.ipv4 = FALSE;
printInfo.host = vm["host"].as<wstring>(); printInfo.host = vm["host"].as<std::wstring>();
if (vm.count("debug")) if (vm.count("debug"))
debug = TRUE; debug = TRUE;
@ -231,10 +207,10 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
return -1; return -1;
} }
int printOutput(printInfoStruct& printInfo, response& response) INT printOutput(printInfoStruct& printInfo, response& response)
{ {
if (debug) if (debug)
wcout << L"Constructing output string" << endl; std::wcout << L"Constructing output string" << '\n';
state state = OK; state state = OK;
@ -252,51 +228,51 @@ int printOutput(printInfoStruct& printInfo, response& response)
<< printInfo.wpl.pString() << ";" << printInfo.cpl.pString() << ";0;100"; << printInfo.wpl.pString() << ";" << printInfo.cpl.pString() << ";0;100";
if (response.dropped == printInfo.num) { 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; return 3;
} }
switch (state) { switch (state) {
case OK: 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; break;
case WARNING: 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; break;
case CRITICAL: 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; break;
} }
return state; return state;
} }
int check_ping4(const printInfoStruct& pi, response& response) INT check_ping4(const printInfoStruct& pi, response& response)
{ {
in_addr ipDest4; in_addr ipDest4;
HANDLE hIcmp; HANDLE hIcmp;
DWORD dwRet = 0, dwRepSize = 0; DWORD dwRet = 0, dwRepSize = 0;
LPVOID repBuf = NULL; LPVOID repBuf = NULL;
UINT rtt = 0; UINT rtt = 0;
int num = pi.num; INT num = pi.num;
LARGE_INTEGER frequency, timer1, timer2; LARGE_INTEGER frequency, timer1, timer2;
LPCWSTR term; LPCWSTR term;
if (debug) 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) { 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; return 3;
} }
if (*term != L'\0') { 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; return 3;
} }
if (debug) if (debug)
wcout << L"Creating Icmp File" << endl; std::wcout << L"Creating Icmp File\n";
if ((hIcmp = IcmpCreateFile()) == INVALID_HANDLE_VALUE) if ((hIcmp = IcmpCreateFile()) == INVALID_HANDLE_VALUE)
goto die; goto die;
@ -312,30 +288,30 @@ int check_ping4(const printInfoStruct& pi, response& response)
QueryPerformanceCounter(&timer1); QueryPerformanceCounter(&timer1);
if (debug) 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, if (!IcmpSendEcho2(hIcmp, NULL, NULL, NULL, ipDest4.S_un.S_addr,
NULL, 0, NULL, repBuf, dwRepSize, pi.timeout)) { NULL, 0, NULL, repBuf, dwRepSize, pi.timeout)) {
response.dropped++; response.dropped++;
if (debug) if (debug)
wcout << L"Dropped: Response was 0" << endl; std::wcout << L"Dropped: Response was 0" << '\n';
continue; continue;
} }
if (debug) if (debug)
wcout << "Ping recieved" << endl; std::wcout << "Ping recieved" << '\n';
PICMP_ECHO_REPLY pEchoReply = static_cast<PICMP_ECHO_REPLY>(repBuf); PICMP_ECHO_REPLY pEchoReply = static_cast<PICMP_ECHO_REPLY>(repBuf);
if (pEchoReply->Status != IP_SUCCESS) { if (pEchoReply->Status != IP_SUCCESS) {
response.dropped++; response.dropped++;
if (debug) if (debug)
wcout << L"Dropped: echo reply status " << pEchoReply->Status << endl; std::wcout << L"Dropped: echo reply status " << pEchoReply->Status << '\n';
continue; continue;
} }
if (debug) if (debug)
wcout << L"Recorded rtt of " << pEchoReply->RoundTripTime << endl; std::wcout << L"Recorded rtt of " << pEchoReply->RoundTripTime << '\n';
rtt += pEchoReply->RoundTripTime; rtt += pEchoReply->RoundTripTime;
if (response.pMin == 0 || pEchoReply->RoundTripTime < response.pMin) if (response.pMin == 0 || pEchoReply->RoundTripTime < response.pMin)
@ -349,7 +325,7 @@ int check_ping4(const printInfoStruct& pi, response& response)
} while (--num); } while (--num);
if (debug) 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) if (hIcmp)
IcmpCloseHandle(hIcmp); IcmpCloseHandle(hIcmp);
@ -370,9 +346,8 @@ die:
return 3; return 3;
} }
int check_ping6(const printInfoStruct& pi, response& response) INT check_ping6(const printInfoStruct& pi, response& response)
{ {
PCWSTR term;
sockaddr_in6 ipDest6, ipSource6; sockaddr_in6 ipDest6, ipSource6;
IP_OPTION_INFORMATION ipInfo = { 30, 0, 0, 0, NULL }; IP_OPTION_INFORMATION ipInfo = { 30, 0, 0, 0, NULL };
DWORD dwRepSize = sizeof(ICMPV6_ECHO_REPLY) + 8; DWORD dwRepSize = sizeof(ICMPV6_ECHO_REPLY) + 8;
@ -380,14 +355,14 @@ int check_ping6(const printInfoStruct& pi, response& response)
HANDLE hIcmp = NULL; HANDLE hIcmp = NULL;
LARGE_INTEGER frequency, timer1, timer2; LARGE_INTEGER frequency, timer1, timer2;
int num = pi.num; INT num = pi.num;
UINT rtt = 0; UINT rtt = 0;
if (debug) 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)) { 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; return 3;
} }
@ -399,7 +374,7 @@ int check_ping6(const printInfoStruct& pi, response& response)
ipSource6.sin6_port = 0; ipSource6.sin6_port = 0;
if (debug) if (debug)
wcout << L"Creating Icmp File" << endl; std::wcout << L"Creating Icmp File" << '\n';
hIcmp = Icmp6CreateFile(); hIcmp = Icmp6CreateFile();
if (hIcmp == INVALID_HANDLE_VALUE) { if (hIcmp == INVALID_HANDLE_VALUE) {
@ -411,18 +386,18 @@ int check_ping6(const printInfoStruct& pi, response& response)
QueryPerformanceCounter(&timer1); QueryPerformanceCounter(&timer1);
if (debug) if (debug)
wcout << L"Sending Icmp echo" << endl; std::wcout << L"Sending Icmp echo" << '\n';
if (!Icmp6SendEcho2(hIcmp, NULL, NULL, NULL, &ipSource6, &ipDest6, if (!Icmp6SendEcho2(hIcmp, NULL, NULL, NULL, &ipSource6, &ipDest6,
NULL, 0, &ipInfo, repBuf, dwRepSize, pi.timeout)) { NULL, 0, &ipInfo, repBuf, dwRepSize, pi.timeout)) {
response.dropped++; response.dropped++;
if (debug) if (debug)
wcout << L"Dropped: Response was 0" << endl; std::wcout << L"Dropped: Response was 0" << '\n';
continue; continue;
} }
if (debug) if (debug)
wcout << "Ping recieved" << endl; std::wcout << "Ping recieved" << '\n';
Icmp6ParseReplies(repBuf, dwRepSize); Icmp6ParseReplies(repBuf, dwRepSize);
@ -431,14 +406,14 @@ int check_ping6(const printInfoStruct& pi, response& response)
if (pEchoReply->Status != IP_SUCCESS) { if (pEchoReply->Status != IP_SUCCESS) {
response.dropped++; response.dropped++;
if (debug) if (debug)
wcout << L"Dropped: echo reply status " << pEchoReply->Status << endl; std::wcout << L"Dropped: echo reply status " << pEchoReply->Status << '\n';
continue; continue;
} }
rtt += pEchoReply->RoundTripTime; rtt += pEchoReply->RoundTripTime;
if (debug) 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) if (response.pMin == 0 || pEchoReply->RoundTripTime < response.pMin)
response.pMin = pEchoReply->RoundTripTime; response.pMin = pEchoReply->RoundTripTime;
@ -451,7 +426,7 @@ int check_ping6(const printInfoStruct& pi, response& response)
} while (--num); } while (--num);
if (debug) 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) if (hIcmp)
IcmpCloseHandle(hIcmp); IcmpCloseHandle(hIcmp);

46
plugins/check_ping.h Normal file
View File

@ -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

View File

@ -21,36 +21,20 @@
#include <tlhelp32.h> #include <tlhelp32.h>
#include <iostream> #include <iostream>
#include "thresholds.h" #include "check_procs.h"
#include "boost/program_options.hpp"
#define VERSION 1.0 #define VERSION 1.0
namespace po = boost::program_options; namespace po = boost::program_options;
using std::endl; using std::wstring; using std::wcout;
using std::cout;
static BOOL debug = FALSE; static BOOL debug = FALSE;
struct printInfoStruct INT wmain(INT argc, WCHAR **argv)
{
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)
{ {
po::variables_map vm; po::variables_map vm;
printInfoStruct printInfo = { }; printInfoStruct printInfo = { };
int r = parseArguments(argc, argv, vm, printInfo); INT r = parseArguments(argc, argv, vm, printInfo);
if (r != -1) if (r != -1)
return r; return r;
@ -61,24 +45,24 @@ int wmain(int argc, wchar_t **argv)
return printOutput(countProcs(), printInfo); 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); GetModuleFileName(NULL, namePath, MAX_PATH);
wchar_t *progName = PathFindFileName(namePath); WCHAR *progName = PathFindFileName(namePath);
po::options_description desc; po::options_description desc;
desc.add_options() desc.add_options()
("help,h", "print help message and exit") ("help,h", "Print help message and exit")
("version,V", "print version and exit") ("version,V", "Print version and exit")
("debug,d", "Verbose/Debug output") ("debug,d", "Verbose/Debug output")
("user,u", po::wvalue<wstring>(), "count only processes by user [arg]") ("user,u", po::wvalue<std::wstring>(), "Count only processes of user")
("warning,w", po::wvalue<wstring>(), "warning threshold") ("warning,w", po::wvalue<std::wstring>(), "Warning threshold")
("critical,c", po::wvalue<wstring>(), "critical threshold") ("critical,c", po::wvalue<std::wstring>(), "Critical threshold")
; ;
po::basic_command_line_parser<wchar_t> parser(ac, av); po::basic_command_line_parser<WCHAR> parser(ac, av);
try { try {
po::store( po::store(
@ -91,16 +75,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
vm); vm);
vm.notify(); vm.notify();
} catch (std::exception& e) { } catch (std::exception& e) {
std::cout << e.what() << endl << desc << endl; std::cout << e.what() << '\n' << desc << '\n';
return 3; return 3;
} }
if (vm.count("help")) { if (vm.count("help")) {
wcout << progName << " Help\n\tVersion: " << VERSION << endl; std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n';
wprintf( wprintf(
L"%s is a simple program to check a machines processes.\n" 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); L"You can use the following options to define its behaviour:\n\n", progName);
cout << desc; std::cout << desc;
wprintf( wprintf(
L"\nIt will then output a string looking something like this:\n\n" L"\nIt will then output a string looking something like this:\n\n"
L"\tPROCS WARNING 67 | load=67;50;90;0\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"to end with a percentage sign.\n\n"
L"All of these options work with the critical threshold \"-c\" too." L"All of these options work with the critical threshold \"-c\" too."
, progName); , progName);
cout << endl; std::cout << '\n';
return 0; return 0;
} }
if (vm.count("version")) { if (vm.count("version")) {
std::cout << "Version: " << VERSION << endl; std::wcout << "Version: " << VERSION << '\n';
return 0; return 0;
} }
if (vm.count("warning")) { if (vm.count("warning")) {
try { try {
printInfo.warn = threshold(vm["warning"].as<wstring>()); printInfo.warn = threshold(vm["warning"].as<std::wstring>());
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
} }
if (vm.count("critical")) { if (vm.count("critical")) {
try { try {
printInfo.crit = threshold(vm["critical"].as<wstring>()); printInfo.crit = threshold(vm["critical"].as<std::wstring>());
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
} }
if (vm.count("user")) if (vm.count("user"))
printInfo.user = vm["user"].as<wstring>(); printInfo.user = vm["user"].as<std::wstring>();
if (vm.count("debug")) if (vm.count("debug"))
debug = TRUE; debug = TRUE;
@ -168,10 +152,10 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
return -1; return -1;
} }
int printOutput(const int numProcs, printInfoStruct& printInfo) INT printOutput(CONST INT numProcs, printInfoStruct& printInfo)
{ {
if (debug) if (debug)
wcout << L"Constructing output string" << endl; std::wcout << L"Constructing output string" << '\n';
state state = OK; state state = OK;
@ -181,38 +165,38 @@ int printOutput(const int numProcs, printInfoStruct& printInfo)
if (printInfo.crit.rend(numProcs)) if (printInfo.crit.rend(numProcs))
state = CRITICAL; state = CRITICAL;
wstring user = L""; std::wstring user = L"";
if (!printInfo.user.empty()) if (!printInfo.user.empty())
user.append(L" processes of user ").append(printInfo.user); user.append(L" processes of user ").append(printInfo.user);
switch (state) { switch (state) {
case OK: case OK:
wcout << L"PROCS OK " << numProcs << user << L" | procs=" << numProcs << L";" std::wcout << L"PROCS OK " << numProcs << user << L" | procs=" << numProcs << L";"
<< printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << endl; << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << '\n';
break; break;
case WARNING: case WARNING:
wcout << L"PROCS WARNING " << numProcs << user << L" | procs=" << numProcs << L";" std::wcout << L"PROCS WARNING " << numProcs << user << L" | procs=" << numProcs << L";"
<< printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << endl; << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << '\n';
break; break;
case CRITICAL: case CRITICAL:
wcout << L"PROCS CRITICAL " << numProcs << user << L" | procs=" << numProcs << L";" std::wcout << L"PROCS CRITICAL " << numProcs << user << L" | procs=" << numProcs << L";"
<< printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << endl; << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << '\n';
break; break;
} }
return state; return state;
} }
int countProcs() INT countProcs()
{ {
if (debug) if (debug)
wcout << L"Counting all processes" << endl; std::wcout << L"Counting all processes" << '\n';
HANDLE hProcessSnap = NULL; HANDLE hProcessSnap = NULL;
PROCESSENTRY32 pe32; PROCESSENTRY32 pe32;
if (debug) if (debug)
wcout << L"Creating snapshot" << endl; std::wcout << L"Creating snapshot" << '\n';
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE) if (hProcessSnap == INVALID_HANDLE_VALUE)
@ -221,37 +205,37 @@ int countProcs()
pe32.dwSize = sizeof(PROCESSENTRY32); pe32.dwSize = sizeof(PROCESSENTRY32);
if (debug) if (debug)
wcout << L"Grabbing first proccess" << endl; std::wcout << L"Grabbing first proccess" << '\n';
if (!Process32First(hProcessSnap, &pe32)) { if (!Process32First(hProcessSnap, &pe32)) {
CloseHandle(hProcessSnap); CloseHandle(hProcessSnap);
return -1; return -1;
} }
int numProcs = 0; INT numProcs = 0;
if (debug) if (debug)
wcout << L"Counting processes..." << endl; std::wcout << L"Counting processes..." << '\n';
do { do {
++numProcs; ++numProcs;
} while (Process32Next(hProcessSnap, &pe32)); } while (Process32Next(hProcessSnap, &pe32));
if (debug) 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) if (hProcessSnap)
CloseHandle(hProcessSnap); CloseHandle(hProcessSnap);
return numProcs; return numProcs;
} }
int countProcs(const wstring user) INT countProcs(CONST std::wstring user)
{ {
if (debug) 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(); CONST WCHAR *wuser = user.c_str();
int numProcs = 0; INT numProcs = 0;
HANDLE hProcessSnap, hProcess = NULL, hToken = NULL; HANDLE hProcessSnap, hProcess = NULL, hToken = NULL;
PROCESSENTRY32 pe32; PROCESSENTRY32 pe32;
@ -261,7 +245,7 @@ int countProcs(const wstring user)
LPWSTR AcctName, DomainName; LPWSTR AcctName, DomainName;
if (debug) if (debug)
wcout << L"Creating snapshot" << endl; std::wcout << L"Creating snapshot" << '\n';
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE) if (hProcessSnap == INVALID_HANDLE_VALUE)
@ -270,17 +254,17 @@ int countProcs(const wstring user)
pe32.dwSize = sizeof(PROCESSENTRY32); pe32.dwSize = sizeof(PROCESSENTRY32);
if (debug) if (debug)
wcout << L"Grabbing first proccess" << endl; std::wcout << L"Grabbing first proccess" << '\n';
if (!Process32First(hProcessSnap, &pe32)) if (!Process32First(hProcessSnap, &pe32))
goto die; goto die;
if (debug) if (debug)
wcout << L"Counting processes..." << endl; std::wcout << L"Counting processes..." << '\n';
do { do {
if (debug) if (debug)
wcout << L"Getting process token" << endl; std::wcout << L"Getting process token" << '\n';
//get ProcessToken //get ProcessToken
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pe32.th32ProcessID); hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pe32.th32ProcessID);
@ -298,7 +282,7 @@ int countProcs(const wstring user)
memset(pSIDTokenUser, 0, dwReturnLength); memset(pSIDTokenUser, 0, dwReturnLength);
if (debug) if (debug)
wcout << L"Received token, saving information" << endl; std::wcout << L"Received token, saving information" << '\n';
//write Info in pSIDTokenUser //write Info in pSIDTokenUser
if (!GetTokenInformation(hToken, TokenUser, pSIDTokenUser, dwReturnLength, NULL)) if (!GetTokenInformation(hToken, TokenUser, pSIDTokenUser, dwReturnLength, NULL))
@ -310,7 +294,7 @@ int countProcs(const wstring user)
dwDomainName = 1; dwDomainName = 1;
if (debug) if (debug)
wcout << L"Looking up SID" << endl; std::wcout << L"Looking up SID" << '\n';
//get dwAcctName and dwDomainName size //get dwAcctName and dwDomainName size
if (!LookupAccountSid(NULL, pSIDTokenUser->User.Sid, AcctName, if (!LookupAccountSid(NULL, pSIDTokenUser->User.Sid, AcctName,
@ -326,11 +310,11 @@ int countProcs(const wstring user)
continue; continue;
if (debug) if (debug)
wcout << L"Comparing " << AcctName << L" to " << wuser << endl; std::wcout << L"Comparing " << AcctName << L" to " << wuser << '\n';
if (!wcscmp(AcctName, wuser)) { if (!wcscmp(AcctName, wuser)) {
++numProcs; ++numProcs;
if (debug) 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<LPWSTR>(AcctName); delete[] reinterpret_cast<LPWSTR>(AcctName);

36
plugins/check_procs.h Normal file
View File

@ -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

View File

@ -20,36 +20,21 @@
#include <Shlwapi.h> #include <Shlwapi.h>
#include <iostream> #include <iostream>
#include "thresholds.h" #include "check_service.h"
#include "boost/program_options.hpp"
#define VERSION 1.1 #define VERSION 1.1
namespace po = boost::program_options; namespace po = boost::program_options;
using std::wcout; using std::endl;
using std::cout; using std::wstring;
static BOOL debug; static BOOL debug;
struct printInfoStruct INT wmain(INT argc, WCHAR **argv)
{
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)
{ {
po::variables_map vm; po::variables_map vm;
printInfoStruct printInfo = { false, 0, L"" }; printInfoStruct printInfo = { false, 0, L"" };
int ret = parseArguments(argc, argv, vm, printInfo); INT ret = parseArguments(argc, argv, vm, printInfo);
if (ret != -1) if (ret != -1)
return ret; return ret;
@ -60,23 +45,23 @@ int wmain(int argc, wchar_t **argv)
return printOutput(printInfo); 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); GetModuleFileName(NULL, namePath, MAX_PATH);
wchar_t *progName = PathFindFileName(namePath); WCHAR *progName = PathFindFileName(namePath);
po::options_description desc; po::options_description desc;
desc.add_options() desc.add_options()
("help,h", "print help message and exit") ("help,h", "Print help message and exit")
("version,V", "print version and exit") ("version,V", "Print version and exit")
("debug,d", "Verbose/Debug output") ("debug,d", "Verbose/Debug output")
("service,s", po::wvalue<wstring>(), "service to check (required)") ("service,s", po::wvalue<std::wstring>(), "Service to check (required)")
("warn,w", "return warning (1) instead of critical (2),\n when service is not running") ("warn,w", "Return warning (1) instead of critical (2),\n when service is not running")
; ;
po::basic_command_line_parser<wchar_t> parser(ac, av); po::basic_command_line_parser<WCHAR> parser(ac, av);
try { try {
po::store( po::store(
@ -89,16 +74,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
vm); vm);
vm.notify(); vm.notify();
} catch (std::exception& e) { } catch (std::exception& e) {
cout << e.what() << endl << desc << endl; std::cout << e.what() << '\n' << desc << '\n';
return 3; return 3;
} }
if (vm.count("help")) { if (vm.count("help")) {
wcout << progName << " Help\n\tVersion: " << VERSION << endl; std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n';
wprintf( wprintf(
L"%s is a simple program to check the status of a service.\n" 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); L"You can use the following options to define its behaviour:\n\n", progName);
cout << desc; std::cout << desc;
wprintf( wprintf(
L"\nIt will then output a string looking something like this:\n\n" 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" 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"all \"-w\" and \"-c\" do is say whether a not running service is a warning\n"
L"or critical state respectively.\n\n" L"or critical state respectively.\n\n"
, progName, progName); , progName, progName);
cout << endl; std::cout << '\n';
return 0; return 0;
} }
if (vm.count("version")) { if (vm.count("version")) {
cout << "Version: " << VERSION << endl; std::cout << "Version: " << VERSION << '\n';
return 0; return 0;
} }
if (!vm.count("service")) { if (!vm.count("service")) {
cout << "Missing argument: service" << endl << desc << endl; std::cout << "Missing argument: service" << '\n' << desc << '\n';
return 3; return 3;
} }
if (vm.count("warn")) if (vm.count("warn"))
printInfo.warn = true; printInfo.warn = true;
printInfo.service = vm["service"].as<wstring>(); printInfo.service = vm["service"].as<std::wstring>();
if (vm.count("debug")) if (vm.count("debug"))
debug = TRUE; debug = TRUE;
@ -140,16 +125,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
return -1; return -1;
} }
int printOutput(const printInfoStruct& printInfo) INT printOutput(CONST printInfoStruct& printInfo)
{ {
if (debug) if (debug)
wcout << L"Constructing output string" << endl; std::wcout << L"Constructing output string" << '\n';
wstring perf; std::wstring perf;
state state = OK; state state = OK;
if (!printInfo.ServiceState) { 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; return 3;
} }
@ -158,20 +143,20 @@ int printOutput(const printInfoStruct& printInfo)
switch (state) { switch (state) {
case OK: 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; break;
case WARNING: 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; break;
case CRITICAL: 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; break;
} }
return state; return state;
} }
DWORD ServiceStatus(const printInfoStruct& printInfo) DWORD ServiceStatus(CONST printInfoStruct& printInfo)
{ {
SC_HANDLE hSCM; SC_HANDLE hSCM;
SC_HANDLE hService; SC_HANDLE hService;
@ -179,14 +164,14 @@ DWORD ServiceStatus(const printInfoStruct& printInfo)
LPBYTE lpBuf = NULL; LPBYTE lpBuf = NULL;
if (debug) if (debug)
wcout << L"Opening SC Manager" << endl; std::wcout << L"Opening SC Manager" << '\n';
hSCM = OpenSCManager(NULL, NULL, GENERIC_READ); hSCM = OpenSCManager(NULL, NULL, GENERIC_READ);
if (hSCM == NULL) if (hSCM == NULL)
goto die; goto die;
if (debug) 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); hService = OpenService(hSCM, printInfo.service.c_str(), SERVICE_QUERY_STATUS);
if (hService == NULL) if (hService == NULL)

36
plugins/check_service.h Normal file
View File

@ -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

View File

@ -20,36 +20,20 @@
#include <iostream> #include <iostream>
#include <WinBase.h> #include <WinBase.h>
#include "thresholds.h" #include "check_swap.h"
#include "boost/program_options.hpp"
#define VERSION 1.0 #define VERSION 1.0
namespace po = boost::program_options; namespace po = boost::program_options;
using std::endl; using std::wcout; using std::wstring;
using std::cout;
static BOOL debug = FALSE; static BOOL debug = FALSE;
struct printInfoStruct INT wmain(INT argc, WCHAR **argv)
{
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)
{ {
printInfoStruct printInfo = { }; printInfoStruct printInfo = { };
po::variables_map vm; po::variables_map vm;
int ret = parseArguments(argc, argv, vm, printInfo); INT ret = parseArguments(argc, argv, vm, printInfo);
if (ret != -1) if (ret != -1)
return ret; return ret;
@ -60,24 +44,24 @@ int wmain(int argc, wchar_t **argv)
return printOutput(printInfo); 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); GetModuleFileName(NULL, namePath, MAX_PATH);
wchar_t *progName = PathFindFileName(namePath); WCHAR *progName = PathFindFileName(namePath);
po::options_description desc; po::options_description desc;
desc.add_options() desc.add_options()
("help,h", "print help message and exit") ("help,h", "Print help message and exit")
("version,V", "print version and exit") ("version,V", "Print version and exit")
("debug,d", "Verbose/Debug output") ("debug,d", "Verbose/Debug output")
("warning,w", po::wvalue<wstring>(), "warning threshold") ("warning,w", po::wvalue<std::wstring>(), "Warning threshold")
("critical,c", po::wvalue<wstring>(), "critical threshold") ("critical,c", po::wvalue<std::wstring>(), "Critical threshold")
("unit,u", po::wvalue<wstring>(), "the unit to use for display (default MB)") ("unit,u", po::wvalue<std::wstring>(), "The unit to use for display (default MB)")
; ;
po::basic_command_line_parser<wchar_t> parser(ac, av); po::basic_command_line_parser<WCHAR> parser(ac, av);
try { try {
po::store( po::store(
@ -90,16 +74,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
vm); vm);
vm.notify(); vm.notify();
} catch (std::exception& e) { } catch (std::exception& e) {
cout << e.what() << endl << desc << endl; std::cout << e.what() << '\n' << desc << '\n';
return 3; return 3;
} }
if (vm.count("help")) { if (vm.count("help")) {
wcout << progName << " Help\n\tVersion: " << VERSION << endl; std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n';
wprintf( wprintf(
L"%s is a simple program to check a machines swap in percent.\n" 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); L"You can use the following options to define its behaviour:\n\n", progName);
cout << desc; std::cout << desc;
wprintf( wprintf(
L"\nIt will then output a string looking something like this:\n\n" 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" 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"to end with a percentage sign.\n\n"
L"All of these options work with the critical threshold \"-c\" too.\n" L"All of these options work with the critical threshold \"-c\" too.\n"
, progName); , progName);
cout << endl; std::cout << '\n';
return 0; return 0;
} }
if (vm.count("version")) if (vm.count("version"))
wcout << L"Version: " << VERSION << endl; std::wcout << L"Version: " << VERSION << '\n';
if (vm.count("warning")) { if (vm.count("warning")) {
try { try {
printInfo.warn = threshold(vm["warning"].as<wstring>()); printInfo.warn = threshold(vm["warning"].as<std::wstring>());
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
printInfo.warn.legal = !printInfo.warn.legal; 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")) { if (vm.count("critical")) {
try { try {
printInfo.crit = threshold(vm["critical"].as<wstring>()); printInfo.crit = threshold(vm["critical"].as<std::wstring>());
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
printInfo.crit.legal = !printInfo.crit.legal; 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")) { if (vm.count("unit")) {
try { try {
printInfo.unit = parseBUnit(vm["unit"].as<wstring>()); printInfo.unit = parseBUnit(vm["unit"].as<std::wstring>());
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
} }
@ -173,10 +157,10 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
return -1; return -1;
} }
int printOutput(printInfoStruct& printInfo) INT printOutput(printInfoStruct& printInfo)
{ {
if (debug) if (debug)
wcout << L"Constructing output string" << endl; std::wcout << L"Constructing output string" << '\n';
state state = OK; state state = OK;
double fswap = ((double)printInfo.aSwap / (double)printInfo.tSwap) * 100.0; double fswap = ((double)printInfo.aSwap / (double)printInfo.tSwap) * 100.0;
@ -189,26 +173,26 @@ int printOutput(printInfoStruct& printInfo)
switch (state) { switch (state) {
case OK: 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) << printInfo.warn.pString(printInfo.tSwap) << L";" << printInfo.crit.pString(printInfo.tSwap)
<< L";0;" << printInfo.tSwap << endl; << L";0;" << printInfo.tSwap << '\n';
break; break;
case WARNING: 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) << printInfo.warn.pString(printInfo.tSwap) << L";" << printInfo.crit.pString(printInfo.tSwap)
<< L";0;" << printInfo.tSwap << endl; << L";0;" << printInfo.tSwap << '\n';
break; break;
case CRITICAL: 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) << printInfo.warn.pString(printInfo.tSwap) << L";" << printInfo.crit.pString(printInfo.tSwap)
<< L";0;" << printInfo.tSwap << endl; << L";0;" << printInfo.tSwap << '\n';
break; break;
} }
return state; return state;
} }
int check_swap(printInfoStruct& printInfo) INT check_swap(printInfoStruct& printInfo)
{ {
MEMORYSTATUSEX MemBuf; MEMORYSTATUSEX MemBuf;
MemBuf.dwLength = sizeof(MemBuf); MemBuf.dwLength = sizeof(MemBuf);

36
plugins/check_swap.h Normal file
View File

@ -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

View File

@ -22,9 +22,7 @@
#include <wuapi.h> #include <wuapi.h>
#include <wuerror.h> #include <wuerror.h>
#include "thresholds.h" #include "check_update.h"
#include "boost/program_options.hpp"
#define VERSION 1.0 #define VERSION 1.0
@ -32,28 +30,14 @@
namespace po = boost::program_options; namespace po = boost::program_options;
using std::wcout; using std::endl;
using std::wstring; using std::cout;
static BOOL debug = FALSE; static BOOL debug = FALSE;
struct printInfoStruct INT wmain(INT argc, WCHAR **argv)
{
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)
{ {
printInfoStruct printInfo = { FALSE, FALSE, 0, FALSE, FALSE, FALSE }; printInfoStruct printInfo = { FALSE, FALSE, 0, FALSE, FALSE, FALSE };
po::variables_map vm; po::variables_map vm;
int ret = parseArguments(argc, argv, vm, printInfo); INT ret = parseArguments(argc, argv, vm, printInfo);
if (ret != -1) if (ret != -1)
return ret; return ret;
@ -64,24 +48,24 @@ int wmain(int argc, wchar_t **argv)
return printOutput(printInfo); 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); GetModuleFileName(NULL, namePath, MAX_PATH);
wchar_t *progName = PathFindFileName(namePath); WCHAR *progName = PathFindFileName(namePath);
po::options_description desc; po::options_description desc;
desc.add_options() desc.add_options()
("help,h", "print help message and exit") ("help,h", "Print help message and exit")
("version,V", "print version and exit") ("version,V", "Print version and exit")
("debug,d", "Verbose/Debug output") ("debug,d", "Verbose/Debug output")
("warning,w", "warn if there are important updates available") ("warning,w", "Warn if there are important updates available")
("critical,c", "critical if there are important updates that require a reboot") ("critical,c", "Critical if there are important updates that require a reboot")
("possible-reboot", "treat \"update may need reboot\" as \"update needs reboot\"") ("possible-reboot", "Treat \"update may need reboot\" as \"update needs reboot\"")
; ;
po::basic_command_line_parser<wchar_t> parser(ac, av); po::basic_command_line_parser<WCHAR> parser(ac, av);
try { try {
po::store( po::store(
@ -94,16 +78,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
vm); vm);
vm.notify(); vm.notify();
} catch (std::exception& e) { } catch (std::exception& e) {
cout << e.what() << endl << desc << endl; std::cout << e.what() << '\n' << desc << '\n';
return 3; return 3;
} }
if (vm.count("help")) { if (vm.count("help")) {
wcout << progName << " Help\n\tVersion: " << VERSION << endl; std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n';
wprintf( wprintf(
L"%s is a simple program to check a machines required updates.\n" 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); L"You can use the following options to define its behaviour:\n\n", progName);
cout << desc; std::cout << desc;
wprintf( wprintf(
L"\nAfter some time, it will then output a string like this one:\n\n" 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" 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"The \"possible-reboot\" option is not recommended since this true for nearly\n"
L"every update." L"every update."
, progName, progName); , progName, progName);
cout << endl; std::cout << '\n';
return 0; return 0;
} if (vm.count("version")) { } if (vm.count("version")) {
cout << "Version: " << VERSION << endl; std::cout << "Version: " << VERSION << '\n';
return 0; return 0;
} }
@ -150,13 +134,13 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
return -1; return -1;
} }
int printOutput(const printInfoStruct& printInfo) INT printOutput(const printInfoStruct& printInfo)
{ {
if (debug) if (debug)
wcout << L"Constructing output string" << endl; std::wcout << L"Constructing output string" << '\n';
state state = OK; state state = OK;
wstring output = L"UPDATE "; std::wstring output = L"UPDATE ";
if (printInfo.important) if (printInfo.important)
state = WARNING; state = WARNING;
@ -176,16 +160,16 @@ int printOutput(const printInfoStruct& printInfo)
break; break;
} }
wcout << output << printInfo.numUpdates << L" | update=" << printInfo.numUpdates << L";" std::wcout << output << printInfo.numUpdates << L" | update=" << printInfo.numUpdates << L";"
<< printInfo.warn << L";" << printInfo.crit << L";0;" << endl; << printInfo.warn << L";" << printInfo.crit << L";0;" << '\n';
return state; return state;
} }
int check_update(printInfoStruct& printInfo) INT check_update(printInfoStruct& printInfo)
{ {
if (debug) if (debug)
wcout << "Initializing COM library" << endl; std::wcout << "Initializing COM library" << '\n';
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
ISearchResult *pResult; ISearchResult *pResult;
IUpdateSession *pSession; IUpdateSession *pSession;
@ -194,7 +178,7 @@ int check_update(printInfoStruct& printInfo)
HRESULT err; HRESULT err;
if (debug) 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); CoCreateInstance(CLSID_UpdateSession, NULL, CLSCTX_INPROC_SERVER, IID_IUpdateSession, (LPVOID*)&pSession);
pSession->CreateUpdateSearcher(&pSearcher); 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 // http://msdn.microsoft.com/en-us/library/ff357803%28v=vs.85%29.aspx
if (debug) if (debug)
wcout << L"Querrying updates from server" << endl; std::wcout << L"Querrying updates from server" << '\n';
err = pSearcher->Search(criteria, &pResult); err = pSearcher->Search(criteria, &pResult);
if (!SUCCEEDED(err)) if (!SUCCEEDED(err))
@ -236,24 +220,24 @@ int check_update(printInfoStruct& printInfo)
for (LONG i = 0; i < updateSize; i++) { for (LONG i = 0; i < updateSize; i++) {
pCollection->get_Item(i, &pUpdate); pCollection->get_Item(i, &pUpdate);
if (debug) { 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); pUpdate->get_InstallationBehavior(&pIbehav);
pIbehav->get_RebootBehavior(&updateReboot); pIbehav->get_RebootBehavior(&updateReboot);
if (updateReboot == irbAlwaysRequiresReboot) { if (updateReboot == irbAlwaysRequiresReboot) {
printInfo.reboot = TRUE; printInfo.reboot = TRUE;
if (debug) if (debug)
wcout << L"It requires reboot" << endl; std::wcout << L"It requires reboot" << '\n';
continue; continue;
} }
if (printInfo.careForCanRequest && updateReboot == irbCanRequestReboot) if (printInfo.careForCanRequest && updateReboot == irbCanRequestReboot)
if (debug) if (debug)
wcout << L"It requires reboot" << endl; std::wcout << L"It requires reboot" << '\n';
printInfo.reboot = TRUE; printInfo.reboot = TRUE;
} }
if (debug) if (debug)
wcout << L"Cleaning up and returning" << endl; std::wcout << L"Cleaning up and returning" << '\n';
SysFreeString(criteria); SysFreeString(criteria);
CoUninitialize(); CoUninitialize();

36
plugins/check_update.h Normal file
View File

@ -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

View File

@ -20,37 +20,21 @@
#include <Shlwapi.h> #include <Shlwapi.h>
#include <iostream> #include <iostream>
#include "thresholds.h" #include "check_uptime.h"
#include "boost/chrono.hpp" #include "boost/chrono.hpp"
#include "boost/program_options.hpp"
#define VERSION 1.0 #define VERSION 1.0
namespace po = boost::program_options; namespace po = boost::program_options;
using std::cout; using std::endl;
using std::wcout; using std::wstring;
static BOOL debug; static BOOL debug;
struct printInfoStruct INT wmain(INT argc, WCHAR **argv)
{
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)
{ {
po::variables_map vm; po::variables_map vm;
printInfoStruct printInfo = { }; printInfoStruct printInfo = { };
int ret = parseArguments(argc, argv, vm, printInfo); INT ret = parseArguments(argc, argv, vm, printInfo);
if (ret != -1) if (ret != -1)
return ret; return ret;
@ -60,24 +44,24 @@ int wmain(int argc, wchar_t **argv)
return printOutput(printInfo); 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); GetModuleFileName(NULL, namePath, MAX_PATH);
wchar_t *progName = PathFindFileName(namePath); WCHAR *progName = PathFindFileName(namePath);
po::options_description desc; po::options_description desc;
desc.add_options() desc.add_options()
("help,h", "print help message and exit") ("help,h", "Print help message and exit")
("version,V", "print version and exit") ("version,V", "Print version and exit")
("warning,w", po::wvalue<wstring>(), "warning threshold (Uses -unit)")
("debug,d", "Verbose/Debug output") ("debug,d", "Verbose/Debug output")
("critical,c", po::wvalue<wstring>(), "critical threshold (Uses -unit)") ("warning,w", po::wvalue<std::wstring>(), "Warning threshold (Uses -unit)")
("unit,u", po::wvalue<wstring>(), "desired unit of output\nh\t- hours\nm\t- minutes\ns\t- seconds (default)\nms\t- milliseconds") ("critical,c", po::wvalue<std::wstring>(), "Critical threshold (Uses -unit)")
("unit,u", po::wvalue<std::wstring>(), "Unit to use:\nh\t- hours\nm\t- minutes\ns\t- seconds (default)\nms\t- milliseconds")
; ;
po::basic_command_line_parser<wchar_t> parser(ac, av); po::basic_command_line_parser<WCHAR> parser(ac, av);
try { try {
po::store( po::store(
@ -90,16 +74,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
vm); vm);
vm.notify(); vm.notify();
} catch (std::exception& e) { } catch (std::exception& e) {
cout << e.what() << endl << desc << endl; std::cout << e.what() << '\n' << desc << '\n';
return 3; return 3;
} }
if (vm.count("help")) { if (vm.count("help")) {
wcout << progName << " Help\n\tVersion: " << VERSION << endl; std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n';
wprintf( wprintf(
L"%s is a simple program to check a machines uptime.\n" 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); L"You can use the following options to define its behaviour:\n\n", progName);
cout << desc; std::cout << desc;
wprintf( wprintf(
L"\nIt will then output a string looking something like this:\n\n" L"\nIt will then output a string looking something like this:\n\n"
L"\tUPTIME WARNING 712h | uptime=712h;700;1800;0\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"to end with a percentage sign.\n\n"
L"All of these options work with the critical threshold \"-c\" too.\n" L"All of these options work with the critical threshold \"-c\" too.\n"
, progName); , progName);
cout << endl; std::cout << '\n';
return 0; return 0;
} }
if (vm.count("version")) { if (vm.count("version")) {
cout << VERSION << endl; std::cout << VERSION << '\n';
return 0; return 0;
} }
if (vm.count("warning")) { if (vm.count("warning")) {
try { try {
printInfo.warn = threshold(vm["warning"].as<wstring>()); printInfo.warn = threshold(vm["warning"].as<std::wstring>());
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
} }
if (vm.count("critical")) { if (vm.count("critical")) {
try { try {
printInfo.crit = threshold(vm["critical"].as<wstring>()); printInfo.crit = threshold(vm["critical"].as<std::wstring>());
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
} }
if (vm.count("unit")) { if (vm.count("unit")) {
try{ try{
printInfo.unit = parseTUnit(vm["unit"].as<wstring>()); printInfo.unit = parseTUnit(vm["unit"].as<std::wstring>());
} catch (std::invalid_argument) { } catch (std::invalid_argument) {
wcout << L"Unknown unit type " << vm["unit"].as<wstring>() << endl; std::wcout << L"Unknown unit type " << vm["unit"].as<std::wstring>() << '\n';
return 3; return 3;
} }
} else } else
@ -175,10 +159,10 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
return -1; return -1;
} }
static int printOutput(printInfoStruct& printInfo) INT printOutput(printInfoStruct& printInfo)
{ {
if (debug) if (debug)
wcout << L"Constructing output string" << endl; std::wcout << L"Constructing output string" << '\n';
state state = OK; state state = OK;
@ -189,34 +173,34 @@ static int printOutput(printInfoStruct& printInfo)
switch (state) { switch (state) {
case OK: 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";" << TunitStr(printInfo.unit) << L";" << printInfo.warn.pString() << L";"
<< printInfo.crit.pString() << L";0;" << endl; << printInfo.crit.pString() << L";0;" << '\n';
break; break;
case WARNING: 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";" << TunitStr(printInfo.unit) << L";" << printInfo.warn.pString() << L";"
<< printInfo.crit.pString() << L";0;" << endl; << printInfo.crit.pString() << L";0;" << '\n';
break; break;
case CRITICAL: 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";" << TunitStr(printInfo.unit) << L";" << printInfo.warn.pString() << L";"
<< printInfo.crit.pString() << L";0;" << endl; << printInfo.crit.pString() << L";0;" << '\n';
break; break;
} }
return state; return state;
} }
void getUptime(printInfoStruct& printInfo) VOID getUptime(printInfoStruct& printInfo)
{ {
if (debug) 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()); boost::chrono::milliseconds uptime = boost::chrono::milliseconds(GetTickCount64());
if (debug) if (debug)
wcout << L"Converting requested unit (default: seconds)" << endl; std::wcout << L"Converting requested unit (default: seconds)" << '\n';
switch (printInfo.unit) { switch (printInfo.unit) {
case TunitH: case TunitH:

36
plugins/check_uptime.h Normal file
View File

@ -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

View File

@ -21,35 +21,20 @@
#include <wtsapi32.h> #include <wtsapi32.h>
#include <iostream> #include <iostream>
#include "thresholds.h" #include "check_users.h"
#include "boost/program_options.hpp"
#define VERSION 1.0 #define VERSION 1.0
namespace po = boost::program_options; namespace po = boost::program_options;
using std::endl; using std::wcout;
using std::cout; using std::wstring;
static BOOL debug = FALSE; static BOOL debug = FALSE;
struct printInfoStruct INT wmain(INT argc, WCHAR **argv)
{
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)
{ {
printInfoStruct printInfo = { }; printInfoStruct printInfo = { };
po::variables_map vm; po::variables_map vm;
int ret = parseArguments(argc, argv, vm, printInfo); INT ret = parseArguments(argc, argv, vm, printInfo);
if (ret != -1) if (ret != -1)
return ret; return ret;
@ -60,23 +45,23 @@ int wmain(int argc, wchar_t **argv)
return printOutput(printInfo); 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); GetModuleFileName(NULL, namePath, MAX_PATH);
wchar_t *progName = PathFindFileName(namePath); WCHAR *progName = PathFindFileName(namePath);
po::options_description desc; po::options_description desc;
desc.add_options() desc.add_options()
("help,h", "print help message and exit") ("help,h", "Print help message and exit")
("version,V", "print version and exit") ("version,V", "Print version and exit")
("debug,d", "Verbose/Debug output") ("debug,d", "Verbose/Debug output")
("warning,w", po::wvalue<wstring>(), "warning threshold") ("warning,w", po::wvalue<std::wstring>(), "Warning threshold")
("critical,c", po::wvalue<wstring>(), "critical threshold") ("critical,c", po::wvalue<std::wstring>(), "Critical threshold")
; ;
po::basic_command_line_parser<wchar_t> parser(ac, av); po::basic_command_line_parser<WCHAR> parser(ac, av);
try { try {
po::store( po::store(
@ -89,16 +74,16 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
vm); vm);
vm.notify(); vm.notify();
} catch (std::exception& e) { } catch (std::exception& e) {
cout << e.what() << endl << desc << endl; std::cout << e.what() << '\n' << desc << '\n';
return 3; return 3;
} }
if (vm.count("help")) { if (vm.count("help")) {
wcout << progName << " Help\n\tVersion: " << VERSION << endl; std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n';
wprintf( wprintf(
L"%s is a simple program to check a machines logged in users.\n" 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); L"You can use the following options to define its behaviour:\n\n", progName);
cout << desc; std::cout << desc;
wprintf( wprintf(
L"\nIt will then output a string looking something like this:\n\n" L"\nIt will then output a string looking something like this:\n\n"
L"\tUSERS WARNING 48 | users=48;10;50;0\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"to end with a percentage sign.\n\n"
L"All of these options work with the critical threshold \"-c\" too." L"All of these options work with the critical threshold \"-c\" too."
, progName); , progName);
cout << endl; std::cout << '\n';
return 0; return 0;
} }
if (vm.count("version")) if (vm.count("version"))
wcout << L"Version: " << VERSION << endl; std::wcout << L"Version: " << VERSION << '\n';
if (vm.count("warning")) { if (vm.count("warning")) {
try { try {
printInfo.warn = threshold(vm["warning"].as<wstring>()); printInfo.warn = threshold(vm["warning"].as<std::wstring>());
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
} }
if (vm.count("critical")) { if (vm.count("critical")) {
try { try {
printInfo.crit = threshold(vm["critical"].as<wstring>()); printInfo.crit = threshold(vm["critical"].as<std::wstring>());
} catch (std::invalid_argument& e) { } catch (std::invalid_argument& e) {
cout << e.what() << endl; std::cout << e.what() << '\n';
return 3; return 3;
} }
} }
@ -160,10 +145,10 @@ int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct&
return -1; return -1;
} }
int printOutput(printInfoStruct& printInfo) INT printOutput(printInfoStruct& printInfo)
{ {
if (debug) if (debug)
wcout << L"Constructing output string" << endl; std::wcout << L"Constructing output string" << '\n';
state state = OK; state state = OK;
@ -175,34 +160,34 @@ int printOutput(printInfoStruct& printInfo)
switch (state) { switch (state) {
case OK: case OK:
wcout << L"USERS OK " << printInfo.users << L" User(s) logged in | users=" << printInfo.users << L";" 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;" << endl; << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << '\n';
break; break;
case WARNING: case WARNING:
wcout << L"USERS WARNING " << printInfo.users << L" User(s) logged in | users=" << printInfo.users << L";" 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;" << endl; << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << '\n';
break; break;
case CRITICAL: case CRITICAL:
wcout << L"USERS CRITICAL " << printInfo.users << L" User(s) logged in | users=" << printInfo.users << L";" 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;" << endl; << printInfo.warn.pString() << L";" << printInfo.crit.pString() << L";0;" << '\n';
break; break;
} }
return state; return state;
} }
int check_users(printInfoStruct& printInfo) INT check_users(printInfoStruct& printInfo)
{ {
double users = 0; DOUBLE users = 0;
WTS_SESSION_INFOW *pSessionInfo = NULL; WTS_SESSION_INFOW *pSessionInfo = NULL;
DWORD count; DWORD count;
DWORD index; DWORD index;
if (debug) 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)) { 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(); die();
if (pSessionInfo) if (pSessionInfo)
WTSFreeMemory(pSessionInfo); WTSFreeMemory(pSessionInfo);
@ -210,22 +195,22 @@ int check_users(printInfoStruct& printInfo)
} }
if (debug) 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++) { for (index = 0; index < count; index++) {
LPWSTR name; LPWSTR name;
DWORD size; DWORD size;
int len; INT len;
if (debug) 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, if (!WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, pSessionInfo[index].SessionId,
WTSUserName, &name, &size)) WTSUserName, &name, &size))
continue; continue;
if (debug) 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); len = lstrlenW(name);
@ -237,12 +222,12 @@ int check_users(printInfoStruct& printInfo)
if (pSessionInfo[index].State == WTSActive || pSessionInfo[index].State == WTSDisconnected) { if (pSessionInfo[index].State == WTSActive || pSessionInfo[index].State == WTSDisconnected) {
users++; users++;
if (debug) 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) 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); WTSFreeMemory(pSessionInfo);
printInfo.users = users; printInfo.users = users;

15
plugins/check_users.h Normal file
View File

@ -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

View File

@ -20,80 +20,77 @@
#include "thresholds.h" #include "thresholds.h"
#include <boost/algorithm/string.hpp> #include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp> #include <boost/lexical_cast.hpp>
#include <vector>
#include <iostream> #include <iostream>
using namespace boost::algorithm; using namespace boost::algorithm;
using std::wstring;
threshold::threshold() threshold::threshold()
: set(false) : set(false)
{} {}
threshold::threshold(const wstring& stri) threshold::threshold(CONST std::wstring& stri)
{ {
if (stri.empty()) if (stri.empty())
throw std::invalid_argument("Threshold must not be empty"); throw std::invalid_argument("Threshold must not be empty");
wstring str = stri; std::wstring str = stri;
//kill whitespace //kill whitespace
boost::algorithm::trim(str); boost::algorithm::trim(str);
bool low = (str.at(0) == L'!'); bool low = (str.at(0) == L'!');
if (low) if (low)
str = wstring(str.begin() + 1, str.end()); str = std::wstring(str.begin() + 1, str.end());
bool pc = false; bool pc = false;
if (str.at(0) == L'[' && str.at(str.length() - 1) == L']') {//is range if (str.at(0) == L'[' && str.at(str.length() - 1) == L']') {//is range
str = wstring(str.begin() + 1, str.end() - 1); str = std::wstring(str.begin() + 1, str.end() - 1);
std::vector<wstring> svec; std::vector<std::wstring> svec;
boost::split(svec, str, boost::is_any_of(L"-")); boost::split(svec, str, boost::is_any_of(L"-"));
if (svec.size() != 2) if (svec.size() != 2)
throw std::invalid_argument("Threshold range requires two arguments"); 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'%') { if (str1.at(str1.length() - 1) == L'%' && str2.at(str2.length() - 1) == L'%') {
pc = true; pc = true;
str1 = wstring(str1.begin(), str1.end() - 1); str1 = std::wstring(str1.begin(), str1.end() - 1);
str2 = wstring(str2.begin(), str2.end() - 1); str2 = std::wstring(str2.begin(), str2.end() - 1);
} }
try { try {
boost::algorithm::trim(str1); boost::algorithm::trim(str1);
lower = boost::lexical_cast<double>(str1); lower = boost::lexical_cast<DOUBLE>(str1);
boost::algorithm::trim(str2); boost::algorithm::trim(str2);
upper = boost::lexical_cast<double>(str2); upper = boost::lexical_cast<DOUBLE>(str2);
legal = !low; perc = pc; set = true; 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"); throw std::invalid_argument("Unknown Threshold type");
} }
} else { //not range } else { //not range
if (str.at(str.length() - 1) == L'%') { if (str.at(str.length() - 1) == L'%') {
pc = true; pc = true;
str = wstring(str.begin(), str.end() - 1); str = std::wstring(str.begin(), str.end() - 1);
} }
try { try {
boost::algorithm::trim(str); boost::algorithm::trim(str);
lower = upper = boost::lexical_cast<double>(str); lower = upper = boost::lexical_cast<DOUBLE>(str);
legal = !low; perc = pc; set = true; 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"); throw std::invalid_argument("Unknown Threshold type");
} }
} }
} }
//return TRUE if the threshold is broken //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 upperAbs = upper;
double lowerAbs = lower; DOUBLE lowerAbs = lower;
if (perc) { if (perc) {
upperAbs = upper / 100 * max; upperAbs = upper / 100.0 * max;
lowerAbs = lower / 100 * max; lowerAbs = lower / 100.0 * max;
} }
if (!set) if (!set)
@ -105,16 +102,16 @@ bool threshold::rend(const double val, const double max)
} }
//returns a printable string of the threshold //returns a printable string of the threshold
std::wstring threshold::pString(const double max) std::wstring threshold::pString(CONST DOUBLE max)
{ {
if (!set) if (!set)
return L""; return L"";
//transform percentages to abolute values //transform percentages to abolute values
double lowerAbs = lower; DOUBLE lowerAbs = lower;
double upperAbs = upper; DOUBLE upperAbs = upper;
if (perc) { if (perc) {
lowerAbs = lower / 100 * max; lowerAbs = lower / 100.0 * max;
upperAbs = upper / 100 * max; upperAbs = upper / 100.0 * max;
} }
std::wstring s, lowerStr = removeZero(lowerAbs), std::wstring s, lowerStr = removeZero(lowerAbs),
@ -129,10 +126,10 @@ std::wstring threshold::pString(const double max)
return s; return s;
} }
std::wstring removeZero(double val) std::wstring removeZero(DOUBLE val)
{ {
std::wstring ret = boost::lexical_cast<std::wstring>(val); std::wstring ret = boost::lexical_cast<std::wstring>(val);
int pos = ret.length(); INT pos = ret.length();
if (ret.find_first_of(L".") == std::string::npos) if (ret.find_first_of(L".") == std::string::npos)
return ret; return ret;
for (std::wstring::reverse_iterator rit = ret.rbegin(); rit != ret.rend(); ++rit) { for (std::wstring::reverse_iterator rit = ret.rbegin(); rit != ret.rend(); ++rit) {
@ -149,14 +146,14 @@ std::wstring removeZero(double val)
std::vector<std::wstring> splitMultiOptions(std::wstring str) std::vector<std::wstring> splitMultiOptions(std::wstring str)
{ {
std::vector<wstring> sVec; std::vector<std::wstring> sVec;
boost::split(sVec, str, boost::is_any_of(L",")); boost::split(sVec, str, boost::is_any_of(L","));
return sVec; 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") if (wstr == L"B")
return BunitB; return BunitB;
@ -172,7 +169,7 @@ Bunit parseBUnit(const wstring& str)
throw std::invalid_argument("Unknown unit type"); throw std::invalid_argument("Unknown unit type");
} }
wstring BunitStr(const Bunit& unit) std::wstring BunitStr(CONST Bunit& unit)
{ {
switch (unit) { switch (unit) {
case BunitB: case BunitB:
@ -189,8 +186,8 @@ wstring BunitStr(const Bunit& unit)
return NULL; return NULL;
} }
Tunit parseTUnit(const wstring& str) { Tunit parseTUnit(CONST std::wstring& str) {
wstring wstr = to_lower_copy(str); std::wstring wstr = to_lower_copy(str);
if (wstr == L"ms") if (wstr == L"ms")
return TunitMS; return TunitMS;
@ -204,7 +201,7 @@ Tunit parseTUnit(const wstring& str) {
throw std::invalid_argument("Unknown unit type"); throw std::invalid_argument("Unknown unit type");
} }
wstring TunitStr(const Tunit& unit) std::wstring TunitStr(CONST Tunit& unit)
{ {
switch (unit) { switch (unit) {
case TunitMS: case TunitMS:
@ -219,12 +216,14 @@ wstring TunitStr(const Tunit& unit)
return NULL; return NULL;
} }
void die(DWORD err) VOID die(DWORD err)
{ {
if (!err) if (!err)
err = GetLastError(); err = GetLastError();
LPWSTR mBuf = NULL; LPWSTR mBuf = NULL;
size_t mS = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, 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); NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&mBuf, 0, NULL))
std::wcout << mBuf << std::endl; std::wcout << "Failed to format error message, last error was: " << err << '\n';
else
std::wcout << mBuf << std::endl;
} }

View File

@ -1,58 +1,70 @@
/****************************************************************************** /******************************************************************************
* Icinga 2 * * Icinga 2 *
* Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.org) * * Copyright (C) 2012-2015 Icinga Development Team (http://www.icinga.org) *
* * * *
* This program is free software; you can redistribute it and/or * * This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License * * modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 * * as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. * * of the License, or (at your option) any later version. *
* * * *
* This program is distributed in the hope that it will be useful, * * This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of * * but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. * * GNU General Public License for more details. *
* * * *
* You should have received a copy of the GNU General Public License * * You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software Foundation * * along with this program; if not, write to the Free Software Foundation *
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
******************************************************************************/ ******************************************************************************/
#ifndef THRESHOLDS_H #ifndef THRESHOLDS_H
#define THRESHOLDS_H #define THRESHOLDS_H
#include <string> #include <string>
#include <Windows.h> #include <Windows.h>
#include <vector> #include <vector>
enum Bunit { BunitB = 0, BunitkB = 1, BunitMB = 2, BunitGB = 3, BunitTB = 4 }; enum Bunit
enum Tunit { TunitMS, TunitS, TunitM, TunitH }; {
enum state { OK = 0, WARNING = 1, CRITICAL = 2 }; 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 class threshold
{ {
public: 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 //TRUE means everything BELOW upper/outside [lower-upper] is fine
bool legal, perc, set; BOOL legal, perc, set;
threshold(); 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 //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 //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<std::wstring> splitMultiOptions(std::wstring); std::vector<std::wstring> splitMultiOptions(std::wstring);
Bunit parseBUnit(const std::wstring&); Bunit parseBUnit(CONST std::wstring&);
std::wstring BunitStr(const Bunit&); std::wstring BunitStr(CONST Bunit&);
Tunit parseTUnit(const std::wstring&); Tunit parseTUnit(CONST std::wstring&);
std::wstring TunitStr(const Tunit&); std::wstring TunitStr(CONST Tunit&);
void die(DWORD err = 0); VOID die(DWORD err = 0);
#endif #endif