-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathinject_webhook.go
201 lines (177 loc) · 6.8 KB
/
inject_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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package controllers
import (
"bytes"
"context"
"errors"
"net/http"
"strings"
"text/template"
jsonpatch "github.com/evanphx/json-patch"
"github.com/redhat-cop/operator-utils/pkg/util/discoveryclient"
utilstemplate "github.com/redhat-cop/operator-utils/pkg/util/templates"
v1authn "k8s.io/api/authentication/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
"sigs.k8s.io/yaml"
)
const patchKey string = "redhat-cop.redhat.io/patch"
type PatchType string
// allowed values one of "application/json-patch+json"'"application/merge-patch+json","application/strategic-merge-patch+json". Default "application/strategic-merge-patch+json"
const patchTypeAnnotation string = "redhat-cop.redhat.io/patch-type"
const (
jsonPatch PatchType = "application/json-patch+json"
mergePatch PatchType = "application/merge-patch+json"
strategicMergePatch PatchType = "application/strategic-merge-patch+json"
)
var createTimePatchLog = logf.Log.WithName("create-time-patch-webhook")
// podAnnotator annotates Pods
// +kubebuilder:object:generate:=false
type PatchInjector struct {
client client.Client
restConfig *rest.Config
decoder *admission.Decoder
crr *CustomResourceDefinitionReconciler
}
func NewPatchInjector(client client.Client, restConfig *rest.Config, customResourceDefinitionReconciler *CustomResourceDefinitionReconciler) *PatchInjector {
return &PatchInjector{
client: client,
restConfig: restConfig,
crr: customResourceDefinitionReconciler,
}
}
// podAnnotator adds an annotation to every incoming pods.
func (a *PatchInjector) Handle(ctx context.Context, req admission.Request) admission.Response {
ctx = context.WithValue(ctx, "restConfig", a.restConfig)
ctx = log.IntoContext(ctx, createTimePatchLog)
obj := &unstructured.Unstructured{}
err := a.decoder.Decode(req, obj)
if err != nil {
return admission.Errored(http.StatusBadRequest, err)
}
for key := range obj.GetAnnotations() {
if key == patchKey {
//compute the template
templ, err := template.New(obj.GetAnnotations()[patchKey]).Funcs(a.advancedTemplateFuncMapWithImpersonation(ctx, &req.UserInfo)).Parse(obj.GetAnnotations()[patchKey])
if err != nil {
createTimePatchLog.Error(err, "unable to parse ", "template", obj.GetAnnotations()[patchKey])
return admission.Errored(http.StatusInternalServerError, err)
}
var b bytes.Buffer
err = templ.Execute(&b, obj)
if err != nil {
createTimePatchLog.Error(err, "unable to process ", "template ", templ, "parameters", obj)
return admission.Errored(http.StatusInternalServerError, err)
}
bb, err := yaml.YAMLToJSON(b.Bytes())
if err != nil {
createTimePatchLog.Error(err, "unable to convert to json", "processed template", b.String())
return admission.Errored(http.StatusInternalServerError, err)
}
patchType, ok := obj.GetAnnotations()[patchTypeAnnotation]
if !ok {
patchType = "application/strategic-merge-patch+json"
}
switch PatchType(patchType) {
case jsonPatch:
{
patch, err := jsonpatch.DecodePatch(bb)
if err != nil {
createTimePatchLog.Error(err, "unable to decode", "jsonpatch", string(bb))
return admission.Errored(http.StatusInternalServerError, err)
}
patchedObject, err := patch.Apply(req.Object.Raw)
if err != nil {
createTimePatchLog.Error(err, "unable patch object", "original", req.Object.Raw, "patch", string(bb))
return admission.Errored(http.StatusInternalServerError, err)
}
return admission.PatchResponseFromRaw(req.Object.Raw, patchedObject)
}
case mergePatch:
{
patchedObject, err := jsonpatch.MergePatch(req.Object.Raw, bb)
if err != nil {
createTimePatchLog.Error(err, "unable patch object", "original", req.Object.Raw, "patch", string(bb))
return admission.Errored(http.StatusInternalServerError, err)
}
return admission.PatchResponseFromRaw(req.Object.Raw, patchedObject)
}
case strategicMergePatch:
{
patchMeta, err := a.getPatchMeta(ctx, obj)
if err != nil {
createTimePatchLog.Error(err, "unable to get patchMeta", "for object", obj)
return admission.Errored(http.StatusInternalServerError, err)
}
patchedObject, err := strategicpatch.StrategicMergePatchUsingLookupPatchMeta(req.Object.Raw, bb, patchMeta)
if err != nil {
createTimePatchLog.Error(err, "unable to get patch", "object", obj, "with patch", bb, "patch type", patchType)
return admission.Errored(http.StatusInternalServerError, err)
}
return admission.PatchResponseFromRaw(req.Object.Raw, patchedObject)
}
default:
{
err := errors.New("unsupported patch type" + patchType)
return admission.Errored(http.StatusInternalServerError, err)
}
}
}
}
return admission.Allowed("no changes")
}
func getModelName(apiresource *metav1.APIResource) string {
var group, version string
if apiresource.Group == "" {
group = "io.k8s.api.core"
} else {
if !strings.Contains(apiresource.Group, ".") {
group = "io.k8s.api." + apiresource.Group
} else {
group = apiresource.Group
}
}
if apiresource.Version == "" {
version = "v1"
} else {
version = apiresource.Version
}
return group + "." + version + "." + apiresource.Kind
}
func (a *PatchInjector) getPatchMeta(context context.Context, obj *unstructured.Unstructured) (strategicpatch.LookupPatchMeta, error) {
log := log.FromContext(context)
resource, found, err := discoveryclient.GetAPIResourceForGVK(context, obj.GroupVersionKind())
if err != nil {
log.Error(err, "unable to find resource from", "GVK", obj.GroupVersionKind())
return nil, err
}
if !found {
return nil, errors.New("GVK not found: " + obj.GroupVersionKind().String())
}
openapiModels := a.crr.GetModels()
log.V(1).Info("getPatchMeta", "getModelName(resource)", getModelName(resource))
openapiSchema := openapiModels.LookupModel(getModelName(resource))
return strategicpatch.NewPatchMetaFromOpenAPI(openapiSchema), nil
}
// InjectDecoder injects the decoder.
func (a *PatchInjector) InjectDecoder(d *admission.Decoder) error {
a.decoder = d
return nil
}
func (a *PatchInjector) advancedTemplateFuncMapWithImpersonation(ctx context.Context, userInfo *v1authn.UserInfo) template.FuncMap {
rc := rest.CopyConfig(a.restConfig)
rc.Impersonate.UserName = userInfo.Username
rc.Impersonate.Groups = userInfo.Groups
extra := map[string][]string{}
for k := range userInfo.Extra {
extra[k] = userInfo.Extra[k]
}
rc.Impersonate.Extra = extra
funcs := utilstemplate.AdvancedTemplateFuncMap(rc, createTimePatchLog)
return funcs
}