leaked_sockets.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. /**
  2. * This file monitors HTTP connections in Node.js and logs any potential socket leaks.
  3. * It uses the `diagnostics_channel` module to intercept requests and reponses in the
  4. * `http` module and tracks the lifetime of each http socket. If a socket is open for
  5. * longer than a specified time, it is considered a potential leak and its details are
  6. * logged along with the corresponding information from /proc/net/tcp.
  7. */
  8. const fs = require('fs')
  9. const diagnosticsChannel = require('diagnostics_channel')
  10. const SOCKET_MONITOR_INTERVAL = 60 * 1000
  11. // set the threshold for logging leaked sockets in minutes, defaults to 15
  12. const MIN_SOCKET_LEAK_TIME =
  13. (parseInt(process.env.LEAKED_SOCKET_AGE_THRESHOLD, 10) || 15) * 60 * 1000
  14. // Record HTTP events using diagnostics_channel
  15. const channels = [
  16. 'http.client.request.start',
  17. 'http.client.response.finish',
  18. 'http.server.request.start',
  19. 'http.server.response.finish',
  20. ]
  21. for (const channel of channels) {
  22. diagnosticsChannel.subscribe(channel, handler(channel))
  23. }
  24. function handler(channel) {
  25. return function ({ request: req, response: res }) {
  26. const socket = req?.socket || res?.socket
  27. if (!socket) {
  28. return
  29. }
  30. // If we haven't seen this socket before, add a debug object from the request
  31. if (!socket._ol_debug && req) {
  32. const { method, protocol, path, url, rawHeaders, _header } = req
  33. socket._ol_debug = {
  34. method,
  35. protocol,
  36. url: url ?? path,
  37. request: { headers: rawHeaders ?? _header, ts: new Date() },
  38. }
  39. } else if (socket._ol_debug && res) {
  40. // We've already seen the request, now add debug info from the response
  41. const { statusCode, statusMessage, headers, _header } = res
  42. Object.assign(socket._ol_debug, {
  43. response: {
  44. statusCode,
  45. statusMessage,
  46. headers: headers ?? _header,
  47. ts: new Date(),
  48. },
  49. })
  50. }
  51. }
  52. }
  53. // Additional functions to log request headers with sensitive information redacted
  54. function flattenHeaders(rawHeaders) {
  55. // Headers can be an array [KEY, VALUE, KEY, VALUE, ..]
  56. // an object {key:value, key:value, ...}
  57. // or a string of the headers separated by \r\n
  58. // Flatten the array and object headers into the string form.
  59. if (Array.isArray(rawHeaders)) {
  60. return rawHeaders
  61. .map((item, index) => (index % 2 === 0 ? `${item}: ` : `${item}\r\n`))
  62. .join('')
  63. } else if (typeof rawHeaders === 'object') {
  64. return Object.entries(rawHeaders)
  65. .map(([key, value]) => `${key}: ${value}\r\n`)
  66. .join('')
  67. } else if (typeof rawHeaders === 'string') {
  68. return rawHeaders
  69. } else {
  70. return JSON.stringify(rawHeaders)
  71. }
  72. }
  73. const REDACT_REGEX = /^(Authorization|Set-Cookie|Cookie):.*?\r/gim
  74. function redactObject(obj) {
  75. const result = {}
  76. for (const [key, value] of Object.entries(obj)) {
  77. if (key === 'headers') {
  78. // remove headers with sensitive information
  79. result[key] = flattenHeaders(value).replace(
  80. REDACT_REGEX,
  81. `$1: REDACTED\r`
  82. )
  83. } else if (
  84. typeof value === 'object' &&
  85. ['request', 'response'].includes(key)
  86. ) {
  87. result[key] = redactObject(value)
  88. } else {
  89. result[key] = value
  90. }
  91. }
  92. return result
  93. }
  94. // Check if an old socket has crossed the threshold for logging.
  95. // We log multiple times with an exponential backoff so we can
  96. // see how long a socket hangs around.
  97. function isOldSocket(handle) {
  98. const now = new Date()
  99. const created = handle._ol_debug.request.ts
  100. const lastLoggedAt = handle._ol_debug.lastLoggedAt ?? created
  101. const nextLogTime = new Date(
  102. created.getTime() +
  103. Math.max(2 * (lastLoggedAt - created), MIN_SOCKET_LEAK_TIME)
  104. )
  105. return now >= nextLogTime
  106. }
  107. function logOldSocket(logger, handle, tcpinfo) {
  108. const now = new Date()
  109. const info = Object.assign(
  110. {
  111. localAddress: handle.localAddress,
  112. localPort: handle.localPort,
  113. remoteAddress: handle.remoteAddress,
  114. remotePort: handle.remotePort,
  115. tcpinfo,
  116. age: Math.floor((now - handle._ol_debug.request.ts) / (60 * 1000)), // age in minutes
  117. },
  118. redactObject(handle._ol_debug)
  119. )
  120. handle._ol_debug.lastLoggedAt = now
  121. if (tcpinfo) {
  122. logger.error(info, 'old socket handle - tcp socket')
  123. } else {
  124. logger.warn(info, 'stale socket handle - no entry in /proc/net/tcp')
  125. }
  126. }
  127. // Correlate socket handles with /proc/net/tcp entries using a key based on the
  128. // local and remote addresses and ports. This will allow us to distinguish between
  129. // sockets that are still open and sockets that have been closed and removed from
  130. // the /proc/net/tcp table but are still present in the node active handles array.
  131. async function getOpenSockets() {
  132. // get open sockets remote and local address:port from /proc/net/tcp
  133. const procNetTcp = '/proc/net/tcp'
  134. const openSockets = new Map()
  135. const lines = await fs.promises.readFile(procNetTcp, 'utf8')
  136. for (const line of lines.split('\n')) {
  137. const socket = parseProcNetTcp(line)
  138. if (socket) {
  139. openSockets.set(socket, line)
  140. }
  141. }
  142. return openSockets
  143. }
  144. function keyFromSocket(socket) {
  145. return `${socket.localAddress}:${socket.localPort} -> ${socket.remoteAddress}:${socket.remotePort}`
  146. }
  147. function decodeHexIpAddress(hex) {
  148. // decode hex ip address to dotted decimal notation
  149. const ip = parseInt(hex, 16)
  150. const a = ip & 0xff
  151. const b = (ip >> 8) & 0xff
  152. const c = (ip >> 16) & 0xff
  153. const d = (ip >> 24) & 0xff
  154. return `${a}.${b}.${c}.${d}`
  155. }
  156. function decodeHexPort(hex) {
  157. // decode hex port to decimal
  158. return parseInt(hex, 16)
  159. }
  160. // Regex for extracting the local and remote addresses and ports from the /proc/net/tcp output
  161. // Example line:
  162. // 16: AB02A8C0:D9E2 86941864:01BB 01 00000000:00000000 02:000004BE 00000000 0 0 36802 2 0000000000000000 28 4 26 10 -1
  163. // ^^^^^^^^^^^^^ ^^^^^^^^^^^^^
  164. // local remote
  165. const TCP_STATE_REGEX =
  166. /^\s*\d+:\s+(?<localHexAddress>[0-9A-F]{8}):(?<localHexPort>[0-9A-F]{4})\s+(?<remoteHexAddress>[0-9A-F]{8}):(?<remoteHexPort>[0-9A-F]{4})/i
  167. function parseProcNetTcp(line) {
  168. const match = line.match(TCP_STATE_REGEX)
  169. if (match) {
  170. const { localHexAddress, localHexPort, remoteHexAddress, remoteHexPort } =
  171. match.groups
  172. return keyFromSocket({
  173. localAddress: decodeHexIpAddress(localHexAddress),
  174. localPort: decodeHexPort(localHexPort),
  175. remoteAddress: decodeHexIpAddress(remoteHexAddress),
  176. remotePort: decodeHexPort(remoteHexPort),
  177. })
  178. }
  179. }
  180. let LeakedSocketsMonitor
  181. // Export the monitor and scanSockets functions
  182. module.exports = LeakedSocketsMonitor = {
  183. monitor(logger) {
  184. const interval = setInterval(
  185. () => LeakedSocketsMonitor.scanSockets(logger),
  186. SOCKET_MONITOR_INTERVAL
  187. )
  188. const Metrics = require('./index')
  189. return Metrics.registerDestructor(() => clearInterval(interval))
  190. },
  191. scanSockets(logger) {
  192. const debugSockets = process._getActiveHandles().filter(handle => {
  193. return handle._ol_debug
  194. })
  195. // Bail out if there are no sockets with the _ol_debug property
  196. if (debugSockets.length === 0) {
  197. return
  198. }
  199. const oldSockets = debugSockets.filter(isOldSocket)
  200. // Bail out if there are no old sockets to log
  201. if (oldSockets.length === 0) {
  202. return
  203. }
  204. // If there old sockets to log, get the connections from /proc/net/tcp
  205. // to distinguish between sockets that are still open and sockets that
  206. // have been closed and removed from the /proc/net/tcp table.
  207. getOpenSockets()
  208. .then(openSockets => {
  209. oldSockets.forEach(handle => {
  210. try {
  211. const key = keyFromSocket(handle)
  212. const tcpinfo = openSockets.get(key)
  213. logOldSocket(logger, handle, tcpinfo)
  214. } catch (err) {
  215. logger.error({ err }, 'error in scanSockets')
  216. }
  217. })
  218. })
  219. .catch(err => {
  220. logger.error({ err }, 'error getting open sockets')
  221. })
  222. },
  223. }