Skip to content

Commit f857020

Browse files
authored
cherry-pick #7523 to v1.66.x branch (#7547)
1 parent 35e915e commit f857020

File tree

4 files changed

+146
-15
lines changed

4 files changed

+146
-15
lines changed

balancer_wrapper.go

+10
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,16 @@ func (acbw *acBalancerWrapper) updateState(s connectivity.State, curAddr resolve
275275
setConnectedAddress(&scs, curAddr)
276276
}
277277
acbw.stateListener(scs)
278+
acbw.ac.mu.Lock()
279+
defer acbw.ac.mu.Unlock()
280+
if s == connectivity.Ready {
281+
// When changing states to READY, reset stateReadyChan. Wait until
282+
// after we notify the LB policy's listener(s) in order to prevent
283+
// ac.getTransport() from unblocking before the LB policy starts
284+
// tracking the subchannel as READY.
285+
close(acbw.ac.stateReadyChan)
286+
acbw.ac.stateReadyChan = make(chan struct{})
287+
}
278288
})
279289
}
280290

clientconn.go

+11-14
Original file line numberDiff line numberDiff line change
@@ -825,14 +825,14 @@ func (cc *ClientConn) newAddrConnLocked(addrs []resolver.Address, opts balancer.
825825
}
826826

827827
ac := &addrConn{
828-
state: connectivity.Idle,
829-
cc: cc,
830-
addrs: copyAddresses(addrs),
831-
scopts: opts,
832-
dopts: cc.dopts,
833-
channelz: channelz.RegisterSubChannel(cc.channelz, ""),
834-
resetBackoff: make(chan struct{}),
835-
stateChan: make(chan struct{}),
828+
state: connectivity.Idle,
829+
cc: cc,
830+
addrs: copyAddresses(addrs),
831+
scopts: opts,
832+
dopts: cc.dopts,
833+
channelz: channelz.RegisterSubChannel(cc.channelz, ""),
834+
resetBackoff: make(chan struct{}),
835+
stateReadyChan: make(chan struct{}),
836836
}
837837
ac.ctx, ac.cancel = context.WithCancel(cc.ctx)
838838
// Start with our address set to the first address; this may be updated if
@@ -1179,8 +1179,8 @@ type addrConn struct {
11791179
addrs []resolver.Address // All addresses that the resolver resolved to.
11801180

11811181
// Use updateConnectivityState for updating addrConn's connectivity state.
1182-
state connectivity.State
1183-
stateChan chan struct{} // closed and recreated on every state change.
1182+
state connectivity.State
1183+
stateReadyChan chan struct{} // closed and recreated on every READY state change.
11841184

11851185
backoffIdx int // Needs to be stateful for resetConnectBackoff.
11861186
resetBackoff chan struct{}
@@ -1193,9 +1193,6 @@ func (ac *addrConn) updateConnectivityState(s connectivity.State, lastErr error)
11931193
if ac.state == s {
11941194
return
11951195
}
1196-
// When changing states, reset the state change channel.
1197-
close(ac.stateChan)
1198-
ac.stateChan = make(chan struct{})
11991196
ac.state = s
12001197
ac.channelz.ChannelMetrics.State.Store(&s)
12011198
if lastErr == nil {
@@ -1513,7 +1510,7 @@ func (ac *addrConn) getReadyTransport() transport.ClientTransport {
15131510
func (ac *addrConn) getTransport(ctx context.Context) (transport.ClientTransport, error) {
15141511
for ctx.Err() == nil {
15151512
ac.mu.Lock()
1516-
t, state, sc := ac.transport, ac.state, ac.stateChan
1513+
t, state, sc := ac.transport, ac.state, ac.stateReadyChan
15171514
ac.mu.Unlock()
15181515
if state == connectivity.Ready {
15191516
return t, nil

producer_ext_test.go

+125
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
/*
2+
*
3+
* Copyright 2024 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 grpc_test
20+
21+
import (
22+
"context"
23+
"strings"
24+
"testing"
25+
"time"
26+
27+
"google.golang.org/grpc"
28+
"google.golang.org/grpc/balancer"
29+
"google.golang.org/grpc/connectivity"
30+
"google.golang.org/grpc/credentials/insecure"
31+
"google.golang.org/grpc/internal/balancer/stub"
32+
"google.golang.org/grpc/internal/stubserver"
33+
testgrpc "google.golang.org/grpc/interop/grpc_testing"
34+
)
35+
36+
type producerBuilder struct{}
37+
38+
type producer struct {
39+
client testgrpc.TestServiceClient
40+
stopped chan struct{}
41+
}
42+
43+
// Build constructs and returns a producer and its cleanup function
44+
func (*producerBuilder) Build(cci any) (balancer.Producer, func()) {
45+
p := &producer{
46+
client: testgrpc.NewTestServiceClient(cci.(grpc.ClientConnInterface)),
47+
stopped: make(chan struct{}),
48+
}
49+
return p, func() {
50+
<-p.stopped
51+
}
52+
}
53+
54+
func (p *producer) TestStreamStart(t *testing.T, streamStarted chan<- struct{}) {
55+
go func() {
56+
defer close(p.stopped)
57+
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
58+
defer cancel()
59+
if _, err := p.client.FullDuplexCall(ctx); err != nil {
60+
t.Errorf("Unexpected error starting stream: %v", err)
61+
}
62+
close(streamStarted)
63+
}()
64+
}
65+
66+
var producerBuilderSingleton = &producerBuilder{}
67+
68+
// TestProducerStreamStartsAfterReady ensures producer streams only start after
69+
// the subchannel reports as READY to the LB policy.
70+
func (s) TestProducerStreamStartsAfterReady(t *testing.T) {
71+
name := strings.ReplaceAll(strings.ToLower(t.Name()), "/", "")
72+
producerCh := make(chan balancer.Producer)
73+
streamStarted := make(chan struct{})
74+
done := make(chan struct{})
75+
bf := stub.BalancerFuncs{
76+
UpdateClientConnState: func(bd *stub.BalancerData, ccs balancer.ClientConnState) error {
77+
sc, err := bd.ClientConn.NewSubConn(ccs.ResolverState.Addresses, balancer.NewSubConnOptions{
78+
StateListener: func(scs balancer.SubConnState) {
79+
if scs.ConnectivityState == connectivity.Ready {
80+
timer := time.NewTimer(5 * time.Millisecond)
81+
select {
82+
case <-streamStarted:
83+
t.Errorf("Producer stream started before Ready listener returned")
84+
case <-timer.C:
85+
}
86+
close(done)
87+
}
88+
},
89+
})
90+
if err != nil {
91+
return err
92+
}
93+
producer, _ := sc.GetOrBuildProducer(producerBuilderSingleton)
94+
producerCh <- producer
95+
sc.Connect()
96+
return nil
97+
},
98+
}
99+
stub.Register(name, bf)
100+
101+
ss := stubserver.StubServer{
102+
FullDuplexCallF: func(stream testgrpc.TestService_FullDuplexCallServer) error {
103+
return nil
104+
},
105+
}
106+
if err := ss.StartServer(); err != nil {
107+
t.Fatal("Error starting server:", err)
108+
}
109+
defer ss.Stop()
110+
111+
cc, err := grpc.NewClient("dns:///"+ss.Address,
112+
grpc.WithDefaultServiceConfig(`{"loadBalancingConfig": [{"`+name+`":{}}]}`),
113+
grpc.WithTransportCredentials(insecure.NewCredentials()),
114+
)
115+
if err != nil {
116+
t.Fatalf("Error creating client: %v", err)
117+
}
118+
defer cc.Close()
119+
120+
go cc.Connect()
121+
p := <-producerCh
122+
p.(*producer).TestStreamStart(t, streamStarted)
123+
124+
<-done
125+
}

resolver_balancer_ext_test.go

-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@ import (
4646
// 5. resolver.Resolver.ResolveNow() ->
4747
func (s) TestResolverBalancerInteraction(t *testing.T) {
4848
name := strings.Replace(strings.ToLower(t.Name()), "/", "", -1)
49-
fmt.Println(name)
5049
bf := stub.BalancerFuncs{
5150
UpdateClientConnState: func(bd *stub.BalancerData, ccs balancer.ClientConnState) error {
5251
bd.ClientConn.ResolveNow(resolver.ResolveNowOptions{})

0 commit comments

Comments
 (0)