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

service_config.go 12 kB

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