Add status.php for getting iTop's status (#56)

Allow for HAProxy and monitoring to get iTop's status
 Add tests for status

Signed-off-by: Guy Couronné <gcouronne:@sapiens.biz>
This commit is contained in:
Guy Couronné
2019-04-17 09:21:45 +02:00
committed by Molkobain
parent a773a4957a
commit d4d16f43ac
5 changed files with 410 additions and 0 deletions

67
status.inc.php Normal file
View File

@@ -0,0 +1,67 @@
<?php
define('STATUS_ERROR', 'ERROR');
define('STATUS_RUNNING', 'RUNNING');
/**
* Get approot.inc.php
* Move to a function for allowing a better testing
*
* @param string $sAppRootFilename
* @throws \Exception
*/
function StatusGetAppRoot($sAppRootFilename = 'approot.inc.php')
{
$sAppRootFile = dirname(__FILE__).'/'.$sAppRootFilename;
/*
* Check that the approot file exists and has the appropriate access rights
*/
if (!file_exists($sAppRootFile) || !is_readable($sAppRootFile))
{
throw new \Exception($sAppRootFilename . ' is not readable');
}
require_once($sAppRootFile);
}
/**
* Check iTop's config File existence and readability
* Move to a function for allowing a better testing
*
* @param string $sConfigFilename
* @throws \Exception
*/
function StatusCheckConfigFile($sConfigFilename = 'config-itop.php')
{
\StatusGetAppRoot();
$sConfigFile = APPCONF.ITOP_DEFAULT_ENV.'/'.$sConfigFilename;
/**
* Check that the configuration file exists and has the appropriate access rights
*/
if (!file_exists($sConfigFile) || !is_readable($sConfigFile))
{
throw new \Exception($sConfigFilename . ' is not readable');
}
}
/**
* Start iTop's application for checking with its internal basic test every it's alright (DB connection, ...)
* Move to a function for allowing a better testing
*
* @param \Config $oConfig
*/
function StatusStartup(\Config $oConfig = null)
{
\StatusCheckConfigFile();
require_once(APPROOT.'/core/cmdbobject.class.inc.php');
require_once(APPROOT.'/application/utils.inc.php');
require_once(APPROOT.'/core/contexttag.class.inc.php');
$soConfigFile = (empty($oConfig)) ? ITOP_DEFAULT_CONFIG_FILE : $oConfig;
//Check if aplication could be started
\MetaModel::Startup($soConfigFile, true /* $bModelOnly */);
}

26
status.php Normal file
View File

@@ -0,0 +1,26 @@
<?php
//Include status functions
require_once(dirname(__FILE__) . '/status.inc.php');
//Do check Status
try
{
\StatusStartup();
$aResult = array('status' => STATUS_RUNNING, 'code' => \RestResult::OK, 'message' => '');
}
catch (\Exception $e)
{
$iCode = (defined('\RestResult::INTERNAL_ERROR')) ? \RestResult::INTERNAL_ERROR : 100;
$aResult = array('status' => STATUS_ERROR, 'code' => $iCode, 'message' => $e->getMessage());
http_response_code(500);
}
//Set headers, based on webservices/rest.php
$sContentType = 'application/json';
header('Content-type: ' . $sContentType);
header('Access-Control-Allow-Origin: *');
//Output result
$sResponse = json_encode($aResult);
echo $sResponse;

View File

@@ -53,6 +53,9 @@
<testsuite name="Application">
<directory>application</directory>
</testsuite>
<testsuite name="Status">
<directory>status</directory>
</testsuite>
</testsuites>
<!-- Code coverage white list -->

View File

@@ -0,0 +1,114 @@
<?php
/**
* User: Guy Couronné (guy.couronne@gmail.com)
* Date: 25/01/2019
*/
namespace Combodo\iTop\Test\UnitTest\Status;
/**
* User: Guy Couronné (guy.couronne@gmail.com)
* Date: 25/01/2019
*/
use PHPUnit\Framework\TestCase;
if (!defined('DEBUG_UNIT_TEST')) {
define('DEBUG_UNIT_TEST', true);
}
/**
* @runTestsInSeparateProcesses
* @preserveGlobalState disabled
* @backupGlobals disabled
*/
class StatusIncTest extends TestCase {
/**
*
* @var string
*/
protected $sAppRoot = '';
/**
*
*/
protected function setUp() {
//AppRoot is the directory containing the directory
//Assume getcwd() is runned inside APPROOT/test
$this->sAppRoot = dirname(getcwd());
}
/**
* @expectedException \Exception
*/
public function testStatusGetAppRootWrongPath() {
include_once($this->sAppRoot . '/status.inc.php');
$sAppRootFilenamewrong = 'approot.inc.php_wrong';
StatusGetAppRoot($sAppRootFilenamewrong);
}
/**
*
*/
public function testStatusGetAppRootGood() {
include_once($this->sAppRoot . '/status.inc.php');
StatusGetAppRoot();
$this->assertNotEmpty(APPROOT);
}
/**
* @expectedException \Exception
*/
public function testStatusCheckConfigFileWrongPath() {
include_once($this->sAppRoot . '/status.inc.php');
$sConfigFilenamewrong = 'config-itop.php_wrong';
StatusCheckConfigFile($sConfigFilenamewrong);
}
/**
*
*/
public function testStatusCheckConfigFileGood() {
include_once($this->sAppRoot . '/status.inc.php');
StatusCheckConfigFile();
$this->assertTrue(true);
}
/**
* @expectedException \MySQLException
*/
public function testStatusStartupWrongDbPwd() {
include_once($this->sAppRoot . '/status.inc.php');
\StatusCheckConfigFile();
require_once(APPROOT . '/core/cmdbobject.class.inc.php');
require_once(APPROOT . '/application/utils.inc.php');
require_once(APPROOT . '/core/contexttag.class.inc.php');
$oConfigWrong = new \Config(ITOP_DEFAULT_CONFIG_FILE);
$oConfigWrong->Set('db_pwd', $oConfigWrong->Get('db_pwd') . '_unittest');
StatusStartup($oConfigWrong);
}
/**
*
*/
public function testStatusStartupGood() {
include_once($this->sAppRoot . '/status.inc.php');
StatusStartup();
$this->assertTrue(true);
}
}

200
test/status/StatusTest.php Normal file
View File

@@ -0,0 +1,200 @@
<?php
/**
* User: Guy Couronné (guy.couronne@gmail.com)
* Date: 25/01/2019
*/
namespace Combodo\iTop\Test\UnitTest\Status;
use Combodo\iTop\Test\UnitTest\ItopDataTestCase;
/**
*
*/
class StatusTest extends ItopDataTestCase {
/**
*
*/
public function testStatusWrongUrl() {
$sUrl = \utils::GetAbsoluteUrlAppRoot() . 'status_wrong.php';
if (function_exists('curl_init')) {
// If cURL is available, let's use it, since it provides a greater control over the various HTTP/SSL options
// For instance fopen does not allow to work around the bug: http://stackoverflow.com/questions/18191672/php-curl-ssl-routinesssl23-get-server-helloreason1112
// by setting the SSLVERSION to 3 as done below.
// Default options, can be overloaded/extended with the 4th parameter of this method, see above $aCurlOptions
$aOptions = array(
CURLOPT_RETURNTRANSFER => true, // return the content of the request
CURLOPT_HEADER => false, // don't return the headers in the output
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_SSL_VERIFYPEER => false, // Disabled SSL Cert checks
// SSLV3 (CURL_SSLVERSION_SSLv3 = 3) is now considered as obsolete/dangerous: http://disablessl3.com/#why
// but it used to be a MUST to prevent a strange SSL error: http://stackoverflow.com/questions/18191672/php-curl-ssl-routinesssl23-get-server-helloreason1112
// CURLOPT_SSLVERSION
CURLOPT_CUSTOMREQUEST => 'HEAD', //Get only HTTP Code as this page should only return a HTTP Code
);
$ch = curl_init($sUrl);
curl_setopt_array($ch, $aOptions);
curl_exec($ch);
$sHttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
} else {
// cURL is not available let's try with streams and fopen...
// By default get_headers uses a GET request to fetch the headers. If you
// want to send a HEAD request instead, you can do so using a stream context:
stream_context_set_default(
array(
'http' => array(
'method' => 'HEAD'
)
)
);
$headers = get_headers($sUrl);
//Undo overriding default context
stream_context_set_default(
array(
'http' => array(
'method' => 'GET'
)
)
);
$sHttpCode = (int) substr($headers[0], 9, 3);
}
$this->assertNotEquals(200, $sHttpCode, "Problem opening URL: $sUrl, $sHttpCode");
}
/**
*
*/
public function testStatusGood() {
$sUrl = \utils::GetAbsoluteUrlAppRoot() . 'status.php';
if (function_exists('curl_init')) {
// If cURL is available, let's use it, since it provides a greater control over the various HTTP/SSL options
// For instance fopen does not allow to work around the bug: http://stackoverflow.com/questions/18191672/php-curl-ssl-routinesssl23-get-server-helloreason1112
// by setting the SSLVERSION to 3 as done below.
// Default options, can be overloaded/extended with the 4th parameter of this method, see above $aCurlOptions
$aOptions = array(
CURLOPT_RETURNTRANSFER => true, // return the content of the request
CURLOPT_HEADER => false, // don't return the headers in the output
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_SSL_VERIFYPEER => false, // Disabled SSL Cert checks
// SSLV3 (CURL_SSLVERSION_SSLv3 = 3) is now considered as obsolete/dangerous: http://disablessl3.com/#why
// but it used to be a MUST to prevent a strange SSL error: http://stackoverflow.com/questions/18191672/php-curl-ssl-routinesssl23-get-server-helloreason1112
// CURLOPT_SSLVERSION
CURLOPT_CUSTOMREQUEST => 'HEAD', //Get only HTTP Code as this page should only return a HTTP Code
);
$ch = curl_init($sUrl);
curl_setopt_array($ch, $aOptions);
curl_exec($ch);
$iErr = curl_errno($ch);
$sErrMsg = curl_error($ch);
$sHttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$this->assertEquals(0, $iErr, "Problem opening URL: $sUrl, $sErrMsg");
} else {
// cURL is not available let's try with streams and fopen...
// By default get_headers uses a GET request to fetch the headers. If you
// want to send a HEAD request instead, you can do so using a stream context:
stream_context_set_default(
array(
'http' => array(
'method' => 'HEAD'
)
)
);
$headers = get_headers($sUrl);
//Undo overriding default context
stream_context_set_default(
array(
'http' => array(
'method' => 'GET'
)
)
);
$sHttpCode = (int) substr($headers[0], 9, 3);
}
$this->assertEquals(200, $sHttpCode, "Problem opening URL: $sUrl, $sHttpCode");
}
/**
*
*/
public function testStatusGoodWithJson() {
$sUrl = \utils::GetAbsoluteUrlAppRoot() . 'status.php';
if (function_exists('curl_init')) {
// If cURL is available, let's use it, since it provides a greater control over the various HTTP/SSL options
// For instance fopen does not allow to work around the bug: http://stackoverflow.com/questions/18191672/php-curl-ssl-routinesssl23-get-server-helloreason1112
// by setting the SSLVERSION to 3 as done below.
// Default options, can be overloaded/extended with the 4th parameter of this method, see above $aCurlOptions
$aOptions = array(
CURLOPT_RETURNTRANSFER => true, // return the content of the request
CURLOPT_HEADER => false, // don't return the headers in the output
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_SSL_VERIFYPEER => false, // Disabled SSL Cert checks
// SSLV3 (CURL_SSLVERSION_SSLv3 = 3) is now considered as obsolete/dangerous: http://disablessl3.com/#why
// but it used to be a MUST to prevent a strange SSL error: http://stackoverflow.com/questions/18191672/php-curl-ssl-routinesssl23-get-server-helloreason1112
// CURLOPT_SSLVERSION
);
$ch = curl_init($sUrl);
curl_setopt_array($ch, $aOptions);
$response = curl_exec($ch);
$iErr = curl_errno($ch);
$sErrMsg = curl_error($ch);
$sHttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$this->assertEquals(0, $iErr, "Problem opening URL: $sUrl, $sErrMsg");
$this->assertEquals(200, $sHttpCode, "Problem opening URL: $sUrl, $sHttpCode");
} else {
// cURL is not available let's try with file_get_contents
$response = file_get_contents($sUrl);
$this->assertNotFalse($response, "Problem opening URL: $sUrl");
}
//Check response
$this->assertNotEmpty($response, 'Empty response');
$this->assertJson($response, 'Not a JSON');
$aResponseDecoded = json_decode($response, true);
//Check status
$this->assertArrayHasKey('status', $aResponseDecoded, 'JSON does not have a status\' field');
$this->assertEquals('RUNNING', $aResponseDecoded['status'], 'Status is not \'RUNNING\'');
//Check code
$this->assertArrayHasKey('code', $aResponseDecoded, 'JSON does not have a code\' field');
$this->assertEquals(0, $aResponseDecoded['code'], 'Code is not 0');
//Check message
$this->assertArrayHasKey('message', $aResponseDecoded, 'JSON does not have a message\' field');
$this->assertEmpty($aResponseDecoded['message'], 'Message is not empty');
}
}