common.go 4.4 KB

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