Files
magpie/internal/otlp/otel_resource.go
T
yetoneandreyoung 83bdfe70d2 otlp: OTEL_RESOURCE_ATTRIBUTES and OTEL_SERVICE_NAME name the server a trace or metric came from (#5167)
Several magpie servers exporting to one collector or to Langfuse all sent
the same resource, service.name=magpie alone, so nothing said which server
an event came from. Both signals' resource now merges the standard
OTEL_RESOURCE_ATTRIBUTES over that default, and OTEL_SERVICE_NAME over
that (otelResourceAttributes in internal/otlp/otel_resource.go). Nothing
about the machine is looked up; only what the user set is sent. Neither
variable turns export on.

Ported from reyoung's 7ed03b819 (feat/otel-resource-attributes, base
4ca55c6b6), reviewed line by line; nothing in it reached past its goal.
Changed from it:
- service.name precedence. The resource SDK spec makes code-supplied
  attributes win over OTEL_RESOURCE_ATTRIBUTES, but magpie's "magpie" is
  the fallback in the role the spec gives unknown_service, not identity
  the user supplied, and magpie's default never overrides a value the
  user set (code standards). So a service.name in the variable wins, and
  OTEL_SERVICE_NAME, which the spec's env table puts over the variable's,
  wins over both. An empty service.name or blank OTEL_SERVICE_NAME counts
  as unset (the spec's "empty value = unset"), so the resource never
  carries service.name="".
- Bytes that aren't UTF-8 once decoded (%FF) are a decoding error and
  discard the variable; before, json.Marshal sent U+FFFD.
- The variable was parsed and, when bad, logged on every flush of each
  signal. It is now parsed once per value and logged once, naming the
  entry by position (never its contents).
- otlp tests clear both variables in otelConfig, so a developer's shell
  can't change what the existing wire tests see.
Kept: whole variable discarded on any invalid entry (no '=', empty key,
bad escape, empty entry such as a trailing comma), as the spec says;
keys and values trimmed and percent-decoded with PathUnescape ('+' stays
'+'); last repeated key wins; values are strings.

Docs: reference.md's OTLP export, plugin-runtime.md's internal/otlp row,
and the privacy pages (en, zh, ja) now say the resource carries what the
user sets there.

Verified:
- TestOTelResourceAttributes reads the resource a test collector gets on
  /v1/traces and /v1/metrics, 17 cases. On the old otelEnvelope it FAILs
  (server, override and duplicate, encoding and empty, unencoded UTF-8,
  OTEL_SERVICE_NAME cases: "traces resource attributes =
  map[service.name:magpie]", same for metrics). Broken by hand one at a
  time, each went red: UTF-8 check off (not_UTF-8_once_decoded), no
  OTEL_SERVICE_NAME (3 cases), empty service.name kept (empty_service_
  name_is_unset), valid entries kept from a bad variable (missing equals,
  trailing comma, empty key, ...), and the per-value cache off
  (TestOTelResourceAttributesLoggedOnceWithoutContents: "logged 4 times,
  want once"). All green restored.
- On mote: go test -tags nogui ./internal/otlp ok; go test -race -count=3
  -run TestOTel ./internal/otlp ok; go vet, GOOS=linux go vet -tags nogui,
  GOOS=windows go vet (internal/otlp); go build, GOOS=linux go build -tags
  nogui, GOOS=windows go build; node --test site/*.test.mjs; gofmt -l
  empty.
- Full suite: run after the push (go test -tags nogui -timeout 45m ./...
  on mote); reds, if any, filed separately.

Not tried: a real collector or Langfuse; Windows/Linux runs of the
package (the code has no OS-specific path).

Co-authored-by: reyoung <728699+reyoung@users.noreply.github.com>
2026-11-04 13:50:09 +08:00

107 lines
3.2 KiB
Go

package otlp
import (
"fmt"
"log"
"net/url"
"os"
"sort"
"strings"
"sync"
"unicode/utf8"
)
// otelResource is what both signals' resources were last built from, so an
// export doesn't parse the variables again and a bad value is logged once,
// not on every flush.
var otelResource struct {
sync.Mutex
attrs, name string
built bool
out []otelAttribute
}
// otelResourceAttributes is the resource every export carries:
// service.name=magpie, with the standard OTEL_RESOURCE_ATTRIBUTES merged
// over it and OTEL_SERVICE_NAME over that (#5167). Only what the user set
// is added; nothing about the machine is looked up.
//
// magpie's "magpie" is the fallback the spec gives the SDK
// (unknown_service), not identity the user supplied, so a service.name the
// user set wins. An empty service.name counts as unset, as an empty
// OTEL_SERVICE_NAME does.
func otelResourceAttributes() []otelAttribute {
attrs, name := os.Getenv("OTEL_RESOURCE_ATTRIBUTES"), strings.TrimSpace(os.Getenv("OTEL_SERVICE_NAME"))
otelResource.Lock()
defer otelResource.Unlock()
if otelResource.built && otelResource.attrs == attrs && otelResource.name == name {
return otelResource.out
}
values, err := parseResourceAttributes(attrs)
if err != nil {
// The spec discards the whole value on any error. The message
// never quotes it: the attributes may name private hosts.
log.Printf("otel: OTEL_RESOURCE_ATTRIBUTES ignored: %s", err)
values = map[string]string{}
}
if values["service.name"] == "" {
values["service.name"] = "magpie"
}
if name != "" {
values["service.name"] = name
}
keys := make([]string, 0, len(values))
for key := range values {
keys = append(keys, key)
}
sort.Strings(keys)
out := make([]otelAttribute, 0, len(keys))
for _, key := range keys {
out = append(out, otelString(key, values[key]))
}
otelResource.attrs, otelResource.name, otelResource.built, otelResource.out = attrs, name, true, out
return out
}
// parseResourceAttributes reads key1=value1,key2=value2: keys and values
// trimmed and percent-decoded, every value a string, the last of a
// repeated key kept. An empty or blank value is no attributes. An error
// names the entry by position only.
func parseResourceAttributes(raw string) (map[string]string, error) {
values := map[string]string{}
if strings.TrimSpace(raw) == "" {
return values, nil
}
for i, entry := range strings.Split(raw, ",") {
key, value, found := strings.Cut(entry, "=")
if !found {
return nil, fmt.Errorf("entry %d has no '='", i+1)
}
key, err := decodeResourcePart(key)
if err != nil {
return nil, fmt.Errorf("entry %d's key %s", i+1, err)
}
if key == "" {
return nil, fmt.Errorf("entry %d has an empty key", i+1)
}
if value, err = decodeResourcePart(value); err != nil {
return nil, fmt.Errorf("entry %d's value %s", i+1, err)
}
values[key] = value
}
return values, nil
}
// decodeResourcePart percent-decodes one key or value. PathUnescape leaves
// '+' as it is: this is not form encoding.
func decodeResourcePart(s string) (string, error) {
s, err := url.PathUnescape(strings.TrimSpace(s))
if err != nil {
return "", fmt.Errorf("has a bad percent escape")
}
if !utf8.ValidString(s) {
return "", fmt.Errorf("is not UTF-8 once decoded")
}
return s, nil
}