Merge branch 'bugfix/logging-configuration-6038'

fixes #6038
This commit is contained in:
Johannes Meyer 2014-04-30 12:01:48 +02:00
commit 75c359bfb0
9 changed files with 140 additions and 649 deletions

View File

@ -38,7 +38,7 @@ use \Icinga\Form\Config\GeneralForm;
use \Icinga\Form\Config\Authentication\ReorderForm;
use \Icinga\Form\Config\Authentication\LdapBackendForm;
use \Icinga\Form\Config\Authentication\DbBackendForm;
use \Icinga\Form\Config\Resource\ResourceForm;
use \Icinga\Form\Config\ResourceForm;
use \Icinga\Form\Config\LoggingForm;
use \Icinga\Form\Config\ConfirmRemovalForm;
use \Icinga\Config\PreservingIniWriter;

View File

@ -66,7 +66,7 @@ class ListController extends Controller
$config_ini = IcingaConfig::app()->toArray();
if (!in_array('logging', $config_ini) || (
in_array('type', $config_ini['logging']) &&
$config_ini['logging']['type'] === 'stream' &&
$config_ini['logging']['type'] === 'file' &&
in_array('target', $config_ini['logging']) &&
file_exists($config_ini['logging']['target'])
)

View File

@ -31,12 +31,9 @@
namespace Icinga\Form\Config;
use Zend_Config;
use Zend_Form_Element_Text;
use Icinga\Application\Config;
use Icinga\Application\Icinga;
use Icinga\Web\Form;
use Icinga\Application\Icinga;
use Icinga\Web\Form\Validator\WritablePathValidator;
use Icinga\Web\Form\Decorator\ConditionalHidden;
/**
* Form class for setting the application wide logging configuration
@ -44,58 +41,13 @@ use Icinga\Web\Form\Decorator\ConditionalHidden;
class LoggingForm extends Form
{
/**
* Base directory to use instead of the one provided by Icinga::app (used for testing)
* Return the default logging directory for type "file"
*
* @var null
* @return string
*/
private $baseDir = null;
/**
* Set a different base directory to use for default paths instead of the one provided by Icinga::app()
*
* @param string $dir The new directory to use
*/
public function setBaseDir($dir)
protected function getDefaultLogDir()
{
$this->baseDir = $dir;
}
/**
* Return the applications base directory or the value from a previous setBaseDir call
*
* This is used to determine the default logging paths in a manner that allows to set a different path
* during testing
*
* @return string
*/
public function getBaseDir()
{
if ($this->baseDir) {
return $this->baseDir;
}
return realpath(Icinga::app()->getApplicationDir() . '/../');
}
/**
* Return true if the debug log path textfield should be displayed
*
* This is the case if the "logging_use_debug" field is autosubmitted
* and true or if it is not submitted, but the configuration for debug
* logging is set to true
*
* @param Zend_Config $config The debug section of the config.ini
*
* @return bool Whether to display the debug path field or not
*/
private function shouldDisplayDebugLog(Zend_Config $config)
{
$debugParam = $this->getRequest()->getParam('logging_debug_enable', null);
if ($debugParam !== null) {
return intval($debugParam) === 1;
} else {
return intval($config->get('enable', 0)) === 1;
}
return realpath(Icinga::app()->getApplicationDir() . '/../var/log/icingaweb.log');
}
/**
@ -108,108 +60,121 @@ class LoggingForm extends Form
$this->setName('form_config_logging');
$config = $this->getConfiguration();
$logging = $config->logging;
if ($logging === null) {
$logging = new Zend_Config(array());
}
$debug = $logging->debug;
if ($debug === null) {
$debug = new Zend_Config(array());
if (($loggingConfig = $config->logging) === null) {
$loggingConfig = new Zend_Config(array());
}
$txtLogPath = new Zend_Form_Element_Text(
$this->addElement(
'checkbox',
'logging_enable',
array(
'required' => true,
'label' => t('Logging Enabled'),
'helptext' => t('Check this to enable logging.'),
'value' => $loggingConfig->enable ? 1 : 0
)
);
$this->addElement(
'select',
'logging_level',
array(
'name' => 'logging_app_target',
'label' => 'Application Log Path',
'helptext' => 'The logfile to write the icingaweb debug logs to.'
. 'The webserver must be able to write at this location',
'required' => true,
'value' => $logging->get('target', $this->getBaseDir() . '/var/log/icingaweb.log')
'label' => t('Logging Level'),
'helptext' => t('The maximum loglevel to emit.'),
'value' => intval($loggingConfig->get('level', 0)),
'multiOptions' => array(
0 => t('Error'),
1 => t('Warning'),
2 => t('Information'),
3 => t('Debug')
)
)
);
$txtLogPath->addValidator(new WritablePathValidator());
$this->addElement($txtLogPath);
$this->addElement(
'checkbox',
'logging_app_verbose',
'select',
'logging_type',
array(
'label' => 'Verbose Logging',
'required' => true,
'helptext' => 'Check to write more verbose output to the icinga log file',
'value' => intval($logging->get('verbose', 0)) === 1
'required' => true,
'label' => t('Logging Type'),
'helptext' => t('The type of logging to utilize.'),
'value' => $loggingConfig->get('type', 'file'),
'multiOptions' => array(
'file' => t('File'),
'syslog' => 'Syslog'
)
)
);
$this->enableAutoSubmit(array('logging_type'));
$this->addElement(
'checkbox',
'logging_debug_enable',
array(
'label' => 'Use Debug Log',
'required' => true,
'helptext' => 'Check to write a seperate debug log (Warning: This file can grow very big)',
'value' => $this->shouldDisplayDebugLog($debug)
)
);
switch ($this->getRequest()->getParam('logging_type', $loggingConfig->get('type', 'file')))
{
case 'syslog':
$this->addElement(
'text',
'logging_application',
array(
'required' => true,
'label' => t('Application Prefix'),
'helptext' => t('The name of the application by which to prefix syslog messages.'),
'value' => $loggingConfig->get('application', 'icingaweb')
)
);
$this->addElement(
'select',
'logging_facility',
array(
'required' => true,
'label' => t('Facility'),
'helptext' => t('The Syslog facility to utilize.'),
'value' => $loggingConfig->get('facility', 'LOG_USER'),
'multiOptions' => array(
'LOG_USER'
)
)
);
break;
case 'file':
default:
$this->addElement(
'text',
'logging_target',
array(
'required' => true,
'label' => t('Filepath'),
'helptext' => t('The logfile to write messages to.'),
'value' => $loggingConfig->target ? $loggingConfig->target : $this->getDefaultLogDir(),
'validators' => array(new WritablePathValidator())
)
);
}
$textLoggingDebugPath = new Zend_Form_Element_Text(
array(
'name' => 'logging_debug_target',
'label' => 'Debug Log Path',
'required' => $this->shouldDisplayDebugLog($debug),
'condition' => $this->shouldDisplayDebugLog($debug),
'value' => $debug->get('target', $this->getBaseDir() . '/var/log/icingaweb2.debug.log'),
'helptext' => 'Set the path to the debug log'
)
);
$textLoggingDebugPath->addValidator(new WritablePathValidator());
$decorator = new ConditionalHidden();
$this->addElement($textLoggingDebugPath);
$textLoggingDebugPath->addDecorator($decorator);
$this->enableAutoSubmit(array('logging_debug_enable'));
$this->addElement(
'button',
'btn_submit',
array(
'type' => 'submit',
'escape' => false,
'value' => '1',
'class' => 'btn btn-cta btn-common',
'label' => '<i class="icinga-icon-save"></i> Save Changes'
)
);
$this->setSubmitLabel('{{SAVE_ICON}} Save Changes');
}
/**
* Return a Zend_Config object containing the state defined in this form
* Return a Zend_Config object containing the state defined in this form
*
* @return Zend_Config The config defined in this form
* @return Zend_Config The config defined in this form
*/
public function getConfig()
{
$config = $this->getConfiguration();
if ($config->logging === null) {
$config->logging = new Zend_Config(array(), true);
}
if ($config->logging->debug === null) {
$config->logging->debug = new Zend_Config(array(), true);
}
$values = $this->getValues();
$cfg = $config->toArray();
$cfg = $this->getConfiguration()->toArray();
$cfg['logging']['enable'] = 1;
$cfg['logging']['type'] = 'stream';
$cfg['logging']['verbose'] = $values['logging_app_verbose'];
$cfg['logging']['target'] = $values['logging_app_target'];
$cfg['logging']['enable'] = $values['logging_enable'] == 1;
$cfg['logging']['level'] = $values['logging_level'];
switch ($values['logging_type'])
{
case 'file':
$cfg['logging']['target'] = $values['logging_target'];
break;
case 'syslog':
$cfg['logging']['application'] = $values['logging_application'];
$cfg['logging']['facility'] = $values['logging_facility'];
break;
}
$cfg['logging']['debug']['enable'] = intval($values['logging_debug_enable']);
$cfg['logging']['debug']['type'] = 'stream';
$cfg['logging']['debug']['target'] = $values['logging_debug_target'];
return new Zend_Config($cfg);
}
}

View File

@ -1,13 +0,0 @@
<?php
namespace Icinga\Module\Monitoring\Form\Config\Backend;
use Icinga\Module\Monitoring\Form\Config\Backend\EditResourceForm;
class CreateResourceForm extends EditResourceForm
{
public function __construct()
{
}
}

View File

@ -1,481 +0,0 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga Web 2.
*
* Icinga Web 2 - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* 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.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*
*/
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Form\Config\Resource;
use \Zend_Config;
use Icinga\Web\Form;
use Icinga\Logger\Logger;
use Icinga\Web\Form\Decorator\HelpText;
use Icinga\Data\ResourceFactory;
/**
* Form for modifying a monitoring backend
*/
class EditResourceForm extends Form
{
/**
* The currently edited resource.
*
* @var Zend_Config
*/
private $resource;
/**
* @var string
*/
private $name = '';
/**
* @var string
*/
private $oldName = '';
/**
* Return the current resource name.
*
* @param string $name
*
* @return void|\Zend_Form
*/
public function setName($name)
{
$this->name = $name;
}
/**
* @return null|string
*/
public function getName()
{
return $this->getValue('resource_all_name');
}
/**
* Set the original name of the resource. This value is persisted using
* a hidden field.
*
* @param $name
*/
public function setOldName($name)
{
$this->oldName = $name;
}
/**
* Get the resource name that was initially set.
*/
public function getOldName()
{
return $this->getValue('resource_all_name_old');
}
private function addDbForm()
{
$this->addElement(
'select',
'resource_db_db',
array(
'label' => 'Database Type',
'value' => $this->getResource()->get('db', 'mysql'),
'required' => true,
'helptext' => 'The type of SQL database you want to create.',
'multiOptions' => array(
'mysql' => 'MySQL',
'pgsql' => 'PostgreSQL'
//'oracle' => 'Oracle'
)
)
);
$this->addElement(
'text',
'resource_db_host',
array (
'label' => 'Host',
'value' => $this->getResource()->get('host', 'localhost'),
'required' => true,
'helptext' => 'The hostname of the database.'
)
);
$this->addElement(
'text',
'resource_db_port',
array(
'label' => 'Port',
'value' => $this->getResource()->get('port', 3306),
'required' => true,
'validators' => array(
array('regex', false, '/^[0-9]+$/')
),
'helptext' => 'The port number to use.'
)
);
$this->addElement(
'text',
'resource_db_dbname',
array(
'label' => 'Database Name',
'value' => $this->getResource()->get('dbname', ''),
'required' => true,
'helptext' => 'The name of the database to use'
)
);
$this->addElement(
'text',
'resource_db_username',
array (
'label' => 'Username',
'value' => $this->getResource()->get('username', ''),
'required' => true,
'helptext' => 'The user name to use for authentication.'
)
);
$this->addElement(
'password',
'resource_db_password',
array(
'label' => 'Password',
'renderPassword' => true,
'value' => $this->getResource()->get('password', ''),
'helptext' => 'The password to use for authentication',
'required' => true
)
);
}
private function addStatusdatForm()
{
$this->addElement(
'text',
'resource_statusdat_status_file',
array(
'label' => 'Status.dat File',
'value' => $this->getResource()->get('status_file', '/usr/local/icinga/var/status.dat'),
'required' => true,
'helptext' => 'Location of your icinga status.dat file'
)
);
$this->addElement(
'text',
'resource_statusdat_object_file',
array(
'label' => 'Objects.cache File',
'value' => $this->getResource()->get('status_file', '/usr/local/icinga/var/objects.cache'),
'required' => true,
'helptext' => 'Location of your icinga objects.cache file'
)
);
}
private function addLivestatusForm()
{
$this->addElement(
'text',
'resource_livestatus_socket',
array(
'label' => 'Livestatus Socket Location',
'required' => true,
'helptext' => 'The path to your livestatus socket used for querying monitoring data',
'value' => $this->getResource()->socket,
)
);
}
private function addLdapForm()
{
$this->addElement(
'text',
'resource_ldap_hostname',
array(
'label' => 'LDAP Server Host',
'allowEmpty' => false,
'value' => $this->getResource()->get('hostname', 'localhost'),
'helptext' => 'The hostname or address of the LDAP server to use for authentication',
'required' => true
)
);
$this->addElement(
'text',
'resource_ldap_root_dn',
array(
'label' => 'LDAP Root DN',
'value' => $this->getResource()->get('root_dn', 'ou=people,dc=icinga,dc=org'),
'helptext' => 'The path where users can be found on the ldap server',
'required' => true
)
);
$this->addElement(
'text',
'resource_ldap_bind_dn',
array(
'label' => 'LDAP Bind DN',
'value' => $this->getResource()->get('bind_dn', 'cn=admin,cn=config'),
'helptext' => 'The user dn to use for querying the ldap server',
'required' => true
)
);
$this->addElement(
'password',
'resource_ldap_bind_pw',
array(
'label' => 'LDAP Bind Password',
'renderPassword' => true,
'value' => $this->getResource()->get('bind_pw', ''),
'helptext' => 'The password to use for querying the ldap server',
'required' => true
)
);
}
/**
* Set the resource configuration to edit.
*
* @param Zend_Config $resource
*/
public function setResource(Zend_Config $resource)
{
$this->resource = $resource;
}
/**
* Get the current resource configuration.
*
* @return Zend_Config
*/
public function getResource()
{
if (!isset($this->resource)) {
// Init empty resource
$this->resource = new Zend_Config(
array('type' => 'db')
);
}
return $this->resource;
}
/**
* Add a field to change the resource name and one hidden field
* to save the previous resource name.
*/
private function addNameFields()
{
$this->addElement(
'text',
'resource_all_name',
array(
'label' => 'Resource Name',
'value' => $this->name,
'helptext' => 'The unique name of this resource',
'required' => true
)
);
$this->addElement(
'hidden',
'resource_all_name_old',
array(
'value' => $this->oldName
)
);
}
/**
* Add checkbox at the beginning of the form which allows to skip logic connection validation
*/
private function addForceCreationCheckbox()
{
$checkbox = new \Zend_Form_Element_Checkbox(
array(
'name' => 'backend_force_creation',
'label' => 'Force Changes',
'helptext' => 'Check this box to enforce changes without connectivity validation',
'order' => 0
)
);
$checkbox->addDecorator(new HelpText());
$this->addElement($checkbox);
}
/**
* Add a select box for choosing the type to use for this backend
*/
private function addTypeSelectionBox()
{
$this->addElement(
'select',
'resource_type',
array(
'label' => 'Resource Type',
'value' => $this->getResource()->type,
'required' => true,
'helptext' => 'The type of resource.',
'multiOptions' => array(
'db' => 'SQL Database',
'ldap' => 'Ldap',
'statusdat' => 'Status.dat',
'livestatus' => 'Livestatus'
)
)
);
$this->enableAutoSubmit(array('resource_type'));
}
/**
* Validate this form with the Zend validation mechanism and perform a validation of the connection.
*
* If validation fails, the 'backend_force_creation' checkbox is prepended to the form to allow users to
* skip the logic connection validation.
*
* @param array $data The form input to validate
*
* @return bool True when validation succeeded, false if not
*/
public function isValid($data)
{
if (!parent::isValid($data)) {
return false;
}
if ($this->getRequest()->getPost('backend_force_creation')) {
return true;
}
if (!$this->isValidResource()) {
$this->addForceCreationCheckbox();
return false;
}
return true;
}
/**
* Test if the changed resource is a valid resource, by instantiating it and
* checking if connection is possible.
*
* @return bool True when connection to the resource is possible.
*/
private function isValidResource()
{
try {
$config = $this->getConfig();
switch ($config->type) {
case 'db':
/*
* It should be possible to run icingaweb without the pgsql or mysql extension or Zend-Pdo-Classes,
* in case they aren't actually used. When the user tries to create a resource that depends on an
* uninstalled extension, an error should be displayed.
*/
if ($config->db === 'mysql' && !ResourceFactory::mysqlAvailable()) {
$this->addErrorMessage(
'You need to install the php extension "mysql" and the Zend_Pdo_Mysql classes to use '
. ' MySQL database resources.'
);
return false;
}
if ($config->db === 'pgsql' && !ResourceFactory::pgsqlAvailable()) {
$this->addErrorMessage(
'You need to install the php extension "pgsql" and the Zend_Pdo_Pgsql classes to use '
. ' PostgreSQL database resources.'
);
return false;
}
$resource = ResourceFactory::createResource($config);
$resource->getConnection()->getConnection();
break;
case 'statusdat':
if (!file_exists($config->object_file) || !file_exists($config->status_file)) {
$this->addErrorMessage(
'Connectivity validation failed, the provided file or socket does not exist.'
);
return false;
}
break;
case 'livestatus':
// TODO: Implement check
break;
case 'ldap':
$resource = ResourceFactory::createResource($config);
$resource->connect();
break;
}
} catch (\Exception $exc) {
$this->addErrorMessage('Connectivity validation failed, connection to the given resource not possible.');
return false;
}
return true;
}
public function create()
{
$this->addNameFields();
$this->addTypeSelectionBox();
switch ($this->getRequest()->getParam('resource_type', $this->getResource()->type)) {
case 'db':
$this->addDbForm();
break;
case 'statusdat':
$this->addStatusdatForm();
break;
case 'livestatus':
$this->addLivestatusForm();
break;
case 'ldap':
$this->addLdapForm();
break;
}
$this->setSubmitLabel('{{SAVE_ICON}} Save Changes');
}
/**
* Return a configuration containing the backend settings entered in this form
*
* @return Zend_Config The updated configuration for this backend
*/
public function getConfig()
{
$values = $this->getValues();
$type = $values['resource_type'];
$result = array('type' => $type);
foreach ($values as $key => $value) {
if ($key !== 'resource_type' && $key !== 'resource_all_name' && $key !== 'resource_all_name_old') {
$configKey = explode('_', $key, 3);
if (sizeof($configKey) < 3) {
Logger::warning('EditResourceForm: invalid form key "' . $key . '" was ignored.');
continue;
}
$result[$configKey[2]] = $value;
}
}
return new Zend_Config($result);
}
}

View File

@ -27,7 +27,7 @@
*/
// {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\Form\Config\Resource;
namespace Icinga\Form\Config;
use Exception;
use Zend_Config;
@ -425,6 +425,26 @@ class ResourceForm extends Form
try {
switch ($config->type) {
case 'db':
/*
* It should be possible to run icingaweb without the pgsql or mysql extension or Zend-Pdo-Classes,
* in case they aren't actually used. When the user tries to create a resource that depends on an
* uninstalled extension, an error should be displayed.
*/
if ($config->db === 'mysql' && !ResourceFactory::mysqlAvailable()) {
$this->addErrorMessage(
t('You need to install the php extension "mysql" and the ' .
'Zend_Pdo_Mysql classes to use MySQL database resources.')
);
return false;
}
if ($config->db === 'pgsql' && !ResourceFactory::pgsqlAvailable()) {
$this->addErrorMessage(
t('You need to install the php extension "pgsql" and the ' .
'Zend_Pdo_Pgsql classes to use PostgreSQL database resources.')
);
return false;
}
$resource = ResourceFactory::createResource($config);
$resource->getConnection()->getConnection();
break;

View File

@ -12,23 +12,23 @@ use Icinga\Application\Config;
use Icinga\Exception\ConfigurationError;
/**
* Class to write log messages to a stream
* Class to write log messages to a file
*/
class StreamWriter extends LogWriter
class FileWriter extends LogWriter
{
/**
* The path to the stream
* The path to the file
*
* @var string
*/
protected $stream;
protected $path;
/**
* Create a new log writer initialized with the given configuration
*/
public function __construct(Zend_Config $config)
{
$this->stream = Config::resolvePath($config->target);
$this->path = Config::resolvePath($config->target);
$this->setup();
}
@ -44,17 +44,17 @@ class StreamWriter extends LogWriter
}
/**
* Create the stream if it does not already exist
* Create the file if it does not already exist
*/
protected function setup()
{
if (substr($this->stream, 0, 6) !== 'php://') {
if (!file_exists($this->stream) && (!@touch($this->stream) || !@chmod($this->stream, 0664))) {
throw new ConfigurationError('Cannot create log file "' . $this->stream . '"');
if (substr($this->path, 0, 6) !== 'php://') {
if (!file_exists($this->path) && (!@touch($this->path) || !@chmod($this->path, 0664))) {
throw new ConfigurationError('Cannot create log file "' . $this->path . '"');
}
if (!@is_writable($this->stream)) {
throw new ConfigurationError('Cannot write to log file "' . $this->stream . '"');
if (!@is_writable($this->path)) {
throw new ConfigurationError('Cannot write to log file "' . $this->path . '"');
}
}
}
@ -85,18 +85,18 @@ class StreamWriter extends LogWriter
}
/**
* Write a message to the stream
* Write a message to the path
*
* @param string $text The message to write
*
* @throws Exception In case write acess to the stream failed
* @throws Exception In case write acess to the path failed
*/
protected function write($text)
{
$fd = fopen($this->stream, 'a');
$fd = fopen($this->path, 'a');
if ($fd === false || fwrite($fd, $text . PHP_EOL) === false) {
throw new Exception('Failed to write to log file "' . $this->stream . '"');
throw new Exception('Failed to write to log file "' . $this->path . '"');
}
fclose($fd);

View File

@ -11,7 +11,7 @@ require_once realpath(dirname(__FILE__) . '/../../../../bootstrap.php');
use Mockery;
use Zend_Config;
use Icinga\Test\BaseTestCase;
use Icinga\Form\Config\Resource\ResourceForm;
use Icinga\Form\Config\ResourceForm;
class TestResourceForm extends ResourceForm
{

View File

@ -7,7 +7,7 @@ namespace Tests\Icinga\Logger\Writer;
use Zend_Config;
use Icinga\Logger\Logger;
use Icinga\Test\BaseTestCase;
use Icinga\Logger\Writer\StreamWriter;
use Icinga\Logger\Writer\FileWriter;
class LoggerTest extends BaseTestCase
{
@ -27,7 +27,7 @@ class LoggerTest extends BaseTestCase
public function testWhetherStreamWriterCreatesMissingFiles()
{
new StreamWriter(new Zend_Config(array('target' => $this->target)));
new FileWriter(new Zend_Config(array('target' => $this->target)));
$this->assertFileExists($this->target, 'StreamWriter does not create missing files on initialization');
}
@ -36,7 +36,7 @@ class LoggerTest extends BaseTestCase
*/
public function testWhetherStreamWriterWritesMessages()
{
$writer = new StreamWriter(new Zend_Config(array('target' => $this->target)));
$writer = new FileWriter(new Zend_Config(array('target' => $this->target)));
$writer->log(Logger::$ERROR, 'This is a test error');
$log = file_get_contents($this->target);
$this->assertContains('This is a test error', $log, 'StreamWriter does not write log messages');