ws update
parent
37690dc79f
commit
fcab8fa2b8
|
|
@ -11303,4 +11303,5 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -2,7 +2,7 @@ import { Controller, Post, Get, Body, Res, Req, UnauthorizedException, UseGuards
|
||||||
import { AuthService } from './auth.service';
|
import { AuthService } from './auth.service';
|
||||||
import { Response, Request } from 'express';
|
import { Response, Request } from 'express';
|
||||||
import { JwtAuthGuard } from './jwt-auth.guard';
|
import { JwtAuthGuard } from './jwt-auth.guard';
|
||||||
import { Logger } from '@nestjs/common/services';
|
import { Logger } from '@nestjs/common';
|
||||||
|
|
||||||
@Controller('auth')
|
@Controller('auth')
|
||||||
export class AuthController {
|
export class AuthController {
|
||||||
|
|
@ -13,19 +13,17 @@ export class AuthController {
|
||||||
@Get('check')
|
@Get('check')
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
async checkAuth(@Req() req: Request) {
|
async checkAuth(@Req() req: Request) {
|
||||||
this.logger.debug(`Check auth request. Cookies: ${JSON.stringify(req.cookies)}`);
|
this.logger.debug(`Проверен запрос на авторизацию. Cookies: ${JSON.stringify(req.cookies)}`);
|
||||||
this.logger.debug(`Check auth request. Headers: ${JSON.stringify(req.headers)}`);
|
|
||||||
|
|
||||||
if (!req.user) {
|
if (!req.user) {
|
||||||
this.logger.warn('Unauthorized access attempt');
|
this.logger.warn('Unauthorized access attempt');
|
||||||
throw new UnauthorizedException('Пользователь не аутентифицирован');
|
throw new UnauthorizedException('Пользователь не аутентифицирован');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Явно указываем тип для req.user
|
|
||||||
const user = req.user as { userId: number; username: string; login?: string };
|
const user = req.user as { userId: number; username: string; login?: string };
|
||||||
const userWithoutPassword = { ...user };
|
const userWithoutPassword = { ...user };
|
||||||
|
|
||||||
this.logger.log(`User authenticated: ${user.username}`);
|
this.logger.log(`Аутентифицированный пользователь: ${user.username}`);
|
||||||
return {
|
return {
|
||||||
isAuthenticated: true,
|
isAuthenticated: true,
|
||||||
user: userWithoutPassword
|
user: userWithoutPassword
|
||||||
|
|
@ -36,11 +34,8 @@ export class AuthController {
|
||||||
async login(
|
async login(
|
||||||
@Body() body: { login: string; password: string },
|
@Body() body: { login: string; password: string },
|
||||||
@Res({ passthrough: true }) res: Response,
|
@Res({ passthrough: true }) res: Response,
|
||||||
@Req() req: Request
|
|
||||||
) {
|
) {
|
||||||
this.logger.debug(`Login attempt for user: ${body.login}`);
|
this.logger.debug(`Login attempt for user: ${body.login}`);
|
||||||
this.logger.debug(`Request cookies: ${JSON.stringify(req.cookies)}`);
|
|
||||||
this.logger.debug(`Request headers: ${JSON.stringify(req.headers)}`);
|
|
||||||
|
|
||||||
const user = await this.authService.validateUser(body.login, body.password);
|
const user = await this.authService.validateUser(body.login, body.password);
|
||||||
if (!user) {
|
if (!user) {
|
||||||
|
|
@ -59,8 +54,6 @@ export class AuthController {
|
||||||
});
|
});
|
||||||
|
|
||||||
this.logger.log(`User ${body.login} successfully logged in`);
|
this.logger.log(`User ${body.login} successfully logged in`);
|
||||||
this.logger.debug(`Set cookie: access_token=${access_token.substring(0, 10)}...`);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
user: {
|
user: {
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,39 @@
|
||||||
|
/* import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
export class LoginDto {
|
||||||
|
@ApiProperty({
|
||||||
|
example: 'admin@example.com',
|
||||||
|
description: 'User email or login',
|
||||||
|
required: true
|
||||||
|
})
|
||||||
|
login: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: 'yourStrongPassword123',
|
||||||
|
description: 'User password',
|
||||||
|
required: true,
|
||||||
|
minLength: 6
|
||||||
|
})
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CheckAuthResponse {
|
||||||
|
@ApiProperty({ example: true, description: 'Статус аутентификации' })
|
||||||
|
isAuthenticated: boolean;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: { userId: 1, username: 'admin', login: 'admin@example.com' },
|
||||||
|
description: 'Пользовательская информация без конфиденциальных данных'
|
||||||
|
})
|
||||||
|
user: {
|
||||||
|
userId: number;
|
||||||
|
username: string;
|
||||||
|
login?: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export class LogoutResponse {
|
||||||
|
@ApiProperty({ example: true, description: 'Статус успешного выхода из системы' })
|
||||||
|
success: boolean;
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
@ -7,6 +7,6 @@ export class AuthGuard implements CanActivate {
|
||||||
context: ExecutionContext,
|
context: ExecutionContext,
|
||||||
): boolean | Promise<boolean> | Observable<boolean> {
|
): boolean | Promise<boolean> | Observable<boolean> {
|
||||||
const request = context.switchToHttp().getRequest();
|
const request = context.switchToHttp().getRequest();
|
||||||
return !!request.user; // Проверка что пользователь аутентифицирован
|
return !!request.user;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -13,7 +13,7 @@ import * as cookieParser from 'cookie-parser';
|
||||||
TypeOrmModule.forFeature([User]),
|
TypeOrmModule.forFeature([User]),
|
||||||
PassportModule,
|
PassportModule,
|
||||||
JwtModule.register({
|
JwtModule.register({
|
||||||
secret: process.env.JWT_SECRET,
|
secret: process.env.JWT_SECRET || 'your-secret-key',
|
||||||
signOptions: { expiresIn: '1h' },
|
signOptions: { expiresIn: '1h' },
|
||||||
}),
|
}),
|
||||||
],
|
],
|
||||||
|
|
|
||||||
|
|
@ -24,7 +24,7 @@ export class AuthService {
|
||||||
|
|
||||||
async login(user: any) {
|
async login(user: any) {
|
||||||
const payload = {
|
const payload = {
|
||||||
username: user.login, // Используем username в payload
|
username: user.login,
|
||||||
sub: user.id
|
sub: user.id
|
||||||
};
|
};
|
||||||
return {
|
return {
|
||||||
|
|
|
||||||
|
|
@ -14,7 +14,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||||
},
|
},
|
||||||
]),
|
]),
|
||||||
ignoreExpiration: false,
|
ignoreExpiration: false,
|
||||||
secretOrKey: process.env.JWT_SECRET,
|
secretOrKey: process.env.JWT_SECRET || 'your-secret-key',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
38
src/main.ts
38
src/main.ts
|
|
@ -1,12 +1,46 @@
|
||||||
import { NestFactory } from '@nestjs/core';
|
import { NestFactory } from '@nestjs/core';
|
||||||
import { AppModule } from './app.module';
|
import { AppModule } from './app.module';
|
||||||
|
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
|
||||||
|
import { Logger } from '@nestjs/common';
|
||||||
|
|
||||||
async function bootstrap() {
|
async function bootstrap() {
|
||||||
const app = await NestFactory.create(AppModule);
|
const app = await NestFactory.create(AppModule);
|
||||||
|
const logger = new Logger('Bootstrap');
|
||||||
|
|
||||||
// Установка глобального префикса для всех маршрутов
|
// Установка глобального префикса для всех маршрутов
|
||||||
app.setGlobalPrefix('api');
|
app.setGlobalPrefix('api');
|
||||||
|
|
||||||
|
// Настройка Swagger
|
||||||
|
const config = new DocumentBuilder()
|
||||||
|
.setTitle('МУФ API')
|
||||||
|
.setDescription('API для сбора метрик и аутентификации')
|
||||||
|
.setVersion('1.0')
|
||||||
|
.addBearerAuth(
|
||||||
|
{
|
||||||
|
type: 'http',
|
||||||
|
scheme: 'bearer',
|
||||||
|
bearerFormat: 'JWT',
|
||||||
|
name: 'JWT',
|
||||||
|
description: 'Enter JWT token',
|
||||||
|
in: 'header',
|
||||||
|
},
|
||||||
|
'JWT-auth', // Это имя для схемы безопасности
|
||||||
|
)
|
||||||
|
.addCookieAuth('access_token') // Для cookie-based аутентификации
|
||||||
|
.build();
|
||||||
|
|
||||||
|
const document = SwaggerModule.createDocument(app, config);
|
||||||
|
SwaggerModule.setup('api/docs', app, document, {
|
||||||
|
swaggerOptions: {
|
||||||
|
persistAuthorization: true,
|
||||||
|
tagsSorter: 'alpha',
|
||||||
|
operationsSorter: 'alpha',
|
||||||
|
docExpansion: 'none',
|
||||||
|
filter: true,
|
||||||
|
},
|
||||||
|
customSiteTitle: 'MSF API Documentation',
|
||||||
|
});
|
||||||
|
|
||||||
// Настройка CORS
|
// Настройка CORS
|
||||||
app.enableCors({
|
app.enableCors({
|
||||||
origin: [process.env.FRONTEND_URL, "http://dev.msf.enode"],
|
origin: [process.env.FRONTEND_URL, "http://dev.msf.enode"],
|
||||||
|
|
@ -18,6 +52,8 @@ async function bootstrap() {
|
||||||
optionsSuccessStatus: 204
|
optionsSuccessStatus: 204
|
||||||
});
|
});
|
||||||
|
|
||||||
await app.listen(process.env.PORT ?? 3000);
|
const port = process.env.PORT ?? 3000;
|
||||||
|
await app.listen(port);
|
||||||
|
logger.log(`Application is running on: http://localhost:${port}/api/docs`);
|
||||||
}
|
}
|
||||||
bootstrap();
|
bootstrap();
|
||||||
|
|
@ -1,11 +1,21 @@
|
||||||
import { Controller, Get, Query } from '@nestjs/common';
|
import { Controller, Get, Query } from '@nestjs/common';
|
||||||
import { PrometheusService } from './prometheus.service';
|
import { PrometheusService } from './prometheus.service';
|
||||||
|
import { ApiTags, ApiOperation, ApiResponse, ApiQuery } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
@ApiTags('Metrics - HTTP')
|
||||||
@Controller('metrics')
|
@Controller('metrics')
|
||||||
export class MetricsController {
|
export class MetricsController {
|
||||||
constructor(private readonly prometheusService: PrometheusService) { }
|
constructor(private readonly prometheusService: PrometheusService) { }
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
|
@ApiOperation({ summary: 'Получиние данных по конкретной метрике' })
|
||||||
|
@ApiQuery({ name: 'metric', required: true, description: 'Имя метрики для извлечения' })
|
||||||
|
@ApiQuery({ name: 'start', required: false, description: 'Начальная временная метка для запроса диапазона' })
|
||||||
|
@ApiQuery({ name: 'end', required: false, description: 'Конечная временная метка для запроса диапазона' })
|
||||||
|
@ApiQuery({ name: 'step', required: false, description: 'Размер шага для запроса диапазона' })
|
||||||
|
@ApiResponse({ status: 200, description: 'Успешно получены метрические данные' })
|
||||||
|
@ApiResponse({ status: 400, description: 'Указанные недопустимые параметры' })
|
||||||
|
@ApiResponse({ status: 500, description: 'Внутренняя ошибка сервера' })
|
||||||
async getMetrics(
|
async getMetrics(
|
||||||
@Query('metric') metric: string,
|
@Query('metric') metric: string,
|
||||||
@Query('start') start: number,
|
@Query('start') start: number,
|
||||||
|
|
@ -19,11 +29,15 @@ export class MetricsController {
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('/all')
|
@Get('/all')
|
||||||
|
@ApiOperation({ summary: 'Получение списка всех метрик' })
|
||||||
|
@ApiResponse({ status: 200, description: 'Список извлеченных метрик' })
|
||||||
async getAllMetrics() {
|
async getAllMetrics() {
|
||||||
return this.prometheusService.fetchAllMetrics();
|
return this.prometheusService.fetchAllMetrics();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get('/all-values')
|
@Get('/all-values')
|
||||||
|
@ApiOperation({ summary: 'Получение списка всех метрик и их значения' })
|
||||||
|
@ApiResponse({ status: 200, description: 'Все метрики с полученными значениями' })
|
||||||
async getAllMetricsWithValues() {
|
async getAllMetricsWithValues() {
|
||||||
return this.prometheusService.fetchAllMetricsWithValues();
|
return this.prometheusService.fetchAllMetricsWithValues();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,11 @@
|
||||||
import { WebSocketGateway, WebSocketServer, OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect, SubscribeMessage } from '@nestjs/websockets';
|
import {
|
||||||
|
WebSocketGateway,
|
||||||
|
WebSocketServer,
|
||||||
|
OnGatewayInit,
|
||||||
|
OnGatewayConnection,
|
||||||
|
OnGatewayDisconnect,
|
||||||
|
SubscribeMessage,
|
||||||
|
} from '@nestjs/websockets';
|
||||||
import { Server, Socket } from 'socket.io';
|
import { Server, Socket } from 'socket.io';
|
||||||
import { PrometheusService } from './prometheus.service';
|
import { PrometheusService } from './prometheus.service';
|
||||||
import { Logger } from '@nestjs/common';
|
import { Logger } from '@nestjs/common';
|
||||||
|
|
@ -20,7 +27,7 @@ export class MetricsGateway implements OnGatewayInit, OnGatewayConnection, OnGat
|
||||||
clients: Set<string>;
|
clients: Set<string>;
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
constructor(private readonly prometheusService: PrometheusService) { }
|
constructor(private readonly prometheusService: PrometheusService) {}
|
||||||
|
|
||||||
afterInit(server: Server) {
|
afterInit(server: Server) {
|
||||||
this.logger.log('WebSocket Gateway initialized');
|
this.logger.log('WebSocket Gateway initialized');
|
||||||
|
|
@ -34,49 +41,89 @@ export class MetricsGateway implements OnGatewayInit, OnGatewayConnection, OnGat
|
||||||
handleDisconnect(client: Socket) {
|
handleDisconnect(client: Socket) {
|
||||||
this.logger.log(`Client disconnected: ${client.id}`);
|
this.logger.log(`Client disconnected: ${client.id}`);
|
||||||
this.activeSockets.delete(client.id);
|
this.activeSockets.delete(client.id);
|
||||||
|
|
||||||
|
// Очистка всех подписок этого клиента
|
||||||
|
for (const [metric, subscription] of this.metricSubscriptions) {
|
||||||
|
subscription.clients.delete(client.id);
|
||||||
|
if (subscription.clients.size === 0) {
|
||||||
|
subscription.stopUpdates();
|
||||||
|
this.metricSubscriptions.delete(metric);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@SubscribeMessage('unsubscribe-all')
|
||||||
|
handleUnsubscribeAll(client: Socket) {
|
||||||
|
for (const [metric, subscription] of this.metricSubscriptions) {
|
||||||
|
subscription.clients.delete(client.id);
|
||||||
|
if (subscription.clients.size === 0) {
|
||||||
|
subscription.stopUpdates();
|
||||||
|
this.metricSubscriptions.delete(metric);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@SubscribeMessage('get-metrics')
|
@SubscribeMessage('get-metrics')
|
||||||
async handleGetMetrics(client: Socket, payload: any) {
|
async handleGetMetrics(client: Socket, payload: any) {
|
||||||
const { metric, start, end, step, isRangeQuery } = payload;
|
const { metric, start, end, step, isRangeQuery, requestId, filters = {} } = payload;
|
||||||
|
|
||||||
try {
|
if (!metric) {
|
||||||
if (isRangeQuery) {
|
client.emit('metrics-error', {
|
||||||
// Обработка разового запроса
|
error: 'Metric name is required',
|
||||||
const data = await this.prometheusService.fetchMetricsRange(metric, start, end, step);
|
requestId
|
||||||
client.emit(`metrics-range-${metric}`, data);
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Исправлено: передаем функцию, а не клиента
|
if (isRangeQuery) {
|
||||||
|
try {
|
||||||
|
const data = await this.prometheusService.fetchMetricsRange(metric, start, end, step, filters);
|
||||||
|
client.emit('metrics-data', { metric, data, requestId });
|
||||||
|
return;
|
||||||
|
} catch (error) {
|
||||||
|
client.emit('metrics-error', {
|
||||||
|
error: error.message,
|
||||||
|
requestId
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
const stopUpdates = await this.sendPeriodicUpdates(
|
const stopUpdates = await this.sendPeriodicUpdates(
|
||||||
metric,
|
metric,
|
||||||
step || 5000,
|
step || 5000,
|
||||||
(data) => {
|
(data) => {
|
||||||
client.emit('metrics-data', { metric, data });
|
client.emit('metrics-data', { metric, data, requestId });
|
||||||
}
|
},
|
||||||
|
filters
|
||||||
);
|
);
|
||||||
|
|
||||||
client.on('disconnect', () => stopUpdates());
|
const cleanup = () => {
|
||||||
client.on('unsubscribe-metric', () => stopUpdates());
|
stopUpdates();
|
||||||
|
client.off('disconnect', cleanup);
|
||||||
|
client.off('unsubscribe-metric', cleanup);
|
||||||
|
};
|
||||||
|
|
||||||
|
client.on('disconnect', cleanup);
|
||||||
|
client.on('unsubscribe-metric', cleanup);
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error(`Error fetching metrics: ${error.message}`);
|
|
||||||
client.emit('metrics-error', {
|
client.emit('metrics-error', {
|
||||||
metric,
|
error: error.message,
|
||||||
error: error.message
|
requestId
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@SubscribeMessage('subscribe-metric')
|
@SubscribeMessage('subscribe-metric')
|
||||||
async handleSubscribeMetric(client: Socket, payload: { metric: string, interval?: number }) {
|
async handleSubscribeMetric(client: Socket, payload: { metric: string; interval?: number }) {
|
||||||
const { metric } = payload;
|
const { metric, interval = 5000 } = payload;
|
||||||
|
|
||||||
if (!this.metricSubscriptions.has(metric)) {
|
if (!this.metricSubscriptions.has(metric)) {
|
||||||
const stopUpdates = await this.sendPeriodicUpdates(
|
const stopUpdates = await this.sendPeriodicUpdates(
|
||||||
metric,
|
metric,
|
||||||
payload.interval || 5000,
|
interval,
|
||||||
(data) => {
|
(data) => {
|
||||||
this.server.emit('metrics-data', { metric, data });
|
this.server.emit('metrics-data', { metric, data });
|
||||||
}
|
}
|
||||||
|
|
@ -87,11 +134,7 @@ export class MetricsGateway implements OnGatewayInit, OnGatewayConnection, OnGat
|
||||||
clients: new Set([client.id])
|
clients: new Set([client.id])
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// Исправлено: добавлена проверка на существование подписки
|
this.metricSubscriptions.get(metric)?.clients.add(client.id);
|
||||||
const subscription = this.metricSubscriptions.get(metric);
|
|
||||||
if (subscription) {
|
|
||||||
subscription.clients.add(client.id);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const unsubscribe = () => {
|
const unsubscribe = () => {
|
||||||
|
|
@ -109,14 +152,18 @@ export class MetricsGateway implements OnGatewayInit, OnGatewayConnection, OnGat
|
||||||
client.on('unsubscribe-metric', unsubscribe);
|
client.on('unsubscribe-metric', unsubscribe);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Метод для периодической отправки обновлений
|
async sendPeriodicUpdates(
|
||||||
async sendPeriodicUpdates(metric: string, interval: number, callback: (data: any) => void) {
|
metric: string,
|
||||||
|
interval: number,
|
||||||
|
callback: (data: any) => void,
|
||||||
|
filters: Record<string, string> = {}
|
||||||
|
) {
|
||||||
const timer = setInterval(async () => {
|
const timer = setInterval(async () => {
|
||||||
try {
|
try {
|
||||||
const data = await this.prometheusService.fetchMetrics(metric);
|
const data = await this.prometheusService.fetchMetricsWithFilters(metric, filters);
|
||||||
callback(data); // Используем переданный callback
|
callback(data);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error(`Error in periodic update for ${metric}: ${error.message}`);
|
this.logger.error(`Error in periodic update for ${metric}:`, error.message);
|
||||||
}
|
}
|
||||||
}, interval);
|
}, interval);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,13 @@
|
||||||
export interface PrometheusMetric {
|
export interface PrometheusMetric {
|
||||||
__name__?: string;
|
__name__: string;
|
||||||
[key: string]: string | number | undefined;
|
device?: string;
|
||||||
|
instance?: string;
|
||||||
|
job?: string;
|
||||||
|
source_id?: string;
|
||||||
|
status: string;
|
||||||
timestamp: number;
|
timestamp: number;
|
||||||
value: number;
|
value: number;
|
||||||
type: string; // Тип метрики ("gauge", "counter", и т. д.)
|
type: string;
|
||||||
description?: string; // Описание метрики
|
description?: string;
|
||||||
status?: string; // Добавляем поле для статуса
|
[key: string]: string | number | undefined;
|
||||||
}
|
}
|
||||||
|
|
@ -52,6 +52,7 @@ export class PrometheusService {
|
||||||
|
|
||||||
// Получаем данные метрики (текущие значения)
|
// Получаем данные метрики (текущие значения)
|
||||||
async fetchMetrics(metric: string): Promise<PrometheusMetric[]> {
|
async fetchMetrics(metric: string): Promise<PrometheusMetric[]> {
|
||||||
|
try {
|
||||||
const response = await lastValueFrom(
|
const response = await lastValueFrom(
|
||||||
this.httpService.get(`${this.prometheusUrl}/query`, {
|
this.httpService.get(`${this.prometheusUrl}/query`, {
|
||||||
params: { query: metric },
|
params: { query: metric },
|
||||||
|
|
@ -62,24 +63,87 @@ export class PrometheusService {
|
||||||
const metricDescription = await this.fetchMetricDescription(metric);
|
const metricDescription = await this.fetchMetricDescription(metric);
|
||||||
|
|
||||||
return response.data.data.result.map((entry): PrometheusMetric => ({
|
return response.data.data.result.map((entry): PrometheusMetric => ({
|
||||||
...entry.metric,
|
__name__: entry.metric.__name__ || metric,
|
||||||
|
device: entry.metric.device,
|
||||||
|
instance: entry.metric.instance,
|
||||||
|
job: entry.metric.job,
|
||||||
|
source_id: entry.metric.source_id,
|
||||||
|
status: entry.metric.status || '0', // По умолчанию '0' (аналог 'green' в старом формате)
|
||||||
timestamp: entry.value[0] * 1000,
|
timestamp: entry.value[0] * 1000,
|
||||||
value: parseFloat(entry.value[1]),
|
value: parseFloat(entry.value[1]),
|
||||||
type: metricType || 'unknown',
|
type: metricType || 'gauge', // По умолчанию 'gauge'
|
||||||
description: metricDescription,
|
description: metricDescription,
|
||||||
status: entry.metric.status || 'green', // Используем статус из Prometheus или 'green' по умолчанию
|
...entry.metric // Добавляем остальные поля метрики
|
||||||
}));
|
}));
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error fetching metrics for ${metric}:`, error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fetchMetricsWithFilters(metric: string, filters: Record<string, string>): Promise<PrometheusMetric[]> {
|
||||||
|
try {
|
||||||
|
const query = this.buildFilteredQuery(metric, filters);
|
||||||
|
const response = await lastValueFrom(
|
||||||
|
this.httpService.get(`${this.prometheusUrl}/query`, {
|
||||||
|
params: { query }
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const metricType = await this.fetchMetricType(metric);
|
||||||
|
const metricDescription = await this.fetchMetricDescription(metric);
|
||||||
|
|
||||||
|
return response.data.data.result.map((entry): PrometheusMetric => ({
|
||||||
|
__name__: entry.metric.__name__ || metric,
|
||||||
|
device: entry.metric.device,
|
||||||
|
instance: entry.metric.instance,
|
||||||
|
job: entry.metric.job,
|
||||||
|
source_id: entry.metric.source_id,
|
||||||
|
status: entry.metric.status || '0',
|
||||||
|
timestamp: entry.value[0] * 1000,
|
||||||
|
value: parseFloat(entry.value[1]),
|
||||||
|
type: metricType || 'gauge',
|
||||||
|
description: metricDescription,
|
||||||
|
...entry.metric
|
||||||
|
}));
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error fetching metrics with filters for ${metric}:`, error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildFilteredQuery(metric: string, filters: Record<string, string>): string {
|
||||||
|
const filterParts = Object.entries(filters)
|
||||||
|
.filter(([_, value]) => value !== undefined && value !== null && value !== "")
|
||||||
|
.map(([key, value]) => {
|
||||||
|
// Для source_id добавляем module$ префикс, если его нет
|
||||||
|
if (key === 'source_id' && !value.startsWith('module$')) {
|
||||||
|
return `${key}="module$${value}"`;
|
||||||
|
}
|
||||||
|
return `${key}="${value}"`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const query = filterParts.length > 0
|
||||||
|
? `${metric}{${filterParts.join(',')}}`
|
||||||
|
: metric;
|
||||||
|
|
||||||
|
console.log('Generated PromQL query:', query); // Добавьте этот лог
|
||||||
|
return query;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Получаем данные метрики за интервал
|
// Получаем данные метрики за интервал
|
||||||
async fetchMetricsRange(metric: string, start: number, end: number, step: number): Promise<PrometheusMetric[]> {
|
async fetchMetricsRange(metric: string, start: number, end: number, step: number, filters: Record<string, string> = {}): Promise<PrometheusMetric[]> {
|
||||||
|
const query = this.buildFilteredQuery(metric, filters); // <-- ВНЕ try
|
||||||
|
try {
|
||||||
|
console.log('Executing range query:', { query, start, end, step });
|
||||||
|
|
||||||
const response = await lastValueFrom(
|
const response = await lastValueFrom(
|
||||||
this.httpService.get(`${this.prometheusUrl}/query_range`, {
|
this.httpService.get(`${this.prometheusUrl}/query_range`, {
|
||||||
params: {
|
params: {
|
||||||
query: metric,
|
query,
|
||||||
start,
|
start,
|
||||||
end,
|
end,
|
||||||
step,
|
step: step.toString()
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
@ -89,15 +153,29 @@ export class PrometheusService {
|
||||||
|
|
||||||
return response.data.data.result.flatMap((entry) =>
|
return response.data.data.result.flatMap((entry) =>
|
||||||
entry.values.map((value): PrometheusMetric => ({
|
entry.values.map((value): PrometheusMetric => ({
|
||||||
...entry.metric,
|
__name__: entry.metric.__name__ || metric,
|
||||||
|
device: entry.metric.device,
|
||||||
|
instance: entry.metric.instance,
|
||||||
|
job: entry.metric.job,
|
||||||
|
source_id: entry.metric.source_id,
|
||||||
|
status: entry.metric.status || '0',
|
||||||
timestamp: value[0] * 1000,
|
timestamp: value[0] * 1000,
|
||||||
value: parseFloat(value[1]),
|
value: parseFloat(value[1]),
|
||||||
type: metricType || 'unknown',
|
type: metricType || 'gauge',
|
||||||
description: metricDescription,
|
description: metricDescription,
|
||||||
status: entry.metric.status || 'green', // Используем статус из Prometheus или 'green' по умолчанию
|
...entry.metric
|
||||||
}))
|
}))
|
||||||
);
|
);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error in fetchMetricsRange:', {
|
||||||
|
error: error.response?.data || error.message,
|
||||||
|
query,
|
||||||
|
filters
|
||||||
|
});
|
||||||
|
throw error;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
// Получаем список всех метрик
|
// Получаем список всех метрик
|
||||||
async fetchAllMetrics(): Promise<string[]> {
|
async fetchAllMetrics(): Promise<string[]> {
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue