From de245a7297ce2a3e1c710d83209da417d0817aeb Mon Sep 17 00:00:00 2001 From: Steve Joachim Date: Fri, 22 Jan 2021 14:17:45 -0500 Subject: [PATCH] Add label to pods created by Kanister (#886) * Add label to pods created by Kanister * Update label map initialization Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com> --- pkg/consts/consts.go | 2 ++ pkg/kube/pod.go | 11 +++++++++-- pkg/kube/pod_test.go | 8 +++++--- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/pkg/consts/consts.go b/pkg/consts/consts.go index 4ff96411b6..8df2ff0d90 100644 --- a/pkg/consts/consts.go +++ b/pkg/consts/consts.go @@ -6,4 +6,6 @@ const ( ContainerNameKey = "Container" PhaseNameKey = "Phase" GoogleCloudCredsFilePath = "/tmp/creds.txt" + LabelKeyCreatedBy = "createdBy" + LabelValueKanister = "kanister" ) diff --git a/pkg/kube/pod.go b/pkg/kube/pod.go index e3c5e2daf6..7aa7a3aaaa 100644 --- a/pkg/kube/pod.go +++ b/pkg/kube/pod.go @@ -30,6 +30,7 @@ import ( "k8s.io/client-go/kubernetes" crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" + "github.com/kanisterio/kanister/pkg/consts" "github.com/kanisterio/kanister/pkg/log" "github.com/kanisterio/kanister/pkg/poll" ) @@ -104,6 +105,9 @@ func CreatePod(ctx context.Context, cli kubernetes.Interface, opts *PodOptions) pod := &v1.Pod{ ObjectMeta: metav1.ObjectMeta{ GenerateName: opts.GenerateName, + Labels: map[string]string{ + consts.LabelKeyCreatedBy: consts.LabelValueKanister, + }, }, Spec: patchedSpecs, } @@ -112,8 +116,11 @@ func CreatePod(ctx context.Context, cli kubernetes.Interface, opts *PodOptions) if opts.Annotations != nil { pod.ObjectMeta.Annotations = opts.Annotations } - if opts.Labels != nil { - pod.ObjectMeta.Labels = opts.Labels + if pod.ObjectMeta.Labels == nil { + pod.ObjectMeta.Labels = map[string]string{} + } + for key, value := range opts.Labels { + pod.ObjectMeta.Labels[key] = value } pod, err = cli.CoreV1().Pods(ns).Create(ctx, pod, metav1.CreateOptions{}) diff --git a/pkg/kube/pod_test.go b/pkg/kube/pod_test.go index 5ce3e7476c..f024946cc5 100644 --- a/pkg/kube/pod_test.go +++ b/pkg/kube/pod_test.go @@ -33,6 +33,7 @@ import ( "k8s.io/client-go/testing" crv1alpha1 "github.com/kanisterio/kanister/pkg/apis/cr/v1alpha1" + "github.com/kanisterio/kanister/pkg/consts" ) type PodSuite struct { @@ -157,9 +158,10 @@ func (s *PodSuite) TestPod(c *C) { c.Check(pod.ObjectMeta.Annotations, DeepEquals, po.Annotations) } - if po.Labels != nil { - c.Check(pod.ObjectMeta.Labels, NotNil) - c.Check(pod.ObjectMeta.Labels, DeepEquals, po.Labels) + c.Check(len(pod.ObjectMeta.Labels), Equals, len(po.Labels)+1) + c.Check(pod.ObjectMeta.Labels[consts.LabelKeyCreatedBy], Equals, consts.LabelValueKanister) + for key, value := range po.Labels { + c.Check(pod.ObjectMeta.Labels[key], Equals, value) } c.Assert(err, IsNil)