metallb-ip-floater/internal/kube.go
Tobias Trabelsi e11b5cd9ff
Some checks are pending
ci/woodpecker/push/woodpecker Pipeline is running
ci/woodpecker/pr/woodpecker Pipeline was successful
ci/woodpecker/pull_request_closed/woodpecker Pipeline was successful
(feat): label node that has floating ip assigned
2024-10-08 22:09:10 +02:00

95 lines
2.4 KiB
Go

package internal
import (
"context"
"errors"
"fmt"
log "github.com/sirupsen/logrus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
func generateClient() (kubernetes.Clientset, error) {
log.WithFields(log.Fields{
"Caller": "generateClient",
}).Info(fmt.Sprintf("Generating k8s client"))
config, err := rest.InClusterConfig()
if err != nil {
return kubernetes.Clientset{}, errors.New(fmt.Sprintf("Could not generate in cluster config: %s", err.Error()))
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
return kubernetes.Clientset{}, errors.New(fmt.Sprintf("Could not generate clientset: %s", err.Error()))
}
return *clientset, nil
}
func LabelNode(nodeName string) error {
client, err := generateClient()
if err != nil {
return errors.New(fmt.Sprintf("Could not generate client: %s", err.Error()))
}
log.WithFields(log.Fields{
"Caller": "LabelNode",
}).Info(fmt.Sprintf("Trying to label node %s", nodeName))
labelKey := "metallb-speaker"
labelValue := "true"
node, err := client.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})
if err != nil {
return errors.New(fmt.Sprintf("Could not find Kubernetes node: %s", err.Error()))
}
if node.Labels == nil {
node.Labels = make(map[string]string)
}
node.Labels[labelKey] = labelValue
_, err = client.CoreV1().Nodes().Update(context.TODO(), node, metav1.UpdateOptions{})
if err != nil {
return errors.New(fmt.Sprintf("Could not update node label: %s", err.Error()))
}
log.WithFields(log.Fields{
"Caller": "LabelNode",
}).Info(fmt.Sprintf("Node %s labeled with %s=%s\n", nodeName, labelKey, labelValue))
return nil
}
// TODO: handle node change
func RemoveLabelFromNode(nodeName string) error {
client, err := generateClient()
if err != nil {
return errors.New(fmt.Sprintf("Could not generate client: %s", err.Error()))
}
log.WithFields(log.Fields{
"Caller": "LabelNode",
}).Info(fmt.Sprintf("Removing Label from node %s", nodeName))
labelKey := "metallb-speaker"
node, err := client.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})
if err != nil {
panic(err.Error())
}
delete(node.Labels, labelKey)
_, err = client.CoreV1().Nodes().Update(context.TODO(), node, metav1.UpdateOptions{})
if err != nil {
panic(err.Error())
}
fmt.Printf("Label %s removed from node %s\n", labelKey, nodeName)
return nil
}