manager.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 clientmanager provides a Manager for provider clients
  14. package clientmanager
  15. import (
  16. "context"
  17. "errors"
  18. "fmt"
  19. "regexp"
  20. "strings"
  21. "sync"
  22. "github.com/go-logr/logr"
  23. v1 "k8s.io/api/core/v1"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. "k8s.io/apimachinery/pkg/labels"
  26. "k8s.io/apimachinery/pkg/types"
  27. ctrl "sigs.k8s.io/controller-runtime"
  28. "sigs.k8s.io/controller-runtime/pkg/client"
  29. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  30. "github.com/external-secrets/external-secrets/pkg/controllers/secretstore/storeutil"
  31. "github.com/external-secrets/external-secrets/providers/v2/common/grpc"
  32. )
  33. const (
  34. errGetClusterSecretStore = "could not get ClusterSecretStore %q, %w"
  35. errGetSecretStore = "could not get SecretStore %q, %w"
  36. errClusterStoreMismatch = "using cluster store %q is not allowed from namespace %q: denied by spec.condition"
  37. )
  38. var (
  39. // globalV2ConnectionPool is a singleton connection pool for v2 gRPC providers.
  40. // It persists across all reconciles and Manager instances to enable connection reuse.
  41. // Initialized once on first use and shared globally.
  42. globalV2ConnectionPool *grpc.ConnectionPool
  43. globalV2ConnectionPoolOnce sync.Once
  44. globalV2ConnectionPoolLog logr.Logger
  45. )
  46. // initGlobalV2ConnectionPool initializes the global connection pool for v2 providers.
  47. // This is called once on first use via sync.Once.
  48. func initGlobalV2ConnectionPool() {
  49. globalV2ConnectionPoolLog = ctrl.Log.WithName("v2-connection-pool")
  50. poolConfig := grpc.DefaultPoolConfig()
  51. globalV2ConnectionPool = grpc.NewConnectionPool(poolConfig)
  52. globalV2ConnectionPoolLog.Info("global v2 connection pool initialized",
  53. "maxIdleTime", poolConfig.MaxIdleTime.String(),
  54. "maxLifetime", poolConfig.MaxLifetime.String(),
  55. "healthCheckInterval", poolConfig.HealthCheckInterval.String())
  56. }
  57. // getGlobalV2ConnectionPool returns the global connection pool, initializing it if needed.
  58. func getGlobalV2ConnectionPool() *grpc.ConnectionPool {
  59. globalV2ConnectionPoolOnce.Do(initGlobalV2ConnectionPool)
  60. return globalV2ConnectionPool
  61. }
  62. // v2PooledConnection tracks connection info needed to release connections back to the pool.
  63. type v2PooledConnection struct {
  64. address string
  65. tlsConfig *grpc.TLSConfig
  66. }
  67. // Manager stores instances of provider clients
  68. // At any given time we must have no more than one instance
  69. // of a client (due to limitations in GCP / see mutexlock there)
  70. // If the controller requests another instance of a given client
  71. // we will close the old client first and then construct a new one.
  72. type Manager struct {
  73. log logr.Logger
  74. client client.Client
  75. controllerClass string
  76. enableFloodgate bool
  77. // store clients by provider type
  78. clientMap map[clientKey]*clientVal
  79. // Track v2 provider connections for release back to pool
  80. v2PooledConnections []v2PooledConnection
  81. }
  82. type clientKey struct {
  83. providerType string
  84. }
  85. type clientVal struct {
  86. client esv1.SecretsClient
  87. store esv1.GenericStore
  88. }
  89. // NewManager constructs a new manager with defaults.
  90. func NewManager(ctrlClient client.Client, controllerClass string, enableFloodgate bool) *Manager {
  91. log := ctrl.Log.WithName("clientmanager")
  92. return &Manager{
  93. log: log,
  94. client: ctrlClient,
  95. controllerClass: controllerClass,
  96. enableFloodgate: enableFloodgate,
  97. clientMap: make(map[clientKey]*clientVal),
  98. }
  99. }
  100. // GetFromStore returns a provider client from the given store.
  101. // Do not close the client returned from this func, instead close
  102. // the manager once you're done with reconciling the external secret.
  103. func (m *Manager) GetFromStore(ctx context.Context, store esv1.GenericStore, namespace string) (esv1.SecretsClient, error) {
  104. storeProvider, err := esv1.GetProvider(store)
  105. if err != nil {
  106. return nil, err
  107. }
  108. secretClient := m.getStoredClient(ctx, storeProvider, store)
  109. if secretClient != nil {
  110. return secretClient, nil
  111. }
  112. m.log.V(1).Info("creating new client",
  113. "provider", fmt.Sprintf("%T", storeProvider),
  114. "store", fmt.Sprintf("%s/%s", store.GetNamespace(), store.GetName()))
  115. // secret client is created only if we are going to refresh
  116. // this skip an unnecessary check/request in the case we are not going to do anything
  117. secretClient, err = storeProvider.NewClient(ctx, store, m.client, namespace)
  118. if err != nil {
  119. return nil, err
  120. }
  121. idx := storeKey(storeProvider)
  122. m.clientMap[idx] = &clientVal{
  123. client: secretClient,
  124. store: store,
  125. }
  126. return secretClient, nil
  127. }
  128. // Get returns a provider client from the given storeRef or sourceRef.secretStoreRef
  129. // while sourceRef.SecretStoreRef takes precedence over storeRef.
  130. // Do not close the client returned from this func, instead close
  131. // the manager once you're done with recinciling the external secret.
  132. func (m *Manager) Get(ctx context.Context, storeRef esv1.SecretStoreRef, namespace string, sourceRef *esv1.StoreGeneratorSourceRef) (esv1.SecretsClient, error) {
  133. if sourceRef != nil && sourceRef.SecretStoreRef != nil {
  134. storeRef = *sourceRef.SecretStoreRef
  135. }
  136. store, err := m.getStore(ctx, &storeRef, namespace)
  137. if err != nil {
  138. return nil, err
  139. }
  140. // check if store should be handled by this controller instance
  141. if !storeutil.ShouldProcessStore(store, m.controllerClass) {
  142. return nil, errors.New("can not reference unmanaged store")
  143. }
  144. // when using ClusterSecretStore, validate the ClusterSecretStore namespace conditions
  145. shouldProcess, err := m.shouldProcessSecret(store, namespace)
  146. if err != nil {
  147. return nil, err
  148. }
  149. if !shouldProcess {
  150. return nil, fmt.Errorf(errClusterStoreMismatch, store.GetName(), namespace)
  151. }
  152. if m.enableFloodgate {
  153. err := storeutil.AssertStoreIsUsable(store)
  154. if err != nil {
  155. return nil, err
  156. }
  157. }
  158. return m.GetFromStore(ctx, store, namespace)
  159. }
  160. // returns a previously stored client from the cache if store and store-version match
  161. // if a client exists for the same provider which points to a different store or store version
  162. // it will be cleaned up.
  163. func (m *Manager) getStoredClient(ctx context.Context, storeProvider esv1.ProviderInterface, store esv1.GenericStore) esv1.SecretsClient {
  164. idx := storeKey(storeProvider)
  165. val, ok := m.clientMap[idx]
  166. if !ok {
  167. return nil
  168. }
  169. valGVK, err := m.client.GroupVersionKindFor(val.store)
  170. if err != nil {
  171. return nil
  172. }
  173. storeGVK, err := m.client.GroupVersionKindFor(store)
  174. if err != nil {
  175. return nil
  176. }
  177. storeName := fmt.Sprintf("%s/%s", store.GetNamespace(), store.GetName())
  178. // return client if it points to the very same store
  179. if val.store.GetObjectMeta().Generation == store.GetGeneration() &&
  180. valGVK == storeGVK &&
  181. val.store.GetName() == store.GetName() &&
  182. val.store.GetNamespace() == store.GetNamespace() {
  183. m.log.V(1).Info("reusing stored client",
  184. "provider", fmt.Sprintf("%T", storeProvider),
  185. "store", storeName)
  186. return val.client
  187. }
  188. m.log.V(1).Info("cleaning up client",
  189. "provider", fmt.Sprintf("%T", storeProvider),
  190. "store", storeName)
  191. // if we have a client, but it points to a different store
  192. // we must clean it up
  193. _ = val.client.Close(ctx)
  194. delete(m.clientMap, idx)
  195. return nil
  196. }
  197. func storeKey(storeProvider esv1.ProviderInterface) clientKey {
  198. return clientKey{
  199. providerType: fmt.Sprintf("%T", storeProvider),
  200. }
  201. }
  202. // getStore fetches the (Cluster)SecretStore from the kube-apiserver
  203. // and returns a GenericStore representing it.
  204. func (m *Manager) getStore(ctx context.Context, storeRef *esv1.SecretStoreRef, namespace string) (esv1.GenericStore, error) {
  205. ref := types.NamespacedName{
  206. Name: storeRef.Name,
  207. }
  208. if storeRef.Kind == esv1.ClusterSecretStoreKind {
  209. var store esv1.ClusterSecretStore
  210. err := m.client.Get(ctx, ref, &store)
  211. if err != nil {
  212. return nil, fmt.Errorf(errGetClusterSecretStore, ref.Name, err)
  213. }
  214. return &store, nil
  215. }
  216. ref.Namespace = namespace
  217. var store esv1.SecretStore
  218. err := m.client.Get(ctx, ref, &store)
  219. if err != nil {
  220. return nil, fmt.Errorf(errGetSecretStore, ref.Name, err)
  221. }
  222. return &store, nil
  223. }
  224. // Close cleans up all clients.
  225. // For v1 providers, it closes the clients directly.
  226. // For v2 providers, it releases connections back to the pool for reuse.
  227. func (m *Manager) Close(ctx context.Context) error {
  228. var errs []string
  229. // Release v2 pooled connections back to the pool
  230. pool := getGlobalV2ConnectionPool()
  231. for _, pooledConn := range m.v2PooledConnections {
  232. pool.Release(pooledConn.address, pooledConn.tlsConfig)
  233. m.log.V(1).Info("released v2 connection back to pool",
  234. "address", pooledConn.address)
  235. }
  236. m.v2PooledConnections = nil
  237. // Close v1 provider clients (they don't use the pool)
  238. for key, val := range m.clientMap {
  239. // Only close v1 clients; v2 clients are managed by the pool
  240. if key.providerType != "v2-provider" && key.providerType != "v2-cluster-provider" {
  241. err := val.client.Close(ctx)
  242. if err != nil {
  243. errs = append(errs, err.Error())
  244. }
  245. }
  246. delete(m.clientMap, key)
  247. }
  248. if len(errs) != 0 {
  249. return fmt.Errorf("errors while closing clients: %s", strings.Join(errs, ", "))
  250. }
  251. return nil
  252. }
  253. func (m *Manager) shouldProcessSecret(store esv1.GenericStore, ns string) (bool, error) {
  254. if store.GetKind() != esv1.ClusterSecretStoreKind {
  255. return true, nil
  256. }
  257. if len(store.GetSpec().Conditions) == 0 {
  258. return true, nil
  259. }
  260. namespace := v1.Namespace{}
  261. if err := m.client.Get(context.Background(), client.ObjectKey{Name: ns}, &namespace); err != nil {
  262. return false, fmt.Errorf("failed to get a namespace %q: %w", ns, err)
  263. }
  264. nsLabels := labels.Set(namespace.GetLabels())
  265. for _, condition := range store.GetSpec().Conditions {
  266. var labelSelectors []*metav1.LabelSelector
  267. if condition.NamespaceSelector != nil {
  268. labelSelectors = append(labelSelectors, condition.NamespaceSelector)
  269. }
  270. for _, n := range condition.Namespaces {
  271. labelSelectors = append(labelSelectors, &metav1.LabelSelector{
  272. MatchLabels: map[string]string{
  273. "kubernetes.io/metadata.name": n,
  274. },
  275. })
  276. }
  277. for _, ls := range labelSelectors {
  278. selector, err := metav1.LabelSelectorAsSelector(ls)
  279. if err != nil {
  280. return false, fmt.Errorf("failed to convert label selector into selector %v: %w", ls, err)
  281. }
  282. if selector.Matches(nsLabels) {
  283. return true, nil
  284. }
  285. }
  286. for _, reg := range condition.NamespaceRegexes {
  287. match, err := regexp.MatchString(reg, ns)
  288. if err != nil {
  289. // Should not happen since store validation already verified the regexes.
  290. return false, fmt.Errorf("failed to compile regex %v: %w", reg, err)
  291. }
  292. if match {
  293. return true, nil
  294. }
  295. }
  296. }
  297. return false, nil
  298. }