dotnet.go 9.3 KB

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