@@ -2,13 +2,15 @@ package mutation
22
33import (
44 "context"
5+ "encoding/json"
56 "fmt"
67 "github.com/jd-opensource/joylive-injector/pkg/admission"
78 "github.com/jd-opensource/joylive-injector/pkg/config"
89 "github.com/jd-opensource/joylive-injector/pkg/log"
910 "github.com/jd-opensource/joylive-injector/pkg/resource"
1011 jsoniter "github.com/json-iterator/go"
1112 "go.uber.org/zap"
13+ "gomodules.xyz/jsonpatch/v2"
1214 admissionv1 "k8s.io/api/admission/v1"
1315 apiv1 "k8s.io/api/admission/v1"
1416 appsv1 "k8s.io/api/apps/v1"
@@ -98,11 +100,28 @@ func injectionDeploy(request *admissionv1.AdmissionRequest) (*admissionv1.Admiss
98100 },
99101 }, nil
100102 }
103+ target := deploy .DeepCopy ()
101104 for k , v := range envs {
102- deploy .Spec .Template .Spec .Containers [0 ].Env = append (deploy .Spec .Template .Spec .Containers [0 ].Env , corev1.EnvVar {Name : k , Value : v })
105+ target .Spec .Template .Spec .Containers [0 ].Env = append (target .Spec .Template .Spec .Containers [0 ].Env , corev1.EnvVar {Name : k , Value : v })
103106 }
104107 log .Infof ("[mutation] /injection-deploy: add envs to deployment %s/%s, envs: %v, deploy's envs: %v" ,
105- deploy .Name , deploy .Namespace , envs , deploy .Spec .Template .Spec .Containers [0 ].Env )
108+ deploy .Name , deploy .Namespace , envs , target .Spec .Template .Spec .Containers [0 ].Env )
109+ patchStr , err := createDeployPatch (target , & deploy )
110+ if err != nil {
111+ return & admissionv1.AdmissionResponse {
112+ UID : request .UID ,
113+ Allowed : true ,
114+ }, nil
115+ }
116+ return & admissionv1.AdmissionResponse {
117+ UID : request .UID ,
118+ Allowed : true ,
119+ Patch : patchStr ,
120+ PatchType : func () * admissionv1.PatchType {
121+ pt := admissionv1 .PatchTypeJSONPatch
122+ return & pt
123+ }(),
124+ }, nil
106125 } else {
107126 log .Warnf ("[mutation] /injection-deploy: the deployment %s/%s does not have the %s or %s label" ,
108127 deploy .Name , deploy .Namespace , config .ServiceSpaceLabel , config .ApplicationLabel )
@@ -162,3 +181,16 @@ func deleteConfigMap(name, namespace string) error {
162181 }
163182 return nil
164183}
184+
185+ func createDeployPatch (target * appsv1.Deployment , original * appsv1.Deployment ) ([]byte , error ) {
186+ targetPod , err := json .Marshal (target )
187+ originalPod , err := json .Marshal (original )
188+ if err != nil {
189+ return nil , err
190+ }
191+ p , err := jsonpatch .CreatePatch (originalPod , targetPod )
192+ if err != nil {
193+ return nil , err
194+ }
195+ return json .Marshal (p )
196+ }
0 commit comments