Метрики теперь забираются за интервал

pull/3/head
DmitriyA 2025-03-04 11:11:54 -05:00
parent f4feb6349f
commit 5ed31984f8
5 changed files with 62 additions and 28 deletions

View File

@ -20,12 +20,14 @@
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/axios": "^4.0.0",
"@nestjs/axios": "^4.0.0",
"@nestjs/common": "^11.0.1",
"@nestjs/core": "^11.0.1",
"@nestjs/config": "^4.0.0",
"@nestjs/platform-express": "^11.0.1",
"axios": "^1.7.9",
"reflect-metadata": "^0.2.2",
"dotenv": "^16.3.1",
"rxjs": "^7.8.1"
},
"devDependencies": {

View File

@ -2,9 +2,15 @@ import { Module } from '@nestjs/common';
import { HttpModule } from '@nestjs/axios';
import { PrometheusService } from './prometheus.service';
import { MetricsController } from './metrics.controller';
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [HttpModule], // Используем новый HttpModule
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env',
}),
HttpModule],
controllers: [MetricsController],
providers: [PrometheusService],
})

View File

@ -1,6 +1,7 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);

View File

@ -4,18 +4,25 @@ import { PrometheusService } from './prometheus.service';
@Controller('metrics')
export class MetricsController {
constructor(private readonly prometheusService: PrometheusService) { }
//Получение конкретной метрики
@Get()
async getMetrics(@Query('metric') metric: string) {
async getMetrics(
@Query('metric') metric: string,
@Query('start') start: number,
@Query('end') end: number,
@Query('step') step: number,
) {
if (start && end && step) {
return this.prometheusService.fetchMetricsRange(metric, start, end, step);
}
return this.prometheusService.fetchMetrics(metric);
}
// Получить список всех метрик
@Get('/all')
async getAllMetrics() {
return this.prometheusService.fetchAllMetrics();
}
// Получить ВСЕ метрики со значениями
@Get('/all-values')
async getAllMetricsWithValues() {
return this.prometheusService.fetchAllMetricsWithValues();

View File

@ -1,15 +1,20 @@
import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { ConfigService } from '@nestjs/config';
import { lastValueFrom } from 'rxjs';
import { PrometheusMetric } from './prometheus-metric.interface';
@Injectable()
export class PrometheusService {
private readonly prometheusUrl = 'http://192.168.2.37:9090/api/v1';
private readonly prometheusUrl: string;
constructor(private readonly httpService: HttpService) { }
//Получаем тип метрики
constructor(
private readonly httpService: HttpService,
private readonly configService: ConfigService
) {
this.prometheusUrl = this.configService.get<string>('PROMETHEUS_API', 'http://localhost:9090');
console.log('Prometheus API URL:', this.prometheusUrl);
}
async fetchMetricType(metric: string): Promise<string | null> {
try {
@ -20,20 +25,13 @@ export class PrometheusService {
);
const metadata = response.data.data[metric];
if (metadata && metadata.length > 0) {
return metadata[0].type; // Возвращаем тип метрики
}
return null;
return metadata?.length ? metadata[0].type : null;
} catch (error) {
console.error(`Ошибка при получении типа метрики ${metric}:`, error);
return null;
}
}
//Данные конкретной метрики, включая ее тип
async fetchMetrics(metric: string): Promise<PrometheusMetric[]> {
const response = await lastValueFrom(
this.httpService.get(`${this.prometheusUrl}/query`, {
@ -41,27 +39,47 @@ export class PrometheusService {
})
);
const metricType = await this.fetchMetricType(metric); // Получаем тип
const metricType = await this.fetchMetricType(metric);
return response.data.data.result.map((entry): PrometheusMetric => ({
...entry.metric,
timestamp: entry.value[0] * 1000, // Преобразуем в миллисекунды
value: parseFloat(entry.value[1]), // Преобразуем в число
type: metricType || 'unknown', // Добавляем тип метрики
timestamp: entry.value[0] * 1000,
value: parseFloat(entry.value[1]),
type: metricType || 'unknown',
}));
}
//Получаем данные всех метрик
async fetchMetricsRange(metric: string, start: number, end: number, step: number): Promise<PrometheusMetric[]> {
const response = await lastValueFrom(
this.httpService.get(`${this.prometheusUrl}/query_range`, {
params: {
query: metric,
start,
end,
step,
},
})
);
const metricType = await this.fetchMetricType(metric);
return response.data.data.result.flatMap((entry) =>
entry.values.map((value): PrometheusMetric => ({
...entry.metric,
timestamp: value[0] * 1000,
value: parseFloat(value[1]),
type: metricType || 'unknown',
}))
);
}
async fetchAllMetrics(): Promise<string[]> {
const response = await lastValueFrom(
this.httpService.get(`${this.prometheusUrl}/label/__name__/values`)
);
return response.data.data; // Это массив с именами метрик
return response.data.data;
}
// Получаем список всех метрик
async fetchAllMetricsWithValues(): Promise<any[]> {
const metricNames = await this.fetchAllMetrics();
const promises = metricNames.map(async (metric) => {