index.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. /* eslint-disable no-console */
  2. const os = require('os')
  3. const ExpressCompression = require('compression')
  4. const promClient = require('prom-client')
  5. const promWrapper = require('./prom_wrapper')
  6. const tracing = require('./tracing')
  7. const DEFAULT_APP_NAME = 'unknown'
  8. const { collectDefaultMetrics } = promWrapper
  9. const destructors = []
  10. require('./uv_threadpool_size')
  11. /**
  12. * Configure the metrics module
  13. */
  14. function configure(opts = {}) {
  15. const appName = opts.appName || DEFAULT_APP_NAME
  16. const hostname = os.hostname()
  17. promClient.register.setDefaultLabels({ app: appName, host: hostname })
  18. if (opts.ttlInMinutes) {
  19. promWrapper.ttlInMinutes = opts.ttlInMinutes
  20. }
  21. }
  22. let initialized = false
  23. /**
  24. * Configure the metrics module and start the default metrics collectors and
  25. * profiling agents.
  26. */
  27. function initialize(appName, opts = {}) {
  28. if (initialized) {
  29. return
  30. }
  31. appName = appName || DEFAULT_APP_NAME
  32. if (tracing.tracingEnabled()) {
  33. tracing.initialize(appName)
  34. }
  35. configure({ ...opts, appName })
  36. collectDefaultMetrics({ timeout: 5000, prefix: '' })
  37. promWrapper.setupSweeping()
  38. console.log(`ENABLE_TRACE_AGENT set to ${process.env.ENABLE_TRACE_AGENT}`)
  39. if (process.env.ENABLE_TRACE_AGENT === 'true') {
  40. console.log('starting google trace agent')
  41. const traceAgent = require('@google-cloud/trace-agent')
  42. const traceOpts = { ignoreUrls: [/^\/status/, /^\/health_check/] }
  43. traceAgent.start(traceOpts)
  44. }
  45. console.log(`ENABLE_PROFILE_AGENT set to ${process.env.ENABLE_PROFILE_AGENT}`)
  46. if (process.env.ENABLE_PROFILE_AGENT === 'true') {
  47. console.log('starting google profile agent')
  48. const profiler = require('@google-cloud/profiler')
  49. profiler.start({
  50. serviceContext: {
  51. service: appName,
  52. version: process.env.BUILD_VERSION,
  53. },
  54. })
  55. }
  56. inc('process_startup')
  57. initialized = true
  58. }
  59. function registerDestructor(func) {
  60. destructors.push(func)
  61. }
  62. function injectMetricsRoute(app) {
  63. app.get(
  64. '/metrics',
  65. ExpressCompression({
  66. level: parseInt(process.env.METRICS_COMPRESSION_LEVEL || '1', 10),
  67. }),
  68. function (req, res, next) {
  69. res.set('Content-Type', promWrapper.registry.contentType)
  70. promWrapper.registry
  71. .metrics()
  72. .then(metrics => {
  73. res.end(metrics)
  74. })
  75. .catch(err => {
  76. next(err)
  77. })
  78. }
  79. )
  80. }
  81. function buildPromKey(key) {
  82. return key.replace(/[^a-zA-Z0-9]/g, '_')
  83. }
  84. function sanitizeValue(value) {
  85. return parseFloat(value)
  86. }
  87. function set(key, value, sampleRate = 1) {
  88. console.log('counts are not currently supported')
  89. }
  90. function inc(key, sampleRate = 1, labels = {}) {
  91. if (arguments.length === 2 && typeof sampleRate === 'object') {
  92. labels = sampleRate
  93. }
  94. key = buildPromKey(key)
  95. promWrapper.metric('counter', key, labels).inc(labels)
  96. if (process.env.DEBUG_METRICS) {
  97. console.log('doing inc', key, labels)
  98. }
  99. }
  100. function count(key, count, sampleRate = 1, labels = {}) {
  101. if (arguments.length === 3 && typeof sampleRate === 'object') {
  102. labels = sampleRate
  103. }
  104. key = buildPromKey(key)
  105. promWrapper.metric('counter', key, labels).inc(labels, count)
  106. if (process.env.DEBUG_METRICS) {
  107. console.log('doing count/inc', key, labels)
  108. }
  109. }
  110. function summary(key, value, labels = {}) {
  111. key = buildPromKey(key)
  112. promWrapper.metric('summary', key, labels).observe(labels, value)
  113. if (process.env.DEBUG_METRICS) {
  114. console.log('doing summary', key, value, labels)
  115. }
  116. }
  117. function timing(key, timeSpan, sampleRate = 1, labels = {}) {
  118. if (arguments.length === 3 && typeof sampleRate === 'object') {
  119. labels = sampleRate
  120. }
  121. key = buildPromKey('timer_' + key)
  122. promWrapper.metric('summary', key, labels).observe(labels, timeSpan)
  123. if (process.env.DEBUG_METRICS) {
  124. console.log('doing timing', key, labels)
  125. }
  126. }
  127. function histogram(key, value, buckets, labels = {}) {
  128. key = buildPromKey('histogram_' + key)
  129. promWrapper.metric('histogram', key, labels, buckets).observe(labels, value)
  130. if (process.env.DEBUG_METRICS) {
  131. console.log('doing histogram', key, buckets, labels)
  132. }
  133. }
  134. class Timer {
  135. constructor(key, sampleRate = 1, labels = {}, buckets) {
  136. if (typeof sampleRate === 'object') {
  137. // called with (key, labels, buckets)
  138. if (arguments.length === 3) {
  139. buckets = labels
  140. labels = sampleRate
  141. }
  142. // called with (key, labels)
  143. if (arguments.length === 2) {
  144. labels = sampleRate
  145. }
  146. sampleRate = 1 // default value to pass to timing function
  147. }
  148. this.start = new Date()
  149. key = buildPromKey(key)
  150. this.key = key
  151. this.sampleRate = sampleRate
  152. this.labels = labels
  153. this.buckets = buckets
  154. }
  155. done() {
  156. const timeSpan = new Date() - this.start
  157. if (this.buckets) {
  158. histogram(this.key, timeSpan, this.buckets, this.labels)
  159. } else {
  160. timing(this.key, timeSpan, this.sampleRate, this.labels)
  161. }
  162. return timeSpan
  163. }
  164. }
  165. function gauge(key, value, sampleRate = 1, labels = {}) {
  166. if (arguments.length === 3 && typeof sampleRate === 'object') {
  167. labels = sampleRate
  168. }
  169. key = buildPromKey(key)
  170. promWrapper.metric('gauge', key, labels).set(labels, sanitizeValue(value))
  171. if (process.env.DEBUG_METRICS) {
  172. console.log('doing gauge', key, labels)
  173. }
  174. }
  175. function globalGauge(key, value, sampleRate = 1, labels = {}) {
  176. key = buildPromKey(key)
  177. labels = { host: 'global', ...labels }
  178. promWrapper.metric('gauge', key, labels).set(labels, sanitizeValue(value))
  179. }
  180. function close() {
  181. for (const func of destructors) {
  182. func()
  183. }
  184. }
  185. module.exports.configure = configure
  186. module.exports.initialize = initialize
  187. module.exports.registerDestructor = registerDestructor
  188. module.exports.injectMetricsRoute = injectMetricsRoute
  189. module.exports.buildPromKey = buildPromKey
  190. module.exports.sanitizeValue = sanitizeValue
  191. module.exports.set = set
  192. module.exports.inc = inc
  193. module.exports.count = count
  194. module.exports.summary = summary
  195. module.exports.timing = timing
  196. module.exports.histogram = histogram
  197. module.exports.Timer = Timer
  198. module.exports.gauge = gauge
  199. module.exports.globalGauge = globalGauge
  200. module.exports.close = close
  201. module.exports.prom = promClient
  202. module.exports.register = promWrapper.registry
  203. module.exports.http = require('./http')
  204. module.exports.open_sockets = require('./open_sockets')
  205. module.exports.leaked_sockets = require('./leaked_sockets')
  206. module.exports.event_loop = require('./event_loop')
  207. module.exports.memory = require('./memory')
  208. module.exports.mongodb = require('./mongodb')
  209. module.exports.timeAsyncMethod = require('./timeAsyncMethod')