|
| 1 | +/* |
| 2 | +Copyright 2024 The Tekton 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 cache |
| 18 | + |
| 19 | +import ( |
| 20 | + "crypto/sha256" |
| 21 | + "encoding/hex" |
| 22 | + "sort" |
| 23 | + "strconv" |
| 24 | + "time" |
| 25 | + |
| 26 | + "context" |
| 27 | + |
| 28 | + v1 "github.com/tektoncd/pipeline/pkg/apis/pipeline/v1" |
| 29 | + "go.uber.org/zap" |
| 30 | + corev1 "k8s.io/api/core/v1" |
| 31 | + utilcache "k8s.io/apimachinery/pkg/util/cache" |
| 32 | + "knative.dev/pkg/logging" |
| 33 | +) |
| 34 | + |
| 35 | +const ( |
| 36 | + // DefaultMaxSize is the default size for the cache |
| 37 | + DefaultMaxSize = 1000 |
| 38 | + |
| 39 | + // ConfigMapName is the name of the ConfigMap containing cache configuration |
| 40 | + ConfigMapName = "resolver-cache-config" |
| 41 | + |
| 42 | + // ConfigMapNamespace is the namespace of the ConfigMap |
| 43 | + ConfigMapNamespace = "tekton-pipelines-resolvers" |
| 44 | +) |
| 45 | + |
| 46 | +var ( |
| 47 | + // DefaultExpiration is the default expiration time for cache entries |
| 48 | + DefaultExpiration = 5 * time.Minute |
| 49 | +) |
| 50 | + |
| 51 | +// ResolverCache is a wrapper around utilcache.LRUExpireCache that provides |
| 52 | +// type-safe methods for caching resolver results. |
| 53 | +type ResolverCache struct { |
| 54 | + cache *utilcache.LRUExpireCache |
| 55 | + logger *zap.SugaredLogger |
| 56 | +} |
| 57 | + |
| 58 | +// NewResolverCache creates a new ResolverCache with the given expiration time and max size |
| 59 | +func NewResolverCache(maxSize int) *ResolverCache { |
| 60 | + return &ResolverCache{ |
| 61 | + cache: utilcache.NewLRUExpireCache(maxSize), |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +// InitializeFromConfigMap initializes the cache with configuration from a ConfigMap |
| 66 | +func (c *ResolverCache) InitializeFromConfigMap(configMap *corev1.ConfigMap) { |
| 67 | + // Set defaults |
| 68 | + maxSize := DefaultMaxSize |
| 69 | + ttl := DefaultExpiration |
| 70 | + |
| 71 | + if configMap != nil { |
| 72 | + // Parse max size |
| 73 | + if maxSizeStr, ok := configMap.Data["max-size"]; ok { |
| 74 | + if parsed, err := strconv.Atoi(maxSizeStr); err == nil && parsed > 0 { |
| 75 | + maxSize = parsed |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + // Parse default TTL |
| 80 | + if ttlStr, ok := configMap.Data["default-ttl"]; ok { |
| 81 | + if parsed, err := time.ParseDuration(ttlStr); err == nil && parsed > 0 { |
| 82 | + ttl = parsed |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + c.cache = utilcache.NewLRUExpireCache(maxSize) |
| 88 | + DefaultExpiration = ttl |
| 89 | +} |
| 90 | + |
| 91 | +// InitializeLogger initializes the logger for the cache using the provided context |
| 92 | +func (c *ResolverCache) InitializeLogger(ctx context.Context) { |
| 93 | + if c.logger == nil { |
| 94 | + c.logger = logging.FromContext(ctx) |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +// Get retrieves a value from the cache. |
| 99 | +func (c *ResolverCache) Get(key string) (interface{}, bool) { |
| 100 | + value, found := c.cache.Get(key) |
| 101 | + if c.logger != nil { |
| 102 | + if found { |
| 103 | + c.logger.Infow("Cache hit", "key", key) |
| 104 | + } else { |
| 105 | + c.logger.Infow("Cache miss", "key", key) |
| 106 | + } |
| 107 | + } |
| 108 | + return value, found |
| 109 | +} |
| 110 | + |
| 111 | +// Add adds a value to the cache with the default expiration time. |
| 112 | +func (c *ResolverCache) Add(key string, value interface{}) { |
| 113 | + if c.logger != nil { |
| 114 | + c.logger.Infow("Adding to cache", "key", key, "expiration", DefaultExpiration) |
| 115 | + } |
| 116 | + c.cache.Add(key, value, DefaultExpiration) |
| 117 | +} |
| 118 | + |
| 119 | +// Remove removes a value from the cache. |
| 120 | +func (c *ResolverCache) Remove(key string) { |
| 121 | + if c.logger != nil { |
| 122 | + c.logger.Infow("Removing from cache", "key", key) |
| 123 | + } |
| 124 | + c.cache.Remove(key) |
| 125 | +} |
| 126 | + |
| 127 | +// AddWithExpiration adds a value to the cache with a custom expiration time |
| 128 | +func (c *ResolverCache) AddWithExpiration(key string, value interface{}, expiration time.Duration) { |
| 129 | + if c.logger != nil { |
| 130 | + c.logger.Infow("Adding to cache with custom expiration", "key", key, "expiration", expiration) |
| 131 | + } |
| 132 | + c.cache.Add(key, value, expiration) |
| 133 | +} |
| 134 | + |
| 135 | +// globalCache is the global instance of ResolverCache |
| 136 | +var globalCache = NewResolverCache(DefaultMaxSize) |
| 137 | + |
| 138 | +// GetGlobalCache returns the global cache instance. |
| 139 | +func GetGlobalCache() *ResolverCache { |
| 140 | + return globalCache |
| 141 | +} |
| 142 | + |
| 143 | +// GenerateCacheKey generates a cache key for the given resolver type and parameters. |
| 144 | +func GenerateCacheKey(resolverType string, params []v1.Param) (string, error) { |
| 145 | + // Create a deterministic string representation of the parameters |
| 146 | + paramStr := resolverType + ":" |
| 147 | + |
| 148 | + // Filter out the 'cache' parameter and sort remaining params by name for determinism |
| 149 | + filteredParams := make([]v1.Param, 0, len(params)) |
| 150 | + for _, p := range params { |
| 151 | + if p.Name != "cache" { |
| 152 | + filteredParams = append(filteredParams, p) |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + // Sort params by name to ensure deterministic ordering |
| 157 | + sort.Slice(filteredParams, func(i, j int) bool { |
| 158 | + return filteredParams[i].Name < filteredParams[j].Name |
| 159 | + }) |
| 160 | + |
| 161 | + for _, p := range filteredParams { |
| 162 | + paramStr += p.Name + "=" |
| 163 | + |
| 164 | + switch p.Value.Type { |
| 165 | + case v1.ParamTypeString: |
| 166 | + paramStr += p.Value.StringVal |
| 167 | + case v1.ParamTypeArray: |
| 168 | + // Sort array values for determinism |
| 169 | + arrayVals := make([]string, len(p.Value.ArrayVal)) |
| 170 | + copy(arrayVals, p.Value.ArrayVal) |
| 171 | + sort.Strings(arrayVals) |
| 172 | + for i, val := range arrayVals { |
| 173 | + if i > 0 { |
| 174 | + paramStr += "," |
| 175 | + } |
| 176 | + paramStr += val |
| 177 | + } |
| 178 | + case v1.ParamTypeObject: |
| 179 | + // Sort object keys for determinism |
| 180 | + keys := make([]string, 0, len(p.Value.ObjectVal)) |
| 181 | + for k := range p.Value.ObjectVal { |
| 182 | + keys = append(keys, k) |
| 183 | + } |
| 184 | + sort.Strings(keys) |
| 185 | + for i, key := range keys { |
| 186 | + if i > 0 { |
| 187 | + paramStr += "," |
| 188 | + } |
| 189 | + paramStr += key + ":" + p.Value.ObjectVal[key] |
| 190 | + } |
| 191 | + default: |
| 192 | + // For unknown types, use StringVal as fallback |
| 193 | + paramStr += p.Value.StringVal |
| 194 | + } |
| 195 | + paramStr += ";" |
| 196 | + } |
| 197 | + |
| 198 | + // Generate a SHA-256 hash of the parameter string |
| 199 | + hash := sha256.Sum256([]byte(paramStr)) |
| 200 | + return hex.EncodeToString(hash[:]), nil |
| 201 | +} |
0 commit comments