Repository navigation
Expand file tree
/
Copy pathpoller_apcupsd.php
More file actions
579 lines (484 loc) · 18.7 KB
/
Copy pathpoller_apcupsd.php
File metadata and controls
579 lines (484 loc) · 18.7 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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
#!/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');
/** @var array<string,mixed> $config */
require_once($config['base_path'] . '/lib/api_automation_tools.php');
require_once($config['base_path'] . '/lib/api_automation.php');
require_once($config['base_path'] . '/lib/api_device.php');
require_once($config['base_path'] . '/lib/api_data_source.php');
require_once($config['base_path'] . '/lib/api_graph.php');
require_once($config['base_path'] . '/lib/api_tree.php');
require_once($config['base_path'] . '/lib/data_query.php');
require_once($config['base_path'] . '/lib/poller.php');
require_once($config['base_path'] . '/lib/snmp.php');
require_once($config['base_path'] . '/lib/template.php');
require_once($config['base_path'] . '/lib/utility.php');
require('./plugins/apcupsd/includes/field_maps.php');
require_once('./plugins/apcupsd/includes/functions.php');
// process calling arguments
$parms = $_SERVER['argv'];
array_shift($parms);
global $debug, $start, $force;
$debug = false;
$force = false;
$start = microtime(true);
if (cacti_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 '-f':
case '--force':
$force = true;
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 . "\n\n";
display_help();
exit;
}
}
}
print 'NOTE: APCUPSD Poller Process Starting.' . PHP_EOL;
$add_devices = true;
$host_template_id = 0;
if (!apcupsd_host_template_imported()) {
cacti_log('NOTE: UPSD Device Package Not Imported. Device automation will not happen until it is imported!', false, 'APCUPSD');
$add_devices = false;
} else {
$host_template_id = (int) db_fetch_cell_prepared('SELECT id FROM host_template WHERE hash = ?', [APCUPSD_HOST_TEMPLATE_HASH]);
}
// apcupsd upses first UPS
$upses = db_fetch_assoc_prepared('SELECT ups.*
FROM apcupsd_ups AS ups
WHERE type_id = 1
AND enabled = "on"
AND poller_id = ?',
[$config['poller_id']]);
$apcupsd = cacti_sizeof($upses);
if ($apcupsd > 0) {
printf('NOTE: Found %s apcaccess enabled UPS\'s' . PHP_EOL, $apcupsd);
foreach ($upses as $ups) {
debug(sprintf('=================== Collecting UPS Information for %s ===================', $ups['name']));
collect_ups_data($ups);
if ($ups['host_id'] > 0) {
$exists = db_fetch_cell_prepared('SELECT id FROM host WHERE id = ?', [$ups['host_id']]);
if (!$exists) {
$ups['host_id'] = 0;
}
}
if ($ups['host_id'] == 0 && $add_devices) {
add_ups_device($ups, $host_template_id);
}
}
} else {
printf('NOTE: Did not find any apcaccess enabled UPS\'s' . PHP_EOL);
}
// apcupsd upses first UPS
$upses = db_fetch_assoc_prepared('SELECT *
FROM apcupsd_ups
WHERE type_id = 2
AND enabled = "on"
AND poller_id = ?',
[$config['poller_id']]);
$snmpupses = cacti_sizeof($upses);
if ($snmpupses > 0) {
printf('NOTE: Found %s snmp enabled UPS\'s' . PHP_EOL, $snmpupses);
foreach ($upses as $ups) {
debug(sprintf('=================== Collecting UPS Information for %s ===================', $ups['name']));
$ups_up = collect_snmp_ups_data($ups);
if ($ups['host_id'] > 0) {
$exists = db_fetch_cell_prepared('SELECT id FROM host WHERE id = ?', [$ups['host_id']]);
if (!$exists) {
$ups['host_id'] = 0;
}
}
if ($ups['host_id'] == 0 && $add_devices && $ups_up) {
add_ups_device($ups, $host_template_id, true);
}
}
} else {
printf('NOTE: Did not find any snmp enabled UPS\'s' . PHP_EOL);
}
$end = microtime(true);
$cacti_stats = sprintf(
'Time:%01.2f APCAUPSes:%s SNMPUPSes:%s',
$end - $start,
$apcupsd, $snmpupses
);
cacti_log("APCUPSD STATS: $cacti_stats", false, 'SYSTEM');
// log to the database
set_config_option('stats_apcupsd', $cacti_stats);
/**
* Creates a new Cacti device for a discovered UPS (apcaccess-based or
* SNMP-based, using the type-appropriate api_device_save() parameters),
* links it back to the apcupsd_ups row, and triggers device automation.
* Called from this script's main flow for each enabled UPS that doesn't
* yet have an associated host_id.
*
* @param array $ups The apcupsd_ups row for the UPS being
* added as a device.
* @param int $host_template_id The host template id to apply to the
* new device.
* @param bool $force_up For SNMP-based UPSes, whether to force
* the new device's status to Up
* immediately after creation; defaults
* to false.
*
* @return void
*/
function add_ups_device($ups, $host_template_id, $force_up = false): void {
$save = [];
if ($ups['type_id'] == 1) {
$host_id = api_device_save(0, $host_template_id, $ups['name'], 'localhost', // id, template_id, description, hostname
'', 0, '', '', // snmp community, snmp_version, snmp_username, snmp_password
161, 500, '', 0, // snmp_port, snmp_timeout, disabled, availability_method
0, 0, 500, 1, $ups['description'], // ping_method, ping_port, ping_timeout, ping_retries, notes
'', '', '', '', '', // snmp_auth_protocol, snmp_prive_passphrase, snmp_priv_protocol, snmp_context, snmp_engine_id
10, 1, $ups['poller_id'], // max_oids, device_threads, poller_id
$ups['site_id'], '', '', 0); // site_id, external_id, location, bulk_walk_size
} else {
$host_id = api_device_save(0, $host_template_id, $ups['name'], $ups['hostname'], // id, template_id, description, hostname
$ups['snmp_community'], $ups['snmp_version'], $ups['snmp_username'], $ups['snmp_password'], // snmp community, snmp_version, snmp_username, snmp_password
$ups['snmp_port'], $ups['snmp_timeout'], '', 2, // snmp_port, snmp_timeout, disabled, availability_method
0, 0, $ups['snmp_timeout'], 1, $ups['description'], // ping_method, ping_port, ping_timeout, print_retries, notes
$ups['snmp_auth_protocol'], $ups['snmp_priv_passphrase'], $ups['snmp_priv_protocol'], $ups['snmp_context'], $ups['snmp_engine_id'], // snmp_auth_protocol, snmp_prive_passphrase, snmp_priv_protocol, snmp_context, snmp_engine_id
10, 1, $ups['poller_id'], // max_oids, device_threads, poller_id
$ups['site_id'], '', '', 0); // site_id, external_id, location, bulk_walk_size
if ($force_up && $host_id) {
db_execute_prepared('UPDATE host SET status = 3 WHERE id = ?', [$host_id]);
}
}
if ($host_id > 0) {
db_execute_prepared('UPDATE apcupsd_ups
SET host_id = ?
WHERE id = ?',
[$host_id, $ups['id']]);
automation_update_device($host_id);
}
}
/**
* Polls a single SNMP-based UPS by fetching each configured OID from the
* global $ups_database mapping, translating enum values, normalizing a
* few special columns (LASTSTEST, TIMELEFT/DLOWBATT, NOMPOWER/NOMOUTV),
* remembering OIDs that returned no data as 'skipped' for next time, and
* saving the resulting reading to apcupsd_ups_stats. Called from this
* script's main flow for each enabled SNMP-type UPS.
*
* @param array $ups The apcupsd_ups row for the UPS being polled.
*
* @return bool True when the UPS responded and a reading was recorded;
* false when the UPS did not respond to the initial system
* uptime probe.
*
* @global array $ups_database Map of apcupsd/SNMP field keys to their
* db_column/snmp_ci/snmp_enum metadata,
* defined in includes/field_maps.php, used to drive
* which OIDs are polled and how they're
* stored.
* @global string $snmp_error Reserved/declared for parity with other
* SNMP-polling functions; not used
* directly here.
*/
function collect_snmp_ups_data($ups): bool {
global $ups_database, $snmp_error;
$start = time();
$save = [];
$save['ups_id'] = $ups['id'];
$save['ups_date'] = date('Y-m-d H:i:s');
$save['ups_hostname'] = $ups['hostname'];
$save['ups_version'] = '1.0 (Cacti Plugin)';
$save['ups_cable'] = 'Ethernet Link';
$save['ups_driver'] = 'Cacti';
$save['ups_mode'] = 'Stand Alone';
if ($ups['snmp_skipped'] != '') {
$skipped = explode(',', $ups['snmp_skipped']);
} else {
$skipped = [];
}
$return_val = false;
$value = cacti_snmp_get($ups['hostname'], $ups['snmp_community'], '.1.3.6.1.2.1.1.3.0', $ups['snmp_version'],
$ups['snmp_username'], $ups['snmp_password'], $ups['snmp_auth_protocol'], $ups['snmp_priv_passphrase'],
$ups['snmp_priv_protocol'], $ups['snmp_context'], $ups['snmp_port'], $ups['snmp_timeout'], 1, 'SNMP',
$ups['snmp_engine_id']);
if ($ups['status'] != 3) {
$ups_down = true;
} else {
$ups_down = false;
}
if ($value > 0) {
// UPS just came back up, retest possible snmp columns
if (!$ups_down) {
$skipped = [];
}
$return_val = true;
db_execute_prepared('UPDATE apcupsd_ups SET status = 3, last_updated=NOW() WHERE id = ?', [$ups['id']]);
foreach ($ups_database as $key => $data) {
if (isset($data['snmp_ci']) && $data['snmp_ci'] != '' && $data['snmp_ci'] != 'NA' && $data['snmp_ci'] != 'UNKNOWN') {
if ($data['snmp_ci'] == 'CURDATE' || $data['db_column'] == 'ups_date') {
$stats[$data['db_column']] = date('Y-m-d H:i:s');
} elseif (!cacti_sizeof($skipped) || !in_array($key, $skipped, true)) {
$value = cacti_snmp_get($ups['hostname'], $ups['snmp_community'], $data['snmp_ci'], $ups['snmp_version'],
$ups['snmp_username'], $ups['snmp_password'], $ups['snmp_auth_protocol'], $ups['snmp_priv_passphrase'],
$ups['snmp_priv_protocol'], $ups['snmp_context'], $ups['snmp_port'], $ups['snmp_timeout'], 1, 'SNMP',
$ups['snmp_engine_id']);
debug("SNMP Check for {$data['snmp_ci']}, Key $key, DB Column: {$data['db_column']}, Rendered: $value");
if ($value != 'U') {
if (isset($data['snmp_enum'])) {
if (is_numeric($value)) {
$prevalue = $value;
debug("------------------ UPS ENUM $key");
if (isset($data['snmp_enum'][$value])) {
$value = $data['snmp_enum'][$value];
} else {
$value = 'Unknown';
}
debug("------------ $prevalue ---- $value");
} else {
if ($value != '') { // log if $value is not empty string
cacti_log("WARNING: SNMP Value from UPS {$ups['name']} hostname {$ups['hostname']}, for key $key, for OID {$data['snmp_ci']} returns invalid ENUM value of $value, setting skipped", false, 'APCUPSD');
}
$skipped[] = $key;
}
}
switch($key) {
case 'LASTSTEST':
if ($value != '') {
$parts = explode('/', $value);
$save[$data['db_column']] = $parts[2] . '-' . $parts[0] . '-' . $parts[1] . ' 00:00:00';
} else {
$save[$data['db_column']] = '';
}
break;
case 'TIMELEFT':
case 'DLOWBATT':
if (is_numeric($value)) {
$value /= 100;
$value /= 60;
$save[$data['db_column']] = $value;
} else {
$save[$data['db_column']] = 0;
}
break;
case 'NOMPOWER':
case 'NOMOUTV':
$parts = explode(' ', $value);
$save[$data['db_column']] = $parts[0];
break;
default:
$save[$data['db_column']] = $value;
break;
}
} else {
debug("SNMP Check for {$data['snmp_ci']}, Key $key, DB Column: {$data['db_column']}, Rendered: No Data, Set Skipping");
$skipped[] = $key;
}
}
}
}
if (cacti_sizeof($skipped)) {
db_execute_prepared('UPDATE apcupsd_ups SET snmp_skipped = ? WHERE id = ?', [implode(',', $skipped), $ups['id']]);
} else {
db_execute_prepared('UPDATE apcupsd_ups SET snmp_skipped = "" WHERE id = ?', [$ups['id']]);
}
} else {
db_execute_prepared('UPDATE apcupsd_ups SET status = 1, snmp_skipped = "" WHERE id = ?', [$ups['id']]);
}
$save['ups_end_rec'] = date('Y-m-d H:i:s');
sql_save($save, 'apcupsd_ups_stats');
return $return_val;
}
/**
* Polls a single apcaccess-based UPS by locating the apcaccess binary,
* running it against the UPS's configured hostname/port, and parsing its
* "KEY: value" output into apcupsd_ups_stats columns (per the global
* $ups_database mapping), also updating the UPS's linked host's up/down
* status based on the STATUS field. Called from this script's main flow
* for each enabled apcaccess-type UPS.
*
* @param array $ups The apcupsd_ups row for the UPS being polled.
*
* @return int|void Returns 1 when the apcaccess command could not be
* built (invalid hostname/port configuration); otherwise
* returns no explicit value after recording the
* reading or error message.
*
* @global array $ups_database Map of apcupsd field keys to their
* db_column metadata, defined in
* includes/field_maps.php, used to translate apcaccess
* output into database columns.
*/
function collect_ups_data($ups) {
global $ups_database;
// for windows, apcupsd.exe must be in the path
$paths = [
'/usr/sbin/',
'/usr/bin/',
'/usr/local/bin/'
];
$found_path = '';
foreach ($paths as $path) {
if (file_exists($path . 'apcaccess')) {
$found_path = $path;
break;
}
}
$command = apcupsd_build_apcaccess_command($found_path . 'apcaccess', $ups['hostname'], $ups['port']);
$output = [];
$return = 0;
$ups_status = 1;
if ($command === false) {
db_execute_prepared('UPDATE apcupsd_ups
SET status = 1, error_message = ?
WHERE id = ?',
[__('Invalid apcupsd hostname or port configuration', 'apcupsd'), $ups['id']]);
return 1;
}
$results = exec($command, $output, $return);
if ($return > 0) {
$message = implode(', ', $output);
db_execute_prepared('UPDATE apcupsd_ups
SET status = 1, error_message = ?
WHERE id = ?',
[$message, $ups['id']]);
} else {
if (cacti_sizeof($output)) {
$sql_insert = 'REPLACE INTO apcupsd_ups_stats (ups_id';
$sql_data = 'VALUES (?';
$sql_params = [];
$sql_params[] = $ups['id'];
foreach ($output as $o) {
debug('Output:' . $o);
$o = explode(': ', $o);
$keyword = trim($o[0]);
if (isset($o[1])) {
$value = trim($o[1]);
} else {
$value = '';
}
if (array_key_exists($keyword, $ups_database)) {
if ($keyword == 'STATUS') {
$status = db_fetch_cell_prepared('SELECT status
FROM host
WHERE id = ?',
[$ups['host_id']]);
if ($value == 'ONLINE' || $value == 'ONLINE SLAVE') {
$ups_status = 3;
if ($status != 3) {
db_execute_prepared('UPDATE host SET status = 3, status_rec_date=NOW() WHERE id = ?', [$ups['host_id']]);
}
} else {
$ups_status = 1;
if ($status != 4) {
db_execute_prepared('UPDATE host SET status = 4, status_fail_date=NOW() WHERE id = ?', [$ups['host_id']]);
}
}
}
$sql_params[] = $value;
$sql_insert .= ', `' . $ups_database[$keyword]['db_column'] . '`';
$sql_data .= ', ?';
} else {
debug('WARNING: Column ' . $keyword . ' is unknown with value ' . $value);
}
}
db_execute_prepared("$sql_insert) $sql_data)", $sql_params);
}
db_execute_prepared('UPDATE apcupsd_ups
SET status = ?, last_updated=NOW()
WHERE id = ?',
[$ups_status, $ups['id']]);
}
}
/**
* Writes $string to standard output, prefixed with the current time and
* 'DEBUG:', when this script was invoked with the '-d'/'--debug' option.
* Called throughout this script's UPS-polling functions to trace
* progress.
*
* @param string $string 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($string): void {
global $debug;
if ($debug) {
print date('H:i:s') . ' DEBUG: ' . trim($string) . PHP_EOL;
}
}
/**
* 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(): void {
global $config;
if (!function_exists('plugin_apcupsd_version')) {
require_once($config['base_path'] . '/plugins/apcupsd/setup.php');
}
$info = plugin_apcupsd_version();
print 'UPS Poller Process, Version ' . $info['version'] . ', ' . COPYRIGHT_YEARS . "\n";
}
/**
* Prints this script's usage/help text. Called from this script's own CLI
* argument parsing when '--help'/'-H'/'-h' is passed, or when an
* unrecognized argument was given.
*
* @return void
*/
function display_help(): void {
display_version();
print "\nThe UPS poller process script for Cacti.\n\n";
print "usage: \n";
print "poller_apcups.php [--force] [--debug]\n";
}