sigs.k8s.io/cluster-api@v1.6.3/internal/util/ssa/cache.go (about)

     1  /*
     2  Copyright 2023 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package ssa
    18  
    19  import (
    20  	"fmt"
    21  	"time"
    22  
    23  	"github.com/pkg/errors"
    24  	"k8s.io/apimachinery/pkg/runtime"
    25  	"k8s.io/client-go/tools/cache"
    26  	"k8s.io/klog/v2"
    27  	"sigs.k8s.io/controller-runtime/pkg/client"
    28  	"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
    29  
    30  	"sigs.k8s.io/cluster-api/internal/util/hash"
    31  )
    32  
    33  const (
    34  	// ttl is the duration for which we keep the keys in the cache.
    35  	ttl = 10 * time.Minute
    36  
    37  	// expirationInterval is the interval in which we will remove expired keys
    38  	// from the cache.
    39  	expirationInterval = 10 * time.Hour
    40  )
    41  
    42  // Cache caches SSA request results.
    43  // Specifically we only use it to cache that a certain request
    44  // doesn't have to be repeated anymore because there was no diff.
    45  type Cache interface {
    46  	// Add adds the given key to the Cache.
    47  	// Note: keys expire after the ttl.
    48  	Add(key string)
    49  
    50  	// Has checks if the given key (still) exists in the Cache.
    51  	// Note: keys expire after the ttl.
    52  	Has(key string) bool
    53  }
    54  
    55  // NewCache creates a new cache.
    56  func NewCache() Cache {
    57  	r := &ssaCache{
    58  		Store: cache.NewTTLStore(func(obj interface{}) (string, error) {
    59  			// We only add strings to the cache, so it's safe to cast to string.
    60  			return obj.(string), nil
    61  		}, ttl),
    62  	}
    63  	go func() {
    64  		for {
    65  			// Call list to clear the cache of expired items.
    66  			// We have to do this periodically as the cache itself only expires
    67  			// items lazily. If we don't do this the cache grows indefinitely.
    68  			r.List()
    69  
    70  			time.Sleep(expirationInterval)
    71  		}
    72  	}()
    73  	return r
    74  }
    75  
    76  type ssaCache struct {
    77  	cache.Store
    78  }
    79  
    80  // Add adds the given key to the Cache.
    81  // Note: keys expire after the ttl.
    82  func (r *ssaCache) Add(key string) {
    83  	// Note: We can ignore the error here because by only allowing strings
    84  	// and providing the corresponding keyFunc ourselves we can guarantee that
    85  	// the error never occurs.
    86  	_ = r.Store.Add(key)
    87  }
    88  
    89  // Has checks if the given key (still) exists in the Cache.
    90  // Note: keys expire after the ttl.
    91  func (r *ssaCache) Has(key string) bool {
    92  	// Note: We can ignore the error here because GetByKey never returns an error.
    93  	_, exists, _ := r.Store.GetByKey(key)
    94  	return exists
    95  }
    96  
    97  // ComputeRequestIdentifier computes a request identifier for the cache.
    98  // The identifier is unique for a specific request to ensure we don't have to re-run the request
    99  // once we found out that it would not produce a diff.
   100  // The identifier consists of: gvk, namespace, name and resourceVersion of the original object and a hash of the modified
   101  // object. This ensures that we re-run the request as soon as either original or modified changes.
   102  func ComputeRequestIdentifier(scheme *runtime.Scheme, original, modified client.Object) (string, error) {
   103  	modifiedObjectHash, err := hash.Compute(modified)
   104  	if err != nil {
   105  		return "", errors.Wrapf(err, "failed to calculate request identifier: failed to compute hash for modified object")
   106  	}
   107  
   108  	gvk, err := apiutil.GVKForObject(original, scheme)
   109  	if err != nil {
   110  		return "", errors.Wrapf(err, "failed to calculate request identifier: failed to get GroupVersionKind of original object %s", klog.KObj(original))
   111  	}
   112  
   113  	return fmt.Sprintf("%s.%s.%s.%d", gvk.String(), klog.KObj(original), original.GetResourceVersion(), modifiedObjectHash), nil
   114  }