tracing.go 5.1 KB

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