source: nscp/modules/CheckSystem/CheckSystem.cpp @ 53be5c8

0.4.10.4.2
Last change on this file since 53be5c8 was 53be5c8, checked in by Michael Medin <michael@…>, 10 months ago
  • LUAScript: Improved lua scripting module a lot
  • LUAScript: Added protocol buffer support to lua scripts
  • tests: Rewrote (halfway there) test_nrpe python script as a lua script.
  • CheckEventLog: Fixed command name when submitting real-time "no action checks"
  • Property mode set to 100644
File size: 64.1 KB
Line 
1/**************************************************************************
2*   Copyright (C) 2004-2007 by Michael Medin <michael@medin.name>         *
3*                                                                         *
4*   This code is part of NSClient++ - http://trac.nakednuns.org/nscp      *
5*                                                                         *
6*   This program is free software; you can redistribute it and/or modify  *
7*   it under the terms of the GNU General Public License as published by  *
8*   the Free Software Foundation; either version 2 of the License, or     *
9*   (at your option) any later version.                                   *
10*                                                                         *
11*   This program is distributed in the hope that it will be useful,       *
12*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
13*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
14*   GNU General Public License for more details.                          *
15*                                                                         *
16*   You should have received a copy of the GNU General Public License     *
17*   along with this program; if not, write to the                         *
18*   Free Software Foundation, Inc.,                                       *
19*   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
20***************************************************************************/
21
22#include "stdafx.h"
23#include "CheckSystem.h"
24
25#include <map>
26#include <set>
27
28#include <boost/regex.hpp>
29#include <boost/assign/list_of.hpp>
30
31#include <tlhelp32.h>
32
33
34#include <utils.h>
35#include <EnumNtSrv.h>
36#include <EnumProcess.h>
37#include <checkHelpers.hpp>
38#include <sysinfo.h>
39#include <filter_framework.hpp>
40#include <simple_registry.hpp>
41#include <settings/client/settings_client.hpp>
42#include <config.h>
43
44/**
45 * Default c-tor
46 * @return
47 */
48CheckSystem::CheckSystem() : pdhThread(_T("pdhThread")) {}
49/**
50 * Default d-tor
51 * @return
52 */
53CheckSystem::~CheckSystem() {}
54
55namespace sh = nscapi::settings_helper;
56
57/**
58 * Load (initiate) module.
59 * Start the background collector thread and let it run until unloadModule() is called.
60 * @return true
61 */
62bool CheckSystem::loadModule() {
63        return loadModuleEx(_T(""), NSCAPI::normalStart);
64}
65
66/**
67 * New version of the load call.
68 * Start the background collector thread and let it run until unloadModule() is called.
69 * @return true
70 */
71
72bool missing_system_counters(std::map<std::wstring,std::wstring> &counters)
73{
74        wchar_t *keys[] = {PDH_SYSTEM_KEY_UPT, PDH_SYSTEM_KEY_MCL, PDH_SYSTEM_KEY_MCB, PDH_SYSTEM_KEY_CPU};
75        BOOST_FOREACH(const wchar_t *cnt, keys) {
76                if (counters.find(cnt) == counters.end())
77                        return true;
78        }
79        return false;
80}
81
82bool CheckSystem::loadModuleEx(std::wstring alias, NSCAPI::moduleLoadMode mode) {
83        PDHCollector::system_counter_data *data = new PDHCollector::system_counter_data;
84        data->check_intervall = 1;
85        try {
86                typedef std::map<std::wstring,std::wstring> counter_map_type;
87                counter_map_type counters;
88
89                sh::settings_registry settings(get_settings_proxy());
90                settings.set_alias(_T("check"), alias, _T("system/windows"));
91
92                settings.alias().add_path_to_settings()
93                        (_T("pdh/counters"), sh::wstring_map_path(&counters)
94                        , _T("PDH COUNTERS"), _T("Define various PDH counters to check."))
95                        ;
96
97                settings.register_all();
98                settings.notify();
99                settings.clear();
100
101                if (counters.empty() || missing_system_counters(counters)) {
102                        std::wstring path = settings.alias().get_settings_path(_T("pdh/counters"));
103
104                        get_core()->settings_register_key(path, PDH_SYSTEM_KEY_UPT, NSCAPI::key_string, _T("UPTIME"), _T("PDH Key for system uptime."), _T("\\2\\674"), false);
105                        get_core()->settings_register_key(path, PDH_SYSTEM_KEY_MCL, NSCAPI::key_string, _T("Commit limit"), _T("PDH key for memory commit limit"), _T("\\4\\30"), false);
106                        get_core()->settings_register_key(path, PDH_SYSTEM_KEY_MCB, NSCAPI::key_string, _T("Commit bytes"), _T("PDH Key for system CPU load."), _T("\\4\\26"), false);
107                        get_core()->settings_register_key(path, PDH_SYSTEM_KEY_CPU, NSCAPI::key_string, _T("CPU Load"), _T("PDH Key for system CPU load."), _T("\\238(_total)\\6"), false);
108                        get_core()->settings_register_key(path + _T("/") + PDH_SYSTEM_KEY_CPU, _T("collection strategy"), NSCAPI::key_string, _T("Collection Strategy"), _T("Collection strategy for CPP is usually round robin."), _T("round robin"), false);
109                }
110
111                settings.alias().add_path_to_settings()
112                        (_T("WINDOWS CHECK SYSTEM"), _T("Section for system checks and system settings"))
113
114                        (_T("service mapping"), _T("SERVICE MAPPING SECTION"), _T("Confiure which services has to be in which state"))
115
116                        (_T("pdh"), _T("PDH COUNTER INFORMATION"), _T(""))
117
118                        ;
119
120                settings.alias().add_key_to_settings()
121                        (_T("default buffer length"), sh::wstring_key(&data->buffer_length, _T("1h")),
122                        _T("DEFAULT LENGTH"), _T("Used to define the default intervall for range buffer checks (ie. CPU)."))
123
124                        (_T("default intervall"), sh::uint_key(&data->check_intervall, 1),
125                        _T("DEFAULT INTERVALL"), _T("Used to define the default intervall for range buffer checks (ie. CPU)."), true)
126
127                        ;
128
129                settings.alias().add_key_to_settings(_T("service mapping"))
130
131                        (_T("BOOT_START"), sh::wstring_vector_key(&lookups_, SERVICE_BOOT_START, _T("ignored")),
132                        _T("SERVICE_BOOT_START"), _T("TODO"), true)
133
134                        (_T("SYSTEM_START"), sh::wstring_vector_key(&lookups_, SERVICE_SYSTEM_START, _T("ignored")),
135                        _T("SERVICE_SYSTEM_START"), _T("TODO"), true)
136
137                        (_T("AUTO_START"), sh::wstring_vector_key(&lookups_, SERVICE_AUTO_START, _T("started")),
138                        _T("SERVICE_AUTO_START"), _T("TODO"), true)
139
140                        (_T("DEMAND_START"), sh::wstring_vector_key(&lookups_, SERVICE_DEMAND_START, _T("ignored")),
141                        _T("SERVICE_DEMAND_START"), _T("TODO"), true)
142
143                        (_T("DISABLED"), sh::wstring_vector_key(&lookups_, SERVICE_DISABLED, _T("stopped")),
144                        _T("SERVICE_DISABLED"), _T("TODO"), true)
145
146                        (_T("DELAYED"), sh::wstring_vector_key(&lookups_, NSCP_SERVICE_DELAYED, _T("ignored")),
147                        _T("SERVICE_DELAYED"), _T("TODO"), true)
148
149                        ;
150
151                settings.register_all();
152                settings.notify();
153
154               
155                typedef PDHCollector::system_counter_data::counter cnt;
156                /*
157                if (default_counters) {
158                        data->counters.push_back(cnt(PDH_SYSTEM_KEY_MCL, _T("\\4\\30"), cnt::type_int64, cnt::format_large, cnt::value));
159                        data->counters.push_back(cnt(PDH_SYSTEM_KEY_CPU, _T("\\238(_total)\\6"), cnt::type_int64, cnt::format_large, cnt::rrd));
160                        data->counters.push_back(cnt(PDH_SYSTEM_KEY_MCB, _T("\\4\\26"), cnt::type_int64, cnt::format_large, cnt::value));
161                        data->counters.push_back(cnt(PDH_SYSTEM_KEY_UPT, _T("\\2\\674"), cnt::type_int64, cnt::format_large, cnt::value));
162                }
163                */
164                BOOST_FOREACH(counter_map_type::value_type c, counters) {
165                        data->counters.push_back(cnt(c.first, c.second, cnt::type_int64, cnt::format_large, cnt::value));
166                }
167
168                register_command(_T("check_CPU"), _T("Check that the load of the CPU(s) are within bounds."),
169                        boost::assign::list_of(_T("checkCPU")));
170                register_command(_T("check_uptime"), _T("Check time since last server re-boot."),
171                        boost::assign::list_of(_T("checkUpTime")));
172                register_command(_T("check_service"), _T("Check the state of one or more of the computer services."),
173                        boost::assign::list_of(_T("checkServiceState")));
174                register_command(_T("check_process"), _T("Check the state of one or more of the processes running on the computer."),
175                        boost::assign::list_of(_T("checkProcState")));
176                register_command(_T("check_memory"), _T("Check free/used memory on the system."),
177                        boost::assign::list_of(_T("checkMem")));
178                register_command(_T("check_pdh"), _T("Check a PDH counter."),
179                        boost::assign::list_of(_T("checkCounter")));
180                register_command(_T("check_registry"), _T("Check values in the registry."),
181                        boost::assign::list_of(_T("checkSingleRegEntry")));
182
183                register_command(_T("listCounterInstances"), _T("*DEPRECATED* List all instances for a counter."));
184
185        } catch (nscapi::nscapi_exception &e) {
186                NSC_LOG_ERROR_STD(_T("Failed to register command: ") + utf8::cvt<std::wstring>(e.what()));
187                return false;
188        } catch (std::exception &e) {
189                NSC_LOG_ERROR_STD(_T("Exception: ") + utf8::cvt<std::wstring>(e.what()));
190                return false;
191        } catch (...) {
192                NSC_LOG_ERROR_STD(_T("Failed to register command."));
193                return false;
194        }
195
196        if (mode == NSCAPI::normalStart) {
197                pdhThread.createThread(data);
198        }
199
200        return true;
201}
202/**
203 * Unload (terminate) module.
204 * Attempt to stop the background processing thread.
205 * @return true if successfully, false if not (if not things might be bad)
206 */
207bool CheckSystem::unloadModule() {
208        if (!pdhThread.exitThread(20000)) {
209                std::wcout << _T("MAJOR ERROR: Could not unload thread...") << std::endl;
210                NSC_LOG_ERROR(_T("Could not exit the thread, memory leak and potential corruption may be the result..."));
211        }
212        return true;
213}
214/**
215 * Check if we have a command handler.
216 * @return true (as we have a command handler)
217 */
218bool CheckSystem::hasCommandHandler() {
219        return true;
220}
221/**
222 * Check if we have a message handler.
223 * @return false as we have no message handler
224 */
225bool CheckSystem::hasMessageHandler() {
226        return false;
227}
228
229int CheckSystem::commandLineExec(const std::wstring &command, std::list<std::wstring> &arguments, std::wstring &result) {
230        if (command == _T("help")) {
231                std::wcerr << _T("Usage: ... CheckSystem <command>") << std::endl;
232                std::wcerr << _T("Commands: debugpdh, listpdh, pdhlookup, pdhmatch, pdhobject") << std::endl;
233                return -1;
234        }
235        if (command == _T("debugpdh")) {
236                PDH::Enumerations::Objects lst;
237                try {
238                        lst = PDH::Enumerations::EnumObjects();
239                } catch (const PDH::PDHException e) {
240                        std::wcout << _T("Service enumeration failed: ") << e.getError();
241                        return 0;
242                }
243                for (PDH::Enumerations::Objects::iterator it = lst.begin();it!=lst.end();++it) {
244                        if ((*it).instances.size() > 0) {
245                                for (PDH::Enumerations::Instances::const_iterator it2 = (*it).instances.begin();it2!=(*it).instances.end();++it2) {
246                                        for (PDH::Enumerations::Counters::const_iterator it3 = (*it).counters.begin();it3!=(*it).counters.end();++it3) {
247                                                std::wstring counter = _T("\\") + (*it).name + _T("(") + (*it2).name + _T(")\\") + (*it3).name;
248                                                std::wcout << _T("testing: ") << counter << _T(": ");
249                                                std::list<std::wstring> errors;
250                                                std::list<std::wstring> status;
251                                                std::wstring error;
252                                                bool bStatus = true;
253                                                if (PDH::PDHResolver::validate(counter, error, false)) {
254                                                        status.push_back(_T("open"));
255                                                } else {
256                                                        errors.push_back(_T("NOT found: ") + error);
257                                                        bStatus = false;
258                                                }
259                                                if (bStatus) {
260                                                       
261                                                        typedef boost::shared_ptr<PDH::PDHCounter> counter_ptr;
262                                                        counter_ptr pCounter;
263                                                        PDH::PDHQuery pdh;
264                                                        try {
265                                                                pdh.addCounter(counter);
266                                                                pdh.open();
267
268                                                                if (pCounter != NULL) {
269                                                                        try {
270                                                                                PDH::PDHCounterInfo info = pCounter->getCounterInfo();
271                                                                                errors.push_back(_T("CounterName: ") + info.szCounterName);
272                                                                                errors.push_back(_T("ExplainText: ") + info.szExplainText);
273                                                                                errors.push_back(_T("FullPath: ") + info.szFullPath);
274                                                                                errors.push_back(_T("InstanceName: ") + info.szInstanceName);
275                                                                                errors.push_back(_T("MachineName: ") + info.szMachineName);
276                                                                                errors.push_back(_T("ObjectName: ") + info.szObjectName);
277                                                                                errors.push_back(_T("ParentInstance: ") + info.szParentInstance);
278                                                                                errors.push_back(_T("Type: ") + strEx::itos(info.dwType));
279                                                                                errors.push_back(_T("Scale: ") + strEx::itos(info.lScale));
280                                                                                errors.push_back(_T("Default Scale: ") + strEx::itos(info.lDefaultScale));
281                                                                                errors.push_back(_T("Status: ") + strEx::itos(info.CStatus));
282                                                                                status.push_back(_T("described"));
283                                                                        } catch (const PDH::PDHException e) {
284                                                                                errors.push_back(_T("Describe failed: ") + e.getError());
285                                                                                bStatus = false;
286                                                                        }
287                                                                }
288
289                                                                pdh.gatherData();
290                                                                pdh.close();
291                                                                status.push_back(_T("queried"));
292                                                        } catch (const PDH::PDHException e) {
293                                                                errors.push_back(_T("Query failed: ") + e.getError());
294                                                                bStatus = false;
295                                                                try {
296                                                                        pdh.gatherData();
297                                                                        pdh.close();
298                                                                        bStatus = true;
299                                                                } catch (const PDH::PDHException e) {
300                                                                        errors.push_back(_T("Query failed (again!): ") + e.getError());
301                                                                }
302                                                        }
303
304                                                }
305                                                if (!bStatus) {
306                                                        std::list<std::wstring>::const_iterator cit = status.begin();
307                                                        for (;cit != status.end(); ++cit) {
308                                                                std::wcout << *cit << _T(", ");
309                                                        }
310                                                        std::wcout << std::endl;
311                                                        std::wcout << _T("  | Log") << std::endl;
312                                                        std::wcout << _T("--+------  --    -") << std::endl;
313                                                        cit = errors.begin();
314                                                        for (;cit != errors.end(); ++cit) {
315                                                                std::wcout << _T("  | ") << *cit << std::endl;
316                                                        }
317                                                } else {
318                                                        std::list<std::wstring>::const_iterator cit = status.begin();
319                                                        for (;cit != status.end(); ++cit) {
320                                                                std::wcout << *cit << _T(", ");;
321                                                        }
322                                                        std::wcout << std::endl;
323                                                }
324                                        }
325                                }
326                        } else {
327                                if ((*it).counters.size() == 0) {
328                                        std::wcout << _T("empty counter: ") << (*it).name << std::endl;
329                                }
330                                for (PDH::Enumerations::Counters::const_iterator it2 = (*it).counters.begin();it2!=(*it).counters.end();++it2) {
331                                        std::wstring counter = _T("\\") + (*it).name + _T("\\") + (*it2).name;
332                                        std::wcout << _T("testing: ") << counter << _T(": ");
333                                        std::wstring error;
334                                        if (PDH::PDHResolver::validate(counter, error, false)) {
335                                                std::wcout << _T(" found ");
336                                        } else {
337                                                std::wcout << _T(" *NOT* found (") << error << _T(") ") << std::endl;
338                                                break;
339                                        }
340                                        bool bOpend = false;
341                                        try {
342                                                PDH::PDHQuery pdh;
343                                                //PDHCollectors::StaticPDHCounterListener<double, PDH_FMT_DOUBLE> cDouble;
344                                                pdh.addCounter(counter);
345                                                pdh.open();
346                                                pdh.gatherData();
347                                                pdh.close();
348                                                bOpend = true;
349                                        } catch (const PDH::PDHException e) {
350                                                std::wcout << _T(" could *not* be open (") << e.getError() << _T(") ") << std::endl;
351                                                break;
352                                        }
353                                        std::wcout << _T(" open ");
354                                        std::wcout << std::endl;
355                                }
356                        }
357                }
358        } else if (command == _T("listpdh")) {
359                bool porcelain = arguments.size() > 0 && arguments.front() == _T("--porcelain");
360                PDH::Enumerations::Objects lst;
361                try {
362                        lst = PDH::Enumerations::EnumObjects();
363                } catch (const PDH::PDHException e) {
364                        result = _T("ERROR: Service enumeration failed: ") + e.getError();
365                        return NSCAPI::returnUNKNOWN;
366                }
367                std::wstringstream ss;
368                BOOST_FOREACH(PDH::Enumerations::Object &obj, lst) {
369                        if (!obj.error.empty()) {
370                                ss << "error," << obj.name << "," << utf8::to_unicode(obj.error) << _T("\n");
371                        } else if (obj.instances.size() > 0) {
372                                BOOST_FOREACH(const PDH::Enumerations::Instance &inst, obj.instances) {
373                                        BOOST_FOREACH(const PDH::Enumerations::Counter &count, obj.counters) {
374                                                if (porcelain)
375                                                        ss << "counter," << obj.name << _T(",") << inst.name << _T(",") << count.name << _T("\n");
376                                                else
377                                                        ss << _T("\\") << obj.name << _T("(") << inst.name << _T(")\\") << count.name << _T("\n");
378                                        }
379                                }
380                        } else {
381                                BOOST_FOREACH(const PDH::Enumerations::Counter &count, obj.counters) {
382                                        if (porcelain)
383                                                ss << obj.name << _T(",") << count.name << _T("\n");
384                                        else
385                                                ss << _T("\\") << obj.name << _T("\\") << count.name << _T("\n");
386                                }
387                        }
388                }
389                result = ss.str();
390                return NSCAPI::returnOK;
391        } else if (command == _T("pdhlookup")) {
392                try {
393                        if (arguments.size() == 0) {
394                                NSC_LOG_ERROR_STD(_T("Need to specify counter index name!"));
395                                return 0;
396                        }
397                        std::wstring name = arguments.front();
398                        DWORD dw = PDH::PDHResolver::lookupIndex(name);
399                        NSC_LOG_MESSAGE_STD(_T("--+--[ Lookup Result ]----------------------------------------"));
400                        NSC_LOG_MESSAGE_STD(_T("  | Index for '") + name + _T("' is ") + strEx::itos(dw));
401                        NSC_LOG_MESSAGE_STD(_T("--+-----------------------------------------------------------"));
402                } catch (const PDH::PDHException e) {
403                        NSC_LOG_ERROR_STD(_T("Failed to lookup index: ") + e.getError());
404                        return 0;
405                }
406        } else if (command == _T("pdhmatch")) {
407                try {
408                        if (arguments.size() == 0) {
409                                NSC_LOG_ERROR_STD(_T("Need to specify counter index name!"));
410                                return 0;
411                        }
412                        std::wstring name = arguments.front();
413                        std::list<std::wstring> list = PDH::PDHResolver::PdhExpandCounterPath(name.c_str());
414                        NSC_LOG_MESSAGE_STD(_T("--+--[ Lookup Result ]----------------------------------------"));
415                        for (std::list<std::wstring>::const_iterator cit = list.begin(); cit != list.end(); ++cit) {
416                                NSC_LOG_MESSAGE_STD(_T("  | Found '") + *cit);
417                        }
418                        NSC_LOG_MESSAGE_STD(_T("--+-----------------------------------------------------------"));
419                } catch (const PDH::PDHException e) {
420                        NSC_LOG_ERROR_STD(_T("Failed to lookup index: ") + e.getError());
421                        return 0;
422                }
423        } else if (command == _T("pdhobject")) {
424                try {
425                        if (arguments.size() == 0) {
426                                NSC_LOG_ERROR_STD(_T("Need to specify counter index name!"));
427                                return 0;
428                        }
429                        std::wstring name = arguments.front();
430                        PDH::Enumerations::pdh_object_details list = PDH::Enumerations::EnumObjectInstances(name.c_str());
431                        NSC_LOG_MESSAGE_STD(_T("--+--[ Lookup Result ]----------------------------------------"));
432                        for (std::list<std::wstring>::const_iterator cit = list.counters.begin(); cit != list.counters.end(); ++cit) {
433                                NSC_LOG_MESSAGE_STD(_T("  | Found Counter: ") + *cit);
434                        }
435                        for (std::list<std::wstring>::const_iterator cit = list.instances.begin(); cit != list.instances.end(); ++cit) {
436                                NSC_LOG_MESSAGE_STD(_T("  | Found Instance: ") + *cit);
437                        }
438                        NSC_LOG_MESSAGE_STD(_T("--+-----------------------------------------------------------"));
439                } catch (const PDH::PDHException e) {
440                        NSC_LOG_ERROR_STD(_T("Failed to lookup index: ") + e.getError());
441                        return 0;
442                }
443        }
444        return 0;
445}
446
447
448/**
449 * Main command parser and delegator.
450 * This also handles a lot of the simpler responses (though some are deferred to other helper functions)
451 *
452 *
453 * @param command
454 * @param argLen
455 * @param **args
456 * @return
457 */
458NSCAPI::nagiosReturn CheckSystem::handleCommand(const std::wstring &target, const std::wstring &command, std::list<std::wstring> &arguments, std::wstring &message, std::wstring &perf) {
459        CheckSystem::returnBundle rb;
460        if (command == _T("checkcpu")) {
461                return checkCPU(arguments, message, perf);
462        } else if (command == _T("checkuptime")) {
463                return checkUpTime(arguments, message, perf);
464        } else if (command == _T("checkservicestate")) {
465                return checkServiceState(arguments, message, perf);
466        } else if (command == _T("checkprocstate")) {
467                return checkProcState(arguments, message, perf);
468        } else if (command == _T("checkmem")) {
469                return checkMem(arguments, message, perf);
470        } else if (command == _T("checkcounter")) {
471                return checkCounter(arguments, message, perf);
472        } else if (command == _T("listcounterinstances")) {
473                return listCounterInstances(arguments, message, perf);
474        } else if (command == _T("checksingleregentry")) {
475                return checkSingleRegEntry(arguments, message, perf);
476        }
477        return NSCAPI::returnIgnored;
478}
479
480
481class cpuload_handler {
482public:
483        static int parse(std::wstring s) {
484                return strEx::stoi(s);
485        }
486        static int parse_percent(std::wstring s) {
487                return strEx::stoi(s);
488        }
489        static std::wstring print(int value) {
490                return strEx::itos(value) + _T("%");
491        }
492        static std::wstring print_unformated(int value) {
493                return strEx::itos(value);
494        }
495
496        static std::wstring get_perf_unit(__int64 value) {
497                return _T("%");
498        }
499        static std::wstring print_perf(__int64 value, std::wstring unit) {
500                return boost::lexical_cast<std::wstring>(value);
501        }
502        static std::wstring print_percent(int value) {
503                return boost::lexical_cast<std::wstring>(value) + _T("%");
504        }
505        static std::wstring key_prefix() {
506                return _T("average load ");
507        }
508        static std::wstring key_postfix() {
509                return _T("");
510        }
511};
512NSCAPI::nagiosReturn CheckSystem::checkCPU(std::list<std::wstring> arguments, std::wstring &msg, std::wstring &perf) {
513        typedef checkHolders::CheckContainer<checkHolders::MaxMinBounds<checkHolders::NumericBounds<int, cpuload_handler> > > CPULoadContainer;
514
515        if (arguments.empty()) {
516                msg = _T("ERROR: Missing argument exception.");
517                return NSCAPI::returnUNKNOWN;
518        }
519        std::list<CPULoadContainer> list;
520        NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK;
521        bool bNSClient = false;
522        bool bPerfData = true;
523        CPULoadContainer tmpObject;
524
525        tmpObject.data = _T("cpuload");
526
527        MAP_OPTIONS_BEGIN(arguments)
528                MAP_OPTIONS_NUMERIC_ALL(tmpObject, _T(""))
529                MAP_OPTIONS_STR(_T("warn"), tmpObject.warn.max_)
530                MAP_OPTIONS_STR(_T("crit"), tmpObject.crit.max_)
531                MAP_OPTIONS_BOOL_FALSE(IGNORE_PERFDATA, bPerfData)
532                MAP_OPTIONS_STR_AND(_T("time"), tmpObject.data, list.push_back(tmpObject))
533                MAP_OPTIONS_STR_AND(_T("Time"), tmpObject.data, list.push_back(tmpObject))
534                MAP_OPTIONS_SHOWALL(tmpObject)
535                MAP_OPTIONS_BOOL_TRUE(NSCLIENT, bNSClient)
536                MAP_OPTIONS_SECONDARY_BEGIN(_T(":"), p2)
537                        else if (p2.first == _T("Time")) {
538                                tmpObject.data = p__.second;
539                                tmpObject.alias = p2.second;
540                                list.push_back(tmpObject);
541                        }
542        MAP_OPTIONS_MISSING_EX(p2, msg, _T("Unknown argument: "))
543                MAP_OPTIONS_SECONDARY_END()
544                MAP_OPTIONS_FALLBACK_AND(tmpObject.data, list.push_back(tmpObject))
545        MAP_OPTIONS_END()
546
547        for (std::list<CPULoadContainer>::const_iterator it = list.begin(); it != list.end(); ++it) {
548                CPULoadContainer load = (*it);
549                PDHCollector *pObject = pdhThread.getThread();
550                if (!pObject) {
551                        msg = _T("ERROR: PDH Collection thread not running.");
552                        return NSCAPI::returnUNKNOWN;
553                }
554                int value = pObject->getCPUAvrage(load.data + _T("m"));
555                if (value == -1) {
556                        msg = _T("ERROR: Could not get data for ") + load.getAlias() + _T(" perhaps we don't collect data this far back?");
557                        return NSCAPI::returnUNKNOWN;
558                }
559                if (bNSClient) {
560                        if (!msg.empty()) msg += _T("&");
561                        msg += strEx::itos(value);
562                } else {
563                        load.setDefault(tmpObject);
564                        load.perfData = bPerfData;
565                        load.runCheck(value, returnCode, msg, perf);
566                }
567        }
568
569        if (msg.empty())
570                msg = _T("OK CPU Load ok.");
571        else if (!bNSClient)
572                msg = nscapi::plugin_helper::translateReturn(returnCode) + _T(": ") + msg;
573        return returnCode;
574}
575
576NSCAPI::nagiosReturn CheckSystem::checkUpTime(std::list<std::wstring> arguments, std::wstring &msg, std::wstring &perf)
577{
578        typedef checkHolders::CheckContainer<checkHolders::MaxMinBoundsTime> UpTimeContainer;
579
580        if (arguments.empty()) {
581                msg = _T("ERROR: Missing argument exception.");
582                return NSCAPI::returnUNKNOWN;
583        }
584        NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK;
585        bool bNSClient = false;
586        bool bPerfData = true;
587        UpTimeContainer bounds;
588
589        bounds.data = _T("uptime");
590
591        MAP_OPTIONS_BEGIN(arguments)
592                MAP_OPTIONS_NUMERIC_ALL(bounds, _T(""))
593                MAP_OPTIONS_STR(_T("warn"), bounds.warn.min_)
594                MAP_OPTIONS_STR(_T("crit"), bounds.crit.min_)
595                MAP_OPTIONS_BOOL_FALSE(IGNORE_PERFDATA, bPerfData)
596                MAP_OPTIONS_STR(_T("Alias"), bounds.data)
597                MAP_OPTIONS_SHOWALL(bounds)
598                MAP_OPTIONS_BOOL_TRUE(NSCLIENT, bNSClient)
599                MAP_OPTIONS_MISSING(msg, _T("Unknown argument: "))
600                MAP_OPTIONS_END()
601
602
603        PDHCollector *pObject = pdhThread.getThread();
604        if (!pObject) {
605                msg = _T("ERROR: PDH Collection thread not running.");
606                return NSCAPI::returnUNKNOWN;
607        }
608        unsigned long long value = pObject->getUptime();
609        if (value == -1) {
610                msg = _T("ERROR: Could not get value");
611                return NSCAPI::returnUNKNOWN;
612        }
613        if (bNSClient) {
614                msg = strEx::itos(value);
615        } else {
616                value *= 1000;
617                bounds.perfData = bPerfData;
618                bounds.runCheck(value, returnCode, msg, perf);
619        }
620
621        if (msg.empty())
622                msg = _T("OK all counters within bounds.");
623        else if (!bNSClient)
624                msg = nscapi::plugin_helper::translateReturn(returnCode) + _T(": ") + msg;
625        return returnCode;
626}
627
628// @todo state_handler
629
630
631inline int get_state(DWORD state) {
632        if (state == SERVICE_RUNNING)
633                return checkHolders::state_started;
634        else if (state == SERVICE_STOPPED)
635                return checkHolders::state_stopped;
636        else if (state == MY_SERVICE_NOT_FOUND)
637                return checkHolders::state_not_found;
638        return checkHolders::state_none;
639}
640
641/**
642 * Retrieve the service state of one or more services (by name).
643 * Parse a list with a service names and verify that all named services are running.
644 * <pre>
645 * Syntax:
646 * request: checkServiceState <option> [<option> [...]]
647 * Return: <return state>&<service1> : <state1> - <service2> : <state2> - ...
648 * Available options:
649 *              <name>=<state>  Check if a service has a specific state
650 *                      State can be wither started or stopped
651 *              ShowAll                 Show the state of all listed service. If not set only critical services are listed.
652 * Examples:
653 * checkServiceState showAll myService MyService
654 *</pre>
655 *
656 * @param command Command to execute
657 * @param argLen The length of the argument buffer
658 * @param **char_args The argument buffer
659 * @param &msg String to put message in
660 * @param &perf String to put performance data in
661 * @return The status of the command
662 */
663NSCAPI::nagiosReturn CheckSystem::checkServiceState(std::list<std::wstring> arguments, std::wstring &msg, std::wstring &perf)
664{
665        typedef checkHolders::CheckContainer<checkHolders::SimpleBoundsStateBoundsInteger> StateContainer;
666        if (arguments.empty()) {
667                msg = _T("ERROR: Missing argument exception.");
668                return NSCAPI::returnUNKNOWN;
669        }
670        std::list<StateContainer> list;
671        std::set<std::wstring> excludeList;
672        NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK;
673        bool bNSClient = false;
674        StateContainer tmpObject;
675        bool bPerfData = true;
676        bool bAutoStart = false;
677        unsigned int truncate = 0;
678
679        tmpObject.data = _T("service");
680        tmpObject.crit.state = _T("started");
681        //{{
682        MAP_OPTIONS_BEGIN(arguments)
683                MAP_OPTIONS_SHOWALL(tmpObject)
684                MAP_OPTIONS_STR(_T("Alias"), tmpObject.data)
685                MAP_OPTIONS_STR2INT(_T("truncate"), truncate)
686                MAP_OPTIONS_BOOL_FALSE(IGNORE_PERFDATA, bPerfData)
687                MAP_OPTIONS_BOOL_TRUE(NSCLIENT, bNSClient)
688                MAP_OPTIONS_BOOL_TRUE(_T("CheckAll"), bAutoStart)
689                MAP_OPTIONS_INSERT(_T("exclude"), excludeList)
690                //MAP_OPTIONS_SECONDARY_BEGIN(_T(":"), p2)
691                //MAP_OPTIONS_MISSING_EX(p2, msg, _T("Unknown argument: "))
692                //MAP_OPTIONS_SECONDARY_END()
693                else {
694                        tmpObject.data = p__.first;
695                        if (p__.second.empty())
696                                tmpObject.crit.state = _T("started");
697                        else
698                                tmpObject.crit.state = p__.second;
699                        list.push_back(tmpObject);
700                }
701        MAP_OPTIONS_END()
702        //}}
703        if (bAutoStart) {
704                // get a list of all service with startup type Automatic
705                /*
706                ;check_all_services[SERVICE_BOOT_START]=ignored
707                ;check_all_services[SERVICE_SYSTEM_START]=ignored
708                ;check_all_services[SERVICE_AUTO_START]=started
709                ;check_all_services[SERVICE_DEMAND_START]=ignored
710                ;check_all_services[SERVICE_DISABLED]=stopped
711                std::wstring wantedMethod = NSCModuleHelper::getSettingsString(C_SYSTEM_SECTION_TITLE, C_SYSTEM_ENUMPROC_METHOD, C_SYSTEM_ENUMPROC_METHOD_DEFAULT);
712                */
713
714                bool vista = systemInfo::isAboveVista(systemInfo::getOSVersion());
715                std::list<TNtServiceInfo> service_list_automatic = TNtServiceInfo::EnumServices(SERVICE_WIN32,SERVICE_INACTIVE|SERVICE_ACTIVE, vista);
716                for (std::list<TNtServiceInfo>::const_iterator service =service_list_automatic.begin();service!=service_list_automatic.end();++service) {
717                        if (excludeList.find((*service).m_strServiceName) == excludeList.end()) {
718                                tmpObject.data = (*service).m_strServiceName;
719                                std::wstring x = lookups_[(*service).m_dwStartType];
720                                if (x != _T("ignored")) {
721                                        tmpObject.crit.state = x;
722                                        list.push_back(tmpObject);
723                                }
724                        }
725                }
726                tmpObject.crit.state = _T("ignored");
727        }
728        for (std::list<StateContainer>::iterator it = list.begin(); it != list.end(); ++it) {
729                TNtServiceInfo info;
730                if (bNSClient) {
731                        try {
732                                info = TNtServiceInfo::GetService((*it).data.c_str());
733                        } catch (NTServiceException e) {
734                                if (!msg.empty()) msg += _T(" - ");
735                                msg += (*it).data + _T(": Error");
736                                nscapi::plugin_helper::escalteReturnCodeToWARN(returnCode);
737                                continue;
738                        }
739                        if ((*it).crit.state.hasBounds()) {
740                                bool ok = (*it).crit.state.check(get_state(info.m_dwCurrentState));
741                                if (!ok || (*it).showAll()) {
742                                        if (info.m_dwCurrentState == SERVICE_RUNNING) {
743                                                if (!msg.empty()) msg += _T(" - ");
744                                                msg += (*it).data + _T(": Started");
745                                        } else if (info.m_dwCurrentState == SERVICE_STOPPED) {
746                                                if (!msg.empty()) msg += _T(" - ");
747                                                msg += (*it).data + _T(": Stopped");
748                                        } else if (info.m_dwCurrentState == MY_SERVICE_NOT_FOUND) {
749                                                if (!msg.empty()) msg += _T(" - ");
750                                                msg += (*it).data + _T(": Not found");
751                                        } else {
752                                                if (!msg.empty()) msg += _T(" - ");
753                                                msg += (*it).data + _T(": Unknown");
754                                        }
755                                        if (!ok)
756                                                nscapi::plugin_helper::escalteReturnCodeToCRIT(returnCode);
757                                }
758                        }
759                } else {
760                        try {
761                                info = TNtServiceInfo::GetService((*it).data.c_str());
762                        } catch (NTServiceException e) {
763                                NSC_LOG_ERROR_STD(e.getError());
764                                msg = e.getError();
765                                return NSCAPI::returnUNKNOWN;
766                        }
767                        checkHolders::state_type value;
768                        if (info.m_dwCurrentState == SERVICE_RUNNING)
769                                value = checkHolders::state_started;
770                        else if (info.m_dwCurrentState == SERVICE_STOPPED)
771                                value = checkHolders::state_stopped;
772                        else if (info.m_dwCurrentState == MY_SERVICE_NOT_FOUND)
773                                value = checkHolders::state_not_found;
774                        else {
775                                NSC_LOG_MESSAGE(_T("Service had no (valid) state: ") + (*it).data + _T(" (") + strEx::itos(info.m_dwCurrentState) + _T(")"));
776                                value = checkHolders::state_none;
777                        }
778                        unsigned int x = returnCode;
779                        (*it).perfData = bPerfData;
780                        (*it).setDefault(tmpObject);
781                        (*it).runCheck(value, returnCode, msg, perf);
782//                      NSC_LOG_MESSAGE(_T("Service: ") + (*it).data + _T(" (") + strEx::itos(info.m_dwCurrentState) + _T(":") + strEx::itos((*it).warn.state.value_) + _T(":") + strEx::itos((*it).crit.state.value_) + _T(") -- (") + strEx::itos(returnCode) + _T(":") + strEx::itos(x) + _T(")"));
783                }
784        }
785        if ((truncate > 0) && (msg.length() > (truncate-4)))
786                msg = msg.substr(0, truncate-4) + _T("...");
787        if (msg.empty() && returnCode == NSCAPI::returnOK)
788                msg = _T("OK: All services are in their appropriate state.");
789        else if (msg.empty())
790                msg = nscapi::plugin_helper::translateReturn(returnCode) + _T(": Whooha this is odd.");
791        else if (!bNSClient)
792                msg = nscapi::plugin_helper::translateReturn(returnCode) + _T(": ") + msg;
793        return returnCode;
794}
795
796/**
797 * Check available memory and return various check results
798 * Example: checkMem showAll maxWarn=50 maxCrit=75
799 *
800 * @param command Command to execute
801 * @param argLen The length of the argument buffer
802 * @param **char_args The argument buffer
803 * @param &msg String to put message in
804 * @param &perf String to put performance data in
805 * @return The status of the command
806 */
807NSCAPI::nagiosReturn CheckSystem::checkMem(std::list<std::wstring> arguments, std::wstring &msg, std::wstring &perf)
808{
809        typedef checkHolders::CheckContainer<checkHolders::MaxMinBounds<checkHolders::NumericPercentageBounds<checkHolders::PercentageValueType<unsigned __int64, unsigned __int64>, checkHolders::disk_size_handler<unsigned __int64> > > > MemoryContainer;
810        if (arguments.empty()) {
811                msg = _T("ERROR: Missing argument exception.");
812                return NSCAPI::returnUNKNOWN;
813        }
814        std::list<MemoryContainer> list;
815        NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK;
816        bool bShowAll = false;
817        bool bPerfData = true;
818        bool bNSClient = false;
819        MemoryContainer tmpObject;
820
821        MAP_OPTIONS_BEGIN(arguments)
822                MAP_OPTIONS_SHOWALL(tmpObject)
823                MAP_OPTIONS_STR_AND(_T("type"), tmpObject.data, list.push_back(tmpObject))
824                MAP_OPTIONS_STR_AND(_T("Type"), tmpObject.data, list.push_back(tmpObject))
825                MAP_OPTIONS_SECONDARY_BEGIN(_T(":"), p2)
826                MAP_OPTIONS_SECONDARY_STR_AND(p2,_T("type"), tmpObject.data, tmpObject.alias, list.push_back(tmpObject))
827                        MAP_OPTIONS_MISSING_EX(p2, msg, _T("Unknown argument: "))
828                        MAP_OPTIONS_SECONDARY_END()
829                MAP_OPTIONS_BOOL_FALSE(IGNORE_PERFDATA, bPerfData)
830                MAP_OPTIONS_BOOL_TRUE(NSCLIENT, bNSClient)
831                MAP_OPTIONS_DISK_ALL(tmpObject, _T(""), _T("Free"), _T("Used"))
832                MAP_OPTIONS_STR(_T("Alias"), tmpObject.data)
833                MAP_OPTIONS_SHOWALL(tmpObject)
834                MAP_OPTIONS_MISSING(msg, _T("Unknown argument: "))
835                MAP_OPTIONS_END()
836
837        if (bNSClient) {
838                tmpObject.data = _T("paged");
839                list.push_back(tmpObject);
840        }
841
842        checkHolders::PercentageValueType<unsigned long long, unsigned long long> dataPaged;
843        CheckMemory::memData data;
844        bool firstPaged = true;
845        bool firstMem = true;
846        for (std::list<MemoryContainer>::const_iterator pit = list.begin(); pit != list.end(); ++pit) {
847                MemoryContainer check = (*pit);
848                check.setDefault(tmpObject);
849                checkHolders::PercentageValueType<unsigned long long, unsigned long long> value;
850                if (firstPaged && (check.data == _T("paged"))) {
851                        firstPaged = false;
852                        PDHCollector *pObject = pdhThread.getThread();
853                        if (!pObject) {
854                                msg = _T("ERROR: PDH Collection thread not running.");
855                                return NSCAPI::returnUNKNOWN;
856                        }
857                        dataPaged.value = pObject->getMemCommit();
858                        if (dataPaged.value == -1) {
859                                msg = _T("ERROR: Failed to get PDH value.");
860                                return NSCAPI::returnUNKNOWN;
861                        }
862                        dataPaged.total = pObject->getMemCommitLimit();
863                        if (dataPaged.total == -1) {
864                                msg = _T("ERROR: Failed to get PDH value.");
865                                return NSCAPI::returnUNKNOWN;
866                        }
867                } else if (firstMem) {
868                        try {
869                                data = memoryChecker.getMemoryStatus();
870                        } catch (CheckMemoryException e) {
871                                msg = e.getError();
872                                return NSCAPI::returnCRIT;
873                        }
874                }
875
876                if (check.data == _T("page")) {
877                        value.value = data.pageFile.total-data.pageFile.avail; // mem.dwTotalPageFile-mem.dwAvailPageFile;
878                        value.total = data.pageFile.total; //mem.dwTotalPageFile;
879                        if (check.alias.empty())
880                                check.alias = _T("page file");
881                } else if (check.data == _T("physical")) {
882                        value.value = data.phys.total-data.phys.avail; //mem.dwTotalPhys-mem.dwAvailPhys;
883                        value.total = data.phys.total; //mem.dwTotalPhys;
884                        if (check.alias.empty())
885                                check.alias = _T("physical memory");
886                } else if (check.data == _T("virtual")) {
887                        value.value = data.virtualMem.total-data.virtualMem.avail;//mem.dwTotalVirtual-mem.dwAvailVirtual;
888                        value.total = data.virtualMem.total;//mem.dwTotalVirtual;
889                        if (check.alias.empty())
890                                check.alias = _T("virtual memory");
891                } else  if (check.data == _T("paged")) {
892                        value.value = dataPaged.value;
893                        value.total = dataPaged.total;
894                        if (check.alias.empty())
895                                check.alias = _T("paged bytes");
896                } else {
897                        msg = check.data + _T(" is not a known check...");
898                        return NSCAPI::returnCRIT;
899                }
900                if (bNSClient) {
901                        msg = strEx::itos(value.total) + _T("&") + strEx::itos(value.value);
902                        return NSCAPI::returnOK;
903                } else {
904                        check.perfData = bPerfData;
905                        check.runCheck(value, returnCode, msg, perf);
906                }
907        }
908
909        if (msg.empty())
910                msg = _T("OK memory within bounds.");
911        else
912                msg = nscapi::plugin_helper::translateReturn(returnCode) + _T(": ") + msg;
913        return returnCode;
914}
915typedef struct NSPROCDATA__ {
916        unsigned int count;
917        unsigned int hung_count;
918        CEnumProcess::CProcessEntry entry;
919        std::wstring key;
920
921        NSPROCDATA__() : count(0), hung_count(0) {}
922        NSPROCDATA__(const NSPROCDATA__ &other) : count(other.count), hung_count(other.hung_count), entry(other.entry), key(other.key) {}
923} NSPROCDATA;
924typedef std::map<std::wstring,NSPROCDATA> NSPROCLST;
925
926class NSC_error : public CEnumProcess::error_reporter {
927        void report_error(std::wstring error) {
928                NSC_LOG_ERROR(error);
929        }
930        void report_warning(std::wstring error) {
931                NSC_LOG_MESSAGE(error);
932        }
933        void report_debug(std::wstring error) {
934                NSC_DEBUG_MSG_STD(_T("PROC::: ") + error);
935        }
936        void report_debug_enter(std::wstring error) {
937                NSC_DEBUG_MSG_STD(_T("PROC>>> ") + error);
938        }
939        void report_debug_exit(std::wstring error) {
940                NSC_DEBUG_MSG_STD(_T("PROC<<<") + error);
941        }
942};
943
944/**
945* Get a hash_map with all running processes.
946* @return a hash_map with all running processes
947*/
948NSPROCLST GetProcessList(bool getCmdLines, bool use16Bit)
949{
950        NSPROCLST ret;
951        CEnumProcess enumeration;
952        if (!enumeration.has_PSAPI()) {
953                NSC_LOG_ERROR_STD(_T("Failed to enumerat processes"));
954                NSC_LOG_ERROR_STD(_T("PSAPI method not availabletry installing \"Platform SDK Redistributable: PSAPI for Windows NT\" from Microsoft."));
955                NSC_LOG_ERROR_STD(_T("Try this URL: http://www.microsoft.com/downloads/details.aspx?FamilyID=3d1fbaed-d122-45cf-9d46-1cae384097ac"));
956                throw CEnumProcess::process_enumeration_exception(_T("PSAPI not avalible, please see eror log for details."));
957        }
958        NSC_error err;
959        CEnumProcess::process_list list = enumeration.enumerate_processes(getCmdLines, use16Bit, &err);
960        for (CEnumProcess::process_list::const_iterator entry = list.begin(); entry != list.end(); ++entry) {
961                std::wstring key;
962                if (getCmdLines && !(*entry).command_line.empty())
963                        key = (*entry).command_line;
964                else
965                        key = boost::to_lower_copy((*entry).filename);
966                NSPROCLST::iterator it = ret.find(key);
967                if (it == ret.end()) {
968                        ret[key].entry = (*entry);
969                        ret[key].count = 1;
970                        ret[key].hung_count = (*entry).hung?1:0;
971                        ret[key].key = key;
972                } else {
973                        if ((*entry).hung)
974                                (*it).second.hung_count++;
975                        (*it).second.count++;
976                }
977        }
978        return ret;
979}
980
981
982
983struct process_count_result {
984        unsigned long running;
985        unsigned long hung;
986        process_count_result() : running(0), hung(0) {}
987
988        std::wstring format_value(std::wstring tag, unsigned long count) {
989                if (count > 1)
990                        return tag + _T("(") + strEx::itos(count) +_T(")");
991                if (count == 1)
992                        return tag;
993                return _T("");
994        }
995        std::wstring to_wstring() {
996                if (running > 0 && hung > 0)
997                        return format_value(_T("running"), running) + _T(", ") + format_value(_T("hung"), hung);
998                if (running > 0)
999                        return format_value(_T("running"), running);
1000                if (hung > 0)
1001                        return format_value(_T("hung"), hung);
1002                return _T("stopped");
1003        }
1004        std::wstring to_wstring_short() {
1005                if (running > 0 && hung > 0)
1006                        return _T("running, hung");
1007                if (running > 0)
1008                        return _T("running");
1009                if (hung > 0)
1010                        return _T("hung");
1011                return _T("stopped");
1012        }
1013
1014};
1015
1016class ProcessBound {
1017public:
1018        checkHolders::ExactBounds<checkHolders::NumericBounds<unsigned long, checkHolders::int_handler> > running;
1019        checkHolders::ExactBounds<checkHolders::NumericBounds<unsigned long, checkHolders::int_handler> > hung;
1020        typedef checkHolders::NumericBounds<unsigned long, checkHolders::int_handler> THolder;
1021
1022        typedef ProcessBound TMyType;
1023        typedef process_count_result TValueType;
1024
1025        ProcessBound() {}
1026        ProcessBound(const ProcessBound &other) {
1027                running = other.running;
1028                hung = other.hung;
1029        }
1030
1031        void reset() {
1032                running.reset();
1033                hung.reset();
1034        }
1035        bool hasBounds() {
1036                return running.hasBounds() || hung.hasBounds();
1037        }
1038        static std::wstring toStringLong(TValueType &value) {
1039                return value.to_wstring();
1040        }
1041        static std::wstring toStringShort(TValueType &value) {
1042                return value.to_wstring_short();
1043        }
1044        std::wstring gatherPerfData(std::wstring alias, TValueType &value, TMyType &warn, TMyType &crit) {
1045                if (hung.hasBounds())
1046                        return hung.gatherPerfData(alias, value.hung, warn.hung, crit.hung);
1047                return running.gatherPerfData(alias, value.running, warn.running, crit.running);
1048        }
1049        std::wstring gatherPerfData(std::wstring alias, TValueType &value) {
1050                THolder tmp;
1051                if (hung.hasBounds())
1052                        return tmp.gatherPerfData(alias, value.hung);
1053                return tmp.gatherPerfData(alias, value.running);
1054        }
1055        bool check(TValueType &value, std::wstring lable, std::wstring &message, checkHolders::ResultType type) {
1056                if (hung.hasBounds()) {
1057                        return hung.check_preformatted(value.hung, value.to_wstring(), lable, message, type);
1058                } else {
1059                        return running.check_preformatted(value.running, value.to_wstring(), lable, message, type);
1060                }
1061                return false;
1062        }
1063
1064};
1065/**
1066 * Check process state and return result
1067 *
1068 * @param command Command to execute
1069 * @param argLen The length of the argument buffer
1070 * @param **char_args The argument buffer
1071 * @param &msg String to put message in
1072 * @param &perf String to put performance data in
1073 * @return The status of the command
1074 */
1075NSCAPI::nagiosReturn CheckSystem::checkProcState(std::list<std::wstring> arguments, std::wstring &msg, std::wstring &perf)
1076{
1077        typedef checkHolders::CheckContainer<ProcessBound> StateContainer;
1078       
1079//      typedef checkHolders::CheckContainer<checkHolders::ExactBoundsState> StateContainer2;
1080
1081        if (arguments.empty()) {
1082                msg = _T("ERROR: Missing argument exception.");
1083                return NSCAPI::returnUNKNOWN;
1084        }
1085        std::list<StateContainer> list;
1086        NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK;
1087        bool bNSClient = false;
1088        StateContainer tmpObject;
1089        bool bPerfData = true;
1090        bool use16bit = false;
1091        bool useCmdLine = false;
1092        bool ignoreState = false;
1093        typedef enum {
1094                match_string, match_substring, match_regexp
1095        } match_type;
1096        match_type match = match_string;
1097
1098       
1099
1100        //tmpObject.data = _T("uptime");
1101        //tmpObject.crit.min = 1;
1102
1103        MAP_OPTIONS_BEGIN(arguments)
1104                //MAP_OPTIONS_NUMERIC_ALL(tmpObject, _T("Count"))
1105                MAP_OPTIONS_EXACT_NUMERIC_ALL_EX(tmpObject, _T("Count"), running)
1106                MAP_OPTIONS_EXACT_NUMERIC_LEGACY_EX(tmpObject, _T("Count"), running)
1107                MAP_OPTIONS_EXACT_NUMERIC_ALL_EX(tmpObject, _T("HungCount"), hung)
1108                MAP_OPTIONS_EXACT_NUMERIC_LEGACY_EX(tmpObject, _T("HungCount"), hung)
1109                MAP_OPTIONS_STR(_T("Alias"), tmpObject.alias)
1110                MAP_OPTIONS_SHOWALL(tmpObject)
1111                MAP_OPTIONS_BOOL_FALSE(IGNORE_PERFDATA, bPerfData)
1112                MAP_OPTIONS_BOOL_TRUE(NSCLIENT, bNSClient)
1113                MAP_OPTIONS_BOOL_TRUE(_T("ignore-state"), ignoreState)
1114                MAP_OPTIONS_BOOL_TRUE(_T("cmdLine"), useCmdLine)
1115                MAP_OPTIONS_BOOL_TRUE(_T("16bit"), use16bit)
1116                MAP_OPTIONS_MODE(_T("match"), _T("string"), match,  match_string)
1117                MAP_OPTIONS_MODE(_T("match"), _T("regexp"), match,  match_regexp)
1118                MAP_OPTIONS_MODE(_T("match"), _T("substr"), match,  match_substring)
1119                MAP_OPTIONS_MODE(_T("match"), _T("substring"), match,  match_substring)
1120                MAP_OPTIONS_SECONDARY_BEGIN(_T(":"), p2)
1121        else if (p2.first == _T("Proc")) {
1122                        tmpObject.data = p__.second;
1123                        tmpObject.alias = p2.second;
1124                        list.push_back(tmpObject);
1125                }
1126        MAP_OPTIONS_MISSING_EX(p2, msg, _T("Unknown argument: "))
1127                MAP_OPTIONS_SECONDARY_END()
1128                else {
1129                        tmpObject.data = p__.first;
1130                        if (p__.second.empty()) {
1131                                if (!tmpObject.crit.running.hasBounds() && !tmpObject.warn.running.hasBounds())
1132                                        tmpObject.crit.running.min = _T("1");
1133                        } else if (p__.second == _T("started")) {
1134                                if (!tmpObject.crit.running.hasBounds() && !tmpObject.warn.running.hasBounds())
1135                                        tmpObject.crit.running.min = _T("1");
1136                        } else if (p__.second == _T("stopped")) {
1137                                if (!tmpObject.crit.running.hasBounds() && !tmpObject.warn.running.hasBounds())
1138                                        tmpObject.crit.running.max = _T("0");
1139                        } else if (p__.second == _T("hung")) {
1140                                if (!tmpObject.crit.hung.hasBounds() && !tmpObject.warn.hung.hasBounds())
1141                                        tmpObject.crit.hung.max = _T("1");
1142                        }
1143                        list.push_back(tmpObject);
1144                        tmpObject.reset();
1145                }
1146        MAP_OPTIONS_END()
1147
1148        NSPROCLST runningProcs;
1149        try {
1150                runningProcs = GetProcessList(useCmdLine, use16bit);
1151        } catch (CEnumProcess::process_enumeration_exception &e) {
1152                NSC_LOG_ERROR_STD(_T("ERROR: ") + e.what());
1153                msg = static_cast<std::wstring>(_T("ERROR: ")) + e.what();
1154                return NSCAPI::returnUNKNOWN;
1155        } catch (...) {
1156                NSC_LOG_ERROR_STD(_T("Unhandled error when processing command"));
1157                msg = _T("Unhandled error when processing command");
1158                return NSCAPI::returnUNKNOWN;
1159        }
1160
1161        for (std::list<StateContainer>::iterator it = list.begin(); it != list.end(); ++it) {
1162                NSPROCLST::iterator proc;
1163                if (match == match_string) {
1164                        proc = runningProcs.find((*it).data);
1165                } else if (match == match_substring) {
1166                        for (proc=runningProcs.begin();proc!=runningProcs.end();++proc) {
1167                                if ((*proc).first.find((*it).data) != std::wstring::npos)
1168                                        break;
1169                        }
1170                } else if (match == match_regexp) {
1171                        try {
1172                                boost::wregex filter((*it).data,boost::regex::icase);
1173                                for (proc=runningProcs.begin();proc!=runningProcs.end();++proc) {
1174                                        std::wstring value = (*proc).first;
1175                                        if (boost::regex_match(value, filter))
1176                                                break;
1177                                }
1178                        } catch (const boost::bad_expression e) {
1179                                NSC_LOG_ERROR_STD(_T("Failed to compile regular expression: ") + (*proc).first);
1180                                msg = _T("Failed to compile regular expression: ") + (*proc).first;
1181                                return NSCAPI::returnUNKNOWN;
1182                        } catch (...) {
1183                                NSC_LOG_ERROR_STD(_T("Failed to compile regular expression: ") + (*proc).first);
1184                                msg = _T("Failed to compile regular expression: ") + (*proc).first;
1185                                return NSCAPI::returnUNKNOWN;
1186                        }
1187                } else {
1188                        NSC_LOG_ERROR_STD(_T("Unsupported mode for: ") + (*proc).first);
1189                        msg = _T("Unsupported mode for: ") + (*proc).first;
1190                        return NSCAPI::returnUNKNOWN;
1191                }
1192                bool bFound = (proc != runningProcs.end());
1193                if (bNSClient) {
1194                        if (bFound && (*it).showAll()) {
1195                                if (!msg.empty()) msg += _T(" - ");
1196                                msg += (*proc).first + _T(": Running");
1197                        } else if (bFound) {
1198                        } else {
1199                                if (!msg.empty()) msg += _T(" - ");
1200                                msg += (*it).data + _T(": not running");
1201                                nscapi::plugin_helper::escalteReturnCodeToCRIT(returnCode);
1202                        }
1203                } else {
1204                        process_count_result value;
1205                        if (bFound) {
1206                                value.hung = (*proc).second.hung_count;
1207                                value.running = (*proc).second.count;
1208                        } else {
1209                                value.hung = 0;
1210                                value.running = 0;
1211//                              if (ignoreState)
1212//                                      value.state = checkHolders::state_stopped | checkHolders::state_started | checkHolders::state_hung;
1213//                              else
1214//                              value.state = checkHolders::state_stopped;
1215                        }
1216                        if (bFound && (*it).alias.empty()) {
1217                                (*it).alias = (*proc).first;
1218                        }
1219                        (*it).perfData = bPerfData;
1220                        (*it).runCheck(value, returnCode, msg, perf);
1221                }
1222
1223        }
1224        if (msg.empty())
1225                msg = _T("OK: All processes are running.");
1226        else if (!bNSClient)
1227                msg = nscapi::plugin_helper::translateReturn(returnCode) + _T(": ") + msg;
1228        return returnCode;
1229}
1230
1231template<class T>
1232class PerfDataContainer : public checkHolders::CheckContainer<T> {
1233private:
1234        typedef PDHCollectors::StaticPDHCounterListener<double, PDH_FMT_DOUBLE> counter_type;
1235        typedef boost::shared_ptr<counter_type> ptr_lsnr_type;
1236        ptr_lsnr_type cDouble;
1237public:
1238
1239        PerfDataContainer() : CheckContainer<T>() {}
1240
1241        PerfDataContainer(const PerfDataContainer &other) : CheckContainer<T>(other), cDouble(other.cDouble) {}
1242        const PerfDataContainer& operator =(const PerfDataContainer &other) {
1243                *((CheckContainer<T>*)this) = other;
1244                cDouble = other.cDouble;
1245                return *this;
1246        }
1247        ptr_lsnr_type get_listener() {
1248                if (!cDouble)
1249                        cDouble = ptr_lsnr_type(new counter_type());
1250                return cDouble;
1251        }
1252};
1253
1254/**
1255 * Check a counter and return the value
1256 *
1257 * @param command Command to execute
1258 * @param argLen The length of the argument buffer
1259 * @param **char_args The argument buffer
1260 * @param &msg String to put message in
1261 * @param &perf String to put performance data in
1262 * @return The status of the command
1263 *
1264 * @todo add parsing support for NRPE
1265 */
1266NSCAPI::nagiosReturn CheckSystem::checkCounter(std::list<std::wstring> arguments, std::wstring &msg, std::wstring &perf)
1267{
1268        typedef PerfDataContainer<checkHolders::MaxMinBoundsDouble> CounterContainer;
1269
1270        if (arguments.empty()) {
1271                msg = _T("ERROR: Missing argument exception.");
1272                return NSCAPI::returnUNKNOWN;
1273        }
1274        std::list<CounterContainer> counters;
1275        NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK;
1276        bool bNSClient = false;
1277        bool bPerfData = true;
1278        /* average maax */
1279        bool bCheckAverages = true;
1280        std::wstring invalidStatus = _T("UNKNOWN");
1281        unsigned int averageDelay = 1000;
1282        CounterContainer tmpObject;
1283        bool bExpandIndex = false;
1284        bool bForceReload = false;
1285        std::wstring extra_format;
1286
1287        MAP_OPTIONS_BEGIN(arguments)
1288                MAP_OPTIONS_STR(_T("InvalidStatus"), invalidStatus)
1289                MAP_OPTIONS_STR_AND(_T("Counter"), tmpObject.data, counters.push_back(tmpObject))
1290                MAP_OPTIONS_STR(_T("MaxWarn"), tmpObject.warn.max_)
1291                MAP_OPTIONS_STR(_T("MinWarn"), tmpObject.warn.min_)
1292                MAP_OPTIONS_STR(_T("MaxCrit"), tmpObject.crit.max_)
1293                MAP_OPTIONS_STR(_T("MinCrit"), tmpObject.crit.min_)
1294                MAP_OPTIONS_BOOL_FALSE(IGNORE_PERFDATA, bPerfData)
1295                MAP_OPTIONS_STR(_T("Alias"), tmpObject.data)
1296                MAP_OPTIONS_STR(_T("format"), extra_format)
1297                MAP_OPTIONS_SHOWALL(tmpObject)
1298                MAP_OPTIONS_BOOL_EX(_T("Averages"), bCheckAverages, _T("true"), _T("false"))
1299                MAP_OPTIONS_BOOL_TRUE(NSCLIENT, bNSClient)
1300                MAP_OPTIONS_BOOL_TRUE(_T("index"), bExpandIndex)
1301                MAP_OPTIONS_BOOL_TRUE(_T("reload"), bForceReload)
1302                MAP_OPTIONS_FIRST_CHAR('\\', tmpObject.data, counters.push_back(tmpObject))
1303                MAP_OPTIONS_SECONDARY_BEGIN(_T(":"), p2)
1304        else if (p2.first == _T("Counter")) {
1305                tmpObject.data = p__.second;
1306                                tmpObject.alias = p2.second;
1307                                counters.push_back(tmpObject);
1308                        }
1309        MAP_OPTIONS_MISSING_EX(p2, msg, _T("Unknown argument: "))
1310                MAP_OPTIONS_SECONDARY_END()
1311                MAP_OPTIONS_FALLBACK_AND(tmpObject.data, counters.push_back(tmpObject))
1312        MAP_OPTIONS_END()
1313
1314        if (counters.empty()) {
1315                msg = _T("No counters specified");
1316                return NSCAPI::returnUNKNOWN;
1317        }
1318        PDH::PDHQuery pdh;
1319
1320        bool has_counter = false;
1321        BOOST_FOREACH(CounterContainer &counter, counters) {
1322                try {
1323                        if (counter.data.find('\\') == std::wstring::npos) {
1324                                /*
1325                                value = pObject->get_double(counter.data);
1326                                if (value == -1) {
1327                                        msg = _T("ERROR: Failed to get counter value: ") + counter.data;
1328                                        return NSCAPI::returnUNKNOWN;
1329                                }
1330                                */
1331                        } else {
1332                                std::wstring tstr;
1333                                if (bExpandIndex) {
1334                                        PDH::PDHResolver::expand_index(counter.data);
1335                                }
1336                                if (!PDH::PDHResolver::validate(counter.data, tstr, bForceReload)) {
1337                                        NSC_LOG_ERROR_STD(_T("ERROR: Counter not found: ") + counter.data + _T(": ") + tstr);
1338                                        if (bNSClient) {
1339                                                NSC_LOG_ERROR_STD(_T("ERROR: Counter not found: ") + counter.data + _T(": ") + tstr);
1340                                                //msg = _T("0");
1341                                        } else {
1342                                                msg = _T("CRIT: Counter not found: ") + counter.data + _T(": ") + tstr;
1343                                                return NSCAPI::returnCRIT;
1344                                        }
1345                                }
1346                                if (!extra_format.empty()) {
1347                                        boost::char_separator<wchar_t> sep(_T(","));
1348
1349                                        boost::tokenizer< boost::char_separator<wchar_t>, std::wstring::const_iterator, std::wstring > tokens(extra_format, sep);
1350                                        DWORD flags = 0;
1351                                        BOOST_FOREACH(std::wstring t, tokens) {
1352                                                if (extra_format == _T("nocap100"))
1353                                                        flags |= PDH_FMT_NOCAP100;
1354                                                else if (extra_format == _T("1000"))
1355                                                        flags |= PDH_FMT_1000;
1356                                                else if (extra_format == _T("noscale"))
1357                                                        flags |= PDH_FMT_NOSCALE;
1358                                                else {
1359                                                        NSC_LOG_ERROR_STD(_T("Unsupported extrta format: ") + extra_format);
1360                                                }
1361                                        }
1362                                        counter.get_listener()->set_extra_format(flags);
1363                                }
1364                                pdh.addCounter(counter.data, counter.get_listener());
1365                                has_counter = true;
1366                        }
1367                } catch (const PDH::PDHException e) {
1368                        NSC_LOG_ERROR_STD(_T("ERROR: ") + e.getError() + _T(" (") + counter.getAlias() + _T("|") + counter.data + _T(")"));
1369                        if (bNSClient)
1370                                msg = _T("0");
1371                        else
1372                                msg = static_cast<std::wstring>(_T("ERROR: ")) + e.getError()+ _T(" (") + counter.getAlias() + _T("|") + counter.data + _T(")");
1373                        return NSCAPI::returnUNKNOWN;
1374                }
1375        }
1376        if (has_counter) {
1377                try {
1378                        pdh.open();
1379                        if (bCheckAverages) {
1380                                pdh.collect();
1381                                Sleep(1000);
1382                        }
1383                        pdh.gatherData();
1384                        pdh.close();
1385                } catch (const PDH::PDHException e) {
1386                        NSC_LOG_ERROR_STD(_T("ERROR: ") + e.getError());
1387                        if (bNSClient)
1388                                msg = _T("0");
1389                        else
1390                                msg = _T("ERROR: ") + e.getError();
1391                        return NSCAPI::returnUNKNOWN;
1392                }
1393        }
1394        BOOST_FOREACH(CounterContainer &counter, counters) {
1395                try {
1396                        double value = 0;
1397                        if (counter.data.find('\\') == std::wstring::npos) {
1398                                PDHCollector *pObject = pdhThread.getThread();
1399                                if (!pObject) {
1400                                        msg = _T("ERROR: PDH Collection thread not running.");
1401                                        return NSCAPI::returnUNKNOWN;
1402                                }
1403                                value = pObject->get_double(counter.data);
1404                                if (value == -1) {
1405                                        msg = _T("ERROR: Failed to get counter value: ") + counter.data;
1406                                        return NSCAPI::returnUNKNOWN;
1407                                }
1408                        } else {
1409                                value = counter.get_listener()->getValue();
1410                        }
1411
1412                        if (bNSClient) {
1413                                if (!msg.empty())
1414                                        msg += _T(",");
1415                                msg += strEx::itos(static_cast<float>(value));
1416                        } else {
1417                                counter.perfData = bPerfData;
1418                                counter.setDefault(tmpObject);
1419                                counter.runCheck(value, returnCode, msg, perf);
1420                        }
1421                } catch (const PDH::PDHException e) {
1422                        NSC_LOG_ERROR_STD(_T("ERROR: ") + e.getError() + _T(" (") + counter.getAlias() + _T("|") + counter.data + _T(")"));
1423                        if (bNSClient)
1424                                msg = _T("0");
1425                        else
1426                                msg = static_cast<std::wstring>(_T("ERROR: ")) + e.getError()+ _T(" (") + counter.getAlias() + _T("|") + counter.data + _T(")");
1427                        return NSCAPI::returnUNKNOWN;
1428                }
1429        }
1430
1431        if (msg.empty() && !bNSClient)
1432                msg = _T("OK all counters within bounds.");
1433        else if (msg.empty()) {
1434                NSC_LOG_ERROR_STD(_T("No value found returning 0?"));
1435                msg = _T("0");
1436        }else if (!bNSClient)
1437                msg = nscapi::plugin_helper::translateReturn(returnCode) + _T(": ") + msg;
1438        return returnCode;
1439}
1440
1441
1442
1443/**
1444 * List all instances for a given counter.
1445 *
1446 * @param command Command to execute
1447 * @param argLen The length of the argument buffer
1448 * @param **char_args The argument buffer
1449 * @param &msg String to put message in
1450 * @param &perf String to put performance data in
1451 * @return The status of the command
1452 *
1453 * @todo add parsing support for NRPE
1454 */
1455NSCAPI::nagiosReturn CheckSystem::listCounterInstances(std::list<std::wstring> arguments, std::wstring &msg, std::wstring &perf)
1456{
1457        typedef checkHolders::CheckContainer<checkHolders::MaxMinBoundsDouble> CounterContainer;
1458
1459        if (arguments.empty()) {
1460                msg = _T("ERROR: Missing argument exception.");
1461                return NSCAPI::returnUNKNOWN;
1462        }
1463
1464        std::wstring counter;
1465        BOOST_FOREACH(std::wstring s, arguments) { counter+= s + _T(" "); }
1466        try {
1467                PDH::Enumerations::pdh_object_details obj = PDH::Enumerations::EnumObjectInstances(counter);
1468                for (PDH::Enumerations::pdh_object_details::list::const_iterator it = obj.instances.begin(); it!=obj.instances.end();++it) {
1469                        if (!msg.empty())
1470                                msg += _T(", ");
1471                        msg += (*it);
1472                }
1473                if (msg.empty()) {
1474                        msg = _T("ERROR: No instances found");
1475                        return NSCAPI::returnUNKNOWN;
1476                }
1477        } catch (const PDH::PDHException e) {
1478                msg = _T("ERROR: Failed to enumerate counter instances: " + e.getError());
1479                return NSCAPI::returnUNKNOWN;
1480        } catch (...) {
1481                msg = _T("ERROR: Failed to enumerate counter instances: <UNKNOWN EXCEPTION>");
1482                return NSCAPI::returnUNKNOWN;
1483        }
1484        return NSCAPI::returnOK;
1485}
1486
1487//////////////////////////////////////////////////////////////////////////
1488//////////////////////////////////////////////////////////////////////////
1489
1490struct regkey_info {
1491
1492        std::wstring error;
1493
1494        static regkey_info get(__int64 now, std::wstring path) {
1495                return regkey_info(now, path);
1496        }
1497
1498        regkey_info()
1499                : ullLastWriteTime(0)
1500                , iType(0)
1501                , ullNow(0)
1502                , uiExists(0)
1503                , ullChildCount(0)
1504        {}
1505        regkey_info(__int64 now, std::wstring path)
1506                : path(path)
1507                , ullLastWriteTime(0)
1508                , iType(0)
1509                , ullNow(now)
1510                , uiExists(0)
1511                , ullChildCount(0)
1512        {
1513                std::wstring key;
1514                try {
1515                        std::wcout << _T("opening: ") << path << std::endl;
1516                        std::wstring::size_type pos = path.find_first_of(L'\\');
1517                        if (pos != std::wstring::npos)  {
1518                                key = path.substr(0, pos);
1519                                path = path.substr(pos+1);
1520                                std::wcout << key << _T(":") << path << std::endl;
1521                                simple_registry::registry_key rkey(simple_registry::parseHKEY(key), path);
1522                                info = rkey.get_info();
1523                                uiExists = 1;
1524                        } else {
1525                                error = _T("Failed to parse key");
1526                        }
1527                } catch (simple_registry::registry_exception &e) {
1528                        try {
1529                                std::wstring::size_type pos = path.find_last_of(L'\\');
1530                                if (pos != std::wstring::npos)  {
1531                                        std::wstring item = path.substr(pos+1);
1532                                        path = path.substr(0, pos);
1533                                        std::wcout << key << _T(":") << path << _T(".") << item << std::endl;
1534                                        simple_registry::registry_key rkey(simple_registry::parseHKEY(key), path);
1535                                        info = rkey.get_info(item);
1536                                        uiExists = 1;
1537                                } else {
1538                                        error = _T("Failed to parse key");
1539                                }
1540                        } catch (simple_registry::registry_exception &e) {
1541                                //error = e.what();
1542                        }
1543                } catch (...) {
1544                        error = _T("Unknown exception");
1545                }
1546
1547                //HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\MaxSize
1548
1549                // TODO get key info here!
1550                //ullLastWriteTime = ((info.ftLastWriteTime.dwHighDateTime * ((unsigned long long)MAXDWORD+1)) + (unsigned long long)info.ftLastWriteTime.dwLowDateTime);
1551        };
1552
1553        unsigned long long ullSize;
1554        __int64 ullLastWriteTime;
1555        __int64 ullNow;
1556        std::wstring filename;
1557        std::wstring path;
1558        unsigned long ullChildCount;
1559        unsigned long uiExists;
1560        unsigned int iType;
1561        simple_registry::registry_key::reg_info info;
1562
1563        static const __int64 MSECS_TO_100NS = 10000;
1564
1565        __int64 get_written() {
1566                return (ullNow-ullLastWriteTime)/MSECS_TO_100NS;
1567        }
1568        std::wstring render(std::wstring syntax) {
1569                strEx::replace(syntax, _T("%path%"), path);
1570                strEx::replace(syntax, _T("%key%"), filename);
1571                strEx::replace(syntax, _T("%write%"), strEx::format_filetime(ullLastWriteTime, DATE_FORMAT));
1572                strEx::replace(syntax, _T("%write-raw%"), strEx::itos(ullLastWriteTime));
1573                strEx::replace(syntax, _T("%now-raw%"), strEx::itos(ullNow));
1574                strEx::replace(syntax, _T("%type%"), format::format_byte_units(iType));
1575                strEx::replace(syntax, _T("%child-count%"), strEx::itos(ullChildCount));
1576                strEx::replace(syntax, _T("%exists%"), strEx::itos(uiExists));
1577                strEx::replace(syntax, _T("%int%"), strEx::itos(info.iValue));
1578                strEx::replace(syntax, _T("%int-value%"), strEx::itos(info.iValue));
1579                strEx::replace(syntax, _T("%string%"), info.sValue);
1580                strEx::replace(syntax, _T("%string-value%"), info.sValue);
1581                return syntax;
1582        }
1583};
1584
1585
1586struct regkey_filter {
1587        filters::filter_all_times written;
1588        filters::filter_all_num_ul type;
1589        filters::filter_all_num_ul exists;
1590        filters::filter_all_num_ul child_count;
1591        filters::filter_all_num_ll value_int;
1592        filters::filter_all_strings value_string;
1593
1594        inline bool hasFilter() {
1595                return type.hasFilter() || exists.hasFilter() || written.hasFilter() || child_count.hasFilter() || value_int.hasFilter() || value_string.hasFilter();
1596        }
1597        bool matchFilter(regkey_info &value) const {
1598                if ((written.hasFilter())&&(written.matchFilter(value.get_written())))
1599                        return true;
1600                else if (type.hasFilter()&&type.matchFilter(value.iType))
1601                        return true;
1602                else if (exists.hasFilter()&&exists.matchFilter(value.uiExists))
1603                        return true;
1604                else if ((child_count.hasFilter())&&(child_count.matchFilter(value.ullChildCount)))
1605                        return true;
1606                else if ((value_int.hasFilter())&&(value_int.matchFilter(value.info.iValue)))
1607                        return true;
1608                else if ((value_string.hasFilter())&&(value_string.matchFilter(value.info.sValue)))
1609                        return true;
1610                return false;
1611        }
1612
1613        std::wstring getValue() const {
1614                if (written.hasFilter())
1615                        return _T("written: ") + written.getValue();
1616                if (type.hasFilter())
1617                        return _T("type: ") + type.getValue();
1618                if (exists.hasFilter())
1619                        return _T("exists: ") + exists.getValue();
1620                if (child_count.hasFilter())
1621                        return _T("child_count: ") + child_count.getValue();
1622                if (value_int.hasFilter())
1623                        return _T("value(i): ") + value_int.getValue();
1624                if (value_string.hasFilter())
1625                        return _T("value(s): ") + value_string.getValue();
1626                return _T("UNknown...");
1627        }
1628
1629};
1630
1631
1632struct regkey_container : public regkey_info {
1633
1634        static regkey_container get(std::wstring path, unsigned long long now) {
1635                return regkey_container(now, path);
1636        }
1637
1638
1639        regkey_container(__int64 now, std::wstring path) : regkey_info(now, path) {}
1640
1641        bool has_errors() {
1642                return !error.empty();
1643        }
1644        std::wstring get_error() {
1645                return error;
1646        }
1647
1648};
1649
1650
1651class regkey_type_handler {
1652public:
1653        static int parse(std::wstring s) {
1654                return 1;
1655        }
1656        static std::wstring print(int value) {
1657                return _T("unknown");
1658        }
1659        static std::wstring print_unformated(int value) {
1660                return strEx::itos(value);
1661        }
1662        static std::wstring key_prefix() {
1663                return _T("");
1664        }
1665        static std::wstring key_postfix() {
1666                return _T("");
1667        }
1668        static std::wstring get_perf_unit(int  value) {
1669                return _T("");
1670        }
1671        static std::wstring print_perf(int  value, std::wstring unit) {
1672                return strEx::itos(value);
1673        }
1674};
1675class regkey_exists_handler {
1676public:
1677        static int parse(std::wstring s) {
1678                if (s  == _T("true"))
1679                        return 1;
1680                return 0;
1681        }
1682        static std::wstring print(int value) {
1683                return value==1?_T("true"):_T("false");
1684        }
1685        static std::wstring print_unformated(int value) {
1686                return strEx::itos(value);
1687        }
1688        static std::wstring key_prefix() {
1689                return _T("");
1690        }
1691        static std::wstring key_postfix() {
1692                return _T("");
1693        }
1694        static std::wstring get_perf_unit(int value) {
1695                return _T("");
1696        }
1697        static std::wstring print_perf(int  value, std::wstring unit) {
1698                return strEx::itos(value);
1699        }
1700};
1701
1702typedef checkHolders::CheckContainer<checkHolders::ExactBounds<checkHolders::NumericBounds<int, regkey_type_handler> > > RegTypeContainer;
1703typedef checkHolders::CheckContainer<checkHolders::ExactBounds<checkHolders::NumericBounds<int, regkey_exists_handler> > > RegExistsContainer;
1704
1705typedef checkHolders::CheckContainer<checkHolders::ExactBoundsULong> ExactULongContainer;
1706typedef checkHolders::CheckContainer<checkHolders::ExactBoundsLongLong> ExactLongLongContainer;
1707typedef checkHolders::CheckContainer<checkHolders::ExactBoundsTime> DateTimeContainer;
1708typedef checkHolders::CheckContainer<checkHolders::FilterBounds<filters::filter_all_strings> > StringContainer;
1709
1710struct check_regkey_child_count : public checkHolders::check_proxy_container<regkey_container, ExactULongContainer> {
1711        check_regkey_child_count() { set_alias(_T("child-count")); }
1712        unsigned long get_value(regkey_container &value) {
1713                return value.ullChildCount;
1714        }
1715};
1716struct check_regkey_int_value : public checkHolders::check_proxy_container<regkey_container, ExactLongLongContainer> {
1717        check_regkey_int_value() { set_alias(_T("value")); }
1718        long long get_value(regkey_container &value) {
1719                return value.info.iValue;
1720        }
1721};
1722struct check_regkey_string_value : public checkHolders::check_proxy_container<regkey_container, StringContainer> {
1723        check_regkey_string_value() { set_alias(_T("value")); }
1724        std::wstring get_value(regkey_container &value) {
1725                return value.info.sValue;
1726        }
1727};
1728struct check_regkey_written : public checkHolders::check_proxy_container<regkey_container, DateTimeContainer> {
1729        check_regkey_written() { set_alias(_T("written")); }
1730        unsigned long long get_value(regkey_container &value) {
1731                return value.ullLastWriteTime;
1732        }
1733};
1734struct check_regkey_type : public checkHolders::check_proxy_container<regkey_container, RegTypeContainer> {
1735        check_regkey_type() { set_alias(_T("type")); }
1736        int get_value(regkey_container &value) {
1737                return value.iType;
1738        }
1739};
1740struct check_regkey_exists : public checkHolders::check_proxy_container<regkey_container, RegExistsContainer> {
1741        check_regkey_exists() { set_alias(_T("exists")); }
1742        int get_value(regkey_container &value) {
1743                return value.uiExists;
1744        }
1745};
1746
1747
1748typedef checkHolders::check_multi_container<regkey_container> check_file_multi;
1749struct check_regkey_factories {
1750        static checkHolders::check_proxy_interface<regkey_container>* type() {
1751                return new check_regkey_type();
1752        }
1753        static checkHolders::check_proxy_interface<regkey_container>* exists() {
1754                return new check_regkey_exists();
1755        }
1756        static checkHolders::check_proxy_interface<regkey_container>* child_count() {
1757                return new check_regkey_child_count();
1758        }
1759        static checkHolders::check_proxy_interface<regkey_container>* written() {
1760                return new check_regkey_written();
1761        }
1762        static checkHolders::check_proxy_interface<regkey_container>* value_string() {
1763                return new check_regkey_string_value();
1764        }
1765        static checkHolders::check_proxy_interface<regkey_container>* value_int() {
1766                return new check_regkey_int_value();
1767        }
1768};
1769
1770#define MAP_FACTORY_PB(value, obj) \
1771                else if ((p__.first == _T("check")) && (p__.second == ##value)) { checker.add_check(check_regkey_factories::obj()); }
1772
1773
1774NSCAPI::nagiosReturn CheckSystem::checkSingleRegEntry(std::list<std::wstring> arguments, std::wstring &message, std::wstring &perf) {
1775        NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK;
1776        check_file_multi checker;
1777        typedef std::pair<int,regkey_filter> filteritem_type;
1778        typedef std::list<filteritem_type > filterlist_type;
1779        if (arguments.empty()) {
1780                message = _T("Missing argument(s).");
1781                return NSCAPI::returnUNKNOWN;
1782        }
1783        std::list<std::wstring> files;
1784        unsigned int truncate = 0;
1785        std::wstring syntax = _T("%filename%");
1786        std::wstring alias;
1787        bool bPerfData = true;
1788
1789        try {
1790                MAP_OPTIONS_BEGIN(arguments)
1791                        MAP_OPTIONS_STR2INT(_T("truncate"), truncate)
1792                        MAP_OPTIONS_BOOL_FALSE(IGNORE_PERFDATA, bPerfData)
1793                        MAP_OPTIONS_STR(_T("syntax"), syntax)
1794                        MAP_OPTIONS_STR(_T("alias"), alias)
1795                        MAP_OPTIONS_PUSH(_T("path"), files)
1796                        MAP_OPTIONS_SHOWALL(checker)
1797                        MAP_OPTIONS_EXACT_NUMERIC_ALL_MULTI(checker, _T(""))
1798                        MAP_FACTORY_PB(_T("type"), type)
1799                        MAP_FACTORY_PB(_T("child-count"), child_count)
1800                        MAP_FACTORY_PB(_T("written"), written)
1801                        MAP_FACTORY_PB(_T("int"), value_int)
1802                        MAP_FACTORY_PB(_T("string"), value_string)
1803                        MAP_OPTIONS_MISSING(message, _T("Unknown argument: "))
1804                        MAP_OPTIONS_END()
1805        } catch (filters::parse_exception e) {
1806                message = e.getMessage();
1807                return NSCAPI::returnUNKNOWN;
1808        } catch (filters::filter_exception e) {
1809                message = e.getMessage();
1810                return NSCAPI::returnUNKNOWN;
1811        }
1812        FILETIME now;
1813        GetSystemTimeAsFileTime(&now);
1814        unsigned __int64 nowi64 = ((now.dwHighDateTime * ((unsigned long long)MAXDWORD+1)) + (unsigned long long)now.dwLowDateTime);
1815        for (std::list<std::wstring>::const_iterator pit = files.begin(); pit != files.end(); ++pit) {
1816                regkey_container info = regkey_container::get(*pit, nowi64);
1817                if (info.has_errors()) {
1818                        message = info.error;
1819                        return NSCAPI::returnUNKNOWN;
1820                }
1821                checker.alias = info.render(syntax);
1822                checker.runCheck(info, returnCode, message, perf);
1823        }
1824        if ((truncate > 0) && (message.length() > (truncate-4))) {
1825                message = message.substr(0, truncate-4) + _T("...");
1826                perf = _T("");
1827        }
1828        if (message.empty())
1829                message = _T("CheckSingleRegkey ok");
1830        return returnCode;
1831}
1832
1833NSC_WRAP_DLL();
1834NSC_WRAPPERS_MAIN_DEF(CheckSystem);
1835NSC_WRAPPERS_IGNORE_MSG_DEF();
1836NSC_WRAPPERS_HANDLE_CMD_DEF();
1837NSC_WRAPPERS_CLI_DEF();
Note: See TracBrowser for help on using the repository browser.