open_sockets.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 { URL } = require('url')
  10. const seconds = 1000
  11. // In Node 0.10 the default is 5, which means only 5 open connections at one.
  12. // Node 0.12 has a default of Infinity. Make sure we have no limit set,
  13. // regardless of Node version.
  14. require('http').globalAgent.maxSockets = Infinity
  15. require('https').globalAgent.maxSockets = Infinity
  16. module.exports = OpenSocketsMonitor = {
  17. monitor(logger) {
  18. const interval = setInterval(
  19. () => OpenSocketsMonitor.gaugeOpenSockets(),
  20. 5 * seconds
  21. )
  22. const Metrics = require('./index')
  23. return Metrics.registerDestructor(() => clearInterval(interval))
  24. },
  25. gaugeOpenSockets() {
  26. let agents, hostname, url
  27. const Metrics = require('./index')
  28. const object = require('http').globalAgent.sockets
  29. for (url in object) {
  30. agents = object[url]
  31. url = new URL(`http://${url}`)
  32. hostname =
  33. url.hostname != null ? url.hostname.replace(/\./g, '_') : undefined
  34. Metrics.gauge(`open_connections.http.${hostname}`, agents.length)
  35. }
  36. return (() => {
  37. const result = []
  38. const object1 = require('https').globalAgent.sockets
  39. for (url in object1) {
  40. agents = object1[url]
  41. url = new URL(`https://${url}`)
  42. hostname =
  43. url.hostname != null ? url.hostname.replace(/\./g, '_') : undefined
  44. result.push(
  45. Metrics.gauge(`open_connections.https.${hostname}`, agents.length)
  46. )
  47. }
  48. return result
  49. })()
  50. }
  51. }