urlbackoff.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package rest
  14. import (
  15. "context"
  16. "fmt"
  17. "net/url"
  18. "time"
  19. "k8s.io/apimachinery/pkg/util/sets"
  20. "k8s.io/client-go/util/flowcontrol"
  21. "k8s.io/klog/v2"
  22. )
  23. // Set of resp. Codes that we backoff for.
  24. // In general these should be errors that indicate a server is overloaded.
  25. // These shouldn't be configured by any user, we set them based on conventions
  26. // described in
  27. var serverIsOverloadedSet = sets.NewInt(429)
  28. var maxResponseCode = 499
  29. //go:generate mockery
  30. // Deprecated: BackoffManager.Sleep ignores the caller's context. Use BackoffManagerWithContext instead.
  31. type BackoffManager interface {
  32. UpdateBackoff(actualURL *url.URL, err error, responseCode int)
  33. CalculateBackoff(actualURL *url.URL) time.Duration
  34. Sleep(d time.Duration)
  35. }
  36. type BackoffManagerWithContext interface {
  37. UpdateBackoffWithContext(ctx context.Context, actualURL *url.URL, err error, responseCode int)
  38. CalculateBackoffWithContext(ctx context.Context, actualURL *url.URL) time.Duration
  39. SleepWithContext(ctx context.Context, d time.Duration)
  40. }
  41. var _ BackoffManager = &URLBackoff{}
  42. var _ BackoffManagerWithContext = &URLBackoff{}
  43. // URLBackoff struct implements the semantics on top of Backoff which
  44. // we need for URL specific exponential backoff.
  45. type URLBackoff struct {
  46. // Uses backoff as underlying implementation.
  47. Backoff *flowcontrol.Backoff
  48. }
  49. // NoBackoff is a stub implementation, can be used for mocking or else as a default.
  50. type NoBackoff struct {
  51. }
  52. func (n *NoBackoff) UpdateBackoff(actualURL *url.URL, err error, responseCode int) {
  53. // do nothing.
  54. }
  55. func (n *NoBackoff) UpdateBackoffWithContext(ctx context.Context, actualURL *url.URL, err error, responseCode int) {
  56. // do nothing.
  57. }
  58. func (n *NoBackoff) CalculateBackoff(actualURL *url.URL) time.Duration {
  59. return 0 * time.Second
  60. }
  61. func (n *NoBackoff) CalculateBackoffWithContext(ctx context.Context, actualURL *url.URL) time.Duration {
  62. return 0 * time.Second
  63. }
  64. func (n *NoBackoff) Sleep(d time.Duration) {
  65. time.Sleep(d)
  66. }
  67. func (n *NoBackoff) SleepWithContext(ctx context.Context, d time.Duration) {
  68. if d == 0 {
  69. return
  70. }
  71. t := time.NewTimer(d)
  72. defer t.Stop()
  73. select {
  74. case <-ctx.Done():
  75. case <-t.C:
  76. }
  77. }
  78. // Disable makes the backoff trivial, i.e., sets it to zero. This might be used
  79. // by tests which want to run 1000s of mock requests without slowing down.
  80. func (b *URLBackoff) Disable() {
  81. b.Backoff = flowcontrol.NewBackOff(0*time.Second, 0*time.Second)
  82. }
  83. // baseUrlKey returns the key which urls will be mapped to.
  84. // For example, 127.0.0.1:8080/api/v2/abcde -> 127.0.0.1:8080.
  85. func (b *URLBackoff) baseUrlKey(rawurl *url.URL) string {
  86. // Simple implementation for now, just the host.
  87. // We may backoff specific paths (i.e. "pods") differentially
  88. // in the future.
  89. host, err := url.Parse(rawurl.String())
  90. if err != nil {
  91. panic(fmt.Sprintf("Error parsing bad URL %q: %v", rawurl, err))
  92. }
  93. return host.Host
  94. }
  95. // UpdateBackoff updates backoff metadata
  96. func (b *URLBackoff) UpdateBackoff(actualURL *url.URL, err error, responseCode int) {
  97. b.UpdateBackoffWithContext(context.Background(), actualURL, err, responseCode)
  98. }
  99. // UpdateBackoffWithContext updates backoff metadata
  100. func (b *URLBackoff) UpdateBackoffWithContext(ctx context.Context, actualURL *url.URL, err error, responseCode int) {
  101. // range for retry counts that we store is [0,13]
  102. if responseCode > maxResponseCode || serverIsOverloadedSet.Has(responseCode) {
  103. b.Backoff.Next(b.baseUrlKey(actualURL), b.Backoff.Clock.Now())
  104. return
  105. } else if responseCode >= 300 || err != nil {
  106. klog.FromContext(ctx).V(4).Info("Client is returning errors", "code", responseCode, "err", err)
  107. }
  108. //If we got this far, there is no backoff required for this URL anymore.
  109. b.Backoff.Reset(b.baseUrlKey(actualURL))
  110. }
  111. // CalculateBackoff takes a url and back's off exponentially,
  112. // based on its knowledge of existing failures.
  113. func (b *URLBackoff) CalculateBackoff(actualURL *url.URL) time.Duration {
  114. return b.Backoff.Get(b.baseUrlKey(actualURL))
  115. }
  116. // CalculateBackoffWithContext takes a url and back's off exponentially,
  117. // based on its knowledge of existing failures.
  118. func (b *URLBackoff) CalculateBackoffWithContext(_ context.Context, actualURL *url.URL) time.Duration {
  119. return b.CalculateBackoff(actualURL)
  120. }
  121. func (b *URLBackoff) Sleep(d time.Duration) {
  122. b.Backoff.Clock.Sleep(d)
  123. }
  124. func (b *URLBackoff) SleepWithContext(ctx context.Context, d time.Duration) {
  125. if d == 0 {
  126. return
  127. }
  128. t := b.Backoff.Clock.NewTimer(d)
  129. defer t.Stop()
  130. select {
  131. case <-ctx.Done():
  132. case <-t.C():
  133. }
  134. }
  135. // backoffManagerNopContext wraps a BackoffManager and adds the *WithContext methods.
  136. type backoffManagerNopContext struct {
  137. BackoffManager
  138. }
  139. var _ BackoffManager = &backoffManagerNopContext{}
  140. var _ BackoffManagerWithContext = &backoffManagerNopContext{}
  141. func (b *backoffManagerNopContext) UpdateBackoffWithContext(ctx context.Context, actualURL *url.URL, err error, responseCode int) {
  142. b.UpdateBackoff(actualURL, err, responseCode)
  143. }
  144. func (b *backoffManagerNopContext) CalculateBackoffWithContext(ctx context.Context, actualURL *url.URL) time.Duration {
  145. return b.CalculateBackoff(actualURL)
  146. }
  147. func (b *backoffManagerNopContext) SleepWithContext(ctx context.Context, d time.Duration) {
  148. b.Sleep(d)
  149. }