Compare commits

..

No commits in common. "c83bbd41498b8a73b3f7941209772bd4f1f1e43f" and "f4feb6349f2c726241deeb072a2bdbfd6bc715ea" have entirely different histories.

9 changed files with 31 additions and 94 deletions

1
.env
View File

@ -1 +0,0 @@
#PROMETHEUS_API=http://192.168.2.34:9090/api/v1

View File

@ -8,6 +8,4 @@ RUN npm install
COPY . .
ENV NODE_ENV=development
CMD ["npm", "run", "start:dev"]

3
Jenkinsfile vendored
View File

@ -41,6 +41,7 @@ pipeline {
always {
script {
echo "Cleaning up workspace..."
sh "rm -rf ${env.WORKSPACE}/package/ || true"
sh "rm -rf ${env.WORKSPACE}/rc/ || true"
}
}
@ -55,7 +56,7 @@ pipeline {
-u "${GITEA_USER}:${GITEA_PASS}" \
-H "Content-Type: application/json" \
-d '{"do":"merge"}' \
http://git.entcor/api/v1/repos/deployer3000/trust-module-backend/pulls/${prId}/merge
http://git.entcor/api/v1/repos/DmitriyA/trust-module-backend/pulls/${prId}/merge
"""
echo "PR ${prId} merged successfully into master!"
}

View File

@ -20,14 +20,12 @@
"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": {
@ -74,4 +72,4 @@
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
}

View File

@ -2,15 +2,9 @@ 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: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env',
}),
HttpModule],
imports: [HttpModule], // Используем новый HttpModule
controllers: [MetricsController],
providers: [PrometheusService],
})

View File

@ -1,7 +1,6 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
@ -12,4 +11,4 @@ async function bootstrap() {
});
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
bootstrap();

View File

@ -4,27 +4,20 @@ import { PrometheusService } from './prometheus.service';
@Controller('metrics')
export class MetricsController {
constructor(private readonly prometheusService: PrometheusService) { }
//Получение конкретной метрики
@Get()
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);
}
async getMetrics(@Query('metric') metric: string) {
return this.prometheusService.fetchMetrics(metric);
}
// Получить список всех метрик
@Get('/all')
async getAllMetrics() {
return this.prometheusService.fetchAllMetrics();
}
// Получить ВСЕ метрики со значениями
@Get('/all-values')
async getAllMetricsWithValues() {
return this.prometheusService.fetchAllMetricsWithValues();
}
}
}

View File

@ -4,5 +4,4 @@ export interface PrometheusMetric {
timestamp: number;
value: number;
type: string; // Тип метрики ("gauge", "counter", и т. д.)
description?: string; // Описание метрики
}
}

View File

@ -1,22 +1,16 @@
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: string;
private readonly prometheusUrl = 'http://192.168.2.37:9090/api/v1';
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);
}
constructor(private readonly httpService: HttpService) { }
//Получаем тип метрики
// Получаем тип метрики
async fetchMetricType(metric: string): Promise<string | null> {
try {
const response = await lastValueFrom(
@ -26,31 +20,20 @@ export class PrometheusService {
);
const metadata = response.data.data[metric];
return metadata?.length ? metadata[0].type : null;
if (metadata && metadata.length > 0) {
return metadata[0].type; // Возвращаем тип метрики
}
return null;
} catch (error) {
console.error(`Ошибка при получении типа метрики ${metric}:`, error);
return null;
}
}
// Получаем описание метрики
async fetchMetricDescription(metric: string): Promise<string | undefined> {
try {
const response = await lastValueFrom(
this.httpService.get(`${this.prometheusUrl}/metadata`, {
params: { metric },
})
);
//Данные конкретной метрики, включая ее тип
const metadata = response.data.data[metric];
return metadata?.length ? metadata[0].help : undefined;
} catch (error) {
console.error(`Ошибка при получении описания метрики ${metric}:`, error);
return undefined;
}
}
// Получаем данные метрики (текущие значения)
async fetchMetrics(metric: string): Promise<PrometheusMetric[]> {
const response = await lastValueFrom(
this.httpService.get(`${this.prometheusUrl}/query`, {
@ -58,54 +41,27 @@ export class PrometheusService {
})
);
const metricType = await this.fetchMetricType(metric);
const metricDescription = await this.fetchMetricDescription(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',
description: metricDescription, // Добавляем описание
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);
const metricDescription = await this.fetchMetricDescription(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',
description: metricDescription, // Добавляем описание
}))
);
}
// Получаем список всех метрик
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) => {