balancer.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. /*
  2. *
  3. * Copyright 2020 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 testutils
  19. import (
  20. "context"
  21. "errors"
  22. "fmt"
  23. "testing"
  24. "google.golang.org/grpc/balancer"
  25. "google.golang.org/grpc/connectivity"
  26. "google.golang.org/grpc/resolver"
  27. )
  28. // TestSubConnsCount is the number of TestSubConns initialized as part of
  29. // package init.
  30. const TestSubConnsCount = 16
  31. // testingLogger wraps the logging methods from testing.T.
  32. type testingLogger interface {
  33. Log(args ...interface{})
  34. Logf(format string, args ...interface{})
  35. }
  36. // TestSubConns contains a list of SubConns to be used in tests.
  37. var TestSubConns []*TestSubConn
  38. func init() {
  39. for i := 0; i < TestSubConnsCount; i++ {
  40. TestSubConns = append(TestSubConns, &TestSubConn{
  41. id: fmt.Sprintf("sc%d", i),
  42. ConnectCh: make(chan struct{}, 1),
  43. })
  44. }
  45. }
  46. // TestSubConn implements the SubConn interface, to be used in tests.
  47. type TestSubConn struct {
  48. id string
  49. ConnectCh chan struct{}
  50. }
  51. // UpdateAddresses is a no-op.
  52. func (tsc *TestSubConn) UpdateAddresses([]resolver.Address) {}
  53. // Connect is a no-op.
  54. func (tsc *TestSubConn) Connect() {
  55. select {
  56. case tsc.ConnectCh <- struct{}{}:
  57. default:
  58. }
  59. }
  60. // GetOrBuildProducer is a no-op.
  61. func (tsc *TestSubConn) GetOrBuildProducer(balancer.ProducerBuilder) (balancer.Producer, func()) {
  62. return nil, nil
  63. }
  64. // String implements stringer to print human friendly error message.
  65. func (tsc *TestSubConn) String() string {
  66. return tsc.id
  67. }
  68. // TestClientConn is a mock balancer.ClientConn used in tests.
  69. type TestClientConn struct {
  70. logger testingLogger
  71. NewSubConnAddrsCh chan []resolver.Address // the last 10 []Address to create subconn.
  72. NewSubConnCh chan balancer.SubConn // the last 10 subconn created.
  73. RemoveSubConnCh chan balancer.SubConn // the last 10 subconn removed.
  74. UpdateAddressesAddrsCh chan []resolver.Address // last updated address via UpdateAddresses().
  75. NewPickerCh chan balancer.Picker // the last picker updated.
  76. NewStateCh chan connectivity.State // the last state.
  77. ResolveNowCh chan resolver.ResolveNowOptions // the last ResolveNow().
  78. subConnIdx int
  79. }
  80. // NewTestClientConn creates a TestClientConn.
  81. func NewTestClientConn(t *testing.T) *TestClientConn {
  82. return &TestClientConn{
  83. logger: t,
  84. NewSubConnAddrsCh: make(chan []resolver.Address, 10),
  85. NewSubConnCh: make(chan balancer.SubConn, 10),
  86. RemoveSubConnCh: make(chan balancer.SubConn, 10),
  87. UpdateAddressesAddrsCh: make(chan []resolver.Address, 1),
  88. NewPickerCh: make(chan balancer.Picker, 1),
  89. NewStateCh: make(chan connectivity.State, 1),
  90. ResolveNowCh: make(chan resolver.ResolveNowOptions, 1),
  91. }
  92. }
  93. // NewSubConn creates a new SubConn.
  94. func (tcc *TestClientConn) NewSubConn(a []resolver.Address, o balancer.NewSubConnOptions) (balancer.SubConn, error) {
  95. sc := TestSubConns[tcc.subConnIdx]
  96. tcc.subConnIdx++
  97. tcc.logger.Logf("testClientConn: NewSubConn(%v, %+v) => %s", a, o, sc)
  98. select {
  99. case tcc.NewSubConnAddrsCh <- a:
  100. default:
  101. }
  102. select {
  103. case tcc.NewSubConnCh <- sc:
  104. default:
  105. }
  106. return sc, nil
  107. }
  108. // RemoveSubConn removes the SubConn.
  109. func (tcc *TestClientConn) RemoveSubConn(sc balancer.SubConn) {
  110. tcc.logger.Logf("testClientConn: RemoveSubConn(%s)", sc)
  111. select {
  112. case tcc.RemoveSubConnCh <- sc:
  113. default:
  114. }
  115. }
  116. // UpdateAddresses updates the addresses on the SubConn.
  117. func (tcc *TestClientConn) UpdateAddresses(sc balancer.SubConn, addrs []resolver.Address) {
  118. tcc.logger.Logf("testClientConn: UpdateAddresses(%v, %+v)", sc, addrs)
  119. select {
  120. case tcc.UpdateAddressesAddrsCh <- addrs:
  121. default:
  122. }
  123. }
  124. // UpdateState updates connectivity state and picker.
  125. func (tcc *TestClientConn) UpdateState(bs balancer.State) {
  126. tcc.logger.Logf("testClientConn: UpdateState(%v)", bs)
  127. select {
  128. case <-tcc.NewStateCh:
  129. default:
  130. }
  131. tcc.NewStateCh <- bs.ConnectivityState
  132. select {
  133. case <-tcc.NewPickerCh:
  134. default:
  135. }
  136. tcc.NewPickerCh <- bs.Picker
  137. }
  138. // ResolveNow panics.
  139. func (tcc *TestClientConn) ResolveNow(o resolver.ResolveNowOptions) {
  140. select {
  141. case <-tcc.ResolveNowCh:
  142. default:
  143. }
  144. tcc.ResolveNowCh <- o
  145. }
  146. // Target panics.
  147. func (tcc *TestClientConn) Target() string {
  148. panic("not implemented")
  149. }
  150. // WaitForErrPicker waits until an error picker is pushed to this ClientConn.
  151. // Returns error if the provided context expires or a non-error picker is pushed
  152. // to the ClientConn.
  153. func (tcc *TestClientConn) WaitForErrPicker(ctx context.Context) error {
  154. select {
  155. case <-ctx.Done():
  156. return errors.New("timeout when waiting for an error picker")
  157. case picker := <-tcc.NewPickerCh:
  158. if _, perr := picker.Pick(balancer.PickInfo{}); perr == nil {
  159. return fmt.Errorf("balancer returned a picker which is not an error picker")
  160. }
  161. }
  162. return nil
  163. }
  164. // WaitForPickerWithErr waits until an error picker is pushed to this
  165. // ClientConn with the error matching the wanted error. Returns an error if
  166. // the provided context expires, including the last received picker error (if
  167. // any).
  168. func (tcc *TestClientConn) WaitForPickerWithErr(ctx context.Context, want error) error {
  169. lastErr := errors.New("received no picker")
  170. for {
  171. select {
  172. case <-ctx.Done():
  173. return fmt.Errorf("timeout when waiting for an error picker with %v; last picker error: %v", want, lastErr)
  174. case picker := <-tcc.NewPickerCh:
  175. if _, lastErr = picker.Pick(balancer.PickInfo{}); lastErr != nil && lastErr.Error() == want.Error() {
  176. return nil
  177. }
  178. }
  179. }
  180. }
  181. // WaitForConnectivityState waits until the state pushed to this ClientConn
  182. // matches the wanted state. Returns an error if the provided context expires,
  183. // including the last received state (if any).
  184. func (tcc *TestClientConn) WaitForConnectivityState(ctx context.Context, want connectivity.State) error {
  185. var lastState connectivity.State = -1
  186. for {
  187. select {
  188. case <-ctx.Done():
  189. return fmt.Errorf("timeout when waiting for state to be %s; last state: %s", want, lastState)
  190. case s := <-tcc.NewStateCh:
  191. if s == want {
  192. return nil
  193. }
  194. lastState = s
  195. }
  196. }
  197. }
  198. // WaitForRoundRobinPicker waits for a picker that passes IsRoundRobin. Also
  199. // drains the matching state channel and requires it to be READY (if an entry
  200. // is pending) to be considered. Returns an error if the provided context
  201. // expires, including the last received error from IsRoundRobin or the picker
  202. // (if any).
  203. func (tcc *TestClientConn) WaitForRoundRobinPicker(ctx context.Context, want ...balancer.SubConn) error {
  204. lastErr := errors.New("received no picker")
  205. for {
  206. select {
  207. case <-ctx.Done():
  208. return fmt.Errorf("timeout when waiting for round robin picker with %v; last error: %v", want, lastErr)
  209. case p := <-tcc.NewPickerCh:
  210. s := connectivity.Ready
  211. select {
  212. case s = <-tcc.NewStateCh:
  213. default:
  214. }
  215. if s != connectivity.Ready {
  216. lastErr = fmt.Errorf("received state %v instead of ready", s)
  217. break
  218. }
  219. var pickerErr error
  220. if err := IsRoundRobin(want, func() balancer.SubConn {
  221. sc, err := p.Pick(balancer.PickInfo{})
  222. if err != nil {
  223. pickerErr = err
  224. } else if sc.Done != nil {
  225. sc.Done(balancer.DoneInfo{})
  226. }
  227. return sc.SubConn
  228. }); pickerErr != nil {
  229. lastErr = pickerErr
  230. continue
  231. } else if err != nil {
  232. lastErr = err
  233. continue
  234. }
  235. return nil
  236. }
  237. }
  238. }
  239. // WaitForPicker waits for a picker that results in f returning nil. If the
  240. // context expires, returns the last error returned by f (if any).
  241. func (tcc *TestClientConn) WaitForPicker(ctx context.Context, f func(balancer.Picker) error) error {
  242. lastErr := errors.New("received no picker")
  243. for {
  244. select {
  245. case <-ctx.Done():
  246. return fmt.Errorf("timeout when waiting for picker; last error: %v", lastErr)
  247. case p := <-tcc.NewPickerCh:
  248. if err := f(p); err != nil {
  249. lastErr = err
  250. continue
  251. }
  252. return nil
  253. }
  254. }
  255. }
  256. // IsRoundRobin checks whether f's return value is roundrobin of elements from
  257. // want. But it doesn't check for the order. Note that want can contain
  258. // duplicate items, which makes it weight-round-robin.
  259. //
  260. // Step 1. the return values of f should form a permutation of all elements in
  261. // want, but not necessary in the same order. E.g. if want is {a,a,b}, the check
  262. // fails if f returns:
  263. // - {a,a,a}: third a is returned before b
  264. // - {a,b,b}: second b is returned before the second a
  265. //
  266. // If error is found in this step, the returned error contains only the first
  267. // iteration until where it goes wrong.
  268. //
  269. // Step 2. the return values of f should be repetitions of the same permutation.
  270. // E.g. if want is {a,a,b}, the check failes if f returns:
  271. // - {a,b,a,b,a,a}: though it satisfies step 1, the second iteration is not
  272. // repeating the first iteration.
  273. //
  274. // If error is found in this step, the returned error contains the first
  275. // iteration + the second iteration until where it goes wrong.
  276. func IsRoundRobin(want []balancer.SubConn, f func() balancer.SubConn) error {
  277. wantSet := make(map[balancer.SubConn]int) // SubConn -> count, for weighted RR.
  278. for _, sc := range want {
  279. wantSet[sc]++
  280. }
  281. // The first iteration: makes sure f's return values form a permutation of
  282. // elements in want.
  283. //
  284. // Also keep the returns values in a slice, so we can compare the order in
  285. // the second iteration.
  286. gotSliceFirstIteration := make([]balancer.SubConn, 0, len(want))
  287. for range want {
  288. got := f()
  289. gotSliceFirstIteration = append(gotSliceFirstIteration, got)
  290. wantSet[got]--
  291. if wantSet[got] < 0 {
  292. return fmt.Errorf("non-roundrobin want: %v, result: %v", want, gotSliceFirstIteration)
  293. }
  294. }
  295. // The second iteration should repeat the first iteration.
  296. var gotSliceSecondIteration []balancer.SubConn
  297. for i := 0; i < 2; i++ {
  298. for _, w := range gotSliceFirstIteration {
  299. g := f()
  300. gotSliceSecondIteration = append(gotSliceSecondIteration, g)
  301. if w != g {
  302. return fmt.Errorf("non-roundrobin, first iter: %v, second iter: %v", gotSliceFirstIteration, gotSliceSecondIteration)
  303. }
  304. }
  305. }
  306. return nil
  307. }
  308. // SubConnFromPicker returns a function which returns a SubConn by calling the
  309. // Pick() method of the provided picker. There is no caching of SubConns here.
  310. // Every invocation of the returned function results in a new pick.
  311. func SubConnFromPicker(p balancer.Picker) func() balancer.SubConn {
  312. return func() balancer.SubConn {
  313. scst, _ := p.Pick(balancer.PickInfo{})
  314. return scst.SubConn
  315. }
  316. }
  317. // ErrTestConstPicker is error returned by test const picker.
  318. var ErrTestConstPicker = fmt.Errorf("const picker error")
  319. // TestConstPicker is a const picker for tests.
  320. type TestConstPicker struct {
  321. Err error
  322. SC balancer.SubConn
  323. }
  324. // Pick returns the const SubConn or the error.
  325. func (tcp *TestConstPicker) Pick(info balancer.PickInfo) (balancer.PickResult, error) {
  326. if tcp.Err != nil {
  327. return balancer.PickResult{}, tcp.Err
  328. }
  329. return balancer.PickResult{SubConn: tcp.SC}, nil
  330. }