-
-
Notifications
You must be signed in to change notification settings - Fork 411
/
Copy pathrrd.php
4766 lines (3911 loc) · 169 KB
/
rrd.php
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-2024 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/ |
+-------------------------------------------------------------------------+
*/
define('RRD_NL', " \\\n");
define('MAX_FETCH_CACHE_SIZE', 5);
if (read_config_option('storage_location')) {
/* load crypt libraries only if the Cacti RRDtool Proxy Server is in use */
set_include_path(CACTI_PATH_INCLUDE . '/vendor/phpseclib/');
include_once('Math/BigInteger.php');
include_once('Crypt/Base.php');
include_once('Crypt/Hash.php');
include_once('Crypt/Random.php');
include_once('Crypt/RSA.php');
include_once('Crypt/Rijndael.php');
global $encryption;
$encryption = true;
}
function escape_command($command) {
return $command; # we escape every single argument now, no need for 'special' escaping
#return preg_replace("/(\\\$|`)/", "", $command); # current cacti code
#TODO return preg_replace((\\\$(?=\w+|\*|\@|\#|\?|\-|\\\$|\!|\_|[0-9]|\(.*\))|`(?=.*(?=`)))","$2", $command); #suggested by ldevantier to allow for a single $
}
/** set the language environment variable for rrdtool functions
* @param string $lang - the desired language to set
* @return null
*/
function rrdtool_set_language($lang = -1) {
global $prev_lang;
$prev_lang = getenv('LANG');
if ($lang == -1) {
putenv('LANG=' . str_replace('-', '_', CACTI_LOCALE) . '.UTF-8');
} else {
putenv('LANG=en_EN.UTF-8');
}
}
/** restore the default language environment variable after rrdtool functions
* @return null
*/
function rrdtool_reset_language() {
global $prev_lang;
putenv('LANG=' . $prev_lang);
}
function rrd_init($output_to_term = true) {
global $config;
$args = func_get_args();
$local_storage = (isset($config['local_storage']) && $config['local_storage'] === true) ? true : false;
$function = ($local_storage === false && read_config_option('storage_location')) ? '__rrd_proxy_init' : '__rrd_init';
return call_user_func_array($function, $args);
}
function __rrd_init($output_to_term = true) {
global $config;
/* set the rrdtool default font */
if (read_config_option('path_rrdtool_default_font')) {
putenv('RRD_DEFAULT_FONT=' . read_config_option('path_rrdtool_default_font'));
}
rrdtool_set_language();
if ($output_to_term) {
$command = read_config_option('path_rrdtool') . ' - ';
} elseif ($config['cacti_server_os'] == 'win32') {
$command = read_config_option('path_rrdtool') . ' - > nul';
} else {
$command = read_config_option('path_rrdtool') . ' - > /dev/null 2>&1';
}
return popen($command, 'w');
}
function __rrd_proxy_init($logopt = 'WEBLOG') {
global $encryption;
$terminator = "_EOT_\r\n";
$encryption = true;
$rsa = new \phpseclib\Crypt\RSA();
$rrdp_socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($rrdp_socket === false) {
cacti_log('CACTI2RRDP ERROR: Unable to create socket to connect to RRDtool Proxy Server', false, $logopt, POLLER_VERBOSITY_LOW);
return false;
}
if (read_config_option('rrdp_load_balancing') == 'on') {
$rrdp_id = random_int(1,2);
$rrdp = @socket_connect($rrdp_socket, (($rrdp_id == 1) ? read_config_option('rrdp_server') : read_config_option('rrdp_server_backup')), (($rrdp_id == 1) ? read_config_option('rrdp_port') : read_config_option('rrdp_port_backup')));
} else {
$rrdp_id = 1;
$rrdp = @socket_connect($rrdp_socket, read_config_option('rrdp_server'), read_config_option('rrdp_port'));
}
if ($rrdp === false) {
/* log entry ... */
cacti_log('CACTI2RRDP ERROR: Unable to connect to RRDtool Proxy Server #' . $rrdp_id, false, $logopt, POLLER_VERBOSITY_LOW);
/* ... and try to use backup path */
$rrdp_id = ($rrdp_id + 1) % 2;
$rrdp = @socket_connect($rrdp_socket, (($rrdp_id == 1) ? read_config_option('rrdp_server') : read_config_option('rrdp_server_backup')), (($rrdp_id == 1) ? read_config_option('rrdp_port') : read_config_option('rrdp_port_backup')));
if ($rrdp === false) {
cacti_log('CACTI2RRDP ERROR: Unable to connect to RRDtool Proxy Server #' . $rrdp_id, false, $logopt, POLLER_VERBOSITY_LOW);
return false;
}
}
$rrdp_fingerprint = ($rrdp_id == 1) ? read_config_option('rrdp_fingerprint') : read_config_option('rrdp_fingerprint_backup');
socket_write($rrdp_socket, read_config_option('rsa_public_key') . $terminator);
/* read public key being returned by the proxy server */
$rrdp_public_key = '';
while (1) {
$recv = socket_read($rrdp_socket, 1000, PHP_BINARY_READ);
if ($recv === false) {
/* timeout */
cacti_log('CACTI2RRDP ERROR: Public RSA Key Exchange - Time-out while reading', false, $logopt, POLLER_VERBOSITY_LOW);
$rrdp_public_key = false;
break;
}
if ($recv == '') {
cacti_log('CACTI2RRDP ERROR: Session closed by Proxy.', false, $logopt, POLLER_VERBOSITY_LOW);
/* session closed by Proxy */
break;
} else {
$rrdp_public_key .= $recv;
if (str_contains($rrdp_public_key, $terminator)) {
$rrdp_public_key = trim(trim($rrdp_public_key, $terminator));
break;
}
}
}
$rsa->loadKey($rrdp_public_key);
$fingerprint = $rsa->getPublicKeyFingerprint();
if ($rrdp_fingerprint != $fingerprint) {
cacti_log('CACTI2RRDP ERROR: Mismatch RSA Fingerprint.', false, $logopt, POLLER_VERBOSITY_LOW);
return false;
} else {
$rrdproxy = array($rrdp_socket, $rrdp_public_key);
/* set the rrdtool default font */
if (read_config_option('path_rrdtool_default_font')) {
rrdtool_execute("setenv RRD_DEFAULT_FONT '" . read_config_option('path_rrdtool_default_font') . "'", false, RRDTOOL_OUTPUT_NULL, $rrdproxy, $logopt = 'WEBLOG');
}
/* disable encryption */
$encryption = rrdtool_execute('setcnn encryption off', false, RRDTOOL_OUTPUT_BOOLEAN, $rrdproxy, $logopt = 'WEBLOG') ? false : true;
return $rrdproxy;
}
}
function rrd_close() {
global $config;
$args = func_get_args();
$local_storage = (isset($config['local_storage']) && $config['local_storage'] === true) ? true : false;
$function = ($local_storage === false && read_config_option('storage_location')) ? '__rrd_proxy_close' : '__rrd_close';
return call_user_func_array($function, $args);
}
function __rrd_close($rrdtool_pipe) {
/* close the rrdtool file descriptor */
if (is_resource($rrdtool_pipe)) {
pclose($rrdtool_pipe);
}
rrdtool_reset_language();
}
function __rrd_proxy_close($rrdp) {
/* close the rrdtool proxy server connection */
$terminator = "_EOT_\r\n";
if ($rrdp) {
socket_write($rrdp[0], encrypt('quit', $rrdp[1]) . $terminator);
@socket_shutdown($rrdp[0], 2);
@socket_close($rrdp[0]);
return;
}
}
function encrypt($output, $rsa_key) {
global $encryption;
if ($encryption) {
$rsa = new \phpseclib\Crypt\RSA();
$aes = new \phpseclib\Crypt\Rijndael();
$aes_key = \phpseclib\Crypt\Random::string(192);
$aes->setKey($aes_key);
$ciphertext = base64_encode($aes->encrypt($output));
$rsa->loadKey($rsa_key);
$aes_key = base64_encode($rsa->encrypt($aes_key));
$aes_key_length = str_pad(dechex(strlen($aes_key)),3,'0',STR_PAD_LEFT);
return $aes_key_length . $aes_key . $ciphertext;
} else {
return $output;
}
}
function decrypt($input) {
global $encryption;
if ($encryption) {
$rsa = new \phpseclib\Crypt\RSA();
$aes = new \phpseclib\Crypt\Rijndael();
$rsa_private_key = read_config_option('rsa_private_key');
$aes_key_length = hexdec(substr($input,0,3));
$aes_key = base64_decode(substr($input,3,$aes_key_length), true);
$ciphertext = base64_decode(substr($input,3 + $aes_key_length), true);
$rsa->loadKey($rsa_private_key);
$aes_key = $rsa->decrypt($aes_key);
$aes->setKey($aes_key);
$plaintext = $aes->decrypt($ciphertext);
return $plaintext;
} else {
return $input;
}
}
function rrdtool_execute() {
global $config;
$args = func_get_args();
$local_storage = (isset($config['local_storage']) && $config['local_storage'] === true) ? true : false;
$function = ($local_storage === false && read_config_option('storage_location')) ? '__rrd_proxy_execute' : '__rrd_execute';
return call_user_func_array($function, $args);
}
function __rrd_execute($command_line, $log_to_stdout, $output_flag, $rrdtool_pipe = null, $logopt = 'WEBLOG') {
global $config;
static $last_command;
if (!is_numeric($output_flag)) {
$output_flag = RRDTOOL_OUTPUT_STDOUT;
}
/* WIN32: before sending this command off to rrdtool, get rid
of all of the backslash (\) characters. Unix does not care; win32 does.
Also make sure to replace all of the backslashes at the end of the line,
but make sure not to get rid of newlines (\n) that are supposed to be
in there (text format) */
$command_line = str_replace("\\\n", ' ', $command_line);
/* output information to the log file if appropriate */
cacti_log('CACTI2RRD: ' . read_config_option('path_rrdtool') . " $command_line", $log_to_stdout, $logopt, POLLER_VERBOSITY_DEBUG);
/* if we want to see the error output from rrdtool; make sure to specify this */
$debug = '';
if ($config['cacti_server_os'] != 'win32') {
if (($output_flag == RRDTOOL_OUTPUT_STDERR || $output_flag == RRDTOOL_OUTPUT_RETURN_STDERR) && !is_resource($rrdtool_pipe)) {
$debug .= ' 2>&1';
}
}
/* use popen to eliminate the zombie issue */
if ($config['cacti_server_os'] == 'unix') {
$pipe_mode = 'r';
} else {
$pipe_mode = 'rb';
}
/* an empty $rrdtool_pipe array means no fp is available */
if ($rrdtool_pipe === null || $rrdtool_pipe === false || !is_resource($rrdtool_pipe)) {
if (str_starts_with($command_line, 'fetch') || str_starts_with($command_line, 'info')) {
$dograph = false;
rrdtool_set_language('en');
} else {
$dograph = true;
rrdtool_set_language();
}
cacti_session_close();
if (is_file(read_config_option('path_rrdtool')) && is_executable(read_config_option('path_rrdtool'))) {
$descriptorspec = array(
0 => array('pipe', 'r'),
1 => array('pipe', 'w')
);
if ($config['is_web']) {
if (isset($_COOKIE['CactiTimeZone'])) {
$gmt_offset = $_COOKIE['CactiTimeZone'];
cacti_time_zone_set($gmt_offset);
}
}
$attempts = 0;
while ($attempts < 5) {
$full_commandline = read_config_option('path_rrdtool') . $debug . ' ' . escape_command($command_line);
if (0 == 1) {
/**
* For debugging issue associated with RRDtool, for now I'm commenting out this line
* There are issues processing graphv output with the --add-jsontime option when
* rrdtool is launched in the background.
*
* The reason for this difference is still to be determined.
*
* cacti_log($command_line);
*/
$process = proc_open(read_config_option('path_rrdtool') . ' - ' . $debug, $descriptorspec, $pipes);
if (!is_resource($process)) {
$attempts++;
unset($process);
} else {
fwrite($pipes[0], escape_command($command_line) . "\r\nquit\r\n");
fclose($pipes[0]);
$fp = $pipes[1];
}
if (!isset($fp)) {
rrdtool_reset_language();
return;
}
/* get the output regardless of the output type */
$output = '';
while (!feof($fp)) {
$output .= fgets($fp, 10000);
}
if (isset($process)) {
fclose($fp);
proc_close($process);
}
} else {
$output = shell_exec($full_commandline);
}
if ($output_flag == RRDTOOL_OUTPUT_STDOUT || $output_flag == RRDTOOL_OUTPUT_GRAPH_DATA) {
if ($output == '' || $output === null) {
if (debounce_run_notification('rrdtool_command_crash', 28880)) {
$backtrace = cacti_debug_backtrace('RRDTOOL Error');
$log_message = sprintf('WARNING: RRDtool Crashed executing the following command line %s. %s', $command_line, $backtrace);
$email_message = __('WARNING: RRDtool Crashed executing the following command line %s. %s', $command_line, $backtrace);
cacti_log($log_message, false, 'RRDTOOL');
admin_email(__('RRDtool Command Crashed'), $email_message);
}
$attempts++;
continue;
}
rrdtool_trim_output($output);
rrdtool_reset_language();
return $output;
} elseif ($output_flag == RRDTOOL_OUTPUT_STDERR || $output_flag == RRDTOOL_OUTPUT_RETURN_STDERR) {
rrdtool_reset_language();
if ($output != '') {
if (substr($output, 1, 3) == 'PNG') {
return 'OK';
} elseif (str_starts_with($output, '<?xml')) {
return 'SVG/XML Output OK';
} elseif ($output_flag == RRDTOOL_OUTPUT_RETURN_STDERR) {
rrdtool_reset_language();
return $output;
} else {
print $output;
break;
}
} else {
return "Error";
}
} else {
rrdtool_reset_language();
return true;
}
}
if ($attempts > 0) {
rrdtool_reset_language();
$backtrace = cacti_debug_backtrace('RRDTOOL Error');
cacti_log("WARNING: RRDtool failed after $attempts attempts for the following command $command_line. $backtrace", false, 'RRDTOOL');
return "";
}
} else {
cacti_log("ERROR: RRDtool executable not found, not executable or error in path '" . read_config_option('path_rrdtool') . "'. No output written to RRDfile.", false, 'RRDTOOL');
}
rrdtool_reset_language();
} else {
/**
* this path will generally always be taken with an rrdtool update command
*/
$i = 0;
while (true) {
if (fwrite($rrdtool_pipe, escape_command(" $command_line") . "\r\n") === false) {
cacti_log("ERROR: Detected RRDtool Crash on '$command_line'. Last command was '$last_command'", false, 'RRDTOOL');
/* close the invalid pipe */
rrd_close($rrdtool_pipe);
/* open a new rrdtool process */
$rrdtool_pipe = rrd_init();
if ($i > 4) {
cacti_log("FATAL: RRDtool Restart Attempts Exceeded. Giving up on '$command_line'.", false, 'RRDTOOL');
break;
} else {
$i++;
}
continue;
} else {
fflush($rrdtool_pipe);
break;
}
}
}
/* store the last command to provide rrdtool segfault diagnostics */
$last_command = $command_line;
}
function rrdtool_trim_output(&$output) {
global $config;
global $user_time, $system_time, $real_time;
/* When using RRDtool with proc_open for long strings
* and using the '-' to handle standard in from inside
* the process, RRDtool automatically appends stderr
* to stdout for batch programs to parse the output
* string. So, therefore, we have to prune that
* output.
*/
if ($config['cacti_server_os'] == 'win32') {
$output = rtrim($output, "OK \n\r");
} else {
$okpos = strrpos($output, 'OK u:');
if ($okpos !== false) {
$stats = substr($output, $okpos);
$line = trim($stats, ' OK');
$parts = explode(' ', $line);
foreach ($parts as $line) {
$sparts = explode(':', $line);
switch($sparts[0]) {
case 'u':
$user_time = $sparts[1];
break;
case 's':
$system_time = $sparts[1];
break;
case 'r':
$real_time = $sparts[1];
break;
}
}
$output = substr($output, 0, $okpos);
}
}
}
function __rrd_proxy_execute($command_line, $log_to_stdout, $output_flag, $rrdp = '', $logopt = 'WEBLOG') {
global $config, $encryption;
static $last_command;
$end_of_packet = "_EOP_\r\n";
$end_of_sequence = "_EOT_\r\n";
if (!is_numeric($output_flag)) {
$output_flag = RRDTOOL_OUTPUT_STDOUT;
}
/* WIN32: before sending this command off to rrdtool, get rid
of all of the '\' characters. Unix does not care; win32 does.
Also make sure to replace all of the fancy "\"s at the end of the line,
but make sure not to get rid of the "\n"s that are supposed to be
in there (text format) */
$command_line = str_replace(array(CACTI_PATH_RRA, "\\\n"), array('.', ' '), $command_line);
/* output information to the log file if appropriate */
cacti_log('CACTI2RRDP: ' . read_config_option('path_rrdtool') . " $command_line", $log_to_stdout, $logopt, POLLER_VERBOSITY_DEBUG);
/* store the last command to provide rrdtool segfault diagnostics */
$last_command = $command_line;
$rrdp_auto_close = false;
if (!$rrdp) {
$rrdp = __rrd_proxy_init($logopt);
$rrdp_auto_close = true;
}
if (!$rrdp) {
cacti_log('CACTI2RRDP ERROR: Unable to connect to RRDtool proxy.', $log_to_stdout, $logopt, POLLER_VERBOSITY_LOW);
return null;
} else {
cacti_log('CACTI2RRDP NOTE: Connection to RRDtool proxy has already been established.', $log_to_stdout, $logopt, POLLER_VERBOSITY_DEBUG);
}
$rrdp_socket = $rrdp[0];
$rrdp_public_key = $rrdp[1];
if (strlen($command_line) >= 8192) {
$command_line = gzencode($command_line, 1);
}
socket_write($rrdp_socket, encrypt($command_line, $rrdp_public_key) . $end_of_sequence);
$input = '';
$output = '';
while (1) {
$recv = socket_read($rrdp_socket, 100000, PHP_BINARY_READ);
if ($recv === false) {
cacti_log('CACTI2RRDP ERROR: Data Transfer - Time-out while reading.', $log_to_stdout, $logopt, POLLER_VERBOSITY_LOW);
break;
}
if ($recv == '') {
/* session closed by Proxy */
if ($output) {
cacti_log('CACTI2RRDP ERROR: Session closed by Proxy.', $log_to_stdout, $logopt, POLLER_VERBOSITY_LOW);
}
break;
} else {
$input .= $recv;
if (str_contains($input, $end_of_sequence)) {
$input = str_replace($end_of_sequence, '', $input);
$transactions = explode($end_of_packet, $input);
foreach ($transactions as $transaction) {
$packet = $transaction;
$transaction = decrypt($transaction);
if ($transaction === false) {
cacti_log('CACTI2RRDP ERROR: Proxy message decryption failed: ###'. $packet . '###', $log_to_stdout, $logopt, POLLER_VERBOSITY_LOW);
break 2;
}
if (str_starts_with($transaction, "\x1f\x8b")) {
$transaction = gzdecode($transaction);
}
$output .= $transaction;
if (substr_count($output, 'OK u') || substr_count($output, 'ERROR:')) {
cacti_log('RRDP: ' . $output, $log_to_stdout, $logopt, POLLER_VERBOSITY_DEBUG);
break 2;
}
}
}
}
}
if ($rrdp_auto_close) {
__rrd_proxy_close($rrdp);
}
switch ($output_flag) {
case RRDTOOL_OUTPUT_NULL:
return;
case RRDTOOL_OUTPUT_STDOUT:
case RRDTOOL_OUTPUT_GRAPH_DATA:
return rtrim(substr($output, 0, strpos($output, 'OK u')));
break;
case RRDTOOL_OUTPUT_STDERR:
if (substr($output, 1, 3) == 'PNG') {
return 'OK';
}
if (str_starts_with($output, 'GIF87')) {
return 'OK';
}
if (str_starts_with($output, '<?xml')) {
return 'SVG/XML Output OK';
}
print $output;
break;
case RRDTOOL_OUTPUT_BOOLEAN:
return (substr_count($output, 'OK u')) ? true : false;
break;
}
}
function rrdtool_function_interface_speed($data_local) {
$ifHighSpeed = db_fetch_cell_prepared('SELECT field_value
FROM host_snmp_cache
WHERE host_id = ?
AND snmp_query_id = ?
AND snmp_index = ?
AND field_name="ifHighSpeed"',
array($data_local['host_id'], $data_local['snmp_query_id'], $data_local['snmp_index'])
);
$ifSpeed = db_fetch_cell_prepared('SELECT field_value
FROM host_snmp_cache
WHERE host_id = ?
AND snmp_query_id = ?
AND snmp_index = ?
AND field_name="ifSpeed"',
array($data_local['host_id'], $data_local['snmp_query_id'], $data_local['snmp_index'])
);
if (!empty($ifHighSpeed)) {
$speed = $ifHighSpeed * 1000000;
} elseif (!empty($ifSpeed)) {
$speed = $ifSpeed;
} else {
$speed = read_config_option('default_interface_speed');
if (empty($speed)) {
$speed = '10000000000000';
} else {
$speed *= 1000000;
}
}
return $speed;
}
function rrdtool_function_create($local_data_id, $show_source, $rrdtool_pipe = null) {
global $config, $data_source_types, $consolidation_functions, $encryption;
include(CACTI_PATH_INCLUDE . '/global_arrays.php');
$data_source_path = get_data_source_path($local_data_id, true);
/* ok, if that passes lets check to make sure an rra does not already
exist, the last thing we want to do is overright data! */
if ($show_source != true) {
if (read_config_option('storage_location')) {
if (rrdtool_execute("file_exists $data_source_path", true, RRDTOOL_OUTPUT_BOOLEAN, $rrdtool_pipe, 'POLLER')) {
return -1;
}
} elseif (file_exists($data_source_path)) {
return -1;
}
}
/* the first thing we must do is make sure there is at least one
rra associated with this data source... *
UPDATE: As of version 0.6.6, we are splitting this up into two
SQL strings because of the multiple DS per RRD support. This is
not a big deal however since this function gets called once per
data source */
$rras = db_fetch_assoc_prepared('SELECT dtd.rrd_step, dsp.x_files_factor,
dspr.steps, dspr.rows, dspc.consolidation_function_id,
(dspr.rows*dspr.steps) AS rra_order
FROM data_template_data AS dtd
LEFT JOIN data_source_profiles AS dsp
ON dtd.data_source_profile_id=dsp.id
LEFT JOIN data_source_profiles_rra AS dspr
ON dsp.id=dspr.data_source_profile_id
LEFT JOIN data_source_profiles_cf AS dspc
ON dsp.id=dspc.data_source_profile_id
WHERE dtd.local_data_id = ?
AND (dspr.steps IS NOT NULL OR dspr.rows IS NOT NULL)
ORDER BY dspc.consolidation_function_id, rra_order',
array($local_data_id)
);
/* if we find that this DS has no RRA associated; get out */
if (cacti_sizeof($rras) <= 0) {
cacti_log("ERROR: There are no RRA's assigned to local_data_id: $local_data_id.");
return false;
}
/* create the "--step" line */
$create_ds = RRD_NL . '--start 0 --step '. $rras[0]['rrd_step'] . ' ' . RRD_NL;
/**
* We have to check for Non-Templated Data Source first as they may not include
* a graph. So, for that case, we need the RRDfile to include all data sources
*/
$data_template_id = db_fetch_cell_prepared('SELECT data_template_id
FROM data_local
WHERE id = ?',
array($local_data_id));
if ($data_template_id > 0) {
$data_sources = db_fetch_assoc_prepared('SELECT DISTINCT dtr.id, dtr.data_source_name, dtr.rrd_heartbeat,
dtr.rrd_minimum, dtr.rrd_maximum, dtr.data_source_type_id
FROM data_template_rrd AS dtr
INNER JOIN graph_templates_item AS gti
ON dtr.id = gti.task_item_id
WHERE local_data_id = ?
ORDER BY local_data_template_rrd_id',
array($local_data_id)
);
} else {
$data_sources = db_fetch_assoc_prepared('SELECT DISTINCT dtr.id, dtr.data_source_name, dtr.rrd_heartbeat,
dtr.rrd_minimum, dtr.rrd_maximum, dtr.data_source_type_id
FROM data_template_rrd AS dtr
WHERE local_data_id = ?
ORDER BY local_data_template_rrd_id',
array($local_data_id)
);
}
/**
* ONLY make a new DS entry if:
*
* - There are multiple data sources and this item is not the main one.
* - There are only one data source (then use it)
*/
if (cacti_sizeof($data_sources)) {
$data_local = db_fetch_row_prepared('SELECT host_id,
snmp_query_id, snmp_index
FROM data_local
WHERE id = ?',
array($local_data_id)
);
$speed = rrdtool_function_interface_speed($data_local);
foreach ($data_sources as $data_source) {
/* use the cacti ds name by default or the user defined one, if entered */
$data_source_name = get_data_source_item_name($data_source['id']);
// Trim the data source maximum
$data_source['rrd_maximum'] = trim($data_source['rrd_maximum']);
if ($data_source['rrd_maximum'] == 'U') {
/* in case no maximum is given, use "Undef" value */
$data_source['rrd_maximum'] = 'U';
} elseif (str_contains($data_source['rrd_maximum'], '|query_')) {
/* in case a query variable is given, evaluate it */
if ($data_source['rrd_maximum'] == '|query_ifSpeed|' || $data_source['rrd_maximum'] == '|query_ifHighSpeed|') {
$data_source['rrd_maximum'] = $speed;
} else {
$data_source['rrd_maximum'] = substitute_snmp_query_data($data_source['rrd_maximum'], $data_local['host_id'], $data_local['snmp_query_id'], $data_local['snmp_index']);
}
} elseif ($data_source['rrd_maximum'] != 'U' && (int)$data_source['rrd_maximum'] <= (int)$data_source['rrd_minimum']) {
/* max > min required, but take care of an "Undef" value */
if ($data_source['data_source_type_id'] == 1 || $data_source['data_source_type_id'] == 4) {
$data_source['rrd_maximum'] = 'U';
} else {
$data_source['rrd_maximum'] = (int)$data_source['rrd_minimum'] + 1;
}
}
/* min==max==0 won't work with rrdtool */
if ($data_source['rrd_minimum'] == 0 && $data_source['rrd_maximum'] == 0) {
$data_source['rrd_maximum'] = 'U';
}
$create_ds .= "DS:$data_source_name:" . $data_source_types[$data_source['data_source_type_id']] . ':' . $data_source['rrd_heartbeat'] . ':' . $data_source['rrd_minimum'] . ':' . $data_source['rrd_maximum'] . RRD_NL;
}
}
$create_rra = '';
/* loop through each available RRA for this DS */
foreach ($rras as $rra) {
$create_rra .= 'RRA:' . $consolidation_functions[$rra['consolidation_function_id']] . ':' . $rra['x_files_factor'] . ':' . $rra['steps'] . ':' . $rra['rows'] . RRD_NL;
}
if ($config['cacti_server_os'] != 'win32') {
$owner_id = fileowner(CACTI_PATH_RRA);
$group_id = filegroup(CACTI_PATH_RRA);
}
/**
* check for structured path configuration, if in place verify directory
* exists and if not create it.
*/
if (read_config_option('extended_paths') == 'on') {
if (read_config_option('storage_location')) {
if (rrdtool_execute('is_dir ' . dirname($data_source_path), true, RRDTOOL_OUTPUT_BOOLEAN, $rrdtool_pipe, 'POLLER') === false) {
if (rrdtool_execute('mkdir ' . dirname($data_source_path), true, RRDTOOL_OUTPUT_BOOLEAN, $rrdtool_pipe, 'POLLER') === false) {
cacti_log("ERROR: Unable to create directory '" . dirname($data_source_path) . "'", false);
}
}
} elseif (!is_dir(dirname($data_source_path))) {
if ($config['is_web'] == false || is_writable(CACTI_PATH_RRA)) {
if (mkdir(dirname($data_source_path), 0775, true)) {
if ($config['cacti_server_os'] != 'win32' && posix_getuid() == 0) {
$success = true;
$paths = explode('/', str_replace(CACTI_PATH_RRA, '/', dirname($data_source_path)));
$spath = '';
foreach ($paths as $path) {
if ($path == '') {
continue;
}
$spath .= '/' . $path;
$powner_id = fileowner(CACTI_PATH_RRA . $spath);
$pgroup_id = fileowner(CACTI_PATH_RRA . $spath);
if ($powner_id != $owner_id) {
$success = chown(CACTI_PATH_RRA . $spath, $owner_id);
}
if ($pgroup_id != $group_id && $success) {
$success = chgrp(CACTI_PATH_RRA . $spath, $group_id);
}
if (!$success) {
cacti_log("ERROR: Unable to set directory permissions for '" . CACTI_PATH_RRA . $spath . "'", false);
break;
}
}
}
} else {
cacti_log("ERROR: Unable to create directory '" . dirname($data_source_path) . "'", false);
}
} else {
cacti_log("WARNING: Poller has not created structured path '" . dirname($data_source_path) . "' yet.", false);
}
}
}
if ($show_source == true) {
return read_config_option('path_rrdtool') . ' create' . RRD_NL . "$data_source_path$create_ds$create_rra";
} else {
$success = rrdtool_execute("create $data_source_path $create_ds$create_rra", true, RRDTOOL_OUTPUT_STDOUT, $rrdtool_pipe, 'POLLER');
if ($config['cacti_server_os'] != 'win32' && posix_getuid() == 0) {
shell_exec("chown $owner_id:$group_id $data_source_path");
}
return $success;
}
}
function rrdtool_function_update($update_cache_array, $rrdtool_pipe = null) {
/* lets count the number of rrd files processed */
$rrds_processed = 0;
foreach ($update_cache_array as $rrd_path => $rrd_fields) {
$create_rrd_file = false;
if (is_array($rrd_fields['times']) && cacti_sizeof($rrd_fields['times'])) {
/* create the rrd if one does not already exist */
if (read_config_option('storage_location') > 0) {
$file_exists = rrdtool_execute("file_exists $rrd_path" , true, RRDTOOL_OUTPUT_BOOLEAN, $rrdtool_pipe, 'POLLER');
} else {
$file_exists = file_exists($rrd_path);
}
ksort($rrd_fields['times']);
if ($file_exists === false) {
$times = array_keys($rrd_fields['times']);
rrdtool_function_create($rrd_fields['local_data_id'], false, $rrdtool_pipe);
$create_rrd_file = true;
}
if (isset($rrd_fields['data_template_id'])) {
$data_template_id = $rrd_fields['data_template_id'];
} else {
$data_template_id = db_fetch_cell_prepared('SELECT data_template_id
FROM data_local
WHERE id = ?',
array($rrd_fields['local_data_id']));
}
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($rrd_fields['local_data_id'])),
'data_source_name', 'data_source_name'
);
} else {
$unused_data_source_names = array();
}
foreach ($rrd_fields['times'] as $update_time => $field_array) {
if (empty($update_time)) {
/* default the rrdupdate time to now */
$rrd_update_values = 'N:';
} else {
$rrd_update_values = $update_time . ':';
}
$rrd_update_template = '';
foreach ($field_array as $field_name => $value) {
if ($rrd_update_template != '') {
$rrd_update_template .= ':';
$rrd_update_values .= ':';
}
$rrd_update_template .= $field_name;
/* if we have "invalid data", give rrdtool an Unknown (U) */
if (!isset($value) || !is_numeric($value)) {
$value = 'U';
}
$rrd_update_values .= $value;
}
if (cacti_version_compare(get_rrdtool_version(), '1.5', '>=')) {
$update_options='--skip-past-updates';
} else {
$update_options='';
}
rrdtool_execute("update $rrd_path $update_options --template $rrd_update_template $rrd_update_values", true, RRDTOOL_OUTPUT_STDOUT, $rrdtool_pipe, 'POLLER');
$rrds_processed++;
}
}
}
return $rrds_processed;
}