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 ResolveNowCallback: func(resolver.ResolveNowOptions) {}, 34 scheme: scheme, 35 } 36} 37 38// Resolver is also a resolver builder. 39// It's build() function always returns itself. 40type Resolver struct { 41 // ResolveNowCallback is called when the ResolveNow method is called on the 42 // resolver. Must not be nil. Must not be changed after the resolver may 43 // be built. 44 ResolveNowCallback func(resolver.ResolveNowOptions) 45 scheme string 46 47 // Fields actually belong to the resolver. 48 CC resolver.ClientConn 49 bootstrapState *resolver.State 50} 51 52// InitialState adds initial state to the resolver so that UpdateState doesn't 53// need to be explicitly called after Dial. 54func (r *Resolver) InitialState(s resolver.State) { 55 r.bootstrapState = &s 56} 57 58// Build returns itself for Resolver, because it's both a builder and a resolver. 59func (r *Resolver) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) { 60 r.CC = cc 61 if r.bootstrapState != nil { 62 r.UpdateState(*r.bootstrapState) 63 } 64 return r, nil 65} 66 67// Scheme returns the test scheme. 68func (r *Resolver) Scheme() string { 69 return r.scheme 70} 71 72// ResolveNow is a noop for Resolver. 73func (r *Resolver) ResolveNow(o resolver.ResolveNowOptions) { 74 r.ResolveNowCallback(o) 75} 76 77// Close is a noop for Resolver. 78func (*Resolver) Close() {} 79 80// UpdateState calls CC.UpdateState. 81func (r *Resolver) UpdateState(s resolver.State) { 82 r.CC.UpdateState(s) 83} 84 85// GenerateAndRegisterManualResolver generates a random scheme and a Resolver 86// with it. It also registers this Resolver. 87// It returns the Resolver and a cleanup function to unregister it. 88func GenerateAndRegisterManualResolver() (*Resolver, func()) { 89 scheme := strconv.FormatInt(time.Now().UnixNano(), 36) 90 r := NewBuilderWithScheme(scheme) 91 resolver.Register(r) 92 return r, func() { resolver.UnregisterForTesting(scheme) } 93} 94