tracing.go 6.5 KB

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