repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/testhelpers/config.go
pkg/testhelpers/config.go
package testhelpers import ( "github.com/traefik/traefik/v3/pkg/config/dynamic" otypes "github.com/traefik/traefik/v3/pkg/observability/types" ) // BuildConfiguration is a helper to create a configuration. func BuildConfiguration(dynamicConfigBuilders ...func(*dynamic.HTTPConfiguration)) *dynamic.HTTPConfiguration { conf := &dynamic.HTTPConfiguration{ Models: map[string]*dynamic.Model{}, ServersTransports: map[string]*dynamic.ServersTransport{}, } for _, build := range dynamicConfigBuilders { build(conf) } return conf } // WithRouters is a helper to create a configuration. func WithRouters(opts ...func(*dynamic.Router) string) func(*dynamic.HTTPConfiguration) { return func(c *dynamic.HTTPConfiguration) { c.Routers = make(map[string]*dynamic.Router) for _, opt := range opts { b := &dynamic.Router{} name := opt(b) c.Routers[name] = b } } } // WithRouter is a helper to create a configuration. func WithRouter(routerName string, opts ...func(*dynamic.Router)) func(*dynamic.Router) string { return func(r *dynamic.Router) string { for _, opt := range opts { opt(r) } return routerName } } // WithRouterMiddlewares is a helper to create a configuration. func WithRouterMiddlewares(middlewaresName ...string) func(*dynamic.Router) { return func(r *dynamic.Router) { r.Middlewares = middlewaresName } } // WithServiceName is a helper to create a configuration. func WithServiceName(serviceName string) func(*dynamic.Router) { return func(r *dynamic.Router) { r.Service = serviceName } } // WithObservability is a helper to create a configuration. func WithObservability() func(*dynamic.Router) { return func(r *dynamic.Router) { r.Observability = &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Metrics: pointer(true), Tracing: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, } } } // WithLoadBalancerServices is a helper to create a configuration. func WithLoadBalancerServices(opts ...func(service *dynamic.ServersLoadBalancer) string) func(*dynamic.HTTPConfiguration) { return func(c *dynamic.HTTPConfiguration) { c.Services = make(map[string]*dynamic.Service) for _, opt := range opts { b := &dynamic.ServersLoadBalancer{} b.SetDefaults() name := opt(b) c.Services[name] = &dynamic.Service{ LoadBalancer: b, } } } } // WithService is a helper to create a configuration. func WithService(name string, opts ...func(*dynamic.ServersLoadBalancer)) func(*dynamic.ServersLoadBalancer) string { return func(r *dynamic.ServersLoadBalancer) string { for _, opt := range opts { opt(r) } return name } } // WithMiddlewares is a helper to create a configuration. func WithMiddlewares(opts ...func(*dynamic.Middleware) string) func(*dynamic.HTTPConfiguration) { return func(c *dynamic.HTTPConfiguration) { c.Middlewares = make(map[string]*dynamic.Middleware) for _, opt := range opts { b := &dynamic.Middleware{} name := opt(b) c.Middlewares[name] = b } } } // WithMiddleware is a helper to create a configuration. func WithMiddleware(name string, opts ...func(*dynamic.Middleware)) func(*dynamic.Middleware) string { return func(r *dynamic.Middleware) string { for _, opt := range opts { opt(r) } return name } } // WithBasicAuth is a helper to create a configuration. func WithBasicAuth(auth *dynamic.BasicAuth) func(*dynamic.Middleware) { return func(r *dynamic.Middleware) { r.BasicAuth = auth } } // WithEntryPoints is a helper to create a configuration. func WithEntryPoints(eps ...string) func(*dynamic.Router) { return func(f *dynamic.Router) { f.EntryPoints = eps } } // WithRule is a helper to create a configuration. func WithRule(rule string) func(*dynamic.Router) { return func(f *dynamic.Router) { f.Rule = rule } } // WithServers is a helper to create a configuration. func WithServers(opts ...func(*dynamic.Server)) func(*dynamic.ServersLoadBalancer) { return func(b *dynamic.ServersLoadBalancer) { for _, opt := range opts { server := dynamic.Server{} opt(&server) b.Servers = append(b.Servers, server) } } } // WithServer is a helper to create a configuration. func WithServer(url string, opts ...func(*dynamic.Server)) func(*dynamic.Server) { return func(s *dynamic.Server) { for _, opt := range opts { opt(s) } s.URL = url } } // WithSticky is a helper to create a configuration. func WithSticky(cookieName string) func(*dynamic.ServersLoadBalancer) { return func(b *dynamic.ServersLoadBalancer) { b.Sticky = &dynamic.Sticky{ Cookie: &dynamic.Cookie{Name: cookieName}, } } } func pointer[T any](v T) *T { return &v }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/testhelpers/helpers.go
pkg/testhelpers/helpers.go
package testhelpers import ( "fmt" "io" "net/http" "net/url" ) // MustNewRequest creates a new http get request or panics if it can't. func MustNewRequest(method, urlStr string, body io.Reader) *http.Request { request, err := http.NewRequest(method, urlStr, body) if err != nil { panic(fmt.Sprintf("failed to create HTTP %s Request for '%s': %s", method, urlStr, err)) } return request } // MustParseURL parses a URL or panics if it can't. func MustParseURL(rawURL string) *url.URL { u, err := url.Parse(rawURL) if err != nil { panic(fmt.Sprintf("failed to parse URL '%s': %s", rawURL, err)) } return u }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/udp/switcher.go
pkg/udp/switcher.go
package udp import ( "github.com/traefik/traefik/v3/pkg/safe" ) // HandlerSwitcher is a switcher implementation of the Handler interface. type HandlerSwitcher struct { handler safe.Safe } // ServeUDP implements the Handler interface. func (s *HandlerSwitcher) ServeUDP(conn *Conn) { handler := s.handler.Get() h, ok := handler.(Handler) if ok { h.ServeUDP(conn) } else { conn.Close() } } // Switch replaces s handler with the given handler. func (s *HandlerSwitcher) Switch(handler Handler) { s.handler.Set(handler) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/udp/conn_test.go
pkg/udp/conn_test.go
package udp import ( "errors" "io" "net" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestConsecutiveWrites(t *testing.T) { ln, err := Listen(net.ListenConfig{}, "udp", ":0", 3*time.Second) require.NoError(t, err) defer func() { err := ln.Close() require.NoError(t, err) }() go func() { for { conn, err := ln.Accept() if errors.Is(err, errClosedListener) { return } require.NoError(t, err) go func() { b := make([]byte, 2048) b2 := make([]byte, 2048) var n int var n2 int n, err = conn.Read(b) require.NoError(t, err) // Wait to make sure that the second packet is received time.Sleep(10 * time.Millisecond) n2, err = conn.Read(b2) require.NoError(t, err) _, err = conn.Write(b[:n]) require.NoError(t, err) _, err = conn.Write(b2[:n2]) require.NoError(t, err) }() } }() udpConn, err := net.Dial("udp", ln.Addr().String()) require.NoError(t, err) // Send multiple packets of different content and length consecutively // Read back packets afterwards and make sure that content matches // This checks if any buffers are overwritten while the receiver is enqueuing multiple packets b := make([]byte, 2048) var n int _, err = udpConn.Write([]byte("TESTLONG0")) require.NoError(t, err) _, err = udpConn.Write([]byte("1TEST")) require.NoError(t, err) n, err = udpConn.Read(b) require.NoError(t, err) require.Equal(t, "TESTLONG0", string(b[:n])) n, err = udpConn.Read(b) require.NoError(t, err) require.Equal(t, "1TEST", string(b[:n])) } func TestListenNotBlocking(t *testing.T) { ln, err := Listen(net.ListenConfig{}, "udp", ":0", 3*time.Second) require.NoError(t, err) defer func() { err := ln.Close() require.NoError(t, err) }() go func() { for { conn, err := ln.Accept() if errors.Is(err, errClosedListener) { return } require.NoError(t, err) go func() { b := make([]byte, 2048) n, err := conn.Read(b) require.NoError(t, err) _, err = conn.Write(b[:n]) require.NoError(t, err) n, err = conn.Read(b) require.NoError(t, err) _, err = conn.Write(b[:n]) require.NoError(t, err) // This should not block second call time.Sleep(10 * time.Second) }() } }() udpConn, err := net.Dial("udp", ln.Addr().String()) require.NoError(t, err) _, err = udpConn.Write([]byte("TEST")) require.NoError(t, err) b := make([]byte, 2048) n, err := udpConn.Read(b) require.NoError(t, err) require.Equal(t, "TEST", string(b[:n])) _, err = udpConn.Write([]byte("TEST2")) require.NoError(t, err) n, err = udpConn.Read(b) require.NoError(t, err) require.Equal(t, "TEST2", string(b[:n])) _, err = udpConn.Write([]byte("TEST")) require.NoError(t, err) done := make(chan struct{}) go func() { udpConn2, err := net.Dial("udp", ln.Addr().String()) require.NoError(t, err) _, err = udpConn2.Write([]byte("TEST")) require.NoError(t, err) n, err = udpConn2.Read(b) require.NoError(t, err) assert.Equal(t, "TEST", string(b[:n])) _, err = udpConn2.Write([]byte("TEST2")) require.NoError(t, err) n, err = udpConn2.Read(b) require.NoError(t, err) assert.Equal(t, "TEST2", string(b[:n])) close(done) }() select { case <-time.Tick(time.Second): t.Error("Timeout") case <-done: } } func TestListenWithZeroTimeout(t *testing.T) { _, err := Listen(net.ListenConfig{}, "udp", ":0", 0) assert.Error(t, err) } func TestTimeoutWithRead(t *testing.T) { testTimeout(t, true) } func TestTimeoutWithoutRead(t *testing.T) { testTimeout(t, false) } func testTimeout(t *testing.T, withRead bool) { t.Helper() ln, err := Listen(net.ListenConfig{}, "udp", ":0", 3*time.Second) require.NoError(t, err) defer func() { err := ln.Close() require.NoError(t, err) }() go func() { for { conn, err := ln.Accept() if errors.Is(err, errClosedListener) { return } require.NoError(t, err) if withRead { buf := make([]byte, 1024) _, err = conn.Read(buf) require.NoError(t, err) } } }() for range 10 { udpConn2, err := net.Dial("udp", ln.Addr().String()) require.NoError(t, err) _, err = udpConn2.Write([]byte("TEST")) require.NoError(t, err) } time.Sleep(10 * time.Millisecond) assert.Len(t, ln.conns, 10) time.Sleep(ln.timeout + time.Second) assert.Empty(t, ln.conns) } func TestShutdown(t *testing.T) { l, err := Listen(net.ListenConfig{}, "udp", ":0", 3*time.Second) require.NoError(t, err) go func() { for { conn, err := l.Accept() if err != nil { return } go func() { conn := conn for { b := make([]byte, 1024*1024) n, err := conn.Read(b) require.NoError(t, err) // We control the termination, // otherwise we would block on the Read above, // until conn is closed by a timeout. // Which means we would get an error, // and even though we are in a goroutine and the current test might be over, // go test would still yell at us if this happens while other tests are still running. if string(b[:n]) == "CLOSE" { return } _, err = conn.Write(b[:n]) require.NoError(t, err) } }() } }() conn, err := net.Dial("udp", l.Addr().String()) require.NoError(t, err) // Start sending packets, to create a "session" with the server. requireEcho(t, "TEST", conn, time.Second) shutdownStartedChan := make(chan struct{}) doneChan := make(chan struct{}) go func() { close(shutdownStartedChan) err := l.Shutdown(5 * time.Second) require.NoError(t, err) close(doneChan) }() // Wait until shutdown has started, and hopefully after 100 ms the listener has stopped accepting new sessions. <-shutdownStartedChan time.Sleep(100 * time.Millisecond) // Make sure that our session is still live even after the shutdown. requireEcho(t, "TEST2", conn, time.Second) // And make sure that on the other hand, opening new sessions is not possible anymore. conn2, err := net.Dial("udp", l.Addr().String()) require.NoError(t, err) _, err = conn2.Write([]byte("TEST")) // Packet is accepted, but dropped require.NoError(t, err) // Make sure that our session is yet again still live. // This is specifically to make sure we don't create a regression in listener's readLoop, // i.e. that we only terminate the listener's readLoop goroutine by closing its pConn. requireEcho(t, "TEST3", conn, time.Second) done := make(chan bool) go func() { defer close(done) b := make([]byte, 1024*1024) n, err := conn2.Read(b) require.Error(t, err) assert.Equal(t, 0, n) }() conn2.Close() select { case <-done: case <-time.Tick(time.Second): t.Fatal("Timeout") } _, err = conn.Write([]byte("CLOSE")) require.NoError(t, err) select { case <-doneChan: case <-time.Tick(5 * time.Second): // In case we introduce a regression that would make the test wait forever. t.Fatal("Timeout during shutdown") } } // requireEcho tests that the conn session is live and functional, // by writing data through it, and expecting the same data as a response when reading on it. // It fatals if the read blocks longer than timeout, // which is useful to detect regressions that would make a test wait forever. func requireEcho(t *testing.T, data string, conn io.ReadWriter, timeout time.Duration) { t.Helper() _, err := conn.Write([]byte(data)) require.NoError(t, err) doneChan := make(chan struct{}) go func() { b := make([]byte, 1024*1024) n, err := conn.Read(b) require.NoError(t, err) assert.Equal(t, data, string(b[:n])) close(doneChan) }() select { case <-doneChan: case <-time.Tick(timeout): t.Fatalf("Timeout during echo for: %s", data) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/udp/proxy.go
pkg/udp/proxy.go
package udp import ( "io" "net" "github.com/rs/zerolog/log" ) // Proxy is a reverse-proxy implementation of the Handler interface. type Proxy struct { // TODO: maybe optimize by pre-resolving it at proxy creation time target string } // NewProxy creates a new Proxy. func NewProxy(address string) (*Proxy, error) { return &Proxy{target: address}, nil } // ServeUDP implements the Handler interface. func (p *Proxy) ServeUDP(conn *Conn) { log.Debug().Msgf("Handling UDP stream from %s to %s", conn.rAddr, p.target) // needed because of e.g. server.trackedConnection defer conn.Close() connBackend, err := net.Dial("udp", p.target) if err != nil { log.Error().Err(err).Msg("Error while dialing backend") return } // maybe not needed, but just in case defer connBackend.Close() errChan := make(chan error) go connCopy(conn, connBackend, errChan) go connCopy(connBackend, conn, errChan) err = <-errChan if err != nil { log.Error().Err(err).Msg("Error while handling UDP stream") } <-errChan } func connCopy(dst io.WriteCloser, src io.Reader, errCh chan error) { // The buffer is initialized to the maximum UDP datagram size, // to make sure that the whole UDP datagram is read or written atomically (no data is discarded). buffer := make([]byte, maxDatagramSize) _, err := io.CopyBuffer(dst, src, buffer) errCh <- err if err := dst.Close(); err != nil { log.Debug().Err(err).Msg("Error while terminating UDP stream") } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/udp/wrr_load_balancer.go
pkg/udp/wrr_load_balancer.go
package udp import ( "errors" "sync" "github.com/rs/zerolog/log" ) type server struct { Handler weight int } // WRRLoadBalancer is a naive RoundRobin load balancer for UDP services. type WRRLoadBalancer struct { servers []server lock sync.Mutex currentWeight int index int } // NewWRRLoadBalancer creates a new WRRLoadBalancer. func NewWRRLoadBalancer() *WRRLoadBalancer { return &WRRLoadBalancer{ index: -1, } } // ServeUDP forwards the connection to the right service. func (b *WRRLoadBalancer) ServeUDP(conn *Conn) { b.lock.Lock() next, err := b.next() b.lock.Unlock() if err != nil { log.Error().Err(err).Msg("Error during load balancing") conn.Close() return } next.ServeUDP(conn) } // AddServer appends a handler to the existing list. func (b *WRRLoadBalancer) AddServer(serverHandler Handler) { w := 1 b.AddWeightedServer(serverHandler, &w) } // AddWeightedServer appends a handler to the existing list with a weight. func (b *WRRLoadBalancer) AddWeightedServer(serverHandler Handler, weight *int) { b.lock.Lock() defer b.lock.Unlock() w := 1 if weight != nil { w = *weight } b.servers = append(b.servers, server{Handler: serverHandler, weight: w}) } func (b *WRRLoadBalancer) maxWeight() int { maximum := -1 for _, s := range b.servers { if s.weight > maximum { maximum = s.weight } } return maximum } func (b *WRRLoadBalancer) weightGcd() int { divisor := -1 for _, s := range b.servers { if divisor == -1 { divisor = s.weight } else { divisor = gcd(divisor, s.weight) } } return divisor } func gcd(a, b int) int { for b != 0 { a, b = b, a%b } return a } func (b *WRRLoadBalancer) next() (Handler, error) { if len(b.servers) == 0 { return nil, errors.New("no servers in the pool") } // The algorithm below may look messy, // but is actually very simple it calculates the GCD and subtracts it on every iteration, // what interleaves servers and allows us not to build an iterator every time we readjust weights. // Maximum weight across all enabled servers maximum := b.maxWeight() if maximum == 0 { return nil, errors.New("all servers have 0 weight") } // GCD across all enabled servers gcd := b.weightGcd() for { b.index = (b.index + 1) % len(b.servers) if b.index == 0 { b.currentWeight -= gcd if b.currentWeight <= 0 { b.currentWeight = maximum } } srv := b.servers[b.index] if srv.weight >= b.currentWeight { return srv, nil } } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/udp/proxy_test.go
pkg/udp/proxy_test.go
package udp import ( "crypto/rand" "net" "runtime" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestProxy_ServeUDP(t *testing.T) { backendAddr := ":8081" go newServer(t, backendAddr, HandlerFunc(func(conn *Conn) { for { b := make([]byte, 1024*1024) n, err := conn.Read(b) require.NoError(t, err) _, err = conn.Write(b[:n]) require.NoError(t, err) } })) proxy, err := NewProxy(backendAddr) require.NoError(t, err) proxyAddr := ":8080" go newServer(t, proxyAddr, proxy) time.Sleep(time.Second) udpConn, err := net.Dial("udp", proxyAddr) require.NoError(t, err) _, err = udpConn.Write([]byte("DATAWRITE")) require.NoError(t, err) b := make([]byte, 1024*1024) n, err := udpConn.Read(b) require.NoError(t, err) assert.Equal(t, "DATAWRITE", string(b[:n])) } func TestProxy_ServeUDP_MaxDataSize(t *testing.T) { if runtime.GOOS == "darwin" { // sudo sysctl -w net.inet.udp.maxdgram=65507 t.Skip("Skip test on darwin as the maximum dgram size is set to 9216 bytes by default") } // Theoretical maximum size of data in a UDP datagram. // 65535 − 8 (UDP header) − 20 (IP header). dataSize := 65507 backendAddr := ":8083" go newServer(t, backendAddr, HandlerFunc(func(conn *Conn) { buffer := make([]byte, dataSize) n, err := conn.Read(buffer) require.NoError(t, err) _, err = conn.Write(buffer[:n]) require.NoError(t, err) })) proxy, err := NewProxy(backendAddr) require.NoError(t, err) proxyAddr := ":8082" go newServer(t, proxyAddr, proxy) time.Sleep(time.Second) udpConn, err := net.Dial("udp", proxyAddr) require.NoError(t, err) want := make([]byte, dataSize) _, err = rand.Read(want) require.NoError(t, err) _, err = udpConn.Write(want) require.NoError(t, err) got := make([]byte, dataSize) _, err = udpConn.Read(got) require.NoError(t, err) assert.Equal(t, want, got) } func newServer(t *testing.T, addr string, handler Handler) { t.Helper() listener, err := Listen(net.ListenConfig{}, "udp", addr, 3*time.Second) require.NoError(t, err) for { conn, err := listener.Accept() require.NoError(t, err) go handler.ServeUDP(conn) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/udp/conn.go
pkg/udp/conn.go
package udp import ( "context" "errors" "fmt" "io" "net" "sync" "time" ) // maxDatagramSize is the maximum size of a UDP datagram. const maxDatagramSize = 65535 const closeRetryInterval = 500 * time.Millisecond var errClosedListener = errors.New("udp: listener closed") // Listener augments a session-oriented Listener over a UDP PacketConn. type Listener struct { pConn *net.UDPConn mu sync.RWMutex conns map[string]*Conn // accepting signifies whether the listener is still accepting new sessions. // It also serves as a sentinel for Shutdown to be idempotent. accepting bool acceptCh chan *Conn // no need for a Once, already indirectly guarded by accepting. // timeout defines how long to wait on an idle session, // before releasing its related resources. timeout time.Duration } // ListenPacketConn creates a new listener from PacketConn. func ListenPacketConn(packetConn net.PacketConn, timeout time.Duration) (*Listener, error) { if timeout <= 0 { return nil, errors.New("timeout should be greater than zero") } pConn, ok := packetConn.(*net.UDPConn) if !ok { return nil, errors.New("packet conn is not an UDPConn") } l := &Listener{ pConn: pConn, acceptCh: make(chan *Conn), conns: make(map[string]*Conn), accepting: true, timeout: timeout, } go l.readLoop() return l, nil } // Listen creates a new listener. func Listen(listenConfig net.ListenConfig, network, address string, timeout time.Duration) (*Listener, error) { if timeout <= 0 { return nil, errors.New("timeout should be greater than zero") } packetConn, err := listenConfig.ListenPacket(context.Background(), network, address) if err != nil { return nil, fmt.Errorf("listen packet: %w", err) } l, err := ListenPacketConn(packetConn, timeout) if err != nil { return nil, fmt.Errorf("listen packet conn: %w", err) } return l, nil } // Accept waits for and returns the next connection to the listener. func (l *Listener) Accept() (*Conn, error) { c := <-l.acceptCh if c == nil { // l.acceptCh got closed return nil, errClosedListener } return c, nil } // Addr returns the listener's network address. func (l *Listener) Addr() net.Addr { return l.pConn.LocalAddr() } // Close closes the listener. // It is like Shutdown with a zero graceTimeout. func (l *Listener) Close() error { return l.Shutdown(0) } // close should not be called more than once. func (l *Listener) close() error { l.mu.Lock() defer l.mu.Unlock() err := l.pConn.Close() for k, v := range l.conns { v.close() delete(l.conns, k) } close(l.acceptCh) return err } // Shutdown closes the listener. // It immediately stops accepting new sessions, // and it waits for all existing sessions to terminate, // and a maximum of graceTimeout. // Then it forces close any session left. func (l *Listener) Shutdown(graceTimeout time.Duration) error { l.mu.Lock() if !l.accepting { l.mu.Unlock() return nil } l.accepting = false l.mu.Unlock() retryInterval := closeRetryInterval if retryInterval > graceTimeout { retryInterval = graceTimeout } start := time.Now() end := start.Add(graceTimeout) for !time.Now().After(end) { l.mu.RLock() if len(l.conns) == 0 { l.mu.RUnlock() break } l.mu.RUnlock() time.Sleep(retryInterval) } return l.close() } // readLoop receives all packets from all remotes. // If a packet comes from a remote that is already known to us (i.e. a "session"), // we find that session, and otherwise we create a new one. // We then send the data the session's readLoop. func (l *Listener) readLoop() { for { // Allocating a new buffer for every read avoids // overwriting data in c.msgs in case the next packet is received // before c.msgs is emptied via Read() buf := make([]byte, maxDatagramSize) n, raddr, err := l.pConn.ReadFrom(buf) if err != nil { return } conn, err := l.getConn(raddr) if err != nil { continue } select { case conn.receiveCh <- buf[:n]: case <-conn.doneCh: continue } } } // getConn returns the ongoing session with raddr if it exists, or creates a new // one otherwise. func (l *Listener) getConn(raddr net.Addr) (*Conn, error) { l.mu.Lock() defer l.mu.Unlock() conn, ok := l.conns[raddr.String()] if ok { return conn, nil } if !l.accepting { return nil, errClosedListener } conn = l.newConn(raddr) l.conns[raddr.String()] = conn l.acceptCh <- conn go conn.readLoop() return conn, nil } func (l *Listener) newConn(rAddr net.Addr) *Conn { return &Conn{ listener: l, rAddr: rAddr, receiveCh: make(chan []byte), readCh: make(chan []byte), sizeCh: make(chan int), doneCh: make(chan struct{}), timeout: l.timeout, } } // Conn represents an on-going session with a client, over UDP packets. type Conn struct { listener *Listener rAddr net.Addr receiveCh chan []byte // to receive the data from the listener's readLoop readCh chan []byte // to receive the buffer into which we should Read sizeCh chan int // to synchronize with the end of a Read msgs [][]byte // to store data from listener, to be consumed by Reads muActivity sync.RWMutex lastActivity time.Time // the last time the session saw either read or write activity timeout time.Duration // for timeouts doneOnce sync.Once doneCh chan struct{} } // readLoop waits for data to come from the listener's readLoop. // It then waits for a Read operation to be ready to consume said data, // that is to say it waits on readCh to receive the slice of bytes that the Read operation wants to read onto. // The Read operation receives the signal that the data has been written to the slice of bytes through the sizeCh. func (c *Conn) readLoop() { ticker := time.NewTicker(c.timeout / 10) defer ticker.Stop() for { if len(c.msgs) == 0 { select { case msg := <-c.receiveCh: c.msgs = append(c.msgs, msg) case <-ticker.C: c.muActivity.RLock() deadline := c.lastActivity.Add(c.timeout) c.muActivity.RUnlock() if time.Now().After(deadline) { c.Close() return } continue } } select { case cBuf := <-c.readCh: msg := c.msgs[0] c.msgs = c.msgs[1:] n := copy(cBuf, msg) c.sizeCh <- n case msg := <-c.receiveCh: c.msgs = append(c.msgs, msg) case <-ticker.C: c.muActivity.RLock() deadline := c.lastActivity.Add(c.timeout) c.muActivity.RUnlock() if time.Now().After(deadline) { c.Close() return } } } } // Read reads up to len(p) bytes into p from the connection. // Each call corresponds to at most one datagram. // If p is smaller than the datagram, the extra bytes will be discarded. func (c *Conn) Read(p []byte) (int, error) { select { case c.readCh <- p: n := <-c.sizeCh c.muActivity.Lock() c.lastActivity = time.Now() c.muActivity.Unlock() return n, nil case <-c.doneCh: return 0, io.EOF } } // Write writes len(p) bytes from p to the underlying connection. // Each call sends at most one datagram. // It is an error to send a message larger than the system's max UDP datagram size. func (c *Conn) Write(p []byte) (n int, err error) { c.muActivity.Lock() c.lastActivity = time.Now() c.muActivity.Unlock() return c.listener.pConn.WriteTo(p, c.rAddr) } func (c *Conn) close() { c.doneOnce.Do(func() { close(c.doneCh) }) } // Close releases resources related to the Conn. func (c *Conn) Close() error { c.close() c.listener.mu.Lock() defer c.listener.mu.Unlock() delete(c.listener.conns, c.rAddr.String()) return nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/udp/handler.go
pkg/udp/handler.go
package udp // Handler is the UDP counterpart of the usual HTTP handler. type Handler interface { ServeUDP(conn *Conn) } // The HandlerFunc type is an adapter to allow the use of ordinary functions as handlers. type HandlerFunc func(conn *Conn) // ServeUDP implements the Handler interface for UDP. func (f HandlerFunc) ServeUDP(conn *Conn) { f(conn) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/version/version.go
pkg/version/version.go
package version import ( "context" "net/http" "net/url" "time" "github.com/google/go-github/v28/github" "github.com/gorilla/mux" goversion "github.com/hashicorp/go-version" "github.com/rs/zerolog/log" "github.com/unrolled/render" ) var ( // Version holds the current version of traefik. Version = "dev" // Codename holds the current version codename of traefik. Codename = "cheddar" // beta cheese // BuildDate holds the build date of traefik. BuildDate = "I don't remember exactly" // StartDate holds the start date of traefik. StartDate = time.Now() // DisableDashboardAd disables ad in the dashboard. DisableDashboardAd = false // DashboardName holds the custom name for the dashboard. DashboardName = "" ) // Handler expose version routes. type Handler struct{} var templatesRenderer = render.New(render.Options{ Directory: "nowhere", }) // Append adds version routes on a router. func (v Handler) Append(router *mux.Router) { router.Methods(http.MethodGet).Path("/api/version"). HandlerFunc(func(response http.ResponseWriter, request *http.Request) { v := struct { Version string Codename string StartDate time.Time `json:"startDate"` UUID string `json:"uuid,omitempty"` DisableDashboardAd bool `json:"disableDashboardAd,omitempty"` DashboardName string `json:"dashboardName,omitempty"` }{ Version: Version, Codename: Codename, StartDate: StartDate, DisableDashboardAd: DisableDashboardAd, DashboardName: DashboardName, } if err := templatesRenderer.JSON(response, http.StatusOK, v); err != nil { log.Error().Err(err).Send() } }) } // CheckNewVersion checks if a new version is available. func CheckNewVersion() { if Version == "dev" { return } client := github.NewClient(nil) updateURL, err := url.Parse("https://update.traefik.io/") if err != nil { log.Warn().Err(err).Msg("Error checking new version") return } client.BaseURL = updateURL releases, resp, err := client.Repositories.ListReleases(context.Background(), "traefik", "traefik", nil) if err != nil { log.Warn().Err(err).Msg("Error checking new version") return } if resp.StatusCode != http.StatusOK { log.Warn().Msgf("Error checking new version: status=%s", resp.Status) return } currentVersion, err := goversion.NewVersion(Version) if err != nil { log.Warn().Err(err).Msg("Error checking new version") return } for _, release := range releases { releaseVersion, err := goversion.NewVersion(*release.TagName) if err != nil { log.Warn().Err(err).Msg("Error checking new version") return } if len(currentVersion.Prerelease()) == 0 && len(releaseVersion.Prerelease()) > 0 { continue } if releaseVersion.GreaterThan(currentVersion) { log.Warn().Err(err).Msgf("A new release of Traefik has been found: %s. Please consider updating.", releaseVersion.String()) return } } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/rules/parser.go
pkg/rules/parser.go
package rules import ( "fmt" "strings" "github.com/vulcand/predicate" "golang.org/x/text/cases" "golang.org/x/text/language" ) const ( and = "and" or = "or" ) // TreeBuilder defines the type for a Tree builder. type TreeBuilder func() *Tree // Tree represents the rules' tree structure. type Tree struct { Matcher string Not bool Value []string RuleLeft *Tree RuleRight *Tree } // NewParser constructs a parser for the given matchers. func NewParser(matchers []string) (predicate.Parser, error) { parserFuncs := make(map[string]interface{}) for _, matcherName := range matchers { fn := func(value ...string) TreeBuilder { return func() *Tree { return &Tree{ Matcher: matcherName, Value: value, } } } parserFuncs[matcherName] = fn parserFuncs[strings.ToLower(matcherName)] = fn parserFuncs[strings.ToUpper(matcherName)] = fn parserFuncs[cases.Title(language.Und).String(strings.ToLower(matcherName))] = fn } return predicate.NewParser(predicate.Def{ Operators: predicate.Operators{ AND: andFunc, OR: orFunc, NOT: notFunc, }, Functions: parserFuncs, }) } func andFunc(left, right TreeBuilder) TreeBuilder { return func() *Tree { return &Tree{ Matcher: and, RuleLeft: left(), RuleRight: right(), } } } func orFunc(left, right TreeBuilder) TreeBuilder { return func() *Tree { return &Tree{ Matcher: or, RuleLeft: left(), RuleRight: right(), } } } func invert(t *Tree) *Tree { switch t.Matcher { case or: t.Matcher = and t.RuleLeft = invert(t.RuleLeft) t.RuleRight = invert(t.RuleRight) case and: t.Matcher = or t.RuleLeft = invert(t.RuleLeft) t.RuleRight = invert(t.RuleRight) default: t.Not = !t.Not } return t } func notFunc(elem TreeBuilder) TreeBuilder { return func() *Tree { return invert(elem()) } } // ParseMatchers returns the subset of matchers in the Tree matching the given matchers. func (tree *Tree) ParseMatchers(matchers []string) []string { switch tree.Matcher { case and, or: return append(tree.RuleLeft.ParseMatchers(matchers), tree.RuleRight.ParseMatchers(matchers)...) default: for _, matcher := range matchers { if tree.Matcher == matcher { return lower(tree.Value) } } return nil } } // CheckRule validates the given rule. func CheckRule(rule *Tree) error { if len(rule.Value) == 0 { return fmt.Errorf("no args for matcher %s", rule.Matcher) } for _, v := range rule.Value { if len(v) == 0 { return fmt.Errorf("empty args for matcher %s, %v", rule.Matcher, rule.Value) } } return nil } func lower(slice []string) []string { var lowerStrings []string for _, value := range slice { lowerStrings = append(lowerStrings, strings.ToLower(value)) } return lowerStrings }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/rules/parser_test.go
pkg/rules/parser_test.go
package rules import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // testTree = Tree + CheckErr type testTree struct { Matcher string Not bool Value []string RuleLeft *testTree RuleRight *testTree // CheckErr allow knowing if a Tree has a rule error. CheckErr bool } func TestRuleMatch(t *testing.T) { matchers := []string{"m"} testCases := []struct { desc string rule string tree testTree matchers []string values []string expectParseErr bool }{ { desc: "No rule", rule: "", expectParseErr: true, }, { desc: "No matcher in rule", rule: "m", expectParseErr: true, }, { desc: "No value in rule", rule: "m()", tree: testTree{ Matcher: "m", Value: []string{}, CheckErr: true, }, }, { desc: "Empty value in rule", rule: "m(``)", tree: testTree{ Matcher: "m", Value: []string{""}, CheckErr: true, }, matchers: []string{"m"}, values: []string{""}, }, { desc: "One value in rule with and", rule: "m(`1`) &&", expectParseErr: true, }, { desc: "One value in rule with or", rule: "m(`1`) ||", expectParseErr: true, }, { desc: "One value in rule with missing back tick", rule: "m(`1)", expectParseErr: true, }, { desc: "One value in rule with missing opening parenthesis", rule: "m(`1`))", expectParseErr: true, }, { desc: "One value in rule with missing closing parenthesis", rule: "(m(`1`)", expectParseErr: true, }, { desc: "One value in rule", rule: "m(`1`)", tree: testTree{ Matcher: "m", Value: []string{"1"}, }, matchers: []string{"m"}, values: []string{"1"}, }, { desc: "One value in rule with superfluous parenthesis", rule: "(m(`1`))", tree: testTree{ Matcher: "m", Value: []string{"1"}, }, matchers: []string{"m"}, values: []string{"1"}, }, { desc: "Rule with CAPS matcher", rule: "M(`1`)", tree: testTree{ Matcher: "m", Value: []string{"1"}, }, matchers: []string{"m"}, values: []string{"1"}, }, { desc: "Invalid matcher in rule", rule: "w(`1`)", expectParseErr: true, }, { desc: "Invalid matchers", rule: "m(`1`)", tree: testTree{ Matcher: "m", Value: []string{"1"}, }, matchers: []string{"not-m"}, }, { desc: "Two value in rule", rule: "m(`1`, `2`)", tree: testTree{ Matcher: "m", Value: []string{"1", "2"}, }, matchers: []string{"m"}, values: []string{"1", "2"}, }, { desc: "Not one value in rule", rule: "!m(`1`)", tree: testTree{ Matcher: "m", Not: true, Value: []string{"1"}, }, matchers: []string{"m"}, values: []string{"1"}, }, { desc: "Two value in rule with and", rule: "m(`1`) && m(`2`)", tree: testTree{ Matcher: "and", CheckErr: true, RuleLeft: &testTree{ Matcher: "m", Value: []string{"1"}, }, RuleRight: &testTree{ Matcher: "m", Value: []string{"2"}, }, }, matchers: []string{"m"}, values: []string{"1", "2"}, }, { desc: "Two value in rule with or", rule: "m(`1`) || m(`2`)", tree: testTree{ Matcher: "or", CheckErr: true, RuleLeft: &testTree{ Matcher: "m", Value: []string{"1"}, }, RuleRight: &testTree{ Matcher: "m", Value: []string{"2"}, }, }, matchers: []string{"m"}, values: []string{"1", "2"}, }, { desc: "Two value in rule with and negated", rule: "!(m(`1`) && m(`2`))", tree: testTree{ Matcher: "or", CheckErr: true, RuleLeft: &testTree{ Matcher: "m", Not: true, Value: []string{"1"}, }, RuleRight: &testTree{ Matcher: "m", Not: true, Value: []string{"2"}, }, }, matchers: []string{"m"}, values: []string{"1", "2"}, }, { desc: "Two value in rule with or negated", rule: "!(m(`1`) || m(`2`))", tree: testTree{ Matcher: "and", CheckErr: true, RuleLeft: &testTree{ Matcher: "m", Not: true, Value: []string{"1"}, }, RuleRight: &testTree{ Matcher: "m", Not: true, Value: []string{"2"}, }, }, matchers: []string{"m"}, values: []string{"1", "2"}, }, { desc: "No value in rule", rule: "m(`1`) && m()", tree: testTree{ Matcher: "and", CheckErr: true, RuleLeft: &testTree{ Matcher: "m", Value: []string{"1"}, }, RuleRight: &testTree{ Matcher: "m", Value: []string{}, CheckErr: true, }, }, matchers: []string{"m"}, values: []string{"1"}, }, } parser, err := NewParser(matchers) require.NoError(t, err) for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() parse, err := parser.Parse(test.rule) if test.expectParseErr { require.Error(t, err) return } require.NoError(t, err) treeBuilder, ok := parse.(TreeBuilder) require.True(t, ok) tree := treeBuilder() checkEquivalence(t, &test.tree, tree) assert.Equal(t, test.values, tree.ParseMatchers(test.matchers)) }) } } func checkEquivalence(t *testing.T, expected *testTree, actual *Tree) { t.Helper() if actual == nil { return } if actual.RuleLeft != nil { checkEquivalence(t, expected.RuleLeft, actual.RuleLeft) } if actual.RuleRight != nil { checkEquivalence(t, expected.RuleRight, actual.RuleRight) } assert.Equal(t, expected.Matcher, actual.Matcher) assert.Equal(t, expected.Not, actual.Not) assert.Equal(t, expected.Value, actual.Value) t.Logf("%+v -> %v", actual, CheckRule(actual)) if expected.CheckErr { assert.Error(t, CheckRule(actual)) } else { assert.NoError(t, CheckRule(actual)) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/observability.go
pkg/observability/observability.go
package observability import ( "fmt" "os" ) func EnsureUserEnvVar() error { if os.Getenv("USER") == "" { if err := os.Setenv("USER", "traefik"); err != nil { return fmt.Errorf("could not set USER environment variable: %w", err) } } return nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/elastic_test.go
pkg/observability/logs/elastic_test.go
package logs import ( "bytes" "os" "testing" "time" "github.com/rs/zerolog" "github.com/stretchr/testify/assert" ) func TestNewElasticLogger(t *testing.T) { buf := bytes.NewBuffer(nil) cwb := zerolog.ConsoleWriter{Out: buf, TimeFormat: time.RFC3339, NoColor: true} out := zerolog.MultiLevelWriter(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}, cwb) logger := NewElasticLogger(zerolog.New(out).With().Caller().Logger()) logger.Errorf("foo") assert.Equal(t, "<nil> ERR elastic_test.go:21 > foo\n", buf.String()) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/hclog_test.go
pkg/observability/logs/hclog_test.go
package logs import ( "bytes" "os" "testing" "time" "github.com/rs/zerolog" "github.com/stretchr/testify/assert" ) func TestNewRetryableHTTPLogger(t *testing.T) { buf := bytes.NewBuffer(nil) cwb := zerolog.ConsoleWriter{Out: buf, TimeFormat: time.RFC3339, NoColor: true} out := zerolog.MultiLevelWriter(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}, cwb) logger := NewRetryableHTTPLogger(zerolog.New(out).With().Caller().Logger()) logger.Info("foo") assert.Equal(t, "<nil> INF hclog_test.go:21 > Foo\n", buf.String()) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/log_test.go
pkg/observability/logs/log_test.go
package logs import ( "bytes" "os" "testing" "time" "github.com/rs/zerolog" "github.com/stretchr/testify/assert" ) func TestNoLevel(t *testing.T) { buf := bytes.NewBuffer(nil) cwb := zerolog.ConsoleWriter{Out: buf, TimeFormat: time.RFC3339, NoColor: true} out := zerolog.MultiLevelWriter(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}, cwb) logger := NoLevel(zerolog.New(out).With().Caller().Logger(), zerolog.DebugLevel) logger.Info().Msg("foo") assert.Equal(t, "<nil> INF log_test.go:21 > foo\n", buf.String()) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/logrus.go
pkg/observability/logs/logrus.go
package logs import ( "github.com/rs/zerolog" ) type LogrusStdWrapper struct { logger zerolog.Logger } func NewLogrusWrapper(logger zerolog.Logger) *LogrusStdWrapper { return &LogrusStdWrapper{logger: logger} } func (l LogrusStdWrapper) Print(args ...interface{}) { l.logger.Debug().CallerSkipFrame(1).MsgFunc(msgFunc(args...)) } func (l LogrusStdWrapper) Printf(s string, args ...interface{}) { l.logger.Debug().CallerSkipFrame(1).Msgf(s, args...) } func (l LogrusStdWrapper) Println(args ...interface{}) { l.logger.Debug().CallerSkipFrame(1).MsgFunc(msgFunc(args...)) } func (l LogrusStdWrapper) Fatal(args ...interface{}) { l.logger.Fatal().CallerSkipFrame(1).MsgFunc(msgFunc(args...)) } func (l LogrusStdWrapper) Fatalf(s string, args ...interface{}) { l.logger.Fatal().CallerSkipFrame(1).Msgf(s, args...) } func (l LogrusStdWrapper) Fatalln(args ...interface{}) { l.logger.Fatal().CallerSkipFrame(1).MsgFunc(msgFunc(args...)) } func (l LogrusStdWrapper) Panic(args ...interface{}) { l.logger.Panic().CallerSkipFrame(1).MsgFunc(msgFunc(args...)) } func (l LogrusStdWrapper) Panicf(s string, args ...interface{}) { l.logger.Panic().CallerSkipFrame(1).Msgf(s, args...) } func (l LogrusStdWrapper) Panicln(args ...interface{}) { l.logger.Panic().CallerSkipFrame(1).MsgFunc(msgFunc(args...)) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/instana_test.go
pkg/observability/logs/instana_test.go
package logs import ( "bytes" "os" "testing" "time" "github.com/rs/zerolog" "github.com/stretchr/testify/assert" ) func TestNewInstanaLogger(t *testing.T) { buf := bytes.NewBuffer(nil) cwb := zerolog.ConsoleWriter{Out: buf, TimeFormat: time.RFC3339, NoColor: true} out := zerolog.MultiLevelWriter(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}, cwb) logger := NewInstanaLogger(zerolog.New(out).With().Caller().Logger()) logger.Info("foo") assert.Equal(t, "<nil> INF instana_test.go:21 > foo\n", buf.String()) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/instana.go
pkg/observability/logs/instana.go
package logs import ( "github.com/rs/zerolog" ) type InstanaLogger struct { logger zerolog.Logger } func NewInstanaLogger(logger zerolog.Logger) *InstanaLogger { return &InstanaLogger{logger: logger} } func (l InstanaLogger) Debug(args ...interface{}) { l.logger.Debug().CallerSkipFrame(1).MsgFunc(msgFunc(args...)) } func (l InstanaLogger) Info(args ...interface{}) { l.logger.Info().CallerSkipFrame(1).MsgFunc(msgFunc(args...)) } func (l InstanaLogger) Warn(args ...interface{}) { l.logger.Warn().CallerSkipFrame(1).MsgFunc(msgFunc(args...)) } func (l InstanaLogger) Error(args ...interface{}) { l.logger.Error().CallerSkipFrame(1).MsgFunc(msgFunc(args...)) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/otel_test.go
pkg/observability/logs/otel_test.go
package logs import ( "compress/gzip" "encoding/json" "io" "net/http" "net/http/httptest" "os" "testing" "time" "github.com/rs/zerolog" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" otypes "github.com/traefik/traefik/v3/pkg/observability/types" "go.opentelemetry.io/collector/pdata/plog/plogotlp" "go.opentelemetry.io/otel/trace" ) func TestLog(t *testing.T) { tests := []struct { desc string level zerolog.Level assertFn func(*testing.T, string) noLog bool }{ { desc: "no level log", level: zerolog.NoLevel, assertFn: func(t *testing.T, log string) { t.Helper() // SeverityUndefined Severity = 0 // UNDEFINED assert.NotContains(t, log, `"severityNumber"`) assert.Regexp(t, `{"key":"resource","value":{"stringValue":"attribute"}}`, log) assert.Regexp(t, `{"key":"service.name","value":{"stringValue":"test"}}`, log) assert.Regexp(t, `"body":{"stringValue":"test"}`, log) assert.Regexp(t, `{"key":"foo","value":{"stringValue":"bar"}}`, log) assert.Regexp(t, `"traceId":"01020304050607080000000000000000","spanId":"0102030405060708"`, log) }, }, { desc: "trace log", level: zerolog.TraceLevel, assertFn: func(t *testing.T, log string) { t.Helper() // SeverityTrace1 Severity = 1 // TRACE assert.Contains(t, log, `"severityNumber":1`) assert.Regexp(t, `{"key":"resource","value":{"stringValue":"attribute"}}`, log) assert.Regexp(t, `{"key":"service.name","value":{"stringValue":"test"}}`, log) assert.Regexp(t, `"body":{"stringValue":"test"}`, log) assert.Regexp(t, `{"key":"foo","value":{"stringValue":"bar"}}`, log) assert.Regexp(t, `"traceId":"01020304050607080000000000000000","spanId":"0102030405060708"`, log) }, }, { desc: "debug log", level: zerolog.DebugLevel, assertFn: func(t *testing.T, log string) { t.Helper() // SeverityDebug1 Severity = 5 // DEBUG assert.Contains(t, log, `"severityNumber":5`) assert.Regexp(t, `{"key":"resource","value":{"stringValue":"attribute"}}`, log) assert.Regexp(t, `{"key":"service.name","value":{"stringValue":"test"}}`, log) assert.Regexp(t, `"body":{"stringValue":"test"}`, log) assert.Regexp(t, `{"key":"foo","value":{"stringValue":"bar"}}`, log) assert.Regexp(t, `"traceId":"01020304050607080000000000000000","spanId":"0102030405060708"`, log) }, }, { desc: "info log", level: zerolog.InfoLevel, assertFn: func(t *testing.T, log string) { t.Helper() // SeverityInfo1 Severity = 9 // INFO assert.Contains(t, log, `"severityNumber":9`) assert.Regexp(t, `{"key":"resource","value":{"stringValue":"attribute"}}`, log) assert.Regexp(t, `{"key":"service.name","value":{"stringValue":"test"}}`, log) assert.Regexp(t, `"body":{"stringValue":"test"}`, log) assert.Regexp(t, `{"key":"foo","value":{"stringValue":"bar"}}`, log) assert.Regexp(t, `"traceId":"01020304050607080000000000000000","spanId":"0102030405060708"`, log) }, }, { desc: "warn log", level: zerolog.WarnLevel, assertFn: func(t *testing.T, log string) { t.Helper() // SeverityWarn1 Severity = 13 // WARN assert.Contains(t, log, `"severityNumber":13`) assert.Regexp(t, `{"key":"resource","value":{"stringValue":"attribute"}}`, log) assert.Regexp(t, `{"key":"service.name","value":{"stringValue":"test"}}`, log) assert.Regexp(t, `"body":{"stringValue":"test"}`, log) assert.Regexp(t, `{"key":"foo","value":{"stringValue":"bar"}}`, log) assert.Regexp(t, `"traceId":"01020304050607080000000000000000","spanId":"0102030405060708"`, log) }, }, { desc: "error log", level: zerolog.ErrorLevel, assertFn: func(t *testing.T, log string) { t.Helper() // SeverityError1 Severity = 17 // ERROR assert.Contains(t, log, `"severityNumber":17`) assert.Regexp(t, `{"key":"resource","value":{"stringValue":"attribute"}}`, log) assert.Regexp(t, `{"key":"service.name","value":{"stringValue":"test"}}`, log) assert.Regexp(t, `"body":{"stringValue":"test"}`, log) assert.Regexp(t, `{"key":"foo","value":{"stringValue":"bar"}}`, log) assert.Regexp(t, `"traceId":"01020304050607080000000000000000","spanId":"0102030405060708"`, log) }, }, { desc: "fatal log", level: zerolog.FatalLevel, assertFn: func(t *testing.T, log string) { t.Helper() // SeverityFatal Severity = 21 // FATAL assert.Contains(t, log, `"severityNumber":21`) assert.Regexp(t, `{"key":"resource","value":{"stringValue":"attribute"}}`, log) assert.Regexp(t, `{"key":"service.name","value":{"stringValue":"test"}}`, log) assert.Regexp(t, `"body":{"stringValue":"test"}`, log) assert.Regexp(t, `{"key":"foo","value":{"stringValue":"bar"}}`, log) assert.Regexp(t, `"traceId":"01020304050607080000000000000000","spanId":"0102030405060708"`, log) }, }, { desc: "panic log", level: zerolog.PanicLevel, assertFn: func(t *testing.T, log string) { t.Helper() // SeverityFatal4 Severity = 24 // FATAL assert.Contains(t, log, `"severityNumber":24`) assert.Regexp(t, `{"key":"resource","value":{"stringValue":"attribute"}}`, log) assert.Regexp(t, `{"key":"service.name","value":{"stringValue":"test"}}`, log) assert.Regexp(t, `"body":{"stringValue":"test"}`, log) assert.Regexp(t, `{"key":"foo","value":{"stringValue":"bar"}}`, log) assert.Regexp(t, `"traceId":"01020304050607080000000000000000","spanId":"0102030405060708"`, log) }, }, } logCh := make(chan string) collector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gzr, err := gzip.NewReader(r.Body) require.NoError(t, err) body, err := io.ReadAll(gzr) require.NoError(t, err) req := plogotlp.NewExportRequest() err = req.UnmarshalProto(body) require.NoError(t, err) marshalledReq, err := json.Marshal(req) require.NoError(t, err) logCh <- string(marshalledReq) })) t.Cleanup(collector.Close) for _, test := range tests { t.Run(test.desc, func(t *testing.T) { config := &otypes.OTelLog{ ServiceName: "test", ResourceAttributes: map[string]string{"resource": "attribute"}, HTTP: &otypes.OTelHTTP{ Endpoint: collector.URL, }, } out := zerolog.MultiLevelWriter(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}) logger := zerolog.New(out).With().Caller().Logger() logger, err := SetupOTelLogger(t.Context(), logger, config) require.NoError(t, err) ctx := trace.ContextWithSpanContext(t.Context(), trace.NewSpanContext(trace.SpanContextConfig{ TraceID: trace.TraceID{0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8}, SpanID: trace.SpanID{0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8}, })) logger = logger.With().Ctx(ctx).Logger() logger.WithLevel(test.level).Str("foo", "bar").Msg("test") select { case <-time.After(5 * time.Second): t.Error("Log not exported") case log := <-logCh: if test.assertFn != nil { test.assertFn(t, log) } } }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/wasm.go
pkg/observability/logs/wasm.go
package logs import ( "context" "github.com/http-wasm/http-wasm-host-go/api" "github.com/rs/zerolog" ) // compile-time check to ensure ConsoleLogger implements api.Logger. var _ api.Logger = WasmLogger{} // WasmLogger is a convenience which writes anything above LogLevelInfo to os.Stdout. type WasmLogger struct { logger *zerolog.Logger } func NewWasmLogger(logger *zerolog.Logger) *WasmLogger { return &WasmLogger{ logger: logger, } } // IsEnabled implements the same method as documented on api.Logger. func (w WasmLogger) IsEnabled(level api.LogLevel) bool { return true } // Log implements the same method as documented on api.Logger. func (w WasmLogger) Log(_ context.Context, level api.LogLevel, message string) { w.logger.WithLevel(zerolog.Level(level + 1)).Msg(message) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/hclog.go
pkg/observability/logs/hclog.go
package logs import ( "fmt" "strings" "unicode" "github.com/rs/zerolog" ) // RetryableHTTPLogger wraps our logger and implements retryablehttp.LeveledLogger. // The retry library sends fields as pairs of keys and values as structured logging, // so we need to adapt them to our logger. type RetryableHTTPLogger struct { logger zerolog.Logger } // NewRetryableHTTPLogger creates an implementation of the retryablehttp.LeveledLogger. func NewRetryableHTTPLogger(logger zerolog.Logger) *RetryableHTTPLogger { return &RetryableHTTPLogger{logger: logger} } // Error starts a new message with error level. func (l RetryableHTTPLogger) Error(msg string, keysAndValues ...interface{}) { logWithLevel(l.logger.Error().CallerSkipFrame(2), msg, keysAndValues...) } // Info starts a new message with info level. func (l RetryableHTTPLogger) Info(msg string, keysAndValues ...interface{}) { logWithLevel(l.logger.Info().CallerSkipFrame(2), msg, keysAndValues...) } // Debug starts a new message with debug level. func (l RetryableHTTPLogger) Debug(msg string, keysAndValues ...interface{}) { logWithLevel(l.logger.Debug().CallerSkipFrame(2), msg, keysAndValues...) } // Warn starts a new message with warn level. func (l RetryableHTTPLogger) Warn(msg string, keysAndValues ...interface{}) { logWithLevel(l.logger.Warn().CallerSkipFrame(2), msg, keysAndValues...) } func logWithLevel(ev *zerolog.Event, msg string, kvs ...interface{}) { if len(kvs)%2 == 0 { for i := 0; i < len(kvs)-1; i += 2 { // The first item of the pair (the key) is supposed to be a string. key, ok := kvs[i].(string) if !ok { continue } val := kvs[i+1] var s fmt.Stringer if s, ok = val.(fmt.Stringer); ok { ev.Str(key, s.String()) } else { ev.Interface(key, val) } } } // Capitalize first character. first := true msg = strings.Map(func(r rune) rune { if first { first = false return unicode.ToTitle(r) } return r }, msg) ev.Msg(msg) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/log.go
pkg/observability/logs/log.go
package logs import ( "fmt" "github.com/rs/zerolog" ) func NoLevel(logger zerolog.Logger, level zerolog.Level) zerolog.Logger { return logger.Hook(NewNoLevelHook(logger.GetLevel(), level)) } type NoLevelHook struct { minLevel zerolog.Level level zerolog.Level } func NewNoLevelHook(minLevel zerolog.Level, level zerolog.Level) *NoLevelHook { return &NoLevelHook{minLevel: minLevel, level: level} } func (n NoLevelHook) Run(e *zerolog.Event, level zerolog.Level, _ string) { if n.minLevel > n.level { e.Discard() return } if level == zerolog.NoLevel { e.Str("level", n.level.String()) } } func msgFunc(i ...any) func() string { return func() string { return fmt.Sprint(i...) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/datadog_test.go
pkg/observability/logs/datadog_test.go
package logs import ( "bytes" "os" "testing" "time" "github.com/rs/zerolog" "github.com/stretchr/testify/assert" ) func TestNewDatadogLogger(t *testing.T) { buf := bytes.NewBuffer(nil) cwb := zerolog.ConsoleWriter{Out: buf, TimeFormat: time.RFC3339, NoColor: true} out := zerolog.MultiLevelWriter(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}, cwb) logger := NewDatadogLogger(zerolog.New(out).With().Caller().Logger()) logger.Log("foo") assert.Equal(t, "<nil> DBG datadog_test.go:21 > foo\n", buf.String()) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/aws.go
pkg/observability/logs/aws.go
package logs import ( "github.com/aws/smithy-go/logging" "github.com/rs/zerolog" ) func NewAWSWrapper(logger zerolog.Logger) logging.LoggerFunc { if logger.GetLevel() > zerolog.DebugLevel { return func(classification logging.Classification, format string, args ...interface{}) {} } return func(classification logging.Classification, format string, args ...interface{}) { logger.Debug().CallerSkipFrame(2).MsgFunc(msgFunc(args...)) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/logrus_test.go
pkg/observability/logs/logrus_test.go
package logs import ( "bytes" "os" "testing" "time" "github.com/rs/zerolog" "github.com/stretchr/testify/assert" ) func TestNewLogrusStdWrapper(t *testing.T) { buf := bytes.NewBuffer(nil) cwb := zerolog.ConsoleWriter{Out: buf, TimeFormat: time.RFC3339, NoColor: true} out := zerolog.MultiLevelWriter(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}, cwb) logger := NewLogrusWrapper(zerolog.New(out).With().Caller().Logger()) logger.Println("foo") assert.Equal(t, "<nil> DBG logrus_test.go:21 > foo\n", buf.String()) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/oxy.go
pkg/observability/logs/oxy.go
package logs import "github.com/rs/zerolog" type OxyWrapper struct { logger zerolog.Logger } func NewOxyWrapper(logger zerolog.Logger) *OxyWrapper { return &OxyWrapper{logger: logger} } func (l OxyWrapper) Debug(s string, i ...interface{}) { l.logger.Debug().CallerSkipFrame(1).Msgf(s, i...) } func (l OxyWrapper) Info(s string, i ...interface{}) { l.logger.Info().CallerSkipFrame(1).Msgf(s, i...) } func (l OxyWrapper) Warn(s string, i ...interface{}) { l.logger.Warn().CallerSkipFrame(1).Msgf(s, i...) } func (l OxyWrapper) Error(s string, i ...interface{}) { l.logger.Error().CallerSkipFrame(1).Msgf(s, i...) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/gokit.go
pkg/observability/logs/gokit.go
package logs import ( kitlog "github.com/go-kit/log" "github.com/rs/zerolog" ) func NewGoKitWrapper(logger zerolog.Logger) kitlog.LoggerFunc { if logger.GetLevel() > zerolog.DebugLevel { return func(args ...interface{}) error { return nil } } return func(args ...interface{}) error { logger.Debug().CallerSkipFrame(2).MsgFunc(msgFunc(args...)) return nil } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/otel.go
pkg/observability/logs/otel.go
package logs import ( "context" "encoding/json" "fmt" "reflect" "time" "github.com/rs/zerolog" "github.com/traefik/traefik/v3/pkg/observability" "github.com/traefik/traefik/v3/pkg/observability/types" otellog "go.opentelemetry.io/otel/log" ) // SetupOTelLogger sets up the OpenTelemetry logger. func SetupOTelLogger(ctx context.Context, logger zerolog.Logger, config *types.OTelLog) (zerolog.Logger, error) { if config == nil { return logger, nil } if err := observability.EnsureUserEnvVar(); err != nil { return zerolog.Logger{}, err } provider, err := config.NewLoggerProvider(ctx) if err != nil { return zerolog.Logger{}, fmt.Errorf("setting up OpenTelemetry logger provider: %w", err) } return logger.Hook(&otelLoggerHook{logger: provider.Logger("traefik")}), nil } // otelLoggerHook is a zerolog hook that forwards logs to OpenTelemetry. type otelLoggerHook struct { logger otellog.Logger } // Run forwards the log message to OpenTelemetry. func (h *otelLoggerHook) Run(e *zerolog.Event, level zerolog.Level, message string) { if level == zerolog.Disabled { return } var record otellog.Record record.SetTimestamp(time.Now().UTC()) record.SetSeverity(otelLogSeverity(level)) record.SetBody(otellog.StringValue(message)) // See https://github.com/rs/zerolog/issues/493. // This is a workaround to get the log fields from the event. // At the moment there's no way to get the log fields from the event, so we use reflection to get the buffer and parse it. logData := make(map[string]any) eventBuffer := fmt.Sprintf("%s}", reflect.ValueOf(e).Elem().FieldByName("buf")) if err := json.Unmarshal([]byte(eventBuffer), &logData); err != nil { record.AddAttributes(otellog.String("parsing_error", fmt.Sprintf("parsing log fields: %s", err))) h.logger.Emit(e.GetCtx(), record) return } recordAttributes := make([]otellog.KeyValue, 0, len(logData)) for k, v := range logData { if k == "level" { continue } if k == "time" { eventTimestamp, ok := v.(string) if !ok { continue } t, err := time.Parse(time.RFC3339, eventTimestamp) if err == nil { record.SetTimestamp(t) continue } } var attributeValue otellog.Value switch v := v.(type) { case string: attributeValue = otellog.StringValue(v) case int: attributeValue = otellog.IntValue(v) case int64: attributeValue = otellog.Int64Value(v) case float64: attributeValue = otellog.Float64Value(v) case bool: attributeValue = otellog.BoolValue(v) case []byte: attributeValue = otellog.BytesValue(v) default: attributeValue = otellog.StringValue(fmt.Sprintf("%v", v)) } recordAttributes = append(recordAttributes, otellog.KeyValue{ Key: k, Value: attributeValue, }) } record.AddAttributes(recordAttributes...) h.logger.Emit(e.GetCtx(), record) } func otelLogSeverity(level zerolog.Level) otellog.Severity { switch level { case zerolog.TraceLevel: return otellog.SeverityTrace case zerolog.DebugLevel: return otellog.SeverityDebug case zerolog.InfoLevel: return otellog.SeverityInfo case zerolog.WarnLevel: return otellog.SeverityWarn case zerolog.ErrorLevel: return otellog.SeverityError case zerolog.FatalLevel: return otellog.SeverityFatal case zerolog.PanicLevel: return otellog.SeverityFatal4 default: return otellog.SeverityUndefined } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/aws_test.go
pkg/observability/logs/aws_test.go
package logs import ( "bytes" "os" "testing" "time" "github.com/aws/smithy-go/logging" "github.com/rs/zerolog" "github.com/stretchr/testify/assert" ) func TestNewAWSWrapper(t *testing.T) { buf := bytes.NewBuffer(nil) cwb := zerolog.ConsoleWriter{Out: buf, TimeFormat: time.RFC3339, NoColor: true} out := zerolog.MultiLevelWriter(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}, cwb) logger := NewAWSWrapper(zerolog.New(out).With().Caller().Logger()) logger.Logf(logging.Debug, "%s", "foo") assert.Equal(t, "<nil> DBG aws_test.go:22 > foo\n", buf.String()) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/oxy_test.go
pkg/observability/logs/oxy_test.go
package logs import ( "bytes" "os" "testing" "time" "github.com/rs/zerolog" "github.com/stretchr/testify/assert" ) func TestNewOxyWrapper(t *testing.T) { buf := bytes.NewBuffer(nil) cwb := zerolog.ConsoleWriter{Out: buf, TimeFormat: time.RFC3339, NoColor: true} out := zerolog.MultiLevelWriter(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}, cwb) logger := NewOxyWrapper(zerolog.New(out).With().Caller().Logger()) logger.Info("foo") assert.Equal(t, "<nil> INF oxy_test.go:21 > foo\n", buf.String()) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/datadog.go
pkg/observability/logs/datadog.go
package logs import "github.com/rs/zerolog" type DatadogLogger struct { logger zerolog.Logger } func NewDatadogLogger(logger zerolog.Logger) *DatadogLogger { return &DatadogLogger{logger: logger} } func (d DatadogLogger) Log(msg string) { d.logger.Debug().CallerSkipFrame(1).Msg(msg) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/fields.go
pkg/observability/logs/fields.go
package logs // Log entry names. const ( EntryPointName = "entryPointName" RouterName = "routerName" Rule = "rule" MiddlewareName = "middlewareName" MiddlewareType = "middlewareType" ProviderName = "providerName" ServiceName = "serviceName" MetricsProviderName = "metricsProviderName" TracingProviderName = "tracingProviderName" ServerIndex = "serverIndex" TLSStoreName = "tlsStoreName" ServersTransportName = "serversTransport" )
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/elastic.go
pkg/observability/logs/elastic.go
package logs import "github.com/rs/zerolog" type ElasticLogger struct { logger zerolog.Logger } func NewElasticLogger(logger zerolog.Logger) *ElasticLogger { return &ElasticLogger{logger: logger} } func (l ElasticLogger) Debugf(format string, args ...interface{}) { l.logger.Debug().CallerSkipFrame(1).Msgf(format, args...) } func (l ElasticLogger) Errorf(format string, args ...interface{}) { l.logger.Error().CallerSkipFrame(1).Msgf(format, args...) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/logs/gokit_test.go
pkg/observability/logs/gokit_test.go
package logs import ( "bytes" "os" "testing" "time" "github.com/rs/zerolog" "github.com/stretchr/testify/assert" ) func TestNewGoKitWrapper(t *testing.T) { buf := bytes.NewBuffer(nil) cwb := zerolog.ConsoleWriter{Out: buf, TimeFormat: time.RFC3339, NoColor: true} out := zerolog.MultiLevelWriter(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}, cwb) logger := NewGoKitWrapper(zerolog.New(out).With().Caller().Logger()) _ = logger.Log("foo") assert.Equal(t, "<nil> DBG gokit_test.go:21 > foo\n", buf.String()) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/tracing/tracing_test.go
pkg/observability/tracing/tracing_test.go
package tracing import ( "compress/gzip" "io" "net/http" "net/http/httptest" "net/url" "testing" "time" "github.com/containous/alice" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/static" otypes "github.com/traefik/traefik/v3/pkg/observability/types" "go.opentelemetry.io/collector/pdata/pcommon" "go.opentelemetry.io/collector/pdata/ptrace" "go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp" "go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace/noop" ) func Test_safeFullURL(t *testing.T) { testCases := []struct { desc string safeQueryParams []string originalURL *url.URL expectedURL *url.URL }{ { desc: "Nil URL", originalURL: nil, expectedURL: nil, }, { desc: "No query parameters", originalURL: &url.URL{Scheme: "https", Host: "example.com"}, expectedURL: &url.URL{Scheme: "https", Host: "example.com"}, }, { desc: "All query parameters redacted", originalURL: &url.URL{Scheme: "https", Host: "example.com", RawQuery: "foo=bar&baz=qux"}, expectedURL: &url.URL{Scheme: "https", Host: "example.com", RawQuery: "baz=REDACTED&foo=REDACTED"}, }, { desc: "Some query parameters unredacted", safeQueryParams: []string{"foo"}, originalURL: &url.URL{Scheme: "https", Host: "example.com", RawQuery: "foo=bar&baz=qux"}, expectedURL: &url.URL{Scheme: "https", Host: "example.com", RawQuery: "baz=REDACTED&foo=bar"}, }, { desc: "User info and some query parameters redacted", safeQueryParams: []string{"foo"}, originalURL: &url.URL{Scheme: "https", Host: "example.com", User: url.UserPassword("username", "password"), RawQuery: "foo=bar&baz=qux"}, expectedURL: &url.URL{Scheme: "https", Host: "example.com", User: url.UserPassword("REDACTED", "REDACTED"), RawQuery: "baz=REDACTED&foo=bar"}, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() tr := NewTracer(nil, nil, nil, test.safeQueryParams) gotURL := tr.safeURL(test.originalURL) assert.Equal(t, test.expectedURL, gotURL) }) } } func TestTracing(t *testing.T) { tests := []struct { desc string propagators string headers map[string]string resourceAttributes map[string]string wantServiceHeadersFn func(t *testing.T, headers http.Header) assertFn func(*testing.T, ptrace.Traces) }{ { desc: "service name and version", assertFn: func(t *testing.T, traces ptrace.Traces) { t.Helper() attributes := resourceAttributes(traces) assert.Equal(t, "traefik", attributes["service.name"]) assert.Equal(t, "dev", attributes["service.version"]) }, }, { desc: "resource attributes must be propagated", resourceAttributes: map[string]string{ "service.environment": "custom", }, assertFn: func(t *testing.T, traces ptrace.Traces) { t.Helper() attributes := resourceAttributes(traces) assert.Equal(t, "custom", attributes["service.environment"]) }, }, { desc: "TraceContext propagation", propagators: "tracecontext", headers: map[string]string{ "traceparent": "00-00000000000000000000000000000001-0000000000000001-01", "tracestate": "foo=bar", }, wantServiceHeadersFn: func(t *testing.T, headers http.Header) { t.Helper() assert.Regexp(t, `(00-00000000000000000000000000000001-\w{16}-01)`, headers["Traceparent"][0]) assert.Equal(t, []string{"foo=bar"}, headers["Tracestate"]) }, assertFn: func(t *testing.T, traces ptrace.Traces) { t.Helper() span := mainSpan(traces) assert.Equal(t, "00000000000000000000000000000001", span.TraceID().String()) assert.Equal(t, "0000000000000001", span.ParentSpanID().String()) assert.Equal(t, "foo=bar", span.TraceState().AsRaw()) }, }, { desc: "root span TraceContext propagation", propagators: "tracecontext", wantServiceHeadersFn: func(t *testing.T, headers http.Header) { t.Helper() assert.Regexp(t, `(00-\w{32}-\w{16}-01)`, headers["Traceparent"][0]) }, assertFn: func(t *testing.T, traces ptrace.Traces) { t.Helper() span := mainSpan(traces) assert.Len(t, span.TraceID().String(), 32) assert.Empty(t, span.ParentSpanID().String()) }, }, { desc: "B3 propagation", propagators: "b3", headers: map[string]string{ "b3": "00000000000000000000000000000001-0000000000000002-1-0000000000000001", }, wantServiceHeadersFn: func(t *testing.T, headers http.Header) { t.Helper() assert.Regexp(t, `(00000000000000000000000000000001-\w{16}-1)`, headers["B3"][0]) }, assertFn: func(t *testing.T, traces ptrace.Traces) { t.Helper() span := mainSpan(traces) assert.Equal(t, "00000000000000000000000000000001", span.TraceID().String()) assert.Equal(t, "0000000000000002", span.ParentSpanID().String()) }, }, { desc: "root span B3 propagation", propagators: "b3", wantServiceHeadersFn: func(t *testing.T, headers http.Header) { t.Helper() assert.Regexp(t, `(\w{32}-\w{16}-1)`, headers["B3"][0]) }, assertFn: func(t *testing.T, traces ptrace.Traces) { t.Helper() span := mainSpan(traces) assert.Len(t, span.TraceID().String(), 32) assert.Empty(t, span.ParentSpanID().String()) }, }, { desc: "B3 propagation Multiple Headers", propagators: "b3multi", headers: map[string]string{ "x-b3-traceid": "00000000000000000000000000000001", "x-b3-parentspanid": "0000000000000001", "x-b3-spanid": "0000000000000002", "x-b3-sampled": "1", }, wantServiceHeadersFn: func(t *testing.T, headers http.Header) { t.Helper() assert.Equal(t, "00000000000000000000000000000001", headers["X-B3-Traceid"][0]) assert.Equal(t, "0000000000000001", headers["X-B3-Parentspanid"][0]) assert.Equal(t, "1", headers["X-B3-Sampled"][0]) assert.Len(t, headers["X-B3-Spanid"][0], 16) }, assertFn: func(t *testing.T, traces ptrace.Traces) { t.Helper() span := mainSpan(traces) assert.Equal(t, "00000000000000000000000000000001", span.TraceID().String()) assert.Equal(t, "0000000000000002", span.ParentSpanID().String()) }, }, { desc: "root span B3 propagation Multiple Headers", propagators: "b3multi", wantServiceHeadersFn: func(t *testing.T, headers http.Header) { t.Helper() assert.Regexp(t, `(\w{32})`, headers["X-B3-Traceid"][0]) assert.Equal(t, "1", headers["X-B3-Sampled"][0]) assert.Regexp(t, `(\w{16})`, headers["X-B3-Spanid"][0]) }, assertFn: func(t *testing.T, traces ptrace.Traces) { t.Helper() span := mainSpan(traces) assert.Len(t, span.TraceID().String(), 32) assert.Empty(t, span.ParentSpanID().String()) }, }, { desc: "Baggage propagation", propagators: "baggage", headers: map[string]string{ "baggage": "userId=id", }, wantServiceHeadersFn: func(t *testing.T, headers http.Header) { t.Helper() assert.Equal(t, []string{"userId=id"}, headers["Baggage"]) }, }, { desc: "Jaeger propagation", propagators: "jaeger", headers: map[string]string{ "uber-trace-id": "00000000000000000000000000000001:0000000000000002:0000000000000001:1", }, wantServiceHeadersFn: func(t *testing.T, headers http.Header) { t.Helper() assert.Regexp(t, `(00000000000000000000000000000001:\w{16}:0:1)`, headers["Uber-Trace-Id"][0]) }, assertFn: func(t *testing.T, traces ptrace.Traces) { t.Helper() span := mainSpan(traces) assert.Equal(t, "00000000000000000000000000000001", span.TraceID().String()) assert.Len(t, span.ParentSpanID().String(), 16) }, }, { desc: "root span Jaeger propagation", propagators: "jaeger", wantServiceHeadersFn: func(t *testing.T, headers http.Header) { t.Helper() assert.Regexp(t, `(\w{32}:\w{16}:0:1)`, headers["Uber-Trace-Id"][0]) }, assertFn: func(t *testing.T, traces ptrace.Traces) { t.Helper() span := mainSpan(traces) assert.Len(t, span.TraceID().String(), 32) assert.Empty(t, span.ParentSpanID().String()) }, }, { desc: "XRay propagation", propagators: "xray", headers: map[string]string{ "X-Amzn-Trace-Id": "Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1", }, wantServiceHeadersFn: func(t *testing.T, headers http.Header) { t.Helper() assert.Regexp(t, `(Root=1-5759e988-bd862e3fe1be46a994272793;Parent=\w{16};Sampled=1)`, headers["X-Amzn-Trace-Id"][0]) }, assertFn: func(t *testing.T, traces ptrace.Traces) { t.Helper() span := mainSpan(traces) assert.Equal(t, "5759e988bd862e3fe1be46a994272793", span.TraceID().String()) assert.Len(t, span.ParentSpanID().String(), 16) }, }, { desc: "root span XRay propagation", propagators: "xray", wantServiceHeadersFn: func(t *testing.T, headers http.Header) { t.Helper() assert.Regexp(t, `(Root=1-\w{8}-\w{24};Parent=\w{16};Sampled=1)`, headers["X-Amzn-Trace-Id"][0]) }, assertFn: func(t *testing.T, traces ptrace.Traces) { t.Helper() span := mainSpan(traces) assert.Len(t, span.TraceID().String(), 32) assert.Empty(t, span.ParentSpanID().String()) }, }, { desc: "no propagation", propagators: "none", wantServiceHeadersFn: func(t *testing.T, headers http.Header) { t.Helper() assert.Empty(t, headers) }, assertFn: func(t *testing.T, traces ptrace.Traces) { t.Helper() span := mainSpan(traces) assert.Len(t, span.TraceID().String(), 32) assert.Empty(t, span.ParentSpanID().String()) }, }, } traceCh := make(chan ptrace.Traces) collector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gzr, err := gzip.NewReader(r.Body) require.NoError(t, err) body, err := io.ReadAll(gzr) require.NoError(t, err) req := ptraceotlp.NewExportRequest() err = req.UnmarshalProto(body) require.NoError(t, err) traceCh <- req.Traces() })) t.Cleanup(collector.Close) for _, test := range tests { t.Run(test.desc, func(t *testing.T) { t.Setenv("OTEL_PROPAGATORS", test.propagators) service := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { tracer := TracerFromContext(r.Context()) ctx, span := tracer.Start(r.Context(), "service") defer span.End() r = r.WithContext(ctx) InjectContextIntoCarrier(r) if test.wantServiceHeadersFn != nil { test.wantServiceHeadersFn(t, r.Header) } }) tracingConfig := &static.Tracing{ ServiceName: "traefik", SampleRate: 1.0, ResourceAttributes: test.resourceAttributes, OTLP: &otypes.OTelTracing{ HTTP: &otypes.OTelHTTP{ Endpoint: collector.URL, }, }, } tracer, closer, err := NewTracing(t.Context(), tracingConfig) require.NoError(t, err) t.Cleanup(func() { _ = closer.Close() }) chain := alice.New(func(next http.Handler) (http.Handler, error) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { tracingCtx := ExtractCarrierIntoContext(r.Context(), r.Header) start := time.Now() tracingCtx, span := tracer.Start(tracingCtx, "test", trace.WithSpanKind(trace.SpanKindServer), trace.WithTimestamp(start)) end := time.Now() span.End(trace.WithTimestamp(end)) next.ServeHTTP(w, r.WithContext(tracingCtx)) }), nil }) epHandler, err := chain.Then(service) require.NoError(t, err) req := httptest.NewRequest(http.MethodGet, "http://www.test.com", nil) for k, v := range test.headers { req.Header.Set(k, v) } rw := httptest.NewRecorder() epHandler.ServeHTTP(rw, req) select { case <-time.After(10 * time.Second): t.Error("Trace not exported") case traces := <-traceCh: assert.Equal(t, http.StatusOK, rw.Code) if test.assertFn != nil { test.assertFn(t, traces) } } }) } } // TestTracerProvider ensures that Tracer returns a valid TracerProvider // when using the default Traefik Tracer and a custom one. func TestTracerProvider(t *testing.T) { t.Parallel() otlpConfig := &otypes.OTelTracing{} otlpConfig.SetDefaults() config := &static.Tracing{OTLP: otlpConfig} tracer, closer, err := NewTracing(t.Context(), config) if err != nil { t.Fatal(err) } closer.Close() _, span := tracer.Start(t.Context(), "test") defer span.End() span.TracerProvider().Tracer("github.com/traefik/traefik") span.TracerProvider().Tracer("other") } // TestNewTracer_HeadersCanonicalization tests that NewTracer properly canonicalizes headers. func TestNewTracer_HeadersCanonicalization(t *testing.T) { testCases := []struct { desc string inputHeaders []string expectedCanonicalHeaders []string }{ { desc: "Empty headers", inputHeaders: []string{}, expectedCanonicalHeaders: []string{}, }, { desc: "Already canonical headers", inputHeaders: []string{"Content-Type", "User-Agent", "Accept-Encoding"}, expectedCanonicalHeaders: []string{"Content-Type", "User-Agent", "Accept-Encoding"}, }, { desc: "Lowercase headers", inputHeaders: []string{"content-type", "user-agent", "accept-encoding"}, expectedCanonicalHeaders: []string{"Content-Type", "User-Agent", "Accept-Encoding"}, }, { desc: "Mixed case headers", inputHeaders: []string{"CoNtEnT-tYpE", "uSeR-aGeNt", "aCcEpT-eNcOdInG"}, expectedCanonicalHeaders: []string{"Content-Type", "User-Agent", "Accept-Encoding"}, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() // Create a mock tracer using a no-op tracer from OpenTelemetry mockTracer := noop.NewTracerProvider().Tracer("test") // Test capturedRequestHeaders tracer := NewTracer(mockTracer, test.inputHeaders, nil, nil) assert.Equal(t, test.expectedCanonicalHeaders, tracer.capturedRequestHeaders) assert.Nil(t, tracer.capturedResponseHeaders) // Test capturedResponseHeaders tracer = NewTracer(mockTracer, nil, test.inputHeaders, nil) assert.Equal(t, test.expectedCanonicalHeaders, tracer.capturedResponseHeaders) assert.Nil(t, tracer.capturedRequestHeaders) }) } } // resourceAttributes extracts resource attributes as a map. func resourceAttributes(traces ptrace.Traces) map[string]string { attributes := make(map[string]string) if traces.ResourceSpans().Len() > 0 { resource := traces.ResourceSpans().At(0).Resource() resource.Attributes().Range(func(k string, v pcommon.Value) bool { if v.Type() == pcommon.ValueTypeStr { attributes[k] = v.Str() } return true }) } return attributes } // mainSpan gets the main span from traces (assumes single span for testing). func mainSpan(traces ptrace.Traces) ptrace.Span { for _, resourceSpans := range traces.ResourceSpans().All() { for _, scopeSpans := range resourceSpans.ScopeSpans().All() { if scopeSpans.Spans().Len() > 0 { return scopeSpans.Spans().At(0) } } } return ptrace.NewSpan() }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/tracing/tracing.go
pkg/observability/tracing/tracing.go
package tracing import ( "context" "fmt" "io" "net" "net/http" "net/url" "slices" "strconv" "strings" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/static" "github.com/traefik/traefik/v3/pkg/observability" otypes "github.com/traefik/traefik/v3/pkg/observability/types" "go.opentelemetry.io/contrib/propagators/autoprop" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/propagation" semconv "go.opentelemetry.io/otel/semconv/v1.37.0" "go.opentelemetry.io/otel/trace" ) // Backend is an abstraction for tracking backend (OpenTelemetry, ...). type Backend interface { Setup(ctx context.Context, serviceName string, sampleRate float64, resourceAttributes map[string]string) (trace.Tracer, io.Closer, error) } // NewTracing Creates a Tracing. func NewTracing(ctx context.Context, conf *static.Tracing) (*Tracer, io.Closer, error) { var backend Backend if conf.OTLP != nil { backend = conf.OTLP } if backend == nil { log.Debug().Msg("Could not initialize tracing, using OpenTelemetry by default") defaultBackend := &otypes.OTelTracing{} backend = defaultBackend } if err := observability.EnsureUserEnvVar(); err != nil { return nil, nil, err } otel.SetTextMapPropagator(autoprop.NewTextMapPropagator()) tr, closer, err := backend.Setup(ctx, conf.ServiceName, conf.SampleRate, conf.ResourceAttributes) if err != nil { return nil, nil, err } return NewTracer(tr, conf.CapturedRequestHeaders, conf.CapturedResponseHeaders, conf.SafeQueryParams), closer, nil } // TracerFromContext extracts the trace.Tracer from the given context. func TracerFromContext(ctx context.Context) *Tracer { // Prevent picking trace.noopSpan tracer. if !trace.SpanContextFromContext(ctx).IsValid() { return nil } span := trace.SpanFromContext(ctx) if span != nil && span.TracerProvider() != nil { tracer := span.TracerProvider().Tracer("github.com/traefik/traefik") if tracer, ok := tracer.(*Tracer); ok { return tracer } return nil } return nil } // ExtractCarrierIntoContext reads cross-cutting concerns from the carrier into a Context. func ExtractCarrierIntoContext(ctx context.Context, headers http.Header) context.Context { propagator := otel.GetTextMapPropagator() return propagator.Extract(ctx, propagation.HeaderCarrier(headers)) } // InjectContextIntoCarrier sets cross-cutting concerns from the request context into the request headers. func InjectContextIntoCarrier(req *http.Request) { propagator := otel.GetTextMapPropagator() propagator.Inject(req.Context(), propagation.HeaderCarrier(req.Header)) } // Span is trace.Span wrapping the Traefik TracerProvider. type Span struct { trace.Span tracerProvider *TracerProvider } // TracerProvider returns the span's TraceProvider. func (s Span) TracerProvider() trace.TracerProvider { return s.tracerProvider } // TracerProvider is trace.TracerProvider wrapping the Traefik Tracer implementation. type TracerProvider struct { trace.TracerProvider tracer *Tracer } // Tracer returns the trace.Tracer for the given options. // It returns specifically the Traefik Tracer when requested. func (t TracerProvider) Tracer(name string, options ...trace.TracerOption) trace.Tracer { if name == "github.com/traefik/traefik" { return t.tracer } return t.TracerProvider.Tracer(name, options...) } // Tracer is trace.Tracer with additional properties. type Tracer struct { trace.Tracer safeQueryParams []string capturedRequestHeaders []string capturedResponseHeaders []string } // NewTracer builds and configures a new Tracer. func NewTracer(tracer trace.Tracer, capturedRequestHeaders, capturedResponseHeaders, safeQueryParams []string) *Tracer { return &Tracer{ Tracer: tracer, safeQueryParams: safeQueryParams, capturedRequestHeaders: canonicalizeHeaders(capturedRequestHeaders), capturedResponseHeaders: canonicalizeHeaders(capturedResponseHeaders), } } // Start starts a new span. // spancheck linter complains about span.End not being called, but this is expected here, // hence its deactivation. // //nolint:spancheck func (t *Tracer) Start(ctx context.Context, spanName string, opts ...trace.SpanStartOption) (context.Context, trace.Span) { if t == nil { return ctx, nil } spanCtx, span := t.Tracer.Start(ctx, spanName, opts...) wrappedSpan := &Span{Span: span, tracerProvider: &TracerProvider{TracerProvider: span.TracerProvider(), tracer: t}} return trace.ContextWithSpan(spanCtx, wrappedSpan), wrappedSpan } // CaptureClientRequest used to add span attributes from the request as a Client. func (t *Tracer) CaptureClientRequest(span trace.Span, r *http.Request) { if t == nil || span == nil || r == nil { return } // Common attributes https://github.com/open-telemetry/semantic-conventions/blob/v1.26.0/docs/http/http-spans.md#common-attributes span.SetAttributes(semconv.HTTPRequestMethodKey.String(r.Method)) span.SetAttributes(semconv.NetworkProtocolVersion(proto(r.Proto))) // Client attributes https://github.com/open-telemetry/semantic-conventions/blob/v1.26.0/docs/http/http-spans.md#http-client sURL := t.safeURL(r.URL) span.SetAttributes(semconv.URLFull(sURL.String())) span.SetAttributes(semconv.URLScheme(sURL.Scheme)) span.SetAttributes(semconv.UserAgentOriginal(r.UserAgent())) host, port, err := net.SplitHostPort(sURL.Host) if err != nil { span.SetAttributes(semconv.NetworkPeerAddress(host)) span.SetAttributes(semconv.ServerAddress(sURL.Host)) switch sURL.Scheme { case "http": span.SetAttributes(semconv.NetworkPeerPort(80)) span.SetAttributes(semconv.ServerPort(80)) case "https": span.SetAttributes(semconv.NetworkPeerPort(443)) span.SetAttributes(semconv.ServerPort(443)) } } else { span.SetAttributes(semconv.NetworkPeerAddress(host)) intPort, _ := strconv.Atoi(port) span.SetAttributes(semconv.NetworkPeerPort(intPort)) span.SetAttributes(semconv.ServerAddress(host)) span.SetAttributes(semconv.ServerPort(intPort)) } for _, header := range t.capturedRequestHeaders { // User-agent is already part of the semantic convention as a recommended attribute. if strings.EqualFold(header, "User-Agent") { continue } if value := r.Header[header]; value != nil { span.SetAttributes(attribute.StringSlice(fmt.Sprintf("http.request.header.%s", strings.ToLower(header)), value)) } } } // CaptureServerRequest used to add span attributes from the request as a Server. func (t *Tracer) CaptureServerRequest(span trace.Span, r *http.Request) { if t == nil || span == nil || r == nil { return } // Common attributes https://github.com/open-telemetry/semantic-conventions/blob/v1.26.0/docs/http/http-spans.md#common-attributes span.SetAttributes(semconv.HTTPRequestMethodKey.String(r.Method)) span.SetAttributes(semconv.NetworkProtocolVersion(proto(r.Proto))) sURL := t.safeURL(r.URL) // Server attributes https://github.com/open-telemetry/semantic-conventions/blob/v1.26.0/docs/http/http-spans.md#http-server-semantic-conventions span.SetAttributes(semconv.HTTPRequestBodySize(int(r.ContentLength))) span.SetAttributes(semconv.URLPath(sURL.Path)) span.SetAttributes(semconv.URLQuery(sURL.RawQuery)) span.SetAttributes(semconv.URLScheme(r.Header.Get("X-Forwarded-Proto"))) span.SetAttributes(semconv.UserAgentOriginal(r.UserAgent())) span.SetAttributes(semconv.ServerAddress(r.Host)) host, port, err := net.SplitHostPort(r.RemoteAddr) if err != nil { span.SetAttributes(semconv.ClientAddress(r.RemoteAddr)) span.SetAttributes(semconv.NetworkPeerAddress(r.Host)) } else { span.SetAttributes(semconv.NetworkPeerAddress(host)) span.SetAttributes(semconv.ClientAddress(host)) intPort, _ := strconv.Atoi(port) span.SetAttributes(semconv.ClientPort(intPort)) span.SetAttributes(semconv.NetworkPeerPort(intPort)) } for _, header := range t.capturedRequestHeaders { // User-agent is already part of the semantic convention as a recommended attribute. if strings.EqualFold(header, "User-Agent") { continue } if value := r.Header[header]; value != nil { span.SetAttributes(attribute.StringSlice(fmt.Sprintf("http.request.header.%s", strings.ToLower(header)), value)) } } } // CaptureResponse captures the response attributes to the span. func (t *Tracer) CaptureResponse(span trace.Span, responseHeaders http.Header, code int, spanKind trace.SpanKind) { if t == nil || span == nil { return } var status codes.Code var desc string switch spanKind { case trace.SpanKindServer: status, desc = serverStatus(code) case trace.SpanKindClient: status, desc = clientStatus(code) default: status, desc = defaultStatus(code) } span.SetStatus(status, desc) if code > 0 { span.SetAttributes(semconv.HTTPResponseStatusCode(code)) } for _, header := range t.capturedResponseHeaders { if value := responseHeaders[header]; value != nil { span.SetAttributes(attribute.StringSlice(fmt.Sprintf("http.response.header.%s", strings.ToLower(header)), value)) } } } func (t *Tracer) safeURL(originalURL *url.URL) *url.URL { if originalURL == nil { return nil } redactedURL := *originalURL // Redact password if exists. if redactedURL.User != nil { redactedURL.User = url.UserPassword("REDACTED", "REDACTED") } // Redact query parameters. query := redactedURL.Query() for k := range query { if slices.Contains(t.safeQueryParams, k) { continue } query.Set(k, "REDACTED") } redactedURL.RawQuery = query.Encode() return &redactedURL } func proto(proto string) string { switch proto { case "HTTP/1.0": return "1.0" case "HTTP/1.1": return "1.1" case "HTTP/2": return "2" case "HTTP/3": return "3" default: return proto } } // serverStatus returns a span status code and message for an HTTP status code // value returned by a server. Status codes in the 400-499 range are not // returned as errors. func serverStatus(code int) (codes.Code, string) { if code < 100 || code >= 600 { return codes.Error, fmt.Sprintf("Invalid HTTP status code %d", code) } if code >= 500 { return codes.Error, "" } return codes.Unset, "" } // clientStatus returns a span status code and message for an HTTP status code // value returned by a server. Status codes in the 400-499 range are not // returned as errors. func clientStatus(code int) (codes.Code, string) { if code < 100 || code >= 600 { return codes.Error, fmt.Sprintf("Invalid HTTP status code %d", code) } if code >= 400 { return codes.Error, "" } return codes.Unset, "" } // defaultStatus returns a span status code and message for an HTTP status code // value generated internally. func defaultStatus(code int) (codes.Code, string) { if code < 100 || code >= 600 { return codes.Error, fmt.Sprintf("Invalid HTTP status code %d", code) } if code >= 500 { return codes.Error, "" } return codes.Unset, "" } // canonicalizeHeaders converts a slice of header keys to their canonical form. // It uses http.CanonicalHeaderKey to ensure that the headers are in a consistent format. func canonicalizeHeaders(headers []string) []string { if headers == nil { return nil } canonicalHeaders := make([]string, len(headers)) for i, header := range headers { canonicalHeaders[i] = http.CanonicalHeaderKey(header) } return canonicalHeaders }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/metrics/metrics.go
pkg/observability/metrics/metrics.go
package metrics import ( "errors" "time" "github.com/go-kit/kit/metrics" "github.com/go-kit/kit/metrics/multi" ) const defaultMetricsPrefix = "traefik" // Registry has to implemented by any system that wants to monitor and expose metrics. type Registry interface { // IsEpEnabled shows whether metrics instrumentation is enabled on entry points. IsEpEnabled() bool // IsRouterEnabled shows whether metrics instrumentation is enabled on routers. IsRouterEnabled() bool // IsSvcEnabled shows whether metrics instrumentation is enabled on services. IsSvcEnabled() bool // server metrics ConfigReloadsCounter() metrics.Counter LastConfigReloadSuccessGauge() metrics.Gauge OpenConnectionsGauge() metrics.Gauge // TLS TLSCertsNotAfterTimestampGauge() metrics.Gauge // entry point metrics EntryPointReqsCounter() CounterWithHeaders EntryPointReqsTLSCounter() metrics.Counter EntryPointReqDurationHistogram() ScalableHistogram EntryPointReqsBytesCounter() metrics.Counter EntryPointRespsBytesCounter() metrics.Counter // router metrics RouterReqsCounter() CounterWithHeaders RouterReqsTLSCounter() metrics.Counter RouterReqDurationHistogram() ScalableHistogram RouterReqsBytesCounter() metrics.Counter RouterRespsBytesCounter() metrics.Counter // service metrics ServiceReqsCounter() CounterWithHeaders ServiceReqsTLSCounter() metrics.Counter ServiceReqDurationHistogram() ScalableHistogram ServiceRetriesCounter() metrics.Counter ServiceServerUpGauge() metrics.Gauge ServiceReqsBytesCounter() metrics.Counter ServiceRespsBytesCounter() metrics.Counter } // NewVoidRegistry is a noop implementation of metrics.Registry. // It is used to avoid nil checking in components that do metric collections. func NewVoidRegistry() Registry { return NewMultiRegistry([]Registry{}) } // NewMultiRegistry is an implementation of metrics.Registry that wraps multiple registries. // It handles the case when a registry hasn't registered some metric and returns nil. // This allows for feature disparity between the different metric implementations. func NewMultiRegistry(registries []Registry) Registry { var configReloadsCounter []metrics.Counter var lastConfigReloadSuccessGauge []metrics.Gauge var openConnectionsGauge []metrics.Gauge var tlsCertsNotAfterTimestampGauge []metrics.Gauge var entryPointReqsCounter []CounterWithHeaders var entryPointReqsTLSCounter []metrics.Counter var entryPointReqDurationHistogram []ScalableHistogram var entryPointReqsBytesCounter []metrics.Counter var entryPointRespsBytesCounter []metrics.Counter var routerReqsCounter []CounterWithHeaders var routerReqsTLSCounter []metrics.Counter var routerReqDurationHistogram []ScalableHistogram var routerReqsBytesCounter []metrics.Counter var routerRespsBytesCounter []metrics.Counter var serviceReqsCounter []CounterWithHeaders var serviceReqsTLSCounter []metrics.Counter var serviceReqDurationHistogram []ScalableHistogram var serviceRetriesCounter []metrics.Counter var serviceServerUpGauge []metrics.Gauge var serviceReqsBytesCounter []metrics.Counter var serviceRespsBytesCounter []metrics.Counter for _, r := range registries { if r.ConfigReloadsCounter() != nil { configReloadsCounter = append(configReloadsCounter, r.ConfigReloadsCounter()) } if r.LastConfigReloadSuccessGauge() != nil { lastConfigReloadSuccessGauge = append(lastConfigReloadSuccessGauge, r.LastConfigReloadSuccessGauge()) } if r.OpenConnectionsGauge() != nil { openConnectionsGauge = append(openConnectionsGauge, r.OpenConnectionsGauge()) } if r.TLSCertsNotAfterTimestampGauge() != nil { tlsCertsNotAfterTimestampGauge = append(tlsCertsNotAfterTimestampGauge, r.TLSCertsNotAfterTimestampGauge()) } if r.EntryPointReqsCounter() != nil { entryPointReqsCounter = append(entryPointReqsCounter, r.EntryPointReqsCounter()) } if r.EntryPointReqsTLSCounter() != nil { entryPointReqsTLSCounter = append(entryPointReqsTLSCounter, r.EntryPointReqsTLSCounter()) } if r.EntryPointReqDurationHistogram() != nil { entryPointReqDurationHistogram = append(entryPointReqDurationHistogram, r.EntryPointReqDurationHistogram()) } if r.EntryPointReqsBytesCounter() != nil { entryPointReqsBytesCounter = append(entryPointReqsBytesCounter, r.EntryPointReqsBytesCounter()) } if r.EntryPointRespsBytesCounter() != nil { entryPointRespsBytesCounter = append(entryPointRespsBytesCounter, r.EntryPointRespsBytesCounter()) } if r.RouterReqsCounter() != nil { routerReqsCounter = append(routerReqsCounter, r.RouterReqsCounter()) } if r.RouterReqsTLSCounter() != nil { routerReqsTLSCounter = append(routerReqsTLSCounter, r.RouterReqsTLSCounter()) } if r.RouterReqDurationHistogram() != nil { routerReqDurationHistogram = append(routerReqDurationHistogram, r.RouterReqDurationHistogram()) } if r.RouterReqsBytesCounter() != nil { routerReqsBytesCounter = append(routerReqsBytesCounter, r.RouterReqsBytesCounter()) } if r.RouterRespsBytesCounter() != nil { routerRespsBytesCounter = append(routerRespsBytesCounter, r.RouterRespsBytesCounter()) } if r.ServiceReqsCounter() != nil { serviceReqsCounter = append(serviceReqsCounter, r.ServiceReqsCounter()) } if r.ServiceReqsTLSCounter() != nil { serviceReqsTLSCounter = append(serviceReqsTLSCounter, r.ServiceReqsTLSCounter()) } if r.ServiceReqDurationHistogram() != nil { serviceReqDurationHistogram = append(serviceReqDurationHistogram, r.ServiceReqDurationHistogram()) } if r.ServiceRetriesCounter() != nil { serviceRetriesCounter = append(serviceRetriesCounter, r.ServiceRetriesCounter()) } if r.ServiceServerUpGauge() != nil { serviceServerUpGauge = append(serviceServerUpGauge, r.ServiceServerUpGauge()) } if r.ServiceReqsBytesCounter() != nil { serviceReqsBytesCounter = append(serviceReqsBytesCounter, r.ServiceReqsBytesCounter()) } if r.ServiceRespsBytesCounter() != nil { serviceRespsBytesCounter = append(serviceRespsBytesCounter, r.ServiceRespsBytesCounter()) } } return &standardRegistry{ epEnabled: len(entryPointReqsCounter) > 0 || len(entryPointReqDurationHistogram) > 0, svcEnabled: len(serviceReqsCounter) > 0 || len(serviceReqDurationHistogram) > 0 || len(serviceRetriesCounter) > 0 || len(serviceServerUpGauge) > 0, routerEnabled: len(routerReqsCounter) > 0 || len(routerReqDurationHistogram) > 0, configReloadsCounter: multi.NewCounter(configReloadsCounter...), lastConfigReloadSuccessGauge: multi.NewGauge(lastConfigReloadSuccessGauge...), openConnectionsGauge: multi.NewGauge(openConnectionsGauge...), tlsCertsNotAfterTimestampGauge: multi.NewGauge(tlsCertsNotAfterTimestampGauge...), entryPointReqsCounter: NewMultiCounterWithHeaders(entryPointReqsCounter...), entryPointReqsTLSCounter: multi.NewCounter(entryPointReqsTLSCounter...), entryPointReqDurationHistogram: MultiHistogram(entryPointReqDurationHistogram), entryPointReqsBytesCounter: multi.NewCounter(entryPointReqsBytesCounter...), entryPointRespsBytesCounter: multi.NewCounter(entryPointRespsBytesCounter...), routerReqsCounter: NewMultiCounterWithHeaders(routerReqsCounter...), routerReqsTLSCounter: multi.NewCounter(routerReqsTLSCounter...), routerReqDurationHistogram: MultiHistogram(routerReqDurationHistogram), routerReqsBytesCounter: multi.NewCounter(routerReqsBytesCounter...), routerRespsBytesCounter: multi.NewCounter(routerRespsBytesCounter...), serviceReqsCounter: NewMultiCounterWithHeaders(serviceReqsCounter...), serviceReqsTLSCounter: multi.NewCounter(serviceReqsTLSCounter...), serviceReqDurationHistogram: MultiHistogram(serviceReqDurationHistogram), serviceRetriesCounter: multi.NewCounter(serviceRetriesCounter...), serviceServerUpGauge: multi.NewGauge(serviceServerUpGauge...), serviceReqsBytesCounter: multi.NewCounter(serviceReqsBytesCounter...), serviceRespsBytesCounter: multi.NewCounter(serviceRespsBytesCounter...), } } type standardRegistry struct { epEnabled bool routerEnabled bool svcEnabled bool configReloadsCounter metrics.Counter lastConfigReloadSuccessGauge metrics.Gauge openConnectionsGauge metrics.Gauge tlsCertsNotAfterTimestampGauge metrics.Gauge entryPointReqsCounter CounterWithHeaders entryPointReqsTLSCounter metrics.Counter entryPointReqDurationHistogram ScalableHistogram entryPointReqsBytesCounter metrics.Counter entryPointRespsBytesCounter metrics.Counter routerReqsCounter CounterWithHeaders routerReqsTLSCounter metrics.Counter routerReqDurationHistogram ScalableHistogram routerReqsBytesCounter metrics.Counter routerRespsBytesCounter metrics.Counter serviceReqsCounter CounterWithHeaders serviceReqsTLSCounter metrics.Counter serviceReqDurationHistogram ScalableHistogram serviceRetriesCounter metrics.Counter serviceServerUpGauge metrics.Gauge serviceReqsBytesCounter metrics.Counter serviceRespsBytesCounter metrics.Counter } func (r *standardRegistry) IsEpEnabled() bool { return r.epEnabled } func (r *standardRegistry) IsRouterEnabled() bool { return r.routerEnabled } func (r *standardRegistry) IsSvcEnabled() bool { return r.svcEnabled } func (r *standardRegistry) ConfigReloadsCounter() metrics.Counter { return r.configReloadsCounter } func (r *standardRegistry) LastConfigReloadSuccessGauge() metrics.Gauge { return r.lastConfigReloadSuccessGauge } func (r *standardRegistry) OpenConnectionsGauge() metrics.Gauge { return r.openConnectionsGauge } func (r *standardRegistry) TLSCertsNotAfterTimestampGauge() metrics.Gauge { return r.tlsCertsNotAfterTimestampGauge } func (r *standardRegistry) EntryPointReqsCounter() CounterWithHeaders { return r.entryPointReqsCounter } func (r *standardRegistry) EntryPointReqsTLSCounter() metrics.Counter { return r.entryPointReqsTLSCounter } func (r *standardRegistry) EntryPointReqDurationHistogram() ScalableHistogram { return r.entryPointReqDurationHistogram } func (r *standardRegistry) EntryPointReqsBytesCounter() metrics.Counter { return r.entryPointReqsBytesCounter } func (r *standardRegistry) EntryPointRespsBytesCounter() metrics.Counter { return r.entryPointRespsBytesCounter } func (r *standardRegistry) RouterReqsCounter() CounterWithHeaders { return r.routerReqsCounter } func (r *standardRegistry) RouterReqsTLSCounter() metrics.Counter { return r.routerReqsTLSCounter } func (r *standardRegistry) RouterReqDurationHistogram() ScalableHistogram { return r.routerReqDurationHistogram } func (r *standardRegistry) RouterReqsBytesCounter() metrics.Counter { return r.routerReqsBytesCounter } func (r *standardRegistry) RouterRespsBytesCounter() metrics.Counter { return r.routerRespsBytesCounter } func (r *standardRegistry) ServiceReqsCounter() CounterWithHeaders { return r.serviceReqsCounter } func (r *standardRegistry) ServiceReqsTLSCounter() metrics.Counter { return r.serviceReqsTLSCounter } func (r *standardRegistry) ServiceReqDurationHistogram() ScalableHistogram { return r.serviceReqDurationHistogram } func (r *standardRegistry) ServiceRetriesCounter() metrics.Counter { return r.serviceRetriesCounter } func (r *standardRegistry) ServiceServerUpGauge() metrics.Gauge { return r.serviceServerUpGauge } func (r *standardRegistry) ServiceReqsBytesCounter() metrics.Counter { return r.serviceReqsBytesCounter } func (r *standardRegistry) ServiceRespsBytesCounter() metrics.Counter { return r.serviceRespsBytesCounter } // ScalableHistogram is a Histogram with a predefined time unit, // used when producing observations without explicitly setting the observed value. type ScalableHistogram interface { With(labelValues ...string) ScalableHistogram Observe(v float64) ObserveFromStart(start time.Time) } // HistogramWithScale is a histogram that will convert its observed value to the specified unit. type HistogramWithScale struct { histogram metrics.Histogram unit time.Duration } // With implements ScalableHistogram. func (s *HistogramWithScale) With(labelValues ...string) ScalableHistogram { h, _ := NewHistogramWithScale(s.histogram.With(labelValues...), s.unit) return h } // ObserveFromStart implements ScalableHistogram. func (s *HistogramWithScale) ObserveFromStart(start time.Time) { if s.unit <= 0 { return } d := float64(time.Since(start).Nanoseconds()) / float64(s.unit) if d < 0 { d = 0 } s.histogram.Observe(d) } // Observe implements ScalableHistogram. func (s *HistogramWithScale) Observe(v float64) { s.histogram.Observe(v) } // NewHistogramWithScale returns a ScalableHistogram. It returns an error if the given unit is <= 0. func NewHistogramWithScale(histogram metrics.Histogram, unit time.Duration) (ScalableHistogram, error) { if unit <= 0 { return nil, errors.New("invalid time unit") } return &HistogramWithScale{ histogram: histogram, unit: unit, }, nil } // MultiHistogram collects multiple individual histograms and treats them as a unit. type MultiHistogram []ScalableHistogram // ObserveFromStart implements ScalableHistogram. func (h MultiHistogram) ObserveFromStart(start time.Time) { for _, histogram := range h { histogram.ObserveFromStart(start) } } // Observe implements ScalableHistogram. func (h MultiHistogram) Observe(v float64) { for _, histogram := range h { histogram.Observe(v) } } // With implements ScalableHistogram. func (h MultiHistogram) With(labelValues ...string) ScalableHistogram { next := make(MultiHistogram, len(h)) for i := range h { next[i] = h[i].With(labelValues...) } return next }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/metrics/statsd.go
pkg/observability/metrics/statsd.go
package metrics import ( "context" "time" "github.com/go-kit/kit/metrics/statsd" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/observability/logs" otypes "github.com/traefik/traefik/v3/pkg/observability/types" "github.com/traefik/traefik/v3/pkg/safe" ) var ( statsdClient *statsd.Statsd statsdTicker *time.Ticker ) const ( statsdConfigReloadsName = "config.reload.total" statsdLastConfigReloadSuccessName = "config.reload.lastSuccessTimestamp" statsdOpenConnectionsName = "open.connections" statsdTLSCertsNotAfterTimestampName = "tls.certs.notAfterTimestamp" statsdEntryPointReqsName = "entrypoint.request.total" statsdEntryPointReqsTLSName = "entrypoint.request.tls.total" statsdEntryPointReqDurationName = "entrypoint.request.duration" statsdEntryPointReqsBytesName = "entrypoint.requests.bytes.total" statsdEntryPointRespsBytesName = "entrypoint.responses.bytes.total" statsdRouterReqsName = "router.request.total" statsdRouterReqsTLSName = "router.request.tls.total" statsdRouterReqsDurationName = "router.request.duration" statsdRouterReqsBytesName = "router.requests.bytes.total" statsdRouterRespsBytesName = "router.responses.bytes.total" statsdServiceReqsName = "service.request.total" statsdServiceReqsTLSName = "service.request.tls.total" statsdServiceReqsDurationName = "service.request.duration" statsdServiceRetriesTotalName = "service.retries.total" statsdServiceServerUpName = "service.server.up" statsdServiceReqsBytesName = "service.requests.bytes.total" statsdServiceRespsBytesName = "service.responses.bytes.total" ) // RegisterStatsd registers the metrics pusher if this didn't happen yet and creates a statsd Registry instance. func RegisterStatsd(ctx context.Context, config *otypes.Statsd) Registry { // just to be sure there is a prefix defined if config.Prefix == "" { config.Prefix = defaultMetricsPrefix } statsdClient = statsd.New(config.Prefix+".", logs.NewGoKitWrapper(*log.Ctx(ctx))) if statsdTicker == nil { statsdTicker = initStatsdTicker(ctx, config) } registry := &standardRegistry{ configReloadsCounter: statsdClient.NewCounter(statsdConfigReloadsName, 1.0), lastConfigReloadSuccessGauge: statsdClient.NewGauge(statsdLastConfigReloadSuccessName), tlsCertsNotAfterTimestampGauge: statsdClient.NewGauge(statsdTLSCertsNotAfterTimestampName), openConnectionsGauge: statsdClient.NewGauge(statsdOpenConnectionsName), } if config.AddEntryPointsLabels { registry.epEnabled = config.AddEntryPointsLabels registry.entryPointReqsCounter = NewCounterWithNoopHeaders(statsdClient.NewCounter(statsdEntryPointReqsName, 1.0)) registry.entryPointReqsTLSCounter = statsdClient.NewCounter(statsdEntryPointReqsTLSName, 1.0) registry.entryPointReqDurationHistogram, _ = NewHistogramWithScale(statsdClient.NewTiming(statsdEntryPointReqDurationName, 1.0), time.Millisecond) registry.entryPointReqsBytesCounter = statsdClient.NewCounter(statsdEntryPointReqsBytesName, 1.0) registry.entryPointRespsBytesCounter = statsdClient.NewCounter(statsdEntryPointRespsBytesName, 1.0) } if config.AddRoutersLabels { registry.routerEnabled = config.AddRoutersLabels registry.routerReqsCounter = NewCounterWithNoopHeaders(statsdClient.NewCounter(statsdRouterReqsName, 1.0)) registry.routerReqsTLSCounter = statsdClient.NewCounter(statsdRouterReqsTLSName, 1.0) registry.routerReqDurationHistogram, _ = NewHistogramWithScale(statsdClient.NewTiming(statsdRouterReqsDurationName, 1.0), time.Millisecond) registry.routerReqsBytesCounter = statsdClient.NewCounter(statsdRouterReqsBytesName, 1.0) registry.routerRespsBytesCounter = statsdClient.NewCounter(statsdRouterRespsBytesName, 1.0) } if config.AddServicesLabels { registry.svcEnabled = config.AddServicesLabels registry.serviceReqsCounter = NewCounterWithNoopHeaders(statsdClient.NewCounter(statsdServiceReqsName, 1.0)) registry.serviceReqsTLSCounter = statsdClient.NewCounter(statsdServiceReqsTLSName, 1.0) registry.serviceReqDurationHistogram, _ = NewHistogramWithScale(statsdClient.NewTiming(statsdServiceReqsDurationName, 1.0), time.Millisecond) registry.serviceRetriesCounter = statsdClient.NewCounter(statsdServiceRetriesTotalName, 1.0) registry.serviceServerUpGauge = statsdClient.NewGauge(statsdServiceServerUpName) registry.serviceReqsBytesCounter = statsdClient.NewCounter(statsdServiceReqsBytesName, 1.0) registry.serviceRespsBytesCounter = statsdClient.NewCounter(statsdServiceRespsBytesName, 1.0) } return registry } // initStatsdTicker initializes metrics pusher and creates a statsdClient if not created already. func initStatsdTicker(ctx context.Context, config *otypes.Statsd) *time.Ticker { address := config.Address if len(address) == 0 { address = "localhost:8125" } report := time.NewTicker(time.Duration(config.PushInterval)) safe.Go(func() { statsdClient.SendLoop(ctx, report.C, "udp", address) }) return report } // StopStatsd stops internal statsdTicker which controls the pushing of metrics to StatsD Agent and resets it to `nil`. func StopStatsd() { if statsdTicker != nil { statsdTicker.Stop() } statsdTicker = nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/metrics/prometheus.go
pkg/observability/metrics/prometheus.go
package metrics import ( "context" "errors" "net/http" "sync" "time" "github.com/go-kit/kit/metrics" stdprometheus "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/collectors" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" otypes "github.com/traefik/traefik/v3/pkg/observability/types" ) const ( // MetricNamePrefix prefix of all metric names. MetricNamePrefix = "traefik_" // server meta information. metricConfigPrefix = MetricNamePrefix + "config_" configReloadsTotalName = metricConfigPrefix + "reloads_total" configLastReloadSuccessName = metricConfigPrefix + "last_reload_success" openConnectionsName = MetricNamePrefix + "open_connections" // TLS. metricsTLSPrefix = MetricNamePrefix + "tls_" tlsCertsNotAfterTimestampName = metricsTLSPrefix + "certs_not_after" // entry point. metricEntryPointPrefix = MetricNamePrefix + "entrypoint_" entryPointReqsTotalName = metricEntryPointPrefix + "requests_total" entryPointReqsTLSTotalName = metricEntryPointPrefix + "requests_tls_total" entryPointReqDurationName = metricEntryPointPrefix + "request_duration_seconds" entryPointReqsBytesTotalName = metricEntryPointPrefix + "requests_bytes_total" entryPointRespsBytesTotalName = metricEntryPointPrefix + "responses_bytes_total" // router level. metricRouterPrefix = MetricNamePrefix + "router_" routerReqsTotalName = metricRouterPrefix + "requests_total" routerReqsTLSTotalName = metricRouterPrefix + "requests_tls_total" routerReqDurationName = metricRouterPrefix + "request_duration_seconds" routerReqsBytesTotalName = metricRouterPrefix + "requests_bytes_total" routerRespsBytesTotalName = metricRouterPrefix + "responses_bytes_total" // service level. metricServicePrefix = MetricNamePrefix + "service_" serviceReqsTotalName = metricServicePrefix + "requests_total" serviceReqsTLSTotalName = metricServicePrefix + "requests_tls_total" serviceReqDurationName = metricServicePrefix + "request_duration_seconds" serviceRetriesTotalName = metricServicePrefix + "retries_total" serviceServerUpName = metricServicePrefix + "server_up" serviceReqsBytesTotalName = metricServicePrefix + "requests_bytes_total" serviceRespsBytesTotalName = metricServicePrefix + "responses_bytes_total" ) // promState holds all metric state internally and acts as the only Collector we register for Prometheus. // // This enables control to remove metrics that belong to outdated configuration. // As an example why this is required, consider Traefik learns about a new service. // It populates the 'traefik_server_service_up' metric for it with a value of 1 (alive). // When the service is undeployed now the metric is still there in the client library // and will be returned on the metrics endpoint until Traefik would be restarted. // // To solve this problem promState keeps track of Traefik's dynamic configuration. // Metrics that "belong" to a dynamic configuration part like services or entryPoints // are removed after they were scraped at least once when the corresponding object // doesn't exist anymore. var promState = newPrometheusState() var promRegistry = stdprometheus.NewRegistry() // PrometheusHandler exposes Prometheus routes. func PrometheusHandler() http.Handler { return promhttp.HandlerFor(promRegistry, promhttp.HandlerOpts{}) } // RegisterPrometheus registers all Prometheus metrics. // It must be called only once and failing to register the metrics will lead to a panic. func RegisterPrometheus(ctx context.Context, config *otypes.Prometheus) Registry { standardRegistry := initStandardRegistry(config) if err := promRegistry.Register(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{})); err != nil { var arErr stdprometheus.AlreadyRegisteredError if !errors.As(err, &arErr) { log.Ctx(ctx).Warn().Msg("ProcessCollector is already registered") } } if err := promRegistry.Register(collectors.NewGoCollector()); err != nil { var arErr stdprometheus.AlreadyRegisteredError if !errors.As(err, &arErr) { log.Ctx(ctx).Warn().Msg("GoCollector is already registered") } } if !registerPromState(ctx) { return nil } return standardRegistry } func initStandardRegistry(config *otypes.Prometheus) Registry { buckets := []float64{0.1, 0.3, 1.2, 5.0} if config.Buckets != nil { buckets = config.Buckets } configReloads := newCounterFrom(stdprometheus.CounterOpts{ Name: configReloadsTotalName, Help: "Config reloads", }, []string{}) lastConfigReloadSuccess := newGaugeFrom(stdprometheus.GaugeOpts{ Name: configLastReloadSuccessName, Help: "Last config reload success", }, []string{}) tlsCertsNotAfterTimestamp := newGaugeFrom(stdprometheus.GaugeOpts{ Name: tlsCertsNotAfterTimestampName, Help: "Certificate expiration timestamp", }, []string{"cn", "serial", "sans"}) openConnections := newGaugeFrom(stdprometheus.GaugeOpts{ Name: openConnectionsName, Help: "How many open connections exist, by entryPoint and protocol", }, []string{"entrypoint", "protocol"}) promState.vectors = []vector{ configReloads.cv, lastConfigReloadSuccess.gv, tlsCertsNotAfterTimestamp.gv, openConnections.gv, } reg := &standardRegistry{ epEnabled: config.AddEntryPointsLabels, routerEnabled: config.AddRoutersLabels, svcEnabled: config.AddServicesLabels, configReloadsCounter: configReloads, lastConfigReloadSuccessGauge: lastConfigReloadSuccess, tlsCertsNotAfterTimestampGauge: tlsCertsNotAfterTimestamp, openConnectionsGauge: openConnections, } if config.AddEntryPointsLabels { entryPointReqs := newCounterWithHeadersFrom(stdprometheus.CounterOpts{ Name: entryPointReqsTotalName, Help: "How many HTTP requests processed on an entrypoint, partitioned by status code, protocol, and method.", }, config.HeaderLabels, []string{"code", "method", "protocol", "entrypoint"}) entryPointReqsTLS := newCounterFrom(stdprometheus.CounterOpts{ Name: entryPointReqsTLSTotalName, Help: "How many HTTP requests with TLS processed on an entrypoint, partitioned by TLS Version and TLS cipher Used.", }, []string{"tls_version", "tls_cipher", "entrypoint"}) entryPointReqDurations := newHistogramFrom(stdprometheus.HistogramOpts{ Name: entryPointReqDurationName, Help: "How long it took to process the request on an entrypoint, partitioned by status code, protocol, and method.", Buckets: buckets, }, []string{"code", "method", "protocol", "entrypoint"}) entryPointReqsBytesTotal := newCounterFrom(stdprometheus.CounterOpts{ Name: entryPointReqsBytesTotalName, Help: "The total size of requests in bytes handled by an entrypoint, partitioned by status code, protocol, and method.", }, []string{"code", "method", "protocol", "entrypoint"}) entryPointRespsBytesTotal := newCounterFrom(stdprometheus.CounterOpts{ Name: entryPointRespsBytesTotalName, Help: "The total size of responses in bytes handled by an entrypoint, partitioned by status code, protocol, and method.", }, []string{"code", "method", "protocol", "entrypoint"}) promState.vectors = append(promState.vectors, entryPointReqs.cv, entryPointReqsTLS.cv, entryPointReqDurations.hv, entryPointReqsBytesTotal.cv, entryPointRespsBytesTotal.cv, ) reg.entryPointReqsCounter = entryPointReqs reg.entryPointReqsTLSCounter = entryPointReqsTLS reg.entryPointReqDurationHistogram, _ = NewHistogramWithScale(entryPointReqDurations, time.Second) reg.entryPointReqsBytesCounter = entryPointReqsBytesTotal reg.entryPointRespsBytesCounter = entryPointRespsBytesTotal } if config.AddRoutersLabels { routerReqs := newCounterWithHeadersFrom(stdprometheus.CounterOpts{ Name: routerReqsTotalName, Help: "How many HTTP requests are processed on a router, partitioned by service, status code, protocol, and method.", }, config.HeaderLabels, []string{"code", "method", "protocol", "router", "service"}) routerReqsTLS := newCounterFrom(stdprometheus.CounterOpts{ Name: routerReqsTLSTotalName, Help: "How many HTTP requests with TLS are processed on a router, partitioned by service, TLS Version, and TLS cipher Used.", }, []string{"tls_version", "tls_cipher", "router", "service"}) routerReqDurations := newHistogramFrom(stdprometheus.HistogramOpts{ Name: routerReqDurationName, Help: "How long it took to process the request on a router, partitioned by service, status code, protocol, and method.", Buckets: buckets, }, []string{"code", "method", "protocol", "router", "service"}) routerReqsBytesTotal := newCounterFrom(stdprometheus.CounterOpts{ Name: routerReqsBytesTotalName, Help: "The total size of requests in bytes handled by a router, partitioned by service, status code, protocol, and method.", }, []string{"code", "method", "protocol", "router", "service"}) routerRespsBytesTotal := newCounterFrom(stdprometheus.CounterOpts{ Name: routerRespsBytesTotalName, Help: "The total size of responses in bytes handled by a router, partitioned by service, status code, protocol, and method.", }, []string{"code", "method", "protocol", "router", "service"}) promState.vectors = append(promState.vectors, routerReqs.cv, routerReqsTLS.cv, routerReqDurations.hv, routerReqsBytesTotal.cv, routerRespsBytesTotal.cv, ) reg.routerReqsCounter = routerReqs reg.routerReqsTLSCounter = routerReqsTLS reg.routerReqDurationHistogram, _ = NewHistogramWithScale(routerReqDurations, time.Second) reg.routerReqsBytesCounter = routerReqsBytesTotal reg.routerRespsBytesCounter = routerRespsBytesTotal } if config.AddServicesLabels { serviceReqs := newCounterWithHeadersFrom(stdprometheus.CounterOpts{ Name: serviceReqsTotalName, Help: "How many HTTP requests processed on a service, partitioned by status code, protocol, and method.", }, config.HeaderLabels, []string{"code", "method", "protocol", "service"}) serviceReqsTLS := newCounterFrom(stdprometheus.CounterOpts{ Name: serviceReqsTLSTotalName, Help: "How many HTTP requests with TLS processed on a service, partitioned by TLS version and TLS cipher.", }, []string{"tls_version", "tls_cipher", "service"}) serviceReqDurations := newHistogramFrom(stdprometheus.HistogramOpts{ Name: serviceReqDurationName, Help: "How long it took to process the request on a service, partitioned by status code, protocol, and method.", Buckets: buckets, }, []string{"code", "method", "protocol", "service"}) serviceRetries := newCounterFrom(stdprometheus.CounterOpts{ Name: serviceRetriesTotalName, Help: "How many request retries happened on a service.", }, []string{"service"}) serviceServerUp := newGaugeFrom(stdprometheus.GaugeOpts{ Name: serviceServerUpName, Help: "service server is up, described by gauge value of 0 or 1.", }, []string{"service", "url"}) serviceReqsBytesTotal := newCounterFrom(stdprometheus.CounterOpts{ Name: serviceReqsBytesTotalName, Help: "The total size of requests in bytes received by a service, partitioned by status code, protocol, and method.", }, []string{"code", "method", "protocol", "service"}) serviceRespsBytesTotal := newCounterFrom(stdprometheus.CounterOpts{ Name: serviceRespsBytesTotalName, Help: "The total size of responses in bytes returned by a service, partitioned by status code, protocol, and method.", }, []string{"code", "method", "protocol", "service"}) promState.vectors = append(promState.vectors, serviceReqs.cv, serviceReqsTLS.cv, serviceReqDurations.hv, serviceRetries.cv, serviceServerUp.gv, serviceReqsBytesTotal.cv, serviceRespsBytesTotal.cv, ) reg.serviceReqsCounter = serviceReqs reg.serviceReqsTLSCounter = serviceReqsTLS reg.serviceReqDurationHistogram, _ = NewHistogramWithScale(serviceReqDurations, time.Second) reg.serviceRetriesCounter = serviceRetries reg.serviceServerUpGauge = serviceServerUp reg.serviceReqsBytesCounter = serviceReqsBytesTotal reg.serviceRespsBytesCounter = serviceRespsBytesTotal } return reg } func registerPromState(ctx context.Context) bool { err := promRegistry.Register(promState) if err == nil { return true } logger := log.Ctx(ctx) var arErr stdprometheus.AlreadyRegisteredError if errors.As(err, &arErr) { logger.Debug().Msg("Prometheus collector already registered.") return true } logger.Error().Err(err).Msg("Unable to register Traefik to Prometheus") return false } // OnConfigurationUpdate receives the current configuration from Traefik. // It then converts the configuration to the optimized package internal format // and sets it to the promState. func OnConfigurationUpdate(conf dynamic.Configuration, entryPoints []string) { dynCfg := newDynamicConfig() for _, value := range entryPoints { dynCfg.entryPoints[value] = true } if conf.HTTP == nil { promState.SetDynamicConfig(dynCfg) return } for name := range conf.HTTP.Routers { dynCfg.routers[name] = true } for serviceName, service := range conf.HTTP.Services { dynCfg.services[serviceName] = make(map[string]bool) if service.LoadBalancer != nil { for _, server := range service.LoadBalancer.Servers { dynCfg.services[serviceName][server.URL] = true } } } promState.SetDynamicConfig(dynCfg) } func newPrometheusState() *prometheusState { return &prometheusState{ dynamicConfig: newDynamicConfig(), deletedURLs: make(map[string][]string), } } type vector interface { stdprometheus.Collector DeletePartialMatch(labels stdprometheus.Labels) int } type prometheusState struct { vectors []vector mtx sync.Mutex dynamicConfig *dynamicConfig deletedEP []string deletedRouters []string deletedServices []string deletedURLs map[string][]string } func (ps *prometheusState) SetDynamicConfig(dynamicConfig *dynamicConfig) { ps.mtx.Lock() defer ps.mtx.Unlock() for ep := range ps.dynamicConfig.entryPoints { if _, ok := dynamicConfig.entryPoints[ep]; !ok { ps.deletedEP = append(ps.deletedEP, ep) } } for router := range ps.dynamicConfig.routers { if _, ok := dynamicConfig.routers[router]; !ok { ps.deletedRouters = append(ps.deletedRouters, router) } } for service, serV := range ps.dynamicConfig.services { actualService, ok := dynamicConfig.services[service] if !ok { ps.deletedServices = append(ps.deletedServices, service) } for url := range serV { if _, ok := actualService[url]; !ok { ps.deletedURLs[service] = append(ps.deletedURLs[service], url) } } } ps.dynamicConfig = dynamicConfig } // Describe implements prometheus.Collector and simply calls // the registered describer functions. func (ps *prometheusState) Describe(ch chan<- *stdprometheus.Desc) { for _, v := range ps.vectors { v.Describe(ch) } } // Collect implements prometheus.Collector. It calls the Collect // method of all metrics it received on the collectors channel. // It's also responsible to remove metrics that belong to an outdated configuration. // The removal happens only after their Collect method was called to ensure that // also those metrics will be exported on the current scrape. func (ps *prometheusState) Collect(ch chan<- stdprometheus.Metric) { for _, v := range ps.vectors { v.Collect(ch) } ps.mtx.Lock() defer ps.mtx.Unlock() for _, ep := range ps.deletedEP { if !ps.dynamicConfig.hasEntryPoint(ep) { ps.DeletePartialMatch(map[string]string{"entrypoint": ep}) } } for _, router := range ps.deletedRouters { if !ps.dynamicConfig.hasRouter(router) { ps.DeletePartialMatch(map[string]string{"router": router}) } } for _, service := range ps.deletedServices { if !ps.dynamicConfig.hasService(service) { ps.DeletePartialMatch(map[string]string{"service": service}) } } for service, urls := range ps.deletedURLs { for _, url := range urls { if !ps.dynamicConfig.hasServerURL(service, url) { ps.DeletePartialMatch(map[string]string{"service": service, "url": url}) } } } ps.deletedEP = nil ps.deletedRouters = nil ps.deletedServices = nil ps.deletedURLs = make(map[string][]string) } // DeletePartialMatch deletes all metrics where the variable labels contain all of those passed in as labels. // The order of the labels does not matter. // It returns the number of metrics deleted. func (ps *prometheusState) DeletePartialMatch(labels stdprometheus.Labels) int { var count int for _, elem := range ps.vectors { count += elem.DeletePartialMatch(labels) } return count } func newDynamicConfig() *dynamicConfig { return &dynamicConfig{ entryPoints: make(map[string]bool), routers: make(map[string]bool), services: make(map[string]map[string]bool), } } // dynamicConfig holds the current configuration for entryPoints, services, // and server URLs in an optimized way to check for existence. This provides // a performant way to check whether the collected metrics belong to the // current configuration or to an outdated one. type dynamicConfig struct { entryPoints map[string]bool routers map[string]bool services map[string]map[string]bool } func (d *dynamicConfig) hasEntryPoint(entrypointName string) bool { _, ok := d.entryPoints[entrypointName] return ok } func (d *dynamicConfig) hasService(serviceName string) bool { _, ok := d.services[serviceName] return ok } func (d *dynamicConfig) hasRouter(routerName string) bool { _, ok := d.routers[routerName] return ok } func (d *dynamicConfig) hasServerURL(serviceName, serverURL string) bool { if service, hasService := d.services[serviceName]; hasService { _, ok := service[serverURL] return ok } return false } func newCounterWithHeadersFrom(opts stdprometheus.CounterOpts, headers map[string]string, labelNames []string) *counterWithHeaders { var headerLabels []string for k := range headers { headerLabels = append(headerLabels, k) } cv := stdprometheus.NewCounterVec(opts, append(labelNames, headerLabels...)) c := &counterWithHeaders{ name: opts.Name, headers: headers, cv: cv, } if len(labelNames) == 0 && len(headerLabels) == 0 { c.collector = cv.WithLabelValues() c.Add(0) } return c } type counterWithHeaders struct { name string cv *stdprometheus.CounterVec labelNamesValues labelNamesValues headers map[string]string collector stdprometheus.Counter } func (c *counterWithHeaders) With(headers http.Header, labelValues ...string) CounterWithHeaders { for headerLabel, headerKey := range c.headers { labelValues = append(labelValues, headerLabel, headers.Get(headerKey)) } lnv := c.labelNamesValues.With(labelValues...) return &counterWithHeaders{ name: c.name, headers: c.headers, cv: c.cv, labelNamesValues: lnv, collector: c.cv.With(lnv.ToLabels()), } } func (c *counterWithHeaders) Add(delta float64) { c.collector.Add(delta) } func (c *counterWithHeaders) Describe(ch chan<- *stdprometheus.Desc) { c.cv.Describe(ch) } func newCounterFrom(opts stdprometheus.CounterOpts, labelNames []string) *counter { cv := stdprometheus.NewCounterVec(opts, labelNames) c := &counter{ name: opts.Name, cv: cv, } if len(labelNames) == 0 { c.collector = cv.WithLabelValues() c.Add(0) } return c } type counter struct { name string cv *stdprometheus.CounterVec labelNamesValues labelNamesValues collector stdprometheus.Counter } func (c *counter) With(labelValues ...string) metrics.Counter { lnv := c.labelNamesValues.With(labelValues...) return &counter{ name: c.name, cv: c.cv, labelNamesValues: lnv, collector: c.cv.With(lnv.ToLabels()), } } func (c *counter) Add(delta float64) { c.collector.Add(delta) } func (c *counter) Describe(ch chan<- *stdprometheus.Desc) { c.cv.Describe(ch) } func newGaugeFrom(opts stdprometheus.GaugeOpts, labelNames []string) *gauge { gv := stdprometheus.NewGaugeVec(opts, labelNames) g := &gauge{ name: opts.Name, gv: gv, } if len(labelNames) == 0 { g.collector = gv.WithLabelValues() g.Set(0) } return g } type gauge struct { name string gv *stdprometheus.GaugeVec labelNamesValues labelNamesValues collector stdprometheus.Gauge } func (g *gauge) With(labelValues ...string) metrics.Gauge { lnv := g.labelNamesValues.With(labelValues...) return &gauge{ name: g.name, gv: g.gv, labelNamesValues: lnv, collector: g.gv.With(lnv.ToLabels()), } } func (g *gauge) Add(delta float64) { g.collector.Add(delta) } func (g *gauge) Set(value float64) { g.collector.Set(value) } func (g *gauge) Describe(ch chan<- *stdprometheus.Desc) { g.gv.Describe(ch) } func newHistogramFrom(opts stdprometheus.HistogramOpts, labelNames []string) *histogram { hv := stdprometheus.NewHistogramVec(opts, labelNames) return &histogram{ name: opts.Name, hv: hv, } } type histogram struct { name string hv *stdprometheus.HistogramVec labelNamesValues labelNamesValues collector stdprometheus.Observer } func (h *histogram) With(labelValues ...string) metrics.Histogram { lnv := h.labelNamesValues.With(labelValues...) return &histogram{ name: h.name, hv: h.hv, labelNamesValues: lnv, collector: h.hv.With(lnv.ToLabels()), } } func (h *histogram) Observe(value float64) { h.collector.Observe(value) } func (h *histogram) Describe(ch chan<- *stdprometheus.Desc) { h.hv.Describe(ch) } // labelNamesValues is a type alias that provides validation on its With method. // Metrics may include it as a member to help them satisfy With semantics and // save some code duplication. type labelNamesValues []string // With validates the input, and returns a new aggregate labelNamesValues. func (lvs labelNamesValues) With(labelValues ...string) labelNamesValues { if len(labelValues)%2 != 0 { labelValues = append(labelValues, "unknown") } labels := make([]string, len(lvs)+len(labelValues)) n := copy(labels, lvs) copy(labels[n:], labelValues) return labels } // ToLabels is a convenience method to convert a labelNamesValues // to the native prometheus.Labels. func (lvs labelNamesValues) ToLabels() stdprometheus.Labels { labels := make(map[string]string, len(lvs)/2) for i := 0; i < len(lvs); i += 2 { labels[lvs[i]] = lvs[i+1] } return labels }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/metrics/influxdb2_test.go
pkg/observability/metrics/influxdb2_test.go
package metrics import ( "fmt" "io" "net/http" "net/http/httptest" "strconv" "testing" "time" "github.com/stretchr/testify/require" ptypes "github.com/traefik/paerser/types" otypes "github.com/traefik/traefik/v3/pkg/observability/types" ) func TestInfluxDB2(t *testing.T) { c := make(chan *string) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(r.Body) require.NoError(t, err) bodyStr := string(body) c <- &bodyStr _, _ = fmt.Fprintln(w, "ok") })) influxDB2Registry := RegisterInfluxDB2(t.Context(), &otypes.InfluxDB2{ Address: ts.URL, Token: "test-token", PushInterval: ptypes.Duration(10 * time.Millisecond), Org: "test-org", Bucket: "test-bucket", AddEntryPointsLabels: true, AddRoutersLabels: true, AddServicesLabels: true, }) t.Cleanup(func() { StopInfluxDB2() ts.Close() }) if !influxDB2Registry.IsEpEnabled() || !influxDB2Registry.IsRouterEnabled() || !influxDB2Registry.IsSvcEnabled() { t.Fatalf("InfluxDB2Registry should return true for IsEnabled(), IsRouterEnabled() and IsSvcEnabled()") } expectedServer := []string{ `(traefik\.config\.reload\.total count=1) [\d]{19}`, `(traefik\.config\.reload\.lastSuccessTimestamp value=1) [\d]{19}`, `(traefik\.open\.connections,entrypoint=test,protocol=TCP value=1) [\d]{19}`, } influxDB2Registry.ConfigReloadsCounter().Add(1) influxDB2Registry.LastConfigReloadSuccessGauge().Set(1) influxDB2Registry.OpenConnectionsGauge().With("entrypoint", "test", "protocol", "TCP").Set(1) msgServer := <-c assertMessage(t, *msgServer, expectedServer) expectedTLS := []string{ `(traefik\.tls\.certs\.notAfterTimestamp,key=value value=1) [\d]{19}`, } influxDB2Registry.TLSCertsNotAfterTimestampGauge().With("key", "value").Set(1) msgTLS := <-c assertMessage(t, *msgTLS, expectedTLS) expectedEntrypoint := []string{ `(traefik\.entrypoint\.requests\.total,code=200,entrypoint=test,method=GET count=1) [\d]{19}`, `(traefik\.entrypoint\.requests\.tls\.total,entrypoint=test,tls_cipher=bar,tls_version=foo count=1) [\d]{19}`, `(traefik\.entrypoint\.request\.duration(?:,code=[\d]{3})?,entrypoint=test p50=10000,p90=10000,p95=10000,p99=10000) [\d]{19}`, `(traefik\.entrypoint\.requests\.bytes\.total,code=200,entrypoint=test,method=GET count=1) [\d]{19}`, `(traefik\.entrypoint\.responses\.bytes\.total,code=200,entrypoint=test,method=GET count=1) [\d]{19}`, } influxDB2Registry.EntryPointReqsCounter().With(nil, "entrypoint", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) influxDB2Registry.EntryPointReqsTLSCounter().With("entrypoint", "test", "tls_version", "foo", "tls_cipher", "bar").Add(1) influxDB2Registry.EntryPointReqDurationHistogram().With("entrypoint", "test").Observe(10000) influxDB2Registry.EntryPointReqsBytesCounter().With("entrypoint", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) influxDB2Registry.EntryPointRespsBytesCounter().With("entrypoint", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) msgEntrypoint := <-c assertMessage(t, *msgEntrypoint, expectedEntrypoint) expectedRouter := []string{ `(traefik\.router\.requests\.total,code=200,method=GET,router=demo,service=test count=1) [\d]{19}`, `(traefik\.router\.requests\.total,code=404,method=GET,router=demo,service=test count=1) [\d]{19}`, `(traefik\.router\.requests\.tls\.total,router=demo,service=test,tls_cipher=bar,tls_version=foo count=1) [\d]{19}`, `(traefik\.router\.request\.duration,code=200,router=demo,service=test p50=10000,p90=10000,p95=10000,p99=10000) [\d]{19}`, `(traefik\.router\.requests\.bytes\.total,code=200,method=GET,router=demo,service=test count=1) [\d]{19}`, `(traefik\.router\.responses\.bytes\.total,code=200,method=GET,router=demo,service=test count=1) [\d]{19}`, } influxDB2Registry.RouterReqsCounter().With(nil, "router", "demo", "service", "test", "code", strconv.Itoa(http.StatusNotFound), "method", http.MethodGet).Add(1) influxDB2Registry.RouterReqsCounter().With(nil, "router", "demo", "service", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) influxDB2Registry.RouterReqsTLSCounter().With("router", "demo", "service", "test", "tls_version", "foo", "tls_cipher", "bar").Add(1) influxDB2Registry.RouterReqDurationHistogram().With("router", "demo", "service", "test", "code", strconv.Itoa(http.StatusOK)).Observe(10000) influxDB2Registry.RouterReqsBytesCounter().With("router", "demo", "service", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) influxDB2Registry.RouterRespsBytesCounter().With("router", "demo", "service", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) msgRouter := <-c assertMessage(t, *msgRouter, expectedRouter) expectedService := []string{ `(traefik\.service\.requests\.total,code=200,method=GET,service=test count=1) [\d]{19}`, `(traefik\.service\.requests\.total,code=404,method=GET,service=test count=1) [\d]{19}`, `(traefik\.service\.requests\.tls\.total,service=test,tls_cipher=bar,tls_version=foo count=1) [\d]{19}`, `(traefik\.service\.request\.duration,code=200,service=test p50=10000,p90=10000,p95=10000,p99=10000) [\d]{19}`, `(traefik\.service\.server\.up,service=test,url=http://127.0.0.1 value=1) [\d]{19}`, `(traefik\.service\.requests\.bytes\.total,code=200,method=GET,service=test count=1) [\d]{19}`, `(traefik\.service\.responses\.bytes\.total,code=200,method=GET,service=test count=1) [\d]{19}`, } influxDB2Registry.ServiceReqsCounter().With(nil, "service", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) influxDB2Registry.ServiceReqsCounter().With(nil, "service", "test", "code", strconv.Itoa(http.StatusNotFound), "method", http.MethodGet).Add(1) influxDB2Registry.ServiceReqsTLSCounter().With("service", "test", "tls_version", "foo", "tls_cipher", "bar").Add(1) influxDB2Registry.ServiceReqDurationHistogram().With("service", "test", "code", strconv.Itoa(http.StatusOK)).Observe(10000) influxDB2Registry.ServiceServerUpGauge().With("service", "test", "url", "http://127.0.0.1").Set(1) influxDB2Registry.ServiceReqsBytesCounter().With("service", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) influxDB2Registry.ServiceRespsBytesCounter().With("service", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) msgService := <-c assertMessage(t, *msgService, expectedService) expectedServiceRetries := []string{ `(traefik\.service\.retries\.total,service=test count=2) [\d]{19}`, `(traefik\.service\.retries\.total,service=foobar count=1) [\d]{19}`, } influxDB2Registry.ServiceRetriesCounter().With("service", "test").Add(1) influxDB2Registry.ServiceRetriesCounter().With("service", "test").Add(1) influxDB2Registry.ServiceRetriesCounter().With("service", "foobar").Add(1) msgServiceRetries := <-c assertMessage(t, *msgServiceRetries, expectedServiceRetries) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/metrics/otel_test.go
pkg/observability/metrics/otel_test.go
package metrics import ( "compress/gzip" "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "regexp" "strconv" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ptypes "github.com/traefik/paerser/types" otypes "github.com/traefik/traefik/v3/pkg/observability/types" "github.com/traefik/traefik/v3/pkg/version" "go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp" "go.opentelemetry.io/otel/attribute" ) func TestOpenTelemetry_labels(t *testing.T) { tests := []struct { desc string values otelLabelNamesValues with []string expect []attribute.KeyValue }{ { desc: "with no starting value", values: otelLabelNamesValues{}, expect: []attribute.KeyValue{}, }, { desc: "with one starting value", values: otelLabelNamesValues{"foo"}, expect: []attribute.KeyValue{}, }, { desc: "with two starting value", values: otelLabelNamesValues{"foo", "bar"}, expect: []attribute.KeyValue{attribute.String("foo", "bar")}, }, { desc: "with no starting value, and with one other value", values: otelLabelNamesValues{}, with: []string{"baz"}, expect: []attribute.KeyValue{attribute.String("baz", "unknown")}, }, { desc: "with no starting value, and with two other value", values: otelLabelNamesValues{}, with: []string{"baz", "buz"}, expect: []attribute.KeyValue{attribute.String("baz", "buz")}, }, { desc: "with one starting value, and with one other value", values: otelLabelNamesValues{"foo"}, with: []string{"baz"}, expect: []attribute.KeyValue{attribute.String("foo", "baz")}, }, { desc: "with one starting value, and with two other value", values: otelLabelNamesValues{"foo"}, with: []string{"baz", "buz"}, expect: []attribute.KeyValue{attribute.String("foo", "baz")}, }, { desc: "with two starting value, and with one other value", values: otelLabelNamesValues{"foo", "bar"}, with: []string{"baz"}, expect: []attribute.KeyValue{ attribute.String("foo", "bar"), attribute.String("baz", "unknown"), }, }, { desc: "with two starting value, and with two other value", values: otelLabelNamesValues{"foo", "bar"}, with: []string{"baz", "buz"}, expect: []attribute.KeyValue{ attribute.String("foo", "bar"), attribute.String("baz", "buz"), }, }, } for _, test := range tests { t.Run(test.desc, func(t *testing.T) { t.Parallel() assert.Equal(t, test.expect, test.values.With(test.with...).ToLabels()) }) } } func TestOpenTelemetry_GaugeCollectorAdd(t *testing.T) { tests := []struct { desc string gc *gaugeCollector delta float64 name string attributes otelLabelNamesValues expect map[string]map[string]gaugeValue }{ { desc: "empty collector", gc: newOpenTelemetryGaugeCollector(), delta: 1, name: "foo", expect: map[string]map[string]gaugeValue{ "foo": {"": {value: 1}}, }, }, { desc: "initialized collector", gc: &gaugeCollector{ values: map[string]map[string]gaugeValue{ "foo": {"": {value: 1}}, }, }, delta: 1, name: "foo", expect: map[string]map[string]gaugeValue{ "foo": {"": {value: 2}}, }, }, { desc: "initialized collector, values with label (only the last one counts)", gc: &gaugeCollector{ values: map[string]map[string]gaugeValue{ "foo": { "bar": { attributes: otelLabelNamesValues{"bar"}, value: 1, }, }, }, }, delta: 1, name: "foo", expect: map[string]map[string]gaugeValue{ "foo": { "": { value: 1, }, "bar": { attributes: otelLabelNamesValues{"bar"}, value: 1, }, }, }, }, { desc: "initialized collector, values with label on set", gc: &gaugeCollector{ values: map[string]map[string]gaugeValue{ "foo": {"bar": {value: 1}}, }, }, delta: 1, name: "foo", attributes: otelLabelNamesValues{"baz"}, expect: map[string]map[string]gaugeValue{ "foo": { "bar": { value: 1, }, "baz": { value: 1, attributes: otelLabelNamesValues{"baz"}, }, }, }, }, } for _, test := range tests { t.Run(test.desc, func(t *testing.T) { t.Parallel() test.gc.add(test.name, test.delta, test.attributes) assert.Equal(t, test.expect, test.gc.values) }) } } func TestOpenTelemetry_GaugeCollectorSet(t *testing.T) { tests := []struct { desc string gc *gaugeCollector value float64 name string attributes otelLabelNamesValues expect map[string]map[string]gaugeValue }{ { desc: "empty collector", gc: newOpenTelemetryGaugeCollector(), value: 1, name: "foo", expect: map[string]map[string]gaugeValue{ "foo": {"": {value: 1}}, }, }, { desc: "initialized collector", gc: &gaugeCollector{ values: map[string]map[string]gaugeValue{ "foo": {"": {value: 1}}, }, }, value: 1, name: "foo", expect: map[string]map[string]gaugeValue{ "foo": {"": {value: 1}}, }, }, { desc: "initialized collector, values with label", gc: &gaugeCollector{ values: map[string]map[string]gaugeValue{ "foo": { "bar": { attributes: otelLabelNamesValues{"bar"}, value: 1, }, }, }, }, value: 1, name: "foo", expect: map[string]map[string]gaugeValue{ "foo": { "": { value: 1, }, "bar": { attributes: otelLabelNamesValues{"bar"}, value: 1, }, }, }, }, { desc: "initialized collector, values with label on set", gc: &gaugeCollector{ values: map[string]map[string]gaugeValue{ "foo": {"": {value: 1}}, }, }, value: 1, name: "foo", attributes: otelLabelNamesValues{"bar"}, expect: map[string]map[string]gaugeValue{ "foo": { "": { value: 1, }, "bar": { value: 1, attributes: otelLabelNamesValues{"bar"}, }, }, }, }, } for _, test := range tests { t.Run(test.desc, func(t *testing.T) { t.Parallel() test.gc.set(test.name, test.value, test.attributes) assert.Equal(t, test.expect, test.gc.values) }) } } func TestOpenTelemetry(t *testing.T) { tests := []struct { desc string serviceName string }{ { desc: "default", }, { desc: "custom-service-name", serviceName: "custom-service-name", }, } for _, test := range tests { t.Run(test.desc, func(t *testing.T) { c := make(chan *string, 5) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gzr, err := gzip.NewReader(r.Body) require.NoError(t, err) body, err := io.ReadAll(gzr) require.NoError(t, err) req := pmetricotlp.NewExportRequest() err = req.UnmarshalProto(body) require.NoError(t, err) marshalledReq, err := json.Marshal(req) require.NoError(t, err) bodyStr := string(marshalledReq) c <- &bodyStr w.WriteHeader(http.StatusOK) })) t.Cleanup(func() { StopOpenTelemetry() ts.Close() }) var cfg otypes.OTLP (&cfg).SetDefaults() cfg.AddRoutersLabels = true cfg.HTTP = &otypes.OTelHTTP{ Endpoint: ts.URL, } cfg.PushInterval = ptypes.Duration(10 * time.Millisecond) wantServiceName := "traefik" if test.serviceName != "" { cfg.ServiceName = test.serviceName wantServiceName = test.serviceName } registry := RegisterOpenTelemetry(t.Context(), &cfg) require.NotNil(t, registry) if !registry.IsEpEnabled() || !registry.IsRouterEnabled() || !registry.IsSvcEnabled() { t.Fatalf("registry should return true for IsEnabled(), IsRouterEnabled() and IsSvcEnabled()") } expected := []string{ `({"key":"service.name","value":{"stringValue":"` + wantServiceName + `"}})`, `({"key":"service.version","value":{"stringValue":"` + version.Version + `"}})`, } tryAssertMessage(t, c, expected) // TODO: the len of startUnixNano is no supposed to be 20, it should be 19 expectedConfig := []string{ `({"name":"traefik_config_reloads_total","description":"Config reloads","unit":"1","sum":{"dataPoints":\[{"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1}\],"aggregationTemporality":2,"isMonotonic":true}})`, `({"name":"traefik_config_last_reload_success","description":"Last config reload success","unit":"ms","gauge":{"dataPoints":\[{"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1}\]}})`, `({"name":"traefik_open_connections","description":"How many open connections exist, by entryPoint and protocol","unit":"1","gauge":{"dataPoints":\[{"attributes":\[{"key":"entrypoint","value":{"stringValue":"test"}},{"key":"protocol","value":{"stringValue":"TCP"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1}\]}})`, } registry.ConfigReloadsCounter().Add(1) registry.LastConfigReloadSuccessGauge().Set(1) registry.OpenConnectionsGauge().With("entrypoint", "test", "protocol", "TCP").Set(1) tryAssertMessage(t, c, expectedConfig) expectedTLSCerts := []string{ `({"name":"traefik_tls_certs_not_after","description":"Certificate expiration timestamp","unit":"s","gauge":{"dataPoints":\[{"attributes":\[{"key":"key","value":{"stringValue":"value"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1}\]}})`, } registry.TLSCertsNotAfterTimestampGauge().With("key", "value").Set(1) tryAssertMessage(t, c, expectedTLSCerts) expectedEntryPoints := []string{ `({"name":"traefik_entrypoint_requests_total","description":"How many HTTP requests processed on an entrypoint, partitioned by status code, protocol, and method.","unit":"1","sum":{"dataPoints":\[{"attributes":\[{"key":"code","value":{"stringValue":"200"}},{"key":"entrypoint","value":{"stringValue":"test1"}},{"key":"method","value":{"stringValue":"GET"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1}\],"aggregationTemporality":2,"isMonotonic":true}})`, `({"name":"traefik_entrypoint_requests_tls_total","description":"How many HTTP requests with TLS processed on an entrypoint, partitioned by TLS Version and TLS cipher Used.","unit":"1","sum":{"dataPoints":\[{"attributes":\[{"key":"entrypoint","value":{"stringValue":"test2"}},{"key":"tls_cipher","value":{"stringValue":"bar"}},{"key":"tls_version","value":{"stringValue":"foo"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1}\],"aggregationTemporality":2,"isMonotonic":true}})`, `({"name":"traefik_entrypoint_request_duration_seconds","description":"How long it took to process the request on an entrypoint, partitioned by status code, protocol, and method.","unit":"s","histogram":{"dataPoints":\[{"attributes":\[{"key":"entrypoint","value":{"stringValue":"test3"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","count":"1","sum":10000,"bucketCounts":\["0","0","0","0","0","0","0","0","0","0","0","0","0","0","1"\],"explicitBounds":\[0.005,0.01,0.025,0.05,0.075,0.1,0.25,0.5,0.75,1,2.5,5,7.5,10\],"min":10000,"max":10000}\],"aggregationTemporality":2}})`, `({"name":"traefik_entrypoint_requests_bytes_total","description":"The total size of requests in bytes handled by an entrypoint, partitioned by status code, protocol, and method.","unit":"1","sum":{"dataPoints":\[{"attributes":\[{"key":"code","value":{"stringValue":"200"}},{"key":"entrypoint","value":{"stringValue":"test1"}},{"key":"method","value":{"stringValue":"GET"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1}\],"aggregationTemporality":2,"isMonotonic":true}})`, `({"name":"traefik_entrypoint_responses_bytes_total","description":"The total size of responses in bytes handled by an entrypoint, partitioned by status code, protocol, and method.","unit":"1","sum":{"dataPoints":\[{"attributes":\[{"key":"code","value":{"stringValue":"200"}},{"key":"entrypoint","value":{"stringValue":"test1"}},{"key":"method","value":{"stringValue":"GET"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1}\],"aggregationTemporality":2,"isMonotonic":true}})`, } registry.EntryPointReqsCounter().With(nil, "entrypoint", "test1", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) registry.EntryPointReqsTLSCounter().With("entrypoint", "test2", "tls_version", "foo", "tls_cipher", "bar").Add(1) registry.EntryPointReqDurationHistogram().With("entrypoint", "test3").Observe(10000) registry.EntryPointReqsBytesCounter().With("entrypoint", "test1", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) registry.EntryPointRespsBytesCounter().With("entrypoint", "test1", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) tryAssertMessage(t, c, expectedEntryPoints) expectedRouters := []string{ `({"name":"traefik_router_requests_total","description":"How many HTTP requests are processed on a router, partitioned by service, status code, protocol, and method.","unit":"1","sum":{"dataPoints":\[{"attributes":\[{"key":"code","value":{"stringValue":"(?:200|404)"}},{"key":"method","value":{"stringValue":"GET"}},{"key":"router","value":{"stringValue":"RouterReqsCounter"}},{"key":"service","value":{"stringValue":"test"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1},{"attributes":\[{"key":"code","value":{"stringValue":"(?:200|404)"}},{"key":"method","value":{"stringValue":"GET"}},{"key":"router","value":{"stringValue":"RouterReqsCounter"}},{"key":"service","value":{"stringValue":"test"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1}\],"aggregationTemporality":2,"isMonotonic":true}})`, `({"name":"traefik_router_requests_tls_total","description":"How many HTTP requests with TLS are processed on a router, partitioned by service, TLS Version, and TLS cipher Used.","unit":"1","sum":{"dataPoints":\[{"attributes":\[{"key":"router","value":{"stringValue":"demo"}},{"key":"service","value":{"stringValue":"test"}},{"key":"tls_cipher","value":{"stringValue":"bar"}},{"key":"tls_version","value":{"stringValue":"foo"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1}\],"aggregationTemporality":2,"isMonotonic":true}})`, `({"name":"traefik_router_request_duration_seconds","description":"How long it took to process the request on a router, partitioned by service, status code, protocol, and method.","unit":"s","histogram":{"dataPoints":\[{"attributes":\[{"key":"code","value":{"stringValue":"200"}},{"key":"router","value":{"stringValue":"demo"}},{"key":"service","value":{"stringValue":"test"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","count":"1","sum":10000,"bucketCounts":\["0","0","0","0","0","0","0","0","0","0","0","0","0","0","1"\],"explicitBounds":\[0.005,0.01,0.025,0.05,0.075,0.1,0.25,0.5,0.75,1,2.5,5,7.5,10\],"min":10000,"max":10000}\],"aggregationTemporality":2}})`, `({"name":"traefik_router_requests_bytes_total","description":"The total size of requests in bytes handled by a router, partitioned by status code, protocol, and method.","unit":"1","sum":{"dataPoints":\[{"attributes":\[{"key":"code","value":{"stringValue":"404"}},{"key":"method","value":{"stringValue":"GET"}},{"key":"router","value":{"stringValue":"RouterReqsCounter"}},{"key":"service","value":{"stringValue":"test"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1}\],"aggregationTemporality":2,"isMonotonic":true}})`, `({"name":"traefik_router_responses_bytes_total","description":"The total size of responses in bytes handled by a router, partitioned by status code, protocol, and method.","unit":"1","sum":{"dataPoints":\[{"attributes":\[{"key":"code","value":{"stringValue":"404"}},{"key":"method","value":{"stringValue":"GET"}},{"key":"router","value":{"stringValue":"RouterReqsCounter"}},{"key":"service","value":{"stringValue":"test"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1}\],"aggregationTemporality":2,"isMonotonic":true}})`, } registry.RouterReqsCounter().With(nil, "router", "RouterReqsCounter", "service", "test", "code", strconv.Itoa(http.StatusNotFound), "method", http.MethodGet).Add(1) registry.RouterReqsCounter().With(nil, "router", "RouterReqsCounter", "service", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) registry.RouterReqsTLSCounter().With("router", "demo", "service", "test", "tls_version", "foo", "tls_cipher", "bar").Add(1) registry.RouterReqDurationHistogram().With("router", "demo", "service", "test", "code", strconv.Itoa(http.StatusOK)).Observe(10000) registry.RouterReqsBytesCounter().With("router", "RouterReqsCounter", "service", "test", "code", strconv.Itoa(http.StatusNotFound), "method", http.MethodGet).Add(1) registry.RouterRespsBytesCounter().With("router", "RouterReqsCounter", "service", "test", "code", strconv.Itoa(http.StatusNotFound), "method", http.MethodGet).Add(1) tryAssertMessage(t, c, expectedRouters) expectedServices := []string{ `({"name":"traefik_service_requests_total","description":"How many HTTP requests processed on a service, partitioned by status code, protocol, and method.","unit":"1","sum":{"dataPoints":\[{"attributes":\[{"key":"code","value":{"stringValue":"(?:200|404)"}},{"key":"method","value":{"stringValue":"GET"}},{"key":"service","value":{"stringValue":"ServiceReqsCounter"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1},{"attributes":\[{"key":"code","value":{"stringValue":"(?:200|404)"}},{"key":"method","value":{"stringValue":"GET"}},{"key":"service","value":{"stringValue":"ServiceReqsCounter"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1}\],"aggregationTemporality":2,"isMonotonic":true}})`, `({"name":"traefik_service_requests_tls_total","description":"How many HTTP requests with TLS processed on a service, partitioned by TLS version and TLS cipher.","unit":"1","sum":{"dataPoints":\[{"attributes":\[{"key":"service","value":{"stringValue":"test"}},{"key":"tls_cipher","value":{"stringValue":"bar"}},{"key":"tls_version","value":{"stringValue":"foo"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1}\],"aggregationTemporality":2,"isMonotonic":true}})`, `({"name":"traefik_service_request_duration_seconds","description":"How long it took to process the request on a service, partitioned by status code, protocol, and method.","unit":"s","histogram":{"dataPoints":\[{"attributes":\[{"key":"code","value":{"stringValue":"200"}},{"key":"service","value":{"stringValue":"test"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","count":"1","sum":10000,"bucketCounts":\["0","0","0","0","0","0","0","0","0","0","0","0","0","0","1"\],"explicitBounds":\[0.005,0.01,0.025,0.05,0.075,0.1,0.25,0.5,0.75,1,2.5,5,7.5,10\],"min":10000,"max":10000}\],"aggregationTemporality":2}})`, `({"name":"traefik_service_server_up","description":"service server is up, described by gauge value of 0 or 1.","unit":"1","gauge":{"dataPoints":\[{"attributes":\[{"key":"service","value":{"stringValue":"test"}},{"key":"url","value":{"stringValue":"http://127.0.0.1"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1}\]}})`, `({"name":"traefik_service_requests_bytes_total","description":"The total size of requests in bytes received by a service, partitioned by status code, protocol, and method.","unit":"1","sum":{"dataPoints":\[{"attributes":\[{"key":"code","value":{"stringValue":"404"}},{"key":"method","value":{"stringValue":"GET"}},{"key":"service","value":{"stringValue":"ServiceReqsCounter"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1}\],"aggregationTemporality":2,"isMonotonic":true}})`, `({"name":"traefik_service_responses_bytes_total","description":"The total size of responses in bytes returned by a service, partitioned by status code, protocol, and method.","unit":"1","sum":{"dataPoints":\[{"attributes":\[{"key":"code","value":{"stringValue":"404"}},{"key":"method","value":{"stringValue":"GET"}},{"key":"service","value":{"stringValue":"ServiceReqsCounter"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1}\],"aggregationTemporality":2,"isMonotonic":true}})`, } registry.ServiceReqsCounter().With(nil, "service", "ServiceReqsCounter", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) registry.ServiceReqsCounter().With(nil, "service", "ServiceReqsCounter", "code", strconv.Itoa(http.StatusNotFound), "method", http.MethodGet).Add(1) registry.ServiceReqsTLSCounter().With("service", "test", "tls_version", "foo", "tls_cipher", "bar").Add(1) registry.ServiceReqDurationHistogram().With("service", "test", "code", strconv.Itoa(http.StatusOK)).Observe(10000) registry.ServiceServerUpGauge().With("service", "test", "url", "http://127.0.0.1").Set(1) registry.ServiceReqsBytesCounter().With("service", "ServiceReqsCounter", "code", strconv.Itoa(http.StatusNotFound), "method", http.MethodGet).Add(1) registry.ServiceRespsBytesCounter().With("service", "ServiceReqsCounter", "code", strconv.Itoa(http.StatusNotFound), "method", http.MethodGet).Add(1) tryAssertMessage(t, c, expectedServices) expectedServicesRetries := []string{ `({"attributes":\[{"key":"service","value":{"stringValue":"foobar"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":1})`, `({"attributes":\[{"key":"service","value":{"stringValue":"test"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","asDouble":2})`, } registry.ServiceRetriesCounter().With("service", "test").Add(1) registry.ServiceRetriesCounter().With("service", "test").Add(1) registry.ServiceRetriesCounter().With("service", "foobar").Add(1) tryAssertMessage(t, c, expectedServicesRetries) // We cannot rely on the previous expected pattern, // because this pattern was for matching only one dataPoint in the histogram, // and as soon as the EntryPointReqDurationHistogram.Observe is called, // it adds a new dataPoint to the histogram. expectedEntryPointReqDuration := []string{ `({"attributes":\[{"key":"entrypoint","value":{"stringValue":"myEntrypoint"}}\],"startTimeUnixNano":"[\d]{19}","timeUnixNano":"[\d]{19}","count":"2","sum":30000,"bucketCounts":\["0","0","0","0","0","0","0","0","0","0","0","0","0","0","2"\],"explicitBounds":\[0.005,0.01,0.025,0.05,0.075,0.1,0.25,0.5,0.75,1,2.5,5,7.5,10\],"min":10000,"max":20000})`, } registry.EntryPointReqDurationHistogram().With("entrypoint", "myEntrypoint").Observe(10000) registry.EntryPointReqDurationHistogram().With("entrypoint", "myEntrypoint").Observe(20000) tryAssertMessage(t, c, expectedEntryPointReqDuration) }) } } func assertMessage(t *testing.T, msg string, expected []string) { t.Helper() errs := verifyMessage(msg, expected) for _, err := range errs { t.Error(err) } } func tryAssertMessage(t *testing.T, c chan *string, expected []string) { t.Helper() var errs []error timeout := time.After(1 * time.Second) for { select { case <-timeout: for _, err := range errs { t.Error(err) } case msg := <-c: errs = verifyMessage(*msg, expected) if len(errs) == 0 { return } } } } func verifyMessage(msg string, expected []string) []error { var errs []error for _, pattern := range expected { re := regexp.MustCompile(pattern) match := re.FindStringSubmatch(msg) if len(match) != 2 { errs = append(errs, fmt.Errorf("got %q %v, want %q", msg, match, pattern)) } } return errs }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/metrics/datadog_test.go
pkg/observability/metrics/datadog_test.go
package metrics import ( "net/http" "strconv" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stvp/go-udp-testing" ptypes "github.com/traefik/paerser/types" otypes "github.com/traefik/traefik/v3/pkg/observability/types" ) func TestDatadog(t *testing.T) { t.Cleanup(StopDatadog) udp.SetAddr(":18125") // This is needed to make sure that UDP Listener listens for data a bit longer, otherwise it will quit after a millisecond udp.Timeout = 5 * time.Second datadogRegistry := RegisterDatadog(t.Context(), &otypes.Datadog{Address: ":18125", PushInterval: ptypes.Duration(time.Second), AddEntryPointsLabels: true, AddRoutersLabels: true, AddServicesLabels: true}) if !datadogRegistry.IsEpEnabled() || !datadogRegistry.IsRouterEnabled() || !datadogRegistry.IsSvcEnabled() { t.Errorf("DatadogRegistry should return true for IsEnabled(), IsRouterEnabled() and IsSvcEnabled()") } testDatadogRegistry(t, defaultMetricsPrefix, datadogRegistry) } func TestDatadogWithPrefix(t *testing.T) { t.Cleanup(StopDatadog) udp.SetAddr(":18125") // This is needed to make sure that UDP Listener listens for data a bit longer, otherwise it will quit after a millisecond udp.Timeout = 5 * time.Second datadogRegistry := RegisterDatadog(t.Context(), &otypes.Datadog{Prefix: "testPrefix", Address: ":18125", PushInterval: ptypes.Duration(time.Second), AddEntryPointsLabels: true, AddRoutersLabels: true, AddServicesLabels: true}) testDatadogRegistry(t, "testPrefix", datadogRegistry) } func TestDatadog_parseDatadogAddress(t *testing.T) { tests := []struct { desc string address string expNetwork string expAddress string }{ { desc: "empty address", expNetwork: "udp", expAddress: "localhost:8125", }, { desc: "udp address", address: "127.0.0.1:8080", expNetwork: "udp", expAddress: "127.0.0.1:8080", }, { desc: "unix address", address: "unix:///path/to/datadog.socket", expNetwork: "unix", expAddress: "/path/to/datadog.socket", }, { desc: "unixgram address", address: "unixgram:///path/to/datadog.socket", expNetwork: "unixgram", expAddress: "/path/to/datadog.socket", }, { desc: "unixstream address", address: "unixstream:///path/to/datadog.socket", expNetwork: "unixstream", expAddress: "/path/to/datadog.socket", }, } for _, test := range tests { t.Run(test.desc, func(t *testing.T) { t.Parallel() gotNetwork, gotAddress := parseDatadogAddress(test.address) assert.Equal(t, test.expNetwork, gotNetwork) assert.Equal(t, test.expAddress, gotAddress) }) } } func testDatadogRegistry(t *testing.T, metricsPrefix string, datadogRegistry Registry) { t.Helper() expected := []string{ metricsPrefix + ".config.reload.total:1.000000|c\n", metricsPrefix + ".config.reload.lastSuccessTimestamp:1.000000|g\n", metricsPrefix + ".open.connections:1.000000|g|#entrypoint:test,protocol:TCP\n", metricsPrefix + ".tls.certs.notAfterTimestamp:1.000000|g|#key:value\n", metricsPrefix + ".entrypoint.request.total:1.000000|c|#entrypoint:test\n", metricsPrefix + ".entrypoint.request.tls.total:1.000000|c|#entrypoint:test,tls_version:foo,tls_cipher:bar\n", metricsPrefix + ".entrypoint.request.duration:10000.000000|h|#entrypoint:test\n", metricsPrefix + ".entrypoint.requests.bytes.total:1.000000|c|#entrypoint:test\n", metricsPrefix + ".entrypoint.responses.bytes.total:1.000000|c|#entrypoint:test\n", metricsPrefix + ".router.request.total:1.000000|c|#router:demo,service:test,code:404,method:GET\n", metricsPrefix + ".router.request.total:1.000000|c|#router:demo,service:test,code:200,method:GET\n", metricsPrefix + ".router.request.tls.total:1.000000|c|#router:demo,service:test,tls_version:foo,tls_cipher:bar\n", metricsPrefix + ".router.request.duration:10000.000000|h|#router:demo,service:test,code:200\n", metricsPrefix + ".router.requests.bytes.total:1.000000|c|#router:demo,service:test,code:200,method:GET\n", metricsPrefix + ".router.responses.bytes.total:1.000000|c|#router:demo,service:test,code:200,method:GET\n", metricsPrefix + ".service.request.total:1.000000|c|#service:test,code:404,method:GET\n", metricsPrefix + ".service.request.total:1.000000|c|#service:test,code:200,method:GET\n", metricsPrefix + ".service.request.tls.total:1.000000|c|#service:test,tls_version:foo,tls_cipher:bar\n", metricsPrefix + ".service.request.duration:10000.000000|h|#service:test,code:200\n", metricsPrefix + ".service.retries.total:2.000000|c|#service:test\n", metricsPrefix + ".service.request.duration:10000.000000|h|#service:test,code:200\n", metricsPrefix + ".service.server.up:1.000000|g|#service:test,url:http://127.0.0.1,one:two\n", metricsPrefix + ".service.requests.bytes.total:1.000000|c|#service:test,code:200,method:GET\n", metricsPrefix + ".service.responses.bytes.total:1.000000|c|#service:test,code:200,method:GET\n", } udp.ShouldReceiveAll(t, expected, func() { datadogRegistry.ConfigReloadsCounter().Add(1) datadogRegistry.LastConfigReloadSuccessGauge().Add(1) datadogRegistry.OpenConnectionsGauge().With("entrypoint", "test", "protocol", "TCP").Add(1) datadogRegistry.TLSCertsNotAfterTimestampGauge().With("key", "value").Set(1) datadogRegistry.EntryPointReqsCounter().With(nil, "entrypoint", "test").Add(1) datadogRegistry.EntryPointReqsTLSCounter().With("entrypoint", "test", "tls_version", "foo", "tls_cipher", "bar").Add(1) datadogRegistry.EntryPointReqDurationHistogram().With("entrypoint", "test").Observe(10000) datadogRegistry.EntryPointReqsBytesCounter().With("entrypoint", "test").Add(1) datadogRegistry.EntryPointRespsBytesCounter().With("entrypoint", "test").Add(1) datadogRegistry.RouterReqsCounter().With(nil, "router", "demo", "service", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) datadogRegistry.RouterReqsCounter().With(nil, "router", "demo", "service", "test", "code", strconv.Itoa(http.StatusNotFound), "method", http.MethodGet).Add(1) datadogRegistry.RouterReqsTLSCounter().With("router", "demo", "service", "test", "tls_version", "foo", "tls_cipher", "bar").Add(1) datadogRegistry.RouterReqDurationHistogram().With("router", "demo", "service", "test", "code", strconv.Itoa(http.StatusOK)).Observe(10000) datadogRegistry.RouterReqsBytesCounter().With("router", "demo", "service", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) datadogRegistry.RouterRespsBytesCounter().With("router", "demo", "service", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) datadogRegistry.ServiceReqsCounter().With(nil, "service", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) datadogRegistry.ServiceReqsCounter().With(nil, "service", "test", "code", strconv.Itoa(http.StatusNotFound), "method", http.MethodGet).Add(1) datadogRegistry.ServiceReqsTLSCounter().With("service", "test", "tls_version", "foo", "tls_cipher", "bar").Add(1) datadogRegistry.ServiceReqDurationHistogram().With("service", "test", "code", strconv.Itoa(http.StatusOK)).Observe(10000) datadogRegistry.ServiceRetriesCounter().With("service", "test").Add(1) datadogRegistry.ServiceRetriesCounter().With("service", "test").Add(1) datadogRegistry.ServiceServerUpGauge().With("service", "test", "url", "http://127.0.0.1", "one", "two").Set(1) datadogRegistry.ServiceReqsBytesCounter().With("service", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) datadogRegistry.ServiceRespsBytesCounter().With("service", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) }) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/metrics/statsd_test.go
pkg/observability/metrics/statsd_test.go
package metrics import ( "net/http" "strconv" "testing" "time" "github.com/stvp/go-udp-testing" ptypes "github.com/traefik/paerser/types" otypes "github.com/traefik/traefik/v3/pkg/observability/types" ) func TestStatsD(t *testing.T) { t.Cleanup(func() { StopStatsd() }) udp.SetAddr(":18125") // This is needed to make sure that UDP Listener listens for data a bit longer, otherwise it will quit after a millisecond udp.Timeout = 5 * time.Second statsdRegistry := RegisterStatsd(t.Context(), &otypes.Statsd{Address: ":18125", PushInterval: ptypes.Duration(time.Second), AddEntryPointsLabels: true, AddRoutersLabels: true, AddServicesLabels: true}) testRegistry(t, defaultMetricsPrefix, statsdRegistry) } func TestStatsDWithPrefix(t *testing.T) { t.Cleanup(func() { StopStatsd() }) udp.SetAddr(":18125") // This is needed to make sure that UDP Listener listens for data a bit longer, otherwise it will quit after a millisecond udp.Timeout = 5 * time.Second statsdRegistry := RegisterStatsd(t.Context(), &otypes.Statsd{Address: ":18125", PushInterval: ptypes.Duration(time.Second), AddEntryPointsLabels: true, AddRoutersLabels: true, AddServicesLabels: true, Prefix: "testPrefix"}) testRegistry(t, "testPrefix", statsdRegistry) } func testRegistry(t *testing.T, metricsPrefix string, registry Registry) { t.Helper() if !registry.IsEpEnabled() || !registry.IsRouterEnabled() || !registry.IsSvcEnabled() { t.Errorf("Statsd registry should return true for IsEnabled(), IsRouterEnabled() and IsSvcEnabled()") } expected := []string{ metricsPrefix + ".config.reload.total:1.000000|c\n", metricsPrefix + ".config.reload.lastSuccessTimestamp:1.000000|g\n", metricsPrefix + ".open.connections:1.000000|g\n", metricsPrefix + ".tls.certs.notAfterTimestamp:1.000000|g\n", metricsPrefix + ".entrypoint.request.total:1.000000|c\n", metricsPrefix + ".entrypoint.request.tls.total:1.000000|c\n", metricsPrefix + ".entrypoint.request.duration:10000.000000|ms", metricsPrefix + ".entrypoint.requests.bytes.total:1.000000|c\n", metricsPrefix + ".entrypoint.responses.bytes.total:1.000000|c\n", metricsPrefix + ".router.request.total:2.000000|c\n", metricsPrefix + ".router.request.tls.total:1.000000|c\n", metricsPrefix + ".router.request.duration:10000.000000|ms", metricsPrefix + ".router.requests.bytes.total:1.000000|c\n", metricsPrefix + ".router.responses.bytes.total:1.000000|c\n", metricsPrefix + ".service.request.total:2.000000|c\n", metricsPrefix + ".service.request.tls.total:1.000000|c\n", metricsPrefix + ".service.request.duration:10000.000000|ms", metricsPrefix + ".service.retries.total:2.000000|c\n", metricsPrefix + ".service.server.up:1.000000|g\n", metricsPrefix + ".service.requests.bytes.total:1.000000|c\n", metricsPrefix + ".service.responses.bytes.total:1.000000|c\n", } udp.ShouldReceiveAll(t, expected, func() { registry.ConfigReloadsCounter().Add(1) registry.LastConfigReloadSuccessGauge().Set(1) registry.OpenConnectionsGauge().With("entrypoint", "test", "protocol", "TCP").Set(1) registry.TLSCertsNotAfterTimestampGauge().With("key", "value").Set(1) registry.EntryPointReqsCounter().With(nil, "entrypoint", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) registry.EntryPointReqsTLSCounter().With("entrypoint", "test", "tls_version", "foo", "tls_cipher", "bar").Add(1) registry.EntryPointReqDurationHistogram().With("entrypoint", "test").Observe(10000) registry.EntryPointReqsBytesCounter().With("entrypoint", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) registry.EntryPointRespsBytesCounter().With("entrypoint", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) registry.RouterReqsCounter().With(nil, "router", "demo", "service", "test", "code", strconv.Itoa(http.StatusNotFound), "method", http.MethodGet).Add(1) registry.RouterReqsCounter().With(nil, "router", "demo", "service", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) registry.RouterReqsTLSCounter().With("router", "demo", "service", "test", "tls_version", "foo", "tls_cipher", "bar").Add(1) registry.RouterReqDurationHistogram().With("router", "demo", "service", "test", "code", strconv.Itoa(http.StatusOK)).Observe(10000) registry.RouterReqsBytesCounter().With("router", "demo", "service", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) registry.RouterRespsBytesCounter().With("router", "demo", "service", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) registry.ServiceReqsCounter().With(nil, "service", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) registry.ServiceReqsCounter().With(nil, "service", "test", "code", strconv.Itoa(http.StatusNotFound), "method", http.MethodGet).Add(1) registry.ServiceReqsTLSCounter().With("service", "test", "tls_version", "foo", "tls_cipher", "bar").Add(1) registry.ServiceReqDurationHistogram().With("service", "test", "code", strconv.Itoa(http.StatusOK)).Observe(10000) registry.ServiceRetriesCounter().With("service", "test").Add(1) registry.ServiceRetriesCounter().With("service", "test").Add(1) registry.ServiceServerUpGauge().With("service:test", "url", "http://127.0.0.1").Set(1) registry.ServiceReqsBytesCounter().With("service", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) registry.ServiceRespsBytesCounter().With("service", "test", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet).Add(1) }) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/metrics/influxdb2.go
pkg/observability/metrics/influxdb2.go
package metrics import ( "context" "errors" "time" "github.com/go-kit/kit/metrics/influx" influxdb2 "github.com/influxdata/influxdb-client-go/v2" influxdb2api "github.com/influxdata/influxdb-client-go/v2/api" "github.com/influxdata/influxdb-client-go/v2/api/write" influxdb2log "github.com/influxdata/influxdb-client-go/v2/log" influxdb "github.com/influxdata/influxdb1-client/v2" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/observability/logs" otypes "github.com/traefik/traefik/v3/pkg/observability/types" "github.com/traefik/traefik/v3/pkg/safe" ) var ( influxDB2Ticker *time.Ticker influxDB2Store *influx.Influx influxDB2Client influxdb2.Client ) const ( influxDBConfigReloadsName = "traefik.config.reload.total" influxDBLastConfigReloadSuccessName = "traefik.config.reload.lastSuccessTimestamp" influxDBOpenConnsName = "traefik.open.connections" influxDBTLSCertsNotAfterTimestampName = "traefik.tls.certs.notAfterTimestamp" influxDBEntryPointReqsName = "traefik.entrypoint.requests.total" influxDBEntryPointReqsTLSName = "traefik.entrypoint.requests.tls.total" influxDBEntryPointReqDurationName = "traefik.entrypoint.request.duration" influxDBEntryPointReqsBytesName = "traefik.entrypoint.requests.bytes.total" influxDBEntryPointRespsBytesName = "traefik.entrypoint.responses.bytes.total" influxDBRouterReqsName = "traefik.router.requests.total" influxDBRouterReqsTLSName = "traefik.router.requests.tls.total" influxDBRouterReqsDurationName = "traefik.router.request.duration" influxDBRouterReqsBytesName = "traefik.router.requests.bytes.total" influxDBRouterRespsBytesName = "traefik.router.responses.bytes.total" influxDBServiceReqsName = "traefik.service.requests.total" influxDBServiceReqsTLSName = "traefik.service.requests.tls.total" influxDBServiceReqsDurationName = "traefik.service.request.duration" influxDBServiceRetriesTotalName = "traefik.service.retries.total" influxDBServiceServerUpName = "traefik.service.server.up" influxDBServiceReqsBytesName = "traefik.service.requests.bytes.total" influxDBServiceRespsBytesName = "traefik.service.responses.bytes.total" ) // RegisterInfluxDB2 creates metrics exporter for InfluxDB2. func RegisterInfluxDB2(ctx context.Context, config *otypes.InfluxDB2) Registry { logger := log.Ctx(ctx) if influxDB2Client == nil { var err error if influxDB2Client, err = newInfluxDB2Client(config); err != nil { logger.Error().Err(err).Send() return nil } } if influxDB2Store == nil { influxDB2Store = influx.New( config.AdditionalLabels, influxdb.BatchPointsConfig{}, logs.NewGoKitWrapper(*logger), ) influxDB2Ticker = time.NewTicker(time.Duration(config.PushInterval)) safe.Go(func() { wc := influxDB2Client.WriteAPIBlocking(config.Org, config.Bucket) influxDB2Store.WriteLoop(ctx, influxDB2Ticker.C, influxDB2Writer{wc: wc}) }) } registry := &standardRegistry{ configReloadsCounter: influxDB2Store.NewCounter(influxDBConfigReloadsName), lastConfigReloadSuccessGauge: influxDB2Store.NewGauge(influxDBLastConfigReloadSuccessName), openConnectionsGauge: influxDB2Store.NewGauge(influxDBOpenConnsName), tlsCertsNotAfterTimestampGauge: influxDB2Store.NewGauge(influxDBTLSCertsNotAfterTimestampName), } if config.AddEntryPointsLabels { registry.epEnabled = config.AddEntryPointsLabels registry.entryPointReqsCounter = NewCounterWithNoopHeaders(influxDB2Store.NewCounter(influxDBEntryPointReqsName)) registry.entryPointReqsTLSCounter = influxDB2Store.NewCounter(influxDBEntryPointReqsTLSName) registry.entryPointReqDurationHistogram, _ = NewHistogramWithScale(influxDB2Store.NewHistogram(influxDBEntryPointReqDurationName), time.Second) registry.entryPointReqsBytesCounter = influxDB2Store.NewCounter(influxDBEntryPointReqsBytesName) registry.entryPointRespsBytesCounter = influxDB2Store.NewCounter(influxDBEntryPointRespsBytesName) } if config.AddRoutersLabels { registry.routerEnabled = config.AddRoutersLabels registry.routerReqsCounter = NewCounterWithNoopHeaders(influxDB2Store.NewCounter(influxDBRouterReqsName)) registry.routerReqsTLSCounter = influxDB2Store.NewCounter(influxDBRouterReqsTLSName) registry.routerReqDurationHistogram, _ = NewHistogramWithScale(influxDB2Store.NewHistogram(influxDBRouterReqsDurationName), time.Second) registry.routerReqsBytesCounter = influxDB2Store.NewCounter(influxDBRouterReqsBytesName) registry.routerRespsBytesCounter = influxDB2Store.NewCounter(influxDBRouterRespsBytesName) } if config.AddServicesLabels { registry.svcEnabled = config.AddServicesLabels registry.serviceReqsCounter = NewCounterWithNoopHeaders(influxDB2Store.NewCounter(influxDBServiceReqsName)) registry.serviceReqsTLSCounter = influxDB2Store.NewCounter(influxDBServiceReqsTLSName) registry.serviceReqDurationHistogram, _ = NewHistogramWithScale(influxDB2Store.NewHistogram(influxDBServiceReqsDurationName), time.Second) registry.serviceRetriesCounter = influxDB2Store.NewCounter(influxDBServiceRetriesTotalName) registry.serviceServerUpGauge = influxDB2Store.NewGauge(influxDBServiceServerUpName) registry.serviceReqsBytesCounter = influxDB2Store.NewCounter(influxDBServiceReqsBytesName) registry.serviceRespsBytesCounter = influxDB2Store.NewCounter(influxDBServiceRespsBytesName) } return registry } // StopInfluxDB2 stops and resets InfluxDB2 client, ticker and store. func StopInfluxDB2() { if influxDB2Client != nil { influxDB2Client.Close() } influxDB2Client = nil if influxDB2Ticker != nil { influxDB2Ticker.Stop() } influxDB2Ticker = nil influxDB2Store = nil } // newInfluxDB2Client creates an influxdb2.Client. func newInfluxDB2Client(config *otypes.InfluxDB2) (influxdb2.Client, error) { if config.Token == "" || config.Org == "" || config.Bucket == "" { return nil, errors.New("token, org or bucket property is missing") } // Disable InfluxDB2 logs. // See https://github.com/influxdata/influxdb-client-go/blob/v2.7.0/options.go#L128 influxdb2log.Log = nil return influxdb2.NewClient(config.Address, config.Token), nil } type influxDB2Writer struct { wc influxdb2api.WriteAPIBlocking } func (w influxDB2Writer) Write(bp influxdb.BatchPoints) error { logger := log.With().Str(logs.MetricsProviderName, "influxdb2").Logger() wps := make([]*write.Point, 0, len(bp.Points())) for _, p := range bp.Points() { fields, err := p.Fields() if err != nil { logger.Error().Err(err).Msgf("Error while getting %s point fields", p.Name()) continue } wps = append(wps, influxdb2.NewPoint( p.Name(), p.Tags(), fields, p.Time(), )) } ctx := logger.WithContext(context.Background()) return w.wc.WritePoint(ctx, wps...) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/metrics/prometheus_test.go
pkg/observability/metrics/prometheus_test.go
package metrics import ( "fmt" "net/http" "strconv" "testing" "time" "github.com/prometheus/client_golang/prometheus" dto "github.com/prometheus/client_model/go" "github.com/stretchr/testify/assert" "github.com/traefik/traefik/v3/pkg/config/dynamic" otypes "github.com/traefik/traefik/v3/pkg/observability/types" th "github.com/traefik/traefik/v3/pkg/testhelpers" ) func TestRegisterPromState(t *testing.T) { t.Cleanup(promState.reset) testCases := []struct { desc string prometheusSlice []*otypes.Prometheus initPromState bool unregisterPromState bool expectedNbRegistries int }{ { desc: "Register once", prometheusSlice: []*otypes.Prometheus{{}}, initPromState: true, unregisterPromState: false, expectedNbRegistries: 1, }, { desc: "Register once with no promState init", prometheusSlice: []*otypes.Prometheus{{}}, initPromState: false, unregisterPromState: false, expectedNbRegistries: 1, }, { desc: "Register twice", prometheusSlice: []*otypes.Prometheus{{}, {}}, initPromState: true, unregisterPromState: false, expectedNbRegistries: 2, }, { desc: "Register twice with no promstate init", prometheusSlice: []*otypes.Prometheus{{}, {}}, initPromState: false, unregisterPromState: false, expectedNbRegistries: 2, }, { desc: "Register twice with unregister", prometheusSlice: []*otypes.Prometheus{{}, {}}, initPromState: true, unregisterPromState: true, expectedNbRegistries: 2, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { actualNbRegistries := 0 for _, prom := range test.prometheusSlice { if test.initPromState { initStandardRegistry(prom) } if registerPromState(t.Context()) { actualNbRegistries++ } if test.unregisterPromState { promRegistry.Unregister(promState) } promState.reset() } promRegistry.Unregister(promState) assert.Equal(t, test.expectedNbRegistries, actualNbRegistries) }) } } func TestPrometheus(t *testing.T) { promState = newPrometheusState() promRegistry = prometheus.NewRegistry() t.Cleanup(promState.reset) prometheusRegistry := RegisterPrometheus(t.Context(), &otypes.Prometheus{ AddEntryPointsLabels: true, AddRoutersLabels: true, AddServicesLabels: true, HeaderLabels: map[string]string{"useragent": "User-Agent"}, }) defer promRegistry.Unregister(promState) if !prometheusRegistry.IsEpEnabled() || !prometheusRegistry.IsRouterEnabled() || !prometheusRegistry.IsSvcEnabled() { t.Errorf("PrometheusRegistry should return true for IsEnabled(), IsRouterEnabled() and IsSvcEnabled()") } prometheusRegistry.ConfigReloadsCounter().Add(1) prometheusRegistry.LastConfigReloadSuccessGauge().Set(float64(time.Now().Unix())) prometheusRegistry. OpenConnectionsGauge(). With("entrypoint", "test", "protocol", "TCP"). Set(1) prometheusRegistry. TLSCertsNotAfterTimestampGauge(). With("cn", "value", "serial", "value", "sans", "value"). Set(float64(time.Now().Unix())) prometheusRegistry. EntryPointReqsCounter(). With(map[string][]string{"User-Agent": {"foobar"}}, "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet, "protocol", "http", "entrypoint", "http"). Add(1) prometheusRegistry. EntryPointReqDurationHistogram(). With("code", strconv.Itoa(http.StatusOK), "method", http.MethodGet, "protocol", "http", "entrypoint", "http"). Observe(1) prometheusRegistry. EntryPointRespsBytesCounter(). With("code", strconv.Itoa(http.StatusOK), "method", http.MethodGet, "protocol", "http", "entrypoint", "http"). Add(1) prometheusRegistry. EntryPointReqsBytesCounter(). With("code", strconv.Itoa(http.StatusOK), "method", http.MethodGet, "protocol", "http", "entrypoint", "http"). Add(1) prometheusRegistry. RouterReqsCounter(). With(nil, "router", "demo", "service", "service1", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet, "protocol", "http"). Add(1) prometheusRegistry. RouterReqsTLSCounter(). With("router", "demo", "service", "service1", "tls_version", "foo", "tls_cipher", "bar"). Add(1) prometheusRegistry. RouterReqDurationHistogram(). With("router", "demo", "service", "service1", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet, "protocol", "http"). Observe(10000) prometheusRegistry. RouterRespsBytesCounter(). With("router", "demo", "service", "service1", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet, "protocol", "http"). Add(1) prometheusRegistry. RouterReqsBytesCounter(). With("router", "demo", "service", "service1", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet, "protocol", "http"). Add(1) prometheusRegistry. ServiceReqsCounter(). With(map[string][]string{"User-Agent": {"foobar"}}, "service", "service1", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet, "protocol", "http"). Add(1) prometheusRegistry. ServiceReqsTLSCounter(). With("service", "service1", "tls_version", "foo", "tls_cipher", "bar"). Add(1) prometheusRegistry. ServiceReqDurationHistogram(). With("service", "service1", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet, "protocol", "http"). Observe(10000) prometheusRegistry. ServiceRetriesCounter(). With("service", "service1"). Add(1) prometheusRegistry. ServiceServerUpGauge(). With("service", "service1", "url", "http://127.0.0.10:80"). Set(1) prometheusRegistry. ServiceRespsBytesCounter(). With("service", "service1", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet, "protocol", "http"). Add(1) prometheusRegistry. ServiceReqsBytesCounter(). With("service", "service1", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet, "protocol", "http"). Add(1) delayForTrackingCompletion() metricsFamilies := mustScrape() testCases := []struct { name string labels map[string]string assert func(*dto.MetricFamily) }{ { name: configReloadsTotalName, assert: buildCounterAssert(t, configReloadsTotalName, 1), }, { name: configLastReloadSuccessName, assert: buildTimestampAssert(t, configLastReloadSuccessName), }, { name: openConnectionsName, labels: map[string]string{ "protocol": "TCP", "entrypoint": "test", }, assert: buildGaugeAssert(t, openConnectionsName, 1), }, { name: tlsCertsNotAfterTimestampName, labels: map[string]string{ "cn": "value", "serial": "value", "sans": "value", }, assert: buildTimestampAssert(t, tlsCertsNotAfterTimestampName), }, { name: entryPointReqsTotalName, labels: map[string]string{ "code": "200", "method": http.MethodGet, "protocol": "http", "entrypoint": "http", "useragent": "foobar", }, assert: buildCounterAssert(t, entryPointReqsTotalName, 1), }, { name: entryPointReqDurationName, labels: map[string]string{ "code": "200", "method": http.MethodGet, "protocol": "http", "entrypoint": "http", }, assert: buildHistogramAssert(t, entryPointReqDurationName, 1), }, { name: entryPointReqsBytesTotalName, labels: map[string]string{ "code": "200", "method": http.MethodGet, "protocol": "http", "entrypoint": "http", }, assert: buildCounterAssert(t, entryPointReqsBytesTotalName, 1), }, { name: entryPointRespsBytesTotalName, labels: map[string]string{ "code": "200", "method": http.MethodGet, "protocol": "http", "entrypoint": "http", }, assert: buildCounterAssert(t, entryPointRespsBytesTotalName, 1), }, { name: routerReqsTotalName, labels: map[string]string{ "code": "200", "method": http.MethodGet, "protocol": "http", "service": "service1", "router": "demo", "useragent": "", }, assert: buildCounterAssert(t, routerReqsTotalName, 1), }, { name: routerReqsTLSTotalName, labels: map[string]string{ "service": "service1", "router": "demo", "tls_version": "foo", "tls_cipher": "bar", }, assert: buildCounterAssert(t, routerReqsTLSTotalName, 1), }, { name: routerReqDurationName, labels: map[string]string{ "code": "200", "method": http.MethodGet, "protocol": "http", "service": "service1", "router": "demo", }, assert: buildHistogramAssert(t, routerReqDurationName, 1), }, { name: routerReqsBytesTotalName, labels: map[string]string{ "code": "200", "method": http.MethodGet, "protocol": "http", "service": "service1", "router": "demo", }, assert: buildCounterAssert(t, routerReqsBytesTotalName, 1), }, { name: routerRespsBytesTotalName, labels: map[string]string{ "code": "200", "method": http.MethodGet, "protocol": "http", "service": "service1", "router": "demo", }, assert: buildCounterAssert(t, routerRespsBytesTotalName, 1), }, { name: serviceReqsTotalName, labels: map[string]string{ "code": "200", "method": http.MethodGet, "protocol": "http", "service": "service1", "useragent": "foobar", }, assert: buildCounterAssert(t, serviceReqsTotalName, 1), }, { name: serviceReqsTLSTotalName, labels: map[string]string{ "service": "service1", "tls_version": "foo", "tls_cipher": "bar", }, assert: buildCounterAssert(t, serviceReqsTLSTotalName, 1), }, { name: serviceReqDurationName, labels: map[string]string{ "code": "200", "method": http.MethodGet, "protocol": "http", "service": "service1", }, assert: buildHistogramAssert(t, serviceReqDurationName, 1), }, { name: serviceRetriesTotalName, labels: map[string]string{ "service": "service1", }, assert: buildGreaterThanCounterAssert(t, serviceRetriesTotalName, 1), }, { name: serviceServerUpName, labels: map[string]string{ "service": "service1", "url": "http://127.0.0.10:80", }, assert: buildGaugeAssert(t, serviceServerUpName, 1), }, { name: serviceReqsBytesTotalName, labels: map[string]string{ "code": "200", "method": http.MethodGet, "protocol": "http", "service": "service1", }, assert: buildCounterAssert(t, serviceReqsBytesTotalName, 1), }, { name: serviceRespsBytesTotalName, labels: map[string]string{ "code": "200", "method": http.MethodGet, "protocol": "http", "service": "service1", }, assert: buildCounterAssert(t, serviceRespsBytesTotalName, 1), }, } for _, test := range testCases { t.Run(test.name, func(t *testing.T) { family := findMetricFamily(test.name, metricsFamilies) if family == nil { t.Errorf("gathered metrics do not contain %q", test.name) return } for _, label := range family.GetMetric()[0].GetLabel() { val, ok := test.labels[label.GetName()] if !ok { t.Errorf("%q metric contains unexpected label %q", test.name, label.GetName()) } else if val != label.GetValue() { t.Errorf("label %q in metric %q has wrong value %q, expected %q", label.GetName(), test.name, label.GetValue(), val) } } test.assert(family) }) } } func TestPrometheusMetricRemoval(t *testing.T) { promState = newPrometheusState() promRegistry = prometheus.NewRegistry() t.Cleanup(promState.reset) prometheusRegistry := RegisterPrometheus(t.Context(), &otypes.Prometheus{AddEntryPointsLabels: true, AddServicesLabels: true, AddRoutersLabels: true}) defer promRegistry.Unregister(promState) conf1 := dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters( th.WithRouter("foo@providerName", th.WithServiceName("bar")), th.WithRouter("router2", th.WithServiceName("bar@providerName")), ), th.WithLoadBalancerServices( th.WithService("bar@providerName", th.WithServers( th.WithServer("http://localhost:9000"), th.WithServer("http://localhost:9999"), th.WithServer("http://localhost:9998"), )), th.WithService("service1", th.WithServers(th.WithServer("http://localhost:9000"))), ), ), } conf2 := dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithRouters( th.WithRouter("foo@providerName", th.WithServiceName("bar")), ), th.WithLoadBalancerServices( th.WithService("bar@providerName", th.WithServers(th.WithServer("http://localhost:9000"))), ), ), } OnConfigurationUpdate(conf1, []string{"entrypoint1", "entrypoint2"}) OnConfigurationUpdate(conf2, []string{"entrypoint1"}) // Register some metrics manually that are not part of the active configuration. // Those metrics should be part of the /metrics output on the first scrape but // should be removed after that scrape. prometheusRegistry. EntryPointReqsCounter(). With(nil, "entrypoint", "entrypoint2", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet, "protocol", "http"). Add(1) prometheusRegistry. RouterReqsCounter(). With(nil, "router", "router2", "service", "bar@providerName", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet, "protocol", "http"). Add(1) prometheusRegistry. ServiceReqsCounter(). With(nil, "service", "service1", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet, "protocol", "http"). Add(1) prometheusRegistry. ServiceServerUpGauge(). With("service", "bar@providerName", "url", "http://localhost:9999"). Set(1) prometheusRegistry. ServiceServerUpGauge(). With("service", "bar@providerName", "url", "http://localhost:9998"). Set(1) assertMetricsExist(t, mustScrape(), entryPointReqsTotalName, routerReqsTotalName, serviceReqsTotalName, serviceServerUpName) assertMetricsAbsent(t, mustScrape(), entryPointReqsTotalName, routerReqsTotalName, serviceReqsTotalName, serviceServerUpName) // To verify that metrics belonging to active configurations are not removed // here the counter examples. prometheusRegistry. EntryPointReqsCounter(). With(nil, "entrypoint", "entrypoint1", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet, "protocol", "http"). Add(1) prometheusRegistry. RouterReqsCounter(). With(nil, "router", "foo@providerName", "service", "bar", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet, "protocol", "http"). Add(1) prometheusRegistry. ServiceReqsCounter(). With(nil, "service", "bar@providerName", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet, "protocol", "http"). Add(1) prometheusRegistry. ServiceServerUpGauge(). With("service", "bar@providerName", "url", "http://localhost:9000"). Set(1) delayForTrackingCompletion() assertMetricsExist(t, mustScrape(), entryPointReqsTotalName, serviceReqsTotalName, serviceServerUpName, routerReqsTotalName) assertMetricsExist(t, mustScrape(), entryPointReqsTotalName, serviceReqsTotalName, serviceServerUpName, routerReqsTotalName) } func TestPrometheusMetricRemoveEndpointForRecoveredService(t *testing.T) { promState = newPrometheusState() promRegistry = prometheus.NewRegistry() t.Cleanup(promState.reset) prometheusRegistry := RegisterPrometheus(t.Context(), &otypes.Prometheus{AddServicesLabels: true}) defer promRegistry.Unregister(promState) conf1 := dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithLoadBalancerServices( th.WithService("service1", th.WithServers(th.WithServer("http://localhost:9000"))), ), ), } conf2 := dynamic.Configuration{ HTTP: th.BuildConfiguration(), } conf3 := dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithLoadBalancerServices( th.WithService("service1", th.WithServers(th.WithServer("http://localhost:9001"))), ), ), } OnConfigurationUpdate(conf1, []string{}) OnConfigurationUpdate(conf2, []string{}) OnConfigurationUpdate(conf3, []string{}) prometheusRegistry. ServiceServerUpGauge(). With("service", "service1", "url", "http://localhost:9000"). Add(1) assertMetricsExist(t, mustScrape(), serviceServerUpName) assertMetricsAbsent(t, mustScrape(), serviceServerUpName) } func TestPrometheusRemovedMetricsReset(t *testing.T) { t.Cleanup(promState.reset) prometheusRegistry := RegisterPrometheus(t.Context(), &otypes.Prometheus{AddEntryPointsLabels: true, AddServicesLabels: true}) defer promRegistry.Unregister(promState) conf1 := dynamic.Configuration{ HTTP: th.BuildConfiguration( th.WithLoadBalancerServices(th.WithService("service", th.WithServers(th.WithServer("http://localhost:9000"))), ), ), } OnConfigurationUpdate(conf1, []string{"entrypoint1", "entrypoint2"}) OnConfigurationUpdate(dynamic.Configuration{}, nil) labelNamesValues := []string{ "service", "service", "code", strconv.Itoa(http.StatusOK), "method", http.MethodGet, "protocol", "http", } prometheusRegistry. ServiceReqsCounter(). With(nil, labelNamesValues...). Add(3) delayForTrackingCompletion() metricsFamilies := mustScrape() assertCounterValue(t, 3, findMetricFamily(serviceReqsTotalName, metricsFamilies), labelNamesValues...) // There is no dynamic configuration and so this metric will be deleted // after the first scrape. assertMetricsAbsent(t, mustScrape(), serviceReqsTotalName) prometheusRegistry. ServiceReqsCounter(). With(nil, labelNamesValues...). Add(1) delayForTrackingCompletion() metricsFamilies = mustScrape() assertCounterValue(t, 1, findMetricFamily(serviceReqsTotalName, metricsFamilies), labelNamesValues...) } // reset is a utility method for unit testing. // It should be called after each test run that changes promState internally // in order to avoid dependencies between unit tests. func (ps *prometheusState) reset() { ps.dynamicConfig = newDynamicConfig() ps.vectors = nil ps.deletedEP = nil ps.deletedRouters = nil ps.deletedServices = nil ps.deletedURLs = make(map[string][]string) } // Tracking and gathering the metrics happens concurrently. // In practice this is no problem, because in case a tracked metric would miss the current scrape, // it would just be there in the next one. // That we can test reliably the tracking of all metrics here, // we sleep for a short amount of time, // to make sure the metric will be present in the next scrape. func delayForTrackingCompletion() { time.Sleep(250 * time.Millisecond) } func mustScrape() []*dto.MetricFamily { families, err := promRegistry.Gather() if err != nil { panic(fmt.Sprintf("could not gather metrics families: %s", err)) } return families } func assertMetricsExist(t *testing.T, families []*dto.MetricFamily, metricNames ...string) { t.Helper() for _, metricName := range metricNames { if findMetricFamily(metricName, families) == nil { t.Errorf("gathered metrics should contain %q", metricName) } } } func assertMetricsAbsent(t *testing.T, families []*dto.MetricFamily, metricNames ...string) { t.Helper() for _, metricName := range metricNames { if findMetricFamily(metricName, families) != nil { t.Errorf("gathered metrics should not contain %q", metricName) } } } func findMetricFamily(name string, families []*dto.MetricFamily) *dto.MetricFamily { for _, family := range families { if family.GetName() == name { return family } } return nil } func findMetricByLabelNamesValues(family *dto.MetricFamily, labelNamesValues ...string) *dto.Metric { if family == nil { return nil } for _, metric := range family.GetMetric() { if hasMetricAllLabelPairs(metric, labelNamesValues...) { return metric } } return nil } func hasMetricAllLabelPairs(metric *dto.Metric, labelNamesValues ...string) bool { for i := 0; i < len(labelNamesValues); i += 2 { name, val := labelNamesValues[i], labelNamesValues[i+1] if !hasMetricLabelPair(metric, name, val) { return false } } return true } func hasMetricLabelPair(metric *dto.Metric, labelName, labelValue string) bool { for _, labelPair := range metric.GetLabel() { if labelPair.GetName() == labelName && labelPair.GetValue() == labelValue { return true } } return false } func assertCounterValue(t *testing.T, want float64, family *dto.MetricFamily, labelNamesValues ...string) { t.Helper() metric := findMetricByLabelNamesValues(family, labelNamesValues...) if metric == nil { t.Error("metric must not be nil") return } if metric.GetCounter() == nil { t.Errorf("metric %s must be a counter", family.GetName()) return } if cv := metric.GetCounter().GetValue(); cv != want { t.Errorf("metric %s has value %v, want %v", family.GetName(), cv, want) } } func buildCounterAssert(t *testing.T, metricName string, expectedValue int) func(family *dto.MetricFamily) { t.Helper() return func(family *dto.MetricFamily) { if cv := int(family.GetMetric()[0].GetCounter().GetValue()); cv != expectedValue { t.Errorf("metric %s has value %d, want %d", metricName, cv, expectedValue) } } } func buildGreaterThanCounterAssert(t *testing.T, metricName string, expectedMinValue int) func(family *dto.MetricFamily) { t.Helper() return func(family *dto.MetricFamily) { if cv := int(family.GetMetric()[0].GetCounter().GetValue()); cv < expectedMinValue { t.Errorf("metric %s has value %d, want at least %d", metricName, cv, expectedMinValue) } } } func buildHistogramAssert(t *testing.T, metricName string, expectedSampleCount int) func(family *dto.MetricFamily) { t.Helper() return func(family *dto.MetricFamily) { if sc := int(family.GetMetric()[0].GetHistogram().GetSampleCount()); sc != expectedSampleCount { t.Errorf("metric %s has sample count value %d, want %d", metricName, sc, expectedSampleCount) } } } func buildGaugeAssert(t *testing.T, metricName string, expectedValue int) func(family *dto.MetricFamily) { t.Helper() return func(family *dto.MetricFamily) { if gv := int(family.GetMetric()[0].GetGauge().GetValue()); gv != expectedValue { t.Errorf("metric %s has value %d, want %d", metricName, gv, expectedValue) } } } func buildTimestampAssert(t *testing.T, metricName string) func(family *dto.MetricFamily) { t.Helper() return func(family *dto.MetricFamily) { if ts := time.Unix(int64(family.GetMetric()[0].GetGauge().GetValue()), 0); time.Since(ts) > time.Minute { t.Errorf("metric %s has wrong timestamp %v", metricName, ts) } } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/metrics/otel.go
pkg/observability/metrics/otel.go
package metrics import ( "context" "fmt" "net" "net/url" "strings" "sync" "time" "github.com/go-kit/kit/metrics" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/observability" otypes "github.com/traefik/traefik/v3/pkg/observability/types" "github.com/traefik/traefik/v3/pkg/types" "github.com/traefik/traefik/v3/pkg/version" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc" "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp" "go.opentelemetry.io/otel/metric" sdkmetric "go.opentelemetry.io/otel/sdk/metric" "go.opentelemetry.io/otel/sdk/resource" semconv "go.opentelemetry.io/otel/semconv/v1.37.0" "go.opentelemetry.io/otel/semconv/v1.37.0/httpconv" "google.golang.org/grpc/credentials" "google.golang.org/grpc/encoding/gzip" ) var ( openTelemetryMeterProvider *sdkmetric.MeterProvider openTelemetryGaugeCollector *gaugeCollector ) // SetMeterProvider sets the meter provider for the tests. func SetMeterProvider(meterProvider *sdkmetric.MeterProvider) { openTelemetryMeterProvider = meterProvider otel.SetMeterProvider(meterProvider) } // SemConvMetricsRegistry holds stables semantic conventions metric instruments. type SemConvMetricsRegistry struct { // server metrics httpServerRequestDuration httpconv.ServerRequestDuration // client metrics httpClientRequestDuration httpconv.ClientRequestDuration } // NewSemConvMetricRegistry registers all stables semantic conventions metrics. func NewSemConvMetricRegistry(ctx context.Context, config *otypes.OTLP) (*SemConvMetricsRegistry, error) { if err := observability.EnsureUserEnvVar(); err != nil { return nil, err } if openTelemetryMeterProvider == nil { var err error if openTelemetryMeterProvider, err = newOpenTelemetryMeterProvider(ctx, config); err != nil { log.Ctx(ctx).Err(err).Msg("Unable to create OpenTelemetry meter provider") return nil, nil } } meter := otel.Meter("github.com/traefik/traefik", metric.WithInstrumentationVersion(version.Version)) httpServerRequestDuration, err := httpconv.NewServerRequestDuration(meter, metric.WithExplicitBucketBoundaries(config.ExplicitBoundaries...)) if err != nil { return nil, fmt.Errorf("can't build httpServerRequestDuration histogram: %w", err) } httpClientRequestDuration, err := httpconv.NewClientRequestDuration(meter, metric.WithExplicitBucketBoundaries(config.ExplicitBoundaries...)) if err != nil { return nil, fmt.Errorf("can't build httpClientRequestDuration histogram: %w", err) } return &SemConvMetricsRegistry{ httpServerRequestDuration: httpServerRequestDuration, httpClientRequestDuration: httpClientRequestDuration, }, nil } // HTTPServerRequestDuration returns the HTTP server request duration histogram. func (s *SemConvMetricsRegistry) HTTPServerRequestDuration() httpconv.ServerRequestDuration { if s == nil { return httpconv.ServerRequestDuration{} } return s.httpServerRequestDuration } // HTTPClientRequestDuration returns the HTTP client request duration histogram. func (s *SemConvMetricsRegistry) HTTPClientRequestDuration() httpconv.ClientRequestDuration { if s == nil { return httpconv.ClientRequestDuration{} } return s.httpClientRequestDuration } // RegisterOpenTelemetry registers all OpenTelemetry metrics. func RegisterOpenTelemetry(ctx context.Context, config *otypes.OTLP) Registry { if openTelemetryMeterProvider == nil { var err error if openTelemetryMeterProvider, err = newOpenTelemetryMeterProvider(ctx, config); err != nil { log.Ctx(ctx).Err(err).Msg("Unable to create OpenTelemetry meter provider") return nil } } if openTelemetryGaugeCollector == nil { openTelemetryGaugeCollector = newOpenTelemetryGaugeCollector() } meter := otel.Meter("github.com/traefik/traefik", metric.WithInstrumentationVersion(version.Version)) reg := &standardRegistry{ epEnabled: config.AddEntryPointsLabels, routerEnabled: config.AddRoutersLabels, svcEnabled: config.AddServicesLabels, configReloadsCounter: newOTLPCounterFrom(meter, configReloadsTotalName, "Config reloads"), lastConfigReloadSuccessGauge: newOTLPGaugeFrom(meter, configLastReloadSuccessName, "Last config reload success", "ms"), openConnectionsGauge: newOTLPGaugeFrom(meter, openConnectionsName, "How many open connections exist, by entryPoint and protocol", "1"), tlsCertsNotAfterTimestampGauge: newOTLPGaugeFrom(meter, tlsCertsNotAfterTimestampName, "Certificate expiration timestamp", "s"), } if config.AddEntryPointsLabels { reg.entryPointReqsCounter = NewCounterWithNoopHeaders(newOTLPCounterFrom(meter, entryPointReqsTotalName, "How many HTTP requests processed on an entrypoint, partitioned by status code, protocol, and method.")) reg.entryPointReqsTLSCounter = newOTLPCounterFrom(meter, entryPointReqsTLSTotalName, "How many HTTP requests with TLS processed on an entrypoint, partitioned by TLS Version and TLS cipher Used.") reg.entryPointReqDurationHistogram, _ = NewHistogramWithScale(newOTLPHistogramFrom(meter, entryPointReqDurationName, "How long it took to process the request on an entrypoint, partitioned by status code, protocol, and method.", "s"), time.Second) reg.entryPointReqsBytesCounter = newOTLPCounterFrom(meter, entryPointReqsBytesTotalName, "The total size of requests in bytes handled by an entrypoint, partitioned by status code, protocol, and method.") reg.entryPointRespsBytesCounter = newOTLPCounterFrom(meter, entryPointRespsBytesTotalName, "The total size of responses in bytes handled by an entrypoint, partitioned by status code, protocol, and method.") } if config.AddRoutersLabels { reg.routerReqsCounter = NewCounterWithNoopHeaders(newOTLPCounterFrom(meter, routerReqsTotalName, "How many HTTP requests are processed on a router, partitioned by service, status code, protocol, and method.")) reg.routerReqsTLSCounter = newOTLPCounterFrom(meter, routerReqsTLSTotalName, "How many HTTP requests with TLS are processed on a router, partitioned by service, TLS Version, and TLS cipher Used.") reg.routerReqDurationHistogram, _ = NewHistogramWithScale(newOTLPHistogramFrom(meter, routerReqDurationName, "How long it took to process the request on a router, partitioned by service, status code, protocol, and method.", "s"), time.Second) reg.routerReqsBytesCounter = newOTLPCounterFrom(meter, routerReqsBytesTotalName, "The total size of requests in bytes handled by a router, partitioned by status code, protocol, and method.") reg.routerRespsBytesCounter = newOTLPCounterFrom(meter, routerRespsBytesTotalName, "The total size of responses in bytes handled by a router, partitioned by status code, protocol, and method.") } if config.AddServicesLabels { reg.serviceReqsCounter = NewCounterWithNoopHeaders(newOTLPCounterFrom(meter, serviceReqsTotalName, "How many HTTP requests processed on a service, partitioned by status code, protocol, and method.")) reg.serviceReqsTLSCounter = newOTLPCounterFrom(meter, serviceReqsTLSTotalName, "How many HTTP requests with TLS processed on a service, partitioned by TLS version and TLS cipher.") reg.serviceReqDurationHistogram, _ = NewHistogramWithScale(newOTLPHistogramFrom(meter, serviceReqDurationName, "How long it took to process the request on a service, partitioned by status code, protocol, and method.", "s"), time.Second) reg.serviceRetriesCounter = newOTLPCounterFrom(meter, serviceRetriesTotalName, "How many request retries happened on a service.") reg.serviceServerUpGauge = newOTLPGaugeFrom(meter, serviceServerUpName, "service server is up, described by gauge value of 0 or 1.", "1") reg.serviceReqsBytesCounter = newOTLPCounterFrom(meter, serviceReqsBytesTotalName, "The total size of requests in bytes received by a service, partitioned by status code, protocol, and method.") reg.serviceRespsBytesCounter = newOTLPCounterFrom(meter, serviceRespsBytesTotalName, "The total size of responses in bytes returned by a service, partitioned by status code, protocol, and method.") } return reg } // StopOpenTelemetry stops and resets Open-Telemetry client. func StopOpenTelemetry() { if openTelemetryMeterProvider == nil { return } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := openTelemetryMeterProvider.Shutdown(ctx); err != nil { log.Err(err).Msg("Unable to shutdown OpenTelemetry meter provider") } openTelemetryMeterProvider = nil } // newOpenTelemetryMeterProvider creates a new controller.Controller. func newOpenTelemetryMeterProvider(ctx context.Context, config *otypes.OTLP) (*sdkmetric.MeterProvider, error) { var ( exporter sdkmetric.Exporter err error ) if config.GRPC != nil { exporter, err = newGRPCExporter(ctx, config.GRPC) } else { exporter, err = newHTTPExporter(ctx, config.HTTP) } if err != nil { return nil, fmt.Errorf("creating exporter: %w", err) } var resAttrs []attribute.KeyValue for k, v := range config.ResourceAttributes { resAttrs = append(resAttrs, attribute.String(k, v)) } res, err := resource.New(ctx, resource.WithContainer(), resource.WithHost(), resource.WithOS(), resource.WithProcess(), resource.WithTelemetrySDK(), resource.WithDetectors(types.K8sAttributesDetector{}), // The following order allows the user to override the service name and version, // as well as any other attributes set by the above detectors. resource.WithAttributes( semconv.ServiceName(config.ServiceName), semconv.ServiceVersion(version.Version), ), resource.WithAttributes(resAttrs...), // Use the environment variables to allow overriding above resource attributes. resource.WithFromEnv(), ) if err != nil { return nil, fmt.Errorf("building resource: %w", err) } opts := []sdkmetric.PeriodicReaderOption{ sdkmetric.WithInterval(time.Duration(config.PushInterval)), } meterProvider := sdkmetric.NewMeterProvider( sdkmetric.WithResource(res), sdkmetric.WithReader(sdkmetric.NewPeriodicReader(exporter, opts...)), // View to customize histogram buckets and rename a single histogram instrument. sdkmetric.WithView(sdkmetric.NewView( sdkmetric.Instrument{Name: "traefik_*_request_duration_seconds"}, sdkmetric.Stream{Aggregation: sdkmetric.AggregationExplicitBucketHistogram{ Boundaries: config.ExplicitBoundaries, }}, )), ) otel.SetMeterProvider(meterProvider) return meterProvider, nil } func newHTTPExporter(ctx context.Context, config *otypes.OTelHTTP) (sdkmetric.Exporter, error) { endpoint, err := url.Parse(config.Endpoint) if err != nil { return nil, fmt.Errorf("invalid collector endpoint %q: %w", config.Endpoint, err) } opts := []otlpmetrichttp.Option{ otlpmetrichttp.WithEndpoint(endpoint.Host), otlpmetrichttp.WithHeaders(config.Headers), otlpmetrichttp.WithCompression(otlpmetrichttp.GzipCompression), } if endpoint.Scheme == "http" { opts = append(opts, otlpmetrichttp.WithInsecure()) } if endpoint.Path != "" { opts = append(opts, otlpmetrichttp.WithURLPath(endpoint.Path)) } if config.TLS != nil { tlsConfig, err := config.TLS.CreateTLSConfig(ctx) if err != nil { return nil, fmt.Errorf("creating TLS client config: %w", err) } opts = append(opts, otlpmetrichttp.WithTLSClientConfig(tlsConfig)) } return otlpmetrichttp.New(ctx, opts...) } func newGRPCExporter(ctx context.Context, config *otypes.OTelGRPC) (sdkmetric.Exporter, error) { host, port, err := net.SplitHostPort(config.Endpoint) if err != nil { return nil, fmt.Errorf("invalid collector endpoint %q: %w", config.Endpoint, err) } opts := []otlpmetricgrpc.Option{ otlpmetricgrpc.WithEndpoint(fmt.Sprintf("%s:%s", host, port)), otlpmetricgrpc.WithHeaders(config.Headers), otlpmetricgrpc.WithCompressor(gzip.Name), } if config.Insecure { opts = append(opts, otlpmetricgrpc.WithInsecure()) } if config.TLS != nil { tlsConfig, err := config.TLS.CreateTLSConfig(ctx) if err != nil { return nil, fmt.Errorf("creating TLS client config: %w", err) } opts = append(opts, otlpmetricgrpc.WithTLSCredentials(credentials.NewTLS(tlsConfig))) } return otlpmetricgrpc.New(ctx, opts...) } func newOTLPCounterFrom(meter metric.Meter, name, desc string) *otelCounter { c, _ := meter.Float64Counter(name, metric.WithDescription(desc), metric.WithUnit("1"), ) return &otelCounter{ ip: c, } } type otelCounter struct { labelNamesValues otelLabelNamesValues ip metric.Float64Counter } func (c *otelCounter) With(labelValues ...string) metrics.Counter { return &otelCounter{ labelNamesValues: c.labelNamesValues.With(labelValues...), ip: c.ip, } } func (c *otelCounter) Add(delta float64) { c.ip.Add(context.Background(), delta, metric.WithAttributes(c.labelNamesValues.ToLabels()...)) } type gaugeValue struct { attributes otelLabelNamesValues value float64 } type gaugeCollector struct { mu sync.Mutex values map[string]map[string]gaugeValue } func newOpenTelemetryGaugeCollector() *gaugeCollector { return &gaugeCollector{ values: make(map[string]map[string]gaugeValue), } } func (c *gaugeCollector) add(name string, delta float64, attributes otelLabelNamesValues) { c.mu.Lock() defer c.mu.Unlock() str := strings.Join(attributes, "") if _, exists := c.values[name]; !exists { c.values[name] = map[string]gaugeValue{ str: { attributes: attributes, value: delta, }, } return } v, exists := c.values[name][str] if !exists { c.values[name][str] = gaugeValue{ attributes: attributes, value: delta, } return } c.values[name][str] = gaugeValue{ attributes: attributes, value: v.value + delta, } } func (c *gaugeCollector) set(name string, value float64, attributes otelLabelNamesValues) { c.mu.Lock() defer c.mu.Unlock() if _, exists := c.values[name]; !exists { c.values[name] = make(map[string]gaugeValue) } c.values[name][strings.Join(attributes, "")] = gaugeValue{ attributes: attributes, value: value, } } func newOTLPGaugeFrom(meter metric.Meter, name, desc string, unit string) *otelGauge { openTelemetryGaugeCollector.values[name] = make(map[string]gaugeValue) c, _ := meter.Float64ObservableGauge(name, metric.WithDescription(desc), metric.WithUnit(unit), ) _, err := meter.RegisterCallback(func(ctx context.Context, observer metric.Observer) error { openTelemetryGaugeCollector.mu.Lock() defer openTelemetryGaugeCollector.mu.Unlock() values, exists := openTelemetryGaugeCollector.values[name] if !exists { return nil } for _, value := range values { observer.ObserveFloat64(c, value.value, metric.WithAttributes(value.attributes.ToLabels()...)) } return nil }, c) if err != nil { log.Err(err).Msg("Unable to register OpenTelemetry meter callback") } return &otelGauge{ ip: c, name: name, } } type otelGauge struct { labelNamesValues otelLabelNamesValues ip metric.Float64ObservableGauge name string } func (g *otelGauge) With(labelValues ...string) metrics.Gauge { return &otelGauge{ labelNamesValues: g.labelNamesValues.With(labelValues...), ip: g.ip, name: g.name, } } func (g *otelGauge) Add(delta float64) { openTelemetryGaugeCollector.add(g.name, delta, g.labelNamesValues) } func (g *otelGauge) Set(value float64) { openTelemetryGaugeCollector.set(g.name, value, g.labelNamesValues) } func newOTLPHistogramFrom(meter metric.Meter, name, desc string, unit string) *otelHistogram { c, _ := meter.Float64Histogram(name, metric.WithDescription(desc), metric.WithUnit(unit), ) return &otelHistogram{ ip: c, } } type otelHistogram struct { labelNamesValues otelLabelNamesValues ip metric.Float64Histogram } func (h *otelHistogram) With(labelValues ...string) metrics.Histogram { return &otelHistogram{ labelNamesValues: h.labelNamesValues.With(labelValues...), ip: h.ip, } } func (h *otelHistogram) Observe(incr float64) { h.ip.Record(context.Background(), incr, metric.WithAttributes(h.labelNamesValues.ToLabels()...)) } // otelLabelNamesValues is the equivalent of prometheus' labelNamesValues // but adapted to OpenTelemetry. // otelLabelNamesValues is a type alias that provides validation on its With // method. // Metrics may include it as a member to help them satisfy With semantics and // save some code duplication. type otelLabelNamesValues []string // With validates the input, and returns a new aggregate otelLabelNamesValues. func (lvs otelLabelNamesValues) With(labelValues ...string) otelLabelNamesValues { if len(labelValues)%2 != 0 { labelValues = append(labelValues, "unknown") } return append(lvs, labelValues...) } // ToLabels is a convenience method to convert a otelLabelNamesValues // to the native attribute.KeyValue. func (lvs otelLabelNamesValues) ToLabels() []attribute.KeyValue { labels := make([]attribute.KeyValue, len(lvs)/2) for i := 0; i < len(labels); i++ { labels[i] = attribute.String(lvs[2*i], lvs[2*i+1]) } return labels }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/metrics/metrics_test.go
pkg/observability/metrics/metrics_test.go
package metrics import ( "bytes" "net/http" "strings" "testing" "time" "github.com/go-kit/kit/metrics" "github.com/go-kit/kit/metrics/generic" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestScalableHistogram(t *testing.T) { h := generic.NewHistogram("test", 1) sh, err := NewHistogramWithScale(h, time.Millisecond) require.NoError(t, err) ticker := time.NewTicker(500 * time.Millisecond) <-ticker.C start := time.Now() <-ticker.C sh.ObserveFromStart(start) var b bytes.Buffer h.Print(&b) extractedDurationString := strings.Split(strings.Split(b.String(), "\n")[1], " ") measuredDuration, err := time.ParseDuration(extractedDurationString[0] + "ms") assert.NoError(t, err) assert.InDelta(t, 500*time.Millisecond, measuredDuration, float64(15*time.Millisecond)) } func TestNewMultiRegistry(t *testing.T) { registries := []Registry{newCollectingRetryMetrics(), newCollectingRetryMetrics()} registry := NewMultiRegistry(registries) registry.ServiceReqsCounter().With(nil, "key", "requests").Add(1) registry.ServiceReqDurationHistogram().With("key", "durations").Observe(float64(2)) registry.ServiceRetriesCounter().With("key", "retries").Add(3) for _, collectingRegistry := range registries { cReqsCounter := collectingRegistry.ServiceReqsCounter().(*counterWithHeadersMock) cReqDurationHistogram := collectingRegistry.ServiceReqDurationHistogram().(*histogramMock) cRetriesCounter := collectingRegistry.ServiceRetriesCounter().(*counterMock) wantCounterValue := float64(1) if cReqsCounter.counterValue != wantCounterValue { t.Errorf("Got value %f for ReqsCounter, want %f", cReqsCounter.counterValue, wantCounterValue) } wantHistogramValue := float64(2) if cReqDurationHistogram.lastHistogramValue != wantHistogramValue { t.Errorf("Got last observation %f for ReqDurationHistogram, want %f", cReqDurationHistogram.lastHistogramValue, wantHistogramValue) } wantCounterValue = float64(3) if cRetriesCounter.counterValue != wantCounterValue { t.Errorf("Got value %f for RetriesCounter, want %f", cRetriesCounter.counterValue, wantCounterValue) } assert.Equal(t, []string{"key", "requests"}, cReqsCounter.lastLabelValues) assert.Equal(t, []string{"key", "durations"}, cReqDurationHistogram.lastLabelValues) assert.Equal(t, []string{"key", "retries"}, cRetriesCounter.lastLabelValues) } } func newCollectingRetryMetrics() Registry { return &standardRegistry{ serviceReqsCounter: &counterWithHeadersMock{}, serviceReqDurationHistogram: &histogramMock{}, serviceRetriesCounter: &counterMock{}, } } type counterMock struct { counterValue float64 lastLabelValues []string } func (c *counterMock) With(labelValues ...string) metrics.Counter { c.lastLabelValues = labelValues return c } func (c *counterMock) Add(delta float64) { c.counterValue += delta } type counterWithHeadersMock struct { counterValue float64 lastLabelValues []string } func (c *counterWithHeadersMock) With(_ http.Header, labelValues ...string) CounterWithHeaders { c.lastLabelValues = labelValues return c } func (c *counterWithHeadersMock) Add(delta float64) { c.counterValue += delta } type histogramMock struct { lastHistogramValue float64 lastLabelValues []string } func (c *histogramMock) With(labelValues ...string) ScalableHistogram { c.lastLabelValues = labelValues return c } func (c *histogramMock) Start() {} func (c *histogramMock) ObserveFromStart(t time.Time) {} func (c *histogramMock) Observe(v float64) { c.lastHistogramValue = v }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/metrics/datadog.go
pkg/observability/metrics/datadog.go
package metrics import ( "context" "net" "strings" "time" "github.com/go-kit/kit/metrics/dogstatsd" "github.com/go-kit/kit/util/conn" gokitlog "github.com/go-kit/log" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/observability/logs" otypes "github.com/traefik/traefik/v3/pkg/observability/types" "github.com/traefik/traefik/v3/pkg/safe" ) const ( unixAddressPrefix = "unix://" unixAddressDatagramPrefix = "unixgram://" unixAddressStreamPrefix = "unixstream://" ) var ( datadogClient *dogstatsd.Dogstatsd datadogLoopCancelFunc context.CancelFunc ) // Metric names consistent with https://github.com/DataDog/integrations-extras/pull/64 const ( ddConfigReloadsName = "config.reload.total" ddLastConfigReloadSuccessName = "config.reload.lastSuccessTimestamp" ddOpenConnsName = "open.connections" ddTLSCertsNotAfterTimestampName = "tls.certs.notAfterTimestamp" ddEntryPointReqsName = "entrypoint.request.total" ddEntryPointReqsTLSName = "entrypoint.request.tls.total" ddEntryPointReqDurationName = "entrypoint.request.duration" ddEntryPointReqsBytesName = "entrypoint.requests.bytes.total" ddEntryPointRespsBytesName = "entrypoint.responses.bytes.total" ddRouterReqsName = "router.request.total" ddRouterReqsTLSName = "router.request.tls.total" ddRouterReqsDurationName = "router.request.duration" ddRouterReqsBytesName = "router.requests.bytes.total" ddRouterRespsBytesName = "router.responses.bytes.total" ddServiceReqsName = "service.request.total" ddServiceReqsTLSName = "service.request.tls.total" ddServiceReqsDurationName = "service.request.duration" ddServiceRetriesName = "service.retries.total" ddServiceServerUpName = "service.server.up" ddServiceReqsBytesName = "service.requests.bytes.total" ddServiceRespsBytesName = "service.responses.bytes.total" ) // RegisterDatadog registers the metrics pusher if this didn't happen yet and creates a datadog Registry instance. func RegisterDatadog(ctx context.Context, config *otypes.Datadog) Registry { // Ensures there is only one DataDog client sending metrics at any given time. StopDatadog() // just to be sure there is a prefix defined if config.Prefix == "" { config.Prefix = defaultMetricsPrefix } datadogLogger := logs.NewGoKitWrapper(log.Logger.With().Str(logs.MetricsProviderName, "datadog").Logger()) datadogClient = dogstatsd.New(config.Prefix+".", datadogLogger) initDatadogClient(ctx, config, datadogLogger) registry := &standardRegistry{ configReloadsCounter: datadogClient.NewCounter(ddConfigReloadsName, 1.0), lastConfigReloadSuccessGauge: datadogClient.NewGauge(ddLastConfigReloadSuccessName), openConnectionsGauge: datadogClient.NewGauge(ddOpenConnsName), tlsCertsNotAfterTimestampGauge: datadogClient.NewGauge(ddTLSCertsNotAfterTimestampName), } if config.AddEntryPointsLabels { registry.epEnabled = config.AddEntryPointsLabels registry.entryPointReqsCounter = NewCounterWithNoopHeaders(datadogClient.NewCounter(ddEntryPointReqsName, 1.0)) registry.entryPointReqsTLSCounter = datadogClient.NewCounter(ddEntryPointReqsTLSName, 1.0) registry.entryPointReqDurationHistogram, _ = NewHistogramWithScale(datadogClient.NewHistogram(ddEntryPointReqDurationName, 1.0), time.Second) registry.entryPointReqsBytesCounter = datadogClient.NewCounter(ddEntryPointReqsBytesName, 1.0) registry.entryPointRespsBytesCounter = datadogClient.NewCounter(ddEntryPointRespsBytesName, 1.0) } if config.AddRoutersLabels { registry.routerEnabled = config.AddRoutersLabels registry.routerReqsCounter = NewCounterWithNoopHeaders(datadogClient.NewCounter(ddRouterReqsName, 1.0)) registry.routerReqsTLSCounter = datadogClient.NewCounter(ddRouterReqsTLSName, 1.0) registry.routerReqDurationHistogram, _ = NewHistogramWithScale(datadogClient.NewHistogram(ddRouterReqsDurationName, 1.0), time.Second) registry.routerReqsBytesCounter = datadogClient.NewCounter(ddRouterReqsBytesName, 1.0) registry.routerRespsBytesCounter = datadogClient.NewCounter(ddRouterRespsBytesName, 1.0) } if config.AddServicesLabels { registry.svcEnabled = config.AddServicesLabels registry.serviceReqsCounter = NewCounterWithNoopHeaders(datadogClient.NewCounter(ddServiceReqsName, 1.0)) registry.serviceReqsTLSCounter = datadogClient.NewCounter(ddServiceReqsTLSName, 1.0) registry.serviceReqDurationHistogram, _ = NewHistogramWithScale(datadogClient.NewHistogram(ddServiceReqsDurationName, 1.0), time.Second) registry.serviceRetriesCounter = datadogClient.NewCounter(ddServiceRetriesName, 1.0) registry.serviceServerUpGauge = datadogClient.NewGauge(ddServiceServerUpName) registry.serviceReqsBytesCounter = datadogClient.NewCounter(ddServiceReqsBytesName, 1.0) registry.serviceRespsBytesCounter = datadogClient.NewCounter(ddServiceRespsBytesName, 1.0) } return registry } func initDatadogClient(ctx context.Context, config *otypes.Datadog, logger gokitlog.LoggerFunc) { network, address := parseDatadogAddress(config.Address) ctx, datadogLoopCancelFunc = context.WithCancel(ctx) safe.Go(func() { ticker := time.NewTicker(time.Duration(config.PushInterval)) defer ticker.Stop() dialer := func(network, address string) (net.Conn, error) { switch network { case "unix": // To mimic the Datadog client when the network is unix we will try to guess the UDS type. newConn, err := net.Dial("unixgram", address) if err != nil && strings.Contains(err.Error(), "protocol wrong type for socket") { return net.Dial("unix", address) } return newConn, err case "unixgram": return net.Dial("unixgram", address) case "unixstream": return net.Dial("unix", address) default: return net.Dial(network, address) } } datadogClient.WriteLoop(ctx, ticker.C, conn.NewManager(dialer, network, address, time.After, logger)) }) } // StopDatadog stops the Datadog metrics pusher. func StopDatadog() { if datadogLoopCancelFunc != nil { datadogLoopCancelFunc() datadogLoopCancelFunc = nil } } func parseDatadogAddress(address string) (string, string) { network := "udp" var addr string switch { case strings.HasPrefix(address, unixAddressPrefix): network = "unix" addr = address[len(unixAddressPrefix):] case strings.HasPrefix(address, unixAddressDatagramPrefix): network = "unixgram" addr = address[len(unixAddressDatagramPrefix):] case strings.HasPrefix(address, unixAddressStreamPrefix): network = "unixstream" addr = address[len(unixAddressStreamPrefix):] case address != "": addr = address default: addr = "localhost:8125" } return network, addr }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/metrics/headers.go
pkg/observability/metrics/headers.go
package metrics import ( "net/http" "github.com/go-kit/kit/metrics" ) // CounterWithHeaders represents a counter that can use http.Header values as label values. type CounterWithHeaders interface { Add(delta float64) With(headers http.Header, labelValues ...string) CounterWithHeaders } // MultiCounterWithHeaders collects multiple individual CounterWithHeaders and treats them as a unit. type MultiCounterWithHeaders []CounterWithHeaders // NewMultiCounterWithHeaders returns a multi-counter, wrapping the passed CounterWithHeaders. func NewMultiCounterWithHeaders(c ...CounterWithHeaders) MultiCounterWithHeaders { return c } // Add adds the given delta value to the counter value. func (c MultiCounterWithHeaders) Add(delta float64) { for _, counter := range c { counter.Add(delta) } } // With creates a new counter by appending the given label values and http.Header as labels and returns it. func (c MultiCounterWithHeaders) With(headers http.Header, labelValues ...string) CounterWithHeaders { next := make(MultiCounterWithHeaders, len(c)) for i := range c { next[i] = c[i].With(headers, labelValues...) } return next } // NewCounterWithNoopHeaders returns a CounterWithNoopHeaders. func NewCounterWithNoopHeaders(counter metrics.Counter) CounterWithNoopHeaders { return CounterWithNoopHeaders{counter: counter} } // CounterWithNoopHeaders is a counter that satisfies CounterWithHeaders but ignores the given http.Header. type CounterWithNoopHeaders struct { counter metrics.Counter } // Add adds the given delta value to the counter value. func (c CounterWithNoopHeaders) Add(delta float64) { c.counter.Add(delta) } // With creates a new counter by appending the given label values and returns it. func (c CounterWithNoopHeaders) With(_ http.Header, labelValues ...string) CounterWithHeaders { return NewCounterWithNoopHeaders(c.counter.With(labelValues...)) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/types/metrics.go
pkg/observability/types/metrics.go
package types import ( "net" "os" "time" "github.com/traefik/paerser/types" ) // Metrics provides options to expose and send Traefik metrics to different third party monitoring systems. type Metrics struct { AddInternals bool `description:"Enables metrics for internal services (ping, dashboard, etc...)." json:"addInternals,omitempty" toml:"addInternals,omitempty" yaml:"addInternals,omitempty" export:"true"` Prometheus *Prometheus `description:"Prometheus metrics exporter type." json:"prometheus,omitempty" toml:"prometheus,omitempty" yaml:"prometheus,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` Datadog *Datadog `description:"Datadog metrics exporter type." json:"datadog,omitempty" toml:"datadog,omitempty" yaml:"datadog,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` StatsD *Statsd `description:"StatsD metrics exporter type." json:"statsD,omitempty" toml:"statsD,omitempty" yaml:"statsD,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` InfluxDB2 *InfluxDB2 `description:"InfluxDB v2 metrics exporter type." json:"influxDB2,omitempty" toml:"influxDB2,omitempty" yaml:"influxDB2,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` OTLP *OTLP `description:"OpenTelemetry metrics exporter type." json:"otlp,omitempty" toml:"otlp,omitempty" yaml:"otlp,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` } // Prometheus can contain specific configuration used by the Prometheus Metrics exporter. type Prometheus struct { Buckets []float64 `description:"Buckets for latency metrics." json:"buckets,omitempty" toml:"buckets,omitempty" yaml:"buckets,omitempty" export:"true"` AddEntryPointsLabels bool `description:"Enable metrics on entry points." json:"addEntryPointsLabels,omitempty" toml:"addEntryPointsLabels,omitempty" yaml:"addEntryPointsLabels,omitempty" export:"true"` AddRoutersLabels bool `description:"Enable metrics on routers." json:"addRoutersLabels,omitempty" toml:"addRoutersLabels,omitempty" yaml:"addRoutersLabels,omitempty" export:"true"` AddServicesLabels bool `description:"Enable metrics on services." json:"addServicesLabels,omitempty" toml:"addServicesLabels,omitempty" yaml:"addServicesLabels,omitempty" export:"true"` EntryPoint string `description:"EntryPoint" json:"entryPoint,omitempty" toml:"entryPoint,omitempty" yaml:"entryPoint,omitempty" export:"true"` ManualRouting bool `description:"Manual routing" json:"manualRouting,omitempty" toml:"manualRouting,omitempty" yaml:"manualRouting,omitempty" export:"true"` HeaderLabels map[string]string `description:"Defines the extra labels for the requests_total metrics, and for each of them, the request header containing the value for this label." json:"headerLabels,omitempty" toml:"headerLabels,omitempty" yaml:"headerLabels,omitempty" export:"true"` } // SetDefaults sets the default values. func (p *Prometheus) SetDefaults() { p.Buckets = []float64{0.1, 0.3, 1.2, 5} p.AddEntryPointsLabels = true p.AddServicesLabels = true p.EntryPoint = "traefik" } // Datadog contains address and metrics pushing interval configuration. type Datadog struct { Address string `description:"Datadog's address." json:"address,omitempty" toml:"address,omitempty" yaml:"address,omitempty"` PushInterval types.Duration `description:"Datadog push interval." json:"pushInterval,omitempty" toml:"pushInterval,omitempty" yaml:"pushInterval,omitempty" export:"true"` AddEntryPointsLabels bool `description:"Enable metrics on entry points." json:"addEntryPointsLabels,omitempty" toml:"addEntryPointsLabels,omitempty" yaml:"addEntryPointsLabels,omitempty" export:"true"` AddRoutersLabels bool `description:"Enable metrics on routers." json:"addRoutersLabels,omitempty" toml:"addRoutersLabels,omitempty" yaml:"addRoutersLabels,omitempty" export:"true"` AddServicesLabels bool `description:"Enable metrics on services." json:"addServicesLabels,omitempty" toml:"addServicesLabels,omitempty" yaml:"addServicesLabels,omitempty" export:"true"` Prefix string `description:"Prefix to use for metrics collection." json:"prefix,omitempty" toml:"prefix,omitempty" yaml:"prefix,omitempty" export:"true"` } // SetDefaults sets the default values. func (d *Datadog) SetDefaults() { host, ok := os.LookupEnv("DD_AGENT_HOST") if !ok { host = "localhost" } port, ok := os.LookupEnv("DD_DOGSTATSD_PORT") if !ok { port = "8125" } d.Address = net.JoinHostPort(host, port) d.PushInterval = types.Duration(10 * time.Second) d.AddEntryPointsLabels = true d.AddServicesLabels = true d.Prefix = "traefik" } // Statsd contains address and metrics pushing interval configuration. type Statsd struct { Address string `description:"StatsD address." json:"address,omitempty" toml:"address,omitempty" yaml:"address,omitempty"` PushInterval types.Duration `description:"StatsD push interval." json:"pushInterval,omitempty" toml:"pushInterval,omitempty" yaml:"pushInterval,omitempty" export:"true"` AddEntryPointsLabels bool `description:"Enable metrics on entry points." json:"addEntryPointsLabels,omitempty" toml:"addEntryPointsLabels,omitempty" yaml:"addEntryPointsLabels,omitempty" export:"true"` AddRoutersLabels bool `description:"Enable metrics on routers." json:"addRoutersLabels,omitempty" toml:"addRoutersLabels,omitempty" yaml:"addRoutersLabels,omitempty" export:"true"` AddServicesLabels bool `description:"Enable metrics on services." json:"addServicesLabels,omitempty" toml:"addServicesLabels,omitempty" yaml:"addServicesLabels,omitempty" export:"true"` Prefix string `description:"Prefix to use for metrics collection." json:"prefix,omitempty" toml:"prefix,omitempty" yaml:"prefix,omitempty" export:"true"` } // SetDefaults sets the default values. func (s *Statsd) SetDefaults() { s.Address = "localhost:8125" s.PushInterval = types.Duration(10 * time.Second) s.AddEntryPointsLabels = true s.AddServicesLabels = true s.Prefix = "traefik" } // InfluxDB2 contains address, token and metrics pushing interval configuration. type InfluxDB2 struct { Address string `description:"InfluxDB v2 address." json:"address,omitempty" toml:"address,omitempty" yaml:"address,omitempty"` Token string `description:"InfluxDB v2 access token." json:"token,omitempty" toml:"token,omitempty" yaml:"token,omitempty" loggable:"false"` PushInterval types.Duration `description:"InfluxDB v2 push interval." json:"pushInterval,omitempty" toml:"pushInterval,omitempty" yaml:"pushInterval,omitempty" export:"true"` Org string `description:"InfluxDB v2 org ID." json:"org,omitempty" toml:"org,omitempty" yaml:"org,omitempty" export:"true"` Bucket string `description:"InfluxDB v2 bucket ID." json:"bucket,omitempty" toml:"bucket,omitempty" yaml:"bucket,omitempty" export:"true"` AddEntryPointsLabels bool `description:"Enable metrics on entry points." json:"addEntryPointsLabels,omitempty" toml:"addEntryPointsLabels,omitempty" yaml:"addEntryPointsLabels,omitempty" export:"true"` AddRoutersLabels bool `description:"Enable metrics on routers." json:"addRoutersLabels,omitempty" toml:"addRoutersLabels,omitempty" yaml:"addRoutersLabels,omitempty" export:"true"` AddServicesLabels bool `description:"Enable metrics on services." json:"addServicesLabels,omitempty" toml:"addServicesLabels,omitempty" yaml:"addServicesLabels,omitempty" export:"true"` AdditionalLabels map[string]string `description:"Additional labels (influxdb tags) on all metrics" json:"additionalLabels,omitempty" toml:"additionalLabels,omitempty" yaml:"additionalLabels,omitempty" export:"true"` } // SetDefaults sets the default values. func (i *InfluxDB2) SetDefaults() { i.Address = "http://localhost:8086" i.PushInterval = types.Duration(10 * time.Second) i.AddEntryPointsLabels = true i.AddServicesLabels = true } // OTLP contains specific configuration used by the OpenTelemetry Metrics exporter. type OTLP struct { GRPC *OTelGRPC `description:"gRPC configuration for the OpenTelemetry collector." json:"grpc,omitempty" toml:"grpc,omitempty" yaml:"grpc,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` HTTP *OTelHTTP `description:"HTTP configuration for the OpenTelemetry collector." json:"http,omitempty" toml:"http,omitempty" yaml:"http,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` AddEntryPointsLabels bool `description:"Enable metrics on entry points." json:"addEntryPointsLabels,omitempty" toml:"addEntryPointsLabels,omitempty" yaml:"addEntryPointsLabels,omitempty" export:"true"` AddRoutersLabels bool `description:"Enable metrics on routers." json:"addRoutersLabels,omitempty" toml:"addRoutersLabels,omitempty" yaml:"addRoutersLabels,omitempty" export:"true"` AddServicesLabels bool `description:"Enable metrics on services." json:"addServicesLabels,omitempty" toml:"addServicesLabels,omitempty" yaml:"addServicesLabels,omitempty" export:"true"` ExplicitBoundaries []float64 `description:"Boundaries for latency metrics." json:"explicitBoundaries,omitempty" toml:"explicitBoundaries,omitempty" yaml:"explicitBoundaries,omitempty" export:"true"` PushInterval types.Duration `description:"Period between calls to collect a checkpoint." json:"pushInterval,omitempty" toml:"pushInterval,omitempty" yaml:"pushInterval,omitempty" export:"true"` ServiceName string `description:"Defines the service name resource attribute." json:"serviceName,omitempty" toml:"serviceName,omitempty" yaml:"serviceName,omitempty" export:"true"` ResourceAttributes map[string]string `description:"Defines additional resource attributes (key:value)." json:"resourceAttributes,omitempty" toml:"resourceAttributes,omitempty" yaml:"resourceAttributes,omitempty" export:"true"` } // SetDefaults sets the default values. func (o *OTLP) SetDefaults() { o.HTTP = &OTelHTTP{} o.HTTP.SetDefaults() o.AddEntryPointsLabels = true o.AddServicesLabels = true o.ExplicitBoundaries = []float64{.005, .01, .025, .05, .075, .1, .25, .5, .75, 1, 2.5, 5, 7.5, 10} o.PushInterval = types.Duration(10 * time.Second) o.ServiceName = OTelTraefikServiceName } // Statistics provides options for monitoring request and response stats. type Statistics struct { RecentErrors int `description:"Number of recent errors logged." json:"recentErrors,omitempty" toml:"recentErrors,omitempty" yaml:"recentErrors,omitempty" export:"true"` } // SetDefaults sets the default values. func (s *Statistics) SetDefaults() { s.RecentErrors = 10 }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/types/tracing_test.go
pkg/observability/types/tracing_test.go
package types import ( "testing" "github.com/stretchr/testify/require" ) func TestTracingVerbosity_Allows(t *testing.T) { tests := []struct { desc string from TracingVerbosity to TracingVerbosity allows bool }{ { desc: "minimal vs minimal", from: MinimalVerbosity, to: MinimalVerbosity, allows: true, }, { desc: "minimal vs detailed", from: MinimalVerbosity, to: DetailedVerbosity, allows: false, }, { desc: "detailed vs minimal", from: DetailedVerbosity, to: MinimalVerbosity, allows: true, }, { desc: "detailed vs detailed", from: DetailedVerbosity, to: DetailedVerbosity, allows: true, }, { desc: "unknown vs minimal", from: TracingVerbosity("unknown"), to: MinimalVerbosity, allows: true, }, { desc: "unknown vs detailed", from: TracingVerbosity("unknown"), to: DetailedVerbosity, allows: false, }, { desc: "minimal vs unknown", from: MinimalVerbosity, to: TracingVerbosity("unknown"), allows: false, }, { desc: "detailed vs unknown", from: DetailedVerbosity, to: TracingVerbosity("unknown"), allows: false, }, } for _, test := range tests { t.Run(test.desc, func(t *testing.T) { t.Parallel() require.Equal(t, test.allows, test.from.Allows(test.to)) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/types/tracing.go
pkg/observability/types/tracing.go
package types import ( "context" "fmt" "io" "net" "net/url" "time" "github.com/rs/zerolog/log" ttypes "github.com/traefik/traefik/v3/pkg/types" "github.com/traefik/traefik/v3/pkg/version" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/exporters/otlp/otlptrace" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" "go.opentelemetry.io/otel/sdk/resource" sdktrace "go.opentelemetry.io/otel/sdk/trace" semconv "go.opentelemetry.io/otel/semconv/v1.37.0" "go.opentelemetry.io/otel/trace" "google.golang.org/grpc/credentials" "google.golang.org/grpc/encoding/gzip" ) type TracingVerbosity string const ( MinimalVerbosity TracingVerbosity = "minimal" DetailedVerbosity TracingVerbosity = "detailed" ) func (v TracingVerbosity) Allows(verbosity TracingVerbosity) bool { switch v { case DetailedVerbosity: return verbosity == DetailedVerbosity || verbosity == MinimalVerbosity default: return verbosity == MinimalVerbosity } } // OTelTracing provides configuration settings for the open-telemetry tracer. type OTelTracing struct { GRPC *OTelGRPC `description:"gRPC configuration for the OpenTelemetry collector." json:"grpc,omitempty" toml:"grpc,omitempty" yaml:"grpc,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` HTTP *OTelHTTP `description:"HTTP configuration for the OpenTelemetry collector." json:"http,omitempty" toml:"http,omitempty" yaml:"http,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` } // SetDefaults sets the default values. func (c *OTelTracing) SetDefaults() { c.HTTP = &OTelHTTP{} c.HTTP.SetDefaults() } // Setup sets up the tracer. func (c *OTelTracing) Setup(ctx context.Context, serviceName string, sampleRate float64, resourceAttributes map[string]string) (trace.Tracer, io.Closer, error) { var ( err error exporter *otlptrace.Exporter ) if c.GRPC != nil { exporter, err = c.setupGRPCExporter() } else { exporter, err = c.setupHTTPExporter() } if err != nil { return nil, nil, fmt.Errorf("setting up exporter: %w", err) } var resAttrs []attribute.KeyValue for k, v := range resourceAttributes { resAttrs = append(resAttrs, attribute.String(k, v)) } res, err := resource.New(ctx, resource.WithContainer(), resource.WithHost(), resource.WithOS(), resource.WithProcess(), resource.WithTelemetrySDK(), resource.WithDetectors(ttypes.K8sAttributesDetector{}), // The following order allows the user to override the service name and version, // as well as any other attributes set by the above detectors. resource.WithAttributes( semconv.ServiceName(serviceName), semconv.ServiceVersion(version.Version), ), resource.WithAttributes(resAttrs...), // Use the environment variables to allow overriding above resource attributes. resource.WithFromEnv(), ) if err != nil { return nil, nil, fmt.Errorf("building resource: %w", err) } // Register the trace exporter with a TracerProvider, using a batch // span processor to aggregate spans before export. bsp := sdktrace.NewBatchSpanProcessor(exporter) tracerProvider := sdktrace.NewTracerProvider( sdktrace.WithSampler(sdktrace.TraceIDRatioBased(sampleRate)), sdktrace.WithResource(res), sdktrace.WithSpanProcessor(bsp), ) otel.SetTracerProvider(tracerProvider) log.Debug().Msg("OpenTelemetry tracer configured") return tracerProvider.Tracer("github.com/traefik/traefik"), &tpCloser{provider: tracerProvider}, err } func (c *OTelTracing) setupHTTPExporter() (*otlptrace.Exporter, error) { endpoint, err := url.Parse(c.HTTP.Endpoint) if err != nil { return nil, fmt.Errorf("invalid collector endpoint %q: %w", c.HTTP.Endpoint, err) } opts := []otlptracehttp.Option{ otlptracehttp.WithEndpoint(endpoint.Host), otlptracehttp.WithHeaders(c.HTTP.Headers), otlptracehttp.WithCompression(otlptracehttp.GzipCompression), } if endpoint.Scheme == "http" { opts = append(opts, otlptracehttp.WithInsecure()) } if endpoint.Path != "" { opts = append(opts, otlptracehttp.WithURLPath(endpoint.Path)) } if c.HTTP.TLS != nil { tlsConfig, err := c.HTTP.TLS.CreateTLSConfig(context.Background()) if err != nil { return nil, fmt.Errorf("creating TLS client config: %w", err) } opts = append(opts, otlptracehttp.WithTLSClientConfig(tlsConfig)) } return otlptrace.New(context.Background(), otlptracehttp.NewClient(opts...)) } func (c *OTelTracing) setupGRPCExporter() (*otlptrace.Exporter, error) { host, port, err := net.SplitHostPort(c.GRPC.Endpoint) if err != nil { return nil, fmt.Errorf("invalid collector endpoint %q: %w", c.GRPC.Endpoint, err) } opts := []otlptracegrpc.Option{ otlptracegrpc.WithEndpoint(fmt.Sprintf("%s:%s", host, port)), otlptracegrpc.WithHeaders(c.GRPC.Headers), otlptracegrpc.WithCompressor(gzip.Name), } if c.GRPC.Insecure { opts = append(opts, otlptracegrpc.WithInsecure()) } if c.GRPC.TLS != nil { tlsConfig, err := c.GRPC.TLS.CreateTLSConfig(context.Background()) if err != nil { return nil, fmt.Errorf("creating TLS client config: %w", err) } opts = append(opts, otlptracegrpc.WithTLSCredentials(credentials.NewTLS(tlsConfig))) } return otlptrace.New(context.Background(), otlptracegrpc.NewClient(opts...)) } // tpCloser converts a TraceProvider into an io.Closer. type tpCloser struct { provider *sdktrace.TracerProvider } func (t *tpCloser) Close() error { if t == nil { return nil } ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(5*time.Second)) defer cancel() return t.provider.Shutdown(ctx) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/types/logs.go
pkg/observability/types/logs.go
package types import ( "context" "fmt" "net" "net/url" "github.com/traefik/paerser/types" ttypes "github.com/traefik/traefik/v3/pkg/types" "github.com/traefik/traefik/v3/pkg/version" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc" "go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp" otelsdk "go.opentelemetry.io/otel/sdk/log" "go.opentelemetry.io/otel/sdk/resource" semconv "go.opentelemetry.io/otel/semconv/v1.37.0" "google.golang.org/grpc/credentials" "google.golang.org/grpc/encoding/gzip" ) const ( // AccessLogKeep is the keep string value. AccessLogKeep = "keep" // AccessLogDrop is the drop string value. AccessLogDrop = "drop" // AccessLogRedact is the redact string value. AccessLogRedact = "redact" ) const ( // CommonFormat is the common logging format (CLF). CommonFormat string = "common" ) const OTelTraefikServiceName = "traefik" // TraefikLog holds the configuration settings for the traefik logger. type TraefikLog struct { Level string `description:"Log level set to traefik logs." json:"level,omitempty" toml:"level,omitempty" yaml:"level,omitempty" export:"true"` Format string `description:"Traefik log format: json | common" json:"format,omitempty" toml:"format,omitempty" yaml:"format,omitempty" export:"true"` NoColor bool `description:"When using the 'common' format, disables the colorized output." json:"noColor,omitempty" toml:"noColor,omitempty" yaml:"noColor,omitempty" export:"true"` FilePath string `description:"Traefik log file path. Stdout is used when omitted or empty." json:"filePath,omitempty" toml:"filePath,omitempty" yaml:"filePath,omitempty"` MaxSize int `description:"Maximum size in megabytes of the log file before it gets rotated." json:"maxSize,omitempty" toml:"maxSize,omitempty" yaml:"maxSize,omitempty" export:"true"` MaxAge int `description:"Maximum number of days to retain old log files based on the timestamp encoded in their filename." json:"maxAge,omitempty" toml:"maxAge,omitempty" yaml:"maxAge,omitempty" export:"true"` MaxBackups int `description:"Maximum number of old log files to retain." json:"maxBackups,omitempty" toml:"maxBackups,omitempty" yaml:"maxBackups,omitempty" export:"true"` Compress bool `description:"Determines if the rotated log files should be compressed using gzip." json:"compress,omitempty" toml:"compress,omitempty" yaml:"compress,omitempty" export:"true"` OTLP *OTelLog `description:"Settings for OpenTelemetry." json:"otlp,omitempty" toml:"otlp,omitempty" yaml:"otlp,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` } // SetDefaults sets the default values. func (l *TraefikLog) SetDefaults() { l.Format = CommonFormat l.Level = "ERROR" } // AccessLog holds the configuration settings for the access logger (middlewares/accesslog). type AccessLog struct { FilePath string `description:"Access log file path. Stdout is used when omitted or empty." json:"filePath,omitempty" toml:"filePath,omitempty" yaml:"filePath,omitempty"` Format string `description:"Access log format: json, common, or genericCLF" json:"format,omitempty" toml:"format,omitempty" yaml:"format,omitempty" export:"true"` Filters *AccessLogFilters `description:"Access log filters, used to keep only specific access logs." json:"filters,omitempty" toml:"filters,omitempty" yaml:"filters,omitempty" export:"true"` Fields *AccessLogFields `description:"AccessLogFields." json:"fields,omitempty" toml:"fields,omitempty" yaml:"fields,omitempty" export:"true"` BufferingSize int64 `description:"Number of access log lines to process in a buffered way." json:"bufferingSize,omitempty" toml:"bufferingSize,omitempty" yaml:"bufferingSize,omitempty" export:"true"` AddInternals bool `description:"Enables access log for internal services (ping, dashboard, etc...)." json:"addInternals,omitempty" toml:"addInternals,omitempty" yaml:"addInternals,omitempty" export:"true"` OTLP *OTelLog `description:"Settings for OpenTelemetry." json:"otlp,omitempty" toml:"otlp,omitempty" yaml:"otlp,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` } // SetDefaults sets the default values. func (l *AccessLog) SetDefaults() { l.Format = CommonFormat l.FilePath = "" l.Filters = &AccessLogFilters{} l.Fields = &AccessLogFields{} l.Fields.SetDefaults() } // AccessLogFilters holds filters configuration. type AccessLogFilters struct { StatusCodes []string `description:"Keep access logs with status codes in the specified range." json:"statusCodes,omitempty" toml:"statusCodes,omitempty" yaml:"statusCodes,omitempty" export:"true"` RetryAttempts bool `description:"Keep access logs when at least one retry happened." json:"retryAttempts,omitempty" toml:"retryAttempts,omitempty" yaml:"retryAttempts,omitempty" export:"true"` MinDuration types.Duration `description:"Keep access logs when request took longer than the specified duration." json:"minDuration,omitempty" toml:"minDuration,omitempty" yaml:"minDuration,omitempty" export:"true"` } // FieldHeaders holds configuration for access log headers. type FieldHeaders struct { DefaultMode string `description:"Default mode for fields: keep | drop | redact" json:"defaultMode,omitempty" toml:"defaultMode,omitempty" yaml:"defaultMode,omitempty" export:"true"` Names map[string]string `description:"Override mode for headers" json:"names,omitempty" toml:"names,omitempty" yaml:"names,omitempty" export:"true"` } // AccessLogFields holds configuration for access log fields. type AccessLogFields struct { DefaultMode string `description:"Default mode for fields: keep | drop" json:"defaultMode,omitempty" toml:"defaultMode,omitempty" yaml:"defaultMode,omitempty" export:"true"` Names map[string]string `description:"Override mode for fields" json:"names,omitempty" toml:"names,omitempty" yaml:"names,omitempty" export:"true"` Headers *FieldHeaders `description:"Headers to keep, drop or redact" json:"headers,omitempty" toml:"headers,omitempty" yaml:"headers,omitempty" export:"true"` } // SetDefaults sets the default values. func (f *AccessLogFields) SetDefaults() { f.DefaultMode = AccessLogKeep f.Headers = &FieldHeaders{ DefaultMode: AccessLogDrop, } } // Keep check if the field need to be kept or dropped. func (f *AccessLogFields) Keep(field string) bool { defaultKeep := true if f != nil { defaultKeep = checkFieldValue(f.DefaultMode, defaultKeep) if v, ok := f.Names[field]; ok { return checkFieldValue(v, defaultKeep) } } return defaultKeep } // KeepHeader checks if the headers need to be kept, dropped or redacted and returns the status. func (f *AccessLogFields) KeepHeader(header string) string { defaultValue := AccessLogKeep if f != nil && f.Headers != nil { defaultValue = checkFieldHeaderValue(f.Headers.DefaultMode, defaultValue) if v, ok := f.Headers.Names[header]; ok { return checkFieldHeaderValue(v, defaultValue) } } return defaultValue } func checkFieldValue(value string, defaultKeep bool) bool { switch value { case AccessLogKeep: return true case AccessLogDrop: return false default: return defaultKeep } } func checkFieldHeaderValue(value, defaultValue string) string { if value == AccessLogKeep || value == AccessLogDrop || value == AccessLogRedact { return value } return defaultValue } // OTelLog provides configuration settings for the open-telemetry logger. type OTelLog struct { ServiceName string `description:"Defines the service name resource attribute." json:"serviceName,omitempty" toml:"serviceName,omitempty" yaml:"serviceName,omitempty" export:"true"` ResourceAttributes map[string]string `description:"Defines additional resource attributes (key:value)." json:"resourceAttributes,omitempty" toml:"resourceAttributes,omitempty" yaml:"resourceAttributes,omitempty"` GRPC *OTelGRPC `description:"gRPC configuration for the OpenTelemetry collector." json:"grpc,omitempty" toml:"grpc,omitempty" yaml:"grpc,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` HTTP *OTelHTTP `description:"HTTP configuration for the OpenTelemetry collector." json:"http,omitempty" toml:"http,omitempty" yaml:"http,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` } // SetDefaults sets the default values. func (o *OTelLog) SetDefaults() { o.ServiceName = OTelTraefikServiceName o.HTTP = &OTelHTTP{} o.HTTP.SetDefaults() } // NewLoggerProvider creates a new OpenTelemetry logger provider. func (o *OTelLog) NewLoggerProvider(ctx context.Context) (*otelsdk.LoggerProvider, error) { var ( err error exporter otelsdk.Exporter ) if o.GRPC != nil { exporter, err = o.buildGRPCExporter() } else { exporter, err = o.buildHTTPExporter() } if err != nil { return nil, fmt.Errorf("setting up exporter: %w", err) } var resAttrs []attribute.KeyValue for k, v := range o.ResourceAttributes { resAttrs = append(resAttrs, attribute.String(k, v)) } res, err := resource.New(ctx, resource.WithContainer(), resource.WithHost(), resource.WithOS(), resource.WithProcess(), resource.WithTelemetrySDK(), resource.WithDetectors(ttypes.K8sAttributesDetector{}), // The following order allows the user to override the service name and version, // as well as any other attributes set by the above detectors. resource.WithAttributes( semconv.ServiceName(o.ServiceName), semconv.ServiceVersion(version.Version), ), resource.WithAttributes(resAttrs...), // Use the environment variables to allow overriding above resource attributes. resource.WithFromEnv(), ) if err != nil { return nil, fmt.Errorf("building resource: %w", err) } // Register the trace provider to allow the global logger to access it. bp := otelsdk.NewBatchProcessor(exporter) loggerProvider := otelsdk.NewLoggerProvider( otelsdk.WithResource(res), otelsdk.WithProcessor(bp), ) return loggerProvider, nil } func (o *OTelLog) buildHTTPExporter() (*otlploghttp.Exporter, error) { endpoint, err := url.Parse(o.HTTP.Endpoint) if err != nil { return nil, fmt.Errorf("invalid collector endpoint %q: %w", o.HTTP.Endpoint, err) } opts := []otlploghttp.Option{ otlploghttp.WithEndpoint(endpoint.Host), otlploghttp.WithHeaders(o.HTTP.Headers), otlploghttp.WithCompression(otlploghttp.GzipCompression), } if endpoint.Scheme == "http" { opts = append(opts, otlploghttp.WithInsecure()) } if endpoint.Path != "" { opts = append(opts, otlploghttp.WithURLPath(endpoint.Path)) } if o.HTTP.TLS != nil { tlsConfig, err := o.HTTP.TLS.CreateTLSConfig(context.Background()) if err != nil { return nil, fmt.Errorf("creating TLS client config: %w", err) } opts = append(opts, otlploghttp.WithTLSClientConfig(tlsConfig)) } return otlploghttp.New(context.Background(), opts...) } func (o *OTelLog) buildGRPCExporter() (*otlploggrpc.Exporter, error) { host, port, err := net.SplitHostPort(o.GRPC.Endpoint) if err != nil { return nil, fmt.Errorf("invalid collector endpoint %q: %w", o.GRPC.Endpoint, err) } opts := []otlploggrpc.Option{ otlploggrpc.WithEndpoint(fmt.Sprintf("%s:%s", host, port)), otlploggrpc.WithHeaders(o.GRPC.Headers), otlploggrpc.WithCompressor(gzip.Name), } if o.GRPC.Insecure { opts = append(opts, otlploggrpc.WithInsecure()) } if o.GRPC.TLS != nil { tlsConfig, err := o.GRPC.TLS.CreateTLSConfig(context.Background()) if err != nil { return nil, fmt.Errorf("creating TLS client config: %w", err) } opts = append(opts, otlploggrpc.WithTLSCredentials(credentials.NewTLS(tlsConfig))) } return otlploggrpc.New(context.Background(), opts...) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/observability/types/otel.go
pkg/observability/types/otel.go
package types import "github.com/traefik/traefik/v3/pkg/types" // OTelGRPC provides configuration settings for the gRPC open-telemetry. type OTelGRPC struct { Endpoint string `description:"Sets the gRPC endpoint (host:port) of the collector." json:"endpoint,omitempty" toml:"endpoint,omitempty" yaml:"endpoint,omitempty"` Insecure bool `description:"Disables client transport security for the exporter." json:"insecure,omitempty" toml:"insecure,omitempty" yaml:"insecure,omitempty" export:"true"` TLS *types.ClientTLS `description:"Defines client transport security parameters." json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" export:"true"` Headers map[string]string `description:"Headers sent with payload." json:"headers,omitempty" toml:"headers,omitempty" yaml:"headers,omitempty"` } // SetDefaults sets the default values. func (o *OTelGRPC) SetDefaults() { o.Endpoint = "localhost:4317" } // OTelHTTP provides configuration settings for the HTTP open-telemetry. type OTelHTTP struct { Endpoint string `description:"Sets the HTTP endpoint (scheme://host:port/path) of the collector." json:"endpoint,omitempty" toml:"endpoint,omitempty" yaml:"endpoint,omitempty"` TLS *types.ClientTLS `description:"Defines client transport security parameters." json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" export:"true"` Headers map[string]string `description:"Headers sent with payload." json:"headers,omitempty" toml:"headers,omitempty" yaml:"headers,omitempty"` } // SetDefaults sets the default values. func (o *OTelHTTP) SetDefaults() { o.Endpoint = "https://localhost:4318" }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/handler_http.go
pkg/api/handler_http.go
package api import ( "encoding/json" "fmt" "net/http" "net/url" "strconv" "strings" "github.com/gorilla/mux" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/tls" ) type routerRepresentation struct { *runtime.RouterInfo Name string `json:"name,omitempty"` Provider string `json:"provider,omitempty"` } func newRouterRepresentation(name string, rt *runtime.RouterInfo) routerRepresentation { if rt.TLS != nil && rt.TLS.Options == "" { rt.TLS.Options = tls.DefaultTLSConfigName } return routerRepresentation{ RouterInfo: rt, Name: name, Provider: getProviderName(name), } } type serviceRepresentation struct { *runtime.ServiceInfo Name string `json:"name,omitempty"` Provider string `json:"provider,omitempty"` Type string `json:"type,omitempty"` ServerStatus map[string]string `json:"serverStatus,omitempty"` } func newServiceRepresentation(name string, si *runtime.ServiceInfo) serviceRepresentation { return serviceRepresentation{ ServiceInfo: si, Name: name, Provider: getProviderName(name), Type: strings.ToLower(extractType(si.Service)), ServerStatus: si.GetAllStatus(), } } type middlewareRepresentation struct { *runtime.MiddlewareInfo Name string `json:"name,omitempty"` Provider string `json:"provider,omitempty"` Type string `json:"type,omitempty"` } func newMiddlewareRepresentation(name string, mi *runtime.MiddlewareInfo) middlewareRepresentation { return middlewareRepresentation{ MiddlewareInfo: mi, Name: name, Provider: getProviderName(name), Type: strings.ToLower(extractType(mi.Middleware)), } } func (h Handler) getRouters(rw http.ResponseWriter, request *http.Request) { results := make([]routerRepresentation, 0, len(h.runtimeConfiguration.Routers)) query := request.URL.Query() criterion := newSearchCriterion(query) for name, rt := range h.runtimeConfiguration.Routers { if keepRouter(name, rt, criterion) { results = append(results, newRouterRepresentation(name, rt)) } } sortRouters(query, results) rw.Header().Set("Content-Type", "application/json") pageInfo, err := pagination(request, len(results)) if err != nil { writeError(rw, err.Error(), http.StatusBadRequest) return } rw.Header().Set(nextPageHeader, strconv.Itoa(pageInfo.nextPage)) err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex]) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() writeError(rw, err.Error(), http.StatusInternalServerError) } } func (h Handler) getRouter(rw http.ResponseWriter, request *http.Request) { scapedRouterID := mux.Vars(request)["routerID"] routerID, err := url.PathUnescape(scapedRouterID) if err != nil { writeError(rw, fmt.Sprintf("unable to decode routerID %q: %s", scapedRouterID, err), http.StatusBadRequest) return } rw.Header().Set("Content-Type", "application/json") router, ok := h.runtimeConfiguration.Routers[routerID] if !ok { writeError(rw, fmt.Sprintf("router not found: %s", routerID), http.StatusNotFound) return } result := newRouterRepresentation(routerID, router) err = json.NewEncoder(rw).Encode(result) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() writeError(rw, err.Error(), http.StatusInternalServerError) } } func (h Handler) getServices(rw http.ResponseWriter, request *http.Request) { results := make([]serviceRepresentation, 0, len(h.runtimeConfiguration.Services)) query := request.URL.Query() criterion := newSearchCriterion(query) for name, si := range h.runtimeConfiguration.Services { if keepService(name, si, criterion) { results = append(results, newServiceRepresentation(name, si)) } } sortServices(query, results) rw.Header().Set("Content-Type", "application/json") pageInfo, err := pagination(request, len(results)) if err != nil { writeError(rw, err.Error(), http.StatusBadRequest) return } rw.Header().Set(nextPageHeader, strconv.Itoa(pageInfo.nextPage)) err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex]) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() writeError(rw, err.Error(), http.StatusInternalServerError) } } func (h Handler) getService(rw http.ResponseWriter, request *http.Request) { scapedServiceID := mux.Vars(request)["serviceID"] serviceID, err := url.PathUnescape(scapedServiceID) if err != nil { writeError(rw, fmt.Sprintf("unable to decode serviceID %q: %s", scapedServiceID, err), http.StatusBadRequest) return } rw.Header().Add("Content-Type", "application/json") service, ok := h.runtimeConfiguration.Services[serviceID] if !ok { writeError(rw, fmt.Sprintf("service not found: %s", serviceID), http.StatusNotFound) return } result := newServiceRepresentation(serviceID, service) err = json.NewEncoder(rw).Encode(result) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() writeError(rw, err.Error(), http.StatusInternalServerError) } } func (h Handler) getMiddlewares(rw http.ResponseWriter, request *http.Request) { results := make([]middlewareRepresentation, 0, len(h.runtimeConfiguration.Middlewares)) query := request.URL.Query() criterion := newSearchCriterion(query) for name, mi := range h.runtimeConfiguration.Middlewares { if keepMiddleware(name, mi, criterion) { results = append(results, newMiddlewareRepresentation(name, mi)) } } sortMiddlewares(query, results) rw.Header().Set("Content-Type", "application/json") pageInfo, err := pagination(request, len(results)) if err != nil { writeError(rw, err.Error(), http.StatusBadRequest) return } rw.Header().Set(nextPageHeader, strconv.Itoa(pageInfo.nextPage)) err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex]) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() writeError(rw, err.Error(), http.StatusInternalServerError) } } func (h Handler) getMiddleware(rw http.ResponseWriter, request *http.Request) { scapedMiddlewareID := mux.Vars(request)["middlewareID"] middlewareID, err := url.PathUnescape(scapedMiddlewareID) if err != nil { writeError(rw, fmt.Sprintf("unable to decode middlewareID %q: %s", scapedMiddlewareID, err), http.StatusBadRequest) return } rw.Header().Set("Content-Type", "application/json") middleware, ok := h.runtimeConfiguration.Middlewares[middlewareID] if !ok { writeError(rw, fmt.Sprintf("middleware not found: %s", middlewareID), http.StatusNotFound) return } result := newMiddlewareRepresentation(middlewareID, middleware) err = json.NewEncoder(rw).Encode(result) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() writeError(rw, err.Error(), http.StatusInternalServerError) } } func keepRouter(name string, item *runtime.RouterInfo, criterion *searchCriterion) bool { if criterion == nil { return true } return criterion.withStatus(item.Status) && criterion.searchIn(item.Rule, name) && criterion.filterService(item.Service) && criterion.filterMiddleware(item.Middlewares) } func keepService(name string, item *runtime.ServiceInfo, criterion *searchCriterion) bool { if criterion == nil { return true } return criterion.withStatus(item.Status) && criterion.searchIn(name) } func keepMiddleware(name string, item *runtime.MiddlewareInfo, criterion *searchCriterion) bool { if criterion == nil { return true } return criterion.withStatus(item.Status) && criterion.searchIn(name) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/sort.go
pkg/api/sort.go
package api import ( "cmp" "net/url" "sort" ) const ( sortByParam = "sortBy" directionParam = "direction" ) const ( ascendantSorting = "asc" descendantSorting = "desc" ) type orderedWithName interface { name() string } type orderedRouter interface { orderedWithName provider() string priority() int status() string rule() string service() string entryPointsCount() int } func sortRouters[T orderedRouter](values url.Values, routers []T) { sortBy := values.Get(sortByParam) direction := values.Get(directionParam) if direction == "" { direction = ascendantSorting } switch sortBy { case "name": sortByName(direction, routers) case "provider": sortByFunc(direction, routers, func(i int) string { return routers[i].provider() }) case "priority": sortByFunc(direction, routers, func(i int) int { return routers[i].priority() }) case "status": sortByFunc(direction, routers, func(i int) string { return routers[i].status() }) case "rule": sortByFunc(direction, routers, func(i int) string { return routers[i].rule() }) case "service": sortByFunc(direction, routers, func(i int) string { return routers[i].service() }) case "entryPoints": sortByFunc(direction, routers, func(i int) int { return routers[i].entryPointsCount() }) default: sortByName(direction, routers) } } func (r routerRepresentation) name() string { return r.Name } func (r routerRepresentation) provider() string { return r.Provider } func (r routerRepresentation) priority() int { return r.Priority } func (r routerRepresentation) status() string { return r.Status } func (r routerRepresentation) rule() string { return r.Rule } func (r routerRepresentation) service() string { return r.Service } func (r routerRepresentation) entryPointsCount() int { return len(r.EntryPoints) } func (r tcpRouterRepresentation) name() string { return r.Name } func (r tcpRouterRepresentation) provider() string { return r.Provider } func (r tcpRouterRepresentation) priority() int { return r.Priority } func (r tcpRouterRepresentation) status() string { return r.Status } func (r tcpRouterRepresentation) rule() string { return r.Rule } func (r tcpRouterRepresentation) service() string { return r.Service } func (r tcpRouterRepresentation) entryPointsCount() int { return len(r.EntryPoints) } func (r udpRouterRepresentation) name() string { return r.Name } func (r udpRouterRepresentation) provider() string { return r.Provider } func (r udpRouterRepresentation) priority() int { // noop return 0 } func (r udpRouterRepresentation) status() string { return r.Status } func (r udpRouterRepresentation) rule() string { // noop return "" } func (r udpRouterRepresentation) service() string { return r.Service } func (r udpRouterRepresentation) entryPointsCount() int { return len(r.EntryPoints) } type orderedService interface { orderedWithName resourceType() string serversCount() int provider() string status() string } func sortServices[T orderedService](values url.Values, services []T) { sortBy := values.Get(sortByParam) direction := values.Get(directionParam) if direction == "" { direction = ascendantSorting } switch sortBy { case "name": sortByName(direction, services) case "type": sortByFunc(direction, services, func(i int) string { return services[i].resourceType() }) case "servers": sortByFunc(direction, services, func(i int) int { return services[i].serversCount() }) case "provider": sortByFunc(direction, services, func(i int) string { return services[i].provider() }) case "status": sortByFunc(direction, services, func(i int) string { return services[i].status() }) default: sortByName(direction, services) } } func (s serviceRepresentation) name() string { return s.Name } func (s serviceRepresentation) resourceType() string { return s.Type } func (s serviceRepresentation) serversCount() int { // TODO: maybe disable that data point altogether, // if we can't/won't compute a fully correct (recursive) result. // Or "redefine" it as only the top-level count? // Note: The current algo is equivalent to the webui one. if s.LoadBalancer == nil { return 0 } return len(s.LoadBalancer.Servers) } func (s serviceRepresentation) provider() string { return s.Provider } func (s serviceRepresentation) status() string { return s.Status } func (s tcpServiceRepresentation) name() string { return s.Name } func (s tcpServiceRepresentation) resourceType() string { return s.Type } func (s tcpServiceRepresentation) serversCount() int { // TODO: maybe disable that data point altogether, // if we can't/won't compute a fully correct (recursive) result. // Or "redefine" it as only the top-level count? // Note: The current algo is equivalent to the webui one. if s.LoadBalancer == nil { return 0 } return len(s.LoadBalancer.Servers) } func (s tcpServiceRepresentation) provider() string { return s.Provider } func (s tcpServiceRepresentation) status() string { return s.Status } func (s udpServiceRepresentation) name() string { return s.Name } func (s udpServiceRepresentation) resourceType() string { return s.Type } func (s udpServiceRepresentation) serversCount() int { // TODO: maybe disable that data point altogether, // if we can't/won't compute a fully correct (recursive) result. // Or "redefine" it as only the top-level count? // Note: The current algo is equivalent to the webui one. if s.LoadBalancer == nil { return 0 } return len(s.LoadBalancer.Servers) } func (s udpServiceRepresentation) provider() string { return s.Provider } func (s udpServiceRepresentation) status() string { return s.Status } type orderedMiddleware interface { orderedWithName resourceType() string provider() string status() string } func sortMiddlewares[T orderedMiddleware](values url.Values, middlewares []T) { sortBy := values.Get(sortByParam) direction := values.Get(directionParam) if direction == "" { direction = ascendantSorting } switch sortBy { case "name": sortByName(direction, middlewares) case "type": sortByFunc(direction, middlewares, func(i int) string { return middlewares[i].resourceType() }) case "provider": sortByFunc(direction, middlewares, func(i int) string { return middlewares[i].provider() }) case "status": sortByFunc(direction, middlewares, func(i int) string { return middlewares[i].status() }) default: sortByName(direction, middlewares) } } func (m middlewareRepresentation) name() string { return m.Name } func (m middlewareRepresentation) resourceType() string { return m.Type } func (m middlewareRepresentation) provider() string { return m.Provider } func (m middlewareRepresentation) status() string { return m.Status } func (m tcpMiddlewareRepresentation) name() string { return m.Name } func (m tcpMiddlewareRepresentation) resourceType() string { return m.Type } func (m tcpMiddlewareRepresentation) provider() string { return m.Provider } func (m tcpMiddlewareRepresentation) status() string { return m.Status } func sortByName[T orderedWithName](direction string, results []T) { // Ascending if direction == ascendantSorting { sort.Slice(results, func(i, j int) bool { return results[i].name() < results[j].name() }) return } // Descending sort.Slice(results, func(i, j int) bool { return results[i].name() > results[j].name() }) } func sortByFunc[T orderedWithName, U cmp.Ordered](direction string, results []T, fn func(int) U) { // Ascending if direction == ascendantSorting { sort.Slice(results, func(i, j int) bool { if fn(i) == fn(j) { return results[i].name() < results[j].name() } return fn(i) < fn(j) }) return } // Descending sort.Slice(results, func(i, j int) bool { if fn(i) == fn(j) { return results[i].name() > results[j].name() } return fn(i) > fn(j) }) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/handler_test.go
pkg/api/handler_test.go
package api import ( "encoding/json" "flag" "io" "net/http" "net/http/httptest" "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/config/static" ) var updateExpected = flag.Bool("update_expected", false, "Update expected files in testdata") func TestHandler_RawData(t *testing.T) { type expected struct { statusCode int json string } testCases := []struct { desc string path string conf runtime.Configuration expected expected }{ { desc: "Get rawdata", path: "/api/rawdata", conf: runtime.Configuration{ Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: pointer(true), Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, }, }, Middlewares: map[string]*runtime.MiddlewareInfo{ "auth@myprovider": { Middleware: &dynamic.Middleware{ BasicAuth: &dynamic.BasicAuth{ Users: []string{"admin:admin"}, }, }, }, "addPrefixTest@myprovider": { Middleware: &dynamic.Middleware{ AddPrefix: &dynamic.AddPrefix{ Prefix: "/titi", }, }, }, "addPrefixTest@anotherprovider": { Middleware: &dynamic.Middleware{ AddPrefix: &dynamic.AddPrefix{ Prefix: "/toto", }, }, }, }, Routers: map[string]*runtime.RouterInfo{ "bar@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", Middlewares: []string{"auth", "addPrefixTest@anotherprovider"}, }, }, "test@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar.other`)", Middlewares: []string{"addPrefixTest", "auth"}, }, }, }, TCPServices: map[string]*runtime.TCPServiceInfo{ "tcpfoo-service@myprovider": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.1", }, }, }, }, }, }, TCPRouters: map[string]*runtime.TCPRouterInfo{ "tcpbar@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "tcpfoo-service@myprovider", Rule: "HostSNI(`foo.bar`)", }, }, "tcptest@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "tcpfoo-service@myprovider", Rule: "HostSNI(`foo.bar.other`)", }, }, }, }, expected: expected{ statusCode: http.StatusOK, json: "testdata/getrawdata.json", }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() // TODO: server status rtConf := &test.conf rtConf.PopulateUsedBy() handler := New(static.Configuration{API: &static.API{}, Global: &static.Global{}}, rtConf) server := httptest.NewServer(handler.createRouter()) resp, err := http.DefaultClient.Get(server.URL + test.path) require.NoError(t, err) assert.Equal(t, test.expected.statusCode, resp.StatusCode) assert.Equal(t, "application/json", resp.Header.Get("Content-Type")) contents, err := io.ReadAll(resp.Body) require.NoError(t, err) err = resp.Body.Close() require.NoError(t, err) if test.expected.json == "" { return } if *updateExpected { var rtRepr RunTimeRepresentation err := json.Unmarshal(contents, &rtRepr) require.NoError(t, err) newJSON, err := json.MarshalIndent(rtRepr, "", "\t") require.NoError(t, err) err = os.WriteFile(test.expected.json, newJSON, 0o644) require.NoError(t, err) } data, err := os.ReadFile(test.expected.json) require.NoError(t, err) assert.JSONEq(t, string(data), string(contents)) }) } } func TestHandler_GetMiddleware(t *testing.T) { testCases := []struct { desc string middlewareName string conf runtime.Configuration expectedStatus int expected interface{} }{ { desc: "Middleware not found", middlewareName: "auth@myprovider", conf: runtime.Configuration{ Middlewares: map[string]*runtime.MiddlewareInfo{}, }, expectedStatus: http.StatusNotFound, }, { desc: "Get middleware", middlewareName: "auth@myprovider", conf: runtime.Configuration{ Middlewares: map[string]*runtime.MiddlewareInfo{ "auth@myprovider": { Middleware: &dynamic.Middleware{ BasicAuth: &dynamic.BasicAuth{ Users: []string{"admin:admin"}, }, }, }, }, }, expectedStatus: http.StatusOK, expected: middlewareRepresentation{ MiddlewareInfo: &runtime.MiddlewareInfo{ Middleware: &dynamic.Middleware{ BasicAuth: &dynamic.BasicAuth{ Users: []string{"admin:admin"}, }, }, }, Name: "auth@myprovider", Provider: "myprovider", Type: "basicauth", }, }, { desc: "Get plugin middleware", middlewareName: "myplugin@myprovider", conf: runtime.Configuration{ Middlewares: map[string]*runtime.MiddlewareInfo{ "myplugin@myprovider": { Middleware: &dynamic.Middleware{ Plugin: map[string]dynamic.PluginConf{ "mysuperplugin": { "foo": "bar", }, }, }, }, }, }, expectedStatus: http.StatusOK, expected: middlewareRepresentation{ MiddlewareInfo: &runtime.MiddlewareInfo{ Middleware: &dynamic.Middleware{ Plugin: map[string]dynamic.PluginConf{ "mysuperplugin": { "foo": "bar", }, }, }, }, Name: "myplugin@myprovider", Provider: "myprovider", Type: "mysuperplugin", }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := New(static.Configuration{API: &static.API{}, Global: &static.Global{}}, &test.conf) server := httptest.NewServer(handler.createRouter()) resp, err := http.DefaultClient.Get(server.URL + "/api/http/middlewares/" + test.middlewareName) require.NoError(t, err) assert.Equal(t, test.expectedStatus, resp.StatusCode) if test.expected == nil { return } data, err := io.ReadAll(resp.Body) require.NoError(t, err) err = resp.Body.Close() require.NoError(t, err) expected, err := json.Marshal(test.expected) require.NoError(t, err) assert.JSONEq(t, string(expected), string(data)) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/handler_support_dump.go
pkg/api/handler_support_dump.go
package api import ( "archive/tar" "compress/gzip" "encoding/json" "fmt" "net/http" "time" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/redactor" "github.com/traefik/traefik/v3/pkg/version" ) func (h Handler) getSupportDump(rw http.ResponseWriter, req *http.Request) { logger := log.Ctx(req.Context()) staticConfig, err := redactor.Anonymize(h.staticConfig) if err != nil { logger.Error().Err(err).Msg("Unable to anonymize and marshal static configuration") writeError(rw, err.Error(), http.StatusInternalServerError) return } runtimeConfig, err := json.Marshal(h.runtimeConfiguration) if err != nil { logger.Error().Err(err).Msg("Unable to marshal runtime configuration") writeError(rw, err.Error(), http.StatusInternalServerError) return } tVersion, err := json.Marshal(struct { Version string `json:"version"` Codename string `json:"codename"` StartDate time.Time `json:"startDate"` }{ Version: version.Version, Codename: version.Codename, StartDate: version.StartDate, }) if err != nil { logger.Error().Err(err).Msg("Unable to marshal version") writeError(rw, err.Error(), http.StatusInternalServerError) return } rw.Header().Set("Content-Type", "application/gzip") rw.Header().Set("Content-Disposition", "attachment; filename=support-dump.tar.gz") // Create gzip writer. gw := gzip.NewWriter(rw) defer gw.Close() // Create tar writer. tw := tar.NewWriter(gw) defer tw.Close() // Add configuration files to the archive. if err := addFile(tw, "version.json", tVersion); err != nil { logger.Error().Err(err).Msg("Unable to archive version file") writeError(rw, err.Error(), http.StatusInternalServerError) return } if err := addFile(tw, "static-config.json", []byte(staticConfig)); err != nil { logger.Error().Err(err).Msg("Unable to archive static configuration") writeError(rw, err.Error(), http.StatusInternalServerError) return } if err := addFile(tw, "runtime-config.json", runtimeConfig); err != nil { logger.Error().Err(err).Msg("Unable to archive runtime configuration") writeError(rw, err.Error(), http.StatusInternalServerError) return } } func addFile(tw *tar.Writer, name string, content []byte) error { header := &tar.Header{ Name: name, Mode: 0o600, Size: int64(len(content)), ModTime: time.Now(), } if err := tw.WriteHeader(header); err != nil { return fmt.Errorf("writing tar header: %w", err) } if _, err := tw.Write(content); err != nil { return fmt.Errorf("writing tar content: %w", err) } return nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/handler_udp_test.go
pkg/api/handler_udp_test.go
package api import ( "encoding/json" "io" "net/http" "net/http/httptest" "net/url" "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/config/static" ) func TestHandler_UDP(t *testing.T) { type expected struct { statusCode int nextPage string jsonFile string } testCases := []struct { desc string path string conf runtime.Configuration expected expected }{ { desc: "all UDP routers, but no config", path: "/api/udp/routers", conf: runtime.Configuration{}, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/udprouters-empty.json", }, }, { desc: "all UDP routers", path: "/api/udp/routers", conf: runtime.Configuration{ UDPRouters: map[string]*runtime.UDPRouterInfo{ "test@myprovider": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, Status: runtime.StatusEnabled, }, "bar@myprovider": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, Status: runtime.StatusWarning, }, "foo@myprovider": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, Status: runtime.StatusDisabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/udprouters.json", }, }, { desc: "all UDP routers, pagination, 1 res per page, want page 2", path: "/api/udp/routers?page=2&per_page=1", conf: runtime.Configuration{ UDPRouters: map[string]*runtime.UDPRouterInfo{ "bar@myprovider": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, }, "baz@myprovider": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, }, "test@myprovider": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "3", jsonFile: "testdata/udprouters-page2.json", }, }, { desc: "UDP routers filtered by status", path: "/api/udp/routers?status=enabled", conf: runtime.Configuration{ UDPRouters: map[string]*runtime.UDPRouterInfo{ "test@myprovider": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, Status: runtime.StatusEnabled, }, "bar@myprovider": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, Status: runtime.StatusWarning, }, "foo@myprovider": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, Status: runtime.StatusDisabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/udprouters-filtered-status.json", }, }, { desc: "UDP routers filtered by search", path: "/api/udp/routers?search=bar@my", conf: runtime.Configuration{ UDPRouters: map[string]*runtime.UDPRouterInfo{ "test@myprovider": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, Status: runtime.StatusEnabled, }, "bar@myprovider": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, Status: runtime.StatusWarning, }, "foo@myprovider": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, Status: runtime.StatusDisabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/udprouters-filtered-search.json", }, }, { desc: "UDP routers filtered by service", path: "/api/udp/routers?serviceName=foo-service@myprovider", conf: runtime.Configuration{ UDPRouters: map[string]*runtime.UDPRouterInfo{ "test@myprovider": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, Status: runtime.StatusEnabled, }, "bar@myprovider": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service", }, Status: runtime.StatusWarning, }, "foo@myprovider": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "bar-service@myprovider", }, Status: runtime.StatusDisabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/udprouters-filtered-serviceName.json", }, }, { desc: "one UDP router by id", path: "/api/udp/routers/bar@myprovider", conf: runtime.Configuration{ UDPRouters: map[string]*runtime.UDPRouterInfo{ "bar@myprovider": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, }, }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/udprouter-bar.json", }, }, { desc: "one UDP router by id containing slash", path: "/api/udp/routers/" + url.PathEscape("foo / bar@myprovider"), conf: runtime.Configuration{ UDPRouters: map[string]*runtime.UDPRouterInfo{ "foo / bar@myprovider": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, }, }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/udprouter-foo-slash-bar.json", }, }, { desc: "one UDP router by id, that does not exist", path: "/api/udp/routers/foo@myprovider", conf: runtime.Configuration{ UDPRouters: map[string]*runtime.UDPRouterInfo{ "bar@myprovider": { UDPRouter: &dynamic.UDPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", }, }, }, }, expected: expected{ statusCode: http.StatusNotFound, }, }, { desc: "one UDP router by id, but no config", path: "/api/udp/routers/bar@myprovider", conf: runtime.Configuration{}, expected: expected{ statusCode: http.StatusNotFound, }, }, { desc: "all udp services, but no config", path: "/api/udp/services", conf: runtime.Configuration{}, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/udpservices-empty.json", }, }, { desc: "all udp services", path: "/api/udp/services", conf: runtime.Configuration{ UDPServices: map[string]*runtime.UDPServiceInfo{ "bar@myprovider": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "127.0.0.1:2345", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, Status: runtime.StatusEnabled, }, "baz@myprovider": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "127.0.0.2:2345", }, }, }, }, UsedBy: []string{"foo@myprovider"}, Status: runtime.StatusWarning, }, "foz@myprovider": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "127.0.0.2:2345", }, }, }, }, UsedBy: []string{"foo@myprovider"}, Status: runtime.StatusDisabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/udpservices.json", }, }, { desc: "udp services filtered by status", path: "/api/udp/services?status=enabled", conf: runtime.Configuration{ UDPServices: map[string]*runtime.UDPServiceInfo{ "bar@myprovider": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "127.0.0.1:2345", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, Status: runtime.StatusEnabled, }, "baz@myprovider": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "127.0.0.2:2345", }, }, }, }, UsedBy: []string{"foo@myprovider"}, Status: runtime.StatusWarning, }, "foz@myprovider": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "127.0.0.2:2345", }, }, }, }, UsedBy: []string{"foo@myprovider"}, Status: runtime.StatusDisabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/udpservices-filtered-status.json", }, }, { desc: "udp services filtered by search", path: "/api/udp/services?search=baz@my", conf: runtime.Configuration{ UDPServices: map[string]*runtime.UDPServiceInfo{ "bar@myprovider": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "127.0.0.1:2345", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, Status: runtime.StatusEnabled, }, "baz@myprovider": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "127.0.0.2:2345", }, }, }, }, UsedBy: []string{"foo@myprovider"}, Status: runtime.StatusWarning, }, "foz@myprovider": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "127.0.0.2:2345", }, }, }, }, UsedBy: []string{"foo@myprovider"}, Status: runtime.StatusDisabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/udpservices-filtered-search.json", }, }, { desc: "all udp services, 1 res per page, want page 2", path: "/api/udp/services?page=2&per_page=1", conf: runtime.Configuration{ UDPServices: map[string]*runtime.UDPServiceInfo{ "bar@myprovider": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "127.0.0.1:2345", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, }, "baz@myprovider": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "127.0.0.2:2345", }, }, }, }, UsedBy: []string{"foo@myprovider"}, }, "test@myprovider": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "127.0.0.3:2345", }, }, }, }, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "3", jsonFile: "testdata/udpservices-page2.json", }, }, { desc: "one udp service by id", path: "/api/udp/services/bar@myprovider", conf: runtime.Configuration{ UDPServices: map[string]*runtime.UDPServiceInfo{ "bar@myprovider": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "127.0.0.1:2345", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, }, }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/udpservice-bar.json", }, }, { desc: "one udp service by id containing slash", path: "/api/udp/services/" + url.PathEscape("foo / bar@myprovider"), conf: runtime.Configuration{ UDPServices: map[string]*runtime.UDPServiceInfo{ "foo / bar@myprovider": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "127.0.0.1:2345", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, }, }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/udpservice-foo-slash-bar.json", }, }, { desc: "one udp service by id, that does not exist", path: "/api/udp/services/nono@myprovider", conf: runtime.Configuration{ UDPServices: map[string]*runtime.UDPServiceInfo{ "bar@myprovider": { UDPService: &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: []dynamic.UDPServer{ { Address: "127.0.0.1:2345", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, }, }, }, expected: expected{ statusCode: http.StatusNotFound, }, }, { desc: "one udp service by id, but no config", path: "/api/udp/services/foo@myprovider", conf: runtime.Configuration{}, expected: expected{ statusCode: http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() rtConf := &test.conf // To lazily initialize the Statuses. rtConf.PopulateUsedBy() rtConf.GetUDPRoutersByEntryPoints(t.Context(), []string{"web"}) handler := New(static.Configuration{API: &static.API{}, Global: &static.Global{}}, rtConf) server := httptest.NewServer(handler.createRouter()) resp, err := http.DefaultClient.Get(server.URL + test.path) require.NoError(t, err) assert.Equal(t, test.expected.nextPage, resp.Header.Get(nextPageHeader)) require.Equal(t, test.expected.statusCode, resp.StatusCode) if test.expected.jsonFile == "" { return } assert.Equal(t, "application/json", resp.Header.Get("Content-Type")) contents, err := io.ReadAll(resp.Body) require.NoError(t, err) err = resp.Body.Close() require.NoError(t, err) if *updateExpected { var results interface{} err := json.Unmarshal(contents, &results) require.NoError(t, err) newJSON, err := json.MarshalIndent(results, "", "\t") require.NoError(t, err) err = os.WriteFile(test.expected.jsonFile, newJSON, 0o644) require.NoError(t, err) } data, err := os.ReadFile(test.expected.jsonFile) require.NoError(t, err) assert.JSONEq(t, string(data), string(contents)) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/handler_overview.go
pkg/api/handler_overview.go
package api import ( "encoding/json" "net/http" "reflect" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/config/static" ) type schemeOverview struct { Routers *section `json:"routers,omitempty"` Services *section `json:"services,omitempty"` Middlewares *section `json:"middlewares,omitempty"` } type section struct { Total int `json:"total"` Warnings int `json:"warnings"` Errors int `json:"errors"` } type features struct { Tracing string `json:"tracing"` Metrics string `json:"metrics"` AccessLog bool `json:"accessLog"` // TODO add certificates resolvers } type overview struct { HTTP schemeOverview `json:"http"` TCP schemeOverview `json:"tcp"` UDP schemeOverview `json:"udp"` Features features `json:"features,omitempty"` Providers []string `json:"providers,omitempty"` } func (h Handler) getOverview(rw http.ResponseWriter, request *http.Request) { result := overview{ HTTP: schemeOverview{ Routers: getHTTPRouterSection(h.runtimeConfiguration.Routers), Services: getHTTPServiceSection(h.runtimeConfiguration.Services), Middlewares: getHTTPMiddlewareSection(h.runtimeConfiguration.Middlewares), }, TCP: schemeOverview{ Routers: getTCPRouterSection(h.runtimeConfiguration.TCPRouters), Services: getTCPServiceSection(h.runtimeConfiguration.TCPServices), Middlewares: getTCPMiddlewareSection(h.runtimeConfiguration.TCPMiddlewares), }, UDP: schemeOverview{ Routers: getUDPRouterSection(h.runtimeConfiguration.UDPRouters), Services: getUDPServiceSection(h.runtimeConfiguration.UDPServices), }, Features: getFeatures(h.staticConfig), Providers: getProviders(h.staticConfig), } rw.Header().Set("Content-Type", "application/json") err := json.NewEncoder(rw).Encode(result) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() writeError(rw, err.Error(), http.StatusInternalServerError) } } func getHTTPRouterSection(routers map[string]*runtime.RouterInfo) *section { var countErrors int var countWarnings int for _, rt := range routers { switch rt.Status { case runtime.StatusDisabled: countErrors++ case runtime.StatusWarning: countWarnings++ } } return &section{ Total: len(routers), Warnings: countWarnings, Errors: countErrors, } } func getHTTPServiceSection(services map[string]*runtime.ServiceInfo) *section { var countErrors int var countWarnings int for _, svc := range services { switch svc.Status { case runtime.StatusDisabled: countErrors++ case runtime.StatusWarning: countWarnings++ } } return &section{ Total: len(services), Warnings: countWarnings, Errors: countErrors, } } func getHTTPMiddlewareSection(middlewares map[string]*runtime.MiddlewareInfo) *section { var countErrors int var countWarnings int for _, mid := range middlewares { switch mid.Status { case runtime.StatusDisabled: countErrors++ case runtime.StatusWarning: countWarnings++ } } return &section{ Total: len(middlewares), Warnings: countWarnings, Errors: countErrors, } } func getTCPRouterSection(routers map[string]*runtime.TCPRouterInfo) *section { var countErrors int var countWarnings int for _, rt := range routers { switch rt.Status { case runtime.StatusDisabled: countErrors++ case runtime.StatusWarning: countWarnings++ } } return &section{ Total: len(routers), Warnings: countWarnings, Errors: countErrors, } } func getTCPServiceSection(services map[string]*runtime.TCPServiceInfo) *section { var countErrors int var countWarnings int for _, svc := range services { switch svc.Status { case runtime.StatusDisabled: countErrors++ case runtime.StatusWarning: countWarnings++ } } return &section{ Total: len(services), Warnings: countWarnings, Errors: countErrors, } } func getTCPMiddlewareSection(middlewares map[string]*runtime.TCPMiddlewareInfo) *section { var countErrors int var countWarnings int for _, mid := range middlewares { switch mid.Status { case runtime.StatusDisabled: countErrors++ case runtime.StatusWarning: countWarnings++ } } return &section{ Total: len(middlewares), Warnings: countWarnings, Errors: countErrors, } } func getUDPRouterSection(routers map[string]*runtime.UDPRouterInfo) *section { var countErrors int var countWarnings int for _, rt := range routers { switch rt.Status { case runtime.StatusDisabled: countErrors++ case runtime.StatusWarning: countWarnings++ } } return &section{ Total: len(routers), Warnings: countWarnings, Errors: countErrors, } } func getUDPServiceSection(services map[string]*runtime.UDPServiceInfo) *section { var countErrors int var countWarnings int for _, svc := range services { switch svc.Status { case runtime.StatusDisabled: countErrors++ case runtime.StatusWarning: countWarnings++ } } return &section{ Total: len(services), Warnings: countWarnings, Errors: countErrors, } } func getProviders(conf static.Configuration) []string { if conf.Providers == nil { return nil } var providers []string v := reflect.ValueOf(conf.Providers).Elem() for i := range v.NumField() { field := v.Field(i) if field.Kind() == reflect.Ptr && field.Elem().Kind() == reflect.Struct { if !field.IsNil() { providers = append(providers, v.Type().Field(i).Name) } } else if field.Kind() == reflect.Map && field.Type().Elem() == reflect.TypeFor[static.PluginConf]() { for _, value := range field.MapKeys() { providers = append(providers, "plugin-"+value.String()) } } } return providers } func getFeatures(conf static.Configuration) features { return features{ Tracing: getTracing(conf), Metrics: getMetrics(conf), AccessLog: conf.AccessLog != nil, } } func getMetrics(conf static.Configuration) string { if conf.Metrics == nil { return "" } v := reflect.ValueOf(conf.Metrics).Elem() for i := range v.NumField() { field := v.Field(i) if field.Kind() == reflect.Ptr && field.Elem().Kind() == reflect.Struct { if !field.IsNil() { return v.Type().Field(i).Name } } } return "" } func getTracing(conf static.Configuration) string { if conf.Tracing == nil { return "" } v := reflect.ValueOf(conf.Tracing).Elem() for i := range v.NumField() { field := v.Field(i) if field.Kind() == reflect.Ptr && field.Elem().Kind() == reflect.Struct { if !field.IsNil() { return v.Type().Field(i).Name } } } return "" }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/handler_udp.go
pkg/api/handler_udp.go
package api import ( "encoding/json" "fmt" "net/http" "net/url" "strconv" "strings" "github.com/gorilla/mux" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/runtime" ) type udpRouterRepresentation struct { *runtime.UDPRouterInfo Name string `json:"name,omitempty"` Provider string `json:"provider,omitempty"` } func newUDPRouterRepresentation(name string, rt *runtime.UDPRouterInfo) udpRouterRepresentation { return udpRouterRepresentation{ UDPRouterInfo: rt, Name: name, Provider: getProviderName(name), } } type udpServiceRepresentation struct { *runtime.UDPServiceInfo Name string `json:"name,omitempty"` Provider string `json:"provider,omitempty"` Type string `json:"type,omitempty"` } func newUDPServiceRepresentation(name string, si *runtime.UDPServiceInfo) udpServiceRepresentation { return udpServiceRepresentation{ UDPServiceInfo: si, Name: name, Provider: getProviderName(name), Type: strings.ToLower(extractType(si.UDPService)), } } func (h Handler) getUDPRouters(rw http.ResponseWriter, request *http.Request) { results := make([]udpRouterRepresentation, 0, len(h.runtimeConfiguration.UDPRouters)) query := request.URL.Query() criterion := newSearchCriterion(query) for name, rt := range h.runtimeConfiguration.UDPRouters { if keepUDPRouter(name, rt, criterion) { results = append(results, newUDPRouterRepresentation(name, rt)) } } sortRouters(query, results) rw.Header().Set("Content-Type", "application/json") pageInfo, err := pagination(request, len(results)) if err != nil { writeError(rw, err.Error(), http.StatusBadRequest) return } rw.Header().Set(nextPageHeader, strconv.Itoa(pageInfo.nextPage)) err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex]) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() writeError(rw, err.Error(), http.StatusInternalServerError) } } func (h Handler) getUDPRouter(rw http.ResponseWriter, request *http.Request) { scapedRouterID := mux.Vars(request)["routerID"] routerID, err := url.PathUnescape(scapedRouterID) if err != nil { writeError(rw, fmt.Sprintf("unable to decode routerID %q: %s", scapedRouterID, err), http.StatusBadRequest) return } rw.Header().Set("Content-Type", "application/json") router, ok := h.runtimeConfiguration.UDPRouters[routerID] if !ok { writeError(rw, fmt.Sprintf("router not found: %s", routerID), http.StatusNotFound) return } result := newUDPRouterRepresentation(routerID, router) err = json.NewEncoder(rw).Encode(result) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() writeError(rw, err.Error(), http.StatusInternalServerError) } } func (h Handler) getUDPServices(rw http.ResponseWriter, request *http.Request) { results := make([]udpServiceRepresentation, 0, len(h.runtimeConfiguration.UDPServices)) query := request.URL.Query() criterion := newSearchCriterion(query) for name, si := range h.runtimeConfiguration.UDPServices { if keepUDPService(name, si, criterion) { results = append(results, newUDPServiceRepresentation(name, si)) } } sortServices(query, results) rw.Header().Set("Content-Type", "application/json") pageInfo, err := pagination(request, len(results)) if err != nil { writeError(rw, err.Error(), http.StatusBadRequest) return } rw.Header().Set(nextPageHeader, strconv.Itoa(pageInfo.nextPage)) err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex]) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() writeError(rw, err.Error(), http.StatusInternalServerError) } } func (h Handler) getUDPService(rw http.ResponseWriter, request *http.Request) { scapedServiceID := mux.Vars(request)["serviceID"] serviceID, err := url.PathUnescape(scapedServiceID) if err != nil { writeError(rw, fmt.Sprintf("unable to decode serviceID %q: %s", scapedServiceID, err), http.StatusBadRequest) return } rw.Header().Set("Content-Type", "application/json") service, ok := h.runtimeConfiguration.UDPServices[serviceID] if !ok { writeError(rw, fmt.Sprintf("service not found: %s", serviceID), http.StatusNotFound) return } result := newUDPServiceRepresentation(serviceID, service) err = json.NewEncoder(rw).Encode(result) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() writeError(rw, err.Error(), http.StatusInternalServerError) } } func keepUDPRouter(name string, item *runtime.UDPRouterInfo, criterion *searchCriterion) bool { if criterion == nil { return true } return criterion.withStatus(item.Status) && criterion.searchIn(name) && criterion.filterService(item.Service) } func keepUDPService(name string, item *runtime.UDPServiceInfo, criterion *searchCriterion) bool { if criterion == nil { return true } return criterion.withStatus(item.Status) && criterion.searchIn(name) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/debug.go
pkg/api/debug.go
package api import ( "expvar" "fmt" "net/http" "net/http/pprof" "runtime" "github.com/gorilla/mux" ) func init() { // TODO Goroutines2 -> Goroutines expvar.Publish("Goroutines2", expvar.Func(goroutines)) } func goroutines() interface{} { return runtime.NumGoroutine() } // DebugHandler expose debug routes. type DebugHandler struct{} // Append add debug routes on a router. func (g DebugHandler) Append(router *mux.Router) { router.Methods(http.MethodGet).Path("/debug/vars"). HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") fmt.Fprint(w, "{\n") first := true expvar.Do(func(kv expvar.KeyValue) { if !first { fmt.Fprint(w, ",\n") } first = false fmt.Fprintf(w, "%q: %s", kv.Key, kv.Value) }) fmt.Fprint(w, "\n}\n") }) runtime.SetBlockProfileRate(1) runtime.SetMutexProfileFraction(5) router.Methods(http.MethodGet).PathPrefix("/debug/pprof/cmdline").HandlerFunc(pprof.Cmdline) router.Methods(http.MethodGet).PathPrefix("/debug/pprof/profile").HandlerFunc(pprof.Profile) router.Methods(http.MethodGet).PathPrefix("/debug/pprof/symbol").HandlerFunc(pprof.Symbol) router.Methods(http.MethodGet).PathPrefix("/debug/pprof/trace").HandlerFunc(pprof.Trace) router.Methods(http.MethodGet).PathPrefix("/debug/pprof/").HandlerFunc(pprof.Index) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/handler_tcp.go
pkg/api/handler_tcp.go
package api import ( "encoding/json" "fmt" "net/http" "net/url" "strconv" "strings" "github.com/gorilla/mux" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/runtime" ) type tcpRouterRepresentation struct { *runtime.TCPRouterInfo Name string `json:"name,omitempty"` Provider string `json:"provider,omitempty"` } func newTCPRouterRepresentation(name string, rt *runtime.TCPRouterInfo) tcpRouterRepresentation { return tcpRouterRepresentation{ TCPRouterInfo: rt, Name: name, Provider: getProviderName(name), } } type tcpServiceRepresentation struct { *runtime.TCPServiceInfo Name string `json:"name,omitempty"` Provider string `json:"provider,omitempty"` Type string `json:"type,omitempty"` ServerStatus map[string]string `json:"serverStatus,omitempty"` } func newTCPServiceRepresentation(name string, si *runtime.TCPServiceInfo) tcpServiceRepresentation { return tcpServiceRepresentation{ TCPServiceInfo: si, Name: name, Provider: getProviderName(name), Type: strings.ToLower(extractType(si.TCPService)), ServerStatus: si.GetAllStatus(), } } type tcpMiddlewareRepresentation struct { *runtime.TCPMiddlewareInfo Name string `json:"name,omitempty"` Provider string `json:"provider,omitempty"` Type string `json:"type,omitempty"` } func newTCPMiddlewareRepresentation(name string, mi *runtime.TCPMiddlewareInfo) tcpMiddlewareRepresentation { return tcpMiddlewareRepresentation{ TCPMiddlewareInfo: mi, Name: name, Provider: getProviderName(name), Type: strings.ToLower(extractType(mi.TCPMiddleware)), } } func (h Handler) getTCPRouters(rw http.ResponseWriter, request *http.Request) { results := make([]tcpRouterRepresentation, 0, len(h.runtimeConfiguration.TCPRouters)) query := request.URL.Query() criterion := newSearchCriterion(query) for name, rt := range h.runtimeConfiguration.TCPRouters { if keepTCPRouter(name, rt, criterion) { results = append(results, newTCPRouterRepresentation(name, rt)) } } sortRouters(query, results) rw.Header().Set("Content-Type", "application/json") pageInfo, err := pagination(request, len(results)) if err != nil { writeError(rw, err.Error(), http.StatusBadRequest) return } rw.Header().Set(nextPageHeader, strconv.Itoa(pageInfo.nextPage)) err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex]) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() writeError(rw, err.Error(), http.StatusInternalServerError) } } func (h Handler) getTCPRouter(rw http.ResponseWriter, request *http.Request) { scapedRouterID := mux.Vars(request)["routerID"] routerID, err := url.PathUnescape(scapedRouterID) if err != nil { writeError(rw, fmt.Sprintf("unable to decode routerID %q: %s", scapedRouterID, err), http.StatusBadRequest) return } rw.Header().Set("Content-Type", "application/json") router, ok := h.runtimeConfiguration.TCPRouters[routerID] if !ok { writeError(rw, fmt.Sprintf("router not found: %s", routerID), http.StatusNotFound) return } result := newTCPRouterRepresentation(routerID, router) err = json.NewEncoder(rw).Encode(result) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() writeError(rw, err.Error(), http.StatusInternalServerError) } } func (h Handler) getTCPServices(rw http.ResponseWriter, request *http.Request) { results := make([]tcpServiceRepresentation, 0, len(h.runtimeConfiguration.TCPServices)) query := request.URL.Query() criterion := newSearchCriterion(query) for name, si := range h.runtimeConfiguration.TCPServices { if keepTCPService(name, si, criterion) { results = append(results, newTCPServiceRepresentation(name, si)) } } sortServices(query, results) rw.Header().Set("Content-Type", "application/json") pageInfo, err := pagination(request, len(results)) if err != nil { writeError(rw, err.Error(), http.StatusBadRequest) return } rw.Header().Set(nextPageHeader, strconv.Itoa(pageInfo.nextPage)) err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex]) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() writeError(rw, err.Error(), http.StatusInternalServerError) } } func (h Handler) getTCPService(rw http.ResponseWriter, request *http.Request) { scapedServiceID := mux.Vars(request)["serviceID"] serviceID, err := url.PathUnescape(scapedServiceID) if err != nil { writeError(rw, fmt.Sprintf("unable to decode serviceID %q: %s", scapedServiceID, err), http.StatusBadRequest) return } rw.Header().Set("Content-Type", "application/json") service, ok := h.runtimeConfiguration.TCPServices[serviceID] if !ok { writeError(rw, fmt.Sprintf("service not found: %s", serviceID), http.StatusNotFound) return } result := newTCPServiceRepresentation(serviceID, service) err = json.NewEncoder(rw).Encode(result) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() writeError(rw, err.Error(), http.StatusInternalServerError) } } func (h Handler) getTCPMiddlewares(rw http.ResponseWriter, request *http.Request) { results := make([]tcpMiddlewareRepresentation, 0, len(h.runtimeConfiguration.Middlewares)) query := request.URL.Query() criterion := newSearchCriterion(query) for name, mi := range h.runtimeConfiguration.TCPMiddlewares { if keepTCPMiddleware(name, mi, criterion) { results = append(results, newTCPMiddlewareRepresentation(name, mi)) } } sortMiddlewares(query, results) rw.Header().Set("Content-Type", "application/json") pageInfo, err := pagination(request, len(results)) if err != nil { writeError(rw, err.Error(), http.StatusBadRequest) return } rw.Header().Set(nextPageHeader, strconv.Itoa(pageInfo.nextPage)) err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex]) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() writeError(rw, err.Error(), http.StatusInternalServerError) } } func (h Handler) getTCPMiddleware(rw http.ResponseWriter, request *http.Request) { scapedMiddlewareID := mux.Vars(request)["middlewareID"] middlewareID, err := url.PathUnescape(scapedMiddlewareID) if err != nil { writeError(rw, fmt.Sprintf("unable to decode middlewareID %q: %s", scapedMiddlewareID, err), http.StatusBadRequest) return } rw.Header().Set("Content-Type", "application/json") middleware, ok := h.runtimeConfiguration.TCPMiddlewares[middlewareID] if !ok { writeError(rw, fmt.Sprintf("middleware not found: %s", middlewareID), http.StatusNotFound) return } result := newTCPMiddlewareRepresentation(middlewareID, middleware) err = json.NewEncoder(rw).Encode(result) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() writeError(rw, err.Error(), http.StatusInternalServerError) } } func keepTCPRouter(name string, item *runtime.TCPRouterInfo, criterion *searchCriterion) bool { if criterion == nil { return true } return criterion.withStatus(item.Status) && criterion.searchIn(item.Rule, name) && criterion.filterService(item.Service) && criterion.filterMiddleware(item.Middlewares) } func keepTCPService(name string, item *runtime.TCPServiceInfo, criterion *searchCriterion) bool { if criterion == nil { return true } return criterion.withStatus(item.Status) && criterion.searchIn(name) } func keepTCPMiddleware(name string, item *runtime.TCPMiddlewareInfo, criterion *searchCriterion) bool { if criterion == nil { return true } return criterion.withStatus(item.Status) && criterion.searchIn(name) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/handler_entrypoint.go
pkg/api/handler_entrypoint.go
package api import ( "encoding/json" "fmt" "net/http" "net/url" "sort" "strconv" "github.com/gorilla/mux" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/static" ) type entryPointRepresentation struct { *static.EntryPoint Name string `json:"name,omitempty"` } func (h Handler) getEntryPoints(rw http.ResponseWriter, request *http.Request) { results := make([]entryPointRepresentation, 0, len(h.staticConfig.EntryPoints)) for name, ep := range h.staticConfig.EntryPoints { results = append(results, entryPointRepresentation{ EntryPoint: ep, Name: name, }) } sort.Slice(results, func(i, j int) bool { return results[i].Name < results[j].Name }) rw.Header().Set("Content-Type", "application/json") pageInfo, err := pagination(request, len(results)) if err != nil { writeError(rw, err.Error(), http.StatusBadRequest) return } rw.Header().Set(nextPageHeader, strconv.Itoa(pageInfo.nextPage)) err = json.NewEncoder(rw).Encode(results[pageInfo.startIndex:pageInfo.endIndex]) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() writeError(rw, err.Error(), http.StatusInternalServerError) } } func (h Handler) getEntryPoint(rw http.ResponseWriter, request *http.Request) { scapedEntryPointID := mux.Vars(request)["entryPointID"] entryPointID, err := url.PathUnescape(scapedEntryPointID) if err != nil { writeError(rw, fmt.Sprintf("unable to decode entryPointID %q: %s", scapedEntryPointID, err), http.StatusBadRequest) return } rw.Header().Set("Content-Type", "application/json") ep, ok := h.staticConfig.EntryPoints[entryPointID] if !ok { writeError(rw, fmt.Sprintf("entry point not found: %s", entryPointID), http.StatusNotFound) return } result := entryPointRepresentation{ EntryPoint: ep, Name: entryPointID, } err = json.NewEncoder(rw).Encode(result) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() writeError(rw, err.Error(), http.StatusInternalServerError) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/criterion.go
pkg/api/criterion.go
package api import ( "fmt" "net/http" "net/url" "slices" "strconv" "strings" ) const ( defaultPerPage = 100 defaultPage = 1 ) const nextPageHeader = "X-Next-Page" type pageInfo struct { startIndex int endIndex int nextPage int } type searchCriterion struct { Search string `url:"search"` Status string `url:"status"` ServiceName string `url:"serviceName"` MiddlewareName string `url:"middlewareName"` } func newSearchCriterion(query url.Values) *searchCriterion { if len(query) == 0 { return nil } search := query.Get("search") status := query.Get("status") serviceName := query.Get("serviceName") middlewareName := query.Get("middlewareName") if status == "" && search == "" && serviceName == "" && middlewareName == "" { return nil } return &searchCriterion{ Search: search, Status: status, ServiceName: serviceName, MiddlewareName: middlewareName, } } func (c *searchCriterion) withStatus(name string) bool { return c.Status == "" || strings.EqualFold(name, c.Status) } func (c *searchCriterion) searchIn(values ...string) bool { if c.Search == "" { return true } return slices.ContainsFunc(values, func(v string) bool { return strings.Contains(strings.ToLower(v), strings.ToLower(c.Search)) }) } func (c *searchCriterion) filterService(name string) bool { if c.ServiceName == "" { return true } if strings.Contains(name, "@") { return c.ServiceName == name } before, _, _ := strings.Cut(c.ServiceName, "@") return before == name } func (c *searchCriterion) filterMiddleware(mns []string) bool { if c.MiddlewareName == "" { return true } for _, mn := range mns { if c.MiddlewareName == mn { return true } } return false } func pagination(request *http.Request, maximum int) (pageInfo, error) { perPage, err := getIntParam(request, "per_page", defaultPerPage) if err != nil { return pageInfo{}, err } page, err := getIntParam(request, "page", defaultPage) if err != nil { return pageInfo{}, err } startIndex := (page - 1) * perPage if startIndex != 0 && startIndex >= maximum { return pageInfo{}, fmt.Errorf("invalid request: page: %d, per_page: %d", page, perPage) } endIndex := startIndex + perPage if endIndex >= maximum { endIndex = maximum } nextPage := 1 if page*perPage < maximum { nextPage = page + 1 } return pageInfo{startIndex: startIndex, endIndex: endIndex, nextPage: nextPage}, nil } func getIntParam(request *http.Request, key string, defaultValue int) (int, error) { raw := request.URL.Query().Get(key) if raw == "" { return defaultValue, nil } value, err := strconv.Atoi(raw) if err != nil || value <= 0 { return 0, fmt.Errorf("invalid request: %s: %d", key, value) } return value, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/handler_overview_test.go
pkg/api/handler_overview_test.go
package api import ( "encoding/json" "io" "net/http" "net/http/httptest" "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/config/static" otypes "github.com/traefik/traefik/v3/pkg/observability/types" "github.com/traefik/traefik/v3/pkg/provider/docker" "github.com/traefik/traefik/v3/pkg/provider/file" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/crd" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/ingress" "github.com/traefik/traefik/v3/pkg/provider/rest" ) func TestHandler_Overview(t *testing.T) { type expected struct { statusCode int jsonFile string } testCases := []struct { desc string path string confStatic static.Configuration confDyn runtime.Configuration expected expected }{ { desc: "without data in the dynamic configuration", path: "/api/overview", confStatic: static.Configuration{API: &static.API{}, Global: &static.Global{}}, confDyn: runtime.Configuration{}, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/overview-empty.json", }, }, { desc: "with data in the dynamic configuration", path: "/api/overview", confStatic: static.Configuration{API: &static.API{}, Global: &static.Global{}}, confDyn: runtime.Configuration{ Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{{URL: "http://127.0.0.1"}}, }, }, Status: runtime.StatusEnabled, }, "bar-service@myprovider": { Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{{URL: "http://127.0.0.1"}}, }, }, Status: runtime.StatusWarning, }, "fii-service@myprovider": { Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{{URL: "http://127.0.0.1"}}, }, }, Status: runtime.StatusDisabled, }, }, Middlewares: map[string]*runtime.MiddlewareInfo{ "auth@myprovider": { Middleware: &dynamic.Middleware{ BasicAuth: &dynamic.BasicAuth{ Users: []string{"admin:admin"}, }, }, Status: runtime.StatusEnabled, }, "addPrefixTest@myprovider": { Middleware: &dynamic.Middleware{ AddPrefix: &dynamic.AddPrefix{ Prefix: "/titi", }, }, }, "addPrefixTest@anotherprovider": { Middleware: &dynamic.Middleware{ AddPrefix: &dynamic.AddPrefix{ Prefix: "/toto", }, }, Err: []string{"error"}, Status: runtime.StatusDisabled, }, }, Routers: map[string]*runtime.RouterInfo{ "bar@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", Middlewares: []string{"auth", "addPrefixTest@anotherprovider"}, }, Status: runtime.StatusEnabled, }, "test@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar.other`)", Middlewares: []string{"addPrefixTest", "auth"}, }, Status: runtime.StatusWarning, }, "foo@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar.other`)", Middlewares: []string{"addPrefixTest", "auth"}, }, Status: runtime.StatusDisabled, }, }, TCPServices: map[string]*runtime.TCPServiceInfo{ "tcpfoo-service@myprovider": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.1", }, }, }, }, Status: runtime.StatusEnabled, }, "tcpbar-service@myprovider": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.2", }, }, }, }, Status: runtime.StatusWarning, }, "tcpfii-service@myprovider": { TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.2", }, }, }, }, Status: runtime.StatusDisabled, }, }, TCPMiddlewares: map[string]*runtime.TCPMiddlewareInfo{ "ipallowlist1@myprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, Status: runtime.StatusEnabled, }, "ipallowlist2@myprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, }, "ipallowlist3@myprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, Status: runtime.StatusDisabled, }, }, TCPRouters: map[string]*runtime.TCPRouterInfo{ "tcpbar@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "tcpfoo-service@myprovider", Rule: "HostSNI(`foo.bar`)", }, Status: runtime.StatusEnabled, }, "tcptest@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "tcpfoo-service@myprovider", Rule: "HostSNI(`foo.bar.other`)", }, Status: runtime.StatusWarning, }, "tcpfoo@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "tcpfoo-service@myprovider", Rule: "HostSNI(`foo.bar.other`)", }, Status: runtime.StatusDisabled, }, }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/overview-dynamic.json", }, }, { desc: "with providers", path: "/api/overview", confStatic: static.Configuration{ Global: &static.Global{}, API: &static.API{}, Providers: &static.Providers{ Docker: &docker.Provider{}, Swarm: &docker.SwarmProvider{}, File: &file.Provider{}, KubernetesIngress: &ingress.Provider{}, KubernetesCRD: &crd.Provider{}, Rest: &rest.Provider{}, Plugin: map[string]static.PluginConf{ "test": map[string]interface{}{}, }, }, }, confDyn: runtime.Configuration{}, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/overview-providers.json", }, }, { desc: "with features", path: "/api/overview", confStatic: static.Configuration{ Global: &static.Global{}, API: &static.API{}, Metrics: &otypes.Metrics{ Prometheus: &otypes.Prometheus{}, }, Tracing: &static.Tracing{}, }, confDyn: runtime.Configuration{}, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/overview-features.json", }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := New(test.confStatic, &test.confDyn) server := httptest.NewServer(handler.createRouter()) resp, err := http.DefaultClient.Get(server.URL + test.path) require.NoError(t, err) require.Equal(t, test.expected.statusCode, resp.StatusCode) if test.expected.jsonFile == "" { return } assert.Equal(t, "application/json", resp.Header.Get("Content-Type")) contents, err := io.ReadAll(resp.Body) require.NoError(t, err) err = resp.Body.Close() require.NoError(t, err) if *updateExpected { var results interface{} err := json.Unmarshal(contents, &results) require.NoError(t, err) newJSON, err := json.MarshalIndent(results, "", "\t") require.NoError(t, err) err = os.WriteFile(test.expected.jsonFile, newJSON, 0o644) require.NoError(t, err) } data, err := os.ReadFile(test.expected.jsonFile) require.NoError(t, err) assert.JSONEq(t, string(data), string(contents)) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/handler_support_dump_test.go
pkg/api/handler_support_dump_test.go
package api import ( "archive/tar" "compress/gzip" "errors" "io" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/config/static" ) func TestHandler_SupportDump(t *testing.T) { testCases := []struct { desc string path string confStatic static.Configuration confDyn runtime.Configuration validate func(t *testing.T, files map[string][]byte) }{ { desc: "empty configurations", path: "/api/support-dump", confStatic: static.Configuration{API: &static.API{}, Global: &static.Global{}}, confDyn: runtime.Configuration{}, validate: func(t *testing.T, files map[string][]byte) { t.Helper() require.Contains(t, files, "static-config.json") require.Contains(t, files, "runtime-config.json") require.Contains(t, files, "version.json") // Verify version.json contains version information assert.Contains(t, string(files["version.json"]), `"version":"dev"`) assert.JSONEq(t, `{"global":{},"api":{}}`, string(files["static-config.json"])) assert.Equal(t, `{}`, string(files["runtime-config.json"])) }, }, { desc: "with configuration data", path: "/api/support-dump", confStatic: static.Configuration{ API: &static.API{}, Global: &static.Global{}, EntryPoints: map[string]*static.EntryPoint{ "web": {Address: ":80"}, }, }, confDyn: runtime.Configuration{ Services: map[string]*runtime.ServiceInfo{ "test-service": { Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{{URL: "http://127.0.0.1:8080"}}, }, }, Status: runtime.StatusEnabled, }, }, }, validate: func(t *testing.T, files map[string][]byte) { t.Helper() require.Contains(t, files, "static-config.json") require.Contains(t, files, "runtime-config.json") require.Contains(t, files, "version.json") // Verify version.json contains version information assert.Contains(t, string(files["version.json"]), `"version":"dev"`) // Verify static config contains entry points assert.Contains(t, string(files["static-config.json"]), `"entryPoints":{"web":{"address":"xxxx","http":{}`) // Verify runtime config contains services assert.Contains(t, string(files["runtime-config.json"]), `"services":`) assert.Contains(t, string(files["runtime-config.json"]), `"test-service"`) }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := New(test.confStatic, &test.confDyn) server := httptest.NewServer(handler.createRouter()) resp, err := http.DefaultClient.Get(server.URL + test.path) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) assert.Equal(t, "application/gzip", resp.Header.Get("Content-Type")) assert.Equal(t, `attachment; filename=support-dump.tar.gz`, resp.Header.Get("Content-Disposition")) // Extract and validate the tar.gz contents. files, err := extractTarGz(resp.Body) require.NoError(t, err) test.validate(t, files) }) } } // extractTarGz reads a tar.gz archive and returns a map of filename to contents func extractTarGz(r io.Reader) (map[string][]byte, error) { files := make(map[string][]byte) gzr, err := gzip.NewReader(r) if err != nil { return nil, err } defer gzr.Close() tr := tar.NewReader(gzr) for { header, err := tr.Next() if errors.Is(err, io.EOF) { break } if err != nil { return nil, err } if header.Typeflag != tar.TypeReg { continue } contents, err := io.ReadAll(tr) if err != nil { return nil, err } files[header.Name] = contents } return files, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/handler.go
pkg/api/handler.go
package api import ( "encoding/json" "net/http" "reflect" "strings" "github.com/gorilla/mux" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/config/static" "github.com/traefik/traefik/v3/pkg/version" ) type apiError struct { Message string `json:"message"` } func writeError(rw http.ResponseWriter, msg string, code int) { data, err := json.Marshal(apiError{Message: msg}) if err != nil { http.Error(rw, msg, code) return } http.Error(rw, string(data), code) } type serviceInfoRepresentation struct { *runtime.ServiceInfo ServerStatus map[string]string `json:"serverStatus,omitempty"` } type tcpServiceInfoRepresentation struct { *runtime.TCPServiceInfo ServerStatus map[string]string `json:"serverStatus,omitempty"` } // RunTimeRepresentation is the configuration information exposed by the API handler. type RunTimeRepresentation struct { Routers map[string]*runtime.RouterInfo `json:"routers,omitempty"` Middlewares map[string]*runtime.MiddlewareInfo `json:"middlewares,omitempty"` Services map[string]*serviceInfoRepresentation `json:"services,omitempty"` TCPRouters map[string]*runtime.TCPRouterInfo `json:"tcpRouters,omitempty"` TCPMiddlewares map[string]*runtime.TCPMiddlewareInfo `json:"tcpMiddlewares,omitempty"` TCPServices map[string]*tcpServiceInfoRepresentation `json:"tcpServices,omitempty"` UDPRouters map[string]*runtime.UDPRouterInfo `json:"udpRouters,omitempty"` UDPServices map[string]*runtime.UDPServiceInfo `json:"udpServices,omitempty"` } // Handler serves the configuration and status of Traefik on API endpoints. type Handler struct { staticConfig static.Configuration // runtimeConfiguration is the data set used to create all the data representations exposed by the API. runtimeConfiguration *runtime.Configuration } // NewBuilder returns a http.Handler builder based on runtime.Configuration. func NewBuilder(staticConfig static.Configuration) func(*runtime.Configuration) http.Handler { return func(configuration *runtime.Configuration) http.Handler { return New(staticConfig, configuration).createRouter() } } // New returns a Handler defined by staticConfig, and if provided, by runtimeConfig. // It finishes populating the information provided in the runtimeConfig. func New(staticConfig static.Configuration, runtimeConfig *runtime.Configuration) *Handler { rConfig := runtimeConfig if rConfig == nil { rConfig = &runtime.Configuration{} } return &Handler{ runtimeConfiguration: rConfig, staticConfig: staticConfig, } } // createRouter creates API routes and router. func (h Handler) createRouter() *mux.Router { router := mux.NewRouter().UseEncodedPath() apiRouter := router.PathPrefix(h.staticConfig.API.BasePath).Subrouter().UseEncodedPath() if h.staticConfig.API.Debug { DebugHandler{}.Append(apiRouter) } apiRouter.Methods(http.MethodGet).Path("/api/rawdata").HandlerFunc(h.getRuntimeConfiguration) // Experimental endpoint apiRouter.Methods(http.MethodGet).Path("/api/overview").HandlerFunc(h.getOverview) apiRouter.Methods(http.MethodGet).Path("/api/support-dump").HandlerFunc(h.getSupportDump) apiRouter.Methods(http.MethodGet).Path("/api/entrypoints").HandlerFunc(h.getEntryPoints) apiRouter.Methods(http.MethodGet).Path("/api/entrypoints/{entryPointID}").HandlerFunc(h.getEntryPoint) apiRouter.Methods(http.MethodGet).Path("/api/http/routers").HandlerFunc(h.getRouters) apiRouter.Methods(http.MethodGet).Path("/api/http/routers/{routerID}").HandlerFunc(h.getRouter) apiRouter.Methods(http.MethodGet).Path("/api/http/services").HandlerFunc(h.getServices) apiRouter.Methods(http.MethodGet).Path("/api/http/services/{serviceID}").HandlerFunc(h.getService) apiRouter.Methods(http.MethodGet).Path("/api/http/middlewares").HandlerFunc(h.getMiddlewares) apiRouter.Methods(http.MethodGet).Path("/api/http/middlewares/{middlewareID}").HandlerFunc(h.getMiddleware) apiRouter.Methods(http.MethodGet).Path("/api/tcp/routers").HandlerFunc(h.getTCPRouters) apiRouter.Methods(http.MethodGet).Path("/api/tcp/routers/{routerID}").HandlerFunc(h.getTCPRouter) apiRouter.Methods(http.MethodGet).Path("/api/tcp/services").HandlerFunc(h.getTCPServices) apiRouter.Methods(http.MethodGet).Path("/api/tcp/services/{serviceID}").HandlerFunc(h.getTCPService) apiRouter.Methods(http.MethodGet).Path("/api/tcp/middlewares").HandlerFunc(h.getTCPMiddlewares) apiRouter.Methods(http.MethodGet).Path("/api/tcp/middlewares/{middlewareID}").HandlerFunc(h.getTCPMiddleware) apiRouter.Methods(http.MethodGet).Path("/api/udp/routers").HandlerFunc(h.getUDPRouters) apiRouter.Methods(http.MethodGet).Path("/api/udp/routers/{routerID}").HandlerFunc(h.getUDPRouter) apiRouter.Methods(http.MethodGet).Path("/api/udp/services").HandlerFunc(h.getUDPServices) apiRouter.Methods(http.MethodGet).Path("/api/udp/services/{serviceID}").HandlerFunc(h.getUDPService) version.Handler{}.Append(apiRouter) return router } func (h Handler) getRuntimeConfiguration(rw http.ResponseWriter, request *http.Request) { siRepr := make(map[string]*serviceInfoRepresentation, len(h.runtimeConfiguration.Services)) for k, v := range h.runtimeConfiguration.Services { siRepr[k] = &serviceInfoRepresentation{ ServiceInfo: v, ServerStatus: v.GetAllStatus(), } } tcpSIRepr := make(map[string]*tcpServiceInfoRepresentation, len(h.runtimeConfiguration.Services)) for k, v := range h.runtimeConfiguration.TCPServices { tcpSIRepr[k] = &tcpServiceInfoRepresentation{ TCPServiceInfo: v, ServerStatus: v.GetAllStatus(), } } result := RunTimeRepresentation{ Routers: h.runtimeConfiguration.Routers, Middlewares: h.runtimeConfiguration.Middlewares, Services: siRepr, TCPRouters: h.runtimeConfiguration.TCPRouters, TCPMiddlewares: h.runtimeConfiguration.TCPMiddlewares, TCPServices: tcpSIRepr, UDPRouters: h.runtimeConfiguration.UDPRouters, UDPServices: h.runtimeConfiguration.UDPServices, } rw.Header().Set("Content-Type", "application/json") err := json.NewEncoder(rw).Encode(result) if err != nil { log.Ctx(request.Context()).Error().Err(err).Send() http.Error(rw, err.Error(), http.StatusInternalServerError) } } func getProviderName(id string) string { return strings.SplitN(id, "@", 2)[1] } func extractType(element interface{}) string { v := reflect.ValueOf(element).Elem() for i := range v.NumField() { field := v.Field(i) if field.Kind() == reflect.Map && field.Type().Elem() == reflect.TypeFor[dynamic.PluginConf]() { if keys := field.MapKeys(); len(keys) == 1 { return keys[0].String() } } if field.Kind() == reflect.Ptr && field.Elem().Kind() == reflect.Struct { if !field.IsNil() { return v.Type().Field(i).Name } } } return "" }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/handler_entrypoint_test.go
pkg/api/handler_entrypoint_test.go
package api import ( "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "net/url" "os" "strconv" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/config/static" ) func TestHandler_EntryPoints(t *testing.T) { type expected struct { statusCode int nextPage string jsonFile string } testCases := []struct { desc string path string conf static.Configuration expected expected }{ { desc: "all entry points, but no config", path: "/api/entrypoints", conf: static.Configuration{API: &static.API{}, Global: &static.Global{}}, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/entrypoints-empty.json", }, }, { desc: "all entry points", path: "/api/entrypoints", conf: static.Configuration{ Global: &static.Global{}, API: &static.API{}, EntryPoints: map[string]*static.EntryPoint{ "web": { Address: ":80", Transport: &static.EntryPointsTransport{ LifeCycle: &static.LifeCycle{ RequestAcceptGraceTimeout: 1, GraceTimeOut: 2, }, RespondingTimeouts: &static.RespondingTimeouts{ ReadTimeout: 3, WriteTimeout: 4, IdleTimeout: 5, }, }, ProxyProtocol: &static.ProxyProtocol{ Insecure: true, TrustedIPs: []string{"192.168.1.1", "192.168.1.2"}, }, ForwardedHeaders: &static.ForwardedHeaders{ Insecure: true, TrustedIPs: []string{"192.168.1.3", "192.168.1.4"}, }, }, "websecure": { Address: ":443", Transport: &static.EntryPointsTransport{ LifeCycle: &static.LifeCycle{ RequestAcceptGraceTimeout: 10, GraceTimeOut: 20, }, RespondingTimeouts: &static.RespondingTimeouts{ ReadTimeout: 30, WriteTimeout: 40, IdleTimeout: 50, }, }, ProxyProtocol: &static.ProxyProtocol{ Insecure: true, TrustedIPs: []string{"192.168.1.10", "192.168.1.20"}, }, ForwardedHeaders: &static.ForwardedHeaders{ Insecure: true, TrustedIPs: []string{"192.168.1.30", "192.168.1.40"}, }, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/entrypoints.json", }, }, { desc: "all entry points, pagination, 1 res per page, want page 2", path: "/api/entrypoints?page=2&per_page=1", conf: static.Configuration{ Global: &static.Global{}, API: &static.API{}, EntryPoints: map[string]*static.EntryPoint{ "web1": {Address: ":81"}, "web2": {Address: ":82"}, "web3": {Address: ":83"}, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "3", jsonFile: "testdata/entrypoints-page2.json", }, }, { desc: "all entry points, pagination, 19 results overall, 7 res per page, want page 3", path: "/api/entrypoints?page=3&per_page=7", conf: static.Configuration{ Global: &static.Global{}, API: &static.API{}, EntryPoints: generateEntryPoints(19), }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/entrypoints-many-lastpage.json", }, }, { desc: "all entry points, pagination, 5 results overall, 10 res per page, want page 2", path: "/api/entrypoints?page=2&per_page=10", conf: static.Configuration{ Global: &static.Global{}, API: &static.API{}, EntryPoints: generateEntryPoints(5), }, expected: expected{ statusCode: http.StatusBadRequest, }, }, { desc: "all entry points, pagination, 10 results overall, 10 res per page, want page 2", path: "/api/entrypoints?page=2&per_page=10", conf: static.Configuration{ Global: &static.Global{}, API: &static.API{}, EntryPoints: generateEntryPoints(10), }, expected: expected{ statusCode: http.StatusBadRequest, }, }, { desc: "one entry point by id", path: "/api/entrypoints/bar", conf: static.Configuration{ Global: &static.Global{}, API: &static.API{}, EntryPoints: map[string]*static.EntryPoint{ "bar": {Address: ":81"}, }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/entrypoint-bar.json", }, }, { desc: "one entry point by id containing slash", path: "/api/entrypoints/" + url.PathEscape("foo / bar"), conf: static.Configuration{ Global: &static.Global{}, API: &static.API{}, EntryPoints: map[string]*static.EntryPoint{ "foo / bar": {Address: ":81"}, }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/entrypoint-foo-slash-bar.json", }, }, { desc: "one entry point by id, that does not exist", path: "/api/entrypoints/foo", conf: static.Configuration{ Global: &static.Global{}, API: &static.API{}, EntryPoints: map[string]*static.EntryPoint{ "bar": {Address: ":81"}, }, }, expected: expected{ statusCode: http.StatusNotFound, }, }, { desc: "one entry point by id, but no config", path: "/api/entrypoints/foo", conf: static.Configuration{API: &static.API{}, Global: &static.Global{}}, expected: expected{ statusCode: http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := New(test.conf, &runtime.Configuration{}) server := httptest.NewServer(handler.createRouter()) resp, err := http.DefaultClient.Get(server.URL + test.path) require.NoError(t, err) require.Equal(t, test.expected.statusCode, resp.StatusCode) assert.Equal(t, test.expected.nextPage, resp.Header.Get(nextPageHeader)) if test.expected.jsonFile == "" { return } assert.Equal(t, "application/json", resp.Header.Get("Content-Type")) contents, err := io.ReadAll(resp.Body) require.NoError(t, err) err = resp.Body.Close() require.NoError(t, err) if *updateExpected { var results interface{} err := json.Unmarshal(contents, &results) require.NoError(t, err) newJSON, err := json.MarshalIndent(results, "", "\t") require.NoError(t, err) err = os.WriteFile(test.expected.jsonFile, newJSON, 0o644) require.NoError(t, err) } data, err := os.ReadFile(test.expected.jsonFile) require.NoError(t, err) assert.JSONEq(t, string(data), string(contents)) }) } } func generateEntryPoints(nb int) map[string]*static.EntryPoint { eps := make(map[string]*static.EntryPoint, nb) for i := range nb { eps[fmt.Sprintf("ep%2d", i)] = &static.EntryPoint{ Address: ":" + strconv.Itoa(i), } } return eps }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/handler_http_test.go
pkg/api/handler_http_test.go
package api import ( "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "net/url" "os" "strconv" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/config/static" ) func pointer[T any](v T) *T { return &v } func TestHandler_HTTP(t *testing.T) { type expected struct { statusCode int nextPage string jsonFile string } testCases := []struct { desc string path string conf runtime.Configuration expected expected }{ { desc: "all routers, but no config", path: "/api/http/routers", conf: runtime.Configuration{}, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/routers-empty.json", }, }, { desc: "all routers", path: "/api/http/routers", conf: runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{ "test@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar.other`)", Middlewares: []string{"addPrefixTest", "auth"}, }, }, "bar@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", Middlewares: []string{"auth", "addPrefixTest@anotherprovider"}, }, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/routers.json", }, }, { desc: "all routers, pagination, 1 res per page, want page 2", path: "/api/http/routers?page=2&per_page=1", conf: runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{ "bar@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", Middlewares: []string{"auth", "addPrefixTest@anotherprovider"}, }, }, "baz@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`toto.bar`)", }, }, "test@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar.other`)", Middlewares: []string{"addPrefixTest", "auth"}, }, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "3", jsonFile: "testdata/routers-page2.json", }, }, { desc: "all routers, pagination, 19 results overall, 7 res per page, want page 3", path: "/api/http/routers?page=3&per_page=7", conf: runtime.Configuration{ Routers: generateHTTPRouters(19), }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/routers-many-lastpage.json", }, }, { desc: "all routers, pagination, 5 results overall, 10 res per page, want page 2", path: "/api/http/routers?page=2&per_page=10", conf: runtime.Configuration{ Routers: generateHTTPRouters(5), }, expected: expected{ statusCode: http.StatusBadRequest, }, }, { desc: "all routers, pagination, 10 results overall, 10 res per page, want page 2", path: "/api/http/routers?page=2&per_page=10", conf: runtime.Configuration{ Routers: generateHTTPRouters(10), }, expected: expected{ statusCode: http.StatusBadRequest, }, }, { desc: "routers filtered by status", path: "/api/http/routers?status=enabled", conf: runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{ "test@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar.other`)", Middlewares: []string{"addPrefixTest", "auth"}, }, Status: runtime.StatusEnabled, }, "bar@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", Middlewares: []string{"auth", "addPrefixTest@anotherprovider"}, }, Status: runtime.StatusDisabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/routers-filtered-status.json", }, }, { desc: "routers filtered by search", path: "/api/http/routers?search=fii", conf: runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{ "test@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "fii-service@myprovider", Rule: "Host(`fii.bar.other`)", Middlewares: []string{"addPrefixTest", "auth"}, }, Status: runtime.StatusEnabled, }, "bar@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", Middlewares: []string{"auth", "addPrefixTest@anotherprovider"}, }, Status: runtime.StatusDisabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/routers-filtered-search.json", }, }, { desc: "routers filtered by service", path: "/api/http/routers?serviceName=fii-service@myprovider", conf: runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{ "test@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "fii-service@myprovider", Rule: "Host(`fii.bar.other`)", Middlewares: []string{"addPrefixTest", "auth"}, }, Status: runtime.StatusEnabled, }, "foo@otherprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "fii-service", Rule: "Host(`fii.foo.other`)", }, Status: runtime.StatusEnabled, }, "bar@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", Middlewares: []string{"auth", "addPrefixTest@anotherprovider"}, }, Status: runtime.StatusDisabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/routers-filtered-serviceName.json", }, }, { desc: "routers filtered by middleware", path: "/api/http/routers?middlewareName=auth", conf: runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{ "test@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "fii-service@myprovider", Rule: "Host(`fii.bar.other`)", Middlewares: []string{"addPrefixTest", "auth"}, }, Status: runtime.StatusEnabled, }, "foo@otherprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "fii-service", Rule: "Host(`fii.foo.other`)", }, Status: runtime.StatusEnabled, }, "bar@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", Middlewares: []string{"auth", "addPrefixTest@anotherprovider"}, }, Status: runtime.StatusDisabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/routers-filtered-middlewareName.json", }, }, { desc: "one router by id", path: "/api/http/routers/bar@myprovider", conf: runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{ "bar@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", Middlewares: []string{"auth", "addPrefixTest@anotherprovider"}, }, Status: "enabled", }, }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/router-bar.json", }, }, { desc: "one router by id containing slash", path: "/api/http/routers/" + url.PathEscape("foo / bar@myprovider"), conf: runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{ "foo / bar@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", Middlewares: []string{"auth", "addPrefixTest@anotherprovider"}, }, Status: "enabled", }, }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/router-foo-slash-bar.json", }, }, { desc: "one router by id, implicitly using default TLS options", path: "/api/http/routers/baz@myprovider", conf: runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{ "baz@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.baz`)", Middlewares: []string{"auth", "addPrefixTest@anotherprovider"}, TLS: &dynamic.RouterTLSConfig{}, }, Status: "enabled", }, }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/router-baz-default-tls-options.json", }, }, { desc: "one router by id, using specific TLS options", path: "/api/http/routers/baz@myprovider", conf: runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{ "baz@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.baz`)", Middlewares: []string{"auth", "addPrefixTest@anotherprovider"}, TLS: &dynamic.RouterTLSConfig{ Options: "myTLS", }, }, Status: "enabled", }, }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/router-baz-custom-tls-options.json", }, }, { desc: "one router by id, that does not exist", path: "/api/http/routers/foo@myprovider", conf: runtime.Configuration{ Routers: map[string]*runtime.RouterInfo{ "bar@myprovider": { Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", Middlewares: []string{"auth", "addPrefixTest@anotherprovider"}, }, }, }, }, expected: expected{ statusCode: http.StatusNotFound, }, }, { desc: "one router by id, but no config", path: "/api/http/routers/foo@myprovider", conf: runtime.Configuration{}, expected: expected{ statusCode: http.StatusNotFound, }, }, { desc: "all services, but no config", path: "/api/http/services", conf: runtime.Configuration{}, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/services-empty.json", }, }, { desc: "all services", path: "/api/http/services", conf: runtime.Configuration{ Services: map[string]*runtime.ServiceInfo{ "bar@myprovider": func() *runtime.ServiceInfo { si := &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: pointer(true), Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, } si.UpdateServerStatus("http://127.0.0.1", "UP") return si }(), "baz@myprovider": func() *runtime.ServiceInfo { si := &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: pointer(true), Servers: []dynamic.Server{ { URL: "http://127.0.0.2", }, }, }, }, UsedBy: []string{"foo@myprovider"}, } si.UpdateServerStatus("http://127.0.0.2", "UP") return si }(), "canary@myprovider": { Service: &dynamic.Service{ Weighted: &dynamic.WeightedRoundRobin{ Services: nil, Sticky: &dynamic.Sticky{ Cookie: &dynamic.Cookie{ Name: "chocolat", Secure: true, HTTPOnly: true, }, }, }, }, Status: runtime.StatusEnabled, UsedBy: []string{"foo@myprovider"}, }, "mirror@myprovider": { Service: &dynamic.Service{ Mirroring: &dynamic.Mirroring{ Service: "one@myprovider", Mirrors: []dynamic.MirrorService{ { Name: "two@myprovider", Percent: 10, }, { Name: "three@myprovider", Percent: 15, }, { Name: "four@myprovider", Percent: 80, }, }, }, }, Status: runtime.StatusEnabled, UsedBy: []string{"foo@myprovider"}, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/services.json", }, }, { desc: "all services, 1 res per page, want page 2", path: "/api/http/services?page=2&per_page=1", conf: runtime.Configuration{ Services: map[string]*runtime.ServiceInfo{ "bar@myprovider": func() *runtime.ServiceInfo { si := &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: pointer(true), Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, } si.UpdateServerStatus("http://127.0.0.1", "UP") return si }(), "baz@myprovider": func() *runtime.ServiceInfo { si := &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: pointer(true), Servers: []dynamic.Server{ { URL: "http://127.0.0.2", }, }, }, }, UsedBy: []string{"foo@myprovider"}, } si.UpdateServerStatus("http://127.0.0.2", "UP") return si }(), "test@myprovider": func() *runtime.ServiceInfo { si := &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: pointer(true), Servers: []dynamic.Server{ { URL: "http://127.0.0.3", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, } si.UpdateServerStatus("http://127.0.0.4", "UP") return si }(), }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "3", jsonFile: "testdata/services-page2.json", }, }, { desc: "services filtered by status", path: "/api/http/services?status=enabled", conf: runtime.Configuration{ Services: map[string]*runtime.ServiceInfo{ "bar@myprovider": func() *runtime.ServiceInfo { si := &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: pointer(true), Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, Status: runtime.StatusEnabled, } si.UpdateServerStatus("http://127.0.0.1", "UP") return si }(), "baz@myprovider": func() *runtime.ServiceInfo { si := &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: pointer(true), Servers: []dynamic.Server{ { URL: "http://127.0.0.2", }, }, }, }, UsedBy: []string{"foo@myprovider"}, Status: runtime.StatusDisabled, } si.UpdateServerStatus("http://127.0.0.2", "UP") return si }(), }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/services-filtered-status.json", }, }, { desc: "services filtered by search", path: "/api/http/services?search=baz", conf: runtime.Configuration{ Services: map[string]*runtime.ServiceInfo{ "bar@myprovider": func() *runtime.ServiceInfo { si := &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: pointer(true), Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, Status: runtime.StatusEnabled, } si.UpdateServerStatus("http://127.0.0.1", "UP") return si }(), "baz@myprovider": func() *runtime.ServiceInfo { si := &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: pointer(true), Servers: []dynamic.Server{ { URL: "http://127.0.0.2", }, }, }, }, UsedBy: []string{"foo@myprovider"}, Status: runtime.StatusDisabled, } si.UpdateServerStatus("http://127.0.0.2", "UP") return si }(), }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/services-filtered-search.json", }, }, { desc: "one service by id", path: "/api/http/services/bar@myprovider", conf: runtime.Configuration{ Services: map[string]*runtime.ServiceInfo{ "bar@myprovider": func() *runtime.ServiceInfo { si := &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: pointer(true), Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, } si.UpdateServerStatus("http://127.0.0.1", "UP") return si }(), }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/service-bar.json", }, }, { desc: "one service by id containing slash", path: "/api/http/services/" + url.PathEscape("foo / bar@myprovider"), conf: runtime.Configuration{ Services: map[string]*runtime.ServiceInfo{ "foo / bar@myprovider": func() *runtime.ServiceInfo { si := &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: pointer(true), Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, } si.UpdateServerStatus("http://127.0.0.1", "UP") return si }(), }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/service-foo-slash-bar.json", }, }, { desc: "one service by id, that does not exist", path: "/api/http/services/nono@myprovider", conf: runtime.Configuration{ Services: map[string]*runtime.ServiceInfo{ "bar@myprovider": func() *runtime.ServiceInfo { si := &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: pointer(true), Servers: []dynamic.Server{ { URL: "http://127.0.0.1", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, } si.UpdateServerStatus("http://127.0.0.1", "UP") return si }(), }, }, expected: expected{ statusCode: http.StatusNotFound, }, }, { desc: "one service by id, but no config", path: "/api/http/services/foo@myprovider", conf: runtime.Configuration{}, expected: expected{ statusCode: http.StatusNotFound, }, }, { desc: "all middlewares, but no config", path: "/api/http/middlewares", conf: runtime.Configuration{}, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/middlewares-empty.json", }, }, { desc: "all middlewares", path: "/api/http/middlewares", conf: runtime.Configuration{ Middlewares: map[string]*runtime.MiddlewareInfo{ "auth@myprovider": { Middleware: &dynamic.Middleware{ BasicAuth: &dynamic.BasicAuth{ Users: []string{"admin:admin"}, }, }, UsedBy: []string{"bar@myprovider", "test@myprovider"}, }, "addPrefixTest@myprovider": { Middleware: &dynamic.Middleware{ AddPrefix: &dynamic.AddPrefix{ Prefix: "/titi", }, }, UsedBy: []string{"test@myprovider"}, }, "addPrefixTest@anotherprovider": { Middleware: &dynamic.Middleware{ AddPrefix: &dynamic.AddPrefix{ Prefix: "/toto", }, }, UsedBy: []string{"bar@myprovider"}, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/middlewares.json", }, }, { desc: "middlewares filtered by status", path: "/api/http/middlewares?status=enabled", conf: runtime.Configuration{ Middlewares: map[string]*runtime.MiddlewareInfo{ "auth@myprovider": { Middleware: &dynamic.Middleware{ BasicAuth: &dynamic.BasicAuth{ Users: []string{"admin:admin"}, }, }, UsedBy: []string{"bar@myprovider", "test@myprovider"}, Status: runtime.StatusEnabled, }, "addPrefixTest@myprovider": { Middleware: &dynamic.Middleware{ AddPrefix: &dynamic.AddPrefix{ Prefix: "/titi", }, }, UsedBy: []string{"test@myprovider"}, Status: runtime.StatusDisabled, }, "addPrefixTest@anotherprovider": { Middleware: &dynamic.Middleware{ AddPrefix: &dynamic.AddPrefix{ Prefix: "/toto", }, }, UsedBy: []string{"bar@myprovider"}, Status: runtime.StatusEnabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/middlewares-filtered-status.json", }, }, { desc: "middlewares filtered by search", path: "/api/http/middlewares?search=addprefixtest", conf: runtime.Configuration{ Middlewares: map[string]*runtime.MiddlewareInfo{ "auth@myprovider": { Middleware: &dynamic.Middleware{ BasicAuth: &dynamic.BasicAuth{ Users: []string{"admin:admin"}, }, }, UsedBy: []string{"bar@myprovider", "test@myprovider"}, Status: runtime.StatusEnabled, }, "addPrefixTest@myprovider": { Middleware: &dynamic.Middleware{ AddPrefix: &dynamic.AddPrefix{ Prefix: "/titi", }, }, UsedBy: []string{"test@myprovider"}, Status: runtime.StatusDisabled, }, "addPrefixTest@anotherprovider": { Middleware: &dynamic.Middleware{ AddPrefix: &dynamic.AddPrefix{ Prefix: "/toto", }, }, UsedBy: []string{"bar@myprovider"}, Status: runtime.StatusEnabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/middlewares-filtered-search.json", }, }, { desc: "all middlewares, 1 res per page, want page 2", path: "/api/http/middlewares?page=2&per_page=1", conf: runtime.Configuration{ Middlewares: map[string]*runtime.MiddlewareInfo{ "auth@myprovider": { Middleware: &dynamic.Middleware{ BasicAuth: &dynamic.BasicAuth{ Users: []string{"admin:admin"}, }, }, UsedBy: []string{"bar@myprovider", "test@myprovider"}, }, "addPrefixTest@myprovider": { Middleware: &dynamic.Middleware{ AddPrefix: &dynamic.AddPrefix{ Prefix: "/titi", }, }, UsedBy: []string{"test@myprovider"}, }, "addPrefixTest@anotherprovider": { Middleware: &dynamic.Middleware{ AddPrefix: &dynamic.AddPrefix{ Prefix: "/toto", }, }, UsedBy: []string{"bar@myprovider"}, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "3", jsonFile: "testdata/middlewares-page2.json", }, }, { desc: "one middleware by id", path: "/api/http/middlewares/auth@myprovider", conf: runtime.Configuration{ Middlewares: map[string]*runtime.MiddlewareInfo{ "auth@myprovider": { Middleware: &dynamic.Middleware{ BasicAuth: &dynamic.BasicAuth{ Users: []string{"admin:admin"}, }, }, UsedBy: []string{"bar@myprovider", "test@myprovider"}, }, "addPrefixTest@myprovider": { Middleware: &dynamic.Middleware{ AddPrefix: &dynamic.AddPrefix{ Prefix: "/titi", }, }, UsedBy: []string{"test@myprovider"}, }, "addPrefixTest@anotherprovider": { Middleware: &dynamic.Middleware{ AddPrefix: &dynamic.AddPrefix{ Prefix: "/toto", }, }, UsedBy: []string{"bar@myprovider"}, }, }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/middleware-auth.json", }, }, { desc: "one middleware by id containing slash", path: "/api/http/middlewares/" + url.PathEscape("foo / bar@myprovider"), conf: runtime.Configuration{ Middlewares: map[string]*runtime.MiddlewareInfo{ "foo / bar@myprovider": { Middleware: &dynamic.Middleware{ AddPrefix: &dynamic.AddPrefix{ Prefix: "/titi", }, }, UsedBy: []string{"test@myprovider"}, }, }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/middleware-foo-slash-bar.json", }, }, { desc: "one middleware by id, that does not exist", path: "/api/http/middlewares/foo@myprovider", conf: runtime.Configuration{ Middlewares: map[string]*runtime.MiddlewareInfo{ "auth@myprovider": { Middleware: &dynamic.Middleware{ BasicAuth: &dynamic.BasicAuth{ Users: []string{"admin:admin"}, }, }, UsedBy: []string{"bar@myprovider", "test@myprovider"}, }, }, }, expected: expected{ statusCode: http.StatusNotFound, }, }, { desc: "one middleware by id, but no config", path: "/api/http/middlewares/foo@myprovider", conf: runtime.Configuration{}, expected: expected{ statusCode: http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() rtConf := &test.conf // To lazily initialize the Statuses. rtConf.PopulateUsedBy() rtConf.GetRoutersByEntryPoints(t.Context(), []string{"web"}, false) rtConf.GetRoutersByEntryPoints(t.Context(), []string{"web"}, true) handler := New(static.Configuration{API: &static.API{}, Global: &static.Global{}}, rtConf) server := httptest.NewServer(handler.createRouter()) resp, err := http.DefaultClient.Get(server.URL + test.path) require.NoError(t, err) require.Equal(t, test.expected.statusCode, resp.StatusCode) assert.Equal(t, test.expected.nextPage, resp.Header.Get(nextPageHeader)) if test.expected.jsonFile == "" { return } assert.Equal(t, "application/json", resp.Header.Get("Content-Type")) contents, err := io.ReadAll(resp.Body) require.NoError(t, err) err = resp.Body.Close() require.NoError(t, err) if *updateExpected { var results interface{} err := json.Unmarshal(contents, &results) require.NoError(t, err) newJSON, err := json.MarshalIndent(results, "", "\t") require.NoError(t, err) err = os.WriteFile(test.expected.jsonFile, newJSON, 0o644) require.NoError(t, err) } data, err := os.ReadFile(test.expected.jsonFile) require.NoError(t, err) assert.JSONEq(t, string(data), string(contents)) }) } } func generateHTTPRouters(nbRouters int) map[string]*runtime.RouterInfo { routers := make(map[string]*runtime.RouterInfo, nbRouters) for i := range nbRouters { routers[fmt.Sprintf("bar%2d@myprovider", i)] = &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar" + strconv.Itoa(i) + "`)", }, } } return routers }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/handler_tcp_test.go
pkg/api/handler_tcp_test.go
package api import ( "encoding/json" "io" "net/http" "net/http/httptest" "net/url" "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" "github.com/traefik/traefik/v3/pkg/config/static" ) func TestHandler_TCP(t *testing.T) { type expected struct { statusCode int nextPage string jsonFile string } testCases := []struct { desc string path string conf runtime.Configuration expected expected }{ { desc: "all TCP routers, but no config", path: "/api/tcp/routers", conf: runtime.Configuration{}, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/tcprouters-empty.json", }, }, { desc: "all TCP routers", path: "/api/tcp/routers", conf: runtime.Configuration{ TCPRouters: map[string]*runtime.TCPRouterInfo{ "test@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar.other`)", TLS: &dynamic.RouterTCPTLSConfig{ Passthrough: false, }, }, Status: runtime.StatusEnabled, }, "bar@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", }, Status: runtime.StatusWarning, }, "foo@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", }, Status: runtime.StatusDisabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/tcprouters.json", }, }, { desc: "all TCP routers, pagination, 1 res per page, want page 2", path: "/api/tcp/routers?page=2&per_page=1", conf: runtime.Configuration{ TCPRouters: map[string]*runtime.TCPRouterInfo{ "bar@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", }, }, "baz@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`toto.bar`)", }, }, "test@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar.other`)", }, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "3", jsonFile: "testdata/tcprouters-page2.json", }, }, { desc: "TCP routers filtered by status", path: "/api/tcp/routers?status=enabled", conf: runtime.Configuration{ TCPRouters: map[string]*runtime.TCPRouterInfo{ "test@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar.other`)", TLS: &dynamic.RouterTCPTLSConfig{ Passthrough: false, }, }, Status: runtime.StatusEnabled, }, "bar@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", }, Status: runtime.StatusWarning, }, "foo@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", }, Status: runtime.StatusDisabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/tcprouters-filtered-status.json", }, }, { desc: "TCP routers filtered by search", path: "/api/tcp/routers?search=bar@my", conf: runtime.Configuration{ TCPRouters: map[string]*runtime.TCPRouterInfo{ "test@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar.other`)", TLS: &dynamic.RouterTCPTLSConfig{ Passthrough: false, }, }, Status: runtime.StatusEnabled, }, "bar@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", }, Status: runtime.StatusWarning, }, "foo@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", }, Status: runtime.StatusDisabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/tcprouters-filtered-search.json", }, }, { desc: "TCP routers filtered by service", path: "/api/tcp/routers?serviceName=foo-service@myprovider", conf: runtime.Configuration{ TCPRouters: map[string]*runtime.TCPRouterInfo{ "test@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar.other`)", TLS: &dynamic.RouterTCPTLSConfig{ Passthrough: false, }, }, Status: runtime.StatusEnabled, }, "bar@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`foo.bar`)", }, Status: runtime.StatusWarning, }, "foo@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "bar-service@myprovider", Rule: "Host(`foo.bar`)", }, Status: runtime.StatusDisabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/tcprouters-filtered-serviceName.json", }, }, { desc: "TCP routers filtered by middleware", path: "/api/tcp/routers?middlewareName=auth", conf: runtime.Configuration{ TCPRouters: map[string]*runtime.TCPRouterInfo{ "test@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar.other`)", Middlewares: []string{"inflightconn@myprovider"}, TLS: &dynamic.RouterTCPTLSConfig{ Passthrough: false, }, }, Status: runtime.StatusEnabled, }, "bar@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service", Rule: "Host(`foo.bar`)", Middlewares: []string{"auth", "inflightconn@myprovider"}, }, Status: runtime.StatusWarning, }, "foo@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "bar-service@myprovider", Rule: "Host(`foo.bar`)", Middlewares: []string{"inflightconn@myprovider", "auth"}, }, Status: runtime.StatusDisabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/tcprouters-filtered-middlewareName.json", }, }, { desc: "one TCP router by id", path: "/api/tcp/routers/bar@myprovider", conf: runtime.Configuration{ TCPRouters: map[string]*runtime.TCPRouterInfo{ "bar@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", }, }, }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/tcprouter-bar.json", }, }, { desc: "one TCP router by id containing slash", path: "/api/tcp/routers/" + url.PathEscape("foo / bar@myprovider"), conf: runtime.Configuration{ TCPRouters: map[string]*runtime.TCPRouterInfo{ "foo / bar@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", }, }, }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/tcprouter-foo-slash-bar.json", }, }, { desc: "one TCP router by id, that does not exist", path: "/api/tcp/routers/foo@myprovider", conf: runtime.Configuration{ TCPRouters: map[string]*runtime.TCPRouterInfo{ "bar@myprovider": { TCPRouter: &dynamic.TCPRouter{ EntryPoints: []string{"web"}, Service: "foo-service@myprovider", Rule: "Host(`foo.bar`)", }, }, }, }, expected: expected{ statusCode: http.StatusNotFound, }, }, { desc: "one TCP router by id, but no config", path: "/api/tcp/routers/bar@myprovider", conf: runtime.Configuration{}, expected: expected{ statusCode: http.StatusNotFound, }, }, { desc: "all tcp services, but no config", path: "/api/tcp/services", conf: runtime.Configuration{}, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/tcpservices-empty.json", }, }, { desc: "all tcp services", path: "/api/tcp/services", conf: runtime.Configuration{ TCPServices: map[string]*runtime.TCPServiceInfo{ "bar@myprovider": func() *runtime.TCPServiceInfo { si := &runtime.TCPServiceInfo{ TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.1:2345", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, Status: runtime.StatusEnabled, } si.UpdateServerStatus("127.0.0.1:2345", "UP") return si }(), "baz@myprovider": func() *runtime.TCPServiceInfo { si := &runtime.TCPServiceInfo{ TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.2:2345", }, }, }, }, UsedBy: []string{"foo@myprovider"}, Status: runtime.StatusWarning, } si.UpdateServerStatus("127.0.0.2:2345", "UP") return si }(), "foz@myprovider": func() *runtime.TCPServiceInfo { si := &runtime.TCPServiceInfo{ TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.3:2345", }, }, }, }, UsedBy: []string{"foo@myprovider"}, Status: runtime.StatusDisabled, } si.UpdateServerStatus("127.0.0.3:2345", "UP") return si }(), }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/tcpservices.json", }, }, { desc: "tcp services filtered by status", path: "/api/tcp/services?status=enabled", conf: runtime.Configuration{ TCPServices: map[string]*runtime.TCPServiceInfo{ "bar@myprovider": func() *runtime.TCPServiceInfo { si := &runtime.TCPServiceInfo{ TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.1:2345", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, Status: runtime.StatusEnabled, } si.UpdateServerStatus("127.0.0.1:2345", "UP") return si }(), "baz@myprovider": func() *runtime.TCPServiceInfo { si := &runtime.TCPServiceInfo{ TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.2:2345", }, }, }, }, UsedBy: []string{"foo@myprovider"}, Status: runtime.StatusWarning, } si.UpdateServerStatus("127.0.0.2:2345", "UP") return si }(), "foz@myprovider": func() *runtime.TCPServiceInfo { si := &runtime.TCPServiceInfo{ TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.3:2345", }, }, }, }, UsedBy: []string{"foo@myprovider"}, Status: runtime.StatusDisabled, } si.UpdateServerStatus("127.0.0.3:2345", "UP") return si }(), }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/tcpservices-filtered-status.json", }, }, { desc: "tcp services filtered by search", path: "/api/tcp/services?search=baz@my", conf: runtime.Configuration{ TCPServices: map[string]*runtime.TCPServiceInfo{ "bar@myprovider": func() *runtime.TCPServiceInfo { si := &runtime.TCPServiceInfo{ TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.1:2345", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, Status: runtime.StatusEnabled, } si.UpdateServerStatus("127.0.0.1:2345", "UP") return si }(), "baz@myprovider": func() *runtime.TCPServiceInfo { si := &runtime.TCPServiceInfo{ TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.2:2345", }, }, }, }, UsedBy: []string{"foo@myprovider"}, Status: runtime.StatusWarning, } si.UpdateServerStatus("127.0.0.2:2345", "UP") return si }(), "foz@myprovider": func() *runtime.TCPServiceInfo { si := &runtime.TCPServiceInfo{ TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.3:2345", }, }, }, }, UsedBy: []string{"foo@myprovider"}, Status: runtime.StatusDisabled, } si.UpdateServerStatus("127.0.0.3:2345", "UP") return si }(), }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/tcpservices-filtered-search.json", }, }, { desc: "all tcp services, 1 res per page, want page 2", path: "/api/tcp/services?page=2&per_page=1", conf: runtime.Configuration{ TCPServices: map[string]*runtime.TCPServiceInfo{ "bar@myprovider": func() *runtime.TCPServiceInfo { si := &runtime.TCPServiceInfo{ TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.1:2345", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, } si.UpdateServerStatus("127.0.0.1:2345", "UP") return si }(), "baz@myprovider": func() *runtime.TCPServiceInfo { si := &runtime.TCPServiceInfo{ TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.2:2345", }, }, }, }, UsedBy: []string{"foo@myprovider"}, } si.UpdateServerStatus("127.0.0.2:2345", "UP") return si }(), "test@myprovider": func() *runtime.TCPServiceInfo { si := &runtime.TCPServiceInfo{ TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.3:2345", }, }, }, }, } si.UpdateServerStatus("127.0.0.3:2345", "UP") return si }(), }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "3", jsonFile: "testdata/tcpservices-page2.json", }, }, { desc: "one tcp service by id", path: "/api/tcp/services/bar@myprovider", conf: runtime.Configuration{ TCPServices: map[string]*runtime.TCPServiceInfo{ "bar@myprovider": func() *runtime.TCPServiceInfo { si := &runtime.TCPServiceInfo{ TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.1:2345", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, } si.UpdateServerStatus("127.0.0.1:2345", "UP") return si }(), }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/tcpservice-bar.json", }, }, { desc: "one tcp service by id containing slash", path: "/api/tcp/services/" + url.PathEscape("foo / bar@myprovider"), conf: runtime.Configuration{ TCPServices: map[string]*runtime.TCPServiceInfo{ "foo / bar@myprovider": func() *runtime.TCPServiceInfo { si := &runtime.TCPServiceInfo{ TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.1:2345", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, } si.UpdateServerStatus("127.0.0.1:2345", "UP") return si }(), }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/tcpservice-foo-slash-bar.json", }, }, { desc: "one tcp service by id, that does not exist", path: "/api/tcp/services/nono@myprovider", conf: runtime.Configuration{ TCPServices: map[string]*runtime.TCPServiceInfo{ "bar@myprovider": func() *runtime.TCPServiceInfo { si := &runtime.TCPServiceInfo{ TCPService: &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "127.0.0.1:2345", }, }, }, }, UsedBy: []string{"foo@myprovider", "test@myprovider"}, } si.UpdateServerStatus("127.0.0.1:2345", "UP") return si }(), }, }, expected: expected{ statusCode: http.StatusNotFound, }, }, { desc: "one tcp service by id, but no config", path: "/api/tcp/services/foo@myprovider", conf: runtime.Configuration{}, expected: expected{ statusCode: http.StatusNotFound, }, }, { desc: "all middlewares", path: "/api/tcp/middlewares", conf: runtime.Configuration{ TCPMiddlewares: map[string]*runtime.TCPMiddlewareInfo{ "ipallowlist1@myprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, UsedBy: []string{"bar@myprovider", "test@myprovider"}, }, "ipallowlist2@myprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.2/32"}, }, }, UsedBy: []string{"test@myprovider"}, }, "ipallowlist1@anotherprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, UsedBy: []string{"bar@myprovider"}, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/tcpmiddlewares.json", }, }, { desc: "middlewares filtered by status", path: "/api/tcp/middlewares?status=enabled", conf: runtime.Configuration{ TCPMiddlewares: map[string]*runtime.TCPMiddlewareInfo{ "ipallowlist@myprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, UsedBy: []string{"bar@myprovider", "test@myprovider"}, Status: runtime.StatusEnabled, }, "ipallowlist2@myprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.2/32"}, }, }, UsedBy: []string{"test@myprovider"}, Status: runtime.StatusDisabled, }, "ipallowlist@anotherprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, UsedBy: []string{"bar@myprovider"}, Status: runtime.StatusEnabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/tcpmiddlewares-filtered-status.json", }, }, { desc: "middlewares filtered by search", path: "/api/tcp/middlewares?search=ipallowlist", conf: runtime.Configuration{ TCPMiddlewares: map[string]*runtime.TCPMiddlewareInfo{ "bad@myprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, UsedBy: []string{"bar@myprovider", "test@myprovider"}, Status: runtime.StatusEnabled, }, "ipallowlist@myprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, UsedBy: []string{"test@myprovider"}, Status: runtime.StatusDisabled, }, "ipallowlist@anotherprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, UsedBy: []string{"bar@myprovider"}, Status: runtime.StatusEnabled, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "1", jsonFile: "testdata/tcpmiddlewares-filtered-search.json", }, }, { desc: "all middlewares, 1 res per page, want page 2", path: "/api/tcp/middlewares?page=2&per_page=1", conf: runtime.Configuration{ TCPMiddlewares: map[string]*runtime.TCPMiddlewareInfo{ "ipallowlist@myprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, UsedBy: []string{"bar@myprovider", "test@myprovider"}, }, "ipallowlist2@myprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.2/32"}, }, }, UsedBy: []string{"test@myprovider"}, }, "ipallowlist@anotherprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, UsedBy: []string{"bar@myprovider"}, }, }, }, expected: expected{ statusCode: http.StatusOK, nextPage: "3", jsonFile: "testdata/tcpmiddlewares-page2.json", }, }, { desc: "one middleware by id", path: "/api/tcp/middlewares/ipallowlist@myprovider", conf: runtime.Configuration{ TCPMiddlewares: map[string]*runtime.TCPMiddlewareInfo{ "ipallowlist@myprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, UsedBy: []string{"bar@myprovider", "test@myprovider"}, }, "ipallowlist2@myprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.2/32"}, }, }, UsedBy: []string{"test@myprovider"}, }, "ipallowlist@anotherprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, UsedBy: []string{"bar@myprovider"}, }, }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/tcpmiddleware-ipallowlist.json", }, }, { desc: "one middleware by id containing slash", path: "/api/tcp/middlewares/" + url.PathEscape("foo / bar@myprovider"), conf: runtime.Configuration{ TCPMiddlewares: map[string]*runtime.TCPMiddlewareInfo{ "foo / bar@myprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPWhiteList: &dynamic.TCPIPWhiteList{ SourceRange: []string{"127.0.0.1/32"}, }, }, UsedBy: []string{"bar@myprovider", "test@myprovider"}, }, }, }, expected: expected{ statusCode: http.StatusOK, jsonFile: "testdata/tcpmiddleware-foo-slash-bar.json", }, }, { desc: "one middleware by id, that does not exist", path: "/api/tcp/middlewares/foo@myprovider", conf: runtime.Configuration{ TCPMiddlewares: map[string]*runtime.TCPMiddlewareInfo{ "ipallowlist@myprovider": { TCPMiddleware: &dynamic.TCPMiddleware{ IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, UsedBy: []string{"bar@myprovider", "test@myprovider"}, }, }, }, expected: expected{ statusCode: http.StatusNotFound, }, }, { desc: "one middleware by id, but no config", path: "/api/tcp/middlewares/foo@myprovider", conf: runtime.Configuration{}, expected: expected{ statusCode: http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() rtConf := &test.conf // To lazily initialize the Statuses. rtConf.PopulateUsedBy() rtConf.GetTCPRoutersByEntryPoints(t.Context(), []string{"web"}) handler := New(static.Configuration{API: &static.API{}, Global: &static.Global{}}, rtConf) server := httptest.NewServer(handler.createRouter()) resp, err := http.DefaultClient.Get(server.URL + test.path) require.NoError(t, err) assert.Equal(t, test.expected.nextPage, resp.Header.Get(nextPageHeader)) require.Equal(t, test.expected.statusCode, resp.StatusCode) if test.expected.jsonFile == "" { return } assert.Equal(t, "application/json", resp.Header.Get("Content-Type")) contents, err := io.ReadAll(resp.Body) require.NoError(t, err) err = resp.Body.Close() require.NoError(t, err) if *updateExpected { var results interface{} err := json.Unmarshal(contents, &results) require.NoError(t, err) newJSON, err := json.MarshalIndent(results, "", "\t") require.NoError(t, err) err = os.WriteFile(test.expected.jsonFile, newJSON, 0o644) require.NoError(t, err) } data, err := os.ReadFile(test.expected.jsonFile) require.NoError(t, err) assert.JSONEq(t, string(data), string(contents)) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/sort_test.go
pkg/api/sort_test.go
package api import ( "fmt" "net/url" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/runtime" ) func TestSortRouters(t *testing.T) { testCases := []struct { direction string sortBy string elements []orderedRouter expected []orderedRouter }{ { direction: ascendantSorting, sortBy: "name", elements: []orderedRouter{ routerRepresentation{ Name: "b", }, routerRepresentation{ Name: "a", }, }, expected: []orderedRouter{ routerRepresentation{ Name: "a", }, routerRepresentation{ Name: "b", }, }, }, { direction: descendantSorting, sortBy: "name", elements: []orderedRouter{ routerRepresentation{ Name: "a", }, routerRepresentation{ Name: "b", }, }, expected: []orderedRouter{ routerRepresentation{ Name: "b", }, routerRepresentation{ Name: "a", }, }, }, { direction: ascendantSorting, sortBy: "provider", elements: []orderedRouter{ routerRepresentation{ Name: "b", Provider: "b", }, routerRepresentation{ Name: "b", Provider: "a", }, routerRepresentation{ Name: "a", Provider: "b", }, routerRepresentation{ Name: "a", Provider: "a", }, }, expected: []orderedRouter{ routerRepresentation{ Name: "a", Provider: "a", }, routerRepresentation{ Name: "b", Provider: "a", }, routerRepresentation{ Name: "a", Provider: "b", }, routerRepresentation{ Name: "b", Provider: "b", }, }, }, { direction: descendantSorting, sortBy: "provider", elements: []orderedRouter{ routerRepresentation{ Name: "a", Provider: "a", }, routerRepresentation{ Name: "a", Provider: "b", }, routerRepresentation{ Name: "b", Provider: "a", }, routerRepresentation{ Name: "b", Provider: "b", }, }, expected: []orderedRouter{ routerRepresentation{ Name: "b", Provider: "b", }, routerRepresentation{ Name: "a", Provider: "b", }, routerRepresentation{ Name: "b", Provider: "a", }, routerRepresentation{ Name: "a", Provider: "a", }, }, }, { direction: ascendantSorting, sortBy: "priority", elements: []orderedRouter{ routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Priority: 2, }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Priority: 2, }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Priority: 1, }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Priority: 1, }, }, }, }, expected: []orderedRouter{ routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Priority: 1, }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Priority: 1, }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Priority: 2, }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Priority: 2, }, }, }, }, }, { direction: descendantSorting, sortBy: "priority", elements: []orderedRouter{ routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Priority: 1, }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Priority: 1, }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Priority: 2, }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Priority: 2, }, }, }, }, expected: []orderedRouter{ routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Priority: 2, }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Priority: 2, }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Priority: 1, }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Priority: 1, }, }, }, }, }, { direction: ascendantSorting, sortBy: "status", elements: []orderedRouter{ routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Status: "b", }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Status: "b", }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Status: "a", }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Status: "a", }, }, }, expected: []orderedRouter{ routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Status: "a", }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Status: "a", }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Status: "b", }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Status: "b", }, }, }, }, { direction: descendantSorting, sortBy: "status", elements: []orderedRouter{ routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Status: "a", }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Status: "a", }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Status: "b", }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Status: "b", }, }, }, expected: []orderedRouter{ routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Status: "b", }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Status: "b", }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Status: "a", }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Status: "a", }, }, }, }, { direction: ascendantSorting, sortBy: "rule", elements: []orderedRouter{ routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Rule: "b", }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Rule: "b", }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Rule: "a", }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Rule: "a", }, }, }, }, expected: []orderedRouter{ routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Rule: "a", }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Rule: "a", }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Rule: "b", }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Rule: "b", }, }, }, }, }, { direction: descendantSorting, sortBy: "rule", elements: []orderedRouter{ routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Rule: "a", }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Rule: "a", }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Rule: "b", }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Rule: "b", }, }, }, }, expected: []orderedRouter{ routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Rule: "b", }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Rule: "b", }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Rule: "a", }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Rule: "a", }, }, }, }, }, { direction: ascendantSorting, sortBy: "service", elements: []orderedRouter{ routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Service: "b", }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Service: "b", }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Service: "a", }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Service: "a", }, }, }, }, expected: []orderedRouter{ routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Service: "a", }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Service: "a", }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Service: "b", }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Service: "b", }, }, }, }, }, { direction: descendantSorting, sortBy: "service", elements: []orderedRouter{ routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Service: "a", }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Service: "a", }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Service: "b", }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Service: "b", }, }, }, }, expected: []orderedRouter{ routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Service: "b", }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Service: "b", }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Service: "a", }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ Service: "a", }, }, }, }, }, { direction: ascendantSorting, sortBy: "entryPoints", elements: []orderedRouter{ routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"a", "b"}, }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"a", "b"}, }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"a"}, }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"a"}, }, }, }, }, expected: []orderedRouter{ routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"a"}, }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"a"}, }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"a", "b"}, }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"a", "b"}, }, }, }, }, }, { direction: descendantSorting, sortBy: "entryPoints", elements: []orderedRouter{ routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"a"}, }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"a"}, }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"a", "b"}, }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"a", "b"}, }, }, }, }, expected: []orderedRouter{ routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"a", "b"}, }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"a", "b"}, }, }, }, routerRepresentation{ Name: "b", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"a"}, }, }, }, routerRepresentation{ Name: "a", RouterInfo: &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"a"}, }, }, }, }, }, } for _, test := range testCases { t.Run(fmt.Sprintf("%s-%s", test.direction, test.sortBy), func(t *testing.T) { t.Parallel() u, err := url.Parse(fmt.Sprintf("/?direction=%s&sortBy=%s", test.direction, test.sortBy)) require.NoError(t, err) sortRouters(u.Query(), test.elements) assert.Equal(t, test.expected, test.elements) }) } } func TestSortServices(t *testing.T) { testCases := []struct { direction string sortBy string elements []orderedService expected []orderedService }{ { direction: ascendantSorting, sortBy: "name", elements: []orderedService{ serviceRepresentation{ Name: "b", }, serviceRepresentation{ Name: "a", }, }, expected: []orderedService{ serviceRepresentation{ Name: "a", }, serviceRepresentation{ Name: "b", }, }, }, { direction: descendantSorting, sortBy: "name", elements: []orderedService{ serviceRepresentation{ Name: "a", }, serviceRepresentation{ Name: "b", }, }, expected: []orderedService{ serviceRepresentation{ Name: "b", }, serviceRepresentation{ Name: "a", }, }, }, { direction: ascendantSorting, sortBy: "type", elements: []orderedService{ serviceRepresentation{ Name: "b", Type: "b", }, serviceRepresentation{ Name: "a", Type: "b", }, serviceRepresentation{ Name: "b", Type: "a", }, serviceRepresentation{ Name: "a", Type: "a", }, }, expected: []orderedService{ serviceRepresentation{ Name: "a", Type: "a", }, serviceRepresentation{ Name: "b", Type: "a", }, serviceRepresentation{ Name: "a", Type: "b", }, serviceRepresentation{ Name: "b", Type: "b", }, }, }, { direction: descendantSorting, sortBy: "type", elements: []orderedService{ serviceRepresentation{ Name: "a", Type: "a", }, serviceRepresentation{ Name: "b", Type: "a", }, serviceRepresentation{ Name: "a", Type: "b", }, serviceRepresentation{ Name: "b", Type: "b", }, }, expected: []orderedService{ serviceRepresentation{ Name: "b", Type: "b", }, serviceRepresentation{ Name: "a", Type: "b", }, serviceRepresentation{ Name: "b", Type: "a", }, serviceRepresentation{ Name: "a", Type: "a", }, }, }, { direction: ascendantSorting, sortBy: "servers", elements: []orderedService{ serviceRepresentation{ Name: "b", ServiceInfo: &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: make([]dynamic.Server, 2), }, }, }, }, serviceRepresentation{ Name: "a", ServiceInfo: &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: make([]dynamic.Server, 2), }, }, }, }, serviceRepresentation{ Name: "b", ServiceInfo: &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: make([]dynamic.Server, 1), }, }, }, }, serviceRepresentation{ Name: "a", ServiceInfo: &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: make([]dynamic.Server, 1), }, }, }, }, }, expected: []orderedService{ serviceRepresentation{ Name: "a", ServiceInfo: &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: make([]dynamic.Server, 1), }, }, }, }, serviceRepresentation{ Name: "b", ServiceInfo: &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: make([]dynamic.Server, 1), }, }, }, }, serviceRepresentation{ Name: "a", ServiceInfo: &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: make([]dynamic.Server, 2), }, }, }, }, serviceRepresentation{ Name: "b", ServiceInfo: &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: make([]dynamic.Server, 2), }, }, }, }, }, }, { direction: descendantSorting, sortBy: "servers", elements: []orderedService{ serviceRepresentation{ Name: "a", ServiceInfo: &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: make([]dynamic.Server, 1), }, }, }, }, serviceRepresentation{ Name: "b", ServiceInfo: &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: make([]dynamic.Server, 1), }, }, }, }, serviceRepresentation{ Name: "a", ServiceInfo: &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: make([]dynamic.Server, 2), }, }, }, }, serviceRepresentation{ Name: "b", ServiceInfo: &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: make([]dynamic.Server, 2), }, }, }, }, }, expected: []orderedService{ serviceRepresentation{ Name: "b", ServiceInfo: &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: make([]dynamic.Server, 2), }, }, }, }, serviceRepresentation{ Name: "a", ServiceInfo: &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: make([]dynamic.Server, 2), }, }, }, }, serviceRepresentation{ Name: "b", ServiceInfo: &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: make([]dynamic.Server, 1), }, }, }, }, serviceRepresentation{ Name: "a", ServiceInfo: &runtime.ServiceInfo{ Service: &dynamic.Service{ LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: make([]dynamic.Server, 1), }, }, }, }, }, }, { direction: ascendantSorting, sortBy: "provider", elements: []orderedService{ serviceRepresentation{ Name: "b", Provider: "b", }, serviceRepresentation{ Name: "b", Provider: "a", }, serviceRepresentation{ Name: "a", Provider: "b", }, serviceRepresentation{ Name: "a", Provider: "a", }, }, expected: []orderedService{ serviceRepresentation{ Name: "a", Provider: "a", }, serviceRepresentation{ Name: "b", Provider: "a", }, serviceRepresentation{ Name: "a", Provider: "b", }, serviceRepresentation{ Name: "b", Provider: "b", }, }, }, { direction: descendantSorting, sortBy: "provider", elements: []orderedService{ serviceRepresentation{ Name: "a", Provider: "a", }, serviceRepresentation{ Name: "a", Provider: "b", }, serviceRepresentation{ Name: "b", Provider: "a", }, serviceRepresentation{ Name: "b", Provider: "b", }, }, expected: []orderedService{ serviceRepresentation{ Name: "b", Provider: "b", }, serviceRepresentation{ Name: "a", Provider: "b", }, serviceRepresentation{ Name: "b", Provider: "a", }, serviceRepresentation{ Name: "a", Provider: "a", }, }, }, { direction: ascendantSorting, sortBy: "status", elements: []orderedService{ serviceRepresentation{ Name: "b", ServiceInfo: &runtime.ServiceInfo{ Status: "b", }, }, serviceRepresentation{ Name: "a", ServiceInfo: &runtime.ServiceInfo{ Status: "b", }, }, serviceRepresentation{ Name: "b", ServiceInfo: &runtime.ServiceInfo{ Status: "a", }, }, serviceRepresentation{ Name: "a", ServiceInfo: &runtime.ServiceInfo{ Status: "a", }, }, }, expected: []orderedService{ serviceRepresentation{ Name: "a", ServiceInfo: &runtime.ServiceInfo{ Status: "a", }, }, serviceRepresentation{ Name: "b", ServiceInfo: &runtime.ServiceInfo{ Status: "a", }, }, serviceRepresentation{ Name: "a", ServiceInfo: &runtime.ServiceInfo{ Status: "b", }, }, serviceRepresentation{ Name: "b", ServiceInfo: &runtime.ServiceInfo{ Status: "b", }, }, }, }, { direction: descendantSorting, sortBy: "status", elements: []orderedService{ serviceRepresentation{ Name: "a", ServiceInfo: &runtime.ServiceInfo{ Status: "a", }, }, serviceRepresentation{ Name: "b", ServiceInfo: &runtime.ServiceInfo{ Status: "a", }, }, serviceRepresentation{ Name: "a", ServiceInfo: &runtime.ServiceInfo{ Status: "b", }, }, serviceRepresentation{ Name: "b", ServiceInfo: &runtime.ServiceInfo{ Status: "b", }, }, }, expected: []orderedService{ serviceRepresentation{ Name: "b", ServiceInfo: &runtime.ServiceInfo{ Status: "b", }, }, serviceRepresentation{ Name: "a", ServiceInfo: &runtime.ServiceInfo{ Status: "b", }, }, serviceRepresentation{ Name: "b", ServiceInfo: &runtime.ServiceInfo{ Status: "a", }, }, serviceRepresentation{ Name: "a", ServiceInfo: &runtime.ServiceInfo{ Status: "a", }, }, }, }, } for _, test := range testCases { t.Run(fmt.Sprintf("%s-%s", test.direction, test.sortBy), func(t *testing.T) { t.Parallel() u, err := url.Parse(fmt.Sprintf("/?direction=%s&sortBy=%s", test.direction, test.sortBy)) require.NoError(t, err) sortServices(u.Query(), test.elements) assert.Equal(t, test.expected, test.elements) }) } } func TestSortMiddlewares(t *testing.T) { testCases := []struct { direction string sortBy string elements []orderedMiddleware expected []orderedMiddleware }{ { direction: ascendantSorting, sortBy: "name", elements: []orderedMiddleware{ middlewareRepresentation{ Name: "b", }, middlewareRepresentation{ Name: "a", }, }, expected: []orderedMiddleware{ middlewareRepresentation{ Name: "a", }, middlewareRepresentation{ Name: "b", }, }, }, { direction: descendantSorting, sortBy: "name", elements: []orderedMiddleware{ middlewareRepresentation{ Name: "a", }, middlewareRepresentation{ Name: "b", }, }, expected: []orderedMiddleware{ middlewareRepresentation{ Name: "b", }, middlewareRepresentation{ Name: "a", }, }, }, { direction: ascendantSorting, sortBy: "type", elements: []orderedMiddleware{ middlewareRepresentation{ Name: "b", Type: "b", }, middlewareRepresentation{ Name: "a", Type: "b", }, middlewareRepresentation{ Name: "b", Type: "a", }, middlewareRepresentation{ Name: "a", Type: "a", }, }, expected: []orderedMiddleware{ middlewareRepresentation{ Name: "a", Type: "a", }, middlewareRepresentation{ Name: "b", Type: "a", }, middlewareRepresentation{ Name: "a", Type: "b", }, middlewareRepresentation{ Name: "b", Type: "b", }, }, }, { direction: descendantSorting, sortBy: "type", elements: []orderedMiddleware{ middlewareRepresentation{ Name: "a", Type: "a", }, middlewareRepresentation{ Name: "b", Type: "a", }, middlewareRepresentation{ Name: "a", Type: "b", }, middlewareRepresentation{ Name: "b", Type: "b", }, }, expected: []orderedMiddleware{ middlewareRepresentation{ Name: "b", Type: "b", }, middlewareRepresentation{ Name: "a", Type: "b", }, middlewareRepresentation{ Name: "b", Type: "a", }, middlewareRepresentation{ Name: "a", Type: "a", }, }, }, { direction: ascendantSorting, sortBy: "provider", elements: []orderedMiddleware{ middlewareRepresentation{ Name: "b", Provider: "b", }, middlewareRepresentation{ Name: "b", Provider: "a", }, middlewareRepresentation{ Name: "a", Provider: "b", }, middlewareRepresentation{ Name: "a", Provider: "a", }, }, expected: []orderedMiddleware{ middlewareRepresentation{ Name: "a", Provider: "a", }, middlewareRepresentation{ Name: "b", Provider: "a", }, middlewareRepresentation{ Name: "a", Provider: "b", }, middlewareRepresentation{ Name: "b", Provider: "b", }, }, }, { direction: descendantSorting, sortBy: "provider", elements: []orderedMiddleware{ middlewareRepresentation{ Name: "a", Provider: "a", }, middlewareRepresentation{ Name: "a", Provider: "b", }, middlewareRepresentation{ Name: "b", Provider: "a", }, middlewareRepresentation{ Name: "b", Provider: "b", }, }, expected: []orderedMiddleware{ middlewareRepresentation{ Name: "b", Provider: "b", }, middlewareRepresentation{ Name: "a", Provider: "b", }, middlewareRepresentation{ Name: "b", Provider: "a", }, middlewareRepresentation{ Name: "a", Provider: "a", }, }, }, { direction: ascendantSorting, sortBy: "status", elements: []orderedMiddleware{ middlewareRepresentation{ Name: "b", MiddlewareInfo: &runtime.MiddlewareInfo{ Status: "b", }, }, middlewareRepresentation{ Name: "a", MiddlewareInfo: &runtime.MiddlewareInfo{ Status: "b", }, }, middlewareRepresentation{ Name: "b", MiddlewareInfo: &runtime.MiddlewareInfo{ Status: "a", }, }, middlewareRepresentation{ Name: "a", MiddlewareInfo: &runtime.MiddlewareInfo{ Status: "a", }, }, }, expected: []orderedMiddleware{ middlewareRepresentation{ Name: "a", MiddlewareInfo: &runtime.MiddlewareInfo{ Status: "a", }, }, middlewareRepresentation{ Name: "b", MiddlewareInfo: &runtime.MiddlewareInfo{ Status: "a", }, }, middlewareRepresentation{ Name: "a", MiddlewareInfo: &runtime.MiddlewareInfo{ Status: "b", }, }, middlewareRepresentation{ Name: "b", MiddlewareInfo: &runtime.MiddlewareInfo{ Status: "b", }, }, }, }, { direction: descendantSorting, sortBy: "status", elements: []orderedMiddleware{ middlewareRepresentation{ Name: "a", MiddlewareInfo: &runtime.MiddlewareInfo{ Status: "a", }, }, middlewareRepresentation{ Name: "b", MiddlewareInfo: &runtime.MiddlewareInfo{ Status: "a", }, }, middlewareRepresentation{ Name: "a", MiddlewareInfo: &runtime.MiddlewareInfo{ Status: "b", }, }, middlewareRepresentation{ Name: "b", MiddlewareInfo: &runtime.MiddlewareInfo{ Status: "b", }, }, }, expected: []orderedMiddleware{ middlewareRepresentation{ Name: "b", MiddlewareInfo: &runtime.MiddlewareInfo{ Status: "b", }, }, middlewareRepresentation{ Name: "a", MiddlewareInfo: &runtime.MiddlewareInfo{ Status: "b", }, }, middlewareRepresentation{ Name: "b", MiddlewareInfo: &runtime.MiddlewareInfo{ Status: "a", }, }, middlewareRepresentation{ Name: "a", MiddlewareInfo: &runtime.MiddlewareInfo{ Status: "a", }, }, }, }, } for _, test := range testCases {
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/dashboard/dashboard_test.go
pkg/api/dashboard/dashboard_test.go
package dashboard import ( "errors" "io/fs" "net/http" "net/http/httptest" "testing" "testing/fstest" "time" "github.com/stretchr/testify/assert" ) func Test_ContentSecurityPolicy(t *testing.T) { testCases := []struct { desc string handler Handler expected int }{ { desc: "OK", handler: Handler{ assets: fstest.MapFS{"foobar.html": &fstest.MapFile{ Mode: 0o755, ModTime: time.Now(), }}, }, expected: http.StatusOK, }, { desc: "Not found", handler: Handler{ assets: fstest.MapFS{}, }, expected: http.StatusNotFound, }, { desc: "Internal server error", handler: Handler{ assets: errorFS{}, }, expected: http.StatusInternalServerError, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() req := httptest.NewRequest(http.MethodGet, "/foobar.html", nil) rw := httptest.NewRecorder() test.handler.ServeHTTP(rw, req) assert.Equal(t, test.expected, rw.Code) assert.Equal(t, "frame-src 'self' https://traefik.io https://*.traefik.io;", rw.Result().Header.Get("Content-Security-Policy")) }) } } type errorFS struct{} func (e errorFS) Open(name string) (fs.File, error) { return nil, errors.New("oops") }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/api/dashboard/dashboard.go
pkg/api/dashboard/dashboard.go
package dashboard import ( "fmt" "io/fs" "net/http" "strings" "text/template" "github.com/gorilla/mux" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/webui" ) type indexTemplateData struct { APIUrl string } // Handler expose dashboard routes. type Handler struct { BasePath string assets fs.FS // optional assets, to override the webui.FS default } func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { assets := h.assets if assets == nil { assets = webui.FS } // Allow iframes from traefik domains only. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-src w.Header().Set("Content-Security-Policy", "frame-src 'self' https://traefik.io https://*.traefik.io;") if r.RequestURI == "/" { indexTemplate, err := template.ParseFS(assets, "index.html") if err != nil { log.Error().Err(err).Msg("Unable to parse index template") http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") apiPath := strings.TrimSuffix(h.BasePath, "/") + "/api/" if err = indexTemplate.Execute(w, indexTemplateData{APIUrl: apiPath}); err != nil { log.Error().Err(err).Msg("Unable to render index template") http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } return } // The content type must be guessed by the file server. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options w.Header().Del("Content-Type") http.FileServerFS(assets).ServeHTTP(w, r) } // Append adds dashboard routes on the given router, optionally using the given // assets (or webui.FS otherwise). func Append(router *mux.Router, basePath string, customAssets fs.FS) error { assets := customAssets if assets == nil { assets = webui.FS } indexTemplate, err := template.ParseFS(assets, "index.html") if err != nil { return fmt.Errorf("parsing index template: %w", err) } dashboardPath := strings.TrimSuffix(basePath, "/") + "/dashboard/" // Expose dashboard router.Methods(http.MethodGet). Path(basePath). HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { prefix := strings.TrimSuffix(req.Header.Get("X-Forwarded-Prefix"), "/") http.Redirect(resp, req, prefix+dashboardPath, http.StatusFound) }) router.Methods(http.MethodGet). Path(dashboardPath). HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Allow iframes from our domains only. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-src w.Header().Set("Content-Security-Policy", "frame-src 'self' https://traefik.io https://*.traefik.io;") w.Header().Set("Content-Type", "text/html; charset=utf-8") apiPath := strings.TrimSuffix(basePath, "/") + "/api/" if err = indexTemplate.Execute(w, indexTemplateData{APIUrl: apiPath}); err != nil { log.Error().Err(err).Msg("Unable to render index template") http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } }) router.Methods(http.MethodGet). PathPrefix(dashboardPath). HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Allow iframes from traefik domains only. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-src w.Header().Set("Content-Security-Policy", "frame-src 'self' https://traefik.io https://*.traefik.io;") // The content type must be guessed by the file server. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options w.Header().Del("Content-Type") http.StripPrefix(dashboardPath, http.FileServerFS(assets)).ServeHTTP(w, r) }) return nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/plugins/middlewareyaegi.go
pkg/plugins/middlewareyaegi.go
package plugins import ( "context" "errors" "fmt" "net/http" "os" "path" "reflect" "strings" "github.com/mitchellh/mapstructure" "github.com/rs/zerolog" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/yaegi/interp" "github.com/traefik/yaegi/stdlib" "github.com/traefik/yaegi/stdlib/syscall" "github.com/traefik/yaegi/stdlib/unsafe" ) type yaegiMiddlewareBuilder struct { fnNew reflect.Value fnCreateConfig reflect.Value } func newYaegiMiddlewareBuilder(i *interp.Interpreter, basePkg, imp string) (*yaegiMiddlewareBuilder, error) { if basePkg == "" { basePkg = strings.ReplaceAll(path.Base(imp), "-", "_") } fnNew, err := i.Eval(basePkg + `.New`) if err != nil { return nil, fmt.Errorf("failed to eval New: %w", err) } fnCreateConfig, err := i.Eval(basePkg + `.CreateConfig`) if err != nil { return nil, fmt.Errorf("failed to eval CreateConfig: %w", err) } return &yaegiMiddlewareBuilder{ fnNew: fnNew, fnCreateConfig: fnCreateConfig, }, nil } func (b yaegiMiddlewareBuilder) newMiddleware(config map[string]interface{}, middlewareName string) (pluginMiddleware, error) { vConfig, err := b.createConfig(config) if err != nil { return nil, err } return &YaegiMiddleware{ middlewareName: middlewareName, config: vConfig, builder: b, }, nil } func (b yaegiMiddlewareBuilder) newHandler(ctx context.Context, next http.Handler, cfg reflect.Value, middlewareName string) (http.Handler, error) { args := []reflect.Value{reflect.ValueOf(ctx), reflect.ValueOf(next), cfg, reflect.ValueOf(middlewareName)} results := b.fnNew.Call(args) if len(results) > 1 && results[1].Interface() != nil { err, ok := results[1].Interface().(error) if !ok { return nil, fmt.Errorf("invalid error type: %T", results[0].Interface()) } return nil, err } handler, ok := results[0].Interface().(http.Handler) if !ok { return nil, fmt.Errorf("invalid handler type: %T", results[0].Interface()) } return handler, nil } func (b yaegiMiddlewareBuilder) createConfig(config map[string]interface{}) (reflect.Value, error) { results := b.fnCreateConfig.Call(nil) if len(results) != 1 { return reflect.Value{}, fmt.Errorf("invalid number of return for the CreateConfig function: %d", len(results)) } vConfig := results[0] if len(config) == 0 { return vConfig, nil } cfg := &mapstructure.DecoderConfig{ DecodeHook: mapstructure.StringToSliceHookFunc(","), WeaklyTypedInput: true, Result: vConfig.Interface(), } decoder, err := mapstructure.NewDecoder(cfg) if err != nil { return reflect.Value{}, fmt.Errorf("failed to create configuration decoder: %w", err) } err = decoder.Decode(config) if err != nil { return reflect.Value{}, fmt.Errorf("failed to decode configuration: %w", err) } return vConfig, nil } // YaegiMiddleware is an HTTP handler plugin wrapper. type YaegiMiddleware struct { middlewareName string config reflect.Value builder yaegiMiddlewareBuilder } // NewHandler creates a new HTTP handler. func (m *YaegiMiddleware) NewHandler(ctx context.Context, next http.Handler) (http.Handler, error) { return m.builder.newHandler(ctx, next, m.config, m.middlewareName) } func newInterpreter(ctx context.Context, goPath string, manifest *Manifest, settings Settings) (*interp.Interpreter, error) { i := interp.New(interp.Options{ GoPath: goPath, Env: os.Environ(), Stdout: logs.NoLevel(*log.Ctx(ctx), zerolog.DebugLevel), Stderr: logs.NoLevel(*log.Ctx(ctx), zerolog.ErrorLevel), }) err := i.Use(stdlib.Symbols) if err != nil { return nil, fmt.Errorf("failed to load symbols: %w", err) } if manifest.UseUnsafe && !settings.UseUnsafe { return nil, errors.New("this plugin uses restricted imports. If you want to use it, you need to allow useUnsafe in the settings") } if settings.UseUnsafe && manifest.UseUnsafe { err := i.Use(unsafe.Symbols) if err != nil { return nil, fmt.Errorf("failed to load unsafe symbols: %w", err) } err = i.Use(syscall.Symbols) if err != nil { return nil, fmt.Errorf("failed to load syscall symbols: %w", err) } } err = i.Use(ppSymbols()) if err != nil { return nil, fmt.Errorf("failed to load provider symbols: %w", err) } _, err = i.Eval(fmt.Sprintf(`import "%s"`, manifest.Import)) if err != nil { return nil, fmt.Errorf("failed to import plugin code %q: %w", manifest.Import, err) } return i, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/plugins/manager_test.go
pkg/plugins/manager_test.go
package plugins import ( zipa "archive/zip" "context" "encoding/json" "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gopkg.in/yaml.v3" ) // mockDownloader is a test implementation of PluginDownloader type mockDownloader struct { downloadFunc func(ctx context.Context, pName, pVersion string) (string, error) checkFunc func(ctx context.Context, pName, pVersion, hash string) error } func (m *mockDownloader) Download(ctx context.Context, pName, pVersion string) (string, error) { if m.downloadFunc != nil { return m.downloadFunc(ctx, pName, pVersion) } return "mockhash", nil } func (m *mockDownloader) Check(ctx context.Context, pName, pVersion, hash string) error { if m.checkFunc != nil { return m.checkFunc(ctx, pName, pVersion, hash) } return nil } func TestPluginManager_ReadManifest(t *testing.T) { tempDir := t.TempDir() opts := ManagerOptions{Output: tempDir} downloader := &mockDownloader{} manager, err := NewManager(downloader, opts) require.NoError(t, err) moduleName := "github.com/test/plugin" pluginPath := filepath.Join(manager.goPath, "src", moduleName) err = os.MkdirAll(pluginPath, 0o755) require.NoError(t, err) manifest := &Manifest{ DisplayName: "Test Plugin", Type: "middleware", Import: "github.com/test/plugin", Summary: "A test plugin", TestData: map[string]interface{}{ "test": "data", }, } manifestPath := filepath.Join(pluginPath, pluginManifest) manifestData, err := yaml.Marshal(manifest) require.NoError(t, err) err = os.WriteFile(manifestPath, manifestData, 0o644) require.NoError(t, err) readManifest, err := manager.ReadManifest(moduleName) require.NoError(t, err) assert.Equal(t, manifest.DisplayName, readManifest.DisplayName) assert.Equal(t, manifest.Type, readManifest.Type) assert.Equal(t, manifest.Import, readManifest.Import) assert.Equal(t, manifest.Summary, readManifest.Summary) } func TestPluginManager_ReadManifest_NotFound(t *testing.T) { tempDir := t.TempDir() opts := ManagerOptions{Output: tempDir} downloader := &mockDownloader{} manager, err := NewManager(downloader, opts) require.NoError(t, err) _, err = manager.ReadManifest("nonexistent/plugin") assert.Error(t, err) } func TestPluginManager_CleanArchives(t *testing.T) { tempDir := t.TempDir() opts := ManagerOptions{Output: tempDir} downloader := &mockDownloader{} manager, err := NewManager(downloader, opts) require.NoError(t, err) testPlugin1 := "test/plugin1" testPlugin2 := "test/plugin2" archive1Dir := filepath.Join(manager.archives, "test", "plugin1") archive2Dir := filepath.Join(manager.archives, "test", "plugin2") err = os.MkdirAll(archive1Dir, 0o755) require.NoError(t, err) err = os.MkdirAll(archive2Dir, 0o755) require.NoError(t, err) archive1Old := filepath.Join(archive1Dir, "v1.0.0.zip") archive1New := filepath.Join(archive1Dir, "v2.0.0.zip") archive2 := filepath.Join(archive2Dir, "v1.0.0.zip") err = os.WriteFile(archive1Old, []byte("old archive"), 0o644) require.NoError(t, err) err = os.WriteFile(archive1New, []byte("new archive"), 0o644) require.NoError(t, err) err = os.WriteFile(archive2, []byte("archive 2"), 0o644) require.NoError(t, err) state := map[string]string{ testPlugin1: "v1.0.0", testPlugin2: "v1.0.0", } stateData, err := json.MarshalIndent(state, "", " ") require.NoError(t, err) err = os.WriteFile(manager.stateFile, stateData, 0o600) require.NoError(t, err) currentPlugins := map[string]Descriptor{ "plugin1": { ModuleName: testPlugin1, Version: "v2.0.0", }, "plugin2": { ModuleName: testPlugin2, Version: "v1.0.0", }, } err = manager.CleanArchives(currentPlugins) require.NoError(t, err) assert.NoFileExists(t, archive1Old) assert.FileExists(t, archive1New) assert.FileExists(t, archive2) } func TestPluginManager_WriteState(t *testing.T) { tempDir := t.TempDir() opts := ManagerOptions{Output: tempDir} downloader := &mockDownloader{} manager, err := NewManager(downloader, opts) require.NoError(t, err) plugins := map[string]Descriptor{ "plugin1": { ModuleName: "test/plugin1", Version: "v1.0.0", }, "plugin2": { ModuleName: "test/plugin2", Version: "v2.0.0", }, } err = manager.WriteState(plugins) require.NoError(t, err) assert.FileExists(t, manager.stateFile) data, err := os.ReadFile(manager.stateFile) require.NoError(t, err) var state map[string]string err = json.Unmarshal(data, &state) require.NoError(t, err) expectedState := map[string]string{ "test/plugin1": "v1.0.0", "test/plugin2": "v2.0.0", } assert.Equal(t, expectedState, state) } func TestPluginManager_ResetAll(t *testing.T) { tempDir := t.TempDir() opts := ManagerOptions{Output: tempDir} downloader := &mockDownloader{} manager, err := NewManager(downloader, opts) require.NoError(t, err) testFile := filepath.Join(manager.GoPath(), "test.txt") err = os.WriteFile(testFile, []byte("test"), 0o644) require.NoError(t, err) archiveFile := filepath.Join(manager.archives, "test.zip") err = os.WriteFile(archiveFile, []byte("archive"), 0o644) require.NoError(t, err) err = manager.ResetAll() require.NoError(t, err) assert.DirExists(t, manager.archives) assert.NoFileExists(t, testFile) assert.NoFileExists(t, archiveFile) } func TestPluginManager_InstallPlugin(t *testing.T) { tests := []struct { name string plugin Descriptor downloadFunc func(ctx context.Context, pName, pVersion string) (string, error) checkFunc func(ctx context.Context, pName, pVersion, hash string) error setupArchive func(t *testing.T, archivePath string) expectError bool errorMsg string }{ { name: "successful installation", plugin: Descriptor{ ModuleName: "github.com/test/plugin", Version: "v1.0.0", Hash: "expected-hash", }, downloadFunc: func(ctx context.Context, pName, pVersion string) (string, error) { return "expected-hash", nil }, checkFunc: func(ctx context.Context, pName, pVersion, hash string) error { return nil }, setupArchive: func(t *testing.T, archivePath string) { t.Helper() // Create a valid zip archive err := os.MkdirAll(filepath.Dir(archivePath), 0o755) require.NoError(t, err) file, err := os.Create(archivePath) require.NoError(t, err) defer file.Close() // Write a minimal zip file with a test file writer := zipa.NewWriter(file) defer writer.Close() fileWriter, err := writer.Create("test-module-v1.0.0/main.go") require.NoError(t, err) _, err = fileWriter.Write([]byte("package main\n\nfunc main() {}\n")) require.NoError(t, err) }, expectError: false, }, { name: "download error", plugin: Descriptor{ ModuleName: "github.com/test/plugin", Version: "v1.0.0", }, downloadFunc: func(ctx context.Context, pName, pVersion string) (string, error) { return "", assert.AnError }, expectError: true, errorMsg: "unable to download plugin", }, { name: "check error", plugin: Descriptor{ ModuleName: "github.com/test/plugin", Version: "v1.0.0", Hash: "expected-hash", }, downloadFunc: func(ctx context.Context, pName, pVersion string) (string, error) { return "actual-hash", nil }, checkFunc: func(ctx context.Context, pName, pVersion, hash string) error { return assert.AnError }, expectError: true, errorMsg: "invalid hash for plugin", }, { name: "unzip error - invalid archive", plugin: Descriptor{ ModuleName: "github.com/test/plugin", Version: "v1.0.0", }, downloadFunc: func(ctx context.Context, pName, pVersion string) (string, error) { return "test-hash", nil }, checkFunc: func(ctx context.Context, pName, pVersion, hash string) error { return nil }, setupArchive: func(t *testing.T, archivePath string) { t.Helper() // Create an invalid zip archive err := os.MkdirAll(filepath.Dir(archivePath), 0o755) require.NoError(t, err) err = os.WriteFile(archivePath, []byte("invalid zip content"), 0o644) require.NoError(t, err) }, expectError: true, errorMsg: "unable to unzip plugin", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { tempDir := t.TempDir() opts := ManagerOptions{Output: tempDir} downloader := &mockDownloader{ downloadFunc: test.downloadFunc, checkFunc: test.checkFunc, } manager, err := NewManager(downloader, opts) require.NoError(t, err) // Setup archive if needed if test.setupArchive != nil { archivePath := filepath.Join(manager.archives, filepath.FromSlash(test.plugin.ModuleName), test.plugin.Version+".zip") test.setupArchive(t, archivePath) } ctx := t.Context() err = manager.InstallPlugin(ctx, test.plugin) if test.expectError { assert.Error(t, err) if test.errorMsg != "" { assert.Contains(t, err.Error(), test.errorMsg) } } else { assert.NoError(t, err) // Verify that plugin sources were extracted sourcePath := filepath.Join(manager.sources, filepath.FromSlash(test.plugin.ModuleName)) assert.DirExists(t, sourcePath) } }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/plugins/providers.go
pkg/plugins/providers.go
package plugins import ( "context" "encoding/json" "fmt" "path" "reflect" "strings" "github.com/mitchellh/mapstructure" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/provider" "github.com/traefik/traefik/v3/pkg/safe" "github.com/traefik/yaegi/interp" ) // PP the interface of a plugin's provider. type PP interface { Init() error Provide(cfgChan chan<- json.Marshaler) error Stop() error } type _PP struct { IValue interface{} WInit func() error WProvide func(cfgChan chan<- json.Marshaler) error WStop func() error } func (p _PP) Init() error { return p.WInit() } func (p _PP) Provide(cfgChan chan<- json.Marshaler) error { return p.WProvide(cfgChan) } func (p _PP) Stop() error { return p.WStop() } func ppSymbols() map[string]map[string]reflect.Value { return map[string]map[string]reflect.Value{ "github.com/traefik/traefik/v3/pkg/plugins/plugins": { "PP": reflect.ValueOf((*PP)(nil)), "_PP": reflect.ValueOf((*_PP)(nil)), }, } } // BuildProvider builds a plugin's provider. func (b Builder) BuildProvider(pName string, config map[string]interface{}) (provider.Provider, error) { if b.providerBuilders == nil { return nil, fmt.Errorf("no plugin definition in the static configuration: %s", pName) } builder, ok := b.providerBuilders[pName] if !ok { return nil, fmt.Errorf("unknown plugin type: %s", pName) } return newProvider(builder, config, "plugin-"+pName) } type providerBuilder struct { // Import plugin's import/package Import string `json:"import,omitempty" toml:"import,omitempty" yaml:"import,omitempty"` // BasePkg plugin's base package name (optional) BasePkg string `json:"basePkg,omitempty" toml:"basePkg,omitempty" yaml:"basePkg,omitempty"` interpreter *interp.Interpreter } // Provider is a plugin's provider wrapper. type Provider struct { name string pp PP } func newProvider(builder providerBuilder, config map[string]interface{}, providerName string) (*Provider, error) { basePkg := builder.BasePkg if basePkg == "" { basePkg = strings.ReplaceAll(path.Base(builder.Import), "-", "_") } vConfig, err := builder.interpreter.Eval(basePkg + `.CreateConfig()`) if err != nil { return nil, fmt.Errorf("failed to eval CreateConfig: %w", err) } cfg := &mapstructure.DecoderConfig{ DecodeHook: mapstructure.StringToSliceHookFunc(","), WeaklyTypedInput: true, Result: vConfig.Interface(), } decoder, err := mapstructure.NewDecoder(cfg) if err != nil { return nil, fmt.Errorf("failed to create configuration decoder: %w", err) } err = decoder.Decode(config) if err != nil { return nil, fmt.Errorf("failed to decode configuration: %w", err) } _, err = builder.interpreter.Eval(`package wrapper import ( "context" ` + basePkg + ` "` + builder.Import + `" "github.com/traefik/traefik/v3/pkg/plugins" ) func NewWrapper(ctx context.Context, config *` + basePkg + `.Config, name string) (plugins.PP, error) { p, err := ` + basePkg + `.New(ctx, config, name) var pv plugins.PP = p return pv, err } `) if err != nil { return nil, fmt.Errorf("failed to eval wrapper: %w", err) } fnNew, err := builder.interpreter.Eval("wrapper.NewWrapper") if err != nil { return nil, fmt.Errorf("failed to eval New: %w", err) } ctx := context.Background() args := []reflect.Value{reflect.ValueOf(ctx), vConfig, reflect.ValueOf(providerName)} results := fnNew.Call(args) if len(results) > 1 && results[1].Interface() != nil { return nil, results[1].Interface().(error) } prov, ok := results[0].Interface().(PP) if !ok { return nil, fmt.Errorf("invalid provider type: %T", results[0].Interface()) } return &Provider{name: providerName, pp: prov}, nil } // Init wraps the Init method of a plugin. func (p *Provider) Init() error { return p.pp.Init() } // Provide wraps the Provide method of a plugin. func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error { defer func() { if err := recover(); err != nil { log.Error().Str(logs.ProviderName, p.name).Msgf("Panic inside the plugin %v", err) } }() cfgChan := make(chan json.Marshaler) pool.GoCtx(func(ctx context.Context) { logger := log.Ctx(ctx).With().Str(logs.ProviderName, p.name).Logger() for { select { case <-ctx.Done(): err := p.pp.Stop() if err != nil { logger.Error().Err(err).Msg("Failed to stop the provider") } return case cfgPg := <-cfgChan: marshalJSON, err := cfgPg.MarshalJSON() if err != nil { logger.Error().Err(err).Msg("Failed to marshal configuration") continue } cfg := &dynamic.Configuration{} err = json.Unmarshal(marshalJSON, cfg) if err != nil { logger.Error().Err(err).Msg("Failed to unmarshal configuration") continue } configurationChan <- dynamic.Message{ ProviderName: p.name, Configuration: cfg, } } } }) err := p.pp.Provide(cfgChan) if err != nil { return fmt.Errorf("error from %s: %w", p.name, err) } return nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/plugins/downloader.go
pkg/plugins/downloader.go
package plugins import ( "context" "errors" "fmt" "io" "net/http" "net/url" "os" "path" "path/filepath" ) // PluginDownloader defines the interface for downloading and validating plugins from remote sources. type PluginDownloader interface { // Download downloads a plugin archive and returns its hash. Download(ctx context.Context, pName, pVersion string) (string, error) // Check checks the plugin archive integrity against a known hash. Check(ctx context.Context, pName, pVersion, hash string) error } // RegistryDownloaderOptions holds configuration options for creating a RegistryDownloader. type RegistryDownloaderOptions struct { HTTPClient *http.Client ArchivesPath string } // RegistryDownloader implements PluginDownloader for HTTP-based plugin downloads. type RegistryDownloader struct { httpClient *http.Client baseURL *url.URL archives string } // NewRegistryDownloader creates a new HTTP-based plugin downloader. func NewRegistryDownloader(opts RegistryDownloaderOptions) (*RegistryDownloader, error) { baseURL, err := url.Parse(pluginsURL) if err != nil { return nil, err } httpClient := opts.HTTPClient if httpClient == nil { httpClient = http.DefaultClient } return &RegistryDownloader{ httpClient: httpClient, baseURL: baseURL, archives: opts.ArchivesPath, }, nil } // Download downloads a plugin archive. func (d *RegistryDownloader) Download(ctx context.Context, pName, pVersion string) (string, error) { filename := d.buildArchivePath(pName, pVersion) var hash string _, err := os.Stat(filename) if err != nil && !os.IsNotExist(err) { return "", fmt.Errorf("failed to read archive %s: %w", filename, err) } if err == nil { hash, err = computeHash(filename) if err != nil { return "", fmt.Errorf("failed to compute hash: %w", err) } } endpoint, err := d.baseURL.Parse(path.Join(d.baseURL.Path, "download", pName, pVersion)) if err != nil { return "", fmt.Errorf("failed to parse endpoint URL: %w", err) } req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil) if err != nil { return "", fmt.Errorf("failed to create request: %w", err) } if hash != "" { req.Header.Set(hashHeader, hash) } resp, err := d.httpClient.Do(req) if err != nil { return "", fmt.Errorf("failed to call service: %w", err) } defer func() { _ = resp.Body.Close() }() switch resp.StatusCode { case http.StatusNotModified: return hash, nil case http.StatusOK: err = os.MkdirAll(filepath.Dir(filename), 0o755) if err != nil { return "", fmt.Errorf("failed to create directory: %w", err) } var file *os.File file, err = os.Create(filename) if err != nil { return "", fmt.Errorf("failed to create file %q: %w", filename, err) } defer func() { _ = file.Close() }() _, err = io.Copy(file, resp.Body) if err != nil { return "", fmt.Errorf("failed to write response: %w", err) } hash, err = computeHash(filename) if err != nil { return "", fmt.Errorf("failed to compute hash: %w", err) } default: data, _ := io.ReadAll(resp.Body) return "", fmt.Errorf("error: %d: %s", resp.StatusCode, string(data)) } return hash, nil } // Check checks the plugin archive integrity. func (d *RegistryDownloader) Check(ctx context.Context, pName, pVersion, hash string) error { endpoint, err := d.baseURL.Parse(path.Join(d.baseURL.Path, "validate", pName, pVersion)) if err != nil { return fmt.Errorf("failed to parse endpoint URL: %w", err) } req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil) if err != nil { return fmt.Errorf("failed to create request: %w", err) } if hash != "" { req.Header.Set(hashHeader, hash) } resp, err := d.httpClient.Do(req) if err != nil { return fmt.Errorf("failed to call service: %w", err) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode == http.StatusOK { return nil } return errors.New("plugin integrity check failed") } // buildArchivePath builds the path to a plugin archive file. func (d *RegistryDownloader) buildArchivePath(pName, pVersion string) string { return filepath.Join(d.archives, filepath.FromSlash(pName), pVersion+".zip") }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/plugins/middlewareyaegi_test.go
pkg/plugins/middlewareyaegi_test.go
package plugins import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/yaegi/interp" ) // TestNewInterpreter_SyscallErrorCase - Tests the security gate logic func TestNewInterpreter_SyscallErrorCase(t *testing.T) { manifest := &Manifest{ Import: "does-not-matter-will-error-before-import", UseUnsafe: true, // Plugin wants unsafe access } settings := Settings{ UseUnsafe: false, // But admin doesn't allow it } ctx := t.Context() _, err := newInterpreter(ctx, "/tmp", manifest, settings) // This proves our security gate logic works require.Error(t, err) assert.Contains(t, err.Error(), "restricted imports", "Our error message should be returned") } // TestNewYaegiMiddlewareBuilder_WithSyscallSupport - Tests the ACTUAL production code! func TestNewYaegiMiddlewareBuilder_WithSyscallSupport(t *testing.T) { tests := []struct { name string pluginType string manifestUnsafe bool settingsUnsafe bool shouldSucceed bool expectedError string }{ { name: "Should work with safe plugin when useUnsafe disabled", pluginType: "safe", manifestUnsafe: false, settingsUnsafe: false, shouldSucceed: true, }, { name: "Should work with unsafe-only plugin when useUnsafe enabled", pluginType: "unsafe-only", manifestUnsafe: true, settingsUnsafe: true, shouldSucceed: true, }, { name: "Should work with unsafe+syscall plugin when useUnsafe enabled", pluginType: "unsafe+syscall", manifestUnsafe: true, settingsUnsafe: true, shouldSucceed: true, }, { name: "Should fail when plugin needs unsafe but setting disabled", pluginType: "unsafe-only", manifestUnsafe: true, settingsUnsafe: false, shouldSucceed: false, expectedError: "restricted imports", }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { ctx := t.Context() // Set GOPATH to include our fixtures directory goPath := "fixtures" // Create interpreter using our ACTUAL newInterpreter function // This will automatically import the real test plugin! interpreter, err := createInterpreterForTesting(ctx, goPath, tc.pluginType, tc.manifestUnsafe, tc.settingsUnsafe) if tc.shouldSucceed { require.NoError(t, err) require.NotNil(t, interpreter) // Test actual middleware building using newYaegiMiddlewareBuilder // The plugin is already loaded by newInterpreter! basePkg := getPluginPackage(tc.pluginType) builder, err := newYaegiMiddlewareBuilder(interpreter, basePkg, basePkg) require.NoError(t, err) require.NotNil(t, builder) // Verify that unsafe/syscall functions actually work if the plugin uses them if tc.pluginType != "safe" { verifyMiddlewareWorks(t, builder) } } else { assert.Error(t, err) assert.Contains(t, err.Error(), tc.expectedError) } }) } } // Helper that uses the ACTUAL newInterpreter function with real test plugins func createInterpreterForTesting(ctx context.Context, goPath, pluginType string, manifestUnsafe, settingsUnsafe bool) (*interp.Interpreter, error) { pluginImport := getPluginPackage(pluginType) manifest := &Manifest{ Import: pluginImport, UseUnsafe: manifestUnsafe, } settings := Settings{ UseUnsafe: settingsUnsafe, } // Call the ACTUAL production newInterpreter function - no workarounds needed! return newInterpreter(ctx, goPath, manifest, settings) } // Helper to get the correct plugin package name based on type func getPluginPackage(pluginType string) string { switch pluginType { case "safe": return "testpluginsafe" case "unsafe-only": return "testpluginunsafe" case "unsafe+syscall": return "testpluginsyscall" default: return "testpluginsafe" } } // Helper to verify that unsafe/syscall functions actually work by invoking the middleware func verifyMiddlewareWorks(t *testing.T, builder *yaegiMiddlewareBuilder) { t.Helper() // Create a middleware instance - this will call the plugin's New() function // which uses unsafe/syscall, proving they work middleware, err := builder.newMiddleware(map[string]interface{}{ "message": "test", }, "test-middleware") require.NoError(t, err, "Should be able to create middleware that uses unsafe/syscall") require.NotNil(t, middleware, "Middleware should not be nil") // The fact that we got here without crashing proves unsafe/syscall work! }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/plugins/middlewarewasm.go
pkg/plugins/middlewarewasm.go
package plugins import ( "context" "encoding/json" "fmt" "net/http" "os" "path/filepath" "reflect" "runtime" "strings" "github.com/http-wasm/http-wasm-host-go/handler" wasm "github.com/http-wasm/http-wasm-host-go/handler/nethttp" "github.com/tetratelabs/wazero" "github.com/traefik/traefik/v3/pkg/middlewares" "github.com/traefik/traefik/v3/pkg/observability/logs" ) type wasmMiddlewareBuilder struct { path string cache wazero.CompilationCache settings Settings } func newWasmMiddlewareBuilder(goPath, moduleName, wasmPath string, settings Settings) (*wasmMiddlewareBuilder, error) { ctx := context.Background() path := filepath.Join(goPath, "src", moduleName, wasmPath) cache := wazero.NewCompilationCache() code, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("loading Wasm binary: %w", err) } rt := wazero.NewRuntimeWithConfig(ctx, wazero.NewRuntimeConfig().WithCompilationCache(cache)) if _, err = rt.CompileModule(ctx, code); err != nil { return nil, fmt.Errorf("compiling guest module: %w", err) } return &wasmMiddlewareBuilder{path: path, cache: cache, settings: settings}, nil } func (b wasmMiddlewareBuilder) newMiddleware(config map[string]interface{}, middlewareName string) (pluginMiddleware, error) { return &WasmMiddleware{ middlewareName: middlewareName, config: reflect.ValueOf(config), builder: b, }, nil } func (b wasmMiddlewareBuilder) newHandler(ctx context.Context, next http.Handler, cfg reflect.Value, middlewareName string) (http.Handler, error) { h, applyCtx, err := b.buildMiddleware(ctx, next, cfg, middlewareName) if err != nil { return nil, fmt.Errorf("building Wasm middleware: %w", err) } return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { h.ServeHTTP(rw, req.WithContext(applyCtx(req.Context()))) }), nil } func (b *wasmMiddlewareBuilder) buildMiddleware(ctx context.Context, next http.Handler, cfg reflect.Value, middlewareName string) (http.Handler, func(ctx context.Context) context.Context, error) { code, err := os.ReadFile(b.path) if err != nil { return nil, nil, fmt.Errorf("loading binary: %w", err) } rt := wazero.NewRuntimeWithConfig(ctx, wazero.NewRuntimeConfig().WithCompilationCache(b.cache)) guestModule, err := rt.CompileModule(ctx, code) if err != nil { return nil, nil, fmt.Errorf("compiling guest module: %w", err) } applyCtx, err := InstantiateHost(ctx, rt, guestModule, b.settings) if err != nil { return nil, nil, fmt.Errorf("instantiating host module: %w", err) } logger := middlewares.GetLogger(ctx, middlewareName, "wasm") config := wazero.NewModuleConfig().WithSysWalltime().WithStartFunctions("_start", "_initialize") for _, env := range b.settings.Envs { config = config.WithEnv(env, os.Getenv(env)) } if len(b.settings.Mounts) > 0 { fsConfig := wazero.NewFSConfig() for _, mount := range b.settings.Mounts { withDir := fsConfig.WithDirMount prefix, readOnly := strings.CutSuffix(mount, ":ro") if readOnly { withDir = fsConfig.WithReadOnlyDirMount } parts := strings.Split(prefix, ":") switch { case len(parts) == 1: fsConfig = withDir(parts[0], parts[0]) case len(parts) == 2: fsConfig = withDir(parts[0], parts[1]) default: return nil, nil, fmt.Errorf("invalid directory %q", mount) } } config = config.WithFSConfig(fsConfig) } opts := []handler.Option{ handler.ModuleConfig(config), handler.Logger(logs.NewWasmLogger(logger)), } i := cfg.Interface() if i != nil { config, ok := i.(map[string]interface{}) if !ok { return nil, nil, fmt.Errorf("could not type assert config: %T", i) } data, err := json.Marshal(config) if err != nil { return nil, nil, fmt.Errorf("marshaling config: %w", err) } opts = append(opts, handler.GuestConfig(data)) } opts = append(opts, handler.Runtime(func(ctx context.Context) (wazero.Runtime, error) { return rt, nil })) mw, err := wasm.NewMiddleware(applyCtx(ctx), code, opts...) if err != nil { return nil, nil, fmt.Errorf("creating middleware: %w", err) } h := mw.NewHandler(ctx, next) // Traefik does not Close the middleware when creating a new instance on a configuration change. // When the middleware is marked to be GC, we need to close it so the wasm instance is properly closed. // Reference: https://github.com/traefik/traefik/issues/11119 runtime.SetFinalizer(h, func(_ http.Handler) { if err := mw.Close(ctx); err != nil { logger.Err(err).Msg("[wasm] middleware Close failed") } else { logger.Debug().Msg("[wasm] middleware Close ok") } }) return h, applyCtx, nil } // WasmMiddleware is an HTTP handler plugin wrapper. type WasmMiddleware struct { middlewareName string config reflect.Value builder wasmMiddlewareBuilder } // NewHandler creates a new HTTP handler. func (m WasmMiddleware) NewHandler(ctx context.Context, next http.Handler) (http.Handler, error) { return m.builder.newHandler(ctx, next, m.config, m.middlewareName) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/plugins/types.go
pkg/plugins/types.go
package plugins const ( runtimeYaegi = "yaegi" runtimeWasm = "wasm" ) const ( typeMiddleware = "middleware" typeProvider = "provider" ) type Settings struct { Envs []string `description:"Environment variables to forward to the wasm guest." json:"envs,omitempty" toml:"envs,omitempty" yaml:"envs,omitempty"` Mounts []string `description:"Directory to mount to the wasm guest." json:"mounts,omitempty" toml:"mounts,omitempty" yaml:"mounts,omitempty"` UseUnsafe bool `description:"Allow the plugin to use unsafe and syscall packages." json:"useUnsafe,omitempty" toml:"useUnsafe,omitempty" yaml:"useUnsafe,omitempty"` } // Descriptor The static part of a plugin configuration. type Descriptor struct { // ModuleName (required) ModuleName string `description:"plugin's module name." json:"moduleName,omitempty" toml:"moduleName,omitempty" yaml:"moduleName,omitempty" export:"true"` // Version (required) Version string `description:"plugin's version." json:"version,omitempty" toml:"version,omitempty" yaml:"version,omitempty" export:"true"` // Hash (optional) Hash string `description:"plugin's hash to validate'" json:"hash,omitempty" toml:"hash,omitempty" yaml:"hash,omitempty" export:"true"` // Settings (optional) Settings Settings `description:"Plugin's settings (works only for wasm plugins)." json:"settings,omitempty" toml:"settings,omitempty" yaml:"settings,omitempty" export:"true"` } // LocalDescriptor The static part of a local plugin configuration. type LocalDescriptor struct { // ModuleName (required) ModuleName string `description:"Plugin's module name." json:"moduleName,omitempty" toml:"moduleName,omitempty" yaml:"moduleName,omitempty" export:"true"` // Settings (optional) Settings Settings `description:"Plugin's settings (works only for wasm plugins)." json:"settings,omitempty" toml:"settings,omitempty" yaml:"settings,omitempty" export:"true"` } // Manifest The plugin manifest. type Manifest struct { DisplayName string `yaml:"displayName"` Type string `yaml:"type"` Runtime string `yaml:"runtime"` WasmPath string `yaml:"wasmPath"` Import string `yaml:"import"` BasePkg string `yaml:"basePkg"` Compatibility string `yaml:"compatibility"` Summary string `yaml:"summary"` UseUnsafe bool `yaml:"useUnsafe"` TestData map[string]interface{} `yaml:"testData"` } // IsYaegiPlugin returns true if the plugin is a Yaegi plugin. func (m *Manifest) IsYaegiPlugin() bool { // defaults always Yaegi to have backwards compatibility to plugins without runtime return m.Runtime == runtimeYaegi || m.Runtime == "" }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/plugins/plugins_test.go
pkg/plugins/plugins_test.go
package plugins import ( "testing" "github.com/stretchr/testify/assert" ) func Test_checkRemotePluginsConfiguration(t *testing.T) { testCases := []struct { name string plugins map[string]Descriptor wantErr bool }{ { name: "nil plugins configuration returns no error", plugins: nil, wantErr: false, }, { name: "malformed module name returns error", plugins: map[string]Descriptor{ "plugin1": {ModuleName: "invalid/module/name", Version: "v1.0.0"}, }, wantErr: true, }, { name: "malformed module name with path traversal returns error", plugins: map[string]Descriptor{ "plugin1": {ModuleName: "github.com/module/../name", Version: "v1.0.0"}, }, wantErr: true, }, { name: "malformed module name with encoded path traversal returns error", plugins: map[string]Descriptor{ "plugin1": {ModuleName: "github.com/module%2F%2E%2E%2Fname", Version: "v1.0.0"}, }, wantErr: true, }, { name: "malformed module name returns error", plugins: map[string]Descriptor{ "plugin1": {ModuleName: "invalid/module/name", Version: "v1.0.0"}, }, wantErr: true, }, { name: "missing plugin version returns error", plugins: map[string]Descriptor{ "plugin1": {ModuleName: "github.com/module/name", Version: ""}, }, wantErr: true, }, { name: "duplicate plugin module name returns error", plugins: map[string]Descriptor{ "plugin1": {ModuleName: "github.com/module/name", Version: "v1.0.0"}, "plugin2": {ModuleName: "github.com/module/name", Version: "v1.1.0"}, }, wantErr: true, }, { name: "valid plugins configuration returns no error", plugins: map[string]Descriptor{ "plugin1": {ModuleName: "github.com/module/name1", Version: "v1.0.0"}, "plugin2": {ModuleName: "github.com/module/name2", Version: "v1.1.0"}, }, wantErr: false, }, } for _, test := range testCases { t.Run(test.name, func(t *testing.T) { t.Parallel() err := checkRemotePluginsConfiguration(test.plugins) if test.wantErr { assert.Error(t, err) } else { assert.NoError(t, err) } }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/plugins/middlewarewasm_test.go
pkg/plugins/middlewarewasm_test.go
package plugins import ( "net/http" "net/http/httptest" "os" "path" "reflect" "testing" "github.com/rs/zerolog" "github.com/rs/zerolog/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tetratelabs/wazero" ) func TestSettingsWithoutSocket(t *testing.T) { cache := wazero.NewCompilationCache() zerolog.SetGlobalLevel(zerolog.DebugLevel) ctx := log.Logger.WithContext(t.Context()) t.Setenv("PLUGIN_TEST", "MY-TEST") t.Setenv("PLUGIN_TEST_B", "MY-TEST_B") testCases := []struct { desc string getSettings func(t *testing.T) (Settings, map[string]interface{}) expected string }{ { desc: "mounts path", getSettings: func(t *testing.T) (Settings, map[string]interface{}) { t.Helper() tempDir := t.TempDir() filePath := path.Join(tempDir, "hello.txt") err := os.WriteFile(filePath, []byte("content_test"), 0o644) require.NoError(t, err) return Settings{Mounts: []string{ tempDir, }}, map[string]interface{}{ "file": filePath, } }, expected: "content_test", }, { desc: "mounts src to dest", getSettings: func(t *testing.T) (Settings, map[string]interface{}) { t.Helper() tempDir := t.TempDir() filePath := path.Join(tempDir, "hello.txt") err := os.WriteFile(filePath, []byte("content_test"), 0o644) require.NoError(t, err) return Settings{Mounts: []string{ tempDir + ":/tmp", }}, map[string]interface{}{ "file": "/tmp/hello.txt", } }, expected: "content_test", }, { desc: "one env", getSettings: func(t *testing.T) (Settings, map[string]interface{}) { t.Helper() envs := []string{"PLUGIN_TEST"} return Settings{Envs: envs}, map[string]interface{}{ "envs": envs, } }, expected: "MY-TEST\n", }, { desc: "two env", getSettings: func(t *testing.T) (Settings, map[string]interface{}) { t.Helper() envs := []string{"PLUGIN_TEST", "PLUGIN_TEST_B"} return Settings{Envs: envs}, map[string]interface{}{ "envs": envs, } }, expected: "MY-TEST\nMY-TEST_B\n", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() settings, config := test.getSettings(t) builder := &wasmMiddlewareBuilder{path: "./fixtures/withoutsocket/plugin.wasm", cache: cache, settings: settings} cfg := reflect.ValueOf(config) m, applyCtx, err := builder.buildMiddleware(ctx, http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.WriteHeader(http.StatusTeapot) }), cfg, "test") require.NoError(t, err) rw := httptest.NewRecorder() req := httptest.NewRequestWithContext(applyCtx(ctx), "GET", "/", http.NoBody) m.ServeHTTP(rw, req) assert.Equal(t, http.StatusOK, rw.Code) assert.Equal(t, test.expected, rw.Body.String()) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/plugins/plugins.go
pkg/plugins/plugins.go
package plugins import ( "context" "errors" "fmt" "strings" "github.com/hashicorp/go-multierror" "github.com/rs/zerolog/log" "golang.org/x/mod/module" ) const localGoPath = "./plugins-local/" // SetupRemotePlugins setup remote plugins environment. func SetupRemotePlugins(manager *Manager, plugins map[string]Descriptor) error { err := checkRemotePluginsConfiguration(plugins) if err != nil { return fmt.Errorf("invalid configuration: %w", err) } err = manager.CleanArchives(plugins) if err != nil { return fmt.Errorf("unable to clean archives: %w", err) } ctx := context.Background() for pAlias, desc := range plugins { log.Ctx(ctx).Debug().Msgf("Installing plugin: %s: %s@%s", pAlias, desc.ModuleName, desc.Version) if err = manager.InstallPlugin(ctx, desc); err != nil { _ = manager.ResetAll() return fmt.Errorf("unable to install plugin %s: %w", pAlias, err) } } err = manager.WriteState(plugins) if err != nil { _ = manager.ResetAll() return fmt.Errorf("unable to write plugins state: %w", err) } return nil } func checkRemotePluginsConfiguration(plugins map[string]Descriptor) error { if plugins == nil { return nil } uniq := make(map[string]struct{}) var errs []string for pAlias, descriptor := range plugins { if err := module.CheckPath(descriptor.ModuleName); err != nil { errs = append(errs, fmt.Sprintf("%s: malformed plugin module name is missing: %s", pAlias, err)) } if descriptor.Version == "" { errs = append(errs, fmt.Sprintf("%s: plugin version is missing", pAlias)) } if _, ok := uniq[descriptor.ModuleName]; ok { errs = append(errs, fmt.Sprintf("only one version of a plugin is allowed, there is a duplicate of %s", descriptor.ModuleName)) continue } uniq[descriptor.ModuleName] = struct{}{} } if len(errs) > 0 { return errors.New(strings.Join(errs, ": ")) } return nil } // SetupLocalPlugins setup local plugins environment. func SetupLocalPlugins(plugins map[string]LocalDescriptor) error { if plugins == nil { return nil } uniq := make(map[string]struct{}) var errs *multierror.Error for pAlias, descriptor := range plugins { if descriptor.ModuleName == "" { errs = multierror.Append(errs, fmt.Errorf("%s: plugin name is missing", pAlias)) } if strings.HasPrefix(descriptor.ModuleName, "/") || strings.HasSuffix(descriptor.ModuleName, "/") { errs = multierror.Append(errs, fmt.Errorf("%s: plugin name should not start or end with a /", pAlias)) continue } if _, ok := uniq[descriptor.ModuleName]; ok { errs = multierror.Append(errs, fmt.Errorf("only one version of a plugin is allowed, there is a duplicate of %s", descriptor.ModuleName)) continue } uniq[descriptor.ModuleName] = struct{}{} err := checkLocalPluginManifest(descriptor) errs = multierror.Append(errs, err) } return errs.ErrorOrNil() } func checkLocalPluginManifest(descriptor LocalDescriptor) error { m, err := ReadManifest(localGoPath, descriptor.ModuleName) if err != nil { return err } var errs *multierror.Error switch m.Type { case typeMiddleware: if m.Runtime != runtimeYaegi && m.Runtime != runtimeWasm && m.Runtime != "" { errs = multierror.Append(errs, fmt.Errorf("%s: unsupported runtime '%q'", descriptor.ModuleName, m.Runtime)) } case typeProvider: if m.Runtime != runtimeYaegi && m.Runtime != "" { errs = multierror.Append(errs, fmt.Errorf("%s: unsupported runtime '%q'", descriptor.ModuleName, m.Runtime)) } default: errs = multierror.Append(errs, fmt.Errorf("%s: unsupported type %q", descriptor.ModuleName, m.Type)) } if m.IsYaegiPlugin() { if m.Import == "" { errs = multierror.Append(errs, fmt.Errorf("%s: missing import", descriptor.ModuleName)) } if !strings.HasPrefix(m.Import, descriptor.ModuleName) { errs = multierror.Append(errs, fmt.Errorf("the import %q must be related to the module name %q", m.Import, descriptor.ModuleName)) } } if m.DisplayName == "" { errs = multierror.Append(errs, fmt.Errorf("%s: missing DisplayName", descriptor.ModuleName)) } if m.Summary == "" { errs = multierror.Append(errs, fmt.Errorf("%s: missing Summary", descriptor.ModuleName)) } if m.TestData == nil { errs = multierror.Append(errs, fmt.Errorf("%s: missing TestData", descriptor.ModuleName)) } return errs.ErrorOrNil() }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/plugins/wasip_mock.go
pkg/plugins/wasip_mock.go
//go:build !linux && !darwin package plugins import ( "context" "github.com/tetratelabs/wazero" ) type ContextApplier func(ctx context.Context) context.Context // InstantiateHost instantiates the Host module. func InstantiateHost(ctx context.Context, runtime wazero.Runtime, mod wazero.CompiledModule, settings Settings) (ContextApplier, error) { return func(ctx context.Context) context.Context { return ctx }, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/plugins/downloader_test.go
pkg/plugins/downloader_test.go
package plugins import ( "archive/zip" "io" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestHTTPPluginDownloader_Download(t *testing.T) { tests := []struct { name string serverResponse func(w http.ResponseWriter, r *http.Request) fileAlreadyExists bool expectError bool }{ { name: "successful download", serverResponse: func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/zip") w.WriteHeader(http.StatusOK) require.NoError(t, fillDummyZip(w)) }, }, { name: "not modified response", serverResponse: func(w http.ResponseWriter, r *http.Request) { http.Error(w, "", http.StatusNotModified) }, fileAlreadyExists: true, }, { name: "server error", serverResponse: func(w http.ResponseWriter, r *http.Request) { http.Error(w, "internal server error", http.StatusInternalServerError) }, expectError: true, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(test.serverResponse)) defer server.Close() tempDir := t.TempDir() archivesPath := filepath.Join(tempDir, "archives") if test.fileAlreadyExists { createDummyZip(t, archivesPath) } baseURL, err := url.Parse(server.URL) require.NoError(t, err) downloader := &RegistryDownloader{ httpClient: server.Client(), baseURL: baseURL, archives: archivesPath, } ctx := t.Context() hash, err := downloader.Download(ctx, "test/plugin", "v1.0.0") if test.expectError { assert.Error(t, err) } else { assert.NoError(t, err) assert.NotEmpty(t, hash) // Check if archive file was created archivePath := downloader.buildArchivePath("test/plugin", "v1.0.0") assert.FileExists(t, archivePath) } }) } } func TestHTTPPluginDownloader_Check(t *testing.T) { tests := []struct { name string serverResponse func(w http.ResponseWriter, r *http.Request) expectError require.ErrorAssertionFunc }{ { name: "successful check", serverResponse: func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) }, expectError: require.NoError, }, { name: "failed check", serverResponse: func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusBadRequest) }, expectError: require.Error, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(test.serverResponse)) defer server.Close() tempDir := t.TempDir() archivesPath := filepath.Join(tempDir, "archives") baseURL, err := url.Parse(server.URL) require.NoError(t, err) downloader := &RegistryDownloader{ httpClient: server.Client(), baseURL: baseURL, archives: archivesPath, } ctx := t.Context() err = downloader.Check(ctx, "test/plugin", "v1.0.0", "testhash") test.expectError(t, err) }) } } func createDummyZip(t *testing.T, path string) { t.Helper() err := os.MkdirAll(path+"/test/plugin/", 0o755) require.NoError(t, err) zipfile, err := os.Create(path + "/test/plugin/v1.0.0.zip") require.NoError(t, err) defer zipfile.Close() err = fillDummyZip(zipfile) require.NoError(t, err) } func fillDummyZip(w io.Writer) error { writer := zip.NewWriter(w) file, err := writer.Create("test.txt") if err != nil { return err } _, _ = file.Write([]byte("test content")) _ = writer.Close() return nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/plugins/builder.go
pkg/plugins/builder.go
package plugins import ( "context" "errors" "fmt" "net/http" "path/filepath" "github.com/rs/zerolog/log" ) // Constructor creates a plugin handler. type Constructor func(context.Context, http.Handler) (http.Handler, error) type pluginMiddleware interface { NewHandler(ctx context.Context, next http.Handler) (http.Handler, error) } type middlewareBuilder interface { newMiddleware(config map[string]interface{}, middlewareName string) (pluginMiddleware, error) } // Builder is a plugin builder. type Builder struct { providerBuilders map[string]providerBuilder middlewareBuilders map[string]middlewareBuilder } // NewBuilder creates a new Builder. func NewBuilder(manager *Manager, plugins map[string]Descriptor, localPlugins map[string]LocalDescriptor) (*Builder, error) { ctx := context.Background() pb := &Builder{ middlewareBuilders: map[string]middlewareBuilder{}, providerBuilders: map[string]providerBuilder{}, } for pName, desc := range plugins { manifest, err := manager.ReadManifest(desc.ModuleName) if err != nil { _ = manager.ResetAll() return nil, fmt.Errorf("%s: failed to read manifest: %w", desc.ModuleName, err) } logger := log.With(). Str("plugin", "plugin-"+pName). Str("module", desc.ModuleName). Str("runtime", manifest.Runtime). Logger() logCtx := logger.WithContext(ctx) switch manifest.Type { case typeMiddleware: middleware, err := newMiddlewareBuilder(logCtx, manager.GoPath(), manifest, desc.ModuleName, desc.Settings) if err != nil { return nil, err } pb.middlewareBuilders[pName] = middleware case typeProvider: pBuilder, err := newProviderBuilder(logCtx, manifest, manager.GoPath(), desc.Settings) if err != nil { return nil, fmt.Errorf("%s: %w", desc.ModuleName, err) } pb.providerBuilders[pName] = pBuilder default: return nil, fmt.Errorf("unknow plugin type: %s", manifest.Type) } } for pName, desc := range localPlugins { manifest, err := ReadManifest(localGoPath, desc.ModuleName) if err != nil { return nil, fmt.Errorf("%s: failed to read manifest: %w", desc.ModuleName, err) } logger := log.With(). Str("plugin", "plugin-"+pName). Str("module", desc.ModuleName). Str("runtime", manifest.Runtime). Logger() logCtx := logger.WithContext(ctx) switch manifest.Type { case typeMiddleware: middleware, err := newMiddlewareBuilder(logCtx, localGoPath, manifest, desc.ModuleName, desc.Settings) if err != nil { return nil, err } pb.middlewareBuilders[pName] = middleware case typeProvider: builder, err := newProviderBuilder(logCtx, manifest, localGoPath, desc.Settings) if err != nil { return nil, fmt.Errorf("%s: %w", desc.ModuleName, err) } pb.providerBuilders[pName] = builder default: return nil, fmt.Errorf("unknow plugin type: %s", manifest.Type) } } return pb, nil } // Build builds a middleware plugin. func (b Builder) Build(pName string, config map[string]interface{}, middlewareName string) (Constructor, error) { if b.middlewareBuilders == nil { return nil, fmt.Errorf("no plugin definitions in the static configuration: %s", pName) } // plugin (pName) can be located in yaegi or wasm middleware builders. if descriptor, ok := b.middlewareBuilders[pName]; ok { m, err := descriptor.newMiddleware(config, middlewareName) if err != nil { return nil, err } return m.NewHandler, nil } return nil, fmt.Errorf("unknown plugin type: %s", pName) } func newMiddlewareBuilder(ctx context.Context, goPath string, manifest *Manifest, moduleName string, settings Settings) (middlewareBuilder, error) { switch manifest.Runtime { case runtimeWasm: wasmPath, err := getWasmPath(manifest) if err != nil { return nil, fmt.Errorf("wasm path: %w", err) } return newWasmMiddlewareBuilder(goPath, moduleName, wasmPath, settings) case runtimeYaegi, "": i, err := newInterpreter(ctx, goPath, manifest, settings) if err != nil { return nil, fmt.Errorf("failed to create Yaegi interpreter: %w", err) } return newYaegiMiddlewareBuilder(i, manifest.BasePkg, manifest.Import) default: return nil, fmt.Errorf("unknown plugin runtime: %s", manifest.Runtime) } } func newProviderBuilder(ctx context.Context, manifest *Manifest, goPath string, settings Settings) (providerBuilder, error) { switch manifest.Runtime { case runtimeYaegi, "": i, err := newInterpreter(ctx, goPath, manifest, settings) if err != nil { return providerBuilder{}, err } return providerBuilder{ interpreter: i, Import: manifest.Import, BasePkg: manifest.BasePkg, }, nil default: return providerBuilder{}, fmt.Errorf("unknown plugin runtime: %s", manifest.Runtime) } } func getWasmPath(manifest *Manifest) (string, error) { wasmPath := manifest.WasmPath if wasmPath == "" { wasmPath = "plugin.wasm" } if !filepath.IsLocal(wasmPath) { return "", errors.New("wasmPath must be a local path") } return wasmPath, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/plugins/wasip.go
pkg/plugins/wasip.go
//go:build linux || darwin package plugins import ( "context" "fmt" "os" "github.com/stealthrocket/wasi-go/imports" wazergo_wasip1 "github.com/stealthrocket/wasi-go/imports/wasi_snapshot_preview1" "github.com/stealthrocket/wazergo" "github.com/tetratelabs/wazero" wazero_wasip1 "github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1" ) type ContextApplier func(ctx context.Context) context.Context // InstantiateHost instantiates the Host module according to the guest requirements (for now only SocketExtensions). func InstantiateHost(ctx context.Context, runtime wazero.Runtime, mod wazero.CompiledModule, settings Settings) (ContextApplier, error) { if extension := imports.DetectSocketsExtension(mod); extension != nil { envs := []string{} for _, env := range settings.Envs { envs = append(envs, fmt.Sprintf("%s=%s", env, os.Getenv(env))) } builder := imports.NewBuilder().WithSocketsExtension("auto", mod) if len(envs) > 0 { builder.WithEnv(envs...) } if len(settings.Mounts) > 0 { builder.WithDirs(settings.Mounts...) } ctx, sys, err := builder.Instantiate(ctx, runtime) if err != nil { return nil, err } inst, err := wazergo.Instantiate(ctx, runtime, wazergo_wasip1.NewHostModule(*extension), wazergo_wasip1.WithWASI(sys)) if err != nil { return nil, fmt.Errorf("wazergo instantiation: %w", err) } return func(ctx context.Context) context.Context { return wazergo.WithModuleInstance(ctx, inst) }, nil } _, err := wazero_wasip1.Instantiate(ctx, runtime) if err != nil { return nil, fmt.Errorf("wazero instantiation: %w", err) } return func(ctx context.Context) context.Context { return ctx }, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/plugins/manager.go
pkg/plugins/manager.go
package plugins import ( zipa "archive/zip" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "os" "path/filepath" "strings" "golang.org/x/mod/module" "golang.org/x/mod/zip" "gopkg.in/yaml.v3" ) const ( sourcesFolder = "sources" archivesFolder = "archives" stateFilename = "state.json" goPathSrc = "src" pluginManifest = ".traefik.yml" ) const pluginsURL = "https://plugins.traefik.io/public/" const ( hashHeader = "X-Plugin-Hash" ) // ManagerOptions the options of a Traefik plugins manager. type ManagerOptions struct { Output string } // Manager manages Traefik plugins lifecycle operations including storage, and manifest reading. type Manager struct { downloader PluginDownloader stateFile string archives string sources string goPath string } // NewManager creates a new Traefik plugins manager. func NewManager(downloader PluginDownloader, opts ManagerOptions) (*Manager, error) { sourcesRootPath := filepath.Join(filepath.FromSlash(opts.Output), sourcesFolder) err := resetDirectory(sourcesRootPath) if err != nil { return nil, err } goPath, err := os.MkdirTemp(sourcesRootPath, "gop-*") if err != nil { return nil, fmt.Errorf("failed to create GoPath: %w", err) } archivesPath := filepath.Join(filepath.FromSlash(opts.Output), archivesFolder) err = os.MkdirAll(archivesPath, 0o755) if err != nil { return nil, fmt.Errorf("failed to create archives directory %s: %w", archivesPath, err) } return &Manager{ downloader: downloader, stateFile: filepath.Join(archivesPath, stateFilename), archives: archivesPath, sources: filepath.Join(goPath, goPathSrc), goPath: goPath, }, nil } // InstallPlugin download and unzip the given plugin. func (m *Manager) InstallPlugin(ctx context.Context, plugin Descriptor) error { hash, err := m.downloader.Download(ctx, plugin.ModuleName, plugin.Version) if err != nil { return fmt.Errorf("unable to download plugin %s: %w", plugin.ModuleName, err) } if plugin.Hash != "" { if plugin.Hash != hash { return fmt.Errorf("invalid hash for plugin %s, expected %s, got %s", plugin.ModuleName, plugin.Hash, hash) } } else { err = m.downloader.Check(ctx, plugin.ModuleName, plugin.Version, hash) if err != nil { return fmt.Errorf("unable to check archive integrity of the plugin %s: %w", plugin.ModuleName, err) } } if err = m.unzip(plugin.ModuleName, plugin.Version); err != nil { return fmt.Errorf("unable to unzip plugin %s: %w", plugin.ModuleName, err) } return nil } // GoPath gets the plugins GoPath. func (m *Manager) GoPath() string { return m.goPath } // ReadManifest reads a plugin manifest. func (m *Manager) ReadManifest(moduleName string) (*Manifest, error) { return ReadManifest(m.goPath, moduleName) } // ReadManifest reads a plugin manifest. func ReadManifest(goPath, moduleName string) (*Manifest, error) { p := filepath.Join(goPath, goPathSrc, filepath.FromSlash(moduleName), pluginManifest) file, err := os.Open(p) if err != nil { return nil, fmt.Errorf("failed to open the plugin manifest %s: %w", p, err) } defer func() { _ = file.Close() }() m := &Manifest{} err = yaml.NewDecoder(file).Decode(m) if err != nil { return nil, fmt.Errorf("failed to decode the plugin manifest %s: %w", p, err) } return m, nil } // CleanArchives cleans plugins archives. func (m *Manager) CleanArchives(plugins map[string]Descriptor) error { if _, err := os.Stat(m.stateFile); os.IsNotExist(err) { return nil } stateFile, err := os.Open(m.stateFile) if err != nil { return fmt.Errorf("failed to open state file %s: %w", m.stateFile, err) } previous := make(map[string]string) err = json.NewDecoder(stateFile).Decode(&previous) if err != nil { return fmt.Errorf("failed to decode state file %s: %w", m.stateFile, err) } for pName, pVersion := range previous { for _, desc := range plugins { if desc.ModuleName == pName && desc.Version != pVersion { archivePath := m.buildArchivePath(pName, pVersion) if err = os.RemoveAll(archivePath); err != nil { return fmt.Errorf("failed to remove archive %s: %w", archivePath, err) } } } } return nil } // WriteState writes the plugins state files. func (m *Manager) WriteState(plugins map[string]Descriptor) error { state := make(map[string]string) for _, descriptor := range plugins { state[descriptor.ModuleName] = descriptor.Version } mp, err := json.MarshalIndent(state, "", " ") if err != nil { return fmt.Errorf("unable to marshal plugin state: %w", err) } return os.WriteFile(m.stateFile, mp, 0o600) } // ResetAll resets all plugins related directories. func (m *Manager) ResetAll() error { if m.goPath == "" { return errors.New("goPath is empty") } err := resetDirectory(filepath.Join(m.goPath, "..")) if err != nil { return fmt.Errorf("unable to reset plugins GoPath directory %s: %w", m.goPath, err) } err = resetDirectory(m.archives) if err != nil { return fmt.Errorf("unable to reset plugins archives directory: %w", err) } return nil } func (m *Manager) unzip(pName, pVersion string) error { err := m.unzipModule(pName, pVersion) if err == nil { return nil } // Unzip as a generic archive if the module unzip fails. // This is useful for plugins that have vendor directories or other structures. // This is also useful for wasm plugins. return m.unzipArchive(pName, pVersion) } func (m *Manager) unzipModule(pName, pVersion string) error { src := m.buildArchivePath(pName, pVersion) dest := filepath.Join(m.sources, filepath.FromSlash(pName)) return zip.Unzip(dest, module.Version{Path: pName, Version: pVersion}, src) } func (m *Manager) unzipArchive(pName, pVersion string) error { zipPath := m.buildArchivePath(pName, pVersion) archive, err := zipa.OpenReader(zipPath) if err != nil { return err } defer func() { _ = archive.Close() }() dest := filepath.Join(m.sources, filepath.FromSlash(pName)) for _, f := range archive.File { err = m.unzipFile(f, dest) if err != nil { return fmt.Errorf("unable to unzip %s: %w", f.Name, err) } } return nil } func (m *Manager) unzipFile(f *zipa.File, dest string) error { rc, err := f.Open() if err != nil { return err } defer func() { _ = rc.Close() }() // Split to discard the first part of the path when the archive is a Yaegi go plugin with vendoring. // In this case the path starts with `[organization]-[project]-[release commit sha1]/`. pathParts := strings.SplitN(f.Name, "/", 2) var fileName string if len(pathParts) < 2 { fileName = pathParts[0] } else { fileName = pathParts[1] } // Validate and sanitize the file path. cleanName := filepath.Clean(fileName) if strings.Contains(cleanName, "..") { return fmt.Errorf("invalid file path in archive: %s", f.Name) } filePath := filepath.Join(dest, cleanName) absFilePath, err := filepath.Abs(filePath) if err != nil { return fmt.Errorf("resolving file path: %w", err) } absDest, err := filepath.Abs(dest) if err != nil { return fmt.Errorf("resolving destination directory: %w", err) } if !strings.HasPrefix(absFilePath, absDest) { return fmt.Errorf("file path escapes destination directory: %s", absFilePath) } if f.FileInfo().IsDir() { err = os.MkdirAll(filePath, f.Mode()) if err != nil { return fmt.Errorf("unable to create archive directory %s: %w", filePath, err) } return nil } err = os.MkdirAll(filepath.Dir(filePath), 0o750) if err != nil { return fmt.Errorf("unable to create archive directory %s for file %s: %w", filepath.Dir(filePath), filePath, err) } elt, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) if err != nil { return err } defer func() { _ = elt.Close() }() _, err = io.Copy(elt, rc) if err != nil { return err } return nil } func (m *Manager) buildArchivePath(pName, pVersion string) string { return filepath.Join(m.archives, filepath.FromSlash(pName), pVersion+".zip") } func resetDirectory(dir string) error { dirPath, err := filepath.Abs(dir) if err != nil { return fmt.Errorf("unable to get absolute path of %s: %w", dir, err) } currentPath, err := os.Getwd() if err != nil { return fmt.Errorf("unable to get the current directory: %w", err) } if strings.HasPrefix(currentPath, dirPath) { return fmt.Errorf("cannot be deleted: the directory path %s is the parent of the current path %s", dirPath, currentPath) } err = os.RemoveAll(dir) if err != nil { return fmt.Errorf("unable to remove directory %s: %w", dirPath, err) } err = os.MkdirAll(dir, 0o755) if err != nil { return fmt.Errorf("unable to create directory %s: %w", dirPath, err) } return nil } func computeHash(filepath string) (string, error) { file, err := os.Open(filepath) if err != nil { return "", err } hash := sha256.New() if _, err := io.Copy(hash, file); err != nil { return "", err } sum := hash.Sum(nil) return hex.EncodeToString(sum), nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/plugins/fixtures/src/testpluginsafe/testpluginsafe.go
pkg/plugins/fixtures/src/testpluginsafe/testpluginsafe.go
package testpluginsafe import ( "context" "net/http" ) type Config struct { Message string } func CreateConfig() *Config { return &Config{Message: "safe plugin"} } func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("X-Test-Plugin", "safe") next.ServeHTTP(rw, req) }), nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/plugins/fixtures/src/testpluginunsafe/testpluginunsafe.go
pkg/plugins/fixtures/src/testpluginunsafe/testpluginunsafe.go
package testpluginunsafe import ( "context" "net/http" "unsafe" ) type Config struct { Message string } func CreateConfig() *Config { return &Config{Message: "unsafe only plugin"} } func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) { // Use ONLY unsafe to test it's available size := unsafe.Sizeof(int(0)) return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("X-Test-Plugin", "unsafe-only") rw.Header().Set("X-Test-Unsafe-Size", string(rune(size))) next.ServeHTTP(rw, req) }), nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/plugins/fixtures/src/testpluginsyscall/testpluginsyscall.go
pkg/plugins/fixtures/src/testpluginsyscall/testpluginsyscall.go
package testpluginsyscall import ( "context" "net/http" "syscall" "unsafe" ) type Config struct { Message string } func CreateConfig() *Config { return &Config{Message: "syscall plugin"} } func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) { // Use syscall and unsafe to test they're available pid := syscall.Getpid() size := unsafe.Sizeof(int(0)) return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("X-Test-Plugin", "syscall") rw.Header().Set("X-Test-PID", string(rune(pid))) rw.Header().Set("X-Test-Size", string(rune(size))) next.ServeHTTP(rw, req) }), nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/plugins/fixtures/withoutsocket/demo.go
pkg/plugins/fixtures/withoutsocket/demo.go
package main import ( "encoding/json" "fmt" "net/http" "os" "github.com/http-wasm/http-wasm-guest-tinygo/handler" "github.com/http-wasm/http-wasm-guest-tinygo/handler/api" ) type config struct { File string `json:"file"` Envs []string `json:"envs"` } var cfg config // Built with // tinygo build -o plugin.wasm -scheduler=none --no-debug -target=wasi ./demo.go func main() { err := json.Unmarshal(handler.Host.GetConfig(), &cfg) if err != nil { handler.Host.Log(api.LogLevelError, fmt.Sprintf("Could not load config %v", err)) os.Exit(1) } handler.HandleRequestFn = handleRequest } func handleRequest(req api.Request, resp api.Response) (next bool, reqCtx uint32) { var bodyContent []byte if cfg.File != "" { var err error bodyContent, err = os.ReadFile(cfg.File) if err != nil { resp.SetStatusCode(http.StatusInternalServerError) resp.Body().Write([]byte(fmt.Sprintf("error reading file %q: %w", cfg.File, err.Error()))) return false, 0 } } if len(cfg.Envs) > 0 { for _, env := range cfg.Envs { bodyContent = append(bodyContent, []byte(os.Getenv(env)+"\n")...) } } resp.Body().Write(bodyContent) return false, 0 }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/types/host_resolver.go
pkg/types/host_resolver.go
package types // HostResolverConfig contain configuration for CNAME Flattening. type HostResolverConfig struct { CnameFlattening bool `description:"A flag to enable/disable CNAME flattening" json:"cnameFlattening,omitempty" toml:"cnameFlattening,omitempty" yaml:"cnameFlattening,omitempty" export:"true"` ResolvConfig string `description:"resolv.conf used for DNS resolving" json:"resolvConfig,omitempty" toml:"resolvConfig,omitempty" yaml:"resolvConfig,omitempty" export:"true"` ResolvDepth int `description:"The maximal depth of DNS recursive resolving" json:"resolvDepth,omitempty" toml:"resolvDepth,omitempty" yaml:"resolvDepth,omitempty" export:"true"` } // SetDefaults sets the default values. func (h *HostResolverConfig) SetDefaults() { h.CnameFlattening = false h.ResolvConfig = "/etc/resolv.conf" h.ResolvDepth = 5 }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/types/tls_test.go
pkg/types/tls_test.go
package types import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) // go run $GOROOT/src/crypto/tls/generate_cert.go --rsa-bits 1024 --host localhost --start-date "Jan 1 00:00:00 1970" --duration=1000000h var cert = `-----BEGIN CERTIFICATE----- MIIB9jCCAV+gAwIBAgIQI3edJckNbicw4WIHs5Ws9TANBgkqhkiG9w0BAQsFADAS MRAwDgYDVQQKEwdBY21lIENvMCAXDTcwMDEwMTAwMDAwMFoYDzIwODQwMTI5MTYw MDAwWjASMRAwDgYDVQQKEwdBY21lIENvMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB iQKBgQCb8oWyME1QRBoMLFei3M8TVKwfZfW74cVjtcugCBMTTOTCouEIgjjmiMv6 FdMio2uBcgeD9R3dOtjjnA7N+xjwZ4vIPqDlJRE3YbfpV9igVX3sXU7ssHTSH0vs R0TuYJwGReIFUnu5QIjGwVorodF+CQ8dTnyXVLeQVU9kvjohHwIDAQABo0swSTAO BgNVHQ8BAf8EBAMCBaAwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDAYDVR0TAQH/BAIw ADAUBgNVHREEDTALgglsb2NhbGhvc3QwDQYJKoZIhvcNAQELBQADgYEADqylUQ/4 lrxh4h8UUQ2wKATQ2kG2YvMGlaIhr2vPZo2QDBlmL2xzai7YXX3+JZyM15TNCamn WtFR7WQIOHzKA1GkR9WkaXKmFbJjhGMSZVCG6ghhTjzB+stBYZXhBsdjCJbkZWBu OeI73oivo0MdI+4iCYCo7TnoY4PZGObwcgI= -----END CERTIFICATE-----` var key = `-----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJvyhbIwTVBEGgws V6LczxNUrB9l9bvhxWO1y6AIExNM5MKi4QiCOOaIy/oV0yKja4FyB4P1Hd062OOc Ds37GPBni8g+oOUlETdht+lX2KBVfexdTuywdNIfS+xHRO5gnAZF4gVSe7lAiMbB Wiuh0X4JDx1OfJdUt5BVT2S+OiEfAgMBAAECgYA9+PbghQl0aFvhko2RDybLi86K +73X2DTVFx3AjvTlqp0OLCQ5eWabVqmYzKuHDGJgoqwR6Irhq80dRpsriCm0YNui mMV35bbimOKz9FoCTKx0ZB6xsqrVoFhjVmX3DOD9Txe41H42ZxmccOKZndR/QaXz VV+1W/Wbz2VawnkyYQJBAMvF6w2eOJRRoN8e7GM7b7uqkupJPp9axgFREoJZb16W mqXUZnH4Cydzc5keG4yknQRHdgz6RrQxnvR7GyKHLfUCQQDD6qG9D5BX0+mNW6TG PRwW/L2qWgnmg9lxtSSQat9ZOnBhw2OLPi0zTu4p70oSmU67/YJr50HEoJpRccZJ mnJDAkBdBTtY2xpe8qhqUjZ80hweYi5wzwDMQ+bRoQ2+/U6usjdkbgJaEm4dE0H4 6tqOqHKZCnokUHfIOEKkvjHT4DulAkBAgiJNSTGi6aDOLa28pGR6YS/mRo1Z/HH9 kcJ/VuFB1Q8p8Zb2QzvI2CVtY2AFbbtSBPALrXKnVqZZSNgcZiFXAkEAvcLKaEXE haGMGwq2BLADPHqAR3hdCJL3ikMJwWUsTkTjm973iEIEZfF5j57EzRI4bASm4Zq5 Zt3BcblLODQ//w== -----END PRIVATE KEY-----` func TestClientTLS_CreateTLSConfig(t *testing.T) { tests := []struct { desc string clientTLS ClientTLS wantCertLen int wantCALen int wantErr bool }{ { desc: "Configure CA", clientTLS: ClientTLS{CA: cert}, wantCALen: 1, wantErr: false, }, { desc: "Configure the client keyPair from strings", clientTLS: ClientTLS{Cert: cert, Key: key}, wantCertLen: 1, wantErr: false, }, { desc: "Configure the client keyPair from files", clientTLS: ClientTLS{Cert: "fixtures/cert.pem", Key: "fixtures/key.pem"}, wantCertLen: 1, wantErr: false, }, { desc: "Configure InsecureSkipVerify", clientTLS: ClientTLS{InsecureSkipVerify: true}, wantErr: false, }, { desc: "Return an error if only the client cert is provided", clientTLS: ClientTLS{Cert: cert}, wantErr: true, }, { desc: "Return an error if only the client key is provided", clientTLS: ClientTLS{Key: key}, wantErr: true, }, { desc: "Return an error if only the client cert is of type file", clientTLS: ClientTLS{Cert: "fixtures/cert.pem", Key: key}, wantErr: true, }, { desc: "Return an error if only the client key is of type file", clientTLS: ClientTLS{Cert: cert, Key: "fixtures/key.pem"}, wantErr: true, }, { desc: "Return an error if the client cert does not exist", clientTLS: ClientTLS{Cert: "fixtures/cert2.pem", Key: "fixtures/key.pem"}, wantErr: true, }, { desc: "Return an error if the client key does not exist", clientTLS: ClientTLS{Cert: "fixtures/cert.pem", Key: "fixtures/key2.pem"}, wantErr: true, }, } for _, test := range tests { t.Run(test.desc, func(t *testing.T) { tlsConfig, err := test.clientTLS.CreateTLSConfig(t.Context()) if test.wantErr { require.Error(t, err) return } require.NoError(t, err) assert.Len(t, tlsConfig.Certificates, test.wantCertLen) assert.Equal(t, test.clientTLS.InsecureSkipVerify, tlsConfig.InsecureSkipVerify) if test.wantCALen > 0 { assert.Len(t, tlsConfig.RootCAs.Subjects(), test.wantCALen) return } assert.Nil(t, tlsConfig.RootCAs) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/types/domains.go
pkg/types/domains.go
package types import ( "strings" ) // +k8s:deepcopy-gen=true // Domain holds a domain name with SANs. type Domain struct { // Main defines the main domain name. Main string `description:"Default subject name." json:"main,omitempty" toml:"main,omitempty" yaml:"main,omitempty"` // SANs defines the subject alternative domain names. SANs []string `description:"Subject alternative names." json:"sans,omitempty" toml:"sans,omitempty" yaml:"sans,omitempty"` } // ToStrArray convert a domain into an array of strings. func (d *Domain) ToStrArray() []string { var domains []string if len(d.Main) > 0 { domains = []string{d.Main} } return append(domains, d.SANs...) } // Set sets a domains from an array of strings. func (d *Domain) Set(domains []string) { if len(domains) > 0 { d.Main = domains[0] d.SANs = domains[1:] } } // MatchDomain returns true if a domain match the cert domain. func MatchDomain(domain, certDomain string) bool { if domain == certDomain { return true } for len(certDomain) > 0 && certDomain[len(certDomain)-1] == '.' { certDomain = certDomain[:len(certDomain)-1] } labels := strings.Split(domain, ".") for i := range labels { labels[i] = "*" candidate := strings.Join(labels, ".") if certDomain == candidate { return true } } return false } // CanonicalDomain returns a lower case domain with trim space. func CanonicalDomain(domain string) string { return strings.ToLower(strings.TrimSpace(domain)) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/types/zz_generated.deepcopy.go
pkg/types/zz_generated.deepcopy.go
//go:build !ignore_autogenerated // +build !ignore_autogenerated /* The MIT License (MIT) Copyright (c) 2016-2020 Containous SAS; 2020-2026 Traefik Labs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Code generated by deepcopy-gen. DO NOT EDIT. package types // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ClientTLS) DeepCopyInto(out *ClientTLS) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClientTLS. func (in *ClientTLS) DeepCopy() *ClientTLS { if in == nil { return nil } out := new(ClientTLS) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Domain) DeepCopyInto(out *Domain) { *out = *in if in.SANs != nil { in, out := &in.SANs, &out.SANs *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Domain. func (in *Domain) DeepCopy() *Domain { if in == nil { return nil } out := new(Domain) in.DeepCopyInto(out) return out }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/types/k8sdetector.go
pkg/types/k8sdetector.go
package types import ( "context" "errors" "fmt" "os" "strings" "github.com/rs/zerolog/log" "go.opentelemetry.io/otel/sdk/resource" semconv "go.opentelemetry.io/otel/semconv/v1.37.0" kerror "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" kclientset "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" ) // K8sAttributesDetector detects the metadata of the Traefik pod running in a Kubernetes cluster. // It reads the pod name from the hostname file and the namespace from the service account namespace file and queries the Kubernetes API to get the pod's UID. type K8sAttributesDetector struct{} func (K8sAttributesDetector) Detect(ctx context.Context) (*resource.Resource, error) { attrs := os.Getenv("OTEL_RESOURCE_ATTRIBUTES") if strings.Contains(attrs, string(semconv.K8SPodNameKey)) || strings.Contains(attrs, string(semconv.K8SPodUIDKey)) { return resource.Empty(), nil } // The InClusterConfig function returns a config for the Kubernetes API server // when it is running inside a Kubernetes cluster. config, err := rest.InClusterConfig() if err != nil && errors.Is(err, rest.ErrNotInCluster) { return resource.Empty(), nil } if err != nil { return nil, fmt.Errorf("creating in cluster config: %w", err) } client, err := kclientset.NewForConfig(config) if err != nil { return nil, fmt.Errorf("creating Kubernetes client: %w", err) } podName, err := os.Hostname() if err != nil { return nil, fmt.Errorf("getting pod name: %w", err) } podNamespaceBytes, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace") if err != nil { return nil, fmt.Errorf("getting pod namespace: %w", err) } podNamespace := string(podNamespaceBytes) pod, err := client.CoreV1().Pods(podNamespace).Get(ctx, podName, metav1.GetOptions{}) if err != nil && (kerror.IsForbidden(err) || kerror.IsNotFound(err)) { log.Error().Err(err).Msg("Unable to build K8s resource attributes for Traefik pod") return resource.Empty(), nil } if err != nil { return nil, fmt.Errorf("getting pod metadata: %w", err) } // To avoid version conflicts with other detectors, we use a Schemaless resource. return resource.NewSchemaless( semconv.K8SPodUID(string(pod.UID)), semconv.K8SPodName(pod.Name), semconv.K8SNamespaceName(podNamespace), ), nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/types/route_appender.go
pkg/types/route_appender.go
package types import ( "github.com/gorilla/mux" ) // RouteAppender appends routes on a router (/api, /ping ...). type RouteAppender interface { Append(systemRouter *mux.Router) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false