OSDN Git Service

new repo
[bytom/vapor.git] / vendor / google.golang.org / grpc / resolver / dns / dns_resolver.go
1 /*
2  *
3  * Copyright 2017 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18
19 // Package dns implements a dns resolver to be installed as the default resolver
20 // in grpc.
21 package dns
22
23 import (
24         "encoding/json"
25         "errors"
26         "fmt"
27         "math/rand"
28         "net"
29         "os"
30         "strconv"
31         "strings"
32         "sync"
33         "time"
34
35         "golang.org/x/net/context"
36         "google.golang.org/grpc/grpclog"
37         "google.golang.org/grpc/resolver"
38 )
39
40 func init() {
41         resolver.Register(NewBuilder())
42 }
43
44 const (
45         defaultPort = "443"
46         defaultFreq = time.Minute * 30
47         golang      = "GO"
48         // In DNS, service config is encoded in a TXT record via the mechanism
49         // described in RFC-1464 using the attribute name grpc_config.
50         txtAttribute = "grpc_config="
51 )
52
53 var errMissingAddr = errors.New("missing address")
54
55 // NewBuilder creates a dnsBuilder which is used to factory DNS resolvers.
56 func NewBuilder() resolver.Builder {
57         return &dnsBuilder{freq: defaultFreq}
58 }
59
60 type dnsBuilder struct {
61         // frequency of polling the DNS server.
62         freq time.Duration
63 }
64
65 // Build creates and starts a DNS resolver that watches the name resolution of the target.
66 func (b *dnsBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOption) (resolver.Resolver, error) {
67         host, port, err := parseTarget(target.Endpoint)
68         if err != nil {
69                 return nil, err
70         }
71
72         // IP address.
73         if net.ParseIP(host) != nil {
74                 host, _ = formatIP(host)
75                 addr := []resolver.Address{{Addr: host + ":" + port}}
76                 i := &ipResolver{
77                         cc: cc,
78                         ip: addr,
79                         rn: make(chan struct{}, 1),
80                         q:  make(chan struct{}),
81                 }
82                 cc.NewAddress(addr)
83                 go i.watcher()
84                 return i, nil
85         }
86
87         // DNS address (non-IP).
88         ctx, cancel := context.WithCancel(context.Background())
89         d := &dnsResolver{
90                 freq:   b.freq,
91                 host:   host,
92                 port:   port,
93                 ctx:    ctx,
94                 cancel: cancel,
95                 cc:     cc,
96                 t:      time.NewTimer(0),
97                 rn:     make(chan struct{}, 1),
98         }
99
100         d.wg.Add(1)
101         go d.watcher()
102         return d, nil
103 }
104
105 // Scheme returns the naming scheme of this resolver builder, which is "dns".
106 func (b *dnsBuilder) Scheme() string {
107         return "dns"
108 }
109
110 // ipResolver watches for the name resolution update for an IP address.
111 type ipResolver struct {
112         cc resolver.ClientConn
113         ip []resolver.Address
114         // rn channel is used by ResolveNow() to force an immediate resolution of the target.
115         rn chan struct{}
116         q  chan struct{}
117 }
118
119 // ResolveNow resend the address it stores, no resolution is needed.
120 func (i *ipResolver) ResolveNow(opt resolver.ResolveNowOption) {
121         select {
122         case i.rn <- struct{}{}:
123         default:
124         }
125 }
126
127 // Close closes the ipResolver.
128 func (i *ipResolver) Close() {
129         close(i.q)
130 }
131
132 func (i *ipResolver) watcher() {
133         for {
134                 select {
135                 case <-i.rn:
136                         i.cc.NewAddress(i.ip)
137                 case <-i.q:
138                         return
139                 }
140         }
141 }
142
143 // dnsResolver watches for the name resolution update for a non-IP target.
144 type dnsResolver struct {
145         freq   time.Duration
146         host   string
147         port   string
148         ctx    context.Context
149         cancel context.CancelFunc
150         cc     resolver.ClientConn
151         // rn channel is used by ResolveNow() to force an immediate resolution of the target.
152         rn chan struct{}
153         t  *time.Timer
154         // wg is used to enforce Close() to return after the watcher() goroutine has finished.
155         // Otherwise, data race will be possible. [Race Example] in dns_resolver_test we
156         // replace the real lookup functions with mocked ones to facilitate testing.
157         // If Close() doesn't wait for watcher() goroutine finishes, race detector sometimes
158         // will warns lookup (READ the lookup function pointers) inside watcher() goroutine
159         // has data race with replaceNetFunc (WRITE the lookup function pointers).
160         wg sync.WaitGroup
161 }
162
163 // ResolveNow invoke an immediate resolution of the target that this dnsResolver watches.
164 func (d *dnsResolver) ResolveNow(opt resolver.ResolveNowOption) {
165         select {
166         case d.rn <- struct{}{}:
167         default:
168         }
169 }
170
171 // Close closes the dnsResolver.
172 func (d *dnsResolver) Close() {
173         d.cancel()
174         d.wg.Wait()
175         d.t.Stop()
176 }
177
178 func (d *dnsResolver) watcher() {
179         defer d.wg.Done()
180         for {
181                 select {
182                 case <-d.ctx.Done():
183                         return
184                 case <-d.t.C:
185                 case <-d.rn:
186                 }
187                 result, sc := d.lookup()
188                 // Next lookup should happen after an interval defined by d.freq.
189                 d.t.Reset(d.freq)
190                 d.cc.NewServiceConfig(string(sc))
191                 d.cc.NewAddress(result)
192         }
193 }
194
195 func (d *dnsResolver) lookupSRV() []resolver.Address {
196         var newAddrs []resolver.Address
197         _, srvs, err := lookupSRV(d.ctx, "grpclb", "tcp", d.host)
198         if err != nil {
199                 grpclog.Infof("grpc: failed dns SRV record lookup due to %v.\n", err)
200                 return nil
201         }
202         for _, s := range srvs {
203                 lbAddrs, err := lookupHost(d.ctx, s.Target)
204                 if err != nil {
205                         grpclog.Warningf("grpc: failed load banlacer address dns lookup due to %v.\n", err)
206                         continue
207                 }
208                 for _, a := range lbAddrs {
209                         a, ok := formatIP(a)
210                         if !ok {
211                                 grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err)
212                                 continue
213                         }
214                         addr := a + ":" + strconv.Itoa(int(s.Port))
215                         newAddrs = append(newAddrs, resolver.Address{Addr: addr, Type: resolver.GRPCLB, ServerName: s.Target})
216                 }
217         }
218         return newAddrs
219 }
220
221 func (d *dnsResolver) lookupTXT() string {
222         ss, err := lookupTXT(d.ctx, d.host)
223         if err != nil {
224                 grpclog.Warningf("grpc: failed dns TXT record lookup due to %v.\n", err)
225                 return ""
226         }
227         var res string
228         for _, s := range ss {
229                 res += s
230         }
231
232         // TXT record must have "grpc_config=" attribute in order to be used as service config.
233         if !strings.HasPrefix(res, txtAttribute) {
234                 grpclog.Warningf("grpc: TXT record %v missing %v attribute", res, txtAttribute)
235                 return ""
236         }
237         return strings.TrimPrefix(res, txtAttribute)
238 }
239
240 func (d *dnsResolver) lookupHost() []resolver.Address {
241         var newAddrs []resolver.Address
242         addrs, err := lookupHost(d.ctx, d.host)
243         if err != nil {
244                 grpclog.Warningf("grpc: failed dns A record lookup due to %v.\n", err)
245                 return nil
246         }
247         for _, a := range addrs {
248                 a, ok := formatIP(a)
249                 if !ok {
250                         grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err)
251                         continue
252                 }
253                 addr := a + ":" + d.port
254                 newAddrs = append(newAddrs, resolver.Address{Addr: addr})
255         }
256         return newAddrs
257 }
258
259 func (d *dnsResolver) lookup() ([]resolver.Address, string) {
260         var newAddrs []resolver.Address
261         newAddrs = d.lookupSRV()
262         // Support fallback to non-balancer address.
263         newAddrs = append(newAddrs, d.lookupHost()...)
264         sc := d.lookupTXT()
265         return newAddrs, canaryingSC(sc)
266 }
267
268 // formatIP returns ok = false if addr is not a valid textual representation of an IP address.
269 // If addr is an IPv4 address, return the addr and ok = true.
270 // If addr is an IPv6 address, return the addr enclosed in square brackets and ok = true.
271 func formatIP(addr string) (addrIP string, ok bool) {
272         ip := net.ParseIP(addr)
273         if ip == nil {
274                 return "", false
275         }
276         if ip.To4() != nil {
277                 return addr, true
278         }
279         return "[" + addr + "]", true
280 }
281
282 // parseTarget takes the user input target string, returns formatted host and port info.
283 // If target doesn't specify a port, set the port to be the defaultPort.
284 // If target is in IPv6 format and host-name is enclosed in sqarue brackets, brackets
285 // are strippd when setting the host.
286 // examples:
287 // target: "www.google.com" returns host: "www.google.com", port: "443"
288 // target: "ipv4-host:80" returns host: "ipv4-host", port: "80"
289 // target: "[ipv6-host]" returns host: "ipv6-host", port: "443"
290 // target: ":80" returns host: "localhost", port: "80"
291 // target: ":" returns host: "localhost", port: "443"
292 func parseTarget(target string) (host, port string, err error) {
293         if target == "" {
294                 return "", "", errMissingAddr
295         }
296         if ip := net.ParseIP(target); ip != nil {
297                 // target is an IPv4 or IPv6(without brackets) address
298                 return target, defaultPort, nil
299         }
300         if host, port, err = net.SplitHostPort(target); err == nil {
301                 // target has port, i.e ipv4-host:port, [ipv6-host]:port, host-name:port
302                 if host == "" {
303                         // Keep consistent with net.Dial(): If the host is empty, as in ":80", the local system is assumed.
304                         host = "localhost"
305                 }
306                 if port == "" {
307                         // If the port field is empty(target ends with colon), e.g. "[::1]:", defaultPort is used.
308                         port = defaultPort
309                 }
310                 return host, port, nil
311         }
312         if host, port, err = net.SplitHostPort(target + ":" + defaultPort); err == nil {
313                 // target doesn't have port
314                 return host, port, nil
315         }
316         return "", "", fmt.Errorf("invalid target address %v, error info: %v", target, err)
317 }
318
319 type rawChoice struct {
320         ClientLanguage *[]string        `json:"clientLanguage,omitempty"`
321         Percentage     *int             `json:"percentage,omitempty"`
322         ClientHostName *[]string        `json:"clientHostName,omitempty"`
323         ServiceConfig  *json.RawMessage `json:"serviceConfig,omitempty"`
324 }
325
326 func containsString(a *[]string, b string) bool {
327         if a == nil {
328                 return true
329         }
330         for _, c := range *a {
331                 if c == b {
332                         return true
333                 }
334         }
335         return false
336 }
337
338 func chosenByPercentage(a *int) bool {
339         if a == nil {
340                 return true
341         }
342         s := rand.NewSource(time.Now().UnixNano())
343         r := rand.New(s)
344         if r.Intn(100)+1 > *a {
345                 return false
346         }
347         return true
348 }
349
350 func canaryingSC(js string) string {
351         if js == "" {
352                 return ""
353         }
354         var rcs []rawChoice
355         err := json.Unmarshal([]byte(js), &rcs)
356         if err != nil {
357                 grpclog.Warningf("grpc: failed to parse service config json string due to %v.\n", err)
358                 return ""
359         }
360         cliHostname, err := os.Hostname()
361         if err != nil {
362                 grpclog.Warningf("grpc: failed to get client hostname due to %v.\n", err)
363                 return ""
364         }
365         var sc string
366         for _, c := range rcs {
367                 if !containsString(c.ClientLanguage, golang) ||
368                         !chosenByPercentage(c.Percentage) ||
369                         !containsString(c.ClientHostName, cliHostname) ||
370                         c.ServiceConfig == nil {
371                         continue
372                 }
373                 sc = string(*c.ServiceConfig)
374                 break
375         }
376         return sc
377 }