Skip to content
Snippets Groups Projects
Commit 60c6f1ad authored by Hahn Axel (hahn)'s avatar Hahn Axel (hahn)
Browse files

Merge branch '7393-update-appmonitor' into 'master'

update appmonitor client v1.137

See merge request !65
parents a705cc9a 34eea7a2
Branches
No related tags found
1 merge request!65update appmonitor client v1.137
Pipeline #4343 passed
Showing
with 968 additions and 866 deletions
...@@ -51,64 +51,66 @@ if(!defined('RESULT_OK')){ ...@@ -51,64 +51,66 @@ if(!defined('RESULT_OK')){
* 2021-10-28 0.93 axel.hahn@iml.unibe.ch add plugins<br> * 2021-10-28 0.93 axel.hahn@iml.unibe.ch add plugins<br>
* 2021-12-14 0.93 axel.hahn@iml.unibe.ch split plugins into single files; added key group in a check<br> * 2021-12-14 0.93 axel.hahn@iml.unibe.ch split plugins into single files; added key group in a check<br>
* 2023-06-02 0.125 axel.hahn@unibe.ch replace array_key_exists for better readability * 2023-06-02 0.125 axel.hahn@unibe.ch replace array_key_exists for better readability
* 2024-07-22 0.137 axel.hahn@unibe.ch php 8 only: use typed variables
* --------------------------------------------------------------------------------<br> * --------------------------------------------------------------------------------<br>
* @version 0.125 * @version 0.137
* @author Axel Hahn * @author Axel Hahn
* @link TODO * @link TODO
* @license GPL * @license GPL
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL 3.0 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL 3.0
* @package IML-Appmonitor * @package IML-Appmonitor
*/ */
class appmonitorcheck { class appmonitorcheck
{
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
// CONFIG // CONFIG
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
/** /**
* starting time using microtime * starting time using microtime
* @var float|string * @var float
*/ */
protected $_iStart=0; protected float $_iStart = 0;
/** /**
* config container * config container
* @var array * @var array
*/ */
protected $_aConfig = []; protected array $_aConfig = [];
/** /**
* data of all checks * data of all checks
* @var array * @var array
*/ */
protected $_aData = []; protected array $_aData = [];
/** /**
* flat array with units for sizes * flat array with units for sizes
* @var array * @var array
*/ */
protected $_units = [ 'B', 'KB', 'MB', 'GB', 'TB' ]; protected array $_units = ['B', 'KB', 'MB', 'GB', 'TB'];
/** /**
* timeout in sec for tcp socket connections * timeout in sec for tcp socket connections
* @var type * @var integer
*/ */
protected $_iTimeoutTcp=5; protected int $_iTimeoutTcp = 5;
/** /**
* point to the plugin directory * point to the plugin directory
* @var string * @var string
*/ */
protected $_sPluginDir=__DIR__.'/../plugins'; protected string $_sPluginDir = __DIR__ . '/../plugins';
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
// CONSTRUCTOR // CONSTRUCTOR
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
/** /**
* constructor (nothing) * Constructor (nothing here)
*/ */
public function __construct() { public function __construct()
{
} }
...@@ -117,10 +119,11 @@ class appmonitorcheck { ...@@ -117,10 +119,11 @@ class appmonitorcheck {
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
/** /**
* internal: create basic array values for metadata * Internal: create basic array values for metadata
* @return boolean * @return boolean
*/ */
protected function _createDefaultMetadata() { protected function _createDefaultMetadata(): bool
{
$this->_aData = [ $this->_aData = [
"name" => $this->_aConfig["name"], "name" => $this->_aConfig["name"],
...@@ -136,29 +139,34 @@ class appmonitorcheck { ...@@ -136,29 +139,34 @@ class appmonitorcheck {
} }
/** /**
* set a result value of a check * Set the result value of a check
* @param type $iResult * @param integer $iResult result code; one of RESULT_OK|RESULT_WARNING|RESULT_ERROR|RESULT_UNKNOWN
* @return type * @return bool
*/ */
protected function _setResult($iResult) { protected function _setResult(int $iResult): bool
return $this->_aData["result"] = (int) $iResult; {
$this->_aData["result"] = (int) $iResult;
return true;
} }
/** /**
* set a result value of a check * Set a result value of a check
* @param type $iResult * @param string $s value; message text for this result
* @return type * @return bool
*/ */
protected function _setOutput($s) { protected function _setOutput(string $s): bool
return $this->_aData["value"] = (string) $s; {
$this->_aData["value"] = $s;
return true;
} }
/** /**
* put counter data to result set * Put counter data to result set
* @param type $aParams * @param array $aParams array with possible keys type, count, visual
* @return boolean * @return boolean
*/ */
protected function _setCounter($aParams){ protected function _setCounter(array $aParams): bool
{
if (is_array($aParams) && count($aParams)) { if (is_array($aParams) && count($aParams)) {
foreach (['type', 'count', 'visual'] as $sMyKey) { foreach (['type', 'count', 'visual'] as $sMyKey) {
if (isset($aParams[$sMyKey])) { if (isset($aParams[$sMyKey])) {
...@@ -170,13 +178,14 @@ class appmonitorcheck { ...@@ -170,13 +178,14 @@ class appmonitorcheck {
} }
/** /**
* set result and output * Set result and output
* @param integer $iResult value; use a RESULT_XYZ constant * @param integer $iResult result code; one of RESULT_OK|RESULT_WARNING|RESULT_ERROR|RESULT_UNKNOWN
* @param string $s message text * @param string $s message text
* @param array $aCounter optional: counter with array keys type, count, visual * @param array $aCounter optional: counter with array keys type, count, visual
* @return boolean * @return boolean
*/ */
protected function _setReturn($iResult, $s, $aCounter=[]) { protected function _setReturn(int $iResult, string $s, array $aCounter = [])
{
$this->_setResult($iResult); $this->_setResult($iResult);
$this->_setOutput($s); $this->_setOutput($s);
$this->_setCounter($aCounter); $this->_setCounter($aCounter);
...@@ -184,12 +193,13 @@ class appmonitorcheck { ...@@ -184,12 +193,13 @@ class appmonitorcheck {
} }
/** /**
* check a given array if it contains wanted keys * Check a given array if it contains wanted keys
* @param array $aConfig array to verify * @param array $aConfig array to verify
* @param string $sKeyList key or keys as comma seprated list * @param string $sKeyList key or keys as comma seprated list
* @return boolean * @return boolean
*/ */
protected function _checkArrayKeys($aConfig, $sKeyList) { protected function _checkArrayKeys($aConfig, $sKeyList)
{
foreach (explode(",", $sKeyList) as $sKey) { foreach (explode(",", $sKeyList) as $sKey) {
if (!isset($aConfig[$sKey])) { if (!isset($aConfig[$sKey])) {
header('HTTP/1.0 503 Service Unavailable'); header('HTTP/1.0 503 Service Unavailable');
...@@ -216,9 +226,9 @@ class appmonitorcheck { ...@@ -216,9 +226,9 @@ class appmonitorcheck {
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
/** /**
* perform a check * Perform a check
* @param type $aConfig * @param array $aConfig configuration array for a check, eg.
* Array * <code>
* [ * [
* [name] => Dummy * [name] => Dummy
* [description] => Dummy Test * [description] => Dummy Test
...@@ -228,10 +238,11 @@ class appmonitorcheck { ...@@ -228,10 +238,11 @@ class appmonitorcheck {
* // its keys depend on the function * // its keys depend on the function
* ] * ]
* ] * ]
* * </code>
* @return array * @return array
*/ */
public function makeCheck($aConfig) { public function makeCheck(array $aConfig): array
{
$this->_iStart = microtime(true); $this->_iStart = microtime(true);
$this->_checkArrayKeys($aConfig, "name,description,check"); $this->_checkArrayKeys($aConfig, "name,description,check");
$this->_checkArrayKeys($aConfig["check"], "function"); $this->_checkArrayKeys($aConfig["check"], "function");
...@@ -282,7 +293,7 @@ class appmonitorcheck { ...@@ -282,7 +293,7 @@ class appmonitorcheck {
. "<pre>RESPONSE " . print_r($aResponse, true) . '</pre>' . "<pre>RESPONSE " . print_r($aResponse, true) . '</pre>'
); );
} }
if(!isset($aResponse[2])){ if (!isset($aResponse[2]) || !$aResponse[2]) {
$aResponse[2] = []; $aResponse[2] = [];
} }
$this->_setReturn($aResponse[0], $aResponse[1], $aResponse[2]); $this->_setReturn($aResponse[0], $aResponse[1], $aResponse[2]);
...@@ -296,12 +307,13 @@ class appmonitorcheck { ...@@ -296,12 +307,13 @@ class appmonitorcheck {
} }
/** /**
* list all available check functions. This is a helper class you can call * List all available checks. This is a helper class you can call
* to get an overview over built in functions and plugins. * to get an overview over built in functions and plugins.
* You get a flat array with all function names. * You get a flat array with all function names.
* @return array * @return array
*/ */
public function listChecks() { public function listChecks(): array
{
$aReturn = []; $aReturn = [];
// return internal protected fuctions named "check[whatever]" // return internal protected fuctions named "check[whatever]"
$class = new ReflectionClass($this); $class = new ReflectionClass($this);
...@@ -319,10 +331,11 @@ class appmonitorcheck { ...@@ -319,10 +331,11 @@ class appmonitorcheck {
} }
/** /**
* final call of class: send response (data array) * Final call of class: send response (data array)
* @return type * @return array
*/ */
public function respond() { public function respond()
{
return $this->_aData; return $this->_aData;
} }
...@@ -331,13 +344,15 @@ class appmonitorcheck { ...@@ -331,13 +344,15 @@ class appmonitorcheck {
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
/** /**
* helper function: read certificate data * Helper function: read certificate data
* called in checkCert() * called in checkCert()
*
* @param string $sUrl url to connect * @param string $sUrl url to connect
* @param boolean $bVerifyCert flag: verify certificate; default: no check * @param boolean $bVerifyCert flag: verify certificate; default: no check
* @return array * @return array
*/ */
protected function _certGetInfos($sUrl, $bVerifyCert) { protected function _certGetInfos(string $sUrl, bool $bVerifyCert): array
{
$iTimeout = 10; $iTimeout = 10;
$aUrldata = parse_url($sUrl); $aUrldata = parse_url($sUrl);
$sHost = isset($aUrldata['host']) ? $aUrldata['host'] : false; $sHost = isset($aUrldata['host']) ? $aUrldata['host'] : false;
...@@ -347,7 +362,8 @@ class appmonitorcheck { ...@@ -347,7 +362,8 @@ class appmonitorcheck {
if ($bVerifyCert) { if ($bVerifyCert) {
$aSsl['verify_peer'] = false; $aSsl['verify_peer'] = false;
$aSsl['verify_peer_name'] = false; $aSsl['verify_peer_name'] = false;
}; }
;
$get = stream_context_create(['ssl' => $aSsl]); $get = stream_context_create(['ssl' => $aSsl]);
if (!$get) { if (!$get) {
return ['_error' => 'Error: Cannot create stream_context']; return ['_error' => 'Error: Cannot create stream_context'];
...@@ -362,26 +378,28 @@ class appmonitorcheck { ...@@ -362,26 +378,28 @@ class appmonitorcheck {
if (!$cert) { if (!$cert) {
return ['_error' => "Error: socket was connected to ssl://$sHost:$iPort - but I cannot read certificate infos with stream_context_get_params "]; return ['_error' => "Error: socket was connected to ssl://$sHost:$iPort - but I cannot read certificate infos with stream_context_get_params "];
} }
$certinfo = openssl_x509_parse($cert['options']['ssl']['peer_certificate']); return openssl_x509_parse($cert['options']['ssl']['peer_certificate']);
return $certinfo;
} }
/** /**
* get human readable space value * Get human readable space value
* @param integer $size * @param integer $size
* @return string * @return string
*/ */
protected function _getHrSize($size){ protected function _getHrSize(int $size): string
{
$power = $size > 0 ? floor(log($size, 1024)) : 0; $power = $size > 0 ? floor(log($size, 1024)) : 0;
return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $this->_units[$power]; return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $this->_units[$power];
} }
/** /**
* get a space in a real value if an integer has added MB|GB|... * get a space in a real value if an integer has added MB|GB|...
* @param string $sValue * @param string $sValue
* @return integer * @return integer
*/ */
protected function _getSize($sValue){ protected function _getSize(string $sValue): int
{
if (is_int($sValue)) { if (is_int($sValue)) {
return $sValue; return $sValue;
} }
...@@ -402,43 +420,4 @@ class appmonitorcheck { ...@@ -402,43 +420,4 @@ class appmonitorcheck {
); );
} }
/**
* compare function for 2 values
* @param string $verifyValue search value
* @param string $sCompare compare function; it is one of
* IS -
* GE - greater or equal
* GT - greater
* @param string $value existing value
* @return boolean
*/
protected function _compare($value, $sCompare, $verifyValue){
switch ($sCompare){
case "IS":
return $value===$verifyValue;
break;
case "GE":
return $value>=$verifyValue;
break;
case "GT":
return $value>$verifyValue;
break;
case "HAS":
return !!(strstr($value, $verifyValue)!==false);
break;
default:
header('HTTP/1.0 503 Service Unavailable');
die('<h1>503 Service Unavailable</h1>'
. '<h2>Details</h2>'
.__METHOD__ . " - FATAL ERROR: a compare function [$sCompare] is not implemented (yet)."
);
break;
}
return false;
}
} }
This diff is collapsed.
This diff is collapsed.
#!/bin/bash #!/bin/bash
# ====================================================================== # ======================================================================
# #
# UPDATE APPMONITOR CLIENT # A P P M O N I T O R :: CLIENT - UPDATE
# #
# requires git, rsync # This script will install or update the appmonitor client only.
#
# Below the document root of a website create a new directory,
# i.e. [webroot]/appmonitor/ and copy this script there.
# Change the directory "cd [webroot]/appmonitor/" and execute it.
# #
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# 2022-04-11 <axel.hahn@iml.unibe.ch> first lines # requires git, rsync
# 2022-04-12 <axel.hahn@iml.unibe.ch> add help; exclude unneeded files # ----------------------------------------------------------------------
# 2022-05-03 <axel.hahn@iml.unibe.ch> create general_include.php # 2022-04-11 0.1 <axel.hahn@iml.unibe.ch> first lines
# 2022-04-12 0.2 <axel.hahn@iml.unibe.ch> add help; exclude unneeded files
# 2022-05-03 0.3 <axel.hahn@iml.unibe.ch> create general_include.php
# 2024-07-25 0.4 <axel.hahn@iml.unibe.ch> update quoting and comments
# ====================================================================== # ======================================================================
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
...@@ -16,14 +23,14 @@ ...@@ -16,14 +23,14 @@
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
readonly git_repo_url="https://github.com/iml-it/appmonitor.git" readonly git_repo_url="https://github.com/iml-it/appmonitor.git"
readonly line="____________________________________________________________" readonly line="______________________________________________________________________________"
readonly version="0.3" readonly version="0.4"
git_target=/tmp/git_data__appmonitor git_target=/tmp/git_data__appmonitor
client_from="${git_target}/public_html/client" client_from="${git_target}/public_html/client"
client_to="." client_to="."
cd $( dirname "$0" ) || exit 1 cd "$( dirname "$0" )" || exit 1
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# FUNCTIONS # FUNCTIONS
...@@ -99,6 +106,9 @@ case "$1" in ...@@ -99,6 +106,9 @@ case "$1" in
This is a helper script to get the files of the IML Appmonitor This is a helper script to get the files of the IML Appmonitor
client part only. client part only.
Below the document root of a website create a new directory,
i.e. [webroot]/appmonitor/ and copy this script there.
This script clones and updates the repository in the /tmp This script clones and updates the repository in the /tmp
directory and syncs the client files of it to a given directory. directory and syncs the client files of it to a given directory.
...@@ -157,6 +167,7 @@ rsync -rav \ ...@@ -157,6 +167,7 @@ rsync -rav \
--exclude "*.sample.*" \ --exclude "*.sample.*" \
--exclude "example.json" \ --exclude "example.json" \
--exclude "check-appmonitor-server.php" \ --exclude "check-appmonitor-server.php" \
--exclude "local.php" \
$client_from/* "$client_to" $client_from/* "$client_to"
echo echo
...@@ -165,7 +176,7 @@ _fileupdate general_include.sample.php ...@@ -165,7 +176,7 @@ _fileupdate general_include.sample.php
echo $line echo $line
echo ">>> #3 of 3 >>> Diff" echo ">>> #3 of 3 >>> Diff"
echo echo
diff -r "$client_from" "$client_to" diff --color -r "$client_from" "$client_to"
echo echo
......
<?php
require __DIR__ . '/check-appmonitor-server.php';
$sJson=ob_get_contents();
ob_end_clean();
echo $oMonitor->renderHtmloutput($sJson);
...@@ -12,6 +12,7 @@ ...@@ -12,6 +12,7 @@
* 2019-05-17 aded check http to config- and tmp dir * 2019-05-17 aded check http to config- and tmp dir
* 2021-11-nn removed all checks ... created as single files * 2021-11-nn removed all checks ... created as single files
* 2022-03-28 move checks into plugins/apps/ * 2022-03-28 move checks into plugins/apps/
* 2024-07-23 php 8: short array syntax
*/ */
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
...@@ -19,65 +20,65 @@ ...@@ -19,65 +20,65 @@
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
$oMonitor->addCheck( $oMonitor->addCheck(
array( [
"name" => "write to ./tmp/", "name" => "write to ./tmp/",
"description" => "Check cache storage", "description" => "Check cache storage",
// "group" => "folder", // "group" => "folder",
"check" => array( "check" => [
"function" => "File", "function" => "File",
"params" => array( "params" => [
"filename" => $sApproot . "/server/tmp", "filename" => "$sApproot/server/tmp",
"dir" => true, "dir" => true,
"writable" => true, "writable" => true,
), ],
), ],
) ]
); );
$oMonitor->addCheck( $oMonitor->addCheck(
array( [
"name" => "write to ./config/", "name" => "write to ./config/",
"description" => "Check config target directory", "description" => "Check config target directory",
// "group" => "folder", // "group" => "folder",
"check" => array( "check" => [
"function" => "File", "function" => "File",
"params" => array( "params" => [
"filename" => $sApproot . "/server/config", "filename" => "$sApproot/server/config",
"dir" => true, "dir" => true,
"writable" => true, "writable" => true,
), ],
), ],
) ]
); );
$oMonitor->addCheck( $oMonitor->addCheck(
array( [
"name" => "check config file", "name" => "check config file",
"description" => "The config file must be writable", "description" => "The config file must be writable",
"parent" => "write to ./config/", "parent" => "write to ./config/",
// "group" => "file", // "group" => "file",
"check" => array( "check" => [
"function" => "File", "function" => "File",
"params" => array( "params" => [
"filename" => $sApproot . "/server/config/appmonitor-server-config.json", "filename" => "$sApproot/server/config/appmonitor-server-config.json",
"file" => true, "file" => true,
"writable" => true, "writable" => true,
), ],
), ],
) ]
); );
$oMonitor->addCheck( $oMonitor->addCheck(
array( [
"name" => "PHP modules", "name" => "PHP modules",
"description" => "Check needed PHP modules", "description" => "Check needed PHP modules",
// "group" => "folder", // "group" => "folder",
"check" => array( "check" => [
"function" => "Phpmodules", "function" => "Phpmodules",
"params" => array( "params" => [
"required" => ["curl"], "required" => ["curl"],
"optional" => [], "optional" => [],
), ],
), ],
) ]
); );
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
...@@ -89,21 +90,21 @@ $sBaseUrl = 'http'.(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] ? 's' : '') ...@@ -89,21 +90,21 @@ $sBaseUrl = 'http'.(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] ? 's' : '')
.'://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'] .'://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT']
.dirname(dirname($_SERVER['REQUEST_URI'])); .dirname(dirname($_SERVER['REQUEST_URI']));
foreach(array('server/config', 'server/tmp') as $sMyDir){ foreach(['server/config', 'server/tmp'] as $sMyDir){
$oMonitor->addCheck( $oMonitor->addCheck(
array( [
"name" => "http to $sMyDir", "name" => "http to $sMyDir",
"description" => "Check if the $sMyDir directory is not accessible (counts as warning on fail)", "description" => "Check if the $sMyDir directory is not accessible (counts as warning on fail)",
"group" => "deny", "group" => "deny",
"check" => array( "check" => [
"function" => "HttpContent", "function" => "HttpContent",
"params" => array( "params" => [
"url" => $sBaseUrl . "/$sMyDir/readme.md", "url" => "$sBaseUrl/$sMyDir/readme.md",
"status" => 403, "status" => 403,
), ],
), ],
"worstresult" => RESULT_WARNING "worstresult" => RESULT_WARNING
) ]
); );
} }
...@@ -114,48 +115,48 @@ require_once($sApproot.'/server/classes/appmonitor-server.class.php'); ...@@ -114,48 +115,48 @@ require_once($sApproot.'/server/classes/appmonitor-server.class.php');
$oServer=new appmonitorserver(); $oServer=new appmonitorserver();
$iCount=count($oServer->getAppIds()); $iCount=count($oServer->getAppIds());
$oMonitor->addCheck( $oMonitor->addCheck(
array( [
"name" => "appcounter", "name" => "appcounter",
"description" => "Monitored apps", "description" => "Monitored apps",
"group" => "monitor", "group" => "monitor",
"parent" => "check config file", "parent" => "check config file",
"check" => array( "check" => [
"function" => "Simple", "function" => "Simple",
"params" => array( "params" => [
"result" => RESULT_OK, "result" => RESULT_OK,
"value" => "Found monitored web apps: $iCount", "value" => "Found monitored web apps: $iCount",
"count" => $iCount, "count" => $iCount,
"visual" => "simple", "visual" => "simple",
), ],
), ],
) ]
); );
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
// check running service // check running service
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
require_once($sApproot.'/server/classes/tinyservice.class.php'); require_once($sApproot.'/server/classes/tinyservice.class.php');
ob_start(); ob_start();
$oService = new tinyservice($sApproot.'/server/service.php', 15, $sApproot.'/server/tmp'); $oService = new tinyservice("$sApproot/server/service.php", 15, "$sApproot/server/tmp");
$sIsStopped=$oService->canStart(); $sIsStopped=$oService->canStart();
$out=ob_get_contents(); $out=ob_get_contents();
ob_clean(); ob_clean();
$oMonitor->addCheck( $oMonitor->addCheck(
array( [
"name" => "running service", "name" => "running service",
"description" => "Check if the service is running", "description" => "Check if the service is running",
"group" => "service", "group" => "service",
"check" => array( "check" => [
"function" => "Simple", "function" => "Simple",
"params" => array( "params" => [
"result" => ($sIsStopped ? RESULT_WARNING : RESULT_OK), "result" => ($sIsStopped ? RESULT_WARNING : RESULT_OK),
"value" => ($sIsStopped "value" => ($sIsStopped
? "Info: Service is NOT running. Apps are checked interactively only (if the appmonitor web ui is running). | Output: $out" ? "Info: Service is NOT running. Apps are checked interactively only (if the appmonitor web ui is running). | Output: $out"
: "OK, service is running. | Output: $out" : "OK, service is running. | Output: $out"
),
),
),
"worstresult" => RESULT_OK
) )
],
],
"worstresult" => RESULT_OK
]
); );
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
// check certificate if https is used // check certificate if https is used
...@@ -170,42 +171,42 @@ include 'shared_check_ssl.php'; ...@@ -170,42 +171,42 @@ include 'shared_check_ssl.php';
* AS A DEMO: using a custom plugin: * AS A DEMO: using a custom plugin:
* *
$oMonitor->addCheck( $oMonitor->addCheck(
array( [
"name" => "plugin test", "name" => "plugin test",
"description" => "minimal test of the plugin plugins/checkHello.php", "description" => "minimal test of the plugin plugins/checkHello.php",
"check" => array( "check" => [
"function" => "Hello", "function" => "Hello",
"params" => array( "params" => []
"message" => "Here I am", "message" => "Here I am",
), ],
), ],
) ]
); );
$oMonitor->addCheck( $oMonitor->addCheck(
array( [
"name" => "plugin Load", "name" => "plugin Load",
"description" => "check current load", "description" => "check current load",
"check" => array( "check" => [
"function" => "Loadmeter", "function" => "Loadmeter",
"params" => array( "params" => [
"warning" => 1.0, "warning" => 1.0,
"error" => 3, "error" => 3,
), ],
), ],
"worstresult" => RESULT_OK "worstresult" => RESULT_OK
) ]
); );
$oMonitor->addCheck( $oMonitor->addCheck(
array( [
"name" => "plugin ApacheProcesses", "name" => "plugin ApacheProcesses",
"description" => "check count running Apache processes", "description" => "check count running Apache processes",
"check" => array( "check" => [
"function" => "ApacheProcesses", "function" => "ApacheProcesses",
"params" => array( "params" => [
), ],
), ],
"worstresult" => RESULT_OK "worstresult" => RESULT_OK
) ]
); );
*/ */
......
...@@ -44,21 +44,74 @@ ...@@ -44,21 +44,74 @@
* *
* 2019-06-07 <axel.hahn@iml.unibe.ch> * 2019-06-07 <axel.hahn@iml.unibe.ch>
* 2022-07-06 <axel.hahn@iml.unibe.ch> set group "monitor" * 2022-07-06 <axel.hahn@iml.unibe.ch> set group "monitor"
* 2024-07-23 <axel.hahn@unibe.ch> php 8 only: use typed variables
* *
*/ */
class checkApacheProcesses extends appmonitorcheck{ class checkApacheProcesses extends appmonitorcheck
{
protected $_sServerStatusUrl = 'http://localhost/server-status'; /**
protected $_iWarn = 50; * url of server status
protected $_iError = 75; * @var string
*/
protected string $_sServerStatusUrl = 'http://localhost/server-status';
/** /**
* fetch http server status and return slots, active and waiting processes * Warning level in percent
* as array i.e. [total] => 256 \n [free] => 247\n [waiting] => 7\n [active] => 2 * @var float
* @return boolean */
protected float $_iWarn = 50;
/**
* Critical level in percent
* @var float
*/ */
protected function _getApacheProcesses() { protected float $_iError = 75;
/**
* Self documentation (as idea)
* @return array
*/
public function explain(): array
{
return [
'name' => 'Plugin ApacheProcesses',
'descriptionm' => 'Check count running Apache processes',
'parameters' => [
'url' => [
'type' => 'string',
'required' => false,
'decsription' => 'Override https server-status page; default is http://localhost/server-status; Use it if the protocol to localhost is not http, but https or if it requires an authentication',
'default' => $this->_sServerStatusUrl,
'example' => '',
],
'warning' => [
'type' => 'float',
'required' => false,
'decsription' => 'Limit to switch to warning (in percent)',
'default' => $this->_iWarn,
'example' => 30,
],
'error' => [
'type' => 'float',
'required' => false,
'decsription' => 'Limit to switch to critical (in percent)',
'default' => $this->_iError,
'example' => 50,
],
],
];
}
/**
* Fetch http server status and return slots, active and waiting processes
* as array i.e. [total] => 256 \n [free] => 247\n [waiting] => 7\n [active] => 2
* It returns false if the url is not reachable
* It returns an empty array if the server status could not be parsed from http response
* @return array
*/
protected function _getApacheProcesses(): bool|array
{
$sBody = file_get_contents($this->_sServerStatusUrl); $sBody = file_get_contents($this->_sServerStatusUrl);
if (!$sBody) { if (!$sBody) {
return false; return false;
...@@ -78,22 +131,22 @@ class checkApacheProcesses extends appmonitorcheck{ ...@@ -78,22 +131,22 @@ class checkApacheProcesses extends appmonitorcheck{
return $aScore; return $aScore;
} }
/** /**
* get default group of this check * Get default group of this check
* @param array $aParams * @return string
* @return array
*/ */
public function getGroup(){ public function getGroup(): string
{
return 'monitor'; return 'monitor';
} }
/** /**
* * Implemented method: run the check
* @param array $aParams * @param array $aParams parameters
* @return array * @return array
*/ */
public function run($aParams){ public function run(array $aParams): array
{
// --- (1) verify if array key(s) exist: // --- (1) verify if array key(s) exist:
// $this->_checkArrayKeys($aParams, "..."); // $this->_checkArrayKeys($aParams, "...");
...@@ -107,7 +160,6 @@ class checkApacheProcesses extends appmonitorcheck{ ...@@ -107,7 +160,6 @@ class checkApacheProcesses extends appmonitorcheck{
$this->_iError = (int) $aParams['error']; $this->_iError = (int) $aParams['error'];
} }
// --- (2) do something magic // --- (2) do something magic
$aProcesses = $this->_getApacheProcesses(); $aProcesses = $this->_getApacheProcesses();
$iActive = $aProcesses ? $aProcesses['active'] : false; $iActive = $aProcesses ? $aProcesses['active'] : false;
...@@ -121,17 +173,16 @@ class checkApacheProcesses extends appmonitorcheck{ ...@@ -121,17 +173,16 @@ class checkApacheProcesses extends appmonitorcheck{
$iResult = RESULT_OK; $iResult = RESULT_OK;
if (($iActive / $iTotal * 100) > $this->_iWarn) { if (($iActive / $iTotal * 100) > $this->_iWarn) {
$iResult = RESULT_WARNING; $iResult = RESULT_WARNING;
$sComment='more than warning level '.$this->_iWarn.'%'; $sComment = "more than warning level $this->_iWarn %";
} else { } else {
$sComment='less than warning level '.$this->_iWarn.'%'; $sComment = "less than warning level $this->_iWarn %";
} }
if (($iActive / $iTotal * 100) > $this->_iError) { if (($iActive / $iTotal * 100) > $this->_iError) {
$iResult = RESULT_ERROR; $iResult = RESULT_ERROR;
$sComment='more than error level '.$this->_iError.'%'; $sComment = "more than error level $this->_iError %";
} }
} }
// --- (3) response // --- (3) response
// see method appmonitorcheck->_setReturn() // see method appmonitorcheck->_setReturn()
// //
......
...@@ -39,20 +39,22 @@ ...@@ -39,20 +39,22 @@
* 2021-10-26 <axel.hahn@iml.unibe.ch> * 2021-10-26 <axel.hahn@iml.unibe.ch>
* 2022-05-02 <axel.hahn@iml.unibe.ch> set warning to 21 days (old value was 30); add "critical" param * 2022-05-02 <axel.hahn@iml.unibe.ch> set warning to 21 days (old value was 30); add "critical" param
* 2022-05-03 <axel.hahn@iml.unibe.ch> critical limit is a warning only (because app is still functional) * 2022-05-03 <axel.hahn@iml.unibe.ch> critical limit is a warning only (because app is still functional)
* 2024-07-23 <axel.hahn@unibe.ch> php 8 only: use typed variables
* *
*/ */
class checkCert extends appmonitorcheck{ class checkCert extends appmonitorcheck
{
/** /**
* get default group of this check * Get default group of this check
* @param array $aParams * @return string
* @return array
*/ */
public function getGroup(){ public function getGroup(): string
{
return 'security'; return 'security';
} }
/** /**
* check SSL certificate * Check SSL certificate
* @param array $aParams * @param array $aParams
* [ * [
* "url" optional: url to connect check; default: own protocol + server * "url" optional: url to connect check; default: own protocol + server
...@@ -60,13 +62,11 @@ class checkCert extends appmonitorcheck{ ...@@ -60,13 +62,11 @@ class checkCert extends appmonitorcheck{
* "warning" optional: count of days to warn; default=21 (=3 weeks) * "warning" optional: count of days to warn; default=21 (=3 weeks)
* "critical" optional: count of days to raise critical; default=5 * "critical" optional: count of days to raise critical; default=5
* ] * ]
* @return boolean * @return array
*/ */
public function run($aParams) { public function run(array $aParams): array
$sUrl = isset($aParams["url"]) {
? $aParams["url"] $sUrl = $aParams["url"] ?? 'http' . ($_SERVER['HTTPS'] ? 's' : '') . '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'];
: 'http'. ($_SERVER['HTTPS'] ? 's' : '') . '://' . $_SERVER['SERVER_NAME'] .':' . $_SERVER['SERVER_PORT']
;
$bVerify = isset($aParams["verify"]) ? !!$aParams["verify"] : true; $bVerify = isset($aParams["verify"]) ? !!$aParams["verify"] : true;
$iWarn = isset($aParams["warning"]) ? (int) ($aParams["warning"]) : 21; $iWarn = isset($aParams["warning"]) ? (int) ($aParams["warning"]) : 21;
$iCrtitcal = isset($aParams["critical"]) ? (int) ($aParams["critical"]) : 5; $iCrtitcal = isset($aParams["critical"]) ? (int) ($aParams["critical"]) : 5;
...@@ -80,17 +80,17 @@ class checkCert extends appmonitorcheck{ ...@@ -80,17 +80,17 @@ class checkCert extends appmonitorcheck{
]; ];
} }
$sDNS=isset($certinfo['extensions']['subjectAltName']) ? $certinfo['extensions']['subjectAltName'] : false; $sDNS = $certinfo['extensions']['subjectAltName'] ?? false;
$sHost = parse_url($sUrl, PHP_URL_HOST); $sHost = parse_url($sUrl, PHP_URL_HOST);
if(strstr($sDNS, 'DNS:'.$sHost)===false){ if (strstr($sDNS, "DNS:$sHost") === false) {
return [ return [
RESULT_ERROR, RESULT_ERROR,
'Wrong certificate: '.$sHost.' is not listed as DNS alias in ['.$sDNS.'] ' . $sMessage "Wrong certificate: $sHost is not listed as DNS alias in [$sDNS]. $sMessage"
]; ];
} }
$iDaysleft = round(($certinfo['validTo_time_t'] - date('U')) / 60 / 60 / 24); $iDaysleft = round(($certinfo['validTo_time_t'] - date('U')) / 60 / 60 / 24);
$sMessage.= 'Issuer: '. $sIssuer=$certinfo['issuer']['O'] $sMessage .= 'Issuer: ' . $certinfo['issuer']['O']
. '; valid from: ' . date("Y-m-d H:i", $certinfo['validFrom_time_t']) . '; valid from: ' . date("Y-m-d H:i", $certinfo['validFrom_time_t'])
. ' to ' . date("Y-m-d H:i", $certinfo['validTo_time_t']) . ' ' . ' to ' . date("Y-m-d H:i", $certinfo['validTo_time_t']) . ' '
. ($iDaysleft ? "($iDaysleft days left)" : "expired since " . (-$iDaysleft) . " days.") . ($iDaysleft ? "($iDaysleft days left)" : "expired since " . (-$iDaysleft) . " days.")
......
...@@ -18,36 +18,39 @@ ...@@ -18,36 +18,39 @@
* ____________________________________________________________________________ * ____________________________________________________________________________
* *
* 2021-10-26 <axel.hahn@iml.unibe.ch> * 2021-10-26 <axel.hahn@iml.unibe.ch>
* 2024-07-23 <axel.hahn@unibe.ch> php 8 only: use typed variables
* *
*/ */
class checkDiskfree extends appmonitorcheck{ class checkDiskfree extends appmonitorcheck
{
/** /**
* get default group of this check * Get default group of this check
* @param array $aParams * @return string
* @return array
*/ */
public function getGroup(){ public function getGroup(): string
{
return 'disk'; return 'disk';
} }
/** /**
* check free disk space on a given directory * Check free disk space on a given directory
* @param array $aParams * @param array $aParams
* [ * [
* "directory" directory that must exist * "directory" directory that must exist
* "warning" space for warning (optional) * "warning" space for warning (optional)
* "critical" minimal space * "critical" minimal space
* ] * ]
* @return boolean * @return array
*/ */
public function run($aParams) { public function run(array $aParams): array
$this->_checkArrayKeys($aParams, "directory", "critical"); {
$this->_checkArrayKeys($aParams, "directory,critical");
$sDirectory = $aParams["directory"]; $sDirectory = $aParams["directory"];
if (!is_dir($sDirectory)) { if (!is_dir($sDirectory)) {
return [ return [
RESULT_ERROR, RESULT_ERROR,
'directory [' . $sDirectory . '] does not exist. Maybe it is wrong or is not mounted.' "directory [$sDirectory] does not exist. Maybe it is wrong or is not mounted."
]; ];
} }
...@@ -55,7 +58,6 @@ class checkDiskfree extends appmonitorcheck{ ...@@ -55,7 +58,6 @@ class checkDiskfree extends appmonitorcheck{
$iCritical = $this->_getSize($aParams["critical"]); $iCritical = $this->_getSize($aParams["critical"]);
$iSpaceLeft = disk_free_space($sDirectory); $iSpaceLeft = disk_free_space($sDirectory);
$sMessage = '[' . $sDirectory . '] has ' . $this->_getHrSize($iSpaceLeft) . ' left.'; $sMessage = '[' . $sDirectory . '] has ' . $this->_getHrSize($iSpaceLeft) . ' left.';
if ($iWarn) { if ($iWarn) {
...@@ -66,7 +68,7 @@ class checkDiskfree extends appmonitorcheck{ ...@@ -66,7 +68,7 @@ class checkDiskfree extends appmonitorcheck{
if ($iWarn < $iSpaceLeft) { if ($iWarn < $iSpaceLeft) {
return [ return [
RESULT_OK, RESULT_OK,
$sMessage.' Warning level is not reached yet (still '.$this->_getHrSize($iSpaceLeft-$iWarn).' over warning limit).' "$sMessage Warning level is not reached yet (still " . $this->_getHrSize($iSpaceLeft - $iWarn) . "over warning limit)."
]; ];
} }
if ($iWarn > $iSpaceLeft && $iCritical < $iSpaceLeft) { if ($iWarn > $iSpaceLeft && $iCritical < $iSpaceLeft) {
......
...@@ -20,20 +20,22 @@ ...@@ -20,20 +20,22 @@
* ____________________________________________________________________________ * ____________________________________________________________________________
* *
* 2022-09-19 <axel.hahn@iml.unibe.ch> * 2022-09-19 <axel.hahn@iml.unibe.ch>
* 2024-07-23 <axel.hahn@unibe.ch> php 8 only: use typed variables
* *
*/ */
class checkExec extends appmonitorcheck{ class checkExec extends appmonitorcheck
{
/** /**
* get default group of this check * Get default group of this check
* @param array $aParams - see run() method * @return string
* @return array
*/ */
public function getGroup($aParams){ public function getGroup()
{
return 'service'; return 'service';
} }
/** /**
* check execution of a command * Check execution of a command
* @param array $aParams * @param array $aParams
* [ * [
* "command" {string} command to execute * "command" {string} command to execute
...@@ -48,9 +50,10 @@ class checkExec extends appmonitorcheck{ ...@@ -48,9 +50,10 @@ class checkExec extends appmonitorcheck{
* "searchWarn" {string} if search string is found check returns with warning * "searchWarn" {string} if search string is found check returns with warning
* "searchCritical" {string} if search string is found check returns with critical * "searchCritical" {string} if search string is found check returns with critical
* ] * ]
* @return boolean * @return array
*/ */
public function run($aParams) { public function run(array $aParams): array
{
$this->_checkArrayKeys($aParams, "command"); $this->_checkArrayKeys($aParams, "command");
$_sCmd = $aParams['command']; $_sCmd = $aParams['command'];
$_bShowOutput = isset($aParams['output']) ? !!$aParams['output'] : true; $_bShowOutput = isset($aParams['output']) ? !!$aParams['output'] : true;
...@@ -78,41 +81,44 @@ class checkExec extends appmonitorcheck{ ...@@ -78,41 +81,44 @@ class checkExec extends appmonitorcheck{
} else { } else {
return [ return [
RESULT_OK, RESULT_OK,
'OK [' . $_sCmd . '] ' .$_sOut "OK [$_sCmd] $_sOut"
]; ];
}; }
break;; ;
// break;
;
// handle given custom exitcodes // handle given custom exitcodes
case "exitcode": case "exitcode":
if (in_array($iRc, $_aRcCritical)) { if (in_array($iRc, $_aRcCritical)) {
return [ return [
RESULT_ERROR, RESULT_ERROR,
'Critical exitcode '.$iRc.' detected: [' . $_sCmd . ']'.$_sOut "Critical exitcode $iRc detected: [$_sCmd] $_sOut"
]; ];
} }
if (in_array($iRc, $_aRcWarning)) { if (in_array($iRc, $_aRcWarning)) {
return [ return [
RESULT_WARNING, RESULT_WARNING,
'Warning exitcode '.$iRc.' detected: [' . $_sCmd . ']'.$_sOut "Warning exitcode $iRc detected: [$_sCmd] $_sOut"
]; ];
} }
if ($iRc == 0 || in_array($iRc, $_aRcOK)) { if ($iRc == 0 || in_array($iRc, $_aRcOK)) {
return [ return [
RESULT_OK, RESULT_OK,
'OK exitcode '.$iRc.' detected: [' . $_sCmd . ']'.$_sOut "OK exitcode $iRc detected: [$_sCmd] $_sOut"
]; ];
} }
return [ return [
RESULT_UNKNOWN, RESULT_UNKNOWN,
'UNKNOWN - unhandled exitcode '.$iRc.' detected: [' . $_sCmd . ']'.$_sOut "UNKNOWN - unhandled exitcode $iRc detected: [$_sCmd] $_sOut"
]; ];
case "search": case "search":
return [ return [
RESULT_UNKNOWN, RESULT_UNKNOWN,
'UNKNOWN method [' . $_sMode . '] - is not implemented yet.' "UNKNOWN method [$_sMode] - is not implemented yet."
]; ];
break;; // break;
;
default: default:
return [ return [
RESULT_UNKNOWN, RESULT_UNKNOWN,
......
...@@ -21,15 +21,17 @@ ...@@ -21,15 +21,17 @@
* ____________________________________________________________________________ * ____________________________________________________________________________
* *
* 2021-10-26 <axel.hahn@iml.unibe.ch> * 2021-10-26 <axel.hahn@iml.unibe.ch>
* * 2024-07-23 <axel.hahn@unibe.ch> php 8 only: use typed variables
*/ */
class checkFile extends appmonitorcheck{ class checkFile extends appmonitorcheck
{
/** /**
* get default group of this check * Get default group of this check
* @param array $aParams - see run() method * @param array $aParams - see run() method
* @return array * @return string
*/ */
public function getGroup($aParams){ public function getGroup(array $aParams = []): string
{
$sReturn = 'file'; $sReturn = 'file';
if (isset($aParams['dir'])) { if (isset($aParams['dir'])) {
$sReturn = 'folder'; $sReturn = 'folder';
...@@ -43,7 +45,7 @@ class checkFile extends appmonitorcheck{ ...@@ -43,7 +45,7 @@ class checkFile extends appmonitorcheck{
} }
/** /**
* check a file * Check a file
* @param array $aParams * @param array $aParams
* [ * [
* "filename" directory that must exist * "filename" directory that must exist
...@@ -55,9 +57,10 @@ class checkFile extends appmonitorcheck{ ...@@ -55,9 +57,10 @@ class checkFile extends appmonitorcheck{
* "readable" flag is readable * "readable" flag is readable
* "writable" flag is writable * "writable" flag is writable
* ] * ]
* @return boolean * @return array
*/ */
public function run($aParams) { public function run(array $aParams): array
{
$aOK = []; $aOK = [];
$aErrors = []; $aErrors = [];
$this->_checkArrayKeys($aParams, "filename"); $this->_checkArrayKeys($aParams, "filename");
...@@ -87,11 +90,12 @@ class checkFile extends appmonitorcheck{ ...@@ -87,11 +90,12 @@ class checkFile extends appmonitorcheck{
if (count($aErrors)) { if (count($aErrors)) {
return [ return [
RESULT_ERROR, RESULT_ERROR,
'file test [' . $sFile . '] ' . $sMessage "file test [$sFile] $sMessage"
]; ];
} else { } else {
return [ return [
RESULT_OK, 'file test [' . $sFile . '] ' . $sMessage RESULT_OK,
"file test [$sFile] $sMessage"
]; ];
} }
} }
......
...@@ -40,16 +40,19 @@ ...@@ -40,16 +40,19 @@
* ____________________________________________________________________________ * ____________________________________________________________________________
* *
* 2019-06-05 <axel.hahn@iml.unibe.ch> * 2019-06-05 <axel.hahn@iml.unibe.ch>
* 2024-07-23 <axel.hahn@unibe.ch> php 8 only: use typed variables
* *
*/ */
class checkHello extends appmonitorcheck{ class checkHello extends appmonitorcheck
{
/** /**
* * Run the check
* @param array $aParams * @param array $aParams
* @return array * @return array
*/ */
public function run($aParams){ public function run(array $aParams): array
{
// --- (1) verify if array key(s) exist: // --- (1) verify if array key(s) exist:
$this->_checkArrayKeys($aParams, "message"); $this->_checkArrayKeys($aParams, "message");
......
...@@ -20,15 +20,20 @@ ...@@ -20,15 +20,20 @@
* 2021-10-26 <axel.hahn@iml.unibe.ch> * 2021-10-26 <axel.hahn@iml.unibe.ch>
* 2022-12-21 <axel.hahn@unibe.ch> add flag sslverify * 2022-12-21 <axel.hahn@unibe.ch> add flag sslverify
* 2023-07-06 <axel.hahn@unibe.ch> add flag userpwd * 2023-07-06 <axel.hahn@unibe.ch> add flag userpwd
* 2024-07-23 <axel.hahn@unibe.ch> php 8 only: use typed variables
* *
*/ */
class checkHttpContent extends appmonitorcheck{ class checkHttpContent extends appmonitorcheck
{
/** /**
* get default group of this check * Get default group of this check
* @param array $aParams * It is a "service" icon or "deny" for expected failures
* @return array *
* @param array $aParams with optional 'status' containing http response code
* @return string
*/ */
public function getGroup($aParams){ public function getGroup(array $aParams=[]): string
{
$sReturn = 'service'; $sReturn = 'service';
if (isset($aParams['status']) && $aParams['status'] > 300 && $aParams['status'] < 500) { if (isset($aParams['status']) && $aParams['status'] > 300 && $aParams['status'] < 500) {
$sReturn = 'deny'; $sReturn = 'deny';
...@@ -37,7 +42,7 @@ class checkHttpContent extends appmonitorcheck{ ...@@ -37,7 +42,7 @@ class checkHttpContent extends appmonitorcheck{
} }
/** /**
* make http request and test response body * Make http request and test response header + body
* @param array $aParams * @param array $aParams
* [ * [
* url string url to fetch * url string url to fetch
...@@ -46,16 +51,20 @@ class checkHttpContent extends appmonitorcheck{ ...@@ -46,16 +51,20 @@ class checkHttpContent extends appmonitorcheck{
* headeronly boolean optional flag to fetch http response herader only; default: false = returns header and body * headeronly boolean optional flag to fetch http response herader only; default: false = returns header and body
* follow boolean optional flag to follow a location; default: false = do not follow * follow boolean optional flag to follow a location; default: false = do not follow
* sslverify boolean flag: enable/ disable verification of ssl certificate; default: true (verification is on) * sslverify boolean flag: enable/ disable verification of ssl certificate; default: true (verification is on)
*
* status integer test for an expected http status code; if none is given then test fails on status 400 and greater * status integer test for an expected http status code; if none is given then test fails on status 400 and greater
*
* headercontains string test for a string in the http response header; it returns OK if the text was found * headercontains string test for a string in the http response header; it returns OK if the text was found
* headernotcontains string test for a string in the http response header; it returns OK if the text was not found * headernotcontains string test for a string in the http response header; it returns OK if the text was not found
* headerregex string test for a regex in the http response header; it returns OK if the regex matches; example: "headerregex"=>"/lowercasematch/i" * headerregex string test for a regex in the http response header; it returns OK if the regex matches; example: "headerregex"=>"/lowercasematch/i"
*
* bodycontains string test for a string in the http response body; it returns OK if the text was found * bodycontains string test for a string in the http response body; it returns OK if the text was found
* bodynotcontains string test for a string in the http response body; it returns OK if the text was not found * bodynotcontains string test for a string in the http response body; it returns OK if the text was not found
* bodyregex string test for a regex in the http response body; it returns OK if the regex matches; example: "headerregex"=>"/lowercasematch/i" * bodyregex string test for a regex in the http response body; it returns OK if the regex matches; example: "headerregex"=>"/lowercasematch/i"
* ] * ]
*/ */
public function run($aParams) { public function run(array $aParams)
{
$this->_checkArrayKeys($aParams, "url"); $this->_checkArrayKeys($aParams, "url");
if (!function_exists("curl_init")) { if (!function_exists("curl_init")) {
header('HTTP/1.0 503 Service Unavailable'); header('HTTP/1.0 503 Service Unavailable');
...@@ -81,7 +90,8 @@ class checkHttpContent extends appmonitorcheck{ ...@@ -81,7 +90,8 @@ class checkHttpContent extends appmonitorcheck{
$sErrorMsg = curl_error($ch); $sErrorMsg = curl_error($ch);
curl_close($ch); curl_close($ch);
return [ return [
RESULT_ERROR, 'ERROR: failed to fetch ' . $aParams["url"] . ' - curl error #'.$iErrorCode.': '.$sErrorMsg RESULT_ERROR,
'ERROR: failed to fetch ' . $aParams["url"] . ' - curl error #' . $iErrorCode . ': ' . $sErrorMsg
]; ];
} }
$sOut = ''; $sOut = '';
...@@ -127,7 +137,7 @@ class checkHttpContent extends appmonitorcheck{ ...@@ -127,7 +137,7 @@ class checkHttpContent extends appmonitorcheck{
$aTmp = explode("\r\n\r\n", $res, 2); $aTmp = explode("\r\n\r\n", $res, 2);
$sHttpHeader = $aTmp[0]; $sHttpHeader = $aTmp[0];
$sHttpBody=isset($aTmp[1]) ? $aTmp[1] : false; $sHttpBody = $aTmp[1] ?? false;
// ---------- check functions // ---------- check functions
...@@ -177,8 +187,7 @@ class checkHttpContent extends appmonitorcheck{ ...@@ -177,8 +187,7 @@ class checkHttpContent extends appmonitorcheck{
$sOut .= "compare failed<br>"; $sOut .= "compare failed<br>";
$bError = true; $bError = true;
} }
} } catch (Exception $e) {
catch(Exception $e){
$sOut .= "Wrong REGEX<br>" . print_r($e, 1) . '<br>'; $sOut .= "Wrong REGEX<br>" . print_r($e, 1) . '<br>';
$bError = true; $bError = true;
} }
...@@ -212,8 +221,7 @@ class checkHttpContent extends appmonitorcheck{ ...@@ -212,8 +221,7 @@ class checkHttpContent extends appmonitorcheck{
$sOut .= "compare failed<br>"; $sOut .= "compare failed<br>";
$bError = true; $bError = true;
} }
} } catch (Exception $e) {
catch(Exception $e){
$sOut .= "Wrong REGEX<br>" . print_r($e, 1) . '<br>'; $sOut .= "Wrong REGEX<br>" . print_r($e, 1) . '<br>';
$bError = true; $bError = true;
} }
......
...@@ -43,24 +43,28 @@ ...@@ -43,24 +43,28 @@
* ____________________________________________________________________________ * ____________________________________________________________________________
* *
* 2019-06-06 <axel.hahn@iml.unibe.ch> * 2019-06-06 <axel.hahn@iml.unibe.ch>
* 2024-07-23 <axel.hahn@unibe.ch> php 8 only: use typed variables
* 2024-07-25 <axel.hahn@unibe.ch> float return with 2 digits behind comma
* *
*/ */
class checkLoadmeter extends appmonitorcheck{ class checkLoadmeter extends appmonitorcheck
{
/** /**
* get default group of this check * Get default group of this check
* @param array $aParams * @return string
* @return array
*/ */
public function getGroup(){ public function getGroup(): string
{
return 'monitor'; return 'monitor';
} }
/** /**
* detect load of a machine and return a float value * Detect load of a machine and return a float value
* windows part was taken from https://stackoverflow.com/questions/5588616/how-do-you-calculate-server-load-in-php * windows part was taken from https://stackoverflow.com/questions/5588616/how-do-you-calculate-server-load-in-php
* @return float * @return float
*/ */
protected function _getLoad() { protected function _getLoad(): float
{
if (function_exists('sys_getloadavg')) { if (function_exists('sys_getloadavg')) {
$load = sys_getloadavg(); $load = sys_getloadavg();
return $load[0]; return $load[0];
...@@ -87,16 +91,16 @@ class checkLoadmeter extends appmonitorcheck{ ...@@ -87,16 +91,16 @@ class checkLoadmeter extends appmonitorcheck{
} }
/** /**
* * Run the check and get load
* @param array $aParams * @param array $aParams optional array with keys warning,error
* @return array * @return array
*/ */
public function run($aParams){ public function run(array $aParams): array
{
// --- (1) verify if array key(s) exist: // --- (1) verify if array key(s) exist:
// $this->_checkArrayKeys($aParams, "..."); // $this->_checkArrayKeys($aParams, "...");
// --- (2) do something magic // --- (2) do something magic
// $fLoad=rand(0, 1.3); // $fLoad=rand(0, 1.3);
// $fLoad=$this->_getServerLoad(); // $fLoad=$this->_getServerLoad();
...@@ -129,12 +133,12 @@ class checkLoadmeter extends appmonitorcheck{ ...@@ -129,12 +133,12 @@ class checkLoadmeter extends appmonitorcheck{
// //
return [ return [
$iResult, $iResult,
($fLoad===false ? 'load value is not available' : 'current load is: '.$fLoad), ($fLoad === false ? 'load value is not available' : 'current load is: ' . round($fLoad, 2)),
($fLoad === false ($fLoad === false
? [] ? []
: [ : [
'type' => 'counter', 'type' => 'counter',
'count'=>$fLoad, 'count' => round($fLoad, 2),
'visual' => 'line', 'visual' => 'line',
] ]
) )
......
...@@ -18,19 +18,22 @@ ...@@ -18,19 +18,22 @@
* ____________________________________________________________________________ * ____________________________________________________________________________
* *
* 2021-10-27 <axel.hahn@iml.unibe.ch> * 2021-10-27 <axel.hahn@iml.unibe.ch>
* 2024-07-23 <axel.hahn@unibe.ch> php 8 only: use typed variables
* *
*/ */
class checkMysqlConnect extends appmonitorcheck{ class checkMysqlConnect extends appmonitorcheck
{
/** /**
* get default group of this check * Get default group of this check
* @param array $aParams * @return string
* @return array
*/ */
public function getGroup(){ public function getGroup(): string
{
return 'database'; return 'database';
} }
/** /**
* check mysql connection to a database using mysqli realconnect * Check mysql connection to a database using mysqli realconnect
* @param array $aParams * @param array $aParams
* [ * [
* server string database hostname / ip address * server string database hostname / ip address
...@@ -40,8 +43,10 @@ class checkMysqlConnect extends appmonitorcheck{ ...@@ -40,8 +43,10 @@ class checkMysqlConnect extends appmonitorcheck{
* port integer optional: port * port integer optional: port
* timeout integer optional timeout in sec; default: 5 * timeout integer optional timeout in sec; default: 5
* ] * ]
* @return array
*/ */
public function run($aParams) { public function run(array $aParams): array
{
$this->_checkArrayKeys($aParams, "server,user,password,db"); $this->_checkArrayKeys($aParams, "server,user,password,db");
$mysqli = mysqli_init(); $mysqli = mysqli_init();
if (!$mysqli) { if (!$mysqli) {
...@@ -58,7 +63,6 @@ class checkMysqlConnect extends appmonitorcheck{ ...@@ -58,7 +63,6 @@ class checkMysqlConnect extends appmonitorcheck{
if ($db) { if ($db) {
$mysqli->close(); $mysqli->close();
return [RESULT_OK, "OK: Mysql database " . $aParams["db"] . " was connected"]; return [RESULT_OK, "OK: Mysql database " . $aParams["db"] . " was connected"];
return true;
} else { } else {
return [ return [
RESULT_ERROR, RESULT_ERROR,
......
...@@ -18,19 +18,21 @@ ...@@ -18,19 +18,21 @@
* ____________________________________________________________________________ * ____________________________________________________________________________
* *
* 2021-10-27 <axel.hahn@iml.unibe.ch> * 2021-10-27 <axel.hahn@iml.unibe.ch>
* 2024-07-23 <axel.hahn@unibe.ch> php 8 only: use typed variables
* *
*/ */
class checkPdoConnect extends appmonitorcheck{ class checkPdoConnect extends appmonitorcheck
{
/** /**
* get default group of this check * Get default group of this check
* @param array $aParams * @return string
* @return array
*/ */
public function getGroup(){ public function getGroup(): string
{
return 'database'; return 'database';
} }
/** /**
* check connection to a database using pdo * Check connection to a database using pdo
* see http://php.net/manual/en/pdo.drivers.php * see http://php.net/manual/en/pdo.drivers.php
* *
* @param array $aParams * @param array $aParams
...@@ -40,8 +42,10 @@ class checkPdoConnect extends appmonitorcheck{ ...@@ -40,8 +42,10 @@ class checkPdoConnect extends appmonitorcheck{
* password string password for db user * password string password for db user
* timeout integer optional timeout in sec; default: 5 * timeout integer optional timeout in sec; default: 5
* ] * ]
* @return array
*/ */
public function run($aParams) { public function run(array $aParams): array
{
$this->_checkArrayKeys($aParams, "connect,user,password"); $this->_checkArrayKeys($aParams, "connect,user,password");
try { try {
......
...@@ -18,28 +18,31 @@ ...@@ -18,28 +18,31 @@
* ____________________________________________________________________________ * ____________________________________________________________________________
* *
* 2022-05-06 <axel.hahn@iml.unibe.ch> first lines * 2022-05-06 <axel.hahn@iml.unibe.ch> first lines
* 2024-07-23 <axel.hahn@unibe.ch> php 8 only: use typed variables
* *
*/ */
class checkPhpmodules extends appmonitorcheck{ class checkPhpmodules extends appmonitorcheck
{
/** /**
* get default group of this check * Get default group of this check
* @param array $aParams * @return string
* @return array
*/ */
public function getGroup(){ public function getGroup(): string
{
return 'service'; return 'service';
} }
/** /**
* check if system is listening to a given port * Check if system is listening to a given port
* @param array $aParams * @param array $aParams
* [ * [
* required array list of required php modules * required array list of required php modules
* optional array optional: list of optional php modules * optional array optional: list of optional php modules
* ] * ]
* @return boolean * @return array
*/ */
public function run($aParams) { public function run(array $aParams): array
{
$sOut = ''; $sOut = '';
$bHasError = false; $bHasError = false;
$bHasWarning = false; $bHasWarning = false;
......
...@@ -20,27 +20,30 @@ ...@@ -20,27 +20,30 @@
* 2022-07-05 <axel.hahn@iml.unibe.ch> * 2022-07-05 <axel.hahn@iml.unibe.ch>
* 2022-09-16 <axel.hahn@iml.unibe.ch> read error before closing socket. * 2022-09-16 <axel.hahn@iml.unibe.ch> read error before closing socket.
* 2022-11-22 <axel.hahn@iml.unibe.ch> Use exec with detecting MS Win for the ping parameter for count of pings * 2022-11-22 <axel.hahn@iml.unibe.ch> Use exec with detecting MS Win for the ping parameter for count of pings
* 2024-07-23 <axel.hahn@unibe.ch> php 8 only: use typed variables
*/ */
class checkPing extends appmonitorcheck{ class checkPing extends appmonitorcheck
{
/** /**
* get default group of this check * Get default group of this check
* @param array $aParams * @return string
* @return array
*/ */
public function getGroup(){ public function getGroup(): string
{
return 'network'; return 'network';
} }
/** /**
* check ping to a target * Check ping to a target
* @param array $aParams * @param array $aParams
* [ * [
* host string optional hostname to connect; default: 127.0.0.1 * host string optional hostname to connect; default: 127.0.0.1
* timeout integer OBSOLET (because using exec): optional timeout in sec; default: 5 * timeout integer OBSOLET (because using exec): optional timeout in sec; default: 5
* ] * ]
* @return boolean * @return array
*/ */
public function run($aParams) { public function run(array $aParams): array
{
$sHost = $aParams['host'] ?? '127.0.0.1'; $sHost = $aParams['host'] ?? '127.0.0.1';
$sParamCount = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? "n" : "c"; $sParamCount = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? "n" : "c";
......
...@@ -21,36 +21,39 @@ ...@@ -21,36 +21,39 @@
* 2022-07-05 <axel.hahn@iml.unibe.ch> send unknown if socket module is not activated. * 2022-07-05 <axel.hahn@iml.unibe.ch> send unknown if socket module is not activated.
* 2022-09-16 <axel.hahn@iml.unibe.ch> read error before closing socket. * 2022-09-16 <axel.hahn@iml.unibe.ch> read error before closing socket.
* 2022-12-05 <axel.hahn@unibe.ch> add @ sign at socket functions to prevent warning * 2022-12-05 <axel.hahn@unibe.ch> add @ sign at socket functions to prevent warning
* 2024-07-23 <axel.hahn@unibe.ch> php 8 only: use typed variables
* *
*/ */
class checkPortTcp extends appmonitorcheck{ class checkPortTcp extends appmonitorcheck
{
/** /**
* get default group of this check * Get default group of this check
* @param array $aParams * @return string
* @return array
*/ */
public function getGroup(){ public function getGroup(): string
{
return 'network'; return 'network';
} }
/** /**
* check if system is listening to a given port * Check if system is listening to a given port
* @param array $aParams * @param array $aParams
* [ * [
* port integer port * port integer port
* host string optional hostname to connect; default: 127.0.0.1 * host string optional hostname to connect; default: 127.0.0.1
* timeout integer optional timeout in sec; default: 5 * timeout integer optional timeout in sec; default: 5
* ] * ]
* @return boolean * @return array
*/ */
public function run($aParams) { public function run(array $aParams): array
{
$this->_checkArrayKeys($aParams, "port"); $this->_checkArrayKeys($aParams, "port");
$sHost = $aParams['host'] ?? '127.0.0.1'; $sHost = $aParams['host'] ?? '127.0.0.1';
$iPort = (int) $aParams['port']; $iPort = (int) $aParams['port'];
if (!function_exists('socket_create')) { if (!function_exists('socket_create')) {
return [RESULT_UNKNOWN, "UNKNOWN: Unable to perform tcp test. The socket module is not enabled in the php installation."]; return [RESULT_UNKNOWN, "UNKNOWN: Unable to perform tcp test. The php-sockets module is not enabled in the php installation."];
} }
// from http://php.net/manual/de/sockets.examples.php // from http://php.net/manual/de/sockets.examples.php
......
...@@ -18,12 +18,14 @@ ...@@ -18,12 +18,14 @@
* ____________________________________________________________________________ * ____________________________________________________________________________
* *
* 2021-10-27 <axel.hahn@iml.unibe.ch> * 2021-10-27 <axel.hahn@iml.unibe.ch>
* 2024-07-23 <axel.hahn@unibe.ch> php 8 only: use typed variables
* *
*/ */
class checkSimple extends appmonitorcheck{ class checkSimple extends appmonitorcheck
{
/** /**
* most simple check: set given values * Most simple check: set given values
* Use this function to add a counter * Use this function to add a counter
* *
* @param array $aParams * @param array $aParams
...@@ -37,9 +39,10 @@ class checkSimple extends appmonitorcheck{ ...@@ -37,9 +39,10 @@ class checkSimple extends appmonitorcheck{
* - label string a label * - label string a label
* - value float a number * - value float a number
* - type string one of simple | bar | line * - type string one of simple | bar | line
* * @return array
*/ */
public function run($aParams) { public function run(array $aParams): array
{
$this->_checkArrayKeys($aParams, "result,value"); $this->_checkArrayKeys($aParams, "result,value");
// $this->_setReturn((int) $aParams["result"], $aParams["value"]); // $this->_setReturn((int) $aParams["result"], $aParams["value"]);
$aData = []; $aData = [];
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment