generated from kubernetes/kubernetes-template-project
/
export.go
167 lines (140 loc) · 4.47 KB
/
export.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
/*
Copyright 2023 The Kubernetes Authors.
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.
*/
// Package export is the export of external cluster
package export
import (
"context"
"fmt"
"io"
"strings"
"time"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/client-go/rest"
"sigs.k8s.io/kwok/pkg/kwokctl/dryrun"
"sigs.k8s.io/kwok/pkg/kwokctl/recording"
"sigs.k8s.io/kwok/pkg/kwokctl/snapshot"
"sigs.k8s.io/kwok/pkg/log"
"sigs.k8s.io/kwok/pkg/utils/client"
"sigs.k8s.io/kwok/pkg/utils/file"
"sigs.k8s.io/kwok/pkg/utils/yaml"
)
type flagpole struct {
Path string
Kubeconfig string
Filters []string
ImpersonateUser string
ImpersonateGroups []string
PageSize int64
PageBufferSize int32
Record bool
}
// NewCommand returns a new cobra.Command for cluster exporting.
func NewCommand(ctx context.Context) *cobra.Command {
flags := &flagpole{}
cmd := &cobra.Command{
Args: cobra.NoArgs,
Use: "export",
Short: "[experimental] Export the snapshots of external clusters",
RunE: func(cmd *cobra.Command, args []string) error {
return runE(cmd.Context(), flags)
},
}
cmd.Flags().StringVar(&flags.Kubeconfig, "kubeconfig", flags.Kubeconfig, "Path to the kubeconfig file to use")
cmd.Flags().StringVar(&flags.Path, "path", "", "Path to the snapshot")
cmd.Flags().StringSliceVar(&flags.Filters, "filter", snapshot.Resources, "Filter the resources to export")
cmd.Flags().StringVar(&flags.ImpersonateUser, "as", "", "Username to impersonate for the operation. User could be a regular user or a service account in a namespace.")
cmd.Flags().StringSliceVar(&flags.ImpersonateGroups, "as-group", nil, "Group to impersonate for the operation, this flag can be repeated to specify multiple groups.")
cmd.Flags().Int64Var(&flags.PageSize, "page-size", 500, "Define the page size")
cmd.Flags().Int32Var(&flags.PageBufferSize, "page-buffer-size", 10, "Define the number of pages to buffer")
cmd.Flags().BoolVar(&flags.Record, "record", false, "Record the change of the cluster")
return cmd
}
func runE(ctx context.Context, flags *flagpole) error {
if flags.Path == "" {
return fmt.Errorf("path is required")
}
if file.Exists(flags.Path) {
return fmt.Errorf("file %q already exists", flags.Path)
}
if dryrun.DryRun {
dryrun.PrintMessage("kubectl --kubeconfig %s get %s -o yaml >%s", flags.Kubeconfig, strings.Join(flags.Filters, ","), flags.Path)
return nil
}
clientset, err := client.NewClientset("", flags.Kubeconfig,
client.WithImpersonate(rest.ImpersonationConfig{
UserName: flags.ImpersonateUser,
Groups: flags.ImpersonateGroups,
}),
)
if err != nil {
return err
}
logger := log.FromContext(ctx)
pagerConfig := &snapshot.PagerConfig{
PageSize: flags.PageSize,
PageBufferSize: flags.PageBufferSize,
}
restMapper, err := clientset.ToRESTMapper()
if err != nil {
return err
}
filters, errs := client.MappingForResources(restMapper, flags.Filters)
if len(errs) > 0 {
for _, err := range errs {
logger.Error("failed to get mapping", err)
}
}
saver, err := snapshot.NewSaver(snapshot.SaveConfig{
Clientset: clientset,
PagerConfig: pagerConfig,
Filters: filters,
})
if err != nil {
return err
}
f, err := file.Open(flags.Path)
if err != nil {
return err
}
defer func() {
_ = f.Close()
}()
press := file.Compress(flags.Path, f)
defer func() {
_ = press.Close()
}()
var writer io.Writer = press
startTime := time.Now()
writer = recording.NewWriteHook(writer, func(b []byte) []byte {
return recording.ReplaceTimeToRelative(startTime, b)
})
encoder := yaml.NewEncoder(writer)
var tracks map[*meta.RESTMapping]*snapshot.TrackData
if flags.Record {
tracks = make(map[*meta.RESTMapping]*snapshot.TrackData)
}
err = saver.Save(ctx, encoder, tracks)
if err != nil {
return err
}
if flags.Record {
logger.Info("Recording")
logger.Info("Press Ctrl+C to stop recording resources")
err = saver.Record(ctx, encoder, tracks)
if err != nil {
return err
}
}
return nil
}