From 706b6092a16be5e9aee0f8ad8246416f648abb1a Mon Sep 17 00:00:00 2001 From: Przemek Maciolek Date: Sat, 21 Mar 2020 11:21:18 +0100 Subject: [PATCH] Extract hostname from pod.name when the former is not set --- processor/k8sprocessor/kube/client.go | 9 +++++++- processor/k8sprocessor/kube/client_test.go | 25 ++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/processor/k8sprocessor/kube/client.go b/processor/k8sprocessor/kube/client.go index 49a731074d41..05668d8cca4e 100644 --- a/processor/k8sprocessor/kube/client.go +++ b/processor/k8sprocessor/kube/client.go @@ -222,7 +222,14 @@ func (c *WatchClient) extractPodAttributes(pod *api_v1.Pod) map[string]string { } if c.Rules.HostName { - tags[c.Rules.Tags.HostName] = pod.Spec.Hostname + // Basing on v1.17 Kubernetes docs, when a hostname is specified, it takes precedence over + // the associated metadata name, see: + // https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#pod-s-hostname-and-subdomain-fields + if pod.Spec.Hostname == "" { + tags[c.Rules.Tags.HostName] = pod.Name + } else { + tags[c.Rules.Tags.HostName] = pod.Spec.Hostname + } } if c.Rules.ClusterName { diff --git a/processor/k8sprocessor/kube/client_test.go b/processor/k8sprocessor/kube/client_test.go index 76d438947447..0cfb140e12d5 100644 --- a/processor/k8sprocessor/kube/client_test.go +++ b/processor/k8sprocessor/kube/client_test.go @@ -125,6 +125,31 @@ func TestDeleteQueue(t *testing.T) { // test delete loop } +func TestNoHostnameExtractionRules(t *testing.T) { + c := newTestClientWithRulesAndFilters(t, ExtractionRules{}, Filters{}) + + podName := "auth-service-abc12-xyz3" + + pod := &api_v1.Pod{ + ObjectMeta: meta_v1.ObjectMeta{ + Name: podName, + }, + Spec: api_v1.PodSpec{}, + Status: api_v1.PodStatus{ + PodIP: "1.1.1.1", + }, + } + + c.Rules = ExtractionRules{ + HostName: true, + Tags: NewExtractionFieldTags(), + } + + c.handlePodAdd(pod) + p, _ := c.GetPodByIP(pod.Status.PodIP) + assert.Equal(t, p.Attributes["k8s.pod.hostname"], podName) +} + func TestExtractionRules(t *testing.T) { c := newTestClientWithRulesAndFilters(t, ExtractionRules{}, Filters{})