Refractor InlinePie and Perfdata helper

Refractor InlinePie methods for better usability, fix several coding guideline
issues and fix some typos
This commit is contained in:
Matthias Jentsch 2014-06-25 10:54:38 +02:00
parent a94ef92cf7
commit f003c38abd
6 changed files with 105 additions and 86 deletions

View File

@ -46,7 +46,8 @@ use Icinga\Logger\Logger;
*/ */
class InlinePie extends AbstractWidget class InlinePie extends AbstractWidget
{ {
const NUMBER_FORMAT_TIME = 'time'; const NUMBER_FORMAT_NONE = 'none';
const NUMBER_FORMAT_TIME = 'time';
const NUMBER_FORMAT_BYTES = 'bytes'; const NUMBER_FORMAT_BYTES = 'bytes';
const NUMBER_FORMAT_RATIO = 'ratio'; const NUMBER_FORMAT_RATIO = 'ratio';
@ -126,7 +127,7 @@ EOD;
* *
* @var string * @var string
*/ */
private $title = ''; private $title;
/** /**
* The style for the HtmlElement * The style for the HtmlElement
@ -168,7 +169,7 @@ EOD;
* *
* @var array * @var array
*/ */
private $format = self::NUMBER_FORMAT_BYTES; private $format = self::NUMBER_FORMAT_NONE;
/** /**
* Set if the tooltip for the empty area should be hidden * Set if the tooltip for the empty area should be hidden
@ -194,18 +195,22 @@ EOD;
/** /**
* The labels to be displayed in the pie-chart * The labels to be displayed in the pie-chart
* *
* @param null $labels * @param mixed $label The label of the displayed value, or null for no labels
* *
* @return $this * @return $this Fluent interface
*/ */
public function setLabels($labels = null) public function setLabel($label)
{ {
if ($labels != null) { if (is_array($label)) {
$this->url->setParam('labels', implode(',', $labels)); $this->url->setParam('labels', implode(',', array_keys($label)));
} elseif ($label != null) {
$labelArr = array($label, $label, $label, '');
$this->url->setParam('labels', implode(',', $labelArr));
$label = $labelArr;
} else { } else {
$this->url->removeKey('labels'); $this->url->removeKey('labels');
} }
$this->labels = $labels; $this->labels = $label;
return $this; return $this;
} }
@ -318,10 +323,12 @@ EOD;
* Create a new InlinePie * Create a new InlinePie
* *
* @param array $data The data displayed by the slices * @param array $data The data displayed by the slices
* @param string $title The title of this Pie
* @param array $colors An array of RGB-Color values to use * @param array $colors An array of RGB-Color values to use
*/ */
public function __construct(array $data, $colors = null) public function __construct(array $data, $title, $colors = null)
{ {
$this->title = $title;
$this->url = Url::fromPath('svg/chart.php'); $this->url = Url::fromPath('svg/chart.php');
if (array_key_exists('data', $data)) { if (array_key_exists('data', $data)) {
$this->data = $data['data']; $this->data = $data['data'];
@ -346,10 +353,11 @@ EOD;
* *
* @return string A serialized array of labels * @return string A serialized array of labels
*/ */
private function createLabelString () { private function createLabelString ()
{
$labels = $this->labels; $labels = $this->labels;
foreach ($labels as $key => $label) { foreach ($labels as $key => $label) {
$labels[$key] = preg_replace('/|/', '', $label); $labels[$key] = str_replace('|', '', $label);
} }
return isset($this->labels) && is_array($this->labels) ? implode('|', $this->labels) : ''; return isset($this->labels) && is_array($this->labels) ? implode('|', $this->labels) : '';
} }
@ -363,27 +371,27 @@ EOD;
public function render() public function render()
{ {
$template = $this->template; $template = $this->template;
$template = preg_replace('{{url}}', $this->url, $template); $template = str_replace('{url}', $this->url, $template);
// style // style
$template = preg_replace('{{width}}', htmlspecialchars($this->width), $template); $template = str_replace('{width}', $this->width, $template);
$template = preg_replace('{{height}}', htmlspecialchars($this->height), $template); $template = str_replace('{height}', $this->height, $template);
$template = preg_replace('{{title}}', htmlspecialchars($this->title), $template); $template = str_replace('{title}', htmlspecialchars($this->title), $template);
$template = preg_replace('{{style}}', $this->style, $template); $template = str_replace('{style}', $this->style, $template);
$template = preg_replace('{{colors}}', implode(',', $this->colors), $template); $template = str_replace('{colors}', implode(',', $this->colors), $template);
$template = preg_replace('{{borderWidth}}', htmlspecialchars($this->borderWidth), $template); $template = str_replace('{borderWidth}', $this->borderWidth, $template);
$template = preg_replace('{{borderColor}}', htmlspecialchars($this->borderColor), $template); $template = str_replace('{borderColor}', $this->borderColor, $template);
$template = preg_replace('{{hideEmptyLabel}}', $this->hideEmptyLabel ? 'true' : 'false', $template); $template = str_replace('{hideEmptyLabel}', $this->hideEmptyLabel ? 'true' : 'false', $template);
// values // values
$formatted = array(); $formatted = array();
foreach ($this->data as $key => $value) { foreach ($this->data as $key => $value) {
$formatted[$key] = $this->formatValue($value); $formatted[$key] = $this->formatValue($value);
} }
$template = preg_replace('{{data}}', htmlspecialchars(implode(',', $this->data)), $template); $template = str_replace('{data}', htmlspecialchars(implode(',', $this->data)), $template);
$template = preg_replace('{{formatted}}', htmlspecialchars(implode('|', $formatted)), $template); $template = str_replace('{formatted}', htmlspecialchars(implode('|', $formatted)), $template);
$template = preg_replace('{{labels}}', htmlspecialchars($this->createLabelString()), $template); $template = str_replace('{labels}', htmlspecialchars($this->createLabelString()), $template);
$template = preg_replace('{{tooltipFormat}}', $this->tooltipFormat, $template); $template = str_replace('{tooltipFormat}', $this->tooltipFormat, $template);
return $template; return $template;
} }
@ -396,11 +404,13 @@ EOD;
*/ */
private function formatValue($value) private function formatValue($value)
{ {
if ($this->format === self::NUMBER_FORMAT_BYTES) { if ($this->format === self::NUMBER_FORMAT_NONE) {
return (string)$value;
} elseif ($this->format === self::NUMBER_FORMAT_BYTES) {
return Format::bytes($value); return Format::bytes($value);
} else if ($this->format === self::NUMBER_FORMAT_TIME) { } elseif ($this->format === self::NUMBER_FORMAT_TIME) {
return Format::duration($value); return Format::duration($value);
} else if ($this->format === self::NUMBER_FORMAT_RATIO) { } elseif ($this->format === self::NUMBER_FORMAT_RATIO) {
return $value; return $value;
} else { } else {
Logger::warning('Unknown format string "' . $this->format . '" for InlinePie, value not formatted.'); Logger::warning('Unknown format string "' . $this->format . '" for InlinePie, value not formatted.');

View File

@ -73,14 +73,18 @@ class Monitoring_MultiController extends Controller
$uniqueComments = array_keys($this->getUniqueValues($comments->getQuery()->fetchAll(), 'comment_internal_id')); $uniqueComments = array_keys($this->getUniqueValues($comments->getQuery()->fetchAll(), 'comment_internal_id'));
// Populate view // Populate view
$this->view->objects = $this->view->hosts = $hosts; $this->view->objects = $this->view->hosts = $hosts;
$this->view->problems = $this->getProblems($hosts); $this->view->problems = $this->getProblems($hosts);
$this->view->comments = $uniqueComments; $this->view->comments = $uniqueComments;
$this->view->hostnames = $this->getProperties($hosts, 'host_name'); $this->view->hostnames = $this->getProperties($hosts, 'host_name');
$this->view->downtimes = $this->getDowntimes($hosts); $this->view->downtimes = $this->getDowntimes($hosts);
$this->view->errors = $errors; $this->view->errors = $errors;
$this->view->states = $this->countStates($hosts, 'host', 'host_name'); $this->view->states = $this->countStates($hosts, 'host', 'host_name');
$this->view->pie = $this->createPie($this->view->states, $this->view->getHelper('MonitoringState')->getHostStateColors()); $this->view->pie = $this->createPie(
$this->view->states,
$this->view->getHelper('MonitoringState')->getHostStateColors(),
t('Host State')
);
// Handle configuration changes // Handle configuration changes
$this->handleConfigurationForm(array( $this->handleConfigurationForm(array(
@ -138,9 +142,17 @@ class Monitoring_MultiController extends Controller
$this->view->servicenames = $this->getProperties($services, 'service_description'); $this->view->servicenames = $this->getProperties($services, 'service_description');
$this->view->downtimes = $this->getDowntimes($services); $this->view->downtimes = $this->getDowntimes($services);
$this->view->service_states = $this->countStates($services, 'service'); $this->view->service_states = $this->countStates($services, 'service');
$this->view->host_states = $this->countStates($services, 'host', 'host_name'); $this->view->host_states = $this->countStates($services, 'host', 'host_name');
$this->view->service_pie = $this->createPie($this->view->service_states, $this->view->getHelper('MonitoringState')->getServiceStateColors()); $this->view->service_pie = $this->createPie(
$this->view->host_pie = $this->createPie($this->view->host_states, $this->view->getHelper('MonitoringState')->getHostStateColors()); $this->view->service_states,
$this->view->getHelper('MonitoringState')->getServiceStateColors(),
t('Service State')
);
$this->view->host_pie = $this->createPie(
$this->view->host_states,
$this->view->getHelper('MonitoringState')->getHostStateColors(),
t('Host State')
);
$this->view->errors = $errors; $this->view->errors = $errors;
$this->handleConfigurationForm(array( $this->handleConfigurationForm(array(
@ -181,13 +193,12 @@ class Monitoring_MultiController extends Controller
private function getUniqueValues($values, $key) private function getUniqueValues($values, $key)
{ {
$unique = array(); $unique = array();
foreach ($values as $value) foreach ($values as $value) {
{ if (is_array($value)) {
if (is_array($value)) { $unique[$value[$key]] = $value[$key];
$unique[$value[$key]] = $value[$key]; } else {
} else { $unique[$value->$key] = $value->$key;
$unique[$value->$key] = $value->$key; }
}
} }
return $unique; return $unique;
} }
@ -236,10 +247,11 @@ class Monitoring_MultiController extends Controller
return $states; return $states;
} }
private function createPie($states, $colors) private function createPie($states, $colors, $title)
{ {
$chart = new InlinePie(array_values($states), $colors); $chart = new InlinePie(array_values($states), $title, $colors);
$chart->setLabels(array_keys($states))->setHeight(100)->setWidth(100); $chart->setLabel(array_keys($states))->setHeight(100)->setWidth(100);
$chart->setTitle($title);
return $chart; return $chart;
} }

View File

@ -18,18 +18,14 @@ class Zend_View_Helper_Perfdata extends Zend_View_Helper_Abstract
if (!$perfdata->isPercentage() && $perfdata->getMaximumValue() === null) { if (!$perfdata->isPercentage() && $perfdata->getMaximumValue() === null) {
continue; continue;
} }
$pieChart = $this->createInlinePie($perfdata, $label); $pieChart = $this->createInlinePie($perfdata, $label, htmlspecialchars($label));
if ($compact) { if ($compact) {
$pieChart->setTitle(
htmlspecialchars($label) /* . ': ' . htmlspecialchars($this->formatPerfdataValue($perfdata) */
);
if (! $float) { if (! $float) {
$result .= $pieChart->render(); $result .= $pieChart->render();
} else { } else {
$result .= '<div style="float: right;">' . $pieChart->render() . '</div>'; $result .= '<div style="float: right;">' . $pieChart->render() . '</div>';
} }
} else { } else {
$pieChart->setTitle(htmlspecialchars($label));
if (! $perfdata->isPercentage()) { if (! $perfdata->isPercentage()) {
$pieChart->setTooltipFormat('{{label}}: {{formatted}} ({{percent}}%)'); $pieChart->setTooltipFormat('{{label}}: {{formatted}} ({{percent}}%)');
} }
@ -61,9 +57,9 @@ class Zend_View_Helper_Perfdata extends Zend_View_Helper_Abstract
$gray = $unusedValue; $gray = $unusedValue;
$green = $orange = $red = 0; $green = $orange = $red = 0;
// TODO(#6122): Add proper treshold parsing. // TODO(#6122): Add proper treshold parsing.
if ($perfdata->getCriticalTreshold() && $perfdata->getValue() > $perfdata->getCriticalTreshold()) { if ($perfdata->getCriticalThreshold() && $perfdata->getValue() > $perfdata->getCriticalThreshold()) {
$red = $usedValue; $red = $usedValue;
} elseif ($perfdata->getWarningTreshold() && $perfdata->getValue() > $perfdata->getWarningTreshold()) { } elseif ($perfdata->getWarningThreshold() && $perfdata->getValue() > $perfdata->getWarningThreshold()) {
$orange = $usedValue; $orange = $usedValue;
} else { } else {
$green = $usedValue; $green = $usedValue;
@ -85,10 +81,10 @@ class Zend_View_Helper_Perfdata extends Zend_View_Helper_Abstract
return $perfdata->getValue(); return $perfdata->getValue();
} }
protected function createInlinePie(Perfdata $perfdata, $label = '') protected function createInlinePie(Perfdata $perfdata, $title, $label = '')
{ {
$pieChart = new InlinePie($this->calculatePieChartData($perfdata)); $pieChart = new InlinePie($this->calculatePieChartData($perfdata), $title);
$pieChart->setLabels(array($label, $label, $label, '')); $pieChart->setLabel($label);
$pieChart->setHideEmptyLabel(); $pieChart->setHideEmptyLabel();
//$pieChart->setHeight(32)->setWidth(32); //$pieChart->setHeight(32)->setWidth(32);

View File

@ -3,8 +3,8 @@ $this->is_service = true;
$this->hostquery = implode($this->hostnames, ','); $this->hostquery = implode($this->hostnames, ',');
$this->servicequery = implode($this->servicenames, ','); $this->servicequery = implode($this->servicenames, ',');
$this->target = array( $this->target = array(
'host' => $this->hostquery, 'host' => $this->hostquery,
'service' => $this->servicequery 'service' => $this->servicequery
); );
?> ?>
@ -24,11 +24,11 @@ $this->target = array(
<td align="center"><?= $this->service_pie->render() ?></td> <td align="center"><?= $this->service_pie->render() ?></td>
<td><?php <td><?php
foreach ($service_states as $state => $count) { foreach ($service_states as $state => $count) {
if ($count > 0) { if ($count > 0) {
echo ucfirst($state) . ': ' . $count . '<br />'; echo ucfirst($state) . ': ' . $count . '<br />';
} }
} }
?></td> ?></td>
<td align="center"><?= $this->host_pie->render() ?></td> <td align="center"><?= $this->host_pie->render() ?></td>

View File

@ -19,6 +19,7 @@ class Perfdata
* Unit of measurement (UOM) * Unit of measurement (UOM)
* *
* @var string * @var string
* @var string
*/ */
protected $unit; protected $unit;
@ -44,18 +45,18 @@ class Perfdata
protected $maxValue; protected $maxValue;
/** /**
* The WARNING treshold * The WARNING threshold
* *
* @var string * @var string
*/ */
protected $warningTreshold; protected $warningThreshold;
/** /**
* The CRITICAL treshold * The CRITICAL threshold
* *
* @var string * @var string
*/ */
protected $criticalTreshold; protected $criticalThreshold;
/** /**
* Create a new Perfdata object based on the given performance data value * Create a new Perfdata object based on the given performance data value
@ -180,9 +181,9 @@ class Perfdata
* *
* @return null|string * @return null|string
*/ */
public function getWarningTreshold() public function getWarningThreshold()
{ {
return $this->warningTreshold; return $this->warningThreshold;
} }
/** /**
@ -190,9 +191,9 @@ class Perfdata
* *
* @return null|string * @return null|string
*/ */
public function getCriticalTreshold() public function getCriticalThreshold()
{ {
return $this->criticalTreshold; return $this->criticalThreshold;
} }
/** /**
@ -240,10 +241,10 @@ class Perfdata
$this->minValue = self::convert($parts[3], $this->unit); $this->minValue = self::convert($parts[3], $this->unit);
case 3: case 3:
// TODO(#6123): Tresholds have the same UOM and need to be converted as well! // TODO(#6123): Tresholds have the same UOM and need to be converted as well!
$this->criticalTreshold = trim($parts[2]) ? trim($parts[2]) : null; $this->criticalThreshold = trim($parts[2]) ? trim($parts[2]) : null;
case 2: case 2:
// TODO(#6123): Tresholds have the same UOM and need to be converted as well! // TODO(#6123): Tresholds have the same UOM and need to be converted as well!
$this->warningTreshold = trim($parts[1]) ? trim($parts[1]) : null; $this->warningThreshold = trim($parts[1]) ? trim($parts[1]) : null;
} }
} }

View File

@ -61,27 +61,27 @@ class PerfdataTest extends BaseTestCase
{ {
$this->assertEquals( $this->assertEquals(
'10', '10',
Perfdata::fromString('1;10')->getWarningTreshold(), Perfdata::fromString('1;10')->getWarningThreshold(),
'Perfdata::getWarningTreshold does not return correct values' 'Perfdata::getWarningTreshold does not return correct values'
); );
$this->assertEquals( $this->assertEquals(
'10:', '10:',
Perfdata::fromString('1;10:')->getWarningTreshold(), Perfdata::fromString('1;10:')->getWarningThreshold(),
'Perfdata::getWarningTreshold does not return correct values' 'Perfdata::getWarningTreshold does not return correct values'
); );
$this->assertEquals( $this->assertEquals(
'~:10', '~:10',
Perfdata::fromString('1;~:10')->getWarningTreshold(), Perfdata::fromString('1;~:10')->getWarningThreshold(),
'Perfdata::getWarningTreshold does not return correct values' 'Perfdata::getWarningTreshold does not return correct values'
); );
$this->assertEquals( $this->assertEquals(
'10:20', '10:20',
Perfdata::fromString('1;10:20')->getWarningTreshold(), Perfdata::fromString('1;10:20')->getWarningThreshold(),
'Perfdata::getWarningTreshold does not return correct values' 'Perfdata::getWarningTreshold does not return correct values'
); );
$this->assertEquals( $this->assertEquals(
'@10:20', '@10:20',
Perfdata::fromString('1;@10:20')->getWarningTreshold(), Perfdata::fromString('1;@10:20')->getWarningThreshold(),
'Perfdata::getWarningTreshold does not return correct values' 'Perfdata::getWarningTreshold does not return correct values'
); );
} }
@ -90,27 +90,27 @@ class PerfdataTest extends BaseTestCase
{ {
$this->assertEquals( $this->assertEquals(
'10', '10',
Perfdata::fromString('1;;10')->getCriticalTreshold(), Perfdata::fromString('1;;10')->getCriticalThreshold(),
'Perfdata::getCriticalTreshold does not return correct values' 'Perfdata::getCriticalTreshold does not return correct values'
); );
$this->assertEquals( $this->assertEquals(
'10:', '10:',
Perfdata::fromString('1;;10:')->getCriticalTreshold(), Perfdata::fromString('1;;10:')->getCriticalThreshold(),
'Perfdata::getCriticalTreshold does not return correct values' 'Perfdata::getCriticalTreshold does not return correct values'
); );
$this->assertEquals( $this->assertEquals(
'~:10', '~:10',
Perfdata::fromString('1;;~:10')->getCriticalTreshold(), Perfdata::fromString('1;;~:10')->getCriticalThreshold(),
'Perfdata::getCriticalTreshold does not return correct values' 'Perfdata::getCriticalTreshold does not return correct values'
); );
$this->assertEquals( $this->assertEquals(
'10:20', '10:20',
Perfdata::fromString('1;;10:20')->getCriticalTreshold(), Perfdata::fromString('1;;10:20')->getCriticalThreshold(),
'Perfdata::getCriticalTreshold does not return correct values' 'Perfdata::getCriticalTreshold does not return correct values'
); );
$this->assertEquals( $this->assertEquals(
'@10:20', '@10:20',
Perfdata::fromString('1;;@10:20')->getCriticalTreshold(), Perfdata::fromString('1;;@10:20')->getCriticalThreshold(),
'Perfdata::getCriticalTreshold does not return correct values' 'Perfdata::getCriticalTreshold does not return correct values'
); );
} }
@ -147,7 +147,7 @@ class PerfdataTest extends BaseTestCase
{ {
$perfdata = Perfdata::fromString('1;;3;5'); $perfdata = Perfdata::fromString('1;;3;5');
$this->assertNull( $this->assertNull(
$perfdata->getWarningTreshold(), $perfdata->getWarningThreshold(),
'Perfdata objects do not return null for missing warning tresholds' 'Perfdata objects do not return null for missing warning tresholds'
); );
$this->assertNull( $this->assertNull(