common.go 4.3 KB

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