orcalb.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. /*
  2. *
  3. * Copyright 2023 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 interop
  19. import (
  20. "context"
  21. "fmt"
  22. "sync"
  23. "time"
  24. v3orcapb "github.com/cncf/xds/go/xds/data/orca/v3"
  25. "google.golang.org/grpc/balancer"
  26. "google.golang.org/grpc/balancer/base"
  27. "google.golang.org/grpc/connectivity"
  28. "google.golang.org/grpc/orca"
  29. )
  30. func init() {
  31. balancer.Register(orcabb{})
  32. }
  33. type orcabb struct{}
  34. func (orcabb) Build(cc balancer.ClientConn, opts balancer.BuildOptions) balancer.Balancer {
  35. return &orcab{cc: cc}
  36. }
  37. func (orcabb) Name() string {
  38. return "test_backend_metrics_load_balancer"
  39. }
  40. type orcab struct {
  41. cc balancer.ClientConn
  42. sc balancer.SubConn
  43. cancelWatch func()
  44. reportMu sync.Mutex
  45. report *v3orcapb.OrcaLoadReport
  46. }
  47. func (o *orcab) UpdateClientConnState(s balancer.ClientConnState) error {
  48. if o.sc != nil {
  49. o.sc.UpdateAddresses(s.ResolverState.Addresses)
  50. return nil
  51. }
  52. if len(s.ResolverState.Addresses) == 0 {
  53. o.ResolverError(fmt.Errorf("produced no addresses"))
  54. return fmt.Errorf("resolver produced no addresses")
  55. }
  56. var err error
  57. o.sc, err = o.cc.NewSubConn(s.ResolverState.Addresses, balancer.NewSubConnOptions{})
  58. if err != nil {
  59. o.cc.UpdateState(balancer.State{ConnectivityState: connectivity.TransientFailure, Picker: base.NewErrPicker(fmt.Errorf("error creating subconn: %v", err))})
  60. return nil
  61. }
  62. o.cancelWatch = orca.RegisterOOBListener(o.sc, o, orca.OOBListenerOptions{ReportInterval: time.Second})
  63. o.sc.Connect()
  64. o.cc.UpdateState(balancer.State{ConnectivityState: connectivity.Connecting, Picker: base.NewErrPicker(balancer.ErrNoSubConnAvailable)})
  65. return nil
  66. }
  67. func (o *orcab) ResolverError(err error) {
  68. if o.sc == nil {
  69. o.cc.UpdateState(balancer.State{ConnectivityState: connectivity.TransientFailure, Picker: base.NewErrPicker(fmt.Errorf("resolver error: %v", err))})
  70. }
  71. }
  72. func (o *orcab) UpdateSubConnState(sc balancer.SubConn, scState balancer.SubConnState) {
  73. if o.sc != sc {
  74. logger.Errorf("received subconn update for unknown subconn: %v vs %v", o.sc, sc)
  75. return
  76. }
  77. switch scState.ConnectivityState {
  78. case connectivity.Ready:
  79. o.cc.UpdateState(balancer.State{ConnectivityState: connectivity.Ready, Picker: &scPicker{sc: sc, o: o}})
  80. case connectivity.TransientFailure:
  81. o.cc.UpdateState(balancer.State{ConnectivityState: connectivity.TransientFailure, Picker: base.NewErrPicker(fmt.Errorf("all subchannels in transient failure: %v", scState.ConnectionError))})
  82. case connectivity.Connecting:
  83. // Ignore; picker already set to "connecting".
  84. case connectivity.Idle:
  85. sc.Connect()
  86. o.cc.UpdateState(balancer.State{ConnectivityState: connectivity.Connecting, Picker: base.NewErrPicker(balancer.ErrNoSubConnAvailable)})
  87. case connectivity.Shutdown:
  88. // Ignore; we are closing but handle that in Close instead.
  89. }
  90. }
  91. func (o *orcab) Close() {
  92. o.cancelWatch()
  93. }
  94. func (o *orcab) OnLoadReport(r *v3orcapb.OrcaLoadReport) {
  95. o.reportMu.Lock()
  96. defer o.reportMu.Unlock()
  97. logger.Infof("received OOB load report: %v", r)
  98. o.report = r
  99. }
  100. type scPicker struct {
  101. sc balancer.SubConn
  102. o *orcab
  103. }
  104. func (p *scPicker) Pick(info balancer.PickInfo) (balancer.PickResult, error) {
  105. doneCB := func(di balancer.DoneInfo) {
  106. if lr, _ := di.ServerLoad.(*v3orcapb.OrcaLoadReport); lr != nil &&
  107. (lr.CpuUtilization != 0 || lr.MemUtilization != 0 || len(lr.Utilization) > 0 || len(lr.RequestCost) > 0) {
  108. // Since all RPCs will respond with a load report due to the
  109. // presence of the DialOption, we need to inspect every field and
  110. // use the out-of-band report instead if all are unset/zero.
  111. setContextCMR(info.Ctx, lr)
  112. } else {
  113. p.o.reportMu.Lock()
  114. defer p.o.reportMu.Unlock()
  115. if lr := p.o.report; lr != nil {
  116. setContextCMR(info.Ctx, lr)
  117. }
  118. }
  119. }
  120. return balancer.PickResult{SubConn: p.sc, Done: doneCB}, nil
  121. }
  122. func setContextCMR(ctx context.Context, lr *v3orcapb.OrcaLoadReport) {
  123. if r := orcaResultFromContext(ctx); r != nil {
  124. *r = lr
  125. }
  126. }
  127. type orcaKey string
  128. var orcaCtxKey = orcaKey("orcaResult")
  129. // contextWithORCAResult sets a key in ctx with a pointer to an ORCA load
  130. // report that is to be filled in by the "test_backend_metrics_load_balancer"
  131. // LB policy's Picker's Done callback.
  132. //
  133. // If a per-call load report is provided from the server for the call, result
  134. // will be filled with that, otherwise the most recent OOB load report is used.
  135. // If no OOB report has been received, result is not modified.
  136. func contextWithORCAResult(ctx context.Context, result **v3orcapb.OrcaLoadReport) context.Context {
  137. return context.WithValue(ctx, orcaCtxKey, result)
  138. }
  139. // orcaResultFromContext returns the ORCA load report stored in the context.
  140. // The LB policy uses this to communicate the load report back to the interop
  141. // client application.
  142. func orcaResultFromContext(ctx context.Context) **v3orcapb.OrcaLoadReport {
  143. v := ctx.Value(orcaCtxKey)
  144. if v == nil {
  145. return nil
  146. }
  147. return v.(**v3orcapb.OrcaLoadReport)
  148. }