tracing.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. package tracing
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "fmt"
  6. "sync"
  7. "time"
  8. "github.com/coroot/coroot-node-agent/common"
  9. "github.com/coroot/coroot-node-agent/ebpftracer"
  10. "github.com/coroot/coroot-node-agent/ebpftracer/l7"
  11. "github.com/coroot/coroot-node-agent/flags"
  12. klog "github.com/sirupsen/logrus"
  13. "go.opentelemetry.io/otel/attribute"
  14. "go.opentelemetry.io/otel/codes"
  15. "go.opentelemetry.io/otel/exporters/otlp/otlptrace"
  16. "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
  17. "go.opentelemetry.io/otel/sdk/resource"
  18. sdktrace "go.opentelemetry.io/otel/sdk/trace"
  19. semconv "go.opentelemetry.io/otel/semconv/v1.18.0"
  20. "go.opentelemetry.io/otel/trace"
  21. "inet.af/netaddr"
  22. )
  23. const (
  24. MemcacheDBItemKeyName attribute.Key = "db.memcached.item"
  25. )
  26. var (
  27. tracer func(containerId string) trace.Tracer
  28. )
  29. func Init(machineId, hostname, version string) {
  30. endpointUrl := *flags.TracesEndpoint
  31. if endpointUrl == nil {
  32. klog.Infoln("no OpenTelemetry traces collector endpoint configured")
  33. return
  34. }
  35. klog.Infoln("OpenTelemetry traces collector endpoint:", endpointUrl.String())
  36. path := endpointUrl.Path
  37. if path == "" {
  38. path = "/"
  39. }
  40. opts := []otlptracehttp.Option{
  41. otlptracehttp.WithEndpoint(endpointUrl.Host),
  42. otlptracehttp.WithURLPath(path),
  43. otlptracehttp.WithHeaders(common.AuthHeaders()),
  44. otlptracehttp.WithTLSClientConfig(&tls.Config{InsecureSkipVerify: *flags.InsecureSkipVerify}),
  45. }
  46. if endpointUrl.Scheme != "https" {
  47. opts = append(opts, otlptracehttp.WithInsecure())
  48. }
  49. client := otlptracehttp.NewClient(opts...)
  50. exporter, err := otlptrace.New(context.Background(), client)
  51. if err != nil {
  52. klog.Fatalln(err)
  53. }
  54. batcher := sdktrace.WithBatcher(exporter)
  55. tracer = func(containerId string) trace.Tracer {
  56. provider := sdktrace.NewTracerProvider(
  57. batcher,
  58. sdktrace.WithResource(resource.NewWithAttributes(
  59. semconv.SchemaURL,
  60. semconv.HostName(hostname),
  61. semconv.HostID(machineId),
  62. semconv.ServiceName(common.ContainerIdToOtelServiceName(containerId)),
  63. semconv.ContainerID(containerId),
  64. )),
  65. )
  66. return provider.Tracer("coroot-node-agent", trace.WithInstrumentationVersion(version))
  67. }
  68. }
  69. type Trace struct {
  70. containerId string
  71. destination netaddr.IPPort
  72. commonAttrs []attribute.KeyValue
  73. ctx context.Context
  74. span trace.Span
  75. lock sync.RWMutex
  76. stack []ebpftracer.StackFunEvent
  77. currenEventCount *uint32
  78. needEventCount uint32
  79. startEventReady bool
  80. endEventReady bool
  81. createAt time.Time
  82. }
  83. func NewTraceFromEvent(containerId string) *Trace {
  84. if tracer == nil {
  85. return nil
  86. }
  87. var currenEventCount uint32
  88. return &Trace{containerId: containerId, currenEventCount: &currenEventCount}
  89. }
  90. func NewTrace(containerId string, destination netaddr.IPPort) *Trace {
  91. if tracer == nil {
  92. return nil
  93. }
  94. return &Trace{containerId: containerId, destination: destination, commonAttrs: []attribute.KeyValue{
  95. semconv.NetPeerName(destination.IP().String()),
  96. semconv.NetPeerPort(int(destination.Port())),
  97. }}
  98. }
  99. func (t *Trace) createSpan(name string, duration time.Duration, error bool, attrs ...attribute.KeyValue) {
  100. end := time.Now()
  101. start := end.Add(-duration)
  102. _, span := tracer(t.containerId).Start(nil, name, trace.WithTimestamp(start), trace.WithSpanKind(trace.SpanKindClient))
  103. span.SetAttributes(attrs...)
  104. span.SetAttributes(t.commonAttrs...)
  105. if error {
  106. span.SetStatus(codes.Error, "")
  107. }
  108. span.End(trace.WithTimestamp(end))
  109. }
  110. func (t *Trace) HttpRequest(method, path string, status l7.Status, duration time.Duration) {
  111. if t == nil || method == "" {
  112. return
  113. }
  114. t.createSpan(method, duration, status >= 400,
  115. semconv.HTTPURL(fmt.Sprintf("http://%s%s", t.destination.String(), path)),
  116. semconv.HTTPMethod(method),
  117. semconv.HTTPStatusCode(int(status)),
  118. )
  119. }
  120. func (t *Trace) Http2Request(method, path, scheme string, status l7.Status, duration time.Duration) {
  121. if t == nil {
  122. return
  123. }
  124. if method == "" {
  125. method = "unknown"
  126. }
  127. if path == "" {
  128. path = "/unknown"
  129. }
  130. if scheme == "" {
  131. scheme = "unknown"
  132. }
  133. t.createSpan(method, duration, status > 400,
  134. semconv.HTTPURL(fmt.Sprintf("%s://%s%s", scheme, t.destination.String(), path)),
  135. semconv.HTTPMethod(method),
  136. semconv.HTTPStatusCode(int(status)),
  137. )
  138. }
  139. func (t *Trace) PostgresQuery(query string, error bool, duration time.Duration) {
  140. if t == nil || query == "" {
  141. return
  142. }
  143. t.createSpan("query", duration, error,
  144. semconv.DBSystemPostgreSQL,
  145. semconv.DBStatement(query),
  146. )
  147. }
  148. func (t *Trace) MysqlQuery(query string, error bool, duration time.Duration) {
  149. if t == nil || query == "" {
  150. return
  151. }
  152. t.createSpan("query", duration, error,
  153. semconv.DBSystemMySQL,
  154. semconv.DBStatement(query),
  155. )
  156. }
  157. func (t *Trace) MongoQuery(query string, error bool, duration time.Duration) {
  158. if t == nil || query == "" {
  159. return
  160. }
  161. t.createSpan("query", duration, error,
  162. semconv.DBSystemMongoDB,
  163. semconv.DBStatement(query),
  164. )
  165. }
  166. func (t *Trace) MemcachedQuery(cmd string, items []string, error bool, duration time.Duration) {
  167. if t == nil || cmd == "" {
  168. return
  169. }
  170. attrs := []attribute.KeyValue{
  171. semconv.DBSystemMemcached,
  172. semconv.DBOperation(cmd),
  173. }
  174. if len(items) == 1 {
  175. attrs = append(attrs, MemcacheDBItemKeyName.String(items[0]))
  176. } else if len(items) > 1 {
  177. attrs = append(attrs, MemcacheDBItemKeyName.StringSlice(items))
  178. }
  179. t.createSpan(cmd, duration, error, attrs...)
  180. }
  181. func (t *Trace) RedisQuery(cmd, args string, error bool, duration time.Duration) {
  182. if t == nil || cmd == "" {
  183. return
  184. }
  185. statement := cmd
  186. if args != "" {
  187. statement += " " + args
  188. }
  189. t.createSpan(cmd, duration, error,
  190. semconv.DBSystemRedis,
  191. semconv.DBOperation(cmd),
  192. semconv.DBStatement(statement),
  193. )
  194. }
  195. func (t *Trace) FunAdd(stackFun ebpftracer.StackFunEvent) {
  196. t.stack = append(t.stack, stackFun)
  197. }