github.com/vshn/k8ify@v1.1.2-0.20240502214202-6c9ed3ef0bf4/pkg/converter/patcher.go (about)

     1  package converter
     2  
     3  import (
     4  	"strings"
     5  
     6  	apps "k8s.io/api/apps/v1"
     7  )
     8  
     9  func addAnnotations(annotations *map[string]string, addAnnotations map[string]string) {
    10  	if *annotations == nil {
    11  		*annotations = make(map[string]string)
    12  	}
    13  	for k, v := range addAnnotations {
    14  		(*annotations)[k] = v
    15  	}
    16  }
    17  
    18  func isModifiedImage(image string, modifiedImages []string) bool {
    19  	for _, modifiedImage := range modifiedImages {
    20  		// check if we have an exact match
    21  		if image == modifiedImage {
    22  			return true
    23  		}
    24  		// check if we have a suffix match. For this we must ensure that the modifiedImage string starts with a "/",
    25  		// otherwise we might get nonsensical partial matches
    26  		if !strings.HasPrefix(modifiedImage, "/") {
    27  			modifiedImage = "/" + modifiedImage
    28  		}
    29  		if strings.HasSuffix(image, modifiedImage) {
    30  			return true
    31  		}
    32  	}
    33  	return false
    34  }
    35  
    36  func PatchDeployments(deployments []apps.Deployment, modifiedImages []string, forceRestartAnnotation map[string]string) {
    37  	// don't use 'range', getting a pointer to an array element does not work with 'range'
    38  	for i := 0; i < len(deployments); i++ {
    39  		for _, container := range deployments[i].Spec.Template.Spec.Containers {
    40  			if isModifiedImage(container.Image, modifiedImages) {
    41  				addAnnotations(&deployments[i].Spec.Template.Annotations, forceRestartAnnotation)
    42  				break
    43  			}
    44  		}
    45  	}
    46  }
    47  
    48  func PatchStatefulSets(statefulSets []apps.StatefulSet, modifiedImages []string, forceRestartAnnotation map[string]string) {
    49  	// don't use 'range', getting a pointer to an array element does not work with 'range'
    50  	for i := 0; i < len(statefulSets); i++ {
    51  		for _, container := range statefulSets[i].Spec.Template.Spec.Containers {
    52  			if isModifiedImage(container.Image, modifiedImages) {
    53  				addAnnotations(&statefulSets[i].Spec.Template.Annotations, forceRestartAnnotation)
    54  				break
    55  			}
    56  		}
    57  	}
    58  }