service_config.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. /*
  2. *
  3. * Copyright 2017 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 grpc
  19. import (
  20. "encoding/json"
  21. "errors"
  22. "fmt"
  23. "reflect"
  24. "time"
  25. "google.golang.org/grpc/codes"
  26. "google.golang.org/grpc/internal"
  27. internalserviceconfig "google.golang.org/grpc/internal/serviceconfig"
  28. "google.golang.org/grpc/serviceconfig"
  29. )
  30. const maxInt = int(^uint(0) >> 1)
  31. // MethodConfig defines the configuration recommended by the service providers for a
  32. // particular method.
  33. //
  34. // Deprecated: Users should not use this struct. Service config should be received
  35. // through name resolver, as specified here
  36. // https://github.com/grpc/grpc/blob/master/doc/service_config.md
  37. type MethodConfig = internalserviceconfig.MethodConfig
  38. type lbConfig struct {
  39. name string
  40. cfg serviceconfig.LoadBalancingConfig
  41. }
  42. // ServiceConfig is provided by the service provider and contains parameters for how
  43. // clients that connect to the service should behave.
  44. //
  45. // Deprecated: Users should not use this struct. Service config should be received
  46. // through name resolver, as specified here
  47. // https://github.com/grpc/grpc/blob/master/doc/service_config.md
  48. type ServiceConfig struct {
  49. serviceconfig.Config
  50. // LB is the load balancer the service providers recommends. This is
  51. // deprecated; lbConfigs is preferred. If lbConfig and LB are both present,
  52. // lbConfig will be used.
  53. LB *string
  54. // lbConfig is the service config's load balancing configuration. If
  55. // lbConfig and LB are both present, lbConfig will be used.
  56. lbConfig *lbConfig
  57. // Methods contains a map for the methods in this service. If there is an
  58. // exact match for a method (i.e. /service/method) in the map, use the
  59. // corresponding MethodConfig. If there's no exact match, look for the
  60. // default config for the service (/service/) and use the corresponding
  61. // MethodConfig if it exists. Otherwise, the method has no MethodConfig to
  62. // use.
  63. Methods map[string]MethodConfig
  64. // If a retryThrottlingPolicy is provided, gRPC will automatically throttle
  65. // retry attempts and hedged RPCs when the client’s ratio of failures to
  66. // successes exceeds a threshold.
  67. //
  68. // For each server name, the gRPC client will maintain a token_count which is
  69. // initially set to maxTokens, and can take values between 0 and maxTokens.
  70. //
  71. // Every outgoing RPC (regardless of service or method invoked) will change
  72. // token_count as follows:
  73. //
  74. // - Every failed RPC will decrement the token_count by 1.
  75. // - Every successful RPC will increment the token_count by tokenRatio.
  76. //
  77. // If token_count is less than or equal to maxTokens / 2, then RPCs will not
  78. // be retried and hedged RPCs will not be sent.
  79. retryThrottling *retryThrottlingPolicy
  80. // healthCheckConfig must be set as one of the requirement to enable LB channel
  81. // health check.
  82. healthCheckConfig *healthCheckConfig
  83. // rawJSONString stores service config json string that get parsed into
  84. // this service config struct.
  85. rawJSONString string
  86. }
  87. // healthCheckConfig defines the go-native version of the LB channel health check config.
  88. type healthCheckConfig struct {
  89. // serviceName is the service name to use in the health-checking request.
  90. ServiceName string
  91. }
  92. type jsonRetryPolicy struct {
  93. MaxAttempts int
  94. InitialBackoff internalserviceconfig.Duration
  95. MaxBackoff internalserviceconfig.Duration
  96. BackoffMultiplier float64
  97. RetryableStatusCodes []codes.Code
  98. }
  99. // retryThrottlingPolicy defines the go-native version of the retry throttling
  100. // policy defined by the service config here:
  101. // https://github.com/grpc/proposal/blob/master/A6-client-retries.md#integration-with-service-config
  102. type retryThrottlingPolicy struct {
  103. // The number of tokens starts at maxTokens. The token_count will always be
  104. // between 0 and maxTokens.
  105. //
  106. // This field is required and must be greater than zero.
  107. MaxTokens float64
  108. // The amount of tokens to add on each successful RPC. Typically this will
  109. // be some number between 0 and 1, e.g., 0.1.
  110. //
  111. // This field is required and must be greater than zero. Up to 3 decimal
  112. // places are supported.
  113. TokenRatio float64
  114. }
  115. type jsonName struct {
  116. Service string
  117. Method string
  118. }
  119. var (
  120. errDuplicatedName = errors.New("duplicated name")
  121. errEmptyServiceNonEmptyMethod = errors.New("cannot combine empty 'service' and non-empty 'method'")
  122. )
  123. func (j jsonName) generatePath() (string, error) {
  124. if j.Service == "" {
  125. if j.Method != "" {
  126. return "", errEmptyServiceNonEmptyMethod
  127. }
  128. return "", nil
  129. }
  130. res := "/" + j.Service + "/"
  131. if j.Method != "" {
  132. res += j.Method
  133. }
  134. return res, nil
  135. }
  136. // TODO(lyuxuan): delete this struct after cleaning up old service config implementation.
  137. type jsonMC struct {
  138. Name *[]jsonName
  139. WaitForReady *bool
  140. Timeout *internalserviceconfig.Duration
  141. MaxRequestMessageBytes *int64
  142. MaxResponseMessageBytes *int64
  143. RetryPolicy *jsonRetryPolicy
  144. }
  145. // TODO(lyuxuan): delete this struct after cleaning up old service config implementation.
  146. type jsonSC struct {
  147. LoadBalancingPolicy *string
  148. LoadBalancingConfig *internalserviceconfig.BalancerConfig
  149. MethodConfig *[]jsonMC
  150. RetryThrottling *retryThrottlingPolicy
  151. HealthCheckConfig *healthCheckConfig
  152. }
  153. func init() {
  154. internal.ParseServiceConfig = parseServiceConfig
  155. }
  156. func parseServiceConfig(js string) *serviceconfig.ParseResult {
  157. if len(js) == 0 {
  158. return &serviceconfig.ParseResult{Err: fmt.Errorf("no JSON service config provided")}
  159. }
  160. var rsc jsonSC
  161. err := json.Unmarshal([]byte(js), &rsc)
  162. if err != nil {
  163. logger.Warningf("grpc: unmarshaling service config %s: %v", js, err)
  164. return &serviceconfig.ParseResult{Err: err}
  165. }
  166. sc := ServiceConfig{
  167. LB: rsc.LoadBalancingPolicy,
  168. Methods: make(map[string]MethodConfig),
  169. retryThrottling: rsc.RetryThrottling,
  170. healthCheckConfig: rsc.HealthCheckConfig,
  171. rawJSONString: js,
  172. }
  173. if c := rsc.LoadBalancingConfig; c != nil {
  174. sc.lbConfig = &lbConfig{
  175. name: c.Name,
  176. cfg: c.Config,
  177. }
  178. }
  179. if rsc.MethodConfig == nil {
  180. return &serviceconfig.ParseResult{Config: &sc}
  181. }
  182. paths := map[string]struct{}{}
  183. for _, m := range *rsc.MethodConfig {
  184. if m.Name == nil {
  185. continue
  186. }
  187. mc := MethodConfig{
  188. WaitForReady: m.WaitForReady,
  189. Timeout: (*time.Duration)(m.Timeout),
  190. }
  191. if mc.RetryPolicy, err = convertRetryPolicy(m.RetryPolicy); err != nil {
  192. logger.Warningf("grpc: unmarshaling service config %s: %v", js, err)
  193. return &serviceconfig.ParseResult{Err: err}
  194. }
  195. if m.MaxRequestMessageBytes != nil {
  196. if *m.MaxRequestMessageBytes > int64(maxInt) {
  197. mc.MaxReqSize = newInt(maxInt)
  198. } else {
  199. mc.MaxReqSize = newInt(int(*m.MaxRequestMessageBytes))
  200. }
  201. }
  202. if m.MaxResponseMessageBytes != nil {
  203. if *m.MaxResponseMessageBytes > int64(maxInt) {
  204. mc.MaxRespSize = newInt(maxInt)
  205. } else {
  206. mc.MaxRespSize = newInt(int(*m.MaxResponseMessageBytes))
  207. }
  208. }
  209. for i, n := range *m.Name {
  210. path, err := n.generatePath()
  211. if err != nil {
  212. logger.Warningf("grpc: error unmarshaling service config %s due to methodConfig[%d]: %v", js, i, err)
  213. return &serviceconfig.ParseResult{Err: err}
  214. }
  215. if _, ok := paths[path]; ok {
  216. err = errDuplicatedName
  217. logger.Warningf("grpc: error unmarshaling service config %s due to methodConfig[%d]: %v", js, i, err)
  218. return &serviceconfig.ParseResult{Err: err}
  219. }
  220. paths[path] = struct{}{}
  221. sc.Methods[path] = mc
  222. }
  223. }
  224. if sc.retryThrottling != nil {
  225. if mt := sc.retryThrottling.MaxTokens; mt <= 0 || mt > 1000 {
  226. return &serviceconfig.ParseResult{Err: fmt.Errorf("invalid retry throttling config: maxTokens (%v) out of range (0, 1000]", mt)}
  227. }
  228. if tr := sc.retryThrottling.TokenRatio; tr <= 0 {
  229. return &serviceconfig.ParseResult{Err: fmt.Errorf("invalid retry throttling config: tokenRatio (%v) may not be negative", tr)}
  230. }
  231. }
  232. return &serviceconfig.ParseResult{Config: &sc}
  233. }
  234. func convertRetryPolicy(jrp *jsonRetryPolicy) (p *internalserviceconfig.RetryPolicy, err error) {
  235. if jrp == nil {
  236. return nil, nil
  237. }
  238. if jrp.MaxAttempts <= 1 ||
  239. jrp.InitialBackoff <= 0 ||
  240. jrp.MaxBackoff <= 0 ||
  241. jrp.BackoffMultiplier <= 0 ||
  242. len(jrp.RetryableStatusCodes) == 0 {
  243. logger.Warningf("grpc: ignoring retry policy %v due to illegal configuration", jrp)
  244. return nil, nil
  245. }
  246. rp := &internalserviceconfig.RetryPolicy{
  247. MaxAttempts: jrp.MaxAttempts,
  248. InitialBackoff: time.Duration(jrp.InitialBackoff),
  249. MaxBackoff: time.Duration(jrp.MaxBackoff),
  250. BackoffMultiplier: jrp.BackoffMultiplier,
  251. RetryableStatusCodes: make(map[codes.Code]bool),
  252. }
  253. if rp.MaxAttempts > 5 {
  254. // TODO(retry): Make the max maxAttempts configurable.
  255. rp.MaxAttempts = 5
  256. }
  257. for _, code := range jrp.RetryableStatusCodes {
  258. rp.RetryableStatusCodes[code] = true
  259. }
  260. return rp, nil
  261. }
  262. func min(a, b *int) *int {
  263. if *a < *b {
  264. return a
  265. }
  266. return b
  267. }
  268. func getMaxSize(mcMax, doptMax *int, defaultVal int) *int {
  269. if mcMax == nil && doptMax == nil {
  270. return &defaultVal
  271. }
  272. if mcMax != nil && doptMax != nil {
  273. return min(mcMax, doptMax)
  274. }
  275. if mcMax != nil {
  276. return mcMax
  277. }
  278. return doptMax
  279. }
  280. func newInt(b int) *int {
  281. return &b
  282. }
  283. func init() {
  284. internal.EqualServiceConfigForTesting = equalServiceConfig
  285. }
  286. // equalServiceConfig compares two configs. The rawJSONString field is ignored,
  287. // because they may diff in white spaces.
  288. //
  289. // If any of them is NOT *ServiceConfig, return false.
  290. func equalServiceConfig(a, b serviceconfig.Config) bool {
  291. if a == nil && b == nil {
  292. return true
  293. }
  294. aa, ok := a.(*ServiceConfig)
  295. if !ok {
  296. return false
  297. }
  298. bb, ok := b.(*ServiceConfig)
  299. if !ok {
  300. return false
  301. }
  302. aaRaw := aa.rawJSONString
  303. aa.rawJSONString = ""
  304. bbRaw := bb.rawJSONString
  305. bb.rawJSONString = ""
  306. defer func() {
  307. aa.rawJSONString = aaRaw
  308. bb.rawJSONString = bbRaw
  309. }()
  310. // Using reflect.DeepEqual instead of cmp.Equal because many balancer
  311. // configs are unexported, and cmp.Equal cannot compare unexported fields
  312. // from unexported structs.
  313. return reflect.DeepEqual(aa, bb)
  314. }