addLabel will add a label to the node given a label key and value Specifying true for the skipExisting parameter will skip adding the label if it already exists
(nodeName string, key string, value string, skipExisting bool)
| 305 | // addLabel will add a label to the node given a label key and value |
| 306 | // Specifying true for the skipExisting parameter will skip adding the label if it already exists |
| 307 | func (n Node) addLabel(nodeName string, key string, value string, skipExisting bool) error { |
| 308 | type metadata struct { |
| 309 | Labels map[string]string `json:"labels"` |
| 310 | } |
| 311 | type patch struct { |
| 312 | Metadata metadata `json:"metadata"` |
| 313 | } |
| 314 | labels := make(map[string]string) |
| 315 | labels[key] = value |
| 316 | payload := patch{ |
| 317 | Metadata: metadata{ |
| 318 | Labels: labels, |
| 319 | }, |
| 320 | } |
| 321 | payloadBytes, err := json.Marshal(payload) |
| 322 | if err != nil { |
| 323 | return fmt.Errorf("an error occurred while marshalling the json to add a label to the node: %w", err) |
| 324 | } |
| 325 | node, err := n.fetchKubernetesNode(nodeName) |
| 326 | if err != nil { |
| 327 | return err |
| 328 | } |
| 329 | if skipExisting { |
| 330 | _, ok := node.Labels[key] |
| 331 | if ok { |
| 332 | return nil |
| 333 | } |
| 334 | } |
| 335 | if n.nthConfig.DryRun { |
| 336 | log.Info().Msgf("Would have added label (%s=%s) to node %s, but dry-run flag was set", key, value, nodeName) |
| 337 | return nil |
| 338 | } |
| 339 | _, err = n.drainHelper.Client.CoreV1().Nodes().Patch(context.TODO(), node.Name, types.StrategicMergePatchType, payloadBytes, metav1.PatchOptions{}) |
| 340 | if err != nil { |
| 341 | return fmt.Errorf("%v node patch failed when adding a label to the node: %w", node.Name, err) |
| 342 | } |
| 343 | return nil |
| 344 | } |
| 345 | |
| 346 | // removeLabel will remove a node label given a label key |
| 347 | func (n Node) removeLabel(nodeName string, key string) error { |
no test coverage detected