common.go 5.0 KB

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