Skip to content

Commit

Permalink
fix that pod spec hash may be changed when new fields are added to po…
Browse files Browse the repository at this point in the history
…d spec
  • Loading branch information
fgksgf committed Jan 10, 2025
1 parent 33926aa commit cca6d12
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
11 changes: 7 additions & 4 deletions pkg/controllers/pd/tasks/pod_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ import (
"github.com/pingcap/tidb-operator/pkg/utils/task/v3"
)

const fakeVersion = "v1.2.3"
const (
fakeVersion = "v1.2.3"
expectedPodSpecHash = "765648cb46"
)

func TestTaskPod(t *testing.T) {
cases := []struct {
Expand Down Expand Up @@ -283,7 +286,7 @@ func TestTaskPod(t *testing.T) {
pod: fake.FakeObj("aaa-pd-xxx", func(obj *corev1.Pod) *corev1.Pod {
obj.Labels = map[string]string{
v1alpha1.LabelKeyConfigHash: "newest",
v1alpha1.LabelKeyPodSpecHash: "6d6499ffc7",
v1alpha1.LabelKeyPodSpecHash: expectedPodSpecHash,
}
return obj
}),
Expand Down Expand Up @@ -332,7 +335,7 @@ func TestTaskPod(t *testing.T) {
pod: fake.FakeObj("aaa-pd-xxx", func(obj *corev1.Pod) *corev1.Pod {
obj.Labels = map[string]string{
v1alpha1.LabelKeyConfigHash: "newest",
v1alpha1.LabelKeyPodSpecHash: "6d6499ffc7",
v1alpha1.LabelKeyPodSpecHash: expectedPodSpecHash,
"xxx": "yyy",
}
return obj
Expand Down Expand Up @@ -383,7 +386,7 @@ func TestTaskPod(t *testing.T) {
obj.Labels = map[string]string{
v1alpha1.LabelKeyInstance: "aaa-xxx",
v1alpha1.LabelKeyConfigHash: "newest",
v1alpha1.LabelKeyPodSpecHash: "6d6499ffc7",
v1alpha1.LabelKeyPodSpecHash: expectedPodSpecHash,
}
return obj
}),
Expand Down
15 changes: 10 additions & 5 deletions pkg/utils/k8s/pod.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package k8s

import (
"encoding/json"
"fmt"
"hash/fnv"

Expand All @@ -29,17 +30,21 @@ import (

// CalculateHashAndSetLabels calculate the hash of pod spec and set it to the pod labels.
func CalculateHashAndSetLabels(pod *corev1.Pod) {
hasher := fnv.New32a()
if pod.Labels == nil {
pod.Labels = map[string]string{}
}
spec := pod.Spec.DeepCopy()
for i := range spec.InitContainers {
c := &spec.InitContainers[i]
// ignores init containers image change to support hot reload image for sidecar
c.Image = ""
}
hashutil.DeepHashObject(hasher, spec)

// This prevents the hash from being changed when new fields are added to the `PodSpec` due to K8s version upgrades.
data, _ := json.Marshal(spec)
hasher := fnv.New32a()
hashutil.DeepHashObject(hasher, data)

if pod.Labels == nil {
pod.Labels = map[string]string{}
}
pod.Labels[v1alpha1.LabelKeyPodSpecHash] = rand.SafeEncodeString(fmt.Sprint(hasher.Sum32()))
}

Expand Down

0 comments on commit cca6d12

Please sign in to comment.