index.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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_DEBUG_AGENT set to ${process.env.ENABLE_DEBUG_AGENT}`)
  46. if (process.env.ENABLE_DEBUG_AGENT === 'true') {
  47. console.log('starting google debug agent')
  48. const debugAgent = require('@google-cloud/debug-agent')
  49. debugAgent.start({
  50. allowExpressions: true,
  51. serviceContext: {
  52. service: appName,
  53. version: process.env.BUILD_VERSION,
  54. },
  55. })
  56. }
  57. console.log(`ENABLE_PROFILE_AGENT set to ${process.env.ENABLE_PROFILE_AGENT}`)
  58. if (process.env.ENABLE_PROFILE_AGENT === 'true') {
  59. console.log('starting google profile agent')
  60. const profiler = require('@google-cloud/profiler')
  61. profiler.start({
  62. serviceContext: {
  63. service: appName,
  64. version: process.env.BUILD_VERSION,
  65. },
  66. })
  67. }
  68. inc('process_startup')
  69. initialized = true
  70. }
  71. function registerDestructor(func) {
  72. destructors.push(func)
  73. }
  74. function injectMetricsRoute(app) {
  75. app.get(
  76. '/metrics',
  77. ExpressCompression({
  78. level: parseInt(process.env.METRICS_COMPRESSION_LEVEL || '1', 10),
  79. }),
  80. function (req, res, next) {
  81. res.set('Content-Type', promWrapper.registry.contentType)
  82. promWrapper.registry
  83. .metrics()
  84. .then(metrics => {
  85. res.end(metrics)
  86. })
  87. .catch(err => {
  88. next(err)
  89. })
  90. }
  91. )
  92. }
  93. function buildPromKey(key) {
  94. return key.replace(/[^a-zA-Z0-9]/g, '_')
  95. }
  96. function sanitizeValue(value) {
  97. return parseFloat(value)
  98. }
  99. function set(key, value, sampleRate = 1) {
  100. console.log('counts are not currently supported')
  101. }
  102. function inc(key, sampleRate = 1, labels = {}) {
  103. if (arguments.length === 2 && typeof sampleRate === 'object') {
  104. labels = sampleRate
  105. }
  106. key = buildPromKey(key)
  107. promWrapper.metric('counter', key, labels).inc(labels)
  108. if (process.env.DEBUG_METRICS) {
  109. console.log('doing inc', key, labels)
  110. }
  111. }
  112. function count(key, count, sampleRate = 1, labels = {}) {
  113. if (arguments.length === 3 && typeof sampleRate === 'object') {
  114. labels = sampleRate
  115. }
  116. key = buildPromKey(key)
  117. promWrapper.metric('counter', key, labels).inc(labels, count)
  118. if (process.env.DEBUG_METRICS) {
  119. console.log('doing count/inc', key, labels)
  120. }
  121. }
  122. function summary(key, value, labels = {}) {
  123. key = buildPromKey(key)
  124. promWrapper.metric('summary', key, labels).observe(labels, value)
  125. if (process.env.DEBUG_METRICS) {
  126. console.log('doing summary', key, value, labels)
  127. }
  128. }
  129. function timing(key, timeSpan, sampleRate = 1, labels = {}) {
  130. if (arguments.length === 3 && typeof sampleRate === 'object') {
  131. labels = sampleRate
  132. }
  133. key = buildPromKey('timer_' + key)
  134. promWrapper.metric('summary', key, labels).observe(labels, timeSpan)
  135. if (process.env.DEBUG_METRICS) {
  136. console.log('doing timing', key, labels)
  137. }
  138. }
  139. function histogram(key, value, buckets, labels = {}) {
  140. key = buildPromKey('histogram_' + key)
  141. promWrapper.metric('histogram', key, labels, buckets).observe(labels, value)
  142. if (process.env.DEBUG_METRICS) {
  143. console.log('doing histogram', key, buckets, labels)
  144. }
  145. }
  146. class Timer {
  147. constructor(key, sampleRate = 1, labels = {}, buckets) {
  148. if (typeof sampleRate === 'object') {
  149. // called with (key, labels, buckets)
  150. if (arguments.length === 3) {
  151. buckets = labels
  152. labels = sampleRate
  153. }
  154. // called with (key, labels)
  155. if (arguments.length === 2) {
  156. labels = sampleRate
  157. }
  158. sampleRate = 1 // default value to pass to timing function
  159. }
  160. this.start = new Date()
  161. key = buildPromKey(key)
  162. this.key = key
  163. this.sampleRate = sampleRate
  164. this.labels = labels
  165. this.buckets = buckets
  166. }
  167. done() {
  168. const timeSpan = new Date() - this.start
  169. if (this.buckets) {
  170. histogram(this.key, timeSpan, this.buckets, this.labels)
  171. } else {
  172. timing(this.key, timeSpan, this.sampleRate, this.labels)
  173. }
  174. return timeSpan
  175. }
  176. }
  177. function gauge(key, value, sampleRate = 1, labels = {}) {
  178. if (arguments.length === 3 && typeof sampleRate === 'object') {
  179. labels = sampleRate
  180. }
  181. key = buildPromKey(key)
  182. promWrapper.metric('gauge', key, labels).set(labels, sanitizeValue(value))
  183. if (process.env.DEBUG_METRICS) {
  184. console.log('doing gauge', key, labels)
  185. }
  186. }
  187. function globalGauge(key, value, sampleRate = 1, labels = {}) {
  188. key = buildPromKey(key)
  189. labels = { host: 'global', ...labels }
  190. promWrapper.metric('gauge', key, labels).set(labels, sanitizeValue(value))
  191. }
  192. function close() {
  193. for (const func of destructors) {
  194. func()
  195. }
  196. }
  197. module.exports.configure = configure
  198. module.exports.initialize = initialize
  199. module.exports.registerDestructor = registerDestructor
  200. module.exports.injectMetricsRoute = injectMetricsRoute
  201. module.exports.buildPromKey = buildPromKey
  202. module.exports.sanitizeValue = sanitizeValue
  203. module.exports.set = set
  204. module.exports.inc = inc
  205. module.exports.count = count
  206. module.exports.summary = summary
  207. module.exports.timing = timing
  208. module.exports.histogram = histogram
  209. module.exports.Timer = Timer
  210. module.exports.gauge = gauge
  211. module.exports.globalGauge = globalGauge
  212. module.exports.close = close
  213. module.exports.prom = promClient
  214. module.exports.register = promWrapper.registry
  215. module.exports.http = require('./http')
  216. module.exports.open_sockets = require('./open_sockets')
  217. module.exports.event_loop = require('./event_loop')
  218. module.exports.memory = require('./memory')
  219. module.exports.timeAsyncMethod = require('./timeAsyncMethod')