feat(integrations): add beszel system usage integration

This commit is contained in:
Thomas Camlong committed 2026-06-08 12:43:45 +02:00
1 parent 87d3f6a0a1
commit ae294b9d88
28 files changed
+955 -2

No files matched your search

@@ -2,6 +2,7 @@ import type { IntegrationKind } from "@homarr/definitions";
import { AdGuardHomeIntegration } from "../adguard-home/adguard-home-integration";
import { AnchorIntegration } from "../anchor/anchor-integration";
import { BeszelIntegration } from "../beszel/beszel-integration";
import { CodebergIntegration } from "../codeberg/codeberg-integration";
import { CoolifyIntegration } from "../coolify/coolify-integration";
import { DashDotIntegration } from "../dashdot/dashdot-integration";
@@ -116,6 +117,7 @@ export const integrationCreators = {
ntfy: NTFYIntegration,
mock: MockIntegration,
truenas: TrueNasIntegration,
beszel: BeszelIntegration,
unraid: UnraidIntegration,
coolify: CoolifyIntegration,
tracearr: TracearrIntegration,
@@ -0,0 +1,143 @@
import type { fetch as undiciFetch } from "undici";
import z from "zod";
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
import { ResponseError } from "@homarr/common/server";
import { HandleIntegrationErrors } from "../base/errors/decorator";
import type { IntegrationTestingInput } from "../base/integration";
import { Integration } from "../base/integration";
import type { TestingResult } from "../base/test-connection/test-connection-service";
import type { ISystemUsageIntegration } from "../interfaces/system-usage/system-usage-integration";
import type { AgentConnectionType, System, SystemLoadStatus } from "../interfaces/system-usage/system-usage-types";
@HandleIntegrationErrors([])
export class BeszelIntegration extends Integration implements ISystemUsageIntegration {
protected async testingAsync({ fetchAsync }: IntegrationTestingInput): Promise<TestingResult> {
await this.authenticateAsync(fetchAsync);
return { success: true as const };
}
public async getSystemsAsync() {
const token = await this.authenticateAsync();
const response = await this.fetchApi("/api/collections/systems/records?perPage=500", token);
const data = z.object({ items: z.array(systemSchema) }).parse(response);
return data.items.map((system) => ({
id: system.id,
name: system.name,
}));
}
public async getSystemDetailsAsync(id: string): Promise<System> {
const token = await this.authenticateAsync();
const response = await this.fetchApi(`/api/collections/systems/records/${id}`, token);
const system = systemSchema.parse(response);
return {
id: system.id,
name: system.name,
status: system.status,
agent: {
connectionType: system.info.ct !== undefined ? (connectionTypeByCode[system.info.ct] ?? null) : null,
version: system.info.v,
},
usage: {
cpuPercentage: system.info.cpu,
memoryPercentage: system.info.mp,
diskPercentage: system.info.dp,
gpuPercentage: system.info.g ?? null,
load: {
status: this.calculateLoadStatus(system.status, system.info.la, system.info.t),
averages: {
one: system.info.la[0],
five: system.info.la[1],
fifteen: system.info.la[2],
},
},
networkBytes: system.info.bb,
temperature: system.info.dt ?? null,
},
};
}
private calculateLoadStatus(
systemStatus: BeszelSystem["status"],
loadAverages: [number, number, number],
threatCount: number | undefined,
): SystemLoadStatus {
if (systemStatus !== "up") return "unknown";
const maxLoad = Math.max(...loadAverages);
const loadPerThread = maxLoad / (threatCount ?? 1);
const meter = loadPerThread * 100;
if (meter >= 90) return "critical";
if (meter >= 65) return "warning";
return "good";
}
private async fetchApi(
path: string,
token: string,
customFetch: typeof undiciFetch = fetchWithTrustedCertificatesAsync,
) {
const response = await customFetch(this.url(path).toString(), {
headers: { Authorization: token },
});
if (!response.ok) {
throw new ResponseError(response);
}
return await response.json();
}
private async authenticateAsync(customFetch: typeof undiciFetch = fetchWithTrustedCertificatesAsync) {
const response = await customFetch(this.url("/api/collections/users/auth-with-password").toString(), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
identity: this.getSecretValue("username"),
password: this.getSecretValue("password"),
}),
});
if (!response.ok) {
// PocketBase returns 400 for failed auth — remap to 401 for proper authorization error classification
const status = response.status === 400 ? 401 : response.status;
throw new ResponseError({ status, url: response.url });
}
const data = authResponseSchema.parse(await response.json());
return data.token;
}
}
const connectionTypeByCode: Record<number, AgentConnectionType> = {
1: "ssh",
2: "webSocket",
};
const authResponseSchema = z.object({
token: z.string(),
});
const systemStatus = ["up", "down", "paused", "pending"] as const;
/**
* See https://github.com/henrygd/beszel/blob/cca7b360395e3e7e4ef870005efddc3bd75b86c4/internal/entities/system/system.go#L104
*/
const systemSchema = z.object({
id: z.string(),
info: z.object({
cpu: z.number(),
mp: z.number(),
dp: z.number(),
g: z.number().optional(),
la: z.tuple([z.number(), z.number(), z.number()]),
bb: z.number(),
dt: z.number().optional(),
v: z.string(),
ct: z.number().optional(),
t: z.number().optional(),
}),
name: z.string(),
status: z.enum(systemStatus),
});
type BeszelSystem = z.infer<typeof systemSchema>;
@@ -0,0 +1,6 @@
import type { System } from "./system-usage-types";
export interface ISystemUsageIntegration {
getSystemsAsync(): Promise<Pick<System, "id" | "name">[]>;
getSystemDetailsAsync(id: System["id"]): Promise<System>;
}
@@ -0,0 +1,31 @@
export type SystemLoadStatus = "good" | "warning" | "critical" | "unknown";
export type SystemStatus = "up" | "down" | "paused" | "pending";
export type AgentConnectionType = "ssh" | "webSocket";
export interface System {
id: string;
name: string;
status: SystemStatus;
usage: SystemUsage;
agent: {
connectionType: AgentConnectionType | null;
version: string;
};
}
export interface SystemUsage {
cpuPercentage: number;
memoryPercentage: number;
diskPercentage: number;
gpuPercentage: number | null;
load: {
status: SystemLoadStatus;
averages: {
one: number;
five: number;
fifteen: number;
};
};
networkBytes: number;
temperature: number | null;
}
@@ -0,0 +1,38 @@
import type { ISystemUsageIntegration } from "../../interfaces/system-usage/system-usage-integration";
import type { System } from "../../types";
export class SystemUsageMockService implements ISystemUsageIntegration {
async getSystemsAsync(): Promise<Pick<System, "id" | "name">[]> {
return await Promise.resolve([
{ id: "1", name: "Mock System 1" },
{ id: "2", name: "Mock System 2" },
]);
}
async getSystemDetailsAsync(id: System["id"]): Promise<System> {
return await Promise.resolve({
id,
name: `Mock System ${id}`,
status: "up",
agent: {
connectionType: "webSocket",
version: "1.0.0",
},
usage: {
cpuPercentage: 25,
memoryPercentage: 50,
diskPercentage: 75,
gpuPercentage: null,
load: {
status: "good",
averages: {
one: 0.5,
five: 0.7,
fifteen: 0.9,
},
},
networkBytes: Math.floor(2 ** 24.5),
temperature: 55,
},
});
}
}
@@ -15,6 +15,7 @@ import type { IMediaServerIntegration } from "../interfaces/media-server/media-s
import type { IMediaTranscodingIntegration } from "../interfaces/media-transcoding/media-transcoding-integration";
import type { NetworkControllerSummaryIntegration } from "../interfaces/network-controller-summary/network-controller-summary-integration";
import type { ISmartHomeIntegration } from "../interfaces/smart-home/smart-home-integration";
import type { ISystemUsageIntegration } from "../interfaces/system-usage/system-usage-integration";
import type { IUpsSummaryIntegration } from "../interfaces/ups-summary/ups-summary-integration";
import { CalendarMockService } from "./data/calendar";
import { ClusterHealthMonitoringMockService } from "./data/cluster-health-monitoring";
@@ -29,6 +30,7 @@ import { NetworkControllerSummaryMockService } from "./data/network-controller-s
import { NotificationsMockService } from "./data/notifications";
import { SmartHomeMockService } from "./data/smart-home";
import { SystemHealthMonitoringMockService } from "./data/system-health-monitoring";
import { SystemUsageMockService } from "./data/system-usage";
import { UpsSummaryMockService } from "./data/ups-summary";
export class MockIntegration
@@ -46,6 +48,7 @@ export class MockIntegration
IMediaTranscodingIntegration,
NetworkControllerSummaryIntegration,
ISmartHomeIntegration,
ISystemUsageIntegration,
IUpsSummaryIntegration
{
private static readonly dnsHole = new DnsHoleMockService();
@@ -61,6 +64,7 @@ export class MockIntegration
private static readonly networkController = new NetworkControllerSummaryMockService();
private static readonly notifications = new NotificationsMockService();
private static readonly smartHome = new SmartHomeMockService();
private static readonly systemUsage = new SystemUsageMockService();
private static readonly upsSummary = new UpsSummaryMockService();
protected async testingAsync(_: IntegrationTestingInput): Promise<TestingResult> {
@@ -130,4 +134,8 @@ export class MockIntegration
// UpsSummaryIntegration
getUpsSummariesAsync = MockIntegration.upsSummary.getUpsSummariesAsync.bind(MockIntegration.upsSummary);
// SystemUsageIntegration
getSystemsAsync = MockIntegration.systemUsage.getSystemsAsync.bind(MockIntegration.systemUsage);
getSystemDetailsAsync = MockIntegration.systemUsage.getSystemDetailsAsync.bind(MockIntegration.systemUsage);
}
+1
View File
@@ -18,3 +18,4 @@ export * from "./interfaces/timetable/timetable-types";
export * from "./tracearr/tracearr-types";
export * from "./speedtest-tracker/speedtest-tracker-types";
export * from "./umami/umami-types";
export * from "./interfaces/system-usage/system-usage-types";
+176
View File
@@ -0,0 +1,176 @@
import { rmdir } from "fs/promises";
import { join } from "path";
import type { StartedTestContainer } from "testcontainers";
import { GenericContainer, Wait } from "testcontainers";
import { afterAll, beforeAll, describe, expect, test, vi } from "vitest";
import { createId } from "@homarr/common";
import { createDb } from "@homarr/db/test";
import { BeszelIntegration } from "../src/beszel/beszel-integration";
vi.mock("@homarr/db", async (importActual) => {
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const actual = await importActual<typeof import("@homarr/db")>();
return {
...actual,
db: createDb(),
};
});
const email = "e2e@homarr.dev";
const password = "12341234";
const publicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAID5PFut0emFoQQ53LlLGfFYA/U1Noe6WPqYN/97LJTvR";
const token = "4af8b512-afdc-4e42-a478-d0a3bfbbb4a8";
const IMAGE_NAME = "henrygd/beszel:latest";
const AGENT_IMAGE_NAME = "henrygd/beszel-agent:latest";
const systemId = "nj259tge7e4h7xy";
describe("Beszel integration", () => {
let socketPathId: string;
let beszelContainer: StartedTestContainer;
let beszelAgentContainer: StartedTestContainer;
beforeAll(async () => {
socketPathId = createId();
beszelContainer = await createBeszelContainer(socketPathId).start();
beszelAgentContainer = await createBeszelAgentContainer(socketPathId, beszelContainer.getMappedPort(8090)).start();
await new Promise((resolve) => setTimeout(resolve, 5_000)); // Wait for Beszel to be ready and have some system_data
}, 20_000);
afterAll(async () => {
await beszelContainer.stop();
await beszelAgentContainer.stop();
await rmdir(createSocketPath(socketPathId), { recursive: true });
}, 5_000);
test("Test connection is successful", async () => {
// Arrange
const integration = createIntegration(beszelContainer.getMappedPort(8090));
// Act
const result = await integration.testConnectionAsync();
// Assert
expect(result.success).toBe(true);
});
test("Test connection fails with invalid credentials", async () => {
// Arrange
const integration = createIntegration(beszelContainer.getMappedPort(8090), {
password: "wrongpassword",
});
// Act
const result = await integration.testConnectionAsync();
// Assert
expect(result.success).toBe(false);
if (result.success) return;
expect(result.error.type).toBe("authorization");
});
test("Can get systems", async () => {
// Arrange
const integration = createIntegration(beszelContainer.getMappedPort(8090));
// Act
const systems = await integration.getSystemsAsync();
// Assert
expect(systems.length).toBe(1);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
expect(systems[0]!.name).toBe("localhost");
});
test("Can get system details", async () => {
// Arrange
const integration = createIntegration(beszelContainer.getMappedPort(8090));
// Act
const system = await integration.getSystemDetailsAsync(systemId);
// Assert
expect(system.id).toBe(systemId);
expect(system.name).toBe("localhost");
expect(system.agent.connectionType).toBe("webSocket");
expect(system.agent.version).toBeDefined();
expect(system.status).toBe("up");
expect(system.usage.cpuPercentage).toBeGreaterThanOrEqual(0);
expect(system.usage.memoryPercentage).toBeGreaterThanOrEqual(0);
expect(system.usage.diskPercentage).toBeGreaterThanOrEqual(0);
expect(system.usage.load.averages.one).toBeGreaterThanOrEqual(0);
expect(system.usage.networkBytes).toBeGreaterThanOrEqual(0);
});
});
const createIntegration = (port: number, overrides: { hostname?: string; password?: string } = {}) =>
new BeszelIntegration({
id: createId(),
name: "Beszel E2E",
url: `http://${overrides.hostname ?? "localhost"}:${port}`,
externalUrl: null,
decryptedSecrets: [
{
kind: "username",
value: email,
},
{
kind: "password",
value: overrides.password ?? password,
},
],
});
const files = ["data.db", "data.db-shm", "data.db-wal", "id_ed25519"];
const createBeszelContainer = (id: string) => {
return new GenericContainer(IMAGE_NAME)
.withCopyFilesToContainer(
files.map((file) => ({
source: join(__dirname, `/volumes/beszel/${file}`),
target: `/beszel_data/${file}`,
})),
)
.withExposedPorts(8090)
.withBindMounts([
{
source: createSocketPath(id),
target: "/beszel_socket",
mode: "rw",
},
])
.withWaitStrategy(Wait.forHttp("/", 8090));
};
const createBeszelAgentContainer = (id: string, port: number) => {
return new GenericContainer(AGENT_IMAGE_NAME)
.withBindMounts([
{
source: "/var/run/docker.sock",
target: "/var/run/docker.sock",
mode: "ro",
},
{
source: createSocketPath(id),
target: "/beszel_socket",
mode: "rw",
},
])
.withEnvironment({
LISTEN: "/beszel_socket/beszel.sock",
HUB_URL: `http://host.docker.internal:${port}`,
TOKEN: token,
KEY: publicKey,
})
.withExtraHosts([
{
// This enabled the usage of host.docker.internal as hostname in the container
host: "host.docker.internal",
ipAddress: "host-gateway",
},
]);
};
const createSocketPath = (id: string) => join(__dirname, `/volumes/beszel/socket-${id}`);
Binary file not shown.
@@ -0,0 +1,7 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtz
c2gtZWQyNTUxOQAAACA+TxbrdHphaEEOdy5SxnxWAP1NTaHulj6mDf/eyyU70QAA
AIgMmaMFDJmjBQAAAAtzc2gtZWQyNTUxOQAAACA+TxbrdHphaEEOdy5SxnxWAP1N
TaHulj6mDf/eyyU70QAAAEBgdIVB4OrfE2cUkVn7lpqtyq+XRq2rxzq01U1DPHB+
fj5PFut0emFoQQ53LlLGfFYA/U1Noe6WPqYN/97LJTvRAAAAAAECAwQF
-----END OPENSSH PRIVATE KEY-----