package main
import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os/exec" "strings" "time" )
type RequestData struct { Image string `json:"image"` Deployment string `json:"deployment"` }
func main() { http.HandleFunc("/update-image", handleUpdateImage) fmt.Println("服务已启动,监听 8080 端口...") log.Fatal(http.ListenAndServe(":8080", nil)) }
func handleUpdateImage(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "仅支持 POST 请求", http.StatusMethodNotAllowed) return }
body, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "读取请求体失败", http.StatusBadRequest) return } defer r.Body.Close()
var data RequestData if err := json.Unmarshal(body, &data); err != nil { http.Error(w, "解析 JSON 失败", http.StatusBadRequest) return }
if data.Image == "" || data.Deployment == "" { http.Error(w, "请求参数不完整", http.StatusBadRequest) return }
cmd := exec.Command("kubectl", "set", "image", "deployment/"+data.Deployment, data.Deployment+"="+data.Image) output, err := cmd.CombinedOutput() fmt.Println("kubectl", "set", "image", "deployment/"+data.Deployment, data.Deployment+"="+data.Image) if err != nil { http.Error(w, fmt.Sprintf("执行 kubectl 命令失败: %s", string(output)), http.StatusInternalServerError) return }
fmt.Printf("Deployment %s 正在启动,等待 1 分钟...\n", data.Deployment) time.Sleep(60 * time.Second)
podName, err := getPodName(data.Deployment) if err != nil { http.Error(w, fmt.Sprintf("获取 Pod 名称失败: %s", err.Error()), http.StatusInternalServerError) return }
fmt.Printf("获取到的 Pod 名称: %s\n", podName)
logOutput, err := getPodLogs(podName) if err != nil { http.Error(w, fmt.Sprintf("获取 Pod 日志失败: %s", err.Error()), http.StatusInternalServerError) return }
output = append(output, []byte("\nPod Logs:\n")...) output = append(output, logOutput...)
w.WriteHeader(http.StatusOK) fmt.Fprintf(w, "镜像已更新为 %s,Deployment 名称: %s\n输出: %s", data.Image, data.Deployment, string(output)) }
func getPodName(deployment string) (string, error) { cmd := exec.Command("bash", "-c", fmt.Sprintf("kubectl get pods | grep %s | awk '{print $1}'", deployment)) output, err := cmd.CombinedOutput() fmt.Println("bash", "-c", fmt.Sprintf("kubectl get pods | grep %s | awk '{print $1}'", deployment)) if err != nil { return "", fmt.Errorf("获取 Pod 名称失败: %s", string(output)) } return strings.TrimSpace(string(output)), nil }
func getPodLogs(podName string) ([]byte, error) { cmd := exec.Command("kubectl", "logs", podName, "--tail=200") output, err := cmd.CombinedOutput() fmt.Println("kubectl", "logs", podName, "--tail=200") if err != nil { return nil, fmt.Errorf("获取 Pod 日志失败: %s", string(output)) } return output, nil }
|