|
| 1 | +import { Injectable, Logger } from '@nestjs/common'; |
| 2 | +import { readFileSync } from 'fs'; |
| 3 | +import * as os from 'os'; |
| 4 | + |
| 5 | +interface CpuStatSnapshot { |
| 6 | + usageUsec: number; |
| 7 | + nrPeriods: number; |
| 8 | + nrThrottled: number; |
| 9 | + timestampMs: number; |
| 10 | +} |
| 11 | + |
| 12 | +interface ProcessCpuSnapshot { |
| 13 | + cpuSecondsTotal: number; |
| 14 | + timestampMs: number; |
| 15 | +} |
| 16 | + |
| 17 | +/** |
| 18 | + * Reads container-aware CPU metrics with ordered fallbacks: |
| 19 | + * 1) cgroups v2 cpu.stat (container-level) |
| 20 | + * 2) Prometheus process_cpu_seconds_total scrape (optional) |
| 21 | + * 3) host loadavg (last resort) |
| 22 | + */ |
| 23 | +@Injectable() |
| 24 | +export class ContainerCpuMetricsService { |
| 25 | + private readonly logger = new Logger(ContainerCpuMetricsService.name); |
| 26 | + private readonly cpuStatPath = '/sys/fs/cgroup/cpu.stat'; |
| 27 | + private previousCpuStatSnapshot?: CpuStatSnapshot; |
| 28 | + private previousProcessCpuSnapshot?: ProcessCpuSnapshot; |
| 29 | + |
| 30 | + async getCpuLoadRatio(): Promise<number> { |
| 31 | + const cgroupRatio = this.getCgroupCpuLoadRatio(); |
| 32 | + if (cgroupRatio !== null) { |
| 33 | + return cgroupRatio; |
| 34 | + } |
| 35 | + |
| 36 | + const prometheusRatio = await this.getPrometheusCpuLoadRatio(); |
| 37 | + if (prometheusRatio !== null) { |
| 38 | + return prometheusRatio; |
| 39 | + } |
| 40 | + |
| 41 | + return this.getLoadAvgRatio(); |
| 42 | + } |
| 43 | + |
| 44 | + private getCgroupCpuLoadRatio(): number | null { |
| 45 | + try { |
| 46 | + const cpuStat = readFileSync(this.cpuStatPath, 'utf8'); |
| 47 | + const usageUsec = this.readMetric(cpuStat, 'usage_usec'); |
| 48 | + const nrPeriods = this.readMetric(cpuStat, 'nr_periods'); |
| 49 | + const nrThrottled = this.readMetric(cpuStat, 'nr_throttled'); |
| 50 | + |
| 51 | + if (usageUsec === null || nrPeriods === null || nrThrottled === null) { |
| 52 | + return null; |
| 53 | + } |
| 54 | + |
| 55 | + const current: CpuStatSnapshot = { |
| 56 | + usageUsec, |
| 57 | + nrPeriods, |
| 58 | + nrThrottled, |
| 59 | + timestampMs: Date.now(), |
| 60 | + }; |
| 61 | + |
| 62 | + const throttleRatio = nrPeriods > 0 ? this.clamp(nrThrottled / nrPeriods) : 0; |
| 63 | + const cpuCount = Math.max(1, os.cpus().length); |
| 64 | + |
| 65 | + if (!this.previousCpuStatSnapshot) { |
| 66 | + this.previousCpuStatSnapshot = current; |
| 67 | + return throttleRatio; |
| 68 | + } |
| 69 | + |
| 70 | + const elapsedUsec = (current.timestampMs - this.previousCpuStatSnapshot.timestampMs) * 1000; |
| 71 | + const deltaUsageUsec = current.usageUsec - this.previousCpuStatSnapshot.usageUsec; |
| 72 | + this.previousCpuStatSnapshot = current; |
| 73 | + |
| 74 | + if (elapsedUsec <= 0 || deltaUsageUsec < 0) { |
| 75 | + return throttleRatio; |
| 76 | + } |
| 77 | + |
| 78 | + const usageRatio = this.clamp(deltaUsageUsec / elapsedUsec / cpuCount); |
| 79 | + return Math.max(usageRatio, throttleRatio); |
| 80 | + } catch { |
| 81 | + return null; |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + private async getPrometheusCpuLoadRatio(): Promise<number | null> { |
| 86 | + const url = process.env.PROMETHEUS_METRICS_URL; |
| 87 | + if (!url) { |
| 88 | + return null; |
| 89 | + } |
| 90 | + |
| 91 | + try { |
| 92 | + const response = await fetch(url); |
| 93 | + if (!response.ok) { |
| 94 | + this.logger.warn(`Prometheus metrics scrape failed: status=${response.status}`); |
| 95 | + return null; |
| 96 | + } |
| 97 | + |
| 98 | + const metricsText = await response.text(); |
| 99 | + const cpuSecondsTotal = this.readPrometheusProcessCpuSeconds(metricsText); |
| 100 | + if (cpuSecondsTotal === null) { |
| 101 | + return null; |
| 102 | + } |
| 103 | + |
| 104 | + const current: ProcessCpuSnapshot = { cpuSecondsTotal, timestampMs: Date.now() }; |
| 105 | + const cpuCount = Math.max(1, os.cpus().length); |
| 106 | + |
| 107 | + if (!this.previousProcessCpuSnapshot) { |
| 108 | + this.previousProcessCpuSnapshot = current; |
| 109 | + return null; |
| 110 | + } |
| 111 | + |
| 112 | + const elapsedSeconds = |
| 113 | + (current.timestampMs - this.previousProcessCpuSnapshot.timestampMs) / 1000; |
| 114 | + const deltaCpuSeconds = |
| 115 | + current.cpuSecondsTotal - this.previousProcessCpuSnapshot.cpuSecondsTotal; |
| 116 | + this.previousProcessCpuSnapshot = current; |
| 117 | + |
| 118 | + if (elapsedSeconds <= 0 || deltaCpuSeconds < 0) { |
| 119 | + return null; |
| 120 | + } |
| 121 | + |
| 122 | + return this.clamp(deltaCpuSeconds / elapsedSeconds / cpuCount); |
| 123 | + } catch { |
| 124 | + return null; |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + private getLoadAvgRatio(): number { |
| 129 | + const load = os.loadavg()[0]; |
| 130 | + const cpuCount = Math.max(1, os.cpus().length); |
| 131 | + return this.clamp(load / cpuCount); |
| 132 | + } |
| 133 | + |
| 134 | + private readMetric(content: string, key: string): number | null { |
| 135 | + const match = content.match(new RegExp(`^${key}\\s+(\\d+)`, 'm')); |
| 136 | + if (!match) return null; |
| 137 | + |
| 138 | + const parsed = Number(match[1]); |
| 139 | + return Number.isFinite(parsed) ? parsed : null; |
| 140 | + } |
| 141 | + |
| 142 | + private readPrometheusProcessCpuSeconds(metricsText: string): number | null { |
| 143 | + const match = metricsText.match( |
| 144 | + /^process_cpu_seconds_total(?:\{[^}]*\})?\s+([0-9]+(?:\.[0-9]+)?)$/m, |
| 145 | + ); |
| 146 | + if (!match) return null; |
| 147 | + |
| 148 | + const parsed = Number(match[1]); |
| 149 | + return Number.isFinite(parsed) ? parsed : null; |
| 150 | + } |
| 151 | + |
| 152 | + private clamp(value: number): number { |
| 153 | + if (!Number.isFinite(value)) return 0; |
| 154 | + if (value < 0) return 0; |
| 155 | + if (value > 1) return 1; |
| 156 | + return value; |
| 157 | + } |
| 158 | +} |
0 commit comments