/
server.go
1102 lines (918 loc) · 33.8 KB
/
server.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 server
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/apis/extensions"
"k8s.io/kubernetes/pkg/labels"
k8sClient "k8s.io/kubernetes/pkg/client/unversioned"
"github.com/30x/enrober/pkg/helper"
)
const (
apigeeKVMName = "shipyard-routing"
apigeeKVMPKName = "x-routing-api-key"
)
//Global Vars
var (
//Kubernetes Client
client k8sClient.Client
//Global Regex
validIPAddressRegex = regexp.MustCompile(`^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$`)
validHostnameRegex = regexp.MustCompile(`^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$`)
//Env Name Regex
envNameRegex = regexp.MustCompile(`\w+\:\w+`)
//Privileged container flag
allowPrivilegedContainers bool
//Namespace Isolation
isolateNamespace bool
//Apigee KVM check
apigeeKVM bool
)
//NOTE: routing secret should probably be a configurable name
//NewServer creates a new server
func NewServer() (server *Server) {
router := mux.NewRouter()
router.Path("/environments").Methods("POST").HandlerFunc(createEnvironment)
router.Path("/environments/{org}:{env}").Methods("GET").HandlerFunc(getEnvironment)
router.Path("/environments/{org}:{env}").Methods("PATCH").HandlerFunc(updateEnvironment)
router.Path("/environments/{org}:{env}").Methods("DELETE").HandlerFunc(deleteEnvironment)
router.Path("/environments/{org}:{env}/deployments").Methods("POST").HandlerFunc(createDeployment)
router.Path("/environments/{org}:{env}/deployments").Methods("GET").HandlerFunc(getDeployments)
router.Path("/environments/{org}:{env}/deployments/{deployment}").Methods("GET").HandlerFunc(getDeployment)
router.Path("/environments/{org}:{env}/deployments/{deployment}").Methods("PATCH").HandlerFunc(updateDeployment)
router.Path("/environments/{org}:{env}/deployments/{deployment}").Methods("DELETE").HandlerFunc(deleteDeployment)
router.Path("/environments/{org}:{env}/deployments/{deployment}/logs").Methods("GET").HandlerFunc(getDeploymentLogs)
// Health Check
router.Path("/environments/status/").Methods("GET").HandlerFunc(getStatus)
router.Path("/environments/status").Methods("GET").HandlerFunc(getStatus)
loggedRouter := handlers.CombinedLoggingHandler(os.Stdout, router)
server = &Server{
Router: loggedRouter,
}
return server
}
// Copied from https://github.com/30x/authsdk/blob/master/apigee.go#L19
//
// TODO: Turn this into some Go-based Apigee client/SDK to replace authsdk
var apigeeApiHost string
func init() {
envVar := os.Getenv("AUTH_API_HOST")
if envVar == "" {
apigeeApiHost = "api.enterprise.apigee.com"
} else {
apigeeApiHost = envVar
}
}
//Start the server
func (server *Server) Start() error {
return http.ListenAndServe(":9000", server.Router)
}
//createEnvironment creates a kubernetes namespace and secret
func createEnvironment(w http.ResponseWriter, r *http.Request) {
//Decode passed JSON body
var tempJSON environmentPost
err := json.NewDecoder(r.Body).Decode(&tempJSON)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
helper.LogError.Printf("Error decoding JSON Body: %s\n", err)
return
}
//Make sure they passed a valid environment name of form {org}:{env}
if !envNameRegex.MatchString(tempJSON.EnvironmentName) {
http.Error(w, "Invalid environment name", http.StatusInternalServerError)
helper.LogError.Printf("Not a valid environment name: %s\n", tempJSON.EnvironmentName)
return
}
//Parse environment name into 2 parts
nameSlice := strings.Split(tempJSON.EnvironmentName, ":")
apigeeOrgName := nameSlice[0]
apigeeEnvName := nameSlice[1]
if os.Getenv("DEPLOY_STATE") == "PROD" {
if !helper.ValidAdmin(apigeeOrgName, w, r) {
return
}
}
// transform EnvironmentName into acceptable k8s namespace name
tempJSON.EnvironmentName = apigeeOrgName + "-" + apigeeEnvName
//space delimited annotation of valid hostnames
var hostsList bytes.Buffer
for index, value := range tempJSON.HostNames {
//Verify each Hostname matches regex
validIP := validIPAddressRegex.MatchString(value)
validHost := validHostnameRegex.MatchString(value)
if !(validIP || validHost) {
//Regex didn't match
http.Error(w, "Invalid Hostname", http.StatusInternalServerError)
helper.LogError.Printf("Not a valid hostname: %s\n", value)
return
}
if index == 0 {
hostsList.WriteString(value)
} else {
hostsList.WriteString(" " + value)
}
}
uniqueHosts, err := helper.UniqueHostNames(tempJSON.HostNames, client)
if err != nil {
errorMessage := fmt.Sprintf("Error in UniqueHostNames: %v", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage + "\n")
return
}
if !uniqueHosts {
errorMessage := "Duplicate HostNames"
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
//Generate both a public and private key
privateKey, err := helper.GenerateRandomString(32)
publicKey, err := helper.GenerateRandomString(32)
if err != nil {
helper.LogError.Printf("Error generating random string: %v\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
//Should attempt KVM creation before creating k8s objects
if apigeeKVM {
httpClient := &http.Client{}
//construct URL
apigeeKVMURL := fmt.Sprintf("https://%s/v1/organizations/%s/environments/%s/keyvaluemaps", apigeeApiHost, apigeeOrgName, apigeeEnvName)
//create JSON body
kvmBody := apigeeKVMBody{
Name: apigeeKVMName,
Entry: []apigeeKVMEntry{
apigeeKVMEntry{
Name: apigeeKVMPKName,
Value: base64.StdEncoding.EncodeToString([]byte(publicKey)),
},
},
}
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(kvmBody)
req, err := http.NewRequest("POST", apigeeKVMURL, b)
if err != nil {
errorMessage := fmt.Sprintf("Unable to create request (Create KVM): %v", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage + "\n")
return
}
//Must pass through the authz header
req.Header.Add("Authorization", r.Header.Get("Authorization"))
req.Header.Add("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
errorMessage := fmt.Sprintf("Error creating Apigee KVM: %v", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage + "\n")
return
}
defer resp.Body.Close()
// If the response was not a 201, we need to check if the response was a 409 because this means the KVM exists
// already and we'll need to update the KVM value(s).
if resp.StatusCode != 201 {
var retryFlag bool
// If the KVM already exists, we need to update its value(s).
if resp.StatusCode == 409 {
b2 := new(bytes.Buffer)
updateKVMURL := fmt.Sprintf("%s/%s", apigeeKVMURL, apigeeKVMName) // Use non-CPS endpoint by default
if isCPSEnabledForOrg(apigeeOrgName, r.Header.Get("Authorization")) {
// When using CPS, the API endpoint is different and instead of sending the whole KVM body, we can only send
// the KVM entry to update. (This will work for now since we are only persisting one key but in the future
// we might need to update this to make N calls, one per key.)
updateKVMURL = fmt.Sprintf("%s/entries/%s", updateKVMURL, apigeeKVMPKName)
json.NewEncoder(b2).Encode(kvmBody.Entry[0])
} else {
// When not using CPS, send the whole KVM body to update all keys in the KVM.
json.NewEncoder(b2).Encode(kvmBody) // Non-CPS takes the whole payload
}
updateKVMReq, err := http.NewRequest("POST", updateKVMURL, b2)
if err != nil {
errorMessage := fmt.Sprintf("Unable to create request (Update KVM): %v", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage + "\n")
return
}
fmt.Printf("The update KVM URL: %v\n", updateKVMReq.URL.String())
updateKVMReq.Header.Add("Authorization", r.Header.Get("Authorization"))
updateKVMReq.Header.Add("Content-Type", "application/json")
resp2, err := httpClient.Do(updateKVMReq)
if err != nil {
errorMessage := fmt.Sprintf("Error creating entry in existing Apigee KVM: %v", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage + "\n")
return
}
defer resp2.Body.Close()
var updateKVMRes retryResponse
//Decode response
err = json.NewDecoder(resp2.Body).Decode(&updateKVMRes)
if err != nil {
fmt.Printf("Failed to decode response: %v\n", err)
http.Error(w, "Failed to decode response", http.StatusInternalServerError)
return
}
// Updating a KVM returns a 200 on success so if it's not a 200, it's a failure
if resp2.StatusCode != 200 {
errorMessage := fmt.Sprintf("Couldn't create KVM entry (Status Code: %d): %v", resp2.StatusCode, updateKVMRes.Message)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage + "\n")
return
}
retryFlag = true
}
if !retryFlag {
errorMessage := fmt.Sprintf("Expected 201 or 409, got: %v", resp.StatusCode)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage + "\n")
return
}
}
}
//Should create an annotation object and pass it into the object literal
nsAnnotations := make(map[string]string)
nsAnnotations["hostNames"] = hostsList.String()
//Add network policy annotation if we are isolating namespaces
if isolateNamespace {
nsAnnotations["net.beta.kubernetes.io/network-policy"] = `{"ingress": {"isolation": "DefaultDeny"}}`
}
//NOTE: Probably shouldn't create annotation if there are no hostNames
nsObject := &api.Namespace{
ObjectMeta: api.ObjectMeta{
Name: tempJSON.EnvironmentName,
Labels: map[string]string{
"runtime": "shipyard",
"organization": apigeeOrgName,
"environment": apigeeEnvName,
"name": tempJSON.EnvironmentName,
},
Annotations: nsAnnotations,
},
}
//Create Namespace
createdNs, err := client.Namespaces().Create(nsObject)
if err != nil {
errorMessage := fmt.Sprintf("Error creating namespace: %v", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage + "\n")
return
}
//Print to console for logging
helper.LogInfo.Printf("Created Namespace: %s\n", createdNs.GetName())
tempSecret := api.Secret{
ObjectMeta: api.ObjectMeta{
Name: "routing",
},
Data: map[string][]byte{},
Type: "Opaque",
}
tempSecret.Data["public-api-key"] = []byte(publicKey)
tempSecret.Data["private-api-key"] = []byte(privateKey)
//Create Secret
secret, err := client.Secrets(tempJSON.EnvironmentName).Create(&tempSecret)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
helper.LogError.Printf("Error creating secret: %s\n", err)
err = client.Namespaces().Delete(createdNs.GetName())
if err != nil {
helper.LogError.Printf("Failed to cleanup namespace\n")
return
}
helper.LogError.Printf("Deleted namespace due to secret creation error\n")
return
}
//Print to console for logging
helper.LogInfo.Printf("Created Secret: %s\n", secret.GetName())
var jsResponse environmentResponse
jsResponse.Name = tempJSON.EnvironmentName
jsResponse.PrivateSecret = secret.Data["private-api-key"]
jsResponse.PublicSecret = secret.Data["public-api-key"]
jsResponse.HostNames = tempJSON.HostNames
js, err := json.Marshal(jsResponse)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
helper.LogError.Printf("Error marshalling response JSON: %s\n", err)
return
}
//Create absolute path for Location header
locationURL := "/environments/" + apigeeOrgName + ":" + apigeeEnvName
w.Header().Add("Location", locationURL)
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(201)
w.Write(js)
}
//getEnvironment returns a kubernetes namespace matching the given environmentGroupID and environmentName
func getEnvironment(w http.ResponseWriter, r *http.Request) {
pathVars := mux.Vars(r)
if os.Getenv("DEPLOY_STATE") == "PROD" {
if !helper.ValidAdmin(pathVars["org"], w, r) {
return
}
}
getNs, err := client.Namespaces().Get(pathVars["org"] + "-" + pathVars["env"])
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
helper.LogError.Printf("Error getting existing Environment: %v\n", err)
return
}
getSecret, err := client.Secrets(pathVars["org"] + "-" + pathVars["env"]).Get("routing")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
helper.LogError.Printf("Error getting existing Secret: %v\n", err)
return
}
var jsResponse environmentResponse
jsResponse.Name = getNs.Name
jsResponse.PrivateSecret = getSecret.Data["private-api-key"]
jsResponse.PublicSecret = getSecret.Data["public-api-key"]
jsResponse.HostNames = strings.Split(getNs.Annotations["hostNames"], " ")
js, err := json.Marshal(jsResponse)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
helper.LogError.Printf("Error marshalling response JSON: %v\n", err)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(js)
helper.LogInfo.Printf("Got Namespace: %s\n", getNs.GetName())
}
//updateEnvironment modifies the hostNames array on an existing environment
func updateEnvironment(w http.ResponseWriter, r *http.Request) {
pathVars := mux.Vars(r)
if os.Getenv("DEPLOY_STATE") == "PROD" {
if !helper.ValidAdmin(pathVars["org"], w, r) {
return
}
}
//Get the existing namespace
getNs, err := client.Namespaces().Get(pathVars["org"] + "-" + pathVars["env"])
if err != nil {
errorMessage := fmt.Sprintf("Namespace %s doesn't exist\n", pathVars["org"]+"-"+pathVars["env"])
helper.LogError.Printf(errorMessage)
http.Error(w, errorMessage, http.StatusNotFound)
return
}
//Get the existing routing secret
getSecret, err := client.Secrets(pathVars["org"] + "-" + pathVars["env"]).Get("routing")
if err != nil {
errorMessage := fmt.Sprintf("Failed to get existing routing secret on %s namespace\n", pathVars["org"]+"-"+pathVars["env"])
helper.LogError.Printf(errorMessage)
http.Error(w, errorMessage, http.StatusInternalServerError)
return
}
//Decode passed JSON body
var tempJSON environmentPatch
err = json.NewDecoder(r.Body).Decode(&tempJSON)
if err != nil {
errorMessage := fmt.Sprintf("Error decoding JSON Body: %s\n", err)
helper.LogError.Printf(errorMessage)
http.Error(w, errorMessage, http.StatusInternalServerError)
return
}
//space delimited annotation of valid hostnames
var hostsList bytes.Buffer
//Take new json and put it into the space delimited string
for index, value := range tempJSON.HostNames {
//Verify each Hostname matches regex
validIP := validIPAddressRegex.MatchString(value)
validHost := validHostnameRegex.MatchString(value)
if !(validIP || validHost) {
//Regex didn't match
http.Error(w, "Invalid Hostname", http.StatusInternalServerError)
helper.LogError.Printf("Not a valid hostname: %s\n", value)
return
}
if index == 0 {
hostsList.WriteString(value)
} else {
hostsList.WriteString(" " + value)
}
}
//If hostNames are same as old then just give 200 back
if bytes.Equal(hostsList.Bytes(), []byte(getNs.Annotations["hostNames"])) {
helper.LogInfo.Printf("Nothing to be updated\n")
return
}
uniqueHosts, err := helper.UniqueHostNames(tempJSON.HostNames, client)
if err != nil {
errorMessage := fmt.Sprintf("Error in UniqueHostNames: %v", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
if !uniqueHosts {
errorMessage := "Duplicate HostNames"
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
getNs.Annotations["hostNames"] = hostsList.String()
updateNS, err := client.Namespaces().Update(getNs)
if err != nil {
errorMessage := fmt.Sprintf("Failed to update existing namespace '%s'\n", getNs)
helper.LogError.Printf(errorMessage)
http.Error(w, errorMessage, http.StatusInternalServerError)
return
}
helper.LogInfo.Printf("Updated hostNames: %s\n", updateNS.Annotations["hostNames"])
var jsResponse environmentResponse
jsResponse.Name = pathVars["environment"]
jsResponse.PrivateSecret = getSecret.Data["private-api-key"]
jsResponse.PublicSecret = getSecret.Data["public-api-key"]
jsResponse.HostNames = tempJSON.HostNames
js, err := json.Marshal(jsResponse)
if err != nil {
errorMessage := fmt.Sprintf("Couldn't marshall namespace: %s\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(js)
}
//deleteEnvironment deletes a kubernetes namespace matching the given org and env name
func deleteEnvironment(w http.ResponseWriter, r *http.Request) {
pathVars := mux.Vars(r)
if os.Getenv("DEPLOY_STATE") == "PROD" {
if !helper.ValidAdmin(pathVars["org"], w, r) {
return
}
}
err := client.Namespaces().Delete(pathVars["org"] + "-" + pathVars["env"])
if err != nil {
errorMessage := fmt.Sprintf("Error in deleteEnvironment: %v\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
w.WriteHeader(204)
helper.LogInfo.Printf("Deleted Namespace: %s\n", pathVars["org"]+"-"+pathVars["env"])
}
//getDeployments returns a list of all deployments matching the given org and env name
func getDeployments(w http.ResponseWriter, r *http.Request) {
pathVars := mux.Vars(r)
if os.Getenv("DEPLOY_STATE") == "PROD" {
if !helper.ValidAdmin(pathVars["org"], w, r) {
return
}
}
depList, err := client.Deployments(pathVars["org"] + "-" + pathVars["env"]).List(api.ListOptions{
LabelSelector: labels.Everything(),
})
if err != nil {
errorMessage := fmt.Sprintf("Error retrieving deployment list: %v\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
js, err := json.Marshal(depList)
if err != nil {
errorMessage := fmt.Sprintf("Error marshalling deployment list: %v\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(js)
for _, value := range depList.Items {
helper.LogInfo.Printf("Got Deployment: %s\n", value.GetName())
}
}
//createDeployment creates a deployment in the given environment(namespace) with the given environmentGroupID based on the given deploymentBody
func createDeployment(w http.ResponseWriter, r *http.Request) {
pathVars := mux.Vars(r)
if os.Getenv("DEPLOY_STATE") == "PROD" {
if !helper.ValidAdmin(pathVars["org"], w, r) {
return
}
}
//Decode passed JSON body
var tempJSON deploymentPost
err := json.NewDecoder(r.Body).Decode(&tempJSON)
if err != nil {
errorMessage := fmt.Sprintf("Error decoding JSON Body: %s\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
if tempJSON.PublicHosts == nil && tempJSON.PrivateHosts == nil {
errorMessage := fmt.Sprintf("No privateHosts or publicHosts given\n")
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
tempPTS := api.PodTemplateSpec{}
//Check if we got a URL
if tempJSON.PtsURL == "" {
//No URL so error
errorMessage := fmt.Sprintf("No ptsURL given\n")
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
tempPTS, err = helper.GetPTSFromURL(tempJSON.PtsURL, r)
if err != nil {
helper.LogError.Printf(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
}
if allowPrivilegedContainers == false {
for _, val := range tempPTS.Spec.Containers {
if val.SecurityContext != nil {
val.SecurityContext.Privileged = func() *bool { b := false; return &b }()
}
}
}
tempPTS.Spec.Containers[0].Env = helper.CacheEnvVars(tempPTS.Spec.Containers[0].Env, tempJSON.EnvVars)
//If map is empty then we need to make it
if len(tempPTS.Annotations) == 0 {
tempPTS.Annotations = make(map[string]string)
}
if tempJSON.PrivateHosts != nil {
tempPTS.Annotations["privateHosts"] = *tempJSON.PrivateHosts
}
if tempJSON.PublicHosts != nil {
tempPTS.Annotations["publicHosts"] = *tempJSON.PublicHosts
}
//If map is empty then we need to make it
if len(tempPTS.Labels) == 0 {
tempPTS.Labels = make(map[string]string)
}
//Add routable label
tempPTS.Labels["routable"] = "true"
tempPTS.Labels["runtime"] = "shipyard"
//Could also use proto package
tempInt := int32(5)
template := extensions.Deployment{
ObjectMeta: api.ObjectMeta{
Name: tempJSON.DeploymentName,
},
Spec: extensions.DeploymentSpec{
RevisionHistoryLimit: &tempInt,
Replicas: *tempJSON.Replicas,
Selector: &unversioned.LabelSelector{
MatchLabels: map[string]string{
"component": tempPTS.Labels["component"],
},
},
Template: tempPTS,
},
}
labelSelector, err := labels.Parse("component=" + tempPTS.Labels["component"])
//Get list of all deployments in namespace with MatchLabels["app"] = tempPTS.Labels["app"]
depList, err := client.Deployments(pathVars["org"] + "-" + pathVars["env"]).List(api.ListOptions{
LabelSelector: labelSelector,
})
if len(depList.Items) != 0 {
errorMessage := fmt.Sprintf("LabelSelector " + labelSelector.String() + " already exists")
helper.LogError.Printf(errorMessage)
http.Error(w, errorMessage, http.StatusInternalServerError)
return
}
//Create Deployment
dep, err := client.Deployments(pathVars["org"] + "-" + pathVars["env"]).Create(&template)
if err != nil {
errorMessage := fmt.Sprintf("Error creating deployment: %s\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
js, err := json.Marshal(dep)
if err != nil {
errorMessage := fmt.Sprintf("Error marshalling deployment: %s\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
}
//Create absolute path for Location header
url := "/environments/" + pathVars["org"] + "-" + pathVars["env"] + "/deployments/" + tempJSON.DeploymentName
w.Header().Add("Location", url)
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(201)
w.Write(js)
helper.LogInfo.Printf("Created Deployment: %s\n", dep.GetName())
}
//getDeployment returns a deployment matching the given environmentGroupID, environmentName, and deploymentName
func getDeployment(w http.ResponseWriter, r *http.Request) {
pathVars := mux.Vars(r)
if os.Getenv("DEPLOY_STATE") == "PROD" {
if !helper.ValidAdmin(pathVars["org"], w, r) {
//Errors should be returned from function
return
}
}
getDep, err := client.Deployments(pathVars["org"] + "-" + pathVars["env"]).Get(pathVars["deployment"])
if err != nil {
errorMessage := fmt.Sprintf("Error retrieving deployment: %s\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
js, err := json.Marshal(getDep)
if err != nil {
errorMessage := fmt.Sprintf("Error marshalling deployment: %v\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(js)
helper.LogInfo.Printf("Got Deployment: %v\n", getDep.GetName())
}
//updateDeployment updates a deployment matching the given environmentGroupID, environmentName, and deploymentName
func updateDeployment(w http.ResponseWriter, r *http.Request) {
pathVars := mux.Vars(r)
if os.Getenv("DEPLOY_STATE") == "PROD" {
if !helper.ValidAdmin(pathVars["org"], w, r) {
return
}
}
//Get the old namespace first so we can fail quickly if it's not there
getDep, err := client.Deployments(pathVars["org"] + "-" + pathVars["env"]).Get(pathVars["deployment"])
if err != nil {
errorMessage := fmt.Sprintf("Error getting existing deployment: %s\n", err)
http.Error(w, errorMessage, http.StatusNotFound)
helper.LogError.Printf(errorMessage)
return
}
//Decode passed JSON body
var tempJSON deploymentPatch
err = json.NewDecoder(r.Body).Decode(&tempJSON)
if err != nil {
errorMessage := fmt.Sprintf("Error decoding JSON Body: %v\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
tempPTS := api.PodTemplateSpec{}
//Check if we got a URL
if tempJSON.PtsURL == "" {
//No URL so error
errorMessage := fmt.Sprintf("No ptsURL or PTS given\n")
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
tempPTS, err = helper.GetPTSFromURL(tempJSON.PtsURL, r)
if err != nil {
helper.LogError.Printf(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
}
//If annotations map is empty then we need to make it
if len(tempPTS.Annotations) == 0 {
tempPTS.Annotations = make(map[string]string)
}
//If labels map is empty then we need to make it
if len(tempPTS.Labels) == 0 {
tempPTS.Labels = make(map[string]string)
}
//Need to cache the previous annotations
cacheAnnotations := getDep.Spec.Template.Annotations
//Only set the replica count if the passed variable
if tempJSON.Replicas != nil {
getDep.Spec.Replicas = *tempJSON.Replicas
}
getDep.Spec.Template = tempPTS
//Replace the privateHosts and publicHosts annotations with cached ones
getDep.Spec.Template.Annotations["publicHosts"] = cacheAnnotations["publicHosts"]
getDep.Spec.Template.Annotations["privateHosts"] = cacheAnnotations["privateHosts"]
if tempJSON.PrivateHosts != nil {
getDep.Spec.Template.Annotations["privateHosts"] = *tempJSON.PrivateHosts
}
if tempJSON.PublicHosts != nil {
getDep.Spec.Template.Annotations["publicHosts"] = *tempJSON.PublicHosts
}
getDep.Spec.Template.Spec.Containers[0].Env = helper.CacheEnvVars(getDep.Spec.Template.Spec.Containers[0].Env, tempJSON.EnvVars)
//Add routable label
getDep.Spec.Template.Labels["routable"] = "true"
dep, err := client.Deployments(pathVars["org"] + "-" + pathVars["env"]).Update(getDep)
if err != nil {
errorMessage := fmt.Sprintf("Error updating deployment: %v\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
js, err := json.Marshal(dep)
if err != nil {
errorMessage := fmt.Sprintf("Error marshalling deployment: %v\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(js)
helper.LogInfo.Printf("Updated Deployment: %s\n", dep.GetName())
}
//deleteDeployment deletes a deployment matching the given environmentGroupID, environmentName, and deploymentName
func deleteDeployment(w http.ResponseWriter, r *http.Request) {
pathVars := mux.Vars(r)
if os.Getenv("DEPLOY_STATE") == "PROD" {
if !helper.ValidAdmin(pathVars["org"], w, r) {
return
}
}
//Get the deployment object
dep, err := client.Deployments(pathVars["org"] + "-" + pathVars["env"]).Get(pathVars["deployment"])
if err != nil {
errorMessage := fmt.Sprintf("Error getting old deployment: %s\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
//Get the match label
selector, err := labels.Parse("component=" + dep.Labels["component"])
if err != nil {
errorMessage := fmt.Sprintf("Error creating label selector: %v\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
//Get the replica sets with the corresponding label
rsList, err := client.ReplicaSets(pathVars["org"] + "-" + pathVars["env"]).List(api.ListOptions{
LabelSelector: selector,
})
if err != nil {
errorMessage := fmt.Sprintf("Error getting replica set list: %v\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
//Get the pods with the corresponding label
podList, err := client.Pods(pathVars["org"] + "-" + pathVars["env"]).List(api.ListOptions{
LabelSelector: selector,
})
//Delete Deployment
err = client.Deployments(pathVars["org"]+"-"+pathVars["env"]).Delete(pathVars["deployment"], &api.DeleteOptions{})
if err != nil {
errorMessage := fmt.Sprintf("Error deleting deployment: %v\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
helper.LogInfo.Printf("Deleted Deployment: %v\n", pathVars["deployment"])
//Delete all Replica Sets that came up in the list
for _, value := range rsList.Items {
err = client.ReplicaSets(pathVars["org"]+"-"+pathVars["env"]).Delete(value.GetName(), &api.DeleteOptions{})
if err != nil {
errorMessage := fmt.Sprintf("Error deleting replica set: %v\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
helper.LogInfo.Printf("Deleted Replica Set: %v\n", value.GetName())
}
//Delete all Pods that came up in the list
for _, value := range podList.Items {
err = client.Pods(pathVars["org"]+"-"+pathVars["env"]).Delete(value.GetName(), &api.DeleteOptions{})
if err != nil {
errorMessage := fmt.Sprintf("Error deleting pod: %v\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
helper.LogInfo.Printf("Deleted Pod: %v\n", value.GetName())
}
w.WriteHeader(204)
}
func getDeploymentLogs(w http.ResponseWriter, r *http.Request) {
pathVars := mux.Vars(r)
if os.Getenv("DEPLOY_STATE") == "PROD" {
if !helper.ValidAdmin(pathVars["org"], w, r) {
return
}
}
//Get query strings
queries := r.URL.Query()
tailString := queries.Get("tail")
var tail int64 = -1
if tailString != "" {
tailInt, err := strconv.Atoi(tailString)
if err != nil {
errorMessage := fmt.Sprintf("Invalid tail value: %s\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
tail = int64(tailInt)
}
previousString := queries.Get("previous")
var previous bool
if previousString != "" {
var err error
previous, err = strconv.ParseBool(previousString)
if err != nil {
errorMessage := fmt.Sprintf("Invalid previous value: %s\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
}
//Get the deployment
dep, err := client.Deployments(pathVars["org"] + "-" + pathVars["env"]).Get(pathVars["deployment"])
if err != nil {
errorMessage := fmt.Sprintf("Error retrieving deployment: %s\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
selector := dep.Spec.Selector
label, err := labels.Parse("component=" + selector.MatchLabels["component"])
if err != nil {
errorMessage := fmt.Sprintf("Error parsing label selector: %s\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)
helper.LogError.Printf(errorMessage)
return
}
podInterface := client.Pods(pathVars["org"] + "-" + pathVars["env"])
pods, err := podInterface.List(api.ListOptions{
LabelSelector: label,
})
if err != nil {
errorMessage := fmt.Sprintf("Error retrieving pods: %s\n", err)
http.Error(w, errorMessage, http.StatusInternalServerError)