forked from banzaicloud/pipeline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
1191 lines (1027 loc) · 39.7 KB
/
main.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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"fmt"
"net/http"
"os"
"time"
banzaiTypes "github.com/banzaicloud/banzai-types/components"
banzaiSimpleTypes "github.com/banzaicloud/banzai-types/components/database"
banzaiHelm "github.com/banzaicloud/banzai-types/components/helm"
banzaiConstants "github.com/banzaicloud/banzai-types/constants"
"github.com/banzaicloud/banzai-types/database"
banzaiUtils "github.com/banzaicloud/banzai-types/utils"
"github.com/banzaicloud/pipeline/auth"
"github.com/banzaicloud/pipeline/cloud"
"github.com/banzaicloud/pipeline/conf"
"github.com/banzaicloud/pipeline/helm"
"github.com/banzaicloud/pipeline/monitor"
"github.com/banzaicloud/pipeline/notify"
"github.com/ghodss/yaml"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/qor/auth/auth_identity"
sessionManager "github.com/qor/session/manager"
"github.com/spf13/viper"
"k8s.io/helm/pkg/timeconv"
"github.com/banzaicloud/pipeline/pods"
"github.com/banzaicloud/pipeline/utils"
"strconv"
"github.com/pkg/errors"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"strings"
"k8s.io/api/extensions/v1beta1"
)
//nodeInstanceType=m3.medium -d nodeInstanceSpotPrice=0.04 -d nodeMin=1 -d nodeMax=3 -d image=ami-6d48500b
//DeploymentType definition to describe a Helm deployment
type DeploymentType struct {
Name string `json:"name" binding:"required"`
ReleaseName string `json:"releasename"`
Version string `json:"version"`
Values interface{} `json:"values"`
}
//TODO: minCount and Maxcount should be optional, but one of them should be present
//Version of Pipeline
var Version string
//GitRev of Pipeline
var GitRev string
func initDatabase() {
host := viper.GetString("dev.host")
port := viper.GetString("dev.port")
user := viper.GetString("dev.user")
password := viper.GetString("dev.password")
dbName := viper.GetString("dev.dbname")
database.Init(host, port, user, password, dbName)
}
type optionsMiddleware struct {
}
func createOptionsMiddleware() *optionsMiddleware {
return &optionsMiddleware{}
}
func (middleware *optionsMiddleware) Response(context *gin.Context) {
if context.Request.Method == "OPTIONS" {
context.AbortWithStatus(http.StatusNoContent)
}
}
func main() {
if len(os.Args) > 1 && os.Args[1] == "--version" {
if GitRev == "" {
fmt.Println("version:", Version)
} else {
fmt.Printf("version: %s-%s\n", Version, GitRev)
}
os.Exit(0)
}
conf.Init()
initDatabase()
auth.Init()
banzaiUtils.LogInfo(banzaiConstants.TagInit, "Logger configured")
banzaiUtils.LogInfo(banzaiConstants.TagInit, "Create table(s):",
banzaiSimpleTypes.ClusterSimple.TableName(banzaiSimpleTypes.ClusterSimple{}),
banzaiSimpleTypes.AmazonClusterSimple.TableName(banzaiSimpleTypes.AmazonClusterSimple{}),
banzaiSimpleTypes.AzureClusterSimple.TableName(banzaiSimpleTypes.AzureClusterSimple{}),
banzaiSimpleTypes.GoogleClusterSimple.TableName(banzaiSimpleTypes.GoogleClusterSimple{}))
database.CreateTables(
&banzaiSimpleTypes.ClusterSimple{},
&banzaiSimpleTypes.AmazonClusterSimple{},
&banzaiSimpleTypes.AzureClusterSimple{},
&banzaiSimpleTypes.GoogleClusterSimple{},
&auth_identity.AuthIdentity{},
&auth.User{},
)
router := gin.Default()
config := cors.DefaultConfig()
config.AllowAllOrigins = true
config.AllowMethods = []string{"PUT", "DELETE", "GET", "POST", "OPTIONS"}
config.AllowHeaders = []string{"Origin", "Authorization", "Content-Type"}
config.ExposeHeaders = []string{"Content-Length"}
config.AllowCredentials = true
config.MaxAge = 12 * time.Hour
router.Use(cors.New(config))
router.Use(createOptionsMiddleware().Response)
if auth.IsEnabled() {
authHandler := gin.WrapH(auth.Auth.NewServeMux())
// We have to make the raw net/http handlers a bit Gin-ish
router.Use(gin.WrapH(sessionManager.SessionManager.Middleware(utils.NopHandler{})))
router.Use(gin.WrapH(auth.RedirectBack.Middleware(utils.NopHandler{})))
authGroup := router.Group("/auth/")
{
authGroup.GET("/*w", authHandler)
authGroup.GET("/*w/*w", authHandler)
}
}
v1 := router.Group("/api/v1/")
{
if auth.IsEnabled() {
v1.Use(auth.Auth0Handler)
}
v1.POST("/clusters", CreateCluster)
v1.GET("/status", Status)
v1.GET("/clusters", FetchClusters)
v1.GET("/clusters/:id", FetchCluster)
v1.PUT("/clusters/:id", UpdateCluster)
v1.DELETE("/clusters/:id", DeleteCluster)
v1.HEAD("/clusters/:id", GetClusterStatus)
v1.GET("/clusters/:id/config", FetchClusterConfig)
v1.GET("/clusters/:id/endpoints", ListEndpoints)
v1.GET("/clusters/:id/deployments", ListDeployments)
v1.POST("/clusters/:id/deployments", CreateDeployment)
v1.HEAD("/clusters/:id/deployments", GetTillerStatus)
v1.DELETE("/clusters/:id/deployments/:name", DeleteDeployment)
v1.PUT("/clusters/:id/deployments/:name", UpgradeDeployment)
v1.HEAD("/clusters/:id/deployments/:name", HelmDeploymentStatus)
v1.POST("/clusters/:id/helminit", InitHelmOnCluster)
v1.GET("/token", auth.GenerateToken)
}
notify.SlackNotify("API is already running")
router.Run(":9090")
}
//UpgradeDeployment - N/A
func UpgradeDeployment(c *gin.Context) {
return
}
//DeleteDeployment deletes a Helm deployment
func DeleteDeployment(c *gin.Context) {
banzaiUtils.LogInfo(banzaiConstants.TagDeleteDeployment, "Start delete deployment")
name := c.Param("name")
// --- [ Get cluster ] --- //
banzaiUtils.LogInfo(banzaiConstants.TagDeleteDeployment, "Get cluster")
cloudCluster, err := cloud.GetClusterFromDB(c)
if err != nil {
return
}
// --- [ Get K8S Config ] --- //
kubeConfig, err := cloud.GetK8SConfig(cloudCluster, c)
if err != nil {
return
}
banzaiUtils.LogInfo(banzaiConstants.TagDeleteDeployment, "Getting K8S Config Succeeded")
// --- [Delete deployment] --- //
banzaiUtils.LogInfo(banzaiConstants.TagDeleteDeployment, "Delete deployment")
err = helm.DeleteDeployment(name, kubeConfig)
if err != nil {
// error during delete deployment
banzaiUtils.LogWarn(banzaiConstants.TagDeleteDeployment, err.Error())
cloud.SetResponseBodyJson(c, http.StatusNotFound, gin.H{
cloud.JsonKeyStatus: http.StatusNotFound,
cloud.JsonKeyMessage: fmt.Sprintf("%s", err),
})
return
} else {
// delete succeeded
banzaiUtils.LogInfo(banzaiConstants.TagDeleteDeployment, "Delete deployment succeeded")
}
cloud.SetResponseBodyJson(c, http.StatusOK, gin.H{
cloud.JsonKeyStatus: http.StatusOK,
cloud.JsonKeyMessage: "success",
})
return
}
// CreateDeployment creates a Helm deployment
func CreateDeployment(c *gin.Context) {
banzaiUtils.LogInfo(banzaiConstants.TagCreateDeployment, "Start create deployment")
// --- [ Get cluster ] --- //
banzaiUtils.LogInfo(banzaiConstants.TagCreateDeployment, "Get cluster")
cloudCluster, err := cloud.GetClusterFromDB(c)
if err != nil {
return
}
banzaiUtils.LogInfo(banzaiConstants.TagCreateDeployment, "Get cluster succeeded")
banzaiUtils.LogInfo(banzaiConstants.TagCreateDeployment, "Bind json into DeploymentType struct")
var deployment DeploymentType
if err := c.BindJSON(&deployment); err != nil {
banzaiUtils.LogInfo(banzaiConstants.TagCreateDeployment, "Bind failed")
banzaiUtils.LogInfo(banzaiConstants.TagCreateDeployment, "Required field is empty."+err.Error())
cloud.SetResponseBodyJson(c, http.StatusBadRequest, gin.H{
cloud.JsonKeyStatus: http.StatusBadRequest,
cloud.JsonKeyMessage: "Required field is empty",
cloud.JsonKeyError: err,
})
return
}
banzaiUtils.LogDebug(banzaiConstants.TagCreateDeployment, fmt.Sprintf("Creating chart %s with version %s and release name %s", deployment.Name, deployment.Version, deployment.ReleaseName))
var values []byte = nil
if deployment.Values != "" {
parsedJSON, err := yaml.Marshal(deployment.Values)
if err != nil {
banzaiUtils.LogError(banzaiConstants.TagCreateDeployment, "Can't parse Values:", err)
}
values, err = yaml.JSONToYAML(parsedJSON)
if err != nil {
banzaiUtils.LogError(banzaiConstants.TagCreateDeployment, "Can't convert JSON to YAML:", err)
return
}
}
// --- [ Get K8S Config ] --- //
kubeConfig, err := cloud.GetK8SConfig(cloudCluster, c)
if err != nil {
return
}
banzaiUtils.LogInfo(banzaiConstants.TagCreateDeployment, "Getting K8S Config Succeeded")
banzaiUtils.LogDebug(banzaiConstants.TagCreateDeployment, "Custom values:", string(values))
banzaiUtils.LogInfo(banzaiConstants.TagCreateDeployment, "Create deployment")
release, err := helm.CreateDeployment(deployment.Name, deployment.ReleaseName, values, kubeConfig, cloudCluster.Name)
if err != nil {
banzaiUtils.LogWarn(banzaiConstants.TagCreateDeployment, "Error during create deployment.", err.Error())
cloud.SetResponseBodyJson(c, http.StatusNotFound, gin.H{
cloud.JsonKeyStatus: http.StatusNotFound,
cloud.JsonKeyMessage: fmt.Sprintf("%s", err),
})
return
} else {
banzaiUtils.LogInfo(banzaiConstants.TagCreateDeployment, "Create deployment succeeded")
}
releaseName := release.Release.Name
releaseNotes := release.Release.Info.Status.Notes
banzaiUtils.LogDebug(banzaiConstants.TagCreateDeployment, "Release name:", releaseName)
banzaiUtils.LogDebug(banzaiConstants.TagCreateDeployment, "Release notes:", releaseNotes)
//Get ingress with deployment prefix TODO
//Get local ingress address?
cloud.SetResponseBodyJson(c, http.StatusCreated, gin.H{
cloud.JsonKeyStatus: http.StatusCreated,
cloud.JsonKeyReleaseName: releaseName,
cloud.JsonKeyNotes: releaseNotes,
})
return
}
type EndpointResponse struct {
Endpoints []*EndpointItem `json:"endpoints"`
}
type EndpointItem struct {
Name string `json:"name"`
Host string `json:"host"`
EndPointURLs []*EndPointURLs `json:"urls"`
}
type EndPointURLs struct {
ServiceName string `json:"servicename"`
URL string `json:"url"`
}
type ErrorResponse struct {
Code int `json:"code"`
Message string `json:"message"`
}
// List service public endpoints
func ListEndpoints(c *gin.Context) {
const traefik = "traefik"
var endpointList []*EndpointItem
var endpointURLs []*EndPointURLs
// --- [ Get cluster ] ---- //
banzaiUtils.LogInfo(banzaiConstants.TagListDeployments, "Get cluster")
cloudCluster, err := cloud.GetClusterFromDB(c)
if err != nil {
return
}
banzaiUtils.LogInfo(banzaiConstants.TagListDeployments, "Getting cluster succeeded")
cloudType := cloudCluster.Cloud
// --- [ Get K8S Config ] --- //
kubeConfig, err := cloud.GetK8SConfig(cloudCluster, c)
if err != nil {
return
}
apiconfig, _ := clientcmd.Load(kubeConfig)
clientConfig := clientcmd.NewDefaultClientConfig(*apiconfig, &clientcmd.ConfigOverrides{})
config, err := clientConfig.ClientConfig()
if err != nil {
banzaiUtils.LogErrorf(banzaiConstants.TagKubernetes, "Could not create kubernetes client from config. %+v", config)
banzaiUtils.LogErrorf(banzaiConstants.TagKubernetes, "Error message: %+v", err)
c.JSON(http.StatusBadRequest, ErrorResponse{
Code: http.StatusBadRequest,
Message: fmt.Sprintf("create kubernetes client failed: %v", err),
})
return
}
client, err := kubernetes.NewForConfig(config)
if err != nil {
banzaiUtils.LogError(banzaiConstants.TagKubernetes, "Could not create kubernetes client from config.")
banzaiUtils.LogErrorf(banzaiConstants.TagKubernetes, "Error message: %+v", err)
c.JSON(http.StatusBadRequest, ErrorResponse{
Code: http.StatusBadRequest,
Message: fmt.Sprintf("create kubernetes client failed: %v", err),
})
return
}
serviceList, err := client.CoreV1().Services("").List(meta_v1.ListOptions{})
if err != nil {
banzaiUtils.LogErrorf(banzaiConstants.TagKubernetes, "Could not list kubernetes services, %+v", config)
banzaiUtils.LogErrorf(banzaiConstants.TagKubernetes, "Error message: %+v", err)
c.JSON(http.StatusInternalServerError, ErrorResponse{
Code: http.StatusInternalServerError,
Message: fmt.Sprintf("List kubernetes services failed: %+v", err),
})
return
}
for _, service := range serviceList.Items {
banzaiUtils.LogDebugf(banzaiConstants.TagKubernetes, "Service: %#v", service.Status)
if len(service.Status.LoadBalancer.Ingress) > 0 {
var publicIp string
switch cloudType {
case banzaiConstants.Amazon:
publicIp = service.Status.LoadBalancer.Ingress[0].Hostname
case banzaiConstants.Azure:
publicIp = service.Status.LoadBalancer.Ingress[0].IP
}
if strings.Contains(service.Spec.Selector["app"], traefik) {
ingressList, err := client.ExtensionsV1beta1().Ingresses("").List(meta_v1.ListOptions{})
if err != nil {
banzaiUtils.LogErrorf(banzaiConstants.TagKubernetes, "Could not list kubernetes ingresses, %+v", config)
banzaiUtils.LogErrorf(banzaiConstants.TagKubernetes, "Error message: %+v", err)
c.JSON(http.StatusInternalServerError, ErrorResponse{
Code: http.StatusInternalServerError,
Message: fmt.Sprintf("List kubernetes ingresses failed: %+v", err),
})
return
}
for _, ingress := range ingressList.Items {
banzaiUtils.LogDebugf(banzaiConstants.TagKubernetes, "Inspecting ingress: %s", ingress.Name)
if ingress.Annotations["kubernetes.io/ingress.class"] == traefik {
endpoints := getIngressEndpoints(publicIp, &ingress)
for i := 0; i < len(endpoints); i++ {
endpointURLs = append(endpointURLs, &(endpoints[i]))
}
}
}
}
endpointList = append(endpointList, &EndpointItem{
Name: service.Name,
Host: publicIp,
EndPointURLs: endpointURLs,
})
}
}
c.JSON(http.StatusOK, EndpointResponse{
Endpoints: endpointList,
})
}
// getIngressEndpoints iterates through all the rules->paths defined in the given Ingress object
// and returns a collection of EndPointURLs form it.
// The EndPointURLs struct is constructed as:
// EndPointURLs {
// ServiceName: {path from ingress rule}
// URL: http://{loadBalancerPublicHost}/{path from ingress rule}/
// }
func getIngressEndpoints(loadBalancerPublicHost string, ingress *v1beta1.Ingress) []EndPointURLs {
var endpointUrls []EndPointURLs
for _, ingressRule := range ingress.Spec.Rules {
for _, ingressPath := range ingressRule.HTTP.Paths {
path := ingressPath.Path
endpointUrls = append(endpointUrls,
EndPointURLs{
ServiceName: strings.TrimPrefix(path, "/"),
URL: fmt.Sprint("http://", loadBalancerPublicHost, path, "/"),
})
}
}
return endpointUrls
}
// ListDeployments lists a Helm deployment
func ListDeployments(c *gin.Context) {
banzaiUtils.LogInfo(banzaiConstants.TagListDeployments, "Start listing deployments")
// --- [ Get cluster ] ---- //
banzaiUtils.LogInfo(banzaiConstants.TagListDeployments, "Get cluster")
cloudCluster, err := cloud.GetClusterFromDB(c)
if err != nil {
return
}
banzaiUtils.LogInfo(banzaiConstants.TagListDeployments, "Getting cluster succeeded")
// --- [ Get K8S Config ] --- //
kubeConfig, err := cloud.GetK8SConfig(cloudCluster, c)
if err != nil {
return
}
banzaiUtils.LogInfo(banzaiConstants.TagListDeployments, "Getting K8S Config Succeeded")
// --- [ Get deployments ] --- //
banzaiUtils.LogInfo(banzaiConstants.TagListDeployments, "Get deployments")
response, err := helm.ListDeployments(nil, kubeConfig)
if err != nil {
banzaiUtils.LogWarn(banzaiConstants.TagListDeployments, "Error getting deployments. ", err)
cloud.SetResponseBodyJson(c, http.StatusNotFound, gin.H{
cloud.JsonKeyStatus: http.StatusNotFound,
cloud.JsonKeyMessage: fmt.Sprintf("%s", err),
})
return
}
var releases []gin.H
if len(response.Releases) > 0 {
for _, r := range response.Releases {
body := gin.H{
"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 {
msg := "There is no installed charts."
banzaiUtils.LogInfo(banzaiConstants.TagListDeployments, msg)
cloud.SetResponseBodyJson(c, http.StatusOK, gin.H{
cloud.JsonKeyMessage: msg,
})
return
}
cloud.SetResponseBodyJson(c, http.StatusOK, releases)
return
}
// CreateCluster creates a K8S cluster in the cloud
func CreateCluster(c *gin.Context) {
banzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, "Cluster creation is stared")
banzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, "Bind json into CreateClusterRequest struct")
// bind request body to struct
var createClusterBaseRequest banzaiTypes.CreateClusterRequest
if err := c.BindJSON(&createClusterBaseRequest); err != nil {
// bind failed
banzaiUtils.LogError(banzaiConstants.TagCreateCluster, "Required field is empty: "+err.Error())
cloud.SetResponseBodyJson(c, http.StatusBadRequest, gin.H{
cloud.JsonKeyStatus: http.StatusBadRequest,
cloud.JsonKeyMessage: "Required field is empty",
cloud.JsonKeyError: err,
})
return
} else {
banzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, "Bind succeeded")
}
banzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, "Searching entry with name:", createClusterBaseRequest.Name)
var savedCluster banzaiSimpleTypes.ClusterSimple
database.Query("SELECT * FROM "+banzaiSimpleTypes.ClusterSimple.TableName(savedCluster)+" WHERE name = ?;",
createClusterBaseRequest.Name,
&savedCluster)
if savedCluster.ID != 0 {
// duplicated entry
msg := "Duplicate entry '" + savedCluster.Name + "' for key 'name'"
banzaiUtils.LogError(banzaiConstants.TagCreateCluster, msg)
cloud.SetResponseBodyJson(c, http.StatusBadRequest, gin.H{
cloud.JsonKeyStatus: http.StatusBadRequest,
cloud.JsonKeyMessage: msg,
})
return
}
banzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, "No entity with this name exists. The creation is possible.")
cloudType := createClusterBaseRequest.Cloud
banzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, "Cloud type is ", cloudType)
var postHookFunctions []func(simple *banzaiSimpleTypes.ClusterSimple, c *gin.Context)
var createdCluster *banzaiSimpleTypes.ClusterSimple = nil
switch cloudType {
case banzaiConstants.Amazon:
// validate and create Amazon cluster
awsData := createClusterBaseRequest.Properties.CreateClusterAmazon
if isValid, err := awsData.Validate(); isValid && len(err) == 0 {
banzaiUtils.LogInfo(banzaiConstants.TagCreateCluster, "Validation is OK")
var isOk bool
isOk, createdCluster = cloud.CreateClusterAmazon(&createClusterBaseRequest, c)
if isOk {
// update prometheus config..
postHookFunctions = append(postHookFunctions, getConfigPostHookAmazon)
postHookFunctions = append(postHookFunctions, updatePrometheusPostHook)
postHookFunctions = append(postHookFunctions, installHelmPostHook)
postHookFunctions = append(postHookFunctions, installIngressControllerPostHook)
}
} else {
// not valid request
cloud.SetResponseBodyJson(c, http.StatusBadRequest, gin.H{
cloud.JsonKeyStatus: http.StatusBadRequest,
cloud.JsonKeyMessage: err,
})
}
case banzaiConstants.Azure:
// validate and create Azure cluster
aksData := createClusterBaseRequest.Properties.CreateClusterAzure
if isValid, err := aksData.Validate(); isValid && len(err) == 0 {
var isOk bool
isOk, createdCluster = cloud.CreateClusterAzure(&createClusterBaseRequest, c)
if isOk {
// update prometheus config..
postHookFunctions = append(postHookFunctions, getConfigPostHookAzure)
postHookFunctions = append(postHookFunctions, updatePrometheusPostHook)
postHookFunctions = append(postHookFunctions, installHelmPostHook)
postHookFunctions = append(postHookFunctions, installIngressControllerPostHook)
}
} else {
// not valid request
cloud.SetResponseBodyJson(c, http.StatusBadRequest, gin.H{
cloud.JsonKeyStatus: http.StatusBadRequest,
cloud.JsonKeyMessage: err,
})
}
case banzaiConstants.Google:
// validate and create Google cluster
gkeData := createClusterBaseRequest.Properties.CreateClusterGoogle
if isValid, err := gkeData.Validate(); isValid && err == nil {
var isOk bool
isOk, createdCluster = cloud.CreateClusterGoogle(&createClusterBaseRequest, c)
if isOk {
// update prometheus config..
postHookFunctions = append(postHookFunctions, getConfigPostHookGoogle)
postHookFunctions = append(postHookFunctions, updatePrometheusPostHook)
postHookFunctions = append(postHookFunctions, installHelmPostHook)
postHookFunctions = append(postHookFunctions, installIngressControllerPostHook)
}
} else {
// not valid request
cloud.SetResponseBodyJson(c, http.StatusBadRequest, gin.H{
cloud.JsonKeyStatus: http.StatusBadRequest,
cloud.JsonKeyMessage: err,
})
}
default:
// wrong cloud type
cloud.SendNotSupportedCloudResponse(c, banzaiConstants.TagCreateCluster)
}
//TODO: need common cluster return with basic attributes like Name
go RunPostHooks(postHookFunctions, createdCluster, c)
}
// Calls posthook functions with created cluster
func RunPostHooks(functionList []func(simple *banzaiSimpleTypes.ClusterSimple, c *gin.Context), createdCluster *banzaiSimpleTypes.ClusterSimple, c *gin.Context) {
for _, i := range functionList {
i(createdCluster, c)
}
}
//DeleteAll deletes all Helm deployment
func deleteAllDeployment(kubeconfig []byte) error {
var logTag = "DeleteAllDeployment"
banzaiUtils.LogInfo(logTag, "Getting deployments....")
releaseResp, err := helm.ListDeployments(nil, kubeconfig)
if err != nil {
return err
}
banzaiUtils.LogInfo(logTag, "Retrieving deployments succeeded.")
banzaiUtils.LogInfo(logTag, "Starting deleting deployments")
for _, r := range releaseResp.Releases {
banzaiUtils.LogInfo(logTag, "Trying to delete deployment", r.Name)
err := helm.DeleteDeployment(r.Name, kubeconfig)
if err != nil {
return err
}
banzaiUtils.LogInfo(logTag, "Deployment", r.Name, "successfully deleted")
}
return nil
}
// DeleteCluster deletes a K8S cluster from the cloud
func DeleteCluster(c *gin.Context) {
banzaiUtils.LogInfo(banzaiConstants.TagDeleteCluster, "Delete cluster start")
cl, err := cloud.GetClusterFromDB(c)
if err != nil {
return
}
if cl.Cloud == banzaiConstants.Amazon {
banzaiUtils.LogInfo(banzaiConstants.TagDeleteCluster, "Start delete created helm charts")
cloudCluster, err := cloud.GetClusterWithDbCluster(cl, c)
if err != nil {
cloud.SetResponseBodyJson(c, http.StatusInternalServerError, gin.H{
cloud.JsonKeyStatus: http.StatusInternalServerError,
cloud.JsonKeyMessage: err,
})
return
}
banzaiUtils.LogInfo(banzaiConstants.TagDeleteCluster, "Get aws cluster succeeded")
config, err := cloud.GetAmazonKubernetesConfig(cloudCluster)
if err != nil {
cloud.SetResponseBodyJson(c, http.StatusInternalServerError, gin.H{
cloud.JsonKeyStatus: http.StatusInternalServerError,
cloud.JsonKeyMessage: err,
})
return
}
err = deleteAllDeployment(config)
if err != nil {
banzaiUtils.LogError(banzaiConstants.TagDeleteCluster, "Error during deleting all deployments #", err.Error())
} else {
banzaiUtils.LogInfo(banzaiConstants.TagDeleteCluster, "Deployments successfully deleted")
}
}
if cloud.DeleteCluster(cl, c) {
// cluster delete success
banzaiUtils.LogInfof(banzaiConstants.TagDeleteCluster, "Cluster %s delete succeeded!", cl.Name)
// delete state store
cloud.DestroyStateStore(cl)
// delete from db
if cloud.DeleteFromDb(cl, c) {
// update Prometheus config
updatePrometheus()
}
}
}
func installIngressControllerPostHook(createdCluster *banzaiSimpleTypes.ClusterSimple, c *gin.Context) {
// --- [ Get K8S Config ] --- //
kubeConfig, err := cloud.GetK8SConfig(createdCluster, c)
if err != nil {
return
}
logTag := "InstallIngressController"
banzaiUtils.LogInfo(logTag, "Getting K8S Config Succeeded")
deploymentName := "banzaicloud-stable/pipeline-cluster-ingress"
releaseName := "pipeline"
_, err = helm.CreateDeployment(deploymentName, releaseName, nil, kubeConfig, createdCluster.Name)
if err != nil {
banzaiUtils.LogErrorf(logTag, "Deploying '%s' failed due to: ", deploymentName)
banzaiUtils.LogErrorf(logTag, "%s", err.Error())
return
}
banzaiUtils.LogInfof(logTag, "'%s' installed", deploymentName)
}
//PostHook functions with func(*cluster.Cluster) signature
func getConfigPostHookAmazon(cs *banzaiSimpleTypes.ClusterSimple, c *gin.Context) {
createdCluster, err := cloud.GetClusterWithDbCluster(cs, c)
if err != nil {
banzaiUtils.LogErrorf("PostHook", "error during get config post hook: %s", createdCluster)
return
}
cloud.RetryGetConfig(createdCluster, "")
}
func getConfigPostHookAzure(createdCluster *banzaiSimpleTypes.ClusterSimple, c *gin.Context) {
cloud.GetAzureK8SConfig(createdCluster, c)
}
func getConfigPostHookGoogle(createdCluster *banzaiSimpleTypes.ClusterSimple, _ *gin.Context) {
cloud.GetGoogleK8SConfig(createdCluster, nil)
}
func updatePrometheusPostHook(_ *banzaiSimpleTypes.ClusterSimple, _ *gin.Context) {
updatePrometheus()
}
func installHelmPostHook(createdCluster *banzaiSimpleTypes.ClusterSimple, c *gin.Context) {
logTag := "InstallHelmPostHook"
retryAttempts := viper.GetInt(banzaiConstants.HELM_RETRY_ATTEMPT_CONFIG)
retrySleepSeconds := viper.GetInt(banzaiConstants.HELM_RETRY_SLEEP_SECONDS)
kce := fmt.Sprintf("./statestore/%s/config", createdCluster.Name)
banzaiUtils.LogInfof(banzaiConstants.TagHelmInstall, "Set $KUBECONFIG env to %s", kce)
os.Setenv("KUBECONFIG", kce)
helmInstall := &banzaiHelm.Install{
Namespace: "kube-system",
ServiceAccount: "tiller",
ImageSpec: "gcr.io/kubernetes-helm/tiller:v2.7.2",
}
err := helm.RetryHelmInstall(helmInstall, createdCluster.Cloud, createdCluster.Name)
if err == nil {
// --- [ Get K8S Config ] --- //
kubeConfig, err := cloud.GetK8SConfig(createdCluster, c)
if err != nil {
return
}
banzaiUtils.LogInfo(logTag, "Getting K8S Config Succeeded")
// --- [ List deployments ] ---- //
for i := 0; i <= retryAttempts; i++ {
banzaiUtils.LogDebugf(logTag, "Waiting for tiller to come up %d/%d", i, retryAttempts)
_, err = helm.GetHelmClient(kubeConfig)
if err == nil {
return
}
time.Sleep(time.Duration(retrySleepSeconds) * time.Second)
}
banzaiUtils.LogError(logTag, "Timeout during waiting for tiller to get ready")
}
}
func updatePrometheus() {
err := monitor.UpdatePrometheusConfig()
if err != nil {
banzaiUtils.LogWarn(banzaiConstants.TagPrometheus, "Could not update prometheus configmap: %v", err)
}
}
// FetchClusters fetches all the K8S clusters from the cloud
func FetchClusters(c *gin.Context) {
banzaiUtils.LogInfo(banzaiConstants.TagListClusters, "Start listing clusters")
var clusters []banzaiSimpleTypes.ClusterSimple
var response []*cloud.ClusterRepresentation
database.Find(&clusters)
if len(clusters) <= 0 {
banzaiUtils.LogInfo(banzaiConstants.TagListClusters, "No clusters found")
cloud.SetResponseBodyJson(c, http.StatusNotFound, gin.H{
cloud.JsonKeyStatus: http.StatusNotFound,
cloud.JsonKeyMessage: "No clusters found!",
})
return
}
for _, cl := range clusters {
clust := cloud.GetClusterRepresentation(&cl)
if clust != nil {
banzaiUtils.LogInfo(banzaiConstants.TagListClusters, fmt.Sprintf("Append %#v cluster representation to response", clust))
response = append(response, clust)
}
}
cloud.SetResponseBodyJson(c, http.StatusOK, gin.H{
cloud.JsonKeyStatus: http.StatusOK,
cloud.JsonKeyData: response,
})
}
// FetchCluster fetch a K8S cluster in the cloud
func FetchCluster(c *gin.Context) {
banzaiUtils.LogInfo(banzaiConstants.TagGetClusterInfo, "Start getting cluster info")
cl, err := cloud.GetClusterFromDB(c)
if err != nil {
return
}
cloud.FetchClusterInfo(cl, c)
}
// UpdateCluster updates a K8S cluster in the cloud (e.g. autoscale)
func UpdateCluster(c *gin.Context) {
banzaiUtils.LogInfo(banzaiConstants.TagGetClusterInfo, "Bind json into UpdateClusterRequest struct")
// bind request body to UpdateClusterRequest struct
var updateRequest banzaiTypes.UpdateClusterRequest
if err := c.BindJSON(&updateRequest); err != nil {
// bind failed, required field(s) empty
banzaiUtils.LogWarn(banzaiConstants.TagGetClusterInfo, "Bind failed.", err.Error())
cloud.SetResponseBodyJson(c, http.StatusBadRequest, gin.H{
cloud.JsonKeyStatus: http.StatusBadRequest,
cloud.JsonKeyMessage: "Required field is empty",
cloud.JsonKeyError: err,
})
return
}
banzaiUtils.LogInfo(banzaiConstants.TagGetClusterInfo, "Load cluster from database")
// load cluster from db
cl, err := cloud.GetClusterFromDB(c)
if err != nil {
return
}
banzaiUtils.LogInfo(banzaiConstants.TagGetClusterInfo, "Start updating cluster:", cl.Name)
banzaiUtils.LogInfo(banzaiConstants.TagGetClusterInfo, "Update request: ", updateRequest)
cloudType := cl.Cloud
switch cloudType {
case banzaiConstants.Amazon:
// read amazon props from amazon_cluster_properties table
banzaiUtils.LogInfo(banzaiConstants.TagGetClusterInfo, "Load amazon props from db")
database.SelectFirstWhere(&cl.Amazon, banzaiSimpleTypes.AmazonClusterSimple{ClusterSimpleId: cl.ID})
case banzaiConstants.Azure:
// read azure props from azure_cluster_properties table
banzaiUtils.LogInfo(banzaiConstants.TagGetClusterInfo, "Load azure props from db")
database.SelectFirstWhere(&cl.Azure, banzaiSimpleTypes.AzureClusterSimple{ClusterSimpleId: cl.ID})
case banzaiConstants.Google:
// read google props from google_cluster_properties table
banzaiUtils.LogInfo(banzaiConstants.TagGetClusterInfo, "Load Google props from db")
database.SelectFirstWhere(&cl.Google, banzaiSimpleTypes.GoogleClusterSimple{ClusterSimpleId: cl.ID})
default:
// not supported cloud type
banzaiUtils.LogWarn(banzaiConstants.TagGetClusterInfo, "Not supported cloud type")
cloud.SendNotSupportedCloudResponse(c, banzaiConstants.TagUpdateCluster)
return
}
banzaiUtils.LogInfo(banzaiConstants.TagGetClusterInfo, "Cluster to modify: ", cl)
if isValid, err := updateRequest.Validate(*cl); isValid && len(err) == 0 {
// validation OK
banzaiUtils.LogInfo(banzaiConstants.TagGetClusterInfo, "Validate is OK")
if cloud.UpdateClusterInCloud(c, &updateRequest, *cl) {
// cluster updated successfully in cloud
// update prometheus config..
updatePrometheus()
}
} else {
// validation failed
banzaiUtils.LogInfo(banzaiConstants.TagGetClusterInfo, "Validation failed")
cloud.SetResponseBodyJson(c, http.StatusBadRequest, gin.H{
cloud.JsonKeyStatus: http.StatusBadRequest,
cloud.JsonKeyMessage: err,
})
}
}
// FetchClusterConfig fetches a cluster config
func FetchClusterConfig(c *gin.Context) {
banzaiUtils.LogInfo(banzaiConstants.TagFetchClusterConfig, "Start fetching cluster config")
// --- [ Get cluster ] --- //
banzaiUtils.LogInfo(banzaiConstants.TagFetchClusterConfig, "Get cluster from database")
cl, err := cloud.GetClusterFromDB(c)
if err != nil {
return
}
banzaiUtils.LogInfo(banzaiConstants.TagFetchClusterConfig, "Get cluster from database succeeded")
banzaiUtils.LogInfo(banzaiConstants.TagFetchClusterConfig, "Cluster type", cl.Cloud)
switch cl.Cloud {
case banzaiConstants.Amazon:
cloud.GetAmazonK8SConfig(cl, c)
case banzaiConstants.Azure:
cloud.GetAzureK8SConfig(cl, c)
case banzaiConstants.Google:
cloud.GetGoogleK8SConfig(cl, c)
default:
cloud.SendNotSupportedCloudResponse(c, banzaiConstants.TagFetchClusterConfig)
}
}
// GetClusterStatus retrieves the cluster status
func GetClusterStatus(c *gin.Context) {
banzaiUtils.LogInfo(banzaiConstants.TagGetClusterStatus, "Start getting cluster status")
// --- [ Get cluster ] --- //
cloudCluster, err := cloud.GetClusterSimple(c)
if err != nil {
banzaiUtils.LogWarn(banzaiConstants.TagGetClusterStatus, "Error during get cluster", err.Error())
cloud.SetResponseBodyJson(c, http.StatusBadRequest, gin.H{
cloud.JsonKeyStatus: http.StatusBadRequest,
cloud.JsonKeyMessage: err.Error(),
})
return
} else {
banzaiUtils.LogInfo(banzaiConstants.TagGetClusterStatus, "Getting cluster status succeeded")
}
cloudType := cloudCluster.Cloud
banzaiUtils.LogInfo(banzaiConstants.TagGetClusterStatus, "Cloud type is", cloudType)
switch cloudType {
case banzaiConstants.Amazon:
cloud.GetAmazonClusterStatus(cloudCluster, c)
case banzaiConstants.Azure:
cloud.GetAzureClusterStatus(cloudCluster, c)
case banzaiConstants.Google:
cloud.GetGoogleClusterStatus(cloudCluster, c)
default:
cloud.SendNotSupportedCloudResponse(c, banzaiConstants.TagGetClusterStatus)
return
}
}
// GetTillerStatus checks if tiller ready to accept deployments
func GetTillerStatus(c *gin.Context) {
banzaiUtils.LogInfo(banzaiConstants.TagGetTillerStatus, "Start getting tiller status")
// --- [ Get cluster ] --- //
banzaiUtils.LogInfo(banzaiConstants.TagGetTillerStatus, "Get cluster")
cloudCluster, err := cloud.GetClusterFromDB(c)
if err != nil {
return
} else {
banzaiUtils.LogInfo(banzaiConstants.TagGetTillerStatus, "Get cluster succeeded:", cloudCluster)
}
// --- [ Get K8S Config ] --- //
kubeConfig, err := cloud.GetK8SConfig(cloudCluster, c)
if err != nil {
return
}
banzaiUtils.LogInfo(banzaiConstants.TagGetTillerStatus, "Getting K8S Config Succeeded")
// --- [ List deployments ] ---- //
_, err = helm.ListDeployments(nil, kubeConfig)
if err != nil {
banzaiUtils.LogWarn(banzaiConstants.TagGetTillerStatus, "Error during getting deployments.", err.Error())
cloud.SetResponseBodyJson(c, http.StatusServiceUnavailable, gin.H{
cloud.JsonKeyStatus: http.StatusServiceUnavailable,
cloud.JsonKeyMessage: "Tiller not available",
})
} else {
banzaiUtils.LogInfo(banzaiConstants.TagGetTillerStatus, "Tiller available")
cloud.SetResponseBodyJson(c, http.StatusOK, gin.H{
cloud.JsonKeyStatus: http.StatusOK,
cloud.JsonKeyMessage: "Tiller available",
})
}
return
}
// FetchDeploymentStatus check the status of the Helm deployment
func FetchDeploymentStatus(c *gin.Context) {
banzaiUtils.LogInfo(banzaiConstants.TagFetchDeploymentStatus, "Start fetching deployment status")
name := c.Param("name")
banzaiUtils.LogInfo(banzaiConstants.TagFetchDeploymentStatus, "Get deployment with name:", name)
// --- [ Get cluster ] --- //
cloudCluster, err := cloud.GetClusterFromDB(c)
if err != nil {