Skip to content

Commit 3cd85b4

Browse files
authored
Add support for labels & annotations in templates (#344)
* Add support for labels and annotations in templates Fixes #335 * Pass Pod in Target to avoid re-lookup of pod for annotations and labels
1 parent 5e06930 commit 3cd85b4

8 files changed

Lines changed: 145 additions & 47 deletions

File tree

‎README.md‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -147,13 +147,15 @@ It accepts a custom template through the `--template` flag, which will be
147147
compiled to a Go template and then used for every log message. This Go template
148148
will receive the following struct:
149149

150-
| property | type | description |
151-
|-----------------|--------|---------------------------------------------|
152-
| `Message` | string | The log message itself |
153-
| `NodeName` | string | The node name where the pod is scheduled on |
154-
| `Namespace` | string | The namespace of the pod |
155-
| `PodName` | string | The name of the pod |
156-
| `ContainerName` | string | The name of the container |
150+
| property | type | description |
151+
|-----------------|-------------------|---------------------------------------------|
152+
| `Message` | string | The log message itself |
153+
| `NodeName` | string | The node name where the pod is scheduled on |
154+
| `Namespace` | string | The namespace of the pod |
155+
| `PodName` | string | The name of the pod |
156+
| `ContainerName` | string | The name of the container |
157+
| `Labels` | map[string]string | The labels of the pod |
158+
| `Annotations` | map[string]string | The annotations of the pod |
157159

158160
The following functions are available within the template (besides the [builtin
159161
functions](https://golang.org/pkg/text/template/#hdr-Functions)):

‎cmd/cmd_test.go‎

Lines changed: 69 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,7 @@ func TestOptionsGenerateTemplate(t *testing.T) {
271271
return o
272272
}(),
273273
"json message",
274-
`{"message":"json message","nodeName":"node1","namespace":"ns1","podName":"pod1","containerName":"container1"}
274+
`{"message":"json message","nodeName":"node1","namespace":"ns1","podName":"pod1","containerName":"container1","labels":{"app":"nginx","env":"prod"},"annotations":{"version":"1.23.4"}}
275275
`,
276276
false,
277277
},
@@ -432,6 +432,72 @@ func TestOptionsGenerateTemplate(t *testing.T) {
432432
`Jan 01 2024 05:00 UTC`,
433433
false,
434434
},
435+
{
436+
"template with specific label",
437+
func() *options {
438+
o := NewOptions(streams)
439+
o.template = "{{.PodName}} [{{.Labels.app}}] {{.Message}}"
440+
return o
441+
}(),
442+
"message with app label",
443+
"pod1 [nginx] message with app label",
444+
false,
445+
},
446+
{
447+
"template with specific annotation",
448+
func() *options {
449+
o := NewOptions(streams)
450+
o.template = "{{.PodName}} [{{.Annotations.version}}] {{.Message}}"
451+
return o
452+
}(),
453+
"message with version annotation",
454+
"pod1 [1.23.4] message with version annotation",
455+
false,
456+
},
457+
{
458+
"template with labels as json",
459+
func() *options {
460+
o := NewOptions(streams)
461+
o.template = "{{.PodName}} {{json .Labels}} {{.Message}}"
462+
return o
463+
}(),
464+
"message with json labels",
465+
"pod1 {\"app\":\"nginx\",\"env\":\"prod\"} message with json labels",
466+
false,
467+
},
468+
{
469+
"template with annotations as json",
470+
func() *options {
471+
o := NewOptions(streams)
472+
o.template = "{{.PodName}} {{json .Annotations}} {{.Message}}"
473+
return o
474+
}(),
475+
"message with json annotations",
476+
"pod1 {\"version\":\"1.23.4\"} message with json annotations",
477+
false,
478+
},
479+
{
480+
"template with missing label",
481+
func() *options {
482+
o := NewOptions(streams)
483+
o.template = "{{.PodName}} [{{.Labels.missing}}] {{.Message}}"
484+
return o
485+
}(),
486+
"message with missing label",
487+
"pod1 [<no value>] message with missing label",
488+
false,
489+
},
490+
{
491+
"template with missing annotation",
492+
func() *options {
493+
o := NewOptions(streams)
494+
o.template = "{{.PodName}} [{{.Annotations.missing}}] {{.Message}}"
495+
return o
496+
}(),
497+
"message with missing annotation",
498+
"pod1 [<no value>] message with missing annotation",
499+
false,
500+
},
435501
}
436502

437503
for _, tt := range tests {
@@ -442,6 +508,8 @@ func TestOptionsGenerateTemplate(t *testing.T) {
442508
Namespace: "ns1",
443509
PodName: "pod1",
444510
ContainerName: "container1",
511+
Labels: map[string]string{"app": "nginx", "env": "prod"},
512+
Annotations: map[string]string{"version": "1.23.4"},
445513
PodColor: color.New(color.FgRed),
446514
ContainerColor: color.New(color.FgBlue),
447515
}

‎stern/stern.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ func Run(ctx context.Context, client kubernetes.Interface, config *Config) error
6666
}
6767
}
6868
newTail := func(t *Target) *Tail {
69-
return NewTail(client.CoreV1(), t.Node, t.Namespace, t.Pod, t.Container, config.Template, config.Out, config.ErrOut, newTailOptions(), config.DiffContainer)
69+
return NewTail(client.CoreV1(), t.Pod, t.Container, config.Template, config.Out, config.ErrOut, newTailOptions(), config.DiffContainer)
7070
}
7171

7272
if config.Stdin {

‎stern/tail.go‎

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,9 @@ const TimestampFormatShort = "01-02 15:04:05"
4343
type Tail struct {
4444
clientset corev1client.CoreV1Interface
4545

46-
NodeName string
47-
Namespace string
48-
PodName string
49-
ContainerName string
46+
Pod *corev1.Pod
47+
ContainerName string
48+
5049
Options *TailOptions
5150
closed chan struct{}
5251
podColor *color.Color
@@ -67,14 +66,12 @@ type ResumeRequest struct {
6766
}
6867

6968
// NewTail returns a new tail for a Kubernetes container inside a pod
70-
func NewTail(clientset corev1client.CoreV1Interface, nodeName, namespace, podName, containerName string, tmpl *template.Template, out, errOut io.Writer, options *TailOptions, diffContainer bool) *Tail {
71-
podColor, containerColor := determineColor(podName, containerName, diffContainer)
69+
func NewTail(clientset corev1client.CoreV1Interface, pod *corev1.Pod, containerName string, tmpl *template.Template, out, errOut io.Writer, options *TailOptions, diffContainer bool) *Tail {
70+
podColor, containerColor := determineColor(pod.Name, containerName, diffContainer)
7271

7372
return &Tail{
7473
clientset: clientset,
75-
NodeName: nodeName,
76-
Namespace: namespace,
77-
PodName: podName,
74+
Pod: pod,
7875
ContainerName: containerName,
7976
Options: options,
8077
closed: make(chan struct{}),
@@ -111,7 +108,7 @@ func (t *Tail) Start(ctx context.Context) error {
111108

112109
t.printStarting()
113110

114-
req := t.clientset.Pods(t.Namespace).GetLogs(t.PodName, &corev1.PodLogOptions{
111+
req := t.clientset.Pods(t.Pod.Namespace).GetLogs(t.Pod.Name, &corev1.PodLogOptions{
115112
Follow: t.Options.Follow,
116113
Timestamps: true,
117114
Container: t.ContainerName,
@@ -155,9 +152,9 @@ func (t *Tail) printStarting() {
155152
p := t.podColor.SprintFunc()
156153
c := t.containerColor.SprintFunc()
157154
if t.Options.Namespace {
158-
fmt.Fprintf(t.errOut, "%s %s %s › %s\n", g("+"), p(t.Namespace), p(t.PodName), c(t.ContainerName))
155+
fmt.Fprintf(t.errOut, "%s %s %s › %s\n", g("+"), p(t.Pod.Namespace), p(t.Pod.Name), c(t.ContainerName))
159156
} else {
160-
fmt.Fprintf(t.errOut, "%s %s › %s\n", g("+"), p(t.PodName), c(t.ContainerName))
157+
fmt.Fprintf(t.errOut, "%s %s › %s\n", g("+"), p(t.Pod.Name), c(t.ContainerName))
161158
}
162159
}
163160
}
@@ -168,9 +165,9 @@ func (t *Tail) printStopping() {
168165
p := t.podColor.SprintFunc()
169166
c := t.containerColor.SprintFunc()
170167
if t.Options.Namespace {
171-
fmt.Fprintf(t.errOut, "%s %s %s › %s\n", r("-"), p(t.Namespace), p(t.PodName), c(t.ContainerName))
168+
fmt.Fprintf(t.errOut, "%s %s %s › %s\n", r("-"), p(t.Pod.Namespace), p(t.Pod.Name), c(t.ContainerName))
172169
} else {
173-
fmt.Fprintf(t.errOut, "%s %s › %s\n", r("-"), p(t.PodName), c(t.ContainerName))
170+
fmt.Fprintf(t.errOut, "%s %s › %s\n", r("-"), p(t.Pod.Name), c(t.ContainerName))
174171
}
175172
}
176173
}
@@ -204,10 +201,12 @@ func (t *Tail) ConsumeRequest(ctx context.Context, request rest.ResponseWrapper)
204201
func (t *Tail) Print(msg string) {
205202
vm := Log{
206203
Message: msg,
207-
NodeName: t.NodeName,
208-
Namespace: t.Namespace,
209-
PodName: t.PodName,
204+
NodeName: t.Pod.Spec.NodeName,
205+
Namespace: t.Pod.Namespace,
206+
PodName: t.Pod.Name,
210207
ContainerName: t.ContainerName,
208+
Labels: t.Pod.Labels,
209+
Annotations: t.Pod.Annotations,
211210
PodColor: t.podColor,
212211
ContainerColor: t.containerColor,
213212
}

‎stern/tail_test.go‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import (
88
"testing"
99
"text/template"
1010

11+
corev1 "k8s.io/api/core/v1"
12+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
1113
"k8s.io/client-go/kubernetes/fake"
1214
)
1315

@@ -103,7 +105,16 @@ line 4 (my-node/my-namespace/my-pod/my-container)
103105
for i, tt := range tests {
104106
t.Run(tt.name, func(t *testing.T) {
105107
out := new(bytes.Buffer)
106-
tail := NewTail(clientset.CoreV1(), "my-node", "my-namespace", "my-pod", "my-container", tmpl, out, io.Discard, &TailOptions{}, false)
108+
pod := &corev1.Pod{
109+
ObjectMeta: metav1.ObjectMeta{
110+
Namespace: "my-namespace",
111+
Name: "my-pod",
112+
},
113+
Spec: corev1.PodSpec{
114+
NodeName: "my-node",
115+
},
116+
}
117+
tail := NewTail(clientset.CoreV1(), pod, "my-container", tmpl, out, io.Discard, &TailOptions{}, false)
107118
tail.resumeRequest = tt.resumeReq
108119
if err := tail.ConsumeRequest(context.TODO(), &responseWrapperMock{data: bytes.NewBufferString(logLines)}); err != nil {
109120
t.Fatalf("%d: unexpected err %v", i, err)
@@ -162,7 +173,13 @@ func TestPrintStarting(t *testing.T) {
162173
clientset := fake.NewSimpleClientset()
163174
for i, tt := range tests {
164175
errOut := new(bytes.Buffer)
165-
tail := NewTail(clientset.CoreV1(), "my-node", "my-namespace", "my-pod", "my-container", nil, io.Discard, errOut, tt.options, false)
176+
pod := &corev1.Pod{
177+
ObjectMeta: metav1.ObjectMeta{
178+
Namespace: "my-namespace",
179+
Name: "my-pod",
180+
},
181+
}
182+
tail := NewTail(clientset.CoreV1(), pod, "my-container", nil, io.Discard, errOut, tt.options, false)
166183
tail.printStarting()
167184

168185
if !bytes.Equal(tt.expected, errOut.Bytes()) {
@@ -204,7 +221,13 @@ func TestPrintStopping(t *testing.T) {
204221
clientset := fake.NewSimpleClientset()
205222
for i, tt := range tests {
206223
errOut := new(bytes.Buffer)
207-
tail := NewTail(clientset.CoreV1(), "my-node", "my-namespace", "my-pod", "my-container", nil, io.Discard, errOut, tt.options, false)
224+
pod := &corev1.Pod{
225+
ObjectMeta: metav1.ObjectMeta{
226+
Namespace: "my-namespace",
227+
Name: "my-pod",
228+
},
229+
}
230+
tail := NewTail(clientset.CoreV1(), pod, "my-container", nil, io.Discard, errOut, tt.options, false)
208231
tail.printStopping()
209232

210233
if !bytes.Equal(tt.expected, errOut.Bytes()) {

‎stern/tail_utils.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,12 @@ type Log struct {
2929
// ContainerName of the container
3030
ContainerName string `json:"containerName"`
3131

32+
// Labels of the pod
33+
Labels map[string]string `json:"labels"`
34+
35+
// Annotations of the pod
36+
Annotations map[string]string `json:"annotations"`
37+
3238
PodColor *color.Color `json:"-"`
3339
ContainerColor *color.Color `json:"-"`
3440
}

‎stern/target.go‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,13 @@ import (
2525

2626
// Target is a target to watch
2727
type Target struct {
28-
Node string
29-
Namespace string
30-
Pod string
28+
Pod *corev1.Pod
3129
Container string
3230
}
3331

3432
// GetID returns the ID of the object
3533
func (t *Target) GetID() string {
36-
return fmt.Sprintf("%s-%s-%s", t.Namespace, t.Pod, t.Container)
34+
return fmt.Sprintf("%s-%s-%s", t.Pod.Namespace, t.Pod.Name, t.Container)
3735
}
3836

3937
// targetState holds a last shown container ID
@@ -112,9 +110,7 @@ OUTER:
112110
}
113111

114112
t := &Target{
115-
Node: pod.Spec.NodeName,
116-
Namespace: pod.Namespace,
117-
Pod: pod.Name,
113+
Pod: pod,
118114
Container: c.Name,
119115
}
120116

‎stern/target_test.go‎

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -49,10 +49,9 @@ func TestTargetFilter(t *testing.T) {
4949
}
5050

5151
genTarget := func(node, pod, container string) Target {
52+
p := createPod(node, pod)
5253
return Target{
53-
Namespace: "ns1",
54-
Node: node,
55-
Pod: pod,
54+
Pod: p,
5655
Container: container,
5756
}
5857
}
@@ -346,12 +345,17 @@ func TestTargetFilterShouldAdd(t *testing.T) {
346345
},
347346
}
348347
}
349-
genTarget := func(container string) Target {
348+
genTarget := func(containerName, containerID string) Target {
349+
pod := createPod(corev1.ContainerStatus{
350+
Name: containerName,
351+
ContainerID: containerID,
352+
State: corev1.ContainerState{
353+
Running: &corev1.ContainerStateRunning{},
354+
},
355+
})
350356
return Target{
351-
Namespace: "ns1",
352-
Node: "node1",
353-
Pod: "pod1",
354-
Container: container,
357+
Pod: pod,
358+
Container: containerName,
355359
}
356360
}
357361
tests := []struct {
@@ -374,7 +378,7 @@ func TestTargetFilterShouldAdd(t *testing.T) {
374378
Running: &corev1.ContainerStateRunning{},
375379
},
376380
},
377-
expected: []Target{genTarget("c1")},
381+
expected: []Target{genTarget("c1", "cid1")},
378382
},
379383
{
380384
name: "same container ID should be ignored",
@@ -396,7 +400,7 @@ func TestTargetFilterShouldAdd(t *testing.T) {
396400
Running: &corev1.ContainerStateRunning{},
397401
},
398402
},
399-
expected: []Target{genTarget("c1")},
403+
expected: []Target{genTarget("c1", "cid2")},
400404
},
401405
{
402406
name: "forget() allows the same ID ",
@@ -408,7 +412,7 @@ func TestTargetFilterShouldAdd(t *testing.T) {
408412
Running: &corev1.ContainerStateRunning{},
409413
},
410414
},
411-
expected: []Target{genTarget("c1")},
415+
expected: []Target{genTarget("c1", "cid2")},
412416
},
413417
}
414418
for _, tt := range tests {

0 commit comments

Comments
 (0)