prometheus_exporter 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 362c40e8c1a1b79fa0c634b1816d4492d62154473a7ea2bf60e802cd32c3ee7c
4
+ data.tar.gz: 292cd4d3c8a9ef912c446a538ad85b9bed22dcb11be9249c0fb070ea90e5f082
5
+ SHA512:
6
+ metadata.gz: 48ab74ff7260056c52e201815498e0f5fe1ee8ed1b5b193b27cbc834c7027c2ad70ca9119577f8a79697ec8c9630ba766b16efa55e90a046049a31da3d7849aa
7
+ data.tar.gz: ef969b551b407de7b4f7906c8275424e57947b2976e9b421f0abe29cba338b6e760f230cd0401d6039f42a827af1c5d40801461b884bf795e7e8e7db1576d438
data/.gitignore ADDED
@@ -0,0 +1,8 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
data/.rubocop.yml ADDED
@@ -0,0 +1,113 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.4
3
+ DisabledByDefault: true
4
+ Exclude:
5
+ - 'db/schema.rb'
6
+ - 'bundle/**/*'
7
+ - 'vendor/**/*'
8
+ - 'node_modules/**/*'
9
+ - 'public/**/*'
10
+
11
+ # Prefer &&/|| over and/or.
12
+ Style/AndOr:
13
+ Enabled: true
14
+
15
+ # Do not use braces for hash literals when they are the last argument of a
16
+ # method call.
17
+ Style/BracesAroundHashParameters:
18
+ Enabled: true
19
+
20
+ # Align `when` with `case`.
21
+ Layout/CaseIndentation:
22
+ Enabled: true
23
+
24
+ # Align comments with method definitions.
25
+ Layout/CommentIndentation:
26
+ Enabled: true
27
+
28
+ # No extra empty lines.
29
+ Layout/EmptyLines:
30
+ Enabled: true
31
+
32
+ # Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }.
33
+ Style/HashSyntax:
34
+ Enabled: true
35
+
36
+ # Two spaces, no tabs (for indentation).
37
+ Layout/IndentationWidth:
38
+ Enabled: true
39
+
40
+ Layout/SpaceAfterColon:
41
+ Enabled: true
42
+
43
+ Layout/SpaceAfterComma:
44
+ Enabled: true
45
+
46
+ Layout/SpaceAroundEqualsInParameterDefault:
47
+ Enabled: true
48
+
49
+ Layout/SpaceAroundKeyword:
50
+ Enabled: true
51
+
52
+ Layout/SpaceAroundOperators:
53
+ Enabled: true
54
+
55
+ Layout/SpaceBeforeFirstArg:
56
+ Enabled: true
57
+
58
+ # Defining a method with parameters needs parentheses.
59
+ Style/MethodDefParentheses:
60
+ Enabled: true
61
+
62
+ # Use `foo {}` not `foo{}`.
63
+ Layout/SpaceBeforeBlockBraces:
64
+ Enabled: true
65
+
66
+ # Use `foo { bar }` not `foo {bar}`.
67
+ Layout/SpaceInsideBlockBraces:
68
+ Enabled: true
69
+
70
+ # Use `{ a: 1 }` not `{a:1}`.
71
+ Layout/SpaceInsideHashLiteralBraces:
72
+ Enabled: true
73
+
74
+ Layout/SpaceInsideParens:
75
+ Enabled: true
76
+
77
+ # Detect hard tabs, no hard tabs.
78
+ Layout/Tab:
79
+ Enabled: true
80
+
81
+ # Blank lines should not have any spaces.
82
+ Layout/TrailingBlankLines:
83
+ Enabled: true
84
+
85
+ # No trailing whitespace.
86
+ Layout/TrailingWhitespace:
87
+ Enabled: true
88
+
89
+ Lint/Debugger:
90
+ Enabled: true
91
+
92
+ Lint/BlockAlignment:
93
+ Enabled: true
94
+
95
+ # Align `end` with the matching keyword or starting expression except for
96
+ # assignments, where it should be aligned with the LHS.
97
+ Lint/EndAlignment:
98
+ Enabled: true
99
+ EnforcedStyleAlignWith: variable
100
+
101
+ # Use my_method(my_arg) not my_method( my_arg ) or my_method my_arg.
102
+ Lint/RequireParentheses:
103
+ Enabled: true
104
+
105
+ Layout/MultilineMethodCallIndentation:
106
+ Enabled: true
107
+ EnforcedStyle: indented
108
+
109
+ Layout/AlignHash:
110
+ Enabled: true
111
+
112
+ Bundler/OrderedGems:
113
+ Enabled: false
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.5.0
5
+ before_install: gem install bundler -v 1.16.1
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at sam.saffron@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in prometheus_exporter.gemspec
6
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,59 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ prometheus_exporter (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ coderay (1.1.2)
10
+ ffi (1.9.18)
11
+ formatador (0.2.5)
12
+ guard (2.14.2)
13
+ formatador (>= 0.2.4)
14
+ listen (>= 2.7, < 4.0)
15
+ lumberjack (>= 1.0.12, < 2.0)
16
+ nenv (~> 0.1)
17
+ notiffany (~> 0.0)
18
+ pry (>= 0.9.12)
19
+ shellany (~> 0.0)
20
+ thor (>= 0.18.1)
21
+ guard-compat (1.2.1)
22
+ guard-minitest (2.4.6)
23
+ guard-compat (~> 1.2)
24
+ minitest (>= 3.0)
25
+ listen (3.1.5)
26
+ rb-fsevent (~> 0.9, >= 0.9.4)
27
+ rb-inotify (~> 0.9, >= 0.9.7)
28
+ ruby_dep (~> 1.2)
29
+ lumberjack (1.0.12)
30
+ method_source (0.9.0)
31
+ minitest (5.11.1)
32
+ nenv (0.3.0)
33
+ notiffany (0.1.1)
34
+ nenv (~> 0.1)
35
+ shellany (~> 0.0)
36
+ pry (0.11.3)
37
+ coderay (~> 1.1.0)
38
+ method_source (~> 0.9.0)
39
+ rake (10.5.0)
40
+ rb-fsevent (0.10.2)
41
+ rb-inotify (0.9.10)
42
+ ffi (>= 0.5.0, < 2)
43
+ ruby_dep (1.5.0)
44
+ shellany (0.0.1)
45
+ thor (0.20.0)
46
+
47
+ PLATFORMS
48
+ ruby
49
+
50
+ DEPENDENCIES
51
+ bundler (~> 1.16)
52
+ guard (~> 2.0)
53
+ guard-minitest (~> 2.0)
54
+ minitest (~> 5.0)
55
+ prometheus_exporter!
56
+ rake (~> 10.0)
57
+
58
+ BUNDLED WITH
59
+ 1.16.1
data/Guardfile ADDED
@@ -0,0 +1,7 @@
1
+ guard :minitest do
2
+ # with Minitest::Unit
3
+ watch(%r{^test/(.*)\/?(.*)_test\.rb$})
4
+ watch(%r{^lib/prometheus_exporter/(.*/)?([^/]+)\.rb$}) { |m| "test/#{m[1]}#{m[2]}_test.rb" }
5
+ watch(%r{^test/test_helper\.rb$}) { 'test' }
6
+ end
7
+
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 Discourse
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,188 @@
1
+ # Prometheus Exporter
2
+
3
+ Prometheus Exporter allows you to aggregate custom metrics from multiple processes and export to Prometheus.
4
+
5
+ It provides a very flexible framework for handling Prometheus metrics and can operate in a single and multiprocess mode.
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'prometheus_exporter'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install prometheus_exporter
22
+
23
+ ## Usage
24
+
25
+ ### Single process mode
26
+
27
+ Simplest way of consuming Prometheus exporter is in a single process mode, to do so:
28
+
29
+ ```ruby
30
+ require 'prometheus_exporter/server'
31
+
32
+ # port is the port that will provide the /metrics route
33
+ server = PrometheusExporter::Server::WebServer.new port: 12345
34
+ server.start
35
+
36
+ gauge = PrometheusExporter::Metric::Gauge.new("rss", "used RSS for process")
37
+ counter = PrometheusExporter::Metric::Counter.new("web_requests", "number of web requests")
38
+ summary = PrometheusExporter::Metric::Summary.new("page_load_time", "time it took to load page")
39
+
40
+ server.collector.register_metric(gauge)
41
+ server.collector.register_metric(counter)
42
+ server.collector.register_metric(summary)
43
+
44
+ gauge.observe(get_rss)
45
+ gauge.observe(get_rss)
46
+
47
+ counter.observe(1, route: 'test/route')
48
+ counter.observe(1, route: 'another/route')
49
+
50
+ summary.observe(1.1)
51
+ summary.observe(1.12)
52
+ summary.observe(0.12)
53
+
54
+ # http://localhost:12345/metrics now returns all your metrics
55
+
56
+ ```
57
+
58
+ ### Multi process mode
59
+
60
+ In some cases, for example unicorn or puma clusters you may want to aggregate metrics across multiple processes.
61
+
62
+ Simplest way to acheive this is use the built-in collector.
63
+
64
+ First, run an exporter on your desired port:
65
+
66
+ ```
67
+ # prometheus_exporter 12345
68
+ ```
69
+
70
+ At this point an exporter is running on port 12345
71
+
72
+ In your application:
73
+
74
+ ```ruby
75
+ require 'prometheus_exporter/client'
76
+
77
+ client = PrometheusExporter::Client.new(host: 'localhost', port: 12345)
78
+ gauge = client.register(:gauge, "awesome", "amount of awesome")
79
+
80
+ gauge.observe(10)
81
+ gauge.observe(99, day: "friday")
82
+
83
+ ```
84
+
85
+ Then you will get the metrics:
86
+
87
+ ```bash
88
+ % curl localhost:12345/metrics
89
+ # HELP collector_working Is the master process collector able to collect metrics
90
+ # TYPE collector_working gauge
91
+ collector_working 1
92
+
93
+ # HELP awesome amount of awesome
94
+ # TYPE awesome gauge
95
+ awesome{day="friday"} 99
96
+ awesome 10
97
+
98
+ ```
99
+
100
+ ### Multi process mode with custom collector
101
+
102
+ You can opt for custom collector logic in a multi process environment.
103
+
104
+ This allows you better control over the amount of data transported over HTTP and also allow you to introduce custom logic into your centralized collector.
105
+
106
+ The standard collector ships "help", "type" and "name" for every metric, in some cases you may want to avoid sending all that data.
107
+
108
+ First, define a custom collector, it is critical you inherit off `PrometheusExporter::Server::Collector`, also it is critical you have custom implementations for #process and #prometheus_metrics_text
109
+
110
+ ```ruby
111
+ class MyCustomCollector < PrometheusExporter::Server::Collector
112
+ def initialize
113
+ @gauge1 = PrometheusExporter::Metric::Gauge.new("thing1", "I am thing 1")
114
+ @gauge2 = PrometheusExporter::Metric::Gauge.new("thing2", "I am thing 2")
115
+ @mutex = Mutex.new
116
+ end
117
+
118
+ def process(obj)
119
+ @mutex.synchronize do
120
+ if thing1 = obj["thing1"]
121
+ @gauge1.observe(thing1)
122
+ end
123
+
124
+ if thing2 = obj["thing2"]
125
+ @gauge2.observe(thing2)
126
+ end
127
+ end
128
+ end
129
+
130
+ def prometheus_metrics_text
131
+ @mutex.synchronize do
132
+ "#{@gauge1.to_prometheus_text}\n#{@gauge2.to_prometheus_text}"
133
+ end
134
+ end
135
+ end
136
+ ```
137
+
138
+ Next, launch the exporter process:
139
+
140
+ ```bash
141
+ % bin/prometheus_exporter 12345 --collector examples/custom_collector.rb
142
+ ```
143
+
144
+ In your application ship it the metrics you want:
145
+
146
+ ```ruby
147
+ require 'prometheus_exporter/client'
148
+
149
+ client = PrometheusExporter::Client.new(host: 'localhost', port: 12345)
150
+ client.send(thing1: 122)
151
+ client.send(thing2: 12)
152
+ ```
153
+
154
+ Now your exporter will echo the metrics:
155
+
156
+ ```
157
+ % curl localhost:12345/metrics
158
+ # HELP collector_working Is the master process collector able to collect metrics
159
+ # TYPE collector_working gauge
160
+ collector_working 1
161
+
162
+ # HELP thing1 I am thing 1
163
+ # TYPE thing1 gauge
164
+ thing1 122
165
+
166
+ # HELP thing2 I am thing 2
167
+ # TYPE thing2 gauge
168
+ thing2 12
169
+ ```
170
+
171
+
172
+ ## Transport concerns
173
+
174
+ Prometheus Exporter handles transport using a simple HTTP protocol. In multi process mode we avoid needing a large number of HTTP request by using chunked encoding to send metrics. This means that a single HTTP channel can deliver 100s or even 1000s of metrics over a single HTTP session to the `/send-metrics` endpoint.
175
+
176
+ When sending data to `send-metrics` we always serialize the data for the chunk to a JSON string, and deserialize it back into an Object before handing the data to the collector.
177
+
178
+ ## Contributing
179
+
180
+ Bug reports and pull requests are welcome on GitHub at https://github.com/discourse/prometheus_exporter. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
181
+
182
+ ## License
183
+
184
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
185
+
186
+ ## Code of Conduct
187
+
188
+ Everyone interacting in the PrometheusExporter project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/SamSaffron/prometheus_exporter/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList["test/**/*_test.rb"]
8
+ end
9
+
10
+ task :default => :test
@@ -0,0 +1,25 @@
1
+ class MyCustomCollector < PrometheusExporter::Server::Collector
2
+ def initialize
3
+ @gauge1 = PrometheusExporter::Metric::Gauge.new("thing1", "I am thing 1")
4
+ @gauge2 = PrometheusExporter::Metric::Gauge.new("thing2", "I am thing 2")
5
+ @mutex = Mutex.new
6
+ end
7
+
8
+ def process(obj)
9
+ @mutex.synchronize do
10
+ if thing1 = obj["thing1"]
11
+ @gauge1.observe(thing1)
12
+ end
13
+
14
+ if thing2 = obj["thing2"]
15
+ @gauge2.observe(thing2)
16
+ end
17
+ end
18
+ end
19
+
20
+ def prometheus_metrics_text
21
+ @mutex.synchronize do
22
+ "#{@gauge1.to_prometheus_text}\n#{@gauge2.to_prometheus_text}"
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,164 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'socket'
5
+ require 'thread'
6
+
7
+ class PrometheusExporter::Client
8
+
9
+ class RemoteMetric
10
+ def initialize(name:, help:, type:, client:)
11
+ @name = name
12
+ @help = help
13
+ @client = client
14
+ @type = type
15
+ end
16
+
17
+ def observe(value = 1, keys = nil)
18
+ @client.send(
19
+ type: @type,
20
+ help: @help,
21
+ name: @name,
22
+ keys: keys,
23
+ value: value
24
+ )
25
+ end
26
+ end
27
+
28
+ MAX_SOCKET_AGE = 25
29
+ MAX_QUEUE_SIZE = 10_000
30
+
31
+ def initialize(host:, port:, max_queue_size: nil, thread_sleep: 0.5)
32
+ @metrics = []
33
+
34
+ @queue = Queue.new
35
+ @socket = nil
36
+ @socket_started = nil
37
+
38
+ max_queue_size ||= MAX_QUEUE_SIZE
39
+ max_queue_size = max_queue_size.to_i
40
+
41
+ if max_queue_size.to_i <= 0
42
+ raise ArgumentError, "max_queue_size must be larger than 0"
43
+ end
44
+
45
+ @max_queue_size = max_queue_size
46
+ @host = host
47
+ @port = port
48
+ @worker_thread = nil
49
+ @mutex = Mutex.new
50
+ @thread_sleep = thread_sleep
51
+ end
52
+
53
+ def register(type, name, help)
54
+ metric = RemoteMetric.new(type: type, name: name, help: help, client: self)
55
+ @metrics << metric
56
+ metric
57
+ end
58
+
59
+ def send(obj)
60
+ @queue << obj.to_json
61
+ if @queue.length > @max_queue_size
62
+ STDERR.puts "Prometheus Exporter client is dropping message cause queue is full"
63
+ @queue.pop
64
+ end
65
+
66
+ ensure_worker_thread!
67
+ end
68
+
69
+ def process_queue
70
+ while @queue.length > 0
71
+ ensure_socket!
72
+
73
+ begin
74
+ message = @queue.pop
75
+ @socket.write(message.bytesize.to_s(16).upcase)
76
+ @socket.write("\r\n")
77
+ @socket.write(message)
78
+ @socket.write("\r\n")
79
+ rescue => e
80
+ STDERR.puts "Prometheus Exporter is dropping a message: #{e}"
81
+ @socket = nil
82
+ raise
83
+ end
84
+ end
85
+ end
86
+
87
+ def stop
88
+ @mutex.synchronize do
89
+ @worker_thread&.kill
90
+ while @worker_thread.alive?
91
+ sleep 0.001
92
+ end
93
+ @worker_thread = nil
94
+ end
95
+
96
+ close_socket!
97
+ end
98
+
99
+ private
100
+
101
+ def worker_loop
102
+ close_socket_if_old!
103
+ process_queue
104
+ sleep @thread_sleep
105
+ rescue => e
106
+ STDERR.puts "Prometheus Exporter, failed to send message #{e}"
107
+ end
108
+
109
+ def ensure_worker_thread!
110
+ unless @worker_thread&.alive?
111
+ @mutex.synchronize do
112
+ return if @worker_thread&.alive?
113
+
114
+ @worker_thread = Thread.new do
115
+ while true
116
+ worker_loop
117
+ end
118
+ end
119
+ end
120
+ end
121
+ end
122
+
123
+ def close_socket!
124
+ begin
125
+ if @socket
126
+ @socket.write("0\r\n")
127
+ @socket.write("\r\n")
128
+ @socket.flush
129
+ @socket.close
130
+ end
131
+ rescue Errno::EPIPE
132
+ end
133
+
134
+ @socket = nil
135
+ @socket_started = nil
136
+ end
137
+
138
+ def close_socket_if_old!
139
+ if @socket && ((@socket_started + MAX_SOCKET_AGE) > Time.now.to_f)
140
+ close_socket!
141
+ end
142
+ end
143
+
144
+ def ensure_socket!
145
+ close_socket_if_old!
146
+
147
+ @socket = TCPSocket.new @host, @port
148
+
149
+ @socket.write("POST /send-metrics HTTP/1.1\r\n")
150
+ @socket.write("Transfer-Encoding: chunked\r\n")
151
+ @socket.write("Connection: Close\r\n")
152
+ @socket.write("Content-Type: application/octet-stream\r\n")
153
+ @socket.write("\r\n")
154
+
155
+ @socket_started = Time.now.to_f
156
+
157
+ nil
158
+ rescue
159
+ @socket = nil
160
+ @socket_started = nil
161
+ raise
162
+ end
163
+
164
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PrometheusExporter::Metric
4
+ class Base
5
+ # prefix applied to all metrics
6
+ def self.default_prefix=(name)
7
+ @default_prefix = name
8
+ end
9
+
10
+ def self.default_prefix
11
+ @default_prefix.to_s
12
+ end
13
+
14
+ attr_accessor :help, :name, :data
15
+
16
+ def initialize(name, help)
17
+ @name = name
18
+ @help = help
19
+ end
20
+
21
+ def type
22
+ raise "Not implemented"
23
+ end
24
+
25
+ def metric_text
26
+ raise "Not implemented"
27
+ end
28
+
29
+ def from_json(json)
30
+ json = JSON.parse(json) if String === json
31
+ @name = json["name"]
32
+ @help = json["help"]
33
+ @data = json["data"]
34
+ if Hash === json["data"]
35
+ @data = {}
36
+ json["data"].each do |k, v|
37
+ k = JSON.parse(k)
38
+ k = Hash[k.map { |k1, v1| [k1.to_sym, v1] }]
39
+ @data[k] = v
40
+ end
41
+ end
42
+ end
43
+
44
+ def prefix(name)
45
+ Base.default_prefix + name
46
+ end
47
+
48
+ def labels_text(labels)
49
+ if labels && labels.length > 0
50
+ s = labels.map do |key, value|
51
+ "#{key}=\"#{value}\""
52
+ end.join(",")
53
+ "{#{s}}"
54
+ end
55
+ end
56
+
57
+ def to_prometheus_text
58
+ <<~TEXT
59
+ # HELP #{prefix(name)} #{help}
60
+ # TYPE #{prefix(name)} #{type}
61
+ #{metric_text}
62
+ TEXT
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PrometheusExporter::Metric
4
+ class Counter < Base
5
+ attr_reader :data
6
+
7
+ def initialize(name, help)
8
+ super
9
+ @data = {}
10
+ end
11
+
12
+ def type
13
+ "counter"
14
+ end
15
+
16
+ def metric_text
17
+ @data.map do |labels, value|
18
+ "#{prefix(@name)}#{labels_text(labels)} #{value}"
19
+ end.join("\n")
20
+ end
21
+
22
+ def observe(increment = 1, labels = {})
23
+ @data[labels] ||= 0
24
+ @data[labels] += increment
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PrometheusExporter::Metric
4
+ class Gauge < Base
5
+ attr_reader :data
6
+
7
+ def initialize(name, help)
8
+ super
9
+ @data = {}
10
+ end
11
+
12
+ def type
13
+ "gauge"
14
+ end
15
+
16
+ def metric_text
17
+ @data.map do |labels, value|
18
+ "#{prefix(@name)}#{labels_text(labels)} #{value}"
19
+ end.join("\n")
20
+ end
21
+
22
+ def observe(value, labels = {})
23
+ @data[labels] = value
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PrometheusExporter::Metric
4
+ class Summary < Base
5
+
6
+ QUANTILES = [0.99, 0.9, 0.5, 0.1, 0.01]
7
+ ROTATE_AGE = 120
8
+
9
+ attr_reader :estimators, :count, :total
10
+
11
+ def initialize(name, help)
12
+ super
13
+ @buffers = [{}, {}]
14
+ @last_rotated = Process.clock_gettime(Process::CLOCK_MONOTONIC)
15
+ @current_buffer = 0
16
+ @counts = {}
17
+ @sums = {}
18
+ end
19
+
20
+ def type
21
+ "summary"
22
+ end
23
+
24
+ def calculate_quantiles(raw_data)
25
+ sorted = raw_data.sort
26
+ length = sorted.length
27
+ result = {}
28
+
29
+ if length > 0
30
+ QUANTILES.each do |quantile|
31
+ result[quantile] = sorted[(length * quantile).ceil - 1]
32
+ end
33
+ end
34
+
35
+ result
36
+ end
37
+
38
+ def calculate_all_quantiles
39
+ buffer = @buffers[@current_buffer]
40
+
41
+ result = {}
42
+ buffer.each do |labels, raw_data|
43
+ result[labels] = calculate_quantiles(raw_data)
44
+ end
45
+
46
+ result
47
+
48
+ end
49
+
50
+ def metric_text
51
+ text = String.new
52
+ first = true
53
+ calculate_all_quantiles.each do |labels, quantiles|
54
+ text << "\n" unless first
55
+ first = false
56
+ quantiles.each do |quantile, value|
57
+ with_quantile = labels.merge(quantile: quantile)
58
+ text << "#{prefix(@name)}#{labels_text(with_quantile)} #{value.to_f}\n"
59
+ end
60
+ text << "#{prefix(@name)}_sum#{labels_text(labels)} #{@sums[labels]}\n"
61
+ text << "#{prefix(@name)}_count#{labels_text(labels)} #{@counts[labels]}"
62
+ end
63
+ text
64
+ end
65
+
66
+ # makes sure we have storage
67
+ def ensure_summary(labels)
68
+ @buffers[0][labels] ||= []
69
+ @buffers[1][labels] ||= []
70
+ @sums[labels] ||= 0.0
71
+ @counts[labels] ||= 0
72
+ nil
73
+ end
74
+
75
+ def rotate_if_needed
76
+ if (now = Process.clock_gettime(Process::CLOCK_MONOTONIC)) > (@last_rotated + ROTATE_AGE)
77
+ @last_rotated = now
78
+ @buffers[@current_buffer].each do |labels, raw|
79
+ raw.clear
80
+ end
81
+ @current_buffer = @current_buffer == 0 ? 1 : 0
82
+ end
83
+ nil
84
+ end
85
+
86
+ def observe(value, labels = {})
87
+ ensure_summary(labels)
88
+ rotate_if_needed
89
+
90
+ value = value.to_f
91
+ @buffers[0][labels] << value
92
+ @buffers[1][labels] << value
93
+ @sums[labels] += value
94
+ @counts[labels] += 1
95
+ end
96
+
97
+ end
98
+ end
@@ -0,0 +1,4 @@
1
+ require_relative "metric/base"
2
+ require_relative "metric/counter"
3
+ require_relative "metric/gauge"
4
+ require_relative "metric/summary"
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PrometheusExporter::Server
4
+
5
+ class Collector
6
+
7
+ def initialize
8
+ @metrics = {}
9
+ @buffer = []
10
+ @mutex = Mutex.new
11
+ end
12
+
13
+ def process(obj)
14
+ @mutex.synchronize do
15
+ metric = @metrics[obj["name"]]
16
+ if !metric
17
+ metric = register_metric_unsafe(obj)
18
+ end
19
+ metric.observe(obj["value"], obj["keys"])
20
+ end
21
+ end
22
+
23
+ def prometheus_metrics_text
24
+ @mutex.synchronize do
25
+ @metrics.values.map(&:to_prometheus_text).join("\n")
26
+ end
27
+ end
28
+
29
+ def register_metric(metric)
30
+ @mutex.synchronize do
31
+ @metrics << metric
32
+ end
33
+ end
34
+
35
+ protected
36
+
37
+ def register_metric_unsafe(obj)
38
+ name = obj["name"]
39
+ help = obj["help"]
40
+
41
+ metric =
42
+ case obj["type"]
43
+ when "gauge"
44
+ PrometheusExporter::Metric::Gauge.new(name, help)
45
+ when "counter"
46
+ PrometheusExporter::Metric::Counter.new(name, help)
47
+ when "summary"
48
+ PrometheusExporter::Metric::Summary.new(name, help)
49
+ end
50
+
51
+ if metric
52
+ @metrics[name] = metric
53
+ else
54
+ STDERR.puts "failed to register metric #{obj}"
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,96 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'webrick'
4
+ require 'timeout'
5
+
6
+ module PrometheusExporter::Server
7
+ class WebServer
8
+ attr_reader :collector
9
+
10
+ def initialize(port: , collector: nil)
11
+
12
+ @server = WEBrick::HTTPServer.new(
13
+ Port: port,
14
+ AccessLog: [],
15
+ Logger: WEBrick::Log.new("/dev/null")
16
+ )
17
+
18
+ @collector = collector || Collector.new
19
+ @port = port
20
+
21
+ @server.mount_proc '/' do |req, res|
22
+ res['ContentType'] = 'text/plain; charset=utf-8'
23
+ if req.path == '/metrics'
24
+ res.status = 200
25
+ res.body = metrics
26
+ elsif req.path == '/send-metrics'
27
+ handle_metrics(req, res)
28
+ else
29
+ res.status = 404
30
+ res.body = "Not Found! The Prometheus Discourse plugin only listens on /metrics and /send-metrics"
31
+ end
32
+ end
33
+ end
34
+
35
+ def handle_metrics(req, res)
36
+ req.body do |block|
37
+ begin
38
+ @collector.process(JSON.parse(block))
39
+ rescue => e
40
+ res.body = "Bad Metrics #{e}"
41
+ res.status = e.respond_to?(:status_code) ? e.status_code : 500
42
+ return
43
+ end
44
+ end
45
+
46
+ res.body = "OK"
47
+ res.status = 200
48
+ end
49
+
50
+ def start
51
+ @runner ||= Thread.start do
52
+ begin
53
+ @server.start
54
+ rescue => e
55
+ STDERR.puts "Failed to start prometheus collector web on port #{@port}: #{e}"
56
+ end
57
+ end
58
+ end
59
+
60
+ def stop
61
+ @server.shutdown
62
+ end
63
+
64
+ def metrics
65
+ metric_text = nil
66
+ begin
67
+ Timeout::timeout(2) do
68
+ metric_text = @collector.prometheus_metrics_text
69
+ end
70
+ rescue Timeout::Error
71
+ # we timed out ... bummer
72
+ STDERR.puts "Generating Prometheus metrics text timed out"
73
+ end
74
+
75
+ @metrics = []
76
+
77
+ add_gauge(
78
+ "collector_working",
79
+ "Is the master process collector able to collect metrics",
80
+ metric_text && metric_text.length > 0 ? 1 : 0
81
+ )
82
+
83
+ <<~TEXT
84
+ #{@metrics.map(&:to_prometheus_text).join("\n\n")}
85
+ #{metric_text}
86
+ TEXT
87
+ end
88
+
89
+ def add_gauge(name, help, value)
90
+ gauge = PrometheusExporter::Metric::Gauge.new(name, help)
91
+ gauge.observe(value)
92
+ @metrics << gauge
93
+ end
94
+
95
+ end
96
+ end
@@ -0,0 +1,3 @@
1
+ require_relative "server/collector"
2
+ require_relative "server/web_server"
3
+ require_relative "metric"
@@ -0,0 +1,3 @@
1
+ module PrometheusExporter
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,6 @@
1
+ require_relative "prometheus_exporter/version"
2
+ require "json"
3
+ require "thread"
4
+
5
+ module PrometheusExporter
6
+ end
@@ -0,0 +1,29 @@
1
+
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "prometheus_exporter/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "prometheus_exporter"
8
+ spec.version = PrometheusExporter::VERSION
9
+ spec.authors = ["Sam Saffron"]
10
+ spec.email = ["sam.saffron@gmail.com"]
11
+
12
+ spec.summary = %q{Prometheus Exporter}
13
+ spec.description = %q{Prometheus metric collector and exporter for Ruby}
14
+ spec.homepage = "https://github.com/discourse/prometheus_exporter"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features|bin)/})
19
+ end
20
+ spec.bindir = "bin"
21
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_development_dependency "bundler", "~> 1.16"
25
+ spec.add_development_dependency "rake", "~> 10.0"
26
+ spec.add_development_dependency "minitest", "~> 5.0"
27
+ spec.add_development_dependency "guard", "~> 2.0"
28
+ spec.add_development_dependency "guard-minitest", "~> 2.0"
29
+ end
metadata ADDED
@@ -0,0 +1,137 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: prometheus_exporter
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Sam Saffron
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2018-01-10 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.16'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.16'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: minitest
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '5.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '5.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: guard
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '2.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '2.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: guard-minitest
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '2.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '2.0'
83
+ description: Prometheus metric collector and exporter for Ruby
84
+ email:
85
+ - sam.saffron@gmail.com
86
+ executables: []
87
+ extensions: []
88
+ extra_rdoc_files: []
89
+ files:
90
+ - ".gitignore"
91
+ - ".rubocop.yml"
92
+ - ".travis.yml"
93
+ - CODE_OF_CONDUCT.md
94
+ - Gemfile
95
+ - Gemfile.lock
96
+ - Guardfile
97
+ - LICENSE.txt
98
+ - README.md
99
+ - Rakefile
100
+ - examples/custom_collector.rb
101
+ - lib/prometheus_exporter.rb
102
+ - lib/prometheus_exporter/client.rb
103
+ - lib/prometheus_exporter/metric.rb
104
+ - lib/prometheus_exporter/metric/base.rb
105
+ - lib/prometheus_exporter/metric/counter.rb
106
+ - lib/prometheus_exporter/metric/gauge.rb
107
+ - lib/prometheus_exporter/metric/summary.rb
108
+ - lib/prometheus_exporter/server.rb
109
+ - lib/prometheus_exporter/server/collector.rb
110
+ - lib/prometheus_exporter/server/web_server.rb
111
+ - lib/prometheus_exporter/version.rb
112
+ - prometheus_exporter.gemspec
113
+ homepage: https://github.com/discourse/prometheus_exporter
114
+ licenses:
115
+ - MIT
116
+ metadata: {}
117
+ post_install_message:
118
+ rdoc_options: []
119
+ require_paths:
120
+ - lib
121
+ required_ruby_version: !ruby/object:Gem::Requirement
122
+ requirements:
123
+ - - ">="
124
+ - !ruby/object:Gem::Version
125
+ version: '0'
126
+ required_rubygems_version: !ruby/object:Gem::Requirement
127
+ requirements:
128
+ - - ">="
129
+ - !ruby/object:Gem::Version
130
+ version: '0'
131
+ requirements: []
132
+ rubyforge_project:
133
+ rubygems_version: 2.7.3
134
+ signing_key:
135
+ specification_version: 4
136
+ summary: Prometheus Exporter
137
+ test_files: []