-
Notifications
You must be signed in to change notification settings - Fork 2.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[exporter/elasticsearch] Flesh out encoding log records with mapping.mode: ecs
#31694
Merged
andrzej-stencel
merged 35 commits into
open-telemetry:main
from
ycombinator:exp-es-ecs-r2
May 7, 2024
Merged
Changes from all commits
Commits
Show all changes
35 commits
Select commit
Hold shift + click to select a range
65bc853
Encode logs based on mapping mode
ycombinator fdd2510
WIP: encode log in ECS mode
ycombinator 75f791b
Adding CHANGELOG entry
ycombinator 7b696e2
Adding TODO
ycombinator 31e5e16
Fleshing out some more
ycombinator f6a5150
Add TODO
ycombinator cbf5a77
Add stub for unit test
ycombinator 0b76792
Use consts from semconv package for attribute names
ycombinator 8e5db80
Pass now for testability
ycombinator 7f536e0
Flesh out unit test
ycombinator 40f2ac4
Remove passthrough keys from conversion map
ycombinator dd63590
If conversion map is empty, just add all attributes
ycombinator 897b1d3
Add unit test for mapLogAttributesToECS
ycombinator 3764860
Quote changelog string with backticks
ycombinator ba5aea5
Flesh out more conversions
ycombinator e346402
Correctly populate @timestamp
ycombinator efbb36b
Rename helper function
ycombinator 1a75e49
Extract helper function
ycombinator 41d7582
Handle event.name -> event.action
ycombinator 3be37bb
Fixing linter error
ycombinator 6eadc5f
Do not set event.received
ycombinator e931129
Add k8s.* -> kubernetes.* conversions
ycombinator 1ec5675
Adding process.runtime.* -> service.runtime.* conversions
ycombinator 1047256
Extract out resourceAttrsConversionMap to package-level variable
ycombinator e514a05
No need to pass time.Now() anymore
ycombinator b4c9edc
Implement ability to skip keys during conversion
ycombinator 603109d
Handle agent name and service language name
ycombinator fa31d70
Handle conversion to ECS os.type field
ycombinator 42bd94c
Fixing OS conversions
ycombinator e928d9a
Don't set service.language.name
ycombinator 67e479d
Handle agent version
ycombinator 0aa3f92
Mention SemConv version in README
ycombinator 0fa9353
Update test
ycombinator d067b2e
Incorporate changes from prereq PR
ycombinator e1dfd60
update issue reference in changelog entry
andrzej-stencel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
# Use this changelog template to create an entry for release notes. | ||
|
||
# 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: elasticsearchexporter | ||
|
||
# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`). | ||
note: "Converts more SemConv fields in OTel events to ECS fields in Elasticsearch documents when `mapping.mode: ecs` is specified." | ||
|
||
# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists. | ||
issues: [31694] | ||
|
||
# (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: | ||
|
||
# If your change doesn't affect end users or the exported elements of any package, | ||
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label. | ||
# Optional: The change log or logs in which this entry should be included. | ||
# e.g. '[user]' or '[user, api]' | ||
# Include 'user' if the change is relevant to end users. | ||
# Include 'api' if there is a change to a library API. | ||
# Default: '[user]' | ||
change_logs: [user] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,16 +6,49 @@ package elasticsearchexporter // import "github.com/open-telemetry/opentelemetry | |
import ( | ||
"bytes" | ||
"encoding/json" | ||
"fmt" | ||
"time" | ||
|
||
"go.opentelemetry.io/collector/pdata/pcommon" | ||
"go.opentelemetry.io/collector/pdata/plog" | ||
"go.opentelemetry.io/collector/pdata/ptrace" | ||
semconv "go.opentelemetry.io/collector/semconv/v1.22.0" | ||
|
||
"github.com/open-telemetry/opentelemetry-collector-contrib/exporter/elasticsearchexporter/internal/objmodel" | ||
"github.com/open-telemetry/opentelemetry-collector-contrib/internal/coreinternal/traceutil" | ||
) | ||
|
||
// resourceAttrsConversionMap contains conversions for resource-level attributes | ||
// from their Semantic Conventions (SemConv) names to equivalent Elastic Common | ||
// Schema (ECS) names. | ||
// If the ECS field name is specified as an empty string (""), the converter will | ||
// neither convert the SemConv key to the equivalent ECS name nor pass-through the | ||
// SemConv key as-is to become the ECS name. | ||
var resourceAttrsConversionMap = map[string]string{ | ||
semconv.AttributeServiceInstanceID: "service.node.name", | ||
semconv.AttributeDeploymentEnvironment: "service.environment", | ||
semconv.AttributeTelemetrySDKName: "", | ||
semconv.AttributeTelemetrySDKLanguage: "", | ||
semconv.AttributeTelemetrySDKVersion: "", | ||
semconv.AttributeTelemetryDistroName: "", | ||
semconv.AttributeTelemetryDistroVersion: "", | ||
semconv.AttributeCloudPlatform: "cloud.service.name", | ||
semconv.AttributeContainerImageTags: "container.image.tag", | ||
semconv.AttributeHostName: "host.hostname", | ||
semconv.AttributeHostArch: "host.architecture", | ||
semconv.AttributeProcessExecutablePath: "process.executable", | ||
semconv.AttributeProcessRuntimeName: "service.runtime.name", | ||
semconv.AttributeProcessRuntimeVersion: "service.runtime.version", | ||
semconv.AttributeOSName: "host.os.name", | ||
semconv.AttributeOSType: "host.os.platform", | ||
semconv.AttributeOSDescription: "host.os.full", | ||
semconv.AttributeOSVersion: "host.os.version", | ||
"k8s.namespace.name": "kubernetes.namespace", | ||
"k8s.node.name": "kubernetes.node.name", | ||
"k8s.pod.name": "kubernetes.pod.name", | ||
"k8s.pod.uid": "kubernetes.pod.uid", | ||
} | ||
|
||
type mappingModel interface { | ||
encodeLog(pcommon.Resource, plog.LogRecord, pcommon.InstrumentationScope) ([]byte, error) | ||
encodeSpan(pcommon.Resource, ptrace.Span, pcommon.InstrumentationScope) ([]byte, error) | ||
|
@@ -41,82 +74,86 @@ const ( | |
|
||
func (m *encodeModel) encodeLog(resource pcommon.Resource, record plog.LogRecord, scope pcommon.InstrumentationScope) ([]byte, error) { | ||
var document objmodel.Document | ||
|
||
switch m.mode { | ||
case MappingECS: | ||
if record.Timestamp() != 0 { | ||
document.AddTimestamp("@timestamp", record.Timestamp()) | ||
} else { | ||
document.AddTimestamp("@timestamp", record.ObservedTimestamp()) | ||
} | ||
|
||
document.AddTraceID("trace.id", record.TraceID()) | ||
document.AddSpanID("span.id", record.SpanID()) | ||
|
||
if n := record.SeverityNumber(); n != plog.SeverityNumberUnspecified { | ||
document.AddInt("event.severity", int64(record.SeverityNumber())) | ||
} | ||
|
||
document.AddString("log.level", record.SeverityText()) | ||
document = m.encodeLogECSMode(resource, record, scope) | ||
default: | ||
document = m.encodeLogDefaultMode(resource, record, scope) | ||
} | ||
|
||
if record.Body().Type() == pcommon.ValueTypeStr { | ||
document.AddAttribute("message", record.Body()) | ||
} | ||
var buf bytes.Buffer | ||
err := document.Serialize(&buf, m.dedot) | ||
return buf.Bytes(), err | ||
} | ||
|
||
fieldMapper := func(k string) string { | ||
switch k { | ||
case "exception.type": | ||
return "error.type" | ||
case "exception.message": | ||
return "error.message" | ||
case "exception.stacktrace": | ||
return "error.stack_trace" | ||
default: | ||
return k | ||
} | ||
} | ||
func (m *encodeModel) encodeLogDefaultMode(resource pcommon.Resource, record plog.LogRecord, scope pcommon.InstrumentationScope) objmodel.Document { | ||
var document objmodel.Document | ||
|
||
resource.Attributes().Range(func(k string, v pcommon.Value) bool { | ||
k = fieldMapper(k) | ||
document.AddAttribute(k, v) | ||
return true | ||
}) | ||
scope.Attributes().Range(func(k string, v pcommon.Value) bool { | ||
k = fieldMapper(k) | ||
document.AddAttribute(k, v) | ||
return true | ||
}) | ||
record.Attributes().Range(func(k string, v pcommon.Value) bool { | ||
k = fieldMapper(k) | ||
document.AddAttribute(k, v) | ||
return true | ||
}) | ||
default: | ||
docTimeStamp := record.Timestamp() | ||
if docTimeStamp.AsTime().UnixNano() == 0 { | ||
docTimeStamp = record.ObservedTimestamp() | ||
} | ||
document.AddTimestamp("@timestamp", docTimeStamp) // We use @timestamp in order to ensure that we can index if the default data stream logs template is used. | ||
document.AddTraceID("TraceId", record.TraceID()) | ||
document.AddSpanID("SpanId", record.SpanID()) | ||
document.AddInt("TraceFlags", int64(record.Flags())) | ||
document.AddString("SeverityText", record.SeverityText()) | ||
document.AddInt("SeverityNumber", int64(record.SeverityNumber())) | ||
document.AddAttribute("Body", record.Body()) | ||
m.encodeAttributes(&document, record.Attributes()) | ||
document.AddAttributes("Resource", resource.Attributes()) | ||
document.AddAttributes("Scope", scopeToAttributes(scope)) | ||
docTimeStamp := record.Timestamp() | ||
if docTimeStamp.AsTime().UnixNano() == 0 { | ||
docTimeStamp = record.ObservedTimestamp() | ||
} | ||
document.AddTimestamp("@timestamp", docTimeStamp) // We use @timestamp in order to ensure that we can index if the default data stream logs template is used. | ||
document.AddTraceID("TraceId", record.TraceID()) | ||
document.AddSpanID("SpanId", record.SpanID()) | ||
document.AddInt("TraceFlags", int64(record.Flags())) | ||
document.AddString("SeverityText", record.SeverityText()) | ||
document.AddInt("SeverityNumber", int64(record.SeverityNumber())) | ||
document.AddAttribute("Body", record.Body()) | ||
m.encodeAttributes(&document, record.Attributes()) | ||
document.AddAttributes("Resource", resource.Attributes()) | ||
document.AddAttributes("Scope", scopeToAttributes(scope)) | ||
|
||
if m.dedup { | ||
document.Dedup() | ||
} else if m.dedot { | ||
document.Sort() | ||
} | ||
|
||
var buf bytes.Buffer | ||
err := document.Serialize(&buf, m.dedot) | ||
return buf.Bytes(), err | ||
return document | ||
|
||
} | ||
|
||
func (m *encodeModel) encodeLogECSMode(resource pcommon.Resource, record plog.LogRecord, scope pcommon.InstrumentationScope) objmodel.Document { | ||
var document objmodel.Document | ||
|
||
// First, try to map resource-level attributes to ECS fields. | ||
encodeLogAttributesECSMode(&document, resource.Attributes(), resourceAttrsConversionMap) | ||
|
||
// Then, try to map scope-level attributes to ECS fields. | ||
scopeAttrsConversionMap := map[string]string{ | ||
// None at the moment | ||
} | ||
encodeLogAttributesECSMode(&document, scope.Attributes(), scopeAttrsConversionMap) | ||
|
||
// Finally, try to map record-level attributes to ECS fields. | ||
recordAttrsConversionMap := map[string]string{ | ||
"event.name": "event.action", | ||
semconv.AttributeExceptionMessage: "error.message", | ||
semconv.AttributeExceptionStacktrace: "error.stacktrace", | ||
semconv.AttributeExceptionType: "error.type", | ||
semconv.AttributeExceptionEscaped: "event.error.exception.handled", | ||
} | ||
encodeLogAttributesECSMode(&document, record.Attributes(), recordAttrsConversionMap) | ||
|
||
// Handle special cases. | ||
encodeLogAgentNameECSMode(&document, resource) | ||
encodeLogAgentVersionECSMode(&document, resource) | ||
encodeLogHostOsTypeECSMode(&document, resource) | ||
encodeLogTimestampECSMode(&document, record) | ||
document.AddTraceID("trace.id", record.TraceID()) | ||
document.AddSpanID("span.id", record.SpanID()) | ||
if n := record.SeverityNumber(); n != plog.SeverityNumberUnspecified { | ||
document.AddInt("event.severity", int64(record.SeverityNumber())) | ||
} | ||
|
||
document.AddString("log.level", record.SeverityText()) | ||
|
||
if record.Body().Type() == pcommon.ValueTypeStr { | ||
document.AddAttribute("message", record.Body()) | ||
} | ||
|
||
return document | ||
} | ||
|
||
func (m *encodeModel) encodeSpan(resource pcommon.Resource, span ptrace.Span, scope pcommon.InstrumentationScope) ([]byte, error) { | ||
|
@@ -193,3 +230,117 @@ func scopeToAttributes(scope pcommon.InstrumentationScope) pcommon.Map { | |
} | ||
return attrs | ||
} | ||
|
||
func encodeLogAttributesECSMode(document *objmodel.Document, attrs pcommon.Map, conversionMap map[string]string) { | ||
if len(conversionMap) == 0 { | ||
// No conversions to be done; add all attributes at top level of | ||
// document. | ||
document.AddAttributes("", attrs) | ||
return | ||
} | ||
|
||
attrs.Range(func(k string, v pcommon.Value) bool { | ||
// If ECS key is found for current k in conversion map, use it. | ||
if ecsKey, exists := conversionMap[k]; exists { | ||
if ecsKey == "" { | ||
// Skip the conversion for this k. | ||
return true | ||
} | ||
|
||
document.AddAttribute(ecsKey, v) | ||
return true | ||
} | ||
|
||
// Otherwise, add key at top level with attribute name as-is. | ||
document.AddAttribute(k, v) | ||
return true | ||
}) | ||
} | ||
|
||
func encodeLogAgentNameECSMode(document *objmodel.Document, resource pcommon.Resource) { | ||
// Parse out telemetry SDK name, language, and distro name from resource | ||
// attributes, setting defaults as needed. | ||
telemetrySdkName := "otlp" | ||
var telemetrySdkLanguage, telemetryDistroName string | ||
|
||
attrs := resource.Attributes() | ||
if v, exists := attrs.Get(semconv.AttributeTelemetrySDKName); exists { | ||
telemetrySdkName = v.Str() | ||
} | ||
if v, exists := attrs.Get(semconv.AttributeTelemetrySDKLanguage); exists { | ||
telemetrySdkLanguage = v.Str() | ||
} | ||
if v, exists := attrs.Get(semconv.AttributeTelemetryDistroName); exists { | ||
telemetryDistroName = v.Str() | ||
if telemetrySdkLanguage == "" { | ||
telemetrySdkLanguage = "unknown" | ||
} | ||
} | ||
|
||
// Construct agent name from telemetry SDK name, language, and distro name. | ||
agentName := telemetrySdkName | ||
if telemetryDistroName != "" { | ||
agentName = fmt.Sprintf("%s/%s/%s", agentName, telemetrySdkLanguage, telemetryDistroName) | ||
} else if telemetrySdkLanguage != "" { | ||
agentName = fmt.Sprintf("%s/%s", agentName, telemetrySdkLanguage) | ||
} | ||
|
||
// Set agent name in document. | ||
document.AddString("agent.name", agentName) | ||
} | ||
|
||
func encodeLogAgentVersionECSMode(document *objmodel.Document, resource pcommon.Resource) { | ||
attrs := resource.Attributes() | ||
|
||
if telemetryDistroVersion, exists := attrs.Get(semconv.AttributeTelemetryDistroVersion); exists { | ||
document.AddString("agent.version", telemetryDistroVersion.Str()) | ||
return | ||
} | ||
|
||
if telemetrySdkVersion, exists := attrs.Get(semconv.AttributeTelemetrySDKVersion); exists { | ||
document.AddString("agent.version", telemetrySdkVersion.Str()) | ||
return | ||
} | ||
} | ||
|
||
func encodeLogHostOsTypeECSMode(document *objmodel.Document, resource pcommon.Resource) { | ||
// https://www.elastic.co/guide/en/ecs/current/ecs-os.html#field-os-type: | ||
// | ||
// "One of these following values should be used (lowercase): linux, macos, unix, windows. | ||
// If the OS you’re dealing with is not in the list, the field should not be populated." | ||
|
||
var ecsHostOsType string | ||
if semConvOsType, exists := resource.Attributes().Get(semconv.AttributeOSType); exists { | ||
switch semConvOsType.Str() { | ||
case "windows", "linux": | ||
ecsHostOsType = semConvOsType.Str() | ||
case "darwin": | ||
ecsHostOsType = "macos" | ||
case "aix", "hpux", "solaris": | ||
ecsHostOsType = "unix" | ||
} | ||
} | ||
|
||
if semConvOsName, exists := resource.Attributes().Get(semconv.AttributeOSName); exists { | ||
switch semConvOsName.Str() { | ||
case "Android": | ||
ecsHostOsType = "android" | ||
case "iOS": | ||
ecsHostOsType = "ios" | ||
} | ||
} | ||
|
||
if ecsHostOsType == "" { | ||
return | ||
} | ||
document.AddString("host.os.type", ecsHostOsType) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. in case host is already part of document it'll result in duplicate host key in json request:
|
||
} | ||
|
||
func encodeLogTimestampECSMode(document *objmodel.Document, record plog.LogRecord) { | ||
if record.Timestamp() != 0 { | ||
document.AddTimestamp("@timestamp", record.Timestamp()) | ||
return | ||
} | ||
|
||
document.AddTimestamp("@timestamp", record.ObservedTimestamp()) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Based on the mappings so far, I'd expect the conversionMap to be smaller than the attributes. If you agree with that statement, it might make sense to iterate over the conversionMap instead. This may reduce the overhead a bit by having to iterate over fewer values.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Internally
pcommon.Map
is an array of key-value pairs (https://github.com/open-telemetry/opentelemetry-collector/blob/f0473ca0a55293b92374cc77e0275026537342da/pdata/pcommon/map.go#L26), so even ifconversionMap
is smaller we'd likely end up iteratingattrs
multiple times that way.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Special case: I did add an early return for the special case where
conversionMap
was empty: 47905d4e98ddccb243dcc3eadd2ac8ed1dc6e097.