从零编写一个采集Nginx stub_status的Exporter并给出主函数骨架
解读
国内云原生面试中,手写 Exporter 是区分“只会用”与“能落地”的核心环节。
Nginx stub_status 模块输出固定 4 行文本,格式简单却覆盖了计数器、Gauge、Histogram 三类语义,非常适合考察候选人对 Prometheus 数据模型、指标类型选择、错误处理、性能、可维护性的综合理解。
面试官通常会在 15~20 分钟内要求:
- 说清 stub_status 的语义映射;
- 现场写出可编译的 main.go 骨架;
- 解释指标命名、标签设计、错误边界、并发安全;
- 给出本地验证步骤(curl /metrics + PromQL)。
任何直接依赖第三方 nginx-exporter 库的行为都会被判 0 分,必须“从零”实现。
知识点
-
stub_status 原始文本格式
Active connections: 42
server accepts handled requests
120000 120000 360000
Reading: 2 Writing: 3 Waiting: 5 -
指标类型选择
- Gauge:active、reading、writing、waiting
- Counter:accepts、handled、requests(单调递增,可计算 rate)
-
Prometheus 客户端库使用
prometheus.NewGaugeVec / NewCounterVec 创建带标签的指标;
prometheus.MustRegister 注册;
promhttp.Handler() 暴露 /metrics。 -
采集逻辑
通过 http.Get 拉取 stub_status;
用 bufio.Scanner 按行解析;
用 regexp 或 fmt.Sscanf 提取数字;
更新指标前必须 Set/Add,保证并发安全(客户端库已加锁)。 -
错误处理
连接超时、404、格式不对都要记录 Error 日志,但绝不能 panic;
指标更新失败时保留上一次成功值,符合 Prometheus 最佳实践。 -
可观测性
自带 exporter 自身指标:exporter_up(1/0)表示采集是否成功;
可暴露 exporter_collect_duration_seconds Histogram,方便 SRE 监控“监控”。 -
国内合规细节
日志统一用 logrus 或 zap,支持 JSON 输出,方便接入 ELK/ Loki;
镜像构建使用国内源(goproxy.cn),Dockerfile 多阶段编译,减小体积。
答案
以下骨架可直接通过 go mod init nginx_stub_exporter && go build 编译运行,依赖仅 prometheus/client_golang。
package main
import (
"bufio"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
const namespace = "nginx_stub"
var (
up = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "up",
Help: "Whether the nginx stub_status endpoint is up (1) or down (0).",
})
connectionsActive = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "connections_active",
Help: "Active client connections.",
})
connectionsReading = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "connections_reading",
Help: "Connections where nginx is reading the request header.",
})
connectionsWriting = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "connections_writing",
Help: "Connections where nginx is writing the response back to the client.",
})
connectionsWaiting = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace,
Name: "connections_waiting",
Help: "Idle client connections.",
})
accepts = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "accepts_total",
Help: "Total client connections accepted.",
})
handled = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "handled_total",
Help: "Total client connections handled.",
})
requests = prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "requests_total",
Help: "Total client requests.",
})
)
type Exporter struct {
uri string
}
func NewExporter(uri string) *Exporter {
return &Exporter{uri: uri}
}
func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
up.Describe(ch)
connectionsActive.Describe(ch)
connectionsReading.Describe(ch)
connectionsWriting.Describe(ch)
connectionsWaiting.Describe(ch)
accepts.Describe(ch)
handled.Describe(ch)
requests.Describe(ch)
}
func (e *Exporter) Collect(ch chan<- prometheus.Metric) {
ok := e.scrape()
if ok {
up.Set(1)
} else {
up.Set(0)
}
up.Collect(ch)
connectionsActive.Collect(ch)
connectionsReading.Collect(ch)
connectionsWriting.Collect(ch)
connectionsWaiting.Collect(ch)
accepts.Collect(ch)
handled.Collect(ch)
requests.Collect(ch)
}
func (e *Exporter) scrape() bool {
resp, err := http.Get(e.uri)
if err != nil {
log.Printf("Error scraping nginx stub_status: %v", err)
return false
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
log.Printf("Non-200 response from nginx stub_status: %d", resp.StatusCode)
return false
}
scanner := bufio.NewScanner(resp.Body)
lineNum := 0
for scanner.Scan() {
line := scanner.Text()
lineNum++
switch lineNum {
case 1:
// Active connections: 42
fields := strings.Fields(line)
if len(fields) != 3 {
log.Printf("Unexpected line 1 format: %s", line)
return false
}
v, err := strconv.ParseFloat(fields[2], 64)
if err != nil {
log.Printf("Error parsing active connections: %v", err)
return false
}
connectionsActive.Set(v)
case 3:
// 120000 120000 360000
fields := strings.Fields(line)
if len(fields) != 3 {
log.Printf("Unexpected line 3 format: %s", line)
return false
}
acc, _ := strconv.ParseFloat(fields[0], 64)
hand, _ := strconv.ParseFloat(fields[1], 64)
req, _ := strconv.ParseFloat(fields[2], 64)
// Counter 只能增加,因此用 Add 而不是 Set
accepts.Add(acc)
handled.Add(hand)
requests.Add(req)
case 4:
// Reading: 2 Writing: 3 Waiting: 5
var read, writ, wait float64
_, err := fmt.Sscanf(line, "Reading: %f Writing: %f Waiting: %f", &read, &writ, &wait)
if err != nil {
log.Printf("Error parsing line 4: %v", err)
return false
}
connectionsReading.Set(read)
connectionsWriting.Set(writ)
connectionsWaiting.Set(wait)
}
}
return scanner.Err() == nil
}
func main() {
uri := os.Getenv("NGINX_STUB_STATUS_URI")
if uri == "" {
uri = "http://127.0.0.1:8080/stub_status"
}
exporter := NewExporter(uri)
prometheus.MustRegister(exporter)
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html><head><title>Nginx Stub Status Exporter</title></head>
<body><h1>Nginx Stub Status Exporter</h1><p><a href="/metrics">Metrics</a></p></body></html>`))
})
listen := ":9113"
log.Printf("Starting nginx_stub_exporter on %s", listen)
log.Fatal(http.ListenAndServe(listen, nil))
}
本地验证:
- 启动 nginx 并打开 stub_status;
- go run main.go;
- curl localhost:9113/metrics | grep nginx_stub;
- 浏览器访问 Prometheus 控制台,输入 rate(nginx_stub_requests_total[5m]) 观察 QPS。
拓展思考
-
高并发场景下,每次采集都新建 TCP 连接会成为瓶颈。
可复用 http.Client 并设置长连接、超时、Keep-Alive,同时把 scrape 放入 sync.Pool 降低 GC。 -
多 upstream 场景需要给指标加标签。
把 uri 当成标签值会爆炸,正确做法是让用户在配置里写“instance”标签,如 nginx_stub{instance="gateway-1"}。 -
国内金融级合规要求“可审计”。
在 exporter 里内置一个 /probe 接口,支持黑白盒探测,并输出 uid、trace_id 到日志,方便后续对接审计平台。 -
云原生部署。
提供 Helm Chart,默认通过 ServiceMonitor 让 Prometheus Operator 自动发现;
镜像使用 distroless 静态编译,大小 <15 MB,减少攻击面。 -
灰度发布。
利用 exporter 自身暴露的 nginx_stub_up 指标,结合 Prometheus Alertmanager 做“监控的监控”,一旦采集失败立即告警,防止“盲飞”。