/
promise_webhook.go
187 lines (156 loc) · 6.13 KB
/
promise_webhook.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
/*
Copyright 2021 Syntasso.
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 v1alpha1
import (
"context"
"fmt"
"reflect"
"strings"
"k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)
// log is for logging in this package.
var (
promiselog = logf.Log.WithName("promise-webhook")
k8sClientSet clientset.Interface
k8sClient client.Client
)
func (p *Promise) SetupWebhookWithManager(mgr ctrl.Manager, cs *clientset.Clientset, c client.Client) error {
k8sClient = c
k8sClientSet = cs
return ctrl.NewWebhookManagedBy(mgr).
For(p).
Complete()
}
var _ webhook.Defaulter = &Promise{}
// Default implements webhook.Defaulter so a webhook will be registered for the type
func (p *Promise) Default() {
promiselog.Info("default", "name", p.Name)
}
// +kubebuilder:webhook:path=/validate-platform-kratix-io-v1alpha1-promise,mutating=false,failurePolicy=fail,sideEffects=None,groups=platform.kratix.io,resources=promises,verbs=create;update,versions=v1alpha1,name=vpromise.kb.io,admissionReviewVersions=v1
var _ webhook.Validator = &Promise{}
func (p *Promise) validateCRD() error {
newCrd, err := p.GetAPIAsCRD()
if err != nil {
if err == ErrNoAPI {
return nil
}
return err
}
_, err = k8sClientSet.ApiextensionsV1().CustomResourceDefinitions().Create(context.TODO(), newCrd, metav1.CreateOptions{DryRun: []string{metav1.DryRunAll}})
if err != nil {
if errors.IsAlreadyExists(err) {
existingCrd, err := k8sClientSet.ApiextensionsV1().CustomResourceDefinitions().Get(context.TODO(), newCrd.Name, metav1.GetOptions{})
if err != nil {
return err
}
existingCrd.Spec = newCrd.Spec
_, err = k8sClientSet.ApiextensionsV1().CustomResourceDefinitions().Update(context.TODO(), existingCrd, metav1.UpdateOptions{DryRun: []string{metav1.DryRunAll}})
if err != nil {
return fmt.Errorf("invalid CRD changes: %w", err)
}
return nil
}
return fmt.Errorf("invalid CRD: %w", err)
}
return nil
}
// ValidateCreate implements webhook.Validator so a webhook will be registered for the type
func (p *Promise) ValidateCreate() (admission.Warnings, error) {
promiselog.Info("validate create", "name", p.Name)
warnings := p.validateRequiredPromises()
if err := p.validateCRD(); err != nil {
return nil, err
}
return warnings, nil
}
func (p *Promise) validateRequiredPromises() admission.Warnings {
warnings := []string{}
for _, requirement := range p.Spec.RequiredPromises {
promiselog.Info("validating requirement", "name", p.Name, "requirement", requirement.Name, "version", requirement.Version)
promise := &Promise{}
err := k8sClient.Get(context.TODO(), client.ObjectKey{
Namespace: p.Namespace,
Name: requirement.Name,
}, promise)
if err != nil {
if errors.IsNotFound(err) {
warnings = append(warnings, fmt.Sprintf("Required Promise %q at version %q not installed", requirement.Name, requirement.Version))
continue
}
promiselog.Error(err, "failed to get requirement", "requirement", requirement.Name, "version", requirement.Version)
continue
}
if promise.Status.Version != requirement.Version {
warnings = append(warnings, fmt.Sprintf("Required Promise %q installed but not at a compatible version, want: %q have: %q", requirement.Name, requirement.Version, promise.Status.Version))
}
}
if len(warnings) != 0 {
warnings = append(warnings, "Promise will not be available until the above issue(s) is resolved")
}
return warnings
}
// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type
func (p *Promise) ValidateUpdate(old runtime.Object) (admission.Warnings, error) {
promiselog.Info("validating promise update", "name", p.Name)
oldPromise, _ := old.(*Promise)
warnings := p.validateRequiredPromises()
if err := p.validateCRD(); err != nil {
return nil, err
}
oldCrd, errOldCrd := oldPromise.GetAPIAsCRD()
newCrd, errNewCrd := p.GetAPIAsCRD()
if errOldCrd == ErrNoAPI {
return warnings, nil
}
if errNewCrd == ErrNoAPI {
return nil, fmt.Errorf("cannot remove API from existing promise")
}
errors := []string{}
if oldCrd.Name != newCrd.Name {
errors = append(errors, fmt.Sprintf("* spec.api.metadata.name: Invalid value: %q: field is immutable", newCrd.Name))
}
if oldCrd.Kind != newCrd.Kind {
errors = append(errors, fmt.Sprintf("* spec.api.kind: Invalid value: %q: field is immutable", newCrd.Kind))
}
if oldCrd.APIVersion != newCrd.APIVersion {
errors = append(errors, fmt.Sprintf("* spec.api.apiVersion: Invalid value: %q: field is immutable", newCrd.APIVersion))
}
if !reflect.DeepEqual(oldCrd.Spec.Names, newCrd.Spec.Names) {
newNames := fmt.Sprintf(
`{"plural": %q, "singular": %q, "kind": %q}`,
newCrd.Spec.Names.Plural,
newCrd.Spec.Names.Singular,
newCrd.Spec.Names.Kind,
)
errors = append(errors, fmt.Sprintf("* spec.api.spec.names: Invalid value: %s: field is immutable", newNames))
}
if len(errors) > 0 {
//TODO: p.Name is coming through empty or so it seems!
return nil, fmt.Errorf("promises.platform.kratix.io %q was not valid:\n%s", p.Name, strings.Join(errors, "\n"))
}
return warnings, nil
}
// ValidateDelete implements webhook.Validator so a webhook will be registered for the type
func (p *Promise) ValidateDelete() (admission.Warnings, error) {
promiselog.Info("validate delete", "name", p.Name)
// TODO(user): fill in your validation logic upon object deletion.
return nil, nil
}