source: nscp/modules/CheckSystem/CheckSystem.cpp @ e26cfe0

0.4.00.4.10.4.2stable
Last change on this file since e26cfe0 was e26cfe0, checked in by Michael Medin <michael@…>, 8 years ago

changes all over manily in the checking code

  • Property mode set to 100644
File size: 23.7 KB
Line 
1// NSClientCompat.cpp : Defines the entry point for the DLL application.
2//
3
4#include "stdafx.h"
5#include "CheckSystem.h"
6#include <utils.h>
7#include <tlhelp32.h>
8#include <EnumNtSrv.h>
9#include <EnumProcess.h>
10#include <sysinfo.h>
11#include <checkHelpers.hpp>
12
13CheckSystem gNSClientCompat;
14
15/**
16 * DLL Entry point
17 * @param hModule
18 * @param ul_reason_for_call
19 * @param lpReserved
20 * @return
21 */
22BOOL APIENTRY DllMain( HANDLE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved)
23{
24        NSCModuleWrapper::wrapDllMain(hModule, ul_reason_for_call);
25        return TRUE;
26}
27
28/**
29 * Default c-tor
30 * @return
31 */
32CheckSystem::CheckSystem() : processMethod_(0) {}
33/**
34 * Default d-tor
35 * @return
36 */
37CheckSystem::~CheckSystem() {}
38/**
39 * Load (initiate) module.
40 * Start the background collector thread and let it run until unloadModule() is called.
41 * @return true
42 */
43bool CheckSystem::loadModule() {
44        pdhThread.createThread();
45
46        std::string wantedMethod = NSCModuleHelper::getSettingsString(C_SYSTEM_SECTION_TITLE, C_SYSTEM_ENUMPROC_METHOD, C_SYSTEM_ENUMPROC_METHOD_DEFAULT);
47
48        CEnumProcess tmp;
49        int method = tmp.GetAvailableMethods();
50
51
52
53        if (wantedMethod == C_SYSTEM_ENUMPROC_METHOD_AUTO) {
54                OSVERSIONINFO osVer = systemInfo::getOSVersion();
55                if (systemInfo::isBelowNT4(osVer)) {
56                        NSC_DEBUG_MSG_STD("Autodetected NT4<, using PSAPI process enumeration.");
57                        processMethod_ = ENUM_METHOD::PSAPI;
58                } else if (systemInfo::isAboveW2K(osVer)) {
59                        NSC_DEBUG_MSG_STD("Autodetected W2K>, using TOOLHELP process enumeration.");
60                        processMethod_ = ENUM_METHOD::TOOLHELP;
61                } else {
62                        NSC_DEBUG_MSG_STD("Autodetected failed, using PSAPI process enumeration.");
63                        processMethod_ = ENUM_METHOD::PSAPI;
64                }
65        } else if (wantedMethod == C_SYSTEM_ENUMPROC_METHOD_PSAPI) {
66                NSC_DEBUG_MSG_STD("Using PSAPI method.");
67                if (method == (method|ENUM_METHOD::PSAPI)) {
68                        processMethod_ = ENUM_METHOD::PSAPI;
69                } else {
70                        NSC_LOG_ERROR_STD("PSAPI method not available, check " C_SYSTEM_ENUMPROC_METHOD " option.");
71                }
72        } else {
73                NSC_DEBUG_MSG_STD("Using TOOLHELP method.");
74                if (method == (method|ENUM_METHOD::TOOLHELP)) {
75                        processMethod_ = ENUM_METHOD::TOOLHELP;
76                } else {
77                        NSC_LOG_ERROR_STD("TOOLHELP method not avalible, check " C_SYSTEM_ENUMPROC_METHOD " option.");
78                }
79        }
80        return true;
81}
82/**
83 * Unload (terminate) module.
84 * Attempt to stop the background processing thread.
85 * @return true if successfully, false if not (if not things might be bad)
86 */
87bool CheckSystem::unloadModule() {
88        if (!pdhThread.exitThread(20000)) {
89                std::cout << "MAJOR ERROR: Could not unload thread..." << std::endl;
90                NSC_LOG_ERROR("Could not exit the thread, memory leak and potential corruption may be the result...");
91        }
92        return true;
93}
94/**
95 * Check if we have a command handler.
96 * @return true (as we have a command handler)
97 */
98bool CheckSystem::hasCommandHandler() {
99        return true;
100}
101/**
102 * Check if we have a message handler.
103 * @return false as we have no message handler
104 */
105bool CheckSystem::hasMessageHandler() {
106        return false;
107}
108/*
109*/
110/**
111 * Main command parser and delegator.
112 * This also handles a lot of the simpler responses (though some are deferred to other helper functions)
113 *
114 *
115 * @param command
116 * @param argLen
117 * @param **args
118 * @return
119 */
120NSCAPI::nagiosReturn CheckSystem::handleCommand(const strEx::blindstr command, const unsigned int argLen, char **char_args, std::string &msg, std::string &perf) {
121        std::list<std::string> stl_args;
122        CheckSystem::returnBundle rb;
123        if (command == "checkCPU") {
124                return checkCPU(argLen, char_args, msg, perf);
125        } else if (command == "checkUpTime") {
126                return checkUpTime(argLen, char_args, msg, perf);
127        } else if (command == "checkServiceState") {
128                return checkServiceState(argLen, char_args, msg, perf);
129        } else if (command == "checkProcState") {
130                return checkProcState(argLen, char_args, msg, perf);
131        } else if (command == "checkMem") {
132                return checkMem(argLen, char_args, msg, perf);
133        } else if (command == "checkCounter") {
134                return checkCounter(argLen, char_args, msg, perf);
135        }
136        return NSCAPI::returnIgnored;
137}
138
139NSCAPI::nagiosReturn CheckSystem::checkCPU(const unsigned int argLen, char **char_args, std::string &msg, std::string &perf)
140{
141        typedef checkHolders::CheckConatiner<checkHolders::MaxMinBoundsInteger> CPULoadConatiner;
142
143        std::list<std::string> stl_args = arrayBuffer::arrayBuffer2list(argLen, char_args);
144        if (stl_args.empty()) {
145                msg = "ERROR: Missing argument exception.";
146                return NSCAPI::returnUNKNOWN;
147        }
148        std::list<CPULoadConatiner> list;
149        NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK;
150        bool bShowAll = false;
151        bool bNSClient = false;
152        CPULoadConatiner tmpObject;
153
154        tmpObject.data = "cpuload";
155
156        MAP_OPTIONS_BEGIN(stl_args)
157                MAP_OPTIONS_STR("MaxWarn", tmpObject.warn.max)
158                MAP_OPTIONS_STR("warn", tmpObject.warn.max)
159                MAP_OPTIONS_STR("MinWarn", tmpObject.warn.min)
160                MAP_OPTIONS_STR("MaxCrit", tmpObject.crit.max)
161                MAP_OPTIONS_STR("crit", tmpObject.crit.max)
162                MAP_OPTIONS_STR("MinCrit", tmpObject.crit.min)
163                MAP_OPTIONS_STR_AND("time", tmpObject.data, list.push_back(tmpObject))
164                MAP_OPTIONS_STR_AND("Time", tmpObject.data, list.push_back(tmpObject))
165                MAP_OPTIONS_BOOL_TRUE(SHOW_ALL, bShowAll)
166                MAP_OPTIONS_BOOL_TRUE(NSCLIENT, bNSClient)
167                        MAP_OPTIONS_SECONDARY_BEGIN(":", p2)
168                        else if (p2.first == "Time") {
169                                tmpObject.data = p__.second;
170                                tmpObject.alias = p2.second;
171                                list.push_back(tmpObject);
172                        }
173                        MAP_OPTIONS_MISSING_EX(p2, msg, "Unknown argument: ")
174                        MAP_OPTIONS_SECONDARY_END()
175                else { tmpObject.data = p__.first, list.push_back(tmpObject); }
176        MAP_OPTIONS_END()
177
178        for (std::list<CPULoadConatiner>::const_iterator it = list.begin(); it != list.end(); ++it) {
179                CPULoadConatiner load = (*it);
180                PDHCollector *pObject = pdhThread.getThread();
181                if (!pObject) {
182                        msg = "ERROR: PDH Collection thread not running.";
183                        return NSCAPI::returnUNKNOWN;
184                }
185                if (bNSClient) {
186                        int value = pObject->getCPUAvrage(load.data + "m");
187                        if (value == -1) {
188                                msg = "ERROR: We don't collect data this far back: " + load.getAlias();
189                                return NSCAPI::returnUNKNOWN;
190                        }
191                        if (!msg.empty()) msg += "&";
192                        msg += strEx::itos(value);
193                } else {
194                        int value = pObject->getCPUAvrage(load.data);
195                        if (value == -1) {
196                                msg = "ERROR: We don't collect data this far back: " + load.getAlias();
197                                return NSCAPI::returnUNKNOWN;
198                        } else {
199                                load.setDefault(tmpObject);
200                                load.runCheck(value, returnCode, msg, perf, bShowAll);
201                        }
202                }
203        }
204
205        if (msg.empty())
206                msg = "OK CPU Load ok.";
207        else if (!bNSClient)
208                msg = NSCHelper::translateReturn(returnCode) + ": " + msg;
209        return returnCode;
210}
211
212NSCAPI::nagiosReturn CheckSystem::checkUpTime(const unsigned int argLen, char **char_args, std::string &msg, std::string &perf)
213{
214        typedef checkHolders::CheckConatiner<checkHolders::MaxMinBoundsTime> UpTimeConatiner;
215
216        std::list<std::string> stl_args = arrayBuffer::arrayBuffer2list(argLen, char_args);
217        if (stl_args.empty()) {
218                msg = "ERROR: Missing argument exception.";
219                return NSCAPI::returnUNKNOWN;
220        }
221        NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK;
222        bool bShowAll = false;
223        bool bNSClient = false;
224        UpTimeConatiner bounds;
225
226        bounds.data = "uptime";
227
228        MAP_OPTIONS_BEGIN(stl_args)
229                MAP_OPTIONS_STR("MaxWarn", bounds.warn.max)
230                MAP_OPTIONS_STR("warn", bounds.warn.min)
231                MAP_OPTIONS_STR("MinWarn", bounds.warn.min)
232                MAP_OPTIONS_STR("MaxCrit", bounds.crit.max)
233                MAP_OPTIONS_STR("crit", bounds.crit.min)
234                MAP_OPTIONS_STR("MinCrit", bounds.crit.min)
235                MAP_OPTIONS_STR("Alias", bounds.data)
236                MAP_OPTIONS_BOOL_TRUE(SHOW_ALL, bShowAll)
237                MAP_OPTIONS_BOOL_TRUE(NSCLIENT, bNSClient)
238                MAP_OPTIONS_MISSING(msg, "Unknown argument: ")
239        MAP_OPTIONS_END()
240
241
242        PDHCollector *pObject = pdhThread.getThread();
243        if (!pObject) {
244                msg = "ERROR: PDH Collection thread not running.";
245                return NSCAPI::returnUNKNOWN;
246        }
247        unsigned long long value = pObject->getUptime();
248        if (bNSClient) {
249                msg = strEx::itos(value);
250        } else {
251                value *= 1000;
252                bounds.runCheck(value, returnCode, msg, perf, bShowAll);
253        }
254
255        if (msg.empty())
256                msg = "OK all counters within bounds.";
257        else if (!bNSClient)
258                msg = NSCHelper::translateReturn(returnCode) + ": " + msg;
259        return returnCode;
260}
261
262// @todo state_handler
263
264
265
266/**
267 * Retrieve the service state of one or more services (by name).
268 * Parse a list with a service names and verify that all named services are running.
269 * <pre>
270 * Syntax:
271 * request: checkServiceState <option> [<option> [...]]
272 * Return: <return state>&<service1> : <state1> - <service2> : <state2> - ...
273 * Available options:
274 *              <name>=<state>  Check if a service has a specific state
275 *                      State can be wither started or stopped
276 *              ShowAll                 Show the state of all listed service. If not set only critical services are listed.
277 * Examples:
278 * checkServiceState showAll myService MyService
279 *</pre>
280 *
281 * @param command Command to execute
282 * @param argLen The length of the argument buffer
283 * @param **char_args The argument buffer
284 * @param &msg String to put message in
285 * @param &perf String to put performance data in
286 * @return The status of the command
287 */
288NSCAPI::nagiosReturn CheckSystem::checkServiceState(const unsigned int argLen, char **char_args, std::string &msg, std::string &perf)
289{
290        typedef checkHolders::CheckConatiner<checkHolders::SimpleBoundsStateBoundsInteger> StateConatiner;
291        std::list<std::string> stl_args = arrayBuffer::arrayBuffer2list(argLen, char_args);
292        if (stl_args.empty()) {
293                msg = "ERROR: Missing argument exception.";
294                return NSCAPI::returnUNKNOWN;
295        }
296        std::list<StateConatiner> list;
297        NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK;
298        bool bShowAll = false;
299        bool bNSClient = false;
300        StateConatiner tmpObject;
301
302        tmpObject.data = "uptime";
303        tmpObject.warn.state = "started";
304
305        MAP_OPTIONS_BEGIN(stl_args)
306                /*
307                MAP_OPTIONS_STR("MaxWarn", tmpObject.warn.max)
308                MAP_OPTIONS_STR("warn", tmpObject.warn.min)
309                MAP_OPTIONS_STR("MinWarn", tmpObject.warn.min)
310                MAP_OPTIONS_STR("MaxCrit", tmpObject.crit.max)
311                MAP_OPTIONS_STR("crit", tmpObject.crit.min)
312                MAP_OPTIONS_STR("MinCrit", tmpObject.crit.min)
313                */
314                MAP_OPTIONS_STR("Alias", tmpObject.data)
315                MAP_OPTIONS_BOOL_TRUE(SHOW_ALL, bShowAll)
316                MAP_OPTIONS_BOOL_FALSE(SHOW_FAIL, bShowAll)
317                MAP_OPTIONS_BOOL_TRUE(NSCLIENT, bNSClient)
318                MAP_OPTIONS_SECONDARY_BEGIN(":", p2)
319                        else if (p2.first == "Time") {
320                                tmpObject.data = p__.second;
321                                tmpObject.alias = p2.second;
322                                list.push_back(tmpObject);
323                        }
324                        MAP_OPTIONS_MISSING_EX(p2, msg, "Unknown argument: ")
325                MAP_OPTIONS_SECONDARY_END()
326                else {
327                        tmpObject.data = p__.first;
328                        if (p__.second.empty())
329                                tmpObject.crit.state = "started";
330                        else
331                                tmpObject.crit.state = p__.second;
332                        list.push_back(tmpObject);
333                }
334        MAP_OPTIONS_END()
335
336        for (std::list<StateConatiner>::iterator it = list.begin(); it != list.end(); ++it) {
337                TNtServiceInfo info;
338                if (bNSClient) {
339                        try {
340                                info = TNtServiceInfo::GetService((*it).data.c_str());
341                        } catch (NTServiceException e) {
342                                if (!msg.empty()) msg += " - ";
343                                msg += (*it).data + ": Unknown";
344                                NSCHelper::escalteReturnCodeToWARN(returnCode);
345                                continue;
346                        }
347                        if ((info.m_dwCurrentState == SERVICE_RUNNING) && (bShowAll)) {
348                                if (!msg.empty()) msg += " - ";
349                                msg += (*it).data + ": Started";
350                        } else if (info.m_dwCurrentState == SERVICE_RUNNING) {
351                        } else if (info.m_dwCurrentState == SERVICE_STOPPED) {
352                                if (!msg.empty()) msg += " - ";
353                                msg += (*it).data + ": Stopped";
354                                NSCHelper::escalteReturnCodeToCRIT(returnCode);
355                        } else {
356                                if (!msg.empty()) msg += " - ";
357                                msg += (*it).data + ": Unknown";
358                                NSCHelper::escalteReturnCodeToWARN(returnCode);
359                        }
360                } else {
361                        try {
362                                info = TNtServiceInfo::GetService((*it).data.c_str());
363                        } catch (NTServiceException e) {
364                                NSC_LOG_ERROR_STD(e.getError());
365                                msg = e.getError();
366                                return NSCAPI::returnUNKNOWN;
367                        }
368                        checkHolders::state_type value;
369                        if (info.m_dwCurrentState == SERVICE_RUNNING)
370                                value = checkHolders::state_started;
371                        else if (info.m_dwCurrentState == SERVICE_STOPPED)
372                                value = checkHolders::state_stopped;
373                        else
374                                value = checkHolders::state_none;
375                        (*it).runCheck(value, returnCode, msg, perf, bShowAll);
376                }
377
378        }
379        if (msg.empty())
380                msg = "OK: All services are running.";
381        else if (!bNSClient)
382                msg = NSCHelper::translateReturn(returnCode) + ": " + msg;
383        return returnCode;
384}
385
386
387/**
388 * Check available memory and return various check results
389 * Example: checkMem showAll maxWarn=50 maxCrit=75
390 *
391 * @param command Command to execute
392 * @param argLen The length of the argument buffer
393 * @param **char_args The argument buffer
394 * @param &msg String to put message in
395 * @param &perf String to put performance data in
396 * @return The status of the command
397 */
398NSCAPI::nagiosReturn CheckSystem::checkMem(const unsigned int argLen, char **char_args, std::string &msg, std::string &perf)
399{
400        typedef checkHolders::CheckConatiner<checkHolders::MaxMinPercentageBoundsInt64 > MemoryConatiner;
401        std::list<std::string> stl_args = arrayBuffer::arrayBuffer2list(argLen, char_args);
402        if (stl_args.empty()) {
403                msg = "ERROR: Missing argument exception.";
404                return NSCAPI::returnUNKNOWN;
405        }
406        NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK;
407        bool bShowAll = false;
408        bool bNSClient = false;
409        MemoryConatiner bounds;
410
411        bounds.data = "page";
412
413        MAP_OPTIONS_BEGIN(stl_args)
414                MAP_OPTIONS_STR("MaxWarn", bounds.warn.max)
415                MAP_OPTIONS_STR("MinWarn", bounds.warn.min)
416                MAP_OPTIONS_STR("MaxCrit", bounds.crit.max)
417                MAP_OPTIONS_STR("MinCrit", bounds.crit.min)
418                MAP_OPTIONS_STR("Alias", bounds.data)
419                MAP_OPTIONS_BOOL_TRUE(SHOW_ALL, bShowAll)
420                MAP_OPTIONS_BOOL_TRUE(NSCLIENT, bNSClient)
421                MAP_OPTIONS_MISSING(msg, "Unknown argument: ")
422        MAP_OPTIONS_END()
423
424        PDHCollector *pObject = pdhThread.getThread();
425        if (!pObject) {
426                msg = "ERROR: PDH Collection thread not running.";
427                return NSCAPI::returnUNKNOWN;
428        }
429        long long pageCommit = pObject->getMemCommit();
430        long long pageCommitLimit = pObject->getMemCommitLimit();
431        if (bNSClient) {
432                msg = strEx::itos(pageCommitLimit) + "&" + strEx::itos(pageCommit);
433                return NSCAPI::returnOK;
434        } else {
435                bounds.warn.max.setMax(pageCommitLimit);
436                bounds.warn.min.setMax(pageCommitLimit);
437                bounds.crit.max.setMax(pageCommitLimit);
438                bounds.crit.min.setMax(pageCommitLimit);
439                bounds.runCheck(pageCommit, returnCode, msg, perf, bShowAll);
440        }
441        if (msg.empty())
442                msg = "OK memory within bounds.";
443        else
444                msg = NSCHelper::translateReturn(returnCode) + ": " + msg;
445        return returnCode;
446}
447typedef struct NSPROCDATA__ {
448        NSPROCDATA__() : count(0) {}
449        NSPROCDATA__(const NSPROCDATA__ &other) {
450                count = other.count;
451                entry = other.entry;
452        }
453
454        unsigned int count;
455        CEnumProcess::CProcessEntry entry;
456} NSPROCDATA;
457typedef std::hash_map<std::string,NSPROCDATA> NSPROCLST;
458/**
459* Get a hash_map with all running processes.
460* @return a hash_map with all running processes
461*/
462NSPROCLST GetProcessList(int processMethod)
463{
464        NSPROCLST ret;
465        if (processMethod == 0) {
466                NSC_LOG_ERROR_STD("ProcessMethod not defined or not available.");
467                return ret;
468        }
469        CEnumProcess enumeration;
470        enumeration.SetMethod(processMethod);
471        CEnumProcess::CProcessEntry entry;
472        for (BOOL OK = enumeration.GetProcessFirst(&entry); OK; OK = enumeration.GetProcessNext(&entry) ) {
473                NSPROCLST::iterator it = ret.find(entry.sFilename);
474                if (it == ret.end())
475                        ret[entry.sFilename].entry = entry;
476                else
477                        (*it).second.count++;
478        }
479        return ret;
480}
481
482/**
483 * Check process state and return result
484 *
485 * @param command Command to execute
486 * @param argLen The length of the argument buffer
487 * @param **char_args The argument buffer
488 * @param &msg String to put message in
489 * @param &perf String to put performance data in
490 * @return The status of the command
491 */
492NSCAPI::nagiosReturn CheckSystem::checkProcState(const unsigned int argLen, char **char_args, std::string &msg, std::string &perf)
493{
494        typedef checkHolders::CheckConatiner<checkHolders::MaxMinStateBoundsStateBoundsInteger> StateConatiner;
495        std::list<std::string> stl_args = arrayBuffer::arrayBuffer2list(argLen, char_args);
496        if (stl_args.empty()) {
497                msg = "ERROR: Missing argument exception.";
498                return NSCAPI::returnUNKNOWN;
499        }
500        std::list<StateConatiner> list;
501        NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK;
502        bool bShowAll = false;
503        bool bNSClient = false;
504        StateConatiner tmpObject;
505
506        tmpObject.data = "uptime";
507        tmpObject.crit.state = "started";
508
509        MAP_OPTIONS_BEGIN(stl_args)
510                MAP_OPTIONS_STR("MaxWarnCount", tmpObject.warn.max)
511                MAP_OPTIONS_STR("MinWarnCount", tmpObject.warn.min)
512                MAP_OPTIONS_STR("MaxCritCount", tmpObject.crit.max)
513                MAP_OPTIONS_STR("MinCritCount", tmpObject.crit.min)
514                MAP_OPTIONS_STR("Alias", tmpObject.alias)
515                MAP_OPTIONS_BOOL_TRUE(SHOW_ALL, bShowAll)
516                MAP_OPTIONS_BOOL_FALSE(SHOW_FAIL, bShowAll)
517                MAP_OPTIONS_BOOL_TRUE(NSCLIENT, bNSClient)
518                MAP_OPTIONS_SECONDARY_BEGIN(":", p2)
519                else if (p2.first == "Proc") {
520                        tmpObject.data = p__.second;
521                        tmpObject.alias = p2.second;
522                        list.push_back(tmpObject);
523                }
524                MAP_OPTIONS_MISSING_EX(p2, msg, "Unknown argument: ")
525                        MAP_OPTIONS_SECONDARY_END()
526                else {
527                        tmpObject.data = p__.first;
528                        if (p__.second.empty())
529                                tmpObject.crit.state = "started";
530                        else
531                                tmpObject.crit.state = p__.second;
532                        list.push_back(tmpObject);
533                }
534        MAP_OPTIONS_END()
535
536
537        NSPROCLST runningProcs;
538        try {
539                runningProcs = GetProcessList(processMethod_);
540        } catch (char *c) {
541                NSC_LOG_ERROR_STD("ERROR: " + c);
542                msg = static_cast<std::string>("ERROR: ") + c;
543                return NSCAPI::returnUNKNOWN;
544        }
545
546        for (std::list<StateConatiner>::iterator it = list.begin(); it != list.end(); ++it) {
547                NSPROCLST::iterator proc = runningProcs.find((*it).data);
548                bool bFound = proc != runningProcs.end();
549                std::string tmp;
550                TNtServiceInfo info;
551                if (bNSClient) {
552                        if (bFound && bShowAll) {
553                                if (!msg.empty()) msg += " - ";
554                                msg += (*it).data + ": Started";
555                        } else if (bFound) {
556                        } else {
557                                if (!msg.empty()) msg += " - ";
558                                msg += (*it).data + ": Stopped";
559                                NSCHelper::escalteReturnCodeToCRIT(returnCode);
560                        }
561                } else {
562                        checkHolders::MaxMinStateValueType<int, checkHolders::state_type> value;
563                        if (bFound) {
564                                value.count = (*proc).second.count;
565                                value.state = checkHolders::state_started;
566                        } else {
567                                value.count = 0;
568                                value.state = checkHolders::state_stopped;
569                        }
570                        (*it).runCheck(value, returnCode, msg, perf, bShowAll);
571                }
572
573        }
574        if (msg.empty())
575                msg = "OK: All processes are running.";
576        else if (!bNSClient)
577                msg = NSCHelper::translateReturn(returnCode) + ": " + msg;
578        return returnCode;
579}
580
581
582/**
583 * Check a counter and return the value
584 *
585 * @param command Command to execute
586 * @param argLen The length of the argument buffer
587 * @param **char_args The argument buffer
588 * @param &msg String to put message in
589 * @param &perf String to put performance data in
590 * @return The status of the command
591 *
592 * @todo add parsing support for NRPE
593 */
594NSCAPI::nagiosReturn CheckSystem::checkCounter(const unsigned int argLen, char **char_args, std::string &msg, std::string &perf)
595{
596        typedef checkHolders::CheckConatiner<checkHolders::MaxMinBoundsDouble> CounterConatiner;
597
598        std::list<std::string> stl_args = arrayBuffer::arrayBuffer2list(argLen, char_args);
599        if (stl_args.empty()) {
600                msg = "ERROR: Missing argument exception.";
601                return NSCAPI::returnUNKNOWN;
602        }
603        std::list<CounterConatiner> counters;
604        NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK;
605        bool bShowAll = false;
606        bool bNSClient = false;
607        /* average maax */
608        bool bCheckAverages = true;
609        unsigned int averageDelay = 1000;
610        CounterConatiner tmpObject;
611
612        MAP_OPTIONS_BEGIN(stl_args)
613                MAP_OPTIONS_STR_AND("Counter", tmpObject.data, counters.push_back(tmpObject))
614                MAP_OPTIONS_STR("MaxWarn", tmpObject.warn.max)
615                MAP_OPTIONS_STR("MinWarn", tmpObject.warn.min)
616                MAP_OPTIONS_STR("MaxCrit", tmpObject.crit.max)
617                MAP_OPTIONS_STR("MinCrit", tmpObject.crit.min)
618                MAP_OPTIONS_STR("Alias", tmpObject.data)
619                MAP_OPTIONS_BOOL_TRUE(SHOW_ALL, bShowAll)
620                MAP_OPTIONS_BOOL_FALSE(SHOW_FAIL, bShowAll)
621                MAP_OPTIONS_BOOL_EX("Averages", bCheckAverages, "true", "false")
622                MAP_OPTIONS_BOOL_TRUE(NSCLIENT, bNSClient)
623                MAP_OPTIONS_SECONDARY_BEGIN(":", p2)
624                        else if (p2.first == "Counter") {
625                                tmpObject.data = p__.second;
626                                tmpObject.alias = p2.second;
627                                counters.push_back(tmpObject);
628                        }
629                        MAP_OPTIONS_MISSING_EX(p2, msg, "Unknown argument: ")
630                MAP_OPTIONS_SECONDARY_END()
631                else {
632                        tmpObject.data = p__.first;
633                        counters.push_back(tmpObject);
634                }
635        MAP_OPTIONS_END()
636
637        for (std::list<CounterConatiner>::const_iterator cit = counters.begin(); cit != counters.end(); ++cit) {
638                CounterConatiner counter = (*cit);
639                try {
640                        std::string tstr;
641                        if (!PDH::Enumerations::validate(counter.data, tstr)) {
642                                msg = tstr;
643                                return NSCAPI::returnUNKNOWN;
644                        }
645                        PDH::PDHQuery pdh;
646                        PDHCollectors::StaticPDHCounterListener<double, PDH_FMT_DOUBLE> cDouble;
647                        pdh.addCounter(counter.data, &cDouble);
648                        pdh.open();
649                        pdh.collect();
650                        Sleep(1000);
651                        pdh.gatherData();
652                        pdh.close();
653                        double value = cDouble.getValue();
654                        std::cout << "Collected double data: " << value << std::endl;
655                        if (bNSClient) {
656                                msg += strEx::itos(value);
657                        } else {
658                                counter.setDefault(tmpObject);
659                                counter.runCheck(value, returnCode, msg, perf, bShowAll);
660                        }
661                } catch (const PDH::PDHException e) {
662                        NSC_LOG_ERROR_STD("ERROR: " + e.getError() + " (" + counter.getAlias() + ")");
663                        msg = static_cast<std::string>("ERROR: ") + e.getError();
664                        return NSCAPI::returnUNKNOWN;
665                }
666        }
667
668        if (msg.empty())
669                msg = "OK all counters within bounds.";
670        else if (!bNSClient)
671                msg = NSCHelper::translateReturn(returnCode) + ": " + msg;
672        return returnCode;
673}
674NSC_WRAPPERS_MAIN_DEF(gNSClientCompat);
675NSC_WRAPPERS_IGNORE_MSG_DEF();
676NSC_WRAPPERS_HANDLE_CMD_DEF(gNSClientCompat);
677NSC_WRAPPERS_HANDLE_CONFIGURATION(gNSClientCompat);
678
679
680
681MODULE_SETTINGS_START(CheckSystem, "System check module", "...")
682
683PAGE("Check options")
684
685ITEM_EDIT_TEXT("Check resolution", "This is how often the PDH data is polled and stored in the CPU buffer. (this is enterd in 1/th: of a second)")
686OPTION("unit", "1/10:th of a second")
687ITEM_MAP_TO("basic_ini_text_mapper")
688OPTION("section", "Check System")
689OPTION("key", "CheckResolution")
690OPTION("default", "10")
691ITEM_END()
692
693ITEM_EDIT_TEXT("CPU buffer size", "This is the size of the buffer that stores CPU history.")
694ITEM_MAP_TO("basic_ini_text_mapper")
695OPTION("section", "Check System")
696OPTION("key", "CPUBufferSize")
697OPTION("default", "1h")
698ITEM_END()
699
700PAGE_END()
701ADVANCED_PAGE("Compatiblity settings")
702
703ITEM_EDIT_TEXT("MemoryCommitByte", "The memory commited bytes used to calculate the avalible memory.")
704OPTION("disableCaption", "Attempt to autodetect this.")
705OPTION("disabled", "auto")
706ITEM_MAP_TO("basic_ini_text_mapper")
707OPTION("section", "Check System")
708OPTION("key", "MemoryCommitByte")
709OPTION("default", "auto")
710ITEM_END()
711
712ITEM_EDIT_TEXT("MemoryCommitLimit", "The memory commit limit used to calculate the avalible memory.")
713OPTION("disableCaption", "Attempt to autodetect this.")
714OPTION("disabled", "auto")
715ITEM_MAP_TO("basic_ini_text_mapper")
716OPTION("section", "Check System")
717OPTION("key", "MemoryCommitLimit")
718OPTION("default", "auto")
719ITEM_END()
720
721ITEM_EDIT_TEXT("SystemSystemUpTime", "The PDH counter for the System uptime.")
722OPTION("disableCaption", "Attempt to autodetect this.")
723OPTION("disabled", "auto")
724ITEM_MAP_TO("basic_ini_text_mapper")
725OPTION("section", "Check System")
726OPTION("key", "SystemSystemUpTime")
727OPTION("default", "auto")
728ITEM_END()
729
730ITEM_EDIT_TEXT("SystemTotalProcessorTime", "The PDH conter usaed to measure CPU load.")
731OPTION("disableCaption", "Attempt to autodetect this.")
732OPTION("disabled", "auto")
733ITEM_MAP_TO("basic_ini_text_mapper")
734OPTION("section", "Check System")
735OPTION("key", "SystemTotalProcessorTime")
736OPTION("default", "auto")
737ITEM_END()
738
739ITEM_EDIT_TEXT("ProcessEnumerationMethod", "The method to use when enumerating processes")
740OPTION("count", "3")
741OPTION("caption_1", "Autodetect (TOOLHELP for NT/4 and PSAPI for W2k)")
742OPTION("value_1", "auto")
743OPTION("caption_2", "TOOLHELP use this for NT/4 systems")
744OPTION("value_2", "TOOLHELP")
745OPTION("caption_3", "PSAPI use this for W2k (and abowe) systems")
746OPTION("value_3", "PSAPI")
747ITEM_MAP_TO("basic_ini_text_mapper")
748OPTION("section", "Check System")
749OPTION("key", "ProcessEnumerationMethod")
750OPTION("default", "auto")
751ITEM_END()
752
753PAGE_END()
754MODULE_SETTINGS_END()
Note: See TracBrowser for help on using the repository browser.