Files
data-collection-terminal/management-panel/app/Services/PrometheusService.php

77 lines
2.2 KiB
PHP

<?php
namespace App\Services;
use GuzzleHttp\Client;
class PrometheusService
{
protected $client;
protected $baseUri = 'http://127.0.0.1:9090/api/v1/'; // Prometheus 的默认地址
public function __construct()
{
$this->client = new Client(['base_uri' => $this->baseUri]);
}
/**
* 执行 Prometheus 实时查询
*
* @param string $query PromQL 查询语句
* @return array 返回查询结果
*/
public function query($query)
{
try {
$response = $this->client->get('query', [
'query' => ['query' => $query],
]);
return json_decode($response->getBody()->getContents(), true);
} catch (\Exception $e) {
// 处理异常,记录日志或返回错误信息
error_log('Query failed: ' . $e->getMessage());
return ['error' => 'Failed to execute query', 'message' => $e->getMessage()];
}
}
/**
* 执行 Prometheus 区间查询
*
* @param string $query PromQL 查询语句
* @param int $start 开始时间(时间戳,单位秒)
* @param int $end 结束时间(时间戳,单位秒)
* @param int $step 时间间隔(单位秒)
* @return array 返回查询结果
*/
public function queryRange($query, $start, $end, $step)
{
try {
$response = $this->client->get('query_range', [
'query' => [
'query' => $query,
'start' => $start,
'end' => $end,
'step' => $step,
],
]);
return json_decode($response->getBody()->getContents(), true);
} catch (\Exception $e) {
// 处理异常,记录日志或返回错误信息
error_log('Query range failed: ' . $e->getMessage());
return ['error' => 'Failed to execute query range', 'message' => $e->getMessage()];
}
}
/**
* 获取 Prometheus 监控的所有目标
*
* @return array 返回目标信息
*/
public function getTargets()
{
$response = $this->client->get('targets');
return json_decode($response->getBody()->getContents(), true);
}
}