public static function content_header($icon, $title, $subtitle = '') { $serverload = implode(', ', sys_getloadavg()); $pid = Service::ServiceData(SInfo::DATA_PID); if ($subtitle != '') { $title .= ' <span>> ' . $subtitle . '</span>'; } $buf = '<div class="row"> <div class="col-xs-12 col-sm-7 col-md-7 col-lg-7"> <h2 class="page-title txt-color-blueDark"><i class="fa-fw fa ' . $icon . '"></i> ' . $title . '</h2> </div> <div class="col-xs-12 col-sm-5 col-md-5 col-lg-5"> <ul id="sparks" class=""> <li class="sparks-info"> <h5>LSWS PID <span id="lst-pid" class="txt-color-blue"> ' . $pid . ' </span></h5> <a class="btn btn-success" title="' . DMsg::UIStr('menu_restart') . '" href="javascript:lst_restart()"><i class="fa fa-lg fa-repeat"></i></a> </li> <li class="sparks-info"> <h5> ' . DMsg::UIStr('note_loadavg') . ' <span id="lst-load" class="txt-color-purple"> ' . $serverload . ' </span></h5> <a class="btn btn-info" title="' . DMsg::UIStr('menu_rtstats') . '" href="#view/realtimestats.php"><i class="fa fa-lg fa-bar-chart-o"></i></a> </li> </ul> </div> </div> '; return $buf; }
/** * Returns a value from the cache. * * @param string $key * * @return mixed */ public function get($key) { $filePath = $this->getFilePathFromKey($key); if (!file_exists($filePath)) { return false; } if (!is_readable($filePath)) { return false; } $cacheFileData = file_get_contents($filePath); if ($this->config['gzipCompression']) { $cacheFileData = gzuncompress($cacheFileData); } $cacheObj = json_decode($cacheFileData); $unixLoad = sys_getloadavg(); if ($cacheObj->expiryTimestamp > time() || $unixLoad[0] >= $this->config['unixLoadUpperThreshold']) { // Cache item has not yet expired or system load is too high $content = $cacheObj->content; if ($unserializedContent = @unserialize($content)) { $content = $unserializedContent; } return $content; } else { // Cache item has expired return false; } }
/** * @return Stage */ public function frontendDashboard() { $Stage = new Stage('Dashboard', 'System'); $Value = 100 / disk_total_space(__DIR__) * disk_free_space(__DIR__); Main::getDispatcher()->registerWidget('System', new Panel('Festplattenkapazität', array('<div class="progress" style="margin-bottom: 0;"> <div class="progress-bar progress-bar-success" style="width: ' . $Value . '%"></div> <div class="progress-bar progress-bar-danger" style="width: ' . (100 - $Value) . '%"></div> </div>', 'Gesamt: ' . number_format(disk_total_space(__DIR__), 0, ',', '.'), 'Frei: ' . number_format(disk_free_space(__DIR__), 0, ',', '.'))), 2, 2); $free = shell_exec('free'); $free = (string) trim($free); $free_arr = explode("\n", $free); $mem = explode(" ", $free_arr[1]); $mem = array_filter($mem); $mem = array_merge($mem); $Value = $mem[2] / $mem[1] * 100; Main::getDispatcher()->registerWidget('System', new Panel('Speicherkapazität', array('<div class="progress" style="margin-bottom: 0;"> <div class="progress-bar progress-bar-success" style="width: ' . $Value . '%"></div> <div class="progress-bar progress-bar-danger" style="width: ' . (100 - $Value) . '%"></div> </div>', 'Gesamt: ' . number_format($mem[1], 0, ',', '.'), 'Frei: ' . number_format($mem[2], 0, ',', '.'))), 2, 2); $load = sys_getloadavg(); Main::getDispatcher()->registerWidget('System', new Panel('Rechenkapazität', array('<div class="progress" style="margin-bottom: 0;"> <div class="progress-bar progress-bar-success" style="width: ' . 50 * (2 - $load[0]) . '%"></div> <div class="progress-bar progress-bar-danger" style="width: ' . 50 * $load[0] . '%"></div> </div>', 'Genutzt: ' . number_format($load[0], 5, ',', '.'), 'Frei: ' . number_format(2 - $load[0], 5, ',', '.'))), 2, 2); $Stage->setContent(Main::getDispatcher()->fetchDashboard('System')); return $Stage; }
function get() { if (!get_config('system', 'hidden_version_siteinfo')) { $version = sprintf(t('Version %s'), \Zotlabs\Lib\System::get_project_version()); if (@is_dir('.git') && function_exists('shell_exec')) { $commit = @shell_exec('git log -1 --format="%h"'); $tag = \Zotlabs\Lib\System::get_std_version(); // @shell_exec('git describe --tags --abbrev=0'); } if (!isset($commit) || strlen($commit) > 16) { $commit = ''; } } else { $version = $commit = ''; } $plugins_list = implode(', ', visible_plugin_list()); if ($plugins_list) { $plugins_text = t('Installed plugins/addons/apps:'); } else { $plugins_text = t('No installed plugins/addons/apps'); } $txt = get_config('system', 'admininfo'); $admininfo = bbcode($txt); if (file_exists('doc/site_donate.html')) { $donate .= file_get_contents('doc/site_donate.html'); } if (function_exists('sys_getloadavg')) { $loadavg = sys_getloadavg(); } $o = replace_macros(get_markup_template('siteinfo.tpl'), array('$title' => t('$Projectname'), '$description' => t('This is a hub of $Projectname - a global cooperative network of decentralized privacy enhanced websites.'), '$version' => $version, '$tag_txt' => t('Tag: '), '$tag' => $tag, '$polled' => t('Last background fetch: '), '$lastpoll' => get_poller_runtime(), '$load_average' => t('Current load average: '), '$loadavg_all' => $loadavg[0] . ', ' . $loadavg[1] . ', ' . $loadavg[2], '$commit' => $commit, '$web_location' => t('Running at web location') . ' ' . z_root(), '$visit' => t('Please visit <a href="http://hubzilla.org">hubzilla.org</a> to learn more about $Projectname.'), '$bug_text' => t('Bug reports and issues: please visit'), '$bug_link_url' => 'https://github.com/redmatrix/hubzilla/issues', '$bug_link_text' => t('$projectname issues'), '$contact' => t('Suggestions, praise, etc. - please email "redmatrix" at librelist - dot com'), '$donate' => $donate, '$adminlabel' => t('Site Administrators'), '$admininfo' => $admininfo, '$plugins_text' => $plugins_text, '$plugins_list' => $plugins_list)); call_hooks('about_hook', $o); return $o; }
protected function assureCpuNotBurning($load = 8) { $cpu = sys_getloadavg(); if ($cpu[0] > $load) { throw new DelayException(); } }
/** * logData * * Retrives data and logs it to file * * @param string $type type of logging default set to normal but it can be API too. * @return string $string if type is API returns data as string * */ public function logData($type = false) { $class = __CLASS__; $settings = Logger::$_settings->{$class}; $timestamp = time(); $load = null; //use the php function if its there if (!function_exists('sys_getloadavg')) { $load = exec("cat /proc/loadavg | awk -F' ' '{print \$1\"|\"\$2\"|\"\$3}'"); } else { $phpload = sys_getloadavg(); $load = $phpload[0] . "|" . $phpload[1] . "|" . $phpload[2]; } //if we want fancy formatting in logs we can always format them like this //$number = number_format((float)$number, 2, '.', ''); $string = $timestamp . '|' . $load . "\n"; //we can also add a switch to feed live data to server with no local logging //by just returning data $filename = sprintf($this->logfile, date('Y-m-d')); LoadUtility::safefilerewrite($filename, $string, "a", true); //If alerts are enabled, check for alerts //note: $phpload dont work on 4.0 needs fixing above if (Alert::$alertStatus) { $alertString = $this->checkAlerts($timestamp, $phpload, $settings); } //Based on API mode return data if need be if ($type == "api") { return $string; } else { return true; } }
/** * Dump live informations from extender process (if in daemon mode and pcntl installed) * * @param int $timestamp_absolute * @param itn $parent_pid * @param int $completed_processes * @param itn $failed_processes */ public static final function dump($timestamp_absolute, $parent_pid, $completed_processes, $failed_processes, $paused) { $statusfile = EXTENDER_CACHE_FOLDER . self::$statusfile; $data = array("RUNNING" => $paused ? 0 : 1, "STARTED" => $timestamp_absolute, "TIME" => microtime(true) - $timestamp_absolute, "PARENTPID" => $parent_pid, "COMPLETED" => $completed_processes, "FAILED" => $failed_processes, "CPUAVG" => sys_getloadavg(), "MEM" => memory_get_usage(true), "MEMPEAK" => memory_get_peak_usage(true), "USER" => get_current_user(), "NICENESS" => function_exists('pcntl_getpriority') ? pcntl_getpriority() : "UNDEFINED"); $content = serialize($data); return file_put_contents($statusfile, $content); }
/** * Get load average in percents. * @return string */ public static function loadAverage() { $load = 0; if (stristr(PHP_OS, 'win')) { // its not a better solution, but no other way to do this $cmd = "wmic cpu get loadpercentage /all"; @exec($cmd, $output); // if output is exist if ($output) { // try to find line with numeric data foreach ($output as $line) { if ($line && preg_match("/^[0-9]+\$/", $line)) { $load = $line; break; } } } } else { $sys_load = sys_getloadavg(); // get linux load average (1 = 100% of 1 CPU) $load = $sys_load[0] * 100; // to percentage } if ((int) $load <= 0) { return 'error'; } return (int) $load . '%'; }
private function getServerCpuUsage() { $load = sys_getloadavg(); $cores = shell_exec('nproc'); $use = shell_exec('ps -A -o pcpu | tail -n+2 | paste -sd+ | bc'); return $use / $cores; }
function get_server_load() { if (stristr(PHP_OS, 'win') != false) { $fileModTime = filemtime("./load.cache"); $cache = @file_get_contents("./load.cache"); if (file_exists("./load.cache") && !empty($cache) && $fileModTime && time() - $fileModTime < 60) { $load = $cache; } else { $wmi = new COM("Winmgmts://"); $server = $wmi->execquery("SELECT LoadPercentage FROM Win32_Processor"); $cpu_num = 0; $load_total = 0; foreach ($server as $cpu) { $cpu_num++; $load_total += $cpu->loadpercentage; } $load = round($load_total / $cpu_num, 2); file_put_contents("./load.cache", $load); } } else { $sys_load = sys_getloadavg(); $load = round($sys_load[0], 2); } return (int) $load; }
private function loadAverage() { if (function_exists('sys_getloadavg')) { $load = sys_getloadavg(); return $load[0]; } }
public function cpu() { $loads = sys_getloadavg(); $cores = trim($this->ssh->exec("grep -P '^processor' /proc/cpuinfo|wc -l")); $load = round($loads[0] / ($cores + 1) * 100, 2); return ['num' => $cores, 'load' => $load]; }
/** * 服务器负载保护函数,本方法目前不支持window系统 * * 最大负载不要超过3*N核,例如有16核(含8核超线程)则 16*3=48 * * @see http://php.net/manual/en/function.sys-getloadavg.php */ function _load_protection($max_load_avg = 24) { global $dir_log, $dir_wwwroot; if (!function_exists('sys_getloadavg')) { return false; } $load = sys_getloadavg(); if (!isset($load[0])) { return false; } if ($load[0] <= $max_load_avg) { // 未超过负载,则跳出 return false; } $msg_tpl = "[%s] HOST:%s LOAD:%s ARGV/URI:%s\n"; $time = @date(DATE_RFC2822); $host = php_uname('n'); $load = sprintf('%.2f', $load[0]); if (php_sapi_name() == "cli" || empty($_SERVER['PHP_SELF'])) { $argv_or_uri = implode(',', $argv); } else { $argv_or_uri = $_SERVER['REQUEST_URI']; } $msg = sprintf($msg_tpl, $time, $host, $load, $argv_or_uri); if (@is_dir($dir_log)) { @file_put_contents($dir_log . "php-server-overload.log", $msg, FILE_APPEND); } # exit with 500 page header("HTTP/1.1 500 Internal Server Error"); header("Expires: " . gmdate("D, d M Y H:i:s", time() - 99999) . " GMT"); header("Cache-Control: private"); header("Pragma: no-cache"); exit(file_get_contents($dir_wwwroot . 'errors/server_overload.html')); }
public function verifyError() { $load = sys_getloadavg(); $CPUProcessNumber = $this->getMaxCPUProcessNumbers(); if ($load[$this->getTime()] > $CPUProcessNumber) { $this->getHandler()->addErrorHandle("Current CPU process number is {$load[$this->getTime()]}, when allowed is {$CPUProcessNumber}", '', $this->getStateType()); } }
/** * CPU Last der letzten 1,5,15 Minuten auslesen */ static function getCPUusage() { if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { return false; } else { return sys_getloadavg(); } }
public function monitor($metric) { switch ($metric) { case 'cpu': return new JsonResponse(['cpu' => sys_getloadavg()[0]]); break; } }
function getload() { $load1 = sys_getloadavg(); $loadoutput = array(); $loadoutput['Metric'] = "Value"; $loadoutput = '{"cols":[{"id":"Load","label":"Load","type":"string"},{"id":"value","label":"Value","type":"number"}],"rows":[{"c":[{"v":"Now"},{"v":' . $load1[0] . '}]},{"c":[{"v":"15min"},{"v":' . $load1[1] . '}]},{"c":[{"v":"30mins"},{"v":' . $load1[2] . '}]}]}'; return $loadoutput; }
/** * Gets the current load average * @return false|float the load average, or false if it could not be determined */ public function getCurrentLoad() { if (stristr(PHP_OS, "win")) { return $this->getCurrentLoadWindows(); } $avg = sys_getloadavg(); return array_shift($avg); }
protected function getAvgLoad() { if (!function_exists('sys_getloadavg')) { return 0; } $ret = sys_getloadavg(); return (double) $ret[0]; }
public function getServerLoad() { if ($this->ipAddress == '127.0.0.1') { $load = sys_getloadavg(); $cpuCores = $this->num_cpus(); return (int) ($load[1] / $cpuCores * 100.0); } }
/** * @param string $interval * @return mixed */ public function getLoadAverage($interval = '5') { $la = array_combine(['1', '5', '15'], sys_getloadavg()); if (array_key_exists($interval, $la)) { return $la[$interval]; } else { throw new \InvalidArgumentException(); } }
public function __invoke() { $load = sys_getloadavg(); if (isset($load[$this->interval])) { return new Response($load[$this->interval], 200, array('Content-Type' => 'text/plain')); } else { return new Response('Whoops!', 500, array('Content-Type' => 'text/plain')); } }
function run() { $this->startTime = date('Y-m-d H:i:s'); $this->__status['start_loadavg'] = sys_getloadavg(); $this->process(); $this->__status['end_loadavg'] = sys_getloadavg(); $this->endTime = date('Y-m-d H:i:s'); return TRUE; }
public function __invoke() { $sysload = sys_getloadavg(); $this->history[] = $sysload[0]; if (count($this->history) > 20) { array_shift($this->history); } return ['current' => $sysload[0], 'history' => $this->history]; }
/** * Adds the actual system load to the log message context. * * @param \AppserverIo\Logger\LogMessageInterface $logMessage The log message we want to add the system load * * @return string The processed log message * @see \AppserverIo\Logger\Processors\ProcessorInterface::process() */ public function process(LogMessageInterface $logMessage) { // load the sysload values $values = sys_getloadavg(); // create an array $sysload = array('system_load_1' => array_shift($values), 'system_load_5' => array_shift($values), 'system_load_15' => array_shift($values)); // merge the values with the actual context instance $logMessage->mergeIntoContext($sysload); }
function randomBytes($length = 16, $secure = true, $raw = true, $startEntropy = "", &$rounds = 0, &$drop = 0) { static $lastRandom = ""; $output = ""; $length = abs((int) $length); $secureValue = ""; $rounds = 0; $drop = 0; while (!isset($output[$length - 1])) { //some entropy, but works ^^ $weakEntropy = array(is_array($startEntropy) ? implode($startEntropy) : $startEntropy, serialize(stat(__FILE__)), __DIR__, PHP_OS, microtime(), (string) lcg_value(), (string) PHP_MAXPATHLEN, PHP_SAPI, (string) PHP_INT_MAX . "." . PHP_INT_SIZE, serialize($_SERVER), serialize(get_defined_constants()), get_current_user(), serialize(ini_get_all()), (string) memory_get_usage() . "." . memory_get_peak_usage(), php_uname(), phpversion(), extension_loaded("gmp") ? gmp_strval(gmp_random(4)) : microtime(), zend_version(), (string) getmypid(), (string) getmyuid(), (string) mt_rand(), (string) getmyinode(), (string) getmygid(), (string) rand(), function_exists("zend_thread_id") ? (string) zend_thread_id() : microtime(), var_export(@get_browser(), true), function_exists("getrusage") ? @implode(getrusage()) : microtime(), function_exists("sys_getloadavg") ? @implode(sys_getloadavg()) : microtime(), serialize(get_loaded_extensions()), sys_get_temp_dir(), (string) disk_free_space("."), (string) disk_total_space("."), uniqid(microtime(), true), file_exists("/proc/cpuinfo") ? file_get_contents("/proc/cpuinfo") : microtime()); shuffle($weakEntropy); $value = hash("sha512", implode($weakEntropy), true); $lastRandom .= $value; foreach ($weakEntropy as $k => $c) { //mixing entropy values with XOR and hash randomness extractor $value ^= hash("sha256", $c . microtime() . $k, true) . hash("sha256", mt_rand() . microtime() . $k . $c, true); $value ^= hash("sha512", (string) lcg_value() . $c . microtime() . $k, true); } unset($weakEntropy); if ($secure === true) { $strongEntropyValues = array(is_array($startEntropy) ? hash("sha512", $startEntropy[($rounds + $drop) % count($startEntropy)], true) : hash("sha512", $startEntropy, true), file_exists("/dev/urandom") ? fread(fopen("/dev/urandom", "rb"), 64) : str_repeat("", 64), (function_exists("openssl_random_pseudo_bytes") and version_compare(PHP_VERSION, "5.3.4", ">=")) ? openssl_random_pseudo_bytes(64) : str_repeat("", 64), function_exists("mcrypt_create_iv") ? mcrypt_create_iv(64, MCRYPT_DEV_URANDOM) : str_repeat("", 64), $value); $strongEntropy = array_pop($strongEntropyValues); foreach ($strongEntropyValues as $value) { $strongEntropy = $strongEntropy ^ $value; } $value = ""; //Von Neumann randomness extractor, increases entropy $bitcnt = 0; for ($j = 0; $j < 64; ++$j) { $a = ord($strongEntropy[$j]); for ($i = 0; $i < 8; $i += 2) { $b = ($a & 1 << $i) > 0 ? 1 : 0; if ($b != (($a & 1 << $i + 1) > 0 ? 1 : 0)) { $secureValue |= $b << $bitcnt; if ($bitcnt == 7) { $value .= chr($secureValue); $secureValue = 0; $bitcnt = 0; } else { ++$bitcnt; } ++$drop; } else { $drop += 2; } } } } $output .= substr($value, 0, min($length - strlen($output), $length)); unset($value); ++$rounds; } $lastRandom = hash("sha512", $lastRandom, true); return $raw === false ? bin2hex($output) : $output; }
function load_monit_init() { $load = sys_getloadavg(); $sleep = 5; $maxload = 2; if ($load[0] > $maxload) { sleep($sleep); echo "Busy server - sleep {$sleep} seconds<br>"; } }
public function getLoadAVG() { $load = sys_getloadavg(); if ($load[0] > 80) { header('HTTP/1.1 503 Too busy, try again later'); die('Server too busy. Please try again later.'); } else { return $load; } }
/** * @test */ public function loadAvgReturnsArrayOfLoadAverage() { $client = static::createClient(); $client->request('GET', '/api/service/loadavg'); $response = $client->getResponse(); $this->assertEquals(200, $response->getStatusCode()); $this->assertJSON($response->getContent()); $result = json_decode($response->getContent(), true); $this->assertEquals(sys_getloadavg(), $result); }
function get_load() { $load = sys_getloadavg(); if ($load[0] > 80) { return -1; } else { $this->res['load'] = $load; return $load; } }