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
|
<?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.
**/
/**
* Class calculates graph data and makes SVG graph.
*/
class CSvgGraphHelper {
/**
* Calculate graph data and draw SVG graph based on given graph configuration.
*
* @param array $options Options for graph.
* @param array $options['data_sets'] Graph data set options.
* @param int $options['data_source'] Data source of graph.
* @param bool $options['dashboard_time'] True if dashboard time is used.
* @param array $options['time_period'] Graph time period used.
* @param array $options['left_y_axis'] Options for graph left Y axis.
* @param array $options['right_y_axis'] Options for graph right Y axis.
* @param array $options['x_axis'] Options for graph X axis.
* @param array $options['legend'] Options for graph legend.
* @param int $options['legend_lines'] Number of lines in the legend.
* @param array $options['problems'] Graph problems options.
* @param array $options['overrides'] Graph override options.
*
* @return array
*/
public static function get(array $options = [], $width, $height) {
$metrics = [];
$errors = [];
$problems = [];
// Find which metrics will be shown in graph and calculate time periods and display options.
self::getMetrics($metrics, $options['data_sets']);
// Apply overrides for previously selected $metrics.
self::applyOverrides($metrics, $options['overrides']);
// Apply time periods for each $metric, based on graph/dashboard time as well as metric level timeshifts.
self::getTimePeriods($metrics, $options['time_period']);
// Find what data source (history or trends) will be used for each metric.
self::getGraphDataSource($metrics, $errors, $options['data_source'], $width);
// Load Data for each metric.
self::getMetricsData($metrics, $errors, $width);
// Legend single line height is 18. Value should be synchronized with $svg-legend-line-height in 'screen.scss'.
$legend_height = ($options['legend'] == SVG_GRAPH_LEGEND_TYPE_SHORT) ? $options['legend_lines'] * 18 : 0;
$metrics = CMacrosResolverHelper::resolveItemNames($metrics);
$metrics = CArrayHelper::renameObjectsKeys($metrics, ['name_expanded' => 'name']);
// Draw SVG graph.
$graph = (new CSvgGraph([
'time_period' => $options['time_period'],
'x_axis' => $options['x_axis'],
'left_y_axis' => $options['left_y_axis'],
'right_y_axis' => $options['right_y_axis']
]))
->setSize($width, $height - $legend_height)
->addMetrics($metrics);
// Get problems to display in graph.
if ($options['problems']['show_problems'] == SVG_GRAPH_PROBLEMS_SHOW) {
$options['problems']['itemids'] =
($options['problems']['graph_item_problems'] == SVG_GRAPH_SELECTED_ITEM_PROBLEMS)
? array_unique(zbx_objectValues($metrics, 'itemid'))
: null;
$problems = self::getProblems($options['problems'], $options['time_period']);
$graph->addProblems($problems);
}
if ($legend_height > 0) {
$labels = [];
foreach ($metrics as $metric) {
$labels[] = [
'name' => $metric['hosts'][0]['name'].NAME_DELIMITER.$metric['name'],
'color' => $metric['options']['color']
];
}
$legend = (new CSvgGraphLegend($labels))
->setAttribute('style', 'height: '.$legend_height.'px')
->toString();
}
else {
$legend = '';
}
// Draw graph.
$graph->draw();
// SBox available only for graphs without overriten relative time.
if ($options['dashboard_time']) {
$graph->addSBox();
}
// Add mouse following helper line.
$graph->addHelper();
return [
'svg' => $graph,
'legend' => $legend,
'data' => [
'dims' => [
'x' => $graph->getCanvasX(),
'y' => $graph->getCanvasY(),
'w' => $graph->getCanvasWidth(),
'h' => $graph->getCanvasHeight()
],
'spp' => (int) ($options['time_period']['time_to'] - $options['time_period']['time_from']) / $graph->getCanvasWidth()
],
'errors' => $errors
];
}
/**
* Select data to show in graph for each metric.
*/
protected static function getMetricsData(array &$metrics = [], array &$errors = [], $width) {
// To reduce number of requests, group metrics by time range.
$tr_groups = [];
foreach ($metrics as $metric_num => &$metric) {
$metric['points'] = [];
$key = $metric['time_period']['time_from'].$metric['time_period']['time_to'];
if (!array_key_exists($key, $tr_groups)) {
$tr_groups[$key]['time'] = [
'from' => $metric['time_period']['time_from'],
'to' => $metric['time_period']['time_to']
];
}
$tr_groups[$key]['items'][$metric_num] = [
'itemid' => $metric['itemid'],
'value_type' => $metric['value_type'],
'source' => ($metric['source'] == SVG_GRAPH_DATA_SOURCE_HISTORY) ? 'history' : 'trends'
];
}
unset($metric);
// Request data.
foreach ($tr_groups as $tr_group) {
$results = Manager::History()->getGraphAggregation($tr_group['items'], $tr_group['time']['from'],
$tr_group['time']['to'], $width
);
if ($results) {
foreach ($tr_group['items'] as $metric_num => $item) {
$metric = &$metrics[$metric_num];
// Collect and sort data points.
if (array_key_exists($item['itemid'], $results)) {
$points = [];
foreach ($results[$item['itemid']]['data'] as $point) {
$points[] = ['clock' => $point['clock'], 'value' => $point['avg']];
}
usort($points, [__CLASS__, 'sortByClock']);
$metric['points'] = $points;
unset($metric['source'], $metric['history'], $metric['trends']);
}
}
unset($metric);
}
}
return $metrics;
}
/**
* Calculate what data source must be used for each metric.
*/
protected static function getGraphDataSource(array &$metrics = [], array &$errors = [], $data_source, $width) {
/**
* If data source is not specified, calculate it automatically. Otherwise, set given $data_source to each
* $metric.
*/
if ($data_source == SVG_GRAPH_DATA_SOURCE_AUTO) {
/**
* First, if global configuration setting "Override item history period" is enabled, override globally
* specified "Data storage period" value to each metric's custom history storage duration, converting it
* to seconds. If "Override item history period" is disabled, item level field 'history' will be used
* later but now we are just storing the field name 'history' in array $to_resolve.
*
* Do the same with trends.
*/
$config = select_config();
$to_resolve = [];
if ($config['hk_history_global']) {
foreach ($metrics as &$metric) {
$metric['history'] = timeUnitToSeconds($config['hk_history']);
}
unset($metric);
}
else {
$to_resolve[] = 'history';
}
if ($config['hk_trends_global']) {
foreach ($metrics as &$metric) {
$metric['trends'] = timeUnitToSeconds($config['hk_trends']);
}
unset($metric);
}
else {
$to_resolve[] = 'trends';
}
// If no global history and trend override enabled, resolve 'history' and/or 'trends' values for given $metric.
if ($to_resolve) {
$metrics = CMacrosResolverHelper::resolveTimeUnitMacros($metrics, $to_resolve);
$simple_interval_parser = new CSimpleIntervalParser();
foreach ($metrics as $num => &$metric) {
// Convert its values to seconds.
if (!$config['hk_history_global']) {
if ($simple_interval_parser->parse($metric['history']) != CParser::PARSE_SUCCESS) {
$errors[] = _s('Incorrect value for field "%1$s": %2$s.', 'history',
_('invalid history storage period')
);
unset($metrics[$num]);
}
else {
$metric['history'] = timeUnitToSeconds($metric['history']);
}
}
if (!$config['hk_trends_global']) {
if ($simple_interval_parser->parse($metric['trends']) != CParser::PARSE_SUCCESS) {
$errors[] = _s('Incorrect value for field "%1$s": %2$s.', 'trends',
_('invalid trend storage period')
);
unset($metrics[$num]);
}
else {
$metric['trends'] = timeUnitToSeconds($metric['trends']);
}
}
}
unset($metric);
}
foreach ($metrics as &$metric) {
/**
* History as a data source is used in 2 cases:
* 1) if trends are disabled (set to 0) either for particular $metric item or globally;
* 2) if period for requested data is newer than the period of keeping history for particular $metric
* item.
*
* Use trends otherwise.
*/
$history = $metric['history'];
$trends = $metric['trends'];
$time_from = $metric['time_period']['time_from'];
$period = $metric['time_period']['time_to'] - $time_from;
$metric['source'] = ($trends == 0 || (time() - $history < $time_from
&& $period / $width <= ZBX_MAX_TREND_DIFF / ZBX_GRAPH_MAX_SKIP_CELL))
? SVG_GRAPH_DATA_SOURCE_HISTORY
: SVG_GRAPH_DATA_SOURCE_TRENDS;
}
unset($metric);
}
else {
foreach ($metrics as &$metric) {
$metric['source'] = $data_source;
}
unset($metric);
}
}
/**
* Find problems at given time period that matches specified problem options.
*/
protected static function getProblems(array $problem_options, array $time_period) {
$options = [
'output' => ['objectid', 'name', 'severity', 'clock', 'r_eventid'],
'select_acknowledges' => ['action'],
'problem_time_from' => $time_period['time_from'],
'problem_time_till' => $time_period['time_to'],
'preservekeys' => true
];
// Find triggers involved.
if ($problem_options['problemhosts'] !== '') {
$options['hostids'] = array_keys(API::Host()->get([
'output' => [],
'searchWildcardsEnabled' => true,
'searchByAny' => true,
'search' => [
'name' => self::processPattern($problem_options['problemhosts'])
],
'preservekeys' => true
]));
// Return if no hosts found.
if (!$options['hostids']) {
return [];
}
}
// Filter out only items of selected metrics.
if ($problem_options['itemids'] !== null) {
$options['objectids'] = array_keys(API::Trigger()->get([
'output' => [],
'hostids' => array_key_exists('hostids', $options) ? $options['hostids'] : null,
'itemids' => $problem_options['itemids'],
'preservekeys' => true
]));
// Return if no triggers found.
if (!$options['objectids']) {
return [];
}
unset($options['hostids']);
}
// Add severity filter.
$filter_severities = implode(',', $problem_options['severities']);
$all_severities = implode(',', range(TRIGGER_SEVERITY_NOT_CLASSIFIED, TRIGGER_SEVERITY_COUNT - 1));
if ($filter_severities !== '' && $filter_severities !== $all_severities) {
$options['severities'] = $problem_options['severities'];
}
// Add problem name filter.
if ($problem_options['problem_name'] !== '') {
$options['searchWildcardsEnabled'] = true;
$options['search']['name'] = $problem_options['problem_name'];
}
// Add tags filter.
if ($problem_options['tags']) {
$options['evaltype'] = $problem_options['evaltype'];
$options['tags'] = $problem_options['tags'];
}
$events = API::Event()->get($options);
// Find end time for each problem.
if ($events) {
$r_events = API::Event()->get([
'output' => ['clock'],
'eventids' => zbx_objectValues($events, 'r_eventid'),
'preservekeys' => true
]);
}
// Add recovery times for each problem event.
foreach ($events as &$event) {
$event['r_clock'] = array_key_exists($event['r_eventid'], $r_events)
? $r_events[$event['r_eventid']]['clock']
: 0;
}
unset($event);
CArrayHelper::sort($events, [['field' => 'clock', 'order' => ZBX_SORT_DOWN]]);
return $events;
}
/**
* Select metrics from given data set options. Apply data set options to each selected metric.
*/
protected static function getMetrics(array &$metrics, array $data_sets) {
$max_metrics = SVG_GRAPH_MAX_NUMBER_OF_METRICS;
foreach ($data_sets as $data_set) {
if (!$data_set['hosts'] || !$data_set['items']) {
continue;
}
if ($max_metrics == 0) {
break;
}
// Find hosts.
$hosts = API::Host()->get([
'output' => [],
'search' => [
'name' => self::processPattern($data_set['hosts'])
],
'searchWildcardsEnabled' => true,
'searchByAny' => true,
'preservekeys' => true
]);
if ($hosts) {
$items = API::Item()->get([
'output' => [
'itemid', 'hostid', 'name', 'history', 'trends', 'units', 'value_type', 'valuemapid', 'key_'
],
'selectHosts' => ['hostid', 'name'],
'hostids' => array_keys($hosts),
'webitems' => true,
'filter' => [
'value_type' => [ITEM_VALUE_TYPE_UINT64, ITEM_VALUE_TYPE_FLOAT]
],
'search' => [
'name' => self::processPattern($data_set['items'])
],
'searchWildcardsEnabled' => true,
'searchByAny' => true,
'sortfield' => 'name',
'sortorder' => ZBX_SORT_UP,
'limit' => $max_metrics
]);
if (!$items) {
continue;
}
unset($data_set['hosts'], $data_set['items']);
// The bigger transparency level, the less visibile the metric is.
$data_set['transparency'] = 10 - (int) $data_set['transparency'];
$data_set['timeshift'] = ($data_set['timeshift'] !== '')
? (int) timeUnitToSeconds($data_set['timeshift'])
: 0;
$colors = getColorVariations('#'.$data_set['color'], count($items));
foreach ($items as $item) {
$data_set['color'] = array_shift($colors);
$metrics[] = $item + ['options' => $data_set];
$max_metrics--;
}
}
}
}
/**
* Apply overrides for each pattern matchig metric.
*/
protected static function applyOverrides(array &$metrics = [], array $overrides = []) {
foreach ($overrides as $override) {
if ($override['hosts'] === '' || $override['items'] === '') {
continue;
}
// Convert timeshift to seconds.
if (array_key_exists('timeshift', $override)) {
$override['timeshift'] = ($override['timeshift'] !== '')
? (int) timeUnitToSeconds($override['timeshift'])
: 0;
}
$hosts_patterns = self::processPattern($override['hosts']);
$items_patterns = self::processPattern($override['items']);
unset($override['hosts'], $override['items']);
$metrics_matched = [];
foreach ($metrics as $metric_num => $metric) {
// If '*' used, apply options to all metrics.
$host_matches = ($hosts_patterns === null);
$item_matches = ($items_patterns === null);
/**
* Find if host and item names matches one of given patterns.
*
* It currently checks if at least one of host pattern and at least one of item pattern matches,
* without checking relation between matching host and item.
*/
if ($hosts_patterns !== null) {
for ($hosts_pattern = reset($hosts_patterns); !$host_matches && $hosts_pattern !== false;
$hosts_pattern = next($hosts_patterns)) {
$pattern = '/^'.str_replace('\*', '.*', preg_quote($hosts_pattern, '/')).'$/i';
$host_matches = (bool) preg_match($pattern, $metric['hosts'][0]['name']);
}
}
if ($items_patterns !== null && $host_matches) {
for ($items_pattern = reset($items_patterns); !$item_matches && $items_pattern !== false;
$items_pattern = next($items_patterns)) {
$pattern = '/^'.str_replace('\*', '.*', preg_quote($items_pattern, '/')).'$/i';
$item_matches = (bool) preg_match($pattern, $metric['name']);
}
}
/**
* We need to know total amount of matched metrics to calculate variations of colors. That's why we
* first collect matching metrics and than override existing metric options.
*/
if ($host_matches && $item_matches) {
$metrics_matched[] = $metric_num;
}
}
// Apply override options to matching metrics.
if ($metrics_matched) {
$colors = (array_key_exists('color', $override) && $override['color'] !== '')
? getColorVariations('#'.$override['color'], count($metrics_matched))
: null;
if (array_key_exists('transparency', $override)) {
// The bigger transparency level, the less visibile the metric is.
$override['transparency'] = 10 - (int) $override['transparency'];
}
foreach ($metrics_matched as $metric_num) {
$metric = &$metrics[$metric_num];
if ($colors !== null) {
$override['color'] = array_shift($colors);
}
$metric['options'] = $override + $metric['options'];
// Fix missing options if draw type has changed.
switch ($metric['options']['type']) {
case SVG_GRAPH_TYPE_POINTS:
if (!array_key_exists('pointsize', $metric['options'])) {
$metric['options']['pointsize'] = SVG_GRAPH_DEFAULT_POINTSIZE;
}
break;
case SVG_GRAPH_TYPE_LINE:
case SVG_GRAPH_TYPE_STAIRCASE:
if (!array_key_exists('fill', $metric['options'])) {
$metric['options']['fill'] = SVG_GRAPH_DEFAULT_FILL;
}
if (!array_key_exists('missingdatafunc', $metric['options'])) {
$metric['options']['missingdatafunc'] = SVG_GRAPH_MISSING_DATA_NONE;
}
if (!array_key_exists('width', $metric['options'])) {
$metric['options']['width'] = SVG_GRAPH_DEFAULT_WIDTH;
}
break;
}
}
unset($metric);
}
}
}
/**
* Apply time period for each metric.
*/
protected static function getTimePeriods(array &$metrics = [], array $options) {
foreach ($metrics as &$metric) {
$metric['time_period'] = $options;
if ($metric['options']['timeshift'] != 0) {
$metric['time_period']['time_from'] =
bcadd($metric['time_period']['time_from'], $metric['options']['timeshift'], 0);
$metric['time_period']['time_to'] =
bcadd($metric['time_period']['time_to'], $metric['options']['timeshift'], 0);
}
}
unset($metric);
}
/**
* Prepare an array to be used for hosts/items filtering.
*
* @param string $patterns String containing hosts/items patterns.
*
* @return mixed|array Returns array of patterns or NULL if all tested hosts/items are valid.
*/
protected static function processPattern($patterns) {
$patterns = array_keys(array_flip(preg_split('/(\r\n|\n|,)/', $patterns)));
foreach ($patterns as &$pattern) {
$pattern = trim($pattern);
if ($pattern === '*') {
$patterns = null;
break;
}
}
unset($pattern);
if ($patterns !== null) {
$patterns = array_filter($patterns, 'strlen');
}
return $patterns;
}
/*
* Sort data points by clock field.
* Do not use this function directly. It serves as value_compare_func function for usort.
*/
protected static function sortByClock($a, $b) {
if ($a['clock'] == $b['clock']) {
return 0;
}
return ($a['clock'] < $b['clock']) ? -1 : 1;
}
}
|