This repository has been archived by the owner on Jul 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathconsul.go
97 lines (83 loc) · 2.08 KB
/
consul.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// Package consul implements grpclb service discovery via Consul (consul.io).
// Service names may be specified as: svcname,tag1,tag2,tag3
package consul
import (
"fmt"
"strings"
"github.com/bsm/grpclb/balancer"
"github.com/hashicorp/consul/api"
)
type discovery struct {
*api.Client
}
// New returns an implementation of balancer.Discovery interface.
func New(config *api.Config) (balancer.Discovery, error) {
if config == nil {
config = api.DefaultConfig()
}
c, err := api.NewClient(config)
if err != nil {
return nil, err
}
return &discovery{Client: c}, nil
}
// Resolve implements balancer.Discovery
func (d *discovery) Resolve(target string) ([]string, error) {
service, tags := splitTarget(target)
return d.query(service, tags)
}
func (d *discovery) query(service string, tags []string) ([]string, error) {
var tag string
if len(tags) > 0 {
tag = tags[0]
}
// Query watcher
entries, _, err := d.Health().Service(service, tag, true, nil)
if err != nil {
return nil, err
}
// If more than one tag is passed, we need to filter
if len(tags) > 1 {
entries = filterEntries(entries, tags[1:])
}
return parseEntries(entries), nil
}
// --------------------------------------------------------------------
func splitTarget(target string) (service string, tags []string) {
parts := strings.Split(target, ",")
service = parts[0]
if len(parts) > 1 {
tags = parts[1:]
}
return
}
func parseEntries(entries []*api.ServiceEntry) []string {
res := make([]string, len(entries))
for i, entry := range entries {
addr := entry.Node.Address
if entry.Service.Address != "" {
addr = entry.Service.Address
}
res[i] = fmt.Sprintf("%s:%d", addr, entry.Service.Port)
}
return res
}
func filterEntries(entries []*api.ServiceEntry, requiredTags []string) (res []*api.ServiceEntry) {
EntriesLoop:
for _, entry := range entries {
for _, required := range requiredTags {
var found bool
for _, tag := range entry.Service.Tags {
if tag == required {
found = true
break
}
}
if !found {
continue EntriesLoop
}
}
res = append(res, entry)
}
return
}