Compare commits

..

45 Commits

Author SHA1 Message Date
Ludovic Fernandez
4461ecfed1 Prepare release v2.1.2 2020-01-07 16:56:05 +01:00
Gary Kramlich
bd676922c3 k8s Ingress: fix crash on rules with nil http 2020-01-07 16:26:08 +01:00
José Carlos Chávez
49356cadd4 fix(tracing): makes sure tracing headers are being propagated when using forwardAuth 2020-01-07 15:48:07 +01:00
Ludovic Fernandez
c02f222005 Improves error message when a configuration file is empty. 2020-01-07 15:24:05 +01:00
Jean-Baptiste Doumenjou
d3977ce40e Improve documentation about Kubernetes IngressRoute 2020-01-07 11:26:05 +01:00
Jean-Baptiste Doumenjou
7283d7eb2f Log the ignored namespace only when needed 2020-01-07 10:46:04 +01:00
Julien Salleyron
807dc46ad0 Handle respondingtimeout and better shutdown tests.
Co-authored-by: Mathieu Lonjaret <mathieu.lonjaret@gmail.com>
2020-01-06 16:56:05 +01:00
Tiago Boeing
0837ec9b70 Fix command for use websecure via CLI 2020-01-01 01:56:04 +01:00
Ludovic Fernandez
b380522df8 fix: dashboard redirect loop 2019-12-24 17:36:04 +01:00
Ludovic Fernandez
c127d34d32 fix: Malformed x-b3-traceid Header 2019-12-22 08:24:03 +01:00
der-domi
bc0b97d5d8 Update ipwhitelist.md 2019-12-19 21:38:03 +01:00
Manuel Zapf
431abe79f3 Query consul for service health separately 2019-12-19 11:00:07 +01:00
Dmitry Sharshakov
4f669bdd66 Don't set user-agent to Go-http-client/1.1 2019-12-18 11:22:06 +01:00
Ludovic Fernandez
8930236396 fix: invalid label/flag parsing. 2019-12-17 16:10:06 +01:00
Ludovic Fernandez
4d0aee67be doc: remove section about templates 2019-12-17 14:30:06 +01:00
Kenneth Peiruza
b501c6d5bf Added ExternalName https support for Kubernetes CRD, as done in v2.0 2019-12-16 21:48:03 +01:00
Ludovic Fernandez
7dcee38b21 Use consistent name in ACME documentation 2019-12-13 15:46:06 +01:00
Damien Duportal
903c63ac13 add a documentation example for dashboard and api for kubernetes CRD 2019-12-13 10:36:04 +01:00
Ludovic Fernandez
a98c9f99d1 Prepare release v2.1.1 2019-12-12 19:44:04 +01:00
Manuel Zapf
b5ae141fb6 Add Migration Guide for Traefik v2.1 2019-12-12 17:06:05 +01:00
Ludovic Fernandez
7eb866ffee Improve documentation about Traefik build. 2019-12-12 16:32:06 +01:00
mpl
61e59d74e0 CloseNotifier: return pointer instead of value 2019-12-12 15:12:05 +01:00
Ludovic Fernandez
e2982185d6 Prepare release v2.1.0 2019-12-11 18:40:04 +01:00
mpl
bdf4c6723f detect CloseNotify capability in accesslog and metrics 2019-12-10 18:18:04 +01:00
Matthieu Hostache
1d4f10bead Fix http/tcp resources pagination 2019-12-10 17:48:04 +01:00
Ludovic Fernandez
aac3e2d4fb Several documentation fixes 2019-12-10 16:12:06 +01:00
Jean-Baptiste Doumenjou
87dd6badac Use valid condition in the service details panel UI 2019-12-10 15:34:06 +01:00
Dmitry Sharshakov
1b6c7af3eb Fix weighted service provider icon 2019-12-10 15:14:06 +01:00
Fernandez Ludovic
5c091a1871 Merge branch 'v2.0' into v2.1 2019-12-09 18:48:20 +01:00
Ludovic Fernandez
fb3839e096 Prepare release v2.0.7 2019-12-09 18:34:04 +01:00
Damien Duportal
eef3ca0295 Improve documentation for ACME/Let's Encrypt 2019-12-09 18:08:04 +01:00
Ludovic Fernandez
c9dc0226fd fix: flaky Travis builds due to 'not get uid/gid' 2019-12-09 15:52:04 +01:00
Ludovic Fernandez
1a7a3a4233 fix: remove double call to server Close. 2019-12-09 15:14:06 +01:00
Julien Salleyron
d2e458f673 Remove mirroring impact in accesslog 2019-12-09 15:12:06 +01:00
Eugen Mayer
e0f265db15 Make trailing slash more prominent for the "secure dashboard setup" too 2019-12-09 12:32:04 +01:00
Ludovic Fernandez
39a3cefc21 fix: PassClientTLSCert middleware separators and formatting 2019-12-09 12:20:06 +01:00
Jean-Baptiste Doumenjou
89db08eb93 Improve documentation on file provider limitations with file system notifications 2019-12-09 11:48:05 +01:00
Eugen Mayer
f40cf2cd8e The Cloudflare hint for the GLOBAL API KEY for CF MAIL/API_KEY 2019-12-09 11:42:06 +01:00
Daniel Tomcej
50bb69b796 Document LE caveats with Kubernetes on v2 2019-12-09 10:16:05 +01:00
Tim
a7d7c2b98b Fix Docker example in "Strip and Rewrite Path Prefixes" in migration guide 2019-12-06 00:42:04 +01:00
Sebastian Pipping
8dfc0d9dda readme: Fix link to file backend/provider documentation 2019-12-05 21:50:04 +01:00
Antoine
0e6dce7093 Do not stop to listen on tcp listeners on temporary errors 2019-12-04 16:26:05 +01:00
Ludovic Fernandez
ddbf4470a1 fix: debug endpoint when insecure API. 2019-12-04 15:28:07 +01:00
Ludovic Fernandez
bc063ad773 Merge current v2.0 branch into v2.1 2019-12-03 10:40:05 +01:00
Michael
ef38810425 Upgrade python version to 3.7 for netlify 2019-12-03 10:16:05 +01:00
85 changed files with 3079 additions and 944 deletions

View File

@@ -3,11 +3,11 @@ PLEASE READ THIS MESSAGE.
Documentation fixes or enhancements:
- for Traefik v1: use branch v1.7
- for Traefik v2: use branch v2.0
- for Traefik v2: use branch v2.1
Bug fixes:
- for Traefik v1: use branch v1.7
- for Traefik v2: use branch v2.0
- for Traefik v2: use branch v2.1
Enhancements:
- for Traefik v1: we only accept bug fixes

View File

@@ -1,3 +1,102 @@
## [v2.1.2](https://github.com/containous/traefik/tree/v2.1.2) (2020-01-07)
[All Commits](https://github.com/containous/traefik/compare/v2.1.1...v2.1.2)
**Bug fixes:**
- **[authentication,middleware,tracing]** fix(tracing): makes sure tracing headers are being propagated when using forwardAuth ([#6072](https://github.com/containous/traefik/pull/6072) by [jcchavezs](https://github.com/jcchavezs))
- **[cli]** fix: invalid label/flag parsing. ([#6028](https://github.com/containous/traefik/pull/6028) by [ldez](https://github.com/ldez))
- **[consulcatalog]** Query consul catalog for service health separately ([#6046](https://github.com/containous/traefik/pull/6046) by [SantoDE](https://github.com/SantoDE))
- **[k8s,k8s/crd]** Restore ExternalName https support for Kubernetes CRD ([#6037](https://github.com/containous/traefik/pull/6037) by [kpeiruza](https://github.com/kpeiruza))
- **[k8s,k8s/crd]** Log the ignored namespace only when needed ([#6087](https://github.com/containous/traefik/pull/6087) by [jbdoumenjou](https://github.com/jbdoumenjou))
- **[k8s,k8s/ingress]** k8s Ingress: fix crash on rules with nil http ([#6121](https://github.com/containous/traefik/pull/6121) by [grimmy](https://github.com/grimmy))
- **[logs]** Improves error message when a configuration file is empty. ([#6135](https://github.com/containous/traefik/pull/6135) by [ldez](https://github.com/ldez))
- **[server]** Handle respondingTimeout and better shutdown tests. ([#6115](https://github.com/containous/traefik/pull/6115) by [juliens](https://github.com/juliens))
- **[server]** Don&#39;t set user-agent to Go-http-client/1.1 ([#6030](https://github.com/containous/traefik/pull/6030) by [sh7dm](https://github.com/sh7dm))
- **[tracing]** fix: Malformed x-b3-traceid Header ([#6079](https://github.com/containous/traefik/pull/6079) by [ldez](https://github.com/ldez))
- **[webui]** fix: dashboard redirect loop ([#6078](https://github.com/containous/traefik/pull/6078) by [ldez](https://github.com/ldez))
**Documentation:**
- **[acme]** Use consistent name in ACME documentation ([#6019](https://github.com/containous/traefik/pull/6019) by [ldez](https://github.com/ldez))
- **[api,k8s/crd]** Add a documentation example for dashboard and api for kubernetes CRD ([#6022](https://github.com/containous/traefik/pull/6022) by [dduportal](https://github.com/dduportal))
- **[cli]** Fix examples for the use of websecure via CLI ([#6116](https://github.com/containous/traefik/pull/6116) by [tiagoboeing](https://github.com/tiagoboeing))
- **[k8s,k8s/crd]** Improve documentation about Kubernetes IngressRoute ([#6058](https://github.com/containous/traefik/pull/6058) by [jbdoumenjou](https://github.com/jbdoumenjou))
- **[middleware]** Improve sourceRange explanation for ipWhiteList ([#6070](https://github.com/containous/traefik/pull/6070) by [der-domi](https://github.com/der-domi))
## [v2.1.1](https://github.com/containous/traefik/tree/v2.1.1) (2019-12-12)
[All Commits](https://github.com/containous/traefik/compare/v2.1.0...v2.1.1)
**Bug fixes:**
- **[logs,middleware,metrics]** CloseNotifier: return pointer instead of value ([#6010](https://github.com/containous/traefik/pull/6010) by [mpl](https://github.com/mpl))
**Documentation:**
- Add Migration Guide for Traefik v2.1 ([#6017](https://github.com/containous/traefik/pull/6017) by [SantoDE](https://github.com/SantoDE))
## [v2.1.0](https://github.com/containous/traefik/tree/v2.1.0) (2019-12-10)
[All Commits](https://github.com/containous/traefik/compare/v2.0.0-rc1...v2.1.0)
**Enhancements:**
- **[consulcatalog]** Add consul catalog options: requireConsistent, stale, cache ([#5752](https://github.com/containous/traefik/pull/5752) by [ldez](https://github.com/ldez))
- **[consulcatalog]** Add Consul Catalog provider ([#5395](https://github.com/containous/traefik/pull/5395) by [negasus](https://github.com/negasus))
- **[k8s,k8s/crd,service]** Support for all services kinds (and sticky) in CRD ([#5711](https://github.com/containous/traefik/pull/5711) by [mpl](https://github.com/mpl))
- **[metrics]** Added configurable prefix for statsd metrics collection ([#5336](https://github.com/containous/traefik/pull/5336) by [schulterklopfer](https://github.com/schulterklopfer))
- **[middleware]** Conditional compression based on request Content-Type ([#5721](https://github.com/containous/traefik/pull/5721) by [ldez](https://github.com/ldez))
- **[server]** Add internal provider ([#5815](https://github.com/containous/traefik/pull/5815) by [ldez](https://github.com/ldez))
- **[tls]** Add support for MaxVersion in tls.Options ([#5650](https://github.com/containous/traefik/pull/5650) by [kmeekva](https://github.com/kmeekva))
- **[tls]** Add tls option for Elliptic Curve Preferences ([#5466](https://github.com/containous/traefik/pull/5466) by [ksarink](https://github.com/ksarink))
- **[tracing]** Update jaeger dependencies ([#5637](https://github.com/containous/traefik/pull/5637) by [mmatur](https://github.com/mmatur))
**Bug fixes:**
- **[api]** fix: debug endpoint when insecure API. ([#5937](https://github.com/containous/traefik/pull/5937) by [ldez](https://github.com/ldez))
- **[cli]** fix: sub command help ([#5887](https://github.com/containous/traefik/pull/5887) by [ldez](https://github.com/ldez))
- **[consulcatalog]** fix: consul catalog constraints. ([#5913](https://github.com/containous/traefik/pull/5913) by [ldez](https://github.com/ldez))
- **[consulcatalog]** Service registered with same id on Consul Catalog ([#5900](https://github.com/containous/traefik/pull/5900) by [mmatur](https://github.com/mmatur))
- **[consulcatalog]** Fix empty address for registering service without IP ([#5826](https://github.com/containous/traefik/pull/5826) by [mmatur](https://github.com/mmatur))
- **[logs,middleware,metrics]** detect CloseNotify capability in accesslog and metrics ([#5985](https://github.com/containous/traefik/pull/5985) by [mpl](https://github.com/mpl))
- **[server]** fix: remove double call to server Close. ([#5960](https://github.com/containous/traefik/pull/5960) by [ldez](https://github.com/ldez))
- **[webui]** Fix weighted service provider icon ([#5983](https://github.com/containous/traefik/pull/5983) by [sh7dm](https://github.com/sh7dm))
- **[webui]** Fix http/tcp resources pagination ([#5986](https://github.com/containous/traefik/pull/5986) by [matthieuh](https://github.com/matthieuh))
- **[webui]** Use valid condition in the service details panel UI ([#5984](https://github.com/containous/traefik/pull/5984) by [jbdoumenjou](https://github.com/jbdoumenjou))
- **[webui]** Web UI: Avoid polling on /api/entrypoints ([#5863](https://github.com/containous/traefik/pull/5863) by [matthieuh](https://github.com/matthieuh))
- **[webui]** Web UI: Sync toolbar table state with url query params ([#5861](https://github.com/containous/traefik/pull/5861) by [matthieuh](https://github.com/matthieuh))
**Documentation:**
- **[consulcatalog]** fix: Consul Catalog documentation. ([#5725](https://github.com/containous/traefik/pull/5725) by [ldez](https://github.com/ldez))
- **[consulcatalog]** Fix consul catalog documentation ([#5661](https://github.com/containous/traefik/pull/5661) by [mmatur](https://github.com/mmatur))
- Prepare release v2.1.0-rc2 ([#5846](https://github.com/containous/traefik/pull/5846) by [ldez](https://github.com/ldez))
- Prepare release v2.1.0-rc1 ([#5844](https://github.com/containous/traefik/pull/5844) by [jbdoumenjou](https://github.com/jbdoumenjou))
- Several documentation fixes ([#5987](https://github.com/containous/traefik/pull/5987) by [ldez](https://github.com/ldez))
- Prepare release v2.1.0-rc3 ([#5929](https://github.com/containous/traefik/pull/5929) by [ldez](https://github.com/ldez))
**Misc:**
- **[cli]** Add custom help function to command ([#5923](https://github.com/containous/traefik/pull/5923) by [Ullaakut](https://github.com/Ullaakut))
- **[server]** fix: use MaxInt32. ([#5845](https://github.com/containous/traefik/pull/5845) by [ldez](https://github.com/ldez))
- Merge current v2.0 branch into master ([#5841](https://github.com/containous/traefik/pull/5841) by [ldez](https://github.com/ldez))
- Merge current v2.0 branch into master ([#5749](https://github.com/containous/traefik/pull/5749) by [ldez](https://github.com/ldez))
- Merge current v2.0 branch into master ([#5619](https://github.com/containous/traefik/pull/5619) by [ldez](https://github.com/ldez))
- Merge current v2.0 branch into master ([#5464](https://github.com/containous/traefik/pull/5464) by [ldez](https://github.com/ldez))
- Merge v2.0.0 into master ([#5402](https://github.com/containous/traefik/pull/5402) by [ldez](https://github.com/ldez))
- Merge v2.0.0-rc3 into master ([#5354](https://github.com/containous/traefik/pull/5354) by [ldez](https://github.com/ldez))
- Merge v2.0.0-rc1 into master ([#5253](https://github.com/containous/traefik/pull/5253) by [ldez](https://github.com/ldez))
- Merge current v2.0 branch into v2.1 ([#5977](https://github.com/containous/traefik/pull/5977) by [ldez](https://github.com/ldez))
- Merge current v2.0 branch into v2.1 ([#5931](https://github.com/containous/traefik/pull/5931) by [ldez](https://github.com/ldez))
- Merge current v2.0 branch into v2.1 ([#5928](https://github.com/containous/traefik/pull/5928) by [ldez](https://github.com/ldez))
## [v2.0.7](https://github.com/containous/traefik/tree/v2.0.7) (2019-12-09)
[All Commits](https://github.com/containous/traefik/compare/v2.0.6...v2.0.7)
**Bug fixes:**
- **[logs,middleware]** Remove mirroring impact in accesslog ([#5967](https://github.com/containous/traefik/pull/5967) by [juliens](https://github.com/juliens))
- **[middleware]** fix: PassClientTLSCert middleware separators and formatting ([#5921](https://github.com/containous/traefik/pull/5921) by [ldez](https://github.com/ldez))
- **[server]** Do not stop to listen on tcp listeners on temporary errors ([#5935](https://github.com/containous/traefik/pull/5935) by [skwair](https://github.com/skwair))
**Documentation:**
- **[acme,k8s/crd,k8s/ingress]** Document LE caveats with Kubernetes on v2 ([#5902](https://github.com/containous/traefik/pull/5902) by [dtomcej](https://github.com/dtomcej))
- **[acme]** The Cloudflare hint for the GLOBAL API KEY for CF MAIL/API_KEY ([#5964](https://github.com/containous/traefik/pull/5964) by [EugenMayer](https://github.com/EugenMayer))
- **[acme]** Improve documentation for ACME/Let&#39;s Encrypt ([#5819](https://github.com/containous/traefik/pull/5819) by [dduportal](https://github.com/dduportal))
- **[file]** Improve documentation on file provider limitations with file system notifications ([#5939](https://github.com/containous/traefik/pull/5939) by [jbdoumenjou](https://github.com/jbdoumenjou))
- Make trailing slash more prominent for the &#34;secure dashboard setup&#34; too ([#5963](https://github.com/containous/traefik/pull/5963) by [EugenMayer](https://github.com/EugenMayer))
- Fix Docker example in &#34;Strip and Rewrite Path Prefixes&#34; in migration guide ([#5949](https://github.com/containous/traefik/pull/5949) by [q210](https://github.com/q210))
- readme: Fix link to file backend/provider documentation ([#5945](https://github.com/containous/traefik/pull/5945) by [hartwork](https://github.com/hartwork))
## [v2.1.0-rc3](https://github.com/containous/traefik/tree/v2.1.0-rc3) (2019-12-02)
[All Commits](https://github.com/containous/traefik/compare/v2.1.0-rc2...v2.1.0-rc3)

View File

@@ -73,7 +73,7 @@ _(But if you'd rather configure some of your routes manually, Traefik supports t
- [Kubernetes](https://docs.traefik.io/providers/kubernetes-crd/)
- [Marathon](https://docs.traefik.io/providers/marathon/)
- [Rancher](https://docs.traefik.io/providers/rancher/) (Metadata)
- [File](https://docs.traefik.io/configuration/backends/file)
- [File](https://docs.traefik.io/providers/file/)
## Quickstart

View File

@@ -69,10 +69,10 @@ Complete documentation is available at https://traefik.io`,
err = cli.Execute(cmdTraefik)
if err != nil {
stdlog.Println(err)
os.Exit(1)
logrus.Exit(1)
}
os.Exit(0)
logrus.Exit(0)
}
func runCmd(staticConfiguration *static.Configuration) error {
@@ -156,7 +156,6 @@ func runCmd(staticConfiguration *static.Configuration) error {
svr.Wait()
log.WithoutContext().Info("Shutting down")
logrus.Exit(0)
return nil
}
@@ -173,7 +172,7 @@ func setupServer(staticConfiguration *static.Configuration) (*server.Server, err
acmeProviders := initACMEProvider(staticConfiguration, &providerAggregator, tlsManager)
serverEntryPointsTCP, err := server.NewTCPEntryPoints(*staticConfiguration)
serverEntryPointsTCP, err := server.NewTCPEntryPoints(staticConfiguration.EntryPoints)
if err != nil {
return nil, err
}

View File

@@ -15,8 +15,12 @@ RUN gem install html-proofer --version 3.13.0 --no-document -- --use-system-libr
RUN apk --no-cache --no-progress add \
git \
nodejs \
npm \
&& npm install --global \
npm
# To handle 'not get uid/gid'
RUN npm config set unsafe-perm true
RUN npm install --global \
markdownlint@0.17.2 \
markdownlint-cli@0.19.0

View File

@@ -62,7 +62,7 @@ Requirements:
- `go` v1.13+
- environment variable `GO111MODULE=on`
- go-bindata `GO111MODULE=off go get -u github.com/containous/go-bindata/...`
- [go-bindata](https://github.com/containous/go-bindata) `GO111MODULE=off go get -u github.com/containous/go-bindata/...`
!!! tip "Source Directory"
@@ -98,30 +98,32 @@ Requirements:
#### Build Traefik
Once you've set up your go environment and cloned the source repository, you can build Traefik.
Beforehand, you need to get `go-bindata` (the first time) in order to be able to use the `go generate` command (which is part of the build process).
Beforehand, you need to get [go-bindata](https://github.com/containous/go-bindata) (the first time) in order to be able to use the `go generate` command (which is part of the build process).
```bash
cd ~/go/src/github.com/containous/traefik
# Get go-bindata. (Important: the ellipses are required.)
GO111MODULE=off go get github.com/containous/go-bindata/...
```
# Let's build
```bash
# Generate UI static files
rm -rf static/ autogen/; make generate-webui
# generate
# (required to merge non-code components into the final binary, such as the web dashboard and the provider's templates)
# required to merge non-code components into the final binary,
# such as the web dashboard/UI
go generate
```
```bash
# Standard go build
go build ./cmd/traefik
```
You will find the Traefik executable (`traefik`) in the `~/go/src/github.com/containous/traefik` directory.
### Updating the templates
If you happen to update the provider's templates (located in `/templates`), you must run `go generate` to update the `autogen` package.
## Testing
### Method 1: `Docker` and `make`

View File

@@ -0,0 +1,4 @@
{
"extends": "../../.markdownlint.json",
"MD041": false
}

View File

@@ -8,6 +8,45 @@ You can configure Traefik to use an ACME provider (like Let's Encrypt) for autom
!!! warning "Let's Encrypt and Rate Limiting"
Note that Let's Encrypt API has [rate limiting](https://letsencrypt.org/docs/rate-limits).
Use Let's Encrypt staging server with the [`caServer`](#caserver) configuration option
when experimenting to avoid hitting this limit too fast.
## Certificate Resolvers
Traefik requires you to define "Certificate Resolvers" in the [static configuration](../getting-started/configuration-overview.md#the-static-configuration),
which are responsible for retrieving certificates from an ACME server.
Then, each ["router"](../routing/routers/index.md) is configured to enable TLS,
and is associated to a certificate resolver through the [`tls.certresolver` configuration option](../routing/routers/index.md#certresolver).
Certificates are requested for domain names retrieved from the router's [dynamic configuration](../getting-started/configuration-overview.md#the-dynamic-configuration).
You can read more about this retrieval mechanism in the following section: [ACME Domain Definition](#domain-definition).
## Domain Definition
Certificate resolvers request certificates for a set of the domain names
inferred from routers, with the following logic:
- If the router has a [`tls.domains`](../routing/routers/index.md#domains) option set,
then the certificate resolver uses the `main` (and optionally `sans`) option of `tls.domains` to know the domain names for this router.
- If no [`tls.domains`](../routing/routers/index.md#domains) option is set,
then the certificate resolver uses the [router's rule](../routing/routers/index.md#rule),
by checking the `Host()` matchers.
Please note that [multiple `Host()` matchers can be used](../routing/routers/index.md#certresolver)) for specifying multiple domain names for this router.
Please note that:
- When multiple domain names are inferred from a given router,
only **one** certificate is requested with the first domain name as the main domain,
and the other domains as ["SANs" (Subject Alternative Name)](https://en.wikipedia.org/wiki/Subject_Alternative_Name).
- As [ACME V2 supports "wildcard domains"](#wildcard-domains),
any router can provide a [wildcard domain](https://en.wikipedia.org/wiki/Wildcard_certificate) name, as "main" domain or as "SAN" domain.
Please check the [configuration examples below](#configuration-examples) for more details.
## Configuration Examples
??? example "Enabling ACME"
@@ -20,10 +59,10 @@ You can configure Traefik to use an ACME provider (like Let's Encrypt) for autom
[entryPoints.web-secure]
address = ":443"
[certificatesResolvers.sample.acme]
[certificatesResolvers.le.acme]
email = "your-email@your-domain.org"
storage = "acme.json"
[certificatesResolvers.sample.acme.httpChallenge]
[certificatesResolvers.le.acme.httpChallenge]
# used during the challenge
entryPoint = "web"
```
@@ -50,10 +89,10 @@ You can configure Traefik to use an ACME provider (like Let's Encrypt) for autom
--entryPoints.web.address=:80
--entryPoints.websecure.address=:443
# ...
--certificatesResolvers.sample.acme.email=your-email@your-domain.org
--certificatesResolvers.sample.acme.storage=acme.json
--certificatesResolvers.le.acme.email=your-email@your-domain.org
--certificatesResolvers.le.acme.storage=acme.json
# used during the challenge
--certificatesResolvers.sample.acme.httpChallenge.entryPoint=web
--certificatesResolvers.le.acme.httpChallenge.entryPoint=web
```
!!! important "Defining a certificates resolver does not result in all routers automatically using it. Each router that is supposed to use the resolver must [reference](../routing/routers/index.md#certresolver) it."
@@ -75,6 +114,26 @@ You can configure Traefik to use an ACME provider (like Let's Encrypt) for autom
--8<-- "content/https/ref-acme.txt"
```
??? example "Single Domain from Router's Rule Example"
* A certificate for the domain `company.com` is requested:
--8<-- "content/https/include-acme-single-domain-example.md"
??? example "Multiple Domains from Router's Rule Example"
* A certificate for the domains `company.com` (main) and `blog.company.org`
is requested:
--8<-- "content/https/include-acme-multiple-domains-from-rule-example.md"
??? example "Multiple Domains from Router's `tls.domain` Example"
* A certificate for the domains `company.com` (main) and `*.company.org` (SAN)
is requested:
--8<-- "content/https/include-acme-multiple-domains-example.md"
## Automatic Renewals
Traefik automatically tracks the expiry date of ACME certificates it generates.
@@ -84,6 +143,13 @@ If there are less than 30 days remaining before the certificate expires, Traefik
!!! info ""
Certificates that are no longer used may still be renewed, as Traefik does not currently check if the certificate is being used before renewing.
## Using LetsEncrypt with Kubernetes
When using LetsEncrypt with kubernetes, there are some known caveats with both the [ingress](../providers/kubernetes-ingress.md) and [crd](../providers/kubernetes-crd.md) providers.
!!! info ""
If you intend to run multiple instances of Traefik with LetsEncrypt, please ensure you read the sections on those provider pages.
## The Different ACME Challenges
!!! important "Defining a certificates resolver does not result in all routers automatically using it. Each router that is supposed to use the resolver must [reference](../routing/routers/index.md#certresolver) it."
@@ -98,9 +164,9 @@ when using the `TLS-ALPN-01` challenge, Traefik must be reachable by Let's Encry
??? example "Configuring the `tlsChallenge`"
```toml tab="File (TOML)"
[certificatesResolvers.sample.acme]
[certificatesResolvers.le.acme]
# ...
[certificatesResolvers.sample.acme.tlsChallenge]
[certificatesResolvers.le.acme.tlsChallenge]
```
```yaml tab="File (YAML)"
@@ -113,7 +179,7 @@ when using the `TLS-ALPN-01` challenge, Traefik must be reachable by Let's Encry
```bash tab="CLI"
# ...
--certificatesResolvers.sample.acme.tlsChallenge=true
--certificatesResolvers.le.acme.tlsChallenge=true
```
### `httpChallenge`
@@ -121,7 +187,7 @@ when using the `TLS-ALPN-01` challenge, Traefik must be reachable by Let's Encry
Use the `HTTP-01` challenge to generate and renew ACME certificates by provisioning an HTTP resource under a well-known URI.
As described on the Let's Encrypt [community forum](https://community.letsencrypt.org/t/support-for-ports-other-than-80-and-443/3419/72),
when using the `HTTP-01` challenge, `certificatesResolvers.sample.acme.httpChallenge.entryPoint` must be reachable by Let's Encrypt through port 80.
when using the `HTTP-01` challenge, `certificatesResolvers.le.acme.httpChallenge.entryPoint` must be reachable by Let's Encrypt through port 80.
??? example "Using an EntryPoint Called http for the `httpChallenge`"
@@ -133,9 +199,9 @@ when using the `HTTP-01` challenge, `certificatesResolvers.sample.acme.httpChall
[entryPoints.web-secure]
address = ":443"
[certificatesResolvers.sample.acme]
[certificatesResolvers.le.acme]
# ...
[certificatesResolvers.sample.acme.httpChallenge]
[certificatesResolvers.le.acme.httpChallenge]
entryPoint = "web"
```
@@ -159,7 +225,7 @@ when using the `HTTP-01` challenge, `certificatesResolvers.sample.acme.httpChall
--entryPoints.web.address=:80
--entryPoints.websecure.address=:443
# ...
--certificatesResolvers.sample.acme.httpChallenge.entryPoint=web
--certificatesResolvers.le.acme.httpChallenge.entryPoint=web
```
!!! info ""
@@ -172,9 +238,9 @@ Use the `DNS-01` challenge to generate and renew ACME certificates by provisioni
??? example "Configuring a `dnsChallenge` with the DigitalOcean Provider"
```toml tab="File (TOML)"
[certificatesResolvers.sample.acme]
[certificatesResolvers.le.acme]
# ...
[certificatesResolvers.sample.acme.dnsChallenge]
[certificatesResolvers.le.acme.dnsChallenge]
provider = "digitalocean"
delayBeforeCheck = 0
# ...
@@ -193,8 +259,8 @@ Use the `DNS-01` challenge to generate and renew ACME certificates by provisioni
```bash tab="CLI"
# ...
--certificatesResolvers.sample.acme.dnsChallenge.provider=digitalocean
--certificatesResolvers.sample.acme.dnsChallenge.delayBeforeCheck=0
--certificatesResolvers.le.acme.dnsChallenge.provider=digitalocean
--certificatesResolvers.le.acme.dnsChallenge.delayBeforeCheck=0
# ...
```
@@ -220,7 +286,7 @@ For example, `CF_API_EMAIL_FILE=/run/secrets/traefik_cf-api-email` could be used
| [Bindman](https://github.com/labbsr0x/bindman-dns-webhook) | `bindman` | `BINDMAN_MANAGER_ADDRESS` | [Additional configuration](https://go-acme.github.io/lego/dns/bindman) |
| [Blue Cat](https://www.bluecatnetworks.com/) | `bluecat` | `BLUECAT_SERVER_URL`, `BLUECAT_USER_NAME`, `BLUECAT_PASSWORD`, `BLUECAT_CONFIG_NAME`, `BLUECAT_DNS_VIEW` | [Additional configuration](https://go-acme.github.io/lego/dns/bluecat) |
| [ClouDNS](https://www.cloudns.net/) | `cloudns` | `CLOUDNS_AUTH_ID`, `CLOUDNS_AUTH_PASSWORD` | [Additional configuration](https://go-acme.github.io/lego/dns/cloudns) |
| [Cloudflare](https://www.cloudflare.com) | `cloudflare` | `CF_API_EMAIL`, `CF_API_KEY` or `CF_DNS_API_TOKEN`, `[CF_ZONE_API_TOKEN]` [^5] | [Additional configuration](https://go-acme.github.io/lego/dns/cloudflare) |
| [Cloudflare](https://www.cloudflare.com) | `cloudflare` | `CF_API_EMAIL`, `CF_API_KEY` [^5] or `CF_DNS_API_TOKEN`, `[CF_ZONE_API_TOKEN]` | [Additional configuration](https://go-acme.github.io/lego/dns/cloudflare) |
| [CloudXNS](https://www.cloudxns.net) | `cloudxns` | `CLOUDXNS_API_KEY`, `CLOUDXNS_SECRET_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/cloudxns) |
| [ConoHa](https://www.conoha.jp) | `conoha` | `CONOHA_TENANT_ID`, `CONOHA_API_USERNAME`, `CONOHA_API_PASSWORD` | [Additional configuration](https://go-acme.github.io/lego/dns/conoha) |
| [DigitalOcean](https://www.digitalocean.com) | `digitalocean` | `DO_AUTH_TOKEN` | [Additional configuration](https://go-acme.github.io/lego/dns/digitalocean) |
@@ -291,9 +357,9 @@ For example, `CF_API_EMAIL_FILE=/run/secrets/traefik_cf-api-email` could be used
Use custom DNS servers to resolve the FQDN authority.
```toml tab="File (TOML)"
[certificatesResolvers.sample.acme]
[certificatesResolvers.le.acme]
# ...
[certificatesResolvers.sample.acme.dnsChallenge]
[certificatesResolvers.le.acme.dnsChallenge]
# ...
resolvers = ["1.1.1.1:53", "8.8.8.8:53"]
```
@@ -312,7 +378,7 @@ certificatesResolvers:
```bash tab="CLI"
# ...
--certificatesResolvers.sample.acme.dnsChallenge.resolvers:=1.1.1.1:53,8.8.8.8:53
--certificatesResolvers.le.acme.dnsChallenge.resolvers:=1.1.1.1:53,8.8.8.8:53
```
#### Wildcard Domains
@@ -320,12 +386,14 @@ certificatesResolvers:
[ACME V2](https://community.letsencrypt.org/t/acme-v2-and-wildcard-certificate-support-is-live/55579) supports wildcard certificates.
As described in [Let's Encrypt's post](https://community.letsencrypt.org/t/staging-endpoint-for-acme-v2/49605) wildcard certificates can only be generated through a [`DNS-01` challenge](#dnschallenge).
## `caServer`
## More Configuration
### `caServer`
??? example "Using the Let's Encrypt staging server"
```toml tab="File (TOML)"
[certificatesResolvers.sample.acme]
[certificatesResolvers.le.acme]
# ...
caServer = "https://acme-staging-v02.api.letsencrypt.org/directory"
# ...
@@ -342,16 +410,16 @@ As described in [Let's Encrypt's post](https://community.letsencrypt.org/t/stagi
```bash tab="CLI"
# ...
--certificatesResolvers.sample.acme.caServer=https://acme-staging-v02.api.letsencrypt.org/directory
--certificatesResolvers.le.acme.caServer=https://acme-staging-v02.api.letsencrypt.org/directory
# ...
```
## `storage`
### `storage`
The `storage` option sets the location where your ACME certificates are saved to.
```toml tab="File (TOML)"
[certificatesResolvers.sample.acme]
[certificatesResolvers.le.acme]
# ...
storage = "acme.json"
# ...
@@ -368,7 +436,7 @@ certificatesResolvers:
```bash tab="CLI"
# ...
--certificatesResolvers.sample.acme.storage=acme.json
--certificatesResolvers.le.acme.storage=acme.json
# ...
```
@@ -376,7 +444,7 @@ The value can refer to some kinds of storage:
- a JSON file
### In a File
#### In a File
ACME certificates can be stored in a JSON file that needs to have a `600` file mode .

View File

@@ -0,0 +1,88 @@
```yaml tab="Docker"
## Dynamic configuration
labels:
- traefik.http.routers.blog.rule=Host(`company.com`) && Path(`/blog`)
- traefik.http.routers.blog.tls=true
- traefik.http.routers.blog.tls.certresolver=le
- traefik.http.routers.blog.tls.domains[0].main=company.org
- traefik.http.routers.blog.tls.domains[0].sans=*.company.org
```
```yaml tab="Docker (Swarm)"
## Dynamic configuration
deploy:
labels:
- traefik.http.routers.blog.rule=Host(`company.com`) && Path(`/blog`)
- traefik.http.services.blog-svc.loadbalancer.server.port=8080"
- traefik.http.routers.blog.tls=true
- traefik.http.routers.blog.tls.certresolver=le
- traefik.http.routers.blog.tls.domains[0].main=company.org
- traefik.http.routers.blog.tls.domains[0].sans=*.company.org
```
```yaml tab="Kubernetes"
---
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
name: blogtls
spec:
entryPoints:
- websecure
routes:
- match: Host(`company.com`) && Path(`/blog`)
kind: Rule
services:
- name: blog
port: 8080
tls:
certResolver: le
```
```json tab="Marathon"
labels: {
"traefik.http.routers.blog.rule": "Host(`company.com`) && Path(`/blog`)",
"traefik.http.routers.blog.tls": "true",
"traefik.http.routers.blog.tls.certresolver": "le",
"traefik.http.routers.blog.tls.domains[0].main": "company.com",
"traefik.http.routers.blog.tls.domains[0].sans": "*.company.com",
"traefik.http.services.blog-svc.loadbalancer.server.port": "8080"
}
```
```yaml tab="Rancher"
## Dynamic configuration
labels:
- traefik.http.routers.blog.rule=Host(`company.com`) && Path(`/blog`)
- traefik.http.routers.blog.tls=true
- traefik.http.routers.blog.tls.certresolver=le
- traefik.http.routers.blog.tls.domains[0].main=company.org
- traefik.http.routers.blog.tls.domains[0].sans=*.company.org
```
```toml tab="File (TOML)"
## Dynamic configuration
[http.routers]
[http.routers.blog]
rule = "Host(`company.com`) && Path(`/blog`)"
[http.routers.blog.tls]
certResolver = "le" # From static configuration
[[http.routers.blog.tls.domains]]
main = "company.org"
sans = ["*.company.org"]
```
```yaml tab="File (YAML)"
## Dynamic configuration
http:
routers:
blog:
rule: "Host(`company.com`) && Path(`/blog`)"
tls:
certResolver: le
domains:
- main: "company.org"
sans:
- "*.company.org"
```

View File

@@ -0,0 +1,72 @@
```yaml tab="Docker"
## Dynamic configuration
labels:
- traefik.http.routers.blog.rule=(Host(`company.com`) && Path(`/blog`)) || Host(`blog.company.org`)
- traefik.http.routers.blog.tls=true
- traefik.http.routers.blog.tls.certresolver=le
```
```yaml tab="Docker (Swarm)"
## Dynamic configuration
deploy:
labels:
- traefik.http.routers.blog.rule=(Host(`company.com`) && Path(`/blog`)) || Host(`blog.company.org`)
- traefik.http.routers.blog.tls=true
- traefik.http.routers.blog.tls.certresolver=le
- traefik.http.services.blog-svc.loadbalancer.server.port=8080"
```
```yaml tab="Kubernetes"
---
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
name: blogtls
spec:
entryPoints:
- websecure
routes:
- match: (Host(`company.com`) && Path(`/blog`)) || Host(`blog.company.org`)
kind: Rule
services:
- name: blog
port: 8080
tls: {}
```
```json tab="Marathon"
labels: {
"traefik.http.routers.blog.rule": "(Host(`company.com`) && Path(`/blog`)) || Host(`blog.company.org`)",
"traefik.http.routers.blog.tls": "true",
"traefik.http.routers.blog.tls.certresolver": "le",
"traefik.http.services.blog-svc.loadbalancer.server.port": "8080"
}
```
```yaml tab="Rancher"
## Dynamic configuration
labels:
- traefik.http.routers.blog.rule=(Host(`company.com`) && Path(`/blog`)) || Host(`blog.company.org`)
- traefik.http.routers.blog.tls=true
- traefik.http.routers.blog.tls.certresolver=le
```
```toml tab="File (TOML)"
## Dynamic configuration
[http.routers]
[http.routers.blog]
rule = "(Host(`company.com`) && Path(`/blog`)) || Host(`blog.company.org`)"
[http.routers.blog.tls]
certResolver = "le" # From static configuration
```
```yaml tab="File (YAML)"
## Dynamic configuration
http:
routers:
blog:
rule: "(Host(`company.com`) && Path(`/blog`)) || Host(`blog.company.org`)"
tls:
certResolver: le
```

View File

@@ -0,0 +1,72 @@
```yaml tab="Docker"
## Dynamic configuration
labels:
- traefik.http.routers.blog.rule=Host(`company.com`) && Path(`/blog`)
- traefik.http.routers.blog.tls=true
- traefik.http.routers.blog.tls.certresolver=le
```
```yaml tab="Docker (Swarm)"
## Dynamic configuration
deploy:
labels:
- traefik.http.routers.blog.rule=Host(`company.com`) && Path(`/blog`)
- traefik.http.routers.blog.tls=true
- traefik.http.routers.blog.tls.certresolver=le
- traefik.http.services.blog-svc.loadbalancer.server.port=8080"
```
```yaml tab="Kubernetes"
---
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
name: blogtls
spec:
entryPoints:
- websecure
routes:
- match: Host(`company.com`) && Path(`/blog`)
kind: Rule
services:
- name: blog
port: 8080
tls: {}
```
```json tab="Marathon"
labels: {
"traefik.http.routers.blog.rule": "Host(`company.com`) && Path(`/blog`)",
"traefik.http.routers.blog.tls": "true",
"traefik.http.routers.blog.tls.certresolver": "le",
"traefik.http.services.blog-svc.loadbalancer.server.port": "8080"
}
```
```yaml tab="Rancher"
## Dynamic configuration
labels:
- traefik.http.routers.blog.rule=Host(`company.com`) && Path(`/blog`)
- traefik.http.routers.blog.tls=true
- traefik.http.routers.blog.tls.certresolver=le
```
```toml tab="Single Domain"
## Dynamic configuration
[http.routers]
[http.routers.blog]
rule = "Host(`company.com`) && Path(`/blog`)"
[http.routers.blog.tls]
certResolver = "le" # From static configuration
```
```yaml tab="File (YAML)"
## Dynamic configuration
http:
routers:
blog:
rule: "Host(`company.com`) && Path(`/blog`)"
tls:
certResolver: le
```

View File

@@ -35,13 +35,13 @@
#
# Optional (but recommended)
#
[certificatesResolvers.sample.acme.tlsChallenge]
[certificatesResolvers.le.acme.tlsChallenge]
# Use a HTTP-01 ACME challenge.
#
# Optional
#
# [certificatesResolvers.sample.acme.httpChallenge]
# [certificatesResolvers.le.acme.httpChallenge]
# EntryPoint to use for the HTTP-01 challenges.
#
@@ -54,7 +54,7 @@
#
# Optional
#
# [certificatesResolvers.sample.acme.dnsChallenge]
# [certificatesResolvers.le.acme.dnsChallenge]
# DNS provider used.
#

View File

@@ -4,13 +4,13 @@
#
# Required
#
--certificatesResolvers.sample.acme.email=test@traefik.io
--certificatesResolvers.le.acme.email=test@traefik.io
# File or key used for certificates storage.
#
# Required
#
--certificatesResolvers.sample.acme.storage=acme.json
--certificatesResolvers.le.acme.storage=acme.json
# CA server to use.
# Uncomment the line to use Let's Encrypt's staging server,
@@ -19,7 +19,7 @@
# Optional
# Default: "https://acme-v02.api.letsencrypt.org/directory"
#
--certificatesResolvers.sample.acme.caServer=https://acme-staging-v02.api.letsencrypt.org/directory
--certificatesResolvers.le.acme.caServer=https://acme-staging-v02.api.letsencrypt.org/directory
# KeyType to use.
#
@@ -28,38 +28,38 @@
#
# Available values : "EC256", "EC384", "RSA2048", "RSA4096", "RSA8192"
#
--certificatesResolvers.sample.acme.keyType=RSA4096
--certificatesResolvers.le.acme.keyType=RSA4096
# Use a TLS-ALPN-01 ACME challenge.
#
# Optional (but recommended)
#
--certificatesResolvers.sample.acme.tlsChallenge=true
--certificatesResolvers.le.acme.tlsChallenge=true
# Use a HTTP-01 ACME challenge.
#
# Optional
#
--certificatesResolvers.sample.acme.httpChallenge=true
--certificatesResolvers.le.acme.httpChallenge=true
# EntryPoint to use for the HTTP-01 challenges.
#
# Required
#
--certificatesResolvers.sample.acme.httpChallenge.entryPoint=web
--certificatesResolvers.le.acme.httpChallenge.entryPoint=web
# Use a DNS-01 ACME challenge rather than HTTP-01 challenge.
# Note: mandatory for wildcard certificate generation.
#
# Optional
#
--certificatesResolvers.sample.acme.dnsChallenge=true
--certificatesResolvers.le.acme.dnsChallenge=true
# DNS provider used.
#
# Required
#
--certificatesResolvers.sample.acme.dnsChallenge.provider=digitalocean
--certificatesResolvers.le.acme.dnsChallenge.provider=digitalocean
# By default, the provider will verify the TXT DNS challenge record before letting ACME verify.
# If delayBeforeCheck is greater than zero, this check is delayed for the configured duration in seconds.
@@ -68,14 +68,14 @@
# Optional
# Default: 0
#
--certificatesResolvers.sample.acme.dnsChallenge.delayBeforeCheck=0
--certificatesResolvers.le.acme.dnsChallenge.delayBeforeCheck=0
# Use following DNS servers to resolve the FQDN authority.
#
# Optional
# Default: empty
#
--certificatesResolvers.sample.acme.dnsChallenge.resolvers=1.1.1.1:53,8.8.8.8:53
--certificatesResolvers.le.acme.dnsChallenge.resolvers=1.1.1.1:53,8.8.8.8:53
# Disable the DNS propagation checks before notifying ACME that the DNS challenge is ready.
#
@@ -85,4 +85,4 @@
# Optional
# Default: false
#
--certificatesResolvers.sample.acme.dnsChallenge.disablePropagationCheck=true
--certificatesResolvers.le.acme.dnsChallenge.disablePropagationCheck=true

View File

@@ -1,5 +1,5 @@
certificatesResolvers:
sample:
le:
# Enable ACME (Let's Encrypt): automatic SSL.
acme:

View File

@@ -40,7 +40,7 @@ tls:
In the above example, we've used the [file provider](../providers/file.md) to handle these definitions.
It is the only available method to configure the certificates (as well as the options and the stores).
However, in [Kubernetes](../providers/kubernetes-crd.md), the certificates can and must be provided by [secrets](../routing/providers/kubernetes-crd.md#tls).
However, in [Kubernetes](../providers/kubernetes-crd.md), the certificates can and must be provided by [secrets](https://kubernetes.io/docs/concepts/configuration/secret/).
## Certificates Stores

View File

@@ -20,4 +20,4 @@ Developing Traefik, our main goal is to make it simple to use, and we're sure yo
!!! info
If you're a business running critical services behind Traefik, know that [Containous](https://containo.us), the company that sponsors Traefik's development, can provide [commercial support](https://containo.us/services/#commercial-support) and develops an [Enterprise Edition](https://containo.us/traefikee/) of Traefik.
If you're a business running critical services behind Traefik, know that [Containous](https://containo.us), the company that sponsors Traefik's development, can provide [commercial support](https://info.containo.us/commercial-services) and develops an [Enterprise Edition](https://containo.us/traefikee/) of Traefik.

View File

@@ -66,7 +66,7 @@ http:
### `sourceRange`
The `sourceRange` option sets the allowed IPs (or ranges of allowed IPs).
The `sourceRange` option sets the allowed IPs (or ranges of allowed IPs by using CIDR notation).
### `ipStrategy`

View File

@@ -406,7 +406,7 @@ In the example, it is the part between `-----BEGIN CERTIFICATE-----` and `-----E
!!! info "Extracted data"
The delimiters and `\n` will be removed.
If there are more than one certificate, they are separated by a "`;`".
If there are more than one certificate, they are separated by a "`,`".
!!! warning "`X-Forwarded-Tls-Client-Cert` value could exceed the web server header size limit"
@@ -421,12 +421,12 @@ The value of the header will be an escaped concatenation of all the selected cer
The following example shows an unescaped result that uses all the available fields:
```text
Subject="DC=org,DC=cheese,C=FR,C=US,ST=Cheese org state,ST=Cheese com state,L=TOULOUSE,L=LYON,O=Cheese,O=Cheese 2,CN=*.cheese.com",Issuer="DC=org,DC=cheese,C=FR,C=US,ST=Signing State,ST=Signing State 2,L=TOULOUSE,L=LYON,O=Cheese,O=Cheese 2,CN=Simple Signing CA 2",NB=1544094616,NA=1607166616,SAN=*.cheese.org,*.cheese.net,*.cheese.com,test@cheese.org,test@cheese.net,10.0.1.0,10.0.1.2
Subject="DC=org,DC=cheese,C=FR,C=US,ST=Cheese org state,ST=Cheese com state,L=TOULOUSE,L=LYON,O=Cheese,O=Cheese 2,CN=*.cheese.com";Issuer="DC=org,DC=cheese,C=FR,C=US,ST=Signing State,ST=Signing State 2,L=TOULOUSE,L=LYON,O=Cheese,O=Cheese 2,CN=Simple Signing CA 2";NB="1544094616";NA="1607166616";SAN="*.cheese.org,*.cheese.net,*.cheese.com,test@cheese.org,test@cheese.net,10.0.1.0,10.0.1.2"
```
!!! info "Multiple certificates"
If there are more than one certificate, they are separated by a `;`.
If there are more than one certificate, they are separated by a `,`.
#### `info.notAfter`
@@ -442,7 +442,7 @@ The data are taken from the following certificate part:
The escape `notAfter` info part will be like:
```text
NA=1607166616
NA="1607166616"
```
#### `info.notBefore`
@@ -459,7 +459,7 @@ Validity
The escape `notBefore` info part will be like:
```text
NB=1544094616
NB="1544094616"
```
#### `info.sans`
@@ -476,7 +476,7 @@ The data are taken from the following certificate part:
The escape SANs info part will be like:
```text
SAN=*.cheese.org,*.cheese.net,*.cheese.com,test@cheese.org,test@cheese.net,10.0.1.0,10.0.1.2
SAN="*.cheese.org,*.cheese.net,*.cheese.com,test@cheese.org,test@cheese.net,10.0.1.0,10.0.1.2"
```
!!! info "multiple values"

View File

@@ -104,7 +104,7 @@ Then any router can refer to an instance of the wanted middleware.
```yaml tab="K8s IngressRoute"
# The definitions below require the definitions for the Middleware and IngressRoute kinds.
# https://docs.traefik.io/v2.0/providers/kubernetes-crd/#traefik-ingressroute-definition
# https://docs.traefik.io/v2.1/reference/dynamic-configuration/kubernetes-crd/#definitions
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
@@ -278,7 +278,7 @@ Then, a [router's TLS field](../routing/routers/index.md#tls) can refer to one o
```yaml tab="K8s IngressRoute"
# The definitions below require the definitions for the TLSOption and IngressRoute kinds.
# https://docs.traefik.io/v2.0/providers/kubernetes-crd/#traefik-ingressroute-definition
# https://docs.traefik.io/v2.1/reference/dynamic-configuration/kubernetes-crd/#definitions
apiVersion: traefik.containo.us/v1alpha1
kind: TLSOption
metadata:
@@ -560,8 +560,8 @@ with the path `/admin` stripped, e.g. to `http://<IP>:<port>/`. In this case, yo
```yaml tab="Docker"
labels:
- "traefik.http.routers.admin.rule=Host(`company.org`) && PathPrefix(`/admin`)"
- "traefik.http.routers.admin.middlewares=admin-stripprefix"
- "traefik.http.middlewares.admin-stripprefix.stripprefix.prefixes=/admin"
- "traefik.http.routers.web.middlewares=admin-stripprefix@docker"
```
```yaml tab="Kubernetes IngressRoute"
@@ -1029,12 +1029,12 @@ As the dashboard access is now secured by default you can either:
[api]
[providers.file]
filename = "/dynamic-conf.toml"
directory = "/path/to/dynamic/config"
##---------------------##
## dynamic configuration
# dynamic-conf.toml
# /path/to/dynamic/config/dynamic-conf.toml
[http.routers.api]
rule = "Host(`traefik.docker.localhost`)"
@@ -1061,12 +1061,12 @@ As the dashboard access is now secured by default you can either:
providers:
file:
filename: /dynamic-conf.yaml
directory: /path/to/dynamic/config
##---------------------##
## dynamic configuration
# dynamic-conf.yaml
# /path/to/dynamic/config/dynamic-conf.yaml
http:
routers:

View File

@@ -0,0 +1,99 @@
# Migration: Steps needed between the versions
## v2.0 to v2.1
In v2.1, a new CRD called `TraefikService` was added. While updating an installation to v2.1,
it is required to apply that CRD before as well as enhance the existing `ClusterRole` definition to allow Traefik to use that CRD.
To add that CRD and enhance the permissions, following definitions need to be applied to the cluster.
```yaml tab="TraefikService"
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: traefikservices.traefik.containo.us
spec:
group: traefik.containo.us
version: v1alpha1
names:
kind: TraefikService
plural: traefikservices
singular: traefikservice
scope: Namespaced
```
```yaml tab="ClusterRole"
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: traefik-ingress-controller
rules:
- apiGroups:
- ""
resources:
- services
- endpoints
- secrets
verbs:
- get
- list
- watch
- apiGroups:
- extensions
resources:
- ingresses
verbs:
- get
- list
- watch
- apiGroups:
- extensions
resources:
- ingresses/status
verbs:
- update
- apiGroups:
- traefik.containo.us
resources:
- middlewares
verbs:
- get
- list
- watch
- apiGroups:
- traefik.containo.us
resources:
- ingressroutes
verbs:
- get
- list
- watch
- apiGroups:
- traefik.containo.us
resources:
- ingressroutetcps
verbs:
- get
- list
- watch
- apiGroups:
- traefik.containo.us
resources:
- tlsoptions
verbs:
- get
- list
- watch
- apiGroups:
- traefik.containo.us
resources:
- traefikservices
verbs:
- get
- list
- watch
```
After having both resources applied, Traefik will work properly.

View File

@@ -85,19 +85,17 @@ We recommend to use a "Host Based rule" as ```Host(`traefik.domain.com`)``` to m
or to make sure that the defined rule captures both prefixes:
```bash tab="Host Rule"
# Matches http://traefik.domain.com/api or http://traefik.domain.com/dashboard
# The dashboard can be accessed on http://traefik.domain.com/dashboard/
rule = "Host(`traefik.domain.com`)"
```
```bash tab="Path Prefix Rule"
# Matches http://traefik.domain.com/api , http://domain.com/api or http://traefik.domain.com/dashboard
# but does not match http://traefik.domain.com/hello
# The dashboard can be accessed on http://domain.com/dashboard/ or http://traefik.domain.com/dashboard/
rule = "PathPrefix(`/api`) || PathPrefix(`/dashboard`)"
```
```bash tab="Combination of Rules"
# Matches http://traefik.domain.com/api or http://traefik.domain.com/dashboard
# but does not match http://traefik.domain.com/hello
# The dashboard can be accessed on http://traefik.domain.com/dashboard/
rule = "Host(`traefik.domain.com`) && (PathPrefix(`/api`) || PathPrefix(`/dashboard`))"
```

View File

@@ -19,6 +19,28 @@ deploy:
- "traefik.http.services.dummy-svc.loadbalancer.server.port=9999"
```
```yaml tab="Kubernetes CRD"
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
name: traefik-dashboard
spec:
routes:
- match: Host(`traefik.domain.com`)
kind: Rule
services:
- name: api@internal
kind: TraefikService
---
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
name: auth
spec:
basicAuth:
secret: secretName # Kubernetes secret named "secretName"
```
```yaml tab="Consul Catalog"
# Dynamic Configuration
- "traefik.http.routers.api.rule=Host(`traefik.domain.com`)"

View File

@@ -59,7 +59,7 @@ ping:
--ping.entryPoint=ping
```
#### `manualRouting`
### `manualRouting`
_Optional, Default=false_

View File

@@ -86,7 +86,7 @@ and [Docker Swarm Mode](https://docs.docker.com/engine/swarm/).
## Routing Configuration
When using Docker as a [provider](https://docs.traefik.io/providers/overview/),
Trafik uses [container labels](https://docs.docker.com/engine/reference/commandline/run/#set-metadata-on-container--l---label---label-file) to retrieve its routing configuration.
Traefik uses [container labels](https://docs.docker.com/engine/reference/commandline/run/#set-metadata-on-container--l---label---label-file) to retrieve its routing configuration.
See the list of labels in the dedicated [routing](../routing/providers/docker.md) section.

View File

@@ -23,17 +23,17 @@ You can write one of these mutually exclusive configuration elements:
```toml tab="File (TOML)"
[providers.file]
filename = "/my/path/to/dynamic-conf.toml"
directory = "/path/to/dynamic/conf"
```
```yaml tab="File (YAML)"
providers:
file:
filename: "/my/path/to/dynamic-conf.yml"
directory: "/path/to/dynamic/conf"
```
```bash tab="CLI"
--providers.file.filename=/my/path/to/dynamic_conf.toml
--providers.file.directory=/path/to/dynamic/conf
```
Declaring Routers, Middlewares & Services:
@@ -100,6 +100,22 @@ You can write one of these mutually exclusive configuration elements:
If you're in a hurry, maybe you'd rather go through the [dynamic configuration](../reference/dynamic-configuration/file.md) references and the [static configuration](../reference/static-configuration/overview.md).
!!! warning "Limitations"
With the file provider, Traefik listens for file system notifications to update the dynamic configuration.
If you use a mounted/bound file system in your orchestrator (like docker or kubernetes), the way the files are linked may be a source of errors.
If the link between the file systems is broken, when a source file/directory is changed/renamed, nothing will be reported to the linked file/directory, so the file system notifications will be neither triggered nor caught.
For example, in docker, if the host file is renamed, the link to the mounted file will be broken and the container's file will not be updated.
To avoid this kind of issue, a good practice is to:
* set the Traefik [**directory**](#directory) configuration with the parent directory
* mount/bind the parent directory
As it is very difficult to listen to all file system notifications, Traefik use [fsnotify](https://github.com/fsnotify/fsnotify).
If using a directory with a mounted directory does not fix your issue, please check your file system compatibility with fsnotify.
### `filename`
Defines the path of the configuration file.
@@ -148,19 +164,19 @@ It works with both the `filename` and the `directory` options.
```toml tab="File (TOML)"
[providers]
[providers.file]
filename = "dynamic_conf.toml"
directory = "/path/to/dynamic/conf"
watch = true
```
```yaml tab="File (YAML)"
providers:
file:
filename: dynamic_conf.yml
directory: /path/to/dynamic/conf
watch: true
```
```bash tab="CLI"
--providers.file.filename=dynamic_conf.toml
--providers.file.directory=/my/path/to/dynamic/conf
--providers.file.watch=true
```

View File

@@ -8,9 +8,60 @@ Traefik used to support Kubernetes only through the [Kubernetes Ingress provider
However, as the community expressed the need to benefit from Traefik features without resorting to (lots of) annotations,
we ended up writing a [Custom Resource Definition](https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/) (alias CRD in the following) for an IngressRoute type, defined below, in order to provide a better way to configure access to a Kubernetes cluster.
## Configuration Requirements
!!! tip "All Steps for a Successful Deployment"
* Add/update **all** the Traefik resources [definitions](../reference/dynamic-configuration/kubernetes-crd.md#definitions)
* Add/update the [RBAC](https://kubernetes.io/docs/reference/access-authn-authz/rbac/) for the Traefik custom resources
* Use [Helm Chart](../getting-started/install-traefik.md#use-the-helm-chart) or use a custom Traefik Deployment
* Enable the kubernetesCRD provider
* Apply the needed kubernetesCRD provider [configuration](#provider-configuration)
* Add all needed traefik custom [resources](../reference/dynamic-configuration/kubernetes-crd.md#resources)
??? example "Initializing Resource Definition and RBAC"
```yaml tab="Traefik Resource Definition"
# All resources definition must be declared
--8<-- "content/reference/dynamic-configuration/kubernetes-crd-definition.yml"
```
```yaml tab="RBAC for Traefik CRD"
--8<-- "content/reference/dynamic-configuration/kubernetes-crd-rbac.yml"
```
## Resource Configuration
See the dedicated section in [routing](../routing/providers/kubernetes-crd.md).
When using KubernetesCRD as a provider,
Traefik uses [Custom Resource Definition](https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/) to retrieve its routing configuration.
Traefik Custom Resource Definitions are a Kubernetes implementation of the Traefik concepts. The main particularities are:
* The usage of `name` **and** `namespace` to refer to another Kubernetes resource.
* The usage of [secret](https://kubernetes.io/docs/concepts/configuration/secret/) for sensible data like:
* TLS certificate.
* Authentication data.
* The structure of the configuration.
* The obligation to declare all the [definitions](../reference/dynamic-configuration/kubernetes-crd.md#definitions).
The Traefik CRD are building blocks which you can assemble according to your needs.
See the list of CRDs in the dedicated [routing section](../routing/providers/kubernetes-crd.md).
## LetsEncrypt Support with the Custom Resource Definition Provider
By design, Traefik is a stateless application, meaning that it only derives its configuration from the environment it runs in, without additional configuration.
For this reason, users can run multiple instances of Traefik at the same time to achieve HA, as is a common pattern in the kubernetes ecosystem.
When using a single instance of Traefik with LetsEncrypt, no issues should be encountered, however this could be a single point of failure.
Unfortunately, it is not possible to run multiple instances of Traefik 2.0 with LetsEncrypt enabled, because there is no way to ensure that the correct instance of Traefik will receive the challenge request, and subsequent responses.
Previous versions of Traefik used a [KV store](https://docs.traefik.io/v1.7/configuration/acme/#storage) to attempt to achieve this, but due to sub-optimal performance was dropped as a feature in 2.0.
If you require LetsEncrypt with HA in a kubernetes environment, we recommend using [TraefikEE](https://containo.us/traefikee/) where distributed LetsEncrypt is a supported feature.
If you are wanting to continue to run Traefik Community Edition, LetsEncrypt HA can be achieved by using a Certificate Controller such as [Cert-Manager](https://docs.cert-manager.io/en/latest/index.html).
When using Cert-Manager to manage certificates, it will create secrets in your namespaces that can be referenced as TLS secrets in your [ingress objects](https://kubernetes.io/docs/concepts/services-networking/ingress/#tls).
When using the Traefik Kubernetes CRD Provider, unfortunately Cert-Manager cannot interface directly with the CRDs _yet_, but this is being worked on by our team.
A workaround it to enable the [Kubernetes Ingress provider](./kubernetes-ingress.md) to allow Cert-Manager to create ingress objects to complete the challenges.
Please note that this still requires manual intervention to create the certificates through Cert-Manager, but once created, Cert-Manager will keep the certificate renewed.
## Provider Configuration

View File

@@ -47,6 +47,20 @@ spec:
servicePort: 80
```
## LetsEncrypt Support with the Ingress Provider
By design, Traefik is a stateless application, meaning that it only derives its configuration from the environment it runs in, without additional configuration.
For this reason, users can run multiple instances of Traefik at the same time to achieve HA, as is a common pattern in the kubernetes ecosystem.
When using a single instance of Traefik with LetsEncrypt, no issues should be encountered, however this could be a single point of failure.
Unfortunately, it is not possible to run multiple instances of Traefik 2.0 with LetsEncrypt enabled, because there is no way to ensure that the correct instance of Traefik will receive the challenge request, and subsequent responses.
Previous versions of Traefik used a [KV store](https://docs.traefik.io/v1.7/configuration/acme/#storage) to attempt to achieve this, but due to sub-optimal performance was dropped as a feature in 2.0.
If you require LetsEncrypt with HA in a kubernetes environment, we recommend using [TraefikEE](https://containo.us/traefikee/) where distributed LetsEncrypt is a supported feature.
If you are wanting to continue to run Traefik Community Edition, LetsEncrypt HA can be achieved by using a Certificate Controller such as [Cert-Manager](https://docs.cert-manager.io/en/latest/index.html).
When using Cert-Manager to manage certificates, it will create secrets in your namespaces that can be referenced as TLS secrets in your [ingress objects](https://kubernetes.io/docs/concepts/services-networking/ingress/#tls).
## Provider Configuration
### `endpoint`

View File

@@ -0,0 +1,73 @@
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: ingressroutes.traefik.containo.us
spec:
group: traefik.containo.us
version: v1alpha1
names:
kind: IngressRoute
plural: ingressroutes
singular: ingressroute
scope: Namespaced
---
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: middlewares.traefik.containo.us
spec:
group: traefik.containo.us
version: v1alpha1
names:
kind: Middleware
plural: middlewares
singular: middleware
scope: Namespaced
---
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: ingressroutetcps.traefik.containo.us
spec:
group: traefik.containo.us
version: v1alpha1
names:
kind: IngressRouteTCP
plural: ingressroutetcps
singular: ingressroutetcp
scope: Namespaced
---
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: tlsoptions.traefik.containo.us
spec:
group: traefik.containo.us
version: v1alpha1
names:
kind: TLSOption
plural: tlsoptions
singular: tlsoption
scope: Namespaced
---
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: traefikservices.traefik.containo.us
spec:
group: traefik.containo.us
version: v1alpha1
names:
kind: TraefikService
plural: traefikservices
singular: traefikservice
scope: Namespaced

View File

@@ -0,0 +1,13 @@
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: ingressroutetcps.traefik.containo.us
spec:
group: traefik.containo.us
version: v1alpha1
names:
kind: IngressRouteTCP
plural: ingressroutetcps
singular: ingressroutetcp
scope: Namespaced

View File

@@ -0,0 +1,57 @@
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: traefik-ingress-controller
rules:
- apiGroups:
- ""
resources:
- services
- endpoints
- secrets
verbs:
- get
- list
- watch
- apiGroups:
- extensions
resources:
- ingresses
verbs:
- get
- list
- watch
- apiGroups:
- extensions
resources:
- ingresses/status
verbs:
- update
- apiGroups:
- traefik.containo.us
resources:
- middlewares
- ingressroutes
- traefikservices
- ingressroutetcps
- tlsoptions
verbs:
- get
- list
- watch
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: traefik-ingress-controller
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: traefik-ingress-controller
subjects:
- kind: ServiceAccount
name: traefik-ingress-controller
namespace: default

View File

@@ -0,0 +1,157 @@
apiVersion: traefik.containo.us/v1alpha1
kind: TraefikService
metadata:
name: wrr2
namespace: default
spec:
weighted:
services:
- name: s1
weight: 1
port: 80
# Optional, as it is the default value
kind: Service
- name: s3
weight: 1
port: 80
---
apiVersion: traefik.containo.us/v1alpha1
kind: TraefikService
metadata:
name: wrr1
namespace: default
spec:
weighted:
services:
- name: wrr2
kind: TraefikService
weight: 1
- name: s3
weight: 1
port: 80
---
apiVersion: traefik.containo.us/v1alpha1
kind: TraefikService
metadata:
name: mirror1
namespace: default
spec:
mirroring:
name: s1
port: 80
mirrors:
- name: s3
percent: 20
port: 80
- name: mirror2
kind: TraefikService
percent: 20
---
apiVersion: traefik.containo.us/v1alpha1
kind: TraefikService
metadata:
name: mirror2
namespace: default
spec:
mirroring:
name: wrr2
kind: TraefikService
mirrors:
- name: s2
# Optional, as it is the default value
kind: Service
percent: 20
port: 80
---
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
name: ingressroute
spec:
entryPoints:
- web
- web-secure
routes:
- match: Host(`foo.com`) && PathPrefix(`/bar`)
kind: Rule
priority: 12
# defining several services is possible and allowed, but for now the servers of
# all the services (for a given route) get merged altogether under the same
# load-balancing strategy.
services:
- name: s1
port: 80
healthCheck:
path: /health
host: baz.com
intervalSeconds: 7
timeoutSeconds: 60
# strategy defines the load balancing strategy between the servers. It defaults
# to Round Robin, and for now only Round Robin is supported anyway.
strategy: RoundRobin
- name: s2
port: 433
healthCheck:
path: /health
host: baz.com
intervalSeconds: 7
timeoutSeconds: 60
- match: PathPrefix(`/misc`)
services:
- name: s3
port: 80
middlewares:
- name: stripprefix
- name: addprefix
- match: PathPrefix(`/misc`)
services:
- name: s3
# Optional, as it is the default value
kind: Service
port: 8443
# scheme allow to override the scheme for the service. (ex: https or h2c)
scheme: https
- match: PathPrefix(`/lb`)
services:
- name: wrr1
kind: TraefikService
- match: PathPrefix(`/mirrored`)
services:
- name: mirror1
kind: TraefikService
# use an empty tls object for TLS with Let's Encrypt
tls:
secretName: supersecret
options:
name: myTLSOption
namespace: default
---
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRouteTCP
metadata:
name: ingressroutetcp.crd
namespace: default
spec:
entryPoints:
- footcp
routes:
- match: HostSNI(`bar.com`)
services:
- name: whoamitcp
port: 8080
tls:
secretName: foosecret
passthrough: false
options:
name: myTLSOption
namespace: default

View File

@@ -3,6 +3,20 @@
Dynamic configuration with Kubernetes Custom Resource
{: .subtitle }
## Definitions
```yaml
--8<-- "content/reference/dynamic-configuration/kubernetes-crd.yml"
--8<-- "content/reference/dynamic-configuration/kubernetes-crd-definition.yml"
```
## Resources
```yaml
--8<-- "content/reference/dynamic-configuration/kubernetes-crd-resource.yml"
```
## RBAC
```yaml
--8<-- "content/reference/dynamic-configuration/kubernetes-crd-rbac.yml"
```

View File

@@ -41,7 +41,7 @@ They define the port which will receive the requests (whether HTTP or TCP).
[entryPoints.web]
address = ":80"
[entryPoints.web-secure]
[entryPoints.websecure]
address = ":443"
```
@@ -51,18 +51,18 @@ They define the port which will receive the requests (whether HTTP or TCP).
web:
address: ":80"
web-secure:
websecure:
address: ":443"
```
```bash tab="CLI"
## Static configuration
--entryPoints.web.address=:80
--entryPoints.web-secure.address=:443
--entryPoints.websecure.address=:443
```
- Two entrypoints are defined: one called `web`, and the other called `web-secure`.
- `web` listens on port `80`, and `web-secure` on port `443`.
- Two entrypoints are defined: one called `web`, and the other called `websecure`.
- `web` listens on port `80`, and `websecure` on port `443`.
## Configuration

View File

@@ -33,9 +33,9 @@ Static configuration:
address = ":8081"
[providers]
# Enable the file provider to define routers / middlewares / services in a file
# Enable the file provider to define routers / middlewares / services in file
[providers.file]
filename = "dynamic_conf.toml"
directory = "/path/to/dynamic/conf"
```
```yaml tab="File (YAML)"
@@ -45,17 +45,17 @@ entryPoints:
address: :8081
providers:
# Enable the file provider to define routers / middlewares / services in a file
# Enable the file provider to define routers / middlewares / services in file
file:
filename: dynamic_conf.yml
directory: /path/to/dynamic/conf
```
```bash tab="CLI"
# Listen on port 8081 for incoming requests
--entryPoints.web.address=:8081
# Enable the file provider to define routers / middlewares / services in a file
--providers.file.filename=dynamic_conf.toml
# Enable the file provider to define routers / middlewares / services in file
--providers.file.directory=/path/to/dynamic/conf
```
Dynamic configuration:
@@ -133,9 +133,9 @@ http:
address = ":8081"
[providers]
# Enable the file provider to define routers / middlewares / services in a file
# Enable the file provider to define routers / middlewares / services in file
[providers.file]
filename = "dynamic_conf.toml"
directory = "/path/to/dynamic/conf"
```
```yaml tab="File (YAML)"
@@ -144,17 +144,17 @@ http:
# Listen on port 8081 for incoming requests
address: :8081
providers:
# Enable the file provider to define routers / middlewares / services in a file
# Enable the file provider to define routers / middlewares / services in file
file:
filename: dynamic_conf.yml
directory: /path/to/dynamic/conf
```
```bash tab="CLI"
# Listen on port 8081 for incoming requests
--entryPoints.web.address=:8081
# Enable the file provider to define routers / middlewares / services in a file
--providers.file.filename=dynamic_conf.toml
# Enable the file provider to define routers / middlewares / services in file
--providers.file.directory=/path/to/dynamic/conf
```
**Dynamic Configuration**

File diff suppressed because it is too large Load Diff

View File

@@ -91,7 +91,7 @@ For example, to change the routing rule, you could add the label ```"traefik.htt
See [tls](../routers/index.md#tls) for more information.
```json
"traefik.http.routers.myrouter>.tls": "true"
"traefik.http.routers.myrouter.tls": "true"
```
??? info "`traefik.http.routers.<router_name>.tls.certresolver`"

View File

@@ -387,7 +387,9 @@ The WRR is able to load balance the requests between multiple services based on
This strategy is only available to load balance between [services](./index.md) and not between [servers](./index.md#servers).
!!! info "This strategy can be defined only with [File](../../providers/file.md)."
!!! info "Supported Providers"
This strategy can be defined currently with the [File](../../providers/file.md) or [IngressRoute](../../providers/kubernetes-crd.md) providers.
```toml tab="TOML"
## Dynamic configuration
@@ -438,7 +440,9 @@ http:
The mirroring is able to mirror requests sent to a service to other services.
!!! info "This strategy can be defined only with [File](../../providers/file.md)."
!!! info "Supported Providers"
This strategy can be defined currently with the [File](../../providers/file.md) or [IngressRoute](../../providers/kubernetes-crd.md) providers.
```toml tab="TOML"
## Dynamic configuration
@@ -583,7 +587,9 @@ The Weighted Round Robin (alias `WRR`) load-balancer of services is in charge of
This strategy is only available to load balance between [services](./index.md) and not between [servers](./index.md#servers).
This strategy can only be defined with [File](../../providers/file.md).
!!! info "Supported Providers"
This strategy can be defined currently with the [File](../../providers/file.md) or [IngressRoute](../../providers/kubernetes-crd.md) providers.
```toml tab="TOML"
## Dynamic configuration

View File

@@ -16,7 +16,7 @@ Static configuration:
[api]
[providers.file]
filename = "dynamic_conf.toml"
directory = "/path/to/dynamic/config"
```
```yaml tab="File (YAML)"
@@ -26,18 +26,18 @@ entryPoints:
providers:
file:
filename: dynamic_conf.yml
directory: /path/to/dynamic/config
api: {}
```
```yaml tab="CLI"
--entryPoints.web.address=:80
--providers.file.filename=dynamic_conf.toml
--providers.file.directory=/path/to/dynamic/config
--api.insecure=true
```
`dynamic_conf.{toml,yml}`:
`/path/to/dynamic/config/dynamic_conf.{toml,yml}`:
```toml tab="TOML"
## dynamic configuration ##
@@ -132,7 +132,7 @@ Static configuration:
[api]
[provider.file]
filename = "dynamic_conf.toml"
directory = "/path/to/dynamic/config"
```
```yaml tab="File (YAML)"
@@ -147,7 +147,7 @@ serversTransport:
providers:
file:
filename: dynamic_conf.yml
directory: /path/to/dynamic/config
api: {}
```
@@ -156,11 +156,11 @@ api: {}
--entryPoints.websecure.address=:4443
# For secure connection on backend.local
--serversTransport.rootCAs=./backend.cert
--providers.file.filename=dynamic_conf.toml
--providers.file.directory=/path/to/dynamic/config
--api.insecure=true
```
`dynamic_conf.{toml,yml}`:
`/path/to/dynamic/config/dynamic_conf.{toml,yml}`:
```toml tab="TOML"
## dynamic configuration ##

View File

@@ -44,7 +44,7 @@ plugins:
- search
- exclude:
glob:
- include-*.md
- "**/include-*.md"
# https://squidfunk.github.io/mkdocs-material/extensions/admonition/
# https://facelessuser.github.io/pymdown-extensions/
@@ -154,6 +154,7 @@ nav:
- 'HTTP Challenge': 'user-guides/docker-compose/acme-http/index.md'
- 'DNS Challenge': 'user-guides/docker-compose/acme-dns/index.md'
- 'Migration':
- 'Traefik v2 minor migrations': 'migration/v2.md'
- 'Traefik v1 to v2': 'migration/v1-to-v2.md'
- 'Contributing':
- 'Thank You!': 'contributing/thank-you.md'

View File

@@ -1 +1 @@
3.6
3.7

2
go.mod
View File

@@ -80,7 +80,7 @@ require (
github.com/stvp/go-udp-testing v0.0.0-20171104055251-c4434f09ec13
github.com/tinylib/msgp v1.0.2 // indirect
github.com/transip/gotransip v5.8.2+incompatible // indirect
github.com/uber/jaeger-client-go v2.19.0+incompatible
github.com/uber/jaeger-client-go v2.21.1+incompatible
github.com/uber/jaeger-lib v2.2.0+incompatible
github.com/unrolled/render v1.0.1
github.com/unrolled/secure v1.0.5

4
go.sum
View File

@@ -554,8 +554,8 @@ github.com/transip/gotransip v5.8.2+incompatible/go.mod h1:uacMoJVmrfOcscM4Bi5NV
github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM=
github.com/uber-go/atomic v1.3.2 h1:Azu9lPBWRNKzYXSIwRfgRuDuS0YKsK4NFhiQv98gkxo=
github.com/uber-go/atomic v1.3.2/go.mod h1:/Ct5t2lcmbJ4OSe/waGBoaVvVqtO0bmtfVNex1PFV8g=
github.com/uber/jaeger-client-go v2.19.0+incompatible h1:pbwbYfHUoaase0oPQOdZ1GcaUjImYGimUXSQ/+8+Z8Q=
github.com/uber/jaeger-client-go v2.19.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk=
github.com/uber/jaeger-client-go v2.21.1+incompatible h1:oozboeZmWz+tyh3VZttJWlF3K73mHgbokieceqKccLo=
github.com/uber/jaeger-client-go v2.21.1+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk=
github.com/uber/jaeger-lib v2.2.0+incompatible h1:MxZXOiR2JuoANZ3J6DE/U0kSFv/eJ/GfSYVCjK7dyaw=
github.com/uber/jaeger-lib v2.2.0+incompatible/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U=
github.com/unrolled/render v1.0.1 h1:VDDnQQVfBMsOsp3VaCJszSO0nkBIVEYoPWeRThk9spY=

View File

@@ -4,7 +4,6 @@ import (
"fmt"
"net/http"
"os"
"strconv"
"time"
"github.com/containous/traefik/v2/integration/try"
@@ -62,23 +61,13 @@ func (s *ConsulCatalogSuite) TearDownSuite(c *check.C) {
}
}
func (s *ConsulCatalogSuite) registerService(id, name, address, port string, tags []string, onAgent bool) error {
iPort, err := strconv.Atoi(port)
if err != nil {
return err
}
func (s *ConsulCatalogSuite) registerService(reg *api.AgentServiceRegistration, onAgent bool) error {
client := s.consulClient
if onAgent {
client = s.consulAgentClient
}
return client.Agent().ServiceRegister(&api.AgentServiceRegistration{
ID: id,
Name: name,
Address: address,
Port: iPort,
Tags: tags,
})
return client.Agent().ServiceRegister(reg)
}
func (s *ConsulCatalogSuite) deregisterService(id string, onAgent bool) error {
@@ -90,11 +79,34 @@ func (s *ConsulCatalogSuite) deregisterService(id string, onAgent bool) error {
}
func (s *ConsulCatalogSuite) TestWithNotExposedByDefaultAndDefaultsSettings(c *check.C) {
err := s.registerService("whoami1", "whoami", s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress, "80", []string{"traefik.enable=true"}, false)
reg1 := &api.AgentServiceRegistration{
ID: "whoami1",
Name: "whoami",
Tags: []string{"traefik.enable=true"},
Port: 80,
Address: s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress,
}
err := s.registerService(reg1, false)
c.Assert(err, checker.IsNil)
err = s.registerService("whoami2", "whoami", s.composeProject.Container(c, "whoami2").NetworkSettings.IPAddress, "80", []string{"traefik.enable=true"}, false)
reg2 := &api.AgentServiceRegistration{
ID: "whoami2",
Name: "whoami",
Tags: []string{"traefik.enable=true"},
Port: 80,
Address: s.composeProject.Container(c, "whoami2").NetworkSettings.IPAddress,
}
err = s.registerService(reg2, false)
c.Assert(err, checker.IsNil)
err = s.registerService("whoami3", "whoami", s.composeProject.Container(c, "whoami3").NetworkSettings.IPAddress, "80", []string{"traefik.enable=true"}, false)
reg3 := &api.AgentServiceRegistration{
ID: "whoami3",
Name: "whoami",
Tags: []string{"traefik.enable=true"},
Port: 80,
Address: s.composeProject.Container(c, "whoami3").NetworkSettings.IPAddress,
}
err = s.registerService(reg3, false)
c.Assert(err, checker.IsNil)
tempObjects := struct {
@@ -128,14 +140,21 @@ func (s *ConsulCatalogSuite) TestWithNotExposedByDefaultAndDefaultsSettings(c *c
}
func (s *ConsulCatalogSuite) TestByLabels(c *check.C) {
labels := []string{
"traefik.enable=true",
"traefik.http.routers.router1.rule=Path(`/whoami`)",
"traefik.http.routers.router1.service=service1",
"traefik.http.services.service1.loadBalancer.server.url=http://" + s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress,
}
containerIP := s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress
err := s.registerService("whoami1", "whoami", s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress, "80", labels, false)
reg := &api.AgentServiceRegistration{
ID: "whoami1",
Name: "whoami",
Tags: []string{
"traefik.enable=true",
"traefik.http.routers.router1.rule=Path(`/whoami`)",
"traefik.http.routers.router1.service=service1",
"traefik.http.services.service1.loadBalancer.server.url=http://" + containerIP,
},
Port: 80,
Address: containerIP,
}
err := s.registerService(reg, false)
c.Assert(err, checker.IsNil)
tempObjects := struct {
@@ -172,7 +191,14 @@ func (s *ConsulCatalogSuite) TestSimpleConfiguration(c *check.C) {
file := s.adaptFile(c, "fixtures/consul_catalog/simple.toml", tempObjects)
defer os.Remove(file)
err := s.registerService("whoami1", "whoami", s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress, "80", []string{"traefik.enable=true"}, false)
reg := &api.AgentServiceRegistration{
ID: "whoami1",
Name: "whoami",
Tags: []string{"traefik.enable=true"},
Port: 80,
Address: s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress,
}
err := s.registerService(reg, false)
c.Assert(err, checker.IsNil)
cmd, display := s.traefikCmd(withConfigFile(file))
@@ -204,7 +230,14 @@ func (s *ConsulCatalogSuite) TestRegisterServiceWithoutIP(c *check.C) {
file := s.adaptFile(c, "fixtures/consul_catalog/simple.toml", tempObjects)
defer os.Remove(file)
err := s.registerService("whoami1", "whoami", "", "80", []string{"traefik.enable=true"}, false)
reg := &api.AgentServiceRegistration{
ID: "whoami1",
Name: "whoami",
Tags: []string{"traefik.enable=true"},
Port: 80,
Address: "",
}
err := s.registerService(reg, false)
c.Assert(err, checker.IsNil)
cmd, display := s.traefikCmd(withConfigFile(file))
@@ -236,7 +269,13 @@ func (s *ConsulCatalogSuite) TestDefaultConsulService(c *check.C) {
file := s.adaptFile(c, "fixtures/consul_catalog/simple.toml", tempObjects)
defer os.Remove(file)
err := s.registerService("whoami1", "whoami", s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress, "80", nil, false)
reg := &api.AgentServiceRegistration{
ID: "whoami1",
Name: "whoami",
Port: 80,
Address: s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress,
}
err := s.registerService(reg, false)
c.Assert(err, checker.IsNil)
// Start traefik
@@ -269,14 +308,20 @@ func (s *ConsulCatalogSuite) TestConsulServiceWithTCPLabels(c *check.C) {
file := s.adaptFile(c, "fixtures/consul_catalog/simple.toml", tempObjects)
defer os.Remove(file)
// Start a container with some labels
labels := []string{
"traefik.tcp.Routers.Super.Rule=HostSNI(`my.super.host`)",
"traefik.tcp.Routers.Super.tls=true",
"traefik.tcp.Services.Super.Loadbalancer.server.port=8080",
// Start a container with some tags
reg := &api.AgentServiceRegistration{
ID: "whoamitcp",
Name: "whoamitcp",
Tags: []string{
"traefik.tcp.Routers.Super.Rule=HostSNI(`my.super.host`)",
"traefik.tcp.Routers.Super.tls=true",
"traefik.tcp.Services.Super.Loadbalancer.server.port=8080",
},
Port: 8080,
Address: s.composeProject.Container(c, "whoamitcp").NetworkSettings.IPAddress,
}
err := s.registerService("whoamitcp", "whoamitcp", s.composeProject.Container(c, "whoamitcp").NetworkSettings.IPAddress, "8080", labels, false)
err := s.registerService(reg, false)
c.Assert(err, checker.IsNil)
// Start traefik
@@ -310,18 +355,31 @@ func (s *ConsulCatalogSuite) TestConsulServiceWithLabels(c *check.C) {
file := s.adaptFile(c, "fixtures/consul_catalog/simple.toml", tempObjects)
defer os.Remove(file)
// Start a container with some labels
labels := []string{
"traefik.http.Routers.Super.Rule=Host(`my.super.host`)",
// Start a container with some tags
reg1 := &api.AgentServiceRegistration{
ID: "whoami1",
Name: "whoami",
Tags: []string{
"traefik.http.Routers.Super.Rule=Host(`my.super.host`)",
},
Port: 80,
Address: s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress,
}
err := s.registerService("whoami1", "whoami", s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress, "80", labels, false)
err := s.registerService(reg1, false)
c.Assert(err, checker.IsNil)
// Start another container by replacing a '.' by a '-'
labels = []string{
"traefik.http.Routers.SuperHost.Rule=Host(`my-super.host`)",
reg2 := &api.AgentServiceRegistration{
ID: "whoami2",
Name: "whoami",
Tags: []string{
"traefik.http.Routers.SuperHost.Rule=Host(`my-super.host`)",
},
Port: 80,
Address: s.composeProject.Container(c, "whoami2").NetworkSettings.IPAddress,
}
err = s.registerService("whoami2", "whoami", s.composeProject.Container(c, "whoami2").NetworkSettings.IPAddress, "80", labels, false)
err = s.registerService(reg2, false)
c.Assert(err, checker.IsNil)
// Start traefik
@@ -364,16 +422,31 @@ func (s *ConsulCatalogSuite) TestSameServiceIDOnDifferentConsulAgent(c *check.C)
file := s.adaptFile(c, "fixtures/consul_catalog/default_not_exposed.toml", tempObjects)
defer os.Remove(file)
// Start a container with some labels
labels := []string{
// Start a container with some tags
tags := []string{
"traefik.enable=true",
"traefik.http.Routers.Super.service=whoami",
"traefik.http.Routers.Super.Rule=Host(`my.super.host`)",
}
err := s.registerService("whoami", "whoami", s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress, "80", labels, false)
reg1 := &api.AgentServiceRegistration{
ID: "whoami",
Name: "whoami",
Tags: tags,
Port: 80,
Address: s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress,
}
err := s.registerService(reg1, false)
c.Assert(err, checker.IsNil)
err = s.registerService("whoami", "whoami", s.composeProject.Container(c, "whoami2").NetworkSettings.IPAddress, "80", labels, true)
reg2 := &api.AgentServiceRegistration{
ID: "whoami",
Name: "whoami",
Tags: tags,
Port: 80,
Address: s.composeProject.Container(c, "whoami2").NetworkSettings.IPAddress,
}
err = s.registerService(reg2, true)
c.Assert(err, checker.IsNil)
// Start traefik
@@ -417,11 +490,18 @@ func (s *ConsulCatalogSuite) TestConsulServiceWithOneMissingLabels(c *check.C) {
file := s.adaptFile(c, "fixtures/consul_catalog/simple.toml", tempObjects)
defer os.Remove(file)
// Start a container with some labels
labels := []string{
"traefik.random.value=my.super.host",
// Start a container with some tags
reg := &api.AgentServiceRegistration{
ID: "whoami1",
Name: "whoami",
Tags: []string{
"traefik.random.value=my.super.host",
},
Port: 80,
Address: s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress,
}
err := s.registerService("whoami1", "whoami", s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress, "80", labels, false)
err := s.registerService(reg, false)
c.Assert(err, checker.IsNil)
// Start traefik
@@ -441,3 +521,82 @@ func (s *ConsulCatalogSuite) TestConsulServiceWithOneMissingLabels(c *check.C) {
err = try.Request(req, 1500*time.Millisecond, try.StatusCodeIs(http.StatusNotFound))
c.Assert(err, checker.IsNil)
}
func (s *ConsulCatalogSuite) TestConsulServiceWithHealthCheck(c *check.C) {
tags := []string{
"traefik.enable=true",
"traefik.http.routers.router1.rule=Path(`/whoami`)",
"traefik.http.routers.router1.service=service1",
"traefik.http.services.service1.loadBalancer.server.url=http://" + s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress,
}
reg1 := &api.AgentServiceRegistration{
ID: "whoami1",
Name: "whoami",
Tags: tags,
Port: 80,
Address: s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress,
Check: &api.AgentServiceCheck{
CheckID: "some-failed-check",
TCP: "127.0.0.1:1234",
Name: "some-failed-check",
Interval: "1s",
Timeout: "1s",
},
}
err := s.registerService(reg1, false)
c.Assert(err, checker.IsNil)
tempObjects := struct {
ConsulAddress string
}{
ConsulAddress: s.consulAddress,
}
file := s.adaptFile(c, "fixtures/consul_catalog/simple.toml", tempObjects)
defer os.Remove(file)
cmd, display := s.traefikCmd(withConfigFile(file))
defer display(c)
err = cmd.Start()
c.Assert(err, checker.IsNil)
defer cmd.Process.Kill()
err = try.GetRequest("http://127.0.0.1:8000/whoami", 2*time.Second, try.StatusCodeIs(http.StatusNotFound))
c.Assert(err, checker.IsNil)
err = s.deregisterService("whoami1", false)
c.Assert(err, checker.IsNil)
containerIP := s.composeProject.Container(c, "whoami2").NetworkSettings.IPAddress
reg2 := &api.AgentServiceRegistration{
ID: "whoami2",
Name: "whoami",
Tags: tags,
Port: 80,
Address: containerIP,
Check: &api.AgentServiceCheck{
CheckID: "some-ok-check",
TCP: containerIP + ":80",
Name: "some-ok-check",
Interval: "1s",
Timeout: "1s",
},
}
err = s.registerService(reg2, false)
c.Assert(err, checker.IsNil)
req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil)
c.Assert(err, checker.IsNil)
req.Host = "whoami"
// FIXME Need to wait for up to 10 seconds (for consul discovery or traefik to boot up ?)
err = try.Request(req, 10*time.Second, try.StatusCodeIs(200), try.BodyContainsOr("Hostname: whoami2"))
c.Assert(err, checker.IsNil)
err = s.deregisterService("whoami2", false)
c.Assert(err, checker.IsNil)
}

View File

@@ -60,7 +60,7 @@
"middlewares": {
"dashboard_redirect@internal": {
"redirectRegex": {
"regex": "^(http:\\/\\/[^:]+(:\\d+)?)/$",
"regex": "^(http:\\/\\/[^:\\/]+(:\\d+)?)\\/$",
"replacement": "${1}/dashboard/",
"permanent": true
},

View File

@@ -13,8 +13,7 @@ import (
)
// decodeFileToNode decodes the configuration in filePath in a tree of untyped nodes.
// If filters is not empty, it skips any configuration element whose name is
// not among filters.
// If filters is not empty, it skips any configuration element whose name is not among filters.
func decodeFileToNode(filePath string, filters ...string) (*parser.Node, error) {
content, err := ioutil.ReadFile(filePath)
if err != nil {
@@ -40,7 +39,20 @@ func decodeFileToNode(filePath string, filters ...string) (*parser.Node, error)
return nil, fmt.Errorf("unsupported file extension: %s", filePath)
}
return decodeRawToNode(data, parser.DefaultRootName, filters...)
if len(data) == 0 {
return nil, fmt.Errorf("no configuration found in file: %s", filePath)
}
node, err := decodeRawToNode(data, parser.DefaultRootName, filters...)
if err != nil {
return nil, err
}
if len(node.Children) == 0 {
return nil, fmt.Errorf("no valid configuration found in file: %s", filePath)
}
return node, nil
}
func getRootFieldNames(element interface{}) []string {

View File

@@ -5,6 +5,7 @@ import (
"github.com/containous/traefik/v2/pkg/config/parser"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_getRootFieldNames(t *testing.T) {
@@ -42,17 +43,43 @@ func Test_getRootFieldNames(t *testing.T) {
}
}
func Test_decodeFileToNode_errors(t *testing.T) {
testCases := []struct {
desc string
confFile string
}{
{
desc: "non existing file",
confFile: "./fixtures/not_existing.toml",
},
{
desc: "file without content",
confFile: "./fixtures/empty.toml",
},
{
desc: "file without any valid configuration",
confFile: "./fixtures/no_conf.toml",
},
}
for _, test := range testCases {
t.Run(test.desc, func(t *testing.T) {
node, err := decodeFileToNode(test.confFile,
"Global", "ServersTransport", "EntryPoints", "Providers", "API", "Metrics", "Ping", "Log", "AccessLog", "Tracing", "HostResolver", "CertificatesResolvers")
require.Error(t, err)
assert.Nil(t, node)
})
}
}
func Test_decodeFileToNode_compare(t *testing.T) {
nodeToml, err := decodeFileToNode("./fixtures/sample.toml",
"Global", "ServersTransport", "EntryPoints", "Providers", "API", "Metrics", "Ping", "Log", "AccessLog", "Tracing", "HostResolver", "CertificatesResolvers")
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
nodeYaml, err := decodeFileToNode("./fixtures/sample.yml")
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
assert.Equal(t, nodeToml, nodeYaml)
}
@@ -60,9 +87,7 @@ func Test_decodeFileToNode_compare(t *testing.T) {
func Test_decodeFileToNode_Toml(t *testing.T) {
node, err := decodeFileToNode("./fixtures/sample.toml",
"Global", "ServersTransport", "EntryPoints", "Providers", "API", "Metrics", "Ping", "Log", "AccessLog", "Tracing", "HostResolver", "CertificatesResolvers")
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
expected := &parser.Node{
Name: "traefik",
@@ -294,9 +319,7 @@ func Test_decodeFileToNode_Toml(t *testing.T) {
func Test_decodeFileToNode_Yaml(t *testing.T) {
node, err := decodeFileToNode("./fixtures/sample.yml")
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
expected := &parser.Node{
Name: "traefik",

View File

View File

@@ -0,0 +1,2 @@
[foo]
bar = "test"

View File

@@ -21,6 +21,10 @@ func DecodeToNode(labels map[string]string, rootName string, filters ...string)
var parts []string
for _, v := range split {
if v == "" {
return nil, fmt.Errorf("invalid element: %s", key)
}
if v[0] == '[' {
return nil, fmt.Errorf("invalid leading character '[' in field name (bracket is a slice delimiter): %s", v)
}

View File

@@ -26,6 +26,15 @@ func TestDecodeToNode(t *testing.T) {
in: map[string]string{},
expected: expected{node: nil},
},
{
desc: "invalid label, ending by a dot",
in: map[string]string{
"traefik.http.": "bar",
},
expected: expected{
error: true,
},
},
{
desc: "level 1",
in: map[string]string{

View File

@@ -10,9 +10,23 @@ import (
)
var (
_ middlewares.Stateful = &captureResponseWriter{}
_ middlewares.Stateful = &captureResponseWriterWithCloseNotify{}
)
type capturer interface {
http.ResponseWriter
Size() int64
Status() int
}
func newCaptureResponseWriter(rw http.ResponseWriter) capturer {
capt := &captureResponseWriter{rw: rw}
if _, ok := rw.(http.CloseNotifier); !ok {
return capt
}
return &captureResponseWriterWithCloseNotify{capt}
}
// captureResponseWriter is a wrapper of type http.ResponseWriter
// that tracks request status and size
type captureResponseWriter struct {
@@ -21,6 +35,16 @@ type captureResponseWriter struct {
size int64
}
type captureResponseWriterWithCloseNotify struct {
*captureResponseWriter
}
// CloseNotify returns a channel that receives at most a
// single value (true) when the client connection has gone away.
func (r *captureResponseWriterWithCloseNotify) CloseNotify() <-chan bool {
return r.rw.(http.CloseNotifier).CloseNotify()
}
func (crw *captureResponseWriter) Header() http.Header {
return crw.rw.Header()
}
@@ -52,13 +76,6 @@ func (crw *captureResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
return nil, nil, fmt.Errorf("not a hijacker: %T", crw.rw)
}
func (crw *captureResponseWriter) CloseNotify() <-chan bool {
if c, ok := crw.rw.(http.CloseNotifier); ok {
return c.CloseNotify()
}
return nil
}
func (crw *captureResponseWriter) Status() int {
return crw.status
}

View File

@@ -0,0 +1,50 @@
package accesslog
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
type rwWithCloseNotify struct {
*httptest.ResponseRecorder
}
func (r *rwWithCloseNotify) CloseNotify() <-chan bool {
panic("implement me")
}
func TestCloseNotifier(t *testing.T) {
testCases := []struct {
rw http.ResponseWriter
desc string
implementsCloseNotifier bool
}{
{
rw: httptest.NewRecorder(),
desc: "does not implement CloseNotifier",
implementsCloseNotifier: false,
},
{
rw: &rwWithCloseNotify{httptest.NewRecorder()},
desc: "implements CloseNotifier",
implementsCloseNotifier: true,
},
}
for _, test := range testCases {
test := test
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
_, ok := test.rw.(http.CloseNotifier)
assert.Equal(t, test.implementsCloseNotifier, ok)
rw := newCaptureResponseWriter(test.rw)
_, impl := rw.(http.CloseNotifier)
assert.Equal(t, test.implementsCloseNotifier, impl)
})
}
}

View File

@@ -49,7 +49,7 @@ func AddServiceFields(rw http.ResponseWriter, req *http.Request, next http.Handl
// AddOriginFields add origin fields
func AddOriginFields(rw http.ResponseWriter, req *http.Request, next http.Handler, data *LogData) {
crw := &captureResponseWriter{rw: rw}
crw := newCaptureResponseWriter(rw)
start := time.Now().UTC()
next.ServeHTTP(crw, req)

View File

@@ -200,7 +200,7 @@ func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request, next http
core[ClientHost] = forwardedFor
}
crw := &captureResponseWriter{rw: rw}
crw := newCaptureResponseWriter(rw)
next.ServeHTTP(crw, reqWithDataTable)

View File

@@ -88,9 +88,11 @@ func (fa *forwardAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
return
}
writeHeader(req, forwardReq, fa.trustForwardHeader)
// Ensure tracing headers are in the request before we copy the headers to the
// forwardReq.
tracing.InjectRequestHeaders(req)
tracing.InjectRequestHeaders(forwardReq)
writeHeader(req, forwardReq, fa.trustForwardHeader)
forwardResponse, forwardErr := httpClient.Do(forwardReq)
if forwardErr != nil {

View File

@@ -3,13 +3,18 @@ package auth
import (
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/containous/traefik/v2/pkg/config/dynamic"
tracingMiddleware "github.com/containous/traefik/v2/pkg/middlewares/tracing"
"github.com/containous/traefik/v2/pkg/testhelpers"
"github.com/containous/traefik/v2/pkg/tracing"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/mocktracer"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/vulcand/oxy/forward"
@@ -394,3 +399,44 @@ func Test_writeHeader(t *testing.T) {
})
}
}
func TestForwardAuthUsesTracing(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Mockpfx-Ids-Traceid") == "" {
t.Errorf("expected Mockpfx-Ids-Traceid header to be present in request")
}
}))
defer server.Close()
next := http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
auth := dynamic.ForwardAuth{
Address: server.URL,
}
tracer := mocktracer.New()
opentracing.SetGlobalTracer(tracer)
tr, _ := tracing.NewTracing("testApp", 100, &mockBackend{tracer})
next, err := NewForward(context.Background(), next, auth, "authTest")
require.NoError(t, err)
next = tracingMiddleware.NewEntryPoint(context.Background(), tr, "tracingTest", next)
ts := httptest.NewServer(next)
defer ts.Close()
req := testhelpers.MustNewRequest(http.MethodGet, ts.URL, nil)
res, err := http.DefaultClient.Do(req)
require.NoError(t, err)
assert.Equal(t, http.StatusOK, res.StatusCode)
}
type mockBackend struct {
opentracing.Tracer
}
func (b *mockBackend) Setup(componentName string) (opentracing.Tracer, io.Closer, error) {
return b.Tracer, ioutil.NopCloser(nil), nil
}

View File

@@ -89,10 +89,10 @@ func (m *metricsMiddleware) ServeHTTP(rw http.ResponseWriter, req *http.Request)
}(labels)
start := time.Now()
recorder := &responseRecorder{rw, http.StatusOK}
recorder := newResponseRecorder(rw)
m.next.ServeHTTP(recorder, req)
labels = append(labels, "code", strconv.Itoa(recorder.statusCode))
labels = append(labels, "code", strconv.Itoa(recorder.getCode()))
m.reqsCounter.With(labels...).Add(1)
m.reqDurationHistogram.With(labels...).Observe(time.Since(start).Seconds())
}

View File

@@ -7,6 +7,7 @@ import (
"testing"
"github.com/go-kit/kit/metrics"
"github.com/stretchr/testify/assert"
)
// CollectingCounter is a metrics.Counter implementation that enables access to the CounterValue and LastLabelValues.
@@ -56,3 +57,44 @@ func newCollectingRetryMetrics() *collectingRetryMetrics {
func (m *collectingRetryMetrics) ServiceRetriesCounter() metrics.Counter {
return m.retriesCounter
}
type rwWithCloseNotify struct {
*httptest.ResponseRecorder
}
func (r *rwWithCloseNotify) CloseNotify() <-chan bool {
panic("implement me")
}
func TestCloseNotifier(t *testing.T) {
testCases := []struct {
rw http.ResponseWriter
desc string
implementsCloseNotifier bool
}{
{
rw: httptest.NewRecorder(),
desc: "does not implement CloseNotifier",
implementsCloseNotifier: false,
},
{
rw: &rwWithCloseNotify{httptest.NewRecorder()},
desc: "implements CloseNotifier",
implementsCloseNotifier: true,
},
}
for _, test := range testCases {
test := test
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
_, ok := test.rw.(http.CloseNotifier)
assert.Equal(t, test.implementsCloseNotifier, ok)
rw := newResponseRecorder(test.rw)
_, impl := rw.(http.CloseNotifier)
assert.Equal(t, test.implementsCloseNotifier, impl)
})
}
}

View File

@@ -6,6 +6,23 @@ import (
"net/http"
)
type recorder interface {
http.ResponseWriter
http.Flusher
getCode() int
}
func newResponseRecorder(rw http.ResponseWriter) recorder {
rec := &responseRecorder{
ResponseWriter: rw,
statusCode: http.StatusOK,
}
if _, ok := rw.(http.CloseNotifier); !ok {
return rec
}
return &responseRecorderWithCloseNotify{rec}
}
// responseRecorder captures information from the response and preserves it for
// later analysis.
type responseRecorder struct {
@@ -13,6 +30,20 @@ type responseRecorder struct {
statusCode int
}
type responseRecorderWithCloseNotify struct {
*responseRecorder
}
// CloseNotify returns a channel that receives at most a
// single value (true) when the client connection has gone away.
func (r *responseRecorderWithCloseNotify) CloseNotify() <-chan bool {
return r.ResponseWriter.(http.CloseNotifier).CloseNotify()
}
func (r *responseRecorder) getCode() int {
return r.statusCode
}
// WriteHeader captures the status code for later retrieval.
func (r *responseRecorder) WriteHeader(status int) {
r.ResponseWriter.WriteHeader(status)
@@ -24,13 +55,6 @@ func (r *responseRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return r.ResponseWriter.(http.Hijacker).Hijack()
}
// CloseNotify returns a channel that receives at most a
// single value (true) when the client connection has gone
// away.
func (r *responseRecorder) CloseNotify() <-chan bool {
return r.ResponseWriter.(http.CloseNotifier).CloseNotify()
}
// Flush sends any buffered data to the client.
func (r *responseRecorder) Flush() {
if f, ok := r.ResponseWriter.(http.Flusher); ok {

View File

@@ -18,10 +18,17 @@ import (
"github.com/opentracing/opentracing-go/ext"
)
const typeName = "PassClientTLSCert"
const (
xForwardedTLSClientCert = "X-Forwarded-Tls-Client-Cert"
xForwardedTLSClientCertInfo = "X-Forwarded-Tls-Client-Cert-Info"
typeName = "PassClientTLSCert"
)
const (
certSeparator = ","
fieldSeparator = ";"
subFieldSeparator = ","
)
var attributeTypeNames = map[string]string{
@@ -55,6 +62,29 @@ func newDistinguishedNameOptions(info *dynamic.TLSCLientCertificateDNInfo) *Dist
}
}
// tlsClientCertificateInfo is a struct for specifying the configuration for the passTLSClientCert middleware.
type tlsClientCertificateInfo struct {
notAfter bool
notBefore bool
sans bool
subject *DistinguishedNameOptions
issuer *DistinguishedNameOptions
}
func newTLSClientCertificateInfo(info *dynamic.TLSClientCertificateInfo) *tlsClientCertificateInfo {
if info == nil {
return nil
}
return &tlsClientCertificateInfo{
issuer: newDistinguishedNameOptions(info.Issuer),
notAfter: info.NotAfter,
notBefore: info.NotBefore,
subject: newDistinguishedNameOptions(info.Subject),
sans: info.Sans,
}
}
// passTLSClientCert is a middleware that helps setup a few tls info features.
type passTLSClientCert struct {
next http.Handler
@@ -71,45 +101,84 @@ func New(ctx context.Context, next http.Handler, config dynamic.PassTLSClientCer
next: next,
name: name,
pem: config.PEM,
info: newTLSClientInfo(config.Info),
info: newTLSClientCertificateInfo(config.Info),
}, nil
}
// tlsClientCertificateInfo is a struct for specifying the configuration for the passTLSClientCert middleware.
type tlsClientCertificateInfo struct {
notAfter bool
notBefore bool
sans bool
subject *DistinguishedNameOptions
issuer *DistinguishedNameOptions
}
func newTLSClientInfo(info *dynamic.TLSClientCertificateInfo) *tlsClientCertificateInfo {
if info == nil {
return nil
}
return &tlsClientCertificateInfo{
issuer: newDistinguishedNameOptions(info.Issuer),
notAfter: info.NotAfter,
notBefore: info.NotBefore,
subject: newDistinguishedNameOptions(info.Subject),
sans: info.Sans,
}
}
func (p *passTLSClientCert) GetTracingInformation() (string, ext.SpanKindEnum) {
return p.name, tracing.SpanKindNoneEnum
}
func (p *passTLSClientCert) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
ctx := middlewares.GetLoggerCtx(req.Context(), p.name, typeName)
logger := log.FromContext(ctx)
if p.pem {
if req.TLS != nil && len(req.TLS.PeerCertificates) > 0 {
req.Header.Set(xForwardedTLSClientCert, getCertificates(ctx, req.TLS.PeerCertificates))
} else {
logger.Warn("Tried to extract a certificate on a request without mutual TLS")
}
}
if p.info != nil {
if req.TLS != nil && len(req.TLS.PeerCertificates) > 0 {
headerContent := p.getCertInfo(ctx, req.TLS.PeerCertificates)
req.Header.Set(xForwardedTLSClientCertInfo, url.QueryEscape(headerContent))
} else {
logger.Warn("Tried to extract a certificate on a request without mutual TLS")
}
}
p.modifyRequestHeaders(ctx, req)
p.next.ServeHTTP(rw, req)
}
func getDNInfo(ctx context.Context, prefix string, options *DistinguishedNameOptions, cs *pkix.Name) string {
// getCertInfo Build a string with the wanted client certificates information
// - the `,` is used to separate certificates
// - the `;` is used to separate root fields
// - the value of root fields is always wrapped by double quote
// - if a field is empty, the field is ignored
func (p *passTLSClientCert) getCertInfo(ctx context.Context, certs []*x509.Certificate) string {
var headerValues []string
for _, peerCert := range certs {
var values []string
if p.info != nil {
subject := getDNInfo(ctx, p.info.subject, &peerCert.Subject)
if subject != "" {
values = append(values, fmt.Sprintf(`Subject="%s"`, strings.TrimSuffix(subject, subFieldSeparator)))
}
issuer := getDNInfo(ctx, p.info.issuer, &peerCert.Issuer)
if issuer != "" {
values = append(values, fmt.Sprintf(`Issuer="%s"`, strings.TrimSuffix(issuer, subFieldSeparator)))
}
if p.info.notBefore {
values = append(values, fmt.Sprintf(`NB="%d"`, uint64(peerCert.NotBefore.Unix())))
}
if p.info.notAfter {
values = append(values, fmt.Sprintf(`NA="%d"`, uint64(peerCert.NotAfter.Unix())))
}
if p.info.sans {
sans := getSANs(peerCert)
if len(sans) > 0 {
values = append(values, fmt.Sprintf(`SAN="%s"`, strings.Join(sans, subFieldSeparator)))
}
}
}
value := strings.Join(values, fieldSeparator)
headerValues = append(headerValues, value)
}
return strings.Join(headerValues, certSeparator)
}
func getDNInfo(ctx context.Context, options *DistinguishedNameOptions, cs *pkix.Name) string {
if options == nil {
return ""
}
@@ -120,7 +189,7 @@ func getDNInfo(ctx context.Context, prefix string, options *DistinguishedNameOpt
for _, name := range cs.Names {
// Domain Component - RFC 2247
if options.DomainComponent && attributeTypeNames[name.Type.String()] == "DC" {
content.WriteString(fmt.Sprintf("DC=%s,", name.Value))
content.WriteString(fmt.Sprintf("DC=%s%s", name.Value, subFieldSeparator))
}
}
@@ -148,11 +217,7 @@ func getDNInfo(ctx context.Context, prefix string, options *DistinguishedNameOpt
writePart(ctx, content, cs.CommonName, "CN")
}
if content.Len() > 0 {
return prefix + `="` + strings.TrimSuffix(content.String(), ",") + `"`
}
return ""
return content.String()
}
func writeParts(ctx context.Context, content io.StringWriter, entries []string, prefix string) {
@@ -163,135 +228,63 @@ func writeParts(ctx context.Context, content io.StringWriter, entries []string,
func writePart(ctx context.Context, content io.StringWriter, entry string, prefix string) {
if len(entry) > 0 {
_, err := content.WriteString(fmt.Sprintf("%s=%s,", prefix, entry))
_, err := content.WriteString(fmt.Sprintf("%s=%s%s", prefix, entry, subFieldSeparator))
if err != nil {
log.FromContext(ctx).Error(err)
}
}
}
// getXForwardedTLSClientCertInfo Build a string with the wanted client certificates information
// like Subject="C=%s,ST=%s,L=%s,O=%s,CN=%s",NB=%d,NA=%d,SAN=%s;
func (p *passTLSClientCert) getXForwardedTLSClientCertInfo(ctx context.Context, certs []*x509.Certificate) string {
var headerValues []string
for _, peerCert := range certs {
var values []string
var sans string
var nb string
var na string
if p.info != nil {
subject := getDNInfo(ctx, "Subject", p.info.subject, &peerCert.Subject)
if len(subject) > 0 {
values = append(values, subject)
}
issuer := getDNInfo(ctx, "Issuer", p.info.issuer, &peerCert.Issuer)
if len(issuer) > 0 {
values = append(values, issuer)
}
}
ci := p.info
if ci != nil {
if ci.notBefore {
nb = fmt.Sprintf("NB=%d", uint64(peerCert.NotBefore.Unix()))
values = append(values, nb)
}
if ci.notAfter {
na = fmt.Sprintf("NA=%d", uint64(peerCert.NotAfter.Unix()))
values = append(values, na)
}
if ci.sans {
sans = fmt.Sprintf("SAN=%s", strings.Join(getSANs(peerCert), ","))
values = append(values, sans)
}
}
value := strings.Join(values, ",")
headerValues = append(headerValues, value)
}
return strings.Join(headerValues, ";")
}
// modifyRequestHeaders set the wanted headers with the certificates information.
func (p *passTLSClientCert) modifyRequestHeaders(ctx context.Context, r *http.Request) {
logger := log.FromContext(ctx)
if p.pem {
if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
r.Header.Set(xForwardedTLSClientCert, getXForwardedTLSClientCert(ctx, r.TLS.PeerCertificates))
} else {
logger.Warn("Tried to extract a certificate on a request without mutual TLS")
}
}
if p.info != nil {
if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
headerContent := p.getXForwardedTLSClientCertInfo(ctx, r.TLS.PeerCertificates)
r.Header.Set(xForwardedTLSClientCertInfo, url.QueryEscape(headerContent))
} else {
logger.Warn("Tried to extract a certificate on a request without mutual TLS")
}
}
}
// sanitize As we pass the raw certificates, remove the useless data and make it http request compliant.
func sanitize(cert []byte) string {
s := string(cert)
r := strings.NewReplacer("-----BEGIN CERTIFICATE-----", "",
cleaned := strings.NewReplacer(
"-----BEGIN CERTIFICATE-----", "",
"-----END CERTIFICATE-----", "",
"\n", "")
cleaned := r.Replace(s)
"\n", "",
).Replace(string(cert))
return url.QueryEscape(cleaned)
}
// extractCertificate extract the certificate from the request.
func extractCertificate(ctx context.Context, cert *x509.Certificate) string {
b := pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}
certPEM := pem.EncodeToMemory(&b)
if certPEM == nil {
log.FromContext(ctx).Error("Cannot extract the certificate content")
return ""
}
return sanitize(certPEM)
}
// getXForwardedTLSClientCert Build a string with the client certificates.
func getXForwardedTLSClientCert(ctx context.Context, certs []*x509.Certificate) string {
// getCertificates Build a string with the client certificates.
func getCertificates(ctx context.Context, certs []*x509.Certificate) string {
var headerValues []string
for _, peerCert := range certs {
headerValues = append(headerValues, extractCertificate(ctx, peerCert))
}
return strings.Join(headerValues, ",")
return strings.Join(headerValues, certSeparator)
}
// extractCertificate extract the certificate from the request.
func extractCertificate(ctx context.Context, cert *x509.Certificate) string {
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
if certPEM == nil {
log.FromContext(ctx).Error("Cannot extract the certificate content")
return ""
}
return sanitize(certPEM)
}
// getSANs get the Subject Alternate Name values.
func getSANs(cert *x509.Certificate) []string {
var sans []string
if cert == nil {
return sans
return nil
}
var sans []string
sans = append(sans, cert.DNSNames...)
sans = append(sans, cert.EmailAddresses...)
var ips []string
for _, ip := range cert.IPAddresses {
ips = append(ips, ip.String())
sans = append(sans, ip.String())
}
sans = append(sans, ips...)
var uris []string
for _, uri := range cert.URIs {
uris = append(uris, uri.String())
sans = append(sans, uri.String())
}
return append(sans, uris...)
return sans
}

View File

@@ -15,6 +15,7 @@ import (
"github.com/containous/traefik/v2/pkg/config/dynamic"
"github.com/containous/traefik/v2/pkg/testhelpers"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -113,6 +114,7 @@ Cg+XKmHzexmTnKaKac2w9ZECpRsQ9IBdQq9OghIwPtOnERTOUJEEgNcqA+9xELjb
pQ==
-----END CERTIFICATE-----
`
minimalCheeseCrt = `-----BEGIN CERTIFICATE-----
MIIEQDCCAygCFFRY0OBk/L5Se0IZRj3CMljawL2UMA0GCSqGSIb3DQEBCwUAMIIB
hDETMBEGCgmSJomT8ixkARkWA29yZzEWMBQGCgmSJomT8ixkARkWBmNoZWVzZTEP
@@ -262,47 +264,6 @@ jECvgAY7Nfd9mZ1KtyNaW31is+kag7NsvjxU/kM=
-----END CERTIFICATE-----`
)
func getCleanCertContents(certContents []string) string {
var re = regexp.MustCompile("-----BEGIN CERTIFICATE-----(?s)(.*)")
var cleanedCertContent []string
for _, certContent := range certContents {
cert := re.FindString(certContent)
cleanedCertContent = append(cleanedCertContent, sanitize([]byte(cert)))
}
return strings.Join(cleanedCertContent, ",")
}
func getCertificate(certContent string) *x509.Certificate {
roots := x509.NewCertPool()
ok := roots.AppendCertsFromPEM([]byte(signingCA))
if !ok {
panic("failed to parse root certificate")
}
block, _ := pem.Decode([]byte(certContent))
if block == nil {
panic("failed to parse certificate PEM")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
panic("failed to parse certificate: " + err.Error())
}
return cert
}
func buildTLSWith(certContents []string) *tls.ConnectionState {
var peerCertificates []*x509.Certificate
for _, certContent := range certContents {
peerCertificates = append(peerCertificates, getCertificate(certContent))
}
return &tls.ConnectionState{PeerCertificates: peerCertificates}
}
var next = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte("bar"))
if err != nil {
@@ -310,59 +271,7 @@ var next = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
}
})
func getExpectedSanitized(s string) string {
return url.QueryEscape(strings.Replace(s, "\n", "", -1))
}
func TestSanitize(t *testing.T) {
testCases := []struct {
desc string
toSanitize []byte
expected string
}{
{
desc: "Empty",
},
{
desc: "With a minimal cert",
toSanitize: []byte(minimalCheeseCrt),
expected: getExpectedSanitized(`MIIEQDCCAygCFFRY0OBk/L5Se0IZRj3CMljawL2UMA0GCSqGSIb3DQEBCwUAMIIB
hDETMBEGCgmSJomT8ixkARkWA29yZzEWMBQGCgmSJomT8ixkARkWBmNoZWVzZTEP
MA0GA1UECgwGQ2hlZXNlMREwDwYDVQQKDAhDaGVlc2UgMjEfMB0GA1UECwwWU2lt
cGxlIFNpZ25pbmcgU2VjdGlvbjEhMB8GA1UECwwYU2ltcGxlIFNpZ25pbmcgU2Vj
dGlvbiAyMRowGAYDVQQDDBFTaW1wbGUgU2lnbmluZyBDQTEcMBoGA1UEAwwTU2lt
cGxlIFNpZ25pbmcgQ0EgMjELMAkGA1UEBhMCRlIxCzAJBgNVBAYTAlVTMREwDwYD
VQQHDAhUT1VMT1VTRTENMAsGA1UEBwwETFlPTjEWMBQGA1UECAwNU2lnbmluZyBT
dGF0ZTEYMBYGA1UECAwPU2lnbmluZyBTdGF0ZSAyMSEwHwYJKoZIhvcNAQkBFhJz
aW1wbGVAc2lnbmluZy5jb20xIjAgBgkqhkiG9w0BCQEWE3NpbXBsZTJAc2lnbmlu
Zy5jb20wHhcNMTgxMjA2MTExMDM2WhcNMjEwOTI1MTExMDM2WjAzMQswCQYDVQQG
EwJGUjETMBEGA1UECAwKU29tZS1TdGF0ZTEPMA0GA1UECgwGQ2hlZXNlMIIBIjAN
BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAskX/bUtwFo1gF2BTPNaNcTUMaRFu
FMZozK8IgLjccZ4kZ0R9oFO6Yp8Zl/IvPaf7tE26PI7XP7eHriUdhnQzX7iioDd0
RZa68waIhAGc+xPzRFrP3b3yj3S2a9Rve3c0K+SCV+EtKAwsxMqQDhoo9PcBfo5B
RHfht07uD5MncUcGirwN+/pxHV5xzAGPcc7On0/5L7bq/G+63nhu78zw9XyuLaHC
PM5VbOUvpyIESJHbMMzTdFGL8ob9VKO+Kr1kVGdEA9i8FLGl3xz/GBKuW/JD0xyW
DrU29mri5vYWHmkuv7ZWHGXnpXjTtPHwveE9/0/ArnmpMyR9JtqFr1oEvQIDAQAB
MA0GCSqGSIb3DQEBCwUAA4IBAQBHta+NWXI08UHeOkGzOTGRiWXsOH2dqdX6gTe9
xF1AIjyoQ0gvpoGVvlnChSzmlUj+vnx/nOYGIt1poE3hZA3ZHZD/awsvGyp3GwWD
IfXrEViSCIyF+8tNNKYyUcEO3xdAsAUGgfUwwF/mZ6MBV5+A/ZEEILlTq8zFt9dV
vdKzIt7fZYxYBBHFSarl1x8pDgWXlf3hAufevGJXip9xGYmznF0T5cq1RbWJ4be3
/9K7yuWhuBYC3sbTbCneHBa91M82za+PIISc1ygCYtWSBoZKSAqLk0rkZpHaekDP
WqeUSNGYV//RunTeuRDAf5OxehERb1srzBXhRZ3cZdzXbgR/`),
},
}
for _, test := range testCases {
test := test
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
require.Equal(t, test.expected, sanitize(test.toSanitize), "The sanitized certificates should be equal")
})
}
}
func TestTLSClientHeadersWithPEM(t *testing.T) {
func TestPassTLSClientCert_PEM(t *testing.T) {
testCases := []struct {
desc string
certContents []string // set the request TLS attribute if defined
@@ -417,70 +326,36 @@ func TestTLSClientHeadersWithPEM(t *testing.T) {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
require.Equal(t, http.StatusOK, res.Code, "Http Status should be OK")
require.Equal(t, "bar", res.Body.String(), "Should be the expected body")
assert.Equal(t, http.StatusOK, res.Code, "Http Status should be OK")
assert.Equal(t, "bar", res.Body.String(), "Should be the expected body")
if test.expectedHeader != "" {
require.Equal(t, getCleanCertContents(test.certContents), req.Header.Get(xForwardedTLSClientCert), "The request header should contain the cleaned certificate")
expected := getCleanCertContents(test.certContents)
assert.Equal(t, expected, req.Header.Get(xForwardedTLSClientCert), "The request header should contain the cleaned certificate")
} else {
require.Empty(t, req.Header.Get(xForwardedTLSClientCert))
assert.Empty(t, req.Header.Get(xForwardedTLSClientCert))
}
require.Empty(t, res.Header().Get(xForwardedTLSClientCert), "The response header should be always empty")
assert.Empty(t, res.Header().Get(xForwardedTLSClientCert), "The response header should be always empty")
})
}
}
func TestGetSans(t *testing.T) {
urlFoo, err := url.Parse("my.foo.com")
require.NoError(t, err)
urlBar, err := url.Parse("my.bar.com")
require.NoError(t, err)
func TestPassTLSClientCert_certInfo(t *testing.T) {
minimalCheeseCertAllInfo := strings.Join([]string{
`Subject="C=FR,ST=Some-State,O=Cheese"`,
`Issuer="DC=org,DC=cheese,C=FR,C=US,ST=Signing State,ST=Signing State 2,L=TOULOUSE,L=LYON,O=Cheese,O=Cheese 2,CN=Simple Signing CA 2"`,
`NB="1544094636"`,
`NA="1632568236"`,
}, fieldSeparator)
testCases := []struct {
desc string
cert *x509.Certificate // set the request TLS attribute if defined
expected []string
}{
{
desc: "With nil",
},
{
desc: "Certificate without Sans",
cert: &x509.Certificate{},
},
{
desc: "Certificate with all Sans",
cert: &x509.Certificate{
DNSNames: []string{"foo", "bar"},
EmailAddresses: []string{"test@test.com", "test2@test.com"},
IPAddresses: []net.IP{net.IPv4(10, 0, 0, 1), net.IPv4(10, 0, 0, 2)},
URIs: []*url.URL{urlFoo, urlBar},
},
expected: []string{"foo", "bar", "test@test.com", "test2@test.com", "10.0.0.1", "10.0.0.2", urlFoo.String(), urlBar.String()},
},
}
for _, test := range testCases {
sans := getSANs(test.cert)
test := test
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
if len(test.expected) > 0 {
for i, expected := range test.expected {
require.Equal(t, expected, sans[i])
}
} else {
require.Empty(t, sans)
}
})
}
}
func TestTLSClientHeadersWithCertInfo(t *testing.T) {
minimalCheeseCertAllInfo := `Subject="C=FR,ST=Some-State,O=Cheese",Issuer="DC=org,DC=cheese,C=FR,C=US,ST=Signing State,ST=Signing State 2,L=TOULOUSE,L=LYON,O=Cheese,O=Cheese 2,CN=Simple Signing CA 2",NB=1544094636,NA=1632568236,SAN=`
completeCertAllInfo := `Subject="DC=org,DC=cheese,C=FR,C=US,ST=Cheese org state,ST=Cheese com state,L=TOULOUSE,L=LYON,O=Cheese,O=Cheese 2,CN=*.cheese.com",Issuer="DC=org,DC=cheese,C=FR,C=US,ST=Signing State,ST=Signing State 2,L=TOULOUSE,L=LYON,O=Cheese,O=Cheese 2,CN=Simple Signing CA 2",NB=1544094616,NA=1607166616,SAN=*.cheese.org,*.cheese.net,*.cheese.com,test@cheese.org,test@cheese.net,10.0.1.0,10.0.1.2`
completeCertAllInfo := strings.Join([]string{
`Subject="DC=org,DC=cheese,C=FR,C=US,ST=Cheese org state,ST=Cheese com state,L=TOULOUSE,L=LYON,O=Cheese,O=Cheese 2,CN=*.cheese.com"`,
`Issuer="DC=org,DC=cheese,C=FR,C=US,ST=Signing State,ST=Signing State 2,L=TOULOUSE,L=LYON,O=Cheese,O=Cheese 2,CN=Simple Signing CA 2"`,
`NB="1544094616"`,
`NA="1607166616"`,
`SAN="*.cheese.org,*.cheese.net,*.cheese.com,test@cheese.org,test@cheese.net,10.0.1.0,10.0.1.2"`,
}, fieldSeparator)
testCases := []struct {
desc string
@@ -547,7 +422,7 @@ func TestTLSClientHeadersWithCertInfo(t *testing.T) {
},
},
},
expectedHeader: url.QueryEscape(minimalCheeseCertAllInfo),
expectedHeader: minimalCheeseCertAllInfo,
},
{
desc: "TLS with simple certificate, with some info",
@@ -564,7 +439,7 @@ func TestTLSClientHeadersWithCertInfo(t *testing.T) {
},
},
},
expectedHeader: url.QueryEscape(`Subject="O=Cheese",Issuer="C=FR,C=US",NA=1632568236,SAN=`),
expectedHeader: `Subject="O=Cheese";Issuer="C=FR,C=US";NA="1632568236"`,
},
{
desc: "TLS with complete certificate, with all info",
@@ -594,7 +469,7 @@ func TestTLSClientHeadersWithCertInfo(t *testing.T) {
},
},
},
expectedHeader: url.QueryEscape(completeCertAllInfo),
expectedHeader: completeCertAllInfo,
},
{
desc: "TLS with 2 certificates, with all info",
@@ -624,7 +499,7 @@ func TestTLSClientHeadersWithCertInfo(t *testing.T) {
},
},
},
expectedHeader: url.QueryEscape(strings.Join([]string{minimalCheeseCertAllInfo, completeCertAllInfo}, ";")),
expectedHeader: strings.Join([]string{minimalCheeseCertAllInfo, completeCertAllInfo}, certSeparator),
},
}
@@ -645,15 +520,157 @@ func TestTLSClientHeadersWithCertInfo(t *testing.T) {
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
require.Equal(t, http.StatusOK, res.Code, "Http Status should be OK")
require.Equal(t, "bar", res.Body.String(), "Should be the expected body")
assert.Equal(t, http.StatusOK, res.Code, "Http Status should be OK")
assert.Equal(t, "bar", res.Body.String(), "Should be the expected body")
if test.expectedHeader != "" {
require.Equal(t, test.expectedHeader, req.Header.Get(xForwardedTLSClientCertInfo), "The request header should contain the cleaned certificate")
unescape, err := url.QueryUnescape(req.Header.Get(xForwardedTLSClientCertInfo))
require.NoError(t, err)
assert.Equal(t, test.expectedHeader, unescape, "The request header should contain the cleaned certificate")
} else {
require.Empty(t, req.Header.Get(xForwardedTLSClientCertInfo))
assert.Empty(t, req.Header.Get(xForwardedTLSClientCertInfo))
}
require.Empty(t, res.Header().Get(xForwardedTLSClientCertInfo), "The response header should be always empty")
assert.Empty(t, res.Header().Get(xForwardedTLSClientCertInfo), "The response header should be always empty")
})
}
}
func Test_sanitize(t *testing.T) {
testCases := []struct {
desc string
toSanitize []byte
expected string
}{
{
desc: "Empty",
},
{
desc: "With a minimal cert",
toSanitize: []byte(minimalCheeseCrt),
expected: `MIIEQDCCAygCFFRY0OBk/L5Se0IZRj3CMljawL2UMA0GCSqGSIb3DQEBCwUAMIIB
hDETMBEGCgmSJomT8ixkARkWA29yZzEWMBQGCgmSJomT8ixkARkWBmNoZWVzZTEP
MA0GA1UECgwGQ2hlZXNlMREwDwYDVQQKDAhDaGVlc2UgMjEfMB0GA1UECwwWU2lt
cGxlIFNpZ25pbmcgU2VjdGlvbjEhMB8GA1UECwwYU2ltcGxlIFNpZ25pbmcgU2Vj
dGlvbiAyMRowGAYDVQQDDBFTaW1wbGUgU2lnbmluZyBDQTEcMBoGA1UEAwwTU2lt
cGxlIFNpZ25pbmcgQ0EgMjELMAkGA1UEBhMCRlIxCzAJBgNVBAYTAlVTMREwDwYD
VQQHDAhUT1VMT1VTRTENMAsGA1UEBwwETFlPTjEWMBQGA1UECAwNU2lnbmluZyBT
dGF0ZTEYMBYGA1UECAwPU2lnbmluZyBTdGF0ZSAyMSEwHwYJKoZIhvcNAQkBFhJz
aW1wbGVAc2lnbmluZy5jb20xIjAgBgkqhkiG9w0BCQEWE3NpbXBsZTJAc2lnbmlu
Zy5jb20wHhcNMTgxMjA2MTExMDM2WhcNMjEwOTI1MTExMDM2WjAzMQswCQYDVQQG
EwJGUjETMBEGA1UECAwKU29tZS1TdGF0ZTEPMA0GA1UECgwGQ2hlZXNlMIIBIjAN
BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAskX/bUtwFo1gF2BTPNaNcTUMaRFu
FMZozK8IgLjccZ4kZ0R9oFO6Yp8Zl/IvPaf7tE26PI7XP7eHriUdhnQzX7iioDd0
RZa68waIhAGc+xPzRFrP3b3yj3S2a9Rve3c0K+SCV+EtKAwsxMqQDhoo9PcBfo5B
RHfht07uD5MncUcGirwN+/pxHV5xzAGPcc7On0/5L7bq/G+63nhu78zw9XyuLaHC
PM5VbOUvpyIESJHbMMzTdFGL8ob9VKO+Kr1kVGdEA9i8FLGl3xz/GBKuW/JD0xyW
DrU29mri5vYWHmkuv7ZWHGXnpXjTtPHwveE9/0/ArnmpMyR9JtqFr1oEvQIDAQAB
MA0GCSqGSIb3DQEBCwUAA4IBAQBHta+NWXI08UHeOkGzOTGRiWXsOH2dqdX6gTe9
xF1AIjyoQ0gvpoGVvlnChSzmlUj+vnx/nOYGIt1poE3hZA3ZHZD/awsvGyp3GwWD
IfXrEViSCIyF+8tNNKYyUcEO3xdAsAUGgfUwwF/mZ6MBV5+A/ZEEILlTq8zFt9dV
vdKzIt7fZYxYBBHFSarl1x8pDgWXlf3hAufevGJXip9xGYmznF0T5cq1RbWJ4be3
/9K7yuWhuBYC3sbTbCneHBa91M82za+PIISc1ygCYtWSBoZKSAqLk0rkZpHaekDP
WqeUSNGYV//RunTeuRDAf5OxehERb1srzBXhRZ3cZdzXbgR/`,
},
}
for _, test := range testCases {
test := test
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
content := sanitize(test.toSanitize)
expected := url.QueryEscape(strings.Replace(test.expected, "\n", "", -1))
assert.Equal(t, expected, content, "The sanitized certificates should be equal")
})
}
}
func Test_getSANs(t *testing.T) {
urlFoo := testhelpers.MustParseURL("my.foo.com")
urlBar := testhelpers.MustParseURL("my.bar.com")
testCases := []struct {
desc string
cert *x509.Certificate // set the request TLS attribute if defined
expected []string
}{
{
desc: "With nil",
},
{
desc: "Certificate without Sans",
cert: &x509.Certificate{},
},
{
desc: "Certificate with all Sans",
cert: &x509.Certificate{
DNSNames: []string{"foo", "bar"},
EmailAddresses: []string{"test@test.com", "test2@test.com"},
IPAddresses: []net.IP{net.IPv4(10, 0, 0, 1), net.IPv4(10, 0, 0, 2)},
URIs: []*url.URL{urlFoo, urlBar},
},
expected: []string{"foo", "bar", "test@test.com", "test2@test.com", "10.0.0.1", "10.0.0.2", urlFoo.String(), urlBar.String()},
},
}
for _, test := range testCases {
sans := getSANs(test.cert)
test := test
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
if len(test.expected) > 0 {
for i, expected := range test.expected {
assert.Equal(t, expected, sans[i])
}
} else {
assert.Empty(t, sans)
}
})
}
}
func getCleanCertContents(certContents []string) string {
exp := regexp.MustCompile("-----BEGIN CERTIFICATE-----(?s)(.*)")
var cleanedCertContent []string
for _, certContent := range certContents {
cert := sanitize([]byte(exp.FindString(certContent)))
cleanedCertContent = append(cleanedCertContent, cert)
}
return strings.Join(cleanedCertContent, certSeparator)
}
func buildTLSWith(certContents []string) *tls.ConnectionState {
var peerCertificates []*x509.Certificate
for _, certContent := range certContents {
peerCertificates = append(peerCertificates, getCertificate(certContent))
}
return &tls.ConnectionState{PeerCertificates: peerCertificates}
}
func getCertificate(certContent string) *x509.Certificate {
roots := x509.NewCertPool()
ok := roots.AppendCertsFromPEM([]byte(signingCA))
if !ok {
panic("failed to parse root certificate")
}
block, _ := pem.Decode([]byte(certContent))
if block == nil {
panic("failed to parse certificate PEM")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
panic("failed to parse certificate: " + err.Error())
}
return cert
}

View File

@@ -152,12 +152,12 @@ func (p *Provider) getConsulServicesData(ctx context.Context) ([]itemData, error
var data []itemData
for name := range consulServiceNames {
consulServices, err := p.fetchService(ctx, name)
consulServices, healthServices, err := p.fetchService(ctx, name)
if err != nil {
return nil, err
}
for _, consulService := range consulServices {
for i, consulService := range consulServices {
address := consulService.ServiceAddress
if address == "" {
address = consulService.Address
@@ -171,7 +171,7 @@ func (p *Provider) getConsulServicesData(ctx context.Context) ([]itemData, error
Port: strconv.Itoa(consulService.ServicePort),
Labels: tagsToNeutralLabels(consulService.ServiceTags, p.Prefix),
Tags: consulService.ServiceTags,
Status: consulService.Checks.AggregatedStatus(),
Status: healthServices[i].Checks.AggregatedStatus(),
}
extraConf, err := p.getConfiguration(item)
@@ -187,15 +187,21 @@ func (p *Provider) getConsulServicesData(ctx context.Context) ([]itemData, error
return data, nil
}
func (p *Provider) fetchService(ctx context.Context, name string) ([]*api.CatalogService, error) {
func (p *Provider) fetchService(ctx context.Context, name string) ([]*api.CatalogService, []*api.ServiceEntry, error) {
var tagFilter string
if !p.ExposedByDefault {
tagFilter = p.Prefix + ".enable=true"
}
opts := &api.QueryOptions{AllowStale: p.Stale, RequireConsistent: p.RequireConsistent, UseCache: p.Cache}
consulServices, _, err := p.client.Catalog().Service(name, tagFilter, opts)
return consulServices, err
if err != nil {
return nil, nil, err
}
healthServices, _, err := p.client.Health().Service(name, tagFilter, false, opts)
return consulServices, healthServices, err
}
func (p *Provider) fetchServices(ctx context.Context) (map[string][]string, error) {

View File

@@ -307,8 +307,13 @@ func (c configBuilder) loadServers(fallbackNamespace string, svc v1alpha1.LoadBa
var servers []dynamic.Server
if service.Spec.Type == corev1.ServiceTypeExternalName {
protocol := "http"
if portSpec.Port == 443 || strings.HasPrefix(portSpec.Name, "https") {
protocol = "https"
}
return append(servers, dynamic.Server{
URL: fmt.Sprintf("http://%s:%d", service.Spec.ExternalName, portSpec.Port),
URL: fmt.Sprintf("%s://%s:%d", protocol, service.Spec.ExternalName, portSpec.Port),
}), nil
}
@@ -375,11 +380,11 @@ func (c configBuilder) nameAndService(ctx context.Context, namespaceService stri
return "", nil, err
}
fullName := fullServiceName(svcCtx, namespace, service.Name, service.Port)
fullName := fullServiceName(svcCtx, namespace, service, service.Port)
return fullName, serversLB, nil
case service.Kind == "TraefikService":
return fullServiceName(svcCtx, namespace, service.Name, 0), nil, nil
return fullServiceName(svcCtx, namespace, service, 0), nil, nil
default:
return "", nil, fmt.Errorf("unsupported service kind %s", service.Kind)
}
@@ -394,27 +399,22 @@ func splitSvcNameProvider(name string) (string, string) {
return svc, pvd
}
func fullServiceName(ctx context.Context, namespace, serviceName string, port int32) string {
func fullServiceName(ctx context.Context, namespace string, service v1alpha1.LoadBalancerSpec, port int32) string {
if port != 0 {
return provider.Normalize(fmt.Sprintf("%s-%s-%d", namespace, serviceName, port))
return provider.Normalize(fmt.Sprintf("%s-%s-%d", namespace, service.Name, port))
}
if !strings.Contains(serviceName, providerNamespaceSeparator) {
return provider.Normalize(fmt.Sprintf("%s-%s", namespace, serviceName))
if !strings.Contains(service.Name, providerNamespaceSeparator) {
return provider.Normalize(fmt.Sprintf("%s-%s", namespace, service.Name))
}
name, pName := splitSvcNameProvider(serviceName)
name, pName := splitSvcNameProvider(service.Name)
if pName == providerName {
return provider.Normalize(fmt.Sprintf("%s-%s", namespace, name))
}
// At this point, if namespace == "default", we do not know whether it had been intentionally set as such,
// or if we're simply hitting the value set by default.
// But as it is most likely very much the latter,
// and we do not want to systematically log spam users in that case,
// we skip logging whenever the namespace is "default".
if namespace != "default" {
log.FromContext(ctx).Warnf("namespace %q is ignored in cross-provider context", namespace)
if service.Namespace != "" {
log.FromContext(ctx).Warnf("namespace %q is ignored in cross-provider context", service.Namespace)
}
return provider.Normalize(name) + providerNamespaceSeparator + pName

View File

@@ -0,0 +1,9 @@
kind: Ingress
apiVersion: extensions/v1beta1
metadata:
name: ""
namespace: testing
spec:
rules:
- host: testing.example.com

View File

@@ -313,53 +313,57 @@ func (p *Provider) loadConfigurationFromIngresses(ctx context.Context, client Cl
conf.HTTP.Services["default-backend"] = service
}
}
for _, rule := range ingress.Spec.Rules {
if err := checkStringQuoteValidity(rule.Host); err != nil {
log.FromContext(ctx).Errorf("Invalid syntax for host: %s", rule.Host)
continue
}
for _, p := range rule.HTTP.Paths {
service, err := loadService(client, ingress.Namespace, p.Backend)
if err != nil {
log.FromContext(ctx).
WithField("serviceName", p.Backend.ServiceName).
WithField("servicePort", p.Backend.ServicePort.String()).
Errorf("Cannot create service: %v", err)
continue
}
if rule.HTTP != nil {
for _, p := range rule.HTTP.Paths {
service, err := loadService(client, ingress.Namespace, p.Backend)
if err != nil {
log.FromContext(ctx).
WithField("serviceName", p.Backend.ServiceName).
WithField("servicePort", p.Backend.ServicePort.String()).
Errorf("Cannot create service: %v", err)
continue
}
if err = checkStringQuoteValidity(p.Path); err != nil {
log.FromContext(ctx).Errorf("Invalid syntax for path: %s", p.Path)
continue
}
if err = checkStringQuoteValidity(p.Path); err != nil {
log.FromContext(ctx).Errorf("Invalid syntax for path: %s", p.Path)
continue
}
serviceName := provider.Normalize(ingress.Namespace + "-" + p.Backend.ServiceName + "-" + p.Backend.ServicePort.String())
var rules []string
if len(rule.Host) > 0 {
rules = []string{"Host(`" + rule.Host + "`)"}
}
serviceName := provider.Normalize(ingress.Namespace + "-" + p.Backend.ServiceName + "-" + p.Backend.ServicePort.String())
var rules []string
if len(rule.Host) > 0 {
rules = []string{"Host(`" + rule.Host + "`)"}
}
if len(p.Path) > 0 {
rules = append(rules, "PathPrefix(`"+p.Path+"`)")
}
if len(p.Path) > 0 {
rules = append(rules, "PathPrefix(`"+p.Path+"`)")
}
routerKey := strings.TrimPrefix(provider.Normalize(rule.Host+p.Path), "-")
conf.HTTP.Routers[routerKey] = &dynamic.Router{
Rule: strings.Join(rules, " && "),
Service: serviceName,
}
if len(ingress.Spec.TLS) > 0 {
// TLS enabled for this ingress, add TLS router
conf.HTTP.Routers[routerKey+"-tls"] = &dynamic.Router{
routerKey := strings.TrimPrefix(provider.Normalize(rule.Host+p.Path), "-")
conf.HTTP.Routers[routerKey] = &dynamic.Router{
Rule: strings.Join(rules, " && "),
Service: serviceName,
TLS: &dynamic.RouterTLSConfig{},
}
if len(ingress.Spec.TLS) > 0 {
// TLS enabled for this ingress, add TLS router
conf.HTTP.Routers[routerKey+"-tls"] = &dynamic.Router{
Rule: strings.Join(rules, " && "),
Service: serviceName,
TLS: &dynamic.RouterTLSConfig{},
}
}
conf.HTTP.Services[serviceName] = service
}
conf.HTTP.Services[serviceName] = service
}
err := p.updateIngressStatus(ingress, client)
if err != nil {
log.FromContext(ctx).Errorf("Error while updating ingress status: %v", err)

View File

@@ -38,6 +38,17 @@ func TestLoadConfigurationFromIngresses(t *testing.T) {
},
},
},
{
desc: "Ingress one rule host only",
expected: &dynamic.Configuration{
TCP: &dynamic.TCPConfiguration{},
HTTP: &dynamic.HTTPConfiguration{
Routers: map[string]*dynamic.Router{},
Middlewares: map[string]*dynamic.Middleware{},
Services: map[string]*dynamic.Service{},
},
},
},
{
desc: "Ingress with a basic rule on one path",
expected: &dynamic.Configuration{

View File

@@ -25,7 +25,7 @@
"middlewares": {
"dashboard_redirect": {
"redirectRegex": {
"regex": "^(http:\\/\\/[^:]+(:\\d+)?)/$",
"regex": "^(http:\\/\\/[^:\\/]+(:\\d+)?)\\/$",
"replacement": "${1}/dashboard/",
"permanent": true
}

View File

@@ -21,6 +21,14 @@
"rule": "PathPrefix(`/`)",
"priority": 2147483645
},
"debug": {
"entryPoints": [
"traefik"
],
"service": "api@internal",
"rule": "PathPrefix(`/debug`)",
"priority": 2147483646
},
"ping": {
"entryPoints": [
"test"
@@ -49,7 +57,7 @@
"middlewares": {
"dashboard_redirect": {
"redirectRegex": {
"regex": "^(http:\\/\\/[^:]+(:\\d+)?)/$",
"regex": "^(http:\\/\\/[^:\\/]+(:\\d+)?)\\/$",
"replacement": "${1}/dashboard/",
"permanent": true
}

View File

@@ -86,7 +86,7 @@ func (i *Provider) apiConfiguration(cfg *dynamic.Configuration) {
cfg.HTTP.Middlewares["dashboard_redirect"] = &dynamic.Middleware{
RedirectRegex: &dynamic.RedirectRegex{
Regex: `^(http:\/\/[^:]+(:\d+)?)/$`,
Regex: `^(http:\/\/[^:\/]+(:\d+)?)\/$`,
Replacement: "${1}/dashboard/",
Permanent: true,
},
@@ -95,6 +95,15 @@ func (i *Provider) apiConfiguration(cfg *dynamic.Configuration) {
StripPrefix: &dynamic.StripPrefix{Prefixes: []string{"/dashboard/", "/dashboard"}},
}
}
if i.staticCfg.API.Debug {
cfg.HTTP.Routers["debug"] = &dynamic.Router{
EntryPoints: []string{"traefik"},
Service: "api@internal",
Priority: math.MaxInt32 - 1,
Rule: "PathPrefix(`/debug`)",
}
}
}
cfg.HTTP.Services["api"] = &dynamic.Service{}

View File

@@ -28,6 +28,7 @@ func Test_createConfiguration(t *testing.T) {
API: &static.API{
Insecure: true,
Dashboard: true,
Debug: true,
},
Ping: &ping.Handler{
EntryPoint: "test",

View File

@@ -49,8 +49,8 @@ func NewConfigurationWatcher(routinesPool *safe.Pool, pvd provider.Provider, pro
// Start the configuration watcher.
func (c *ConfigurationWatcher) Start() {
c.routinesPool.Go(func(stop chan bool) { c.listenProviders(stop) })
c.routinesPool.Go(func(stop chan bool) { c.listenConfigurations(stop) })
c.routinesPool.Go(c.listenProviders)
c.routinesPool.Go(c.listenConfigurations)
c.startProvider()
}

View File

@@ -48,7 +48,6 @@ func NewServer(routinesPool *safe.Pool, entryPoints TCPEntryPoints, watcher *Con
// Start starts the server and Stop/Close it when context is Done
func (s *Server) Start(ctx context.Context) {
go func() {
defer s.Close()
<-ctx.Done()
logger := log.FromContext(ctx)
logger.Info("I have to go...")
@@ -59,9 +58,7 @@ func (s *Server) Start(ctx context.Context) {
s.tcpEntryPoints.Start()
s.watcher.Start()
s.routinesPool.Go(func(stop chan bool) {
s.listenSignals(stop)
})
s.routinesPool.Go(s.listenSignals)
}
// Wait blocks until the server shutdown.

View File

@@ -52,9 +52,9 @@ func (h *httpForwarder) Accept() (net.Conn, error) {
type TCPEntryPoints map[string]*TCPEntryPoint
// NewTCPEntryPoints creates a new TCPEntryPoints.
func NewTCPEntryPoints(staticConfiguration static.Configuration) (TCPEntryPoints, error) {
func NewTCPEntryPoints(entryPointsConfig static.EntryPoints) (TCPEntryPoints, error) {
serverEntryPointsTCP := make(TCPEntryPoints)
for entryPointName, config := range staticConfiguration.EntryPoints {
for entryPointName, config := range entryPointsConfig {
ctx := log.With(context.Background(), log.Str(log.EntryPointName, entryPointName))
var err error
@@ -158,6 +158,10 @@ func (e *TCPEntryPoint) StartTCP(ctx context.Context) {
conn, err := e.listener.Accept()
if err != nil {
logger.Error(err)
if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
continue
}
return
}
@@ -167,6 +171,23 @@ func (e *TCPEntryPoint) StartTCP(ctx context.Context) {
}
safe.Go(func() {
// Enforce read/write deadlines at the connection level,
// because when we're peeking the first byte to determine whether we are doing TLS,
// the deadlines at the server level are not taken into account.
if e.transportConfiguration.RespondingTimeouts.ReadTimeout > 0 {
err := writeCloser.SetReadDeadline(time.Now().Add(time.Duration(e.transportConfiguration.RespondingTimeouts.ReadTimeout)))
if err != nil {
logger.Errorf("Error while setting read deadline: %v", err)
}
}
if e.transportConfiguration.RespondingTimeouts.WriteTimeout > 0 {
err = writeCloser.SetWriteDeadline(time.Now().Add(time.Duration(e.transportConfiguration.RespondingTimeouts.WriteTimeout)))
if err != nil {
logger.Errorf("Error while setting write deadline: %v", err)
}
}
e.switcher.ServeTCP(newTrackedConnection(writeCloser, e.tracker))
})
}
@@ -187,48 +208,48 @@ func (e *TCPEntryPoint) Shutdown(ctx context.Context) {
logger.Debugf("Waiting %s seconds before killing connections.", graceTimeOut)
var wg sync.WaitGroup
shutdownServer := func(server stoppableServer) {
defer wg.Done()
err := server.Shutdown(ctx)
if err == nil {
return
}
if ctx.Err() == context.DeadlineExceeded {
logger.Debugf("Server failed to shutdown within deadline because: %s", err)
if err = server.Close(); err != nil {
logger.Error(err)
}
return
}
logger.Error(err)
// We expect Close to fail again because Shutdown most likely failed when trying to close a listener.
// We still call it however, to make sure that all connections get closed as well.
server.Close()
}
if e.httpServer.Server != nil {
wg.Add(1)
go func() {
defer wg.Done()
if err := e.httpServer.Server.Shutdown(ctx); err != nil {
if ctx.Err() == context.DeadlineExceeded {
logger.Debugf("Wait server shutdown is overdue to: %s", err)
err = e.httpServer.Server.Close()
if err != nil {
logger.Error(err)
}
}
}
}()
go shutdownServer(e.httpServer.Server)
}
if e.httpsServer.Server != nil {
wg.Add(1)
go func() {
defer wg.Done()
if err := e.httpsServer.Server.Shutdown(ctx); err != nil {
if ctx.Err() == context.DeadlineExceeded {
logger.Debugf("Wait server shutdown is overdue to: %s", err)
err = e.httpsServer.Server.Close()
if err != nil {
logger.Error(err)
}
}
}
}()
go shutdownServer(e.httpsServer.Server)
}
if e.tracker != nil {
wg.Add(1)
go func() {
defer wg.Done()
if err := e.tracker.Shutdown(ctx); err != nil {
if ctx.Err() == context.DeadlineExceeded {
logger.Debugf("Wait hijack connection is overdue to: %s", err)
e.tracker.Close()
}
err := e.tracker.Shutdown(ctx)
if err == nil {
return
}
if ctx.Err() == context.DeadlineExceeded {
logger.Debugf("Server failed to shutdown before deadline because: %s", err)
}
e.tracker.Close()
}()
}
@@ -455,8 +476,11 @@ func createHTTPServer(ctx context.Context, ln net.Listener, configuration *stati
}
serverHTTP := &http.Server{
Handler: handler,
ErrorLog: httpServerLogger,
Handler: handler,
ErrorLog: httpServerLogger,
ReadTimeout: time.Duration(configuration.Transport.RespondingTimeouts.ReadTimeout),
WriteTimeout: time.Duration(configuration.Transport.RespondingTimeouts.WriteTimeout),
IdleTimeout: time.Duration(configuration.Transport.RespondingTimeouts.IdleTimeout),
}
listener := newHTTPForwarder(ln)

View File

@@ -3,8 +3,11 @@ package server
import (
"bufio"
"context"
"errors"
"io"
"net"
"net/http"
"strings"
"testing"
"time"
@@ -15,128 +18,206 @@ import (
"github.com/stretchr/testify/require"
)
func TestShutdownHTTP(t *testing.T) {
entryPoint, err := NewTCPEntryPoint(context.Background(), &static.EntryPoint{
Address: ":0",
Transport: &static.EntryPointsTransport{
LifeCycle: &static.LifeCycle{
RequestAcceptGraceTimeout: 0,
GraceTimeOut: types.Duration(5 * time.Second),
},
},
ForwardedHeaders: &static.ForwardedHeaders{},
})
require.NoError(t, err)
go entryPoint.StartTCP(context.Background())
router := &tcp.Router{}
router.HTTPHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
time.Sleep(1 * time.Second)
rw.WriteHeader(http.StatusOK)
}))
entryPoint.SwitchRouter(router)
conn, err := net.Dial("tcp", entryPoint.listener.Addr().String())
require.NoError(t, err)
go entryPoint.Shutdown(context.Background())
request, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8082", nil)
require.NoError(t, err)
err = request.Write(conn)
require.NoError(t, err)
resp, err := http.ReadResponse(bufio.NewReader(conn), request)
require.NoError(t, err)
assert.Equal(t, resp.StatusCode, http.StatusOK)
}
func TestShutdownHTTPHijacked(t *testing.T) {
entryPoint, err := NewTCPEntryPoint(context.Background(), &static.EntryPoint{
Address: ":0",
Transport: &static.EntryPointsTransport{
LifeCycle: &static.LifeCycle{
RequestAcceptGraceTimeout: 0,
GraceTimeOut: types.Duration(5 * time.Second),
},
},
ForwardedHeaders: &static.ForwardedHeaders{},
})
require.NoError(t, err)
go entryPoint.StartTCP(context.Background())
func TestShutdownHijacked(t *testing.T) {
router := &tcp.Router{}
router.HTTPHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
conn, _, err := rw.(http.Hijacker).Hijack()
require.NoError(t, err)
time.Sleep(1 * time.Second)
resp := http.Response{StatusCode: http.StatusOK}
err = resp.Write(conn)
require.NoError(t, err)
}))
entryPoint.SwitchRouter(router)
conn, err := net.Dial("tcp", entryPoint.listener.Addr().String())
require.NoError(t, err)
go entryPoint.Shutdown(context.Background())
request, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8082", nil)
require.NoError(t, err)
err = request.Write(conn)
require.NoError(t, err)
resp, err := http.ReadResponse(bufio.NewReader(conn), request)
require.NoError(t, err)
assert.Equal(t, resp.StatusCode, http.StatusOK)
testShutdown(t, router)
}
func TestShutdownTCPConn(t *testing.T) {
func TestShutdownHTTP(t *testing.T) {
router := &tcp.Router{}
router.HTTPHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(http.StatusOK)
time.Sleep(time.Second)
}))
testShutdown(t, router)
}
func TestShutdownTCP(t *testing.T) {
router := &tcp.Router{}
router.AddCatchAllNoTLS(tcp.HandlerFunc(func(conn tcp.WriteCloser) {
for {
_, err := http.ReadRequest(bufio.NewReader(conn))
if err == io.EOF || (err != nil && strings.HasSuffix(err.Error(), "use of closed network connection")) {
return
}
require.NoError(t, err)
resp := http.Response{StatusCode: http.StatusOK}
err = resp.Write(conn)
require.NoError(t, err)
}
}))
testShutdown(t, router)
}
func testShutdown(t *testing.T, router *tcp.Router) {
epConfig := &static.EntryPointsTransport{}
epConfig.SetDefaults()
epConfig.LifeCycle.RequestAcceptGraceTimeout = 0
epConfig.LifeCycle.GraceTimeOut = types.Duration(5 * time.Second)
entryPoint, err := NewTCPEntryPoint(context.Background(), &static.EntryPoint{
Address: ":0",
Transport: &static.EntryPointsTransport{
LifeCycle: &static.LifeCycle{
RequestAcceptGraceTimeout: 0,
GraceTimeOut: types.Duration(5 * time.Second),
},
},
// We explicitly use an IPV4 address because on Alpine, with an IPV6 address
// there seems to be shenanigans related to properly cleaning up file descriptors
Address: "127.0.0.1:0",
Transport: epConfig,
ForwardedHeaders: &static.ForwardedHeaders{},
})
require.NoError(t, err)
go entryPoint.StartTCP(context.Background())
conn, err := startEntrypoint(entryPoint, router)
require.NoError(t, err)
router := &tcp.Router{}
router.AddCatchAllNoTLS(tcp.HandlerFunc(func(conn tcp.WriteCloser) {
_, err := http.ReadRequest(bufio.NewReader(conn))
require.NoError(t, err)
time.Sleep(1 * time.Second)
epAddr := entryPoint.listener.Addr().String()
resp := http.Response{StatusCode: http.StatusOK}
err = resp.Write(conn)
require.NoError(t, err)
}))
request, err := http.NewRequest(http.MethodHead, "http://127.0.0.1:8082", nil)
require.NoError(t, err)
entryPoint.SwitchRouter(router)
time.Sleep(time.Millisecond * 100)
conn, err := net.Dial("tcp", entryPoint.listener.Addr().String())
// We need to do a write on the conn before the shutdown to make it "exist".
// Because the connection indeed exists as far as TCP is concerned,
// but since we only pass it along to the HTTP server after at least one byte is peaked,
// the HTTP server (and hence its shutdown) does not know about the connection until that first byte peaking.
err = request.Write(conn)
require.NoError(t, err)
go entryPoint.Shutdown(context.Background())
request, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8082", nil)
require.NoError(t, err)
// Make sure that new connections are not permitted anymore.
// Note that this should be true not only after Shutdown has returned,
// but technically also as early as the Shutdown has closed the listener,
// i.e. during the shutdown and before the gracetime is over.
var testOk bool
for i := 0; i < 10; i++ {
loopConn, err := net.Dial("tcp", epAddr)
if err == nil {
loopConn.Close()
time.Sleep(time.Millisecond * 100)
continue
}
if !strings.HasSuffix(err.Error(), "connection refused") && !strings.HasSuffix(err.Error(), "reset by peer") {
t.Fatalf(`unexpected error: got %v, wanted "connection refused" or "reset by peer"`, err)
}
testOk = true
break
}
if !testOk {
t.Fatal("entry point never closed")
}
err = request.Write(conn)
require.NoError(t, err)
// And make sure that the connection we had opened before shutting things down is still operational
resp, err := http.ReadResponse(bufio.NewReader(conn), request)
require.NoError(t, err)
assert.Equal(t, resp.StatusCode, http.StatusOK)
assert.Equal(t, http.StatusOK, resp.StatusCode)
}
func startEntrypoint(entryPoint *TCPEntryPoint, router *tcp.Router) (net.Conn, error) {
go entryPoint.StartTCP(context.Background())
entryPoint.SwitchRouter(router)
var conn net.Conn
var err error
var epStarted bool
for i := 0; i < 10; i++ {
conn, err = net.Dial("tcp", entryPoint.listener.Addr().String())
if err != nil {
time.Sleep(time.Millisecond * 100)
continue
}
epStarted = true
break
}
if !epStarted {
return nil, errors.New("entry point never started")
}
return conn, err
}
func TestReadTimeoutWithoutFirstByte(t *testing.T) {
epConfig := &static.EntryPointsTransport{}
epConfig.SetDefaults()
epConfig.RespondingTimeouts.ReadTimeout = types.Duration(time.Second * 2)
entryPoint, err := NewTCPEntryPoint(context.Background(), &static.EntryPoint{
Address: ":0",
Transport: epConfig,
ForwardedHeaders: &static.ForwardedHeaders{},
})
require.NoError(t, err)
router := &tcp.Router{}
router.HTTPHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(http.StatusOK)
}))
conn, err := startEntrypoint(entryPoint, router)
require.NoError(t, err)
errChan := make(chan error)
go func() {
b := make([]byte, 2048)
_, err := conn.Read(b)
errChan <- err
}()
select {
case err := <-errChan:
require.Equal(t, io.EOF, err)
case <-time.Tick(time.Second * 5):
t.Error("Timeout while read")
}
}
func TestReadTimeoutWithFirstByte(t *testing.T) {
epConfig := &static.EntryPointsTransport{}
epConfig.SetDefaults()
epConfig.RespondingTimeouts.ReadTimeout = types.Duration(time.Second * 2)
entryPoint, err := NewTCPEntryPoint(context.Background(), &static.EntryPoint{
Address: ":0",
Transport: epConfig,
ForwardedHeaders: &static.ForwardedHeaders{},
})
require.NoError(t, err)
router := &tcp.Router{}
router.HTTPHandler(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(http.StatusOK)
}))
conn, err := startEntrypoint(entryPoint, router)
require.NoError(t, err)
_, err = conn.Write([]byte("GET /some HTTP/1.1\r\n"))
require.NoError(t, err)
errChan := make(chan error)
go func() {
b := make([]byte, 2048)
_, err := conn.Read(b)
errChan <- err
}()
select {
case err := <-errChan:
require.Equal(t, io.EOF, err)
case <-time.Tick(time.Second * 5):
t.Error("Timeout while read")
}
}

View File

@@ -8,6 +8,7 @@ import (
"net/http"
"sync"
"github.com/containous/traefik/v2/pkg/middlewares/accesslog"
"github.com/containous/traefik/v2/pkg/safe"
)
@@ -63,11 +64,21 @@ func (m *Mirroring) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if handler.count*100 < total*uint64(handler.percent) {
handler.count++
handler.lock.Unlock()
// In ServeHTTP, we rely on the presence of the accesslog datatable found in the
// request's context to know whether we should mutate said datatable (and
// contribute some fields to the log). In this instance, we do not want the mirrors
// mutating (i.e. changing the service name in) the logs related to the mirrored
// server. Especially since it would result in unguarded concurrent reads/writes on
// the datatable. Therefore, we reset any potential datatable key in the new
// context that we pass around.
ctx := context.WithValue(req.Context(), accesslog.DataTableKey, nil)
// When a request served by m.handler is successful, req.Context will be canceled,
// which would trigger a cancellation of the ongoing mirrored requests.
// Therefore, we give a new, non-cancellable context to each of the mirrored calls,
// so they can terminate by themselves.
handler.ServeHTTP(m.rw, req.WithContext(contextStopPropagation{req.Context()}))
handler.ServeHTTP(m.rw, req.WithContext(contextStopPropagation{ctx}))
} else {
handler.lock.Unlock()
}

View File

@@ -52,6 +52,10 @@ func buildProxy(passHostHeader *bool, responseForwarding *dynamic.ResponseForwar
outReq.ProtoMajor = 1
outReq.ProtoMinor = 1
if _, ok := outReq.Header["User-Agent"]; !ok {
outReq.Header.Set("User-Agent", "")
}
// Do not pass client Host header unless optsetter PassHostHeader is set.
if passHostHeader != nil && !*passHostHeader {
outReq.Host = outReq.URL.Host

View File

@@ -8,6 +8,7 @@ import (
"net"
"net/http"
"strings"
"time"
"github.com/containous/traefik/v2/pkg/log"
)
@@ -34,7 +35,23 @@ func (r *Router) ServeTCP(conn WriteCloser) {
}
br := bufio.NewReader(conn)
serverName, tls, peeked := clientHelloServerName(br)
serverName, tls, peeked, err := clientHelloServerName(br)
if err != nil {
conn.Close()
return
}
// Remove read/write deadline and delegate this to underlying tcp server (for now only handled by HTTP Server)
err = conn.SetReadDeadline(time.Time{})
if err != nil {
log.WithoutContext().Errorf("Error while setting read deadline: %v", err)
}
err = conn.SetWriteDeadline(time.Time{})
if err != nil {
log.WithoutContext().Errorf("Error while setting write deadline: %v", err)
}
if !tls {
switch {
case r.catchAllNoTLS != nil:
@@ -176,33 +193,34 @@ func (c *Conn) Read(p []byte) (n int, err error) {
// clientHelloServerName returns the SNI server name inside the TLS ClientHello,
// without consuming any bytes from br.
// On any error, the empty string is returned.
func clientHelloServerName(br *bufio.Reader) (string, bool, string) {
func clientHelloServerName(br *bufio.Reader) (string, bool, string, error) {
hdr, err := br.Peek(1)
if err != nil {
if err != io.EOF {
log.Errorf("Error while Peeking first byte: %s", err)
opErr, ok := err.(*net.OpError)
if err != io.EOF && (!ok || !opErr.Timeout()) {
log.WithoutContext().Errorf("Error while Peeking first byte: %s", err)
}
return "", false, ""
return "", false, "", err
}
const recordTypeHandshake = 0x16
if hdr[0] != recordTypeHandshake {
// log.Errorf("Error not tls")
return "", false, getPeeked(br) // Not TLS.
return "", false, getPeeked(br), nil // Not TLS.
}
const recordHeaderLen = 5
hdr, err = br.Peek(recordHeaderLen)
if err != nil {
log.Errorf("Error while Peeking hello: %s", err)
return "", false, getPeeked(br)
return "", false, getPeeked(br), nil
}
recLen := int(hdr[3])<<8 | int(hdr[4]) // ignoring version in hdr[1:3]
helloBytes, err := br.Peek(recordHeaderLen + recLen)
if err != nil {
log.Errorf("Error while Hello: %s", err)
return "", true, getPeeked(br)
return "", true, getPeeked(br), nil
}
sni := ""
@@ -214,7 +232,7 @@ func clientHelloServerName(br *bufio.Reader) (string, bool, string) {
})
_ = server.Handshake()
return sni, true, getPeeked(br)
return sni, true, getPeeked(br), nil
}
func getPeeked(br *bufio.Reader) string {

View File

@@ -102,7 +102,8 @@ func (f FileOrContent) IsPath() bool {
func (f FileOrContent) Read() ([]byte, error) {
var content []byte
if _, err := os.Stat(f.String()); err == nil {
if f.IsPath() {
var err error
content, err = ioutil.ReadFile(f.String())
if err != nil {
return nil, err

View File

@@ -1,14 +1,15 @@
import { APP } from '../_helpers/APP'
import { getTotal } from './utils'
const apiBase = '/http'
function getAllRouters (params) {
return APP.api.get(`${apiBase}/routers?search=${params.query}&status=${params.status}&per_page=${params.limit}&page=${params.page}`)
.then(body => {
const total = body.data ? body.data.length : 0
console.log('Success -> HttpService -> getAllRouters', body.data)
// TODO - suggestion: add the total-pages in api response to optimize the query
return { data: body.data || [], total }
.then(response => {
const { data = [], headers } = response
const total = getTotal(headers, params)
console.log('Success -> HttpService -> getAllRouters', response, response.data)
return { data, total }
})
}
@@ -22,11 +23,11 @@ function getRouterByName (name) {
function getAllServices (params) {
return APP.api.get(`${apiBase}/services?search=${params.query}&status=${params.status}&per_page=${params.limit}&page=${params.page}`)
.then(body => {
const total = body.data ? body.data.length : 0
console.log('Success -> HttpService -> getAllServices', body.data)
// TODO - suggestion: add the total-pages in api response to optimize the query
return { data: body.data || [], total }
.then(response => {
const { data = [], headers } = response
const total = getTotal(headers, params)
console.log('Success -> HttpService -> getAllServices', response.data)
return { data, total }
})
}
@@ -40,11 +41,11 @@ function getServiceByName (name) {
function getAllMiddlewares (params) {
return APP.api.get(`${apiBase}/middlewares?search=${params.query}&status=${params.status}&per_page=${params.limit}&page=${params.page}`)
.then(body => {
const total = body.data ? body.data.length : 0
console.log('Success -> HttpService -> getAllMiddlewares', body.data)
// TODO - suggestion: add the total-pages in api response to optimize the query
return { data: body.data || [], total }
.then(response => {
const { data = [], headers } = response
const total = getTotal(headers, params)
console.log('Success -> HttpService -> getAllMiddlewares', response.data)
return { data, total }
})
}

View File

@@ -1,14 +1,15 @@
import { APP } from '../_helpers/APP'
import { getTotal } from './utils'
const apiBase = '/tcp'
function getAllRouters (params) {
return APP.api.get(`${apiBase}/routers?search=${params.query}&status=${params.status}&per_page=${params.limit}&page=${params.page}`)
.then(body => {
const total = body.data ? body.data.length : 0
console.log('Success -> HttpService -> getAllRouters', body.data)
// TODO - suggestion: add the total-pages in api response to optimize the query
return { data: body.data || [], total }
.then(response => {
const { data = [], headers } = response
const total = getTotal(headers, params)
console.log('Success -> HttpService -> getAllRouters', response.data)
return { data, total }
})
}
@@ -22,11 +23,11 @@ function getRouterByName (name) {
function getAllServices (params) {
return APP.api.get(`${apiBase}/services?search=${params.query}&status=${params.status}&per_page=${params.limit}&page=${params.page}`)
.then(body => {
const total = body.data ? body.data.length : 0
console.log('Success -> HttpService -> getAllServices', body.data)
// TODO - suggestion: add the total-pages in api response to optimize the query
return { data: body.data || [], total }
.then(response => {
const { data = [], headers } = response
const total = getTotal(headers, params)
console.log('Success -> HttpService -> getAllServices', response.data)
return { data, total }
})
}

View File

@@ -0,0 +1,8 @@
export const getTotal = (headers, params) => {
const nextPage = parseInt(headers['x-next-page'], 10) || 1
const hasNextPage = nextPage > 1
return hasNextPage
? (params.page + 1) * params.limit
: params.page * params.limit
}

View File

@@ -55,11 +55,11 @@ export default {
methods: {
getProvider (service) {
const words = service.name.split('@')
if (words.length !== 2) {
return this.provider
if (words.length === 2) {
return words[1]
}
return words[1]
return this.data.provider
}
}
}

View File

@@ -54,7 +54,7 @@
</div>
</q-card-section>
<q-card-section v-if="data.loadBalancer.terminationDelay">
<q-card-section v-if="data.loadBalancer && data.loadBalancer.terminationDelay">
<div class="row items-start no-wrap">
<div class="col">
<div class="text-subtitle2">Termination Delay</div>

View File

@@ -55,11 +55,11 @@ export default {
methods: {
getProvider (service) {
const words = service.name.split('@')
if (words.length !== 2) {
return this.provider
if (words.length === 2) {
return words[1]
}
return words[1]
return this.data.provider
}
}
}

View File

@@ -7,7 +7,7 @@
<meta name="description" content="<%= htmlWebpackPlugin.options.productDescription %>">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width<% if (htmlWebpackPlugin.options.ctx.mode.cordova) { %>, viewport-fit=cover<% } %>">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width<% if (htmlWebpackPlugin.options.ctx.mode.cordova || htmlWebpackPlugin.options.ctx.mode.capacitor) { %>, viewport-fit=cover<% } %>">
<link rel="icon" type="image/png" href="statics/app-logo-128x128.png">
<link rel="icon" type="image/png" sizes="16x16" href="statics/icons/favicon-16x16.png">