Compare commits

...

32 Commits

Author SHA1 Message Date
Vincent Demeester
784fd74d3f Merge pull request #138 from dylanmei/marathon_uses_port_from_label
Marathon provider uses port from label.
2016-01-13 08:30:00 +01:00
Dylan Meissner
cfbd43d1ee Marathon provider uses port or portIndex from label. 2016-01-12 06:46:29 -08:00
Vincent Demeester
f10bbd8c69 Merge pull request #153 from PierreZ/master
Fix Issue #150: Add possibility to have REST API in read-only mode
2016-01-09 00:32:53 +01:00
Pierre Zemb
6bcb6f92f5 Update Doc about read-only mode 2016-01-03 20:45:53 +01:00
PierreZ
f6b5684a5b adding read only mode 2016-01-03 20:42:09 +01:00
Vincent Demeester
866e8db5f7 Merge pull request #137 from dylanmei/marathon_route_names_with_slashes
Marathon tmpl converts slashes in Marathon app names to dashes
2015-12-07 22:12:45 +01:00
Dylan Meissner
a9925c7521 The included Marathon tmpl converts multiple slashes in Marathon app names to dashes. 2015-12-05 10:02:39 -08:00
Vincent Demeester
f955cc33c5 Merge pull request #134 from emilevauge/add-getBool-kvprovider-or-not
Removes getBool from kv provider
2015-12-04 09:41:36 +01:00
emile
e728f32a15 Removes getBool from kv provider, fixes https://github.com/emilevauge/traefik/issues/117 2015-12-04 09:28:43 +01:00
Vincent Demeester
4abb4c6489 Merge pull request #135 from ViBiOh/master
Adding expose for default port
2015-12-03 17:45:22 +01:00
Vincent Boutour
66998e60b8 Adding expose for default port 2015-12-03 17:15:01 +01:00
Vincent Demeester
71288e5799 Merge pull request #123 from emilevauge/alltasks-status-marathon
Add filter task by running status in marathon
2015-12-02 09:49:28 +01:00
emile
8fdd0b20d1 Add filter task by running status in marathon 2015-12-01 22:53:31 +01:00
Emile Vauge
4e9ff45747 Merge pull request #121 from janeczku/sni-support
Add TLS SNI support
2015-12-01 22:52:27 +01:00
Jan Broer
d6e28a923c Adds TLS SNI support for the frontends 2015-12-01 22:26:17 +01:00
Vincent Demeester
1604786285 Merge pull request #126 from emilevauge/lock-prepareserver
Add mutex around prepareserver
2015-11-24 10:20:44 +01:00
emile
35cb9100cd Add mutex around prepareserver 2015-11-24 09:12:20 +01:00
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
35 changed files with 2939 additions and 492 deletions

View File

@@ -1,4 +1,5 @@
FROM scratch
COPY script/ca-certificates.crt /etc/ssl/certs/
COPY dist/traefik /
EXPOSE 80
ENTRYPOINT ["/traefik"]

View File

@@ -40,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
@@ -48,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

@@ -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)

View File

@@ -4,6 +4,7 @@ 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,18 +1,22 @@
package main
import (
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
AccessLogsFile string
TraefikLogsFile string
CertFile, KeyFile string
Certificates []Certificate
LogLevel string
ProvidersThrottleDuration time.Duration
Docker *provider.Docker
@@ -25,6 +29,13 @@ type GlobalConfiguration struct {
Boltdb *provider.BoltDb
}
// Certificate holds a SSL cert/key pair
type Certificate struct {
CertFile string
KeyFile string
}
// NewGlobalConfiguration returns a GlobalConfiguration with default values.
func NewGlobalConfiguration() *GlobalConfiguration {
globalConfiguration := new(GlobalConfiguration)
// default values
@@ -36,4 +47,13 @@ func NewGlobalConfiguration() *GlobalConfiguration {
return globalConfiguration
}
// 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 configuration
}
type configs map[string]*types.Configuration

View File

@@ -102,10 +102,12 @@ For example:
#
# logLevel = "ERROR"
# SSL certificate and key used
# SSL certificates and keys
# You may add several certificate/key pairs to terminate HTTPS for multiple domain names using TLS SNI
#
# Optional
#
# [[certificates]]
# CertFile = "traefik.crt"
# KeyFile = "traefik.key"
@@ -241,6 +243,11 @@ address = ":8080"
#
# CertFile = "traefik.crt"
# KeyFile = "traefik.key"
#
# Set REST API to read-only mode
#
# Optional
# ReadOnly = false
```
- `/`: provides a simple HTML frontend of Træfik
@@ -404,6 +411,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:
@@ -472,7 +487,8 @@ domain = "marathon.localhost"
Labels can be used on containers to override default behaviour:
- `traefik.backend=foo`: assign the application to `foo` backend
- `traefik.port=80`: register this port. Useful when the application exposes multiples ports.
- `traefik.portIndex=1`: register port by index in the application's ports array. Useful when the application exposes multiple ports.
- `traefik.port=80`: register the explicit application port value. Cannot be used alongside `traefik.portIndex`.
- `traefik.protocol=https`: override the default `http` protocol
- `traefik.weight=10`: assign this weight to the application
- `traefik.enable=false`: disable this application in Træfɪk

View File

@@ -43,7 +43,7 @@ import:
- package: github.com/alecthomas/units
ref: 6b4e7dc5e3143b85ea77909c72caf89416fc2915
- package: github.com/gambol99/go-marathon
ref: 0ba31bcb0d7633ba1888d744c42990eb15281cf1
ref: 8ce3f764250b2de3f2c627d12ca7dd21bd5e7f93
- package: github.com/mailgun/predicate
ref: cb0bff91a7ab7cf7571e661ff883fc997bc554a3
- package: github.com/thoas/stats
@@ -142,3 +142,8 @@ import:
- package: github.com/codahale/hdrhistogram
ref: 954f16e8b9ef0e5d5189456aa4c1202758e04f17
- package: github.com/gorilla/websocket
- package: github.com/donovanhide/eventsource
ref: d8a3071799b98cacd30b6da92f536050ccfe6da4
- package: github.com/golang/glog
ref: fca8c8854093a154ff1eb580aae10276ad6b1b5f

View File

@@ -15,7 +15,7 @@ func (s *FileSuite) TestSimpleConfiguration(c *check.C) {
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
@@ -30,7 +30,7 @@ func (s *FileSuite) TestSimpleConfigurationNoPanic(c *check.C) {
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

View File

@@ -0,0 +1,32 @@
port = ":443"
logLevel = "DEBUG"
[[certificates]]
CertFile = "fixtures/https/snitest.com.cert"
KeyFile = "fixtures/https/snitest.com.key"
[[certificates]]
CertFile = "fixtures/https/snitest.org.cert"
KeyFile = "fixtures/https/snitest.org.key"
[file]
[backends]
[backends.backend1]
[backends.backend1.servers.server1]
url = "http://127.0.0.1:9010"
[backends.backend2]
[backends.backend2.servers.server1]
url = "http://127.0.0.1:9020"
[frontends]
[frontends.frontend1]
backend = "backend1"
[frontends.frontend1.routes.test_1]
rule = "Host"
value = "snitest.com"
[frontends.frontend2]
backend = "backend2"
[frontends.frontend2.routes.test_2]
rule = "Host"
value = "snitest.org"

View File

@@ -0,0 +1,19 @@
-----BEGIN CERTIFICATE-----
MIIC/zCCAeegAwIBAgIJAL858pci5XyjMA0GCSqGSIb3DQEBBQUAMBYxFDASBgNV
BAMMC3NuaXRlc3QuY29tMB4XDTE1MTEyMzIyMDU1NloXDTI1MTEyMDIyMDU1Nlow
FjEUMBIGA1UEAwwLc25pdGVzdC5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
ggEKAoIBAQDVF25wEroSIUO/dNgHxlyt8pZFVpJ8fNaJw7cnlZ1JP2hLuEbmjAFT
dHqS8wKDNYHktsBEOUfN/qbk0AiGb+SvhQw6kfM/QSj9fXVQ7KhYP9XYOekTOH7d
M0Z2L3RGgqs8z+83exOOnAFVvIJCMZJXEeijV6iJlmpCcJa0Kg/JHlxhoWTEeZuU
G+hITafk1yWOKorTCPlMhB30wuQoWfbHP+3G0bsERLXFiMANE8EtQu8+ZhfseBUh
5Tu5gIC4Fnria7mRixAZeEiAblFP9h0vrNRcP3nmuVz0tHPIeQsJQiEhxaZ09oUW
h9WqTsYCP1821+SVazM9oFRTpy6chZyTAgMBAAGjUDBOMB0GA1UdDgQWBBSz9mbX
ia1TM5FG4Zgagaet24S8HDAfBgNVHSMEGDAWgBSz9mbXia1TM5FG4Zgagaet24S8
HDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQB79W8XTxlozh9w/W7T
5vDev67G4T/wetABSb68CRrqojt78PMJuS89JarA8I3ts00O+0JYnsHxp+9qC7pf
jWHcDSiLwRUMu7MXW/KIen1EB8BQNA0xWbAiQaWYPHzsBlX48+9wBe0HTDx7Lcxb
OsmnXHBF5fd2EY+R8qJu+PyTDDL1WLItFJpzHiFiGiYF8Tyic3kkPjje6eIOxRmT
hq+qbwApzbzz6h/VD5xR3zBDFBo2Xs5tdP264KIw/YXDpaXVBiJ5DDjQ3dtJw1G5
yzgrHQZWJN8Gs8ZZgGdgRf7PHox8xEZtqPiMkChDz6T7Ha3U0xYN6TZGNZOR6DHs
K9/8
-----END CERTIFICATE-----

View File

@@ -0,0 +1,27 @@
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEA1RducBK6EiFDv3TYB8ZcrfKWRVaSfHzWicO3J5WdST9oS7hG
5owBU3R6kvMCgzWB5LbARDlHzf6m5NAIhm/kr4UMOpHzP0Eo/X11UOyoWD/V2Dnp
Ezh+3TNGdi90RoKrPM/vN3sTjpwBVbyCQjGSVxHoo1eoiZZqQnCWtCoPyR5cYaFk
xHmblBvoSE2n5NcljiqK0wj5TIQd9MLkKFn2xz/txtG7BES1xYjADRPBLULvPmYX
7HgVIeU7uYCAuBZ64mu5kYsQGXhIgG5RT/YdL6zUXD955rlc9LRzyHkLCUIhIcWm
dPaFFofVqk7GAj9fNtfklWszPaBUU6cunIWckwIDAQABAoIBABAdQYDAKcoNMe5c
i6mq2n9dBPghX9qCJkcswcEAk3BilySCvvnYRJFnEY3jSqFZfoUpPMjr+/4b78sF
4F8qPwT27sHPH7H833ir8B86hlCGI0nCt1l4wD9CDWYKmKRsZT6oCtMLP6NdMMyn
AMK4tPRYqlsP2fLtqQN1ODBPrfnraoNHtOVE784iBCD5dewICA5RIQG2i/d2+CGF
+bahFqUXVCqHoxBz4AVvrRFL99VcP7P2iZyk6hDQ7fci7Xay8Wb/HutRxuqvF0aU
bG6Enk6CCtNZHLwNPp4Hqft0Udvg2tG8okYwbEmoEO40nQsCSzRCpq5Uvzi+LX1k
LykQ6+ECgYEA7x8vQoyOK60Q3LPpJFGDec2+XJPoesTfJTT6idaP7ukUL8p3FsUo
9vtxRRfhSOdPoAINmrL0TyMekO2B6zXx0pmWVpMrFwZW6zMwZAnLp/w+3USpbGCy
K12IIwvRYzTzKwoMTVAKTXm36b6oqr2La4bTdJR7REY6G374FrJb/H0CgYEA5CHk
Ym0h7cf00fw9UEHRfzUZxmCfRWY6K8InOuHdLi+u4TiyXzs8x5s0e/DN/raNmTGx
QO81UzuS3nKwc4n5QyXjVnhzR5DbbSACDwHtdnxZByL0D1KvPjtRF8F+rWXViXv2
TM7UiOmn6R375FPSAPxeyMx8Womc3EnAAfLWGk8CgYEAv8I2WBv3dzcWqqbsdF+a
G/fOjNdgO/PdLy1JLXiPfHwV4C1xSyVZMJd7wnjgBWLaC+sZldGk8kGrpXWSFlnw
T38zfMIQcCp5Uax/RfpFA7XZhAAoDe2NdBFRtyknBXPU/dLVArsJSBAwWJa5FBNk
1xoMQRVBtQLMXnh341utQNECgYEA4o1R2/ka16NaWmpPjXM/lD9skFgF84p4vFn8
UXpaB3LtDdcbNH2Ed4mHToouWAR8jCUQLTcg0r53tRdaafMcKfXnVUka2nhdoHpH
8RVt99u3IeIxU0I+q+OGPbw3jAV0UStcxpwj7q9zw4q2SuJ+y+HUUz7XQ6Yjs5Q9
7PF2c/sCgYEAhdVn5gZ5FvYKrBi46t3pxPsWK476HmQEVHVi5+od7wg+araDelAe
8QE8hc8qdZGbjdB/AHSPCeUxfO2vnpsCoSRs29o6pDvQuqvHYs+M53l5LEYeOjof
t6J/DK5Pim2CAFjYFcZk8/Gyl5HjTw3PpdWxoPD5v2Xw3bbY57IIbm4=
-----END RSA PRIVATE KEY-----

View File

@@ -0,0 +1,19 @@
-----BEGIN CERTIFICATE-----
MIIC/zCCAeegAwIBAgIJALAYHG/vGqWEMA0GCSqGSIb3DQEBBQUAMBYxFDASBgNV
BAMMC3NuaXRlc3Qub3JnMB4XDTE1MTEyMzIyMDU0NFoXDTI1MTEyMDIyMDU0NFow
FjEUMBIGA1UEAwwLc25pdGVzdC5vcmcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
ggEKAoIBAQC8b2Qv68Xnv4wgJ6HNupxABSUA5KXmv9g7pwwsFMSOK15o2qGFzx/x
9loIi5pMIYIy4SVwJNrYUi772nCYMqSIVXlwct/CE70j2Jb2geIHu3jHbFWXruWb
W1tGGUYzvnsOUziPE3rLWa/NObNYLLlUKJaxfHrxnpuKpQUsXzoLl25cJEVr4jg2
ZITpdraxaBLisdlWY7EwwHBLu2nxH5Rn+nIjenFfdUwKF9s5dGy63tfBc8LX9yJk
+kOwy1al/Wxa0DUb6rSt0QDCcD+rXnjk2zWPtsHz1btwtqM+FLtN5z0Lmnx7DF3C
tCf1TMzduzZ6aeHk77zc664ZQun5cH33AgMBAAGjUDBOMB0GA1UdDgQWBBRn/nNz
PUsmDKmKv3GGo3km5KKvUDAfBgNVHSMEGDAWgBRn/nNzPUsmDKmKv3GGo3km5KKv
UDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQBkuutIcbBdESgvNLLr
k/8HUDuFm72lYHZFE+c76CxqYN52w02NCTiq1InoDUvqZXb/StATBwRRduTUPCj9
KUkC7pOjAFxjzjExsHrtZSq01WinrxNI+qSKvI8jFngMHnwN1omTt7/D7nxeW5Of
FJTkElnxtELAGHoIwZ+bKprnexefpn9UW84VJvJ2crSR63vBvdTrgsrEGW6kQj1I
62laDpax4+x8t2h+sfG6uNIA1cFrG8Sk+O2Bi3ogB7Y/4e8r6WA23IRP+aSv0J2b
k5fvuuXbIc979pQOoO03zG0S7Wpmpsw+9dQB9TOxGITOLfCZwEuIhnv+M9lLqCks
7H2A
-----END CERTIFICATE-----

View File

@@ -0,0 +1,27 @@
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAvG9kL+vF57+MICehzbqcQAUlAOSl5r/YO6cMLBTEjiteaNqh
hc8f8fZaCIuaTCGCMuElcCTa2FIu+9pwmDKkiFV5cHLfwhO9I9iW9oHiB7t4x2xV
l67lm1tbRhlGM757DlM4jxN6y1mvzTmzWCy5VCiWsXx68Z6biqUFLF86C5duXCRF
a+I4NmSE6Xa2sWgS4rHZVmOxMMBwS7tp8R+UZ/pyI3pxX3VMChfbOXRsut7XwXPC
1/ciZPpDsMtWpf1sWtA1G+q0rdEAwnA/q1545Ns1j7bB89W7cLajPhS7Tec9C5p8
ewxdwrQn9UzM3bs2emnh5O+83OuuGULp+XB99wIDAQABAoIBAGOn9bByXQQnhZAr
5aLMIn6pOdyzEBptM4q42fMmOJ2HyjJiDjKaTCbHRu5mBoBk6FrIP+iDVUo6jKad
7BZSEjoYGlWiKzyU+97NWWmdX1D/kOzHGq1RzhTPyAHWtA4Bm0sEMFFa2AJbuGIt
NfBYFtuva6MKVmsamuBETewdoLEnxzzDFcuOaxXRfTC/ikWcYyB4KEWA5fjroUQC
Llo9/UTGTkh1Hynv9AXY6Qia/RbrIQjKveKCRj6PjxyE/qN9qfmngczz2pK0hRhL
Z+K06y8G+Yj1I1zm5jNg1kakVQKoBsnaYkmIUBUSmWv6ERotedOWtOAMlOKa+0l2
DS7Ou2ECgYEA91doi+3XrMVsgyTEm/ArzEyRUfM5dCSvBCRFhO7QQp2OYAbjJk5S
pmdpqmwTsXNNMU+XNkWCLug5pk0PTJwP0mVLE2fLYqCCXoyaMltQ0Yk2gaun/RwE
w5EfyMwOQakLFY/ODvduQfyNpaoWgFz4/WPNTVNCGs04LepSGKaFNy0CgYEAwwgV
jKeFA+QZGooTInyk07ZlAbenEPu/c2y3UUFxclP0CjP2/VBOpz9B62vhzCKbjD1c
/L3x1CKC4n4lbeyHi4vrF69LX9SHr1Jm0SUtyKeV3g0EAzIWI0HFhVUkMvtbibQ4
HXrLVCJO77xetQ7RQszss1z9g3WotAAiBMiQgDMCgYBTLjoilOIrYFmV4Q+dwa95
DWbxwHJZ9NxG8EvQ4N95B7OR578Matqwy6ZlgeM9kiErrDCWN9oIHGEG5HN4uCM6
BoaxB/8GNCSj13Uj6kHLtfF2ulvMa1fOzUd7J+TDgC4SGkKaFewmlOCuDf1zPdEe
pimtD4rzqIB0MJFbaOT0IQKBgDBPjlb7IB3ooLdMQJUoXwP6iGa2gXHZioEjCv3b
wihZ13e3i5UQEYuoRcH1RUd1wyYoBSKuQnsT2WwVZ1wlXSYaELAbQgaI9NtfBA0G
sqKjsKICg13vSECPiEgQ4Rin3vLra4MR6c/7d6Y2+RbMhtWPQYrkm/+2Y4XDCqo4
rGK1AoGAOFZ3RVhuwXzFdKNe32LM1wm1eZ7waxjI4bQS2xUN/3C/uWS7A3LaSlc3
eRG3DaVpez4DQVupZDHMgxJUYqqKynUj6GD1YiaxGROj3TYCu6e7OxyhalhCllSu
w/X5M802XqzLjeec5zHoZDfknnAkgR9MsxZYmZPFaDyL6GOKUB8=
-----END RSA PRIVATE KEY-----

110
integration/https_test.go Normal file
View File

@@ -0,0 +1,110 @@
package main
import (
"crypto/tls"
"net"
"net/http"
"net/http/httptest"
"os/exec"
"time"
checker "github.com/vdemeester/shakers"
check "gopkg.in/check.v1"
)
// HTTPSSuite
type HTTPSSuite struct{ BaseSuite }
// TestWithSNIConfigHandshake involves a client sending a SNI hostname of
// "snitest.com", which happens to match the CN of 'snitest.com.crt'. The test
// verifies that traefik presents the correct certificate.
func (s *HTTPSSuite) TestWithSNIConfigHandshake(c *check.C) {
cmd := exec.Command(traefikBinary, "fixtures/https/https_sni.toml")
err := cmd.Start()
c.Assert(err, checker.IsNil)
defer cmd.Process.Kill()
time.Sleep(500 * time.Millisecond)
tlsConfig := &tls.Config{
InsecureSkipVerify: true,
ServerName: "snitest.com",
}
conn, err := tls.Dial("tcp", "127.0.0.1:443", tlsConfig)
c.Assert(err, checker.IsNil, check.Commentf("failed to connect to server"))
defer conn.Close()
err = conn.Handshake()
c.Assert(err, checker.IsNil, check.Commentf("TLS handshake error"))
cs := conn.ConnectionState()
err = cs.PeerCertificates[0].VerifyHostname("snitest.com")
c.Assert(err, checker.IsNil, check.Commentf("certificate did not match SNI servername"))
}
// TestWithSNIConfigRoute involves a client sending HTTPS requests with
// SNI hostnames of "snitest.org" and "snitest.com". The test verifies
// that traefik routes the requests to the expected backends.
func (s *HTTPSSuite) TestWithSNIConfigRoute(c *check.C) {
cmd := exec.Command(traefikBinary, "fixtures/https/https_sni.toml")
err := cmd.Start()
c.Assert(err, checker.IsNil)
defer cmd.Process.Kill()
backend1 := startTestServer("9010", 204)
backend2 := startTestServer("9020", 205)
defer backend1.Close()
defer backend2.Close()
time.Sleep(2000 * time.Millisecond)
tr1 := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
ServerName: "snitest.com",
},
}
tr2 := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
ServerName: "snitest.org",
},
}
client := &http.Client{Transport: tr1}
req, _ := http.NewRequest("GET", "https://127.0.0.1/", nil)
req.Host = "snitest.com"
req.Header.Set("Host", "snitest.com")
req.Header.Set("Accept", "*/*")
resp, err := client.Do(req)
c.Assert(err, checker.IsNil)
// Expected a 204 (from backend1)
c.Assert(resp.StatusCode, checker.Equals, 204)
client = &http.Client{Transport: tr2}
req, _ = http.NewRequest("GET", "https://127.0.0.1/", nil)
req.Host = "snitest.org"
req.Header.Set("Host", "snitest.org")
req.Header.Set("Accept", "*/*")
resp, err = client.Do(req)
c.Assert(err, checker.IsNil)
// Expected a 205 (from backend2)
c.Assert(resp.StatusCode, checker.Equals, 205)
}
func startTestServer(port string, statusCode int) (ts *httptest.Server) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(statusCode)
})
listener, err := net.Listen("tcp", "127.0.0.1:"+port)
if err != nil {
panic(err)
}
ts = &httptest.Server{
Listener: listener,
Config: &http.Server{Handler: handler},
}
ts.Start()
return
}

View File

@@ -24,6 +24,7 @@ func Test(t *testing.T) {
func init() {
check.Suite(&SimpleSuite{})
check.Suite(&HTTPSSuite{})
check.Suite(&FileSuite{})
check.Suite(&DockerSuite{})
check.Suite(&ConsulSuite{})

View File

@@ -1,19 +1,20 @@
package provider
import "github.com/emilevauge/traefik/types"
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 {
Watch bool
Endpoint string
Prefix string
Filename string
KvProvider *Kv
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.KvProvider = NewBoltDbProvider(provider)
return provider.KvProvider.provide(configurationChan)
provider.StoreType = store.BOLTDB
boltdb.Register()
return provider.provide(configurationChan)
}

View File

@@ -1,19 +1,20 @@
package provider
import "github.com/emilevauge/traefik/types"
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 {
Watch bool
Endpoint string
Prefix string
Filename string
KvProvider *Kv
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.KvProvider = NewConsulProvider(provider)
return provider.KvProvider.provide(configurationChan)
provider.StoreType = store.CONSUL
consul.Register()
return provider.provide(configurationChan)
}

View File

@@ -1,7 +1,6 @@
package provider
import (
"bytes"
"errors"
"fmt"
"strconv"
@@ -9,28 +8,45 @@ import (
"text/template"
"time"
"github.com/BurntSushi/toml"
"github.com/BurntSushi/ty/fun"
log "github.com/Sirupsen/logrus"
"github.com/cenkalti/backoff"
"github.com/emilevauge/traefik/autogen"
"github.com/emilevauge/traefik/types"
"github.com/fsouza/go-dockerclient"
)
// Docker holds configurations of the Docker provider.
type Docker struct {
Watch bool
baseProvider
Endpoint string
Filename 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 {
dockerClient, err := docker.NewClient(provider.Endpoint)
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
@@ -55,9 +71,12 @@ func (provider *Docker) Provide(configurationChan chan<- types.ConfigMessage) er
}
if event.Status == "start" || event.Status == "die" {
log.Debugf("Docker event receveived %+v", event)
configuration := provider.loadDockerConfig(dockerClient)
configuration := provider.loadDockerConfig(listContainers(dockerClient))
if configuration != nil {
configurationChan <- types.ConfigMessage{"docker", configuration}
configurationChan <- types.ConfigMessage{
ProviderName: "docker",
Configuration: configuration,
}
}
}
}
@@ -72,94 +91,31 @@ func (provider *Docker) Provide(configurationChan chan<- types.ConfigMessage) er
}()
}
configuration := provider.loadDockerConfig(dockerClient)
configurationChan <- types.ConfigMessage{"docker", configuration}
configuration := provider.loadDockerConfig(listContainers(dockerClient))
configurationChan <- types.ConfigMessage{
ProviderName: "docker",
Configuration: configuration,
}
return nil
}
func (provider *Docker) loadDockerConfig(dockerClient *docker.Client) *types.Configuration {
func (provider *Docker) loadDockerConfig(containersInspected []docker.Container) *types.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"
},
"getPassHostHeader": func(container docker.Container) string {
if passHostHeader, err := provider.getLabel(container, "traefik.frontend.passHostHeader"); err == nil {
return passHostHeader
}
return "false"
},
"getFrontendValue": provider.GetFrontendValue,
"getFrontendRule": provider.GetFrontendRule,
"replace": func(s1 string, s2 string, s3 string) string {
return strings.Replace(s3, s1, s2, -1)
},
}
configuration := new(types.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)
"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(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
}
labels, err := provider.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
}, containersInspected).([]docker.Container)
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)
}
@@ -173,50 +129,112 @@ func (provider *Docker) loadDockerConfig(dockerClient *docker.Client) *types.Con
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 := autogen.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)
configuration, err := provider.getConfiguration("templates/docker.tmpl", DockerFuncMap, 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
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 := 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)
}
func (provider *Docker) getEscapedName(name string) string {
return strings.Replace(name, "/", "", -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
}
func (provider *Docker) getLabel(container docker.Container, label string) (string, error) {
// 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
@@ -225,11 +243,11 @@ func (provider *Docker) getLabel(container docker.Container, label string) (stri
return "", errors.New("Label not found:" + label)
}
func (provider *Docker) getLabels(container docker.Container, labels []string) (map[string]string, error) {
func getLabels(container docker.Container, labels []string) (map[string]string, error) {
var globalErr error
foundLabels := map[string]string{}
for _, label := range labels {
foundLabel, err := provider.getLabel(container, label)
foundLabel, err := getLabel(container, label)
// Error out only if one of them is defined.
if err != nil {
globalErr = errors.New("Label not found: " + label)
@@ -241,20 +259,14 @@ func (provider *Docker) getLabels(container docker.Container, labels []string) (
return foundLabels, globalErr
}
// 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 := provider.getLabel(container, "traefik.frontend.value"); err == nil {
return label
}
return provider.getEscapedName(container.Name) + "." + provider.Domain
}
func listContainers(dockerClient *docker.Client) []docker.Container {
containerList, _ := dockerClient.ListContainers(docker.ListContainersOptions{})
containersInspected := []docker.Container{}
// 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 := provider.getLabel(container, "traefik.frontend.rule"); err == nil {
return label
// get inspect containers
for _, container := range containerList {
containerInspected, _ := dockerClient.InspectContainer(container.ID)
containersInspected = append(containersInspected, *containerInspected)
}
return "Host"
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)
}
}
}

View File

@@ -1,19 +1,20 @@
package provider
import "github.com/emilevauge/traefik/types"
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 {
Watch bool
Endpoint string
Prefix string
Filename string
KvProvider *Kv
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.KvProvider = NewEtcdProvider(provider)
return provider.KvProvider.provide(configurationChan)
provider.StoreType = store.ETCD
etcd.Register()
return provider.provide(configurationChan)
}

View File

@@ -13,8 +13,7 @@ import (
// File holds configurations of the File provider.
type File struct {
Watch bool
Filename string
baseProvider
}
// Provide allows the provider to provide configurations to traefik
@@ -44,7 +43,10 @@ func (provider *File) Provide(configurationChan chan<- types.ConfigMessage) erro
log.Debug("File event:", event)
configuration := provider.loadFileConfig(file.Name())
if configuration != nil {
configurationChan <- types.ConfigMessage{"file", configuration}
configurationChan <- types.ConfigMessage{
ProviderName: "file",
Configuration: configuration,
}
}
}
case error := <-watcher.Errors:
@@ -60,7 +62,10 @@ func (provider *File) Provide(configurationChan chan<- types.ConfigMessage) erro
}
configuration := provider.loadFileConfig(file.Name())
configurationChan <- types.ConfigMessage{"file", configuration}
configurationChan <- types.ConfigMessage{
ProviderName: "file",
Configuration: configuration,
}
return nil
}

View File

@@ -2,92 +2,27 @@
package provider
import (
"bytes"
"errors"
"strings"
"text/template"
"time"
"github.com/BurntSushi/toml"
"github.com/BurntSushi/ty/fun"
log "github.com/Sirupsen/logrus"
"github.com/docker/libkv"
"github.com/docker/libkv/store"
"github.com/docker/libkv/store/boltdb"
"github.com/docker/libkv/store/consul"
"github.com/docker/libkv/store/etcd"
"github.com/docker/libkv/store/zookeeper"
"github.com/emilevauge/traefik/autogen"
"github.com/emilevauge/traefik/types"
)
// Kv holds common configurations of key-value providers.
type Kv struct {
Watch bool
baseProvider
Endpoint string
Prefix string
Filename string
StoreType store.Backend
kvclient store.Store
}
// NewConsulProvider returns a Consul provider.
func NewConsulProvider(provider *Consul) *Kv {
kvProvider := new(Kv)
kvProvider.Watch = provider.Watch
kvProvider.Endpoint = provider.Endpoint
kvProvider.Prefix = provider.Prefix
kvProvider.Filename = provider.Filename
kvProvider.StoreType = store.CONSUL
return kvProvider
}
// NewEtcdProvider returns a Etcd provider.
func NewEtcdProvider(provider *Etcd) *Kv {
kvProvider := new(Kv)
kvProvider.Watch = provider.Watch
kvProvider.Endpoint = provider.Endpoint
kvProvider.Prefix = provider.Prefix
kvProvider.Filename = provider.Filename
kvProvider.StoreType = store.ETCD
return kvProvider
}
// NewZkProvider returns a Zookepper provider.
func NewZkProvider(provider *Zookepper) *Kv {
kvProvider := new(Kv)
kvProvider.Watch = provider.Watch
kvProvider.Endpoint = provider.Endpoint
kvProvider.Prefix = provider.Prefix
kvProvider.Filename = provider.Filename
kvProvider.StoreType = store.ZK
return kvProvider
}
// NewBoltDbProvider returns a BoldDb provider.
func NewBoltDbProvider(provider *BoltDb) *Kv {
kvProvider := new(Kv)
kvProvider.Watch = provider.Watch
kvProvider.Endpoint = provider.Endpoint
kvProvider.Prefix = provider.Prefix
kvProvider.Filename = provider.Filename
kvProvider.StoreType = store.BOLTDB
return kvProvider
}
func (provider *Kv) provide(configurationChan chan<- types.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},
@@ -114,88 +49,70 @@ func (provider *Kv) provide(configurationChan chan<- types.ConfigMessage) error
<-chanKeys
configuration := provider.loadConfig()
if configuration != nil {
configurationChan <- types.ConfigMessage{string(provider.StoreType), configuration}
configurationChan <- types.ConfigMessage{
ProviderName: string(provider.StoreType),
Configuration: configuration,
}
}
defer close(stopCh)
}
}()
}
configuration := provider.loadConfig()
configurationChan <- types.ConfigMessage{string(provider.StoreType), configuration}
configurationChan <- types.ConfigMessage{
ProviderName: string(provider.StoreType),
Configuration: configuration,
}
return nil
}
func (provider *Kv) loadConfig() *types.Configuration {
configuration := new(types.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]
},
"List": provider.list,
"Get": provider.get,
"Last": provider.last,
}
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 := autogen.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)
configuration, err := provider.getConfiguration("templates/kv.tmpl", KvFuncMap, templateObjects)
if err != nil {
log.Error("Error with kv template:", err)
return nil
log.Error(err)
}
if _, err := toml.Decode(buffer.String(), configuration); err != nil {
log.Error("Error creating kv configuration:", err)
log.Error(buffer.String())
return nil
}
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) last(key string) string {
splittedKey := strings.Split(key, "/")
return splittedKey[len(splittedKey)-1]
}

312
provider/kv_test.go Normal file
View File

@@ -0,0 +1,312 @@
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 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
}

View File

@@ -1,28 +1,29 @@
package provider
import (
"bytes"
"errors"
"net/url"
"strconv"
"strings"
"text/template"
"github.com/BurntSushi/toml"
"github.com/BurntSushi/ty/fun"
log "github.com/Sirupsen/logrus"
"github.com/emilevauge/traefik/autogen"
"github.com/emilevauge/traefik/types"
"github.com/gambol99/go-marathon"
)
// Marathon holds configuration of the Marathon provider.
type Marathon struct {
Watch bool
baseProvider
Endpoint string
Domain string
Filename string
NetworkInterface string
marathonClient marathon.Marathon
marathonClient lightMarathonClient
}
type lightMarathonClient interface {
Applications(url.Values) (*marathon.Applications, error)
AllTasks(v url.Values) (*marathon.Tasks, error)
}
// Provide allows the provider to provide configurations to traefik
@@ -48,7 +49,10 @@ func (provider *Marathon) Provide(configurationChan chan<- types.ConfigMessage)
log.Debug("Marathon event receveived", event)
configuration := provider.loadMarathonConfig()
if configuration != nil {
configurationChan <- types.ConfigMessage{"marathon", configuration}
configurationChan <- types.ConfigMessage{
ProviderName: "marathon",
Configuration: configuration,
}
}
}
}()
@@ -56,59 +60,24 @@ func (provider *Marathon) Provide(configurationChan chan<- types.ConfigMessage)
}
configuration := provider.loadMarathonConfig()
configurationChan <- types.ConfigMessage{"marathon", configuration}
configurationChan <- types.ConfigMessage{
ProviderName: "marathon",
Configuration: configuration,
}
return nil
}
func (provider *Marathon) loadMarathonConfig() *types.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"
},
"getPassHostHeader": func(application marathon.Application) string {
if passHostHeader, err := provider.getLabel(application, "traefik.frontend.passHostHeader"); err == nil {
return passHostHeader
}
return "false"
},
"getFrontendValue": provider.GetFrontendValue,
"getFrontendRule": provider.GetFrontendRule,
"getPort": provider.getPort,
"getWeight": provider.getWeight,
"getDomain": provider.getDomain,
"getProtocol": provider.getProtocol,
"getPassHostHeader": provider.getPassHostHeader,
"getFrontendValue": provider.getFrontendValue,
"getFrontendRule": provider.getFrontendRule,
"replace": replace,
}
configuration := new(types.Configuration)
applications, err := provider.marathonClient.Applications(nil)
if err != nil {
@@ -116,7 +85,7 @@ func (provider *Marathon) loadMarathonConfig() *types.Configuration {
return nil
}
tasks, err := provider.marathonClient.AllTasks()
tasks, err := provider.marathonClient.AllTasks((url.Values{"status": []string{"running"}}))
if err != nil {
log.Errorf("Failed to create a client for marathon, error: %s", err)
return nil
@@ -124,54 +93,12 @@ func (provider *Marathon) loadMarathonConfig() *types.Configuration {
//filter tasks
filteredTasks := fun.Filter(func(task marathon.Task) 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
return taskFilter(task, applications)
}, 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
return applicationFilter(app, filteredTasks)
}, applications.Apps).([]marathon.Application)
templateObjects := struct {
@@ -184,41 +111,91 @@ func (provider *Marathon) loadMarathonConfig() *types.Configuration {
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 := autogen.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)
configuration, err := provider.getConfiguration("templates/marathon.tmpl", MarathonFuncMap, templateObjects)
if err != nil {
log.Error("Error with marathon template:", err)
return nil
log.Error(err)
}
if _, err := toml.Decode(buffer.String(), configuration); err != nil {
log.Error("Error creating marathon configuration:", err)
return nil
}
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, err := getApplication(task, applications.Apps)
if err != nil {
log.Errorf("Unable to get marathon application from task %s", task.AppID)
return false
}
if application.Labels["traefik.enable"] == "false" {
log.Debugf("Filtering disabled marathon task %s", task.AppID)
return false
}
//filter indeterminable task port
portIndexLabel := application.Labels["traefik.portIndex"]
portValueLabel := application.Labels["traefik.port"]
if portIndexLabel != "" && portValueLabel != "" {
log.Debugf("Filtering marathon task %s specifying both traefik.portIndex and traefik.port labels", task.AppID)
return false
}
if portIndexLabel == "" && portValueLabel == "" && len(application.Ports) > 1 {
log.Debugf("Filtering marathon task %s with more than 1 port and no traefik.portIndex or traefik.port label", task.AppID)
return false
}
if portIndexLabel != "" {
index, err := strconv.Atoi(application.Labels["traefik.portIndex"])
if err != nil || index < 0 || index > len(application.Ports)-1 {
log.Debugf("Filtering marathon task %s with unexpected value for traefik.portIndex label", task.AppID)
return false
}
}
if portValueLabel != "" {
port, err := strconv.Atoi(application.Labels["traefik.port"])
if err != nil {
log.Debugf("Filtering marathon task %s with unexpected value for traefik.port label", task.AppID)
return false
}
var foundPort bool
for _, exposedPort := range task.Ports {
if port == exposedPort {
foundPort = true
break
}
}
if !foundPort {
log.Debugf("Filtering marathon task %s without a matching port for traefik.port label", 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 {
@@ -237,22 +214,78 @@ func (provider *Marathon) getLabel(application marathon.Application, label strin
return "", errors.New("Label not found:" + label)
}
func (provider *Marathon) getEscapedName(name string) string {
return strings.Replace(name, "/", "", -1)
func (provider *Marathon) getPort(task marathon.Task, applications []marathon.Application) string {
application, err := getApplication(task, applications)
if err != nil {
log.Errorf("Unable to get marathon application from task %s", task.AppID)
return ""
}
if portIndexLabel, err := provider.getLabel(application, "traefik.portIndex"); err == nil {
if index, err := strconv.Atoi(portIndexLabel); err == nil {
return strconv.Itoa(task.Ports[index])
}
}
if portValueLabel, err := provider.getLabel(application, "traefik.port"); err == nil {
return portValueLabel
}
for _, port := range task.Ports {
return strconv.Itoa(port)
}
return ""
}
// GetFrontendValue returns the frontend value for the specified application, using
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 {
func (provider *Marathon) 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
return getEscapedName(application.ID) + "." + provider.Domain
}
// GetFrontendRule returns the frontend rule for the specified application, using
// 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 {
func (provider *Marathon) getFrontendRule(application marathon.Application) string {
if label, err := provider.getLabel(application, "traefik.frontend.rule"); err == nil {
return label
}

802
provider/marathon_test.go Normal file
View File

@@ -0,0 +1,802 @@
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(v url.Values) (*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: "specify-port-number",
Ports: []int{80, 443},
},
applications: &marathon.Applications{
Apps: []marathon.Application{
{
ID: "specify-port-number",
Ports: []int{80, 443},
Labels: map[string]string{
"traefik.port": "80",
},
},
},
},
expected: true,
},
{
task: marathon.Task{
AppID: "specify-unknown-port-number",
Ports: []int{80, 443},
},
applications: &marathon.Applications{
Apps: []marathon.Application{
{
ID: "specify-unknown-port-number",
Ports: []int{80, 443},
Labels: map[string]string{
"traefik.port": "8080",
},
},
},
},
expected: false,
},
{
task: marathon.Task{
AppID: "specify-port-index",
Ports: []int{80, 443},
},
applications: &marathon.Applications{
Apps: []marathon.Application{
{
ID: "specify-port-index",
Ports: []int{80, 443},
Labels: map[string]string{
"traefik.portIndex": "0",
},
},
},
},
expected: true,
},
{
task: marathon.Task{
AppID: "specify-out-of-range-port-index",
Ports: []int{80, 443},
},
applications: &marathon.Applications{
Apps: []marathon.Application{
{
ID: "specify-out-of-range-port-index",
Ports: []int{80, 443},
Labels: map[string]string{
"traefik.portIndex": "2",
},
},
},
},
expected: false,
},
{
task: marathon.Task{
AppID: "specify-both-port-index-and-number",
Ports: []int{80, 443},
},
applications: &marathon.Applications{
Apps: []marathon.Application{
{
ID: "specify-both-port-index-and-number",
Ports: []int{80, 443},
Labels: map[string]string{
"traefik.port": "443",
"traefik.portIndex": "1",
},
},
},
},
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 {
applications []marathon.Application
task marathon.Task
expected string
}{
{
applications: []marathon.Application{},
task: marathon.Task{},
expected: "",
},
{
applications: []marathon.Application{
{
ID: "test1",
},
},
task: marathon.Task{
AppID: "test2",
},
expected: "",
},
{
applications: []marathon.Application{
{
ID: "test1",
},
},
task: marathon.Task{
AppID: "test1",
Ports: []int{80},
},
expected: "80",
},
{
applications: []marathon.Application{
{
ID: "test1",
},
},
task: marathon.Task{
AppID: "test1",
Ports: []int{80, 443},
},
expected: "80",
},
{
applications: []marathon.Application{
{
ID: "specify-port-number",
Labels: map[string]string{
"traefik.port": "443",
},
},
},
task: marathon.Task{
AppID: "specify-port-number",
Ports: []int{80, 443},
},
expected: "443",
},
{
applications: []marathon.Application{
{
ID: "specify-port-index",
Labels: map[string]string{
"traefik.portIndex": "1",
},
},
},
task: marathon.Task{
AppID: "specify-port-index",
Ports: []int{80, 443},
},
expected: "443",
},
}
for _, c := range cases {
actual := provider.getPort(c.task, c.applications)
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)
}
}
}

View File

@@ -1,6 +1,15 @@
package provider
import "github.com/emilevauge/traefik/types"
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 {
@@ -8,3 +17,51 @@ type Provider interface {
// 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)
}
}
}

View File

@@ -1,19 +1,20 @@
package provider
import "github.com/emilevauge/traefik/types"
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 {
Watch bool
Endpoint string
Prefix string
Filename string
KvProvider *Kv
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.KvProvider = NewZkProvider(provider)
return provider.KvProvider.provide(configurationChan)
provider.StoreType = store.ZK
zookeeper.Register()
return provider.provide(configurationChan)
}

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

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

View File

@@ -1,7 +1,7 @@
{{$apps := .Applications}}
[backends]{{range .Tasks}}
[backends.backend{{.AppID | replace "/" "-"}}.servers.server-{{.ID | replace "." "-"}}]
url = "{{getProtocol . $apps}}://{{.Host}}:{{getPort .}}"
url = "{{getProtocol . $apps}}://{{.Host}}:{{getPort . $apps}}"
weight = {{getWeight . $apps}}
{{end}}
@@ -9,7 +9,7 @@
[frontends.frontend{{.ID | replace "/" "-"}}]
backend = "backend{{.ID | replace "/" "-"}}"
passHostHeader = {{getPassHostHeader .}}
[frontends.frontend-{{.ID | replace "/" ""}}.routes.route-host-{{.ID | replace "/" ""}}]
[frontends.frontend{{.ID | replace "/" "-"}}.routes.route-host{{.ID | replace "/" "-"}}]
rule = "{{getFrontendRule .}}"
value = "{{getFrontendValue .}}"
{{end}}
{{end}}

View File

@@ -14,7 +14,6 @@ import (
"syscall"
"time"
"github.com/BurntSushi/toml"
log "github.com/Sirupsen/logrus"
"github.com/codegangsta/negroni"
"github.com/emilevauge/traefik/middlewares"
@@ -27,6 +26,7 @@ import (
"github.com/mailgun/oxy/roundrobin"
"github.com/thoas/stats"
"gopkg.in/alecthomas/kingpin.v2"
"sync"
)
var (
@@ -54,6 +54,7 @@ func main() {
defer close(stopChan)
var providers = []provider.Provider{}
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
var serverLock sync.Mutex
// load global configuration
globalConfiguration := LoadFileConfig(*globalConfigFile)
@@ -125,6 +126,7 @@ func main() {
newConfigurationRouter, err := LoadConfig(newConfigurations, globalConfiguration)
if err == nil {
serverLock.Lock()
currentConfigurations = newConfigurations
configurationRouter = newConfigurationRouter
oldServer := srv
@@ -139,6 +141,7 @@ func main() {
log.Info("Stopping old server")
oldServer.Close()
}
serverLock.Unlock()
} else {
log.Error("Error loading new configuration, aborted ", err)
}
@@ -200,39 +203,49 @@ func main() {
//negroni.Use(middlewares.NewRoutes(configurationRouter))
var er error
serverLock.Lock()
srv, er = prepareServer(configurationRouter, globalConfiguration, nil, loggerMiddleware, metrics)
if er != nil {
log.Fatal("Error preparing server: ", er)
}
go startServer(srv, globalConfiguration)
//TODO change that!
time.Sleep(100 * time.Millisecond)
serverLock.Unlock()
<-stopChan
log.Info("Shutting down")
}
func createTLSConfig(certFile string, keyFile string) (*tls.Config, error) {
// creates a TLS config that allows terminating HTTPS for multiple domains using SNI
func createTLSConfig(certs []Certificate) (*tls.Config, error) {
if len(certs) == 0 {
return nil, nil
}
config := &tls.Config{}
if config.NextProtos == nil {
config.NextProtos = []string{"http/1.1"}
}
var err error
config.Certificates = make([]tls.Certificate, 1)
if len(certFile) > 0 && len(keyFile) > 0 {
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
config.Certificates = make([]tls.Certificate, len(certs))
for i, v := range certs {
config.Certificates[i], err = tls.LoadX509KeyPair(v.CertFile, v.KeyFile)
if err != nil {
return nil, err
}
} else {
return nil, nil
}
// BuildNameToCertificate parses the CommonName and SubjectAlternateName fields
// in each certificate and populates the config.NameToCertificate map.
config.BuildNameToCertificate()
return config, nil
}
func startServer(srv *manners.GracefulServer, globalConfiguration *GlobalConfiguration) {
log.Info("Starting server")
if len(globalConfiguration.CertFile) > 0 && len(globalConfiguration.KeyFile) > 0 {
err := srv.ListenAndServeTLS(globalConfiguration.CertFile, globalConfiguration.KeyFile)
if srv.TLSConfig != nil {
err := srv.ListenAndServeTLSWithConfig(srv.TLSConfig)
if err != nil {
log.Fatal("Error creating server: ", err)
}
@@ -253,7 +266,7 @@ func prepareServer(router *mux.Router, globalConfiguration *GlobalConfiguration,
negroni.Use(middleware)
}
negroni.UseHandler(router)
tlsConfig, err := createTLSConfig(globalConfiguration.CertFile, globalConfiguration.KeyFile)
tlsConfig, err := createTLSConfig(globalConfiguration.Certificates)
if err != nil {
log.Fatalf("Error creating TLS config %s", err)
return nil, err
@@ -266,20 +279,21 @@ 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: tlsConfig,
}, 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)
@@ -291,7 +305,10 @@ func LoadConfig(configurations configs, globalConfiguration *GlobalConfiguration
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 {
@@ -346,25 +363,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

@@ -37,10 +37,12 @@
#
# logLevel = "ERROR"
# SSL certificate and key used
# SSL certificates and keys
# You may add several certificate/key pairs to terminate HTTPS for multiple domain names using TLS SNI
#
# Optional
#
# [[certificates]]
# CertFile = "traefik.crt"
# KeyFile = "traefik.key"
@@ -138,6 +140,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

View File

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

10
web.go
View File

@@ -14,9 +14,12 @@ import (
"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
ReadOnly bool
}
var (
@@ -25,6 +28,8 @@ var (
})
)
// 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()
@@ -36,6 +41,11 @@ func (provider *WebProvider) Provide(configurationChan chan<- types.ConfigMessag
systemRouter.Methods("GET").Path("/api/providers").HandlerFunc(getConfigHandler)
systemRouter.Methods("GET").Path("/api/providers/{provider}").HandlerFunc(getProviderHandler)
systemRouter.Methods("PUT").Path("/api/providers/{provider}").HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
if provider.ReadOnly {
response.WriteHeader(http.StatusForbidden)
fmt.Fprintf(response, "REST API is in read-only mode")
return
}
vars := mux.Vars(request)
if vars["provider"] != "web" {
response.WriteHeader(http.StatusBadRequest)