knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/apiextensions/storageversion/migrator.go (about)

     1  /*
     2  Copyright 2020 The Knative 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 storageversion
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  
    23  	apix "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
    24  	apixclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
    25  	apierrs "k8s.io/apimachinery/pkg/api/errors"
    26  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    27  	"k8s.io/apimachinery/pkg/runtime"
    28  	"k8s.io/apimachinery/pkg/runtime/schema"
    29  	"k8s.io/apimachinery/pkg/types"
    30  	"k8s.io/client-go/dynamic"
    31  	"k8s.io/client-go/tools/pager"
    32  )
    33  
    34  // Migrator will read custom resource definitions and upgrade
    35  // the associated resources to the latest storage version
    36  type Migrator struct {
    37  	dynamicClient dynamic.Interface
    38  	apixClient    apixclient.Interface
    39  }
    40  
    41  // NewMigrator will return a new Migrator
    42  func NewMigrator(d dynamic.Interface, a apixclient.Interface) *Migrator {
    43  	return &Migrator{
    44  		dynamicClient: d,
    45  		apixClient:    a,
    46  	}
    47  }
    48  
    49  // Migrate takes a group resource (ie. resource.some.group.dev) and
    50  // updates instances of the resource to the latest storage version
    51  //
    52  // This is done by listing all the resources and performing an empty patch
    53  // which triggers a migration on the K8s API server
    54  //
    55  // Finally the migrator will update the CRD's status and drop older storage
    56  // versions
    57  func (m *Migrator) Migrate(ctx context.Context, gr schema.GroupResource) error {
    58  	crdClient := m.apixClient.ApiextensionsV1().CustomResourceDefinitions()
    59  
    60  	crd, err := crdClient.Get(ctx, gr.String(), metav1.GetOptions{})
    61  	if err != nil {
    62  		return fmt.Errorf("unable to fetch crd %s - %w", gr, err)
    63  	}
    64  
    65  	version := storageVersion(crd)
    66  
    67  	if version == "" {
    68  		return fmt.Errorf("unable to determine storage version for %s", gr)
    69  	}
    70  
    71  	// don't migrate storage version if CRD has a single valid storage in its status
    72  	if len(crd.Status.StoredVersions) == 1 && crd.Status.StoredVersions[0] == version {
    73  		return nil
    74  	}
    75  
    76  	if err := m.migrateResources(ctx, gr.WithVersion(version)); err != nil {
    77  		return err
    78  	}
    79  
    80  	patch := `{"status":{"storedVersions":["` + version + `"]}}`
    81  	_, err = crdClient.Patch(ctx, crd.Name, types.StrategicMergePatchType, []byte(patch), metav1.PatchOptions{}, "status")
    82  	if err != nil {
    83  		return fmt.Errorf("unable to drop storage version definition %s - %w", gr, err)
    84  	}
    85  
    86  	return nil
    87  }
    88  
    89  func (m *Migrator) migrateResources(ctx context.Context, gvr schema.GroupVersionResource) error {
    90  	client := m.dynamicClient.Resource(gvr)
    91  
    92  	listFunc := func(ctx context.Context, opts metav1.ListOptions) (runtime.Object, error) {
    93  		return client.Namespace(metav1.NamespaceAll).List(ctx, opts)
    94  	}
    95  
    96  	onEach := func(obj runtime.Object) error {
    97  		item := obj.(metav1.Object)
    98  
    99  		_, err := client.Namespace(item.GetNamespace()).
   100  			Patch(ctx, item.GetName(), types.MergePatchType, []byte("{}"), metav1.PatchOptions{})
   101  
   102  		if err != nil && !apierrs.IsNotFound(err) {
   103  			return fmt.Errorf("unable to patch resource %s/%s (gvr: %s) - %w",
   104  				item.GetNamespace(), item.GetName(),
   105  				gvr, err)
   106  		}
   107  
   108  		return nil
   109  	}
   110  
   111  	pager := pager.New(listFunc)
   112  	return pager.EachListItem(ctx, metav1.ListOptions{}, onEach)
   113  }
   114  
   115  func storageVersion(crd *apix.CustomResourceDefinition) string {
   116  	var version string
   117  
   118  	for _, v := range crd.Spec.Versions {
   119  		if v.Storage {
   120  			version = v.Name
   121  			break
   122  		}
   123  	}
   124  
   125  	return version
   126  }