From 5725aaac6aae83d78d7dba4667d2ccc523933790 Mon Sep 17 00:00:00 2001 From: Sercan Degirmenci Date: Fri, 9 Feb 2018 23:40:33 +0300 Subject: [PATCH] initial v2 resolver implementation cleanup api and change Readme add comments to some functions don't send empty address list to grpc fix grpc name resolution add tests to parse target fix license --- LICENSE | 202 ++++++++++++++++++++++++++++++++++++++++ README.md | 32 ++++--- balancer.go | 135 --------------------------- balancer_test.go | 199 --------------------------------------- builder.go | 237 +++++++++++++++++++++++++++++++++++++++++++++++ builder_test.go | 144 ++++++++++++++++++++++++++++ kubernetes.go | 80 ++++++++++++++-- models.go | 14 ++- resolver.go | 86 ----------------- stream.go | 4 +- watcher.go | 95 ------------------- 11 files changed, 690 insertions(+), 538 deletions(-) create mode 100644 LICENSE delete mode 100644 balancer.go delete mode 100644 balancer_test.go create mode 100644 builder.go create mode 100644 builder_test.go delete mode 100644 resolver.go delete mode 100644 watcher.go diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5ae44e5 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2017 Sercan Degirmenci + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/README.md b/README.md index ba3a804..4035f62 100644 --- a/README.md +++ b/README.md @@ -2,17 +2,27 @@ Grpc Client-Side Load Balancer with Kubernetes name resolver ```go -//New balancer for default namespace -balancer := kuberesolver.New() -//Dials with RoundRobin lb and kubernetes name resolver. if url schema is not 'kubernetes' than uses dns -cc, err := balancer.Dial("kubernetes://service-name:portname", opts...) -// or, add balancer as dial option bu this does not fallback to dns if schema is not 'kubernetes' -cc, err := grpc.Dial("kubernetes://service-name:portname", balancer.DialOption(), opts...) +// Register kuberesolver to grpc +kuberesolver.RegisterInCluster() +// is same as +resolver.Register(kuberesolver.NewBuilder(nil)) +// you can bring your own k8s client, below is default behaviour +client, err := kuberesolver.NewInClusterK8sClient() +resolver.Register(kuberesolver.NewBuilder(client)) + +// USAGE: +// if schema is 'kubernetes' then grpc will use kuberesolver to resolve addresses +cc, err := grpc.Dial("kubernetes:///service-name.namespace:portname", opts...) ``` -An url can be one of the following + +An url can be one of the following, [grpc naming docs](https://github.com/grpc/grpc/blob/master/doc/naming.md) ``` -kubernetes://service-name:portname uses kubernetes api to fetch endpoints and port names -kubernetes://service-name:8080 uses kubernetes api to fetch endpoints but uses given port -dns://service-name:8080 does not use lb -service-name:8080 +kubernetes:///service-name:8080 +kubernetes:///service-name:portname +kubernetes:///service-name.namespace:8080 + +kubernetes://namespace/service-name:8080 +kubernetes://service-name:8080/ +kubernetes://service-name.namespace:8080/ + ``` diff --git a/balancer.go b/balancer.go deleted file mode 100644 index d03162d..0000000 --- a/balancer.go +++ /dev/null @@ -1,135 +0,0 @@ -package kuberesolver - -import ( - "errors" - "fmt" - "net/url" - "strconv" - "strings" - - "google.golang.org/grpc" - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/naming" -) - -type Balancer struct { - Namespace string - client *k8sClient - resolvers []*kubeResolver -} - -type TargetUrlType int32 - -const ( - TargetTypeDNS TargetUrlType = 0 - TargetTypeKubernetes TargetUrlType = 1 - kubernetesSchema = "kubernetes" - dnsSchema = "dns" -) - -type targetInfo struct { - urlType TargetUrlType - target string - port string - resolveByPortName bool - useFirstPort bool -} - -func parseTarget(target string) (targetInfo, error) { - u, err := url.Parse(target) - if err != nil { - return targetInfo{}, err - } - ti := targetInfo{} - if u.Scheme == kubernetesSchema { - ti.urlType = TargetTypeKubernetes - spl := strings.Split(u.Host, ":") - if len(spl) == 2 { - ti.target = spl[0] - ti.port = spl[1] - ti.useFirstPort = false - if _, err := strconv.Atoi(ti.port); err != nil { - ti.resolveByPortName = true - } else { - ti.resolveByPortName = false - } - } else { - ti.target = spl[0] - ti.useFirstPort = true - } - } else if u.Scheme == dnsSchema { - ti.urlType = TargetTypeDNS - ti.target = u.Host - } else { - ti.urlType = TargetTypeDNS - ti.target = target - } - return ti, nil -} - -//Resolver returns Resolver for grpc -func (b *Balancer) Resolver() naming.Resolver { - return newResolver(b.client, b.Namespace) -} - -//DialOption returns grpc.DialOption with RoundRobin balancer and resolver -func (b *Balancer) DialOption() grpc.DialOption { - rs := newResolver(b.client, b.Namespace) - return grpc.WithBalancer(grpc.RoundRobin(rs)) -} - -// Dial calls grpc.Dial, also parses target and uses load balancer if necessary -func (b *Balancer) Dial(target string, opts ...grpc.DialOption) (*grpc.ClientConn, error) { - pt, err := parseTarget(target) - if err != nil { - return nil, err - } - switch pt.urlType { - case TargetTypeKubernetes: - if b.client == nil { - return nil, errors.New("application is not running inside kubernetes") - } - grpclog.Printf("kuberesolver: using kubernetes resolver target=%s", pt.target) - rs := newResolver(b.client, b.Namespace) - b.resolvers = append(b.resolvers, rs) - opts := append(opts, grpc.WithBalancer(grpc.RoundRobin(rs))) - return grpc.Dial(target, opts...) - case TargetTypeDNS: - return grpc.Dial(pt.target, opts...) - default: - return nil, errors.New("Unknown target type") - } -} - -func (b *Balancer) Healthy() error { - for _, r := range b.resolvers { - if r.watcher != nil { - if len(r.watcher.endpoints) == 0 { - return fmt.Errorf("target does not have endpoints") - } - } - } - return nil -} - -// IsInCluster returns true if application is running inside kubernetes cluster -func (b *Balancer) IsInCluster() bool { - return b.client != nil -} - -// New creates a Balancer with "default" namespace -func New() *Balancer { - return NewWithNamespace("default") -} - -// NewWithNamespace creates a Balancer with given namespace. -func NewWithNamespace(namespace string) *Balancer { - client, err := newInClusterClient() - if err != nil { - grpclog.Printf("kuberesolver: application is not running inside kubernetes") - } - return &Balancer{ - Namespace: namespace, - client: client, - } -} diff --git a/balancer_test.go b/balancer_test.go deleted file mode 100644 index 6e2ab9a..0000000 --- a/balancer_test.go +++ /dev/null @@ -1,199 +0,0 @@ -package kuberesolver - -import ( - "crypto/tls" - "crypto/x509" - "fmt" - "io/ioutil" - "net/http" - "os" - "reflect" - "testing" - "time" - - "google.golang.org/grpc/naming" -) - -func TestParseTarget(t *testing.T) { - // kubernetes://otsimo-watch:portname - // kubernetes://otsimo-watch:45638 - // dns://10.0.1.4:2341 - // 10.0.1.4:2341 - tests := []struct { - target string - result targetInfo - err error - }{ - { - target: "kubernetes://otsimo-watch:portname", - result: targetInfo{ - urlType: TargetTypeKubernetes, - target: "otsimo-watch", - port: "portname", - resolveByPortName: true, - useFirstPort: false, - }, - }, - { - target: "kubernetes://service-name:5638", - result: targetInfo{ - urlType: TargetTypeKubernetes, - target: "service-name", - port: "5638", - resolveByPortName: false, - useFirstPort: false, - }, - }, - { - target: "kubernetes://service-name", - result: targetInfo{ - urlType: TargetTypeKubernetes, - target: "service-name", - port: "", - resolveByPortName: false, - useFirstPort: true, - }, - }, - { - target: "dns://10.0.1.4:2341", - result: targetInfo{ - urlType: TargetTypeDNS, - target: "10.0.1.4:2341", - port: "", - resolveByPortName: false, - useFirstPort: false, - }, - }, - { - target: "10.0.1.4:2341", - result: targetInfo{ - urlType: TargetTypeDNS, - target: "10.0.1.4:2341", - port: "", - resolveByPortName: false, - useFirstPort: false, - }, - }, - { - target: "services.otsimo.com:2315", - result: targetInfo{ - urlType: TargetTypeDNS, - target: "services.otsimo.com:2315", - port: "", - resolveByPortName: false, - useFirstPort: false, - }, - }, - { - target: "services.otsimo.com", - result: targetInfo{ - urlType: TargetTypeDNS, - target: "services.otsimo.com", - port: "", - resolveByPortName: false, - useFirstPort: false, - }, - }, - { - target: "tcp://10.0.1.4:2341", - result: targetInfo{ - urlType: TargetTypeDNS, - target: "tcp://10.0.1.4:2341", - port: "", - resolveByPortName: false, - useFirstPort: false, - }, - }, - } - - for i, test := range tests { - ti, err := parseTarget(test.target) - if test.err != nil { - if !reflect.DeepEqual(err, test.err) { - t.Fatal(fmt.Errorf("case %d failed, errors are not equal", i)) - } - continue - } else { - if err != nil { - t.Fatal(fmt.Errorf("case %d failed, errors must be nil but found, %v", i, err)) - } - } - if !reflect.DeepEqual(ti, test.result) { - t.Fatal(fmt.Errorf("case %d failed, want='%+v' got='%+v'", i, test.result, ti)) - } - } -} - -func TestConnection(t *testing.T) { - caCrtFile := os.Getenv("TEST_K8S_CA_CRT") - clientCrtFile := os.Getenv("TEST_K8S_CLIENT_CRT") - clientKeyFile := os.Getenv("TEST_K8S_CLIENT_KEY") - apiHost := os.Getenv("TEST_K8S_API_HOST") - service := os.Getenv("TEST_K8S_SERVICE") - servicePort := os.Getenv("TEST_K8S_SERVICE_PORT") - if len(caCrtFile) == 0 || len(clientCrtFile) == 0 || len(clientKeyFile) == 0 || len(apiHost) == 0 { - t.Fatal("") - } - ca, err := ioutil.ReadFile(caCrtFile) - if err != nil { - t.Fatal(err) - } - certPool := x509.NewCertPool() - certPool.AppendCertsFromPEM(ca) - cert, err := tls.LoadX509KeyPair(clientCrtFile, clientKeyFile) - if err != nil { - t.Fatal(err) - } - transport := &http.Transport{TLSClientConfig: &tls.Config{ - MinVersion: tls.VersionTLS10, - RootCAs: certPool, - Certificates: []tls.Certificate{cert}, - }} - client := &k8sClient{ - host: apiHost, - httpClient: &http.Client{Transport: transport}, - } - ti := targetInfo{ - urlType: TargetTypeKubernetes, - target: service, - port: servicePort, - resolveByPortName: false, - useFirstPort: false, - } - kr := newResolver(client, "default", ti) - w, err := kr.Resolve(ti.target) - if err != nil { - t.Fatal(err) - } - res := make(chan struct { - up []*naming.Update - }) - errChan := make(chan error) - go func() { - for { - u2, err := w.Next() - if err != nil { - errChan <- err - } else { - res <- struct { - up []*naming.Update - }{ - up: u2, - } - } - } - }() - for { - select { - case rrr := <-res: - for _, r := range rrr.up { - fmt.Printf("u1: %s %d\n", r.Addr, r.Op) - } - case <-time.After(time.Second * 180): - w.Close() - t.Fatal("time out") - case err := <-errChan: - t.Fatal(err) - } - } -} diff --git a/builder.go b/builder.go new file mode 100644 index 0000000..523f42b --- /dev/null +++ b/builder.go @@ -0,0 +1,237 @@ +package kuberesolver + +import ( + "fmt" + "io" + "net" + "strconv" + "strings" + "sync" + "time" + + "golang.org/x/net/context" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/resolver" +) + +const ( + kubernetesSchema = "kubernetes" +) + +type targetInfo struct { + serviceName string + serviceNamespace string + port string + resolveByPortName bool + useFirstPort bool +} + +// RegisterInCluster registers the kuberesolver builder to grpc +func RegisterInCluster() { + resolver.Register(NewBuilder(nil)) +} + +// NewBuilder creates a kubeBuilder which is used to factory Kuberesolvers. +func NewBuilder(client K8sClient) resolver.Builder { + return &kubeBuilder{ + k8sClient: client, + } +} + +type kubeBuilder struct { + k8sClient K8sClient +} + +func parseResolverTarget(target resolver.Target) (targetInfo, error) { + // kubernetes://default/service:port + end := target.Endpoint + snamespace := target.Authority + // kubernetes://service.default:port/ + if end == "" { + end = target.Authority + snamespace = "default" + } + // kubernetes:///service:port + // kubernetes://service:port/ + if snamespace == "" { + snamespace = "default" + } + + ti := targetInfo{} + if end == "" { + return targetInfo{}, fmt.Errorf("target(%q) is empty", target) + } + var name string + var port string + if strings.LastIndex(end, ":") < 0 { + name = end + port = "" + ti.useFirstPort = true + } else { + var err error + name, port, err = net.SplitHostPort(end) + if err != nil { + return targetInfo{}, fmt.Errorf("target endpoint='%s' is invalid. grpc target is %#v, err=%v", end, target, err) + } + } + + namesplit := strings.SplitN(name, ".", 2) + sname := name + if len(namesplit) == 2 { + sname = namesplit[0] + snamespace = namesplit[1] + } + ti.serviceName = sname + ti.serviceNamespace = snamespace + ti.port = port + if !ti.useFirstPort { + if _, err := strconv.Atoi(ti.port); err != nil { + ti.resolveByPortName = true + } else { + ti.resolveByPortName = false + } + } + return ti, nil +} + +// Build creates a new resolver for the given target. +// +// gRPC dial calls Build synchronously, and fails if the returned error is +// not nil. +func (b *kubeBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOption) (resolver.Resolver, error) { + if b.k8sClient == nil { + if cl, err := NewInClusterK8sClient(); err == nil { + b.k8sClient = cl + } else { + return nil, err + } + } + ctx, cancel := context.WithCancel(context.Background()) + ti, err := parseResolverTarget(target) + if err != nil { + return nil, err + } + r := &kResolver{ + target: ti, + ctx: ctx, + cancel: cancel, + cc: cc, + rn: make(chan struct{}, 1), + k8sClient: b.k8sClient, + } + r.wg.Add(1) + go until(func() { + err := r.watch() + if err != nil && err != io.EOF { + grpclog.Errorf("kuberesolver: watching ended with error='%v', will reconnect again", err) + } + }, time.Second, ctx.Done()) + return r, nil +} + +// Scheme returns the scheme supported by this resolver. +// Scheme is defined at https://github.com/grpc/grpc/blob/master/doc/naming.md. +func (b *kubeBuilder) Scheme() string { + return kubernetesSchema +} + +type kResolver struct { + target targetInfo + ctx context.Context + cancel context.CancelFunc + cc resolver.ClientConn + // rn channel is used by ResolveNow() to force an immediate resolution of the target. + rn chan struct{} + k8sClient K8sClient + // wg is used to enforce Close() to return after the watcher() goroutine has finished. + // Otherwise, data race will be possible. [Race Example] in dns_resolver_test we + // replace the real lookup functions with mocked ones to facilitate testing. + // If Close() doesn't wait for watcher() goroutine finishes, race detector sometimes + // will warns lookup (READ the lookup function pointers) inside watcher() goroutine + // has data race with replaceNetFunc (WRITE the lookup function pointers). + wg sync.WaitGroup +} + +// ResolveNow will be called by gRPC to try to resolve the target name again. +// It's just a hint, resolver can ignore this if it's not necessary. +func (k *kResolver) ResolveNow(resolver.ResolveNowOption) { + select { + case k.rn <- struct{}{}: + default: + } +} + +// Close closes the resolver. +func (k *kResolver) Close() { + k.cancel() + k.wg.Wait() +} + +func (k *kResolver) makeAddresses(e Endpoints) ([]resolver.Address, string) { + var newAddrs []resolver.Address + for _, subset := range e.Subsets { + port := "" + if k.target.useFirstPort { + port = strconv.Itoa(subset.Ports[0].Port) + } else if k.target.resolveByPortName { + for _, p := range subset.Ports { + if p.Name == k.target.port { + port = strconv.Itoa(p.Port) + break + } + } + } else { + port = k.target.port + } + + if len(port) == 0 { + port = strconv.Itoa(subset.Ports[0].Port) + } + + for _, address := range subset.Addresses { + sname := k.target.serviceName + if address.TargetRef != nil { + sname = address.TargetRef.Name + } + newAddrs = append(newAddrs, resolver.Address{ + Type: resolver.Backend, + Addr: net.JoinHostPort(address.IP, port), + ServerName: sname, + Metadata: nil, + }) + } + } + return newAddrs, "" +} + +func (k *kResolver) handle(e Endpoints) { + result, _ := k.makeAddresses(e) + // k.cc.NewServiceConfig(sc) + if len(result) > 0 { + k.cc.NewAddress(result) + } +} + +func (k *kResolver) watch() error { + sw, err := watchEndpoints(k.k8sClient, k.target.serviceNamespace, k.target.serviceName) + if err != nil { + return err + } + for { + select { + case <-k.ctx.Done(): + return nil + case <-k.rn: + e, err := getEndpoints(k.k8sClient, k.target.serviceNamespace, k.target.serviceName) + if err == nil { + k.handle(e) + } + case up, hasMore := <-sw.ResultChan(): + if hasMore { + k.handle(up.Object) + } else { + return nil + } + } + } +} diff --git a/builder_test.go b/builder_test.go new file mode 100644 index 0000000..1993dc1 --- /dev/null +++ b/builder_test.go @@ -0,0 +1,144 @@ +package kuberesolver + +import ( + "fmt" + "strings" + "testing" + + "google.golang.org/grpc/resolver" +) + +func newTestBuilder() resolver.Builder { + cl := NewInsecureK8sClient("http://127.0.0.1:8001") + return NewBuilder(cl) +} + +type fakeConn struct { + cmp chan struct{} + found []string +} + +func (fc *fakeConn) NewAddress(addresses []resolver.Address) { + for i, a := range addresses { + fc.found = append(fc.found, a.Addr) + fmt.Printf("%d, address: %s\n", i, a.Addr) + fmt.Printf("%d, servername: %s\n", i, a.ServerName) + fmt.Printf("%d, type: %+v\n", i, a.Type) + } + fc.cmp <- struct{}{} +} + +func (*fakeConn) NewServiceConfig(serviceConfig string) { + fmt.Printf("serviceConfig: %s\n", serviceConfig) +} + +func TestBuilder(t *testing.T) { + bl := newTestBuilder() + fc := &fakeConn{ + cmp: make(chan struct{}), + } + rs, err := bl.Build(resolver.Target{Endpoint: "kube-dns.kube-system:53", Scheme: "kubernetes", Authority: ""}, fc, resolver.BuildOption{}) + if err != nil { + t.Fatal(err) + } + <-fc.cmp + if len(fc.found) == 0 { + t.Fatal("could not found endpoints") + } + fmt.Printf("ResolveNow \n") + rs.ResolveNow(resolver.ResolveNowOption{}) + <-fc.cmp +} + +// +// split2 returns the values from strings.SplitN(s, sep, 2). +// If sep is not found, it returns ("", s, false) instead. +func split2(s, sep string) (string, string, bool) { + spl := strings.SplitN(s, sep, 2) + if len(spl) < 2 { + return "", "", false + } + return spl[0], spl[1], true +} + +// copied from grpc package to test parsing endpoints +// +// parseTarget splits target into a struct containing scheme, authority and +// endpoint. +func parseTarget(target string) (ret resolver.Target) { + var ok bool + ret.Scheme, ret.Endpoint, ok = split2(target, "://") + if !ok { + return resolver.Target{Endpoint: target} + } + ret.Authority, ret.Endpoint, _ = split2(ret.Endpoint, "/") + return ret +} + +func TestParseResolverTarget(t *testing.T) { + for _, test := range []struct { + target resolver.Target + want targetInfo + err bool + }{ + {resolver.Target{"", "", ""}, targetInfo{"", "", "", false, false}, true}, + {resolver.Target{"", "a", ""}, targetInfo{"a", "default", "", false, true}, false}, + {resolver.Target{"", "", "a"}, targetInfo{"a", "default", "", false, true}, false}, + {resolver.Target{"", "a", "b"}, targetInfo{"b", "a", "", false, true}, false}, + {resolver.Target{"", "a.b", ""}, targetInfo{"a", "b", "", false, true}, false}, + {resolver.Target{"", "", "a.b"}, targetInfo{"a", "b", "", false, true}, false}, + {resolver.Target{"", "", "a.b:80"}, targetInfo{"a", "b", "80", false, false}, false}, + {resolver.Target{"", "", "a.b:port"}, targetInfo{"a", "b", "port", true, false}, false}, + {resolver.Target{"", "a", "b:port"}, targetInfo{"b", "a", "port", true, false}, false}, + {resolver.Target{"", "b.a:port", ""}, targetInfo{"b", "a", "port", true, false}, false}, + {resolver.Target{"", "b.a:80", ""}, targetInfo{"b", "a", "80", false, false}, false}, + } { + got, err := parseResolverTarget(test.target) + if err == nil && test.err { + t.Errorf("want error but got nil") + continue + } + if err != nil && !test.err { + t.Errorf("got '%v' error but don't want an error", err) + continue + } + if got != test.want { + t.Errorf("parseTarget(%q) = %+v, want %+v", test.target, got, test.want) + } + } +} + +func TestParseTargets(t *testing.T) { + for _, test := range []struct { + target string + want targetInfo + err bool + }{ + {"", targetInfo{}, true}, + {"kubernetes:///", targetInfo{}, true}, + {"kubernetes://a:30", targetInfo{}, true}, + {"kubernetes://a/", targetInfo{"a", "default", "", false, true}, false}, + {"kubernetes:///a", targetInfo{"a", "default", "", false, true}, false}, + {"kubernetes://a/b", targetInfo{"b", "a", "", false, true}, false}, + {"kubernetes://a.b/", targetInfo{"a", "b", "", false, true}, false}, + {"kubernetes:///a.b:80", targetInfo{"a", "b", "80", false, false}, false}, + {"kubernetes:///a.b:port", targetInfo{"a", "b", "port", true, false}, false}, + {"kubernetes:///a:port", targetInfo{"a", "default", "port", true, false}, false}, + {"kubernetes://x/a:port", targetInfo{"a", "x", "port", true, false}, false}, + {"kubernetes://a.x:port/", targetInfo{"a", "x", "port", true, false}, false}, + {"kubernetes://a.x:30/", targetInfo{"a", "x", "30", false, false}, false}, + } { + got, err := parseResolverTarget(parseTarget(test.target)) + if err == nil && test.err { + t.Errorf("want error but got nil") + continue + } + if err != nil && !test.err { + t.Errorf("got '%v' error but don't want an error", err) + continue + } + if got != test.want { + t.Errorf("parseTarget(%q) = %+v, want %+v", test.target, got, test.want) + } + } +} diff --git a/kubernetes.go b/kubernetes.go index 737880e..18925ea 100644 --- a/kubernetes.go +++ b/kubernetes.go @@ -3,11 +3,14 @@ package kuberesolver import ( "crypto/tls" "crypto/x509" + "encoding/json" "fmt" "io/ioutil" "net" "net/http" + "net/url" "os" + "strings" "time" ) @@ -16,13 +19,23 @@ const ( serviceAccountCACert = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" ) +// K8sClient is minimal kubernetes client interface +type K8sClient interface { + Do(req *http.Request) (*http.Response, error) + GetRequest(url string) (*http.Request, error) + Host() string +} + type k8sClient struct { host string token string httpClient *http.Client } -func (kc *k8sClient) getRequest(url string) (*http.Request, error) { +func (kc *k8sClient) GetRequest(url string) (*http.Request, error) { + if !strings.HasPrefix(url, kc.host) { + url = fmt.Sprintf("%s/%s", kc.host, url) + } req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err @@ -37,12 +50,12 @@ func (kc *k8sClient) Do(req *http.Request) (*http.Response, error) { return kc.httpClient.Do(req) } -/* -KUBERNETES_SERVICE_PORT=443 -KUBERNETES_SERVICE_PORT_HTTPS=443 -KUBERNETES_SERVICE_HOST=10.0.0.1 -*/ -func newInClusterClient() (*k8sClient, error) { +func (kc *k8sClient) Host() string { + return kc.host +} + +// NewInClusterK8sClient creates K8sClient if it is inside Kubernetes +func NewInClusterK8sClient() (K8sClient, error) { host, port := os.Getenv("KUBERNETES_SERVICE_HOST"), os.Getenv("KUBERNETES_SERVICE_PORT") if len(host) == 0 || len(port) == 0 { return nil, fmt.Errorf("unable to load in-cluster configuration, KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT must be defined") @@ -69,3 +82,56 @@ func newInClusterClient() (*k8sClient, error) { httpClient: httpClient, }, nil } + +// NewInsecureK8sClient creates an insecure k8s client which is suitable +// to connect kubernetes api behind proxy +func NewInsecureK8sClient(apiURL string) K8sClient { + return &k8sClient{ + host: apiURL, + httpClient: http.DefaultClient, + } +} + +func getEndpoints(client K8sClient, namespace, targetName string) (Endpoints, error) { + u, err := url.Parse(fmt.Sprintf("%s/api/v1/namespaces/%s/endpoints/%s", + client.Host(), namespace, targetName)) + if err != nil { + return Endpoints{}, err + } + req, err := client.GetRequest(u.String()) + if err != nil { + return Endpoints{}, err + } + resp, err := client.Do(req) + if err != nil { + return Endpoints{}, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return Endpoints{}, fmt.Errorf("invalid response code %d", resp.StatusCode) + } + result := Endpoints{} + err = json.NewDecoder(resp.Body).Decode(&result) + return result, err +} + +func watchEndpoints(client K8sClient, namespace, targetName string) (watchInterface, error) { + u, err := url.Parse(fmt.Sprintf("%s/api/v1/watch/namespaces/%s/endpoints/%s", + client.Host(), namespace, targetName)) + if err != nil { + return nil, err + } + req, err := client.GetRequest(u.String()) + if err != nil { + return nil, err + } + resp, err := client.Do(req) + if err != nil { + return nil, err + } + if resp.StatusCode != http.StatusOK { + defer resp.Body.Close() + return nil, fmt.Errorf("invalid response code %d", resp.StatusCode) + } + return newStreamWatcher(resp.Body), nil +} diff --git a/models.go b/models.go index 3cf13fa..167e361 100644 --- a/models.go +++ b/models.go @@ -23,8 +23,10 @@ type Endpoints struct { } type Metadata struct { - Name string `json:"name"` - ResourceVersion string `json:"resourceVersion"` + Name string `json:"name"` + Namespace string `json:"namespace"` + ResourceVersion string `json:"resourceVersion"` + Labels map[string]string `json:"labels"` } type Subset struct { @@ -33,9 +35,15 @@ type Subset struct { } type Address struct { - IP string `json:"ip"` + IP string `json:"ip"` + TargetRef *ObjectReference `json:"targetRef,omitempty"` } +type ObjectReference struct { + Kind string `json:"kind"` + Name string `json:"name"` + Namespace string `json:"namespace"` +} type Port struct { Name string `json:"name"` Port int `json:"port"` diff --git a/resolver.go b/resolver.go deleted file mode 100644 index 1c6a92d..0000000 --- a/resolver.go +++ /dev/null @@ -1,86 +0,0 @@ -package kuberesolver - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/url" - "time" - - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/naming" -) - -// kubeResolver resolves service names using Kubernetes endpoints. -type kubeResolver struct { - k8sClient *k8sClient - namespace string - watcher *watcher -} - -// NewResolver returns a new Kubernetes resolver. -func newResolver(client *k8sClient, namespace string) *kubeResolver { - if namespace == "" { - namespace = "default" - } - return &kubeResolver{client, namespace, nil} -} - -// Resolve creates a Kubernetes watcher for the named target. -func (r *kubeResolver) Resolve(target string) (naming.Watcher, error) { - pt, err := parseTarget(target) - if err != nil { - return nil, err - } - resultChan := make(chan watchResult) - stopCh := make(chan struct{}) - wtarget := pt.target - go until(func() { - err := r.watch(wtarget, stopCh, resultChan) - if err != nil { - grpclog.Printf("kuberesolver: watching ended with error='%v', will reconnect again", err) - } - }, time.Second, stopCh) - - r.watcher = &watcher{ - target: pt, - endpoints: make(map[string]interface{}), - stopCh: stopCh, - result: resultChan, - } - return r.watcher, nil -} - -func (r *kubeResolver) watch(target string, stopCh <-chan struct{}, resultCh chan<- watchResult) error { - u, err := url.Parse(fmt.Sprintf("%s/api/v1/watch/namespaces/%s/endpoints/%s", - r.k8sClient.host, r.namespace, target)) - if err != nil { - return err - } - req, err := r.k8sClient.getRequest(u.String()) - if err != nil { - return err - } - resp, err := r.k8sClient.Do(req) - if err != nil { - return err - } - if resp.StatusCode != http.StatusOK { - defer resp.Body.Close() - rbody, _ := ioutil.ReadAll(resp.Body) - return fmt.Errorf("invalid response code %d: %s", resp.StatusCode, rbody) - } - sw := newStreamWatcher(resp.Body) - for { - select { - case <-stopCh: - return nil - case up, more := <-sw.ResultChan(): - if more { - resultCh <- watchResult{err: nil, ep: &up} - } else { - return nil - } - } - } -} diff --git a/stream.go b/stream.go index 51aab49..30a600c 100644 --- a/stream.go +++ b/stream.go @@ -79,9 +79,9 @@ func (sw *streamWatcher) receive() { case io.EOF: // watch closed normally case io.ErrUnexpectedEOF: - grpclog.Printf("kuberesolver: Unexpected EOF during watch stream event decoding: %v", err) + grpclog.Infof("kuberesolver: Unexpected EOF during watch stream event decoding: %v", err) default: - grpclog.Printf("kuberesolver: Unable to decode an event from the watch stream: %v", err) + grpclog.Infof("kuberesolver: Unable to decode an event from the watch stream: %v", err) } return } diff --git a/watcher.go b/watcher.go deleted file mode 100644 index 42437bd..0000000 --- a/watcher.go +++ /dev/null @@ -1,95 +0,0 @@ -package kuberesolver - -import ( - "net" - "strconv" - "sync" - - "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/naming" -) - -type watchResult struct { - ep *Event - err error -} - -// A Watcher provides name resolution updates from Kubernetes endpoints -// identified by name. -type watcher struct { - target targetInfo - endpoints map[string]interface{} - stopCh chan struct{} - result chan watchResult - sync.Mutex - stopped bool -} - -// Close closes the watcher, cleaning up any open connections. -func (w *watcher) Close() { - close(w.stopCh) -} - -// Next updates the endpoints for the name being watched. -func (w *watcher) Next() ([]*naming.Update, error) { - updates := make([]*naming.Update, 0) - updatedEndpoints := make(map[string]interface{}) - var ep Event - - select { - case <-w.stopCh: - w.Lock() - if !w.stopped { - w.stopped = true - } - w.Unlock() - return updates, nil - case r := <-w.result: - if r.err == nil { - ep = *r.ep - } else { - return updates, r.err - } - } - for _, subset := range ep.Object.Subsets { - port := "" - if w.target.useFirstPort { - port = strconv.Itoa(subset.Ports[0].Port) - } else if w.target.resolveByPortName { - for _, p := range subset.Ports { - if p.Name == w.target.port { - port = strconv.Itoa(p.Port) - break - } - } - } else { - port = w.target.port - } - - if len(port) == 0 { - port = strconv.Itoa(subset.Ports[0].Port) - } - for _, address := range subset.Addresses { - endpoint := net.JoinHostPort(address.IP, port) - updatedEndpoints[endpoint] = nil - } - } - - // Create updates to add new endpoints. - for addr, md := range updatedEndpoints { - if _, ok := w.endpoints[addr]; !ok { - updates = append(updates, &naming.Update{naming.Add, addr, md}) - grpclog.Printf("kuberesolver: %s ADDED to %s", addr, w.target.target) - } - } - - // Create updates to delete old endpoints. - for addr := range w.endpoints { - if _, ok := updatedEndpoints[addr]; !ok { - updates = append(updates, &naming.Update{naming.Delete, addr, nil}) - grpclog.Printf("kuberesolver: %s DELETED from %s", addr, w.target.target) - } - } - w.endpoints = updatedEndpoints - return updates, nil -}