Class: PrometheusExporter::Server::WebServer

Inherits:
Object
  • Object
show all
Defined in:
lib/prometheus_exporter/server/web_server.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ WebServer

Returns a new instance of WebServer.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/prometheus_exporter/server/web_server.rb', line 12

def initialize(opts)
  @port = opts[:port] || PrometheusExporter::DEFAULT_PORT
  @bind = opts[:bind] || PrometheusExporter::DEFAULT_BIND_ADDRESS
  @collector = opts[:collector] || Collector.new
  @timeout = opts[:timeout] || PrometheusExporter::DEFAULT_TIMEOUT
  @verbose = opts[:verbose] || false
  @auth = opts[:auth]
  @realm = opts[:realm] || PrometheusExporter::DEFAULT_REALM

  @metrics_total =
    PrometheusExporter::Metric::Counter.new(
      "collector_metrics_total",
      "Total metrics processed by exporter web.",
    )

  @sessions_total =
    PrometheusExporter::Metric::Counter.new(
      "collector_sessions_total",
      "Total send_metric sessions processed by exporter web.",
    )

  @bad_metrics_total =
    PrometheusExporter::Metric::Counter.new(
      "collector_bad_metrics_total",
      "Total mis-handled metrics by collector.",
    )

  @metrics_total.observe(0)
  @sessions_total.observe(0)
  @bad_metrics_total.observe(0)

  @access_log, @logger = nil
  log_target = opts[:log_target]

  if @verbose
    @access_log = [
      [$stderr, WEBrick::AccessLog::COMMON_LOG_FORMAT],
      [$stderr, WEBrick::AccessLog::REFERER_LOG_FORMAT],
    ]
    @logger = WEBrick::Log.new(log_target || $stderr)
  else
    @access_log = []
    @logger = WEBrick::Log.new(log_target || "/dev/null")
  end

  @logger.info "Using Basic Authentication via #{@auth}" if @verbose && @auth

  if %w[ALL ANY].include?(@bind)
    @logger.info "Listening on both 0.0.0.0/:: network interfaces"
    @bind = nil
  end

  @server =
    WEBrick::HTTPServer.new(
      Port: @port,
      BindAddress: @bind,
      Logger: @logger,
      AccessLog: @access_log,
    )

  @server.mount_proc "/" do |req, res|
    res["Content-Type"] = "text/plain; charset=utf-8"
    if req.path == "/metrics"
      authenticate(req, res) if @auth

      res.status = 200
      if req.header["accept-encoding"].to_s.include?("gzip")
        sio = StringIO.new
        collected_metrics = metrics
        begin
          writer = Zlib::GzipWriter.new(sio)
          writer.write(collected_metrics)
        ensure
          writer.close
        end
        res.body = sio.string
        res.header["content-encoding"] = "gzip"
      else
        res.body = metrics
      end
    elsif req.path == "/send-metrics"
      handle_metrics(req, res)
    elsif req.path == "/ping"
      res.body = "PONG"
    else
      res.status = 404
      res.body =
        "Not Found! The Prometheus Ruby Exporter only listens on /ping, /metrics and /send-metrics"
    end
  end
end

Instance Attribute Details

#collectorObject (readonly)

Returns the value of attribute collector.



10
11
12
# File 'lib/prometheus_exporter/server/web_server.rb', line 10

def collector
  @collector
end

Instance Method Details

#add_gauge(name, help, value) ⇒ Object



182
183
184
185
186
# File 'lib/prometheus_exporter/server/web_server.rb', line 182

def add_gauge(name, help, value)
  gauge = PrometheusExporter::Metric::Gauge.new(name, help)
  gauge.observe(value)
  gauge
end

#authenticate(req, res) ⇒ Object



188
189
190
191
192
193
194
# File 'lib/prometheus_exporter/server/web_server.rb', line 188

def authenticate(req, res)
  htpasswd = WEBrick::HTTPAuth::Htpasswd.new(@auth)
  basic_auth =
    WEBrick::HTTPAuth::BasicAuth.new({ Realm: @realm, UserDB: htpasswd, Logger: @logger })

  basic_auth.authenticate(req, res)
end

#get_rssObject



167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/prometheus_exporter/server/web_server.rb', line 167

def get_rss
  @pagesize ||=
    begin
      `getconf PAGESIZE`.to_i
    rescue StandardError
      4096
    end
  @pid ||= Process.pid
  begin
    File.read("/proc/#{@pid}/statm").split(" ")[1].to_i * @pagesize
  rescue StandardError
    0
  end
end

#handle_metrics(req, res) ⇒ Object



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/prometheus_exporter/server/web_server.rb', line 104

def handle_metrics(req, res)
  @sessions_total.observe
  req.body do |block|
    begin
      @metrics_total.observe
      @collector.process(block)
    rescue => e
      @logger.error "\n\n#{e.inspect}\n#{e.backtrace}\n\n" if @verbose
      @bad_metrics_total.observe
      res.body = "Bad Metrics #{e}"
      res.status = e.respond_to?(:status_code) ? e.status_code : 500
      break
    end
  end

  res.body = "OK"
  res.status = 200
end

#metricsObject



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/prometheus_exporter/server/web_server.rb', line 138

def metrics
  metric_text = nil
  begin
    Timeout.timeout(@timeout) { metric_text = @collector.prometheus_metrics_text }
  rescue Timeout::Error
    # we timed out ... bummer
    @logger.error "Generating Prometheus metrics text timed out"
  end

  metrics = []

  metrics << add_gauge(
    "collector_working",
    "Is the master process collector able to collect metrics",
    metric_text && metric_text.length > 0 ? 1 : 0,
  )

  metrics << add_gauge("collector_rss", "total memory used by collector process", get_rss)

  metrics << @metrics_total
  metrics << @sessions_total
  metrics << @bad_metrics_total

  <<~TEXT
  #{metrics.map(&:to_prometheus_text).join("\n\n")}
  #{metric_text}
  TEXT
end

#startObject



123
124
125
126
127
128
129
130
131
132
# File 'lib/prometheus_exporter/server/web_server.rb', line 123

def start
  @runner ||=
    Thread.start do
      begin
        @server.start
      rescue => e
        @logger.error "Failed to start prometheus collector web on port #{@port}: #{e}"
      end
    end
end

#stopObject



134
135
136
# File 'lib/prometheus_exporter/server/web_server.rb', line 134

def stop
  @server.shutdown
end