forked from Cacti/cacti
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpoller.php
More file actions
2566 lines (2160 loc) · 84 KB
/
poller.php
File metadata and controls
2566 lines (2160 loc) · 84 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
<?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/ |
+-------------------------------------------------------------------------+
*/
/**
* exec_poll - executes a command and returns its output
*
* @param (string) $command - the command to execute
*
* @return (string) the output of $command after execution
*/
function exec_poll($command) {
global $config;
if (function_exists('popen')) {
if ($config['cacti_server_os'] == 'unix') {
$fp = popen($command, 'r');
} else {
$fp = popen($command, 'rb');
}
/* return if the popen command was not successful */
if (!is_resource($fp)) {
cacti_log('WARNING; Problem with POPEN command.', false, 'POLLER');
return 'U';
}
$output = fgets($fp, 8192);
pclose($fp);
} else {
$output = `$command`;
}
return $output;
}
/**
* exec_poll_php - sends a command to the php script server and returns the output
*
* @param (string) $command - the command to send to the php script server
* @param (bool) $using_proc_function - whether or not this version of php is making use
* of the proc_open() and proc_close() functions (php 4.3+)
* @param (array) $pipes - the array of r/w pipes returned from proc_open()
* @param (resource) $proc_fd - the file descriptor returned from proc_open()
*
* @return (string) - the output of $command after execution against the php script
* server
*/
function exec_poll_php($command, $using_proc_function, $pipes, $proc_fd) {
global $config;
$output = '';
/* execute using php process */
if ($using_proc_function == 1) {
if (is_resource($proc_fd)) {
/* $pipes now looks like this:
* 0 => writeable handle connected to child stdin
* 1 => readable handle connected to child stdout
* 2 => any error output will be sent to child stderr */
/* send command to the php server */
fwrite($pipes[0], $command . "\r\n");
fflush($pipes[0]);
$output = fgets($pipes[1], 8192);
if (substr_count($output, 'ERROR') > 0) {
$output = 'U';
}
}
/* execute the old fashion way */
} else {
/* formulate command */
$command = read_config_option('path_php_binary') . ' ' . $command;
if (function_exists('popen')) {
if ($config['cacti_server_os'] == 'unix') {
$fp = popen($command, 'r');
} else {
$fp = popen($command, 'rb');
}
/* return if the popen command was not successful */
if (!is_resource($fp)) {
cacti_log('WARNING; Problem with POPEN command.', false, 'POLLER');
return 'U';
}
$output = fgets($fp, 8192);
pclose($fp);
} else {
$output = `$command`;
}
}
return $output;
}
/**
* exec_background - executes a program in the background so that php can continue
* to execute code in the foreground.
*
* @param (string) $filename - the full pathname to the script to execute
* @param (string) $args - any additional arguments that must be passed onto the executable
* @param (string) $redirect_args - any additional arguments for file re-direction. Otherwise output goes to /dev/null
*
* @return (void)
*/
function exec_background($filename, $args = '', $redirect_args = '') {
global $config, $debug;
if (is_array($args)) {
$args = implode(' ', array_map('cacti_escapeshellarg', $args));
}
if (is_array($redirect_args)) {
$redirect_args = '';
}
cacti_log("DEBUG: About to Spawn a Remote Process [CMD: $filename, ARGS: $args]", true, 'POLLER', ($debug ? POLLER_VERBOSITY_NONE:POLLER_VERBOSITY_DEBUG));
if (file_exists($filename)) {
if ($config['cacti_server_os'] == 'win32') {
if (!file_escaped($filename)) {
$filename = cacti_escapeshellcmd($filename);
}
if ($redirect_args == '') {
pclose(popen('start "Cactiplus" /I ' . $filename . ' ' . $args, 'r'));
} else {
pclose(popen('start "Cactiplus" /I ' . $filename . ' ' . $args . ' ' . $redirect_args, 'r'));
}
} elseif ($redirect_args == '') {
exec($filename . ' ' . $args . ' > /dev/null 2>&1 &');
} else {
exec($filename . ' ' . $args . ' ' . $redirect_args . ' &');
}
} elseif (file_exists_2gb($filename)) {
if ($redirect_args == '') {
exec($filename . ' ' . $args . ' > /dev/null 2>&1 &');
} else {
exec($filename . ' ' . $args . ' ' . $redirect_args . ' &');
}
}
}
/**
* exec_with_timeout - Execute a command and return it's output. Either wait until the
* command exits or the timeout has expired.
*
* @param (string) $cmd Command to execute.
* @param (string) $output A return array of output.
* @param (int) $return_code The return code from the script
* @param (int) $timeout Timeout in seconds.
*
* @return (string|bool) Either the last line of output or false on error
*/
function exec_with_timeout($cmd, &$output, &$return_code, $timeout = 5) {
// File descriptors passed to the process.
$descriptors = array(
0 => array('pipe', 'r'), // stdin
1 => array('pipe', 'w'), // stdout
2 => array('pipe', 'w') // stderr
);
// Start the process.
$process = proc_open('exec setsid ' . $cmd, $descriptors, $pipes);
if (!is_resource($process)) {
return false;
}
// Set the stdout stream to non-blocking.
stream_set_blocking($pipes[1], 0);
// Set the stderr stream to non-blocking.
stream_set_blocking($pipes[2], 0);
// Turn the timeout into microseconds.
$timeout = (int) $timeout * 1000000;
// Output buffer.
$buffer = '';
// While we have time to wait.
while ($timeout > 0) {
$start = microtime(true);
// Wait until we have output or the timer expired.
$read = array($pipes[1]);
$write = array();
$other = array();
stream_select($read, $write, $other, 0, $timeout);
// Get the status of the process.
// Do this before we read from the stream,
// this way we can't lose the last bit of output if the process dies between these functions.
$status = proc_get_status($process);
// Read the contents from the buffer.
// This function will always return immediately as the stream is non-blocking.
$buffer .= stream_get_contents($pipes[1]);
if (!$status['running']) {
// Break from this loop if the process exited before the timeout.
break;
}
// Subtract the number of microseconds that we waited.
$timeout -= (int) ((microtime(true) - $start) * 1000000);
}
// Check if there were any errors.
$errors = stream_get_contents($pipes[2]);
if (isset($status['exitcode'])) {
$return_code = $status['exitcode'];
} else {
$return_code = 1;
}
if (!empty($errors)) {
cacti_log('WARNING: exec_with_timeout stderr: ' . trim($errors), false, 'POLLER', POLLER_VERBOSITY_MEDIUM);
}
// Kill the process in case the timeout expired and it's still running.
// If the process already exited this won't do anything.
// Do not use a negative PID here because the child PID is not guaranteed
// to be the process-group ID on every platform/runtime combination.
if (isset($status['pid']) && $status['running'] && function_exists('posix_kill')) {
posix_kill($status['pid'], 9);
}
proc_terminate($process, 9);
// Close all streams.
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
if ($buffer != '') {
$output = explode("\n", $buffer);
return(end($output));
} else {
return;
}
}
function file_escaped($file) {
if (substr($file, 0, 1) == '"' && substr($file, -1, 1) == '"') {
return true;
}
return false;
}
/**
* file_exists_2gb - fail safe version of the file exists function to correct
* for errors in certain versions of php.
*
* @param (string) $filename - the name of the file to be tested.
*
* @return (int) 1 if the file exists otherwise 0
*/
function file_exists_2gb($filename) {
global $config;
$rval = 0;
if ($config['cacti_server_os'] != 'win32') {
system("test -f $filename", $rval);
return ($rval == 0);
} else {
return 0;
}
}
/**
* update_reindex_cache - builds a cache that is used by the poller to determine if the
* indexes for a particular data query/host have changed
*
* @param (int) $host_id - the id of the host to which the data query belongs
* @param (int) $data_query_id - the id of the data query to rebuild the reindex cache for
*
* @return (void)
*/
function update_reindex_cache($host_id, $data_query_id) {
global $config;
include_once($config['library_path'] . '/data_query.php');
include_once($config['library_path'] . '/snmp.php');
/* will be used to keep track of sql statements to execute later on */
$recache_stack = array();
$host = db_fetch_row_prepared('SELECT ' . SQL_NO_CACHE . ' *
FROM host
WHERE id = ?',
array($host_id));
$data_query = db_fetch_row_prepared('SELECT ' . SQL_NO_CACHE . ' *
FROM host_snmp_query
WHERE host_id = ?
AND snmp_query_id = ?',
array($host_id, $data_query_id));
$data_query_type = db_fetch_cell_prepared('SELECT ' . SQL_NO_CACHE . ' data_input.type_id
FROM data_input
INNER JOIN snmp_query
ON data_input.id = snmp_query.data_input_id
WHERE snmp_query.id = ?',
array($data_query_id));
$data_query_xml = get_data_query_array($data_query_id);
if (cacti_sizeof($data_query)) {
switch ($data_query['reindex_method']) {
case DATA_QUERY_AUTOINDEX_NONE:
break;
case DATA_QUERY_AUTOINDEX_BACKWARDS_UPTIME:
/* the uptime backwards method requires snmp, so make sure snmp is actually enabled
* on this device first */
if ($host['snmp_version'] > 0) {
if (isset($data_query_xml['oid_uptime'])) {
$oid_uptime = $data_query_xml['oid_uptime'];
} elseif (isset($data_query_xml['uptime_oid'])) {
$oid_uptime = $data_query_xml['uptime_oid'];
} else {
$oid_uptime = '.1.3.6.1.2.1.1.3.0';
}
$session = cacti_snmp_session($host['hostname'], $host['snmp_community'], $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_engine_id'], $host['snmp_port'],
$host['snmp_timeout'], $host['ping_retries'], $host['max_oids']);
if ($session !== false) {
if ($oid_uptime == '.1.3.6.1.2.1.1.3.0') {
$checks = array(
'.1.3.6.1.6.3.10.2.1.3.0',
'.1.3.6.1.2.1.1.3.0'
);
foreach($checks as $oid_uptime) {
$assert_value = cacti_snmp_session_get($session, $oid_uptime);
if (is_numeric($assert_value)) {
if ($oid_uptime == '.1.3.6.1.6.3.10.2.1.3.0') {
$assert_value *= 100;
}
break;
}
}
$oid_uptime = '.1.3.6.1.2.1.1.3.0';
} else {
$assert_value = cacti_snmp_session_get($session, $oid_uptime);
}
}
$session->close();
$recache_stack[] = "('$host_id', '$data_query_id'," . POLLER_ACTION_SNMP . ", '<', '$assert_value', '$oid_uptime', 1)";
}
break;
case DATA_QUERY_AUTOINDEX_INDEX_NUM_CHANGE:
/* this method requires that some command/oid can be used to determine the
* current number of indexes in the data query
* pay ATTENTION to quoting!
* the script parameters are usually enclosed in single tics: '
* so we have to enclose the whole list of parameters in double tics: "
* */
/* the assert_value counts the number of distinct indexes currently available in host_snmp_cache
* we do NOT make use of <oid_num_indexes> or the like!
* this works, even if no <oid_num_indexes> was given
*/
$assert_value = cacti_sizeof(db_fetch_assoc_prepared('SELECT DISTINCT ' . SQL_NO_CACHE . ' snmp_index
FROM host_snmp_cache
WHERE host_id = ?
AND snmp_query_id = ?
AND snmp_index != ""',
array($host_id, $data_query_id)));
/* now, we have to build the (list of) commands that are later used on a recache event
* the result of those commands will be compared to the assert_value we have just computed
* on a comparison failure, a reindex event will be generated
*/
switch ($data_query_type) {
case DATA_INPUT_TYPE_SNMP_QUERY:
if (isset($data_query_xml['oid_num_indexes'])) { /* we have a specific OID for counting indexes */
$recache_stack[] = "($host_id, $data_query_id," . POLLER_ACTION_SNMP . ", '=', " . db_qstr($assert_value) . ", " . db_qstr($data_query_xml['oid_num_indexes']) . ", 1)";
} else { /* count all indexes found */
$recache_stack[] = "($host_id, $data_query_id, " . POLLER_ACTION_SNMP_COUNT . ", '=', " . db_qstr($assert_value) . ", " . db_qstr($data_query_xml['oid_index']) . ", 1)";
}
break;
case DATA_INPUT_TYPE_SCRIPT_QUERY:
if (isset($data_query_xml['arg_num_indexes'])) { /* we have a specific request for counting indexes */
/* escape path (windows!) and parameters for use with database sql; TODO: replace by db specific escape function like mysql_real_escape_string? */
$recache_stack[] = "($host_id, $data_query_id, " . POLLER_ACTION_SCRIPT . ", '=', " . db_qstr($assert_value) . ", " . db_qstr(get_script_query_path((isset($data_query_xml['arg_prepend']) ? $data_query_xml['arg_prepend'] . ' ': '') . $data_query_xml['arg_num_indexes'], $data_query_xml['script_path'], $host_id)) . ", 1)";
} else { /* count all indexes found */
/* escape path (windows!) and parameters for use with database sql; TODO: replace by db specific escape function like mysql_real_escape_string? */
$recache_stack[] = "($host_id, $data_query_id, " . POLLER_ACTION_SCRIPT_COUNT . ", '=', " . db_qstr($assert_value) . ", " . db_qstr(get_script_query_path((isset($data_query_xml['arg_prepend']) ? $data_query_xml['arg_prepend'] . ' ': '') . $data_query_xml['arg_index'], $data_query_xml['script_path'], $host_id)) . ", 1)";
}
break;
case DATA_INPUT_TYPE_QUERY_SCRIPT_SERVER:
if (isset($data_query_xml['arg_num_indexes'])) { /* we have a specific request for counting indexes */
/* escape path (windows!) and parameters for use with database sql; TODO: replace by db specific escape function like mysql_real_escape_string? */
$recache_stack[] = "($host_id, $data_query_id, " . POLLER_ACTION_SCRIPT_PHP . ", '=', " . db_qstr($assert_value) . ", " . db_qstr(get_script_query_path($data_query_xml['script_function'] . ' ' . (isset($data_query_xml['arg_prepend']) ? $data_query_xml['arg_prepend'] . ' ': '') . $data_query_xml['arg_num_indexes'], $data_query_xml['script_path'], $host_id)) . ", 1)";
} else { /* count all indexes found */
# TODO: push the correct assert value
/* escape path (windows!) and parameters for use with database sql; TODO: replace by db specific escape function like mysql_real_escape_string? */
#$recache_stack[] = "($host_id, $data_query_id," . POLLER_ACTION_SCRIPT_PHP_COUNT . ", '=', " . db_qstr($assert_value) . ", " . db_qstr(get_script_query_path($data_query_xml['script_function'] . ' ' . (isset($data_query_xml['arg_prepend']) ? $data_query_xml['arg_prepend'] . ' ': '') . $data_query_xml['arg_index'], $data_query_xml['script_path'], $host_id)) . ", 1)";
# omit the assert value until we are able to run an 'index' command through script server
}
break;
}
break;
case DATA_QUERY_AUTOINDEX_FIELD_VERIFICATION:
$primary_indexes = db_fetch_assoc_prepared('SELECT ' . SQL_NO_CACHE . ' snmp_index, oid, field_value
FROM host_snmp_cache
WHERE host_id = ?
AND snmp_query_id = ?
AND field_name = ?',
array($host_id, $data_query_id, $data_query['sort_field']));
if (cacti_sizeof($primary_indexes) > 0) {
foreach ($primary_indexes as $index) {
$assert_value = $index['field_value'];
if ($data_query_type == DATA_INPUT_TYPE_SNMP_QUERY) {
$recache_stack[] = "($host_id, $data_query_id, " . POLLER_ACTION_SNMP . ", '=', " . db_qstr($assert_value) . ', ' . db_qstr(($data_query_xml['fields'][$data_query['sort_field']]['source'] == 'index') ? $data_query_xml['oid_index'] . '.' . $index['snmp_index']:$data_query_xml['fields'][$data_query['sort_field']]['oid'] . '.' . $index['snmp_index']) . ", 1)";
} elseif ($data_query_type == DATA_INPUT_TYPE_SCRIPT_QUERY) {
$recache_stack[] = '(' . $host_id . ', ' . $data_query_id . ', ' . POLLER_ACTION_SCRIPT . ", '=', " . db_qstr($assert_value) . ', ' . db_qstr(get_script_query_path((isset($data_query_xml['arg_prepend']) ? $data_query_xml['arg_prepend'] . ' ': '') . $data_query_xml['arg_get'] . ' ' . $data_query_xml['fields'][$data_query['sort_field']]['query_name'] . ' "' . $index['snmp_index'] . '"', $data_query_xml['script_path'], $host_id)) . ", 1)";
}
}
}
break;
}
}
if (cacti_sizeof($recache_stack)) {
poller_update_poller_reindex_from_buffer($host_id, $data_query_id, $recache_stack);
}
}
function poller_update_poller_reindex_from_buffer($host_id, $data_query_id, &$recache_stack) {
/* set all fields present value to 0, to mark the outliers when we are all done */
db_execute_prepared('UPDATE poller_reindex
SET present = 0
WHERE host_id = ?
AND data_query_id = ?',
array($host_id, $data_query_id));
/* setup the database call */
$sql_prefix = 'INSERT INTO poller_reindex (host_id, data_query_id, action, op, assert_value, arg1, present) VALUES';
$sql_suffix = ' ON DUPLICATE KEY UPDATE action=VALUES(action), op=VALUES(op), assert_value=VALUES(assert_value), present=VALUES(present)';
/* use a reasonable insert buffer, the default is 1MByte */
$max_packet = 256000;
/* setup some defaults */
$overhead = strlen($sql_prefix) + strlen($sql_suffix);
$buf_len = 0;
$buf_count = 0;
$buffer = '';
foreach($recache_stack AS $record) {
if ($buf_count == 0) {
$delim = ' ';
} else {
$delim = ', ';
}
$buffer .= $delim . $record;
$buf_len += strlen($record);
if (($overhead + $buf_len) > ($max_packet - 1024)) {
db_execute($sql_prefix . $buffer . $sql_suffix);
$buffer = '';
$buf_len = 0;
$buf_count = 0;
} else {
$buf_count++;
}
}
if ($buf_count > 0) {
db_execute($sql_prefix . $buffer . $sql_suffix);
}
/* remove stale records FROM the poller reindex */
db_execute_prepared('DELETE FROM poller_reindex
WHERE host_id = ?
AND data_query_id = ?
AND present = 0', array($host_id, $data_query_id));
poller_push_reindex_only_data_to_main($host_id, $data_query_id);
}
/**
* process_poller_output - grabs data from the 'poller_output' table and feeds the *completed*
* results to RRDtool for processing
*
* @param (resource) $rrdtool_pipe - the array of pipes containing the file descriptor for rrdtool
* @param (int) $remainder - don't use LIMIT if true
*
* @return (int) - The number of rrdfiles processed
*/
function process_poller_output(&$rrdtool_pipe, $remainder = 0) {
global $config, $debug;
static $rrd_field_names = array();
static $checked_bad = false;
include_once($config['library_path'] . '/rrd.php');
/* let's count the number of rrd files we processed */
$rrds_processed = 0;
$max_rows = 40000;
if ($remainder == 0) {
$remainder = $max_rows;
}
cacti_log("Processing Poller Output with $remainder maximum items to be processed", false, 'POLLER', POLLER_VERBOSITY_HIGH);
$limit = 'LIMIT ' . $max_rows;
/* create/update the rrd files */
$results = db_fetch_assoc("SELECT po.output, po.time,
UNIX_TIMESTAMP(po.time) as unix_time, po.local_data_id, dl.data_template_id,
pi.rrd_path, pi.rrd_name, pi.rrd_num
FROM poller_output AS po
INNER JOIN poller_item AS pi
ON po.local_data_id = pi.local_data_id
AND po.rrd_name = pi.rrd_name
INNER JOIN data_local AS dl
ON dl.id = po.local_data_id
ORDER BY po.local_data_id
$limit");
if (!cacti_sizeof($rrd_field_names)) {
$rrd_field_names = array_rekey(
db_fetch_assoc_prepared('SELECT ' . SQL_NO_CACHE . '
CONCAT(data_template_id, "_", data_name) AS keyname, data_source_names AS data_source_name
FROM poller_data_template_field_mappings'),
'keyname', array('data_source_name'));
}
if (cacti_sizeof($results)) {
/* create an array keyed off of each .rrd file */
foreach ($results as $item) {
/* trim the default characters, but add single and double quotes */
$value = $item['output'];
$unix_time = $item['unix_time'];
$rrd_path = $item['rrd_path'];
$rrd_name = $item['rrd_name'];
$local_data_id = $item['local_data_id'];
$data_template_id = $item['data_template_id'];
$rrd_tmpl = '';
$rrd_update_array[$rrd_path]['local_data_id'] = $local_data_id;
if ((is_numeric($value)) || ($value == 'U' && $rrd_name != '')) {
/* single one value output */
$rrd_update_array[$rrd_path]['times'][$unix_time][$rrd_name] = $value;
} elseif (is_hexadecimal($value)) {
/**
* special case of one value output: hexadecimal to decimal conversion
* attempt to accommodate 32bit and 64bit systems
*/
$value = str_replace(' ', '', $value);
if (strlen($value) <= 8 || ((2147483647+1) == intval(2147483647+1))) {
$rrd_update_array[$rrd_path]['times'][$unix_time][$rrd_name] = hexdec($value);
} elseif (function_exists('bcpow')) {
$dec = 0;
$vallen = strlen($value);
for ($i = 1; $i <= $vallen; $i++) {
$dec = bcadd($dec, bcmul(strval(hexdec($value[$i - 1])), bcpow('16', strval($vallen - $i))));
}
$rrd_update_array[$rrd_path]['times'][$unix_time][$rrd_name] = $dec;
} else {
$rrd_update_array[$rrd_path]['times'][$unix_time][$rrd_name] = 'U';
}
} elseif (strpos($value, ':') !== false) {
/* multiple value output */
$values = preg_split('/\s+/', $value);
if ($data_template_id > 0) {
$unused_data_source_names = array_rekey(
db_fetch_assoc_prepared('SELECT DISTINCT dtr.data_source_name, dtr.data_source_name
FROM data_template_rrd AS dtr
LEFT JOIN graph_templates_item AS gti
ON dtr.id = gti.task_item_id
WHERE dtr.local_data_id = ?
AND gti.task_item_id IS NULL',
array($local_data_id)),
'data_source_name', 'data_source_name'
);
} else {
$unused_data_source_names = array();
}
foreach($values as $value) {
$matches = explode(':', $value);
if (cacti_sizeof($matches) == 2) {
if (isset($rrd_field_names[$item['data_template_id'] . '_' . $matches[0]])) {
$field = $rrd_field_names[$item['data_template_id'] . '_' . $matches[0]]['data_source_name'];
if (cacti_sizeof($unused_data_source_names) && isset($unused_data_source_names[$field])) {
continue;
}
cacti_log("Parsed MULTI output field '" . $matches[0] . ':' . $matches[1] . "' [map " . $matches[0] . '->' . $field . ']' , true, 'POLLER', ($debug ? POLLER_VERBOSITY_NONE:POLLER_VERBOSITY_HIGH));
if (is_numeric($matches[1]) || ($matches[1] == 'U')) {
$rrd_update_array[$rrd_path]['times'][$unix_time][$field] = $matches[1];
} elseif ((function_exists('is_hexadecimal')) && (is_hexadecimal($matches[1]))) {
$rrd_update_array[$rrd_path]['times'][$unix_time][$field] = hexdec($matches[1]);
} else {
$rrd_update_array[$rrd_path]['times'][$unix_time][$field] = 'U';
}
$rrd_update_array[$rrd_path]['times'][$unix_time][$field] = $matches[1];
$rrd_tmpl .= ($rrd_tmpl != '' ? ':':'') . $field;
$rrd_update_array[$rrd_path]['template'] = $rrd_tmpl;
} else {
// Handle data source without a data template
if ($data_template_id > 0) {
$nt_rrd_field_names = array_rekey(
db_fetch_assoc_prepared('SELECT DISTINCT dtr.data_source_name, dif.data_name
FROM graph_templates_item AS gti
INNER JOIN data_template_rrd AS dtr
ON gti.task_item_id = dtr.id
INNER JOIN data_input_fields AS dif
ON dtr.data_input_field_id = dif.id
WHERE dtr.local_data_id = ?',
array($local_data_id)),
'data_name', 'data_source_name'
);
} else {
$nt_rrd_field_names = array_rekey(
db_fetch_assoc_prepared('SELECT DISTINCT dtr.data_source_name, dif.data_name
FROM data_template_rrd AS dtr
INNER JOIN data_input_fields AS dif
ON dtr.data_input_field_id = dif.id
WHERE dtr.local_data_id = ?',
array($local_data_id)),
'data_name', 'data_source_name'
);
}
if (cacti_sizeof($nt_rrd_field_names)) {
if (isset($nt_rrd_field_names[$matches[0]])) {
$field = $nt_rrd_field_names[$matches[0]];
if (cacti_sizeof($unused_data_source_names) && isset($unused_data_source_names[$field])) {
continue;
}
cacti_log("Parsed MULTI output field '" . $matches[0] . ':' . $matches[1] . "' [map " . $matches[0] . '->' . $field . ']' , true, 'POLLER', ($debug ? POLLER_VERBOSITY_NONE:POLLER_VERBOSITY_HIGH));
if (is_numeric($matches[1]) || ($matches[1] == 'U')) {
$rrd_update_array[$rrd_path]['times'][$unix_time][$field] = $matches[1];
} elseif ((function_exists('is_hexadecimal')) && (is_hexadecimal($matches[1]))) {
$rrd_update_array[$rrd_path]['times'][$unix_time][$field] = hexdec($matches[1]);
} else {
$rrd_update_array[$rrd_path]['times'][$unix_time][$field] = 'U';
}
$rrd_tmpl .= ($rrd_tmpl != '' ? ':':'') . $field;
}
}
$rrd_update_array[$rrd_path]['template'] = $rrd_tmpl;
}
}
}
} else {
if ($data_template_id > 0) {
$unused_data_source_names = array_rekey(
db_fetch_assoc_prepared('SELECT DISTINCT dtr.data_source_name, dtr.data_source_name
FROM data_template_rrd AS dtr
LEFT JOIN graph_templates_item AS gti
ON dtr.id = gti.task_item_id
WHERE dtr.local_data_id = ?
AND gti.task_item_id IS NULL',
array($local_data_id)),
'data_source_name', 'data_source_name'
);
$nt_rrd_field_names = array_rekey(
db_fetch_assoc_prepared('SELECT DISTINCT dtr.data_source_name, dif.data_name
FROM graph_templates_item AS gti
INNER JOIN data_template_rrd AS dtr
ON gti.task_item_id = dtr.id
INNER JOIN data_input_fields AS dif
ON dtr.data_input_field_id = dif.id
WHERE dtr.local_data_id = ?',
array($local_data_id)),
'data_name', 'data_source_name'
);
} else {
$unused_data_source_names = array();
$nt_rrd_field_names = array_rekey(
db_fetch_assoc_prepared('SELECT DISTINCT dtr.data_source_name, dif.data_name
FROM data_template_rrd AS dtr
INNER JOIN data_input_fields AS dif
ON dtr.data_input_field_id = dif.id
WHERE dtr.local_data_id = ?',
array($local_data_id)),
'data_name', 'data_source_name'
);
}
$expected = '';
if (cacti_sizeof($nt_rrd_field_names)) {
foreach($nt_rrd_field_names as $field) {
if (cacti_sizeof($unused_data_source_names) && isset($unused_data_source_names[$field])) {
continue;
}
$expected .= ($expected != '' ? ' ':'') . "$field:value";
$rrd_update_array[$rrd_path]['times'][$unix_time][$field] = 'U';
$rrd_tmpl .= ($rrd_tmpl != '' ? ':':'') . $field;
}
$rrd_update_array[$rrd_path]['template'] = $rrd_tmpl;
}
cacti_log(sprintf('WARNING: Invalid output! MULTI DS[%d] Encountered [%s] Expected[%s]', $item['local_data_id'], $value, $expected), false, 'POLLER');
}
/* fallback values */
if ((!isset($rrd_update_array[$rrd_path]['times'][$unix_time])) && ($rrd_name != '')) {
$rrd_update_array[$rrd_path]['times'][$unix_time][$rrd_name] = 'U';
} elseif ((!isset($rrd_update_array[$rrd_path]['times'][$unix_time])) && ($rrd_name == '')) {
unset($rrd_update_array[$rrd_path]);
}
}
/* make sure each .rrd file has complete data */
$k = 0;
$data_ids = array();
foreach ($results as $item) {
$unix_time = $item['unix_time'];
$rrd_path = $item['rrd_path'];
$rrd_name = $item['rrd_name'];
if (isset($rrd_update_array[$rrd_path]['times'][$unix_time])) {
/**
* Check to see if we have partial data sources. If so
* we did not get a full update, so we should not be removing
* those data sources from the $rrd_update_array yet.
*/
if ($item['rrd_num'] <= cacti_sizeof($rrd_update_array[$rrd_path]['times'][$unix_time])) {
$data_ids[] = $item['local_data_id'];
$k++;
if ($k % 10000 == 0) {
db_execute('DELETE FROM poller_output WHERE local_data_id IN (' . implode(',', $data_ids) . ')');
$data_ids = array();
$k = 0;
}
} else {
unset($rrd_update_array[$rrd_path]['times'][$unix_time]);
}
}
}
if ($k > 0) {
db_execute('DELETE FROM poller_output WHERE local_data_id IN (' . implode(',', $data_ids) . ')');
}
/* process dsstats information */
dsstats_poller_output($rrd_update_array);
dsdebug_poller_output($rrd_update_array);
api_plugin_hook_function('poller_output', $rrd_update_array);
if (boost_poller_on_demand($results)) {
$rrds_processed = rrdtool_function_update($rrd_update_array, $rrdtool_pipe);
}
$results = NULL;
$rrd_update_array = NULL;
/* to much records in poller_output, process in chunks */
$rows = db_fetch_cell('SELECT COUNT(local_data_id)
FROM poller_output');
/* to much records in poller_output, process in chunks */
if ($rows && $remainder == $max_rows) {
$running = db_fetch_cell('SELECT COUNT(*)
FROM poller_time
WHERE end_time = "0000-00-00"');
$rrds_processed += process_poller_output($rrdtool_pipe, $rows < $max_rows ? $rows : $max_rows);
if ($running == 0 && !$checked_bad) {
// Remove recently deleted items from the poller_output table
db_execute('DELETE FROM poller_output WHERE local_data_id NOT IN (SELECT id FROM data_local)');
// Identify data sources that are somehow not aligned
$items = db_fetch_assoc('SELECT rrd_num,
COUNT(DISTINCT po.local_data_id, po.rrd_name) AS ids, dt.name, dl.host_id,
GROUP_CONCAT(DISTINCT po.local_data_id) AS local_data_ids
FROM poller_output AS po
LEFT JOIN poller_item AS pi
ON po.local_data_id = pi.local_data_id
LEFT JOIN data_local AS dl
ON po.local_data_id = dl.id
LEFT JOIN data_template AS dt
ON dl.data_template_id = dt.id
GROUP BY po.local_data_id
HAVING rrd_num IS NULL OR rrd_num != ids
ORDER BY dt.name');
if (cacti_sizeof($items)) {
cacti_log(sprintf('WARNING: There are %s Data Sources not returning all data leaving rows in the poller output table. Details to follow.', cacti_sizeof($items)), false, 'POLLER');
$prevName = '';
foreach($items as $item) {
if ($prevName != $item['name']) {
cacti_log(sprintf('WARNING: Data Template \'%s\' is impacted by lack of complete information', $item['name']), false, 'POLLER');
$prevName = $item['name'];
db_execute('DELETE FROM poller_output WHERE local_data_id IN(' . $item['local_data_ids'] . ')');
}
}
}
$checked_bad = true;
}
}
}
return $rrds_processed;
}
/**
* update_resource_cache - place the cacti website in the poller_resource_cache
* for remote pollers to consume
*
* @param (int) $poller_id - The id of the poller. 1 is the main system
*
* @return (void)
*/
function update_resource_cache($poller_id = 1) {
global $config, $remote_db_cnn_id;
if ($config['cacti_server_os'] == 'win32') return;
if ($poller_id == 1) {
$conn = false;
} else {
$conn = $remote_db_cnn_id;
}
$mpath = $config['base_path'];
$spath = $config['scripts_path'];
$rpath = $config['resource_path'];
$excluded_extensions = array('tar', 'gz', 'zip', 'tgz', 'ttf', 'z', 'exe', 'pack', 'swp', 'swo');
$excluded_dirs = array('.git', 'log', '.gitattributes', '.github');
$paths = array(
'base' => array('recursive' => false, 'path' => $mpath),
'scripts' => array('recursive' => true, 'path' => $spath),
'resource' => array('recursive' => true, 'path' => $rpath),
'lib' => array('recursive' => true, 'path' => $mpath . '/lib'),
'include' => array('recursive' => true, 'path' => $mpath . '/include'),
'install' => array('recursive' => true, 'path' => $mpath . '/install'),
'formats' => array('recursive' => true, 'path' => $mpath . '/formats'),
'locales' => array('recursive' => true, 'path' => $mpath . '/locales'),
'images' => array('recursive' => true, 'path' => $mpath . '/images'),
'mibs' => array('recursive' => true, 'path' => $mpath . '/mibs'),
'cli' => array('recursive' => true, 'path' => $mpath . '/cli')
);
$pollers = db_fetch_cell('SELECT COUNT(*) FROM poller WHERE disabled=""', '', true, $conn);
if ($poller_id == 1 && $pollers > 1) {
foreach($paths as $type => $path) {
if (is_readable($path['path'])) {
$pathinfo = pathinfo($path['path']);
if (isset($pathinfo['extension'])) {
$extension = strtolower($pathinfo['extension']);
} else {
$extension = '';
}
/* exclude spurious extensions directories */
$exclude = false;
if (array_search($extension, $excluded_extensions, true) !== false) {
$exclude = true;
}
if (array_search(basename($path['path']), $excluded_dirs, true) !== false) {
$exclude = true;
}
if (!$exclude) {
cache_in_path($path['path'], $type, $path['recursive']);
}
} else {
cacti_log("ERROR: Unable to read the " . $type . " path '" . $path['path'] . "'", false, 'REPLICATE');
}
}
/* handle plugin paths */
$files_and_dirs = array_diff(scandir($mpath . '/plugins'), array('..', '.'));
if (cacti_sizeof($files_and_dirs)) {
foreach($files_and_dirs as $path) {
if (is_dir($mpath . '/plugins/' . $path)) {
if (file_exists($mpath . '/plugins/' . $path . '/INFO')) {
$info = parse_ini_file($mpath . '/plugins/' . $path . '/INFO', true);
$dir_exclusions = array('..', '.', '.git', '.github', '.gitattributes');
$file_exclusions = $excluded_extensions;
if (isset($info['info']['nosync'])) {
$exclude_paths = explode(',', $info['info']['nosync']);
if (cacti_sizeof($exclude_paths)) {
foreach($exclude_paths as $epath) {
if (strpos($epath, '*.') !== false) {
$file_exclusions[] = trim(str_replace('*.', '', $epath));
} else {
$dir_exclusions[] = trim($epath);
}
}
}
}
$fod = array_diff(scandir($mpath . '/plugins/' . $path), $dir_exclusions);
if (cacti_sizeof($fod)) {
foreach($fod as $file_or_dir) {
$fpath = $mpath . '/plugins/' . $path . '/' . $file_or_dir;
if (is_dir($fpath)) {
cache_in_path($fpath, $path . '_' . basename($file_or_dir), true);
} else {
$pathinfo = pathinfo($fpath);
if (isset($pathinfo['extension'])) {
$extension = strtolower($pathinfo['extension']);
} else {
$extension = '';
}
/* exclude spurious extensions */
$exclude = false;
if (array_search($extension, $file_exclusions, true) !== false) {
$exclude = true;
}
if (!$exclude) {
cache_in_path($fpath, 'plugins', false);
}
}
}
}