-
-
Notifications
You must be signed in to change notification settings - Fork 411
/
Copy pathdsstats.php
1495 lines (1252 loc) · 47.3 KB
/
dsstats.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/ |
+-------------------------------------------------------------------------+
*/
/**
* get_rrdfile_names - this routine returns all of the RRDfiles know to Cacti
* so as to be processed when performing the Daily, Weekly, Monthly and Yearly
* average and peak calculations.
*
* @param $thread_id - (int) The thread to process
* @param $max_threads - (int) The maximum number of threads
*
* @return - (mixed) The RRDfile names
*/
function get_rrdfile_names($thread_id = 1, $max_threads = 1) {
static $dsrows = array();
if ($max_threads == 1) {
return db_fetch_assoc('SELECT dtd.local_data_id, data_source_path, rrd_num AS dsses, GROUP_CONCAT(DISTINCT data_source_name) AS dsnames
FROM data_template_data AS dtd
INNER JOIN data_template_rrd AS dtr
ON dtd.local_data_id = dtr.local_data_id
LEFT JOIN poller_item AS pi
ON pi.local_data_id = dtd.local_data_id
WHERE pi.local_data_id IS NOT NULL
AND data_source_path != ""
AND dtd.local_data_id != 0
GROUP BY dtd.local_data_id');
} elseif (cacti_sizeof($dsrows)) {
return $dsrows;
} else {
$dsses_total = db_fetch_cell('SELECT COUNT(DISTINCT dtd.local_data_id)
FROM data_template_data AS dtd
LEFT JOIN poller_item AS pi
ON pi.local_data_id = dtd.local_data_id
WHERE pi.local_data_id IS NOT NULL
AND data_source_path != ""
AND dtd.local_data_id != 0');
$split_size = ceil($dsses_total / $max_threads);
$start = (($thread_id - 1) * $split_size) + 1;
$rows = db_fetch_assoc("SELECT dtd.local_data_id, data_source_path, rrd_num AS dsses, GROUP_CONCAT(DISTINCT data_source_name) AS dsnames
FROM data_template_data AS dtd
INNER JOIN data_template_rrd AS dtr
ON dtd.local_data_id = dtr.local_data_id
LEFT JOIN poller_item AS pi
ON pi.local_data_id = dtd.local_data_id
WHERE pi.local_data_id IS NOT NULL
AND data_source_path != ''
AND dtd.local_data_id != 0
GROUP BY dtd.local_data_id
LIMIT $start, $split_size");
$dsrows = $rows;
if (isset($rows)) {
return $rows;
} else {
return array();
}
}
}
/**
* dsstats_debug - this simple routine prints a standard message to the console
* when running in debug mode.
*
* @param $message - (string) The message to display
*
* @return - NULL
*/
function dsstats_debug($message) {
global $debug;
if ($debug) {
print 'DSSTATS: ' . $message . PHP_EOL;
}
}
/**
* dsstats_get_and_store_ds_avgpeak_values - this routine is a generic routine that takes an time interval as an
* input parameter and then, though additional function calls, reads the RRDfiles for the correct information
* and stores that information into the various database tables.
*
* @param $interval - (string) either 'daily', 'weekly', 'monthly', or 'yearly'
* @param $type - (string) the statistics type to store
* @param $thread_id - (int) the dsstats parallel thread id
*
* @return - NULL
*/
function dsstats_get_and_store_ds_avgpeak_values($interval, $type, $thread_id = 1) {
global $config;
global $total_user, $total_system, $total_real, $total_dsses;
global $user_time, $system_time, $real_time, $rrd_files;
$user_time = 0;
$system_time = 0;
$real_time = 0;
$dsses = 0;
dsstats_debug(sprintf('Processing %s for Thread %s', $interval, $thread_id));
$max_threads = read_config_option('dsstats_parallel');
$mode = read_config_option('dsstats_mode');
$peak = read_config_option('dsstats_peak') == 'on' ? true: false;
if (empty($max_threads)) {
$max_threads = 1;
set_config_option('dsstats_parallel', '1');
}
if (empty($thread_id)) {
$thread_id = 1;
$max_threads = 1;
}
$rrdfiles = get_rrdfile_names($thread_id, $max_threads);
$stats = array();
$rrd_files += cacti_sizeof($rrdfiles);
$use_proxy = (read_config_option('storage_location') > 0 ? true : false);
/* open a pipe to rrdtool for writing and reading */
if ($use_proxy) {
$rrd_process = rrd_init(false);
} else {
$rrd_process = dsstats_rrdtool_init();
}
if (cacti_sizeof($rrdfiles)) {
foreach ($rrdfiles as $file) {
$dsses += $file['dsses'];
if ($file['data_source_path'] != '') {
$rrdfile = str_replace('<path_rra>', CACTI_PATH_RRA, $file['data_source_path']);
$local_data_id = $file['local_data_id'];
$dsnames = explode(',', $file['dsnames']);
$stats[$local_data_id] = dsstats_obtain_data_source_avgpeak_values($local_data_id, $rrdfile, $interval, $mode, $peak, $rrd_process);
} else {
$data_source_name = db_fetch_cell_prepared('SELECT name_cache
FROM data_template_data
WHERE local_data_id = ?',
array($file['local_data_id']));
cacti_log("WARNING: Data Source '$data_source_name' is damaged and contains no path. Please delete and re-create both the Graph and Data Source.", false, 'DSSTATS');
}
}
}
if ($use_proxy) {
rrd_close($rrd_process);
} else {
dsstats_rrdtool_close($rrd_process);
}
dsstats_write_buffer($stats, $interval, $mode);
if (!empty($type)) {
$total_user += $user_time;
$total_system += $system_time;
$total_real += $real_time;
$total_dsses += $dsses;
set_config_option('dsstats_rrd_system_' . $type . '_' . $thread_id, $total_system);
set_config_option('dsstats_rrd_user_' . $type . '_' . $thread_id, $total_user);
set_config_option('dsstats_rrd_real_' . $type . '_' . $thread_id, $total_real);
set_config_option('dsstats_total_rrds_' . $type . '_' . $thread_id, $rrd_files);
set_config_option('dsstats_total_dsses_' . $type . '_' . $thread_id, $total_dsses);
}
}
/**
* dsstats_write_buffer - this routine provide bulk database insert services to the various tables that store
* the average and peak information for Data Sources.
*
* @param array $stats_array - A multi dimensional array keyed by the local_data_id that contains both
* the average and max values for each internal RRDfile Data Source.
* @param string $interval - 'daily', 'weekly', 'monthly', and 'yearly'. Used for determining the table to
* update during the dumping of the buffer.
* @param int $mode - The mode of collection legacy '0' or advanced '1'
*
* @return - NULL
*/
function dsstats_write_buffer(&$stats_array, $interval, $mode) {
$outbuf = '';
$out_length = 0;
$i = 1;
$max_packet = 256000;
// Format $stats[ldi][avg|max][rrd_name][metric] = $value
if ($mode == 1) {
$sql_prefix = "INSERT INTO data_source_stats_$interval
(local_data_id, rrd_name, cf, average, peak, p95n, p90n, p75n, p50n, p25n, sum, stddev, lslslope, lslint, lslcorrel) VALUES";
$sql_suffix = ' ON DUPLICATE KEY UPDATE
average=VALUES(average),
peak=VALUES(peak),
p95n=VALUES(p95n),
p90n=VALUES(p90n),
p75n=VALUES(p75n),
p50n=VALUES(p50n),
p25n=VALUES(p25n),
sum=VALUES(sum),
stddev=VALUES(stddev),
lslslope=VALUES(lslslope),
lslint=VALUES(lslint),
lslcorrel=VALUES(lslcorrel)';
} else {
$sql_prefix = "INSERT INTO data_source_stats_$interval (local_data_id, rrd_name, cf, average, peak) VALUES";
$sql_suffix = ' ON DUPLICATE KEY UPDATE
average=VALUES(average),
peak=VALUES(peak)';
}
$overhead = strlen($sql_prefix) + strlen($sql_suffix);
/* don't attempt to process an empty array */
/* Format $stats[ldi][avg|max][rrd_name][metric] = $value */
if (cacti_sizeof($stats_array)) {
foreach ($stats_array as $local_data_id => $ldi_stats) {
if (cacti_sizeof($ldi_stats)) {
foreach ($ldi_stats as $cf => $cf_stats) {
if ($cf == 'avg') {
$mycf = '0';
} else {
$mycf = '1';
}
foreach($cf_stats as $rrd_name => $stats) {
if ($mode == 0) {
$outbuf .= ($i == 1 ? ' ':', ') . "('" .
$local_data_id . "','" .
$rrd_name . "','" .
$mycf . "','" .
$stats['avg'] . "','" .
$stats['peak'] . "')";
} else {
$outbuf .= ($i == 1 ? ' ':', ') . "('" .
$local_data_id . "','" .
$rrd_name . "','" .
$mycf . "','" .
$stats['avg'] . "','" .
$stats['peak'] . "','" .
$stats['p95n'] . "','" .
$stats['p90n'] . "','" .
$stats['p75n'] . "','" .
$stats['p50n'] . "','" .
$stats['p25n'] . "','" .
$stats['sum'] . "','" .
$stats['stddev'] . "','" .
$stats['lslslope'] . "','" .
$stats['lslint'] . "','" .
$stats['lslcorrel'] . "')";
}
$out_length += strlen($outbuf);
if (($out_length + $overhead) > $max_packet) {
db_execute($sql_prefix . $outbuf . $sql_suffix);
$outbuf = '';
$out_length = 0;
$i = 1;
} else {
$i++;
}
}
}
} else {
$host_id = db_fetch_cell_prepared('SELECT host_id
FROM data_local
WHERE id = ?',
array($local_data_id));
cacti_log(sprintf("WARNING: Problem with Data Source for Device[%s], DS[%s], Interval[%s]", $host_id, $local_data_id, ucfirst($interval)), false, 'DSSTATS');
}
}
/* flush the buffer if it still has elements in it */
if ($out_length > 0) {
db_execute($sql_prefix . $outbuf . $sql_suffix);
}
}
}
/**
* dsstats_obtain_data_source_avgpeak_values - this routine, given the rrdfile name, interval and RRDtool process
* pipes, will obtain the average a peak values from the RRDfile. It does this in two steps:
*
* 1) It first reads the RRDfile's information header to obtain all of the internal data source names,
* poller interval and consolidation functions.
* 2) Based upon the available consolidation functions, it then grabs either AVERAGE, and MAX, or just AVERAGE
* in the case where the MAX consolidation function is not included in the RRDfile, and then proceeds to
* gather data from the RRDfile for the time period in question. It allows RRDtool to select the RRA to
* use by simply limiting the number of rows to be returned to the default.
*
* Once it has all of the information from the RRDfile. It then decomposes the resulting XML file to its
* components and then calculates the AVERAGE and MAX values from that data and returns an array to the calling
* function for storage into the respective database table.
*
* @param $local_data_id - (int) The Cacti Local Data Id
* @param $rrdfile - (string) The rrdfile to process
* @param $interval - (string) The interval type to process
* @param $mode - (int) If we should be collecting legacy stats or not
* @param $peak - (bool) If the peak should be take from the max cf
* @param $rrd_process - (resource) Pipes to the background RRDtool process
*
* @return - (mixed) An array of AVERAGE, and MAX values in an RRDfile by Data Source name
*/
function dsstats_obtain_data_source_avgpeak_values($local_data_id, $rrdfile, $interval, $mode, $peak, $rrd_process) {
global $config, $user_time, $system_time, $real_time;
$use_proxy = (read_config_option('storage_location') ? true : false);
if ($use_proxy) {
$file_exists = rrdtool_execute("file_exists $rrdfile", true, RRDTOOL_OUTPUT_BOOLEAN, $rrd_process, 'DSSTATS');
} else {
clearstatcache();
$file_exists = file_exists($rrdfile);
}
/* don't attempt to get information if the file does not exist */
if ($file_exists) {
$stats_command = db_fetch_cell_prepared('SELECT stats_command
FROM data_source_stats_command_cache
WHERE local_data_id = ?',
array($local_data_id));
if ($stats_command == '') {
$stats_command = dsstats_get_stats_command($local_data_id, $rrdfile, $use_proxy, $mode, $peak, $rrd_process);
}
if ($stats_command !== false) {
/* change the interval to something RRDtool understands */
switch($interval) {
case 'daily':
$interval = 'day';
break;
case 'weekly':
$interval = 'week';
break;
case 'monthly':
$interval = 'month';
break;
case 'yearly':
$interval = 'year';
break;
}
/* now execute the graph command */
$stats_cmd = 'graph x --start now-1' . $interval . ' --end now ' . trim($stats_command);
//print $stats_cmd . PHP_EOL . PHP_EOL;
if ($use_proxy) {
$xport_data = rrdtool_execute($stats_cmd, false, RRDTOOL_OUTPUT_STDOUT, $rrd_process, 'DSSTATS');
} else {
$xport_data = dsstats_rrdtool_execute($stats_cmd, $rrd_process);
}
/* process the xport array and return average and peak values */
if ($xport_data != '') {
$xport_array = explode("\n", $xport_data);
if (cacti_sizeof($xport_array)) {
foreach ($xport_array as $index => $line) {
$line = trim($line);
if ($line == '' || $line == '0x0') {
continue;
}
if ($index > 0) {
// Catch the last line
if (str_starts_with($line, 'OK')) {
$line = trim($line, ' OK');
$parts = explode(' ', $line);
//print $line . PHP_EOL;
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;
}
}
break;
} else {
// Get the rrd_name and the remainder
$parts = explode('-', $line);
$rrd_name = $parts[0];
$namvalpt = $parts[1];
// Get the combined variable and value
$parts = explode('=', $namvalpt);
$variable = $parts[0];
$value = $parts[1];
// Get the metric and the mode
$parts = explode('_', $variable);
$metric = $parts[0];
$amode = $parts[1];
if (stripos($value, 'nan') === false) {
$dsvalues[$amode][$rrd_name][$metric] = $value;
} else {
$dsvalues[$amode][$rrd_name][$metric] = 'NULL';
}
}
}
}
return $dsvalues;
}
}
}
} elseif (($interval == 'daily') || ($interval == 'day')) {
/* only alarm if performing the 'daily' averages */
cacti_log("WARNING: File does not exist! DS[$local_data_id], FILE[" . $rrdfile . "]", false, 'DSSTATS');
}
}
function dsstats_get_stats_command($local_data_id, $rrdfile, $use_proxy, $mode, $peak, $rrd_process) {
global $config, $user_time, $system_time, $real_time;
/* high speed or snail speed */
if ($use_proxy) {
$info = rrdtool_execute("info $rrdfile", false, RRDTOOL_OUTPUT_STDOUT, $rrd_process, 'DSSTATS');
} else {
$info = dsstats_rrdtool_execute("info $rrdfile", $rrd_process);
}
/**
* Get the current values of stats and peak settings to see if there is any change to purge the cache
*/
$temp_mode = read_config_option('dsstats_mode');
$temp_peak = read_config_option('dsstats_peak');
set_config_option('dsstats_temp_mode', $temp_mode);
set_config_option('dsstats_temp_peak', $temp_peak);
$length = strlen($info);
$command = '';
/* don't do anything if RRDfile did not return data */
if ($info != '') {
$info_array = explode("\n", $info);
$average = false;
$max = false;
$dsnames = array();
/* figure out what is in this RRDfile. Assume CF Uniformity as Cacti does not allow async rrdfiles.
* also verify the consolidation functions in the RRDfile for average and max calculations.
*/
if (cacti_sizeof($info_array)) {
foreach ($info_array as $line) {
if (str_contains($line, 'ds[')) {
$parts = explode(']', $line);
$parts2 = explode('[', $parts[0]);
$dsnames[trim($parts2[1])] = 1;
} elseif (str_contains($line, '.cf')) {
$parts = explode('=', $line);
if (str_contains($parts[1], 'AVERAGE')) {
$average = true;
}
if (str_contains($parts[1], 'MAX')) {
$max = true;
}
} elseif (str_contains($line, 'step')) {
$parts = explode('=', $line);
$poller_interval = trim($parts[1]);
}
}
}
/* create the command syntax to get data */
/* assume that an RRDfile has not more than 62 data sources */
$defs = 'abcdefghijklmnopqrstuvwxyz012345789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$i = 0;
$j = 0;
$def = '';
$command = '';
$dsvalues = array();
/* escape the file name if on Windows */
if ($config['cacti_server_os'] != 'unix') {
$rrdfile = str_replace(':', '\\:', $rrdfile);
}
/* setup the graph command by parsing through the internal data source names */
if (cacti_sizeof($dsnames)) {
foreach ($dsnames as $dsname => $present) {
$mydata_avg = $defs[$j] . $defs[$i] . '_a';
$mydata_max = $defs[$j] . $defs[$i] . '_m';
if ($average) {
$def .= 'DEF:' . $mydata_avg . '="' . $rrdfile . '":' . $dsname . ':AVERAGE ';
$command .= " VDEF:{$mydata_avg}_aa=$mydata_avg,AVERAGE PRINT:{$mydata_avg}_aa:{$dsname}-avg_avg=%lf";
$command .= " VDEF:{$mydata_avg}_am=$mydata_avg,MAXIMUM PRINT:{$mydata_avg}_am:{$dsname}-peak_avg=%lf";
$i++;
}
if ($max && $peak) {
$def .= 'DEF:' . $mydata_max . '="' . $rrdfile . '":' . $dsname . ':MAX ';
$command .= " VDEF:{$mydata_max}_ma=$mydata_max,AVERAGE PRINT:{$mydata_max}_ma:{$dsname}-avg_max=%lf";
$command .= " VDEF:{$mydata_max}_mm=$mydata_max,MAXIMUM PRINT:{$mydata_max}_mm:{$dsname}-peak_max=%lf";
$i++;
}
if ($mode == 1) {
$pt = array('95', '90', '75', '50', '25');
if ($average) {
foreach($pt as $s) {
$command .= " VDEF:{$mydata_avg}_p{$s}n={$mydata_avg},$s,PERCENTNAN PRINT:{$mydata_avg}_p{$s}n:{$dsname}-p{$s}n_avg=%lf";
}
// TOTAL
$command .= " VDEF:{$mydata_avg}_sum=$mydata_avg,TOTAL PRINT:{$mydata_avg}_sum:{$dsname}-sum_avg=%lf";
// STDDEV
$command .= " VDEF:{$mydata_avg}_stddev=$mydata_avg,STDEV PRINT:{$mydata_avg}_stddev:{$dsname}-stddev_avg=%lf";
// LSLSLOPE
$command .= " VDEF:{$mydata_avg}_lslslope=$mydata_avg,LSLSLOPE PRINT:{$mydata_avg}_lslslope:{$dsname}-lslslope_avg=%lf";
// LSLINT
$command .= " VDEF:{$mydata_avg}_lslint=$mydata_avg,LSLINT PRINT:{$mydata_avg}_lslint:{$dsname}-lslint_avg=%lf";
// LSLCORREL
$command .= " VDEF:{$mydata_avg}_lslcorrel=$mydata_avg,LSLCORREL PRINT:{$mydata_avg}_lslcorrel:{$dsname}-lslcorrel_avg=%lf";
}
if ($max && $peak) {
foreach($pt as $s) {
$command .= " VDEF:{$mydata_max}_p{$s}n={$mydata_max},$s,PERCENTNAN PRINT:{$mydata_max}_p{$s}n:{$dsname}-p{$s}n_max=%lf";
}
// TOTAL
$command .= " VDEF:{$mydata_max}_sum=$mydata_max,TOTAL PRINT:{$mydata_max}_sum:{$dsname}-sum_max=%lf";
// STDDEV
$command .= " VDEF:{$mydata_max}_stddev=$mydata_max,STDEV PRINT:{$mydata_max}_stddev:{$dsname}-stddev_max=%lf";
// LSLSLOPE
$command .= " VDEF:{$mydata_max}_lslslope=$mydata_max,LSLSLOPE PRINT:{$mydata_max}_lslslope:{$dsname}-lslslope_max=%lf";
// LSLINT
$command .= " VDEF:{$mydata_max}_lslint=$mydata_max,LSLINT PRINT:{$mydata_max}_lslint:{$dsname}-lslint_max=%lf";
// LSLCORREL
$command .= " VDEF:{$mydata_max}_lslcorrel=$mydata_max,LSLCORREL PRINT:{$mydata_max}_lslcorrel:{$dsname}-lslcorrel_max=%lf";
}
}
if ($i > 50) {
$j++;
$i = 0;
}
}
}
$command = trim($def) . ' ' . $command;
db_execute_prepared('REPLACE INTO data_source_stats_command_cache
(local_data_id, stats_command)
VALUES(?, ?)',
array($local_data_id, $command));
return $command;
}
return false;
}
/**
* dsstats_log_statistics - provides generic timing message to both the Cacti log and the settings
* table so that the statistics can be graphed as well.
*
* @param $type - (string) the type of statistics to log, either 'HOURLY', 'DAILY', 'BOOST' or 'MAJOR'.
*
* @return - NULL
*/
function dsstats_log_statistics($type) {
global $start;
dsstats_debug($type);
if ($type == 'HOURLY') {
$sub_type = '';
} elseif ($type == 'MAJOR') {
$sub_type = 'dchild';
} elseif ($type == 'DAILY') {
$sub_type = 'child';
} elseif ($type == 'BOOST') {
$sub_type = 'bchild';
}
/* take time and log performance data */
$end = microtime(true);
if ($sub_type != '') {
$rrd_user = db_fetch_cell_prepared('SELECT SUM(value)
FROM settings
WHERE name LIKE ?',
array('dsstats_rrd_user_%' . $sub_type . '%'));
$rrd_system = db_fetch_cell_prepared('SELECT SUM(value)
FROM settings
WHERE name LIKE ?',
array('dsstats_rrd_system_%' . $sub_type . '%'));
$rrd_real = db_fetch_cell_prepared('SELECT SUM(value)
FROM settings
WHERE name LIKE ?',
array('dsstats_rrd_real_%' . $sub_type . '%'));
$rrd_files = db_fetch_cell_prepared('SELECT SUM(value)
FROM settings
WHERE name LIKE ?',
array('dsstats_total_rrds_%' . $sub_type . '%'));
$dsses = db_fetch_cell_prepared('SELECT SUM(value)
FROM settings
WHERE name LIKE ?',
array('dsstats_total_dsses_%' . $sub_type . '%'));
$processes = read_config_option('dsstats_parallel');
$cacti_stats = sprintf('Time:%01.2f Type:%s Threads:%s RRDfiles:%s DSSes:%s RRDUser:%01.2f RRDSystem:%01.2f RRDReal:%01.2f', $end - $start, $type, $processes, $rrd_files, $dsses, $rrd_user, $rrd_system, $rrd_real);
db_execute("DELETE FROM settings
WHERE name LIKE 'dsstats_rrd_%$sub_type%'
OR name LIKE 'dsstats_total_rrds%_$sub_type%'
OR name LIKE 'dsstats_total_dsses%_$sub_type%'");
} else {
$cacti_stats = sprintf('Time:%01.2f Type:%s', $end - $start, $type);
}
/* take time and log performance data */
$start = microtime(true);
/* log to the database */
set_config_option('stats_dsstats_' . $type, $cacti_stats);
/* log to the logfile */
cacti_log('DSSTATS STATS: ' . $cacti_stats , true, 'SYSTEM');
}
/**
* dsstats_log_child_stats - logs dsstats child process information
*
* @param $type - (string) The type of child, MAJOR, DAILY, BOOST
* @param $thread_id - (int) The parallel thread id
* @param $total_time - (int) The total time to collect date
*
* @return - NULL
*/
function dsstats_log_child_stats($type, $thread_id, $total_time) {
$rrd_user = db_fetch_cell_prepared('SELECT SUM(value)
FROM settings
WHERE name LIKE ?',
array('dsstats_rrd_user_%' . $type . '_' . $thread_id . '%'));
$rrd_system = db_fetch_cell_prepared('SELECT SUM(value)
FROM settings
WHERE name LIKE ?',
array('dsstats_rrd_system_%' . $type . '_' . $thread_id . '%'));
$rrd_real = db_fetch_cell_prepared('SELECT SUM(value)
FROM settings
WHERE name LIKE ?',
array('dsstats_rrd_real_%' . $type . '_' . $thread_id . '%'));
$rrd_files = db_fetch_cell_prepared('SELECT SUM(value)
FROM settings
WHERE name LIKE ?',
array('dsstats_total_rrds_%' . $type . '_' . $thread_id . '%'));
$dsses = db_fetch_cell_prepared('SELECT SUM(value)
FROM settings
WHERE name LIKE ?',
array('dsstats_total_dsses_%' . $type . '_' . $thread_id . '%'));
$cacti_stats = sprintf('Time:%01.2f Type:%s ProcessNumber:%s RRDfiles:%s DSSes:%s RRDUser:%01.2f RRDSystem:%01.2f RRDReal:%01.2f', $total_time, strtoupper($type), $thread_id, $rrd_files, $dsses, $rrd_user, $rrd_system, $rrd_real);
cacti_log('DSSTATS CHILD STATS: ' . $cacti_stats, true, 'SYSTEM');
}
/**
* dsstats_error_handler - this routine logs all PHP error transactions
* to make sure they are properly logged.
*
* @param $errno - (int) The errornum reported by the system
* @param $errmsg - (string) The error message provides by the error
* @param $filename - (string) The filename that encountered the error
* @param $linenum - (int) The line number where the error occurred
* @param $vars - (mixed) The current state of PHP variables.
*
* @returns - (bool) always returns true for some reason
*/
function dsstats_error_handler($errno, $errmsg, $filename, $linenum, $vars = array()) {
if (read_config_option('log_verbosity') >= POLLER_VERBOSITY_DEBUG) {
/* define all error types */
$errortype = array(
E_ERROR => 'Error',
E_WARNING => 'Warning',
E_PARSE => 'Parsing Error',
E_NOTICE => 'Notice',
E_CORE_ERROR => 'Core Error',
E_CORE_WARNING => 'Core Warning',
E_COMPILE_ERROR => 'Compile Error',
E_COMPILE_WARNING => 'Compile Warning',
E_USER_ERROR => 'User Error',
E_USER_WARNING => 'User Warning',
E_USER_NOTICE => 'User Notice',
E_STRICT => 'Runtime Notice'
);
if (defined('E_RECOVERABLE_ERROR')) {
$errortype[E_RECOVERABLE_ERROR] = 'Catchable Fatal Error';
}
/* create an error string for the log */
$err = "ERRNO:'" . $errno . "' TYPE:'" . $errortype[$errno] .
"' MESSAGE:'" . $errmsg . "' IN FILE:'" . $filename .
"' LINE NO:'" . $linenum . "'";
/* let's ignore some lesser issues */
if (str_contains($errmsg, 'date_default_timezone')) {
return;
}
if (str_contains($errmsg, 'Only variables')) {
return;
}
/* log the error to the Cacti log */
cacti_log('PROGERR: ' . $err, false, 'DSSTATS');
}
return;
}
/**
* dsstats_poller_output - this routine runs in parallel with the cacti poller and
* populates the last and cache tables. On larger systems, it should be noted that
* the memory overhead for the global arrays, $ds_types, $ds_last, $ds_multi
* could be serval hundred megabytes. So, this should be kept in mind when running the
* sizing your system.
*
* The routine basically loads those 4 structures into memory, and then uses them to
* determine what should be stored in both the Cache and the Last tables. The 4 structures
* contain the following information:
*
* $ds_types - The type of data source, keyed by the local_data_id and the rrd_name stored inside
* of the RRDfile.
* $ds_last - For the COUNTER, and DERIVE DS types, the last measured and stored value.
* $ds_multi - For Multi Part responses, stores the mapping of the Data Input Fields to the
* Internal RRDfile DS names.
*
* The routine loops through all poller output items and makes decisions relative to the output
* that should be stored into the two tables, and then bulk inserts that information once
* all poller items have been processed.
*
* The purpose for loading then entire structures into memory at one time is to reduce the latency
* related to multiple database calls. The author believed that PHP's array hashing algorithms
* would be as fast, if not faster, than MySQL, when considering the transaction overhead and therefore
* chose this method.
*
* @param $rrd_update_array - (mixed) The output from the poller output table to be processed by dsstats
*
* @return - NULL
*/
function dsstats_poller_output(&$rrd_update_array) {
global $config;
static $ds_types = array();
static $ds_multi = array();
/* suppress warnings */
if (defined('E_DEPRECATED')) {
error_reporting(E_ALL ^ E_DEPRECATED);
} else {
error_reporting(E_ALL);
}
/* install the dsstats error handler */
set_error_handler('dsstats_error_handler');
/* do not make any calculations unless enabled */
if (read_config_option('dsstats_enable') == 'on') {
if (cacti_sizeof($rrd_update_array) > 0) {
/* we will assume a smaller than the max packet size. This would appear to be around the sweat spot. */
$max_packet = '264000';
/* initialize some variables related to the DB inserts */
$outbuf = '';
$sql_cache_prefix = 'INSERT INTO data_source_stats_hourly_cache (local_data_id, rrd_name, time, `value`) VALUES';
$sql_last_prefix = 'INSERT INTO data_source_stats_hourly_last (local_data_id, rrd_name, `value`, calculated) VALUES';
$sql_suffix = ' ON DUPLICATE KEY UPDATE `value`=VALUES(`value`)';
$sql_last_suffix = ' ON DUPLICATE KEY UPDATE `value`=VALUES(`value`), `calculated`=VALUES(`calculated`)';
$overhead = strlen($sql_cache_prefix) + strlen($sql_suffix);
$overhead_last = strlen($sql_last_prefix) + strlen($sql_last_suffix);
/* determine the keyvalue pairs to decide on how to store data */
if (!cacti_sizeof($ds_types)) {
$ds_types = array_rekey(
db_fetch_assoc('SELECT DISTINCT data_source_name, data_source_type_id, rrd_step, rrd_maximum
FROM data_template_rrd AS dtr
INNER JOIN data_template_data AS dtd
ON dtd.local_data_id = dtr.local_data_id
WHERE dtd.local_data_id > 0'),
'data_source_name', array('data_source_type_id', 'rrd_step', 'rrd_maximum')
);
}
/* make the association between the multi-part name value pairs and the RRDfile internal
* data source names.
*/
if (!cacti_sizeof($ds_multi)) {
$ds_multi = array_rekey(
db_fetch_assoc('SELECT DISTINCT data_name, data_source_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 dif.id = dtr.data_input_field_id
WHERE dtr.data_input_field_id != 0'),
'data_name', 'data_source_name'
);
}
/* required for updating tables */
$cache_i = 1;
$last_i = 1;
$out_length = 0;
$last_length = 0;
$lastbuf = '';
$cachebuf = '';
/* process each array */
$n = 1;
foreach ($rrd_update_array as $data_source) {
if (isset($data_source['times'])) {
foreach ($data_source['times'] as $time => $sample) {
foreach ($sample as $ds => $value) {
$result['local_data_id'] = $data_source['local_data_id'];
$result['rrd_name'] = $ds;
$result['time'] = date('Y-m-d H:i:s', $time);
if (is_numeric($value)) {
$result['output'] = $value;
} elseif ($value == 'U' || strtolower($value) == 'nan') {
$result['output'] = 'NULL';
} else {
$result['output'] = 'NULL';
cacti_log('ERROR: Output from local_data_id ' .
$data_source['local_data_id'] .
", for RRDfile DS Name '$ds', is invalid. " .
"It outputs was : '" . $value . "'. " .
'Please check your script or data input method for errors.');
}
$lastval = '';
if (!isset($ds_types[$result['rrd_name']]['data_source_type_id'])) {
$polling_interval = db_fetch_cell_prepared('SELECT rrd_step
FROM data_template_data
WHERE local_data_id = ?',
array($data_source['local_data_id']));
$ds_type = db_fetch_cell_prepared('SELECT data_source_type_id
FROM data_template_rrd
WHERE local_data_id = ?',
array($data_source['local_data_id']));
} else {
$polling_interval = $ds_types[$result['rrd_name']]['rrd_step'];
$ds_type = $ds_types[$result['rrd_name']]['data_source_type_id'];
}
switch ($ds_type) {
case 2: // COUNTER
case 6: // DCOUNTER
/* get the last values from the database for COUNTER and DERIVE data sources */
$ds_last = db_fetch_cell_prepared('SELECT SQL_NO_CACHE `value`
FROM data_source_stats_hourly_last
WHERE local_data_id = ?
AND rrd_name = ?',
array($result['local_data_id'], $result['rrd_name']));
if ($ds_last == '' || $ds_last == 'NULL') {
$currentval = 'NULL';
} elseif ($result['output'] == 'NULL') {
$currentval = 'NULL';
} elseif ($result['output'] >= $ds_last) {
/* everything is normal */
$currentval = $result['output'] - $ds_last;
} else {
$max_value = $ds_types[$result['rrd_name']]['rrd_maximum'];
/* possible overflow, see if its 32bit or 64bit */
if ($ds_last > 4294967295) {
$currentval = (18446744073709551615 - $ds_last) + $result['output'];
} else {
$currentval = (4294967295 - $ds_last) + $result['output'];
}
if ($max_value != 'U' && $currentval > $max_value) {
$currentval = 'NULL';
}
}
if ($currentval != 'NULL') {
$currentval /= $polling_interval;
if ($ds_type == 6) {
$currentval = round($currentval, 0);
}
}
$lastval = $result['output'];
if ($ds_type == 6) {
$lastval = round($lastval, 0);
}
break;
case 3: // DERIVE
case 7: // DDERIVE
/* get the last values from the database for COUNTER and DERIVE data sources */
$ds_last = db_fetch_cell_prepared('SELECT SQL_NO_CACHE `value`
FROM data_source_stats_hourly_last
WHERE local_data_id = ?
AND rrd_name = ?', array($result['local_data_id'], $result['rrd_name']));
if ($ds_last == '') {
$currentval = 'NULL';
} elseif ($result['output'] != 'NULL') {
$currentval = ($result['output'] - $ds_last) / $polling_interval;
if ($ds_type == 7) {
$currentval = round($currentval, 0);
}
} else {
$currentval = 'NULL';
}
$lastval = $result['output'];
if ($ds_type == 7) {
$lastval = round($lastval, 0);
}