diff --git a/util/clientmetric/clientmetric.go b/util/clientmetric/clientmetric.go index 765b69160..88a92ba1c 100644 --- a/util/clientmetric/clientmetric.go +++ b/util/clientmetric/clientmetric.go @@ -35,22 +35,42 @@ var ( lastLogVal []scanEntry // by Metric.regIdx unsorted []*Metric // by Metric.regIdx - // valFreeList is a set of free contiguous int64s whose - // element addresses get assigned to Metric.v. + // valFreeList is a set of free contiguous metricVals whose + // element addresses get assigned to Metric.vals. // Any memory address in len(valFreeList) is free for use. // They're contiguous to reduce cache churn during diff scans. // When out of length, a new backing array is made. - valFreeList []int64 + valFreeList []metricVals ) +// metricVals are the values that make up the value of a metric. +// Both are atomic. +type metricVals struct { + // v is the value in this process. Metric.v points to it. + // A metric with a value function calls that instead, and leaves v unused. + v int64 + // ext is the sum of the metric's values in other processes + // that add to the value in this process. See [Remote]. + ext int64 +} + // scanEntry contains the minimal data needed for quickly scanning // memory for changed values. It's small to reduce memory pressure. type scanEntry struct { - v *int64 // Metric.v + vals *metricVals // Metric.vals f func() int64 // Metric.f lastLogged int64 // last logged value } +// value returns the current value of the metric. +func (ent *scanEntry) value() int64 { + ext := atomic.LoadInt64(&ent.vals.ext) + if ent.f != nil { + return ent.f() + ext + } + return atomic.LoadInt64(&ent.vals.v) + ext +} + // MetricUpdate requests that a client metric value be updated. // // This is the request body sent to /localapi/v0/upload-client-metrics. @@ -69,8 +89,9 @@ type MetricUpdate struct { // // It's safe for concurrent use. type Metric struct { - v *int64 // atomic; the metric value + v *int64 // atomic; the metric value in this process f func() int64 // value function (v is ignored if f is non-nil) + vals *metricVals // set by Publish regIdx int // index into lastLogVal and unsorted name string typ Type @@ -91,11 +112,19 @@ type Metric struct { func (m *Metric) Name() string { return m.name } +// Value returns the value of m, which accounts for the values +// of the same metric in other processes, if any. See [Remote]. func (m *Metric) Value() int64 { + var v int64 if m.f != nil { - return m.f() + v = m.f() + } else { + v = atomic.LoadInt64(m.v) } - return atomic.LoadInt64(m.v) + if m.vals == nil { + return v // not published + } + return v + atomic.LoadInt64(&m.vals.ext) } func (m *Metric) Type() Type { return m.typ } @@ -131,6 +160,10 @@ func (m *Metric) Set(v int64) { func (m *Metric) Publish() { mu.Lock() defer mu.Unlock() + m.publishLocked() +} + +func (m *Metric) publishLocked() { if m.name == "" { panic("unnamed Metric") } @@ -140,20 +173,17 @@ func (m *Metric) Publish() { metrics[m.name] = m sortedDirty = true + if len(valFreeList) == 0 { + valFreeList = make([]metricVals, 256) + } + m.vals = &valFreeList[0] + valFreeList = valFreeList[1:] if m.f == nil { - if len(valFreeList) == 0 { - valFreeList = make([]int64, 256) - } - m.v = &valFreeList[0] - valFreeList = valFreeList[1:] + m.v = &m.vals.v } if buildfeatures.HasLogTail { - if m.f != nil { - lastLogVal = append(lastLogVal, scanEntry{f: m.f}) - } else { - lastLogVal = append(lastLogVal, scanEntry{v: m.v}) - } + lastLogVal = append(lastLogVal, scanEntry{vals: m.vals, f: m.f}) } m.regIdx = len(unsorted) @@ -348,12 +378,7 @@ func EncodeLogTailMetricsDelta() string { var enc *deltaEncBuf // lazy for i, ent := range lastLogVal { - var val int64 - if ent.f != nil { - val = ent.f() - } else { - val = atomic.LoadInt64(ent.v) - } + val := ent.value() delta := val - ent.lastLogged if delta == 0 { continue @@ -401,6 +426,9 @@ type deltaEncBuf struct { scratch [binary.MaxVarintLen64]byte } +// gaugeWireNamePrefix is the prefix that the names of gauges have on the wire. +const gaugeWireNamePrefix = "gauge_" + // writeName writes a "name" (N) record to the buffer, which notes // that the immediately following record's wireID has the provided // name. @@ -409,7 +437,7 @@ func (b *deltaEncBuf) writeName(name string, typ Type) { if typ == TypeGauge { // Add the gauge_ prefix so that tsweb knows that this is a gauge metric // when generating the Prometheus version. - namePrefix = "gauge_" + namePrefix = gaugeWireNamePrefix } b.buf.WriteByte('N') b.writeHexVarint(int64(len(namePrefix) + len(name))) @@ -460,6 +488,7 @@ func ResetForTest(t testenv.TB) { if m.v != nil { atomic.StoreInt64(m.v, 0) } + atomic.StoreInt64(&m.vals.ext, 0) } } diff --git a/util/clientmetric/omit.go b/util/clientmetric/omit.go index db8e60f40..223c6835e 100644 --- a/util/clientmetric/omit.go +++ b/util/clientmetric/omit.go @@ -33,4 +33,9 @@ func NewAggregateCounter(string) *Metric { return &zeroMetric } func NewCounterFunc(string, func() int64) *Metric { return &zeroMetric } func NewGaugeFunc(string, func() int64) *Metric { return &zeroMetric } +type Remote struct{} + +func (*Remote) Update(string) error { return nil } +func (*Remote) Reset() {} + func ResetForTest(any) {} diff --git a/util/clientmetric/remote.go b/util/clientmetric/remote.go new file mode 100644 index 000000000..514a18302 --- /dev/null +++ b/util/clientmetric/remote.go @@ -0,0 +1,214 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build !ts_omit_clientmetrics + +package clientmetric + +import ( + "cmp" + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "strings" + "sync" + "sync/atomic" + + "tailscale.com/util/mak" +) + +// Remote merges the client metrics of another process into those of this one, +// for [Metric.Value] and [EncodeLogTailMetricsDelta] to report them as one. +// It is for processes whose logs, and so metrics, are uploaded by this process. +// For example, tailscaled runs as a service on Windows, which uploads the logs, +// and has a subprocess that does the actual work and has most of the metrics. +// +// A counter is the sum of its values in both processes. +// A gauge is set to its value in the remote process, +// and to zero when that process exits. +// +// There should be one Remote per remote process. The zero value is ready to use. +type Remote struct { + mu sync.Mutex + // metrics maps the wire IDs in the remote process's deltas, + // which that process assigns independently of this one, + // to the metrics they refer to. + metrics map[int64]*remoteMetric +} + +type remoteMetric struct { + m *Metric // the local metric with the same name + val int64 // the remote's last known value +} + +// replaces reports whether the remote's value of the metric +// replaces the local one rather than adds to it. +func (rm *remoteMetric) replaces() bool { + // A metric with a value function has no local value to replace. + return rm.m.typ == TypeGauge && rm.m.f == nil +} + +// set sets the remote's value of the metric to v. +func (rm *remoteMetric) set(v int64) { + if rm.replaces() { + atomic.StoreInt64(rm.m.v, v) + } else { + atomic.AddInt64(&rm.m.vals.ext, v-rm.val) + } + rm.val = v +} + +// release is called when the remote process no longer has the metric. +// A counter keeps what the process has added to it, +// so that it doesn't go backwards if the process is restarted. +func (rm *remoteMetric) release() { + if rm.m.typ == TypeGauge { + rm.set(0) + } +} + +// Update applies delta, as returned by [EncodeLogTailMetricsDelta] +// in the remote process. Every delta must be applied, in order. +// +// A record of a metric that cannot be resolved is skipped, and the rest +// of delta is still applied. Update then returns the first such error. +func (r *Remote) Update(delta string) error { + r.mu.Lock() + defer r.mu.Unlock() + + var skipped error // the first error for a record that was skipped + var name string // of the metric in the following record, if not empty + for len(delta) > 0 { + op := delta[0] + delta = delta[1:] + switch op { + case 'N': + n, rest, err := readHexVarint(delta) + if err != nil { + return fmt.Errorf("reading name length: %w", err) + } + if n < 1 || n > int64(len(rest)) { + return fmt.Errorf("invalid name length %d", n) + } + name, delta = rest[:n], rest[n:] + case 'S', 'I': + id, rest, err := readHexVarint(delta) + if err != nil { + return fmt.Errorf("reading wire ID: %w", err) + } + v, rest, err := readHexVarint(rest) + if err != nil { + return fmt.Errorf("reading value: %w", err) + } + delta = rest + + rm, err := r.metricLocked(id, name) + name = "" + if err != nil { + skipped = cmp.Or(skipped, err) + continue + } + if op == 'I' { + v += rm.val + } + rm.set(v) + default: + return fmt.Errorf("unknown op %q", op) + } + } + return skipped +} + +// metricLocked returns the metric with the given wire ID in the remote process. +// The name is that of the metric on the wire if the record has one, +// and is empty otherwise. +// +// r.mu must be held. +func (r *Remote) metricLocked(id int64, name string) (*remoteMetric, error) { + rm := r.metrics[id] + if name == "" { + if rm == nil { + return nil, fmt.Errorf("no name for wire ID %d", id) + } + return rm, nil + } + if rm != nil && wireName(rm.m) == name { + return rm, nil + } + m, err := metricForWireName(name) + if err != nil { + return nil, err + } + if rm != nil { + rm.release() + } + rm = &remoteMetric{m: m} + mak.Set(&r.metrics, id, rm) + return rm, nil +} + +// Reset is called when the remote process has exited. +func (r *Remote) Reset() { + r.mu.Lock() + defer r.mu.Unlock() + for _, rm := range r.metrics { + rm.release() + } + clear(r.metrics) +} + +// wireName returns the name of m as written by [deltaEncBuf.writeName]. +func wireName(m *Metric) string { + if m.typ == TypeGauge { + return gaugeWireNamePrefix + m.name + } + return m.name +} + +// metricForWireName returns the metric with the given name on the wire, +// publishing it if this process doesn't have it. +func metricForWireName(wireName string) (*Metric, error) { + typ := TypeCounter + name, isGauge := strings.CutPrefix(wireName, gaugeWireNamePrefix) + if isGauge { + typ = TypeGauge + } + if i := strings.IndexFunc(name, isIllegalMetricRune); name == "" || i != -1 { + return nil, fmt.Errorf("illegal metric name %q", wireName) + } + + mu.Lock() + defer mu.Unlock() + if m, ok := metrics[name]; ok { + if m.typ != typ { + return nil, fmt.Errorf("metric %q is of another type in this process", wireName) + } + return m, nil + } + m := NewUnpublished(name, typ) + m.publishLocked() + return m, nil +} + +// readHexVarint reads a value written by [deltaEncBuf.writeHexVarint] +// from the start of s, and returns it along with the rest of s. +func readHexVarint(s string) (v int64, rest string, err error) { + var buf [binary.MaxVarintLen64]byte + for i := range buf { + if len(s) < 2*(i+1) { + break + } + if _, err := hex.Decode(buf[i:i+1], []byte(s[2*i:2*i+2])); err != nil { + return 0, "", err + } + if buf[i] < 0x80 { + v, n := binary.Varint(buf[:i+1]) + if n <= 0 { + break // overflows 64 bits + } + return v, s[2*(i+1):], nil + } + } + return 0, "", errors.New("invalid varint") +} diff --git a/util/clientmetric/remote_test.go b/util/clientmetric/remote_test.go new file mode 100644 index 000000000..bb96dbff6 --- /dev/null +++ b/util/clientmetric/remote_test.go @@ -0,0 +1,363 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package clientmetric + +import ( + "math" + "sync" + "testing" +) + +// remoteDelta returns a delta as encoded by a remote process. +func remoteDelta(f func(*deltaEncBuf)) string { + var enc deltaEncBuf + f(&enc) + return enc.buf.String() +} + +func TestRemote(t *testing.T) { + type localMetric struct { + name string + typ Type + val int64 + } + // step is an update from, or the exit of, one of the remote processes, + // followed by the checks to make. + type step struct { + remote int // index of the remote process + update func(*deltaEncBuf) // the delta to apply, if not nil + reset bool // whether the remote process exits + want map[string]int64 // values of the metrics by name + wantDelta string // delta that this process encodes, if not empty + } + tests := []struct { + name string + local []localMetric + steps []step + }{ + { + name: "counter-in-both-is-summed", + local: []localMetric{{"c", TypeCounter, 3}}, + steps: []step{ + { + update: func(enc *deltaEncBuf) { + enc.writeName("c", TypeCounter) + enc.writeValue(1, 5) + }, + want: map[string]int64{"c": 8}, + wantDelta: "N02cS0210", + }, + { + update: func(enc *deltaEncBuf) { enc.writeDelta(1, 2) }, + want: map[string]int64{"c": 10}, + wantDelta: "I0204", + }, + }, + }, + { + name: "remote-only-metrics-are-published", + steps: []step{ + { + update: func(enc *deltaEncBuf) { + enc.writeName("c", TypeCounter) + enc.writeValue(1, 100) + enc.writeName("g", TypeGauge) + enc.writeValue(2, 7) + }, + want: map[string]int64{"c": 100, "g": 7}, + wantDelta: "N02cS02c801N0egauge_gS040e", + }, + { + update: func(enc *deltaEncBuf) { + enc.writeDelta(1, 50) + enc.writeDelta(2, -3) + }, + want: map[string]int64{"c": 150, "g": 4}, + wantDelta: "I0264I0405", + }, + }, + }, + { + name: "gauge-in-both-is-replaced", + local: []localMetric{{"g", TypeGauge, 1}}, + steps: []step{ + { + update: func(enc *deltaEncBuf) { + enc.writeName("g", TypeGauge) + enc.writeValue(1, 1) + }, + want: map[string]int64{"g": 1}, // rather than 2 + }, + { + update: func(enc *deltaEncBuf) { enc.writeValue(1, 5) }, + want: map[string]int64{"g": 5}, + }, + { + reset: true, + want: map[string]int64{"g": 0}, + }, + }, + }, + { + name: "name-is-repeated", + steps: []step{ + { + update: func(enc *deltaEncBuf) { + enc.writeName("c", TypeCounter) + enc.writeValue(1, 100) + }, + want: map[string]int64{"c": 100}, + }, + { + update: func(enc *deltaEncBuf) { + enc.writeName("c", TypeCounter) + enc.writeValue(1, 150) + }, + want: map[string]int64{"c": 150}, + }, + }, + }, + { + name: "exit-keeps-counters-and-drops-gauges", + local: []localMetric{{"c", TypeCounter, 3}}, + steps: []step{ + { + update: func(enc *deltaEncBuf) { + enc.writeName("c", TypeCounter) + enc.writeValue(1, 7) + enc.writeName("g", TypeGauge) + enc.writeValue(2, 4) + }, + want: map[string]int64{"c": 10, "g": 4}, + }, + { + reset: true, + want: map[string]int64{"c": 10, "g": 0}, + }, + { + // The new remote process allocates its wire IDs anew. + update: func(enc *deltaEncBuf) { + enc.writeName("g", TypeGauge) + enc.writeValue(1, 2) + enc.writeName("c", TypeCounter) + enc.writeValue(2, 1) + }, + want: map[string]int64{"c": 11, "g": 2}, + }, + }, + }, + { + name: "two-remotes", + local: []localMetric{{"c", TypeCounter, 1}, {"g", TypeGauge, 1}}, + steps: []step{ + { + remote: 0, + update: func(enc *deltaEncBuf) { + enc.writeName("c", TypeCounter) + enc.writeValue(1, 10) + enc.writeName("g", TypeGauge) + enc.writeValue(2, 2) + }, + want: map[string]int64{"c": 11, "g": 2}, + }, + { + remote: 1, + update: func(enc *deltaEncBuf) { + enc.writeName("g", TypeGauge) + enc.writeValue(1, 5) + enc.writeName("c", TypeCounter) + enc.writeValue(2, 100) + }, + want: map[string]int64{"c": 111, "g": 5}, // the gauge is as last set + }, + { + remote: 0, + reset: true, + want: map[string]int64{"c": 111}, + }, + { + remote: 1, + reset: true, + want: map[string]int64{"c": 111, "g": 0}, + }, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + clearMetrics() + for _, lm := range tt.local { + m := NewUnpublished(lm.name, lm.typ) + m.Publish() + m.Set(lm.val) + } + + var remotes [2]Remote + for i, st := range tt.steps { + r := &remotes[st.remote] + if st.update != nil { + if err := r.Update(remoteDelta(st.update)); err != nil { + t.Fatalf("step %d: %v", i, err) + } + } + if st.reset { + r.Reset() + } + for name, want := range st.want { + mu.Lock() + m, ok := metrics[name] + mu.Unlock() + if !ok { + t.Errorf("step %d: metric %q is not published", i, name) + } else if got := m.Value(); got != want { + t.Errorf("step %d: %s = %d; want %d", i, name, got, want) + } + } + if st.wantDelta != "" { + advanceTime() + if got := EncodeLogTailMetricsDelta(); got != st.wantDelta { + t.Errorf("step %d: delta = %q; want %q", i, got, st.wantDelta) + } + } + } + }) + } +} + +func TestRemoteInvalid(t *testing.T) { + clearMetrics() + for _, delta := range []string{ + "X", + "N", + "N06fo", + "N00S0202", + "N06f-oS0202", + "S0202", + "N06fooS02", + "N06fooSzz02", + "N06fooS8080808080808080808002", + "N06fooS02ffffffffffffffffff7f", + } { + var r Remote + if err := r.Update(delta); err == nil { + t.Errorf("Update(%q) succeeded; want error", delta) + } + } +} + +// TestRemoteSkipsUnresolved tests that Update applies the records that +// follow one whose metric it cannot resolve. +func TestRemoteSkipsUnresolved(t *testing.T) { + clearMetrics() + mismatched := NewGauge("mismatched") + applied := NewCounter("applied") + var r Remote + err := r.Update(remoteDelta(func(enc *deltaEncBuf) { + enc.writeDelta(1, 5) // has no name + enc.writeName("mismatched", TypeCounter) + enc.writeValue(2, 7) + enc.writeName("applied", TypeCounter) + enc.writeValue(3, 9) + })) + if err == nil { + t.Error("Update succeeded; want error") + } + if got := applied.Value(); got != 9 { + t.Errorf("applied = %d; want 9", got) + } + if got := mismatched.Value(); got != 0 { + t.Errorf("mismatched = %d; want 0", got) + } +} + +func TestReadHexVarint(t *testing.T) { + for _, want := range []int64{ + 0, + 1, + -1, + 63, // the largest value encoded in one byte + 64, + -64, // the smallest value encoded in one byte + -65, + 300, + -300, + 1 << 40, + math.MaxInt64, + math.MinInt64, + } { + var enc deltaEncBuf + enc.writeHexVarint(want) + const tail = "S0202" + got, rest, err := readHexVarint(enc.buf.String() + tail) + if err != nil { + t.Errorf("readHexVarint(%q): %v", enc.buf.String()+tail, err) + continue + } + if got != want || rest != tail { + t.Errorf("readHexVarint(%q) = %d, %q; want %d, %q", enc.buf.String()+tail, got, rest, want, tail) + } + } + + for _, s := range []string{ + "", // empty + "0", // half of a byte + "zz", // not hex + "80", // continues past the end + "800", // continues into half of a byte + "80zz", // continues into non-hex + "8080808080808080808001", // longer than a 64-bit varint + } { + if v, rest, err := readHexVarint(s); err == nil { + t.Errorf("readHexVarint(%q) = %d, %q; want error", s, v, rest) + } + } +} + +// TestRemoteConcurrent tests that metrics can be updated and read +// while a Remote is being updated. It is mostly for the race detector. +func TestRemoteConcurrent(t *testing.T) { + clearMetrics() + c := NewCounter("c") + g := NewGauge("g") + + const n = 1000 + var wg sync.WaitGroup + wg.Go(func() { + for range n { + c.Add(1) + g.Set(1) + } + }) + wg.Go(func() { + for range n { + c.Value() + g.Value() + } + }) + + var r Remote + for i := range int64(n) { + err := r.Update(remoteDelta(func(enc *deltaEncBuf) { + if i == 0 { + enc.writeName("c", TypeCounter) + } + enc.writeValue(1, i+1) + if i == 0 { + enc.writeName("g", TypeGauge) + } + enc.writeValue(2, i+1) + })) + if err != nil { + t.Fatal(err) + } + } + wg.Wait() + + if got, want := c.Value(), int64(2*n); got != want { + t.Errorf("c = %d; want %d", got, want) + } + if got, want := g.Value(), int64(n); got != want { + t.Errorf("g = %d; want %d", got, want) + } +}