sigs.k8s.io/cluster-api@v1.7.1/internal/controllers/topology/cluster/patches/patch.go (about)

     1  /*
     2  Copyright 2021 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package patches
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"encoding/json"
    23  	"strings"
    24  
    25  	jsonpatch "github.com/evanphx/json-patch/v5"
    26  	"github.com/pkg/errors"
    27  	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
    28  	"k8s.io/apimachinery/pkg/runtime"
    29  
    30  	"sigs.k8s.io/cluster-api/internal/contract"
    31  	tlog "sigs.k8s.io/cluster-api/internal/log"
    32  )
    33  
    34  // PatchOption represents an option for the patchObject and patchTemplate funcs.
    35  type PatchOption interface {
    36  	// ApplyToHelper applies configuration to the given options.
    37  	ApplyToHelper(*PatchOptions)
    38  }
    39  
    40  // PatchOptions contains options for patchObject and patchTemplate.
    41  type PatchOptions struct {
    42  	preserveFields []contract.Path
    43  }
    44  
    45  // ApplyOptions applies the given patch options.
    46  func (o *PatchOptions) ApplyOptions(opts []PatchOption) {
    47  	for _, opt := range opts {
    48  		opt.ApplyToHelper(o)
    49  	}
    50  }
    51  
    52  // PreserveFields instructs the patch func to preserve fields.
    53  type PreserveFields []contract.Path
    54  
    55  // ApplyToHelper applies this configuration to the given patch options.
    56  func (i PreserveFields) ApplyToHelper(opts *PatchOptions) {
    57  	opts.preserveFields = i
    58  }
    59  
    60  // patchObject overwrites spec in object with spec.template.spec of modifiedObject,
    61  // while preserving the configured fields.
    62  // For example, ControlPlane.spec will be overwritten with the patched
    63  // ControlPlaneTemplate.spec.template.spec but preserving spec.version and spec.replicas
    64  // which are previously set by the topology controller and shouldn't be overwritten.
    65  func patchObject(ctx context.Context, object, modifiedObject *unstructured.Unstructured, opts ...PatchOption) error {
    66  	return patchUnstructured(ctx, object, modifiedObject, "spec.template.spec", "spec", opts...)
    67  }
    68  
    69  // patchTemplate overwrites spec.template.spec in template with spec.template.spec of modifiedTemplate,
    70  // while preserving the configured fields.
    71  // For example, it's possible to patch BootstrapTemplate.spec.template.spec with a patched
    72  // BootstrapTemplate.spec.template.spec while preserving fields configured via opts.fieldsToPreserve.
    73  func patchTemplate(ctx context.Context, template, modifiedTemplate *unstructured.Unstructured, opts ...PatchOption) error {
    74  	return patchUnstructured(ctx, template, modifiedTemplate, "spec.template.spec", "spec.template.spec", opts...)
    75  }
    76  
    77  // patchUnstructured overwrites original.destSpecPath with modified.srcSpecPath.
    78  // NOTE: Original won't be changed at all, if there is no diff.
    79  func patchUnstructured(ctx context.Context, original, modified *unstructured.Unstructured, srcSpecPath, destSpecPath string, opts ...PatchOption) error {
    80  	log := tlog.LoggerFrom(ctx)
    81  
    82  	patchOptions := &PatchOptions{}
    83  	patchOptions.ApplyOptions(opts)
    84  
    85  	// Create a copy to store the result of the patching temporarily.
    86  	patched := original.DeepCopy()
    87  
    88  	// copySpec overwrites patched.destSpecPath with modified.srcSpecPath.
    89  	if err := copySpec(copySpecInput{
    90  		src:              modified,
    91  		dest:             patched,
    92  		srcSpecPath:      srcSpecPath,
    93  		destSpecPath:     destSpecPath,
    94  		fieldsToPreserve: patchOptions.preserveFields,
    95  	}); err != nil {
    96  		return errors.Wrapf(err, "failed to apply patch to %s", tlog.KObj{Obj: original})
    97  	}
    98  
    99  	// Calculate diff.
   100  	diff, err := calculateDiff(original, patched)
   101  	if err != nil {
   102  		return errors.Wrapf(err, "failed to apply patch to %s: failed to calculate diff", tlog.KObj{Obj: original})
   103  	}
   104  
   105  	// Return if there is no diff.
   106  	if bytes.Equal(diff, []byte("{}")) {
   107  		return nil
   108  	}
   109  
   110  	// Log the delta between the object before and after applying the accumulated patches.
   111  	log.V(4).WithObject(original).Infof("Applying accumulated patches to desired state: %s", string(diff))
   112  
   113  	// Overwrite original.
   114  	*original = *patched
   115  	return nil
   116  }
   117  
   118  // calculateDiff calculates the diff between two Unstructured objects.
   119  func calculateDiff(original, patched *unstructured.Unstructured) ([]byte, error) {
   120  	originalJSON, err := json.Marshal(original.Object["spec"])
   121  	if err != nil {
   122  		return nil, errors.Errorf("failed to marshal original object")
   123  	}
   124  
   125  	patchedJSON, err := json.Marshal(patched.Object["spec"])
   126  	if err != nil {
   127  		return nil, errors.Errorf("failed to marshal patched object")
   128  	}
   129  
   130  	diff, err := jsonpatch.CreateMergePatch(originalJSON, patchedJSON)
   131  	if err != nil {
   132  		return nil, errors.Errorf("failed to diff objects")
   133  	}
   134  	return diff, nil
   135  }
   136  
   137  // patchTemplateSpec overwrites spec in templateJSON with spec of patchedTemplateBytes.
   138  func patchTemplateSpec(templateJSON *runtime.RawExtension, patchedTemplateBytes []byte) error {
   139  	// Convert templates to Unstructured.
   140  	template, err := bytesToUnstructured(templateJSON.Raw)
   141  	if err != nil {
   142  		return errors.Wrap(err, "failed to convert template to Unstructured")
   143  	}
   144  	patchedTemplate, err := bytesToUnstructured(patchedTemplateBytes)
   145  	if err != nil {
   146  		return errors.Wrap(err, "failed to convert patched template to Unstructured")
   147  	}
   148  
   149  	// Copy spec from patchedTemplate to template.
   150  	if err := copySpec(copySpecInput{
   151  		src:          patchedTemplate,
   152  		dest:         template,
   153  		srcSpecPath:  "spec",
   154  		destSpecPath: "spec",
   155  	}); err != nil {
   156  		return errors.Wrap(err, "failed to apply patch to template")
   157  	}
   158  
   159  	// Marshal template and store it in templateJSON.
   160  	templateBytes, err := template.MarshalJSON()
   161  	if err != nil {
   162  		return errors.Wrapf(err, "failed to marshal patched template")
   163  	}
   164  	templateJSON.Object = template
   165  	templateJSON.Raw = templateBytes
   166  	return nil
   167  }
   168  
   169  type copySpecInput struct {
   170  	src              *unstructured.Unstructured
   171  	dest             *unstructured.Unstructured
   172  	srcSpecPath      string
   173  	destSpecPath     string
   174  	fieldsToPreserve []contract.Path
   175  }
   176  
   177  // copySpec copies a field from a srcSpecPath in src to a destSpecPath in dest,
   178  // while preserving fieldsToPreserve.
   179  func copySpec(in copySpecInput) error {
   180  	// Backup fields that should be preserved from dest.
   181  	preservedFields := map[string]interface{}{}
   182  	for _, field := range in.fieldsToPreserve {
   183  		value, found, err := unstructured.NestedFieldNoCopy(in.dest.Object, field...)
   184  		if !found {
   185  			// Continue if the field does not exist in src. fieldsToPreserve don't have to exist.
   186  			continue
   187  		} else if err != nil {
   188  			return errors.Wrapf(err, "failed to get field %q from %s", strings.Join(field, "."), tlog.KObj{Obj: in.dest})
   189  		}
   190  		preservedFields[strings.Join(field, ".")] = value
   191  	}
   192  
   193  	// Get spec from src.
   194  	srcSpec, found, err := unstructured.NestedFieldNoCopy(in.src.Object, strings.Split(in.srcSpecPath, ".")...)
   195  	if !found {
   196  		return errors.Errorf("missing field %q in %s", in.srcSpecPath, tlog.KObj{Obj: in.src})
   197  	} else if err != nil {
   198  		return errors.Wrapf(err, "failed to get field %q from %s", in.srcSpecPath, tlog.KObj{Obj: in.src})
   199  	}
   200  
   201  	// Set spec in dest.
   202  	if err := unstructured.SetNestedField(in.dest.Object, srcSpec, strings.Split(in.destSpecPath, ".")...); err != nil {
   203  		return errors.Wrapf(err, "failed to set field %q on %s", in.destSpecPath, tlog.KObj{Obj: in.dest})
   204  	}
   205  
   206  	// Restore preserved fields.
   207  	for path, value := range preservedFields {
   208  		if err := unstructured.SetNestedField(in.dest.Object, value, strings.Split(path, ".")...); err != nil {
   209  			return errors.Wrapf(err, "failed to set field %q on %s", path, tlog.KObj{Obj: in.dest})
   210  		}
   211  	}
   212  	return nil
   213  }