grpclb_config.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. *
  3. * Copyright 2019 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 grpclb
  19. import (
  20. "encoding/json"
  21. "google.golang.org/grpc"
  22. "google.golang.org/grpc/balancer/roundrobin"
  23. )
  24. type serviceConfig struct {
  25. LoadBalancingConfig *[]map[string]*grpclbServiceConfig
  26. }
  27. type grpclbServiceConfig struct {
  28. ChildPolicy *[]map[string]json.RawMessage
  29. }
  30. func parseFullServiceConfig(s string) *serviceConfig {
  31. var ret serviceConfig
  32. err := json.Unmarshal([]byte(s), &ret)
  33. if err != nil {
  34. return nil
  35. }
  36. return &ret
  37. }
  38. func parseServiceConfig(s string) *grpclbServiceConfig {
  39. parsedSC := parseFullServiceConfig(s)
  40. if parsedSC == nil {
  41. return nil
  42. }
  43. lbConfigs := parsedSC.LoadBalancingConfig
  44. if lbConfigs == nil {
  45. return nil
  46. }
  47. for _, lbC := range *lbConfigs {
  48. if v, ok := lbC[grpclbName]; ok {
  49. return v
  50. }
  51. }
  52. return nil
  53. }
  54. const (
  55. roundRobinName = roundrobin.Name
  56. pickFirstName = grpc.PickFirstBalancerName
  57. )
  58. func childIsPickFirst(s string) bool {
  59. parsedSC := parseServiceConfig(s)
  60. if parsedSC == nil {
  61. return false
  62. }
  63. childConfigs := parsedSC.ChildPolicy
  64. if childConfigs == nil {
  65. return false
  66. }
  67. for _, childC := range *childConfigs {
  68. // If round_robin exists before pick_first, return false
  69. if _, ok := childC[roundRobinName]; ok {
  70. return false
  71. }
  72. // If pick_first is before round_robin, return true
  73. if _, ok := childC[pickFirstName]; ok {
  74. return true
  75. }
  76. }
  77. return false
  78. }