Skip to content

Commit

Permalink
Add getStatsByDeviceAndType for Prometheus metric queries
Browse files Browse the repository at this point in the history
  • Loading branch information
SquirrelDevelopper committed Jan 30, 2025
1 parent c958b66 commit aedd5b8
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 2 deletions.
1 change: 0 additions & 1 deletion server/src/controllers/rest/devices/devicestats.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { API } from 'ssm-shared-lib';
import DeviceRepo from '../../../data/database/repository/DeviceRepo';
import { InternalError, NotFoundError } from '../../../middlewares/api/ApiError';
import { SuccessResponse } from '../../../middlewares/api/ApiResponse';
Expand Down
57 changes: 56 additions & 1 deletion server/src/services/DeviceStatsUseCases.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { StatsType, Systeminformation } from 'ssm-shared-lib';
import { DateTime } from 'luxon';
import Device from '../data/database/model/Device';
import ContainerRepo from '../data/database/repository/ContainerRepo';
import { updateQueue } from '../helpers/queue/queueManager';
Expand Down Expand Up @@ -27,6 +28,11 @@ interface DeviceSystemInfo {
};
}

interface DeviceStat {
date: string;
value: number;
}

// Constants
const BYTES_IN_MB = 1024 * 1024;

Expand Down Expand Up @@ -111,6 +117,54 @@ async function createStatIfMinInterval(
await createDeviceStatFromJson(deviceInfo, device);
}

async function getStatsByDeviceAndType(
device: Device,
from: number,
type?: string,
): Promise<DeviceStat[] | null> {
logger.info(`getStatsByDeviceAndType - type: ${type}, from: ${from}, device: ${device.uuid}`);

if (!type) {
throw new Error('Type is required');
}

if (!device?.uuid) {
throw new Error('Device UUID is required');
}

try {
// Calculate time range
const toDate = DateTime.now().toJSDate();
const fromDate = DateTime.now().minus({ hours: from }).toJSDate();

const result = await prometheusService.queryDeviceMetrics(
type as StatsType.DeviceStatsType,
[device.uuid],
{ from: fromDate, to: toDate },
);

if (!result.success) {
logger.error(`Failed to get stats: ${result.error}`);
return null;
}

if (!result.data) {
return null;
}

// Transform the data into DeviceStat format
return result.data
.map((item) => ({
date: item.date,
value: parseFloat(item.value),
}))
.sort((a, b) => a.date.localeCompare(b.date));
} catch (error) {
logger.error(`Error getting stats for device ${device.uuid}:`, error);
return null;
}
}

async function getStatsByDevicesAndType(
devices: Device[],
from: Date,
Expand Down Expand Up @@ -206,7 +260,8 @@ async function getStatByDeviceAndType(

export default {
createStatIfMinInterval,
getStatsByDevicesAndType,
getStatsByDeviceAndType,
getStatByDeviceAndType,
getStatsByDevicesAndType,
getSingleAveragedStatsByDevicesAndType,
};

0 comments on commit aedd5b8

Please sign in to comment.