Skip to content

Commit

Permalink
use patch vs update
Browse files Browse the repository at this point in the history
  • Loading branch information
kelseyhightower committed Jul 17, 2017
1 parent e914f0d commit 43c68ce
Showing 1 changed file with 27 additions and 3 deletions.
30 changes: 27 additions & 3 deletions envoy-initializer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
package main

import (
"encoding/json"
"flag"
"log"
"os"
Expand All @@ -25,6 +26,8 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
Expand Down Expand Up @@ -125,11 +128,32 @@ func initializePod(pod *corev1.Pod, c *config, clientset *kubernetes.Clientset)
pod.ObjectMeta.Initializers.Pending = append(pendingInitializers[:0], pendingInitializers[1:]...)
}

o, err := runtime.NewScheme().DeepCopy(pod)
if err != nil {
return err
}
initializedPod := o.(*corev1.Pod)

// Modify the PodSec and post an update.
pod.Spec.Containers = append(pod.Spec.Containers, c.Containers...)
pod.Spec.Volumes = append(pod.Spec.Volumes, c.Volumes...)
initializedPod.Spec.Containers = append(pod.Spec.Containers, c.Containers...)
initializedPod.Spec.Volumes = append(pod.Spec.Volumes, c.Volumes...)

oldData, err := json.Marshal(pod)
if err != nil {
return err
}

newData, err := json.Marshal(initializedPod)
if err != nil {
return err
}

patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, corev1.Pod{})
if err != nil {
return err
}

_, err := clientset.CoreV1().Pods(pod.Namespace).Update(pod)
_, err = clientset.CoreV1().Pods(pod.Namespace).Patch(pod.Name, types.StrategicMergePatchType, patchBytes)
if err != nil {
return err
}
Expand Down

0 comments on commit 43c68ce

Please sign in to comment.