forked from kubernetes-sigs/cluster-api
/
util.go
315 lines (267 loc) · 7.85 KB
/
util.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
/*
Copyright 2017 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 util
import (
"context"
"errors"
"fmt"
"io"
"math/rand"
"os"
"os/exec"
"os/user"
"strings"
"time"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/json"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/klog"
clusterv1 "sigs.k8s.io/cluster-api/pkg/apis/cluster/v1alpha1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
const (
// CharSet defines the alphanumeric set for random string generation
CharSet = "0123456789abcdefghijklmnopqrstuvwxyz"
// MachineListFormatDeprecationMessage notifies the user that the old
// MachineList format is no longer supported
MachineListFormatDeprecationMessage = "Your MachineList items must include Kind and APIVersion"
)
var (
rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
)
// RandomToken returns a random token.
func RandomToken() string {
return fmt.Sprintf("%s.%s", RandomString(6), RandomString(16))
}
// RandomString returns a random alphanumeric string.
func RandomString(n int) string {
result := make([]byte, n)
for i := range result {
result[i] = CharSet[rnd.Intn(len(CharSet))]
}
return string(result)
}
// GetControlPlaneMachine returns a control plane machine from input.
// Deprecated: use GetControlPlaneMachines.
func GetControlPlaneMachine(machines []*clusterv1.Machine) *clusterv1.Machine {
for _, machine := range machines {
if IsControlPlaneMachine(machine) {
return machine
}
}
return nil
}
// GetControlPlaneMachines returns a slice containing control plane machines.
func GetControlPlaneMachines(machines []*clusterv1.Machine) (res []*clusterv1.Machine) {
for _, machine := range machines {
if IsControlPlaneMachine(machine) {
res = append(res, machine)
}
}
return
}
// Home returns the user home directory.
func Home() string {
home := os.Getenv("HOME")
if strings.Contains(home, "root") {
return "/root"
}
usr, err := user.Current()
if err != nil {
klog.Warningf("unable to find user: %v", err)
return ""
}
return usr.HomeDir
}
// GetDefaultKubeConfigPath returns the standard user kubeconfig
func GetDefaultKubeConfigPath() string {
localDir := fmt.Sprintf("%s/.kube", Home())
if _, err := os.Stat(localDir); os.IsNotExist(err) {
if err := os.Mkdir(localDir, 0777); err != nil {
klog.Fatal(err)
}
}
return fmt.Sprintf("%s/config", localDir)
}
// GetMachineIfExists gets a machine from the API server if it exists
func GetMachineIfExists(c client.Client, namespace, name string) (*clusterv1.Machine, error) {
if c == nil {
// Being called before k8s is setup as part of control plane VM creation
return nil, nil
}
// Machines are identified by name
machine := &clusterv1.Machine{}
err := c.Get(context.Background(), client.ObjectKey{Namespace: namespace, Name: name}, machine)
if err != nil {
if apierrors.IsNotFound(err) {
return nil, nil
}
return nil, err
}
return machine, nil
}
// IsControlPlaneMachine checks machine is a control plane node.
func IsControlPlaneMachine(machine *clusterv1.Machine) bool {
return machine.Spec.Versions.ControlPlane != ""
}
// IsNodeReady returns true if a node is ready.
func IsNodeReady(node *v1.Node) bool {
for _, condition := range node.Status.Conditions {
if condition.Type == v1.NodeReady {
return condition.Status == v1.ConditionTrue
}
}
return false
}
// Copy deep copies a Machine object.
func Copy(m *clusterv1.Machine) *clusterv1.Machine {
ret := &clusterv1.Machine{}
ret.APIVersion = m.APIVersion
ret.Kind = m.Kind
ret.ClusterName = m.ClusterName
ret.GenerateName = m.GenerateName
ret.Name = m.Name
ret.Namespace = m.Namespace
m.Spec.DeepCopyInto(&ret.Spec)
return ret
}
// ExecCommand Executes a local command in the current shell.
func ExecCommand(name string, args ...string) (string, error) {
cmdOut, err := exec.Command(name, args...).Output()
if err != nil {
s := strings.Join(append([]string{name}, args...), " ")
klog.Infof("Executing command %q: %v", s, err)
return string(""), err
}
return string(cmdOut), nil
}
// Filter filters a list for a string.
func Filter(list []string, strToFilter string) (newList []string) {
for _, item := range list {
if item != strToFilter {
newList = append(newList, item)
}
}
return
}
// Contains returns true if a list contains a string.
func Contains(list []string, strToSearch string) bool {
for _, item := range list {
if item == strToSearch {
return true
}
}
return false
}
// GetNamespaceOrDefault returns the default namespace if given empty
// output.
func GetNamespaceOrDefault(namespace string) string {
if namespace == "" {
return v1.NamespaceDefault
}
return namespace
}
// ParseClusterYaml parses a YAML file for cluster objects.
func ParseClusterYaml(file string) (*clusterv1.Cluster, error) {
reader, err := os.Open(file)
if err != nil {
return nil, err
}
defer reader.Close()
decoder := yaml.NewYAMLOrJSONDecoder(reader, 32)
bytes, err := decodeClusterV1Kinds(decoder, "Cluster")
if err != nil {
return nil, err
}
var cluster clusterv1.Cluster
if err := json.Unmarshal(bytes[0], &cluster); err != nil {
return nil, err
}
return &cluster, nil
}
// ParseMachinesYaml extracts machine objects from a file.
func ParseMachinesYaml(file string) ([]*clusterv1.Machine, error) {
reader, err := os.Open(file)
if err != nil {
return nil, err
}
defer reader.Close()
decoder := yaml.NewYAMLOrJSONDecoder(reader, 32)
var (
bytes [][]byte
machineList clusterv1.MachineList
machines = []*clusterv1.Machine{}
)
// TODO: use the universal decoder instead of doing this.
if bytes, err = decodeClusterV1Kinds(decoder, "MachineList"); err != nil {
if isMissingKind(err) {
err = errors.New(MachineListFormatDeprecationMessage)
}
return nil, err
}
// TODO: this is O(n^2) and must be optimized
for _, ml := range bytes {
if err := json.Unmarshal(ml, &machineList); err != nil {
return nil, err
}
for i := range machineList.Items {
machine := &machineList.Items[i]
if machine.APIVersion == "" || machine.Kind == "" {
return nil, errors.New(MachineListFormatDeprecationMessage)
}
machines = append(machines, machine)
}
}
// reset reader to search for discrete Machine definitions
if _, err := reader.Seek(0, 0); err != nil {
return nil, err
}
if bytes, err = decodeClusterV1Kinds(decoder, "Machine"); err != nil {
return nil, err
}
for _, m := range bytes {
machine := &clusterv1.Machine{}
if err := json.Unmarshal(m, machine); err != nil {
return nil, err
}
machines = append(machines, machine)
}
return machines, nil
}
// isMissingKind reimplements runtime.IsMissingKind as the YAMLOrJSONDecoder
// hides the error type.
func isMissingKind(err error) bool {
return strings.Contains(err.Error(), "Object 'Kind' is missing in")
}
// decodeClusterV1Kinds returns a slice of objects matching the clusterv1 kind.
func decodeClusterV1Kinds(decoder *yaml.YAMLOrJSONDecoder, kind string) ([][]byte, error) {
outs := [][]byte{}
for {
var out unstructured.Unstructured
if err := decoder.Decode(&out); err == io.EOF {
break
} else if err != nil {
return nil, err
}
if out.GetKind() == kind && out.GetAPIVersion() == clusterv1.SchemeGroupVersion.String() {
marshaled, err := out.MarshalJSON()
if err != nil {
return outs, err
}
outs = append(outs, marshaled)
}
}
return outs, nil
}