dedup BuildLabels

Signed-off-by: Jin Dong <djdongjin95@gmail.com>
This commit is contained in:
Jin Dong
2024-10-21 13:23:25 -04:00
parent a5cd0d0a5c
commit 38ba7f2f7e
8 changed files with 52 additions and 100 deletions

View File

@@ -21,9 +21,11 @@ import (
"path"
"time"
"github.com/containerd/containerd/v2/pkg/namespaces"
"github.com/containerd/containerd/v2/internal/cri/constants"
crilabels "github.com/containerd/containerd/v2/internal/cri/labels"
clabels "github.com/containerd/containerd/v2/pkg/labels"
"github.com/containerd/containerd/v2/pkg/namespaces"
"github.com/containerd/log"
)
// deferCleanupTimeout is the default timeout for containerd cleanup operations
@@ -64,3 +66,24 @@ func GetPassthroughAnnotations(podAnnotations map[string]string,
}
return passthroughAnnotations
}
// BuildLabel builds the labels from config to be passed to containerd
func BuildLabels(configLabels, imageConfigLabels map[string]string, containerType string) map[string]string {
labels := make(map[string]string)
for k, v := range imageConfigLabels {
if err := clabels.Validate(k, v); err == nil {
labels[k] = v
} else {
// In case the image label is invalid, we output a warning and skip adding it to the
// container.
log.L.WithError(err).Warnf("unable to add image label with key %s to the container", k)
}
}
// labels from the CRI request (config) will override labels in the image config
for k, v := range configLabels {
labels[k] = v
}
labels[crilabels.ContainerKindLabel] = containerType
return labels
}

View File

@@ -17,8 +17,10 @@
package util
import (
"strings"
"testing"
crilabels "github.com/containerd/containerd/v2/internal/cri/labels"
"github.com/stretchr/testify/assert"
)
@@ -136,3 +138,26 @@ func TestPassThroughAnnotationsFilter(t *testing.T) {
})
}
}
func TestBuildLabels(t *testing.T) {
imageConfigLabels := map[string]string{
"a": "z",
"d": "y",
"long-label": strings.Repeat("example", 10000),
}
configLabels := map[string]string{
"a": "b",
"c": "d",
}
newLabels := BuildLabels(configLabels, imageConfigLabels, crilabels.ContainerKindSandbox)
assert.Len(t, newLabels, 4)
assert.Equal(t, "b", newLabels["a"])
assert.Equal(t, "d", newLabels["c"])
assert.Equal(t, "y", newLabels["d"])
assert.Equal(t, crilabels.ContainerKindSandbox, newLabels[crilabels.ContainerKindLabel])
assert.NotContains(t, newLabels, "long-label")
newLabels["a"] = "e"
assert.Empty(t, configLabels[crilabels.ContainerKindLabel], "should not add new labels into original label")
assert.Equal(t, "b", configLabels["a"], "change in new labels should not affect original label")
}