service_config.go 12 KB

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