source: nscp/modules/CheckWMI/CheckWMI.cpp @ 3692371

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

2009-01-20 MickeM

  • Fixed issue with CheckWMI when no filter was specified.

2009-01-17 MickeM

+ Added new command line option pdhlookup (to CheckSystem) to lookup index from names.

Probably not usefull to anyone but me :) Usage: "nsclient++ -noboot CheckSystem pdhlookup Antal bindningsreferenser"

  • Fixed so PDH Collectors use the same exception as the rest of the PDH stuff (might give better errors when PDH breaks, but I doubt it)
  • removed debug output from -noboot + Added new command line option pdhmatch to use pattern matching on PDH queries Usage: nsclient++ -noboot CheckSystem pdhmatch \Process(*)\Antal trådar
  • Improved error reporting in the PDH subsystem. + Added new module A_DebugLogMetrics.dll which can be used to generate debug info. Enable the module and a file called process_info.csv will be created under %APP_DATA%/nsclient++/process_info.csv which contains metrics.
  • Fixed handle leak in CheckExternalProcess? and NRPEListsner (executing commands).

2009-01-13 MickeM

  • Fixed issue with 64-bit installer (now installs under Program Files (and not x86) + Brand new build enviornment based upon boost build!!! Use batch file to build (release-build.bat or modify to make your own)
  • Modified /about so it now shows a lot of usefull(?) info.

2008-11-13 MickeM

+ Added truncate option to checkServiceState

2008-09-24 MickeM

  • Imroved the installer (now auto-updates the version when built)
  • Property mode set to 100644
File size: 12.5 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 "CheckWMI.h"
24#include <strEx.h>
25#include <time.h>
26#include <map>
27#include <vector>
28
29
30CheckWMI gCheckWMI;
31
32BOOL APIENTRY DllMain( HANDLE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved)
33{
34        NSCModuleWrapper::wrapDllMain(hModule, ul_reason_for_call);
35        return TRUE;
36}
37
38CheckWMI::CheckWMI() {
39}
40CheckWMI::~CheckWMI() {
41}
42
43
44bool CheckWMI::loadModule() {
45        try {
46                NSCModuleHelper::registerCommand(_T("CheckWMIValue"), _T("Run a WMI query and check the resulting value (the values of each row determin the state)."));
47                NSCModuleHelper::registerCommand(_T("CheckWMI"), _T("Run a WMI query and check the resulting rows (the number of hits determine state)."));
48        } catch (NSCModuleHelper::NSCMHExcpetion &e) {
49                NSC_LOG_ERROR_STD(_T("Failed to register command: ") + e.msg_);
50        } catch (...) {
51                NSC_LOG_ERROR_STD(_T("Failed to register command."));
52        }
53        return true;
54}
55bool CheckWMI::unloadModule() {
56        return true;
57}
58
59bool CheckWMI::hasCommandHandler() {
60        return true;
61}
62bool CheckWMI::hasMessageHandler() {
63        return false;
64}
65
66
67#define MAP_CHAINED_FILTER(value, obj) \
68                        else if (p__.first.length() > 8 && p__.first.substr(1,6) == _T("filter") && p__.first.substr(7,1) == _T("-") && p__.first.substr(8) == value) { \
69                        WMIQuery::wmi_filter filter; filter.obj = p__.second; chain.push_filter(p__.first, filter); }
70
71#define MAP_SECONDARY_CHAINED_FILTER(value, obj) \
72                        else if (p2.first.length() > 8 && p2.first.substr(1,6) == _T("filter") && p2.first.substr(7,1) == _T("-") && p2.first.substr(8) == value) { \
73                        WMIQuery::wmi_filter filter; filter.obj = p__.second; filter.alias = p2.second; chain.push_filter(p__.first, filter); }
74
75#define MAP_CHAINED_FILTER_STRING(value) \
76        MAP_CHAINED_FILTER(value, string)
77
78#define MAP_CHAINED_FILTER_NUMERIC(value) \
79        MAP_CHAINED_FILTER(value, numeric)
80
81NSCAPI::nagiosReturn CheckWMI::CheckSimpleWMI(const unsigned int argLen, TCHAR **char_args, std::wstring &message, std::wstring &perf) {
82        typedef checkHolders::CheckContainer<checkHolders::MaxMinBounds<checkHolders::NumericBounds<int, checkHolders::int_handler> > > WMIContainer;
83
84        NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK;
85        typedef filters::chained_filter<WMIQuery::wmi_filter,WMIQuery::wmi_row> filter_chain;
86        filter_chain chain;
87        std::list<std::wstring> args = arrayBuffer::arrayBuffer2list(argLen, char_args);
88        if (args.empty()) {
89                message = _T("Missing argument(s).");
90                return NSCAPI::returnCRIT;
91        }
92        unsigned int truncate = 0;
93        std::wstring query, alias;
94        std::wstring ns = _T("root\\cimv2");
95        bool bPerfData = true;
96
97        WMIContainer result_query;
98        try {
99                MAP_OPTIONS_BEGIN(args)
100                MAP_OPTIONS_STR(_T("Query"), query)
101                MAP_OPTIONS_STR2INT(_T("truncate"), truncate)
102                MAP_OPTIONS_STR(_T("namespace"), ns)
103                MAP_OPTIONS_STR(_T("Alias"), alias)
104                MAP_OPTIONS_BOOL_FALSE(IGNORE_PERFDATA, bPerfData)
105                MAP_OPTIONS_NUMERIC_ALL(result_query, _T(""))
106                MAP_OPTIONS_SHOWALL(result_query)
107                MAP_CHAINED_FILTER(_T("string"),string)
108                MAP_CHAINED_FILTER(_T("numeric"),numeric)
109                MAP_OPTIONS_SECONDARY_BEGIN(_T(":"), p2)
110                MAP_SECONDARY_CHAINED_FILTER(_T("string"),string)
111                MAP_SECONDARY_CHAINED_FILTER(_T("numeric"),numeric)
112                        else if (p2.first == _T("Query")) {
113                                        query = p__.second;
114                                        alias = p2.second;
115                                }
116                MAP_OPTIONS_MISSING_EX(p2, message, _T("Unknown argument: "))
117                        MAP_OPTIONS_SECONDARY_END()
118                MAP_OPTIONS_END()
119        } catch (filters::parse_exception e) {
120                message = _T("WMIQuery failed: ") + e.getMessage();
121                return NSCAPI::returnCRIT;
122        }
123
124        WMIQuery::result_type rows;
125        try {
126                WMIQuery wmiQuery;
127                rows = wmiQuery.execute(ns, query);
128        } catch (WMIException e) {
129                message = _T("WMIQuery failed: ") + e.getMessage();
130                return NSCAPI::returnCRIT;
131        }
132        int hit_count = 0;
133
134        if (chain.empty()) {
135                NSC_DEBUG_MSG_STD(_T("No filters specified so we will match all rows"));
136                hit_count = rows.size();
137        } else {
138                bool match = chain.get_inital_state();
139                for (WMIQuery::result_type::iterator citRow = rows.begin(); citRow != rows.end(); ++citRow) {
140                        WMIQuery::wmi_row vals = *citRow;
141                        match = chain.match(match, vals);
142                        if (match) {
143                                strEx::append_list(message, vals.render());
144                                hit_count++;
145                        }
146                }
147        }
148
149        if (!bPerfData)
150                result_query.perfData = false;
151        result_query.runCheck(hit_count, returnCode, message, perf);
152        if ((truncate > 0) && (message.length() > (truncate-4)))
153                message = message.substr(0, truncate-4) + _T("...");
154        if (message.empty())
155                message = _T("OK: WMI Query returned no results.");
156        return returnCode;
157}
158
159NSCAPI::nagiosReturn CheckWMI::CheckSimpleWMIValue(const unsigned int argLen, TCHAR **char_args, std::wstring &message, std::wstring &perf) {
160        typedef checkHolders::CheckContainer<checkHolders::MaxMinBounds<checkHolders::NumericBounds<long long, checkHolders::int64_handler> > > WMIContainer;
161        std::list<std::wstring> stl_args = arrayBuffer::arrayBuffer2list(argLen, char_args);
162        if (stl_args.empty()) {
163                message = _T("ERROR: Missing argument exception.");
164                return NSCAPI::returnUNKNOWN;
165        }
166        std::list<WMIContainer> list;
167        NSCAPI::nagiosReturn returnCode = NSCAPI::returnOK;
168        WMIContainer tmpObject;
169        bool bPerfData = true;
170        unsigned int truncate = 0;
171        std::wstring query;
172        std::wstring ns = _T("root\\cimv2");
173        std::wstring aliasCol;
174
175        // Query=Select ... MaxWarn=5 MaxCrit=12 Check=Col1 --(later)-- Match==test Check=Col2
176        // MaxWarnNumeric:ID=>5
177        try {
178                MAP_OPTIONS_BEGIN(stl_args)
179                        MAP_OPTIONS_SHOWALL(tmpObject)
180                        MAP_OPTIONS_NUMERIC_ALL(tmpObject, _T(""))
181                        MAP_OPTIONS_STR(_T("namespace"), ns)
182                        MAP_OPTIONS_STR(_T("Alias"), tmpObject.data)
183                        MAP_OPTIONS_STR(_T("AliasCol"), aliasCol)
184                        MAP_OPTIONS_STR(_T("Query"), query)
185                        MAP_OPTIONS_BOOL_FALSE(IGNORE_PERFDATA, bPerfData)
186                        MAP_OPTIONS_STR_AND(_T("Check"), tmpObject.data, list.push_back(tmpObject))
187                        MAP_OPTIONS_STR(_T("Alias"), tmpObject.data)
188                        MAP_OPTIONS_SECONDARY_BEGIN(_T(":"), p2)
189                        MAP_OPTIONS_SECONDARY_STR_AND(p2,_T("Check"), tmpObject.data, tmpObject.alias, list.push_back(tmpObject))
190                                MAP_OPTIONS_MISSING_EX(p2, message, _T("Unknown argument: "))
191                                MAP_OPTIONS_SECONDARY_END()
192                        MAP_OPTIONS_MISSING(message, _T("Unknown argument: "))
193                        MAP_OPTIONS_END()
194
195        } catch (filters::parse_exception e) {
196                message = _T("WMIQuery failed: ") + e.getMessage();
197                return NSCAPI::returnCRIT;
198        }
199
200        WMIQuery::result_type rows;
201        try {
202                NSC_DEBUG_MSG_STD(_T("Running query: '") + query + _T("' on: ") + ns);
203                WMIQuery wmiQuery;
204                rows = wmiQuery.execute(ns, query);
205        } catch (WMIException e) {
206                message = _T("WMIQuery failed: ") + e.getMessage();
207                return NSCAPI::returnCRIT;
208        }
209        int hit_count = 0;
210
211        for (std::list<WMIContainer>::const_iterator it = list.begin(); it != list.end(); ++it) {
212                WMIContainer itm = (*it);
213                itm.setDefault(tmpObject);
214                itm.perfData = bPerfData;
215                if (itm.data == _T("*")) {
216                        for (WMIQuery::result_type::const_iterator citRow = rows.begin(); citRow != rows.end(); ++citRow) {
217                                for (WMIQuery::wmi_row::list_type::const_iterator citCol = (*citRow).results.begin(); citCol != (*citRow).results.end(); ++citCol) {
218                                        long long value = (*citCol).second.numeric;
219                                        itm.runCheck(value, returnCode, message, perf);
220                                }
221                        }
222                }
223        }
224        for (WMIQuery::result_type::const_iterator citRow = rows.begin(); citRow != rows.end(); ++citRow) {
225                bool found = false;
226                std::wstring alias;
227                if (!aliasCol.empty()) {
228                        alias = (*citRow).get(aliasCol).string;
229                }
230                for (WMIQuery::wmi_row::list_type::const_iterator citCol = (*citRow).results.begin(); citCol != (*citRow).results.end(); ++citCol) {
231                        for (std::list<WMIContainer>::const_iterator it = list.begin(); it != list.end(); ++it) {
232                                WMIContainer itm = (*it);
233                                if (itm.data == _T("*")) {
234                                        found = true;
235                                } else if ((*citCol).first == itm.data) {
236                                        std::wstring oldAlias = itm.alias;
237                                        if (!alias.empty())
238                                                itm.alias = alias + _T(" ") + itm.getAlias();
239                                        found = true;
240                                        long long value = (*citCol).second.numeric;
241                                        itm.runCheck(value, returnCode, message, perf);
242                                        itm.alias = oldAlias;
243                                }
244                        }
245                }
246                if (!found) {
247                        NSC_LOG_ERROR_STD(_T("At least one of the queried columns was not found!"));
248                }
249        }
250
251        if ((truncate > 0) && (message.length() > (truncate-4)))
252                message = message.substr(0, truncate-4) + _T("...");
253        if (message.empty())
254                message = _T("OK: Everything seems fine.");
255        return returnCode;
256}
257
258
259NSCAPI::nagiosReturn CheckWMI::handleCommand(const strEx::blindstr command, const unsigned int argLen, TCHAR **char_args, std::wstring &msg, std::wstring &perf) {
260        if (command == _T("CheckWMI")) {
261                return CheckSimpleWMI(argLen, char_args, msg, perf);
262        } else if (command == _T("CheckWMIValue")) {
263                return CheckSimpleWMIValue(argLen, char_args, msg, perf);
264        }       
265        return NSCAPI::returnIgnored;
266}
267int CheckWMI::commandLineExec(const TCHAR* command, const unsigned int argLen, TCHAR** char_args) {
268        //WMIQuery wmiQuery;
269        std::wstring query = command;
270        std::wstring ns = _T("root\\cimv2");
271        query += _T(" ") + arrayBuffer::arrayBuffer2string(char_args, argLen, _T(" "));
272        WMIQuery::result_type rows;
273        try {
274                WMIQuery wmiQuery;
275                NSC_DEBUG_MSG_STD(_T("Running query: '") + query + _T("' on: ") + ns);
276                rows = wmiQuery.execute(ns, query);
277        } catch (WMIException e) {
278                NSC_LOG_ERROR_STD(_T("WMIQuery failed: ") + e.getMessage());
279                return -1;
280        }
281        if (rows.empty()) {
282                NSC_LOG_MESSAGE(_T("Query returned no rows."));
283        } else {
284                NSC_DEBUG_MSG_STD(_T("Query returned: ") + strEx::itos(rows.size()) + _T(" rows."));
285                std::vector<std::wstring::size_type> widths;
286                for (WMIQuery::result_type::const_iterator citRow = rows.begin(); citRow != rows.end(); ++citRow) {
287                        const WMIQuery::wmi_row vals = *citRow;
288                        if (citRow == rows.begin()) {
289                                for (WMIQuery::wmi_row::list_type::const_iterator citCol = vals.results.begin(); citCol != vals.results.end(); ++citCol) {
290                                        widths.push_back( (*citCol).first.length()+1 );
291                                }
292                        }
293                        int i=0;
294                        for (WMIQuery::wmi_row::list_type::const_iterator citCol = vals.results.begin(); citCol != vals.results.end(); ++citCol, i++) {
295                                widths[i] = max(widths[i], (*citCol).second.string.length()+1);
296                        }
297                }
298                std::wstring row2 = _T("|");
299                for (WMIQuery::result_type::iterator citRow = rows.begin(); citRow != rows.end(); ++citRow) {
300                        const WMIQuery::wmi_row vals = *citRow;
301                        if (citRow == rows.begin()) {
302                                int i=0;
303                                std::wstring row1 = _T("|");
304                                for (WMIQuery::wmi_row::list_type::const_iterator citCol = vals.results.begin(); citCol != vals.results.end(); ++citCol, i++) {
305                                        std::wstring::size_type w = widths[i]-(*citCol).first.length();
306                                        if (w<0) w=0;
307                                        row1 += std::wstring(w, ' ') + (*citCol).first + _T(" |");
308                                        row2 += std::wstring(widths[i], '-') + _T("-+");
309
310                                }
311                                NSC_LOG_MESSAGE(row2);
312                                NSC_LOG_MESSAGE(row1);
313                                NSC_LOG_MESSAGE(row2);
314                        }
315                        int i=0;
316                        std::wstring row = _T("|");
317                        for (WMIQuery::wmi_row::list_type::const_iterator citCol = vals.results.begin(); citCol != vals.results.end(); ++citCol, i++) {
318                                std::wstring::size_type w = widths[i]-(*citCol).second.string.length();
319                                if (w<0) w=0;
320                                row += std::wstring(w, ' ') + (*citCol).second.string + _T(" |");
321                        }
322                        NSC_LOG_MESSAGE(row);
323                }
324                NSC_LOG_MESSAGE(row2);
325        }
326        return 0;
327}
328
329
330NSC_WRAPPERS_MAIN_DEF(gCheckWMI);
331NSC_WRAPPERS_IGNORE_MSG_DEF();
332NSC_WRAPPERS_HANDLE_CMD_DEF(gCheckWMI);
333NSC_WRAPPERS_CLI_DEF(gCheckWMI);
Note: See TracBrowser for help on using the repository browser.