<?php
session_start();
$expire = 1800;
if (empty($_SESSION['user_id']) || (time() - $_SESSION['login_time'] > $expire)) {
    session_destroy();
    header("Content-Type:application/json;charset=utf-8");
    echo json_encode(["code"=>401,"msg"=>"未登录，请前往登录页面"],JSON_UNESCAPED_UNICODE);
    exit;
}
header("Content-Type:application/json; charset=utf-8");

$promAddr = "http://10.150.117.190:9090";
$gbUnit = 1073741824;
$promQuery = urlencode('node_directory_size_bytes');
$apiUrl = "{$promAddr}/api/v1/query?query={$promQuery}";
$resp = @file_get_contents($apiUrl);
if(!$resp){
    echo json_encode(["code"=>500,"msg"=>"无法连接Prometheus"],JSON_UNESCAPED_UNICODE);
    exit;
}
$raw = json_decode($resp, true);

$allData = [];
if ($raw['status'] === 'success' && !empty($raw['data']['result'])) {
    foreach ($raw['data']['result'] as $item) {
        $dir = $item['metric']['directory'];
        $instanceIp = $item['metric']['instance'];
        $instanceIp = explode(':', $instanceIp)[0];
        $userName = basename($dir);
        $byteNum = floatval($item['value'][1]);
        $gbNum = round($byteNum / $gbUnit, 2);

        $allData[] = [
            "instance_ip" => $instanceIp,
            "username"    => $userName,
            "directory"   => $dir,
            "size_gb"     => $gbNum
        ];
    }
    usort($allData, function ($a, $b) {
        return $b['size_gb'] <=> $a['size_gb'];
    });
}

echo json_encode([
    "code"  => 0,
    "msg"   => "查询成功",
    "list"  => $allData
], JSON_UNESCAPED_UNICODE);
exit;
?>
