...

Source file src/sigs.k8s.io/cli-utils/pkg/object/dependson/annotation.go

Documentation: sigs.k8s.io/cli-utils/pkg/object/dependson

     1  // Copyright 2021 The Kubernetes Authors.
     2  // SPDX-License-Identifier: Apache-2.0
     3  //
     4  
     5  package dependson
     6  
     7  import (
     8  	"errors"
     9  	"fmt"
    10  
    11  	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
    12  	"k8s.io/klog/v2"
    13  	"sigs.k8s.io/cli-utils/pkg/object"
    14  )
    15  
    16  const (
    17  	Annotation = "config.kubernetes.io/depends-on"
    18  )
    19  
    20  // HasAnnotation returns true if the config.kubernetes.io/depends-on annotation
    21  // is present, false if not.
    22  func HasAnnotation(u *unstructured.Unstructured) bool {
    23  	if u == nil {
    24  		return false
    25  	}
    26  	_, found := u.GetAnnotations()[Annotation]
    27  	return found
    28  }
    29  
    30  // ReadAnnotation reads the depends-on annotation and parses the the set of
    31  // object references.
    32  func ReadAnnotation(u *unstructured.Unstructured) (DependencySet, error) {
    33  	depSet := DependencySet{}
    34  	if u == nil {
    35  		return depSet, nil
    36  	}
    37  	depSetStr, found := u.GetAnnotations()[Annotation]
    38  	if !found {
    39  		return depSet, nil
    40  	}
    41  	klog.V(5).Infof("depends-on annotation found for %s/%s: %q",
    42  		u.GetNamespace(), u.GetName(), depSetStr)
    43  
    44  	depSet, err := ParseDependencySet(depSetStr)
    45  	if err != nil {
    46  		return depSet, object.InvalidAnnotationError{
    47  			Annotation: Annotation,
    48  			Cause:      err,
    49  		}
    50  	}
    51  	return depSet, nil
    52  }
    53  
    54  // WriteAnnotation updates the supplied unstructured object to add the
    55  // depends-on annotation. The value is a string of objmetas delimited by commas.
    56  // Each objmeta is formatted as "${group}/${kind}/${name}" if cluster-scoped or
    57  // "${group}/namespaces/${namespace}/${kind}/${name}" if namespace-scoped.
    58  func WriteAnnotation(obj *unstructured.Unstructured, depSet DependencySet) error {
    59  	if obj == nil {
    60  		return errors.New("object is nil")
    61  	}
    62  	if depSet.Equal(DependencySet{}) {
    63  		return errors.New("dependency set is empty")
    64  	}
    65  
    66  	depSetStr, err := FormatDependencySet(depSet)
    67  	if err != nil {
    68  		return fmt.Errorf("failed to format depends-on annotation: %w", err)
    69  	}
    70  
    71  	a := obj.GetAnnotations()
    72  	if a == nil {
    73  		a = map[string]string{}
    74  	}
    75  	a[Annotation] = depSetStr
    76  	obj.SetAnnotations(a)
    77  	return nil
    78  }
    79  

View as plain text