dotnet.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. package containers
  2. import (
  3. "bytes"
  4. "context"
  5. "debug/elf"
  6. "errors"
  7. "fmt"
  8. "math"
  9. "net"
  10. "path/filepath"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/coroot/coroot-node-agent/proc"
  15. "github.com/jpillora/backoff"
  16. "github.com/prometheus/client_golang/prometheus"
  17. "github.com/pyroscope-io/dotnetdiag"
  18. "github.com/pyroscope-io/dotnetdiag/nettrace"
  19. "github.com/pyroscope-io/dotnetdiag/nettrace/typecode"
  20. klog "github.com/sirupsen/logrus"
  21. )
  22. const (
  23. dotNetDiagnosticTimeout = 500 * time.Millisecond
  24. dotNetEventInterval = 5 * time.Second
  25. provider = "System.Runtime"
  26. )
  27. type dotNetMetric struct {
  28. fields map[string]string
  29. values map[string]float64
  30. }
  31. func (m *dotNetMetric) value() float64 {
  32. switch m.fields["CounterType"] {
  33. case "Sum":
  34. return m.values["Increment"]
  35. case "Mean":
  36. return m.values["Mean"]
  37. }
  38. return math.NaN()
  39. }
  40. func (m *dotNetMetric) name() string {
  41. return m.fields["Name"]
  42. }
  43. func (m *dotNetMetric) units() string {
  44. return m.fields["DisplayUnits"]
  45. }
  46. type DotNetMonitor struct {
  47. pid uint32
  48. cancel context.CancelFunc
  49. lastUpdate time.Time
  50. runtimeVersion string
  51. info *prometheus.GaugeVec
  52. memoryAllocatedBytes prometheus.Counter
  53. exceptionCount prometheus.Gauge
  54. heapSize *prometheus.GaugeVec
  55. gcCount *prometheus.CounterVec
  56. heapFragmentationPercent prometheus.Gauge
  57. monitorLockContentionCount prometheus.Counter
  58. threadPoolCompletedItemsCount prometheus.Counter
  59. threadPoolQueueLength prometheus.Gauge
  60. threadPoolThreadsCount prometheus.Gauge
  61. }
  62. func NewDotNetMonitor(ctx context.Context, pid uint32, appName string) *DotNetMonitor {
  63. klog.Infof("starting DotNetMonitor: pid=%d, app=%s", pid, appName)
  64. constLabels := prometheus.Labels{"application": appName}
  65. m := &DotNetMonitor{
  66. pid: pid,
  67. info: newGaugeVec("container_dotnet_info", "Meta information about the Common Language Runtime (CLR)", constLabels, "runtime_version"),
  68. memoryAllocatedBytes: newCounter("container_dotnet_memory_allocated_bytes_total", "The number of bytes allocated", constLabels),
  69. exceptionCount: newGauge("container_dotnet_exceptions_total", "The number of exceptions that have occurred", constLabels),
  70. heapSize: newGaugeVec("container_dotnet_memory_heap_size_bytes", "Total size of the heap generation in bytes", constLabels, "generation"),
  71. gcCount: newCounterVec("container_dotnet_gc_count_total", "The number of times GC has occurred for the generation", constLabels, "generation"),
  72. heapFragmentationPercent: newGauge("container_dotnet_heap_fragmentation_percent", "The heap fragmentation", constLabels),
  73. monitorLockContentionCount: newCounter("container_dotnet_monitor_lock_contentions_total", "The number of times there was contention when trying to take the monitor's lock", constLabels),
  74. threadPoolCompletedItemsCount: newCounter("container_dotnet_thread_pool_completed_items_total", "The number of work items that have been processed in the ThreadPool", constLabels),
  75. threadPoolQueueLength: newGauge("container_dotnet_thread_pool_queue_length", "The number of work items that are currently queued to be processed in the ThreadPool", constLabels),
  76. threadPoolThreadsCount: newGauge("container_dotnet_thread_pool_size", "The number of thread pool threads that currently exist in the ThreadPool", constLabels),
  77. }
  78. go m.run(ctx)
  79. return m
  80. }
  81. func (m *DotNetMonitor) Collect(ch chan<- prometheus.Metric) {
  82. if m.lastUpdate.Before(time.Now().Add(-2 * dotNetEventInterval)) {
  83. return
  84. }
  85. m.info.Collect(ch)
  86. m.memoryAllocatedBytes.Collect(ch)
  87. m.exceptionCount.Collect(ch)
  88. m.heapSize.Collect(ch)
  89. m.gcCount.Collect(ch)
  90. m.heapFragmentationPercent.Collect(ch)
  91. m.monitorLockContentionCount.Collect(ch)
  92. m.threadPoolCompletedItemsCount.Collect(ch)
  93. m.threadPoolQueueLength.Collect(ch)
  94. m.threadPoolThreadsCount.Collect(ch)
  95. }
  96. func (m *DotNetMonitor) processMetric(name, units string, v float64) {
  97. m.lastUpdate = time.Now()
  98. if math.IsNaN(v) {
  99. return
  100. }
  101. switch units {
  102. case "MB":
  103. v *= 1000 * 1000
  104. }
  105. switch name {
  106. case "alloc-rate":
  107. m.memoryAllocatedBytes.Add(v)
  108. case "exception-count":
  109. m.exceptionCount.Set(v)
  110. case "gen-0-gc-count":
  111. m.gcCount.WithLabelValues("Gen0").Add(v)
  112. case "gen-1-gc-count":
  113. m.gcCount.WithLabelValues("Gen1").Add(v)
  114. case "gen-2-gc-count":
  115. m.gcCount.WithLabelValues("Gen2").Add(v)
  116. case "gen-0-size":
  117. m.heapSize.WithLabelValues("Gen0").Set(v)
  118. case "gen-1-size":
  119. m.heapSize.WithLabelValues("Gen1").Set(v)
  120. case "gen-2-size":
  121. m.heapSize.WithLabelValues("Gen2").Set(v)
  122. case "loh-size":
  123. m.heapSize.WithLabelValues("LOH").Set(v)
  124. case "poh-size":
  125. m.heapSize.WithLabelValues("POH").Set(v)
  126. case "gc-fragmentation":
  127. m.heapFragmentationPercent.Set(v)
  128. case "monitor-lock-contention-count":
  129. m.monitorLockContentionCount.Add(v)
  130. case "threadpool-completed-items-count":
  131. m.threadPoolCompletedItemsCount.Add(v)
  132. case "threadpool-queue-length":
  133. m.threadPoolQueueLength.Set(v)
  134. case "threadpool-thread-count":
  135. m.threadPoolThreadsCount.Set(v)
  136. }
  137. }
  138. func (m *DotNetMonitor) run(ctx context.Context) {
  139. b := backoff.Backoff{Factor: 2, Min: time.Second, Max: time.Minute}
  140. for {
  141. select {
  142. case <-ctx.Done():
  143. return
  144. default:
  145. err := m.connect(ctx)
  146. if err == nil {
  147. return
  148. }
  149. d := b.Duration()
  150. klog.Warningf(
  151. "failed to establish connection with the .NET diagnostic socket pid=%d, next attempt in %s: %s",
  152. m.pid, d.String(), err,
  153. )
  154. time.Sleep(d)
  155. }
  156. }
  157. }
  158. func (m *DotNetMonitor) connect(ctx context.Context) error {
  159. files, _ := filepath.Glob(proc.Path(m.pid, fmt.Sprintf("root/tmp/dotnet-diagnostic-%d-*-socket", proc.GetNsPid(m.pid))))
  160. if len(files) != 1 {
  161. return fmt.Errorf("no socket found")
  162. }
  163. klog.Infoln(".NET diagnostic socket:", files[0])
  164. c := dotnetdiag.NewClient(files[0], dotnetdiag.WithDialer(func(addr string) (net.Conn, error) {
  165. return net.DialTimeout("unix", addr, dotNetDiagnosticTimeout)
  166. }))
  167. if pi, err := c.ProcessInfo(); err == nil {
  168. m.info.WithLabelValues(pi.ClrProductVersion).Set(1)
  169. } else {
  170. m.info.WithLabelValues("unknown").Set(1)
  171. }
  172. ctc := dotnetdiag.CollectTracingConfig{
  173. CircularBufferSizeMB: 10,
  174. Providers: []dotnetdiag.ProviderConfig{
  175. {
  176. Keywords: math.MaxInt64,
  177. LogLevel: 5,
  178. ProviderName: provider,
  179. FilterData: "EventCounterIntervalSec=" + strconv.Itoa(int(dotNetEventInterval.Seconds())),
  180. },
  181. },
  182. }
  183. sess, err := c.CollectTracing(ctc)
  184. if err != nil {
  185. return err
  186. }
  187. defer func() {
  188. _ = sess.Close()
  189. }()
  190. stream := nettrace.NewStream(sess)
  191. if _, err = stream.Open(); err != nil {
  192. return err
  193. }
  194. metadata := map[int32]*nettrace.Metadata{}
  195. stream.EventHandler = func(e *nettrace.Blob) error {
  196. md, ok := metadata[e.Header.MetadataID]
  197. if !ok {
  198. return fmt.Errorf("metadata not found")
  199. }
  200. parser := nettrace.Parser{Buffer: e.Payload}
  201. if md.Header.ProviderName != provider {
  202. return nil
  203. }
  204. dnm := &dotNetMetric{
  205. fields: map[string]string{},
  206. values: map[string]float64{},
  207. }
  208. if err := parseFields(md.Payload.Fields, parser, dnm); err != nil {
  209. return err
  210. }
  211. m.processMetric(dnm.name(), dnm.units(), dnm.value())
  212. return nil
  213. }
  214. stream.MetadataHandler = func(md *nettrace.Metadata) error {
  215. metadata[md.Header.MetaDataID] = md
  216. return nil
  217. }
  218. for {
  219. select {
  220. case <-ctx.Done():
  221. return nil
  222. default:
  223. if err = stream.Next(); err != nil {
  224. return err
  225. }
  226. }
  227. }
  228. }
  229. func parseFields(fields []nettrace.MetadataField, parser nettrace.Parser, metric *dotNetMetric) error {
  230. for _, field := range fields {
  231. switch field.TypeCode {
  232. case typecode.Object:
  233. if err := parseFields(field.Payload.Fields, parser, metric); err != nil {
  234. return err
  235. }
  236. case typecode.String:
  237. v := parser.UTF16NTS()
  238. if err := parser.Err(); err != nil {
  239. return err
  240. }
  241. metric.fields[field.Name] = v
  242. case typecode.Double:
  243. var v float64
  244. parser.Read(&v)
  245. if err := parser.Err(); err != nil {
  246. return err
  247. }
  248. metric.values[field.Name] = v
  249. case typecode.Single:
  250. var v float32
  251. parser.Read(&v)
  252. if err := parser.Err(); err != nil {
  253. return err
  254. }
  255. metric.values[field.Name] = float64(v)
  256. case typecode.Int32:
  257. var v int32
  258. parser.Read(&v)
  259. if err := parser.Err(); err != nil {
  260. return err
  261. }
  262. metric.values[field.Name] = float64(v)
  263. default:
  264. return fmt.Errorf("unsupported field type: %d", field.TypeCode)
  265. }
  266. }
  267. return nil
  268. }
  269. func dotNetApp(pid uint32) (string, error) {
  270. file, err := elf.Open(proc.Path(pid, "exe"))
  271. if err != nil {
  272. return "", err
  273. }
  274. defer func() { _ = file.Close() }()
  275. res, _ := file.DynString(elf.DT_RPATH)
  276. if len(res) == 0 {
  277. res, _ = file.DynString(elf.DT_RUNPATH)
  278. }
  279. if len(res) == 1 && res[0] == "$ORIGIN/netcoredeps" {
  280. cmdline := proc.GetCmdline(pid)
  281. if cmdline == nil {
  282. return "", errors.New("failed to read proc cmdline")
  283. }
  284. firstArg := bytes.Split(cmdline, []byte{0})[0]
  285. parts := strings.Split(string(firstArg), "/")
  286. app := parts[len(parts)-1]
  287. return app, nil
  288. }
  289. return "", nil
  290. }