Jordan Savant # Software Engineer

This script will do a full system sweep of remaining resources for Apache, Memory, Disk, CPU and report it back.

Use the key to run it, though its mostly harmless. I think its best as CLI only.

<?php

$isCli = isset($argv);

$key = "KEYHERE";

$check = $isCli ? @$argv[1] : $_GET['key'];

if ($check != $key) {
    http_response_code(403);
    echo json_encode([
        'version' => 1,
        'valid' => false
    ], JSON_PRETTY_PRINT);
    exit(1);
}

# Get Stats
$apacheWorkerMax = (int)trim(shell_exec("grep '^\s*MaxRequestWorkers' /etc/apache2/mods-enabled/mpm_prefork.conf | awk '{print $2}'"));
$apacheWorkerCount = (int)trim(shell_exec("ps aux | grep sbin[/]apache2 | expr $(wc -l) - 1"));
$apacheLoad = $apacheWorkerCount / $apacheWorkerMax;
$apacheLoadPercent = (int)round($apacheLoad * 100);

# takes 1 second
$cpuLoadPercent = (float)trim(shell_exec("{ head -n1 /proc/stat;sleep 1;head -n1 /proc/stat; } | awk '/^cpu /{u=$2-u;s=$4-s;i=$5-i;w=$6-w}END{print int(0.5+100*(u+s+w)/(u+s+i+w))}'"));
$memoryTotal = (int)trim(shell_exec("free -mt | sed '2!d' | awk '{print $2}'"));
$memoryFree = (int)trim(shell_exec("free -mt | sed '2!d' | awk '{print $4}'"));
$memoryCache = (int)trim(shell_exec("free -mt | sed '2!d' | awk '{print $6}'"));
$memoryAvailable = ($memoryCache + $memoryFree);
$memoryLoad = ($memoryTotal - $memoryAvailable) / $memoryTotal;
$memoryLoadPercent = (int)($memoryLoad * 100);
$diskTotal = (int)trim(shell_exec("df -m | awk '$6 == \"/\" {print $2}'"));
$diskUsed = (int)trim(shell_exec("df -m | awk '$6 == \"/\" {print $3}'"));
$diskLoad = $diskUsed / $diskTotal;
$diskLoadPercent = (int)round($diskLoad * 100);

# Determine risk
$statusCode = 0;
$status = 'healthy';
$riskThreshold = 80;
if ($memoryLoadPercent > $riskThreshold || $cpuLoadPercent > $riskThreshold || $apacheLoadPercent > $riskThreshold || $diskLoadPercent > $riskThreshold) {
    $status = 'high-load';
    $statusCode = 1;
}

$response = [
    'version' => 1,
    'valid' => true,
    'status' => $status,
    'statusCode' => $statusCode,
    'humanReadable' => "Server is $status: Apache load is $apacheLoadPercent%, CPU load is $cpuLoadPercent%, memory usage is $memoryLoadPercent%, disk usage is $diskLoadPercent%",
    'detail' => [
        'riskThresholdPercent' => $riskThreshold,
        'apacheWorkerMax' => $apacheWorkerMax,
        'apacheWorkerCount' => $apacheWorkerCount,
        'apacheLoadPercent' => $apacheLoadPercent,
        'cpuLoadPercent' => $cpuLoadPercent,
        'memoryTotal' => $memoryTotal,
        'memoryAvailable' => $memoryAvailable,
        'memoryLoadPercent' => $memoryLoadPercent,
        'diskTotal' => $diskTotal,
        'diskUsed' => $diskUsed,
        'diskLoadPercent' => $diskLoadPercent,
    ]
];

echo json_encode($response, JSON_PRETTY_PRINT);