service_config.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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, initialBackoffMS). In general, the nth attempt will occur at
  126. // random(0,
  127. // min(initialBackoffMS*backoffMultiplier**(n-1), maxBackoffMS)).
  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.ParseServiceConfig = func(sc string) (interface{}, error) {
  240. return parseServiceConfig(sc)
  241. }
  242. }
  243. func parseServiceConfig(js string) (*ServiceConfig, error) {
  244. if len(js) == 0 {
  245. return nil, fmt.Errorf("no JSON service config provided")
  246. }
  247. var rsc jsonSC
  248. err := json.Unmarshal([]byte(js), &rsc)
  249. if err != nil {
  250. grpclog.Warningf("grpc: parseServiceConfig error unmarshaling %s due to %v", js, err)
  251. return nil, err
  252. }
  253. sc := ServiceConfig{
  254. LB: rsc.LoadBalancingPolicy,
  255. Methods: make(map[string]MethodConfig),
  256. retryThrottling: rsc.RetryThrottling,
  257. healthCheckConfig: rsc.HealthCheckConfig,
  258. rawJSONString: js,
  259. }
  260. if rsc.LoadBalancingConfig != nil {
  261. for i, lbcfg := range *rsc.LoadBalancingConfig {
  262. if len(lbcfg) != 1 {
  263. err := fmt.Errorf("invalid loadBalancingConfig: entry %v does not contain exactly 1 policy/config pair: %q", i, lbcfg)
  264. grpclog.Warningf(err.Error())
  265. return nil, err
  266. }
  267. var name string
  268. var jsonCfg json.RawMessage
  269. for name, jsonCfg = range lbcfg {
  270. }
  271. builder := balancer.Get(name)
  272. if builder == nil {
  273. continue
  274. }
  275. sc.lbConfig = &lbConfig{name: name}
  276. if parser, ok := builder.(balancer.ConfigParser); ok {
  277. var err error
  278. sc.lbConfig.cfg, err = parser.ParseConfig(jsonCfg)
  279. if err != nil {
  280. return nil, fmt.Errorf("error parsing loadBalancingConfig for policy %q: %v", name, err)
  281. }
  282. } else if string(jsonCfg) != "{}" {
  283. grpclog.Warningf("non-empty balancer configuration %q, but balancer does not implement ParseConfig", string(jsonCfg))
  284. }
  285. break
  286. }
  287. }
  288. if rsc.MethodConfig == nil {
  289. return &sc, nil
  290. }
  291. for _, m := range *rsc.MethodConfig {
  292. if m.Name == nil {
  293. continue
  294. }
  295. d, err := parseDuration(m.Timeout)
  296. if err != nil {
  297. grpclog.Warningf("grpc: parseServiceConfig error unmarshaling %s due to %v", js, err)
  298. return nil, err
  299. }
  300. mc := MethodConfig{
  301. WaitForReady: m.WaitForReady,
  302. Timeout: d,
  303. }
  304. if mc.retryPolicy, err = convertRetryPolicy(m.RetryPolicy); err != nil {
  305. grpclog.Warningf("grpc: parseServiceConfig error unmarshaling %s due to %v", js, err)
  306. return nil, err
  307. }
  308. if m.MaxRequestMessageBytes != nil {
  309. if *m.MaxRequestMessageBytes > int64(maxInt) {
  310. mc.MaxReqSize = newInt(maxInt)
  311. } else {
  312. mc.MaxReqSize = newInt(int(*m.MaxRequestMessageBytes))
  313. }
  314. }
  315. if m.MaxResponseMessageBytes != nil {
  316. if *m.MaxResponseMessageBytes > int64(maxInt) {
  317. mc.MaxRespSize = newInt(maxInt)
  318. } else {
  319. mc.MaxRespSize = newInt(int(*m.MaxResponseMessageBytes))
  320. }
  321. }
  322. for _, n := range *m.Name {
  323. if path, valid := n.generatePath(); valid {
  324. sc.Methods[path] = mc
  325. }
  326. }
  327. }
  328. if sc.retryThrottling != nil {
  329. if mt := sc.retryThrottling.MaxTokens; mt <= 0 || mt > 1000 {
  330. return nil, fmt.Errorf("invalid retry throttling config: maxTokens (%v) out of range (0, 1000]", mt)
  331. }
  332. if tr := sc.retryThrottling.TokenRatio; tr <= 0 {
  333. return nil, fmt.Errorf("invalid retry throttling config: tokenRatio (%v) may not be negative", tr)
  334. }
  335. }
  336. return &sc, nil
  337. }
  338. func convertRetryPolicy(jrp *jsonRetryPolicy) (p *retryPolicy, err error) {
  339. if jrp == nil {
  340. return nil, nil
  341. }
  342. ib, err := parseDuration(&jrp.InitialBackoff)
  343. if err != nil {
  344. return nil, err
  345. }
  346. mb, err := parseDuration(&jrp.MaxBackoff)
  347. if err != nil {
  348. return nil, err
  349. }
  350. if jrp.MaxAttempts <= 1 ||
  351. *ib <= 0 ||
  352. *mb <= 0 ||
  353. jrp.BackoffMultiplier <= 0 ||
  354. len(jrp.RetryableStatusCodes) == 0 {
  355. grpclog.Warningf("grpc: ignoring retry policy %v due to illegal configuration", jrp)
  356. return nil, nil
  357. }
  358. rp := &retryPolicy{
  359. maxAttempts: jrp.MaxAttempts,
  360. initialBackoff: *ib,
  361. maxBackoff: *mb,
  362. backoffMultiplier: jrp.BackoffMultiplier,
  363. retryableStatusCodes: make(map[codes.Code]bool),
  364. }
  365. if rp.maxAttempts > 5 {
  366. // TODO(retry): Make the max maxAttempts configurable.
  367. rp.maxAttempts = 5
  368. }
  369. for _, code := range jrp.RetryableStatusCodes {
  370. rp.retryableStatusCodes[code] = true
  371. }
  372. return rp, nil
  373. }
  374. func min(a, b *int) *int {
  375. if *a < *b {
  376. return a
  377. }
  378. return b
  379. }
  380. func getMaxSize(mcMax, doptMax *int, defaultVal int) *int {
  381. if mcMax == nil && doptMax == nil {
  382. return &defaultVal
  383. }
  384. if mcMax != nil && doptMax != nil {
  385. return min(mcMax, doptMax)
  386. }
  387. if mcMax != nil {
  388. return mcMax
  389. }
  390. return doptMax
  391. }
  392. func newInt(b int) *int {
  393. return &b
  394. }