-
Notifications
You must be signed in to change notification settings - Fork 0
/
kubectl.go
474 lines (369 loc) · 11.8 KB
/
kubectl.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
package kubectl
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"github.com/cjlapao/common-go/commands"
"github.com/cjlapao/common-go/helper"
"github.com/cjlapao/common-go/log"
"github.com/cjlapao/deployment-tools-go/common"
"gopkg.in/yaml.v2"
)
var logger = log.Get()
// Module Entity
type Module struct {
Exists bool
ClientVersion string
ServerVersion string
Version Version
Exec string
Path string
CurrentContext string
KubeConfig KubeConfig
}
// NewModule creates a new Istio Module
func NewModule() Module {
module := Module{
Exists: false,
}
module.SetExists()
if !module.Exists {
module.GetModule()
}
// module.GetKubeConfig()
return module
}
// SetExists checks if Istio module exists
func (m *Module) SetExists() bool {
logger.Notice("Checking for installed kubectl version...")
var kubectlModuleFolder string
toolsFolder := common.ToolsFolder()
files, err := ioutil.ReadDir(toolsFolder)
if err != nil {
return false
}
for _, f := range files {
matched, _ := regexp.Match("^kubectl", []byte(f.Name()))
logger.Debug("Module Item:", f.Name())
if matched && f.IsDir() {
kubectlModuleFolder = f.Name()
logger.Debug("Matched On:", f.Name())
}
}
if len(kubectlModuleFolder) > 0 {
m.Path = helper.JoinPath(toolsFolder, kubectlModuleFolder)
switch helper.GetOperatingSystem() {
case helper.WindowsOs:
m.Exec = helper.JoinPath(m.Path, "kubectl.exe")
case helper.LinuxOs:
m.Exec = helper.JoinPath(m.Path, "kubectl")
}
if helper.FileExists(m.Exec) {
err := m.GetVersion()
if err == nil {
logger.Success("Found kubectl Module version", m.ClientVersion)
m.Exists = true
return true
}
}
}
logger.Notice("Kubectl Module was not found under tools")
return false
}
// GetVersion gets Istio latest version from github
func (m *Module) GetVersion() error {
if len(m.Exec) > 0 {
logger.Debug("Found Kubectl executable, getting the version")
out, err := commands.Execute(m.Exec, "version", "-o", "json", "--client=true")
if err != nil && !strings.ContainsAny(err.Error(), "Unable to connect to the server: dial tcp [::1]:8080: connectex: No connection could be made because the target machine actively refused it.") {
logger.Error(err.Error())
return err
}
logger.Debug("Kubectl version output")
logger.Debug(out)
version := Version{}
jsonError := json.Unmarshal([]byte(out), &version)
if jsonError != nil {
logger.Error(jsonError.Error())
return jsonError
}
m.Version = version
m.ClientVersion = version.ClientVersion.GitVersion
m.ServerVersion = version.ServerVersion.GitVersion
return nil
}
return errors.New("Executable was not found, cannot get a version")
}
// GetModule GetModule Istio into the tools folder
func (m *Module) GetModule() {
logger.Notice("Checking online for latest version")
latestVersion := getLatestVersion()
toolsFolder := common.ToolsFolder()
if m.Exists && getVersionFromString(m.ClientVersion) < getVersionFromString(latestVersion) {
logger.Warn("There is a new version (" + latestVersion + ") online...")
}
if !m.Exists {
if len(latestVersion) > 0 {
filename, err := downloadModule(latestVersion)
if err == nil {
logger.Notice("Installing Kubectl", latestVersion)
switch helper.GetOperatingSystem() {
case helper.WindowsOs:
m.Path = helper.JoinPath(toolsFolder, "kubectl-"+latestVersion, "bin")
m.Exec = helper.JoinPath(m.Path, "kubectl.exe")
case helper.LinuxOs:
commands.Execute("chmod", "+x", filename)
m.Path = helper.JoinPath(toolsFolder, "kubectl-"+latestVersion, "bin")
m.Exec = helper.JoinPath(m.Path, "kubectl")
}
}
m.SetExists()
commands.Execute("export", "PATH="+m.Path+"/bin:$PATH")
}
} else {
logger.Notice("Found version", m.ClientVersion, "on", toolsFolder)
}
}
// GetKubeConfig gets Kubectl config from system
func (m *Module) GetKubeConfig() *KubeConfig {
logger.Notice("Getting Kubectl config from system")
out, err := commands.Execute(m.Exec, "config", "view", "--raw")
if err != nil {
logger.Error(err.Error())
return nil
}
if err == nil && len(out) > 0 {
kubeConfig, err := parseKubeConfig(out)
if err != nil {
logger.Error(err)
}
m.KubeConfig = kubeConfig
m.CurrentContext = kubeConfig.CurrentContext
kubeconfigBytes, err := yaml.Marshal(kubeConfig)
if err != nil {
logger.Error(err)
}
helper.WriteToFile(string(kubeconfigBytes), common.KubeConfig())
return &m.KubeConfig
}
return nil
}
// AddKubeConfig adds a kubeconfig string into the Kubectl config
func (m *Module) AddKubeConfig(kubeConfig string) error {
if len(kubeConfig) == 0 {
return errors.New("The kubeconfig was null or empty")
}
logger.Notice("Adding kube config to Kubectl")
config, err := parseKubeConfig(kubeConfig)
if err != nil {
logger.Error(err)
return err
}
// Adding the cluster
for _, cluster := range config.Clusters {
err := m.AddCluster(cluster)
if err != nil {
return err
}
}
// Adding the users
for _, user := range config.Users {
err := m.AddCredentials(user)
if err != nil {
return err
}
}
// Adding the contexts
for _, context := range config.Contexts {
err := m.AddContext(context)
if err != nil {
return err
}
}
// Adding the current context
if len(config.CurrentContext) > 0 {
err := m.SetContext(config.CurrentContext)
if err != nil {
return err
}
}
m.GetKubeConfig()
return nil
}
// AddCluster Adds a cluster to the kubectl config
func (m *Module) AddCluster(cluster ClusterElement) error {
var cmdErr error
var out string
logger.Debug("AddCluster")
certTempFile := helper.JoinPath(common.TempFolder(), "ca.cert")
if len(cluster.Cluster.CertificateAuthorityData) > 0 {
bytes, err := base64.StdEncoding.DecodeString(cluster.Cluster.CertificateAuthorityData)
if err != nil {
return err
}
helper.WriteToFile(string(bytes), certTempFile)
cluster.Cluster.CertificateAuthority = certTempFile
out, cmdErr = commands.Execute(m.Exec, "config", "set-cluster", cluster.Name, "--server="+cluster.Cluster.Server, "--certificate-authority="+cluster.Cluster.CertificateAuthority, "--embed-certs=true")
} else {
out, cmdErr = commands.Execute(m.Exec, "config", "set-cluster", cluster.Name, "--server="+cluster.Cluster.Server, "--certificate-authority="+cluster.Cluster.CertificateAuthority)
}
logger.Debug(out)
if cmdErr != nil {
logger.Error(cmdErr)
return cmdErr
}
helper.DeleteFile(certTempFile)
return nil
}
// AddCredentials Adds a credential to the kubectl config
func (m *Module) AddCredentials(user UserElement) error {
var cmdErr error
var out string
logger.Debug("AddCredentials")
if len(user.User.Token) > 0 {
out, cmdErr = commands.Execute(m.Exec, "config", "set-credentials", user.Name, "--token="+user.User.Token)
} else if len(user.User.Username) > 0 {
out, cmdErr = commands.Execute(m.Exec, "config", "set-credentials", user.Name, "--username="+user.User.Username, "--password="+user.User.Password)
} else {
out, cmdErr = commands.Execute(m.Exec, "config", "set-credentials", user.Name, "--client-certificate="+user.User.ClientCertificate, "--client-key="+user.User.ClientKey)
}
logger.Debug(out)
if cmdErr != nil {
logger.Error(cmdErr)
return cmdErr
}
return nil
}
// AddContext Adds a context to the kubectl config
func (m *Module) AddContext(context ContextElement) error {
logger.Debug("AddContext")
out, cmdErr := commands.Execute(m.Exec, "config", "set-context", context.Name, "--cluster="+context.Context.Cluster, "--user="+context.Context.User, "--namespace="+context.Context.Namespace)
logger.Debug(out)
if cmdErr != nil {
logger.Error(cmdErr)
return cmdErr
}
return nil
}
// SetContext Sets the default context for kubectl
func (m *Module) SetContext(contextName string) error {
logger.Debug("SetContext")
if len(contextName) == 0 {
return errors.New("Context name is empty")
}
// Adding the current context
out, cmdErr := commands.Execute(m.Exec, "config", "use-context", contextName)
logger.Debug(out)
if cmdErr != nil {
logger.Error(cmdErr)
return cmdErr
}
m.CurrentContext = contextName
return nil
}
// Delete Deletes a manifest from the default context
func (m *Module) Delete(manifestPath string) error {
logger.Notice("Deleting " + manifestPath + " from " + m.CurrentContext)
if len(manifestPath) == 0 {
return errors.New("Path is empty")
}
if !helper.FileExists(manifestPath) {
return errors.New("Manifes file " + manifestPath + "Does not exists in system")
}
out, cmdErr := commands.Execute(m.Exec, "delete", "--ignore-not-found=true", "-f", manifestPath, "--kubeconfig", common.KubeConfig(), "--context", m.CurrentContext)
if cmdErr != nil {
return cmdErr
}
logger.Debug(out)
logger.Success("Manifest " + manifestPath + " deleted sucessfully")
return nil
}
// DeleteNamespace Deletes a manifest from the default context
func (m *Module) DeleteNamespace(namespace string) error {
logger.Notice("Deleting Namespace " + namespace + " from " + m.CurrentContext)
if len(namespace) == 0 {
return errors.New("Namespace is empty")
}
out, cmdErr := commands.Execute(m.Exec, "delete", "namespace", namespace, "--kubeconfig", common.KubeConfig(), "--context", m.CurrentContext)
if cmdErr != nil {
return cmdErr
}
logger.Debug(out)
logger.Success("Namespace " + namespace + " deleted successfully")
return nil
}
// GetAllNamespace Deletes a manifest from the default context
func (m *Module) GetAllNamespace() error {
logger.Notice("Getting all namespaces from " + m.CurrentContext)
out, cmdErr := commands.Execute(m.Exec, "get", "namespace", "--kubeconfig", common.KubeConfig(), "--context", m.CurrentContext)
if cmdErr != nil {
return cmdErr
}
logger.Debug(out)
logger.Success("Got all namespaces successfully")
return nil
}
func getLatestVersion() string {
baseURL := "https://storage.googleapis.com/kubernetes-release/release/stable.txt"
logger.Debug("Listing all available versions of kubectl to download")
response, err := http.Get(baseURL)
helper.CheckError(err)
defer response.Body.Close()
if response.StatusCode == http.StatusOK {
bodyBytes, err := ioutil.ReadAll(response.Body)
helper.CheckError(err)
latestVersion := string(bodyBytes)
logger.Debug("Version:", latestVersion)
return latestVersion
}
return ""
}
func downloadModule(version string) (string, error) {
var filename string
toolsFolder := common.ToolsFolder()
foldername := helper.JoinPath(toolsFolder, "kubectl-"+strings.ReplaceAll(version, "v", ""))
switch helper.GetOperatingSystem() {
case helper.WindowsOs:
filename = "kubectl.exe"
case helper.LinuxOs:
filename = "kubectl"
}
url := "https://storage.googleapis.com/kubernetes-release/release/" + version + "/bin/" + strings.ToLower(helper.GetOperatingSystem().String()) + "/amd64/" + filename
if _, err := os.Stat(toolsFolder); os.IsNotExist(err) {
logger.Debug("Tools folder doesn't exist, creating")
os.Mkdir(toolsFolder, os.ModeDir)
}
if _, err := os.Stat(foldername); os.IsNotExist(err) {
logger.Debug("Kubectl folder doesn't exist, creating")
os.Mkdir(foldername, os.ModeDir)
}
downloadPath := helper.JoinPath(foldername, filename)
logger.Debug("Downloading file into", downloadPath)
err := helper.DownloadFile(url, downloadPath)
logger.Error(err)
return filename, err
}
func getVersionFromString(value string) int {
v, err := strconv.Atoi(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(value, "kubectl", ""), "-", ""), ".", ""))
if err != nil {
return -1
}
logger.Debug("Istio int version: ", fmt.Sprint(v))
return v
}
func parseKubeConfig(value string) (KubeConfig, error) {
var kubeConfig KubeConfig
yamlErr := yaml.Unmarshal([]byte(value), &kubeConfig)
if yamlErr != nil {
logger.Error(yamlErr)
return KubeConfig{}, yamlErr
}
return kubeConfig, nil
}