You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

373 line
11 KiB

  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. // healthCheckConfig must be set as one of the requirement to enable LB channel
  92. // health check.
  93. healthCheckConfig *healthCheckConfig
  94. }
  95. // healthCheckConfig defines the go-native version of the LB channel health check config.
  96. type healthCheckConfig struct {
  97. // serviceName is the service name to use in the health-checking request.
  98. ServiceName string
  99. }
  100. // retryPolicy defines the go-native version of the retry policy defined by the
  101. // service config here:
  102. // https://github.com/grpc/proposal/blob/master/A6-client-retries.md#integration-with-service-config
  103. type retryPolicy struct {
  104. // MaxAttempts is the maximum number of attempts, including the original RPC.
  105. //
  106. // This field is required and must be two or greater.
  107. maxAttempts int
  108. // Exponential backoff parameters. The initial retry attempt will occur at
  109. // random(0, initialBackoffMS). In general, the nth attempt will occur at
  110. // random(0,
  111. // min(initialBackoffMS*backoffMultiplier**(n-1), maxBackoffMS)).
  112. //
  113. // These fields are required and must be greater than zero.
  114. initialBackoff time.Duration
  115. maxBackoff time.Duration
  116. backoffMultiplier float64
  117. // The set of status codes which may be retried.
  118. //
  119. // Status codes are specified as strings, e.g., "UNAVAILABLE".
  120. //
  121. // This field is required and must be non-empty.
  122. // Note: a set is used to store this for easy lookup.
  123. retryableStatusCodes map[codes.Code]bool
  124. }
  125. type jsonRetryPolicy struct {
  126. MaxAttempts int
  127. InitialBackoff string
  128. MaxBackoff string
  129. BackoffMultiplier float64
  130. RetryableStatusCodes []codes.Code
  131. }
  132. // retryThrottlingPolicy defines the go-native version of the retry throttling
  133. // policy defined by the service config here:
  134. // https://github.com/grpc/proposal/blob/master/A6-client-retries.md#integration-with-service-config
  135. type retryThrottlingPolicy struct {
  136. // The number of tokens starts at maxTokens. The token_count will always be
  137. // between 0 and maxTokens.
  138. //
  139. // This field is required and must be greater than zero.
  140. MaxTokens float64
  141. // The amount of tokens to add on each successful RPC. Typically this will
  142. // be some number between 0 and 1, e.g., 0.1.
  143. //
  144. // This field is required and must be greater than zero. Up to 3 decimal
  145. // places are supported.
  146. TokenRatio float64
  147. }
  148. func parseDuration(s *string) (*time.Duration, error) {
  149. if s == nil {
  150. return nil, nil
  151. }
  152. if !strings.HasSuffix(*s, "s") {
  153. return nil, fmt.Errorf("malformed duration %q", *s)
  154. }
  155. ss := strings.SplitN((*s)[:len(*s)-1], ".", 3)
  156. if len(ss) > 2 {
  157. return nil, fmt.Errorf("malformed duration %q", *s)
  158. }
  159. // hasDigits is set if either the whole or fractional part of the number is
  160. // present, since both are optional but one is required.
  161. hasDigits := false
  162. var d time.Duration
  163. if len(ss[0]) > 0 {
  164. i, err := strconv.ParseInt(ss[0], 10, 32)
  165. if err != nil {
  166. return nil, fmt.Errorf("malformed duration %q: %v", *s, err)
  167. }
  168. d = time.Duration(i) * time.Second
  169. hasDigits = true
  170. }
  171. if len(ss) == 2 && len(ss[1]) > 0 {
  172. if len(ss[1]) > 9 {
  173. return nil, fmt.Errorf("malformed duration %q", *s)
  174. }
  175. f, err := strconv.ParseInt(ss[1], 10, 64)
  176. if err != nil {
  177. return nil, fmt.Errorf("malformed duration %q: %v", *s, err)
  178. }
  179. for i := 9; i > len(ss[1]); i-- {
  180. f *= 10
  181. }
  182. d += time.Duration(f)
  183. hasDigits = true
  184. }
  185. if !hasDigits {
  186. return nil, fmt.Errorf("malformed duration %q", *s)
  187. }
  188. return &d, nil
  189. }
  190. type jsonName struct {
  191. Service *string
  192. Method *string
  193. }
  194. func (j jsonName) generatePath() (string, bool) {
  195. if j.Service == nil {
  196. return "", false
  197. }
  198. res := "/" + *j.Service + "/"
  199. if j.Method != nil {
  200. res += *j.Method
  201. }
  202. return res, true
  203. }
  204. // TODO(lyuxuan): delete this struct after cleaning up old service config implementation.
  205. type jsonMC struct {
  206. Name *[]jsonName
  207. WaitForReady *bool
  208. Timeout *string
  209. MaxRequestMessageBytes *int64
  210. MaxResponseMessageBytes *int64
  211. RetryPolicy *jsonRetryPolicy
  212. }
  213. // TODO(lyuxuan): delete this struct after cleaning up old service config implementation.
  214. type jsonSC struct {
  215. LoadBalancingPolicy *string
  216. MethodConfig *[]jsonMC
  217. RetryThrottling *retryThrottlingPolicy
  218. HealthCheckConfig *healthCheckConfig
  219. }
  220. func parseServiceConfig(js string) (ServiceConfig, error) {
  221. if len(js) == 0 {
  222. return ServiceConfig{}, fmt.Errorf("no JSON service config provided")
  223. }
  224. var rsc jsonSC
  225. err := json.Unmarshal([]byte(js), &rsc)
  226. if err != nil {
  227. grpclog.Warningf("grpc: parseServiceConfig error unmarshaling %s due to %v", js, err)
  228. return ServiceConfig{}, err
  229. }
  230. sc := ServiceConfig{
  231. LB: rsc.LoadBalancingPolicy,
  232. Methods: make(map[string]MethodConfig),
  233. retryThrottling: rsc.RetryThrottling,
  234. healthCheckConfig: rsc.HealthCheckConfig,
  235. }
  236. if rsc.MethodConfig == nil {
  237. return sc, nil
  238. }
  239. for _, m := range *rsc.MethodConfig {
  240. if m.Name == nil {
  241. continue
  242. }
  243. d, err := parseDuration(m.Timeout)
  244. if err != nil {
  245. grpclog.Warningf("grpc: parseServiceConfig error unmarshaling %s due to %v", js, err)
  246. return ServiceConfig{}, err
  247. }
  248. mc := MethodConfig{
  249. WaitForReady: m.WaitForReady,
  250. Timeout: d,
  251. }
  252. if mc.retryPolicy, err = convertRetryPolicy(m.RetryPolicy); err != nil {
  253. grpclog.Warningf("grpc: parseServiceConfig error unmarshaling %s due to %v", js, err)
  254. return ServiceConfig{}, err
  255. }
  256. if m.MaxRequestMessageBytes != nil {
  257. if *m.MaxRequestMessageBytes > int64(maxInt) {
  258. mc.MaxReqSize = newInt(maxInt)
  259. } else {
  260. mc.MaxReqSize = newInt(int(*m.MaxRequestMessageBytes))
  261. }
  262. }
  263. if m.MaxResponseMessageBytes != nil {
  264. if *m.MaxResponseMessageBytes > int64(maxInt) {
  265. mc.MaxRespSize = newInt(maxInt)
  266. } else {
  267. mc.MaxRespSize = newInt(int(*m.MaxResponseMessageBytes))
  268. }
  269. }
  270. for _, n := range *m.Name {
  271. if path, valid := n.generatePath(); valid {
  272. sc.Methods[path] = mc
  273. }
  274. }
  275. }
  276. if sc.retryThrottling != nil {
  277. if sc.retryThrottling.MaxTokens <= 0 ||
  278. sc.retryThrottling.MaxTokens > 1000 ||
  279. sc.retryThrottling.TokenRatio <= 0 {
  280. // Illegal throttling config; disable throttling.
  281. sc.retryThrottling = nil
  282. }
  283. }
  284. return sc, nil
  285. }
  286. func convertRetryPolicy(jrp *jsonRetryPolicy) (p *retryPolicy, err error) {
  287. if jrp == nil {
  288. return nil, nil
  289. }
  290. ib, err := parseDuration(&jrp.InitialBackoff)
  291. if err != nil {
  292. return nil, err
  293. }
  294. mb, err := parseDuration(&jrp.MaxBackoff)
  295. if err != nil {
  296. return nil, err
  297. }
  298. if jrp.MaxAttempts <= 1 ||
  299. *ib <= 0 ||
  300. *mb <= 0 ||
  301. jrp.BackoffMultiplier <= 0 ||
  302. len(jrp.RetryableStatusCodes) == 0 {
  303. grpclog.Warningf("grpc: ignoring retry policy %v due to illegal configuration", jrp)
  304. return nil, nil
  305. }
  306. rp := &retryPolicy{
  307. maxAttempts: jrp.MaxAttempts,
  308. initialBackoff: *ib,
  309. maxBackoff: *mb,
  310. backoffMultiplier: jrp.BackoffMultiplier,
  311. retryableStatusCodes: make(map[codes.Code]bool),
  312. }
  313. if rp.maxAttempts > 5 {
  314. // TODO(retry): Make the max maxAttempts configurable.
  315. rp.maxAttempts = 5
  316. }
  317. for _, code := range jrp.RetryableStatusCodes {
  318. rp.retryableStatusCodes[code] = true
  319. }
  320. return rp, nil
  321. }
  322. func min(a, b *int) *int {
  323. if *a < *b {
  324. return a
  325. }
  326. return b
  327. }
  328. func getMaxSize(mcMax, doptMax *int, defaultVal int) *int {
  329. if mcMax == nil && doptMax == nil {
  330. return &defaultVal
  331. }
  332. if mcMax != nil && doptMax != nil {
  333. return min(mcMax, doptMax)
  334. }
  335. if mcMax != nil {
  336. return mcMax
  337. }
  338. return doptMax
  339. }
  340. func newInt(b int) *int {
  341. return &b
  342. }