Repository navigation
Expand file tree
/
Copy pathpoller_hmib.php
More file actions
1410 lines (1206 loc) · 46.9 KB
/
Copy pathpoller_hmib.php
File metadata and controls
1410 lines (1206 loc) · 46.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
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/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('../..');
include('./include/cli_check.php');
include_once('./lib/poller.php');
include_once('./lib/snmp.php');
include_once('./lib/ping.php');
// process calling arguments
$parms = $_SERVER['argv'];
array_shift($parms);
global $debug, $start, $seed, $forcerun;
$debug = false;
$forcerun = false;
$forcediscovery = false;
$mainrun = false;
$host_id = '';
$start = '';
$seed = '';
$key = '';
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 '--host-id':
$host_id = $value;
break;
case '--seed':
$seed = $value;
break;
case '--key':
$key = $value;
break;
case '-f':
case '--force':
$forcerun = true;
break;
case '-fd':
case '--force-discovery':
$forcediscovery = 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 . "\n\n";
display_help();
exit;
}
}
}
// Check for mandatory parameters
if (!$mainrun && $host_id == '') {
print "FATAL: You must specify a Cacti host-id run\n";
exit;
}
// Do not process if not enabled
if (read_config_option('hmib_enabled') == '' || !api_plugin_is_enabled('hmib')) {
print 'WARNING: The Host Mib Collection is Down! Exiting' . PHP_EOL;
exit(0);
}
if ($seed == '') {
$seed = rand();
}
if ($start == '') {
$start = microtime(true);
}
if ($mainrun) {
process_hosts();
} else {
checkHost((int) $host_id);
}
exit(0);
/**
* Determines whether a scheduled collection task is due to run, based on
* elapsed time since its last run versus its configured frequency, or
* whether a forced run was requested. Called from process_hosts() to
* decide whether autodiscovery/other periodic subtasks should run this
* cycle.
*
* @param float $start The current run's start time (from
* microtime(true)).
* @param float|null $lastrun The task's last-run time as a Unix timestamp; may
* carry fractional seconds when sourced from
* microtime(true). Null (an unset settings row, e.g.
* a task's first run) is treated as 0.
* @param int|null $frequency The task's configured run frequency in
* seconds; 0/null disables the task.
*
* @return bool True if the task is due to run, false otherwise.
*
* @global bool $forcerun Whether this run was started with '--force',
* in which case the task always runs.
*/
function runCollector(float $start, ?float $lastrun, ?int $frequency): bool {
global $forcerun;
// read_config_option() returns null for an unset lastrun/frequency setting
// (e.g. a task's very first run); normalize so the typed comparison is safe.
$lastrun = (float) $lastrun;
$frequency = (int) $frequency;
if ((empty($lastrun) || ($start - $lastrun) > $frequency) && $frequency > 0 || $forcerun) {
return true;
} else {
return false;
}
}
/**
* Prints a debug message to stdout when CLI debug output is enabled.
* Called throughout this script to report progress during collection.
*
* @param string $message The debug message to print.
*
* @return void
*
* @global bool $debug Whether debug output ('--debug' CLI flag) is
* enabled; when false, this function is a no-op.
*/
function debug(string $message): void {
global $debug;
if ($debug) {
print 'DEBUG: ' . trim($message) . "\n";
}
}
/**
* Determines whether an SNMP request performed through Cacti core's SNMP
* library failed. Combines the failure signals core exposes: an exception
* recorded in the global $snmp_error, the 'U' unavailable marker (or
* false/null) returned by a failed GET or by a walk called with invalid
* parameters, and 'Timeout' text core may leave in a GET result without
* setting $snmp_error. A walk returns a parsed (possibly empty) array;
* an empty array is a successful empty result and is not treated as a
* failure. Used by the poller's collectors to count SNMP failures for
* their summary warning logs.
*
* @param mixed $result The value returned by cacti_snmp_get() or
* cacti_snmp_walk().
*
* @return bool True if the request failed, false otherwise.
*
* @global string $snmp_error The last SNMP error message set by Cacti
* core's SNMP library.
*/
function hmib_snmp_request_failed($result): bool {
global $snmp_error;
if (!empty($snmp_error)) {
return true;
}
if ($result === false || $result === null || $result === 'U') {
return true;
}
// A GET can return timeout text without setting $snmp_error; a walk
// returns a parsed array where empty means a successful empty result.
if (is_string($result)) {
return stripos($result, 'Timeout') !== false;
}
return false;
}
/**
* Scans every enabled, SNMP-capable Cacti host to detect which ones
* support the Host Resources MIB, registering each supported host in
* plugin_hmib_hrSystem. Acquires a simple process lock (via
* plugin_hmib_processes) for the duration of the scan and records the
* last-run time when finished. Called from process_hosts() when
* autodiscovery is due to run.
*
* @return bool Always true.
*
* @global bool $debug Whether debug output is enabled (declared
* but not directly used here; debug() reads
* it itself).
* @global int $snmp_errors Accumulates the number of SNMP query
* failures encountered during the scan, for
* the summary warning logged at the end.
*/
function autoDiscoverHosts(): bool {
global $debug, $snmp_errors;
$hosts = db_fetch_assoc("SELECT *
FROM host
WHERE snmp_version>0
AND disabled!='on'
AND status!=1");
debug("Starting AutoDiscovery for '" . sizeof($hosts) . "' Hosts");
// set a process lock
db_execute('REPLACE INTO plugin_hmib_processes (pid, taskid) VALUES (' . getmypid() . ', 0)');
$snmp_errors = 0;
if (cacti_sizeof($hosts)) {
foreach ($hosts as $host) {
debug("AutoDiscovery Check for Host '" . $host['description'] . '[' . $host['hostname'] . "]'");
$hostMib = cacti_snmp_walk($host['hostname'], $host['snmp_community'], '.1.3.6.1.2.1.25.1', $host['snmp_version'],
$host['snmp_username'], $host['snmp_password'],
$host['snmp_auth_protocol'], $host['snmp_priv_passphrase'], $host['snmp_priv_protocol'],
$host['snmp_context'], $host['snmp_port'], $host['snmp_timeout'],
read_config_option('snmp_retries'), $host['max_oids']);
if (hmib_snmp_request_failed($hostMib)) {
$snmp_errors++;
}
$system = cacti_snmp_get($host['hostname'], $host['snmp_community'], '.1.3.6.1.2.1.1.1.0', $host['snmp_version'],
$host['snmp_username'], $host['snmp_password'],
$host['snmp_auth_protocol'], $host['snmp_priv_passphrase'], $host['snmp_priv_protocol'],
$host['snmp_context'], $host['snmp_port'], $host['snmp_timeout'],
read_config_option('snmp_retries'));
if (hmib_snmp_request_failed($system)) {
$snmp_errors++;
}
if (cacti_sizeof($hostMib)) {
$add = true;
if ($add) {
debug("Host '" . $host['description'] . '[' . $host['hostname'] . "]' Supports Host MIB Resources");
db_execute('INSERT INTO plugin_hmib_hrSystem
(host_id) VALUES (' . $host['id'] . ')
ON DUPLICATE KEY UPDATE host_id=VALUES(host_id)');
}
}
}
}
if ($snmp_errors > 0) {
cacti_log("WARNING: There were $snmp_errors SNMP errors while performing autoDiscover data", false, 'HMIB', POLLER_VERBOSITY_MEDIUM);
}
// remove the process lock
db_execute('DELETE FROM plugin_hmib_processes WHERE pid=' . getmypid());
db_execute("REPLACE INTO settings (name,value) VALUES ('hmib_autodiscovery_lastrun', '" . time() . "')");
return true;
}
/**
* Master process orchestrating a full Host MIB collection cycle: runs
* autodiscovery when due, purges stale process locks, then launches a
* background per-host collector process (process_host()) for every
* discovered Host MIB device, respecting the configured concurrency
* limit, and waits for all of them to finish. Once complete, updates
* per-collector last-run timestamps, purges data for hosts removed from
* Cacti (when auto-purge is enabled), recomputes summary statistics
* (CPU/memory/swap) in plugin_hmib_hrSystem, re-detects host OS types,
* and launches the graph automation process. Called from this script's
* main flow when run with the '-M' (main run) flag.
*
* @return void
*
* @global float $start The run's start time (from microtime(true)),
* used to decide which sub-collectors are due and
* to compute overall run duration.
* @global mixed $seed A random value identifying this run, used to tag
* and track the per-host collector processes it
* launches.
*/
function process_hosts(): void {
global $start, $seed;
print "NOTE: Processing Hosts Begins\n";
/* All time/dates will be stored in timestamps
* Get Autodiscovery Lastrun Information
*/
$auto_discovery_lastrun = read_config_option('hmib_autodiscovery_lastrun');
// Get Collection Frequencies (in seconds)
$auto_discovery_freq = read_config_option('hmib_autodiscovery_freq');
// Set the booleans based upon current times
if (read_config_option('hmib_autodiscovery') == 'on') {
print "NOTE: Auto Discovery Starting\n";
if (runCollector($start, $auto_discovery_lastrun, $auto_discovery_freq)) {
autoDiscoverHosts();
}
print "NOTE: Auto Discovery Complete\n";
}
// Purge collectors that run longer than 10 minutes
db_execute('DELETE FROM plugin_hmib_processes WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(started)) > 600');
// Do not process collectors are still running
if (db_fetch_cell('SELECT count(*) FROM plugin_hmib_processes') > 0) {
print "WARNING: Another Host Mib Collector is still running! Exiting\n";
exit(0);
}
/* The hosts to scan will
* 1) Not be disabled,
* 2) Be linked to the host table
* 3) Be up and operational
*/
$hosts = db_fetch_assoc("SELECT hm.host_id, host.description, host.hostname FROM plugin_hmib_hrSystem AS hm
INNER JOIN host
ON host.id=hm.host_id
WHERE host.disabled!='on'
AND host.status!=1");
// Remove entries from down and disabled hosts
db_execute("DELETE FROM plugin_hmib_hrSWRun
WHERE host_id IN(
SELECT id
FROM host
WHERE disabled='on'
OR host.status=1
)");
db_execute("DELETE FROM plugin_hmib_hrDevices
WHERE host_id IN(
SELECT id
FROM host
WHERE disabled='on'
OR host.status=1
)");
db_execute("DELETE FROM plugin_hmib_hrStorage
WHERE host_id IN(
SELECT id
FROM host
WHERE disabled='on'
OR host.status=1
)");
db_execute("DELETE FROM plugin_hmib_hrProcessor
WHERE host_id IN(
SELECT id
FROM host
WHERE disabled='on'
OR host.status=1
)");
$concurrent_processes = read_config_option('hmib_concurrent_processes');
print "NOTE: Launching Collectors Starting\n";
$i = 0;
if (cacti_sizeof($hosts)) {
foreach ($hosts as $host) {
while (true) {
$processes = db_fetch_cell('SELECT COUNT(*) FROM plugin_hmib_processes');
if ($processes < $concurrent_processes) {
// put a placeholder in place to prevent overloads on slow systems
$key = rand();
db_execute("INSERT INTO plugin_hmib_processes (pid, taskid, started) VALUES ($key, $seed, NOW())");
print "NOTE: Launching Host Collector For: '" . $host['description'] . '[' . $host['hostname'] . "]'\n";
process_host($host['host_id'], $seed, $key);
usleep(10000);
break;
} else {
sleep(1);
}
}
}
}
// taking a break cause for slow systems slow
sleep(5);
print "NOTE: All Hosts Launched, proceeding to wait for completion\n";
// wait for all processes to end or max run time
while (true) {
$processes_left = db_fetch_cell("SELECT count(*) FROM plugin_hmib_processes WHERE taskid=$seed");
$pl = db_fetch_cell('SELECT count(*) FROM plugin_hmib_processes');
if ($processes_left == 0) {
print "NOTE: All Processes Complete, Exiting\n";
break;
} else {
print "NOTE: Waiting on '$processes_left' Processes\n";
sleep(2);
}
}
print "NOTE: Updating Last Run Statistics\n";
// Update the last runtimes
// All time/dates will be stored in timestamps;
// Get Collector Lastrun Information
$hrDevices_lastrun = read_config_option('hmib_hrDevices_lastrun');
$hrSWRun_lastrun = read_config_option('hmib_hrSWRun_lastrun');
$hrSWRunPerf_lastrun = read_config_option('hmib_hrSWRunPerf_lastrun');
$hrSWInstalled_lastrun = read_config_option('hmib_hrSWInstalled_lastrun');
$hrStorage_lastrun = read_config_option('hmib_hrStorage_lastrun');
$hrProcessor_lastrun = read_config_option('hmib_hrProcessor_lastrun');
// Get Collection Frequencies (in seconds)
$hrDevices_freq = read_config_option('hmib_hrDevices_freq');
$hrSWRun_freq = read_config_option('hmib_hrSWRun_freq');
$hrSWRunPerf_freq = read_config_option('hmib_hrSWRunPerf_freq');
$hrSWInstalled_freq = read_config_option('hmib_hrSWInstalled_freq');
$hrStorage_freq = read_config_option('hmib_hrStorage_freq');
$hrProcessor_freq = read_config_option('hmib_hrProcessor_freq');
// set the collector statistics
if (runCollector($start, $hrDevices_lastrun, $hrDevices_freq)) {
db_execute("REPLACE INTO settings (name,value) VALUES ('hmib_hrDevices_lastrun', '$start')");
}
if (runCollector($start, $hrSWRun_lastrun, $hrSWRun_freq)) {
db_execute("REPLACE INTO settings (name,value) VALUES ('hmib_hrSWRun_lastrun', '$start')");
}
if (runCollector($start, $hrSWRunPerf_lastrun, $hrSWRunPerf_freq)) {
db_execute("REPLACE INTO settings (name,value) VALUES ('hmib_hrSWRunPerf_lastrun', '$start')");
}
if (runCollector($start, $hrSWInstalled_lastrun, $hrSWInstalled_freq)) {
db_execute("REPLACE INTO settings (name,value) VALUES ('hmib_hrSWInstalled_lastrun', '$start')");
}
if (runCollector($start, $hrStorage_lastrun, $hrStorage_freq)) {
db_execute("REPLACE INTO settings (name,value) VALUES ('hmib_hrStorage_lastrun', '$start')");
}
if (runCollector($start, $hrProcessor_lastrun, $hrProcessor_freq)) {
db_execute("REPLACE INTO settings (name,value) VALUES ('hmib_hrProcessor_lastrun', '$start')");
}
if (read_config_option('hmib_autopurge') == 'on') {
print "NOTE: Auto Purging Hosts\n";
$dead_hosts = db_fetch_assoc('SELECT host_id FROM plugin_hmib_hrSystem AS hr
LEFT JOIN host
ON host.id=hr.host_id
WHERE host.id IS NULL');
if (cacti_sizeof($dead_hosts)) {
foreach ($dead_hosts as $host) {
db_execute('DELETE FROM plugin_hmib_hrSystem WHERE host_id=' . $host['host_id']);
db_execute('DELETE FROM plugin_hmib_hrSWRun WHERE host_id=' . $host['host_id']);
db_execute('DELETE FROM plugin_hmib_hrSWRun_last_seen WHERE host_id=' . $host['host_id']);
db_execute('DELETE FROM plugin_hmib_hrDevices WHERE host_id=' . $host['host_id']);
db_execute('DELETE FROM plugin_hmib_hrStorage WHERE host_id=' . $host['host_id']);
db_execute('DELETE FROM plugin_hmib_hrProcessor WHERE host_id=' . $host['host_id']);
db_execute('DELETE FROM plugin_hmib_hrSWInstalled WHERE host_id=' . $host['host_id']);
print "Purging Host with ID '" . $host['host_id'] . "'\n";
}
}
}
print "NOTE: Updating Summary Statistics for Each Host\n";
// update some statistics in hrSystem
$stats = db_fetch_assoc('SELECT
host.id AS host_id,
host.status AS host_status,
AVG(`load`) AS cpuPercent,
COUNT(`load`) AS numCpus
FROM host
INNER JOIN plugin_hmib_hrSystem AS hrs
ON host.id=hrs.host_id
LEFT JOIN plugin_hmib_hrProcessor AS hrp
ON hrp.host_id=hrs.host_id
GROUP BY host.id, host.status');
if (cacti_sizeof($stats)) {
$sql_insert = '';
$sql_prefix = 'INSERT INTO plugin_hmib_hrSystem
(host_id, host_status, cpuPercent, numCpus) VALUES ';
$sql_suffix = ' ON DUPLICATE KEY UPDATE
host_status=VALUES(host_status),
cpuPercent=VALUES(cpuPercent),
numCpus=VALUES(numCpus)';
$j = 0;
foreach ($stats as $s) {
$sql_insert .= (strlen($sql_insert) ? ', ' : '') . '(' .
$s['host_id'] . ', ' .
$s['host_status'] . ', ' .
(!empty($s['cpuPercent']) ? $s['cpuPercent'] : '0') . ', ' .
(!empty($s['numCpus']) ? $s['numCpus'] : '0') . ')';
$j++;
if (($j % 200) == 0) {
db_execute($sql_prefix . $sql_insert . $sql_suffix);
$sql_insert = '';
}
}
if (strlen($sql_insert)) {
db_execute($sql_prefix . $sql_insert . $sql_suffix);
}
}
// update the memory information
db_execute('INSERT INTO plugin_hmib_hrSystem
(host_id, memSize, memUsed, swapSize, swapUsed)
SELECT host_id,
SUM(CASE WHEN type=12 THEN size * allocationUnits ELSE 0 END) AS memSize,
SUM(CASE WHEN type=12 AND size > 0 THEN (used / size) * 100 ELSE 0 END) AS memUsed,
SUM(CASE WHEN type=13 THEN size * allocationUnits ELSE 0 END) AS swapSize,
SUM(CASE WHEN type=13 AND size > 0 THEN (used / size) * 100 ELSE 0 END) AS swapUsed
FROM plugin_hmib_hrStorage
WHERE type IN(12,13)
GROUP BY host_id
ON DUPLICATE KEY UPDATE
memSize=VALUES(memSize),
memUsed=VALUES(memUsed),
swapSize=VALUES(swapSize),
swapUsed=VALUES(swapUsed)');
print "NOTE: Detecting Host Types Based Upon Host Types Table\n";
$types = db_fetch_assoc('SELECT * FROM plugin_hmib_hrSystemTypes');
if (cacti_sizeof($types)) {
foreach ($types as $t) {
db_execute_prepared('UPDATE plugin_hmib_hrSystem AS hrs SET host_type = ?
WHERE hrs.sysDescr LIKE ?
AND hrs.sysObjectID LIKE ?',
[$t['id'], '%' . $t['sysDescrMatch'] . '%', $t['sysObjectID'] . '%']);
}
}
// for hosts that are down, clear information
db_execute('UPDATE plugin_hmib_hrSystem
SET users=0, cpuPercent=0, processes=0, memUsed=0, swapUsed=0, uptime=0, sysUptime=0
WHERE host_status IN (0,1)');
// take time and log performance data
$end = microtime(true);
$cacti_stats = sprintf(
'Time:%0.2f ' .
'Processes:%s ' .
'Hosts:%s',
round($end - $start,2),
$concurrent_processes,
sizeof($hosts));
// log to the database
db_execute("REPLACE INTO settings (name,value) VALUES ('stats_hmib', '" . $cacti_stats . "')");
// log to the logfile
cacti_log('HMIB STATS: ' . $cacti_stats , true, 'SYSTEM');
print "NOTE: Host Mib Polling Completed, $cacti_stats\n";
// launch the graph creation process
process_graphs();
}
/**
* Launches a background poller_hmib.php worker process to collect data
* for a single host. Called from process_hosts() for each discovered
* Host MIB device, respecting the configured concurrency limit.
*
* @param int $host_id The host id to collect data for.
* @param mixed $seed The current run's seed value, used to tag the
* launched process.
* @param mixed $key The placeholder process-lock key to pass
* through so the worker can remove it once it
* registers its own lock.
*
* @return void
*
* @global array $config Cacti global configuration array; used to
* resolve the PHP binary and this plugin's
* poller script path.
* @global bool $debug Whether debug output is enabled, propagated
* to the worker via '--debug'.
* @global float $start The current run's start time, propagated to
* the worker via '--start'.
* @global bool $forcerun Whether this run was forced, propagated to
* the worker via '--force'.
*/
function process_host(int $host_id, $seed, $key): void {
global $config, $debug, $start, $forcerun;
exec_background(read_config_option('path_php_binary'),' -q ' .
$config['base_path'] . '/plugins/hmib/poller_hmib.php' .
' --host-id=' . $host_id .
' --start=' . $start .
' --seed=' . $seed .
' --key=' . $key .
($forcerun ? ' --force' : '') .
($debug ? ' --debug' : ''));
}
/**
* Launches a background poller_graphs.php process to run graph
* automation once all per-host data collection has completed. Called
* from process_hosts() at the end of a collection cycle.
*
* @return void
*
* @global array $config Cacti global configuration array; used to
* resolve the PHP binary and poller_graphs.php
* path.
* @global bool $debug Whether debug output is enabled, propagated
* via '--debug'.
* @global float $start Reserved/declared for parity with
* process_host(); not used directly here.
* @global bool $forcerun Whether this run was forced, propagated via
* '--force'.
*/
function process_graphs(): void {
global $config, $debug, $start, $forcerun;
exec_background(read_config_option('path_php_binary'),' -q ' .
$config['base_path'] . '/plugins/hmib/poller_graphs.php' .
($forcerun ? ' --force' : '') .
($debug ? ' --debug' : ''));
}
/**
* Runs the full set of per-host Host MIB collectors for a single device
* (system info, devices, running processes and their performance,
* installed software, storage, processor), each only when its own
* configured collection interval is due. Called from this script's main
* flow when run with a specific '--host-id' (i.e. as a per-host worker
* launched by process_host()).
*
* @param int $host_id The host id to collect data for.
*
* @return void
*
* @global array $config Cacti global configuration array (declared
* but not directly used here).
* @global float $start The current run's start time, used to
* decide which sub-collectors are due.
* @global mixed $seed The current run's seed value, used to
* register this worker's process lock.
* @global mixed $key The placeholder process-lock key from the
* launching process_host() call, removed
* once this worker registers its own lock.
* @global int $snmp_errors Reset and accumulated here to track SNMP
* query failures during this host's
* collection.
*/
function checkHost(int $host_id): void {
global $config, $start, $seed, $key, $snmp_errors;
$snmp_errors = 0;
// All time/dates will be stored in timestamps;
// Get Collector Lastrun Information
$hrDevices_lastrun = read_config_option('hmib_hrDevices_lastrun');
$hrSWRun_lastrun = read_config_option('hmib_hrSWRun_lastrun');
$hrSWRunPerf_lastrun = read_config_option('hmib_hrSWRunPerf_lastrun');
$hrSWInstalled_lastrun = read_config_option('hmib_hrSWInstalled_lastrun');
$hrStorage_lastrun = read_config_option('hmib_hrStorage_lastrun');
$hrProcessor_lastrun = read_config_option('hmib_hrProcessor_lastrun');
// Get Collection Frequencies (in seconds)
$hrDevices_freq = read_config_option('hmib_hrDevices_freq');
$hrSWRun_freq = read_config_option('hmib_hrSWRun_freq');
$hrSWRunPerf_freq = read_config_option('hmib_hrSWRunPerf_freq');
$hrSWInstalled_freq = read_config_option('hmib_hrSWInstalled_freq');
$hrStorage_freq = read_config_option('hmib_hrStorage_freq');
$hrProcessor_freq = read_config_option('hmib_hrProcessor_freq');
// remove the key process and insert the set a process lock
if ($key != '') {
db_execute("DELETE FROM plugin_hmib_processes WHERE pid=$key");
}
db_execute('REPLACE INTO plugin_hmib_processes (pid, taskid) VALUES (' . getmypid() . ", $seed)");
// obtain host information
$host = db_fetch_row_prepared('SELECT *
FROM host WHERE id = ?',
[$host_id]);
if (is_array($host) && cacti_sizeof($host)) {
// Run the collectors
cacti_log(sprintf('Running Device System Info Collection for Device[%s]', $host['id']), false, 'HMIB', POLLER_VERBOSITY_MEDIUM);
collect_hrSystem($host);
if (runCollector($start, $hrDevices_lastrun, $hrDevices_freq)) {
cacti_log(sprintf('Running Device Collection for Device[%s]', $host['id']), false, 'HMIB', POLLER_VERBOSITY_MEDIUM);
collect_hrDevices($host);
}
if (runCollector($start, $hrSWRun_lastrun, $hrSWRun_freq)) {
cacti_log(sprintf('Running Running Process Collection for Device[%s]', $host['id']), false, 'HMIB', POLLER_VERBOSITY_MEDIUM);
collect_hrSWRun($host);
}
if (runCollector($start, $hrSWRunPerf_lastrun, $hrSWRunPerf_freq)) {
cacti_log(sprintf('Running Running Process Performance Collection for Device[%s]', $host['id']), false, 'HMIB', POLLER_VERBOSITY_MEDIUM);
collect_hrSWRunPerf($host);
}
if (runCollector($start, $hrSWInstalled_lastrun, $hrSWInstalled_freq)) {
cacti_log(sprintf('Running Software Install Collection for Device[%s]', $host['id']), false, 'HMIB', POLLER_VERBOSITY_MEDIUM);
collect_hrSWInstalled($host);
}
if (runCollector($start, $hrStorage_lastrun, $hrStorage_freq)) {
cacti_log(sprintf('Running Storage Collection for Device[%s]', $host['id']), false, 'HMIB', POLLER_VERBOSITY_MEDIUM);
collect_hrStorage($host);
}
if (runCollector($start, $hrProcessor_lastrun, $hrProcessor_freq)) {
cacti_log(sprintf('Running Processor Collection for Device[%s]', $host['id']), false, 'HMIB', POLLER_VERBOSITY_MEDIUM);
collect_hrProcessor($host);
}
// compensate for batch systems
$time = substr((string) time(), 0, 3);
// update the most recent table
db_execute_prepared('INSERT INTO plugin_hmib_hrSWRun_last_seen (host_id, name, total_time)
SELECT DISTINCT host_id, name, ' . read_config_option('hmib_hrSWRunPerf_freq') . " AS `total_time`
FROM plugin_hmib_hrSWRun
WHERE host_id = ?
AND name NOT LIKE '$time%'
ON DUPLICATE KEY UPDATE
last_seen=NOW(),
total_time=total_time+VALUES(total_time)",
[$host['id']]);
// remove the process lock
db_execute_prepared('DELETE FROM plugin_hmib_processes
WHERE pid = ?',
[getmypid()]);
// remove odd entries
db_execute("DELETE FROM plugin_hmib_hrSWRun_last_seen WHERE name='' OR name LIKE '$time%'");
if ($snmp_errors > 0) {
cacti_log("WARNING: Device[$host_id] experienced $snmp_errors SNMP Errors while performing data. Increase logging to HIGH to see errors.", false, 'HMIB');
}
}
}
/**
* Queries a device's Host Resources System group and MIB-II system
* group via SNMP, maps the returned OIDs to their plugin_hmib_hrSystem
* column names (parsing the date field specially), and updates the
* device's row with the collected values. Called from checkHost() for
* every device, on every run.
*
* @param array $host Reference, the Cacti host row to collect data for,
* providing SNMP connection settings.
*
* @return void
*
* @global array $hrSystem Map of OID => plugin_hmib_hrSystem column
* name, used to translate SNMP results into
* database columns.
* @global mixed $cnn_id Reserved/declared for parity with other
* collector functions in this file; not used
* directly here.
* @global int $snmp_errors Reserved/declared for parity with other
* collector functions in this file; not used
* directly here.
*/
function collect_hrSystem(array &$host): void {
global $hrSystem, $cnn_id, $snmp_errors;
if (cacti_sizeof($host)) {
debug("Polling hrSystem from '" . $host['description'] . '[' . $host['hostname'] . "]'");
$hostMib = cacti_snmp_walk($host['hostname'], $host['snmp_community'], '.1.3.6.1.2.1.25.1', $host['snmp_version'],
$host['snmp_username'], $host['snmp_password'],
$host['snmp_auth_protocol'], $host['snmp_priv_passphrase'], $host['snmp_priv_protocol'],
$host['snmp_context'], $host['snmp_port'], $host['snmp_timeout'],
read_config_option('snmp_retries'), $host['max_oids']);
if (hmib_snmp_request_failed($hostMib)) {
$snmp_errors++;
}
// A failed walk can return false/null; keep the merge operands arrays.
if (!is_array($hostMib)) {
$hostMib = array();
}
$systemMib = cacti_snmp_walk($host['hostname'], $host['snmp_community'], '.1.3.6.1.2.1.1', $host['snmp_version'],
$host['snmp_username'], $host['snmp_password'],
$host['snmp_auth_protocol'], $host['snmp_priv_passphrase'], $host['snmp_priv_protocol'],
$host['snmp_context'], $host['snmp_port'], $host['snmp_timeout'],
read_config_option('snmp_retries'), $host['max_oids']);
if (hmib_snmp_request_failed($systemMib)) {
$snmp_errors++;
}
if (!is_array($systemMib)) {
$systemMib = array();
}
$hostMib = array_merge($hostMib, $systemMib);
$set_string = '';
// Locate the values names
if (cacti_sizeof($hostMib)) {
foreach ($hostMib as $mib) {
// do some cleanup
if (substr($mib['oid'], 0, 1) != '.') {
$mib['oid'] = '.' . trim($mib['oid']);
}
if (substr($mib['value'], 0, 4) == 'OID:') {
$mib['value'] = str_replace('OID:', '', $mib['value']);
}
$key = array_search($mib['oid'], $hrSystem, true);
if ($key == 'date') {
$mib['value'] = hmib_dateParse($mib['value']);
}
if (!empty($key)) {
$set_string .= (strlen($set_string) ? ', ' : '') . $key . '=' . db_qstr(trim($mib['value']));
}
}
}
// Update the values
if (strlen($set_string)) {
db_execute("UPDATE plugin_hmib_hrSystem SET $set_string WHERE host_id=" . $host['id']);
}
}
}
/**
* Parses a Host Resources hrSystemDate-style comma-separated date/time
* string (dropping any sub-second fraction) into a MySQL-compatible
* 'Y-m-d H:i:s' string, falling back to the current time if the value
* can't be parsed. Called from collect_hrSystem() to normalize the
* sysUptime/system date field.
*
* @param string $value The raw date/time string returned by the device.
*
* @return string The normalized 'Y-m-d H:i:s' date/time string.
*/
function hmib_dateParse(string $value): string {
$value = explode(',', $value);
if (isset($value[1]) && strpos($value[1], '.')) {
$value[1] = substr($value[1], 0, (int) strpos($value[1], '.'));
}
$date1 = trim($value[0] . ' ' . ($value[1] ?? ''));
$time1 = strtotime($date1);
if ($time1 === false) {
$value = date('Y-m-d H:i:s');
} else {
$value = date('Y-m-d H:i:s', $time1);
}
return $value;
}
/**
* Splits a table entry's full OID into its base table OID and trailing
* index portion, at the last '.' separator. Called from
* collectHostIndexedOid() while processing walked table rows.
*
* @param string $oid The full OID (base + index) to split.
*
* @return array A two-element [base, index] array, or an empty array if
* $oid has no '.' separator.
*/
function hmib_splitBaseIndex(string $oid): array {
$splitIndex = [];
$oid = strrev($oid);
$pos = strpos($oid, '.');
if ($pos !== false) {
$index = strrev(substr($oid, 0, $pos));
$base = strrev(substr($oid, $pos + 1));
return [$base, $index];
} else {
return $splitIndex;
}
}
/**
* Generic Host Resources indexed-table collector: walks every OID column
* defined in a table's SNMP tree map for a device, reassembles the
* per-index rows, maps known type OIDs (via plugin_hmib_types) to their
* descriptions, and bulk-upserts the resulting rows into the target
* table, marking rows no longer present as absent rather than deleting
* them outright. Called from collect_hrSWRun()/collect_hrSWRunPerf()/
* collect_hrSWInstalled()/collect_hrStorage()/collect_hrProcessor()/
* collect_hrDevices() for each Host Resources table type.
*
* @param array $host Reference, the Cacti host row to collect data
* for, providing SNMP connection settings.
* @param array $tree Map of column name => OID defining the table's
* SNMP structure to walk.
* @param string $table The plugin_hmib_* database table to upsert the
* collected rows into.
* @param string $name A display name for this table, used in debug/log
* messages.
*
* @return void
*
* @global mixed $cnn_id Reserved/declared for parity with other
* collector functions in this file; not used
* directly here.
*/
function collectHostIndexedOid(array &$host, array $tree, string $table, string $name): void {
global $cnn_id, $snmp_errors;
static $types;
debug("Beginning Processing for '" . $host['description'] . '[' . $host['hostname'] . "]', Table '$name'");
if (!cacti_sizeof($types)) {
$types = array_rekey(db_fetch_assoc('SELECT id, oid, description FROM plugin_hmib_types'), 'oid', ['id', 'description']);
}