github.com/percona/percona-xtradb-cluster-operator@v1.14.0/pkg/k8s/annotation.go (about)

     1  package k8s
     2  
     3  import (
     4  	"context"
     5  
     6  	"k8s.io/client-go/util/retry"
     7  	"sigs.k8s.io/controller-runtime/pkg/client"
     8  )
     9  
    10  // AnnotateObject adds the specified annotations to the object
    11  func AnnotateObject(ctx context.Context, c client.Client, obj client.Object, annotations map[string]string) error {
    12  	return retry.RetryOnConflict(retry.DefaultRetry, func() error {
    13  		_obj := obj.DeepCopyObject().(client.Object)
    14  		err := c.Get(ctx, client.ObjectKeyFromObject(obj), _obj)
    15  		if err != nil {
    16  			return err
    17  		}
    18  
    19  		a := _obj.GetAnnotations()
    20  		if a == nil {
    21  			a = make(map[string]string)
    22  		}
    23  
    24  		for k, v := range annotations {
    25  			a[k] = v
    26  		}
    27  		_obj.SetAnnotations(a)
    28  
    29  		return c.Patch(ctx, _obj, client.MergeFrom(obj))
    30  	})
    31  }
    32  
    33  // DeannotateObject removes the specified annotation from the object
    34  func DeannotateObject(ctx context.Context, c client.Client, obj client.Object, annotation string) error {
    35  	return retry.RetryOnConflict(retry.DefaultRetry, func() error {
    36  		_obj := obj.DeepCopyObject().(client.Object)
    37  		err := c.Get(ctx, client.ObjectKeyFromObject(obj), _obj)
    38  		if err != nil {
    39  			return err
    40  		}
    41  
    42  		a := _obj.GetAnnotations()
    43  		if a == nil {
    44  			a = make(map[string]string)
    45  		}
    46  
    47  		delete(a, annotation)
    48  		_obj.SetAnnotations(a)
    49  
    50  		return c.Patch(ctx, _obj, client.MergeFrom(obj))
    51  	})
    52  }