mongodb.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. const { Gauge, Summary } = require('prom-client')
  2. function monitor(mongoClient) {
  3. const labelNames = ['mongo_server']
  4. const poolSize = new Gauge({
  5. name: 'mongo_connection_pool_size',
  6. help: 'number of connections in the connection pool',
  7. labelNames,
  8. // Use this one metric's collect() to set all metrics' values.
  9. collect,
  10. })
  11. const availableConnections = new Gauge({
  12. name: 'mongo_connection_pool_available',
  13. help: 'number of connections that are not busy',
  14. labelNames,
  15. })
  16. const waitQueueSize = new Gauge({
  17. name: 'mongo_connection_pool_waiting',
  18. help: 'number of operations waiting for an available connection',
  19. labelNames,
  20. })
  21. const maxPoolSize = new Gauge({
  22. name: 'mongo_connection_pool_max',
  23. help: 'max size for the connection pool',
  24. labelNames,
  25. })
  26. const mongoCommandTimer = new Summary({
  27. name: 'mongo_command_time',
  28. help: 'time taken to complete a mongo command',
  29. percentiles: [],
  30. labelNames: ['status', 'method'],
  31. })
  32. if (mongoClient.on) {
  33. mongoClient.on('commandSucceeded', event => {
  34. mongoCommandTimer.observe(
  35. {
  36. status: 'success',
  37. method: event.commandName === 'find' ? 'read' : 'write',
  38. },
  39. event.duration
  40. )
  41. })
  42. mongoClient.on('commandFailed', event => {
  43. mongoCommandTimer.observe(
  44. {
  45. status: 'failed',
  46. method: event.commandName === 'find' ? 'read' : 'write',
  47. },
  48. event.duration
  49. )
  50. })
  51. }
  52. function collect() {
  53. // Reset all gauges in case they contain values for servers that
  54. // disappeared
  55. poolSize.reset()
  56. availableConnections.reset()
  57. waitQueueSize.reset()
  58. maxPoolSize.reset()
  59. const servers = mongoClient.topology?.s?.servers
  60. if (servers != null) {
  61. for (const [address, server] of servers) {
  62. // The server object is different between v4 and v5 (c.f. https://github.com/mongodb/node-mongodb-native/pull/3645)
  63. const pool = server.s?.pool || server.pool
  64. if (pool == null) {
  65. continue
  66. }
  67. const labels = { mongo_server: address }
  68. poolSize.set(labels, pool.totalConnectionCount)
  69. availableConnections.set(labels, pool.availableConnectionCount)
  70. waitQueueSize.set(labels, pool.waitQueueSize)
  71. maxPoolSize.set(labels, pool.options.maxPoolSize)
  72. }
  73. }
  74. }
  75. }
  76. module.exports = { monitor }