mongodb.js 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. const { Gauge, Summary, Counter } = require('prom-client')
  2. /** @type {poolSize: Gauge<string>, availableConnections: Gauge<string>, waitQueueSize: Gauge<string>, maxPoolSize: Gauge<string>, mongoCommandStarted: Counter<string>, mongoCommandTimer: Summary<string>} */
  3. let metrics
  4. const collectPoolMetrics = []
  5. /**
  6. * @param clientLabel
  7. */
  8. function initMetricsOnce(clientLabel) {
  9. if (metrics) return
  10. const poolLabelNames = ['mongo_server']
  11. if (clientLabel) poolLabelNames.push('client')
  12. const poolSize = new Gauge({
  13. name: 'mongo_connection_pool_size',
  14. help: 'number of connections in the connection pool',
  15. labelNames: poolLabelNames,
  16. // Use this one metric's collect() to set all metrics' values.
  17. collect() {
  18. // Reset all gauges in case they contain values for servers that
  19. // disappeared
  20. metrics.poolSize.reset()
  21. metrics.availableConnections.reset()
  22. metrics.waitQueueSize.reset()
  23. metrics.maxPoolSize.reset()
  24. collectPoolMetrics.forEach(fn => fn())
  25. },
  26. })
  27. const availableConnections = new Gauge({
  28. name: 'mongo_connection_pool_available',
  29. help: 'number of connections that are not busy',
  30. labelNames: poolLabelNames,
  31. })
  32. const waitQueueSize = new Gauge({
  33. name: 'mongo_connection_pool_waiting',
  34. help: 'number of operations waiting for an available connection',
  35. labelNames: poolLabelNames,
  36. })
  37. const maxPoolSize = new Gauge({
  38. name: 'mongo_connection_pool_max',
  39. help: 'max size for the connection pool',
  40. labelNames: poolLabelNames,
  41. })
  42. const mongoCommandStarted = new Counter({
  43. name: 'mongo_command_started',
  44. help: 'mongo command started',
  45. labelNames: ['method', 'collection'],
  46. })
  47. const mongoCommandTimer = new Summary({
  48. name: 'mongo_command_time',
  49. help: 'time taken to complete a mongo command',
  50. percentiles: [],
  51. labelNames: ['status', 'method', 'ns'],
  52. })
  53. metrics = {
  54. poolSize,
  55. availableConnections,
  56. waitQueueSize,
  57. maxPoolSize,
  58. mongoCommandStarted,
  59. mongoCommandTimer,
  60. }
  61. return metrics
  62. }
  63. function monitor(mongoClient, clientLabel) {
  64. initMetricsOnce(clientLabel)
  65. mongoClient.on('commandStarted', event => {
  66. const { commandName, command } = event
  67. const collection = command?.[commandName]
  68. if (typeof collection !== 'string') return // Lifecycle commands
  69. if (commandName === 'create') return // Mongoose init
  70. metrics.mongoCommandStarted.inc({
  71. method: commandName === 'find' ? 'read' : 'write',
  72. collection,
  73. })
  74. })
  75. mongoClient.on('commandSucceeded', event => {
  76. metrics.mongoCommandTimer.observe(
  77. {
  78. status: 'success',
  79. method: event.commandName === 'find' ? 'read' : 'write',
  80. ns: event.reply?.cursor?.ns, // best effort, set on 'find'
  81. },
  82. event.duration
  83. )
  84. })
  85. mongoClient.on('commandFailed', event => {
  86. metrics.mongoCommandTimer.observe(
  87. {
  88. status: 'failed',
  89. method: event.commandName === 'find' ? 'read' : 'write',
  90. },
  91. event.duration
  92. )
  93. })
  94. function collect() {
  95. const servers = mongoClient.topology?.s?.servers
  96. if (servers != null) {
  97. for (const [address, server] of servers) {
  98. // The server object is different between v4 and v5 (c.f. https://github.com/mongodb/node-mongodb-native/pull/3645)
  99. const pool = server.s?.pool || server.pool
  100. if (pool == null) {
  101. continue
  102. }
  103. const labels = { mongo_server: address }
  104. if (clientLabel) labels.client = clientLabel
  105. metrics.poolSize.set(labels, pool.totalConnectionCount)
  106. metrics.availableConnections.set(labels, pool.availableConnectionCount)
  107. metrics.waitQueueSize.set(labels, pool.waitQueueSize)
  108. metrics.maxPoolSize.set(labels, pool.options.maxPoolSize)
  109. }
  110. }
  111. }
  112. collectPoolMetrics.push(collect)
  113. }
  114. module.exports = {
  115. monitor,
  116. reset() {
  117. metrics = undefined
  118. collectPoolMetrics.length = 0
  119. },
  120. }