<?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}";

// 改用curl，不依赖allow_url_fopen
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$resp = curl_exec($ch);
$curlErr = curl_error($ch);
curl_close($ch);

if(!$resp || !empty($curlErr)){
    echo json_encode(["code"=>500,"msg"=>"无法连接Prometheus：".$curlErr],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;
?>
