Skip to content

Commit 2a73501

Browse files
author
Mengqi Yu
committed
cleanup the code a bit
1 parent 040c471 commit 2a73501

11 files changed

+110
-126
lines changed

pkg/webhook/admission.go

+5-14
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,9 @@ func (w *admissionWebhook) setDefaults() {
5151
// can't do defaulting, skip it.
5252
return
5353
}
54-
if w.t == webhookTypeMutating {
54+
if w.t == mutatingWebhook {
5555
w.path = "/mutate-" + w.rules[0].Resources[0]
56-
} else if w.t == webhookTypeValidating {
56+
} else if w.t == validatingWebhook {
5757
w.path = "/validate-" + w.rules[0].Resources[0]
5858
}
5959
}
@@ -64,16 +64,7 @@ func (w *admissionWebhook) setDefaults() {
6464
}
6565
}
6666

67-
// GetName returns the name of the webhook.
68-
func (w *admissionWebhook) GetName() string {
69-
return w.name
70-
}
71-
72-
// GetPath returns the path that the webhook registered.
73-
func (w *admissionWebhook) GetPath() string {
74-
w.setDefaults()
75-
return w.path
76-
}
67+
var _ webhook = &admissionWebhook{}
7768

7869
// GetType returns the type of the webhook.
7970
func (w *admissionWebhook) GetType() webhookType {
@@ -88,8 +79,8 @@ func (w *admissionWebhook) Validate() error {
8879
if len(w.name) == 0 {
8980
return errors.New("field name should not be empty")
9081
}
91-
if w.t != webhookTypeMutating && w.t != webhookTypeValidating {
92-
return fmt.Errorf("unsupported Type: %v, only webhookTypeMutating and webhookTypeValidating are supported", w.t)
82+
if w.t != mutatingWebhook && w.t != validatingWebhook {
83+
return fmt.Errorf("unsupported Type: %v, only mutatingWebhook and validatingWebhook are supported", w.t)
9384
}
9485
if len(w.path) == 0 {
9586
return errors.New("field path should not be empty")

pkg/webhook/generator.go

+75-78
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ import (
3434
)
3535

3636
type generatorOptions struct {
37-
// registry maps a path to a http.Handler.
38-
registry map[string]Webhook
37+
// webhooks maps a path to a webhoook.
38+
webhooks map[string]webhook
3939

4040
// port is the port number that the server will serve.
4141
// It will be defaulted to 443 if unspecified.
@@ -51,17 +51,16 @@ type generatorOptions struct {
5151

5252
// secret is the location for storing the certificate for the admission server.
5353
// The server should have permission to create a secret in the namespace.
54-
// This is optional.
55-
secret *apitypes.NamespacedName // nolint: structcheck
54+
secret *apitypes.NamespacedName
5655

5756
// service is a k8s service fronting the webhook server pod(s).
58-
// This field is optional. But one and only one of service and host need to be set.
57+
// One and only one of service and host can be set.
5958
// This maps to field .Webhooks.ClientConfig.Service
6059
// https://github.com/kubernetes/api/blob/183f3326a9353bd6d41430fc80f96259331d029c/admissionregistration/v1beta1/types.go#L260
6160
service *service
6261
// host is the host name of .Webhooks.ClientConfig.URL
6362
// https://github.com/kubernetes/api/blob/183f3326a9353bd6d41430fc80f96259331d029c/admissionregistration/v1beta1/types.go#L250
64-
// This field is optional. But one and only one of service and host need to be set.
63+
// One and only one of service and host can be set.
6564
// If neither service nor host is unspecified, host will be defaulted to "localhost".
6665
host *string
6766
}
@@ -79,8 +78,8 @@ type service struct {
7978

8079
// setDefault does defaulting for the generatorOptions.
8180
func (o *generatorOptions) setDefault() {
82-
if o.registry == nil {
83-
o.registry = map[string]Webhook{}
81+
if o.webhooks == nil {
82+
o.webhooks = map[string]webhook{}
8483
}
8584
if o.port <= 0 {
8685
o.port = 443
@@ -117,71 +116,16 @@ func (o *generatorOptions) Generate() ([]runtime.Object, error) {
117116
return objects, nil
118117
}
119118

120-
func (o *generatorOptions) getClientConfig() (*admissionregistration.WebhookClientConfig, error) {
121-
if o.host != nil && o.service != nil {
122-
return nil, errors.New("URL and service can't be set at the same time")
123-
}
124-
cc := &admissionregistration.WebhookClientConfig{
125-
// Put an non-empty and not harmful CABundle here.
126-
// Not doing this will cause the field
127-
CABundle: []byte(`\n`),
128-
}
129-
if o.host != nil {
130-
u := url.URL{
131-
Scheme: "https",
132-
Host: net.JoinHostPort(*o.host, strconv.Itoa(int(o.port))),
133-
}
134-
urlString := u.String()
135-
cc.URL = &urlString
136-
}
137-
if o.service != nil {
138-
cc.Service = &admissionregistration.ServiceReference{
139-
Name: o.service.name,
140-
Namespace: o.service.namespace,
141-
// Path will be set later
142-
}
143-
}
144-
return cc, nil
145-
}
146-
147-
// getClientConfigWithPath constructs a WebhookClientConfig based on the server generatorOptions.
148-
// It will use path to the set the path in WebhookClientConfig.
149-
func (o *generatorOptions) getClientConfigWithPath(path string) (*admissionregistration.WebhookClientConfig, error) {
150-
cc, err := o.getClientConfig()
151-
if err != nil {
152-
return nil, err
153-
}
154-
return cc, setPath(cc, path)
155-
}
156-
157-
// setPath sets the path in the WebhookClientConfig.
158-
func setPath(cc *admissionregistration.WebhookClientConfig, path string) error {
159-
if cc.URL != nil {
160-
u, err := url.Parse(*cc.URL)
161-
if err != nil {
162-
return err
163-
}
164-
u.Path = path
165-
urlString := u.String()
166-
cc.URL = &urlString
167-
}
168-
if cc.Service != nil {
169-
cc.Service.Path = &path
170-
}
171-
return nil
172-
}
173-
174-
// whConfigs creates a mutatingWebhookConfiguration and(or) a validatingWebhookConfiguration based on registry.
175-
// For the same type of webhook configuration, it generates a webhook entry per endpoint.
119+
// whConfigs creates a mutatingWebhookConfiguration and(or) a validatingWebhookConfiguration.
176120
func (o *generatorOptions) whConfigs() ([]runtime.Object, error) {
177-
for _, webhook := range o.registry {
121+
for _, webhook := range o.webhooks {
178122
if err := webhook.Validate(); err != nil {
179123
return nil, err
180124
}
181125
}
182126

183127
objs := []runtime.Object{}
184-
mutatingWH, err := o.mutatingWHConfigs()
128+
mutatingWH, err := o.mutatingWHConfig()
185129
if err != nil {
186130
return nil, err
187131
}
@@ -198,15 +142,16 @@ func (o *generatorOptions) whConfigs() ([]runtime.Object, error) {
198142
return objs, nil
199143
}
200144

201-
func (o *generatorOptions) mutatingWHConfigs() (runtime.Object, error) {
145+
// mutatingWHConfig creates mutatingWebhookConfiguration.
146+
func (o *generatorOptions) mutatingWHConfig() (runtime.Object, error) {
202147
mutatingWebhooks := []v1beta1.Webhook{}
203-
for path, webhook := range o.registry {
204-
if webhook.GetType() != webhookTypeMutating {
148+
for path, webhook := range o.webhooks {
149+
if webhook.GetType() != mutatingWebhook {
205150
continue
206151
}
207152

208-
admissionWebhook := webhook.(*admissionWebhook)
209-
wh, err := o.admissionWebhook(path, admissionWebhook)
153+
aw := webhook.(*admissionWebhook)
154+
wh, err := o.admissionWebhook(path, aw)
210155
if err != nil {
211156
return nil, err
212157
}
@@ -226,10 +171,9 @@ func (o *generatorOptions) mutatingWHConfigs() (runtime.Object, error) {
226171
ObjectMeta: metav1.ObjectMeta{
227172
Name: o.mutatingWebhookConfigName,
228173
Annotations: map[string]string{
229-
// The format is "namespace/secret-name"
230174
// This annotation will be understood by cert-manager.
231175
// TODO(mengqiy): point to the section in kubebuilder book when everything is ready.
232-
"alpha.admissionwebhook.kubebuilder.io/ca-secret-name": o.secret.String(),
176+
"alpha.admissionwebhook.cert-manager.io": "true",
233177
},
234178
},
235179
Webhooks: mutatingWebhooks,
@@ -240,9 +184,9 @@ func (o *generatorOptions) mutatingWHConfigs() (runtime.Object, error) {
240184

241185
func (o *generatorOptions) validatingWHConfigs() (runtime.Object, error) {
242186
validatingWebhooks := []v1beta1.Webhook{}
243-
for path, webhook := range o.registry {
187+
for path, webhook := range o.webhooks {
244188
var aw *admissionWebhook
245-
if webhook.GetType() != webhookTypeValidating {
189+
if webhook.GetType() != validatingWebhook {
246190
continue
247191
}
248192

@@ -267,10 +211,9 @@ func (o *generatorOptions) validatingWHConfigs() (runtime.Object, error) {
267211
ObjectMeta: metav1.ObjectMeta{
268212
Name: o.validatingWebhookConfigName,
269213
Annotations: map[string]string{
270-
// The format is "namespace/secret-name"
271214
// This annotation will be understood by cert-manager.
272215
// TODO(mengqiy): point to the section in kubebuilder book when everything is ready.
273-
"alpha.admissionwebhook.kubebuilder.io/ca-secret-name": o.secret.String(),
216+
"alpha.admissionwebhook.cert-manager.io": "true",
274217
},
275218
},
276219
Webhooks: validatingWebhooks,
@@ -305,6 +248,60 @@ func (o *generatorOptions) admissionWebhook(path string, wh *admissionWebhook) (
305248
return webhook, nil
306249
}
307250

251+
// getClientConfigWithPath constructs a WebhookClientConfig based on the server generatorOptions.
252+
// It will use path to the set the path in WebhookClientConfig.
253+
func (o *generatorOptions) getClientConfigWithPath(path string) (*admissionregistration.WebhookClientConfig, error) {
254+
cc, err := o.getClientConfig()
255+
if err != nil {
256+
return nil, err
257+
}
258+
return cc, setPath(cc, path)
259+
}
260+
261+
func (o *generatorOptions) getClientConfig() (*admissionregistration.WebhookClientConfig, error) {
262+
if o.host != nil && o.service != nil {
263+
return nil, errors.New("URL and service can't be set at the same time")
264+
}
265+
cc := &admissionregistration.WebhookClientConfig{
266+
// Put an non-empty and not harmful CABundle here.
267+
// Not doing this will cause the field
268+
CABundle: []byte(`\n`),
269+
}
270+
if o.host != nil {
271+
u := url.URL{
272+
Scheme: "https",
273+
Host: net.JoinHostPort(*o.host, strconv.Itoa(int(o.port))),
274+
}
275+
urlString := u.String()
276+
cc.URL = &urlString
277+
}
278+
if o.service != nil {
279+
cc.Service = &admissionregistration.ServiceReference{
280+
Name: o.service.name,
281+
Namespace: o.service.namespace,
282+
// Path will be set later
283+
}
284+
}
285+
return cc, nil
286+
}
287+
288+
// setPath sets the path in the WebhookClientConfig.
289+
func setPath(cc *admissionregistration.WebhookClientConfig, path string) error {
290+
if cc.URL != nil {
291+
u, err := url.Parse(*cc.URL)
292+
if err != nil {
293+
return err
294+
}
295+
u.Path = path
296+
urlString := u.String()
297+
cc.URL = &urlString
298+
}
299+
if cc.Service != nil {
300+
cc.Service.Path = &path
301+
}
302+
return nil
303+
}
304+
308305
// getService creates a corev1.Service object fronting the admission server.
309306
func (o *generatorOptions) getService() runtime.Object {
310307
if o.service == nil {
@@ -322,7 +319,7 @@ func (o *generatorOptions) getService() runtime.Object {
322319
// Secret here only need name, since it will be in the same namespace as the service.
323320
// This annotation will be understood by cert-manager.
324321
// TODO(mengqiy): point to the section in kubebuilder book when everything is ready.
325-
"alpha.service.kubebuilder.io/serving-cert-secret-name": o.secret.Name,
322+
"alpha.service.cert-manager.io/serving-cert-secret-name": o.secret.Name,
326323
},
327324
},
328325
Spec: corev1.ServiceSpec{

pkg/webhook/generator_test.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ var expected = map[string]string{
2828
kind: MutatingWebhookConfiguration
2929
metadata:
3030
annotations:
31-
alpha.admissionwebhook.kubebuilder.io/ca-secret-name: test-system/webhook-secret
31+
alpha.admissionwebhook.cert-manager.io: "true"
3232
creationTimestamp: null
3333
name: test-mutating-webhook-cfg
3434
webhooks:
@@ -57,7 +57,7 @@ apiVersion: admissionregistration.k8s.io/v1beta1
5757
kind: ValidatingWebhookConfiguration
5858
metadata:
5959
annotations:
60-
alpha.admissionwebhook.kubebuilder.io/ca-secret-name: test-system/webhook-secret
60+
alpha.admissionwebhook.cert-manager.io: "true"
6161
creationTimestamp: null
6262
name: test-validating-webhook-cfg
6363
webhooks:
@@ -87,7 +87,7 @@ apiVersion: v1
8787
kind: Service
8888
metadata:
8989
annotations:
90-
alpha.service.kubebuilder.io/serving-cert-secret-name: webhook-secret
90+
alpha.service.cert-manager.io/serving-cert-secret-name: webhook-secret
9191
creationTimestamp: null
9292
name: webhook-service
9393
namespace: test-system

pkg/webhook/manifests.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ import (
2626
"github.com/ghodss/yaml"
2727
"github.com/spf13/afero"
2828

29-
generateinteral "sigs.k8s.io/controller-tools/pkg/internal/general"
29+
"sigs.k8s.io/controller-tools/pkg/internal/general"
3030
)
3131

3232
// Options represent options for generating the webhook manifests.
@@ -44,7 +44,7 @@ func Generate(o *Options) error {
4444
return err
4545
}
4646

47-
err := generateinteral.ParseDir(o.InputDir, o.parseAnnotation)
47+
err := general.ParseDir(o.InputDir, o.parseAnnotation)
4848
if err != nil {
4949
return fmt.Errorf("failed to parse the input dir: %v", err)
5050
}
@@ -54,7 +54,7 @@ func Generate(o *Options) error {
5454
return err
5555
}
5656

57-
err = o.writeObjectsToDisk(objs...)
57+
err = o.WriteObjectsToDisk(objs...)
5858
if err != nil {
5959
return err
6060
}

pkg/webhook/manifests_test.go

+6-6
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ func TestManifestGenerator(t *testing.T) {
3030
ignoreFP := admissionregistrationv1beta1.Ignore
3131
tests := []struct {
3232
content string
33-
exp map[string]Webhook
33+
exp map[string]webhook
3434
}{
3535
{
3636
content: `package foo
@@ -54,10 +54,10 @@ func TestManifestGenerator(t *testing.T) {
5454
func baz() {
5555
fmt.Println(time.Now())
5656
}`,
57-
exp: map[string]Webhook{
57+
exp: map[string]webhook{
5858
"/bar": &admissionWebhook{
5959
name: "bar-webhook",
60-
t: webhookTypeMutating,
60+
t: mutatingWebhook,
6161
path: "/bar",
6262
rules: []admissionregistrationv1beta1.RuleWithOperations{
6363
{
@@ -75,7 +75,7 @@ func TestManifestGenerator(t *testing.T) {
7575
},
7676
"/baz": &admissionWebhook{
7777
name: "baz-webhook",
78-
t: webhookTypeValidating,
78+
t: validatingWebhook,
7979
path: "/baz",
8080
rules: []admissionregistrationv1beta1.RuleWithOperations{
8181
{
@@ -106,8 +106,8 @@ func TestManifestGenerator(t *testing.T) {
106106
if err != nil {
107107
t.Errorf("processFile should have succeeded, but got error: %v", err)
108108
}
109-
if !reflect.DeepEqual(test.exp, o.registry) {
110-
t.Errorf("webhooks should have matched, expected %#v and got %#v", test.exp, o.registry)
109+
if !reflect.DeepEqual(test.exp, o.webhooks) {
110+
t.Errorf("webhooks should have matched, expected %#v and got %#v", test.exp, o.webhooks)
111111
}
112112
}
113113
}

0 commit comments

Comments
 (0)