New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update godoc for webhook #147

Merged
merged 1 commit into from Sep 18, 2018
Jump to file or symbol
Failed to load files and symbols.
+216 −27
Diff settings

Always

Just for now

View
@@ -49,6 +49,19 @@ system must be read for each Reconciler.
* Controller require Watches to be configured to enqueue reconcile.Requests in response to events.
Webhook
Admission Webhooks are a mechanism for extending kubernetes APIs. Webhooks can be configured with target
event type (object Create, Update, Delete), the API server will send AdmissionRequests to them
when certain events happen. The webhooks may mutate and (or) validate the object embedded in
the AdmissionReview requests and send back the response to the API server.
There are 2 types of admission webhook: mutating and validating admission webhook.
Mutating webhook is used to mutate a core API object or a CRD instance before the API server admits it.
Validating webhook is used to validate if an object meets certain requirements.
* Admission Webhooks require Handler(s) to be provided to process the received AdmissionReview requests.
Reconciler
Reconciler is a function provided to a Controller that may be called at anytime with the Name and Namespace of an object.
@@ -0,0 +1,107 @@
/*
Copyright 2018 The Kubernetes 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 builder provides methods to build admission webhooks.
The following are 2 examples for building mutating webhook and validating webhook.
webhook1, err := NewWebhookBuilder().
Mutating().
Operations(admissionregistrationv1beta1.Create).
ForType(&corev1.Pod{}).
WithManager(mgr).
Handlers(mutatingHandler11, mutatingHandler12).
Build()
if err != nil {
// handle error
}
webhook2, err := NewWebhookBuilder().
Validating().
Operations(admissionregistrationv1beta1.Create, admissionregistrationv1beta1.Update).
ForType(&appsv1.Deployment{}).
WithManager(mgr).
Handlers(validatingHandler21).
Build()
if err != nil {
// handle error
}
Note: To build a webhook for a CRD, you need to ensure the manager uses the scheme that understands your CRD.
This is necessary, because if the scheme doesn't understand your CRD types, the decoder won't be able to decode
the CR object from the admission review request.
The following snippet shows how to register CRD types with manager's scheme.
mgr, err := manager.New(cfg, manager.Options{})
if err != nil {
// handle error
}
// SchemeGroupVersion is group version used to register these objects
SchemeGroupVersion = schema.GroupVersion{Group: "crew.k8s.io", Version: "v1"}
// SchemeBuilder is used to add go types to the GroupVersionKind scheme
SchemeBuilder = &scheme.Builder{GroupVersion: SchemeGroupVersion}
// Register your CRD types.
SchemeBuilder.Register(&Kraken{}, &KrakenList{})
// Register your CRD types with the manager's scheme.
err = SchemeBuilder.AddToScheme(mgr.GetScheme())
if err != nil {
// handle error
}
There are more options for configuring a webhook. e.g. Name, Path, FailurePolicy, NamespaceSelector.
Here is another example:
webhook3, err := NewWebhookBuilder().
Name("foo.example.com").
Path("/mutatepods").
Mutating().
Operations(admissionregistrationv1beta1.Create).
ForType(&corev1.Pod{}).
FailurePolicy(admissionregistrationv1beta1.Fail).
WithManager(mgr).
Handlers(mutatingHandler31, mutatingHandler32).
Build()
if err != nil {
// handle error
}
For most users, we recommend to use Operations and ForType instead of Rules to construct a webhook,
since it is more intuitive and easier to pass the target operations to Operations method and
a empty target object to ForType method than passing a complex RuleWithOperations struct to Rules method.
Rules may be useful for some more advanced use cases like subresources, wildcard resources etc.
Here is an example:
webhook4, err := NewWebhookBuilder().
Validating().
Rules(admissionregistrationv1beta1.RuleWithOperations{
Operations: []admissionregistrationv1beta1.OperationType{admissionregistrationv1beta1.Create},
Rule: admissionregistrationv1beta1.Rule{
APIGroups: []string{"apps", "batch"},
APIVersions: []string{"v1"},
Resources: []string{"*"},
},
}).
WithManager(mgr).
Handlers(validatingHandler41).
Build()
if err != nil {
// handle error
}
*/
package builder
@@ -15,30 +15,81 @@ limitations under the License.
*/
/*
Package admission provides functions to build and bootstrap an admission webhook server for a k8s cluster.
Build webhooks
webhook1, err := NewWebhookBuilder().
Name("foo.k8s.io").
Mutating().
Operations(admissionregistrationv1beta1.Create).
ForType(&corev1.Pod{}).
WithManager(mgr).
Build(mutatingHandler1, mutatingHandler2)
if err != nil {
// handle error
}
webhook2, err := NewWebhookBuilder().
Name("bar.k8s.io").
Validating().
Operations(admissionregistrationv1beta1.Create, admissionregistrationv1beta1.Update).
ForType(&appsv1.Deployment{}).
WithManager(mgr).
Build(validatingHandler1)
if err != nil {
// handle error
Package admission provides implementation for admission webhook and methods to implement admission webhook handlers.
The following snippet is an example implementation of mutating handler.
type Mutator struct {
client client.Client
decoder types.Decoder
}
func (m *Mutator) mutatePodsFn(ctx context.Context, pod *corev1.Pod) error {
// your logic to mutate the passed-in pod.
}
func (m *Mutator) Handle(ctx context.Context, req types.Request) types.Response {
pod := &corev1.Pod{}
err := m.decoder.Decode(req, pod)
if err != nil {
return admission.ErrorResponse(http.StatusBadRequest, err)
}
// Do deepcopy before actually mutate the object.
copy := pod.DeepCopy()
err = m.mutatePodsFn(ctx, copy)
if err != nil {
return admission.ErrorResponse(http.StatusInternalServerError, err)
}
return admission.PatchResponse(pod, copy)
}
// InjectClient is called by the Manager and provides a client.Client to the Mutator instance.
func (m *Mutator) InjectClient(c client.Client) error {
h.client = c
return nil
}
// InjectDecoder is called by the Manager and provides a types.Decoder to the Mutator instance.
func (m *Mutator) InjectDecoder(d types.Decoder) error {
h.decoder = d
return nil
}
The following snippet is an example implementation of validating handler.
type Handler struct {
client client.Client
decoder types.Decoder
}
func (v *Validator) validatePodsFn(ctx context.Context, pod *corev1.Pod) (bool, string, error) {
// your business logic
}
func (v *Validator) Handle(ctx context.Context, req types.Request) types.Response {
pod := &corev1.Pod{}
err := h.decoder.Decode(req, pod)
if err != nil {
return admission.ErrorResponse(http.StatusBadRequest, err)
}
allowed, reason, err := h.validatePodsFn(ctx, pod)
if err != nil {
return admission.ErrorResponse(http.StatusInternalServerError, err)
}
return admission.ValidationResponse(allowed, reason)
}
// InjectClient is called by the Manager and provides a client.Client to the Validator instance.
func (v *Validator) InjectClient(c client.Client) error {
h.client = c
return nil
}
// InjectDecoder is called by the Manager and provides a types.Decoder to the Validator instance.
func (v *Validator) InjectDecoder(d types.Decoder) error {
h.decoder = d
return nil
}
*/
package admission
View
@@ -15,7 +15,9 @@ limitations under the License.
*/
/*
Package webhook provides functions to build and bootstrap an admission webhook server for a k8s cluster.
Package webhook provides methods to build and bootstrap a webhook server.
Currently, it only supports admission webhooks. It will support CRD conversion webhooks in the near future.
Build webhooks
@@ -46,9 +48,25 @@ Build webhooks
// handle error
}
Create a server for webhooks.
Create a webhook server.
as, err := NewServer("baz-admission-server", mrg, ServerOptions{})
as, err := NewServer("baz-admission-server", mgr, ServerOptions{
CertDir: "/tmp/cert",
BootstrapOptions: &BootstrapOptions{
Secret: &apitypes.NamespacedName{
Namespace: "default",
Name: "foo-admission-server-secret",
},
Service: &Service{
Namespace: "default",
Name: "foo-admission-server-service",
// Selectors should select the pods that runs this webhook server.
Selectors: map[string]string{
"app": "foo-admission-server",
},
},
},
})
if err != nil {
// handle error
}
ProTip! Use n and p to navigate between commits in a pull request.