Skip to content

Commit

Permalink
[pickfirst_check_addrs] do it in pickfirst?
Browse files Browse the repository at this point in the history
  • Loading branch information
menghanl committed May 20, 2022
1 parent 9f4b31a commit 6f40d78
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions pickfirst.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (

"google.golang.org/grpc/balancer"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/resolver"
)

// PickFirstBalancerName is the name of the pick_first balancer.
Expand All @@ -47,6 +48,7 @@ type pickfirstBalancer struct {
state connectivity.State
cc balancer.ClientConn
subConn balancer.SubConn
addrs []resolver.Address
}

func (b *pickfirstBalancer) ResolverError(err error) {
Expand All @@ -68,6 +70,18 @@ func (b *pickfirstBalancer) ResolverError(err error) {
})
}

func equalAddresses(a, b []resolver.Address) bool {
if len(a) != len(b) {
return false
}
for i, v := range a {
if !v.Equal(b[i]) {
return false
}
}
return true
}

func (b *pickfirstBalancer) UpdateClientConnState(state balancer.ClientConnState) error {
if len(state.ResolverState.Addresses) == 0 {
// The resolver reported an empty address list. Treat it like an error by
Expand All @@ -82,6 +96,21 @@ func (b *pickfirstBalancer) UpdateClientConnState(state balancer.ClientConnState
return balancer.ErrBadResolverState
}

if equalAddresses(b.addrs, state.ResolverState.Addresses) {
// Avoid updating SubConn addresses if the addresses are the same.
//
// Usually SubConns can compare the new addresses with the address in
// use, and will not recreate the connection if not necessary.
//
// A special case is if the SubConn is in Connecting (so it's still
// trying to connect the addresses, and there's no address in use).
// Calling update addresses, even with the same set of Addresses, cause
// the SubConn to stop connecting, and retry with the new (same) set of
// addresses.
return nil
}
b.addrs = state.ResolverState.Addresses

if b.subConn != nil {
b.cc.UpdateAddresses(b.subConn, state.ResolverState.Addresses)
return nil
Expand Down

0 comments on commit 6f40d78

Please sign in to comment.