coredns/plugin/kubernetes/kubernetes.go

602 lines
18 KiB
Go
Raw Normal View History

BK8s datasource middleware -- PoC for A records (#153) * Laying down kubernetes middleware foundation * Duplicated a bunch of code form etcd middleware * Duplicated code hacked to compile and load as a separate middleware * Adding verbose build option to Makefile * Removing stubzone and tls support tls and stubzone support was carried over from base etcd middleware code. Removing to simplify the kube middleware implementation. (For now.) * Adding conf directory for sample conf files * Removing stubzone support from query handler * Remove upstream and proxy from k8s corefile. Not sure that upstream or proxy makes sense for a k8s backed zone. * Comment out use of singleflight serialization * Removing parsing support for "upstream" directive from k8s * Removing upstream directive parsing code * Removing CNAME and TXT lookup implementation * Create README.md Brain-dump of DNS record name assembly and open work items. * Adding notes about wildcard handling * Adding basic k8s API client * Fleshing out methods on k8s connector * Remove PathPrefix from middleware init * Removing incorrect plural * Adding brute-force k8s service lookup functions * Initializing k8s API connector during startup * Hacking around to call k8s connector * Parsing incoming domain name into serviceName and namespace * Improving and simplifying k8s zone matching and label segmentation * Removing unused functions carried over from etcd middleware * Adding basic return of k8s data to DNS client * updated debugging println statements to flag with "[debug]" * removed code in kubernetes.go::Records that was a hold-over from etcd middleware. * Removed some random exploratory hacking. * Minior README.md updates * Updating with demo instructions * Updating README.md with CoreFile and removing completed TODO items * Updating conf file and README to reflect DNS response cache works * Disabling DNS response caching * Adding debug statement on entry to Records() * Changing port number in exampes to port 53. * Misc style and clarity changes * Removing empty function definitions * Adding comment to track future cleanup * Refactoring README to follow style of other middleware * Exposing dataobject field (typo)
2016-06-06 12:49:53 -07:00
// Package kubernetes provides the kubernetes backend.
package kubernetes
import (
"context"
k8s middleware cleanup, testcases, basic SRV (#181) * Removing unnecessary gitignore pattern * Updating Makefile to run unittests for subpackages * Adding Corefile validation to ignore overlapping zones * Fixing SRV query handling * Updating README.md now that SRV works * Fixing debug message, adding code comment * Clarifying implementation of zone normalization * "Overlapping zones" is ill-defined. Reimplemented zone overlap/subzone checking to contain these functions in k8s middleware and provide better code comments explaining the normalization. * Separate build verbosity from test verbosity * Cleaning up comments to match repo code style * Merging warning messages into single message * Moving function docs to before function declaration * Adding test cases for k8sclient connector * Tests cover connector create and setting base url * Fixed bugs in connector create and setting base url functions * Updaing README to group and order development work * Priority focused on achieving functional parity with SkyDNS. * Adding work items to README and cleaning up formatting * More README format cleaning * List formating * Refactoring k8s API call to allow dependency injection * Add test cases for data parsing from k8s into dataobject structures * URL is dependency-injected to allow replacement with a mock http server during test execution * Adding more data validation for JSON parsing tests * Adding test case for GetResourceList() * Adding notes about SkyDNS embedded IP and port record names * Marked test case implemented. * Fixing formatting for example command. * Fixing formatting * Adding notes about Docker image building. * Adding SkyDNS work item * Updating TODO list * Adding name template to Corefile to specify how k8s record names are assembled * Adding template support for multi-segment zones * Updating example CoreFile for k8s with template comment * Misc whitespace cleanup * Adding SkyDNS naming notes * Adding namespace filtering to CoreFile config * Updating example k8sCoreFile to specify namespaces * Removing unused codepath * Adding check for valid namespace * More README TODO restructuring to focus effort * Adding template validation while parsing CoreFile * Record name template is considered invalid if it contains a symbol of the form ${bar} where the symbol "${bar}" is not an accepted template symbol. * Refactoring generation of answer records * Parse typeName out of query string * Refactor answer record creation as operation over list of ServiceItems * Moving k8s API caching into SkyDNS equivalency segment * Adding function to assemble record names from template * Warning: This commit may be broken. Syncing to get laptop code over to dev machine. * More todo notes * Adding comment describing sample test data. * Update k8sCorefile * Adding comment * Adding filtering support for kubernetes "type" * Required refactoring to support reuse of the StringInSlice function. * Cleaning up formatting * Adding note about SkyDNS supporting word "any". * baseUrl -> baseURL * Also removed debug statement from core/setup/kubernetes.go * Fixing test breaking from Url -> URL naming changes * Changing record name template language ${...} -> {...} * Fix formatting with go fmt * Updating all k8sclient data getters to return error value * Adding error message to k8sclient data accessors * Cleaning up setup for kubernetes * Removed verbose nils in initial k8s middleware instance * Set reasonable defaults if CoreFile has no parameters in the kubernetes block. (k8s endpoint, and name template) * Formatting cleanup -- go fmt
2016-07-07 01:40:58 -07:00
"errors"
"fmt"
"net"
plugin/kubernetes: Watch EndpointSlices (#4209) * initial commit Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * convert endpointslices to object.endpoints Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add opt hard coded for now Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * check that server supports endpointslice Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * fix import grouping Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * dont use endpoint slice in 1.17 or 1.18 Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * bump kind/k8s in circle ci to latest Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * drop k8s to latest supported by kind Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * use endpointslice name as endoint Name; index by Service name Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * use index key comparison in nsAddrs() Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add Index to object.Endpoint fixtures; fix direct endpoint name compares Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add slice dup check and test Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * todo Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add ep-slice skew dup test for reverse Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * nsaddrs: de-dup ep-slice skew dups; add test Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * remove todo Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * address various feedback Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * consolidate endpoint/slice informer code Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * fix endpoint informer consolidation; use clearer func name Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * log info; use major/minor fields Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * fix nsAddr and unit test Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add latency tracking for endpointslices Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * endpointslice latency unit test & fix Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * code shuffling Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * rename endpointslices in tests Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * remove de-dup from nsAddrs and test Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * remove de-dup from findServices / test Signed-off-by: Chris O'Haver <cohaver@infoblox.com>
2020-10-30 08:14:30 -04:00
"strconv"
2016-09-23 09:48:11 -03:00
"strings"
"time"
BK8s datasource middleware -- PoC for A records (#153) * Laying down kubernetes middleware foundation * Duplicated a bunch of code form etcd middleware * Duplicated code hacked to compile and load as a separate middleware * Adding verbose build option to Makefile * Removing stubzone and tls support tls and stubzone support was carried over from base etcd middleware code. Removing to simplify the kube middleware implementation. (For now.) * Adding conf directory for sample conf files * Removing stubzone support from query handler * Remove upstream and proxy from k8s corefile. Not sure that upstream or proxy makes sense for a k8s backed zone. * Comment out use of singleflight serialization * Removing parsing support for "upstream" directive from k8s * Removing upstream directive parsing code * Removing CNAME and TXT lookup implementation * Create README.md Brain-dump of DNS record name assembly and open work items. * Adding notes about wildcard handling * Adding basic k8s API client * Fleshing out methods on k8s connector * Remove PathPrefix from middleware init * Removing incorrect plural * Adding brute-force k8s service lookup functions * Initializing k8s API connector during startup * Hacking around to call k8s connector * Parsing incoming domain name into serviceName and namespace * Improving and simplifying k8s zone matching and label segmentation * Removing unused functions carried over from etcd middleware * Adding basic return of k8s data to DNS client * updated debugging println statements to flag with "[debug]" * removed code in kubernetes.go::Records that was a hold-over from etcd middleware. * Removed some random exploratory hacking. * Minior README.md updates * Updating with demo instructions * Updating README.md with CoreFile and removing completed TODO items * Updating conf file and README to reflect DNS response cache works * Disabling DNS response caching * Adding debug statement on entry to Records() * Changing port number in exampes to port 53. * Misc style and clarity changes * Removing empty function definitions * Adding comment to track future cleanup * Refactoring README to follow style of other middleware * Exposing dataobject field (typo)
2016-06-06 12:49:53 -07:00
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/etcd/msg"
"github.com/coredns/coredns/plugin/kubernetes/object"
"github.com/coredns/coredns/plugin/pkg/dnsutil"
"github.com/coredns/coredns/plugin/pkg/fall"
"github.com/coredns/coredns/request"
BK8s datasource middleware -- PoC for A records (#153) * Laying down kubernetes middleware foundation * Duplicated a bunch of code form etcd middleware * Duplicated code hacked to compile and load as a separate middleware * Adding verbose build option to Makefile * Removing stubzone and tls support tls and stubzone support was carried over from base etcd middleware code. Removing to simplify the kube middleware implementation. (For now.) * Adding conf directory for sample conf files * Removing stubzone support from query handler * Remove upstream and proxy from k8s corefile. Not sure that upstream or proxy makes sense for a k8s backed zone. * Comment out use of singleflight serialization * Removing parsing support for "upstream" directive from k8s * Removing upstream directive parsing code * Removing CNAME and TXT lookup implementation * Create README.md Brain-dump of DNS record name assembly and open work items. * Adding notes about wildcard handling * Adding basic k8s API client * Fleshing out methods on k8s connector * Remove PathPrefix from middleware init * Removing incorrect plural * Adding brute-force k8s service lookup functions * Initializing k8s API connector during startup * Hacking around to call k8s connector * Parsing incoming domain name into serviceName and namespace * Improving and simplifying k8s zone matching and label segmentation * Removing unused functions carried over from etcd middleware * Adding basic return of k8s data to DNS client * updated debugging println statements to flag with "[debug]" * removed code in kubernetes.go::Records that was a hold-over from etcd middleware. * Removed some random exploratory hacking. * Minior README.md updates * Updating with demo instructions * Updating README.md with CoreFile and removing completed TODO items * Updating conf file and README to reflect DNS response cache works * Disabling DNS response caching * Adding debug statement on entry to Records() * Changing port number in exampes to port 53. * Misc style and clarity changes * Removing empty function definitions * Adding comment to track future cleanup * Refactoring README to follow style of other middleware * Exposing dataobject field (typo)
2016-06-06 12:49:53 -07:00
k8s middleware cleanup, testcases, basic SRV (#181) * Removing unnecessary gitignore pattern * Updating Makefile to run unittests for subpackages * Adding Corefile validation to ignore overlapping zones * Fixing SRV query handling * Updating README.md now that SRV works * Fixing debug message, adding code comment * Clarifying implementation of zone normalization * "Overlapping zones" is ill-defined. Reimplemented zone overlap/subzone checking to contain these functions in k8s middleware and provide better code comments explaining the normalization. * Separate build verbosity from test verbosity * Cleaning up comments to match repo code style * Merging warning messages into single message * Moving function docs to before function declaration * Adding test cases for k8sclient connector * Tests cover connector create and setting base url * Fixed bugs in connector create and setting base url functions * Updaing README to group and order development work * Priority focused on achieving functional parity with SkyDNS. * Adding work items to README and cleaning up formatting * More README format cleaning * List formating * Refactoring k8s API call to allow dependency injection * Add test cases for data parsing from k8s into dataobject structures * URL is dependency-injected to allow replacement with a mock http server during test execution * Adding more data validation for JSON parsing tests * Adding test case for GetResourceList() * Adding notes about SkyDNS embedded IP and port record names * Marked test case implemented. * Fixing formatting for example command. * Fixing formatting * Adding notes about Docker image building. * Adding SkyDNS work item * Updating TODO list * Adding name template to Corefile to specify how k8s record names are assembled * Adding template support for multi-segment zones * Updating example CoreFile for k8s with template comment * Misc whitespace cleanup * Adding SkyDNS naming notes * Adding namespace filtering to CoreFile config * Updating example k8sCoreFile to specify namespaces * Removing unused codepath * Adding check for valid namespace * More README TODO restructuring to focus effort * Adding template validation while parsing CoreFile * Record name template is considered invalid if it contains a symbol of the form ${bar} where the symbol "${bar}" is not an accepted template symbol. * Refactoring generation of answer records * Parse typeName out of query string * Refactor answer record creation as operation over list of ServiceItems * Moving k8s API caching into SkyDNS equivalency segment * Adding function to assemble record names from template * Warning: This commit may be broken. Syncing to get laptop code over to dev machine. * More todo notes * Adding comment describing sample test data. * Update k8sCorefile * Adding comment * Adding filtering support for kubernetes "type" * Required refactoring to support reuse of the StringInSlice function. * Cleaning up formatting * Adding note about SkyDNS supporting word "any". * baseUrl -> baseURL * Also removed debug statement from core/setup/kubernetes.go * Fixing test breaking from Url -> URL naming changes * Changing record name template language ${...} -> {...} * Fix formatting with go fmt * Updating all k8sclient data getters to return error value * Adding error message to k8sclient data accessors * Cleaning up setup for kubernetes * Removed verbose nils in initial k8s middleware instance * Set reasonable defaults if CoreFile has no parameters in the kubernetes block. (k8s endpoint, and name template) * Formatting cleanup -- go fmt
2016-07-07 01:40:58 -07:00
"github.com/miekg/dns"
api "k8s.io/api/core/v1"
discovery "k8s.io/api/discovery/v1"
discoveryV1beta1 "k8s.io/api/discovery/v1beta1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
meta "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
)
// Kubernetes implements a plugin that connects to a Kubernetes cluster.
BK8s datasource middleware -- PoC for A records (#153) * Laying down kubernetes middleware foundation * Duplicated a bunch of code form etcd middleware * Duplicated code hacked to compile and load as a separate middleware * Adding verbose build option to Makefile * Removing stubzone and tls support tls and stubzone support was carried over from base etcd middleware code. Removing to simplify the kube middleware implementation. (For now.) * Adding conf directory for sample conf files * Removing stubzone support from query handler * Remove upstream and proxy from k8s corefile. Not sure that upstream or proxy makes sense for a k8s backed zone. * Comment out use of singleflight serialization * Removing parsing support for "upstream" directive from k8s * Removing upstream directive parsing code * Removing CNAME and TXT lookup implementation * Create README.md Brain-dump of DNS record name assembly and open work items. * Adding notes about wildcard handling * Adding basic k8s API client * Fleshing out methods on k8s connector * Remove PathPrefix from middleware init * Removing incorrect plural * Adding brute-force k8s service lookup functions * Initializing k8s API connector during startup * Hacking around to call k8s connector * Parsing incoming domain name into serviceName and namespace * Improving and simplifying k8s zone matching and label segmentation * Removing unused functions carried over from etcd middleware * Adding basic return of k8s data to DNS client * updated debugging println statements to flag with "[debug]" * removed code in kubernetes.go::Records that was a hold-over from etcd middleware. * Removed some random exploratory hacking. * Minior README.md updates * Updating with demo instructions * Updating README.md with CoreFile and removing completed TODO items * Updating conf file and README to reflect DNS response cache works * Disabling DNS response caching * Adding debug statement on entry to Records() * Changing port number in exampes to port 53. * Misc style and clarity changes * Removing empty function definitions * Adding comment to track future cleanup * Refactoring README to follow style of other middleware * Exposing dataobject field (typo)
2016-06-06 12:49:53 -07:00
type Kubernetes struct {
Next plugin.Handler
Zones []string
Upstream Upstreamer
APIServerList []string
APICertAuth string
APIClientCert string
APIClientKey string
ClientConfig clientcmd.ClientConfig
APIConn dnsController
Namespaces map[string]struct{}
podMode string
endpointNameMode bool
Fall fall.F
ttl uint32
2018-02-12 14:27:16 -05:00
opts dnsControlOpts
primaryZoneIndex int
localIPs []net.IP
autoPathSearch []string // Local search path from /etc/resolv.conf. Needed for autopath.
}
// Upstreamer is used to resolve CNAME or other external targets
type Upstreamer interface {
Lookup(ctx context.Context, state request.Request, name string, typ uint16) (*dns.Msg, error)
}
2018-01-29 13:16:13 -05:00
// New returns a initialized Kubernetes. It default interfaceAddrFunc to return 127.0.0.1. All other
// values default to their zero value, primaryZoneIndex will thus point to the first zone.
func New(zones []string) *Kubernetes {
k := new(Kubernetes)
k.Zones = zones
k.Namespaces = make(map[string]struct{})
k.podMode = podModeDisabled
k.ttl = defaultTTL
return k
}
2017-01-11 16:23:10 -05:00
const (
// podModeDisabled is the default value where pod requests are ignored
podModeDisabled = "disabled"
// podModeVerified is where Pod requests are answered only if they exist
podModeVerified = "verified"
2019-08-15 21:15:23 +08:00
// podModeInsecure is where pod requests are answered without verifying they exist
podModeInsecure = "insecure"
// DNSSchemaVersion is the schema version: https://github.com/kubernetes/dns/blob/master/docs/specification.md
DNSSchemaVersion = "1.1.0"
// Svc is the DNS schema for kubernetes services
Svc = "svc"
// Pod is the DNS schema for kubernetes pods
Pod = "pod"
// defaultTTL to apply to all answers.
defaultTTL = 5
2017-01-11 16:23:10 -05:00
)
var (
errNoItems = errors.New("no items found")
errNsNotExposed = errors.New("namespace is not exposed")
errInvalidRequest = errors.New("invalid query name")
)
// Services implements the ServiceBackend interface.
func (k *Kubernetes) Services(ctx context.Context, state request.Request, exact bool, opt plugin.Options) (svcs []msg.Service, err error) {
// We're looking again at types, which we've already done in ServeDNS, but there are some types k8s just can't answer.
switch state.QType() {
case dns.TypeTXT:
// 1 label + zone, label must be "dns-version".
t, _ := dnsutil.TrimZone(state.Name(), state.Zone)
segs := dns.SplitDomainName(t)
if len(segs) != 1 {
return nil, nil
}
if segs[0] != "dns-version" {
return nil, nil
}
svc := msg.Service{Text: DNSSchemaVersion, TTL: 28800, Key: msg.Path(state.QName(), coredns)}
return []msg.Service{svc}, nil
case dns.TypeNS:
// We can only get here if the qname equals the zone, see ServeDNS in handler.go.
nss := k.nsAddrs(false, state.Zone)
var svcs []msg.Service
for _, ns := range nss {
if ns.Header().Rrtype == dns.TypeA {
svcs = append(svcs, msg.Service{Host: ns.(*dns.A).A.String(), Key: msg.Path(ns.Header().Name, coredns), TTL: k.ttl})
continue
}
if ns.Header().Rrtype == dns.TypeAAAA {
svcs = append(svcs, msg.Service{Host: ns.(*dns.AAAA).AAAA.String(), Key: msg.Path(ns.Header().Name, coredns), TTL: k.ttl})
}
}
return svcs, nil
}
if isDefaultNS(state.Name(), state.Zone) {
nss := k.nsAddrs(false, state.Zone)
var svcs []msg.Service
for _, ns := range nss {
if ns.Header().Rrtype == dns.TypeA && state.QType() == dns.TypeA {
svcs = append(svcs, msg.Service{Host: ns.(*dns.A).A.String(), Key: msg.Path(state.QName(), coredns), TTL: k.ttl})
continue
}
if ns.Header().Rrtype == dns.TypeAAAA && state.QType() == dns.TypeAAAA {
svcs = append(svcs, msg.Service{Host: ns.(*dns.AAAA).AAAA.String(), Key: msg.Path(state.QName(), coredns), TTL: k.ttl})
}
}
return svcs, nil
}
s, e := k.Records(ctx, state, false)
// SRV for external services is not yet implemented, so remove those records.
if state.QType() != dns.TypeSRV {
return s, e
}
internal := []msg.Service{}
for _, svc := range s {
if t, _ := svc.HostType(); t != dns.TypeCNAME {
internal = append(internal, svc)
}
2017-01-15 14:37:18 +00:00
}
return internal, e
2017-01-15 14:37:18 +00:00
}
// primaryZone will return the first non-reverse zone being handled by this plugin
func (k *Kubernetes) primaryZone() string { return k.Zones[k.primaryZoneIndex] }
// Lookup implements the ServiceBackend interface.
func (k *Kubernetes) Lookup(ctx context.Context, state request.Request, name string, typ uint16) (*dns.Msg, error) {
return k.Upstream.Lookup(ctx, state, name, typ)
}
// IsNameError implements the ServiceBackend interface.
func (k *Kubernetes) IsNameError(err error) bool {
return err == errNoItems || err == errNsNotExposed || err == errInvalidRequest
}
func (k *Kubernetes) getClientConfig() (*rest.Config, error) {
if k.ClientConfig != nil {
return k.ClientConfig.ClientConfig()
}
2017-06-23 18:02:45 -04:00
loadingRules := &clientcmd.ClientConfigLoadingRules{}
overrides := &clientcmd.ConfigOverrides{}
clusterinfo := clientcmdapi.Cluster{}
authinfo := clientcmdapi.AuthInfo{}
// Connect to API from in cluster
if len(k.APIServerList) == 0 {
cc, err := rest.InClusterConfig()
if err != nil {
return nil, err
}
cc.ContentType = "application/vnd.kubernetes.protobuf"
return cc, err
}
// Connect to API from out of cluster
// Only the first one is used. We will deprecate multiple endpoints later.
clusterinfo.Server = k.APIServerList[0]
if len(k.APICertAuth) > 0 {
clusterinfo.CertificateAuthority = k.APICertAuth
}
if len(k.APIClientCert) > 0 {
authinfo.ClientCertificate = k.APIClientCert
}
if len(k.APIClientKey) > 0 {
authinfo.ClientKey = k.APIClientKey
}
overrides.ClusterInfo = clusterinfo
overrides.AuthInfo = authinfo
clientConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, overrides)
cc, err := clientConfig.ClientConfig()
if err != nil {
return nil, err
}
cc.ContentType = "application/vnd.kubernetes.protobuf"
return cc, err
}
2018-02-12 14:27:16 -05:00
// InitKubeCache initializes a new Kubernetes cache.
func (k *Kubernetes) InitKubeCache(ctx context.Context) (onStart func() error, onShut func() error, err error) {
config, err := k.getClientConfig()
if err != nil {
return nil, nil, err
}
kubeClient, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, nil, fmt.Errorf("failed to create kubernetes notification controller: %q", err)
}
2018-02-12 14:27:16 -05:00
if k.opts.labelSelector != nil {
var selector labels.Selector
2018-02-12 14:27:16 -05:00
selector, err = meta.LabelSelectorAsSelector(k.opts.labelSelector)
if err != nil {
return nil, nil, fmt.Errorf("unable to create Selector for LabelSelector '%s': %q", k.opts.labelSelector, err)
}
2018-02-12 14:27:16 -05:00
k.opts.selector = selector
}
if k.opts.namespaceLabelSelector != nil {
var selector labels.Selector
selector, err = meta.LabelSelectorAsSelector(k.opts.namespaceLabelSelector)
if err != nil {
return nil, nil, fmt.Errorf("unable to create Selector for LabelSelector '%s': %q", k.opts.namespaceLabelSelector, err)
}
k.opts.namespaceSelector = selector
}
2018-02-12 14:27:16 -05:00
k.opts.initPodCache = k.podMode == podModeVerified
k.opts.zones = k.Zones
k.opts.endpointNameMode = k.endpointNameMode
k.APIConn = newdnsController(ctx, kubeClient, k.opts)
initEndpointWatch := k.opts.initEndpointsCache
onStart = func() error {
go func() {
if initEndpointWatch {
// Revert to watching Endpoints for incompatible K8s.
// This can be removed when all supported k8s versions support endpointslices.
ok, v := k.endpointSliceSupported(kubeClient)
if !ok {
k.APIConn.(*dnsControl).WatchEndpoints(ctx)
}
// Revert to EndpointSlice v1beta1 if v1 is not supported
if ok && v == discoveryV1beta1.SchemeGroupVersion.String() {
k.APIConn.(*dnsControl).WatchEndpointSliceV1beta1(ctx)
}
}
k.APIConn.Run()
}()
timeout := 5 * time.Second
timeoutTicker := time.NewTicker(timeout)
defer timeoutTicker.Stop()
logDelay := 500 * time.Millisecond
logTicker := time.NewTicker(logDelay)
defer logTicker.Stop()
checkSyncTicker := time.NewTicker(100 * time.Millisecond)
defer checkSyncTicker.Stop()
for {
select {
case <-checkSyncTicker.C:
if k.APIConn.HasSynced() {
return nil
}
case <-logTicker.C:
log.Info("waiting for Kubernetes API before starting server")
case <-timeoutTicker.C:
log.Warning("starting server with unsynced Kubernetes API")
return nil
}
}
plugin/kubernetes: Watch EndpointSlices (#4209) * initial commit Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * convert endpointslices to object.endpoints Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add opt hard coded for now Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * check that server supports endpointslice Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * fix import grouping Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * dont use endpoint slice in 1.17 or 1.18 Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * bump kind/k8s in circle ci to latest Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * drop k8s to latest supported by kind Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * use endpointslice name as endoint Name; index by Service name Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * use index key comparison in nsAddrs() Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add Index to object.Endpoint fixtures; fix direct endpoint name compares Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add slice dup check and test Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * todo Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add ep-slice skew dup test for reverse Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * nsaddrs: de-dup ep-slice skew dups; add test Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * remove todo Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * address various feedback Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * consolidate endpoint/slice informer code Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * fix endpoint informer consolidation; use clearer func name Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * log info; use major/minor fields Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * fix nsAddr and unit test Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add latency tracking for endpointslices Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * endpointslice latency unit test & fix Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * code shuffling Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * rename endpointslices in tests Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * remove de-dup from nsAddrs and test Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * remove de-dup from findServices / test Signed-off-by: Chris O'Haver <cohaver@infoblox.com>
2020-10-30 08:14:30 -04:00
}
onShut = func() error {
return k.APIConn.Stop()
}
return onStart, onShut, err
}
// endpointSliceSupported will determine which endpoint object type to watch (endpointslices or endpoints)
// based on the supportability of endpointslices in the API and server version. It will return true when endpointslices
// should be watched, and false when endpoints should be watched.
// If the API supports discovery, and the server versions >= 1.19, true is returned.
// Also returned is the discovery version supported: "v1" if v1 is supported, and v1beta1 if v1beta1 is supported and
// v1 is not supported.
// This function should be removed, when all supported versions of k8s support v1.
func (k *Kubernetes) endpointSliceSupported(kubeClient *kubernetes.Clientset) (bool, string) {
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
logTicker := time.NewTicker(10 * time.Second)
defer logTicker.Stop()
var connErr error
for {
select {
case <-logTicker.C:
if connErr == nil {
continue
}
log.Warningf("Kubernetes API connection failure: %v", connErr)
case <-ticker.C:
sv, err := kubeClient.ServerVersion()
if err != nil {
connErr = err
continue
}
// Disable use of endpoint slices for k8s versions 1.18 and earlier. The Endpointslices API was enabled
// by default in 1.17 but Service -> Pod proxy continued to use Endpoints by default until 1.19.
// DNS results should be built from the same source data that the proxy uses. This decision assumes
// k8s EndpointSliceProxying feature gate is at the default (i.e. only enabled for k8s >= 1.19).
major, _ := strconv.Atoi(sv.Major)
minor, _ := strconv.Atoi(strings.TrimRight(sv.Minor, "+"))
if major <= 1 && minor <= 18 {
log.Info("Watching Endpoints instead of EndpointSlices in k8s versions < 1.19")
return false, ""
}
// Enable use of endpoint slices if the API supports the discovery api
_, err = kubeClient.Discovery().ServerResourcesForGroupVersion(discovery.SchemeGroupVersion.String())
if err == nil {
return true, discovery.SchemeGroupVersion.String()
} else if !kerrors.IsNotFound(err) {
connErr = err
continue
}
_, err = kubeClient.Discovery().ServerResourcesForGroupVersion(discoveryV1beta1.SchemeGroupVersion.String())
if err == nil {
return true, discoveryV1beta1.SchemeGroupVersion.String()
} else if !kerrors.IsNotFound(err) {
connErr = err
continue
}
// Disable use of endpoint slices in case that it is disabled in k8s versions 1.19 and newer.
log.Info("Endpointslices API disabled. Watching Endpoints instead.")
return false, ""
}
}
}
// Records looks up services in kubernetes.
func (k *Kubernetes) Records(ctx context.Context, state request.Request, exact bool) ([]msg.Service, error) {
r, e := parseRequest(state.Name(), state.Zone)
if e != nil {
return nil, e
}
if r.podOrSvc == "" {
return nil, nil
}
if dnsutil.IsReverse(state.Name()) > 0 {
return nil, errNoItems
}
if !k.namespaceExposed(r.namespace) {
2016-11-11 16:56:15 +00:00
return nil, errNsNotExposed
k8s middleware cleanup, testcases, basic SRV (#181) * Removing unnecessary gitignore pattern * Updating Makefile to run unittests for subpackages * Adding Corefile validation to ignore overlapping zones * Fixing SRV query handling * Updating README.md now that SRV works * Fixing debug message, adding code comment * Clarifying implementation of zone normalization * "Overlapping zones" is ill-defined. Reimplemented zone overlap/subzone checking to contain these functions in k8s middleware and provide better code comments explaining the normalization. * Separate build verbosity from test verbosity * Cleaning up comments to match repo code style * Merging warning messages into single message * Moving function docs to before function declaration * Adding test cases for k8sclient connector * Tests cover connector create and setting base url * Fixed bugs in connector create and setting base url functions * Updaing README to group and order development work * Priority focused on achieving functional parity with SkyDNS. * Adding work items to README and cleaning up formatting * More README format cleaning * List formating * Refactoring k8s API call to allow dependency injection * Add test cases for data parsing from k8s into dataobject structures * URL is dependency-injected to allow replacement with a mock http server during test execution * Adding more data validation for JSON parsing tests * Adding test case for GetResourceList() * Adding notes about SkyDNS embedded IP and port record names * Marked test case implemented. * Fixing formatting for example command. * Fixing formatting * Adding notes about Docker image building. * Adding SkyDNS work item * Updating TODO list * Adding name template to Corefile to specify how k8s record names are assembled * Adding template support for multi-segment zones * Updating example CoreFile for k8s with template comment * Misc whitespace cleanup * Adding SkyDNS naming notes * Adding namespace filtering to CoreFile config * Updating example k8sCoreFile to specify namespaces * Removing unused codepath * Adding check for valid namespace * More README TODO restructuring to focus effort * Adding template validation while parsing CoreFile * Record name template is considered invalid if it contains a symbol of the form ${bar} where the symbol "${bar}" is not an accepted template symbol. * Refactoring generation of answer records * Parse typeName out of query string * Refactor answer record creation as operation over list of ServiceItems * Moving k8s API caching into SkyDNS equivalency segment * Adding function to assemble record names from template * Warning: This commit may be broken. Syncing to get laptop code over to dev machine. * More todo notes * Adding comment describing sample test data. * Update k8sCorefile * Adding comment * Adding filtering support for kubernetes "type" * Required refactoring to support reuse of the StringInSlice function. * Cleaning up formatting * Adding note about SkyDNS supporting word "any". * baseUrl -> baseURL * Also removed debug statement from core/setup/kubernetes.go * Fixing test breaking from Url -> URL naming changes * Changing record name template language ${...} -> {...} * Fix formatting with go fmt * Updating all k8sclient data getters to return error value * Adding error message to k8sclient data accessors * Cleaning up setup for kubernetes * Removed verbose nils in initial k8s middleware instance * Set reasonable defaults if CoreFile has no parameters in the kubernetes block. (k8s endpoint, and name template) * Formatting cleanup -- go fmt
2016-07-07 01:40:58 -07:00
}
if r.podOrSvc == Pod {
pods, err := k.findPods(r, state.Zone)
return pods, err
k8s middleware cleanup, testcases, basic SRV (#181) * Removing unnecessary gitignore pattern * Updating Makefile to run unittests for subpackages * Adding Corefile validation to ignore overlapping zones * Fixing SRV query handling * Updating README.md now that SRV works * Fixing debug message, adding code comment * Clarifying implementation of zone normalization * "Overlapping zones" is ill-defined. Reimplemented zone overlap/subzone checking to contain these functions in k8s middleware and provide better code comments explaining the normalization. * Separate build verbosity from test verbosity * Cleaning up comments to match repo code style * Merging warning messages into single message * Moving function docs to before function declaration * Adding test cases for k8sclient connector * Tests cover connector create and setting base url * Fixed bugs in connector create and setting base url functions * Updaing README to group and order development work * Priority focused on achieving functional parity with SkyDNS. * Adding work items to README and cleaning up formatting * More README format cleaning * List formating * Refactoring k8s API call to allow dependency injection * Add test cases for data parsing from k8s into dataobject structures * URL is dependency-injected to allow replacement with a mock http server during test execution * Adding more data validation for JSON parsing tests * Adding test case for GetResourceList() * Adding notes about SkyDNS embedded IP and port record names * Marked test case implemented. * Fixing formatting for example command. * Fixing formatting * Adding notes about Docker image building. * Adding SkyDNS work item * Updating TODO list * Adding name template to Corefile to specify how k8s record names are assembled * Adding template support for multi-segment zones * Updating example CoreFile for k8s with template comment * Misc whitespace cleanup * Adding SkyDNS naming notes * Adding namespace filtering to CoreFile config * Updating example k8sCoreFile to specify namespaces * Removing unused codepath * Adding check for valid namespace * More README TODO restructuring to focus effort * Adding template validation while parsing CoreFile * Record name template is considered invalid if it contains a symbol of the form ${bar} where the symbol "${bar}" is not an accepted template symbol. * Refactoring generation of answer records * Parse typeName out of query string * Refactor answer record creation as operation over list of ServiceItems * Moving k8s API caching into SkyDNS equivalency segment * Adding function to assemble record names from template * Warning: This commit may be broken. Syncing to get laptop code over to dev machine. * More todo notes * Adding comment describing sample test data. * Update k8sCorefile * Adding comment * Adding filtering support for kubernetes "type" * Required refactoring to support reuse of the StringInSlice function. * Cleaning up formatting * Adding note about SkyDNS supporting word "any". * baseUrl -> baseURL * Also removed debug statement from core/setup/kubernetes.go * Fixing test breaking from Url -> URL naming changes * Changing record name template language ${...} -> {...} * Fix formatting with go fmt * Updating all k8sclient data getters to return error value * Adding error message to k8sclient data accessors * Cleaning up setup for kubernetes * Removed verbose nils in initial k8s middleware instance * Set reasonable defaults if CoreFile has no parameters in the kubernetes block. (k8s endpoint, and name template) * Formatting cleanup -- go fmt
2016-07-07 01:40:58 -07:00
}
BK8s datasource middleware -- PoC for A records (#153) * Laying down kubernetes middleware foundation * Duplicated a bunch of code form etcd middleware * Duplicated code hacked to compile and load as a separate middleware * Adding verbose build option to Makefile * Removing stubzone and tls support tls and stubzone support was carried over from base etcd middleware code. Removing to simplify the kube middleware implementation. (For now.) * Adding conf directory for sample conf files * Removing stubzone support from query handler * Remove upstream and proxy from k8s corefile. Not sure that upstream or proxy makes sense for a k8s backed zone. * Comment out use of singleflight serialization * Removing parsing support for "upstream" directive from k8s * Removing upstream directive parsing code * Removing CNAME and TXT lookup implementation * Create README.md Brain-dump of DNS record name assembly and open work items. * Adding notes about wildcard handling * Adding basic k8s API client * Fleshing out methods on k8s connector * Remove PathPrefix from middleware init * Removing incorrect plural * Adding brute-force k8s service lookup functions * Initializing k8s API connector during startup * Hacking around to call k8s connector * Parsing incoming domain name into serviceName and namespace * Improving and simplifying k8s zone matching and label segmentation * Removing unused functions carried over from etcd middleware * Adding basic return of k8s data to DNS client * updated debugging println statements to flag with "[debug]" * removed code in kubernetes.go::Records that was a hold-over from etcd middleware. * Removed some random exploratory hacking. * Minior README.md updates * Updating with demo instructions * Updating README.md with CoreFile and removing completed TODO items * Updating conf file and README to reflect DNS response cache works * Disabling DNS response caching * Adding debug statement on entry to Records() * Changing port number in exampes to port 53. * Misc style and clarity changes * Removing empty function definitions * Adding comment to track future cleanup * Refactoring README to follow style of other middleware * Exposing dataobject field (typo)
2016-06-06 12:49:53 -07:00
services, err := k.findServices(r, state.Zone)
return services, err
k8s middleware cleanup, testcases, basic SRV (#181) * Removing unnecessary gitignore pattern * Updating Makefile to run unittests for subpackages * Adding Corefile validation to ignore overlapping zones * Fixing SRV query handling * Updating README.md now that SRV works * Fixing debug message, adding code comment * Clarifying implementation of zone normalization * "Overlapping zones" is ill-defined. Reimplemented zone overlap/subzone checking to contain these functions in k8s middleware and provide better code comments explaining the normalization. * Separate build verbosity from test verbosity * Cleaning up comments to match repo code style * Merging warning messages into single message * Moving function docs to before function declaration * Adding test cases for k8sclient connector * Tests cover connector create and setting base url * Fixed bugs in connector create and setting base url functions * Updaing README to group and order development work * Priority focused on achieving functional parity with SkyDNS. * Adding work items to README and cleaning up formatting * More README format cleaning * List formating * Refactoring k8s API call to allow dependency injection * Add test cases for data parsing from k8s into dataobject structures * URL is dependency-injected to allow replacement with a mock http server during test execution * Adding more data validation for JSON parsing tests * Adding test case for GetResourceList() * Adding notes about SkyDNS embedded IP and port record names * Marked test case implemented. * Fixing formatting for example command. * Fixing formatting * Adding notes about Docker image building. * Adding SkyDNS work item * Updating TODO list * Adding name template to Corefile to specify how k8s record names are assembled * Adding template support for multi-segment zones * Updating example CoreFile for k8s with template comment * Misc whitespace cleanup * Adding SkyDNS naming notes * Adding namespace filtering to CoreFile config * Updating example k8sCoreFile to specify namespaces * Removing unused codepath * Adding check for valid namespace * More README TODO restructuring to focus effort * Adding template validation while parsing CoreFile * Record name template is considered invalid if it contains a symbol of the form ${bar} where the symbol "${bar}" is not an accepted template symbol. * Refactoring generation of answer records * Parse typeName out of query string * Refactor answer record creation as operation over list of ServiceItems * Moving k8s API caching into SkyDNS equivalency segment * Adding function to assemble record names from template * Warning: This commit may be broken. Syncing to get laptop code over to dev machine. * More todo notes * Adding comment describing sample test data. * Update k8sCorefile * Adding comment * Adding filtering support for kubernetes "type" * Required refactoring to support reuse of the StringInSlice function. * Cleaning up formatting * Adding note about SkyDNS supporting word "any". * baseUrl -> baseURL * Also removed debug statement from core/setup/kubernetes.go * Fixing test breaking from Url -> URL naming changes * Changing record name template language ${...} -> {...} * Fix formatting with go fmt * Updating all k8sclient data getters to return error value * Adding error message to k8sclient data accessors * Cleaning up setup for kubernetes * Removed verbose nils in initial k8s middleware instance * Set reasonable defaults if CoreFile has no parameters in the kubernetes block. (k8s endpoint, and name template) * Formatting cleanup -- go fmt
2016-07-07 01:40:58 -07:00
}
BK8s datasource middleware -- PoC for A records (#153) * Laying down kubernetes middleware foundation * Duplicated a bunch of code form etcd middleware * Duplicated code hacked to compile and load as a separate middleware * Adding verbose build option to Makefile * Removing stubzone and tls support tls and stubzone support was carried over from base etcd middleware code. Removing to simplify the kube middleware implementation. (For now.) * Adding conf directory for sample conf files * Removing stubzone support from query handler * Remove upstream and proxy from k8s corefile. Not sure that upstream or proxy makes sense for a k8s backed zone. * Comment out use of singleflight serialization * Removing parsing support for "upstream" directive from k8s * Removing upstream directive parsing code * Removing CNAME and TXT lookup implementation * Create README.md Brain-dump of DNS record name assembly and open work items. * Adding notes about wildcard handling * Adding basic k8s API client * Fleshing out methods on k8s connector * Remove PathPrefix from middleware init * Removing incorrect plural * Adding brute-force k8s service lookup functions * Initializing k8s API connector during startup * Hacking around to call k8s connector * Parsing incoming domain name into serviceName and namespace * Improving and simplifying k8s zone matching and label segmentation * Removing unused functions carried over from etcd middleware * Adding basic return of k8s data to DNS client * updated debugging println statements to flag with "[debug]" * removed code in kubernetes.go::Records that was a hold-over from etcd middleware. * Removed some random exploratory hacking. * Minior README.md updates * Updating with demo instructions * Updating README.md with CoreFile and removing completed TODO items * Updating conf file and README to reflect DNS response cache works * Disabling DNS response caching * Adding debug statement on entry to Records() * Changing port number in exampes to port 53. * Misc style and clarity changes * Removing empty function definitions * Adding comment to track future cleanup * Refactoring README to follow style of other middleware * Exposing dataobject field (typo)
2016-06-06 12:49:53 -07:00
func endpointHostname(addr object.EndpointAddress, endpointNameMode bool) string {
if addr.Hostname != "" {
return addr.Hostname
}
if endpointNameMode && addr.TargetRefName != "" {
return addr.TargetRefName
}
if strings.Contains(addr.IP, ".") {
return strings.Replace(addr.IP, ".", "-", -1)
}
if strings.Contains(addr.IP, ":") {
return strings.Replace(addr.IP, ":", "-", -1)
}
return ""
}
func (k *Kubernetes) findPods(r recordRequest, zone string) (pods []msg.Service, err error) {
if k.podMode == podModeDisabled {
return nil, errNoItems
2017-01-11 16:23:10 -05:00
}
namespace := r.namespace
if !k.namespaceExposed(namespace) {
return nil, errNoItems
}
podname := r.service
// handle empty pod name
if podname == "" {
if k.namespaceExposed(namespace) {
// NODATA
return nil, nil
}
// NXDOMAIN
return nil, errNoItems
}
zonePath := msg.Path(zone, coredns)
ip := ""
2017-01-11 16:23:10 -05:00
if strings.Count(podname, "-") == 3 && !strings.Contains(podname, "--") {
ip = strings.ReplaceAll(podname, "-", ".")
2017-01-11 16:23:10 -05:00
} else {
ip = strings.ReplaceAll(podname, "-", ":")
2017-01-11 16:23:10 -05:00
}
if k.podMode == podModeInsecure {
if !k.namespaceExposed(namespace) { // namespace does not exist
return nil, errNoItems
}
// If ip does not parse as an IP address, we return an error, otherwise we assume a CNAME and will try to resolve it in backend_lookup.go
if net.ParseIP(ip) == nil {
return nil, errNoItems
}
return []msg.Service{{Key: strings.Join([]string{zonePath, Pod, namespace, podname}, "/"), Host: ip, TTL: k.ttl}}, err
}
// PodModeVerified
err = errNoItems
2017-01-11 16:23:10 -05:00
for _, p := range k.APIConn.PodIndex(ip) {
// check for matching ip and namespace
if ip == p.PodIP && match(namespace, p.Namespace) {
s := msg.Service{Key: strings.Join([]string{zonePath, Pod, namespace, podname}, "/"), Host: ip, TTL: k.ttl}
pods = append(pods, s)
2017-01-11 16:23:10 -05:00
err = nil
}
}
return pods, err
}
// findServices returns the services matching r from the cache.
func (k *Kubernetes) findServices(r recordRequest, zone string) (services []msg.Service, err error) {
if !k.namespaceExposed(r.namespace) {
return nil, errNoItems
}
// handle empty service name
if r.service == "" {
if k.namespaceExposed(r.namespace) {
// NODATA
return nil, nil
}
// NXDOMAIN
return nil, errNoItems
}
err = errNoItems
var (
endpointsListFunc func() []*object.Endpoints
endpointsList []*object.Endpoints
serviceList []*object.Service
)
idx := object.ServiceKey(r.service, r.namespace)
serviceList = k.APIConn.SvcIndex(idx)
endpointsListFunc = func() []*object.Endpoints { return k.APIConn.EpIndex(idx) }
zonePath := msg.Path(zone, coredns)
for _, svc := range serviceList {
if !(match(r.namespace, svc.Namespace) && match(r.service, svc.Name)) {
continue
}
// If "ignore empty_service" option is set and no endpoints exist, return NXDOMAIN unless
// it's a headless or externalName service (covered below).
if k.opts.ignoreEmptyService && svc.Type != api.ServiceTypeExternalName && !svc.Headless() { // serve NXDOMAIN if no endpoint is able to answer
podsCount := 0
for _, ep := range endpointsListFunc() {
for _, eps := range ep.Subsets {
podsCount += len(eps.Addresses)
}
}
if podsCount == 0 {
continue
}
}
// External service
if svc.Type == api.ServiceTypeExternalName {
s := msg.Service{Key: strings.Join([]string{zonePath, Svc, svc.Namespace, svc.Name}, "/"), Host: svc.ExternalName, TTL: k.ttl}
if t, _ := s.HostType(); t == dns.TypeCNAME {
s.Key = strings.Join([]string{zonePath, Svc, svc.Namespace, svc.Name}, "/")
services = append(services, s)
err = nil
}
continue
}
// Endpoint query or headless service
if svc.Headless() || r.endpoint != "" {
if endpointsList == nil {
endpointsList = endpointsListFunc()
}
plugin/kubernetes: Watch EndpointSlices (#4209) * initial commit Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * convert endpointslices to object.endpoints Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add opt hard coded for now Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * check that server supports endpointslice Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * fix import grouping Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * dont use endpoint slice in 1.17 or 1.18 Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * bump kind/k8s in circle ci to latest Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * drop k8s to latest supported by kind Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * use endpointslice name as endoint Name; index by Service name Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * use index key comparison in nsAddrs() Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add Index to object.Endpoint fixtures; fix direct endpoint name compares Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add slice dup check and test Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * todo Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add ep-slice skew dup test for reverse Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * nsaddrs: de-dup ep-slice skew dups; add test Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * remove todo Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * address various feedback Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * consolidate endpoint/slice informer code Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * fix endpoint informer consolidation; use clearer func name Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * log info; use major/minor fields Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * fix nsAddr and unit test Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add latency tracking for endpointslices Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * endpointslice latency unit test & fix Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * code shuffling Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * rename endpointslices in tests Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * remove de-dup from nsAddrs and test Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * remove de-dup from findServices / test Signed-off-by: Chris O'Haver <cohaver@infoblox.com>
2020-10-30 08:14:30 -04:00
for _, ep := range endpointsList {
plugin/kubernetes: Watch EndpointSlices (#4209) * initial commit Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * convert endpointslices to object.endpoints Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add opt hard coded for now Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * check that server supports endpointslice Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * fix import grouping Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * dont use endpoint slice in 1.17 or 1.18 Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * bump kind/k8s in circle ci to latest Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * drop k8s to latest supported by kind Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * use endpointslice name as endoint Name; index by Service name Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * use index key comparison in nsAddrs() Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add Index to object.Endpoint fixtures; fix direct endpoint name compares Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add slice dup check and test Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * todo Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add ep-slice skew dup test for reverse Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * nsaddrs: de-dup ep-slice skew dups; add test Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * remove todo Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * address various feedback Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * consolidate endpoint/slice informer code Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * fix endpoint informer consolidation; use clearer func name Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * log info; use major/minor fields Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * fix nsAddr and unit test Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * add latency tracking for endpointslices Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * endpointslice latency unit test & fix Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * code shuffling Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * rename endpointslices in tests Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * remove de-dup from nsAddrs and test Signed-off-by: Chris O'Haver <cohaver@infoblox.com> * remove de-dup from findServices / test Signed-off-by: Chris O'Haver <cohaver@infoblox.com>
2020-10-30 08:14:30 -04:00
if object.EndpointsKey(svc.Name, svc.Namespace) != ep.Index {
continue
}
for _, eps := range ep.Subsets {
for _, addr := range eps.Addresses {
// See comments in parse.go parseRequest about the endpoint handling.
if r.endpoint != "" {
if !match(r.endpoint, endpointHostname(addr, k.endpointNameMode)) {
continue
}
}
for _, p := range eps.Ports {
if !(matchPortAndProtocol(r.port, p.Name, r.protocol, p.Protocol)) {
continue
}
s := msg.Service{Host: addr.IP, Port: int(p.Port), TTL: k.ttl}
s.Key = strings.Join([]string{zonePath, Svc, svc.Namespace, svc.Name, endpointHostname(addr, k.endpointNameMode)}, "/")
err = nil
services = append(services, s)
}
}
}
}
continue
}
// ClusterIP service
for _, p := range svc.Ports {
if !(matchPortAndProtocol(r.port, p.Name, r.protocol, string(p.Protocol))) {
Adding wildcard support (#190) * Commenting out unused functions. TODO: remove when it is not needed * Update README with namespace and template example * Adding note about changing the record name format via a template * Adding test scripts to automate k8s startup * Automating k8s namespace creation * Adding automation to start 4 k8s services * Updating documentation for k8s tests * Avoid downloading kubectl if already exists * Adding debug statement when namespace is not exposed. * Adding basic kubernetes integration tests * Makefile now contains a "testk8s" target. This target requires k8s to be running. * Adding test/kubernetes_test.go file with a couple of basic A record tests. * Updating k8s integration tests to only run k8s integration tests * Adding support for namespace wildcards * Refactoring to move filtering logic to kubernetes.go file * go fmt fixes * Adding wildcard support for namespaces and service names * Kubernetes integration tests updated for A records. * Expanded record name assembly for answer section not yet implemented. * Refactoring to focus k8sclient code just on accessing k8s API. Filtering now handled in kubernetes.go * Adding wildcard test cases * Adding skydns startup script. (To allow side by side testing of wildcards.) * Commenting out record name assmebly based on NameTemplate. Need to improve template before this makes sense. * Adding basic SRV integration tests * Need to add verification for additional answer section * Fixing comments and formatting * Moving wildcard constants to vars * Travis test execution appears to be failing on access to these constants * Fixing access to util package * Trying to work around Travis test bug * Reverting to access kubernetes/util as "util" Travis breakage is due to "Infoblox-CTO" in src path
2016-07-14 14:50:14 -07:00
continue
}
err = nil
for _, ip := range svc.ClusterIPs {
s := msg.Service{Host: ip, Port: int(p.Port), TTL: k.ttl}
s.Key = strings.Join([]string{zonePath, Svc, svc.Namespace, svc.Name}, "/")
services = append(services, s)
}
}
Adding wildcard support (#190) * Commenting out unused functions. TODO: remove when it is not needed * Update README with namespace and template example * Adding note about changing the record name format via a template * Adding test scripts to automate k8s startup * Automating k8s namespace creation * Adding automation to start 4 k8s services * Updating documentation for k8s tests * Avoid downloading kubectl if already exists * Adding debug statement when namespace is not exposed. * Adding basic kubernetes integration tests * Makefile now contains a "testk8s" target. This target requires k8s to be running. * Adding test/kubernetes_test.go file with a couple of basic A record tests. * Updating k8s integration tests to only run k8s integration tests * Adding support for namespace wildcards * Refactoring to move filtering logic to kubernetes.go file * go fmt fixes * Adding wildcard support for namespaces and service names * Kubernetes integration tests updated for A records. * Expanded record name assembly for answer section not yet implemented. * Refactoring to focus k8sclient code just on accessing k8s API. Filtering now handled in kubernetes.go * Adding wildcard test cases * Adding skydns startup script. (To allow side by side testing of wildcards.) * Commenting out record name assmebly based on NameTemplate. Need to improve template before this makes sense. * Adding basic SRV integration tests * Need to add verification for additional answer section * Fixing comments and formatting * Moving wildcard constants to vars * Travis test execution appears to be failing on access to these constants * Fixing access to util package * Trying to work around Travis test bug * Reverting to access kubernetes/util as "util" Travis breakage is due to "Infoblox-CTO" in src path
2016-07-14 14:50:14 -07:00
}
return services, err
BK8s datasource middleware -- PoC for A records (#153) * Laying down kubernetes middleware foundation * Duplicated a bunch of code form etcd middleware * Duplicated code hacked to compile and load as a separate middleware * Adding verbose build option to Makefile * Removing stubzone and tls support tls and stubzone support was carried over from base etcd middleware code. Removing to simplify the kube middleware implementation. (For now.) * Adding conf directory for sample conf files * Removing stubzone support from query handler * Remove upstream and proxy from k8s corefile. Not sure that upstream or proxy makes sense for a k8s backed zone. * Comment out use of singleflight serialization * Removing parsing support for "upstream" directive from k8s * Removing upstream directive parsing code * Removing CNAME and TXT lookup implementation * Create README.md Brain-dump of DNS record name assembly and open work items. * Adding notes about wildcard handling * Adding basic k8s API client * Fleshing out methods on k8s connector * Remove PathPrefix from middleware init * Removing incorrect plural * Adding brute-force k8s service lookup functions * Initializing k8s API connector during startup * Hacking around to call k8s connector * Parsing incoming domain name into serviceName and namespace * Improving and simplifying k8s zone matching and label segmentation * Removing unused functions carried over from etcd middleware * Adding basic return of k8s data to DNS client * updated debugging println statements to flag with "[debug]" * removed code in kubernetes.go::Records that was a hold-over from etcd middleware. * Removed some random exploratory hacking. * Minior README.md updates * Updating with demo instructions * Updating README.md with CoreFile and removing completed TODO items * Updating conf file and README to reflect DNS response cache works * Disabling DNS response caching * Adding debug statement on entry to Records() * Changing port number in exampes to port 53. * Misc style and clarity changes * Removing empty function definitions * Adding comment to track future cleanup * Refactoring README to follow style of other middleware * Exposing dataobject field (typo)
2016-06-06 12:49:53 -07:00
}
Cherry-pick: Implement notifies for transfer plugin (#3972) (#4142) * Implement notifies for transfer plugin (#3972) * Fix notifies in transfer plugin Signed-off-by: Miek Gieben <miek@miek.nl> * Make it compile Signed-off-by: Miek Gieben <miek@miek.nl> * Port more plugins Signed-off-by: Miek Gieben <miek@miek.nl> * golint Signed-off-by: Miek Gieben <miek@miek.nl> * Fix tests Signed-off-by: Miek Gieben <miek@miek.nl> * Fix notifies in transfer plugin Signed-off-by: Miek Gieben <miek@miek.nl> * Make it compile Signed-off-by: Miek Gieben <miek@miek.nl> * Port more plugins Signed-off-by: Miek Gieben <miek@miek.nl> * golint Signed-off-by: Miek Gieben <miek@miek.nl> * Fix tests Signed-off-by: Miek Gieben <miek@miek.nl> * Fix tests Signed-off-by: Miek Gieben <miek@miek.nl> * really fix test Signed-off-by: Miek Gieben <miek@miek.nl> * Implement ixfr fallback and unify file and auto for transfering Signed-off-by: Miek Gieben <miek@miek.nl> * Add transfer tests copied and modified from #3452 Signed-off-by: Miek Gieben <miek@miek.nl> * Test correct selection of plugin Signed-off-by: Miek Gieben <miek@miek.nl> * add upstream back in Signed-off-by: Miek Gieben <miek@miek.nl> * Implement ixfr fallback and unify file and auto for transfering Signed-off-by: Miek Gieben <miek@miek.nl> * fix test Signed-off-by: Miek Gieben <miek@miek.nl> * properly merge Signed-off-by: Miek Gieben <miek@miek.nl> * Remove plugin/kubernetes/setup_transfer_test.go Signed-off-by: Yong Tang <yong.tang.github@outlook.com> Co-authored-by: Miek Gieben <miek@miek.nl>
2020-09-24 11:30:39 -07:00
// Serial return the SOA serial.
func (k *Kubernetes) Serial(state request.Request) uint32 { return uint32(k.APIConn.Modified(false)) }
Cherry-pick: Implement notifies for transfer plugin (#3972) (#4142) * Implement notifies for transfer plugin (#3972) * Fix notifies in transfer plugin Signed-off-by: Miek Gieben <miek@miek.nl> * Make it compile Signed-off-by: Miek Gieben <miek@miek.nl> * Port more plugins Signed-off-by: Miek Gieben <miek@miek.nl> * golint Signed-off-by: Miek Gieben <miek@miek.nl> * Fix tests Signed-off-by: Miek Gieben <miek@miek.nl> * Fix notifies in transfer plugin Signed-off-by: Miek Gieben <miek@miek.nl> * Make it compile Signed-off-by: Miek Gieben <miek@miek.nl> * Port more plugins Signed-off-by: Miek Gieben <miek@miek.nl> * golint Signed-off-by: Miek Gieben <miek@miek.nl> * Fix tests Signed-off-by: Miek Gieben <miek@miek.nl> * Fix tests Signed-off-by: Miek Gieben <miek@miek.nl> * really fix test Signed-off-by: Miek Gieben <miek@miek.nl> * Implement ixfr fallback and unify file and auto for transfering Signed-off-by: Miek Gieben <miek@miek.nl> * Add transfer tests copied and modified from #3452 Signed-off-by: Miek Gieben <miek@miek.nl> * Test correct selection of plugin Signed-off-by: Miek Gieben <miek@miek.nl> * add upstream back in Signed-off-by: Miek Gieben <miek@miek.nl> * Implement ixfr fallback and unify file and auto for transfering Signed-off-by: Miek Gieben <miek@miek.nl> * fix test Signed-off-by: Miek Gieben <miek@miek.nl> * properly merge Signed-off-by: Miek Gieben <miek@miek.nl> * Remove plugin/kubernetes/setup_transfer_test.go Signed-off-by: Yong Tang <yong.tang.github@outlook.com> Co-authored-by: Miek Gieben <miek@miek.nl>
2020-09-24 11:30:39 -07:00
// MinTTL returns the minimal TTL.
func (k *Kubernetes) MinTTL(state request.Request) uint32 { return k.ttl }
// match checks if a and b are equal.
func match(a, b string) bool {
return strings.EqualFold(a, b)
Adding wildcard support (#190) * Commenting out unused functions. TODO: remove when it is not needed * Update README with namespace and template example * Adding note about changing the record name format via a template * Adding test scripts to automate k8s startup * Automating k8s namespace creation * Adding automation to start 4 k8s services * Updating documentation for k8s tests * Avoid downloading kubectl if already exists * Adding debug statement when namespace is not exposed. * Adding basic kubernetes integration tests * Makefile now contains a "testk8s" target. This target requires k8s to be running. * Adding test/kubernetes_test.go file with a couple of basic A record tests. * Updating k8s integration tests to only run k8s integration tests * Adding support for namespace wildcards * Refactoring to move filtering logic to kubernetes.go file * go fmt fixes * Adding wildcard support for namespaces and service names * Kubernetes integration tests updated for A records. * Expanded record name assembly for answer section not yet implemented. * Refactoring to focus k8sclient code just on accessing k8s API. Filtering now handled in kubernetes.go * Adding wildcard test cases * Adding skydns startup script. (To allow side by side testing of wildcards.) * Commenting out record name assmebly based on NameTemplate. Need to improve template before this makes sense. * Adding basic SRV integration tests * Need to add verification for additional answer section * Fixing comments and formatting * Moving wildcard constants to vars * Travis test execution appears to be failing on access to these constants * Fixing access to util package * Trying to work around Travis test bug * Reverting to access kubernetes/util as "util" Travis breakage is due to "Infoblox-CTO" in src path
2016-07-14 14:50:14 -07:00
}
// matchPortAndProtocol matches port and protocol, permitting the the 'a' inputs to be wild
func matchPortAndProtocol(aPort, bPort, aProtocol, bProtocol string) bool {
return (match(aPort, bPort) || aPort == "") && (match(aProtocol, bProtocol) || aProtocol == "")
}
const coredns = "c" // used as a fake key prefix in msg.Service