service_config.go 14 KB

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