balancer_test.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. /*
  2. *
  3. * Copyright 2018 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. package test
  19. import (
  20. "context"
  21. "reflect"
  22. "testing"
  23. "time"
  24. "google.golang.org/grpc"
  25. "google.golang.org/grpc/balancer"
  26. "google.golang.org/grpc/connectivity"
  27. "google.golang.org/grpc/credentials"
  28. "google.golang.org/grpc/grpclog"
  29. "google.golang.org/grpc/internal/leakcheck"
  30. "google.golang.org/grpc/metadata"
  31. "google.golang.org/grpc/resolver"
  32. testpb "google.golang.org/grpc/test/grpc_testing"
  33. "google.golang.org/grpc/testdata"
  34. )
  35. const testBalancerName = "testbalancer"
  36. // testBalancer creates one subconn with the first address from resolved
  37. // addresses.
  38. //
  39. // It's used to test options for NewSubConn are applies correctly.
  40. type testBalancer struct {
  41. cc balancer.ClientConn
  42. sc balancer.SubConn
  43. newSubConnOptions balancer.NewSubConnOptions
  44. pickOptions []balancer.PickOptions
  45. doneInfo []balancer.DoneInfo
  46. }
  47. func (b *testBalancer) Build(cc balancer.ClientConn, opt balancer.BuildOptions) balancer.Balancer {
  48. b.cc = cc
  49. return b
  50. }
  51. func (*testBalancer) Name() string {
  52. return testBalancerName
  53. }
  54. func (b *testBalancer) HandleResolvedAddrs(addrs []resolver.Address, err error) {
  55. // Only create a subconn at the first time.
  56. if err == nil && b.sc == nil {
  57. b.sc, err = b.cc.NewSubConn(addrs, b.newSubConnOptions)
  58. if err != nil {
  59. grpclog.Errorf("testBalancer: failed to NewSubConn: %v", err)
  60. return
  61. }
  62. b.cc.UpdateBalancerState(connectivity.Connecting, &picker{sc: b.sc, bal: b})
  63. b.sc.Connect()
  64. }
  65. }
  66. func (b *testBalancer) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) {
  67. grpclog.Infof("testBalancer: HandleSubConnStateChange: %p, %v", sc, s)
  68. if b.sc != sc {
  69. grpclog.Infof("testBalancer: ignored state change because sc is not recognized")
  70. return
  71. }
  72. if s == connectivity.Shutdown {
  73. b.sc = nil
  74. return
  75. }
  76. switch s {
  77. case connectivity.Ready, connectivity.Idle:
  78. b.cc.UpdateBalancerState(s, &picker{sc: sc, bal: b})
  79. case connectivity.Connecting:
  80. b.cc.UpdateBalancerState(s, &picker{err: balancer.ErrNoSubConnAvailable, bal: b})
  81. case connectivity.TransientFailure:
  82. b.cc.UpdateBalancerState(s, &picker{err: balancer.ErrTransientFailure, bal: b})
  83. }
  84. }
  85. func (b *testBalancer) Close() {
  86. }
  87. type picker struct {
  88. err error
  89. sc balancer.SubConn
  90. bal *testBalancer
  91. }
  92. func (p *picker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) {
  93. p.bal.pickOptions = append(p.bal.pickOptions, opts)
  94. if p.err != nil {
  95. return nil, nil, p.err
  96. }
  97. return p.sc, func(d balancer.DoneInfo) { p.bal.doneInfo = append(p.bal.doneInfo, d) }, nil
  98. }
  99. func TestCredsBundleFromBalancer(t *testing.T) {
  100. balancer.Register(&testBalancer{
  101. newSubConnOptions: balancer.NewSubConnOptions{
  102. CredsBundle: &testCredsBundle{},
  103. },
  104. })
  105. defer leakcheck.Check(t)
  106. te := newTest(t, env{name: "creds-bundle", network: "tcp", balancer: ""})
  107. te.tapHandle = authHandle
  108. te.customDialOptions = []grpc.DialOption{
  109. grpc.WithBalancerName(testBalancerName),
  110. }
  111. creds, err := credentials.NewServerTLSFromFile(testdata.Path("server1.pem"), testdata.Path("server1.key"))
  112. if err != nil {
  113. t.Fatalf("Failed to generate credentials %v", err)
  114. }
  115. te.customServerOptions = []grpc.ServerOption{
  116. grpc.Creds(creds),
  117. }
  118. te.startServer(&testServer{})
  119. defer te.tearDown()
  120. cc := te.clientConn()
  121. tc := testpb.NewTestServiceClient(cc)
  122. if _, err := tc.EmptyCall(context.Background(), &testpb.Empty{}); err != nil {
  123. t.Fatalf("Test failed. Reason: %v", err)
  124. }
  125. }
  126. func TestPickAndDone(t *testing.T) {
  127. defer leakcheck.Check(t)
  128. for _, e := range listTestEnv() {
  129. testPickAndDone(t, e)
  130. }
  131. }
  132. func testPickAndDone(t *testing.T, e env) {
  133. te := newTest(t, e)
  134. b := &testBalancer{}
  135. balancer.Register(b)
  136. te.customDialOptions = []grpc.DialOption{
  137. grpc.WithBalancerName(testBalancerName),
  138. }
  139. te.userAgent = failAppUA
  140. te.startServer(&testServer{security: e.security})
  141. defer te.tearDown()
  142. cc := te.clientConn()
  143. tc := testpb.NewTestServiceClient(cc)
  144. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  145. defer cancel()
  146. wantErr := detailedError
  147. if _, err := tc.EmptyCall(ctx, &testpb.Empty{}); !reflect.DeepEqual(err, wantErr) {
  148. t.Fatalf("TestService/EmptyCall(_, _) = _, %v, want _, %v", err, wantErr)
  149. }
  150. md := metadata.Pairs("testMDKey", "testMDVal")
  151. ctx = metadata.NewOutgoingContext(ctx, md)
  152. if _, err := tc.UnaryCall(ctx, &testpb.SimpleRequest{}); err != nil {
  153. t.Fatalf("TestService.UnaryCall(%v, _, _, _) = _, %v; want _, <nil>", ctx, err)
  154. }
  155. poWant := []balancer.PickOptions{
  156. {FullMethodName: "/grpc.testing.TestService/EmptyCall"},
  157. {FullMethodName: "/grpc.testing.TestService/UnaryCall", Header: md},
  158. }
  159. if !reflect.DeepEqual(b.pickOptions, poWant) {
  160. t.Fatalf("b.pickOptions = %v; want %v", b.pickOptions, poWant)
  161. }
  162. if len(b.doneInfo) < 1 || !reflect.DeepEqual(b.doneInfo[0].Err, wantErr) {
  163. t.Fatalf("b.doneInfo = %v; want b.doneInfo[0].Err = %v", b.doneInfo, wantErr)
  164. }
  165. if len(b.doneInfo) < 2 || !reflect.DeepEqual(b.doneInfo[1].Trailer, testTrailerMetadata) {
  166. t.Fatalf("b.doneInfo = %v; want b.doneInfo[1].Trailer = %v", b.doneInfo, testTrailerMetadata)
  167. }
  168. }