common.go 5.0 KB

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