Skip to content

Commit 1600464

Browse files
authored
fix(plugins): remove key if no plugins left (#2179)
1 parent d9788af commit 1600464

File tree

2 files changed

+52
-5
lines changed

2 files changed

+52
-5
lines changed

controllers/controller_shared.go

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -203,13 +203,24 @@ func updatePluginConfigMap(cm *corev1.ConfigMap, value []byte, key string, depre
203203
}
204204

205205
// TODO: temporary solution that is used to migrate to a new naming scheme, can be deprecated later
206-
_, ok := cm.BinaryData[deprecatedKey]
207-
if ok {
206+
if _, ok := cm.BinaryData[deprecatedKey]; ok {
208207
delete(cm.BinaryData, deprecatedKey)
209208

210209
isUpdated = true
211210
}
212211

212+
// Delete the key if no plugins left
213+
if len(value) == 0 {
214+
if _, ok := cm.BinaryData[key]; ok {
215+
{
216+
delete(cm.BinaryData, key)
217+
isUpdated = true // nolint:wsl_v5
218+
219+
return
220+
}
221+
}
222+
}
223+
213224
if !bytes.Equal(value, cm.BinaryData[key]) {
214225
cm.BinaryData[key] = value
215226
isUpdated = true
@@ -235,9 +246,15 @@ func ReconcilePlugins(ctx context.Context, k8sClient client.Client, scheme *runt
235246
// when we fetch the actual contents of the ConfigMap using k8sClient, so we need to set it here again
236247
controllerutil.SetControllerReference(grafana, cm, scheme) //nolint:errcheck
237248

238-
val, err := json.Marshal(plugins.Sanitize())
239-
if err != nil {
240-
return err
249+
val := []byte{}
250+
251+
// Just in case we have some broken plugins, better to assess length of the sanitized list, not the original one
252+
sanitized := plugins.Sanitize()
253+
if len(sanitized) > 0 {
254+
val, err = json.Marshal(sanitized)
255+
if err != nil {
256+
return err
257+
}
241258
}
242259

243260
isUpdated := updatePluginConfigMap(cm, val, cmKey, cmDeprecatedKey)

controllers/controller_shared_test.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,36 @@ func TestUpdatePluginConfigMap(t *testing.T) {
373373
},
374374
},
375375
},
376+
{
377+
name: "removed plugin (nil)",
378+
cm: &corev1.ConfigMap{
379+
BinaryData: map[string][]byte{
380+
"a": []byte("1"),
381+
},
382+
},
383+
value: nil,
384+
key: "a",
385+
deprecatedKey: "b",
386+
want: true,
387+
wantCM: &corev1.ConfigMap{
388+
BinaryData: map[string][]byte{},
389+
},
390+
},
391+
{
392+
name: "removed plugin (empty slice)",
393+
cm: &corev1.ConfigMap{
394+
BinaryData: map[string][]byte{
395+
"a": []byte("1"),
396+
},
397+
},
398+
value: []byte{},
399+
key: "a",
400+
deprecatedKey: "b",
401+
want: true,
402+
wantCM: &corev1.ConfigMap{
403+
BinaryData: map[string][]byte{},
404+
},
405+
},
376406
}
377407

378408
for _, tt := range tests {

0 commit comments

Comments
 (0)