source: nscp/modules/CheckSystem/CheckSystem.cpp @ 9fdde88

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