In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/02 Report--
Admission Controller introduction
The three most important things Apiserver does are:
Authentication: see if it is legitimate user authorization: see what permissions the user has admission controller: a chain of calls to control or modify the request, such as whether the request is allowed.
Admission controller is very useful and an extension of K8s that is often used. Today I will introduce it at the source level and how to develop an admission controller myself.
Our application scenario is: we want to add an annotation to all the pod that need to be created, because we injected the configuration of lxcfs into pod through podpreset, but it is easy for users to forget to add it when writing yaml files, so we need to do automatic processing on apiserver.
Metadata: name: test-net annotations: initializer.kubernetes.io/lxcfs: "true" # is to add this configuration to the metadata of pod by default admission controller
There are already many admission plug-ins that are very useful by default. Here are a few of them:
Name function AlwaysPullImages adjusts all mirror policies to alwaysPull. When multi-tenant security is used, the tolerance time of DefaultStorageClass default storage type DefaultTolerationSeconds node notready:NoExecute is more useful. For example, sometimes we upgrade kubelet and hope that pod will not drift and will use DenyEscalatingExec to refuse to remotely connect to the container ExtendedResourceToleration. For example, if I have an extended resource, then I can use it to defile the node and prevent the pod that does not need that resource from coming to my machine. For example, GPULimitRanger is very useful in multi-tenant quotas. If pod does not have a quota, then I can default to a very low quota NamespaceAutoProvision. It is also very useful to create a PodPreset when the namespace of the resource does not exist. It is important to preprocess the pod and set the ResourceQuota multi-tenant quota to see whether the resource meets the configuration alwaysPullImages introduction in resource quota.
This is often enabled when multi-tenancy is used, forcing all images to be pulled, because if not, other tenants can write a yaml to start your image if they know your image name. When forced to pull, they hesitate to need image pull secret, so they cannot pull your image.
So what the admission does is change the image pull strategy to alwaysPull:
Code location:
Kubernetes/plugin/pkg/admission/alwayspullimages/admission.gofunc (a * AlwaysPullImages) Admit (attributes admission.Attributes, o admission.ObjectInterfaces) (err error) {/ / you can get all the information about the object in attibutes If shouldIgnore (attributes) {/ / check whether it is the object you follow, such as creating a configmap, then you can obviously ignore return nil} pod. Ok: = attributes.GetObject (). (* api.Pod) / / the pull policies of both initContainer and Container are changed here for I: = range pod.Spec.InitContainers {pod.Spec.InitContainers [I] .ImagePullPolicy = api.PullAlways} for I: = range pod.Spec.Containers {pod.Spec.Containers [I] .ImagePullPolicy = api.PullAlways} return nil} # also provides a verification interface See if func (a * AlwaysPullImages) Validate (attributes admission.Attributes, o admission.ObjectInterfaces) (err error) {pod, ok: = attributes.GetObject (). (* api.Pod) for I: = range pod.Spec.InitContainers {if pod.Spec.InitContainers [I] .ImagePullPolicy! = api.PullAlways {return admission.NewForbidden (attributes, field.NotSupported (field.NewPath ("spec") "initContainers") .Index (I) .Child ("imagePullPolicy"), pod.Spec.InitContainers [I] .ImagePullPolicy, [] string {string (api.PullAlways)},)}}. Return nil}
Then implement a registration function:
Func Register (plugins * admission.Plugins) {plugins.Register (PluginName, func (config io.Reader) (admission.Interface, error) {return NewAlwaysPullImages (), nil})} type AlwaysPullImages struct {* admission.Handler}
Finally, you need to register it in plugin:
Kubernetes/pkg/kubeapiserver/options/plugins.gofunc RegisterAllAdmissionPlugins (plugins * admission.Plugins) {imagepolicy.Register (plugins)...}
So the implementation of an admission is very simple, mainly to implement two interfaces.
Admission control webhooks
In many cases, we don't want to make big changes to apiserver code, so apiserver provides a way to dynamically extend admission, which is highly recommended.
There are two types:
Validating admission Webhook only verifies. For example, if a special field is detected, the request body can be modified through mutating admission webhook (patch).
More important is the AdmissionReview structure, which contains a request and a response
Request: have Object details, user information
Response: the most important thing is 1. Whether or not to allow 2. Modify (patch) type 3. Modify the value of (patch), which conforms to the json patch standard (kubectl patch)
An example of webhook server can be found here
Look at a specific example, labelpatch, which adds some label to the object's metadata.
Const (/ / specific json patch format addFirstLabelPatch string = `[{"op": "add", "path": "/ metadata/labels", "value": {"added-label": "yes"}}) `addAdditionalLabelPatch string =` [{"op": "add", "path": "/ metadata/labels/added-label" "value": "yes"}] `) / Add a label {"added-label": "yes"} to the objectfunc addLabel (ar v1beta1.AdmissionReview) * v1beta1.AdmissionResponse {obj: = struct {metav1.ObjectMeta Data map [string] string} {} raw: = ar.Request.Object.Raw err: = json.Unmarshal (raw) & obj) if err! = nil {klog.Error (err) return toAdmissionResponse (err)} reviewResponse: = v1beta1.AdmissionResponse {} reviewResponse.Allowed = true if len (obj.ObjectMeta.Labels) = 0 {reviewResponse.Patch = [] byte (addFirstLabelPatch) / / what needs most attention here is that it is modified through patch} else {reviewResponse.Patch = [] byte (addAdditionalLabelPatch) )} pt: = v1beta1.PatchTypeJSONPatch reviewResponse.PatchType = & pt return & reviewResponse}
Put this in the http handle.
Put the HTTPS service into a service so that apiserver can discover it automatically.
ApiVersion: admissionregistration.k8s.io/v1beta1kind: ValidatingWebhookConfigurationmetadata: name: webhooks:- name: rules: # it's best to know which api the hook cares about to avoid unnecessary extra overhead. -apiGroups: "" apiVersions:-v1 operations:-CREATE resources:-pods scope: "Namespaced" clientConfig: service: namespace: # webhook server namespace name: # service name caBundle: # because you need to access through https, configure apiserver with ca admissionReviewVersions:-v1beta1 timeoutSeconds: 1 summary
Adminssion control is a very important way to extend APIserver, and if you master its development, you can solve some practical problems in a more elegant way. It is a sharp weapon to develop PaaS platform based on K8s.
More wonderful: https://sealyun.com
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 238
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.