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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
|
<?php
/*
** Zabbix
** Copyright (C) 2001-2019 Zabbix SIA
**
** 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.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
**/
/**
* General class for SVG Graph usage.
*/
class CSvgGraph extends CSvg {
const SVG_GRAPH_X_AXIS_HEIGHT = 20;
const SVG_GRAPH_DEFAULT_COLOR = '#b0af07';
const SVG_GRAPH_DEFAULT_TRANSPARENCY = 5;
const SVG_GRAPH_DEFAULT_POINTSIZE = 1;
const SVG_GRAPH_DEFAULT_LINE_WIDTH = 1;
const SVG_GRAPH_X_AXIS_LABEL_MARGIN = 5;
const SVG_GRAPH_Y_AXIS_LEFT_LABEL_MARGIN = 5;
const SVG_GRAPH_Y_AXIS_RIGHT_LABEL_MARGIN = 12;
protected $canvas_height;
protected $canvas_width;
protected $canvas_x;
protected $canvas_y;
/**
* Problems annotation labels color.
*
* @var string
*/
protected $color_annotation = '#AA4455';
/**
* Text color.
*
* @var string
*/
protected $text_color;
/**
* Grid color.
*
* @var string
*/
protected $grid_color;
/**
* Array of graph metrics data.
*
* @var array
*/
protected $metrics = [];
/**
* Array of graph points data. Calculated from metrics data.
*
* @var array
*/
protected $points = [];
/**
* Array of metric paths. Where key is metric index from $metrics array.
*
* @var array
*/
protected $paths = [];
/**
* Array of graph problems to display.
*
* @var array
*/
protected $problems = [];
protected $max_value_left = null;
protected $max_value_right = null;
protected $min_value_left = null;
protected $min_value_right = null;
protected $left_y_show = false;
protected $left_y_min = null;
protected $left_y_max = null;
protected $left_y_units = null;
protected $left_y_empty = true;
protected $right_y_show = false;
protected $right_y_min = null;
protected $right_y_max = null;
protected $right_y_units = null;
protected $right_y_empty = true;
protected $right_y_zero = null;
protected $left_y_zero = null;
protected $x_show;
protected $offset_bottom;
/**
* Value for graph left offset. Is used as width for left Y axis container.
*
* @var int
*/
protected $offset_left = 20;
/**
* Value for graph right offset. Is used as width for right Y axis container.
*
* @var int
*/
protected $offset_right = 20;
/**
* Maximum width of container for every Y axis.
*
* @var int
*/
protected $max_yaxis_width = 120;
protected $offset_top;
protected $time_from;
protected $time_till;
/**
* Height for X axis container.
*
* @var int
*/
protected $xaxis_height = 20;
/**
* SVG default size.
*/
protected $width = 1000;
protected $height = 1000;
public function __construct(array $options) {
parent::__construct();
// Set colors.
$theme = getUserGraphTheme();
$this->text_color = '#' . $theme['textcolor'];
$this->grid_color = '#' . $theme['gridcolor'];
$this
->setTimePeriod($options['time_period']['time_from'], $options['time_period']['time_to'])
->setXAxis($options['x_axis'])
->setYAxisLeft($options['left_y_axis'])
->setYAxisRight($options['right_y_axis']);
}
/**
* Get graph canvas X offset.
*
* @return int
*/
public function getCanvasX() {
return $this->canvas_x;
}
/**
* Get graph canvas Y offset.
*
* @return int
*/
public function getCanvasY() {
return $this->canvas_y;
}
/**
* Get graph canvas width.
*
* @return int
*/
public function getCanvasWidth() {
return $this->canvas_width;
}
/**
* Get graph canvas height.
*
* @return int
*/
public function getCanvasHeight() {
return $this->canvas_height;
}
/**
* Set problems data for graph.
*
* @param array $problems Array of problems data.
*
* @return CSvgGraph
*/
public function addProblems(array $problems) {
$this->problems = $problems;
return $this;
}
/**
* Set metrics data for graph.
*
* @param array $metrics Array of metrics data.
*
* @return CSvgGraph
*/
public function addMetrics(array $metrics = []) {
$metrics_for_each_axes = [
GRAPH_YAXIS_SIDE_LEFT => 0,
GRAPH_YAXIS_SIDE_RIGHT => 0
];
foreach ($metrics as $i => $metric) {
$min_value = null;
$max_value = null;
if ($metric['points']) {
$metrics_for_each_axes[$metric['options']['axisy']]++;
foreach ($metric['points'] as $point) {
if ($min_value === null || $min_value > $point['value']) {
$min_value = $point['value'];
}
if ($max_value === null || $max_value < $point['value']) {
$max_value = $point['value'];
}
$this->points[$i][$point['clock']] = $point['value'];
}
if ($metric['options']['axisy'] == GRAPH_YAXIS_SIDE_LEFT) {
if ($this->min_value_left === null || $this->min_value_left > $min_value) {
$this->min_value_left = $min_value;
}
if ($this->max_value_left === null || $this->max_value_left < $max_value) {
$this->max_value_left = $max_value;
}
}
else {
if ($this->min_value_right === null || $this->min_value_right > $min_value) {
$this->min_value_right = $min_value;
}
if ($this->max_value_right === null || $this->max_value_right < $max_value) {
$this->max_value_right = $max_value;
}
}
}
$this->metrics[$i] = [
'name' => $metric['hosts'][0]['name'].NAME_DELIMITER.$metric['name'],
'itemid' => $metric['itemid'],
'units' => $metric['units'],
'host' => $metric['hosts'][0],
'options' => ['order' => $i] + $metric['options']
];
}
$this->left_y_empty = ($metrics_for_each_axes[GRAPH_YAXIS_SIDE_LEFT] == 0);
$this->right_y_empty = ($metrics_for_each_axes[GRAPH_YAXIS_SIDE_RIGHT] == 0);
return $this;
}
/**
* Set graph time period.
*
* @param int $time_from Timestamp.
* @param int @time_till Timestamp.
*
* @return CSvgGraph
*/
public function setTimePeriod($time_from, $time_till) {
$this->time_from = $time_from;
$this->time_till = $time_till;
return $this;
}
/**
* Set left side Y axis display options.
*
* @param array $options
* @param int $options['show']
* @param string $options['min']
* @param string $options['max']
* @param string $options['units']
*
* @return CSvgGraph
*/
public function setYAxisLeft(array $options) {
$this->left_y_show = ($options['show'] == SVG_GRAPH_AXIS_SHOW);
if ($options['min'] !== '') {
$this->left_y_min = $options['min'];
}
if ($options['max'] !== '') {
$this->left_y_max = $options['max'];
}
if ($options['units'] !== null) {
$units = trim(preg_replace('/\s+/', ' ', $options['units']));
$this->left_y_units = htmlspecialchars($units);
}
return $this;
}
/**
* Set right side Y axis display options.
*
* @param array $options
* @param int $options['show']
* @param string $options['min']
* @param string $options['max']
* @param string $options['units']
*
* @return CSvgGraph
*/
public function setYAxisRight(array $options) {
$this->right_y_show = ($options['show'] == SVG_GRAPH_AXIS_SHOW);
if ($options['min'] !== '') {
$this->right_y_min = $options['min'];
}
if ($options['max'] !== '') {
$this->right_y_max = $options['max'];
}
if ($options['units'] !== null) {
$units = trim(preg_replace('/\s+/', ' ', $options['units']));
$this->right_y_units = htmlspecialchars($units);
}
return $this;
}
/**
* Show or hide X axis.
*
* @param array $options
*
* @return CSvgGraph
*/
public function setXAxis(array $options) {
$this->x_show = ($options['show'] == SVG_GRAPH_AXIS_SHOW);
return $this;
}
/**
* Return array of horizontal labels with positions. Array key will be position, value will be label.
*
* @return array
*/
public function getTimeGridWithPosition() {
$period = $this->time_till - $this->time_from;
$step = round(bcmul(bcdiv($period, $this->canvas_width), 100)); // Grid cell (100px) in seconds.
$start = $this->time_from + $step - $this->time_from % $step;
$time_formats = ['Y-n-d', 'n-d', 'n-d H:i','H:i', 'H:i:s'];
// Search for most appropriate time format.
foreach ($time_formats as $fmt) {
$grid_values = [];
for ($clock = $start; $this->time_till >= $clock; $clock += $step) {
$relative_pos = round($this->canvas_width - $this->canvas_width * ($this->time_till - $clock) / $period);
$grid_values[$relative_pos] = date($fmt, $clock);
}
/**
* If at least two calculated time-strings are equal, proceed with next format. Do that as long as each date
* is different or there is no more time formats to test.
*/
if (count(array_flip($grid_values)) == count($grid_values) || $fmt === end($time_formats)) {
break;
}
}
return $grid_values;
}
/**
* Add UI selection box element to graph.
*
* @return CSvgGraph
*/
public function addSBox() {
$this->addItem([
(new CSvgRect(0, 0, 0, 0))->addClass('svg-graph-selection'),
(new CSvgText(0, 0, ''))->addClass('svg-graph-selection-text')
]);
return $this;
}
/**
* Add UI helper line that follows mouse.
*
* @return CSvgGraph
*/
public function addHelper() {
$this->addItem((new CSvgLine(0, 0, 0, 0))->addClass(CSvgTag::ZBX_STYLE_GRAPH_HELPER));
return $this;
}
/**
* Render graph.
*
* @return CSvgGraph
*/
public function draw() {
$this->applyMissingDataFunc();
$this->calculateDimensions();
$this->calculatePaths();
$this->drawGrid();
if ($this->left_y_show) {
$this->drawCanvasLeftYAxis();
}
if ($this->right_y_show) {
$this->drawCanvasRightYAxis();
}
if ($this->x_show) {
$this->drawCanvasXAxis();
}
$this->drawMetricsLine();
$this->drawMetricsPoint();
$this->drawProblems();
$this->addClipArea();
return $this;
}
/**
* Add dynamic clip path to hide metric lines and area outside graph canvas.
*/
protected function addClipArea() {
$areaid = uniqid('metric_clip_');
// CSS styles.
$this->styles['.'.CSvgTag::ZBX_STYLE_GRAPH_AREA]['clip-path'] = 'url(#'.$areaid.')';
$this->styles['[data-metric]']['clip-path'] = 'url(#'.$areaid.')';
$this->addItem(
(new CsvgTag('clipPath'))
->addItem(
(new CSvgPath(implode(' ', [
'M'.$this->canvas_x.','.($this->canvas_y - 3),
'H'.($this->canvas_width + $this->canvas_x),
'V'.($this->canvas_height + $this->canvas_y),
'H'.($this->canvas_x)
])))
)
->setAttribute('id', $areaid)
);
}
/**
* Calculate canvas size, margins and offsets for graph canvas inside SVG element.
*/
protected function calculateDimensions() {
// Canvas height must be specified before call self::getValuesGridWithPosition.
$this->offset_top = 10;
$this->offset_bottom = self::SVG_GRAPH_X_AXIS_HEIGHT;
$this->canvas_height = $this->height - $this->offset_top - $this->offset_bottom;
$this->canvas_y = $this->offset_top;
// Set missing properties for left Y axis.
if ($this->left_y_min === null) {
$this->left_y_min = $this->min_value_left ? : 0;
}
if ($this->left_y_max === null) {
$this->left_y_max = $this->max_value_left ? : 1;
}
if ($this->left_y_min == $this->left_y_max) {
$this->left_y_min -= 0.5;
$this->left_y_max += 0.5;
}
$grid = $this->getValueGrid($this->left_y_min, $this->left_y_max);
$this->left_y_min = $grid[0];
$this->left_y_max = end($grid);
if ($this->left_y_units === null) {
$this->left_y_units = '';
foreach ($this->metrics as $metric) {
if ($metric['options']['axisy'] == GRAPH_YAXIS_SIDE_LEFT) {
$this->left_y_units = $metric['units'];
break;
}
}
}
// Set missing properties for right Y axis.
if ($this->right_y_min === null) {
$this->right_y_min = $this->min_value_right ? : 0;
}
if ($this->right_y_max === null) {
$this->right_y_max = $this->max_value_right ? : 1;
}
if ($this->right_y_min == $this->right_y_max) {
$this->right_y_min -= 0.5;
$this->right_y_max += 0.5;
}
$grid = $this->getValueGrid($this->right_y_min, $this->right_y_max);
$this->right_y_min = $grid[0];
$this->right_y_max = end($grid);
if ($this->right_y_units === null) {
$this->right_y_units = '';
foreach ($this->metrics as $metric) {
if ($metric['options']['axisy'] == GRAPH_YAXIS_SIDE_RIGHT) {
$this->right_y_units = $metric['units'];
break;
}
}
}
// Define canvas dimensions and offsets, except canvas height and bottom offset.
$approx_width = 10;
if ($this->left_y_show) {
$values = $this->getValuesGridWithPosition(GRAPH_YAXIS_SIDE_LEFT, $this->left_y_empty);
if ($values) {
$offset_left = max($this->offset_left, max(array_map('strlen', $values)) * $approx_width);
$this->offset_left = (int) min($offset_left, $this->max_yaxis_width);
}
}
if ($this->right_y_show) {
$values = $this->getValuesGridWithPosition(GRAPH_YAXIS_SIDE_RIGHT, $this->right_y_empty);
if ($values) {
$offset_right = max($this->offset_right, max(array_map('strlen', $values)) * $approx_width);
$offset_right += self::SVG_GRAPH_Y_AXIS_RIGHT_LABEL_MARGIN;
$this->offset_right = (int) min($offset_right, $this->max_yaxis_width);
}
}
$this->canvas_width = $this->width - $this->offset_left - $this->offset_right;
$this->canvas_x = $this->offset_left;
// Calculate Y = 0 position.
$delta = (($this->right_y_max - $this->right_y_min) ? : 1);
$this->right_y_zero = $this->canvas_y + $this->canvas_height * $this->right_y_max / $delta;
$delta = (($this->left_y_max - $this->left_y_min) ? : 1);
$this->left_y_zero = $this->canvas_y + $this->canvas_height * $this->left_y_max / $delta;
}
/**
* Get array of X points with labels, for grid and X/Y axes. Array key is Y coordinate for SVG, value is label with
* axis units.
*
* @param int $side Type of X axis: GRAPH_YAXIS_SIDE_RIGHT, GRAPH_YAXIS_SIDE_LEFT
*
* @return array
*/
protected function getValuesGridWithPosition($side, $empty_set = false) {
if ($empty_set) {
$units = '';
}
elseif ($side === GRAPH_YAXIS_SIDE_LEFT) {
$min_value = $this->left_y_min;
$max_value = $this->left_y_max;
$units = $this->left_y_units;
}
else {
$min_value = $this->right_y_min;
$max_value = $this->right_y_max;
$units = $this->right_y_units;
}
$grid = $empty_set ? [0, 1] : $this->getValueGrid($min_value, $max_value);
$min_value = $grid[0];
$max_value = end($grid);
$delta = ($max_value != $min_value)
? $max_value - $min_value
: (count($grid) > 1 ? end($grid) - $grid[0] : 1);
$grid_values = [];
foreach ($grid as $value) {
$relative_pos = $this->canvas_height - $this->canvas_height * ($max_value - $value) / $delta;
if ($relative_pos >= 0 && $relative_pos <= $this->canvas_height) {
$grid_values[$relative_pos] = convert_units([
'value' => $value,
'units' => $units,
'convert' => ITEM_CONVERT_NO_UNITS
]);
}
}
/*
* This will fix a rare corner case when values on Y axes are aligned in such a way that calculated Y=0 (based
* on steps calculated by self::getValueGrid) is out of the allowed area (typically by less then 1px) and are
* not drawn on Y axis. Fix will calculate the real value on Y=0. The interval will always be smaller than
* interval between any other 2 grid values.
*
* This is done on left side Y axis only, because on right side Y axis we will not draw label on Y=0 to not
* overlap the arrow on X axis.
*
* This is also done only if distance between Y=0 and next lowest Y value is larger than 25px, to avoid label
* overlapping.
*/
if ($side == GRAPH_YAXIS_SIDE_LEFT) {
$lowest = key($grid_values);
if (!array_key_exists(0, $grid_values) && $lowest > 25) {
$grid_values[0] = convert_units([
'value' => $grid_values[$lowest] - ($lowest * ($max_value - $min_value) / $this->canvas_height),
'units' => $units,
'convert' => ITEM_CONVERT_NO_UNITS
]);
ksort($grid_values);
}
}
return $grid_values;
}
/**
* Add Y axis with labels to left side of graph.
*/
protected function drawCanvasLeftYaxis() {
$grid_values = $this->getValuesGridWithPosition(GRAPH_YAXIS_SIDE_LEFT, $this->left_y_empty);
$this->addItem(
(new CSvgGraphAxis($grid_values, GRAPH_YAXIS_SIDE_LEFT))
->setSize($this->offset_left, $this->canvas_height)
->setPosition($this->canvas_x - $this->offset_left, $this->canvas_y)
->setTextColor($this->text_color)
->setLineColor($this->grid_color)
);
}
/**
* Add Y axis with labels to right side of graph.
*/
protected function drawCanvasRightYAxis() {
$grid_values = $this->getValuesGridWithPosition(GRAPH_YAXIS_SIDE_RIGHT, $this->right_y_empty);
$this->addItem(
(new CSvgGraphAxis($grid_values, GRAPH_YAXIS_SIDE_RIGHT))
->setSize($this->offset_right, $this->canvas_height)
->setPosition($this->canvas_x + $this->canvas_width, $this->canvas_y)
->setTextColor($this->text_color)
->setLineColor($this->grid_color)
);
}
/**
* Add X axis with labels to graph.
*/
protected function drawCanvasXAxis() {
$this->addItem(
(new CSvgGraphAxis($this->getTimeGridWithPosition(), GRAPH_YAXIS_SIDE_BOTTOM))
->setSize($this->canvas_width, $this->xaxis_height)
->setPosition($this->canvas_x, $this->canvas_y + $this->canvas_height)
->setTextColor($this->text_color)
->setLineColor($this->grid_color)
);
}
/**
* Calculate array of points between $min and $max value.
*
* @param int $min Minimum value.
* @param int $max Maximum value.
*
* @return $array
*/
protected function getValueGrid($min, $max) {
$res = [];
// If absolute min/max is equal, calculate grid with 4 rows to make 0 centered. 5 rows otherwise.
$grid_rows = (abs($min) == abs($max)) ? 4 : 5;
$decimals = strlen(substr(strrchr($max, '.'), 1));
$decimals = $decimals > 4 ? 4 : $decimals;
$decimals = $decimals < 2 ? 2 : $decimals;
for ($base = 10; $base > .01; $base /= 10) {
$mul = ($max > 0) ? 1 / pow($base, floor(log10($max))) : 1;
$max10 = ceil($mul * $max) / $mul;
$min10 = floor($mul * $min) / $mul;
$delta = $max10 - $min10;
$delta = ceil($mul * $delta) / $mul;
if ($mul >= 1) {
if ($delta) {
for ($i = 0; $delta >= $i; $i += $delta / $grid_rows) {
$res[] = sprintf('%.'.$decimals.'f', $i + $min10);
}
}
else {
$res[] = $min10;
}
break;
}
}
return $res;
}
/**
* Add grid to graph.
*/
protected function drawGrid() {
$time_points = $this->x_show ? $this->getTimeGridWithPosition() : [];
$value_points = [];
if ($this->left_y_show) {
$value_points = $this->getValuesGridWithPosition(GRAPH_YAXIS_SIDE_LEFT, $this->left_y_empty);
unset($time_points[0]);
}
elseif ($this->right_y_show) {
$value_points = $this->getValuesGridWithPosition(GRAPH_YAXIS_SIDE_RIGHT, $this->right_y_empty);
unset($time_points[$this->canvas_width]);
}
if ($this->x_show) {
unset($value_points[0]);
}
$this->addItem((new CSvgGraphGrid($value_points, $time_points))
->setPosition($this->canvas_x, $this->canvas_y)
->setSize($this->canvas_width, $this->canvas_height)
->setColor($this->grid_color)
);
}
/**
* Calculate paths for metric elements.
*/
protected function calculatePaths() {
foreach ($this->metrics as $index => $metric) {
if (!array_key_exists($index, $this->points)) {
continue;
}
if ($metric['options']['axisy'] == GRAPH_YAXIS_SIDE_RIGHT) {
$min_value = $this->right_y_min;
$max_value = $this->right_y_max;
}
else {
$min_value = $this->left_y_min;
$max_value = $this->left_y_max;
}
$time_range = $this->time_till - $this->time_from ? : 1;
$value_diff = $max_value - $min_value ? : 1;
$timeshift = $metric['options']['timeshift'];
$paths = [];
$path_num = 0;
foreach ($this->points[$index] as $clock => $point) {
// If missing data function is SVG_GRAPH_MISSING_DATA_NONE, path should be splitted in multiple svg shapes.
if ($point === null) {
$path_num++;
continue;
}
/**
* Avoid invisible data point drawing. Data sets of type != SVG_GRAPH_TYPE_POINTS cannot be skipped to
* keep shape unchanged.
*/
$in_range = ($max_value >= $point && $min_value <= $point);
if ($in_range || $metric['options']['type'] != SVG_GRAPH_TYPE_POINTS) {
$x = $this->canvas_x + $this->canvas_width
- $this->canvas_width * ($this->time_till - $clock + $timeshift) / $time_range;
$y = $this->canvas_y + $this->canvas_height * ($max_value - $point) / $value_diff;
$paths[$path_num][] = [$x, $y, convert_units([
'value' => $point,
'units' => $metric['units']
])];
}
}
if ($paths) {
$this->paths[$index] = $paths;
}
}
}
/**
* Modifies metric data and Y value range according specified missing data function.
*/
protected function applyMissingDataFunc() {
foreach ($this->metrics as $index => $metric) {
/**
* - Missing data points are calculated only between existing data points;
* - Missing data points are not calculated for SVG_GRAPH_TYPE_POINTS metrics;
* - SVG_GRAPH_MISSING_DATA_CONNECTED is default behavior of SVG graphs, so no need to calculate anything
* here.
*/
if (array_key_exists($index, $this->points)
&& $metric['options']['type'] != SVG_GRAPH_TYPE_POINTS
&& $metric['options']['missingdatafunc'] != SVG_GRAPH_MISSING_DATA_CONNECTED) {
$points = &$this->points[$index];
$missing_data_points = $this->getMissingData($points, $metric['options']['missingdatafunc']);
// Sort according new clock times (array keys).
$points += $missing_data_points;
ksort($points);
// Missing data function can change min value of Y axis.
if ($missing_data_points
&& $metric['options']['missingdatafunc'] == SVG_GRAPH_MISSING_DATA_TREAT_AS_ZERO) {
if ($this->min_value_left > 0 && $metric['options']['axisy'] == GRAPH_YAXIS_SIDE_LEFT) {
$this->min_value_left = 0;
}
elseif ($this->min_value_right > 0 && $metric['options']['axisy'] == GRAPH_YAXIS_SIDE_RIGHT) {
$this->min_value_right = 0;
}
}
}
}
}
/**
* Calculate missing data for given set of $points according given $missingdatafunc.
*
* @param array $points Array of metric points to modify, where key is metric timestamp.
* @param int $missingdatafunc Type of function, allowed value:
* SVG_GRAPH_MISSING_DATA_TREAT_AS_ZERO, SVG_GRAPH_MISSING_DATA_NONE,
* SVG_GRAPH_MISSING_DATA_CONNECTED
*
* @return array Array of calculated missing data points.
*/
protected function getMissingData(array $points = [], $missingdatafunc) {
// Get average distance between points to detect gaps of missing data.
$prev_clock = null;
$points_distance = [];
foreach ($points as $clock => $point) {
if ($prev_clock !== null) {
$points_distance[] = $clock - $prev_clock;
}
$prev_clock = $clock;
}
/**
* $threshold is a minimal period of time at what we assume that data point is missed;
* $average_distance is an average distance between existing data points;
* $gap_interval is a time distance between missing points used to fulfill gaps of missing data.
* It's unique for each gap.
*/
$average_distance = $points_distance ? array_sum($points_distance) / count($points_distance) : 0;
$threshold = $points_distance ? $average_distance * 3 : 0;
// Add missing values.
$prev_clock = null;
$missing_points = [];
foreach ($points as $clock => $point) {
if ($prev_clock !== null && ($clock - $prev_clock) > $threshold) {
$gap_interval = floor(($clock - $prev_clock) / $threshold);
if ($missingdatafunc == SVG_GRAPH_MISSING_DATA_NONE) {
$missing_points[$prev_clock + $gap_interval] = null;
}
elseif ($missingdatafunc == SVG_GRAPH_MISSING_DATA_TREAT_AS_ZERO) {
$missing_points[$prev_clock + $gap_interval] = 0;
$missing_points[$clock - $gap_interval] = 0;
}
}
$prev_clock = $clock;
}
return $missing_points;
}
/**
* Add fill area to graph for metric of type SVG_GRAPH_TYPE_LINE or SVG_GRAPH_TYPE_STAIRCASE.
*/
protected function drawMetricArea(array $metric, array $paths) {
$y_zero = ($metric['options']['axisy'] == GRAPH_YAXIS_SIDE_RIGHT) ? $this->right_y_zero : $this->left_y_zero;
foreach ($paths as $path) {
if (count($path) > 1) {
$this->addItem(new CSvgGraphArea($path, $metric, $y_zero));
}
}
}
/**
* Add line paths to graph for metric of type SVG_GRAPH_TYPE_LINE or SVG_GRAPH_TYPE_STAIRCASE.
*/
protected function drawMetricsLine() {
foreach ($this->metrics as $index => $metric) {
if (array_key_exists($index, $this->paths) && ($metric['options']['type'] == SVG_GRAPH_TYPE_LINE
|| $metric['options']['type'] == SVG_GRAPH_TYPE_STAIRCASE)) {
if ($metric['options']['fill'] > 0) {
$this->drawMetricArea($metric, $this->paths[$index]);
}
$this->addItem(new CSvgGraphLineGroup($this->paths[$index], $metric));
}
}
}
/**
* Add metric of type points to graph.
*/
protected function drawMetricsPoint() {
foreach ($this->metrics as $index => $metric) {
if ($metric['options']['type'] == SVG_GRAPH_TYPE_POINTS && array_key_exists($index, $this->paths)) {
$this->addItem(new CSvgGraphPoints(reset($this->paths[$index]), $metric));
}
}
}
/**
* Add problems tooltip data to graph.
*/
protected function drawProblems() {
$today = strtotime('today');
$container = (new CSvgGroup())->addClass(CSvgTag::ZBX_STYLE_GRAPH_PROBLEMS);
foreach ($this->problems as $problem) {
// If problem is never recovered, it will be drown till the end of graph or till current time.
$time_to = ($problem['r_clock'] == 0)
? min($this->time_till, time())
: min($this->time_till, $problem['r_clock']);
$time_range = $this->time_till - $this->time_from;
$x1 = $this->canvas_x + $this->canvas_width
- $this->canvas_width * ($this->time_till - $problem['clock']) / $time_range;
$x2 = $this->canvas_x + $this->canvas_width
- $this->canvas_width * ($this->time_till - $time_to) / $time_range;
if ($this->canvas_x > $x1) {
$x1 = $this->canvas_x;
}
// Make problem info.
if ($problem['r_clock'] != 0) {
$status_str = _('RESOLVED');
$status_color = ZBX_STYLE_OK_UNACK_FG;
}
else {
$status_str = _('PROBLEM');
$status_color = ZBX_STYLE_PROBLEM_UNACK_FG;
foreach ($problem['acknowledges'] as $acknowledge) {
if ($acknowledge['action'] & ZBX_PROBLEM_UPDATE_CLOSE) {
$status_str = _('CLOSING');
$status_color = ZBX_STYLE_OK_UNACK_FG;
break;
}
}
}
$info = [
'name' => $problem['name'],
'clock' => ($problem['clock'] >= $today)
? zbx_date2str(TIME_FORMAT_SECONDS, $problem['clock'])
: zbx_date2str(DATE_TIME_FORMAT_SECONDS, $problem['clock']),
'r_clock' => ($problem['r_clock'] != 0)
? ($problem['r_clock'] >= $today)
? zbx_date2str(TIME_FORMAT_SECONDS, $problem['r_clock'])
: zbx_date2str(DATE_TIME_FORMAT_SECONDS, $problem['r_clock'])
: '',
'url' => (new CUrl('tr_events.php'))
->setArgument('triggerid', $problem['objectid'])
->setArgument('eventid', $problem['eventid'])
->getUrl(),
'r_eventid' => $problem['r_eventid'],
'severity' => getSeverityStyle($problem['severity'], $problem['r_clock'] == 0),
'status' => $status_str,
'status_color' => $status_color
];
// At least 3 pixels expected to be occupied to show the range. Show simple anotation otherwise.
$draw_type = ($x2 - $x1) > 2 ? CSvgGraphAnnotation::TYPE_RANGE : CSvgGraphAnnotation::TYPE_SIMPLE;
// Draw border lines. Make them dashed if beginning or ending of highligted zone is visible in graph.
if ($problem['clock'] > $this->time_from) {
$draw_type |= CSvgGraphAnnotation::DASH_LINE_START;
}
if ($this->time_till > $time_to) {
$draw_type |= CSvgGraphAnnotation::DASH_LINE_END;
}
$container->addItem(
(new CSvgGraphAnnotation($draw_type))
->setInformation(CJs::encodeJson($info))
->setSize(min($x2 - $x1, $this->canvas_width), $this->canvas_height)
->setPosition(max($x1, $this->canvas_x), $this->canvas_y)
->setColor($this->color_annotation)
);
}
$this->addItem($container);
}
}
|