package kubectl import ( "fmt" "strings" "errors" "time" "os/exec" "encoding/json" log "oc-deploy/log_wrapper" ) type KubeObject struct { Bin string // Chemin vers le binaire Name string Kind string } type getOutput struct { Kind string `json:"kind"` Status getStatusOutput `json:"status"` } type getStatusOutput struct { Replicas int `json:"replicas"` UnavailableReplicas int `json:"unavailableReplicas"` } func (this KubeObject) Get() (map[string]any, error) { if this.Kind == "Deployment" {return this.getDeployment()} if this.Kind == "StatefulSet" {return this.getStatefulSet()} return make(map[string]any), fmt.Errorf("Kind %s inconnu", this.Kind) } func (this KubeObject) getDeployment() (map[string]any, error) { bin := this.Bin name := this.Name msg := fmt.Sprintf("%s get deployment %s -o json", bin, name) log.Log().Debug().Msg(msg) m := make(map[string]any) cmd_args := strings.Split(msg, " ") cmd := exec.Command(cmd_args[0], cmd_args[1:]...) stdout, err := cmd.CombinedOutput() if err != nil { return m, errors.New(string(stdout)) } var objmap getOutput json.Unmarshal(stdout, &objmap) kind := objmap.Kind status := objmap.Status m["name"] = name m["kind"] = kind m["replicas"] = status.Replicas m["UnavailableReplicas"] = status.UnavailableReplicas return m, nil } func (this KubeObject) getStatefulSet() (map[string]any, error) { bin := this.Bin name := this.Name msg := fmt.Sprintf("%s get statefulset %s -o json", bin, name) log.Log().Debug().Msg(msg) m := make(map[string]any) cmd_args := strings.Split(msg, " ") cmd := exec.Command(cmd_args[0], cmd_args[1:]...) stdout, err := cmd.CombinedOutput() if err != nil { return m, errors.New(string(stdout)) } var objmap getOutput json.Unmarshal(stdout, &objmap) kind := objmap.Kind status := objmap.Status m["name"] = name m["kind"] = kind m["replicas"] = status.Replicas m["UnavailableReplicas"] = status.UnavailableReplicas return m, nil } func (this KubeObject) Wait() (error) { boucle := 10 sleep := 10000 * time.Millisecond for _ = range boucle { log.Log().Debug().Msg(fmt.Sprintf("Check Deployement %s", this.Name)) m, err := this.Get() if err != nil { return err } ko := m["UnavailableReplicas"].(int) if ko == 0 { return nil } log.Log().Info().Msg(fmt.Sprintf(" >> %s (Unavailable : %d)...", this.Name, ko)) time.Sleep(sleep) } return errors.New("Temps d'attente dépassé") }