Skip to content

Commit dd58aab

Browse files
committed
feat: add experimental clusterctl migrate command
- Experimental migration support focuses on v1beta1 to v1beta2 conversions for core Cluster API resources Signed-off-by: Satyam Bhardwaj <[email protected]>
1 parent 3f1bdf1 commit dd58aab

File tree

11 files changed

+1355
-0
lines changed

11 files changed

+1355
-0
lines changed

cmd/clusterctl/cmd/migrate.go

Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
/*
2+
Copyright 2025 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 cmd
18+
19+
import (
20+
"fmt"
21+
"io"
22+
"os"
23+
"strings"
24+
25+
"github.com/pkg/errors"
26+
"github.com/spf13/cobra"
27+
"k8s.io/apimachinery/pkg/runtime/schema"
28+
29+
clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2"
30+
"sigs.k8s.io/cluster-api/cmd/clusterctl/internal/migrate"
31+
"sigs.k8s.io/cluster-api/cmd/clusterctl/internal/scheme"
32+
)
33+
34+
type migrateOptions struct {
35+
output string
36+
toVersion string
37+
}
38+
39+
var migrateOpts = &migrateOptions{}
40+
41+
var supportedTargetVersions = []string{
42+
clusterv1.GroupVersion.Version,
43+
}
44+
45+
var migrateCmd = &cobra.Command{
46+
Use: "migrate [SOURCE]",
47+
Short: "EXPERIMENTAL: Migrate cluster.x-k8s.io resources between API versions",
48+
Long: `EXPERIMENTAL: Migrate cluster.x-k8s.io resources between API versions.
49+
50+
This command is EXPERIMENTAL and may be removed in a future release!
51+
52+
Scope and limitations:
53+
- Only cluster.x-k8s.io resources are converted
54+
- Other CAPI API groups are passed through unchanged
55+
- ClusterClass patches are not migrated
56+
- Field order may change and comments will be removed in output
57+
- API version references are dropped during conversion (except ClusterClass and external
58+
remediation references)
59+
60+
Examples:
61+
# Migrate from file to stdout
62+
clusterctl migrate cluster.yaml
63+
64+
# Migrate from stdin to stdout
65+
cat cluster.yaml | clusterctl migrate
66+
67+
# Explicitly specify target <VERSION>
68+
clusterctl migrate cluster.yaml --to-version <VERSION> --output migrated-cluster.yaml`,
69+
70+
Args: cobra.MaximumNArgs(1),
71+
RunE: func(_ *cobra.Command, args []string) error {
72+
return runMigrate(args)
73+
},
74+
}
75+
76+
func init() {
77+
migrateCmd.Flags().StringVarP(&migrateOpts.output, "output", "o", "", "Output file path (default: stdout)")
78+
migrateCmd.Flags().StringVar(&migrateOpts.toVersion, "to-version", clusterv1.GroupVersion.Version, fmt.Sprintf("Target API version for migration (supported: %s)", strings.Join(supportedTargetVersions, ", ")))
79+
80+
RootCmd.AddCommand(migrateCmd)
81+
}
82+
83+
func isSupportedTargetVersion(version string) bool {
84+
for _, v := range supportedTargetVersions {
85+
if v == version {
86+
return true
87+
}
88+
}
89+
return false
90+
}
91+
92+
func runMigrate(args []string) error {
93+
if !isSupportedTargetVersion(migrateOpts.toVersion) {
94+
return errors.Errorf("invalid --to-version value %q: supported versions are %s", migrateOpts.toVersion, strings.Join(supportedTargetVersions, ", "))
95+
}
96+
97+
fmt.Fprint(os.Stderr, "WARNING: This command is EXPERIMENTAL and may be removed in a future release!")
98+
99+
var input io.Reader
100+
var inputName string
101+
102+
if len(args) == 0 {
103+
input = os.Stdin
104+
inputName = "stdin"
105+
} else {
106+
sourceFile := args[0]
107+
// #nosec G304
108+
// command accepts user-provided file path by design
109+
file, err := os.Open(sourceFile)
110+
if err != nil {
111+
return errors.Wrapf(err, "failed to open input file %q", sourceFile)
112+
}
113+
defer file.Close()
114+
input = file
115+
inputName = sourceFile
116+
}
117+
118+
// Determine output destination
119+
var output io.Writer
120+
var outputFile *os.File
121+
var err error
122+
123+
if migrateOpts.output == "" {
124+
output = os.Stdout
125+
} else {
126+
outputFile, err = os.Create(migrateOpts.output)
127+
if err != nil {
128+
return errors.Wrapf(err, "failed to create output file %q", migrateOpts.output)
129+
}
130+
defer outputFile.Close()
131+
output = outputFile
132+
}
133+
134+
// Create migration engine components
135+
parser := migrate.NewYAMLParser(scheme.Scheme)
136+
137+
targetGV := schema.GroupVersion{
138+
Group: clusterv1.GroupVersion.Group,
139+
Version: migrateOpts.toVersion,
140+
}
141+
142+
converter, err := migrate.NewConverter(targetGV)
143+
if err != nil {
144+
return errors.Wrap(err, "failed to create converter")
145+
}
146+
147+
engine, err := migrate.NewEngine(parser, converter)
148+
if err != nil {
149+
return errors.Wrap(err, "failed to create migration engine")
150+
}
151+
152+
opts := migrate.MigrationOptions{
153+
Input: input,
154+
Output: output,
155+
Errors: os.Stderr,
156+
ToVersion: migrateOpts.toVersion,
157+
}
158+
159+
result, err := engine.Migrate(opts)
160+
if err != nil {
161+
return errors.Wrap(err, "migration failed")
162+
}
163+
164+
if result.TotalResources > 0 {
165+
fmt.Fprintf(os.Stderr, "\nMigration completed:\n")
166+
fmt.Fprintf(os.Stderr, " Total resources processed: %d\n", result.TotalResources)
167+
fmt.Fprintf(os.Stderr, " Resources converted: %d\n", result.ConvertedCount)
168+
fmt.Fprintf(os.Stderr, " Resources skipped: %d\n", result.SkippedCount)
169+
170+
if result.ErrorCount > 0 {
171+
fmt.Fprintf(os.Stderr, " Resources with errors: %d\n", result.ErrorCount)
172+
}
173+
174+
if len(result.Warnings) > 0 {
175+
fmt.Fprintf(os.Stderr, " Warnings: %d\n", len(result.Warnings))
176+
}
177+
178+
fmt.Fprintf(os.Stderr, "\nSource: %s\n", inputName)
179+
if migrateOpts.output != "" {
180+
fmt.Fprintf(os.Stderr, "Output: %s\n", migrateOpts.output)
181+
}
182+
}
183+
184+
if result.ErrorCount > 0 {
185+
return errors.Errorf("migration completed with %d errors", result.ErrorCount)
186+
}
187+
188+
return nil
189+
}
Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
/*
2+
Copyright 2025 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 migrate
18+
19+
import (
20+
"fmt"
21+
22+
"github.com/pkg/errors"
23+
"k8s.io/apimachinery/pkg/runtime"
24+
"k8s.io/apimachinery/pkg/runtime/schema"
25+
"sigs.k8s.io/controller-runtime/pkg/conversion"
26+
27+
clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2"
28+
"sigs.k8s.io/cluster-api/cmd/clusterctl/internal/scheme"
29+
)
30+
31+
// Converter handles conversion of individual CAPI resources between API versions.
32+
type Converter struct {
33+
scheme *runtime.Scheme
34+
targetGV schema.GroupVersion
35+
targetGVKMap gvkConversionMap
36+
}
37+
38+
// gvkConversionMap caches conversions from a source GroupVersionKind to its target GroupVersionKind.
39+
type gvkConversionMap map[schema.GroupVersionKind]schema.GroupVersionKind
40+
41+
// ConversionResult represents the outcome of converting a single resource.
42+
type ConversionResult struct {
43+
Object runtime.Object
44+
// Converted indicates whether the object was actually converted
45+
Converted bool
46+
Error error
47+
Warnings []string
48+
}
49+
50+
// NewConverter creates a new resource converter using the clusterctl scheme.
51+
func NewConverter(targetGV schema.GroupVersion) (*Converter, error) {
52+
return &Converter{
53+
scheme: scheme.Scheme,
54+
targetGV: targetGV,
55+
targetGVKMap: make(gvkConversionMap),
56+
}, nil
57+
}
58+
59+
// ConvertResource converts a single resource to the target version.
60+
// Returns the converted object, or the original if no conversion is needed.
61+
func (c *Converter) ConvertResource(info ResourceInfo, obj runtime.Object) ConversionResult {
62+
gvk := info.GroupVersionKind
63+
64+
if gvk.Group == clusterv1.GroupVersion.Group && gvk.Version == c.targetGV.Version {
65+
return ConversionResult{
66+
Object: obj,
67+
Converted: false,
68+
Warnings: []string{fmt.Sprintf("Resource %s/%s is already at version %s", gvk.Kind, info.Name, c.targetGV.Version)},
69+
}
70+
}
71+
72+
if gvk.Group != clusterv1.GroupVersion.Group {
73+
return ConversionResult{
74+
Object: obj,
75+
Converted: false,
76+
Warnings: []string{fmt.Sprintf("Skipping non-%s resource: %s", clusterv1.GroupVersion.Group, gvk.String())},
77+
}
78+
}
79+
80+
targetGVK, err := c.getTargetGVK(gvk)
81+
if err != nil {
82+
return ConversionResult{
83+
Object: obj,
84+
Converted: false,
85+
Error: errors.Wrapf(err, "failed to determine target GVK for %s", gvk.String()),
86+
}
87+
}
88+
89+
// Check if the object is already typed
90+
// If it's typed and implements conversion.Convertible, use the custom ConvertTo method
91+
if convertible, ok := obj.(conversion.Convertible); ok {
92+
// Create a new instance of the target type
93+
targetObj, err := c.scheme.New(targetGVK)
94+
if err != nil {
95+
return ConversionResult{
96+
Object: obj,
97+
Converted: false,
98+
Error: errors.Wrapf(err, "failed to create target object for %s", targetGVK.String()),
99+
}
100+
}
101+
102+
// Check if the target object is a Hub
103+
if hub, ok := targetObj.(conversion.Hub); ok {
104+
if err := convertible.ConvertTo(hub); err != nil {
105+
return ConversionResult{
106+
Object: obj,
107+
Converted: false,
108+
Error: errors.Wrapf(err, "failed to convert %s from %s to %s", gvk.Kind, gvk.Version, c.targetGV.Version),
109+
}
110+
}
111+
112+
// Ensure the GVK is set on the converted object
113+
hubObj := hub.(runtime.Object)
114+
hubObj.GetObjectKind().SetGroupVersionKind(targetGVK)
115+
116+
return ConversionResult{
117+
Object: hubObj,
118+
Converted: true,
119+
Error: nil,
120+
Warnings: nil,
121+
}
122+
}
123+
}
124+
125+
// Use scheme-based conversion for all remaining cases
126+
convertedObj, err := c.scheme.ConvertToVersion(obj, targetGVK.GroupVersion())
127+
if err != nil {
128+
return ConversionResult{
129+
Object: obj,
130+
Converted: false,
131+
Error: errors.Wrapf(err, "failed to convert %s from %s to %s", gvk.Kind, gvk.Version, c.targetGV.Version),
132+
}
133+
}
134+
135+
return ConversionResult{
136+
Object: convertedObj,
137+
Converted: true,
138+
Error: nil,
139+
Warnings: nil,
140+
}
141+
}
142+
143+
// getTargetGVK returns the target GroupVersionKind for a given source GVK.
144+
func (c *Converter) getTargetGVK(sourceGVK schema.GroupVersionKind) (schema.GroupVersionKind, error) {
145+
// Check cache first
146+
if targetGVK, ok := c.targetGVKMap[sourceGVK]; ok {
147+
return targetGVK, nil
148+
}
149+
150+
// Create target GVK with same kind but target version
151+
targetGVK := schema.GroupVersionKind{
152+
Group: c.targetGV.Group,
153+
Version: c.targetGV.Version,
154+
Kind: sourceGVK.Kind,
155+
}
156+
157+
// Verify the target type exists in the scheme
158+
if !c.scheme.Recognizes(targetGVK) {
159+
return schema.GroupVersionKind{}, errors.Errorf("target GVK %s not recognized by scheme", targetGVK.String())
160+
}
161+
162+
// Cache for future use
163+
c.targetGVKMap[sourceGVK] = targetGVK
164+
165+
return targetGVK, nil
166+
}

0 commit comments

Comments
 (0)