span.go 9.6 KB

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