Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: adding a MontoringManager storing statistics for given set of containers #499

Merged
merged 6 commits into from
Mar 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
201 changes: 201 additions & 0 deletions packages/backend/src/managers/monitoringManager.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
/**********************************************************************
* Copyright (C) 2024 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
***********************************************************************/

import { beforeEach, expect, afterEach, test, vi } from 'vitest';
import { MonitoringManager } from './monitoringManager';
import { containerEngine, type ContainerStatsInfo, type Webview } from '@podman-desktop/api';
import { Messages } from '@shared/Messages';

vi.mock('@podman-desktop/api', async () => {
return {
containerEngine: {
statsContainer: vi.fn(),
},
};
});

const webviewMock = {
postMessage: vi.fn(),
} as unknown as Webview;

beforeEach(() => {
vi.resetAllMocks();

vi.mocked(webviewMock.postMessage).mockResolvedValue(undefined);
vi.mocked(containerEngine.statsContainer).mockResolvedValue(undefined);

vi.useFakeTimers();
});

afterEach(() => {
vi.useRealTimers();
});

function simplifiedCallback(callback: (arg: ContainerStatsInfo) => void, cpu: number, ram: number): void {
callback({
cpu_stats: {
cpu_usage: {
total_usage: cpu,
},
},
memory_stats: {
usage: ram,
},
} as unknown as ContainerStatsInfo);
}

test('expect constructor to do nothing', () => {
const manager = new MonitoringManager(webviewMock);
expect(containerEngine.statsContainer).not.toHaveBeenCalled();
expect(manager.getStats().length).toBe(0);
expect(webviewMock.postMessage).not.toHaveBeenCalled();
});

test('expect monitor method to start stats container', async () => {
const manager = new MonitoringManager(webviewMock);
await manager.monitor('randomContainerId', 'dummyEngineId');

expect(containerEngine.statsContainer).toHaveBeenCalledWith('dummyEngineId', 'randomContainerId', expect.anything());
});

test('expect monitor method to start stats container', async () => {
const manager = new MonitoringManager(webviewMock);
await manager.monitor('randomContainerId', 'dummyEngineId');

expect(containerEngine.statsContainer).toHaveBeenCalledWith('dummyEngineId', 'randomContainerId', expect.anything());
});

test('expect dispose to dispose stats container', async () => {
const manager = new MonitoringManager(webviewMock);
const fakeDisposable = vi.fn();
vi.mocked(containerEngine.statsContainer).mockResolvedValue({
dispose: fakeDisposable,
});

await manager.monitor('randomContainerId', 'dummyEngineId');

manager.dispose();
expect(fakeDisposable).toHaveBeenCalled();
});

test('expect webview to be notified when statsContainer call back', async () => {
const manager = new MonitoringManager(webviewMock);
let mCallback: (stats: ContainerStatsInfo) => void;
vi.mocked(containerEngine.statsContainer).mockImplementation(async (_engineId, _id, callback) => {
mCallback = callback;
return { dispose: () => {} };
});

await manager.monitor('randomContainerId', 'dummyEngineId');
await vi.waitFor(() => {
expect(mCallback).toBeDefined();
});

const date = new Date(2000, 1, 1, 13);
vi.setSystemTime(date);

simplifiedCallback(mCallback, 123, 99);

expect(webviewMock.postMessage).toHaveBeenCalledWith({
id: Messages.MSG_MONITORING_UPDATE,
body: [
{
containerId: 'randomContainerId',
stats: [
{
timestamp: Date.now(),
cpu_usage: 123,
memory_usage: 99,
},
],
},
],
});
});

test('expect stats to cumulate', async () => {
const manager = new MonitoringManager(webviewMock);
let mCallback: (stats: ContainerStatsInfo) => void;
vi.mocked(containerEngine.statsContainer).mockImplementation(async (_engineId, _id, callback) => {
mCallback = callback;
return { dispose: () => {} };
});

await manager.monitor('randomContainerId', 'dummyEngineId');
await vi.waitFor(() => {
expect(mCallback).toBeDefined();
});

simplifiedCallback(mCallback, 0, 0);
simplifiedCallback(mCallback, 1, 1);
simplifiedCallback(mCallback, 2, 2);
simplifiedCallback(mCallback, 3, 3);

const stats = manager.getStats();
expect(stats.length).toBe(1);
expect(stats[0].stats.length).toBe(4);
});

test('expect old stats to be removed', async () => {
const manager = new MonitoringManager(webviewMock);
let mCallback: (stats: ContainerStatsInfo) => void;
vi.mocked(containerEngine.statsContainer).mockImplementation(async (_engineId, _id, callback) => {
mCallback = callback;
return { dispose: () => {} };
});

await manager.monitor('randomContainerId', 'dummyEngineId');
await vi.waitFor(() => {
expect(mCallback).toBeDefined();
});

vi.setSystemTime(new Date(2000, 1, 1, 13));

simplifiedCallback(mCallback, 0, 0);

vi.setSystemTime(new Date(2005, 1, 1, 13));

simplifiedCallback(mCallback, 1, 1);
simplifiedCallback(mCallback, 2, 2);
simplifiedCallback(mCallback, 3, 3);

const stats = manager.getStats();
expect(stats.length).toBe(1);
expect(stats[0].stats.length).toBe(3);
});

test('expect stats to be disposed if stats result is an error', async () => {
const manager = new MonitoringManager(webviewMock);
let mCallback: (stats: ContainerStatsInfo) => void;
const fakeDisposable = vi.fn();
vi.mocked(containerEngine.statsContainer).mockImplementation(async (_engineId, _id, callback) => {
mCallback = callback;
return { dispose: fakeDisposable };
});

await manager.monitor('randomContainerId', 'dummyEngineId');
await vi.waitFor(() => {
expect(mCallback).toBeDefined();
});

mCallback({ cause: 'container is stopped' } as unknown as ContainerStatsInfo);

const stats = manager.getStats();
expect(stats.length).toBe(0);
expect(fakeDisposable).toHaveBeenCalled();
});
90 changes: 90 additions & 0 deletions packages/backend/src/managers/monitoringManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/**********************************************************************
* Copyright (C) 2024 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
***********************************************************************/
import { type Disposable, type Webview, containerEngine, type ContainerStatsInfo } from '@podman-desktop/api';
import { Publisher } from '../utils/Publisher';
import { Messages } from '@shared/Messages';

export interface StatsInfo {
timestamp: number;
cpu_usage: number;
memory_usage: number;
}

export interface StatsHistory {
containerId: string;
stats: StatsInfo[];
}

export const MAX_AGE: number = 5 * 60 * 1000; // 5 minutes

export class MonitoringManager extends Publisher<StatsHistory[]> implements Disposable {
#containerStats: Map<string, StatsHistory>;
#disposables: Disposable[];

constructor(webview: Webview) {
super(webview, Messages.MSG_MONITORING_UPDATE, () => this.getStats());
this.#containerStats = new Map<string, StatsHistory>();
this.#disposables = [];
}

async monitor(containerId: string, engineId: string): Promise<Disposable> {
const disposable = await containerEngine.statsContainer(engineId, containerId, statsInfo => {
if ('cause' in statsInfo) {
console.error('Cannot stats container', statsInfo.cause);
disposable.dispose();
} else {
this.push(containerId, statsInfo);
}
});
this.#disposables.push(disposable);
return disposable;
}

private push(containerId: string, statsInfo: ContainerStatsInfo): void {
let stats: StatsInfo[] = [];
if (this.#containerStats.has(containerId)) {
const limit = Date.now() - MAX_AGE;
stats = this.#containerStats.get(containerId).stats.filter(stats => stats.timestamp > limit);
}

this.#containerStats.set(containerId, {
containerId: containerId,
stats: [
...stats,
{
timestamp: Date.now(),
cpu_usage: statsInfo.cpu_stats.cpu_usage.total_usage,
memory_usage: statsInfo.memory_stats.usage,
},
],
});
this.notify();
}

clear(containerId: string): void {
this.#containerStats.delete(containerId);
}

getStats(): StatsHistory[] {
return Array.from(this.#containerStats.values());
}

dispose(): void {
this.#disposables.forEach(disposable => disposable.dispose());
}
}
1 change: 1 addition & 0 deletions packages/shared/Messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,6 @@ export enum Messages {
MSG_APPLICATIONS_STATE_UPDATE = 'applications-state-update',
MSG_LOCAL_REPOSITORY_UPDATE = 'local-repository-update',
MSG_INFERENCE_SERVERS_UPDATE = 'inference-servers-update',
MSG_MONITORING_UPDATE = 'monitoring-update',
MSG_SUPPORTED_LANGUAGES_UPDATE = 'supported-languages-supported',
}