-
Notifications
You must be signed in to change notification settings - Fork 1
/
get_record.go
1411 lines (1232 loc) · 39.9 KB
/
get_record.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 api
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"net/http"
"os"
"strconv"
"strings"
"time"
ptylib "github.com/creack/pty"
"github.com/galleybytes/terraform-operator-api/pkg/common/models"
tfv1beta1 "github.com/galleybytes/terraform-operator/pkg/apis/tf/v1beta1"
tfo "github.com/galleybytes/terraform-operator/pkg/client/clientset/versioned"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/sorenisanerd/gotty/webtty"
"gopkg.in/yaml.v3"
"gorm.io/gorm"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/remotecommand"
"k8s.io/kubectl/pkg/cmd/exec"
"k8s.io/kubectl/pkg/scheme"
)
type Response struct {
StatusInfo StatusInfo `json:"status_info"`
Data interface{} `json:"data"`
}
type StatusInfo struct {
StatusCode int64 `json:"status_code"`
Message string `json:"message"`
}
func response(httpstatus int64, message string, results interface{}) *Response {
resp := Response{
StatusInfo: StatusInfo{
StatusCode: httpstatus,
Message: message,
},
Data: results,
}
return &resp
}
func (h APIHandler) GetDistinctGeneration(c *gin.Context) {
// The TFOResourceSpec is created once for each generation that passes thru the monitor. It is the best
// resource to query for generations of a particular resource.
uuid := c.Param("tfo_resource_uuid")
var generation []int
if result := h.DB.Raw("SELECT DISTINCT generation FROM tfo_resource_specs WHERE tfo_resource_uuid = ?", &uuid).Scan(&generation); result.Error != nil {
c.JSON(http.StatusNotFound, response(http.StatusNotFound, result.Error.Error(), nil))
return
}
c.JSON(http.StatusOK, response(http.StatusOK, "", generation))
}
func (h APIHandler) GetUuidByClusterID(c *gin.Context) {
clusterID := c.Param("cluster_id")
var clusterIdInfo models.TFOResource
if result := h.DB.Where("cluster_id = ?", clusterID).First(&clusterIdInfo); result.Error != nil {
c.AbortWithError(http.StatusNotFound, result.Error)
return
}
c.JSON(http.StatusOK, &clusterIdInfo)
}
func (h APIHandler) GetCluster(c *gin.Context) {
clusterID := c.Param("cluster_id")
if clusterID == "" {
// ID must be integer-like
clusterID = "-1" // will hopefully never match a primary key
}
clusterName := c.Param("cluster_name")
var clusters []models.Cluster
responseMsg := ""
if result := h.DB.Where("name = ?", clusterName).Or("id = ?", clusterID).First(&clusters); result.Error != nil {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
c.JSON(http.StatusUnprocessableEntity, response(http.StatusUnprocessableEntity, result.Error.Error(), clusters))
return
}
responseMsg = result.Error.Error()
}
c.JSON(http.StatusOK, response(http.StatusOK, responseMsg, clusters))
}
func (h APIHandler) Index(c *gin.Context) {
// TODO return api discovery data
c.JSON(http.StatusNoContent, nil)
}
func (h APIHandler) workflows(c *gin.Context) {
matchAny, _ := c.GetQuery("matchAny")
offset, _ := c.GetQuery("offset")
limit, _ := c.GetQuery("limit")
n, _ := strconv.Atoi(offset)
l, _ := strconv.Atoi(limit)
if l == 0 {
l = 10
}
var result []struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
ClusterName string `json:"cluster_name"`
CurrentState string `json:"state"`
UUID string `json:"uuid"`
CurrentGeneration string `json:"current_generation"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
query := workflows(h.DB).
Limit(l).
Offset(n).
Order("tfo_resources.updated_at DESC")
if matchAny != "" {
m := fmt.Sprintf("%%%s%%", matchAny)
name := m
namespace := m
clusterName := m
if strings.Contains(matchAny, "=") {
name = "%"
namespace = "%"
clusterName = "%"
for _, matchAnyOfColumn := range strings.Split(matchAny, " ") {
if !strings.Contains(matchAnyOfColumn, "=") {
continue
}
columnQuery := strings.Split(matchAnyOfColumn, "=")
key := columnQuery[0]
value := columnQuery[1]
if key == "name" {
query.Where("tfo_resources.name LIKE ?", fmt.Sprintf("%%%s%%", value))
}
if key == "namespace" {
query.Where("tfo_resources.namespace LIKE ?", fmt.Sprintf("%%%s%%", value))
}
if strings.HasPrefix(key, "cluster") {
query.Where("clusters.name LIKE ?", fmt.Sprintf("%%%s%%", value))
}
}
} else {
query.Where("(tfo_resources.name LIKE ? or tfo_resources.namespace LIKE ? or clusters.name LIKE ?)",
name,
namespace,
clusterName,
)
}
}
query.Debug().Scan(&result)
c.JSON(http.StatusOK, response(http.StatusOK, "", result))
}
func (h APIHandler) ListClusters(c *gin.Context) {
var clusters []models.Cluster
if result := h.DB.Find(&clusters); result.Error != nil {
c.AbortWithError(http.StatusNotFound, result.Error)
return
}
c.JSON(http.StatusOK, &clusters)
}
func (h APIHandler) GetClustersResources(c *gin.Context) {
var resources []models.TFOResource
clusterID := c.Param("cluster_id")
if result := h.DB.Where("cluster_id = ?", clusterID).Find(&resources); result.Error != nil {
c.AbortWithError(http.StatusNotFound, result.Error)
return
}
c.JSON(http.StatusOK, &resources)
}
func (h APIHandler) GetResourceByUUID(c *gin.Context) {
var tfoResources []models.TFOResource
uuid := c.Param("tfo_resource_uuid")
responseMsg := ""
if result := h.DB.First(&tfoResources, "uuid = ?", uuid); result.Error != nil {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
c.JSON(http.StatusUnprocessableEntity, response(http.StatusUnprocessableEntity, result.Error.Error(), tfoResources))
return
}
responseMsg = result.Error.Error()
}
c.JSON(http.StatusOK, response(http.StatusOK, responseMsg, tfoResources))
}
func highestRerun(taskPods []models.TaskPod, taskType string, minimum float64) (models.TaskPod, float64) {
taskPodOfHighestRerun := models.TaskPod{}
highestRerunObservedInLogs := 0
for _, taskPod := range taskPods {
if taskPod.TaskType == taskType {
if taskPod.Rerun > highestRerunObservedInLogs {
highestRerunObservedInLogs = taskPod.Rerun
}
}
}
// return only the highest rerun. It is ok to return an empty list, this just indicates that the task
// has not produced logs yet.
rerun := math.Max(float64(highestRerunObservedInLogs), minimum)
for _, taskPod := range taskPods {
if taskPod.TaskType == taskType && taskPod.Rerun == int(rerun) {
taskPodOfHighestRerun = taskPod
}
}
return taskPodOfHighestRerun, rerun
}
func (h APIHandler) LatestGeneration(uuid string) string {
var tfoResource models.TFOResource
if result := h.DB.First(&tfoResource, "uuid = ?", &uuid); result.Error != nil {
return ""
}
return tfoResource.CurrentGeneration
}
// ResourceLog data contract for clients to consume
type ResourceLog struct {
ID uint `json:"id"`
LogMessage string `json:"message"`
TaskType string `json:"task_type"`
Rerun int `json:"rerun"`
LineNo string `json:"line_no"`
TFOResourceUUID string `json:"tfo_resource_uuid"`
}
// GetClustersResourceLogs will return the latest logs for the selected resource. The only filted allowed
// in this call is the generation to switch getting the latest logs for a given generation.
func (h APIHandler) GetClustersResourcesLogs(c *gin.Context) {
// URL param arguments expected. These are used to construct the url and are always expected to contain a string
generationFilter := c.Param("generation")
taskTypeFilter := c.Param("task_type")
rerunFilter := c.Param("rerun")
uuid := c.Param("tfo_resource_uuid")
logs, err := h.ResourceLogs(generationFilter, rerunFilter, taskTypeFilter, uuid)
if err != nil {
c.AbortWithError(http.StatusNotFound, err)
}
c.JSON(http.StatusOK, response(http.StatusOK, "", logs))
}
func (h APIHandler) ResourceLogs(generationFilter, rerunFilter, taskTypeFilter, uuid string) ([]ResourceLog, error) {
logs := []ResourceLog{}
if generationFilter == "latest" || generationFilter == "" {
// "latest" is a special case that reads the 'CurrentGeneration' value out of TFOResource
generationFilter = h.LatestGeneration(uuid)
}
var taskPods []models.TaskPod
if rerunFilter != "" {
if result := h.DB.Where("tfo_resource_uuid = ? AND generation = ? AND rerun = ?", &uuid, &generationFilter, &rerunFilter).Find(&taskPods); result.Error != nil {
return logs, result.Error
}
} else {
if result := h.DB.Where("tfo_resource_uuid = ? AND generation = ?", &uuid, &generationFilter).Find(&taskPods); result.Error != nil {
return logs, result.Error
}
}
// We've retrieved all the logs for the generation at this point, but we need to ensure we only display
// the latest rerun logs. If a user wants a specific rerun, a different query will need to be constructed
// We must have knowledge of the order of logs to return the correct result to the user. Each task type
// can have a different rerun number, and therefore, we have to make sure that when the results are
// returned, the latest tasks do not have earlier reruns than previous tasks.
//
// 9 | |
// 8 | |
// R 7 | Good Results | Bad result becuase the apply log
// E 6 | | doesn't reflect the result of plan
// R 5 | |
// U 4 | | x
// N 3 | x x | x
// 2 | |
// 1 | x | x
// 0 |_x_____________________|____x________________________
// p t n y p t n y
// u i a l u i a l
// t n l p t n l p
// e i p p e i p p
// s a s a
// Create this in order to store the logs filtered by the rerun sort
// filteredResuilts := []models.TFOTaskLog{}
taskPodsOfHighestRerun := []models.TaskPod{}
currentRerun := float64(0)
for _, taskType := range taskTypesInOrder {
taskPod, rerun := highestRerun(taskPods, taskType, currentRerun)
currentRerun = rerun
if taskTypeFilter != "" && taskPod.TaskType != taskTypeFilter {
continue
}
taskPodsOfHighestRerun = append(taskPodsOfHighestRerun, taskPod)
}
// Find all the tfoTaskLogs that were created from the taskPods
taskPodUUIDs := []string{}
for _, t := range taskPodsOfHighestRerun {
taskPodUUIDs = append(taskPodUUIDs, t.UUID)
}
var tfoTaskLogs []models.TFOTaskLog
if result := h.DB.Where("task_pod_uuid IN ?", taskPodUUIDs).Find(&tfoTaskLogs); result.Error != nil {
return logs, result.Error
}
// TODO optimize the taskPod/taskLog matching algorithm, leaving this simple lookup since logs are
// unlikely to be more than just a few thousand lines max. This number should be easily handled.
for _, taskPod := range taskPodsOfHighestRerun {
for _, log := range tfoTaskLogs {
if log.TaskPodUUID == taskPod.UUID {
// TODO does the size need to be sent?
logs = append(logs, ResourceLog{
ID: log.ID,
LogMessage: log.Message,
Rerun: taskPod.Rerun,
TaskType: taskPod.TaskType,
})
}
}
}
return logs, nil
}
func (h APIHandler) GetTFOTaskLogsViaTask(c *gin.Context) {
emptyResponse := []interface{}{}
taskPodUUID := c.Param("task_pod_uuid")
var tfoTaskLogs []models.TFOTaskLog
if result := h.DB.Where("task_pod_uuid = ?", taskPodUUID).Find(&tfoTaskLogs); result.Error != nil {
// TODO No plans have been executed yet. This is not an error but we are not able to continue until the plan pod shows up.
c.JSON(http.StatusOK, response(http.StatusOK, "TaskPod "+result.Error.Error(), emptyResponse))
return
}
c.JSON(http.StatusOK, response(http.StatusOK, "", tfoTaskLogs))
}
func (h APIHandler) LookupResourceSpec(generation, uuid string) *models.TFOResourceSpec {
var tfoResource models.TFOResource
var tfoResourceSpec models.TFOResourceSpec
if generation == "latest" {
if result := h.DB.First(&tfoResource, "uuid = ?", &uuid); result.Error != nil {
return nil
}
generation = tfoResource.CurrentGeneration
}
if result := h.DB.Where("tfo_resource_uuid = ? AND generation =?", uuid, generation).First(&tfoResourceSpec); result.Error != nil {
return nil
}
return &tfoResourceSpec
}
type GetResourceSpecResponseData struct {
models.TFOResourceSpec `json:",inline"`
}
// func (h APIHandler) GetResourceSpec(c *gin.Context) {
// uuid := c.Param("tfo_resource_uuid")
// generation := c.Param("generation")
// tfoResourceSpec := h.LookupResourceSpec(generation, uuid)
// responseData := []interface{}{}
// if tfoResourceSpec != nil {
// responseData = append(responseData, GetResourceSpecResponseData{TFOResourceSpec: *tfoResourceSpec})
// }
// c.JSON(http.StatusOK, &responseData)
// }
type GetApprovalStatusResponseData struct {
TFOResourceUUID string `json:"tfo_resource_uuid"`
TaskPodUUID string `json:"task_pod_uuid"`
// Status is fuzzy. -1 means it hasn't been decided, 0 is false, 1 is true for the approvals.
// Hasn't been decided means there is no record in the approvals table matching the uuid.
Status int `json:"status"`
}
func (h APIHandler) GetTaskPod(c *gin.Context) {
responseData := []interface{}{}
taskPodUUID := c.Param("task_pod_uuid")
taskPods := []models.TaskPod{}
if result := h.DB.Where("uuid = ?", &taskPodUUID).Find(&taskPods); result.Error != nil {
// TODO No plans have been executed yet. This is not an error but we are not able to continue until the plan pod shows up.
c.JSON(http.StatusOK, response(http.StatusOK, result.Error.Error(), responseData))
return
}
c.JSON(http.StatusOK, response(http.StatusOK, "", taskPods))
}
type approvalResponse struct {
models.Approval `json:",inline"`
Status string `json:"status"`
}
func (h APIHandler) AllApprovals(c *gin.Context) {
approval := []models.Approval{}
h.DB.Last(&approval)
c.JSON(http.StatusOK, response(http.StatusOK, "", approval))
}
func (h APIHandler) GetApprovalStatusViaTaskPodUUID(c *gin.Context) {
responseData := []interface{}{}
taskPodUUID := c.Param("task_pod_uuid")
taskPod := models.TaskPod{}
if result := h.DB.Where("uuid = ?", &taskPodUUID).Find(&taskPod); result.Error != nil {
// TODO No plans have been executed yet. This is not an error but we are not able to continue until the plan pod shows up.
c.JSON(http.StatusOK, response(http.StatusOK, "TaskPod "+result.Error.Error(), responseData))
return
}
if taskPod.TaskType != "plan" {
// TODO what's the message
c.JSON(http.StatusOK, response(http.StatusOK, fmt.Sprintf("approvals are for plan types, but uuid was for %s type", taskPod.TaskType), responseData))
return
}
approvals := []models.Approval{}
if result := h.DB.Where("task_pod_uuid = ?", &taskPod.UUID).First(&approvals); result.Error != nil {
c.JSON(http.StatusOK, response(http.StatusOK, "Approval "+result.Error.Error(), []approvalResponse{
{
Status: "nodata",
Approval: models.Approval{
TaskPodUUID: taskPodUUID,
},
},
}))
return
}
c.JSON(http.StatusOK, response(http.StatusOK, "", []approvalResponse{
{
Approval: approvals[0],
Status: "complete",
},
}))
}
// GetApprovalStatus only looks at the latest resource spec by getting the TFOResource's 'LatestGeneration'.
// Use the generation to get the TFOResourceSpec and parses the "spec" for the requireApproval value. If the
// value is "true", this function finds the latest plan task by getting the TaskPod with the highest rerun number.
// The UUID of the TaskPod is used to lookup the Approval status to return to the caller.
func (h APIHandler) GetApprovalStatus(c *gin.Context) {
responseData := []interface{}{}
uuid := c.Param("tfo_resource_uuid")
generationFilter := c.Param("generation")
generation := generationFilter
if generationFilter == "" || generationFilter == "latest" {
generation = h.LatestGeneration(uuid)
}
tfoResourceSpec := h.LookupResourceSpec(generation, uuid)
if tfoResourceSpec == nil {
// TODO What's the error messsage?
c.JSON(http.StatusOK, response(http.StatusOK, "", responseData))
return
}
spec := struct {
RequireApproval bool `yaml:"requireApproval"`
}{}
err := yaml.Unmarshal([]byte(tfoResourceSpec.ResourceSpec), &spec)
if err != nil {
c.JSON(http.StatusOK, response(http.StatusOK, err.Error(), responseData))
return
}
if !spec.RequireApproval {
// TODO what's the message when no require approval is required?
c.JSON(http.StatusOK, response(http.StatusOK, "", responseData))
return
}
taskType := "plan"
taskPods := []models.TaskPod{}
if result := h.DB.Where("tfo_resource_uuid = ? AND generation = ? AND task_type = ?", &uuid, &generation, &taskType).Find(&taskPods); result.Error != nil {
// TODO No plans have been executed yet. This is not an error but we are not able to continue until the plan pod shows up.
c.JSON(http.StatusOK, response(http.StatusOK, "", responseData))
return
}
taskPod, _ := highestRerun(taskPods, taskType, 0)
// status := -1
approvals := []models.Approval{}
if result := h.DB.Where("task_pod_uuid = ?", &taskPod.UUID).First(&approvals); result.Error != nil {
c.JSON(http.StatusOK, response(http.StatusOK, "Approval "+result.Error.Error(), []approvalResponse{
{
Status: "nodata",
Approval: models.Approval{
TaskPodUUID: taskPod.UUID,
},
},
}))
return
}
c.JSON(http.StatusOK, response(http.StatusOK, "", []approvalResponse{
{
Approval: approvals[0],
Status: "complete",
},
}))
}
// UpdateApproval takes the uuid and a JSON data param and create a row in the approval table.
func (h APIHandler) UpdateApproval(c *gin.Context) {
uuid := c.Param("task_pod_uuid")
type Approval struct {
IsApproved bool `json:"is_approved"`
}
approvalData := new(Approval)
err := c.BindJSON(approvalData)
if err != nil {
// TODO send message that data is missing or whatever bindjson error returns
c.JSON(http.StatusNotAcceptable, nil)
return
}
log.Print(approvalData)
approval := models.Approval{}
if result := h.DB.Where("task_pod_uuid = ?", &uuid).First(&approval); result.Error == nil {
// TODO Approval is already set, user should be informed
c.JSON(http.StatusNoContent, nil)
return
} else {
if !errors.Is(result.Error, gorm.ErrRecordNotFound) {
// TODO Something unexpected happened
c.JSON(http.StatusBadRequest, nil)
return
}
}
approval = models.Approval{
IsApproved: approvalData.IsApproved,
TaskPodUUID: uuid,
}
createResult := h.DB.Create(&approval)
if createResult.Error != nil {
// TODO Something unexpected happened
c.JSON(http.StatusBadRequest, nil)
return
}
c.JSON(http.StatusNoContent, nil)
}
type SocketListener struct {
Connection *websocket.Conn
IsListening bool
EventType chan int
Message []byte
Err error
}
// Listen runs a background function and returns a response on the EventType channel.
func (s *SocketListener) Listen() {
if s.IsListening {
return
}
s.IsListening = true
s.EventType = make(chan int)
go func() {
t, msg, err := s.Connection.ReadMessage()
s.Message = []byte(msg)
s.Err = err
s.IsListening = false
s.EventType <- t
}()
}
func (h APIHandler) ResourceLogWatcher(c *gin.Context) {
tfoResourceUUID := c.Param("tfo_resource_uuid")
_ = tfoResourceUUID
var wsupgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
// how can i make this more secure?
wsupgrader.CheckOrigin = func(r *http.Request) bool { return true }
conn, err := wsupgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Printf("Failed to set websocket upgrade: %+v", err)
return
}
defer conn.Close()
s := SocketListener{Connection: conn}
s.Listen()
taskLog := models.TFOTaskLog{}
if result := h.DB.Last(&taskLog); result.Error != nil {
return
}
lastTaskLogID := taskLog.ID
logs, err := h.ResourceLogs("", "", "", tfoResourceUUID)
if err != nil {
return
}
b, err := json.Marshal(logs)
if err != nil {
// Why did it fail?
return
}
conn.WriteMessage(1, b)
for {
select {
case i := <-s.EventType:
if i == -1 {
log.Println("Closing socket: client is going away")
return
}
if s.Err != nil {
log.Printf("An error was sent in the socket event: %s", s.Err.Error())
}
log.Printf("The event sent was: %s. Listening for next event...", string(s.Message))
s.Listen()
case <-time.Tick(1 * time.Second):
taskLog := models.TFOTaskLog{}
if result := h.DB.Last(&taskLog); result.Error != nil {
return
}
if lastTaskLogID == taskLog.ID {
// NOISE --> log.Println("No new logs. Last log id is ", lastTaskLogID)
continue
}
logs, err := h.ResourceLogs("", "", "", tfoResourceUUID)
if err != nil {
// Why did it fail?
return
}
b, err := json.Marshal(logs)
if err != nil {
// Why did it fail?
return
}
conn.WriteMessage(1, b)
lastTaskLogID = taskLog.ID
}
}
}
// Check if terraform namespace/name resource exists in vcluster
func getResource(parentClientset kubernetes.Interface, clusterName, namespace, name string, ctx context.Context) (*tfv1beta1.Terraform, error) {
config, err := getVclusterConfig(parentClientset, "internal", clusterName)
if err != nil {
return nil, err
}
tfoclientset := tfo.NewForConfigOrDie(config)
return tfoclientset.TfV1beta1().Terraforms(namespace).Get(ctx, name, metav1.GetOptions{})
}
func (h APIHandler) Debugger(c *gin.Context) {
clusterName := c.Param("cluster_name")
clusterID := h.getClusterID(clusterName)
if clusterID == 0 {
c.JSON(http.StatusUnprocessableEntity, response(http.StatusUnprocessableEntity, fmt.Sprintf("cluster_name '%s' not found", clusterName), nil))
return
}
name := c.Param("name")
namespace := c.Param("namespace")
if _, err := getResource(h.clientset, clusterName, namespace, name, c); err != nil {
c.JSON(http.StatusUnprocessableEntity, response(http.StatusUnprocessableEntity, fmt.Sprintf("tf resource '%s/%s' not found", namespace, name), nil))
return
}
cmd := []string{}
for key, values := range c.Request.URL.Query() {
if key == "command" {
cmd = values
}
}
var wsupgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
// how can i make this more secure?
wsupgrader.CheckOrigin = func(r *http.Request) bool { return true }
conn, err := wsupgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Printf("Failed to set websocket upgrade: %+v", err)
return
}
defer conn.Close()
execCommand := []string{
"/bin/bash",
"-c",
`cd $TFO_MAIN_MODULE && \
export PS1="\\w\\$ " && \
if [[ -n "$AWS_WEB_IDENTITY_TOKEN_FILE" ]]; then
export $(irsa-tokengen);
echo printf "\nAWS creds set from token file\n"
fi && \
printf "\nTry running 'terraform init'\n\n" && bash
`,
}
podExecReadWriter, err := newSessionInTerraformDebugPod(h.clientset, clusterName, namespace, name, c, cmd, execCommand)
if err != nil {
log.Printf("Failed to connect to debug pod: %s", err)
return
}
var opts []webtty.Option
opts = append(opts, webtty.WithPermitWrite())
webTTY, err := webtty.New(&wsWrapper{conn}, podExecReadWriter, opts...)
if err != nil {
log.Printf("failed to create webtty: %s", err)
return
}
errCh := make(chan error)
go func() {
errCh <- webTTY.Run(c)
}()
select {
case err = <-errCh:
log.Println(err)
msg := websocket.FormatCloseMessage(websocket.CloseGoingAway, "")
err := conn.WriteMessage(websocket.CloseMessage, msg)
if err != nil {
log.Println(err)
}
case err = <-podExecReadWriter.Closer:
log.Println("Closing the connection")
var closeCode int
var msg string
if err != nil {
closeCode = websocket.CloseGoingAway
msg = err.Error()
} else {
closeCode = websocket.CloseNormalClosure
msg = ""
}
closeMsg := websocket.FormatCloseMessage(closeCode, msg)
err := conn.WriteMessage(websocket.CloseMessage, closeMsg)
if err != nil {
log.Println(err)
}
}
// return
}
func (h APIHandler) UnlockTerraform(c *gin.Context) {
clusterName := c.Param("cluster_name")
clusterID := h.getClusterID(clusterName)
if clusterID == 0 {
c.JSON(http.StatusUnprocessableEntity, response(http.StatusUnprocessableEntity, fmt.Sprintf("cluster_name '%s' not found", clusterName), nil))
return
}
name := c.Param("name")
namespace := c.Param("namespace")
if _, err := getResource(h.clientset, clusterName, namespace, name, c); err != nil {
c.JSON(http.StatusUnprocessableEntity, response(http.StatusUnprocessableEntity, fmt.Sprintf("tf resource '%s/%s' not found", namespace, name), nil))
return
}
command := []string{
"/bin/bash",
"-c",
`cd $TFO_MAIN_MODULE && \
file=$(mktemp) && \
terraform plan -no-color 2>$file
if [[ ! -s "$file" ]] ; then
echo "\nno lock detected exiting"
exit 0
fi && \
cat $file
lock=$(grep -A1 "Lock Info" $file | grep "ID") && \
lock_id=$(echo $lock | sed -n 's/.*\([0-9a-fA-F-]\{36\}\).*/\1/p') && \
echo lock=$lock && \
echo lock_id=$lock_id && \
if [ -n "$lock_id" ]; then
terraform force-unlock -force $lock_id
fi && \
echo "Done"`,
}
err := runUnlockTerraformDebugPod(h.clientset, clusterName, namespace, name, c, command)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, response(http.StatusUnprocessableEntity, fmt.Sprintf("terraform unlock failed: %s", err), nil))
return
}
err = rerun(h.clientset, clusterName, namespace, name, "unlock-terraform-triggered-rerun", c)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, response(http.StatusUnprocessableEntity, fmt.Sprintf("Failed to trigger rerun: %s", err), []any{}))
return
}
c.JSON(http.StatusOK, response(http.StatusOK, "terraform unlocked", nil))
}
type wsWrapper struct {
*websocket.Conn
}
func (wsw *wsWrapper) Write(p []byte) (n int, err error) {
// log.Println("wsWrapper.Write ", string(p))
writer, err := wsw.Conn.NextWriter(websocket.TextMessage)
if err != nil {
return 0, err
}
defer writer.Close()
return writer.Write(p)
}
func (wsw *wsWrapper) Read(p []byte) (n int, err error) {
// log.Println("wsWrapper.Read ", string(p))
for {
msgType, reader, err := wsw.Conn.NextReader()
if err != nil {
// log.Println("I didn't read it cuz err", err)
return 0, err
}
if msgType != websocket.TextMessage {
// log.Println("I didn't read it cuz wrong type")
continue
}
b, err := ioutil.ReadAll(reader)
if len(b) > len(p) {
// log.Println("I didn't read it cuz another error", err)
return 0, fmt.Errorf("client message exceeded buffer size: %s", err)
}
// log.Println("I did read something into a reader which produced this: %s", string(b))
// log.Println("I think I read it but I'm not 100%% sure", err)
dec, err := base64.StdEncoding.DecodeString(string(b[1:]))
if err != nil {
// log.Println("I didn't read it cuz could not decode", err)
continue
}
// log.Printf("I'm reading dec = %s ", string(dec))
n = copy(p, append([]byte{b[0]}, dec...))
return n, err
// n, err = wsw.podTTY.Write(dec)
// if err != nil {
// return 0, err
// }
}
}
// type PodExecFactory struct{}
type PodExec struct {
pty *os.File
reader io.Reader
writer io.Writer
termSizer TermSizer
Closer chan error
}
type TermSizer struct {
SizeCh chan remotecommand.TerminalSize
}
func (t TermSizer) Next() *remotecommand.TerminalSize {
size := <-t.SizeCh
return &size
}
// func (f *PodExecFactory) Name() string {
// return "Pod Exec"
// }
// func (f *PodExecFactory) New(params map[string][]string, headers map[string][]string) (Slave, error) {
// return New()
// }
// command string, argv []string, headers map[string][]string, options ...Option
func newSessionInTerraformDebugPod(clientset kubernetes.Interface, clusterName, namespace, name string, c *gin.Context, cmd, execCommand []string) (*PodExec, error) {
pty, tty, err := ptylib.Open()
if err != nil {
log.Fatal(err)
}
os.Stdin = tty
os.Stderr = tty
os.Stdout = tty
sizeCh := make(chan remotecommand.TerminalSize)
closeCh := make(chan error)
termSizer := TermSizer{
SizeCh: sizeCh,
}
go func() {
defer pty.Close()
err := RemoteDebug(clientset, clusterName, namespace, name, tty, c, termSizer, cmd, execCommand)
log.Println("Pod exec exited")
closeCh <- err
}()
return &PodExec{
pty: pty,
reader: pty,
writer: pty,
termSizer: termSizer,
Closer: closeCh,
}, nil
}
func (podExec *PodExec) Read(p []byte) (n int, err error) {
return podExec.reader.Read(p)
}
func (podExec *PodExec) Write(p []byte) (n int, err error) {
return podExec.writer.Write(p)
}
// WindowTitleVariables returns any values that can be used to fill out
// the title of a terminal.
func (p *PodExec) WindowTitleVariables() map[string]interface{} {
return map[string]interface{}{
"command": "tfo",
"hostname": "localhost",
}
}
// ResizeTerminal sets a new size of the terminal.
func (p *PodExec) ResizeTerminal(columns int, rows int) error {
// log.Println("Resizing Terminal", columns, rows)
p.termSizer.SizeCh <- remotecommand.TerminalSize{
Width: uint16(columns),
Height: uint16(rows),
}
return nil
}
func (p *PodExec) Close() error {
log.Println("Going away...")
return nil
}
func createDebugPodManifest(c *gin.Context, config *rest.Config, namespace, name string, command []string) (*corev1.Pod, error) {
tfoclientset := tfo.NewForConfigOrDie(config)
tfclient := tfoclientset.TfV1beta1().Terraforms(namespace)
tf, err := tfclient.Get(c, name, metav1.GetOptions{})
if err != nil {
return nil, err