简体   繁体   English

如何为 kubernetes 录取 controller 写回复

[英]How to write a response for kubernetes admission controller

I am trying to write a simple admission controller for pod naming (validation) but for some reason I am generating a wrong response.我正在尝试为 pod 命名(验证)编写一个简单的准入 controller,但由于某种原因,我产生了错误的响应。

Here is my code:这是我的代码:

package main

import (
      "fmt" 
      "encoding/json"
      "io/ioutil"
      "net/http"
      "github.com/golang/glog"

      // for Kubernetes 
      "k8s.io/api/admission/v1beta1"
      "k8s.io/api/core/v1"
      metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
      "regexp"
)

type myValidServerhandler struct {

}
// this is the handler fuction from the HTTP server 
func (gs *myValidServerhandler) serve(w http.ResponseWriter, r *http.Request) {
    var Body []byte
    if r.Body != nil {
        if data , err := ioutil.ReadAll(r.Body); err == nil {
            Body = data
        }
    }

    if len(Body) == 0 {
        glog.Error("Unable to retrive Body from API")
        http.Error(w,"Empty Body", http.StatusBadRequest)
        return
    }

    glog.Info("Received Request")
// this is where I make sure the request is for the validation prefix
    if r.URL.Path != "/validate" {
         glog.Error("Not a Validataion String")
        http.Error(w,"Not a Validataion String", http.StatusBadRequest)
        return
    }
// in this part the function takes the AdmissionReivew and make sure in is in the right
// JSON format 
    arRequest := &v1beta1.AdmissionReview{}
    if err := json.Unmarshal(Body, arRequest); err != nil {
        glog.Error("incorrect Body")
        http.Error(w, "incorrect Body", http.StatusBadRequest)
        return
    }

    raw := arRequest.Request.Object.Raw
    pod := v1.Pod{}
    if err := json.Unmarshal(raw, &pod); err != nil {
        glog.Error("Error Deserializing Pod")
        return
    }
// this is where I make sure the pod name contains the kuku string
    podnamingReg := regexp.MustCompile(`kuku`)
    if podnamingReg.MatchString(string(pod.Name)) {
        return
    } else {
        glog.Error("the pod does not contain \"kuku\"")
        http.Error(w, "the pod does not contain \"kuku\"", http.StatusBadRequest)
        return
    }

// I think the main problem is with this part of the code because the 
// error from the events I getting in the Kubernetes namespace is that 
// I am sending 200 without a body response

    arResponse := v1beta1.AdmissionReview{
        Response: &v1beta1.AdmissionResponse{
            Result:  &metav1.Status{},
            Allowed: true,
        },
    }
// generating the JSON response after the validation 
    resp, err := json.Marshal(arResponse)
    if err != nil {
        glog.Error("Can't encode response:", err)
        http.Error(w, fmt.Sprintf("couldn't encode response: %v", err), http.StatusInternalServerError)
    }

    glog.Infof("Ready to write  response ...")
    if _, err := w.Write(resp); err != nil {
        glog.Error("Can't write response", err)
        http.Error(w, fmt.Sprintf("cloud not write response: %v", err), http.StatusInternalServerError)
    }
}

The code is working as expected except for a positive output (where the pod name meets the criteria) there is another file with a main just grabbing the TLS files and starting the HTTP service.代码按预期工作,除了肯定的 output(其中 pod 名称符合标准)之外,还有另一个文件,其主要内容只是抓取 TLS 文件并启动 HTTP 服务。

so after a few digging I found what was wrong with my code所以经过几次挖掘后,我发现我的代码有什么问题

first this part首先这部分

  if podnamingReg.MatchString(string(pod.Name)) {
    return
  } else {
    glog.Error("the pod does not contain \"kuku\"")
    http.Error(w, "the pod does not contain \"kuku\"", http.StatusBadRequest)
    return
  }

by writing "return" twice I discarded the rest of the code and more so I haven't attached the request UID to the response UID and because I am using the v1 and not the v1beta1 I needed to adding the APIVersion in the response so the rest of the code looks like:通过写“return”两次,我丢弃了代码的 rest 等等,所以我没有将请求 UID 附加到响应 UID,因为我使用的是 v1 而不是 v1beta1,所以我需要在响应中添加 APIVersion 所以rest 的代码如下所示:

   arResponse := v1beta1.AdmissionReview{
        Response: &v1beta1.AdmissionResponse{
            Result:  &metav1.Status{},
            Allowed: false,
        },
    }

    podnamingReg := regexp.MustCompile(`kuku`)

    if podnamingReg.MatchString(string(pod.Name)) {
        fmt.Printf("the pod %s is up to the name standard", pod.Name)
        arResponse.Response.Allowed = true  
    } 

    arResponse.APIVersion = "admission.k8s.io/v1"
    arResponse.Kind = arRequest.Kind
    arResponse.Response.UID = arRequest.Request.UID

so I needed to add the 2 parts and make sure that in case the pod name is not up to standard then I need to return the right response所以我需要添加 2 个部分并确保如果 pod 名称不符合标准,那么我需要返回正确的响应

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在路由 controller 外的 Express 中访问响应 - How access Response in Express outside Route controller 如何从另一个控制器中获取控制器的响应? - How to get a controller's response from within another controller? 如何将 curl 命令的 json 响应写入文件 - how to write json response of curl command to file 如何在给定JSON响应的改造2.0中编写响应类 - How to write response class in retrofit 2.0 given JSON response Rails 5如何为会话创建动作编写api控制器功能测试 - Rails 5 how to write api controller functional test for session create action 如何使用 do.net CLI 创建具有读/写操作的 api controller - How to create an api controller with read/write actions with dotnet CLI 作为REST API的响应返回时,如何将一个对象写入另一个对象? - How to write an object into another while returning as a response of REST API? 如何将带有单独 API URL 响应的 ajax 返回给 YII2 中的控制器? - How to return ajax with separate API URL response to controller in YII2? 如何编写Rails Controller以模拟更新twitter-API之类的? - How to write rails Controller to simulate update twitter-API like? 如何编写 Splunk 查询来计算多个端点的响应代码 - How to write a Splunk query to count response codes of multiple endpoints
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM