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 manual defines a resolver that can be used to manually send resolved 20// addresses to ClientConn. 21package manual 22 23import ( 24 "strconv" 25 "time" 26 27 "google.golang.org/grpc/resolver" 28) 29 30// NewBuilderWithScheme creates a new test resolver builder with the given scheme. 31func NewBuilderWithScheme(scheme string) *Resolver { 32 return &Resolver{ 33 scheme: scheme, 34 } 35} 36 37// Resolver is also a resolver builder. 38// It's build() function always returns itself. 39type Resolver struct { 40 scheme string 41 42 // Fields actually belong to the resolver. 43 cc resolver.ClientConn 44 bootstrapState *resolver.State 45} 46 47// InitialState adds initial state to the resolver so that UpdateState doesn't 48// need to be explicitly called after Dial. 49func (r *Resolver) InitialState(s resolver.State) { 50 r.bootstrapState = &s 51} 52 53// Build returns itself for Resolver, because it's both a builder and a resolver. 54func (r *Resolver) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOption) (resolver.Resolver, error) { 55 r.cc = cc 56 if r.bootstrapState != nil { 57 r.UpdateState(*r.bootstrapState) 58 } 59 return r, nil 60} 61 62// Scheme returns the test scheme. 63func (r *Resolver) Scheme() string { 64 return r.scheme 65} 66 67// ResolveNow is a noop for Resolver. 68func (*Resolver) ResolveNow(o resolver.ResolveNowOption) {} 69 70// Close is a noop for Resolver. 71func (*Resolver) Close() {} 72 73// UpdateState calls cc.UpdateState. 74func (r *Resolver) UpdateState(s resolver.State) { 75 r.cc.UpdateState(s) 76} 77 78// GenerateAndRegisterManualResolver generates a random scheme and a Resolver 79// with it. It also registers this Resolver. 80// It returns the Resolver and a cleanup function to unregister it. 81func GenerateAndRegisterManualResolver() (*Resolver, func()) { 82 scheme := strconv.FormatInt(time.Now().UnixNano(), 36) 83 r := NewBuilderWithScheme(scheme) 84 resolver.Register(r) 85 return r, func() { resolver.UnregisterForTesting(scheme) } 86} 87