Skip to content

Commit c2050f4

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 <sbhardwaj@mirantis.com>
1 parent 3f1bdf1 commit c2050f4

File tree

11 files changed

+1424
-0
lines changed

11 files changed

+1424
-0
lines changed

cmd/clusterctl/cmd/migrate.go

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

0 commit comments

Comments
 (0)