2019-03-14 14:56:06 +00:00
|
|
|
package crd
|
2019-02-21 22:08:05 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2019-03-14 14:56:06 +00:00
|
|
|
"crypto/sha256"
|
2019-02-21 22:08:05 +00:00
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"reflect"
|
|
|
|
"sort"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
2019-08-03 01:58:23 +00:00
|
|
|
"github.com/cenkalti/backoff/v3"
|
|
|
|
"github.com/containous/traefik/v2/pkg/config/dynamic"
|
|
|
|
"github.com/containous/traefik/v2/pkg/job"
|
|
|
|
"github.com/containous/traefik/v2/pkg/log"
|
|
|
|
"github.com/containous/traefik/v2/pkg/safe"
|
|
|
|
"github.com/containous/traefik/v2/pkg/tls"
|
2019-02-21 22:08:05 +00:00
|
|
|
corev1 "k8s.io/api/core/v1"
|
|
|
|
"k8s.io/apimachinery/pkg/labels"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
annotationKubernetesIngressClass = "kubernetes.io/ingress.class"
|
|
|
|
traefikDefaultIngressClass = "traefik"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Provider holds configurations of the provider.
|
|
|
|
type Provider struct {
|
2019-07-01 09:30:05 +00:00
|
|
|
Endpoint string `description:"Kubernetes server endpoint (required for external cluster client)." json:"endpoint,omitempty" toml:"endpoint,omitempty" yaml:"endpoint,omitempty"`
|
|
|
|
Token string `description:"Kubernetes bearer token (not needed for in-cluster client)." json:"token,omitempty" toml:"token,omitempty" yaml:"token,omitempty"`
|
|
|
|
CertAuthFilePath string `description:"Kubernetes certificate authority file path (not needed for in-cluster client)." json:"certAuthFilePath,omitempty" toml:"certAuthFilePath,omitempty" yaml:"certAuthFilePath,omitempty"`
|
|
|
|
DisablePassHostHeaders bool `description:"Kubernetes disable PassHost Headers." json:"disablePassHostHeaders,omitempty" toml:"disablePassHostHeaders,omitempty" yaml:"disablePassHostHeaders,omitempty" export:"true"`
|
|
|
|
Namespaces []string `description:"Kubernetes namespaces." json:"namespaces,omitempty" toml:"namespaces,omitempty" yaml:"namespaces,omitempty" export:"true"`
|
|
|
|
LabelSelector string `description:"Kubernetes label selector to use." json:"labelSelector,omitempty" toml:"labelSelector,omitempty" yaml:"labelSelector,omitempty" export:"true"`
|
|
|
|
IngressClass string `description:"Value of kubernetes.io/ingress.class annotation to watch for." json:"ingressClass,omitempty" toml:"ingressClass,omitempty" yaml:"ingressClass,omitempty" export:"true"`
|
2019-02-21 22:08:05 +00:00
|
|
|
lastConfiguration safe.Safe
|
|
|
|
}
|
|
|
|
|
2019-03-19 16:30:04 +00:00
|
|
|
func (p *Provider) newK8sClient(ctx context.Context, labelSelector string) (*clientWrapper, error) {
|
|
|
|
labelSel, err := labels.Parse(labelSelector)
|
2019-02-21 22:08:05 +00:00
|
|
|
if err != nil {
|
2019-03-19 16:30:04 +00:00
|
|
|
return nil, fmt.Errorf("invalid label selector: %q", labelSelector)
|
2019-02-21 22:08:05 +00:00
|
|
|
}
|
2019-03-19 16:30:04 +00:00
|
|
|
log.FromContext(ctx).Infof("label selector is: %q", labelSel)
|
2019-02-21 22:08:05 +00:00
|
|
|
|
|
|
|
withEndpoint := ""
|
|
|
|
if p.Endpoint != "" {
|
|
|
|
withEndpoint = fmt.Sprintf(" with endpoint %v", p.Endpoint)
|
|
|
|
}
|
|
|
|
|
2019-03-14 14:56:06 +00:00
|
|
|
var client *clientWrapper
|
2019-03-11 13:54:05 +00:00
|
|
|
switch {
|
|
|
|
case os.Getenv("KUBERNETES_SERVICE_HOST") != "" && os.Getenv("KUBERNETES_SERVICE_PORT") != "":
|
2019-02-21 22:08:05 +00:00
|
|
|
log.FromContext(ctx).Infof("Creating in-cluster Provider client%s", withEndpoint)
|
2019-03-14 14:56:06 +00:00
|
|
|
client, err = newInClusterClient(p.Endpoint)
|
2019-03-11 13:54:05 +00:00
|
|
|
case os.Getenv("KUBECONFIG") != "":
|
|
|
|
log.FromContext(ctx).Infof("Creating cluster-external Provider client from KUBECONFIG %s", os.Getenv("KUBECONFIG"))
|
2019-03-14 14:56:06 +00:00
|
|
|
client, err = newExternalClusterClientFromFile(os.Getenv("KUBECONFIG"))
|
2019-03-11 13:54:05 +00:00
|
|
|
default:
|
2019-02-21 22:08:05 +00:00
|
|
|
log.FromContext(ctx).Infof("Creating cluster-external Provider client%s", withEndpoint)
|
2019-03-14 14:56:06 +00:00
|
|
|
client, err = newExternalClusterClient(p.Endpoint, p.Token, p.CertAuthFilePath)
|
2019-02-21 22:08:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if err == nil {
|
2019-03-19 16:30:04 +00:00
|
|
|
client.labelSelector = labelSel
|
2019-02-21 22:08:05 +00:00
|
|
|
}
|
|
|
|
|
2019-03-14 14:56:06 +00:00
|
|
|
return client, err
|
2019-02-21 22:08:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Init the provider.
|
|
|
|
func (p *Provider) Init() error {
|
2019-03-27 14:02:06 +00:00
|
|
|
return nil
|
2019-02-21 22:08:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Provide allows the k8s provider to provide configurations to traefik
|
|
|
|
// using the given configuration channel.
|
2019-07-10 07:26:04 +00:00
|
|
|
func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error {
|
2019-03-14 14:56:06 +00:00
|
|
|
ctxLog := log.With(context.Background(), log.Str(log.ProviderName, "kubernetescrd"))
|
2019-02-21 22:08:05 +00:00
|
|
|
logger := log.FromContext(ctxLog)
|
|
|
|
|
2019-03-19 16:30:04 +00:00
|
|
|
logger.Debugf("Using label selector: %q", p.LabelSelector)
|
2019-02-21 22:08:05 +00:00
|
|
|
k8sClient, err := p.newK8sClient(ctxLog, p.LabelSelector)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
pool.Go(func(stop chan bool) {
|
|
|
|
operation := func() error {
|
|
|
|
stopWatch := make(chan struct{}, 1)
|
|
|
|
defer close(stopWatch)
|
|
|
|
eventsChan, err := k8sClient.WatchAll(p.Namespaces, stopWatch)
|
|
|
|
if err != nil {
|
|
|
|
logger.Errorf("Error watching kubernetes events: %v", err)
|
|
|
|
timer := time.NewTimer(1 * time.Second)
|
|
|
|
select {
|
|
|
|
case <-timer.C:
|
|
|
|
return err
|
|
|
|
case <-stop:
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-stop:
|
|
|
|
return nil
|
|
|
|
case event := <-eventsChan:
|
2019-06-21 15:18:05 +00:00
|
|
|
conf := p.loadConfigurationFromCRD(ctxLog, k8sClient)
|
2019-02-21 22:08:05 +00:00
|
|
|
|
|
|
|
if reflect.DeepEqual(p.lastConfiguration.Get(), conf) {
|
|
|
|
logger.Debugf("Skipping Kubernetes event kind %T", event)
|
|
|
|
} else {
|
|
|
|
p.lastConfiguration.Set(conf)
|
2019-07-10 07:26:04 +00:00
|
|
|
configurationChan <- dynamic.Message{
|
2019-03-14 14:56:06 +00:00
|
|
|
ProviderName: "kubernetescrd",
|
2019-02-21 22:08:05 +00:00
|
|
|
Configuration: conf,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
notify := func(err error, time time.Duration) {
|
|
|
|
logger.Errorf("Provider connection error: %s; retrying in %s", err, time)
|
|
|
|
}
|
|
|
|
err := backoff.RetryNotify(safe.OperationWithRecover(operation), job.NewBackOff(backoff.NewExponentialBackOff()), notify)
|
|
|
|
if err != nil {
|
|
|
|
logger.Errorf("Cannot connect to Provider: %s", err)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-08-26 08:30:05 +00:00
|
|
|
func (p *Provider) loadConfigurationFromCRD(ctx context.Context, client Client) *dynamic.Configuration {
|
|
|
|
tlsConfigs := make(map[string]*tls.CertAndStores)
|
|
|
|
conf := &dynamic.Configuration{
|
|
|
|
HTTP: p.loadIngressRouteConfiguration(ctx, client, tlsConfigs),
|
|
|
|
TCP: p.loadIngressRouteTCPConfiguration(ctx, client, tlsConfigs),
|
|
|
|
TLS: &dynamic.TLSConfiguration{
|
|
|
|
Certificates: getTLSConfig(tlsConfigs),
|
|
|
|
Options: buildTLSOptions(ctx, client),
|
|
|
|
},
|
2019-02-21 22:08:05 +00:00
|
|
|
}
|
|
|
|
|
2019-08-26 08:30:05 +00:00
|
|
|
for _, middleware := range client.GetMiddlewares() {
|
|
|
|
conf.HTTP.Middlewares[makeID(middleware.Namespace, middleware.Name)] = &middleware.Spec
|
2019-02-21 22:08:05 +00:00
|
|
|
}
|
|
|
|
|
2019-08-26 08:30:05 +00:00
|
|
|
return conf
|
2019-02-21 22:08:05 +00:00
|
|
|
}
|
|
|
|
|
2019-06-27 21:58:03 +00:00
|
|
|
func buildTLSOptions(ctx context.Context, client Client) map[string]tls.Options {
|
2019-06-21 15:18:05 +00:00
|
|
|
tlsOptionsCRD := client.GetTLSOptions()
|
2019-06-27 21:58:03 +00:00
|
|
|
var tlsOptions map[string]tls.Options
|
2019-06-21 15:18:05 +00:00
|
|
|
|
|
|
|
if len(tlsOptionsCRD) == 0 {
|
|
|
|
return tlsOptions
|
|
|
|
}
|
2019-06-27 21:58:03 +00:00
|
|
|
tlsOptions = make(map[string]tls.Options)
|
2019-06-21 15:18:05 +00:00
|
|
|
|
|
|
|
for _, tlsOption := range tlsOptionsCRD {
|
|
|
|
logger := log.FromContext(log.With(ctx, log.Str("tlsOption", tlsOption.Name), log.Str("namespace", tlsOption.Namespace)))
|
|
|
|
var clientCAs []tls.FileOrContent
|
|
|
|
|
2019-07-12 15:50:04 +00:00
|
|
|
for _, secretName := range tlsOption.Spec.ClientAuth.SecretNames {
|
2019-06-21 15:18:05 +00:00
|
|
|
secret, exists, err := client.GetSecret(tlsOption.Namespace, secretName)
|
|
|
|
if err != nil {
|
|
|
|
logger.Errorf("Failed to fetch secret %s/%s: %v", tlsOption.Namespace, secretName, err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
if !exists {
|
|
|
|
logger.Warnf("Secret %s/%s does not exist", tlsOption.Namespace, secretName)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
cert, err := getCABlocks(secret, tlsOption.Namespace, secretName)
|
|
|
|
if err != nil {
|
|
|
|
logger.Errorf("Failed to extract CA from secret %s/%s: %v", tlsOption.Namespace, secretName, err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
clientCAs = append(clientCAs, tls.FileOrContent(cert))
|
|
|
|
}
|
|
|
|
|
2019-06-27 21:58:03 +00:00
|
|
|
tlsOptions[makeID(tlsOption.Namespace, tlsOption.Name)] = tls.Options{
|
2019-06-21 15:18:05 +00:00
|
|
|
MinVersion: tlsOption.Spec.MinVersion,
|
|
|
|
CipherSuites: tlsOption.Spec.CipherSuites,
|
2019-07-12 15:50:04 +00:00
|
|
|
ClientAuth: tls.ClientAuth{
|
|
|
|
CAFiles: clientCAs,
|
|
|
|
ClientAuthType: tlsOption.Spec.ClientAuth.ClientAuthType,
|
2019-06-21 15:18:05 +00:00
|
|
|
},
|
|
|
|
SniStrict: tlsOption.Spec.SniStrict,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return tlsOptions
|
|
|
|
}
|
|
|
|
|
2019-08-26 08:30:05 +00:00
|
|
|
func checkStringQuoteValidity(value string) error {
|
|
|
|
_, err := strconv.Unquote(`"` + value + `"`)
|
|
|
|
return err
|
2019-02-21 22:08:05 +00:00
|
|
|
}
|
|
|
|
|
2019-06-11 13:12:04 +00:00
|
|
|
func makeServiceKey(rule, ingressName string) (string, error) {
|
|
|
|
h := sha256.New()
|
|
|
|
if _, err := h.Write([]byte(rule)); err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
key := fmt.Sprintf("%s-%.10x", ingressName, h.Sum(nil))
|
|
|
|
|
|
|
|
return key, nil
|
|
|
|
}
|
|
|
|
|
2019-03-14 14:56:06 +00:00
|
|
|
func makeID(namespace, name string) string {
|
|
|
|
if namespace == "" {
|
|
|
|
return name
|
|
|
|
}
|
2019-06-11 13:12:04 +00:00
|
|
|
|
2019-03-14 14:56:06 +00:00
|
|
|
return namespace + "/" + name
|
|
|
|
}
|
|
|
|
|
2019-02-21 22:08:05 +00:00
|
|
|
func shouldProcessIngress(ingressClass string, ingressClassAnnotation string) bool {
|
|
|
|
return ingressClass == ingressClassAnnotation ||
|
|
|
|
(len(ingressClass) == 0 && ingressClassAnnotation == traefikDefaultIngressClass)
|
|
|
|
}
|
|
|
|
|
2019-06-27 21:58:03 +00:00
|
|
|
func getTLS(k8sClient Client, secretName, namespace string) (*tls.CertAndStores, error) {
|
2019-06-11 13:12:04 +00:00
|
|
|
secret, exists, err := k8sClient.GetSecret(namespace, secretName)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to fetch secret %s/%s: %v", namespace, secretName, err)
|
|
|
|
}
|
|
|
|
if !exists {
|
|
|
|
return nil, fmt.Errorf("secret %s/%s does not exist", namespace, secretName)
|
|
|
|
}
|
|
|
|
|
|
|
|
cert, key, err := getCertificateBlocks(secret, namespace, secretName)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2019-06-27 21:58:03 +00:00
|
|
|
return &tls.CertAndStores{
|
|
|
|
Certificate: tls.Certificate{
|
2019-06-11 13:12:04 +00:00
|
|
|
CertFile: tls.FileOrContent(cert),
|
|
|
|
KeyFile: tls.FileOrContent(key),
|
|
|
|
},
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2019-06-27 21:58:03 +00:00
|
|
|
func getTLSConfig(tlsConfigs map[string]*tls.CertAndStores) []*tls.CertAndStores {
|
2019-02-21 22:08:05 +00:00
|
|
|
var secretNames []string
|
|
|
|
for secretName := range tlsConfigs {
|
|
|
|
secretNames = append(secretNames, secretName)
|
|
|
|
}
|
|
|
|
sort.Strings(secretNames)
|
|
|
|
|
2019-06-27 21:58:03 +00:00
|
|
|
var configs []*tls.CertAndStores
|
2019-02-21 22:08:05 +00:00
|
|
|
for _, secretName := range secretNames {
|
|
|
|
configs = append(configs, tlsConfigs[secretName])
|
|
|
|
}
|
|
|
|
|
|
|
|
return configs
|
|
|
|
}
|
|
|
|
|
|
|
|
func getCertificateBlocks(secret *corev1.Secret, namespace, secretName string) (string, string, error) {
|
|
|
|
var missingEntries []string
|
|
|
|
|
|
|
|
tlsCrtData, tlsCrtExists := secret.Data["tls.crt"]
|
|
|
|
if !tlsCrtExists {
|
|
|
|
missingEntries = append(missingEntries, "tls.crt")
|
|
|
|
}
|
|
|
|
|
|
|
|
tlsKeyData, tlsKeyExists := secret.Data["tls.key"]
|
|
|
|
if !tlsKeyExists {
|
|
|
|
missingEntries = append(missingEntries, "tls.key")
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(missingEntries) > 0 {
|
|
|
|
return "", "", fmt.Errorf("secret %s/%s is missing the following TLS data entries: %s",
|
|
|
|
namespace, secretName, strings.Join(missingEntries, ", "))
|
|
|
|
}
|
|
|
|
|
|
|
|
cert := string(tlsCrtData)
|
|
|
|
if cert == "" {
|
|
|
|
missingEntries = append(missingEntries, "tls.crt")
|
|
|
|
}
|
|
|
|
|
|
|
|
key := string(tlsKeyData)
|
|
|
|
if key == "" {
|
|
|
|
missingEntries = append(missingEntries, "tls.key")
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(missingEntries) > 0 {
|
|
|
|
return "", "", fmt.Errorf("secret %s/%s contains the following empty TLS data entries: %s",
|
|
|
|
namespace, secretName, strings.Join(missingEntries, ", "))
|
|
|
|
}
|
|
|
|
|
|
|
|
return cert, key, nil
|
|
|
|
}
|
2019-06-21 15:18:05 +00:00
|
|
|
|
|
|
|
func getCABlocks(secret *corev1.Secret, namespace, secretName string) (string, error) {
|
|
|
|
tlsCrtData, tlsCrtExists := secret.Data["tls.ca"]
|
|
|
|
if !tlsCrtExists {
|
|
|
|
return "", fmt.Errorf("the tls.ca entry is missing from secret %s/%s",
|
|
|
|
namespace, secretName)
|
|
|
|
}
|
|
|
|
|
|
|
|
cert := string(tlsCrtData)
|
|
|
|
if cert == "" {
|
|
|
|
return "", fmt.Errorf("the tls.ca entry in secret %s/%s is empty",
|
|
|
|
namespace, secretName)
|
|
|
|
}
|
|
|
|
|
|
|
|
return cert, nil
|
|
|
|
}
|