index.js 5.7 KB

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