dotnet.go 9.1 KB

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