common.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. /*
  2. Copyright © 2025 ESO Maintainer Team
  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. https://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 common
  14. import (
  15. "context"
  16. "time"
  17. "golang.org/x/time/rate"
  18. corev1 "k8s.io/api/core/v1"
  19. "k8s.io/apimachinery/pkg/labels"
  20. "k8s.io/apimachinery/pkg/selection"
  21. "k8s.io/client-go/util/workqueue"
  22. ctrl "sigs.k8s.io/controller-runtime"
  23. "sigs.k8s.io/controller-runtime/pkg/cache"
  24. "sigs.k8s.io/controller-runtime/pkg/client"
  25. "sigs.k8s.io/controller-runtime/pkg/reconcile"
  26. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  27. )
  28. // BuildManagedSecretClient creates a new client that only sees secrets with the "managed" label.
  29. func BuildManagedSecretClient(mgr ctrl.Manager, namespace string) (client.Client, error) {
  30. // secrets we manage will have the `reconcile.external-secrets.io/managed=true` label
  31. managedLabelReq, _ := labels.NewRequirement(esv1.LabelManaged, selection.Equals, []string{esv1.LabelManagedValue})
  32. managedLabelSelector := labels.NewSelector().Add(*managedLabelReq)
  33. // create a new cache with a label selector for managed secrets
  34. // NOTE: this means that the cache/client will be unable to see secrets without the "managed" label
  35. secretCacheOpts := cache.Options{
  36. HTTPClient: mgr.GetHTTPClient(),
  37. Scheme: mgr.GetScheme(),
  38. Mapper: mgr.GetRESTMapper(),
  39. ByObject: map[client.Object]cache.ByObject{
  40. &corev1.Secret{}: {
  41. Label: managedLabelSelector,
  42. },
  43. },
  44. // this requires us to explicitly start an informer for each object type
  45. // and helps avoid people mistakenly using the secret client for other resources
  46. ReaderFailOnMissingInformer: true,
  47. }
  48. if namespace != "" {
  49. secretCacheOpts.DefaultNamespaces = map[string]cache.Config{
  50. namespace: {},
  51. }
  52. }
  53. secretCache, err := cache.New(mgr.GetConfig(), secretCacheOpts)
  54. if err != nil {
  55. return nil, err
  56. }
  57. // start an informer for secrets
  58. // this is required because we set ReaderFailOnMissingInformer to true
  59. _, err = secretCache.GetInformer(context.Background(), &corev1.Secret{})
  60. if err != nil {
  61. return nil, err
  62. }
  63. // add the secret cache to the manager, so that it starts at the same time
  64. err = mgr.Add(secretCache)
  65. if err != nil {
  66. return nil, err
  67. }
  68. // create a new client that uses the secret cache
  69. secretClient, err := client.New(mgr.GetConfig(), client.Options{
  70. HTTPClient: mgr.GetHTTPClient(),
  71. Scheme: mgr.GetScheme(),
  72. Mapper: mgr.GetRESTMapper(),
  73. Cache: &client.CacheOptions{
  74. Reader: secretCache,
  75. },
  76. })
  77. if err != nil {
  78. return nil, err
  79. }
  80. return secretClient, nil
  81. }
  82. // BuildRateLimiter creates a new rate limiter for our controllers.
  83. // NOTE: we dont use `DefaultTypedControllerRateLimiter` because it retries very aggressively, starting at 5ms!
  84. func BuildRateLimiter() workqueue.TypedRateLimiter[reconcile.Request] {
  85. // exponential backoff rate limiter
  86. // - this handles per-item rate limiting for ~failures~
  87. // - it uses an exponential backoff strategy were: delay = baseDelay * 2^failures
  88. // - graph visualization: https://www.desmos.com/calculator/fexlpdmiti
  89. failureBaseDelay := 1 * time.Second
  90. failureMaxDelay := 7 * time.Minute
  91. failureRateLimiter := workqueue.NewTypedItemExponentialFailureRateLimiter[reconcile.Request](failureBaseDelay, failureMaxDelay)
  92. // overall rate limiter
  93. // - this handles overall rate limiting, ignoring individual items and only considering the overall rate
  94. // - it implements a "token bucket" of size totalMaxBurst that is initially full,
  95. // and which is refilled at rate totalEventsPerSecond tokens per second.
  96. totalEventsPerSecond := 10
  97. totalMaxBurst := 100
  98. totalRateLimiter := &workqueue.TypedBucketRateLimiter[reconcile.Request]{
  99. Limiter: rate.NewLimiter(rate.Limit(totalEventsPerSecond), totalMaxBurst),
  100. }
  101. // return the worst-case (longest) of the rate limiters for a given item
  102. return workqueue.NewTypedMaxOfRateLimiter[reconcile.Request](failureRateLimiter, totalRateLimiter)
  103. }