0

Iv had an idea to make a server performance module for a crm application I work with. So that an admin can monitor graphs of current CPU load%, memory used % number of currently running processes etc all in near to real time. But the module would have to work on both Linux and Windows servers.

Is this possible a standard php installation on both Linux and Windows?

For example I have came across this script that works well for CPU load:

      function _getServerLoadLinuxData()
{
    if (is_readable("/proc/stat"))
    {
        $stats = @file_get_contents("/proc/stat");

        if ($stats !== false)
        {
            // Remove double spaces to make it easier to extract values with explode()
            $stats = preg_replace("/[[:blank:]]+/", " ", $stats);

            // Separate lines
            $stats = str_replace(array("\r\n", "\n\r", "\r"), "\n", $stats);
            $stats = explode("\n", $stats);

            // Separate values and find line for main CPU load
            foreach ($stats as $statLine)
            {
                $statLineData = explode(" ", trim($statLine));

                // Found!
                if
                (
                    (count($statLineData) >= 5) &&
                    ($statLineData[0] == "cpu")
                )
                {
                    return array(
                        $statLineData[1],
                        $statLineData[2],
                        $statLineData[3],
                        $statLineData[4],
                    );
                }
            }
        }
    }

    return null;
}

// Returns server load in percent (just number, without percent sign)
function getServerLoad()
{
    $load = null;

    if (stristr(PHP_OS, "win"))
    {
        $cmd = "wmic cpu get loadpercentage /all";
        @exec($cmd, $output);

        if ($output)
        {
            foreach ($output as $line)
            {
                if ($line && preg_match("/^[0-9]+\$/", $line))
                {
                    $load = $line;
                    break;
                }
            }
        }
    }
    else
    {
        if (is_readable("/proc/stat"))
        {
            // Collect 2 samples - each with 1 second period
            // See: https://de.wikipedia.org/wiki/Load#Der_Load_Average_auf_Unix-Systemen
            $statData1 = _getServerLoadLinuxData();
            sleep(1);
            $statData2 = _getServerLoadLinuxData();

            if
            (
                (!is_null($statData1)) &&
                (!is_null($statData2))
            )
            {
                // Get difference
                $statData2[0] -= $statData1[0];
                $statData2[1] -= $statData1[1];
                $statData2[2] -= $statData1[2];
                $statData2[3] -= $statData1[3];

                // Sum up the 4 values for User, Nice, System and Idle and calculate
                // the percentage of idle time (which is part of the 4 values!)
                $cpuTime = $statData2[0] + $statData2[1] + $statData2[2] + $statData2[3];

                // Invert percentage to get CPU time, not idle time
                $load = 100 - ($statData2[3] * 100 / $cpuTime);
            }
        }
    }

    return $load;
}

//----------------------------

$cpuLoad = getServerLoad();
if (is_null($cpuLoad)) {
    echo "CPU load not estimateable (maybe too old Windows or missing rights at Linux or Windows)";
}
else {
    echo $cpuLoad . "% ";
}

I can get Linux uptime with :

  uptime = shell_exec("cut -d. -f1 /proc/uptime");
  $days = floor($uptime/60/60/24);
  $hours = $uptime/60/60%24;
  $mins = $uptime/60%60;
  $secs = $uptime%60;
  echo "up $days days $hours hours $mins minutes and $secs seconds";

I have tried the following to get memory usage but its not accurate.

    function get_server_memory_usage(){

$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);
$memory_usage = $mem[2]/$mem[1]*100;

return $memory_usage;
}

According to system monitor my pc has 7.8 GB of ram and I am only using 63% of it but with the function above its saying I and using 95%? Is this just showing memory allocated to PHP? I would rather be able to get the total system memory in Gigabytes then get the percentage used.

Also wandering what the option are on a Linux system if you dont have access to /proc/ ?

user794846
  • 1,881
  • 5
  • 29
  • 72
  • It's a lot of effort to make a monitoring tool in PHP. You should consider using a monitor tool like zabbix, cacti, nagios, Icinga. Why build something that others already build and tested. PHP is not a solution for everything. When you want cross platform monitoring use one of the open source packages. Save yourself some trouble. zabbix also offers a webservice api so you can get the required data from zabbix in your PHP Crm – Romuald Villetet Aug 05 '16 at 13:48
  • yes but its just to a be a small monitoring module not a large fully functional application. – user794846 Aug 05 '16 at 13:49
  • If I could get a reliable cross platform way of getting cpu load and memory usage it would probably be enough. Surly such a class exists somewhere already. – user794846 Aug 05 '16 at 13:51
  • There is no cross platform way of getting cpu or memory usage. Like you see in your code for cpu load, there are different approaches for *NIX and Windows. The same goes for memory usage. Take a look at this question https://stackoverflow.com/questions/9095948/how-to-retrieve-available-ram-from-windows-command-line – Charlotte Dunois Aug 05 '16 at 13:54
  • sys_getloadavg doesn't output it as a % though does it? – user794846 Aug 05 '16 at 13:56
  • Nope, it's a decimal number (the same as you get over cmd). – Charlotte Dunois Aug 05 '16 at 13:58
  • See this https://stackoverflow.com/questions/9229333/how-to-get-overall-cpu-usage-e-g-57-on-linux – Charlotte Dunois Aug 05 '16 at 13:58

0 Answers0