metrics 包的全局指标(UpstreamTotal 等)默认是 nil,只有 main 调过 metrics.Init() 之后才有值。任何不经过 main 的调用路径都会在 controller/tts.go -> adapter/volcano/synthesis.go -> metrics.AdapterRecorder 处 nil 解引用,整个进程崩掉。 生产路径本来没问题(二进制一定先 Init),但这类崩溃只在运行时暴露,且漏掉指标初始化属于很容易踩的装配错误,不该以 panic 收场。 改动: Counter.Add / Gauge.Set / Gauge.Add / Histogram.Observe 增加空接收者判断,nil 时静默忽略(与 noop 语义一致);在包注释里写成显式设计约定,避免以后被当成冗余代码删掉。
95 lines
2.1 KiB
Go
95 lines
2.1 KiB
Go
package telemetry
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"sort"
|
|
"sync"
|
|
"sync/atomic"
|
|
)
|
|
|
|
// Counter 单调递增的累计指标(整数语义,内部用 float64 位以 atomic 操作)。
|
|
type Counter struct {
|
|
metricName string
|
|
help string
|
|
labelNames []string
|
|
|
|
mu sync.RWMutex
|
|
values map[string]*counterChild // key = labelKey(...)
|
|
}
|
|
|
|
type counterChild struct {
|
|
labels Labels
|
|
bits atomic.Uint64 // float64
|
|
}
|
|
|
|
func newCounter(name, help string, labelNames []string) *Counter {
|
|
return &Counter{
|
|
metricName: name,
|
|
help: help,
|
|
labelNames: append([]string(nil), labelNames...),
|
|
values: make(map[string]*counterChild),
|
|
}
|
|
}
|
|
|
|
// Inc 计数 +1。
|
|
func (c *Counter) Inc(labels Labels) { c.Add(1, labels) }
|
|
|
|
// Add 累加 v(v 必须 >= 0)。
|
|
//
|
|
// 空接收者(nil *Counter)安全:未初始化的全局指标(如 metrics.Init() 尚未调用时
|
|
// 的 metrics.UpstreamTotal)会被静默忽略,而不是 panic。
|
|
// 这让"直接调用 handler"的测试/复用场景不会因为漏掉指标初始化而崩溃。
|
|
func (c *Counter) Add(v float64, labels Labels) {
|
|
if c == nil || v < 0 {
|
|
return
|
|
}
|
|
child := c.getOrCreate(labels)
|
|
for {
|
|
bits := child.bits.Load()
|
|
cur := float64frombits(bits)
|
|
next := float64bits(cur + v)
|
|
if child.bits.CompareAndSwap(bits, next) {
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func (c *Counter) getOrCreate(labels Labels) *counterChild {
|
|
key := labelKey(c.labelNames, labels)
|
|
c.mu.RLock()
|
|
if child, ok := c.values[key]; ok {
|
|
c.mu.RUnlock()
|
|
return child
|
|
}
|
|
c.mu.RUnlock()
|
|
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
if child, ok := c.values[key]; ok {
|
|
return child
|
|
}
|
|
child := &counterChild{labels: copyLabels(labels, c.labelNames)}
|
|
c.values[key] = child
|
|
return child
|
|
}
|
|
|
|
func (c *Counter) collect(w io.Writer) {
|
|
fmt.Fprintf(w, "# HELP %s %s\n", c.metricName, c.help)
|
|
fmt.Fprintf(w, "# TYPE %s counter\n", c.metricName)
|
|
|
|
c.mu.RLock()
|
|
keys := make([]string, 0, len(c.values))
|
|
for k := range c.values {
|
|
keys = append(keys, k)
|
|
}
|
|
sort.Strings(keys)
|
|
defer c.mu.RUnlock()
|
|
|
|
for _, k := range keys {
|
|
child := c.values[k]
|
|
val := float64frombits(child.bits.Load())
|
|
writeMetricLine(w, c.metricName, child.labels, val)
|
|
}
|
|
}
|