Compare commits

..

38 Commits

Author SHA1 Message Date
Vincent Demeester
4729e3e999 Merge pull request #124 from emilevauge/panic-bad-configuration
Add check in invoked method
2015-11-23 20:54:16 +01:00
emile
b0e66a4aa6 Add check invoked method 2015-11-23 16:06:47 +01:00
Vincent Demeester
4218467ab3 Merge pull request #122 from emilevauge/add-getBool-kvprovider
Add GetBool function in KV provider, used by passHostHeader
2015-11-23 08:38:35 +01:00
emile
6e62625ebf Add GetBool function in KV provider, used by passHostHeader 2015-11-22 23:39:43 +01:00
Vincent Demeester
c8a0a83e2b Merge pull request #120 from starpost/docker-tls
Docker TLS support
2015-11-20 18:51:36 +01:00
KM Tong
76bd04e349 Merge branch 'master' into docker-tls 2015-11-20 23:13:26 +08:00
唐家文
a8a78b8ea3 docker TLS support 2015-11-20 23:05:06 +08:00
Emile Vauge
3435ebfe42 Merge pull request #108 from vdemeester/refactor-providers-with-test
Refactor providers and add unit tests
2015-11-19 19:42:03 +01:00
Vincent Demeester
4d485e1b6b Refactor providers and add tests
- Add a `baseProvider` struct with common
- Refactor docker, kv(s) and marathon providers (spliting into small pieces)
- Add unit tests

Signed-off-by: Vincent Demeester <vincent@sbr.pm>
2015-11-19 17:22:17 +01:00
Vincent Demeester
3f905ee7d0 Merge pull request #112 from bennyhansson/master
Add passHostHeader to kv frontend definition.
2015-11-17 16:28:59 +01:00
Benny Hansson
e90cb6b53b Add passHostHeader to frontend definition. 2015-11-16 22:51:52 +01:00
Vincent Demeester
400655f212 Merge pull request #109 from polds/docker/clean-frontend
Replace [ and ] in frontend names
2015-11-13 09:35:14 +01:00
Peter Olds
481a4b2096 Replace [ and ] in frontend names
Signed-off-by: Peter Olds <polds@kyanicorp.com>
2015-11-12 17:04:19 -07:00
Emile Vauge
85bbd49798 Merge pull request #96 from vdemeester/validate-golint
Add validate-golint target and script …
2015-11-08 20:05:01 +01:00
Vincent Demeester
40391c57c2 Add validate-golint target and script …
… and *lint* the latest piece of code.

Signed-off-by: Vincent Demeester <vincent@sbr.pm>
2015-11-06 18:11:57 +01:00
Emile Vauge
7607eb173b Merge pull request #94 from vdemeester/fix-labels-docker
Fix docker labels (frontend.*) non-presence
2015-11-05 15:50:30 +01:00
Vincent Demeester
15318c4631 Fix docker labels (frontend.*)
Using Docker provider, you can specify `traefik.frontend.rule` and
`traefik.frontend.value` labels. If they are not both provided, there is
a default behavior. On the current master, if they are not defined, the
container is filtered (and thus the default behavior is broken).

Fixes that.

Signed-off-by: Vincent Demeester <vincent@sbr.pm>
2015-11-05 15:14:25 +01:00
Emile Vauge
7be566ef7c Merge pull request #93 from vdemeester/integration-test-simple
Updates and additions on some integration tests
2015-11-04 09:12:41 +01:00
Vincent Demeester
3c9ec55f0a Updates and additions on some integration tests
- Use defer to kill traefik process (to fix the still running traefik
  binaries if the given tests is failing before the kill)
- Add TestWithWebConfig
- Add *.test to gitignore to ignore the test binaries generated by go.

Signed-off-by: Vincent Demeester <vincent@sbr.pm>
2015-11-03 23:06:31 +01:00
Emile Vauge
5ee6981410 Merge pull request #92 from vdemeester/linting-some-packages
Linting some packages
2015-11-02 22:47:45 +01:00
Vincent Demeester
c32f82baee Linting types package
Signed-off-by: Vincent Demeester <vincent@sbr.pm>
2015-11-02 21:15:10 +01:00
Vincent Demeester
89bb1ae835 Linting provider package
Signed-off-by: Vincent Demeester <vincent@sbr.pm>
2015-11-02 21:15:03 +01:00
Vincent Demeester
9387235a04 Linting middlewares package
Signed-off-by: Vincent Demeester <vincent@sbr.pm>
2015-11-02 21:14:54 +01:00
Emile Vauge
7766d0ddaa Merge pull request #88 from vdemeester/refactor-package
Refactor traefik with package
2015-11-02 21:08:29 +01:00
Vincent Demeester
cdade5f649 Rename NameProvider to Name
Because golint is gonna cry at some point otherwise.

Signed-off-by: Vincent Demeester <vincent@sbr.pm>
2015-11-02 19:48:34 +01:00
Vincent Demeester
de0a57ec76 Refactor traefik with package
Split a bit traefik into package. The idea behind this refactor is to
start move inter-dependencies away and do some DRY or SRP.

- Adds a `provider` package, with providers except `web.go`
- Adds a `types` package with common struct.
- Move `gen.go` to an `autogen` package

Signed-off-by: Vincent Demeester <vincent@sbr.pm>
2015-11-02 18:35:55 +01:00
Emile Vauge
6e1a0554c0 Merge pull request #91 from vdemeester/go-bindata-out-of-generation
Remove go get go-bindata from generate.go
2015-11-02 16:36:20 +01:00
Vincent Demeester
ae73d08d67 Remove go get go-bindata from generate.go
This mades the build impossible offline (as when doing a go generate it
was trying to go get something)

Signed-off-by: Vincent Demeester <vincent@sbr.pm>
2015-11-02 13:56:55 +01:00
Emile Vauge
ddceefa4e1 Merge pull request #90 from vdemeester/move-version-away
Move version info in its own file.
2015-11-02 10:29:34 +01:00
Vincent Demeester
80cd6c3699 Move version info in its own file.
Signed-off-by: Vincent Demeester <vincent@sbr.pm>
2015-11-02 09:14:49 +01:00
Vincent Demeester
9cfd0a6b26 Merge pull request #87 from emilevauge/add-passhostheader
Add passhostheader in frontends configuration
2015-11-02 09:07:14 +01:00
emile
1e99ecf583 Add passHostHeader in frontend configuration, added traefik.frontend.passHostHeader label 2015-11-02 08:40:54 +01:00
Vincent Demeester
aae7941689 Merge pull request #83 from emilevauge/marathon-filter-healthchecks
Add healthcheck filter in marathon tasks
2015-11-01 22:27:28 +01:00
emile
d888b4fcb5 Added healthcheck filter in marathon tasks 2015-11-01 22:06:05 +01:00
Emile Vauge
b029e7eded Merge pull request #84 from vdemeester/ignore-me
Add .dockerignore to lightweight build context
2015-10-30 13:15:34 +01:00
Vincent Demeester
6f3afe8213 Add .dockerignore to lightweight build context
Ignoring vendor/ and dist/

Signed-off-by: Vincent Demeester <vincent@sbr.pm>
2015-10-30 12:10:13 +01:00
Emile Vauge
b4c019afb6 Merge pull request #85 from vdemeester/make-me-happy
Add a all target than runs default tasks
2015-10-30 12:03:06 +01:00
Vincent Demeester
143ea86ab9 Add a all target than runs default tasks
Signed-off-by: Vincent Demeester <vincent@sbr.pm>
2015-10-30 09:11:43 +01:00
58 changed files with 3318 additions and 939 deletions

3
.dockerignore Normal file
View File

@@ -0,0 +1,3 @@
dist/
vendor/
!dist/traefik

2
.gitignore vendored
View File

@@ -5,5 +5,5 @@ log
*.iml
traefik
traefik.toml
*.test
vendor/

View File

@@ -3,7 +3,8 @@
TRAEFIK_ENVS := \
-e OS_ARCH_ARG \
-e OS_PLATFORM_ARG \
-e TESTFLAGS
-e TESTFLAGS \
-e CIRCLECI
BIND_DIR := "dist"
TRAEFIK_MOUNT := -v "$(CURDIR)/$(BIND_DIR):/go/src/github.com/emilevauge/traefik/$(BIND_DIR)"
@@ -20,6 +21,9 @@ print-%: ; @echo $*=$($*)
default: binary
all: build
$(DOCKER_RUN_TRAEFIK) ./script/make.sh
binary: build
$(DOCKER_RUN_TRAEFIK) ./script/make.sh generate binary
@@ -36,7 +40,7 @@ test-integration: build
$(DOCKER_RUN_TRAEFIK) ./script/make.sh generate test-integration
validate: build
$(DOCKER_RUN_TRAEFIK) ./script/make.sh validate-gofmt validate-govet
$(DOCKER_RUN_TRAEFIK) ./script/make.sh validate-gofmt validate-govet validate-golint
validate-gofmt: build
$(DOCKER_RUN_TRAEFIK) ./script/make.sh validate-gofmt
@@ -44,6 +48,9 @@ validate-gofmt: build
validate-govet: build
$(DOCKER_RUN_TRAEFIK) ./script/make.sh validate-govet
validate-golint: build
$(DOCKER_RUN_TRAEFIK) ./script/make.sh validate-golint
build: dist
docker build -t "$(TRAEFIK_DEV_IMAGE)" -f build.Dockerfile .

View File

@@ -85,6 +85,7 @@ You need either [Docker](https://github.com/docker/docker) and `make`, or `go` a
#### Setting up your `go` environment
- You need `go` v1.5
- You need to set `export GO15VENDOREXPERIMENT=1` environment variable
- You need `go-bindata` to be able to use `go generate` command (needed to build) : `go get github.com/jteeuwen/go-bindata/...`.
- If you clone Træfɪk into something like `~/go/src/github.com/traefik`, your `GOPATH` variable will have to be set to `~/go`: export `GOPATH=~/go`.
#### Using `Docker` and `Makefile`

View File

@@ -4,40 +4,37 @@ Copyright
package main
import (
"net/http"
log "github.com/Sirupsen/logrus"
"github.com/gorilla/mux"
"github.com/mailgun/oxy/utils"
"net/http"
)
// 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 Error level in logrus.
func (oxylogger *OxyLogger) Errorf(format string, args ...interface{}) {
log.Errorf(format, args...)
}
type ErrorHandler struct {
}
func (e *ErrorHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, err error) {
log.Error("server error ", err.Error())
utils.DefaultHandler.ServeHTTP(w, req, err)
}
func notFoundHandler(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r)
//templatesRenderer.HTML(w, http.StatusNotFound, "notFound", nil)
}
// LoadDefaultConfig returns a default gorrilla.mux router from the specified configuration.
func LoadDefaultConfig(globalConfiguration *GlobalConfiguration) *mux.Router {
router := mux.NewRouter()
router.NotFoundHandler = http.HandlerFunc(notFoundHandler)

0
autogen/.placeholder Normal file
View File

View File

@@ -1,14 +0,0 @@
package main
type BoltDbProvider struct {
Watch bool
Endpoint string
Prefix string
Filename string
KvProvider *KvProvider
}
func (provider *BoltDbProvider) Provide(configurationChan chan<- configMessage) error {
provider.KvProvider = NewBoltDbProvider(provider)
return provider.KvProvider.provide(configurationChan)
}

View File

@@ -3,6 +3,8 @@ FROM golang:1.5
RUN go get github.com/Masterminds/glide
RUN go get github.com/mitchellh/gox
RUN go get github.com/tcnksm/ghr
RUN go get github.com/jteeuwen/go-bindata/...
RUN go get github.com/golang/lint/golint
# Which docker version to test on
ENV DOCKER_VERSION 1.6.2

View File

@@ -1,11 +1,16 @@
package main
import (
"errors"
"strings"
fmtlog "log"
"time"
"github.com/BurntSushi/toml"
"github.com/emilevauge/traefik/provider"
"github.com/emilevauge/traefik/types"
)
// 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 {
Port string
GraceTimeOut int64
@@ -14,16 +19,17 @@ type GlobalConfiguration struct {
CertFile, KeyFile string
LogLevel string
ProvidersThrottleDuration time.Duration
Docker *DockerProvider
File *FileProvider
Docker *provider.Docker
File *provider.File
Web *WebProvider
Marathon *MarathonProvider
Consul *ConsulProvider
Etcd *EtcdProvider
Zookeeper *ZookepperProvider
Boltdb *BoltDbProvider
Marathon *provider.Marathon
Consul *provider.Consul
Etcd *provider.Etcd
Zookeeper *provider.Zookepper
Boltdb *provider.BoltDb
}
// NewGlobalConfiguration returns a GlobalConfiguration with default values.
func NewGlobalConfiguration() *GlobalConfiguration {
globalConfiguration := new(GlobalConfiguration)
// default values
@@ -35,78 +41,13 @@ func NewGlobalConfiguration() *GlobalConfiguration {
return globalConfiguration
}
// Backend configuration
type Backend struct {
Servers map[string]Server `json:"servers,omitempty"`
CircuitBreaker *CircuitBreaker `json:"circuitBreaker,omitempty"`
LoadBalancer *LoadBalancer `json:"loadBalancer,omitempty"`
}
// LoadBalancer configuration
type LoadBalancer struct {
Method string `json:"method,omitempty"`
}
// CircuitBreaker configuration
type CircuitBreaker struct {
Expression string `json:"expression,omitempty"`
}
// Server configuration
type Server struct {
URL string `json:"url,omitempty"`
Weight int `json:"weight,omitempty"`
}
// Route configuration
type Route struct {
Rule string `json:"rule,omitempty"`
Value string `json:"value,omitempty"`
}
// Frontend configuration
type Frontend struct {
Backend string `json:"backend,omitempty"`
Routes map[string]Route `json:"routes,omitempty"`
}
// Configuration of a provider
type Configuration struct {
Backends map[string]*Backend `json:"backends,omitempty"`
Frontends map[string]*Frontend `json:"frontends,omitempty"`
}
// Load Balancer Method
type LoadBalancerMethod uint8
const (
// wrr (default) = Weighted Round Robin
wrr LoadBalancerMethod = iota
// drr = Dynamic Round Robin
drr
)
var loadBalancerMethodNames = []string{
"wrr",
"drr",
}
func NewLoadBalancerMethod(loadBalancer *LoadBalancer) (LoadBalancerMethod, error) {
if loadBalancer != nil {
for i, name := range loadBalancerMethodNames {
if strings.EqualFold(name, loadBalancer.Method) {
return LoadBalancerMethod(i), nil
}
}
// LoadFileConfig returns a GlobalConfiguration from reading the specified file (a toml file).
func LoadFileConfig(file string) *GlobalConfiguration {
configuration := NewGlobalConfiguration()
if _, err := toml.DecodeFile(file, configuration); err != nil {
fmtlog.Fatalf("Error reading file: %s", err)
}
return wrr, ErrInvalidLoadBalancerMethod
return configuration
}
var ErrInvalidLoadBalancerMethod = errors.New("Invalid method, using default")
type configMessage struct {
providerName string
configuration *Configuration
}
type configs map[string]*Configuration
type configs map[string]*types.Configuration

View File

@@ -1,14 +0,0 @@
package main
type ConsulProvider struct {
Watch bool
Endpoint string
Prefix string
Filename string
KvProvider *KvProvider
}
func (provider *ConsulProvider) Provide(configurationChan chan<- configMessage) error {
provider.KvProvider = NewConsulProvider(provider)
return provider.KvProvider.provide(configurationChan)
}

239
docker.go
View File

@@ -1,239 +0,0 @@
package main
import (
"bytes"
"errors"
"strconv"
"strings"
"text/template"
"time"
"fmt"
"github.com/BurntSushi/toml"
"github.com/BurntSushi/ty/fun"
log "github.com/Sirupsen/logrus"
"github.com/cenkalti/backoff"
"github.com/fsouza/go-dockerclient"
)
type DockerProvider struct {
Watch bool
Endpoint string
Filename string
Domain string
}
func (provider *DockerProvider) Provide(configurationChan chan<- configMessage) error {
if dockerClient, err := docker.NewClient(provider.Endpoint); err != nil {
log.Errorf("Failed to create a client for docker, error: %s", err)
return err
} else {
err := dockerClient.Ping()
if err != nil {
log.Errorf("Docker connection error %+v", err)
return err
}
log.Debug("Docker connection established")
if provider.Watch {
dockerEvents := make(chan *docker.APIEvents)
dockerClient.AddEventListener(dockerEvents)
log.Debug("Docker listening")
go func() {
operation := func() error {
for {
event := <-dockerEvents
if event == nil {
return errors.New("Docker event nil")
// log.Fatalf("Docker connection error")
}
if event.Status == "start" || event.Status == "die" {
log.Debugf("Docker event receveived %+v", event)
configuration := provider.loadDockerConfig(dockerClient)
if configuration != nil {
configurationChan <- configMessage{"docker", configuration}
}
}
}
}
notify := func(err error, time time.Duration) {
log.Errorf("Docker connection error %+v, retrying in %s", err, time)
}
err := backoff.RetryNotify(operation, backoff.NewExponentialBackOff(), notify)
if err != nil {
log.Fatalf("Cannot connect to docker server %+v", err)
}
}()
}
configuration := provider.loadDockerConfig(dockerClient)
configurationChan <- configMessage{"docker", configuration}
}
return nil
}
func (provider *DockerProvider) loadDockerConfig(dockerClient *docker.Client) *Configuration {
var DockerFuncMap = template.FuncMap{
"getBackend": func(container docker.Container) string {
if label, err := provider.getLabel(container, "traefik.backend"); err == nil {
return label
}
return provider.getEscapedName(container.Name)
},
"getPort": func(container docker.Container) string {
if label, err := provider.getLabel(container, "traefik.port"); err == nil {
return label
}
for key := range container.NetworkSettings.Ports {
return key.Port()
}
return ""
},
"getWeight": func(container docker.Container) string {
if label, err := provider.getLabel(container, "traefik.weight"); err == nil {
return label
}
return "0"
},
"getDomain": func(container docker.Container) string {
if label, err := provider.getLabel(container, "traefik.domain"); err == nil {
return label
}
return provider.Domain
},
"getProtocol": func(container docker.Container) string {
if label, err := provider.getLabel(container, "traefik.protocol"); err == nil {
return label
}
return "http"
},
"getFrontendValue": provider.GetFrontendValue,
"getFrontendRule": provider.GetFrontendRule,
"replace": func(s1 string, s2 string, s3 string) string {
return strings.Replace(s3, s1, s2, -1)
},
}
configuration := new(Configuration)
containerList, _ := dockerClient.ListContainers(docker.ListContainersOptions{})
containersInspected := []docker.Container{}
frontends := map[string][]docker.Container{}
// get inspect containers
for _, container := range containerList {
containerInspected, _ := dockerClient.InspectContainer(container.ID)
containersInspected = append(containersInspected, *containerInspected)
}
// filter containers
filteredContainers := fun.Filter(func(container docker.Container) bool {
if len(container.NetworkSettings.Ports) == 0 {
log.Debugf("Filtering container without port %s", container.Name)
return false
}
_, err := strconv.Atoi(container.Config.Labels["traefik.port"])
if len(container.NetworkSettings.Ports) > 1 && err != nil {
log.Debugf("Filtering container with more than 1 port and no traefik.port label %s", container.Name)
return false
}
if container.Config.Labels["traefik.enable"] == "false" {
log.Debugf("Filtering disabled container %s", container.Name)
return false
}
if _, err := provider.getLabels(container, []string{"traefik.frontend.rule", "traefik.frontend.value"}); err != nil {
log.Debugf("Filtering bad labeled container %s", container.Name)
return false
}
return true
}, containersInspected).([]docker.Container)
for _, container := range filteredContainers {
frontends[provider.getFrontendName(container)] = append(frontends[provider.getFrontendName(container)], container)
}
templateObjects := struct {
Containers []docker.Container
Frontends map[string][]docker.Container
Domain string
}{
filteredContainers,
frontends,
provider.Domain,
}
tmpl := template.New(provider.Filename).Funcs(DockerFuncMap)
if len(provider.Filename) > 0 {
_, err := tmpl.ParseFiles(provider.Filename)
if err != nil {
log.Error("Error reading file", err)
return nil
}
} else {
buf, err := Asset("templates/docker.tmpl")
if err != nil {
log.Error("Error reading file", err)
}
_, err = tmpl.Parse(string(buf))
if err != nil {
log.Error("Error reading file", err)
return nil
}
}
var buffer bytes.Buffer
err := tmpl.Execute(&buffer, templateObjects)
if err != nil {
log.Error("Error with docker template", err)
return nil
}
if _, err := toml.Decode(buffer.String(), configuration); err != nil {
log.Error("Error creating docker configuration ", err)
return nil
}
return configuration
}
func (provider *DockerProvider) getFrontendName(container docker.Container) string {
// Replace '.' with '-' in quoted keys because of this issue https://github.com/BurntSushi/toml/issues/78
frontendName := fmt.Sprintf("%s-%s", provider.GetFrontendRule(container), provider.GetFrontendValue(container))
return strings.Replace(frontendName, ".", "-", -1)
}
func (provider *DockerProvider) getEscapedName(name string) string {
return strings.Replace(name, "/", "", -1)
}
func (provider *DockerProvider) getLabel(container docker.Container, label string) (string, error) {
for key, value := range container.Config.Labels {
if key == label {
return value, nil
}
}
return "", errors.New("Label not found:" + label)
}
func (provider *DockerProvider) getLabels(container docker.Container, labels []string) (map[string]string, error) {
foundLabels := map[string]string{}
for _, label := range labels {
if foundLabel, err := provider.getLabel(container, label); err != nil {
return nil, errors.New("Label not found: " + label)
} else {
foundLabels[label] = foundLabel
}
}
return foundLabels, nil
}
func (provider *DockerProvider) GetFrontendValue(container docker.Container) string {
if label, err := provider.getLabel(container, "traefik.frontend.value"); err == nil {
return label
}
return provider.getEscapedName(container.Name) + "." + provider.Domain
}
func (provider *DockerProvider) GetFrontendRule(container docker.Container) string {
if label, err := provider.getLabel(container, "traefik.frontend.rule"); err == nil {
return label
}
return "Host"
}

View File

@@ -38,6 +38,7 @@ Frontends can be defined using the following rules:
A frontend is a set of rules that forwards the incoming http traffic to a backend.
You can optionally enable `passHostHeader` to forward client `Host` header to the backend.
### HTTP Backends
@@ -163,6 +164,7 @@ logLevel = "DEBUG"
value = "test.localhost"
[frontends.frontend2]
backend = "backend1"
passHostHeader = true
[frontends.frontend2.routes.test_2]
rule = "Path"
value = "/test"
@@ -210,6 +212,7 @@ filename = "rules.toml"
value = "test.localhost"
[frontends.frontend2]
backend = "backend1"
passHostHeader = true
[frontends.frontend2.routes.test_2]
rule = "Path"
value = "/test"
@@ -401,6 +404,14 @@ watch = true
# Optional
#
# filename = "docker.tmpl"
# Enable docker TLS connection
#
# [docker.tls]
# ca = "/etc/ssl/ca.crt"
# cert = "/etc/ssl/docker.crt"
# key = "/etc/ssl/docker.key"
# insecureskipverify = true
```
Labels can be used on containers to override default behaviour:
@@ -412,6 +423,7 @@ Labels can be used on containers to override default behaviour:
- `traefik.enable=false`: disable this container in Træfɪk
- `traefik.frontend.rule=Host`: override the default frontend rule (Default: Host). See [frontends](#frontends).
- `traefik.frontend.value=test.example.com`: override the default frontend value (Default: `{containerName}.{domain}`) See [frontends](#frontends).
- `traefik.frontend.passHostHeader=true`: forward client `Host` header to the backend.
* `traefik.domain=traefik.localhost`: override the default domain
@@ -474,6 +486,7 @@ Labels can be used on containers to override default behaviour:
- `traefik.enable=false`: disable this application in Træfɪk
- `traefik.frontend.rule=Host`: override the default frontend rule (Default: Host). See [frontends](#frontends).
- `traefik.frontend.value=test.example.com`: override the default frontend value (Default: `{appName}.{domain}`) See [frontends](#frontends).
- `traefik.frontend.passHostHeader=true`: forward client `Host` header to the backend.
* `traefik.domain=traefik.localhost`: override the default domain
## <a id="consul"></a> Consul backend
@@ -551,6 +564,7 @@ The Keys-Values structure should look (using `prefix = "/traefik"`):
| Key | Value |
|----------------------------------------------------|------------|
| `/traefik/frontends/frontend2/backend` | `backend1` |
| `/traefik/frontends/frontend2/passHostHeader` | `true` |
| `/traefik/frontends/frontend2/routes/test_2/rule` | `Path` |
| `/traefik/frontends/frontend2/routes/test_2/value` | `/test` |
@@ -630,6 +644,7 @@ The Keys-Values structure should look (using `prefix = "/traefik"`):
| Key | Value |
|----------------------------------------------------|------------|
| `/traefik/frontends/frontend2/backend` | `backend1` |
| `/traefik/frontends/frontend2/passHostHeader` | `true` |
| `/traefik/frontends/frontend2/routes/test_2/rule` | `Path` |
| `/traefik/frontends/frontend2/routes/test_2/value` | `/test` |
@@ -708,6 +723,7 @@ The Keys-Values structure should look (using `prefix = "/traefik"`):
| Key | Value |
|----------------------------------------------------|------------|
| `/traefik/frontends/frontend2/backend` | `backend1` |
| `/traefik/frontends/frontend2/passHostHeader` | `true` |
| `/traefik/frontends/frontend2/routes/test_2/rule` | `Path` |
| `/traefik/frontends/frontend2/routes/test_2/value` | `/test` |

14
etcd.go
View File

@@ -1,14 +0,0 @@
package main
type EtcdProvider struct {
Watch bool
Endpoint string
Prefix string
Filename string
KvProvider *KvProvider
}
func (provider *EtcdProvider) Provide(configurationChan chan<- configMessage) error {
provider.KvProvider = NewEtcdProvider(provider)
return provider.KvProvider.provide(configurationChan)
}

View File

@@ -1 +0,0 @@
package main

View File

@@ -2,9 +2,8 @@
Copyright
*/
//go:generate go get github.com/jteeuwen/go-bindata/...
//go:generate rm -vf gen.go
//go:generate go-bindata -o gen.go static/... templates/...
//go:generate rm -vf autogen/gen.go
//go:generate go-bindata -pkg autogen -o autogen/gen.go ./static/... ./templates/...
//go:generate mkdir -p vendor/github.com/docker/docker/autogen/dockerversion
//go:generate cp script/dockerversion vendor/github.com/docker/docker/autogen/dockerversion/dockerversion.go

View File

@@ -10,6 +10,9 @@ import (
check "gopkg.in/check.v1"
)
// SimpleSuite
type SimpleSuite struct{ BaseSuite }
func (s *SimpleSuite) TestNoOrInexistentConfigShouldFail(c *check.C) {
cmd := exec.Command(traefikBinary)
output, err := cmd.CombinedOutput()
@@ -37,6 +40,7 @@ func (s *SimpleSuite) TestSimpleDefaultConfig(c *check.C) {
cmd := exec.Command(traefikBinary, "fixtures/simple_default.toml")
err := cmd.Start()
c.Assert(err, checker.IsNil)
defer cmd.Process.Kill()
time.Sleep(500 * time.Millisecond)
// TODO validate : run on 80
@@ -45,7 +49,18 @@ func (s *SimpleSuite) TestSimpleDefaultConfig(c *check.C) {
// Expected a 404 as we did not comfigure anything
c.Assert(err, checker.IsNil)
c.Assert(resp.StatusCode, checker.Equals, 404)
killErr := cmd.Process.Kill()
c.Assert(killErr, checker.IsNil)
}
func (s *SimpleSuite) TestWithWebConfig(c *check.C) {
cmd := exec.Command(traefikBinary, "fixtures/simple_web.toml")
err := cmd.Start()
c.Assert(err, checker.IsNil)
defer cmd.Process.Kill()
time.Sleep(500 * time.Millisecond)
resp, err := http.Get("http://127.0.0.1:8080/api")
// Expected a 200
c.Assert(err, checker.IsNil)
c.Assert(resp.StatusCode, checker.Equals, 200)
}

View File

@@ -13,6 +13,7 @@ func (s *ConsulSuite) TestSimpleConfiguration(c *check.C) {
cmd := exec.Command(traefikBinary, "fixtures/consul/simple.toml")
err := cmd.Start()
c.Assert(err, checker.IsNil)
defer cmd.Process.Kill()
time.Sleep(500 * time.Millisecond)
// TODO validate : run on 80
@@ -21,7 +22,4 @@ func (s *ConsulSuite) TestSimpleConfiguration(c *check.C) {
// Expected a 404 as we did not comfigure anything
c.Assert(err, checker.IsNil)
c.Assert(resp.StatusCode, checker.Equals, 404)
killErr := cmd.Process.Kill()
c.Assert(killErr, checker.IsNil)
}

View File

@@ -1,15 +1,140 @@
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"time"
"github.com/docker/docker/opts"
"github.com/docker/docker/pkg/namesgenerator"
"github.com/fsouza/go-dockerclient"
checker "github.com/vdemeester/shakers"
check "gopkg.in/check.v1"
)
var (
// Label added to started container to identify them as part of the integration test
TestLabel = "io.traefik.test"
// Images to have or pull before the build in order to make it work
// FIXME handle this offline but loading them before build
RequiredImages = map[string]string{
"swarm": "1.0.0",
"nginx": "1",
}
)
// Docker test suites
type DockerSuite struct {
BaseSuite
client *docker.Client
}
func (s *DockerSuite) startContainer(c *check.C, image string, args ...string) string {
return s.startContainerWithConfig(c, docker.CreateContainerOptions{
Config: &docker.Config{
Image: image,
Cmd: args,
},
})
}
func (s *DockerSuite) startContainerWithLabels(c *check.C, image string, labels map[string]string, args ...string) string {
return s.startContainerWithConfig(c, docker.CreateContainerOptions{
Config: &docker.Config{
Image: image,
Cmd: args,
Labels: labels,
},
})
}
func (s *DockerSuite) startContainerWithConfig(c *check.C, config docker.CreateContainerOptions) string {
if config.Name == "" {
config.Name = namesgenerator.GetRandomName(10)
}
if config.Config.Labels == nil {
config.Config.Labels = map[string]string{}
}
config.Config.Labels[TestLabel] = "true"
container, err := s.client.CreateContainer(config)
c.Assert(err, checker.IsNil, check.Commentf("Error creating a container using config %v", config))
err = s.client.StartContainer(container.ID, &docker.HostConfig{})
c.Assert(err, checker.IsNil, check.Commentf("Error starting container %v", container))
return container.Name
}
func (s *DockerSuite) SetUpSuite(c *check.C) {
dockerHost := os.Getenv("DOCKER_HOST")
if dockerHost == "" {
// FIXME Handle windows -- see if dockerClient already handle that or not
dockerHost = fmt.Sprintf("unix://%s", opts.DefaultUnixSocket)
}
// Make sure we can speak to docker
dockerClient, err := docker.NewClient(dockerHost)
c.Assert(err, checker.IsNil, check.Commentf("Error connecting to docker daemon"))
s.client = dockerClient
c.Assert(s.client.Ping(), checker.IsNil)
// Pull required images
for repository, tag := range RequiredImages {
image := fmt.Sprintf("%s:%s", repository, tag)
_, err := s.client.InspectImage(image)
if err != nil {
if err != docker.ErrNoSuchImage {
c.Fatalf("Error while inspect image %s", image)
}
err = s.client.PullImage(docker.PullImageOptions{
Repository: repository,
Tag: tag,
}, docker.AuthConfiguration{})
c.Assert(err, checker.IsNil, check.Commentf("Error while pulling image %s", image))
}
}
}
func (s *DockerSuite) cleanContainers(c *check.C) {
// Clean the mess, a.k.a. the running containers with the right label
containerList, err := s.client.ListContainers(docker.ListContainersOptions{
Filters: map[string][]string{
"label": {fmt.Sprintf("%s=true", TestLabel)},
},
})
c.Assert(err, checker.IsNil, check.Commentf("Error listing containers started by traefik"))
for _, container := range containerList {
err = s.client.KillContainer(docker.KillContainerOptions{
ID: container.ID,
})
c.Assert(err, checker.IsNil, check.Commentf("Error killing container %v", container))
if os.Getenv("CIRCLECI") == "" {
// On circleci, we won't delete them — it errors out for now >_<
err = s.client.RemoveContainer(docker.RemoveContainerOptions{
ID: container.ID,
RemoveVolumes: true,
})
c.Assert(err, checker.IsNil, check.Commentf("Error removing container %v", container))
}
}
}
func (s *DockerSuite) TearDownTest(c *check.C) {
s.cleanContainers(c)
}
func (s *DockerSuite) TearDownSuite(c *check.C) {
// Call cleanContainers, just in case (?)
// s.cleanContainers(c)
}
func (s *DockerSuite) TestSimpleConfiguration(c *check.C) {
file := s.adaptFileForHost(c, "fixtures/docker/simple.toml")
defer os.Remove(file)
@@ -17,15 +142,110 @@ func (s *DockerSuite) TestSimpleConfiguration(c *check.C) {
cmd := exec.Command(traefikBinary, file)
err := cmd.Start()
c.Assert(err, checker.IsNil)
defer cmd.Process.Kill()
time.Sleep(500 * time.Millisecond)
// TODO validate : run on 80
resp, err := http.Get("http://127.0.0.1/")
c.Assert(err, checker.IsNil)
// Expected a 404 as we did not comfigure anything
c.Assert(resp.StatusCode, checker.Equals, 404)
}
func (s *DockerSuite) TestDefaultDockerContainers(c *check.C) {
file := s.adaptFileForHost(c, "fixtures/docker/simple.toml")
defer os.Remove(file)
name := s.startContainer(c, "swarm:1.0.0", "manage", "token://blablabla")
// Start traefik
cmd := exec.Command(traefikBinary, file)
err := cmd.Start()
c.Assert(err, checker.IsNil)
defer cmd.Process.Kill()
// FIXME Need to wait than 500 milliseconds more (for swarm or traefik to boot up ?)
time.Sleep(1500 * time.Millisecond)
client := &http.Client{}
req, err := http.NewRequest("GET", "http://127.0.0.1/version", nil)
c.Assert(err, checker.IsNil)
req.Host = fmt.Sprintf("%s.docker.localhost", name)
resp, err := client.Do(req)
c.Assert(err, checker.IsNil)
c.Assert(resp.StatusCode, checker.Equals, 200)
body, err := ioutil.ReadAll(resp.Body)
c.Assert(err, checker.IsNil)
var version map[string]interface{}
c.Assert(json.Unmarshal(body, &version), checker.IsNil)
c.Assert(version["Version"], checker.Equals, "swarm/1.0.0")
}
func (s *DockerSuite) TestDockerContainersWithLabels(c *check.C) {
file := s.adaptFileForHost(c, "fixtures/docker/simple.toml")
defer os.Remove(file)
// Start a container with some labels
labels := map[string]string{
"traefik.frontend.rule": "Host",
"traefik.frontend.value": "my.super.host",
}
s.startContainerWithLabels(c, "swarm:1.0.0", labels, "manage", "token://blabla")
// Start traefik
cmd := exec.Command(traefikBinary, file)
err := cmd.Start()
c.Assert(err, checker.IsNil)
defer cmd.Process.Kill()
// FIXME Need to wait than 500 milliseconds more (for swarm or traefik to boot up ?)
time.Sleep(1500 * time.Millisecond)
client := &http.Client{}
req, err := http.NewRequest("GET", "http://127.0.0.1/version", nil)
c.Assert(err, checker.IsNil)
req.Host = fmt.Sprintf("my.super.host")
resp, err := client.Do(req)
c.Assert(err, checker.IsNil)
c.Assert(resp.StatusCode, checker.Equals, 200)
body, err := ioutil.ReadAll(resp.Body)
c.Assert(err, checker.IsNil)
var version map[string]interface{}
c.Assert(json.Unmarshal(body, &version), checker.IsNil)
c.Assert(version["Version"], checker.Equals, "swarm/1.0.0")
}
func (s *DockerSuite) TestDockerContainersWithOneMissingLabels(c *check.C) {
file := s.adaptFileForHost(c, "fixtures/docker/simple.toml")
defer os.Remove(file)
// Start a container with some labels
labels := map[string]string{
"traefik.frontend.value": "my.super.host",
}
s.startContainerWithLabels(c, "swarm:1.0.0", labels, "manage", "token://blabla")
// Start traefik
cmd := exec.Command(traefikBinary, file)
err := cmd.Start()
c.Assert(err, checker.IsNil)
defer cmd.Process.Kill()
// FIXME Need to wait than 500 milliseconds more (for swarm or traefik to boot up ?)
time.Sleep(1500 * time.Millisecond)
client := &http.Client{}
req, err := http.NewRequest("GET", "http://127.0.0.1/version", nil)
c.Assert(err, checker.IsNil)
req.Host = fmt.Sprintf("my.super.host")
resp, err := client.Do(req)
c.Assert(err, checker.IsNil)
c.Assert(resp.StatusCode, checker.Equals, 404)
killErr := cmd.Process.Kill()
c.Assert(killErr, checker.IsNil)
}

View File

@@ -13,16 +13,14 @@ func (s *FileSuite) TestSimpleConfiguration(c *check.C) {
cmd := exec.Command(traefikBinary, "fixtures/file/simple.toml")
err := cmd.Start()
c.Assert(err, checker.IsNil)
defer cmd.Process.Kill()
time.Sleep(500 * time.Millisecond)
time.Sleep(1000 * time.Millisecond)
resp, err := http.Get("http://127.0.0.1/")
// Expected a 404 as we did not configure anything
c.Assert(err, checker.IsNil)
c.Assert(resp.StatusCode, checker.Equals, 404)
killErr := cmd.Process.Kill()
c.Assert(killErr, checker.IsNil)
}
// #56 regression test, make sure it does not fail
@@ -30,14 +28,12 @@ func (s *FileSuite) TestSimpleConfigurationNoPanic(c *check.C) {
cmd := exec.Command(traefikBinary, "fixtures/file/56-simple-panic.toml")
err := cmd.Start()
c.Assert(err, checker.IsNil)
defer cmd.Process.Kill()
time.Sleep(500 * time.Millisecond)
time.Sleep(1000 * time.Millisecond)
resp, err := http.Get("http://127.0.0.1/")
// Expected a 404 as we did not configure anything
c.Assert(err, checker.IsNil)
c.Assert(resp.StatusCode, checker.Equals, 404)
killErr := cmd.Process.Kill()
c.Assert(killErr, checker.IsNil)
}

View File

@@ -0,0 +1,5 @@
logLevel = "DEBUG"
[web]
address = ":8080"

View File

@@ -32,9 +32,6 @@ func init() {
var traefikBinary = "../dist/traefik"
// SimpleSuite
type SimpleSuite struct{ BaseSuite }
// File test suites
type FileSuite struct{ BaseSuite }
@@ -44,17 +41,6 @@ func (s *FileSuite) SetUpSuite(c *check.C) {
s.composeProject.Up()
}
// Docker test suites
type DockerSuite struct{ BaseSuite }
func (s *DockerSuite) SetUpSuite(c *check.C) {
// Make sure we can speak to docker
}
func (s *DockerSuite) TearDownSuite(c *check.C) {
// Clean the mess
}
// Consul test suites (using libcompose)
type ConsulSuite struct{ BaseSuite }

View File

@@ -13,6 +13,7 @@ func (s *MarathonSuite) TestSimpleConfiguration(c *check.C) {
cmd := exec.Command(traefikBinary, "fixtures/marathon/simple.toml")
err := cmd.Start()
c.Assert(err, checker.IsNil)
defer cmd.Process.Kill()
time.Sleep(500 * time.Millisecond)
// TODO validate : run on 80
@@ -21,7 +22,4 @@ func (s *MarathonSuite) TestSimpleConfiguration(c *check.C) {
// Expected a 404 as we did not configure anything
c.Assert(err, checker.IsNil)
c.Assert(resp.StatusCode, checker.Equals, 404)
killErr := cmd.Process.Kill()
c.Assert(killErr, checker.IsNil)
}

196
kv.go
View File

@@ -1,196 +0,0 @@
/*
Copyright
*/
package main
import (
"bytes"
"github.com/docker/libkv"
"github.com/docker/libkv/store/boltdb"
"github.com/docker/libkv/store/consul"
"github.com/docker/libkv/store/etcd"
"github.com/docker/libkv/store/zookeeper"
"strings"
"text/template"
"errors"
"github.com/BurntSushi/toml"
"github.com/BurntSushi/ty/fun"
log "github.com/Sirupsen/logrus"
"github.com/docker/libkv/store"
"time"
)
type KvProvider struct {
Watch bool
Endpoint string
Prefix string
Filename string
StoreType store.Backend
kvclient store.Store
}
func NewConsulProvider(provider *ConsulProvider) *KvProvider {
kvProvider := new(KvProvider)
kvProvider.Watch = provider.Watch
kvProvider.Endpoint = provider.Endpoint
kvProvider.Prefix = provider.Prefix
kvProvider.Filename = provider.Filename
kvProvider.StoreType = store.CONSUL
return kvProvider
}
func NewEtcdProvider(provider *EtcdProvider) *KvProvider {
kvProvider := new(KvProvider)
kvProvider.Watch = provider.Watch
kvProvider.Endpoint = provider.Endpoint
kvProvider.Prefix = provider.Prefix
kvProvider.Filename = provider.Filename
kvProvider.StoreType = store.ETCD
return kvProvider
}
func NewZkProvider(provider *ZookepperProvider) *KvProvider {
kvProvider := new(KvProvider)
kvProvider.Watch = provider.Watch
kvProvider.Endpoint = provider.Endpoint
kvProvider.Prefix = provider.Prefix
kvProvider.Filename = provider.Filename
kvProvider.StoreType = store.ZK
return kvProvider
}
func NewBoltDbProvider(provider *BoltDbProvider) *KvProvider {
kvProvider := new(KvProvider)
kvProvider.Watch = provider.Watch
kvProvider.Endpoint = provider.Endpoint
kvProvider.Prefix = provider.Prefix
kvProvider.Filename = provider.Filename
kvProvider.StoreType = store.BOLTDB
return kvProvider
}
func (provider *KvProvider) provide(configurationChan chan<- configMessage) error {
switch provider.StoreType {
case store.CONSUL:
consul.Register()
case store.ETCD:
etcd.Register()
case store.ZK:
zookeeper.Register()
case store.BOLTDB:
boltdb.Register()
default:
return errors.New("Invalid kv store: " + string(provider.StoreType))
}
kv, err := libkv.NewStore(
provider.StoreType,
[]string{provider.Endpoint},
&store.Config{
ConnectionTimeout: 30 * time.Second,
Bucket: "traefik",
},
)
if err != nil {
return err
}
if _, err := kv.List(""); err != nil {
return err
}
provider.kvclient = kv
if provider.Watch {
stopCh := make(chan struct{})
chanKeys, err := kv.WatchTree(provider.Prefix, stopCh)
if err != nil {
return err
}
go func() {
for {
<-chanKeys
configuration := provider.loadConfig()
if configuration != nil {
configurationChan <- configMessage{string(provider.StoreType), configuration}
}
defer close(stopCh)
}
}()
}
configuration := provider.loadConfig()
configurationChan <- configMessage{string(provider.StoreType), configuration}
return nil
}
func (provider *KvProvider) loadConfig() *Configuration {
configuration := new(Configuration)
templateObjects := struct {
Prefix string
}{
provider.Prefix,
}
var KvFuncMap = template.FuncMap{
"List": func(keys ...string) []string {
joinedKeys := strings.Join(keys, "")
keysPairs, err := provider.kvclient.List(joinedKeys)
if err != nil {
log.Error("Error getting keys: ", joinedKeys, err)
return nil
}
directoryKeys := make(map[string]string)
for _, key := range keysPairs {
directory := strings.Split(strings.TrimPrefix(key.Key, strings.TrimPrefix(joinedKeys, "/")), "/")[0]
directoryKeys[directory] = joinedKeys + directory
}
return fun.Values(directoryKeys).([]string)
},
"Get": func(keys ...string) string {
joinedKeys := strings.Join(keys, "")
keyPair, err := provider.kvclient.Get(joinedKeys)
if err != nil {
log.Debug("Error getting key: ", joinedKeys, err)
return ""
} else if keyPair == nil {
return ""
}
return string(keyPair.Value)
},
"Last": func(key string) string {
splittedKey := strings.Split(key, "/")
return splittedKey[len(splittedKey)-1]
},
}
tmpl := template.New(provider.Filename).Funcs(KvFuncMap)
if len(provider.Filename) > 0 {
_, err := tmpl.ParseFiles(provider.Filename)
if err != nil {
log.Error("Error reading file", err)
return nil
}
} else {
buf, err := Asset("templates/kv.tmpl")
if err != nil {
log.Error("Error reading file", err)
}
_, err = tmpl.Parse(string(buf))
if err != nil {
log.Error("Error reading file", err)
return nil
}
}
var buffer bytes.Buffer
err := tmpl.Execute(&buffer, templateObjects)
if err != nil {
log.Error("Error with kv template:", err)
return nil
}
if _, err := toml.Decode(buffer.String(), configuration); err != nil {
log.Error("Error creating kv configuration:", err)
log.Error(buffer.String())
return nil
}
return configuration
}

View File

@@ -1,230 +0,0 @@
package main
import (
"bytes"
"strconv"
"strings"
"text/template"
"errors"
"github.com/BurntSushi/toml"
"github.com/BurntSushi/ty/fun"
log "github.com/Sirupsen/logrus"
"github.com/gambol99/go-marathon"
)
type MarathonProvider struct {
Watch bool
Endpoint string
marathonClient marathon.Marathon
Domain string
Filename string
NetworkInterface string
}
func (provider *MarathonProvider) Provide(configurationChan chan<- configMessage) error {
config := marathon.NewDefaultConfig()
config.URL = provider.Endpoint
config.EventsInterface = provider.NetworkInterface
client, err := marathon.NewClient(config)
if err != nil {
log.Errorf("Failed to create a client for marathon, error: %s", err)
return err
}
provider.marathonClient = client
update := make(marathon.EventsChannel, 5)
if provider.Watch {
if err := client.AddEventsListener(update, marathon.EVENTS_APPLICATIONS); err != nil {
log.Errorf("Failed to register for subscriptions, %s", err)
} else {
go func() {
for {
event := <-update
log.Debug("Marathon event receveived", event)
configuration := provider.loadMarathonConfig()
if configuration != nil {
configurationChan <- configMessage{"marathon", configuration}
}
}
}()
}
}
configuration := provider.loadMarathonConfig()
configurationChan <- configMessage{"marathon", configuration}
return nil
}
func (provider *MarathonProvider) loadMarathonConfig() *Configuration {
var MarathonFuncMap = template.FuncMap{
"getPort": func(task marathon.Task) string {
for _, port := range task.Ports {
return strconv.Itoa(port)
}
return ""
},
"getWeight": func(task marathon.Task, applications []marathon.Application) string {
application, errApp := getApplication(task, applications)
if errApp != nil {
log.Errorf("Unable to get marathon application from task %s", task.AppID)
return "0"
}
if label, err := provider.getLabel(application, "traefik.weight"); err == nil {
return label
}
return "0"
},
"getDomain": func(application marathon.Application) string {
if label, err := provider.getLabel(application, "traefik.domain"); err == nil {
return label
}
return provider.Domain
},
"replace": func(s1 string, s2 string, s3 string) string {
return strings.Replace(s3, s1, s2, -1)
},
"getProtocol": func(task marathon.Task, applications []marathon.Application) string {
application, errApp := getApplication(task, applications)
if errApp != nil {
log.Errorf("Unable to get marathon application from task %s", task.AppID)
return "http"
}
if label, err := provider.getLabel(application, "traefik.protocol"); err == nil {
return label
}
return "http"
},
"getFrontendValue": provider.GetFrontendValue,
"getFrontendRule": provider.GetFrontendRule,
}
configuration := new(Configuration)
applications, err := provider.marathonClient.Applications(nil)
if err != nil {
log.Errorf("Failed to create a client for marathon, error: %s", err)
return nil
}
tasks, err := provider.marathonClient.AllTasks()
if err != nil {
log.Errorf("Failed to create a client for marathon, error: %s", err)
return nil
}
//filter tasks
filteredTasks := fun.Filter(func(task marathon.Task) bool {
if len(task.Ports) == 0 {
log.Debug("Filtering marathon task without port", task.AppID)
return false
}
application, errApp := getApplication(task, applications.Apps)
if errApp != nil {
log.Errorf("Unable to get marathon application from task %s", task.AppID)
return false
}
_, err := strconv.Atoi(application.Labels["traefik.port"])
if len(application.Ports) > 1 && err != nil {
log.Debug("Filtering marathon task with more than 1 port and no traefik.port label", task.AppID)
return false
}
if application.Labels["traefik.enable"] == "false" {
log.Debug("Filtering disabled marathon task", task.AppID)
return false
}
return true
}, tasks.Tasks).([]marathon.Task)
//filter apps
filteredApps := fun.Filter(func(app marathon.Application) bool {
//get ports from app tasks
if !fun.Exists(func(task marathon.Task) bool {
if task.AppID == app.ID {
return true
}
return false
}, filteredTasks) {
return false
}
return true
}, applications.Apps).([]marathon.Application)
templateObjects := struct {
Applications []marathon.Application
Tasks []marathon.Task
Domain string
}{
filteredApps,
filteredTasks,
provider.Domain,
}
tmpl := template.New(provider.Filename).Funcs(MarathonFuncMap)
if len(provider.Filename) > 0 {
_, err := tmpl.ParseFiles(provider.Filename)
if err != nil {
log.Error("Error reading file", err)
return nil
}
} else {
buf, err := Asset("templates/marathon.tmpl")
if err != nil {
log.Error("Error reading file", err)
}
_, err = tmpl.Parse(string(buf))
if err != nil {
log.Error("Error reading file", err)
return nil
}
}
var buffer bytes.Buffer
err = tmpl.Execute(&buffer, templateObjects)
if err != nil {
log.Error("Error with marathon template:", err)
return nil
}
if _, err := toml.Decode(buffer.String(), configuration); err != nil {
log.Error("Error creating marathon configuration:", err)
return nil
}
return configuration
}
func getApplication(task marathon.Task, apps []marathon.Application) (marathon.Application, error) {
for _, application := range apps {
if application.ID == task.AppID {
return application, nil
}
}
return marathon.Application{}, errors.New("Application not found: " + task.AppID)
}
func (provider *MarathonProvider) getLabel(application marathon.Application, label string) (string, error) {
for key, value := range application.Labels {
if key == label {
return value, nil
}
}
return "", errors.New("Label not found:" + label)
}
func (provider *MarathonProvider) getEscapedName(name string) string {
return strings.Replace(name, "/", "", -1)
}
func (provider *MarathonProvider) GetFrontendValue(application marathon.Application) string {
if label, err := provider.getLabel(application, "traefik.frontend.value"); err == nil {
return label
}
return provider.getEscapedName(application.ID) + "." + provider.Domain
}
func (provider *MarathonProvider) GetFrontendRule(application marathon.Application) string {
if label, err := provider.getLabel(application, "traefik.frontend.rule"); err == nil {
return label
}
return "Host"
}

View File

@@ -1,6 +1,3 @@
/*
Copyright
*/
package middlewares
import (
@@ -9,10 +6,12 @@ import (
"github.com/mailgun/oxy/cbreaker"
)
// CircuitBreaker holds the oxy circuit breaker.
type CircuitBreaker struct {
circuitBreaker *cbreaker.CircuitBreaker
}
// NewCircuitBreaker returns a new CircuitBreaker.
func NewCircuitBreaker(next http.Handler, expression string, options ...cbreaker.CircuitBreakerOption) *CircuitBreaker {
circuitBreaker, _ := cbreaker.New(next, expression, options...)
return &CircuitBreaker{circuitBreaker}

View File

@@ -1,6 +1,3 @@
/*
Copyright
*/
package middlewares
import (
@@ -16,7 +13,7 @@ type Logger struct {
file *os.File
}
// NewLogger returns a new Logger instance
// NewLogger returns a new Logger instance.
func NewLogger(file string) *Logger {
if len(file) > 0 {
fi, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
@@ -36,6 +33,7 @@ func (l *Logger) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.Ha
}
}
// Close closes the logger (i.e. the file).
func (l *Logger) Close() {
l.file.Close()
}

View File

@@ -1,6 +1,3 @@
/*
Copyright
*/
package middlewares
import (
@@ -11,10 +8,12 @@ import (
"github.com/gorilla/mux"
)
// Routes holds the gorilla mux routes (for the API & co).
type Routes struct {
router *mux.Router
}
// NewRoutes return a Routes based on the given router.
func NewRoutes(router *mux.Router) *Routes {
return &Routes{router}
}

View File

@@ -1,20 +1,20 @@
/*
Copyright
*/
package middlewares
import (
log "github.com/Sirupsen/logrus"
"github.com/mailgun/oxy/roundrobin"
"net/http"
"strings"
"time"
log "github.com/Sirupsen/logrus"
"github.com/mailgun/oxy/roundrobin"
)
// WebsocketUpgrader holds Websocket configuration.
type WebsocketUpgrader struct {
rr *roundrobin.RoundRobin
}
// NewWebsocketUpgrader returns a new WebsocketUpgrader.
func NewWebsocketUpgrader(rr *roundrobin.RoundRobin) *WebsocketUpgrader {
wu := WebsocketUpgrader{
rr: rr,

View File

@@ -1,5 +0,0 @@
package main
type Provider interface {
Provide(configurationChan chan<- configMessage) error
}

20
provider/boltdb.go Normal file
View File

@@ -0,0 +1,20 @@
package provider
import (
"github.com/docker/libkv/store"
"github.com/docker/libkv/store/boltdb"
"github.com/emilevauge/traefik/types"
)
// BoltDb holds configurations of the BoltDb provider.
type BoltDb struct {
Kv
}
// Provide allows the provider to provide configurations to traefik
// using the given configuration channel.
func (provider *BoltDb) Provide(configurationChan chan<- types.ConfigMessage) error {
provider.StoreType = store.BOLTDB
boltdb.Register()
return provider.provide(configurationChan)
}

20
provider/consul.go Normal file
View File

@@ -0,0 +1,20 @@
package provider
import (
"github.com/docker/libkv/store"
"github.com/docker/libkv/store/consul"
"github.com/emilevauge/traefik/types"
)
// Consul holds configurations of the Consul provider.
type Consul struct {
Kv
}
// Provide allows the provider to provide configurations to traefik
// using the given configuration channel.
func (provider *Consul) Provide(configurationChan chan<- types.ConfigMessage) error {
provider.StoreType = store.CONSUL
consul.Register()
return provider.provide(configurationChan)
}

272
provider/docker.go Normal file
View File

@@ -0,0 +1,272 @@
package provider
import (
"errors"
"fmt"
"strconv"
"strings"
"text/template"
"time"
"github.com/BurntSushi/ty/fun"
log "github.com/Sirupsen/logrus"
"github.com/cenkalti/backoff"
"github.com/emilevauge/traefik/types"
"github.com/fsouza/go-dockerclient"
)
// Docker holds configurations of the Docker provider.
type Docker struct {
baseProvider
Endpoint string
Domain string
TLS *DockerTLS
}
// DockerTLS holds TLS specific configurations
type DockerTLS struct {
CA string
Cert string
Key string
InsecureSkipVerify bool
}
// Provide allows the provider to provide configurations to traefik
// using the given configuration channel.
func (provider *Docker) Provide(configurationChan chan<- types.ConfigMessage) error {
var dockerClient *docker.Client
var err error
if provider.TLS != nil {
dockerClient, err = docker.NewTLSClient(provider.Endpoint,
provider.TLS.Cert, provider.TLS.Key, provider.TLS.CA)
if err == nil {
dockerClient.TLSConfig.InsecureSkipVerify = provider.TLS.InsecureSkipVerify
}
} else {
dockerClient, err = docker.NewClient(provider.Endpoint)
}
if err != nil {
log.Errorf("Failed to create a client for docker, error: %s", err)
return err
}
err = dockerClient.Ping()
if err != nil {
log.Errorf("Docker connection error %+v", err)
return err
}
log.Debug("Docker connection established")
if provider.Watch {
dockerEvents := make(chan *docker.APIEvents)
dockerClient.AddEventListener(dockerEvents)
log.Debug("Docker listening")
go func() {
operation := func() error {
for {
event := <-dockerEvents
if event == nil {
return errors.New("Docker event nil")
// log.Fatalf("Docker connection error")
}
if event.Status == "start" || event.Status == "die" {
log.Debugf("Docker event receveived %+v", event)
configuration := provider.loadDockerConfig(listContainers(dockerClient))
if configuration != nil {
configurationChan <- types.ConfigMessage{
ProviderName: "docker",
Configuration: configuration,
}
}
}
}
}
notify := func(err error, time time.Duration) {
log.Errorf("Docker connection error %+v, retrying in %s", err, time)
}
err := backoff.RetryNotify(operation, backoff.NewExponentialBackOff(), notify)
if err != nil {
log.Fatalf("Cannot connect to docker server %+v", err)
}
}()
}
configuration := provider.loadDockerConfig(listContainers(dockerClient))
configurationChan <- types.ConfigMessage{
ProviderName: "docker",
Configuration: configuration,
}
return nil
}
func (provider *Docker) loadDockerConfig(containersInspected []docker.Container) *types.Configuration {
var DockerFuncMap = template.FuncMap{
"getBackend": provider.getBackend,
"getPort": provider.getPort,
"getWeight": provider.getWeight,
"getDomain": provider.getDomain,
"getProtocol": provider.getProtocol,
"getPassHostHeader": provider.getPassHostHeader,
"getFrontendValue": provider.getFrontendValue,
"getFrontendRule": provider.getFrontendRule,
"replace": replace,
}
// filter containers
filteredContainers := fun.Filter(containerFilter, containersInspected).([]docker.Container)
frontends := map[string][]docker.Container{}
for _, container := range filteredContainers {
frontends[provider.getFrontendName(container)] = append(frontends[provider.getFrontendName(container)], container)
}
templateObjects := struct {
Containers []docker.Container
Frontends map[string][]docker.Container
Domain string
}{
filteredContainers,
frontends,
provider.Domain,
}
configuration, err := provider.getConfiguration("templates/docker.tmpl", DockerFuncMap, templateObjects)
if err != nil {
log.Error(err)
}
return configuration
}
func containerFilter(container docker.Container) bool {
if len(container.NetworkSettings.Ports) == 0 {
log.Debugf("Filtering container without port %s", container.Name)
return false
}
_, err := strconv.Atoi(container.Config.Labels["traefik.port"])
if len(container.NetworkSettings.Ports) > 1 && err != nil {
log.Debugf("Filtering container with more than 1 port and no traefik.port label %s", container.Name)
return false
}
if container.Config.Labels["traefik.enable"] == "false" {
log.Debugf("Filtering disabled container %s", container.Name)
return false
}
labels, err := getLabels(container, []string{"traefik.frontend.rule", "traefik.frontend.value"})
if len(labels) != 0 && err != nil {
log.Debugf("Filtering bad labeled container %s", container.Name)
return false
}
return true
}
func (provider *Docker) getFrontendName(container docker.Container) string {
// Replace '.' with '-' in quoted keys because of this issue https://github.com/BurntSushi/toml/issues/78
frontendName := fmt.Sprintf("%s-%s", provider.getFrontendRule(container), provider.getFrontendValue(container))
frontendName = strings.Replace(frontendName, "[", "", -1)
frontendName = strings.Replace(frontendName, "]", "", -1)
return strings.Replace(frontendName, ".", "-", -1)
}
// GetFrontendValue returns the frontend value for the specified container, using
// it's label. It returns a default one if the label is not present.
func (provider *Docker) getFrontendValue(container docker.Container) string {
if label, err := getLabel(container, "traefik.frontend.value"); err == nil {
return label
}
return getEscapedName(container.Name) + "." + provider.Domain
}
// GetFrontendRule returns the frontend rule for the specified container, using
// it's label. It returns a default one (Host) if the label is not present.
func (provider *Docker) getFrontendRule(container docker.Container) string {
if label, err := getLabel(container, "traefik.frontend.rule"); err == nil {
return label
}
return "Host"
}
func (provider *Docker) getBackend(container docker.Container) string {
if label, err := getLabel(container, "traefik.backend"); err == nil {
return label
}
return getEscapedName(container.Name)
}
func (provider *Docker) getPort(container docker.Container) string {
if label, err := getLabel(container, "traefik.port"); err == nil {
return label
}
for key := range container.NetworkSettings.Ports {
return key.Port()
}
return ""
}
func (provider *Docker) getWeight(container docker.Container) string {
if label, err := getLabel(container, "traefik.weight"); err == nil {
return label
}
return "0"
}
func (provider *Docker) getDomain(container docker.Container) string {
if label, err := getLabel(container, "traefik.domain"); err == nil {
return label
}
return provider.Domain
}
func (provider *Docker) getProtocol(container docker.Container) string {
if label, err := getLabel(container, "traefik.protocol"); err == nil {
return label
}
return "http"
}
func (provider *Docker) getPassHostHeader(container docker.Container) string {
if passHostHeader, err := getLabel(container, "traefik.frontend.passHostHeader"); err == nil {
return passHostHeader
}
return "false"
}
func getLabel(container docker.Container, label string) (string, error) {
for key, value := range container.Config.Labels {
if key == label {
return value, nil
}
}
return "", errors.New("Label not found:" + label)
}
func getLabels(container docker.Container, labels []string) (map[string]string, error) {
var globalErr error
foundLabels := map[string]string{}
for _, label := range labels {
foundLabel, err := getLabel(container, label)
// Error out only if one of them is defined.
if err != nil {
globalErr = errors.New("Label not found: " + label)
continue
}
foundLabels[label] = foundLabel
}
return foundLabels, globalErr
}
func listContainers(dockerClient *docker.Client) []docker.Container {
containerList, _ := dockerClient.ListContainers(docker.ListContainersOptions{})
containersInspected := []docker.Container{}
// get inspect containers
for _, container := range containerList {
containerInspected, _ := dockerClient.InspectContainer(container.ID)
containersInspected = append(containersInspected, *containerInspected)
}
return containersInspected
}

788
provider/docker_test.go Normal file
View File

@@ -0,0 +1,788 @@
package provider
import (
"reflect"
"strings"
"testing"
"github.com/emilevauge/traefik/types"
"github.com/fsouza/go-dockerclient"
)
func TestDockerGetFrontendName(t *testing.T) {
provider := &Docker{
Domain: "docker.localhost",
}
containers := []struct {
container docker.Container
expected string
}{
{
container: docker.Container{
Name: "foo",
Config: &docker.Config{},
},
expected: "Host-foo-docker-localhost",
},
{
container: docker.Container{
Name: "bar",
Config: &docker.Config{
Labels: map[string]string{
"traefik.frontend.rule": "Header",
},
},
},
expected: "Header-bar-docker-localhost",
},
{
container: docker.Container{
Name: "test",
Config: &docker.Config{
Labels: map[string]string{
"traefik.frontend.value": "foo.bar",
},
},
},
expected: "Host-foo-bar",
},
{
container: docker.Container{
Name: "test",
Config: &docker.Config{
Labels: map[string]string{
"traefik.frontend.value": "foo.bar",
"traefik.frontend.rule": "Header",
},
},
},
expected: "Header-foo-bar",
},
{
container: docker.Container{
Name: "test",
Config: &docker.Config{
Labels: map[string]string{
"traefik.frontend.value": "[foo.bar]",
"traefik.frontend.rule": "Header",
},
},
},
expected: "Header-foo-bar",
},
}
for _, e := range containers {
actual := provider.getFrontendName(e.container)
if actual != e.expected {
t.Fatalf("expected %q, got %q", e.expected, actual)
}
}
}
func TestDockerGetFrontendValue(t *testing.T) {
provider := &Docker{
Domain: "docker.localhost",
}
containers := []struct {
container docker.Container
expected string
}{
{
container: docker.Container{
Name: "foo",
Config: &docker.Config{},
},
expected: "foo.docker.localhost",
},
{
container: docker.Container{
Name: "bar",
Config: &docker.Config{},
},
expected: "bar.docker.localhost",
},
{
container: docker.Container{
Name: "test",
Config: &docker.Config{
Labels: map[string]string{
"traefik.frontend.value": "foo.bar",
},
},
},
expected: "foo.bar",
},
}
for _, e := range containers {
actual := provider.getFrontendValue(e.container)
if actual != e.expected {
t.Fatalf("expected %q, got %q", e.expected, actual)
}
}
}
func TestDockerGetFrontendRule(t *testing.T) {
provider := &Docker{}
containers := []struct {
container docker.Container
expected string
}{
{
container: docker.Container{
Name: "foo",
Config: &docker.Config{},
},
expected: "Host",
},
{
container: docker.Container{
Name: "test",
Config: &docker.Config{
Labels: map[string]string{
"traefik.frontend.rule": "foo",
},
},
},
expected: "foo",
},
}
for _, e := range containers {
actual := provider.getFrontendRule(e.container)
if actual != e.expected {
t.Fatalf("expected %q, got %q", e.expected, actual)
}
}
}
func TestDockerGetBackend(t *testing.T) {
provider := &Docker{}
containers := []struct {
container docker.Container
expected string
}{
{
container: docker.Container{
Name: "foo",
Config: &docker.Config{},
},
expected: "foo",
},
{
container: docker.Container{
Name: "bar",
Config: &docker.Config{},
},
expected: "bar",
},
{
container: docker.Container{
Name: "test",
Config: &docker.Config{
Labels: map[string]string{
"traefik.backend": "foobar",
},
},
},
expected: "foobar",
},
}
for _, e := range containers {
actual := provider.getBackend(e.container)
if actual != e.expected {
t.Fatalf("expected %q, got %q", e.expected, actual)
}
}
}
func TestDockerGetPort(t *testing.T) {
provider := &Docker{}
containers := []struct {
container docker.Container
expected string
}{
{
container: docker.Container{
Name: "foo",
Config: &docker.Config{},
NetworkSettings: &docker.NetworkSettings{},
},
expected: "",
},
{
container: docker.Container{
Name: "bar",
Config: &docker.Config{},
NetworkSettings: &docker.NetworkSettings{
Ports: map[docker.Port][]docker.PortBinding{
"80/tcp": {},
},
},
},
expected: "80",
},
// FIXME handle this better..
// {
// container: docker.Container{
// Name: "bar",
// Config: &docker.Config{},
// NetworkSettings: &docker.NetworkSettings{
// Ports: map[docker.Port][]docker.PortBinding{
// "80/tcp": []docker.PortBinding{},
// "443/tcp": []docker.PortBinding{},
// },
// },
// },
// expected: "80",
// },
{
container: docker.Container{
Name: "test",
Config: &docker.Config{
Labels: map[string]string{
"traefik.port": "8080",
},
},
NetworkSettings: &docker.NetworkSettings{
Ports: map[docker.Port][]docker.PortBinding{
"80/tcp": {},
},
},
},
expected: "8080",
},
}
for _, e := range containers {
actual := provider.getPort(e.container)
if actual != e.expected {
t.Fatalf("expected %q, got %q", e.expected, actual)
}
}
}
func TestDockerGetWeight(t *testing.T) {
provider := &Docker{}
containers := []struct {
container docker.Container
expected string
}{
{
container: docker.Container{
Name: "foo",
Config: &docker.Config{},
},
expected: "0",
},
{
container: docker.Container{
Name: "test",
Config: &docker.Config{
Labels: map[string]string{
"traefik.weight": "10",
},
},
},
expected: "10",
},
}
for _, e := range containers {
actual := provider.getWeight(e.container)
if actual != e.expected {
t.Fatalf("expected %q, got %q", e.expected, actual)
}
}
}
func TestDockerGetDomain(t *testing.T) {
provider := &Docker{
Domain: "docker.localhost",
}
containers := []struct {
container docker.Container
expected string
}{
{
container: docker.Container{
Name: "foo",
Config: &docker.Config{},
},
expected: "docker.localhost",
},
{
container: docker.Container{
Name: "test",
Config: &docker.Config{
Labels: map[string]string{
"traefik.domain": "foo.bar",
},
},
},
expected: "foo.bar",
},
}
for _, e := range containers {
actual := provider.getDomain(e.container)
if actual != e.expected {
t.Fatalf("expected %q, got %q", e.expected, actual)
}
}
}
func TestDockerGetProtocol(t *testing.T) {
provider := &Docker{}
containers := []struct {
container docker.Container
expected string
}{
{
container: docker.Container{
Name: "foo",
Config: &docker.Config{},
},
expected: "http",
},
{
container: docker.Container{
Name: "test",
Config: &docker.Config{
Labels: map[string]string{
"traefik.protocol": "https",
},
},
},
expected: "https",
},
}
for _, e := range containers {
actual := provider.getProtocol(e.container)
if actual != e.expected {
t.Fatalf("expected %q, got %q", e.expected, actual)
}
}
}
func TestDockerGetPassHostHeader(t *testing.T) {
provider := &Docker{}
containers := []struct {
container docker.Container
expected string
}{
{
container: docker.Container{
Name: "foo",
Config: &docker.Config{},
},
expected: "false",
},
{
container: docker.Container{
Name: "test",
Config: &docker.Config{
Labels: map[string]string{
"traefik.frontend.passHostHeader": "true",
},
},
},
expected: "true",
},
}
for _, e := range containers {
actual := provider.getPassHostHeader(e.container)
if actual != e.expected {
t.Fatalf("expected %q, got %q", e.expected, actual)
}
}
}
func TestDockerGetLabel(t *testing.T) {
containers := []struct {
container docker.Container
expected string
}{
{
container: docker.Container{
Config: &docker.Config{},
},
expected: "Label not found:",
},
{
container: docker.Container{
Config: &docker.Config{
Labels: map[string]string{
"foo": "bar",
},
},
},
expected: "",
},
}
for _, e := range containers {
label, err := getLabel(e.container, "foo")
if e.expected != "" {
if err == nil || !strings.Contains(err.Error(), e.expected) {
t.Fatalf("expected an error with %q, got %v", e.expected, err)
}
} else {
if label != "bar" {
t.Fatalf("expected label 'bar', got %s", label)
}
}
}
}
func TestDockerGetLabels(t *testing.T) {
containers := []struct {
container docker.Container
expectedLabels map[string]string
expectedError string
}{
{
container: docker.Container{
Config: &docker.Config{},
},
expectedLabels: map[string]string{},
expectedError: "Label not found:",
},
{
container: docker.Container{
Config: &docker.Config{
Labels: map[string]string{
"foo": "fooz",
},
},
},
expectedLabels: map[string]string{
"foo": "fooz",
},
expectedError: "Label not found: bar",
},
{
container: docker.Container{
Config: &docker.Config{
Labels: map[string]string{
"foo": "fooz",
"bar": "barz",
},
},
},
expectedLabels: map[string]string{
"foo": "fooz",
"bar": "barz",
},
expectedError: "",
},
}
for _, e := range containers {
labels, err := getLabels(e.container, []string{"foo", "bar"})
if !reflect.DeepEqual(labels, e.expectedLabels) {
t.Fatalf("expect %v, got %v", e.expectedLabels, labels)
}
if e.expectedError != "" {
if err == nil || !strings.Contains(err.Error(), e.expectedError) {
t.Fatalf("expected an error with %q, got %v", e.expectedError, err)
}
}
}
}
func TestDockerTraefikFilter(t *testing.T) {
containers := []struct {
container docker.Container
expected bool
}{
{
container: docker.Container{
Config: &docker.Config{},
NetworkSettings: &docker.NetworkSettings{},
},
expected: false,
},
{
container: docker.Container{
Config: &docker.Config{
Labels: map[string]string{
"traefik.enable": "false",
},
},
NetworkSettings: &docker.NetworkSettings{
Ports: map[docker.Port][]docker.PortBinding{
"80/tcp": {},
},
},
},
expected: false,
},
{
container: docker.Container{
Config: &docker.Config{
Labels: map[string]string{
"traefik.frontend.rule": "Host",
},
},
NetworkSettings: &docker.NetworkSettings{
Ports: map[docker.Port][]docker.PortBinding{
"80/tcp": {},
},
},
},
expected: false,
},
{
container: docker.Container{
Config: &docker.Config{
Labels: map[string]string{
"traefik.frontend.value": "foo.bar",
},
},
NetworkSettings: &docker.NetworkSettings{
Ports: map[docker.Port][]docker.PortBinding{
"80/tcp": {},
},
},
},
expected: false,
},
{
container: docker.Container{
Config: &docker.Config{},
NetworkSettings: &docker.NetworkSettings{
Ports: map[docker.Port][]docker.PortBinding{
"80/tcp": {},
"443/tcp": {},
},
},
},
expected: false,
},
{
container: docker.Container{
Config: &docker.Config{},
NetworkSettings: &docker.NetworkSettings{
Ports: map[docker.Port][]docker.PortBinding{
"80/tcp": {},
},
},
},
expected: true,
},
{
container: docker.Container{
Config: &docker.Config{
Labels: map[string]string{
"traefik.port": "80",
},
},
NetworkSettings: &docker.NetworkSettings{
Ports: map[docker.Port][]docker.PortBinding{
"80/tcp": {},
"443/tcp": {},
},
},
},
expected: true,
},
{
container: docker.Container{
Config: &docker.Config{
Labels: map[string]string{
"traefik.enable": "true",
},
},
NetworkSettings: &docker.NetworkSettings{
Ports: map[docker.Port][]docker.PortBinding{
"80/tcp": {},
},
},
},
expected: true,
},
{
container: docker.Container{
Config: &docker.Config{
Labels: map[string]string{
"traefik.enable": "anything",
},
},
NetworkSettings: &docker.NetworkSettings{
Ports: map[docker.Port][]docker.PortBinding{
"80/tcp": {},
},
},
},
expected: true,
},
{
container: docker.Container{
Config: &docker.Config{
Labels: map[string]string{
"traefik.frontend.rule": "Host",
"traefik.frontend.value": "foo.bar",
},
},
NetworkSettings: &docker.NetworkSettings{
Ports: map[docker.Port][]docker.PortBinding{
"80/tcp": {},
},
},
},
expected: true,
},
}
for _, e := range containers {
actual := containerFilter(e.container)
if actual != e.expected {
t.Fatalf("expected %v, got %v", e.expected, actual)
}
}
}
func TestDockerLoadDockerConfig(t *testing.T) {
cases := []struct {
containers []docker.Container
expectedFrontends map[string]*types.Frontend
expectedBackends map[string]*types.Backend
}{
{
containers: []docker.Container{},
expectedFrontends: map[string]*types.Frontend{},
expectedBackends: map[string]*types.Backend{},
},
{
containers: []docker.Container{
{
Name: "test",
Config: &docker.Config{},
NetworkSettings: &docker.NetworkSettings{
Ports: map[docker.Port][]docker.PortBinding{
"80/tcp": {},
},
IPAddress: "127.0.0.1",
},
},
},
expectedFrontends: map[string]*types.Frontend{
`"frontend-Host-test-docker-localhost"`: {
Backend: "backend-test",
Routes: map[string]types.Route{
`"route-frontend-Host-test-docker-localhost"`: {
Rule: "Host",
Value: "test.docker.localhost",
},
},
},
},
expectedBackends: map[string]*types.Backend{
"backend-test": {
Servers: map[string]types.Server{
"server-test": {
URL: "http://127.0.0.1:80",
},
},
CircuitBreaker: nil,
LoadBalancer: nil,
},
},
},
{
containers: []docker.Container{
{
Name: "test1",
Config: &docker.Config{
Labels: map[string]string{
"traefik.backend": "foobar",
},
},
NetworkSettings: &docker.NetworkSettings{
Ports: map[docker.Port][]docker.PortBinding{
"80/tcp": {},
},
IPAddress: "127.0.0.1",
},
},
{
Name: "test2",
Config: &docker.Config{
Labels: map[string]string{
"traefik.backend": "foobar",
},
},
NetworkSettings: &docker.NetworkSettings{
Ports: map[docker.Port][]docker.PortBinding{
"80/tcp": {},
},
IPAddress: "127.0.0.1",
},
},
},
expectedFrontends: map[string]*types.Frontend{
`"frontend-Host-test1-docker-localhost"`: {
Backend: "backend-foobar",
Routes: map[string]types.Route{
`"route-frontend-Host-test1-docker-localhost"`: {
Rule: "Host",
Value: "test1.docker.localhost",
},
},
},
`"frontend-Host-test2-docker-localhost"`: {
Backend: "backend-foobar",
Routes: map[string]types.Route{
`"route-frontend-Host-test2-docker-localhost"`: {
Rule: "Host",
Value: "test2.docker.localhost",
},
},
},
},
expectedBackends: map[string]*types.Backend{
"backend-foobar": {
Servers: map[string]types.Server{
"server-test1": {
URL: "http://127.0.0.1:80",
},
"server-test2": {
URL: "http://127.0.0.1:80",
},
},
CircuitBreaker: nil,
LoadBalancer: nil,
},
},
},
}
provider := &Docker{
Domain: "docker.localhost",
}
for _, c := range cases {
actualConfig := provider.loadDockerConfig(c.containers)
// Compare backends
if !reflect.DeepEqual(actualConfig.Backends, c.expectedBackends) {
t.Fatalf("expected %#v, got %#v", c.expectedBackends, actualConfig.Backends)
}
if !reflect.DeepEqual(actualConfig.Frontends, c.expectedFrontends) {
t.Fatalf("expected %#v, got %#v", c.expectedFrontends, actualConfig.Frontends)
}
}
}

20
provider/etcd.go Normal file
View File

@@ -0,0 +1,20 @@
package provider
import (
"github.com/docker/libkv/store"
"github.com/docker/libkv/store/etcd"
"github.com/emilevauge/traefik/types"
)
// Etcd holds configurations of the Etcd provider.
type Etcd struct {
Kv
}
// Provide allows the provider to provide configurations to traefik
// using the given configuration channel.
func (provider *Etcd) Provide(configurationChan chan<- types.ConfigMessage) error {
provider.StoreType = store.ETCD
etcd.Register()
return provider.provide(configurationChan)
}

View File

@@ -1,4 +1,4 @@
package main
package provider
import (
"os"
@@ -7,15 +7,18 @@ import (
"github.com/BurntSushi/toml"
log "github.com/Sirupsen/logrus"
"github.com/emilevauge/traefik/types"
"gopkg.in/fsnotify.v1"
)
type FileProvider struct {
Watch bool
Filename string
// File holds configurations of the File provider.
type File struct {
baseProvider
}
func (provider *FileProvider) Provide(configurationChan chan<- configMessage) error {
// Provide allows the provider to provide configurations to traefik
// using the given configuration channel.
func (provider *File) Provide(configurationChan chan<- types.ConfigMessage) error {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Error("Error creating file watcher", err)
@@ -38,9 +41,12 @@ func (provider *FileProvider) Provide(configurationChan chan<- configMessage) er
case event := <-watcher.Events:
if strings.Contains(event.Name, file.Name()) {
log.Debug("File event:", event)
configuration := provider.LoadFileConfig(file.Name())
configuration := provider.loadFileConfig(file.Name())
if configuration != nil {
configurationChan <- configMessage{"file", configuration}
configurationChan <- types.ConfigMessage{
ProviderName: "file",
Configuration: configuration,
}
}
}
case error := <-watcher.Errors:
@@ -55,13 +61,16 @@ func (provider *FileProvider) Provide(configurationChan chan<- configMessage) er
}
}
configuration := provider.LoadFileConfig(file.Name())
configurationChan <- configMessage{"file", configuration}
configuration := provider.loadFileConfig(file.Name())
configurationChan <- types.ConfigMessage{
ProviderName: "file",
Configuration: configuration,
}
return nil
}
func (provider *FileProvider) LoadFileConfig(filename string) *Configuration {
configuration := new(Configuration)
func (provider *File) loadFileConfig(filename string) *types.Configuration {
configuration := new(types.Configuration)
if _, err := toml.DecodeFile(filename, configuration); err != nil {
log.Error("Error reading file:", err)
return nil

1
provider/file_test.go Normal file
View File

@@ -0,0 +1 @@
package provider

130
provider/kv.go Normal file
View File

@@ -0,0 +1,130 @@
// Package provider holds the different provider implementation.
package provider
import (
"strings"
"text/template"
"time"
"github.com/BurntSushi/ty/fun"
log "github.com/Sirupsen/logrus"
"github.com/docker/libkv"
"github.com/docker/libkv/store"
"github.com/emilevauge/traefik/types"
"strconv"
)
// Kv holds common configurations of key-value providers.
type Kv struct {
baseProvider
Endpoint string
Prefix string
StoreType store.Backend
kvclient store.Store
}
func (provider *Kv) provide(configurationChan chan<- types.ConfigMessage) error {
kv, err := libkv.NewStore(
provider.StoreType,
[]string{provider.Endpoint},
&store.Config{
ConnectionTimeout: 30 * time.Second,
Bucket: "traefik",
},
)
if err != nil {
return err
}
if _, err := kv.List(""); err != nil {
return err
}
provider.kvclient = kv
if provider.Watch {
stopCh := make(chan struct{})
chanKeys, err := kv.WatchTree(provider.Prefix, stopCh)
if err != nil {
return err
}
go func() {
for {
<-chanKeys
configuration := provider.loadConfig()
if configuration != nil {
configurationChan <- types.ConfigMessage{
ProviderName: string(provider.StoreType),
Configuration: configuration,
}
}
defer close(stopCh)
}
}()
}
configuration := provider.loadConfig()
configurationChan <- types.ConfigMessage{
ProviderName: string(provider.StoreType),
Configuration: configuration,
}
return nil
}
func (provider *Kv) loadConfig() *types.Configuration {
templateObjects := struct {
Prefix string
}{
provider.Prefix,
}
var KvFuncMap = template.FuncMap{
"List": provider.list,
"Get": provider.get,
"GetBool": provider.getBool,
"Last": provider.last,
}
configuration, err := provider.getConfiguration("templates/kv.tmpl", KvFuncMap, templateObjects)
if err != nil {
log.Error(err)
}
return configuration
}
func (provider *Kv) list(keys ...string) []string {
joinedKeys := strings.Join(keys, "")
keysPairs, err := provider.kvclient.List(joinedKeys)
if err != nil {
log.Error("Error getting keys: ", joinedKeys, err)
return nil
}
directoryKeys := make(map[string]string)
for _, key := range keysPairs {
directory := strings.Split(strings.TrimPrefix(key.Key, strings.TrimPrefix(joinedKeys, "/")), "/")[0]
directoryKeys[directory] = joinedKeys + directory
}
return fun.Values(directoryKeys).([]string)
}
func (provider *Kv) get(keys ...string) string {
joinedKeys := strings.Join(keys, "")
keyPair, err := provider.kvclient.Get(joinedKeys)
if err != nil {
log.Error("Error getting key: ", joinedKeys, err)
return ""
} else if keyPair == nil {
return ""
}
return string(keyPair.Value)
}
func (provider *Kv) getBool(keys ...string) bool {
value := provider.get(keys...)
b, err := strconv.ParseBool(string(value))
if err != nil {
log.Error("Error getting key: ", strings.Join(keys, ""), err)
return false
}
return b
}
func (provider *Kv) last(key string) string {
splittedKey := strings.Split(key, "/")
return splittedKey[len(splittedKey)-1]
}

367
provider/kv_test.go Normal file
View File

@@ -0,0 +1,367 @@
package provider
import (
"errors"
"strings"
"testing"
"github.com/docker/libkv/store"
"reflect"
"sort"
)
func TestKvList(t *testing.T) {
cases := []struct {
provider *Kv
keys []string
expected []string
}{
{
provider: &Kv{
kvclient: &Mock{},
},
keys: []string{},
expected: []string{},
},
{
provider: &Kv{
kvclient: &Mock{},
},
keys: []string{"traefik"},
expected: []string{},
},
{
provider: &Kv{
kvclient: &Mock{
KVPairs: []*store.KVPair{
{
Key: "foo",
Value: []byte("bar"),
},
},
},
},
keys: []string{"bar"},
expected: []string{},
},
{
provider: &Kv{
kvclient: &Mock{
KVPairs: []*store.KVPair{
{
Key: "foo",
Value: []byte("bar"),
},
},
},
},
keys: []string{"foo"},
expected: []string{"foo"},
},
{
provider: &Kv{
kvclient: &Mock{
KVPairs: []*store.KVPair{
{
Key: "foo/baz/1",
Value: []byte("bar"),
},
{
Key: "foo/baz/2",
Value: []byte("bar"),
},
{
Key: "foo/baz/biz/1",
Value: []byte("bar"),
},
},
},
},
keys: []string{"foo", "/baz/"},
expected: []string{"foo/baz/biz", "foo/baz/1", "foo/baz/2"},
},
}
for _, c := range cases {
actual := c.provider.list(c.keys...)
sort.Strings(actual)
sort.Strings(c.expected)
if !reflect.DeepEqual(actual, c.expected) {
t.Fatalf("expected %v, got %v for %v and %v", c.expected, actual, c.keys, c.provider)
}
}
// Error case
provider := &Kv{
kvclient: &Mock{
Error: true,
},
}
actual := provider.list("anything")
if actual != nil {
t.Fatalf("Should have return nil, got %v", actual)
}
}
func TestKvGet(t *testing.T) {
cases := []struct {
provider *Kv
keys []string
expected string
}{
{
provider: &Kv{
kvclient: &Mock{},
},
keys: []string{},
expected: "",
},
{
provider: &Kv{
kvclient: &Mock{},
},
keys: []string{"traefik"},
expected: "",
},
{
provider: &Kv{
kvclient: &Mock{
KVPairs: []*store.KVPair{
{
Key: "foo",
Value: []byte("bar"),
},
},
},
},
keys: []string{"bar"},
expected: "",
},
{
provider: &Kv{
kvclient: &Mock{
KVPairs: []*store.KVPair{
{
Key: "foo",
Value: []byte("bar"),
},
},
},
},
keys: []string{"foo"},
expected: "bar",
},
{
provider: &Kv{
kvclient: &Mock{
KVPairs: []*store.KVPair{
{
Key: "foo/baz/1",
Value: []byte("bar1"),
},
{
Key: "foo/baz/2",
Value: []byte("bar2"),
},
{
Key: "foo/baz/biz/1",
Value: []byte("bar3"),
},
},
},
},
keys: []string{"foo", "/baz/", "2"},
expected: "bar2",
},
}
for _, c := range cases {
actual := c.provider.get(c.keys...)
if actual != c.expected {
t.Fatalf("expected %v, got %v for %v and %v", c.expected, actual, c.keys, c.provider)
}
}
// Error case
provider := &Kv{
kvclient: &Mock{
Error: true,
},
}
actual := provider.get("anything")
if actual != "" {
t.Fatalf("Should have return nil, got %v", actual)
}
}
func TestKvGetBool(t *testing.T) {
cases := []struct {
provider *Kv
keys []string
expected bool
}{
{
provider: &Kv{
kvclient: &Mock{
KVPairs: []*store.KVPair{
{
Key: "foo",
Value: []byte("true"),
},
},
},
},
keys: []string{"foo"},
expected: true,
},
{
provider: &Kv{
kvclient: &Mock{
KVPairs: []*store.KVPair{
{
Key: "foo",
Value: []byte("false"),
},
},
},
},
keys: []string{"foo"},
expected: false,
},
}
for _, c := range cases {
actual := c.provider.getBool(c.keys...)
if actual != c.expected {
t.Fatalf("expected %v, got %v for %v and %v", c.expected, actual, c.keys, c.provider)
}
}
// Error case
provider := &Kv{
kvclient: &Mock{
Error: true,
},
}
actual := provider.get("anything")
if actual != "" {
t.Fatalf("Should have return nil, got %v", actual)
}
}
func TestKvLast(t *testing.T) {
cases := []struct {
key string
expected string
}{
{
key: "",
expected: "",
},
{
key: "foo",
expected: "foo",
},
{
key: "foo/bar",
expected: "bar",
},
{
key: "foo/bar/baz",
expected: "baz",
},
// FIXME is this wanted ?
{
key: "foo/bar/",
expected: "",
},
}
provider := &Kv{}
for _, c := range cases {
actual := provider.last(c.key)
if actual != c.expected {
t.Fatalf("expected %s, got %s", c.expected, actual)
}
}
}
// Extremely limited mock store so we can test initialization
type Mock struct {
Error bool
KVPairs []*store.KVPair
}
func (s *Mock) Put(key string, value []byte, opts *store.WriteOptions) error {
return errors.New("Put not supported")
}
func (s *Mock) Get(key string) (*store.KVPair, error) {
if s.Error {
return nil, errors.New("Error")
}
for _, kvPair := range s.KVPairs {
if kvPair.Key == key {
return kvPair, nil
}
}
return nil, nil
}
func (s *Mock) Delete(key string) error {
return errors.New("Delete not supported")
}
// Exists mock
func (s *Mock) Exists(key string) (bool, error) {
return false, errors.New("Exists not supported")
}
// Watch mock
func (s *Mock) Watch(key string, stopCh <-chan struct{}) (<-chan *store.KVPair, error) {
return nil, errors.New("Watch not supported")
}
// WatchTree mock
func (s *Mock) WatchTree(prefix string, stopCh <-chan struct{}) (<-chan []*store.KVPair, error) {
return nil, errors.New("WatchTree not supported")
}
// NewLock mock
func (s *Mock) NewLock(key string, options *store.LockOptions) (store.Locker, error) {
return nil, errors.New("NewLock not supported")
}
// List mock
func (s *Mock) List(prefix string) ([]*store.KVPair, error) {
if s.Error {
return nil, errors.New("Error")
}
kv := []*store.KVPair{}
for _, kvPair := range s.KVPairs {
if strings.HasPrefix(kvPair.Key, prefix) {
kv = append(kv, kvPair)
}
}
return kv, nil
}
// DeleteTree mock
func (s *Mock) DeleteTree(prefix string) error {
return errors.New("DeleteTree not supported")
}
// 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("AtomicPut not supported")
}
// AtomicDelete mock
func (s *Mock) AtomicDelete(key string, previous *store.KVPair) (bool, error) {
return false, errors.New("AtomicDelete not supported")
}
// Close mock
func (s *Mock) Close() {
return
}

243
provider/marathon.go Normal file
View File

@@ -0,0 +1,243 @@
package provider
import (
"errors"
"net/url"
"strconv"
"text/template"
"github.com/BurntSushi/ty/fun"
log "github.com/Sirupsen/logrus"
"github.com/emilevauge/traefik/types"
"github.com/gambol99/go-marathon"
)
// Marathon holds configuration of the Marathon provider.
type Marathon struct {
baseProvider
Endpoint string
Domain string
NetworkInterface string
marathonClient lightMarathonClient
}
type lightMarathonClient interface {
Applications(url.Values) (*marathon.Applications, error)
AllTasks() (*marathon.Tasks, error)
}
// Provide allows the provider to provide configurations to traefik
// using the given configuration channel.
func (provider *Marathon) Provide(configurationChan chan<- types.ConfigMessage) error {
config := marathon.NewDefaultConfig()
config.URL = provider.Endpoint
config.EventsInterface = provider.NetworkInterface
client, err := marathon.NewClient(config)
if err != nil {
log.Errorf("Failed to create a client for marathon, error: %s", err)
return err
}
provider.marathonClient = client
update := make(marathon.EventsChannel, 5)
if provider.Watch {
if err := client.AddEventsListener(update, marathon.EVENTS_APPLICATIONS); err != nil {
log.Errorf("Failed to register for subscriptions, %s", err)
} else {
go func() {
for {
event := <-update
log.Debug("Marathon event receveived", event)
configuration := provider.loadMarathonConfig()
if configuration != nil {
configurationChan <- types.ConfigMessage{
ProviderName: "marathon",
Configuration: configuration,
}
}
}
}()
}
}
configuration := provider.loadMarathonConfig()
configurationChan <- types.ConfigMessage{
ProviderName: "marathon",
Configuration: configuration,
}
return nil
}
func (provider *Marathon) loadMarathonConfig() *types.Configuration {
var MarathonFuncMap = template.FuncMap{
"getPort": provider.getPort,
"getWeight": provider.getWeight,
"getDomain": provider.getDomain,
"getProtocol": provider.getProtocol,
"getPassHostHeader": provider.getPassHostHeader,
"getFrontendValue": provider.getFrontendValue,
"getFrontendRule": provider.getFrontendRule,
"replace": replace,
}
applications, err := provider.marathonClient.Applications(nil)
if err != nil {
log.Errorf("Failed to create a client for marathon, error: %s", err)
return nil
}
tasks, err := provider.marathonClient.AllTasks()
if err != nil {
log.Errorf("Failed to create a client for marathon, error: %s", err)
return nil
}
//filter tasks
filteredTasks := fun.Filter(func(task marathon.Task) bool {
return taskFilter(task, applications)
}, tasks.Tasks).([]marathon.Task)
//filter apps
filteredApps := fun.Filter(func(app marathon.Application) bool {
return applicationFilter(app, filteredTasks)
}, applications.Apps).([]marathon.Application)
templateObjects := struct {
Applications []marathon.Application
Tasks []marathon.Task
Domain string
}{
filteredApps,
filteredTasks,
provider.Domain,
}
configuration, err := provider.getConfiguration("templates/marathon.tmpl", MarathonFuncMap, templateObjects)
if err != nil {
log.Error(err)
}
return configuration
}
func taskFilter(task marathon.Task, applications *marathon.Applications) bool {
if len(task.Ports) == 0 {
log.Debug("Filtering marathon task without port %s", task.AppID)
return false
}
application, errApp := getApplication(task, applications.Apps)
if errApp != nil {
log.Errorf("Unable to get marathon application from task %s", task.AppID)
return false
}
_, err := strconv.Atoi(application.Labels["traefik.port"])
if len(application.Ports) > 1 && err != nil {
log.Debugf("Filtering marathon task %s with more than 1 port and no traefik.port label", task.AppID)
return false
}
if application.Labels["traefik.enable"] == "false" {
log.Debugf("Filtering disabled marathon task %s", task.AppID)
return false
}
//filter healthchecks
if application.HasHealthChecks() {
if task.HasHealthCheckResults() {
for _, healthcheck := range task.HealthCheckResult {
// found one bad healthcheck, return false
if !healthcheck.Alive {
log.Debugf("Filtering marathon task %s with bad healthcheck", task.AppID)
return false
}
}
} else {
log.Debugf("Filtering marathon task %s with bad healthcheck", task.AppID)
return false
}
}
return true
}
func applicationFilter(app marathon.Application, filteredTasks []marathon.Task) bool {
return fun.Exists(func(task marathon.Task) bool {
return task.AppID == app.ID
}, filteredTasks)
}
func getApplication(task marathon.Task, apps []marathon.Application) (marathon.Application, error) {
for _, application := range apps {
if application.ID == task.AppID {
return application, nil
}
}
return marathon.Application{}, errors.New("Application not found: " + task.AppID)
}
func (provider *Marathon) getLabel(application marathon.Application, label string) (string, error) {
for key, value := range application.Labels {
if key == label {
return value, nil
}
}
return "", errors.New("Label not found:" + label)
}
func (provider *Marathon) getPort(task marathon.Task) string {
for _, port := range task.Ports {
return strconv.Itoa(port)
}
return ""
}
func (provider *Marathon) getWeight(task marathon.Task, applications []marathon.Application) string {
application, errApp := getApplication(task, applications)
if errApp != nil {
log.Errorf("Unable to get marathon application from task %s", task.AppID)
return "0"
}
if label, err := provider.getLabel(application, "traefik.weight"); err == nil {
return label
}
return "0"
}
func (provider *Marathon) getDomain(application marathon.Application) string {
if label, err := provider.getLabel(application, "traefik.domain"); err == nil {
return label
}
return provider.Domain
}
func (provider *Marathon) getProtocol(task marathon.Task, applications []marathon.Application) string {
application, errApp := getApplication(task, applications)
if errApp != nil {
log.Errorf("Unable to get marathon application from task %s", task.AppID)
return "http"
}
if label, err := provider.getLabel(application, "traefik.protocol"); err == nil {
return label
}
return "http"
}
func (provider *Marathon) getPassHostHeader(application marathon.Application) string {
if passHostHeader, err := provider.getLabel(application, "traefik.frontend.passHostHeader"); err == nil {
return passHostHeader
}
return "false"
}
// getFrontendValue returns the frontend value for the specified application, using
// it's label. It returns a default one if the label is not present.
func (provider *Marathon) getFrontendValue(application marathon.Application) string {
if label, err := provider.getLabel(application, "traefik.frontend.value"); err == nil {
return label
}
return getEscapedName(application.ID) + "." + provider.Domain
}
// getFrontendRule returns the frontend rule for the specified application, using
// it's label. It returns a default one (Host) if the label is not present.
func (provider *Marathon) getFrontendRule(application marathon.Application) string {
if label, err := provider.getLabel(application, "traefik.frontend.rule"); err == nil {
return label
}
return "Host"
}

656
provider/marathon_test.go Normal file
View File

@@ -0,0 +1,656 @@
package provider
import (
"errors"
"net/url"
"reflect"
"testing"
"github.com/emilevauge/traefik/types"
"github.com/gambol99/go-marathon"
)
type fakeClient struct {
applicationsError bool
applications *marathon.Applications
tasksError bool
tasks *marathon.Tasks
}
func (c *fakeClient) Applications(url.Values) (*marathon.Applications, error) {
if c.applicationsError {
return nil, errors.New("error")
}
return c.applications, nil
}
func (c *fakeClient) AllTasks() (*marathon.Tasks, error) {
if c.tasksError {
return nil, errors.New("error")
}
return c.tasks, nil
}
func TestMarathonLoadConfig(t *testing.T) {
cases := []struct {
applicationsError bool
applications *marathon.Applications
tasksError bool
tasks *marathon.Tasks
expectedNil bool
expectedFrontends map[string]*types.Frontend
expectedBackends map[string]*types.Backend
}{
{
applications: &marathon.Applications{},
tasks: &marathon.Tasks{},
expectedFrontends: map[string]*types.Frontend{},
expectedBackends: map[string]*types.Backend{},
},
{
applicationsError: true,
applications: &marathon.Applications{},
tasks: &marathon.Tasks{},
expectedNil: true,
expectedFrontends: map[string]*types.Frontend{},
expectedBackends: map[string]*types.Backend{},
},
{
applications: &marathon.Applications{},
tasksError: true,
tasks: &marathon.Tasks{},
expectedNil: true,
expectedFrontends: map[string]*types.Frontend{},
expectedBackends: map[string]*types.Backend{},
},
{
applications: &marathon.Applications{
Apps: []marathon.Application{
{
ID: "/test",
Ports: []int{80},
},
},
},
tasks: &marathon.Tasks{
Tasks: []marathon.Task{
{
ID: "test",
AppID: "/test",
Host: "127.0.0.1",
Ports: []int{80},
},
},
},
expectedFrontends: map[string]*types.Frontend{
`frontend-test`: {
Backend: "backend-test",
Routes: map[string]types.Route{
`route-host-test`: {
Rule: "Host",
Value: "test.docker.localhost",
},
},
},
},
expectedBackends: map[string]*types.Backend{
"backend-test": {
Servers: map[string]types.Server{
"server-test": {
URL: "http://127.0.0.1:80",
Weight: 0,
},
},
CircuitBreaker: nil,
LoadBalancer: nil,
},
},
},
}
for _, c := range cases {
provider := &Marathon{
Domain: "docker.localhost",
marathonClient: &fakeClient{
applicationsError: c.applicationsError,
applications: c.applications,
tasksError: c.tasksError,
tasks: c.tasks,
},
}
actualConfig := provider.loadMarathonConfig()
if c.expectedNil {
if actualConfig != nil {
t.Fatalf("Should have been nil, got %v", actualConfig)
}
} else {
// Compare backends
if !reflect.DeepEqual(actualConfig.Backends, c.expectedBackends) {
t.Fatalf("expected %#v, got %#v", c.expectedBackends, actualConfig.Backends)
}
if !reflect.DeepEqual(actualConfig.Frontends, c.expectedFrontends) {
t.Fatalf("expected %#v, got %#v", c.expectedFrontends, actualConfig.Frontends)
}
}
}
}
func TestMarathonTaskFilter(t *testing.T) {
cases := []struct {
task marathon.Task
applications *marathon.Applications
expected bool
}{
{
task: marathon.Task{},
applications: &marathon.Applications{},
expected: false,
},
{
task: marathon.Task{
AppID: "test",
Ports: []int{80},
},
applications: &marathon.Applications{},
expected: false,
},
{
task: marathon.Task{
AppID: "test",
Ports: []int{80},
},
applications: &marathon.Applications{
Apps: []marathon.Application{
{
ID: "foo",
},
},
},
expected: false,
},
{
task: marathon.Task{
AppID: "foo",
Ports: []int{80},
},
applications: &marathon.Applications{
Apps: []marathon.Application{
{
ID: "foo",
Ports: []int{80, 443},
},
},
},
expected: false,
},
{
task: marathon.Task{
AppID: "foo",
Ports: []int{80},
},
applications: &marathon.Applications{
Apps: []marathon.Application{
{
ID: "foo",
Ports: []int{80},
Labels: map[string]string{
"traefik.enable": "false",
},
},
},
},
expected: false,
},
{
task: marathon.Task{
AppID: "foo",
Ports: []int{80},
},
applications: &marathon.Applications{
Apps: []marathon.Application{
{
ID: "foo",
Ports: []int{80},
HealthChecks: []*marathon.HealthCheck{
marathon.NewDefaultHealthCheck(),
},
},
},
},
expected: false,
},
{
task: marathon.Task{
AppID: "foo",
Ports: []int{80},
HealthCheckResult: []*marathon.HealthCheckResult{
{
Alive: false,
},
},
},
applications: &marathon.Applications{
Apps: []marathon.Application{
{
ID: "foo",
Ports: []int{80},
HealthChecks: []*marathon.HealthCheck{
marathon.NewDefaultHealthCheck(),
},
},
},
},
expected: false,
},
{
task: marathon.Task{
AppID: "foo",
Ports: []int{80},
HealthCheckResult: []*marathon.HealthCheckResult{
{
Alive: true,
},
{
Alive: false,
},
},
},
applications: &marathon.Applications{
Apps: []marathon.Application{
{
ID: "foo",
Ports: []int{80},
HealthChecks: []*marathon.HealthCheck{
marathon.NewDefaultHealthCheck(),
},
},
},
},
expected: false,
},
{
task: marathon.Task{
AppID: "foo",
Ports: []int{80},
},
applications: &marathon.Applications{
Apps: []marathon.Application{
{
ID: "foo",
Ports: []int{80},
},
},
},
expected: true,
},
{
task: marathon.Task{
AppID: "foo",
Ports: []int{80},
HealthCheckResult: []*marathon.HealthCheckResult{
{
Alive: true,
},
},
},
applications: &marathon.Applications{
Apps: []marathon.Application{
{
ID: "foo",
Ports: []int{80},
HealthChecks: []*marathon.HealthCheck{
marathon.NewDefaultHealthCheck(),
},
},
},
},
expected: true,
},
}
for _, c := range cases {
actual := taskFilter(c.task, c.applications)
if actual != c.expected {
t.Fatalf("expected %v, got %v", c.expected, actual)
}
}
}
func TestMarathonApplicationFilter(t *testing.T) {
cases := []struct {
application marathon.Application
filteredTasks []marathon.Task
expected bool
}{
{
application: marathon.Application{},
filteredTasks: []marathon.Task{},
expected: false,
},
{
application: marathon.Application{
ID: "test",
},
filteredTasks: []marathon.Task{},
expected: false,
},
{
application: marathon.Application{
ID: "foo",
},
filteredTasks: []marathon.Task{
{
AppID: "bar",
},
},
expected: false,
},
{
application: marathon.Application{
ID: "foo",
},
filteredTasks: []marathon.Task{
{
AppID: "foo",
},
},
expected: true,
},
}
for _, c := range cases {
actual := applicationFilter(c.application, c.filteredTasks)
if actual != c.expected {
t.Fatalf("expected %v, got %v", c.expected, actual)
}
}
}
func TestMarathonGetPort(t *testing.T) {
provider := &Marathon{}
cases := []struct {
task marathon.Task
expected string
}{
{
task: marathon.Task{},
expected: "",
},
{
task: marathon.Task{
Ports: []int{80},
},
expected: "80",
},
{
task: marathon.Task{
Ports: []int{80, 443},
},
expected: "80",
},
}
for _, c := range cases {
actual := provider.getPort(c.task)
if actual != c.expected {
t.Fatalf("expected %q, got %q", c.expected, actual)
}
}
}
func TestMarathonGetWeigh(t *testing.T) {
provider := &Marathon{}
applications := []struct {
applications []marathon.Application
task marathon.Task
expected string
}{
{
applications: []marathon.Application{},
task: marathon.Task{},
expected: "0",
},
{
applications: []marathon.Application{
{
ID: "test1",
Labels: map[string]string{
"traefik.weight": "10",
},
},
},
task: marathon.Task{
AppID: "test2",
},
expected: "0",
},
{
applications: []marathon.Application{
{
ID: "test",
Labels: map[string]string{
"traefik.test": "10",
},
},
},
task: marathon.Task{
AppID: "test",
},
expected: "0",
},
{
applications: []marathon.Application{
{
ID: "test",
Labels: map[string]string{
"traefik.weight": "10",
},
},
},
task: marathon.Task{
AppID: "test",
},
expected: "10",
},
}
for _, a := range applications {
actual := provider.getWeight(a.task, a.applications)
if actual != a.expected {
t.Fatalf("expected %q, got %q", a.expected, actual)
}
}
}
func TestMarathonGetDomain(t *testing.T) {
provider := &Marathon{
Domain: "docker.localhost",
}
applications := []struct {
application marathon.Application
expected string
}{
{
application: marathon.Application{},
expected: "docker.localhost",
},
{
application: marathon.Application{
Labels: map[string]string{
"traefik.domain": "foo.bar",
},
},
expected: "foo.bar",
},
}
for _, a := range applications {
actual := provider.getDomain(a.application)
if actual != a.expected {
t.Fatalf("expected %q, got %q", a.expected, actual)
}
}
}
func TestMarathonGetProtocol(t *testing.T) {
provider := &Marathon{}
applications := []struct {
applications []marathon.Application
task marathon.Task
expected string
}{
{
applications: []marathon.Application{},
task: marathon.Task{},
expected: "http",
},
{
applications: []marathon.Application{
{
ID: "test1",
Labels: map[string]string{
"traefik.protocol": "https",
},
},
},
task: marathon.Task{
AppID: "test2",
},
expected: "http",
},
{
applications: []marathon.Application{
{
ID: "test",
Labels: map[string]string{
"traefik.foo": "bar",
},
},
},
task: marathon.Task{
AppID: "test",
},
expected: "http",
},
{
applications: []marathon.Application{
{
ID: "test",
Labels: map[string]string{
"traefik.protocol": "https",
},
},
},
task: marathon.Task{
AppID: "test",
},
expected: "https",
},
}
for _, a := range applications {
actual := provider.getProtocol(a.task, a.applications)
if actual != a.expected {
t.Fatalf("expected %q, got %q", a.expected, actual)
}
}
}
func TestMarathonGetPassHostHeader(t *testing.T) {
provider := &Marathon{}
applications := []struct {
application marathon.Application
expected string
}{
{
application: marathon.Application{},
expected: "false",
},
{
application: marathon.Application{
Labels: map[string]string{
"traefik.frontend.passHostHeader": "true",
},
},
expected: "true",
},
}
for _, a := range applications {
actual := provider.getPassHostHeader(a.application)
if actual != a.expected {
t.Fatalf("expected %q, got %q", a.expected, actual)
}
}
}
func TestMarathonGetFrontendValue(t *testing.T) {
provider := &Marathon{
Domain: "docker.localhost",
}
applications := []struct {
application marathon.Application
expected string
}{
{
application: marathon.Application{},
expected: ".docker.localhost",
},
{
application: marathon.Application{
ID: "test",
},
expected: "test.docker.localhost",
},
{
application: marathon.Application{
Labels: map[string]string{
"traefik.frontend.value": "foo.bar",
},
},
expected: "foo.bar",
},
}
for _, a := range applications {
actual := provider.getFrontendValue(a.application)
if actual != a.expected {
t.Fatalf("expected %q, got %q", a.expected, actual)
}
}
}
func TestMarathonGetFrontendRule(t *testing.T) {
provider := &Marathon{}
applications := []struct {
application marathon.Application
expected string
}{
{
application: marathon.Application{},
expected: "Host",
},
{
application: marathon.Application{
Labels: map[string]string{
"traefik.frontend.rule": "Header",
},
},
expected: "Header",
},
}
for _, a := range applications {
actual := provider.getFrontendRule(a.application)
if actual != a.expected {
t.Fatalf("expected %q, got %q", a.expected, actual)
}
}
}

67
provider/provider.go Normal file
View File

@@ -0,0 +1,67 @@
package provider
import (
"bytes"
"io/ioutil"
"strings"
"text/template"
"github.com/BurntSushi/toml"
"github.com/emilevauge/traefik/autogen"
"github.com/emilevauge/traefik/types"
)
// Provider defines methods of a provider.
type Provider interface {
// Provide allows the provider to provide configurations to traefik
// using the given configuration channel.
Provide(configurationChan chan<- types.ConfigMessage) error
}
type baseProvider struct {
Watch bool
Filename string
}
func (p *baseProvider) getConfiguration(defaultTemplateFile string, funcMap template.FuncMap, templateObjects interface{}) (*types.Configuration, error) {
var (
buf []byte
err error
)
configuration := new(types.Configuration)
tmpl := template.New(p.Filename).Funcs(funcMap)
if len(p.Filename) > 0 {
buf, err = ioutil.ReadFile(p.Filename)
if err != nil {
return nil, err
}
} else {
buf, err = autogen.Asset(defaultTemplateFile)
if err != nil {
return nil, err
}
}
_, err = tmpl.Parse(string(buf))
if err != nil {
return nil, err
}
var buffer bytes.Buffer
err = tmpl.Execute(&buffer, templateObjects)
if err != nil {
return nil, err
}
if _, err := toml.Decode(buffer.String(), configuration); err != nil {
return nil, err
}
return configuration, nil
}
func replace(s1 string, s2 string, s3 string) string {
return strings.Replace(s3, s1, s2, -1)
}
func getEscapedName(name string) string {
return strings.Replace(name, "/", "", -1)
}

170
provider/provider_test.go Normal file
View File

@@ -0,0 +1,170 @@
package provider
import (
"io/ioutil"
"os"
"strings"
"testing"
"text/template"
)
type myProvider struct {
baseProvider
}
func (p *myProvider) Foo() string {
return "bar"
}
func TestConfigurationErrors(t *testing.T) {
templateErrorFile, err := ioutil.TempFile("", "provider-configuration-error")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(templateErrorFile.Name())
data := []byte("Not a valid template {{ Bar }}")
err = ioutil.WriteFile(templateErrorFile.Name(), data, 0700)
if err != nil {
t.Fatal(err)
}
templateInvalidTOMLFile, err := ioutil.TempFile("", "provider-configuration-error")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(templateInvalidTOMLFile.Name())
data = []byte(`Hello {{ .Name }}
{{ Foo }}`)
err = ioutil.WriteFile(templateInvalidTOMLFile.Name(), data, 0700)
if err != nil {
t.Fatal(err)
}
invalids := []struct {
provider *myProvider
defaultTemplate string
expectedError string
funcMap template.FuncMap
templateObjects interface{}
}{
{
provider: &myProvider{
baseProvider{
Filename: "/non/existent/template.tmpl",
},
},
expectedError: "open /non/existent/template.tmpl: no such file or directory",
},
{
provider: &myProvider{},
defaultTemplate: "non/existent/template.tmpl",
expectedError: "Asset non/existent/template.tmpl not found",
},
{
provider: &myProvider{
baseProvider{
Filename: templateErrorFile.Name(),
},
},
expectedError: `function "Bar" not defined`,
},
{
provider: &myProvider{
baseProvider{
Filename: templateInvalidTOMLFile.Name(),
},
},
expectedError: "Near line 1, key 'Hello': Near line 1: Expected key separator '=', but got '<' instead",
funcMap: template.FuncMap{
"Foo": func() string {
return "bar"
},
},
templateObjects: struct{ Name string }{Name: "bar"},
},
}
for _, invalid := range invalids {
configuration, err := invalid.provider.getConfiguration(invalid.defaultTemplate, invalid.funcMap, nil)
if err == nil || !strings.Contains(err.Error(), invalid.expectedError) {
t.Fatalf("should have generate an error with %q, got %v", invalid.expectedError, err)
}
if configuration != nil {
t.Fatalf("shouldn't have return a configuration object : %v", configuration)
}
}
}
func TestGetConfiguration(t *testing.T) {
templateFile, err := ioutil.TempFile("", "provider-configuration")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(templateFile.Name())
data := []byte(`[backends]
[backends.backend1]
[backends.backend1.circuitbreaker]
expression = "NetworkErrorRatio() > 0.5"
[backends.backend1.servers.server1]
url = "http://172.17.0.2:80"
weight = 10
[backends.backend1.servers.server2]
url = "http://172.17.0.3:80"
weight = 1
[frontends]
[frontends.frontend1]
backend = "backend1"
passHostHeader = true
[frontends.frontend11.routes.test_2]
rule = "Path"
value = "/test"`)
err = ioutil.WriteFile(templateFile.Name(), data, 0700)
if err != nil {
t.Fatal(err)
}
provider := &myProvider{
baseProvider{
Filename: templateFile.Name(),
},
}
configuration, err := provider.getConfiguration(templateFile.Name(), nil, nil)
if err != nil {
t.Fatalf("Shouldn't have error out, got %v", err)
}
if configuration == nil {
t.Fatalf("Configuration should not be nil, but was")
}
}
func TestReplace(t *testing.T) {
cases := []struct {
str string
expected string
}{
{
str: "",
expected: "",
},
{
str: "foo",
expected: "bar",
},
{
str: "foo foo",
expected: "bar bar",
},
{
str: "somethingfoo",
expected: "somethingbar",
},
}
for _, c := range cases {
actual := replace("foo", "bar", c.str)
if actual != c.expected {
t.Fatalf("expected %q, got %q, for %q", c.expected, actual, c.str)
}
}
}

20
provider/zk.go Normal file
View File

@@ -0,0 +1,20 @@
package provider
import (
"github.com/docker/libkv/store"
"github.com/docker/libkv/store/zookeeper"
"github.com/emilevauge/traefik/types"
)
// Zookepper holds configurations of the Zookepper provider.
type Zookepper struct {
Kv
}
// Provide allows the provider to provide configurations to traefik
// using the given configuration channel.
func (provider *Zookepper) Provide(configurationChan chan<- types.ConfigMessage) error {
provider.StoreType = store.ZK
zookeeper.Register()
return provider.provide(configurationChan)
}

View File

@@ -1,7 +1,7 @@
#!/bin/bash
set -e
if ! test -e gen.go; then
if ! test -e autogen/gen.go; then
echo >&2 'error: generate must be run before binary'
false
fi

View File

@@ -1,8 +1,8 @@
#!/bin/bash
set -e
if ! test -e gen.go; then
echo >&2 'error: generate must be run before binary'
if ! test -e autogen/gen.go; then
echo >&2 'error: generate must be run before crossbinary'
false
fi

View File

@@ -5,6 +5,7 @@ set -e
DEFAULT_BUNDLES=(
validate-gofmt
validate-govet
generate
binary
test-unit

View File

@@ -1,8 +1,8 @@
#!/bin/bash
set -e
if ! test -e gen.go; then
echo >&2 'error: generate must be run before binary'
if ! test -e autogen/gen.go; then
echo >&2 'error: generate must be run before test-unit'
false
fi

31
script/validate-golint Executable file
View File

@@ -0,0 +1,31 @@
#!/bin/bash
source "$(dirname "$BASH_SOURCE")/.validate"
IFS=$'\n'
files=( $(validate_diff --diff-filter=ACMR --name-only -- '*.go' | grep -v '^vendor/\|autogen' || true) )
unset IFS
errors=()
for f in "${files[@]}"; do
# we use "git show" here to validate that what's committed passes go vet
failedLint=$(golint "$f")
if [ "$failedLint" ]; then
errors+=( "$failedLint" )
fi
done
if [ ${#errors[@]} -eq 0 ]; then
echo 'Congratulations! All Go source files have been linted.'
else
{
echo "Errors from golint:"
for err in "${errors[@]}"; do
echo "$err"
done
echo
echo 'Please fix the above errors. You can test via "golint" and commit the result.'
echo
} >&2
false
fi

View File

@@ -18,5 +18,6 @@
</div>
<div data-bg-show="frontendCtrl.frontend.backend" class="panel-footer">
<span class="label label-warning" role="button" data-toggle="collapse" href="#{{frontendCtrl.frontend.backend}}" aria-expanded="false">{{frontendCtrl.frontend.backend}}</span>
<span data-ng-show="frontendCtrl.frontend.passHostHeader" class="label label-warning">Pass Host Header</span>
</div>
</div>

View File

@@ -7,6 +7,7 @@
[frontends]{{range $frontend, $containers := .Frontends}}
[frontends."frontend-{{$frontend}}"]{{$container := index $containers 0}}
backend = "backend-{{getBackend $container}}"
passHostHeader = {{getPassHostHeader $container}}
[frontends."frontend-{{$frontend}}".routes."route-frontend-{{$frontend}}"]
rule = "{{getFrontendRule $container}}"
value = "{{getFrontendValue $container}}"

View File

@@ -28,6 +28,7 @@
{{$frontend := Last .}}
[frontends.{{$frontend}}]
backend = "{{Get . "/backend"}}"
passHostHeader = "{{GetBool . "/passHostHeader"}}"
{{$routes := List . "/routes/"}}
{{range $routes}}
[frontends.{{$frontend}}.routes.{{Last .}}]

View File

@@ -8,6 +8,7 @@
[frontends]{{range .Applications}}
[frontends.frontend{{.ID | replace "/" "-"}}]
backend = "backend{{.ID | replace "/" "-"}}"
passHostHeader = {{getPassHostHeader .}}
[frontends.frontend-{{.ID | replace "/" ""}}.routes.route-host-{{.ID | replace "/" ""}}]
rule = "{{getFrontendRule .}}"
value = "{{getFrontendValue .}}"

View File

@@ -2,21 +2,23 @@ package main
import (
"crypto/tls"
"errors"
fmtlog "log"
"net/http"
"net/url"
"os"
"os/signal"
"reflect"
"runtime"
"strings"
"syscall"
"time"
"errors"
"github.com/BurntSushi/toml"
log "github.com/Sirupsen/logrus"
"github.com/codegangsta/negroni"
"github.com/emilevauge/traefik/middlewares"
"github.com/emilevauge/traefik/provider"
"github.com/emilevauge/traefik/types"
"github.com/gorilla/mux"
"github.com/mailgun/manners"
"github.com/mailgun/oxy/cbreaker"
@@ -24,12 +26,9 @@ import (
"github.com/mailgun/oxy/roundrobin"
"github.com/thoas/stats"
"gopkg.in/alecthomas/kingpin.v2"
"runtime"
)
var (
Version = ""
BuildDate = ""
globalConfigFile = kingpin.Arg("conf", "Main configration file.").Default("traefik.toml").String()
version = kingpin.Flag("version", "Get Version.").Short('v').Bool()
currentConfigurations = make(configs)
@@ -44,15 +43,15 @@ func main() {
fmtlog.SetFlags(fmtlog.Lshortfile | fmtlog.LstdFlags)
var srv *manners.GracefulServer
var configurationRouter *mux.Router
var configurationChan = make(chan configMessage, 10)
var configurationChan = make(chan types.ConfigMessage, 10)
defer close(configurationChan)
var configurationChanValidated = make(chan configMessage, 10)
var configurationChanValidated = make(chan types.ConfigMessage, 10)
defer close(configurationChanValidated)
var sigs = make(chan os.Signal, 1)
defer close(sigs)
var stopChan = make(chan bool)
defer close(stopChan)
var providers = []Provider{}
var providers = []provider.Provider{}
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
// load global configuration
@@ -86,22 +85,22 @@ func main() {
// listen new configurations from providers
go func() {
lastReceivedConfiguration := time.Unix(0, 0)
lastConfigs := make(map[string]*configMessage)
lastConfigs := make(map[string]*types.ConfigMessage)
for {
configMsg := <-configurationChan
log.Infof("Configuration receveived from provider %s: %#v", configMsg.providerName, configMsg.configuration)
lastConfigs[configMsg.providerName] = &configMsg
log.Infof("Configuration receveived from provider %s: %#v", configMsg.ProviderName, configMsg.Configuration)
lastConfigs[configMsg.ProviderName] = &configMsg
if time.Now().After(lastReceivedConfiguration.Add(time.Duration(globalConfiguration.ProvidersThrottleDuration))) {
log.Infof("Last %s config received more than %s, OK", configMsg.providerName, globalConfiguration.ProvidersThrottleDuration)
log.Infof("Last %s config received more than %s, OK", configMsg.ProviderName, globalConfiguration.ProvidersThrottleDuration)
// last config received more than n s ago
configurationChanValidated <- configMsg
} else {
log.Infof("Last %s config received less than %s, waiting...", configMsg.providerName, globalConfiguration.ProvidersThrottleDuration)
log.Infof("Last %s config received less than %s, waiting...", configMsg.ProviderName, globalConfiguration.ProvidersThrottleDuration)
go func() {
<-time.After(globalConfiguration.ProvidersThrottleDuration)
if time.Now().After(lastReceivedConfiguration.Add(time.Duration(globalConfiguration.ProvidersThrottleDuration))) {
log.Infof("Waited for %s config, OK", configMsg.providerName)
configurationChanValidated <- *lastConfigs[configMsg.providerName]
log.Infof("Waited for %s config, OK", configMsg.ProviderName)
configurationChanValidated <- *lastConfigs[configMsg.ProviderName]
}
}()
}
@@ -111,9 +110,9 @@ func main() {
go func() {
for {
configMsg := <-configurationChanValidated
if configMsg.configuration == nil {
log.Info("Skipping empty configuration")
} else if reflect.DeepEqual(currentConfigurations[configMsg.providerName], configMsg.configuration) {
if configMsg.Configuration == nil {
log.Info("Skipping empty Configuration")
} else if reflect.DeepEqual(currentConfigurations[configMsg.ProviderName], configMsg.Configuration) {
log.Info("Skipping same configuration")
} else {
// Copy configurations to new map so we don't change current if LoadConfig fails
@@ -121,7 +120,7 @@ func main() {
for k, v := range currentConfigurations {
newConfigurations[k] = v
}
newConfigurations[configMsg.providerName] = configMsg.configuration
newConfigurations[configMsg.ProviderName] = configMsg.Configuration
newConfigurationRouter, err := LoadConfig(newConfigurations, globalConfiguration)
if err == nil {
@@ -266,20 +265,20 @@ func prepareServer(router *mux.Router, globalConfiguration *GlobalConfiguration,
Handler: negroni,
TLSConfig: tlsConfig,
}), nil
} else {
server, err := oldServer.HijackListener(&http.Server{
Addr: globalConfiguration.Port,
Handler: negroni,
}, tlsConfig)
if err != nil {
log.Fatalf("Error hijacking server %s", err)
return nil, err
} else {
return server, nil
}
}
server, err := oldServer.HijackListener(&http.Server{
Addr: globalConfiguration.Port,
Handler: negroni,
}, tlsConfig)
if err != nil {
log.Fatalf("Error hijacking server %s", err)
return nil, err
}
return server, nil
}
// LoadConfig returns a new gorrilla.mux Route from the specified global configuration and the dynamic
// provider configurations.
func LoadConfig(configurations configs, globalConfiguration *GlobalConfiguration) (*mux.Router, error) {
router := mux.NewRouter()
router.NotFoundHandler = http.HandlerFunc(notFoundHandler)
@@ -287,11 +286,14 @@ func LoadConfig(configurations configs, globalConfiguration *GlobalConfiguration
for _, configuration := range configurations {
for frontendName, frontend := range configuration.Frontends {
log.Debugf("Creating frontend %s", frontendName)
fwd, _ := forward.New(forward.Logger(oxyLogger))
fwd, _ := forward.New(forward.Logger(oxyLogger), forward.PassHostHeader(frontend.PassHostHeader))
newRoute := router.NewRoute().Name(frontendName)
for routeName, route := range frontend.Routes {
log.Debugf("Creating route %s %s:%s", routeName, route.Rule, route.Value)
newRouteReflect := Invoke(newRoute, route.Rule, route.Value)
newRouteReflect, err := invoke(newRoute, route.Rule, route.Value)
if err != nil {
return nil, err
}
newRoute = newRouteReflect[0].Interface().(*mux.Route)
}
if backends[frontend.Backend] == nil {
@@ -301,12 +303,12 @@ func LoadConfig(configurations configs, globalConfiguration *GlobalConfiguration
if configuration.Backends[frontend.Backend] == nil {
return nil, errors.New("Backend not found: " + frontend.Backend)
}
lbMethod, err := NewLoadBalancerMethod(configuration.Backends[frontend.Backend].LoadBalancer)
lbMethod, err := types.NewLoadBalancerMethod(configuration.Backends[frontend.Backend].LoadBalancer)
if err != nil {
configuration.Backends[frontend.Backend].LoadBalancer = &LoadBalancer{Method: "wrr"}
configuration.Backends[frontend.Backend].LoadBalancer = &types.LoadBalancer{Method: "wrr"}
}
switch lbMethod {
case drr:
case types.Drr:
log.Infof("Creating load-balancer drr")
rebalancer, _ := roundrobin.NewRebalancer(rr, roundrobin.RebalancerLogger(oxyLogger))
lb = rebalancer
@@ -318,7 +320,7 @@ func LoadConfig(configurations configs, globalConfiguration *GlobalConfiguration
log.Infof("Creating server %s %s", serverName, url.String())
rebalancer.UpsertServer(url, roundrobin.Weight(server.Weight))
}
case wrr:
case types.Wrr:
log.Infof("Creating load-balancer wrr")
lb = middlewares.NewWebsocketUpgrader(rr)
for serverName, server := range configuration.Backends[frontend.Backend].Servers {
@@ -346,25 +348,23 @@ func LoadConfig(configurations configs, globalConfiguration *GlobalConfiguration
newRoute.Handler(backends[frontend.Backend])
err := newRoute.GetError()
if err != nil {
log.Error("Error building route: %s", err)
log.Errorf("Error building route: %s", err)
}
}
}
return router, nil
}
func Invoke(any interface{}, name string, args ...interface{}) []reflect.Value {
// Invoke calls the specified method with the specified arguments on the specified interface.
// It uses the go(lang) reflect package.
func invoke(any interface{}, name string, args ...interface{}) ([]reflect.Value, error) {
inputs := make([]reflect.Value, len(args))
for i := range args {
inputs[i] = reflect.ValueOf(args[i])
}
return reflect.ValueOf(any).MethodByName(name).Call(inputs)
}
func LoadFileConfig(file string) *GlobalConfiguration {
configuration := NewGlobalConfiguration()
if _, err := toml.DecodeFile(file, configuration); err != nil {
fmtlog.Fatalf("Error reading file: %s", err)
method := reflect.ValueOf(any).MethodByName(name)
if method.IsValid() {
return method.Call(inputs), nil
}
return configuration
return nil, errors.New("Method not found: " + name)
}

View File

@@ -138,6 +138,14 @@
#
# filename = "docker.tmpl"
# Enable docker TLS connection
#
# [docker.tls]
# ca = "/etc/ssl/ca.crt"
# cert = "/etc/ssl/docker.crt"
# key = "/etc/ssl/docker.key"
# insecureskipverify = true
################################################################
# Mesos/Marathon configuration backend
@@ -356,6 +364,7 @@
# value = "test.localhost"
# [frontends.frontend2]
# backend = "backend1"
# passHostHeader = true
# [frontends.frontend2.routes.test_2]
# rule = "Path"
# value = "/test"

84
types/types.go Normal file
View File

@@ -0,0 +1,84 @@
package types
import (
"errors"
"strings"
)
// Backend holds backend configuration.
type Backend struct {
Servers map[string]Server `json:"servers,omitempty"`
CircuitBreaker *CircuitBreaker `json:"circuitBreaker,omitempty"`
LoadBalancer *LoadBalancer `json:"loadBalancer,omitempty"`
}
// LoadBalancer holds load balancing configuration.
type LoadBalancer struct {
Method string `json:"method,omitempty"`
}
// CircuitBreaker holds circuit breaker configuration.
type CircuitBreaker struct {
Expression string `json:"expression,omitempty"`
}
// Server holds server configuration.
type Server struct {
URL string `json:"url,omitempty"`
Weight int `json:"weight,omitempty"`
}
// Route holds route configuration.
type Route struct {
Rule string `json:"rule,omitempty"`
Value string `json:"value,omitempty"`
}
// Frontend holds frontend configuration.
type Frontend struct {
Backend string `json:"backend,omitempty"`
Routes map[string]Route `json:"routes,omitempty"`
PassHostHeader bool `json:"passHostHeader,omitempty"`
}
// LoadBalancerMethod holds the method of load balancing to use.
type LoadBalancerMethod uint8
const (
// Wrr (default) = Weighted Round Robin
Wrr LoadBalancerMethod = iota
// Drr = Dynamic Round Robin
Drr
)
var loadBalancerMethodNames = []string{
"Wrr",
"Drr",
}
// NewLoadBalancerMethod create a new LoadBalancerMethod from a given LoadBalancer.
func NewLoadBalancerMethod(loadBalancer *LoadBalancer) (LoadBalancerMethod, error) {
if loadBalancer != nil {
for i, name := range loadBalancerMethodNames {
if strings.EqualFold(name, loadBalancer.Method) {
return LoadBalancerMethod(i), nil
}
}
}
return Wrr, ErrInvalidLoadBalancerMethod
}
// ErrInvalidLoadBalancerMethod is thrown when the specified load balancing method is invalid.
var ErrInvalidLoadBalancerMethod = errors.New("Invalid method, using default")
// Configuration of a provider.
type Configuration struct {
Backends map[string]*Backend `json:"backends,omitempty"`
Frontends map[string]*Frontend `json:"frontends,omitempty"`
}
// ConfigMessage hold configuration information exchanged between parts of traefik.
type ConfigMessage struct {
ProviderName string
Configuration *Configuration
}

8
version.go Normal file
View File

@@ -0,0 +1,8 @@
package main
var (
// Version holds the current version of traefik.
Version = ""
// BuildDate holds the build date of traefik.
BuildDate = ""
)

14
web.go
View File

@@ -8,10 +8,14 @@ import (
log "github.com/Sirupsen/logrus"
"github.com/elazarl/go-bindata-assetfs"
"github.com/emilevauge/traefik/autogen"
"github.com/emilevauge/traefik/types"
"github.com/gorilla/mux"
"github.com/unrolled/render"
)
// WebProvider is a provider.Provider implementation that provides the UI.
// FIXME to be handled another way.
type WebProvider struct {
Address string
CertFile, KeyFile string
@@ -23,7 +27,9 @@ var (
})
)
func (provider *WebProvider) Provide(configurationChan chan<- configMessage) error {
// Provide allows the provider to provide configurations to traefik
// using the given configuration channel.
func (provider *WebProvider) Provide(configurationChan chan<- types.ConfigMessage) error {
systemRouter := mux.NewRouter()
// health route
@@ -41,11 +47,11 @@ func (provider *WebProvider) Provide(configurationChan chan<- configMessage) err
return
}
configuration := new(Configuration)
configuration := new(types.Configuration)
body, _ := ioutil.ReadAll(request.Body)
err := json.Unmarshal(body, configuration)
if err == nil {
configurationChan <- configMessage{"web", configuration}
configurationChan <- types.ConfigMessage{"web", configuration}
getConfigHandler(response, request)
} else {
log.Errorf("Error parsing configuration %+v", err)
@@ -65,7 +71,7 @@ func (provider *WebProvider) Provide(configurationChan chan<- configMessage) err
systemRouter.Methods("GET").Path("/").HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
http.Redirect(response, request, "/dashboard/", 302)
})
systemRouter.Methods("GET").PathPrefix("/dashboard/").Handler(http.StripPrefix("/dashboard/", http.FileServer(&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "static"})))
systemRouter.Methods("GET").PathPrefix("/dashboard/").Handler(http.StripPrefix("/dashboard/", http.FileServer(&assetfs.AssetFS{Asset: autogen.Asset, AssetDir: autogen.AssetDir, Prefix: "static"})))
go func() {
if len(provider.CertFile) > 0 && len(provider.KeyFile) > 0 {

14
zk.go
View File

@@ -1,14 +0,0 @@
package main
type ZookepperProvider struct {
Watch bool
Endpoint string
Prefix string
Filename string
KvProvider *KvProvider
}
func (provider *ZookepperProvider) Provide(configurationChan chan<- configMessage) error {
provider.KvProvider = NewZkProvider(provider)
return provider.KvProvider.provide(configurationChan)
}