-
Notifications
You must be signed in to change notification settings - Fork 567
Expand file tree
/
Copy pathClusterRestHandler.go
More file actions
777 lines (717 loc) · 26.6 KB
/
ClusterRestHandler.go
File metadata and controls
777 lines (717 loc) · 26.6 KB
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
/*
* Copyright (c) 2020-2024. Devtron Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cluster
import (
"context"
"encoding/json"
"errors"
"net/http"
"strconv"
"strings"
"time"
bean2 "github.com/devtron-labs/devtron/pkg/cluster/bean"
"github.com/devtron-labs/devtron/pkg/cluster/environment"
"github.com/devtron-labs/devtron/pkg/cluster/rbac"
"github.com/devtron-labs/devtron/pkg/auth/authorisation/casbin"
"github.com/devtron-labs/devtron/pkg/auth/user"
"github.com/devtron-labs/devtron/pkg/genericNotes"
"github.com/devtron-labs/devtron/pkg/genericNotes/repository"
"github.com/devtron-labs/devtron/api/restHandler/common"
"github.com/devtron-labs/devtron/pkg/cluster"
delete2 "github.com/devtron-labs/devtron/pkg/delete"
util2 "github.com/devtron-labs/devtron/util"
"github.com/go-pg/pg"
"github.com/gorilla/mux"
"go.uber.org/zap"
"gopkg.in/go-playground/validator.v9"
)
const CLUSTER_DELETE_SUCCESS_RESP = "Cluster deleted successfully."
type ClusterRestHandler interface {
Save(w http.ResponseWriter, r *http.Request)
SaveClusters(w http.ResponseWriter, r *http.Request)
ValidateKubeconfig(w http.ResponseWriter, r *http.Request)
FindAll(w http.ResponseWriter, r *http.Request)
FindById(w http.ResponseWriter, r *http.Request)
FindNoteByClusterId(w http.ResponseWriter, r *http.Request)
Update(w http.ResponseWriter, r *http.Request)
UpdateClusterDescription(w http.ResponseWriter, r *http.Request)
UpdateClusterNote(w http.ResponseWriter, r *http.Request)
FindAllForAutoComplete(w http.ResponseWriter, r *http.Request)
DeleteCluster(w http.ResponseWriter, r *http.Request)
GetClusterNamespaces(w http.ResponseWriter, r *http.Request)
GetAllClusterNamespaces(w http.ResponseWriter, r *http.Request)
FindAllForClusterPermission(w http.ResponseWriter, r *http.Request)
FindByIds(w http.ResponseWriter, r *http.Request)
}
type ClusterRestHandlerImpl struct {
clusterService cluster.ClusterService
clusterNoteService genericNotes.GenericNoteService
clusterDescriptionService cluster.ClusterDescriptionService
logger *zap.SugaredLogger
userService user.UserService
validator *validator.Validate
enforcer casbin.Enforcer
deleteService delete2.DeleteService
environmentService environment.EnvironmentService
clusterRbacService rbac.ClusterRbacService
}
func NewClusterRestHandlerImpl(clusterService cluster.ClusterService,
clusterNoteService genericNotes.GenericNoteService,
clusterDescriptionService cluster.ClusterDescriptionService,
logger *zap.SugaredLogger,
userService user.UserService,
validator *validator.Validate,
enforcer casbin.Enforcer,
deleteService delete2.DeleteService,
environmentService environment.EnvironmentService,
clusterRbacService rbac.ClusterRbacService) *ClusterRestHandlerImpl {
return &ClusterRestHandlerImpl{
clusterService: clusterService,
clusterNoteService: clusterNoteService,
clusterDescriptionService: clusterDescriptionService,
logger: logger,
userService: userService,
validator: validator,
enforcer: enforcer,
deleteService: deleteService,
environmentService: environmentService,
clusterRbacService: clusterRbacService,
}
}
func (impl ClusterRestHandlerImpl) SaveClusters(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("token")
decoder := json.NewDecoder(r.Body)
userId, err := impl.userService.GetLoggedInUser(r)
if userId == 0 || err != nil {
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
return
}
beans := []*bean2.ClusterBean{}
err = decoder.Decode(&beans)
if err != nil {
impl.logger.Errorw("request err, Save", "error", err, "payload", beans)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
// not logging bean object as it contains sensitive data
impl.logger.Infow("request payload received for save clusters")
// RBAC enforcer applying
if ok := impl.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionCreate, "*"); !ok {
common.WriteJsonResp(w, errors.New("unauthorized User"), nil, http.StatusForbidden)
return
}
//RBAC enforcer Ends
ctx, cancel := context.WithCancel(r.Context())
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
if util2.IsBaseStack() {
ctx = context.WithValue(ctx, "token", token)
}
for _, bean := range beans {
l := len(bean.ServerUrl)
if l > 1 && bean.ServerUrl[l-1:] == "/" {
bean.ServerUrl = bean.ServerUrl[0 : l-1]
}
if bean.Id != 0 {
_, err1 := impl.clusterService.Update(ctx, bean, userId)
if err1 != nil {
bean.ErrorInConnecting = err1.Error()
} else {
bean.ClusterUpdated = true
}
} else {
_, err1 := impl.clusterService.Save(ctx, bean, userId)
if err1 != nil {
bean.ErrorInConnecting = err1.Error()
}
}
}
res := beans
common.WriteJsonResp(w, err, res, http.StatusOK)
}
func (impl ClusterRestHandlerImpl) Save(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("token")
decoder := json.NewDecoder(r.Body)
userId, err := impl.userService.GetLoggedInUser(r)
if userId == 0 || err != nil {
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
return
}
bean := new(bean2.ClusterBean)
err = decoder.Decode(bean)
if err != nil {
impl.logger.Errorw("request err, Save", "error", err, "payload", bean)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
impl.logger.Infow("request payload, Save", "payload", bean)
err = impl.validator.Struct(bean)
if err != nil {
impl.logger.Errorw("validation err, Save", "err", err, "payload", bean)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
// RBAC enforcer applying
if ok := impl.enforcer.Enforce(token, casbin.ResourceCluster, casbin.ActionCreate, "*"); !ok {
common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)
return
}
//RBAC enforcer Ends
ctx, cancel := context.WithCancel(r.Context())
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
if util2.IsBaseStack() {
ctx = context.WithValue(ctx, "token", token)
}
bean, err = impl.clusterService.Save(ctx, bean, userId)
if err != nil {
impl.logger.Errorw("service err, Save", "err", err, "payload", bean)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
/* isTriggered, err := impl.installedAppService.DeployDefaultChartOnCluster(bean, userId)
if err != nil {
impl.logger.Errorw("service err, Save, on DeployDefaultChartOnCluster", "err", err, "payload", bean)
}
if isTriggered {
bean.AgentInstallationStage = 1
} else {
bean.AgentInstallationStage = 0
}*/
common.WriteJsonResp(w, err, bean, http.StatusOK)
}
func (impl ClusterRestHandlerImpl) ValidateKubeconfig(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("token")
decoder := json.NewDecoder(r.Body)
userId, err := impl.userService.GetLoggedInUser(r)
if userId == 0 || err != nil {
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
return
}
bean := &bean2.Kubeconfig{}
err = decoder.Decode(bean)
if err != nil {
impl.logger.Errorw("request err, Validate", "error", err, "payload", bean)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
err = impl.validator.Struct(bean)
if err != nil {
impl.logger.Errorw("validation err, Validate", "err", err, "payload", bean)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
// RBAC enforcer applying
if ok := impl.enforcer.Enforce(token, casbin.ResourceCluster, casbin.ActionCreate, "*"); !ok {
common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)
return
}
//RBAC enforcer Ends
ctx, cancel := context.WithCancel(r.Context())
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
if util2.IsBaseStack() {
ctx = context.WithValue(ctx, "token", token)
}
res, err := impl.clusterService.ValidateKubeconfig(bean.Config)
if err != nil {
impl.logger.Errorw("error in validating kubeconfig")
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
common.WriteJsonResp(w, err, res, http.StatusOK)
}
func (impl ClusterRestHandlerImpl) FindAll(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("token")
clusterList, err := impl.clusterService.FindAllWithoutConfig()
if err != nil {
impl.logger.Errorw("service err, FindAll", "err", err)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
// RBAC enforcer applying
var result []*bean2.ClusterBean
for _, item := range clusterList {
if ok := impl.enforcer.Enforce(token, casbin.ResourceCluster, casbin.ActionGet, item.ClusterName); ok {
item.SetClusterStatus()
result = append(result, item)
}
}
//RBAC enforcer Ends
common.WriteJsonResp(w, err, result, http.StatusOK)
}
func (impl ClusterRestHandlerImpl) FindByIds(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("token")
// Parse clusterId query parameter
clusterIdsStr := r.URL.Query().Get("clusterId")
if clusterIdsStr == "" {
// If no clusterId parameter, return all clusters (same as FindAll)
impl.FindAll(w, r)
return
}
// Parse comma-separated cluster IDs
var clusterIds []int
clusterIdStrs := strings.Split(clusterIdsStr, ",")
for _, idStr := range clusterIdStrs {
idStr = strings.TrimSpace(idStr)
if idStr == "" {
continue
}
id, err := strconv.Atoi(idStr)
if err != nil {
impl.logger.Errorw("request err, FindByIds", "error", err, "clusterId", idStr)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
clusterIds = append(clusterIds, id)
}
if len(clusterIds) == 0 {
// If no valid cluster IDs, return empty result
common.WriteJsonResp(w, nil, []*bean2.ClusterBean{}, http.StatusOK)
return
}
clusterList, err := impl.clusterService.FindByIdsWithoutConfig(clusterIds)
if err != nil {
impl.logger.Errorw("service err, FindByIds", "err", err)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
// RBAC enforcer applying
var result []*bean2.ClusterBean
for _, item := range clusterList {
if ok := impl.enforcer.Enforce(token, casbin.ResourceCluster, casbin.ActionGet, item.ClusterName); ok {
item.SetClusterStatus()
result = append(result, item)
}
}
//RBAC enforcer Ends
common.WriteJsonResp(w, nil, result, http.StatusOK)
}
func (impl ClusterRestHandlerImpl) FindById(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
i, err := strconv.Atoi(id)
if err != nil {
impl.logger.Errorw("request err, FindById", "error", err, "clusterId", id)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
bean, err := impl.clusterService.FindByIdWithoutConfig(i)
if err != nil {
impl.logger.Errorw("service err, FindById", "err", err, "clusterId", id)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
// RBAC enforcer applying
token := r.Header.Get("token")
if ok := impl.enforcer.Enforce(token, casbin.ResourceCluster, casbin.ActionGet, bean.ClusterName); !ok {
common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)
return
}
//RBAC enforcer Ends
common.WriteJsonResp(w, err, bean, http.StatusOK)
}
func (impl ClusterRestHandlerImpl) FindNoteByClusterId(w http.ResponseWriter, r *http.Request) {
userId, err := impl.userService.GetLoggedInUser(r)
if userId == 0 || err != nil {
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
return
}
vars := mux.Vars(r)
id := vars["id"]
clusterId, err := strconv.Atoi(id)
if err != nil {
impl.logger.Errorw("request err, FindById", "error", err, "clusterId", id)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
bean, err := impl.clusterDescriptionService.FindByClusterIdWithClusterDetails(clusterId)
if err != nil {
if err == pg.ErrNoRows {
impl.logger.Errorw("cluster not found, FindById", "err", err, "clusterId", id)
common.WriteJsonResp(w, errors.New("invalid cluster id"), nil, http.StatusNotFound)
return
}
impl.logger.Errorw("service err, FindById", "err", err, "clusterId", id)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
// RBAC enforcer applying
token := r.Header.Get("token")
authenticated, err := impl.clusterRbacService.CheckAuthorization(bean.ClusterName, bean.ClusterId, token, userId, true)
if err != nil {
impl.logger.Errorw("error in checking rbac for cluster", "err", err, "clusterId", bean.ClusterId)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
if !authenticated {
common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)
return
}
//RBAC enforcer Ends
common.WriteJsonResp(w, err, bean, http.StatusOK)
}
func (impl ClusterRestHandlerImpl) Update(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("token")
decoder := json.NewDecoder(r.Body)
userId, err := impl.userService.GetLoggedInUser(r)
if userId == 0 || err != nil {
impl.logger.Errorw("service err, Update", "error", err, "userId", userId)
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
return
}
var bean bean2.ClusterBean
err = decoder.Decode(&bean)
if err != nil {
impl.logger.Errorw("request err, Update", "error", err, "payload", bean)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
impl.logger.Infow("request payload, Update", "payload", bean)
err = impl.validator.Struct(bean)
if err != nil {
impl.logger.Errorw("validate err, Update", "error", err, "payload", bean)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
// RBAC enforcer applying
if ok := impl.enforcer.Enforce(token, casbin.ResourceCluster, casbin.ActionUpdate, bean.ClusterName); !ok {
common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)
return
}
// RBAC enforcer ends
ctx, cancel := context.WithCancel(r.Context())
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
if util2.IsBaseStack() {
ctx = context.WithValue(ctx, "token", token)
}
_, err = impl.clusterService.Update(ctx, &bean, userId)
if err != nil {
impl.logger.Errorw("service err, Update", "error", err, "payload", bean)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
common.WriteJsonResp(w, err, bean, http.StatusOK)
}
func (impl ClusterRestHandlerImpl) UpdateClusterDescription(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("token")
decoder := json.NewDecoder(r.Body)
userId, err := impl.userService.GetLoggedInUser(r)
if userId == 0 || err != nil {
impl.logger.Errorw("service err, Update", "error", err, "userId", userId)
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
return
}
var bean bean2.ClusterBean
err = decoder.Decode(&bean)
if err != nil {
impl.logger.Errorw("request err, UpdateClusterDescription", "error", err, "payload", bean)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
impl.logger.Infow("request payload, UpdateClusterDescription", "payload", bean)
//TODO: add apt validation
clusterDescription, err := impl.clusterDescriptionService.FindByClusterIdWithClusterDetails(bean.Id)
if err != nil {
impl.logger.Errorw("service err, FindById", "err", err, "clusterId", bean.Id)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
// RBAC enforcer applying
authenticated := impl.clusterRbacService.CheckAuthorisationForAllK8sPermissions(token, clusterDescription.ClusterName, casbin.ActionUpdate)
if !authenticated {
common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)
return
}
// RBAC enforcer ends
err = impl.clusterService.UpdateClusterDescription(&bean, userId)
if err != nil {
impl.logger.Errorw("service err, UpdateClusterDescription", "error", err, "payload", bean)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
common.WriteJsonResp(w, err, "Cluster description updated successfully", http.StatusOK)
}
func (impl ClusterRestHandlerImpl) UpdateClusterNote(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("token")
decoder := json.NewDecoder(r.Body)
userId, err := impl.userService.GetLoggedInUser(r)
if userId == 0 || err != nil {
impl.logger.Errorw("service err, Update", "error", err, "userId", userId)
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
return
}
var bean repository.GenericNote
err = decoder.Decode(&bean)
if err != nil {
impl.logger.Errorw("request err, Update", "error", err, "payload", bean)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
impl.logger.Infow("request payload, Update", "payload", bean)
err = impl.validator.Struct(bean)
if err != nil {
impl.logger.Errorw("validate err, Update", "error", err, "payload", bean)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
clusterDescription, err := impl.clusterDescriptionService.FindByClusterIdWithClusterDetails(bean.Identifier)
if err != nil {
impl.logger.Errorw("service err, FindById", "err", err, "clusterId", bean.Identifier)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
// RBAC enforcer applying
authenticated := impl.clusterRbacService.CheckAuthorisationForAllK8sPermissions(token, clusterDescription.ClusterName, casbin.ActionUpdate)
if !authenticated {
common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)
return
}
// RBAC enforcer ends
bean.IdentifierType = repository.ClusterType
clusterNoteResponseBean, err := impl.clusterNoteService.Update(&bean, userId)
if err != nil {
impl.logger.Errorw("cluster note service err, Update", "error", err, "payload", bean)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
common.WriteJsonResp(w, err, clusterNoteResponseBean, http.StatusOK)
}
func (impl ClusterRestHandlerImpl) FindAllForAutoComplete(w http.ResponseWriter, r *http.Request) {
start := time.Now()
clusterList, err := impl.clusterService.FindAllForAutoComplete()
dbOperationTime := time.Since(start)
if err != nil {
impl.logger.Errorw("service err, FindAllForAutoComplete", "error", err)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
var result []bean2.ClusterBean
v := r.URL.Query()
authEnabled := true
auth := v.Get("auth")
if len(auth) > 0 {
authEnabled, err = strconv.ParseBool(auth)
if err != nil {
authEnabled = true
err = nil
//ignore error, apply rbac by default
}
}
// RBAC enforcer applying
token := r.Header.Get("token")
start = time.Now()
for _, item := range clusterList {
if authEnabled == true {
if ok := impl.enforcer.Enforce(token, casbin.ResourceCluster, casbin.ActionGet, item.ClusterName); ok {
result = append(result, item)
}
} else {
result = append(result, item)
}
}
impl.logger.Infow("Cluster elapsed Time for enforcer", "dbElapsedTime", dbOperationTime, "enforcerTime", time.Since(start), "envSize", len(result))
//RBAC enforcer Ends
if len(result) == 0 {
result = make([]bean2.ClusterBean, 0)
}
common.WriteJsonResp(w, err, result, http.StatusOK)
}
func (impl ClusterRestHandlerImpl) DeleteCluster(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
userId, err := impl.userService.GetLoggedInUser(r)
if userId == 0 || err != nil {
impl.logger.Errorw("service err, Delete", "error", err, "userId", userId)
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
return
}
var bean bean2.DeleteClusterBean
err = decoder.Decode(&bean)
if err != nil {
impl.logger.Errorw("request err, Delete", "error", err, "payload", bean)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
impl.logger.Debugw("request payload, Delete", "payload", bean)
err = impl.validator.Struct(bean)
if err != nil {
impl.logger.Errorw("validate err, Delete", "error", err, "payload", bean)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
// RBAC enforcer applying
token := r.Header.Get("token")
if ok := impl.enforcer.Enforce(token, casbin.ResourceCluster, casbin.ActionCreate, "*"); !ok {
common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)
return
}
//RBAC enforcer Ends
err = impl.deleteService.DeleteCluster(&bean, userId)
if err != nil {
impl.logger.Errorw("error in deleting cluster", "err", err, "id", bean.Id)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
common.WriteJsonResp(w, err, CLUSTER_DELETE_SUCCESS_RESP, http.StatusOK)
}
func (impl ClusterRestHandlerImpl) GetAllClusterNamespaces(w http.ResponseWriter, r *http.Request) {
token := r.Header.Get("token")
userId, err := impl.userService.GetLoggedInUser(r)
if userId == 0 || err != nil {
impl.logger.Errorw("err, GetAllClusterNamespaces", "error", err, "userId", userId)
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
return
}
clusterNamespaces := impl.clusterService.GetAllClusterNamespaces()
// RBAC enforcer applying
filteredClusterNamespaces, err := impl.HandleRbacForClusterNamespace(userId, token, clusterNamespaces)
if err != nil {
impl.logger.Errorw("error in GetAllClusterNamespaces", "err", err)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
//RBAC enforcer Ends
common.WriteJsonResp(w, nil, filteredClusterNamespaces, http.StatusOK)
}
func (impl ClusterRestHandlerImpl) HandleRbacForClusterNamespace(userId int32, token string, clusterNamespaces map[string][]string) (map[string][]string, error) {
filteredClusterNamespaces := make(map[string][]string)
if ok := impl.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionGet, "*"); ok {
return clusterNamespaces, nil
}
roles, err := impl.clusterService.FetchRolesFromGroup(userId)
if err != nil {
impl.logger.Errorw("error on fetching user roles for cluster list", "err", err)
return nil, err
}
clusterAndNameSpaceVsAllowedMap := make(map[string]bool, len(roles))
clusterNameVsAllAllowedMap := make(map[string]bool, len(roles))
for _, role := range roles {
clusterAndNameSpaceVsAllowedMap[strings.ToLower(role.Cluster+"_"+role.Namespace)] = true
if role.Namespace == "" {
clusterNameVsAllAllowedMap[role.Cluster] = true
} else {
clusterNameVsAllAllowedMap[role.Cluster] = false
}
}
for clusterName, allNamespaces := range clusterNamespaces {
if val, exist := clusterNameVsAllAllowedMap[clusterName]; val {
filteredClusterNamespaces[clusterName] = allNamespaces
} else if exist {
for _, namespace := range allNamespaces {
if val2, exist2 := clusterAndNameSpaceVsAllowedMap[strings.ToLower(clusterName+"_"+namespace)]; exist2 && val2 {
filteredClusterNamespaces[clusterName] = append(filteredClusterNamespaces[clusterName], namespace)
}
}
}
}
return filteredClusterNamespaces, nil
}
func (impl ClusterRestHandlerImpl) GetClusterNamespaces(w http.ResponseWriter, r *http.Request) {
//token := r.Header.Get("token")
vars := mux.Vars(r)
clusterIdString := vars["clusterId"]
userId, err := impl.userService.GetLoggedInUser(r)
if userId == 0 || err != nil {
impl.logger.Errorw("user not authorized", "error", err, "userId", userId)
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
return
}
token := r.Header.Get("token")
isActionUserSuperAdmin := false
if ok := impl.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionGet, "*"); ok {
isActionUserSuperAdmin = true
}
clusterId, err := strconv.Atoi(clusterIdString)
if err != nil {
impl.logger.Errorw("failed to extract clusterId from param", "error", err, "clusterId", clusterIdString)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
return
}
allClusterNamespaces, err := impl.clusterService.FindAllNamespacesByUserIdAndClusterId(userId, clusterId, isActionUserSuperAdmin)
if err != nil {
// Check if it's a cluster connectivity error and return appropriate status code
if err.Error() == cluster.ErrClusterNotReachable {
impl.logger.Errorw("cluster connectivity error in GetClusterNamespaces", "error", err, "clusterId", clusterId)
common.WriteJsonResp(w, err, nil, http.StatusBadRequest)
} else {
impl.logger.Errorw("error in GetClusterNamespaces", "error", err, "clusterId", clusterId)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
}
return
}
common.WriteJsonResp(w, nil, allClusterNamespaces, http.StatusOK)
}
func (impl ClusterRestHandlerImpl) FindAllForClusterPermission(w http.ResponseWriter, r *http.Request) {
userId, err := impl.userService.GetLoggedInUser(r)
if userId == 0 || err != nil {
impl.logger.Errorw("user not authorized", "error", err, "userId", userId)
common.WriteJsonResp(w, err, "Unauthorized User", http.StatusUnauthorized)
return
}
token := r.Header.Get("token")
isActionUserSuperAdmin := false
if ok := impl.enforcer.Enforce(token, casbin.ResourceGlobal, casbin.ActionGet, "*"); ok {
isActionUserSuperAdmin = true
}
clusterList, err := impl.clusterService.FindAllForClusterByUserId(userId, isActionUserSuperAdmin)
if err != nil {
impl.logger.Errorw("error in deleting cluster", "err", err)
common.WriteJsonResp(w, err, nil, http.StatusInternalServerError)
return
}
// RBAC enforcer applying
// Already applied at service layer
//RBAC enforcer Ends
if len(clusterList) == 0 {
// assumption is that if list is empty, then it can happen only in case of Unauthorized (but not sending Unauthorized for super-admin user)
if isActionUserSuperAdmin {
clusterList = make([]bean2.ClusterBean, 0)
} else {
common.WriteJsonResp(w, errors.New("unauthorized"), nil, http.StatusForbidden)
return
}
}
common.WriteJsonResp(w, err, clusterList, http.StatusOK)
}