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

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