forked from kptdev/porch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctionconfigreconciler.go
More file actions
374 lines (312 loc) · 10.8 KB
/
Copy pathfunctionconfigreconciler.go
File metadata and controls
374 lines (312 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
// Copyright 2026 The kpt Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package reconciler
import (
"context"
"maps"
"path/filepath"
"regexp"
"slices"
"strings"
"sync"
"github.com/kptdev/krm-functions-catalog/functions/go/apply-replacements/replacements"
setNamespace "github.com/kptdev/krm-functions-catalog/functions/go/set-namespace/transformer"
"github.com/kptdev/krm-functions-catalog/functions/go/starlark/starlark"
fnsdk "github.com/kptdev/krm-functions-sdk/go/fn"
configapi "github.com/kptdev/porch/api/porchconfig/v1alpha1"
imageutil "github.com/kptdev/porch/pkg/util/image"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
"k8s.io/klog/v2"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)
const BaseFinalizer = "config.porch.kpt.dev/functionconfig"
const ServerFinalizer = BaseFinalizer + "-porch-server"
const FunctionRunnerFinalizer = BaseFinalizer + "-function-runner"
const ControllerFinalizer = BaseFinalizer + "-controller"
type BinaryCacheEntry struct {
PrefixRegex *regexp.Regexp
Tags map[string]string
}
type BuiltInCacheEntry struct {
PrefixRegex *regexp.Regexp
Process fnsdk.ResourceListProcessor
Tags []string
}
type FunctionConfigStore struct {
mu sync.RWMutex
functionConfigurations map[string]*configapi.FunctionConfig
binaryExecutorCache map[string]BinaryCacheEntry
builtInExecutorCache map[string]BuiltInCacheEntry
defaultImagePrefix string
defaultBinaryDir string
}
func NewFunctionConfigStore(defaultImagePrefix, defaultBinaryDir string) *FunctionConfigStore {
return &FunctionConfigStore{
functionConfigurations: make(map[string]*configapi.FunctionConfig),
binaryExecutorCache: make(map[string]BinaryCacheEntry),
builtInExecutorCache: make(map[string]BuiltInCacheEntry),
defaultImagePrefix: strings.TrimRight(defaultImagePrefix, "/"),
defaultBinaryDir: strings.TrimRight(defaultBinaryDir, "/"),
}
}
func (s *FunctionConfigStore) UpsertFunctionConfig(name string, obj *configapi.FunctionConfig) {
s.mu.Lock()
defer s.mu.Unlock()
s.functionConfigurations[name] = obj
}
func (s *FunctionConfigStore) generateRegexPattern(prefixes []string) *regexp.Regexp {
var preparedPrefixes []string
for _, prefix := range prefixes {
if prefix == "" {
preparedPrefixes = append(preparedPrefixes, regexp.QuoteMeta(s.defaultImagePrefix))
} else {
preparedPrefixes = append(preparedPrefixes, regexp.QuoteMeta(prefix))
}
}
return regexp.MustCompile("^(?:" + strings.Join(preparedPrefixes, "|") + ")$")
}
func (s *FunctionConfigStore) UpdateBinaryCache(_ string, obj *configapi.FunctionConfig) {
s.mu.Lock()
defer s.mu.Unlock()
var binaryCacheEntry BinaryCacheEntry
binaryCacheEntry.Tags = make(map[string]string)
// Create a prefix Regex
binaryCacheEntry.PrefixRegex = s.generateRegexPattern(obj.Spec.Prefixes)
abs := obj.Spec.BinaryExecutor.Path
if abs[0] != '/' {
var err error
abs, err = filepath.Abs(filepath.Join(s.defaultBinaryDir, obj.Spec.BinaryExecutor.Path))
if err != nil {
klog.Warningf("Failed to cache %q: %v", obj.Spec.Image, err)
return
}
}
for _, tag := range obj.Spec.BinaryExecutor.Tags {
binaryCacheEntry.Tags[tag] = abs
}
s.binaryExecutorCache[obj.Spec.Image] = binaryCacheEntry
}
func (s *FunctionConfigStore) UpdateExecCache(name string, functionConfig *configapi.FunctionConfig) {
s.mu.Lock()
defer s.mu.Unlock()
id := name
if functionConfig.Spec.GoExecutor.ID != nil {
id = *functionConfig.Spec.GoExecutor.ID
}
applyMappings := func(id string, fn fnsdk.ResourceListProcessorFunc) {
//Clear previous entries for the actual function
for img := range s.builtInExecutorCache {
if strings.Contains(img, name) {
delete(s.builtInExecutorCache, img)
}
}
s.builtInExecutorCache[id] = BuiltInCacheEntry{
Process: fn,
Tags: functionConfig.Spec.GoExecutor.Tags,
PrefixRegex: s.generateRegexPattern(functionConfig.Spec.Prefixes),
}
}
if functionConfig.Name == "apply-replacements" {
applyMappings(id, replacements.ApplyReplacements)
}
if functionConfig.Name == "set-namespace" {
applyMappings(id, setNamespace.Run)
}
if functionConfig.Name == "starlark" {
applyMappings(id, starlark.Process)
}
}
func (s *FunctionConfigStore) DeleteFunctionConfig(key types.NamespacedName) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.functionConfigurations, key.Name)
}
func (s *FunctionConfigStore) GetFunctionConfig(name string) (*configapi.FunctionConfig, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
config, ok := s.functionConfigurations[name]
return config, ok
}
func (s *FunctionConfigStore) GetBinaryFromCache(image string) (string, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
parsedImage := imageutil.Parse(image)
prefixToCheck := parsedImage.Prefix()
binaryStore, exists := s.binaryExecutorCache[parsedImage.BaseName]
if exists {
if binaryStore.PrefixRegex.MatchString(prefixToCheck) {
binaryPath, tagExists := binaryStore.Tags[parsedImage.Tag]
if tagExists {
return binaryPath, true
}
}
}
return "", false
}
func (s *FunctionConfigStore) GetBinaryFromCacheByConstraint(image, tag string) (string, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
parsedImage := imageutil.Parse(image)
cacheEntry, ok := s.binaryExecutorCache[parsedImage.BaseName]
if !ok {
return "", false
}
if !cacheEntry.PrefixRegex.MatchString(parsedImage.Prefix()) {
return "", false
}
cacheKeys := slices.Collect(maps.Keys(cacheEntry.Tags))
selectedKey, err := imageutil.FindBestSemverMatch(tag, cacheKeys)
if err != nil {
return "", false
}
selectedBinary, ok := cacheEntry.Tags[selectedKey]
return selectedBinary, ok
}
func (s *FunctionConfigStore) GetExecCache() map[string]BuiltInCacheEntry {
s.mu.RLock()
defer s.mu.RUnlock()
return s.builtInExecutorCache
}
// GetProcessorFromCache looks up a function processor by image, holding the read lock for the duration of the lookup.
func (s *FunctionConfigStore) GetProcessorFromCache(image string) (fnsdk.ResourceListProcessor, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
parsedImage := imageutil.Parse(image)
entry, found := s.builtInExecutorCache[parsedImage.BaseName]
prefixToCheck := parsedImage.Prefix()
if prefixToCheck == "" {
prefixToCheck = s.defaultImagePrefix
}
if slices.Contains(entry.Tags, parsedImage.Tag) {
if entry.PrefixRegex.MatchString(prefixToCheck) {
return entry.Process, found
}
}
return nil, false
}
func (s *FunctionConfigStore) List() []*configapi.FunctionConfig {
s.mu.Lock()
defer s.mu.Unlock()
return slices.Collect(maps.Values(s.functionConfigurations))
}
type ReconcilerFor string
const (
ReconcilerForFunctionRunner ReconcilerFor = "function-runner"
ReconcilerForServer ReconcilerFor = "server"
ReconcilerForController ReconcilerFor = "controller"
)
type FunctionConfigReconciler struct {
Client client.Client
FunctionConfigStore *FunctionConfigStore
// For indicates which component the reconciler is collecting the configs for
// TODO: remove after merging of function-runner into server
For ReconcilerFor
}
func (r *FunctionConfigReconciler) Reconcile(ctx context.Context, req ctrl.Request) (res ctrl.Result, finalErr error) {
klog.Infof("FunctionConfig %q changed", req.NamespacedName)
obj := &configapi.FunctionConfig{}
err := r.Client.Get(ctx, req.NamespacedName, obj)
if apierrors.IsNotFound(err) {
r.FunctionConfigStore.DeleteFunctionConfig(req.NamespacedName)
return ctrl.Result{}, nil
}
if err != nil {
return ctrl.Result{}, err
}
if obj.DeletionTimestamp != nil {
if err := r.removeFinalizer(ctx, obj); err != nil {
return ctrl.Result{}, err
}
r.FunctionConfigStore.DeleteFunctionConfig(req.NamespacedName)
return ctrl.Result{}, nil
}
if err := r.addFinalizer(ctx, obj); err != nil {
return ctrl.Result{}, err
}
defer func() {
patch := client.MergeFrom(obj.DeepCopy())
if finalErr != nil {
obj.Status.Error = finalErr.Error()
} else {
obj.Status.Error = ""
switch r.For {
case ReconcilerForFunctionRunner:
obj.Status.FunctionRunnerObservedGeneration = obj.Generation
case ReconcilerForServer:
obj.Status.ApiServerObservedGeneration = obj.Generation
case ReconcilerForController:
obj.Status.ControllerObservedGeneration = obj.Generation
}
}
if err := r.Client.Status().Patch(ctx, obj, patch); err != nil {
klog.Errorf("Failed to update status of FunctionConfig %q: %v", obj.Name, err)
if finalErr == nil {
finalErr = err
}
}
}()
// Check if the FunctionConfig already exists in the store with a different name to avoid duplications
image := obj.Spec.Image
fc, exists := r.FunctionConfigStore.GetFunctionConfig(image)
if exists && fc.Name != obj.Name {
klog.Infof("FunctionConfig for %s image is already in the store with a different name", image)
return ctrl.Result{}, nil
}
r.FunctionConfigStore.UpsertFunctionConfig(obj.Name, obj)
if obj.Spec.BinaryExecutor != nil {
r.FunctionConfigStore.UpdateBinaryCache(obj.Name, obj)
}
if obj.Spec.GoExecutor != nil {
r.FunctionConfigStore.UpdateExecCache(obj.Name, obj)
}
return ctrl.Result{}, nil
}
func (r *FunctionConfigReconciler) removeFinalizer(ctx context.Context, obj *configapi.FunctionConfig) error {
patch := client.MergeFrom(obj.DeepCopy())
switch r.For {
case ReconcilerForFunctionRunner:
controllerutil.RemoveFinalizer(obj, FunctionRunnerFinalizer)
case ReconcilerForServer:
controllerutil.RemoveFinalizer(obj, ServerFinalizer)
case ReconcilerForController:
controllerutil.RemoveFinalizer(obj, ControllerFinalizer)
}
if err := r.Client.Patch(ctx, obj, patch); err != nil {
klog.Errorf("Failed to remove finalizer from FunctionConfig %q: %v", obj.Name, err)
return err
}
return nil
}
func (r *FunctionConfigReconciler) addFinalizer(ctx context.Context, obj *configapi.FunctionConfig) error {
patch := client.MergeFrom(obj.DeepCopy())
updated := false
switch r.For {
case ReconcilerForFunctionRunner:
updated = controllerutil.AddFinalizer(obj, FunctionRunnerFinalizer)
case ReconcilerForServer:
updated = controllerutil.AddFinalizer(obj, ServerFinalizer)
case ReconcilerForController:
updated = controllerutil.AddFinalizer(obj, ControllerFinalizer)
}
if updated {
if err := r.Client.Patch(ctx, obj, patch); err != nil {
klog.Errorf("Failed to add finalizer to FunctionConfig %q: %v", obj.Name, err)
return err
}
}
return nil
}