|
| 1 | +package kubernetes |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "log" |
| 8 | + "time" |
| 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/tools/clientcmd" |
| 14 | +) |
| 15 | + |
| 16 | +type patchStringValue struct { |
| 17 | + Op string `json:"op"` |
| 18 | + Path string `json:"path"` |
| 19 | + Value string `json:"value"` |
| 20 | +} |
| 21 | + |
| 22 | +type LabelNodes struct { |
| 23 | + KubeConfigFilePath string |
| 24 | + Labels map[string]string |
| 25 | +} |
| 26 | + |
| 27 | +func (l *LabelNodes) Prevalidate() error { |
| 28 | + return nil |
| 29 | +} |
| 30 | + |
| 31 | +func (l *LabelNodes) Run() error { |
| 32 | + config, err := clientcmd.BuildConfigFromFlags("", l.KubeConfigFilePath) |
| 33 | + if err != nil { |
| 34 | + return fmt.Errorf("error building kubeconfig: %w", err) |
| 35 | + } |
| 36 | + |
| 37 | + clientset, err := kubernetes.NewForConfig(config) |
| 38 | + if err != nil { |
| 39 | + return fmt.Errorf("error creating Kubernetes client: %w", err) |
| 40 | + } |
| 41 | + |
| 42 | + ctx, cancel := context.WithTimeout(context.Background(), defaultTimeoutSeconds*time.Second) |
| 43 | + defer cancel() |
| 44 | + |
| 45 | + nodes, err := clientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{}) |
| 46 | + if err != nil { |
| 47 | + return fmt.Errorf("failed to get nodes: %w", err) |
| 48 | + } |
| 49 | + |
| 50 | + patch := []patchStringValue{} |
| 51 | + for k, v := range l.Labels { |
| 52 | + patch = append(patch, patchStringValue{ |
| 53 | + Op: "add", |
| 54 | + Path: "/metadata/labels/" + k, |
| 55 | + Value: v, |
| 56 | + }) |
| 57 | + } |
| 58 | + b, err := json.Marshal(patch) |
| 59 | + if err != nil { |
| 60 | + return fmt.Errorf("failed to marshal patch: %w", err) |
| 61 | + } |
| 62 | + |
| 63 | + for i := range nodes.Items { |
| 64 | + log.Println("Labeling node", nodes.Items[i].Name) |
| 65 | + _, err = clientset.CoreV1().Nodes().Patch(ctx, nodes.Items[i].Name, types.JSONPatchType, b, metav1.PatchOptions{}) |
| 66 | + if err != nil { |
| 67 | + return fmt.Errorf("failed to patch pod: %w", err) |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + return nil |
| 72 | +} |
| 73 | + |
| 74 | +func (l *LabelNodes) Stop() error { |
| 75 | + return nil |
| 76 | +} |
0 commit comments