Skip to content

Commit

Permalink
[processor/k8sattr] Use RFC3339 format for creation timestamp value (#…
Browse files Browse the repository at this point in the history
…24016)

**Description:** This PR changes the format used for the
`k8s.pod.start_time` value. Previously the
[.String()](https://pkg.go.dev/time#Time.String) method was used but
documentation for that says it should only be used for debugging.
Instead use [.MarshalText()](https://pkg.go.dev/time#Time.MarshalText)
which formats in RFC3339.

I have listed this as a breaking change because it is possible that end
users are making assertions on the format of this timestamp value.

Timestamp output:
before: `2023-07-10 12:34:39.740638 -0700 PDT m=+0.020184946`
after `2023-07-10T12:39:53.112485-07:00`
**Link to tracking Issue:** n/a

**Testing:** Updated unit tests.

**Documentation:** Add blurb at bottom of readme
  • Loading branch information
bryan-aguilar authored Jul 12, 2023
1 parent 17262f4 commit aeb0bc9
Show file tree
Hide file tree
Showing 6 changed files with 187 additions and 2 deletions.
22 changes: 22 additions & 0 deletions .chloggen/k8sattr_timestampformat.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Use this changelog template to create an entry for release notes.
# If your change doesn't affect end users, such as a test fix or a tooling change,
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: enhancement

# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
component: k8sattrprocessor

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Add k8sattr.rfc3339 feature gate to allow RFC3339 format for k8s.pod.start_time timestamp value.

# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
issues: [24016]

# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext: |
Timestamp value before and after.
`2023-07-10 12:34:39.740638 -0700 PDT m=+0.020184946`, `2023-07-10T12:39:53.112485-07:00`
8 changes: 8 additions & 0 deletions processor/k8sattributesprocessor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,3 +273,11 @@ The processor does not support detecting containers from the same pods when runn
as a sidecar. While this can be done, we think it is simpler to just use the kubernetes
downward API to inject environment variables into the pods and directly use their values
as tags.

## Timestamp Format

By default, the `k8s.pod.start_time` uses [Time.String()](https://pkg.go.dev/time#Time.String) to format the
timestamp value.

The `k8sattr.rfc3339` feature gate can be enabled to format the `k8s.pod.start_time` timestamp value with an RFC3339
compliant timestamp. See [Time.MarshalText()](https://pkg.go.dev/time#Time.MarshalText) for more information.
2 changes: 1 addition & 1 deletion processor/k8sattributesprocessor/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ require (
go.opentelemetry.io/collector/component v0.81.0
go.opentelemetry.io/collector/confmap v0.81.0
go.opentelemetry.io/collector/consumer v0.81.0
go.opentelemetry.io/collector/featuregate v1.0.0-rcv0013
go.opentelemetry.io/collector/pdata v1.0.0-rcv0013
go.opentelemetry.io/collector/processor v0.81.0
go.opentelemetry.io/collector/receiver v0.81.0
Expand Down Expand Up @@ -82,7 +83,6 @@ require (
go.opentelemetry.io/collector/exporter v0.81.0 // indirect
go.opentelemetry.io/collector/extension v0.81.0 // indirect
go.opentelemetry.io/collector/extension/auth v0.81.0 // indirect
go.opentelemetry.io/collector/featuregate v1.0.0-rcv0013 // indirect
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.42.1-0.20230612162650-64be7e574a17 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.42.0 // indirect
go.opentelemetry.io/otel v1.16.0 // indirect
Expand Down
19 changes: 18 additions & 1 deletion processor/k8sattributesprocessor/internal/kube/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"sync"
"time"

"go.opentelemetry.io/collector/featuregate"
conventions "go.opentelemetry.io/collector/semconv/v1.6.1"
"go.uber.org/zap"
apps_v1 "k8s.io/api/apps/v1"
Expand All @@ -25,6 +26,14 @@ import (
"github.com/open-telemetry/opentelemetry-collector-contrib/processor/k8sattributesprocessor/internal/observability"
)

// Upgrade to StageBeta in v0.83.0
var enableRFC3339Timestamp = featuregate.GlobalRegistry().MustRegister(
"k8sattr.rfc3339",
featuregate.StageAlpha,
featuregate.WithRegisterDescription("When enabled, uses RFC3339 format for k8s.pod.start_time value"),
featuregate.WithRegisterFromVersion("v0.82.0"),
)

// WatchClient is the main interface provided by this package to a kubernetes cluster.
type WatchClient struct {
m sync.RWMutex
Expand Down Expand Up @@ -343,7 +352,15 @@ func (c *WatchClient) extractPodAttributes(pod *api_v1.Pod) map[string]string {
if c.Rules.StartTime {
ts := pod.GetCreationTimestamp()
if !ts.IsZero() {
tags[tagStartTime] = ts.String()
if enableRFC3339Timestamp.IsEnabled() {
if rfc3339ts, err := ts.MarshalText(); err != nil {
c.logger.Error("failed to unmarshal pod creation timestamp", zap.Error(err))
} else {
tags[tagStartTime] = string(rfc3339ts)
}
} else {
tags[tagStartTime] = ts.String()
}
}
}

Expand Down
132 changes: 132 additions & 0 deletions processor/k8sattributesprocessor/internal/kube/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/collector/featuregate"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"go.uber.org/zap/zaptest/observer"
Expand Down Expand Up @@ -540,8 +541,139 @@ func TestHandlerWrongType(t *testing.T) {
}
}

func TestRFC3339FeatureGate(t *testing.T) {
err := featuregate.GlobalRegistry().Set(enableRFC3339Timestamp.ID(), true)
require.NoError(t, err)

c, _ := newTestClientWithRulesAndFilters(t, Filters{})
// Disable saving ip into k8s.pod.ip
c.Associations[0].Sources[0].Name = ""

pod := &api_v1.Pod{
ObjectMeta: meta_v1.ObjectMeta{
Name: "auth-service-abc12-xyz3",
UID: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
Namespace: "ns1",
CreationTimestamp: meta_v1.Now(),
Labels: map[string]string{
"label1": "lv1",
"label2": "k1=v1 k5=v5 extra!",
},
Annotations: map[string]string{
"annotation1": "av1",
},
OwnerReferences: []meta_v1.OwnerReference{
{
APIVersion: "apps/v1",
Kind: "ReplicaSet",
Name: "auth-service-66f5996c7c",
UID: "207ea729-c779-401d-8347-008ecbc137e3",
},
{
APIVersion: "apps/v1",
Kind: "DaemonSet",
Name: "auth-daemonset",
UID: "c94d3814-2253-427a-ab13-2cf609e4dafa",
},
{
APIVersion: "batch/v1",
Kind: "Job",
Name: "auth-cronjob-27667920",
UID: "59f27ac1-5c71-42e5-abe9-2c499d603706",
},
{
APIVersion: "apps/v1",
Kind: "StatefulSet",
Name: "pi-statefulset",
UID: "03755eb1-6175-47d5-afd5-05cfc30244d7",
},
},
},
Spec: api_v1.PodSpec{
NodeName: "node1",
Hostname: "host1",
},
Status: api_v1.PodStatus{
PodIP: "1.1.1.1",
},
}

isController := true
replicaset := &apps_v1.ReplicaSet{
ObjectMeta: meta_v1.ObjectMeta{
Name: "auth-service-66f5996c7c",
Namespace: "ns1",
UID: "207ea729-c779-401d-8347-008ecbc137e3",
OwnerReferences: []meta_v1.OwnerReference{
{
Name: "auth-service",
Kind: "Deployment",
UID: "ffff-gggg-hhhh-iiii-eeeeeeeeeeee",
Controller: &isController,
},
},
},
}

rfc3339ts, err := pod.GetCreationTimestamp().MarshalText()
require.NoError(t, err)

testCases := []struct {
name string
rules ExtractionRules
attributes map[string]string
}{{
name: "metadata",
rules: ExtractionRules{
DeploymentName: true,
DeploymentUID: true,
Namespace: true,
PodName: true,
PodUID: true,
PodHostName: true,
Node: true,
StartTime: true,
},
attributes: map[string]string{
"k8s.deployment.name": "auth-service",
"k8s.deployment.uid": "ffff-gggg-hhhh-iiii-eeeeeeeeeeee",
"k8s.namespace.name": "ns1",
"k8s.node.name": "node1",
"k8s.pod.name": "auth-service-abc12-xyz3",
"k8s.pod.hostname": "host1",
"k8s.pod.uid": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
"k8s.pod.start_time": string(rfc3339ts),
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
c.Rules = tc.rules

// manually call the data removal functions here
// normally the informer does this, but fully emulating the informer in this test is annoying
transformedPod := removeUnnecessaryPodData(pod, c.Rules)
transformedReplicaset := removeUnnecessaryReplicaSetData(replicaset)
c.handleReplicaSetAdd(transformedReplicaset)
c.handlePodAdd(transformedPod)
p, ok := c.GetPod(newPodIdentifier("connection", "", pod.Status.PodIP))
require.True(t, ok)

assert.Equal(t, len(tc.attributes), len(p.Attributes))
for k, v := range tc.attributes {
got, ok := p.Attributes[k]
assert.True(t, ok)
assert.Equal(t, v, got)
}
})
}
err = featuregate.GlobalRegistry().Set(enableRFC3339Timestamp.ID(), false)
require.NoError(t, err)
}

func TestExtractionRules(t *testing.T) {
c, _ := newTestClientWithRulesAndFilters(t, Filters{})

// Disable saving ip into k8s.pod.ip
c.Associations[0].Sources[0].Name = ""

Expand Down
6 changes: 6 additions & 0 deletions processor/k8sattributesprocessor/processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ func (kp *kubernetesprocessor) initKubeClient(logger *zap.Logger, kubeClient kub
}

func (kp *kubernetesprocessor) Start(_ context.Context, _ component.Host) error {
if kp.rules.StartTime {
kp.logger.Warn("k8s.pod.start_time value will be changed to use RFC3339 format in v0.83.0. " +
"see https://github.com/open-telemetry/opentelemetry-collector-contrib/pull/24016 for more information. " +
"enable feature-gate k8sattr.rfc3339 to opt into this change.")
}

if !kp.passthroughMode {
go kp.kc.Start()
}
Expand Down

0 comments on commit aeb0bc9

Please sign in to comment.