/
resolver.go
96 lines (85 loc) · 1.81 KB
/
resolver.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
package discovery
import (
"context"
"net/url"
"time"
"github.com/go-warrior/pkg/log"
"github.com/go-warrior/pkg/registry"
"google.golang.org/grpc/attributes"
"google.golang.org/grpc/resolver"
)
type discoveryResolver struct {
w registry.Watcher
cc resolver.ClientConn
log *log.Helper
ctx context.Context
cancel context.CancelFunc
}
func (r *discoveryResolver) watch() {
for {
select {
case <-r.ctx.Done():
return
default:
}
ins, err := r.w.Next()
if err != nil {
r.log.Errorf("Failed to watch discovery endpoint: %v", err)
time.Sleep(time.Second)
continue
}
r.update(ins)
}
}
func (r *discoveryResolver) update(ins []*registry.ServiceInstance) {
var addrs []resolver.Address
for _, in := range ins {
endpoint, err := parseEndpoint(in.Endpoints)
if err != nil {
r.log.Errorf("Failed to parse discovery endpoint: %v", err)
continue
}
if endpoint == "" {
continue
}
addr := resolver.Address{
ServerName: in.Name,
Attributes: parseAttributes(in.Metadata),
Addr: endpoint,
}
addrs = append(addrs, addr)
}
if len(addrs) == 0 {
r.log.Warnf("[resovler]Zero endpoint found,refused to write, ins: %v", ins)
return
}
r.cc.UpdateState(resolver.State{Addresses: addrs})
}
func (r *discoveryResolver) Close() {
r.cancel()
r.w.Stop()
}
func (r *discoveryResolver) ResolveNow(options resolver.ResolveNowOptions) {}
func parseEndpoint(endpoints []string) (string, error) {
for _, e := range endpoints {
u, err := url.Parse(e)
if err != nil {
return "", err
}
if u.Scheme == "grpc" {
return u.Host, nil
}
}
return "", nil
}
func parseAttributes(md map[string]string) *attributes.Attributes {
var a *attributes.Attributes
for k, v := range md {
if a == nil {
a = attributes.New(k, v)
} else {
a.WithValue(k, v)
}
}
return a
}