Compare commits

...

10 Commits

Author SHA1 Message Date
deployer3000 c83bbd4149 Merge pull request 'rc' (#4) from rc into main 2025-03-17 16:10:30 +03:00
YurijO e131228b4b Merge pull request 'feature' (#3) from feature into rc
test-org/trust-module-backend/pipeline/pr-main Build started... Details
Reviewed-on: http://192.168.2.61/deployer3000/trust-module-backend/pulls/3
2025-03-17 16:05:27 +03:00
DmitriyA 7b7b7f7034 Обновить .env
test-org/trust-module-backend/pipeline/pr-main This commit looks good Details
test-org/trust-module-backend/pipeline/pr-rc This commit looks good Details
2025-03-06 11:55:17 +03:00
DmitriyA 78edc4e3a4 Исправил конфликт 2025-03-06 03:51:55 -05:00
DmitriyA 0afbcd7467 Merge branch 'feature' of http://git.enode/deployer3000/trust-module-backend into feature 2025-03-06 03:49:35 -05:00
DmitriyA 085d48cdbf Метрики теперь забираются за интервал времени 2025-03-06 03:43:53 -05:00
DmitriyA 5ed31984f8 Метрики теперь забираются за интервал 2025-03-04 11:11:54 -05:00
DmitriyA 76fa893146 Добавить .env 2025-02-26 16:33:57 +03:00
DmitriyA c4ece458e4 Хранение api в .env файле 2025-02-26 13:24:00 +00:00
yuobrezkov 1bfa621c27 Changed Jenkinsfile 2025-02-21 12:31:08 +03:00
9 changed files with 94 additions and 31 deletions

1
.env Normal file
View File

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

View File

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

3
Jenkinsfile vendored
View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,16 +1,22 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios'; import { HttpService } from '@nestjs/axios';
import { ConfigService } from '@nestjs/config';
import { lastValueFrom } from 'rxjs'; import { lastValueFrom } from 'rxjs';
import { PrometheusMetric } from './prometheus-metric.interface'; import { PrometheusMetric } from './prometheus-metric.interface';
@Injectable() @Injectable()
export class PrometheusService { 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> { async fetchMetricType(metric: string): Promise<string | null> {
try { try {
const response = await lastValueFrom( const response = await lastValueFrom(
@ -20,20 +26,31 @@ export class PrometheusService {
); );
const metadata = response.data.data[metric]; 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) { } catch (error) {
console.error(`Ошибка при получении типа метрики ${metric}:`, error); console.error(`Ошибка при получении типа метрики ${metric}:`, error);
return null; 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[]> { async fetchMetrics(metric: string): Promise<PrometheusMetric[]> {
const response = await lastValueFrom( const response = await lastValueFrom(
this.httpService.get(`${this.prometheusUrl}/query`, { this.httpService.get(`${this.prometheusUrl}/query`, {
@ -41,27 +58,54 @@ export class PrometheusService {
}) })
); );
const metricType = await this.fetchMetricType(metric); // Получаем тип const metricType = await this.fetchMetricType(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, ...entry.metric,
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 || 'unknown',
description: metricDescription, // Добавляем описание
})); }));
} }
//Получаем данные всех метрик // Получаем данные метрики за интервал
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[]> { async fetchAllMetrics(): Promise<string[]> {
const response = await lastValueFrom( const response = await lastValueFrom(
this.httpService.get(`${this.prometheusUrl}/label/__name__/values`) this.httpService.get(`${this.prometheusUrl}/label/__name__/values`)
); );
return response.data.data; // Это массив с именами метрик return response.data.data;
} }
// Получаем список всех метрик // Получаем все метрики с их значениями
async fetchAllMetricsWithValues(): Promise<any[]> { async fetchAllMetricsWithValues(): Promise<any[]> {
const metricNames = await this.fetchAllMetrics(); const metricNames = await this.fetchAllMetrics();
const promises = metricNames.map(async (metric) => { const promises = metricNames.map(async (metric) => {