1
0
Fork 0

Merge branch 'v2.2' into master

This commit is contained in:
Michael 2020-05-18 18:37:11 +02:00
commit 7928e6d0cd
No known key found for this signature in database
GPG key ID: 71EDE16780F920E8
167 changed files with 554 additions and 563 deletions

View file

@ -15,7 +15,7 @@ const (
maskLarge = maskShort + maskShort + maskShort + maskShort + maskShort + maskShort + maskShort + maskShort
)
// Do configuration.
// Do sends configuration.
func Do(baseConfig interface{}, indent bool) (string, error) {
anomConfig, err := copystructure.Copy(baseConfig)
if err != nil {
@ -120,7 +120,7 @@ func reset(field reflect.Value, name string) error {
return nil
}
// isExported return true is a struct field is exported, else false
// isExported return true is a struct field is exported, else false.
func isExported(f reflect.StructField) bool {
if f.PkgPath != "" && !f.Anonymous {
return false

View file

@ -8,12 +8,12 @@ import (
"github.com/gorilla/mux"
)
// DashboardHandler expose dashboard routes
// DashboardHandler expose dashboard routes.
type DashboardHandler struct {
Assets *assetfs.AssetFS
}
// Append add dashboard routes on a router
// Append add dashboard routes on a router.
func (g DashboardHandler) Append(router *mux.Router) {
if g.Assets == nil {
log.WithoutContext().Error("No assets for dashboard")

View file

@ -19,10 +19,10 @@ func goroutines() interface{} {
return runtime.NumGoroutine()
}
// DebugHandler expose debug routes
// DebugHandler expose debug routes.
type DebugHandler struct{}
// Append add debug routes on a router
// Append add debug routes on a router.
func (g DebugHandler) Append(router *mux.Router) {
router.Methods(http.MethodGet).Path("/debug/vars").
HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {

View file

@ -55,7 +55,7 @@ type Handler struct {
runtimeConfiguration *runtime.Configuration
}
// NewBuilder returns a http.Handler builder based on runtime.Configuration
// NewBuilder returns a http.Handler builder based on runtime.Configuration.
func NewBuilder(staticConfig static.Configuration) func(*runtime.Configuration) http.Handler {
return func(configuration *runtime.Configuration) http.Handler {
return New(staticConfig, configuration).createRouter()

View file

@ -55,7 +55,7 @@ func execute(cmd *Command, args []string, root bool) error {
// Calls command without args.
if len(args) == 1 {
if err := run(cmd, args[1:]); err != nil {
return fmt.Errorf("command %s error: %v", args[0], err)
return fmt.Errorf("command %s error: %w", args[0], err)
}
return nil
}
@ -65,7 +65,7 @@ func execute(cmd *Command, args []string, root bool) error {
// then we run the top level command itself.
if root && cmd.Name != args[1] && !contains(cmd.subCommands, args[1]) {
if err := run(cmd, args[1:]); err != nil {
return fmt.Errorf("command %s error: %v", filepath.Base(args[0]), err)
return fmt.Errorf("command %s error: %w", filepath.Base(args[0]), err)
}
return nil
}
@ -74,7 +74,7 @@ func execute(cmd *Command, args []string, root bool) error {
if len(args) >= 2 && cmd.Name == args[1] {
if len(args) < 3 || !contains(cmd.subCommands, args[2]) {
if err := run(cmd, args[2:]); err != nil {
return fmt.Errorf("command %s error: %v", cmd.Name, err)
return fmt.Errorf("command %s error: %w", cmd.Name, err)
}
return nil
}
@ -83,7 +83,7 @@ func execute(cmd *Command, args []string, root bool) error {
// No sub-command, calls the current command.
if len(cmd.subCommands) == 0 {
if err := run(cmd, args[1:]); err != nil {
return fmt.Errorf("command %s error: %v", cmd.Name, err)
return fmt.Errorf("command %s error: %w", cmd.Name, err)
}
return nil
}

View file

@ -21,7 +21,7 @@ func (e *EnvLoader) Load(_ []string, cmd *Command) (bool, error) {
if err := env.Decode(vars, env.DefaultNamePrefix, cmd.Configuration); err != nil {
log.WithoutContext().Debug("environment variables", strings.Join(vars, ", "))
return false, fmt.Errorf("failed to decode configuration from environment variables: %v ", err)
return false, fmt.Errorf("failed to decode configuration from environment variables: %w ", err)
}
log.WithoutContext().Println("Configuration loaded from environment variables.")

View file

@ -17,7 +17,7 @@ func (*FlagLoader) Load(args []string, cmd *Command) (bool, error) {
}
if err := flag.Decode(args, cmd.Configuration); err != nil {
return false, fmt.Errorf("failed to decode configuration from flags: %v", err)
return false, fmt.Errorf("failed to decode configuration from flags: %w", err)
}
log.WithoutContext().Println("Configuration loaded from flags.")

View file

@ -16,10 +16,10 @@ import (
"github.com/mitchellh/hashstructure"
)
// collectorURL URL where the stats are send
// collectorURL URL where the stats are send.
const collectorURL = "https://collect.traefik.io/9vxmmkcdmalbdi635d4jgc5p5rx0h7h8"
// Collected data
// Collected data.
type data struct {
Version string
Codename string

View file

@ -19,7 +19,7 @@ type Configurations map[string]*Configuration
// +k8s:deepcopy-gen=true
// Configuration is the root of the dynamic configuration
// Configuration is the root of the dynamic configuration.
type Configuration struct {
HTTP *HTTPConfiguration `json:"http,omitempty" toml:"http,omitempty" yaml:"http,omitempty"`
TCP *TCPConfiguration `json:"tcp,omitempty" toml:"tcp,omitempty" yaml:"tcp,omitempty"`

View file

@ -47,7 +47,7 @@ type Router struct {
// +k8s:deepcopy-gen=true
// RouterTLSConfig holds the TLS configuration for a router
// RouterTLSConfig holds the TLS configuration for a router.
type RouterTLSConfig struct {
Options string `json:"options,omitempty" toml:"options,omitempty" yaml:"options,omitempty"`
CertResolver string `json:"certResolver,omitempty" toml:"certResolver,omitempty" yaml:"certResolver,omitempty"`

View file

@ -95,7 +95,7 @@ type Buffering struct {
// +k8s:deepcopy-gen=true
// Chain holds a chain of middlewares
// Chain holds a chain of middlewares.
type Chain struct {
Middlewares []string `json:"middlewares,omitempty" toml:"middlewares,omitempty" yaml:"middlewares,omitempty"`
}
@ -191,13 +191,13 @@ type Headers struct {
IsDevelopment bool `json:"isDevelopment,omitempty" toml:"isDevelopment,omitempty" yaml:"isDevelopment,omitempty"`
}
// HasCustomHeadersDefined checks to see if any of the custom header elements have been set
// HasCustomHeadersDefined checks to see if any of the custom header elements have been set.
func (h *Headers) HasCustomHeadersDefined() bool {
return h != nil && (len(h.CustomResponseHeaders) != 0 ||
len(h.CustomRequestHeaders) != 0)
}
// HasCorsHeadersDefined checks to see if any of the cors header elements have been set
// HasCorsHeadersDefined checks to see if any of the cors header elements have been set.
func (h *Headers) HasCorsHeadersDefined() bool {
return h != nil && (h.AccessControlAllowCredentials ||
len(h.AccessControlAllowHeaders) != 0 ||
@ -208,7 +208,7 @@ func (h *Headers) HasCorsHeadersDefined() bool {
h.AddVaryHeader)
}
// HasSecureHeadersDefined checks to see if any of the secure header elements have been set
// HasSecureHeadersDefined checks to see if any of the secure header elements have been set.
func (h *Headers) HasSecureHeadersDefined() bool {
return h != nil && (len(h.AllowedHosts) != 0 ||
len(h.HostsProxyHeaders) != 0 ||
@ -245,7 +245,7 @@ type IPStrategy struct {
// Get an IP selection strategy.
// If nil return the RemoteAddr strategy
// else return a strategy base on the configuration using the X-Forwarded-For Header.
// Depth override the ExcludedIPs
// Depth override the ExcludedIPs.
func (s *IPStrategy) Get() (ip.Strategy, error) {
if s == nil {
return &ip.RemoteAddrStrategy{}, nil
@ -420,7 +420,7 @@ type TLSCLientCertificateDNInfo struct {
// +k8s:deepcopy-gen=true
// Users holds a list of users
// Users holds a list of users.
type Users []string
// +k8s:deepcopy-gen=true
@ -449,7 +449,7 @@ func (c *ClientTLS) CreateTLSConfig() (*tls.Config, error) {
if _, errCA := os.Stat(c.CA); errCA == nil {
ca, err = ioutil.ReadFile(c.CA)
if err != nil {
return nil, fmt.Errorf("failed to read CA. %s", err)
return nil, fmt.Errorf("failed to read CA. %w", err)
}
} else {
ca = []byte(c.CA)
@ -478,7 +478,7 @@ func (c *ClientTLS) CreateTLSConfig() (*tls.Config, error) {
if errKeyIsFile == nil {
cert, err = tls.LoadX509KeyPair(c.Cert, c.Key)
if err != nil {
return nil, fmt.Errorf("failed to load TLS keypair: %v", err)
return nil, fmt.Errorf("failed to load TLS keypair: %w", err)
}
} else {
return nil, fmt.Errorf("tls cert is a file, but tls key is not")
@ -487,7 +487,7 @@ func (c *ClientTLS) CreateTLSConfig() (*tls.Config, error) {
if errKeyIsFile != nil {
cert, err = tls.X509KeyPair([]byte(c.Cert), []byte(c.Key))
if err != nil {
return nil, fmt.Errorf("failed to load TLS keypair: %v", err)
return nil, fmt.Errorf("failed to load TLS keypair: %w", err)
}
} else {
return nil, fmt.Errorf("TLS key is a file, but tls cert is not")

View file

@ -55,7 +55,7 @@ type TCPRouter struct {
// +k8s:deepcopy-gen=true
// RouterTCPTLSConfig holds the TLS configuration for a router
// RouterTCPTLSConfig holds the TLS configuration for a router.
type RouterTCPTLSConfig struct {
Passthrough bool `json:"passthrough" toml:"passthrough" yaml:"passthrough"`
Options string `json:"options,omitempty" toml:"options,omitempty" yaml:"options,omitempty"`
@ -76,7 +76,7 @@ type TCPServersLoadBalancer struct {
Servers []TCPServer `json:"servers,omitempty" toml:"servers,omitempty" yaml:"servers,omitempty" label-slice-as-struct:"server"`
}
// SetDefaults Default values for a TCPServersLoadBalancer
// SetDefaults Default values for a TCPServersLoadBalancer.
func (l *TCPServersLoadBalancer) SetDefaults() {
defaultTerminationDelay := 100 // in milliseconds
l.TerminationDelay = &defaultTerminationDelay
@ -101,7 +101,7 @@ func (l *TCPServersLoadBalancer) Mergeable(loadBalancer *TCPServersLoadBalancer)
// +k8s:deepcopy-gen=true
// TCPServer holds a TCP Server configuration
// TCPServer holds a TCP Server configuration.
type TCPServer struct {
Address string `json:"address,omitempty" toml:"address,omitempty" yaml:"address,omitempty" label:"-"`
Port string `toml:"-" json:"-" yaml:"-"`

View file

@ -17,7 +17,7 @@ const DefaultNamePrefix = "TRAEFIK_"
// env vars -> map
// map -> tree of untyped nodes
// untyped nodes -> nodes augmented with metadata such as kind (inferred from element)
// "typed" nodes -> typed element
// "typed" nodes -> typed element.
func Decode(environ []string, prefix string, element interface{}) error {
if err := checkPrefix(prefix); err != nil {
return err
@ -40,7 +40,7 @@ func Decode(environ []string, prefix string, element interface{}) error {
// The operation goes through three stages roughly summarized as:
// typed configuration in element -> tree of untyped nodes
// untyped nodes -> nodes augmented with metadata such as kind (inferred from element)
// "typed" nodes -> environment variables with default values (determined by type/kind)
// "typed" nodes -> environment variables with default values (determined by type/kind).
func Encode(element interface{}) ([]parser.Flat, error) {
if element == nil {
return nil, nil

View file

@ -9,7 +9,7 @@ import (
// The operation goes through three stages roughly summarized as:
// file contents -> tree of untyped nodes
// untyped nodes -> nodes augmented with metadata such as kind (inferred from element)
// "typed" nodes -> typed element
// "typed" nodes -> typed element.
func Decode(filePath string, element interface{}) error {
if element == nil {
return nil

View file

@ -10,7 +10,7 @@ import (
// flag arguments -> parsed map of flags
// map -> tree of untyped nodes
// untyped nodes -> nodes augmented with metadata such as kind (inferred from element)
// "typed" nodes -> typed element
// "typed" nodes -> typed element.
func Decode(args []string, element interface{}) error {
ref, err := Parse(args, element)
if err != nil {
@ -24,7 +24,7 @@ func Decode(args []string, element interface{}) error {
// The operation goes through three stages roughly summarized as:
// typed configuration in element -> tree of untyped nodes
// untyped nodes -> nodes augmented with metadata such as kind (inferred from element)
// "typed" nodes -> flags with default values (determined by type/kind)
// "typed" nodes -> flags with default values (determined by type/kind).
func Encode(element interface{}) ([]parser.Flat, error) {
if element == nil {
return nil, nil

View file

@ -12,7 +12,7 @@ import (
// The operation goes through three stages roughly summarized as:
// KV pairs -> tree of untyped nodes
// untyped nodes -> nodes augmented with metadata such as kind (inferred from element)
// "typed" nodes -> typed element
// "typed" nodes -> typed element.
func Decode(pairs []*store.KVPair, element interface{}, rootName string) error {
if element == nil {
return nil

View file

@ -28,7 +28,7 @@ func EncodeConfiguration(conf *dynamic.Configuration) (map[string]string, error)
}
// Decode converts the labels to an element.
// labels -> [ node -> node + metadata (type) ] -> element (node)
// labels -> [ node -> node + metadata (type) ] -> element (node).
func Decode(labels map[string]string, element interface{}, filters ...string) error {
return parser.Decode(labels, element, parser.DefaultRootName, filters...)
}

View file

@ -15,7 +15,7 @@ type EncoderToNodeOpts struct {
}
// EncodeToNode converts an element to a node.
// element -> nodes
// element -> nodes.
func EncodeToNode(element interface{}, rootName string, opts EncoderToNodeOpts) (*Node, error) {
rValue := reflect.ValueOf(element)
node := &Node{Name: rootName}

View file

@ -1,7 +1,7 @@
package parser
// EncodeNode Converts a node to labels.
// nodes -> labels
// nodes -> labels.
func EncodeNode(node *Node) map[string]string {
labels := make(map[string]string)
encodeNode(labels, node.Name, node)

View file

@ -6,7 +6,7 @@ package parser
// The operation goes through three stages roughly summarized as:
// labels -> tree of untyped nodes
// untyped nodes -> nodes augmented with metadata such as kind (inferred from element)
// "typed" nodes -> typed element
// "typed" nodes -> typed element.
func Decode(labels map[string]string, element interface{}, rootName string, filters ...string) error {
node, err := DecodeToNode(labels, rootName, filters...)
if err != nil {
@ -28,7 +28,7 @@ func Decode(labels map[string]string, element interface{}, rootName string, filt
}
// Encode converts an element to labels.
// element -> node (value) -> label (node)
// element -> node (value) -> label (node).
func Encode(element interface{}, rootName string) (map[string]string, error) {
etnOpts := EncoderToNodeOpts{OmitEmpty: true, TagName: TagLabel, AllowSliceAsStruct: true}
node, err := EncodeToNode(element, rootName, etnOpts)

View file

@ -8,7 +8,7 @@ import (
"github.com/containous/traefik/v2/pkg/log"
)
// Status of the router/service
// Status of the router/service.
const (
StatusEnabled = "enabled"
StatusDisabled = "disabled"

View file

@ -179,7 +179,7 @@ func (s *ServiceInfo) UpdateServerStatus(server string, status string) {
}
// GetAllStatus returns all the statuses of all the servers in ServiceInfo.
// It is the responsibility of the caller to check that s is not nil
// It is the responsibility of the caller to check that s is not nil.
func (s *ServiceInfo) GetAllStatus() map[string]string {
s.serverStatusMu.RLock()
defer s.serverStatusMu.RUnlock()

View file

@ -9,7 +9,7 @@ import (
"github.com/stretchr/testify/require"
)
// all the Routers/Middlewares/Services are considered fully qualified
// all the Routers/Middlewares/Services are considered fully qualified.
func TestPopulateUsedBy(t *testing.T) {
testCases := []struct {
desc string

View file

@ -49,7 +49,7 @@ const (
DefaultAcmeCAServer = "https://acme-v02.api.letsencrypt.org/directory"
)
// Configuration is the static configuration
// Configuration is the static configuration.
type Configuration struct {
Global *Global `description:"Global configuration options" json:"global,omitempty" toml:"global,omitempty" yaml:"global,omitempty" export:"true"`
@ -81,7 +81,7 @@ type Global struct {
SendAnonymousUsage bool `description:"Periodically send anonymous usage statistics. If the option is not specified, it will be enabled by default." json:"sendAnonymousUsage,omitempty" toml:"sendAnonymousUsage,omitempty" yaml:"sendAnonymousUsage,omitempty" label:"allowEmpty" export:"true"`
}
// ServersTransport options to configure communication between Traefik and the servers
// ServersTransport options to configure communication between Traefik and the servers.
type ServersTransport struct {
InsecureSkipVerify bool `description:"Disable SSL certificate verification." json:"insecureSkipVerify,omitempty" toml:"insecureSkipVerify,omitempty" yaml:"insecureSkipVerify,omitempty" export:"true"`
RootCAs []tls.FileOrContent `description:"Add cert file for self-signed certificate." json:"rootCAs,omitempty" toml:"rootCAs,omitempty" yaml:"rootCAs,omitempty"`
@ -89,7 +89,7 @@ type ServersTransport struct {
ForwardingTimeouts *ForwardingTimeouts `description:"Timeouts for requests forwarded to the backend servers." json:"forwardingTimeouts,omitempty" toml:"forwardingTimeouts,omitempty" yaml:"forwardingTimeouts,omitempty" export:"true"`
}
// API holds the API configuration
// API holds the API configuration.
type API struct {
Insecure bool `description:"Activate API directly on the entryPoint named traefik." json:"insecure,omitempty" toml:"insecure,omitempty" yaml:"insecure,omitempty" export:"true"`
Dashboard bool `description:"Activate dashboard." json:"dashboard,omitempty" toml:"dashboard,omitempty" yaml:"dashboard,omitempty" export:"true"`
@ -158,7 +158,7 @@ func (t *Tracing) SetDefaults() {
t.SpanNameLimit = 0
}
// Providers contains providers configuration
// Providers contains providers configuration.
type Providers struct {
ProvidersThrottleDuration types.Duration `description:"Backends throttle duration: minimum duration between 2 events from providers before applying a new configuration. It avoids unnecessary reloads if multiples events are sent in a short amount of time." json:"providersThrottleDuration,omitempty" toml:"providersThrottleDuration,omitempty" yaml:"providersThrottleDuration,omitempty" export:"true"`
@ -224,7 +224,7 @@ func (c *Configuration) initACMEProvider() {
legolog.Logger = stdlog.New(log.WithoutContext().WriterLevel(logrus.DebugLevel), "legolog: ", 0)
}
// ValidateConfiguration validate that configuration is coherent
// ValidateConfiguration validate that configuration is coherent.
func (c *Configuration) ValidateConfiguration() error {
var acmeEmail string
for name, resolver := range c.CertificatesResolvers {

View file

@ -25,8 +25,7 @@ const (
var singleton *HealthCheck
var once sync.Once
// Balancer is the set of operations required to manage the list of servers in a
// load-balancer.
// Balancer is the set of operations required to manage the list of servers in a load-balancer.
type Balancer interface {
Servers() []*url.URL
RemoveServer(u *url.URL) error
@ -39,8 +38,9 @@ type BalancerHandler interface {
Balancer
}
// metricsRegistry is a local interface in the health check package, exposing only the required metrics
// necessary for the health check package. This makes it easier for the tests.
// metricsRegistry is a local interface in the health check package,
// exposing only the required metrics necessary for the health check package.
// This makes it easier for the tests.
type metricsRegistry interface {
BackendServerUpGauge() metrics.Gauge
}
@ -68,7 +68,7 @@ type backendURL struct {
weight int
}
// BackendConfig HealthCheck configuration for a backend
// BackendConfig HealthCheck configuration for a backend.
type BackendConfig struct {
Options
name string
@ -92,7 +92,7 @@ func (b *BackendConfig) newRequest(serverURL *url.URL) (*http.Request, error) {
return http.NewRequest(http.MethodGet, u.String(), http.NoBody)
}
// this function adds additional http headers and hostname to http.request
// this function adds additional http headers and hostname to http.request.
func (b *BackendConfig) addHeadersAndHost(req *http.Request) *http.Request {
if b.Options.Hostname != "" {
req.Host = b.Options.Hostname
@ -104,14 +104,14 @@ func (b *BackendConfig) addHeadersAndHost(req *http.Request) *http.Request {
return req
}
// HealthCheck struct
// HealthCheck struct.
type HealthCheck struct {
Backends map[string]*BackendConfig
metrics metricsRegistry
cancel context.CancelFunc
}
// SetBackendsConfiguration set backends configuration
// SetBackendsConfiguration set backends configuration.
func (hc *HealthCheck) SetBackendsConfiguration(parentCtx context.Context, backends map[string]*BackendConfig) {
hc.Backends = backends
if hc.cancel != nil {
@ -152,28 +152,21 @@ func (hc *HealthCheck) checkBackend(ctx context.Context, backend *BackendConfig)
enabledURLs := backend.LB.Servers()
var newDisabledURLs []backendURL
// FIXME re enable metrics
for _, disabledURL := range backend.disabledURLs {
// FIXME serverUpMetricValue := float64(0)
if err := checkHealth(disabledURL.url, backend); err == nil {
logger.Warnf("Health check up: Returning to server list. Backend: %q URL: %q Weight: %d",
backend.name, disabledURL.url.String(), disabledURL.weight)
if err = backend.LB.UpsertServer(disabledURL.url, roundrobin.Weight(disabledURL.weight)); err != nil {
logger.Error(err)
}
// FIXME serverUpMetricValue = 1
} else {
logger.Warnf("Health check still failing. Backend: %q URL: %q Reason: %s", backend.name, disabledURL.url.String(), err)
newDisabledURLs = append(newDisabledURLs, disabledURL)
}
// FIXME labelValues := []string{"backend", backend.name, "url", backendurl.url.String()}
// FIXME hc.metrics.BackendServerUpGauge().With(labelValues...).Set(serverUpMetricValue)
}
backend.disabledURLs = newDisabledURLs
// FIXME re enable metrics
for _, enableURL := range enabledURLs {
// FIXME serverUpMetricValue := float64(1)
if err := checkHealth(enableURL, backend); err != nil {
weight := 1
rr, ok := backend.LB.(*roundrobin.RoundRobin)
@ -189,35 +182,25 @@ func (hc *HealthCheck) checkBackend(ctx context.Context, backend *BackendConfig)
logger.Error(err)
}
backend.disabledURLs = append(backend.disabledURLs, backendURL{enableURL, weight})
// FIXME serverUpMetricValue = 0
}
// FIXME labelValues := []string{"backend", backend.name, "url", enableURL.String()}
// FIXME hc.metrics.BackendServerUpGauge().With(labelValues...).Set(serverUpMetricValue)
}
}
// FIXME re add metrics
//func GetHealthCheck(metrics metricsRegistry) *HealthCheck {
// GetHealthCheck returns the health check which is guaranteed to be a singleton.
func GetHealthCheck() *HealthCheck {
once.Do(func() {
singleton = newHealthCheck()
//singleton = newHealthCheck(metrics)
})
return singleton
}
// FIXME re add metrics
//func newHealthCheck(metrics metricsRegistry) *HealthCheck {
func newHealthCheck() *HealthCheck {
return &HealthCheck{
Backends: make(map[string]*BackendConfig),
//metrics: metrics,
}
}
// NewBackendConfig Instantiate a new BackendConfig
// NewBackendConfig Instantiate a new BackendConfig.
func NewBackendConfig(options Options, backendName string) *BackendConfig {
return &BackendConfig{
Options: options,
@ -230,7 +213,7 @@ func NewBackendConfig(options Options, backendName string) *BackendConfig {
func checkHealth(serverURL *url.URL, backend *BackendConfig) error {
req, err := backend.newRequest(serverURL)
if err != nil {
return fmt.Errorf("failed to create HTTP request: %s", err)
return fmt.Errorf("failed to create HTTP request: %w", err)
}
req = backend.addHeadersAndHost(req)
@ -248,7 +231,7 @@ func checkHealth(serverURL *url.URL, backend *BackendConfig) error {
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("HTTP request failed: %s", err)
return fmt.Errorf("HTTP request failed: %w", err)
}
defer resp.Body.Close()
@ -260,7 +243,7 @@ func checkHealth(serverURL *url.URL, backend *BackendConfig) error {
return nil
}
// NewLBStatusUpdater returns a new LbStatusUpdater
// NewLBStatusUpdater returns a new LbStatusUpdater.
func NewLBStatusUpdater(bh BalancerHandler, info *runtime.ServiceInfo) *LbStatusUpdater {
return &LbStatusUpdater{
BalancerHandler: bh,
@ -298,7 +281,7 @@ func (lb *LbStatusUpdater) UpsertServer(u *url.URL, options ...roundrobin.Server
// Balancers is a list of Balancers(s) that implements the Balancer interface.
type Balancers []Balancer
// Servers returns the servers url from all the BalancerHandler
// Servers returns the servers url from all the BalancerHandler.
func (b Balancers) Servers() []*url.URL {
var servers []*url.URL
for _, lb := range b {

View file

@ -7,13 +7,13 @@ import (
"strings"
)
// Checker allows to check that addresses are in a trusted IPs
// Checker allows to check that addresses are in a trusted IPs.
type Checker struct {
authorizedIPs []*net.IP
authorizedIPsNet []*net.IPNet
}
// NewChecker builds a new Checker given a list of CIDR-Strings to trusted IPs
// NewChecker builds a new Checker given a list of CIDR-Strings to trusted IPs.
func NewChecker(trustedIPs []string) (*Checker, error) {
if len(trustedIPs) == 0 {
return nil, errors.New("no trusted IPs provided")
@ -27,7 +27,7 @@ func NewChecker(trustedIPs []string) (*Checker, error) {
} else {
_, ipAddr, err := net.ParseCIDR(ipMask)
if err != nil {
return nil, fmt.Errorf("parsing CIDR trusted IPs %s: %v", ipAddr, err)
return nil, fmt.Errorf("parsing CIDR trusted IPs %s: %w", ipAddr, err)
}
checker.authorizedIPsNet = append(checker.authorizedIPsNet, ipAddr)
}
@ -36,7 +36,7 @@ func NewChecker(trustedIPs []string) (*Checker, error) {
return checker, nil
}
// IsAuthorized checks if provided request is authorized by the trusted IPs
// IsAuthorized checks if provided request is authorized by the trusted IPs.
func (ip *Checker) IsAuthorized(addr string) error {
var invalidMatches []string
@ -58,7 +58,7 @@ func (ip *Checker) IsAuthorized(addr string) error {
return nil
}
// Contains checks if provided address is in the trusted IPs
// Contains checks if provided address is in the trusted IPs.
func (ip *Checker) Contains(addr string) (bool, error) {
if len(addr) == 0 {
return false, errors.New("empty IP address")
@ -66,13 +66,13 @@ func (ip *Checker) Contains(addr string) (bool, error) {
ipAddr, err := parseIP(addr)
if err != nil {
return false, fmt.Errorf("unable to parse address: %s: %s", addr, err)
return false, fmt.Errorf("unable to parse address: %s: %w", addr, err)
}
return ip.ContainsIP(ipAddr), nil
}
// ContainsIP checks if provided address is in the trusted IPs
// ContainsIP checks if provided address is in the trusted IPs.
func (ip *Checker) ContainsIP(addr net.IP) bool {
for _, authorizedIP := range ip.authorizedIPs {
if authorizedIP.Equal(addr) {

View file

@ -10,15 +10,15 @@ const (
xForwardedFor = "X-Forwarded-For"
)
// Strategy a strategy for IP selection
// Strategy a strategy for IP selection.
type Strategy interface {
GetIP(req *http.Request) string
}
// RemoteAddrStrategy a strategy that always return the remote address
// RemoteAddrStrategy a strategy that always return the remote address.
type RemoteAddrStrategy struct{}
// GetIP returns the selected IP
// GetIP returns the selected IP.
func (s *RemoteAddrStrategy) GetIP(req *http.Request) string {
ip, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
@ -27,12 +27,12 @@ func (s *RemoteAddrStrategy) GetIP(req *http.Request) string {
return ip
}
// DepthStrategy a strategy based on the depth inside the X-Forwarded-For from right to left
// DepthStrategy a strategy based on the depth inside the X-Forwarded-For from right to left.
type DepthStrategy struct {
Depth int
}
// GetIP return the selected IP
// GetIP return the selected IP.
func (s *DepthStrategy) GetIP(req *http.Request) string {
xff := req.Header.Get(xForwardedFor)
xffs := strings.Split(xff, ",")
@ -44,12 +44,12 @@ func (s *DepthStrategy) GetIP(req *http.Request) string {
}
// CheckerStrategy a strategy based on an IP Checker
// allows to check that addresses are in a trusted IPs
// allows to check that addresses are in a trusted IPs.
type CheckerStrategy struct {
Checker *Checker
}
// GetIP return the selected IP
// GetIP return the selected IP.
func (s *CheckerStrategy) GetIP(req *http.Request) string {
if s.Checker == nil {
return ""

View file

@ -80,7 +80,7 @@ func AddHook(hook logrus.Hook) {
}
// CustomWriterLevel logs writer for a specific level. (with a custom scanner buffer size.)
// adapted from github.com/Sirupsen/logrus/writer.go
// adapted from github.com/Sirupsen/logrus/writer.go.
func CustomWriterLevel(level logrus.Level, maxScanTokenSize int) *io.PipeWriter {
reader, writer := io.Pipe()
@ -110,7 +110,7 @@ func CustomWriterLevel(level logrus.Level, maxScanTokenSize int) *io.PipeWriter
}
// extract from github.com/Sirupsen/logrus/writer.go
// Hack the buffer size
// Hack the buffer size.
func writerScanner(reader io.ReadCloser, scanTokenSize int, printFunc func(args ...interface{})) {
scanner := bufio.NewScanner(reader)

View file

@ -1,6 +1,6 @@
package log
// Log entry name
// Log entry names.
const (
EntryPointName = "entryPointName"
RouterName = "routerName"

View file

@ -15,7 +15,7 @@ const (
loggerKey contextKey = iota
)
// Logger the Traefik logger
// Logger the Traefik logger.
type Logger interface {
logrus.FieldLogger
WriterLevel(logrus.Level) *io.PipeWriter
@ -57,14 +57,14 @@ func GetLevel() logrus.Level {
return logrus.GetLevel()
}
// Str adds a string field
// Str adds a string field.
func Str(key, value string) func(logrus.Fields) {
return func(fields logrus.Fields) {
fields[key] = value
}
}
// With Adds fields
// With Adds fields.
func With(ctx context.Context, opts ...func(logrus.Fields)) context.Context {
logger := FromContext(ctx)
@ -77,7 +77,7 @@ func With(ctx context.Context, opts ...func(logrus.Fields)) context.Context {
return context.WithValue(ctx, loggerKey, logger)
}
// FromContext Gets the logger from context
// FromContext Gets the logger from context.
func FromContext(ctx context.Context) Logger {
if ctx == nil {
panic("nil context")
@ -91,12 +91,12 @@ func FromContext(ctx context.Context) Logger {
return logger
}
// WithoutContext Gets the main logger
// WithoutContext Gets the main logger.
func WithoutContext() Logger {
return mainLogger
}
// OpenFile opens the log file using the specified path
// OpenFile opens the log file using the specified path.
func OpenFile(path string) error {
logFilePath = path
@ -110,7 +110,7 @@ func OpenFile(path string) error {
return nil
}
// CloseFile closes the log and sets the Output to stdout
// CloseFile closes the log and sets the Output to stdout.
func CloseFile() error {
logrus.SetOutput(os.Stdout)
@ -120,9 +120,8 @@ func CloseFile() error {
return nil
}
// RotateFile closes and reopens the log file to allow for rotation
// by an external source. If the log isn't backed by a file then
// it does nothing.
// RotateFile closes and reopens the log file to allow for rotation by an external source.
// If the log isn't backed by a file then it does nothing.
func RotateFile() error {
logger := FromContext(context.Background())

View file

@ -80,7 +80,7 @@ func RegisterInfluxDB(ctx context.Context, config *types.InfluxDB) Registry {
return registry
}
// initInfluxDBTicker creates a influxDBClient
// initInfluxDBTicker creates a influxDBClient.
func initInfluxDBClient(ctx context.Context, config *types.InfluxDB) *influx.Influx {
logger := log.FromContext(ctx)
@ -123,7 +123,7 @@ func initInfluxDBClient(ctx context.Context, config *types.InfluxDB) *influx.Inf
}))
}
// initInfluxDBTicker initializes metrics pusher
// initInfluxDBTicker initializes metrics pusher.
func initInfluxDBTicker(ctx context.Context, config *types.InfluxDB) *time.Ticker {
report := time.NewTicker(time.Duration(config.PushInterval))
@ -135,7 +135,7 @@ func initInfluxDBTicker(ctx context.Context, config *types.InfluxDB) *time.Ticke
return report
}
// StopInfluxDB stops internal influxDBTicker which controls the pushing of metrics to InfluxDB Agent and resets it to `nil`
// StopInfluxDB stops internal influxDBTicker which controls the pushing of metrics to InfluxDB Agent and resets it to `nil`.
func StopInfluxDB() {
if influxDBTicker != nil {
influxDBTicker.Stop()

View file

@ -71,7 +71,7 @@ func RegisterStatsd(ctx context.Context, config *types.Statsd) Registry {
return registry
}
// initStatsdTicker initializes metrics pusher and creates a statsdClient if not created already
// initStatsdTicker initializes metrics pusher and creates a statsdClient if not created already.
func initStatsdTicker(ctx context.Context, config *types.Statsd) *time.Ticker {
address := config.Address
if len(address) == 0 {
@ -87,7 +87,7 @@ func initStatsdTicker(ctx context.Context, config *types.Statsd) *time.Ticker {
return report
}
// StopStatsd stops internal statsdTicker which controls the pushing of metrics to StatsD Agent and resets it to `nil`
// StopStatsd stops internal statsdTicker which controls the pushing of metrics to StatsD Agent and resets it to `nil`.
func StopStatsd() {
if statsdTicker != nil {
statsdTicker.Stop()

View file

@ -28,7 +28,7 @@ func newCaptureResponseWriter(rw http.ResponseWriter) capturer {
}
// captureResponseWriter is a wrapper of type http.ResponseWriter
// that tracks request status and size
// that tracks request status and size.
type captureResponseWriter struct {
rw http.ResponseWriter
status int

View file

@ -7,7 +7,7 @@ import (
"github.com/vulcand/oxy/utils"
)
// FieldApply function hook to add data in accesslog
// FieldApply function hook to add data in accesslog.
type FieldApply func(rw http.ResponseWriter, r *http.Request, next http.Handler, data *LogData)
// FieldHandler sends a new field to the logger.
@ -39,7 +39,7 @@ func (f *FieldHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
}
}
// AddServiceFields add service fields
// AddServiceFields add service fields.
func AddServiceFields(rw http.ResponseWriter, req *http.Request, next http.Handler, data *LogData) {
data.Core[ServiceURL] = req.URL // note that this is *not* the original incoming URL
data.Core[ServiceAddr] = req.URL.Host
@ -47,7 +47,7 @@ func AddServiceFields(rw http.ResponseWriter, req *http.Request, next http.Handl
next.ServeHTTP(rw, req)
}
// AddOriginFields add origin fields
// AddOriginFields add origin fields.
func AddOriginFields(rw http.ResponseWriter, req *http.Request, next http.Handler, data *LogData) {
crw := newCaptureResponseWriter(rw)
start := time.Now().UTC()

View file

@ -75,7 +75,7 @@ func NewHandler(config *types.AccessLog) (*Handler, error) {
if len(config.FilePath) > 0 {
f, err := openAccessLogFile(config.FilePath)
if err != nil {
return nil, fmt.Errorf("error opening access log file: %s", err)
return nil, fmt.Errorf("error opening access log file: %w", err)
}
file = f
}
@ -132,12 +132,12 @@ func openAccessLogFile(filePath string) (*os.File, error) {
dir := filepath.Dir(filePath)
if err := os.MkdirAll(dir, 0755); err != nil {
return nil, fmt.Errorf("failed to create log path %s: %s", dir, err)
return nil, fmt.Errorf("failed to create log path %s: %w", dir, err)
}
file, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0664)
if err != nil {
return nil, fmt.Errorf("error opening file %s: %s", filePath, err)
return nil, fmt.Errorf("error opening file %s: %w", filePath, err)
}
return file, nil

View file

@ -5,7 +5,7 @@ import (
"regexp"
)
// ParseAccessLog parse line of access log and return a map with each fields
// ParseAccessLog parse line of access log and return a map with each fields.
func ParseAccessLog(data string) (map[string]string, error) {
var buffer bytes.Buffer
buffer.WriteString(`(\S+)`) // 1 - ClientHost

View file

@ -20,7 +20,7 @@ const (
wwwAuthenticate = "Www-Authenticate"
)
// DigestRequest is a client for digest authentication requests
// DigestRequest is a client for digest authentication requests.
type digestRequest struct {
client *http.Client
username, password string
@ -35,7 +35,7 @@ func (nc nonceCount) String() string {
var wanted = []string{algorithm, nonce, opaque, qop, realm}
// New makes a DigestRequest instance
// New makes a DigestRequest instance.
func newDigestRequest(username, password string, client *http.Client) *digestRequest {
return &digestRequest{
client: client,
@ -44,7 +44,7 @@ func newDigestRequest(username, password string, client *http.Client) *digestReq
}
}
// Do does requests as http.Do does
// Do does requests as http.Do does.
func (r *digestRequest) Do(req *http.Request) (*http.Response, error) {
parts, err := r.makeParts(req)
if err != nil {
@ -133,7 +133,7 @@ func (r *digestRequest) makeAuthorization(req *http.Request, parts map[string]st
)
}
// GenerateRandom generates random string
// GenerateRandom generates random string.
func generateRandom(n int) string {
b := make([]byte, 8)
_, _ = io.ReadFull(rand.Reader, b)

View file

@ -18,7 +18,7 @@ type chainBuilder interface {
BuildChain(ctx context.Context, middlewares []string) *alice.Chain
}
// New creates a chain middleware
// New creates a chain middleware.
func New(ctx context.Context, next http.Handler, config dynamic.Chain, builder chainBuilder, name string) (http.Handler, error) {
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")

View file

@ -39,7 +39,7 @@ func New(ctx context.Context, next http.Handler, confCircuitBreaker dynamic.Circ
}, nil
}
// NewCircuitBreakerOptions returns a new CircuitBreakerOption
// NewCircuitBreakerOptions returns a new CircuitBreakerOption.
func createCircuitBreakerOptions(expression string) cbreaker.CircuitBreakerOption {
return cbreaker.Fallback(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
tracing.SetErrorWithEvent(req, "blocked by circuit-breaker (%q)", expression)

View file

@ -131,12 +131,12 @@ func (c *customErrors) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
func newRequest(baseURL string) (*http.Request, error) {
u, err := url.Parse(baseURL)
if err != nil {
return nil, fmt.Errorf("error pages: error when parse URL: %v", err)
return nil, fmt.Errorf("error pages: error when parse URL: %w", err)
}
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
return nil, fmt.Errorf("error pages: error when create query: %v", err)
return nil, fmt.Errorf("error pages: error when create query: %w", err)
}
req.RequestURI = u.RequestURI()
@ -250,7 +250,7 @@ func (cc *codeCatcher) WriteHeader(code int) {
cc.headersSent = true
}
// Hijack hijacks the connection
// Hijack hijacks the connection.
func (cc *codeCatcher) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if hj, ok := cc.responseWriter.(http.Hijacker); ok {
return hj.Hijack()
@ -349,7 +349,7 @@ func (r *responseRecorderWithoutCloseNotify) WriteHeader(code int) {
r.Code = code
}
// Hijack hijacks the connection
// Hijack hijacks the connection.
func (r *responseRecorderWithoutCloseNotify) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return r.responseWriter.(http.Hijacker).Hijack()
}

View file

@ -37,9 +37,10 @@ var xHeaders = []string{
xRealIP,
}
// XForwarded is an HTTP handler wrapper that sets the X-Forwarded headers, and other relevant headers for a
// reverse-proxy. Unless insecure is set, it first removes all the existing values for those headers if the remote
// address is not one of the trusted ones.
// XForwarded is an HTTP handler wrapper that sets the X-Forwarded headers,
// and other relevant headers for a reverse-proxy.
// Unless insecure is set,
// it first removes all the existing values for those headers if the remote address is not one of the trusted ones.
type XForwarded struct {
insecure bool
trustedIps []string
@ -80,15 +81,13 @@ func (x *XForwarded) isTrustedIP(ip string) bool {
return x.ipChecker.IsAuthorized(ip) == nil
}
// removeIPv6Zone removes the zone if the given IP is an ipv6 address and it has
// {zone} information in it, like "[fe80::d806:a55d:eb1b:49cc%vEthernet (vmxnet3
// Ethernet Adapter - Virtual Switch)]:64692"
// removeIPv6Zone removes the zone if the given IP is an ipv6 address and it has {zone} information in it,
// like "[fe80::d806:a55d:eb1b:49cc%vEthernet (vmxnet3 Ethernet Adapter - Virtual Switch)]:64692".
func removeIPv6Zone(clientIP string) string {
return strings.Split(clientIP, "%")[0]
}
// isWebsocketRequest returns whether the specified HTTP request is a
// websocket handshake request
// isWebsocketRequest returns whether the specified HTTP request is a websocket handshake request.
func isWebsocketRequest(req *http.Request) bool {
containsHeader := func(name, value string) bool {
items := strings.Split(req.Header.Get(name), ",")
@ -141,7 +140,7 @@ func (x *XForwarded) rewrite(outreq *http.Request) {
}
if isWebsocketRequest(outreq) {
if outreq.Header.Get(xForwardedProto) == "https" {
if outreq.Header.Get(xForwardedProto) == "https" || outreq.Header.Get(xForwardedProto) == "wss" {
outreq.Header.Set(xForwardedProto, "wss")
} else {
outreq.Header.Set(xForwardedProto, "ws")
@ -161,7 +160,7 @@ func (x *XForwarded) rewrite(outreq *http.Request) {
}
}
// ServeHTTP implements http.Handler
// ServeHTTP implements http.Handler.
func (x *XForwarded) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !x.insecure && !x.isTrustedIP(r.RemoteAddr) {
for _, h := range xHeaders {

View file

@ -203,6 +203,17 @@ func TestServeHTTP(t *testing.T) {
xForwardedProto: "wss",
},
},
{
desc: "xForwardedProto with websocket and tls and already x-forwarded-proto with wss",
tls: true,
websocket: true,
incomingHeaders: map[string]string{
xForwardedProto: "wss",
},
expectedHeaders: map[string]string{
xForwardedProto: "wss",
},
},
{
desc: "xForwardedPort with explicit port",
host: "foo.com:8080",

View file

@ -6,12 +6,12 @@ import (
"github.com/containous/traefik/v2/pkg/safe"
)
// HTTPHandlerSwitcher allows hot switching of http.ServeMux
// HTTPHandlerSwitcher allows hot switching of http.ServeMux.
type HTTPHandlerSwitcher struct {
handler *safe.Safe
}
// NewHandlerSwitcher builds a new instance of HTTPHandlerSwitcher
// NewHandlerSwitcher builds a new instance of HTTPHandlerSwitcher.
func NewHandlerSwitcher(newHandler http.Handler) (hs *HTTPHandlerSwitcher) {
return &HTTPHandlerSwitcher{
handler: safe.New(newHandler),
@ -23,13 +23,13 @@ func (h *HTTPHandlerSwitcher) ServeHTTP(rw http.ResponseWriter, req *http.Reques
handlerBackup.ServeHTTP(rw, req)
}
// GetHandler returns the current http.ServeMux
// GetHandler returns the current http.ServeMux.
func (h *HTTPHandlerSwitcher) GetHandler() (newHandler http.Handler) {
handler := h.handler.Get().(http.Handler)
return handler
}
// UpdateHandler safely updates the current http.ServeMux with a new one
// UpdateHandler safely updates the current http.ServeMux with a new one.
func (h *HTTPHandlerSwitcher) UpdateHandler(newHandler http.Handler) {
h.handler.Set(newHandler)
}

View file

@ -38,12 +38,12 @@ func New(ctx context.Context, next http.Handler, config dynamic.InFlightReq, nam
sourceMatcher, err := middlewares.GetSourceExtractor(ctxLog, config.SourceCriterion)
if err != nil {
return nil, fmt.Errorf("error creating requests limiter: %v", err)
return nil, fmt.Errorf("error creating requests limiter: %w", err)
}
handler, err := connlimit.New(next, sourceMatcher, config.Amount)
if err != nil {
return nil, fmt.Errorf("error creating connection limit: %v", err)
return nil, fmt.Errorf("error creating connection limit: %w", err)
}
return &inFlightReq{handler: handler, name: name}, nil

View file

@ -18,7 +18,7 @@ const (
typeName = "IPWhiteLister"
)
// ipWhiteLister is a middleware that provides Checks of the Requesting IP against a set of Whitelists
// ipWhiteLister is a middleware that provides Checks of the Requesting IP against a set of Whitelists.
type ipWhiteLister struct {
next http.Handler
whiteLister *ip.Checker
@ -26,7 +26,7 @@ type ipWhiteLister struct {
name string
}
// New builds a new IPWhiteLister given a list of CIDR-Strings to whitelist
// New builds a new IPWhiteLister given a list of CIDR-Strings to whitelist.
func New(ctx context.Context, next http.Handler, config dynamic.IPWhiteList, name string) (http.Handler, error) {
logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName))
logger.Debug("Creating middleware")
@ -37,7 +37,7 @@ func New(ctx context.Context, next http.Handler, config dynamic.IPWhiteList, nam
checker, err := ip.NewChecker(config.SourceRange)
if err != nil {
return nil, fmt.Errorf("cannot parse CIDR whitelist %s: %v", config.SourceRange, err)
return nil, fmt.Errorf("cannot parse CIDR whitelist %s: %w", config.SourceRange, err)
}
strategy, err := config.IPStrategy.Get()

View file

@ -50,7 +50,7 @@ func (r *responseRecorder) WriteHeader(status int) {
r.statusCode = status
}
// Hijack hijacks the connection
// Hijack hijacks the connection.
func (r *responseRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return r.ResponseWriter.(http.Hijacker).Hijack()
}

View file

@ -139,7 +139,7 @@ func (p *passTLSClientCert) ServeHTTP(rw http.ResponseWriter, req *http.Request)
// - the `,` is used to separate certificates
// - the `;` is used to separate root fields
// - the value of root fields is always wrapped by double quote
// - if a field is empty, the field is ignored
// - if a field is empty, the field is ignored.
func (p *passTLSClientCert) getCertInfo(ctx context.Context, certs []*x509.Certificate) string {
var headerValues []string

View file

@ -14,12 +14,12 @@ const (
typeName = "Pipelining"
)
// pipelining returns a middleware
// pipelining returns a middleware.
type pipelining struct {
next http.Handler
}
// New returns a new pipelining instance
// New returns a new pipelining instance.
func New(ctx context.Context, next http.Handler, name string) http.Handler {
log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware")
@ -37,7 +37,7 @@ func (p *pipelining) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
}
}
// writerWithoutCloseNotify helps to disable closeNotify
// writerWithoutCloseNotify helps to disable closeNotify.
type writerWithoutCloseNotify struct {
W http.ResponseWriter
}
@ -52,8 +52,7 @@ func (w *writerWithoutCloseNotify) Write(buf []byte) (int, error) {
return w.W.Write(buf)
}
// WriteHeader sends an HTTP response header with the provided
// status code.
// WriteHeader sends an HTTP response header with the provided status code.
func (w *writerWithoutCloseNotify) WriteHeader(code int) {
w.W.WriteHeader(code)
}

View file

@ -34,7 +34,7 @@ func New(ctx context.Context, next http.Handler, config dynamic.ReplacePathRegex
exp, err := regexp.Compile(strings.TrimSpace(config.Regex))
if err != nil {
return nil, fmt.Errorf("error compiling regular expression %s: %s", config.Regex, err)
return nil, fmt.Errorf("error compiling regular expression %s: %w", config.Regex, err)
}
return &replacePathRegex{

View file

@ -105,7 +105,7 @@ func cnameResolve(ctx context.Context, host string, resolvPath string) (*cnameRe
func getRecord(client *dns.Client, msg *dns.Msg, server string, port string) (*cnameResolv, error) {
resp, _, err := client.Exchange(msg, net.JoinHostPort(server, port))
if err != nil {
return nil, fmt.Errorf("exchange error for server %s: %v", server, err)
return nil, fmt.Errorf("exchange error for server %s: %w", server, err)
}
if resp == nil || len(resp.Answer) == 0 {

View file

@ -3,7 +3,7 @@ package middlewares
import "net/http"
// Stateful interface groups all http interfaces that must be
// implemented by a stateful middleware (ie: recorders)
// implemented by a stateful middleware (ie: recorders).
type Stateful interface {
http.ResponseWriter
http.Hijacker

View file

@ -27,12 +27,12 @@ func (n MockTracer) Extract(format interface{}, carrier interface{}) (opentracin
return nil, opentracing.ErrSpanContextNotFound
}
// MockSpanContext
// MockSpanContext.
type MockSpanContext struct{}
func (n MockSpanContext) ForeachBaggageItem(handler func(k, v string) bool) {}
// MockSpan
// MockSpan.
type MockSpan struct {
OpName string
Tags map[string]interface{}

View file

@ -22,12 +22,12 @@ func (s *statusCodeWithoutCloseNotify) WriteHeader(status int) {
s.ResponseWriter.WriteHeader(status)
}
// Status get response status
// Status get response status.
func (s *statusCodeWithoutCloseNotify) Status() int {
return s.status
}
// Hijack hijacks the connection
// Hijack hijacks the connection.
func (s *statusCodeWithoutCloseNotify) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return s.ResponseWriter.(http.Hijacker).Hijack()
}

View file

@ -35,7 +35,7 @@ func Wrap(ctx context.Context, constructor alice.Constructor) alice.Constructor
}
}
// NewWrapper returns a http.Handler struct
// NewWrapper returns a http.Handler struct.
func NewWrapper(next http.Handler, name string, spanKind ext.SpanKindEnum) http.Handler {
return &Wrapper{
next: next,

View file

@ -12,7 +12,7 @@ import (
"github.com/go-acme/lego/v3/registration"
)
// Account is used to store lets encrypt registration info
// Account is used to store lets encrypt registration info.
type Account struct {
Email string
Registration *registration.Resource
@ -21,11 +21,11 @@ type Account struct {
}
const (
// RegistrationURLPathV1Regexp is a regexp which match ACME registration URL in the V1 format
// RegistrationURLPathV1Regexp is a regexp which match ACME registration URL in the V1 format.
RegistrationURLPathV1Regexp = `^.*/acme/reg/\d+$`
)
// NewAccount creates an account
// NewAccount creates an account.
func NewAccount(ctx context.Context, email string, keyTypeValue string) (*Account, error) {
keyType := GetKeyType(ctx, keyTypeValue)
@ -42,17 +42,17 @@ func NewAccount(ctx context.Context, email string, keyTypeValue string) (*Accoun
}, nil
}
// GetEmail returns email
// GetEmail returns email.
func (a *Account) GetEmail() string {
return a.Email
}
// GetRegistration returns lets encrypt registration resource
// GetRegistration returns lets encrypt registration resource.
func (a *Account) GetRegistration() *registration.Resource {
return a.Registration
}
// GetPrivateKey returns private key
// GetPrivateKey returns private key.
func (a *Account) GetPrivateKey() crypto.PrivateKey {
privateKey, err := x509.ParsePKCS1PrivateKey(a.PrivateKey)
if err != nil {
@ -64,7 +64,7 @@ func (a *Account) GetPrivateKey() crypto.PrivateKey {
return privateKey
}
// GetKeyType used to determine which algo to used
// GetKeyType used to determine which algo to used.
func GetKeyType(ctx context.Context, value string) certcrypto.KeyType {
logger := log.FromContext(ctx)

View file

@ -13,7 +13,7 @@ import (
var _ Store = (*LocalStore)(nil)
// LocalStore Stores implementation for local file
// LocalStore Stores implementation for local file.
type LocalStore struct {
saveDataChan chan map[string]*StoredData
filename string
@ -22,7 +22,7 @@ type LocalStore struct {
storedData map[string]*StoredData
}
// NewLocalStore initializes a new LocalStore with a file name
// NewLocalStore initializes a new LocalStore with a file name.
func NewLocalStore(filename string) *LocalStore {
store := &LocalStore{filename: filename, saveDataChan: make(chan map[string]*StoredData)}
store.listenSaveAction()
@ -93,7 +93,7 @@ func (s *LocalStore) get(resolverName string) (*StoredData, error) {
return s.storedData[resolverName], nil
}
// listenSaveAction listens to a chan to store ACME data in json format into LocalStore.filename
// listenSaveAction listens to a chan to store ACME data in json format into `LocalStore.filename`.
func (s *LocalStore) listenSaveAction() {
safe.Go(func() {
logger := log.WithoutContext().WithField(log.ProviderName, "acme")
@ -111,7 +111,7 @@ func (s *LocalStore) listenSaveAction() {
})
}
// GetAccount returns ACME Account
// GetAccount returns ACME Account.
func (s *LocalStore) GetAccount(resolverName string) (*Account, error) {
storedData, err := s.get(resolverName)
if err != nil {
@ -121,7 +121,7 @@ func (s *LocalStore) GetAccount(resolverName string) (*Account, error) {
return storedData.Account, nil
}
// SaveAccount stores ACME Account
// SaveAccount stores ACME Account.
func (s *LocalStore) SaveAccount(resolverName string, account *Account) error {
storedData, err := s.get(resolverName)
if err != nil {
@ -134,7 +134,7 @@ func (s *LocalStore) SaveAccount(resolverName string, account *Account) error {
return nil
}
// GetCertificates returns ACME Certificates list
// GetCertificates returns ACME Certificates list.
func (s *LocalStore) GetCertificates(resolverName string) ([]*CertAndStore, error) {
storedData, err := s.get(resolverName)
if err != nil {
@ -144,7 +144,7 @@ func (s *LocalStore) GetCertificates(resolverName string) ([]*CertAndStore, erro
return storedData.Certificates, nil
}
// SaveCertificates stores ACME Certificates list
// SaveCertificates stores ACME Certificates list.
func (s *LocalStore) SaveCertificates(resolverName string, certificates []*CertAndStore) error {
storedData, err := s.get(resolverName)
if err != nil {
@ -173,7 +173,7 @@ func NewLocalChallengeStore() *LocalChallengeStore {
}
}
// GetHTTPChallengeToken Get the http challenge token from the store
// GetHTTPChallengeToken Get the http challenge token from the store.
func (s *LocalChallengeStore) GetHTTPChallengeToken(token, domain string) ([]byte, error) {
s.lock.RLock()
defer s.lock.RUnlock()
@ -193,7 +193,7 @@ func (s *LocalChallengeStore) GetHTTPChallengeToken(token, domain string) ([]byt
return result, nil
}
// SetHTTPChallengeToken Set the http challenge token in the store
// SetHTTPChallengeToken Set the http challenge token in the store.
func (s *LocalChallengeStore) SetHTTPChallengeToken(token, domain string, keyAuth []byte) error {
s.lock.Lock()
defer s.lock.Unlock()
@ -210,7 +210,7 @@ func (s *LocalChallengeStore) SetHTTPChallengeToken(token, domain string, keyAut
return nil
}
// RemoveHTTPChallengeToken Remove the http challenge token in the store
// RemoveHTTPChallengeToken Remove the http challenge token in the store.
func (s *LocalChallengeStore) RemoveHTTPChallengeToken(token, domain string) error {
s.lock.Lock()
defer s.lock.Unlock()
@ -228,7 +228,7 @@ func (s *LocalChallengeStore) RemoveHTTPChallengeToken(token, domain string) err
return nil
}
// AddTLSChallenge Add a certificate to the ACME TLS-ALPN-01 certificates storage
// AddTLSChallenge Add a certificate to the ACME TLS-ALPN-01 certificates storage.
func (s *LocalChallengeStore) AddTLSChallenge(domain string, cert *Certificate) error {
s.lock.Lock()
defer s.lock.Unlock()
@ -241,7 +241,7 @@ func (s *LocalChallengeStore) AddTLSChallenge(domain string, cert *Certificate)
return nil
}
// GetTLSChallenge Get a certificate from the ACME TLS-ALPN-01 certificates storage
// GetTLSChallenge Get a certificate from the ACME TLS-ALPN-01 certificates storage.
func (s *LocalChallengeStore) GetTLSChallenge(domain string) (*Certificate, error) {
s.lock.Lock()
defer s.lock.Unlock()
@ -253,7 +253,7 @@ func (s *LocalChallengeStore) GetTLSChallenge(domain string) (*Certificate, erro
return s.storedData.TLSChallenges[domain], nil
}
// RemoveTLSChallenge Remove a certificate from the ACME TLS-ALPN-01 certificates storage
// RemoveTLSChallenge Remove a certificate from the ACME TLS-ALPN-01 certificates storage.
func (s *LocalChallengeStore) RemoveTLSChallenge(domain string) error {
s.lock.Lock()
defer s.lock.Unlock()

View file

@ -7,7 +7,7 @@ import (
"os"
)
// CheckFile checks file permissions and content size
// CheckFile checks file permissions and content size.
func CheckFile(name string) (bool, error) {
f, err := os.Open(name)
if err != nil {

View file

@ -28,11 +28,11 @@ import (
)
var (
// oscpMustStaple enables OSCP stapling as from https://github.com/go-acme/lego/issues/270
// oscpMustStaple enables OSCP stapling as from https://github.com/go-acme/lego/issues/270.
oscpMustStaple = false
)
// Configuration holds ACME configuration provided by users
// 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"`
@ -56,14 +56,14 @@ type CertAndStore struct {
Store string
}
// Certificate is a struct which contains all data needed from an ACME certificate
// 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"`
}
// DNSChallenge contains DNS challenge Configuration
// 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"`
DelayBeforeCheck types.Duration `description:"Assume DNS propagates after a delay in seconds rather than finding and querying nameservers." json:"delayBeforeCheck,omitempty" toml:"delayBeforeCheck,omitempty" yaml:"delayBeforeCheck,omitempty"`
@ -71,12 +71,12 @@ type DNSChallenge struct {
DisablePropagationCheck bool `description:"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"`
}
// HTTPChallenge contains HTTP challenge Configuration
// HTTPChallenge contains HTTP challenge Configuration.
type HTTPChallenge struct {
EntryPoint string `description:"HTTP challenge EntryPoint" json:"entryPoint,omitempty" toml:"entryPoint,omitempty" yaml:"entryPoint,omitempty"`
}
// TLSChallenge contains TLS challenge Configuration
// TLSChallenge contains TLS challenge Configuration.
type TLSChallenge struct{}
// Provider holds configurations of the provider.
@ -98,22 +98,22 @@ type Provider struct {
resolvingDomainsMutex sync.RWMutex
}
// SetTLSManager sets the tls manager to use
// SetTLSManager sets the tls manager to use.
func (p *Provider) SetTLSManager(tlsManager *traefiktls.Manager) {
p.tlsManager = tlsManager
}
// SetConfigListenerChan initializes the configFromListenerChan
// SetConfigListenerChan initializes the configFromListenerChan.
func (p *Provider) SetConfigListenerChan(configFromListenerChan chan dynamic.Configuration) {
p.configFromListenerChan = configFromListenerChan
}
// ListenConfiguration sets a new Configuration into the configFromListenerChan
// ListenConfiguration sets a new Configuration into the configFromListenerChan.
func (p *Provider) ListenConfiguration(config dynamic.Configuration) {
p.configFromListenerChan <- config
}
// Init for compatibility reason the BaseProvider implements an empty Init
// Init for compatibility reason the BaseProvider implements an empty Init.
func (p *Provider) Init() error {
ctx := log.With(context.Background(), log.Str(log.ProviderName, p.ResolverName+".acme"))
logger := log.FromContext(ctx)
@ -125,7 +125,7 @@ func (p *Provider) Init() error {
var err error
p.account, err = p.Store.GetAccount(p.ResolverName)
if err != nil {
return fmt.Errorf("unable to get ACME account: %v", err)
return fmt.Errorf("unable to get ACME account: %w", err)
}
// Reset Account if caServer changed, thus registration URI can be updated
@ -136,7 +136,7 @@ func (p *Provider) Init() error {
p.certificates, err = p.Store.GetCertificates(p.ResolverName)
if err != nil {
return fmt.Errorf("unable to get ACME certificates : %v", err)
return fmt.Errorf("unable to get ACME certificates : %w", err)
}
// Init the currently resolved domain map
@ -442,7 +442,7 @@ func (p *Provider) resolveCertificate(ctx context.Context, domain types.Domain,
client, err := p.getClient()
if err != nil {
return nil, fmt.Errorf("cannot get ACME client %v", err)
return nil, fmt.Errorf("cannot get ACME client %w", err)
}
request := certificate.ObtainRequest{
@ -453,7 +453,7 @@ func (p *Provider) resolveCertificate(ctx context.Context, domain types.Domain,
cert, err := client.Certificate.Obtain(request)
if err != nil {
return nil, fmt.Errorf("unable to generate a certificate for the domains %v: %v", uncheckedDomains, err)
return nil, fmt.Errorf("unable to generate a certificate for the domains %v: %w", uncheckedDomains, err)
}
if cert == nil {
return nil, fmt.Errorf("domains %v do not generate a certificate", uncheckedDomains)
@ -498,7 +498,7 @@ func (p *Provider) addCertificateForDomain(domain types.Domain, certificate []by
// deleteUnnecessaryDomains deletes from the configuration :
// - Duplicated domains
// - Domains which are checked by wildcard domain
// - Domains which are checked by wildcard domain.
func deleteUnnecessaryDomains(ctx context.Context, domains []types.Domain) []types.Domain {
var newDomains []types.Domain
@ -657,7 +657,7 @@ func (p *Provider) renewCertificates(ctx context.Context) {
}
// Get provided certificate which check a domains list (Main and SANs)
// from static and dynamic provided certificates
// from static and dynamic provided certificates.
func (p *Provider) getUncheckedDomains(ctx context.Context, domainsToCheck []string, tlsStore string) []string {
p.resolvingDomainsMutex.RLock()
defer p.resolvingDomainsMutex.RUnlock()
@ -716,7 +716,7 @@ func getX509Certificate(ctx context.Context, cert *Certificate) (*x509.Certifica
return crt, err
}
// getValidDomains checks if given domain is allowed to generate a ACME certificate and return it
// getValidDomains checks if given domain is allowed to generate a ACME certificate and return it.
func (p *Provider) getValidDomains(ctx context.Context, domain types.Domain) ([]string, error) {
domains := domain.ToStrArray()
if len(domains) == 0 {

View file

@ -94,12 +94,12 @@ func (p *ProviderAggregator) AddProvider(provider provider.Provider) error {
return nil
}
// Init the provider
// Init the provider.
func (p ProviderAggregator) Init() error {
return nil
}
// Provide calls the provide method of every providers
// Provide calls the provide method of every providers.
func (p ProviderAggregator) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error {
if p.fileProvider != nil {
launchProvider(configurationChan, pool, p.fileProvider)

View file

@ -18,7 +18,7 @@ type constraintLabelFunc func(map[string]string) bool
// The expression must match any logical boolean combination of:
// - `Label(labelName, labelValue)`
// - `LabelRegex(labelName, regexValue)`
// - `MarathonConstraint(field:operator:value)`
// - `MarathonConstraint(field:operator:value)`.
func MatchLabels(labels map[string]string, expr string) (bool, error) {
if expr == "" {
return true, nil

View file

@ -12,7 +12,7 @@ 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)`
// - `TagRegex(regexValue)`.
func MatchTags(tags []string, expr string) (bool, error) {
if expr == "" {
return true, nil

View file

@ -89,7 +89,7 @@ func (p *Provider) SetDefaults() {
func (p *Provider) Init() error {
defaultRuleTpl, err := provider.MakeDefaultRuleTemplate(p.DefaultRule, nil)
if err != nil {
return fmt.Errorf("error while parsing default rule: %v", err)
return fmt.Errorf("error while parsing default rule: %w", err)
}
p.defaultRuleTpl = defaultRuleTpl
@ -107,7 +107,7 @@ func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.
p.client, err = createClient(p.Endpoint)
if err != nil {
return fmt.Errorf("error create consul client, %v", err)
return fmt.Errorf("error create consul client, %w", err)
}
ticker := time.NewTicker(time.Duration(p.RefreshInterval))

View file

@ -73,7 +73,7 @@ func (p *Provider) SetDefaults() {
func (p *Provider) Init() error {
defaultRuleTpl, err := provider.MakeDefaultRuleTemplate(p.DefaultRule, nil)
if err != nil {
return fmt.Errorf("error while parsing default rule: %v", err)
return fmt.Errorf("error while parsing default rule: %w", err)
}
p.defaultRuleTpl = defaultRuleTpl

View file

@ -11,7 +11,8 @@ const (
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.
// 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
Docker specificConfiguration
@ -38,8 +39,8 @@ func (p *Provider) getConfiguration(container dockerData) (configuration, error)
return conf, nil
}
// getStringMultipleStrict get multiple string values associated to several labels
// Fail if one label is missing
// 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 {
@ -53,7 +54,7 @@ func getStringMultipleStrict(labels map[string]string, labelNames ...string) (ma
return foundLabels, nil
}
// getStringValue get string value associated to a label
// getStringValue get string value associated to a label.
func getStringValue(labels map[string]string, labelName string, defaultValue string) string {
if value, ok := labels[labelName]; ok && len(value) > 0 {
return value

View file

@ -40,7 +40,7 @@ func (p *Provider) SetDefaults() {
p.Filename = ""
}
// Init the provider
// Init the provider.
func (p *Provider) Init() error {
return nil
}
@ -75,8 +75,8 @@ func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.
return nil
}
// BuildConfiguration loads configuration either from file or a directory specified by 'Filename'/'Directory'
// and returns a 'Configuration' object
// 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(context.Background(), log.Str(log.ProviderName, providerName))
@ -94,12 +94,12 @@ func (p *Provider) BuildConfiguration() (*dynamic.Configuration, error) {
func (p *Provider) addWatcher(pool *safe.Pool, directory string, configurationChan chan<- dynamic.Message, callback func(chan<- dynamic.Message, fsnotify.Event)) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return fmt.Errorf("error creating file watcher: %s", err)
return fmt.Errorf("error creating file watcher: %w", err)
}
err = watcher.Add(directory)
if err != nil {
return fmt.Errorf("error adding file watcher: %s", err)
return fmt.Errorf("error adding file watcher: %w", err)
}
// Process events
@ -201,7 +201,7 @@ func flattenCertificates(ctx context.Context, tlsConfig *dynamic.TLSConfiguratio
func (p *Provider) loadFileConfigFromDirectory(ctx context.Context, directory string, configuration *dynamic.Configuration) (*dynamic.Configuration, error) {
fileList, err := ioutil.ReadDir(directory)
if err != nil {
return configuration, fmt.Errorf("unable to read directory %s: %v", directory, err)
return configuration, fmt.Errorf("unable to read directory %s: %w", directory, err)
}
if configuration == nil {
@ -234,7 +234,7 @@ func (p *Provider) loadFileConfigFromDirectory(ctx context.Context, directory st
if item.IsDir() {
configuration, err = p.loadFileConfigFromDirectory(ctx, filepath.Join(directory, item.Name()), configuration)
if err != nil {
return configuration, fmt.Errorf("unable to load content configuration from subdirectory %s: %v", item, err)
return configuration, fmt.Errorf("unable to load content configuration from subdirectory %s: %w", item, err)
}
continue
}
@ -249,7 +249,7 @@ func (p *Provider) loadFileConfigFromDirectory(ctx context.Context, directory st
var c *dynamic.Configuration
c, err = p.loadFileConfig(ctx, filepath.Join(directory, item.Name()), true)
if err != nil {
return configuration, fmt.Errorf("%s: %v", filepath.Join(directory, item.Name()), err)
return configuration, fmt.Errorf("%s: %w", filepath.Join(directory, item.Name()), err)
}
for name, conf := range c.HTTP.Routers {
@ -354,7 +354,7 @@ func (p *Provider) loadFileConfigFromDirectory(ctx context.Context, directory st
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 - %s", filename, err)
return nil, fmt.Errorf("error reading configuration file: %s - %w", filename, err)
}
var defaultFuncMap = sprig.TxtFuncMap()
@ -391,7 +391,7 @@ func (p *Provider) CreateConfiguration(ctx context.Context, filename string, fun
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 - %s", filename, err)
return nil, fmt.Errorf("error reading configuration file: %s - %w", filename, err)
}
return p.decodeConfiguration(filename, content)

View file

@ -280,7 +280,7 @@ func createProvider(t *testing.T, test ProvideTestCase, watch bool) (*Provider,
}
}
// createTempDir Helper
// createTempDir Helper.
func createTempDir(t *testing.T, dir string) string {
t.Helper()

View file

@ -101,7 +101,7 @@ func newClientImpl(csKube *kubernetes.Clientset, csCrd *versioned.Clientset) *cl
func newInClusterClient(endpoint string) (*clientWrapper, error) {
config, err := rest.InClusterConfig()
if err != nil {
return nil, fmt.Errorf("failed to create in-cluster configuration: %v", err)
return nil, fmt.Errorf("failed to create in-cluster configuration: %w", err)
}
if endpoint != "" {
@ -135,7 +135,7 @@ func newExternalClusterClient(endpoint, token, caFilePath string) (*clientWrappe
if caFilePath != "" {
caData, err := ioutil.ReadFile(caFilePath)
if err != nil {
return nil, fmt.Errorf("failed to read CA file %s: %v", caFilePath, err)
return nil, fmt.Errorf("failed to read CA file %s: %w", caFilePath, err)
}
config.TLSClientConfig = rest.TLSClientConfig{CAData: caData}

View file

@ -325,7 +325,7 @@ func createForwardAuthMiddleware(k8sClient Client, namespace string, auth *v1alp
if len(auth.TLS.CASecret) > 0 {
caSecret, err := loadCASecret(namespace, auth.TLS.CASecret, k8sClient)
if err != nil {
return nil, fmt.Errorf("failed to load auth ca secret: %v", err)
return nil, fmt.Errorf("failed to load auth ca secret: %w", err)
}
forwardAuth.TLS.CA = caSecret
}
@ -333,7 +333,7 @@ func createForwardAuthMiddleware(k8sClient Client, namespace string, auth *v1alp
if len(auth.TLS.CertSecret) > 0 {
authSecretCert, authSecretKey, err := loadAuthTLSSecret(namespace, auth.TLS.CertSecret, k8sClient)
if err != nil {
return nil, fmt.Errorf("failed to load auth secret: %v", err)
return nil, fmt.Errorf("failed to load auth secret: %w", err)
}
forwardAuth.TLS.Cert = authSecretCert
forwardAuth.TLS.Key = authSecretKey
@ -345,7 +345,7 @@ func createForwardAuthMiddleware(k8sClient Client, namespace string, auth *v1alp
func loadCASecret(namespace, secretName string, k8sClient Client) (string, error) {
secret, ok, err := k8sClient.GetSecret(namespace, secretName)
if err != nil {
return "", fmt.Errorf("failed to fetch secret '%s/%s': %v", namespace, secretName, err)
return "", fmt.Errorf("failed to fetch secret '%s/%s': %w", namespace, secretName, err)
}
if !ok {
return "", fmt.Errorf("secret '%s/%s' not found", namespace, secretName)
@ -366,7 +366,7 @@ func loadCASecret(namespace, secretName string, k8sClient Client) (string, error
func loadAuthTLSSecret(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': %s", namespace, secretName, err)
return "", "", fmt.Errorf("failed to fetch secret '%s/%s': %w", namespace, secretName, err)
}
if !exists {
return "", "", fmt.Errorf("secret '%s/%s' does not exist", namespace, secretName)
@ -424,7 +424,7 @@ func getAuthCredentials(k8sClient Client, authSecret, namespace string) ([]strin
auth, err := loadAuthCredentials(namespace, authSecret, k8sClient)
if err != nil {
return nil, fmt.Errorf("failed to load auth credentials: %v", err)
return nil, fmt.Errorf("failed to load auth credentials: %w", err)
}
return auth, nil
@ -433,7 +433,7 @@ func getAuthCredentials(k8sClient Client, authSecret, namespace string) ([]strin
func loadAuthCredentials(namespace, secretName string, k8sClient Client) ([]string, error) {
secret, ok, err := k8sClient.GetSecret(namespace, secretName)
if err != nil {
return nil, fmt.Errorf("failed to fetch secret '%s/%s': %v", namespace, secretName, err)
return nil, fmt.Errorf("failed to fetch secret '%s/%s': %w", namespace, secretName, err)
}
if !ok {
return nil, fmt.Errorf("secret '%s/%s' not found", namespace, secretName)
@ -459,7 +459,7 @@ func loadAuthCredentials(namespace, secretName string, k8sClient Client) ([]stri
}
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("error reading secret for %s/%s: %v", namespace, secretName, err)
return nil, fmt.Errorf("error reading secret for %s/%s: %w", namespace, secretName, err)
}
if len(credentials) == 0 {
return nil, fmt.Errorf("secret '%s/%s' does not contain any credentials", namespace, secretName)
@ -641,7 +641,7 @@ func shouldProcessIngress(ingressClass string, ingressClassAnnotation string) bo
func getTLS(k8sClient Client, secretName, namespace string) (*tls.CertAndStores, error) {
secret, exists, err := k8sClient.GetSecret(namespace, secretName)
if err != nil {
return nil, fmt.Errorf("failed to fetch secret %s/%s: %v", namespace, secretName, err)
return nil, fmt.Errorf("failed to fetch secret %s/%s: %w", namespace, secretName, err)
}
if !exists {
return nil, fmt.Errorf("secret %s/%s does not exist", namespace, secretName)

View file

@ -55,7 +55,7 @@ type ErrorPage struct {
// +k8s:deepcopy-gen=true
// Chain holds a chain of middlewares
// Chain holds a chain of middlewares.
type Chain struct {
Middlewares []MiddlewareRef `json:"middlewares,omitempty"`
}

View file

@ -17,7 +17,7 @@ type TLSOption struct {
// +k8s:deepcopy-gen=true
// TLSOptionSpec configures TLS for an entry point
// TLSOptionSpec configures TLS for an entry point.
type TLSOptionSpec struct {
MinVersion string `json:"minVersion,omitempty"`
MaxVersion string `json:"maxVersion,omitempty"`

View file

@ -68,7 +68,7 @@ type clientWrapper struct {
func newInClusterClient(endpoint string) (*clientWrapper, error) {
config, err := rest.InClusterConfig()
if err != nil {
return nil, fmt.Errorf("failed to create in-cluster configuration: %s", err)
return nil, fmt.Errorf("failed to create in-cluster configuration: %w", err)
}
if endpoint != "" {
@ -102,7 +102,7 @@ func newExternalClusterClient(endpoint, token, caFilePath string) (*clientWrappe
if caFilePath != "" {
caData, err := ioutil.ReadFile(caFilePath)
if err != nil {
return nil, fmt.Errorf("failed to read CA file %s: %s", caFilePath, err)
return nil, fmt.Errorf("failed to read CA file %s: %w", caFilePath, err)
}
config.TLSClientConfig = rest.TLSClientConfig{CAData: caData}
@ -219,7 +219,7 @@ func (c *clientWrapper) UpdateIngressStatus(src *networkingv1beta1.Ingress, ip,
ing, err := c.factories[c.lookupNamespace(src.Namespace)].Networking().V1beta1().Ingresses().Lister().Ingresses(src.Namespace).Get(src.Name)
if err != nil {
return fmt.Errorf("failed to get ingress %s/%s: %v", src.Namespace, src.Name, err)
return fmt.Errorf("failed to get ingress %s/%s: %w", src.Namespace, src.Name, err)
}
if len(ing.Status.LoadBalancer.Ingress) > 0 {
@ -238,7 +238,7 @@ func (c *clientWrapper) UpdateIngressStatus(src *networkingv1beta1.Ingress, ip,
_, err = c.clientset.NetworkingV1beta1().Ingresses(ingCopy.Namespace).UpdateStatus(ctx, ingCopy, metav1.UpdateOptions{})
if err != nil {
return fmt.Errorf("failed to update ingress status %s/%s: %v", src.Namespace, src.Name, err)
return fmt.Errorf("failed to update ingress status %s/%s: %w", src.Namespace, src.Name, err)
}
log.Infof("Updated status on ingress %s/%s", src.Namespace, src.Name)
@ -248,7 +248,7 @@ func (c *clientWrapper) UpdateIngressStatus(src *networkingv1beta1.Ingress, ip,
func (c *clientWrapper) updateIngressStatusOld(src *networkingv1beta1.Ingress, ip, hostname string) error {
ing, err := c.factories[c.lookupNamespace(src.Namespace)].Extensions().V1beta1().Ingresses().Lister().Ingresses(src.Namespace).Get(src.Name)
if err != nil {
return fmt.Errorf("failed to get ingress %s/%s: %v", src.Namespace, src.Name, err)
return fmt.Errorf("failed to get ingress %s/%s: %w", src.Namespace, src.Name, err)
}
if len(ing.Status.LoadBalancer.Ingress) > 0 {
@ -267,7 +267,7 @@ func (c *clientWrapper) updateIngressStatusOld(src *networkingv1beta1.Ingress, i
_, err = c.clientset.ExtensionsV1beta1().Ingresses(ingCopy.Namespace).UpdateStatus(ctx, ingCopy, metav1.UpdateOptions{})
if err != nil {
return fmt.Errorf("failed to update ingress status %s/%s: %v", src.Namespace, src.Name, err)
return fmt.Errorf("failed to update ingress status %s/%s: %w", src.Namespace, src.Name, err)
}
log.Infof("Updated status on ingress %s/%s", src.Namespace, src.Name)

View file

@ -46,7 +46,7 @@ type Provider struct {
lastConfiguration safe.Safe
}
// EndpointIngress holds the endpoint information for the Kubernetes provider
// 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"`
@ -306,7 +306,7 @@ func (p *Provider) updateIngressStatus(ing *v1beta1.Ingress, k8sClient Client) e
service, exists, err := k8sClient.GetService(serviceNamespace, serviceName)
if err != nil {
return fmt.Errorf("cannot get service %s, received error: %s", p.IngressEndpoint.PublishedService, err)
return fmt.Errorf("cannot get service %s, received error: %w", p.IngressEndpoint.PublishedService, err)
}
if exists && service.Status.LoadBalancer.Ingress == nil {
@ -346,7 +346,7 @@ func getCertificates(ctx context.Context, ingress *v1beta1.Ingress, k8sClient Cl
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: %v", ingress.Namespace, t.SecretName, err)
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)

View file

@ -19,7 +19,7 @@ func (p *Provider) SetDefaults() {
p.Endpoints = []string{"127.0.0.1:8500"}
}
// Init the provider
// Init the provider.
func (p *Provider) Init() error {
return p.Provider.Init(store.CONSUL, "consul")
}

View file

@ -19,7 +19,7 @@ func (p *Provider) SetDefaults() {
p.Endpoints = []string{"127.0.0.1:2379"}
}
// Init the provider
// Init the provider.
func (p *Provider) Init() error {
return p.Provider.Init(store.ETCDV3, "etcd")
}

View file

@ -41,7 +41,7 @@ func (p *Provider) SetDefaults() {
p.RootKey = "traefik"
}
// Init the provider
// Init the provider.
func (p *Provider) Init(storeType store.Backend, name string) error {
ctx := log.With(context.Background(), log.Str(log.ProviderName, name))

View file

@ -14,13 +14,13 @@ func newProviderMock(kvPairs []*store.KVPair) *Provider {
}
}
// Override Get/List to return a error
// Override Get/List to return a error.
type KvError struct {
Get error
List error
}
// Extremely limited mock store so we can test initialization
// Extremely limited mock store so we can test initialization.
type Mock struct {
Error KvError
KVPairs []*store.KVPair
@ -61,7 +61,7 @@ func (s *Mock) Delete(key string) error {
return errors.New("method Delete not supported")
}
// Exists mock
// Exists mock.
func (s *Mock) Exists(key string, options *store.ReadOptions) (bool, error) {
if err := s.Error.Get; err != nil {
return false, err
@ -74,22 +74,22 @@ func (s *Mock) Exists(key string, options *store.ReadOptions) (bool, error) {
return false, store.ErrKeyNotFound
}
// Watch mock
// Watch mock.
func (s *Mock) Watch(key string, stopCh <-chan struct{}, options *store.ReadOptions) (<-chan *store.KVPair, error) {
return nil, errors.New("method Watch not supported")
}
// WatchTree mock
// WatchTree mock.
func (s *Mock) WatchTree(prefix string, stopCh <-chan struct{}, options *store.ReadOptions) (<-chan []*store.KVPair, error) {
return s.WatchTreeMethod(), nil
}
// NewLock mock
// NewLock mock.
func (s *Mock) NewLock(key string, options *store.LockOptions) (store.Locker, error) {
return nil, errors.New("method NewLock not supported")
}
// List mock
// List mock.
func (s *Mock) List(prefix string, options *store.ReadOptions) ([]*store.KVPair, error) {
if err := s.Error.List; err != nil {
return nil, err
@ -103,20 +103,20 @@ func (s *Mock) List(prefix string, options *store.ReadOptions) ([]*store.KVPair,
return kv, nil
}
// DeleteTree mock
// DeleteTree mock.
func (s *Mock) DeleteTree(prefix string) error {
return errors.New("method DeleteTree not supported")
}
// AtomicPut mock
// AtomicPut mock.
func (s *Mock) AtomicPut(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
// AtomicDelete mock.
func (s *Mock) AtomicDelete(key string, previous *store.KVPair) (bool, error) {
return false, errors.New("method AtomicDelete not supported")
}
// Close mock
// Close mock.
func (s *Mock) Close() {}

View file

@ -19,7 +19,7 @@ func (p *Provider) SetDefaults() {
p.Endpoints = []string{"127.0.0.1:6379"}
}
// Init the provider
// Init the provider.
func (p *Provider) Init() error {
return p.Provider.Init(store.REDIS, "redis")
}

View file

@ -19,7 +19,7 @@ func (p *Provider) SetDefaults() {
p.Endpoints = []string{"127.0.0.1:2181"}
}
// Init the provider
// Init the provider.
func (p *Provider) Init() error {
return p.Provider.Init(store.ZK, "zookeeper")
}

View file

@ -362,7 +362,7 @@ func (p *Provider) getServerHost(task marathon.Task, app marathon.Application, e
func getPort(task marathon.Task, app marathon.Application, serverPort string) (string, error) {
port, err := processPorts(app, task, serverPort)
if err != nil {
return "", fmt.Errorf("unable to process ports for %s %s: %v", app.ID, task.ID, err)
return "", fmt.Errorf("unable to process ports for %s %s: %w", app.ID, task.ID, err)
}
return strconv.Itoa(port), nil

View file

@ -77,13 +77,13 @@ func (p *Provider) SetDefaults() {
p.DefaultRule = DefaultTemplateRule
}
// Basic holds basic authentication specific configurations
// Basic holds basic authentication specific configurations.
type Basic struct {
HTTPBasicAuthUser string `description:"Basic authentication User." json:"httpBasicAuthUser,omitempty" toml:"httpBasicAuthUser,omitempty" yaml:"httpBasicAuthUser,omitempty"`
HTTPBasicPassword string `description:"Basic authentication Password." json:"httpBasicPassword,omitempty" toml:"httpBasicPassword,omitempty" yaml:"httpBasicPassword,omitempty"`
}
// Init the provider
// Init the provider.
func (p *Provider) Init() error {
fm := template.FuncMap{
"strsToItfs": func(values []string) []interface{} {
@ -97,7 +97,7 @@ func (p *Provider) Init() error {
defaultRuleTpl, err := provider.MakeDefaultRuleTemplate(p.DefaultRule, fm)
if err != nil {
return fmt.Errorf("error while parsing default rule: %v", err)
return fmt.Errorf("error while parsing default rule: %w", err)
}
p.defaultRuleTpl = defaultRuleTpl

View file

@ -20,13 +20,13 @@ const (
DefaultTemplateRule = "Host(`{{ normalize .Name }}`)"
)
// Health
// Health.
const (
healthy = "healthy"
updatingHealthy = "updating-healthy"
)
// State
// States.
const (
active = "active"
running = "running"
@ -75,7 +75,7 @@ type rancherData struct {
func (p *Provider) Init() error {
defaultRuleTpl, err := provider.MakeDefaultRuleTemplate(p.DefaultRule, nil)
if err != nil {
return fmt.Errorf("error while parsing default rule: %v", err)
return fmt.Errorf("error while parsing default rule: %w", err)
}
p.defaultRuleTpl = defaultRuleTpl

View file

@ -31,7 +31,7 @@ func (p *Provider) Init() error {
return nil
}
// CreateRouter creates a router for the Rest API
// 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)

View file

@ -144,7 +144,7 @@ func (i *Provider) getEntryPointPort(name string, def *static.Redirections) (str
_, port, err := net.SplitHostPort(dst.Address)
if err != nil {
return "", fmt.Errorf("invalid entry point %q address %q: %v",
return "", fmt.Errorf("invalid entry point %q address %q: %w",
name, i.staticCfg.EntryPoints[def.EntryPoint.To].Address, err)
}

View file

@ -9,7 +9,7 @@ import (
type treeBuilder func() *tree
// ParseDomains extract domains from rule
// ParseDomains extract domains from rule.
func ParseDomains(rule string) ([]string, error) {
parser, err := newParser()
if err != nil {
@ -29,8 +29,8 @@ func ParseDomains(rule string) ([]string, error) {
return lower(parseDomain(buildTree())), nil
}
// ParseHostSNI extracts the HostSNIs declared in a rule
// This is a first naive implementation used in TCP routing
// ParseHostSNI extracts the HostSNIs declared in a rule.
// This is a first naive implementation used in TCP routing.
func ParseHostSNI(rule string) ([]string, error) {
parser, err := newTCPParser()
if err != nil {

View file

@ -22,7 +22,7 @@ var funcs = map[string]func(*mux.Route, ...string) error{
"Query": query,
}
// Router handle routing with rules
// Router handle routing with rules.
type Router struct {
*mux.Router
parser predicate.Parser
@ -45,7 +45,7 @@ func NewRouter() (*Router, error) {
func (r *Router) AddRoute(rule string, priority int, handler http.Handler) error {
parse, err := r.parser.Parse(rule)
if err != nil {
return fmt.Errorf("error while parsing rule %s: %v", rule, err)
return fmt.Errorf("error while parsing rule %s: %w", rule, err)
}
buildTree, ok := parse.(treeBuilder)

View file

@ -12,14 +12,14 @@ import (
type routineCtx func(ctx context.Context)
// Pool is a pool of go routines
// Pool is a pool of go routines.
type Pool struct {
waitGroup sync.WaitGroup
ctx context.Context
cancel context.CancelFunc
}
// NewPool creates a Pool
// NewPool creates a Pool.
func NewPool(parentCtx context.Context) *Pool {
ctx, cancel := context.WithCancel(parentCtx)
return &Pool{
@ -28,7 +28,7 @@ func NewPool(parentCtx context.Context) *Pool {
}
}
// GoCtx starts a recoverable goroutine with a context
// GoCtx starts a recoverable goroutine with a context.
func (p *Pool) GoCtx(goroutine routineCtx) {
p.waitGroup.Add(1)
Go(func() {
@ -37,18 +37,18 @@ func (p *Pool) GoCtx(goroutine routineCtx) {
})
}
// Stop stops all started routines, waiting for their termination
// Stop stops all started routines, waiting for their termination.
func (p *Pool) Stop() {
p.cancel()
p.waitGroup.Wait()
}
// Go starts a recoverable goroutine
// Go starts a recoverable goroutine.
func Go(goroutine func()) {
GoWithRecover(goroutine, defaultRecoverGoroutine)
}
// GoWithRecover starts a recoverable goroutine using given customRecover() function
// GoWithRecover starts a recoverable goroutine using given customRecover() function.
func GoWithRecover(goroutine func(), customRecover func(err interface{})) {
go func() {
defer func() {
@ -66,13 +66,13 @@ func defaultRecoverGoroutine(err interface{}) {
logger.Errorf("Stack: %s", debug.Stack())
}
// OperationWithRecover wrap a backoff operation in a Recover
// OperationWithRecover wrap a backoff operation in a Recover.
func OperationWithRecover(operation backoff.Operation) backoff.Operation {
return func() (err error) {
defer func() {
if res := recover(); res != nil {
defaultRecoverGoroutine(res)
err = fmt.Errorf("panic in operation: %s", err)
err = fmt.Errorf("panic in operation: %w", err)
}
}()
return operation()

View file

@ -4,25 +4,25 @@ import (
"sync"
)
// Safe contains a thread-safe value
// Safe contains a thread-safe value.
type Safe struct {
value interface{}
lock sync.RWMutex
}
// New create a new Safe instance given a value
// New create a new Safe instance given a value.
func New(value interface{}) *Safe {
return &Safe{value: value, lock: sync.RWMutex{}}
}
// Get returns the value
// Get returns the value.
func (s *Safe) Get() interface{} {
s.lock.RLock()
defer s.lock.RUnlock()
return s.value
}
// Set sets a new value
// Set sets a new value.
func (s *Safe) Set(value interface{}) {
s.lock.Lock()
defer s.lock.Unlock()

View file

@ -69,7 +69,7 @@ func (c *ConfigurationWatcher) Stop() {
close(c.configurationValidatedChan)
}
// AddListener adds a new listener function used when new configuration is provided
// AddListener adds a new listener function used when new configuration is provided.
func (c *ConfigurationWatcher) AddListener(listener func(dynamic.Configuration)) {
if c.configurationListeners == nil {
c.configurationListeners = make([]func(dynamic.Configuration), 0)

View file

@ -10,7 +10,7 @@ import (
const cookieNameLength = 6
// GetName of a cookie
// GetName of a cookie.
func GetName(cookieName string, backendName string) string {
if len(cookieName) != 0 {
return sanitizeName(cookieName)
@ -19,7 +19,7 @@ func GetName(cookieName string, backendName string) string {
return GenerateName(backendName)
}
// GenerateName Generate a hashed name
// GenerateName Generate a hashed name.
func GenerateName(backendName string) string {
data := []byte("_TRAEFIK_BACKEND_" + backendName)
@ -33,7 +33,7 @@ func GenerateName(backendName string) string {
return fmt.Sprintf("_%x", hash.Sum(nil))[:cookieNameLength]
}
// sanitizeName According to [RFC 2616](https://www.ietf.org/rfc/rfc2616.txt) section 2.2
// sanitizeName According to [RFC 2616](https://www.ietf.org/rfc/rfc2616.txt) section 2.2.
func sanitizeName(backend string) string {
sanitizer := func(r rune) rune {
switch r {

View file

@ -37,7 +37,7 @@ const (
middlewareStackKey middlewareStackType = iota
)
// Builder the middleware builder
// Builder the middleware builder.
type Builder struct {
configs map[string]*runtime.MiddlewareInfo
serviceBuilder serviceBuilder
@ -47,12 +47,12 @@ type serviceBuilder interface {
BuildHTTP(ctx context.Context, serviceName string, responseModifier func(*http.Response) error) (http.Handler, error)
}
// NewBuilder creates a new Builder
// NewBuilder creates a new Builder.
func NewBuilder(configs map[string]*runtime.MiddlewareInfo, serviceBuilder serviceBuilder) *Builder {
return &Builder{configs: configs, serviceBuilder: serviceBuilder}
}
// BuildChain creates a middleware chain
// BuildChain creates a middleware chain.
func (b *Builder) BuildChain(ctx context.Context, middlewares []string) *alice.Chain {
chain := alice.New()
for _, name := range middlewares {
@ -99,7 +99,7 @@ func checkRecursion(ctx context.Context, middlewareName string) (context.Context
return context.WithValue(ctx, middlewareStackKey, append(currentStack, middlewareName)), nil
}
// it is the responsibility of the caller to make sure that b.configs[middlewareName].Middleware exists
// it is the responsibility of the caller to make sure that b.configs[middlewareName].Middleware exists.
func (b *Builder) buildConstructor(ctx context.Context, middlewareName string) (alice.Constructor, error) {
config := b.configs[middlewareName]
if config == nil || config.Middleware == nil {

View file

@ -13,7 +13,7 @@ const (
key contextKey = iota
)
// AddInContext Adds the provider name in the context
// AddInContext Adds the provider name in the context.
func AddInContext(ctx context.Context, elementName string) context.Context {
parts := strings.Split(elementName, "@")
if len(parts) == 1 {
@ -39,7 +39,7 @@ func GetQualifiedName(ctx context.Context, elementName string) string {
return elementName
}
// MakeQualifiedName Creates a qualified name for an element
// MakeQualifiedName Creates a qualified name for an element.
func MakeQualifiedName(providerName string, elementName string) string {
return elementName + "@" + providerName
}

View file

@ -33,7 +33,7 @@ type serviceManager interface {
LaunchHealthCheck()
}
// Manager A route/router manager
// Manager A route/router manager.
type Manager struct {
routerHandlers map[string]http.Handler
serviceManager serviceManager
@ -43,7 +43,7 @@ type Manager struct {
conf *runtime.Configuration
}
// NewManager Creates a new Manager
// NewManager Creates a new Manager.
func NewManager(conf *runtime.Configuration,
serviceManager serviceManager,
middlewaresBuilder middlewareBuilder,
@ -68,7 +68,7 @@ func (m *Manager) getHTTPRouters(ctx context.Context, entryPoints []string, tls
return make(map[string]map[string]*runtime.RouterInfo)
}
// BuildHandlers Builds handler for all entry points
// BuildHandlers Builds handler for all entry points.
func (m *Manager) BuildHandlers(rootCtx context.Context, entryPoints []string, tls bool) map[string]http.Handler {
entryPointHandlers := make(map[string]http.Handler)

View file

@ -21,7 +21,7 @@ const (
defaultTLSStoreName = "default"
)
// NewManager Creates a new Manager
// NewManager Creates a new Manager.
func NewManager(conf *runtime.Configuration,
serviceManager *tcpservice.Manager,
httpHandlers map[string]http.Handler,
@ -37,7 +37,7 @@ func NewManager(conf *runtime.Configuration,
}
}
// Manager is a route/router manager
// Manager is a route/router manager.
type Manager struct {
serviceManager *tcpservice.Manager
httpHandlers map[string]http.Handler
@ -62,7 +62,7 @@ func (m *Manager) getHTTPRouters(ctx context.Context, entryPoints []string, tls
return make(map[string]map[string]*runtime.RouterInfo)
}
// BuildHandlers builds the handlers for the given entrypoints
// BuildHandlers builds the handlers for the given entrypoints.
func (m *Manager) BuildHandlers(rootCtx context.Context, entryPoints []string) map[string]*tcp.Router {
entryPointsRouters := m.getTCPRouters(rootCtx, entryPoints)
entryPointsRoutersHTTP := m.getHTTPRouters(rootCtx, entryPoints, true)
@ -117,7 +117,7 @@ func (m *Manager) buildEntryPointHandler(ctx context.Context, configs map[string
domains, err := rules.ParseDomains(routerHTTPConfig.Rule)
if err != nil {
routerErr := fmt.Errorf("invalid rule %s, error: %v", routerHTTPConfig.Rule, err)
routerErr := fmt.Errorf("invalid rule %s, error: %w", routerHTTPConfig.Rule, err)
routerHTTPConfig.AddError(routerErr, true)
logger.Debug(routerErr)
continue

View file

@ -12,7 +12,7 @@ import (
"github.com/containous/traefik/v2/pkg/udp"
)
// NewManager Creates a new Manager
// NewManager Creates a new Manager.
func NewManager(conf *runtime.Configuration,
serviceManager *udpservice.Manager,
) *Manager {
@ -22,7 +22,7 @@ func NewManager(conf *runtime.Configuration,
}
}
// Manager is a route/router manager
// Manager is a route/router manager.
type Manager struct {
serviceManager *udpservice.Manager
conf *runtime.Configuration
@ -36,7 +36,7 @@ func (m *Manager) getUDPRouters(ctx context.Context, entryPoints []string) map[s
return make(map[string]map[string]*runtime.UDPRouterInfo)
}
// BuildHandlers builds the handlers for the given entrypoints
// BuildHandlers builds the handlers for the given entrypoints.
func (m *Manager) BuildHandlers(rootCtx context.Context, entryPoints []string) map[string]udp.Handler {
entryPointsRouters := m.getUDPRouters(rootCtx, entryPoints)

View file

@ -31,7 +31,7 @@ type RouterFactory struct {
tlsManager *tls.Manager
}
// NewRouterFactory creates a new RouterFactory
// NewRouterFactory creates a new RouterFactory.
func NewRouterFactory(staticConfiguration static.Configuration, managerFactory *service.ManagerFactory, tlsManager *tls.Manager, chainBuilder *middleware.ChainBuilder) *RouterFactory {
var entryPointsTCP, entryPointsUDP []string
for name, cfg := range staticConfiguration.EntryPoints {
@ -57,7 +57,7 @@ func NewRouterFactory(staticConfiguration static.Configuration, managerFactory *
}
}
// CreateRouters creates new TCPRouters and UDPRouters
// CreateRouters creates new TCPRouters and UDPRouters.
func (f *RouterFactory) CreateRouters(conf dynamic.Configuration) (map[string]*tcpCore.Router, map[string]udpCore.Handler) {
ctx := context.Background()

View file

@ -13,7 +13,7 @@ import (
"github.com/containous/traefik/v2/pkg/server/middleware"
)
// Server is the reverse-proxy/load-balancer engine
// Server is the reverse-proxy/load-balancer engine.
type Server struct {
watcher *ConfigurationWatcher
tcpEntryPoints TCPEntryPoints
@ -47,7 +47,7 @@ func NewServer(routinesPool *safe.Pool, entryPoints TCPEntryPoints, entryPointsU
return srv
}
// Start starts the server and Stop/Close it when context is Done
// Start starts the server and Stop/Close it when context is Done.
func (s *Server) Start(ctx context.Context) {
go func() {
<-ctx.Done()
@ -69,7 +69,7 @@ func (s *Server) Wait() {
<-s.stopChan
}
// Stop stops the server
// Stop stops the server.
func (s *Server) Stop() {
defer log.WithoutContext().Info("Server stopped")
@ -79,7 +79,7 @@ func (s *Server) Stop() {
s.stopChan <- true
}
// Close destroys the server
// Close destroys the server.
func (s *Server) Close() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)

View file

@ -37,18 +37,18 @@ func newHTTPForwarder(ln net.Listener) *httpForwarder {
}
}
// ServeTCP uses the connection to serve it later in "Accept"
// ServeTCP uses the connection to serve it later in "Accept".
func (h *httpForwarder) ServeTCP(conn tcp.WriteCloser) {
h.connChan <- conn
}
// Accept retrieves a served connection in ServeTCP
// Accept retrieves a served connection in ServeTCP.
func (h *httpForwarder) Accept() (net.Conn, error) {
conn := <-h.connChan
return conn, nil
}
// TCPEntryPoints holds a map of TCPEntryPoint (the entrypoint names being the keys)
// TCPEntryPoints holds a map of TCPEntryPoint (the entrypoint names being the keys).
type TCPEntryPoints map[string]*TCPEntryPoint
// NewTCPEntryPoints creates a new TCPEntryPoints.
@ -57,7 +57,7 @@ func NewTCPEntryPoints(entryPointsConfig static.EntryPoints) (TCPEntryPoints, er
for entryPointName, config := range entryPointsConfig {
protocol, err := config.GetProtocol()
if err != nil {
return nil, fmt.Errorf("error while building entryPoint %s: %v", entryPointName, err)
return nil, fmt.Errorf("error while building entryPoint %s: %w", entryPointName, err)
}
if protocol != "tcp" {
@ -68,7 +68,7 @@ func NewTCPEntryPoints(entryPointsConfig static.EntryPoints) (TCPEntryPoints, er
serverEntryPointsTCP[entryPointName], err = NewTCPEntryPoint(ctx, config)
if err != nil {
return nil, fmt.Errorf("error while building entryPoint %s: %v", entryPointName, err)
return nil, fmt.Errorf("error while building entryPoint %s: %w", entryPointName, err)
}
}
return serverEntryPointsTCP, nil
@ -109,7 +109,7 @@ func (eps TCPEntryPoints) Switch(routersTCP map[string]*tcp.Router) {
}
}
// TCPEntryPoint is the TCP server
// TCPEntryPoint is the TCP server.
type TCPEntryPoint struct {
listener net.Listener
switcher *tcp.HandlerSwitcher
@ -119,27 +119,27 @@ type TCPEntryPoint struct {
httpsServer *httpServer
}
// NewTCPEntryPoint creates a new TCPEntryPoint
// NewTCPEntryPoint creates a new TCPEntryPoint.
func NewTCPEntryPoint(ctx context.Context, configuration *static.EntryPoint) (*TCPEntryPoint, error) {
tracker := newConnectionTracker()
listener, err := buildListener(ctx, configuration)
if err != nil {
return nil, fmt.Errorf("error preparing server: %v", err)
return nil, fmt.Errorf("error preparing server: %w", err)
}
router := &tcp.Router{}
httpServer, err := createHTTPServer(ctx, listener, configuration, true)
if err != nil {
return nil, fmt.Errorf("error preparing httpServer: %v", err)
return nil, fmt.Errorf("error preparing httpServer: %w", err)
}
router.HTTPForwarder(httpServer.Forwarder)
httpsServer, err := createHTTPServer(ctx, listener, configuration, false)
if err != nil {
return nil, fmt.Errorf("error preparing httpsServer: %v", err)
return nil, fmt.Errorf("error preparing httpsServer: %w", err)
}
router.HTTPSForwarder(httpsServer.Forwarder)
@ -201,7 +201,7 @@ func (e *TCPEntryPoint) Start(ctx context.Context) {
}
}
// Shutdown stops the TCP connections
// Shutdown stops the TCP connections.
func (e *TCPEntryPoint) Shutdown(ctx context.Context) {
logger := log.FromContext(ctx)
@ -381,7 +381,7 @@ func buildListener(ctx context.Context, entryPoint *static.EntryPoint) (net.List
listener, err := net.Listen("tcp", entryPoint.GetAddress())
if err != nil {
return nil, fmt.Errorf("error opening listener: %v", err)
return nil, fmt.Errorf("error opening listener: %w", err)
}
listener = tcpKeepAliveListener{listener.(*net.TCPListener)}
@ -389,7 +389,7 @@ func buildListener(ctx context.Context, entryPoint *static.EntryPoint) (net.List
if entryPoint.ProxyProtocol != nil {
listener, err = buildProxyProtocolListener(ctx, entryPoint, listener)
if err != nil {
return nil, fmt.Errorf("error creating proxy protocol listener: %v", err)
return nil, fmt.Errorf("error creating proxy protocol listener: %w", err)
}
}
return listener, nil
@ -406,14 +406,14 @@ type connectionTracker struct {
lock sync.RWMutex
}
// AddConnection add a connection in the tracked connections list
// AddConnection add a connection in the tracked connections list.
func (c *connectionTracker) AddConnection(conn net.Conn) {
c.lock.Lock()
defer c.lock.Unlock()
c.conns[conn] = struct{}{}
}
// RemoveConnection remove a connection from the tracked connections list
// RemoveConnection remove a connection from the tracked connections list.
func (c *connectionTracker) RemoveConnection(conn net.Conn) {
c.lock.Lock()
defer c.lock.Unlock()
@ -426,7 +426,7 @@ func (c *connectionTracker) isEmpty() bool {
return len(c.conns) == 0
}
// Shutdown wait for the connection closing
// Shutdown wait for the connection closing.
func (c *connectionTracker) Shutdown(ctx context.Context) error {
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
@ -442,7 +442,7 @@ func (c *connectionTracker) Shutdown(ctx context.Context) error {
}
}
// Close close all the connections in the tracked connections list
// Close close all the connections in the tracked connections list.
func (c *connectionTracker) Close() {
c.lock.Lock()
defer c.lock.Unlock()

View file

@ -21,7 +21,7 @@ func NewUDPEntryPoints(cfg static.EntryPoints) (UDPEntryPoints, error) {
for entryPointName, entryPoint := range cfg {
protocol, err := entryPoint.GetProtocol()
if err != nil {
return nil, fmt.Errorf("error while building entryPoint %s: %v", entryPointName, err)
return nil, fmt.Errorf("error while building entryPoint %s: %w", entryPointName, err)
}
if protocol != "udp" {
@ -30,7 +30,7 @@ func NewUDPEntryPoints(cfg static.EntryPoints) (UDPEntryPoints, error) {
ep, err := NewUDPEntryPoint(entryPoint)
if err != nil {
return nil, fmt.Errorf("error while building entryPoint %s: %v", entryPointName, err)
return nil, fmt.Errorf("error while building entryPoint %s: %w", entryPointName, err)
}
entryPoints[entryPointName] = ep
}

View file

@ -15,10 +15,10 @@ import (
"github.com/containous/traefik/v2/pkg/types"
)
// StatusClientClosedRequest non-standard HTTP status code for client disconnection
// StatusClientClosedRequest non-standard HTTP status code for client disconnection.
const StatusClientClosedRequest = 499
// StatusClientClosedRequestText non-standard HTTP status for client disconnection
// StatusClientClosedRequestText non-standard HTTP status for client disconnection.
const StatusClientClosedRequestText = "Client Closed Request"
func buildProxy(passHostHeader *bool, responseForwarding *dynamic.ResponseForwarding, defaultRoundTripper http.RoundTripper, bufferPool httputil.BufferPool, responseModifier func(*http.Response) error) (http.Handler, error) {
@ -26,7 +26,7 @@ func buildProxy(passHostHeader *bool, responseForwarding *dynamic.ResponseForwar
if responseForwarding != nil {
err := flushInterval.Set(responseForwarding.FlushInterval)
if err != nil {
return nil, fmt.Errorf("error creating flush interval: %v", err)
return nil, fmt.Errorf("error creating flush interval: %w", err)
}
}
if flushInterval == 0 {

View file

@ -35,7 +35,7 @@ const (
const defaultMaxBodySize int64 = -1
// NewManager creates a new Manager
// NewManager creates a new Manager.
func NewManager(configs map[string]*runtime.ServiceInfo, defaultRoundTripper http.RoundTripper, metricsRegistry metrics.Registry, routinePool *safe.Pool) *Manager {
return &Manager{
routinePool: routinePool,
@ -47,7 +47,7 @@ func NewManager(configs map[string]*runtime.ServiceInfo, defaultRoundTripper htt
}
}
// Manager The service manager
// Manager The service manager.
type Manager struct {
routinePool *safe.Pool
metricsRegistry metrics.Registry
@ -314,7 +314,7 @@ func (m *Manager) getLoadBalancer(ctx context.Context, serviceName string, servi
lbsu := healthcheck.NewLBStatusUpdater(lb, m.configs[serviceName])
if err := m.upsertServers(ctx, lbsu, service.Servers); err != nil {
return nil, fmt.Errorf("error configuring load balancer for service %s: %v", serviceName, err)
return nil, fmt.Errorf("error configuring load balancer for service %s: %w", serviceName, err)
}
return lbsu, nil
@ -326,13 +326,13 @@ func (m *Manager) upsertServers(ctx context.Context, lb healthcheck.BalancerHand
for name, srv := range servers {
u, err := url.Parse(srv.URL)
if err != nil {
return fmt.Errorf("error parsing server URL %s: %v", srv.URL, err)
return fmt.Errorf("error parsing server URL %s: %w", srv.URL, err)
}
logger.WithField(log.ServerName, name).Debugf("Creating server %d %s", name, u)
if err := lb.UpsertServer(u, roundrobin.Weight(1)); err != nil {
return fmt.Errorf("error adding server %s to load balancer: %v", srv.URL, err)
return fmt.Errorf("error adding server %s to load balancer: %w", srv.URL, err)
}
// FIXME Handle Metrics

Some files were not shown because too many files have changed in this diff Show more