|
| 1 | +package node |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + |
| 8 | + "github.com/doitintl/kubeip/internal/types" |
| 9 | + "github.com/pkg/errors" |
| 10 | + v1 "k8s.io/api/core/v1" |
| 11 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 12 | + typesv1 "k8s.io/apimachinery/pkg/types" |
| 13 | + "k8s.io/client-go/kubernetes" |
| 14 | +) |
| 15 | + |
| 16 | +type Tainter interface { |
| 17 | + RemoveTaintKey(ctx context.Context, node *types.Node, taintKey string) (bool, error) |
| 18 | +} |
| 19 | + |
| 20 | +type tainter struct { |
| 21 | + client kubernetes.Interface |
| 22 | +} |
| 23 | + |
| 24 | +func deleteTaintsByKey(taints []v1.Taint, taintKey string) ([]v1.Taint, bool) { |
| 25 | + newTaints := []v1.Taint{} |
| 26 | + didDelete := false |
| 27 | + |
| 28 | + for i := range taints { |
| 29 | + if taintKey == taints[i].Key { |
| 30 | + didDelete = true |
| 31 | + continue |
| 32 | + } |
| 33 | + newTaints = append(newTaints, taints[i]) |
| 34 | + } |
| 35 | + |
| 36 | + return newTaints, didDelete |
| 37 | +} |
| 38 | + |
| 39 | +func NewTainter(client kubernetes.Interface) Tainter { |
| 40 | + return &tainter{ |
| 41 | + client: client, |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +func (t *tainter) RemoveTaintKey(ctx context.Context, node *types.Node, taintKey string) (bool, error) { |
| 46 | + // get node object from API server |
| 47 | + n, err := t.client.CoreV1().Nodes().Get(ctx, node.Name, metav1.GetOptions{}) |
| 48 | + if err != nil { |
| 49 | + return false, errors.Wrap(err, "failed to get kubernetes node") |
| 50 | + } |
| 51 | + |
| 52 | + // Remove taint from the node representation |
| 53 | + newTaints, didDelete := deleteTaintsByKey(n.Spec.Taints, taintKey) |
| 54 | + if !didDelete { |
| 55 | + return false, nil |
| 56 | + } |
| 57 | + |
| 58 | + // Marshal the remaining taints of the node into json format for patching. |
| 59 | + // The remaining taints may be empty, and that will result in an empty json array "[]" |
| 60 | + newTaintsMarshaled, err := json.Marshal(newTaints) |
| 61 | + if err != nil { |
| 62 | + return false, errors.Wrap(err, "failed to marshal new taints") |
| 63 | + } |
| 64 | + |
| 65 | + // Patch the node with only the remaining taints |
| 66 | + patch := fmt.Sprintf(`{"spec":{"taints":%v}}`, string(newTaintsMarshaled)) |
| 67 | + _, err = t.client.CoreV1().Nodes().Patch(ctx, node.Name, typesv1.MergePatchType, []byte(patch), metav1.PatchOptions{}) |
| 68 | + if err != nil { |
| 69 | + return false, errors.Wrap(err, "failed to patch node taints") |
| 70 | + } |
| 71 | + |
| 72 | + return true, nil |
| 73 | +} |
0 commit comments