manager.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. /*
  2. Copyright © 2025 ESO Maintainer Team
  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. pb "github.com/external-secrets/external-secrets/proto/provider"
  31. adapterstore "github.com/external-secrets/external-secrets/providers/v2/adapter/store"
  32. "github.com/external-secrets/external-secrets/providers/v2/common/grpc"
  33. )
  34. const (
  35. errGetClusterSecretStore = "could not get ClusterSecretStore %q, %w"
  36. errGetSecretStore = "could not get SecretStore %q, %w"
  37. errSecretStoreNotReady = "%s %q is not ready"
  38. errClusterStoreMismatch = "using cluster store %q is not allowed from namespace %q: denied by spec.condition"
  39. errClusterProviderDenied = "using ClusterProvider %q is not allowed from namespace %q: denied by spec.conditions"
  40. )
  41. var (
  42. // globalV2ConnectionPool is a singleton connection pool for v2 gRPC providers.
  43. // It persists across all reconciles and Manager instances to enable connection reuse.
  44. // Initialized once on first use and shared globally.
  45. globalV2ConnectionPool *grpc.ConnectionPool
  46. globalV2ConnectionPoolOnce sync.Once
  47. globalV2ConnectionPoolLog logr.Logger
  48. )
  49. // initGlobalV2ConnectionPool initializes the global connection pool for v2 providers.
  50. // This is called once on first use via sync.Once.
  51. func initGlobalV2ConnectionPool() {
  52. globalV2ConnectionPoolLog = ctrl.Log.WithName("v2-connection-pool")
  53. poolConfig := grpc.DefaultPoolConfig()
  54. globalV2ConnectionPool = grpc.NewConnectionPool(poolConfig)
  55. globalV2ConnectionPoolLog.Info("global v2 connection pool initialized",
  56. "maxIdleTime", poolConfig.MaxIdleTime.String(),
  57. "maxLifetime", poolConfig.MaxLifetime.String(),
  58. "healthCheckInterval", poolConfig.HealthCheckInterval.String())
  59. }
  60. // getGlobalV2ConnectionPool returns the global connection pool, initializing it if needed.
  61. func getGlobalV2ConnectionPool() *grpc.ConnectionPool {
  62. globalV2ConnectionPoolOnce.Do(initGlobalV2ConnectionPool)
  63. return globalV2ConnectionPool
  64. }
  65. // v2PooledConnection tracks connection info needed to release connections back to the pool.
  66. type v2PooledConnection struct {
  67. address string
  68. tlsConfig *grpc.TLSConfig
  69. }
  70. // Manager stores instances of provider clients
  71. // At any given time we must have no more than one instance
  72. // of a client (due to limitations in GCP / see mutexlock there)
  73. // If the controller requests another instance of a given client
  74. // we will close the old client first and then construct a new one.
  75. type Manager struct {
  76. log logr.Logger
  77. client client.Client
  78. controllerClass string
  79. enableFloodgate bool
  80. // store clients by provider type
  81. clientMap map[clientKey]*clientVal
  82. // Track v2 provider connections for release back to pool
  83. v2PooledConnections []v2PooledConnection
  84. }
  85. type clientKey struct {
  86. providerType string
  87. // For v2 providers, store the provider name and namespace
  88. v2ProviderName string
  89. v2ProviderNamespace string
  90. }
  91. type clientVal struct {
  92. client esv1.SecretsClient
  93. store esv1.GenericStore
  94. // For v2 providers, store the generation for cache invalidation
  95. v2ProviderGeneration int64
  96. }
  97. // v2ProviderConfig contains configuration for creating a v2 provider client.
  98. type v2ProviderConfig struct {
  99. name string
  100. resourceNamespace string // empty for cluster-scoped resources
  101. manifestNamespace string // namespace of the ExternalSecret/PushSecret
  102. config esv1.ProviderConfig
  103. generation int64
  104. isClusterScoped bool
  105. kindStr string // "Provider" or "ClusterProvider"
  106. }
  107. // NewManager constructs a new manager with defaults.
  108. func NewManager(ctrlClient client.Client, controllerClass string, enableFloodgate bool) *Manager {
  109. log := ctrl.Log.WithName("clientmanager")
  110. return &Manager{
  111. log: log,
  112. client: ctrlClient,
  113. controllerClass: controllerClass,
  114. enableFloodgate: enableFloodgate,
  115. clientMap: make(map[clientKey]*clientVal),
  116. }
  117. }
  118. // GetFromStore returns a provider client from the given store.
  119. // Do not close the client returned from this func, instead close
  120. // the manager once you're done with reconciling the external secret.
  121. func (m *Manager) GetFromStore(ctx context.Context, store esv1.GenericStore, namespace string) (esv1.SecretsClient, error) {
  122. storeProvider, err := esv1.GetProvider(store)
  123. if err != nil {
  124. return nil, err
  125. }
  126. secretClient := m.getStoredClient(ctx, storeProvider, store)
  127. if secretClient != nil {
  128. return secretClient, nil
  129. }
  130. m.log.V(1).Info("creating new client",
  131. "provider", fmt.Sprintf("%T", storeProvider),
  132. "store", fmt.Sprintf("%s/%s", store.GetNamespace(), store.GetName()))
  133. // secret client is created only if we are going to refresh
  134. // this skip an unnecessary check/request in the case we are not going to do anything
  135. secretClient, err = storeProvider.NewClient(ctx, store, m.client, namespace)
  136. if err != nil {
  137. return nil, err
  138. }
  139. idx := storeKey(storeProvider)
  140. m.clientMap[idx] = &clientVal{
  141. client: secretClient,
  142. store: store,
  143. }
  144. return secretClient, nil
  145. }
  146. // Get returns a provider client from the given storeRef or sourceRef.secretStoreRef
  147. // while sourceRef.SecretStoreRef takes precedence over storeRef.
  148. // Do not close the client returned from this func, instead close
  149. // the manager once you're done with recinciling the external secret.
  150. func (m *Manager) Get(ctx context.Context, storeRef esv1.SecretStoreRef, namespace string, sourceRef *esv1.StoreGeneratorSourceRef) (esv1.SecretsClient, error) {
  151. if storeRef.Kind == esv1.ProviderKindStr {
  152. return m.getV2ProviderClient(ctx, storeRef.Name, namespace)
  153. }
  154. if storeRef.Kind == esv1.ClusterProviderKindStr {
  155. return m.getV2ClusterProviderClient(ctx, storeRef.Name, namespace)
  156. }
  157. if sourceRef != nil && sourceRef.SecretStoreRef != nil {
  158. storeRef = *sourceRef.SecretStoreRef
  159. }
  160. store, err := m.getStore(ctx, &storeRef, namespace)
  161. if err != nil {
  162. return nil, err
  163. }
  164. // check if store should be handled by this controller instance
  165. if !ShouldProcessStore(store, m.controllerClass) {
  166. return nil, errors.New("can not reference unmanaged store")
  167. }
  168. // when using ClusterSecretStore, validate the ClusterSecretStore namespace conditions
  169. shouldProcess, err := m.shouldProcessSecret(store, namespace)
  170. if err != nil {
  171. return nil, err
  172. }
  173. if !shouldProcess {
  174. return nil, fmt.Errorf(errClusterStoreMismatch, store.GetName(), namespace)
  175. }
  176. if m.enableFloodgate {
  177. err := assertStoreIsUsable(store)
  178. if err != nil {
  179. return nil, err
  180. }
  181. }
  182. return m.GetFromStore(ctx, store, namespace)
  183. }
  184. // getOrCreateV2Client is a shared helper for creating or retrieving v2 provider clients.
  185. // It handles caching, connection pooling, and client lifecycle for both Provider and ClusterProvider.
  186. func (m *Manager) getOrCreateV2Client(ctx context.Context, cfg v2ProviderConfig, authNamespace string) (esv1.SecretsClient, error) {
  187. // Determine cache key type based on resource type
  188. cacheKeyType := "v2-provider"
  189. if cfg.isClusterScoped {
  190. cacheKeyType = "v2-cluster-provider"
  191. }
  192. // Create cache key
  193. cacheKey := clientKey{
  194. providerType: cacheKeyType,
  195. v2ProviderName: cfg.name,
  196. v2ProviderNamespace: cfg.manifestNamespace,
  197. }
  198. // Check if we have a cached client
  199. if cached, ok := m.clientMap[cacheKey]; ok {
  200. if cached.v2ProviderGeneration == cfg.generation {
  201. m.log.V(1).Info("reusing cached v2 provider client",
  202. cfg.kindStr, cfg.name,
  203. "manifestNamespace", cfg.manifestNamespace,
  204. "authNamespace", authNamespace,
  205. "generation", cfg.generation)
  206. // Record cache hit
  207. providerType := "provider"
  208. if cfg.isClusterScoped {
  209. providerType = "cluster-provider"
  210. }
  211. clientManagerMetrics.RecordCacheHit(providerType)
  212. return cached.client, nil
  213. }
  214. // Cache is stale, invalidate
  215. m.log.V(1).Info("provider generation changed, invalidating cache",
  216. cfg.kindStr, cfg.name,
  217. "manifestNamespace", cfg.manifestNamespace,
  218. "oldGeneration", cached.v2ProviderGeneration,
  219. "newGeneration", cfg.generation)
  220. // Record cache invalidation
  221. providerType := "provider"
  222. if cfg.isClusterScoped {
  223. providerType = "cluster-provider"
  224. }
  225. clientManagerMetrics.RecordCacheInvalidation(providerType, "generation_change")
  226. delete(m.clientMap, cacheKey)
  227. }
  228. m.log.V(1).Info("getting v2 provider client from pool",
  229. cfg.kindStr, cfg.name,
  230. "manifestNamespace", cfg.manifestNamespace,
  231. "authNamespace", authNamespace,
  232. "address", cfg.config.Address)
  233. // Get provider address
  234. address := cfg.config.Address
  235. if address == "" {
  236. return nil, fmt.Errorf("provider address is required in %s %q", cfg.kindStr, cfg.name)
  237. }
  238. // Load TLS configuration
  239. tlsConfig, err := grpc.LoadClientTLSConfig(ctx, m.client, cfg.config.Address, "external-secrets-system")
  240. if err != nil {
  241. return nil, fmt.Errorf("failed to load TLS config for %s %q: %w", cfg.kindStr, cfg.name, err)
  242. }
  243. // Get connection from global pool
  244. pool := getGlobalV2ConnectionPool()
  245. grpcClient, err := pool.Get(ctx, address, tlsConfig)
  246. if err != nil {
  247. return nil, fmt.Errorf("failed to get gRPC client from pool for %s %q: %w", cfg.kindStr, cfg.name, err)
  248. }
  249. // Track this connection for release when Manager closes
  250. m.v2PooledConnections = append(m.v2PooledConnections, v2PooledConnection{
  251. address: address,
  252. tlsConfig: tlsConfig,
  253. })
  254. // Convert ProviderReference to protobuf format
  255. providerRef := &pb.ProviderReference{
  256. ApiVersion: cfg.config.ProviderRef.APIVersion,
  257. Kind: cfg.config.ProviderRef.Kind,
  258. Name: cfg.config.ProviderRef.Name,
  259. Namespace: cfg.config.ProviderRef.Namespace,
  260. }
  261. // Wrap with V2ClientWrapper
  262. wrappedClient := adapterstore.NewClient(grpcClient, providerRef, authNamespace)
  263. // Cache the client for this Manager instance
  264. m.clientMap[cacheKey] = &clientVal{
  265. client: wrappedClient,
  266. store: nil, // v2 providers don't use GenericStore
  267. v2ProviderGeneration: cfg.generation,
  268. }
  269. m.log.Info("v2 provider client obtained from pool",
  270. cfg.kindStr, cfg.name,
  271. "manifestNamespace", cfg.manifestNamespace,
  272. "authNamespace", authNamespace,
  273. "address", address)
  274. return wrappedClient, nil
  275. }
  276. // getV2ProviderClient creates or retrieves a cached gRPC client for a v2 Provider.
  277. // It uses the global connection pool to enable connection reuse across reconciles.
  278. func (m *Manager) getV2ProviderClient(ctx context.Context, providerName, namespace string) (esv1.SecretsClient, error) {
  279. // Fetch the Provider resource
  280. var provider esv1.Provider
  281. providerKey := types.NamespacedName{
  282. Name: providerName,
  283. Namespace: namespace,
  284. }
  285. if err := m.client.Get(ctx, providerKey, &provider); err != nil {
  286. return nil, fmt.Errorf("failed to get Provider %q: %w", providerName, err)
  287. }
  288. // Build configuration for the helper
  289. cfg := v2ProviderConfig{
  290. name: providerName,
  291. resourceNamespace: namespace,
  292. manifestNamespace: namespace,
  293. config: provider.Spec.Config,
  294. generation: provider.Generation,
  295. isClusterScoped: false,
  296. kindStr: esv1.ProviderKindStr,
  297. }
  298. // For namespace-scoped Provider, auth namespace is always the manifest namespace
  299. return m.getOrCreateV2Client(ctx, cfg, namespace)
  300. }
  301. // getV2ClusterProviderClient creates or retrieves a cached gRPC client for a v2 ClusterProvider.
  302. // It uses the global connection pool to enable connection reuse across reconciles.
  303. func (m *Manager) getV2ClusterProviderClient(ctx context.Context, providerName, namespace string) (esv1.SecretsClient, error) {
  304. // Fetch the ClusterProvider resource (cluster-scoped)
  305. var clusterProvider esv1.ClusterProvider
  306. providerKey := types.NamespacedName{
  307. Name: providerName,
  308. }
  309. if err := m.client.Get(ctx, providerKey, &clusterProvider); err != nil {
  310. return nil, fmt.Errorf("failed to get ClusterProvider %q: %w", providerName, err)
  311. }
  312. // Validate namespace conditions
  313. shouldProcess, err := m.validateNamespaceConditions(clusterProvider.Spec.Conditions, namespace)
  314. if err != nil {
  315. return nil, err
  316. }
  317. if !shouldProcess {
  318. return nil, fmt.Errorf(errClusterProviderDenied, providerName, namespace)
  319. }
  320. // Determine authentication namespace based on authenticationScope
  321. authNamespace := namespace // default to ManifestNamespace
  322. if clusterProvider.Spec.AuthenticationScope == esv1.AuthenticationScopeProviderNamespace {
  323. // Use namespace from providerRef
  324. if clusterProvider.Spec.Config.ProviderRef.Namespace != "" {
  325. authNamespace = clusterProvider.Spec.Config.ProviderRef.Namespace
  326. } else {
  327. return nil, fmt.Errorf("ClusterProvider %q has authenticationScope=ProviderNamespace but spec.config.providerRef.namespace is empty", providerName)
  328. }
  329. }
  330. // Build configuration for the helper
  331. cfg := v2ProviderConfig{
  332. name: providerName,
  333. resourceNamespace: "", // cluster-scoped
  334. manifestNamespace: namespace,
  335. config: clusterProvider.Spec.Config,
  336. generation: clusterProvider.Generation,
  337. isClusterScoped: true,
  338. kindStr: esv1.ClusterProviderKindStr,
  339. }
  340. return m.getOrCreateV2Client(ctx, cfg, authNamespace)
  341. }
  342. // returns a previously stored client from the cache if store and store-version match
  343. // if a client exists for the same provider which points to a different store or store version
  344. // it will be cleaned up.
  345. func (m *Manager) getStoredClient(ctx context.Context, storeProvider esv1.ProviderInterface, store esv1.GenericStore) esv1.SecretsClient {
  346. idx := storeKey(storeProvider)
  347. val, ok := m.clientMap[idx]
  348. if !ok {
  349. return nil
  350. }
  351. valGVK, err := m.client.GroupVersionKindFor(val.store)
  352. if err != nil {
  353. return nil
  354. }
  355. storeGVK, err := m.client.GroupVersionKindFor(store)
  356. if err != nil {
  357. return nil
  358. }
  359. storeName := fmt.Sprintf("%s/%s", store.GetNamespace(), store.GetName())
  360. // return client if it points to the very same store
  361. if val.store.GetObjectMeta().Generation == store.GetGeneration() &&
  362. valGVK == storeGVK &&
  363. val.store.GetName() == store.GetName() &&
  364. val.store.GetNamespace() == store.GetNamespace() {
  365. m.log.V(1).Info("reusing stored client",
  366. "provider", fmt.Sprintf("%T", storeProvider),
  367. "store", storeName)
  368. // Record cache hit
  369. providerType := "unknown"
  370. if idx.v2ProviderName != "" {
  371. if idx.v2ProviderNamespace == "" {
  372. providerType = "cluster-provider"
  373. } else {
  374. providerType = "provider"
  375. }
  376. }
  377. clientManagerMetrics.RecordCacheHit(providerType)
  378. return val.client
  379. }
  380. m.log.V(1).Info("cleaning up client",
  381. "provider", fmt.Sprintf("%T", storeProvider),
  382. "store", storeName)
  383. // if we have a client, but it points to a different store
  384. // we must clean it up
  385. _ = val.client.Close(ctx)
  386. delete(m.clientMap, idx)
  387. // Record cache invalidation
  388. providerType := "unknown"
  389. reason := "store_mismatch"
  390. if idx.v2ProviderName != "" {
  391. if idx.v2ProviderNamespace == "" {
  392. providerType = "cluster-provider"
  393. } else {
  394. providerType = "provider"
  395. }
  396. if val.store.GetObjectMeta().Generation != store.GetGeneration() {
  397. reason = "generation_change"
  398. }
  399. }
  400. clientManagerMetrics.RecordCacheInvalidation(providerType, reason)
  401. return nil
  402. }
  403. func storeKey(storeProvider esv1.ProviderInterface) clientKey {
  404. return clientKey{
  405. providerType: fmt.Sprintf("%T", storeProvider),
  406. }
  407. }
  408. // getStore fetches the (Cluster)SecretStore from the kube-apiserver
  409. // and returns a GenericStore representing it.
  410. func (m *Manager) getStore(ctx context.Context, storeRef *esv1.SecretStoreRef, namespace string) (esv1.GenericStore, error) {
  411. ref := types.NamespacedName{
  412. Name: storeRef.Name,
  413. }
  414. if storeRef.Kind == esv1.ClusterSecretStoreKind {
  415. var store esv1.ClusterSecretStore
  416. err := m.client.Get(ctx, ref, &store)
  417. if err != nil {
  418. return nil, fmt.Errorf(errGetClusterSecretStore, ref.Name, err)
  419. }
  420. return &store, nil
  421. }
  422. ref.Namespace = namespace
  423. var store esv1.SecretStore
  424. err := m.client.Get(ctx, ref, &store)
  425. if err != nil {
  426. return nil, fmt.Errorf(errGetSecretStore, ref.Name, err)
  427. }
  428. return &store, nil
  429. }
  430. // Close cleans up all clients.
  431. // For v1 providers, it closes the clients directly.
  432. // For v2 providers, it releases connections back to the pool for reuse.
  433. func (m *Manager) Close(ctx context.Context) error {
  434. var errs []string
  435. // Release v2 pooled connections back to the pool
  436. pool := getGlobalV2ConnectionPool()
  437. for _, pooledConn := range m.v2PooledConnections {
  438. pool.Release(pooledConn.address, pooledConn.tlsConfig)
  439. m.log.V(1).Info("released v2 connection back to pool",
  440. "address", pooledConn.address)
  441. }
  442. m.v2PooledConnections = nil
  443. // Close v1 provider clients (they don't use the pool)
  444. for key, val := range m.clientMap {
  445. // Only close v1 clients; v2 clients are managed by the pool
  446. if key.providerType != "v2-provider" {
  447. err := val.client.Close(ctx)
  448. if err != nil {
  449. errs = append(errs, err.Error())
  450. }
  451. }
  452. delete(m.clientMap, key)
  453. }
  454. if len(errs) != 0 {
  455. return fmt.Errorf("errors while closing clients: %s", strings.Join(errs, ", "))
  456. }
  457. return nil
  458. }
  459. // validateNamespaceConditions checks if a namespace matches the given conditions.
  460. // Returns true if the namespace is allowed, false if denied.
  461. func (m *Manager) validateNamespaceConditions(conditions []esv1.ClusterSecretStoreCondition, ns string) (bool, error) {
  462. if len(conditions) == 0 {
  463. return true, nil
  464. }
  465. namespace := v1.Namespace{}
  466. if err := m.client.Get(context.Background(), client.ObjectKey{Name: ns}, &namespace); err != nil {
  467. return false, fmt.Errorf("failed to get a namespace %q: %w", ns, err)
  468. }
  469. nsLabels := labels.Set(namespace.GetLabels())
  470. for _, condition := range conditions {
  471. var labelSelectors []*metav1.LabelSelector
  472. if condition.NamespaceSelector != nil {
  473. labelSelectors = append(labelSelectors, condition.NamespaceSelector)
  474. }
  475. for _, n := range condition.Namespaces {
  476. labelSelectors = append(labelSelectors, &metav1.LabelSelector{
  477. MatchLabels: map[string]string{
  478. "kubernetes.io/metadata.name": n,
  479. },
  480. })
  481. }
  482. for _, ls := range labelSelectors {
  483. selector, err := metav1.LabelSelectorAsSelector(ls)
  484. if err != nil {
  485. return false, fmt.Errorf("failed to convert label selector into selector %v: %w", ls, err)
  486. }
  487. if selector.Matches(nsLabels) {
  488. return true, nil
  489. }
  490. }
  491. for _, reg := range condition.NamespaceRegexes {
  492. match, err := regexp.MatchString(reg, ns)
  493. if err != nil {
  494. // Should not happen since store validation already verified the regexes.
  495. return false, fmt.Errorf("failed to compile regex %v: %w", reg, err)
  496. }
  497. if match {
  498. return true, nil
  499. }
  500. }
  501. }
  502. return false, nil
  503. }
  504. // shouldProcessSecret validates if a secret should be processed based on namespace conditions.
  505. // This is a wrapper around validateNamespaceConditions for backward compatibility with GenericStore.
  506. func (m *Manager) shouldProcessSecret(store esv1.GenericStore, ns string) (bool, error) {
  507. // Only check conditions for cluster-scoped resources (ClusterSecretStore and ClusterProvider)
  508. if store.GetKind() != esv1.ClusterSecretStoreKind && store.GetKind() != esv1.ClusterProviderKind {
  509. return true, nil
  510. }
  511. return m.validateNamespaceConditions(store.GetSpec().Conditions, ns)
  512. }
  513. // assertStoreIsUsable asserts that the store is ready to use.
  514. func assertStoreIsUsable(store esv1.GenericStore) error {
  515. if store == nil {
  516. return nil
  517. }
  518. condition := GetSecretStoreCondition(store.GetStatus(), esv1.SecretStoreReady)
  519. if condition == nil || condition.Status != v1.ConditionTrue {
  520. return fmt.Errorf(errSecretStoreNotReady, store.GetKind(), store.GetName())
  521. }
  522. return nil
  523. }
  524. // ShouldProcessStore returns true if the store should be processed.
  525. func ShouldProcessStore(store esv1.GenericStore, class string) bool {
  526. if store == nil || store.GetSpec().Controller == "" || store.GetSpec().Controller == class {
  527. return true
  528. }
  529. return false
  530. }
  531. // GetSecretStoreCondition returns the condition with the provided type.
  532. func GetSecretStoreCondition(status esv1.SecretStoreStatus, condType esv1.SecretStoreConditionType) *esv1.SecretStoreStatusCondition {
  533. for i := range status.Conditions {
  534. c := status.Conditions[i]
  535. if c.Type == condType {
  536. return &c
  537. }
  538. }
  539. return nil
  540. }