service_config.go 11 KB

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