index.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. /**
  23. * Configure the metrics module and start the default metrics collectors and
  24. * profiling agents.
  25. */
  26. function initialize(appName, opts = {}) {
  27. appName = appName || DEFAULT_APP_NAME
  28. if (tracing.tracingEnabled()) {
  29. tracing.initialize(appName)
  30. }
  31. configure({ ...opts, appName })
  32. collectDefaultMetrics({ timeout: 5000, prefix: '' })
  33. promWrapper.setupSweeping()
  34. console.log(`ENABLE_TRACE_AGENT set to ${process.env.ENABLE_TRACE_AGENT}`)
  35. if (process.env.ENABLE_TRACE_AGENT === 'true') {
  36. console.log('starting google trace agent')
  37. const traceAgent = require('@google-cloud/trace-agent')
  38. const traceOpts = { ignoreUrls: [/^\/status/, /^\/health_check/] }
  39. traceAgent.start(traceOpts)
  40. }
  41. console.log(`ENABLE_DEBUG_AGENT set to ${process.env.ENABLE_DEBUG_AGENT}`)
  42. if (process.env.ENABLE_DEBUG_AGENT === 'true') {
  43. console.log('starting google debug agent')
  44. const debugAgent = require('@google-cloud/debug-agent')
  45. debugAgent.start({
  46. allowExpressions: true,
  47. serviceContext: {
  48. service: appName,
  49. version: process.env.BUILD_VERSION,
  50. },
  51. })
  52. }
  53. console.log(`ENABLE_PROFILE_AGENT set to ${process.env.ENABLE_PROFILE_AGENT}`)
  54. if (process.env.ENABLE_PROFILE_AGENT === 'true') {
  55. console.log('starting google profile agent')
  56. const profiler = require('@google-cloud/profiler')
  57. profiler.start({
  58. serviceContext: {
  59. service: appName,
  60. version: process.env.BUILD_VERSION,
  61. },
  62. })
  63. }
  64. inc('process_startup')
  65. }
  66. function registerDestructor(func) {
  67. destructors.push(func)
  68. }
  69. function injectMetricsRoute(app) {
  70. app.get(
  71. '/metrics',
  72. ExpressCompression({
  73. level: parseInt(process.env.METRICS_COMPRESSION_LEVEL || '1', 10),
  74. }),
  75. function (req, res) {
  76. res.set('Content-Type', promWrapper.registry.contentType)
  77. res.end(promWrapper.registry.metrics())
  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, opts = {}) {
  91. if (arguments.length === 2 && typeof sampleRate === 'object') {
  92. opts = sampleRate
  93. }
  94. key = buildPromKey(key)
  95. promWrapper.metric('counter', key).inc(opts)
  96. if (process.env.DEBUG_METRICS) {
  97. console.log('doing inc', key, opts)
  98. }
  99. }
  100. function count(key, count, sampleRate = 1, opts = {}) {
  101. if (arguments.length === 3 && typeof sampleRate === 'object') {
  102. opts = sampleRate
  103. }
  104. key = buildPromKey(key)
  105. promWrapper.metric('counter', key).inc(opts, count)
  106. if (process.env.DEBUG_METRICS) {
  107. console.log('doing count/inc', key, opts)
  108. }
  109. }
  110. function summary(key, value, opts = {}) {
  111. key = buildPromKey(key)
  112. promWrapper.metric('summary', key).observe(opts, value)
  113. if (process.env.DEBUG_METRICS) {
  114. console.log('doing summary', key, value, opts)
  115. }
  116. }
  117. function timing(key, timeSpan, sampleRate = 1, opts = {}) {
  118. if (arguments.length === 3 && typeof sampleRate === 'object') {
  119. opts = sampleRate
  120. }
  121. key = buildPromKey('timer_' + key)
  122. promWrapper.metric('summary', key).observe(opts, timeSpan)
  123. if (process.env.DEBUG_METRICS) {
  124. console.log('doing timing', key, opts)
  125. }
  126. }
  127. function histogram(key, value, buckets, opts = {}) {
  128. key = buildPromKey('histogram_' + key)
  129. promWrapper.metric('histogram', key, buckets).observe(opts, value)
  130. if (process.env.DEBUG_METRICS) {
  131. console.log('doing histogram', key, buckets, opts)
  132. }
  133. }
  134. class Timer {
  135. constructor(key, sampleRate = 1, opts = {}, buckets) {
  136. if (typeof sampleRate === 'object') {
  137. // called with (key, opts, buckets)
  138. if (arguments.length === 3) {
  139. buckets = opts
  140. opts = sampleRate
  141. }
  142. // called with (key, opts)
  143. if (arguments.length === 2) {
  144. opts = 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.opts = opts
  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.opts)
  159. } else {
  160. timing(this.key, timeSpan, this.sampleRate, this.opts)
  161. }
  162. return timeSpan
  163. }
  164. }
  165. function gauge(key, value, sampleRate = 1, opts = {}) {
  166. if (arguments.length === 3 && typeof sampleRate === 'object') {
  167. opts = sampleRate
  168. }
  169. key = buildPromKey(key)
  170. promWrapper
  171. .metric('gauge', key)
  172. .set({ status: opts.status }, sanitizeValue(value))
  173. if (process.env.DEBUG_METRICS) {
  174. console.log('doing gauge', key, opts)
  175. }
  176. }
  177. function globalGauge(key, value, sampleRate = 1, opts = {}) {
  178. key = buildPromKey(key)
  179. promWrapper
  180. .metric('gauge', key)
  181. .set({ host: 'global', status: opts.status }, sanitizeValue(value))
  182. }
  183. function close() {
  184. for (const func of destructors) {
  185. func()
  186. }
  187. }
  188. module.exports.configure = configure
  189. module.exports.initialize = initialize
  190. module.exports.registerDestructor = registerDestructor
  191. module.exports.injectMetricsRoute = injectMetricsRoute
  192. module.exports.buildPromKey = buildPromKey
  193. module.exports.sanitizeValue = sanitizeValue
  194. module.exports.set = set
  195. module.exports.inc = inc
  196. module.exports.count = count
  197. module.exports.summary = summary
  198. module.exports.timing = timing
  199. module.exports.histogram = histogram
  200. module.exports.Timer = Timer
  201. module.exports.gauge = gauge
  202. module.exports.globalGauge = globalGauge
  203. module.exports.close = close
  204. module.exports.prom = promClient
  205. module.exports.register = promWrapper.registry
  206. module.exports.http = require('./http')
  207. module.exports.mongodb = require('./mongodb')
  208. module.exports.open_sockets = require('./open_sockets')
  209. module.exports.event_loop = require('./event_loop')
  210. module.exports.memory = require('./memory')
  211. module.exports.timeAsyncMethod = require('./timeAsyncMethod')