From 33f21bdb1fbd8cf69f044d2da916246d7b8d8543 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 2 Nov 2026 08:57:49 +0800 Subject: [PATCH] otlp: a global proxy switch drops the exporter's idle connection to the collector (#4824) The residue ggbdpq's #4824 patch named. The OTel exporter keeps its own long-lived transport (Proxy: netproxy.Func). An https collector gets HTTP/2, which pools by authority alone, so after the global proxy moved, every batch kept going through the old proxy's connection. The exporter now holds a netproxy.Watch, and send closes the client's idle connections when the proxy has moved since the last send. An exporter built without one (otel_cost_test's literal) skips the check. Run at the pushed head (on mote, base 4d55a0a02) - TestOTelGlobalSwitchDialsThroughTheNewProxy is new. It uses an HTTPS HTTP/2 collector and two counting SOCKS5 proxies, and passes. The otlp package passes. - The full suite, gofmt and the cross-OS vet are as recorded in the #4824 netproxy commit before this one. The only reds are #4826 and #4807, neither in otlp. Broken by hand: with the moved check off, the test is red: "after the switch: 2 at the collector, 1 connections through A, 0 through B". Not tried: a real OTel collector behind a real proxy switch. --- internal/otlp/otel.go | 10 ++- internal/otlp/otel_proxy_test.go | 125 +++++++++++++++++++++++++++++++ 2 files changed, 134 insertions(+), 1 deletion(-) create mode 100644 internal/otlp/otel_proxy_test.go diff --git a/internal/otlp/otel.go b/internal/otlp/otel.go index 959ea77ce..c1d595fba 100644 --- a/internal/otlp/otel.go +++ b/internal/otlp/otel.go @@ -60,6 +60,11 @@ type otelExporter struct { ctx context.Context cancel context.CancelFunc client *http.Client + // moved is whether the global proxy moved since the exporter's last + // send: its transport is its own, not a dispatch, and pools an HTTPS + // collector's HTTP/2 connection by the collector alone, so a switch + // left the batches after it on the old proxy's connection (#4824) + moved func() bool salt [8]byte last time.Time dropped atomic.Uint64 @@ -107,7 +112,7 @@ func (x *Exporter) Serve() func() { func newOTelExporter() *otelExporter { ctx, cancel := context.WithCancel(context.Background()) e := &otelExporter{queue: make(chan otelItem, otelQueueSize), stop: make(chan struct{}), done: make(chan struct{}), ctx: ctx, cancel: cancel, - last: time.Now(), client: &http.Client{Timeout: 3 * time.Second, + last: time.Now(), moved: netproxy.Watch(), client: &http.Client{Timeout: 3 * time.Second, Transport: &http.Transport{Proxy: netproxy.Func, MaxIdleConnsPerHost: 2, IdleConnTimeout: 90 * time.Second}, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}} rand.Read(e.salt[:]) @@ -338,6 +343,9 @@ func (e *otelExporter) send(config settings.OTel, signal string, payload any) { req.Header.Set(k, v) } req.Header.Set("Content-Type", "application/json") + if e.moved != nil && e.moved() { + e.client.CloseIdleConnections() + } res, err := e.client.Do(req) retry := err != nil if res != nil { diff --git a/internal/otlp/otel_proxy_test.go b/internal/otlp/otel_proxy_test.go new file mode 100644 index 000000000..084a1e5c6 --- /dev/null +++ b/internal/otlp/otel_proxy_test.go @@ -0,0 +1,125 @@ +package otlp + +import ( + "crypto/tls" + "crypto/x509" + "encoding/binary" + "io" + "net" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "sync/atomic" + "testing" + "time" + + "github.com/yetone/magpie/internal/settings" +) + +// A switch of the global proxy left the exporter on the old one: its +// transport is its own, and an HTTPS collector's HTTP/2 connection is +// pooled by the collector alone, so the batches after the switch rode the +// connection dialled through the old proxy (#4824). The send after a move +// drops the idle connections and dials through the proxy in force. +func TestOTelGlobalSwitchDialsThroughTheNewProxy(t *testing.T) { + var got atomic.Int32 + collector := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.ProtoMajor != 2 { + t.Errorf("the batch went over %s, want HTTP/2", r.Proto) + } + got.Add(1) + io.WriteString(w, `{}`) + })) + collector.EnableHTTP2 = true + collector.StartTLS() + t.Cleanup(collector.Close) + pool := x509.NewCertPool() + pool.AddCert(collector.Certificate()) + otelConfig(t, settings.OTel{Endpoint: collector.URL}) + a, na := countingSOCKS(t) + b, nb := countingSOCKS(t) + var cur atomic.Pointer[url.URL] + cur.Store(a) + e := newOTelExporter() + t.Cleanup(e.cancel) + t.Cleanup(e.client.CloseIdleConnections) + tr := e.client.Transport.(*http.Transport) + // the collector is on the loopback, which Func leaves direct, and its + // certificate is the test's own; HTTP/2 as with no TLS config set + tr.Proxy = func(*http.Request) (*url.URL, error) { return cur.Load(), nil } + tr.TLSClientConfig = &tls.Config{RootCAs: pool} + tr.ForceAttemptHTTP2 = true + cfg, _ := settings.OTelExport() + batch := []otelItem{{record: Record{Time: time.Now(), Status: 200}, config: cfg}} + if err := settings.Save(settings.Settings{Proxy: a.String()}); err != nil { + t.Fatal(err) + } + e.flush(batch) + if got.Load() != 1 || na.Load() != 1 || nb.Load() != 0 { + t.Fatalf("the first batch: %d at the collector, %d connections through A, %d through B", got.Load(), na.Load(), nb.Load()) + } + cur.Store(b) + if err := settings.Save(settings.Settings{Proxy: b.String()}); err != nil { + t.Fatal(err) + } + e.flush(batch) + if got.Load() != 2 || na.Load() != 1 || nb.Load() != 1 { + t.Fatalf("after the switch: %d at the collector, %d connections through A, %d through B, want the batch dialled through B and no new one through A", got.Load(), na.Load(), nb.Load()) + } +} + +// countingSOCKS is a SOCKS5 proxy, no auth, counting the connections it +// carried. +func countingSOCKS(t *testing.T) (*url.URL, *atomic.Int32) { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + var n atomic.Int32 + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + go func(c net.Conn) { + defer c.Close() + var h [2]byte + io.ReadFull(c, h[:]) + io.CopyN(io.Discard, c, int64(h[1])) + c.Write([]byte{5, 0}) + var r [4]byte + io.ReadFull(c, r[:]) + var host string + switch r[3] { + case 1: + b := make([]byte, 4) + io.ReadFull(c, b) + host = net.IP(b).String() + case 3: + var l [1]byte + io.ReadFull(c, l[:]) + b := make([]byte, l[0]) + io.ReadFull(c, b) + host = string(b) + } + var pb [2]byte + io.ReadFull(c, pb[:]) + up, err := net.Dial("tcp", net.JoinHostPort(host, strconv.Itoa(int(binary.BigEndian.Uint16(pb[:]))))) + if err != nil { + c.Write([]byte{5, 5, 0, 1, 0, 0, 0, 0, 0, 0}) + return + } + defer up.Close() + n.Add(1) + c.Write([]byte{5, 0, 0, 1, 127, 0, 0, 1, 0, 0}) + go io.Copy(up, c) + io.Copy(c, up) + }(c) + } + }() + return &url.URL{Scheme: "socks5", Host: ln.Addr().String()}, &n +}