tracing.go 5.2 KB

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