| 201 | } |
| 202 | |
| 203 | export class CgroupV1Source implements MachineStatsSource { |
| 204 | public readonly name = 'cgroup-v1'; |
| 205 | protected log = new Logger('hardware'); |
| 206 | protected lastSample: Sample | null = null; |
| 207 | protected loggedFailure: Set<string> = new Set(); |
| 208 | |
| 209 | protected now: () => number; |
| 210 | protected readFile: ReadFileFn; |
| 211 | |
| 212 | constructor(opts: CgroupSourceOpts = {}) { |
| 213 | this.now = opts.now ?? Date.now; |
| 214 | this.readFile = opts.readFile ?? defaultReadFile; |
| 215 | } |
| 216 | |
| 217 | public async read(): Promise<IResourceLoad> { |
| 218 | const [cpu, memory] = await Promise.all([ |
| 219 | this.readCpu(), |
| 220 | this.readMemory(), |
| 221 | ]); |
| 222 | return { cpu, memory }; |
| 223 | } |
| 224 | |
| 225 | protected async readCpu(): Promise<number | null> { |
| 226 | let usageNsContent: string; |
| 227 | let quotaContent: string; |
| 228 | let periodContent: string; |
| 229 | try { |
| 230 | [usageNsContent, quotaContent, periodContent] = await Promise.all([ |
| 231 | readWithTimeout('/sys/fs/cgroup/cpu/cpuacct.usage', this.readFile), |
| 232 | readWithTimeout('/sys/fs/cgroup/cpu/cpu.cfs_quota_us', this.readFile), |
| 233 | readWithTimeout('/sys/fs/cgroup/cpu/cpu.cfs_period_us', this.readFile), |
| 234 | ]); |
| 235 | } catch (err) { |
| 236 | this.logOnce('cpu-read', err); |
| 237 | return null; |
| 238 | } |
| 239 | |
| 240 | const usageNs = Number(usageNsContent.trim()); |
| 241 | const cores = parseCpuV1Quota(quotaContent, periodContent); |
| 242 | if (!Number.isFinite(usageNs) || cores === null || cores <= 0) { |
| 243 | this.logOnce('cpu-parse', new Error('cgroup v1 cpu parse failed')); |
| 244 | return null; |
| 245 | } |
| 246 | |
| 247 | const usageUsec = usageNs / 1000; |
| 248 | const timestamp = this.now(); |
| 249 | const previous = this.lastSample; |
| 250 | this.lastSample = { usageUsec, timestamp }; |
| 251 | if (!previous) return null; |
| 252 | |
| 253 | const dWallMs = timestamp - previous.timestamp; |
| 254 | if (dWallMs <= 0) return null; |
| 255 | const dUsageUsec = usageUsec - previous.usageUsec; |
| 256 | if (dUsageUsec < 0) return null; |
| 257 | |
| 258 | return dUsageUsec / (dWallMs * cores * 1000); |
| 259 | } |
| 260 |
nothing calls this directly
no outgoing calls
no test coverage detected