|
| 1 | +package utils |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "log" |
| 8 | + "os/exec" |
| 9 | + |
| 10 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 11 | + "k8s.io/apimachinery/pkg/types" |
| 12 | + "k8s.io/client-go/kubernetes" |
| 13 | + "k8s.io/client-go/rest" |
| 14 | +) |
| 15 | + |
| 16 | +type raftStatus struct { |
| 17 | + Leader string `json:"leader"` |
| 18 | + State string `json:"state"` |
| 19 | + Nodes []string `json:"nodes"` |
| 20 | +} |
| 21 | + |
| 22 | +type MySQLNode struct { |
| 23 | + PodName string |
| 24 | + Namespace string |
| 25 | + Role string |
| 26 | +} |
| 27 | + |
| 28 | +func GetClientSet() (*kubernetes.Clientset, error) { |
| 29 | + // Creates the in-cluster config |
| 30 | + config, err := rest.InClusterConfig() |
| 31 | + if err != nil { |
| 32 | + return nil, fmt.Errorf("failed to create in-cluster config: %v", err) |
| 33 | + } |
| 34 | + // Creates the clientset |
| 35 | + clientset, err := kubernetes.NewForConfig(config) |
| 36 | + if err != nil { |
| 37 | + return nil, fmt.Errorf("failed to create clientset: %v", err) |
| 38 | + } |
| 39 | + return clientset, nil |
| 40 | +} |
| 41 | + |
| 42 | +func PatchRoleLabelTo(n MySQLNode) error { |
| 43 | + // Creates the clientset |
| 44 | + clientset, err := GetClientSet() |
| 45 | + if err != nil { |
| 46 | + return fmt.Errorf("failed to create clientset: %v", err) |
| 47 | + } |
| 48 | + patch := fmt.Sprintf(`{"metadata":{"labels":{"role":"%s"}}}`, n.Role) |
| 49 | + _, err = clientset.CoreV1().Pods(n.Namespace).Patch(context.TODO(), n.PodName, types.MergePatchType, []byte(patch), metav1.PatchOptions{}) |
| 50 | + if err != nil { |
| 51 | + return fmt.Errorf("failed to patch pod role label: %v", err) |
| 52 | + } |
| 53 | + return nil |
| 54 | +} |
| 55 | + |
| 56 | +func XenonPingMyself() error { |
| 57 | + args := []string{"xenon", "ping"} |
| 58 | + cmd := exec.Command("xenoncli", args...) |
| 59 | + if err := cmd.Run(); err != nil { |
| 60 | + return fmt.Errorf("failed to exec xenoncli xenon ping: %v", err) |
| 61 | + } |
| 62 | + return nil |
| 63 | +} |
| 64 | + |
| 65 | +func GetRaftStatus() *raftStatus { |
| 66 | + args := []string{"raft", "status"} |
| 67 | + cmd := exec.Command("xenoncli", args...) |
| 68 | + res, err := cmd.Output() |
| 69 | + if err != nil { |
| 70 | + log.Fatalf("failed to exec xenoncli raft status: %v", err) |
| 71 | + } |
| 72 | + raftStatus := raftStatus{} |
| 73 | + if err := json.Unmarshal(res, &raftStatus); err != nil { |
| 74 | + log.Fatalf("failed to unmarshal raft status: %v", err) |
| 75 | + } |
| 76 | + return &raftStatus |
| 77 | +} |
| 78 | + |
| 79 | +func GetRole() string { |
| 80 | + return GetRaftStatus().State |
| 81 | +} |
0 commit comments