Kubernetes变异Webhook补丁问题

时间:2019-07-13 20:23:26

标签: go kubernetes webhooks patch

我试图绕过Kubernetes Admission Controllers,并尝试更改pod使其包含一个初始化容器和一个将安装所有容器的卷。

将创建该卷,并且init容器会挂载该卷,但是原始容器无法挂载新卷。我正在使用Golang编写webhook,并使用Json补丁来更改pod。如果有人能指出我正确的方向,那就太好了!



func serve(w http.ResponseWriter, r *http.Request) {
    body, err := ioutil.ReadAll(r.Body)

    if err != nil {
        glog.Error(err.Error())
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    if len(body) == 0 {
        glog.Error("the request body is empty")
        http.Error(w, "the request body is empty", http.StatusBadRequest)
        return
    }

    if r.Header.Get("Content-Type") != "application/json" {
        glog.Errorf("the content-type is %s, but expect application/json", r.Header.Get("Content-Type"))
        http.Error(w, "invalid content-type, expect `application/json`", http.StatusUnsupportedMediaType)
        return
    }

    request := v1beta1.AdmissionReview{}

    if _, _, err := universalDeserializer.Decode(body, nil, &request); err != nil {
        glog.Errorf("could not deserialize request: %s", err)
        w.WriteHeader(http.StatusBadRequest)
        return
    }

    if request.Request == nil {
        glog.Error("could not find admission review in the request body")
        w.WriteHeader(http.StatusBadRequest)
        return
    }

    response := v1beta1.AdmissionReview{Response: &v1beta1.AdmissionResponse{UID: request.Request.UID}}
    response.Response.Allowed = true

    var pod corev1.Pod
    if err := json.Unmarshal(request.Request.Object.Raw, &pod); err != nil {
        glog.Errorf("Could not unmarshal raw object to a pod object: %v", err)
        w.WriteHeader(http.StatusBadRequest)
        return
    }

    required, err := mutationRequired(&pod.ObjectMeta)

    if err != nil {
        glog.Error(err)
    }

    if required {
        pbytes, _ := createPatch(&pod)
        response.Response.Patch = pbytes
    }

    reviewBytes, err := json.Marshal(response)

    if err != nil {
        glog.Error(err)
        http.Error(w, fmt.Sprintf("problem marshaling json: %v", err), http.StatusInternalServerError)
    }

    if _, err := w.Write(reviewBytes); err != nil {
        glog.Errorf("error writting response back to kubernetes: %v", err)
        http.Error(w, fmt.Sprintf("could not write response: %v", err), http.StatusInternalServerError)
    }
}

func mutationRequired(m *metav1.ObjectMeta) (bool, error) {
    for _, n := range config.AllowedNamespaces {
        if m.Namespace != n {
            glog.Infof("request from pod %s is from namespace %s which is allowed", m.Name, m.Namespace)
            a := m.GetAnnotations()

            if len(a) < 1 {
                glog.Infof("pod %s has no annotations so mutation is not required", m.Name)
                return false, nil
            }

            if _, ok := a[enableKey]; ok {
                glog.Infof("annotation: %s found with value %s", enableKey, a[enableKey])
                b, err := strconv.ParseBool(a[enableKey])

                if err != nil {
                    glog.Errorf("was unable to parse the annotation value: %s", err)
                    return false, err
                }
                return b, nil
            }
            glog.Infof("pod %s has does not have the enable annotation so mutation not required", m.Name)
        }
    }
    glog.Infof("request from %s is coming from namespace %s which is not allowed", m.Name, m.Namespace)
    return false, nil
}

func addCredentialVolume() (patch patchOperation) {
    volume := corev1.Volume{
        Name: "vault-creds",
        VolumeSource: corev1.VolumeSource{
            EmptyDir: &corev1.EmptyDirVolumeSource{
                Medium: "Memory",
            },
        },
    }

    value := []corev1.Volume{volume}

    return patchOperation{
        Op:    "add",
        Path:  "/spec/volumes",
        Value: value,
    }
}
// this is the part not working 
func updateVolumeMounts(p *corev1.Pod) (patch patchOperation) {
    vmount := corev1.VolumeMount{
        Name:      "vault-creds",
        MountPath: "/creds",
        ReadOnly:  true,
    }
    for _, c := range p.Spec.Containers {
        c.VolumeMounts = append(c.VolumeMounts, vmount)
    }
    return patchOperation{
        Op:    "replace",
        Path:  "/spec/containers",
        Value: p.Spec.Containers,
    }
}

func addInitContainer(p *corev1.Pod) (patch patchOperation) {

    req := corev1.ResourceList{
        "cpu":    resource.MustParse("10m"),
        "memory": resource.MustParse("20Mi"),
    }

    lim := corev1.ResourceList{
        "cpu":    resource.MustParse("30m"),
        "memory": resource.MustParse("50Mi"),
    }

    vault := corev1.Container{
        Name:            "vault-init",
        Image:           config.Image,
        ImagePullPolicy: "Always",

        Resources: corev1.ResourceRequirements{
            Requests: req,
            Limits:   lim,
        },
        VolumeMounts: []corev1.VolumeMount{
            corev1.VolumeMount{
                Name:      "vault-creds",
                MountPath: "/creds",
            },
        },
        Command: []string{"echo", "'Hello' > /creds/cred.txt"},
    }
    p.Spec.InitContainers = append(p.Spec.InitContainers, vault)

    return patchOperation{
        Op:    "add",
        Path:  "/spec/initContainers",
        Value: p.Spec.InitContainers,
    }
}

func createPatch(p *corev1.Pod) ([]byte, error) {
    var patch []patchOperation
    patch = append(patch, addInitContainer(p))
    patch = append(patch, addCredentialVolume())
    patch = append(patch, updateVolumeMounts(p))
    return json.Marshal(patch)
}

0 个答案:

没有答案