service_config.go 14 KB

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