tracing.go 5.0 KB

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