-
Notifications
You must be signed in to change notification settings - Fork 0
/
helm.go
627 lines (558 loc) · 16.8 KB
/
helm.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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
package api
import (
"fmt"
htype "github.com/banzaicloud/banzai-types/components/helm"
"github.com/banzaicloud/banzai-types/constants"
"github.com/banzaicloud/pipeline/helm"
"github.com/ghodss/yaml"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"k8s.io/helm/pkg/proto/hapi/release"
"k8s.io/helm/pkg/repo"
"k8s.io/helm/pkg/timeconv"
"net/http"
)
// ChartQuery describes a query to get available helm chart's list
type ChartQuery struct {
Name string `form:"name"`
Repo string `form:"repo"`
Version string `form:"version"`
Keyword string `form:"keyword"`
}
// GetK8sConfig returns the Kubernetes config
func GetK8sConfig(c *gin.Context) ([]byte, bool) {
log := logger.WithFields(logrus.Fields{"tag": "GetKubernetesConfig"})
commonCluster, ok := GetCommonClusterFromRequest(c)
if ok != true {
return nil, false
}
kubeConfig, err := commonCluster.GetK8sConfig()
if err != nil {
log.Errorf("Error getting config: %s", err.Error())
c.JSON(http.StatusBadRequest, htype.ErrorResponse{
Code: http.StatusBadRequest,
Message: "Error getting kubeconfig",
Error: err.Error(),
})
return nil, false
}
return kubeConfig, true
}
// CreateDeployment creates a Helm deployment
func CreateDeployment(c *gin.Context) {
log := logger.WithFields(logrus.Fields{"tag": constants.TagCreateDeployment})
parsedRequest, err := parseCreateUpdateDeploymentRequest(c)
if err != nil {
log.Error(err.Error())
c.JSON(http.StatusBadRequest, htype.ErrorResponse{
Code: http.StatusBadRequest,
Message: "Error during parsing request!",
Error: errors.Cause(err).Error(),
})
return
}
release, err := helm.CreateDeployment(parsedRequest.deploymentName,
parsedRequest.deploymentReleaseName, parsedRequest.values, parsedRequest.kubeConfig,
parsedRequest.clusterName)
if err != nil {
//TODO distinguish error codes
log.Errorf("Error during create deployment. %s", err.Error())
c.JSON(http.StatusBadRequest, htype.ErrorResponse{
Code: http.StatusBadRequest,
Message: "Error creating deployment",
Error: err.Error(),
})
return
}
log.Info("Create deployment succeeded")
releaseName := release.Release.Name
releaseNotes := release.Release.Info.Status.Notes
log.Debug("Release name: ", releaseName)
log.Debug("Release notes: ", releaseNotes)
response := htype.CreateUpdateDeploymentResponse{
ReleaseName: releaseName,
Notes: releaseNotes,
}
c.JSON(http.StatusCreated, response)
return
}
// ListDeployments lists a Helm deployment
func ListDeployments(c *gin.Context) {
log := logger.WithFields(logrus.Fields{"tag": constants.TagListDeployments})
kubeConfig, ok := GetK8sConfig(c)
if ok != true {
return
}
log.Info("Get deployments")
response, err := helm.ListDeployments(nil, kubeConfig)
if err != nil {
log.Error("Error during create deployment.", err.Error())
c.JSON(http.StatusBadRequest, htype.ErrorResponse{
Code: http.StatusBadRequest,
Message: "Error listing deployments",
Error: err.Error(),
})
return
}
var releases []htype.ListDeploymentResponse
if len(response.Releases) > 0 {
for _, r := range response.Releases {
body := htype.ListDeploymentResponse{
Name: r.Name,
Chart: fmt.Sprintf("%s-%s", r.Chart.Metadata.Name, r.Chart.Metadata.Version),
Version: r.Version,
Updated: timeconv.String(r.Info.LastDeployed),
Status: r.Info.Status.Code.String()}
releases = append(releases, body)
}
} else {
log.Info("There is no installed charts.")
}
c.JSON(http.StatusOK, releases)
return
}
// HelmDeploymentStatus checks the status of a deployment through the helm client API
func HelmDeploymentStatus(c *gin.Context) {
log := logger.WithFields(logrus.Fields{"tag": "DeploymentStatus"})
name := c.Param("name")
log.Infof("getting status for deployment: [%s]", name)
kubeConfig, ok := GetK8sConfig(c)
if !ok {
log.Debug("could not get the k8s config")
return
}
status, err := helm.GetDeploymentStatus(name, kubeConfig)
// we have the status code in the status, regardless the error!
var (
statusCode int
msg string
)
if err != nil {
// the helm client returned with error
statusCode = int(status)
msg = err.Error()
} else {
// the helm client returned with the status of the deployment
if val, ok := release.Status_Code_name[status]; ok {
log.Infof("deployment status: [%s]", val)
statusCode = http.StatusOK
msg = val
}
}
log.Infof("deployment status for [%s] is [%d]", name, status)
c.JSON(statusCode, htype.DeploymentStatusResponse{
Status: statusCode,
Message: msg,
})
}
// InitHelmOnCluster installs Helm on AKS cluster and configure the Helm client
func InitHelmOnCluster(c *gin.Context) {
log := logger.WithFields(logrus.Fields{"tag": constants.TagHelmInstall})
log.Info("Start helm install")
commonCluster, ok := GetCommonClusterFromRequest(c)
if ok != true {
return
}
kubeConfig, err := commonCluster.GetK8sConfig()
if err != nil {
log.Errorf("Error during getting kubeconfig: %s", err.Error())
c.JSON(http.StatusBadRequest, htype.ErrorResponse{
Code: http.StatusBadRequest,
Message: "Error getting kubeconfig",
Error: err.Error(),
})
return
}
// bind request body to struct
var helmInstall htype.Install
if err := c.BindJSON(&helmInstall); err != nil {
// bind failed
log.Errorf("Required field is empty: %s", err.Error())
c.JSON(http.StatusBadRequest, htype.ErrorResponse{
Code: http.StatusBadRequest,
Message: "Error parsing request",
Error: err.Error(),
})
return
}
err = helm.Install(&helmInstall, kubeConfig, commonCluster.GetName())
if err != nil {
log.Errorf("Unable to install chart: %s", err.Error())
c.JSON(http.StatusBadRequest, htype.ErrorResponse{
Code: http.StatusBadRequest,
Message: "Error installing helm",
Error: err.Error(),
})
return
}
message := "helm initialising"
c.JSON(http.StatusCreated, htype.InstallResponse{
Status: http.StatusCreated,
Message: message,
})
log.Info(message)
return
}
// GetTillerStatus checks if tiller ready to accept deployments
func GetTillerStatus(c *gin.Context) {
log := logger.WithFields(logrus.Fields{"tag": "GetTillerStatus"})
name := c.Param("name")
log.Infof("Retrieving status for deployment: %s", name)
kubeConfig, ok := GetK8sConfig(c)
if ok != true {
return
}
// --- [ List deployments ] ---- //
_, err := helm.ListDeployments(nil, kubeConfig)
if err != nil {
message := "Error connecting to tiller"
c.JSON(http.StatusBadRequest, htype.ErrorResponse{
Code: http.StatusBadRequest,
Message: message,
Error: err.Error(),
})
log.Error(message)
return
}
c.JSON(http.StatusOK, htype.StatusResponse{
Status: http.StatusOK,
Message: "Tiller is available",
})
return
}
//UpgradeDeployment - Upgrades helm deployment, if --reuse-value is specified reuses the last release's value.
func UpgradeDeployment(c *gin.Context) {
log := logger.WithFields(logrus.Fields{"tag": "UpgradeDeployment"})
name := c.Param("name")
log.Infof("Upgrading deployment: %s", name)
parsedRequest, err := parseCreateUpdateDeploymentRequest(c)
if err != nil {
log.Error(err.Error())
c.JSON(http.StatusBadRequest, htype.ErrorResponse{
Code: http.StatusBadRequest,
Message: "Error during parsing request!",
Error: errors.Cause(err).Error(),
})
return
}
release, err := helm.UpgradeDeployment(name,
parsedRequest.deploymentName, parsedRequest.values,
parsedRequest.reuseValues, parsedRequest.kubeConfig, parsedRequest.clusterName)
if err != nil {
log.Errorf("Error during upgrading deployment. %s", err.Error())
c.JSON(http.StatusInternalServerError, htype.ErrorResponse{
Code: http.StatusInternalServerError,
Message: "Error upgrading deployment",
Error: err.Error(),
})
return
}
log.Info("Upgrade deployment succeeded")
releaseNotes := release.Release.Info.Status.Notes
log.Debug("Release notes: ", releaseNotes)
response := htype.CreateUpdateDeploymentResponse{
ReleaseName: name,
Notes: releaseNotes,
}
c.JSON(http.StatusCreated, response)
return
}
//DeleteDeployment deletes a Helm deployment
func DeleteDeployment(c *gin.Context) {
log := logger.WithFields(logrus.Fields{"tag": "DeleteDeployment"})
name := c.Param("name")
log.Infof("Delete deployment: %s", name)
kubeConfig, ok := GetK8sConfig(c)
if ok != true {
return
}
err := helm.DeleteDeployment(name, kubeConfig)
if err != nil {
// error during delete deployment
log.Errorf("Error deleting deployment: %s", err.Error())
c.JSON(http.StatusBadRequest, htype.ErrorResponse{
Code: http.StatusBadRequest,
Message: "Error deleting deployment",
Error: err.Error(),
})
return
}
c.JSON(http.StatusOK, htype.DeleteResponse{
Status: http.StatusOK,
Message: "Deployment deleted!",
Name: name,
})
}
type parsedDeploymentRequest struct {
deploymentName string
deploymentReleaseName string
reuseValues bool
values []byte
kubeConfig []byte
clusterName string
}
func parseCreateUpdateDeploymentRequest(c *gin.Context) (*parsedDeploymentRequest, error) {
log := logger.WithFields(logrus.Fields{"tag": "parseCreateUpdateDeploymentRequest"})
pdr := new(parsedDeploymentRequest)
commonCluster, ok := GetCommonClusterFromRequest(c)
if ok != true {
return nil, errors.New("Get cluster failed!")
}
pdr.clusterName = commonCluster.GetName()
var deployment *htype.CreateUpdateDeploymentRequest
err := c.BindJSON(&deployment)
if err != nil {
return nil, errors.Wrap(err, "Error parsing request:")
}
log.Info("Parse deployment succeeded")
log.Debugf("Parsing chart %s with version %s and release name %s", deployment.Name, deployment.Version, deployment.ReleaseName)
pdr.deploymentName = deployment.Name
pdr.deploymentReleaseName = deployment.ReleaseName
pdr.reuseValues = deployment.ReUseValues
if deployment.Values != "" {
parsedJSON, err := yaml.Marshal(deployment.Values)
if err != nil {
return nil, errors.Wrap(err, "Can't parse Values:")
}
pdr.values, err = yaml.JSONToYAML(parsedJSON)
if err != nil {
return nil, errors.Wrap(err, "Can't convert json to yaml:")
}
}
pdr.kubeConfig, err = commonCluster.GetK8sConfig()
if err != nil {
return nil, errors.Wrap(err, "Error getting kubeconfig:")
}
log.Debug("Custom values: ", string(pdr.values))
return pdr, nil
}
//HelmReposGet listing helm repositories in the cluster
func HelmReposGet(c *gin.Context) {
log := logger.WithFields(logrus.Fields{"tag": "HelmReposGet"})
log.Info("Get helm repository")
clusterName, ok := GetCommonClusterNameFromRequest(c)
if ok != true {
return
}
response, err := helm.ReposGet(clusterName)
if err != nil {
log.Error("Error during get helm repo list.", err.Error())
c.JSON(http.StatusInternalServerError, htype.ErrorResponse{
Code: http.StatusInternalServerError,
Message: "Error listing helm repos",
Error: err.Error(),
})
return
}
c.JSON(http.StatusOK, response)
return
}
//HelmReposAdd add a new helm repository
func HelmReposAdd(c *gin.Context) {
log := logger.WithFields(logrus.Fields{"tag": "HelmReposAdd"})
log.Info("Add helm repository")
clusterName, ok := GetCommonClusterNameFromRequest(c)
if ok != true {
return
}
var repo *repo.Entry
err := c.BindJSON(&repo)
if err != nil {
log.Errorf("Error parsing request: %s", err.Error())
c.JSON(http.StatusBadRequest, htype.ErrorResponse{
Code: http.StatusBadRequest,
Message: "Error parsing request",
Error: err.Error(),
})
return
}
err = helm.ReposAdd(clusterName, repo)
if err != nil {
log.Error("Error adding helm repo", err.Error())
c.JSON(http.StatusBadRequest, htype.ErrorResponse{
Code: http.StatusBadRequest,
Message: "Error adding helm repo",
Error: err.Error(),
})
return
}
c.JSON(http.StatusOK, htype.StatusResponse{
Status: http.StatusOK,
Message: "resource successfully added.",
Name: repo.Name})
return
}
//HelmReposDelete delete the helm repository
func HelmReposDelete(c *gin.Context) {
log := logger.WithFields(logrus.Fields{"tag": "HelmReposDelete"})
log.Info("Delete helm repository")
clusterName, ok := GetCommonClusterNameFromRequest(c)
if ok != true {
return
}
repoName := c.Param("name")
log.Debugln("repoName:", repoName)
err := helm.ReposDelete(clusterName, repoName)
if err != nil {
log.Error("Error during get helm repo delete.", err.Error())
if err.Error() == helm.ErrRepoNotFound.Error() {
c.JSON(http.StatusOK, htype.DeleteResponse{
Status: http.StatusOK,
Message: err.Error(),
Name: repoName})
return
}
c.JSON(http.StatusBadRequest, htype.ErrorResponse{
Code: http.StatusBadRequest,
Message: "error deleting helm repos",
Error: err.Error(),
})
return
}
c.JSON(http.StatusOK, htype.DeleteResponse{
Status: http.StatusOK,
Message: "resource deleted successfully.",
Name: repoName})
return
}
//HelmReposModify modify the helm repository
func HelmReposModify(c *gin.Context) {
log := logger.WithFields(logrus.Fields{"tag": "HelmReposModify"})
log.Info("modify helm repository")
clusterName, ok := GetCommonClusterNameFromRequest(c)
if ok != true {
return
}
repoName := c.Param("name")
log.Debugln("repoName:", repoName)
var newRepo *repo.Entry
err := c.BindJSON(&newRepo)
if err != nil {
log.Errorf("Error parsing request: %s", err.Error())
c.JSON(http.StatusBadRequest, htype.ErrorResponse{
Code: http.StatusBadRequest,
Message: "error parsing request",
Error: err.Error(),
})
return
}
errModify := helm.ReposModify(clusterName, repoName, newRepo)
if errModify != nil {
if errModify == helm.ErrRepoNotFound {
c.JSON(http.StatusNotFound, htype.ErrorResponse{
Code: http.StatusNotFound,
Error: errModify.Error(),
Message: "repo not found",
})
return
}
log.Error("Error during helm repo modified.", errModify.Error())
c.JSON(http.StatusBadRequest, htype.ErrorResponse{
Code: http.StatusBadRequest,
Error: errModify.Error(),
Message: "repo modification failed",
})
return
}
c.JSON(http.StatusOK, htype.StatusResponse{
Status: http.StatusOK,
Message: "resource modified successfully",
Name: repoName})
return
}
// HelmReposUpdate update the helm repo
func HelmReposUpdate(c *gin.Context) {
log := logger.WithFields(logrus.Fields{"tag": "ReposUpdate"})
log.Info("delete helm repository")
clusterName, ok := GetCommonClusterNameFromRequest(c)
if ok != true {
return
}
repoName := c.Param("name")
log.Debugln("repoName:", repoName)
errUpdate := helm.ReposUpdate(clusterName, repoName)
if errUpdate != nil {
log.Error("Error during helm repo update.", errUpdate.Error())
c.JSON(http.StatusNotFound, htype.ErrorResponse{
Code: http.StatusNotFound,
Error: errUpdate.Error(),
Message: "repository update failed",
})
return
}
c.JSON(http.StatusOK, htype.StatusResponse{
Status: http.StatusOK,
Message: "repository updated successfully",
Name: repoName})
return
}
//HelmCharts get available helm chart's list
func HelmCharts(c *gin.Context) {
log := logger.WithFields(logrus.Fields{"tag": "HelmCharts"})
log.Info("Get helm repository charts")
clusterName, ok := GetCommonClusterNameFromRequest(c)
if ok != true {
return
}
var query ChartQuery
err := c.BindQuery(&query)
if err != nil {
log.Errorf("Error parsing request: %s", err.Error())
c.JSON(http.StatusBadRequest, htype.ErrorResponse{
Code: http.StatusBadRequest,
Message: "error parsing request",
Error: err.Error(),
})
return
}
log.Info(query)
response, err := helm.ChartsGet(clusterName, query.Name, query.Repo, query.Version, query.Keyword)
if err != nil {
log.Error("Error during get helm repo chart list.", err.Error())
c.JSON(http.StatusBadRequest, htype.ErrorResponse{
Code: http.StatusBadRequest,
Message: "Error listing helm repo charts",
Error: err.Error(),
})
return
}
c.JSON(http.StatusOK, response)
return
}
//HelmChart get helm chart details
func HelmChart(c *gin.Context) {
log := logger.WithFields(logrus.Fields{"tag": "HelmChart"})
log.Info("Get helm chart")
clusterName, ok := GetCommonClusterNameFromRequest(c)
if ok != true {
return
}
log.Debugf("%#v", c)
chartRepo := c.Param("reponame")
log.Debugln("chartRepo:", chartRepo)
chartName := c.Param("name")
log.Debugln("chartName:", chartName)
chartVersion := c.Param("version")
log.Debugln("version:", chartVersion)
response, err := helm.ChartGet(clusterName, chartRepo, chartName, chartVersion)
if err != nil {
log.Error("Error during get helm chart information.", err.Error())
c.JSON(http.StatusBadRequest, htype.ErrorResponse{
Code: http.StatusBadRequest,
Message: "Error during get helm chart information.",
Error: err.Error(),
})
return
}
if response == nil {
c.JSON(http.StatusNotFound, htype.ErrorResponse{
Code: http.StatusNotFound,
Error: "Chart Not Found!",
Message: "Chart Not Found!",
})
return
}
c.JSON(http.StatusOK, response)
return
}