span.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package sdk
  4. import (
  5. "encoding/json"
  6. "fmt"
  7. "math"
  8. "reflect"
  9. "runtime"
  10. "strings"
  11. "sync"
  12. "sync/atomic"
  13. "time"
  14. "unicode/utf8"
  15. "go.opentelemetry.io/otel/attribute"
  16. "go.opentelemetry.io/otel/codes"
  17. semconv "go.opentelemetry.io/otel/semconv/v1.37.0"
  18. "go.opentelemetry.io/otel/trace"
  19. "go.opentelemetry.io/otel/trace/noop"
  20. "go.opentelemetry.io/auto/sdk/internal/telemetry"
  21. )
  22. type span struct {
  23. noop.Span
  24. spanContext trace.SpanContext
  25. sampled atomic.Bool
  26. mu sync.Mutex
  27. traces *telemetry.Traces
  28. span *telemetry.Span
  29. }
  30. func (s *span) SpanContext() trace.SpanContext {
  31. if s == nil {
  32. return trace.SpanContext{}
  33. }
  34. // s.spanContext is immutable, do not acquire lock s.mu.
  35. return s.spanContext
  36. }
  37. func (s *span) IsRecording() bool {
  38. if s == nil {
  39. return false
  40. }
  41. return s.sampled.Load()
  42. }
  43. func (s *span) SetStatus(c codes.Code, msg string) {
  44. if s == nil || !s.sampled.Load() {
  45. return
  46. }
  47. s.mu.Lock()
  48. defer s.mu.Unlock()
  49. if s.span.Status == nil {
  50. s.span.Status = new(telemetry.Status)
  51. }
  52. s.span.Status.Message = msg
  53. switch c {
  54. case codes.Unset:
  55. s.span.Status.Code = telemetry.StatusCodeUnset
  56. case codes.Error:
  57. s.span.Status.Code = telemetry.StatusCodeError
  58. case codes.Ok:
  59. s.span.Status.Code = telemetry.StatusCodeOK
  60. }
  61. }
  62. func (s *span) SetAttributes(attrs ...attribute.KeyValue) {
  63. if s == nil || !s.sampled.Load() {
  64. return
  65. }
  66. s.mu.Lock()
  67. defer s.mu.Unlock()
  68. limit := maxSpan.Attrs
  69. if limit == 0 {
  70. // No attributes allowed.
  71. n := int64(len(attrs))
  72. if n > 0 {
  73. s.span.DroppedAttrs += uint32( //nolint:gosec // Bounds checked.
  74. min(n, math.MaxUint32),
  75. )
  76. }
  77. return
  78. }
  79. m := make(map[string]int)
  80. for i, a := range s.span.Attrs {
  81. m[a.Key] = i
  82. }
  83. for _, a := range attrs {
  84. val := convAttrValue(a.Value)
  85. if val.Empty() {
  86. s.span.DroppedAttrs++
  87. continue
  88. }
  89. if idx, ok := m[string(a.Key)]; ok {
  90. s.span.Attrs[idx] = telemetry.Attr{
  91. Key: string(a.Key),
  92. Value: val,
  93. }
  94. } else if limit < 0 || len(s.span.Attrs) < limit {
  95. s.span.Attrs = append(s.span.Attrs, telemetry.Attr{
  96. Key: string(a.Key),
  97. Value: val,
  98. })
  99. m[string(a.Key)] = len(s.span.Attrs) - 1
  100. } else {
  101. s.span.DroppedAttrs++
  102. }
  103. }
  104. }
  105. // convCappedAttrs converts up to limit attrs into a []telemetry.Attr. The
  106. // number of dropped attributes is also returned.
  107. func convCappedAttrs(limit int, attrs []attribute.KeyValue) ([]telemetry.Attr, uint32) {
  108. n := len(attrs)
  109. if limit == 0 {
  110. var out uint32
  111. if n > 0 {
  112. out = uint32(min(int64(n), math.MaxUint32)) //nolint:gosec // Bounds checked.
  113. }
  114. return nil, out
  115. }
  116. if limit < 0 {
  117. // Unlimited.
  118. return convAttrs(attrs), 0
  119. }
  120. if n < 0 {
  121. n = 0
  122. }
  123. limit = min(n, limit)
  124. return convAttrs(attrs[:limit]), uint32(n - limit) //nolint:gosec // Bounds checked.
  125. }
  126. func convAttrs(attrs []attribute.KeyValue) []telemetry.Attr {
  127. if len(attrs) == 0 {
  128. // Avoid allocations if not necessary.
  129. return nil
  130. }
  131. out := make([]telemetry.Attr, 0, len(attrs))
  132. for _, attr := range attrs {
  133. key := string(attr.Key)
  134. val := convAttrValue(attr.Value)
  135. if val.Empty() {
  136. continue
  137. }
  138. out = append(out, telemetry.Attr{Key: key, Value: val})
  139. }
  140. return out
  141. }
  142. func convAttrValue(value attribute.Value) telemetry.Value {
  143. switch value.Type() {
  144. case attribute.BOOL:
  145. return telemetry.BoolValue(value.AsBool())
  146. case attribute.INT64:
  147. return telemetry.Int64Value(value.AsInt64())
  148. case attribute.FLOAT64:
  149. return telemetry.Float64Value(value.AsFloat64())
  150. case attribute.STRING:
  151. v := truncate(maxSpan.AttrValueLen, value.AsString())
  152. return telemetry.StringValue(v)
  153. case attribute.BOOLSLICE:
  154. slice := value.AsBoolSlice()
  155. out := make([]telemetry.Value, 0, len(slice))
  156. for _, v := range slice {
  157. out = append(out, telemetry.BoolValue(v))
  158. }
  159. return telemetry.SliceValue(out...)
  160. case attribute.INT64SLICE:
  161. slice := value.AsInt64Slice()
  162. out := make([]telemetry.Value, 0, len(slice))
  163. for _, v := range slice {
  164. out = append(out, telemetry.Int64Value(v))
  165. }
  166. return telemetry.SliceValue(out...)
  167. case attribute.FLOAT64SLICE:
  168. slice := value.AsFloat64Slice()
  169. out := make([]telemetry.Value, 0, len(slice))
  170. for _, v := range slice {
  171. out = append(out, telemetry.Float64Value(v))
  172. }
  173. return telemetry.SliceValue(out...)
  174. case attribute.STRINGSLICE:
  175. slice := value.AsStringSlice()
  176. out := make([]telemetry.Value, 0, len(slice))
  177. for _, v := range slice {
  178. v = truncate(maxSpan.AttrValueLen, v)
  179. out = append(out, telemetry.StringValue(v))
  180. }
  181. return telemetry.SliceValue(out...)
  182. }
  183. return telemetry.Value{}
  184. }
  185. // truncate returns a truncated version of s such that it contains less than
  186. // the limit number of characters. Truncation is applied by returning the limit
  187. // number of valid characters contained in s.
  188. //
  189. // If limit is negative, it returns the original string.
  190. //
  191. // UTF-8 is supported. When truncating, all invalid characters are dropped
  192. // before applying truncation.
  193. //
  194. // If s already contains less than the limit number of bytes, it is returned
  195. // unchanged. No invalid characters are removed.
  196. func truncate(limit int, s string) string {
  197. // This prioritize performance in the following order based on the most
  198. // common expected use-cases.
  199. //
  200. // - Short values less than the default limit (128).
  201. // - Strings with valid encodings that exceed the limit.
  202. // - No limit.
  203. // - Strings with invalid encodings that exceed the limit.
  204. if limit < 0 || len(s) <= limit {
  205. return s
  206. }
  207. // Optimistically, assume all valid UTF-8.
  208. var b strings.Builder
  209. count := 0
  210. for i, c := range s {
  211. if c != utf8.RuneError {
  212. count++
  213. if count > limit {
  214. return s[:i]
  215. }
  216. continue
  217. }
  218. _, size := utf8.DecodeRuneInString(s[i:])
  219. if size == 1 {
  220. // Invalid encoding.
  221. b.Grow(len(s) - 1)
  222. _, _ = b.WriteString(s[:i])
  223. s = s[i:]
  224. break
  225. }
  226. }
  227. // Fast-path, no invalid input.
  228. if b.Cap() == 0 {
  229. return s
  230. }
  231. // Truncate while validating UTF-8.
  232. for i := 0; i < len(s) && count < limit; {
  233. c := s[i]
  234. if c < utf8.RuneSelf {
  235. // Optimization for single byte runes (common case).
  236. _ = b.WriteByte(c)
  237. i++
  238. count++
  239. continue
  240. }
  241. _, size := utf8.DecodeRuneInString(s[i:])
  242. if size == 1 {
  243. // We checked for all 1-byte runes above, this is a RuneError.
  244. i++
  245. continue
  246. }
  247. _, _ = b.WriteString(s[i : i+size])
  248. i += size
  249. count++
  250. }
  251. return b.String()
  252. }
  253. func (s *span) End(opts ...trace.SpanEndOption) {
  254. if s == nil || !s.sampled.Swap(false) {
  255. return
  256. }
  257. // s.end exists so the lock (s.mu) is not held while s.ended is called.
  258. s.ended(s.end(opts))
  259. }
  260. func (s *span) end(opts []trace.SpanEndOption) []byte {
  261. s.mu.Lock()
  262. defer s.mu.Unlock()
  263. cfg := trace.NewSpanEndConfig(opts...)
  264. if t := cfg.Timestamp(); !t.IsZero() {
  265. s.span.EndTime = cfg.Timestamp()
  266. } else {
  267. s.span.EndTime = time.Now()
  268. }
  269. b, _ := json.Marshal(s.traces) // TODO: do not ignore this error.
  270. return b
  271. }
  272. // Expected to be implemented in eBPF.
  273. //
  274. //go:noinline
  275. func (*span) ended(buf []byte) { ended(buf) }
  276. // ended is used for testing.
  277. var ended = func([]byte) {}
  278. func (s *span) RecordError(err error, opts ...trace.EventOption) {
  279. if s == nil || err == nil || !s.sampled.Load() {
  280. return
  281. }
  282. cfg := trace.NewEventConfig(opts...)
  283. attrs := cfg.Attributes()
  284. attrs = append(attrs,
  285. semconv.ExceptionType(typeStr(err)),
  286. semconv.ExceptionMessage(err.Error()),
  287. )
  288. if cfg.StackTrace() {
  289. buf := make([]byte, 2048)
  290. n := runtime.Stack(buf, false)
  291. attrs = append(attrs, semconv.ExceptionStacktrace(string(buf[0:n])))
  292. }
  293. s.mu.Lock()
  294. defer s.mu.Unlock()
  295. s.addEvent(semconv.ExceptionEventName, cfg.Timestamp(), attrs)
  296. }
  297. func typeStr(i any) string {
  298. t := reflect.TypeOf(i)
  299. if t.PkgPath() == "" && t.Name() == "" {
  300. // Likely a builtin type.
  301. return t.String()
  302. }
  303. return fmt.Sprintf("%s.%s", t.PkgPath(), t.Name())
  304. }
  305. func (s *span) AddEvent(name string, opts ...trace.EventOption) {
  306. if s == nil || !s.sampled.Load() {
  307. return
  308. }
  309. cfg := trace.NewEventConfig(opts...)
  310. s.mu.Lock()
  311. defer s.mu.Unlock()
  312. s.addEvent(name, cfg.Timestamp(), cfg.Attributes())
  313. }
  314. // addEvent adds an event with name and attrs at tStamp to the span. The span
  315. // lock (s.mu) needs to be held by the caller.
  316. func (s *span) addEvent(name string, tStamp time.Time, attrs []attribute.KeyValue) {
  317. limit := maxSpan.Events
  318. if limit == 0 {
  319. s.span.DroppedEvents++
  320. return
  321. }
  322. if limit > 0 && len(s.span.Events) == limit {
  323. // Drop head while avoiding allocation of more capacity.
  324. copy(s.span.Events[:limit-1], s.span.Events[1:])
  325. s.span.Events = s.span.Events[:limit-1]
  326. s.span.DroppedEvents++
  327. }
  328. e := &telemetry.SpanEvent{Time: tStamp, Name: name}
  329. e.Attrs, e.DroppedAttrs = convCappedAttrs(maxSpan.EventAttrs, attrs)
  330. s.span.Events = append(s.span.Events, e)
  331. }
  332. func (s *span) AddLink(link trace.Link) {
  333. if s == nil || !s.sampled.Load() {
  334. return
  335. }
  336. l := maxSpan.Links
  337. s.mu.Lock()
  338. defer s.mu.Unlock()
  339. if l == 0 {
  340. s.span.DroppedLinks++
  341. return
  342. }
  343. if l > 0 && len(s.span.Links) == l {
  344. // Drop head while avoiding allocation of more capacity.
  345. copy(s.span.Links[:l-1], s.span.Links[1:])
  346. s.span.Links = s.span.Links[:l-1]
  347. s.span.DroppedLinks++
  348. }
  349. s.span.Links = append(s.span.Links, convLink(link))
  350. }
  351. func convLinks(links []trace.Link) []*telemetry.SpanLink {
  352. out := make([]*telemetry.SpanLink, 0, len(links))
  353. for _, link := range links {
  354. out = append(out, convLink(link))
  355. }
  356. return out
  357. }
  358. func convLink(link trace.Link) *telemetry.SpanLink {
  359. l := &telemetry.SpanLink{
  360. TraceID: telemetry.TraceID(link.SpanContext.TraceID()),
  361. SpanID: telemetry.SpanID(link.SpanContext.SpanID()),
  362. TraceState: link.SpanContext.TraceState().String(),
  363. Flags: uint32(link.SpanContext.TraceFlags()),
  364. }
  365. l.Attrs, l.DroppedAttrs = convCappedAttrs(maxSpan.LinkAttrs, link.Attributes)
  366. return l
  367. }
  368. func (s *span) SetName(name string) {
  369. if s == nil || !s.sampled.Load() {
  370. return
  371. }
  372. s.mu.Lock()
  373. defer s.mu.Unlock()
  374. s.span.Name = name
  375. }
  376. func (*span) TracerProvider() trace.TracerProvider { return TracerProvider() }