common.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package common
  13. import (
  14. "context"
  15. "time"
  16. "golang.org/x/time/rate"
  17. corev1 "k8s.io/api/core/v1"
  18. "k8s.io/apimachinery/pkg/labels"
  19. "k8s.io/apimachinery/pkg/selection"
  20. "k8s.io/client-go/util/workqueue"
  21. ctrl "sigs.k8s.io/controller-runtime"
  22. "sigs.k8s.io/controller-runtime/pkg/cache"
  23. "sigs.k8s.io/controller-runtime/pkg/client"
  24. "sigs.k8s.io/controller-runtime/pkg/reconcile"
  25. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  26. )
  27. // BuildManagedSecretClient creates a new client that only sees secrets with the "managed" label.
  28. func BuildManagedSecretClient(mgr ctrl.Manager) (client.Client, error) {
  29. // secrets we manage will have the `reconcile.external-secrets.io/managed=true` label
  30. managedLabelReq, _ := labels.NewRequirement(esv1beta1.LabelManaged, selection.Equals, []string{esv1beta1.LabelManagedValue})
  31. managedLabelSelector := labels.NewSelector().Add(*managedLabelReq)
  32. // create a new cache with a label selector for managed secrets
  33. // NOTE: this means that the cache/client will be unable to see secrets without the "managed" label
  34. secretCacheOpts := cache.Options{
  35. HTTPClient: mgr.GetHTTPClient(),
  36. Scheme: mgr.GetScheme(),
  37. Mapper: mgr.GetRESTMapper(),
  38. ByObject: map[client.Object]cache.ByObject{
  39. &corev1.Secret{}: {
  40. Label: managedLabelSelector,
  41. },
  42. },
  43. // this requires us to explicitly start an informer for each object type
  44. // and helps avoid people mistakenly using the secret client for other resources
  45. ReaderFailOnMissingInformer: true,
  46. }
  47. secretCache, err := cache.New(mgr.GetConfig(), secretCacheOpts)
  48. if err != nil {
  49. return nil, err
  50. }
  51. // start an informer for secrets
  52. // this is required because we set ReaderFailOnMissingInformer to true
  53. _, err = secretCache.GetInformer(context.Background(), &corev1.Secret{})
  54. if err != nil {
  55. return nil, err
  56. }
  57. // add the secret cache to the manager, so that it starts at the same time
  58. err = mgr.Add(secretCache)
  59. if err != nil {
  60. return nil, err
  61. }
  62. // create a new client that uses the secret cache
  63. secretClient, err := client.New(mgr.GetConfig(), client.Options{
  64. HTTPClient: mgr.GetHTTPClient(),
  65. Scheme: mgr.GetScheme(),
  66. Mapper: mgr.GetRESTMapper(),
  67. Cache: &client.CacheOptions{
  68. Reader: secretCache,
  69. },
  70. })
  71. if err != nil {
  72. return nil, err
  73. }
  74. return secretClient, nil
  75. }
  76. // BuildRateLimiter creates a new rate limiter for our controllers.
  77. // NOTE: we dont use `DefaultTypedControllerRateLimiter` because it retries very aggressively, starting at 5ms!
  78. func BuildRateLimiter() workqueue.TypedRateLimiter[reconcile.Request] {
  79. // exponential backoff rate limiter
  80. // - this handles per-item rate limiting for ~failures~
  81. // - it uses an exponential backoff strategy were: delay = baseDelay * 2^failures
  82. // - graph visualization: https://www.desmos.com/calculator/fexlpdmiti
  83. failureBaseDelay := 1 * time.Second
  84. failureMaxDelay := 7 * time.Minute
  85. failureRateLimiter := workqueue.NewTypedItemExponentialFailureRateLimiter[reconcile.Request](failureBaseDelay, failureMaxDelay)
  86. // overall rate limiter
  87. // - this handles overall rate limiting, ignoring individual items and only considering the overall rate
  88. // - it implements a "token bucket" of size totalMaxBurst that is initially full,
  89. // and which is refilled at rate totalEventsPerSecond tokens per second.
  90. totalEventsPerSecond := 10
  91. totalMaxBurst := 100
  92. totalRateLimiter := &workqueue.TypedBucketRateLimiter[reconcile.Request]{
  93. Limiter: rate.NewLimiter(rate.Limit(totalEventsPerSecond), totalMaxBurst),
  94. }
  95. // return the worst-case (longest) of the rate limiters for a given item
  96. return workqueue.NewTypedMaxOfRateLimiter[reconcile.Request](failureRateLimiter, totalRateLimiter)
  97. }