wrr.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. "fmt"
  21. "sync"
  22. "google.golang.org/grpc/internal/wrr"
  23. )
  24. // testWRR is a deterministic WRR implementation.
  25. //
  26. // The real implementation does random WRR. testWRR makes the balancer behavior
  27. // deterministic and easier to test.
  28. //
  29. // With {a: 2, b: 3}, the Next() results will be {a, a, b, b, b}.
  30. type testWRR struct {
  31. itemsWithWeight []struct {
  32. item interface{}
  33. weight int64
  34. }
  35. length int
  36. mu sync.Mutex
  37. idx int // The index of the item that will be picked
  38. count int64 // The number of times the current item has been picked.
  39. }
  40. // NewTestWRR return a WRR for testing. It's deterministic instead of random.
  41. func NewTestWRR() wrr.WRR {
  42. return &testWRR{}
  43. }
  44. func (twrr *testWRR) Add(item interface{}, weight int64) {
  45. twrr.itemsWithWeight = append(twrr.itemsWithWeight, struct {
  46. item interface{}
  47. weight int64
  48. }{item: item, weight: weight})
  49. twrr.length++
  50. }
  51. func (twrr *testWRR) Next() interface{} {
  52. twrr.mu.Lock()
  53. iww := twrr.itemsWithWeight[twrr.idx]
  54. twrr.count++
  55. if twrr.count >= iww.weight {
  56. twrr.idx = (twrr.idx + 1) % twrr.length
  57. twrr.count = 0
  58. }
  59. twrr.mu.Unlock()
  60. return iww.item
  61. }
  62. func (twrr *testWRR) String() string {
  63. return fmt.Sprint(twrr.itemsWithWeight)
  64. }