要解决AdmissionController阻止一个已终止的Pod被完全删除的问题,可以通过自定义Admission Webhook来进行处理。以下是一个示例的解决方案,代码使用Go语言编写:
创建一个名为admission-controller
的文件夹,并在其中创建main.go
文件。
在main.go
中导入必要的包:
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"syscall"
)
PodDeleteHandler
的结构体,用于处理Pod删除请求:type PodDeleteHandler struct{}
PodDeleteHandler
结构体的ServeHTTP
方法,用于处理请求和响应:func (h *PodDeleteHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// 读取请求的Body
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read request body", http.StatusInternalServerError)
return
}
// 解析请求的JSON数据
var request AdmissionRequest
if err := json.Unmarshal(body, &request); err != nil {
http.Error(w, "Failed to unmarshal request body", http.StatusBadRequest)
return
}
// 检查Pod是否已终止
if request.Request.Object.Metadata.DeletionTimestamp != nil {
// Pod已终止,阻止删除操作
response := AdmissionResponse{
APIVersion: "admission.k8s.io/v1",
Kind: "AdmissionReview",
Response: AdmissionReviewResponse{
Allowed: false,
Result: &Result{
Message: fmt.Sprintf("Pod %s is terminated and cannot be deleted", request.Request.Object.Metadata.Name),
},
},
}
// 返回响应的JSON数据
responseJSON, err := json.Marshal(response)
if err != nil {
http.Error(w, "Failed to marshal response body", http.StatusInternalServerError)
return
}
// 设置响应头部
w.Header().Set("Content-Type", "application/json")
// 写入响应的JSON数据
w.Write(responseJSON)
return
}
// 允许删除操作
response := AdmissionResponse{
APIVersion: "admission.k8s.io/v1",
Kind: "AdmissionReview",
Response: AdmissionReviewResponse{
Allowed: true,
},
}
// 返回响应的JSON数据
responseJSON, err := json.Marshal(response)
if err != nil {
http.Error(w, "Failed to marshal response body", http.StatusInternalServerError)
return
}
// 设置响应头部
w.Header().Set("Content-Type", "application/json")
// 写入响应的JSON数据
w.Write(responseJSON)
}
AdmissionRequest
的结构体,用于解析请求的JSON数据:type AdmissionRequest struct {
APIVersion string `json:"apiVersion"`
Kind string `json:"kind"`
Request AdmissionReview `json:"request"`
}
type AdmissionReview struct {
Object Object `json:"object"`
}
type Object struct {
Metadata Metadata `json:"metadata"`
}
type Metadata struct {
Name string `json:"name"`
DeletionTimestamp *string `json:"deletionTimestamp"`
}
AdmissionResponse
的结构体,用于生成响应的JSON数据:type AdmissionResponse struct {
APIVersion string `json:"apiVersion"`
Kind string `json:"kind"`
Response AdmissionReviewResponse `json:"response"`
}
type AdmissionReviewResponse struct {
Allowed bool `json:"allowed"`
Result *Result `json:"result,omitempty"`
}
type Result struct {
Message string `json:"message"`
}
main
函数中,创建一个http.Server
并注册PodDeleteHandler
处理器:func main() {
// 创建一个http.Server
server := &http.Server{
Addr: ":8080",
}
// 创建一个PodDeleteHandler实例
podDeleteHandler := &PodDeleteHandler{}
// 注册PodDeleteHandler处理器
http.Handle("/pod-delete", podDeleteHandler)
// 启动