Repository navigation
Expand file tree
/
Copy pathpoller_wmi.php
More file actions
501 lines (421 loc) · 15.9 KB
/
Copy pathpoller_wmi.php
File metadata and controls
501 lines (421 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
#!/usr/bin/php -q
<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2026 The Cacti Group |
| |
| This program is free software; you can redistribute it and/or |
| modify it under the terms of the GNU General Public License |
| as published by the Free Software Foundation; either version 2 |
| of the License, or (at your option) any later version. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDTool-based Graphing Solution |
+-------------------------------------------------------------------------+
| This code is designed, written, and maintained by the Cacti Group. See |
| about.php and/or the AUTHORS file for specific developer information. |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/
chdir(__DIR__);
chdir('../..');
require('./include/cli_check.php');
require_once('./lib/poller.php');
require_once('./lib/ping.php');
require_once('./plugins/wmi/includes/functions.php');
// process calling arguments
$parms = $_SERVER['argv'];
array_shift($parms);
global $debug, $start, $seed, $forcerun;
$debug = false;
$forcerun = false;
$mainrun = false;
$host_id = '';
$start = '';
$seed = '';
$key = '';
if (sizeof($parms)) {
foreach ($parms as $parameter) {
if (strpos($parameter, '=')) {
[$arg, $value] = explode('=', $parameter);
} else {
$arg = $parameter;
$value = '';
}
switch ($arg) {
case '-d':
case '--debug':
$debug = true;
break;
case '--host-id':
$host_id = $value;
break;
case '--seed':
$seed = $value;
break;
case '--key':
$key = $value;
break;
case '-f':
case '--force':
$forcerun = true;
break;
case '-M':
$mainrun = true;
break;
case '-s':
case '--start':
$start = $value;
break;
case '--version':
case '-V':
case '-v':
display_version();
exit;
case '--help':
case '-H':
case '-h':
display_help();
exit;
default:
print 'ERROR: Invalid Parameter ' . $parameter . PHP_EOL . PHP_EOL;
display_help();
exit;
}
}
}
// Check for mandatory parameters
if (!$mainrun && $host_id == '') {
print 'FATAL: You must specify a Cacti host-id run' . PHP_EOL;
exit;
}
// Do not process if not enabled
if (!api_plugin_is_enabled('wmi')) {
print 'WARNING: The Host WMI Collection is Down! Exiting' . PHP_EOL;
exit(0);
}
if ($seed == '') {
$seed = rand();
}
if ($start == '') {
$start = microtime(true);
}
if ($mainrun) {
process_all_devices();
} else {
process_device((int) $host_id);
}
exit(0);
/**
* Writes $message to standard output, prefixed 'DEBUG:', when this script
* was invoked with the '-d'/'--debug' option. Called throughout this
* script's device-processing functions to trace progress.
*
* @param string $message The message to print when debugging is enabled.
*
* @return void
*
* @global bool $debug Whether debug output is enabled, set from this
* script's own CLI argument parsing.
*/
function debug($message) {
global $debug;
if ($debug) {
print 'DEBUG: ' . trim($message) . PHP_EOL;
}
}
/**
* Master-run entry point: finds every enabled, up, non-disabled device
* due for a WMI query refresh, launches a background poller_wmi.php
* child process (bounded by the 'wmi_processes' concurrency setting) for
* each, waits for all children to finish (tracked via the wmi_processes
* table), optionally auto-purges cache/mapping rows for devices that no
* longer exist, and logs overall polling statistics. Called from this
* script's main flow when invoked with the '-M' (master) option.
*
* @return void
*
* @global float $start Set from this script's own CLI argument parsing
* (or the current time); used to compute total
* elapsed run time for the stats log.
* @global int $seed Set from this script's own CLI argument parsing
* (or a random value); used to tag/track this run's
* child processes in the wmi_processes table.
*/
function process_all_devices() {
global $start, $seed;
print 'NOTE: Processing Hosts Begins' . PHP_EOL;
// Do not process collectors are still running
if (db_fetch_cell('SELECT COUNT(*) FROM wmi_processes') > 0) {
print 'WARNING: Another WMI Collector is still running! Exiting' . PHP_EOL;
exit(0);
}
/* The devices to scan will
* 1) Not be disabled,
* 2) Be linked to the host table
* 3) Be up and operational
*/
$devices = db_fetch_assoc("SELECT DISTINCT h.id AS host_id, h.description, h.hostname
FROM host_template_wmi_query AS htwq
LEFT JOIN host AS h
ON htwq.host_template_id = h.host_template_id
LEFT JOIN host_wmi_query AS hwq
ON hwq.host_id = h.id
AND hwq.wmi_query_id = htwq.wmi_query_id
INNER JOIN wmi_wql_queries AS wwq
ON wwq.id = htwq.wmi_query_id
WHERE (UNIX_TIMESTAMP(NOW()) >= UNIX_TIMESTAMP(last_started)+frequency OR last_started IS NULL)
AND h.status != 1
AND h.disabled != 'on'
AND wwq.enabled = 'on'
AND wmi_account > 0");
// Remove entries from down and disabled devices
db_execute("DELETE FROM host_wmi_cache
WHERE host_id IN(
SELECT id
FROM host
WHERE disabled='on'
OR host.status=1
)");
$concurrent_processes = read_config_option('wmi_processes');
if (empty($concurrent_processes)) {
set_config_option('wmi_processes', '10');
}
print 'NOTE: Launching Collectors Starting' . PHP_EOL;
$i = 0;
if (sizeof($devices)) {
foreach ($devices as $device) {
while (true) {
$processes = db_fetch_cell('SELECT COUNT(*) FROM wmi_processes');
if ($processes < $concurrent_processes) {
// put a placeholder in place to prevent overloads on slow systems
$key = rand();
db_execute_prepared('INSERT INTO wmi_processes (pid, taskid, started) VALUES (?, ?, NOW())', [$key, $seed]);
print "NOTE: Launching WMI Collector For: '" . $device['description'] . '[' . $device['hostname'] . "]'" . PHP_EOL;
process_background_device($device['host_id'], $seed, $key);
usleep(10000);
break;
} else {
sleep(1);
}
}
}
print 'NOTE: All WMI Devices Launched, proceeding to wait for completion' . PHP_EOL;
// wait for all processes to end or max run time
while (true) {
$processes_left = db_fetch_cell_prepared('SELECT COUNT(*) FROM wmi_processes WHERE taskid = ?', [$seed]);
$pl = db_fetch_cell('SELECT COUNT(*) FROM wmi_processes');
if ($processes_left == 0) {
print 'NOTE: All Processes Complete, Exiting' . PHP_EOL;
break;
} else {
print "NOTE: Waiting on '$processes_left' Processes" . PHP_EOL;
sleep(2);
}
}
} else {
print 'NOTE: No Devices found this pass to launch' . PHP_EOL;
}
if (read_config_option('wmi_autopurge') == 'on') {
print 'NOTE: Auto Purging Devices' . PHP_EOL;
$dead_devices = db_fetch_assoc('SELECT host_id
FROM host_wmi_cache AS hwc
LEFT JOIN host
ON host.id = hwc.host_id
WHERE host.id IS NULL');
if (sizeof($dead_devices)) {
foreach ($dead_devices as $device) {
db_execute_prepared('DELETE FROM host_wmi_cache WHERE host_id = ?', [$device['host_id']]);
db_execute_prepared('DELETE FROM host_wmi_query WHERE host_id = ?', [$device['host_id']]);
print "Purged WMI Device with ID '" . $device['host_id'] . "'" . PHP_EOL;
}
}
}
// take time and log performance data
$end = microtime(true);
$cacti_stats = sprintf(
'Time:%01.2f ' .
'Processes:%s ' .
'Devices:%s',
$end - $start,
$concurrent_processes,
cacti_sizeof($devices));
// log to the database
set_config_option('stats_wmi', $cacti_stats);
// log to the logfile
cacti_log('WMI STATS: ' . $cacti_stats , true, 'SYSTEM');
print "NOTE: Device WMI Polling Completed, $cacti_stats" . PHP_EOL;
}
/**
* Launches a background poller_wmi.php child process to poll a single
* device's WMI queries, passing along the master run's shared seed/start
* time and the device's process-lock placeholder key. Called from
* process_all_devices() for each device due for a WMI query refresh.
*
* @param int $host_id The Cacti host id to poll in the background.
* @param int $seed The master run's shared task/seed identifier,
* used to track this run's child processes.
* @param int $key The wmi_processes placeholder row's pid value to
* replace once the child process starts.
*
* @return void
*
* @global array $config Cacti global configuration array; used to
* locate the PHP binary and this script.
* @global bool $debug Whether debug output is enabled, propagated
* to the child process.
* @global float $start The master run's shared start time,
* propagated to the child process.
* @global bool $forcerun Whether a forced run was requested,
* propagated to the child process.
*/
function process_background_device($host_id, $seed, $key) {
global $config, $debug, $start, $forcerun;
exec_background(read_config_option('path_php_binary'),' -q ' .
$config['base_path'] . '/plugins/wmi/poller_wmi.php' .
' --host-id=' . $host_id .
' --start=' . $start .
' --seed=' . $seed .
' --key=' . $key .
($forcerun ? ' --force' : '') .
($debug ? ' --debug' : ''));
}
/**
* Child-process entry point: runs every WMI query due for a single
* device (via run_store_wmi_query()), recording each query's last-run
* time, runtime, and failure status in host_wmi_query, then releases this
* process's lock row in wmi_processes. Called from this script's main
* flow when invoked with '--host-id=N' (i.e. as a background child of
* process_background_device()).
*
* @param int $host_id The Cacti host id to poll.
*
* @return void
*
* @global array $config Reserved/declared for parity with other
* device-processing functions; not used
* directly here.
* @global float $start Reserved/declared for parity with other
* device-processing functions; not used
* directly here.
* @global int $seed The current run's shared task identifier,
* used to release this device's process
* lock row.
* @global int $key This device's wmi_processes placeholder
* pid value, replaced with the real pid at
* the start of processing.
* @global int $snmp_errors Reserved/declared for parity with other
* device-processing functions; not used
* directly here.
*/
function process_device($host_id) {
global $config, $start, $seed, $key, $snmp_errors;
$wmi_errors = 0;
$queries_to_run = db_fetch_assoc_prepared('SELECT h.id, h.wmi_account, htwq.wmi_query_id, wwq.*
FROM host_template_wmi_query AS htwq
LEFT JOIN host AS h
ON htwq.host_template_id = h.host_template_id
LEFT JOIN host_wmi_query AS hwq
ON hwq.host_id = h.id
AND hwq.wmi_query_id = htwq.wmi_query_id
INNER JOIN wmi_wql_queries AS wwq
ON wwq.id = htwq.wmi_query_id
WHERE (UNIX_TIMESTAMP(NOW()) >= UNIX_TIMESTAMP(last_started)+frequency OR last_started IS NULL)
AND h.id = ?
AND wmi_account > 0',
[$host_id]);
// remove the key process and insert the set a process lock
db_execute_prepared('REPLACE INTO wmi_processes (pid, taskid) VALUES (?, ?)', [getmypid(), $seed]);
db_execute_prepared('DELETE FROM wmi_processes WHERE pid = ? AND taskid = ?', [$key, $seed]);
$qstart = date('Y-m-d H:i:s');
if (cacti_sizeof($queries_to_run)) {
foreach ($queries_to_run as $q) {
$qmstart = microtime(true);
cacti_log('NOTE: Executing WMI Query[' . $q['wmi_query_id'] . "] for Device [$host_id].", false, 'WMI', POLLER_VERBOSITY_MEDIUM);
$account = db_fetch_row_prepared('SELECT *
FROM wmi_user_accounts
WHERE id = ?',
[$q['wmi_account']]);
if (!cacti_sizeof($account)) {
cacti_log('WARNING: WMI Account ID ' . $q['wmi_account'] . " not found for WMI Device[$host_id].", false, 'WMI');
break;
}
$run_before = db_fetch_row_prepared('SELECT *
FROM host_wmi_query
WHERE host_id = ?
AND wmi_query_id = ?',
[$host_id, $q['wmi_query_id']]);
$run_before = is_array($run_before) ? $run_before : [];
if (!cacti_sizeof($run_before)) {
$last_failed = '0000-00-00 00:00:00';
} else {
$last_failed = $run_before['last_failed'];
}
// Run the query and store the data
$status = run_store_wmi_query($host_id, $q['wmi_query_id']) ? 0 : 1;
$qmend = microtime(true);
if ($status != 0) {
$last_failed = date('Y-m-d H:i:s');
cacti_log('WARNING: Errored WMI Query[' . $q['wmi_query_id'] . "] for Device [$host_id] in " . round($qmend - $qmstart, 2) . ' seconds.', false, 'WMI');
} else {
cacti_log('NOTE: Finished WMI Query[' . $q['wmi_query_id'] . "] for Device [$host_id] in " . round($qmend - $qmstart, 2) . ' seconds.', false, 'WMI', POLLER_VERBOSITY_MEDIUM);
}
db_execute_prepared('REPLACE INTO host_wmi_query
(host_id, wmi_query_id, sort_field, title_format, last_started, last_runtime, last_failed)
VALUES (?, ?, ?, ?, ?, ?, ?)',
[$host_id, $q['wmi_query_id'], '', '', $qstart, ($qmend - $qmstart), $last_failed]
);
}
} else {
cacti_log("NOTE: WMI Device[$host_id] had no WMI Queries to run this cycle.", false, 'WMI', POLLER_VERBOSITY_MEDIUM);
}
// remove the process lock
db_execute_prepared('DELETE FROM wmi_processes WHERE pid = ?', [getmypid()]);
if ($wmi_errors > 0) {
cacti_log("WARNING: WMI Device[$host_id] experienced $wmi_errors WMI Errors while performing data collection. Increase logging to HIGH for this device to see the errors.", false, 'WMI');
}
}
/**
* Prints this script's name, plugin version, and copyright banner.
* Called from this script's own CLI argument parsing when
* '--version'/'-V'/'-v' is passed, and from display_help() before
* printing usage text.
*
* @return void
*
* @global array $config Cacti global configuration array; used to load
* this plugin's setup.php if needed to determine
* the plugin version.
*/
function display_version() {
global $config;
if (!function_exists('plugin_wmi_version')) {
require_once($config['base_path'] . '/plugins/wmi/setup.php');
}
$info = plugin_wmi_version();
if (!isset($info['version'])) {
cacti_log('ERROR: WMI plugin INFO file is missing required fields, skipping version display', false, 'WMI');
return;
}
print 'Device WMI Poller Process, Version ' . $info['version'] . ', ' . COPYRIGHT_YEARS . PHP_EOL;
}
/**
* Prints this script's usage/help text for both master and child process
* invocations. Called from this script's own CLI argument parsing when
* '--help'/'-H'/'-h' is passed.
*
* @return void
*/
function display_help() {
display_version();
print PHP_EOL;
print 'The Device WMI poller process script for Cacti.' . PHP_EOL . PHP_EOL;
print 'usage:' . PHP_EOL;
print 'master process: poller_wmi.php [-M] [-f] [-d]' . PHP_EOL;
print 'child process: poller_wmi.php --host-id=N [--seed=N] [-f] [-d]' . PHP_EOL . PHP_EOL;
}