Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/comm/project-status/utils.ts
5770 views
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import type {
7
CGroup,
8
DiskUsageInfo,
9
} from "@cocalc/util/types/project-info/types";
10
11
/**
12
* Calculate resource usage statistics from cgroup data.
13
*
14
* This function processes cgroup resource information and calculates usage percentages
15
* for both memory and CPU. It works with both cgroup v1 and v2 data structures,
16
* handling the unified CGroup interface that abstracts the differences between versions.
17
*/
18
export function cgroup_stats(cg: CGroup, du?: DiskUsageInfo) {
19
// DiskUsage for /tmp – add to memory usage since it's already been
20
// calculated appropriately by the backend based on whether /tmp is tmpfs
21
const mem_rss = cg.mem_stat.total_rss + (du?.usage ?? 0);
22
const mem_tot = cg.mem_stat.hierarchical_memory_limit;
23
24
// Handle unlimited (-1) and zero memory limits to avoid division by zero
25
const mem_pct = mem_tot <= 0 ? 0 : 100 * Math.min(1, mem_rss / mem_tot);
26
27
// Handle unlimited (-1) and zero CPU limits to avoid division by zero
28
const cpu_pct =
29
cg.cpu_cores_limit <= 0
30
? 0
31
: 100 * Math.min(1, cg.cpu_usage_rate / cg.cpu_cores_limit);
32
33
const cpu_tot = cg.cpu_usage; // seconds
34
return { mem_rss, mem_tot, mem_pct, cpu_pct, cpu_tot };
35
}
36
37