-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathwebhook.go
1807 lines (1528 loc) · 55.7 KB
/
webhook.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"context"
"os"
"github.com/buger/jsonparser"
guuid "github.com/google/uuid"
"k8s.io/api/admission/v1"
admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
//"k8s.io/kubernetes/pkg/apis/core/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/rest"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
platformworkflowclientset "github.com/cloud-ark/kubeplus/platform-operator/pkg/generated/clientset/versioned"
platformworkflowv1alpha1 "github.com/cloud-ark/kubeplus/platform-operator/pkg/apis/workflowcontroller/v1alpha1"
)
type WebhookServer struct {
server *http.Server
}
// WhSvrParameters ...
// Webhook Server parameters
type WhSvrParameters struct {
port int // webhook server port
certFile string // path to the x509 certificate for https
keyFile string // path to the x509 private key matching `CertFile`
alsoLogToStderr bool
}
type patchOperation struct {
Op string `json:"op"`
Path string `json:"path"`
Value interface{} `json:"value,omitempty"`
}
type label struct {
key string
value string
}
type ResourceComposition struct {
CPU_limits string
Mem_limits string
CPU_requests string
Mem_requests string
Name string
Namespace string
ChartName string
ChartURL string
Group string
Kind string
Plural string
Version string
Policy platformworkflowv1alpha1.Pol
}
var (
runtimeScheme = runtime.NewScheme()
codecs = serializer.NewCodecFactory(runtimeScheme)
deserializer = codecs.UniversalDeserializer()
accountidentity = "accountidentity"
webhook_namespace = GetNamespace()
annotations StoredAnnotations = StoredAnnotations{}
customAPIPlatformWorkflowMap map[string]string
customKindPluralMap map[string]string
customAPIInstanceUIDMap map[string]string
customAPIQuotaMap map[string]interface{}
kindPluralMap map[string]string
chartKindMap map[string]string
resourcePolicyMap map[string]interface{}
resourceNameObjMap map[string]interface{}
namespaceHelmAnnotationMap map[string]string
maxAllowedLength int
maxLengthKind int
resCompositions []ResourceComposition
)
func init() {
_ = corev1.AddToScheme(runtimeScheme)
_ = admissionregistrationv1beta1.AddToScheme(runtimeScheme)
// defaulting with webhooks:
// https://github.com/kubernetes/kubernetes/issues/57982
_ = v1.AddToScheme(runtimeScheme)
annotations.KindToEntry = make(map[string][]Entry, 0)
customAPIPlatformWorkflowMap = make(map[string]string,0)
customAPIInstanceUIDMap = make(map[string]string,0)
customKindPluralMap = make(map[string]string,0)
customAPIQuotaMap = make(map[string]interface{}, 0)
kindPluralMap = make(map[string]string,0)
chartKindMap = make(map[string]string,0)
resourcePolicyMap = make(map[string]interface{}, 0)
resourceNameObjMap = make(map[string]interface{}, 0)
namespaceHelmAnnotationMap = make(map[string]string, 0)
maxAllowedLength = 30
maxLengthKind = 28
go setup()
}
func setup() {
fmt.Println("Inside setup")
var resCompositionsArr []byte
var resString string
for {
resCompositionsArr = GetExistingResourceCompositions()
resString = string(resCompositionsArr)
fmt.Printf("ExistingResCompositions:%s\n", resString)
if strings.Contains(resString, "connection refused") {
time.Sleep(1 * time.Second)
} else {
break
}
}
fmt.Printf("ExistingResCompositions1:%s\n", resString)
err := json.Unmarshal([]byte(resString), &resCompositions)
if err != nil {
fmt.Printf("Unmarshalling error:%s\n", err.Error())
}
fmt.Printf("Rescompositions:%v\n", resCompositions)
for _, res := range resCompositions {
name := res.Name
ns := res.Namespace
group := res.Group
version := res.Version
kind := res.Kind
plural := res.Plural
chartName := res.ChartName
chartURL := res.ChartURL
cpu_limits := res.CPU_limits
mem_limits := res.Mem_limits
cpu_requests := res.CPU_requests
mem_requests := res.Mem_requests
podPolicy := res.Policy
customAPI := group + "/" + version + "/" + kind
fmt.Printf("%s %s %s %s %s %s %s %s %s %s %s %s %s\n", name, ns, group, version, kind, plural, chartName, chartURL, cpu_limits, mem_limits, cpu_requests, mem_requests, customAPI)
customAPIPlatformWorkflowMap[customAPI] = name
customKindPluralMap[customAPI] = plural
var quota_map map[string]string
quota_map = make(map[string]string)
quota_map["requests.cpu"] = cpu_requests
quota_map["limits.cpu"] = cpu_limits
quota_map["requests.memory"] = mem_requests
quota_map["limits.memory"] = mem_limits
customAPIQuotaMap[customAPI] = quota_map
lowercaseKind := strings.ToLower(kind)
kindPluralMap[lowercaseKind] = plural
customAPI1 := group + "/" + version + "/" + lowercaseKind
resourcePolicyMap[customAPI1] = podPolicy
}
}
// main mutation process
func (whsvr *WebhookServer) mutate(ar *v1.AdmissionReview, httpMethod string) *v1.AdmissionResponse {
req := ar.Request
fmt.Println("=== Request ===")
fmt.Println(req.Kind.Kind)
fmt.Println(req.Name)
fmt.Println(req.Namespace)
fmt.Println(httpMethod)
//fmt.Printf("%s\n", string(req.Object.Raw))
fmt.Println("=== Request ===")
fmt.Println("=== User ===")
fmt.Println(req.UserInfo.Username)
fmt.Println("=== User ===")
user := req.UserInfo.Username
var patchOperations []patchOperation
patchOperations = make([]patchOperation, 0)
if httpMethod == http.MethodDelete {
resp := handleDelete(ar)
return resp
}
saveResource(ar)
if req.Kind.Kind == "ResourcePolicy" {
saveResourcePolicy(ar)
}
if req.Kind.Kind == "ResourceComposition" {
if strings.Contains(user, "kubeplus-saas-provider") {
crdNameCheck := checkCRDNameValidity(ar)
if crdNameCheck != "" {
return &v1.AdmissionResponse{
Result: &metav1.Status{
Message: crdNameCheck,
},
}
}
message := checkChartExists(ar)
if message != "" {
return &v1.AdmissionResponse{
Result: &metav1.Status{
Message: message,
},
}
}
statusMessageToCheck := "New CRD defined in ResourceComposition created successfully."
statusMessage := getStatusMessage(ar)
if statusMessageToCheck == statusMessage {
fmt.Printf("Intercepted call from platform-controller. Nothing to do for this call..\n")
return &v1.AdmissionResponse{
Allowed: true,
}
}
errResponse := trackCustomAPIs(ar)
if errResponse != nil {
//fmt.Printf("111222333")
return errResponse
}
} else {
return &v1.AdmissionResponse{
Result: &metav1.Status{
Message: "ResourceComposition instance can only be created by Provider.",
},
}
}
}
var pacAnnotationMap map[string]string
if req.Kind.Kind == "CustomResourceDefinition" {
pacAnnotationMap = getPaCAnnotation(ar)
}
accountIdentityAnnotationMap := getAccountIdentityAnnotation(ar)
allAnnotations := mergeMaps(pacAnnotationMap, accountIdentityAnnotationMap)
annotationPatch := getAnnotationPatch(allAnnotations)
patchOperations = append(patchOperations, annotationPatch)
errResponse := handleCustomAPIs(ar)
if errResponse != nil {
return errResponse
}
if req.Kind.Kind == "Pod" {
customAPI, rootKind, rootName, rootNamespace := checkServiceLevelPolicyApplicability(ar)
var podResourcePatches []patchOperation
if customAPI != "" && strings.Contains(customAPI, "platformapi.kubeplus") {
podResourcePatches = applyPolicies(ar, customAPI, rootKind, rootName, rootNamespace)
// Add label if the Pod belongs to custom resource
labels := make(map[string]string, 0)
allLabels, _, _, err := jsonparser.Get(req.Object.Raw, "metadata", "labels")
if err == nil {
json.Unmarshal(allLabels, &labels)
fmt.Printf("Pod all labels:%v\n", labels)
}
labels["partof"] = strings.ToLower(rootKind + "-" + rootName)
fmt.Printf("All labels:%v\n", labels)
podLabelPatch := patchOperation{
Op: "add",
Path: "/metadata/labels",
Value: labels,
}
patchOperations = append(patchOperations, podLabelPatch)
} else {
// Check if Namespace-level policy is applicable.
podResourcePatches = checkAndApplyNSPolicies(ar)
}
for _, podPatch := range podResourcePatches {
patchOperations = append(patchOperations, podPatch)
}
}
if req.Kind.Kind == "Namespace" {
if strings.Contains(user, "kubeplus-saas-provider") || strings.Contains(user, "kubeplus-saas-consumer") {
return &v1.AdmissionResponse{
Result: &metav1.Status{
Message: "Permission denied: Namespace cannot be created.",
},
}
}
if !strings.Contains(webhook_namespace, "default") {
return &v1.AdmissionResponse{
Result: &metav1.Status{
Message: "Permission denied: Namespace can be created only if KubePlus is deployed in default Namespace.",
},
}
}
fmt.Printf("Recording Namespace...\n")
releaseName := getReleaseName(ar)
fmt.Printf("DEF Release name:%s\n", releaseName)
if releaseName != "" {
_, nsName, _ := getObjectDetails(ar)
namespaceHelmAnnotationMap[nsName] = releaseName
}
}
fmt.Printf("PatchOperations:%v\n", patchOperations)
patchBytes, _ := json.Marshal(patchOperations)
//fmt.Printf("---------------------------------\n")
// marshal the struct into bytes to pass into AdmissionResponse
return &v1.AdmissionResponse{
Allowed: true,
Patch: patchBytes,
PatchType: func() *v1.PatchType {
pt := v1.PatchTypeJSONPatch
return &pt
}(),
}
}
func getStatusMessage(ar *v1.AdmissionReview) string {
fmt.Println("Inside getStatusMessage")
req := ar.Request
body := req.Object.Raw
status, err := jsonparser.GetUnsafeString(body, "status","status")
if err != nil {
fmt.Errorf("Error:%s\n", err)
}
fmt.Printf("getStatusMessage:%s\n", status)
return status
}
func handleDelete(ar *v1.AdmissionReview) *v1.AdmissionResponse {
fmt.Println("Inside handleDelete...")
req := ar.Request
//fmt.Printf("%v\n---",req)
//body := req.Object.Raw
namespace := req.Namespace
resName := req.Name
//fmt.Printf("Body:%v\n", body)
apiv1 := req.Kind
apiv2 := req.Resource
fmt.Printf("&&&&&\n")
fmt.Printf("APIv1:%s, APIv2:%s\n", apiv1, apiv2)
group := req.Resource.Group
version := req.Resource.Version
kind := req.Kind.Kind
fmt.Printf("Group:%s, version:%s\n", group, version)
plural := string(GetPlural(kind, group))
apiVersion := group + "/" + version
fmt.Printf("NS:%s, Kind:%s, apiVersion:%s, group:%s, version:%s plural:%s resName:%s\n",
namespace, kind, apiVersion, group, version, plural, resName)
fmt.Println("=== User ===")
fmt.Println(req.UserInfo.Username)
fmt.Println("=== User ===")
user := req.UserInfo.Username
if user == "system:serviceaccount:default:kubeplus" {
return &v1.AdmissionResponse{
Allowed: true,
}
}
if kind == "ResourceComposition" {
if !strings.Contains(user, "kubeplus-saas-provider") {
return &v1.AdmissionResponse{
Result: &metav1.Status{
Message: "ResourceComposition instance can only be deleted by Provider.",
},
}
}
// check status of helm releases for this CRD
fmt.Println("Delete ResourceComposition")
config, err := rest.InClusterConfig()
if err != nil {
fmt.Printf("Error:%s\n", err.Error())
}
var sampleclientset platformworkflowclientset.Interface
sampleclientset, err = platformworkflowclientset.NewForConfig(config)
if err != nil {
fmt.Printf("Error:%s\n", err.Error())
}
platformWorkflow, err := sampleclientset.WorkflowsV1alpha1().ResourceCompositions(namespace).Get(context.Background(), resName, metav1.GetOptions{})
if err != nil {
fmt.Printf("Error:%s\n", err.Error())
}
crdnamespace := platformWorkflow.ObjectMeta.Namespace
fmt.Printf("Namespace: %s\n", crdnamespace)
crdkind := platformWorkflow.Spec.NewResource.Resource.Kind
crdgroup := platformWorkflow.Spec.NewResource.Resource.Group
crdversion := platformWorkflow.Spec.NewResource.Resource.Version
crdplural := platformWorkflow.Spec.NewResource.Resource.Plural
fmt.Printf("Kind:%s, Group:%s, Version:%s, Plural:%s\n", crdkind, crdgroup, crdversion, crdplural)
ownerRes := schema.GroupVersionResource{Group: crdgroup,
Version: crdversion,
Resource: crdplural}
fmt.Printf("GVR: %v\n", ownerRes)
dynamicClient, err := dynamic.NewForConfig(config)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
}
crdObjList, err := dynamicClient.Resource(ownerRes).Namespace(crdnamespace).List(context.Background(), metav1.ListOptions{})
if err != nil {
fmt.Printf("Error:%v\n...checking at cluster-scope", err)
crdObjList, err = dynamicClient.Resource(ownerRes).List(context.Background(), metav1.ListOptions{})
if err != nil {
fmt.Printf("Error:%v\n", err)
}
}
if crdObjList != nil {
for _, instanceObj := range crdObjList.Items {
objData := instanceObj.UnstructuredContent()
status := objData["status"]
labels := instanceObj.GetLabels()
forcedDelete, _ := labels["delete"]
if status == nil && forcedDelete == "" {
return &v1.AdmissionResponse{
Result: &metav1.Status{
Message: "Error: ResourceComposition instance cannot be deleted. It has an application instance starting up.",
},
}
}
}
}
}
if kind == "Namespace" {
if (strings.Contains(user, "kubeplus-saas-provider") || strings.Contains(user, "kubeplus-saas-consumer")) {
return &v1.AdmissionResponse{
Result: &metav1.Status{
Message: "Permission denied: Namespace cannot be deleted.",
},
}
}
}
fmt.Printf("Calling DeleteCRDInstances...")
resp := DeleteCRDInstances(kind, group, version, plural, namespace, resName)
fmt.Println("After calling DeleteCRDInstances...")
respString := string(resp)
if strings.Contains(respString, "Error") {
fmt.Println(respString)
return &v1.AdmissionResponse{
Result: &metav1.Status{
Message: respString,
},
}
}
return &v1.AdmissionResponse{
Allowed: true,
}
}
func checkAndApplyNSPolicies(ar *v1.AdmissionReview) []patchOperation {
req := ar.Request
// Get Pod's Namespace; Check if Namespace has Helm release annotation;
// Check if there is a Policy to be applied for that kind.
// Assumption: A Given Kind name can exist in only one API group.
// TODO:
// Look up apiVersion + "/" + kind from arSaved
// Use above to find out resourcePolicy from resourcePolicyMap
// For applying polices - the spec comes from resourcePolicy, the values
// come from arSaved.
podNamespace := req.Namespace
fmt.Printf("Pod Namespace:%s\n", podNamespace)
releaseName := namespaceHelmAnnotationMap[podNamespace]
fmt.Printf("Release Name:%s\n", releaseName)
customAPI := ""
serviceKind := ""
serviceInstance := ""
var podPolicy interface{}
if releaseName != "" {
parts := strings.Split(releaseName, "-")
if len(parts) > 0 {
serviceKind = parts[0]
serviceInstance = parts[1]
for key, value := range resourcePolicyMap {
parts1 := strings.Split(key, "/")
if len(parts1) == 3 {
targetKind := parts1[2]
fmt.Printf("TargetKind:%s\n", targetKind)
if targetKind == serviceKind {
customAPI = key
podPolicy = value
fmt.Printf("Custom API for Policy application:%s\n", customAPI)
}
}
}
}
}
patchOperations := make([]patchOperation, 0)
// Check if this is Namespace-scoped policy
if podPolicy != nil {
podPolicy1 := podPolicy.(platformworkflowv1alpha1.Pol)
scope := podPolicy1.PolicyResources.Scope
fmt.Printf("Scope:%s\n",scope)
if scope == "Namespace" {
resKindAndName := serviceKind + "-" + serviceInstance
resAR := resourceNameObjMap[resKindAndName].(*v1.AdmissionReview)
req := resAR.Request
body := resAR.Request.Object.Raw
serviceKindCanonical := req.Kind.Kind
serviceKindNamespace, _ := jsonparser.GetUnsafeString(body, "metadata", "namespace")
if serviceKindNamespace == "" {
serviceKindNamespace = "default"
}
fmt.Printf("serviceKindCanonical:%s ServiceInstance:%s ServiceNamespace:%s\n", serviceKindCanonical, serviceInstance, serviceKindNamespace)
patchOperations = applyPolicies(ar, customAPI, serviceKindCanonical, serviceInstance, serviceKindNamespace)
}
}
return patchOperations
}
func getReleaseName(ar *v1.AdmissionReview) string {
req := ar.Request
annotations1 := make(map[string]string, 0)
allAnnotations, _, _, err := jsonparser.Get(req.Object.Raw, "metadata", "annotations")
if err == nil {
json.Unmarshal(allAnnotations, &annotations1)
//fmt.Printf("All Annotations:%v\n", annotations1)
}
for key, value := range annotations1 {
if key == "meta.helm.sh/release-name" {
releaseName := value
fmt.Printf("ABC --- Release name:%s\n", releaseName)
return releaseName
}
}
return ""
}
func saveResource(ar *v1.AdmissionReview) {
fmt.Printf("Inside saveResource")
kind, resName, _ := getObjectDetails(ar)
//key := kind + "/" + namespace + "/" + resName
key := kind + "-" + resName
fmt.Printf("Res Key:%s\n", key)
val, ok := resourceNameObjMap[key]
if !ok {
resourceNameObjMap[key] = ar
} else {
fmt.Printf("Key %s already present in resourceNameObjMap\n", key)
fmt.Printf("%v\n", val)
}
}
func saveResourcePolicy(ar *v1.AdmissionReview) {
req := ar.Request
body := req.Object.Raw
resPolicyName, _ := jsonparser.GetUnsafeString(body, "metadata", "name")
fmt.Printf("Resource Policy Name:%s\n", resPolicyName)
var resourcePolicy platformworkflowv1alpha1.ResourcePolicy
err = json.Unmarshal(body, &resourcePolicy)
if err != nil {
fmt.Println(err)
}
kind := resourcePolicy.Spec.Resource.Kind
lowercaseKind := strings.ToLower(kind)
group := resourcePolicy.Spec.Resource.Group
version := resourcePolicy.Spec.Resource.Version
fmt.Printf("Kind:%s, Group:%s, Version:%s\n", kind, group, version)
podPolicy := resourcePolicy.Spec.Policy
fmt.Printf("Pod Policy:%v\n", podPolicy)
customAPI := group + "/" + version + "/" + lowercaseKind
resourcePolicyMap[customAPI] = podPolicy
fmt.Printf("Resource Policy Map:%v\n", resourcePolicyMap)
}
func checkServiceLevelPolicyApplicability(ar *v1.AdmissionReview) (string, string, string, string) {
fmt.Printf("Inside checkServiceLevelPolicyApplicability")
req := ar.Request
body := req.Object.Raw
//fmt.Printf("Body:%v\n", body)
namespace := req.Namespace
fmt.Println("Namespace:%s\n",namespace)
// TODO: looks like we can just keep one - namespace or namespace1
namespace1, _, _, err := jsonparser.Get(body, "metadata", "namespace")
if err == nil {
fmt.Printf("Namespace1:%s\n", namespace1)
}
ownerKind, _, _, err1 := jsonparser.Get(body, "metadata", "ownerReferences", "[0]", "kind")
if err1 != nil {
fmt.Printf("Error:%v\n", err1)
} else {
fmt.Printf("ownerKind:%v\n", string(ownerKind))
}
ownerName, _, _, err1 := jsonparser.Get(body, "metadata", "ownerReferences", "[0]", "name")
if err1 != nil {
fmt.Printf("Error:%v\n", err1)
} else {
fmt.Printf("ownerName:%v\n", string(ownerName))
}
ownerAPIVersion, _, _, err1 := jsonparser.Get(body, "metadata", "ownerReferences", "[0]", "apiVersion")
if err1 != nil {
fmt.Printf("Error:%v\n", err1)
} else {
fmt.Printf("ownerAPIVersion:%v\n", string(ownerAPIVersion))
}
ownerKindS := string(ownerKind)
ownerNameS := string(ownerName)
ownerAPIVersionS := string(ownerAPIVersion)
rootKind := ""
rootName := ""
rootAPIVersion := ""
if ownerKindS == "" && ownerNameS == "" && ownerAPIVersionS == "" {
annotations1 := make(map[string]string, 0)
allAnnotations, _, _, err := jsonparser.Get(req.Object.Raw, "metadata", "annotations")
if err == nil {
json.Unmarshal(allAnnotations, &annotations1)
//fmt.Printf("All Annotations:%v\n", annotations1)
}
releaseName := annotations1["meta.helm.sh/release-name"]
fmt.Printf("Helm release name:%s\n", releaseName)
capiGroup := ""
capiVersion := ""
rootKind, rootName, capiGroup, capiVersion = getAPIDetailsFromHelmReleaseAnnotation(releaseName)
rootAPIVersion = capiGroup + "/" + capiVersion
fmt.Printf("RK:%s, RN:%s, RAPI:%s\n", rootKind, rootName, rootAPIVersion)
} else {
rootKind, rootName, rootAPIVersion = findRoot(namespace, ownerKindS, ownerNameS, ownerAPIVersionS)
}
fmt.Printf("Root Kind:%s\n", rootKind)
fmt.Printf("Root Name:%s\n", rootName)
fmt.Printf("Root API Version:%s\n", rootAPIVersion)
lowercaseKind := strings.ToLower(rootKind)
// Check if the rootKind, rootName, rootAPIVersion is registered to be applied policies on.
customAPI := rootAPIVersion + "/" + lowercaseKind
fmt.Printf("Custom API:%s\n", customAPI)
if podPolicy, ok := resourcePolicyMap[customAPI]; ok {
fmt.Printf("Resource Policy:%v\n", podPolicy)
return customAPI, rootKind, rootName, string(namespace1)
}
return "", "", "", ""
}
func getGroupVersion(apiVersion string) (string, string) {
parts := strings.Split(apiVersion, "/")
group := ""
version := ""
if len(parts) == 2 {
group = parts[0]
version = parts[1]
} else {
version = parts[0]
}
return group, version
}
func findRoot(namespace, kind, name, apiVersion string) (string, string, string) {
rootKind := ""
rootName := ""
rootAPIVersion := ""
time.Sleep(10)
group, version := getGroupVersion(apiVersion)
fmt.Printf("Group:%s\n", group)
fmt.Printf("Version:%s\n", version)
fmt.Printf("ResName:%s\n", name)
fmt.Printf("Namespace:%s\n", namespace)
ownerResKindPlural, _, ownerResApiVersion, ownerResGroup := getKindAPIDetails(kind)
fmt.Printf("ownerResKindPlural:%s\n", ownerResKindPlural)
fmt.Printf("ownerResApiVersion:%s\n", ownerResApiVersion)
fmt.Printf("ownerResGroup:%s\n", ownerResGroup)
ownerRes := schema.GroupVersionResource{Group: ownerResGroup,
Version: ownerResApiVersion,
Resource: ownerResKindPlural}
fmt.Printf("OwnerRes:%v\n", ownerRes)
dynamicClient, err1 := getDynamicClient1()
if err1 != nil {
fmt.Printf("Error 1:%v\n", err1)
fmt.Println(err1)
return rootKind, rootName, rootAPIVersion
}
instanceObj, err2 := dynamicClient.Resource(ownerRes).Namespace(namespace).Get(context.Background(),
name,
metav1.GetOptions{})
if err2 != nil {
fmt.Printf("Error 2:%v\n", err2)
fmt.Println(err2)
return rootKind, rootName, rootAPIVersion
}
ownerReference := instanceObj.GetOwnerReferences()
if len(ownerReference) == 0 {
// Reached the root
// Jump of from the Helm annotation; should be of type <plural>-<name>
fmt.Printf("Intermediate Root kind:%s\n", kind)
fmt.Printf("Intermediate Root name:%s\n", name)
fmt.Printf("Intermediate Root APIVersion:%s\n", apiVersion)
annotations := instanceObj.GetAnnotations()
releaseName := annotations["meta.helm.sh/release-name"]
capiKind, oinstance, capiGroup, capiVersion := getAPIDetailsFromHelmReleaseAnnotation(releaseName)
return capiKind, oinstance, capiGroup + "/" + capiVersion
} else {
owner := ownerReference[0]
ownerKind := owner.Kind
ownerName := owner.Name
ownerAPIVersion := owner.APIVersion
rootKind, rootName, rootAPIVersion := findRoot(namespace, ownerKind, ownerName, ownerAPIVersion)
return rootKind, rootName, rootAPIVersion
}
}
func getAPIDetailsFromHelmReleaseAnnotation(releaseName string) (string, string, string, string) {
capiKind := ""
oinstance := ""
capiGroup := ""
capiVersion := ""
parts := strings.Split(releaseName, "-")
if len(parts) >= 2 {
okindLowerCase := parts[0]
if len(parts) > 2 {
oinstance = strings.Join(parts[1:],"-")
} else if len(parts) == 2 {
oinstance = parts[1]
}
fmt.Printf("KindPluralMap2:%v\n", kindPluralMap)
oplural := kindPluralMap[okindLowerCase]
fmt.Printf("OPlural:%s OInstance:%s\n", oplural, oinstance)
customAPI := ""
for k, v := range customKindPluralMap {
if v == oplural {
customAPI = k
break
}
}
fmt.Printf("CustomAPI:%s\n", customAPI)
if customAPI != "" {
capiParts := strings.Split(customAPI, "/")
capiGroup = capiParts[0]
capiVersion = capiParts[1]
capiKind = capiParts[2]
fmt.Printf("capiGroup:%s capiVersion:%s capiKind:%s\n", capiGroup, capiVersion, capiKind)
}
} else {
return "","","",""
}
return capiKind, oinstance, capiGroup, capiVersion
}
func applyPolicies(ar *v1.AdmissionReview, customAPI, rootKind, rootName, rootNamespace string) []patchOperation {
req := ar.Request
body := req.Object.Raw
podName, _ := jsonparser.GetUnsafeString(req.Object.Raw, "metadata", "name")
fmt.Printf("Pod Name:%s\n", podName)
/*
res1, _, _, _ := jsonparser.Get(body, "spec", "containers")
var containers map[string]any
json.Unmarshal(res1, &containers)
for key, value := range containers {
mapval := value.(map[string]any)
fmt.Printf("%v %v\n", key, mapval["name"])
}*/
// TODO: Defaulting to the first container. Take input for additional containers
res, dataType, _, err1 := jsonparser.Get(body, "spec", "containers", "[0]", "resources")
if err1 != nil {
fmt.Printf("Error:%v\n", err1)
} else {
fmt.Printf("Resources:%v\n", string(res))
}
var operation string
fmt.Printf("DataType:%s\n", dataType)
operation = "add"
podPolicy := resourcePolicyMap[customAPI]
fmt.Printf("PodPolicy:%v\n", podPolicy)
xType := fmt.Sprintf("%T", podPolicy)
fmt.Printf("Pod Policy type:%s\n", xType) // "[]int"
patchOperations := make([]patchOperation, 0)
podPolicy1 := podPolicy.(platformworkflowv1alpha1.Pol)
// 1. Requests
cpuRequest := podPolicy1.PolicyResources.Requests.CPU
memRequest := podPolicy1.PolicyResources.Requests.Memory
if cpuRequest != "" && memRequest != "" {
fmt.Printf("CPU Request:%s\n", cpuRequest)
if strings.Contains(cpuRequest, "values") {
cpuRequest = getFieldValueFromInstance(cpuRequest,rootKind, rootName)
}
fmt.Printf("CPU Request1:%s\n", cpuRequest)
fmt.Printf("Mem Request:%s\n", memRequest)
if strings.Contains(memRequest, "values") {
memRequest = getFieldValueFromInstance(memRequest,rootKind, rootName)
}
fmt.Printf("Mem Request1:%s\n", memRequest)
podResRequest := make(map[string]string,0)
podResRequest["cpu"] = cpuRequest
podResRequest["memory"] = memRequest
patch1 := patchOperation{
Op: operation,
Path: "/spec/containers/0/resources/requests",
Value: podResRequest,
}
patchOperations = append(patchOperations, patch1)
}
// 2. Limits
cpuLimit := podPolicy1.PolicyResources.Limits.CPU
memLimit := podPolicy1.PolicyResources.Limits.Memory
if cpuLimit != "" && memLimit != "" {
fmt.Printf("CPU Limit:%s\n", cpuLimit)
fmt.Printf("Mem Limit:%s\n", memLimit)
podResLimits := make(map[string]string,0)
podResLimits["cpu"] = cpuLimit
podResLimits["memory"] = memLimit
patch2 := patchOperation{
Op: operation,
Path: "/spec/containers/0/resources/limits",
Value: podResLimits,
}
patchOperations = append(patchOperations, patch2)
}
// 3. Node Selector
nodeSelector := podPolicy1.PolicyResources.NodeSelector
if nodeSelector != "" {
fmt.Printf("Node Selector:%s\n", nodeSelector)
fieldValueS := getFieldValueFromInstance(nodeSelector, rootKind, rootName)
if fieldValueS != "" {
podNodeSelector := make(map[string]string,0)
podNodeSelector["kubernetes.io/hostname"] = fieldValueS
patch3 := patchOperation{
Op: operation,
Path: "/spec/nodeSelector",
Value: podNodeSelector,
}
patchOperations = append(patchOperations, patch3)
}
}
return patchOperations
}
func getFieldValueFromInstance(fieldName, rootKind, rootName string) string {
parts := strings.Split(fieldName, ".")
field := parts[1]
field = strings.TrimSpace(field)
fmt.Printf("Field:%s\n", field)
//kind, resName, namespace := getObjectDetails(ar)
lowercaseRootKind := strings.ToLower(rootKind)
//rootkey := lowercaseRootKind + "/" + rootNamespace + "/" + rootName
rootkey := lowercaseRootKind + "-" + rootName
fmt.Printf("Root Key:%s\n", rootkey)
arSaved := resourceNameObjMap[rootkey].(*v1.AdmissionReview)
reqObject := arSaved.Request
reqspec := reqObject.Object.Raw
fieldValue, _, _, err2 := jsonparser.Get(reqspec, "spec", field)
fieldValueS := string(fieldValue)
if err2 != nil {
fmt.Printf("Error:%v\n", err2)
} else {
fmt.Printf("Fields:%v\n", string(fieldValue))
}
return fieldValueS
}
func getObjectDetails(ar *v1.AdmissionReview) (string, string, string) {
req := ar.Request
body := req.Object.Raw
kind := req.Kind.Kind
lowercaseKind := strings.ToLower(kind)
resName, _ := jsonparser.GetUnsafeString(body, "metadata", "name")
namespace, _ := jsonparser.GetUnsafeString(body, "metadata", "namespace")
if namespace == "" {
namespace = "default"
}
return lowercaseKind, resName, namespace
}
func trackCustomAPIs(ar *v1.AdmissionReview) *v1.AdmissionResponse {
req := ar.Request
body := req.Object.Raw
var platformWorkflow platformworkflowv1alpha1.ResourceComposition
err := json.Unmarshal(body, &platformWorkflow)
if err != nil {
fmt.Println(err)
}
platformWorkflowName, _ := jsonparser.GetUnsafeString(body, "metadata", "name")
namespace1, _, _, err := jsonparser.Get(body, "metadata", "namespace")
namespace := string(namespace1)
if namespace == "" {
namespace = "default"
}
// Ensure that ResourceComposition is created in the same Namespace
// where KubePlus is deployed.
kubePlusNS := GetNamespace()
if namespace != kubePlusNS {
return &v1.AdmissionResponse{
Result: &metav1.Status{
Message: "ResourceComposition instance should be created in the same Namespace as KubePlus Namespace (" + kubePlusNS + ")",
},
}
}