Fix PSR compliance

Commit first part of correction.

refs #4246
This commit is contained in:
Marius Hein 2013-06-06 16:52:54 +02:00
parent 11f4a5b0b5
commit 172c699c47
23 changed files with 962 additions and 311 deletions

View File

@ -1,14 +1,26 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
// TODO: Search for the best and safest quoting
// TODO: Check whether attributes are safe. Script, title in combination with
// Hover-Tips etc. Eventually create a whitelist for a few options only.
/**
* Class Zend_View_Helper_Qlink
* @package Application\Views
*/
class Zend_View_Helper_Qlink extends Zend_View_Helper_Abstract
{
public function qlink($htmlContent, $urlFormat, array $uriParams = array(),
array $properties = array())
{
/**
* @param $htmlContent
* @param $urlFormat
* @param array $uriParams
* @param array $properties
* @return string
*/
public function qlink(
$htmlContent,
$urlFormat,
array $uriParams = array(),
array $properties = array()
) {
$quote = true;
$attributes = array();
$baseUrl = null;
@ -47,17 +59,20 @@ class Zend_View_Helper_Qlink extends Zend_View_Helper_Abstract
'<a href="%s"%s>%s</a>',
$this->getFormattedUrl($urlFormat, $uriParams, $baseUrl),
!empty($attributes) ? ' ' . implode(' ', $attributes) : '',
$quote
? filter_var(
$quote ? filter_var(
$htmlContent,
FILTER_SANITIZE_FULL_SPECIAL_CHARS,
FILTER_FLAG_NO_ENCODE_QUOTES
)
// Alternativ: htmlentities($htmlContent)
: $htmlContent
) : $htmlContent // Alternative: htmlentities($htmlContent)
);
}
/**
* @param $urlFormat
* @param $uriParams
* @param null $baseUrl
* @return string
*/
public function getFormattedUrl($urlFormat, $uriParams, $baseUrl = null)
{
$params = $args = array();
@ -76,4 +91,3 @@ class Zend_View_Helper_Qlink extends Zend_View_Helper_Abstract
return is_null($baseUrl) ? $this->view->baseUrl($url) : $baseUrl . $url;
}
}

View File

@ -1,32 +1,76 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Application;
/**
* Class Logger
* @package Icinga\Application
*/
class Logger
{
/**
*
*/
const DEFAULT_LOG_TYPE = "stream";
/**
*
*/
const DEFAULT_LOG_TARGET = "./var/log/icinga.log";
/**
*
*/
const DEFAULT_DEBUG_TARGET = "./var/log/icinga.debug.log";
/**
* @var array
*/
private $writers = array();
/**
* @var null
*/
private $logger = null;
/**
* @var
*/
private static $instance;
/**
* @var array
*/
private static $queue = array();
/**
* @param \Zend_Config $config
*/
public function __construct(\Zend_Config $config)
{
$this->overwrite($config);
}
public function getWriters() {
/**
* @return array
*/
public function getWriters()
{
return $this->writers;
}
/**
* @param \Zend_Config $config
*/
public function overwrite(\Zend_Config $config)
{
$this->clearLog();
try {
if ($config->debug && $config->debug->enable == 1)
if ($config->debug && $config->debug->enable == 1) {
$this->setupDebugLog($config);
}
} catch (\Icinga\Exception\ConfigurationError $e) {
$this->warn("Could not create debug log: {$e->getMessage()}");
}
@ -35,34 +79,50 @@ class Logger
$this->flushQueue();
}
/**
* @param \Zend_Config $config
*/
private function setupDebugLog(\Zend_Config $config)
{
$type = $config->debug->get("type", self::DEFAULT_LOG_TYPE);
$target = $config->debug->get("target", self::DEFAULT_LOG_TARGET);
if ($target == self::DEFAULT_LOG_TARGET)
if ($target == self::DEFAULT_LOG_TARGET) {
$type == self::DEFAULT_LOG_TYPE;
}
$this->addWriter($type, $target, \Zend_Log::DEBUG);
}
/**
* @param \Zend_Config $config
*/
private function setupLog(\Zend_Config $config)
{
$type = $config->get("type", self::DEFAULT_LOG_TYPE);
$target = $config->get("target", self::DEFAULT_DEBUG_TARGET);
if ($target == self::DEFAULT_DEBUG_TARGET)
if ($target == self::DEFAULT_DEBUG_TARGET) {
$type == self::DEFAULT_LOG_TYPE;
}
$level = \Zend_Log::WARN;
if ($config->get("verbose", 0) == 1)
if ($config->get("verbose", 0) == 1) {
$level = \Zend_Log::INFO;
}
$this->addWriter($type, $target, $level);
}
/**
* @param $type
* @param $target
* @param $priority
* @throws \Icinga\Exception\ConfigurationError
*/
private function addWriter($type, $target, $priority)
{
$type[0] = strtoupper($type[0]);
$writerClass = "\Zend_Log_Writer_" . $type;
if (!class_exists($writerClass))
if (!class_exists($writerClass)) {
throw new \Icinga\Exception\ConfigurationError("Could not create log: Unknown type " . $type);
}
$writer = new $writerClass($target);
@ -71,6 +131,9 @@ class Logger
$this->writers[] = $writer;
}
/**
* flushQueue
*/
public function flushQueue()
{
foreach (self::$queue as $msgTypePair) {
@ -78,6 +141,10 @@ class Logger
}
}
/**
* @param array $argv
* @return string
*/
public static function formatMessage(array $argv)
{
@ -90,14 +157,17 @@ class Logger
$format = json_encode($format);
}
foreach ($argv as &$arg) {
if (!is_string($arg))
if (!is_string($arg)) {
$arg = json_encode($arg);
}
}
return @vsprintf($format, $argv);
}
/**
* clearLog
*/
public function clearLog()
{
$this->logger = null;
@ -105,35 +175,64 @@ class Logger
$this->logger = new \Zend_Log();
}
/**
* @param \Zend_Config $config
* @return Logger
*/
public static function create(\Zend_Config $config)
{
if (self::$instance)
if (self::$instance) {
return self::$instance->overwrite($config);
}
return self::$instance = new Logger($config);
}
/**
* debug
*/
public static function debug()
{
self::log(self::formatMessage(func_get_args()), \Zend_Log::DEBUG);
}
public static function warn() {
/**
*
*/
public static function warn()
{
self::log(self::formatMessage(func_get_args()), \Zend_Log::WARN);
}
public static function info() {
/**
*
*/
public static function info()
{
self::log(self::formatMessage(func_get_args()), \Zend_Log::INFO);
}
public static function error() {
/**
*
*/
public static function error()
{
self::log(self::formatMessage(func_get_args()), \Zend_Log::ERR);
}
public static function fatal() {
/**
*
*/
public static function fatal()
{
self::log(self::formatMessage(func_get_args()), \Zend_Log::EMERG);
}
private static function log($msg,$level = \Zend_Log::INFO) {
/**
* @param $msg
* @param int $level
*/
private static function log($msg, $level = \Zend_Log::INFO)
{
$logger = self::$instance;
if (!$logger) {
@ -144,8 +243,11 @@ class Logger
$logger->logger->log($msg, $level);
}
public static function reset() {
/**
*
*/
public static function reset()
{
self::$queue = array();
self::$instance = null;
}

View File

@ -1,16 +1,26 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Backend;
use Icinga\Application\Config;
/**
* Icinga Backend Abstract
*
* @package Icinga\Backend
*/
namespace Icinga\Backend;
use Icinga\Application\Config;
abstract class AbstractBackend
{
/**
* @var \Zend_Config
*/
protected $config;
/**
* @var array
*/
protected $extensions = array();
/**
@ -23,8 +33,9 @@ abstract class AbstractBackend
*/
final public function __construct(\Zend_Config $config = null)
{
if ($config == null)
if ($config == null) {
$config = new \Zend_Config(array());
}
$this->config = $config;
$this->init();
}
@ -34,7 +45,9 @@ abstract class AbstractBackend
*
* return void
*/
protected function init() {}
protected function init()
{
}
/**
* Dummy function for fluent code
@ -52,8 +65,10 @@ abstract class AbstractBackend
* Leave fields empty to get all available properties
*
* @param string Virtual table name
* @param array Fields
* return \Icinga\Backend\Ido\Query
* @param array $fields
* @throws \Exception
* @return
* @internal param \Icinga\Backend\Fields $array return \Icinga\Backend\Ido\Query* return \Icinga\Backend\Ido\Query
*/
public function from($virtual_table, $fields = array())
{
@ -65,11 +80,19 @@ abstract class AbstractBackend
return $query;
}
/**
* @param $virtual_table
* @return bool
*/
public function hasView($virtual_table)
{
return class_exists($this->tableToClassName($virtual_table));
}
/**
* @param $virtual_table
* @return string
*/
protected function tableToClassName($virtual_table)
{
if (strpos($virtual_table, "/") !== false) {
@ -81,15 +104,19 @@ abstract class AbstractBackend
}
}
/**
* @return mixed
*/
public function getName()
{
return preg_replace('~^.+\\\(.+?)$~', '$1', get_class($this));
}
/**
* @return mixed
*/
public function __toString()
{
return $this->getName();
}
}

View File

@ -1,35 +1,53 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Backend\Criteria;
/**
* Class Order
*
* Constants for order definitions.
* These only describe logical orders without going into storage specific
* details, like which fields are used for ordering. It's completely up to the query to determine what to do with these
* constants (although the result should be consistent among the different storage apis).
*
* @package Icinga\Backend\Criteria
*/
class Order
{
/**
* Order by the newest events. What this means has to be determined in the context.
* Mostly this affects last_state_change
*
* @var string
*/
const STATE_CHANGE = "state_change";
/**
* Order by the state of service objects. Mostly this is critical->unknown->warning->ok,
* but also might take acknowledgments and downtimes in account
*
* @var string
*/
const SERVICE_STATE = "service_state";
/**
* Order by the state of host objects. Mostly this is critical->unknown->warning->ok,
* but also might take acknowledgments and downtimes in account
*
* @var string
*/
const HOST_STATE = "host_state";
/**
* @var string
*/
const HOST_NAME = "host_name";
/**
*
* @var string
*/
const SERVICE_NAME = "service_description";
}

View File

@ -1,21 +1,26 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Backend\DataView;
/**
* Class AbstractAccessorStrategy
* Basic interface for views.
* The name sound weirder than it is: Views define special get and exists operations for fields that are not
* directly available in a resultset, but exist under another name or can be accessed by loading an additional object
* during runtime.
* The name sound weirder than it is: Views define special get and exists operations for fields
* that are not directly available in a resultset, but exist under another name or can be
* accessed by loading an additional object during runtime.
*
* @see Icinga\Backend\DataView\ObjectRemappingView For an implementation of mapping field names
* to storage specific names, e.g. service_state being status.current_state in status.dat views.
*
* @see Icinga\Backend\MonitoringObjectList For the typical usage of this class. It is not wrapped
* around the monitoring object, so we don't use __get() or __set() and always have to give the item we'd like to access.
*
* around the monitoring object, so we don't use __get() or __set() and always have to give the
* item we'd like to access.
* @package Icinga\Backend\DataView
*/
interface AbstractAccessorStrategy {
interface AbstractAccessorStrategy
{
/**
* Returns a field for the item, or throws an Exception if the field doesn't exist
*

View File

@ -1,17 +1,25 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Backend\DataView;
/**
* Class ObjectRemappingView
*
* Dataview that maps generic field names to storage specific fields or requests them via handlers.
*
* When accessing objects, every storage api returns them with other names. You can't simply say $object->service_state,
* because this field is, e.g. under status.current_state in the status.dat view, while IDO uses servicestate->current_state.
* When accessing objects, every storage api returns them with other names. You can't simply say
* $object->service_state, because this field is, e.g. under status.current_state in the status.dat
* view, while IDO uses servicestate->current_state.
*
* This view is intended for normalizing these changes, so a request of service_state returns the right field for the backend.
* When implementing it, you have to fill the mappedParameters and/or the handlerParameters array. While mappedParameters
* simply translate logic field names to storage specific ones, handlerParameters determins functions that handle data
* retrieval for the specific fields.
* This view is intended for normalizing these changes, so a request of service_state returns the
* right field for the backend. When implementing it, you have to fill the mappedParameters and/or
* the handlerParameters array. While mappedParameters simply translate logic field names to
* storage specific ones, handlerParameters determins functions that handle data retrieval for
* the specific fields.
*
* @package Icinga\Backend\DataView
*/
class ObjectRemappingView implements AbstractAccessorStrategy
{
@ -46,15 +54,17 @@ class ObjectRemappingView implements AbstractAccessorStrategy
public function get(&$item, $field)
{
if (isset($item->$field))
if (isset($item->$field)) {
return $item->$field;
}
if (isset($this->mappedParameters[$field])) {
$mapped = explode(".", $this->mappedParameters[$field]);
$res = $item;
foreach ($mapped as $map) {
if(!isset($res->$map))
if (!isset($res->$map)) {
return "";
}
$res = $res->$map;
}
return $res;
@ -76,8 +86,9 @@ class ObjectRemappingView implements AbstractAccessorStrategy
*/
public function getNormalizedFieldName($field)
{
if(isset($this->mappedParameters[$field]))
if (isset($this->mappedParameters[$field])) {
return $this->mappedParameters[$field];
}
return $field;
}
@ -96,5 +107,4 @@ class ObjectRemappingView implements AbstractAccessorStrategy
|| isset($this->handlerParameters[$field])
);
}
}

View File

@ -1,23 +1,85 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Backend;
use Icinga\Web\Paginator\Adapter\QueryAdapter;
/**
* Class Query
* @package Icinga\Backend
*/
abstract class Query
{
/**
* @var AbstractBackend
*/
protected $backend;
/**
* @var array
*/
protected $columns = array();
/**
* @var array
*/
protected $available_columns = array();
/**
* @param null $count
* @param null $offset
* @return mixed
*/
abstract public function limit($count = null, $offset = null);
/**
* @param $column
* @param null $value
* @return mixed
*/
abstract public function where($column, $value = null);
/**
* @param string $column
* @param null $dir
* @return mixed
*/
abstract public function order($column = '', $dir = null);
/**
* @return mixed
*/
abstract public function fetchAll();
/**
* @return mixed
*/
abstract public function fetchRow();
/**
* @return mixed
*/
abstract public function fetchPairs();
/**
* @return mixed
*/
abstract public function fetchOne();
/**
* @return mixed
*/
abstract public function count();
public function __construct(\Icinga\Backend\AbstractBackend $backend, $columns = array())
/**
* @param AbstractBackend $backend
* @param array $columns
* @return \Icinga\Backend\Query
*/
public function __construct(AbstractBackend $backend, $columns = array())
{
$this->backend = $backend;
if (empty($columns) || $columns === '*') {
@ -28,6 +90,10 @@ abstract class Query
$this->init();
}
/**
* @param array $filters
* @return $this
*/
public function applyFilters($filters = array())
{
foreach ($filters as $key => $val) {
@ -36,13 +102,23 @@ abstract class Query
return $this;
}
/**
* @return mixed
*/
abstract protected function init();
protected function finalize() {}
/*
*
*/
protected function finalize()
{
}
/**
* Return a pagination adapter for the current query
*
* @param null $limit
* @param null $page
* @return \Zend_Paginator
*/
public function paginate($limit = null, $page = null)
@ -56,11 +132,10 @@ abstract class Query
$limit = $request->getParam('limit', 20);
}
$paginator = new \Zend_Paginator(
new \Icinga\Web\Paginator\Adapter\QueryAdapter($this)
new QueryAdapter($this)
);
$paginator->setItemCountPerPage($limit);
$paginator->setCurrentPageNumber($page);
return $paginator;
}
}

View File

@ -1,37 +1,60 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Backend;
use Icinga\Protocol\Statusdat as StatusdatProtocol;
/**
* Class Statusdat
* @package Icinga\Backend
*/
class Statusdat extends AbstractBackend
{
/**
* @var null
*/
private $reader = null;
/**
*
*/
public function init()
{
$this->reader = new StatusdatProtocol\Reader($this->config);
}
/**
* @return null
*/
public function getReader()
{
return $this->reader;
}
/**
* @param array $filter
* @param array $flags
* @return mixed
*/
public function listServices($filter = array(), $flags = array())
{
$query = $this->select()->from("servicelist");
return $query->fetchAll();
}
/**
* @param $host
* @return MonitoringObjectList|null
*/
public function fetchHost($host)
{
$objs = & $this->reader->getObjects();
if (!isset($objs["host"][$host]))
if (!isset($objs["host"][$host])) {
return null;
}
$result = array($objs["host"][$host]);
return new MonitoringObjectList(
$result,
@ -39,13 +62,19 @@ class Statusdat extends AbstractBackend
);
}
/**
* @param $host
* @param $service
* @return MonitoringObjectList|null
*/
public function fetchService($host, $service)
{
$idxName = $host . ";" . $service;
$objs = & $this->reader->getObjects();
if (!isset($objs["service"][$idxName]))
if (!isset($objs["service"][$idxName])) {
return null;
}
$result = array($objs["service"][$idxName]);
return new MonitoringObjectList(
$result,
@ -53,6 +82,4 @@ class Statusdat extends AbstractBackend
);
}
}

View File

@ -1,16 +1,34 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Backend\Statusdat\DataView;
use \Icinga\Protocol\Statusdat\IReader;
/**
* Class StatusdatHostView
* @package Icinga\Backend\Statusdat\DataView
*/
class StatusdatHostView extends \Icinga\Backend\DataView\ObjectRemappingView
{
/**
* @var mixed
*/
private $state;
/**
* @var array
*/
protected $handlerParameters = array(
"host" => "getHost",
"downtimes_with_info" => "getDowntimes",
"comments_with_info" => "getComments"
);
/**
* @var array
*/
protected $mappedParameters = array(
"host_address" => "host_name",
"host_name" => "host_name",
@ -27,22 +45,31 @@ class StatusdatHostView extends \Icinga\Backend\DataView\ObjectRemappingView
"host_check_latency" => "status.check_latency",
"host_check_execution_time" => "status.check_execution_time",
"active_checks_enabled" => "status.active_checks_enabled",
"acknowledged" => "status.problem_has_been_acknowledged",
"host_acknowledged" => "status.problem_has_been_acknowledged",
// "state" => "current_state"
);
public function getHost(&$item) {
if(!isset($this->state["host"][$item->host_name]))
/**
* @param $item
* @return null
*/
public function getHost(&$item)
{
if (!isset($this->state["host"][$item->host_name])) {
return null;
if(!isset($this->state["host"][$item->host_name]))
}
if (!isset($this->state["host"][$item->host_name])) {
return null;
}
return $this->state["host"][$item->host_name];
}
public function __construct(IReader $reader) {
/**
* @param IReader $reader
*/
public function __construct(IReader $reader)
{
$this->state = & $reader->getState();
}
}

View File

@ -1,16 +1,30 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Backend\Statusdat\DataView;
use Icinga\Backend\DataView\ObjectRemappingView;
use \Icinga\Protocol\Statusdat\IReader;
class StatusdatServiceView extends \Icinga\Backend\DataView\ObjectRemappingView
class StatusdatServiceView extends ObjectRemappingView
{
/**
* @var mixed
*/
private $state;
/**
* @var array
*/
protected $handlerParameters = array(
"host" => "getHost",
"downtimes_with_info" => "getDowntimes"
);
/**
* @var array
*/
protected $mappedParameters = array(
"host_address" => "parenthost.address",
"host_name" => "host_name",
@ -31,30 +45,52 @@ class StatusdatServiceView extends \Icinga\Backend\DataView\ObjectRemappingView
);
/**
* @param \Icinga\Backend\DataView\The $item
* @param \Icinga\Backend\DataView\The $field
* @return \Icinga\Backend\DataView\The|string
*/
public function get(&$item, $field)
{
if(!isset($item->parenthost) && isset($this->state["host"]))
if (!isset($item->parenthost) && isset($this->state["host"])) {
$item->parenthost = $this->state["host"];
}
return parent::get($item, $field);
}
/**
* @param \Icinga\Backend\DataView\The $item
* @param \Icinga\Backend\DataView\The $field
* @return bool
*/
public function exists(&$item, $field)
{
if(!isset($item->parenthost))
if (!isset($item->parenthost)) {
$item->parenthost = $this->state["host"];
}
return parent::exists($item, $field);
}
/**
* @param $item
* @return null
*/
public function getHost(&$item)
{
if (!isset($this->state["host"][$item->host_name]))
if (!isset($this->state["host"][$item->host_name])) {
return null;
if (!isset($this->state["host"][$item->host_name]))
}
if (!isset($this->state["host"][$item->host_name])) {
return null;
}
return $this->state["host"][$item->host_name];
}
/**
* @param IReader $reader
*/
public function __construct(IReader $reader)
{
$this->state = & $reader->getState();

View File

@ -1,12 +1,29 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Backend\Statusdat;
abstract class GroupsummaryQuery extends Query
{
/**
* @var mixed
*/
protected $reader;
/**
* @var string
*/
protected $groupType = "servicegroup";
/**
* @var string
*/
protected $base = "services";
/**
* @var array
*/
protected $available_columns = array(
'ok' => 'SUM(CASE WHEN state = 0 THEN 1 ELSE 0 END)',
'critical' => 'SUM(CASE WHEN state = 2 AND downtime = 0 AND ack = 0 THEN 1 ELSE 0 END)',
@ -20,6 +37,9 @@ abstract class GroupsummaryQuery extends Query
'warning_ack' => 'SUM(CASE WHEN state = 1 AND downtime = 0 AND ack = 1 THEN 1 ELSE 0 END)',
);
/**
* @var array
*/
protected $order_columns = array(
'state' => array(
'ASC' => array(
@ -50,32 +70,44 @@ abstract class GroupsummaryQuery extends Query
)
);
/**
* @param $obj
* @return string
*/
private function getStateType(&$obj)
{
if ($obj->status->current_state == 0)
if ($obj->status->current_state == 0) {
return "ok";
}
$typeBase = "";
if ($obj->status->current_state == 1) {
$typeBase = 'warning';
} else if ($obj->status->current_state == 2) {
} else {
if ($obj->status->current_state == 2) {
$typeBase = 'critical';
} else if ($obj->status->current_state == 3) {
} else {
if ($obj->status->current_state == 3) {
$typeBase = 'unknown';
}
}
}
if ($obj->status->problem_has_been_acknowledged) {
return $typeBase . "_ack";
} else if (isset($obj->status->downtime)) {
} else {
if (isset($obj->status->downtime)) {
return $typeBase . "_dt";
}
}
return $typeBase;
}
/**
* @param $indices
* @return array
*/
public function groupByProblemType(&$indices)
{
$typename = $this->groupType . "_name";
$result = array();
foreach ($indices as $type => $subIndices) {
@ -110,21 +142,30 @@ abstract class GroupsummaryQuery extends Query
/**
* @var \Icinga\Protocol\Statusdat\Query
* @return mixed|void
*/
public function init() {
public function init()
{
$this->reader = $this->backend->getReader();
$this->query = $this->reader->select()->from($this->base,array())->groupByFunction("groupByProblemType",$this)->where("COUNT{group} > 0");
$this->query = $this->reader->select()->from($this->base, array())->groupByFunction(
"groupByProblemType",
$this
)->where("COUNT{group} > 0");
}
/**
* @param The $column
* @param null $value
* @return $this|Query
*/
public function where($column, $value = null)
{
if ($column === 'problems') {
if ($value === 'true') {
//$this->where("COUNT{downtime} == 0 AND status.problem_has_been_acknowledged == 0 AND status.current_state > 0");
//$this->where(
// "COUNT{downtime} == 0 AND status.problem_has_been_acknowledged == 0 AND status.current_state > 0"
// );
}
} elseif ($column === 'search') {
if ($value) {
@ -136,4 +177,3 @@ abstract class GroupsummaryQuery extends Query
return $this;
}
}

View File

@ -1,10 +1,22 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Backend\Statusdat;
/**
* Class HostgroupsummaryQuery
* @package Icinga\Backend\Statusdat
*/
class HostgroupsummaryQuery extends GroupsummaryQuery
{
/**
* @var string
*/
protected $groupType = "hostgroup";
/**
* @var string
*/
protected $base = "hosts";
}

View File

@ -1,29 +1,34 @@
<?php
/**
* Created by JetBrains PhpStorm.
* User: moja
* Date: 1/29/13
* Time: 11:36 AM
* To change this template use File | Settings | File Templates.
*/
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Backend\Statusdat;
use Icinga\Protocol\Statusdat;
use Icinga\Exception;
/**
* Class HostListQuery
* @package Icinga\Backend\Statusdat
*/
class HostListQuery extends Query
{
/**
* @var \Icinga\Protocol\Statusdat\Query
*/
protected $query;
/**
* @var string
*/
protected $view = 'Icinga\Backend\Statusdat\DataView\StatusdatHostView';
public function init() {
/**
* @return mixed|void
*/
public function init()
{
$this->reader = $this->backend->getReader();
$this->query = $this->reader->select()->from("hosts", array());
}
}

View File

@ -1,28 +1,41 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Backend\Statusdat;
use Icinga\Backend\Criteria\Order;
use Icinga\Backend\MonitoringObjectList as MList;
use Icinga\Protocol\Statusdat;
use Icinga\Exception;
use Icinga\Backend\Query as BaseQuery;
/**
* Base class for statusdat queries, contains most of the filter/order logic
*
* Class Query
* @package Icinga\Backend\Statusdat
*/
abstract class Query extends \Icinga\Backend\Query
abstract class Query extends BaseQuery
{
/**
* @var null
*/
protected $cursor = null;
/**
* @var string
*/
protected $view = 'Icinga\Backend\Statusdat\DataView\StatusdatServiceView';
/**
* @var array Mapping of order to field names
* @todo Is not complete right now
*/
protected $orderColumns = array(
\Icinga\Backend\Criteria\Order::SERVICE_STATE => "status.current_state",
\Icinga\Backend\Criteria\Order::STATE_CHANGE => "status.last_state_change",
\Icinga\Backend\Criteria\Order::HOST_STATE => "status.current_state",
\Icinga\Backend\Criteria\Order::HOST_NAME => "host_name",
\Icinga\Backend\Criteria\Order::SERVICE_NAME => "service_description"
Order::SERVICE_STATE => "status.current_state",
Order::STATE_CHANGE => "status.last_state_change",
Order::HOST_STATE => "status.current_state",
Order::HOST_NAME => "host_name",
Order::SERVICE_NAME => "service_description"
);
/**
@ -40,11 +53,12 @@ abstract class Query extends \Icinga\Backend\Query
foreach ($filters as $filter => $value) {
$filter[0] = strtoupper($filter[0]);
$filterMethod = "apply" . $filter . "Filter";
if (method_exists($this, $filterMethod))
if (method_exists($this, $filterMethod)) {
$this->$filterMethod($filter, $value);
else
} else {
$this->where($filter, $value);
}
}
return $this;
}
@ -117,27 +131,45 @@ abstract class Query extends \Icinga\Backend\Query
$this->query->where("(status.problem_has_been_acknowledged = ? )", $val);
}
/**
* @param $type
* @param $value
*/
public function applyHostnameFilter($type, $value)
{
if (!is_array($value))
if (!is_array($value)) {
$value = array($value);
}
$this->query->where("host_name LIKE ?", $value);
}
/**
* @param $type
* @param $value
*/
public function applyStateFilter($type, $value)
{
$this->query->where("status.current_state = $value");
}
/**
* @param $type
* @param $value
*/
public function applyHoststateFilter($type, $value)
{
$this->query->where("host.status.current_state = $value");
}
/**
* @param $type
* @param $value
*/
public function applyServiceDescriptionFilter($type, $value)
{
if (!is_array($value))
if (!is_array($value)) {
$value = array($value);
}
$this->query->where("service_description LIKE ?", $value);
}
@ -163,52 +195,70 @@ abstract class Query extends \Icinga\Backend\Query
public function order($column = '', $dir = null)
{
if ($column)
if ($column) {
$this->query->order($this->orderColumns[$column], strtolower($dir));
}
return $this;
}
/**
* Applies a filter on this query by calling the statusdat where() function
*
* @param $column The (statusdat!) column to filter in "field operator ?" format. (@example status.current_state > ?)
* @param $column The (statusdat!) column to filter in "field operator ?"
* format. (@example status.current_state > ?)
* @param mixed $value The value to filter for
* @return Query Returns this query,for fluent interface
*/
public function where($column, $value = null)
{
if (!is_array($value))
if (!is_array($value)) {
$value = array($value);
}
$this->query->where($column, $value);
return $this;
}
/**
* @return MList|mixed|null
*/
public function fetchAll()
{
$view = $this->view;
if (!$this->cursor)
if (!$this->cursor) {
$this->cursor = new MList($this->query->getResult(), new $view($this->reader));
}
return $this->cursor;
}
/**
* @return mixed
*/
public function fetchRow()
{
return next($this->fetchAll());
}
/**
* @return mixed|void
*/
public function fetchPairs()
{
}
/**
* @return mixed
*/
public function fetchOne()
{
return next($this->fetchAll());
}
/**
* @return int|mixed
*/
public function count()
{
return count($this->query->getResult());
}
}

View File

@ -1,10 +1,22 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Backend\Statusdat;
/**
* Class ServicegroupsummaryQuery
* @package Icinga\Backend\Statusdat
*/
class ServicegroupsummaryQuery extends GroupsummaryQuery
{
/**
* @var string
*/
protected $groupType = "servicegroup";
/**
* @var string
*/
protected $base = "services";
}

View File

@ -1,32 +1,34 @@
<?php
/**
* Created by JetBrains PhpStorm.
* User: moja
* Date: 1/29/13
* Time: 11:36 AM
* To change this template use File | Settings | File Templates.
*/
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Backend\Statusdat;
use Icinga\Backend\MonitoringObjectList as MList;
use Icinga\Protocol\Statusdat;
use Icinga\Backend\Statusdat\DataView\StatusdatServiceView as StatusdatServiceView;
use Icinga\Exception;
/**
* Class ServicelistQuery
* @package Icinga\Backend\Statusdat
*/
class ServicelistQuery extends Query
{
/**
* @var \Icinga\Protocol\Statusdat\Query
*/
protected $query;
/**
* @var string
*/
protected $view = 'Icinga\Backend\Statusdat\DataView\StatusdatServiceView';
public function init() {
public function init()
{
$this->reader = $this->backend->getReader();
$this->query = $this->reader->select()->from("services", array());
}
}

View File

@ -1,8 +1,13 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Exception;
/**
* Class ConfigurationError
* @package Icinga\Exception
*/
class ConfigurationError extends \RuntimeException
{
}

View File

@ -1,9 +1,15 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Exception;
use RuntimeException;
/**
* Class MissingParameterException
* @package Icinga\Exception
*/
class MissingParameterException extends RuntimeException
{
}

View File

@ -1,8 +1,13 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Exception;
/**
* Class NotImplementedError
* @package Icinga\Exception
*/
class NotImplementedError extends \Exception
{
}

View File

@ -1,8 +1,13 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Exception;
/**
* Class ProgrammingError
* @package Icinga\Exception
*/
class ProgrammingError extends \Exception
{
}

View File

@ -1,26 +1,60 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Commandpipe;
use \Icinga\Protocol\Commandpipe\Exception\InvalidCommandException;
use \Icinga\Protocol\Commandpipe\Comment;
/**
* Class Acknowledgement
* @package Icinga\Protocol\Commandpipe
*/
class Acknowledgement implements IComment
{
/**
* @var int
*/
public $expireTime = -1;
/**
* @var bool
*/
public $notify = false;
/**
* @var Comment|null
*/
public $comment = null;
/**
* @var bool
*/
public $sticky;
/**
* @param int $time
*/
public function setExpireTime($time)
{
$this->expireTime = intval($time);
}
/**
* @param boolean $bool
*/
public function setNotify($bool)
{
$this->notify = (bool)$bool;
}
/**
* @param Comment $comment
* @param bool $notify
* @param $expire
* @param bool $sticky
*/
public function __construct(Comment $comment, $notify = false, $expire = -1, $sticky = false)
{
$this->comment = $comment;
@ -29,10 +63,20 @@ class Acknowledgement implements IComment
$this->sticky = $sticky;
}
/**
* @param $type
* @return string
* @throws Exception\InvalidCommandException
*/
public function getFormatString($type)
{
$params = ';'.($this->sticky ? '2' : '0').';'.($this->notify ? '1 ': '0').';'.($this->comment->persistent ? '1' : '0');
$params .= ($this->expireTime > -1 ? ';'.$this->expireTime.';' : ';').$this->comment->author.';'.$this->comment->comment;
$params = ';'
. ($this->sticky ? '2' : '0')
. ';' . ($this->notify ? '1 ' : '0')
. ';' . ($this->comment->persistent ? '1' : '0');
$params .= ($this->expireTime > -1 ? ';'. $this->expireTime . ';' : ';')
. $this->comment->author . ';' . $this->comment->comment;
switch ($type) {
case CommandPipe::TYPE_HOST:
@ -49,10 +93,5 @@ class Acknowledgement implements IComment
$base = "ACKNOWLEDGE_{$typeVar}_PROBLEM" . ($this->expireTime > -1 ? '_EXPIRE' : '');
return $base . $params;
}
}

View File

@ -1,11 +1,20 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Commandpipe;
use Icinga\Application\Logger as IcingaLogger;
/**
* Class CommandPipe
* @package Icinga\Protocol\Commandpipe
*/
class CommandPipe
{
private $path;
private $name;
private $user = falsE;
private $user = false;
private $host = false;
private $port = 22;
public $fopen_mode = "w";
@ -34,10 +43,13 @@ class CommandPipe
public function send($command)
{
if (!$this->host) {
IcingaLogger::debug("Attempting to send external icinga command $command to local command file {$this->path}");
IcingaLogger::debug(
"Attempting to send external icinga command $command to local command file {$this->path}"
);
$file = @fopen($this->path, $this->fopen_mode);
if (!$file)
if (!$file) {
throw new \RuntimeException("Could not open icinga pipe at $file : " . print_r(error_get_last(), true));
}
fwrite($file, "[" . time() . "] " . $command . PHP_EOL);
IcingaLogger::debug('Writing [' . time() . '] ' . $command . PHP_EOL);
fclose($file);
@ -45,21 +57,48 @@ class CommandPipe
// send over ssh
$retCode = 0;
$output = array();
IcingaLogger::debug('Icinga instance is on different host, attempting to send command %s via ssh to %s:%s/%s', $command, $this->host, $this->port, $this->path);
IcingaLogger::debug(
'Icinga instance is on different host, attempting to send command %s via ssh to %s:%s/%s',
$command,
$this->host,
$this->port,
$this->path
);
$hostConnector = $this->user ? $this->user . "@" . $this->host : $this->host;
exec("ssh $hostConnector -p{$this->port} \"echo '[".time()."] ".escapeshellcmd($command)."' > {$this->path}\"", $output, $retCode);
IcingaLogger::debug("$:ssh $hostConnector -p{$this->port} \"echo '[".time()."] ".escapeshellcmd($command)."' > {$this->path}\"");
exec(
"ssh $hostConnector -p{$this->port} \"echo '[" . time() . "] "
. escapeshellcmd(
$command
)
. "' > {$this->path}\"",
$output,
$retCode
);
IcingaLogger::debug(
"$:ssh $hostConnector -p{$this->port} \"echo '[" . time() . "] " . escapeshellcmd(
$command
) . "' > {$this->path}\""
);
IcingaLogger::debug("Code code %s: %s ", $retCode, $output);
if ($retCode != 0) {
throw new \RuntimeException('Could not send command to remote icinga host: '.implode("\n", $output)." (returncode $retCode)");
throw new \RuntimeException(
'Could not send command to remote icinga host: '
. implode(
"\n",
$output
)
. " (returncode $retCode)"
);
}
}
}
public function acknowledge($objects,IComment $acknowledgementOrComment) {
if (is_a($acknowledgementOrComment,'Icinga\Protocol\Commandpipe\Comment'))
public function acknowledge($objects, IComment $acknowledgementOrComment)
{
if (is_a($acknowledgementOrComment, 'Icinga\Protocol\Commandpipe\Comment')) {
$acknowledgementOrComment = new Acknowledgement($acknowledgementOrComment);
}
foreach ($objects as $object) {
if (isset($object->service_description)) {
@ -94,9 +133,11 @@ class CommandPipe
}
}
public function scheduleForcedCheck($objects,$time=false,$withChilds=false) {
if (!$time)
public function scheduleForcedCheck($objects, $time = false, $withChilds = false)
{
if (!$time) {
$time = time();
}
$base = "SCHEDULE_FORCED_";
foreach ($objects as $object) {
if (isset($object->service_description)) {
@ -107,9 +148,11 @@ class CommandPipe
}
}
public function scheduleCheck($objects,$time=false,$withChilds=false) {
if (!$time)
public function scheduleCheck($objects, $time = false, $withChilds = false)
{
if (!$time) {
$time = time();
}
$base = "SCHEDULE_";
foreach ($objects as $object) {
if (isset($object->service_description)) {
@ -151,8 +194,9 @@ class CommandPipe
$type = "HOST_COMMENT";
}
$cmd = "DEL_ALL_{$type}S;" . $object->host_name;
if ($type == "SERVICE_COMMENT")
if ($type == "SERVICE_COMMENT") {
$cmd .= ";" . $object->service_description;
}
$this->send($cmd);
}
}
@ -171,8 +215,9 @@ class CommandPipe
private function getObjectType($object)
{
//@TODO: This must be refactored once more commands are supported
if (isset($object->service_description))
if (isset($object->service_description)) {
return self::TYPE_SERVICE;
}
return self::TYPE_HOST;
}
@ -180,12 +225,15 @@ class CommandPipe
{
foreach ($objects as $object) {
$type = $this->getObjectType($object);
if($type == self::TYPE_SERVICE)
$this->send(sprintf($downtime->getFormatString($type),$object->host_name,$object->service_description));
else
if ($type == self::TYPE_SERVICE) {
$this->send(
sprintf($downtime->getFormatString($type), $object->host_name, $object->service_description)
);
} else {
$this->send(sprintf($downtime->getFormatString($type), $object->host_name));
}
}
}
public function removeDowntime($objects, $starttime = 0)
{
@ -196,10 +244,12 @@ class CommandPipe
continue;
}
$cmd = "DEL_DOWNTIME_BY_HOST_NAME;" . $object->host_name;
if($type == self::TYPE_SERVICE)
if ($type == self::TYPE_SERVICE) {
$cmd .= ";" . $object->service_description;
if($starttime != 0)
}
if ($starttime != 0) {
$cmd .= ";" . $starttime;
}
$this->send($cmd);
}
}
@ -215,7 +265,9 @@ class CommandPipe
$type = $this->getObjectType($object);
$formatArray = $flags->getFormatString($type);
foreach ($formatArray as $format) {
$format .= ";".$object->host_name.($type == self::TYPE_SERVICE ? ";".$object->service_description : "");
$format .= ";"
. $object->host_name
. ($type == self::TYPE_SERVICE ? ";" . $object->service_description : "");
$this->send($format);
}
}
@ -223,98 +275,169 @@ class CommandPipe
public function enableActiveChecks($objects)
{
$this->setMonitoringProperties($objects,new PropertyModifier(array(
$this->setMonitoringProperties(
$objects,
new PropertyModifier(
array(
PropertyModifier::ACTIVE => PropertyModifier::STATE_ENABLE
)));
)
)
);
}
public function disableActiveChecks($objects)
{
$this->modifyMonitoringProperties($objects,new PropertyModifier(array(
$this->modifyMonitoringProperties(
$objects,
new PropertyModifier(
array(
PropertyModifier::ACTIVE => PropertyModifier::STATE_DISABLE
)));
)
)
);
}
public function enablePassiveChecks($objects)
{
$this->setMonitoringProperties($objects,new PropertyModifier(array(
$this->setMonitoringProperties(
$objects,
new PropertyModifier(
array(
PropertyModifier::PASSIVE => PropertyModifier::STATE_ENABLE
)));
)
)
);
}
public function disablePassiveChecks($objects)
{
$this->modifyMonitoringProperties($objects,new PropertyModifier(array(
$this->modifyMonitoringProperties(
$objects,
new PropertyModifier(
array(
PropertyModifier::PASSIVE => PropertyModifier::STATE_DISABLE
)));
)
)
);
}
public function enableFlappingDetection($objects)
{
$this->setMonitoringProperties($objects,new PropertyModifier(array(
$this->setMonitoringProperties(
$objects,
new PropertyModifier(
array(
PropertyModifier::FLAPPING => PropertyModifier::STATE_ENABLE
)));
)
)
);
}
public function disableFlappingDetection($objects)
{
$this->setMonitoringProperties($objects,new PropertyModifier(array(
$this->setMonitoringProperties(
$objects,
new PropertyModifier(
array(
PropertyModifier::FLAPPING => PropertyModifier::STATE_DISABLE
)));
)
)
);
}
public function enableNotifications($objects)
{
$this->setMonitoringProperties($objects,new PropertyModifier(array(
$this->setMonitoringProperties(
$objects,
new PropertyModifier(
array(
PropertyModifier::NOTIFICATIONS => PropertyModifier::STATE_ENABLE
)));
)
)
);
}
public function disableNotifications($objects)
{
$this->setMonitoringProperties($objects,new PropertyModifier(array(
$this->setMonitoringProperties(
$objects,
new PropertyModifier(
array(
PropertyModifier::NOTIFICATIONS => PropertyModifier::STATE_DISABLE
)));
)
)
);
}
public function enableFreshnessChecks($objects)
{
$this->setMonitoringProperties($objects,new PropertyModifier(array(
$this->setMonitoringProperties(
$objects,
new PropertyModifier(
array(
PropertyModifier::FRESHNESS => PropertyModifier::STATE_ENABLE
)));
)
)
);
}
public function disableFreshnessChecks($objects)
{
$this->setMonitoringProperties($objects,new PropertyModifier(array(
$this->setMonitoringProperties(
$objects,
new PropertyModifier(
array(
PropertyModifier::FRESHNESS => PropertyModifier::STATE_DISABLE
)));
)
)
);
}
public function enableEventHandler($objects)
{
$this->setMonitoringProperties($objects,new PropertyModifier(array(
$this->setMonitoringProperties(
$objects,
new PropertyModifier(
array(
PropertyModifier::EVENTHANDLER => PropertyModifier::STATE_ENABLE
)));
)
)
);
}
public function disableEventHandler($objects)
{
$this->setMonitoringProperties($objects,new PropertyModifier(array(
$this->setMonitoringProperties(
$objects,
new PropertyModifier(
array(
PropertyModifier::EVENTHANDLER => PropertyModifier::STATE_DISABLE
)));
)
)
);
}
public function enablePerfdata($objects)
{
$this->setMonitoringProperties($objects,new PropertyModifier(array(
$this->setMonitoringProperties(
$objects,
new PropertyModifier(
array(
PropertyModifier::PERFDATA => PropertyModifier::STATE_ENABLE
)));
)
)
);
}
public function disablePerfdata($objects)
{
$this->setMonitoringProperties($objects,new PropertyModifier(array(
$this->setMonitoringProperties(
$objects,
new PropertyModifier(
array(
PropertyModifier::PERFDATA => PropertyModifier::STATE_DISABLE
)));
)
)
);
}
}

View File

@ -1,7 +1,13 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Protocol\Commandpipe\Exception;
/**
* Class InvalidCommandException
* @package Icinga\Protocol\Commandpipe\Exception
*/
class InvalidCommandException extends \Exception
{
}