Skip to content

Commit 24fc7b3

Browse files
authored
Fix the race issue of encoderMap (#6085)
1 parent 093ab5e commit 24fc7b3

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

pkg/utils/k8s/revision/controller_revision.go

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919
"context"
2020
"encoding/json"
2121
"fmt"
22+
"sync"
2223

2324
appsv1 "k8s.io/api/apps/v1"
2425
kuberuntime "k8s.io/apimachinery/pkg/runtime"
@@ -38,7 +39,8 @@ const (
3839
defaultRevisionHistoryLimit = 10
3940
)
4041

41-
var encoderMap = map[schema.GroupVersion]kuberuntime.Encoder{}
42+
// encoderMap is a map of `GroupVersion` to `kuberuntime.Encoder`.
43+
var encoderMap sync.Map
4244

4345
// GetCurrentAndUpdate returns the current and update ControllerRevisions. It also
4446
// returns a collision count that records the number of name collisions set saw when creating
@@ -135,7 +137,8 @@ func newRevision(obj client.Object, component string, labels map[string]string,
135137
// getPatch returns a merge patch that can be applied to restore a CR to a previous version.
136138
// The current state that we save is just the spec.
137139
func getPatch(obj client.Object, gvk schema.GroupVersionKind) ([]byte, error) {
138-
encoder, ok := encoderMap[gvk.GroupVersion()]
140+
var encoder kuberuntime.Encoder
141+
val, ok := encoderMap.Load(gvk.GroupVersion())
139142
if !ok {
140143
encoder = scheme.Codecs.EncoderForVersion(
141144
serializerjson.NewSerializerWithOptions(
@@ -149,7 +152,9 @@ func getPatch(obj client.Object, gvk schema.GroupVersionKind) ([]byte, error) {
149152
}),
150153
gvk.GroupVersion(),
151154
)
152-
encoderMap[gvk.GroupVersion()] = encoder
155+
encoderMap.Store(gvk.GroupVersion(), encoder)
156+
} else {
157+
encoder = val.(kuberuntime.Encoder)
153158
}
154159

155160
buf := bytes.Buffer{}

0 commit comments

Comments
 (0)