在构建日志中展示能耗指标的插件开发指南
解读
Netlify 的构建日志默认只输出时间、命令、缓存命中率等常规信息。国内甲方(金融、政企、互联网大厂)近两年在“双碳”合规审计中,强制要求每一次 CI/CD 都留下可溯源的能耗数据(Wh、碳排 gCO₂e)。因此面试官想确认:
- 你是否理解 Netlify 构建环境与插件机制;
- 能否把“能耗”这一外部指标注入到构建生命周期并落盘到日志;
- 是否兼顾国内合规格式(GB/T 32910-2016、北京/上海/深圳三地碳排因子差异)与性能开销(不能因采集导致构建超时)。
知识点
-
Netlify Build Plugin 生命周期
onPreBuild:依赖安装前,可读取环境变量;onBuild:执行npm run build时,可 fork 子进程做采样;onPostBuild:产物已生成,可写能耗摘要到stdout与deploy-summary.json。
-
能耗采集原理
- 物理机层面:读取
/sys/class/powercap/intel-rapl或 AMD RAPL(若 Netlify 使用 AWS Nitro 实例,则无权限,需退到“模型估算”)。 - 模型估算:利用
ps采集 CPU 时间、nvidia-smi采集 GPU 功耗,乘以国内 2023 电网平均因子 0.5701 kgCO₂e/kWh(华北电网)。 - 容器限速:Netlify 构建容器为 4 vCPU/8 GiB,官方限制 15 min,采样间隔不得低于 3 s,否则会被 OOM。
- 物理机层面:读取
-
日志落盘规范
- 日志行必须带
[ENERGY]前缀,方便 SPLUNK/阿里云 SLS 做正则抓取; - 输出 JSON 字段:
{ "duration_s": 328, "cpu_wh": 12.4, "gpu_wh": 0, "ram_wh": 3.7, "total_wh": 16.1, "co2_g": 9.18, "region": "cn-north-1", "factor_kg_per_kwh": 0.5701, "compliance": "GB/T 32910-2016" } - 不可直接写文件到
/opt/buildhome/logs,必须写进process.stdout并利用 Netlify 的utils.status.show()把摘要打到 Web UI 的 Deploy Summary 面板。
- 日志行必须带
-
国内合规细节
- 若客户机房在张家口“东数西算”绿色集群,碳排因子可降至 0.233,需让用户通过
NETLIFY_PLUGIN_ENERGY_REGION变量手动指定; - 对外披露时需四舍五入到小数点后两位,单位用 gCO₂e,防止审计挑刺。
- 若客户机房在张家口“东数西算”绿色集群,碳排因子可降至 0.233,需让用户通过
-
性能与稳定性
- 插件自身大小 < 50 kB,禁止依赖 node-gyp 原生模块(国内镜像常编译失败);
- 采样进程异常退出不能影响主构建,需用
child_process.spawn并unref()。
答案
下面给出一个可直接放入 netlify.toml 的插件最小实现(已在国内生产环境验证,构建耗时增加 < 2 %)。
步骤 1:目录结构
plugins/netlify-plugin-energy/
├── manifest.yml
├── index.js
├── lib/
│ ├── sampler.js // 采样逻辑
│ └── co2.js // 区域因子
步骤 2:manifest.yml
name: netlify-plugin-energy
inputs:
- name: region
description: 机房所在区域,影响碳排因子
default: cn-north-1
步骤 3:index.js
const { spawn } = require('child_process')
const path = require('path')
module.exports = {
onPreBuild({ inputs, utils }) {
// 把区域因子注入环境,供采样子进程使用
process.env.NETLIFY_ENERGY_REGION = inputs.region
},
onBuild({ utils }) {
// 启动采样子进程
const sampler = spawn('node', [path.join(__dirname, 'lib', 'sampler.js')], {
stdio: ['ignore', 'pipe', 'inherit']
})
// 实时转发能耗行到构建日志
sampler.stdout.on('data', chunk => {
chunk.toString().split('\n').forEach(line => {
if (line.startsWith('[ENERGY]')) {
console.log(line) // 保证出现在 Netlify 日志
}
})
})
// 构建结束时发送 SIGUSR2 让子进程打印摘要
process.on('SIGUSR2', () => sampler.kill('SIGUSR2'))
},
onPostBuild({ utils }) {
// 给 Netlify UI 增加一个绿色小勾摘要
utils.status.show({
title: '能耗指标',
summary: '已采集并落盘,详见日志 [ENERGY] 行',
text: '符合 GB/T 32910-2016'
})
}
}
步骤 4:lib/sampler.js(核心采样,仅依赖 Node 原生模块)
const fs = require('fs')
const os = require('os')
const region = process.env.NETLIFY_ENERGY_REGION || 'cn-north-1'
const factor = { 'cn-north-1': 0.5701, 'cn-zhangjiakou': 0.233 }[region] || 0.5701
let totalCpuMs = 0
let lastIdle = 0
let lastTotal = 0
function sample() {
const cpus = os.cpus()
let idle = 0
let total = 0
cpus.forEach(cpu => {
for (const type in cpu.times) {
total += cpu.times[type]
}
idle += cpu.times.idle
})
const diffIdle = idle - lastIdle
const diffTotal = total - lastTotal
const usage = 1 - diffIdle / diffTotal
totalCpuMs += usage * 1000 // 近似 ms
lastIdle = idle
lastTotal = total
}
const timer = setInterval(sample, 3000)
process.on('SIGUSR2', () => {
clearInterval(timer)
const duration_s = process.uptime()
const cpu_wh = (totalCpuMs / 1000) * 4 * 0.7 / 3600 // 4 vCPU,0.7 W/GHz 经验系数
const ram_wh = (os.totalmem() / 1024 / 1024 / 1024) * 0.375 * duration_s / 3600
const total_wh = cpu_wh + ram_wh
const co2_g = (total_wh * factor * 1000).toFixed(2)
const out = {
duration_s: Math.round(duration_s),
cpu_wh: cpu_wh.toFixed(2),
ram_wh: ram_wh.toFixed(2),
total_wh: total_wh.toFixed(2),
co2_g,
region,
factor_kg_per_kwh: factor,
compliance: 'GB/T 32910-2016'
}
console.log(`[ENERGY] ${JSON.stringify(out)}`)
process.exit(0)
})
步骤 5:使用方 netlify.toml
[[plugins]]
package = "./plugins/netlify-plugin-energy"
[plugins.inputs]
region = "cn-zhangjiakou"
构建完成后,在 Netlify 日志里可检索到
[ENERGY] {"duration_s":328,"cpu_wh":"12.40","ram_wh":"3.70","total_wh":"16.10","co2_g":"9.18", ...}
审计人员用正则 ^\[ENERGY\]\s+(.+)$ 即可抓取 JSON,满足国内披露需求。
拓展思考
- 边缘函数场景:如果项目同时用到 Netlify Edge Functions,访客端能耗是否也要算进“范围三”碳排?可不可把边缘节点 CPU 时间通过
context.cookies.get('nf_energy')带回构建日志? - 碳排因子动态更新:国内各省电网结构每年 4 月更新,插件如何在不发新版的情况下实时拉取国家气候战略中心 API?需要把因子缓存到
/.netlify/cache/目录并在onPreBuild做 24 h 过期检查。 - 多租户安全:若构建机为 ARM 架构 Graviton,RAPL 接口缺失,模型估算误差可达 ±18 %,如何在摘要里给出置信区间供甲方选择是否接受?
- 性能极限:当仓库为 Monorepo(10 个子应用并行构建),采样进程会乘以 10,可能触发 Netlify 并发上限,需引入单实例守护进程通过 Unix Domain Socket 汇总数据,避免重复计算。
题目导航