span_implementation.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright 2022 The OpenZipkin Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package zipkin
  15. import (
  16. "sync"
  17. "sync/atomic"
  18. "time"
  19. "github.com/openzipkin/zipkin-go/model"
  20. )
  21. type spanImpl struct {
  22. mtx sync.RWMutex
  23. model.SpanModel
  24. tracer *Tracer
  25. mustCollect int32 // used as atomic bool (1 = true, 0 = false)
  26. flushOnFinish bool
  27. }
  28. func (s *spanImpl) Context() model.SpanContext {
  29. return s.SpanContext
  30. }
  31. func (s *spanImpl) SetName(name string) {
  32. s.mtx.Lock()
  33. s.Name = name
  34. s.mtx.Unlock()
  35. }
  36. func (s *spanImpl) SetRemoteEndpoint(e *model.Endpoint) {
  37. s.mtx.Lock()
  38. if e == nil {
  39. s.RemoteEndpoint = nil
  40. } else {
  41. s.RemoteEndpoint = &model.Endpoint{}
  42. *s.RemoteEndpoint = *e
  43. }
  44. s.mtx.Unlock()
  45. }
  46. func (s *spanImpl) Annotate(t time.Time, value string) {
  47. a := model.Annotation{
  48. Timestamp: t,
  49. Value: value,
  50. }
  51. s.mtx.Lock()
  52. s.Annotations = append(s.Annotations, a)
  53. s.mtx.Unlock()
  54. }
  55. func (s *spanImpl) Tag(key, value string) {
  56. s.mtx.Lock()
  57. if key == string(TagError) {
  58. if _, found := s.Tags[key]; found {
  59. s.mtx.Unlock()
  60. return
  61. }
  62. }
  63. s.Tags[key] = value
  64. s.mtx.Unlock()
  65. }
  66. func (s *spanImpl) Finish() {
  67. if atomic.CompareAndSwapInt32(&s.mustCollect, 1, 0) {
  68. s.Duration = time.Since(s.Timestamp)
  69. if s.flushOnFinish {
  70. s.tracer.reporter.Send(s.SpanModel)
  71. }
  72. }
  73. }
  74. func (s *spanImpl) FinishedWithDuration(d time.Duration) {
  75. if atomic.CompareAndSwapInt32(&s.mustCollect, 1, 0) {
  76. s.Duration = d
  77. if s.flushOnFinish {
  78. s.tracer.reporter.Send(s.SpanModel)
  79. }
  80. }
  81. }
  82. func (s *spanImpl) Flush() {
  83. if s.SpanModel.Debug || (s.SpanModel.Sampled != nil && *s.SpanModel.Sampled) {
  84. s.tracer.reporter.Send(s.SpanModel)
  85. }
  86. }