-
Notifications
You must be signed in to change notification settings - Fork 226
/
migratecmd.go
349 lines (331 loc) · 11.2 KB
/
migratecmd.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
// Copyright 2020 Google LLC.
// SPDX-License-Identifier: Apache-2.0
package commands
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"github.com/GoogleContainerTools/kpt/internal/cmdliveinit"
"github.com/GoogleContainerTools/kpt/pkg/live"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/klog"
cmdutil "k8s.io/kubectl/pkg/cmd/util"
"k8s.io/kubectl/pkg/util/i18n"
"sigs.k8s.io/cli-utils/pkg/common"
"sigs.k8s.io/cli-utils/pkg/config"
"sigs.k8s.io/cli-utils/pkg/inventory"
"sigs.k8s.io/cli-utils/pkg/manifestreader"
"sigs.k8s.io/cli-utils/pkg/object"
"sigs.k8s.io/cli-utils/pkg/provider"
)
// MigrateRunner encapsulates fields for the kpt migrate command.
type MigrateRunner struct {
Command *cobra.Command
ioStreams genericclioptions.IOStreams
dir string
dryRun bool
initOptions *cmdliveinit.KptInitOptions
cmProvider provider.Provider
rgProvider provider.Provider
cmLoader manifestreader.ManifestLoader
rgLoader manifestreader.ManifestLoader
}
// NewMigrateRunner returns a pointer to an initial MigrateRunner structure.
func GetMigrateRunner(cmProvider provider.Provider, rgProvider provider.Provider,
cmLoader manifestreader.ManifestLoader, rgLoader manifestreader.ManifestLoader,
ioStreams genericclioptions.IOStreams) *MigrateRunner {
r := &MigrateRunner{
ioStreams: ioStreams,
dryRun: false,
initOptions: cmdliveinit.NewKptInitOptions(cmProvider.Factory(), ioStreams),
cmProvider: cmProvider,
rgProvider: rgProvider,
cmLoader: cmLoader,
rgLoader: rgLoader,
dir: "",
}
cmd := &cobra.Command{
Use: "migrate [DIR | -]",
DisableFlagsInUseLine: true,
Short: i18n.T("Migrate inventory from ConfigMap to ResourceGroup custom resource"),
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
// default to current working directory
args = append(args, ".")
}
fmt.Fprint(ioStreams.Out, "inventory migration...\n")
if err := r.Run(ioStreams.In, args); err != nil {
fmt.Fprint(ioStreams.Out, "failed\n")
fmt.Fprint(ioStreams.Out, "inventory migration...failed\n")
return err
}
fmt.Fprint(ioStreams.Out, "inventory migration...success\n")
return nil
},
}
cmd.Flags().StringVar(&r.initOptions.Name, "name", "", "Inventory object name")
cmd.Flags().BoolVar(&r.initOptions.Force, "force", false, "Set inventory values even if already set in Kptfile")
cmd.Flags().BoolVar(&r.dryRun, "dry-run", false, "Do not actually migrate, but show steps")
r.Command = cmd
return r
}
// NewCmdMigrate returns the cobra command for the migrate command.
func NewCmdMigrate(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *cobra.Command {
configMapProvider := provider.NewProvider(f)
resourceGroupProvider := live.NewResourceGroupProvider(f)
cmLoader := manifestreader.NewManifestLoader(f)
rgLoader := live.NewResourceGroupManifestLoader(f)
return GetMigrateRunner(configMapProvider, resourceGroupProvider, cmLoader, rgLoader, ioStreams).Command
}
// Run executes the migration from the ConfigMap based inventory to the ResourceGroup
// based inventory.
func (mr *MigrateRunner) Run(reader io.Reader, args []string) error {
// Validate the number of arguments.
if len(args) > 1 {
return fmt.Errorf("too many arguments; migrate requires one directory argument (or stdin)")
}
// Validate argument is a directory.
if len(args) == 1 {
var err error
mr.dir, err = config.NormalizeDir(args[0])
if err != nil {
return err
}
}
// Store the stdin bytes if necessary so they can be used twice.
var stdinBytes []byte
var err error
if len(args) == 0 {
stdinBytes, err = ioutil.ReadAll(reader)
if err != nil {
return err
}
if len(stdinBytes) == 0 {
return fmt.Errorf("no arguments means stdin has data; missing bytes on stdin")
}
}
// Apply the ResourceGroup CRD to the cluster, ignoring if it already exists.
if err := mr.applyCRD(); err != nil {
return err
}
// Retrieve the current ConfigMap inventory objects.
cmInvObj, err := mr.retrieveConfigMapInv(bytes.NewReader(stdinBytes), args)
if err != nil {
if _, ok := err.(inventory.NoInventoryObjError); ok {
// No ConfigMap inventory means the migration has already run before.
klog.V(4).Infoln("swallowing no ConfigMap inventory error")
return nil
}
klog.V(4).Infof("error retrieving ConfigMap inventory object: %s", err)
return err
}
cmInventoryID := cmInvObj.ID()
klog.V(4).Infof("previous inventoryID: %s", cmInventoryID)
// Update the Kptfile with the resource group values (e.g. namespace, name, id).
if err := mr.updateKptfile(args, cmInventoryID); err != nil {
return err
}
cmObjs, err := mr.retrieveInvObjs(cmInvObj)
if err != nil {
return err
}
if len(cmObjs) > 0 {
// Migrate the ConfigMap inventory objects to a ResourceGroup custom resource.
if err = mr.migrateObjs(cmObjs, bytes.NewReader(stdinBytes), args); err != nil {
return err
}
// Delete the old ConfigMap inventory object.
if err = mr.deleteConfigMapInv(cmInvObj); err != nil {
return err
}
}
return mr.deleteConfigMapFile()
}
// applyCRD applies the ResourceGroup custom resource definition, returning an
// error if one occurred. Ignores "AlreadyExists" error. Uses the definition
// stored in the "rgCrd" variable.
func (mr *MigrateRunner) applyCRD() error {
fmt.Fprint(mr.ioStreams.Out, " ensuring ResourceGroup CRD exists in cluster...")
// Simply return early if this is a dry run
if mr.dryRun {
fmt.Fprintln(mr.ioStreams.Out, "success")
return nil
}
// Install the ResourceGroup CRD to the cluster.
err := live.InstallResourceGroupCRD(mr.cmProvider.Factory())
if err == nil {
fmt.Fprintln(mr.ioStreams.Out, "success")
} else {
fmt.Fprintln(mr.ioStreams.Out, "failed")
}
return err
}
// updateKptfile installs the "inventory" fields in the Kptfile.
func (mr *MigrateRunner) updateKptfile(args []string, prevID string) error {
fmt.Fprint(mr.ioStreams.Out, " updating Kptfile inventory values...")
if !mr.dryRun {
// Set inventory ID from previous inventory object.
mr.initOptions.InventoryID = prevID
mr.initOptions.Quiet = true
if err := mr.initOptions.Run(args); err != nil {
if _, exists := err.(*cmdliveinit.InvExistsError); exists {
fmt.Fprint(mr.ioStreams.Out, "values already exist...")
} else {
return err
}
}
}
fmt.Fprint(mr.ioStreams.Out, "success\n")
return nil
}
// retrieveConfigMapInv retrieves the ConfigMap inventory object or
// an error if one occurred.
func (mr *MigrateRunner) retrieveConfigMapInv(reader io.Reader, args []string) (inventory.InventoryInfo, error) {
fmt.Fprint(mr.ioStreams.Out, " retrieve the current ConfigMap inventory...")
cmReader, err := mr.cmLoader.ManifestReader(reader, args[0])
if err != nil {
return nil, err
}
objs, err := cmReader.Read()
if err != nil {
return nil, err
}
cmInv, _, err := mr.cmLoader.InventoryInfo(objs)
if err != nil {
// No ConfigMap inventory means the migration has already run before.
if _, ok := err.(inventory.NoInventoryObjError); ok { //nolint
fmt.Fprintln(mr.ioStreams.Out, "no ConfigMap inventory...completed")
}
} else {
fmt.Fprintf(mr.ioStreams.Out, "success (inventory-id: %s)\n", cmInv.ID())
}
return cmInv, err
}
// retrieveInvObjs returns the object references from the passed
// inventory object by querying the inventory object in the cluster,
// or an error if one occurred.
func (mr *MigrateRunner) retrieveInvObjs(invObj inventory.InventoryInfo) ([]object.ObjMetadata, error) {
fmt.Fprint(mr.ioStreams.Out, " retrieve ConfigMap inventory objs...")
cmInvClient, err := mr.cmProvider.InventoryClient()
if err != nil {
return nil, err
}
cmObjs, err := cmInvClient.GetClusterObjs(invObj)
if err != nil {
return nil, err
}
fmt.Fprintf(mr.ioStreams.Out, "success (%d inventory objects)\n", len(cmObjs))
return cmObjs, nil
}
// migrateObjs stores the passed objects in the ResourceGroup inventory
// object and applies the inventory object to the cluster. Returns
// an error if one occurred.
func (mr *MigrateRunner) migrateObjs(cmObjs []object.ObjMetadata, reader io.Reader, args []string) error {
if err := validateParams(reader, args); err != nil {
return err
}
fmt.Fprint(mr.ioStreams.Out, " migrate inventory to ResourceGroup...")
if len(cmObjs) == 0 {
fmt.Fprint(mr.ioStreams.Out, "no inventory objects found\n")
return nil
}
if mr.dryRun {
fmt.Fprintln(mr.ioStreams.Out, "success")
return nil
}
rgReader, err := mr.rgLoader.ManifestReader(reader, args[0])
if err != nil {
return err
}
objs, err := rgReader.Read()
if err != nil {
return err
}
// Filter the ConfigMap inventory object.
rgInv, err := findResourceGroupInv(objs)
if err != nil {
return err
}
rgInvClient, err := mr.rgProvider.InventoryClient()
if err != nil {
return err
}
inv := live.WrapInventoryInfoObj(rgInv)
_, err = rgInvClient.Merge(inv, cmObjs)
if err != nil {
return err
}
fmt.Fprint(mr.ioStreams.Out, "success\n")
return nil
}
// deleteConfigMapInv removes the passed inventory object from the
// cluster. Returns an error if one occurred.
func (mr *MigrateRunner) deleteConfigMapInv(invObj inventory.InventoryInfo) error {
fmt.Fprint(mr.ioStreams.Out, " deleting old ConfigMap inventory object...")
cmInvClient, err := mr.cmProvider.InventoryClient()
if err != nil {
return err
}
if mr.dryRun {
cmInvClient.SetDryRunStrategy(common.DryRunClient)
}
if err = cmInvClient.DeleteInventoryObj(invObj); err != nil {
return err
}
fmt.Fprint(mr.ioStreams.Out, "success\n")
return nil
}
// deleteConfigMapFile deletes the ConfigMap template inventory file. This file
// is usually named "inventory-template.yaml". This operation only happens if
// the input was a directory argument (otherwise there is nothing to delete).
// Returns an error if one occurs while deleting the file. Does NOT return an
// error if the inventory template file is missing.
func (mr *MigrateRunner) deleteConfigMapFile() error {
// Only delete the file if the input was a directory argument.
if len(mr.dir) > 0 {
cmFilename, _, err := common.ExpandDir(mr.dir)
if err != nil {
return err
}
if len(cmFilename) > 0 {
fmt.Fprintf(mr.ioStreams.Out, "deleting inventory template file: %s...", cmFilename)
if !mr.dryRun {
err = os.Remove(cmFilename)
if err != nil {
fmt.Fprint(mr.ioStreams.Out, "failed\n")
return err
}
}
fmt.Fprint(mr.ioStreams.Out, "success\n")
}
}
return nil
}
// findResourceGroupInv returns the ResourceGroup inventory object from the
// passed slice of objects, or nil and and error if there is a problem.
func findResourceGroupInv(objs []*unstructured.Unstructured) (*unstructured.Unstructured, error) {
for _, obj := range objs {
isInv, err := live.IsResourceGroupInventory(obj)
if err != nil {
return nil, err
}
if isInv {
return obj, nil
}
}
return nil, fmt.Errorf("resource group inventory object not found")
}
// validateParams validates input parameters and returns error if any
func validateParams(reader io.Reader, args []string) error {
if reader == nil && len(args) == 0 {
return fmt.Errorf("unable to build ManifestReader without both reader or args")
}
if len(args) > 1 {
return fmt.Errorf("expected one directory argument allowed; got (%s)", args)
}
return nil
}