forked from nephio-project/porch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
engine.go
1490 lines (1293 loc) · 48.3 KB
/
engine.go
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022,2024 The kpt and Nephio 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 engine
import (
"bytes"
"context"
"fmt"
"io/fs"
"os"
"path/filepath"
"reflect"
"strings"
api "github.com/nephio-project/porch/api/porch/v1alpha1"
configapi "github.com/nephio-project/porch/api/porchconfig/v1alpha1"
"github.com/nephio-project/porch/internal/kpt/builtins"
"github.com/nephio-project/porch/internal/kpt/fnruntime"
"github.com/nephio-project/porch/pkg/cache"
"github.com/nephio-project/porch/pkg/kpt"
kptfile "github.com/nephio-project/porch/pkg/kpt/api/kptfile/v1"
"github.com/nephio-project/porch/pkg/kpt/fn"
"github.com/nephio-project/porch/pkg/meta"
"github.com/nephio-project/porch/pkg/objects"
"github.com/nephio-project/porch/pkg/repository"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/klog/v2"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/kustomize/kyaml/comments"
"sigs.k8s.io/kustomize/kyaml/kio"
"sigs.k8s.io/kustomize/kyaml/yaml"
)
var tracer = otel.Tracer("engine")
const (
OptimisticLockErrorMsg = "the object has been modified; please apply your changes to the latest version and try again"
)
type CaDEngine interface {
// ObjectCache() is a cache of all our objects.
ObjectCache() WatcherManager
UpdatePackageResources(ctx context.Context, repositoryObj *configapi.Repository, oldPackage *PackageRevision, old, new *api.PackageRevisionResources) (*PackageRevision, *api.RenderStatus, error)
ListFunctions(ctx context.Context, repositoryObj *configapi.Repository) ([]*Function, error)
ListPackageRevisions(ctx context.Context, repositorySpec *configapi.Repository, filter repository.ListPackageRevisionFilter) ([]*PackageRevision, error)
CreatePackageRevision(ctx context.Context, repositoryObj *configapi.Repository, obj *api.PackageRevision, parent *PackageRevision) (*PackageRevision, error)
UpdatePackageRevision(ctx context.Context, repositoryObj *configapi.Repository, oldPackage *PackageRevision, old, new *api.PackageRevision, parent *PackageRevision) (*PackageRevision, error)
DeletePackageRevision(ctx context.Context, repositoryObj *configapi.Repository, obj *PackageRevision) error
ListPackages(ctx context.Context, repositorySpec *configapi.Repository, filter repository.ListPackageFilter) ([]*Package, error)
CreatePackage(ctx context.Context, repositoryObj *configapi.Repository, obj *api.PorchPackage) (*Package, error)
UpdatePackage(ctx context.Context, repositoryObj *configapi.Repository, oldPackage *Package, old, new *api.PorchPackage) (*Package, error)
DeletePackage(ctx context.Context, repositoryObj *configapi.Repository, obj *Package) error
}
type Package struct {
repoPackage repository.Package
}
func (p *Package) GetPackage() *api.PorchPackage {
return p.repoPackage.GetPackage()
}
func (p *Package) KubeObjectName() string {
return p.repoPackage.KubeObjectName()
}
// TODO: This is a bit awkward, and we should see if there is a way to avoid
// having to expose this function. Any functionality that requires creating new
// engine.PackageRevision resources should be in the engine package.
func ToPackageRevision(pkgRev repository.PackageRevision, pkgRevMeta meta.PackageRevisionMeta) *PackageRevision {
return &PackageRevision{
repoPackageRevision: pkgRev,
packageRevisionMeta: pkgRevMeta,
}
}
type PackageRevision struct {
repoPackageRevision repository.PackageRevision
packageRevisionMeta meta.PackageRevisionMeta
}
func (p *PackageRevision) GetPackageRevision(ctx context.Context) (*api.PackageRevision, error) {
repoPkgRev, err := p.repoPackageRevision.GetPackageRevision(ctx)
if err != nil {
return nil, err
}
var isLatest bool
if val, found := repoPkgRev.Labels[api.LatestPackageRevisionKey]; found && val == api.LatestPackageRevisionValue {
isLatest = true
}
repoPkgRev.Labels = p.packageRevisionMeta.Labels
if isLatest {
// copy the labels in case the cached object is being read by another go routine
labels := make(map[string]string, len(repoPkgRev.Labels))
for k, v := range repoPkgRev.Labels {
labels[k] = v
}
labels[api.LatestPackageRevisionKey] = api.LatestPackageRevisionValue
repoPkgRev.Labels = labels
}
repoPkgRev.Annotations = p.packageRevisionMeta.Annotations
repoPkgRev.Finalizers = p.packageRevisionMeta.Finalizers
repoPkgRev.OwnerReferences = p.packageRevisionMeta.OwnerReferences
repoPkgRev.DeletionTimestamp = p.packageRevisionMeta.DeletionTimestamp
return repoPkgRev, nil
}
func (p *PackageRevision) KubeObjectName() string {
return p.repoPackageRevision.KubeObjectName()
}
func (p *PackageRevision) GetResources(ctx context.Context) (*api.PackageRevisionResources, error) {
return p.repoPackageRevision.GetResources(ctx)
}
type Function struct {
RepoFunction repository.Function
}
func (f *Function) Name() string {
return f.RepoFunction.Name()
}
func (f *Function) GetFunction() (*api.Function, error) {
return f.RepoFunction.GetFunction()
}
func NewCaDEngine(opts ...EngineOption) (CaDEngine, error) {
engine := &cadEngine{}
for _, opt := range opts {
if err := opt.apply(engine); err != nil {
return nil, err
}
}
return engine, nil
}
type cadEngine struct {
cache *cache.Cache
// runnerOptionsResolver returns the RunnerOptions for function execution in the specified namespace.
runnerOptionsResolver func(namespace string) fnruntime.RunnerOptions
runtime fn.FunctionRuntime
credentialResolver repository.CredentialResolver
referenceResolver ReferenceResolver
userInfoProvider repository.UserInfoProvider
metadataStore meta.MetadataStore
watcherManager *watcherManager
}
var _ CaDEngine = &cadEngine{}
type mutation interface {
Apply(ctx context.Context, resources repository.PackageResources) (repository.PackageResources, *api.TaskResult, error)
}
// ObjectCache is a cache of all our objects.
func (cad *cadEngine) ObjectCache() WatcherManager {
return cad.watcherManager
}
func (cad *cadEngine) OpenRepository(ctx context.Context, repositorySpec *configapi.Repository) (repository.Repository, error) {
ctx, span := tracer.Start(ctx, "cadEngine::OpenRepository", trace.WithAttributes())
defer span.End()
return cad.cache.OpenRepository(ctx, repositorySpec)
}
func (cad *cadEngine) ListPackageRevisions(ctx context.Context, repositorySpec *configapi.Repository, filter repository.ListPackageRevisionFilter) ([]*PackageRevision, error) {
ctx, span := tracer.Start(ctx, "cadEngine::ListPackageRevisions", trace.WithAttributes())
defer span.End()
repo, err := cad.cache.OpenRepository(ctx, repositorySpec)
if err != nil {
return nil, err
}
pkgRevs, err := repo.ListPackageRevisions(ctx, filter)
if err != nil {
return nil, err
}
var packageRevisions []*PackageRevision
for _, pr := range pkgRevs {
pkgRevMeta, err := cad.metadataStore.Get(ctx, types.NamespacedName{
Name: pr.KubeObjectName(),
Namespace: pr.KubeObjectNamespace(),
})
if err != nil {
// If a PackageRev CR doesn't exist, we treat the
// Packagerevision as not existing.
if apierrors.IsNotFound(err) {
continue
}
return nil, err
}
packageRevisions = append(packageRevisions, &PackageRevision{
repoPackageRevision: pr,
packageRevisionMeta: pkgRevMeta,
})
}
return packageRevisions, nil
}
func buildPackageConfig(ctx context.Context, obj *api.PackageRevision, parent *PackageRevision) (*builtins.PackageConfig, error) {
config := &builtins.PackageConfig{}
parentPath := ""
var parentConfig *unstructured.Unstructured
if parent != nil {
parentObj, err := parent.GetPackageRevision(ctx)
if err != nil {
return nil, err
}
parentPath = parentObj.Spec.PackageName
resources, err := parent.GetResources(ctx)
if err != nil {
return nil, fmt.Errorf("error getting resources from parent package %q: %w", parentObj.Name, err)
}
configMapObj, err := ExtractContextConfigMap(resources.Spec.Resources)
if err != nil {
return nil, fmt.Errorf("error getting configuration from parent package %q: %w", parentObj.Name, err)
}
parentConfig = configMapObj
if parentConfig != nil {
// TODO: Should we support kinds other than configmaps?
var parentConfigMap corev1.ConfigMap
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(parentConfig.Object, &parentConfigMap); err != nil {
return nil, fmt.Errorf("error parsing ConfigMap from parent configuration: %w", err)
}
if s := parentConfigMap.Data[builtins.ConfigKeyPackagePath]; s != "" {
parentPath = s + "/" + parentPath
}
}
}
if parentPath == "" {
config.PackagePath = obj.Spec.PackageName
} else {
config.PackagePath = parentPath + "/" + obj.Spec.PackageName
}
return config, nil
}
func (cad *cadEngine) CreatePackageRevision(ctx context.Context, repositoryObj *configapi.Repository, obj *api.PackageRevision, parent *PackageRevision) (*PackageRevision, error) {
ctx, span := tracer.Start(ctx, "cadEngine::CreatePackageRevision", trace.WithAttributes())
defer span.End()
packageConfig, err := buildPackageConfig(ctx, obj, parent)
if err != nil {
return nil, err
}
// Validate package lifecycle. Cannot create a final package
switch obj.Spec.Lifecycle {
case "":
// Set draft as default
obj.Spec.Lifecycle = api.PackageRevisionLifecycleDraft
case api.PackageRevisionLifecycleDraft, api.PackageRevisionLifecycleProposed:
// These values are ok
case api.PackageRevisionLifecyclePublished, api.PackageRevisionLifecycleDeletionProposed:
// TODO: generate errors that can be translated to correct HTTP responses
return nil, fmt.Errorf("cannot create a package revision with lifecycle value 'Final'")
default:
return nil, fmt.Errorf("unsupported lifecycle value: %s", obj.Spec.Lifecycle)
}
repo, err := cad.cache.OpenRepository(ctx, repositoryObj)
if err != nil {
return nil, err
}
if err := repository.ValidateWorkspaceName(obj.Spec.WorkspaceName); err != nil {
return nil, fmt.Errorf("failed to create packagerevision: %w", err)
}
revs, err := repo.ListPackageRevisions(ctx, repository.ListPackageRevisionFilter{
Package: obj.Spec.PackageName})
if err != nil {
return nil, fmt.Errorf("error listing package revisions: %w", err)
}
if err := ensureUniqueWorkspaceName(obj, revs); err != nil {
return nil, err
}
draft, err := repo.CreatePackageRevision(ctx, obj)
if err != nil {
return nil, err
}
if err := cad.applyTasks(ctx, draft, repositoryObj, obj, packageConfig); err != nil {
return nil, err
}
if err := draft.UpdateLifecycle(ctx, obj.Spec.Lifecycle); err != nil {
return nil, err
}
// Updates are done.
repoPkgRev, err := draft.Close(ctx)
if err != nil {
return nil, err
}
pkgRevMeta := meta.PackageRevisionMeta{
Name: repoPkgRev.KubeObjectName(),
Namespace: repoPkgRev.KubeObjectNamespace(),
Labels: obj.Labels,
Annotations: obj.Annotations,
Finalizers: obj.Finalizers,
OwnerReferences: obj.OwnerReferences,
}
pkgRevMeta, err = cad.metadataStore.Create(ctx, pkgRevMeta, repositoryObj.Name, repoPkgRev.UID())
if err != nil {
return nil, err
}
sent := cad.watcherManager.NotifyPackageRevisionChange(watch.Added, repoPkgRev, pkgRevMeta)
klog.Infof("engine: sent %d for new PackageRevision %s/%s", sent, repoPkgRev.KubeObjectNamespace(), repoPkgRev.KubeObjectName())
return &PackageRevision{
repoPackageRevision: repoPkgRev,
packageRevisionMeta: pkgRevMeta,
}, nil
}
// The workspaceName must be unique, because it used to generate the package revision's metadata.name.
func ensureUniqueWorkspaceName(obj *api.PackageRevision, existingRevs []repository.PackageRevision) error {
for _, r := range existingRevs {
k := r.Key()
if k.WorkspaceName == obj.Spec.WorkspaceName {
return fmt.Errorf("package revision workspaceNames must be unique; package revision with name %s in repo %s with "+
"workspaceName %s already exists", obj.Spec.PackageName, obj.Spec.RepositoryName, obj.Spec.WorkspaceName)
}
}
return nil
}
func getPackageRevision(ctx context.Context, repo repository.Repository, name string) (repository.PackageRevision, bool, error) {
repoPkgRevs, err := repo.ListPackageRevisions(ctx, repository.ListPackageRevisionFilter{
KubeObjectName: name,
})
if err != nil {
return nil, false, err
}
if len(repoPkgRevs) == 0 {
return nil, false, nil
}
return repoPkgRevs[0], true, nil
}
// TODO: See if we can use a library here for parsing OCI image urls
func getBaseImage(image string) string {
if s := strings.Split(image, "@sha256:"); len(s) > 1 {
return s[0]
}
if s := strings.Split(image, ":"); len(s) > 1 {
return s[0]
}
return image
}
func taskTypeOneOf(taskType api.TaskType, oneOf ...api.TaskType) bool {
for _, tt := range oneOf {
if taskType == tt {
return true
}
}
return false
}
func (cad *cadEngine) applyTasks(ctx context.Context, draft repository.PackageDraft, repositoryObj *configapi.Repository, obj *api.PackageRevision, packageConfig *builtins.PackageConfig) error {
var mutations []mutation
// Unless first task is Init or Clone, insert Init to create an empty package.
tasks := obj.Spec.Tasks
if len(tasks) == 0 || !taskTypeOneOf(tasks[0].Type, api.TaskTypeInit, api.TaskTypeClone, api.TaskTypeEdit) {
mutations = append(mutations, &initPackageMutation{
name: obj.Spec.PackageName,
task: &api.Task{
Init: &api.PackageInitTaskSpec{
Subpackage: "",
Description: fmt.Sprintf("%s description", obj.Spec.PackageName),
},
},
})
}
for i := range tasks {
task := &tasks[i]
mutation, err := cad.mapTaskToMutation(ctx, obj, task, repositoryObj.Spec.Deployment, packageConfig)
if err != nil {
return err
}
mutations = append(mutations, mutation)
}
// Render package after creation.
mutations = cad.conditionalAddRender(obj, mutations)
baseResources := repository.PackageResources{}
if _, _, err := applyResourceMutations(ctx, draft, baseResources, mutations); err != nil {
return err
}
return nil
}
type RepositoryOpener interface {
OpenRepository(ctx context.Context, repositorySpec *configapi.Repository) (repository.Repository, error)
}
func (cad *cadEngine) mapTaskToMutation(ctx context.Context, obj *api.PackageRevision, task *api.Task, isDeployment bool, packageConfig *builtins.PackageConfig) (mutation, error) {
switch task.Type {
case api.TaskTypeInit:
if task.Init == nil {
return nil, fmt.Errorf("init not set for task of type %q", task.Type)
}
return &initPackageMutation{
name: obj.Spec.PackageName,
task: task,
}, nil
case api.TaskTypeClone:
if task.Clone == nil {
return nil, fmt.Errorf("clone not set for task of type %q", task.Type)
}
return &clonePackageMutation{
task: task,
namespace: obj.Namespace,
name: obj.Spec.PackageName,
isDeployment: isDeployment,
repoOpener: cad,
credentialResolver: cad.credentialResolver,
referenceResolver: cad.referenceResolver,
packageConfig: packageConfig,
}, nil
case api.TaskTypeUpdate:
if task.Update == nil {
return nil, fmt.Errorf("update not set for task of type %q", task.Type)
}
cloneTask := findCloneTask(obj)
if cloneTask == nil {
return nil, fmt.Errorf("upstream source not found for package rev %q; only cloned packages can be updated", obj.Spec.PackageName)
}
return &updatePackageMutation{
cloneTask: cloneTask,
updateTask: task,
namespace: obj.Namespace,
repoOpener: cad,
referenceResolver: cad.referenceResolver,
pkgName: obj.Spec.PackageName,
}, nil
case api.TaskTypePatch:
return buildPatchMutation(ctx, task)
case api.TaskTypeEdit:
if task.Edit == nil {
return nil, fmt.Errorf("edit not set for task of type %q", task.Type)
}
return &editPackageMutation{
task: task,
namespace: obj.Namespace,
packageName: obj.Spec.PackageName,
repositoryName: obj.Spec.RepositoryName,
repoOpener: cad,
referenceResolver: cad.referenceResolver,
}, nil
case api.TaskTypeEval:
if task.Eval == nil {
return nil, fmt.Errorf("eval not set for task of type %q", task.Type)
}
// TODO: We should find a different way to do this. Probably a separate
// task for render.
if task.Eval.Image == "render" {
runnerOptions := cad.runnerOptionsResolver(obj.Namespace)
return &renderPackageMutation{
runnerOptions: runnerOptions,
runtime: cad.runtime,
}, nil
} else {
runnerOptions := cad.runnerOptionsResolver(obj.Namespace)
return &evalFunctionMutation{
runnerOptions: runnerOptions,
runtime: cad.runtime,
task: task,
}, nil
}
default:
return nil, fmt.Errorf("task of type %q not supported", task.Type)
}
}
func (cad *cadEngine) UpdatePackageRevision(ctx context.Context, repositoryObj *configapi.Repository, oldPackage *PackageRevision, oldObj, newObj *api.PackageRevision, parent *PackageRevision) (*PackageRevision, error) {
ctx, span := tracer.Start(ctx, "cadEngine::UpdatePackageRevision", trace.WithAttributes())
defer span.End()
newRV := newObj.GetResourceVersion()
if len(newRV) == 0 {
return nil, fmt.Errorf("resourceVersion must be specified for an update")
}
if newRV != oldObj.GetResourceVersion() {
return nil, apierrors.NewConflict(api.Resource("packagerevisions"), oldObj.GetName(), fmt.Errorf(OptimisticLockErrorMsg))
}
repo, err := cad.cache.OpenRepository(ctx, repositoryObj)
if err != nil {
return nil, err
}
// Check if the PackageRevision is in the terminating state and
// and this request removes the last finalizer.
repoPkgRev := oldPackage.repoPackageRevision
pkgRevMetaNN := types.NamespacedName{
Name: repoPkgRev.KubeObjectName(),
Namespace: repoPkgRev.KubeObjectNamespace(),
}
pkgRevMeta, err := cad.metadataStore.Get(ctx, pkgRevMetaNN)
if err != nil {
return nil, err
}
// If this is in the terminating state and we are removing the last finalizer,
// we delete the resource instead of updating it.
if pkgRevMeta.DeletionTimestamp != nil && len(newObj.Finalizers) == 0 {
if err := cad.deletePackageRevision(ctx, repo, repoPkgRev, pkgRevMeta); err != nil {
return nil, err
}
return ToPackageRevision(repoPkgRev, pkgRevMeta), nil
}
// Validate package lifecycle. Can only update a draft.
switch lifecycle := oldObj.Spec.Lifecycle; lifecycle {
default:
return nil, fmt.Errorf("invalid original lifecycle value: %q", lifecycle)
case api.PackageRevisionLifecycleDraft, api.PackageRevisionLifecycleProposed:
// Draft or proposed can be updated.
case api.PackageRevisionLifecyclePublished, api.PackageRevisionLifecycleDeletionProposed:
// Only metadata (currently labels and annotations) and lifecycle can be updated for published packages.
if oldObj.Spec.Lifecycle != newObj.Spec.Lifecycle {
if err := oldPackage.repoPackageRevision.UpdateLifecycle(ctx, newObj.Spec.Lifecycle); err != nil {
return nil, err
}
}
pkgRevMeta, err = cad.updatePkgRevMeta(ctx, repoPkgRev, newObj)
if err != nil {
return nil, err
}
sent := cad.watcherManager.NotifyPackageRevisionChange(watch.Modified, repoPkgRev, pkgRevMeta)
klog.Infof("engine: sent %d for updated PackageRevision metadata %s/%s", sent, repoPkgRev.KubeObjectNamespace(), repoPkgRev.KubeObjectName())
return ToPackageRevision(repoPkgRev, pkgRevMeta), nil
}
switch lifecycle := newObj.Spec.Lifecycle; lifecycle {
default:
return nil, fmt.Errorf("invalid desired lifecycle value: %q", lifecycle)
case api.PackageRevisionLifecycleDraft, api.PackageRevisionLifecycleProposed, api.PackageRevisionLifecyclePublished, api.PackageRevisionLifecycleDeletionProposed:
// These values are ok
}
if isRecloneAndReplay(oldObj, newObj) {
packageConfig, err := buildPackageConfig(ctx, newObj, parent)
if err != nil {
return nil, err
}
repoPkgRev, err := cad.recloneAndReplay(ctx, repo, repositoryObj, newObj, packageConfig)
if err != nil {
return nil, err
}
pkgRevMeta, err = cad.updatePkgRevMeta(ctx, repoPkgRev, newObj)
if err != nil {
return nil, err
}
sent := cad.watcherManager.NotifyPackageRevisionChange(watch.Modified, repoPkgRev, pkgRevMeta)
klog.Infof("engine: sent %d for reclone and replay PackageRevision %s/%s", sent, repoPkgRev.KubeObjectNamespace(), repoPkgRev.KubeObjectName())
return ToPackageRevision(repoPkgRev, pkgRevMeta), nil
}
var mutations []mutation
if len(oldObj.Spec.Tasks) > len(newObj.Spec.Tasks) {
return nil, fmt.Errorf("removing tasks is not yet supported")
}
for i := range oldObj.Spec.Tasks {
oldTask := &oldObj.Spec.Tasks[i]
newTask := &newObj.Spec.Tasks[i]
if oldTask.Type != newTask.Type {
return nil, fmt.Errorf("changing task types is not yet supported")
}
}
if len(newObj.Spec.Tasks) > len(oldObj.Spec.Tasks) {
if len(newObj.Spec.Tasks) > len(oldObj.Spec.Tasks)+1 {
return nil, fmt.Errorf("can only append one task at a time")
}
newTask := newObj.Spec.Tasks[len(newObj.Spec.Tasks)-1]
if newTask.Type != api.TaskTypeUpdate {
return nil, fmt.Errorf("appended task is type %q, must be type %q", newTask.Type, api.TaskTypeUpdate)
}
if newTask.Update == nil {
return nil, fmt.Errorf("update not set for updateTask of type %q", newTask.Type)
}
cloneTask := findCloneTask(oldObj)
if cloneTask == nil {
return nil, fmt.Errorf("upstream source not found for package rev %q; only cloned packages can be updated", oldObj.Spec.PackageName)
}
mutation := &updatePackageMutation{
cloneTask: cloneTask,
updateTask: &newTask,
repoOpener: cad,
referenceResolver: cad.referenceResolver,
namespace: repositoryObj.Namespace,
pkgName: oldObj.GetName(),
}
mutations = append(mutations, mutation)
}
// Re-render if we are making changes.
mutations = cad.conditionalAddRender(newObj, mutations)
draft, err := repo.UpdatePackageRevision(ctx, oldPackage.repoPackageRevision)
if err != nil {
return nil, err
}
// If any of the fields in the API that are projections from the Kptfile
// must be updated in the Kptfile as well.
kfPatchTask, created, err := createKptfilePatchTask(ctx, oldPackage.repoPackageRevision, newObj)
if err != nil {
return nil, err
}
if created {
kfPatchMutation, err := buildPatchMutation(ctx, kfPatchTask)
if err != nil {
return nil, err
}
mutations = append(mutations, kfPatchMutation)
}
// Re-render if we are making changes.
mutations = cad.conditionalAddRender(newObj, mutations)
// TODO: Handle the case if alongside lifecycle change, tasks are changed too.
// Update package contents only if the package is in draft state
if oldObj.Spec.Lifecycle == api.PackageRevisionLifecycleDraft {
apiResources, err := oldPackage.GetResources(ctx)
if err != nil {
return nil, fmt.Errorf("cannot get package resources: %w", err)
}
resources := repository.PackageResources{
Contents: apiResources.Spec.Resources,
}
if _, _, err := applyResourceMutations(ctx, draft, resources, mutations); err != nil {
return nil, err
}
}
if err := draft.UpdateLifecycle(ctx, newObj.Spec.Lifecycle); err != nil {
return nil, err
}
// Updates are done.
repoPkgRev, err = draft.Close(ctx)
if err != nil {
return nil, err
}
pkgRevMeta, err = cad.updatePkgRevMeta(ctx, repoPkgRev, newObj)
if err != nil {
return nil, err
}
sent := cad.watcherManager.NotifyPackageRevisionChange(watch.Modified, repoPkgRev, pkgRevMeta)
klog.Infof("engine: sent %d for updated PackageRevision %s/%s", sent, repoPkgRev.KubeObjectNamespace(), repoPkgRev.KubeObjectName())
// Refresh Cache after package is approved so that 'main' package rev is available instantly after creation
if repoPkgRev.Lifecycle() == api.PackageRevisionLifecyclePublished {
err := repo.RefreshCache(ctx)
if err != nil {
return nil, err
}
}
return ToPackageRevision(repoPkgRev, pkgRevMeta), nil
}
func (cad *cadEngine) updatePkgRevMeta(ctx context.Context, repoPkgRev repository.PackageRevision, apiPkgRev *api.PackageRevision) (meta.PackageRevisionMeta, error) {
pkgRevMeta := meta.PackageRevisionMeta{
Name: repoPkgRev.KubeObjectName(),
Namespace: repoPkgRev.KubeObjectNamespace(),
Labels: apiPkgRev.Labels,
Annotations: apiPkgRev.Annotations,
Finalizers: apiPkgRev.Finalizers,
OwnerReferences: apiPkgRev.OwnerReferences,
}
return cad.metadataStore.Update(ctx, pkgRevMeta)
}
func createKptfilePatchTask(ctx context.Context, oldPackage repository.PackageRevision, newObj *api.PackageRevision) (*api.Task, bool, error) {
kf, err := oldPackage.GetKptfile(ctx)
if err != nil {
return nil, false, err
}
var orgKfString string
{
var buf bytes.Buffer
d := yaml.NewEncoder(&buf)
if err := d.Encode(kf); err != nil {
return nil, false, err
}
orgKfString = buf.String()
}
var readinessGates []kptfile.ReadinessGate
for _, rg := range newObj.Spec.ReadinessGates {
readinessGates = append(readinessGates, kptfile.ReadinessGate{
ConditionType: rg.ConditionType,
})
}
var conditions []kptfile.Condition
for _, c := range newObj.Status.Conditions {
conditions = append(conditions, kptfile.Condition{
Type: c.Type,
Status: convertStatusToKptfile(c.Status),
Reason: c.Reason,
Message: c.Message,
})
}
if kf.Info == nil && len(readinessGates) > 0 {
kf.Info = &kptfile.PackageInfo{}
}
if len(readinessGates) > 0 {
kf.Info.ReadinessGates = readinessGates
}
if kf.Status == nil && len(conditions) > 0 {
kf.Status = &kptfile.Status{}
}
if len(conditions) > 0 {
kf.Status.Conditions = conditions
}
var newKfString string
{
var buf bytes.Buffer
d := yaml.NewEncoder(&buf)
if err := d.Encode(kf); err != nil {
return nil, false, err
}
newKfString = buf.String()
}
patchSpec, err := GeneratePatch(kptfile.KptFileName, orgKfString, newKfString)
if err != nil {
return nil, false, err
}
// If patch is empty, don't create a Task.
if patchSpec.Contents == "" {
return nil, false, nil
}
return &api.Task{
Type: api.TaskTypePatch,
Patch: &api.PackagePatchTaskSpec{
Patches: []api.PatchSpec{
patchSpec,
},
},
}, true, nil
}
func convertStatusToKptfile(s api.ConditionStatus) kptfile.ConditionStatus {
switch s {
case api.ConditionTrue:
return kptfile.ConditionTrue
case api.ConditionFalse:
return kptfile.ConditionFalse
case api.ConditionUnknown:
return kptfile.ConditionUnknown
default:
panic(fmt.Errorf("unknown condition status: %v", s))
}
}
// conditionalAddRender adds a render mutation to the end of the mutations slice if the last
// entry is not already a render mutation.
func (cad *cadEngine) conditionalAddRender(subject client.Object, mutations []mutation) []mutation {
if len(mutations) == 0 || isRenderMutation(mutations[len(mutations)-1]) {
return mutations
}
runnerOptions := cad.runnerOptionsResolver(subject.GetNamespace())
return append(mutations, &renderPackageMutation{
runnerOptions: runnerOptions,
runtime: cad.runtime,
})
}
func isRenderMutation(m mutation) bool {
_, isRender := m.(*renderPackageMutation)
return isRender
}
func (cad *cadEngine) DeletePackageRevision(ctx context.Context, repositoryObj *configapi.Repository, oldPackage *PackageRevision) error {
ctx, span := tracer.Start(ctx, "cadEngine::DeletePackageRevision", trace.WithAttributes())
defer span.End()
repo, err := cad.cache.OpenRepository(ctx, repositoryObj)
if err != nil {
return err
}
// We delete the PackageRev regardless of any finalizers, since it
// will always have the same finalizers as the PackageRevision. This
// will put the PackageRev, and therefore the PackageRevision in the
// terminating state.
// But we only delete the PackageRevision from the repo once all finalizers
// have been removed.
namespacedName := types.NamespacedName{
Name: oldPackage.repoPackageRevision.KubeObjectName(),
Namespace: oldPackage.repoPackageRevision.KubeObjectNamespace(),
}
pkgRevMeta, err := cad.metadataStore.Delete(ctx, namespacedName, false)
if err != nil {
return err
}
if len(pkgRevMeta.Finalizers) > 0 {
klog.Infof("PackageRevision %s deleted, but still have finalizers: %s", oldPackage.KubeObjectName(), strings.Join(pkgRevMeta.Finalizers, ","))
sent := cad.watcherManager.NotifyPackageRevisionChange(watch.Modified, oldPackage.repoPackageRevision, oldPackage.packageRevisionMeta)
klog.Infof("engine: sent %d modified for deleted PackageRevision %s/%s with finalizers", sent, oldPackage.repoPackageRevision.KubeObjectNamespace(), oldPackage.KubeObjectName())
return nil
}
klog.Infof("PackageRevision %s deleted for real since no finalizers", oldPackage.KubeObjectName())
return cad.deletePackageRevision(ctx, repo, oldPackage.repoPackageRevision, oldPackage.packageRevisionMeta)
}
func (cad *cadEngine) deletePackageRevision(ctx context.Context, repo repository.Repository, repoPkgRev repository.PackageRevision, pkgRevMeta meta.PackageRevisionMeta) error {
ctx, span := tracer.Start(ctx, "cadEngine::deletePackageRevision", trace.WithAttributes())
defer span.End()
if err := repo.DeletePackageRevision(ctx, repoPkgRev); err != nil {
return err
}
nn := types.NamespacedName{
Name: pkgRevMeta.Name,
Namespace: pkgRevMeta.Namespace,
}
if _, err := cad.metadataStore.Delete(ctx, nn, true); err != nil {
// If this fails, the CR will be cleaned up by the background job.
if !apierrors.IsNotFound(err) {
klog.Warningf("Error deleting PkgRevMeta %s: %v", nn.String(), err)
}
}
sent := cad.watcherManager.NotifyPackageRevisionChange(watch.Deleted, repoPkgRev, pkgRevMeta)
klog.Infof("engine: sent %d for deleted PackageRevision %s/%s", sent, repoPkgRev.KubeObjectNamespace(), repoPkgRev.KubeObjectName())
return nil
}
func (cad *cadEngine) ListPackages(ctx context.Context, repositorySpec *configapi.Repository, filter repository.ListPackageFilter) ([]*Package, error) {
ctx, span := tracer.Start(ctx, "cadEngine::ListPackages", trace.WithAttributes())
defer span.End()
repo, err := cad.cache.OpenRepository(ctx, repositorySpec)
if err != nil {
return nil, err
}
pkgs, err := repo.ListPackages(ctx, filter)
if err != nil {
return nil, err
}
var packages []*Package
for _, p := range pkgs {
packages = append(packages, &Package{
repoPackage: p,
})
}
return packages, nil
}
func (cad *cadEngine) CreatePackage(ctx context.Context, repositoryObj *configapi.Repository, obj *api.PorchPackage) (*Package, error) {
ctx, span := tracer.Start(ctx, "cadEngine::CreatePackage", trace.WithAttributes())
defer span.End()
repo, err := cad.cache.OpenRepository(ctx, repositoryObj)
if err != nil {
return nil, err
}
pkg, err := repo.CreatePackage(ctx, obj)
if err != nil {
return nil, err
}
return &Package{
repoPackage: pkg,
}, nil
}
func (cad *cadEngine) UpdatePackage(ctx context.Context, repositoryObj *configapi.Repository, oldPackage *Package, oldObj, newObj *api.PorchPackage) (*Package, error) {
ctx, span := tracer.Start(ctx, "cadEngine::UpdatePackage", trace.WithAttributes())
defer span.End()
// TODO
var pkg *Package
return pkg, fmt.Errorf("Updating packages is not yet supported")
}
func (cad *cadEngine) DeletePackage(ctx context.Context, repositoryObj *configapi.Repository, oldPackage *Package) error {
ctx, span := tracer.Start(ctx, "cadEngine::DeletePackage", trace.WithAttributes())
defer span.End()
repo, err := cad.cache.OpenRepository(ctx, repositoryObj)
if err != nil {
return err
}
if err := repo.DeletePackage(ctx, oldPackage.repoPackage); err != nil {
return err
}
return nil
}
func (cad *cadEngine) UpdatePackageResources(ctx context.Context, repositoryObj *configapi.Repository, oldPackage *PackageRevision, old, new *api.PackageRevisionResources) (*PackageRevision, *api.RenderStatus, error) {
ctx, span := tracer.Start(ctx, "cadEngine::UpdatePackageResources", trace.WithAttributes())
defer span.End()
rev, err := oldPackage.repoPackageRevision.GetPackageRevision(ctx)
if err != nil {
return nil, nil, err
}
newRV := new.GetResourceVersion()
if len(newRV) == 0 {
return nil, nil, fmt.Errorf("resourceVersion must be specified for an update")
}
if newRV != old.GetResourceVersion() {
return nil, nil, apierrors.NewConflict(api.Resource("packagerevisionresources"), old.GetName(), fmt.Errorf(OptimisticLockErrorMsg))
}
// Validate package lifecycle. Can only update a draft.
switch lifecycle := rev.Spec.Lifecycle; lifecycle {
default:
return nil, nil, fmt.Errorf("invalid original lifecycle value: %q", lifecycle)
case api.PackageRevisionLifecycleDraft:
// Only drafts can be updated.
case api.PackageRevisionLifecycleProposed, api.PackageRevisionLifecyclePublished, api.PackageRevisionLifecycleDeletionProposed:
// TODO: generate errors that can be translated to correct HTTP responses
return nil, nil, fmt.Errorf("cannot update a package revision with lifecycle value %q; package must be Draft", lifecycle)
}
repo, err := cad.cache.OpenRepository(ctx, repositoryObj)
if err != nil {
return nil, nil, err
}
draft, err := repo.UpdatePackageRevision(ctx, oldPackage.repoPackageRevision)