/
get_cluster.go
292 lines (248 loc) · 7.66 KB
/
get_cluster.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
/*
Copyright 2016 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 main
import (
"fmt"
"io"
"os"
"strings"
"github.com/spf13/cobra"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/kops/cmd/kops/util"
api "k8s.io/kops/pkg/apis/kops"
"k8s.io/kops/pkg/apis/kops/registry"
"k8s.io/kops/util/pkg/tables"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
"k8s.io/kubernetes/pkg/kubectl/util/i18n"
)
var (
getClusterLong = templates.LongDesc(i18n.T(`
Display one or many cluster resources.`))
getClusterExample = templates.Examples(i18n.T(`
# Get all clusters in a state store
kops get clusters
# Get a cluster
kops get cluster k8s-cluster.example.com
# Get a cluster YAML desired configuration
kops get cluster k8s-cluster.example.com -o yaml
# Save a cluster desired configuration to YAML file
kops get cluster k8s-cluster.example.com -o yaml > cluster-desired-config.yaml
`))
getClusterShort = i18n.T(`Get one or many clusters.`)
// Warning for --full. Since we are not using the template from kubectl
// we have to have zero white space before the comment characters otherwise
// output to stdout is going to be off.
get_cluster_full_warning = i18n.T(`
//
// WARNING: Do not use a '--full' cluster specification to define a Kubernetes installation.
// You may experience unexpected behavior and other bugs. Use only the required elements
// and any modifications that you require.
//
// Use the following command to retrieve only the required elements:
// $ kops get cluster -o yaml
//
`)
)
type GetClusterOptions struct {
*GetOptions
// FullSpec determines if we should output the completed (fully populated) spec
FullSpec bool
// ClusterNames is a list of cluster names to show; if not specified all clusters will be shown
ClusterNames []string
}
func NewCmdGetCluster(f *util.Factory, out io.Writer, getOptions *GetOptions) *cobra.Command {
options := GetClusterOptions{
GetOptions: getOptions,
}
cmd := &cobra.Command{
Use: "clusters",
Aliases: []string{"cluster"},
Short: getClusterShort,
Long: getClusterLong,
Example: getClusterExample,
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 0 {
options.ClusterNames = append(options.ClusterNames, args...)
}
if rootCommand.clusterName != "" {
if len(args) != 0 {
exitWithError(fmt.Errorf("cannot mix --name for cluster with positional arguments"))
}
options.ClusterNames = append(options.ClusterNames, rootCommand.clusterName)
}
err := RunGetClusters(&rootCommand, os.Stdout, &options)
if err != nil {
exitWithError(err)
}
},
}
cmd.Flags().BoolVar(&options.FullSpec, "full", options.FullSpec, "Show fully populated configuration")
return cmd
}
func RunGetClusters(context Factory, out io.Writer, options *GetClusterOptions) error {
client, err := context.Clientset()
if err != nil {
return err
}
var clusterList []*api.Cluster
if len(options.ClusterNames) != 1 {
list, err := client.ListClusters(metav1.ListOptions{})
if err != nil {
return err
}
for i := range list.Items {
clusterList = append(clusterList, &list.Items[i])
}
} else {
// Optimization - avoid fetching all clusters if we're only querying one
cluster, err := client.GetCluster(options.ClusterNames[0])
if err != nil {
if !apierrors.IsNotFound(err) {
return err
}
} else {
clusterList = append(clusterList, cluster)
}
}
clusters, err := filterClustersByName(options.ClusterNames, clusterList)
if err != nil {
return err
}
if len(clusters) == 0 {
return fmt.Errorf("no clusters found")
}
if options.FullSpec {
var err error
clusters, err = fullClusterSpecs(clusters)
if err != nil {
return err
}
fmt.Fprint(out, get_cluster_full_warning)
}
var obj []runtime.Object
if options.output != OutputTable {
for _, c := range clusters {
obj = append(obj, c)
}
}
switch options.output {
case OutputTable:
return clusterOutputTable(clusters, out)
case OutputYaml:
return fullOutputYAML(out, obj...)
case OutputJSON:
return fullOutputJSON(out, obj...)
default:
return fmt.Errorf("Unknown output format: %q", options.output)
}
}
// filterClustersByName returns the clusters matching the specified names.
// If names are specified and no cluster is found with a name, we return an error.
func filterClustersByName(clusterNames []string, clusters []*api.Cluster) ([]*api.Cluster, error) {
if len(clusterNames) != 0 {
// Build a map as we want to return them in the same order as args
m := make(map[string]*api.Cluster)
for _, c := range clusters {
m[c.ObjectMeta.Name] = c
}
var filtered []*api.Cluster
for _, clusterName := range clusterNames {
c := m[clusterName]
if c == nil {
return nil, fmt.Errorf("cluster not found %q", clusterName)
}
filtered = append(filtered, c)
}
return filtered, nil
}
return clusters, nil
}
func clusterOutputTable(clusters []*api.Cluster, out io.Writer) error {
t := &tables.Table{}
t.AddColumn("NAME", func(c *api.Cluster) string {
return c.ObjectMeta.Name
})
t.AddColumn("CLOUD", func(c *api.Cluster) string {
return c.Spec.CloudProvider
})
t.AddColumn("ZONES", func(c *api.Cluster) string {
zones := sets.NewString()
for _, s := range c.Spec.Subnets {
if s.Zone != "" {
zones.Insert(s.Zone)
}
}
return strings.Join(zones.List(), ",")
})
return t.Render(clusters, out, "NAME", "CLOUD", "ZONES")
}
// fullOutputJson outputs the marshalled JSON of a list of clusters and instance groups. It will handle
// nils for clusters and instanceGroups slices.
func fullOutputJSON(out io.Writer, args ...runtime.Object) error {
argsLen := len(args)
if argsLen > 1 {
if _, err := fmt.Fprint(out, "["); err != nil {
return err
}
}
for i, arg := range args {
if i != 0 {
if _, err := fmt.Fprint(out, ","); err != nil {
return err
}
}
if err := marshalToWriter(arg, marshalJSON, out); err != nil {
return err
}
}
if argsLen > 1 {
if _, err := fmt.Fprint(out, "]"); err != nil {
return err
}
}
return nil
}
// fullOutputJson outputs the marshalled JSON of a list of clusters and instance groups. It will handle
// nils for clusters and instanceGroups slices.
func fullOutputYAML(out io.Writer, args ...runtime.Object) error {
for i, obj := range args {
if i != 0 {
if err := writeYAMLSep(out); err != nil {
return fmt.Errorf("error writing to stdout: %v", err)
}
}
if err := marshalToWriter(obj, marshalYaml, out); err != nil {
return err
}
}
return nil
}
func fullClusterSpecs(clusters []*api.Cluster) ([]*api.Cluster, error) {
var fullSpecs []*api.Cluster
for _, cluster := range clusters {
configBase, err := registry.ConfigBase(cluster)
if err != nil {
return nil, fmt.Errorf("error reading full cluster spec for %q: %v", cluster.ObjectMeta.Name, err)
}
fullSpec := &api.Cluster{}
err = registry.ReadConfigDeprecated(configBase.Join(registry.PathClusterCompleted), fullSpec)
if err != nil {
return nil, fmt.Errorf("error reading full cluster spec for %q: %v", cluster.ObjectMeta.Name, err)
}
fullSpecs = append(fullSpecs, fullSpec)
}
return fullSpecs, nil
}