Class: Yabeda::Prometheus::Exporter

Inherits:
Prometheus::Middleware::Exporter
  • Object
show all
Defined in:
lib/yabeda/prometheus/exporter.rb

Overview

Rack application or middleware that provides metrics exposition endpoint

Constant Summary collapse

NOT_FOUND_HANDLER =
lambda do |_env|
  [404, { "Content-Type" => "text/plain" }, ["Not Found\n"]]
end.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Exporter

Returns a new instance of Exporter.



57
58
59
# File 'lib/yabeda/prometheus/exporter.rb', line 57

def initialize(app, options = {})
  super(app, options.merge(registry: Yabeda::Prometheus.registry))
end

Class Method Details

.call(env) ⇒ Object

Allows to use middleware as standalone rack application



16
17
18
19
20
# File 'lib/yabeda/prometheus/exporter.rb', line 16

def call(env)
  options = env.fetch("action_dispatch.request.path_parameters", {})
  @app ||= new(NOT_FOUND_HANDLER, path: "/", **options)
  @app.call(env)
end

.rack_app(exporter = self, logger: Logger.new(IO::NULL), use_deflater: true, **exporter_options) ⇒ Object



34
35
36
37
38
39
40
41
42
# File 'lib/yabeda/prometheus/exporter.rb', line 34

def rack_app(exporter = self, logger: Logger.new(IO::NULL), use_deflater: true, **exporter_options)
  ::Rack::Builder.new do
    use ::Rack::Deflater if use_deflater
    use ::Rack::CommonLogger, logger
    use ::Rack::ShowExceptions
    use exporter, **exporter_options
    run NOT_FOUND_HANDLER
  end
end

.rack_handlerObject



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/yabeda/prometheus/exporter.rb', line 44

def rack_handler
  if Gem.loaded_specs['rack']&.version&.>= Gem::Version.new('3.0')
    require 'rackup'
    ::Rackup::Handler::WEBrick
  else
    ::Rack::Handler::WEBrick
  end
rescue LoadError
  warn 'Please add gems rackup and webrick to your Gemfile to expose Yabeda metrics from prometheus-mmap'
  ::Rack::Handler::WEBrick
end

.start_metrics_server!(**rack_app_options) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/yabeda/prometheus/exporter.rb', line 22

def start_metrics_server!(**rack_app_options)
  Thread.new do
    default_port = ENV.fetch("PORT", 9394)
    rack_handler.run(
      rack_app(**rack_app_options),
      Host: ENV["PROMETHEUS_EXPORTER_BIND"] || "0.0.0.0",
      Port: ENV.fetch("PROMETHEUS_EXPORTER_PORT", default_port),
      AccessLog: [],
    )
  end
end

Instance Method Details

#call(env) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/yabeda/prometheus/exporter.rb', line 61

def call(env)
  ::Yabeda.collect! if env["PATH_INFO"] == path

  if ::Yabeda.debug?
    result = nil
    ::Yabeda.prometheus_exporter.render_duration.measure({}) do
      result = super
    end
    result
  else
    super
  end
end