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/types/http_code_range.go
pkg/types/http_code_range.go
package types import ( "slices" "strconv" "strings" ) // HTTPCodeRanges holds HTTP code ranges. type HTTPCodeRanges [][2]int // NewHTTPCodeRanges creates HTTPCodeRanges from a given []string. // Break out the http status code ranges into a low int and high int // for ease of use at runtime. func NewHTTPCodeRanges(strBlocks []string) (HTTPCodeRanges, error) { var blocks HTTPCodeRanges for _, block := range strBlocks { codes := strings.Split(block, "-") // if only a single HTTP code was configured, assume the best and create the correct configuration on the user's behalf if len(codes) == 1 { codes = append(codes, codes[0]) } lowCode, err := strconv.Atoi(codes[0]) if err != nil { return nil, err } highCode, err := strconv.Atoi(codes[1]) if err != nil { return nil, err } blocks = append(blocks, [2]int{lowCode, highCode}) } return blocks, nil } // Contains tests whether the passed status code is within one of its HTTP code ranges. func (h HTTPCodeRanges) Contains(statusCode int) bool { return slices.ContainsFunc(h, func(block [2]int) bool { return statusCode >= block[0] && statusCode <= block[1] }) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/types/domain_test.go
pkg/types/domain_test.go
package types import ( "testing" "github.com/stretchr/testify/assert" ) func TestDomain_ToStrArray(t *testing.T) { testCases := []struct { desc string domain Domain expected []string }{ { desc: "with Main and SANs", domain: Domain{ Main: "foo.com", SANs: []string{"bar.foo.com", "bir.foo.com"}, }, expected: []string{"foo.com", "bar.foo.com", "bir.foo.com"}, }, { desc: "without SANs", domain: Domain{ Main: "foo.com", }, expected: []string{"foo.com"}, }, { desc: "without Main", domain: Domain{ SANs: []string{"bar.foo.com", "bir.foo.com"}, }, expected: []string{"bar.foo.com", "bir.foo.com"}, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() domains := test.domain.ToStrArray() assert.Equal(t, test.expected, domains) }) } } func TestDomain_Set(t *testing.T) { testCases := []struct { desc string rawDomains []string expected Domain }{ { desc: "with 3 domains", rawDomains: []string{"foo.com", "bar.foo.com", "bir.foo.com"}, expected: Domain{ Main: "foo.com", SANs: []string{"bar.foo.com", "bir.foo.com"}, }, }, { desc: "with 1 domain", rawDomains: []string{"foo.com"}, expected: Domain{ Main: "foo.com", SANs: []string{}, }, }, { desc: "", rawDomains: nil, expected: Domain{}, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() domain := Domain{} domain.Set(test.rawDomains) assert.Equal(t, test.expected, domain) }) } } func TestMatchDomain(t *testing.T) { testCases := []struct { desc string certDomain string domain string expected bool }{ { desc: "exact match", certDomain: "traefik.wtf", domain: "traefik.wtf", expected: true, }, { desc: "wildcard and root domain", certDomain: "*.traefik.wtf", domain: "traefik.wtf", expected: false, }, { desc: "wildcard and sub domain", certDomain: "*.traefik.wtf", domain: "sub.traefik.wtf", expected: true, }, { desc: "wildcard and sub sub domain", certDomain: "*.traefik.wtf", domain: "sub.sub.traefik.wtf", expected: false, }, { desc: "double wildcard and sub sub domain", certDomain: "*.*.traefik.wtf", domain: "sub.sub.traefik.wtf", expected: true, }, { desc: "sub sub domain and invalid wildcard", certDomain: "sub.*.traefik.wtf", domain: "sub.sub.traefik.wtf", expected: false, }, { desc: "sub sub domain and valid wildcard", certDomain: "*.sub.traefik.wtf", domain: "sub.sub.traefik.wtf", expected: true, }, { desc: "dot replaced by a char", certDomain: "sub.sub.traefik.wtf", domain: "sub.sub.traefikiwtf", expected: false, }, { desc: "*", certDomain: "*", domain: "sub.sub.traefik.wtf", expected: false, }, { desc: "?", certDomain: "?", domain: "sub.sub.traefik.wtf", expected: false, }, { desc: "...................", certDomain: "...................", domain: "sub.sub.traefik.wtf", expected: false, }, { desc: "wildcard and *", certDomain: "*.traefik.wtf", domain: "*.*.traefik.wtf", expected: false, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() domains := MatchDomain(test.domain, test.certDomain) assert.Equal(t, test.expected, domains) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/types/file_or_content.go
pkg/types/file_or_content.go
package types import "os" // FileOrContent holds a file path or content. type FileOrContent string // String returns the FileOrContent in string format. func (f FileOrContent) String() string { return string(f) } // IsPath returns true if the FileOrContent is a file path, otherwise returns false. func (f FileOrContent) IsPath() bool { _, err := os.Stat(f.String()) return err == nil } // Read returns the content after reading the FileOrContent variable. func (f FileOrContent) Read() ([]byte, error) { var content []byte if f.IsPath() { var err error content, err = os.ReadFile(f.String()) if err != nil { return nil, err } } else { content = []byte(f) } return content, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/types/tls.go
pkg/types/tls.go
package types import ( "context" "crypto/tls" "crypto/x509" "errors" "fmt" "os" "github.com/rs/zerolog/log" ) // +k8s:deepcopy-gen=true // ClientTLS holds TLS specific configurations as client // CA, Cert and Key can be either path or file contents. type ClientTLS struct { CA string `description:"TLS CA" json:"ca,omitempty" toml:"ca,omitempty" yaml:"ca,omitempty"` Cert string `description:"TLS cert" json:"cert,omitempty" toml:"cert,omitempty" yaml:"cert,omitempty"` Key string `description:"TLS key" json:"key,omitempty" toml:"key,omitempty" yaml:"key,omitempty" loggable:"false"` InsecureSkipVerify bool `description:"TLS insecure skip verify" json:"insecureSkipVerify,omitempty" toml:"insecureSkipVerify,omitempty" yaml:"insecureSkipVerify,omitempty" export:"true"` } // CreateTLSConfig creates a TLS config from ClientTLS structures. func (c *ClientTLS) CreateTLSConfig(ctx context.Context) (*tls.Config, error) { if c == nil { log.Ctx(ctx).Warn().Msg("clientTLS is nil") return nil, nil } // Not initialized, to rely on system bundle. var caPool *x509.CertPool if c.CA != "" { var ca []byte if _, errCA := os.Stat(c.CA); errCA == nil { var err error ca, err = os.ReadFile(c.CA) if err != nil { return nil, fmt.Errorf("failed to read CA. %w", err) } } else { ca = []byte(c.CA) } caPool = x509.NewCertPool() if !caPool.AppendCertsFromPEM(ca) { return nil, errors.New("failed to parse CA") } } hasCert := len(c.Cert) > 0 hasKey := len(c.Key) > 0 if hasCert != hasKey { return nil, errors.New("both TLS cert and key must be defined") } if !hasCert || !hasKey { return &tls.Config{ RootCAs: caPool, InsecureSkipVerify: c.InsecureSkipVerify, }, nil } cert, err := loadKeyPair(c.Cert, c.Key) if err != nil { return nil, err } return &tls.Config{ Certificates: []tls.Certificate{cert}, RootCAs: caPool, InsecureSkipVerify: c.InsecureSkipVerify, }, nil } func loadKeyPair(cert, key string) (tls.Certificate, error) { keyPair, err := tls.X509KeyPair([]byte(cert), []byte(key)) if err == nil { return keyPair, nil } _, err = os.Stat(cert) if err != nil { return tls.Certificate{}, errors.New("cert file does not exist") } _, err = os.Stat(key) if err != nil { return tls.Certificate{}, errors.New("key file does not exist") } keyPair, err = tls.LoadX509KeyPair(cert, key) if err != nil { return tls.Certificate{}, err } return keyPair, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/configuration.go
pkg/provider/configuration.go
package provider import ( "bytes" "context" "maps" "reflect" "slices" "strings" "text/template" "unicode" "github.com/Masterminds/sprig/v3" "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/tls" ) // Merge merges multiple configurations. func Merge(ctx context.Context, configurations map[string]*dynamic.Configuration) *dynamic.Configuration { logger := log.Ctx(ctx) configuration := &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: make(map[string]*dynamic.Router), Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), ServersTransports: make(map[string]*dynamic.ServersTransport), }, TCP: &dynamic.TCPConfiguration{ Routers: make(map[string]*dynamic.TCPRouter), Services: make(map[string]*dynamic.TCPService), Middlewares: make(map[string]*dynamic.TCPMiddleware), ServersTransports: make(map[string]*dynamic.TCPServersTransport), }, UDP: &dynamic.UDPConfiguration{ Routers: make(map[string]*dynamic.UDPRouter), Services: make(map[string]*dynamic.UDPService), }, TLS: &dynamic.TLSConfiguration{ Stores: make(map[string]tls.Store), }, } servicesToDelete := map[string]struct{}{} services := map[string][]string{} routersToDelete := map[string]struct{}{} routers := map[string][]string{} servicesTCPToDelete := map[string]struct{}{} servicesTCP := map[string][]string{} routersTCPToDelete := map[string]struct{}{} routersTCP := map[string][]string{} servicesUDPToDelete := map[string]struct{}{} servicesUDP := map[string][]string{} routersUDPToDelete := map[string]struct{}{} routersUDP := map[string][]string{} middlewaresToDelete := map[string]struct{}{} middlewares := map[string][]string{} middlewaresTCPToDelete := map[string]struct{}{} middlewaresTCP := map[string][]string{} transportsToDelete := map[string]struct{}{} transports := map[string][]string{} transportsTCPToDelete := map[string]struct{}{} transportsTCP := map[string][]string{} storesToDelete := map[string]struct{}{} stores := map[string][]string{} var sortedKeys []string for key := range configurations { sortedKeys = append(sortedKeys, key) } slices.Sort(sortedKeys) for _, root := range sortedKeys { conf := configurations[root] for serviceName, service := range conf.HTTP.Services { services[serviceName] = append(services[serviceName], root) if !AddService(configuration.HTTP, serviceName, service) { servicesToDelete[serviceName] = struct{}{} } } for routerName, router := range conf.HTTP.Routers { routers[routerName] = append(routers[routerName], root) if !AddRouter(configuration.HTTP, routerName, router) { routersToDelete[routerName] = struct{}{} } } for transportName, transport := range conf.HTTP.ServersTransports { transports[transportName] = append(transports[transportName], root) if !AddTransport(configuration.HTTP, transportName, transport) { transportsToDelete[transportName] = struct{}{} } } for serviceName, service := range conf.TCP.Services { servicesTCP[serviceName] = append(servicesTCP[serviceName], root) if !AddServiceTCP(configuration.TCP, serviceName, service) { servicesTCPToDelete[serviceName] = struct{}{} } } for routerName, router := range conf.TCP.Routers { routersTCP[routerName] = append(routersTCP[routerName], root) if !AddRouterTCP(configuration.TCP, routerName, router) { routersTCPToDelete[routerName] = struct{}{} } } for transportName, transport := range conf.TCP.ServersTransports { transportsTCP[transportName] = append(transportsTCP[transportName], root) if !AddTransportTCP(configuration.TCP, transportName, transport) { transportsTCPToDelete[transportName] = struct{}{} } } for serviceName, service := range conf.UDP.Services { servicesUDP[serviceName] = append(servicesUDP[serviceName], root) if !AddServiceUDP(configuration.UDP, serviceName, service) { servicesUDPToDelete[serviceName] = struct{}{} } } for routerName, router := range conf.UDP.Routers { routersUDP[routerName] = append(routersUDP[routerName], root) if !AddRouterUDP(configuration.UDP, routerName, router) { routersUDPToDelete[routerName] = struct{}{} } } for middlewareName, middleware := range conf.HTTP.Middlewares { middlewares[middlewareName] = append(middlewares[middlewareName], root) if !AddMiddleware(configuration.HTTP, middlewareName, middleware) { middlewaresToDelete[middlewareName] = struct{}{} } } for middlewareName, middleware := range conf.TCP.Middlewares { middlewaresTCP[middlewareName] = append(middlewaresTCP[middlewareName], root) if !AddMiddlewareTCP(configuration.TCP, middlewareName, middleware) { middlewaresTCPToDelete[middlewareName] = struct{}{} } } for storeName, store := range conf.TLS.Stores { stores[storeName] = append(stores[storeName], root) if !AddStore(configuration.TLS, storeName, store) { storesToDelete[storeName] = struct{}{} } } } for serviceName := range servicesToDelete { logger.Error().Str(logs.ServiceName, serviceName). Interface("configuration", services[serviceName]). Msg("Service defined multiple times with different configurations") delete(configuration.HTTP.Services, serviceName) } for routerName := range routersToDelete { logger.Error().Str(logs.RouterName, routerName). Interface("configuration", routers[routerName]). Msg("Router defined multiple times with different configurations") delete(configuration.HTTP.Routers, routerName) } for transportName := range transportsToDelete { logger.Error().Str(logs.ServersTransportName, transportName). Interface("configuration", transports[transportName]). Msg("ServersTransport defined multiple times with different configurations") delete(configuration.HTTP.ServersTransports, transportName) } for serviceName := range servicesTCPToDelete { logger.Error().Str(logs.ServiceName, serviceName). Interface("configuration", servicesTCP[serviceName]). Msg("Service TCP defined multiple times with different configurations") delete(configuration.TCP.Services, serviceName) } for routerName := range routersTCPToDelete { logger.Error().Str(logs.RouterName, routerName). Interface("configuration", routersTCP[routerName]). Msg("Router TCP defined multiple times with different configurations") delete(configuration.TCP.Routers, routerName) } for transportName := range transportsTCPToDelete { logger.Error().Str(logs.ServersTransportName, transportName). Interface("configuration", transportsTCP[transportName]). Msg("ServersTransport TCP defined multiple times with different configurations") delete(configuration.TCP.ServersTransports, transportName) } for serviceName := range servicesUDPToDelete { logger.Error().Str(logs.ServiceName, serviceName). Interface("configuration", servicesUDP[serviceName]). Msg("UDP service defined multiple times with different configurations") delete(configuration.UDP.Services, serviceName) } for routerName := range routersUDPToDelete { logger.Error().Str(logs.RouterName, routerName). Interface("configuration", routersUDP[routerName]). Msg("UDP router defined multiple times with different configurations") delete(configuration.UDP.Routers, routerName) } for middlewareName := range middlewaresToDelete { logger.Error().Str(logs.MiddlewareName, middlewareName). Interface("configuration", middlewares[middlewareName]). Msg("Middleware defined multiple times with different configurations") delete(configuration.HTTP.Middlewares, middlewareName) } for middlewareName := range middlewaresTCPToDelete { logger.Error().Str(logs.MiddlewareName, middlewareName). Interface("configuration", middlewaresTCP[middlewareName]). Msg("TCP Middleware defined multiple times with different configurations") delete(configuration.TCP.Middlewares, middlewareName) } for storeName := range storesToDelete { logger.Error().Str("storeName", storeName). Msgf("TLS store defined multiple times with different configurations in %v", stores[storeName]) delete(configuration.TLS.Stores, storeName) } return configuration } // AddServiceTCP adds a service to a configuration. func AddServiceTCP(configuration *dynamic.TCPConfiguration, serviceName string, service *dynamic.TCPService) bool { if _, ok := configuration.Services[serviceName]; !ok { configuration.Services[serviceName] = service return true } if !configuration.Services[serviceName].LoadBalancer.Mergeable(service.LoadBalancer) { return false } uniq := map[string]struct{}{} for _, server := range configuration.Services[serviceName].LoadBalancer.Servers { uniq[server.Address] = struct{}{} } for _, server := range service.LoadBalancer.Servers { if _, ok := uniq[server.Address]; !ok { configuration.Services[serviceName].LoadBalancer.Servers = append(configuration.Services[serviceName].LoadBalancer.Servers, server) } } return true } // AddRouterTCP adds a router to a configuration. func AddRouterTCP(configuration *dynamic.TCPConfiguration, routerName string, router *dynamic.TCPRouter) bool { if _, ok := configuration.Routers[routerName]; !ok { configuration.Routers[routerName] = router return true } return reflect.DeepEqual(configuration.Routers[routerName], router) } // AddMiddlewareTCP adds a middleware to a configuration. func AddMiddlewareTCP(configuration *dynamic.TCPConfiguration, middlewareName string, middleware *dynamic.TCPMiddleware) bool { if _, ok := configuration.Middlewares[middlewareName]; !ok { configuration.Middlewares[middlewareName] = middleware return true } return reflect.DeepEqual(configuration.Middlewares[middlewareName], middleware) } // AddTransportTCP adds a servers transport to a configuration. func AddTransportTCP(configuration *dynamic.TCPConfiguration, transportName string, transport *dynamic.TCPServersTransport) bool { if _, ok := configuration.ServersTransports[transportName]; !ok { configuration.ServersTransports[transportName] = transport return true } return reflect.DeepEqual(configuration.ServersTransports[transportName], transport) } // AddServiceUDP adds a service to a configuration. func AddServiceUDP(configuration *dynamic.UDPConfiguration, serviceName string, service *dynamic.UDPService) bool { if _, ok := configuration.Services[serviceName]; !ok { configuration.Services[serviceName] = service return true } if !configuration.Services[serviceName].LoadBalancer.Mergeable(service.LoadBalancer) { return false } uniq := map[string]struct{}{} for _, server := range configuration.Services[serviceName].LoadBalancer.Servers { uniq[server.Address] = struct{}{} } for _, server := range service.LoadBalancer.Servers { if _, ok := uniq[server.Address]; !ok { configuration.Services[serviceName].LoadBalancer.Servers = append(configuration.Services[serviceName].LoadBalancer.Servers, server) } } return true } // AddRouterUDP adds a router to a configuration. func AddRouterUDP(configuration *dynamic.UDPConfiguration, routerName string, router *dynamic.UDPRouter) bool { if _, ok := configuration.Routers[routerName]; !ok { configuration.Routers[routerName] = router return true } return reflect.DeepEqual(configuration.Routers[routerName], router) } // AddService adds a service to a configuration. func AddService(configuration *dynamic.HTTPConfiguration, serviceName string, service *dynamic.Service) bool { if _, ok := configuration.Services[serviceName]; !ok { configuration.Services[serviceName] = service return true } if !configuration.Services[serviceName].LoadBalancer.Mergeable(service.LoadBalancer) { return false } uniq := map[string]struct{}{} for _, server := range configuration.Services[serviceName].LoadBalancer.Servers { uniq[server.URL] = struct{}{} } for _, server := range service.LoadBalancer.Servers { if _, ok := uniq[server.URL]; !ok { configuration.Services[serviceName].LoadBalancer.Servers = append(configuration.Services[serviceName].LoadBalancer.Servers, server) } } return true } // AddRouter adds a router to a configuration. func AddRouter(configuration *dynamic.HTTPConfiguration, routerName string, router *dynamic.Router) bool { if _, ok := configuration.Routers[routerName]; !ok { configuration.Routers[routerName] = router return true } return reflect.DeepEqual(configuration.Routers[routerName], router) } // AddTransport adds a servers transport to a configuration. func AddTransport(configuration *dynamic.HTTPConfiguration, transportName string, transport *dynamic.ServersTransport) bool { if _, ok := configuration.ServersTransports[transportName]; !ok { configuration.ServersTransports[transportName] = transport return true } return reflect.DeepEqual(configuration.ServersTransports[transportName], transport) } // AddMiddleware adds a middleware to a configuration. func AddMiddleware(configuration *dynamic.HTTPConfiguration, middlewareName string, middleware *dynamic.Middleware) bool { if _, ok := configuration.Middlewares[middlewareName]; !ok { configuration.Middlewares[middlewareName] = middleware return true } return reflect.DeepEqual(configuration.Middlewares[middlewareName], middleware) } // AddStore adds a middleware to a configurations. func AddStore(configuration *dynamic.TLSConfiguration, storeName string, store tls.Store) bool { if _, ok := configuration.Stores[storeName]; !ok { configuration.Stores[storeName] = store return true } return reflect.DeepEqual(configuration.Stores[storeName], store) } // MakeDefaultRuleTemplate creates the default rule template. func MakeDefaultRuleTemplate(defaultRule string, funcMap template.FuncMap) (*template.Template, error) { defaultFuncMap := sprig.TxtFuncMap() defaultFuncMap["normalize"] = Normalize for k, fn := range funcMap { defaultFuncMap[k] = fn } return template.New("defaultRule").Funcs(defaultFuncMap).Parse(defaultRule) } // BuildTCPRouterConfiguration builds a router configuration. func BuildTCPRouterConfiguration(ctx context.Context, configuration *dynamic.TCPConfiguration) { for routerName, router := range configuration.Routers { loggerRouter := log.Ctx(ctx).With().Str(logs.RouterName, routerName).Logger() if len(router.Rule) == 0 { delete(configuration.Routers, routerName) loggerRouter.Error().Msg("Empty rule") continue } if router.Service == "" { if len(configuration.Services) > 1 { delete(configuration.Routers, routerName) loggerRouter.Error(). Msgf("Router %s cannot be linked automatically with multiple Services: %q", routerName, slices.Collect(maps.Keys(configuration.Services))) continue } for serviceName := range configuration.Services { router.Service = serviceName } } } } // BuildUDPRouterConfiguration builds a router configuration. func BuildUDPRouterConfiguration(ctx context.Context, configuration *dynamic.UDPConfiguration) { for routerName, router := range configuration.Routers { loggerRouter := log.Ctx(ctx).With().Str(logs.RouterName, routerName).Logger() if router.Service != "" { continue } if len(configuration.Services) > 1 { delete(configuration.Routers, routerName) loggerRouter.Error(). Msgf("Router %s cannot be linked automatically with multiple Services: %q", routerName, slices.Collect(maps.Keys(configuration.Services))) continue } for serviceName := range configuration.Services { router.Service = serviceName break } } } // BuildRouterConfiguration builds a router configuration. func BuildRouterConfiguration(ctx context.Context, configuration *dynamic.HTTPConfiguration, defaultRouterName string, defaultRuleTpl *template.Template, model interface{}) { if len(configuration.Routers) == 0 { if len(configuration.Services) > 1 { log.Ctx(ctx).Info().Msg("Could not create a router for the container: too many services") } else { configuration.Routers = make(map[string]*dynamic.Router) configuration.Routers[defaultRouterName] = &dynamic.Router{} } } for routerName, router := range configuration.Routers { loggerRouter := log.Ctx(ctx).With().Str(logs.RouterName, routerName).Logger() if len(router.Rule) == 0 { writer := &bytes.Buffer{} if err := defaultRuleTpl.Execute(writer, model); err != nil { loggerRouter.Error().Err(err).Msg("Error while parsing default rule") delete(configuration.Routers, routerName) continue } router.Rule = writer.String() if len(router.Rule) == 0 { loggerRouter.Error().Msg("Undefined rule") delete(configuration.Routers, routerName) continue } // Flag default rule routers to add the denyRouterRecursion middleware. router.DefaultRule = true } if router.Service == "" { if len(configuration.Services) > 1 { delete(configuration.Routers, routerName) loggerRouter.Error(). Msgf("Router %s cannot be linked automatically with multiple Services: %q", routerName, slices.Collect(maps.Keys(configuration.Services))) continue } for serviceName := range configuration.Services { router.Service = serviceName } } } } // Normalize replaces all special chars with `-`. func Normalize(name string) string { fargs := func(c rune) bool { return !unicode.IsLetter(c) && !unicode.IsNumber(c) } // get function return strings.Join(strings.FieldsFunc(name, fargs), "-") }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/provider.go
pkg/provider/provider.go
package provider import ( "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/safe" ) // Provider defines methods of a provider. type Provider interface { // Provide allows the provider to provide configurations to traefik // using the given configuration channel. Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error Init() error } // NamespacedProvider is implemented by providers that support namespace-scoped configurations, // where each configured namespace results in a dedicated provider instance. // This enables clear identification of which namespace each provider instance serves during // startup logging and operational monitoring. type NamespacedProvider interface { Provider // Namespace returns the specific namespace this provider instance is configured for. Namespace() string }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/acme/local_store_windows.go
pkg/provider/acme/local_store_windows.go
package acme import "os" // CheckFile checks file content size // Do not check file permissions on Windows right now func CheckFile(name string) (bool, error) { f, err := os.Open(name) if err != nil { if os.IsNotExist(err) { f, err = os.Create(name) if err != nil { return false, err } return false, f.Chmod(0o600) } return false, err } defer f.Close() fi, err := f.Stat() if err != nil { return false, err } return fi.Size() > 0, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/acme/challenge_tls.go
pkg/provider/acme/challenge_tls.go
package acme import ( "fmt" "slices" "sync" "time" "github.com/go-acme/lego/v4/challenge/tlsalpn01" "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/safe" traefiktls "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" ) const providerNameALPN = "tlsalpn.acme" // ChallengeTLSALPN TLSALPN challenge provider implements challenge.Provider. type ChallengeTLSALPN struct { chans map[string]chan struct{} muChans sync.Mutex certs map[string]*Certificate muCerts sync.Mutex configurationChan chan<- dynamic.Message } // NewChallengeTLSALPN creates a new ChallengeTLSALPN. func NewChallengeTLSALPN() *ChallengeTLSALPN { return &ChallengeTLSALPN{ chans: make(map[string]chan struct{}), certs: make(map[string]*Certificate), } } // Present presents a challenge to obtain new ACME certificate. func (c *ChallengeTLSALPN) Present(domain, _, keyAuth string) error { logger := log.With().Str(logs.ProviderName, providerNameALPN).Logger() logger.Debug().Msgf("TLS Challenge Present temp certificate for %s", domain) certPEMBlock, keyPEMBlock, err := tlsalpn01.ChallengeBlocks(domain, keyAuth) if err != nil { return err } cert := &Certificate{Certificate: certPEMBlock, Key: keyPEMBlock, Domain: types.Domain{Main: "TEMP-" + domain}} c.muChans.Lock() ch := make(chan struct{}) c.chans[string(certPEMBlock)] = ch c.muChans.Unlock() c.muCerts.Lock() c.certs[keyAuth] = cert conf := createMessage(c.certs) c.muCerts.Unlock() c.configurationChan <- conf // Present should return when its dynamic configuration has been received and applied by Traefik. // The timer exists in case the above does not happen, to ensure the challenge cleanup. timer := time.NewTimer(time.Minute) defer timer.Stop() select { case t := <-timer.C: c.muChans.Lock() c.cleanChan(string(certPEMBlock)) c.muChans.Unlock() err = c.CleanUp(domain, "", keyAuth) if err != nil { logger.Error().Err(err).Msg("Failed to clean up TLS challenge") } return fmt.Errorf("timeout %s", t) case <-ch: // noop return nil } } // CleanUp cleans the challenges when certificate is obtained. func (c *ChallengeTLSALPN) CleanUp(domain, _, keyAuth string) error { log.Debug().Str(logs.ProviderName, providerNameALPN). Msgf("TLS Challenge CleanUp temp certificate for %s", domain) c.muCerts.Lock() delete(c.certs, keyAuth) conf := createMessage(c.certs) c.muCerts.Unlock() c.configurationChan <- conf return nil } // Init the provider. func (c *ChallengeTLSALPN) Init() error { return nil } // ThrottleDuration returns the throttle duration. func (c *ChallengeTLSALPN) ThrottleDuration() time.Duration { return 0 } // Provide allows the provider to provide configurations to traefik using the given configuration channel. func (c *ChallengeTLSALPN) Provide(configurationChan chan<- dynamic.Message, _ *safe.Pool) error { c.configurationChan = configurationChan return nil } // ListenConfiguration sets a new Configuration into the configurationChan. func (c *ChallengeTLSALPN) ListenConfiguration(conf dynamic.Configuration) { c.muChans.Lock() for _, certificate := range conf.TLS.Certificates { if !slices.Contains(certificate.Stores, tlsalpn01.ACMETLS1Protocol) { continue } c.cleanChan(certificate.CertFile.String()) } c.muChans.Unlock() } func (c *ChallengeTLSALPN) cleanChan(key string) { if _, ok := c.chans[key]; ok { close(c.chans[key]) delete(c.chans, key) } } func createMessage(certs map[string]*Certificate) dynamic.Message { conf := dynamic.Message{ ProviderName: providerNameALPN, Configuration: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, }, TLS: &dynamic.TLSConfiguration{}, }, } for _, cert := range certs { certConf := &traefiktls.CertAndStores{ Certificate: traefiktls.Certificate{ CertFile: types.FileOrContent(cert.Certificate), KeyFile: types.FileOrContent(cert.Key), }, Stores: []string{tlsalpn01.ACMETLS1Protocol}, } conf.Configuration.TLS.Certificates = append(conf.Configuration.TLS.Certificates, certConf) } return conf }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/acme/challenge_http.go
pkg/provider/acme/challenge_http.go
package acme import ( "context" "errors" "fmt" "net" "net/http" "net/url" "regexp" "sync" "time" "github.com/go-acme/lego/v4/challenge/http01" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/observability/logs" ) // ChallengeHTTP HTTP challenge provider implements challenge.Provider. type ChallengeHTTP struct { httpChallenges map[string]map[string][]byte lock sync.RWMutex } // NewChallengeHTTP creates a new ChallengeHTTP. func NewChallengeHTTP() *ChallengeHTTP { return &ChallengeHTTP{ httpChallenges: make(map[string]map[string][]byte), } } // Present presents a challenge to obtain new ACME certificate. func (c *ChallengeHTTP) Present(domain, token, keyAuth string) error { c.lock.Lock() defer c.lock.Unlock() if _, ok := c.httpChallenges[token]; !ok { c.httpChallenges[token] = map[string][]byte{} } c.httpChallenges[token][domain] = []byte(keyAuth) return nil } // CleanUp cleans the challenges when certificate is obtained. func (c *ChallengeHTTP) CleanUp(domain, token, _ string) error { c.lock.Lock() defer c.lock.Unlock() if c.httpChallenges == nil && len(c.httpChallenges) == 0 { return nil } if _, ok := c.httpChallenges[token]; ok { delete(c.httpChallenges[token], domain) if len(c.httpChallenges[token]) == 0 { delete(c.httpChallenges, token) } } return nil } // Timeout calculates the maximum of time allowed to resolved an ACME challenge. func (c *ChallengeHTTP) Timeout() (timeout, interval time.Duration) { return 60 * time.Second, 5 * time.Second } func (c *ChallengeHTTP) ServeHTTP(rw http.ResponseWriter, req *http.Request) { logger := log.Ctx(req.Context()).With().Str(logs.ProviderName, "acme").Logger() token, err := getPathParam(req.URL) if err != nil { logger.Error().Err(err).Msg("Unable to get token") rw.WriteHeader(http.StatusNotFound) return } if token != "" { domain, _, err := net.SplitHostPort(req.Host) if err != nil { logger.Debug().Err(err).Msg("Unable to split host and port. Fallback to request host.") domain = req.Host } tokenValue := c.getTokenValue(logger.WithContext(req.Context()), token, domain) if len(tokenValue) > 0 { rw.WriteHeader(http.StatusOK) _, err = rw.Write(tokenValue) if err != nil { logger.Error().Err(err).Msg("Unable to write token") } return } } rw.WriteHeader(http.StatusNotFound) } func (c *ChallengeHTTP) getTokenValue(ctx context.Context, token, domain string) []byte { logger := log.Ctx(ctx) logger.Debug().Msgf("Retrieving the ACME challenge for %s (token %q)...", domain, token) c.lock.RLock() defer c.lock.RUnlock() if _, ok := c.httpChallenges[token]; !ok { logger.Error().Msgf("Cannot retrieve the ACME challenge for %s (token %q)", domain, token) return nil } result, ok := c.httpChallenges[token][domain] if !ok { logger.Error().Msgf("Cannot retrieve the ACME challenge for %s (token %q)", domain, token) return nil } return result } func getPathParam(uri *url.URL) (string, error) { exp := regexp.MustCompile(fmt.Sprintf(`^%s([^/]+)/?$`, http01.ChallengePath(""))) parts := exp.FindStringSubmatch(uri.Path) if len(parts) != 2 { return "", errors.New("missing token") } return parts[1], nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/acme/local_store_unix.go
pkg/provider/acme/local_store_unix.go
//go:build !windows // +build !windows package acme import ( "fmt" "os" ) // CheckFile checks file permissions and content size. func CheckFile(name string) (bool, error) { f, err := os.Open(name) if err != nil && os.IsNotExist(err) { nf, err := os.Create(name) if err != nil { return false, err } defer nf.Close() return false, nf.Chmod(0o600) } if err != nil { return false, err } defer f.Close() fi, err := f.Stat() if err != nil { return false, err } if fi.Mode().Perm()&0o077 != 0 { return false, fmt.Errorf("permissions %o for %s are too open, please use 600", fi.Mode().Perm(), name) } return fi.Size() > 0, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/acme/local_store.go
pkg/provider/acme/local_store.go
package acme import ( "context" "encoding/json" "io" "os" "sync" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/safe" ) var _ Store = (*LocalStore)(nil) // LocalStore Stores implementation for local file. type LocalStore struct { saveDataChan chan map[string]*StoredData filename string lock sync.RWMutex storedData map[string]*StoredData } // NewLocalStore initializes a new LocalStore with a file name. func NewLocalStore(filename string, routinesPool *safe.Pool) *LocalStore { store := &LocalStore{filename: filename, saveDataChan: make(chan map[string]*StoredData)} store.listenSaveAction(routinesPool) return store } func (s *LocalStore) save(resolverName string, storedData *StoredData) { s.lock.Lock() defer s.lock.Unlock() s.storedData[resolverName] = storedData // we cannot pass s.storedData directly, map is reference type and as result // we can face with race condition, so we need to work with objects copy s.saveDataChan <- s.unSafeCopyOfStoredData() } func (s *LocalStore) get(resolverName string) (*StoredData, error) { s.lock.Lock() defer s.lock.Unlock() if s.storedData == nil { s.storedData = map[string]*StoredData{} hasData, err := CheckFile(s.filename) if err != nil { return nil, err } if hasData { logger := log.With().Str(logs.ProviderName, "acme").Logger() f, err := os.Open(s.filename) if err != nil { return nil, err } defer f.Close() file, err := io.ReadAll(f) if err != nil { return nil, err } if len(file) > 0 { if err := json.Unmarshal(file, &s.storedData); err != nil { return nil, err } } // Delete all certificates with no value var certificates []*CertAndStore for _, storedData := range s.storedData { for _, certificate := range storedData.Certificates { if len(certificate.Certificate.Certificate) == 0 || len(certificate.Key) == 0 { logger.Debug().Msgf("Deleting empty certificate %v for %v", certificate, certificate.Domain.ToStrArray()) continue } certificates = append(certificates, certificate) } if len(certificates) < len(storedData.Certificates) { storedData.Certificates = certificates // we cannot pass s.storedData directly, map is reference type and as result // we can face with race condition, so we need to work with objects copy s.saveDataChan <- s.unSafeCopyOfStoredData() } } } } if s.storedData[resolverName] == nil { s.storedData[resolverName] = &StoredData{} } return s.storedData[resolverName], nil } // listenSaveAction listens to a chan to store ACME data in json format into `LocalStore.filename`. func (s *LocalStore) listenSaveAction(routinesPool *safe.Pool) { routinesPool.GoCtx(func(ctx context.Context) { logger := log.With().Str(logs.ProviderName, "acme").Logger() for { select { case <-ctx.Done(): return case object := <-s.saveDataChan: select { case <-ctx.Done(): // Stop handling events because Traefik is shutting down. return default: } data, err := json.MarshalIndent(object, "", " ") if err != nil { logger.Error().Err(err).Send() } err = os.WriteFile(s.filename, data, 0o600) if err != nil { logger.Error().Err(err).Send() } } } }) } // unSafeCopyOfStoredData creates maps copy of storedData. Is not thread safe, you should use `s.lock`. func (s *LocalStore) unSafeCopyOfStoredData() map[string]*StoredData { result := map[string]*StoredData{} for k, v := range s.storedData { result[k] = v } return result } // GetAccount returns ACME Account. func (s *LocalStore) GetAccount(resolverName string) (*Account, error) { storedData, err := s.get(resolverName) if err != nil { return nil, err } return storedData.Account, nil } // SaveAccount stores ACME Account. func (s *LocalStore) SaveAccount(resolverName string, account *Account) error { storedData, err := s.get(resolverName) if err != nil { return err } storedData.Account = account s.save(resolverName, storedData) return nil } // GetCertificates returns ACME Certificates list. func (s *LocalStore) GetCertificates(resolverName string) ([]*CertAndStore, error) { storedData, err := s.get(resolverName) if err != nil { return nil, err } return storedData.Certificates, nil } // SaveCertificates stores ACME Certificates list. func (s *LocalStore) SaveCertificates(resolverName string, certificates []*CertAndStore) error { storedData, err := s.get(resolverName) if err != nil { return err } storedData.Certificates = certificates s.save(resolverName, storedData) return nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/acme/store.go
pkg/provider/acme/store.go
package acme // StoredData represents the data managed by Store. type StoredData struct { Account *Account Certificates []*CertAndStore } // Store is a generic interface that represents a storage. type Store interface { GetAccount(resolverName string) (*Account, error) SaveAccount(resolverName string, account *Account) error GetCertificates(resolverName string) ([]*CertAndStore, error) SaveCertificates(resolverName string, certificates []*CertAndStore) error }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/acme/local_store_test.go
pkg/provider/acme/local_store_test.go
package acme import ( "fmt" "os" "path/filepath" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/safe" ) func TestLocalStore_GetAccount(t *testing.T) { acmeFile := filepath.Join(t.TempDir(), "acme.json") email := "some42@email.com" filePayload := fmt.Sprintf(`{ "test": { "Account": { "Email": "%s" } } }`, email) err := os.WriteFile(acmeFile, []byte(filePayload), 0o600) require.NoError(t, err) testCases := []struct { desc string filename string expected *Account }{ { desc: "empty file", filename: filepath.Join(t.TempDir(), "acme-empty.json"), expected: nil, }, { desc: "file with data", filename: acmeFile, expected: &Account{Email: "some42@email.com"}, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { s := NewLocalStore(test.filename, safe.NewPool(t.Context())) account, err := s.GetAccount("test") require.NoError(t, err) assert.Equal(t, test.expected, account) }) } } func TestLocalStore_SaveAccount(t *testing.T) { acmeFile := filepath.Join(t.TempDir(), "acme.json") s := NewLocalStore(acmeFile, safe.NewPool(t.Context())) email := "some@email.com" err := s.SaveAccount("test", &Account{Email: email}) require.NoError(t, err) time.Sleep(100 * time.Millisecond) file, err := os.ReadFile(acmeFile) require.NoError(t, err) expected := `{ "test": { "Account": { "Email": "some@email.com", "Registration": null, "PrivateKey": null, "KeyType": "" }, "Certificates": null } }` assert.Equal(t, expected, string(file)) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/acme/provider.go
pkg/provider/acme/provider.go
package acme import ( "context" "crypto/tls" "crypto/x509" "errors" "fmt" "net" "net/http" "net/url" "os" "reflect" "slices" "sort" "strconv" "strings" "sync" "time" "github.com/go-acme/lego/v4/certificate" "github.com/go-acme/lego/v4/challenge" "github.com/go-acme/lego/v4/challenge/dns01" "github.com/go-acme/lego/v4/challenge/http01" "github.com/go-acme/lego/v4/challenge/tlsalpn01" "github.com/go-acme/lego/v4/lego" "github.com/go-acme/lego/v4/providers/dns" "github.com/go-acme/lego/v4/registration" "github.com/rs/zerolog/log" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" httpmuxer "github.com/traefik/traefik/v3/pkg/muxer/http" tcpmuxer "github.com/traefik/traefik/v3/pkg/muxer/tcp" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/safe" traefiktls "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" "github.com/traefik/traefik/v3/pkg/version" ) const resolverSuffix = ".acme" // Configuration holds ACME configuration provided by users. type Configuration struct { Email string `description:"Email address used for registration." json:"email,omitempty" toml:"email,omitempty" yaml:"email,omitempty"` CAServer string `description:"CA server to use." json:"caServer,omitempty" toml:"caServer,omitempty" yaml:"caServer,omitempty"` PreferredChain string `description:"Preferred chain to use." json:"preferredChain,omitempty" toml:"preferredChain,omitempty" yaml:"preferredChain,omitempty" export:"true"` Profile string `description:"Certificate profile to use." json:"profile,omitempty" toml:"profile,omitempty" yaml:"profile,omitempty" export:"true"` EmailAddresses []string `description:"CSR email addresses to use." json:"emailAddresses,omitempty" toml:"emailAddresses,omitempty" yaml:"emailAddresses,omitempty"` DisableCommonName bool `description:"Disable the common name in the CSR." json:"disableCommonName,omitempty" toml:"disableCommonName,omitempty" yaml:"disableCommonName,omitempty" export:"true"` Storage string `description:"Storage to use." json:"storage,omitempty" toml:"storage,omitempty" yaml:"storage,omitempty" export:"true"` KeyType string `description:"KeyType used for generating certificate private key. Allow value 'EC256', 'EC384', 'RSA2048', 'RSA4096', 'RSA8192'." json:"keyType,omitempty" toml:"keyType,omitempty" yaml:"keyType,omitempty" export:"true"` EAB *EAB `description:"External Account Binding to use." json:"eab,omitempty" toml:"eab,omitempty" yaml:"eab,omitempty"` CertificatesDuration int `description:"Certificates' duration in hours." json:"certificatesDuration,omitempty" toml:"certificatesDuration,omitempty" yaml:"certificatesDuration,omitempty" export:"true"` ClientTimeout ptypes.Duration `description:"Timeout for a complete HTTP transaction with the ACME server." json:"clientTimeout,omitempty" toml:"clientTimeout,omitempty" yaml:"clientTimeout,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` ClientResponseHeaderTimeout ptypes.Duration `description:"Timeout for receiving the response headers when communicating with the ACME server." json:"clientResponseHeaderTimeout,omitempty" toml:"clientResponseHeaderTimeout,omitempty" yaml:"clientResponseHeaderTimeout,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` CACertificates []string `description:"Specify the paths to PEM encoded CA Certificates that can be used to authenticate an ACME server with an HTTPS certificate not issued by a CA in the system-wide trusted root list." json:"caCertificates,omitempty" toml:"caCertificates,omitempty" yaml:"caCertificates,omitempty"` CASystemCertPool bool `description:"Define if the certificates pool must use a copy of the system cert pool." json:"caSystemCertPool,omitempty" toml:"caSystemCertPool,omitempty" yaml:"caSystemCertPool,omitempty" export:"true"` CAServerName string `description:"Specify the CA server name that can be used to authenticate an ACME server with an HTTPS certificate not issued by a CA in the system-wide trusted root list." json:"caServerName,omitempty" toml:"caServerName,omitempty" yaml:"caServerName,omitempty" export:"true"` DNSChallenge *DNSChallenge `description:"Activate DNS-01 Challenge." json:"dnsChallenge,omitempty" toml:"dnsChallenge,omitempty" yaml:"dnsChallenge,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` HTTPChallenge *HTTPChallenge `description:"Activate HTTP-01 Challenge." json:"httpChallenge,omitempty" toml:"httpChallenge,omitempty" yaml:"httpChallenge,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` TLSChallenge *TLSChallenge `description:"Activate TLS-ALPN-01 Challenge." json:"tlsChallenge,omitempty" toml:"tlsChallenge,omitempty" yaml:"tlsChallenge,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` } // SetDefaults sets the default values. func (a *Configuration) SetDefaults() { a.CAServer = lego.LEDirectoryProduction a.Storage = "acme.json" a.KeyType = "RSA4096" a.CertificatesDuration = 3 * 30 * 24 // 90 Days a.ClientTimeout = ptypes.Duration(2 * time.Minute) a.ClientResponseHeaderTimeout = ptypes.Duration(30 * time.Second) } // CertAndStore allows mapping a TLS certificate to a TLS store. type CertAndStore struct { Certificate Store string } // Certificate is a struct which contains all data needed from an ACME certificate. type Certificate struct { Domain types.Domain `json:"domain,omitempty" toml:"domain,omitempty" yaml:"domain,omitempty"` Certificate []byte `json:"certificate,omitempty" toml:"certificate,omitempty" yaml:"certificate,omitempty"` Key []byte `json:"key,omitempty" toml:"key,omitempty" yaml:"key,omitempty"` } // EAB contains External Account Binding configuration. type EAB struct { Kid string `description:"Key identifier from External CA." json:"kid,omitempty" toml:"kid,omitempty" yaml:"kid,omitempty" loggable:"false"` HmacEncoded string `description:"Base64 encoded HMAC key from External CA." json:"hmacEncoded,omitempty" toml:"hmacEncoded,omitempty" yaml:"hmacEncoded,omitempty" loggable:"false"` } // DNSChallenge contains DNS challenge configuration. type DNSChallenge struct { Provider string `description:"Use a DNS-01 based challenge provider rather than HTTPS." json:"provider,omitempty" toml:"provider,omitempty" yaml:"provider,omitempty" export:"true"` Resolvers []string `description:"Use following DNS servers to resolve the FQDN authority." json:"resolvers,omitempty" toml:"resolvers,omitempty" yaml:"resolvers,omitempty"` Propagation *Propagation `description:"DNS propagation checks configuration" json:"propagation,omitempty" toml:"propagation,omitempty" yaml:"propagation,omitempty" label:"allowEmpty" file:"allowEmpty" export:"true"` // Deprecated: please use Propagation.DelayBeforeChecks instead. DelayBeforeCheck ptypes.Duration `description:"(Deprecated) Assume DNS propagates after a delay in seconds rather than finding and querying nameservers." json:"delayBeforeCheck,omitempty" toml:"delayBeforeCheck,omitempty" yaml:"delayBeforeCheck,omitempty" export:"true"` // Deprecated: please use Propagation.DisableChecks instead. DisablePropagationCheck bool `description:"(Deprecated) Disable the DNS propagation checks before notifying ACME that the DNS challenge is ready. [not recommended]" json:"disablePropagationCheck,omitempty" toml:"disablePropagationCheck,omitempty" yaml:"disablePropagationCheck,omitempty" export:"true"` } type Propagation struct { DisableChecks bool `description:"Disables the challenge TXT record propagation checks (not recommended)." json:"disableChecks,omitempty" toml:"disableChecks,omitempty" yaml:"disableChecks,omitempty" export:"true"` DisableANSChecks bool `description:"Disables the challenge TXT record propagation checks against authoritative nameservers." json:"disableANSChecks,omitempty" toml:"disableANSChecks,omitempty" yaml:"disableANSChecks,omitempty" export:"true"` RequireAllRNS bool `description:"Requires the challenge TXT record to be propagated to all recursive nameservers." json:"requireAllRNS,omitempty" toml:"requireAllRNS,omitempty" yaml:"requireAllRNS,omitempty" export:"true"` DelayBeforeChecks ptypes.Duration `description:"Defines the delay before checking the challenge TXT record propagation." json:"delayBeforeChecks,omitempty" toml:"delayBeforeChecks,omitempty" yaml:"delayBeforeChecks,omitempty" export:"true"` } // HTTPChallenge contains HTTP challenge configuration. type HTTPChallenge struct { EntryPoint string `description:"HTTP challenge EntryPoint" json:"entryPoint,omitempty" toml:"entryPoint,omitempty" yaml:"entryPoint,omitempty" export:"true"` Delay ptypes.Duration `description:"Delay between the creation of the challenge and the validation." json:"delay,omitempty" toml:"delay,omitempty" yaml:"delay,omitempty" export:"true"` } // TLSChallenge contains TLS challenge configuration. type TLSChallenge struct { Delay ptypes.Duration `description:"Delay between the creation of the challenge and the validation." json:"delay,omitempty" toml:"delay,omitempty" yaml:"delay,omitempty" export:"true"` } // Provider holds configurations of the provider. type Provider struct { *Configuration ResolverName string Store Store `json:"store,omitempty" toml:"store,omitempty" yaml:"store,omitempty"` TLSChallengeProvider challenge.Provider HTTPChallengeProvider challenge.Provider certificates []*CertAndStore certificatesMu sync.RWMutex account *Account client *lego.Client configurationChan chan<- dynamic.Message tlsManager *traefiktls.Manager clientMutex sync.Mutex configFromListenerChan chan dynamic.Configuration pool *safe.Pool resolvingDomains map[string]struct{} resolvingDomainsMutex sync.RWMutex } // SetTLSManager sets the tls manager to use. func (p *Provider) SetTLSManager(tlsManager *traefiktls.Manager) { p.tlsManager = tlsManager } // SetConfigListenerChan initializes the configFromListenerChan. func (p *Provider) SetConfigListenerChan(configFromListenerChan chan dynamic.Configuration) { p.configFromListenerChan = configFromListenerChan } // ListenConfiguration sets a new Configuration into the configFromListenerChan. func (p *Provider) ListenConfiguration(config dynamic.Configuration) { p.configFromListenerChan <- config } // Init inits the provider. func (p *Provider) Init() error { logger := log.With().Str(logs.ProviderName, p.ResolverName+resolverSuffix).Logger() if len(p.Configuration.Storage) == 0 { return errors.New("unable to initialize ACME provider with no storage location for the certificates") } if p.CertificatesDuration < 1 { return errors.New("cannot manage certificates with duration lower than 1 hour") } if p.ClientTimeout < p.ClientResponseHeaderTimeout { return errors.New("clientTimeout must be at least clientResponseHeaderTimeout") } var err error p.account, err = p.Store.GetAccount(p.ResolverName) if err != nil { return fmt.Errorf("unable to get ACME account: %w", err) } // Reset Account if caServer changed, thus registration URI can be updated if p.account != nil && p.account.Registration != nil && !isAccountMatchingCaServer(logger.WithContext(context.Background()), p.account.Registration.URI, p.CAServer) { logger.Info().Msg("Account URI does not match the current CAServer. The account will be reset.") p.account = nil } p.certificatesMu.Lock() p.certificates, err = p.Store.GetCertificates(p.ResolverName) p.certificatesMu.Unlock() if err != nil { return fmt.Errorf("unable to get ACME certificates : %w", err) } // Init the currently resolved domain map p.resolvingDomains = make(map[string]struct{}) return nil } func isAccountMatchingCaServer(ctx context.Context, accountURI, serverURI string) bool { logger := log.Ctx(ctx) aru, err := url.Parse(accountURI) if err != nil { logger.Info().Err(err).Str("registrationURL", accountURI).Msg("Unable to parse account.Registration URL") return false } cau, err := url.Parse(serverURI) if err != nil { logger.Info().Err(err).Str("caServerURL", serverURI).Msg("Unable to parse CAServer URL") return false } return cau.Hostname() == aru.Hostname() } // ThrottleDuration returns the throttle duration. func (p *Provider) ThrottleDuration() time.Duration { return 0 } // Provide allows the file provider to provide configurations to traefik // using the given Configuration channel. func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error { logger := log.With().Str(logs.ProviderName, p.ResolverName+resolverSuffix).Str("acmeCA", p.Configuration.CAServer). Logger() ctx := logger.WithContext(context.Background()) p.pool = pool p.watchNewDomains(ctx) p.configurationChan = configurationChan p.certificatesMu.RLock() msg := p.buildMessage() p.certificatesMu.RUnlock() p.configurationChan <- msg renewPeriod, renewInterval := getCertificateRenewDurations(p.CertificatesDuration) logger.Debug().Msgf("Attempt to renew certificates %q before expiry and check every %q", renewPeriod, renewInterval) p.renewCertificates(ctx, renewPeriod) ticker := time.NewTicker(renewInterval) pool.GoCtx(func(ctxPool context.Context) { for { select { case <-ticker.C: p.renewCertificates(ctx, renewPeriod) case <-ctxPool.Done(): ticker.Stop() return } } }) return nil } func (p *Provider) getClient() (*lego.Client, error) { p.clientMutex.Lock() defer p.clientMutex.Unlock() logger := log.With().Str(logs.ProviderName, p.ResolverName+resolverSuffix).Logger() ctx := logger.WithContext(context.Background()) if p.client != nil { return p.client, nil } account, err := p.initAccount(ctx) if err != nil { return nil, err } logger.Debug().Msg("Building ACME client...") caServer := lego.LEDirectoryProduction if len(p.CAServer) > 0 { caServer = p.CAServer } logger.Debug().Msg(caServer) config := lego.NewConfig(account) config.CADirURL = caServer config.Certificate.KeyType = GetKeyType(ctx, p.KeyType) config.UserAgent = fmt.Sprintf("containous-traefik/%s", version.Version) config.Certificate.DisableCommonName = p.DisableCommonName config.HTTPClient, err = p.createHTTPClient() if err != nil { return nil, fmt.Errorf("creating HTTP client: %w", err) } client, err := lego.NewClient(config) if err != nil { return nil, err } // New users will need to register; be sure to save it if account.GetRegistration() == nil { reg, errR := p.register(ctx, client) if errR != nil { return nil, errR } account.Registration = reg } // Save the account once before all the certificates generation/storing // No certificate can be generated if account is not initialized err = p.Store.SaveAccount(p.ResolverName, account) if err != nil { return nil, err } if (p.DNSChallenge == nil || len(p.DNSChallenge.Provider) == 0) && (p.HTTPChallenge == nil || len(p.HTTPChallenge.EntryPoint) == 0) && p.TLSChallenge == nil { return nil, errors.New("ACME challenge not specified, please select TLS or HTTP or DNS Challenge") } if p.DNSChallenge != nil && len(p.DNSChallenge.Provider) > 0 { logger.Debug().Msgf("Using DNS Challenge provider: %s", p.DNSChallenge.Provider) var provider challenge.Provider provider, err = dns.NewDNSChallengeProviderByName(p.DNSChallenge.Provider) if err != nil { return nil, err } var opts []dns01.ChallengeOption if len(p.DNSChallenge.Resolvers) > 0 { opts = append(opts, dns01.AddRecursiveNameservers(p.DNSChallenge.Resolvers)) } if p.DNSChallenge.Propagation != nil { if p.DNSChallenge.Propagation.RequireAllRNS { opts = append(opts, dns01.RecursiveNSsPropagationRequirement()) } if p.DNSChallenge.Propagation.DisableANSChecks { opts = append(opts, dns01.DisableAuthoritativeNssPropagationRequirement()) } opts = append(opts, dns01.PropagationWait(time.Duration(p.DNSChallenge.Propagation.DelayBeforeChecks), p.DNSChallenge.Propagation.DisableChecks)) } err = client.Challenge.SetDNS01Provider(provider, opts...) if err != nil { return nil, err } } if p.HTTPChallenge != nil && len(p.HTTPChallenge.EntryPoint) > 0 { logger.Debug().Msg("Using HTTP Challenge provider.") err = client.Challenge.SetHTTP01Provider(p.HTTPChallengeProvider, http01.SetDelay(time.Duration(p.HTTPChallenge.Delay))) if err != nil { return nil, err } } if p.TLSChallenge != nil { logger.Debug().Msg("Using TLS Challenge provider.") err = client.Challenge.SetTLSALPN01Provider(p.TLSChallengeProvider, tlsalpn01.SetDelay(time.Duration(p.TLSChallenge.Delay))) if err != nil { return nil, err } } p.client = client return p.client, nil } func (p *Provider) createHTTPClient() (*http.Client, error) { tlsConfig, err := p.createClientTLSConfig() if err != nil { return nil, fmt.Errorf("creating client TLS config: %w", err) } return &http.Client{ Timeout: time.Duration(p.ClientTimeout), Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).DialContext, TLSHandshakeTimeout: 30 * time.Second, ResponseHeaderTimeout: time.Duration(p.ClientResponseHeaderTimeout), TLSClientConfig: tlsConfig, }, }, nil } func (p *Provider) createClientTLSConfig() (*tls.Config, error) { if len(p.CACertificates) > 0 || p.CAServerName != "" { certPool, err := lego.CreateCertPool(p.CACertificates, p.CASystemCertPool) if err != nil { return nil, fmt.Errorf("creating cert pool with custom certificates: %w", err) } return &tls.Config{ ServerName: p.CAServerName, RootCAs: certPool, }, nil } // Compatibility layer with the lego. // https://github.com/go-acme/lego/blob/834a9089f143e3407b3f5c8b93a0e285ba231fe2/lego/client_config.go#L24-L34 // https://github.com/go-acme/lego/blob/834a9089f143e3407b3f5c8b93a0e285ba231fe2/lego/client_config.go#L97-L113 serverName := os.Getenv("LEGO_CA_SERVER_NAME") customCACertsPath := os.Getenv("LEGO_CA_CERTIFICATES") if customCACertsPath == "" && serverName == "" { return nil, nil } useSystemCertPool, _ := strconv.ParseBool(os.Getenv("LEGO_CA_SYSTEM_CERT_POOL")) certPool, err := lego.CreateCertPool(strings.Split(customCACertsPath, string(os.PathListSeparator)), useSystemCertPool) if err != nil { return nil, fmt.Errorf("creating cert pool: %w", err) } return &tls.Config{ ServerName: serverName, RootCAs: certPool, }, nil } func (p *Provider) initAccount(ctx context.Context) (*Account, error) { if p.account == nil || len(p.account.Email) == 0 { var err error p.account, err = NewAccount(ctx, p.Email, p.KeyType) if err != nil { return nil, err } } // Set the KeyType if not already defined in the account if len(p.account.KeyType) == 0 { p.account.KeyType = GetKeyType(ctx, p.KeyType) } return p.account, nil } func (p *Provider) register(ctx context.Context, client *lego.Client) (*registration.Resource, error) { logger := log.Ctx(ctx) if p.EAB != nil { logger.Info().Msg("Register with external account binding...") eabOptions := registration.RegisterEABOptions{TermsOfServiceAgreed: true, Kid: p.EAB.Kid, HmacEncoded: p.EAB.HmacEncoded} return client.Registration.RegisterWithExternalAccountBinding(eabOptions) } logger.Info().Msg("Register...") return client.Registration.Register(registration.RegisterOptions{TermsOfServiceAgreed: true}) } func (p *Provider) resolveDomains(ctx context.Context, domains []string, tlsStore string) { logger := log.Ctx(ctx) if len(domains) == 0 { logger.Debug().Msg("No domain parsed in provider ACME") return } logger.Debug().Msgf("Trying to challenge certificate for domain %v found in HostSNI rule", domains) var domain types.Domain if len(domains) > 0 { domain = types.Domain{Main: domains[0]} if len(domains) > 1 { domain.SANs = domains[1:] } safe.Go(func() { dom, cert, err := p.resolveCertificate(ctx, domain, tlsStore) if err != nil { logger.Error().Err(err).Strs("domains", domains).Msg("Unable to obtain ACME certificate for domains") return } err = p.addCertificateForDomain(dom, cert, tlsStore) if err != nil { logger.Error().Err(err).Strs("domains", dom.ToStrArray()).Msg("Error adding certificate for domains") } }) } } func (p *Provider) watchNewDomains(ctx context.Context) { rootLogger := log.Ctx(ctx).With().Str(logs.ProviderName, p.ResolverName+resolverSuffix).Str("ACME CA", p.Configuration.CAServer).Logger() ctx = rootLogger.WithContext(ctx) p.pool.GoCtx(func(ctxPool context.Context) { for { select { case config := <-p.configFromListenerChan: if config.TCP != nil { for routerName, route := range config.TCP.Routers { if route.TLS == nil || route.TLS.CertResolver != p.ResolverName { continue } logger := rootLogger.With().Str(logs.RouterName, routerName).Str(logs.Rule, route.Rule).Logger() ctxRouter := logger.WithContext(ctx) if len(route.TLS.Domains) > 0 { domains := deleteUnnecessaryDomains(ctxRouter, route.TLS.Domains) for _, domain := range domains { safe.Go(func() { dom, cert, err := p.resolveCertificate(ctx, domain, traefiktls.DefaultTLSStoreName) if err != nil { logger.Error().Err(err).Strs("domains", domain.ToStrArray()).Msg("Unable to obtain ACME certificate for domains") return } err = p.addCertificateForDomain(dom, cert, traefiktls.DefaultTLSStoreName) if err != nil { logger.Error().Err(err).Strs("domains", dom.ToStrArray()).Msg("Error adding certificate for domains") } }) } } else { domains, err := tcpmuxer.ParseHostSNI(route.Rule) if err != nil { logger.Error().Err(err).Msg("Error parsing domains in provider ACME") continue } p.resolveDomains(ctxRouter, domains, traefiktls.DefaultTLSStoreName) } } } if config.HTTP != nil { for routerName, route := range config.HTTP.Routers { if route.TLS == nil || route.TLS.CertResolver != p.ResolverName { continue } logger := rootLogger.With().Str(logs.RouterName, routerName).Str(logs.Rule, route.Rule).Logger() ctxRouter := logger.WithContext(ctx) if len(route.TLS.Domains) > 0 { domains := deleteUnnecessaryDomains(ctxRouter, route.TLS.Domains) for _, domain := range domains { safe.Go(func() { dom, cert, err := p.resolveCertificate(ctx, domain, traefiktls.DefaultTLSStoreName) if err != nil { logger.Error().Err(err).Strs("domains", domain.ToStrArray()).Msg("Unable to obtain ACME certificate for domains") return } err = p.addCertificateForDomain(dom, cert, traefiktls.DefaultTLSStoreName) if err != nil { logger.Error().Err(err).Strs("domains", dom.ToStrArray()).Msg("Error adding certificate for domain") } }) } } else { domains, err := httpmuxer.ParseDomains(route.Rule) if err != nil { logger.Error().Err(err).Msg("Error parsing domains in provider ACME") continue } p.resolveDomains(ctxRouter, domains, traefiktls.DefaultTLSStoreName) } } } if config.TLS == nil { continue } for tlsStoreName, tlsStore := range config.TLS.Stores { logger := rootLogger.With().Str(logs.TLSStoreName, tlsStoreName).Logger() if tlsStore.DefaultCertificate != nil && tlsStore.DefaultGeneratedCert != nil { logger.Warn().Msg("defaultCertificate and defaultGeneratedCert cannot be defined at the same time.") } // Gives precedence to the user defined default certificate. if tlsStore.DefaultCertificate != nil || tlsStore.DefaultGeneratedCert == nil { continue } if tlsStore.DefaultGeneratedCert.Domain == nil || tlsStore.DefaultGeneratedCert.Resolver == "" { logger.Warn().Msg("default generated certificate domain or resolver is missing.") continue } if tlsStore.DefaultGeneratedCert.Resolver != p.ResolverName { continue } validDomains, err := p.sanitizeDomains(ctx, *tlsStore.DefaultGeneratedCert.Domain) if err != nil { logger.Error().Err(err).Strs("domains", tlsStore.DefaultGeneratedCert.Domain.ToStrArray()).Msg("domains validation") } if p.certExists(validDomains) { logger.Debug().Msg("Default ACME certificate generation is not required.") continue } safe.Go(func() { cert, err := p.resolveDefaultCertificate(ctx, validDomains) if err != nil { logger.Error().Err(err).Strs("domains", validDomains).Msgf("Unable to obtain ACME certificate for domain") return } domain := types.Domain{ Main: validDomains[0], } if len(validDomains) > 0 { domain.SANs = validDomains[1:] } err = p.addCertificateForDomain(domain, cert, traefiktls.DefaultTLSStoreName) if err != nil { logger.Error().Err(err).Msg("Error adding certificate for domain") } }) } case <-ctxPool.Done(): return } } }) } func (p *Provider) resolveDefaultCertificate(ctx context.Context, domains []string) (*certificate.Resource, error) { logger := log.Ctx(ctx) p.resolvingDomainsMutex.Lock() sortedDomains := slices.Clone(domains) slices.Sort(sortedDomains) domainKey := strings.Join(sortedDomains, ",") if _, ok := p.resolvingDomains[domainKey]; ok { p.resolvingDomainsMutex.Unlock() return nil, nil } p.resolvingDomains[domainKey] = struct{}{} for _, certDomain := range domains { p.resolvingDomains[certDomain] = struct{}{} } p.resolvingDomainsMutex.Unlock() defer p.removeResolvingDomains(append(domains, domainKey)) logger.Debug().Msgf("Loading ACME certificates %+v...", domains) client, err := p.getClient() if err != nil { return nil, fmt.Errorf("cannot get ACME client %w", err) } request := certificate.ObtainRequest{ Domains: domains, Bundle: true, EmailAddresses: p.EmailAddresses, Profile: p.Profile, PreferredChain: p.PreferredChain, } cert, err := client.Certificate.Obtain(request) if err != nil { return nil, fmt.Errorf("unable to generate a certificate for the domains %v: %w", domains, err) } if cert == nil { return nil, fmt.Errorf("unable to generate a certificate for the domains %v", domains) } if len(cert.Certificate) == 0 || len(cert.PrivateKey) == 0 { return nil, fmt.Errorf("certificate for domains %v is empty: %v", domains, cert) } logger.Debug().Msgf("Default certificate obtained for domains %+v", domains) return cert, nil } func (p *Provider) resolveCertificate(ctx context.Context, domain types.Domain, tlsStore string) (types.Domain, *certificate.Resource, error) { domains, err := p.sanitizeDomains(ctx, domain) if err != nil { return types.Domain{}, nil, err } // Check if provided certificates are not already in progress and lock them if needed uncheckedDomains := p.getUncheckedDomains(ctx, domains, tlsStore) if len(uncheckedDomains) == 0 { return types.Domain{}, nil, nil } defer p.removeResolvingDomains(uncheckedDomains) logger := log.Ctx(ctx) logger.Debug().Msgf("Loading ACME certificates %+v...", uncheckedDomains) client, err := p.getClient() if err != nil { return types.Domain{}, nil, fmt.Errorf("cannot get ACME client %w", err) } request := certificate.ObtainRequest{ Domains: domains, Bundle: true, EmailAddresses: p.EmailAddresses, Profile: p.Profile, PreferredChain: p.PreferredChain, } cert, err := client.Certificate.Obtain(request) if err != nil { return types.Domain{}, nil, fmt.Errorf("unable to generate a certificate for the domains %v: %w", uncheckedDomains, err) } if cert == nil { return types.Domain{}, nil, fmt.Errorf("unable to generate a certificate for the domains %v", uncheckedDomains) } if len(cert.Certificate) == 0 || len(cert.PrivateKey) == 0 { return types.Domain{}, nil, fmt.Errorf("certificate for domains %v is empty: %v", uncheckedDomains, cert) } logger.Debug().Msgf("Certificates obtained for domains %+v", uncheckedDomains) domain = types.Domain{Main: uncheckedDomains[0]} if len(uncheckedDomains) > 1 { domain.SANs = uncheckedDomains[1:] } return domain, cert, nil } func (p *Provider) removeResolvingDomains(resolvingDomains []string) { p.resolvingDomainsMutex.Lock() defer p.resolvingDomainsMutex.Unlock() for _, domain := range resolvingDomains { delete(p.resolvingDomains, domain) } } func (p *Provider) addCertificateForDomain(domain types.Domain, crt *certificate.Resource, tlsStore string) error { if crt == nil { return nil } p.certificatesMu.Lock() defer p.certificatesMu.Unlock() cert := Certificate{Certificate: crt.Certificate, Key: crt.PrivateKey, Domain: domain} certUpdated := false for _, domainsCertificate := range p.certificates { if reflect.DeepEqual(domain, domainsCertificate.Certificate.Domain) { domainsCertificate.Certificate = cert certUpdated = true break } } if !certUpdated { p.certificates = append(p.certificates, &CertAndStore{Certificate: cert, Store: tlsStore}) } p.configurationChan <- p.buildMessage() return p.Store.SaveCertificates(p.ResolverName, p.certificates) } // getCertificateRenewDurations returns renew durations calculated from the given certificatesDuration in hours. // The first (RenewPeriod) is the period before the end of the certificate duration, during which the certificate should be renewed. // The second (RenewInterval) is the interval between renew attempts. func getCertificateRenewDurations(certificatesDuration int) (time.Duration, time.Duration) { switch { case certificatesDuration >= 365*24: // >= 1 year return 4 * 30 * 24 * time.Hour, 7 * 24 * time.Hour // 4 month, 1 week case certificatesDuration >= 3*30*24: // >= 90 days return 30 * 24 * time.Hour, 24 * time.Hour // 30 days, 1 day case certificatesDuration >= 30*24: // >= 30 days return 10 * 24 * time.Hour, 12 * time.Hour // 10 days, 12 hours case certificatesDuration >= 7*24: // >= 7 days return 24 * time.Hour, time.Hour // 1 days, 1 hour case certificatesDuration >= 24: // >= 1 days return 6 * time.Hour, 10 * time.Minute // 6 hours, 10 minutes default: return 20 * time.Minute, time.Minute } } // deleteUnnecessaryDomains deletes from the configuration : // - Duplicated domains // - Domains which are checked by wildcard domain. func deleteUnnecessaryDomains(ctx context.Context, domains []types.Domain) []types.Domain { var newDomains []types.Domain logger := log.Ctx(ctx) for idxDomainToCheck, domainToCheck := range domains { keepDomain := true for idxDomain, domain := range domains { if idxDomainToCheck == idxDomain { continue } if reflect.DeepEqual(domain, domainToCheck) { if idxDomainToCheck > idxDomain { logger.Warn().Msgf("The domain %v is duplicated in the configuration but will be process by ACME provider only once.", domainToCheck) keepDomain = false } break } // Check if CN or SANS to check already exists // or cannot be checked by a wildcard var newDomainsToCheck []string for _, domainProcessed := range domainToCheck.ToStrArray() { if idxDomain < idxDomainToCheck && isDomainAlreadyChecked(domainProcessed, domain.ToStrArray()) { // The domain is duplicated in a CN logger.Warn().Msgf("Domain %q is duplicated in the configuration or validated by the domain %v. It will be processed once.", domainProcessed, domain) continue } else if domain.Main != domainProcessed && strings.HasPrefix(domain.Main, "*") && isDomainAlreadyChecked(domainProcessed, []string{domain.Main}) { // Check if a wildcard can validate the domain logger.Warn().Msgf("Domain %q will not be processed by ACME provider because it is validated by the wildcard %q", domainProcessed, domain.Main) continue } newDomainsToCheck = append(newDomainsToCheck, domainProcessed) } // Delete the domain if both Main and SANs can be validated by the wildcard domain // otherwise keep the unchecked values if newDomainsToCheck == nil { keepDomain = false break } domainToCheck.Set(newDomainsToCheck) } if keepDomain {
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/acme/account.go
pkg/provider/acme/account.go
package acme import ( "context" "crypto" "crypto/rand" "crypto/rsa" "crypto/x509" "github.com/go-acme/lego/v4/certcrypto" "github.com/go-acme/lego/v4/registration" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/observability/logs" ) // Account is used to store lets encrypt registration info. type Account struct { Email string Registration *registration.Resource PrivateKey []byte KeyType certcrypto.KeyType } const ( // RegistrationURLPathV1Regexp is a regexp which match ACME registration URL in the V1 format. RegistrationURLPathV1Regexp = `^.*/acme/reg/\d+$` ) // NewAccount creates an account. func NewAccount(ctx context.Context, email, keyTypeValue string) (*Account, error) { keyType := GetKeyType(ctx, keyTypeValue) // Create a user. New accounts need an email and private key to start privateKey, err := rsa.GenerateKey(rand.Reader, 4096) if err != nil { return nil, err } return &Account{ Email: email, PrivateKey: x509.MarshalPKCS1PrivateKey(privateKey), KeyType: keyType, }, nil } // GetEmail returns email. func (a *Account) GetEmail() string { return a.Email } // GetRegistration returns lets encrypt registration resource. func (a *Account) GetRegistration() *registration.Resource { return a.Registration } // GetPrivateKey returns private key. func (a *Account) GetPrivateKey() crypto.PrivateKey { privateKey, err := x509.ParsePKCS1PrivateKey(a.PrivateKey) if err != nil { log.Error().Str(logs.ProviderName, "acme"). Err(err).Msgf("Cannot unmarshal private key %+v", a.PrivateKey) return nil } return privateKey } // GetKeyType used to determine which algo to used. func GetKeyType(ctx context.Context, value string) certcrypto.KeyType { logger := log.Ctx(ctx) switch value { case "EC256": return certcrypto.EC256 case "EC384": return certcrypto.EC384 case "RSA2048": return certcrypto.RSA2048 case "RSA4096": return certcrypto.RSA4096 case "RSA8192": return certcrypto.RSA8192 case "": logger.Info().Msgf("The key type is empty. Use default key type %v.", certcrypto.RSA4096) return certcrypto.RSA4096 default: logger.Info().Msgf("Unable to determine the key type value %q: falling back on %v.", value, certcrypto.RSA4096) return certcrypto.RSA4096 } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/acme/provider_test.go
pkg/provider/acme/provider_test.go
package acme import ( "crypto/tls" "testing" "time" "github.com/go-acme/lego/v4/certcrypto" "github.com/stretchr/testify/assert" "github.com/traefik/traefik/v3/pkg/safe" "github.com/traefik/traefik/v3/pkg/types" ) func TestGetUncheckedCertificates(t *testing.T) { t.Skip("Needs TLS Manager") wildcardMap := make(map[string]*tls.Certificate) wildcardMap["*.traefik.wtf"] = &tls.Certificate{} wildcardSafe := &safe.Safe{} wildcardSafe.Set(wildcardMap) domainMap := make(map[string]*tls.Certificate) domainMap["traefik.wtf"] = &tls.Certificate{} domainSafe := &safe.Safe{} domainSafe.Set(domainMap) // TODO Add a test for DefaultCertificate testCases := []struct { desc string dynamicCerts *safe.Safe resolvingDomains map[string]struct{} acmeCertificates []*CertAndStore domains []string expectedDomains []string }{ { desc: "wildcard to generate", domains: []string{"*.traefik.wtf"}, expectedDomains: []string{"*.traefik.wtf"}, }, { desc: "wildcard already exists in dynamic certificates", domains: []string{"*.traefik.wtf"}, dynamicCerts: wildcardSafe, expectedDomains: nil, }, { desc: "wildcard already exists in ACME certificates", domains: []string{"*.traefik.wtf"}, acmeCertificates: []*CertAndStore{ { Certificate: Certificate{ Domain: types.Domain{Main: "*.traefik.wtf"}, }, }, }, expectedDomains: nil, }, { desc: "domain CN and SANs to generate", domains: []string{"traefik.wtf", "foo.traefik.wtf"}, expectedDomains: []string{"traefik.wtf", "foo.traefik.wtf"}, }, { desc: "domain CN already exists in dynamic certificates and SANs to generate", domains: []string{"traefik.wtf", "foo.traefik.wtf"}, dynamicCerts: domainSafe, expectedDomains: []string{"foo.traefik.wtf"}, }, { desc: "domain CN already exists in ACME certificates and SANs to generate", domains: []string{"traefik.wtf", "foo.traefik.wtf"}, acmeCertificates: []*CertAndStore{ { Certificate: Certificate{ Domain: types.Domain{Main: "traefik.wtf"}, }, }, }, expectedDomains: []string{"foo.traefik.wtf"}, }, { desc: "domain already exists in dynamic certificates", domains: []string{"traefik.wtf"}, dynamicCerts: domainSafe, expectedDomains: nil, }, { desc: "domain already exists in ACME certificates", domains: []string{"traefik.wtf"}, acmeCertificates: []*CertAndStore{ { Certificate: Certificate{ Domain: types.Domain{Main: "traefik.wtf"}, }, }, }, expectedDomains: nil, }, { desc: "domain matched by wildcard in dynamic certificates", domains: []string{"who.traefik.wtf", "foo.traefik.wtf"}, dynamicCerts: wildcardSafe, expectedDomains: nil, }, { desc: "domain matched by wildcard in ACME certificates", domains: []string{"who.traefik.wtf", "foo.traefik.wtf"}, acmeCertificates: []*CertAndStore{ { Certificate: Certificate{ Domain: types.Domain{Main: "*.traefik.wtf"}, }, }, }, expectedDomains: nil, }, { desc: "root domain with wildcard in ACME certificates", domains: []string{"traefik.wtf", "foo.traefik.wtf"}, acmeCertificates: []*CertAndStore{ { Certificate: Certificate{ Domain: types.Domain{Main: "*.traefik.wtf"}, }, }, }, expectedDomains: []string{"traefik.wtf"}, }, { desc: "all domains already managed by ACME", domains: []string{"traefik.wtf", "foo.traefik.wtf"}, resolvingDomains: map[string]struct{}{ "traefik.wtf": {}, "foo.traefik.wtf": {}, }, expectedDomains: []string{}, }, { desc: "one domain already managed by ACME", domains: []string{"traefik.wtf", "foo.traefik.wtf"}, resolvingDomains: map[string]struct{}{ "traefik.wtf": {}, }, expectedDomains: []string{"foo.traefik.wtf"}, }, { desc: "wildcard domain already managed by ACME checks the domains", domains: []string{"bar.traefik.wtf", "foo.traefik.wtf"}, resolvingDomains: map[string]struct{}{ "*.traefik.wtf": {}, }, expectedDomains: []string{}, }, { desc: "wildcard domain already managed by ACME checks domains and another domain checks one other domain, one domain still unchecked", domains: []string{"traefik.wtf", "bar.traefik.wtf", "foo.traefik.wtf", "acme.wtf"}, resolvingDomains: map[string]struct{}{ "*.traefik.wtf": {}, "traefik.wtf": {}, }, expectedDomains: []string{"acme.wtf"}, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() if test.resolvingDomains == nil { test.resolvingDomains = make(map[string]struct{}) } acmeProvider := Provider{ // certificateStore: &traefiktls.CertificateStore{ // DynamicCerts: test.dynamicCerts, // }, certificates: test.acmeCertificates, resolvingDomains: test.resolvingDomains, } domains := acmeProvider.getUncheckedDomains(t.Context(), test.domains, "default") assert.Len(t, domains, len(test.expectedDomains), "Unexpected domains.") }) } } func TestProvider_sanitizeDomains(t *testing.T) { testCases := []struct { desc string domains types.Domain dnsChallenge *DNSChallenge expectedErr string expectedDomains []string }{ { desc: "valid wildcard", domains: types.Domain{Main: "*.traefik.wtf"}, dnsChallenge: &DNSChallenge{}, expectedErr: "", expectedDomains: []string{"*.traefik.wtf"}, }, { desc: "no wildcard", domains: types.Domain{Main: "traefik.wtf", SANs: []string{"foo.traefik.wtf"}}, dnsChallenge: &DNSChallenge{}, expectedErr: "", expectedDomains: []string{"traefik.wtf", "foo.traefik.wtf"}, }, { desc: "no domain", domains: types.Domain{}, dnsChallenge: nil, expectedErr: "no domain was given", expectedDomains: nil, }, { desc: "unauthorized wildcard with SAN", domains: types.Domain{Main: "*.*.traefik.wtf", SANs: []string{"foo.traefik.wtf"}}, dnsChallenge: &DNSChallenge{}, expectedErr: "unable to generate a wildcard certificate in ACME provider for domain \"*.*.traefik.wtf,foo.traefik.wtf\" : ACME does not allow '*.*' wildcard domain", expectedDomains: nil, }, { desc: "wildcard and SANs", domains: types.Domain{Main: "*.traefik.wtf", SANs: []string{"traefik.wtf"}}, dnsChallenge: &DNSChallenge{}, expectedErr: "", expectedDomains: []string{"*.traefik.wtf", "traefik.wtf"}, }, { desc: "wildcard SANs", domains: types.Domain{Main: "*.traefik.wtf", SANs: []string{"*.acme.wtf"}}, dnsChallenge: &DNSChallenge{}, expectedErr: "", expectedDomains: []string{"*.traefik.wtf", "*.acme.wtf"}, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() acmeProvider := Provider{Configuration: &Configuration{DNSChallenge: test.dnsChallenge}} domains, err := acmeProvider.sanitizeDomains(t.Context(), test.domains) if len(test.expectedErr) > 0 { assert.EqualError(t, err, test.expectedErr, "Unexpected error.") } else { assert.Len(t, domains, len(test.expectedDomains), "Unexpected domains.") } }) } } func TestDeleteUnnecessaryDomains(t *testing.T) { testCases := []struct { desc string domains []types.Domain expectedDomains []types.Domain }{ { desc: "no domain to delete", domains: []types.Domain{ { Main: "acme.wtf", SANs: []string{"traefik.acme.wtf", "foo.bar"}, }, { Main: "*.foo.acme.wtf", }, { Main: "acme02.wtf", SANs: []string{"traefik.acme02.wtf", "bar.foo"}, }, }, expectedDomains: []types.Domain{ { Main: "acme.wtf", SANs: []string{"traefik.acme.wtf", "foo.bar"}, }, { Main: "*.foo.acme.wtf", SANs: []string{}, }, { Main: "acme02.wtf", SANs: []string{"traefik.acme02.wtf", "bar.foo"}, }, }, }, { desc: "wildcard and root domain", domains: []types.Domain{ { Main: "acme.wtf", }, { Main: "*.acme.wtf", SANs: []string{"acme.wtf"}, }, }, expectedDomains: []types.Domain{ { Main: "acme.wtf", SANs: []string{}, }, { Main: "*.acme.wtf", SANs: []string{}, }, }, }, { desc: "2 equals domains", domains: []types.Domain{ { Main: "acme.wtf", SANs: []string{"traefik.acme.wtf", "foo.bar"}, }, { Main: "acme.wtf", SANs: []string{"traefik.acme.wtf", "foo.bar"}, }, }, expectedDomains: []types.Domain{ { Main: "acme.wtf", SANs: []string{"traefik.acme.wtf", "foo.bar"}, }, }, }, { desc: "2 domains with same values", domains: []types.Domain{ { Main: "acme.wtf", SANs: []string{"traefik.acme.wtf"}, }, { Main: "acme.wtf", SANs: []string{"traefik.acme.wtf", "foo.bar"}, }, }, expectedDomains: []types.Domain{ { Main: "acme.wtf", SANs: []string{"traefik.acme.wtf"}, }, { Main: "foo.bar", SANs: []string{}, }, }, }, { desc: "domain totally checked by wildcard", domains: []types.Domain{ { Main: "who.acme.wtf", SANs: []string{"traefik.acme.wtf", "bar.acme.wtf"}, }, { Main: "*.acme.wtf", }, }, expectedDomains: []types.Domain{ { Main: "*.acme.wtf", SANs: []string{}, }, }, }, { desc: "duplicated wildcard", domains: []types.Domain{ { Main: "*.acme.wtf", SANs: []string{"acme.wtf"}, }, { Main: "*.acme.wtf", }, }, expectedDomains: []types.Domain{ { Main: "*.acme.wtf", SANs: []string{"acme.wtf"}, }, }, }, { desc: "domain partially checked by wildcard", domains: []types.Domain{ { Main: "traefik.acme.wtf", SANs: []string{"acme.wtf", "foo.bar"}, }, { Main: "*.acme.wtf", }, { Main: "who.acme.wtf", SANs: []string{"traefik.acme.wtf", "bar.acme.wtf"}, }, }, expectedDomains: []types.Domain{ { Main: "acme.wtf", SANs: []string{"foo.bar"}, }, { Main: "*.acme.wtf", SANs: []string{}, }, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() domains := deleteUnnecessaryDomains(t.Context(), test.domains) assert.Equal(t, test.expectedDomains, domains, "unexpected domain") }) } } func TestIsAccountMatchingCaServer(t *testing.T) { testCases := []struct { desc string accountURI string serverURI string expected bool }{ { desc: "acme staging with matching account", accountURI: "https://acme-staging-v02.api.letsencrypt.org/acme/acct/1234567", serverURI: "https://acme-staging-v02.api.letsencrypt.org/acme/directory", expected: true, }, { desc: "acme production with matching account", accountURI: "https://acme-v02.api.letsencrypt.org/acme/acct/1234567", serverURI: "https://acme-v02.api.letsencrypt.org/acme/directory", expected: true, }, { desc: "http only acme with matching account", accountURI: "http://acme.api.letsencrypt.org/acme/acct/1234567", serverURI: "http://acme.api.letsencrypt.org/acme/directory", expected: true, }, { desc: "different subdomains for account and server", accountURI: "https://test1.example.org/acme/acct/1234567", serverURI: "https://test2.example.org/acme/directory", expected: false, }, { desc: "different domains for account and server", accountURI: "https://test.example1.org/acme/acct/1234567", serverURI: "https://test.example2.org/acme/directory", expected: false, }, { desc: "different tld for account and server", accountURI: "https://test.example.com/acme/acct/1234567", serverURI: "https://test.example.org/acme/directory", expected: false, }, { desc: "malformed account url", accountURI: "//|\\/test.example.com/acme/acct/1234567", serverURI: "https://test.example.com/acme/directory", expected: false, }, { desc: "malformed server url", accountURI: "https://test.example.com/acme/acct/1234567", serverURI: "//|\\/test.example.com/acme/directory", expected: false, }, { desc: "malformed server and account url", accountURI: "//|\\/test.example.com/acme/acct/1234567", serverURI: "//|\\/test.example.com/acme/directory", expected: false, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() result := isAccountMatchingCaServer(t.Context(), test.accountURI, test.serverURI) assert.Equal(t, test.expected, result) }) } } func TestInitAccount(t *testing.T) { testCases := []struct { desc string account *Account email string keyType string expectedAccount *Account }{ { desc: "Existing account with all information", account: &Account{ Email: "foo@foo.net", KeyType: certcrypto.EC256, }, expectedAccount: &Account{ Email: "foo@foo.net", KeyType: certcrypto.EC256, }, }, { desc: "Account nil", email: "foo@foo.net", keyType: "EC256", expectedAccount: &Account{ Email: "foo@foo.net", KeyType: certcrypto.EC256, }, }, { desc: "Existing account with no email", account: &Account{ KeyType: certcrypto.RSA4096, }, email: "foo@foo.net", keyType: "EC256", expectedAccount: &Account{ Email: "foo@foo.net", KeyType: certcrypto.EC256, }, }, { desc: "Existing account with no key type", account: &Account{ Email: "foo@foo.net", }, email: "bar@foo.net", keyType: "EC256", expectedAccount: &Account{ Email: "foo@foo.net", KeyType: certcrypto.EC256, }, }, { desc: "Existing account and provider with no key type", account: &Account{ Email: "foo@foo.net", }, email: "bar@foo.net", expectedAccount: &Account{ Email: "foo@foo.net", KeyType: certcrypto.RSA4096, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() acmeProvider := Provider{account: test.account, Configuration: &Configuration{Email: test.email, KeyType: test.keyType}} actualAccount, err := acmeProvider.initAccount(t.Context()) assert.NoError(t, err, "Init account in error") assert.Equal(t, test.expectedAccount.Email, actualAccount.Email, "unexpected email account") assert.Equal(t, test.expectedAccount.KeyType, actualAccount.KeyType, "unexpected keyType account") }) } } func Test_getCertificateRenewDurations(t *testing.T) { testCases := []struct { desc string certificatesDurations int expectRenewPeriod time.Duration expectRenewInterval time.Duration }{ { desc: "Less than 24 Hours certificates: 20 minutes renew period, 1 minutes renew interval", certificatesDurations: 1, expectRenewPeriod: time.Minute * 20, expectRenewInterval: time.Minute, }, { desc: "1 Year certificates: 4 months renew period, 1 week renew interval", certificatesDurations: 24 * 365, expectRenewPeriod: time.Hour * 24 * 30 * 4, expectRenewInterval: time.Hour * 24 * 7, }, { desc: "265 Days certificates: 30 days renew period, 1 day renew interval", certificatesDurations: 24 * 265, expectRenewPeriod: time.Hour * 24 * 30, expectRenewInterval: time.Hour * 24, }, { desc: "90 Days certificates: 30 days renew period, 1 day renew interval", certificatesDurations: 24 * 90, expectRenewPeriod: time.Hour * 24 * 30, expectRenewInterval: time.Hour * 24, }, { desc: "30 Days certificates: 10 days renew period, 12 hour renew interval", certificatesDurations: 24 * 30, expectRenewPeriod: time.Hour * 24 * 10, expectRenewInterval: time.Hour * 12, }, { desc: "7 Days certificates: 1 days renew period, 1 hour renew interval", certificatesDurations: 24 * 7, expectRenewPeriod: time.Hour * 24, expectRenewInterval: time.Hour, }, { desc: "24 Hours certificates: 6 hours renew period, 10 minutes renew interval", certificatesDurations: 24, expectRenewPeriod: time.Hour * 6, expectRenewInterval: time.Minute * 10, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() renewPeriod, renewInterval := getCertificateRenewDurations(test.certificatesDurations) assert.Equal(t, test.expectRenewPeriod, renewPeriod) assert.Equal(t, test.expectRenewInterval, renewInterval) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/file/file.go
pkg/provider/file/file.go
package file import ( "bytes" "context" "errors" "fmt" "os" "os/signal" "path" "path/filepath" "strings" "syscall" "text/template" "github.com/Masterminds/sprig/v3" "github.com/fsnotify/fsnotify" "github.com/rs/zerolog/log" "github.com/traefik/paerser/file" "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/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" ) const providerName = "file" var _ provider.Provider = (*Provider)(nil) // Provider holds configurations of the provider. type Provider struct { Directory string `description:"Load dynamic configuration from one or more .yml or .toml files in a directory." json:"directory,omitempty" toml:"directory,omitempty" yaml:"directory,omitempty" export:"true"` Watch bool `description:"Watch provider." json:"watch,omitempty" toml:"watch,omitempty" yaml:"watch,omitempty" export:"true"` Filename string `description:"Load dynamic configuration from a file." json:"filename,omitempty" toml:"filename,omitempty" yaml:"filename,omitempty" export:"true"` DebugLogGeneratedTemplate bool `description:"Enable debug logging of generated configuration template." json:"debugLogGeneratedTemplate,omitempty" toml:"debugLogGeneratedTemplate,omitempty" yaml:"debugLogGeneratedTemplate,omitempty" export:"true"` } // SetDefaults sets the default values. func (p *Provider) SetDefaults() { p.Watch = true p.Filename = "" } // Init the provider. func (p *Provider) Init() error { return nil } // Provide allows the file provider to provide configurations to traefik // using the given configuration channel. func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error { logger := log.With().Str(logs.ProviderName, providerName).Logger() if p.Watch { var watchItems []string switch { case len(p.Directory) > 0: watchItems = append(watchItems, p.Directory) fileList, err := os.ReadDir(p.Directory) if err != nil { return fmt.Errorf("unable to read directory %s: %w", p.Directory, err) } for _, entry := range fileList { if entry.IsDir() { // ignore sub-dir continue } watchItems = append(watchItems, path.Join(p.Directory, entry.Name())) } case len(p.Filename) > 0: watchItems = append(watchItems, filepath.Dir(p.Filename), p.Filename) default: return errors.New("error using file configuration provider, neither filename nor directory is defined") } if err := p.addWatcher(pool, watchItems, configurationChan, p.applyConfiguration); err != nil { return err } } pool.GoCtx(func(ctx context.Context) { signals := make(chan os.Signal, 1) signal.Notify(signals, syscall.SIGHUP) for { select { case <-ctx.Done(): return // signals only receives SIGHUP events. case <-signals: if err := p.applyConfiguration(configurationChan); err != nil { logger.Error().Err(err).Msg("Error while building configuration") } } } }) if err := p.applyConfiguration(configurationChan); err != nil { if p.Watch { logger.Err(err).Msg("Error while building configuration (for the first time)") return nil } return err } return nil } func (p *Provider) addWatcher(pool *safe.Pool, items []string, configurationChan chan<- dynamic.Message, callback func(chan<- dynamic.Message) error) error { watcher, err := fsnotify.NewWatcher() if err != nil { return fmt.Errorf("error creating file watcher: %w", err) } for _, item := range items { log.Debug().Msgf("add watcher on: %s", item) err = watcher.Add(item) if err != nil { return fmt.Errorf("error adding file watcher: %w", err) } } // Process events pool.GoCtx(func(ctx context.Context) { logger := log.With().Str(logs.ProviderName, providerName).Logger() defer watcher.Close() for { select { case <-ctx.Done(): return case evt := <-watcher.Events: if p.Directory == "" { _, evtFileName := filepath.Split(evt.Name) _, confFileName := filepath.Split(p.Filename) if evtFileName == confFileName { err := callback(configurationChan) if err != nil { logger.Error().Err(err).Msg("Error occurred during watcher callback") } } } else { err := callback(configurationChan) if err != nil { logger.Error().Err(err).Msg("Error occurred during watcher callback") } } case err := <-watcher.Errors: logger.Error().Err(err).Msg("Watcher event error") } } }) return nil } // applyConfiguration builds the configuration and sends it to the given configurationChan. func (p *Provider) applyConfiguration(configurationChan chan<- dynamic.Message) error { configuration, err := p.buildConfiguration() if err != nil { return err } sendConfigToChannel(configurationChan, configuration) return nil } // buildConfiguration loads configuration either from file or a directory // specified by 'Filename'/'Directory' and returns a 'Configuration' object. func (p *Provider) buildConfiguration() (*dynamic.Configuration, error) { ctx := log.With().Str(logs.ProviderName, providerName).Logger().WithContext(context.Background()) if len(p.Directory) > 0 { return p.loadFileConfigFromDirectory(ctx, p.Directory, nil) } if len(p.Filename) > 0 { return p.loadFileConfig(ctx, p.Filename, true) } return nil, errors.New("error using file configuration provider, neither filename nor directory is defined") } func sendConfigToChannel(configurationChan chan<- dynamic.Message, configuration *dynamic.Configuration) { configurationChan <- dynamic.Message{ ProviderName: "file", Configuration: configuration, } } func (p *Provider) loadFileConfig(ctx context.Context, filename string, parseTemplate bool) (*dynamic.Configuration, error) { var err error var configuration *dynamic.Configuration if parseTemplate { configuration, err = p.CreateConfiguration(ctx, filename, template.FuncMap{}, false) } else { configuration, err = p.DecodeConfiguration(filename) } if err != nil { return nil, err } if configuration.TLS != nil { configuration.TLS.Certificates = flattenCertificates(ctx, configuration.TLS) // TLS Options if configuration.TLS.Options != nil { for name, options := range configuration.TLS.Options { var caCerts []types.FileOrContent for _, caFile := range options.ClientAuth.CAFiles { content, err := caFile.Read() if err != nil { log.Ctx(ctx).Error().Err(err).Send() continue } caCerts = append(caCerts, types.FileOrContent(content)) } options.ClientAuth.CAFiles = caCerts configuration.TLS.Options[name] = options } } // TLS stores if len(configuration.TLS.Stores) > 0 { for name, store := range configuration.TLS.Stores { if store.DefaultCertificate == nil { continue } content, err := store.DefaultCertificate.CertFile.Read() if err != nil { log.Ctx(ctx).Error().Err(err).Send() continue } store.DefaultCertificate.CertFile = types.FileOrContent(content) content, err = store.DefaultCertificate.KeyFile.Read() if err != nil { log.Ctx(ctx).Error().Err(err).Send() continue } store.DefaultCertificate.KeyFile = types.FileOrContent(content) configuration.TLS.Stores[name] = store } } } // HTTP ServersTransport if configuration.HTTP != nil && len(configuration.HTTP.ServersTransports) > 0 { for name, st := range configuration.HTTP.ServersTransports { var certificates []tls.Certificate for _, cert := range st.Certificates { content, err := cert.CertFile.Read() if err != nil { log.Ctx(ctx).Error().Err(err).Send() continue } cert.CertFile = types.FileOrContent(content) content, err = cert.KeyFile.Read() if err != nil { log.Ctx(ctx).Error().Err(err).Send() continue } cert.KeyFile = types.FileOrContent(content) certificates = append(certificates, cert) } configuration.HTTP.ServersTransports[name].Certificates = certificates var rootCAs []types.FileOrContent for _, rootCA := range st.RootCAs { content, err := rootCA.Read() if err != nil { log.Ctx(ctx).Error().Err(err).Send() continue } rootCAs = append(rootCAs, types.FileOrContent(content)) } st.RootCAs = rootCAs } } // TCP ServersTransport if configuration.TCP != nil && len(configuration.TCP.ServersTransports) > 0 { for name, st := range configuration.TCP.ServersTransports { var certificates []tls.Certificate if st.TLS == nil { continue } for _, cert := range st.TLS.Certificates { content, err := cert.CertFile.Read() if err != nil { log.Ctx(ctx).Error().Err(err).Send() continue } cert.CertFile = types.FileOrContent(content) content, err = cert.KeyFile.Read() if err != nil { log.Ctx(ctx).Error().Err(err).Send() continue } cert.KeyFile = types.FileOrContent(content) certificates = append(certificates, cert) } configuration.TCP.ServersTransports[name].TLS.Certificates = certificates var rootCAs []types.FileOrContent for _, rootCA := range st.TLS.RootCAs { content, err := rootCA.Read() if err != nil { log.Ctx(ctx).Error().Err(err).Send() continue } rootCAs = append(rootCAs, types.FileOrContent(content)) } st.TLS.RootCAs = rootCAs } } return configuration, nil } func flattenCertificates(ctx context.Context, tlsConfig *dynamic.TLSConfiguration) []*tls.CertAndStores { var certs []*tls.CertAndStores for _, cert := range tlsConfig.Certificates { content, err := cert.Certificate.CertFile.Read() if err != nil { log.Ctx(ctx).Error().Err(err).Send() continue } cert.Certificate.CertFile = types.FileOrContent(string(content)) content, err = cert.Certificate.KeyFile.Read() if err != nil { log.Ctx(ctx).Error().Err(err).Send() continue } cert.Certificate.KeyFile = types.FileOrContent(string(content)) certs = append(certs, cert) } return certs } func (p *Provider) loadFileConfigFromDirectory(ctx context.Context, directory string, configuration *dynamic.Configuration) (*dynamic.Configuration, error) { fileList, err := os.ReadDir(directory) if err != nil { return configuration, fmt.Errorf("unable to read directory %s: %w", directory, err) } if configuration == nil { configuration = &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: make(map[string]*dynamic.Router), Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), ServersTransports: make(map[string]*dynamic.ServersTransport), }, TCP: &dynamic.TCPConfiguration{ Routers: make(map[string]*dynamic.TCPRouter), Services: make(map[string]*dynamic.TCPService), Middlewares: make(map[string]*dynamic.TCPMiddleware), ServersTransports: make(map[string]*dynamic.TCPServersTransport), }, TLS: &dynamic.TLSConfiguration{ Stores: make(map[string]tls.Store), Options: make(map[string]tls.Options), }, UDP: &dynamic.UDPConfiguration{ Routers: make(map[string]*dynamic.UDPRouter), Services: make(map[string]*dynamic.UDPService), }, } } configTLSMaps := make(map[*tls.CertAndStores]struct{}) for _, item := range fileList { logger := log.Ctx(ctx).With().Str("filename", item.Name()).Logger() if item.IsDir() { configuration, err = p.loadFileConfigFromDirectory(logger.WithContext(ctx), filepath.Join(directory, item.Name()), configuration) if err != nil { return configuration, fmt.Errorf("unable to load content configuration from subdirectory %s: %w", item, err) } continue } switch strings.ToLower(filepath.Ext(item.Name())) { case ".toml", ".yaml", ".yml": // noop default: continue } var c *dynamic.Configuration c, err = p.loadFileConfig(logger.WithContext(ctx), filepath.Join(directory, item.Name()), true) if err != nil { return configuration, fmt.Errorf("%s: %w", filepath.Join(directory, item.Name()), err) } for name, conf := range c.HTTP.Routers { if _, exists := configuration.HTTP.Routers[name]; exists { logger.Warn().Str(logs.RouterName, name).Msg("HTTP router already configured, skipping") } else { configuration.HTTP.Routers[name] = conf } } for name, conf := range c.HTTP.Middlewares { if _, exists := configuration.HTTP.Middlewares[name]; exists { logger.Warn().Str(logs.MiddlewareName, name).Msg("HTTP middleware already configured, skipping") } else { configuration.HTTP.Middlewares[name] = conf } } for name, conf := range c.HTTP.Services { if _, exists := configuration.HTTP.Services[name]; exists { logger.Warn().Str(logs.ServiceName, name).Msg("HTTP service already configured, skipping") } else { configuration.HTTP.Services[name] = conf } } for name, conf := range c.HTTP.ServersTransports { if _, exists := configuration.HTTP.ServersTransports[name]; exists { logger.Warn().Str(logs.ServersTransportName, name).Msg("HTTP servers transport already configured, skipping") } else { configuration.HTTP.ServersTransports[name] = conf } } for name, conf := range c.TCP.Routers { if _, exists := configuration.TCP.Routers[name]; exists { logger.Warn().Str(logs.RouterName, name).Msg("TCP router already configured, skipping") } else { configuration.TCP.Routers[name] = conf } } for name, conf := range c.TCP.Middlewares { if _, exists := configuration.TCP.Middlewares[name]; exists { logger.Warn().Str(logs.MiddlewareName, name).Msg("TCP middleware already configured, skipping") } else { configuration.TCP.Middlewares[name] = conf } } for name, conf := range c.TCP.Services { if _, exists := configuration.TCP.Services[name]; exists { logger.Warn().Str(logs.ServiceName, name).Msg("TCP service already configured, skipping") } else { configuration.TCP.Services[name] = conf } } for name, conf := range c.TCP.ServersTransports { if _, exists := configuration.TCP.ServersTransports[name]; exists { logger.Warn().Str(logs.ServersTransportName, name).Msg("TCP servers transport already configured, skipping") } else { configuration.TCP.ServersTransports[name] = conf } } for name, conf := range c.UDP.Routers { if _, exists := configuration.UDP.Routers[name]; exists { logger.Warn().Str(logs.RouterName, name).Msg("UDP router already configured, skipping") } else { configuration.UDP.Routers[name] = conf } } for name, conf := range c.UDP.Services { if _, exists := configuration.UDP.Services[name]; exists { logger.Warn().Str(logs.ServiceName, name).Msg("UDP service already configured, skipping") } else { configuration.UDP.Services[name] = conf } } for _, conf := range c.TLS.Certificates { if _, exists := configTLSMaps[conf]; exists { logger.Warn().Msgf("TLS configuration %v already configured, skipping", conf) } else { configTLSMaps[conf] = struct{}{} } } for name, conf := range c.TLS.Options { if _, exists := configuration.TLS.Options[name]; exists { logger.Warn().Msgf("TLS options %v already configured, skipping", name) } else { if configuration.TLS.Options == nil { configuration.TLS.Options = map[string]tls.Options{} } configuration.TLS.Options[name] = conf } } for name, conf := range c.TLS.Stores { if _, exists := configuration.TLS.Stores[name]; exists { logger.Warn().Msgf("TLS store %v already configured, skipping", name) } else { if configuration.TLS.Stores == nil { configuration.TLS.Stores = map[string]tls.Store{} } configuration.TLS.Stores[name] = conf } } } if len(configTLSMaps) > 0 && configuration.TLS == nil { configuration.TLS = &dynamic.TLSConfiguration{} } for conf := range configTLSMaps { configuration.TLS.Certificates = append(configuration.TLS.Certificates, conf) } return configuration, nil } // CreateConfiguration creates a provider configuration from content using templating. func (p *Provider) CreateConfiguration(ctx context.Context, filename string, funcMap template.FuncMap, templateObjects interface{}) (*dynamic.Configuration, error) { tmplContent, err := readFile(filename) if err != nil { return nil, fmt.Errorf("error reading configuration file: %s - %w", filename, err) } defaultFuncMap := sprig.TxtFuncMap() defaultFuncMap["normalize"] = provider.Normalize defaultFuncMap["split"] = strings.Split for funcID, funcElement := range funcMap { defaultFuncMap[funcID] = funcElement } tmpl := template.New(p.Filename).Funcs(defaultFuncMap) _, err = tmpl.Parse(tmplContent) if err != nil { return nil, err } var buffer bytes.Buffer err = tmpl.Execute(&buffer, templateObjects) if err != nil { return nil, err } renderedTemplate := buffer.String() if p.DebugLogGeneratedTemplate { logger := log.Ctx(ctx) logger.Debug().Msgf("Template content: %s", tmplContent) logger.Debug().Msgf("Rendering results: %s", renderedTemplate) } return p.decodeConfiguration(filename, renderedTemplate) } // DecodeConfiguration Decodes a *types.Configuration from a content. func (p *Provider) DecodeConfiguration(filename string) (*dynamic.Configuration, error) { content, err := readFile(filename) if err != nil { return nil, fmt.Errorf("error reading configuration file: %s - %w", filename, err) } return p.decodeConfiguration(filename, content) } func (p *Provider) decodeConfiguration(filePath, content string) (*dynamic.Configuration, error) { configuration := &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: make(map[string]*dynamic.Router), Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), ServersTransports: make(map[string]*dynamic.ServersTransport), }, TCP: &dynamic.TCPConfiguration{ Routers: make(map[string]*dynamic.TCPRouter), Services: make(map[string]*dynamic.TCPService), Middlewares: make(map[string]*dynamic.TCPMiddleware), ServersTransports: make(map[string]*dynamic.TCPServersTransport), }, TLS: &dynamic.TLSConfiguration{ Stores: make(map[string]tls.Store), Options: make(map[string]tls.Options), }, UDP: &dynamic.UDPConfiguration{ Routers: make(map[string]*dynamic.UDPRouter), Services: make(map[string]*dynamic.UDPService), }, } err := file.DecodeContent(content, strings.ToLower(filepath.Ext(filePath)), configuration) if err != nil { return nil, err } return configuration, nil } func readFile(filename string) (string, error) { if len(filename) > 0 { buf, err := os.ReadFile(filename) if err != nil { return "", err } return string(buf), nil } return "", fmt.Errorf("invalid filename: %s", filename) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/file/file_test.go
pkg/provider/file/file_test.go
package file import ( "io" "os" "path/filepath" "strconv" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/safe" ) type ProvideTestCase struct { desc string directoryPaths []string filePath string expectedNumRouter int expectedNumService int expectedNumTLSConf int expectedNumTLSOptions int } func TestTLSCertificateContent(t *testing.T) { tempDir := t.TempDir() fileTLS, err := createTempFile("./fixtures/toml/tls_file.cert", tempDir) require.NoError(t, err) fileTLSKey, err := createTempFile("./fixtures/toml/tls_file_key.cert", tempDir) require.NoError(t, err) fileConfig, err := os.CreateTemp(tempDir, "temp*.toml") require.NoError(t, err) content := ` [[tls.certificates]] certFile = "` + fileTLS.Name() + `" keyFile = "` + fileTLSKey.Name() + `" [tls.options.default.clientAuth] caFiles = ["` + fileTLS.Name() + `"] [tls.stores.default.defaultCertificate] certFile = "` + fileTLS.Name() + `" keyFile = "` + fileTLSKey.Name() + `" [http.serversTransports.default] rootCAs = ["` + fileTLS.Name() + `"] [[http.serversTransports.default.certificates]] certFile = "` + fileTLS.Name() + `" keyFile = "` + fileTLSKey.Name() + `" [tcp.serversTransports.default] [tcp.serversTransports.default.tls] rootCAs = ["` + fileTLS.Name() + `"] [[tcp.serversTransports.default.tls.certificates]] certFile = "` + fileTLS.Name() + `" keyFile = "` + fileTLSKey.Name() + `" ` _, err = fileConfig.WriteString(content) require.NoError(t, err) provider := &Provider{} configuration, err := provider.loadFileConfig(t.Context(), fileConfig.Name(), true) require.NoError(t, err) require.Equal(t, "CONTENT", configuration.TLS.Certificates[0].Certificate.CertFile.String()) require.Equal(t, "CONTENTKEY", configuration.TLS.Certificates[0].Certificate.KeyFile.String()) require.Equal(t, "CONTENT", configuration.TLS.Options["default"].ClientAuth.CAFiles[0].String()) require.Equal(t, "CONTENT", configuration.TLS.Stores["default"].DefaultCertificate.CertFile.String()) require.Equal(t, "CONTENTKEY", configuration.TLS.Stores["default"].DefaultCertificate.KeyFile.String()) require.Equal(t, "CONTENT", configuration.HTTP.ServersTransports["default"].Certificates[0].CertFile.String()) require.Equal(t, "CONTENTKEY", configuration.HTTP.ServersTransports["default"].Certificates[0].KeyFile.String()) require.Equal(t, "CONTENT", configuration.HTTP.ServersTransports["default"].RootCAs[0].String()) require.Equal(t, "CONTENT", configuration.TCP.ServersTransports["default"].TLS.Certificates[0].CertFile.String()) require.Equal(t, "CONTENTKEY", configuration.TCP.ServersTransports["default"].TLS.Certificates[0].KeyFile.String()) require.Equal(t, "CONTENT", configuration.TCP.ServersTransports["default"].TLS.RootCAs[0].String()) } func TestErrorWhenEmptyConfig(t *testing.T) { provider := &Provider{} configChan := make(chan dynamic.Message) errorChan := make(chan struct{}) go func() { err := provider.Provide(configChan, safe.NewPool(t.Context())) assert.Error(t, err) close(errorChan) }() timeout := time.After(time.Second) select { case <-configChan: t.Fatal("We should not receive config message") case <-timeout: t.Fatal("timeout while waiting for config") case <-errorChan: } } func TestProvideWithoutWatch(t *testing.T) { for _, test := range getTestCases() { t.Run(test.desc+" without watch", func(t *testing.T) { provider := createProvider(t, test, false) configChan := make(chan dynamic.Message) provider.DebugLogGeneratedTemplate = true go func() { err := provider.Provide(configChan, safe.NewPool(t.Context())) assert.NoError(t, err) }() timeout := time.After(time.Second) select { case conf := <-configChan: require.NotNil(t, conf.Configuration.HTTP) numServices := len(conf.Configuration.HTTP.Services) + len(conf.Configuration.TCP.Services) + len(conf.Configuration.UDP.Services) numRouters := len(conf.Configuration.HTTP.Routers) + len(conf.Configuration.TCP.Routers) + len(conf.Configuration.UDP.Routers) assert.Equal(t, test.expectedNumService, numServices) assert.Equal(t, test.expectedNumRouter, numRouters) require.NotNil(t, conf.Configuration.TLS) assert.Len(t, conf.Configuration.TLS.Certificates, test.expectedNumTLSConf) assert.Len(t, conf.Configuration.TLS.Options, test.expectedNumTLSOptions) case <-timeout: t.Errorf("timeout while waiting for config") } }) } } func TestProvideWithWatch(t *testing.T) { for _, test := range getTestCases() { t.Run(test.desc+" with watch", func(t *testing.T) { provider := createProvider(t, test, true) configChan := make(chan dynamic.Message) go func() { err := provider.Provide(configChan, safe.NewPool(t.Context())) assert.NoError(t, err) }() timeout := time.After(time.Second) select { case conf := <-configChan: require.NotNil(t, conf.Configuration.HTTP) numServices := len(conf.Configuration.HTTP.Services) + len(conf.Configuration.TCP.Services) + len(conf.Configuration.UDP.Services) numRouters := len(conf.Configuration.HTTP.Routers) + len(conf.Configuration.TCP.Routers) + len(conf.Configuration.UDP.Routers) assert.Equal(t, 0, numServices) assert.Equal(t, 0, numRouters) require.NotNil(t, conf.Configuration.TLS) assert.Empty(t, conf.Configuration.TLS.Certificates) case <-timeout: t.Errorf("timeout while waiting for config") } if len(test.filePath) > 0 { err := copyFile(test.filePath, provider.Filename) require.NoError(t, err) } if len(test.directoryPaths) > 0 { for i, filePath := range test.directoryPaths { err := copyFile(filePath, filepath.Join(provider.Directory, strconv.Itoa(i)+filepath.Ext(filePath))) require.NoError(t, err) } } timeout = time.After(1 * time.Second) var numUpdates, numServices, numRouters, numTLSConfs int for { select { case conf := <-configChan: numUpdates++ numServices = len(conf.Configuration.HTTP.Services) + len(conf.Configuration.TCP.Services) + len(conf.Configuration.UDP.Services) numRouters = len(conf.Configuration.HTTP.Routers) + len(conf.Configuration.TCP.Routers) + len(conf.Configuration.UDP.Routers) numTLSConfs = len(conf.Configuration.TLS.Certificates) t.Logf("received update #%d: services %d/%d, routers %d/%d, TLS configs %d/%d", numUpdates, numServices, test.expectedNumService, numRouters, test.expectedNumRouter, numTLSConfs, test.expectedNumTLSConf) if numServices == test.expectedNumService && numRouters == test.expectedNumRouter && numTLSConfs == test.expectedNumTLSConf { return } case <-timeout: t.Fatal("timeout while waiting for config") } } }) } } func getTestCases() []ProvideTestCase { return []ProvideTestCase{ { desc: "simple file", filePath: "./fixtures/toml/simple_file_01.toml", expectedNumRouter: 3, expectedNumService: 6, expectedNumTLSConf: 5, }, { desc: "simple file with tcp and udp", filePath: "./fixtures/toml/simple_file_02.toml", expectedNumRouter: 5, expectedNumService: 8, expectedNumTLSConf: 5, }, { desc: "simple file yaml", filePath: "./fixtures/yaml/simple_file_01.yml", expectedNumRouter: 3, expectedNumService: 6, expectedNumTLSConf: 5, }, { desc: "template file", filePath: "./fixtures/toml/template_file.toml", expectedNumRouter: 20, }, { desc: "template file yaml", filePath: "./fixtures/yaml/template_file.yml", expectedNumRouter: 20, }, { desc: "simple directory", directoryPaths: []string{ "./fixtures/toml/dir01_file01.toml", "./fixtures/toml/dir01_file02.toml", "./fixtures/toml/dir01_file03.toml", }, expectedNumRouter: 2, expectedNumService: 3, expectedNumTLSConf: 4, expectedNumTLSOptions: 1, }, { desc: "simple directory yaml", directoryPaths: []string{ "./fixtures/yaml/dir01_file01.yml", "./fixtures/yaml/dir01_file02.yml", "./fixtures/yaml/dir01_file03.yml", }, expectedNumRouter: 2, expectedNumService: 3, expectedNumTLSConf: 4, expectedNumTLSOptions: 1, }, { desc: "template in directory", directoryPaths: []string{ "./fixtures/toml/template_in_directory_file01.toml", "./fixtures/toml/template_in_directory_file02.toml", }, expectedNumRouter: 20, expectedNumService: 20, }, { desc: "template in directory yaml", directoryPaths: []string{ "./fixtures/yaml/template_in_directory_file01.yml", "./fixtures/yaml/template_in_directory_file02.yml", }, expectedNumRouter: 20, expectedNumService: 20, }, { desc: "simple file with empty store yaml", filePath: "./fixtures/yaml/simple_empty_store.yml", expectedNumRouter: 0, expectedNumService: 0, expectedNumTLSConf: 0, }, } } func createProvider(t *testing.T, test ProvideTestCase, watch bool) *Provider { t.Helper() tempDir := t.TempDir() provider := &Provider{} provider.Watch = true if len(test.directoryPaths) > 0 { if !watch { for _, filePath := range test.directoryPaths { var err error _, err = createTempFile(filePath, tempDir) require.NoError(t, err) } } provider.Directory = tempDir } if len(test.filePath) > 0 { var file *os.File if watch { var err error file, err = os.CreateTemp(tempDir, "temp*"+filepath.Ext(test.filePath)) require.NoError(t, err) } else { var err error file, err = createTempFile(test.filePath, tempDir) require.NoError(t, err) } provider.Filename = file.Name() } t.Cleanup(func() { os.RemoveAll(tempDir) }) return provider } func copyFile(srcPath, dstPath string) error { dst, err := os.OpenFile(dstPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o666) if err != nil { return err } defer dst.Close() src, err := os.Open(srcPath) if err != nil { return err } defer src.Close() _, err = io.Copy(dst, src) return err } func createTempFile(srcPath, tempDir string) (*os.File, error) { file, err := os.CreateTemp(tempDir, "temp*"+filepath.Ext(srcPath)) if err != nil { return nil, err } defer file.Close() src, err := os.Open(srcPath) if err != nil { return nil, err } defer src.Close() _, err = io.Copy(file, src) return file, err }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/traefik/internal_test.go
pkg/provider/traefik/internal_test.go
package traefik import ( "encoding/json" "flag" "os" "path/filepath" "testing" "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" "github.com/traefik/traefik/v3/pkg/ping" "github.com/traefik/traefik/v3/pkg/provider/rest" "github.com/traefik/traefik/v3/pkg/types" ) var updateExpected = flag.Bool("update_expected", false, "Update expected files in fixtures") func pointer[T any](v T) *T { return &v } func Test_createConfiguration(t *testing.T) { testCases := []struct { desc string staticCfg static.Configuration }{ { desc: "full_configuration.json", staticCfg: static.Configuration{ API: &static.API{ Insecure: true, Dashboard: true, Debug: true, }, Ping: &ping.Handler{ EntryPoint: "test", ManualRouting: false, }, Providers: &static.Providers{ Rest: &rest.Provider{ Insecure: true, }, }, Metrics: &otypes.Metrics{ Prometheus: &otypes.Prometheus{ EntryPoint: "test", ManualRouting: false, }, }, }, }, { desc: "full_configuration_secure.json", staticCfg: static.Configuration{ API: &static.API{ Insecure: false, Dashboard: true, }, Ping: &ping.Handler{ EntryPoint: "test", ManualRouting: true, }, Providers: &static.Providers{ Rest: &rest.Provider{ Insecure: false, }, }, Metrics: &otypes.Metrics{ Prometheus: &otypes.Prometheus{ EntryPoint: "test", ManualRouting: true, }, }, }, }, { desc: "api_insecure_with_dashboard.json", staticCfg: static.Configuration{ API: &static.API{ Insecure: true, Dashboard: true, }, }, }, { desc: "api_insecure_without_dashboard.json", staticCfg: static.Configuration{ API: &static.API{ Insecure: true, Dashboard: false, }, }, }, { desc: "api_secure_with_dashboard.json", staticCfg: static.Configuration{ API: &static.API{ Insecure: false, Dashboard: true, }, }, }, { desc: "api_secure_without_dashboard.json", staticCfg: static.Configuration{ API: &static.API{ Insecure: false, Dashboard: false, }, }, }, { desc: "ping_simple.json", staticCfg: static.Configuration{ Ping: &ping.Handler{ EntryPoint: "test", ManualRouting: false, }, }, }, { desc: "ping_custom.json", staticCfg: static.Configuration{ Ping: &ping.Handler{ EntryPoint: "test", ManualRouting: true, }, }, }, { desc: "rest_insecure.json", staticCfg: static.Configuration{ Providers: &static.Providers{ Rest: &rest.Provider{ Insecure: true, }, }, }, }, { desc: "rest_secure.json", staticCfg: static.Configuration{ Providers: &static.Providers{ Rest: &rest.Provider{ Insecure: false, }, }, }, }, { desc: "prometheus_simple.json", staticCfg: static.Configuration{ Metrics: &otypes.Metrics{ Prometheus: &otypes.Prometheus{ EntryPoint: "test", ManualRouting: false, }, }, }, }, { desc: "prometheus_custom.json", staticCfg: static.Configuration{ Metrics: &otypes.Metrics{ Prometheus: &otypes.Prometheus{ EntryPoint: "test", ManualRouting: true, }, }, }, }, { desc: "models.json", staticCfg: static.Configuration{ EntryPoints: map[string]*static.EntryPoint{ "websecure": { HTTP: static.HTTPConfig{ Middlewares: []string{"test"}, TLS: &static.TLSConfig{ Options: "opt", CertResolver: "le", Domains: []types.Domain{ {Main: "mainA", SANs: []string{"sanA1", "sanA2"}}, {Main: "mainB", SANs: []string{"sanB1", "sanB2"}}, }, }, }, Observability: &static.ObservabilityConfig{ AccessLogs: pointer(false), Tracing: pointer(false), Metrics: pointer(false), }, }, }, }, }, { desc: "redirection.json", staticCfg: static.Configuration{ EntryPoints: map[string]*static.EntryPoint{ "web": { Address: ":80", HTTP: static.HTTPConfig{ Redirections: &static.Redirections{ EntryPoint: &static.RedirectEntryPoint{ To: "websecure", Scheme: "https", Permanent: true, }, }, }, }, "websecure": { Address: ":443", }, }, }, }, { desc: "redirection_port.json", staticCfg: static.Configuration{ EntryPoints: map[string]*static.EntryPoint{ "web": { Address: ":80", HTTP: static.HTTPConfig{ Redirections: &static.Redirections{ EntryPoint: &static.RedirectEntryPoint{ To: ":443", Scheme: "https", Permanent: true, }, }, }, }, "websecure": { Address: ":443", }, }, }, }, { desc: "redirection_with_protocol.json", staticCfg: static.Configuration{ EntryPoints: map[string]*static.EntryPoint{ "web": { Address: ":80", HTTP: static.HTTPConfig{ Redirections: &static.Redirections{ EntryPoint: &static.RedirectEntryPoint{ To: "websecure", Scheme: "https", Permanent: true, }, }, }, }, "websecure": { Address: ":443/tcp", }, }, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() provider := Provider{staticCfg: test.staticCfg} cfg := provider.createConfiguration(t.Context()) filename := filepath.Join("fixtures", test.desc) if *updateExpected { newJSON, err := json.MarshalIndent(cfg, "", " ") require.NoError(t, err) err = os.WriteFile(filename, newJSON, 0o644) require.NoError(t, err) } expectedJSON, err := os.ReadFile(filename) require.NoError(t, err) actualJSON, err := json.MarshalIndent(cfg, "", " ") require.NoError(t, err) assert.JSONEq(t, string(expectedJSON), string(actualJSON)) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/traefik/internal.go
pkg/provider/traefik/internal.go
package traefik import ( "context" "fmt" "math" "net" "regexp" "time" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/static" "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/traefik/v3/pkg/tls" ) const defaultInternalEntryPointName = "traefik" var _ provider.Provider = (*Provider)(nil) // Provider is a provider.Provider implementation that provides the internal routers. type Provider struct { staticCfg static.Configuration } // New creates a new instance of the internal provider. func New(staticCfg static.Configuration) *Provider { return &Provider{staticCfg: staticCfg} } // ThrottleDuration returns the throttle duration. func (i *Provider) ThrottleDuration() time.Duration { return 0 } // Provide allows the provider to provide configurations to traefik using the given configuration channel. func (i *Provider) Provide(configurationChan chan<- dynamic.Message, _ *safe.Pool) error { ctx := log.With().Str(logs.ProviderName, "internal").Logger().WithContext(context.Background()) configurationChan <- dynamic.Message{ ProviderName: "internal", Configuration: i.createConfiguration(ctx), } return nil } // Init the provider. func (i *Provider) Init() error { return nil } func (i *Provider) createConfiguration(ctx context.Context) *dynamic.Configuration { cfg := &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: make(map[string]*dynamic.Router), Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), Models: make(map[string]*dynamic.Model), ServersTransports: make(map[string]*dynamic.ServersTransport), }, TCP: &dynamic.TCPConfiguration{ Routers: make(map[string]*dynamic.TCPRouter), Services: make(map[string]*dynamic.TCPService), Models: make(map[string]*dynamic.TCPModel), ServersTransports: make(map[string]*dynamic.TCPServersTransport), }, TLS: &dynamic.TLSConfiguration{ Stores: make(map[string]tls.Store), Options: make(map[string]tls.Options), }, } i.apiConfiguration(cfg) i.pingConfiguration(cfg) i.restConfiguration(cfg) i.prometheusConfiguration(cfg) i.entryPointModels(cfg) i.redirection(ctx, cfg) i.serverTransport(cfg) i.serverTransportTCP(cfg) i.acme(cfg) cfg.HTTP.Services["noop"] = &dynamic.Service{} return cfg } func (i *Provider) acme(cfg *dynamic.Configuration) { allowACMEByPass := map[string]bool{} for name, ep := range i.staticCfg.EntryPoints { allowACMEByPass[name] = ep.AllowACMEByPass } var eps []string var epsByPass []string uniq := map[string]struct{}{} for _, resolver := range i.staticCfg.CertificatesResolvers { if resolver.ACME != nil && resolver.ACME.HTTPChallenge != nil && resolver.ACME.HTTPChallenge.EntryPoint != "" { if _, ok := uniq[resolver.ACME.HTTPChallenge.EntryPoint]; ok { continue } uniq[resolver.ACME.HTTPChallenge.EntryPoint] = struct{}{} if allowByPass, ok := allowACMEByPass[resolver.ACME.HTTPChallenge.EntryPoint]; ok && allowByPass { epsByPass = append(epsByPass, resolver.ACME.HTTPChallenge.EntryPoint) continue } eps = append(eps, resolver.ACME.HTTPChallenge.EntryPoint) } } if len(eps) > 0 { rt := &dynamic.Router{ Rule: "PathPrefix(`/.well-known/acme-challenge/`)", // "default" stands for the default rule syntax in Traefik v3, i.e. the v3 syntax. RuleSyntax: "default", EntryPoints: eps, Service: "acme-http@internal", Priority: math.MaxInt, } cfg.HTTP.Routers["acme-http"] = rt cfg.HTTP.Services["acme-http"] = &dynamic.Service{} } if len(epsByPass) > 0 { rt := &dynamic.Router{ Rule: "PathPrefix(`/.well-known/acme-challenge/`)", EntryPoints: epsByPass, Service: "acme-http@internal", } cfg.HTTP.Routers["acme-http-bypass"] = rt cfg.HTTP.Services["acme-http"] = &dynamic.Service{} } } func (i *Provider) redirection(ctx context.Context, cfg *dynamic.Configuration) { for name, ep := range i.staticCfg.EntryPoints { if ep.HTTP.Redirections == nil { continue } logger := log.Ctx(ctx).With().Str(logs.EntryPointName, name).Logger() def := ep.HTTP.Redirections if def.EntryPoint == nil || def.EntryPoint.To == "" { logger.Error().Msg("Unable to create redirection: the entry point or the port is missing") continue } port, err := i.getRedirectPort(name, def) if err != nil { logger.Error().Err(err).Send() continue } rtName := provider.Normalize(name + "-to-" + def.EntryPoint.To) mdName := "redirect-" + rtName rt := &dynamic.Router{ Rule: "HostRegexp(`^.+$`)", // "default" stands for the default rule syntax in Traefik v3, i.e. the v3 syntax. RuleSyntax: "default", EntryPoints: []string{name}, Middlewares: []string{mdName}, Service: "noop@internal", Priority: def.EntryPoint.Priority, } cfg.HTTP.Routers[rtName] = rt rs := &dynamic.Middleware{ RedirectScheme: &dynamic.RedirectScheme{ Scheme: def.EntryPoint.Scheme, Port: port, Permanent: def.EntryPoint.Permanent, }, } cfg.HTTP.Middlewares[mdName] = rs } } func (i *Provider) getRedirectPort(name string, def *static.Redirections) (string, error) { exp := regexp.MustCompile(`^:(\d+)$`) if exp.MatchString(def.EntryPoint.To) { _, port, err := net.SplitHostPort(def.EntryPoint.To) if err != nil { return "", fmt.Errorf("invalid port value: %w", err) } return port, nil } return i.getEntryPointPort(name, def) } func (i *Provider) getEntryPointPort(name string, def *static.Redirections) (string, error) { dst, ok := i.staticCfg.EntryPoints[def.EntryPoint.To] if !ok { return "", fmt.Errorf("'to' entry point field references a non-existing entry point: %s", def.EntryPoint.To) } _, port, err := net.SplitHostPort(dst.GetAddress()) if err != nil { return "", fmt.Errorf("invalid entry point %q address %q: %w", name, i.staticCfg.EntryPoints[def.EntryPoint.To].Address, err) } return port, nil } func (i *Provider) entryPointModels(cfg *dynamic.Configuration) { defaultRuleSyntax := "" if i.staticCfg.Core != nil && i.staticCfg.Core.DefaultRuleSyntax != "" { defaultRuleSyntax = i.staticCfg.Core.DefaultRuleSyntax } for name, ep := range i.staticCfg.EntryPoints { if defaultRuleSyntax != "" { cfg.TCP.Models[name] = &dynamic.TCPModel{ DefaultRuleSyntax: defaultRuleSyntax, } } if len(ep.HTTP.Middlewares) == 0 && ep.HTTP.TLS == nil && defaultRuleSyntax == "" && ep.Observability == nil && ep.HTTP.EncodedCharacters == nil { continue } httpModel := &dynamic.Model{ DefaultRuleSyntax: defaultRuleSyntax, Middlewares: ep.HTTP.Middlewares, } if ep.HTTP.EncodedCharacters != nil { httpModel.DeniedEncodedPathCharacters = &dynamic.RouterDeniedEncodedPathCharacters{ AllowEncodedSlash: ep.HTTP.EncodedCharacters.AllowEncodedSlash, AllowEncodedBackSlash: ep.HTTP.EncodedCharacters.AllowEncodedBackSlash, AllowEncodedPercent: ep.HTTP.EncodedCharacters.AllowEncodedPercent, AllowEncodedQuestionMark: ep.HTTP.EncodedCharacters.AllowEncodedQuestionMark, AllowEncodedSemicolon: ep.HTTP.EncodedCharacters.AllowEncodedSemicolon, AllowEncodedHash: ep.HTTP.EncodedCharacters.AllowEncodedHash, AllowEncodedNullCharacter: ep.HTTP.EncodedCharacters.AllowEncodedNullCharacter, } } if ep.Observability != nil { httpModel.Observability = dynamic.RouterObservabilityConfig{ AccessLogs: ep.Observability.AccessLogs, Metrics: ep.Observability.Metrics, Tracing: ep.Observability.Tracing, TraceVerbosity: ep.Observability.TraceVerbosity, } } if ep.HTTP.TLS != nil { httpModel.TLS = &dynamic.RouterTLSConfig{ Options: ep.HTTP.TLS.Options, CertResolver: ep.HTTP.TLS.CertResolver, Domains: ep.HTTP.TLS.Domains, } } cfg.HTTP.Models[name] = httpModel } } func (i *Provider) apiConfiguration(cfg *dynamic.Configuration) { if i.staticCfg.API == nil { return } if i.staticCfg.API.Insecure { cfg.HTTP.Routers["api"] = &dynamic.Router{ EntryPoints: []string{defaultInternalEntryPointName}, Service: "api@internal", Priority: math.MaxInt - 1, Rule: "PathPrefix(`/api`)", // "default" stands for the default rule syntax in Traefik v3, i.e. the v3 syntax. RuleSyntax: "default", } if i.staticCfg.API.Dashboard { cfg.HTTP.Routers["dashboard"] = &dynamic.Router{ EntryPoints: []string{defaultInternalEntryPointName}, Service: "dashboard@internal", Priority: math.MaxInt - 2, Rule: "PathPrefix(`/`)", // "default" stands for the default rule syntax in Traefik v3, i.e. the v3 syntax. RuleSyntax: "default", Middlewares: []string{"dashboard_redirect@internal", "dashboard_stripprefix@internal"}, } cfg.HTTP.Middlewares["dashboard_redirect"] = &dynamic.Middleware{ RedirectRegex: &dynamic.RedirectRegex{ Regex: `^(http:\/\/(\[[\w:.]+\]|[\w\._-]+)(:\d+)?)\/$`, Replacement: "${1}/dashboard/", Permanent: true, }, } cfg.HTTP.Middlewares["dashboard_stripprefix"] = &dynamic.Middleware{ StripPrefix: &dynamic.StripPrefix{Prefixes: []string{"/dashboard/", "/dashboard"}}, } } if i.staticCfg.API.Debug { cfg.HTTP.Routers["debug"] = &dynamic.Router{ EntryPoints: []string{defaultInternalEntryPointName}, Service: "api@internal", Priority: math.MaxInt - 1, Rule: "PathPrefix(`/debug`)", // "default" stands for the default rule syntax in Traefik v3, i.e. the v3 syntax. RuleSyntax: "default", } } } cfg.HTTP.Services["api"] = &dynamic.Service{} if i.staticCfg.API.Dashboard { cfg.HTTP.Services["dashboard"] = &dynamic.Service{} } } func (i *Provider) pingConfiguration(cfg *dynamic.Configuration) { if i.staticCfg.Ping == nil { return } if !i.staticCfg.Ping.ManualRouting { cfg.HTTP.Routers["ping"] = &dynamic.Router{ EntryPoints: []string{i.staticCfg.Ping.EntryPoint}, Service: "ping@internal", Priority: math.MaxInt, Rule: "PathPrefix(`/ping`)", // "default" stands for the default rule syntax in Traefik v3, i.e. the v3 syntax. RuleSyntax: "default", } } cfg.HTTP.Services["ping"] = &dynamic.Service{} } func (i *Provider) restConfiguration(cfg *dynamic.Configuration) { if i.staticCfg.Providers == nil || i.staticCfg.Providers.Rest == nil { return } if i.staticCfg.Providers.Rest.Insecure { cfg.HTTP.Routers["rest"] = &dynamic.Router{ EntryPoints: []string{defaultInternalEntryPointName}, Service: "rest@internal", Priority: math.MaxInt, Rule: "PathPrefix(`/api/providers`)", // "default" stands for the default rule syntax in Traefik v3, i.e. the v3 syntax. RuleSyntax: "default", } } cfg.HTTP.Services["rest"] = &dynamic.Service{} } func (i *Provider) prometheusConfiguration(cfg *dynamic.Configuration) { if i.staticCfg.Metrics == nil || i.staticCfg.Metrics.Prometheus == nil { return } if !i.staticCfg.Metrics.Prometheus.ManualRouting { cfg.HTTP.Routers["prometheus"] = &dynamic.Router{ EntryPoints: []string{i.staticCfg.Metrics.Prometheus.EntryPoint}, Service: "prometheus@internal", Priority: math.MaxInt, Rule: "PathPrefix(`/metrics`)", // "default" stands for the default rule syntax in Traefik v3, i.e. the v3 syntax. RuleSyntax: "default", } } cfg.HTTP.Services["prometheus"] = &dynamic.Service{} } func (i *Provider) serverTransport(cfg *dynamic.Configuration) { if i.staticCfg.ServersTransport == nil { return } st := &dynamic.ServersTransport{ InsecureSkipVerify: i.staticCfg.ServersTransport.InsecureSkipVerify, RootCAs: i.staticCfg.ServersTransport.RootCAs, MaxIdleConnsPerHost: i.staticCfg.ServersTransport.MaxIdleConnsPerHost, } if i.staticCfg.ServersTransport.Spiffe != nil { st.Spiffe = &dynamic.Spiffe{ IDs: i.staticCfg.ServersTransport.Spiffe.IDs, TrustDomain: i.staticCfg.ServersTransport.Spiffe.TrustDomain, } } if i.staticCfg.ServersTransport.ForwardingTimeouts != nil { st.ForwardingTimeouts = &dynamic.ForwardingTimeouts{ DialTimeout: i.staticCfg.ServersTransport.ForwardingTimeouts.DialTimeout, ResponseHeaderTimeout: i.staticCfg.ServersTransport.ForwardingTimeouts.ResponseHeaderTimeout, IdleConnTimeout: i.staticCfg.ServersTransport.ForwardingTimeouts.IdleConnTimeout, } } cfg.HTTP.ServersTransports["default"] = st } func (i *Provider) serverTransportTCP(cfg *dynamic.Configuration) { if i.staticCfg.TCPServersTransport == nil { return } st := &dynamic.TCPServersTransport{ DialTimeout: i.staticCfg.TCPServersTransport.DialTimeout, DialKeepAlive: i.staticCfg.TCPServersTransport.DialKeepAlive, } if i.staticCfg.TCPServersTransport.TLS != nil { st.TLS = &dynamic.TLSClientConfig{ InsecureSkipVerify: i.staticCfg.TCPServersTransport.TLS.InsecureSkipVerify, RootCAs: i.staticCfg.TCPServersTransport.TLS.RootCAs, } if i.staticCfg.TCPServersTransport.TLS.Spiffe != nil { st.TLS.Spiffe = &dynamic.Spiffe{ IDs: i.staticCfg.ServersTransport.Spiffe.IDs, TrustDomain: i.staticCfg.ServersTransport.Spiffe.TrustDomain, } } } cfg.TCP.ServersTransports["default"] = st }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/docker/shared_test.go
pkg/provider/docker/shared_test.go
package docker import ( "strconv" "testing" containertypes "github.com/docker/docker/api/types/container" networktypes "github.com/docker/docker/api/types/network" swarmtypes "github.com/docker/docker/api/types/swarm" "github.com/docker/go-connections/nat" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func Test_getPort_docker(t *testing.T) { testCases := []struct { desc string container containertypes.InspectResponse serverPort string expected string }{ { desc: "no binding, no server port label", container: containerJSON(name("foo")), expected: "", }, { desc: "binding, no server port label", container: containerJSON(ports(nat.PortMap{ "80/tcp": {}, })), expected: "80", }, { desc: "binding, multiple ports, no server port label", container: containerJSON(ports(nat.PortMap{ "80/tcp": {}, "443/tcp": {}, })), expected: "80", }, { desc: "no binding, server port label", container: containerJSON(), serverPort: "8080", expected: "8080", }, { desc: "binding, server port label", container: containerJSON( ports(nat.PortMap{ "80/tcp": {}, })), serverPort: "8080", expected: "8080", }, { desc: "binding, multiple ports, server port label", container: containerJSON(ports(nat.PortMap{ "8080/tcp": {}, "80/tcp": {}, })), serverPort: "8080", expected: "8080", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() dData := parseContainer(test.container) actual := getPort(dData, test.serverPort) assert.Equal(t, test.expected, actual) }) } } func Test_getPort_swarm(t *testing.T) { testCases := []struct { service swarmtypes.Service serverPort string networks map[string]*networktypes.Summary expected string }{ { service: swarmService( withEndpointSpec(modeDNSRR), ), networks: map[string]*networktypes.Summary{}, serverPort: "8080", expected: "8080", }, } for serviceID, test := range testCases { t.Run(strconv.Itoa(serviceID), func(t *testing.T) { t.Parallel() var p SwarmProvider require.NoError(t, p.Init()) dData, err := p.parseService(t.Context(), test.service, test.networks) require.NoError(t, err) actual := getPort(dData, test.serverPort) assert.Equal(t, test.expected, actual) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/docker/data.go
pkg/provider/docker/data.go
package docker import ( containertypes "github.com/docker/docker/api/types/container" "github.com/docker/go-connections/nat" ) // dockerData holds the need data to the provider. type dockerData struct { ID string ServiceName string Name string Status string Labels map[string]string // List of labels set to container or service NetworkSettings networkSettings Health string NodeIP string // Only filled in Swarm mode. ExtraConf configuration } // NetworkSettings holds the networks data to the provider. type networkSettings struct { NetworkMode containertypes.NetworkMode Ports nat.PortMap Networks map[string]*networkData } // networkData holds the network data to the provider. type networkData struct { Name string Addr string Port int Protocol string ID string }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/docker/pswarm.go
pkg/provider/docker/pswarm.go
package docker import ( "context" "fmt" "net" "strconv" "time" "github.com/cenkalti/backoff/v4" "github.com/docker/docker/api/types/filters" networktypes "github.com/docker/docker/api/types/network" swarmtypes "github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/versions" "github.com/docker/docker/client" "github.com/rs/zerolog/log" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/job" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/provider" "github.com/traefik/traefik/v3/pkg/safe" ) const swarmName = "swarm" var _ provider.Provider = (*SwarmProvider)(nil) // SwarmProvider holds configurations of the provider. type SwarmProvider struct { Shared `yaml:",inline" export:"true"` ClientConfig `yaml:",inline" export:"true"` RefreshSeconds ptypes.Duration `description:"Polling interval for swarm mode." json:"refreshSeconds,omitempty" toml:"refreshSeconds,omitempty" yaml:"refreshSeconds,omitempty" export:"true"` } // SetDefaults sets the default values. func (p *SwarmProvider) SetDefaults() { p.Watch = true p.ExposedByDefault = true p.Endpoint = "unix:///var/run/docker.sock" p.RefreshSeconds = ptypes.Duration(15 * time.Second) p.DefaultRule = DefaultTemplateRule } // Init the provider. func (p *SwarmProvider) Init() error { defaultRuleTpl, err := provider.MakeDefaultRuleTemplate(p.DefaultRule, nil) if err != nil { return fmt.Errorf("error while parsing default rule: %w", err) } p.defaultRuleTpl = defaultRuleTpl return nil } func (p *SwarmProvider) createClient(ctx context.Context) (*client.Client, error) { return createClient(ctx, p.ClientConfig) } // Provide allows the docker provider to provide configurations to traefik using the given configuration channel. func (p *SwarmProvider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error { pool.GoCtx(func(routineCtx context.Context) { logger := log.Ctx(routineCtx).With().Str(logs.ProviderName, swarmName).Logger() ctxLog := logger.WithContext(routineCtx) operation := func() error { var err error ctx, cancel := context.WithCancel(ctxLog) defer cancel() ctx = log.Ctx(ctx).With().Str(logs.ProviderName, swarmName).Logger().WithContext(ctx) dockerClient, err := p.createClient(ctx) if err != nil { logger.Error().Err(err).Msg("Failed to create Docker API client") return err } defer func() { _ = dockerClient.Close() }() builder := NewDynConfBuilder(p.Shared, dockerClient, true) serverVersion, err := dockerClient.ServerVersion(ctx) if err != nil { logger.Error().Err(err).Msg("Failed to retrieve information of the docker client and server host") return err } logger.Debug().Msgf("Provider connection established with docker %s (API %s)", serverVersion.Version, serverVersion.APIVersion) dockerDataList, err := p.listServices(ctx, dockerClient) if err != nil { logger.Error().Err(err).Msg("Failed to list services for docker swarm mode") return err } configuration := builder.build(ctxLog, dockerDataList) configurationChan <- dynamic.Message{ ProviderName: swarmName, Configuration: configuration, } if p.Watch { errChan := make(chan error) // TODO: This need to be change. Linked to Swarm events docker/docker#23827 ticker := time.NewTicker(time.Duration(p.RefreshSeconds)) pool.GoCtx(func(ctx context.Context) { logger := log.Ctx(ctx).With().Str(logs.ProviderName, swarmName).Logger() ctx = logger.WithContext(ctx) defer close(errChan) for { select { case <-ticker.C: services, err := p.listServices(ctx, dockerClient) if err != nil { logger.Error().Err(err).Msg("Failed to list services for docker swarm mode") errChan <- err return } configuration := builder.build(ctx, services) if configuration != nil { configurationChan <- dynamic.Message{ ProviderName: swarmName, Configuration: configuration, } } case <-ctx.Done(): ticker.Stop() return } } }) if err, ok := <-errChan; ok { return err } // channel closed } return nil } notify := func(err error, time time.Duration) { logger.Error().Err(err).Msgf("Provider error, retrying in %s", time) } err := backoff.RetryNotify(safe.OperationWithRecover(operation), backoff.WithContext(job.NewBackOff(backoff.NewExponentialBackOff()), ctxLog), notify) if err != nil { logger.Error().Err(err).Msg("Cannot retrieve data") } }) return nil } func (p *SwarmProvider) listServices(ctx context.Context, dockerClient client.APIClient) ([]dockerData, error) { logger := log.Ctx(ctx) serviceList, err := dockerClient.ServiceList(ctx, swarmtypes.ServiceListOptions{}) if err != nil { return nil, err } serverVersion, err := dockerClient.ServerVersion(ctx) if err != nil { return nil, err } networkListArgs := filters.NewArgs() // https://docs.docker.com/engine/api/v1.29/#tag/Network (Docker 17.06) if versions.GreaterThanOrEqualTo(serverVersion.APIVersion, "1.29") { networkListArgs.Add("scope", "swarm") } else { networkListArgs.Add("driver", "overlay") } networkList, err := dockerClient.NetworkList(ctx, networktypes.ListOptions{Filters: networkListArgs}) if err != nil { logger.Debug().Err(err).Msg("Failed to network inspect on client for docker") return nil, err } networkMap := make(map[string]*networktypes.Summary) for _, network := range networkList { networkMap[network.ID] = &network } var dockerDataList []dockerData var dockerDataListTasks []dockerData for _, service := range serviceList { dData, err := p.parseService(ctx, service, networkMap) if err != nil { logger.Error().Err(err).Msgf("Skip container %s", getServiceName(dData)) continue } if dData.ExtraConf.LBSwarm { if len(dData.NetworkSettings.Networks) > 0 { dockerDataList = append(dockerDataList, dData) } } else { isGlobalSvc := service.Spec.Mode.Global != nil dockerDataListTasks, err = listTasks(ctx, dockerClient, service.ID, dData, networkMap, isGlobalSvc) if err != nil { logger.Warn().Err(err).Send() } else { dockerDataList = append(dockerDataList, dockerDataListTasks...) } } } return dockerDataList, err } func (p *SwarmProvider) parseService(ctx context.Context, service swarmtypes.Service, networkMap map[string]*networktypes.Summary) (dockerData, error) { logger := log.Ctx(ctx) dData := dockerData{ ID: service.ID, ServiceName: service.Spec.Annotations.Name, Name: service.Spec.Annotations.Name, Labels: service.Spec.Annotations.Labels, NetworkSettings: networkSettings{}, } extraConf, err := p.extractSwarmLabels(dData) if err != nil { return dockerData{}, err } dData.ExtraConf = extraConf if service.Spec.EndpointSpec == nil { return dData, nil } if service.Spec.EndpointSpec.Mode == swarmtypes.ResolutionModeDNSRR { if dData.ExtraConf.LBSwarm { logger.Warn().Msgf("Ignored %s endpoint-mode not supported, service name: %s. Fallback to Traefik load balancing", swarmtypes.ResolutionModeDNSRR, service.Spec.Annotations.Name) } } else if service.Spec.EndpointSpec.Mode == swarmtypes.ResolutionModeVIP { dData.NetworkSettings.Networks = make(map[string]*networkData) for _, virtualIP := range service.Endpoint.VirtualIPs { networkService := networkMap[virtualIP.NetworkID] if networkService == nil { logger.Debug().Msgf("Network not found, id: %s", virtualIP.NetworkID) continue } if len(virtualIP.Addr) == 0 { logger.Debug().Msgf("No virtual IPs found in network %s", virtualIP.NetworkID) continue } ip, _, _ := net.ParseCIDR(virtualIP.Addr) network := &networkData{ Name: networkService.Name, ID: virtualIP.NetworkID, Addr: ip.String(), } dData.NetworkSettings.Networks[network.Name] = network } } return dData, nil } func listTasks(ctx context.Context, dockerClient client.APIClient, serviceID string, serviceDockerData dockerData, networkMap map[string]*networktypes.Summary, isGlobalSvc bool, ) ([]dockerData, error) { serviceIDFilter := filters.NewArgs() serviceIDFilter.Add("service", serviceID) serviceIDFilter.Add("desired-state", "running") taskList, err := dockerClient.TaskList(ctx, swarmtypes.TaskListOptions{Filters: serviceIDFilter}) if err != nil { return nil, err } var dockerDataList []dockerData for _, task := range taskList { if task.Status.State != swarmtypes.TaskStateRunning { continue } dData, err := parseTasks(ctx, dockerClient, task, serviceDockerData, networkMap, isGlobalSvc) if err != nil { log.Ctx(ctx).Warn().Err(err).Msgf("Error while parsing task %s", getServiceName(dData)) continue } if len(dData.NetworkSettings.Networks) > 0 { dockerDataList = append(dockerDataList, dData) } } return dockerDataList, err } func parseTasks(ctx context.Context, dockerClient client.APIClient, task swarmtypes.Task, serviceDockerData dockerData, networkMap map[string]*networktypes.Summary, isGlobalSvc bool, ) (dockerData, error) { dData := dockerData{ ID: task.ID, ServiceName: serviceDockerData.Name, Name: serviceDockerData.Name + "." + strconv.Itoa(task.Slot), Labels: serviceDockerData.Labels, ExtraConf: serviceDockerData.ExtraConf, NetworkSettings: networkSettings{}, } if isGlobalSvc { dData.Name = serviceDockerData.Name + "." + task.ID } if task.NodeID != "" { node, _, err := dockerClient.NodeInspectWithRaw(ctx, task.NodeID) if err != nil { return dockerData{}, fmt.Errorf("inspecting node %s: %w", task.NodeID, err) } dData.NodeIP = node.Status.Addr } if task.NetworksAttachments != nil { dData.NetworkSettings.Networks = make(map[string]*networkData) for _, virtualIP := range task.NetworksAttachments { if networkService, present := networkMap[virtualIP.Network.ID]; present { if len(virtualIP.Addresses) > 0 { // Not sure about this next loop - when would a task have multiple IP's for the same network? for _, addr := range virtualIP.Addresses { ip, _, _ := net.ParseCIDR(addr) network := &networkData{ ID: virtualIP.Network.ID, Name: networkService.Name, Addr: ip.String(), } dData.NetworkSettings.Networks[network.Name] = network } } else { log.Ctx(ctx).Debug().Msgf("No IP addresses found for network %s", virtualIP.Network.ID) } } } } return dData, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/docker/pswarm_mock_test.go
pkg/provider/docker/pswarm_mock_test.go
package docker import ( "context" dockertypes "github.com/docker/docker/api/types" containertypes "github.com/docker/docker/api/types/container" networktypes "github.com/docker/docker/api/types/network" swarmtypes "github.com/docker/docker/api/types/swarm" dockerclient "github.com/docker/docker/client" ) type fakeTasksClient struct { dockerclient.APIClient tasks []swarmtypes.Task container containertypes.InspectResponse err error } func (c *fakeTasksClient) TaskList(ctx context.Context, options swarmtypes.TaskListOptions) ([]swarmtypes.Task, error) { return c.tasks, c.err } func (c *fakeTasksClient) ContainerInspect(ctx context.Context, container string) (containertypes.InspectResponse, error) { return c.container, c.err } type fakeServicesClient struct { dockerclient.APIClient dockerVersion string networks []networktypes.Summary nodes []swarmtypes.Node services []swarmtypes.Service tasks []swarmtypes.Task err error } func (c *fakeServicesClient) NodeInspectWithRaw(ctx context.Context, nodeID string) (swarmtypes.Node, []byte, error) { for _, node := range c.nodes { if node.ID == nodeID { return node, nil, nil } } return swarmtypes.Node{}, nil, c.err } func (c *fakeServicesClient) ServiceList(ctx context.Context, options swarmtypes.ServiceListOptions) ([]swarmtypes.Service, error) { return c.services, c.err } func (c *fakeServicesClient) ServerVersion(ctx context.Context) (dockertypes.Version, error) { return dockertypes.Version{APIVersion: c.dockerVersion}, c.err } func (c *fakeServicesClient) NetworkList(ctx context.Context, options networktypes.ListOptions) ([]networktypes.Summary, error) { return c.networks, c.err } func (c *fakeServicesClient) TaskList(ctx context.Context, options swarmtypes.TaskListOptions) ([]swarmtypes.Task, error) { return c.tasks, c.err }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/docker/config.go
pkg/provider/docker/config.go
package docker import ( "context" "errors" "fmt" "net" "strings" containertypes "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" "github.com/docker/go-connections/nat" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/label" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/provider" "github.com/traefik/traefik/v3/pkg/provider/constraints" ) type DynConfBuilder struct { Shared apiClient client.APIClient swarm bool } func NewDynConfBuilder(configuration Shared, apiClient client.APIClient, swarm bool) *DynConfBuilder { return &DynConfBuilder{Shared: configuration, apiClient: apiClient, swarm: swarm} } func (p *DynConfBuilder) build(ctx context.Context, containersInspected []dockerData) *dynamic.Configuration { configurations := make(map[string]*dynamic.Configuration) for _, container := range containersInspected { containerName := getServiceName(container) + "-" + container.ID logger := log.Ctx(ctx).With().Str("container", containerName).Logger() ctxContainer := logger.WithContext(ctx) if !p.keepContainer(ctxContainer, container) { continue } confFromLabel, err := label.DecodeConfiguration(container.Labels) if err != nil { logger.Error().Err(err).Send() continue } var tcpOrUDP bool if len(confFromLabel.TCP.Routers) > 0 || len(confFromLabel.TCP.Services) > 0 { tcpOrUDP = true err := p.buildTCPServiceConfiguration(ctxContainer, container, confFromLabel.TCP) if err != nil { logger.Error().Err(err).Send() continue } provider.BuildTCPRouterConfiguration(ctxContainer, confFromLabel.TCP) } if len(confFromLabel.UDP.Routers) > 0 || len(confFromLabel.UDP.Services) > 0 { tcpOrUDP = true err := p.buildUDPServiceConfiguration(ctxContainer, container, confFromLabel.UDP) if err != nil { logger.Error().Err(err).Send() continue } provider.BuildUDPRouterConfiguration(ctxContainer, confFromLabel.UDP) } if tcpOrUDP && len(confFromLabel.HTTP.Routers) == 0 && len(confFromLabel.HTTP.Middlewares) == 0 && len(confFromLabel.HTTP.Services) == 0 { configurations[containerName] = confFromLabel continue } err = p.buildServiceConfiguration(ctxContainer, container, confFromLabel.HTTP) if err != nil { logger.Error().Err(err).Send() continue } serviceName := getServiceName(container) model := struct { Name string ContainerName string Labels map[string]string }{ Name: serviceName, ContainerName: strings.TrimPrefix(container.Name, "/"), Labels: container.Labels, } provider.BuildRouterConfiguration(ctx, confFromLabel.HTTP, serviceName, p.defaultRuleTpl, model) configurations[containerName] = confFromLabel } return provider.Merge(ctx, configurations) } func (p *DynConfBuilder) buildTCPServiceConfiguration(ctx context.Context, container dockerData, configuration *dynamic.TCPConfiguration) error { serviceName := getServiceName(container) if len(configuration.Services) == 0 { configuration.Services = map[string]*dynamic.TCPService{ serviceName: { LoadBalancer: new(dynamic.TCPServersLoadBalancer), }, } } // Keep an empty server load-balancer for non-running containers. if container.Status != "" && container.Status != containertypes.StateRunning { return nil } // Keep an empty server load-balancer for unhealthy containers. if container.Health != "" && container.Health != containertypes.Healthy { return nil } for name, service := range configuration.Services { ctx := log.Ctx(ctx).With().Str(logs.ServiceName, name).Logger().WithContext(ctx) if err := p.addServerTCP(ctx, container, service.LoadBalancer); err != nil { return fmt.Errorf("service %q error: %w", name, err) } } return nil } func (p *DynConfBuilder) buildUDPServiceConfiguration(ctx context.Context, container dockerData, configuration *dynamic.UDPConfiguration) error { serviceName := getServiceName(container) if len(configuration.Services) == 0 { configuration.Services = make(map[string]*dynamic.UDPService) configuration.Services[serviceName] = &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{}, } } // Keep an empty server load-balancer for non-running containers. if container.Status != "" && container.Status != containertypes.StateRunning { return nil } // Keep an empty server load-balancer for unhealthy containers. if container.Health != "" && container.Health != containertypes.Healthy { return nil } for name, service := range configuration.Services { ctx := log.Ctx(ctx).With().Str(logs.ServiceName, name).Logger().WithContext(ctx) if err := p.addServerUDP(ctx, container, service.LoadBalancer); err != nil { return fmt.Errorf("service %q error: %w", name, err) } } return nil } func (p *DynConfBuilder) buildServiceConfiguration(ctx context.Context, container dockerData, configuration *dynamic.HTTPConfiguration) error { serviceName := getServiceName(container) if len(configuration.Services) == 0 { configuration.Services = make(map[string]*dynamic.Service) lb := &dynamic.ServersLoadBalancer{} lb.SetDefaults() configuration.Services[serviceName] = &dynamic.Service{ LoadBalancer: lb, } } // Keep an empty server load-balancer for non-running containers. if container.Status != "" && container.Status != containertypes.StateRunning { return nil } // Keep an empty server load-balancer for unhealthy containers. if container.Health != "" && container.Health != containertypes.Healthy { return nil } for name, service := range configuration.Services { ctx := log.Ctx(ctx).With().Str(logs.ServiceName, name).Logger().WithContext(ctx) if err := p.addServer(ctx, container, service.LoadBalancer); err != nil { return fmt.Errorf("service %q error: %w", name, err) } } return nil } func (p *DynConfBuilder) keepContainer(ctx context.Context, container dockerData) bool { logger := log.Ctx(ctx) if !container.ExtraConf.Enable { logger.Debug().Msg("Filtering disabled container") return false } matches, err := constraints.MatchLabels(container.Labels, p.Constraints) if err != nil { logger.Error().Err(err).Msg("Error matching constraints expression") return false } if !matches { logger.Debug().Msgf("Container pruned by constraint expression: %q", p.Constraints) return false } // AllowNonRunning has precedence over AllowEmptyServices. // If AllowNonRunning is true, we don't care about the container health/status, // and we need to quit before checking it. // Only configurable with the Docker provider. if container.ExtraConf.AllowNonRunning { return true } if container.Status != "" && container.Status != containertypes.StateRunning { logger.Debug().Msg("Filtering non running container") return false } if !p.AllowEmptyServices && container.Health != "" && container.Health != containertypes.Healthy { logger.Debug().Msg("Filtering unhealthy or starting container") return false } return true } func (p *DynConfBuilder) addServerTCP(ctx context.Context, container dockerData, loadBalancer *dynamic.TCPServersLoadBalancer) error { if loadBalancer == nil { return errors.New("load-balancer is not defined") } if len(loadBalancer.Servers) == 0 { loadBalancer.Servers = []dynamic.TCPServer{{}} } serverPort := loadBalancer.Servers[0].Port loadBalancer.Servers[0].Port = "" ip, port, err := p.getIPPort(ctx, container, serverPort) if err != nil { return err } if port == "" { return errors.New("port is missing") } loadBalancer.Servers[0].Address = net.JoinHostPort(ip, port) return nil } func (p *DynConfBuilder) addServerUDP(ctx context.Context, container dockerData, loadBalancer *dynamic.UDPServersLoadBalancer) error { if loadBalancer == nil { return errors.New("load-balancer is not defined") } if len(loadBalancer.Servers) == 0 { loadBalancer.Servers = []dynamic.UDPServer{{}} } serverPort := loadBalancer.Servers[0].Port loadBalancer.Servers[0].Port = "" ip, port, err := p.getIPPort(ctx, container, serverPort) if err != nil { return err } if port == "" { return errors.New("port is missing") } loadBalancer.Servers[0].Address = net.JoinHostPort(ip, port) return nil } func (p *DynConfBuilder) addServer(ctx context.Context, container dockerData, loadBalancer *dynamic.ServersLoadBalancer) error { if loadBalancer == nil { return errors.New("load-balancer is not defined") } if len(loadBalancer.Servers) == 0 { loadBalancer.Servers = []dynamic.Server{{}} } if loadBalancer.Servers[0].URL != "" { if loadBalancer.Servers[0].Scheme != "" || loadBalancer.Servers[0].Port != "" { return errors.New("defining scheme or port is not allowed when URL is defined") } return nil } serverPort := loadBalancer.Servers[0].Port loadBalancer.Servers[0].Port = "" ip, port, err := p.getIPPort(ctx, container, serverPort) if err != nil { return err } if port == "" { return errors.New("port is missing") } scheme := loadBalancer.Servers[0].Scheme loadBalancer.Servers[0].Scheme = "" if scheme == "" { scheme = "http" } loadBalancer.Servers[0].URL = fmt.Sprintf("%s://%s", scheme, net.JoinHostPort(ip, port)) return nil } func (p *DynConfBuilder) getIPPort(ctx context.Context, container dockerData, serverPort string) (string, string, error) { logger := log.Ctx(ctx) var ip, port string usedBound := false if p.UseBindPortIP { portBinding, err := p.getPortBinding(container, serverPort) switch { case err != nil: logger.Info().Msgf("Unable to find a binding for container %q, falling back on its internal IP/Port.", container.Name) case portBinding.HostIP == "0.0.0.0" || len(portBinding.HostIP) == 0: logger.Info().Msgf("Cannot determine the IP address (got %q) for %q's binding, falling back on its internal IP/Port.", portBinding.HostIP, container.Name) default: ip = portBinding.HostIP port = portBinding.HostPort usedBound = true } } if !usedBound { ip = p.getIPAddress(ctx, container) port = getPort(container, serverPort) } if len(ip) == 0 { return "", "", fmt.Errorf("unable to find the IP address for the container %q: the server is ignored", container.Name) } return ip, port, nil } func (p *DynConfBuilder) getIPAddress(ctx context.Context, container dockerData) string { logger := log.Ctx(ctx) netNotFound := false if container.ExtraConf.Network != "" { settings := container.NetworkSettings if settings.Networks != nil { network := settings.Networks[container.ExtraConf.Network] if network != nil { return network.Addr } netNotFound = true } } if container.NetworkSettings.NetworkMode.IsHost() { if container.NodeIP != "" { return container.NodeIP } if host, err := net.LookupHost("host.docker.internal"); err == nil { return host[0] } if host, err := net.LookupHost("host.containers.internal"); err == nil { return host[0] } return "127.0.0.1" } if container.NetworkSettings.NetworkMode.IsContainer() { connectedContainer := container.NetworkSettings.NetworkMode.ConnectedContainer() containerInspected, err := p.apiClient.ContainerInspect(context.Background(), connectedContainer) if err != nil { logger.Warn().Err(err).Msgf("Unable to get IP address for container %s: failed to inspect container ID %s", container.Name, connectedContainer) return "" } // Check connected container for traefik.docker.network, // falling back to the network specified on the current container. containerParsed := parseContainer(containerInspected) extraConf, err := p.extractLabels(containerParsed) if err != nil { logger.Warn().Err(err).Msgf("Unable to get IP address for container %s: failed to get extra configuration for container %s", container.Name, containerInspected.Name) return "" } if extraConf.Network == "" { extraConf.Network = container.ExtraConf.Network } containerParsed.ExtraConf = extraConf return p.getIPAddress(ctx, containerParsed) } if netNotFound { logger.Warn().Msgf("Could not find network named %q for container %q. Maybe you're missing the project's prefix in the label?", container.ExtraConf.Network, container.Name) } for _, network := range container.NetworkSettings.Networks { if netNotFound { logger.Warn().Msgf("Defaulting to first available network (%q) for container %q.", network, container.Name) } return network.Addr } logger.Warn().Msg("Unable to find the IP address.") return "" } func (p *DynConfBuilder) getPortBinding(container dockerData, serverPort string) (*nat.PortBinding, error) { port := getPort(container, serverPort) for netPort, portBindings := range container.NetworkSettings.Ports { if strings.EqualFold(string(netPort), port+"/TCP") || strings.EqualFold(string(netPort), port+"/UDP") { for _, p := range portBindings { return &p, nil } } } return nil, fmt.Errorf("unable to find the external IP:Port for the container %q", container.Name) } func (p *DynConfBuilder) extractLabels(container dockerData) (configuration, error) { if p.swarm { return p.Shared.extractSwarmLabels(container) } return p.Shared.extractDockerLabels(container) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/docker/shared_labels.go
pkg/provider/docker/shared_labels.go
package docker import ( "errors" "fmt" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/label" ) const ( labelDockerComposeProject = "com.docker.compose.project" labelDockerComposeService = "com.docker.compose.service" ) // configuration contains information from the labels that are globals (not related to the dynamic configuration) // or specific to the provider. type configuration struct { Enable bool Network string LBSwarm bool AllowNonRunning bool } type labelConfiguration struct { Enable bool Docker *dockerSpecificConfiguration Swarm *specificConfiguration } type dockerSpecificConfiguration struct { Network *string LBSwarm bool AllowNonRunning bool } type specificConfiguration struct { Network *string LBSwarm bool } func (p *Shared) extractDockerLabels(container dockerData) (configuration, error) { conf := labelConfiguration{Enable: p.ExposedByDefault} if err := label.Decode(container.Labels, &conf, "traefik.docker.", "traefik.enable"); err != nil { return configuration{}, fmt.Errorf("decoding Docker labels: %w", err) } network := p.Network if conf.Docker != nil && conf.Docker.Network != nil { network = *conf.Docker.Network } var allowNonRunning bool if conf.Docker != nil { allowNonRunning = conf.Docker.AllowNonRunning } return configuration{ Enable: conf.Enable, Network: network, AllowNonRunning: allowNonRunning, }, nil } func (p *Shared) extractSwarmLabels(container dockerData) (configuration, error) { labelConf := labelConfiguration{Enable: p.ExposedByDefault} if err := label.Decode(container.Labels, &labelConf, "traefik.enable", "traefik.docker.", "traefik.swarm."); err != nil { return configuration{}, fmt.Errorf("decoding Swarm labels: %w", err) } if labelConf.Docker != nil && labelConf.Swarm != nil { return configuration{}, errors.New("both Docker and Swarm labels are defined") } conf := configuration{ Enable: labelConf.Enable, Network: p.Network, } if labelConf.Docker != nil { log.Warn().Msg("Labels traefik.docker.* for Swarm provider are deprecated. Please use traefik.swarm.* labels instead") conf.LBSwarm = labelConf.Docker.LBSwarm if labelConf.Docker.Network != nil { conf.Network = *labelConf.Docker.Network } } if labelConf.Swarm != nil { conf.LBSwarm = labelConf.Swarm.LBSwarm if labelConf.Swarm.Network != nil { conf.Network = *labelConf.Swarm.Network } } return conf, nil } // getStringMultipleStrict get multiple string values associated to several labels. // Fail if one label is missing. func getStringMultipleStrict(labels map[string]string, labelNames ...string) (map[string]string, error) { foundLabels := map[string]string{} for _, name := range labelNames { value := getStringValue(labels, name, "") // Error out only if one of them is not defined. if len(value) == 0 { return nil, fmt.Errorf("label not found: %s", name) } foundLabels[name] = value } return foundLabels, nil } // getStringValue get string value associated to a label. func getStringValue(labels map[string]string, labelName, defaultValue string) string { if value, ok := labels[labelName]; ok && len(value) > 0 { return value } return defaultValue }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/docker/shared.go
pkg/provider/docker/shared.go
package docker import ( "context" "encoding/base64" "fmt" "net/http" "text/template" "time" "github.com/docker/cli/cli/connhelper" containertypes "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" "github.com/docker/go-connections/nat" "github.com/docker/go-connections/sockets" "github.com/rs/zerolog/log" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/provider" "github.com/traefik/traefik/v3/pkg/types" "github.com/traefik/traefik/v3/pkg/version" ) // DefaultTemplateRule The default template for the default rule. const DefaultTemplateRule = "Host(`{{ normalize .Name }}`)" type Shared struct { ExposedByDefault bool `description:"Expose containers by default." json:"exposedByDefault,omitempty" toml:"exposedByDefault,omitempty" yaml:"exposedByDefault,omitempty" export:"true"` Constraints string `description:"Constraints is an expression that Traefik matches against the container's labels to determine whether to create any route for that container." json:"constraints,omitempty" toml:"constraints,omitempty" yaml:"constraints,omitempty" export:"true"` AllowEmptyServices bool `description:"Disregards the Docker containers health checks with respect to the creation or removal of the corresponding services." json:"allowEmptyServices,omitempty" toml:"allowEmptyServices,omitempty" yaml:"allowEmptyServices,omitempty" export:"true"` Network string `description:"Default Docker network used." json:"network,omitempty" toml:"network,omitempty" yaml:"network,omitempty" export:"true"` UseBindPortIP bool `description:"Use the ip address from the bound port, rather than from the inner network." json:"useBindPortIP,omitempty" toml:"useBindPortIP,omitempty" yaml:"useBindPortIP,omitempty" export:"true"` Watch bool `description:"Watch Docker events." json:"watch,omitempty" toml:"watch,omitempty" yaml:"watch,omitempty" export:"true"` DefaultRule string `description:"Default rule." json:"defaultRule,omitempty" toml:"defaultRule,omitempty" yaml:"defaultRule,omitempty"` defaultRuleTpl *template.Template } func inspectContainers(ctx context.Context, dockerClient client.ContainerAPIClient, containerID string) dockerData { containerInspected, err := dockerClient.ContainerInspect(ctx, containerID) if err != nil { log.Ctx(ctx).Warn().Err(err).Msgf("Failed to inspect container %s", containerID) return dockerData{} } // Always parse all containers (running and stopped) // The allowNonRunning filtering will be applied later in service configuration if containerInspected.ContainerJSONBase != nil && containerInspected.ContainerJSONBase.State != nil { return parseContainer(containerInspected) } return dockerData{} } func parseContainer(container containertypes.InspectResponse) dockerData { dData := dockerData{ NetworkSettings: networkSettings{}, } if container.ContainerJSONBase != nil { dData.ID = container.ContainerJSONBase.ID dData.Name = container.ContainerJSONBase.Name dData.ServiceName = dData.Name // Default ServiceName to be the container's Name. dData.Status = container.ContainerJSONBase.State.Status if container.ContainerJSONBase.HostConfig != nil { dData.NetworkSettings.NetworkMode = container.ContainerJSONBase.HostConfig.NetworkMode } if container.State != nil && container.State.Health != nil { dData.Health = container.State.Health.Status } } if container.Config != nil && container.Config.Labels != nil { dData.Labels = container.Config.Labels } if container.NetworkSettings != nil { if container.NetworkSettings.Ports != nil { dData.NetworkSettings.Ports = container.NetworkSettings.Ports } if container.NetworkSettings.Networks != nil { dData.NetworkSettings.Networks = make(map[string]*networkData) for name, containerNetwork := range container.NetworkSettings.Networks { addr := containerNetwork.IPAddress if addr == "" { addr = containerNetwork.GlobalIPv6Address } dData.NetworkSettings.Networks[name] = &networkData{ ID: containerNetwork.NetworkID, Name: name, Addr: addr, } } } } return dData } type ClientConfig struct { Username string `description:"Username for Basic HTTP authentication." json:"username,omitempty" toml:"username,omitempty" yaml:"username,omitempty"` Password string `description:"Password for Basic HTTP authentication." json:"password,omitempty" toml:"password,omitempty" yaml:"password,omitempty"` Endpoint string `description:"Docker server endpoint. Can be a TCP or a Unix socket endpoint." json:"endpoint,omitempty" toml:"endpoint,omitempty" yaml:"endpoint,omitempty"` TLS *types.ClientTLS `description:"Enable Docker TLS support." json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" export:"true"` HTTPClientTimeout ptypes.Duration `description:"Client timeout for HTTP connections." json:"httpClientTimeout,omitempty" toml:"httpClientTimeout,omitempty" yaml:"httpClientTimeout,omitempty" export:"true"` } func createClient(ctx context.Context, cfg ClientConfig) (*client.Client, error) { opts, err := getClientOpts(ctx, cfg) if err != nil { return nil, err } httpHeaders := map[string]string{ "User-Agent": "Traefik " + version.Version, } if cfg.Username != "" && cfg.Password != "" { httpHeaders["Authorization"] = "Basic " + base64.StdEncoding.EncodeToString([]byte(cfg.Username+":"+cfg.Password)) } opts = append(opts, client.FromEnv, client.WithAPIVersionNegotiation(), client.WithHTTPHeaders(httpHeaders)) return client.NewClientWithOpts(opts...) } func getClientOpts(ctx context.Context, cfg ClientConfig) ([]client.Opt, error) { helper, err := connhelper.GetConnectionHelper(cfg.Endpoint) if err != nil { return nil, err } // SSH if helper != nil { // https://github.com/docker/cli/blob/ebca1413117a3fcb81c89d6be226dcec74e5289f/cli/context/docker/load.go#L112-L123 httpClient := &http.Client{ Transport: &http.Transport{ DialContext: helper.Dialer, }, } return []client.Opt{ client.WithHTTPClient(httpClient), client.WithTimeout(time.Duration(cfg.HTTPClientTimeout)), client.WithHost(helper.Host), // To avoid 400 Bad Request: malformed Host header daemon error client.WithDialContext(helper.Dialer), }, nil } opts := []client.Opt{ client.WithHost(cfg.Endpoint), client.WithTimeout(time.Duration(cfg.HTTPClientTimeout)), } if cfg.TLS != nil { conf, err := cfg.TLS.CreateTLSConfig(ctx) if err != nil { return nil, fmt.Errorf("unable to create client TLS configuration: %w", err) } hostURL, err := client.ParseHostURL(cfg.Endpoint) if err != nil { return nil, err } tr := &http.Transport{ TLSClientConfig: conf, } if err := sockets.ConfigureTransport(tr, hostURL.Scheme, hostURL.Host); err != nil { return nil, err } opts = append(opts, client.WithHTTPClient(&http.Client{Transport: tr, Timeout: time.Duration(cfg.HTTPClientTimeout)})) } return opts, nil } func getPort(container dockerData, serverPort string) string { if len(serverPort) > 0 { return serverPort } var ports []nat.Port for port := range container.NetworkSettings.Ports { ports = append(ports, port) } less := func(i, j nat.Port) bool { return i.Int() < j.Int() } nat.Sort(ports, less) if len(ports) > 0 { return ports[0].Port() } return "" } func getServiceName(container dockerData) string { serviceName := container.ServiceName if values, err := getStringMultipleStrict(container.Labels, labelDockerComposeProject, labelDockerComposeService); err == nil { serviceName = values[labelDockerComposeService] + "_" + values[labelDockerComposeProject] } return provider.Normalize(serviceName) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/docker/config_test.go
pkg/provider/docker/config_test.go
package docker import ( "strconv" "testing" "time" containertypes "github.com/docker/docker/api/types/container" networktypes "github.com/docker/docker/api/types/network" swarmtypes "github.com/docker/docker/api/types/swarm" "github.com/docker/go-connections/nat" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/provider" "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" ) func TestDynConfBuilder_DefaultRule(t *testing.T) { testCases := []struct { desc string containers []dockerData defaultRule string expected *dynamic.Configuration }{ { desc: "default rule with no variable", containers: []dockerData{ { ServiceName: "Test", Name: "Test", Labels: map[string]string{}, NetworkSettings: networkSettings{ Ports: nat.PortMap{ nat.Port("80/tcp"): []nat.PortBinding{}, }, Networks: map[string]*networkData{ "bridge": { Name: "bridge", Addr: "127.0.0.1", }, }, }, }, }, defaultRule: "Host(`foo.bar`)", expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Test": { Service: "Test", Rule: "Host(`foo.bar`)", DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "default rule with service name", containers: []dockerData{ { ServiceName: "Test", Name: "Test", Labels: map[string]string{}, NetworkSettings: networkSettings{ Ports: nat.PortMap{ nat.Port("80/tcp"): []nat.PortBinding{}, }, Networks: map[string]*networkData{ "bridge": { Name: "bridge", Addr: "127.0.0.1", }, }, }, }, }, defaultRule: "Host(`{{ .Name }}.foo.bar`)", expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Test": { Service: "Test", Rule: "Host(`Test.foo.bar`)", DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "default rule with label", containers: []dockerData{ { ServiceName: "Test", Name: "Test", Labels: map[string]string{ "traefik.domain": "foo.bar", }, NetworkSettings: networkSettings{ Ports: nat.PortMap{ nat.Port("80/tcp"): []nat.PortBinding{}, }, Networks: map[string]*networkData{ "bridge": { Name: "bridge", Addr: "127.0.0.1", }, }, }, }, }, defaultRule: `Host("{{ .Name }}.{{ index .Labels "traefik.domain" }}")`, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Test": { Service: "Test", Rule: `Host("Test.foo.bar")`, DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "invalid rule", containers: []dockerData{ { ServiceName: "Test", Name: "Test", Labels: map[string]string{}, NetworkSettings: networkSettings{ Ports: nat.PortMap{ nat.Port("80/tcp"): []nat.PortBinding{}, }, Networks: map[string]*networkData{ "bridge": { Name: "bridge", Addr: "127.0.0.1", }, }, }, }, }, defaultRule: `Host("{{ .Toto }}")`, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "undefined rule", containers: []dockerData{ { ServiceName: "Test", Name: "Test", Labels: map[string]string{}, NetworkSettings: networkSettings{ Ports: nat.PortMap{ nat.Port("80/tcp"): []nat.PortBinding{}, }, Networks: map[string]*networkData{ "bridge": { Name: "bridge", Addr: "127.0.0.1", }, }, }, }, }, defaultRule: ``, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "default template rule", containers: []dockerData{ { ServiceName: "Test", Name: "Test", Labels: map[string]string{}, NetworkSettings: networkSettings{ Ports: nat.PortMap{ nat.Port("80/tcp"): []nat.PortBinding{}, }, Networks: map[string]*networkData{ "bridge": { Name: "bridge", Addr: "127.0.0.1", }, }, }, }, }, defaultRule: DefaultTemplateRule, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Test": { Service: "Test", Rule: "Host(`Test`)", DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() p := Provider{ Shared: Shared{ ExposedByDefault: true, DefaultRule: test.defaultRule, }, } require.NoError(t, p.Init()) builder := NewDynConfBuilder(p.Shared, nil, false) for i := range len(test.containers) { var err error test.containers[i].ExtraConf, err = builder.extractLabels(test.containers[i]) require.NoError(t, err) } configuration := builder.build(t.Context(), test.containers) assert.Equal(t, test.expected, configuration) }) } } func TestDynConfBuilder_build(t *testing.T) { testCases := []struct { desc string containers []dockerData useBindPortIP bool constraints string expected *dynamic.Configuration allowEmptyServices bool }{ { desc: "invalid HTTP service definition", containers: []dockerData{ { ServiceName: "Test", Name: "Test", Labels: map[string]string{ "traefik.http.services.test": "", }, NetworkSettings: networkSettings{ Ports: nat.PortMap{ nat.Port("80/tcp"): []nat.PortBinding{}, }, Networks: map[string]*networkData{ "bridge": { Name: "bridge", Addr: "127.0.0.1", }, }, }, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "invalid TCP service definition", containers: []dockerData{ { ServiceName: "Test", Name: "Test", Labels: map[string]string{ "traefik.tcp.services.test": "", }, NetworkSettings: networkSettings{ Ports: nat.PortMap{ nat.Port("80/tcp"): []nat.PortBinding{}, }, Networks: map[string]*networkData{ "bridge": { Name: "bridge", Addr: "127.0.0.1", }, }, }, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "invalid UDP service definition", containers: []dockerData{ { ServiceName: "Test", Name: "Test", Labels: map[string]string{ "traefik.udp.services.test": "", }, NetworkSettings: networkSettings{ Ports: nat.PortMap{ nat.Port("80/udp"): []nat.PortBinding{}, }, Networks: map[string]*networkData{ "bridge": { Name: "bridge", Addr: "127.0.0.1", }, }, }, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "one container no label", containers: []dockerData{ { ServiceName: "Test", Name: "Test", Labels: map[string]string{}, NetworkSettings: networkSettings{ Ports: nat.PortMap{ nat.Port("80/tcp"): []nat.PortBinding{}, }, Networks: map[string]*networkData{ "bridge": { Name: "bridge", Addr: "127.0.0.1", }, }, }, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Test": { Service: "Test", Rule: "Host(`Test.traefik.wtf`)", DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "two containers no label", containers: []dockerData{ { ServiceName: "Test", Name: "Test", Labels: map[string]string{}, NetworkSettings: networkSettings{ Ports: nat.PortMap{ nat.Port("80/tcp"): []nat.PortBinding{}, }, Networks: map[string]*networkData{ "bridge": { Name: "bridge", Addr: "127.0.0.1", }, }, }, }, { ServiceName: "Test2", Name: "Test2", Labels: map[string]string{}, NetworkSettings: networkSettings{ Ports: nat.PortMap{ nat.Port("80/tcp"): []nat.PortBinding{}, }, Networks: map[string]*networkData{ "bridge": { Name: "bridge", Addr: "127.0.0.2", }, }, }, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Test": { Service: "Test", Rule: "Host(`Test.traefik.wtf`)", DefaultRule: true, }, "Test2": { Service: "Test2", Rule: "Host(`Test2.traefik.wtf`)", DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, "Test2": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.2:80", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "two containers with same service name no label", containers: []dockerData{ { ID: "1", ServiceName: "Test", Name: "Test", Labels: map[string]string{}, NetworkSettings: networkSettings{ Ports: nat.PortMap{ nat.Port("80/tcp"): []nat.PortBinding{}, }, Networks: map[string]*networkData{ "bridge": { Name: "bridge", Addr: "127.0.0.1", }, }, }, }, { ID: "2", ServiceName: "Test", Name: "Test", Labels: map[string]string{}, NetworkSettings: networkSettings{ Ports: nat.PortMap{ nat.Port("80/tcp"): []nat.PortBinding{}, }, Networks: map[string]*networkData{ "bridge": { Name: "bridge", Addr: "127.0.0.2", }, }, }, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Test": { Service: "Test", Rule: "Host(`Test.traefik.wtf`)", DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", }, { URL: "http://127.0.0.2:80", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "one container with label (not on server)", containers: []dockerData{ { ServiceName: "Test", Name: "Test", Labels: map[string]string{ "traefik.http.services.Service1.loadbalancer.passhostheader": "true", }, NetworkSettings: networkSettings{ Ports: nat.PortMap{ nat.Port("80/tcp"): []nat.PortBinding{}, }, Networks: map[string]*networkData{ "bridge": { Name: "bridge", Addr: "127.0.0.1", }, }, }, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Test": { Service: "Service1", Rule: "Host(`Test.traefik.wtf`)", DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "one container with labels", containers: []dockerData{ { ServiceName: "Test", Name: "Test", Labels: map[string]string{ "traefik.http.services.Service1.loadbalancer.passhostheader": "true", "traefik.http.routers.Router1.rule": "Host(`foo.com`)", "traefik.http.routers.Router1.service": "Service1", }, NetworkSettings: networkSettings{ Ports: nat.PortMap{ nat.Port("80/tcp"): []nat.PortBinding{}, }, Networks: map[string]*networkData{ "bridge": { Name: "bridge", Addr: "127.0.0.1", }, }, }, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Router1": { Service: "Service1", Rule: "Host(`foo.com`)", }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "one container with rule label", containers: []dockerData{ { ServiceName: "Test", Name: "Test", Labels: map[string]string{ "traefik.http.routers.Router1.rule": "Host(`foo.com`)", }, NetworkSettings: networkSettings{ Ports: nat.PortMap{ nat.Port("80/tcp"): []nat.PortBinding{}, }, Networks: map[string]*networkData{ "bridge": { Name: "bridge", Addr: "127.0.0.1", }, }, }, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, Routers: map[string]*dynamic.Router{ "Router1": { Service: "Test", Rule: "Host(`foo.com`)", }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "one container with rule label and one service", containers: []dockerData{ { ServiceName: "Test", Name: "Test", Labels: map[string]string{ "traefik.http.routers.Router1.rule": "Host(`foo.com`)", "traefik.http.services.Service1.loadbalancer.passhostheader": "true", }, NetworkSettings: networkSettings{ Ports: nat.PortMap{ nat.Port("80/tcp"): []nat.PortBinding{}, }, Networks: map[string]*networkData{ "bridge": { Name: "bridge", Addr: "127.0.0.1", }, }, }, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Router1": { Service: "Service1", Rule: "Host(`foo.com`)", }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "one container with rule label and two services", containers: []dockerData{ { ServiceName: "Test", Name: "Test", Labels: map[string]string{ "traefik.http.routers.Router1.rule": "Host(`foo.com`)", "traefik.http.services.Service1.loadbalancer.passhostheader": "true", "traefik.http.services.Service2.loadbalancer.passhostheader": "true", }, NetworkSettings: networkSettings{ Ports: nat.PortMap{ nat.Port("80/tcp"): []nat.PortBinding{}, }, Networks: map[string]*networkData{ "bridge": { Name: "bridge", Addr: "127.0.0.1", }, }, }, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, "Service2": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ {
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/docker/pdocker.go
pkg/provider/docker/pdocker.go
package docker import ( "context" "errors" "fmt" "io" "strings" "time" "github.com/cenkalti/backoff/v4" "github.com/docker/docker/api/types/container" eventtypes "github.com/docker/docker/api/types/events" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/client" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/job" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/provider" "github.com/traefik/traefik/v3/pkg/safe" ) const dockerName = "docker" var _ provider.Provider = (*Provider)(nil) // Provider holds configurations of the provider. type Provider struct { Shared `yaml:",inline" export:"true"` ClientConfig `yaml:",inline" export:"true"` } // SetDefaults sets the default values. func (p *Provider) SetDefaults() { p.Watch = true p.ExposedByDefault = true p.Endpoint = "unix:///var/run/docker.sock" p.DefaultRule = DefaultTemplateRule } // Init the provider. func (p *Provider) Init() error { defaultRuleTpl, err := provider.MakeDefaultRuleTemplate(p.DefaultRule, nil) if err != nil { return fmt.Errorf("error while parsing default rule: %w", err) } p.defaultRuleTpl = defaultRuleTpl return nil } func (p *Provider) createClient(ctx context.Context) (*client.Client, error) { return createClient(ctx, p.ClientConfig) } // Provide allows the docker provider to provide configurations to traefik using the given configuration channel. func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error { pool.GoCtx(func(routineCtx context.Context) { logger := log.Ctx(routineCtx).With().Str(logs.ProviderName, dockerName).Logger() ctxLog := logger.WithContext(routineCtx) operation := func() error { var err error ctx, cancel := context.WithCancel(ctxLog) defer cancel() ctx = log.Ctx(ctx).With().Str(logs.ProviderName, dockerName).Logger().WithContext(ctx) dockerClient, err := p.createClient(ctxLog) if err != nil { logger.Error().Err(err).Msg("Failed to create Docker API client") return err } defer func() { _ = dockerClient.Close() }() builder := NewDynConfBuilder(p.Shared, dockerClient, false) serverVersion, err := dockerClient.ServerVersion(ctx) if err != nil { logger.Error().Err(err).Msg("Failed to retrieve information of the docker client and server host") return err } logger.Debug().Msgf("Provider connection established with docker %s (API %s)", serverVersion.Version, serverVersion.APIVersion) dockerDataList, err := p.listContainers(ctx, dockerClient) if err != nil { logger.Error().Err(err).Msg("Failed to list containers for docker") return err } configuration := builder.build(ctxLog, dockerDataList) configurationChan <- dynamic.Message{ ProviderName: dockerName, Configuration: configuration, } if p.Watch { f := filters.NewArgs() f.Add("type", "container") options := eventtypes.ListOptions{ Filters: f, } startStopHandle := func(m eventtypes.Message) { logger.Debug().Msgf("Provider event received %+v", m) containers, err := p.listContainers(ctx, dockerClient) if err != nil { logger.Error().Err(err).Msg("Failed to list containers for docker") // Call cancel to get out of the monitor return } configuration := builder.build(ctx, containers) if configuration != nil { message := dynamic.Message{ ProviderName: dockerName, Configuration: configuration, } select { case configurationChan <- message: case <-ctx.Done(): } } } eventsc, errc := dockerClient.Events(ctx, options) for { select { case event := <-eventsc: if event.Action == "start" || event.Action == "die" || strings.HasPrefix(string(event.Action), "health_status") { startStopHandle(event) } case err := <-errc: if errors.Is(err, io.EOF) { logger.Debug().Msg("Provider event stream closed") } return err case <-ctx.Done(): return nil } } } return nil } notify := func(err error, time time.Duration) { logger.Error().Err(err).Msgf("Provider error, retrying in %s", time) } err := backoff.RetryNotify(safe.OperationWithRecover(operation), backoff.WithContext(job.NewBackOff(backoff.NewExponentialBackOff()), ctxLog), notify) if err != nil { logger.Error().Err(err).Msg("Cannot retrieve data") } }) return nil } func (p *Provider) listContainers(ctx context.Context, dockerClient client.ContainerAPIClient) ([]dockerData, error) { containerList, err := dockerClient.ContainerList(ctx, container.ListOptions{ All: true, }) if err != nil { return nil, err } var inspectedContainers []dockerData // get inspect containers for _, c := range containerList { dData := inspectContainers(ctx, dockerClient, c.ID) if len(dData.Name) == 0 { continue } extraConf, err := p.extractDockerLabels(dData) if err != nil { log.Ctx(ctx).Error().Err(err).Msgf("Skip container %s", getServiceName(dData)) continue } dData.ExtraConf = extraConf inspectedContainers = append(inspectedContainers, dData) } return inspectedContainers, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/docker/pswarm_test.go
pkg/provider/docker/pswarm_test.go
package docker import ( "strconv" "testing" "time" networktypes "github.com/docker/docker/api/types/network" swarmtypes "github.com/docker/docker/api/types/swarm" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestListTasks(t *testing.T) { testCases := []struct { service swarmtypes.Service tasks []swarmtypes.Task isGlobalSVC bool expectedTasks []string networks map[string]*networktypes.Summary }{ { service: swarmService(serviceName("container")), tasks: []swarmtypes.Task{ swarmTask("id1", taskSlot(1), taskNetworkAttachment("1", "network1", "overlay", []string{"127.0.0.1"}), taskStatus(taskState(swarmtypes.TaskStateRunning)), ), swarmTask("id2", taskSlot(2), taskNetworkAttachment("1", "network1", "overlay", []string{"127.0.0.2"}), taskStatus(taskState(swarmtypes.TaskStatePending)), ), swarmTask("id3", taskSlot(3), taskNetworkAttachment("1", "network1", "overlay", []string{"127.0.0.3"}), ), swarmTask("id4", taskSlot(4), taskNetworkAttachment("1", "network1", "overlay", []string{"127.0.0.4"}), taskStatus(taskState(swarmtypes.TaskStateRunning)), ), swarmTask("id5", taskSlot(5), taskNetworkAttachment("1", "network1", "overlay", []string{"127.0.0.5"}), taskStatus(taskState(swarmtypes.TaskStateFailed)), ), }, isGlobalSVC: false, expectedTasks: []string{ "container.1", "container.4", }, networks: map[string]*networktypes.Summary{ "1": { Name: "foo", }, }, }, } for caseID, test := range testCases { t.Run(strconv.Itoa(caseID), func(t *testing.T) { t.Parallel() var p SwarmProvider require.NoError(t, p.Init()) dockerData, err := p.parseService(t.Context(), test.service, test.networks) require.NoError(t, err) dockerClient := &fakeTasksClient{tasks: test.tasks} taskDockerData, _ := listTasks(t.Context(), dockerClient, test.service.ID, dockerData, test.networks, test.isGlobalSVC) if len(test.expectedTasks) != len(taskDockerData) { t.Errorf("expected tasks %v, got %v", test.expectedTasks, taskDockerData) } for i, taskID := range test.expectedTasks { if taskDockerData[i].Name != taskID { t.Errorf("expect task id %v, got %v", taskID, taskDockerData[i].Name) } } }) } } func TestSwarmProvider_listServices(t *testing.T) { testCases := []struct { desc string services []swarmtypes.Service tasks []swarmtypes.Task dockerVersion string networks []networktypes.Summary expectedServices []string }{ { desc: "Should return no service due to no networks defined", services: []swarmtypes.Service{ swarmService( serviceName("service1"), serviceLabels(map[string]string{ "traefik.swarm.network": "barnet", "traefik.swarm.LBSwarm": "true", }), withEndpointSpec(modeVIP), withEndpoint( virtualIP("1", "10.11.12.13/24"), virtualIP("2", "10.11.12.99/24"), )), swarmService( serviceName("service2"), serviceLabels(map[string]string{ "traefik.swarm.network": "barnet", "traefik.swarm.LBSwarm": "true", }), withEndpointSpec(modeDNSRR)), }, dockerVersion: "1.30", networks: []networktypes.Summary{}, expectedServices: []string{}, }, { desc: "Should return only service1", services: []swarmtypes.Service{ swarmService( serviceName("service1"), serviceLabels(map[string]string{ "traefik.swarm.network": "barnet", "traefik.swarm.LBSwarm": "true", }), withEndpointSpec(modeVIP), withEndpoint( virtualIP("yk6l57rfwizjzxxzftn4amaot", "10.11.12.13/24"), virtualIP("2", "10.11.12.99/24"), )), swarmService( serviceName("service2"), serviceLabels(map[string]string{ "traefik.swarm.network": "barnet", "traefik.swarm.LBSwarm": "true", }), withEndpointSpec(modeDNSRR)), }, dockerVersion: "1.30", networks: []networktypes.Summary{ { Name: "network_name", ID: "yk6l57rfwizjzxxzftn4amaot", Created: time.Now(), Scope: "swarm", Driver: "overlay", EnableIPv6: false, Internal: true, Ingress: false, ConfigOnly: false, Options: map[string]string{ "com.docker.networktypes.driver.overlay.vxlanid_list": "4098", "com.docker.networktypes.enable_ipv6": "false", }, Labels: map[string]string{ "com.docker.stack.namespace": "test", }, }, }, expectedServices: []string{ "service1", }, }, { desc: "Should return service1 and service2", services: []swarmtypes.Service{ swarmService( serviceName("service1"), serviceLabels(map[string]string{ "traefik.swarm.network": "barnet", }), withEndpointSpec(modeVIP), withEndpoint( virtualIP("yk6l57rfwizjzxxzftn4amaot", "10.11.12.13/24"), virtualIP("2", "10.11.12.99/24"), )), swarmService( serviceName("service2"), serviceLabels(map[string]string{ "traefik.swarm.network": "barnet", }), withEndpointSpec(modeDNSRR)), }, tasks: []swarmtypes.Task{ swarmTask("id1", taskNetworkAttachment("yk6l57rfwizjzxxzftn4amaot", "network_name", "overlay", []string{"127.0.0.1"}), taskStatus(taskState(swarmtypes.TaskStateRunning)), ), swarmTask("id2", taskNetworkAttachment("yk6l57rfwizjzxxzftn4amaot", "network_name", "overlay", []string{"127.0.0.1"}), taskStatus(taskState(swarmtypes.TaskStateRunning)), ), }, dockerVersion: "1.30", networks: []networktypes.Summary{ { Name: "network_name", ID: "yk6l57rfwizjzxxzftn4amaot", Created: time.Now(), Scope: "swarm", Driver: "overlay", EnableIPv6: false, Internal: true, Ingress: false, ConfigOnly: false, Options: map[string]string{ "com.docker.networktypes.driver.overlay.vxlanid_list": "4098", "com.docker.networktypes.enable_ipv6": "false", }, Labels: map[string]string{ "com.docker.stack.namespace": "test", }, }, }, expectedServices: []string{ "service1.0", "service1.0", "service2.0", "service2.0", }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() dockerClient := &fakeServicesClient{services: test.services, tasks: test.tasks, dockerVersion: test.dockerVersion, networks: test.networks} var p SwarmProvider require.NoError(t, p.Init()) serviceDockerData, err := p.listServices(t.Context(), dockerClient) assert.NoError(t, err) assert.Len(t, serviceDockerData, len(test.expectedServices)) for i, serviceName := range test.expectedServices { if len(serviceDockerData) <= i { require.Fail(t, "index", "invalid index %d", i) } assert.Equal(t, serviceName, serviceDockerData[i].Name) } }) } } func TestSwarmProvider_parseService_task(t *testing.T) { testCases := []struct { service swarmtypes.Service tasks []swarmtypes.Task nodes []swarmtypes.Node isGlobalSVC bool expected map[string]dockerData networks map[string]*networktypes.Summary }{ { service: swarmService(serviceName("container")), tasks: []swarmtypes.Task{ swarmTask("id1", taskSlot(1)), swarmTask("id2", taskSlot(2)), swarmTask("id3", taskSlot(3)), }, isGlobalSVC: false, expected: map[string]dockerData{ "id1": { Name: "container.1", }, "id2": { Name: "container.2", }, "id3": { Name: "container.3", }, }, networks: map[string]*networktypes.Summary{ "1": { Name: "foo", }, }, }, { service: swarmService(serviceName("container")), tasks: []swarmtypes.Task{ swarmTask("id1"), swarmTask("id2"), swarmTask("id3"), }, isGlobalSVC: true, expected: map[string]dockerData{ "id1": { Name: "container.id1", }, "id2": { Name: "container.id2", }, "id3": { Name: "container.id3", }, }, networks: map[string]*networktypes.Summary{ "1": { Name: "foo", }, }, }, { service: swarmService( serviceName("container"), withEndpointSpec(modeVIP), withEndpoint( virtualIP("1", ""), ), ), tasks: []swarmtypes.Task{ swarmTask( "id1", taskNetworkAttachment("1", "vlan", "macvlan", []string{"127.0.0.1"}), taskStatus( taskState(swarmtypes.TaskStateRunning), taskContainerStatus("c1"), ), ), }, isGlobalSVC: true, expected: map[string]dockerData{ "id1": { Name: "container.id1", NetworkSettings: networkSettings{ Networks: map[string]*networkData{ "vlan": { Name: "vlan", Addr: "10.11.12.13", }, }, }, }, }, networks: map[string]*networktypes.Summary{ "1": { Name: "vlan", }, }, }, { service: swarmService(serviceName("container")), tasks: []swarmtypes.Task{ swarmTask("id1", taskSlot(1), taskNodeID("id1"), ), }, nodes: []swarmtypes.Node{ { ID: "id1", Status: swarmtypes.NodeStatus{ Addr: "10.11.12.13", }, }, }, expected: map[string]dockerData{ "id1": { Name: "container.1", NodeIP: "10.11.12.13", }, }, networks: map[string]*networktypes.Summary{ "1": { Name: "foo", }, }, }, } for caseID, test := range testCases { t.Run(strconv.Itoa(caseID), func(t *testing.T) { t.Parallel() var p SwarmProvider require.NoError(t, p.Init()) dData, err := p.parseService(t.Context(), test.service, test.networks) require.NoError(t, err) dockerClient := &fakeServicesClient{ tasks: test.tasks, nodes: test.nodes, } for _, task := range test.tasks { taskDockerData, err := parseTasks(t.Context(), dockerClient, task, dData, test.networks, test.isGlobalSVC) require.NoError(t, err) expected := test.expected[task.ID] assert.Equal(t, expected.Name, taskDockerData.Name) assert.Equal(t, expected.NodeIP, taskDockerData.NodeIP) } }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/docker/builder_test.go
pkg/provider/docker/builder_test.go
package docker import ( containertypes "github.com/docker/docker/api/types/container" networktypes "github.com/docker/docker/api/types/network" swarmtypes "github.com/docker/docker/api/types/swarm" "github.com/docker/go-connections/nat" ) func containerJSON(ops ...func(*containertypes.InspectResponse)) containertypes.InspectResponse { c := &containertypes.InspectResponse{ ContainerJSONBase: &containertypes.ContainerJSONBase{ Name: "fake", HostConfig: &containertypes.HostConfig{}, State: &containertypes.State{}, }, Config: &containertypes.Config{}, NetworkSettings: &containertypes.NetworkSettings{ NetworkSettingsBase: containertypes.NetworkSettingsBase{}, }, } for _, op := range ops { op(c) } return *c } func name(name string) func(*containertypes.InspectResponse) { return func(c *containertypes.InspectResponse) { c.ContainerJSONBase.Name = name } } func networkMode(mode string) func(*containertypes.InspectResponse) { return func(c *containertypes.InspectResponse) { c.ContainerJSONBase.HostConfig.NetworkMode = containertypes.NetworkMode(mode) } } func ports(portMap nat.PortMap) func(*containertypes.InspectResponse) { return func(c *containertypes.InspectResponse) { c.NetworkSettings.NetworkSettingsBase.Ports = portMap } } func withNetwork(name string, ops ...func(*networktypes.EndpointSettings)) func(*containertypes.InspectResponse) { return func(c *containertypes.InspectResponse) { if c.NetworkSettings.Networks == nil { c.NetworkSettings.Networks = map[string]*networktypes.EndpointSettings{} } c.NetworkSettings.Networks[name] = &networktypes.EndpointSettings{} for _, op := range ops { op(c.NetworkSettings.Networks[name]) } } } func ipv4(ip string) func(*networktypes.EndpointSettings) { return func(s *networktypes.EndpointSettings) { s.IPAddress = ip } } func ipv6(ip string) func(*networktypes.EndpointSettings) { return func(s *networktypes.EndpointSettings) { s.GlobalIPv6Address = ip } } func swarmTask(id string, ops ...func(*swarmtypes.Task)) swarmtypes.Task { task := &swarmtypes.Task{ ID: id, } for _, op := range ops { op(task) } return *task } func taskSlot(slot int) func(*swarmtypes.Task) { return func(task *swarmtypes.Task) { task.Slot = slot } } func taskNodeID(id string) func(*swarmtypes.Task) { return func(task *swarmtypes.Task) { task.NodeID = id } } func taskNetworkAttachment(id, name, driver string, addresses []string) func(*swarmtypes.Task) { return func(task *swarmtypes.Task) { task.NetworksAttachments = append(task.NetworksAttachments, swarmtypes.NetworkAttachment{ Network: swarmtypes.Network{ ID: id, Spec: swarmtypes.NetworkSpec{ Annotations: swarmtypes.Annotations{ Name: name, }, DriverConfiguration: &swarmtypes.Driver{ Name: driver, }, }, }, Addresses: addresses, }) } } func taskStatus(ops ...func(*swarmtypes.TaskStatus)) func(*swarmtypes.Task) { return func(task *swarmtypes.Task) { status := &swarmtypes.TaskStatus{} for _, op := range ops { op(status) } task.Status = *status } } func taskState(state swarmtypes.TaskState) func(*swarmtypes.TaskStatus) { return func(status *swarmtypes.TaskStatus) { status.State = state } } func taskContainerStatus(id string) func(*swarmtypes.TaskStatus) { return func(status *swarmtypes.TaskStatus) { status.ContainerStatus = &swarmtypes.ContainerStatus{ ContainerID: id, } } } func swarmService(ops ...func(*swarmtypes.Service)) swarmtypes.Service { service := &swarmtypes.Service{ ID: "serviceID", Spec: swarmtypes.ServiceSpec{ Annotations: swarmtypes.Annotations{ Name: "defaultServiceName", }, }, } for _, op := range ops { op(service) } return *service } func serviceName(name string) func(service *swarmtypes.Service) { return func(service *swarmtypes.Service) { service.Spec.Annotations.Name = name } } func serviceLabels(labels map[string]string) func(service *swarmtypes.Service) { return func(service *swarmtypes.Service) { service.Spec.Annotations.Labels = labels } } func withEndpoint(ops ...func(*swarmtypes.Endpoint)) func(*swarmtypes.Service) { return func(service *swarmtypes.Service) { endpoint := &swarmtypes.Endpoint{} for _, op := range ops { op(endpoint) } service.Endpoint = *endpoint } } func virtualIP(networkID, addr string) func(*swarmtypes.Endpoint) { return func(endpoint *swarmtypes.Endpoint) { if endpoint.VirtualIPs == nil { endpoint.VirtualIPs = []swarmtypes.EndpointVirtualIP{} } endpoint.VirtualIPs = append(endpoint.VirtualIPs, swarmtypes.EndpointVirtualIP{ NetworkID: networkID, Addr: addr, }) } } func withEndpointSpec(ops ...func(*swarmtypes.EndpointSpec)) func(*swarmtypes.Service) { return func(service *swarmtypes.Service) { endpointSpec := &swarmtypes.EndpointSpec{} for _, op := range ops { op(endpointSpec) } service.Spec.EndpointSpec = endpointSpec } } func modeDNSRR(spec *swarmtypes.EndpointSpec) { spec.Mode = swarmtypes.ResolutionModeDNSRR } func modeVIP(spec *swarmtypes.EndpointSpec) { spec.Mode = swarmtypes.ResolutionModeVIP }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/nomad/tag_test.go
pkg/provider/nomad/tag_test.go
package nomad import ( "testing" "github.com/stretchr/testify/assert" ) func Test_tagsToLabels(t *testing.T) { testCases := []struct { desc string tags []string prefix string expected map[string]string }{ { desc: "no tags", tags: []string{}, prefix: "traefik", expected: map[string]string{}, }, { desc: "minimal global config", tags: []string{"traefik.enable=false"}, prefix: "traefik", expected: map[string]string{ "traefik.enable": "false", }, }, { desc: "config with domain", tags: []string{ "traefik.enable=true", "traefik.domain=example.com", }, prefix: "traefik", expected: map[string]string{ "traefik.enable": "true", "traefik.domain": "example.com", }, }, { desc: "config with custom prefix", tags: []string{ "custom.enable=true", "custom.domain=example.com", }, prefix: "custom", expected: map[string]string{ "traefik.enable": "true", "traefik.domain": "example.com", }, }, { desc: "config with spaces in tags", tags: []string{ "custom.enable = true", "custom.domain = example.com", }, prefix: "custom", expected: map[string]string{ "traefik.enable": "true", "traefik.domain": "example.com", }, }, { desc: "with a prefix", prefix: "test", tags: []string{ "test.aaa=01", "test.bbb=02", "ccc=03", "test.ddd=04=to", }, expected: map[string]string{ "traefik.aaa": "01", "traefik.bbb": "02", "traefik.ddd": "04=to", }, }, { desc: "with an empty prefix", prefix: "", tags: []string{ "test.aaa=01", "test.bbb=02", "ccc=03", "test.ddd=04=to", }, expected: map[string]string{ "traefik.test.aaa": "01", "traefik.test.bbb": "02", "traefik.ccc": "03", "traefik.test.ddd": "04=to", }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() labels := tagsToLabels(test.tags, test.prefix) assert.Equal(t, test.expected, labels) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/nomad/config.go
pkg/provider/nomad/config.go
package nomad import ( "context" "errors" "fmt" "hash/fnv" "net" "sort" "strconv" "strings" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/label" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/provider" "github.com/traefik/traefik/v3/pkg/provider/constraints" ) func (p *Provider) buildConfig(ctx context.Context, items []item) *dynamic.Configuration { configurations := make(map[string]*dynamic.Configuration) for _, i := range items { svcName := provider.Normalize(i.Node + "-" + i.Name + "-" + i.ID) logger := log.Ctx(ctx).With().Str(logs.ServiceName, svcName).Logger() ctxSvc := logger.WithContext(ctx) if !p.keepItem(ctxSvc, i) { continue } labels := tagsToLabels(i.Tags, p.Prefix) config, err := label.DecodeConfiguration(labels) if err != nil { logger.Error().Err(err).Msg("Failed to decode configuration") continue } var tcpOrUDP bool if len(config.TCP.Routers) > 0 || len(config.TCP.Services) > 0 { tcpOrUDP = true if err := p.buildTCPConfig(i, config.TCP); err != nil { logger.Error().Err(err).Msg("Failed to build TCP service configuration") continue } provider.BuildTCPRouterConfiguration(ctxSvc, config.TCP) } if len(config.UDP.Routers) > 0 || len(config.UDP.Services) > 0 { tcpOrUDP = true if err := p.buildUDPConfig(i, config.UDP); err != nil { logger.Error().Err(err).Msg("Failed to build UDP service configuration") continue } provider.BuildUDPRouterConfiguration(ctxSvc, config.UDP) } // tcp/udp, skip configuring http service if tcpOrUDP && len(config.HTTP.Routers) == 0 && len(config.HTTP.Middlewares) == 0 && len(config.HTTP.Services) == 0 { configurations[svcName] = config continue } // configure http service if err := p.buildServiceConfig(i, config.HTTP); err != nil { logger.Error().Err(err).Msg("Failed to build HTTP service configuration") continue } model := struct { Name string Labels map[string]string }{ Name: i.Name, Labels: labels, } provider.BuildRouterConfiguration(ctx, config.HTTP, getName(i), p.defaultRuleTpl, model) configurations[svcName] = config } return provider.Merge(ctx, configurations) } func (p *Provider) buildTCPConfig(i item, configuration *dynamic.TCPConfiguration) error { if len(configuration.Services) == 0 { configuration.Services = map[string]*dynamic.TCPService{ getName(i): { LoadBalancer: new(dynamic.TCPServersLoadBalancer), }, } } for _, service := range configuration.Services { // Leave load balancer empty when no address and allowEmptyServices = true if !(i.Address == "" && p.AllowEmptyServices) { if err := p.addServerTCP(i, service.LoadBalancer); err != nil { return err } } } return nil } func (p *Provider) buildUDPConfig(i item, configuration *dynamic.UDPConfiguration) error { if len(configuration.Services) == 0 { configuration.Services = make(map[string]*dynamic.UDPService) configuration.Services[getName(i)] = &dynamic.UDPService{ LoadBalancer: new(dynamic.UDPServersLoadBalancer), } } for _, service := range configuration.Services { // Leave load balancer empty when no address and allowEmptyServices = true if !(i.Address == "" && p.AllowEmptyServices) { if err := p.addServerUDP(i, service.LoadBalancer); err != nil { return err } } } return nil } func (p *Provider) buildServiceConfig(i item, configuration *dynamic.HTTPConfiguration) error { if len(configuration.Services) == 0 { configuration.Services = make(map[string]*dynamic.Service) lb := new(dynamic.ServersLoadBalancer) lb.SetDefaults() configuration.Services[getName(i)] = &dynamic.Service{ LoadBalancer: lb, } } for _, service := range configuration.Services { // Leave load balancer empty when no address and allowEmptyServices = true if !(i.Address == "" && p.AllowEmptyServices) { if err := p.addServer(i, service.LoadBalancer); err != nil { return err } } } return nil } // TODO: check whether it is mandatory to filter again. func (p *Provider) keepItem(ctx context.Context, i item) bool { logger := log.Ctx(ctx) if !i.ExtraConf.Enable { logger.Debug().Msg("Filtering disabled item") return false } matches, err := constraints.MatchTags(i.Tags, p.Constraints) if err != nil { logger.Error().Err(err).Msg("Error matching constraint expressions") return false } if !matches { logger.Debug().Msgf("Filtering out item due to constraints: %q", p.Constraints) return false } // TODO: filter on health when that information exists (nomad 1.4+) return true } func (p *Provider) addServerTCP(i item, lb *dynamic.TCPServersLoadBalancer) error { if lb == nil { return errors.New("load-balancer is missing") } if len(lb.Servers) == 0 { lb.Servers = []dynamic.TCPServer{{}} } if i.Address == "" { return errors.New("address is missing") } port := lb.Servers[0].Port lb.Servers[0].Port = "" if port == "" && i.Port > 0 { port = strconv.Itoa(i.Port) } if port == "" { return errors.New("port is missing") } lb.Servers[0].Address = net.JoinHostPort(i.Address, port) return nil } func (p *Provider) addServerUDP(i item, lb *dynamic.UDPServersLoadBalancer) error { if lb == nil { return errors.New("load-balancer is missing") } if len(lb.Servers) == 0 { lb.Servers = []dynamic.UDPServer{{}} } if i.Address == "" { return errors.New("address is missing") } port := lb.Servers[0].Port lb.Servers[0].Port = "" if port == "" && i.Port > 0 { port = strconv.Itoa(i.Port) } if port == "" { return errors.New("port is missing") } lb.Servers[0].Address = net.JoinHostPort(i.Address, port) return nil } func (p *Provider) addServer(i item, lb *dynamic.ServersLoadBalancer) error { if lb == nil { return errors.New("load-balancer is missing") } if len(lb.Servers) == 0 { lb.Servers = []dynamic.Server{{}} } if i.Address == "" { return errors.New("address is missing") } if lb.Servers[0].URL != "" { if lb.Servers[0].Scheme != "" || lb.Servers[0].Port != "" { return errors.New("defining scheme or port is not allowed when URL is defined") } return nil } port := lb.Servers[0].Port lb.Servers[0].Port = "" if port == "" && i.Port > 0 { port = strconv.Itoa(i.Port) } if port == "" { return errors.New("port is missing") } scheme := lb.Servers[0].Scheme lb.Servers[0].Scheme = "" if scheme == "" { scheme = "http" } lb.Servers[0].URL = fmt.Sprintf("%s://%s", scheme, net.JoinHostPort(i.Address, port)) return nil } func getName(i item) string { if !i.ExtraConf.Canary { return provider.Normalize(i.Name) } tags := make([]string, len(i.Tags)) copy(tags, i.Tags) sort.Strings(tags) hasher := fnv.New64() hasher.Write([]byte(strings.Join(tags, ""))) return provider.Normalize(fmt.Sprintf("%s-%d", i.Name, hasher.Sum64())) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/nomad/nomad.go
pkg/provider/nomad/nomad.go
package nomad import ( "context" "errors" "fmt" "strings" "text/template" "time" "github.com/cenkalti/backoff/v4" "github.com/hashicorp/nomad/api" "github.com/mitchellh/hashstructure" "github.com/rs/zerolog/log" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/job" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/provider" "github.com/traefik/traefik/v3/pkg/provider/constraints" "github.com/traefik/traefik/v3/pkg/safe" "github.com/traefik/traefik/v3/pkg/types" ) const ( // providerName is the name of this provider. providerName = "nomad" // defaultTemplateRule is the default template for the default rule. defaultTemplateRule = "Host(`{{ normalize .Name }}`)" // defaultPrefix is the default prefix used in tag values indicating the service // should be consumed and exposed via traefik. defaultPrefix = "traefik" ) var _ provider.Provider = (*Provider)(nil) type item struct { ID string // service ID Name string // service name Namespace string // service namespace Node string // node ID Datacenter string // region Address string // service address Port int // service port Tags []string // service tags ExtraConf configuration // global options } // configuration contains information from the service's tags that are globals // (not specific to the dynamic configuration). type configuration struct { Enable bool // <prefix>.enable is the corresponding label. Canary bool // <prefix>.nomad.canary is the corresponding label. } // ProviderBuilder is responsible for constructing namespaced instances of the Nomad provider. type ProviderBuilder struct { Configuration `yaml:",inline" export:"true"` Namespaces []string `description:"Sets the Nomad namespaces used to discover services." json:"namespaces,omitempty" toml:"namespaces,omitempty" yaml:"namespaces,omitempty"` } // BuildProviders builds Nomad provider instances for the given namespaces configuration. func (p *ProviderBuilder) BuildProviders() []*Provider { if len(p.Namespaces) == 0 { return []*Provider{{ Configuration: p.Configuration, name: providerName, }} } var providers []*Provider for _, namespace := range p.Namespaces { providers = append(providers, &Provider{ Configuration: p.Configuration, name: providerName + "-" + namespace, namespace: namespace, }) } return providers } // Configuration represents the Nomad provider configuration. type Configuration struct { DefaultRule string `description:"Default rule." json:"defaultRule,omitempty" toml:"defaultRule,omitempty" yaml:"defaultRule,omitempty"` Constraints string `description:"Constraints is an expression that Traefik matches against the Nomad service's tags to determine whether to create route(s) for that service." json:"constraints,omitempty" toml:"constraints,omitempty" yaml:"constraints,omitempty" export:"true"` Endpoint *EndpointConfig `description:"Nomad endpoint settings" json:"endpoint,omitempty" toml:"endpoint,omitempty" yaml:"endpoint,omitempty" export:"true"` Prefix string `description:"Prefix for nomad service tags." json:"prefix,omitempty" toml:"prefix,omitempty" yaml:"prefix,omitempty" export:"true"` Stale bool `description:"Use stale consistency for catalog reads." json:"stale,omitempty" toml:"stale,omitempty" yaml:"stale,omitempty" export:"true"` ExposedByDefault bool `description:"Expose Nomad services by default." json:"exposedByDefault,omitempty" toml:"exposedByDefault,omitempty" yaml:"exposedByDefault,omitempty" export:"true"` RefreshInterval ptypes.Duration `description:"Interval for polling Nomad API." json:"refreshInterval,omitempty" toml:"refreshInterval,omitempty" yaml:"refreshInterval,omitempty" export:"true"` AllowEmptyServices bool `description:"Allow the creation of services without endpoints." json:"allowEmptyServices,omitempty" toml:"allowEmptyServices,omitempty" yaml:"allowEmptyServices,omitempty" export:"true"` Watch bool `description:"Watch Nomad Service events." json:"watch,omitempty" toml:"watch,omitempty" yaml:"watch,omitempty" export:"true"` ThrottleDuration ptypes.Duration `description:"Watch throttle duration." json:"throttleDuration,omitempty" toml:"throttleDuration,omitempty" yaml:"throttleDuration,omitempty" export:"true"` } // SetDefaults sets the default values for the Nomad Traefik Provider Configuration. func (c *Configuration) SetDefaults() { defConfig := api.DefaultConfig() c.Endpoint = &EndpointConfig{ Address: defConfig.Address, Region: defConfig.Region, Token: defConfig.SecretID, } if defConfig.TLSConfig != nil && (defConfig.TLSConfig.Insecure || defConfig.TLSConfig.CACert != "" || defConfig.TLSConfig.ClientCert != "" || defConfig.TLSConfig.ClientKey != "") { c.Endpoint.TLS = &types.ClientTLS{ CA: defConfig.TLSConfig.CACert, Cert: defConfig.TLSConfig.ClientCert, Key: defConfig.TLSConfig.ClientKey, InsecureSkipVerify: defConfig.TLSConfig.Insecure, } } c.Prefix = defaultPrefix c.ExposedByDefault = true c.RefreshInterval = ptypes.Duration(15 * time.Second) c.DefaultRule = defaultTemplateRule c.ThrottleDuration = ptypes.Duration(0) } type EndpointConfig struct { // Address is the Nomad endpoint address, if empty it defaults to NOMAD_ADDR or "http://127.0.0.1:4646". Address string `description:"The address of the Nomad server, including scheme and port." json:"address,omitempty" toml:"address,omitempty" yaml:"address,omitempty"` // Region is the Nomad region, if empty it defaults to NOMAD_REGION. Region string `description:"Nomad region to use. If not provided, the local agent region is used." json:"region,omitempty" toml:"region,omitempty" yaml:"region,omitempty"` // Token is the ACL token to connect with Nomad, if empty it defaults to NOMAD_TOKEN. Token string `description:"Token is used to provide a per-request ACL token." json:"token,omitempty" toml:"token,omitempty" yaml:"token,omitempty" loggable:"false"` TLS *types.ClientTLS `description:"Configure TLS." json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" export:"true"` EndpointWaitTime ptypes.Duration `description:"WaitTime limits how long a Watch will block. If not provided, the agent default values will be used" json:"endpointWaitTime,omitempty" toml:"endpointWaitTime,omitempty" yaml:"endpointWaitTime,omitempty" export:"true"` } // Provider holds configuration along with the namespace it will discover services in. type Provider struct { Configuration name string namespace string client *api.Client // client for Nomad API defaultRuleTpl *template.Template // default routing rule lastConfiguration safe.Safe } // SetDefaults sets the default values for the Nomad Traefik Provider. func (p *Provider) SetDefaults() { p.Configuration.SetDefaults() } // Init the Nomad Traefik Provider. func (p *Provider) Init() error { if p.namespace == api.AllNamespacesNamespace { return errors.New("wildcard namespace not supported") } if p.ThrottleDuration > 0 && !p.Watch { return errors.New("throttle duration should not be used with polling mode") } defaultRuleTpl, err := provider.MakeDefaultRuleTemplate(p.DefaultRule, nil) if err != nil { return fmt.Errorf("error while parsing default rule: %w", err) } p.defaultRuleTpl = defaultRuleTpl // In case they didn't initialize Provider with BuildProviders if p.name == "" { p.name = providerName } return nil } // Provide allows the Nomad Traefik Provider to provide configurations to traefik // using the given configuration channel. func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error { var err error p.client, err = createClient(p.namespace, p.Endpoint) if err != nil { return fmt.Errorf("failed to create nomad API client: %w", err) } pool.GoCtx(func(routineCtx context.Context) { logger := log.Ctx(routineCtx).With().Str(logs.ProviderName, p.name).Logger() ctxLog := logger.WithContext(routineCtx) operation := func() error { ctx, cancel := context.WithCancel(ctxLog) defer cancel() serviceEventsChan, err := p.pollOrWatch(ctx) if err != nil { return fmt.Errorf("watching Nomad events: %w", err) } throttleDuration := time.Duration(p.ThrottleDuration) throttledChan := throttleEvents(ctx, throttleDuration, pool, serviceEventsChan) if throttledChan != nil { serviceEventsChan = throttledChan } conf, err := p.loadConfiguration(ctx) if err != nil { return fmt.Errorf("loading configuration: %w", err) } if _, err := p.updateLastConfiguration(conf); err != nil { return fmt.Errorf("updating last configuration: %w", err) } configurationChan <- dynamic.Message{ ProviderName: p.name, Configuration: conf, } for { select { case <-ctx.Done(): return nil case event := <-serviceEventsChan: conf, err = p.loadConfiguration(ctx) if err != nil { return fmt.Errorf("loading configuration: %w", err) } updated, err := p.updateLastConfiguration(conf) if err != nil { return fmt.Errorf("updating last configuration: %w", err) } if !updated { logger.Debug().Msgf("Skipping Nomad event %d with no changes", event.Index) continue } configurationChan <- dynamic.Message{ ProviderName: p.name, Configuration: conf, } // If we're throttling, we sleep here for the throttle duration to // enforce that we don't refresh faster than our throttle. time.Sleep // returns immediately if p.ThrottleDuration is 0 (no throttle). time.Sleep(throttleDuration) } } } failure := func(err error, d time.Duration) { logger.Error().Err(err).Msgf("Loading configuration, retrying in %s", d) } if retryErr := backoff.RetryNotify( safe.OperationWithRecover(operation), backoff.WithContext(job.NewBackOff(backoff.NewExponentialBackOff()), ctxLog), failure, ); retryErr != nil { logger.Error().Err(retryErr).Msg("Cannot connect to Nomad server") } }) return nil } func (p *Provider) pollOrWatch(ctx context.Context) (<-chan *api.Events, error) { if p.Watch { return p.client.EventStream().Stream(ctx, map[api.Topic][]string{ api.TopicService: {"*"}, }, 0, &api.QueryOptions{ Namespace: p.namespace, }, ) } serviceEventsChan := make(chan *api.Events, 1) go func() { ticker := time.NewTicker(time.Duration(p.RefreshInterval)) defer ticker.Stop() for { select { case <-ctx.Done(): return case t := <-ticker.C: serviceEventsChan <- &api.Events{ Index: uint64(t.UnixNano()), } } } }() return serviceEventsChan, nil } func (p *Provider) loadConfiguration(ctx context.Context) (*dynamic.Configuration, error) { var items []item var err error if p.AllowEmptyServices { items, err = p.getNomadServiceDataWithEmptyServices(ctx) if err != nil { return nil, err } } else { items, err = p.getNomadServiceData(ctx) if err != nil { return nil, err } } return p.buildConfig(ctx, items), nil } func (p *Provider) updateLastConfiguration(conf *dynamic.Configuration) (bool, error) { confHash, err := hashstructure.Hash(conf, nil) if err != nil { return false, fmt.Errorf("hashing the configuration: %w", err) } if p.lastConfiguration.Get() == confHash { return false, nil } p.lastConfiguration.Set(confHash) return true, nil } func (p *Provider) getNomadServiceData(ctx context.Context) ([]item, error) { // first, get list of service stubs opts := &api.QueryOptions{AllowStale: p.Stale} opts = opts.WithContext(ctx) stubs, _, err := p.client.Services().List(opts) if err != nil { return nil, err } var items []item for _, stub := range stubs { for _, service := range stub.Services { logger := log.Ctx(ctx).With().Str("serviceName", service.ServiceName).Logger() extraConf := p.getExtraConf(service.Tags) if !extraConf.Enable { logger.Debug().Msg("Filter Nomad service that is not enabled") continue } matches, err := constraints.MatchTags(service.Tags, p.Constraints) if err != nil { logger.Error().Err(err).Msg("Error matching constraint expressions") continue } if !matches { logger.Debug().Msgf("Filter Nomad service not matching constraints: %q", p.Constraints) continue } instances, err := p.fetchService(ctx, service.ServiceName) if err != nil { return nil, err } for _, i := range instances { items = append(items, item{ ID: i.ID, Name: i.ServiceName, Namespace: i.Namespace, Node: i.NodeID, Datacenter: i.Datacenter, Address: i.Address, Port: i.Port, Tags: i.Tags, ExtraConf: p.getExtraConf(i.Tags), }) } } } return items, nil } func (p *Provider) getNomadServiceDataWithEmptyServices(ctx context.Context) ([]item, error) { jobsOpts := &api.QueryOptions{AllowStale: p.Stale} jobsOpts = jobsOpts.WithContext(ctx) jobStubs, _, err := p.client.Jobs().List(jobsOpts) if err != nil { return nil, err } var items []item // Get Services even when they are scaled down to zero. Currently the nomad service interface does not support this. https://github.com/hashicorp/nomad/issues/19731 for _, jobStub := range jobStubs { jobInfoOpts := &api.QueryOptions{} jobInfoOpts = jobInfoOpts.WithContext(ctx) job, _, err := p.client.Jobs().Info(jobStub.ID, jobInfoOpts) if err != nil { return nil, err } for _, taskGroup := range job.TaskGroups { services := []*api.Service{} // Get all services in job -> taskgroup services = append(services, taskGroup.Services...) // Get all services in job -> taskgroup -> tasks for _, task := range taskGroup.Tasks { services = append(services, task.Services...) } for _, service := range services { logger := log.Ctx(ctx).With().Str("serviceName", service.TaskName).Logger() extraConf := p.getExtraConf(service.Tags) if !extraConf.Enable { logger.Debug().Msg("Filter Nomad service that is not enabled") continue } matches, err := constraints.MatchTags(service.Tags, p.Constraints) if err != nil { logger.Error().Err(err).Msg("Error matching constraint expressions") continue } if !matches { logger.Debug().Msgf("Filter Nomad service not matching constraints: %q", p.Constraints) continue } if nil != taskGroup.Scaling && *taskGroup.Scaling.Enabled && *taskGroup.Count == 0 { // Add items without address items = append(items, item{ // Create a unique id for non registered services ID: fmt.Sprintf("%s-%s-%s-%s-%s", *job.Namespace, *job.Name, *taskGroup.Name, service.TaskName, service.Name), Name: service.Name, Namespace: *job.Namespace, Node: "", Datacenter: "", Address: "", Port: -1, Tags: service.Tags, ExtraConf: p.getExtraConf(service.Tags), }) } else { instances, err := p.fetchService(ctx, service.Name) if err != nil { return nil, err } for _, i := range instances { items = append(items, item{ ID: i.ID, Name: i.ServiceName, Namespace: i.Namespace, Node: i.NodeID, Datacenter: i.Datacenter, Address: i.Address, Port: i.Port, Tags: i.Tags, ExtraConf: p.getExtraConf(i.Tags), }) } } } } } return items, nil } // getExtraConf returns a configuration with settings which are not part of the dynamic configuration (e.g. "<prefix>.enable"). func (p *Provider) getExtraConf(tags []string) configuration { labels := tagsToLabels(tags, p.Prefix) enabled := p.ExposedByDefault if v, exists := labels["traefik.enable"]; exists { enabled = strings.EqualFold(v, "true") } var canary bool if v, exists := labels["traefik.nomad.canary"]; exists { canary = strings.EqualFold(v, "true") } return configuration{Enable: enabled, Canary: canary} } // fetchService queries Nomad API for services matching name, // that also have the <prefix>.enable=true set in its tags. func (p *Provider) fetchService(ctx context.Context, name string) ([]*api.ServiceRegistration, error) { var tagFilter string if !p.ExposedByDefault { tagFilter = fmt.Sprintf(`Tags contains %q`, fmt.Sprintf("%s.enable=true", p.Prefix)) } // TODO: Nomad currently (v1.3.0) does not support health checks, // and as such does not yet return health status information. // When it does, refactor this section to include health status. opts := &api.QueryOptions{AllowStale: p.Stale, Filter: tagFilter} opts = opts.WithContext(ctx) services, _, err := p.client.Services().Get(name, opts) if err != nil { return nil, fmt.Errorf("failed to fetch services: %w", err) } return services, nil } func createClient(namespace string, endpoint *EndpointConfig) (*api.Client, error) { config := api.Config{ Address: endpoint.Address, Namespace: namespace, Region: endpoint.Region, SecretID: endpoint.Token, WaitTime: time.Duration(endpoint.EndpointWaitTime), } if endpoint.TLS != nil { config.TLSConfig = &api.TLSConfig{ CACert: endpoint.TLS.CA, ClientCert: endpoint.TLS.Cert, ClientKey: endpoint.TLS.Key, Insecure: endpoint.TLS.InsecureSkipVerify, } } return api.NewClient(&config) } // Copied from the Kubernetes provider. func throttleEvents(ctx context.Context, throttleDuration time.Duration, pool *safe.Pool, eventsChan <-chan *api.Events) chan *api.Events { if throttleDuration == 0 { return nil } // Create a buffered channel to hold the pending event (if we're delaying processing the event due to throttling). eventsChanBuffered := make(chan *api.Events, 1) // Run a goroutine that reads events from eventChan and does a // non-blocking write to pendingEvent. This guarantees that writing to // eventChan will never block, and that pendingEvent will have // something in it if there's been an event since we read from that channel. pool.GoCtx(func(ctxPool context.Context) { for { select { case <-ctxPool.Done(): return case nextEvent := <-eventsChan: select { case eventsChanBuffered <- nextEvent: default: // We already have an event in eventsChanBuffered, so we'll // do a refresh as soon as our throttle allows us to. It's fine // to drop the event and keep whatever's in the buffer -- we // don't do different things for different events. log.Ctx(ctx).Debug().Msgf("Dropping event %d due to throttling", nextEvent.Index) } } } }) return eventsChanBuffered } // Namespace returns the namespace of the Nomad provider. func (p *Provider) Namespace() string { return p.namespace }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/nomad/config_test.go
pkg/provider/nomad/config_test.go
package nomad import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" ) func Test_defaultRule(t *testing.T) { testCases := []struct { desc string items []item rule string expected *dynamic.Configuration }{ { desc: "default rule with no variable", items: []item{ { ID: "id", Node: "node1", Name: "Test", Address: "127.0.0.1", Port: 9999, ExtraConf: configuration{Enable: true}, }, }, rule: "Host(`example.com`)", expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Test": { Service: "Test", Rule: "Host(`example.com`)", DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:9999", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "default rule with label", items: []item{ { ID: "id", Node: "Node1", Name: "Test", Address: "127.0.0.1", Tags: []string{ "traefik.domain=example.com", }, Port: 9999, ExtraConf: configuration{Enable: true}, }, }, rule: `Host("{{ .Name }}.{{ index .Labels "traefik.domain" }}")`, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Test": { Service: "Test", Rule: `Host("Test.example.com")`, DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:9999", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "invalid rule", items: []item{ { ID: "id", Node: "Node1", Name: "Test", Address: "127.0.0.1", Port: 9999, ExtraConf: configuration{Enable: true}, }, }, rule: `Host"{{ .Invalid }}")`, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:9999", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "default template rule", items: []item{ { ID: "id", Node: "Node1", Name: "Test", Address: "127.0.0.1", Port: 9999, ExtraConf: configuration{Enable: true}, }, }, rule: defaultTemplateRule, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Test": { Service: "Test", Rule: "Host(`Test`)", DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:9999", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { p := new(Provider) p.SetDefaults() p.DefaultRule = test.rule err := p.Init() require.NoError(t, err) config := p.buildConfig(t.Context(), test.items) require.Equal(t, test.expected, config) }) } } func Test_buildConfig(t *testing.T) { testCases := []struct { desc string items []item constraints string expected *dynamic.Configuration }{ { desc: "one service no tags", items: []item{ { ID: "id", Node: "Node1", Name: "dev/Test", Address: "127.0.0.1", Port: 9999, ExtraConf: configuration{Enable: true}, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "dev-Test": { Service: "dev-Test", Rule: "Host(`dev-Test.traefik.test`)", DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "dev-Test": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:9999", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "two services no tags", items: []item{ { ID: "id1", Node: "Node1", Name: "Test1", Address: "192.168.1.101", Port: 9999, ExtraConf: configuration{Enable: true}, }, { ID: "id2", Node: "Node2", Name: "Test2", Address: "192.168.1.102", Port: 9999, ExtraConf: configuration{Enable: true}, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Test1": { Service: "Test1", Rule: "Host(`Test1.traefik.test`)", DefaultRule: true, }, "Test2": { Service: "Test2", Rule: "Host(`Test2.traefik.test`)", DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test1": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://192.168.1.101:9999", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, "Test2": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://192.168.1.102:9999", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "two services with same name no label", items: []item{ { ID: "id1", Node: "Node1", Name: "Test", Tags: []string{}, Address: "127.0.0.1", Port: 9999, ExtraConf: configuration{Enable: true}, }, { ID: "id2", Node: "Node2", Name: "Test", Tags: []string{}, Address: "127.0.0.2", Port: 9999, ExtraConf: configuration{Enable: true}, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Test": { Service: "Test", Rule: "Host(`Test.traefik.test`)", DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:9999", }, { URL: "http://127.0.0.2:9999", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "two services same name and id no label same node", items: []item{ { ID: "id1", Node: "Node1", Name: "Test", Tags: []string{}, Address: "127.0.0.1", Port: 9999, ExtraConf: configuration{Enable: true}, }, { ID: "id1", Node: "Node1", Name: "Test", Tags: []string{}, Address: "127.0.0.2", Port: 9999, ExtraConf: configuration{Enable: true}, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Test": { Service: "Test", Rule: "Host(`Test.traefik.test`)", DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.2:9999", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "two services same service name and id no label on different nodes", items: []item{ { ID: "id1", Node: "Node1", Name: "Test", Tags: []string{}, Address: "127.0.0.1", Port: 9999, ExtraConf: configuration{Enable: true}, }, { ID: "id1", Node: "Node2", Name: "Test", Tags: []string{}, Address: "127.0.0.2", Port: 9999, ExtraConf: configuration{Enable: true}, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Test": { Service: "Test", Rule: "Host(`Test.traefik.test`)", DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:9999", }, { URL: "http://127.0.0.2:9999", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "one service with label (not on server)", items: []item{ { ID: "id1", Name: "Test", Tags: []string{ "traefik.http.services.Service1.loadbalancer.passhostheader=true", }, Address: "127.0.0.1", Port: 9999, ExtraConf: configuration{Enable: true}, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Test": { Service: "Service1", Rule: "Host(`Test.traefik.test`)", DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:9999", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "one service with labels", items: []item{ { ID: "id1", Name: "Test", Tags: []string{ "traefik.http.services.Service1.loadbalancer.passhostheader = true", "traefik.http.routers.Router1.rule = Host(`foo.com`)", "traefik.http.routers.Router1.service = Service1", }, Address: "127.0.0.1", Port: 9999, ExtraConf: configuration{Enable: true}, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Router1": { Service: "Service1", Rule: "Host(`foo.com`)", }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:9999", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "empty service", items: []item{ { ID: "id1", Name: "Test", Tags: []string{ "traefik.enable=true", }, Address: "", Port: -1, ExtraConf: configuration{Enable: true}, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "one service with rule label", items: []item{ { ID: "id1", Name: "Test", Tags: []string{ "traefik.http.routers.Router1.rule = Host(`foo.com`)", }, Address: "127.0.0.1", Port: 9999, ExtraConf: configuration{Enable: true}, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:9999", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, Routers: map[string]*dynamic.Router{ "Router1": { Service: "Test", Rule: "Host(`foo.com`)", }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "one service with rule label and one traefik service", items: []item{ { ID: "id1", Name: "Test", Tags: []string{ "traefik.http.routers.Router1.rule = Host(`foo.com`)", "traefik.http.services.Service1.loadbalancer.passhostheader = true", }, Address: "127.0.0.1", Port: 9999, ExtraConf: configuration{Enable: true}, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Router1": { Service: "Service1", Rule: "Host(`foo.com`)", }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:9999", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "one service with rule label and two traefik services", items: []item{ { ID: "id1", Name: "Test", Tags: []string{ "traefik.http.routers.Router1.rule = Host(`foo.com`)", "traefik.http.services.Service1.loadbalancer.passhostheader= true", "traefik.http.services.Service2.loadbalancer.passhostheader = true", }, Address: "127.0.0.1", Port: 9999, ExtraConf: configuration{Enable: true}, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:9999", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, "Service2": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:9999", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "two services with same traefik service and different passhostheader", items: []item{ { ID: "id1", Name: "Test", Tags: []string{ "traefik.http.services.Service1.loadbalancer.passhostheader = true", }, Address: "127.0.0.1", Port: 9999, ExtraConf: configuration{Enable: true}, }, { ID: "id2", Name: "Test", Tags: []string{ "traefik.http.services.Service1.loadbalancer.passhostheader = false", }, Address: "127.0.0.2", Port: 9999, ExtraConf: configuration{Enable: true}, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Test": { Service: "Service1", Rule: "Host(`Test.traefik.test`)", DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "three services with same name and different passhostheader", items: []item{ { ID: "id1", Name: "Test", Tags: []string{ "traefik.http.services.Service1.loadbalancer.passhostheader = false", }, Address: "127.0.0.1", Port: 9999, ExtraConf: configuration{Enable: true}, }, { ID: "id2", Name: "Test", Tags: []string{ "traefik.http.services.Service1.loadbalancer.passhostheader = true", }, Address: "127.0.0.1", Port: 9999, ExtraConf: configuration{Enable: true}, }, { ID: "id3", Name: "Test", Tags: []string{ "traefik.http.services.Service1.loadbalancer.passhostheader = true", }, Address: "127.0.0.2", Port: 9999, ExtraConf: configuration{Enable: true}, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Test": { Service: "Service1", Rule: "Host(`Test.traefik.test`)", DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "two services with same name and same LB methods", items: []item{ { ID: "id1", Name: "Test", Tags: []string{ "traefik.http.services.Service1.loadbalancer.passhostheader = true", }, Address: "127.0.0.1", Port: 9999, ExtraConf: configuration{Enable: true}, }, { ID: "id2", Name: "Test", Tags: []string{ "traefik.http.services.Service1.loadbalancer.passhostheader = true", }, Address: "127.0.0.2", Port: 9999, ExtraConf: configuration{Enable: true}, }, }, expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Test": { Service: "Service1", Rule: "Host(`Test.traefik.test`)", DefaultRule: true, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://127.0.0.1:9999", }, { URL: "http://127.0.0.2:9999", }, }, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Stores: map[string]tls.Store{}, }, }, }, { desc: "one service with InFlightReq in label (default value)", items: []item{ { ID: "id1", Name: "Test", Tags: []string{ "traefik.http.middlewares.Middleware1.inflightreq.amount = 42", }, Address: "127.0.0.1",
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/nomad/nomad_test.go
pkg/provider/nomad/nomad_test.go
package nomad import ( "fmt" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/types" ) var responses = map[string][]byte{} func TestMain(m *testing.M) { err := setup() if err != nil { fmt.Fprintf(os.Stderr, "%s", err.Error()) os.Exit(1) } m.Run() } func Test_globalConfig(t *testing.T) { cases := []struct { Name string Prefix string Tags []string ExposedByDefault bool exp configuration }{ { Name: "expose_by_default_no_tags", Prefix: "traefik", Tags: nil, ExposedByDefault: true, exp: configuration{Enable: true}, }, { Name: "not_expose_by_default_no_tags", Prefix: "traefik", Tags: nil, ExposedByDefault: false, exp: configuration{Enable: false}, }, { Name: "expose_by_default_tags_enable", Prefix: "traefik", Tags: []string{"traefik.enable=true"}, ExposedByDefault: true, exp: configuration{Enable: true}, }, { Name: "expose_by_default_tags_disable", Prefix: "traefik", Tags: []string{"traefik.enable=false"}, ExposedByDefault: true, exp: configuration{Enable: false}, }, { Name: "expose_by_default_tags_enable_custom_prefix", Prefix: "custom", Tags: []string{"custom.enable=true"}, ExposedByDefault: true, exp: configuration{Enable: true}, }, { Name: "expose_by_default_tags_disable_custom_prefix", Prefix: "custom", Tags: []string{"custom.enable=false"}, ExposedByDefault: true, exp: configuration{Enable: false}, }, } for _, test := range cases { t.Run(test.Name, func(t *testing.T) { p := Provider{ Configuration: Configuration{ ExposedByDefault: test.ExposedByDefault, Prefix: test.Prefix, }, } result := p.getExtraConf(test.Tags) require.Equal(t, test.exp, result) }) } } func TestProvider_SetDefaults_Endpoint(t *testing.T) { testCases := []struct { desc string envs map[string]string expected *EndpointConfig }{ { desc: "without env vars", envs: map[string]string{}, expected: &EndpointConfig{ Address: "http://127.0.0.1:4646", }, }, { desc: "with env vars", envs: map[string]string{ "NOMAD_ADDR": "https://nomad.example.com", "NOMAD_REGION": "us-west", "NOMAD_TOKEN": "almighty_token", "NOMAD_CACERT": "/etc/ssl/private/nomad-agent-ca.pem", "NOMAD_CLIENT_CERT": "/etc/ssl/private/global-client-nomad.pem", "NOMAD_CLIENT_KEY": "/etc/ssl/private/global-client-nomad-key.pem", "NOMAD_SKIP_VERIFY": "true", }, expected: &EndpointConfig{ Address: "https://nomad.example.com", Region: "us-west", Token: "almighty_token", TLS: &types.ClientTLS{ CA: "/etc/ssl/private/nomad-agent-ca.pem", Cert: "/etc/ssl/private/global-client-nomad.pem", Key: "/etc/ssl/private/global-client-nomad-key.pem", InsecureSkipVerify: true, }, EndpointWaitTime: 0, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { for k, v := range test.envs { t.Setenv(k, v) } p := &Provider{} p.SetDefaults() assert.Equal(t, test.expected, p.Endpoint) }) } } func Test_getNomadServiceDataWithEmptyServices_GroupService_Scaling1(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case strings.HasSuffix(r.RequestURI, "/v1/jobs"): _, _ = w.Write(responses["jobs_job1"]) case strings.HasSuffix(r.RequestURI, "/v1/job/job1"): _, _ = w.Write(responses["job_job1_WithGroupService_Scaling1"]) case strings.HasSuffix(r.RequestURI, "/v1/service/job1"): _, _ = w.Write(responses["service_job1"]) } })) t.Cleanup(ts.Close) p := new(Provider) p.SetDefaults() p.Endpoint.Address = ts.URL err := p.Init() require.NoError(t, err) // fudge client, avoid starting up via Provide p.client, err = createClient(p.namespace, p.Endpoint) require.NoError(t, err) // make the query for services items, err := p.getNomadServiceDataWithEmptyServices(t.Context()) require.NoError(t, err) require.Len(t, items, 1) } func Test_getNomadServiceDataWithEmptyServices_GroupService_Scaling0(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case strings.HasSuffix(r.RequestURI, "/v1/jobs"): _, _ = w.Write(responses["jobs_job2"]) case strings.HasSuffix(r.RequestURI, "/v1/job/job2"): _, _ = w.Write(responses["job_job2_WithGroupService_Scaling0"]) case strings.HasSuffix(r.RequestURI, "/v1/service/job2"): _, _ = w.Write(responses["service_job2"]) } })) t.Cleanup(ts.Close) p := new(Provider) p.SetDefaults() p.Endpoint.Address = ts.URL err := p.Init() require.NoError(t, err) // fudge client, avoid starting up via Provide p.client, err = createClient(p.namespace, p.Endpoint) require.NoError(t, err) // make the query for services items, err := p.getNomadServiceDataWithEmptyServices(t.Context()) require.NoError(t, err) require.Len(t, items, 1) } func Test_getNomadServiceDataWithEmptyServices_GroupService_ScalingDisabled(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case strings.HasSuffix(r.RequestURI, "/v1/jobs"): _, _ = w.Write(responses["jobs_job3"]) case strings.HasSuffix(r.RequestURI, "/v1/job/job3"): _, _ = w.Write(responses["job_job3_WithGroupService_ScalingDisabled"]) case strings.HasSuffix(r.RequestURI, "/v1/service/job3"): _, _ = w.Write(responses["service_job3"]) } })) t.Cleanup(ts.Close) p := new(Provider) p.SetDefaults() p.Endpoint.Address = ts.URL err := p.Init() require.NoError(t, err) // fudge client, avoid starting up via Provide p.client, err = createClient(p.namespace, p.Endpoint) require.NoError(t, err) // make the query for services items, err := p.getNomadServiceDataWithEmptyServices(t.Context()) require.NoError(t, err) require.Len(t, items, 1) } func Test_getNomadServiceDataWithEmptyServices_GroupService_ScalingDisabled_Stopped(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case strings.HasSuffix(r.RequestURI, "/v1/jobs"): _, _ = w.Write(responses["jobs_job4"]) case strings.HasSuffix(r.RequestURI, "/v1/job/job4"): _, _ = w.Write(responses["job_job4_WithGroupService_ScalingDisabled_Stopped"]) case strings.HasSuffix(r.RequestURI, "/v1/service/job4"): _, _ = w.Write(responses["service_job4"]) } })) t.Cleanup(ts.Close) p := new(Provider) p.SetDefaults() p.Endpoint.Address = ts.URL err := p.Init() require.NoError(t, err) // fudge client, avoid starting up via Provide p.client, err = createClient(p.namespace, p.Endpoint) require.NoError(t, err) // make the query for services items, err := p.getNomadServiceDataWithEmptyServices(t.Context()) require.NoError(t, err) // Should not be listed as job is stopped require.Empty(t, items) } func Test_getNomadServiceDataWithEmptyServices_GroupTaskService_Scaling1(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case strings.HasSuffix(r.RequestURI, "/v1/jobs"): _, _ = w.Write(responses["jobs_job5"]) case strings.HasSuffix(r.RequestURI, "/v1/job/job5"): _, _ = w.Write(responses["job_job5_WithGroupTaskService_Scaling1"]) case strings.HasSuffix(r.RequestURI, "/v1/service/job5task1"): _, _ = w.Write(responses["service_job5task1"]) case strings.HasSuffix(r.RequestURI, "/v1/service/job5task2"): _, _ = w.Write(responses["service_job5task2"]) } })) t.Cleanup(ts.Close) p := new(Provider) p.SetDefaults() p.Endpoint.Address = ts.URL err := p.Init() require.NoError(t, err) // fudge client, avoid starting up via Provide p.client, err = createClient(p.namespace, p.Endpoint) require.NoError(t, err) // make the query for services items, err := p.getNomadServiceDataWithEmptyServices(t.Context()) require.NoError(t, err) require.Len(t, items, 2) } func Test_getNomadServiceDataWithEmptyServices_GroupTaskService_Scaling0(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case strings.HasSuffix(r.RequestURI, "/v1/jobs"): _, _ = w.Write(responses["jobs_job6"]) case strings.HasSuffix(r.RequestURI, "/v1/job/job6"): _, _ = w.Write(responses["job_job6_WithGroupTaskService_Scaling0"]) case strings.HasSuffix(r.RequestURI, "/v1/service/job6task1"): _, _ = w.Write(responses["service_job6task1"]) case strings.HasSuffix(r.RequestURI, "/v1/service/job6task2"): _, _ = w.Write(responses["service_job6task2"]) } })) t.Cleanup(ts.Close) p := new(Provider) p.SetDefaults() p.Endpoint.Address = ts.URL err := p.Init() require.NoError(t, err) // fudge client, avoid starting up via Provide p.client, err = createClient(p.namespace, p.Endpoint) require.NoError(t, err) // make the query for services items, err := p.getNomadServiceDataWithEmptyServices(t.Context()) require.NoError(t, err) require.Len(t, items, 2) } func Test_getNomadServiceDataWithEmptyServices_TCP(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case strings.HasSuffix(r.RequestURI, "/v1/jobs"): _, _ = w.Write(responses["jobs_job7"]) case strings.HasSuffix(r.RequestURI, "/v1/job/job7"): _, _ = w.Write(responses["job_job7_TCP"]) case strings.HasSuffix(r.RequestURI, "/v1/service/job7"): _, _ = w.Write(responses["service_job7"]) } })) t.Cleanup(ts.Close) p := new(Provider) p.SetDefaults() p.Endpoint.Address = ts.URL err := p.Init() require.NoError(t, err) // fudge client, avoid starting up via Provide p.client, err = createClient(p.namespace, p.Endpoint) require.NoError(t, err) // make the query for services items, err := p.getNomadServiceDataWithEmptyServices(t.Context()) require.NoError(t, err) require.Len(t, items, 1) } func Test_getNomadServiceDataWithEmptyServices_UDP(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case strings.HasSuffix(r.RequestURI, "/v1/jobs"): _, _ = w.Write(responses["jobs_job8"]) case strings.HasSuffix(r.RequestURI, "/v1/job/job8"): _, _ = w.Write(responses["job_job8_UDP"]) case strings.HasSuffix(r.RequestURI, "/v1/service/job8"): _, _ = w.Write(responses["service_job8"]) } })) t.Cleanup(ts.Close) p := new(Provider) p.SetDefaults() p.Endpoint.Address = ts.URL err := p.Init() require.NoError(t, err) // fudge client, avoid starting up via Provide p.client, err = createClient(p.namespace, p.Endpoint) require.NoError(t, err) // make the query for services items, err := p.getNomadServiceDataWithEmptyServices(t.Context()) require.NoError(t, err) require.Len(t, items, 1) } func Test_getNomadServiceDataWithEmptyServices_ScalingEnabled_Stopped(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case strings.HasSuffix(r.RequestURI, "/v1/jobs"): _, _ = w.Write(responses["jobs_job9"]) case strings.HasSuffix(r.RequestURI, "/v1/job/job9"): _, _ = w.Write(responses["job_job9_ScalingEnabled_Stopped"]) case strings.HasSuffix(r.RequestURI, "/v1/service/job9"): _, _ = w.Write(responses["service_job9"]) } })) t.Cleanup(ts.Close) p := new(Provider) p.SetDefaults() p.Endpoint.Address = ts.URL err := p.Init() require.NoError(t, err) // fudge client, avoid starting up via Provide p.client, err = createClient(p.namespace, p.Endpoint) require.NoError(t, err) // make the query for services items, err := p.getNomadServiceDataWithEmptyServices(t.Context()) require.NoError(t, err) // Should not be listed as job is stopped require.Empty(t, items) } func setup() error { responsesDir := "./fixtures" files, err := os.ReadDir(responsesDir) if err != nil { return err } for _, file := range files { if !file.IsDir() && filepath.Ext(file.Name()) == ".json" { content, err := os.ReadFile(filepath.Join(responsesDir, file.Name())) if err != nil { return err } responses[strings.TrimSuffix(filepath.Base(file.Name()), filepath.Ext(file.Name()))] = content } } return nil } func Test_getNomadServiceData(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case strings.HasSuffix(r.RequestURI, "/v1/services"): _, _ = w.Write(responses["services"]) case strings.HasSuffix(r.RequestURI, "/v1/service/redis"): _, _ = w.Write(responses["service_redis"]) case strings.HasSuffix(r.RequestURI, "/v1/service/hello-nomad"): _, _ = w.Write(responses["service_hello"]) } })) t.Cleanup(ts.Close) p := new(Provider) p.SetDefaults() p.Endpoint.Address = ts.URL err := p.Init() require.NoError(t, err) // fudge client, avoid starting up via Provide p.client, err = createClient(p.namespace, p.Endpoint) require.NoError(t, err) // make the query for services items, err := p.getNomadServiceData(t.Context()) require.NoError(t, err) require.Len(t, items, 2) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/nomad/tag.go
pkg/provider/nomad/tag.go
package nomad import ( "strings" ) func tagsToLabels(tags []string, prefix string) map[string]string { labels := make(map[string]string, len(tags)) for _, tag := range tags { if strings.HasPrefix(tag, prefix) { if parts := strings.SplitN(tag, "=", 2); len(parts) == 2 { left, right := strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]) key := "traefik." + strings.TrimPrefix(left, prefix+".") labels[key] = right } } } return labels }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/constraints/constraints_tags.go
pkg/provider/constraints/constraints_tags.go
package constraints import ( "errors" "regexp" "slices" "github.com/vulcand/predicate" ) type constraintTagFunc func([]string) bool // MatchTags reports whether the expression matches with the given tags. // The expression must match any logical boolean combination of: // - `Tag(tagValue)` // - `TagRegex(regexValue)`. func MatchTags(tags []string, expr string) (bool, error) { if expr == "" { return true, nil } p, err := predicate.NewParser(predicate.Def{ Operators: predicate.Operators{ AND: andTagFunc, NOT: notTagFunc, OR: orTagFunc, }, Functions: map[string]interface{}{ "Tag": tagFn, "TagRegex": tagRegexFn, }, }) if err != nil { return false, err } parse, err := p.Parse(expr) if err != nil { return false, err } fn, ok := parse.(constraintTagFunc) if !ok { return false, errors.New("not a constraintTagFunc") } return fn(tags), nil } func tagFn(name string) constraintTagFunc { return func(tags []string) bool { return slices.Contains(tags, name) } } func tagRegexFn(expr string) constraintTagFunc { return func(tags []string) bool { exp, err := regexp.Compile(expr) if err != nil { return false } return slices.ContainsFunc(tags, func(tag string) bool { return exp.MatchString(tag) }) } } func andTagFunc(a, b constraintTagFunc) constraintTagFunc { return func(tags []string) bool { return a(tags) && b(tags) } } func orTagFunc(a, b constraintTagFunc) constraintTagFunc { return func(tags []string) bool { return a(tags) || b(tags) } } func notTagFunc(a constraintTagFunc) constraintTagFunc { return func(tags []string) bool { return !a(tags) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/constraints/constraints_tags_test.go
pkg/provider/constraints/constraints_tags_test.go
package constraints import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMatchTags(t *testing.T) { testCases := []struct { expr string tags []string expected bool expectedErr bool }{ { expr: `Tag("world")`, tags: []string{"hello", "world"}, expected: true, }, { expr: `Tag("worlds")`, tags: []string{"hello", "world"}, expected: false, }, { expr: `!Tag("world")`, tags: []string{"hello", "world"}, expected: false, }, { expr: `Tag("hello") && Tag("world")`, tags: []string{"hello", "world"}, expected: true, }, { expr: `Tag("hello") && Tag("worlds")`, tags: []string{"hello", "world"}, expected: false, }, { expr: `Tag("hello") && !Tag("world")`, tags: []string{"hello", "world"}, expected: false, }, { expr: `Tag("hello") || Tag( "world")`, tags: []string{"hello", "world"}, expected: true, }, { expr: `Tag( "worlds") || Tag("hello")`, tags: []string{"hello", "world"}, expected: true, }, { expr: `Tag("hello") || !Tag("world")`, tags: []string{"hello", "world"}, expected: true, }, { expr: `Tag()`, tags: []string{"hello", "world"}, expectedErr: true, }, { expr: `Foo("hello")`, tags: []string{"hello", "world"}, expectedErr: true, }, { expr: `Tag("hello")`, expected: false, }, { expr: ``, expected: true, }, { expr: `TagRegex("hel\\w+")`, tags: []string{"hello", "world"}, expected: true, }, { expr: `TagRegex("hell\\w+s")`, tags: []string{"hello", "world"}, expected: false, }, { expr: `!TagRegex("hel\\w+")`, tags: []string{"hello", "world"}, expected: false, }, } for _, test := range testCases { t.Run(test.expr, func(t *testing.T) { t.Parallel() matches, err := MatchTags(test.tags, test.expr) if test.expectedErr { require.Error(t, err) } else { require.NoError(t, err) } assert.Equal(t, test.expected, matches) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/constraints/constraints_labels.go
pkg/provider/constraints/constraints_labels.go
package constraints import ( "errors" "regexp" "github.com/vulcand/predicate" ) type constraintLabelFunc func(map[string]string) bool // MatchLabels reports whether the expression matches with the given labels. // The expression must match any logical boolean combination of: // - `Label(labelName, labelValue)` // - `LabelRegex(labelName, regexValue)`. func MatchLabels(labels map[string]string, expr string) (bool, error) { if expr == "" { return true, nil } p, err := predicate.NewParser(predicate.Def{ Operators: predicate.Operators{ AND: andLabelFunc, NOT: notLabelFunc, OR: orLabelFunc, }, Functions: map[string]interface{}{ "Label": labelFn, "LabelRegex": labelRegexFn, }, }) if err != nil { return false, err } parse, err := p.Parse(expr) if err != nil { return false, err } fn, ok := parse.(constraintLabelFunc) if !ok { return false, errors.New("not a constraintLabelFunc") } return fn(labels), nil } func labelFn(name, value string) constraintLabelFunc { return func(labels map[string]string) bool { return labels[name] == value } } func labelRegexFn(name, expr string) constraintLabelFunc { return func(labels map[string]string) bool { matched, err := regexp.MatchString(expr, labels[name]) if err != nil { return false } return matched } } func andLabelFunc(a, b constraintLabelFunc) constraintLabelFunc { return func(labels map[string]string) bool { return a(labels) && b(labels) } } func orLabelFunc(a, b constraintLabelFunc) constraintLabelFunc { return func(labels map[string]string) bool { return a(labels) || b(labels) } } func notLabelFunc(a constraintLabelFunc) constraintLabelFunc { return func(labels map[string]string) bool { return !a(labels) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/constraints/constraints_labels_test.go
pkg/provider/constraints/constraints_labels_test.go
package constraints import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMatchLabels(t *testing.T) { testCases := []struct { expr string labels map[string]string expected bool expectedErr bool }{ { expr: `Label("hello", "world")`, labels: map[string]string{ "hello": "world", "foo": "bar", }, expected: true, }, { expr: `Label("hello", "worlds")`, labels: map[string]string{ "hello": "world", "foo": "bar", }, expected: false, }, { expr: `Label("hi", "world")`, labels: map[string]string{ "hello": "world", "foo": "bar", }, expected: false, }, { expr: `!Label("hello", "world")`, labels: map[string]string{ "hello": "world", "foo": "bar", }, expected: false, }, { expr: `Label("hello", "world") && Label("foo", "bar")`, labels: map[string]string{ "hello": "world", "foo": "bar", }, expected: true, }, { expr: `Label("hello", "worlds") && Label("foo", "bar")`, labels: map[string]string{ "hello": "world", "foo": "bar", }, expected: false, }, { expr: `Label("hello", "world") && !Label("foo", "bar")`, labels: map[string]string{ "hello": "world", "foo": "bar", }, expected: false, }, { expr: `Label("hello", "world") || Label("foo", "bar")`, labels: map[string]string{ "hello": "world", "foo": "bar", }, expected: true, }, { expr: `Label("hello", "worlds") || Label("foo", "bar")`, labels: map[string]string{ "hello": "world", "foo": "bar", }, expected: true, }, { expr: `Label("hello", "world") || !Label("foo", "bar")`, labels: map[string]string{ "hello": "world", "foo": "bar", }, expected: true, }, { expr: `Label("hello")`, labels: map[string]string{ "hello": "world", "foo": "bar", }, expectedErr: true, }, { expr: `Foo("hello")`, labels: map[string]string{ "hello": "world", "foo": "bar", }, expectedErr: true, }, { expr: `Label("hello", "bar")`, expected: false, }, { expr: ``, expected: true, }, { expr: `LabelRegex("hello", "w\\w+")`, labels: map[string]string{ "hello": "world", "foo": "bar", }, expected: true, }, { expr: `LabelRegex("hello", "w\\w+s")`, labels: map[string]string{ "hello": "world", "foo": "bar", }, expected: false, }, { expr: `LabelRegex("hi", "w\\w+")`, labels: map[string]string{ "hello": "world", "foo": "bar", }, expected: false, }, { expr: `!LabelRegex("hello", "w\\w+")`, labels: map[string]string{ "hello": "world", "foo": "bar", }, expected: false, }, { expr: `LabelRegex("hello", "w(\\w+")`, labels: map[string]string{ "hello": "world", "foo": "bar", }, expected: false, }, } for _, test := range testCases { t.Run(test.expr, func(t *testing.T) { t.Parallel() matches, err := MatchLabels(test.labels, test.expr) if test.expectedErr { require.Error(t, err) } else { require.NoError(t, err) } assert.Equal(t, test.expected, matches) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kv/kv.go
pkg/provider/kv/kv.go
package kv import ( "context" "errors" "fmt" "path" "time" "github.com/cenkalti/backoff/v4" "github.com/kvtools/valkeyrie" "github.com/kvtools/valkeyrie/store" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/kv" "github.com/traefik/traefik/v3/pkg/job" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/safe" ) // Provider holds configurations of the provider. type Provider struct { RootKey string `description:"Root key used for KV store." json:"rootKey,omitempty" toml:"rootKey,omitempty" yaml:"rootKey,omitempty"` Endpoints []string `description:"KV store endpoints." json:"endpoints,omitempty" toml:"endpoints,omitempty" yaml:"endpoints,omitempty"` name string kvClient store.Store } // SetDefaults sets the default values. func (p *Provider) SetDefaults() { p.RootKey = "traefik" } // Init the provider. func (p *Provider) Init(storeType, name string, config valkeyrie.Config) error { ctx := log.With().Str(logs.ProviderName, name).Logger().WithContext(context.Background()) p.name = name kvClient, err := p.createKVClient(ctx, storeType, config) if err != nil { return fmt.Errorf("failed to Connect to KV store: %w", err) } p.kvClient = kvClient return nil } // Provide allows the docker provider to provide configurations to traefik using the given configuration channel. func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error { logger := log.With().Str(logs.ProviderName, p.name).Logger() ctx := logger.WithContext(context.Background()) operation := func() error { if _, err := p.kvClient.Exists(ctx, path.Join(p.RootKey, "qmslkjdfmqlskdjfmqlksjazcueznbvbwzlkajzebvkwjdcqmlsfj"), nil); err != nil { return fmt.Errorf("KV store connection error: %w", err) } return nil } notify := func(err error, time time.Duration) { logger.Error().Err(err).Msgf("KV connection error, retrying in %s", time) } err := backoff.RetryNotify(safe.OperationWithRecover(operation), backoff.WithContext(job.NewBackOff(backoff.NewExponentialBackOff()), ctx), notify) if err != nil { return fmt.Errorf("cannot connect to KV server: %w", err) } configuration, err := p.buildConfiguration(ctx) if err != nil { logger.Error().Err(err).Msg("Cannot build the configuration") } else { configurationChan <- dynamic.Message{ ProviderName: p.name, Configuration: configuration, } } pool.GoCtx(func(ctxPool context.Context) { ctxLog := logger.With().Str(logs.ProviderName, p.name).Logger().WithContext(ctxPool) err := p.watchKv(ctxLog, configurationChan) if err != nil { logger.Error().Err(err).Msg("Cannot retrieve data") } }) return nil } func (p *Provider) watchKv(ctx context.Context, configurationChan chan<- dynamic.Message) error { operation := func() error { events, err := p.kvClient.WatchTree(ctx, p.RootKey, nil) if err != nil { return fmt.Errorf("failed to watch KV: %w", err) } for { select { case <-ctx.Done(): return nil case _, ok := <-events: if !ok { return errors.New("the WatchTree channel is closed") } configuration, errC := p.buildConfiguration(ctx) if errC != nil { return errC } if configuration != nil { configurationChan <- dynamic.Message{ ProviderName: p.name, Configuration: configuration, } } } } } notify := func(err error, time time.Duration) { log.Ctx(ctx).Error().Err(err).Msgf("Provider error, retrying in %s", time) } return backoff.RetryNotify(safe.OperationWithRecover(operation), backoff.WithContext(job.NewBackOff(backoff.NewExponentialBackOff()), ctx), notify) } func (p *Provider) buildConfiguration(ctx context.Context) (*dynamic.Configuration, error) { pairs, err := p.kvClient.List(ctx, p.RootKey, nil) if err != nil { if errors.Is(err, store.ErrKeyNotFound) { // This empty configuration satisfies the pkg/server/configurationwatcher.go isEmptyConfiguration func constraints, // and will not be discarded by the configuration watcher. return &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: make(map[string]*dynamic.Router), }, }, nil } return nil, err } cfg := &dynamic.Configuration{} err = kv.Decode(pairs, cfg, p.RootKey) if err != nil { return nil, err } return cfg, nil } func (p *Provider) createKVClient(ctx context.Context, storeType string, config valkeyrie.Config) (store.Store, error) { kvStore, err := valkeyrie.NewStore(ctx, storeType, p.Endpoints, config) if err != nil { return nil, err } return &storeWrapper{Store: kvStore}, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kv/kv_mock_test.go
pkg/provider/kv/kv_mock_test.go
package kv import ( "context" "errors" "strings" "github.com/kvtools/valkeyrie/store" ) func newProviderMock(kvPairs []*store.KVPair) *Provider { return &Provider{ RootKey: "traefik", kvClient: newKvClientMock(kvPairs, nil), } } // Override Get/List to return a error. type KvError struct { Get error List error } // Extremely limited mock store so we can test initialization. type Mock struct { Error KvError KVPairs []*store.KVPair WatchTreeMethod func() <-chan []*store.KVPair } func newKvClientMock(kvPairs []*store.KVPair, err error) *Mock { mock := &Mock{ KVPairs: kvPairs, } if err != nil { mock.Error = KvError{ Get: err, List: err, } } return mock } func (s *Mock) Put(ctx context.Context, key string, value []byte, opts *store.WriteOptions) error { return errors.New("method Put not supported") } func (s *Mock) Get(ctx context.Context, key string, options *store.ReadOptions) (*store.KVPair, error) { if err := s.Error.Get; err != nil { return nil, err } for _, kvPair := range s.KVPairs { if kvPair.Key == key { return kvPair, nil } } return nil, store.ErrKeyNotFound } func (s *Mock) Delete(ctx context.Context, key string) error { return errors.New("method Delete not supported") } // Exists mock. func (s *Mock) Exists(ctx context.Context, key string, options *store.ReadOptions) (bool, error) { if err := s.Error.Get; err != nil { return false, err } for _, kvPair := range s.KVPairs { if strings.HasPrefix(kvPair.Key, key) { return true, nil } } return false, store.ErrKeyNotFound } // Watch mock. func (s *Mock) Watch(ctx context.Context, key string, options *store.ReadOptions) (<-chan *store.KVPair, error) { return nil, errors.New("method Watch not supported") } // WatchTree mock. func (s *Mock) WatchTree(ctx context.Context, prefix string, options *store.ReadOptions) (<-chan []*store.KVPair, error) { return s.WatchTreeMethod(), nil } // NewLock mock. func (s *Mock) NewLock(ctx context.Context, key string, options *store.LockOptions) (store.Locker, error) { return nil, errors.New("method NewLock not supported") } // List mock. func (s *Mock) List(ctx context.Context, prefix string, options *store.ReadOptions) ([]*store.KVPair, error) { if err := s.Error.List; err != nil { return nil, err } var kv []*store.KVPair for _, kvPair := range s.KVPairs { if strings.HasPrefix(kvPair.Key, prefix) { kv = append(kv, kvPair) } } return kv, nil } // DeleteTree mock. func (s *Mock) DeleteTree(ctx context.Context, prefix string) error { return errors.New("method DeleteTree not supported") } // AtomicPut mock. func (s *Mock) AtomicPut(ctx context.Context, key string, value []byte, previous *store.KVPair, opts *store.WriteOptions) (bool, *store.KVPair, error) { return false, nil, errors.New("method AtomicPut not supported") } // AtomicDelete mock. func (s *Mock) AtomicDelete(ctx context.Context, key string, previous *store.KVPair) (bool, error) { return false, errors.New("method AtomicDelete not supported") } // Close mock. func (s *Mock) Close() error { return nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kv/storewrapper.go
pkg/provider/kv/storewrapper.go
package kv import ( "context" "github.com/kvtools/valkeyrie/store" "github.com/rs/zerolog/log" ) type storeWrapper struct { store.Store } func (s *storeWrapper) Put(ctx context.Context, key string, value []byte, options *store.WriteOptions) error { log.Debug().Msgf("Put: %s %s", key, string(value)) if s.Store == nil { return nil } return s.Store.Put(ctx, key, value, options) } func (s *storeWrapper) Get(ctx context.Context, key string, options *store.ReadOptions) (*store.KVPair, error) { log.Debug().Msgf("Get: %s", key) if s.Store == nil { return nil, nil } return s.Store.Get(ctx, key, options) } func (s *storeWrapper) Delete(ctx context.Context, key string) error { log.Debug().Msgf("Delete: %s", key) if s.Store == nil { return nil } return s.Store.Delete(ctx, key) } func (s *storeWrapper) Exists(ctx context.Context, key string, options *store.ReadOptions) (bool, error) { log.Debug().Msgf("Exists: %s", key) if s.Store == nil { return true, nil } return s.Store.Exists(ctx, key, options) } func (s *storeWrapper) Watch(ctx context.Context, key string, options *store.ReadOptions) (<-chan *store.KVPair, error) { log.Debug().Msgf("Watch: %s", key) if s.Store == nil { return nil, nil } return s.Store.Watch(ctx, key, options) } func (s *storeWrapper) WatchTree(ctx context.Context, directory string, options *store.ReadOptions) (<-chan []*store.KVPair, error) { log.Debug().Msgf("WatchTree: %s", directory) if s.Store == nil { return nil, nil } return s.Store.WatchTree(ctx, directory, options) } func (s *storeWrapper) NewLock(ctx context.Context, key string, options *store.LockOptions) (store.Locker, error) { log.Debug().Msgf("NewLock: %s", key) if s.Store == nil { return nil, nil } return s.Store.NewLock(ctx, key, options) } func (s *storeWrapper) List(ctx context.Context, directory string, options *store.ReadOptions) ([]*store.KVPair, error) { log.Debug().Msgf("List: %s", directory) if s.Store == nil { return nil, nil } return s.Store.List(ctx, directory, options) } func (s *storeWrapper) DeleteTree(ctx context.Context, directory string) error { log.Debug().Msgf("DeleteTree: %s", directory) if s.Store == nil { return nil } return s.Store.DeleteTree(ctx, directory) } func (s *storeWrapper) AtomicPut(ctx context.Context, key string, value []byte, previous *store.KVPair, options *store.WriteOptions) (bool, *store.KVPair, error) { log.Debug().Msgf("AtomicPut: %s %s %v", key, string(value), previous) if s.Store == nil { return true, nil, nil } return s.Store.AtomicPut(ctx, key, value, previous, options) } func (s *storeWrapper) AtomicDelete(ctx context.Context, key string, previous *store.KVPair) (bool, error) { log.Debug().Msgf("AtomicDelete: %s %v", key, previous) if s.Store == nil { return true, nil } return s.Store.AtomicDelete(ctx, key, previous) } func (s *storeWrapper) Close() error { log.Debug().Msg("Close") if s.Store == nil { return nil } return s.Store.Close() }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kv/kv_test.go
pkg/provider/kv/kv_test.go
package kv import ( "errors" "testing" "time" "github.com/kvtools/valkeyrie/store" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" ) func pointer[T any](v T) *T { return &v } func Test_buildConfiguration(t *testing.T) { provider := newProviderMock(mapToPairs(map[string]string{ "traefik/http/routers/Router0/entryPoints/0": "foobar", "traefik/http/routers/Router0/entryPoints/1": "foobar", "traefik/http/routers/Router0/middlewares/0": "foobar", "traefik/http/routers/Router0/middlewares/1": "foobar", "traefik/http/routers/Router0/service": "foobar", "traefik/http/routers/Router0/rule": "foobar", "traefik/http/routers/Router0/priority": "42", "traefik/http/routers/Router0/tls": "", "traefik/http/routers/Router1/rule": "foobar", "traefik/http/routers/Router1/priority": "42", "traefik/http/routers/Router1/tls/domains/0/main": "foobar", "traefik/http/routers/Router1/tls/domains/0/sans/0": "foobar", "traefik/http/routers/Router1/tls/domains/0/sans/1": "foobar", "traefik/http/routers/Router1/tls/domains/1/main": "foobar", "traefik/http/routers/Router1/tls/domains/1/sans/0": "foobar", "traefik/http/routers/Router1/tls/domains/1/sans/1": "foobar", "traefik/http/routers/Router1/tls/options": "foobar", "traefik/http/routers/Router1/tls/certResolver": "foobar", "traefik/http/routers/Router1/entryPoints/0": "foobar", "traefik/http/routers/Router1/entryPoints/1": "foobar", "traefik/http/routers/Router1/middlewares/0": "foobar", "traefik/http/routers/Router1/middlewares/1": "foobar", "traefik/http/routers/Router1/service": "foobar", "traefik/http/services/Service01/loadBalancer/healthCheck/path": "foobar", "traefik/http/services/Service01/loadBalancer/healthCheck/port": "42", "traefik/http/services/Service01/loadBalancer/healthCheck/interval": "1s", "traefik/http/services/Service01/loadBalancer/healthCheck/unhealthyinterval": "1s", "traefik/http/services/Service01/loadBalancer/healthCheck/timeout": "1s", "traefik/http/services/Service01/loadBalancer/healthCheck/hostname": "foobar", "traefik/http/services/Service01/loadBalancer/healthCheck/headers/name0": "foobar", "traefik/http/services/Service01/loadBalancer/healthCheck/headers/name1": "foobar", "traefik/http/services/Service01/loadBalancer/healthCheck/scheme": "foobar", "traefik/http/services/Service01/loadBalancer/healthCheck/mode": "foobar", "traefik/http/services/Service01/loadBalancer/healthCheck/followredirects": "true", "traefik/http/services/Service01/loadBalancer/responseForwarding/flushInterval": "1s", "traefik/http/services/Service01/loadBalancer/passHostHeader": "true", "traefik/http/services/Service01/loadBalancer/sticky/cookie/name": "foobar", "traefik/http/services/Service01/loadBalancer/sticky/cookie/secure": "true", "traefik/http/services/Service01/loadBalancer/sticky/cookie/httpOnly": "true", "traefik/http/services/Service01/loadBalancer/sticky/cookie/path": "foobar", "traefik/http/services/Service01/loadBalancer/strategy": "foobar", "traefik/http/services/Service01/loadBalancer/servers/0/url": "foobar", "traefik/http/services/Service01/loadBalancer/servers/1/url": "foobar", "traefik/http/services/Service02/mirroring/service": "foobar", "traefik/http/services/Service02/mirroring/mirrorBody": "true", "traefik/http/services/Service02/mirroring/maxBodySize": "42", "traefik/http/services/Service02/mirroring/mirrors/0/name": "foobar", "traefik/http/services/Service02/mirroring/mirrors/0/percent": "42", "traefik/http/services/Service02/mirroring/mirrors/1/name": "foobar", "traefik/http/services/Service02/mirroring/mirrors/1/percent": "42", "traefik/http/services/Service03/weighted/sticky/cookie/name": "foobar", "traefik/http/services/Service03/weighted/sticky/cookie/secure": "true", "traefik/http/services/Service03/weighted/sticky/cookie/httpOnly": "true", "traefik/http/services/Service03/weighted/sticky/cookie/path": "foobar", "traefik/http/services/Service03/weighted/services/0/name": "foobar", "traefik/http/services/Service03/weighted/services/0/weight": "42", "traefik/http/services/Service03/weighted/services/1/name": "foobar", "traefik/http/services/Service03/weighted/services/1/weight": "42", "traefik/http/services/Service04/failover/service": "foobar", "traefik/http/services/Service04/failover/fallback": "foobar", "traefik/http/middlewares/Middleware08/forwardAuth/authResponseHeaders/0": "foobar", "traefik/http/middlewares/Middleware08/forwardAuth/authResponseHeaders/1": "foobar", "traefik/http/middlewares/Middleware08/forwardAuth/authRequestHeaders/0": "foobar", "traefik/http/middlewares/Middleware08/forwardAuth/authRequestHeaders/1": "foobar", "traefik/http/middlewares/Middleware08/forwardAuth/tls/key": "foobar", "traefik/http/middlewares/Middleware08/forwardAuth/tls/insecureSkipVerify": "true", "traefik/http/middlewares/Middleware08/forwardAuth/tls/ca": "foobar", "traefik/http/middlewares/Middleware08/forwardAuth/tls/caOptional": "true", "traefik/http/middlewares/Middleware08/forwardAuth/tls/cert": "foobar", "traefik/http/middlewares/Middleware08/forwardAuth/address": "foobar", "traefik/http/middlewares/Middleware08/forwardAuth/trustForwardHeader": "true", "traefik/http/middlewares/Middleware08/forwardAuth/forwardBody": "true", "traefik/http/middlewares/Middleware08/forwardAuth/maxBodySize": "42", "traefik/http/middlewares/Middleware08/forwardAuth/preserveLocationHeader": "true", "traefik/http/middlewares/Middleware08/forwardAuth/preserveRequestMethod": "true", "traefik/http/middlewares/Middleware15/redirectScheme/scheme": "foobar", "traefik/http/middlewares/Middleware15/redirectScheme/port": "foobar", "traefik/http/middlewares/Middleware15/redirectScheme/permanent": "true", "traefik/http/middlewares/Middleware17/replacePathRegex/regex": "foobar", "traefik/http/middlewares/Middleware17/replacePathRegex/replacement": "foobar", "traefik/http/middlewares/Middleware14/redirectRegex/regex": "foobar", "traefik/http/middlewares/Middleware14/redirectRegex/replacement": "foobar", "traefik/http/middlewares/Middleware14/redirectRegex/permanent": "true", "traefik/http/middlewares/Middleware16/replacePath/path": "foobar", "traefik/http/middlewares/Middleware06/digestAuth/removeHeader": "true", "traefik/http/middlewares/Middleware06/digestAuth/realm": "foobar", "traefik/http/middlewares/Middleware06/digestAuth/headerField": "foobar", "traefik/http/middlewares/Middleware06/digestAuth/users/0": "foobar", "traefik/http/middlewares/Middleware06/digestAuth/users/1": "foobar", "traefik/http/middlewares/Middleware06/digestAuth/usersFile": "foobar", "traefik/http/middlewares/Middleware09/headers/accessControlAllowHeaders/0": "foobar", "traefik/http/middlewares/Middleware09/headers/accessControlAllowHeaders/1": "foobar", "traefik/http/middlewares/Middleware09/headers/accessControlAllowOriginList/0": "foobar", "traefik/http/middlewares/Middleware09/headers/accessControlAllowOriginList/1": "foobar", "traefik/http/middlewares/Middleware09/headers/accessControlAllowOriginListRegex/0": "foobar", "traefik/http/middlewares/Middleware09/headers/accessControlAllowOriginListRegex/1": "foobar", "traefik/http/middlewares/Middleware09/headers/contentTypeNosniff": "true", "traefik/http/middlewares/Middleware09/headers/accessControlAllowCredentials": "true", "traefik/http/middlewares/Middleware09/headers/featurePolicy": "foobar", "traefik/http/middlewares/Middleware09/headers/permissionsPolicy": "foobar", "traefik/http/middlewares/Middleware09/headers/forceSTSHeader": "true", "traefik/http/middlewares/Middleware09/headers/sslRedirect": "true", "traefik/http/middlewares/Middleware09/headers/sslHost": "foobar", "traefik/http/middlewares/Middleware09/headers/sslForceHost": "true", "traefik/http/middlewares/Middleware09/headers/sslProxyHeaders/name1": "foobar", "traefik/http/middlewares/Middleware09/headers/sslProxyHeaders/name0": "foobar", "traefik/http/middlewares/Middleware09/headers/allowedHosts/0": "foobar", "traefik/http/middlewares/Middleware09/headers/allowedHosts/1": "foobar", "traefik/http/middlewares/Middleware09/headers/stsPreload": "true", "traefik/http/middlewares/Middleware09/headers/frameDeny": "true", "traefik/http/middlewares/Middleware09/headers/isDevelopment": "true", "traefik/http/middlewares/Middleware09/headers/customResponseHeaders/name1": "foobar", "traefik/http/middlewares/Middleware09/headers/customResponseHeaders/name0": "foobar", "traefik/http/middlewares/Middleware09/headers/accessControlAllowMethods/0": "foobar", "traefik/http/middlewares/Middleware09/headers/accessControlAllowMethods/1": "foobar", "traefik/http/middlewares/Middleware09/headers/stsSeconds": "42", "traefik/http/middlewares/Middleware09/headers/stsIncludeSubdomains": "true", "traefik/http/middlewares/Middleware09/headers/customFrameOptionsValue": "foobar", "traefik/http/middlewares/Middleware09/headers/accessControlMaxAge": "42", "traefik/http/middlewares/Middleware09/headers/addVaryHeader": "true", "traefik/http/middlewares/Middleware09/headers/hostsProxyHeaders/0": "foobar", "traefik/http/middlewares/Middleware09/headers/hostsProxyHeaders/1": "foobar", "traefik/http/middlewares/Middleware09/headers/sslTemporaryRedirect": "true", "traefik/http/middlewares/Middleware09/headers/customBrowserXSSValue": "foobar", "traefik/http/middlewares/Middleware09/headers/referrerPolicy": "foobar", "traefik/http/middlewares/Middleware09/headers/accessControlExposeHeaders/0": "foobar", "traefik/http/middlewares/Middleware09/headers/accessControlExposeHeaders/1": "foobar", "traefik/http/middlewares/Middleware09/headers/contentSecurityPolicy": "foobar", "traefik/http/middlewares/Middleware09/headers/contentSecurityPolicyReportOnly": "foobar", "traefik/http/middlewares/Middleware09/headers/publicKey": "foobar", "traefik/http/middlewares/Middleware09/headers/customRequestHeaders/name0": "foobar", "traefik/http/middlewares/Middleware09/headers/customRequestHeaders/name1": "foobar", "traefik/http/middlewares/Middleware09/headers/browserXssFilter": "true", "traefik/http/middlewares/Middleware10/ipAllowList/sourceRange/0": "foobar", "traefik/http/middlewares/Middleware10/ipAllowList/sourceRange/1": "foobar", "traefik/http/middlewares/Middleware10/ipAllowList/ipStrategy/excludedIPs/0": "foobar", "traefik/http/middlewares/Middleware10/ipAllowList/ipStrategy/excludedIPs/1": "foobar", "traefik/http/middlewares/Middleware10/ipAllowList/ipStrategy/depth": "42", "traefik/http/middlewares/Middleware11/inFlightReq/amount": "42", "traefik/http/middlewares/Middleware11/inFlightReq/sourceCriterion/requestHost": "true", "traefik/http/middlewares/Middleware11/inFlightReq/sourceCriterion/ipStrategy/depth": "42", "traefik/http/middlewares/Middleware11/inFlightReq/sourceCriterion/ipStrategy/excludedIPs/0": "foobar", "traefik/http/middlewares/Middleware11/inFlightReq/sourceCriterion/ipStrategy/excludedIPs/1": "foobar", "traefik/http/middlewares/Middleware11/inFlightReq/sourceCriterion/requestHeaderName": "foobar", "traefik/http/middlewares/Middleware12/passTLSClientCert/pem": "true", "traefik/http/middlewares/Middleware12/passTLSClientCert/info/notAfter": "true", "traefik/http/middlewares/Middleware12/passTLSClientCert/info/notBefore": "true", "traefik/http/middlewares/Middleware12/passTLSClientCert/info/sans": "true", "traefik/http/middlewares/Middleware12/passTLSClientCert/info/subject/country": "true", "traefik/http/middlewares/Middleware12/passTLSClientCert/info/subject/province": "true", "traefik/http/middlewares/Middleware12/passTLSClientCert/info/subject/locality": "true", "traefik/http/middlewares/Middleware12/passTLSClientCert/info/subject/organization": "true", "traefik/http/middlewares/Middleware12/passTLSClientCert/info/subject/organizationalunit": "true", "traefik/http/middlewares/Middleware12/passTLSClientCert/info/subject/commonName": "true", "traefik/http/middlewares/Middleware12/passTLSClientCert/info/subject/serialNumber": "true", "traefik/http/middlewares/Middleware12/passTLSClientCert/info/subject/domainComponent": "true", "traefik/http/middlewares/Middleware12/passTLSClientCert/info/issuer/country": "true", "traefik/http/middlewares/Middleware12/passTLSClientCert/info/issuer/province": "true", "traefik/http/middlewares/Middleware12/passTLSClientCert/info/issuer/locality": "true", "traefik/http/middlewares/Middleware12/passTLSClientCert/info/issuer/organization": "true", "traefik/http/middlewares/Middleware12/passTLSClientCert/info/issuer/commonName": "true", "traefik/http/middlewares/Middleware12/passTLSClientCert/info/issuer/serialNumber": "true", "traefik/http/middlewares/Middleware12/passTLSClientCert/info/issuer/domainComponent": "true", "traefik/http/middlewares/Middleware00/addPrefix/prefix": "foobar", "traefik/http/middlewares/Middleware03/chain/middlewares/0": "foobar", "traefik/http/middlewares/Middleware03/chain/middlewares/1": "foobar", "traefik/http/middlewares/Middleware04/circuitBreaker/expression": "foobar", "traefik/http/middlewares/Middleware04/circuitBreaker/checkPeriod": "1s", "traefik/http/middlewares/Middleware04/circuitBreaker/fallbackDuration": "1s", "traefik/http/middlewares/Middleware04/circuitBreaker/recoveryDuration": "1s", "traefik/http/middlewares/Middleware04/circuitBreaker/responseCode": "404", "traefik/http/middlewares/Middleware07/errors/status/0": "foobar", "traefik/http/middlewares/Middleware07/errors/status/1": "foobar", "traefik/http/middlewares/Middleware07/errors/service": "foobar", "traefik/http/middlewares/Middleware07/errors/query": "foobar", "traefik/http/middlewares/Middleware13/rateLimit/average": "42", "traefik/http/middlewares/Middleware13/rateLimit/period": "1s", "traefik/http/middlewares/Middleware13/rateLimit/burst": "42", "traefik/http/middlewares/Middleware13/rateLimit/sourceCriterion/requestHeaderName": "foobar", "traefik/http/middlewares/Middleware13/rateLimit/sourceCriterion/requestHost": "true", "traefik/http/middlewares/Middleware13/rateLimit/sourceCriterion/ipStrategy/depth": "42", "traefik/http/middlewares/Middleware13/rateLimit/sourceCriterion/ipStrategy/excludedIPs/0": "foobar", "traefik/http/middlewares/Middleware13/rateLimit/sourceCriterion/ipStrategy/excludedIPs/1": "foobar", "traefik/http/middlewares/Middleware20/stripPrefixRegex/regex/0": "foobar", "traefik/http/middlewares/Middleware20/stripPrefixRegex/regex/1": "foobar", "traefik/http/middlewares/Middleware01/basicAuth/users/0": "foobar", "traefik/http/middlewares/Middleware01/basicAuth/users/1": "foobar", "traefik/http/middlewares/Middleware01/basicAuth/usersFile": "foobar", "traefik/http/middlewares/Middleware01/basicAuth/realm": "foobar", "traefik/http/middlewares/Middleware01/basicAuth/removeHeader": "true", "traefik/http/middlewares/Middleware01/basicAuth/headerField": "foobar", "traefik/http/middlewares/Middleware02/buffering/maxResponseBodyBytes": "42", "traefik/http/middlewares/Middleware02/buffering/memResponseBodyBytes": "42", "traefik/http/middlewares/Middleware02/buffering/retryExpression": "foobar", "traefik/http/middlewares/Middleware02/buffering/maxRequestBodyBytes": "42", "traefik/http/middlewares/Middleware02/buffering/memRequestBodyBytes": "42", "traefik/http/middlewares/Middleware05/compress/encodings": "foobar, foobar", "traefik/http/middlewares/Middleware05/compress/minResponseBodyBytes": "42", "traefik/http/middlewares/Middleware18/retry/attempts": "42", "traefik/http/middlewares/Middleware19/stripPrefix/prefixes/0": "foobar", "traefik/http/middlewares/Middleware19/stripPrefix/prefixes/1": "foobar", "traefik/http/middlewares/Middleware19/stripPrefix/forceSlash": "true", "traefik/tcp/routers/TCPRouter0/entryPoints/0": "foobar", "traefik/tcp/routers/TCPRouter0/entryPoints/1": "foobar", "traefik/tcp/routers/TCPRouter0/service": "foobar", "traefik/tcp/routers/TCPRouter0/rule": "foobar", "traefik/tcp/routers/TCPRouter0/tls/options": "foobar", "traefik/tcp/routers/TCPRouter0/tls/certResolver": "foobar", "traefik/tcp/routers/TCPRouter0/tls/domains/0/main": "foobar", "traefik/tcp/routers/TCPRouter0/tls/domains/0/sans/0": "foobar", "traefik/tcp/routers/TCPRouter0/tls/domains/0/sans/1": "foobar", "traefik/tcp/routers/TCPRouter0/tls/domains/1/main": "foobar", "traefik/tcp/routers/TCPRouter0/tls/domains/1/sans/0": "foobar", "traefik/tcp/routers/TCPRouter0/tls/domains/1/sans/1": "foobar", "traefik/tcp/routers/TCPRouter0/tls/passthrough": "true", "traefik/tcp/routers/TCPRouter1/entryPoints/0": "foobar", "traefik/tcp/routers/TCPRouter1/entryPoints/1": "foobar", "traefik/tcp/routers/TCPRouter1/service": "foobar", "traefik/tcp/routers/TCPRouter1/rule": "foobar", "traefik/tcp/routers/TCPRouter1/tls/domains/0/main": "foobar", "traefik/tcp/routers/TCPRouter1/tls/domains/0/sans/0": "foobar", "traefik/tcp/routers/TCPRouter1/tls/domains/0/sans/1": "foobar", "traefik/tcp/routers/TCPRouter1/tls/domains/1/main": "foobar", "traefik/tcp/routers/TCPRouter1/tls/domains/1/sans/0": "foobar", "traefik/tcp/routers/TCPRouter1/tls/domains/1/sans/1": "foobar", "traefik/tcp/routers/TCPRouter1/tls/passthrough": "true", "traefik/tcp/routers/TCPRouter1/tls/options": "foobar", "traefik/tcp/routers/TCPRouter1/tls/certResolver": "foobar", "traefik/tcp/services/TCPService01/loadBalancer/terminationDelay": "42", "traefik/tcp/services/TCPService01/loadBalancer/servers/0/address": "foobar", "traefik/tcp/services/TCPService01/loadBalancer/servers/1/address": "foobar", "traefik/tcp/services/TCPService02/weighted/services/0/name": "foobar", "traefik/tcp/services/TCPService02/weighted/services/0/weight": "42", "traefik/tcp/services/TCPService02/weighted/services/1/name": "foobar", "traefik/tcp/services/TCPService02/weighted/services/1/weight": "43", "traefik/udp/routers/UDPRouter0/entrypoints/0": "foobar", "traefik/udp/routers/UDPRouter0/entrypoints/1": "foobar", "traefik/udp/routers/UDPRouter0/service": "foobar", "traefik/udp/routers/UDPRouter1/entrypoints/0": "foobar", "traefik/udp/routers/UDPRouter1/entrypoints/1": "foobar", "traefik/udp/routers/UDPRouter1/service": "foobar", "traefik/udp/services/UDPService01/loadBalancer/servers/0/address": "foobar", "traefik/udp/services/UDPService01/loadBalancer/servers/1/address": "foobar", "traefik/udp/services/UDPService02/loadBalancer/servers/0/address": "foobar", "traefik/udp/services/UDPService02/loadBalancer/servers/1/address": "foobar", "traefik/tls/options/Options0/minVersion": "foobar", "traefik/tls/options/Options0/maxVersion": "foobar", "traefik/tls/options/Options0/cipherSuites/0": "foobar", "traefik/tls/options/Options0/cipherSuites/1": "foobar", "traefik/tls/options/Options0/sniStrict": "true", "traefik/tls/options/Options0/curvePreferences/0": "foobar", "traefik/tls/options/Options0/curvePreferences/1": "foobar", "traefik/tls/options/Options0/clientAuth/caFiles/0": "foobar", "traefik/tls/options/Options0/clientAuth/caFiles/1": "foobar", "traefik/tls/options/Options0/clientAuth/clientAuthType": "foobar", "traefik/tls/options/Options1/sniStrict": "true", "traefik/tls/options/Options1/curvePreferences/0": "foobar", "traefik/tls/options/Options1/curvePreferences/1": "foobar", "traefik/tls/options/Options1/clientAuth/caFiles/0": "foobar", "traefik/tls/options/Options1/clientAuth/caFiles/1": "foobar", "traefik/tls/options/Options1/clientAuth/clientAuthType": "foobar", "traefik/tls/options/Options1/minVersion": "foobar", "traefik/tls/options/Options1/maxVersion": "foobar", "traefik/tls/options/Options1/cipherSuites/0": "foobar", "traefik/tls/options/Options1/cipherSuites/1": "foobar", "traefik/tls/stores/Store0/defaultCertificate/certFile": "foobar", "traefik/tls/stores/Store0/defaultCertificate/keyFile": "foobar", "traefik/tls/stores/Store1/defaultCertificate/certFile": "foobar", "traefik/tls/stores/Store1/defaultCertificate/keyFile": "foobar", "traefik/tls/certificates/0/certFile": "foobar", "traefik/tls/certificates/0/keyFile": "foobar", "traefik/tls/certificates/0/stores/0": "foobar", "traefik/tls/certificates/0/stores/1": "foobar", "traefik/tls/certificates/1/certFile": "foobar", "traefik/tls/certificates/1/keyFile": "foobar", "traefik/tls/certificates/1/stores/0": "foobar", "traefik/tls/certificates/1/stores/1": "foobar", })) cfg, err := provider.buildConfiguration(t.Context()) require.NoError(t, err) expected := &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "Router1": { EntryPoints: []string{ "foobar", "foobar", }, Middlewares: []string{ "foobar", "foobar", }, Service: "foobar", Rule: "foobar", Priority: 42, TLS: &dynamic.RouterTLSConfig{ Options: "foobar", CertResolver: "foobar", Domains: []types.Domain{ { Main: "foobar", SANs: []string{ "foobar", "foobar", }, }, { Main: "foobar", SANs: []string{ "foobar", "foobar", }, }, }, }, }, "Router0": { EntryPoints: []string{ "foobar", "foobar", }, Middlewares: []string{ "foobar", "foobar", }, Service: "foobar", Rule: "foobar", Priority: 42, TLS: &dynamic.RouterTLSConfig{}, }, }, Middlewares: map[string]*dynamic.Middleware{ "Middleware10": { IPAllowList: &dynamic.IPAllowList{ SourceRange: []string{ "foobar", "foobar", }, IPStrategy: &dynamic.IPStrategy{ Depth: 42, ExcludedIPs: []string{ "foobar", "foobar", }, }, }, }, "Middleware13": { RateLimit: &dynamic.RateLimit{ Average: 42, Burst: 42, Period: ptypes.Duration(time.Second), SourceCriterion: &dynamic.SourceCriterion{ IPStrategy: &dynamic.IPStrategy{ Depth: 42, ExcludedIPs: []string{ "foobar", "foobar", }, }, RequestHeaderName: "foobar", RequestHost: true, }, }, }, "Middleware19": { StripPrefix: &dynamic.StripPrefix{ Prefixes: []string{ "foobar", "foobar", }, ForceSlash: pointer(true), }, }, "Middleware00": { AddPrefix: &dynamic.AddPrefix{ Prefix: "foobar", }, }, "Middleware02": { Buffering: &dynamic.Buffering{ MaxRequestBodyBytes: 42, MemRequestBodyBytes: 42, MaxResponseBodyBytes: 42, MemResponseBodyBytes: 42, RetryExpression: "foobar", }, }, "Middleware04": { CircuitBreaker: &dynamic.CircuitBreaker{ Expression: "foobar", CheckPeriod: ptypes.Duration(time.Second), FallbackDuration: ptypes.Duration(time.Second), RecoveryDuration: ptypes.Duration(time.Second), ResponseCode: 404, }, }, "Middleware05": { Compress: &dynamic.Compress{ MinResponseBodyBytes: 42, Encodings: []string{ "foobar", "foobar", }, }, }, "Middleware08": { ForwardAuth: &dynamic.ForwardAuth{ Address: "foobar", TLS: &dynamic.ClientTLS{ CA: "foobar", Cert: "foobar", Key: "foobar", InsecureSkipVerify: true, CAOptional: pointer(true),
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kv/consul/consul.go
pkg/provider/kv/consul/consul.go
package consul import ( "context" "errors" "fmt" "time" "github.com/kvtools/consul" "github.com/traefik/traefik/v3/pkg/provider" "github.com/traefik/traefik/v3/pkg/provider/kv" "github.com/traefik/traefik/v3/pkg/types" ) // providerName is the Consul provider name. const providerName = "consul" var _ provider.Provider = (*Provider)(nil) // ProviderBuilder is responsible for constructing namespaced instances of the Consul provider. type ProviderBuilder struct { kv.Provider `yaml:",inline" export:"true"` Token string `description:"Per-request ACL token." json:"token,omitempty" toml:"token,omitempty" yaml:"token,omitempty" loggable:"false"` TLS *types.ClientTLS `description:"Enable TLS support." json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" export:"true"` Namespaces []string `description:"Sets the namespaces used to discover the configuration (Consul Enterprise only)." json:"namespaces,omitempty" toml:"namespaces,omitempty" yaml:"namespaces,omitempty"` } // SetDefaults sets the default values. func (p *ProviderBuilder) SetDefaults() { p.Provider.SetDefaults() p.Endpoints = []string{"127.0.0.1:8500"} } // BuildProviders builds Consul provider instances for the given namespaces configuration. func (p *ProviderBuilder) BuildProviders() []*Provider { if len(p.Namespaces) == 0 { return []*Provider{{ Provider: p.Provider, name: providerName, token: p.Token, tls: p.TLS, }} } var providers []*Provider for _, namespace := range p.Namespaces { providers = append(providers, &Provider{ Provider: p.Provider, name: providerName + "-" + namespace, namespace: namespace, token: p.Token, tls: p.TLS, }) } return providers } // Provider holds configurations of the provider. type Provider struct { kv.Provider name string namespace string token string tls *types.ClientTLS } // Init the provider. func (p *Provider) Init() error { // Wildcard namespace allows fetching KV values from any namespace for recursive requests (see https://www.consul.io/api/kv#ns). // As we are not supporting multiple namespaces at the same time, wildcard namespace is not allowed. if p.namespace == "*" { return errors.New("wildcard namespace is not supported") } // In case they didn't initialize with BuildProviders. if p.name == "" { p.name = providerName } config := &consul.Config{ ConnectionTimeout: 3 * time.Second, Token: p.token, Namespace: p.namespace, } if p.tls != nil { var err error config.TLS, err = p.tls.CreateTLSConfig(context.Background()) if err != nil { return fmt.Errorf("unable to create client TLS configuration: %w", err) } } return p.Provider.Init(consul.StoreName, p.name, config) } // Namespace returns the namespace of the Consul provider. func (p *Provider) Namespace() string { return p.namespace }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kv/consul/consul_test.go
pkg/provider/kv/consul/consul_test.go
package consul import ( "testing" "github.com/stretchr/testify/assert" ) func TestNamespaces(t *testing.T) { testCases := []struct { desc string namespaces []string expectedNamespaces []string }{ { desc: "no defined namespaces", expectedNamespaces: []string{""}, }, { desc: "use of 1 defined namespaces", namespaces: []string{"test-ns"}, expectedNamespaces: []string{"test-ns"}, }, { desc: "use of multiple defined namespaces", namespaces: []string{"test-ns1", "test-ns2", "test-ns3", "test-ns4"}, expectedNamespaces: []string{"test-ns1", "test-ns2", "test-ns3", "test-ns4"}, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() pb := &ProviderBuilder{ Namespaces: test.namespaces, } assert.Equal(t, test.expectedNamespaces, extractNSFromProvider(pb.BuildProviders())) }) } } func extractNSFromProvider(providers []*Provider) []string { res := make([]string, len(providers)) for i, p := range providers { res[i] = p.namespace } return res }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kv/zk/zk.go
pkg/provider/kv/zk/zk.go
package zk import ( "time" "github.com/kvtools/zookeeper" "github.com/traefik/traefik/v3/pkg/provider" "github.com/traefik/traefik/v3/pkg/provider/kv" ) var _ provider.Provider = (*Provider)(nil) // Provider holds configurations of the provider. type Provider struct { kv.Provider `yaml:",inline" export:"true"` Username string `description:"Username for authentication." json:"username,omitempty" toml:"username,omitempty" yaml:"username,omitempty" loggable:"false"` Password string `description:"Password for authentication." json:"password,omitempty" toml:"password,omitempty" yaml:"password,omitempty" loggable:"false"` } // SetDefaults sets the default values. func (p *Provider) SetDefaults() { p.Provider.SetDefaults() p.Endpoints = []string{"127.0.0.1:2181"} } // Init the provider. func (p *Provider) Init() error { config := &zookeeper.Config{ ConnectionTimeout: 3 * time.Second, Username: p.Username, Password: p.Password, } return p.Provider.Init(zookeeper.StoreName, "zookeeper", config) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kv/redis/redis.go
pkg/provider/kv/redis/redis.go
package redis import ( "context" "errors" "fmt" "github.com/kvtools/redis" "github.com/traefik/traefik/v3/pkg/provider" "github.com/traefik/traefik/v3/pkg/provider/kv" "github.com/traefik/traefik/v3/pkg/types" ) var _ provider.Provider = (*Provider)(nil) // Provider holds configurations of the provider. type Provider struct { kv.Provider `yaml:",inline" export:"true"` TLS *types.ClientTLS `description:"Enable TLS support." json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" export:"true"` Username string `description:"Username for authentication." json:"username,omitempty" toml:"username,omitempty" yaml:"username,omitempty" loggable:"false"` Password string `description:"Password for authentication." json:"password,omitempty" toml:"password,omitempty" yaml:"password,omitempty" loggable:"false"` DB int `description:"Database to be selected after connecting to the server." json:"db,omitempty" toml:"db,omitempty" yaml:"db,omitempty"` Sentinel *Sentinel `description:"Enable Sentinel support." json:"sentinel,omitempty" toml:"sentinel,omitempty" yaml:"sentinel,omitempty" export:"true"` } // Sentinel holds the Redis Sentinel configuration. type Sentinel struct { MasterName string `description:"Name of the master." json:"masterName,omitempty" toml:"masterName,omitempty" yaml:"masterName,omitempty" export:"true"` Username string `description:"Username for Sentinel authentication." json:"username,omitempty" toml:"username,omitempty" yaml:"username,omitempty" loggable:"false"` Password string `description:"Password for Sentinel authentication." json:"password,omitempty" toml:"password,omitempty" yaml:"password,omitempty" loggable:"false"` LatencyStrategy bool `description:"Defines whether to route commands to the closest master or replica nodes (mutually exclusive with RandomStrategy and ReplicaStrategy)." json:"latencyStrategy,omitempty" toml:"latencyStrategy,omitempty" yaml:"latencyStrategy,omitempty" export:"true"` RandomStrategy bool `description:"Defines whether to route commands randomly to master or replica nodes (mutually exclusive with LatencyStrategy and ReplicaStrategy)." json:"randomStrategy,omitempty" toml:"randomStrategy,omitempty" yaml:"randomStrategy,omitempty" export:"true"` ReplicaStrategy bool `description:"Defines whether to route all commands to replica nodes (mutually exclusive with LatencyStrategy and RandomStrategy)." json:"replicaStrategy,omitempty" toml:"replicaStrategy,omitempty" yaml:"replicaStrategy,omitempty" export:"true"` UseDisconnectedReplicas bool `description:"Use replicas disconnected with master when cannot get connected replicas." json:"useDisconnectedReplicas,omitempty" toml:"useDisconnectedReplicas,omitempty" yaml:"useDisconnectedReplicas,omitempty" export:"true"` } // SetDefaults sets the default values. func (p *Provider) SetDefaults() { p.Provider.SetDefaults() p.Endpoints = []string{"127.0.0.1:6379"} } // Init the provider. func (p *Provider) Init() error { config := &redis.Config{ Username: p.Username, Password: p.Password, DB: p.DB, } if p.TLS != nil { var err error config.TLS, err = p.TLS.CreateTLSConfig(context.Background()) if err != nil { return fmt.Errorf("unable to create client TLS configuration: %w", err) } } if p.Sentinel != nil { count := 0 if p.Sentinel.LatencyStrategy { count++ } if p.Sentinel.ReplicaStrategy { count++ } if p.Sentinel.RandomStrategy { count++ } if count > 1 { return errors.New("latencyStrategy, randomStrategy and replicaStrategy options are mutually exclusive, please use only one of those options") } clusterClient := p.Sentinel.LatencyStrategy || p.Sentinel.RandomStrategy config.Sentinel = &redis.Sentinel{ MasterName: p.Sentinel.MasterName, Username: p.Sentinel.Username, Password: p.Sentinel.Password, ClusterClient: clusterClient, RouteByLatency: p.Sentinel.LatencyStrategy, RouteRandomly: p.Sentinel.RandomStrategy, ReplicaOnly: p.Sentinel.ReplicaStrategy, UseDisconnectedReplicas: p.Sentinel.UseDisconnectedReplicas, } } return p.Provider.Init(redis.StoreName, "redis", config) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kv/etcd/etcd.go
pkg/provider/kv/etcd/etcd.go
package etcd import ( "context" "fmt" "time" "github.com/kvtools/etcdv3" "github.com/traefik/traefik/v3/pkg/provider" "github.com/traefik/traefik/v3/pkg/provider/kv" "github.com/traefik/traefik/v3/pkg/types" ) var _ provider.Provider = (*Provider)(nil) // Provider holds configurations of the provider. type Provider struct { kv.Provider `yaml:",inline" export:"true"` TLS *types.ClientTLS `description:"Enable TLS support." json:"tls,omitempty" toml:"tls,omitempty" yaml:"tls,omitempty" export:"true"` Username string `description:"Username for authentication." json:"username,omitempty" toml:"username,omitempty" yaml:"username,omitempty" loggable:"false"` Password string `description:"Password for authentication." json:"password,omitempty" toml:"password,omitempty" yaml:"password,omitempty" loggable:"false"` } // SetDefaults sets the default values. func (p *Provider) SetDefaults() { p.Provider.SetDefaults() p.Endpoints = []string{"127.0.0.1:2379"} } // Init the provider. func (p *Provider) Init() error { config := &etcdv3.Config{ ConnectionTimeout: 3 * time.Second, Username: p.Username, Password: p.Password, } if p.TLS != nil { var err error config.TLS, err = p.TLS.CreateTLSConfig(context.Background()) if err != nil { return fmt.Errorf("unable to create client TLS configuration: %w", err) } } return p.Provider.Init(etcdv3.StoreName, "etcd", config) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/tailscale/provider.go
pkg/provider/tailscale/provider.go
package tailscale import ( "context" "crypto/tls" "crypto/x509" "sort" "strings" "sync" "time" "github.com/rs/zerolog/log" "github.com/tailscale/tscert" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/muxer/http" "github.com/traefik/traefik/v3/pkg/muxer/tcp" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/safe" traefiktls "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" ) // Provider is the Tailscale certificates provider implementation. It receives // configuration updates (e.g. new router, with new domain) from Traefik core, // fetches the corresponding TLS certificates from the Tailscale daemon, and // sends back to Traefik core a configuration updated with the certificates. type Provider struct { ResolverName string dynConfigs chan dynamic.Configuration // updates from Traefik core dynMessages chan<- dynamic.Message // update to Traefik core certByDomainMu sync.RWMutex certByDomain map[string]traefiktls.Certificate } // ThrottleDuration implements the aggregator.throttled interface, in order to // ensure that this provider is unthrottled. func (p *Provider) ThrottleDuration() time.Duration { return 0 } // Init implements the provider.Provider interface. func (p *Provider) Init() error { p.dynConfigs = make(chan dynamic.Configuration) p.certByDomain = make(map[string]traefiktls.Certificate) return nil } // HandleConfigUpdate hands out a configuration update to the provider. func (p *Provider) HandleConfigUpdate(cfg dynamic.Configuration) { p.dynConfigs <- cfg } // Provide starts the provider, which will henceforth send configuration // updates on dynMessages. func (p *Provider) Provide(dynMessages chan<- dynamic.Message, pool *safe.Pool) error { p.dynMessages = dynMessages logger := log.With().Str(logs.ProviderName, p.ResolverName+".tailscale").Logger() pool.GoCtx(func(ctx context.Context) { p.watchDomains(logger.WithContext(ctx)) }) pool.GoCtx(func(ctx context.Context) { p.renewCertificates(logger.WithContext(ctx)) }) return nil } // watchDomains watches for Tailscale domain certificates that should be fetched from the Tailscale daemon. func (p *Provider) watchDomains(ctx context.Context) { for { select { case <-ctx.Done(): return case cfg := <-p.dynConfigs: domains := p.findDomains(ctx, cfg) newDomains := p.findNewDomains(domains) purged := p.purgeUnusedCerts(domains) if len(newDomains) == 0 && !purged { continue } // TODO: what should we do if the fetched certificate is going to expire before the next refresh tick? p.fetchCerts(ctx, newDomains) p.sendDynamicConfig() } } } // renewCertificates routinely renews previously resolved Tailscale // certificates before they expire. func (p *Provider) renewCertificates(ctx context.Context) { ticker := time.NewTicker(24 * time.Hour) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-ticker.C: p.certByDomainMu.RLock() var domainsToRenew []string for domain, cert := range p.certByDomain { tlsCert, err := cert.GetCertificateFromBytes() if err != nil { log.Ctx(ctx). Err(err). Msgf("Unable to get certificate for domain %s", domain) continue } // Tailscale tries to renew certificates 14 days before its expiration date. // See https://github.com/tailscale/tailscale/blob/d9efbd97cbf369151e31453749f6692df7413709/ipn/localapi/cert.go#L116 if isValidCert(tlsCert, domain, time.Now().AddDate(0, 0, 14)) { continue } domainsToRenew = append(domainsToRenew, domain) } p.certByDomainMu.RUnlock() if len(domainsToRenew) == 0 { continue } p.fetchCerts(ctx, domainsToRenew) p.sendDynamicConfig() } } } // findDomains goes through the given dynamic.Configuration and returns all // Tailscale-specific domains found. func (p *Provider) findDomains(ctx context.Context, cfg dynamic.Configuration) []string { logger := log.Ctx(ctx) var domains []string if cfg.HTTP != nil { for _, router := range cfg.HTTP.Routers { if router.TLS == nil || router.TLS.CertResolver != p.ResolverName { continue } // As a domain list is explicitly defined we are only using the // configured domains. Only the Main domain is considered as // Tailscale domain certificate does not support multiple SANs. if len(router.TLS.Domains) > 0 { for _, domain := range router.TLS.Domains { domains = append(domains, domain.Main) } continue } parsedDomains, err := http.ParseDomains(router.Rule) if err != nil { logger.Error().Err(err).Msg("Unable to parse HTTP router domains") continue } domains = append(domains, parsedDomains...) } } if cfg.TCP != nil { for _, router := range cfg.TCP.Routers { if router.TLS == nil || router.TLS.CertResolver != p.ResolverName { continue } // As a domain list is explicitly defined we are only using the // configured domains. Only the Main domain is considered as // Tailscale domain certificate does not support multiple SANs. if len(router.TLS.Domains) > 0 { for _, domain := range router.TLS.Domains { domains = append(domains, domain.Main) } continue } parsedDomains, err := tcp.ParseHostSNI(router.Rule) if err != nil { logger.Error().Err(err).Msg("Unable to parse TCP router domains") continue } domains = append(domains, parsedDomains...) } } return sanitizeDomains(ctx, domains) } // findNewDomains returns the domains that have not already been fetched from // the Tailscale daemon. func (p *Provider) findNewDomains(domains []string) []string { p.certByDomainMu.RLock() defer p.certByDomainMu.RUnlock() var newDomains []string for _, domain := range domains { if _, ok := p.certByDomain[domain]; ok { continue } newDomains = append(newDomains, domain) } return newDomains } // purgeUnusedCerts purges the certByDomain map by removing unused certificates // and returns whether some certificates have been removed. func (p *Provider) purgeUnusedCerts(domains []string) bool { p.certByDomainMu.Lock() defer p.certByDomainMu.Unlock() newCertByDomain := make(map[string]traefiktls.Certificate) for _, domain := range domains { if cert, ok := p.certByDomain[domain]; ok { newCertByDomain[domain] = cert } } purged := len(p.certByDomain) > len(newCertByDomain) p.certByDomain = newCertByDomain return purged } // fetchCerts fetches the certificates for the provided domains from the // Tailscale daemon. func (p *Provider) fetchCerts(ctx context.Context, domains []string) { logger := log.Ctx(ctx) for _, domain := range domains { cert, key, err := tscert.CertPair(ctx, domain) if err != nil { logger.Error().Err(err).Msgf("Unable to fetch certificate for domain %q", domain) continue } logger.Debug().Msgf("Fetched certificate for domain %q", domain) p.certByDomainMu.Lock() p.certByDomain[domain] = traefiktls.Certificate{ CertFile: types.FileOrContent(cert), KeyFile: types.FileOrContent(key), } p.certByDomainMu.Unlock() } } // sendDynamicConfig sends a dynamic.Message with the dynamic.Configuration // containing the newly generated (or renewed) Tailscale certs. func (p *Provider) sendDynamicConfig() { p.certByDomainMu.RLock() defer p.certByDomainMu.RUnlock() // TODO: we always send back to traefik core the set of certificates // sorted, to make sure that two identical sets, that would be sorted // differently, do not trigger another configuration update because of the // mismatch. But in reality we should not end up sending a certificates // update if there was no new certs to generate or renew in the first // place, so this scenario should never happen, and the sorting might // actually not be needed. var sortedDomains []string for domain := range p.certByDomain { sortedDomains = append(sortedDomains, domain) } sort.Strings(sortedDomains) var certs []*traefiktls.CertAndStores for _, domain := range sortedDomains { // Only the default store is supported. certs = append(certs, &traefiktls.CertAndStores{ Stores: []string{traefiktls.DefaultTLSStoreName}, Certificate: p.certByDomain[domain], }) } p.dynMessages <- dynamic.Message{ ProviderName: p.ResolverName + ".tailscale", Configuration: &dynamic.Configuration{ TLS: &dynamic.TLSConfiguration{Certificates: certs}, }, } } // sanitizeDomains removes duplicated and invalid Tailscale subdomains, from // the provided list. func sanitizeDomains(ctx context.Context, domains []string) []string { logger := log.Ctx(ctx) seen := map[string]struct{}{} var sanitizedDomains []string for _, domain := range domains { if _, ok := seen[domain]; ok { continue } if !isTailscaleDomain(domain) { logger.Error().Msgf("Domain %s is not a valid Tailscale domain", domain) continue } sanitizedDomains = append(sanitizedDomains, domain) seen[domain] = struct{}{} } return sanitizedDomains } // isTailscaleDomain returns whether the given domain is a valid Tailscale // domain. A valid Tailscale domain has the following form: // machine-name.domains-alias.ts.net. func isTailscaleDomain(domain string) bool { // TODO: extra check, against the actual list of allowed domains names, // provided by the Tailscale daemon status? labels := strings.Split(domain, ".") return len(labels) == 4 && labels[2] == "ts" && labels[3] == "net" } // isValidCert returns whether the given tls.Certificate is valid for the given // domain at the given time. func isValidCert(cert tls.Certificate, domain string, now time.Time) bool { var leaf *x509.Certificate intermediates := x509.NewCertPool() for i, raw := range cert.Certificate { der, err := x509.ParseCertificate(raw) if err != nil { return false } if i == 0 { leaf = der continue } intermediates.AddCert(der) } if leaf == nil { return false } _, err := leaf.Verify(x509.VerifyOptions{ DNSName: domain, Intermediates: intermediates, CurrentTime: now, }) return err == nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/tailscale/provider_test.go
pkg/provider/tailscale/provider_test.go
package tailscale import ( "testing" "github.com/stretchr/testify/assert" "github.com/traefik/traefik/v3/pkg/config/dynamic" traefiktls "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" ) func TestProvider_findDomains(t *testing.T) { testCases := []struct { desc string config dynamic.Configuration want []string }{ { desc: "ignore domain with non-matching resolver", config: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "foo": { Rule: "Host(`machine.http.ts.net`)", TLS: &dynamic.RouterTLSConfig{CertResolver: "bar"}, }, }, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "foo": { Rule: "HostSNI(`machine.tcp.ts.net`)", TLS: &dynamic.RouterTCPTLSConfig{CertResolver: "bar"}, }, }, }, }, }, { desc: "sanitize domains", config: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "dup": { Rule: "Host(`machine.http.ts.net`)", TLS: &dynamic.RouterTLSConfig{CertResolver: "foo"}, }, "malformed": { Rule: "Host(`machine.http.ts.foo`)", TLS: &dynamic.RouterTLSConfig{CertResolver: "foo"}, }, }, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "dup": { Rule: "HostSNI(`machine.http.ts.net`)", TLS: &dynamic.RouterTCPTLSConfig{CertResolver: "foo"}, }, "malformed": { Rule: "HostSNI(`machine.tcp.ts.foo`)", TLS: &dynamic.RouterTCPTLSConfig{CertResolver: "foo"}, }, }, }, }, want: []string{"machine.http.ts.net"}, }, { desc: "domains from HTTP and TCP router rule", config: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "foo": { Rule: "Host(`machine.http.ts.net`)", TLS: &dynamic.RouterTLSConfig{CertResolver: "foo"}, }, }, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "foo": { Rule: "HostSNI(`machine.tcp.ts.net`)", TLS: &dynamic.RouterTCPTLSConfig{CertResolver: "foo"}, }, }, }, }, want: []string{"machine.http.ts.net", "machine.tcp.ts.net"}, }, { desc: "domains from HTTP and TCP TLS configuration", config: dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "foo": { Rule: "Host(`machine.http.ts.net`)", TLS: &dynamic.RouterTLSConfig{ Domains: []types.Domain{{Main: "main.http.ts.net"}}, CertResolver: "foo", }, }, }, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "foo": { Rule: "HostSNI(`machine.tcp.ts.net`)", TLS: &dynamic.RouterTCPTLSConfig{ Domains: []types.Domain{{Main: "main.tcp.ts.net"}}, CertResolver: "foo", }, }, }, }, }, want: []string{"main.http.ts.net", "main.tcp.ts.net"}, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() p := Provider{ResolverName: "foo"} got := p.findDomains(t.Context(), test.config) assert.Equal(t, test.want, got) }) } } func TestProvider_findNewDomains(t *testing.T) { p := Provider{ ResolverName: "foo", certByDomain: map[string]traefiktls.Certificate{ "foo.com": {}, }, } got := p.findNewDomains([]string{"foo.com", "bar.com"}) assert.Equal(t, []string{"bar.com"}, got) } func TestProvider_purgeUnusedCerts(t *testing.T) { p := Provider{ ResolverName: "foo", certByDomain: map[string]traefiktls.Certificate{ "foo.com": {}, "bar.com": {}, }, } got := p.purgeUnusedCerts([]string{"foo.com"}) assert.True(t, got) assert.Len(t, p.certByDomain, 1) assert.Contains(t, p.certByDomain, "foo.com") } func TestProvider_sendDynamicConfig(t *testing.T) { testCases := []struct { desc string certByDomain map[string]traefiktls.Certificate want []*traefiktls.CertAndStores }{ { desc: "without certificates", }, { desc: "with certificates", certByDomain: map[string]traefiktls.Certificate{ "foo.com": {CertFile: "foo.crt", KeyFile: "foo.key"}, "bar.com": {CertFile: "bar.crt", KeyFile: "bar.key"}, }, want: []*traefiktls.CertAndStores{ { Certificate: traefiktls.Certificate{CertFile: "bar.crt", KeyFile: "bar.key"}, Stores: []string{traefiktls.DefaultTLSStoreName}, }, { Certificate: traefiktls.Certificate{CertFile: "foo.crt", KeyFile: "foo.key"}, Stores: []string{traefiktls.DefaultTLSStoreName}, }, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() msgCh := make(chan dynamic.Message, 1) p := Provider{ ResolverName: "foo", dynMessages: msgCh, certByDomain: test.certByDomain, } p.sendDynamicConfig() got := <-msgCh assert.Equal(t, "foo.tailscale", got.ProviderName) assert.NotNil(t, got.Configuration) assert.Equal(t, &dynamic.TLSConfiguration{Certificates: test.want}, got.Configuration.TLS) }) } } func Test_sanitizeDomains(t *testing.T) { testCases := []struct { desc string domains []string want []string }{ { desc: "duplicate domains", domains: []string{"foo.domain.ts.net", "foo.domain.ts.net"}, want: []string{"foo.domain.ts.net"}, }, { desc: "not a Tailscale domain", domains: []string{"foo.domain.ts.com"}, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() got := sanitizeDomains(t.Context(), test.domains) assert.Equal(t, test.want, got) }) } } func Test_isTailscaleDomain(t *testing.T) { testCases := []struct { desc string domain string want bool }{ { desc: "valid domains", domain: "machine.domains.ts.net", want: true, }, { desc: "bad suffix", domain: "machine.domains.foo.net", want: false, }, { desc: "too much labels", domain: "foo.machine.domains.ts.net", want: false, }, { desc: "not enough labels", domain: "domains.ts.net", want: false, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() got := isTailscaleDomain(test.domain) assert.Equal(t, test.want, got) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/rest/rest.go
pkg/provider/rest/rest.go
package rest import ( "encoding/json" "fmt" "net/http" "github.com/gorilla/mux" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/provider" "github.com/traefik/traefik/v3/pkg/safe" "github.com/unrolled/render" ) var _ provider.Provider = (*Provider)(nil) // Provider is a provider.Provider implementation that provides a Rest API. type Provider struct { Insecure bool `description:"Activate REST Provider directly on the entryPoint named traefik." json:"insecure,omitempty" toml:"insecure,omitempty" yaml:"insecure,omitempty" export:"true"` configurationChan chan<- dynamic.Message } // SetDefaults sets the default values. func (p *Provider) SetDefaults() {} var templatesRenderer = render.New(render.Options{Directory: "nowhere"}) // Init the provider. func (p *Provider) Init() error { return nil } // CreateRouter creates a router for the Rest API. func (p *Provider) CreateRouter() *mux.Router { router := mux.NewRouter() router.Methods(http.MethodPut).Path("/api/providers/{provider}").Handler(p) return router } func (p *Provider) ServeHTTP(rw http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) if vars["provider"] != "rest" { http.Error(rw, "Only 'rest' provider can be updated through the REST API", http.StatusBadRequest) return } configuration := new(dynamic.Configuration) if err := json.NewDecoder(req.Body).Decode(configuration); err != nil { log.Error().Err(err).Msg("Error parsing configuration") http.Error(rw, fmt.Sprintf("%+v", err), http.StatusBadRequest) return } p.configurationChan <- dynamic.Message{ProviderName: "rest", Configuration: configuration} if err := templatesRenderer.JSON(rw, http.StatusOK, configuration); err != nil { log.Error().Err(err).Send() } } // Provide allows the provider to provide configurations to traefik // using the given configuration channel. func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error { p.configurationChan = configurationChan return nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/aggregator/ring_channel.go
pkg/provider/aggregator/ring_channel.go
package aggregator import ( "github.com/traefik/traefik/v3/pkg/config/dynamic" ) // RingChannel implements a channel in a way that never blocks the writer. // Specifically, if a value is written to a RingChannel when its buffer is full then the oldest // value in the buffer is discarded to make room (just like a standard ring-buffer). // Note that Go's scheduler can cause discarded values when they could be avoided, simply by scheduling // the writer before the reader, so caveat emptor. type RingChannel struct { input, output chan dynamic.Message buffer *dynamic.Message } func newRingChannel() *RingChannel { ch := &RingChannel{ input: make(chan dynamic.Message), output: make(chan dynamic.Message), } go ch.ringBuffer() return ch } func (ch *RingChannel) in() chan<- dynamic.Message { return ch.input } func (ch *RingChannel) out() <-chan dynamic.Message { return ch.output } // for all buffered cases. func (ch *RingChannel) ringBuffer() { var input, output chan dynamic.Message var next dynamic.Message input = ch.input for input != nil || output != nil { select { // Prefer to write if possible, which is surprisingly effective in reducing // dropped elements due to overflow. The naive read/write select chooses randomly // when both channels are ready, which produces unnecessary drops 50% of the time. case output <- next: ch.buffer = nil default: select { case elem, open := <-input: if !open { input = nil break } ch.buffer = &elem case output <- next: ch.buffer = nil } } if ch.buffer == nil { output = nil continue } output = ch.output next = *ch.buffer } close(ch.output) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/aggregator/aggregator_test.go
pkg/provider/aggregator/aggregator_test.go
package aggregator import ( "bytes" "testing" "time" "github.com/rs/zerolog" "github.com/rs/zerolog/log" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/provider" "github.com/traefik/traefik/v3/pkg/safe" ) func TestProviderAggregator_Provide(t *testing.T) { aggregator := ProviderAggregator{ internalProvider: &providerMock{"internal"}, fileProvider: &providerMock{"file"}, providers: []provider.Provider{ &providerMock{"salad"}, &providerMock{"tomato"}, &providerMock{"onion"}, }, } cfgCh := make(chan dynamic.Message) errCh := make(chan error) pool := safe.NewPool(t.Context()) t.Cleanup(pool.Stop) go func() { errCh <- aggregator.Provide(cfgCh, pool) }() // Make sure the file provider is always called first. requireReceivedMessageFromProviders(t, cfgCh, []string{"file"}) // Check if all providers have been called, the order doesn't matter. requireReceivedMessageFromProviders(t, cfgCh, []string{"salad", "tomato", "onion", "internal"}) require.NoError(t, <-errCh) } func TestLaunchNamespacedProvider(t *testing.T) { // Capture log output var buf bytes.Buffer originalLogger := log.Logger log.Logger = zerolog.New(&buf).Level(zerolog.InfoLevel) providerWithNamespace := &mockNamespacedProvider{namespace: "test-namespace"} aggregator := ProviderAggregator{ internalProvider: providerWithNamespace, } cfgCh := make(chan dynamic.Message) pool := safe.NewPool(t.Context()) t.Cleanup(func() { pool.Stop() log.Logger = originalLogger }) err := aggregator.Provide(cfgCh, pool) require.NoError(t, err) output := buf.String() assert.Contains(t, output, "Starting provider *aggregator.mockNamespacedProvider (namespace: test-namespace)") } // requireReceivedMessageFromProviders makes sure the given providers have emitted a message on the given message channel. // Providers order is not enforced. func requireReceivedMessageFromProviders(t *testing.T, cfgCh <-chan dynamic.Message, names []string) { t.Helper() var msg dynamic.Message var receivedMessagesFrom []string for range names { select { case <-time.After(100 * time.Millisecond): require.Fail(t, "Timeout while waiting for configuration.") case msg = <-cfgCh: receivedMessagesFrom = append(receivedMessagesFrom, msg.ProviderName) } } require.ElementsMatch(t, names, receivedMessagesFrom) } type providerMock struct { Name string } func (p *providerMock) Init() error { return nil } func (p *providerMock) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error { configurationChan <- dynamic.Message{ ProviderName: p.Name, Configuration: &dynamic.Configuration{}, } return nil } // mockNamespacedProvider is a mock implementation of NamespacedProvider for testing. type mockNamespacedProvider struct { namespace string } func (m *mockNamespacedProvider) Namespace() string { return m.namespace } func (m *mockNamespacedProvider) Provide(_ chan<- dynamic.Message, _ *safe.Pool) error { return nil } func (m *mockNamespacedProvider) Init() error { return nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/aggregator/aggregator.go
pkg/provider/aggregator/aggregator.go
package aggregator import ( "context" "fmt" "time" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/static" "github.com/traefik/traefik/v3/pkg/provider" "github.com/traefik/traefik/v3/pkg/provider/file" "github.com/traefik/traefik/v3/pkg/provider/traefik" "github.com/traefik/traefik/v3/pkg/redactor" "github.com/traefik/traefik/v3/pkg/safe" ) // throttled defines what kind of config refresh throttling the aggregator should // set up for a given provider. // If a provider implements throttled, the configuration changes it sends will be // taken into account no more often than the frequency inferred from ThrottleDuration(). // If ThrottleDuration returns zero, no throttling will take place. // If throttled is not implemented, the throttling will be set up in accordance // with the global providersThrottleDuration option. type throttled interface { ThrottleDuration() time.Duration } // maybeThrottledProvide returns the Provide method of the given provider, // potentially augmented with some throttling depending on whether and how the // provider implements the throttled interface. func maybeThrottledProvide(prd provider.Provider, defaultDuration time.Duration) func(chan<- dynamic.Message, *safe.Pool) error { providerThrottleDuration := defaultDuration if throttled, ok := prd.(throttled); ok { // per-provider throttling providerThrottleDuration = throttled.ThrottleDuration() } if providerThrottleDuration == 0 { // throttling disabled return prd.Provide } return func(configurationChan chan<- dynamic.Message, pool *safe.Pool) error { rc := newRingChannel() pool.GoCtx(func(ctx context.Context) { for { select { case <-ctx.Done(): return case msg := <-rc.out(): configurationChan <- msg time.Sleep(providerThrottleDuration) } } }) return prd.Provide(rc.in(), pool) } } // ProviderAggregator aggregates providers. type ProviderAggregator struct { internalProvider provider.Provider fileProvider provider.Provider providers []provider.Provider providersThrottleDuration time.Duration } // NewProviderAggregator returns an aggregate of all the providers configured in the static configuration. func NewProviderAggregator(conf static.Providers) *ProviderAggregator { p := &ProviderAggregator{ providersThrottleDuration: time.Duration(conf.ProvidersThrottleDuration), } if conf.File != nil { p.quietAddProvider(conf.File) } if conf.Docker != nil { p.quietAddProvider(conf.Docker) } if conf.Swarm != nil { p.quietAddProvider(conf.Swarm) } if conf.Rest != nil { p.quietAddProvider(conf.Rest) } if conf.KubernetesIngress != nil { p.quietAddProvider(conf.KubernetesIngress) } if conf.KubernetesIngressNGINX != nil { p.quietAddProvider(conf.KubernetesIngressNGINX) } if conf.KubernetesCRD != nil { p.quietAddProvider(conf.KubernetesCRD) } if conf.Knative != nil { p.quietAddProvider(conf.Knative) } if conf.KubernetesGateway != nil { p.quietAddProvider(conf.KubernetesGateway) } if conf.Ecs != nil { p.quietAddProvider(conf.Ecs) } if conf.ConsulCatalog != nil { for _, pvd := range conf.ConsulCatalog.BuildProviders() { p.quietAddProvider(pvd) } } if conf.Nomad != nil { for _, pvd := range conf.Nomad.BuildProviders() { p.quietAddProvider(pvd) } } if conf.Consul != nil { for _, pvd := range conf.Consul.BuildProviders() { p.quietAddProvider(pvd) } } if conf.Etcd != nil { p.quietAddProvider(conf.Etcd) } if conf.ZooKeeper != nil { p.quietAddProvider(conf.ZooKeeper) } if conf.Redis != nil { p.quietAddProvider(conf.Redis) } if conf.HTTP != nil { p.quietAddProvider(conf.HTTP) } return p } func (p *ProviderAggregator) quietAddProvider(provider provider.Provider) { err := p.AddProvider(provider) if err != nil { log.Error().Err(err).Msgf("Error while initializing provider %T", provider) } } // AddProvider adds a provider in the providers map. func (p *ProviderAggregator) AddProvider(provider provider.Provider) error { err := provider.Init() if err != nil { return err } switch provider.(type) { case *file.Provider: p.fileProvider = provider case *traefik.Provider: p.internalProvider = provider default: p.providers = append(p.providers, provider) } return nil } // Init the provider. func (p *ProviderAggregator) Init() error { return nil } // Provide calls the provide method of every providers. func (p *ProviderAggregator) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error { if p.fileProvider != nil { p.launchProvider(configurationChan, pool, p.fileProvider) } for _, prd := range p.providers { safe.Go(func() { p.launchProvider(configurationChan, pool, prd) }) } // internal provider must be the last because we use it to know if all the providers are loaded. // ConfigurationWatcher will wait for this requiredProvider before applying configurations. if p.internalProvider != nil { p.launchProvider(configurationChan, pool, p.internalProvider) } return nil } func (p *ProviderAggregator) launchProvider(configurationChan chan<- dynamic.Message, pool *safe.Pool, prd provider.Provider) { jsonConf, err := redactor.RemoveCredentials(prd) if err != nil { log.Debug().Err(err).Msgf("Cannot marshal the provider configuration %T", prd) } // Check if provider has namespace information. var namespaceInfo string if namespaceProvider, ok := prd.(provider.NamespacedProvider); ok { if namespace := namespaceProvider.Namespace(); namespace != "" { namespaceInfo = fmt.Sprintf(" (namespace: %s)", namespace) } } log.Info().Msgf("Starting provider %T%s", prd, namespaceInfo) log.Debug().RawJSON("config", []byte(jsonConf)).Msgf("%T provider configuration%s", prd, namespaceInfo) if err := maybeThrottledProvide(prd, p.providersThrottleDuration)(configurationChan, pool); err != nil { log.Error().Err(err).Msgf("Cannot start the provider %T", prd) return } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/knative/client.go
pkg/provider/kubernetes/knative/client.go
package knative import ( "context" "errors" "fmt" "os" "time" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/k8s" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" kinformers "k8s.io/client-go/informers" kclientset "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" knativenetworkingv1alpha1 "knative.dev/networking/pkg/apis/networking/v1alpha1" knativenetworkingclientset "knative.dev/networking/pkg/client/clientset/versioned" knativenetworkinginformers "knative.dev/networking/pkg/client/informers/externalversions" ) const resyncPeriod = 10 * time.Minute type clientWrapper struct { csKnativeNetworking knativenetworkingclientset.Interface csKube kclientset.Interface factoriesKnativeNetworking map[string]knativenetworkinginformers.SharedInformerFactory factoriesKube map[string]kinformers.SharedInformerFactory labelSelector string isNamespaceAll bool watchedNamespaces []string } func createClientFromConfig(c *rest.Config) (*clientWrapper, error) { csKnativeNetworking, err := knativenetworkingclientset.NewForConfig(c) if err != nil { return nil, err } csKube, err := kclientset.NewForConfig(c) if err != nil { return nil, err } return newClientImpl(csKnativeNetworking, csKube), nil } func newClientImpl(csKnativeNetworking knativenetworkingclientset.Interface, csKube kclientset.Interface) *clientWrapper { return &clientWrapper{ csKnativeNetworking: csKnativeNetworking, csKube: csKube, factoriesKnativeNetworking: make(map[string]knativenetworkinginformers.SharedInformerFactory), factoriesKube: make(map[string]kinformers.SharedInformerFactory), } } // newInClusterClient returns a new Provider client that is expected to run // inside the cluster. func newInClusterClient(endpoint string) (*clientWrapper, error) { config, err := rest.InClusterConfig() if err != nil { return nil, fmt.Errorf("creating in-cluster configuration: %w", err) } if endpoint != "" { config.Host = endpoint } return createClientFromConfig(config) } func newExternalClusterClientFromFile(file string) (*clientWrapper, error) { configFromFlags, err := clientcmd.BuildConfigFromFlags("", file) if err != nil { return nil, err } return createClientFromConfig(configFromFlags) } // newExternalClusterClient returns a new Provider client that may run outside // of the cluster. // The endpoint parameter must not be empty. func newExternalClusterClient(endpoint, token, caFilePath string) (*clientWrapper, error) { if endpoint == "" { return nil, errors.New("endpoint missing for external cluster client") } config := &rest.Config{ Host: endpoint, BearerToken: token, } if caFilePath != "" { caData, err := os.ReadFile(caFilePath) if err != nil { return nil, fmt.Errorf("reading CA file %s: %w", caFilePath, err) } config.TLSClientConfig = rest.TLSClientConfig{CAData: caData} } return createClientFromConfig(config) } // WatchAll starts namespace-specific controllers for all relevant kinds. func (c *clientWrapper) WatchAll(namespaces []string, stopCh <-chan struct{}) (<-chan interface{}, error) { eventCh := make(chan interface{}, 1) eventHandler := &k8s.ResourceEventHandler{Ev: eventCh} if len(namespaces) == 0 { namespaces = []string{metav1.NamespaceAll} c.isNamespaceAll = true } c.watchedNamespaces = namespaces for _, ns := range namespaces { factory := knativenetworkinginformers.NewSharedInformerFactoryWithOptions(c.csKnativeNetworking, resyncPeriod, knativenetworkinginformers.WithNamespace(ns), knativenetworkinginformers.WithTweakListOptions(func(opts *metav1.ListOptions) { opts.LabelSelector = c.labelSelector })) _, err := factory.Networking().V1alpha1().Ingresses().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } factoryKube := kinformers.NewSharedInformerFactoryWithOptions(c.csKube, resyncPeriod, kinformers.WithNamespace(ns)) _, err = factoryKube.Core().V1().Services().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryKube.Core().V1().Secrets().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } c.factoriesKube[ns] = factoryKube c.factoriesKnativeNetworking[ns] = factory } for _, ns := range namespaces { c.factoriesKnativeNetworking[ns].Start(stopCh) c.factoriesKube[ns].Start(stopCh) } for _, ns := range namespaces { for t, ok := range c.factoriesKnativeNetworking[ns].WaitForCacheSync(stopCh) { if !ok { return nil, fmt.Errorf("timed out waiting for controller caches to sync %s in namespace %q", t.String(), ns) } } for t, ok := range c.factoriesKube[ns].WaitForCacheSync(stopCh) { if !ok { return nil, fmt.Errorf("timed out waiting for controller caches to sync %s in namespace %q", t.String(), ns) } } } return eventCh, nil } func (c *clientWrapper) ListIngresses() []*knativenetworkingv1alpha1.Ingress { var result []*knativenetworkingv1alpha1.Ingress for ns, factory := range c.factoriesKnativeNetworking { ings, err := factory.Networking().V1alpha1().Ingresses().Lister().List(labels.Everything()) // todo: label selector if err != nil { log.Error().Msgf("Failed to list ingresses in namespace %s: %s", ns, err) } result = append(result, ings...) } return result } func (c *clientWrapper) UpdateIngressStatus(ingress *knativenetworkingv1alpha1.Ingress) error { _, err := c.csKnativeNetworking.NetworkingV1alpha1().Ingresses(ingress.Namespace).UpdateStatus(context.TODO(), ingress, metav1.UpdateOptions{}) if err != nil { return fmt.Errorf("updating knative ingress status %s/%s: %w", ingress.Namespace, ingress.Name, err) } log.Info().Msgf("Updated status on knative ingress %s/%s", ingress.Namespace, ingress.Name) return nil } // GetService returns the named service from the given namespace. func (c *clientWrapper) GetService(namespace, name string) (*corev1.Service, error) { if !c.isWatchedNamespace(namespace) { return nil, fmt.Errorf("getting service %s/%s: namespace is not within watched namespaces", namespace, name) } return c.factoriesKube[c.lookupNamespace(namespace)].Core().V1().Services().Lister().Services(namespace).Get(name) } // GetSecret returns the named secret from the given namespace. func (c *clientWrapper) GetSecret(namespace, name string) (*corev1.Secret, error) { if !c.isWatchedNamespace(namespace) { return nil, fmt.Errorf("getting secret %s/%s: namespace is not within watched namespaces", namespace, name) } return c.factoriesKube[c.lookupNamespace(namespace)].Core().V1().Secrets().Lister().Secrets(namespace).Get(name) } // isWatchedNamespace checks to ensure that the namespace is being watched before we request // it to ensure we don't panic by requesting an out-of-watch object. func (c *clientWrapper) isWatchedNamespace(ns string) bool { if c.isNamespaceAll { return true } for _, watchedNamespace := range c.watchedNamespaces { if watchedNamespace == ns { return true } } return false } // lookupNamespace returns the lookup namespace key for the given namespace. // When listening on all namespaces, it returns the client-go identifier ("") // for all-namespaces. Otherwise, it returns the given namespace. // The distinction is necessary because we index all informers on the special // identifier iff all-namespaces are requested but receive specific namespace // identifiers from the Kubernetes API, so we have to bridge this gap. func (c *clientWrapper) lookupNamespace(ns string) string { if c.isNamespaceAll { return metav1.NamespaceAll } return ns }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/knative/kubernetes_test.go
pkg/provider/kubernetes/knative/kubernetes_test.go
package knative import ( "os" "path/filepath" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/k8s" "k8s.io/apimachinery/pkg/runtime" kubefake "k8s.io/client-go/kubernetes/fake" kscheme "k8s.io/client-go/kubernetes/scheme" "k8s.io/utils/ptr" knativenetworkingv1alpha1 "knative.dev/networking/pkg/apis/networking/v1alpha1" knfake "knative.dev/networking/pkg/client/clientset/versioned/fake" ) func init() { // required by k8s.MustParseYaml if err := knativenetworkingv1alpha1.AddToScheme(kscheme.Scheme); err != nil { panic(err) } } func Test_loadConfiguration(t *testing.T) { testCases := []struct { desc string paths []string want *dynamic.Configuration wantLen int }{ { desc: "Wrong ingress class", paths: []string{"wrong_ingress_class.yaml"}, wantLen: 0, want: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Services: map[string]*dynamic.Service{}, Middlewares: map[string]*dynamic.Middleware{}, }, }, }, { desc: "Cluster Local", paths: []string{"cluster_local.yaml", "services.yaml"}, wantLen: 1, want: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "default-helloworld-go-rule-0-path-0": { EntryPoints: []string{"priv-http", "priv-https"}, Service: "default-helloworld-go-rule-0-path-0-wrr", Rule: "(Host(`helloworld-go.default`) || Host(`helloworld-go.default.svc`) || Host(`helloworld-go.default.svc.cluster.local`))", Middlewares: []string{}, }, }, Services: map[string]*dynamic.Service{ "default-helloworld-go-rule-0-path-0-split-0": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: "wrr", PassHostHeader: ptr.To(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: types.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.43.38.208:80", }, }, }, }, "default-helloworld-go-rule-0-path-0-split-1": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: "wrr", PassHostHeader: ptr.To(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: types.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.43.44.18:80", }, }, }, }, "default-helloworld-go-rule-0-path-0-wrr": { Weighted: &dynamic.WeightedRoundRobin{ Services: []dynamic.WRRService{ { Name: "default-helloworld-go-rule-0-path-0-split-0", Weight: ptr.To(50), Headers: map[string]string{ "Knative-Serving-Namespace": "default", "Knative-Serving-Revision": "helloworld-go-00001", }, }, { Name: "default-helloworld-go-rule-0-path-0-split-1", Weight: ptr.To(50), Headers: map[string]string{ "Knative-Serving-Namespace": "default", "Knative-Serving-Revision": "helloworld-go-00002", }, }, }, }, }, }, Middlewares: map[string]*dynamic.Middleware{}, }, }, }, { desc: "External IP", paths: []string{"external_ip.yaml", "services.yaml"}, wantLen: 1, want: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "default-helloworld-go-rule-0-path-0": { EntryPoints: []string{"http", "https"}, Service: "default-helloworld-go-rule-0-path-0-wrr", Rule: "(Host(`helloworld-go.default`) || Host(`helloworld-go.default.svc`) || Host(`helloworld-go.default.svc.cluster.local`))", Middlewares: []string{}, }, }, Services: map[string]*dynamic.Service{ "default-helloworld-go-rule-0-path-0-split-0": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: "wrr", PassHostHeader: ptr.To(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: types.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.43.38.208:80", }, }, }, }, "default-helloworld-go-rule-0-path-0-split-1": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: "wrr", PassHostHeader: ptr.To(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: types.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.43.44.18:80", }, }, }, }, "default-helloworld-go-rule-0-path-0-wrr": { Weighted: &dynamic.WeightedRoundRobin{ Services: []dynamic.WRRService{ { Name: "default-helloworld-go-rule-0-path-0-split-0", Weight: ptr.To(50), Headers: map[string]string{ "Knative-Serving-Namespace": "default", "Knative-Serving-Revision": "helloworld-go-00001", }, }, { Name: "default-helloworld-go-rule-0-path-0-split-1", Weight: ptr.To(50), Headers: map[string]string{ "Knative-Serving-Namespace": "default", "Knative-Serving-Revision": "helloworld-go-00002", }, }, }, }, }, }, Middlewares: map[string]*dynamic.Middleware{}, }, }, }, { desc: "TLS", paths: []string{"tls.yaml", "services.yaml"}, wantLen: 1, want: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "default-helloworld-go-rule-0-path-0": { EntryPoints: []string{"http", "https"}, Service: "default-helloworld-go-rule-0-path-0-wrr", Rule: "(Host(`helloworld-go.default`) || Host(`helloworld-go.default.svc`) || Host(`helloworld-go.default.svc.cluster.local`))", Middlewares: []string{}, }, "default-helloworld-go-rule-0-path-0-tls": { EntryPoints: []string{"http", "https"}, Service: "default-helloworld-go-rule-0-path-0-wrr", Rule: "(Host(`helloworld-go.default`) || Host(`helloworld-go.default.svc`) || Host(`helloworld-go.default.svc.cluster.local`))", Middlewares: []string{}, TLS: &dynamic.RouterTLSConfig{}, }, }, Services: map[string]*dynamic.Service{ "default-helloworld-go-rule-0-path-0-split-0": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: "wrr", PassHostHeader: ptr.To(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: types.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.43.38.208:80", }, }, }, }, "default-helloworld-go-rule-0-path-0-split-1": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: "wrr", PassHostHeader: ptr.To(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: types.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.43.44.18:80", }, }, }, }, "default-helloworld-go-rule-0-path-0-wrr": { Weighted: &dynamic.WeightedRoundRobin{ Services: []dynamic.WRRService{ { Name: "default-helloworld-go-rule-0-path-0-split-0", Weight: ptr.To(50), Headers: map[string]string{ "Knative-Serving-Namespace": "default", "Knative-Serving-Revision": "helloworld-go-00001", }, }, { Name: "default-helloworld-go-rule-0-path-0-split-1", Weight: ptr.To(50), Headers: map[string]string{ "Knative-Serving-Namespace": "default", "Knative-Serving-Revision": "helloworld-go-00002", }, }, }, }, }, }, Middlewares: map[string]*dynamic.Middleware{}, }, }, }, } for _, testCase := range testCases { t.Run(testCase.desc, func(t *testing.T) { t.Parallel() k8sObjects, knObjects := readResources(t, testCase.paths) k8sClient := kubefake.NewClientset(k8sObjects...) knClient := knfake.NewSimpleClientset(knObjects...) client := newClientImpl(knClient, k8sClient) eventCh, err := client.WatchAll(nil, make(chan struct{})) require.NoError(t, err) if len(k8sObjects) > 0 || len(knObjects) > 0 { // just wait for the first event <-eventCh } p := Provider{ PublicEntrypoints: []string{"http", "https"}, PrivateEntrypoints: []string{"priv-http", "priv-https"}, client: client, } got, gotIngresses := p.loadConfiguration(t.Context()) assert.Len(t, gotIngresses, testCase.wantLen) assert.Equal(t, testCase.want, got) }) } } func Test_buildRule(t *testing.T) { testCases := []struct { desc string hosts []string headers map[string]knativenetworkingv1alpha1.HeaderMatch path string want string }{ { desc: "single host, no headers, no path", hosts: []string{"example.com"}, want: "(Host(`example.com`))", }, { desc: "multiple hosts, no headers, no path", hosts: []string{"example.com", "foo.com"}, want: "(Host(`example.com`) || Host(`foo.com`))", }, { desc: "single host, single header, no path", hosts: []string{"example.com"}, headers: map[string]knativenetworkingv1alpha1.HeaderMatch{ "X-Header": {Exact: "value"}, }, want: "(Host(`example.com`)) && (Header(`X-Header`,`value`))", }, { desc: "single host, multiple headers, no path", hosts: []string{"example.com"}, headers: map[string]knativenetworkingv1alpha1.HeaderMatch{ "X-Header": {Exact: "value"}, "X-Header2": {Exact: "value2"}, }, want: "(Host(`example.com`)) && (Header(`X-Header`,`value`) && Header(`X-Header2`,`value2`))", }, { desc: "single host, multiple headers, with path", hosts: []string{"example.com"}, headers: map[string]knativenetworkingv1alpha1.HeaderMatch{ "X-Header": {Exact: "value"}, "X-Header2": {Exact: "value2"}, }, path: "/foo", want: "(Host(`example.com`)) && (Header(`X-Header`,`value`) && Header(`X-Header2`,`value2`)) && PathPrefix(`/foo`)", }, { desc: "single host, no headers, with path", hosts: []string{"example.com"}, path: "/foo", want: "(Host(`example.com`)) && PathPrefix(`/foo`)", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() got := buildRule(test.hosts, test.headers, test.path) assert.Equal(t, test.want, got) }) } } func Test_mergeHTTPConfigs(t *testing.T) { testCases := []struct { desc string configs []*dynamic.HTTPConfiguration want *dynamic.HTTPConfiguration }{ { desc: "one empty configuration", configs: []*dynamic.HTTPConfiguration{ { Routers: map[string]*dynamic.Router{ "router1": {Rule: "Host(`example.com`)"}, }, Middlewares: map[string]*dynamic.Middleware{ "middleware1": {Headers: &dynamic.Headers{CustomRequestHeaders: map[string]string{"X-Test": "value"}}}, }, Services: map[string]*dynamic.Service{ "service1": {LoadBalancer: &dynamic.ServersLoadBalancer{Servers: []dynamic.Server{{URL: "http://example.com"}}}}, }, }, { Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, }, }, want: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "router1": {Rule: "Host(`example.com`)"}, }, Middlewares: map[string]*dynamic.Middleware{ "middleware1": {Headers: &dynamic.Headers{CustomRequestHeaders: map[string]string{"X-Test": "value"}}}, }, Services: map[string]*dynamic.Service{ "service1": {LoadBalancer: &dynamic.ServersLoadBalancer{Servers: []dynamic.Server{{URL: "http://example.com"}}}}, }, }, }, { desc: "merging two non-empty configurations", configs: []*dynamic.HTTPConfiguration{ { Routers: map[string]*dynamic.Router{ "router1": {Rule: "Host(`example.com`)"}, }, Middlewares: map[string]*dynamic.Middleware{ "middleware1": {Headers: &dynamic.Headers{CustomRequestHeaders: map[string]string{"X-Test": "value"}}}, }, Services: map[string]*dynamic.Service{ "service1": {LoadBalancer: &dynamic.ServersLoadBalancer{Servers: []dynamic.Server{{URL: "http://example.com"}}}}, }, }, { Routers: map[string]*dynamic.Router{ "router2": {Rule: "PathPrefix(`/test`)"}, }, Middlewares: map[string]*dynamic.Middleware{ "middleware2": {Headers: &dynamic.Headers{CustomRequestHeaders: map[string]string{"X-Test": "value"}}}, }, Services: map[string]*dynamic.Service{ "service2": {LoadBalancer: &dynamic.ServersLoadBalancer{Servers: []dynamic.Server{{URL: "http://example.com"}}}}, }, }, }, want: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "router1": {Rule: "Host(`example.com`)"}, "router2": {Rule: "PathPrefix(`/test`)"}, }, Middlewares: map[string]*dynamic.Middleware{ "middleware1": {Headers: &dynamic.Headers{CustomRequestHeaders: map[string]string{"X-Test": "value"}}}, "middleware2": {Headers: &dynamic.Headers{CustomRequestHeaders: map[string]string{"X-Test": "value"}}}, }, Services: map[string]*dynamic.Service{ "service1": {LoadBalancer: &dynamic.ServersLoadBalancer{Servers: []dynamic.Server{{URL: "http://example.com"}}}}, "service2": {LoadBalancer: &dynamic.ServersLoadBalancer{Servers: []dynamic.Server{{URL: "http://example.com"}}}}, }, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() got := mergeHTTPConfigs(test.configs...) assert.Equal(t, test.want, got) }) } } func readResources(t *testing.T, paths []string) ([]runtime.Object, []runtime.Object) { t.Helper() var ( k8sObjects []runtime.Object knObjects []runtime.Object ) for _, path := range paths { yamlContent, err := os.ReadFile(filepath.FromSlash("./fixtures/" + path)) if err != nil { panic(err) } objects := k8s.MustParseYaml(yamlContent) for _, obj := range objects { switch obj.GetObjectKind().GroupVersionKind().Group { case "networking.internal.knative.dev": knObjects = append(knObjects, obj) default: k8sObjects = append(k8sObjects, obj) } } } return k8sObjects, knObjects }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/knative/kubernetes.go
pkg/provider/kubernetes/knative/kubernetes.go
package knative import ( "context" "errors" "fmt" "maps" "net" "os" "slices" "strconv" "strings" "time" "github.com/cenkalti/backoff/v4" "github.com/mitchellh/hashstructure" "github.com/rs/zerolog/log" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/job" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/safe" "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/utils/ptr" knativenetworking "knative.dev/networking/pkg/apis/networking" knativenetworkingv1alpha1 "knative.dev/networking/pkg/apis/networking/v1alpha1" "knative.dev/pkg/network" ) const ( providerName = "knative" traefikIngressClassName = "traefik.ingress.networking.knative.dev" ) // ServiceRef holds a Kubernetes service reference. type ServiceRef struct { Name string `description:"Name of the Kubernetes service." json:"desc,omitempty" toml:"desc,omitempty" yaml:"desc,omitempty"` Namespace string `description:"Namespace of the Kubernetes service." json:"namespace,omitempty" toml:"namespace,omitempty" yaml:"namespace,omitempty"` } // Provider holds configurations of the provider. type Provider struct { Endpoint string `description:"Kubernetes server endpoint (required for external cluster client)." json:"endpoint,omitempty" toml:"endpoint,omitempty" yaml:"endpoint,omitempty"` Token string `description:"Kubernetes bearer token (not needed for in-cluster client)." json:"token,omitempty" toml:"token,omitempty" yaml:"token,omitempty"` CertAuthFilePath string `description:"Kubernetes certificate authority file path (not needed for in-cluster client)." json:"certAuthFilePath,omitempty" toml:"certAuthFilePath,omitempty" yaml:"certAuthFilePath,omitempty"` Namespaces []string `description:"Kubernetes namespaces." json:"namespaces,omitempty" toml:"namespaces,omitempty" yaml:"namespaces,omitempty" export:"true"` LabelSelector string `description:"Kubernetes label selector to use." json:"labelSelector,omitempty" toml:"labelSelector,omitempty" yaml:"labelSelector,omitempty" export:"true"` PublicEntrypoints []string `description:"Entrypoint names used to expose the Ingress publicly. If empty an Ingress is exposed on all entrypoints." json:"publicEntrypoints,omitempty" toml:"publicEntrypoints,omitempty" yaml:"publicEntrypoints,omitempty" export:"true"` PublicService ServiceRef `description:"Kubernetes service used to expose the networking controller publicly." json:"publicService,omitempty" toml:"publicService,omitempty" yaml:"publicService,omitempty" export:"true"` PrivateEntrypoints []string `description:"Entrypoint names used to expose the Ingress privately. If empty local Ingresses are skipped." json:"privateEntrypoints,omitempty" toml:"privateEntrypoints,omitempty" yaml:"privateEntrypoints,omitempty" export:"true"` PrivateService ServiceRef `description:"Kubernetes service used to expose the networking controller privately." json:"privateService,omitempty" toml:"privateService,omitempty" yaml:"privateService,omitempty" export:"true"` ThrottleDuration ptypes.Duration `description:"Ingress refresh throttle duration" json:"throttleDuration,omitempty" toml:"throttleDuration,omitempty" yaml:"throttleDuration,omitempty"` client *clientWrapper lastConfiguration safe.Safe } // Init the provider. func (p *Provider) Init() error { logger := log.With().Str(logs.ProviderName, providerName).Logger() // Initializes Kubernetes client. var err error p.client, err = p.newK8sClient(logger.WithContext(context.Background())) if err != nil { return fmt.Errorf("creating kubernetes client: %w", err) } return nil } // Provide allows the knative provider to provide configurations to traefik using the given configuration channel. func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error { logger := log.With().Str(logs.ProviderName, providerName).Logger() ctxLog := logger.WithContext(context.Background()) pool.GoCtx(func(ctxPool context.Context) { operation := func() error { eventsChan, err := p.client.WatchAll(p.Namespaces, ctxPool.Done()) if err != nil { logger.Error().Msgf("Error watching kubernetes events: %v", err) timer := time.NewTimer(1 * time.Second) select { case <-timer.C: return err case <-ctxPool.Done(): return nil } } throttleDuration := time.Duration(p.ThrottleDuration) throttledChan := throttleEvents(ctxLog, throttleDuration, pool, eventsChan) if throttledChan != nil { eventsChan = throttledChan } for { select { case <-ctxPool.Done(): return nil case event := <-eventsChan: // Note that event is the *first* event that came in during this throttling interval -- if we're hitting our throttle, we may have dropped events. // This is fine, because we don't treat different event types differently. // But if we do in the future, we'll need to track more information about the dropped events. conf, ingressStatuses := p.loadConfiguration(ctxLog) confHash, err := hashstructure.Hash(conf, nil) switch { case err != nil: logger.Error().Msg("Unable to hash the configuration") case p.lastConfiguration.Get() == confHash: logger.Debug().Msgf("Skipping Kubernetes event kind %T", event) default: p.lastConfiguration.Set(confHash) configurationChan <- dynamic.Message{ ProviderName: providerName, Configuration: conf, } } // If we're throttling, // we sleep here for the throttle duration to enforce that we don't refresh faster than our throttle. // time.Sleep returns immediately if p.ThrottleDuration is 0 (no throttle). time.Sleep(throttleDuration) // Updating the ingress status after the throttleDuration allows to wait to make sure that the dynamic conf is updated before updating the status. // This is needed for the conformance tests to pass, for example. for _, ingress := range ingressStatuses { if err := p.updateKnativeIngressStatus(ctxLog, ingress); err != nil { logger.Error().Err(err).Msgf("Error updating status for Ingress %s/%s", ingress.Namespace, ingress.Name) } } } } } notify := func(err error, time time.Duration) { logger.Error().Msgf("Provider connection error: %v; retrying in %s", err, time) } err := backoff.RetryNotify(safe.OperationWithRecover(operation), backoff.WithContext(job.NewBackOff(backoff.NewExponentialBackOff()), ctxPool), notify) if err != nil { logger.Error().Msgf("Cannot connect to Provider: %v", err) } }) return nil } func (p *Provider) newK8sClient(ctx context.Context) (*clientWrapper, error) { logger := log.Ctx(ctx).With().Logger() _, err := labels.Parse(p.LabelSelector) if err != nil { return nil, fmt.Errorf("parsing label selector: %q", p.LabelSelector) } logger.Info().Msgf("Label selector is: %q", p.LabelSelector) withEndpoint := "" if p.Endpoint != "" { withEndpoint = fmt.Sprintf(" with endpoint %s", p.Endpoint) } var client *clientWrapper switch { case os.Getenv("KUBERNETES_SERVICE_HOST") != "" && os.Getenv("KUBERNETES_SERVICE_PORT") != "": logger.Info().Msgf("Creating in-cluster Provider client%s", withEndpoint) client, err = newInClusterClient(p.Endpoint) case os.Getenv("KUBECONFIG") != "": logger.Info().Msgf("Creating cluster-external Provider client from KUBECONFIG %s", os.Getenv("KUBECONFIG")) client, err = newExternalClusterClientFromFile(os.Getenv("KUBECONFIG")) default: logger.Info().Msgf("Creating cluster-external Provider client%s", withEndpoint) client, err = newExternalClusterClient(p.Endpoint, p.Token, p.CertAuthFilePath) } if err != nil { return nil, err } client.labelSelector = p.LabelSelector return client, nil } func (p *Provider) loadConfiguration(ctx context.Context) (*dynamic.Configuration, []*knativenetworkingv1alpha1.Ingress) { conf := &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: make(map[string]*dynamic.Router), Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), }, } var ingressStatuses []*knativenetworkingv1alpha1.Ingress uniqCerts := make(map[string]*tls.CertAndStores) for _, ingress := range p.client.ListIngresses() { logger := log.Ctx(ctx).With(). Str("ingress", ingress.Name). Str("namespace", ingress.Namespace). Logger() if ingress.Annotations[knativenetworking.IngressClassAnnotationKey] != traefikIngressClassName { logger.Debug().Msgf("Skipping Ingress %s/%s", ingress.Namespace, ingress.Name) continue } if err := p.loadCertificates(ctx, ingress, uniqCerts); err != nil { logger.Error().Err(err).Msg("Error loading TLS certificates") continue } conf.HTTP = mergeHTTPConfigs(conf.HTTP, p.buildRouters(ctx, ingress)) // TODO: should we handle configuration errors? ingressStatuses = append(ingressStatuses, ingress) } if len(uniqCerts) > 0 { conf.TLS = &dynamic.TLSConfiguration{ Certificates: slices.Collect(maps.Values(uniqCerts)), } } return conf, ingressStatuses } // loadCertificates loads the TLS certificates for the given Knative Ingress. // This method mutates the uniqCerts map to add the loaded certificates. func (p *Provider) loadCertificates(ctx context.Context, ingress *knativenetworkingv1alpha1.Ingress, uniqCerts map[string]*tls.CertAndStores) error { for _, t := range ingress.Spec.TLS { // TODO: maybe this could be allowed with an allowCrossNamespace option in the future. if t.SecretNamespace != ingress.Namespace { log.Ctx(ctx).Debug().Msg("TLS secret namespace has to be the same as the Ingress one") continue } key := ingress.Namespace + "-" + t.SecretName // TODO: as specified in the GoDoc we should validate that the certificates contain the configured Hosts. if _, exists := uniqCerts[key]; !exists { cert, err := p.loadCertificate(ingress.Namespace, t.SecretName) if err != nil { return fmt.Errorf("getting certificate: %w", err) } uniqCerts[key] = &tls.CertAndStores{Certificate: cert} } } return nil } func (p *Provider) loadCertificate(namespace, secretName string) (tls.Certificate, error) { secret, err := p.client.GetSecret(namespace, secretName) if err != nil { return tls.Certificate{}, fmt.Errorf("getting secret %s/%s: %w", namespace, secretName, err) } certBytes, hasCert := secret.Data[corev1.TLSCertKey] keyBytes, hasKey := secret.Data[corev1.TLSPrivateKeyKey] if (!hasCert || len(certBytes) == 0) || (!hasKey || len(keyBytes) == 0) { return tls.Certificate{}, errors.New("secret does not contain a keypair") } return tls.Certificate{ CertFile: types.FileOrContent(certBytes), KeyFile: types.FileOrContent(keyBytes), }, nil } func (p *Provider) buildRouters(ctx context.Context, ingress *knativenetworkingv1alpha1.Ingress) *dynamic.HTTPConfiguration { logger := log.Ctx(ctx).With().Logger() conf := &dynamic.HTTPConfiguration{ Routers: make(map[string]*dynamic.Router), Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), } for ri, rule := range ingress.Spec.Rules { if rule.HTTP == nil { logger.Debug().Msgf("No HTTP rule defined for rule %d in Ingress %s", ri, ingress.Name) continue } entrypoints := p.PublicEntrypoints if rule.Visibility == knativenetworkingv1alpha1.IngressVisibilityClusterLocal { if p.PrivateEntrypoints == nil { // Skip route creation as no internal entrypoints are defined for cluster local visibility. continue } entrypoints = p.PrivateEntrypoints } // TODO: support rewrite host for pi, path := range rule.HTTP.Paths { routerKey := fmt.Sprintf("%s-%s-rule-%d-path-%d", ingress.Namespace, ingress.Name, ri, pi) router := &dynamic.Router{ EntryPoints: entrypoints, Rule: buildRule(rule.Hosts, path.Headers, path.Path), Middlewares: make([]string, 0), Service: routerKey + "-wrr", } if len(path.AppendHeaders) > 0 { midKey := fmt.Sprintf("%s-append-headers", routerKey) router.Middlewares = append(router.Middlewares, midKey) conf.Middlewares[midKey] = &dynamic.Middleware{ Headers: &dynamic.Headers{ CustomRequestHeaders: path.AppendHeaders, }, } } wrr, services, err := p.buildWeightedRoundRobin(routerKey, path.Splits) if err != nil { logger.Error().Err(err).Msg("Error building weighted round robin") continue } // TODO: support Ingress#HTTPOption to check if HTTP router should redirect to the HTTPS one. conf.Routers[routerKey] = router // TODO: at some point we should allow to define a default TLS secret at the provider level to enable TLS with a custom cert when external-domain-tls is disabled. // see https://knative.dev/docs/serving/encryption/external-domain-tls/#manually-obtain-and-renew-certificates if len(ingress.Spec.TLS) > 0 { conf.Routers[routerKey+"-tls"] = &dynamic.Router{ EntryPoints: router.EntryPoints, Rule: router.Rule, // TODO: maybe the rule should be a new one containing the TLS hosts injected by Knative. Middlewares: router.Middlewares, Service: router.Service, TLS: &dynamic.RouterTLSConfig{}, } } conf.Services[routerKey+"-wrr"] = &dynamic.Service{Weighted: wrr} for k, v := range services { conf.Services[k] = v } } } return conf } func (p *Provider) buildWeightedRoundRobin(routerKey string, splits []knativenetworkingv1alpha1.IngressBackendSplit) (*dynamic.WeightedRoundRobin, map[string]*dynamic.Service, error) { wrr := &dynamic.WeightedRoundRobin{ Services: make([]dynamic.WRRService, 0), } services := make(map[string]*dynamic.Service) for si, split := range splits { serviceKey := fmt.Sprintf("%s-split-%d", routerKey, si) var err error services[serviceKey], err = p.buildService(split.ServiceNamespace, split.ServiceName, split.ServicePort) if err != nil { return nil, nil, fmt.Errorf("building service: %w", err) } // As described in the spec if there is only one split it defaults to 100. percent := split.Percent if len(splits) == 1 { percent = 100 } wrr.Services = append(wrr.Services, dynamic.WRRService{ Name: serviceKey, Weight: ptr.To(percent), Headers: split.AppendHeaders, }) } return wrr, services, nil } func (p *Provider) buildService(namespace, serviceName string, port intstr.IntOrString) (*dynamic.Service, error) { servers, err := p.buildServers(namespace, serviceName, port) if err != nil { return nil, fmt.Errorf("building servers: %w", err) } var lb dynamic.ServersLoadBalancer lb.SetDefaults() lb.Servers = servers return &dynamic.Service{LoadBalancer: &lb}, nil } func (p *Provider) buildServers(namespace, serviceName string, port intstr.IntOrString) ([]dynamic.Server, error) { service, err := p.client.GetService(namespace, serviceName) if err != nil { return nil, fmt.Errorf("getting service %s/%s: %w", namespace, serviceName, err) } var svcPort *corev1.ServicePort for _, p := range service.Spec.Ports { if p.Name == port.String() || strconv.Itoa(int(p.Port)) == port.String() { svcPort = &p break } } if svcPort == nil { return nil, errors.New("service port not found") } if service.Spec.ClusterIP == "" { return nil, errors.New("service does not have a ClusterIP") } scheme := "http" if svcPort.AppProtocol != nil && *svcPort.AppProtocol == knativenetworking.AppProtocolH2C { scheme = "h2c" } hostPort := net.JoinHostPort(service.Spec.ClusterIP, strconv.Itoa(int(svcPort.Port))) return []dynamic.Server{{URL: fmt.Sprintf("%s://%s", scheme, hostPort)}}, nil } func (p *Provider) updateKnativeIngressStatus(ctx context.Context, ingress *knativenetworkingv1alpha1.Ingress) error { log.Ctx(ctx).Debug().Msgf("Updating status for Ingress %s/%s", ingress.Namespace, ingress.Name) var publicLbs []knativenetworkingv1alpha1.LoadBalancerIngressStatus if p.PublicService.Name != "" && p.PublicService.Namespace != "" { publicLbs = append(publicLbs, knativenetworkingv1alpha1.LoadBalancerIngressStatus{ DomainInternal: network.GetServiceHostname(p.PublicService.Name, p.PublicService.Namespace), }) } var privateLbs []knativenetworkingv1alpha1.LoadBalancerIngressStatus if p.PrivateService.Name != "" && p.PrivateService.Namespace != "" { privateLbs = append(privateLbs, knativenetworkingv1alpha1.LoadBalancerIngressStatus{ DomainInternal: network.GetServiceHostname(p.PrivateService.Name, p.PrivateService.Namespace), }) } if ingress.GetStatus() == nil || !ingress.GetStatus().GetCondition(knativenetworkingv1alpha1.IngressConditionNetworkConfigured).IsTrue() || ingress.GetGeneration() != ingress.GetStatus().ObservedGeneration { ingress.Status.MarkNetworkConfigured() ingress.Status.MarkLoadBalancerReady(publicLbs, privateLbs) ingress.Status.ObservedGeneration = ingress.GetGeneration() return p.client.UpdateIngressStatus(ingress) } return nil } func buildRule(hosts []string, headers map[string]knativenetworkingv1alpha1.HeaderMatch, path string) string { var operands []string if len(hosts) > 0 { var hostRules []string for _, host := range hosts { hostRules = append(hostRules, fmt.Sprintf("Host(`%v`)", host)) } operands = append(operands, fmt.Sprintf("(%s)", strings.Join(hostRules, " || "))) } if len(headers) > 0 { headerKeys := slices.Collect(maps.Keys(headers)) slices.Sort(headerKeys) var headerRules []string for _, key := range headerKeys { headerRules = append(headerRules, fmt.Sprintf("Header(`%s`,`%s`)", key, headers[key].Exact)) } operands = append(operands, fmt.Sprintf("(%s)", strings.Join(headerRules, " && "))) } if len(path) > 0 { operands = append(operands, fmt.Sprintf("PathPrefix(`%s`)", path)) } return strings.Join(operands, " && ") } func mergeHTTPConfigs(confs ...*dynamic.HTTPConfiguration) *dynamic.HTTPConfiguration { conf := &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, } for _, c := range confs { for k, v := range c.Routers { conf.Routers[k] = v } for k, v := range c.Middlewares { conf.Middlewares[k] = v } for k, v := range c.Services { conf.Services[k] = v } } return conf } func throttleEvents(ctx context.Context, throttleDuration time.Duration, pool *safe.Pool, eventsChan <-chan interface{}) chan interface{} { logger := log.Ctx(ctx).With().Logger() if throttleDuration == 0 { return nil } // Create a buffered channel to hold the pending event (if we're delaying processing the event due to throttling) eventsChanBuffered := make(chan interface{}, 1) // Run a goroutine that reads events from eventChan and does a non-blocking write to pendingEvent. // This guarantees that writing to eventChan will never block, // and that pendingEvent will have something in it if there's been an event since we read from that channel. pool.GoCtx(func(ctxPool context.Context) { for { select { case <-ctxPool.Done(): return case nextEvent := <-eventsChan: select { case eventsChanBuffered <- nextEvent: default: // We already have an event in eventsChanBuffered, so we'll do a refresh as soon as our throttle allows us to. // It's fine to drop the event and keep whatever's in the buffer -- we don't do different things for different events logger.Debug().Msgf("Dropping event kind %T due to throttling", nextEvent) } } } }) return eventsChanBuffered }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/k8s/parser.go
pkg/provider/kubernetes/k8s/parser.go
package k8s import ( "fmt" "regexp" "strings" "github.com/rs/zerolog/log" "k8s.io/apimachinery/pkg/runtime" kscheme "k8s.io/client-go/kubernetes/scheme" ) // MustParseYaml parses a YAML to objects. func MustParseYaml(content []byte) []runtime.Object { acceptedK8sTypes := regexp.MustCompile(`^(Namespace|Deployment|EndpointSlice|Node|Service|ConfigMap|Ingress|IngressRoute|IngressRouteTCP|IngressRouteUDP|Middleware|MiddlewareTCP|Secret|TLSOption|TLSStore|TraefikService|IngressClass|ServersTransport|ServersTransportTCP|GatewayClass|Gateway|GRPCRoute|HTTPRoute|TCPRoute|TLSRoute|ReferenceGrant|BackendTLSPolicy)$`) files := strings.Split(string(content), "---\n") retVal := make([]runtime.Object, 0, len(files)) for _, file := range files { if file == "\n" || file == "" { continue } decode := kscheme.Codecs.UniversalDeserializer().Decode obj, groupVersionKind, err := decode([]byte(file), nil, nil) if err != nil { panic(fmt.Sprintf("Error while decoding YAML object. Err was: %s", err)) } if !acceptedK8sTypes.MatchString(groupVersionKind.Kind) { log.Debug().Msgf("The custom-roles configMap contained K8s object types which are not supported! Skipping object with type: %s", groupVersionKind.Kind) } else { retVal = append(retVal, obj) } } return retVal }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/k8s/router_transform.go
pkg/provider/kubernetes/k8s/router_transform.go
package k8s import ( "context" "github.com/traefik/traefik/v3/pkg/config/dynamic" "k8s.io/apimachinery/pkg/runtime" ) type RouterTransform interface { Apply(ctx context.Context, rt *dynamic.Router, object runtime.Object) error }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/k8s/event_handler_test.go
pkg/provider/kubernetes/k8s/event_handler_test.go
package k8s import ( "testing" "github.com/stretchr/testify/assert" discoveryv1 "k8s.io/api/discovery/v1" netv1 "k8s.io/api/networking/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func Test_detectChanges(t *testing.T) { portA := int32(80) portB := int32(8080) tests := []struct { name string oldObj interface{} newObj interface{} want bool }{ { name: "With nil values", want: true, }, { name: "With empty endpointslice", oldObj: &discoveryv1.EndpointSlice{}, newObj: &discoveryv1.EndpointSlice{}, }, { name: "With old nil", newObj: &discoveryv1.EndpointSlice{}, want: true, }, { name: "With new nil", oldObj: &discoveryv1.EndpointSlice{}, want: true, }, { name: "With same version", oldObj: &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "1", }, }, newObj: &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "1", }, }, }, { name: "With different version", oldObj: &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "1", }, }, newObj: &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "2", }, }, }, { name: "Ingress With same version", oldObj: &netv1.Ingress{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "1", }, }, newObj: &netv1.Ingress{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "1", }, }, }, { name: "Ingress With different version", oldObj: &netv1.Ingress{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "1", }, }, newObj: &netv1.Ingress{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "2", }, }, want: true, }, { name: "With same annotations", oldObj: &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "1", Annotations: map[string]string{ "test-annotation": "_", }, }, }, newObj: &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "2", Annotations: map[string]string{ "test-annotation": "_", }, }, }, }, { name: "With different annotations", oldObj: &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "1", Annotations: map[string]string{ "test-annotation": "V", }, }, }, newObj: &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "2", Annotations: map[string]string{ "test-annotation": "X", }, }, }, }, { name: "With same endpoints and ports", oldObj: &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "1", }, Endpoints: []discoveryv1.Endpoint{}, Ports: []discoveryv1.EndpointPort{}, }, newObj: &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "1", }, Endpoints: []discoveryv1.Endpoint{}, Ports: []discoveryv1.EndpointPort{}, }, }, { name: "With different len of endpoints", oldObj: &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "1", }, Endpoints: []discoveryv1.Endpoint{}, }, newObj: &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "2", }, Endpoints: []discoveryv1.Endpoint{{}}, }, want: true, }, { name: "With different endpoints", oldObj: &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "1", }, Endpoints: []discoveryv1.Endpoint{{ Addresses: []string{"10.10.10.10"}, }}, }, newObj: &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "2", }, Endpoints: []discoveryv1.Endpoint{{ Addresses: []string{"10.10.10.11"}, }}, }, want: true, }, { name: "With different len of ports", oldObj: &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "1", }, Ports: []discoveryv1.EndpointPort{}, }, newObj: &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "2", }, Ports: []discoveryv1.EndpointPort{{}}, }, want: true, }, { name: "With different ports", oldObj: &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "1", }, Ports: []discoveryv1.EndpointPort{{ Port: &portA, }}, }, newObj: &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ ResourceVersion: "2", }, Ports: []discoveryv1.EndpointPort{{ Port: &portB, }}, }, want: true, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { t.Parallel() assert.Equal(t, test.want, objChanged(test.oldObj, test.newObj)) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/k8s/endpoint_test.go
pkg/provider/kubernetes/k8s/endpoint_test.go
package k8s import ( "testing" "github.com/stretchr/testify/assert" v1 "k8s.io/api/discovery/v1" ) func TestEndpointServing(t *testing.T) { tests := []struct { name string endpoint v1.Endpoint want bool }{ { name: "no status", endpoint: v1.Endpoint{ Conditions: v1.EndpointConditions{ Ready: nil, Serving: nil, }, }, want: false, }, { name: "ready", endpoint: v1.Endpoint{ Conditions: v1.EndpointConditions{ Ready: pointer(true), Serving: nil, }, }, want: true, }, { name: "not ready", endpoint: v1.Endpoint{ Conditions: v1.EndpointConditions{ Ready: pointer(false), Serving: nil, }, }, want: false, }, { name: "not ready and serving", endpoint: v1.Endpoint{ Conditions: v1.EndpointConditions{ Ready: pointer(false), Serving: pointer(true), }, }, want: true, }, { name: "not ready and not serving", endpoint: v1.Endpoint{ Conditions: v1.EndpointConditions{ Ready: pointer(false), Serving: pointer(false), }, }, want: false, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { got := EndpointServing(test.endpoint) assert.Equal(t, test.want, got) }) } } 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/provider/kubernetes/k8s/event_handler.go
pkg/provider/kubernetes/k8s/event_handler.go
package k8s import ( discoveryv1 "k8s.io/api/discovery/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // ResourceEventHandler handles Add, Update or Delete Events for resources. type ResourceEventHandler struct { Ev chan<- interface{} } // OnAdd is called on Add Events. func (reh *ResourceEventHandler) OnAdd(obj interface{}, _ bool) { eventHandlerFunc(reh.Ev, obj) } // OnUpdate is called on Update Events. // Ignores useless changes. func (reh *ResourceEventHandler) OnUpdate(oldObj, newObj interface{}) { if objChanged(oldObj, newObj) { eventHandlerFunc(reh.Ev, newObj) } } // OnDelete is called on Delete Events. func (reh *ResourceEventHandler) OnDelete(obj interface{}) { eventHandlerFunc(reh.Ev, obj) } // eventHandlerFunc will pass the obj on to the events channel or drop it. // This is so passing the events along won't block in the case of high volume. // The events are only used for signaling anyway so dropping a few is ok. func eventHandlerFunc(events chan<- interface{}, obj interface{}) { select { case events <- obj: default: } } func objChanged(oldObj, newObj interface{}) bool { if oldObj == nil || newObj == nil { return true } if oldObj.(metav1.Object).GetResourceVersion() == newObj.(metav1.Object).GetResourceVersion() { return false } if _, ok := oldObj.(*discoveryv1.EndpointSlice); ok { return endpointSliceChanged(oldObj.(*discoveryv1.EndpointSlice), newObj.(*discoveryv1.EndpointSlice)) } return true } // In some Kubernetes versions leader election is done by updating an endpoint annotation every second, // if there are no changes to the endpoints addresses, ports, and there are no addresses defined for an endpoint // the event can safely be ignored and won't cause unnecessary config reloads. // TODO: check if Kubernetes is still using EndpointSlice for leader election, which seems to not be the case anymore. func endpointSliceChanged(a, b *discoveryv1.EndpointSlice) bool { if len(a.Ports) != len(b.Ports) { return true } for i, aport := range a.Ports { bport := b.Ports[i] if aport.Name != bport.Name { return true } if aport.Port != bport.Port { return true } } if len(a.Endpoints) != len(b.Endpoints) { return true } for i, ea := range a.Endpoints { eb := b.Endpoints[i] if endpointChanged(ea, eb) { return true } } return false } func endpointChanged(a, b discoveryv1.Endpoint) bool { if len(a.Addresses) != len(b.Addresses) { return true } for i, aaddr := range a.Addresses { baddr := b.Addresses[i] if aaddr != baddr { return true } } return false }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/k8s/endpoint.go
pkg/provider/kubernetes/k8s/endpoint.go
package k8s import ( v1 "k8s.io/api/discovery/v1" "k8s.io/utils/ptr" ) // EndpointServing returns true if the endpoint is still serving the service. func EndpointServing(endpoint v1.Endpoint) bool { return ptr.Deref(endpoint.Conditions.Ready, false) || ptr.Deref(endpoint.Conditions.Serving, false) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/ingress/builder_ingress_test.go
pkg/provider/kubernetes/ingress/builder_ingress_test.go
package ingress import netv1 "k8s.io/api/networking/v1" func buildIngress(opts ...func(*netv1.Ingress)) *netv1.Ingress { i := &netv1.Ingress{} i.Kind = "Ingress" for _, opt := range opts { opt(i) } return i } func iNamespace(value string) func(*netv1.Ingress) { return func(i *netv1.Ingress) { i.Namespace = value } } func iRules(opts ...func(*netv1.IngressSpec)) func(*netv1.Ingress) { return func(i *netv1.Ingress) { s := &netv1.IngressSpec{} for _, opt := range opts { opt(s) } i.Spec = *s } } func iRule(opts ...func(*netv1.IngressRule)) func(*netv1.IngressSpec) { return func(spec *netv1.IngressSpec) { r := &netv1.IngressRule{} for _, opt := range opts { opt(r) } spec.Rules = append(spec.Rules, *r) } } func iHost(name string) func(*netv1.IngressRule) { return func(rule *netv1.IngressRule) { rule.Host = name } } func iTLSes(opts ...func(*netv1.IngressTLS)) func(*netv1.Ingress) { return func(i *netv1.Ingress) { for _, opt := range opts { iTLS := netv1.IngressTLS{} opt(&iTLS) i.Spec.TLS = append(i.Spec.TLS, iTLS) } } } func iTLS(secret string, hosts ...string) func(*netv1.IngressTLS) { return func(i *netv1.IngressTLS) { i.SecretName = secret i.Hosts = hosts } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/ingress/convert_test.go
pkg/provider/kubernetes/ingress/convert_test.go
package ingress import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" netv1 "k8s.io/api/networking/v1" ) func Test_convertSlice_corev1_to_networkingv1(t *testing.T) { g := []corev1.LoadBalancerIngress{ { IP: "132456", Hostname: "foo", Ports: []corev1.PortStatus{ { Port: 123, Protocol: "https", Error: pointer("test"), }, }, }, } actual, err := convertSlice[netv1.IngressLoadBalancerIngress](g) require.NoError(t, err) expected := []netv1.IngressLoadBalancerIngress{ { IP: "132456", Hostname: "foo", Ports: []netv1.IngressPortStatus{ { Port: 123, Protocol: "https", Error: pointer("test"), }, }, }, } assert.Equal(t, expected, actual) } func Test_convert(t *testing.T) { g := &corev1.LoadBalancerIngress{ IP: "132456", Hostname: "foo", Ports: []corev1.PortStatus{ { Port: 123, Protocol: "https", Error: pointer("test"), }, }, } actual, err := convert[netv1.IngressLoadBalancerIngress](g) require.NoError(t, err) expected := &netv1.IngressLoadBalancerIngress{ IP: "132456", Hostname: "foo", Ports: []netv1.IngressPortStatus{ { Port: 123, Protocol: "https", Error: pointer("test"), }, }, } assert.Equal(t, expected, actual) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/ingress/client.go
pkg/provider/kubernetes/ingress/client.go
package ingress import ( "context" "errors" "fmt" "os" "path/filepath" "runtime" "slices" "time" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/k8s" "github.com/traefik/traefik/v3/pkg/types" traefikversion "github.com/traefik/traefik/v3/pkg/version" corev1 "k8s.io/api/core/v1" discoveryv1 "k8s.io/api/discovery/v1" netv1 "k8s.io/api/networking/v1" kerror "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/selection" kinformers "k8s.io/client-go/informers" kclientset "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" ) const ( resyncPeriod = 10 * time.Minute defaultTimeout = 5 * time.Second ) // Client is a client for the Provider master. // WatchAll starts the watch of the Provider resources and updates the stores. // The stores can then be accessed via the Get* functions. type Client interface { WatchAll(namespaces []string, stopCh <-chan struct{}) (<-chan interface{}, error) GetIngresses() []*netv1.Ingress GetIngressClasses() ([]*netv1.IngressClass, error) GetService(namespace, name string) (*corev1.Service, bool, error) GetSecret(namespace, name string) (*corev1.Secret, bool, error) GetNodes() ([]*corev1.Node, bool, error) GetEndpointSlicesForService(namespace, serviceName string) ([]*discoveryv1.EndpointSlice, error) UpdateIngressStatus(ing *netv1.Ingress, ingStatus []netv1.IngressLoadBalancerIngress) error } type clientWrapper struct { clientset kclientset.Interface clusterScopeFactory kinformers.SharedInformerFactory factoriesKube map[string]kinformers.SharedInformerFactory factoriesSecret map[string]kinformers.SharedInformerFactory factoriesIngress map[string]kinformers.SharedInformerFactory ingressLabelSelector string isNamespaceAll bool disableIngressClassInformer bool // Deprecated. disableClusterScopeInformer bool watchedNamespaces []string } // newInClusterClient returns a new Provider client that is expected to run // inside the cluster. func newInClusterClient(endpoint string) (*clientWrapper, error) { config, err := rest.InClusterConfig() if err != nil { return nil, fmt.Errorf("failed to create in-cluster configuration: %w", err) } if endpoint != "" { config.Host = endpoint } return createClientFromConfig(config) } func newExternalClusterClientFromFile(file string) (*clientWrapper, error) { configFromFlags, err := clientcmd.BuildConfigFromFlags("", file) if err != nil { return nil, err } return createClientFromConfig(configFromFlags) } // newExternalClusterClient returns a new Provider client that may run outside // of the cluster. // The endpoint parameter must not be empty. func newExternalClusterClient(endpoint, caFilePath string, token types.FileOrContent) (*clientWrapper, error) { if endpoint == "" { return nil, errors.New("endpoint missing for external cluster client") } tokenData, err := token.Read() if err != nil { return nil, fmt.Errorf("read token: %w", err) } config := &rest.Config{ Host: endpoint, BearerToken: string(tokenData), } if caFilePath != "" { caData, err := os.ReadFile(caFilePath) if err != nil { return nil, fmt.Errorf("failed to read CA file %s: %w", caFilePath, err) } config.TLSClientConfig = rest.TLSClientConfig{CAData: caData} } return createClientFromConfig(config) } func createClientFromConfig(c *rest.Config) (*clientWrapper, error) { c.UserAgent = fmt.Sprintf( "%s/%s (%s/%s) kubernetes/ingress", filepath.Base(os.Args[0]), traefikversion.Version, runtime.GOOS, runtime.GOARCH, ) clientset, err := kclientset.NewForConfig(c) if err != nil { return nil, err } return newClientImpl(clientset), nil } func newClientImpl(clientset kclientset.Interface) *clientWrapper { return &clientWrapper{ clientset: clientset, factoriesSecret: make(map[string]kinformers.SharedInformerFactory), factoriesIngress: make(map[string]kinformers.SharedInformerFactory), factoriesKube: make(map[string]kinformers.SharedInformerFactory), } } // WatchAll starts namespace-specific controllers for all relevant kinds. func (c *clientWrapper) WatchAll(namespaces []string, stopCh <-chan struct{}) (<-chan interface{}, error) { eventCh := make(chan interface{}, 1) eventHandler := &k8s.ResourceEventHandler{Ev: eventCh} if len(namespaces) == 0 { namespaces = []string{metav1.NamespaceAll} c.isNamespaceAll = true } c.watchedNamespaces = namespaces notOwnedByHelm := func(opts *metav1.ListOptions) { opts.LabelSelector = "owner!=helm" } matchesLabelSelector := func(opts *metav1.ListOptions) { opts.LabelSelector = c.ingressLabelSelector } for _, ns := range namespaces { factoryIngress := kinformers.NewSharedInformerFactoryWithOptions(c.clientset, resyncPeriod, kinformers.WithNamespace(ns), kinformers.WithTweakListOptions(matchesLabelSelector)) _, err := factoryIngress.Networking().V1().Ingresses().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } c.factoriesIngress[ns] = factoryIngress factoryKube := kinformers.NewSharedInformerFactoryWithOptions(c.clientset, resyncPeriod, kinformers.WithNamespace(ns)) _, err = factoryKube.Core().V1().Services().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryKube.Discovery().V1().EndpointSlices().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } c.factoriesKube[ns] = factoryKube factorySecret := kinformers.NewSharedInformerFactoryWithOptions(c.clientset, resyncPeriod, kinformers.WithNamespace(ns), kinformers.WithTweakListOptions(notOwnedByHelm)) _, err = factorySecret.Core().V1().Secrets().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } c.factoriesSecret[ns] = factorySecret } for _, ns := range namespaces { c.factoriesIngress[ns].Start(stopCh) c.factoriesKube[ns].Start(stopCh) c.factoriesSecret[ns].Start(stopCh) } for _, ns := range namespaces { for t, ok := range c.factoriesIngress[ns].WaitForCacheSync(stopCh) { if !ok { return nil, fmt.Errorf("timed out waiting for controller caches to sync %s in namespace %q", t.String(), ns) } } for t, ok := range c.factoriesKube[ns].WaitForCacheSync(stopCh) { if !ok { return nil, fmt.Errorf("timed out waiting for controller caches to sync %s in namespace %q", t.String(), ns) } } for t, ok := range c.factoriesSecret[ns].WaitForCacheSync(stopCh) { if !ok { return nil, fmt.Errorf("timed out waiting for controller caches to sync %s in namespace %q", t.String(), ns) } } } if !c.disableIngressClassInformer || !c.disableClusterScopeInformer { c.clusterScopeFactory = kinformers.NewSharedInformerFactory(c.clientset, resyncPeriod) _, err := c.clusterScopeFactory.Networking().V1().IngressClasses().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } if !c.disableClusterScopeInformer { _, err = c.clusterScopeFactory.Core().V1().Nodes().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } } c.clusterScopeFactory.Start(stopCh) for t, ok := range c.clusterScopeFactory.WaitForCacheSync(stopCh) { if !ok { return nil, fmt.Errorf("timed out waiting for controller caches to sync %s", t.String()) } } } return eventCh, nil } // GetIngresses returns all Ingresses for observed namespaces in the cluster. func (c *clientWrapper) GetIngresses() []*netv1.Ingress { var results []*netv1.Ingress for ns, factory := range c.factoriesIngress { // networking listNew, err := factory.Networking().V1().Ingresses().Lister().List(labels.Everything()) if err != nil { log.Error().Err(err).Msgf("Failed to list ingresses in namespace %s", ns) continue } results = append(results, listNew...) } return results } // UpdateIngressStatus updates an Ingress with a provided status. func (c *clientWrapper) UpdateIngressStatus(src *netv1.Ingress, ingStatus []netv1.IngressLoadBalancerIngress) error { if !c.isWatchedNamespace(src.Namespace) { return fmt.Errorf("failed to get ingress %s/%s: namespace is not within watched namespaces", src.Namespace, src.Name) } ing, err := c.factoriesIngress[c.lookupNamespace(src.Namespace)].Networking().V1().Ingresses().Lister().Ingresses(src.Namespace).Get(src.Name) if err != nil { return fmt.Errorf("failed to get ingress %s/%s: %w", src.Namespace, src.Name, err) } logger := log.With().Str("namespace", ing.Namespace).Str("ingress", ing.Name).Logger() if isLoadBalancerIngressEquals(ing.Status.LoadBalancer.Ingress, ingStatus) { logger.Debug().Msg("Skipping ingress status update") return nil } ingCopy := ing.DeepCopy() ingCopy.Status = netv1.IngressStatus{LoadBalancer: netv1.IngressLoadBalancerStatus{Ingress: ingStatus}} ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout) defer cancel() _, err = c.clientset.NetworkingV1().Ingresses(ingCopy.Namespace).UpdateStatus(ctx, ingCopy, metav1.UpdateOptions{}) if err != nil { return fmt.Errorf("failed to update ingress status %s/%s: %w", src.Namespace, src.Name, err) } logger.Info().Msg("Updated ingress status") return nil } // isLoadBalancerIngressEquals returns true if the given slices are equal, false otherwise. func isLoadBalancerIngressEquals(aSlice, bSlice []netv1.IngressLoadBalancerIngress) bool { if len(aSlice) != len(bSlice) { return false } aMap := make(map[string]struct{}) for _, aIngress := range aSlice { aMap[aIngress.Hostname+aIngress.IP] = struct{}{} } for _, bIngress := range bSlice { if _, exists := aMap[bIngress.Hostname+bIngress.IP]; !exists { return false } } return true } // GetService returns the named service from the given namespace. func (c *clientWrapper) GetService(namespace, name string) (*corev1.Service, bool, error) { if !c.isWatchedNamespace(namespace) { return nil, false, fmt.Errorf("failed to get service %s/%s: namespace is not within watched namespaces", namespace, name) } service, err := c.factoriesKube[c.lookupNamespace(namespace)].Core().V1().Services().Lister().Services(namespace).Get(name) exist, err := translateNotFoundError(err) return service, exist, err } // GetEndpointSlicesForService returns the EndpointSlices for the given service name in the given namespace. func (c *clientWrapper) GetEndpointSlicesForService(namespace, serviceName string) ([]*discoveryv1.EndpointSlice, error) { if !c.isWatchedNamespace(namespace) { return nil, fmt.Errorf("failed to get endpointslices for service %s/%s: namespace is not within watched namespaces", namespace, serviceName) } serviceLabelRequirement, err := labels.NewRequirement(discoveryv1.LabelServiceName, selection.Equals, []string{serviceName}) if err != nil { return nil, fmt.Errorf("failed to create service label selector requirement: %w", err) } serviceSelector := labels.NewSelector() serviceSelector = serviceSelector.Add(*serviceLabelRequirement) return c.factoriesKube[c.lookupNamespace(namespace)].Discovery().V1().EndpointSlices().Lister().EndpointSlices(namespace).List(serviceSelector) } // GetSecret returns the named secret from the given namespace. func (c *clientWrapper) GetSecret(namespace, name string) (*corev1.Secret, bool, error) { if !c.isWatchedNamespace(namespace) { return nil, false, fmt.Errorf("failed to get secret %s/%s: namespace is not within watched namespaces", namespace, name) } secret, err := c.factoriesSecret[c.lookupNamespace(namespace)].Core().V1().Secrets().Lister().Secrets(namespace).Get(name) exist, err := translateNotFoundError(err) return secret, exist, err } func (c *clientWrapper) GetNodes() ([]*corev1.Node, bool, error) { nodes, err := c.clusterScopeFactory.Core().V1().Nodes().Lister().List(labels.Everything()) exist, err := translateNotFoundError(err) return nodes, exist, err } func (c *clientWrapper) GetIngressClasses() ([]*netv1.IngressClass, error) { if c.clusterScopeFactory == nil { return nil, errors.New("cluster factory not loaded") } var ics []*netv1.IngressClass ingressClasses, err := c.clusterScopeFactory.Networking().V1().IngressClasses().Lister().List(labels.Everything()) if err != nil { return nil, err } for _, ic := range ingressClasses { if ic.Spec.Controller == traefikDefaultIngressClassController { ics = append(ics, ic) } } return ics, nil } // lookupNamespace returns the lookup namespace key for the given namespace. // When listening on all namespaces, it returns the client-go identifier ("") // for all-namespaces. Otherwise, it returns the given namespace. // The distinction is necessary because we index all informers on the special // identifier iff all-namespaces are requested but receive specific namespace // identifiers from the Kubernetes API, so we have to bridge this gap. func (c *clientWrapper) lookupNamespace(ns string) string { if c.isNamespaceAll { return metav1.NamespaceAll } return ns } // translateNotFoundError will translate a "not found" error to a boolean return // value which indicates if the resource exists and a nil error. func translateNotFoundError(err error) (bool, error) { if kerror.IsNotFound(err) { return false, nil } return err == nil, err } // isWatchedNamespace checks to ensure that the namespace is being watched before we request // it to ensure we don't panic by requesting an out-of-watch object. func (c *clientWrapper) isWatchedNamespace(ns string) bool { if c.isNamespaceAll { return true } return slices.Contains(c.watchedNamespaces, ns) } // filterIngressClassByName return a slice containing ingressclasses with the correct name. func filterIngressClassByName(ingressClassName string, ics []*netv1.IngressClass) []*netv1.IngressClass { var ingressClasses []*netv1.IngressClass for _, ic := range ics { if ic.Name == ingressClassName { ingressClasses = append(ingressClasses, ic) } } return ingressClasses }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/ingress/annotations.go
pkg/provider/kubernetes/ingress/annotations.go
package ingress import ( "regexp" "strings" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/label" ) const ( // https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/#syntax-and-character-set annotationsPrefix = "traefik.ingress.kubernetes.io/" ) var annotationsRegex = regexp.MustCompile(`(.+)\.(\w+)\.(\d+)\.(.+)`) // RouterConfig is the router's root configuration from annotations. type RouterConfig struct { Router *RouterIng `json:"router,omitempty"` } // RouterIng is the router's configuration from annotations. type RouterIng struct { PathMatcher string `json:"pathMatcher,omitempty"` EntryPoints []string `json:"entryPoints,omitempty"` Middlewares []string `json:"middlewares,omitempty"` Priority int `json:"priority,omitempty"` RuleSyntax string `json:"ruleSyntax,omitempty"` TLS *dynamic.RouterTLSConfig `json:"tls,omitempty" label:"allowEmpty"` Observability *dynamic.RouterObservabilityConfig `json:"observability,omitempty" label:"allowEmpty"` } // SetDefaults sets the default values. func (r *RouterIng) SetDefaults() { r.PathMatcher = defaultPathMatcher } // ServiceConfig is the service's root configuration from annotations. type ServiceConfig struct { Service *ServiceIng `json:"service,omitempty"` } // ServiceIng is the service's configuration from annotations. type ServiceIng struct { ServersScheme string `json:"serversScheme,omitempty"` ServersTransport string `json:"serversTransport,omitempty"` PassHostHeader *bool `json:"passHostHeader"` Sticky *dynamic.Sticky `json:"sticky,omitempty" label:"allowEmpty"` NativeLB *bool `json:"nativeLB,omitempty"` NodePortLB bool `json:"nodePortLB,omitempty"` } // SetDefaults sets the default values. func (s *ServiceIng) SetDefaults() { s.PassHostHeader = func(v bool) *bool { return &v }(true) } func parseRouterConfig(annotations map[string]string) (*RouterConfig, error) { labels := convertAnnotations(annotations) if len(labels) == 0 { return nil, nil } cfg := &RouterConfig{} err := label.Decode(labels, cfg, "traefik.router.") if err != nil { return nil, err } return cfg, nil } func parseServiceConfig(annotations map[string]string) (*ServiceConfig, error) { labels := convertAnnotations(annotations) if len(labels) == 0 { return nil, nil } cfg := &ServiceConfig{} err := label.Decode(labels, cfg, "traefik.service.") if err != nil { return nil, err } return cfg, nil } func convertAnnotations(annotations map[string]string) map[string]string { if len(annotations) == 0 { return nil } result := make(map[string]string) for key, value := range annotations { if !strings.HasPrefix(key, annotationsPrefix) { continue } newKey := strings.ReplaceAll(key, "ingress.kubernetes.io/", "") if annotationsRegex.MatchString(newKey) { newKey = annotationsRegex.ReplaceAllString(newKey, "$1.$2[$3].$4") } result[newKey] = value } return result }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/ingress/convert.go
pkg/provider/kubernetes/ingress/convert.go
package ingress import ( "errors" corev1 "k8s.io/api/core/v1" netv1 "k8s.io/api/networking/v1" ) type marshaler interface { Marshal() ([]byte, error) } type unmarshaler interface { Unmarshal(data []byte) error } type LoadBalancerIngress interface { corev1.LoadBalancerIngress | netv1.IngressLoadBalancerIngress } // convertSlice converts slice of LoadBalancerIngress to slice of LoadBalancerIngress. // O (Bar), I (Foo) => []Bar. func convertSlice[O LoadBalancerIngress, I LoadBalancerIngress](loadBalancerIngresses []I) ([]O, error) { var results []O for _, loadBalancerIngress := range loadBalancerIngresses { mar, ok := any(&loadBalancerIngress).(marshaler) if !ok { // All the pointer of types related to the interface LoadBalancerIngress are compatible with the interface marshaler. continue } um, err := convert[O](mar) if err != nil { return nil, err } v, ok := any(*um).(O) if !ok { continue } results = append(results, v) } return results, nil } // convert must only be used with unmarshaler and marshaler compatible types. func convert[T any](input marshaler) (*T, error) { data, err := input.Marshal() if err != nil { return nil, err } var output T um, ok := any(&output).(unmarshaler) if !ok { return nil, errors.New("the output type doesn't implement unmarshaler interface") } err = um.Unmarshal(data) if err != nil { return nil, err } return &output, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/ingress/client_test.go
pkg/provider/kubernetes/ingress/client_test.go
package ingress import ( "errors" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" discoveryv1 "k8s.io/api/discovery/v1" netv1 "k8s.io/api/networking/v1" kerror "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" kschema "k8s.io/apimachinery/pkg/runtime/schema" kversion "k8s.io/apimachinery/pkg/version" discoveryfake "k8s.io/client-go/discovery/fake" kubefake "k8s.io/client-go/kubernetes/fake" ) func TestTranslateNotFoundError(t *testing.T) { testCases := []struct { desc string err error expectedExists bool expectedError error }{ { desc: "kubernetes not found error", err: kerror.NewNotFound(kschema.GroupResource{}, "foo"), expectedExists: false, expectedError: nil, }, { desc: "nil error", err: nil, expectedExists: true, expectedError: nil, }, { desc: "not a kubernetes not found error", err: errors.New("bar error"), expectedExists: false, expectedError: errors.New("bar error"), }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() exists, err := translateNotFoundError(test.err) assert.Equal(t, test.expectedExists, exists) assert.Equal(t, test.expectedError, err) }) } } func TestIsLoadBalancerIngressEquals(t *testing.T) { testCases := []struct { desc string aSlice []netv1.IngressLoadBalancerIngress bSlice []netv1.IngressLoadBalancerIngress expectedEqual bool }{ { desc: "both slices are empty", expectedEqual: true, }, { desc: "not the same length", bSlice: []netv1.IngressLoadBalancerIngress{ {IP: "192.168.1.1", Hostname: "traefik"}, }, expectedEqual: false, }, { desc: "same ordered content", aSlice: []netv1.IngressLoadBalancerIngress{ {IP: "192.168.1.1", Hostname: "traefik"}, }, bSlice: []netv1.IngressLoadBalancerIngress{ {IP: "192.168.1.1", Hostname: "traefik"}, }, expectedEqual: true, }, { desc: "same unordered content", aSlice: []netv1.IngressLoadBalancerIngress{ {IP: "192.168.1.1", Hostname: "traefik"}, {IP: "192.168.1.2", Hostname: "traefik2"}, }, bSlice: []netv1.IngressLoadBalancerIngress{ {IP: "192.168.1.2", Hostname: "traefik2"}, {IP: "192.168.1.1", Hostname: "traefik"}, }, expectedEqual: true, }, { desc: "different ordered content", aSlice: []netv1.IngressLoadBalancerIngress{ {IP: "192.168.1.1", Hostname: "traefik"}, {IP: "192.168.1.2", Hostname: "traefik2"}, }, bSlice: []netv1.IngressLoadBalancerIngress{ {IP: "192.168.1.1", Hostname: "traefik"}, {IP: "192.168.1.2", Hostname: "traefik"}, }, expectedEqual: false, }, { desc: "different unordered content", aSlice: []netv1.IngressLoadBalancerIngress{ {IP: "192.168.1.1", Hostname: "traefik"}, {IP: "192.168.1.2", Hostname: "traefik2"}, }, bSlice: []netv1.IngressLoadBalancerIngress{ {IP: "192.168.1.2", Hostname: "traefik3"}, {IP: "192.168.1.1", Hostname: "traefik"}, }, expectedEqual: false, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() gotEqual := isLoadBalancerIngressEquals(test.aSlice, test.bSlice) assert.Equal(t, test.expectedEqual, gotEqual) }) } } func TestClientIgnoresHelmOwnedSecrets(t *testing.T) { secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Namespace: "default", Name: "secret", }, } helmSecret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Namespace: "default", Name: "helm-secret", Labels: map[string]string{ "owner": "helm", }, }, } kubeClient := kubefake.NewSimpleClientset(helmSecret, secret) discovery, _ := kubeClient.Discovery().(*discoveryfake.FakeDiscovery) discovery.FakedServerVersion = &kversion.Info{ GitVersion: "v1.19", } client := newClientImpl(kubeClient) stopCh := make(chan struct{}) eventCh, err := client.WatchAll(nil, stopCh) require.NoError(t, err) select { case event := <-eventCh: secret, ok := event.(*corev1.Secret) require.True(t, ok) assert.NotEqual(t, "helm-secret", secret.Name) case <-time.After(50 * time.Millisecond): assert.Fail(t, "expected to receive event for secret") } select { case <-eventCh: assert.Fail(t, "received more than one event") case <-time.After(50 * time.Millisecond): } _, found, err := client.GetSecret("default", "secret") require.NoError(t, err) assert.True(t, found) _, found, err = client.GetSecret("default", "helm-secret") require.NoError(t, err) assert.False(t, found) } func TestClientIgnoresEmptyEndpointSliceUpdates(t *testing.T) { emptyEndpointSlice := &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ Name: "empty-endpointslice", Namespace: "test", ResourceVersion: "1244", Annotations: map[string]string{ "test-annotation": "_", }, }, } samplePortName := "testing" samplePortNumber := int32(1337) samplePortProtocol := corev1.ProtocolTCP sampleAddressReady := true filledEndpointSlice := &discoveryv1.EndpointSlice{ ObjectMeta: metav1.ObjectMeta{ Name: "filled-endpointslice", Namespace: "test", ResourceVersion: "1234", }, AddressType: discoveryv1.AddressTypeIPv4, Endpoints: []discoveryv1.Endpoint{{ Addresses: []string{"10.13.37.1"}, Conditions: discoveryv1.EndpointConditions{ Ready: &sampleAddressReady, }, }}, Ports: []discoveryv1.EndpointPort{{ Name: &samplePortName, Port: &samplePortNumber, Protocol: &samplePortProtocol, }}, } kubeClient := kubefake.NewSimpleClientset(emptyEndpointSlice, filledEndpointSlice) discovery, _ := kubeClient.Discovery().(*discoveryfake.FakeDiscovery) discovery.FakedServerVersion = &kversion.Info{ GitVersion: "v1.19", } client := newClientImpl(kubeClient) stopCh := make(chan struct{}) eventCh, err := client.WatchAll(nil, stopCh) require.NoError(t, err) select { case event := <-eventCh: ep, ok := event.(*discoveryv1.EndpointSlice) require.True(t, ok) assert.True(t, ep.Name == "empty-endpointslice" || ep.Name == "filled-endpointslice") case <-time.After(50 * time.Millisecond): assert.Fail(t, "expected to receive event for endpointslices") } emptyEndpointSlice, err = kubeClient.DiscoveryV1().EndpointSlices("test").Get(t.Context(), "empty-endpointslice", metav1.GetOptions{}) assert.NoError(t, err) // Update endpoint annotation and resource version (apparently not done by fake client itself) // to show an update that should not trigger an update event on our eventCh. // This reflects the behavior of kubernetes controllers which use endpoint annotations for leader election. emptyEndpointSlice.Annotations["test-annotation"] = "___" emptyEndpointSlice.ResourceVersion = "1245" _, err = kubeClient.DiscoveryV1().EndpointSlices("test").Update(t.Context(), emptyEndpointSlice, metav1.UpdateOptions{}) require.NoError(t, err) select { case event := <-eventCh: ep, ok := event.(*discoveryv1.EndpointSlice) require.True(t, ok) assert.Fail(t, "didn't expect to receive event for empty endpointslice update", ep.Name) case <-time.After(50 * time.Millisecond): } filledEndpointSlice, err = kubeClient.DiscoveryV1().EndpointSlices("test").Get(t.Context(), "filled-endpointslice", metav1.GetOptions{}) assert.NoError(t, err) filledEndpointSlice.Endpoints[0].Addresses[0] = "10.13.37.2" filledEndpointSlice.ResourceVersion = "1235" _, err = kubeClient.DiscoveryV1().EndpointSlices("test").Update(t.Context(), filledEndpointSlice, metav1.UpdateOptions{}) require.NoError(t, err) select { case event := <-eventCh: ep, ok := event.(*discoveryv1.EndpointSlice) require.True(t, ok) assert.Equal(t, "filled-endpointslice", ep.Name) case <-time.After(50 * time.Millisecond): assert.Fail(t, "expected to receive event for filled endpointslice") } select { case <-eventCh: assert.Fail(t, "received more than one event") case <-time.After(50 * time.Millisecond): } newPortNumber := int32(42) filledEndpointSlice.Ports[0].Port = &newPortNumber filledEndpointSlice.ResourceVersion = "1236" _, err = kubeClient.DiscoveryV1().EndpointSlices("test").Update(t.Context(), filledEndpointSlice, metav1.UpdateOptions{}) require.NoError(t, err) select { case event := <-eventCh: ep, ok := event.(*discoveryv1.EndpointSlice) require.True(t, ok) assert.Equal(t, "filled-endpointslice", ep.Name) case <-time.After(50 * time.Millisecond): assert.Fail(t, "expected to receive event for filled endpointslice") } select { case <-eventCh: assert.Fail(t, "received more than one event") case <-time.After(50 * time.Millisecond): } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/ingress/kubernetes_test.go
pkg/provider/kubernetes/ingress/kubernetes_test.go
package ingress import ( "errors" "fmt" "math" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" traefikhttp "github.com/traefik/traefik/v3/pkg/muxer/http" otypes "github.com/traefik/traefik/v3/pkg/observability/types" "github.com/traefik/traefik/v3/pkg/provider" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/k8s" "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" corev1 "k8s.io/api/core/v1" netv1 "k8s.io/api/networking/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" kubefake "k8s.io/client-go/kubernetes/fake" ) var _ provider.Provider = (*Provider)(nil) func pointer[T any](v T) *T { return &v } func TestLoadConfigurationFromIngresses(t *testing.T) { testCases := []struct { desc string ingressClass string expected *dynamic.Configuration allowEmptyServices bool disableIngressClassLookup bool disableClusterScopeResources bool defaultRuleSyntax string strictPrefixMatching bool }{ { desc: "Empty ingresses", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, }, }, }, { desc: "Ingress one rule host only", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, }, }, }, { desc: "Ingress with a basic rule on one path", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-bar": { Rule: "PathPrefix(`/bar`)", Service: "testing-service1-80", }, }, Services: map[string]*dynamic.Service{ "testing-service1-80": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:8080", }, { URL: "http://10.21.0.1:8080", }, }, }, }, }, }, }, }, { desc: "Ingress with annotations", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-bar": { Rule: "Path(`/bar`)", EntryPoints: []string{"ep1", "ep2"}, Service: "testing-service1-80", Middlewares: []string{"md1", "md2"}, Priority: 42, RuleSyntax: "v2", TLS: &dynamic.RouterTLSConfig{ CertResolver: "foobar", Domains: []types.Domain{ { Main: "domain.com", SANs: []string{"one.domain.com", "two.domain.com"}, }, { Main: "example.com", SANs: []string{"one.example.com", "two.example.com"}, }, }, Options: "foobar", }, Observability: &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Tracing: pointer(true), Metrics: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, }, Services: map[string]*dynamic.Service{ "testing-service1-80": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Sticky: &dynamic.Sticky{ Cookie: &dynamic.Cookie{ Name: "foobar", Secure: true, HTTPOnly: true, Path: pointer("/"), }, }, Servers: []dynamic.Server{ { URL: "protocol://10.10.0.1:8080", }, { URL: "protocol://10.21.0.1:8080", }, }, ServersTransport: "foobar@file", }, }, }, }, }, }, { desc: "Ingress with two different rules with one path", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-bar": { Rule: "PathPrefix(`/bar`)", Service: "testing-service1-80", }, "testing-foo": { Rule: "PathPrefix(`/foo`)", Service: "testing-service1-80", }, }, Services: map[string]*dynamic.Service{ "testing-service1-80": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:8080", }, { URL: "http://10.21.0.1:8080", }, }, }, }, }, }, }, }, { desc: "Ingress with conflicting routers on host", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-bar-bar-aba9a7d00e9b06a78e16": { Rule: "HostRegexp(`^[a-zA-Z0-9-]+\\.bar$`) && PathPrefix(`/bar`)", Service: "testing-service1-80", }, "testing-bar-bar-636bf36c00fedaab3d44": { Rule: "Host(`bar`) && PathPrefix(`/bar`)", Service: "testing-service1-80", }, }, Services: map[string]*dynamic.Service{ "testing-service1-80": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:8080", }, { URL: "http://10.21.0.1:8080", }, }, }, }, }, }, }, }, { desc: "Ingress with conflicting routers on path", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-foo-bar-d0b30949e54d6a7515ca": { Rule: "PathPrefix(`/foo/bar`)", Service: "testing-service1-80", }, "testing-foo-bar-dcd54bae39a6d7557f48": { Rule: "PathPrefix(`/foo-bar`)", Service: "testing-service1-80", }, }, Services: map[string]*dynamic.Service{ "testing-service1-80": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:8080", }, { URL: "http://10.21.0.1:8080", }, }, }, }, }, }, }, }, { desc: "Ingress one rule with two paths", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-bar": { Rule: "PathPrefix(`/bar`)", Service: "testing-service1-80", }, "testing-foo": { Rule: "PathPrefix(`/foo`)", Service: "testing-service1-80", }, }, Services: map[string]*dynamic.Service{ "testing-service1-80": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:8080", }, { URL: "http://10.21.0.1:8080", }, }, }, }, }, }, }, }, { desc: "Ingress one rule with one path and one host", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-traefik-tchouk-bar": { Rule: "Host(`traefik.tchouk`) && PathPrefix(`/bar`)", Service: "testing-service1-80", }, }, Services: map[string]*dynamic.Service{ "testing-service1-80": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:8080", }, { URL: "http://10.21.0.1:8080", }, }, }, }, }, }, }, }, { desc: "Ingress with one host without path", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-example-com": { Rule: "Host(`example.com`)", Service: "testing-example-com-80", }, }, Services: map[string]*dynamic.Service{ "testing-example-com-80": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.11.0.1:80", }, }, }, }, }, }, }, }, { desc: "Ingress one rule with one host and two paths", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-traefik-tchouk-bar": { Rule: "Host(`traefik.tchouk`) && PathPrefix(`/bar`)", Service: "testing-service1-80", }, "testing-traefik-tchouk-foo": { Rule: "Host(`traefik.tchouk`) && PathPrefix(`/foo`)", Service: "testing-service1-80", }, }, Services: map[string]*dynamic.Service{ "testing-service1-80": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:8080", }, { URL: "http://10.21.0.1:8080", }, }, }, }, }, }, }, }, { desc: "Ingress Two rules with one host and one path", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-traefik-tchouk-bar": { Rule: "Host(`traefik.tchouk`) && PathPrefix(`/bar`)", Service: "testing-service1-80", }, "testing-traefik-courgette-carotte": { Rule: "Host(`traefik.courgette`) && PathPrefix(`/carotte`)", Service: "testing-service1-80", }, }, Services: map[string]*dynamic.Service{ "testing-service1-80": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:8080", }, { URL: "http://10.21.0.1:8080", }, }, }, }, }, }, }, }, { desc: "Ingress with two services", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-traefik-tchouk-bar": { Rule: "Host(`traefik.tchouk`) && PathPrefix(`/bar`)", Service: "testing-service1-80", }, "testing-traefik-courgette-carotte": { Rule: "Host(`traefik.courgette`) && PathPrefix(`/carotte`)", Service: "testing-service2-8082", }, }, Services: map[string]*dynamic.Service{ "testing-service1-80": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:8080", }, { URL: "http://10.21.0.1:8080", }, }, }, }, "testing-service2-8082": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.10.0.2:8080", }, { URL: "http://10.21.0.2:8080", }, }, }, }, }, }, }, }, { desc: "Ingress with one service without endpoints subset", allowEmptyServices: true, expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-traefik-tchouk-bar": { Rule: "Host(`traefik.tchouk`) && PathPrefix(`/bar`)", Service: "testing-service1-80", }, }, Services: map[string]*dynamic.Service{ "testing-service1-80": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, }, }, }, { desc: "Ingress with backend resource", allowEmptyServices: true, expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{}, Services: map[string]*dynamic.Service{}, }, }, }, { desc: "Ingress without backend", allowEmptyServices: true, expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{}, Services: map[string]*dynamic.Service{}, }, }, }, { desc: "Ingress with one service without endpoint", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{}, Services: map[string]*dynamic.Service{}, }, }, }, { desc: "Single Service Ingress (without any rules)", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "default-router": { Rule: "PathPrefix(`/`)", RuleSyntax: "default", Service: "default-backend", Priority: math.MinInt32, }, }, Services: map[string]*dynamic.Service{ "default-backend": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:8080", }, { URL: "http://10.21.0.1:8080", }, }, }, }, }, }, }, }, { desc: "Ingress with port value in backend and no pod replica", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-traefik-tchouk-bar": { Rule: "Host(`traefik.tchouk`) && PathPrefix(`/bar`)", Service: "testing-service1-80", }, }, Services: map[string]*dynamic.Service{ "testing-service1-80": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:8089", }, { URL: "http://10.21.0.1:8089", }, }, }, }, }, }, }, }, { desc: "Ingress with port name in backend and no pod replica", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-traefik-tchouk-bar": { Rule: "Host(`traefik.tchouk`) && PathPrefix(`/bar`)", Service: "testing-service1-tchouk", }, }, Services: map[string]*dynamic.Service{ "testing-service1-tchouk": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:8089", }, { URL: "http://10.21.0.1:8089", }, }, }, }, }, }, }, }, { desc: "Ingress with port name in backend and 2 pod replica", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-traefik-tchouk-bar": { Rule: "Host(`traefik.tchouk`) && PathPrefix(`/bar`)", Service: "testing-service1-tchouk", }, }, Services: map[string]*dynamic.Service{ "testing-service1-tchouk": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:8089", }, { URL: "http://10.10.0.2:8089", }, }, }, }, }, }, }, }, { desc: "Ingress with two paths using same service and different port name", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-traefik-tchouk-bar": { Rule: "Host(`traefik.tchouk`) && PathPrefix(`/bar`)", Service: "testing-service1-tchouk", }, "testing-traefik-tchouk-foo": { Rule: "Host(`traefik.tchouk`) && PathPrefix(`/foo`)", Service: "testing-service1-carotte", }, }, Services: map[string]*dynamic.Service{ "testing-service1-tchouk": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:8089", }, { URL: "http://10.10.0.2:8089", }, }, }, }, "testing-service1-carotte": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:8090", }, { URL: "http://10.10.0.2:8090", }, }, }, }, }, }, }, }, { desc: "Ingress with a named port matching subset of service pods", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-traefik-tchouk-bar": { Rule: "Host(`traefik.tchouk`) && PathPrefix(`/bar`)", Service: "testing-service1-tchouk", }, }, Services: map[string]*dynamic.Service{ "testing-service1-tchouk": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:8089", }, { URL: "http://10.10.0.2:8089", }, }, }, }, }, }, }, }, { desc: "2 ingresses in different namespace with same service name", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-traefik-tchouk-bar": { Rule: "Host(`traefik.tchouk`) && PathPrefix(`/bar`)", Service: "testing-service1-tchouk", }, "toto-toto-traefik-tchouk-bar": { Rule: "Host(`toto.traefik.tchouk`) && PathPrefix(`/bar`)", Service: "toto-service1-tchouk", }, }, Services: map[string]*dynamic.Service{ "testing-service1-tchouk": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:8089", }, { URL: "http://10.10.0.2:8089", }, }, }, }, "toto-service1-tchouk": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.11.0.1:8089", }, { URL: "http://10.11.0.2:8089", }, }, }, }, }, }, }, }, { desc: "Ingress with unknown service port name", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{}, Services: map[string]*dynamic.Service{}, }, }, }, { desc: "Ingress with unknown service port", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{}, Services: map[string]*dynamic.Service{}, }, }, }, { desc: "Ingress with port invalid for one service", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-traefik-port-port": { Rule: "Host(`traefik.port`) && PathPrefix(`/port`)", Service: "testing-service1-8080", }, }, Services: map[string]*dynamic.Service{ "testing-service1-8080": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.0.0.1:8080", }, }, }, }, }, }, }, }, { desc: "TLS support", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-example-com": { Rule: "Host(`example.com`)", Service: "testing-example-com-80", TLS: &dynamic.RouterTLSConfig{}, }, }, Services: map[string]*dynamic.Service{ "testing-example-com-80": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.11.0.1:80", }, }, }, }, }, }, TLS: &dynamic.TLSConfiguration{ Certificates: []*tls.CertAndStores{ { Certificate: tls.Certificate{ CertFile: types.FileOrContent("-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----"), KeyFile: types.FileOrContent("-----BEGIN PRIVATE KEY-----\n-----END PRIVATE KEY-----"), }, }, }, }, }, }, { desc: "Ingress with a basic rule on one path with https (port == 443)", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-bar": { Rule: "PathPrefix(`/bar`)", Service: "testing-service1-443", }, }, Services: map[string]*dynamic.Service{ "testing-service1-443": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "https://10.10.0.1:8443", }, { URL: "https://10.21.0.1:8443", }, }, }, }, }, }, }, }, { desc: "Ingress with a basic rule on one path with https (portname == https)", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-bar": { Rule: "PathPrefix(`/bar`)", Service: "testing-service1-8443", }, }, Services: map[string]*dynamic.Service{ "testing-service1-8443": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "https://10.10.0.1:8443", }, { URL: "https://10.21.0.1:8443", }, }, }, }, }, }, }, }, { desc: "Ingress with a basic rule on one path with https (portname starts with https)", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-bar": { Rule: "PathPrefix(`/bar`)", Service: "testing-service1-8443", }, }, Services: map[string]*dynamic.Service{ "testing-service1-8443": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "https://10.10.0.1:8443", }, { URL: "https://10.21.0.1:8443", }, }, }, }, }, }, }, }, { desc: "Double Single Service Ingress", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "default-router": { Rule: "PathPrefix(`/`)", RuleSyntax: "default", Service: "default-backend", Priority: math.MinInt32, }, }, Services: map[string]*dynamic.Service{ "default-backend": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.30.0.1:8080", }, { URL: "http://10.41.0.1:8080", }, }, }, }, }, }, }, }, { desc: "Ingress with default traefik ingressClass", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{ "testing-bar": { Rule: "PathPrefix(`/bar`)", Service: "testing-service1-80", }, }, Services: map[string]*dynamic.Service{ "testing-service1-80": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, PassHostHeader: pointer(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:8080", }, }, }, }, }, }, }, }, { desc: "Ingress without provider traefik ingressClass and unknown annotation", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{}, Services: map[string]*dynamic.Service{}, }, }, }, { desc: "Ingress with non matching provider traefik ingressClass and annotation", ingressClass: "tchouk", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{}, Routers: map[string]*dynamic.Router{}, Services: map[string]*dynamic.Service{}, }, }, }, { desc: "Ingress with ingressClass without annotation", ingressClass: "tchouk", expected: &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Middlewares: map[string]*dynamic.Middleware{},
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/ingress/kubernetes.go
pkg/provider/kubernetes/ingress/kubernetes.go
package ingress import ( "context" "crypto/sha256" "errors" "fmt" "math" "net" "os" "regexp" "slices" "sort" "strconv" "strings" "time" "github.com/cenkalti/backoff/v4" "github.com/mitchellh/hashstructure" "github.com/rs/zerolog/log" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/job" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/provider" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/k8s" "github.com/traefik/traefik/v3/pkg/safe" "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" corev1 "k8s.io/api/core/v1" netv1 "k8s.io/api/networking/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/utils/ptr" ) const ( annotationKubernetesIngressClass = "kubernetes.io/ingress.class" traefikDefaultIngressClass = "traefik" traefikDefaultIngressClassController = "traefik.io/ingress-controller" defaultPathMatcher = "PathPrefix" ) // Provider holds configurations of the provider. type Provider struct { Endpoint string `description:"Kubernetes server endpoint (required for external cluster client)." json:"endpoint,omitempty" toml:"endpoint,omitempty" yaml:"endpoint,omitempty"` Token types.FileOrContent `description:"Kubernetes bearer token (not needed for in-cluster client). It accepts either a token value or a file path to the token." json:"token,omitempty" toml:"token,omitempty" yaml:"token,omitempty" loggable:"false"` CertAuthFilePath string `description:"Kubernetes certificate authority file path (not needed for in-cluster client)." json:"certAuthFilePath,omitempty" toml:"certAuthFilePath,omitempty" yaml:"certAuthFilePath,omitempty"` Namespaces []string `description:"Kubernetes namespaces." json:"namespaces,omitempty" toml:"namespaces,omitempty" yaml:"namespaces,omitempty" export:"true"` LabelSelector string `description:"Kubernetes Ingress label selector to use." json:"labelSelector,omitempty" toml:"labelSelector,omitempty" yaml:"labelSelector,omitempty" export:"true"` IngressClass string `description:"Value of kubernetes.io/ingress.class annotation or IngressClass name to watch for." json:"ingressClass,omitempty" toml:"ingressClass,omitempty" yaml:"ingressClass,omitempty" export:"true"` IngressEndpoint *EndpointIngress `description:"Kubernetes Ingress Endpoint." json:"ingressEndpoint,omitempty" toml:"ingressEndpoint,omitempty" yaml:"ingressEndpoint,omitempty" export:"true"` ThrottleDuration ptypes.Duration `description:"Ingress refresh throttle duration" json:"throttleDuration,omitempty" toml:"throttleDuration,omitempty" yaml:"throttleDuration,omitempty" export:"true"` AllowEmptyServices bool `description:"Allow creation of services without endpoints." json:"allowEmptyServices,omitempty" toml:"allowEmptyServices,omitempty" yaml:"allowEmptyServices,omitempty" export:"true"` AllowExternalNameServices bool `description:"Allow ExternalName services." json:"allowExternalNameServices,omitempty" toml:"allowExternalNameServices,omitempty" yaml:"allowExternalNameServices,omitempty" export:"true"` // Deprecated: please use DisableClusterScopeResources. DisableIngressClassLookup bool `description:"Disables the lookup of IngressClasses (Deprecated, please use DisableClusterScopeResources)." json:"disableIngressClassLookup,omitempty" toml:"disableIngressClassLookup,omitempty" yaml:"disableIngressClassLookup,omitempty" export:"true"` DisableClusterScopeResources bool `description:"Disables the lookup of cluster scope resources (incompatible with IngressClasses and NodePortLB enabled services)." json:"disableClusterScopeResources,omitempty" toml:"disableClusterScopeResources,omitempty" yaml:"disableClusterScopeResources,omitempty" export:"true"` NativeLBByDefault bool `description:"Defines whether to use Native Kubernetes load-balancing mode by default." json:"nativeLBByDefault,omitempty" toml:"nativeLBByDefault,omitempty" yaml:"nativeLBByDefault,omitempty" export:"true"` StrictPrefixMatching bool `description:"Make prefix matching strictly comply with the Kubernetes Ingress specification (path-element-wise matching instead of character-by-character string matching)." json:"strictPrefixMatching,omitempty" toml:"strictPrefixMatching,omitempty" yaml:"strictPrefixMatching,omitempty" export:"true"` // The default rule syntax is initialized with the configuration defined by the user with the core.DefaultRuleSyntax option. DefaultRuleSyntax string `json:"-" toml:"-" yaml:"-" label:"-" file:"-"` lastConfiguration safe.Safe routerTransform k8s.RouterTransform } func (p *Provider) SetRouterTransform(routerTransform k8s.RouterTransform) { p.routerTransform = routerTransform } func (p *Provider) applyRouterTransform(ctx context.Context, rt *dynamic.Router, ingress *netv1.Ingress) { if p.routerTransform == nil { return } err := p.routerTransform.Apply(ctx, rt, ingress) if err != nil { log.Ctx(ctx).Error().Err(err).Msg("Apply router transform") } } // EndpointIngress holds the endpoint information for the Kubernetes provider. type EndpointIngress struct { IP string `description:"IP used for Kubernetes Ingress endpoints." json:"ip,omitempty" toml:"ip,omitempty" yaml:"ip,omitempty"` Hostname string `description:"Hostname used for Kubernetes Ingress endpoints." json:"hostname,omitempty" toml:"hostname,omitempty" yaml:"hostname,omitempty"` PublishedService string `description:"Published Kubernetes Service to copy status from." json:"publishedService,omitempty" toml:"publishedService,omitempty" yaml:"publishedService,omitempty"` } func (p *Provider) newK8sClient(ctx context.Context) (*clientWrapper, error) { _, err := labels.Parse(p.LabelSelector) if err != nil { return nil, fmt.Errorf("invalid ingress label selector: %q", p.LabelSelector) } logger := log.Ctx(ctx) logger.Info().Msgf("ingress label selector is: %q", p.LabelSelector) withEndpoint := "" if p.Endpoint != "" { withEndpoint = fmt.Sprintf(" with endpoint %v", p.Endpoint) } var cl *clientWrapper switch { case os.Getenv("KUBERNETES_SERVICE_HOST") != "" && os.Getenv("KUBERNETES_SERVICE_PORT") != "": logger.Info().Msgf("Creating in-cluster Provider client%s", withEndpoint) cl, err = newInClusterClient(p.Endpoint) case os.Getenv("KUBECONFIG") != "": logger.Info().Msgf("Creating cluster-external Provider client from KUBECONFIG %s", os.Getenv("KUBECONFIG")) cl, err = newExternalClusterClientFromFile(os.Getenv("KUBECONFIG")) default: logger.Info().Msgf("Creating cluster-external Provider client%s", withEndpoint) cl, err = newExternalClusterClient(p.Endpoint, p.CertAuthFilePath, p.Token) } if err != nil { return nil, err } cl.ingressLabelSelector = p.LabelSelector cl.disableIngressClassInformer = p.DisableIngressClassLookup || p.DisableClusterScopeResources cl.disableClusterScopeInformer = p.DisableClusterScopeResources return cl, nil } // Init the provider. func (p *Provider) Init() error { return nil } // Provide allows the k8s provider to provide configurations to traefik // using the given configuration channel. func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error { logger := log.With().Str(logs.ProviderName, "kubernetes").Logger() ctxLog := logger.WithContext(context.Background()) k8sClient, err := p.newK8sClient(ctxLog) if err != nil { return err } if p.AllowExternalNameServices { logger.Info().Msg("ExternalName service loading is enabled, please ensure that this is expected (see AllowExternalNameServices option)") } pool.GoCtx(func(ctxPool context.Context) { operation := func() error { eventsChan, err := k8sClient.WatchAll(p.Namespaces, ctxPool.Done()) if err != nil { logger.Error().Err(err).Msg("Error watching kubernetes events") timer := time.NewTimer(1 * time.Second) select { case <-timer.C: return err case <-ctxPool.Done(): return nil } } throttleDuration := time.Duration(p.ThrottleDuration) throttledChan := throttleEvents(ctxLog, throttleDuration, pool, eventsChan) if throttledChan != nil { eventsChan = throttledChan } for { select { case <-ctxPool.Done(): return nil case event := <-eventsChan: // Note that event is the *first* event that came in during this // throttling interval -- if we're hitting our throttle, we may have // dropped events. This is fine, because we don't treat different // event types differently. But if we do in the future, we'll need to // track more information about the dropped events. conf := p.loadConfigurationFromIngresses(ctxLog, k8sClient) confHash, err := hashstructure.Hash(conf, nil) switch { case err != nil: logger.Error().Msg("Unable to hash the configuration") case p.lastConfiguration.Get() == confHash: logger.Debug().Msgf("Skipping Kubernetes event kind %T", event) default: p.lastConfiguration.Set(confHash) configurationChan <- dynamic.Message{ ProviderName: "kubernetes", Configuration: conf, } } // If we're throttling, we sleep here for the throttle duration to // enforce that we don't refresh faster than our throttle. time.Sleep // returns immediately if p.ThrottleDuration is 0 (no throttle). time.Sleep(throttleDuration) } } } notify := func(err error, time time.Duration) { logger.Error().Err(err).Msgf("Provider error, retrying in %s", time) } err := backoff.RetryNotify(safe.OperationWithRecover(operation), backoff.WithContext(job.NewBackOff(backoff.NewExponentialBackOff()), ctxPool), notify) if err != nil { logger.Error().Err(err).Msg("Cannot retrieve data") } }) return nil } func (p *Provider) loadConfigurationFromIngresses(ctx context.Context, client Client) *dynamic.Configuration { conf := &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, }, } var ingressClasses []*netv1.IngressClass if !p.DisableIngressClassLookup && !p.DisableClusterScopeResources { ics, err := client.GetIngressClasses() if err != nil { log.Ctx(ctx).Warn().Err(err).Msg("Failed to list ingress classes") } if p.IngressClass != "" { ingressClasses = filterIngressClassByName(p.IngressClass, ics) } else { ingressClasses = ics } } ingresses := client.GetIngresses() certConfigs := make(map[string]*tls.CertAndStores) for _, ingress := range ingresses { logger := log.Ctx(ctx).With().Str("ingress", ingress.Name).Str("namespace", ingress.Namespace).Logger() ctxIngress := logger.WithContext(ctx) if !p.shouldProcessIngress(ingress, ingressClasses) { continue } if err := p.updateIngressStatus(ingress, client); err != nil { logger.Error().Err(err).Msg("Error while updating ingress status") } rtConfig, err := parseRouterConfig(ingress.Annotations) if err != nil { logger.Error().Err(err).Msg("Failed to parse annotations") continue } err = getCertificates(ctxIngress, ingress, client, certConfigs) if err != nil { logger.Error().Err(err).Msg("Error configuring TLS") } if len(ingress.Spec.Rules) == 0 && ingress.Spec.DefaultBackend != nil { if _, ok := conf.HTTP.Services["default-backend"]; ok { logger.Error().Msg("The default backend already exists.") continue } service, err := p.loadService(client, ingress.Namespace, *ingress.Spec.DefaultBackend) if err != nil { logger.Error(). Str("serviceName", ingress.Spec.DefaultBackend.Service.Name). Str("servicePort", ingress.Spec.DefaultBackend.Service.Port.String()). Err(err). Msg("Cannot create service") continue } if len(service.LoadBalancer.Servers) == 0 && !p.AllowEmptyServices { logger.Error(). Str("serviceName", ingress.Spec.DefaultBackend.Service.Name). Str("servicePort", ingress.Spec.DefaultBackend.Service.Port.String()). Msg("Skipping service: no endpoints found") continue } rt := &dynamic.Router{ Rule: "PathPrefix(`/`)", // "default" stands for the default rule syntax in Traefik v3, i.e. the v3 syntax. RuleSyntax: "default", Priority: math.MinInt32, Service: "default-backend", } if rtConfig != nil && rtConfig.Router != nil { rt.EntryPoints = rtConfig.Router.EntryPoints rt.Middlewares = rtConfig.Router.Middlewares rt.TLS = rtConfig.Router.TLS rt.Observability = rtConfig.Router.Observability } p.applyRouterTransform(ctxIngress, rt, ingress) conf.HTTP.Routers["default-router"] = rt conf.HTTP.Services["default-backend"] = service } routers := map[string][]*dynamic.Router{} for _, rule := range ingress.Spec.Rules { if rule.HTTP == nil { continue } for _, pa := range rule.HTTP.Paths { if pa.Backend.Resource != nil { // https://kubernetes.io/docs/concepts/services-networking/ingress/#resource-backend logger.Error().Msg("Resource backends are not supported") continue } if pa.Backend.Service == nil { logger.Error().Msg("Missing service definition") continue } service, err := p.loadService(client, ingress.Namespace, pa.Backend) if err != nil { logger.Error(). Str("serviceName", pa.Backend.Service.Name). Str("servicePort", pa.Backend.Service.Port.String()). Err(err). Msg("Cannot create service") continue } if len(service.LoadBalancer.Servers) == 0 && !p.AllowEmptyServices { logger.Error(). Str("serviceName", pa.Backend.Service.Name). Str("servicePort", pa.Backend.Service.Port.String()). Msg("Skipping service: no endpoints found") continue } portString := pa.Backend.Service.Port.Name if len(pa.Backend.Service.Port.Name) == 0 { portString = strconv.Itoa(int(pa.Backend.Service.Port.Number)) } serviceName := provider.Normalize(ingress.Namespace + "-" + pa.Backend.Service.Name + "-" + portString) conf.HTTP.Services[serviceName] = service rt := p.loadRouter(rule, pa, rtConfig, serviceName) p.applyRouterTransform(ctxIngress, rt, ingress) routerKey := strings.TrimPrefix(provider.Normalize(ingress.Namespace+"-"+ingress.Name+"-"+rule.Host+pa.Path), "-") routers[routerKey] = append(routers[routerKey], rt) } } for routerKey, conflictingRouters := range routers { if len(conflictingRouters) == 1 { conf.HTTP.Routers[routerKey] = conflictingRouters[0] continue } logger.Debug().Msgf("Multiple routers are defined with the same key %q, generating hashes to avoid conflicts", routerKey) for _, router := range conflictingRouters { key, err := makeRouterKeyWithHash(routerKey, router.Rule) if err != nil { logger.Error().Err(err).Send() continue } conf.HTTP.Routers[key] = router } } } certs := getTLSConfig(certConfigs) if len(certs) > 0 { conf.TLS = &dynamic.TLSConfiguration{ Certificates: certs, } } return conf } func (p *Provider) updateIngressStatus(ing *netv1.Ingress, k8sClient Client) error { // Only process if an EndpointIngress has been configured. if p.IngressEndpoint == nil { return nil } if len(p.IngressEndpoint.PublishedService) == 0 { if len(p.IngressEndpoint.IP) == 0 && len(p.IngressEndpoint.Hostname) == 0 { return errors.New("publishedService or ip or hostname must be defined") } return k8sClient.UpdateIngressStatus(ing, []netv1.IngressLoadBalancerIngress{{IP: p.IngressEndpoint.IP, Hostname: p.IngressEndpoint.Hostname}}) } serviceInfo := strings.Split(p.IngressEndpoint.PublishedService, "/") if len(serviceInfo) != 2 { return fmt.Errorf("invalid publishedService format (expected 'namespace/service' format): %s", p.IngressEndpoint.PublishedService) } serviceNamespace, serviceName := serviceInfo[0], serviceInfo[1] service, exists, err := k8sClient.GetService(serviceNamespace, serviceName) if err != nil { return fmt.Errorf("cannot get service %s, received error: %w", p.IngressEndpoint.PublishedService, err) } if !exists { return fmt.Errorf("missing service: %s", p.IngressEndpoint.PublishedService) } var ingressStatus []netv1.IngressLoadBalancerIngress switch service.Spec.Type { case corev1.ServiceTypeLoadBalancer: if service.Status.LoadBalancer.Ingress == nil { // service exists, but has no Load Balancer status log.Debug().Msgf("Skipping updating Ingress %s/%s due to service %s having no status set", ing.Namespace, ing.Name, p.IngressEndpoint.PublishedService) return nil } ingressStatus, err = convertSlice[netv1.IngressLoadBalancerIngress](service.Status.LoadBalancer.Ingress) if err != nil { return fmt.Errorf("converting ingress loadbalancer status: %w", err) } case corev1.ServiceTypeClusterIP: var ports []netv1.IngressPortStatus for _, port := range service.Spec.Ports { ports = append(ports, netv1.IngressPortStatus{ Port: port.Port, Protocol: port.Protocol, }) } for _, ip := range service.Spec.ExternalIPs { ingressStatus = append(ingressStatus, netv1.IngressLoadBalancerIngress{ IP: ip, Ports: ports, }) } case corev1.ServiceTypeNodePort: if p.DisableClusterScopeResources { return errors.New("node port service type is not supported when cluster scope resources lookup is disabled") } nodes, _, err := k8sClient.GetNodes() if err != nil { return fmt.Errorf("getting nodes: %w", err) } var ports []netv1.IngressPortStatus for _, port := range service.Spec.Ports { ports = append(ports, netv1.IngressPortStatus{ Port: port.NodePort, Protocol: port.Protocol, }) } for _, node := range nodes { for _, address := range node.Status.Addresses { if address.Type == corev1.NodeExternalIP { ingressStatus = append(ingressStatus, netv1.IngressLoadBalancerIngress{ IP: address.Address, Ports: ports, }) } } } case corev1.ServiceTypeExternalName: ingressStatus = []netv1.IngressLoadBalancerIngress{{ Hostname: service.Spec.ExternalName, }} default: return fmt.Errorf("unsupported service type: %s", service.Spec.Type) } return k8sClient.UpdateIngressStatus(ing, ingressStatus) } func (p *Provider) shouldProcessIngress(ingress *netv1.Ingress, ingressClasses []*netv1.IngressClass) bool { // configuration through the new kubernetes ingressClass if ingress.Spec.IngressClassName != nil { return slices.ContainsFunc(ingressClasses, func(ic *netv1.IngressClass) bool { return *ingress.Spec.IngressClassName == ic.ObjectMeta.Name }) } return p.IngressClass == ingress.Annotations[annotationKubernetesIngressClass] || len(p.IngressClass) == 0 && ingress.Annotations[annotationKubernetesIngressClass] == traefikDefaultIngressClass } func (p *Provider) loadService(client Client, namespace string, backend netv1.IngressBackend) (*dynamic.Service, error) { service, exists, err := client.GetService(namespace, backend.Service.Name) if err != nil { return nil, err } if !exists { return nil, errors.New("service not found") } if !p.AllowExternalNameServices && service.Spec.Type == corev1.ServiceTypeExternalName { return nil, fmt.Errorf("externalName services not allowed: %s/%s", namespace, backend.Service.Name) } var portName string var portSpec corev1.ServicePort var match bool for _, p := range service.Spec.Ports { if backend.Service.Port.Number == p.Port || (backend.Service.Port.Name == p.Name && len(p.Name) > 0) { portName = p.Name portSpec = p match = true break } } if !match { return nil, errors.New("service port not found") } lb := &dynamic.ServersLoadBalancer{} lb.SetDefaults() svc := &dynamic.Service{LoadBalancer: lb} svcConfig, err := parseServiceConfig(service.Annotations) if err != nil { return nil, err } nativeLB := p.NativeLBByDefault if svcConfig != nil && svcConfig.Service != nil { svc.LoadBalancer.Sticky = svcConfig.Service.Sticky if svcConfig.Service.PassHostHeader != nil { svc.LoadBalancer.PassHostHeader = svcConfig.Service.PassHostHeader } if svcConfig.Service.ServersTransport != "" { svc.LoadBalancer.ServersTransport = svcConfig.Service.ServersTransport } if svcConfig.Service.NativeLB != nil { nativeLB = *svcConfig.Service.NativeLB } if svcConfig.Service.NodePortLB && service.Spec.Type == corev1.ServiceTypeNodePort { if p.DisableClusterScopeResources { return nil, errors.New("nodes lookup is disabled") } nodes, nodesExists, nodesErr := client.GetNodes() if nodesErr != nil { return nil, nodesErr } if !nodesExists || len(nodes) == 0 { return nil, fmt.Errorf("nodes not found in namespace %s", namespace) } protocol := getProtocol(portSpec, portSpec.Name, svcConfig) var servers []dynamic.Server for _, node := range nodes { for _, addr := range node.Status.Addresses { if addr.Type == corev1.NodeInternalIP { hostPort := net.JoinHostPort(addr.Address, strconv.Itoa(int(portSpec.NodePort))) servers = append(servers, dynamic.Server{ URL: fmt.Sprintf("%s://%s", protocol, hostPort), }) } } } if len(servers) == 0 { return nil, fmt.Errorf("no servers were generated for service %s in namespace", backend.Service.Name) } svc.LoadBalancer.Servers = servers return svc, nil } } if service.Spec.Type == corev1.ServiceTypeExternalName { protocol := getProtocol(portSpec, portSpec.Name, svcConfig) hostPort := net.JoinHostPort(service.Spec.ExternalName, strconv.Itoa(int(portSpec.Port))) svc.LoadBalancer.Servers = []dynamic.Server{ {URL: fmt.Sprintf("%s://%s", protocol, hostPort)}, } return svc, nil } if nativeLB { address, err := getNativeServiceAddress(*service, portSpec) if err != nil { return nil, fmt.Errorf("getting native Kubernetes Service address: %w", err) } protocol := getProtocol(portSpec, portSpec.Name, svcConfig) svc.LoadBalancer.Servers = []dynamic.Server{ {URL: fmt.Sprintf("%s://%s", protocol, address)}, } return svc, nil } endpointSlices, err := client.GetEndpointSlicesForService(namespace, backend.Service.Name) if err != nil { return nil, fmt.Errorf("getting endpointslices: %w", err) } addresses := map[string]struct{}{} for _, endpointSlice := range endpointSlices { var port int32 for _, p := range endpointSlice.Ports { if portName == *p.Name { port = *p.Port break } } if port == 0 { continue } protocol := getProtocol(portSpec, portName, svcConfig) for _, endpoint := range endpointSlice.Endpoints { if !k8s.EndpointServing(endpoint) { continue } for _, address := range endpoint.Addresses { if _, ok := addresses[address]; ok { continue } addresses[address] = struct{}{} svc.LoadBalancer.Servers = append(svc.LoadBalancer.Servers, dynamic.Server{ URL: fmt.Sprintf("%s://%s", protocol, net.JoinHostPort(address, strconv.Itoa(int(port)))), Fenced: ptr.Deref(endpoint.Conditions.Terminating, false) && ptr.Deref(endpoint.Conditions.Serving, false), }) } } } return svc, nil } func (p *Provider) loadRouter(rule netv1.IngressRule, pa netv1.HTTPIngressPath, rtConfig *RouterConfig, serviceName string) *dynamic.Router { rt := &dynamic.Router{ Service: serviceName, } if rtConfig != nil && rtConfig.Router != nil { rt.RuleSyntax = rtConfig.Router.RuleSyntax rt.Priority = rtConfig.Router.Priority rt.EntryPoints = rtConfig.Router.EntryPoints rt.Middlewares = rtConfig.Router.Middlewares rt.TLS = rtConfig.Router.TLS rt.Observability = rtConfig.Router.Observability } var rules []string if len(rule.Host) > 0 { if rt.RuleSyntax == "v2" || (rt.RuleSyntax == "" && p.DefaultRuleSyntax == "v2") { rules = append(rules, buildHostRuleV2(rule.Host)) } else { rules = append(rules, buildHostRule(rule.Host)) } } if len(pa.Path) > 0 { matcher := defaultPathMatcher if pa.PathType == nil || *pa.PathType == "" || *pa.PathType == netv1.PathTypeImplementationSpecific { if rtConfig != nil && rtConfig.Router != nil && rtConfig.Router.PathMatcher != "" { matcher = rtConfig.Router.PathMatcher } } else if *pa.PathType == netv1.PathTypeExact { matcher = "Path" } rules = append(rules, buildRule(p.StrictPrefixMatching, matcher, pa.Path)) } rt.Rule = strings.Join(rules, " && ") return rt } func buildHostRuleV2(host string) string { if strings.HasPrefix(host, "*.") { host = strings.Replace(host, "*.", "{subdomain:[a-zA-Z0-9-]+}.", 1) return fmt.Sprintf("HostRegexp(`%s`)", host) } return fmt.Sprintf("Host(`%s`)", host) } func buildHostRule(host string) string { if strings.HasPrefix(host, "*.") { host = strings.Replace(regexp.QuoteMeta(host), `\*\.`, `[a-zA-Z0-9-]+\.`, 1) return fmt.Sprintf("HostRegexp(`^%s$`)", host) } return fmt.Sprintf("Host(`%s`)", host) } func getCertificates(ctx context.Context, ingress *netv1.Ingress, k8sClient Client, tlsConfigs map[string]*tls.CertAndStores) error { for _, t := range ingress.Spec.TLS { if t.SecretName == "" { log.Ctx(ctx).Debug().Msg("Skipping TLS sub-section: No secret name provided") continue } configKey := ingress.Namespace + "-" + t.SecretName if _, tlsExists := tlsConfigs[configKey]; !tlsExists { secret, exists, err := k8sClient.GetSecret(ingress.Namespace, t.SecretName) if err != nil { return fmt.Errorf("failed to fetch secret %s/%s: %w", ingress.Namespace, t.SecretName, err) } if !exists { return fmt.Errorf("secret %s/%s does not exist", ingress.Namespace, t.SecretName) } cert, key, err := getCertificateBlocks(secret, ingress.Namespace, t.SecretName) if err != nil { return err } tlsConfigs[configKey] = &tls.CertAndStores{ Certificate: tls.Certificate{ CertFile: types.FileOrContent(cert), KeyFile: types.FileOrContent(key), }, } } } return nil } func getCertificateBlocks(secret *corev1.Secret, namespace, secretName string) (string, string, error) { var missingEntries []string tlsCrtData, tlsCrtExists := secret.Data["tls.crt"] if !tlsCrtExists { missingEntries = append(missingEntries, "tls.crt") } tlsKeyData, tlsKeyExists := secret.Data["tls.key"] if !tlsKeyExists { missingEntries = append(missingEntries, "tls.key") } if len(missingEntries) > 0 { return "", "", fmt.Errorf("secret %s/%s is missing the following TLS data entries: %s", namespace, secretName, strings.Join(missingEntries, ", ")) } cert := string(tlsCrtData) if cert == "" { missingEntries = append(missingEntries, "tls.crt") } key := string(tlsKeyData) if key == "" { missingEntries = append(missingEntries, "tls.key") } if len(missingEntries) > 0 { return "", "", fmt.Errorf("secret %s/%s contains the following empty TLS data entries: %s", namespace, secretName, strings.Join(missingEntries, ", ")) } return cert, key, nil } func getTLSConfig(tlsConfigs map[string]*tls.CertAndStores) []*tls.CertAndStores { var secretNames []string for secretName := range tlsConfigs { secretNames = append(secretNames, secretName) } sort.Strings(secretNames) var configs []*tls.CertAndStores for _, secretName := range secretNames { configs = append(configs, tlsConfigs[secretName]) } return configs } func getNativeServiceAddress(service corev1.Service, svcPort corev1.ServicePort) (string, error) { if service.Spec.ClusterIP == "None" { return "", fmt.Errorf("no clusterIP on headless service: %s/%s", service.Namespace, service.Name) } if service.Spec.ClusterIP == "" { return "", fmt.Errorf("no clusterIP found for service: %s/%s", service.Namespace, service.Name) } return net.JoinHostPort(service.Spec.ClusterIP, strconv.Itoa(int(svcPort.Port))), nil } func getProtocol(portSpec corev1.ServicePort, portName string, svcConfig *ServiceConfig) string { if svcConfig != nil && svcConfig.Service != nil && svcConfig.Service.ServersScheme != "" { return svcConfig.Service.ServersScheme } protocol := "http" if portSpec.Port == 443 || strings.HasPrefix(portName, "https") { protocol = "https" } return protocol } func makeRouterKeyWithHash(key, rule string) (string, error) { h := sha256.New() if _, err := h.Write([]byte(rule)); err != nil { return "", err } dupKey := fmt.Sprintf("%s-%.10x", key, h.Sum(nil)) return dupKey, nil } func buildRule(strictPrefixMatching bool, matcher string, path string) string { // When enabled, strictPrefixMatching ensures that prefix matching follows // the Kubernetes Ingress spec (path-element-wise instead of character-wise). if strictPrefixMatching && matcher == "PathPrefix" { // According to // https://kubernetes.io/docs/concepts/services-networking/ingress/#examples, // "/v12" should not match "/v1". // // Traefik's default PathPrefix matcher performs a character-wise prefix match, // unlike Kubernetes which matches path elements. To mimic Kubernetes behavior, // we will use Path and PathPrefix to replicate element-wise behavior. // // "PathPrefix" in Kubernetes Gateway API is semantically equivalent to the "Prefix" path type in the // Kubernetes Ingress API. return buildStrictPrefixMatchingRule(path) } return fmt.Sprintf("%s(`%s`)", matcher, path) } // buildStrictPrefixMatchingRule is a helper function to build a path prefix rule that matches path prefix split by `/`. // For example, the paths `/abc`, `/abc/`, and `/abc/def` would all match the prefix `/abc`, // but the path `/abcd` would not. See TestStrictPrefixMatchingRule() for more examples. // // "PathPrefix" in Kubernetes Gateway API is semantically equivalent to the "Prefix" path type in the // Kubernetes Ingress API. func buildStrictPrefixMatchingRule(path string) string { if path == "/" { return "PathPrefix(`/`)" } path = strings.TrimSuffix(path, "/") return fmt.Sprintf("(Path(`%[1]s`) || PathPrefix(`%[1]s/`))", path) } func throttleEvents(ctx context.Context, throttleDuration time.Duration, pool *safe.Pool, eventsChan <-chan interface{}) chan interface{} { if throttleDuration == 0 { return nil } // Create a buffered channel to hold the pending event (if we're delaying processing the event due to throttling). eventsChanBuffered := make(chan interface{}, 1) // Run a goroutine that reads events from eventChan and does a // non-blocking write to pendingEvent. This guarantees that writing to // eventChan will never block, and that pendingEvent will have // something in it if there's been an event since we read from that channel. pool.GoCtx(func(ctxPool context.Context) { for { select { case <-ctxPool.Done(): return case nextEvent := <-eventsChan: select { case eventsChanBuffered <- nextEvent: default: // We already have an event in eventsChanBuffered, so we'll // do a refresh as soon as our throttle allows us to. It's fine // to drop the event and keep whatever's in the buffer -- we // don't do different things for different events. log.Ctx(ctx).Debug().Msgf("Dropping event kind %T due to throttling", nextEvent) } } } }) return eventsChanBuffered }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/ingress/annotations_test.go
pkg/provider/kubernetes/ingress/annotations_test.go
package ingress import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" otypes "github.com/traefik/traefik/v3/pkg/observability/types" "github.com/traefik/traefik/v3/pkg/types" ) func Test_parseRouterConfig(t *testing.T) { testCases := []struct { desc string annotations map[string]string expected *RouterConfig }{ { desc: "router annotations", annotations: map[string]string{ "ingress.kubernetes.io/foo": "bar", "traefik.ingress.kubernetes.io/foo": "bar", "traefik.ingress.kubernetes.io/router.pathmatcher": "foobar", "traefik.ingress.kubernetes.io/router.entrypoints": "foobar,foobar", "traefik.ingress.kubernetes.io/router.middlewares": "foobar,foobar", "traefik.ingress.kubernetes.io/router.priority": "42", "traefik.ingress.kubernetes.io/router.rulesyntax": "foobar", "traefik.ingress.kubernetes.io/router.tls": "true", "traefik.ingress.kubernetes.io/router.tls.certresolver": "foobar", "traefik.ingress.kubernetes.io/router.tls.domains.0.main": "foobar", "traefik.ingress.kubernetes.io/router.tls.domains.0.sans": "foobar,foobar", "traefik.ingress.kubernetes.io/router.tls.domains.1.main": "foobar", "traefik.ingress.kubernetes.io/router.tls.domains.1.sans": "foobar,foobar", "traefik.ingress.kubernetes.io/router.tls.options": "foobar", "traefik.ingress.kubernetes.io/router.observability.accessLogs": "true", "traefik.ingress.kubernetes.io/router.observability.metrics": "true", "traefik.ingress.kubernetes.io/router.observability.tracing": "true", }, expected: &RouterConfig{ Router: &RouterIng{ PathMatcher: "foobar", EntryPoints: []string{"foobar", "foobar"}, Middlewares: []string{"foobar", "foobar"}, Priority: 42, RuleSyntax: "foobar", TLS: &dynamic.RouterTLSConfig{ CertResolver: "foobar", Domains: []types.Domain{ { Main: "foobar", SANs: []string{"foobar", "foobar"}, }, { Main: "foobar", SANs: []string{"foobar", "foobar"}, }, }, Options: "foobar", }, Observability: &dynamic.RouterObservabilityConfig{ AccessLogs: pointer(true), Tracing: pointer(true), Metrics: pointer(true), TraceVerbosity: otypes.MinimalVerbosity, }, }, }, }, { desc: "simple TLS annotation", annotations: map[string]string{ "traefik.ingress.kubernetes.io/router.tls": "true", }, expected: &RouterConfig{ Router: &RouterIng{ PathMatcher: "PathPrefix", TLS: &dynamic.RouterTLSConfig{}, }, }, }, { desc: "empty map", annotations: nil, expected: nil, }, { desc: "nil map", annotations: nil, expected: nil, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() cfg, err := parseRouterConfig(test.annotations) require.NoError(t, err) assert.Equal(t, test.expected, cfg) }) } } func Test_parseServiceConfig(t *testing.T) { testCases := []struct { desc string annotations map[string]string expected *ServiceConfig }{ { desc: "service annotations", annotations: map[string]string{ "ingress.kubernetes.io/foo": "bar", "traefik.ingress.kubernetes.io/foo": "bar", "traefik.ingress.kubernetes.io/service.serversscheme": "protocol", "traefik.ingress.kubernetes.io/service.serverstransport": "foobar@file", "traefik.ingress.kubernetes.io/service.passhostheader": "true", "traefik.ingress.kubernetes.io/service.nativelb": "true", "traefik.ingress.kubernetes.io/service.sticky.cookie": "true", "traefik.ingress.kubernetes.io/service.sticky.cookie.httponly": "true", "traefik.ingress.kubernetes.io/service.sticky.cookie.name": "foobar", "traefik.ingress.kubernetes.io/service.sticky.cookie.secure": "true", "traefik.ingress.kubernetes.io/service.sticky.cookie.samesite": "none", "traefik.ingress.kubernetes.io/service.sticky.cookie.domain": "foo.com", "traefik.ingress.kubernetes.io/service.sticky.cookie.path": "foobar", }, expected: &ServiceConfig{ Service: &ServiceIng{ Sticky: &dynamic.Sticky{ Cookie: &dynamic.Cookie{ Name: "foobar", Secure: true, HTTPOnly: true, SameSite: "none", Domain: "foo.com", Path: pointer("foobar"), }, }, ServersScheme: "protocol", ServersTransport: "foobar@file", PassHostHeader: pointer(true), NativeLB: pointer(true), }, }, }, { desc: "simple sticky annotation", annotations: map[string]string{ "traefik.ingress.kubernetes.io/service.sticky.cookie": "true", }, expected: &ServiceConfig{ Service: &ServiceIng{ Sticky: &dynamic.Sticky{ Cookie: &dynamic.Cookie{ Path: pointer("/"), }, }, PassHostHeader: pointer(true), }, }, }, { desc: "empty map", annotations: map[string]string{}, expected: nil, }, { desc: "nil map", annotations: nil, expected: nil, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() cfg, err := parseServiceConfig(test.annotations) require.NoError(t, err) assert.Equal(t, test.expected, cfg) }) } } func Test_convertAnnotations(t *testing.T) { testCases := []struct { desc string annotations map[string]string expected map[string]string }{ { desc: "router annotations", annotations: map[string]string{ "ingress.kubernetes.io/foo": "bar", "traefik.ingress.kubernetes.io/foo": "bar", "traefik.ingress.kubernetes.io/router.pathmatcher": "foobar", "traefik.ingress.kubernetes.io/router.entrypoints": "foobar,foobar", "traefik.ingress.kubernetes.io/router.middlewares": "foobar,foobar", "traefik.ingress.kubernetes.io/router.priority": "42", "traefik.ingress.kubernetes.io/router.rulesyntax": "foobar", "traefik.ingress.kubernetes.io/router.tls": "true", "traefik.ingress.kubernetes.io/router.tls.certresolver": "foobar", "traefik.ingress.kubernetes.io/router.tls.domains.0.main": "foobar", "traefik.ingress.kubernetes.io/router.tls.domains.0.sans": "foobar,foobar", "traefik.ingress.kubernetes.io/router.tls.domains.1.main": "foobar", "traefik.ingress.kubernetes.io/router.tls.domains.1.sans": "foobar,foobar", "traefik.ingress.kubernetes.io/router.tls.options": "foobar", "traefik.ingress.kubernetes.io/router.observability.accessLogs": "true", "traefik.ingress.kubernetes.io/router.observability.metrics": "true", "traefik.ingress.kubernetes.io/router.observability.tracing": "true", }, expected: map[string]string{ "traefik.foo": "bar", "traefik.router.pathmatcher": "foobar", "traefik.router.entrypoints": "foobar,foobar", "traefik.router.middlewares": "foobar,foobar", "traefik.router.priority": "42", "traefik.router.rulesyntax": "foobar", "traefik.router.tls": "true", "traefik.router.tls.certresolver": "foobar", "traefik.router.tls.domains[0].main": "foobar", "traefik.router.tls.domains[0].sans": "foobar,foobar", "traefik.router.tls.domains[1].main": "foobar", "traefik.router.tls.domains[1].sans": "foobar,foobar", "traefik.router.tls.options": "foobar", "traefik.router.observability.accessLogs": "true", "traefik.router.observability.metrics": "true", "traefik.router.observability.tracing": "true", }, }, { desc: "service annotations", annotations: map[string]string{ "traefik.ingress.kubernetes.io/service.serversscheme": "protocol", "traefik.ingress.kubernetes.io/service.serverstransport": "foobar@file", "traefik.ingress.kubernetes.io/service.passhostheader": "true", "traefik.ingress.kubernetes.io/service.sticky.cookie": "true", "traefik.ingress.kubernetes.io/service.sticky.cookie.httponly": "true", "traefik.ingress.kubernetes.io/service.sticky.cookie.name": "foobar", "traefik.ingress.kubernetes.io/service.sticky.cookie.secure": "true", }, expected: map[string]string{ "traefik.service.passhostheader": "true", "traefik.service.serversscheme": "protocol", "traefik.service.serverstransport": "foobar@file", "traefik.service.sticky.cookie": "true", "traefik.service.sticky.cookie.httponly": "true", "traefik.service.sticky.cookie.name": "foobar", "traefik.service.sticky.cookie.secure": "true", }, }, { desc: "empty map", annotations: map[string]string{}, expected: nil, }, { desc: "nil map", annotations: nil, expected: nil, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() labels := convertAnnotations(test.annotations) assert.Equal(t, test.expected, labels) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/ingress/client_mock_test.go
pkg/provider/kubernetes/ingress/client_mock_test.go
package ingress import ( "fmt" "os" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/k8s" corev1 "k8s.io/api/core/v1" discoveryv1 "k8s.io/api/discovery/v1" netv1 "k8s.io/api/networking/v1" ) var _ Client = (*clientMock)(nil) type clientMock struct { ingresses []*netv1.Ingress services []*corev1.Service secrets []*corev1.Secret endpointSlices []*discoveryv1.EndpointSlice nodes []*corev1.Node ingressClasses []*netv1.IngressClass apiServiceError error apiSecretError error apiEndpointSlicesError error apiNodesError error apiIngressStatusError error watchChan chan interface{} } func newClientMock(path string) clientMock { c := clientMock{} yamlContent, err := os.ReadFile(path) if err != nil { panic(fmt.Errorf("unable to read file %q: %w", path, err)) } k8sObjects := k8s.MustParseYaml(yamlContent) for _, obj := range k8sObjects { switch o := obj.(type) { case *corev1.Service: c.services = append(c.services, o) case *corev1.Secret: c.secrets = append(c.secrets, o) case *discoveryv1.EndpointSlice: c.endpointSlices = append(c.endpointSlices, o) case *corev1.Node: c.nodes = append(c.nodes, o) case *netv1.Ingress: c.ingresses = append(c.ingresses, o) case *netv1.IngressClass: c.ingressClasses = append(c.ingressClasses, o) default: panic(fmt.Sprintf("Unknown runtime object %+v %T", o, o)) } } return c } func (c clientMock) GetIngresses() []*netv1.Ingress { return c.ingresses } func (c clientMock) GetService(namespace, name string) (*corev1.Service, bool, error) { if c.apiServiceError != nil { return nil, false, c.apiServiceError } for _, service := range c.services { if service.Namespace == namespace && service.Name == name { return service, true, nil } } return nil, false, c.apiServiceError } func (c clientMock) GetEndpointSlicesForService(namespace, serviceName string) ([]*discoveryv1.EndpointSlice, error) { if c.apiEndpointSlicesError != nil { return nil, c.apiEndpointSlicesError } var result []*discoveryv1.EndpointSlice for _, endpointSlice := range c.endpointSlices { if endpointSlice.Namespace == namespace && endpointSlice.Labels[discoveryv1.LabelServiceName] == serviceName { result = append(result, endpointSlice) } } return result, nil } func (c clientMock) GetNodes() ([]*corev1.Node, bool, error) { if c.apiNodesError != nil { return nil, false, c.apiNodesError } return c.nodes, true, nil } func (c clientMock) GetSecret(namespace, name string) (*corev1.Secret, bool, error) { if c.apiSecretError != nil { return nil, false, c.apiSecretError } for _, secret := range c.secrets { if secret.Namespace == namespace && secret.Name == name { return secret, true, nil } } return nil, false, nil } func (c clientMock) GetIngressClasses() ([]*netv1.IngressClass, error) { return c.ingressClasses, nil } func (c clientMock) WatchAll(namespaces []string, stopCh <-chan struct{}) (<-chan interface{}, error) { return c.watchChan, nil } func (c clientMock) UpdateIngressStatus(_ *netv1.Ingress, _ []netv1.IngressLoadBalancerIngress) error { return c.apiIngressStatusError }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/gateway/tlsroute_test.go
pkg/provider/kubernetes/gateway/tlsroute_test.go
package gateway import ( "testing" "github.com/stretchr/testify/assert" gatev1 "sigs.k8s.io/gateway-api/apis/v1" ) func Test_hostSNIRule(t *testing.T) { testCases := []struct { desc string hostnames []gatev1.Hostname expectedRule string expectedPriority int expectError bool }{ { desc: "Empty", expectedRule: "HostSNI(`*`)", expectedPriority: 0, }, { desc: "Empty hostname", hostnames: []gatev1.Hostname{""}, expectedRule: "HostSNI(`*`)", expectedPriority: 0, }, { desc: "Supported wildcard", hostnames: []gatev1.Hostname{"*.foo"}, expectedRule: "HostSNIRegexp(`^[a-z0-9-\\.]+\\.foo$`)", expectedPriority: 4, }, { desc: "Some empty hostnames", hostnames: []gatev1.Hostname{"foo", "", "bar"}, expectedRule: "HostSNI(`foo`) || HostSNI(`bar`)", expectedPriority: 3, }, { desc: "Valid hostname", hostnames: []gatev1.Hostname{"foo"}, expectedRule: "HostSNI(`foo`)", expectedPriority: 3, }, { desc: "Multiple valid hostnames", hostnames: []gatev1.Hostname{"foo", "bar"}, expectedRule: "HostSNI(`foo`) || HostSNI(`bar`)", expectedPriority: 3, }, { desc: "Multiple valid hostnames with wildcard", hostnames: []gatev1.Hostname{"bar.foo", "foo.foo", "*.foo"}, expectedRule: "HostSNI(`bar.foo`) || HostSNI(`foo.foo`) || HostSNIRegexp(`^[a-z0-9-\\.]+\\.foo$`)", expectedPriority: 7, }, { desc: "Multiple overlapping hostnames", hostnames: []gatev1.Hostname{"foo", "bar", "foo", "baz"}, expectedRule: "HostSNI(`foo`) || HostSNI(`bar`) || HostSNI(`baz`)", expectedPriority: 3, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() rule, priority := hostSNIRule(test.hostnames) assert.Equal(t, test.expectedRule, rule) assert.Equal(t, test.expectedPriority, priority) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/gateway/client.go
pkg/provider/kubernetes/gateway/client.go
package gateway import ( "context" "errors" "fmt" "os" "reflect" "slices" "time" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/k8s" "github.com/traefik/traefik/v3/pkg/types" corev1 "k8s.io/api/core/v1" discoveryv1 "k8s.io/api/discovery/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/selection" ktypes "k8s.io/apimachinery/pkg/types" kinformers "k8s.io/client-go/informers" kclientset "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/util/retry" gatev1 "sigs.k8s.io/gateway-api/apis/v1" gatev1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" gatev1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" gateclientset "sigs.k8s.io/gateway-api/pkg/client/clientset/versioned" gateinformers "sigs.k8s.io/gateway-api/pkg/client/informers/externalversions" ) const resyncPeriod = 10 * time.Minute type clientWrapper struct { csGateway gateclientset.Interface csKube kclientset.Interface factoryNamespace kinformers.SharedInformerFactory factoryGatewayClass gateinformers.SharedInformerFactory factoriesGateway map[string]gateinformers.SharedInformerFactory factoriesKube map[string]kinformers.SharedInformerFactory factoriesSecret map[string]kinformers.SharedInformerFactory isNamespaceAll bool watchedNamespaces []string labelSelector string experimentalChannel bool } func createClientFromConfig(c *rest.Config) (*clientWrapper, error) { csGateway, err := gateclientset.NewForConfig(c) if err != nil { return nil, err } csKube, err := kclientset.NewForConfig(c) if err != nil { return nil, err } return newClientImpl(csKube, csGateway), nil } func newClientImpl(csKube kclientset.Interface, csGateway gateclientset.Interface) *clientWrapper { return &clientWrapper{ csGateway: csGateway, csKube: csKube, factoriesGateway: make(map[string]gateinformers.SharedInformerFactory), factoriesKube: make(map[string]kinformers.SharedInformerFactory), factoriesSecret: make(map[string]kinformers.SharedInformerFactory), } } // newInClusterClient returns a new Provider client that is expected to run // inside the cluster. func newInClusterClient(endpoint string) (*clientWrapper, error) { config, err := rest.InClusterConfig() if err != nil { return nil, fmt.Errorf("failed to create in-cluster configuration: %w", err) } if endpoint != "" { config.Host = endpoint } return createClientFromConfig(config) } func newExternalClusterClientFromFile(file string) (*clientWrapper, error) { configFromFlags, err := clientcmd.BuildConfigFromFlags("", file) if err != nil { return nil, err } return createClientFromConfig(configFromFlags) } // newExternalClusterClient returns a new Provider client that may run outside of the cluster. // The endpoint parameter must not be empty. func newExternalClusterClient(endpoint, caFilePath string, token types.FileOrContent) (*clientWrapper, error) { if endpoint == "" { return nil, errors.New("endpoint missing for external cluster client") } tokenData, err := token.Read() if err != nil { return nil, fmt.Errorf("read token: %w", err) } config := &rest.Config{ Host: endpoint, BearerToken: string(tokenData), } if caFilePath != "" { caData, err := os.ReadFile(caFilePath) if err != nil { return nil, fmt.Errorf("failed to read CA file %s: %w", caFilePath, err) } config.TLSClientConfig = rest.TLSClientConfig{CAData: caData} } return createClientFromConfig(config) } // WatchAll starts namespace-specific controllers for all relevant kinds. func (c *clientWrapper) WatchAll(namespaces []string, stopCh <-chan struct{}) (<-chan interface{}, error) { eventCh := make(chan interface{}, 1) eventHandler := &k8s.ResourceEventHandler{Ev: eventCh} if len(namespaces) == 0 { namespaces = []string{metav1.NamespaceAll} c.isNamespaceAll = true } c.watchedNamespaces = namespaces notOwnedByHelm := func(opts *metav1.ListOptions) { opts.LabelSelector = "owner!=helm" } labelSelectorOptions := func(options *metav1.ListOptions) { options.LabelSelector = c.labelSelector } c.factoryNamespace = kinformers.NewSharedInformerFactory(c.csKube, resyncPeriod) _, err := c.factoryNamespace.Core().V1().Namespaces().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } c.factoryGatewayClass = gateinformers.NewSharedInformerFactoryWithOptions(c.csGateway, resyncPeriod, gateinformers.WithTweakListOptions(labelSelectorOptions)) _, err = c.factoryGatewayClass.Gateway().V1().GatewayClasses().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } for _, ns := range namespaces { factoryKube := kinformers.NewSharedInformerFactoryWithOptions(c.csKube, resyncPeriod, kinformers.WithNamespace(ns)) _, err = factoryKube.Core().V1().Services().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryKube.Discovery().V1().EndpointSlices().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } factoryGateway := gateinformers.NewSharedInformerFactoryWithOptions(c.csGateway, resyncPeriod, gateinformers.WithNamespace(ns)) _, err = factoryGateway.Gateway().V1().Gateways().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryGateway.Gateway().V1().HTTPRoutes().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryGateway.Gateway().V1().GRPCRoutes().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryGateway.Gateway().V1beta1().ReferenceGrants().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryGateway.Gateway().V1().BackendTLSPolicies().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryKube.Core().V1().ConfigMaps().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } if c.experimentalChannel { _, err = factoryGateway.Gateway().V1alpha2().TCPRoutes().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryGateway.Gateway().V1alpha2().TLSRoutes().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } } factorySecret := kinformers.NewSharedInformerFactoryWithOptions(c.csKube, resyncPeriod, kinformers.WithNamespace(ns), kinformers.WithTweakListOptions(notOwnedByHelm)) _, err = factorySecret.Core().V1().Secrets().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } c.factoriesGateway[ns] = factoryGateway c.factoriesKube[ns] = factoryKube c.factoriesSecret[ns] = factorySecret } c.factoryNamespace.Start(stopCh) c.factoryGatewayClass.Start(stopCh) for _, ns := range namespaces { c.factoriesGateway[ns].Start(stopCh) c.factoriesKube[ns].Start(stopCh) c.factoriesSecret[ns].Start(stopCh) } for t, ok := range c.factoryNamespace.WaitForCacheSync(stopCh) { if !ok { return nil, fmt.Errorf("timed out waiting for controller caches to sync %s", t.String()) } } for t, ok := range c.factoryGatewayClass.WaitForCacheSync(stopCh) { if !ok { return nil, fmt.Errorf("timed out waiting for controller caches to sync %s", t.String()) } } for _, ns := range namespaces { for t, ok := range c.factoriesGateway[ns].WaitForCacheSync(stopCh) { if !ok { return nil, fmt.Errorf("timed out waiting for controller caches to sync %s in namespace %q", t.String(), ns) } } for t, ok := range c.factoriesKube[ns].WaitForCacheSync(stopCh) { if !ok { return nil, fmt.Errorf("timed out waiting for controller caches to sync %s in namespace %q", t.String(), ns) } } for t, ok := range c.factoriesSecret[ns].WaitForCacheSync(stopCh) { if !ok { return nil, fmt.Errorf("timed out waiting for controller caches to sync %s in namespace %q", t.String(), ns) } } } return eventCh, nil } func (c *clientWrapper) ListNamespaces(selector labels.Selector) ([]string, error) { ns, err := c.factoryNamespace.Core().V1().Namespaces().Lister().List(selector) if err != nil { return nil, err } var namespaces []string for _, namespace := range ns { if !c.isWatchedNamespace(namespace.Name) { log.Warn().Msgf("Namespace %q is not within %q watched namespaces", selector, namespace) continue } namespaces = append(namespaces, namespace.Name) } return namespaces, nil } func (c *clientWrapper) ListHTTPRoutes() ([]*gatev1.HTTPRoute, error) { var httpRoutes []*gatev1.HTTPRoute for _, namespace := range c.watchedNamespaces { routes, err := c.factoriesGateway[c.lookupNamespace(namespace)].Gateway().V1().HTTPRoutes().Lister().HTTPRoutes(namespace).List(labels.Everything()) if err != nil { return nil, fmt.Errorf("listing HTTP routes in namespace %s", namespace) } httpRoutes = append(httpRoutes, routes...) } return httpRoutes, nil } func (c *clientWrapper) ListGRPCRoutes() ([]*gatev1.GRPCRoute, error) { var grpcRoutes []*gatev1.GRPCRoute for _, namespace := range c.watchedNamespaces { routes, err := c.factoriesGateway[c.lookupNamespace(namespace)].Gateway().V1().GRPCRoutes().Lister().GRPCRoutes(namespace).List(labels.Everything()) if err != nil { return nil, fmt.Errorf("listing GRPC routes in namespace %s", namespace) } grpcRoutes = append(grpcRoutes, routes...) } return grpcRoutes, nil } func (c *clientWrapper) ListTCPRoutes() ([]*gatev1alpha2.TCPRoute, error) { var tcpRoutes []*gatev1alpha2.TCPRoute for _, namespace := range c.watchedNamespaces { routes, err := c.factoriesGateway[c.lookupNamespace(namespace)].Gateway().V1alpha2().TCPRoutes().Lister().TCPRoutes(namespace).List(labels.Everything()) if err != nil { return nil, fmt.Errorf("listing TCP routes in namespace %s", namespace) } tcpRoutes = append(tcpRoutes, routes...) } return tcpRoutes, nil } func (c *clientWrapper) ListTLSRoutes() ([]*gatev1alpha2.TLSRoute, error) { var tlsRoutes []*gatev1alpha2.TLSRoute for _, namespace := range c.watchedNamespaces { routes, err := c.factoriesGateway[c.lookupNamespace(namespace)].Gateway().V1alpha2().TLSRoutes().Lister().TLSRoutes(namespace).List(labels.Everything()) if err != nil { return nil, fmt.Errorf("listing TLS routes in namespace %s", namespace) } tlsRoutes = append(tlsRoutes, routes...) } return tlsRoutes, nil } func (c *clientWrapper) ListReferenceGrants(namespace string) ([]*gatev1beta1.ReferenceGrant, error) { if !c.isWatchedNamespace(namespace) { return nil, fmt.Errorf("failed to get ReferenceGrants: namespace %s is not within watched namespaces", namespace) } referenceGrants, err := c.factoriesGateway[c.lookupNamespace(namespace)].Gateway().V1beta1().ReferenceGrants().Lister().ReferenceGrants(namespace).List(labels.Everything()) if err != nil { return nil, err } return referenceGrants, nil } func (c *clientWrapper) ListGateways() []*gatev1.Gateway { var result []*gatev1.Gateway for ns, factory := range c.factoriesGateway { gateways, err := factory.Gateway().V1().Gateways().Lister().Gateways(ns).List(labels.Everything()) if err != nil { log.Error().Err(err).Msgf("Failed to list Gateways in namespace %s", ns) continue } result = append(result, gateways...) } return result } func (c *clientWrapper) ListGatewayClasses() ([]*gatev1.GatewayClass, error) { return c.factoryGatewayClass.Gateway().V1().GatewayClasses().Lister().List(labels.Everything()) } // ListEndpointSlicesForService returns the EndpointSlices for the given service name in the given namespace. func (c *clientWrapper) ListEndpointSlicesForService(namespace, serviceName string) ([]*discoveryv1.EndpointSlice, error) { if !c.isWatchedNamespace(namespace) { return nil, fmt.Errorf("failed to get endpointslices for service %s/%s: namespace is not within watched namespaces", namespace, serviceName) } serviceLabelRequirement, err := labels.NewRequirement(discoveryv1.LabelServiceName, selection.Equals, []string{serviceName}) if err != nil { return nil, fmt.Errorf("failed to create service label selector requirement: %w", err) } serviceSelector := labels.NewSelector() serviceSelector = serviceSelector.Add(*serviceLabelRequirement) return c.factoriesKube[c.lookupNamespace(namespace)].Discovery().V1().EndpointSlices().Lister().EndpointSlices(namespace).List(serviceSelector) } // ListBackendTLSPoliciesForService returns the BackendTLSPolicy for the given service name in the given namespace. func (c *clientWrapper) ListBackendTLSPoliciesForService(namespace, serviceName string) ([]*gatev1.BackendTLSPolicy, error) { if !c.isWatchedNamespace(namespace) { return nil, fmt.Errorf("failed to get BackendTLSPolicies for service %s/%s: namespace is not within watched namespaces", namespace, serviceName) } policies, err := c.factoriesGateway[c.lookupNamespace(namespace)].Gateway().V1().BackendTLSPolicies().Lister().BackendTLSPolicies(namespace).List(labels.Everything()) if err != nil { return nil, fmt.Errorf("failed to list BackendTLSPolicies in namespace %s", namespace) } var servicePolicies []*gatev1.BackendTLSPolicy for _, policy := range policies { for _, ref := range policy.Spec.TargetRefs { // The policy does not target the service. if (ref.Group != "" && ref.Group != groupCore) || ref.Kind != kindService || string(ref.Name) != serviceName { continue } servicePolicies = append(servicePolicies, policy) } } return servicePolicies, nil } // GetService returns the named service from the given namespace. func (c *clientWrapper) GetService(namespace, name string) (*corev1.Service, error) { if !c.isWatchedNamespace(namespace) { return nil, fmt.Errorf("failed to get service %s/%s: namespace is not within watched namespaces", namespace, name) } return c.factoriesKube[c.lookupNamespace(namespace)].Core().V1().Services().Lister().Services(namespace).Get(name) } // GetSecret returns the named secret from the given namespace. func (c *clientWrapper) GetSecret(namespace, name string) (*corev1.Secret, error) { if !c.isWatchedNamespace(namespace) { return nil, fmt.Errorf("failed to get secret %s/%s: namespace is not within watched namespaces", namespace, name) } return c.factoriesSecret[c.lookupNamespace(namespace)].Core().V1().Secrets().Lister().Secrets(namespace).Get(name) } // GetConfigMap returns the named configMap from the given namespace. func (c *clientWrapper) GetConfigMap(namespace, name string) (*corev1.ConfigMap, error) { if !c.isWatchedNamespace(namespace) { return nil, fmt.Errorf("failed to get configMap %s/%s: namespace is not within watched namespaces", namespace, name) } return c.factoriesKube[c.lookupNamespace(namespace)].Core().V1().ConfigMaps().Lister().ConfigMaps(namespace).Get(name) } func (c *clientWrapper) UpdateGatewayClassStatus(ctx context.Context, name string, status gatev1.GatewayClassStatus) error { err := retry.RetryOnConflict(retry.DefaultRetry, func() error { currentGatewayClass, err := c.factoryGatewayClass.Gateway().V1().GatewayClasses().Lister().Get(name) if err != nil { // We have to return err itself here (not wrapped inside another error) // so that RetryOnConflict can identify it correctly. return err } if conditionsEqual(currentGatewayClass.Status.Conditions, status.Conditions) { return nil } currentGatewayClass = currentGatewayClass.DeepCopy() currentGatewayClass.Status = status if _, err = c.csGateway.GatewayV1().GatewayClasses().UpdateStatus(ctx, currentGatewayClass, metav1.UpdateOptions{}); err != nil { // We have to return err itself here (not wrapped inside another error) // so that RetryOnConflict can identify it correctly. return err } return nil }) if err != nil { return fmt.Errorf("failed to update GatewayClass %s status: %w", name, err) } return nil } func (c *clientWrapper) UpdateGatewayStatus(ctx context.Context, gateway ktypes.NamespacedName, status gatev1.GatewayStatus) error { if !c.isWatchedNamespace(gateway.Namespace) { return fmt.Errorf("cannot update Gateway status %s/%s: namespace is not within watched namespaces", gateway.Namespace, gateway.Name) } err := retry.RetryOnConflict(retry.DefaultRetry, func() error { currentGateway, err := c.factoriesGateway[c.lookupNamespace(gateway.Namespace)].Gateway().V1().Gateways().Lister().Gateways(gateway.Namespace).Get(gateway.Name) if err != nil { // We have to return err itself here (not wrapped inside another error) // so that RetryOnConflict can identify it correctly. return err } if gatewayStatusEqual(currentGateway.Status, status) { return nil } currentGateway = currentGateway.DeepCopy() currentGateway.Status = status if _, err = c.csGateway.GatewayV1().Gateways(gateway.Namespace).UpdateStatus(ctx, currentGateway, metav1.UpdateOptions{}); err != nil { // We have to return err itself here (not wrapped inside another error) // so that RetryOnConflict can identify it correctly. return err } return nil }) if err != nil { return fmt.Errorf("failed to update Gateway %s/%s status: %w", gateway.Namespace, gateway.Name, err) } return nil } func (c *clientWrapper) UpdateHTTPRouteStatus(ctx context.Context, route ktypes.NamespacedName, status gatev1.HTTPRouteStatus) error { if !c.isWatchedNamespace(route.Namespace) { return fmt.Errorf("updating HTTPRoute status %s/%s: namespace is not within watched namespaces", route.Namespace, route.Name) } err := retry.RetryOnConflict(retry.DefaultRetry, func() error { currentRoute, err := c.factoriesGateway[c.lookupNamespace(route.Namespace)].Gateway().V1().HTTPRoutes().Lister().HTTPRoutes(route.Namespace).Get(route.Name) if err != nil { // We have to return err itself here (not wrapped inside another error) // so that RetryOnConflict can identify it correctly. return err } parentStatuses := make([]gatev1.RouteParentStatus, len(status.Parents)) copy(parentStatuses, status.Parents) // keep statuses added by other gateway controllers. // TODO: we should also keep statuses for gateways managed by other Traefik instances. for _, parentStatus := range currentRoute.Status.Parents { if parentStatus.ControllerName != controllerName { parentStatuses = append(parentStatuses, parentStatus) } } // do not update status when nothing has changed. if routeParentStatusesEqual(currentRoute.Status.Parents, parentStatuses) { return nil } currentRoute = currentRoute.DeepCopy() currentRoute.Status = gatev1.HTTPRouteStatus{ RouteStatus: gatev1.RouteStatus{ Parents: parentStatuses, }, } if _, err = c.csGateway.GatewayV1().HTTPRoutes(route.Namespace).UpdateStatus(ctx, currentRoute, metav1.UpdateOptions{}); err != nil { // We have to return err itself here (not wrapped inside another error) // so that RetryOnConflict can identify it correctly. return err } return nil }) if err != nil { return fmt.Errorf("failed to update HTTPRoute %s/%s status: %w", route.Namespace, route.Name, err) } return nil } func (c *clientWrapper) UpdateGRPCRouteStatus(ctx context.Context, route ktypes.NamespacedName, status gatev1.GRPCRouteStatus) error { if !c.isWatchedNamespace(route.Namespace) { return fmt.Errorf("updating GRPCRoute status %s/%s: namespace is not within watched namespaces", route.Namespace, route.Name) } err := retry.RetryOnConflict(retry.DefaultRetry, func() error { currentRoute, err := c.factoriesGateway[c.lookupNamespace(route.Namespace)].Gateway().V1().GRPCRoutes().Lister().GRPCRoutes(route.Namespace).Get(route.Name) if err != nil { // We have to return err itself here (not wrapped inside another error) // so that RetryOnConflict can identify it correctly. return err } parentStatuses := make([]gatev1.RouteParentStatus, len(status.Parents)) copy(parentStatuses, status.Parents) // keep statuses added by other gateway controllers. // TODO: we should also keep statuses for gateways managed by other Traefik instances. for _, parentStatus := range currentRoute.Status.Parents { if parentStatus.ControllerName != controllerName { parentStatuses = append(parentStatuses, parentStatus) } } // do not update status when nothing has changed. if routeParentStatusesEqual(currentRoute.Status.Parents, parentStatuses) { return nil } currentRoute = currentRoute.DeepCopy() currentRoute.Status = gatev1.GRPCRouteStatus{ RouteStatus: gatev1.RouteStatus{ Parents: parentStatuses, }, } if _, err = c.csGateway.GatewayV1().GRPCRoutes(route.Namespace).UpdateStatus(ctx, currentRoute, metav1.UpdateOptions{}); err != nil { // We have to return err itself here (not wrapped inside another error) // so that RetryOnConflict can identify it correctly. return err } return nil }) if err != nil { return fmt.Errorf("failed to update GRPCRoute %q status: %w", route.Name, err) } return nil } func (c *clientWrapper) UpdateTCPRouteStatus(ctx context.Context, route ktypes.NamespacedName, status gatev1alpha2.TCPRouteStatus) error { if !c.isWatchedNamespace(route.Namespace) { return fmt.Errorf("updating TCPRoute status %s/%s: namespace is not within watched namespaces", route.Namespace, route.Name) } err := retry.RetryOnConflict(retry.DefaultRetry, func() error { currentRoute, err := c.factoriesGateway[c.lookupNamespace(route.Namespace)].Gateway().V1alpha2().TCPRoutes().Lister().TCPRoutes(route.Namespace).Get(route.Name) if err != nil { // We have to return err itself here (not wrapped inside another error) // so that RetryOnConflict can identify it correctly. return err } parentStatuses := make([]gatev1.RouteParentStatus, len(status.Parents)) copy(parentStatuses, status.Parents) // keep statuses added by other gateway controllers. // TODO: we should also keep statuses for gateways managed by other Traefik instances. for _, parentStatus := range currentRoute.Status.Parents { if parentStatus.ControllerName != controllerName { parentStatuses = append(parentStatuses, parentStatus) } } // do not update status when nothing has changed. if routeParentStatusesEqual(currentRoute.Status.Parents, parentStatuses) { return nil } currentRoute = currentRoute.DeepCopy() currentRoute.Status = gatev1alpha2.TCPRouteStatus{ RouteStatus: gatev1.RouteStatus{ Parents: parentStatuses, }, } if _, err = c.csGateway.GatewayV1alpha2().TCPRoutes(route.Namespace).UpdateStatus(ctx, currentRoute, metav1.UpdateOptions{}); err != nil { // We have to return err itself here (not wrapped inside another error) // so that RetryOnConflict can identify it correctly. return err } return nil }) if err != nil { return fmt.Errorf("failed to update TCPRoute %s/%s status: %w", route.Namespace, route.Name, err) } return nil } func (c *clientWrapper) UpdateTLSRouteStatus(ctx context.Context, route ktypes.NamespacedName, status gatev1alpha2.TLSRouteStatus) error { if !c.isWatchedNamespace(route.Namespace) { return fmt.Errorf("updating TLSRoute status %s/%s: namespace is not within watched namespaces", route.Namespace, route.Name) } err := retry.RetryOnConflict(retry.DefaultRetry, func() error { currentRoute, err := c.factoriesGateway[c.lookupNamespace(route.Namespace)].Gateway().V1alpha2().TLSRoutes().Lister().TLSRoutes(route.Namespace).Get(route.Name) if err != nil { // We have to return err itself here (not wrapped inside another error) // so that RetryOnConflict can identify it correctly. return err } parentStatuses := make([]gatev1.RouteParentStatus, len(status.Parents)) copy(parentStatuses, status.Parents) // keep statuses added by other gateway controllers. // TODO: we should also keep statuses for gateways managed by other Traefik instances. for _, parentStatus := range currentRoute.Status.Parents { if parentStatus.ControllerName != controllerName { parentStatuses = append(parentStatuses, parentStatus) } } // do not update status when nothing has changed. if routeParentStatusesEqual(currentRoute.Status.Parents, parentStatuses) { return nil } currentRoute = currentRoute.DeepCopy() currentRoute.Status = gatev1alpha2.TLSRouteStatus{ RouteStatus: gatev1.RouteStatus{ Parents: parentStatuses, }, } if _, err = c.csGateway.GatewayV1alpha2().TLSRoutes(route.Namespace).UpdateStatus(ctx, currentRoute, metav1.UpdateOptions{}); err != nil { // We have to return err itself here (not wrapped inside another error) // so that RetryOnConflict can identify it correctly. return err } return nil }) if err != nil { return fmt.Errorf("failed to update TLSRoute %s/%s status: %w", route.Namespace, route.Name, err) } return nil } func (c *clientWrapper) UpdateBackendTLSPolicyStatus(ctx context.Context, policy ktypes.NamespacedName, status gatev1.PolicyStatus) error { if !c.isWatchedNamespace(policy.Namespace) { return fmt.Errorf("updating BackendTLSPolicy status %s/%s: namespace is not within watched namespaces", policy.Namespace, policy.Name) } err := retry.RetryOnConflict(retry.DefaultRetry, func() error { currentPolicy, err := c.factoriesGateway[c.lookupNamespace(policy.Namespace)].Gateway().V1().BackendTLSPolicies().Lister().BackendTLSPolicies(policy.Namespace).Get(policy.Name) if err != nil { // We have to return err itself here (not wrapped inside another error) // so that RetryOnConflict can identify it correctly. return err } ancestorStatuses := make([]gatev1.PolicyAncestorStatus, len(status.Ancestors)) copy(ancestorStatuses, status.Ancestors) // keep statuses added by other gateway controllers, // and statuses for Traefik gateway controller but not for the same Gateway as the one in parameter (AncestorRef). for _, ancestorStatus := range currentPolicy.Status.Ancestors { if ancestorStatus.ControllerName != controllerName { ancestorStatuses = append(ancestorStatuses, ancestorStatus) continue } } if len(ancestorStatuses) > 16 { return fmt.Errorf("failed to update BackendTLSPolicy %s/%s status: PolicyAncestor statuses count exceeds 16", policy.Namespace, policy.Name) } // do not update status when nothing has changed. if policyAncestorStatusesEqual(currentPolicy.Status.Ancestors, ancestorStatuses) { return nil } currentPolicy = currentPolicy.DeepCopy() currentPolicy.Status = gatev1.PolicyStatus{ Ancestors: ancestorStatuses, } if _, err = c.csGateway.GatewayV1().BackendTLSPolicies(policy.Namespace).UpdateStatus(ctx, currentPolicy, metav1.UpdateOptions{}); err != nil { // We have to return err itself here (not wrapped inside another error) // so that RetryOnConflict can identify it correctly. return err } return nil }) if err != nil { return fmt.Errorf("failed to update BackendTLSPolicy %s/%s status: %w", policy.Namespace, policy.Name, err) } return nil } // lookupNamespace returns the lookup namespace listenerKey for the given namespace. // When listening on all namespaces, it returns the client-go identifier ("") // for all-namespaces. Otherwise, it returns the given namespace. // The distinction is necessary because we index all informers on the special // identifier iff all-namespaces are requested but receive specific namespace // identifiers from the Kubernetes API, so we have to bridge this gap. func (c *clientWrapper) lookupNamespace(namespace string) string { if c.isNamespaceAll { return metav1.NamespaceAll } return namespace } // isWatchedNamespace checks to ensure that the namespace is being watched before we request // it to ensure we don't panic by requesting an out-of-watch object. func (c *clientWrapper) isWatchedNamespace(namespace string) bool { if c.isNamespaceAll { return true } return slices.Contains(c.watchedNamespaces, namespace) } func gatewayStatusEqual(statusA, statusB gatev1.GatewayStatus) bool { return reflect.DeepEqual(statusA.Addresses, statusB.Addresses) && listenersStatusEqual(statusA.Listeners, statusB.Listeners) && conditionsEqual(statusA.Conditions, statusB.Conditions) } func policyAncestorStatusesEqual(policyAncestorStatusesA, policyAncestorStatusesB []gatev1.PolicyAncestorStatus) bool { if len(policyAncestorStatusesA) != len(policyAncestorStatusesB) { return false } for _, sA := range policyAncestorStatusesA { if !slices.ContainsFunc(policyAncestorStatusesB, func(sB gatev1.PolicyAncestorStatus) bool { return policyAncestorStatusEqual(sB, sA) }) { return false } } for _, sB := range policyAncestorStatusesB { if !slices.ContainsFunc(policyAncestorStatusesA, func(sA gatev1.PolicyAncestorStatus) bool { return policyAncestorStatusEqual(sA, sB) }) { return false } } return true } func policyAncestorStatusEqual(sA, sB gatev1.PolicyAncestorStatus) bool { return sA.ControllerName == sB.ControllerName && reflect.DeepEqual(sA.AncestorRef, sB.AncestorRef) && conditionsEqual(sA.Conditions, sB.Conditions) } func routeParentStatusesEqual(routeParentStatusesA, routeParentStatusesB []gatev1alpha2.RouteParentStatus) bool { if len(routeParentStatusesA) != len(routeParentStatusesB) { return false } for _, sA := range routeParentStatusesA { if !slices.ContainsFunc(routeParentStatusesB, func(sB gatev1alpha2.RouteParentStatus) bool { return routeParentStatusEqual(sB, sA) }) { return false } } for _, sB := range routeParentStatusesB { if !slices.ContainsFunc(routeParentStatusesA, func(sA gatev1alpha2.RouteParentStatus) bool { return routeParentStatusEqual(sA, sB) }) { return false } } return true } func routeParentStatusEqual(sA, sB gatev1alpha2.RouteParentStatus) bool { return sA.ControllerName == sB.ControllerName && reflect.DeepEqual(sA.ParentRef, sB.ParentRef) && conditionsEqual(sA.Conditions, sB.Conditions) } func listenersStatusEqual(listenerA, listenerB []gatev1.ListenerStatus) bool { return slices.EqualFunc(listenerA, listenerB, func(lA gatev1.ListenerStatus, lB gatev1.ListenerStatus) bool { return lA.Name == lB.Name && lA.AttachedRoutes == lB.AttachedRoutes && conditionsEqual(lA.Conditions, lB.Conditions) }) } func conditionsEqual(conditionsA, conditionsB []metav1.Condition) bool { return slices.EqualFunc(conditionsA, conditionsB, func(cA metav1.Condition, cB metav1.Condition) bool { return cA.Type == cB.Type && cA.Reason == cB.Reason && cA.Status == cB.Status && cA.Message == cB.Message && cA.ObservedGeneration == cB.ObservedGeneration }) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/gateway/features.go
pkg/provider/kubernetes/gateway/features.go
package gateway import ( "sync" "k8s.io/apimachinery/pkg/util/sets" "sigs.k8s.io/gateway-api/pkg/features" ) var SupportedFeatures = sync.OnceValue(func() []features.FeatureName { featureSet := sets.New[features.Feature](). Insert(features.GatewayCoreFeatures.UnsortedList()...). Insert(features.GatewayExtendedFeatures.Intersection(extendedGatewayFeatures()).UnsortedList()...). Insert(features.HTTPRouteCoreFeatures.UnsortedList()...). Insert(features.HTTPRouteExtendedFeatures.Intersection(extendedHTTPRouteFeatures()).UnsortedList()...). Insert(features.ReferenceGrantCoreFeatures.UnsortedList()...). Insert(features.BackendTLSPolicyCoreFeatures.UnsortedList()...). Insert(features.GRPCRouteCoreFeatures.UnsortedList()...). Insert(features.TLSRouteCoreFeatures.UnsortedList()...) featureNames := make([]features.FeatureName, 0, featureSet.Len()) for f := range featureSet { featureNames = append(featureNames, f.Name) } return featureNames }) // extendedGatewayFeatures returns the supported extended Gateway features. func extendedGatewayFeatures() sets.Set[features.Feature] { return sets.New(features.GatewayPort8080Feature) } // extendedHTTPRouteFeatures returns the supported extended HTTP Route features. func extendedHTTPRouteFeatures() sets.Set[features.Feature] { return sets.New( features.HTTPRouteQueryParamMatchingFeature, features.HTTPRouteMethodMatchingFeature, features.HTTPRoutePortRedirectFeature, features.HTTPRouteSchemeRedirectFeature, features.HTTPRouteHostRewriteFeature, features.HTTPRoutePathRewriteFeature, features.HTTPRoutePathRedirectFeature, features.HTTPRouteResponseHeaderModificationFeature, features.HTTPRouteBackendProtocolH2CFeature, features.HTTPRouteBackendProtocolWebSocketFeature, features.HTTPRouteDestinationPortMatchingFeature, ) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/gateway/tlsroute.go
pkg/provider/kubernetes/gateway/tlsroute.go
package gateway import ( "context" "fmt" "net" "regexp" "strconv" "strings" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/provider" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ktypes "k8s.io/apimachinery/pkg/types" "k8s.io/utils/ptr" gatev1 "sigs.k8s.io/gateway-api/apis/v1" gatev1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" ) func (p *Provider) loadTLSRoutes(ctx context.Context, gatewayListeners []gatewayListener, conf *dynamic.Configuration) { logger := log.Ctx(ctx) routes, err := p.client.ListTLSRoutes() if err != nil { logger.Error().Err(err).Msgf("Unable to list TLSRoute") return } for _, route := range routes { logger := log.Ctx(ctx).With(). Str("tls_route", route.Name). Str("namespace", route.Namespace).Logger() routeListeners := matchingGatewayListeners(gatewayListeners, route.Namespace, route.Spec.ParentRefs) if len(routeListeners) == 0 { continue } var parentStatuses []gatev1alpha2.RouteParentStatus for _, parentRef := range route.Spec.ParentRefs { parentStatus := &gatev1alpha2.RouteParentStatus{ ParentRef: parentRef, ControllerName: controllerName, Conditions: []metav1.Condition{ { Type: string(gatev1.RouteConditionAccepted), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonNoMatchingParent), }, }, } for _, listener := range routeListeners { accepted := matchListener(listener, parentRef) if accepted && !allowRoute(listener, route.Namespace, kindTLSRoute) { parentStatus.Conditions = updateRouteConditionAccepted(parentStatus.Conditions, string(gatev1.RouteReasonNotAllowedByListeners)) accepted = false } hostnames, ok := findMatchingHostnames(listener.Hostname, route.Spec.Hostnames) if accepted && !ok { parentStatus.Conditions = updateRouteConditionAccepted(parentStatus.Conditions, string(gatev1.RouteReasonNoMatchingListenerHostname)) accepted = false } if accepted { listener.Status.AttachedRoutes++ // only consider the route attached if the listener is in an "attached" state. if listener.Attached { parentStatus.Conditions = updateRouteConditionAccepted(parentStatus.Conditions, string(gatev1.RouteReasonAccepted)) } } routeConf, resolveRefCondition := p.loadTLSRoute(listener, route, hostnames) if accepted && listener.Attached { mergeTCPConfiguration(routeConf, conf) } parentStatus.Conditions = upsertRouteConditionResolvedRefs(parentStatus.Conditions, resolveRefCondition) } parentStatuses = append(parentStatuses, *parentStatus) } routeStatus := gatev1alpha2.TLSRouteStatus{ RouteStatus: gatev1alpha2.RouteStatus{ Parents: parentStatuses, }, } if err := p.client.UpdateTLSRouteStatus(ctx, ktypes.NamespacedName{Namespace: route.Namespace, Name: route.Name}, routeStatus); err != nil { logger.Warn(). Err(err). Msg("Unable to update TLSRoute status") } } } func (p *Provider) loadTLSRoute(listener gatewayListener, route *gatev1alpha2.TLSRoute, hostnames []gatev1.Hostname) (*dynamic.Configuration, metav1.Condition) { conf := &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: make(map[string]*dynamic.TCPRouter), Middlewares: make(map[string]*dynamic.TCPMiddleware), Services: make(map[string]*dynamic.TCPService), ServersTransports: make(map[string]*dynamic.TCPServersTransport), }, } condition := metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionTrue, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteConditionResolvedRefs), } for ri, routeRule := range route.Spec.Rules { if len(routeRule.BackendRefs) == 0 { // Should not happen due to validation. // https://github.com/kubernetes-sigs/gateway-api/blob/v0.4.0/apis/v1alpha2/tlsroute_types.go#L120 continue } rule, priority := hostSNIRule(hostnames) router := dynamic.TCPRouter{ RuleSyntax: "default", Rule: rule, Priority: priority, EntryPoints: []string{listener.EPName}, TLS: &dynamic.RouterTCPTLSConfig{ Passthrough: listener.TLS != nil && listener.TLS.Mode != nil && *listener.TLS.Mode == gatev1.TLSModePassthrough, }, } // Adding the gateway desc and the entryPoint desc prevents overlapping of routers build from the same routes. routeKey := provider.Normalize(fmt.Sprintf("%s-%s-%s-gw-%s-%s-ep-%s-%d", strings.ToLower(kindTLSRoute), route.Namespace, route.Name, listener.GWNamespace, listener.GWName, listener.EPName, ri)) // Routing criteria should be introduced at some point. routerName := makeRouterName("", routeKey) if len(routeRule.BackendRefs) == 1 && isInternalService(routeRule.BackendRefs[0]) { router.Service = string(routeRule.BackendRefs[0].Name) conf.TCP.Routers[routerName] = &router continue } var serviceCondition *metav1.Condition router.Service, serviceCondition = p.loadTLSWRRService(conf, routerName, routeRule.BackendRefs, route) if serviceCondition != nil { condition = *serviceCondition } conf.TCP.Routers[routerName] = &router } return conf, condition } // loadTLSWRRService is generating a WRR service, even when there is only one target. func (p *Provider) loadTLSWRRService(conf *dynamic.Configuration, routeKey string, backendRefs []gatev1.BackendRef, route *gatev1alpha2.TLSRoute) (string, *metav1.Condition) { name := routeKey + "-wrr" if _, ok := conf.TCP.Services[name]; ok { return name, nil } var wrr dynamic.TCPWeightedRoundRobin var condition *metav1.Condition for _, backendRef := range backendRefs { svcName, svc, errCondition := p.loadTLSService(route, backendRef) weight := ptr.To(int(ptr.Deref(backendRef.Weight, 1))) if errCondition != nil { condition = errCondition errName := routeKey + "-err-lb" conf.TCP.Services[errName] = &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{}, }, } wrr.Services = append(wrr.Services, dynamic.TCPWRRService{ Name: errName, Weight: weight, }) continue } if svc != nil { conf.TCP.Services[svcName] = svc } wrr.Services = append(wrr.Services, dynamic.TCPWRRService{ Name: svcName, Weight: weight, }) } conf.TCP.Services[name] = &dynamic.TCPService{Weighted: &wrr} return name, condition } func (p *Provider) loadTLSService(route *gatev1alpha2.TLSRoute, backendRef gatev1.BackendRef) (string, *dynamic.TCPService, *metav1.Condition) { kind := ptr.Deref(backendRef.Kind, kindService) group := groupCore if backendRef.Group != nil && *backendRef.Group != "" { group = string(*backendRef.Group) } namespace := route.Namespace if backendRef.Namespace != nil && *backendRef.Namespace != "" { namespace = string(*backendRef.Namespace) } serviceName := provider.Normalize(namespace + "-" + string(backendRef.Name)) if err := p.isReferenceGranted(kindTLSRoute, route.Namespace, group, string(kind), string(backendRef.Name), namespace); err != nil { return serviceName, nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonRefNotPermitted), Message: fmt.Sprintf("Cannot load TLSRoute BackendRef %s/%s/%s/%s: %s", group, kind, namespace, backendRef.Name, err), } } if group != groupCore || kind != kindService { name, err := p.loadTCPBackendRef(backendRef) if err != nil { return serviceName, nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonInvalidKind), Message: fmt.Sprintf("Cannot load TLSRoute BackendRef %s/%s/%s/%s: %s", group, kind, namespace, backendRef.Name, err), } } return name, nil, nil } port := ptr.Deref(backendRef.Port, gatev1.PortNumber(0)) if port == 0 { return serviceName, nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonUnsupportedProtocol), Message: fmt.Sprintf("Cannot load TLSRoute BackendRef %s/%s/%s/%s port is required", group, kind, namespace, backendRef.Name), } } portStr := strconv.FormatInt(int64(port), 10) serviceName = provider.Normalize(serviceName + "-" + portStr) lb, errCondition := p.loadTLSServers(namespace, route, backendRef) if errCondition != nil { return serviceName, nil, errCondition } return serviceName, &dynamic.TCPService{LoadBalancer: lb}, nil } func (p *Provider) loadTLSServers(namespace string, route *gatev1alpha2.TLSRoute, backendRef gatev1.BackendRef) (*dynamic.TCPServersLoadBalancer, *metav1.Condition) { backendAddresses, svcPort, err := p.getBackendAddresses(namespace, backendRef) if err != nil { return nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.GetGeneration(), LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonBackendNotFound), Message: fmt.Sprintf("Cannot load TLSRoute BackendRef %s/%s: %s", namespace, backendRef.Name, err), } } if svcPort.Protocol != corev1.ProtocolTCP { return nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.GetGeneration(), LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonUnsupportedProtocol), Message: fmt.Sprintf("Cannot load TLSRoute BackendRef %s/%s: only TCP protocol is supported", namespace, backendRef.Name), } } lb := &dynamic.TCPServersLoadBalancer{} for _, ba := range backendAddresses { lb.Servers = append(lb.Servers, dynamic.TCPServer{ // TODO determine whether the servers needs TLS, from the port? Address: net.JoinHostPort(ba.IP, strconv.Itoa(int(ba.Port))), }) } return lb, nil } func hostSNIRule(hostnames []gatev1.Hostname) (string, int) { var priority int rules := make([]string, 0, len(hostnames)) uniqHostnames := map[gatev1.Hostname]struct{}{} for _, hostname := range hostnames { if len(hostname) == 0 { continue } host := string(hostname) wildcard := strings.Count(host, "*") thisPriority := len(hostname) - wildcard if priority < thisPriority { priority = thisPriority } if _, exists := uniqHostnames[hostname]; exists { continue } uniqHostnames[hostname] = struct{}{} if wildcard == 0 { rules = append(rules, fmt.Sprintf("HostSNI(`%s`)", host)) continue } host = strings.Replace(regexp.QuoteMeta(host), `\*\.`, `[a-z0-9-\.]+\.`, 1) rules = append(rules, fmt.Sprintf("HostSNIRegexp(`^%s$`)", host)) } if len(hostnames) == 0 || len(rules) == 0 { return "HostSNI(`*`)", 0 } return strings.Join(rules, " || "), priority }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/gateway/grpcroute.go
pkg/provider/kubernetes/gateway/grpcroute.go
package gateway import ( "context" "errors" "fmt" "net" "strconv" "strings" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/provider" "google.golang.org/grpc/codes" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ktypes "k8s.io/apimachinery/pkg/types" "k8s.io/utils/ptr" gatev1 "sigs.k8s.io/gateway-api/apis/v1" ) // TODO: as described in the specification https://gateway-api.sigs.k8s.io/reference/spec/#gateway.networking.k8s.io%2fv1.GRPCRoute, we should check for hostname conflicts between HTTP and GRPC routes. func (p *Provider) loadGRPCRoutes(ctx context.Context, gatewayListeners []gatewayListener, conf *dynamic.Configuration) { routes, err := p.client.ListGRPCRoutes() if err != nil { log.Ctx(ctx).Error().Err(err).Msg("Unable to list GRPCRoutes") return } for _, route := range routes { logger := log.Ctx(ctx).With(). Str("grpc_route", route.Name). Str("namespace", route.Namespace). Logger() routeListeners := matchingGatewayListeners(gatewayListeners, route.Namespace, route.Spec.ParentRefs) if len(routeListeners) == 0 { continue } var parentStatuses []gatev1.RouteParentStatus for _, parentRef := range route.Spec.ParentRefs { parentStatus := &gatev1.RouteParentStatus{ ParentRef: parentRef, ControllerName: controllerName, Conditions: []metav1.Condition{ { Type: string(gatev1.RouteConditionAccepted), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonNoMatchingParent), }, }, } for _, listener := range routeListeners { accepted := matchListener(listener, parentRef) if accepted && !allowRoute(listener, route.Namespace, kindGRPCRoute) { parentStatus.Conditions = updateRouteConditionAccepted(parentStatus.Conditions, string(gatev1.RouteReasonNotAllowedByListeners)) accepted = false } hostnames, ok := findMatchingHostnames(listener.Hostname, route.Spec.Hostnames) if accepted && !ok { parentStatus.Conditions = updateRouteConditionAccepted(parentStatus.Conditions, string(gatev1.RouteReasonNoMatchingListenerHostname)) accepted = false } if accepted { // Gateway listener should have AttachedRoutes set even when Gateway has unresolved refs. listener.Status.AttachedRoutes++ // Only consider the route attached if the listener is in an "attached" state. if listener.Attached { parentStatus.Conditions = updateRouteConditionAccepted(parentStatus.Conditions, string(gatev1.RouteReasonAccepted)) } } routeConf, resolveRefCondition := p.loadGRPCRoute(logger.WithContext(ctx), listener, route, hostnames) if accepted && listener.Attached { mergeHTTPConfiguration(routeConf, conf) } parentStatus.Conditions = upsertRouteConditionResolvedRefs(parentStatus.Conditions, resolveRefCondition) } parentStatuses = append(parentStatuses, *parentStatus) } status := gatev1.GRPCRouteStatus{ RouteStatus: gatev1.RouteStatus{ Parents: parentStatuses, }, } if err := p.client.UpdateGRPCRouteStatus(ctx, ktypes.NamespacedName{Namespace: route.Namespace, Name: route.Name}, status); err != nil { logger.Warn(). Err(err). Msg("Unable to update GRPCRoute status") } } } func (p *Provider) loadGRPCRoute(ctx context.Context, listener gatewayListener, route *gatev1.GRPCRoute, hostnames []gatev1.Hostname) (*dynamic.Configuration, metav1.Condition) { conf := &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: make(map[string]*dynamic.Router), Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), ServersTransports: make(map[string]*dynamic.ServersTransport), }, } condition := metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionTrue, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteConditionResolvedRefs), } for ri, routeRule := range route.Spec.Rules { // Adding the gateway desc and the entryPoint desc prevents overlapping of routers build from the same routes. routeKey := provider.Normalize(fmt.Sprintf("%s-%s-%s-gw-%s-%s-ep-%s-%d", strings.ToLower(kindGRPCRoute), route.Namespace, route.Name, listener.GWNamespace, listener.GWName, listener.EPName, ri)) matches := routeRule.Matches if len(matches) == 0 { matches = []gatev1.GRPCRouteMatch{{}} } for _, match := range matches { rule, priority := buildGRPCMatchRule(hostnames, match) router := dynamic.Router{ // "default" stands for the default rule syntax in Traefik v3, i.e. the v3 syntax. RuleSyntax: "default", Rule: rule, Priority: priority, EntryPoints: []string{listener.EPName}, } if listener.Protocol == gatev1.HTTPSProtocolType { router.TLS = &dynamic.RouterTLSConfig{} } var err error routerName := makeRouterName(rule, routeKey) router.Middlewares, err = p.loadGRPCMiddlewares(conf, route.Namespace, routerName, routeRule.Filters) switch { case err != nil: log.Ctx(ctx).Error().Err(err).Msg("Unable to load GRPC route filters") errWrrName := routerName + "-err-wrr" conf.HTTP.Services[errWrrName] = &dynamic.Service{ Weighted: &dynamic.WeightedRoundRobin{ Services: []dynamic.WRRService{ { Name: "invalid-grpcroute-filter", GRPCStatus: &dynamic.GRPCStatus{ Code: codes.Unavailable, Msg: "Service Unavailable", }, Weight: ptr.To(1), }, }, }, } router.Service = errWrrName default: var serviceCondition *metav1.Condition router.Service, serviceCondition = p.loadGRPCService(conf, routerName, routeRule, route) if serviceCondition != nil { condition = *serviceCondition } } conf.HTTP.Routers[routerName] = &router } } return conf, condition } func (p *Provider) loadGRPCService(conf *dynamic.Configuration, routeKey string, routeRule gatev1.GRPCRouteRule, route *gatev1.GRPCRoute) (string, *metav1.Condition) { name := routeKey + "-wrr" if _, ok := conf.HTTP.Services[name]; ok { return name, nil } var wrr dynamic.WeightedRoundRobin var condition *metav1.Condition for _, backendRef := range routeRule.BackendRefs { svcName, svc, errCondition := p.loadGRPCBackendRef(route, backendRef) weight := ptr.To(int(ptr.Deref(backendRef.Weight, 1))) if errCondition != nil { condition = errCondition wrr.Services = append(wrr.Services, dynamic.WRRService{ Name: svcName, GRPCStatus: &dynamic.GRPCStatus{ Code: codes.Unavailable, Msg: "Service Unavailable", }, Weight: weight, }) continue } if svc != nil { conf.HTTP.Services[svcName] = svc } wrr.Services = append(wrr.Services, dynamic.WRRService{ Name: svcName, Weight: weight, }) } conf.HTTP.Services[name] = &dynamic.Service{Weighted: &wrr} return name, condition } func (p *Provider) loadGRPCBackendRef(route *gatev1.GRPCRoute, backendRef gatev1.GRPCBackendRef) (string, *dynamic.Service, *metav1.Condition) { kind := ptr.Deref(backendRef.Kind, kindService) group := groupCore if backendRef.Group != nil && *backendRef.Group != "" { group = string(*backendRef.Group) } namespace := route.Namespace if backendRef.Namespace != nil && *backendRef.Namespace != "" { namespace = string(*backendRef.Namespace) } serviceName := provider.Normalize(namespace + "-" + string(backendRef.Name)) if group != groupCore || kind != kindService { return serviceName, nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonInvalidKind), Message: fmt.Sprintf("Cannot load GRPCBackendRef %s/%s/%s/%s: only Kubernetes services are supported", group, kind, namespace, backendRef.Name), } } if err := p.isReferenceGranted(kindGRPCRoute, route.Namespace, group, string(kind), string(backendRef.Name), namespace); err != nil { return serviceName, nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonRefNotPermitted), Message: fmt.Sprintf("Cannot load GRPCBackendRef %s/%s/%s/%s: %s", group, kind, namespace, backendRef.Name, err), } } port := ptr.Deref(backendRef.Port, gatev1.PortNumber(0)) if port == 0 { return serviceName, nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonUnsupportedProtocol), Message: fmt.Sprintf("Cannot load GRPCBackendRef %s/%s/%s/%s: port is required", group, kind, namespace, backendRef.Name), } } portStr := strconv.FormatInt(int64(port), 10) serviceName = provider.Normalize(serviceName + "-" + portStr + "-grpc") lb, errCondition := p.loadGRPCServers(namespace, route, backendRef) if errCondition != nil { return serviceName, nil, errCondition } return serviceName, &dynamic.Service{LoadBalancer: lb}, nil } func (p *Provider) loadGRPCMiddlewares(conf *dynamic.Configuration, namespace, routerName string, filters []gatev1.GRPCRouteFilter) ([]string, error) { type namedMiddleware struct { Name string Config *dynamic.Middleware } var middlewares []namedMiddleware for i, filter := range filters { name := fmt.Sprintf("%s-%s-%d", routerName, strings.ToLower(string(filter.Type)), i) switch filter.Type { case gatev1.GRPCRouteFilterRequestHeaderModifier: middlewares = append(middlewares, namedMiddleware{ name, createRequestHeaderModifier(filter.RequestHeaderModifier), }) case gatev1.GRPCRouteFilterExtensionRef: name, middleware, err := p.loadHTTPRouteFilterExtensionRef(namespace, filter.ExtensionRef) if err != nil { return nil, fmt.Errorf("loading ExtensionRef filter %s: %w", filter.Type, err) } middlewares = append(middlewares, namedMiddleware{ name, middleware, }) default: // As per the spec: https://gateway-api.sigs.k8s.io/api-types/httproute/#filters-optional // In all cases where incompatible or unsupported filters are // specified, implementations MUST add a warning condition to // status. return nil, fmt.Errorf("unsupported filter %s", filter.Type) } } var middlewareNames []string for _, m := range middlewares { if m.Config != nil { conf.HTTP.Middlewares[m.Name] = m.Config } middlewareNames = append(middlewareNames, m.Name) } return middlewareNames, nil } func (p *Provider) loadGRPCServers(namespace string, route *gatev1.GRPCRoute, backendRef gatev1.GRPCBackendRef) (*dynamic.ServersLoadBalancer, *metav1.Condition) { backendAddresses, svcPort, err := p.getBackendAddresses(namespace, backendRef.BackendRef) if err != nil { return nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonBackendNotFound), Message: fmt.Sprintf("Cannot load GRPCBackendRef %s/%s: %s", namespace, backendRef.Name, err), } } if svcPort.Protocol != corev1.ProtocolTCP { return nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonUnsupportedProtocol), Message: fmt.Sprintf("Cannot load GRPCBackendRef %s/%s: only TCP protocol is supported", namespace, backendRef.Name), } } protocol, err := getGRPCServiceProtocol(svcPort) if err != nil { return nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonUnsupportedProtocol), Message: fmt.Sprintf("Cannot load GRPCBackendRef %s/%s: only \"kubernetes.io/h2c\" and \"https\" appProtocol is supported", namespace, backendRef.Name), } } lb := &dynamic.ServersLoadBalancer{} lb.SetDefaults() for _, ba := range backendAddresses { lb.Servers = append(lb.Servers, dynamic.Server{ URL: fmt.Sprintf("%s://%s", protocol, net.JoinHostPort(ba.IP, strconv.Itoa(int(ba.Port)))), }) } return lb, nil } func buildGRPCMatchRule(hostnames []gatev1.Hostname, match gatev1.GRPCRouteMatch) (string, int) { var matchRules []string methodRule := buildGRPCMethodRule(match.Method) matchRules = append(matchRules, methodRule) headerRules := buildGRPCHeaderRules(match.Headers) matchRules = append(matchRules, headerRules...) matchRulesStr := strings.Join(matchRules, " && ") hostRule, priority := buildHostRule(hostnames) if hostRule == "" { return matchRulesStr, len(matchRulesStr) } return hostRule + " && " + matchRulesStr, priority + len(matchRulesStr) } func buildGRPCMethodRule(method *gatev1.GRPCMethodMatch) string { if method == nil { return "PathPrefix(`/`)" } sExpr := "[^/]+" if s := ptr.Deref(method.Service, ""); s != "" { sExpr = s } mExpr := "[^/]+" if m := ptr.Deref(method.Method, ""); m != "" { mExpr = m } return fmt.Sprintf("PathRegexp(`/%s/%s`)", sExpr, mExpr) } func buildGRPCHeaderRules(headers []gatev1.GRPCHeaderMatch) []string { var rules []string for _, header := range headers { switch ptr.Deref(header.Type, gatev1.GRPCHeaderMatchExact) { case gatev1.GRPCHeaderMatchExact: rules = append(rules, fmt.Sprintf("Header(`%s`,`%s`)", header.Name, header.Value)) case gatev1.GRPCHeaderMatchRegularExpression: rules = append(rules, fmt.Sprintf("HeaderRegexp(`%s`,`%s`)", header.Name, header.Value)) } } return rules } func getGRPCServiceProtocol(portSpec corev1.ServicePort) (string, error) { if portSpec.Protocol != corev1.ProtocolTCP { return "", errors.New("only TCP protocol is supported") } if portSpec.AppProtocol == nil { return schemeH2C, nil } switch ap := strings.ToLower(*portSpec.AppProtocol); ap { case appProtocolH2C: return schemeH2C, nil case appProtocolHTTPS: return schemeHTTPS, nil default: return "", fmt.Errorf("unsupported application protocol %s", ap) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/gateway/annotations.go
pkg/provider/kubernetes/gateway/annotations.go
package gateway import ( "fmt" "strings" "github.com/traefik/traefik/v3/pkg/config/label" ) const annotationsPrefix = "traefik.io/" // ServiceConfig is the service's root configuration from annotations. type ServiceConfig struct { Service Service `json:"service"` } // Service is the service's configuration from annotations. type Service struct { NativeLB *bool `json:"nativeLB"` } func parseServiceAnnotations(annotations map[string]string) (ServiceConfig, error) { var svcConf ServiceConfig labels := convertAnnotations(annotations) if len(labels) == 0 { return svcConf, nil } if err := label.Decode(labels, &svcConf, "traefik.service."); err != nil { return svcConf, fmt.Errorf("decoding labels: %w", err) } return svcConf, nil } func convertAnnotations(annotations map[string]string) map[string]string { if len(annotations) == 0 { return nil } result := make(map[string]string) for key, value := range annotations { if !strings.HasPrefix(key, annotationsPrefix) { continue } newKey := strings.ReplaceAll(key, "io/", "") result[newKey] = value } return result }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/gateway/tcproute.go
pkg/provider/kubernetes/gateway/tcproute.go
package gateway import ( "context" "fmt" "net" "strconv" "strings" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/provider" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ktypes "k8s.io/apimachinery/pkg/types" "k8s.io/utils/ptr" gatev1 "sigs.k8s.io/gateway-api/apis/v1" gatev1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" ) func (p *Provider) loadTCPRoutes(ctx context.Context, gatewayListeners []gatewayListener, conf *dynamic.Configuration) { logger := log.Ctx(ctx) routes, err := p.client.ListTCPRoutes() if err != nil { logger.Error().Err(err).Msgf("Unable to list TCPRoutes") return } for _, route := range routes { logger := log.Ctx(ctx).With(). Str("tcp_route", route.Name). Str("namespace", route.Namespace). Logger() routeListeners := matchingGatewayListeners(gatewayListeners, route.Namespace, route.Spec.ParentRefs) if len(routeListeners) == 0 { continue } var parentStatuses []gatev1alpha2.RouteParentStatus for _, parentRef := range route.Spec.ParentRefs { parentStatus := &gatev1alpha2.RouteParentStatus{ ParentRef: parentRef, ControllerName: controllerName, Conditions: []metav1.Condition{ { Type: string(gatev1.RouteConditionAccepted), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonNoMatchingParent), }, }, } for _, listener := range routeListeners { accepted := matchListener(listener, parentRef) if accepted && !allowRoute(listener, route.Namespace, kindTCPRoute) { parentStatus.Conditions = updateRouteConditionAccepted(parentStatus.Conditions, string(gatev1.RouteReasonNotAllowedByListeners)) accepted = false } if accepted { listener.Status.AttachedRoutes++ // only consider the route attached if the listener is in an "attached" state. if listener.Attached { parentStatus.Conditions = updateRouteConditionAccepted(parentStatus.Conditions, string(gatev1.RouteReasonAccepted)) } } routeConf, resolveRefCondition := p.loadTCPRoute(listener, route) if accepted && listener.Attached { mergeTCPConfiguration(routeConf, conf) } parentStatus.Conditions = upsertRouteConditionResolvedRefs(parentStatus.Conditions, resolveRefCondition) } parentStatuses = append(parentStatuses, *parentStatus) } routeStatus := gatev1alpha2.TCPRouteStatus{ RouteStatus: gatev1alpha2.RouteStatus{ Parents: parentStatuses, }, } if err := p.client.UpdateTCPRouteStatus(ctx, ktypes.NamespacedName{Namespace: route.Namespace, Name: route.Name}, routeStatus); err != nil { logger.Warn(). Err(err). Msg("Unable to update TCPRoute status") } } } func (p *Provider) loadTCPRoute(listener gatewayListener, route *gatev1alpha2.TCPRoute) (*dynamic.Configuration, metav1.Condition) { conf := &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ Routers: make(map[string]*dynamic.TCPRouter), Middlewares: make(map[string]*dynamic.TCPMiddleware), Services: make(map[string]*dynamic.TCPService), ServersTransports: make(map[string]*dynamic.TCPServersTransport), }, } condition := metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionTrue, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteConditionResolvedRefs), } for ri, rule := range route.Spec.Rules { if rule.BackendRefs == nil { // Should not happen due to validation. // https://github.com/kubernetes-sigs/gateway-api/blob/v0.4.0/apis/v1alpha2/tcproute_types.go#L76 continue } router := dynamic.TCPRouter{ Rule: "HostSNI(`*`)", EntryPoints: []string{listener.EPName}, RuleSyntax: "default", } if listener.Protocol == gatev1.TLSProtocolType && listener.TLS != nil { router.TLS = &dynamic.RouterTCPTLSConfig{ Passthrough: listener.TLS.Mode != nil && *listener.TLS.Mode == gatev1.TLSModePassthrough, } } // Adding the gateway desc and the entryPoint desc prevents overlapping of routers build from the same routes. routeKey := provider.Normalize(fmt.Sprintf("%s-%s-%s-gw-%s-%s-ep-%s-%d", strings.ToLower(kindTCPRoute), route.Namespace, route.Name, listener.GWNamespace, listener.GWName, listener.EPName, ri)) // Routing criteria should be introduced at some point. routerName := makeRouterName("", routeKey) if len(rule.BackendRefs) == 1 && isInternalService(rule.BackendRefs[0]) { router.Service = string(rule.BackendRefs[0].Name) conf.TCP.Routers[routerName] = &router continue } var serviceCondition *metav1.Condition router.Service, serviceCondition = p.loadTCPWRRService(conf, routerName, rule.BackendRefs, route) if serviceCondition != nil { condition = *serviceCondition } conf.TCP.Routers[routerName] = &router } return conf, condition } // loadTCPWRRService is generating a WRR service, even when there is only one target. func (p *Provider) loadTCPWRRService(conf *dynamic.Configuration, routeKey string, backendRefs []gatev1.BackendRef, route *gatev1alpha2.TCPRoute) (string, *metav1.Condition) { name := routeKey + "-wrr" if _, ok := conf.TCP.Services[name]; ok { return name, nil } var wrr dynamic.TCPWeightedRoundRobin var condition *metav1.Condition for _, backendRef := range backendRefs { svcName, svc, errCondition := p.loadTCPService(route, backendRef) weight := ptr.To(int(ptr.Deref(backendRef.Weight, 1))) if errCondition != nil { condition = errCondition errName := routeKey + "-err-lb" conf.TCP.Services[errName] = &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{}, }, } wrr.Services = append(wrr.Services, dynamic.TCPWRRService{ Name: errName, Weight: weight, }) continue } if svc != nil { conf.TCP.Services[svcName] = svc } wrr.Services = append(wrr.Services, dynamic.TCPWRRService{ Name: svcName, Weight: weight, }) } conf.TCP.Services[name] = &dynamic.TCPService{Weighted: &wrr} return name, condition } func (p *Provider) loadTCPService(route *gatev1alpha2.TCPRoute, backendRef gatev1.BackendRef) (string, *dynamic.TCPService, *metav1.Condition) { kind := ptr.Deref(backendRef.Kind, kindService) group := groupCore if backendRef.Group != nil && *backendRef.Group != "" { group = string(*backendRef.Group) } namespace := route.Namespace if backendRef.Namespace != nil && *backendRef.Namespace != "" { namespace = string(*backendRef.Namespace) } serviceName := provider.Normalize(namespace + "-" + string(backendRef.Name)) if err := p.isReferenceGranted(kindTCPRoute, route.Namespace, group, string(kind), string(backendRef.Name), namespace); err != nil { return serviceName, nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonRefNotPermitted), Message: fmt.Sprintf("Cannot load TCPRoute BackendRef %s/%s/%s/%s: %s", group, kind, namespace, backendRef.Name, err), } } if group != groupCore || kind != kindService { name, err := p.loadTCPBackendRef(backendRef) if err != nil { return serviceName, nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonInvalidKind), Message: fmt.Sprintf("Cannot load TCPRoute BackendRef %s/%s/%s/%s: %s", group, kind, namespace, backendRef.Name, err), } } return name, nil, nil } port := ptr.Deref(backendRef.Port, gatev1.PortNumber(0)) if port == 0 { return serviceName, nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonUnsupportedProtocol), Message: fmt.Sprintf("Cannot load TCPRoute BackendRef %s/%s/%s/%s port is required", group, kind, namespace, backendRef.Name), } } portStr := strconv.FormatInt(int64(port), 10) serviceName = provider.Normalize(serviceName + "-" + portStr) lb, errCondition := p.loadTCPServers(namespace, route, backendRef) if errCondition != nil { return serviceName, nil, errCondition } return serviceName, &dynamic.TCPService{LoadBalancer: lb}, nil } func (p *Provider) loadTCPServers(namespace string, route *gatev1alpha2.TCPRoute, backendRef gatev1.BackendRef) (*dynamic.TCPServersLoadBalancer, *metav1.Condition) { backendAddresses, svcPort, err := p.getBackendAddresses(namespace, backendRef) if err != nil { return nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.GetGeneration(), LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonBackendNotFound), Message: fmt.Sprintf("Cannot load TCPRoute BackendRef %s/%s: %s", namespace, backendRef.Name, err), } } if svcPort.Protocol != corev1.ProtocolTCP { return nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.GetGeneration(), LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonUnsupportedProtocol), Message: fmt.Sprintf("Cannot load TCPRoute BackendRef %s/%s: only TCP protocol is supported", namespace, backendRef.Name), } } lb := &dynamic.TCPServersLoadBalancer{} for _, ba := range backendAddresses { lb.Servers = append(lb.Servers, dynamic.TCPServer{ Address: net.JoinHostPort(ba.IP, strconv.Itoa(int(ba.Port))), }) } return lb, nil } func (p *Provider) loadTCPBackendRef(backendRef gatev1.BackendRef) (string, error) { // Support for cross-provider references (e.g: api@internal). // This provides the same behavior as for IngressRoutes. if *backendRef.Kind == "TraefikService" && strings.Contains(string(backendRef.Name), "@") { return string(backendRef.Name), nil } return "", fmt.Errorf("unsupported BackendRef %s/%s/%s", *backendRef.Group, *backendRef.Kind, backendRef.Name) } func mergeTCPConfiguration(from, to *dynamic.Configuration) { if from == nil || from.TCP == nil || to == nil { return } if to.TCP == nil { to.TCP = from.TCP return } if to.TCP.Routers == nil { to.TCP.Routers = map[string]*dynamic.TCPRouter{} } for routerName, router := range from.TCP.Routers { to.TCP.Routers[routerName] = router } if to.TCP.Middlewares == nil { to.TCP.Middlewares = map[string]*dynamic.TCPMiddleware{} } for middlewareName, middleware := range from.TCP.Middlewares { to.TCP.Middlewares[middlewareName] = middleware } if to.TCP.Services == nil { to.TCP.Services = map[string]*dynamic.TCPService{} } for serviceName, service := range from.TCP.Services { to.TCP.Services[serviceName] = service } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/gateway/client_test.go
pkg/provider/kubernetes/gateway/client_test.go
package gateway import ( "testing" "github.com/stretchr/testify/assert" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" gatev1 "sigs.k8s.io/gateway-api/apis/v1" ) func Test_gatewayStatusEquals(t *testing.T) { testCases := []struct { desc string statusA gatev1.GatewayStatus statusB gatev1.GatewayStatus expected bool }{ { desc: "Empty", statusA: gatev1.GatewayStatus{}, statusB: gatev1.GatewayStatus{}, expected: true, }, { desc: "Same status", statusA: gatev1.GatewayStatus{ Conditions: []metav1.Condition{ { Type: "foobar", Reason: "foobar", }, }, Listeners: []gatev1.ListenerStatus{ { Name: "foo", Conditions: []metav1.Condition{ { Type: "foobar", Reason: "foobar", }, }, }, }, }, statusB: gatev1.GatewayStatus{ Conditions: []metav1.Condition{ { Type: "foobar", Reason: "foobar", }, }, Listeners: []gatev1.ListenerStatus{ { Name: "foo", Conditions: []metav1.Condition{ { Type: "foobar", Reason: "foobar", }, }, }, }, }, expected: true, }, { desc: "Listeners length not equal", statusA: gatev1.GatewayStatus{ Listeners: []gatev1.ListenerStatus{}, }, statusB: gatev1.GatewayStatus{ Listeners: []gatev1.ListenerStatus{ {}, }, }, expected: false, }, { desc: "Gateway conditions length not equal", statusA: gatev1.GatewayStatus{ Conditions: []metav1.Condition{}, }, statusB: gatev1.GatewayStatus{ Conditions: []metav1.Condition{ {}, }, }, expected: false, }, { desc: "Gateway conditions different types", statusA: gatev1.GatewayStatus{ Conditions: []metav1.Condition{ { Type: "foobar", }, }, }, statusB: gatev1.GatewayStatus{ Conditions: []metav1.Condition{ { Type: "foobir", }, }, }, expected: false, }, { desc: "Gateway conditions same types but different reason", statusA: gatev1.GatewayStatus{ Conditions: []metav1.Condition{ { Type: "foobar", }, }, }, statusB: gatev1.GatewayStatus{ Conditions: []metav1.Condition{ { Type: "foobar", Reason: "Another reason", }, }, }, expected: false, }, { desc: "Gateway listeners conditions length", statusA: gatev1.GatewayStatus{ Listeners: []gatev1.ListenerStatus{ { Name: "foo", Conditions: []metav1.Condition{}, }, }, }, statusB: gatev1.GatewayStatus{ Listeners: []gatev1.ListenerStatus{ { Name: "foo", Conditions: []metav1.Condition{ {}, }, }, }, }, expected: false, }, { desc: "Gateway listeners conditions same types but different status", statusA: gatev1.GatewayStatus{ Listeners: []gatev1.ListenerStatus{ { Conditions: []metav1.Condition{ { Type: "foobar", }, }, }, }, }, statusB: gatev1.GatewayStatus{ Listeners: []gatev1.ListenerStatus{ { Conditions: []metav1.Condition{ { Type: "foobar", Status: "Another status", }, }, }, }, }, expected: false, }, { desc: "Gateway listeners conditions same types but different message", statusA: gatev1.GatewayStatus{ Listeners: []gatev1.ListenerStatus{ { Conditions: []metav1.Condition{ { Type: "foobar", }, }, }, }, }, statusB: gatev1.GatewayStatus{ Listeners: []gatev1.ListenerStatus{ { Conditions: []metav1.Condition{ { Type: "foobar", Message: "Another status", }, }, }, }, }, expected: false, }, { desc: "Gateway listeners conditions same types/reason but different names", statusA: gatev1.GatewayStatus{ Listeners: []gatev1.ListenerStatus{ { Name: "foo", Conditions: []metav1.Condition{ { Type: "foobar", Reason: "foobar", }, }, }, }, }, statusB: gatev1.GatewayStatus{ Listeners: []gatev1.ListenerStatus{ { Name: "bar", Conditions: []metav1.Condition{ { Type: "foobar", Reason: "foobar", }, }, }, }, }, expected: false, }, { desc: "Gateway listeners with same conditions but different number of attached routes", statusA: gatev1.GatewayStatus{ Listeners: []gatev1.ListenerStatus{ { Name: "foo", AttachedRoutes: 1, Conditions: []metav1.Condition{ { Type: "foobar", Reason: "foobar", }, }, }, }, }, statusB: gatev1.GatewayStatus{ Listeners: []gatev1.ListenerStatus{ { Name: "foo", AttachedRoutes: 2, Conditions: []metav1.Condition{ { Type: "foobar", Reason: "foobar", }, }, }, }, }, expected: false, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() result := gatewayStatusEqual(test.statusA, test.statusB) assert.Equal(t, test.expected, result) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/gateway/httproute_test.go
pkg/provider/kubernetes/gateway/httproute_test.go
package gateway import ( "testing" "github.com/stretchr/testify/assert" "k8s.io/utils/ptr" gatev1 "sigs.k8s.io/gateway-api/apis/v1" ) func Test_buildHostRule(t *testing.T) { testCases := []struct { desc string hostnames []gatev1.Hostname expectedRule string expectedPriority int expectErr bool }{ { desc: "Empty (should not happen)", expectedRule: "", }, { desc: "One Host", hostnames: []gatev1.Hostname{ "Foo", }, expectedRule: "Host(`Foo`)", expectedPriority: 3, }, { desc: "Multiple Hosts", hostnames: []gatev1.Hostname{ "Foo", "Bar", "Bir", }, expectedRule: "(Host(`Foo`) || Host(`Bar`) || Host(`Bir`))", expectedPriority: 3, }, { desc: "Several Host and wildcard", hostnames: []gatev1.Hostname{ "*.bar.foo", "bar.foo", "foo.foo", }, expectedRule: "(HostRegexp(`^[a-z0-9-\\.]+\\.bar\\.foo$`) || Host(`bar.foo`) || Host(`foo.foo`))", expectedPriority: 9, }, { desc: "Host with wildcard", hostnames: []gatev1.Hostname{ "*.bar.foo", }, expectedRule: "HostRegexp(`^[a-z0-9-\\.]+\\.bar\\.foo$`)", expectedPriority: 9, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() rule, priority := buildHostRule(test.hostnames) assert.Equal(t, test.expectedRule, rule) assert.Equal(t, test.expectedPriority, priority) }) } } func Test_buildMatchRule(t *testing.T) { testCases := []struct { desc string match gatev1.HTTPRouteMatch hostnames []gatev1.Hostname expectedRule string expectedPriority int expectedError bool }{ { desc: "Empty rule and matches", expectedRule: "PathPrefix(`/`)", expectedPriority: 1, }, { desc: "One Host rule without match", hostnames: []gatev1.Hostname{"foo.com"}, expectedRule: "Host(`foo.com`) && PathPrefix(`/`)", expectedPriority: 8, }, { desc: "One HTTPRouteMatch with nil HTTPHeaderMatch", match: gatev1.HTTPRouteMatch{ Path: ptr.To(gatev1.HTTPPathMatch{ Type: ptr.To(gatev1.PathMatchPathPrefix), Value: ptr.To("/"), }), Headers: nil, }, expectedRule: "PathPrefix(`/`)", expectedPriority: 1, }, { desc: "One HTTPRouteMatch with nil HTTPHeaderMatch Type", match: gatev1.HTTPRouteMatch{ Path: ptr.To(gatev1.HTTPPathMatch{ Type: ptr.To(gatev1.PathMatchPathPrefix), Value: ptr.To("/"), }), Headers: []gatev1.HTTPHeaderMatch{ {Name: "foo", Value: "bar"}, }, }, expectedRule: "PathPrefix(`/`) && Header(`foo`,`bar`)", expectedPriority: 101, }, { desc: "One HTTPRouteMatch with nil HTTPPathMatch", match: gatev1.HTTPRouteMatch{Path: nil}, expectedRule: "PathPrefix(`/`)", expectedPriority: 1, }, { desc: "One HTTPRouteMatch with nil HTTPPathMatch Type", match: gatev1.HTTPRouteMatch{ Path: &gatev1.HTTPPathMatch{ Type: nil, Value: ptr.To("/foo/"), }, }, expectedRule: "(Path(`/foo`) || PathPrefix(`/foo/`))", expectedPriority: 10500, }, { desc: "One HTTPRouteMatch with nil HTTPPathMatch Values", match: gatev1.HTTPRouteMatch{ Path: &gatev1.HTTPPathMatch{ Type: ptr.To(gatev1.PathMatchExact), Value: nil, }, }, expectedRule: "Path(`/`)", expectedPriority: 100000, }, { desc: "One Path", match: gatev1.HTTPRouteMatch{ Path: &gatev1.HTTPPathMatch{ Type: ptr.To(gatev1.PathMatchExact), Value: ptr.To("/foo/"), }, }, expectedRule: "Path(`/foo/`)", expectedPriority: 100000, }, { desc: "Path && Header", match: gatev1.HTTPRouteMatch{ Path: &gatev1.HTTPPathMatch{ Type: ptr.To(gatev1.PathMatchExact), Value: ptr.To("/foo/"), }, Headers: []gatev1.HTTPHeaderMatch{ { Type: ptr.To(gatev1.HeaderMatchExact), Name: "my-header", Value: "foo", }, }, }, expectedRule: "Path(`/foo/`) && Header(`my-header`,`foo`)", expectedPriority: 100100, }, { desc: "Host && Path && Header", hostnames: []gatev1.Hostname{"foo.com"}, match: gatev1.HTTPRouteMatch{ Path: &gatev1.HTTPPathMatch{ Type: ptr.To(gatev1.PathMatchExact), Value: ptr.To("/foo/"), }, Headers: []gatev1.HTTPHeaderMatch{ { Type: ptr.To(gatev1.HeaderMatchExact), Name: "my-header", Value: "foo", }, }, }, expectedRule: "Host(`foo.com`) && Path(`/foo/`) && Header(`my-header`,`foo`)", expectedPriority: 100107, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() rule, priority := buildMatchRule(test.hostnames, test.match) assert.Equal(t, test.expectedRule, rule) assert.Equal(t, test.expectedPriority, priority) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/gateway/httproute.go
pkg/provider/kubernetes/gateway/httproute.go
package gateway import ( "context" "errors" "fmt" "net" "net/http" "regexp" "slices" "strconv" "strings" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/provider" "github.com/traefik/traefik/v3/pkg/types" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ktypes "k8s.io/apimachinery/pkg/types" "k8s.io/utils/ptr" gatev1 "sigs.k8s.io/gateway-api/apis/v1" ) func (p *Provider) loadHTTPRoutes(ctx context.Context, gatewayListeners []gatewayListener, conf *dynamic.Configuration) { routes, err := p.client.ListHTTPRoutes() if err != nil { log.Ctx(ctx).Error().Err(err).Msg("Unable to list HTTPRoutes") return } for _, route := range routes { logger := log.Ctx(ctx).With(). Str("http_route", route.Name). Str("namespace", route.Namespace). Logger() routeListeners := matchingGatewayListeners(gatewayListeners, route.Namespace, route.Spec.ParentRefs) if len(routeListeners) == 0 { continue } var parentStatuses []gatev1.RouteParentStatus for _, parentRef := range route.Spec.ParentRefs { parentStatus := &gatev1.RouteParentStatus{ ParentRef: parentRef, ControllerName: controllerName, Conditions: []metav1.Condition{ { Type: string(gatev1.RouteConditionAccepted), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonNoMatchingParent), }, }, } for _, listener := range routeListeners { accepted := matchListener(listener, parentRef) if accepted && !allowRoute(listener, route.Namespace, kindHTTPRoute) { parentStatus.Conditions = updateRouteConditionAccepted(parentStatus.Conditions, string(gatev1.RouteReasonNotAllowedByListeners)) accepted = false } hostnames, ok := findMatchingHostnames(listener.Hostname, route.Spec.Hostnames) if accepted && !ok { parentStatus.Conditions = updateRouteConditionAccepted(parentStatus.Conditions, string(gatev1.RouteReasonNoMatchingListenerHostname)) accepted = false } if accepted { // Gateway listener should have AttachedRoutes set even when Gateway has unresolved refs. listener.Status.AttachedRoutes++ // Only consider the route attached if the listener is in an "attached" state. if listener.Attached { parentStatus.Conditions = updateRouteConditionAccepted(parentStatus.Conditions, string(gatev1.RouteReasonAccepted)) } } routeConf, resolveRefCondition := p.loadHTTPRoute(logger.WithContext(ctx), listener, route, hostnames) if accepted && listener.Attached { mergeHTTPConfiguration(routeConf, conf) } parentStatus.Conditions = upsertRouteConditionResolvedRefs(parentStatus.Conditions, resolveRefCondition) } parentStatuses = append(parentStatuses, *parentStatus) } status := gatev1.HTTPRouteStatus{ RouteStatus: gatev1.RouteStatus{ Parents: parentStatuses, }, } if err := p.client.UpdateHTTPRouteStatus(ctx, ktypes.NamespacedName{Namespace: route.Namespace, Name: route.Name}, status); err != nil { logger.Warn(). Err(err). Msg("Unable to update HTTPRoute status") } } } func (p *Provider) loadHTTPRoute(ctx context.Context, listener gatewayListener, route *gatev1.HTTPRoute, hostnames []gatev1.Hostname) (*dynamic.Configuration, metav1.Condition) { conf := &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: make(map[string]*dynamic.Router), Middlewares: make(map[string]*dynamic.Middleware), Services: make(map[string]*dynamic.Service), ServersTransports: make(map[string]*dynamic.ServersTransport), }, } condition := metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionTrue, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteConditionResolvedRefs), } for ri, routeRule := range route.Spec.Rules { // Adding the gateway desc and the entryPoint desc prevents overlapping of routers build from the same routes. routeKey := provider.Normalize(fmt.Sprintf("%s-%s-%s-gw-%s-%s-ep-%s-%d", strings.ToLower(kindHTTPRoute), route.Namespace, route.Name, listener.GWNamespace, listener.GWName, listener.EPName, ri)) for _, match := range routeRule.Matches { rule, priority := buildMatchRule(hostnames, match) router := dynamic.Router{ // "default" stands for the default rule syntax in Traefik v3, i.e. the v3 syntax. RuleSyntax: "default", Rule: rule, Priority: priority + len(route.Spec.Rules) - ri, EntryPoints: []string{listener.EPName}, } if listener.Protocol == gatev1.HTTPSProtocolType { router.TLS = &dynamic.RouterTLSConfig{} } var err error routerName := makeRouterName(rule, routeKey) router.Middlewares, err = p.loadMiddlewares(conf, route.Namespace, routerName, routeRule.Filters, match.Path) switch { case err != nil: log.Ctx(ctx).Error().Err(err).Msg("Unable to load HTTPRoute filters") errWrrName := routerName + "-err-wrr" conf.HTTP.Services[errWrrName] = &dynamic.Service{ Weighted: &dynamic.WeightedRoundRobin{ Services: []dynamic.WRRService{ { Name: "invalid-httproute-filter", Status: ptr.To(500), Weight: ptr.To(1), }, }, }, } router.Service = errWrrName case len(routeRule.BackendRefs) == 1 && isInternalService(routeRule.BackendRefs[0].BackendRef): router.Service = string(routeRule.BackendRefs[0].Name) default: var serviceCondition *metav1.Condition router.Service, serviceCondition = p.loadWRRService(ctx, listener, conf, routerName, routeRule, route) if serviceCondition != nil { condition = *serviceCondition } } p.applyRouterTransform(ctx, &router, route) conf.HTTP.Routers[routerName] = &router } } return conf, condition } func (p *Provider) loadWRRService(ctx context.Context, listener gatewayListener, conf *dynamic.Configuration, routeKey string, routeRule gatev1.HTTPRouteRule, route *gatev1.HTTPRoute) (string, *metav1.Condition) { name := routeKey + "-wrr" if _, ok := conf.HTTP.Services[name]; ok { return name, nil } var wrr dynamic.WeightedRoundRobin var condition *metav1.Condition for _, backendRef := range routeRule.BackendRefs { svcName, errCondition := p.loadService(ctx, listener, conf, route, backendRef) weight := ptr.To(int(ptr.Deref(backendRef.Weight, 1))) if errCondition != nil { log.Ctx(ctx).Error(). Msgf("Unable to load HTTPRoute backend: %s", errCondition.Message) condition = errCondition wrr.Services = append(wrr.Services, dynamic.WRRService{ Name: svcName, Status: ptr.To(500), Weight: weight, }) continue } wrr.Services = append(wrr.Services, dynamic.WRRService{ Name: svcName, Weight: weight, }) } conf.HTTP.Services[name] = &dynamic.Service{Weighted: &wrr} return name, condition } // loadService returns a dynamic.Service config corresponding to the given gatev1.HTTPBackendRef. // Note that the returned dynamic.Service config can be nil (for cross-provider, internal services, and backendFunc). func (p *Provider) loadService(ctx context.Context, listener gatewayListener, conf *dynamic.Configuration, route *gatev1.HTTPRoute, backendRef gatev1.HTTPBackendRef) (string, *metav1.Condition) { kind := ptr.Deref(backendRef.Kind, kindService) group := groupCore if backendRef.Group != nil && *backendRef.Group != "" { group = string(*backendRef.Group) } namespace := route.Namespace if backendRef.Namespace != nil && *backendRef.Namespace != "" { namespace = string(*backendRef.Namespace) } serviceName := provider.Normalize(namespace + "-" + string(backendRef.Name) + "-http") if err := p.isReferenceGranted(kindHTTPRoute, route.Namespace, group, string(kind), string(backendRef.Name), namespace); err != nil { return serviceName, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonRefNotPermitted), Message: fmt.Sprintf("Cannot load HTTPBackendRef %s/%s/%s/%s: %s", group, kind, namespace, backendRef.Name, err), } } if group != groupCore || kind != kindService { name, service, err := p.loadHTTPBackendRef(namespace, backendRef) if err != nil { return serviceName, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonInvalidKind), Message: fmt.Sprintf("Cannot load HTTPBackendRef %s/%s/%s/%s: %s", group, kind, namespace, backendRef.Name, err), } } if service != nil { conf.HTTP.Services[name] = service } return name, nil } port := ptr.Deref(backendRef.Port, gatev1.PortNumber(0)) if port == 0 { return serviceName, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonUnsupportedProtocol), Message: fmt.Sprintf("Cannot load HTTPBackendRef %s/%s/%s/%s: port is required", group, kind, namespace, backendRef.Name), } } portStr := strconv.FormatInt(int64(port), 10) serviceName = provider.Normalize(serviceName + "-" + portStr) lb, st, errCondition := p.loadHTTPServers(ctx, namespace, route, backendRef, listener) if errCondition != nil { return serviceName, errCondition } if st != nil { lb.ServersTransport = serviceName conf.HTTP.ServersTransports[serviceName] = st } conf.HTTP.Services[serviceName] = &dynamic.Service{LoadBalancer: lb} return serviceName, nil } func (p *Provider) loadHTTPBackendRef(namespace string, backendRef gatev1.HTTPBackendRef) (string, *dynamic.Service, error) { // Support for cross-provider references (e.g: api@internal). // This provides the same behavior as for IngressRoutes. if *backendRef.Kind == "TraefikService" && strings.Contains(string(backendRef.Name), "@") { return string(backendRef.Name), nil, nil } backendFunc, ok := p.groupKindBackendFuncs[string(*backendRef.Group)][string(*backendRef.Kind)] if !ok { return "", nil, fmt.Errorf("unsupported HTTPBackendRef %s/%s/%s", *backendRef.Group, *backendRef.Kind, backendRef.Name) } if backendFunc == nil { return "", nil, fmt.Errorf("undefined backendFunc for HTTPBackendRef %s/%s/%s", *backendRef.Group, *backendRef.Kind, backendRef.Name) } return backendFunc(string(backendRef.Name), namespace) } func (p *Provider) loadMiddlewares(conf *dynamic.Configuration, namespace, routerName string, filters []gatev1.HTTPRouteFilter, pathMatch *gatev1.HTTPPathMatch) ([]string, error) { type namedMiddleware struct { Name string Config *dynamic.Middleware } pm := ptr.Deref(pathMatch, gatev1.HTTPPathMatch{ Type: ptr.To(gatev1.PathMatchPathPrefix), Value: ptr.To("/"), }) var middlewares []namedMiddleware for i, filter := range filters { name := fmt.Sprintf("%s-%s-%d", routerName, strings.ToLower(string(filter.Type)), i) switch filter.Type { case gatev1.HTTPRouteFilterRequestRedirect: middlewares = append(middlewares, namedMiddleware{ name, createRequestRedirect(filter.RequestRedirect, pm), }) case gatev1.HTTPRouteFilterRequestHeaderModifier: middlewares = append(middlewares, namedMiddleware{ name, createRequestHeaderModifier(filter.RequestHeaderModifier), }) case gatev1.HTTPRouteFilterResponseHeaderModifier: middlewares = append(middlewares, namedMiddleware{ name, createResponseHeaderModifier(filter.ResponseHeaderModifier), }) case gatev1.HTTPRouteFilterExtensionRef: name, middleware, err := p.loadHTTPRouteFilterExtensionRef(namespace, filter.ExtensionRef) if err != nil { return nil, fmt.Errorf("loading ExtensionRef filter %s: %w", filter.Type, err) } middlewares = append(middlewares, namedMiddleware{ name, middleware, }) case gatev1.HTTPRouteFilterURLRewrite: middleware, err := createURLRewrite(filter.URLRewrite, pm) if err != nil { return nil, fmt.Errorf("invalid filter %s: %w", filter.Type, err) } middlewares = append(middlewares, namedMiddleware{ name, middleware, }) default: // As per the spec: https://gateway-api.sigs.k8s.io/api-types/httproute/#filters-optional // In all cases where incompatible or unsupported filters are // specified, implementations MUST add a warning condition to // status. return nil, fmt.Errorf("unsupported filter %s", filter.Type) } } var middlewareNames []string for _, m := range middlewares { if m.Config != nil { conf.HTTP.Middlewares[m.Name] = m.Config } middlewareNames = append(middlewareNames, m.Name) } return middlewareNames, nil } func (p *Provider) loadHTTPRouteFilterExtensionRef(namespace string, extensionRef *gatev1.LocalObjectReference) (string, *dynamic.Middleware, error) { if extensionRef == nil { return "", nil, errors.New("filter extension ref undefined") } filterFunc, ok := p.groupKindFilterFuncs[string(extensionRef.Group)][string(extensionRef.Kind)] if !ok { return "", nil, fmt.Errorf("unsupported filter extension ref %s/%s/%s", extensionRef.Group, extensionRef.Kind, extensionRef.Name) } if filterFunc == nil { return "", nil, fmt.Errorf("undefined filterFunc for filter extension ref %s/%s/%s", extensionRef.Group, extensionRef.Kind, extensionRef.Name) } return filterFunc(string(extensionRef.Name), namespace) } func (p *Provider) loadHTTPServers(ctx context.Context, namespace string, route *gatev1.HTTPRoute, backendRef gatev1.HTTPBackendRef, listener gatewayListener) (*dynamic.ServersLoadBalancer, *dynamic.ServersTransport, *metav1.Condition) { backendAddresses, svcPort, err := p.getBackendAddresses(namespace, backendRef.BackendRef) if err != nil { return nil, nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonBackendNotFound), Message: fmt.Sprintf("Cannot load HTTPBackendRef %s/%s: %s", namespace, backendRef.Name, err), } } backendTLSPolicies, err := p.client.ListBackendTLSPoliciesForService(namespace, string(backendRef.Name)) if err != nil { return nil, nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonRefNotPermitted), Message: fmt.Sprintf("Cannot list BackendTLSPolicies for Service %s/%s: %s", namespace, string(backendRef.Name), err), } } // Sort BackendTLSPolicies by creation timestamp, then by name to match the BackendTLSPolicy requirements. slices.SortStableFunc(backendTLSPolicies, func(a, b *gatev1.BackendTLSPolicy) int { cmpTime := a.CreationTimestamp.Time.Compare(b.CreationTimestamp.Time) if cmpTime == 0 { return strings.Compare(a.Name, b.Name) } return cmpTime }) var serversTransport *dynamic.ServersTransport for _, policy := range backendTLSPolicies { for _, targetRef := range policy.Spec.TargetRefs { if targetRef.SectionName != nil && svcPort.Name != string(*targetRef.SectionName) { continue } policyAncestorStatus := gatev1.PolicyAncestorStatus{ AncestorRef: gatev1.ParentReference{ Group: ptr.To(gatev1.Group(groupGateway)), Kind: ptr.To(gatev1.Kind(kindGateway)), Namespace: ptr.To(gatev1.Namespace(namespace)), Name: gatev1.ObjectName(listener.GWName), SectionName: ptr.To(gatev1.SectionName(listener.Name)), }, ControllerName: controllerName, } // Multiple BackendTLSPolicies can match the same service port, meaning that there is a conflict. if serversTransport != nil { policyAncestorStatus.Conditions = append(policyAncestorStatus.Conditions, metav1.Condition{ Type: string(gatev1.BackendTLSPolicyConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: policy.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.BackendTLSPolicyReasonResolvedRefs), }, metav1.Condition{ Type: string(gatev1.PolicyConditionAccepted), Status: metav1.ConditionFalse, ObservedGeneration: policy.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.PolicyReasonConflicted), }, ) status := gatev1.PolicyStatus{ Ancestors: []gatev1.PolicyAncestorStatus{policyAncestorStatus}, } if err := p.client.UpdateBackendTLSPolicyStatus(ctx, ktypes.NamespacedName{Namespace: policy.Namespace, Name: policy.Name}, status); err != nil { log.Ctx(ctx).Warn().Err(err).Msg("Unable to update conflicting BackendTLSPolicy status") } continue } var resolvedRefCondition metav1.Condition serversTransport, resolvedRefCondition = p.loadServersTransport(namespace, policy) policyAncestorStatus.Conditions = append(policyAncestorStatus.Conditions, resolvedRefCondition) if resolvedRefCondition.Status == metav1.ConditionFalse { policyAncestorStatus.Conditions = append(policyAncestorStatus.Conditions, metav1.Condition{ Type: string(gatev1.PolicyConditionAccepted), Status: metav1.ConditionFalse, ObservedGeneration: policy.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.BackendTLSPolicyReasonNoValidCACertificate), }) } else { policyAncestorStatus.Conditions = append(policyAncestorStatus.Conditions, metav1.Condition{ Type: string(gatev1.PolicyConditionAccepted), Status: metav1.ConditionTrue, ObservedGeneration: policy.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.PolicyReasonAccepted), }) } status := gatev1.PolicyStatus{ Ancestors: []gatev1.PolicyAncestorStatus{policyAncestorStatus}, } if err := p.client.UpdateBackendTLSPolicyStatus(ctx, ktypes.NamespacedName{Namespace: policy.Namespace, Name: policy.Name}, status); err != nil { log.Ctx(ctx).Warn().Err(err).Msg("Unable to update BackendTLSPolicy status") } // When something wen wrong during the loading of a ServersTransport, // we stop here and return a route condition error. if resolvedRefCondition.Status == metav1.ConditionFalse { return nil, nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonRefNotPermitted), Message: fmt.Sprintf("Cannot apply BackendTLSPolicy for Service %s/%s: %s", namespace, string(backendRef.Name), resolvedRefCondition.Message), } } } } lb := &dynamic.ServersLoadBalancer{} lb.SetDefaults() // If a ServersTransport is set, it means a BackendTLSPolicy matched the service port, and we can safely assume the protocol is HTTPS. // When no ServersTransport is set, we need to determine the protocol based on the service port. protocol := "https" if serversTransport == nil { protocol, err = getHTTPServiceProtocol(svcPort) if err != nil { return nil, nil, &metav1.Condition{ Type: string(gatev1.RouteConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: route.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.RouteReasonUnsupportedProtocol), Message: fmt.Sprintf("Cannot load HTTPBackendRef %s/%s: %s", namespace, backendRef.Name, err), } } } for _, ba := range backendAddresses { lb.Servers = append(lb.Servers, dynamic.Server{ URL: fmt.Sprintf("%s://%s", protocol, net.JoinHostPort(ba.IP, strconv.Itoa(int(ba.Port)))), }) } return lb, serversTransport, nil } func (p *Provider) loadServersTransport(namespace string, policy *gatev1.BackendTLSPolicy) (*dynamic.ServersTransport, metav1.Condition) { st := &dynamic.ServersTransport{ ServerName: string(policy.Spec.Validation.Hostname), } if policy.Spec.Validation.WellKnownCACertificates != nil { return st, metav1.Condition{ Type: string(gatev1.BackendTLSPolicyConditionResolvedRefs), Status: metav1.ConditionTrue, ObservedGeneration: policy.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.BackendTLSPolicyReasonResolvedRefs), } } for _, caCertRef := range policy.Spec.Validation.CACertificateRefs { if (caCertRef.Group != "" && caCertRef.Group != groupCore) || caCertRef.Kind != "ConfigMap" { return nil, metav1.Condition{ Type: string(gatev1.BackendTLSPolicyConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: policy.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.BackendTLSPolicyReasonInvalidKind), Message: "Only ConfigMaps are supported", } } configMap, err := p.client.GetConfigMap(namespace, string(caCertRef.Name)) if err != nil { return nil, metav1.Condition{ Type: string(gatev1.BackendTLSPolicyConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: policy.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.BackendTLSPolicyReasonInvalidCACertificateRef), Message: fmt.Sprintf("getting configmap %s/%s: %s", namespace, string(caCertRef.Name), err), } } caCRT, ok := configMap.Data["ca.crt"] if !ok { return nil, metav1.Condition{ Type: string(gatev1.BackendTLSPolicyConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: policy.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.BackendTLSPolicyReasonInvalidCACertificateRef), Message: fmt.Sprintf("configmap %s/%s does not have a ca.crt", namespace, string(caCertRef.Name)), } } st.RootCAs = append(st.RootCAs, types.FileOrContent(caCRT)) } return st, metav1.Condition{ Type: string(gatev1.BackendTLSPolicyConditionResolvedRefs), Status: metav1.ConditionTrue, ObservedGeneration: policy.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.BackendTLSPolicyReasonResolvedRefs), } } func buildHostRule(hostnames []gatev1.Hostname) (string, int) { var rules []string var priority int for _, hostname := range hostnames { host := string(hostname) if priority < len(host) { priority = len(host) } wildcard := strings.Count(host, "*") if wildcard == 0 { rules = append(rules, fmt.Sprintf("Host(`%s`)", host)) continue } host = strings.Replace(regexp.QuoteMeta(host), `\*\.`, `[a-z0-9-\.]+\.`, 1) rules = append(rules, fmt.Sprintf("HostRegexp(`^%s$`)", host)) } switch len(rules) { case 0: return "", 0 case 1: return rules[0], priority default: return fmt.Sprintf("(%s)", strings.Join(rules, " || ")), priority } } // buildMatchRule builds the route rule and computes its priority. // The current priority computing is rather naive but aims to fulfill Conformance tests suite requirement. // The priority is computed to match the following precedence order: // // * "Exact" path match (+100000). // * "Prefix" path match with largest number of characters (+10000 + nb_characters*100). // * Method match (+1000). // * Largest number of header matches (+100 each). // * Largest number of query param matches (+10 each). // // In case of multiple matches for a route, the maximum priority among all matches is retain. func buildMatchRule(hostnames []gatev1.Hostname, match gatev1.HTTPRouteMatch) (string, int) { path := ptr.Deref(match.Path, gatev1.HTTPPathMatch{ Type: ptr.To(gatev1.PathMatchPathPrefix), Value: ptr.To("/"), }) var priority int var matchRules []string pathRule, pathPriority := buildPathRule(path) matchRules = append(matchRules, pathRule) priority += pathPriority if match.Method != nil { matchRules = append(matchRules, fmt.Sprintf("Method(`%s`)", *match.Method)) priority += 1000 } headerRules, headersPriority := buildHeaderRules(match.Headers) matchRules = append(matchRules, headerRules...) priority += headersPriority queryParamRules, queryParamsPriority := buildQueryParamRules(match.QueryParams) matchRules = append(matchRules, queryParamRules...) priority += queryParamsPriority matchRulesStr := strings.Join(matchRules, " && ") hostRule, hostPriority := buildHostRule(hostnames) if hostRule == "" { return matchRulesStr, priority } // A route with a host should match over the same route with no host. priority += hostPriority return hostRule + " && " + matchRulesStr, priority } func buildPathRule(pathMatch gatev1.HTTPPathMatch) (string, int) { pathType := ptr.Deref(pathMatch.Type, gatev1.PathMatchPathPrefix) pathValue := ptr.Deref(pathMatch.Value, "/") switch pathType { case gatev1.PathMatchExact: return fmt.Sprintf("Path(`%s`)", pathValue), 100000 case gatev1.PathMatchPathPrefix: // PathPrefix(`/`) rule is a catch-all, // here we ensure it would be evaluated last. if pathValue == "/" { return "PathPrefix(`/`)", 1 } pv := strings.TrimSuffix(pathValue, "/") return fmt.Sprintf("(Path(`%[1]s`) || PathPrefix(`%[1]s/`))", pv), 10000 + len(pathValue)*100 case gatev1.PathMatchRegularExpression: return fmt.Sprintf("PathRegexp(`%s`)", pathValue), 10000 + len(pathValue)*100 default: return "PathPrefix(`/`)", 1 } } func buildHeaderRules(headers []gatev1.HTTPHeaderMatch) ([]string, int) { var ( rules []string priority int ) for _, header := range headers { typ := ptr.Deref(header.Type, gatev1.HeaderMatchExact) switch typ { case gatev1.HeaderMatchExact: rules = append(rules, fmt.Sprintf("Header(`%s`,`%s`)", header.Name, header.Value)) case gatev1.HeaderMatchRegularExpression: rules = append(rules, fmt.Sprintf("HeaderRegexp(`%s`,`%s`)", header.Name, header.Value)) } priority += 100 } return rules, priority } func buildQueryParamRules(queryParams []gatev1.HTTPQueryParamMatch) ([]string, int) { var ( rules []string priority int ) for _, qp := range queryParams { typ := ptr.Deref(qp.Type, gatev1.QueryParamMatchExact) switch typ { case gatev1.QueryParamMatchExact: rules = append(rules, fmt.Sprintf("Query(`%s`,`%s`)", qp.Name, qp.Value)) case gatev1.QueryParamMatchRegularExpression: rules = append(rules, fmt.Sprintf("QueryRegexp(`%s`,`%s`)", qp.Name, qp.Value)) } priority += 10 } return rules, priority } // createRequestHeaderModifier does not enforce/check the configuration, // as the spec indicates that either the webhook or CEL (since v1.0 GA Release) should enforce that. func createRequestHeaderModifier(filter *gatev1.HTTPHeaderFilter) *dynamic.Middleware { sets := map[string]string{} for _, header := range filter.Set { sets[string(header.Name)] = header.Value } adds := map[string]string{} for _, header := range filter.Add { adds[string(header.Name)] = header.Value } return &dynamic.Middleware{ RequestHeaderModifier: &dynamic.HeaderModifier{ Set: sets, Add: adds, Remove: filter.Remove, }, } } // createResponseHeaderModifier does not enforce/check the configuration, // as the spec indicates that either the webhook or CEL (since v1.0 GA Release) should enforce that. func createResponseHeaderModifier(filter *gatev1.HTTPHeaderFilter) *dynamic.Middleware { sets := map[string]string{} for _, header := range filter.Set { sets[string(header.Name)] = header.Value } adds := map[string]string{} for _, header := range filter.Add { adds[string(header.Name)] = header.Value } return &dynamic.Middleware{ ResponseHeaderModifier: &dynamic.HeaderModifier{ Set: sets, Add: adds, Remove: filter.Remove, }, } } func createRequestRedirect(filter *gatev1.HTTPRequestRedirectFilter, pathMatch gatev1.HTTPPathMatch) *dynamic.Middleware { var hostname *string if filter.Hostname != nil { hostname = ptr.To(string(*filter.Hostname)) } var port *string filterScheme := ptr.Deref(filter.Scheme, "") if filterScheme == schemeHTTP || filterScheme == schemeHTTPS { port = ptr.To("") } if filter.Port != nil { port = ptr.To(strconv.Itoa(int(*filter.Port))) } var path *string var pathPrefix *string if filter.Path != nil { switch filter.Path.Type { case gatev1.FullPathHTTPPathModifier: path = filter.Path.ReplaceFullPath case gatev1.PrefixMatchHTTPPathModifier: path = filter.Path.ReplacePrefixMatch pathPrefix = pathMatch.Value } } return &dynamic.Middleware{ RequestRedirect: &dynamic.RequestRedirect{ Scheme: filter.Scheme, Hostname: hostname, Port: port, Path: path, PathPrefix: pathPrefix, StatusCode: ptr.Deref(filter.StatusCode, http.StatusFound), }, } } func createURLRewrite(filter *gatev1.HTTPURLRewriteFilter, pathMatch gatev1.HTTPPathMatch) (*dynamic.Middleware, error) { if filter.Path == nil && filter.Hostname == nil { return nil, errors.New("empty configuration") } var host *string if filter.Hostname != nil { host = ptr.To(string(*filter.Hostname)) } var path *string var pathPrefix *string if filter.Path != nil { switch filter.Path.Type { case gatev1.FullPathHTTPPathModifier: path = filter.Path.ReplaceFullPath case gatev1.PrefixMatchHTTPPathModifier: path = filter.Path.ReplacePrefixMatch pathPrefix = pathMatch.Value } } return &dynamic.Middleware{ URLRewrite: &dynamic.URLRewrite{ Hostname: host, Path: path, PathPrefix: pathPrefix, }, }, nil } func getHTTPServiceProtocol(portSpec corev1.ServicePort) (string, error) { if portSpec.Protocol != corev1.ProtocolTCP { return "", errors.New("only TCP protocol is supported") } if portSpec.AppProtocol == nil { protocol := schemeHTTP if portSpec.Port == 443 || strings.HasPrefix(portSpec.Name, schemeHTTPS) { protocol = schemeHTTPS } return protocol, nil } switch ap := strings.ToLower(*portSpec.AppProtocol); ap { case appProtocolH2C: return schemeH2C, nil case appProtocolHTTP, appProtocolWS: return schemeHTTP, nil case appProtocolHTTPS, appProtocolWSS: return schemeHTTPS, nil default: return "", fmt.Errorf("unsupported application protocol %s", ap) } } func mergeHTTPConfiguration(from, to *dynamic.Configuration) { if from == nil || from.HTTP == nil || to == nil { return } if to.HTTP == nil { to.HTTP = from.HTTP return } if to.HTTP.Routers == nil { to.HTTP.Routers = map[string]*dynamic.Router{} } for routerName, router := range from.HTTP.Routers { to.HTTP.Routers[routerName] = router } if to.HTTP.Middlewares == nil { to.HTTP.Middlewares = map[string]*dynamic.Middleware{} } for middlewareName, middleware := range from.HTTP.Middlewares { to.HTTP.Middlewares[middlewareName] = middleware } if to.HTTP.Services == nil { to.HTTP.Services = map[string]*dynamic.Service{} } for serviceName, service := range from.HTTP.Services { to.HTTP.Services[serviceName] = service } if to.HTTP.ServersTransports == nil { to.HTTP.ServersTransports = map[string]*dynamic.ServersTransport{} } for name, serversTransport := range from.HTTP.ServersTransports { to.HTTP.ServersTransports[name] = serversTransport } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/gateway/kubernetes_test.go
pkg/provider/kubernetes/gateway/kubernetes_test.go
package gateway import ( "errors" "net/http" "os" "path/filepath" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/provider" traefikv1alpha1 "github.com/traefik/traefik/v3/pkg/provider/kubernetes/crd/traefikio/v1alpha1" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/k8s" "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" "google.golang.org/grpc/codes" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" kubefake "k8s.io/client-go/kubernetes/fake" kscheme "k8s.io/client-go/kubernetes/scheme" "k8s.io/utils/ptr" gatev1 "sigs.k8s.io/gateway-api/apis/v1" gatev1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" gatev1alpha3 "sigs.k8s.io/gateway-api/apis/v1alpha3" gatev1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" gatefake "sigs.k8s.io/gateway-api/pkg/client/clientset/versioned/fake" ) var _ provider.Provider = (*Provider)(nil) func init() { // required by k8s.MustParseYaml if err := gatev1.AddToScheme(kscheme.Scheme); err != nil { panic(err) } if err := gatev1beta1.AddToScheme(kscheme.Scheme); err != nil { panic(err) } if err := gatev1alpha2.AddToScheme(kscheme.Scheme); err != nil { panic(err) } if err := gatev1alpha3.AddToScheme(kscheme.Scheme); err != nil { panic(err) } } const ( listenerCert string = `-----BEGIN CERTIFICATE----- MIIBqDCCAU6gAwIBAgIUYOsr0QgHOBq4kYRCL5+TDdVt6bQwCgYIKoZIzj0EAwIw FjEUMBIGA1UEAwwLZXhhbXBsZS5jb20wHhcNMjUxMDEwMDcxNzMwWhcNMzUxMDA4 MDcxNzMwWjAWMRQwEgYDVQQDDAtleGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqG SM49AwEHA0IABDOriw3ZQ7wIhWrbPS6JFQT3bToNCF00vSV5fab6TbXyL8tlsGre TRIF2EwgsteMOkxGKKSlDvuaDwq8p/qV+0ujejB4MB0GA1UdDgQWBBRMEkuexXQh UtDgRg1KBv72CDq+EzAfBgNVHSMEGDAWgBRMEkuexXQhUtDgRg1KBv72CDq+EzAP BgNVHRMBAf8EBTADAQH/MCUGA1UdEQQeMByCC2V4YW1wbGUuY29tgg0qLmV4YW1w bGUuY29tMAoGCCqGSM49BAMCA0gAMEUCIQDs87Vk0swA6HgOJjROye1mxD83qcGy peFgoxV93Dy+cwIgV0MMEJJbVsTyZK3EQ++Xc5rEL78nrJ+YIEV+rCUWj5U= -----END CERTIFICATE-----` listenerKey string = `-----BEGIN PRIVATE KEY----- MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgnwgL5DY4UB14sM6f DikQdtqh2QW1ArfF4fc1UFzifdGhRANCAAQzq4sN2UO8CIVq2z0uiRUE9206DQhd NL0leX2m+k218i/LZbBq3k0SBdhMILLXjDpMRiikpQ77mg8KvKf6lftL -----END PRIVATE KEY-----` ) func TestGatewayClassLabelSelector(t *testing.T) { k8sObjects, gwObjects := readResources(t, []string{"gatewayclass_labelselector.yaml"}) kubeClient := kubefake.NewSimpleClientset(k8sObjects...) gwClient := newGatewaySimpleClientSet(t, gwObjects...) client := newClientImpl(kubeClient, gwClient) // This is initialized by the Provider init method but this cannot be called in a unit test. client.labelSelector = "name=traefik-internal" eventCh, err := client.WatchAll(nil, make(chan struct{})) require.NoError(t, err) if len(k8sObjects) > 0 || len(gwObjects) > 0 { // just wait for the first event <-eventCh } p := Provider{ EntryPoints: map[string]Entrypoint{"http": {Address: ":9080"}}, StatusAddress: &StatusAddress{IP: "1.2.3.4"}, client: client, } _ = p.loadConfigurationFromGateways(t.Context()) gw, err := gwClient.GatewayV1().Gateways("default").Get(t.Context(), "traefik-external", metav1.GetOptions{}) require.NoError(t, err) assert.Empty(t, gw.Status.Addresses) gw, err = gwClient.GatewayV1().Gateways("default").Get(t.Context(), "traefik-internal", metav1.GetOptions{}) require.NoError(t, err) require.Len(t, gw.Status.Addresses, 1) require.NotNil(t, gw.Status.Addresses[0].Type) assert.Equal(t, gatev1.IPAddressType, *gw.Status.Addresses[0].Type) assert.Equal(t, "1.2.3.4", gw.Status.Addresses[0].Value) } func TestLoadHTTPRoutes(t *testing.T) { testCases := []struct { desc string ingressClass string paths []string expected *dynamic.Configuration entryPoints map[string]Entrypoint experimentalChannel bool nativeLB bool }{ { desc: "Empty", expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Empty because missing entry point", paths: []string{"services.yml", "httproute/simple.yml"}, entryPoints: map[string]Entrypoint{"web": { Address: ":443", }}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Empty because no http route defined", paths: []string{"services.yml", "httproute/without_httproute.yml"}, entryPoints: map[string]Entrypoint{"web": { Address: ":80", }}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Empty caused by missing GatewayClass", entryPoints: map[string]Entrypoint{"web": { Address: ":80", }}, paths: []string{"services.yml", "httproute/without_gatewayclass.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Empty caused by unknown GatewayClass controller desc", entryPoints: map[string]Entrypoint{"web": { Address: ":80", }}, paths: []string{"services.yml", "httproute/gatewayclass_with_unknown_controller.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Router with service in error caused by wrong TargetPort", entryPoints: map[string]Entrypoint{"web": { Address: ":80", }}, paths: []string{"services.yml", "httproute/with_wrong_service_port.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "httproute-default-http-app-1-gw-default-my-gateway-ep-web-0-1c0cf64bde37d9d0df06": { EntryPoints: []string{"web"}, Service: "httproute-default-http-app-1-gw-default-my-gateway-ep-web-0-1c0cf64bde37d9d0df06-wrr", Rule: "Host(`foo.com`) && Path(`/bar`)", Priority: 100008, RuleSyntax: "default", }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "httproute-default-http-app-1-gw-default-my-gateway-ep-web-0-1c0cf64bde37d9d0df06-wrr": { Weighted: &dynamic.WeightedRoundRobin{ Services: []dynamic.WRRService{ { Name: "default-whoami-http-9000", Weight: ptr.To(1), Status: ptr.To(500), }, }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Empty caused by HTTPS without TLS", entryPoints: map[string]Entrypoint{"websecure": { Address: ":443", }}, paths: []string{"services.yml", "httproute/with_protocol_https_without_tls.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Empty caused by HTTPS with TLS passthrough", entryPoints: map[string]Entrypoint{"websecure": { Address: ":443", }}, paths: []string{"services.yml", "httproute/with_protocol_https_with_tls_passthrough.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Empty caused by HTTPRoute with protocol TLS", entryPoints: map[string]Entrypoint{"websecure": { Address: ":443", }}, paths: []string{"services.yml", "httproute/with_protocol_tls.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Empty caused by HTTPRoute with protocol TCP", entryPoints: map[string]Entrypoint{"websecure": { Address: ":443", }}, paths: []string{"services.yml", "httproute/with_protocol_tcp.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Empty caused by TCPRoute with protocol HTTP", entryPoints: map[string]Entrypoint{"websecure": { Address: ":9000", }}, paths: []string{"services.yml", "tcproute/with_protocol_http.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Empty caused by TCPRoute with protocol HTTPS", entryPoints: map[string]Entrypoint{"websecure": { Address: ":9000", }}, paths: []string{"services.yml", "tcproute/with_protocol_https.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Empty caused by TLSRoute with protocol TCP", entryPoints: map[string]Entrypoint{"websecure": { Address: ":9001", }}, paths: []string{"services.yml", "tlsroute/with_protocol_tcp.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Empty caused by TLSRoute with protocol HTTP", entryPoints: map[string]Entrypoint{"websecure": { Address: ":9001", }}, paths: []string{"services.yml", "tlsroute/with_protocol_http.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Empty caused by TLSRoute with protocol HTTPS", entryPoints: map[string]Entrypoint{"websecure": { Address: ":9001", }}, paths: []string{"services.yml", "tlsroute/with_protocol_https.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Empty caused use http entrypoint with tls activated with HTTPRoute", entryPoints: map[string]Entrypoint{"websecure": { Address: ":443", HasHTTPTLSConf: true, }}, paths: []string{"services.yml", "httproute/simple_with_tls_entrypoint.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Empty because no tcp route defined tls protocol", paths: []string{"services.yml", "tcproute/without_tcproute_tls_protocol.yml"}, entryPoints: map[string]Entrypoint{"TCP": { Address: ":8080", }}, experimentalChannel: true, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Certificates: []*tls.CertAndStores{ { Certificate: tls.Certificate{ CertFile: types.FileOrContent(listenerCert), KeyFile: types.FileOrContent(listenerKey), }, }, }, }, }, }, { desc: "Empty caused by HTTPRoute with TLS configuration", entryPoints: map[string]Entrypoint{"web": { Address: ":80", }}, paths: []string{"services.yml", "httproute/with_tls_configuration.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Simple HTTPRoute", paths: []string{"services.yml", "httproute/simple.yml"}, entryPoints: map[string]Entrypoint{"web": { Address: ":80", }}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "httproute-default-http-app-1-gw-default-my-gateway-ep-web-0-1c0cf64bde37d9d0df06": { EntryPoints: []string{"web"}, Service: "httproute-default-http-app-1-gw-default-my-gateway-ep-web-0-1c0cf64bde37d9d0df06-wrr", Rule: "Host(`foo.com`) && Path(`/bar`)", Priority: 100008, RuleSyntax: "default", }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "httproute-default-http-app-1-gw-default-my-gateway-ep-web-0-1c0cf64bde37d9d0df06-wrr": { Weighted: &dynamic.WeightedRoundRobin{ Services: []dynamic.WRRService{ { Name: "default-whoami-http-80", Weight: ptr.To(1), }, }, }, }, "default-whoami-http-80": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:80", }, { URL: "http://10.10.0.2:80", }, }, PassHostHeader: ptr.To(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Simple HTTPRoute, with api@internal service", paths: []string{"services.yml", "httproute/simple_to_api_internal.yml"}, entryPoints: map[string]Entrypoint{"web": { Address: ":80", }}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "httproute-default-http-app-1-gw-default-my-gateway-ep-web-0-1c0cf64bde37d9d0df06": { EntryPoints: []string{"web"}, Service: "api@internal", Rule: "Host(`foo.com`) && Path(`/bar`)", Priority: 100008, RuleSyntax: "default", }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Simple HTTPRoute with protocol HTTPS", paths: []string{"services.yml", "httproute/with_protocol_https.yml"}, entryPoints: map[string]Entrypoint{"websecure": { Address: ":443", }}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "httproute-default-http-app-1-gw-default-my-gateway-ep-websecure-0-1c0cf64bde37d9d0df06": { EntryPoints: []string{"websecure"}, Service: "httproute-default-http-app-1-gw-default-my-gateway-ep-websecure-0-1c0cf64bde37d9d0df06-wrr", Rule: "Host(`foo.com`) && Path(`/bar`)", Priority: 100008, RuleSyntax: "default", TLS: &dynamic.RouterTLSConfig{}, }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "httproute-default-http-app-1-gw-default-my-gateway-ep-websecure-0-1c0cf64bde37d9d0df06-wrr": { Weighted: &dynamic.WeightedRoundRobin{ Services: []dynamic.WRRService{ { Name: "default-whoami-http-80", Weight: ptr.To(1), }, }, }, }, "default-whoami-http-80": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:80", }, { URL: "http://10.10.0.2:80", }, }, PassHostHeader: ptr.To(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{ Certificates: []*tls.CertAndStores{ { Certificate: tls.Certificate{ CertFile: types.FileOrContent(listenerCert), KeyFile: types.FileOrContent(listenerKey), }, }, }, }, }, }, { desc: "Simple HTTPRoute, with multiple hosts", paths: []string{"services.yml", "httproute/with_multiple_host.yml"}, entryPoints: map[string]Entrypoint{"web": { Address: ":80", }}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "httproute-default-http-app-1-gw-default-my-gateway-ep-web-0-66e726cd8903b49727ae": { EntryPoints: []string{"web"}, Service: "httproute-default-http-app-1-gw-default-my-gateway-ep-web-0-66e726cd8903b49727ae-wrr", Rule: "(Host(`foo.com`) || Host(`bar.com`)) && PathPrefix(`/`)", Priority: 9, RuleSyntax: "default", }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "httproute-default-http-app-1-gw-default-my-gateway-ep-web-0-66e726cd8903b49727ae-wrr": { Weighted: &dynamic.WeightedRoundRobin{ Services: []dynamic.WRRService{ { Name: "default-whoami-http-80", Weight: ptr.To(1), }, }, }, }, "default-whoami-http-80": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:80", }, { URL: "http://10.10.0.2:80", }, }, PassHostHeader: ptr.To(true), ResponseForwarding: &dynamic.ResponseForwarding{ FlushInterval: ptypes.Duration(100 * time.Millisecond), }, }, }, }, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Simple HTTPRoute, with two hosts one wildcard", paths: []string{"services.yml", "with_two_hosts_one_wildcard.yml"}, entryPoints: map[string]Entrypoint{"web": { Address: ":80", }}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{ "httproute-default-http-app-1-gw-default-my-gateway-ep-web-0-baa117c0219e3878749f": { EntryPoints: []string{"web"}, Service: "httproute-default-http-app-1-gw-default-my-gateway-ep-web-0-baa117c0219e3878749f-wrr", Rule: "(Host(`foo.com`) || HostRegexp(`^[a-z0-9-\\.]+\\.bar\\.com$`)) && PathPrefix(`/`)", Priority: 11, RuleSyntax: "default", }, }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "httproute-default-http-app-1-gw-default-my-gateway-ep-web-0-baa117c0219e3878749f-wrr": { Weighted: &dynamic.WeightedRoundRobin{ Services: []dynamic.WRRService{ { Name: "default-whoami-http-80", Weight: ptr.To(1), }, }, }, }, "default-whoami-http-80": { LoadBalancer: &dynamic.ServersLoadBalancer{ Strategy: dynamic.BalancerStrategyWRR, Servers: []dynamic.Server{ { URL: "http://10.10.0.1:80", }, { URL: "http://10.10.0.2:80",
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/gateway/kubernetes.go
pkg/provider/kubernetes/gateway/kubernetes.go
package gateway import ( "context" "crypto/sha256" "errors" "fmt" "os" "slices" "sort" "strconv" "strings" "time" "github.com/cenkalti/backoff/v4" "github.com/hashicorp/go-multierror" "github.com/mitchellh/hashstructure" "github.com/rs/zerolog/log" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/job" "github.com/traefik/traefik/v3/pkg/observability/logs" traefikv1alpha1 "github.com/traefik/traefik/v3/pkg/provider/kubernetes/crd/traefikio/v1alpha1" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/k8s" "github.com/traefik/traefik/v3/pkg/safe" "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" ktypes "k8s.io/apimachinery/pkg/types" "k8s.io/utils/ptr" gatev1 "sigs.k8s.io/gateway-api/apis/v1" gatev1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" ) const ( providerName = "kubernetesgateway" controllerName = "traefik.io/gateway-controller" groupCore = "core" groupGateway = "gateway.networking.k8s.io" kindGateway = "Gateway" kindTraefikService = "TraefikService" kindHTTPRoute = "HTTPRoute" kindGRPCRoute = "GRPCRoute" kindTCPRoute = "TCPRoute" kindTLSRoute = "TLSRoute" kindService = "Service" appProtocolHTTP = "http" appProtocolHTTPS = "https" appProtocolH2C = "kubernetes.io/h2c" appProtocolWS = "kubernetes.io/ws" appProtocolWSS = "kubernetes.io/wss" schemeHTTP = "http" schemeHTTPS = "https" schemeH2C = "h2c" ) // Provider holds configurations of the provider. type Provider struct { Endpoint string `description:"Kubernetes server endpoint (required for external cluster client)." json:"endpoint,omitempty" toml:"endpoint,omitempty" yaml:"endpoint,omitempty"` Token types.FileOrContent `description:"Kubernetes bearer token (not needed for in-cluster client). It accepts either a token value or a file path to the token." json:"token,omitempty" toml:"token,omitempty" yaml:"token,omitempty" loggable:"false"` CertAuthFilePath string `description:"Kubernetes certificate authority file path (not needed for in-cluster client)." json:"certAuthFilePath,omitempty" toml:"certAuthFilePath,omitempty" yaml:"certAuthFilePath,omitempty"` Namespaces []string `description:"Kubernetes namespaces." json:"namespaces,omitempty" toml:"namespaces,omitempty" yaml:"namespaces,omitempty" export:"true"` LabelSelector string `description:"Kubernetes label selector to select specific GatewayClasses." json:"labelSelector,omitempty" toml:"labelSelector,omitempty" yaml:"labelSelector,omitempty" export:"true"` ThrottleDuration ptypes.Duration `description:"Kubernetes refresh throttle duration" json:"throttleDuration,omitempty" toml:"throttleDuration,omitempty" yaml:"throttleDuration,omitempty" export:"true"` ExperimentalChannel bool `description:"Toggles Experimental Channel resources support (TCPRoute, TLSRoute...)." json:"experimentalChannel,omitempty" toml:"experimentalChannel,omitempty" yaml:"experimentalChannel,omitempty" export:"true"` StatusAddress *StatusAddress `description:"Defines the Kubernetes Gateway status address." json:"statusAddress,omitempty" toml:"statusAddress,omitempty" yaml:"statusAddress,omitempty" export:"true"` NativeLBByDefault bool `description:"Defines whether to use Native Kubernetes load-balancing by default." json:"nativeLBByDefault,omitempty" toml:"nativeLBByDefault,omitempty" yaml:"nativeLBByDefault,omitempty" export:"true"` EntryPoints map[string]Entrypoint `json:"-" toml:"-" yaml:"-" label:"-" file:"-"` // groupKindFilterFuncs is the list of allowed Group and Kinds for the Filter ExtensionRef objects. groupKindFilterFuncs map[string]map[string]BuildFilterFunc // groupKindBackendFuncs is the list of allowed Group and Kinds for the Backend ExtensionRef objects. groupKindBackendFuncs map[string]map[string]BuildBackendFunc lastConfiguration safe.Safe routerTransform k8s.RouterTransform client *clientWrapper } // Entrypoint defines the available entry points. type Entrypoint struct { Address string HasHTTPTLSConf bool } // StatusAddress holds the Gateway Status address configuration. type StatusAddress struct { IP string `description:"IP used to set Kubernetes Gateway status address." json:"ip,omitempty" toml:"ip,omitempty" yaml:"ip,omitempty"` Hostname string `description:"Hostname used for Kubernetes Gateway status address." json:"hostname,omitempty" toml:"hostname,omitempty" yaml:"hostname,omitempty"` Service ServiceRef `description:"Published Kubernetes Service to copy status addresses from." json:"service,omitempty" toml:"service,omitempty" yaml:"service,omitempty"` } // ServiceRef holds a Kubernetes service reference. type ServiceRef struct { Name string `description:"Name of the Kubernetes service." json:"name,omitempty" toml:"name,omitempty" yaml:"name,omitempty"` Namespace string `description:"Namespace of the Kubernetes service." json:"namespace,omitempty" toml:"namespace,omitempty" yaml:"namespace,omitempty"` } // BuildFilterFunc returns the name of the filter and the related dynamic.Middleware if needed. type BuildFilterFunc func(name, namespace string) (string, *dynamic.Middleware, error) // BuildBackendFunc returns the name of the backend and the related dynamic.Service if needed. type BuildBackendFunc func(name, namespace string) (string, *dynamic.Service, error) type ExtensionBuilderRegistry interface { RegisterFilterFuncs(group, kind string, builderFunc BuildFilterFunc) RegisterBackendFuncs(group, kind string, builderFunc BuildBackendFunc) } type gatewayListener struct { Name string Port gatev1.PortNumber Protocol gatev1.ProtocolType TLS *gatev1.ListenerTLSConfig Hostname *gatev1.Hostname Status *gatev1.ListenerStatus AllowedNamespaces []string AllowedRouteKinds []string Attached bool GWName string GWNamespace string GWGeneration int64 EPName string } // RegisterFilterFuncs registers an allowed Group, Kind, and builder for the Filter ExtensionRef objects. func (p *Provider) RegisterFilterFuncs(group, kind string, builderFunc BuildFilterFunc) { if p.groupKindFilterFuncs == nil { p.groupKindFilterFuncs = map[string]map[string]BuildFilterFunc{} } if p.groupKindFilterFuncs[group] == nil { p.groupKindFilterFuncs[group] = map[string]BuildFilterFunc{} } p.groupKindFilterFuncs[group][kind] = builderFunc } // RegisterBackendFuncs registers an allowed Group, Kind, and builder for the Backend ExtensionRef objects. func (p *Provider) RegisterBackendFuncs(group, kind string, builderFunc BuildBackendFunc) { if p.groupKindBackendFuncs == nil { p.groupKindBackendFuncs = map[string]map[string]BuildBackendFunc{} } if p.groupKindBackendFuncs[group] == nil { p.groupKindBackendFuncs[group] = map[string]BuildBackendFunc{} } p.groupKindBackendFuncs[group][kind] = builderFunc } func (p *Provider) SetRouterTransform(routerTransform k8s.RouterTransform) { p.routerTransform = routerTransform } func (p *Provider) applyRouterTransform(ctx context.Context, rt *dynamic.Router, route *gatev1.HTTPRoute) { if p.routerTransform == nil { return } if err := p.routerTransform.Apply(ctx, rt, route); err != nil { log.Ctx(ctx).Error().Err(err).Msg("Apply router transform") } } func (p *Provider) newK8sClient(ctx context.Context) (*clientWrapper, error) { // Label selector validation _, err := labels.Parse(p.LabelSelector) if err != nil { return nil, fmt.Errorf("invalid label selector: %q", p.LabelSelector) } logger := log.Ctx(ctx) logger.Info().Msgf("Label selector is: %q", p.LabelSelector) var client *clientWrapper switch { case os.Getenv("KUBERNETES_SERVICE_HOST") != "" && os.Getenv("KUBERNETES_SERVICE_PORT") != "": logger.Info().Str("endpoint", p.Endpoint).Msg("Creating in-cluster Provider client") client, err = newInClusterClient(p.Endpoint) case os.Getenv("KUBECONFIG") != "": logger.Info().Msgf("Creating cluster-external Provider client from KUBECONFIG %s", os.Getenv("KUBECONFIG")) client, err = newExternalClusterClientFromFile(os.Getenv("KUBECONFIG")) default: logger.Info().Str("endpoint", p.Endpoint).Msg("Creating cluster-external Provider client") client, err = newExternalClusterClient(p.Endpoint, p.CertAuthFilePath, p.Token) } if err != nil { return nil, err } client.labelSelector = p.LabelSelector client.experimentalChannel = p.ExperimentalChannel return client, nil } // Init the provider. func (p *Provider) Init() error { logger := log.With().Str(logs.ProviderName, providerName).Logger() var err error p.client, err = p.newK8sClient(logger.WithContext(context.Background())) if err != nil { return fmt.Errorf("creating k8s client: %w", err) } return nil } // Provide allows the k8s provider to provide configurations to traefik using the given configuration channel. func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error { logger := log.With().Str(logs.ProviderName, providerName).Logger() ctxLog := logger.WithContext(context.Background()) pool.GoCtx(func(ctxPool context.Context) { operation := func() error { eventsChan, err := p.client.WatchAll(p.Namespaces, ctxPool.Done()) if err != nil { logger.Error().Err(err).Msg("Error watching kubernetes events") timer := time.NewTimer(1 * time.Second) select { case <-timer.C: return err case <-ctxPool.Done(): return nil } } throttleDuration := time.Duration(p.ThrottleDuration) throttledChan := throttleEvents(ctxLog, throttleDuration, pool, eventsChan) if throttledChan != nil { eventsChan = throttledChan } for { select { case <-ctxPool.Done(): return nil case event := <-eventsChan: // Note that event is the *first* event that came in during this throttling interval -- if we're hitting our throttle, we may have dropped events. // This is fine, because we don't treat different event types differently. // But if we do in the future, we'll need to track more information about the dropped events. conf := p.loadConfigurationFromGateways(ctxLog) confHash, err := hashstructure.Hash(conf, nil) switch { case err != nil: logger.Error().Msg("Unable to hash the configuration") case p.lastConfiguration.Get() == confHash: logger.Debug().Msgf("Skipping Kubernetes event kind %T", event) default: p.lastConfiguration.Set(confHash) configurationChan <- dynamic.Message{ ProviderName: providerName, Configuration: conf, } } // If we're throttling, // we sleep here for the throttle duration to enforce that we don't refresh faster than our throttle. // time.Sleep returns immediately if p.ThrottleDuration is 0 (no throttle). time.Sleep(throttleDuration) } } } notify := func(err error, time time.Duration) { logger.Error().Err(err).Msgf("Provider error, retrying in %s", time) } err := backoff.RetryNotify(safe.OperationWithRecover(operation), backoff.WithContext(job.NewBackOff(backoff.NewExponentialBackOff()), ctxPool), notify) if err != nil { logger.Error().Err(err).Msg("Cannot retrieve data") } }) return nil } // TODO Handle errors and update resources statuses (gatewayClass, gateway). func (p *Provider) loadConfigurationFromGateways(ctx context.Context) *dynamic.Configuration { conf := &dynamic.Configuration{ HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TLS: &dynamic.TLSConfiguration{}, } addresses, err := p.gatewayAddresses() if err != nil { log.Ctx(ctx).Error().Err(err).Msg("Unable to get Gateway status addresses") return nil } gatewayClasses, err := p.client.ListGatewayClasses() if err != nil { log.Ctx(ctx).Error().Err(err).Msg("Unable to list GatewayClasses") return nil } var supportedFeatures []gatev1.SupportedFeature for _, feature := range SupportedFeatures() { supportedFeatures = append(supportedFeatures, gatev1.SupportedFeature{Name: gatev1.FeatureName(feature)}) } slices.SortFunc(supportedFeatures, func(a, b gatev1.SupportedFeature) int { return strings.Compare(string(a.Name), string(b.Name)) }) gatewayClassNames := map[string]struct{}{} for _, gatewayClass := range gatewayClasses { if gatewayClass.Spec.ControllerName != controllerName { continue } gatewayClassNames[gatewayClass.Name] = struct{}{} status := gatev1.GatewayClassStatus{ Conditions: upsertGatewayClassConditionAccepted(gatewayClass.Status.Conditions, metav1.Condition{ Type: string(gatev1.GatewayClassConditionStatusAccepted), Status: metav1.ConditionTrue, ObservedGeneration: gatewayClass.Generation, Reason: "Handled", Message: "Handled by Traefik controller", LastTransitionTime: metav1.Now(), }), SupportedFeatures: supportedFeatures, } if err := p.client.UpdateGatewayClassStatus(ctx, gatewayClass.Name, status); err != nil { log.Ctx(ctx). Warn(). Err(err). Str("gateway_class", gatewayClass.Name). Msg("Unable to update GatewayClass status") } } var gateways []*gatev1.Gateway for _, gateway := range p.client.ListGateways() { if _, ok := gatewayClassNames[string(gateway.Spec.GatewayClassName)]; !ok { continue } gateways = append(gateways, gateway) } var gatewayListeners []gatewayListener for _, gateway := range gateways { logger := log.Ctx(ctx).With(). Str("gateway", gateway.Name). Str("namespace", gateway.Namespace). Logger() gatewayListeners = append(gatewayListeners, p.loadGatewayListeners(logger.WithContext(ctx), gateway, conf)...) } p.loadHTTPRoutes(ctx, gatewayListeners, conf) p.loadGRPCRoutes(ctx, gatewayListeners, conf) if p.ExperimentalChannel { p.loadTCPRoutes(ctx, gatewayListeners, conf) p.loadTLSRoutes(ctx, gatewayListeners, conf) } for _, gateway := range gateways { logger := log.Ctx(ctx).With(). Str("gateway", gateway.Name). Str("namespace", gateway.Namespace). Logger() var listeners []gatewayListener for _, listener := range gatewayListeners { if listener.GWName == gateway.Name && listener.GWNamespace == gateway.Namespace { listeners = append(listeners, listener) } } gatewayStatus, errConditions := p.makeGatewayStatus(gateway, listeners, addresses) if len(errConditions) > 0 { messages := map[string]struct{}{} for _, condition := range errConditions { messages[condition.Message] = struct{}{} } var conditionsErr error for message := range messages { conditionsErr = multierror.Append(conditionsErr, errors.New(message)) } logger.Error(). Err(conditionsErr). Msg("Gateway Not Accepted") } if err = p.client.UpdateGatewayStatus(ctx, ktypes.NamespacedName{Name: gateway.Name, Namespace: gateway.Namespace}, gatewayStatus); err != nil { logger.Warn(). Err(err). Msg("Unable to update Gateway status") } } return conf } func (p *Provider) loadGatewayListeners(ctx context.Context, gateway *gatev1.Gateway, conf *dynamic.Configuration) []gatewayListener { tlsConfigs := make(map[string]*tls.CertAndStores) allocatedListeners := make(map[string]struct{}) gatewayListeners := make([]gatewayListener, len(gateway.Spec.Listeners)) for i, listener := range gateway.Spec.Listeners { gatewayListeners[i] = gatewayListener{ Name: string(listener.Name), GWName: gateway.Name, GWNamespace: gateway.Namespace, GWGeneration: gateway.Generation, Port: listener.Port, Protocol: listener.Protocol, TLS: listener.TLS, Hostname: listener.Hostname, Status: &gatev1.ListenerStatus{ Name: listener.Name, SupportedKinds: []gatev1.RouteGroupKind{}, Conditions: []metav1.Condition{}, }, } ep, err := p.entryPointName(listener.Port, listener.Protocol) if err != nil { // update "Detached" status with "PortUnavailable" reason gatewayListeners[i].Status.Conditions = append(gatewayListeners[i].Status.Conditions, metav1.Condition{ Type: string(gatev1.ListenerConditionAccepted), Status: metav1.ConditionFalse, ObservedGeneration: gateway.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.ListenerReasonPortUnavailable), Message: fmt.Sprintf("Cannot find entryPoint for Gateway: %v", err), }) continue } gatewayListeners[i].EPName = ep allowedRoutes := ptr.Deref(listener.AllowedRoutes, gatev1.AllowedRoutes{Namespaces: &gatev1.RouteNamespaces{From: ptr.To(gatev1.NamespacesFromSame)}}) gatewayListeners[i].AllowedNamespaces, err = p.allowedNamespaces(gateway.Namespace, allowedRoutes.Namespaces) if err != nil { // update "ResolvedRefs" status true with "InvalidRoutesRef" reason gatewayListeners[i].Status.Conditions = append(gatewayListeners[i].Status.Conditions, metav1.Condition{ Type: string(gatev1.ListenerConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: gateway.Generation, LastTransitionTime: metav1.Now(), Reason: "InvalidRouteNamespacesSelector", // Should never happen as the selector is validated by kubernetes Message: fmt.Sprintf("Invalid route namespaces selector: %v", err), }) continue } supportedKinds, conditions := supportedRouteKinds(listener.Protocol, p.ExperimentalChannel) if len(conditions) > 0 { gatewayListeners[i].Status.Conditions = append(gatewayListeners[i].Status.Conditions, conditions...) continue } routeKinds, conditions := allowedRouteKinds(gateway, listener, supportedKinds) for _, kind := range routeKinds { gatewayListeners[i].AllowedRouteKinds = append(gatewayListeners[i].AllowedRouteKinds, string(kind.Kind)) } gatewayListeners[i].Status.SupportedKinds = routeKinds if len(conditions) > 0 { gatewayListeners[i].Status.Conditions = append(gatewayListeners[i].Status.Conditions, conditions...) continue } listenerKey := makeListenerKey(listener) if _, ok := allocatedListeners[listenerKey]; ok { gatewayListeners[i].Status.Conditions = append(gatewayListeners[i].Status.Conditions, metav1.Condition{ Type: string(gatev1.ListenerConditionConflicted), Status: metav1.ConditionTrue, ObservedGeneration: gateway.Generation, LastTransitionTime: metav1.Now(), Reason: "DuplicateListener", Message: "A listener with same protocol, port and hostname already exists", }) continue } allocatedListeners[listenerKey] = struct{}{} if (listener.Protocol == gatev1.HTTPProtocolType || listener.Protocol == gatev1.TCPProtocolType) && listener.TLS != nil { gatewayListeners[i].Status.Conditions = append(gatewayListeners[i].Status.Conditions, metav1.Condition{ Type: string(gatev1.ListenerConditionAccepted), Status: metav1.ConditionFalse, ObservedGeneration: gateway.Generation, LastTransitionTime: metav1.Now(), Reason: "InvalidTLSConfiguration", // TODO check the spec if a proper reason is introduced at some point Message: "TLS configuration must no be defined when using HTTP or TCP protocol", }) continue } // TLS if listener.Protocol == gatev1.HTTPSProtocolType || listener.Protocol == gatev1.TLSProtocolType { if listener.TLS == nil || (len(listener.TLS.CertificateRefs) == 0 && listener.TLS.Mode != nil && *listener.TLS.Mode != gatev1.TLSModePassthrough) { // update "Detached" status with "UnsupportedProtocol" reason gatewayListeners[i].Status.Conditions = append(gatewayListeners[i].Status.Conditions, metav1.Condition{ Type: string(gatev1.ListenerConditionAccepted), Status: metav1.ConditionFalse, ObservedGeneration: gateway.Generation, LastTransitionTime: metav1.Now(), Reason: "InvalidTLSConfiguration", // TODO check the spec if a proper reason is introduced at some point Message: fmt.Sprintf("No TLS configuration for Gateway Listener %s:%d and protocol %q", listener.Name, listener.Port, listener.Protocol), }) continue } var tlsModeType gatev1.TLSModeType if listener.TLS.Mode != nil { tlsModeType = *listener.TLS.Mode } isTLSPassthrough := tlsModeType == gatev1.TLSModePassthrough if isTLSPassthrough && len(listener.TLS.CertificateRefs) > 0 { // https://gateway-api.sigs.k8s.io/v1alpha2/references/spec/#gateway.networking.k8s.io/v1alpha2.GatewayTLSConfig log.Ctx(ctx).Warn().Msg("In case of Passthrough TLS mode, no TLS settings take effect as the TLS session from the client is NOT terminated at the Gateway") } // Allowed configurations: // Protocol TLS -> Passthrough -> TLSRoute/TCPRoute // Protocol TLS -> Terminate -> TLSRoute/TCPRoute // Protocol HTTPS -> Terminate -> HTTPRoute if listener.Protocol == gatev1.HTTPSProtocolType && isTLSPassthrough { gatewayListeners[i].Status.Conditions = append(gatewayListeners[i].Status.Conditions, metav1.Condition{ Type: string(gatev1.ListenerConditionAccepted), Status: metav1.ConditionFalse, ObservedGeneration: gateway.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.ListenerReasonUnsupportedProtocol), Message: "HTTPS protocol is not supported with TLS mode Passthrough", }) continue } if !isTLSPassthrough { if len(listener.TLS.CertificateRefs) == 0 { // update "ResolvedRefs" status true with "InvalidCertificateRef" reason gatewayListeners[i].Status.Conditions = append(gatewayListeners[i].Status.Conditions, metav1.Condition{ Type: string(gatev1.ListenerConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: gateway.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.ListenerReasonInvalidCertificateRef), Message: "One TLS CertificateRef is required in Terminate mode", }) continue } // TODO Should we support multiple certificates? certificateRef := listener.TLS.CertificateRefs[0] if certificateRef.Kind == nil || *certificateRef.Kind != "Secret" || certificateRef.Group == nil || (*certificateRef.Group != "" && *certificateRef.Group != groupCore) { // update "ResolvedRefs" status true with "InvalidCertificateRef" reason gatewayListeners[i].Status.Conditions = append(gatewayListeners[i].Status.Conditions, metav1.Condition{ Type: string(gatev1.ListenerConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: gateway.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.ListenerReasonInvalidCertificateRef), Message: fmt.Sprintf("Unsupported TLS CertificateRef group/kind: %s/%s", groupToString(certificateRef.Group), kindToString(certificateRef.Kind)), }) continue } certificateNamespace := gateway.Namespace if certificateRef.Namespace != nil && string(*certificateRef.Namespace) != gateway.Namespace { certificateNamespace = string(*certificateRef.Namespace) } if err := p.isReferenceGranted(kindGateway, gateway.Namespace, groupCore, "Secret", string(certificateRef.Name), certificateNamespace); err != nil { gatewayListeners[i].Status.Conditions = append(gatewayListeners[i].Status.Conditions, metav1.Condition{ Type: string(gatev1.ListenerConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: gateway.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.ListenerReasonRefNotPermitted), Message: fmt.Sprintf("Cannot load CertificateRef %s/%s: %s", certificateNamespace, certificateRef.Name, err), }) continue } configKey := certificateNamespace + "/" + string(certificateRef.Name) if _, tlsExists := tlsConfigs[configKey]; !tlsExists { tlsConf, err := p.getTLS(certificateRef.Name, certificateNamespace) if err != nil { // update "ResolvedRefs" status false with "InvalidCertificateRef" reason // update "Programmed" status false with "Invalid" reason gatewayListeners[i].Status.Conditions = append(gatewayListeners[i].Status.Conditions, metav1.Condition{ Type: string(gatev1.ListenerConditionResolvedRefs), Status: metav1.ConditionFalse, ObservedGeneration: gateway.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.ListenerReasonInvalidCertificateRef), Message: fmt.Sprintf("Error while retrieving certificate: %v", err), }, metav1.Condition{ Type: string(gatev1.ListenerConditionProgrammed), Status: metav1.ConditionFalse, ObservedGeneration: gateway.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.ListenerReasonInvalid), Message: fmt.Sprintf("Error while retrieving certificate: %v", err), }, ) continue } tlsConfigs[configKey] = tlsConf } } } gatewayListeners[i].Attached = true } if len(tlsConfigs) > 0 { conf.TLS.Certificates = append(conf.TLS.Certificates, getTLSConfig(tlsConfigs)...) } return gatewayListeners } func (p *Provider) makeGatewayStatus(gateway *gatev1.Gateway, listeners []gatewayListener, addresses []gatev1.GatewayStatusAddress) (gatev1.GatewayStatus, []metav1.Condition) { gatewayStatus := gatev1.GatewayStatus{Addresses: addresses} var errorConditions []metav1.Condition for _, listener := range listeners { if len(listener.Status.Conditions) == 0 { listener.Status.Conditions = append(listener.Status.Conditions, metav1.Condition{ Type: string(gatev1.ListenerConditionAccepted), Status: metav1.ConditionTrue, ObservedGeneration: gateway.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.ListenerReasonAccepted), Message: "No error found", }, metav1.Condition{ Type: string(gatev1.ListenerConditionResolvedRefs), Status: metav1.ConditionTrue, ObservedGeneration: gateway.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.ListenerReasonResolvedRefs), Message: "No error found", }, metav1.Condition{ Type: string(gatev1.ListenerConditionProgrammed), Status: metav1.ConditionTrue, ObservedGeneration: gateway.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.ListenerReasonProgrammed), Message: "No error found", }, ) // TODO: refactor gatewayStatus.Listeners = append(gatewayStatus.Listeners, *listener.Status) continue } errorConditions = append(errorConditions, listener.Status.Conditions...) gatewayStatus.Listeners = append(gatewayStatus.Listeners, *listener.Status) } if len(errorConditions) > 0 { // GatewayConditionReady "Ready", GatewayConditionReason "ListenersNotValid" gatewayStatus.Conditions = append(gatewayStatus.Conditions, metav1.Condition{ Type: string(gatev1.GatewayConditionAccepted), Status: metav1.ConditionFalse, ObservedGeneration: gateway.Generation, LastTransitionTime: metav1.Now(), Reason: string(gatev1.GatewayReasonListenersNotValid), Message: "All Listeners must be valid", }) return gatewayStatus, errorConditions } gatewayStatus.Conditions = append(gatewayStatus.Conditions, // update "Accepted" status with "Accepted" reason metav1.Condition{ Type: string(gatev1.GatewayConditionAccepted), Status: metav1.ConditionTrue, ObservedGeneration: gateway.Generation, Reason: string(gatev1.GatewayReasonAccepted), Message: "Gateway successfully scheduled", LastTransitionTime: metav1.Now(), }, // update "Programmed" status with "Programmed" reason metav1.Condition{ Type: string(gatev1.GatewayConditionProgrammed), Status: metav1.ConditionTrue, ObservedGeneration: gateway.Generation, Reason: string(gatev1.GatewayReasonProgrammed), Message: "Gateway successfully scheduled", LastTransitionTime: metav1.Now(), }, ) return gatewayStatus, nil } func (p *Provider) gatewayAddresses() ([]gatev1.GatewayStatusAddress, error) { if p.StatusAddress == nil { return nil, nil } if p.StatusAddress.IP != "" { return []gatev1.GatewayStatusAddress{{ Type: ptr.To(gatev1.IPAddressType), Value: p.StatusAddress.IP, }}, nil } if p.StatusAddress.Hostname != "" { return []gatev1.GatewayStatusAddress{{ Type: ptr.To(gatev1.HostnameAddressType), Value: p.StatusAddress.Hostname, }}, nil } svcRef := p.StatusAddress.Service if svcRef.Name != "" && svcRef.Namespace != "" { svc, err := p.client.GetService(svcRef.Namespace, svcRef.Name) if err != nil { return nil, fmt.Errorf("getting service: %w", err) } var addresses []gatev1.GatewayStatusAddress for _, addr := range svc.Status.LoadBalancer.Ingress { switch { case addr.IP != "": addresses = append(addresses, gatev1.GatewayStatusAddress{ Type: ptr.To(gatev1.IPAddressType), Value: addr.IP, }) case addr.Hostname != "": addresses = append(addresses, gatev1.GatewayStatusAddress{ Type: ptr.To(gatev1.HostnameAddressType), Value: addr.Hostname, }) } } return addresses, nil } return nil, errors.New("empty Gateway status address configuration") } func (p *Provider) entryPointName(port gatev1.PortNumber, protocol gatev1.ProtocolType) (string, error) { portStr := strconv.FormatInt(int64(port), 10) for name, entryPoint := range p.EntryPoints { if strings.HasSuffix(entryPoint.Address, ":"+portStr) { // If the protocol is HTTP the entryPoint must have no TLS conf // Not relevant for gatev1.TLSProtocolType && gatev1.TCPProtocolType if protocol == gatev1.HTTPProtocolType && entryPoint.HasHTTPTLSConf { continue } return name, nil } } return "", fmt.Errorf("no matching entryPoint for port %d and protocol %q", port, protocol) } func (p *Provider) isReferenceGranted(fromKind, fromNamespace, toGroup, toKind, toName, toNamespace string) error { if toNamespace == fromNamespace { return nil } refGrants, err := p.client.ListReferenceGrants(toNamespace) if err != nil { return fmt.Errorf("listing ReferenceGrant: %w", err) } refGrants = filterReferenceGrantsFrom(refGrants, groupGateway, fromKind, fromNamespace) refGrants = filterReferenceGrantsTo(refGrants, toGroup, toKind, toName) if len(refGrants) == 0 { return errors.New("missing ReferenceGrant") } return nil } func (p *Provider) getTLS(secretName gatev1.ObjectName, namespace string) (*tls.CertAndStores, error) { secret, err := p.client.GetSecret(namespace, string(secretName)) if err != nil { return nil, fmt.Errorf("getting secret: %w", err) } cert, key, err := getCertificateBlocks(secret, namespace, string(secretName)) if err != nil { return nil, fmt.Errorf("getting certificate blocks: %w", err) } certAndStore := &tls.CertAndStores{ Certificate: tls.Certificate{ CertFile: types.FileOrContent(cert), KeyFile: types.FileOrContent(key), }, } if _, err := certAndStore.GetCertificate(); err != nil {
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/gateway/annotations_test.go
pkg/provider/kubernetes/gateway/annotations_test.go
package gateway import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "k8s.io/utils/ptr" ) func Test_parseServiceConfig(t *testing.T) { testCases := []struct { desc string annotations map[string]string expected ServiceConfig }{ { desc: "service annotations", annotations: map[string]string{ "ingress.kubernetes.io/foo": "bar", "traefik.io/foo": "bar", "traefik.io/service.nativelb": "true", }, expected: ServiceConfig{ Service: Service{ NativeLB: ptr.To(true), }, }, }, { desc: "empty map", annotations: map[string]string{}, expected: ServiceConfig{}, }, { desc: "nil map", annotations: nil, expected: ServiceConfig{}, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() cfg, err := parseServiceAnnotations(test.annotations) require.NoError(t, err) assert.Equal(t, test.expected, cfg) }) } } func Test_convertAnnotations(t *testing.T) { testCases := []struct { desc string annotations map[string]string expected map[string]string }{ { desc: "service annotations", annotations: map[string]string{ "traefik.io/service.nativelb": "true", }, expected: map[string]string{ "traefik.service.nativelb": "true", }, }, { desc: "empty map", annotations: map[string]string{}, expected: nil, }, { desc: "nil map", annotations: nil, expected: nil, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() labels := convertAnnotations(test.annotations) assert.Equal(t, test.expected, labels) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/gateway/grpcroute_test.go
pkg/provider/kubernetes/gateway/grpcroute_test.go
package gateway import ( "testing" "github.com/stretchr/testify/assert" "k8s.io/utils/ptr" gatev1 "sigs.k8s.io/gateway-api/apis/v1" ) func Test_buildGRPCMatchRule(t *testing.T) { testCases := []struct { desc string match gatev1.GRPCRouteMatch hostnames []gatev1.Hostname expectedRule string expectedPriority int expectedError bool }{ { desc: "Empty rule and matches", expectedRule: "PathPrefix(`/`)", expectedPriority: 15, }, { desc: "One Host rule without match", hostnames: []gatev1.Hostname{"foo.com"}, expectedRule: "Host(`foo.com`) && PathPrefix(`/`)", expectedPriority: 22, }, { desc: "One GRPCRouteMatch with no GRPCHeaderMatch", match: gatev1.GRPCRouteMatch{ Method: &gatev1.GRPCMethodMatch{ Type: ptr.To(gatev1.GRPCMethodMatchExact), Service: ptr.To("foo"), Method: ptr.To("bar"), }, }, expectedRule: "PathRegexp(`/foo/bar`)", expectedPriority: 22, }, { desc: "One GRPCRouteMatch with one GRPCHeaderMatch", match: gatev1.GRPCRouteMatch{ Method: &gatev1.GRPCMethodMatch{ Type: ptr.To(gatev1.GRPCMethodMatchExact), Service: ptr.To("foo"), Method: ptr.To("bar"), }, Headers: []gatev1.GRPCHeaderMatch{ { Type: ptr.To(gatev1.GRPCHeaderMatchExact), Name: "foo", Value: "bar", }, }, }, expectedRule: "PathRegexp(`/foo/bar`) && Header(`foo`,`bar`)", expectedPriority: 45, }, { desc: "One GRPCRouteMatch with one GRPCHeaderMatch and one Host", hostnames: []gatev1.Hostname{"foo.com"}, match: gatev1.GRPCRouteMatch{ Method: &gatev1.GRPCMethodMatch{ Type: ptr.To(gatev1.GRPCMethodMatchExact), Service: ptr.To("foo"), Method: ptr.To("bar"), }, Headers: []gatev1.GRPCHeaderMatch{ { Type: ptr.To(gatev1.GRPCHeaderMatchExact), Name: "foo", Value: "bar", }, }, }, expectedRule: "Host(`foo.com`) && PathRegexp(`/foo/bar`) && Header(`foo`,`bar`)", expectedPriority: 52, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() rule, priority := buildGRPCMatchRule(test.hostnames, test.match) assert.Equal(t, test.expectedRule, rule) assert.Equal(t, test.expectedPriority, priority) }) } } func Test_buildGRPCMethodRule(t *testing.T) { testCases := []struct { desc string method *gatev1.GRPCMethodMatch expectedRule string }{ { desc: "Empty", expectedRule: "PathPrefix(`/`)", }, { desc: "Exact service matching", method: &gatev1.GRPCMethodMatch{ Type: ptr.To(gatev1.GRPCMethodMatchExact), Service: ptr.To("foo"), }, expectedRule: "PathRegexp(`/foo/[^/]+`)", }, { desc: "Exact method matching", method: &gatev1.GRPCMethodMatch{ Type: ptr.To(gatev1.GRPCMethodMatchExact), Method: ptr.To("bar"), }, expectedRule: "PathRegexp(`/[^/]+/bar`)", }, { desc: "Exact service and method matching", method: &gatev1.GRPCMethodMatch{ Type: ptr.To(gatev1.GRPCMethodMatchExact), Service: ptr.To("foo"), Method: ptr.To("bar"), }, expectedRule: "PathRegexp(`/foo/bar`)", }, { desc: "Regexp service matching", method: &gatev1.GRPCMethodMatch{ Type: ptr.To(gatev1.GRPCMethodMatchRegularExpression), Service: ptr.To("[^1-9/]"), }, expectedRule: "PathRegexp(`/[^1-9/]/[^/]+`)", }, { desc: "Regexp method matching", method: &gatev1.GRPCMethodMatch{ Type: ptr.To(gatev1.GRPCMethodMatchRegularExpression), Method: ptr.To("[^1-9/]"), }, expectedRule: "PathRegexp(`/[^/]+/[^1-9/]`)", }, { desc: "Regexp service and method matching", method: &gatev1.GRPCMethodMatch{ Type: ptr.To(gatev1.GRPCMethodMatchRegularExpression), Service: ptr.To("[^1-9/]"), Method: ptr.To("[^1-9/]"), }, expectedRule: "PathRegexp(`/[^1-9/]/[^1-9/]`)", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() rule := buildGRPCMethodRule(test.method) assert.Equal(t, test.expectedRule, rule) }) } } func Test_buildGRPCHeaderRules(t *testing.T) { testCases := []struct { desc string headers []gatev1.GRPCHeaderMatch expectedRules []string }{ { desc: "Empty", }, { desc: "One exact match type", headers: []gatev1.GRPCHeaderMatch{ { Type: ptr.To(gatev1.GRPCHeaderMatchExact), Name: "foo", Value: "bar", }, }, expectedRules: []string{"Header(`foo`,`bar`)"}, }, { desc: "One regexp match type", headers: []gatev1.GRPCHeaderMatch{ { Type: ptr.To(gatev1.GRPCHeaderMatchRegularExpression), Name: "foo", Value: ".*", }, }, expectedRules: []string{"HeaderRegexp(`foo`,`.*`)"}, }, { desc: "One exact and regexp match type", headers: []gatev1.GRPCHeaderMatch{ { Type: ptr.To(gatev1.GRPCHeaderMatchExact), Name: "foo", Value: "bar", }, { Type: ptr.To(gatev1.GRPCHeaderMatchRegularExpression), Name: "foo", Value: ".*", }, }, expectedRules: []string{ "Header(`foo`,`bar`)", "HeaderRegexp(`foo`,`.*`)", }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() rule := buildGRPCHeaderRules(test.headers) assert.Equal(t, test.expectedRules, rule) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/crd/client.go
pkg/provider/kubernetes/crd/client.go
package crd import ( "errors" "fmt" "os" "path/filepath" "runtime" "slices" "time" "github.com/rs/zerolog/log" traefikclientset "github.com/traefik/traefik/v3/pkg/provider/kubernetes/crd/generated/clientset/versioned" traefikinformers "github.com/traefik/traefik/v3/pkg/provider/kubernetes/crd/generated/informers/externalversions" traefikv1alpha1 "github.com/traefik/traefik/v3/pkg/provider/kubernetes/crd/traefikio/v1alpha1" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/k8s" "github.com/traefik/traefik/v3/pkg/types" "github.com/traefik/traefik/v3/pkg/version" corev1 "k8s.io/api/core/v1" discoveryv1 "k8s.io/api/discovery/v1" kerror "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/selection" kinformers "k8s.io/client-go/informers" kclientset "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" ) const resyncPeriod = 10 * time.Minute // Client is a client for the Provider master. // WatchAll starts the watch of the Provider resources and updates the stores. // The stores can then be accessed via the Get* functions. type Client interface { WatchAll(namespaces []string, stopCh <-chan struct{}) (<-chan interface{}, error) GetIngressRoutes() []*traefikv1alpha1.IngressRoute GetIngressRouteTCPs() []*traefikv1alpha1.IngressRouteTCP GetIngressRouteUDPs() []*traefikv1alpha1.IngressRouteUDP GetMiddlewares() []*traefikv1alpha1.Middleware GetMiddlewareTCPs() []*traefikv1alpha1.MiddlewareTCP GetTraefikService(namespace, name string) (*traefikv1alpha1.TraefikService, bool, error) GetTraefikServices() []*traefikv1alpha1.TraefikService GetTLSOptions() []*traefikv1alpha1.TLSOption GetServersTransports() []*traefikv1alpha1.ServersTransport GetServersTransportTCPs() []*traefikv1alpha1.ServersTransportTCP GetTLSStores() []*traefikv1alpha1.TLSStore GetService(namespace, name string) (*corev1.Service, bool, error) GetSecret(namespace, name string) (*corev1.Secret, bool, error) GetEndpointSlicesForService(namespace, serviceName string) ([]*discoveryv1.EndpointSlice, error) GetNodes() ([]*corev1.Node, bool, error) GetConfigMap(namespace, name string) (*corev1.ConfigMap, bool, error) } // TODO: add tests for the clientWrapper (and its methods) itself. type clientWrapper struct { csCrd traefikclientset.Interface csKube kclientset.Interface clusterScopeFactory kinformers.SharedInformerFactory disableClusterScopeInformer bool factoriesCrd map[string]traefikinformers.SharedInformerFactory factoriesKube map[string]kinformers.SharedInformerFactory factoriesSecret map[string]kinformers.SharedInformerFactory labelSelector string isNamespaceAll bool watchedNamespaces []string } func createClientFromConfig(c *rest.Config) (*clientWrapper, error) { c.UserAgent = fmt.Sprintf( "%s/%s (%s/%s) kubernetes/crd", filepath.Base(os.Args[0]), version.Version, runtime.GOOS, runtime.GOARCH, ) csCrd, err := traefikclientset.NewForConfig(c) if err != nil { return nil, err } csKube, err := kclientset.NewForConfig(c) if err != nil { return nil, err } return newClientImpl(csKube, csCrd), nil } func newClientImpl(csKube kclientset.Interface, csCrd traefikclientset.Interface) *clientWrapper { return &clientWrapper{ csCrd: csCrd, csKube: csKube, factoriesCrd: make(map[string]traefikinformers.SharedInformerFactory), factoriesKube: make(map[string]kinformers.SharedInformerFactory), factoriesSecret: make(map[string]kinformers.SharedInformerFactory), } } // newInClusterClient returns a new Provider client that is expected to run // inside the cluster. func newInClusterClient(endpoint string) (*clientWrapper, error) { config, err := rest.InClusterConfig() if err != nil { return nil, fmt.Errorf("failed to create in-cluster configuration: %w", err) } if endpoint != "" { config.Host = endpoint } return createClientFromConfig(config) } func newExternalClusterClientFromFile(file string) (*clientWrapper, error) { configFromFlags, err := clientcmd.BuildConfigFromFlags("", file) if err != nil { return nil, err } return createClientFromConfig(configFromFlags) } // newExternalClusterClient returns a new Provider client that may run outside // of the cluster. // The endpoint parameter must not be empty. func newExternalClusterClient(endpoint, caFilePath string, token types.FileOrContent) (*clientWrapper, error) { if endpoint == "" { return nil, errors.New("endpoint missing for external cluster client") } tokenData, err := token.Read() if err != nil { return nil, fmt.Errorf("read token: %w", err) } config := &rest.Config{ Host: endpoint, BearerToken: string(tokenData), } if caFilePath != "" { caData, err := os.ReadFile(caFilePath) if err != nil { return nil, fmt.Errorf("failed to read CA file %s: %w", caFilePath, err) } config.TLSClientConfig = rest.TLSClientConfig{CAData: caData} } return createClientFromConfig(config) } // WatchAll starts namespace-specific controllers for all relevant kinds. func (c *clientWrapper) WatchAll(namespaces []string, stopCh <-chan struct{}) (<-chan interface{}, error) { eventCh := make(chan interface{}, 1) eventHandler := &k8s.ResourceEventHandler{Ev: eventCh} if len(namespaces) == 0 { namespaces = []string{metav1.NamespaceAll} c.isNamespaceAll = true } c.watchedNamespaces = namespaces notOwnedByHelm := func(opts *metav1.ListOptions) { opts.LabelSelector = "owner!=helm" } matchesLabelSelector := func(opts *metav1.ListOptions) { opts.LabelSelector = c.labelSelector } for _, ns := range namespaces { factoryCrd := traefikinformers.NewSharedInformerFactoryWithOptions(c.csCrd, resyncPeriod, traefikinformers.WithNamespace(ns), traefikinformers.WithTweakListOptions(matchesLabelSelector)) _, err := factoryCrd.Traefik().V1alpha1().IngressRoutes().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryCrd.Traefik().V1alpha1().Middlewares().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryCrd.Traefik().V1alpha1().MiddlewareTCPs().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryCrd.Traefik().V1alpha1().IngressRouteTCPs().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryCrd.Traefik().V1alpha1().IngressRouteUDPs().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryCrd.Traefik().V1alpha1().TLSOptions().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryCrd.Traefik().V1alpha1().ServersTransports().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryCrd.Traefik().V1alpha1().ServersTransportTCPs().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryCrd.Traefik().V1alpha1().TLSStores().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryCrd.Traefik().V1alpha1().TraefikServices().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } factoryKube := kinformers.NewSharedInformerFactoryWithOptions(c.csKube, resyncPeriod, kinformers.WithNamespace(ns)) _, err = factoryKube.Core().V1().Services().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryKube.Discovery().V1().EndpointSlices().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } _, err = factoryKube.Core().V1().ConfigMaps().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } factorySecret := kinformers.NewSharedInformerFactoryWithOptions(c.csKube, resyncPeriod, kinformers.WithNamespace(ns), kinformers.WithTweakListOptions(notOwnedByHelm)) _, err = factorySecret.Core().V1().Secrets().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } c.factoriesCrd[ns] = factoryCrd c.factoriesKube[ns] = factoryKube c.factoriesSecret[ns] = factorySecret } for _, ns := range namespaces { c.factoriesCrd[ns].Start(stopCh) c.factoriesKube[ns].Start(stopCh) c.factoriesSecret[ns].Start(stopCh) } for _, ns := range namespaces { for t, ok := range c.factoriesCrd[ns].WaitForCacheSync(stopCh) { if !ok { return nil, fmt.Errorf("timed out waiting for controller caches to sync %s in namespace %q", t.String(), ns) } } for t, ok := range c.factoriesKube[ns].WaitForCacheSync(stopCh) { if !ok { return nil, fmt.Errorf("timed out waiting for controller caches to sync %s in namespace %q", t.String(), ns) } } for t, ok := range c.factoriesSecret[ns].WaitForCacheSync(stopCh) { if !ok { return nil, fmt.Errorf("timed out waiting for controller caches to sync %s in namespace %q", t.String(), ns) } } } if !c.disableClusterScopeInformer { c.clusterScopeFactory = kinformers.NewSharedInformerFactory(c.csKube, resyncPeriod) _, err := c.clusterScopeFactory.Core().V1().Nodes().Informer().AddEventHandler(eventHandler) if err != nil { return nil, err } c.clusterScopeFactory.Start(stopCh) for t, ok := range c.clusterScopeFactory.WaitForCacheSync(stopCh) { if !ok { return nil, fmt.Errorf("timed out waiting for controller caches to sync %s", t.String()) } } } return eventCh, nil } func (c *clientWrapper) GetIngressRoutes() []*traefikv1alpha1.IngressRoute { var result []*traefikv1alpha1.IngressRoute for ns, factory := range c.factoriesCrd { ings, err := factory.Traefik().V1alpha1().IngressRoutes().Lister().List(labels.Everything()) if err != nil { log.Error().Err(err).Msgf("Failed to list ingress routes in namespace %s", ns) } result = append(result, ings...) } return result } func (c *clientWrapper) GetIngressRouteTCPs() []*traefikv1alpha1.IngressRouteTCP { var result []*traefikv1alpha1.IngressRouteTCP for ns, factory := range c.factoriesCrd { ings, err := factory.Traefik().V1alpha1().IngressRouteTCPs().Lister().List(labels.Everything()) if err != nil { log.Error().Err(err).Msgf("Failed to list tcp ingress routes in namespace %s", ns) } result = append(result, ings...) } return result } func (c *clientWrapper) GetIngressRouteUDPs() []*traefikv1alpha1.IngressRouteUDP { var result []*traefikv1alpha1.IngressRouteUDP for ns, factory := range c.factoriesCrd { ings, err := factory.Traefik().V1alpha1().IngressRouteUDPs().Lister().List(labels.Everything()) if err != nil { log.Error().Err(err).Msgf("Failed to list udp ingress routes in namespace %s", ns) } result = append(result, ings...) } return result } func (c *clientWrapper) GetMiddlewares() []*traefikv1alpha1.Middleware { var result []*traefikv1alpha1.Middleware for ns, factory := range c.factoriesCrd { middlewares, err := factory.Traefik().V1alpha1().Middlewares().Lister().List(labels.Everything()) if err != nil { log.Error().Err(err).Msgf("Failed to list middlewares in namespace %s", ns) } result = append(result, middlewares...) } return result } func (c *clientWrapper) GetMiddlewareTCPs() []*traefikv1alpha1.MiddlewareTCP { var result []*traefikv1alpha1.MiddlewareTCP for ns, factory := range c.factoriesCrd { middlewares, err := factory.Traefik().V1alpha1().MiddlewareTCPs().Lister().List(labels.Everything()) if err != nil { log.Error().Err(err).Msgf("Failed to list TCP middlewares in namespace %s", ns) } result = append(result, middlewares...) } return result } // GetTraefikService returns the named service from the given namespace. func (c *clientWrapper) GetTraefikService(namespace, name string) (*traefikv1alpha1.TraefikService, bool, error) { if !c.isWatchedNamespace(namespace) { return nil, false, fmt.Errorf("failed to get service %s/%s: namespace is not within watched namespaces", namespace, name) } service, err := c.factoriesCrd[c.lookupNamespace(namespace)].Traefik().V1alpha1().TraefikServices().Lister().TraefikServices(namespace).Get(name) exist, err := translateNotFoundError(err) return service, exist, err } func (c *clientWrapper) GetTraefikServices() []*traefikv1alpha1.TraefikService { var result []*traefikv1alpha1.TraefikService for ns, factory := range c.factoriesCrd { traefikServices, err := factory.Traefik().V1alpha1().TraefikServices().Lister().List(labels.Everything()) if err != nil { log.Error().Err(err).Msgf("Failed to list Traefik services in namespace %s", ns) } result = append(result, traefikServices...) } return result } // GetServersTransports returns all ServersTransport. func (c *clientWrapper) GetServersTransports() []*traefikv1alpha1.ServersTransport { var result []*traefikv1alpha1.ServersTransport for ns, factory := range c.factoriesCrd { serversTransports, err := factory.Traefik().V1alpha1().ServersTransports().Lister().List(labels.Everything()) if err != nil { log.Error().Err(err).Str("namespace", ns).Msg("Failed to list servers transport in namespace") } result = append(result, serversTransports...) } return result } // GetServersTransportTCPs returns all ServersTransportTCP. func (c *clientWrapper) GetServersTransportTCPs() []*traefikv1alpha1.ServersTransportTCP { var result []*traefikv1alpha1.ServersTransportTCP for ns, factory := range c.factoriesCrd { serversTransports, err := factory.Traefik().V1alpha1().ServersTransportTCPs().Lister().List(labels.Everything()) if err != nil { log.Error().Err(err).Str("namespace", ns).Msg("Failed to list servers transport TCP in namespace") } result = append(result, serversTransports...) } return result } // GetTLSOptions returns all TLS options. func (c *clientWrapper) GetTLSOptions() []*traefikv1alpha1.TLSOption { var result []*traefikv1alpha1.TLSOption for ns, factory := range c.factoriesCrd { options, err := factory.Traefik().V1alpha1().TLSOptions().Lister().List(labels.Everything()) if err != nil { log.Error().Err(err).Msgf("Failed to list tls options in namespace %s", ns) } result = append(result, options...) } return result } // GetTLSStores returns all TLS stores. func (c *clientWrapper) GetTLSStores() []*traefikv1alpha1.TLSStore { var result []*traefikv1alpha1.TLSStore for ns, factory := range c.factoriesCrd { stores, err := factory.Traefik().V1alpha1().TLSStores().Lister().List(labels.Everything()) if err != nil { log.Error().Err(err).Msgf("Failed to list tls stores in namespace %s", ns) } result = append(result, stores...) } return result } // GetService returns the named service from the given namespace. func (c *clientWrapper) GetService(namespace, name string) (*corev1.Service, bool, error) { if !c.isWatchedNamespace(namespace) { return nil, false, fmt.Errorf("failed to get service %s/%s: namespace is not within watched namespaces", namespace, name) } service, err := c.factoriesKube[c.lookupNamespace(namespace)].Core().V1().Services().Lister().Services(namespace).Get(name) exist, err := translateNotFoundError(err) return service, exist, err } // GetEndpointSlicesForService returns the EndpointSlices for the given service name in the given namespace. func (c *clientWrapper) GetEndpointSlicesForService(namespace, serviceName string) ([]*discoveryv1.EndpointSlice, error) { if !c.isWatchedNamespace(namespace) { return nil, fmt.Errorf("failed to get endpointslices for service %s/%s: namespace is not within watched namespaces", namespace, serviceName) } serviceLabelRequirement, err := labels.NewRequirement(discoveryv1.LabelServiceName, selection.Equals, []string{serviceName}) if err != nil { return nil, fmt.Errorf("failed to create service label selector requirement: %w", err) } serviceSelector := labels.NewSelector() serviceSelector = serviceSelector.Add(*serviceLabelRequirement) return c.factoriesKube[c.lookupNamespace(namespace)].Discovery().V1().EndpointSlices().Lister().EndpointSlices(namespace).List(serviceSelector) } // GetSecret returns the named secret from the given namespace. func (c *clientWrapper) GetSecret(namespace, name string) (*corev1.Secret, bool, error) { if !c.isWatchedNamespace(namespace) { return nil, false, fmt.Errorf("failed to get secret %s/%s: namespace is not within watched namespaces", namespace, name) } secret, err := c.factoriesSecret[c.lookupNamespace(namespace)].Core().V1().Secrets().Lister().Secrets(namespace).Get(name) exist, err := translateNotFoundError(err) return secret, exist, err } // GetConfigMap returns the named config map from the given namespace. func (c *clientWrapper) GetConfigMap(namespace, name string) (*corev1.ConfigMap, bool, error) { if !c.isWatchedNamespace(namespace) { return nil, false, fmt.Errorf("failed to get config map %s/%s: namespace is not within watched namespaces", namespace, name) } configMap, err := c.factoriesKube[c.lookupNamespace(namespace)].Core().V1().ConfigMaps().Lister().ConfigMaps(namespace).Get(name) exist, err := translateNotFoundError(err) return configMap, exist, err } func (c *clientWrapper) GetNodes() ([]*corev1.Node, bool, error) { nodes, err := c.clusterScopeFactory.Core().V1().Nodes().Lister().List(labels.Everything()) exist, err := translateNotFoundError(err) return nodes, exist, err } // lookupNamespace returns the lookup namespace key for the given namespace. // When listening on all namespaces, it returns the client-go identifier ("") // for all-namespaces. Otherwise, it returns the given namespace. // The distinction is necessary because we index all informers on the special // identifier iff all-namespaces are requested but receive specific namespace // identifiers from the Kubernetes API, so we have to bridge this gap. func (c *clientWrapper) lookupNamespace(ns string) string { if c.isNamespaceAll { return metav1.NamespaceAll } return ns } // isWatchedNamespace checks to ensure that the namespace is being watched before we request // it to ensure we don't panic by requesting an out-of-watch object. func (c *clientWrapper) isWatchedNamespace(ns string) bool { if c.isNamespaceAll { return true } return slices.Contains(c.watchedNamespaces, ns) } // translateNotFoundError will translate a "not found" error to a boolean return // value which indicates if the resource exists and a nil error. func translateNotFoundError(err error) (bool, error) { if kerror.IsNotFound(err) { return false, nil } return err == nil, err }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/crd/kubernetes_udp.go
pkg/provider/kubernetes/crd/kubernetes_udp.go
package crd import ( "context" "errors" "fmt" "net" "strconv" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/dynamic" traefikv1alpha1 "github.com/traefik/traefik/v3/pkg/provider/kubernetes/crd/traefikio/v1alpha1" corev1 "k8s.io/api/core/v1" ) func (p *Provider) loadIngressRouteUDPConfiguration(ctx context.Context, client Client) *dynamic.UDPConfiguration { conf := &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, } for _, ingressRouteUDP := range client.GetIngressRouteUDPs() { logger := log.Ctx(ctx).With().Str("ingress", ingressRouteUDP.Name).Str("namespace", ingressRouteUDP.Namespace).Logger() if !shouldProcessIngress(p.IngressClass, ingressRouteUDP.Annotations[annotationKubernetesIngressClass]) { continue } ingressName := ingressRouteUDP.Name if len(ingressName) == 0 { ingressName = ingressRouteUDP.GenerateName } for i, route := range ingressRouteUDP.Spec.Routes { key := fmt.Sprintf("%s-%d", ingressName, i) serviceName := makeID(ingressRouteUDP.Namespace, key) for _, service := range route.Services { balancerServerUDP, err := p.createLoadBalancerServerUDP(client, ingressRouteUDP.Namespace, service) if err != nil { logger.Error(). Str("serviceName", service.Name). Stringer("servicePort", &service.Port). Err(err). Msg("Cannot create service") continue } // If there is only one service defined, we skip the creation of the load balancer of services, // i.e. the service on top is directly a load balancer of servers. if len(route.Services) == 1 { conf.Services[serviceName] = balancerServerUDP break } serviceKey := fmt.Sprintf("%s-%s-%s", serviceName, service.Name, &service.Port) conf.Services[serviceKey] = balancerServerUDP srv := dynamic.UDPWRRService{Name: serviceKey} srv.SetDefaults() if service.Weight != nil { srv.Weight = service.Weight } if conf.Services[serviceName] == nil { conf.Services[serviceName] = &dynamic.UDPService{Weighted: &dynamic.UDPWeightedRoundRobin{}} } conf.Services[serviceName].Weighted.Services = append(conf.Services[serviceName].Weighted.Services, srv) } conf.Routers[serviceName] = &dynamic.UDPRouter{ EntryPoints: ingressRouteUDP.Spec.EntryPoints, Service: serviceName, } } } return conf } func (p *Provider) createLoadBalancerServerUDP(client Client, parentNamespace string, service traefikv1alpha1.ServiceUDP) (*dynamic.UDPService, error) { ns := parentNamespace if len(service.Namespace) > 0 { if !isNamespaceAllowed(p.AllowCrossNamespace, parentNamespace, service.Namespace) { return nil, fmt.Errorf("udp service %s/%s is not in the parent resource namespace %s", service.Namespace, service.Name, ns) } ns = service.Namespace } servers, err := p.loadUDPServers(client, ns, service) if err != nil { return nil, err } udpService := &dynamic.UDPService{ LoadBalancer: &dynamic.UDPServersLoadBalancer{ Servers: servers, }, } return udpService, nil } func (p *Provider) loadUDPServers(client Client, namespace string, svc traefikv1alpha1.ServiceUDP) ([]dynamic.UDPServer, error) { service, exists, err := client.GetService(namespace, svc.Name) if err != nil { return nil, err } if !exists { return nil, errors.New("service not found") } if service.Spec.Type == corev1.ServiceTypeExternalName && !p.AllowExternalNameServices { return nil, fmt.Errorf("externalName services not allowed: %s/%s", namespace, svc.Name) } svcPort, err := getServicePort(service, svc.Port) if err != nil { return nil, err } var servers []dynamic.UDPServer if service.Spec.Type == corev1.ServiceTypeNodePort && svc.NodePortLB { if p.DisableClusterScopeResources { return nil, errors.New("nodes lookup is disabled") } nodes, nodesExists, nodesErr := client.GetNodes() if nodesErr != nil { return nil, nodesErr } if !nodesExists || len(nodes) == 0 { return nil, fmt.Errorf("nodes not found for NodePort service %s/%s", svc.Namespace, svc.Name) } for _, node := range nodes { for _, addr := range node.Status.Addresses { if addr.Type == corev1.NodeInternalIP { servers = append(servers, dynamic.UDPServer{ Address: net.JoinHostPort(addr.Address, strconv.Itoa(int(svcPort.NodePort))), }) } } } if len(servers) == 0 { return nil, fmt.Errorf("no servers were generated for service %s/%s", svc.Namespace, svc.Name) } return servers, nil } if service.Spec.Type == corev1.ServiceTypeExternalName { servers = append(servers, dynamic.UDPServer{ Address: net.JoinHostPort(service.Spec.ExternalName, strconv.Itoa(int(svcPort.Port))), }) } else { nativeLB := p.NativeLBByDefault if svc.NativeLB != nil { nativeLB = *svc.NativeLB } if nativeLB { address, err := getNativeServiceAddress(*service, *svcPort) if err != nil { return nil, fmt.Errorf("getting native Kubernetes Service address: %w", err) } return []dynamic.UDPServer{{Address: address}}, nil } endpointSlices, err := client.GetEndpointSlicesForService(namespace, svc.Name) if err != nil { return nil, fmt.Errorf("getting endpointslices: %w", err) } addresses := map[string]struct{}{} for _, endpointSlice := range endpointSlices { var port int32 for _, p := range endpointSlice.Ports { if svcPort.Name == *p.Name { port = *p.Port break } } if port == 0 { continue } for _, endpoint := range endpointSlice.Endpoints { if endpoint.Conditions.Ready == nil || !*endpoint.Conditions.Ready { continue } for _, address := range endpoint.Addresses { if _, ok := addresses[address]; ok { continue } addresses[address] = struct{}{} servers = append(servers, dynamic.UDPServer{ Address: net.JoinHostPort(address, strconv.Itoa(int(port))), }) } } } } if len(servers) == 0 && !p.AllowEmptyServices { return nil, fmt.Errorf("no servers found for %s/%s", namespace, svc.Name) } return servers, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/crd/client_test.go
pkg/provider/kubernetes/crd/client_test.go
package crd import ( "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" traefikcrdfake "github.com/traefik/traefik/v3/pkg/provider/kubernetes/crd/generated/clientset/versioned/fake" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" kubefake "k8s.io/client-go/kubernetes/fake" ) func TestClientIgnoresHelmOwnedSecrets(t *testing.T) { secret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Namespace: "default", Name: "secret", }, } helmSecret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Namespace: "default", Name: "helm-secret", Labels: map[string]string{ "owner": "helm", }, }, } kubeClient := kubefake.NewSimpleClientset(helmSecret, secret) crdClient := traefikcrdfake.NewSimpleClientset() client := newClientImpl(kubeClient, crdClient) stopCh := make(chan struct{}) eventCh, err := client.WatchAll(nil, stopCh) require.NoError(t, err) select { case event := <-eventCh: secret, ok := event.(*corev1.Secret) require.True(t, ok) assert.NotEqual(t, "helm-secret", secret.Name) case <-time.After(50 * time.Millisecond): assert.Fail(t, "expected to receive event for secret") } select { case <-eventCh: assert.Fail(t, "received more than one event") case <-time.After(50 * time.Millisecond): } _, found, err := client.GetSecret("default", "secret") require.NoError(t, err) assert.True(t, found) _, found, err = client.GetSecret("default", "helm-secret") require.NoError(t, err) assert.False(t, found) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/crd/kubernetes_http.go
pkg/provider/kubernetes/crd/kubernetes_http.go
package crd import ( "context" "errors" "fmt" "net" "strconv" "strings" "github.com/rs/zerolog/log" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/provider" traefikv1alpha1 "github.com/traefik/traefik/v3/pkg/provider/kubernetes/crd/traefikio/v1alpha1" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/k8s" "github.com/traefik/traefik/v3/pkg/tls" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/utils/ptr" ) const ( httpsProtocol = "https" httpProtocol = "http" ) func (p *Provider) loadIngressRouteConfiguration(ctx context.Context, client Client, tlsConfigs map[string]*tls.CertAndStores) *dynamic.HTTPConfiguration { conf := &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, } for _, ingressRoute := range client.GetIngressRoutes() { logger := log.Ctx(ctx).With().Str("ingress", ingressRoute.Name).Str("namespace", ingressRoute.Namespace).Logger() // TODO keep the name ingressClass? if !shouldProcessIngress(p.IngressClass, ingressRoute.Annotations[annotationKubernetesIngressClass]) { continue } err := getTLSHTTP(ctx, ingressRoute, client, tlsConfigs) if err != nil { logger.Error().Err(err).Msg("Error configuring TLS") } ingressName := ingressRoute.Name if len(ingressName) == 0 { ingressName = ingressRoute.GenerateName } cb := configBuilder{ client: client, allowCrossNamespace: p.AllowCrossNamespace, allowExternalNameServices: p.AllowExternalNameServices, allowEmptyServices: p.AllowEmptyServices, nativeLBByDefault: p.NativeLBByDefault, disableClusterScopeResources: p.DisableClusterScopeResources, } parentRouterNames, err := resolveParentRouterNames(client, ingressRoute, p.AllowCrossNamespace) if err != nil { logger.Error().Err(err).Msg("Error resolving parent routers") continue } for _, route := range ingressRoute.Spec.Routes { if len(route.Kind) > 0 && route.Kind != "Rule" { logger.Error().Msgf("Unsupported match kind: %s. Only \"Rule\" is supported for now.", route.Kind) continue } if len(route.Match) == 0 { logger.Error().Msg("Empty match rule") continue } serviceKey := makeServiceKey(route.Match, ingressName) mds, err := p.makeMiddlewareKeys(ctx, ingressRoute.Namespace, route.Middlewares) if err != nil { logger.Error().Err(err).Msg("Failed to create middleware keys") continue } normalized := provider.Normalize(makeID(ingressRoute.Namespace, serviceKey)) serviceName := normalized switch { case len(route.Services) > 1: spec := traefikv1alpha1.TraefikServiceSpec{ Weighted: &traefikv1alpha1.WeightedRoundRobin{ Services: route.Services, }, } errBuild := cb.buildServicesLB(ctx, ingressRoute.Namespace, spec, serviceName, conf.Services) if errBuild != nil { logger.Error().Err(errBuild).Send() continue } case len(route.Services) == 1: fullName, serversLB, err := cb.nameAndService(ctx, ingressRoute.Namespace, route.Services[0].LoadBalancerSpec) if err != nil { logger.Error().Err(err).Send() continue } if serversLB != nil { conf.Services[serviceName] = serversLB } else { serviceName = fullName } default: // Routes without services leave serviceName empty. serviceName = "" } r := &dynamic.Router{ Middlewares: mds, Priority: route.Priority, RuleSyntax: route.Syntax, EntryPoints: ingressRoute.Spec.EntryPoints, Rule: route.Match, Service: serviceName, Observability: route.Observability, ParentRefs: parentRouterNames, } if ingressRoute.Spec.TLS != nil { r.TLS = &dynamic.RouterTLSConfig{ CertResolver: ingressRoute.Spec.TLS.CertResolver, Domains: ingressRoute.Spec.TLS.Domains, } if ingressRoute.Spec.TLS.Options != nil && len(ingressRoute.Spec.TLS.Options.Name) > 0 { tlsOptionsName := ingressRoute.Spec.TLS.Options.Name // Is a Kubernetes CRD reference, (i.e. not a cross-provider reference) ns := ingressRoute.Spec.TLS.Options.Namespace if !strings.Contains(tlsOptionsName, providerNamespaceSeparator) { if len(ns) == 0 { ns = ingressRoute.Namespace } tlsOptionsName = makeID(ns, tlsOptionsName) } else if len(ns) > 0 { logger. Warn().Str("TLSOption", ingressRoute.Spec.TLS.Options.Name). Msgf("Namespace %q is ignored in cross-provider context", ns) } if !isNamespaceAllowed(p.AllowCrossNamespace, ingressRoute.Namespace, ns) { logger.Error().Msgf("TLSOption %s/%s is not in the IngressRoute namespace %s", ns, ingressRoute.Spec.TLS.Options.Name, ingressRoute.Namespace) continue } r.TLS.Options = tlsOptionsName } } p.applyRouterTransform(ctx, r, ingressRoute) conf.Routers[normalized] = r } } return conf } func (p *Provider) makeMiddlewareKeys(ctx context.Context, ingRouteNamespace string, middlewares []traefikv1alpha1.MiddlewareRef) ([]string, error) { var mds []string for _, mi := range middlewares { name := mi.Name if !p.AllowCrossNamespace && strings.HasSuffix(mi.Name, providerNamespaceSeparator+providerName) { // Since we are not able to know if another namespace is in the name (namespace-name@kubernetescrd), // if the provider namespace kubernetescrd is used, // we don't allow this format to avoid cross namespace references. return nil, fmt.Errorf("invalid reference to middleware %s: with crossnamespace disallowed, the namespace field needs to be explicitly specified", mi.Name) } if strings.Contains(name, providerNamespaceSeparator) { if len(mi.Namespace) > 0 { log.Ctx(ctx). Warn().Str(logs.MiddlewareName, mi.Name). Msgf("namespace %q is ignored in cross-provider context", mi.Namespace) } mds = append(mds, name) continue } ns := ingRouteNamespace if len(mi.Namespace) > 0 { if !isNamespaceAllowed(p.AllowCrossNamespace, ingRouteNamespace, mi.Namespace) { return nil, fmt.Errorf("middleware %s/%s is not in the IngressRoute namespace %s", mi.Namespace, mi.Name, ingRouteNamespace) } ns = mi.Namespace } mds = append(mds, provider.Normalize(makeID(ns, name))) } return mds, nil } // resolveParentRouterNames resolves parent IngressRoute references to router names. // It returns the list of parent router names and an error if one occurred during processing. func resolveParentRouterNames(client Client, ingressRoute *traefikv1alpha1.IngressRoute, allowCrossNamespace bool) ([]string, error) { // If no parent refs, return empty list (not an error). if len(ingressRoute.Spec.ParentRefs) == 0 { return nil, nil } var parentRouterNames []string for _, parentRef := range ingressRoute.Spec.ParentRefs { // Determine parent namespace (default to child namespace if not specified). parentNamespace := parentRef.Namespace if parentNamespace == "" { parentNamespace = ingressRoute.Namespace } // Validate cross-namespace access. if !isNamespaceAllowed(allowCrossNamespace, ingressRoute.Namespace, parentNamespace) { return nil, fmt.Errorf("cross-namespace reference to parent IngressRoute %s/%s not allowed", parentNamespace, parentRef.Name) } var parentIngressRoute *traefikv1alpha1.IngressRoute for _, ir := range client.GetIngressRoutes() { if ir.Name == parentRef.Name && ir.Namespace == parentNamespace { parentIngressRoute = ir break } } if parentIngressRoute == nil { return nil, fmt.Errorf("parent IngressRoute %s/%s does not exist", parentNamespace, parentRef.Name) } // Compute router names for all routes in parent IngressRoute. for _, route := range parentIngressRoute.Spec.Routes { serviceKey := makeServiceKey(route.Match, parentIngressRoute.Name) routerName := provider.Normalize(makeID(parentIngressRoute.Namespace, serviceKey)) parentRouterNames = append(parentRouterNames, routerName) } } return parentRouterNames, nil } type configBuilder struct { client Client allowCrossNamespace bool allowExternalNameServices bool allowEmptyServices bool nativeLBByDefault bool disableClusterScopeResources bool } // buildTraefikService creates the configuration for the traefik service defined in tService, // and adds it to the given conf map. func (c configBuilder) buildTraefikService(ctx context.Context, tService *traefikv1alpha1.TraefikService, conf map[string]*dynamic.Service) error { id := provider.Normalize(makeID(tService.Namespace, tService.Name)) switch { case tService.Spec.Weighted != nil: return c.buildServicesLB(ctx, tService.Namespace, tService.Spec, id, conf) case tService.Spec.Mirroring != nil: return c.buildMirroring(ctx, tService, id, conf) case tService.Spec.HighestRandomWeight != nil: return c.buildHRW(ctx, tService, id, conf) default: return errors.New("unspecified service type") } } // buildServicesLB creates the configuration for the load-balancer of services named id, and defined in tService. // It adds it to the given conf map. func (c configBuilder) buildServicesLB(ctx context.Context, namespace string, tService traefikv1alpha1.TraefikServiceSpec, id string, conf map[string]*dynamic.Service) error { var wrrServices []dynamic.WRRService for _, service := range tService.Weighted.Services { fullName, k8sService, err := c.nameAndService(ctx, namespace, service.LoadBalancerSpec) if err != nil { return err } if k8sService != nil { conf[fullName] = k8sService } weight := service.Weight if weight == nil { weight = func(i int) *int { return &i }(1) } wrrServices = append(wrrServices, dynamic.WRRService{ Name: fullName, Weight: weight, }) } var sticky *dynamic.Sticky if tService.Weighted.Sticky != nil && tService.Weighted.Sticky.Cookie != nil { sticky = &dynamic.Sticky{ Cookie: &dynamic.Cookie{ Name: tService.Weighted.Sticky.Cookie.Name, Secure: tService.Weighted.Sticky.Cookie.Secure, HTTPOnly: tService.Weighted.Sticky.Cookie.HTTPOnly, SameSite: tService.Weighted.Sticky.Cookie.SameSite, MaxAge: tService.Weighted.Sticky.Cookie.MaxAge, Domain: tService.Weighted.Sticky.Cookie.Domain, }, } sticky.Cookie.SetDefaults() if tService.Weighted.Sticky.Cookie.Path != nil { sticky.Cookie.Path = tService.Weighted.Sticky.Cookie.Path } } conf[id] = &dynamic.Service{ Weighted: &dynamic.WeightedRoundRobin{ Services: wrrServices, Sticky: sticky, }, } return nil } // buildMirroring creates the configuration for the mirroring service named id, and defined by tService. // It adds it to the given conf map. func (c configBuilder) buildMirroring(ctx context.Context, tService *traefikv1alpha1.TraefikService, id string, conf map[string]*dynamic.Service) error { fullNameMain, k8sService, err := c.nameAndService(ctx, tService.Namespace, tService.Spec.Mirroring.LoadBalancerSpec) if err != nil { return err } if k8sService != nil { conf[fullNameMain] = k8sService } var mirrorServices []dynamic.MirrorService for _, mirror := range tService.Spec.Mirroring.Mirrors { mirroredName, k8sService, err := c.nameAndService(ctx, tService.Namespace, mirror.LoadBalancerSpec) if err != nil { return err } if k8sService != nil { conf[mirroredName] = k8sService } mirrorServices = append(mirrorServices, dynamic.MirrorService{ Name: mirroredName, Percent: mirror.Percent, }) } conf[id] = &dynamic.Service{ Mirroring: &dynamic.Mirroring{ Service: fullNameMain, Mirrors: mirrorServices, MirrorBody: tService.Spec.Mirroring.MirrorBody, MaxBodySize: tService.Spec.Mirroring.MaxBodySize, }, } return nil } // buildServersLB creates the configuration for the load-balancer of servers defined by svc. func (c configBuilder) buildServersLB(namespace string, svc traefikv1alpha1.LoadBalancerSpec) (*dynamic.Service, error) { lb := &dynamic.ServersLoadBalancer{} lb.SetDefaults() // This is required by the tests as the fake client does not apply default values. // TODO: remove this when the fake client apply default values. if svc.Strategy != "" { switch svc.Strategy { case dynamic.BalancerStrategyWRR, dynamic.BalancerStrategyP2C, dynamic.BalancerStrategyHRW, dynamic.BalancerStrategyLeastTime: lb.Strategy = svc.Strategy // Here we are just logging a warning as the default value is already applied. case "RoundRobin": log.Warn(). Str("namespace", namespace). Str("service", svc.Name). Msgf("RoundRobin strategy value is deprecated, please use %s value instead", dynamic.BalancerStrategyWRR) default: return nil, fmt.Errorf("load-balancer strategy %s is not supported", svc.Strategy) } } servers, err := c.loadServers(namespace, svc) if err != nil { return nil, err } lb.Servers = servers if svc.HealthCheck != nil { lb.HealthCheck = &dynamic.ServerHealthCheck{ Scheme: svc.HealthCheck.Scheme, Path: svc.HealthCheck.Path, Method: svc.HealthCheck.Method, Status: svc.HealthCheck.Status, Port: svc.HealthCheck.Port, Hostname: svc.HealthCheck.Hostname, Headers: svc.HealthCheck.Headers, } lb.HealthCheck.SetDefaults() if svc.HealthCheck.FollowRedirects != nil { lb.HealthCheck.FollowRedirects = svc.HealthCheck.FollowRedirects } if svc.HealthCheck.Mode != "http" { lb.HealthCheck.Mode = svc.HealthCheck.Mode } if svc.HealthCheck.Interval != nil { if err := lb.HealthCheck.Interval.Set(svc.HealthCheck.Interval.String()); err != nil { return nil, err } } // If the UnhealthyInterval option is not set, we use the Interval option value, // to check the unhealthy targets as often as the healthy ones. if svc.HealthCheck.UnhealthyInterval == nil { lb.HealthCheck.UnhealthyInterval = &lb.HealthCheck.Interval } else { var unhealthyInterval ptypes.Duration if err := unhealthyInterval.Set(svc.HealthCheck.UnhealthyInterval.String()); err != nil { return nil, err } lb.HealthCheck.UnhealthyInterval = &unhealthyInterval } if svc.HealthCheck.Timeout != nil { if err := lb.HealthCheck.Timeout.Set(svc.HealthCheck.Timeout.String()); err != nil { return nil, err } } } if svc.PassiveHealthCheck != nil { lb.PassiveHealthCheck = &dynamic.PassiveServerHealthCheck{} lb.PassiveHealthCheck.SetDefaults() if svc.PassiveHealthCheck.MaxFailedAttempts != nil { lb.PassiveHealthCheck.MaxFailedAttempts = *svc.PassiveHealthCheck.MaxFailedAttempts } if svc.PassiveHealthCheck.FailureWindow != nil { if err := lb.PassiveHealthCheck.FailureWindow.Set(svc.PassiveHealthCheck.FailureWindow.String()); err != nil { return nil, err } } } conf := svc lb.PassHostHeader = conf.PassHostHeader if lb.PassHostHeader == nil { passHostHeader := true lb.PassHostHeader = &passHostHeader } if conf.ResponseForwarding != nil && conf.ResponseForwarding.FlushInterval != "" { err := lb.ResponseForwarding.FlushInterval.Set(conf.ResponseForwarding.FlushInterval) if err != nil { return nil, fmt.Errorf("unable to parse flushInterval: %w", err) } } if svc.Sticky != nil && svc.Sticky.Cookie != nil { lb.Sticky = &dynamic.Sticky{ Cookie: &dynamic.Cookie{ Name: svc.Sticky.Cookie.Name, Secure: svc.Sticky.Cookie.Secure, HTTPOnly: svc.Sticky.Cookie.HTTPOnly, SameSite: svc.Sticky.Cookie.SameSite, MaxAge: svc.Sticky.Cookie.MaxAge, Domain: svc.Sticky.Cookie.Domain, }, } lb.Sticky.Cookie.SetDefaults() if svc.Sticky.Cookie.Path != nil { lb.Sticky.Cookie.Path = svc.Sticky.Cookie.Path } } lb.ServersTransport, err = c.makeServersTransportKey(namespace, svc.ServersTransport) if err != nil { return nil, err } return &dynamic.Service{LoadBalancer: lb}, nil } func (c configBuilder) makeServersTransportKey(parentNamespace string, serversTransportName string) (string, error) { if serversTransportName == "" { return "", nil } if !c.allowCrossNamespace && strings.HasSuffix(serversTransportName, providerNamespaceSeparator+providerName) { // Since we are not able to know if another namespace is in the name (namespace-name@kubernetescrd), // if the provider namespace kubernetescrd is used, // we don't allow this format to avoid cross namespace references. return "", fmt.Errorf("invalid reference to serversTransport %s: namespace-name@kubernetescrd format is not allowed when crossnamespace is disallowed", serversTransportName) } if strings.Contains(serversTransportName, providerNamespaceSeparator) { return serversTransportName, nil } return provider.Normalize(makeID(parentNamespace, serversTransportName)), nil } func (c configBuilder) loadServers(parentNamespace string, svc traefikv1alpha1.LoadBalancerSpec) ([]dynamic.Server, error) { namespace := namespaceOrFallback(svc, parentNamespace) if !isNamespaceAllowed(c.allowCrossNamespace, parentNamespace, namespace) { return nil, fmt.Errorf("load balancer service %s/%s is not in the parent resource namespace %s", svc.Namespace, svc.Name, parentNamespace) } // If the service uses explicitly the provider suffix sanitizedName := strings.TrimSuffix(svc.Name, providerNamespaceSeparator+providerName) service, exists, err := c.client.GetService(namespace, sanitizedName) if err != nil { return nil, err } if !exists { return nil, fmt.Errorf("kubernetes service not found: %s/%s", namespace, sanitizedName) } svcPort, err := getServicePort(service, svc.Port) if err != nil { return nil, err } if service.Spec.Type != corev1.ServiceTypeExternalName && svc.HealthCheck != nil { return nil, fmt.Errorf("healthCheck allowed only for ExternalName services: %s/%s", namespace, sanitizedName) } if service.Spec.Type == corev1.ServiceTypeExternalName { if !c.allowExternalNameServices { return nil, fmt.Errorf("externalName services not allowed: %s/%s", namespace, sanitizedName) } protocol, err := parseServiceProtocol(svc.Scheme, svcPort.Name, svcPort.Port) if err != nil { return nil, err } hostPort := net.JoinHostPort(service.Spec.ExternalName, strconv.Itoa(int(svcPort.Port))) return []dynamic.Server{{URL: fmt.Sprintf("%s://%s", protocol, hostPort)}}, nil } nativeLB := c.nativeLBByDefault if svc.NativeLB != nil { nativeLB = *svc.NativeLB } if nativeLB { address, err := getNativeServiceAddress(*service, *svcPort) if err != nil { return nil, fmt.Errorf("getting native Kubernetes Service address: %w", err) } protocol, err := parseServiceProtocol(svc.Scheme, svcPort.Name, svcPort.Port) if err != nil { return nil, err } return []dynamic.Server{{URL: fmt.Sprintf("%s://%s", protocol, address)}}, nil } var servers []dynamic.Server if service.Spec.Type == corev1.ServiceTypeNodePort && svc.NodePortLB { if c.disableClusterScopeResources { return nil, errors.New("nodes lookup is disabled") } nodes, nodesExists, nodesErr := c.client.GetNodes() if nodesErr != nil { return nil, nodesErr } if !nodesExists || len(nodes) == 0 { return nil, fmt.Errorf("nodes not found for NodePort service %s/%s", namespace, sanitizedName) } protocol, err := parseServiceProtocol(svc.Scheme, svcPort.Name, svcPort.Port) if err != nil { return nil, err } for _, node := range nodes { for _, addr := range node.Status.Addresses { if addr.Type == corev1.NodeInternalIP { hostPort := net.JoinHostPort(addr.Address, strconv.Itoa(int(svcPort.NodePort))) servers = append(servers, dynamic.Server{ URL: fmt.Sprintf("%s://%s", protocol, hostPort), }) } } } if len(servers) == 0 { return nil, fmt.Errorf("no servers were generated for service %s in namespace", sanitizedName) } return servers, nil } endpointSlices, err := c.client.GetEndpointSlicesForService(namespace, sanitizedName) if err != nil { return nil, fmt.Errorf("getting endpointslices: %w", err) } addresses := map[string]struct{}{} for _, endpointSlice := range endpointSlices { var port int32 for _, p := range endpointSlice.Ports { if svcPort.Name == *p.Name { port = *p.Port break } } if port == 0 { continue } protocol, err := parseServiceProtocol(svc.Scheme, svcPort.Name, svcPort.Port) if err != nil { return nil, err } for _, endpoint := range endpointSlice.Endpoints { if !k8s.EndpointServing(endpoint) { continue } for _, address := range endpoint.Addresses { if _, ok := addresses[address]; ok { continue } addresses[address] = struct{}{} servers = append(servers, dynamic.Server{ URL: fmt.Sprintf("%s://%s", protocol, net.JoinHostPort(address, strconv.Itoa(int(port)))), Fenced: ptr.Deref(endpoint.Conditions.Terminating, false) && ptr.Deref(endpoint.Conditions.Serving, false), }) } } } if len(servers) == 0 && !c.allowEmptyServices { return nil, fmt.Errorf("no servers found for %s/%s", namespace, sanitizedName) } return servers, nil } // nameAndService returns the name that should be used for the svc service in the generated config. // In addition, if the service is a Kubernetes one, // it generates and returns the configuration part for such a service, // so that the caller can add it to the global config map. func (c configBuilder) nameAndService(ctx context.Context, parentNamespace string, service traefikv1alpha1.LoadBalancerSpec) (string, *dynamic.Service, error) { svcCtx := log.Ctx(ctx).With().Str(logs.ServiceName, service.Name).Logger().WithContext(ctx) namespace := namespaceOrFallback(service, parentNamespace) if !isNamespaceAllowed(c.allowCrossNamespace, parentNamespace, namespace) { return "", nil, fmt.Errorf("service %s/%s not in the parent resource namespace %s", service.Namespace, service.Name, parentNamespace) } switch service.Kind { case "", "Service": serversLB, err := c.buildServersLB(namespace, service) if err != nil { return "", nil, err } fullName := fullServiceName(svcCtx, namespace, service, service.Port) return fullName, serversLB, nil case "TraefikService": return fullServiceName(svcCtx, namespace, service, intstr.FromInt(0)), nil, nil default: return "", nil, fmt.Errorf("unsupported service kind %s", service.Kind) } } func (c configBuilder) buildHRW(ctx context.Context, tService *traefikv1alpha1.TraefikService, id string, conf map[string]*dynamic.Service) error { var hrwServices []dynamic.HRWService for _, hrwService := range tService.Spec.HighestRandomWeight.Services { hrwServiceName, k8sService, err := c.nameAndService(ctx, tService.Namespace, hrwService.LoadBalancerSpec) if err != nil { return err } if k8sService != nil { conf[hrwServiceName] = k8sService } weight := hrwService.Weight if weight == nil { weight = func(i int) *int { return &i }(1) } hrwServices = append(hrwServices, dynamic.HRWService{ Name: hrwServiceName, Weight: weight, }) } conf[id] = &dynamic.Service{ HighestRandomWeight: &dynamic.HighestRandomWeight{ Services: hrwServices, }, } return nil } func splitSvcNameProvider(name string) (string, string) { parts := strings.Split(name, providerNamespaceSeparator) svc := strings.Join(parts[:len(parts)-1], providerNamespaceSeparator) pvd := parts[len(parts)-1] return svc, pvd } func fullServiceName(ctx context.Context, namespace string, service traefikv1alpha1.LoadBalancerSpec, port intstr.IntOrString) string { if (port.Type == intstr.Int && port.IntVal != 0) || (port.Type == intstr.String && port.StrVal != "") { return provider.Normalize(fmt.Sprintf("%s-%s-%s", namespace, service.Name, &port)) } if !strings.Contains(service.Name, providerNamespaceSeparator) { return provider.Normalize(fmt.Sprintf("%s-%s", namespace, service.Name)) } name, pName := splitSvcNameProvider(service.Name) if pName == providerName { return provider.Normalize(fmt.Sprintf("%s-%s", namespace, name)) } if service.Namespace != "" { log.Ctx(ctx).Warn().Msgf("namespace %q is ignored in cross-provider context", service.Namespace) } return provider.Normalize(name) + providerNamespaceSeparator + pName } func namespaceOrFallback(lb traefikv1alpha1.LoadBalancerSpec, fallback string) string { if lb.Namespace != "" { return lb.Namespace } return fallback } // getTLSHTTP mutates tlsConfigs. func getTLSHTTP(ctx context.Context, ingressRoute *traefikv1alpha1.IngressRoute, k8sClient Client, tlsConfigs map[string]*tls.CertAndStores) error { if ingressRoute.Spec.TLS == nil { return nil } if ingressRoute.Spec.TLS.SecretName == "" { log.Ctx(ctx).Debug().Msg("No secret name provided") return nil } configKey := ingressRoute.Namespace + "/" + ingressRoute.Spec.TLS.SecretName if _, tlsExists := tlsConfigs[configKey]; !tlsExists { tlsConf, err := getTLS(k8sClient, ingressRoute.Spec.TLS.SecretName, ingressRoute.Namespace) if err != nil { return err } tlsConfigs[configKey] = tlsConf } return nil } // parseServiceProtocol parses the scheme, port name, and number to determine the correct protocol. // an error is returned if the scheme provided is invalid. func parseServiceProtocol(providedScheme, portName string, portNumber int32) (string, error) { switch providedScheme { case httpProtocol, httpsProtocol, "h2c": return providedScheme, nil case "": if portNumber == 443 || strings.HasPrefix(portName, httpsProtocol) { return httpsProtocol, nil } return httpProtocol, nil } return "", fmt.Errorf("invalid scheme %q specified", providedScheme) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/crd/kubernetes_tcp.go
pkg/provider/kubernetes/crd/kubernetes_tcp.go
package crd import ( "context" "errors" "fmt" "net" "strconv" "strings" "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" traefikv1alpha1 "github.com/traefik/traefik/v3/pkg/provider/kubernetes/crd/traefikio/v1alpha1" "github.com/traefik/traefik/v3/pkg/tls" corev1 "k8s.io/api/core/v1" ) func (p *Provider) loadIngressRouteTCPConfiguration(ctx context.Context, client Client, tlsConfigs map[string]*tls.CertAndStores) *dynamic.TCPConfiguration { conf := &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, } for _, ingressRouteTCP := range client.GetIngressRouteTCPs() { logger := log.Ctx(ctx).With().Str("ingress", ingressRouteTCP.Name).Str("namespace", ingressRouteTCP.Namespace).Logger() if !shouldProcessIngress(p.IngressClass, ingressRouteTCP.Annotations[annotationKubernetesIngressClass]) { continue } if ingressRouteTCP.Spec.TLS != nil && !ingressRouteTCP.Spec.TLS.Passthrough { err := getTLSTCP(ctx, ingressRouteTCP, client, tlsConfigs) if err != nil { logger.Error().Err(err).Msg("Error configuring TLS") } } ingressName := ingressRouteTCP.Name if len(ingressName) == 0 { ingressName = ingressRouteTCP.GenerateName } for _, route := range ingressRouteTCP.Spec.Routes { if len(route.Match) == 0 { logger.Error().Msg("Empty match rule") continue } key := makeServiceKey(route.Match, ingressName) mds, err := p.makeMiddlewareTCPKeys(ctx, ingressRouteTCP.Namespace, route.Middlewares) if err != nil { logger.Error().Err(err).Msg("Failed to create middleware keys") continue } serviceName := makeID(ingressRouteTCP.Namespace, key) for _, service := range route.Services { balancerServerTCP, err := p.createLoadBalancerServerTCP(client, ingressRouteTCP.Namespace, service) if err != nil { logger.Error(). Str("serviceName", service.Name). Stringer("servicePort", &service.Port). Err(err). Msg("Cannot create service") continue } // If there is only one service defined, we skip the creation of the load balancer of services, // i.e. the service on top is directly a load balancer of servers. if len(route.Services) == 1 { conf.Services[serviceName] = balancerServerTCP break } serviceKey := fmt.Sprintf("%s-%s-%s", serviceName, service.Name, &service.Port) conf.Services[serviceKey] = balancerServerTCP srv := dynamic.TCPWRRService{Name: serviceKey} srv.SetDefaults() if service.Weight != nil { srv.Weight = service.Weight } if conf.Services[serviceName] == nil { conf.Services[serviceName] = &dynamic.TCPService{Weighted: &dynamic.TCPWeightedRoundRobin{}} } conf.Services[serviceName].Weighted.Services = append(conf.Services[serviceName].Weighted.Services, srv) } r := &dynamic.TCPRouter{ EntryPoints: ingressRouteTCP.Spec.EntryPoints, Middlewares: mds, Rule: route.Match, Priority: route.Priority, RuleSyntax: route.Syntax, Service: serviceName, } if ingressRouteTCP.Spec.TLS != nil { r.TLS = &dynamic.RouterTCPTLSConfig{ Passthrough: ingressRouteTCP.Spec.TLS.Passthrough, CertResolver: ingressRouteTCP.Spec.TLS.CertResolver, Domains: ingressRouteTCP.Spec.TLS.Domains, } if ingressRouteTCP.Spec.TLS.Options != nil && len(ingressRouteTCP.Spec.TLS.Options.Name) > 0 { tlsOptionsName := ingressRouteTCP.Spec.TLS.Options.Name // Is a Kubernetes CRD reference (i.e. not a cross-provider reference) ns := ingressRouteTCP.Spec.TLS.Options.Namespace if !strings.Contains(tlsOptionsName, providerNamespaceSeparator) { if len(ns) == 0 { ns = ingressRouteTCP.Namespace } tlsOptionsName = makeID(ns, tlsOptionsName) } else if len(ns) > 0 { logger.Warn(). Str("TLSOption", ingressRouteTCP.Spec.TLS.Options.Name). Msgf("Namespace %q is ignored in cross-provider context", ns) } if !isNamespaceAllowed(p.AllowCrossNamespace, ingressRouteTCP.Namespace, ns) { logger.Error().Msgf("TLSOption %s/%s is not in the IngressRouteTCP namespace %s", ns, ingressRouteTCP.Spec.TLS.Options.Name, ingressRouteTCP.Namespace) continue } r.TLS.Options = tlsOptionsName } } conf.Routers[serviceName] = r } } return conf } func (p *Provider) makeMiddlewareTCPKeys(ctx context.Context, ingRouteTCPNamespace string, middlewares []traefikv1alpha1.ObjectReference) ([]string, error) { var mds []string for _, mi := range middlewares { if strings.Contains(mi.Name, providerNamespaceSeparator) { if len(mi.Namespace) > 0 { log.Ctx(ctx).Warn(). Str(logs.MiddlewareName, mi.Name). Msgf("Namespace %q is ignored in cross-provider context", mi.Namespace) } mds = append(mds, mi.Name) continue } ns := ingRouteTCPNamespace if len(mi.Namespace) > 0 { if !isNamespaceAllowed(p.AllowCrossNamespace, ingRouteTCPNamespace, mi.Namespace) { return nil, fmt.Errorf("middleware %s/%s is not in the IngressRouteTCP namespace %s", mi.Namespace, mi.Name, ingRouteTCPNamespace) } ns = mi.Namespace } mds = append(mds, provider.Normalize(makeID(ns, mi.Name))) } return mds, nil } func (p *Provider) createLoadBalancerServerTCP(client Client, parentNamespace string, service traefikv1alpha1.ServiceTCP) (*dynamic.TCPService, error) { ns := parentNamespace if len(service.Namespace) > 0 { if !isNamespaceAllowed(p.AllowCrossNamespace, parentNamespace, service.Namespace) { return nil, fmt.Errorf("tcp service %s/%s is not in the parent resource namespace %s", service.Namespace, service.Name, parentNamespace) } ns = service.Namespace } servers, err := p.loadTCPServers(client, ns, service) if err != nil { return nil, err } tcpService := &dynamic.TCPService{ LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: servers, }, } if service.ProxyProtocol != nil { tcpService.LoadBalancer.ProxyProtocol = &dynamic.ProxyProtocol{} tcpService.LoadBalancer.ProxyProtocol.SetDefaults() if service.ProxyProtocol.Version != 0 { tcpService.LoadBalancer.ProxyProtocol.Version = service.ProxyProtocol.Version } } if service.ServersTransport == "" && service.TerminationDelay != nil { tcpService.LoadBalancer.TerminationDelay = service.TerminationDelay } if service.ServersTransport != "" { tcpService.LoadBalancer.ServersTransport, err = p.makeTCPServersTransportKey(parentNamespace, service.ServersTransport) if err != nil { return nil, err } } return tcpService, nil } func (p *Provider) loadTCPServers(client Client, namespace string, svc traefikv1alpha1.ServiceTCP) ([]dynamic.TCPServer, error) { service, exists, err := client.GetService(namespace, svc.Name) if err != nil { return nil, err } if !exists { return nil, errors.New("service not found") } if service.Spec.Type == corev1.ServiceTypeExternalName && !p.AllowExternalNameServices { return nil, fmt.Errorf("externalName services not allowed: %s/%s", namespace, svc.Name) } svcPort, err := getServicePort(service, svc.Port) if err != nil { return nil, err } var servers []dynamic.TCPServer if service.Spec.Type == corev1.ServiceTypeNodePort && svc.NodePortLB { if p.DisableClusterScopeResources { return nil, errors.New("nodes lookup is disabled") } nodes, nodesExists, nodesErr := client.GetNodes() if nodesErr != nil { return nil, nodesErr } if !nodesExists || len(nodes) == 0 { return nil, fmt.Errorf("nodes not found for NodePort service %s/%s", svc.Namespace, svc.Name) } for _, node := range nodes { for _, addr := range node.Status.Addresses { if addr.Type == corev1.NodeInternalIP { servers = append(servers, dynamic.TCPServer{ Address: net.JoinHostPort(addr.Address, strconv.Itoa(int(svcPort.NodePort))), TLS: svc.TLS, }) } } } if len(servers) == 0 { return nil, fmt.Errorf("no servers were generated for service %s/%s", svc.Namespace, svc.Name) } return servers, nil } if service.Spec.Type == corev1.ServiceTypeExternalName { servers = append(servers, dynamic.TCPServer{ Address: net.JoinHostPort(service.Spec.ExternalName, strconv.Itoa(int(svcPort.Port))), TLS: svc.TLS, }) } else { nativeLB := p.NativeLBByDefault if svc.NativeLB != nil { nativeLB = *svc.NativeLB } if nativeLB { address, err := getNativeServiceAddress(*service, *svcPort) if err != nil { return nil, fmt.Errorf("getting native Kubernetes Service address: %w", err) } return []dynamic.TCPServer{{Address: address, TLS: svc.TLS}}, nil } endpointSlices, err := client.GetEndpointSlicesForService(namespace, svc.Name) if err != nil { return nil, fmt.Errorf("getting endpointslices: %w", err) } addresses := map[string]struct{}{} for _, endpointSlice := range endpointSlices { var port int32 for _, p := range endpointSlice.Ports { if svcPort.Name == *p.Name { port = *p.Port break } } if port == 0 { continue } for _, endpoint := range endpointSlice.Endpoints { if endpoint.Conditions.Ready == nil || !*endpoint.Conditions.Ready { continue } for _, address := range endpoint.Addresses { if _, ok := addresses[address]; ok { continue } addresses[address] = struct{}{} servers = append(servers, dynamic.TCPServer{ Address: net.JoinHostPort(address, strconv.Itoa(int(port))), TLS: svc.TLS, }) } } } } if len(servers) == 0 && !p.AllowEmptyServices { return nil, fmt.Errorf("no servers found for %s/%s", namespace, svc.Name) } return servers, nil } func (p *Provider) makeTCPServersTransportKey(parentNamespace string, serversTransportName string) (string, error) { if serversTransportName == "" { return "", nil } if !p.AllowCrossNamespace && strings.HasSuffix(serversTransportName, providerNamespaceSeparator+providerName) { // Since we are not able to know if another namespace is in the name (namespace-name@kubernetescrd), // if the provider namespace kubernetescrd is used, // we don't allow this format to avoid cross namespace references. return "", fmt.Errorf("invalid reference to serversTransport %s: namespace-name@kubernetescrd format is not allowed when crossnamespace is disallowed", serversTransportName) } if strings.Contains(serversTransportName, providerNamespaceSeparator) { return serversTransportName, nil } return provider.Normalize(makeID(parentNamespace, serversTransportName)), nil } // getTLSTCP mutates tlsConfigs. func getTLSTCP(ctx context.Context, ingressRoute *traefikv1alpha1.IngressRouteTCP, k8sClient Client, tlsConfigs map[string]*tls.CertAndStores) error { if ingressRoute.Spec.TLS == nil { return nil } if ingressRoute.Spec.TLS.SecretName == "" { log.Ctx(ctx).Debug().Msg("No secret name provided") return nil } configKey := ingressRoute.Namespace + "/" + ingressRoute.Spec.TLS.SecretName if _, tlsExists := tlsConfigs[configKey]; !tlsExists { tlsConf, err := getTLS(k8sClient, ingressRoute.Spec.TLS.SecretName, ingressRoute.Namespace) if err != nil { return err } tlsConfigs[configKey] = tlsConf } return nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/crd/kubernetes_test.go
pkg/provider/kubernetes/crd/kubernetes_test.go
package crd import ( "os" "path/filepath" "strings" "testing" "time" auth "github.com/abbot/go-http-auth" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/provider" traefikcrdfake "github.com/traefik/traefik/v3/pkg/provider/kubernetes/crd/generated/clientset/versioned/fake" traefikv1alpha1 "github.com/traefik/traefik/v3/pkg/provider/kubernetes/crd/traefikio/v1alpha1" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/gateway" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/k8s" "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/intstr" kubefake "k8s.io/client-go/kubernetes/fake" kscheme "k8s.io/client-go/kubernetes/scheme" ) var _ provider.Provider = (*Provider)(nil) func pointer[T any](v T) *T { return &v } func init() { // required by k8s.MustParseYaml err := traefikv1alpha1.AddToScheme(kscheme.Scheme) if err != nil { panic(err) } } func TestLoadIngressRouteTCPs(t *testing.T) { testCases := []struct { desc string ingressClass string paths []string allowEmptyServices bool expected *dynamic.Configuration }{ { desc: "Empty", expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Simple Ingress Route, with foo entrypoint", paths: []string{"tcp/services.yml", "tcp/simple.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "default-test.route-fdd3e9338e47a45efefc": { EntryPoints: []string{"foo"}, Service: "default-test.route-fdd3e9338e47a45efefc", Rule: "HostSNI(`foo.com`)", }, }, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{ "default-test.route-fdd3e9338e47a45efefc": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "10.10.0.1:8000", }, { Address: "10.10.0.2:8000", }, }, }, }, }, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Simple Ingress Route, with foo entrypoint, tls encryption to service", paths: []string{"tcp/services.yml", "tcp/with_tls_service.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "default-test.route-fdd3e9338e47a45efefc": { EntryPoints: []string{"foo"}, Service: "default-test.route-fdd3e9338e47a45efefc", Rule: "HostSNI(`foo.com`)", }, }, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{ "default-test.route-fdd3e9338e47a45efefc": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "10.10.0.1:8000", TLS: true, }, { Address: "10.10.0.2:8000", TLS: true, }, }, }, }, }, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Simple Ingress Route, with foo entrypoint and middleware", paths: []string{"tcp/services.yml", "tcp/with_middleware.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "default-test.route-fdd3e9338e47a45efefc": { EntryPoints: []string{"foo"}, Service: "default-test.route-fdd3e9338e47a45efefc", Middlewares: []string{"default-ipallowlist", "foo-ipallowlist"}, Rule: "HostSNI(`foo.com`)", }, }, Middlewares: map[string]*dynamic.TCPMiddleware{ "default-ipallowlist": { IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, "foo-ipallowlist": { IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, }, Services: map[string]*dynamic.TCPService{ "default-test.route-fdd3e9338e47a45efefc": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "10.10.0.1:8000", }, { Address: "10.10.0.2:8000", }, }, }, }, }, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Middlewares in ingress route config are normalized", paths: []string{"tcp/services.yml", "tcp/with_middleware_multiple_hyphens.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "default-test.route-fdd3e9338e47a45efefc": { EntryPoints: []string{"foo"}, Service: "default-test.route-fdd3e9338e47a45efefc", Middlewares: []string{"default-multiple-hyphens"}, Rule: "HostSNI(`foo.com`)", }, }, Middlewares: map[string]*dynamic.TCPMiddleware{ "default-multiple-hyphens": { IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, }, Services: map[string]*dynamic.TCPService{ "default-test.route-fdd3e9338e47a45efefc": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "10.10.0.1:8000", }, { Address: "10.10.0.2:8000", }, }, }, }, }, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Simple Ingress Route, with foo entrypoint and crossprovider middleware", paths: []string{"tcp/services.yml", "tcp/with_middleware_crossprovider.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "default-test.route-fdd3e9338e47a45efefc": { EntryPoints: []string{"foo"}, Service: "default-test.route-fdd3e9338e47a45efefc", Middlewares: []string{"default-ipallowlist", "foo-ipallowlist", "ipallowlist@file", "ipallowlist-foo@file"}, Rule: "HostSNI(`foo.com`)", }, }, Middlewares: map[string]*dynamic.TCPMiddleware{ "default-ipallowlist": { IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, "foo-ipallowlist": { IPAllowList: &dynamic.TCPIPAllowList{ SourceRange: []string{"127.0.0.1/32"}, }, }, }, Services: map[string]*dynamic.TCPService{ "default-test.route-fdd3e9338e47a45efefc": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "10.10.0.1:8000", }, { Address: "10.10.0.2:8000", }, }, }, }, }, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "One ingress Route with two different rules", paths: []string{"tcp/services.yml", "tcp/with_two_rules.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "default-test.route-fdd3e9338e47a45efefc": { EntryPoints: []string{"foo"}, Service: "default-test.route-fdd3e9338e47a45efefc", Rule: "HostSNI(`foo.com`)", }, "default-test.route-f44ce589164e656d231c": { EntryPoints: []string{"foo"}, Service: "default-test.route-f44ce589164e656d231c", Rule: "HostSNI(`bar.com`)", }, }, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{ "default-test.route-fdd3e9338e47a45efefc": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "10.10.0.1:8000", }, { Address: "10.10.0.2:8000", }, }, }, }, "default-test.route-f44ce589164e656d231c": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "10.10.0.1:8000", }, { Address: "10.10.0.2:8000", }, }, }, }, }, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "One ingress Route with two identical rules", paths: []string{"tcp/services.yml", "tcp/with_two_identical_rules.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "default-test.route-fdd3e9338e47a45efefc": { EntryPoints: []string{"foo"}, Service: "default-test.route-fdd3e9338e47a45efefc", Rule: "HostSNI(`foo.com`)", }, }, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{ "default-test.route-fdd3e9338e47a45efefc": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "10.10.0.1:8000", }, { Address: "10.10.0.2:8000", }, }, }, }, }, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "One ingress Route with two different services", paths: []string{"tcp/services.yml", "tcp/with_two_services.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "default-test.route-fdd3e9338e47a45efefc": { EntryPoints: []string{"foo"}, Service: "default-test.route-fdd3e9338e47a45efefc", Rule: "HostSNI(`foo.com`)", }, }, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{ "default-test.route-fdd3e9338e47a45efefc": { Weighted: &dynamic.TCPWeightedRoundRobin{ Services: []dynamic.TCPWRRService{ { Name: "default-test.route-fdd3e9338e47a45efefc-whoamitcp-8000", Weight: pointer(2), }, { Name: "default-test.route-fdd3e9338e47a45efefc-whoamitcp2-8080", Weight: pointer(3), }, }, }, }, "default-test.route-fdd3e9338e47a45efefc-whoamitcp-8000": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "10.10.0.1:8000", }, { Address: "10.10.0.2:8000", }, }, }, }, "default-test.route-fdd3e9338e47a45efefc-whoamitcp2-8080": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "10.10.0.3:8080", }, { Address: "10.10.0.4:8080", }, }, }, }, }, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "One ingress Route with different services namespaces", paths: []string{"tcp/services.yml", "tcp/with_different_services_ns.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "default-test.route-fdd3e9338e47a45efefc": { EntryPoints: []string{"foo"}, Service: "default-test.route-fdd3e9338e47a45efefc", Rule: "HostSNI(`foo.com`)", }, }, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{ "default-test.route-fdd3e9338e47a45efefc": { Weighted: &dynamic.TCPWeightedRoundRobin{ Services: []dynamic.TCPWRRService{ { Name: "default-test.route-fdd3e9338e47a45efefc-whoamitcp-8000", Weight: pointer(2), }, { Name: "default-test.route-fdd3e9338e47a45efefc-whoamitcp2-8080", Weight: pointer(3), }, { Name: "default-test.route-fdd3e9338e47a45efefc-whoamitcp3-8083", Weight: pointer(4), }, }, }, }, "default-test.route-fdd3e9338e47a45efefc-whoamitcp-8000": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "10.10.0.1:8000", }, { Address: "10.10.0.2:8000", }, }, }, }, "default-test.route-fdd3e9338e47a45efefc-whoamitcp2-8080": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "10.10.0.3:8080", }, { Address: "10.10.0.4:8080", }, }, }, }, "default-test.route-fdd3e9338e47a45efefc-whoamitcp3-8083": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "10.10.0.7:8083", }, { Address: "10.10.0.8:8083", }, }, }, }, }, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Ingress class does not match", paths: []string{"tcp/services.yml", "tcp/simple.yml"}, ingressClass: "tchouk", expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "Route with empty rule value is ignored", paths: []string{"tcp/services.yml", "tcp/with_no_rule_value.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{}, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{}, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "TLS", paths: []string{"tcp/services.yml", "tcp/with_tls.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TLS: &dynamic.TLSConfiguration{ Certificates: []*tls.CertAndStores{ { Certificate: tls.Certificate{ CertFile: types.FileOrContent("-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----"), KeyFile: types.FileOrContent("-----BEGIN PRIVATE KEY-----\n-----END PRIVATE KEY-----"), }, }, }, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "default-test.route-fdd3e9338e47a45efefc": { EntryPoints: []string{"foo"}, Service: "default-test.route-fdd3e9338e47a45efefc", Rule: "HostSNI(`foo.com`)", TLS: &dynamic.RouterTCPTLSConfig{}, }, }, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{ "default-test.route-fdd3e9338e47a45efefc": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "10.10.0.1:8000", }, { Address: "10.10.0.2:8000", }, }, }, }, }, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, }, }, { desc: "TLS with passthrough", paths: []string{"tcp/services.yml", "tcp/with_tls_passthrough.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "default-test.route-fdd3e9338e47a45efefc": { EntryPoints: []string{"foo"}, Service: "default-test.route-fdd3e9338e47a45efefc", Rule: "HostSNI(`foo.com`)", TLS: &dynamic.RouterTCPTLSConfig{ Passthrough: true, }, }, }, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{ "default-test.route-fdd3e9338e47a45efefc": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "10.10.0.1:8000", }, { Address: "10.10.0.2:8000", }, }, }, }, }, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, TLS: &dynamic.TLSConfiguration{}, }, }, { desc: "TLS with tls options", paths: []string{"tcp/services.yml", "tcp/with_tls_options.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "default-foo": { MinVersion: "VersionTLS12", CipherSuites: []string{ "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "TLS_RSA_WITH_AES_256_GCM_SHA384", }, ClientAuth: tls.ClientAuth{ CAFiles: []types.FileOrContent{ types.FileOrContent("-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----"), types.FileOrContent("-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----"), }, ClientAuthType: "VerifyClientCertIfGiven", }, SniStrict: true, DisableSessionTickets: true, ALPNProtocols: []string{ "h2", "http/1.1", "acme-tls/1", }, }, }, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "default-test.route-fdd3e9338e47a45efefc": { EntryPoints: []string{"foo"}, Service: "default-test.route-fdd3e9338e47a45efefc", Rule: "HostSNI(`foo.com`)", TLS: &dynamic.RouterTCPTLSConfig{ Options: "default-foo", }, }, }, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{ "default-test.route-fdd3e9338e47a45efefc": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "10.10.0.1:8000", }, { Address: "10.10.0.2:8000", }, }, }, }, }, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, }, }, { desc: "TLS with tls options and specific namespace", paths: []string{"tcp/services.yml", "tcp/with_tls_options_and_specific_namespace.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "myns-foo": { MinVersion: "VersionTLS12", CipherSuites: []string{ "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "TLS_RSA_WITH_AES_256_GCM_SHA384", }, ClientAuth: tls.ClientAuth{ CAFiles: []types.FileOrContent{ types.FileOrContent("-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----"), types.FileOrContent("-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----"), }, ClientAuthType: "VerifyClientCertIfGiven", }, SniStrict: true, ALPNProtocols: []string{ "h2", "http/1.1", "acme-tls/1", }, }, }, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "default-test.route-fdd3e9338e47a45efefc": { EntryPoints: []string{"foo"}, Service: "default-test.route-fdd3e9338e47a45efefc", Rule: "HostSNI(`foo.com`)", TLS: &dynamic.RouterTCPTLSConfig{ Options: "myns-foo", }, }, }, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{ "default-test.route-fdd3e9338e47a45efefc": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "10.10.0.1:8000", }, { Address: "10.10.0.2:8000", }, }, }, }, }, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, }, }, { desc: "TLS with bad tls options", paths: []string{"tcp/services.yml", "tcp/with_bad_tls_options.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "default-foo": { MinVersion: "VersionTLS12", CipherSuites: []string{ "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "TLS_RSA_WITH_AES_256_GCM_SHA384", }, ClientAuth: tls.ClientAuth{ CAFiles: []types.FileOrContent{ types.FileOrContent("-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----"), }, ClientAuthType: "VerifyClientCertIfGiven", }, SniStrict: true, ALPNProtocols: []string{ "h2", "http/1.1", "acme-tls/1", }, }, }, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "default-test.route-fdd3e9338e47a45efefc": { EntryPoints: []string{"foo"}, Service: "default-test.route-fdd3e9338e47a45efefc", Rule: "HostSNI(`foo.com`)", TLS: &dynamic.RouterTCPTLSConfig{ Options: "default-foo", }, }, }, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{ "default-test.route-fdd3e9338e47a45efefc": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "10.10.0.1:8000", }, { Address: "10.10.0.2:8000", }, }, }, }, }, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, }, }, { desc: "TLS with unknown tls options", paths: []string{"tcp/services.yml", "tcp/with_unknown_tls_options.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "default-foo": { MinVersion: "VersionTLS12", ALPNProtocols: []string{ "h2", "http/1.1", "acme-tls/1", }, CipherSuites: []string{ "TLS_AES_128_GCM_SHA256", "TLS_AES_256_GCM_SHA384", "TLS_CHACHA20_POLY1305_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", }, }, }, }, TCP: &dynamic.TCPConfiguration{ Routers: map[string]*dynamic.TCPRouter{ "default-test.route-fdd3e9338e47a45efefc": { EntryPoints: []string{"foo"}, Service: "default-test.route-fdd3e9338e47a45efefc", Rule: "HostSNI(`foo.com`)", TLS: &dynamic.RouterTCPTLSConfig{ Options: "default-unknown", }, }, }, Middlewares: map[string]*dynamic.TCPMiddleware{}, Services: map[string]*dynamic.TCPService{ "default-test.route-fdd3e9338e47a45efefc": { LoadBalancer: &dynamic.TCPServersLoadBalancer{ Servers: []dynamic.TCPServer{ { Address: "10.10.0.1:8000", }, { Address: "10.10.0.2:8000", }, }, }, }, }, ServersTransports: map[string]*dynamic.TCPServersTransport{}, }, HTTP: &dynamic.HTTPConfiguration{ Routers: map[string]*dynamic.Router{}, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{}, ServersTransports: map[string]*dynamic.ServersTransport{}, }, }, }, { desc: "TLS with unknown tls options namespace", paths: []string{"tcp/services.yml", "tcp/with_unknown_tls_options_namespace.yml"}, expected: &dynamic.Configuration{ UDP: &dynamic.UDPConfiguration{ Routers: map[string]*dynamic.UDPRouter{}, Services: map[string]*dynamic.UDPService{}, }, TLS: &dynamic.TLSConfiguration{ Options: map[string]tls.Options{ "default-foo": { MinVersion: "VersionTLS12", ALPNProtocols: []string{ "h2", "http/1.1", "acme-tls/1", },
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/crd/kubernetes.go
pkg/provider/kubernetes/crd/kubernetes.go
package crd import ( "bufio" "bytes" "context" "crypto/sha1" "crypto/sha256" "encoding/base64" "encoding/json" "errors" "fmt" "net" "os" "slices" "sort" "strconv" "strings" "time" "github.com/cenkalti/backoff/v4" "github.com/mitchellh/hashstructure" "github.com/rs/zerolog/log" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/job" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/provider" traefikv1alpha1 "github.com/traefik/traefik/v3/pkg/provider/kubernetes/crd/traefikio/v1alpha1" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/gateway" "github.com/traefik/traefik/v3/pkg/provider/kubernetes/k8s" "github.com/traefik/traefik/v3/pkg/safe" "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" corev1 "k8s.io/api/core/v1" apiextensionv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/util/intstr" ) const ( annotationKubernetesIngressClass = "kubernetes.io/ingress.class" traefikDefaultIngressClass = "traefik" ) const ( providerName = "kubernetescrd" providerNamespaceSeparator = "@" ) // Provider holds configurations of the provider. type Provider struct { Endpoint string `description:"Kubernetes server endpoint (required for external cluster client)." json:"endpoint,omitempty" toml:"endpoint,omitempty" yaml:"endpoint,omitempty"` Token types.FileOrContent `description:"Kubernetes bearer token (not needed for in-cluster client). It accepts either a token value or a file path to the token." json:"token,omitempty" toml:"token,omitempty" yaml:"token,omitempty" loggable:"false"` CertAuthFilePath string `description:"Kubernetes certificate authority file path (not needed for in-cluster client)." json:"certAuthFilePath,omitempty" toml:"certAuthFilePath,omitempty" yaml:"certAuthFilePath,omitempty"` Namespaces []string `description:"Kubernetes namespaces." json:"namespaces,omitempty" toml:"namespaces,omitempty" yaml:"namespaces,omitempty" export:"true"` AllowCrossNamespace bool `description:"Allow cross namespace resource reference." json:"allowCrossNamespace,omitempty" toml:"allowCrossNamespace,omitempty" yaml:"allowCrossNamespace,omitempty" export:"true"` AllowExternalNameServices bool `description:"Allow ExternalName services." json:"allowExternalNameServices,omitempty" toml:"allowExternalNameServices,omitempty" yaml:"allowExternalNameServices,omitempty" export:"true"` LabelSelector string `description:"Kubernetes label selector to use." json:"labelSelector,omitempty" toml:"labelSelector,omitempty" yaml:"labelSelector,omitempty" export:"true"` IngressClass string `description:"Value of kubernetes.io/ingress.class annotation to watch for." json:"ingressClass,omitempty" toml:"ingressClass,omitempty" yaml:"ingressClass,omitempty" export:"true"` ThrottleDuration ptypes.Duration `description:"Ingress refresh throttle duration" json:"throttleDuration,omitempty" toml:"throttleDuration,omitempty" yaml:"throttleDuration,omitempty" export:"true"` AllowEmptyServices bool `description:"Allow the creation of services without endpoints." json:"allowEmptyServices,omitempty" toml:"allowEmptyServices,omitempty" yaml:"allowEmptyServices,omitempty" export:"true"` NativeLBByDefault bool `description:"Defines whether to use Native Kubernetes load-balancing mode by default." json:"nativeLBByDefault,omitempty" toml:"nativeLBByDefault,omitempty" yaml:"nativeLBByDefault,omitempty" export:"true"` DisableClusterScopeResources bool `description:"Disables the lookup of cluster scope resources (incompatible with IngressClasses and NodePortLB enabled services)." json:"disableClusterScopeResources,omitempty" toml:"disableClusterScopeResources,omitempty" yaml:"disableClusterScopeResources,omitempty" export:"true"` lastConfiguration safe.Safe routerTransform k8s.RouterTransform } func (p *Provider) SetRouterTransform(routerTransform k8s.RouterTransform) { p.routerTransform = routerTransform } func (p *Provider) applyRouterTransform(ctx context.Context, rt *dynamic.Router, ingress *traefikv1alpha1.IngressRoute) { if p.routerTransform == nil { return } err := p.routerTransform.Apply(ctx, rt, ingress) if err != nil { log.Ctx(ctx).Error().Err(err).Msg("Apply router transform") } } func (p *Provider) newK8sClient(ctx context.Context) (*clientWrapper, error) { _, err := labels.Parse(p.LabelSelector) if err != nil { return nil, fmt.Errorf("invalid label selector: %q", p.LabelSelector) } log.Ctx(ctx).Info().Msgf("label selector is: %q", p.LabelSelector) withEndpoint := "" if p.Endpoint != "" { withEndpoint = fmt.Sprintf(" with endpoint %s", p.Endpoint) } var client *clientWrapper switch { case os.Getenv("KUBERNETES_SERVICE_HOST") != "" && os.Getenv("KUBERNETES_SERVICE_PORT") != "": log.Ctx(ctx).Info().Msgf("Creating in-cluster Provider client%s", withEndpoint) client, err = newInClusterClient(p.Endpoint) case os.Getenv("KUBECONFIG") != "": log.Ctx(ctx).Info().Msgf("Creating cluster-external Provider client from KUBECONFIG %s", os.Getenv("KUBECONFIG")) client, err = newExternalClusterClientFromFile(os.Getenv("KUBECONFIG")) default: log.Ctx(ctx).Info().Msgf("Creating cluster-external Provider client%s", withEndpoint) client, err = newExternalClusterClient(p.Endpoint, p.CertAuthFilePath, p.Token) } if err != nil { return nil, err } client.labelSelector = p.LabelSelector client.disableClusterScopeInformer = p.DisableClusterScopeResources return client, nil } // Init the provider. func (p *Provider) Init() error { return nil } // Provide allows the k8s provider to provide configurations to traefik // using the given configuration channel. func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error { logger := log.With().Str(logs.ProviderName, providerName).Logger() ctxLog := logger.WithContext(context.Background()) k8sClient, err := p.newK8sClient(ctxLog) if err != nil { return err } if p.AllowCrossNamespace { logger.Warn().Msg("Cross-namespace reference between IngressRoutes and resources is enabled, please ensure that this is expected (see AllowCrossNamespace option)") } if p.AllowExternalNameServices { logger.Info().Msg("ExternalName service loading is enabled, please ensure that this is expected (see AllowExternalNameServices option)") } pool.GoCtx(func(ctxPool context.Context) { operation := func() error { eventsChan, err := k8sClient.WatchAll(p.Namespaces, ctxPool.Done()) if err != nil { logger.Error().Err(err).Msg("Error watching kubernetes events") timer := time.NewTimer(1 * time.Second) select { case <-timer.C: return err case <-ctxPool.Done(): return nil } } throttleDuration := time.Duration(p.ThrottleDuration) throttledChan := throttleEvents(ctxLog, throttleDuration, pool, eventsChan) if throttledChan != nil { eventsChan = throttledChan } for { select { case <-ctxPool.Done(): return nil case event := <-eventsChan: // Note that event is the *first* event that came in during this throttling interval -- if we're hitting our throttle, we may have dropped events. // This is fine, because we don't treat different event types differently. // But if we do in the future, we'll need to track more information about the dropped events. conf := p.loadConfigurationFromCRD(ctxLog, k8sClient) confHash, err := hashstructure.Hash(conf, nil) switch { case err != nil: logger.Error().Err(err).Msg("Unable to hash the configuration") case p.lastConfiguration.Get() == confHash: logger.Debug().Msgf("Skipping Kubernetes event kind %T", event) default: p.lastConfiguration.Set(confHash) configurationChan <- dynamic.Message{ ProviderName: providerName, Configuration: conf, } } // If we're throttling, // we sleep here for the throttle duration to enforce that we don't refresh faster than our throttle. // time.Sleep returns immediately if p.ThrottleDuration is 0 (no throttle). time.Sleep(throttleDuration) } } } notify := func(err error, time time.Duration) { logger.Error().Err(err).Msgf("Provider error, retrying in %s", time) } err := backoff.RetryNotify(safe.OperationWithRecover(operation), backoff.WithContext(job.NewBackOff(backoff.NewExponentialBackOff()), ctxPool), notify) if err != nil { logger.Error().Err(err).Msg("Cannot retrieve data") } }) return nil } func (p *Provider) loadConfigurationFromCRD(ctx context.Context, client Client) *dynamic.Configuration { stores, tlsConfigs := buildTLSStores(ctx, client) if tlsConfigs == nil { tlsConfigs = make(map[string]*tls.CertAndStores) } conf := &dynamic.Configuration{ // TODO: choose between mutating and returning tlsConfigs HTTP: p.loadIngressRouteConfiguration(ctx, client, tlsConfigs), TCP: p.loadIngressRouteTCPConfiguration(ctx, client, tlsConfigs), UDP: p.loadIngressRouteUDPConfiguration(ctx, client), TLS: &dynamic.TLSConfiguration{ Options: buildTLSOptions(ctx, client), Stores: stores, }, } // Done after because tlsConfigs is mutated by the others above. conf.TLS.Certificates = getTLSConfig(tlsConfigs) for _, middleware := range client.GetMiddlewares() { id := provider.Normalize(makeID(middleware.Namespace, middleware.Name)) logger := log.Ctx(ctx).With().Str(logs.MiddlewareName, id).Logger() ctxMid := logger.WithContext(ctx) basicAuth, err := createBasicAuthMiddleware(client, middleware.Namespace, middleware.Spec.BasicAuth) if err != nil { logger.Error().Err(err).Msg("Error while reading basic auth middleware") continue } digestAuth, err := createDigestAuthMiddleware(client, middleware.Namespace, middleware.Spec.DigestAuth) if err != nil { logger.Error().Err(err).Msg("Error while reading digest auth middleware") continue } forwardAuth, err := createForwardAuthMiddleware(client, middleware.Namespace, middleware.Spec.ForwardAuth) if err != nil { logger.Error().Err(err).Msg("Error while reading forward auth middleware") continue } errorPage, errorPageService, err := p.createErrorPageMiddleware(client, middleware.Namespace, middleware.Spec.Errors) if err != nil { logger.Error().Err(err).Msg("Error while reading error page middleware") continue } if errorPage != nil && errorPageService != nil { serviceName := id + "-errorpage-service" errorPage.Service = serviceName conf.HTTP.Services[serviceName] = errorPageService } plugin, err := createPluginMiddleware(client, middleware.Namespace, middleware.Spec.Plugin) if err != nil { logger.Error().Err(err).Msg("Error while reading plugins middleware") continue } rateLimit, err := createRateLimitMiddleware(client, middleware.Namespace, middleware.Spec.RateLimit) if err != nil { logger.Error().Err(err).Msg("Error while reading rateLimit middleware") continue } retry, err := createRetryMiddleware(middleware.Spec.Retry) if err != nil { logger.Error().Err(err).Msg("Error while reading retry middleware") continue } circuitBreaker, err := createCircuitBreakerMiddleware(middleware.Spec.CircuitBreaker) if err != nil { logger.Error().Err(err).Msg("Error while reading circuit breaker middleware") continue } conf.HTTP.Middlewares[id] = &dynamic.Middleware{ AddPrefix: middleware.Spec.AddPrefix, StripPrefix: middleware.Spec.StripPrefix, StripPrefixRegex: middleware.Spec.StripPrefixRegex, ReplacePath: middleware.Spec.ReplacePath, ReplacePathRegex: middleware.Spec.ReplacePathRegex, Chain: createChainMiddleware(ctxMid, middleware.Namespace, middleware.Spec.Chain), IPWhiteList: middleware.Spec.IPWhiteList, IPAllowList: middleware.Spec.IPAllowList, Headers: middleware.Spec.Headers, Errors: errorPage, RateLimit: rateLimit, RedirectRegex: middleware.Spec.RedirectRegex, RedirectScheme: middleware.Spec.RedirectScheme, BasicAuth: basicAuth, DigestAuth: digestAuth, ForwardAuth: forwardAuth, InFlightReq: middleware.Spec.InFlightReq, Buffering: middleware.Spec.Buffering, CircuitBreaker: circuitBreaker, Compress: createCompressMiddleware(middleware.Spec.Compress), PassTLSClientCert: middleware.Spec.PassTLSClientCert, Retry: retry, ContentType: middleware.Spec.ContentType, GrpcWeb: middleware.Spec.GrpcWeb, Plugin: plugin, } } for _, middlewareTCP := range client.GetMiddlewareTCPs() { id := provider.Normalize(makeID(middlewareTCP.Namespace, middlewareTCP.Name)) conf.TCP.Middlewares[id] = &dynamic.TCPMiddleware{ InFlightConn: middlewareTCP.Spec.InFlightConn, IPWhiteList: middlewareTCP.Spec.IPWhiteList, IPAllowList: middlewareTCP.Spec.IPAllowList, } } cb := configBuilder{ client: client, allowCrossNamespace: p.AllowCrossNamespace, allowExternalNameServices: p.AllowExternalNameServices, allowEmptyServices: p.AllowEmptyServices, } for _, service := range client.GetTraefikServices() { err := cb.buildTraefikService(ctx, service, conf.HTTP.Services) if err != nil { log.Ctx(ctx).Error().Str(logs.ServiceName, service.Name).Err(err). Msg("Error while building TraefikService") continue } } for _, serversTransport := range client.GetServersTransports() { logger := log.Ctx(ctx).With(). Str(logs.ServersTransportName, serversTransport.Name). Str("namespace", serversTransport.Namespace). Logger() if len(serversTransport.Spec.RootCAsSecrets) > 0 { logger.Warn().Msg("RootCAsSecrets option is deprecated, please use the RootCA option instead.") } var rootCAs []types.FileOrContent for _, secret := range serversTransport.Spec.RootCAsSecrets { caSecret, err := loadCASecret(serversTransport.Namespace, secret, client) if err != nil { logger.Error(). Err(err). Str("secret", secret). Msg("Error while loading CA Secret") continue } rootCAs = append(rootCAs, types.FileOrContent(caSecret)) } for _, rootCA := range serversTransport.Spec.RootCAs { if rootCA.Secret != nil && rootCA.ConfigMap != nil { logger.Error().Msg("Error while loading CA: both Secret and ConfigMap are defined") continue } if rootCA.Secret != nil { ca, err := loadCASecret(serversTransport.Namespace, *rootCA.Secret, client) if err != nil { logger.Error(). Err(err). Str("secret", *rootCA.Secret). Msg("Error while loading CA Secret") continue } rootCAs = append(rootCAs, types.FileOrContent(ca)) continue } ca, err := loadCAConfigMap(serversTransport.Namespace, *rootCA.ConfigMap, client) if err != nil { logger.Error(). Err(err). Str("configMap", *rootCA.ConfigMap). Msg("Error while loading CA ConfigMap") continue } rootCAs = append(rootCAs, types.FileOrContent(ca)) } var certs tls.Certificates for _, secret := range serversTransport.Spec.CertificatesSecrets { tlsSecret, tlsKey, err := loadAuthTLSSecret(serversTransport.Namespace, secret, client) if err != nil { logger.Error().Err(err).Msgf("Error while loading certificates %s", secret) continue } certs = append(certs, tls.Certificate{ CertFile: types.FileOrContent(tlsSecret), KeyFile: types.FileOrContent(tlsKey), }) } forwardingTimeout := &dynamic.ForwardingTimeouts{} forwardingTimeout.SetDefaults() if serversTransport.Spec.ForwardingTimeouts != nil { if serversTransport.Spec.ForwardingTimeouts.DialTimeout != nil { err := forwardingTimeout.DialTimeout.Set(serversTransport.Spec.ForwardingTimeouts.DialTimeout.String()) if err != nil { logger.Error().Err(err).Msg("Error while reading DialTimeout") } } if serversTransport.Spec.ForwardingTimeouts.ResponseHeaderTimeout != nil { err := forwardingTimeout.ResponseHeaderTimeout.Set(serversTransport.Spec.ForwardingTimeouts.ResponseHeaderTimeout.String()) if err != nil { logger.Error().Err(err).Msg("Error while reading ResponseHeaderTimeout") } } if serversTransport.Spec.ForwardingTimeouts.IdleConnTimeout != nil { err := forwardingTimeout.IdleConnTimeout.Set(serversTransport.Spec.ForwardingTimeouts.IdleConnTimeout.String()) if err != nil { logger.Error().Err(err).Msg("Error while reading IdleConnTimeout") } } if serversTransport.Spec.ForwardingTimeouts.ReadIdleTimeout != nil { err := forwardingTimeout.ReadIdleTimeout.Set(serversTransport.Spec.ForwardingTimeouts.ReadIdleTimeout.String()) if err != nil { logger.Error().Err(err).Msg("Error while reading ReadIdleTimeout") } } if serversTransport.Spec.ForwardingTimeouts.PingTimeout != nil { err := forwardingTimeout.PingTimeout.Set(serversTransport.Spec.ForwardingTimeouts.PingTimeout.String()) if err != nil { logger.Error().Err(err).Msg("Error while reading PingTimeout") } } } id := provider.Normalize(makeID(serversTransport.Namespace, serversTransport.Name)) conf.HTTP.ServersTransports[id] = &dynamic.ServersTransport{ ServerName: serversTransport.Spec.ServerName, InsecureSkipVerify: serversTransport.Spec.InsecureSkipVerify, RootCAs: rootCAs, Certificates: certs, DisableHTTP2: serversTransport.Spec.DisableHTTP2, MaxIdleConnsPerHost: serversTransport.Spec.MaxIdleConnsPerHost, ForwardingTimeouts: forwardingTimeout, PeerCertURI: serversTransport.Spec.PeerCertURI, Spiffe: serversTransport.Spec.Spiffe, } } for _, serversTransportTCP := range client.GetServersTransportTCPs() { logger := log.Ctx(ctx).With().Str(logs.ServersTransportName, serversTransportTCP.Name).Logger() var tcpServerTransport dynamic.TCPServersTransport tcpServerTransport.SetDefaults() if serversTransportTCP.Spec.DialTimeout != nil { err := tcpServerTransport.DialTimeout.Set(serversTransportTCP.Spec.DialTimeout.String()) if err != nil { logger.Error().Err(err).Msg("Error while reading DialTimeout") } } if serversTransportTCP.Spec.DialKeepAlive != nil { err := tcpServerTransport.DialKeepAlive.Set(serversTransportTCP.Spec.DialKeepAlive.String()) if err != nil { logger.Error().Err(err).Msg("Error while reading DialKeepAlive") } } if serversTransportTCP.Spec.TerminationDelay != nil { err := tcpServerTransport.TerminationDelay.Set(serversTransportTCP.Spec.TerminationDelay.String()) if err != nil { logger.Error().Err(err).Msg("Error while reading TerminationDelay") } } if serversTransportTCP.Spec.ProxyProtocol != nil { tcpServerTransport.ProxyProtocol = serversTransportTCP.Spec.ProxyProtocol } if serversTransportTCP.Spec.TLS != nil { if len(serversTransportTCP.Spec.TLS.RootCAsSecrets) > 0 { logger.Warn().Msg("RootCAsSecrets option is deprecated, please use the RootCA option instead.") } var rootCAs []types.FileOrContent for _, secret := range serversTransportTCP.Spec.TLS.RootCAsSecrets { caSecret, err := loadCASecret(serversTransportTCP.Namespace, secret, client) if err != nil { logger.Error(). Err(err). Str("secret", secret). Msg("Error while loading CA Secret") continue } rootCAs = append(rootCAs, types.FileOrContent(caSecret)) } for _, rootCA := range serversTransportTCP.Spec.TLS.RootCAs { if rootCA.Secret != nil && rootCA.ConfigMap != nil { logger.Error().Msg("Error while loading CA: both Secret and ConfigMap are defined") continue } if rootCA.Secret != nil { ca, err := loadCASecret(serversTransportTCP.Namespace, *rootCA.Secret, client) if err != nil { logger.Error(). Err(err). Str("secret", *rootCA.Secret). Msg("Error while loading CA Secret") continue } rootCAs = append(rootCAs, types.FileOrContent(ca)) continue } ca, err := loadCAConfigMap(serversTransportTCP.Namespace, *rootCA.ConfigMap, client) if err != nil { logger.Error(). Err(err). Str("configMap", *rootCA.ConfigMap). Msg("Error while loading CA ConfigMap") continue } rootCAs = append(rootCAs, types.FileOrContent(ca)) } var certs tls.Certificates for _, secret := range serversTransportTCP.Spec.TLS.CertificatesSecrets { tlsCert, tlsKey, err := loadAuthTLSSecret(serversTransportTCP.Namespace, secret, client) if err != nil { logger.Error(). Err(err). Str("certificates", secret). Msg("Error while loading certificates") continue } certs = append(certs, tls.Certificate{ CertFile: types.FileOrContent(tlsCert), KeyFile: types.FileOrContent(tlsKey), }) } tcpServerTransport.TLS = &dynamic.TLSClientConfig{ ServerName: serversTransportTCP.Spec.TLS.ServerName, InsecureSkipVerify: serversTransportTCP.Spec.TLS.InsecureSkipVerify, RootCAs: rootCAs, Certificates: certs, PeerCertURI: serversTransportTCP.Spec.TLS.PeerCertURI, } tcpServerTransport.TLS.Spiffe = serversTransportTCP.Spec.TLS.Spiffe } id := provider.Normalize(makeID(serversTransportTCP.Namespace, serversTransportTCP.Name)) conf.TCP.ServersTransports[id] = &tcpServerTransport } return conf } // getServicePort always returns a valid port, an error otherwise. func getServicePort(svc *corev1.Service, port intstr.IntOrString) (*corev1.ServicePort, error) { if svc == nil { return nil, errors.New("service is not defined") } if (port.Type == intstr.Int && port.IntVal == 0) || (port.Type == intstr.String && port.StrVal == "") { return nil, errors.New("ingressRoute service port not defined") } hasValidPort := false for _, p := range svc.Spec.Ports { if (port.Type == intstr.Int && port.IntVal == p.Port) || (port.Type == intstr.String && port.StrVal == p.Name) { return &p, nil } if p.Port != 0 { hasValidPort = true } } if svc.Spec.Type != corev1.ServiceTypeExternalName || port.Type == intstr.String { return nil, fmt.Errorf("service port not found: %s", &port) } if hasValidPort { log.Warn().Msgf("The port %s from IngressRoute doesn't match with ports defined in the ExternalName service %s/%s.", &port, svc.Namespace, svc.Name) } return &corev1.ServicePort{Port: port.IntVal}, nil } func getNativeServiceAddress(service corev1.Service, svcPort corev1.ServicePort) (string, error) { if service.Spec.ClusterIP == "None" { return "", fmt.Errorf("no clusterIP on headless service: %s/%s", service.Namespace, service.Name) } if service.Spec.ClusterIP == "" { return "", fmt.Errorf("no clusterIP found for service: %s/%s", service.Namespace, service.Name) } return net.JoinHostPort(service.Spec.ClusterIP, strconv.Itoa(int(svcPort.Port))), nil } func createPluginMiddleware(k8sClient Client, ns string, plugins map[string]apiextensionv1.JSON) (map[string]dynamic.PluginConf, error) { if plugins == nil { return nil, nil } data, err := json.Marshal(plugins) if err != nil { return nil, err } pcMap := map[string]dynamic.PluginConf{} if err = json.Unmarshal(data, &pcMap); err != nil { return nil, err } for _, pc := range pcMap { for key := range pc { if pc[key], err = loadSecretKeys(k8sClient, ns, pc[key]); err != nil { return nil, err } } } return pcMap, nil } func loadSecretKeys(k8sClient Client, ns string, i interface{}) (interface{}, error) { var err error switch iv := i.(type) { case string: if !strings.HasPrefix(iv, "urn:k8s:secret:") { return iv, nil } return getSecretValue(k8sClient, ns, iv) case []interface{}: for i := range iv { if iv[i], err = loadSecretKeys(k8sClient, ns, iv[i]); err != nil { return nil, err } } case map[string]interface{}: for k := range iv { if iv[k], err = loadSecretKeys(k8sClient, ns, iv[k]); err != nil { return nil, err } } } return i, nil } func getSecretValue(c Client, ns, urn string) (string, error) { parts := strings.Split(urn, ":") if len(parts) != 5 { return "", fmt.Errorf("malformed secret URN %q", urn) } secretName := parts[3] secret, ok, err := c.GetSecret(ns, secretName) if err != nil { return "", err } if !ok { return "", fmt.Errorf("secret %s/%s is not found", ns, secretName) } secretKey := parts[4] secretValue, ok := secret.Data[secretKey] if !ok { return "", fmt.Errorf("key %q not found in secret %s/%s", secretKey, ns, secretName) } return string(secretValue), nil } func createCircuitBreakerMiddleware(circuitBreaker *traefikv1alpha1.CircuitBreaker) (*dynamic.CircuitBreaker, error) { if circuitBreaker == nil { return nil, nil } cb := &dynamic.CircuitBreaker{Expression: circuitBreaker.Expression} cb.SetDefaults() if circuitBreaker.CheckPeriod != nil { if err := cb.CheckPeriod.Set(circuitBreaker.CheckPeriod.String()); err != nil { return nil, err } } if circuitBreaker.FallbackDuration != nil { if err := cb.FallbackDuration.Set(circuitBreaker.FallbackDuration.String()); err != nil { return nil, err } } if circuitBreaker.RecoveryDuration != nil { if err := cb.RecoveryDuration.Set(circuitBreaker.RecoveryDuration.String()); err != nil { return nil, err } } if circuitBreaker.ResponseCode != 0 { cb.ResponseCode = circuitBreaker.ResponseCode } return cb, nil } func createCompressMiddleware(compress *traefikv1alpha1.Compress) *dynamic.Compress { if compress == nil { return nil } c := &dynamic.Compress{} c.SetDefaults() if compress.ExcludedContentTypes != nil { c.ExcludedContentTypes = compress.ExcludedContentTypes } if compress.IncludedContentTypes != nil { c.IncludedContentTypes = compress.IncludedContentTypes } if compress.MinResponseBodyBytes != nil { c.MinResponseBodyBytes = *compress.MinResponseBodyBytes } if compress.Encodings != nil { c.Encodings = compress.Encodings } if compress.DefaultEncoding != nil { c.DefaultEncoding = *compress.DefaultEncoding } return c } func createRateLimitMiddleware(client Client, namespace string, rateLimit *traefikv1alpha1.RateLimit) (*dynamic.RateLimit, error) { if rateLimit == nil { return nil, nil } rl := &dynamic.RateLimit{} rl.SetDefaults() if rateLimit.Average != nil { rl.Average = *rateLimit.Average } if rateLimit.Burst != nil { rl.Burst = *rateLimit.Burst } if rateLimit.Period != nil { err := rl.Period.Set(rateLimit.Period.String()) if err != nil { return nil, err } } if rateLimit.SourceCriterion != nil { rl.SourceCriterion = rateLimit.SourceCriterion } if rateLimit.Redis != nil { rl.Redis = &dynamic.Redis{ DB: rateLimit.Redis.DB, PoolSize: rateLimit.Redis.PoolSize, MinIdleConns: rateLimit.Redis.MinIdleConns, MaxActiveConns: rateLimit.Redis.MaxActiveConns, } rl.Redis.SetDefaults() if len(rateLimit.Redis.Endpoints) > 0 { rl.Redis.Endpoints = rateLimit.Redis.Endpoints } if rateLimit.Redis.TLS != nil { rl.Redis.TLS = &types.ClientTLS{ InsecureSkipVerify: rateLimit.Redis.TLS.InsecureSkipVerify, } if len(rateLimit.Redis.TLS.CASecret) > 0 { caSecret, err := loadCASecret(namespace, rateLimit.Redis.TLS.CASecret, client) if err != nil { return nil, fmt.Errorf("failed to load auth ca secret: %w", err) } rl.Redis.TLS.CA = caSecret } if len(rateLimit.Redis.TLS.CertSecret) > 0 { authSecretCert, authSecretKey, err := loadAuthTLSSecret(namespace, rateLimit.Redis.TLS.CertSecret, client) if err != nil { return nil, fmt.Errorf("failed to load auth secret: %w", err) } rl.Redis.TLS.Cert = authSecretCert rl.Redis.TLS.Key = authSecretKey } } if rateLimit.Redis.DialTimeout != nil { err := rl.Redis.DialTimeout.Set(rateLimit.Redis.DialTimeout.String()) if err != nil { return nil, err } } if rateLimit.Redis.ReadTimeout != nil { err := rl.Redis.ReadTimeout.Set(rateLimit.Redis.ReadTimeout.String()) if err != nil { return nil, err } } if rateLimit.Redis.WriteTimeout != nil { err := rl.Redis.WriteTimeout.Set(rateLimit.Redis.WriteTimeout.String()) if err != nil { return nil, err } } if rateLimit.Redis.Secret != "" { var err error rl.Redis.Username, rl.Redis.Password, err = loadRedisCredentials(namespace, rateLimit.Redis.Secret, client) if err != nil { return nil, err } } } return rl, nil } func loadRedisCredentials(namespace, secretName string, k8sClient Client) (string, string, error) { secret, exists, err := k8sClient.GetSecret(namespace, secretName) if err != nil { return "", "", fmt.Errorf("failed to fetch secret '%s/%s': %w", namespace, secretName, err) } if !exists { return "", "", fmt.Errorf("secret '%s/%s' not found", namespace, secretName) } if secret == nil { return "", "", fmt.Errorf("data for secret '%s/%s' must not be nil", namespace, secretName) } username, usernameExists := secret.Data["username"] password, passwordExists := secret.Data["password"] if !usernameExists || !passwordExists { return "", "", fmt.Errorf("secret '%s/%s' must contain both username and password keys", secret.Namespace, secret.Name) } return string(username), string(password), nil } func createRetryMiddleware(retry *traefikv1alpha1.Retry) (*dynamic.Retry, error) { if retry == nil { return nil, nil } r := &dynamic.Retry{Attempts: retry.Attempts} err := r.InitialInterval.Set(retry.InitialInterval.String()) if err != nil { return nil, err } return r, nil } func (p *Provider) createErrorPageMiddleware(client Client, namespace string, errorPage *traefikv1alpha1.ErrorPage) (*dynamic.ErrorPage, *dynamic.Service, error) { if errorPage == nil { return nil, nil, nil } errorPageMiddleware := &dynamic.ErrorPage{ Status: errorPage.Status, StatusRewrites: errorPage.StatusRewrites, Query: errorPage.Query, } cb := configBuilder{ client: client, allowCrossNamespace: p.AllowCrossNamespace, allowExternalNameServices: p.AllowExternalNameServices, allowEmptyServices: p.AllowEmptyServices, } balancerServerHTTP, err := cb.buildServersLB(namespace, errorPage.Service.LoadBalancerSpec) if err != nil { return nil, nil, err } return errorPageMiddleware, balancerServerHTTP, nil } func (p *Provider) FillExtensionBuilderRegistry(registry gateway.ExtensionBuilderRegistry) { registry.RegisterFilterFuncs(traefikv1alpha1.GroupName, "Middleware", func(name, namespace string) (string, *dynamic.Middleware, error) { if len(p.Namespaces) > 0 && !slices.Contains(p.Namespaces, namespace) { return "", nil, fmt.Errorf("namespace %q is not allowed", namespace) } return makeID(namespace, name) + providerNamespaceSeparator + providerName, nil, nil }) registry.RegisterBackendFuncs(traefikv1alpha1.GroupName, "TraefikService", func(name, namespace string) (string, *dynamic.Service, error) { if len(p.Namespaces) > 0 && !slices.Contains(p.Namespaces, namespace) { return "", nil, fmt.Errorf("namespace %q is not allowed", namespace) } return makeID(namespace, name) + providerNamespaceSeparator + providerName, nil, nil }) } func createForwardAuthMiddleware(k8sClient Client, namespace string, auth *traefikv1alpha1.ForwardAuth) (*dynamic.ForwardAuth, error) { if auth == nil { return nil, nil } if len(auth.Address) == 0 { return nil, errors.New("forward authentication requires an address") } forwardAuth := &dynamic.ForwardAuth{ Address: auth.Address, TrustForwardHeader: auth.TrustForwardHeader, AuthResponseHeaders: auth.AuthResponseHeaders, AuthResponseHeadersRegex: auth.AuthResponseHeadersRegex, AuthRequestHeaders: auth.AuthRequestHeaders, AddAuthCookiesToResponse: auth.AddAuthCookiesToResponse, HeaderField: auth.HeaderField, ForwardBody: auth.ForwardBody, PreserveLocationHeader: auth.PreserveLocationHeader, PreserveRequestMethod: auth.PreserveRequestMethod, } forwardAuth.SetDefaults() if auth.MaxBodySize != nil {
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/crd/traefikio/v1alpha1/middleware.go
pkg/provider/kubernetes/crd/traefikio/v1alpha1/middleware.go
package v1alpha1 import ( "github.com/traefik/traefik/v3/pkg/config/dynamic" apiextensionv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" ) // +genclient // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +kubebuilder:storageversion // Middleware is the CRD implementation of a Traefik Middleware. // More info: https://doc.traefik.io/traefik/v3.6/reference/routing-configuration/http/middlewares/overview/ type Middleware struct { metav1.TypeMeta `json:",inline"` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata metav1.ObjectMeta `json:"metadata"` Spec MiddlewareSpec `json:"spec"` } // +k8s:deepcopy-gen=true // MiddlewareSpec defines the desired state of a Middleware. type MiddlewareSpec struct { AddPrefix *dynamic.AddPrefix `json:"addPrefix,omitempty"` StripPrefix *dynamic.StripPrefix `json:"stripPrefix,omitempty"` StripPrefixRegex *dynamic.StripPrefixRegex `json:"stripPrefixRegex,omitempty"` ReplacePath *dynamic.ReplacePath `json:"replacePath,omitempty"` ReplacePathRegex *dynamic.ReplacePathRegex `json:"replacePathRegex,omitempty"` Chain *Chain `json:"chain,omitempty"` // Deprecated: please use IPAllowList instead. IPWhiteList *dynamic.IPWhiteList `json:"ipWhiteList,omitempty"` IPAllowList *dynamic.IPAllowList `json:"ipAllowList,omitempty"` Headers *dynamic.Headers `json:"headers,omitempty"` Errors *ErrorPage `json:"errors,omitempty"` RateLimit *RateLimit `json:"rateLimit,omitempty"` RedirectRegex *dynamic.RedirectRegex `json:"redirectRegex,omitempty"` RedirectScheme *dynamic.RedirectScheme `json:"redirectScheme,omitempty"` BasicAuth *BasicAuth `json:"basicAuth,omitempty"` DigestAuth *DigestAuth `json:"digestAuth,omitempty"` ForwardAuth *ForwardAuth `json:"forwardAuth,omitempty"` InFlightReq *dynamic.InFlightReq `json:"inFlightReq,omitempty"` Buffering *dynamic.Buffering `json:"buffering,omitempty"` CircuitBreaker *CircuitBreaker `json:"circuitBreaker,omitempty"` Compress *Compress `json:"compress,omitempty"` PassTLSClientCert *dynamic.PassTLSClientCert `json:"passTLSClientCert,omitempty"` Retry *Retry `json:"retry,omitempty"` ContentType *dynamic.ContentType `json:"contentType,omitempty"` GrpcWeb *dynamic.GrpcWeb `json:"grpcWeb,omitempty"` // Plugin defines the middleware plugin configuration. // More info: https://doc.traefik.io/traefik/v3.6/reference/routing-configuration/http/middlewares/overview/#community-middlewares Plugin map[string]apiextensionv1.JSON `json:"plugin,omitempty"` } // +k8s:deepcopy-gen=true // ErrorPage holds the custom error middleware configuration. // This middleware returns a custom page in lieu of the default, according to configured ranges of HTTP Status codes. // More info: https://doc.traefik.io/traefik/v3.6/reference/routing-configuration/http/middlewares/errorpages/ type ErrorPage struct { // Status defines which status or range of statuses should result in an error page. // It can be either a status code as a number (500), // as multiple comma-separated numbers (500,502), // as ranges by separating two codes with a dash (500-599), // or a combination of the two (404,418,500-599). // +kubebuilder:validation:items:Pattern=`^([1-5][0-9]{2}[,-]?)+$` Status []string `json:"status,omitempty"` // StatusRewrites defines a mapping of status codes that should be returned instead of the original error status codes. // For example: "418": 404 or "410-418": 404 StatusRewrites map[string]int `json:"statusRewrites,omitempty"` // Service defines the reference to a Kubernetes Service that will serve the error page. // More info: https://doc.traefik.io/traefik/v3.6/reference/routing-configuration/http/middlewares/errorpages/#service Service Service `json:"service,omitempty"` // Query defines the URL for the error page (hosted by service). // The {status} variable can be used in order to insert the status code in the URL. // The {originalStatus} variable can be used in order to insert the upstream status code in the URL. // The {url} variable can be used in order to insert the escaped request URL. Query string `json:"query,omitempty"` } // +k8s:deepcopy-gen=true // CircuitBreaker holds the circuit breaker configuration. type CircuitBreaker struct { // Expression is the condition that triggers the tripped state. Expression string `json:"expression,omitempty" toml:"expression,omitempty" yaml:"expression,omitempty" export:"true"` // CheckPeriod is the interval between successive checks of the circuit breaker condition (when in standby state). // +kubebuilder:validation:Pattern="^([0-9]+(ns|us|µs|ms|s|m|h)?)+$" // +kubebuilder:validation:XIntOrString CheckPeriod *intstr.IntOrString `json:"checkPeriod,omitempty" toml:"checkPeriod,omitempty" yaml:"checkPeriod,omitempty" export:"true"` // FallbackDuration is the duration for which the circuit breaker will wait before trying to recover (from a tripped state). FallbackDuration *intstr.IntOrString `json:"fallbackDuration,omitempty" toml:"fallbackDuration,omitempty" yaml:"fallbackDuration,omitempty" export:"true"` // RecoveryDuration is the duration for which the circuit breaker will try to recover (as soon as it is in recovering state). // +kubebuilder:validation:Pattern="^([0-9]+(ns|us|µs|ms|s|m|h)?)+$" // +kubebuilder:validation:XIntOrString RecoveryDuration *intstr.IntOrString `json:"recoveryDuration,omitempty" toml:"recoveryDuration,omitempty" yaml:"recoveryDuration,omitempty" export:"true"` // ResponseCode is the status code that the circuit breaker will return while it is in the open state. // +kubebuilder:validation:Minimum=100 // +kubebuilder:validation:Maximum=599 ResponseCode int `json:"responseCode,omitempty" toml:"responseCode,omitempty" yaml:"responseCode,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // Chain holds the configuration of the chain middleware. // This middleware enables to define reusable combinations of other pieces of middleware. // More info: https://doc.traefik.io/traefik/v3.6/reference/routing-configuration/http/middlewares/chain/ type Chain struct { // Middlewares is the list of MiddlewareRef which composes the chain. Middlewares []MiddlewareRef `json:"middlewares,omitempty"` } // +k8s:deepcopy-gen=true // BasicAuth holds the basic auth middleware configuration. // This middleware restricts access to your services to known users. // More info: https://doc.traefik.io/traefik/v3.6/reference/routing-configuration/http/middlewares/basicauth/ type BasicAuth struct { // Secret is the name of the referenced Kubernetes Secret containing user credentials. Secret string `json:"secret,omitempty"` // Realm allows the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme. // Default: traefik. Realm string `json:"realm,omitempty"` // RemoveHeader sets the removeHeader option to true to remove the authorization header before forwarding the request to your service. // Default: false. RemoveHeader bool `json:"removeHeader,omitempty"` // HeaderField defines a header field to store the authenticated user. // More info: https://doc.traefik.io/traefik/v3.6/reference/routing-configuration/http/middlewares/basicauth/#headerfield HeaderField string `json:"headerField,omitempty"` } // +k8s:deepcopy-gen=true // DigestAuth holds the digest auth middleware configuration. // This middleware restricts access to your services to known users. // More info: https://doc.traefik.io/traefik/v3.6/reference/routing-configuration/http/middlewares/digestauth/ type DigestAuth struct { // Secret is the name of the referenced Kubernetes Secret containing user credentials. Secret string `json:"secret,omitempty"` // RemoveHeader defines whether to remove the authorization header before forwarding the request to the backend. RemoveHeader bool `json:"removeHeader,omitempty"` // Realm allows the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme. // Default: traefik. Realm string `json:"realm,omitempty"` // HeaderField defines a header field to store the authenticated user. // More info: https://doc.traefik.io/traefik/v3.6/reference/routing-configuration/http/middlewares/digestauth/#headerfield HeaderField string `json:"headerField,omitempty"` } // +k8s:deepcopy-gen=true // ForwardAuth holds the forward auth middleware configuration. // This middleware delegates the request authentication to a Service. // More info: https://doc.traefik.io/traefik/v3.6/reference/routing-configuration/http/middlewares/forwardauth/ type ForwardAuth struct { // Address defines the authentication server address. Address string `json:"address,omitempty"` // TrustForwardHeader defines whether to trust (ie: forward) all X-Forwarded-* headers. TrustForwardHeader bool `json:"trustForwardHeader,omitempty"` // AuthResponseHeaders defines the list of headers to copy from the authentication server response and set on forwarded request, replacing any existing conflicting headers. AuthResponseHeaders []string `json:"authResponseHeaders,omitempty"` // AuthResponseHeadersRegex defines the regex to match headers to copy from the authentication server response and set on forwarded request, after stripping all headers that match the regex. // More info: https://doc.traefik.io/traefik/v3.6/reference/routing-configuration/http/middlewares/forwardauth/#authresponseheadersregex AuthResponseHeadersRegex string `json:"authResponseHeadersRegex,omitempty"` // AuthRequestHeaders defines the list of the headers to copy from the request to the authentication server. // If not set or empty then all request headers are passed. AuthRequestHeaders []string `json:"authRequestHeaders,omitempty"` // TLS defines the configuration used to secure the connection to the authentication server. TLS *ClientTLSWithCAOptional `json:"tls,omitempty"` // AddAuthCookiesToResponse defines the list of cookies to copy from the authentication server response to the response. AddAuthCookiesToResponse []string `json:"addAuthCookiesToResponse,omitempty"` // HeaderField defines a header field to store the authenticated user. // More info: https://doc.traefik.io/traefik/v3.6/reference/routing-configuration/http/middlewares/forwardauth/#headerfield HeaderField string `json:"headerField,omitempty"` // ForwardBody defines whether to send the request body to the authentication server. ForwardBody bool `json:"forwardBody,omitempty"` // MaxBodySize defines the maximum body size in bytes allowed to be forwarded to the authentication server. MaxBodySize *int64 `json:"maxBodySize,omitempty"` // PreserveLocationHeader defines whether to forward the Location header to the client as is or prefix it with the domain name of the authentication server. PreserveLocationHeader bool `json:"preserveLocationHeader,omitempty"` // PreserveRequestMethod defines whether to preserve the original request method while forwarding the request to the authentication server. PreserveRequestMethod bool `json:"preserveRequestMethod,omitempty"` } // +k8s:deepcopy-gen=true // ClientTLSWithCAOptional holds the client TLS configuration. // TODO: This has to be removed once the CAOptional option is removed. type ClientTLSWithCAOptional struct { ClientTLS `json:",inline"` // Deprecated: TLS client authentication is a server side option (see https://github.com/golang/go/blob/740a490f71d026bb7d2d13cb8fa2d6d6e0572b70/src/crypto/tls/common.go#L634). CAOptional *bool `json:"caOptional,omitempty"` } // +k8s:deepcopy-gen=true // RateLimit holds the rate limit configuration. // This middleware ensures that services will receive a fair amount of requests, and allows one to define what fair is. // More info: https://doc.traefik.io/traefik/v3.6/reference/routing-configuration/http/middlewares/ratelimit/ type RateLimit struct { // Average is the maximum rate, by default in requests/s, allowed for the given source. // It defaults to 0, which means no rate limiting. // The rate is actually defined by dividing Average by Period. So for a rate below 1req/s, // one needs to define a Period larger than a second. // +kubebuilder:validation:Minimum=0 Average *int64 `json:"average,omitempty"` // Period, in combination with Average, defines the actual maximum rate, such as: // r = Average / Period. It defaults to a second. // +kubebuilder:validation:XIntOrString Period *intstr.IntOrString `json:"period,omitempty"` // Burst is the maximum number of requests allowed to arrive in the same arbitrarily small period of time. // It defaults to 1. // +kubebuilder:validation:Minimum=0 Burst *int64 `json:"burst,omitempty"` // SourceCriterion defines what criterion is used to group requests as originating from a common source. // If several strategies are defined at the same time, an error will be raised. // If none are set, the default is to use the request's remote address field (as an ipStrategy). SourceCriterion *dynamic.SourceCriterion `json:"sourceCriterion,omitempty"` // Redis hold the configs of Redis as bucket in rate limiter. Redis *Redis `json:"redis,omitempty"` } // +k8s:deepcopy-gen=true // Redis contains the configuration for using Redis in middleware. // In a Kubernetes setup, the username and password are stored in a Secret file within the same namespace as the middleware. type Redis struct { // Endpoints contains either a single address or a seed list of host:port addresses. // Default value is ["localhost:6379"]. Endpoints []string `json:"endpoints,omitempty"` // TLS defines TLS-specific configurations, including the CA, certificate, and key, // which can be provided as a file path or file content. TLS *ClientTLS `json:"tls,omitempty"` // Secret defines the name of the referenced Kubernetes Secret containing Redis credentials. Secret string `json:"secret,omitempty"` // DB defines the Redis database that will be selected after connecting to the server. DB int `json:"db,omitempty"` // PoolSize defines the initial number of socket connections. // If the pool runs out of available connections, additional ones will be created beyond PoolSize. // This can be limited using MaxActiveConns. // // Default value is 0, meaning 10 connections per every available CPU as reported by runtime.GOMAXPROCS. PoolSize int `json:"poolSize,omitempty"` // MinIdleConns defines the minimum number of idle connections. // Default value is 0, and idle connections are not closed by default. MinIdleConns int `json:"minIdleConns,omitempty"` // MaxActiveConns defines the maximum number of connections allocated by the pool at a given time. // Default value is 0, meaning there is no limit. MaxActiveConns int `json:"maxActiveConns,omitempty"` // ReadTimeout defines the timeout for socket read operations. // Default value is 3 seconds. // +kubebuilder:validation:Pattern="^([0-9]+(ns|us|µs|ms|s|m|h)?)+$" // +kubebuilder:validation:XIntOrString ReadTimeout *intstr.IntOrString `json:"readTimeout,omitempty"` // WriteTimeout defines the timeout for socket write operations. // Default value is 3 seconds. // +kubebuilder:validation:Pattern="^([0-9]+(ns|us|µs|ms|s|m|h)?)+$" // +kubebuilder:validation:XIntOrString WriteTimeout *intstr.IntOrString `json:"writeTimeout,omitempty"` // DialTimeout sets the timeout for establishing new connections. // Default value is 5 seconds. // +kubebuilder:validation:Pattern="^([0-9]+(ns|us|µs|ms|s|m|h)?)+$" // +kubebuilder:validation:XIntOrString DialTimeout *intstr.IntOrString `json:"dialTimeout,omitempty"` } // +k8s:deepcopy-gen=true // ClientTLS holds the client TLS configuration. type ClientTLS struct { // CASecret is the name of the referenced Kubernetes Secret containing the CA to validate the server certificate. // The CA certificate is extracted from key `tls.ca` or `ca.crt`. CASecret string `json:"caSecret,omitempty"` // CertSecret is the name of the referenced Kubernetes Secret containing the client certificate. // The client certificate is extracted from the keys `tls.crt` and `tls.key`. CertSecret string `json:"certSecret,omitempty"` // InsecureSkipVerify defines whether the server certificates should be validated. InsecureSkipVerify bool `json:"insecureSkipVerify,omitempty"` } // +k8s:deepcopy-gen=true // Compress holds the compress middleware configuration. // This middleware compresses responses before sending them to the client, using gzip, brotli, or zstd compression. // More info: https://doc.traefik.io/traefik/v3.6/reference/routing-configuration/http/middlewares/compress/ type Compress struct { // ExcludedContentTypes defines the list of content types to compare the Content-Type header of the incoming requests and responses before compressing. // `application/grpc` is always excluded. ExcludedContentTypes []string `json:"excludedContentTypes,omitempty"` // IncludedContentTypes defines the list of content types to compare the Content-Type header of the responses before compressing. IncludedContentTypes []string `json:"includedContentTypes,omitempty"` // MinResponseBodyBytes defines the minimum amount of bytes a response body must have to be compressed. // Default: 1024. // +kubebuilder:validation:Minimum=0 MinResponseBodyBytes *int `json:"minResponseBodyBytes,omitempty"` // Encodings defines the list of supported compression algorithms. Encodings []string `json:"encodings,omitempty"` // DefaultEncoding specifies the default encoding if the `Accept-Encoding` header is not in the request or contains a wildcard (`*`). DefaultEncoding *string `json:"defaultEncoding,omitempty"` } // +k8s:deepcopy-gen=true // Retry holds the retry middleware configuration. // This middleware reissues requests a given number of times to a backend server if that server does not reply. // As soon as the server answers, the middleware stops retrying, regardless of the response status. // More info: https://doc.traefik.io/traefik/v3.6/reference/routing-configuration/http/middlewares/retry/ type Retry struct { // Attempts defines how many times the request should be retried. // +kubebuilder:validation:Minimum=0 Attempts int `json:"attempts,omitempty"` // InitialInterval defines the first wait time in the exponential backoff series. // The maximum interval is calculated as twice the initialInterval. // If unspecified, requests will be retried immediately. // The value of initialInterval should be provided in seconds or as a valid duration format, // see https://pkg.go.dev/time#ParseDuration. // +kubebuilder:validation:Pattern="^([0-9]+(ns|us|µs|ms|s|m|h)?)+$" // +kubebuilder:validation:XIntOrString InitialInterval intstr.IntOrString `json:"initialInterval,omitempty"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // MiddlewareList is a collection of Middleware resources. type MiddlewareList struct { metav1.TypeMeta `json:",inline"` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata metav1.ListMeta `json:"metadata"` // Items is the list of Middleware. Items []Middleware `json:"items"` }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/crd/traefikio/v1alpha1/zz_generated.deepcopy.go
pkg/provider/kubernetes/crd/traefikio/v1alpha1/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 v1alpha1 import ( dynamic "github.com/traefik/traefik/v3/pkg/config/dynamic" tls "github.com/traefik/traefik/v3/pkg/tls" types "github.com/traefik/traefik/v3/pkg/types" v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" runtime "k8s.io/apimachinery/pkg/runtime" intstr "k8s.io/apimachinery/pkg/util/intstr" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *BasicAuth) DeepCopyInto(out *BasicAuth) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BasicAuth. func (in *BasicAuth) DeepCopy() *BasicAuth { if in == nil { return nil } out := new(BasicAuth) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Certificate) DeepCopyInto(out *Certificate) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Certificate. func (in *Certificate) DeepCopy() *Certificate { if in == nil { return nil } out := new(Certificate) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Chain) DeepCopyInto(out *Chain) { *out = *in if in.Middlewares != nil { in, out := &in.Middlewares, &out.Middlewares *out = make([]MiddlewareRef, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Chain. func (in *Chain) DeepCopy() *Chain { if in == nil { return nil } out := new(Chain) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CircuitBreaker) DeepCopyInto(out *CircuitBreaker) { *out = *in if in.CheckPeriod != nil { in, out := &in.CheckPeriod, &out.CheckPeriod *out = new(intstr.IntOrString) **out = **in } if in.FallbackDuration != nil { in, out := &in.FallbackDuration, &out.FallbackDuration *out = new(intstr.IntOrString) **out = **in } if in.RecoveryDuration != nil { in, out := &in.RecoveryDuration, &out.RecoveryDuration *out = new(intstr.IntOrString) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CircuitBreaker. func (in *CircuitBreaker) DeepCopy() *CircuitBreaker { if in == nil { return nil } out := new(CircuitBreaker) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ClientAuth) DeepCopyInto(out *ClientAuth) { *out = *in if in.SecretNames != nil { in, out := &in.SecretNames, &out.SecretNames *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClientAuth. func (in *ClientAuth) DeepCopy() *ClientAuth { if in == nil { return nil } out := new(ClientAuth) in.DeepCopyInto(out) return out } // 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 *ClientTLSWithCAOptional) DeepCopyInto(out *ClientTLSWithCAOptional) { *out = *in out.ClientTLS = in.ClientTLS if in.CAOptional != nil { in, out := &in.CAOptional, &out.CAOptional *out = new(bool) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClientTLSWithCAOptional. func (in *ClientTLSWithCAOptional) DeepCopy() *ClientTLSWithCAOptional { if in == nil { return nil } out := new(ClientTLSWithCAOptional) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Compress) DeepCopyInto(out *Compress) { *out = *in if in.ExcludedContentTypes != nil { in, out := &in.ExcludedContentTypes, &out.ExcludedContentTypes *out = make([]string, len(*in)) copy(*out, *in) } if in.IncludedContentTypes != nil { in, out := &in.IncludedContentTypes, &out.IncludedContentTypes *out = make([]string, len(*in)) copy(*out, *in) } if in.MinResponseBodyBytes != nil { in, out := &in.MinResponseBodyBytes, &out.MinResponseBodyBytes *out = new(int) **out = **in } if in.Encodings != nil { in, out := &in.Encodings, &out.Encodings *out = make([]string, len(*in)) copy(*out, *in) } if in.DefaultEncoding != nil { in, out := &in.DefaultEncoding, &out.DefaultEncoding *out = new(string) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Compress. func (in *Compress) DeepCopy() *Compress { if in == nil { return nil } out := new(Compress) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DigestAuth) DeepCopyInto(out *DigestAuth) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DigestAuth. func (in *DigestAuth) DeepCopy() *DigestAuth { if in == nil { return nil } out := new(DigestAuth) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ErrorPage) DeepCopyInto(out *ErrorPage) { *out = *in if in.Status != nil { in, out := &in.Status, &out.Status *out = make([]string, len(*in)) copy(*out, *in) } if in.StatusRewrites != nil { in, out := &in.StatusRewrites, &out.StatusRewrites *out = make(map[string]int, len(*in)) for key, val := range *in { (*out)[key] = val } } in.Service.DeepCopyInto(&out.Service) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ErrorPage. func (in *ErrorPage) DeepCopy() *ErrorPage { if in == nil { return nil } out := new(ErrorPage) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ForwardAuth) DeepCopyInto(out *ForwardAuth) { *out = *in if in.AuthResponseHeaders != nil { in, out := &in.AuthResponseHeaders, &out.AuthResponseHeaders *out = make([]string, len(*in)) copy(*out, *in) } if in.AuthRequestHeaders != nil { in, out := &in.AuthRequestHeaders, &out.AuthRequestHeaders *out = make([]string, len(*in)) copy(*out, *in) } if in.TLS != nil { in, out := &in.TLS, &out.TLS *out = new(ClientTLSWithCAOptional) (*in).DeepCopyInto(*out) } if in.AddAuthCookiesToResponse != nil { in, out := &in.AddAuthCookiesToResponse, &out.AddAuthCookiesToResponse *out = make([]string, len(*in)) copy(*out, *in) } if in.MaxBodySize != nil { in, out := &in.MaxBodySize, &out.MaxBodySize *out = new(int64) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ForwardAuth. func (in *ForwardAuth) DeepCopy() *ForwardAuth { if in == nil { return nil } out := new(ForwardAuth) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ForwardingTimeouts) DeepCopyInto(out *ForwardingTimeouts) { *out = *in if in.DialTimeout != nil { in, out := &in.DialTimeout, &out.DialTimeout *out = new(intstr.IntOrString) **out = **in } if in.ResponseHeaderTimeout != nil { in, out := &in.ResponseHeaderTimeout, &out.ResponseHeaderTimeout *out = new(intstr.IntOrString) **out = **in } if in.IdleConnTimeout != nil { in, out := &in.IdleConnTimeout, &out.IdleConnTimeout *out = new(intstr.IntOrString) **out = **in } if in.ReadIdleTimeout != nil { in, out := &in.ReadIdleTimeout, &out.ReadIdleTimeout *out = new(intstr.IntOrString) **out = **in } if in.PingTimeout != nil { in, out := &in.PingTimeout, &out.PingTimeout *out = new(intstr.IntOrString) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ForwardingTimeouts. func (in *ForwardingTimeouts) DeepCopy() *ForwardingTimeouts { if in == nil { return nil } out := new(ForwardingTimeouts) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HighestRandomWeight) DeepCopyInto(out *HighestRandomWeight) { *out = *in if in.Services != nil { in, out := &in.Services, &out.Services *out = make([]Service, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HighestRandomWeight. func (in *HighestRandomWeight) DeepCopy() *HighestRandomWeight { if in == nil { return nil } out := new(HighestRandomWeight) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IngressRoute) DeepCopyInto(out *IngressRoute) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressRoute. func (in *IngressRoute) DeepCopy() *IngressRoute { if in == nil { return nil } out := new(IngressRoute) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *IngressRoute) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IngressRouteList) DeepCopyInto(out *IngressRouteList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]IngressRoute, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressRouteList. func (in *IngressRouteList) DeepCopy() *IngressRouteList { if in == nil { return nil } out := new(IngressRouteList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *IngressRouteList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IngressRouteRef) DeepCopyInto(out *IngressRouteRef) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressRouteRef. func (in *IngressRouteRef) DeepCopy() *IngressRouteRef { if in == nil { return nil } out := new(IngressRouteRef) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IngressRouteSpec) DeepCopyInto(out *IngressRouteSpec) { *out = *in if in.Routes != nil { in, out := &in.Routes, &out.Routes *out = make([]Route, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.EntryPoints != nil { in, out := &in.EntryPoints, &out.EntryPoints *out = make([]string, len(*in)) copy(*out, *in) } if in.TLS != nil { in, out := &in.TLS, &out.TLS *out = new(TLS) (*in).DeepCopyInto(*out) } if in.ParentRefs != nil { in, out := &in.ParentRefs, &out.ParentRefs *out = make([]IngressRouteRef, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressRouteSpec. func (in *IngressRouteSpec) DeepCopy() *IngressRouteSpec { if in == nil { return nil } out := new(IngressRouteSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IngressRouteTCP) DeepCopyInto(out *IngressRouteTCP) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressRouteTCP. func (in *IngressRouteTCP) DeepCopy() *IngressRouteTCP { if in == nil { return nil } out := new(IngressRouteTCP) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *IngressRouteTCP) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IngressRouteTCPList) DeepCopyInto(out *IngressRouteTCPList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]IngressRouteTCP, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressRouteTCPList. func (in *IngressRouteTCPList) DeepCopy() *IngressRouteTCPList { if in == nil { return nil } out := new(IngressRouteTCPList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *IngressRouteTCPList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IngressRouteTCPSpec) DeepCopyInto(out *IngressRouteTCPSpec) { *out = *in if in.Routes != nil { in, out := &in.Routes, &out.Routes *out = make([]RouteTCP, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.EntryPoints != nil { in, out := &in.EntryPoints, &out.EntryPoints *out = make([]string, len(*in)) copy(*out, *in) } if in.TLS != nil { in, out := &in.TLS, &out.TLS *out = new(TLSTCP) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressRouteTCPSpec. func (in *IngressRouteTCPSpec) DeepCopy() *IngressRouteTCPSpec { if in == nil { return nil } out := new(IngressRouteTCPSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IngressRouteUDP) DeepCopyInto(out *IngressRouteUDP) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressRouteUDP. func (in *IngressRouteUDP) DeepCopy() *IngressRouteUDP { if in == nil { return nil } out := new(IngressRouteUDP) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *IngressRouteUDP) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IngressRouteUDPList) DeepCopyInto(out *IngressRouteUDPList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]IngressRouteUDP, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressRouteUDPList. func (in *IngressRouteUDPList) DeepCopy() *IngressRouteUDPList { if in == nil { return nil } out := new(IngressRouteUDPList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *IngressRouteUDPList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IngressRouteUDPSpec) DeepCopyInto(out *IngressRouteUDPSpec) { *out = *in if in.Routes != nil { in, out := &in.Routes, &out.Routes *out = make([]RouteUDP, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.EntryPoints != nil { in, out := &in.EntryPoints, &out.EntryPoints *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IngressRouteUDPSpec. func (in *IngressRouteUDPSpec) DeepCopy() *IngressRouteUDPSpec { if in == nil { return nil } out := new(IngressRouteUDPSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *LoadBalancerSpec) DeepCopyInto(out *LoadBalancerSpec) { *out = *in if in.Sticky != nil { in, out := &in.Sticky, &out.Sticky *out = new(dynamic.Sticky) (*in).DeepCopyInto(*out) } out.Port = in.Port if in.PassHostHeader != nil { in, out := &in.PassHostHeader, &out.PassHostHeader *out = new(bool) **out = **in } if in.ResponseForwarding != nil { in, out := &in.ResponseForwarding, &out.ResponseForwarding *out = new(ResponseForwarding) **out = **in } if in.Weight != nil { in, out := &in.Weight, &out.Weight *out = new(int) **out = **in } if in.NativeLB != nil { in, out := &in.NativeLB, &out.NativeLB *out = new(bool) **out = **in } if in.HealthCheck != nil { in, out := &in.HealthCheck, &out.HealthCheck *out = new(ServerHealthCheck) (*in).DeepCopyInto(*out) } if in.PassiveHealthCheck != nil { in, out := &in.PassiveHealthCheck, &out.PassiveHealthCheck *out = new(PassiveServerHealthCheck) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LoadBalancerSpec. func (in *LoadBalancerSpec) DeepCopy() *LoadBalancerSpec { if in == nil { return nil } out := new(LoadBalancerSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Middleware) DeepCopyInto(out *Middleware) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Middleware. func (in *Middleware) DeepCopy() *Middleware { if in == nil { return nil } out := new(Middleware) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *Middleware) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MiddlewareList) DeepCopyInto(out *MiddlewareList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Middleware, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MiddlewareList. func (in *MiddlewareList) DeepCopy() *MiddlewareList { if in == nil { return nil } out := new(MiddlewareList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *MiddlewareList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MiddlewareRef) DeepCopyInto(out *MiddlewareRef) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MiddlewareRef. func (in *MiddlewareRef) DeepCopy() *MiddlewareRef { if in == nil { return nil } out := new(MiddlewareRef) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MiddlewareSpec) DeepCopyInto(out *MiddlewareSpec) { *out = *in if in.AddPrefix != nil { in, out := &in.AddPrefix, &out.AddPrefix *out = new(dynamic.AddPrefix) **out = **in } if in.StripPrefix != nil { in, out := &in.StripPrefix, &out.StripPrefix *out = new(dynamic.StripPrefix) (*in).DeepCopyInto(*out) } if in.StripPrefixRegex != nil { in, out := &in.StripPrefixRegex, &out.StripPrefixRegex *out = new(dynamic.StripPrefixRegex) (*in).DeepCopyInto(*out) } if in.ReplacePath != nil { in, out := &in.ReplacePath, &out.ReplacePath *out = new(dynamic.ReplacePath) **out = **in } if in.ReplacePathRegex != nil { in, out := &in.ReplacePathRegex, &out.ReplacePathRegex *out = new(dynamic.ReplacePathRegex) **out = **in } if in.Chain != nil { in, out := &in.Chain, &out.Chain *out = new(Chain) (*in).DeepCopyInto(*out) } if in.IPWhiteList != nil { in, out := &in.IPWhiteList, &out.IPWhiteList *out = new(dynamic.IPWhiteList) (*in).DeepCopyInto(*out) } if in.IPAllowList != nil { in, out := &in.IPAllowList, &out.IPAllowList *out = new(dynamic.IPAllowList) (*in).DeepCopyInto(*out) } if in.Headers != nil { in, out := &in.Headers, &out.Headers *out = new(dynamic.Headers) (*in).DeepCopyInto(*out) } if in.Errors != nil { in, out := &in.Errors, &out.Errors *out = new(ErrorPage) (*in).DeepCopyInto(*out) } if in.RateLimit != nil { in, out := &in.RateLimit, &out.RateLimit *out = new(RateLimit) (*in).DeepCopyInto(*out) } if in.RedirectRegex != nil { in, out := &in.RedirectRegex, &out.RedirectRegex *out = new(dynamic.RedirectRegex) **out = **in } if in.RedirectScheme != nil { in, out := &in.RedirectScheme, &out.RedirectScheme *out = new(dynamic.RedirectScheme) **out = **in } if in.BasicAuth != nil { in, out := &in.BasicAuth, &out.BasicAuth *out = new(BasicAuth) **out = **in } if in.DigestAuth != nil { in, out := &in.DigestAuth, &out.DigestAuth *out = new(DigestAuth) **out = **in } if in.ForwardAuth != nil { in, out := &in.ForwardAuth, &out.ForwardAuth *out = new(ForwardAuth) (*in).DeepCopyInto(*out) } if in.InFlightReq != nil { in, out := &in.InFlightReq, &out.InFlightReq *out = new(dynamic.InFlightReq) (*in).DeepCopyInto(*out) } if in.Buffering != nil { in, out := &in.Buffering, &out.Buffering *out = new(dynamic.Buffering) **out = **in } if in.CircuitBreaker != nil { in, out := &in.CircuitBreaker, &out.CircuitBreaker *out = new(CircuitBreaker) (*in).DeepCopyInto(*out) } if in.Compress != nil { in, out := &in.Compress, &out.Compress *out = new(Compress) (*in).DeepCopyInto(*out) } if in.PassTLSClientCert != nil { in, out := &in.PassTLSClientCert, &out.PassTLSClientCert *out = new(dynamic.PassTLSClientCert) (*in).DeepCopyInto(*out) } if in.Retry != nil { in, out := &in.Retry, &out.Retry *out = new(Retry) **out = **in } if in.ContentType != nil { in, out := &in.ContentType, &out.ContentType *out = new(dynamic.ContentType) (*in).DeepCopyInto(*out) } if in.GrpcWeb != nil { in, out := &in.GrpcWeb, &out.GrpcWeb *out = new(dynamic.GrpcWeb) (*in).DeepCopyInto(*out) } if in.Plugin != nil { in, out := &in.Plugin, &out.Plugin *out = make(map[string]v1.JSON, len(*in)) for key, val := range *in { (*out)[key] = *val.DeepCopy() } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MiddlewareSpec. func (in *MiddlewareSpec) DeepCopy() *MiddlewareSpec { if in == nil { return nil } out := new(MiddlewareSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MiddlewareTCP) DeepCopyInto(out *MiddlewareTCP) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MiddlewareTCP. func (in *MiddlewareTCP) DeepCopy() *MiddlewareTCP { if in == nil { return nil } out := new(MiddlewareTCP) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *MiddlewareTCP) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MiddlewareTCPList) DeepCopyInto(out *MiddlewareTCPList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]MiddlewareTCP, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MiddlewareTCPList. func (in *MiddlewareTCPList) DeepCopy() *MiddlewareTCPList { if in == nil { return nil } out := new(MiddlewareTCPList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *MiddlewareTCPList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MiddlewareTCPSpec) DeepCopyInto(out *MiddlewareTCPSpec) { *out = *in if in.InFlightConn != nil { in, out := &in.InFlightConn, &out.InFlightConn *out = new(dynamic.TCPInFlightConn) **out = **in } if in.IPWhiteList != nil { in, out := &in.IPWhiteList, &out.IPWhiteList *out = new(dynamic.TCPIPWhiteList) (*in).DeepCopyInto(*out) } if in.IPAllowList != nil { in, out := &in.IPAllowList, &out.IPAllowList *out = new(dynamic.TCPIPAllowList) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MiddlewareTCPSpec. func (in *MiddlewareTCPSpec) DeepCopy() *MiddlewareTCPSpec { if in == nil { return nil } out := new(MiddlewareTCPSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MirrorService) DeepCopyInto(out *MirrorService) { *out = *in in.LoadBalancerSpec.DeepCopyInto(&out.LoadBalancerSpec) return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MirrorService. func (in *MirrorService) DeepCopy() *MirrorService { if in == nil { return nil } out := new(MirrorService) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Mirroring) DeepCopyInto(out *Mirroring) { *out = *in in.LoadBalancerSpec.DeepCopyInto(&out.LoadBalancerSpec) if in.MirrorBody != nil { in, out := &in.MirrorBody, &out.MirrorBody *out = new(bool) **out = **in } if in.MaxBodySize != nil { in, out := &in.MaxBodySize, &out.MaxBodySize *out = new(int64) **out = **in } if in.Mirrors != nil { in, out := &in.Mirrors, &out.Mirrors *out = make([]MirrorService, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Mirroring. func (in *Mirroring) DeepCopy() *Mirroring { if in == nil { return nil } out := new(Mirroring) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ObjectReference) DeepCopyInto(out *ObjectReference) { *out = *in return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ObjectReference. func (in *ObjectReference) DeepCopy() *ObjectReference { if in == nil { return nil } out := new(ObjectReference) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PassiveServerHealthCheck) DeepCopyInto(out *PassiveServerHealthCheck) { *out = *in if in.FailureWindow != nil { in, out := &in.FailureWindow, &out.FailureWindow *out = new(intstr.IntOrString) **out = **in } if in.MaxFailedAttempts != nil { in, out := &in.MaxFailedAttempts, &out.MaxFailedAttempts *out = new(int) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PassiveServerHealthCheck. func (in *PassiveServerHealthCheck) DeepCopy() *PassiveServerHealthCheck { if in == nil { return nil } out := new(PassiveServerHealthCheck) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RateLimit) DeepCopyInto(out *RateLimit) { *out = *in if in.Average != nil { in, out := &in.Average, &out.Average *out = new(int64) **out = **in } if in.Period != nil { in, out := &in.Period, &out.Period *out = new(intstr.IntOrString) **out = **in } if in.Burst != nil { in, out := &in.Burst, &out.Burst *out = new(int64) **out = **in } if in.SourceCriterion != nil { in, out := &in.SourceCriterion, &out.SourceCriterion *out = new(dynamic.SourceCriterion) (*in).DeepCopyInto(*out) } if in.Redis != nil { in, out := &in.Redis, &out.Redis *out = new(Redis) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RateLimit. func (in *RateLimit) DeepCopy() *RateLimit { if in == nil { return nil } out := new(RateLimit) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Redis) DeepCopyInto(out *Redis) {
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/crd/traefikio/v1alpha1/tlsstore.go
pkg/provider/kubernetes/crd/traefikio/v1alpha1/tlsstore.go
package v1alpha1 import ( "github.com/traefik/traefik/v3/pkg/tls" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // +genclient // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +kubebuilder:storageversion // TLSStore is the CRD implementation of a Traefik TLS Store. // For the time being, only the TLSStore named default is supported. // This means that you cannot have two stores that are named default in different Kubernetes namespaces. // More info: https://doc.traefik.io/traefik/v3.6/reference/routing-configuration/http/tls/tls-certificates/#certificates-stores#certificates-stores type TLSStore struct { metav1.TypeMeta `json:",inline"` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata metav1.ObjectMeta `json:"metadata"` Spec TLSStoreSpec `json:"spec"` } // +k8s:deepcopy-gen=true // TLSStoreSpec defines the desired state of a TLSStore. type TLSStoreSpec struct { // DefaultCertificate defines the default certificate configuration. DefaultCertificate *Certificate `json:"defaultCertificate,omitempty"` // DefaultGeneratedCert defines the default generated certificate configuration. DefaultGeneratedCert *tls.GeneratedCert `json:"defaultGeneratedCert,omitempty"` // Certificates is a list of secret names, each secret holding a key/certificate pair to add to the store. Certificates []Certificate `json:"certificates,omitempty"` } // +k8s:deepcopy-gen=true // Certificate holds a secret name for the TLSStore resource. type Certificate struct { // SecretName is the name of the referenced Kubernetes Secret to specify the certificate details. SecretName string `json:"secretName"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // TLSStoreList is a collection of TLSStore resources. type TLSStoreList struct { metav1.TypeMeta `json:",inline"` // Standard object's metadata. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata metav1.ListMeta `json:"metadata"` // Items is the list of TLSStore. Items []TLSStore `json:"items"` }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/provider/kubernetes/crd/traefikio/v1alpha1/types.go
pkg/provider/kubernetes/crd/traefikio/v1alpha1/types.go
package v1alpha1 /* This file is needed for kubernetes/code-generator/kube_codegen.sh script used in script/code-gen.sh. */ // +genclient
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false