-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
clone.go
291 lines (234 loc) · 8.73 KB
/
clone.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
/*
* This file is part of the KubeVirt project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright 2023 Red Hat, Inc.
*
*/
package clone
import (
"fmt"
"strings"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/rand"
clonev1alpha1 "kubevirt.io/api/clone/v1alpha1"
"kubevirt.io/client-go/kubecli"
"kubevirt.io/kubevirt/pkg/pointer"
)
const (
Clone = "clone"
NameFlag = "name"
SourceNameFlag = "source-name"
TargetNameFlag = "target-name"
SourceTypeFlag = "source-type"
TargetTypeFlag = "target-type"
LabelFilterFlag = "label-filter"
AnnotationFilterFlag = "annotation-filter"
NewMacAddressesFlag = "new-mac-address"
NewSMBiosSerialFlag = "new-smbios-serial"
supportedSourceTypes = "vm, vmsnapshot"
supportedTargetTypes = "vm"
)
type createClone struct {
name string
sourceName string
targetName string
sourceType string
targetType string
labelFilters []string
annotationFilters []string
newMacAddresses []string
newSmbiosSerial string
}
type cloneSpec clonev1alpha1.VirtualMachineCloneSpec
type optionFn func(*createClone, *cloneSpec) error
var optFns = map[string]optionFn{
NewMacAddressesFlag: withNewMacAddresses,
}
func NewCommand() *cobra.Command {
c := createClone{}
cmd := &cobra.Command{
Use: Clone,
Short: "Create a clone object manifest",
Example: c.usage(),
RunE: func(cmd *cobra.Command, _ []string) error {
return c.run(cmd)
},
}
const emptyValue = ""
const supportsMultipleFlags = "Can be provided multiple times."
cmd.Flags().StringVar(&c.name, NameFlag, emptyValue, "Specify the name of the clone. If not specified, name would be randomized.")
cmd.Flags().StringVar(&c.sourceName, SourceNameFlag, emptyValue, "Specify the clone's source name.")
cmd.Flags().StringVar(&c.targetName, TargetNameFlag, emptyValue, "Specify the clone's target name.")
cmd.Flags().StringVar(&c.sourceType, SourceTypeFlag, emptyValue, "Specify the clone's source type. Default type is VM. Supported types: "+supportedSourceTypes)
cmd.Flags().StringVar(&c.targetType, TargetTypeFlag, emptyValue, "Specify the clone's target type. Default type is VM. Supported types: "+supportedTargetTypes)
cmd.Flags().StringArrayVar(&c.labelFilters, LabelFilterFlag, nil, "Specify clone's label filters. "+supportsMultipleFlags)
cmd.Flags().StringArrayVar(&c.annotationFilters, AnnotationFilterFlag, nil, "Specify clone's annotation filters. "+supportsMultipleFlags)
cmd.Flags().StringArrayVar(&c.newMacAddresses, NewMacAddressesFlag, nil, "Specify clone's new mac addresses. For example: 'interfaceName0:newAddress0'")
cmd.Flags().StringVar(&c.newSmbiosSerial, NewSMBiosSerialFlag, emptyValue, "Specify the clone's new smbios serial")
if err := cmd.MarkFlagRequired(SourceNameFlag); err != nil {
panic(err)
}
return cmd
}
func withNewMacAddresses(c *createClone, cloneSpec *cloneSpec) error {
for _, param := range c.newMacAddresses {
splitParam := strings.Split(param, ":")
if len(splitParam) != 2 {
return fmt.Errorf("newMacAddress parameter %s is invalid: exactly one ':' is expected. For example: 'interface0:address0'", param)
}
interfaceName, newAddress := splitParam[0], splitParam[1]
if interfaceName == "" {
return fmt.Errorf("newMacAddress parameter %s has empty interface name", param)
}
if newAddress == "" {
return fmt.Errorf("newMacAddress parameter %s has empty address name", param)
}
if cloneSpec.NewMacAddresses == nil {
cloneSpec.NewMacAddresses = map[string]string{}
}
cloneSpec.NewMacAddresses[interfaceName] = newAddress
}
return nil
}
func (c *createClone) usage() string {
return ` # Create a manifest for a clone with a random name:
{{ProgramName}} create clone --source-name sourceVM --target-name targetVM
# Create a manifest for a clone with a specified name:
{{ProgramName}} create clone --name my-clone --source-name sourceVM --target-name targetVM
# Create a manifest for a clone with a randomized target name (target name is omitted):
{{ProgramName}} create clone --source-name sourceVM
# Create a manifest for a clone with specified source / target types. The default type is VM.
{{ProgramName}} create clone --source-name sourceVM --source-type vm --target-name targetVM --target-type vm
# Supported source types are vm (aliases: VM, VirtualMachine, virtualmachine) and snapshot (aliases: vmsnapshot
# VirtualMachineSnapshot, VMSnapshot). The only supported target type is vm.
# Create a manifest for a clone with a source type snapshot to a target type VM:
{{ProgramName}} create clone --source-name mySnapshot --source-type snapshot --target-name targetVM
# Create a manifest for a clone with label filters:
{{ProgramName}} create clone --source-name sourceVM --label-filter '*' --label-filter '!some/key'
# Create a manifest for a clone with annotation filters:
{{ProgramName}} create clone --source-name sourceVM --annotation-filter '*' --annotation-filter '!some/key'
# Create a manifest for a clone with new MAC addresses:
{{ProgramName}} create clone --source-name sourceVM --new-mac-address interface1:00-11-22 --new-mac-address interface2:00-11-33
# Create a manifest for a clone with new SMBIOS serial:
{{ProgramName}} create clone --source-name sourceVM --new-smbios-serial "new-serial"
# Create a manifest for a clone and use it to create a resource with kubectl
{{ProgramName}} create clone --source-name sourceVM | kubectl create -f -`
}
func (c *createClone) newClone() (*clonev1alpha1.VirtualMachineClone, error) {
clone := kubecli.NewMinimalClone(c.name)
source, err := c.typeToTypedLocalObjectReference(c.sourceType, c.sourceName, true)
if err != nil {
return nil, err
}
target, err := c.typeToTypedLocalObjectReference(c.targetType, c.targetName, false)
if err != nil {
return nil, err
}
clone.Spec = clonev1alpha1.VirtualMachineCloneSpec{
Source: source,
Target: target,
AnnotationFilters: c.annotationFilters,
LabelFilters: c.labelFilters,
NewSMBiosSerial: pointer.P(c.newSmbiosSerial),
}
return clone, nil
}
func (c *createClone) applyFlags(cmd *cobra.Command, spec *clonev1alpha1.VirtualMachineCloneSpec) error {
for flag := range optFns {
if cmd.Flags().Changed(flag) {
if err := optFns[flag](c, (*cloneSpec)(spec)); err != nil {
return err
}
}
}
return nil
}
func (c *createClone) run(cmd *cobra.Command) error {
c.setDefaults()
err := c.validateFlags()
if err != nil {
return err
}
clone, err := c.newClone()
if err != nil {
return err
}
err = c.applyFlags(cmd, &clone.Spec)
if err != nil {
return err
}
if clone.Name == "" {
clone.Name = "clone-" + rand.String(5)
}
cloneBytes, err := yaml.Marshal(clone)
if err != nil {
return err
}
cmd.Print(string(cloneBytes))
return nil
}
func (c *createClone) typeToTypedLocalObjectReference(sourceOrTargetType, sourceOrTargetName string, isSource bool) (*v1.TypedLocalObjectReference, error) {
var kind, apiGroup string
generateErr := func() error {
var sourceTargetStr string
var supportedTypes string
if isSource {
sourceTargetStr = "source"
supportedTypes = supportedSourceTypes
} else {
sourceTargetStr = "target"
supportedTypes = supportedTargetTypes
}
return fmt.Errorf("%s type %s is not supported. Supported types: %s", sourceTargetStr, sourceOrTargetType, supportedTypes)
}
switch sourceOrTargetType {
case "vm", "VM", "VirtualMachine", "virtualmachine":
kind = "VirtualMachine"
apiGroup = "kubevirt.io"
case "snapshot", "VirtualMachineSnapshot", "vmsnapshot", "VMSnapshot":
if !isSource {
return nil, generateErr()
}
kind = "VirtualMachineSnapshot"
apiGroup = "snapshot.kubevirt.io"
default:
return nil, generateErr()
}
return &v1.TypedLocalObjectReference{
Name: sourceOrTargetName,
Kind: kind,
APIGroup: &apiGroup,
}, nil
}
func (c *createClone) setDefaults() {
if c.name == "" {
c.name = "clone-" + rand.String(5)
}
const defaultType = "vm"
if c.sourceType == "" {
c.sourceType = defaultType
}
if c.targetType == "" {
c.targetType = defaultType
}
}
func (c *createClone) validateFlags() error {
if c.sourceName == "" {
return fmt.Errorf("source name must not be empty")
}
return nil
}