index.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. if (arguments.length === 2 && typeof sampleRate === 'object') {
  88. opts = sampleRate
  89. }
  90. key = buildPromKey(key)
  91. promWrapper.metric('counter', key).inc(opts)
  92. if (process.env.DEBUG_METRICS) {
  93. console.log('doing inc', key, opts)
  94. }
  95. }
  96. function count(key, count, sampleRate = 1, opts = {}) {
  97. if (arguments.length === 3 && typeof sampleRate === 'object') {
  98. opts = sampleRate
  99. }
  100. key = buildPromKey(key)
  101. promWrapper.metric('counter', key).inc(opts, count)
  102. if (process.env.DEBUG_METRICS) {
  103. console.log('doing count/inc', key, opts)
  104. }
  105. }
  106. function summary(key, value, opts = {}) {
  107. key = buildPromKey(key)
  108. promWrapper.metric('summary', key).observe(opts, value)
  109. if (process.env.DEBUG_METRICS) {
  110. console.log('doing summary', key, value, opts)
  111. }
  112. }
  113. function timing(key, timeSpan, sampleRate = 1, opts = {}) {
  114. if (arguments.length === 3 && typeof sampleRate === 'object') {
  115. opts = sampleRate
  116. }
  117. key = buildPromKey('timer_' + key)
  118. promWrapper.metric('summary', key).observe(opts, timeSpan)
  119. if (process.env.DEBUG_METRICS) {
  120. console.log('doing timing', key, opts)
  121. }
  122. }
  123. function histogram(key, value, buckets, opts = {}) {
  124. key = buildPromKey('histogram_' + key)
  125. promWrapper.metric('histogram', key, buckets).observe(opts, value)
  126. if (process.env.DEBUG_METRICS) {
  127. console.log('doing histogram', key, buckets, opts)
  128. }
  129. }
  130. class Timer {
  131. constructor(key, sampleRate = 1, opts = {}, buckets) {
  132. if (typeof sampleRate === 'object') {
  133. // called with (key, opts, buckets)
  134. if (arguments.length === 3) {
  135. buckets = opts
  136. opts = sampleRate
  137. }
  138. // called with (key, opts)
  139. if (arguments.length === 2) {
  140. opts = sampleRate
  141. }
  142. sampleRate = 1 // default value to pass to timing function
  143. }
  144. this.start = new Date()
  145. key = buildPromKey(key)
  146. this.key = key
  147. this.sampleRate = sampleRate
  148. this.opts = opts
  149. this.buckets = buckets
  150. }
  151. done() {
  152. const timeSpan = new Date() - this.start
  153. if (this.buckets) {
  154. histogram(this.key, timeSpan, this.buckets, this.opts)
  155. } else {
  156. timing(this.key, timeSpan, this.sampleRate, this.opts)
  157. }
  158. return timeSpan
  159. }
  160. }
  161. function gauge(key, value, sampleRate = 1, opts = {}) {
  162. if (arguments.length === 3 && typeof sampleRate === 'object') {
  163. opts = sampleRate
  164. }
  165. key = buildPromKey(key)
  166. promWrapper
  167. .metric('gauge', key)
  168. .set({ status: opts.status }, sanitizeValue(value))
  169. if (process.env.DEBUG_METRICS) {
  170. console.log('doing gauge', key, opts)
  171. }
  172. }
  173. function globalGauge(key, value, sampleRate = 1, opts = {}) {
  174. key = buildPromKey(key)
  175. promWrapper
  176. .metric('gauge', key)
  177. .set({ host: 'global', status: opts.status }, sanitizeValue(value))
  178. }
  179. function close() {
  180. for (const func of destructors) {
  181. func()
  182. }
  183. }
  184. module.exports.configure = configure
  185. module.exports.initialize = initialize
  186. module.exports.registerDestructor = registerDestructor
  187. module.exports.injectMetricsRoute = injectMetricsRoute
  188. module.exports.buildPromKey = buildPromKey
  189. module.exports.sanitizeValue = sanitizeValue
  190. module.exports.set = set
  191. module.exports.inc = inc
  192. module.exports.count = count
  193. module.exports.summary = summary
  194. module.exports.timing = timing
  195. module.exports.histogram = histogram
  196. module.exports.Timer = Timer
  197. module.exports.gauge = gauge
  198. module.exports.globalGauge = globalGauge
  199. module.exports.close = close
  200. module.exports.prom = promClient
  201. module.exports.register = promWrapper.registry
  202. module.exports.http = require('./http')
  203. module.exports.mongodb = require('./mongodb')
  204. module.exports.open_sockets = require('./open_sockets')
  205. module.exports.event_loop = require('./event_loop')
  206. module.exports.memory = require('./memory')
  207. module.exports.timeAsyncMethod = require('./timeAsyncMethod')