open_sockets.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. * decaffeinate suggestions:
  3. * DS102: Remove unnecessary code created because of implicit returns
  4. * DS205: Consider reworking code to avoid use of IIFEs
  5. * DS207: Consider shorter variations of null checks
  6. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  7. */
  8. let OpenSocketsMonitor
  9. const seconds = 1000
  10. // In Node 0.10 the default is 5, which means only 5 open connections at one.
  11. // Node 0.12 has a default of Infinity. Make sure we have no limit set,
  12. // regardless of Node version.
  13. require('http').globalAgent.maxSockets = Infinity
  14. require('https').globalAgent.maxSockets = Infinity
  15. const SOCKETS_HTTP = require('http').globalAgent.sockets
  16. const SOCKETS_HTTPS = require('https').globalAgent.sockets
  17. // keep track of set gauges and reset them in the next collection cycle
  18. const SEEN_HOSTS_HTTP = new Set()
  19. const SEEN_HOSTS_HTTPS = new Set()
  20. function collectOpenConnections(sockets, seenHosts, prefix) {
  21. const Metrics = require('./index')
  22. Object.keys(sockets).forEach(host => seenHosts.add(host))
  23. seenHosts.forEach(host => {
  24. // host: 'HOST:PORT:'
  25. const hostname = host.split(':')[0]
  26. const openConnections = (sockets[host] || []).length
  27. if (!openConnections) {
  28. seenHosts.delete(host)
  29. }
  30. Metrics.gauge(`open_connections.${prefix}.${hostname}`, openConnections)
  31. })
  32. }
  33. module.exports = OpenSocketsMonitor = {
  34. monitor(logger) {
  35. const interval = setInterval(
  36. () => OpenSocketsMonitor.gaugeOpenSockets(),
  37. 5 * seconds
  38. )
  39. const Metrics = require('./index')
  40. return Metrics.registerDestructor(() => clearInterval(interval))
  41. },
  42. gaugeOpenSockets() {
  43. collectOpenConnections(SOCKETS_HTTP, SEEN_HOSTS_HTTP, 'http')
  44. collectOpenConnections(SOCKETS_HTTPS, SEEN_HOSTS_HTTPS, 'https')
  45. },
  46. }