Extract some code in packages
- This will help split stuff in smaller, better tested packages - This moves some stuff like the traefik command to package `cmd` Signed-off-by: Vincent Demeester <vincent@sbr.pm>
This commit is contained in:
parent
9c9015a7b1
commit
7fcb7b86d3
12 changed files with 41 additions and 40 deletions
31
server/adapters.go
Normal file
31
server/adapters.go
Normal file
|
@ -0,0 +1,31 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/containous/traefik/log"
|
||||
)
|
||||
|
||||
// OxyLogger implements oxy Logger interface with logrus.
|
||||
type OxyLogger struct {
|
||||
}
|
||||
|
||||
// Infof logs specified string as Debug level in logrus.
|
||||
func (oxylogger *OxyLogger) Infof(format string, args ...interface{}) {
|
||||
log.Debugf(format, args...)
|
||||
}
|
||||
|
||||
// Warningf logs specified string as Warning level in logrus.
|
||||
func (oxylogger *OxyLogger) Warningf(format string, args ...interface{}) {
|
||||
log.Warningf(format, args...)
|
||||
}
|
||||
|
||||
// Errorf logs specified string as Warningf level in logrus.
|
||||
func (oxylogger *OxyLogger) Errorf(format string, args ...interface{}) {
|
||||
log.Warningf(format, args...)
|
||||
}
|
||||
|
||||
func notFoundHandler(w http.ResponseWriter, r *http.Request) {
|
||||
http.NotFound(w, r)
|
||||
//templatesRenderer.HTML(w, http.StatusNotFound, "notFound", nil)
|
||||
}
|
493
server/configuration.go
Normal file
493
server/configuration.go
Normal file
|
@ -0,0 +1,493 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/containous/flaeg"
|
||||
"github.com/containous/traefik/acme"
|
||||
"github.com/containous/traefik/provider/boltdb"
|
||||
"github.com/containous/traefik/provider/consul"
|
||||
"github.com/containous/traefik/provider/docker"
|
||||
"github.com/containous/traefik/provider/dynamodb"
|
||||
"github.com/containous/traefik/provider/ecs"
|
||||
"github.com/containous/traefik/provider/etcd"
|
||||
"github.com/containous/traefik/provider/eureka"
|
||||
"github.com/containous/traefik/provider/file"
|
||||
"github.com/containous/traefik/provider/kubernetes"
|
||||
"github.com/containous/traefik/provider/marathon"
|
||||
"github.com/containous/traefik/provider/mesos"
|
||||
"github.com/containous/traefik/provider/rancher"
|
||||
"github.com/containous/traefik/provider/zk"
|
||||
"github.com/containous/traefik/types"
|
||||
)
|
||||
|
||||
// TraefikConfiguration holds GlobalConfiguration and other stuff
|
||||
type TraefikConfiguration struct {
|
||||
GlobalConfiguration `mapstructure:",squash"`
|
||||
ConfigFile string `short:"c" description:"Configuration file to use (TOML)."`
|
||||
}
|
||||
|
||||
// GlobalConfiguration holds global configuration (with providers, etc.).
|
||||
// It's populated from the traefik configuration file passed as an argument to the binary.
|
||||
type GlobalConfiguration struct {
|
||||
GraceTimeOut flaeg.Duration `short:"g" description:"Duration to give active requests a chance to finish during hot-reload"`
|
||||
Debug bool `short:"d" description:"Enable debug mode"`
|
||||
CheckNewVersion bool `description:"Periodically check if a new version has been released"`
|
||||
AccessLogsFile string `description:"Access logs file"`
|
||||
TraefikLogsFile string `description:"Traefik logs file"`
|
||||
LogLevel string `short:"l" description:"Log level"`
|
||||
EntryPoints EntryPoints `description:"Entrypoints definition using format: --entryPoints='Name:http Address::8000 Redirect.EntryPoint:https' --entryPoints='Name:https Address::4442 TLS:tests/traefik.crt,tests/traefik.key;prod/traefik.crt,prod/traefik.key'"`
|
||||
Cluster *types.Cluster `description:"Enable clustering"`
|
||||
Constraints types.Constraints `description:"Filter services by constraint, matching with service tags"`
|
||||
ACME *acme.ACME `description:"Enable ACME (Let's Encrypt): automatic SSL"`
|
||||
DefaultEntryPoints DefaultEntryPoints `description:"Entrypoints to be used by frontends that do not specify any entrypoint"`
|
||||
ProvidersThrottleDuration flaeg.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."`
|
||||
MaxIdleConnsPerHost int `description:"If non-zero, controls the maximum idle (keep-alive) to keep per-host. If zero, DefaultMaxIdleConnsPerHost is used"`
|
||||
IdleTimeout flaeg.Duration `description:"maximum amount of time an idle (keep-alive) connection will remain idle before closing itself."`
|
||||
InsecureSkipVerify bool `description:"Disable SSL certificate verification"`
|
||||
Retry *Retry `description:"Enable retry sending request if network error"`
|
||||
Docker *docker.Provider `description:"Enable Docker backend"`
|
||||
File *file.Provider `description:"Enable File backend"`
|
||||
Web *WebProvider `description:"Enable Web backend"`
|
||||
Marathon *marathon.Provider `description:"Enable Marathon backend"`
|
||||
Consul *consul.Provider `description:"Enable Consul backend"`
|
||||
ConsulCatalog *consul.CatalogProvider `description:"Enable Consul catalog backend"`
|
||||
Etcd *etcd.Provider `description:"Enable Etcd backend"`
|
||||
Zookeeper *zk.Provider `description:"Enable Zookeeper backend"`
|
||||
Boltdb *boltdb.Provider `description:"Enable Boltdb backend"`
|
||||
Kubernetes *kubernetes.Provider `description:"Enable Kubernetes backend"`
|
||||
Mesos *mesos.Provider `description:"Enable Mesos backend"`
|
||||
Eureka *eureka.Provider `description:"Enable Eureka backend"`
|
||||
ECS *ecs.Provider `description:"Enable ECS backend"`
|
||||
Rancher *rancher.Provider `description:"Enable Rancher backend"`
|
||||
DynamoDB *dynamodb.Provider `description:"Enable DynamoDB backend"`
|
||||
}
|
||||
|
||||
// DefaultEntryPoints holds default entry points
|
||||
type DefaultEntryPoints []string
|
||||
|
||||
// String is the method to format the flag's value, part of the flag.Value interface.
|
||||
// The String method's output will be used in diagnostics.
|
||||
func (dep *DefaultEntryPoints) String() string {
|
||||
return strings.Join(*dep, ",")
|
||||
}
|
||||
|
||||
// Set is the method to set the flag value, part of the flag.Value interface.
|
||||
// Set's argument is a string to be parsed to set the flag.
|
||||
// It's a comma-separated list, so we split it.
|
||||
func (dep *DefaultEntryPoints) Set(value string) error {
|
||||
entrypoints := strings.Split(value, ",")
|
||||
if len(entrypoints) == 0 {
|
||||
return errors.New("Bad DefaultEntryPoints format: " + value)
|
||||
}
|
||||
for _, entrypoint := range entrypoints {
|
||||
*dep = append(*dep, entrypoint)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get return the EntryPoints map
|
||||
func (dep *DefaultEntryPoints) Get() interface{} {
|
||||
return DefaultEntryPoints(*dep)
|
||||
}
|
||||
|
||||
// SetValue sets the EntryPoints map with val
|
||||
func (dep *DefaultEntryPoints) SetValue(val interface{}) {
|
||||
*dep = DefaultEntryPoints(val.(DefaultEntryPoints))
|
||||
}
|
||||
|
||||
// Type is type of the struct
|
||||
func (dep *DefaultEntryPoints) Type() string {
|
||||
return fmt.Sprint("defaultentrypoints")
|
||||
}
|
||||
|
||||
// EntryPoints holds entry points configuration of the reverse proxy (ip, port, TLS...)
|
||||
type EntryPoints map[string]*EntryPoint
|
||||
|
||||
// String is the method to format the flag's value, part of the flag.Value interface.
|
||||
// The String method's output will be used in diagnostics.
|
||||
func (ep *EntryPoints) String() string {
|
||||
return fmt.Sprintf("%+v", *ep)
|
||||
}
|
||||
|
||||
// Set is the method to set the flag value, part of the flag.Value interface.
|
||||
// Set's argument is a string to be parsed to set the flag.
|
||||
// It's a comma-separated list, so we split it.
|
||||
func (ep *EntryPoints) Set(value string) error {
|
||||
regex := regexp.MustCompile("(?:Name:(?P<Name>\\S*))\\s*(?:Address:(?P<Address>\\S*))?\\s*(?:TLS:(?P<TLS>\\S*))?\\s*((?P<TLSACME>TLS))?\\s*(?:CA:(?P<CA>\\S*))?\\s*(?:Redirect.EntryPoint:(?P<RedirectEntryPoint>\\S*))?\\s*(?:Redirect.Regex:(?P<RedirectRegex>\\S*))?\\s*(?:Redirect.Replacement:(?P<RedirectReplacement>\\S*))?\\s*(?:Compress:(?P<Compress>\\S*))?")
|
||||
match := regex.FindAllStringSubmatch(value, -1)
|
||||
if match == nil {
|
||||
return errors.New("Bad EntryPoints format: " + value)
|
||||
}
|
||||
matchResult := match[0]
|
||||
result := make(map[string]string)
|
||||
for i, name := range regex.SubexpNames() {
|
||||
if i != 0 {
|
||||
result[name] = matchResult[i]
|
||||
}
|
||||
}
|
||||
var tls *TLS
|
||||
if len(result["TLS"]) > 0 {
|
||||
certs := Certificates{}
|
||||
if err := certs.Set(result["TLS"]); err != nil {
|
||||
return err
|
||||
}
|
||||
tls = &TLS{
|
||||
Certificates: certs,
|
||||
}
|
||||
} else if len(result["TLSACME"]) > 0 {
|
||||
tls = &TLS{
|
||||
Certificates: Certificates{},
|
||||
}
|
||||
}
|
||||
if len(result["CA"]) > 0 {
|
||||
files := strings.Split(result["CA"], ",")
|
||||
tls.ClientCAFiles = files
|
||||
}
|
||||
var redirect *Redirect
|
||||
if len(result["RedirectEntryPoint"]) > 0 || len(result["RedirectRegex"]) > 0 || len(result["RedirectReplacement"]) > 0 {
|
||||
redirect = &Redirect{
|
||||
EntryPoint: result["RedirectEntryPoint"],
|
||||
Regex: result["RedirectRegex"],
|
||||
Replacement: result["RedirectReplacement"],
|
||||
}
|
||||
}
|
||||
|
||||
compress := false
|
||||
if len(result["Compress"]) > 0 {
|
||||
compress = strings.EqualFold(result["Compress"], "enable") || strings.EqualFold(result["Compress"], "on")
|
||||
}
|
||||
|
||||
(*ep)[result["Name"]] = &EntryPoint{
|
||||
Address: result["Address"],
|
||||
TLS: tls,
|
||||
Redirect: redirect,
|
||||
Compress: compress,
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Get return the EntryPoints map
|
||||
func (ep *EntryPoints) Get() interface{} {
|
||||
return EntryPoints(*ep)
|
||||
}
|
||||
|
||||
// SetValue sets the EntryPoints map with val
|
||||
func (ep *EntryPoints) SetValue(val interface{}) {
|
||||
*ep = EntryPoints(val.(EntryPoints))
|
||||
}
|
||||
|
||||
// Type is type of the struct
|
||||
func (ep *EntryPoints) Type() string {
|
||||
return fmt.Sprint("entrypoints")
|
||||
}
|
||||
|
||||
// EntryPoint holds an entry point configuration of the reverse proxy (ip, port, TLS...)
|
||||
type EntryPoint struct {
|
||||
Network string
|
||||
Address string
|
||||
TLS *TLS
|
||||
Redirect *Redirect
|
||||
Auth *types.Auth
|
||||
Compress bool
|
||||
}
|
||||
|
||||
// Redirect configures a redirection of an entry point to another, or to an URL
|
||||
type Redirect struct {
|
||||
EntryPoint string
|
||||
Regex string
|
||||
Replacement string
|
||||
}
|
||||
|
||||
// TLS configures TLS for an entry point
|
||||
type TLS struct {
|
||||
MinVersion string
|
||||
CipherSuites []string
|
||||
Certificates Certificates
|
||||
ClientCAFiles []string
|
||||
}
|
||||
|
||||
// Map of allowed TLS minimum versions
|
||||
var minVersion = map[string]uint16{
|
||||
`VersionTLS10`: tls.VersionTLS10,
|
||||
`VersionTLS11`: tls.VersionTLS11,
|
||||
`VersionTLS12`: tls.VersionTLS12,
|
||||
}
|
||||
|
||||
// Map of TLS CipherSuites from crypto/tls
|
||||
// Available CipherSuites defined at https://golang.org/pkg/crypto/tls/#pkg-constants
|
||||
var cipherSuites = map[string]uint16{
|
||||
`TLS_RSA_WITH_RC4_128_SHA`: tls.TLS_RSA_WITH_RC4_128_SHA,
|
||||
`TLS_RSA_WITH_3DES_EDE_CBC_SHA`: tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
|
||||
`TLS_RSA_WITH_AES_128_CBC_SHA`: tls.TLS_RSA_WITH_AES_128_CBC_SHA,
|
||||
`TLS_RSA_WITH_AES_256_CBC_SHA`: tls.TLS_RSA_WITH_AES_256_CBC_SHA,
|
||||
`TLS_RSA_WITH_AES_128_CBC_SHA256`: tls.TLS_RSA_WITH_AES_128_CBC_SHA256,
|
||||
`TLS_RSA_WITH_AES_128_GCM_SHA256`: tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
|
||||
`TLS_RSA_WITH_AES_256_GCM_SHA384`: tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
|
||||
`TLS_ECDHE_ECDSA_WITH_RC4_128_SHA`: tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
|
||||
`TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA`: tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
|
||||
`TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA`: tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
|
||||
`TLS_ECDHE_RSA_WITH_RC4_128_SHA`: tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
|
||||
`TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA`: tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
|
||||
`TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA`: tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
|
||||
`TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA`: tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
|
||||
`TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256`: tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
|
||||
`TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256`: tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
|
||||
`TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`: tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
|
||||
`TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`: tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
|
||||
`TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`: tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
|
||||
`TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384`: tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
|
||||
`TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305`: tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
|
||||
`TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305`: tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
|
||||
}
|
||||
|
||||
// Certificates defines traefik certificates type
|
||||
// Certs and Keys could be either a file path, or the file content itself
|
||||
type Certificates []Certificate
|
||||
|
||||
//CreateTLSConfig creates a TLS config from Certificate structures
|
||||
func (certs *Certificates) CreateTLSConfig() (*tls.Config, error) {
|
||||
config := &tls.Config{}
|
||||
config.Certificates = []tls.Certificate{}
|
||||
certsSlice := []Certificate(*certs)
|
||||
for _, v := range certsSlice {
|
||||
isAPath := false
|
||||
_, errCert := os.Stat(v.CertFile)
|
||||
_, errKey := os.Stat(v.KeyFile)
|
||||
if errCert == nil {
|
||||
if errKey == nil {
|
||||
isAPath = true
|
||||
} else {
|
||||
return nil, fmt.Errorf("bad TLS Certificate KeyFile format, expected a path")
|
||||
}
|
||||
} else if errKey == nil {
|
||||
return nil, fmt.Errorf("bad TLS Certificate KeyFile format, expected a path")
|
||||
}
|
||||
|
||||
cert := tls.Certificate{}
|
||||
var err error
|
||||
if isAPath {
|
||||
cert, err = tls.LoadX509KeyPair(v.CertFile, v.KeyFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
cert, err = tls.X509KeyPair([]byte(v.CertFile), []byte(v.KeyFile))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
config.Certificates = append(config.Certificates, cert)
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// String is the method to format the flag's value, part of the flag.Value interface.
|
||||
// The String method's output will be used in diagnostics.
|
||||
func (certs *Certificates) String() string {
|
||||
if len(*certs) == 0 {
|
||||
return ""
|
||||
}
|
||||
var result []string
|
||||
for _, certificate := range *certs {
|
||||
result = append(result, certificate.CertFile+","+certificate.KeyFile)
|
||||
}
|
||||
return strings.Join(result, ";")
|
||||
}
|
||||
|
||||
// Set is the method to set the flag value, part of the flag.Value interface.
|
||||
// Set's argument is a string to be parsed to set the flag.
|
||||
// It's a comma-separated list, so we split it.
|
||||
func (certs *Certificates) Set(value string) error {
|
||||
certificates := strings.Split(value, ";")
|
||||
for _, certificate := range certificates {
|
||||
files := strings.Split(certificate, ",")
|
||||
if len(files) != 2 {
|
||||
return errors.New("Bad certificates format: " + value)
|
||||
}
|
||||
*certs = append(*certs, Certificate{
|
||||
CertFile: files[0],
|
||||
KeyFile: files[1],
|
||||
})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Type is type of the struct
|
||||
func (certs *Certificates) Type() string {
|
||||
return fmt.Sprint("certificates")
|
||||
}
|
||||
|
||||
// Certificate holds a SSL cert/key pair
|
||||
// Certs and Key could be either a file path, or the file content itself
|
||||
type Certificate struct {
|
||||
CertFile string
|
||||
KeyFile string
|
||||
}
|
||||
|
||||
// Retry contains request retry config
|
||||
type Retry struct {
|
||||
Attempts int `description:"Number of attempts"`
|
||||
}
|
||||
|
||||
// NewTraefikDefaultPointersConfiguration creates a TraefikConfiguration with pointers default values
|
||||
func NewTraefikDefaultPointersConfiguration() *TraefikConfiguration {
|
||||
//default Docker
|
||||
var defaultDocker docker.Provider
|
||||
defaultDocker.Watch = true
|
||||
defaultDocker.ExposedByDefault = true
|
||||
defaultDocker.Endpoint = "unix:///var/run/docker.sock"
|
||||
defaultDocker.SwarmMode = false
|
||||
|
||||
// default File
|
||||
var defaultFile file.Provider
|
||||
defaultFile.Watch = true
|
||||
defaultFile.Filename = "" //needs equivalent to viper.ConfigFileUsed()
|
||||
|
||||
// default Web
|
||||
var defaultWeb WebProvider
|
||||
defaultWeb.Address = ":8080"
|
||||
defaultWeb.Statistics = &types.Statistics{
|
||||
RecentErrors: 10,
|
||||
}
|
||||
|
||||
// default Metrics
|
||||
defaultWeb.Metrics = &types.Metrics{
|
||||
Prometheus: &types.Prometheus{
|
||||
Buckets: types.Buckets{0.1, 0.3, 1.2, 5},
|
||||
},
|
||||
}
|
||||
|
||||
// default Marathon
|
||||
var defaultMarathon marathon.Provider
|
||||
defaultMarathon.Watch = true
|
||||
defaultMarathon.Endpoint = "http://127.0.0.1:8080"
|
||||
defaultMarathon.ExposedByDefault = true
|
||||
defaultMarathon.Constraints = types.Constraints{}
|
||||
defaultMarathon.DialerTimeout = flaeg.Duration(60 * time.Second)
|
||||
defaultMarathon.KeepAlive = flaeg.Duration(10 * time.Second)
|
||||
|
||||
// default Consul
|
||||
var defaultConsul consul.Provider
|
||||
defaultConsul.Watch = true
|
||||
defaultConsul.Endpoint = "127.0.0.1:8500"
|
||||
defaultConsul.Prefix = "traefik"
|
||||
defaultConsul.Constraints = types.Constraints{}
|
||||
|
||||
// default CatalogProvider
|
||||
var defaultConsulCatalog consul.CatalogProvider
|
||||
defaultConsulCatalog.Endpoint = "127.0.0.1:8500"
|
||||
defaultConsulCatalog.Constraints = types.Constraints{}
|
||||
|
||||
// default Etcd
|
||||
var defaultEtcd etcd.Provider
|
||||
defaultEtcd.Watch = true
|
||||
defaultEtcd.Endpoint = "127.0.0.1:2379"
|
||||
defaultEtcd.Prefix = "/traefik"
|
||||
defaultEtcd.Constraints = types.Constraints{}
|
||||
|
||||
//default Zookeeper
|
||||
var defaultZookeeper zk.Provider
|
||||
defaultZookeeper.Watch = true
|
||||
defaultZookeeper.Endpoint = "127.0.0.1:2181"
|
||||
defaultZookeeper.Prefix = "/traefik"
|
||||
defaultZookeeper.Constraints = types.Constraints{}
|
||||
|
||||
//default Boltdb
|
||||
var defaultBoltDb boltdb.Provider
|
||||
defaultBoltDb.Watch = true
|
||||
defaultBoltDb.Endpoint = "127.0.0.1:4001"
|
||||
defaultBoltDb.Prefix = "/traefik"
|
||||
defaultBoltDb.Constraints = types.Constraints{}
|
||||
|
||||
//default Provider
|
||||
var defaultKubernetes kubernetes.Provider
|
||||
defaultKubernetes.Watch = true
|
||||
defaultKubernetes.Endpoint = ""
|
||||
defaultKubernetes.LabelSelector = ""
|
||||
defaultKubernetes.Constraints = types.Constraints{}
|
||||
|
||||
// default Mesos
|
||||
var defaultMesos mesos.Provider
|
||||
defaultMesos.Watch = true
|
||||
defaultMesos.Endpoint = "http://127.0.0.1:5050"
|
||||
defaultMesos.ExposedByDefault = true
|
||||
defaultMesos.Constraints = types.Constraints{}
|
||||
defaultMesos.RefreshSeconds = 30
|
||||
defaultMesos.ZkDetectionTimeout = 30
|
||||
defaultMesos.StateTimeoutSecond = 30
|
||||
|
||||
//default ECS
|
||||
var defaultECS ecs.Provider
|
||||
defaultECS.Watch = true
|
||||
defaultECS.ExposedByDefault = true
|
||||
defaultECS.RefreshSeconds = 15
|
||||
defaultECS.Cluster = "default"
|
||||
defaultECS.Constraints = types.Constraints{}
|
||||
|
||||
//default Rancher
|
||||
var defaultRancher rancher.Provider
|
||||
defaultRancher.Watch = true
|
||||
defaultRancher.ExposedByDefault = true
|
||||
|
||||
// default DynamoDB
|
||||
var defaultDynamoDB dynamodb.Provider
|
||||
defaultDynamoDB.Constraints = types.Constraints{}
|
||||
defaultDynamoDB.RefreshSeconds = 15
|
||||
defaultDynamoDB.TableName = "traefik"
|
||||
defaultDynamoDB.Watch = true
|
||||
|
||||
defaultConfiguration := GlobalConfiguration{
|
||||
Docker: &defaultDocker,
|
||||
File: &defaultFile,
|
||||
Web: &defaultWeb,
|
||||
Marathon: &defaultMarathon,
|
||||
Consul: &defaultConsul,
|
||||
ConsulCatalog: &defaultConsulCatalog,
|
||||
Etcd: &defaultEtcd,
|
||||
Zookeeper: &defaultZookeeper,
|
||||
Boltdb: &defaultBoltDb,
|
||||
Kubernetes: &defaultKubernetes,
|
||||
Mesos: &defaultMesos,
|
||||
ECS: &defaultECS,
|
||||
Rancher: &defaultRancher,
|
||||
DynamoDB: &defaultDynamoDB,
|
||||
Retry: &Retry{},
|
||||
}
|
||||
|
||||
//default Rancher
|
||||
//@TODO: ADD
|
||||
|
||||
return &TraefikConfiguration{
|
||||
GlobalConfiguration: defaultConfiguration,
|
||||
}
|
||||
}
|
||||
|
||||
// NewTraefikConfiguration creates a TraefikConfiguration with default values
|
||||
func NewTraefikConfiguration() *TraefikConfiguration {
|
||||
return &TraefikConfiguration{
|
||||
GlobalConfiguration: GlobalConfiguration{
|
||||
GraceTimeOut: flaeg.Duration(10 * time.Second),
|
||||
AccessLogsFile: "",
|
||||
TraefikLogsFile: "",
|
||||
LogLevel: "ERROR",
|
||||
EntryPoints: map[string]*EntryPoint{},
|
||||
Constraints: types.Constraints{},
|
||||
DefaultEntryPoints: []string{},
|
||||
ProvidersThrottleDuration: flaeg.Duration(2 * time.Second),
|
||||
MaxIdleConnsPerHost: 200,
|
||||
IdleTimeout: flaeg.Duration(180 * time.Second),
|
||||
CheckNewVersion: true,
|
||||
},
|
||||
ConfigFile: "",
|
||||
}
|
||||
}
|
||||
|
||||
type configs map[string]*types.Configuration
|
211
server/rules.go
Normal file
211
server/rules.go
Normal file
|
@ -0,0 +1,211 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/BurntSushi/ty/fun"
|
||||
"github.com/containous/mux"
|
||||
"github.com/containous/traefik/types"
|
||||
)
|
||||
|
||||
// Rules holds rule parsing and configuration
|
||||
type Rules struct {
|
||||
route *serverRoute
|
||||
err error
|
||||
}
|
||||
|
||||
func (r *Rules) host(hosts ...string) *mux.Route {
|
||||
return r.route.route.MatcherFunc(func(req *http.Request, route *mux.RouteMatch) bool {
|
||||
reqHost, _, err := net.SplitHostPort(req.Host)
|
||||
if err != nil {
|
||||
reqHost = req.Host
|
||||
}
|
||||
for _, host := range hosts {
|
||||
if types.CanonicalDomain(reqHost) == types.CanonicalDomain(host) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Rules) hostRegexp(hosts ...string) *mux.Route {
|
||||
router := r.route.route.Subrouter()
|
||||
for _, host := range hosts {
|
||||
router.Host(types.CanonicalDomain(host))
|
||||
}
|
||||
return r.route.route
|
||||
}
|
||||
|
||||
func (r *Rules) path(paths ...string) *mux.Route {
|
||||
router := r.route.route.Subrouter()
|
||||
for _, path := range paths {
|
||||
router.Path(strings.TrimSpace(path))
|
||||
}
|
||||
return r.route.route
|
||||
}
|
||||
|
||||
func (r *Rules) pathPrefix(paths ...string) *mux.Route {
|
||||
router := r.route.route.Subrouter()
|
||||
for _, path := range paths {
|
||||
router.PathPrefix(strings.TrimSpace(path))
|
||||
}
|
||||
return r.route.route
|
||||
}
|
||||
|
||||
type bySize []string
|
||||
|
||||
func (a bySize) Len() int { return len(a) }
|
||||
func (a bySize) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
|
||||
func (a bySize) Less(i, j int) bool { return len(a[i]) > len(a[j]) }
|
||||
|
||||
func (r *Rules) pathStrip(paths ...string) *mux.Route {
|
||||
sort.Sort(bySize(paths))
|
||||
r.route.stripPrefixes = paths
|
||||
router := r.route.route.Subrouter()
|
||||
for _, path := range paths {
|
||||
router.Path(strings.TrimSpace(path))
|
||||
}
|
||||
return r.route.route
|
||||
}
|
||||
|
||||
func (r *Rules) addPrefix(paths ...string) *mux.Route {
|
||||
for _, path := range paths {
|
||||
r.route.addPrefix = path
|
||||
}
|
||||
return r.route.route
|
||||
}
|
||||
|
||||
func (r *Rules) pathPrefixStrip(paths ...string) *mux.Route {
|
||||
sort.Sort(bySize(paths))
|
||||
r.route.stripPrefixes = paths
|
||||
router := r.route.route.Subrouter()
|
||||
for _, path := range paths {
|
||||
router.PathPrefix(strings.TrimSpace(path))
|
||||
}
|
||||
return r.route.route
|
||||
}
|
||||
|
||||
func (r *Rules) methods(methods ...string) *mux.Route {
|
||||
return r.route.route.Methods(methods...)
|
||||
}
|
||||
|
||||
func (r *Rules) headers(headers ...string) *mux.Route {
|
||||
return r.route.route.Headers(headers...)
|
||||
}
|
||||
|
||||
func (r *Rules) headersRegexp(headers ...string) *mux.Route {
|
||||
return r.route.route.HeadersRegexp(headers...)
|
||||
}
|
||||
|
||||
func (r *Rules) parseRules(expression string, onRule func(functionName string, function interface{}, arguments []string) error) error {
|
||||
functions := map[string]interface{}{
|
||||
"Host": r.host,
|
||||
"HostRegexp": r.hostRegexp,
|
||||
"Path": r.path,
|
||||
"PathStrip": r.pathStrip,
|
||||
"PathPrefix": r.pathPrefix,
|
||||
"PathPrefixStrip": r.pathPrefixStrip,
|
||||
"Method": r.methods,
|
||||
"Headers": r.headers,
|
||||
"HeadersRegexp": r.headersRegexp,
|
||||
"AddPrefix": r.addPrefix,
|
||||
}
|
||||
|
||||
if len(expression) == 0 {
|
||||
return errors.New("Empty rule")
|
||||
}
|
||||
|
||||
f := func(c rune) bool {
|
||||
return c == ':'
|
||||
}
|
||||
|
||||
// Allow multiple rules separated by ;
|
||||
splitRule := func(c rune) bool {
|
||||
return c == ';'
|
||||
}
|
||||
|
||||
parsedRules := strings.FieldsFunc(expression, splitRule)
|
||||
|
||||
for _, rule := range parsedRules {
|
||||
// get function
|
||||
parsedFunctions := strings.FieldsFunc(rule, f)
|
||||
if len(parsedFunctions) == 0 {
|
||||
return errors.New("Error parsing rule: '" + rule + "'")
|
||||
}
|
||||
functionName := strings.TrimSpace(parsedFunctions[0])
|
||||
parsedFunction, ok := functions[functionName]
|
||||
if !ok {
|
||||
return errors.New("Error parsing rule: '" + rule + "'. Unknown function: '" + parsedFunctions[0] + "'")
|
||||
}
|
||||
parsedFunctions = append(parsedFunctions[:0], parsedFunctions[1:]...)
|
||||
fargs := func(c rune) bool {
|
||||
return c == ','
|
||||
}
|
||||
// get function
|
||||
parsedArgs := strings.FieldsFunc(strings.Join(parsedFunctions, ":"), fargs)
|
||||
if len(parsedArgs) == 0 {
|
||||
return errors.New("Error parsing args from rule: '" + rule + "'")
|
||||
}
|
||||
|
||||
for i := range parsedArgs {
|
||||
parsedArgs[i] = strings.TrimSpace(parsedArgs[i])
|
||||
}
|
||||
|
||||
err := onRule(functionName, parsedFunction, parsedArgs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Parsing error on rule: %v", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Parse parses rules expressions
|
||||
func (r *Rules) Parse(expression string) (*mux.Route, error) {
|
||||
var resultRoute *mux.Route
|
||||
err := r.parseRules(expression, func(functionName string, function interface{}, arguments []string) error {
|
||||
inputs := make([]reflect.Value, len(arguments))
|
||||
for i := range arguments {
|
||||
inputs[i] = reflect.ValueOf(arguments[i])
|
||||
}
|
||||
method := reflect.ValueOf(function)
|
||||
if method.IsValid() {
|
||||
resultRoute = method.Call(inputs)[0].Interface().(*mux.Route)
|
||||
if r.err != nil {
|
||||
return r.err
|
||||
}
|
||||
if resultRoute.GetError() != nil {
|
||||
return resultRoute.GetError()
|
||||
}
|
||||
|
||||
} else {
|
||||
return errors.New("Method not found: '" + functionName + "'")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Error parsing rule: %v", err)
|
||||
}
|
||||
return resultRoute, nil
|
||||
}
|
||||
|
||||
// ParseDomains parses rules expressions and returns domains
|
||||
func (r *Rules) ParseDomains(expression string) ([]string, error) {
|
||||
domains := []string{}
|
||||
err := r.parseRules(expression, func(functionName string, function interface{}, arguments []string) error {
|
||||
if functionName == "Host" {
|
||||
domains = append(domains, arguments...)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Error parsing domains: %v", err)
|
||||
}
|
||||
return fun.Map(types.CanonicalDomain, domains).([]string), nil
|
||||
}
|
165
server/rules_test.go
Normal file
165
server/rules_test.go
Normal file
|
@ -0,0 +1,165 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/containous/mux"
|
||||
)
|
||||
|
||||
func TestParseOneRule(t *testing.T) {
|
||||
router := mux.NewRouter()
|
||||
route := router.NewRoute()
|
||||
serverRoute := &serverRoute{route: route}
|
||||
rules := &Rules{route: serverRoute}
|
||||
|
||||
expression := "Host:foo.bar"
|
||||
routeResult, err := rules.Parse(expression)
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Error while building route for Host:foo.bar")
|
||||
}
|
||||
|
||||
request, err := http.NewRequest("GET", "http://foo.bar", nil)
|
||||
routeMatch := routeResult.Match(request, &mux.RouteMatch{Route: routeResult})
|
||||
|
||||
if routeMatch == false {
|
||||
t.Log(err)
|
||||
t.Fatal("Rule Host:foo.bar don't match")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTwoRules(t *testing.T) {
|
||||
router := mux.NewRouter()
|
||||
route := router.NewRoute()
|
||||
serverRoute := &serverRoute{route: route}
|
||||
rules := &Rules{route: serverRoute}
|
||||
|
||||
expression := "Host: Foo.Bar ; Path:/FOObar"
|
||||
routeResult, err := rules.Parse(expression)
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("Error while building route for Host:foo.bar;Path:/FOObar")
|
||||
}
|
||||
|
||||
request, err := http.NewRequest("GET", "http://foo.bar/foobar", nil)
|
||||
routeMatch := routeResult.Match(request, &mux.RouteMatch{Route: routeResult})
|
||||
|
||||
if routeMatch == true {
|
||||
t.Log(err)
|
||||
t.Fatal("Rule Host:foo.bar;Path:/FOObar don't match")
|
||||
}
|
||||
|
||||
request, err = http.NewRequest("GET", "http://foo.bar/FOObar", nil)
|
||||
routeMatch = routeResult.Match(request, &mux.RouteMatch{Route: routeResult})
|
||||
|
||||
if routeMatch == false {
|
||||
t.Log(err)
|
||||
t.Fatal("Rule Host:foo.bar;Path:/FOObar don't match")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDomains(t *testing.T) {
|
||||
rules := &Rules{}
|
||||
expressionsSlice := []string{
|
||||
"Host:foo.bar,test.bar",
|
||||
"Path:/test",
|
||||
"Host:foo.bar;Path:/test",
|
||||
"Host: Foo.Bar ;Path:/test",
|
||||
}
|
||||
domainsSlice := [][]string{
|
||||
{"foo.bar", "test.bar"},
|
||||
{},
|
||||
{"foo.bar"},
|
||||
{"foo.bar"},
|
||||
}
|
||||
for i, expression := range expressionsSlice {
|
||||
domains, err := rules.ParseDomains(expression)
|
||||
if err != nil {
|
||||
t.Fatalf("Error while parsing domains: %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(domains, domainsSlice[i]) {
|
||||
t.Fatalf("Error parsing domains: expected %+v, got %+v", domainsSlice[i], domains)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPriorites(t *testing.T) {
|
||||
router := mux.NewRouter()
|
||||
router.StrictSlash(true)
|
||||
rules := &Rules{route: &serverRoute{route: router.NewRoute()}}
|
||||
routeFoo, err := rules.Parse("PathPrefix:/foo")
|
||||
if err != nil {
|
||||
t.Fatal("Error while building route for PathPrefix:/foo")
|
||||
}
|
||||
fooHandler := &fakeHandler{name: "fooHandler"}
|
||||
routeFoo.Handler(fooHandler)
|
||||
|
||||
if !router.Match(&http.Request{URL: &url.URL{
|
||||
Path: "/foo",
|
||||
}}, &mux.RouteMatch{}) {
|
||||
t.Fatalf("Error matching route")
|
||||
}
|
||||
|
||||
if router.Match(&http.Request{URL: &url.URL{
|
||||
Path: "/fo",
|
||||
}}, &mux.RouteMatch{}) {
|
||||
t.Fatalf("Error matching route")
|
||||
}
|
||||
|
||||
multipleRules := &Rules{route: &serverRoute{route: router.NewRoute()}}
|
||||
routeFoobar, err := multipleRules.Parse("PathPrefix:/foobar")
|
||||
if err != nil {
|
||||
t.Fatal("Error while building route for PathPrefix:/foobar")
|
||||
}
|
||||
foobarHandler := &fakeHandler{name: "foobarHandler"}
|
||||
routeFoobar.Handler(foobarHandler)
|
||||
if !router.Match(&http.Request{URL: &url.URL{
|
||||
Path: "/foo",
|
||||
}}, &mux.RouteMatch{}) {
|
||||
t.Fatalf("Error matching route")
|
||||
}
|
||||
fooMatcher := &mux.RouteMatch{}
|
||||
if !router.Match(&http.Request{URL: &url.URL{
|
||||
Path: "/foobar",
|
||||
}}, fooMatcher) {
|
||||
t.Fatalf("Error matching route")
|
||||
}
|
||||
|
||||
if fooMatcher.Handler == foobarHandler {
|
||||
t.Fatalf("Error matching priority")
|
||||
}
|
||||
|
||||
if fooMatcher.Handler != fooHandler {
|
||||
t.Fatalf("Error matching priority")
|
||||
}
|
||||
|
||||
routeFoo.Priority(1)
|
||||
routeFoobar.Priority(10)
|
||||
router.SortRoutes()
|
||||
|
||||
foobarMatcher := &mux.RouteMatch{}
|
||||
if !router.Match(&http.Request{URL: &url.URL{
|
||||
Path: "/foobar",
|
||||
}}, foobarMatcher) {
|
||||
t.Fatalf("Error matching route")
|
||||
}
|
||||
|
||||
if foobarMatcher.Handler != foobarHandler {
|
||||
t.Fatalf("Error matching priority")
|
||||
}
|
||||
|
||||
if foobarMatcher.Handler == fooHandler {
|
||||
t.Fatalf("Error matching priority")
|
||||
}
|
||||
}
|
||||
|
||||
type fakeHandler struct {
|
||||
name string
|
||||
}
|
||||
|
||||
func (h *fakeHandler) ServeHTTP(http.ResponseWriter, *http.Request) {
|
||||
|
||||
}
|
870
server/server.go
Normal file
870
server/server.go
Normal file
|
@ -0,0 +1,870 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/signal"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"sort"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/codegangsta/negroni"
|
||||
"github.com/containous/mux"
|
||||
"github.com/containous/traefik/cluster"
|
||||
"github.com/containous/traefik/healthcheck"
|
||||
"github.com/containous/traefik/log"
|
||||
"github.com/containous/traefik/middlewares"
|
||||
"github.com/containous/traefik/provider"
|
||||
"github.com/containous/traefik/safe"
|
||||
"github.com/containous/traefik/types"
|
||||
"github.com/streamrail/concurrent-map"
|
||||
"github.com/vulcand/oxy/cbreaker"
|
||||
"github.com/vulcand/oxy/connlimit"
|
||||
"github.com/vulcand/oxy/forward"
|
||||
"github.com/vulcand/oxy/roundrobin"
|
||||
"github.com/vulcand/oxy/utils"
|
||||
)
|
||||
|
||||
var oxyLogger = &OxyLogger{}
|
||||
|
||||
// Server is the reverse-proxy/load-balancer engine
|
||||
type Server struct {
|
||||
serverEntryPoints serverEntryPoints
|
||||
configurationChan chan types.ConfigMessage
|
||||
configurationValidatedChan chan types.ConfigMessage
|
||||
signals chan os.Signal
|
||||
stopChan chan bool
|
||||
providers []provider.Provider
|
||||
currentConfigurations safe.Safe
|
||||
globalConfiguration GlobalConfiguration
|
||||
loggerMiddleware *middlewares.Logger
|
||||
routinesPool *safe.Pool
|
||||
leadership *cluster.Leadership
|
||||
}
|
||||
|
||||
type serverEntryPoints map[string]*serverEntryPoint
|
||||
|
||||
type serverEntryPoint struct {
|
||||
httpServer *http.Server
|
||||
httpRouter *middlewares.HandlerSwitcher
|
||||
}
|
||||
|
||||
type serverRoute struct {
|
||||
route *mux.Route
|
||||
stripPrefixes []string
|
||||
addPrefix string
|
||||
}
|
||||
|
||||
// NewServer returns an initialized Server.
|
||||
func NewServer(globalConfiguration GlobalConfiguration) *Server {
|
||||
server := new(Server)
|
||||
|
||||
server.serverEntryPoints = make(map[string]*serverEntryPoint)
|
||||
server.configurationChan = make(chan types.ConfigMessage, 100)
|
||||
server.configurationValidatedChan = make(chan types.ConfigMessage, 100)
|
||||
server.signals = make(chan os.Signal, 1)
|
||||
server.stopChan = make(chan bool, 1)
|
||||
server.providers = []provider.Provider{}
|
||||
signal.Notify(server.signals, syscall.SIGINT, syscall.SIGTERM)
|
||||
currentConfigurations := make(configs)
|
||||
server.currentConfigurations.Set(currentConfigurations)
|
||||
server.globalConfiguration = globalConfiguration
|
||||
server.loggerMiddleware = middlewares.NewLogger(globalConfiguration.AccessLogsFile)
|
||||
server.routinesPool = safe.NewPool(context.Background())
|
||||
if globalConfiguration.Cluster != nil {
|
||||
// leadership creation if cluster mode
|
||||
server.leadership = cluster.NewLeadership(server.routinesPool.Ctx(), globalConfiguration.Cluster)
|
||||
}
|
||||
|
||||
return server
|
||||
}
|
||||
|
||||
// Start starts the server.
|
||||
func (server *Server) Start() {
|
||||
server.startHTTPServers()
|
||||
server.startLeadership()
|
||||
server.routinesPool.Go(func(stop chan bool) {
|
||||
server.listenProviders(stop)
|
||||
})
|
||||
server.routinesPool.Go(func(stop chan bool) {
|
||||
server.listenConfigurations(stop)
|
||||
})
|
||||
server.configureProviders()
|
||||
server.startProviders()
|
||||
go server.listenSignals()
|
||||
}
|
||||
|
||||
// Wait blocks until server is shutted down.
|
||||
func (server *Server) Wait() {
|
||||
<-server.stopChan
|
||||
}
|
||||
|
||||
// Stop stops the server
|
||||
func (server *Server) Stop() {
|
||||
defer log.Info("Server stopped")
|
||||
var wg sync.WaitGroup
|
||||
for sepn, sep := range server.serverEntryPoints {
|
||||
wg.Add(1)
|
||||
go func(serverEntryPointName string, serverEntryPoint *serverEntryPoint) {
|
||||
defer wg.Done()
|
||||
graceTimeOut := time.Duration(server.globalConfiguration.GraceTimeOut)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), graceTimeOut)
|
||||
log.Debugf("Waiting %s seconds before killing connections on entrypoint %s...", graceTimeOut, serverEntryPointName)
|
||||
if err := serverEntryPoint.httpServer.Shutdown(ctx); err != nil {
|
||||
log.Debugf("Wait is over due to: %s", err)
|
||||
serverEntryPoint.httpServer.Close()
|
||||
}
|
||||
cancel()
|
||||
log.Debugf("Entrypoint %s closed", serverEntryPointName)
|
||||
}(sepn, sep)
|
||||
}
|
||||
wg.Wait()
|
||||
server.stopChan <- true
|
||||
}
|
||||
|
||||
// Close destroys the server
|
||||
func (server *Server) Close() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(server.globalConfiguration.GraceTimeOut))
|
||||
go func(ctx context.Context) {
|
||||
<-ctx.Done()
|
||||
if ctx.Err() == context.Canceled {
|
||||
return
|
||||
} else if ctx.Err() == context.DeadlineExceeded {
|
||||
log.Warnf("Timeout while stopping traefik, killing instance ✝")
|
||||
os.Exit(1)
|
||||
}
|
||||
}(ctx)
|
||||
server.stopLeadership()
|
||||
server.routinesPool.Cleanup()
|
||||
close(server.configurationChan)
|
||||
close(server.configurationValidatedChan)
|
||||
signal.Stop(server.signals)
|
||||
close(server.signals)
|
||||
close(server.stopChan)
|
||||
server.loggerMiddleware.Close()
|
||||
cancel()
|
||||
}
|
||||
|
||||
func (server *Server) startLeadership() {
|
||||
if server.leadership != nil {
|
||||
server.leadership.Participate(server.routinesPool)
|
||||
// server.leadership.AddGoCtx(func(ctx context.Context) {
|
||||
// log.Debugf("Started test routine")
|
||||
// <-ctx.Done()
|
||||
// log.Debugf("Stopped test routine")
|
||||
// })
|
||||
}
|
||||
}
|
||||
|
||||
func (server *Server) stopLeadership() {
|
||||
if server.leadership != nil {
|
||||
server.leadership.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
func (server *Server) startHTTPServers() {
|
||||
server.serverEntryPoints = server.buildEntryPoints(server.globalConfiguration)
|
||||
|
||||
for newServerEntryPointName, newServerEntryPoint := range server.serverEntryPoints {
|
||||
serverMiddlewares := []negroni.Handler{server.loggerMiddleware, metrics}
|
||||
if server.globalConfiguration.Web != nil && server.globalConfiguration.Web.Metrics != nil {
|
||||
if server.globalConfiguration.Web.Metrics.Prometheus != nil {
|
||||
metricsMiddleware := middlewares.NewMetricsWrapper(middlewares.NewPrometheus(newServerEntryPointName, server.globalConfiguration.Web.Metrics.Prometheus))
|
||||
serverMiddlewares = append(serverMiddlewares, metricsMiddleware)
|
||||
}
|
||||
}
|
||||
if server.globalConfiguration.Web != nil && server.globalConfiguration.Web.Statistics != nil {
|
||||
statsRecorder = middlewares.NewStatsRecorder(server.globalConfiguration.Web.Statistics.RecentErrors)
|
||||
serverMiddlewares = append(serverMiddlewares, statsRecorder)
|
||||
}
|
||||
if server.globalConfiguration.EntryPoints[newServerEntryPointName].Auth != nil {
|
||||
authMiddleware, err := middlewares.NewAuthenticator(server.globalConfiguration.EntryPoints[newServerEntryPointName].Auth)
|
||||
if err != nil {
|
||||
log.Fatal("Error starting server: ", err)
|
||||
}
|
||||
serverMiddlewares = append(serverMiddlewares, authMiddleware)
|
||||
}
|
||||
if server.globalConfiguration.EntryPoints[newServerEntryPointName].Compress {
|
||||
serverMiddlewares = append(serverMiddlewares, &middlewares.Compress{})
|
||||
}
|
||||
newsrv, err := server.prepareServer(newServerEntryPointName, newServerEntryPoint.httpRouter, server.globalConfiguration.EntryPoints[newServerEntryPointName], serverMiddlewares...)
|
||||
if err != nil {
|
||||
log.Fatal("Error preparing server: ", err)
|
||||
}
|
||||
serverEntryPoint := server.serverEntryPoints[newServerEntryPointName]
|
||||
serverEntryPoint.httpServer = newsrv
|
||||
go server.startServer(serverEntryPoint.httpServer, server.globalConfiguration)
|
||||
}
|
||||
}
|
||||
|
||||
func (server *Server) listenProviders(stop chan bool) {
|
||||
lastReceivedConfiguration := safe.New(time.Unix(0, 0))
|
||||
lastConfigs := cmap.New()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
case configMsg, ok := <-server.configurationChan:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
server.defaultConfigurationValues(configMsg.Configuration)
|
||||
currentConfigurations := server.currentConfigurations.Get().(configs)
|
||||
jsonConf, _ := json.Marshal(configMsg.Configuration)
|
||||
log.Debugf("Configuration received from provider %s: %s", configMsg.ProviderName, string(jsonConf))
|
||||
if configMsg.Configuration == nil || configMsg.Configuration.Backends == nil && configMsg.Configuration.Frontends == nil {
|
||||
log.Infof("Skipping empty Configuration for provider %s", configMsg.ProviderName)
|
||||
} else if reflect.DeepEqual(currentConfigurations[configMsg.ProviderName], configMsg.Configuration) {
|
||||
log.Infof("Skipping same configuration for provider %s", configMsg.ProviderName)
|
||||
} else {
|
||||
lastConfigs.Set(configMsg.ProviderName, &configMsg)
|
||||
lastReceivedConfigurationValue := lastReceivedConfiguration.Get().(time.Time)
|
||||
providersThrottleDuration := time.Duration(server.globalConfiguration.ProvidersThrottleDuration)
|
||||
if time.Now().After(lastReceivedConfigurationValue.Add(providersThrottleDuration)) {
|
||||
log.Debugf("Last %s config received more than %s, OK", configMsg.ProviderName, server.globalConfiguration.ProvidersThrottleDuration.String())
|
||||
// last config received more than n s ago
|
||||
server.configurationValidatedChan <- configMsg
|
||||
} else {
|
||||
log.Debugf("Last %s config received less than %s, waiting...", configMsg.ProviderName, server.globalConfiguration.ProvidersThrottleDuration.String())
|
||||
safe.Go(func() {
|
||||
<-time.After(providersThrottleDuration)
|
||||
lastReceivedConfigurationValue := lastReceivedConfiguration.Get().(time.Time)
|
||||
if time.Now().After(lastReceivedConfigurationValue.Add(time.Duration(providersThrottleDuration))) {
|
||||
log.Debugf("Waited for %s config, OK", configMsg.ProviderName)
|
||||
if lastConfig, ok := lastConfigs.Get(configMsg.ProviderName); ok {
|
||||
server.configurationValidatedChan <- *lastConfig.(*types.ConfigMessage)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
lastReceivedConfiguration.Set(time.Now())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (server *Server) defaultConfigurationValues(configuration *types.Configuration) {
|
||||
if configuration == nil || configuration.Frontends == nil {
|
||||
return
|
||||
}
|
||||
for _, frontend := range configuration.Frontends {
|
||||
// default endpoints if not defined in frontends
|
||||
if len(frontend.EntryPoints) == 0 {
|
||||
frontend.EntryPoints = server.globalConfiguration.DefaultEntryPoints
|
||||
}
|
||||
}
|
||||
for backendName, backend := range configuration.Backends {
|
||||
_, err := types.NewLoadBalancerMethod(backend.LoadBalancer)
|
||||
if err != nil {
|
||||
log.Debugf("Load balancer method '%+v' for backend %s: %v. Using default wrr.", backend.LoadBalancer, backendName, err)
|
||||
backend.LoadBalancer = &types.LoadBalancer{Method: "wrr"}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (server *Server) listenConfigurations(stop chan bool) {
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
case configMsg, ok := <-server.configurationValidatedChan:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
currentConfigurations := server.currentConfigurations.Get().(configs)
|
||||
|
||||
// Copy configurations to new map so we don't change current if LoadConfig fails
|
||||
newConfigurations := make(configs)
|
||||
for k, v := range currentConfigurations {
|
||||
newConfigurations[k] = v
|
||||
}
|
||||
newConfigurations[configMsg.ProviderName] = configMsg.Configuration
|
||||
|
||||
newServerEntryPoints, err := server.loadConfig(newConfigurations, server.globalConfiguration)
|
||||
if err == nil {
|
||||
for newServerEntryPointName, newServerEntryPoint := range newServerEntryPoints {
|
||||
server.serverEntryPoints[newServerEntryPointName].httpRouter.UpdateHandler(newServerEntryPoint.httpRouter.GetHandler())
|
||||
log.Infof("Server configuration reloaded on %s", server.serverEntryPoints[newServerEntryPointName].httpServer.Addr)
|
||||
}
|
||||
server.currentConfigurations.Set(newConfigurations)
|
||||
server.postLoadConfig()
|
||||
} else {
|
||||
log.Error("Error loading new configuration, aborted ", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (server *Server) postLoadConfig() {
|
||||
if server.globalConfiguration.ACME == nil {
|
||||
return
|
||||
}
|
||||
if server.leadership != nil && !server.leadership.IsLeader() {
|
||||
return
|
||||
}
|
||||
if server.globalConfiguration.ACME.OnHostRule {
|
||||
currentConfigurations := server.currentConfigurations.Get().(configs)
|
||||
for _, configuration := range currentConfigurations {
|
||||
for _, frontend := range configuration.Frontends {
|
||||
|
||||
// check if one of the frontend entrypoints is configured with TLS
|
||||
TLSEnabled := false
|
||||
for _, entrypoint := range frontend.EntryPoints {
|
||||
if server.globalConfiguration.EntryPoints[entrypoint].TLS != nil {
|
||||
TLSEnabled = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if TLSEnabled {
|
||||
for _, route := range frontend.Routes {
|
||||
rules := Rules{}
|
||||
domains, err := rules.ParseDomains(route.Rule)
|
||||
if err != nil {
|
||||
log.Errorf("Error parsing domains: %v", err)
|
||||
} else {
|
||||
server.globalConfiguration.ACME.LoadCertificateForDomains(domains)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (server *Server) configureProviders() {
|
||||
// configure providers
|
||||
if server.globalConfiguration.Docker != nil {
|
||||
server.providers = append(server.providers, server.globalConfiguration.Docker)
|
||||
}
|
||||
if server.globalConfiguration.Marathon != nil {
|
||||
server.providers = append(server.providers, server.globalConfiguration.Marathon)
|
||||
}
|
||||
if server.globalConfiguration.File != nil {
|
||||
server.providers = append(server.providers, server.globalConfiguration.File)
|
||||
}
|
||||
if server.globalConfiguration.Web != nil {
|
||||
server.globalConfiguration.Web.server = server
|
||||
server.providers = append(server.providers, server.globalConfiguration.Web)
|
||||
}
|
||||
if server.globalConfiguration.Consul != nil {
|
||||
server.providers = append(server.providers, server.globalConfiguration.Consul)
|
||||
}
|
||||
if server.globalConfiguration.ConsulCatalog != nil {
|
||||
server.providers = append(server.providers, server.globalConfiguration.ConsulCatalog)
|
||||
}
|
||||
if server.globalConfiguration.Etcd != nil {
|
||||
server.providers = append(server.providers, server.globalConfiguration.Etcd)
|
||||
}
|
||||
if server.globalConfiguration.Zookeeper != nil {
|
||||
server.providers = append(server.providers, server.globalConfiguration.Zookeeper)
|
||||
}
|
||||
if server.globalConfiguration.Boltdb != nil {
|
||||
server.providers = append(server.providers, server.globalConfiguration.Boltdb)
|
||||
}
|
||||
if server.globalConfiguration.Kubernetes != nil {
|
||||
server.providers = append(server.providers, server.globalConfiguration.Kubernetes)
|
||||
}
|
||||
if server.globalConfiguration.Mesos != nil {
|
||||
server.providers = append(server.providers, server.globalConfiguration.Mesos)
|
||||
}
|
||||
if server.globalConfiguration.Eureka != nil {
|
||||
server.providers = append(server.providers, server.globalConfiguration.Eureka)
|
||||
}
|
||||
if server.globalConfiguration.ECS != nil {
|
||||
server.providers = append(server.providers, server.globalConfiguration.ECS)
|
||||
}
|
||||
if server.globalConfiguration.Rancher != nil {
|
||||
server.providers = append(server.providers, server.globalConfiguration.Rancher)
|
||||
}
|
||||
if server.globalConfiguration.DynamoDB != nil {
|
||||
server.providers = append(server.providers, server.globalConfiguration.DynamoDB)
|
||||
}
|
||||
}
|
||||
|
||||
func (server *Server) startProviders() {
|
||||
// start providers
|
||||
for _, provider := range server.providers {
|
||||
providerType := reflect.TypeOf(provider)
|
||||
jsonConf, _ := json.Marshal(provider)
|
||||
log.Infof("Starting provider %v %s", providerType, jsonConf)
|
||||
currentProvider := provider
|
||||
safe.Go(func() {
|
||||
err := currentProvider.Provide(server.configurationChan, server.routinesPool, server.globalConfiguration.Constraints)
|
||||
if err != nil {
|
||||
log.Errorf("Error starting provider %v: %s", providerType, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (server *Server) listenSignals() {
|
||||
sig := <-server.signals
|
||||
log.Infof("I have to go... %+v", sig)
|
||||
log.Info("Stopping server")
|
||||
server.Stop()
|
||||
}
|
||||
|
||||
// creates a TLS config that allows terminating HTTPS for multiple domains using SNI
|
||||
func (server *Server) createTLSConfig(entryPointName string, tlsOption *TLS, router *middlewares.HandlerSwitcher) (*tls.Config, error) {
|
||||
if tlsOption == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
config, err := tlsOption.Certificates.CreateTLSConfig()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// ensure http2 enabled
|
||||
config.NextProtos = []string{"h2", "http/1.1"}
|
||||
|
||||
if len(tlsOption.ClientCAFiles) > 0 {
|
||||
pool := x509.NewCertPool()
|
||||
for _, caFile := range tlsOption.ClientCAFiles {
|
||||
data, err := ioutil.ReadFile(caFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ok := pool.AppendCertsFromPEM(data)
|
||||
if !ok {
|
||||
return nil, errors.New("invalid certificate(s) in " + caFile)
|
||||
}
|
||||
}
|
||||
config.ClientCAs = pool
|
||||
config.ClientAuth = tls.RequireAndVerifyClientCert
|
||||
}
|
||||
|
||||
if server.globalConfiguration.ACME != nil {
|
||||
if _, ok := server.serverEntryPoints[server.globalConfiguration.ACME.EntryPoint]; ok {
|
||||
if entryPointName == server.globalConfiguration.ACME.EntryPoint {
|
||||
checkOnDemandDomain := func(domain string) bool {
|
||||
routeMatch := &mux.RouteMatch{}
|
||||
router := router.GetHandler()
|
||||
match := router.Match(&http.Request{URL: &url.URL{}, Host: domain}, routeMatch)
|
||||
if match && routeMatch.Route != nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
if server.leadership == nil {
|
||||
err := server.globalConfiguration.ACME.CreateLocalConfig(config, checkOnDemandDomain)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
err := server.globalConfiguration.ACME.CreateClusterConfig(server.leadership, config, checkOnDemandDomain)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return nil, errors.New("Unknown entrypoint " + server.globalConfiguration.ACME.EntryPoint + " for ACME configuration")
|
||||
}
|
||||
}
|
||||
if len(config.Certificates) == 0 {
|
||||
return nil, errors.New("No certificates found for TLS entrypoint " + entryPointName)
|
||||
}
|
||||
// BuildNameToCertificate parses the CommonName and SubjectAlternateName fields
|
||||
// in each certificate and populates the config.NameToCertificate map.
|
||||
config.BuildNameToCertificate()
|
||||
//Set the minimum TLS version if set in the config TOML
|
||||
if minConst, exists := minVersion[server.globalConfiguration.EntryPoints[entryPointName].TLS.MinVersion]; exists {
|
||||
config.PreferServerCipherSuites = true
|
||||
config.MinVersion = minConst
|
||||
}
|
||||
//Set the list of CipherSuites if set in the config TOML
|
||||
if server.globalConfiguration.EntryPoints[entryPointName].TLS.CipherSuites != nil {
|
||||
//if our list of CipherSuites is defined in the entrypoint config, we can re-initilize the suites list as empty
|
||||
config.CipherSuites = make([]uint16, 0)
|
||||
for _, cipher := range server.globalConfiguration.EntryPoints[entryPointName].TLS.CipherSuites {
|
||||
if cipherConst, exists := cipherSuites[cipher]; exists {
|
||||
config.CipherSuites = append(config.CipherSuites, cipherConst)
|
||||
} else {
|
||||
//CipherSuite listed in the toml does not exist in our listed
|
||||
return nil, errors.New("Invalid CipherSuite: " + cipher)
|
||||
}
|
||||
}
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
|
||||
func (server *Server) startServer(srv *http.Server, globalConfiguration GlobalConfiguration) {
|
||||
log.Infof("Starting server on %s", srv.Addr)
|
||||
var err error
|
||||
if srv.TLSConfig != nil {
|
||||
err = srv.ListenAndServeTLS("", "")
|
||||
} else {
|
||||
err = srv.ListenAndServe()
|
||||
}
|
||||
if err != nil {
|
||||
log.Error("Error creating server: ", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (server *Server) prepareServer(entryPointName string, router *middlewares.HandlerSwitcher, entryPoint *EntryPoint, middlewares ...negroni.Handler) (*http.Server, error) {
|
||||
log.Infof("Preparing server %s %+v", entryPointName, entryPoint)
|
||||
// middlewares
|
||||
var negroni = negroni.New()
|
||||
for _, middleware := range middlewares {
|
||||
negroni.Use(middleware)
|
||||
}
|
||||
negroni.UseHandler(router)
|
||||
tlsConfig, err := server.createTLSConfig(entryPointName, entryPoint.TLS, router)
|
||||
if err != nil {
|
||||
log.Errorf("Error creating TLS config: %s", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &http.Server{
|
||||
Addr: entryPoint.Address,
|
||||
Handler: negroni,
|
||||
TLSConfig: tlsConfig,
|
||||
IdleTimeout: time.Duration(server.globalConfiguration.IdleTimeout),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (server *Server) buildEntryPoints(globalConfiguration GlobalConfiguration) map[string]*serverEntryPoint {
|
||||
serverEntryPoints := make(map[string]*serverEntryPoint)
|
||||
for entryPointName := range globalConfiguration.EntryPoints {
|
||||
router := server.buildDefaultHTTPRouter()
|
||||
serverEntryPoints[entryPointName] = &serverEntryPoint{
|
||||
httpRouter: middlewares.NewHandlerSwitcher(router),
|
||||
}
|
||||
}
|
||||
return serverEntryPoints
|
||||
}
|
||||
|
||||
// LoadConfig returns a new gorilla.mux Route from the specified global configuration and the dynamic
|
||||
// provider configurations.
|
||||
func (server *Server) loadConfig(configurations configs, globalConfiguration GlobalConfiguration) (map[string]*serverEntryPoint, error) {
|
||||
serverEntryPoints := server.buildEntryPoints(globalConfiguration)
|
||||
redirectHandlers := make(map[string]http.Handler)
|
||||
|
||||
backends := map[string]http.Handler{}
|
||||
|
||||
backendsHealthcheck := map[string]*healthcheck.BackendHealthCheck{}
|
||||
|
||||
backend2FrontendMap := map[string]string{}
|
||||
for _, configuration := range configurations {
|
||||
frontendNames := sortedFrontendNamesForConfig(configuration)
|
||||
frontend:
|
||||
for _, frontendName := range frontendNames {
|
||||
frontend := configuration.Frontends[frontendName]
|
||||
|
||||
log.Debugf("Creating frontend %s", frontendName)
|
||||
|
||||
fwd, err := forward.New(forward.Logger(oxyLogger), forward.PassHostHeader(frontend.PassHostHeader))
|
||||
if err != nil {
|
||||
log.Errorf("Error creating forwarder for frontend %s: %v", frontendName, err)
|
||||
log.Errorf("Skipping frontend %s...", frontendName)
|
||||
continue frontend
|
||||
}
|
||||
saveBackend := middlewares.NewSaveBackend(fwd)
|
||||
if len(frontend.EntryPoints) == 0 {
|
||||
log.Errorf("No entrypoint defined for frontend %s, defaultEntryPoints:%s", frontendName, globalConfiguration.DefaultEntryPoints)
|
||||
log.Errorf("Skipping frontend %s...", frontendName)
|
||||
continue frontend
|
||||
}
|
||||
|
||||
for _, entryPointName := range frontend.EntryPoints {
|
||||
log.Debugf("Wiring frontend %s to entryPoint %s", frontendName, entryPointName)
|
||||
if _, ok := serverEntryPoints[entryPointName]; !ok {
|
||||
log.Errorf("Undefined entrypoint '%s' for frontend %s", entryPointName, frontendName)
|
||||
log.Errorf("Skipping frontend %s...", frontendName)
|
||||
continue frontend
|
||||
}
|
||||
|
||||
newServerRoute := &serverRoute{route: serverEntryPoints[entryPointName].httpRouter.GetHandler().NewRoute().Name(frontendName)}
|
||||
for routeName, route := range frontend.Routes {
|
||||
err := getRoute(newServerRoute, &route)
|
||||
if err != nil {
|
||||
log.Errorf("Error creating route for frontend %s: %v", frontendName, err)
|
||||
log.Errorf("Skipping frontend %s...", frontendName)
|
||||
continue frontend
|
||||
}
|
||||
log.Debugf("Creating route %s %s", routeName, route.Rule)
|
||||
}
|
||||
|
||||
entryPoint := globalConfiguration.EntryPoints[entryPointName]
|
||||
if entryPoint.Redirect != nil {
|
||||
if redirectHandlers[entryPointName] != nil {
|
||||
newServerRoute.route.Handler(redirectHandlers[entryPointName])
|
||||
} else if handler, err := server.loadEntryPointConfig(entryPointName, entryPoint); err != nil {
|
||||
log.Errorf("Error loading entrypoint configuration for frontend %s: %v", frontendName, err)
|
||||
log.Errorf("Skipping frontend %s...", frontendName)
|
||||
continue frontend
|
||||
} else {
|
||||
newServerRoute.route.Handler(handler)
|
||||
redirectHandlers[entryPointName] = handler
|
||||
}
|
||||
} else {
|
||||
if backends[frontend.Backend] == nil {
|
||||
log.Debugf("Creating backend %s", frontend.Backend)
|
||||
var lb http.Handler
|
||||
rr, _ := roundrobin.New(saveBackend)
|
||||
if configuration.Backends[frontend.Backend] == nil {
|
||||
log.Errorf("Undefined backend '%s' for frontend %s", frontend.Backend, frontendName)
|
||||
log.Errorf("Skipping frontend %s...", frontendName)
|
||||
continue frontend
|
||||
}
|
||||
|
||||
lbMethod, err := types.NewLoadBalancerMethod(configuration.Backends[frontend.Backend].LoadBalancer)
|
||||
if err != nil {
|
||||
log.Errorf("Error loading load balancer method '%+v' for frontend %s: %v", configuration.Backends[frontend.Backend].LoadBalancer, frontendName, err)
|
||||
log.Errorf("Skipping frontend %s...", frontendName)
|
||||
continue frontend
|
||||
}
|
||||
|
||||
stickysession := configuration.Backends[frontend.Backend].LoadBalancer.Sticky
|
||||
cookiename := "_TRAEFIK_BACKEND"
|
||||
var sticky *roundrobin.StickySession
|
||||
|
||||
if stickysession {
|
||||
sticky = roundrobin.NewStickySession(cookiename)
|
||||
}
|
||||
|
||||
switch lbMethod {
|
||||
case types.Drr:
|
||||
log.Debugf("Creating load-balancer drr")
|
||||
rebalancer, _ := roundrobin.NewRebalancer(rr, roundrobin.RebalancerLogger(oxyLogger))
|
||||
if stickysession {
|
||||
log.Debugf("Sticky session with cookie %v", cookiename)
|
||||
rebalancer, _ = roundrobin.NewRebalancer(rr, roundrobin.RebalancerLogger(oxyLogger), roundrobin.RebalancerStickySession(sticky))
|
||||
}
|
||||
lb = rebalancer
|
||||
for serverName, server := range configuration.Backends[frontend.Backend].Servers {
|
||||
url, err := url.Parse(server.URL)
|
||||
if err != nil {
|
||||
log.Errorf("Error parsing server URL %s: %v", server.URL, err)
|
||||
log.Errorf("Skipping frontend %s...", frontendName)
|
||||
continue frontend
|
||||
}
|
||||
backend2FrontendMap[url.String()] = frontendName
|
||||
log.Debugf("Creating server %s at %s with weight %d", serverName, url.String(), server.Weight)
|
||||
if err := rebalancer.UpsertServer(url, roundrobin.Weight(server.Weight)); err != nil {
|
||||
log.Errorf("Error adding server %s to load balancer: %v", server.URL, err)
|
||||
log.Errorf("Skipping frontend %s...", frontendName)
|
||||
continue frontend
|
||||
}
|
||||
if configuration.Backends[frontend.Backend].HealthCheck != nil {
|
||||
var interval time.Duration
|
||||
if configuration.Backends[frontend.Backend].HealthCheck.Interval != "" {
|
||||
interval, err = time.ParseDuration(configuration.Backends[frontend.Backend].HealthCheck.Interval)
|
||||
if err != nil {
|
||||
log.Errorf("Wrong healthcheck interval: %s", err)
|
||||
interval = time.Second * 30
|
||||
}
|
||||
}
|
||||
backendsHealthcheck[frontend.Backend] = healthcheck.NewBackendHealthCheck(configuration.Backends[frontend.Backend].HealthCheck.Path, interval, rebalancer)
|
||||
}
|
||||
}
|
||||
case types.Wrr:
|
||||
log.Debugf("Creating load-balancer wrr")
|
||||
if stickysession {
|
||||
log.Debugf("Sticky session with cookie %v", cookiename)
|
||||
rr, _ = roundrobin.New(saveBackend, roundrobin.EnableStickySession(sticky))
|
||||
}
|
||||
lb = rr
|
||||
for serverName, server := range configuration.Backends[frontend.Backend].Servers {
|
||||
url, err := url.Parse(server.URL)
|
||||
if err != nil {
|
||||
log.Errorf("Error parsing server URL %s: %v", server.URL, err)
|
||||
log.Errorf("Skipping frontend %s...", frontendName)
|
||||
continue frontend
|
||||
}
|
||||
backend2FrontendMap[url.String()] = frontendName
|
||||
log.Debugf("Creating server %s at %s with weight %d", serverName, url.String(), server.Weight)
|
||||
if err := rr.UpsertServer(url, roundrobin.Weight(server.Weight)); err != nil {
|
||||
log.Errorf("Error adding server %s to load balancer: %v", server.URL, err)
|
||||
log.Errorf("Skipping frontend %s...", frontendName)
|
||||
continue frontend
|
||||
}
|
||||
}
|
||||
if configuration.Backends[frontend.Backend].HealthCheck != nil {
|
||||
var interval time.Duration
|
||||
if configuration.Backends[frontend.Backend].HealthCheck.Interval != "" {
|
||||
interval, err = time.ParseDuration(configuration.Backends[frontend.Backend].HealthCheck.Interval)
|
||||
if err != nil {
|
||||
log.Errorf("Wrong healthcheck interval: %s", err)
|
||||
interval = time.Second * 30
|
||||
}
|
||||
}
|
||||
backendsHealthcheck[frontend.Backend] = healthcheck.NewBackendHealthCheck(configuration.Backends[frontend.Backend].HealthCheck.Path, interval, rr)
|
||||
}
|
||||
}
|
||||
maxConns := configuration.Backends[frontend.Backend].MaxConn
|
||||
if maxConns != nil && maxConns.Amount != 0 {
|
||||
extractFunc, err := utils.NewExtractor(maxConns.ExtractorFunc)
|
||||
if err != nil {
|
||||
log.Errorf("Error creating connlimit: %v", err)
|
||||
log.Errorf("Skipping frontend %s...", frontendName)
|
||||
continue frontend
|
||||
}
|
||||
log.Debugf("Creating load-balancer connlimit")
|
||||
lb, err = connlimit.New(lb, extractFunc, maxConns.Amount, connlimit.Logger(oxyLogger))
|
||||
if err != nil {
|
||||
log.Errorf("Error creating connlimit: %v", err)
|
||||
log.Errorf("Skipping frontend %s...", frontendName)
|
||||
continue frontend
|
||||
}
|
||||
}
|
||||
// retry ?
|
||||
if globalConfiguration.Retry != nil {
|
||||
retries := len(configuration.Backends[frontend.Backend].Servers)
|
||||
if globalConfiguration.Retry.Attempts > 0 {
|
||||
retries = globalConfiguration.Retry.Attempts
|
||||
}
|
||||
lb = middlewares.NewRetry(retries, lb)
|
||||
log.Debugf("Creating retries max attempts %d", retries)
|
||||
}
|
||||
|
||||
var negroni = negroni.New()
|
||||
if server.globalConfiguration.Web != nil && server.globalConfiguration.Web.Metrics != nil {
|
||||
if server.globalConfiguration.Web.Metrics.Prometheus != nil {
|
||||
metricsMiddlewareBackend := middlewares.NewMetricsWrapper(middlewares.NewPrometheus(frontend.Backend, server.globalConfiguration.Web.Metrics.Prometheus))
|
||||
negroni.Use(metricsMiddlewareBackend)
|
||||
}
|
||||
}
|
||||
|
||||
if len(frontend.BasicAuth) > 0 {
|
||||
users := types.Users{}
|
||||
for _, user := range frontend.BasicAuth {
|
||||
users = append(users, user)
|
||||
}
|
||||
|
||||
auth := &types.Auth{}
|
||||
auth.Basic = &types.Basic{
|
||||
Users: users,
|
||||
}
|
||||
authMiddleware, err := middlewares.NewAuthenticator(auth)
|
||||
if err != nil {
|
||||
log.Fatal("Error creating Auth: ", err)
|
||||
}
|
||||
negroni.Use(authMiddleware)
|
||||
}
|
||||
|
||||
if configuration.Backends[frontend.Backend].CircuitBreaker != nil {
|
||||
log.Debugf("Creating circuit breaker %s", configuration.Backends[frontend.Backend].CircuitBreaker.Expression)
|
||||
cbreaker, err := middlewares.NewCircuitBreaker(lb, configuration.Backends[frontend.Backend].CircuitBreaker.Expression, cbreaker.Logger(oxyLogger))
|
||||
if err != nil {
|
||||
log.Errorf("Error creating circuit breaker: %v", err)
|
||||
log.Errorf("Skipping frontend %s...", frontendName)
|
||||
continue frontend
|
||||
}
|
||||
negroni.Use(cbreaker)
|
||||
} else {
|
||||
negroni.UseHandler(lb)
|
||||
}
|
||||
backends[frontend.Backend] = negroni
|
||||
} else {
|
||||
log.Debugf("Reusing backend %s", frontend.Backend)
|
||||
}
|
||||
if frontend.Priority > 0 {
|
||||
newServerRoute.route.Priority(frontend.Priority)
|
||||
}
|
||||
server.wireFrontendBackend(newServerRoute, backends[frontend.Backend])
|
||||
}
|
||||
err := newServerRoute.route.GetError()
|
||||
if err != nil {
|
||||
log.Errorf("Error building route: %s", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
healthcheck.GetHealthCheck().SetBackendsConfiguration(server.routinesPool.Ctx(), backendsHealthcheck)
|
||||
middlewares.SetBackend2FrontendMap(&backend2FrontendMap)
|
||||
//sort routes
|
||||
for _, serverEntryPoint := range serverEntryPoints {
|
||||
serverEntryPoint.httpRouter.GetHandler().SortRoutes()
|
||||
}
|
||||
return serverEntryPoints, nil
|
||||
}
|
||||
|
||||
func (server *Server) wireFrontendBackend(serverRoute *serverRoute, handler http.Handler) {
|
||||
// add prefix
|
||||
if len(serverRoute.addPrefix) > 0 {
|
||||
handler = &middlewares.AddPrefix{
|
||||
Prefix: serverRoute.addPrefix,
|
||||
Handler: handler,
|
||||
}
|
||||
}
|
||||
|
||||
// strip prefix
|
||||
if len(serverRoute.stripPrefixes) > 0 {
|
||||
handler = &middlewares.StripPrefix{
|
||||
Prefixes: serverRoute.stripPrefixes,
|
||||
Handler: handler,
|
||||
}
|
||||
}
|
||||
|
||||
serverRoute.route.Handler(handler)
|
||||
}
|
||||
|
||||
func (server *Server) loadEntryPointConfig(entryPointName string, entryPoint *EntryPoint) (http.Handler, error) {
|
||||
regex := entryPoint.Redirect.Regex
|
||||
replacement := entryPoint.Redirect.Replacement
|
||||
if len(entryPoint.Redirect.EntryPoint) > 0 {
|
||||
regex = "^(?:https?:\\/\\/)?([\\w\\._-]+)(?::\\d+)?(.*)$"
|
||||
if server.globalConfiguration.EntryPoints[entryPoint.Redirect.EntryPoint] == nil {
|
||||
return nil, errors.New("Unknown entrypoint " + entryPoint.Redirect.EntryPoint)
|
||||
}
|
||||
protocol := "http"
|
||||
if server.globalConfiguration.EntryPoints[entryPoint.Redirect.EntryPoint].TLS != nil {
|
||||
protocol = "https"
|
||||
}
|
||||
r, _ := regexp.Compile("(:\\d+)")
|
||||
match := r.FindStringSubmatch(server.globalConfiguration.EntryPoints[entryPoint.Redirect.EntryPoint].Address)
|
||||
if len(match) == 0 {
|
||||
return nil, errors.New("Bad Address format: " + server.globalConfiguration.EntryPoints[entryPoint.Redirect.EntryPoint].Address)
|
||||
}
|
||||
replacement = protocol + "://$1" + match[0] + "$2"
|
||||
}
|
||||
rewrite, err := middlewares.NewRewrite(regex, replacement, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log.Debugf("Creating entryPoint redirect %s -> %s : %s -> %s", entryPointName, entryPoint.Redirect.EntryPoint, regex, replacement)
|
||||
negroni := negroni.New()
|
||||
negroni.Use(rewrite)
|
||||
return negroni, nil
|
||||
}
|
||||
|
||||
func (server *Server) buildDefaultHTTPRouter() *mux.Router {
|
||||
router := mux.NewRouter()
|
||||
router.NotFoundHandler = http.HandlerFunc(notFoundHandler)
|
||||
router.StrictSlash(true)
|
||||
router.SkipClean(true)
|
||||
return router
|
||||
}
|
||||
|
||||
func getRoute(serverRoute *serverRoute, route *types.Route) error {
|
||||
rules := Rules{route: serverRoute}
|
||||
newRoute, err := rules.Parse(route.Rule)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
newRoute.Priority(serverRoute.route.GetPriority() + len(route.Rule))
|
||||
serverRoute.route = newRoute
|
||||
return nil
|
||||
}
|
||||
|
||||
func sortedFrontendNamesForConfig(configuration *types.Configuration) []string {
|
||||
keys := []string{}
|
||||
for key := range configuration.Frontends {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
332
server/web.go
Normal file
332
server/web.go
Normal file
|
@ -0,0 +1,332 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"expvar"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"runtime"
|
||||
|
||||
"github.com/codegangsta/negroni"
|
||||
"github.com/containous/mux"
|
||||
"github.com/containous/traefik/autogen"
|
||||
"github.com/containous/traefik/log"
|
||||
"github.com/containous/traefik/middlewares"
|
||||
"github.com/containous/traefik/safe"
|
||||
"github.com/containous/traefik/types"
|
||||
"github.com/containous/traefik/version"
|
||||
"github.com/elazarl/go-bindata-assetfs"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
thoas_stats "github.com/thoas/stats"
|
||||
"github.com/unrolled/render"
|
||||
)
|
||||
|
||||
var (
|
||||
metrics = thoas_stats.New()
|
||||
statsRecorder *middlewares.StatsRecorder
|
||||
)
|
||||
|
||||
// WebProvider is a provider.Provider implementation that provides the UI.
|
||||
// FIXME to be handled another way.
|
||||
type WebProvider struct {
|
||||
Address string `description:"Web administration port"`
|
||||
CertFile string `description:"SSL certificate"`
|
||||
KeyFile string `description:"SSL certificate"`
|
||||
ReadOnly bool `description:"Enable read only API"`
|
||||
Statistics *types.Statistics `description:"Enable more detailed statistics"`
|
||||
Metrics *types.Metrics `description:"Enable a metrics exporter"`
|
||||
Path string `description:"Root path for dashboard and API"`
|
||||
server *Server
|
||||
Auth *types.Auth
|
||||
}
|
||||
|
||||
var (
|
||||
templatesRenderer = render.New(render.Options{
|
||||
Directory: "nowhere",
|
||||
})
|
||||
)
|
||||
|
||||
func init() {
|
||||
expvar.Publish("Goroutines", expvar.Func(goroutines))
|
||||
}
|
||||
|
||||
func goroutines() interface{} {
|
||||
return runtime.NumGoroutine()
|
||||
}
|
||||
|
||||
// Provide allows the provider to provide configurations to traefik
|
||||
// using the given configuration channel.
|
||||
func (provider *WebProvider) Provide(configurationChan chan<- types.ConfigMessage, pool *safe.Pool, _ types.Constraints) error {
|
||||
|
||||
systemRouter := mux.NewRouter()
|
||||
|
||||
if provider.Path == "" {
|
||||
provider.Path = "/"
|
||||
}
|
||||
|
||||
if provider.Path != "/" {
|
||||
if provider.Path[len(provider.Path)-1:] != "/" {
|
||||
provider.Path += "/"
|
||||
}
|
||||
systemRouter.Methods("GET").Path("/").HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
|
||||
http.Redirect(response, request, provider.Path, 302)
|
||||
})
|
||||
}
|
||||
|
||||
// Prometheus route
|
||||
if provider.Metrics != nil && provider.Metrics.Prometheus != nil {
|
||||
systemRouter.Methods("GET").Path(provider.Path + "metrics").Handler(promhttp.Handler())
|
||||
}
|
||||
|
||||
// health route
|
||||
systemRouter.Methods("GET").Path(provider.Path + "health").HandlerFunc(provider.getHealthHandler)
|
||||
|
||||
// ping route
|
||||
systemRouter.Methods("GET").Path(provider.Path + "ping").HandlerFunc(provider.getPingHandler)
|
||||
// API routes
|
||||
systemRouter.Methods("GET").Path(provider.Path + "api").HandlerFunc(provider.getConfigHandler)
|
||||
systemRouter.Methods("GET").Path(provider.Path + "api/version").HandlerFunc(provider.getVersionHandler)
|
||||
systemRouter.Methods("GET").Path(provider.Path + "api/providers").HandlerFunc(provider.getConfigHandler)
|
||||
systemRouter.Methods("GET").Path(provider.Path + "api/providers/{provider}").HandlerFunc(provider.getProviderHandler)
|
||||
systemRouter.Methods("PUT").Path(provider.Path + "api/providers/{provider}").HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
|
||||
if provider.ReadOnly {
|
||||
response.WriteHeader(http.StatusForbidden)
|
||||
fmt.Fprintf(response, "REST API is in read-only mode")
|
||||
return
|
||||
}
|
||||
vars := mux.Vars(request)
|
||||
if vars["provider"] != "web" {
|
||||
response.WriteHeader(http.StatusBadRequest)
|
||||
fmt.Fprintf(response, "Only 'web' provider can be updated through the REST API")
|
||||
return
|
||||
}
|
||||
|
||||
configuration := new(types.Configuration)
|
||||
body, _ := ioutil.ReadAll(request.Body)
|
||||
err := json.Unmarshal(body, configuration)
|
||||
if err == nil {
|
||||
configurationChan <- types.ConfigMessage{ProviderName: "web", Configuration: configuration}
|
||||
provider.getConfigHandler(response, request)
|
||||
} else {
|
||||
log.Errorf("Error parsing configuration %+v", err)
|
||||
http.Error(response, fmt.Sprintf("%+v", err), http.StatusBadRequest)
|
||||
}
|
||||
})
|
||||
systemRouter.Methods("GET").Path(provider.Path + "api/providers/{provider}/backends").HandlerFunc(provider.getBackendsHandler)
|
||||
systemRouter.Methods("GET").Path(provider.Path + "api/providers/{provider}/backends/{backend}").HandlerFunc(provider.getBackendHandler)
|
||||
systemRouter.Methods("GET").Path(provider.Path + "api/providers/{provider}/backends/{backend}/servers").HandlerFunc(provider.getServersHandler)
|
||||
systemRouter.Methods("GET").Path(provider.Path + "api/providers/{provider}/backends/{backend}/servers/{server}").HandlerFunc(provider.getServerHandler)
|
||||
systemRouter.Methods("GET").Path(provider.Path + "api/providers/{provider}/frontends").HandlerFunc(provider.getFrontendsHandler)
|
||||
systemRouter.Methods("GET").Path(provider.Path + "api/providers/{provider}/frontends/{frontend}").HandlerFunc(provider.getFrontendHandler)
|
||||
systemRouter.Methods("GET").Path(provider.Path + "api/providers/{provider}/frontends/{frontend}/routes").HandlerFunc(provider.getRoutesHandler)
|
||||
systemRouter.Methods("GET").Path(provider.Path + "api/providers/{provider}/frontends/{frontend}/routes/{route}").HandlerFunc(provider.getRouteHandler)
|
||||
|
||||
// Expose dashboard
|
||||
systemRouter.Methods("GET").Path(provider.Path).HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
|
||||
http.Redirect(response, request, provider.Path+"dashboard/", 302)
|
||||
})
|
||||
systemRouter.Methods("GET").PathPrefix(provider.Path + "dashboard/").Handler(http.StripPrefix(provider.Path+"dashboard/", http.FileServer(&assetfs.AssetFS{Asset: autogen.Asset, AssetInfo: autogen.AssetInfo, AssetDir: autogen.AssetDir, Prefix: "static"})))
|
||||
|
||||
// expvars
|
||||
if provider.server.globalConfiguration.Debug {
|
||||
systemRouter.Methods("GET").Path(provider.Path + "debug/vars").HandlerFunc(expvarHandler)
|
||||
}
|
||||
|
||||
go func() {
|
||||
var err error
|
||||
var negroni = negroni.New()
|
||||
if provider.Auth != nil {
|
||||
authMiddleware, err := middlewares.NewAuthenticator(provider.Auth)
|
||||
if err != nil {
|
||||
log.Fatal("Error creating Auth: ", err)
|
||||
}
|
||||
negroni.Use(authMiddleware)
|
||||
}
|
||||
negroni.UseHandler(systemRouter)
|
||||
|
||||
if len(provider.CertFile) > 0 && len(provider.KeyFile) > 0 {
|
||||
err = http.ListenAndServeTLS(provider.Address, provider.CertFile, provider.KeyFile, negroni)
|
||||
} else {
|
||||
err = http.ListenAndServe(provider.Address, negroni)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
log.Fatal("Error creating server: ", err)
|
||||
}
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
|
||||
// healthResponse combines data returned by thoas/stats with statistics (if
|
||||
// they are enabled).
|
||||
type healthResponse struct {
|
||||
*thoas_stats.Data
|
||||
*middlewares.Stats
|
||||
}
|
||||
|
||||
func (provider *WebProvider) getHealthHandler(response http.ResponseWriter, request *http.Request) {
|
||||
health := &healthResponse{Data: metrics.Data()}
|
||||
if statsRecorder != nil {
|
||||
health.Stats = statsRecorder.Data()
|
||||
}
|
||||
templatesRenderer.JSON(response, http.StatusOK, health)
|
||||
}
|
||||
|
||||
func (provider *WebProvider) getPingHandler(response http.ResponseWriter, request *http.Request) {
|
||||
fmt.Fprintf(response, "OK")
|
||||
}
|
||||
|
||||
func (provider *WebProvider) getConfigHandler(response http.ResponseWriter, request *http.Request) {
|
||||
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
|
||||
templatesRenderer.JSON(response, http.StatusOK, currentConfigurations)
|
||||
}
|
||||
|
||||
func (provider *WebProvider) getVersionHandler(response http.ResponseWriter, request *http.Request) {
|
||||
v := struct {
|
||||
Version string
|
||||
Codename string
|
||||
}{
|
||||
Version: version.Version,
|
||||
Codename: version.Codename,
|
||||
}
|
||||
templatesRenderer.JSON(response, http.StatusOK, v)
|
||||
}
|
||||
|
||||
func (provider *WebProvider) getProviderHandler(response http.ResponseWriter, request *http.Request) {
|
||||
vars := mux.Vars(request)
|
||||
providerID := vars["provider"]
|
||||
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
|
||||
if provider, ok := currentConfigurations[providerID]; ok {
|
||||
templatesRenderer.JSON(response, http.StatusOK, provider)
|
||||
} else {
|
||||
http.NotFound(response, request)
|
||||
}
|
||||
}
|
||||
|
||||
func (provider *WebProvider) getBackendsHandler(response http.ResponseWriter, request *http.Request) {
|
||||
vars := mux.Vars(request)
|
||||
providerID := vars["provider"]
|
||||
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
|
||||
if provider, ok := currentConfigurations[providerID]; ok {
|
||||
templatesRenderer.JSON(response, http.StatusOK, provider.Backends)
|
||||
} else {
|
||||
http.NotFound(response, request)
|
||||
}
|
||||
}
|
||||
|
||||
func (provider *WebProvider) getBackendHandler(response http.ResponseWriter, request *http.Request) {
|
||||
vars := mux.Vars(request)
|
||||
providerID := vars["provider"]
|
||||
backendID := vars["backend"]
|
||||
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
|
||||
if provider, ok := currentConfigurations[providerID]; ok {
|
||||
if backend, ok := provider.Backends[backendID]; ok {
|
||||
templatesRenderer.JSON(response, http.StatusOK, backend)
|
||||
return
|
||||
}
|
||||
}
|
||||
http.NotFound(response, request)
|
||||
}
|
||||
|
||||
func (provider *WebProvider) getServersHandler(response http.ResponseWriter, request *http.Request) {
|
||||
vars := mux.Vars(request)
|
||||
providerID := vars["provider"]
|
||||
backendID := vars["backend"]
|
||||
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
|
||||
if provider, ok := currentConfigurations[providerID]; ok {
|
||||
if backend, ok := provider.Backends[backendID]; ok {
|
||||
templatesRenderer.JSON(response, http.StatusOK, backend.Servers)
|
||||
return
|
||||
}
|
||||
}
|
||||
http.NotFound(response, request)
|
||||
}
|
||||
|
||||
func (provider *WebProvider) getServerHandler(response http.ResponseWriter, request *http.Request) {
|
||||
vars := mux.Vars(request)
|
||||
providerID := vars["provider"]
|
||||
backendID := vars["backend"]
|
||||
serverID := vars["server"]
|
||||
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
|
||||
if provider, ok := currentConfigurations[providerID]; ok {
|
||||
if backend, ok := provider.Backends[backendID]; ok {
|
||||
if server, ok := backend.Servers[serverID]; ok {
|
||||
templatesRenderer.JSON(response, http.StatusOK, server)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
http.NotFound(response, request)
|
||||
}
|
||||
|
||||
func (provider *WebProvider) getFrontendsHandler(response http.ResponseWriter, request *http.Request) {
|
||||
vars := mux.Vars(request)
|
||||
providerID := vars["provider"]
|
||||
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
|
||||
if provider, ok := currentConfigurations[providerID]; ok {
|
||||
templatesRenderer.JSON(response, http.StatusOK, provider.Frontends)
|
||||
} else {
|
||||
http.NotFound(response, request)
|
||||
}
|
||||
}
|
||||
|
||||
func (provider *WebProvider) getFrontendHandler(response http.ResponseWriter, request *http.Request) {
|
||||
vars := mux.Vars(request)
|
||||
providerID := vars["provider"]
|
||||
frontendID := vars["frontend"]
|
||||
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
|
||||
if provider, ok := currentConfigurations[providerID]; ok {
|
||||
if frontend, ok := provider.Frontends[frontendID]; ok {
|
||||
templatesRenderer.JSON(response, http.StatusOK, frontend)
|
||||
return
|
||||
}
|
||||
}
|
||||
http.NotFound(response, request)
|
||||
}
|
||||
|
||||
func (provider *WebProvider) getRoutesHandler(response http.ResponseWriter, request *http.Request) {
|
||||
vars := mux.Vars(request)
|
||||
providerID := vars["provider"]
|
||||
frontendID := vars["frontend"]
|
||||
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
|
||||
if provider, ok := currentConfigurations[providerID]; ok {
|
||||
if frontend, ok := provider.Frontends[frontendID]; ok {
|
||||
templatesRenderer.JSON(response, http.StatusOK, frontend.Routes)
|
||||
return
|
||||
}
|
||||
}
|
||||
http.NotFound(response, request)
|
||||
}
|
||||
|
||||
func (provider *WebProvider) getRouteHandler(response http.ResponseWriter, request *http.Request) {
|
||||
|
||||
vars := mux.Vars(request)
|
||||
providerID := vars["provider"]
|
||||
frontendID := vars["frontend"]
|
||||
routeID := vars["route"]
|
||||
currentConfigurations := provider.server.currentConfigurations.Get().(configs)
|
||||
if provider, ok := currentConfigurations[providerID]; ok {
|
||||
if frontend, ok := provider.Frontends[frontendID]; ok {
|
||||
if route, ok := frontend.Routes[routeID]; ok {
|
||||
templatesRenderer.JSON(response, http.StatusOK, route)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
http.NotFound(response, request)
|
||||
}
|
||||
|
||||
func expvarHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
fmt.Fprintf(w, "{\n")
|
||||
first := true
|
||||
expvar.Do(func(kv expvar.KeyValue) {
|
||||
if !first {
|
||||
fmt.Fprintf(w, ",\n")
|
||||
}
|
||||
first = false
|
||||
fmt.Fprintf(w, "%q: %s", kv.Key, kv.Value)
|
||||
})
|
||||
fmt.Fprintf(w, "\n}\n")
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue