Kubernetes强制从私有镜像仓库中拉取Docker映像。

参考代码
https://github.com/jainishshah17/tugger
关键的开了2个接口,mutate用作修改控制器、validate用作验证控制器

    http.HandleFunc("/mutate", mutateAdmissionReviewHandler)
    http.HandleFunc("/validate", validateAdmissionReviewHandler)
func mutateAdmissionReviewHandler(w http.ResponseWriter, r *http.Request) {
    log.Printf("Serving request: %s", r.URL.Path)
    //set header
    w.Header().Set("Content-Type", "application/json")
        //获取请求body
    data, err := ioutil.ReadAll(r.Body)
    if err != nil {
        log.Println(err)
        w.WriteHeader(http.StatusBadRequest)
        return
    }

    log.Println(string(data))

    ar := v1beta1.AdmissionReview{}
        //将请求的数据转化为AdmissionReview结构
    if err := json.Unmarshal(data, &ar); err != nil {
        log.Println(err)
        w.WriteHeader(http.StatusBadRequest)
        return
    }

    namespace := ar.Request.Namespace
    log.Printf("AdmissionReview Namespace is: %s", namespace)
        //初始化一个admissionResponse
    admissionResponse := v1beta1.AdmissionResponse{Allowed: false}
    patches := []patch{}
        //如果不在白名单里面,就处理
    if !contains(whitelistedNamespaces, namespace) {
        pod := v1.Pod{}
                //转化为pod对象
        if err := json.Unmarshal(ar.Request.Object.Raw, &pod); err != nil {
            log.Println(err)
            w.WriteHeader(http.StatusBadRequest)
            return
        }

        // Handle Containers
        for _, container := range pod.Spec.Containers {
                        //修改container地址
            createPatch := handleContainer(&container, dockerRegistryUrl)
            if createPatch {
                                //更新
                patches = append(patches, patch{
                    Op:    "add",
                    Path:  "/spec/containers",
                    Value: []v1.Container{container},
                })
            }
        }

        // 同理,修改init container
        for _, container := range pod.Spec.InitContainers {
            createPatch := handleContainer(&container, dockerRegistryUrl)
            if createPatch {
                patches = append(patches, patch{
                    Op:    "add",
                    Path:  "/spec/initContainers",
                    Value: []v1.Container{container},
                })
            }
        }
    } else {
        log.Printf("Namespace is %s Whitelisted", namespace)
    }
        //设置admissionResponse通过
    admissionResponse.Allowed = true
    if len(patches) > 0 {

        // Add image pull secret patche
        patches = append(patches, patch{
            Op:   "add",
            Path: "/spec/imagePullSecrets",
            Value: []v1.LocalObjectReference{
                v1.LocalObjectReference{
                    Name: registrySecretName,
                },
            },
        })
                //转成json
        patchContent, err := json.Marshal(patches)
        if err != nil {
            log.Println(err)
            w.WriteHeader(http.StatusBadRequest)
            return
        }
                //填入Response
        admissionResponse.Patch = patchContent
        pt := v1beta1.PatchTypeJSONPatch
        admissionResponse.PatchType = &pt
    }

    ar = v1beta1.AdmissionReview{
        Response: &admissionResponse,
    }

    data, err = json.Marshal(ar)
    if err != nil {
        log.Println(err)
        w.WriteHeader(http.StatusInternalServerError)
        return
    }
       返回
    w.WriteHeader(http.StatusOK)
    w.Write(data)
}
func handleContainer(container *v1.Container, dockerRegistryUrl string) bool {
    log.Println("Container Image is", container.Image)
        //不在仓库白名单
    if !containsRegisty(whitelistedRegistries, container.Image) {
        message := fmt.Sprintf("Image is not being pulled from Private Registry: %s", container.Image)
        log.Printf(message)
                //修改为自己的仓库
        newImage := dockerRegistryUrl + "/" + container.Image
        log.Printf("Changing image registry to: %s", newImage)
        SendSlackNotification("Changing image registry to: " + newImage + " from: " + container.Image)

        container.Image = newImage
        return true
    } else {
        log.Printf("Image is being pulled from Private Registry: %s", container.Image)
    }
    return false
}

你可能感兴趣的:(Kubernetes强制从私有镜像仓库中拉取Docker映像。)