diff --git a/.travis.yml b/.travis.yml index 3003447..789f8ce 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,4 +12,4 @@ before_script: - composer install -n script: - - composer test + - vendor/bin/phpunit diff --git a/README.md b/README.md index 7155a9f..e820906 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ To get started, you will first need to have Monit installed with HTTP access ena 2. Add `config/servers.ini` (you can use [`servers.template.ini`](config/servers.template.ini)) 3. Set up a crontab job to run cron every minute: ```cron - * * * * * cd /path/to/monit-graph && composer cron >> /var/log/monit-graph.log + * * * * * cd /path/to/monit-graph && php src/scripts/cron.php >> /var/log/monit-graph.log ``` 4. Start server: ```bash diff --git a/composer.json b/composer.json index a9c93e2..615d84d 100644 --- a/composer.json +++ b/composer.json @@ -5,14 +5,15 @@ "keywords": ["monit", "graph"], "license": "BSD 3-clause", "require": { - "php": ">=5.5.0", + "php": ">=5.6.0", "slim/slim": "^3.1", "slim/php-view": "^2.0", "monolog/monolog": "^1.17", "tuupola/slim-basic-auth": "^2.2" }, "require-dev": { - "phpunit/phpunit": ">=4.8 < 6.0" + "phpunit/phpunit": ">=4.8", + "squizlabs/php_codesniffer": "^2.5" }, "authors": [ { @@ -20,16 +21,21 @@ "email": "dan@dreamconception.com" } ], - "autoload-dev": { + "autoload": { "psr-4": { - "Tests\\": "tests/" + "MonitGraph\\": "src/MonitGraph" } }, "scripts": { - "server": "php -S 0.0.0.0:8080 -t web/public web/public/index.php", - "test": "phpunit", - "cron": "php src/cron.php", - "build-massive-data": "php tests/utils/build_massive_data.php", - "reverse-xml": "php src/reverse_xml.php" + "server": "php -S 0.0.0.0:8080 -t src/web/public src/web/public/index.php", + "cron": "php src/scripts/cron.php", + "build-massive-data": "php tests/scripts/build_massive_data.php", + "reverse-xml": "php src/scripts/reverse_xml.php", + "test": [ + "@phpunit", + "@phpcs" + ], + "phpunit": "php vendor/bin/phpunit", + "phpcs": "php vendor/bin/phpcs" } } diff --git a/composer.lock b/composer.lock index dd7eb88..17ebffb 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file", "This file is @generated automatically" ], - "content-hash": "bb7c07b964ed6e559118e81e10b2ad69", + "content-hash": "bf41222126a7fd1f55b1e9d394ed7e67", "packages": [ { "name": "container-interop/container-interop", @@ -1729,6 +1729,84 @@ "homepage": "https://github.com/sebastianbergmann/version", "time": "2016-10-03T07:35:21+00:00" }, + { + "name": "squizlabs/php_codesniffer", + "version": "2.8.1", + "source": { + "type": "git", + "url": "https://github.com/squizlabs/PHP_CodeSniffer.git", + "reference": "d7cf0d894e8aa4c73712ee4a331cc1eaa37cdc7d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/d7cf0d894e8aa4c73712ee4a331cc1eaa37cdc7d", + "reference": "d7cf0d894e8aa4c73712ee4a331cc1eaa37cdc7d", + "shasum": "" + }, + "require": { + "ext-simplexml": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": ">=5.1.2" + }, + "require-dev": { + "phpunit/phpunit": "~4.0" + }, + "bin": [ + "scripts/phpcs", + "scripts/phpcbf" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.x-dev" + } + }, + "autoload": { + "classmap": [ + "CodeSniffer.php", + "CodeSniffer/CLI.php", + "CodeSniffer/Exception.php", + "CodeSniffer/File.php", + "CodeSniffer/Fixer.php", + "CodeSniffer/Report.php", + "CodeSniffer/Reporting.php", + "CodeSniffer/Sniff.php", + "CodeSniffer/Tokens.php", + "CodeSniffer/Reports/", + "CodeSniffer/Tokenizers/", + "CodeSniffer/DocGenerators/", + "CodeSniffer/Standards/AbstractPatternSniff.php", + "CodeSniffer/Standards/AbstractScopeSniff.php", + "CodeSniffer/Standards/AbstractVariableSniff.php", + "CodeSniffer/Standards/IncorrectPatternException.php", + "CodeSniffer/Standards/Generic/Sniffs/", + "CodeSniffer/Standards/MySource/Sniffs/", + "CodeSniffer/Standards/PEAR/Sniffs/", + "CodeSniffer/Standards/PSR1/Sniffs/", + "CodeSniffer/Standards/PSR2/Sniffs/", + "CodeSniffer/Standards/Squiz/Sniffs/", + "CodeSniffer/Standards/Zend/Sniffs/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Greg Sherwood", + "role": "lead" + } + ], + "description": "PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.", + "homepage": "http://www.squizlabs.com/php-codesniffer", + "keywords": [ + "phpcs", + "standards" + ], + "time": "2017-03-01T22:17:45+00:00" + }, { "name": "symfony/yaml", "version": "v3.2.7", diff --git a/config/config.default.php b/config/config.default.php index 8df0c1c..856d592 100644 --- a/config/config.default.php +++ b/config/config.default.php @@ -1,29 +1,29 @@ 3600, // Amount in seconds of the default view should be (0 equals all available data) - 'default_chart_type' => "LineChart", // Default chart type - 'default_refresh_seconds' => 120, // Default amount of seconds before data is reloaded (0 equals never) - 'default_specific_service' => "", // Default service to be displayed (none is equal to all services) - 'default_dont_show_alerts' => "on", - 'limit_records_shown' => 750, +return [ + /* Monit-Graph display information */ + 'default_time_range' => 3600, // Amount in seconds of the default view should be (0 equals all available data) + 'default_chart_type' => "LineChart", // Default chart type + 'default_refresh_seconds' => 120, // Default amount of seconds before data is reloaded (0 equals never) + 'default_specific_service' => "", // Default service to be displayed (none is equal to all services) + 'default_dont_show_alerts' => "on", + 'limit_records_shown' => 750, - /* Monit-Graph history handling */ - 'chunk_size' => 1024*1024, // Maximum size in bytes for each service history chunk (0 equals unlimited, remember to set php.ini so the scripts can handle it as well) - 'limit_number_of_chunks' => 14, // Maximum number of chunks saved per service records, will delete all above this (0 equals unlimited) + /* Monit-Graph history handling */ + 'chunk_size' => 1024*1024, // Maximum size in bytes for each service history chunk (0 equals unlimited, remember to set php.ini so the scripts can handle it as well) + 'limit_number_of_chunks' => 14, // Maximum number of chunks saved per service records, will delete all above this (0 equals unlimited) - 'server_configs' => parse_ini_file(__DIR__ . "/servers.ini", true), + 'server_configs' => parse_ini_file(__DIR__ . "/servers.ini", true), - 'slimconfig' => [ - 'displayErrorDetails' => true, // set to false in production - 'addContentLengthHeader' => false, // Allow the web server to send the content-length header - ], + 'slimconfig' => [ + 'displayErrorDetails' => true, // set to false in production + 'addContentLengthHeader' => false, // Allow the web server to send the content-length header + ], - // Basic authentication can be enabled. By default, ADMIN_PASSWORD environment variables - // is used. You can generate your own hashed password by running `htpasswd -nbBC 10 username password` - // 'basic_auth_users' => ['admin' => getenv('ADMIN_PASSWORD')] - ]; + // Basic authentication can be enabled. By default, ADMIN_PASSWORD environment variables + // is used. You can generate your own hashed password by running `htpasswd -nbBC 10 username password` + // 'basic_auth_users' => ['admin' => getenv('ADMIN_PASSWORD')] +]; diff --git a/phpcs.xml b/phpcs.xml new file mode 100644 index 0000000..bb5d3fb --- /dev/null +++ b/phpcs.xml @@ -0,0 +1,18 @@ + + + MonitGraph coding standard + + + + + + + + + + + + config + src + tests + diff --git a/phpunit.xml b/phpunit.xml index ec50e14..7363967 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,7 +1,22 @@ - + + + - - tests + + ./tests/ diff --git a/src/monit_graph.class.php b/src/MonitGraph/Base.php similarity index 78% rename from src/monit_graph.class.php rename to src/MonitGraph/Base.php index 182dc32..910f997 100644 --- a/src/monit_graph.class.php +++ b/src/MonitGraph/Base.php @@ -32,32 +32,34 @@ * @copyright Dan Schultzer */ +namespace MonitGraph; + /** - * Monit Graph class + * Monit Graph base class * */ -class MonitGraph +class Base { /** * Version of MonitGraph */ - const version = '2.0'; + const VERSION = '2.0'; /** * Identifier of MonitGraph */ - const identifier = 'MonitGraph'; + const IDENTIFIER = 'MonitGraph'; /** * Path to data directory */ - const data_path = __DIR__ . '/../data'; + const DATA_PATH = __DIR__ . '/../../data'; /** * Path to data directory */ - const server_xml_file_name = 'server.xml'; + const SERVER_XML_FILE_NAME = 'server.xml'; /** * Configs @@ -66,10 +68,10 @@ public static function config() { if (getenv("CONFIG_FILE")) { $config = require(getenv("CONFIG_FILE")); - } elseif (file_exists(__DIR__ . "/../config/config.php")) { - $config = require(__DIR__ . "/../config/config.php"); + } elseif (file_exists(__DIR__ . "/../../config/config.php")) { + $config = require(__DIR__ . "/../../config/config.php"); } else { - $config = require(__DIR__ . "/../config/config.default.php"); + $config = require(__DIR__ . "/../../config/config.default.php"); } return $config; @@ -78,32 +80,32 @@ public static function config() /** * Get data directory */ - public static function dataDir() - { - if (isset(self::config()['data_dir'])) { - return self::config()['data_dir'] . "/"; - } - - return self::data_path . "/"; + public static function dataDir() + { + if (isset(self::config()['data_dir'])) { + return self::config()['data_dir'] . "/"; } + return self::DATA_PATH . "/"; + } + /** * Testing the server configs */ public static function checkConfig($server_configs) { - $id = array(); - $url = array(); + $id = []; + $url = []; foreach ($server_configs as $config) { $id[] = $config['server_id']; $url[] = $config['config']['url']; } if (count($id) != count(array_unique($id))) { - error_log("[" . self::identifier . "] " . __FILE__ . " line " . __LINE__ . ": ID's in server config needs to be unique"); + error_log("[" . self::IDENTIFIER . "] " . __FILE__ . " line " . __LINE__ . ": ID's in server config needs to be unique"); return false; } if (count($url) != count(array_unique($url))) { - error_log("[" . self::identifier . "] " . __FILE__ . " line " . __LINE__ . ": You should not use the same URL for individual servers"); + error_log("[" . self::IDENTIFIER . "] " . __FILE__ . " line " . __LINE__ . ": You should not use the same URL for individual servers"); return false; } return true; @@ -114,16 +116,18 @@ public static function checkConfig($server_configs) * * Will connect and download data from the monit URL. */ - public static function cron($server_id, - $monit_url, - $monit_uri_xml, - $monit_url_ssl = true, - $monit_http_username = "", - $monit_http_password = "", - $verify_ssl = true, - $chunk_size = 0, - $number_of_chunks = 0) - { + public static function cron( + $server_id, + $monit_url, + $monit_uri_xml, + $monit_url_ssl = true, + $monit_http_username = "", + $monit_http_password = "", + $verify_ssl = true, + $chunk_size = 0, + $number_of_chunks = 0 + ) { + $found_settings = $ssl_on = $http_login = false; if (!($server_id = self::isServerIDValid($server_id))) { @@ -144,14 +148,14 @@ public static function cron($server_id, if ($found_settings) { $time_difference = intval($xml->incarnation)+intval($xml->uptime)+intval($xml->poll)-20-time(); // 20 seconds connection time if ($time_difference>0) { - error_log("[" . self::identifier . "] " . __FILE__ . " line " . __LINE__ . ": Poll time has not been reached (missing $time_difference seconds), waiting for one more cycle"); + error_log("[" . self::IDENTIFIER . "] " . __FILE__ . " line " . __LINE__ . ": Poll time has not been reached (missing $time_difference seconds), waiting for one more cycle"); return false; } } - $headers = array(); + $headers = []; $headers[] = 'Accept: application/xml'; - $user_agent = 'Cron Monit Graph '.(self:: version); + $user_agent = 'Cron Monit Graph '.(self::VERSION); if ($monit_url_ssl) { $url = "https://"; @@ -193,7 +197,7 @@ public static function cron($server_id, curl_close($ch); if ($curl_errno > 0) { - error_log("[" . self::identifier . "] " . __FILE__ . " line " . __LINE__ . ": cURL Error ($curl_errno): $curl_error"); + error_log("[" . self::IDENTIFIER . "] " . __FILE__ . " line " . __LINE__ . ": cURL Error ($curl_errno): $curl_error"); } else { libxml_use_internal_errors(true); if ($xml = simplexml_load_string($data)) { @@ -206,7 +210,7 @@ public static function cron($server_id, } } else { foreach (libxml_get_errors() as $error) { - error_log("[" . self::identifier . "] " . __FILE__ . " line " . __LINE__ . ": " . $error->message); + error_log("[" . self::IDENTIFIER . "] " . __FILE__ . " line " . __LINE__ . ": " . $error->message); } } } @@ -220,7 +224,7 @@ public static function getSettings($server_id) if (!self::settingsWriteable($server_id)) { exit("Cannot write settings"); } - $filename = self::dataDir() . $server_id . "-" . self::server_xml_file_name; + $filename = self::dataDir() . $server_id . "-" . self::SERVER_XML_FILE_NAME; if (file_exists($filename)) { return simplexml_load_string(file_get_contents($filename)); } @@ -235,21 +239,21 @@ public static function putSettings($server_id, $xml) if (!self::settingsWriteable($server_id)) { exit("Cannot write settings"); } - $filename = self::dataDir() . $server_id . "-" . self::server_xml_file_name; + $filename = self::dataDir() . $server_id . "-" . self::SERVER_XML_FILE_NAME; if (!$handle=fopen($filename, 'w')) { - error_log("[" . self::identifier . "] " . __FILE__ . " line " . __LINE__ . ": Cannot open $filename"); + error_log("[" . self::IDENTIFIER . "] " . __FILE__ . " line " . __LINE__ . ": Cannot open $filename"); exit("Cannot open $filename"); } $dom_xml = dom_import_simplexml($xml); - $dom = new DOMDocument('1.0'); + $dom = new \DOMDocument('1.0'); $dom_xml = $dom->importNode($dom_xml, true); $dom_xml = $dom->appendChild($dom_xml); $dom->preserveWhiteSpace = false; $dom->formatOutput = false; if (fwrite($handle, $dom->saveXML()) === false) { fclose($handle); - error_log("[" . self::identifier . "] " . __FILE__ . " line " . __LINE__ . ": Cannot write to $filename"); + error_log("[" . self::IDENTIFIER . "] " . __FILE__ . " line " . __LINE__ . ": Cannot write to $filename"); exit("Cannot write to $filename"); } fclose($handle); @@ -263,7 +267,7 @@ public static function putSettings($server_id, $xml) public static function datapathWriteable() { if (!is_writeable(self::dataDir())) { - error_log("[" . self::identifier . "] " . __FILE__ . " line " . __LINE__ . ": " . self::dataDir() . " is not write-able!"); + error_log("[" . self::IDENTIFIER . "] " . __FILE__ . " line " . __LINE__ . ": " . self::dataDir() . " is not write-able!"); return false; } return true; @@ -277,9 +281,9 @@ public static function settingsWriteable($server_id) if (!self::datapathWriteable()) { return false; } - $filename = self::dataDir() . $server_id . "-" . self::server_xml_file_name; + $filename = self::dataDir() . $server_id . "-" . self::SERVER_XML_FILE_NAME; if (file_exists($filename) && !is_writeable($filename)) { - error_log("[" . self::identifier . "] " . __FILE__ . " line " . __LINE__ . ": " . $filename . " is not write-able!"); + error_log("[" . self::IDENTIFIER . "] " . __FILE__ . " line " . __LINE__ . ": " . $filename . " is not write-able!"); return false; } return true; @@ -296,7 +300,7 @@ public static function writeServiceHistoric($server_id, $xml, $type, $chunk_size exit("Cannot write in data path"); } - $dom = new DOMDocument('1.0'); + $dom = new \DOMDocument('1.0'); $service = $dom->createElement("records"); $attr_name=$dom->createAttribute("name"); $attr_name->value = $name; @@ -370,7 +374,7 @@ public static function writeServiceHistoric($server_id, $xml, $type, $chunk_size } } - $filename = $dir . "/" . $name." . xml"; + $filename = $dir . "/" . $name . ".xml"; if (file_exists($filename)) { if (!self::rotateFiles($filename, $chunk_size, $number_of_chunks)) { exit("Fatal error, could not rotate file $filename"); @@ -386,7 +390,7 @@ public static function writeServiceHistoric($server_id, $xml, $type, $chunk_size } } if (!$handle=fopen($filename, 'w')) { - error_log("[" . self::identifier . "] " . __FILE__ . " line " . __LINE__ . ": Cannot open $filename"); + error_log("[" . self::IDENTIFIER . "] " . __FILE__ . " line " . __LINE__ . ": Cannot open $filename"); exit("Cannot open $filename"); } @@ -394,7 +398,7 @@ public static function writeServiceHistoric($server_id, $xml, $type, $chunk_size $dom->formatOutput = false; if (fwrite($handle, $dom->saveXML()) === false) { fclose($handle); - error_log("[" . self::identifier . "] " . __FILE__ . " line " . __LINE__ . ": Cannot write to $filename"); + error_log("[" . self::IDENTIFIER . "] " . __FILE__ . " line " . __LINE__ . ": Cannot write to $filename"); exit("Cannot write to $filename"); } fclose($handle); @@ -408,39 +412,39 @@ public static function writeServiceHistoric($server_id, $xml, $type, $chunk_size public static function returnGoogleGraphJSON($filename, $time_range, $limit_number_of_items = 0) { if (!file_exists($filename) or !$xml=simplexml_load_string(file_get_contents($filename))) { - error_log("[" . self::identifier . "] " . __FILE__ . " line " . __LINE__ . ": $filename could not be found!"); + error_log("[" . self::IDENTIFIER . "] " . __FILE__ . " line " . __LINE__ . ": $filename could not be found!"); return false; } - $array = array(); + $array = []; if ($xml["type"]=="5") { - $array["cols"]=array( - array("label"=>"Time","type"=>"datetime"), - array("label"=>"CPU Usage","type"=>"number"), - array("label"=>"Memory Usage","type"=>"number"), - array("label"=>"Swap","type"=>"number"), - array("label"=>"Alerts","type"=>"number") - ); + $array["cols"]=[ + ["label"=>"Time","type"=>"datetime"], + ["label"=>"CPU Usage","type"=>"number"], + ["label"=>"Memory Usage","type"=>"number"], + ["label"=>"Swap","type"=>"number"], + ["label"=>"Alerts","type"=>"number"] + ]; } elseif ($xml["type"]=="7") { - $array["cols"]=array( - array("label"=>"Time","type"=>"datetime"), - array("label"=>"Status","type"=>"number"), - array("label"=>"Alerts","type"=>"number") - ); + $array["cols"]=[ + ["label"=>"Time","type"=>"datetime"], + ["label"=>"Status","type"=>"number"], + ["label"=>"Alerts","type"=>"number"] + ]; } else { - $array["cols"]=array( - array("label"=>"Time","type"=>"datetime"), - array("label"=>"CPU Usage","type"=>"number"), - array("label"=>"Memory Usage","type"=>"number"), - array("label"=>"Alerts","type"=>"number") - ); + $array["cols"]=[ + ["label"=>"Time","type"=>"datetime"], + ["label"=>"CPU Usage","type"=>"number"], + ["label"=>"Memory Usage","type"=>"number"], + ["label"=>"Alerts","type"=>"number"] + ]; } - $array["rows"]=array(); + $array["rows"]=[]; $include_file_number = 0; - $allowed_memory = self::let_to_num(ini_get('memory_limit')); - $run_time = self::let_to_num(ini_get('memory_limit')); + $allowed_memory = self::letToNum(ini_get('memory_limit')); + $run_time = self::letToNum(ini_get('memory_limit')); $run_while = true; while ($run_while) { @@ -452,31 +456,31 @@ public static function returnGoogleGraphJSON($filename, $time_range, $limit_numb /* Different setup for different service types */ if ($xml["type"]=="5") { - $array["rows"][]["c"]=array( - array("v"=>"%%new Date(" . (intVal($record['time']) * 1000) . ")%%"), - array("v"=>(float)$record->cpu), - array("v"=>(float)$record->memory), - array("v"=>(float)$record->swap), - array("v"=>(float)$record->alert*100) - ); + $array["rows"][]["c"]=[ + ["v"=>"%%new Date(" . (intVal($record['time']) * 1000) . ")%%"], + ["v"=>(float)$record->cpu], + ["v"=>(float)$record->memory], + ["v"=>(float)$record->swap], + ["v"=>(float)$record->alert*100] + ]; } elseif ($xml["type"]=="7") { - $array["rows"][]["c"]=array( - array("v"=>"%%new Date(" . (intVal($record['time']) * 1000) . ")%%"), - array("v"=>(float)$record->program_status), - array("v"=>(float)$record->alert*100) - ); + $array["rows"][]["c"]=[ + ["v"=>"%%new Date(" . (intVal($record['time']) * 1000) . ")%%"], + ["v"=>(float)$record->program_status], + ["v"=>(float)$record->alert*100] + ]; } else { - $array["rows"][]["c"]=array( - array("v"=>"%%new Date(" . (intVal($record['time']) * 1000) . ")%%"), - array("v"=>(float)$record->cpu), - array("v"=>(float)$record->memory), - array("v"=>(float)$record->alert*100) - ); + $array["rows"][]["c"]=[ + ["v"=>"%%new Date(" . (intVal($record['time']) * 1000) . ")%%"], + ["v"=>(float)$record->cpu], + ["v"=>(float)$record->memory], + ["v"=>(float)$record->alert*100] + ]; } /* Just checking if we reach memory limit and stop when that happens */ if ((memory_get_usage()/$allowed_memory)>0.9) { - error_log("[" . self::identifier . "] " . __FILE__ . " line " . __LINE__ . ": Memory usage is using over 90% (of $allowed_memory) with currently " . count($array["rows"]) . " rows (last record with date of " . date("Y-m-d H:i:s P", intVal($record['time'])) . "). Please increase allowed memory use if you wish parse more data."); + error_log("[" . self::IDENTIFIER . "] " . __FILE__ . " line " . __LINE__ . ": Memory usage is using over 90% (of $allowed_memory) with currently " . count($array["rows"]) . " rows (last record with date of " . date("Y-m-d H:i:s P", intVal($record['time'])) . "). Please increase allowed memory use if you wish parse more data."); $run_while = false; break; } @@ -488,7 +492,7 @@ public static function returnGoogleGraphJSON($filename, $time_range, $limit_numb $xml = null; unset($xml); if (!$xml=simplexml_load_string(file_get_contents($next_file))) { - error_log("[" . self::identifier . "] " . __FILE__ . " line " . __LINE__ . ": " . $next_file . " could not be opened"); + error_log("[" . self::IDENTIFIER . "] " . __FILE__ . " line " . __LINE__ . ": " . $next_file . " could not be opened"); break; } } else { @@ -504,7 +508,7 @@ public static function returnGoogleGraphJSON($filename, $time_range, $limit_numb $number_of_items = count($array["rows"]); if ($limit_number_of_items>0 && $number_of_items>$limit_number_of_items) { $exponent = ceil(log($limit_number_of_items/$number_of_items)/log(0.5)); // Calculating how many iterations we should do until we are below the maximum number of items - for ($i=0;$i<$exponent;$i++) { + for ($i=0; $i<$exponent; $i++) { foreach (range(1, count($array["rows"]), 2) as $key) { // Go through every second element and delete it unset($array["rows"][$key]); } @@ -523,25 +527,25 @@ public static function returnGoogleGraphJSON($filename, $time_range, $limit_numb */ public static function getLastRecord($server_id) { - $files = MonitGraph::getLogFilesForServerID($server_id); + $files = self::getLogFilesForServerID($server_id); if (!$files) { return false; } /* Check the directory for the Monit instance ID */ - $return_array = array(); + $return_array = []; foreach ($files as $file) { if (!file_exists($file) or !$xml=simplexml_load_string(file_get_contents($file))) { - error_log("[".self::identifier."] ".__FILE__." line ".__LINE__.": $filename could not be loaded!"); + error_log("[".self::IDENTIFIER."] ".__FILE__." line ".__LINE__.": $filename could not be loaded!"); return false; } - $return_array[]=array( + $return_array[]=[ "name"=>$xml['name'], "time"=>intVal($xml->record[0]['time']), "memory"=>$xml->record[0]->memory, "cpu"=>$xml->record[0]->cpu, "swap"=>@$xml->record[0]->swap, - "status"=>$xml->record[0]->status); + "status"=>$xml->record[0]->status]; } return $return_array; } @@ -555,7 +559,7 @@ public static function getInformationServerID($server_id) /* First retrieve the server configuration */ $server_file = self::dataDir() . $server_id . "-server.xml"; if (!file_exists($server_file) or !$server_xml=simplexml_load_string(file_get_contents($server_file))) { - error_log("[".self::identifier."] ".__FILE__." line ".__LINE__.": $server_file could not be loaded!"); + error_log("[".self::IDENTIFIER."] ".__FILE__." line ".__LINE__.": $server_file could not be loaded!"); return false; } return $server_xml; @@ -567,7 +571,7 @@ public static function getInformationServerID($server_id) public static function getLogFilesForServerID($server_id, $specific_services = "") { /* Check the directory for the Monit instance ID */ - $files = array(); + $files = []; foreach (glob(self::dataDir() . $server_id . "/" . $specific_services . "*.xml") as $file) { $files[] = $file; } @@ -587,28 +591,28 @@ public static function deleteDataFiles($server_id, $xml_file_name = false) // First everything in the data directory foreach (glob($dirname."*") as $file) { if (!unlink($file)) { - error_log("[".self::identifier."] ".__FILE__." line ".__LINE__.": Could not delete $file"); + error_log("[".self::IDENTIFIER."] ".__FILE__." line ".__LINE__.": Could not delete $file"); return false; } } // Now the data directory itself if (!unlink($dirname)) { - error_log("[".self::identifier."] ".__FILE__." line ".__LINE__.": Could not delete $dirname"); + error_log("[".self::IDENTIFIER."] ".__FILE__." line ".__LINE__.": Could not delete $dirname"); return false; } // Now the server file $server_file = self::dataDir() . $server_id . "-server.xml"; if (!unlink($server_file)) { - error_log("[".self::identifier."] ".__FILE__." line ".__LINE__.": Could not delete $server_file"); + error_log("[".self::IDENTIFIER."] ".__FILE__." line ".__LINE__.": Could not delete $server_file"); return false; } } else { // Only delete specific data file foreach (glob(self::dataDir() . $server_id . "/" . $xml_file_name . "*") as $file) { if (!unlink($file)) { - error_log("[" . self::identifier . "] " . __FILE__ . " line " . __LINE__ . ": Could not delete $file"); + error_log("[" . self::IDENTIFIER . "] " . __FILE__ . " line " . __LINE__ . ": Could not delete $file"); return false; } } @@ -626,25 +630,25 @@ public static function rotateFiles($filename, $chunk_size, $limit_of_chunks) if (intVal($chunk_size) > 0) { if (file_exists($filename) && filesize($filename) > $chunk_size) { // If file size are larger than allowed chunk size, rotate it $files = glob($filename.".*"); - usort($files, array("MonitGraph","sortRotatedFilesLastFirst")); - for ($i=0;$i0 && intval($server_id)) { return intVal($server_id); } - error_log("[".self::identifier."] ".__FILE__." line ".__LINE__.": Server ID is not valid $server_id!"); + error_log("[".self::IDENTIFIER."] ".__FILE__." line ".__LINE__.": Server ID is not valid $server_id!"); return false; } diff --git a/src/cron.php b/src/cron.php deleted file mode 100644 index 7adc610..0000000 --- a/src/cron.php +++ /dev/null @@ -1,20 +0,0 @@ -createElement("records"); - $dom->appendChild($service); - - $attr_name=$dom->createAttribute("name"); - $attr_name->value = $name; - $service->appendChild($attr_name); - - $attr_type=$dom->createAttribute("type"); - $attr_type->value = $type; - $service->appendChild($attr_type); - - for ($i = count($xml->record) -1; $i>0; $i--) { - $record = $xml->record[$i]; - $new_service = $dom->createElement("record"); - - $time=$dom->createAttribute("time"); - $time->value = $record["time"]; - $new_service->appendChild($time); - - if ($type=="5") { - $memory = $dom->createElement("memory", $record->memory); - $new_service->appendChild($memory); - - $cpu = $dom->createElement("cpu", $record->cpu); - $new_service->appendChild($cpu); - - $swap = $dom->createElement("swap", $record->swap); - $new_service->appendChild($swap); - } else { - $memory = $dom->createElement("memory", $record->memory); - $new_service->appendChild($memory); - - $cpu = $dom->createElement("cpu", $record->cpu); - $new_service->appendChild($cpu); - - $pid = $dom->createElement("pid", $record->pid); - $new_service->appendChild($pid); - - $uptime = $dom->createElement("uptime", $record->uptime); - $new_service->appendChild($uptime); - - $children = $dom->createElement("children", $record->children); - $new_service->appendChild($children); - } - - $status = $dom->createElement("status", $record->status); - $new_service->appendChild($status); - - $alert = $dom->createElement("alert", $record->alert); - $new_service->appendChild($alert); - - $monitor = $dom->createElement("monitor", $record->monitor); - $new_service->appendChild($monitor); - - $service->appendChild($new_service); - } - - $dom->validate(); - $handle = fopen($file, 'w'); - if (!$handle) { - die("Cannot open $file"); - } - - $dom->preserveWhiteSpace = false; - $dom->formatOutput = false; - if (fwrite($handle, $dom->saveXML()) === false) { - fclose($handle); - die("Cannot write to $file"); - } - fclose($handle); - } - } diff --git a/src/scripts/build_massive_data.php b/src/scripts/build_massive_data.php new file mode 100644 index 0000000..f12db94 --- /dev/null +++ b/src/scripts/build_massive_data.php @@ -0,0 +1,121 @@ +validate(); + + $handle = fopen($output_file, 'w'); + if (!$handle) { + die("Cannot open $output_file"); + } + + $dom->preserveWhiteSpace = false; + $dom->formatOutput = false; + if (fwrite($handle, $dom->saveXML()) === false) { + fclose($handle); + die("Cannot write to $output_file"); + } +} + + $config = \MonitGraph\Base::config(); + + $output_file = __DIR__ . "/../../data/massive_data_points/service.xml"; + $overwrite = true; + $number_of_data_points = 25000; + $seconds_difference_per_point = 60; // How many seconds between each point + $data_time = time() - $number_of_data_points * $seconds_difference_per_point; + $data_memory = $data_cpu = $data_pid = $data_uptime = $data_children = $data_status = $data_alert = 0; + $data_monitor = $data_cpu = 1; + $data_memory = 5; + $file_size = -1; + $file_size_total = 0; + + $name = "massive_data_points"; + $type = "3"; + +for ($i = 0; $i<$number_of_data_points; $i++) { + if ($file_size == -1 || ($config['chunk_size'] > 0 && $file_size > $config['chunk_size'])) { + if (isset($dom)) { + if (file_exists($output_file)) { + \MonitGraph\Base::rotateFiles($output_file, $config['chunk_size'], $config['limit_number_of_chunks']); + } + echo "Writting out $file_size bytes and reached $i points out of $number_of_data_points\n"; + $file_size_total += $file_size; + writeDom($dom, $output_file); + usleep(100); //relaxing the cpu + } + $file_size = 0; + $dom = null; + unset($dom); + + $dom = new DOMDocument('1.0'); + $service = $dom->createElement("records"); + $dom->appendChild($service); + + $attr_name=$dom->createAttribute("name"); + $attr_name->value = $name; + $service->appendChild($attr_name); + + $attr_type=$dom->createAttribute("type"); + $attr_type->value = $type; + $service->appendChild($attr_type); + } + $data_time += $seconds_difference_per_point; + + $data_memory += rand(-2, 2)/10; + if ($data_memory >= 100 || $data_memory <= 0) { + $data_memory = 0; + } + + $data_cpu += rand(-1, 1)/10; + if ($data_cpu >= 100 || $data_cpu <= 0) { + $data_cpu = 0; + } + + $data_swap = 0; + + $new_service = $dom->createElement("record"); + + $time=$dom->createAttribute("time"); + $time->value = $data_time; + $new_service->appendChild($time); + + $memory = $dom->createElement("memory", intVal($data_memory)); + $new_service->appendChild($memory); + + $cpu = $dom->createElement("cpu", $data_cpu); + $new_service->appendChild($cpu); + + $pid = $dom->createElement("pid", $data_pid); + $new_service->appendChild($pid); + + $uptime = $dom->createElement("uptime", $data_uptime); + $new_service->appendChild($uptime); + + $children = $dom->createElement("children", $data_children); + $new_service->appendChild($children); + + $status = $dom->createElement("status", $data_status); + $new_service->appendChild($status); + + $alert = $dom->createElement("alert", $data_alert); + $new_service->appendChild($alert); + + $monitor = $dom->createElement("monitor", $data_monitor); + $new_service->appendChild($monitor); + + $service->appendChild($new_service); + + $file_size=$dom->save("/tmp/tmp.xml"); // Let's check the file size +} + + writeDom($dom, $output_file); + + echo number_format($number_of_data_points) . " data points written\n"; + echo "Memory peak: " . number_format(memory_get_peak_usage() / 1024, 0, ".", ",") . " kb\n"; + echo "File size: " . number_format($file_size_total / 1024, 0, ".", ",") . " kb\n"; diff --git a/src/scripts/cron.php b/src/scripts/cron.php new file mode 100644 index 0000000..9d6f02c --- /dev/null +++ b/src/scripts/cron.php @@ -0,0 +1,23 @@ +createElement("records"); + $dom->appendChild($service); + + $attr_name=$dom->createAttribute("name"); + $attr_name->value = $name; + $service->appendChild($attr_name); + + $attr_type=$dom->createAttribute("type"); + $attr_type->value = $type; + $service->appendChild($attr_type); + + for ($i = count($xml->record) -1; $i>0; $i--) { + $record = $xml->record[$i]; + $new_service = $dom->createElement("record"); + + $time=$dom->createAttribute("time"); + $time->value = $record["time"]; + $new_service->appendChild($time); + + if ($type=="5") { + $memory = $dom->createElement("memory", $record->memory); + $new_service->appendChild($memory); + + $cpu = $dom->createElement("cpu", $record->cpu); + $new_service->appendChild($cpu); + + $swap = $dom->createElement("swap", $record->swap); + $new_service->appendChild($swap); + } else { + $memory = $dom->createElement("memory", $record->memory); + $new_service->appendChild($memory); + + $cpu = $dom->createElement("cpu", $record->cpu); + $new_service->appendChild($cpu); + + $pid = $dom->createElement("pid", $record->pid); + $new_service->appendChild($pid); + + $uptime = $dom->createElement("uptime", $record->uptime); + $new_service->appendChild($uptime); + + $children = $dom->createElement("children", $record->children); + $new_service->appendChild($children); + } + + $status = $dom->createElement("status", $record->status); + $new_service->appendChild($status); + + $alert = $dom->createElement("alert", $record->alert); + $new_service->appendChild($alert); + + $monitor = $dom->createElement("monitor", $record->monitor); + $new_service->appendChild($monitor); + + $service->appendChild($new_service); + } + + $dom->validate(); + $handle = fopen($file, 'w'); + if (!$handle) { + die("Cannot open $file"); + } + + $dom->preserveWhiteSpace = false; + $dom->formatOutput = false; + if (fwrite($handle, $dom->saveXML()) === false) { + fclose($handle); + die("Cannot write to $file"); + } + fclose($handle); + } +} diff --git a/web/dependencies.php b/src/web/dependencies.php similarity index 94% rename from web/dependencies.php rename to src/web/dependencies.php index 51a35c5..427a7b5 100644 --- a/web/dependencies.php +++ b/src/web/dependencies.php @@ -5,7 +5,7 @@ // view renderer $container['renderer'] = function ($c) { - $config = MonitGraph::config(); + $config = \MonitGraph\Base::config(); $settings = $c->get('settings')['renderer']; $renderer = new Slim\Views\PhpRenderer($settings['template_path']); $renderer->addAttribute('router', $c->get('router')); diff --git a/src/web/middleware.php b/src/web/middleware.php new file mode 100644 index 0000000..886c84a --- /dev/null +++ b/src/web/middleware.php @@ -0,0 +1,7 @@ +add(new \Slim\Middleware\HttpBasicAuthentication([ + "users" => \MonitGraph\Base::config()['basic_auth_users'] + ])); +} diff --git a/web/public/.htaccess b/src/web/public/.htaccess similarity index 100% rename from web/public/.htaccess rename to src/web/public/.htaccess diff --git a/web/public/assets/css/reset.css b/src/web/public/assets/css/reset.css similarity index 100% rename from web/public/assets/css/reset.css rename to src/web/public/assets/css/reset.css diff --git a/web/public/assets/css/style.css b/src/web/public/assets/css/style.css similarity index 63% rename from web/public/assets/css/style.css rename to src/web/public/assets/css/style.css index 7c091d9..7498fd7 100644 --- a/web/public/assets/css/style.css +++ b/src/web/public/assets/css/style.css @@ -1,18 +1,18 @@ /* GENERAL */ body { - font: 13px/1.5 'Helvetica Neue', Arial, 'Liberation Sans', FreeSans, sans-serif; - background-color: #fff; - padding:10px; + font: 13px/1.5 'Helvetica Neue', Arial, 'Liberation Sans', FreeSans, sans-serif; + background-color: #fff; + padding:10px; } a { - color:#5050a7; - text-decoration:none; + color:#5050a7; + text-decoration:none; } a:hover { - color:#8080e7; + color:#8080e7; } .clear{ @@ -20,72 +20,72 @@ a:hover { } .logo { - float:right; + float:right; } .bordered_box { - background-color:#fff; - border: 1px solid #d0d0d0; - margin-bottom:20px; - padding:10px; + background-color:#fff; + border: 1px solid #d0d0d0; + margin-bottom:20px; + padding:10px; } .bordered_box h2 { - font-size:18px; + font-size:18px; } .bordered_box h2 a { - text-decoration:none; - color:#000; + text-decoration:none; + color:#000; } .form_box { - overflow:visible; + overflow:visible; } .form_box .input_box { - float:left; - display:block; - margin-right:10px; - padding:5px; - border:1px solid #d0d0d0; - height:20px; - margin-bottom:5px; + float:left; + display:block; + margin-right:10px; + padding:5px; + border:1px solid #d0d0d0; + height:20px; + margin-bottom:5px; } .form_box input, .form_box select { - background-color:#fff; - border:1px solid #d0d0d0; + background-color:#fff; + border:1px solid #d0d0d0; } .form_box input:hover, .form_box select:hover { - background-color: #e0e0e0; + background-color: #e0e0e0; } .form_box label:hover, .form_box input:hover, .form_box select:hover { - cursor:pointer; + cursor:pointer; } .form_box .submit_box { - float:left; + float:left; } .form_box .submit { - background-color: #d0d0d0; - font-weight:bold; - height:30px; + background-color: #d0d0d0; + font-weight:bold; + height:30px; } .server_box .service_header div, .server_box .service_row div { - float:left; - width:250px; + float:left; + width:250px; } .server_box div strong { - display:block; + display:block; } .server_box .actions { - width:100%; + width:100%; } .btn { diff --git a/web/public/index.php b/src/web/public/index.php similarity index 92% rename from web/public/index.php rename to src/web/public/index.php index f3c04b7..55f8314 100644 --- a/web/public/index.php +++ b/src/web/public/index.php @@ -9,7 +9,7 @@ } } -require __DIR__ . '/../../vendor/autoload.php'; +require __DIR__ . '/../../../vendor/autoload.php'; // Instantiate the app $settings = require __DIR__ . '/../settings.php'; diff --git a/web/routes.php b/src/web/routes.php similarity index 82% rename from web/routes.php rename to src/web/routes.php index 9cf2af2..f862c19 100644 --- a/web/routes.php +++ b/src/web/routes.php @@ -1,18 +1,16 @@ get('/server/{server_id}/data', function ($request, $response, $args) { $params = $request->getQueryParams(); if (!isset($params['file'])) { - return $response->withJson(array()); + return $response->withJson([]); } if (!isset($params['time_range'])) { $params['time_range'] = 0; } $body = new \Slim\Http\Body(fopen('php://temp', 'r+')); - $body->write(MonitGraph::returnGoogleGraphJSON($params['file'], $params['time_range'], $this->renderer->getAttribute('config')['limit_records_shown'])); + $body->write(\MonitGraph\Base::returnGoogleGraphJSON($params['file'], $params['time_range'], $this->renderer->getAttribute('config')['limit_records_shown'])); $response = $response->withBody($body); return $response->withHeader('Content-Type', 'application/json;charset=utf-8'); @@ -32,7 +30,7 @@ } else { $filename = $args['delete_data']; } - if (MonitGraph::deleteDataFiles($args['server_id'], $filename)) { + if (\MonitGraph\Base::deleteDataFiles($args['server_id'], $filename)) { $yield = '

All the files have been deleted successfully at ' . $name . '

'; } else { $yield = '

Some errors happened in the deletion process'; @@ -48,16 +46,18 @@ $app->get('/server/{server_id}', function ($request, $response, $args) { $params = $request->getQueryParams(); - return $this->renderer->render($response, - 'server.phtml', - [ + return $this->renderer->render( + $response, + 'server.phtml', + [ 'server_id' => $args['server_id'], 'chart_type' => @$params['chart_type'], 'time_range' => @$params['time_range'], 'refresh_seconds' => @$params['refresh_seconds'], 'specific_services' => @$params['specific_services'], 'dont_show_alerts' => @$params['dont_show_alerts'] - ]); + ] + ); })->setName('server'); $app->get('/', function ($request, $response, $args) { diff --git a/web/settings.php b/src/web/settings.php similarity index 81% rename from web/settings.php rename to src/web/settings.php index f58b1d2..e8ad3e7 100644 --- a/web/settings.php +++ b/src/web/settings.php @@ -1,7 +1,5 @@ ".$server_config['name']." service logs

"; diff --git a/tests/bootstrap.php b/tests/bootstrap.php new file mode 100644 index 0000000..62a9b9d --- /dev/null +++ b/tests/bootstrap.php @@ -0,0 +1,5 @@ +addPsr4('MonitGraph\Tests\\', __DIR__); diff --git a/tests/support/config.php b/tests/support/config.php index 7bbbd4e..97398c5 100644 --- a/tests/support/config.php +++ b/tests/support/config.php @@ -1,7 +1,7 @@ validate(); - - $handle = fopen($output_file, 'w'); - if (!$handle) { - die("Cannot open $output_file"); - } - - $dom->preserveWhiteSpace = false; - $dom->formatOutput = false; - if (fwrite($handle, $dom->saveXML()) === false) { - fclose($handle); - die("Cannot write to $output_file"); - } - } - - $config = MonitGraph::config(); - - $output_file = __DIR__ . "/../../data/massive_data_points/service.xml"; - $overwrite = true; - $number_of_data_points = 25000; - $seconds_difference_per_point = 60; // How many seconds between each point - $data_time = time() - $number_of_data_points * $seconds_difference_per_point; - $data_memory = $data_cpu = $data_pid = $data_uptime = $data_children = $data_status = $data_alert = 0; - $data_monitor = $data_cpu = 1; - $data_memory = 5; - $file_size = -1; - $file_size_total = 0; - - $name = "massive_data_points"; - $type = "3"; - - for ($i = 0; $i<$number_of_data_points; $i++) { - if ($file_size == -1 || ($config['chunk_size'] > 0 && $file_size > $config['chunk_size'])) { - if (isset($dom)) { - if (file_exists($output_file)) { - MonitGraph::rotateFiles($output_file, $config['chunk_size'], $config['limit_number_of_chunks']); - } - echo "Writting out $file_size bytes and reached $i points out of $number_of_data_points\n"; - $file_size_total += $file_size; - writeDom($dom, $output_file); - usleep(100); //relaxing the cpu - } - $file_size = 0; - $dom = null; - unset($dom); - - $dom = new DOMDocument('1.0'); - $service = $dom->createElement("records"); - $dom->appendChild($service); - - $attr_name=$dom->createAttribute("name"); - $attr_name->value = $name; - $service->appendChild($attr_name); - - $attr_type=$dom->createAttribute("type"); - $attr_type->value = $type; - $service->appendChild($attr_type); - } - $data_time += $seconds_difference_per_point; - - $data_memory += rand(-2, 2)/10; - if ($data_memory >= 100 || $data_memory <= 0) { - $data_memory = 0; - } - - $data_cpu += rand(-1, 1)/10; - if ($data_cpu >= 100 || $data_cpu <= 0) { - $data_cpu = 0; - } - - $data_swap = 0; - - $new_service = $dom->createElement("record"); - - $time=$dom->createAttribute("time"); - $time->value = $data_time; - $new_service->appendChild($time); - - $memory = $dom->createElement("memory", intVal($data_memory)); - $new_service->appendChild($memory); - - $cpu = $dom->createElement("cpu", $data_cpu); - $new_service->appendChild($cpu); - - $pid = $dom->createElement("pid", $data_pid); - $new_service->appendChild($pid); - - $uptime = $dom->createElement("uptime", $data_uptime); - $new_service->appendChild($uptime); - - $children = $dom->createElement("children", $data_children); - $new_service->appendChild($children); - - $status = $dom->createElement("status", $data_status); - $new_service->appendChild($status); - - $alert = $dom->createElement("alert", $data_alert); - $new_service->appendChild($alert); - - $monitor = $dom->createElement("monitor", $data_monitor); - $new_service->appendChild($monitor); - - $service->appendChild($new_service); - - $file_size=$dom->save("/tmp/tmp.xml"); // Let's check the file size - } - - writeDom($dom, $output_file); - - echo number_format($number_of_data_points) . " data points written\n"; - echo "Memory peak: " . number_format(memory_get_peak_usage() / 1024, 0, ".", ",") . " kb\n"; - echo "File size: " . number_format($file_size_total / 1024, 0, ".", ",") . " kb\n"; diff --git a/tests/web/IndexTest.php b/tests/web/IndexTest.php index 8946f6b..7c7355c 100644 --- a/tests/web/IndexTest.php +++ b/tests/web/IndexTest.php @@ -1,6 +1,6 @@ withMiddleware) { - require __DIR__ . '/../../web/middleware.php'; + require __DIR__ . '/../../src/web/middleware.php'; } // Register routes - require __DIR__ . '/../../web/routes.php'; + require __DIR__ . '/../../src/web/routes.php'; // Process the application $response = $app->process($request, $response); diff --git a/web/middleware.php b/web/middleware.php deleted file mode 100644 index c4501eb..0000000 --- a/web/middleware.php +++ /dev/null @@ -1,9 +0,0 @@ -add(new \Slim\Middleware\HttpBasicAuthentication([ - "users" => MonitGraph::config()['basic_auth_users'] - ])); -}