hawkular-client 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 0c2bd7524ca6889a513ffac38121ecd21626d26c
4
+ data.tar.gz: c8a90d9d4a3b042baf12c8fd046601d5442ccce1
5
+ SHA512:
6
+ metadata.gz: d3015ffa0cb3c714b9141a9b6783539b115c556a617911e931bc5905fd7e10bfa37727bd927a9e629e0021027495c01be5c62af8158810091624ce0a5790a6bb
7
+ data.tar.gz: 64541ba6774f5f67582586acafd3c806861a51b1dc6452848716c8c552ada2db434b2a3c5be37cfd6aef059023d2fe9873a6b9c5f30ec5f706683701dbfe9006
data/.gitignore ADDED
@@ -0,0 +1,38 @@
1
+ *.gem
2
+ *.rbc
3
+ /.config
4
+ /coverage/
5
+ /InstalledFiles
6
+ /pkg/
7
+ /spec/reports/
8
+ /test/tmp/
9
+ /test/version_tmp/
10
+ /tmp/
11
+
12
+ ## Specific to RubyMotion:
13
+ .dat*
14
+ .repl_history
15
+ build/
16
+
17
+ ## Documentation cache and generated files:
18
+ /.yardoc/
19
+ /_yardoc/
20
+ /doc/
21
+ /rdoc/
22
+
23
+ ## Environment normalisation:
24
+ /.bundle/
25
+ /vendor/bundle
26
+ /lib/bundler/man/
27
+
28
+ # for a library or gem, you might want to ignore these files since the code is
29
+ # intended to run in multiple environments; otherwise, check them in:
30
+ # Gemfile.lock
31
+ # .ruby-version
32
+ # .ruby-gemset
33
+
34
+ # unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
35
+ .rvmrc
36
+
37
+ # test config
38
+ spec/endpoint.yml
data/CHANGES.rdoc ADDED
@@ -0,0 +1,5 @@
1
+ == Changes
2
+
3
+ This document describes the relevant changes beween releases of the
4
+ _hawkular-client_ project.
5
+
data/Gemfile ADDED
@@ -0,0 +1,2 @@
1
+ source "http://rubygems.org"
2
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
data/README.rdoc ADDED
@@ -0,0 +1,33 @@
1
+ = hawkular-client-ruby
2
+
3
+ A Ruby Hawkular Client.
4
+
5
+ == Contributing to hawkular-client-ruby
6
+
7
+ * Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
8
+ * Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
9
+ * Fork the project
10
+ * Start a feature/bugfix branch
11
+ * Commit and push until you are happy with your contribution
12
+ * Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
13
+ * Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
14
+
15
+ == Running the tests
16
+
17
+ * Copy the file spec/endpoint.yml.example to spec/endpoint.yml
18
+ * Edit the endpoint properties (user, password and host name)
19
+ * From command line run => rake spec
20
+
21
+ == Logging
22
+
23
+ If you want to see API requests and responses, use the following environment
24
+ variables:
25
+
26
+ RESTCLIENT_LOG=stdout HAWKULARCLIENT_LOG_RESPONSE=1 rake spec
27
+
28
+ == Generate documentation
29
+
30
+ Client documentation can be generated using http://yardoc.org
31
+
32
+ yardoc
33
+
data/Rakefile ADDED
@@ -0,0 +1,9 @@
1
+ require "bundler/gem_tasks"
2
+ require 'rspec/core/rake_task'
3
+
4
+ RSpec::Core::RakeTask.new(:spec) do |task|
5
+ task.pattern = "./spec/**/*_spec.rb"
6
+ task.rspec_opts = ['--color']
7
+ end
8
+
9
+ task :default => :spec
@@ -0,0 +1,30 @@
1
+ # -*- encoding: utf-8 -*-
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'metrics/version'
5
+
6
+ Gem::Specification.new do |gem|
7
+ gem.name = "hawkular-client"
8
+ gem.version = Hawkular::Metrics::VERSION
9
+ gem.authors = ['Libor Zoubek']
10
+ gem.email = ['lzoubek@redhat.com']
11
+ gem.homepage = "https://github.com/hawkular/hawkular-client-ruby"
12
+ gem.summary = %q{A Ruby client for Hawkular}
13
+ gem.description = <<-EOS
14
+ A Ruby client for Hawkular
15
+ EOS
16
+
17
+ gem.files = `git ls-files`.split($/)
18
+ gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
19
+ gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
20
+ gem.require_paths = ["lib"]
21
+
22
+ gem.add_runtime_dependency('rest-client')
23
+ gem.add_development_dependency('shoulda')
24
+ gem.add_development_dependency('rspec-rails', '~> 2.6')
25
+ gem.add_development_dependency('rake')
26
+ gem.add_development_dependency('yardoc')
27
+
28
+ gem.rdoc_options << '--title' << gem.name << '--main' << 'README.rdoc' << '--line-numbers' << '--inline-source'
29
+ gem.extra_rdoc_files = ['README.rdoc', 'CHANGES.rdoc']
30
+ end
@@ -0,0 +1,187 @@
1
+
2
+
3
+ require "json"
4
+ require "rest-client"
5
+
6
+ module Hawkular
7
+ # Metrics module provides access to Hawkular Metrics REST API
8
+ # @see http://www.hawkular.org/docs/rest/rest-metrics.html Hawkular Metrics REST API Documentation
9
+ # @example Create Hawkular-Metrics client and start pushing some metric data
10
+ # # create client instance
11
+ # client = Hawkular::Metrics::Client::new("http://server","username","password",{"tenant" => "your tenant ID"})
12
+ # # push gauge metric data for metric called "myGauge" (no need to create metric definition unless you wish to specify data retention)
13
+ # client.gauges.push_data("myGauge", {:value => 3.1415925})
14
+ module Metrics
15
+ end
16
+ end
17
+
18
+ require "metrics/types"
19
+ require "metrics/tenant_api"
20
+ require "metrics/metric_api"
21
+
22
+
23
+ module Hawkular::Metrics
24
+
25
+ class HawkularException < StandardError
26
+ def initialize(message)
27
+ @message = message
28
+ super
29
+ end
30
+
31
+ def message
32
+ @message
33
+ end
34
+ end
35
+
36
+ class Client
37
+
38
+ # @!visibility private
39
+ attr_reader :credentials, :entrypoint, :options
40
+ # @return [Tenants] access tenants API
41
+ attr_reader :tenants
42
+ # @return [Counters] access counters API
43
+ attr_reader :counters
44
+ # @return [Gauges] access gauges API
45
+ attr_reader :gauges
46
+ # @return [Availability] access counters API
47
+ attr_reader :avail
48
+
49
+ # Construct a new Hawkular Metrics client class.
50
+ # optional parameters
51
+ # @param entrypoint [String]
52
+ # @param username [String]
53
+ # @param password [String]
54
+ # @param options [Hash{String=>String}] client options
55
+ # @example initialize with Hawkular-tenant option
56
+ # Hawkular::Metrics::Client::new("http://server","username","password",{"tenant" => "your tenant ID"})
57
+ #
58
+ def initialize(entrypoint='http://localhost:8080/hawkular/metrics',username=nil, password=nil, options={})
59
+ @entrypoint = entrypoint
60
+ @credentials = { :username => username, :password => password }
61
+ @options = {
62
+ :tenant => nil,
63
+ }.merge(options)
64
+
65
+ @tenants = Client::Tenants::new self
66
+ @counters = Client::Counters::new self
67
+ @gauges = Client::Gauges::new self
68
+ @avail = Client::Availability::new self
69
+ end
70
+
71
+
72
+ def http_get(suburl, headers={})
73
+ begin
74
+ res = rest_client(suburl).get(http_headers(headers))
75
+ puts "#{res}\n" if ENV['HAWKULARCLIENT_LOG_RESPONSE']
76
+ res.empty? ? {} : JSON.parse(res)
77
+ rescue
78
+ handle_fault $!
79
+ end
80
+ end
81
+
82
+
83
+ def http_post(suburl, hash, headers={})
84
+ begin
85
+ body = JSON.generate(hash)
86
+ res = rest_client(suburl).post(body, http_headers(headers))
87
+ puts "#{res}\n" if ENV['HAWKULARCLIENT_LOG_RESPONSE']
88
+ res.empty? ? {} : JSON.parse(res)
89
+ rescue
90
+ handle_fault $!
91
+ end
92
+ end
93
+
94
+ def http_put(suburl, hash, headers={})
95
+ begin
96
+ body = JSON.generate(hash)
97
+ res = rest_client(suburl).put(body, http_headers(headers))
98
+ puts "#{res}\n" if ENV['HAWKULARCLIENT_LOG_RESPONSE']
99
+ res.empty? ? {} : JSON.parse(res)
100
+ rescue
101
+ handle_fault $!
102
+ end
103
+ end
104
+
105
+ def http_delete(suburl, headers={})
106
+ begin
107
+ res = rest_client(suburl).delete(http_headers(headers))
108
+ puts "#{res}\n" if ENV['HAWKULARCLIENT_LOG_RESPONSE']
109
+ res.empty? ? {} : JSON.parse(res)
110
+ rescue
111
+ handle_fault $!
112
+ end
113
+ end
114
+
115
+
116
+
117
+ # @!visibility private
118
+ def rest_client(suburl)
119
+ options[:timeout] = ENV['HAWKULARCLIENT_REST_TIMEOUT'] if ENV['HAWKULARCLIENT_REST_TIMEOUT']
120
+ # strip @endpoint in case suburl is absolute
121
+ if suburl.match(/^http/)
122
+ suburl = suburl[@entrypoint.length,suburl.length]
123
+ end
124
+ RestClient::Resource.new(@entrypoint, options)[suburl]
125
+ end
126
+
127
+ # @!visibility private
128
+ def base_url
129
+ url = URI.parse(@entrypoint)
130
+ "#{url.scheme}://#{url.host}:#{url.port}"
131
+ end
132
+
133
+ # @!visibility private
134
+ def self.parse_response(response)
135
+ JSON.parse(response)
136
+ end
137
+
138
+ # @!visibility private
139
+ def http_headers(headers ={})
140
+ {}.merge(auth_header)
141
+ .merge(tenant_header)
142
+ .merge({
143
+ :content_type => 'application/json',
144
+ :accept => 'application/json',
145
+ })
146
+ .merge(headers)
147
+ end
148
+
149
+ # timestamp of current time
150
+ # @return [Integer] timestamp
151
+ def now
152
+ Integer(Time::now.to_f * 1000)
153
+ end
154
+
155
+ private
156
+
157
+
158
+ def tenant_header
159
+ @options[:tenant].nil? ? {} : { :'Hawkular-Tenant' => @options[:tenant], "tenantId" => @options[:tenant] }
160
+ end
161
+
162
+
163
+ def auth_header
164
+ if @credentials[:username].nil? and @credentials[:password].nil?
165
+ return {}
166
+ end
167
+ # This is the method for strict_encode64:
168
+ encoded_credentials = ["#{@credentials[:username]}:#{@credentials[:password]}"].pack("m0").gsub(/\n/,'')
169
+ {:authorization => "Basic " + encoded_credentials }
170
+ end
171
+
172
+ def handle_fault(f)
173
+ if defined? f.http_body and !f.http_body.nil?
174
+ begin
175
+ fault = "#{f.errorMsg}\n%s\n" % JSON.parse(f.http_body)["errorMsg"]
176
+ rescue
177
+ fault = f.http_body
178
+ raise HawkularException::new(fault)
179
+ end
180
+ else
181
+ raise f
182
+ end
183
+
184
+ end
185
+ end
186
+
187
+ end
@@ -0,0 +1,176 @@
1
+ module Hawkular::Metrics
2
+ class Client
3
+
4
+ # @!visibility private
5
+ def default_timestamp(array)
6
+ n = now
7
+ array.each { |p|
8
+ p[:timestamp] ||= n
9
+ }
10
+ array
11
+ end
12
+
13
+
14
+ # Push data for multiple metrics of all supported types
15
+ # @param gauges [Array]
16
+ # @param counters [Array]
17
+ # @param availabilities [Array]
18
+ # @example push datapoints of 2 counter metrics
19
+ # client = Hawkular::Metrics::client::new
20
+ # client.push_data(counters: [{:id => "counter1", :data => [{:value => 1}, {:value => 2}]},{:id => "counter2", :data => [{:value => 1}, {:value => 3}]}])
21
+ # @example push gauge and availability datapoints
22
+ # client.push_data(gauges: [{:id => "gauge1", :data => [{:value => 1}, {:value => 2}]}], availabilities: [{:id => "avail1", :data => [{:value => "up"}]}])
23
+ def push_data(gauges: [], counters: [], availabilities: [])
24
+ gauges.each { |g|
25
+ default_timestamp g[:data]
26
+ }
27
+ counters.each { |g|
28
+ default_timestamp g[:data]
29
+ }
30
+ availabilities.each { |g|
31
+ default_timestamp g[:data]
32
+ }
33
+ data = {:gauges => gauges, :counters => counters, :availabilities => availabilities}
34
+ http_post("/metrics/data", data)
35
+ end
36
+
37
+ # Base class for accessing metric definition and data of all types (counters, gauges, availabilities)
38
+ class Metrics
39
+
40
+ # @param client [Client]
41
+ # @param metricType [String] metric type (one of "counter", "gauge", "availability")
42
+ # @param resource [String] REST resource name for accessing metrics of given type (one of "counters", "gauges", "availability")
43
+ def initialize(client, metricType, resource)
44
+ @client = client
45
+ @type = metricType
46
+ @resource = resource
47
+ end
48
+
49
+ # Create new metric definition
50
+ # @param definition [MetricDefinition or Hash] gauge/counter/availability options.
51
+ # @example Create gauge metric definition using Hash
52
+ # client = Hawkular::Metrics::client::new
53
+ # client.gauges.create({:id => "id", :dataRetention => 90, :tags => {:tag1 => "value1"}, :tenantId => "your tenant id"})
54
+ def create(definition)
55
+ if definition.kind_of?(Hawkular::Metrics::MetricDefinition)
56
+ definition = definition.hash
57
+ end
58
+ @client.http_post('/'+@resource, definition)
59
+ end
60
+
61
+ # Query metric definitions by tags
62
+ # @param tags [Hash]
63
+ # @return [Array[MetricDefinition]]
64
+ def query(tags)
65
+ tags = tags.map do |k,v|
66
+ "#{k}:#{v}"
67
+ end
68
+ @client.http_get("/metrics/?type=#{@type}&tags=#{tags.join(',')}").map do |g|
69
+ Hawkular::Metrics::MetricDefinition::new(g)
70
+ end
71
+ end
72
+
73
+ # Get metric definition by id
74
+ # @param id [String]
75
+ # @return [MetricDefinition]
76
+ def get(id)
77
+ Hawkular::Metrics::MetricDefinition::new(@client.http_get("/#{@resource}/#{id}"))
78
+ end
79
+
80
+ # update tags for given metric definition
81
+ # @param metricDefinition [MetricDefinition]
82
+ def update_tags(metricDefinition)
83
+ @client.http_put("/#{@resource}/#{metricDefinition.id}/tags",metricDefinition.hash[:tags])
84
+ end
85
+
86
+ # Push metric data
87
+ # @param id [String] metric definition ID
88
+ # @param data [Array[Hash]] Single datapoint or array of datapoints
89
+ # @example Push counter data with timestamp
90
+ # client = Hawkular::Metics::Client::new
91
+ # now = Integer(Time::now.to_f * 1000)
92
+ # client.counters.push_data("counter id", [{:value => 1, :timestamp => now - 1000}, {:value => 2, :timestamp => now}])
93
+ # @example Push single availability without timestamp
94
+ # client.avail.push_data("avail_id", {:value => "up"})
95
+ # @example Push gague data with tags
96
+ # client.gagues.push_data("gauge_id", [{:value => 0.1, :tags => {:tagName => "myMin"}},{:value => 99.9, :tags => {:tagName => "myMax"}}])
97
+ def push_data(id, data)
98
+ if !data.kind_of?(Array)
99
+ data = [data]
100
+ end
101
+
102
+ @client.default_timestamp data
103
+ @client.http_post("/#{@resource}/#{id}/data", data)
104
+ end
105
+
106
+ # Retrieve metric datapoints
107
+ # @param id [String] metric definition id
108
+ # @param starts [Integer] optional timestamp (default now - 8h)
109
+ # @param ends [Integer] optional timestamp (default now)
110
+ # @return [Array[Hash]] datapoints
111
+ # @see #push_data #push_data for datapoint detail
112
+ def get_data(id, starts: nil, ends: nil)
113
+ params = {:start => starts, :end => ends}
114
+ params.delete_if { |k, v| v.nil? }
115
+ resp = @client.http_get("/#{@resource}/#{id}/data/?"+URI.encode_www_form(params))
116
+ return [] if !resp.kind_of?(Array) # API returns no content (empty Hash) instead of empty array
117
+ resp
118
+ end
119
+ end
120
+
121
+ # Class that interracts with "gauge" metric types
122
+ class Gauges < Metrics
123
+
124
+ # @param client [Client]
125
+ def initialize(client)
126
+ super(client, 'gauge', 'gauges')
127
+ end
128
+
129
+ # Retrieve time ranges when given gauge matches given operation and threshold
130
+ # @param id [String] gauge ID
131
+ # @param starts [Integer] timestamp (default now - 8h)
132
+ # @param ends [Integer] timestamp (default now)
133
+ # @param threshold [Numeric]
134
+ # @param operation [String] A comparison operation to perform between values and the threshold. Supported operations include "ge", "gte", "lt", "lte", and "eq"
135
+ # @example Get time periods when metric "gauge1" was under 10 in past 4 hours
136
+ # before4h = client.now - (4 * 60 * 60 * 1000)
137
+ # client.gauges.get_periods("gauge1", starts: before4h, threshold: 10, operation: "lte")
138
+ def get_periods(id, starts: nil, ends: nil, threshold:, operation:)
139
+ params = {:start => starts, :end => ends, :threshold => threshold, :op => operation}
140
+ params.delete_if { |k, v| v.nil? }
141
+ @client.http_get("/#{@resource}/#{id}/periods?"+URI.encode_www_form(params))
142
+ end
143
+
144
+ end
145
+
146
+ # Class that interracts with "counter" metric types
147
+ class Counters < Metrics
148
+
149
+ # @param client [Client]
150
+ def initialize(client)
151
+ super(client, 'counter', 'counters')
152
+ end
153
+
154
+ # get rate for given metric
155
+ # @param id [String] metric ID
156
+ def get_rate(id:)
157
+ @client.http_get("/#{@resource}/#{id}/rate")
158
+ end
159
+ end
160
+
161
+ # Class that interracts with "availability" metric types
162
+ class Availability < Metrics
163
+
164
+ # @param client [Client]
165
+ def initialize(client)
166
+ super(client, 'availability', 'availability')
167
+ end
168
+
169
+ end
170
+
171
+
172
+ private
173
+
174
+
175
+ end
176
+ end
@@ -0,0 +1,27 @@
1
+ module Hawkular::Metrics
2
+ class Client
3
+ # Provides access to tenants API
4
+ class Tenants
5
+
6
+ # @param client [Client]
7
+ def initialize(client)
8
+ @client = client
9
+ @resource = "tenants"
10
+ end
11
+
12
+ # Create new tenant
13
+ # @param id [String] tenant ID/Name
14
+ def create(id)
15
+ @client.http_post("/#{@resource}", {:id => id})
16
+ end
17
+
18
+ # Query existing tenants
19
+ # @return [Array[Tenant]]
20
+ def query
21
+ @client.http_get("/#{@resource}").map do |t|
22
+ Hawkular::Metrics::Tenant::new(t)
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,38 @@
1
+ module Hawkular
2
+ module Metrics
3
+ class BaseObject
4
+ attr_reader :json
5
+ attr_accessor :id
6
+
7
+ def initialize(json)
8
+ @json = json
9
+ if !json.nil?
10
+ @id = @json['id']
11
+ end
12
+ end
13
+ end
14
+
15
+ class Tenant < BaseObject
16
+ end
17
+
18
+ class MetricDefinition < BaseObject
19
+ attr_accessor :tenantId, :dataRetention, :tags
20
+
21
+ def initialize(json=nil)
22
+ super(json)
23
+ if !json.nil?
24
+ @tenantId = @json['tenantId']
25
+ @dataRetention = @json['dataRetention']
26
+ @tags = @json['tags']
27
+ end
28
+ end
29
+
30
+ def hash
31
+ h = {:id => @id, :tenantId => @tenantId, :dataRetention => @dataRetention, :tags => @tags}
32
+ h.delete_if { |k, v| v.nil? }
33
+ h
34
+ end
35
+
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,5 @@
1
+ module Hawkular
2
+ module Metrics
3
+ VERSION = "0.1.0"
4
+ end
5
+ end
@@ -0,0 +1,7 @@
1
+ # This is example configuration for integration tests and it should
2
+ # work out-of-box with hawkular in dev environment
3
+
4
+ url: "http://localhost:8080/hawkular/metrics"
5
+ # authentication is not yet supported in hawkular-metrics 0.5.0
6
+ # user: "jdoe"
7
+ # password: "jdoe"
@@ -0,0 +1,243 @@
1
+ require "#{File.dirname(__FILE__)}/../spec_helper"
2
+ require "securerandom"
3
+
4
+ # examples related to Hawkular Metrics
5
+
6
+
7
+ # time constants
8
+ t4h = 4 * 60 * 60 * 1000
9
+
10
+ # more or less generic methodc common for all metric types (counters, gauges, availabilities)
11
+ def create_metric_using_hash(endpoint)
12
+ id = SecureRandom.uuid
13
+ endpoint.create({:id => id, :dataRetention => 123, :tags => {:some => "value"}, :tenantId => @tenant})
14
+ metric = endpoint.get(id)
15
+
16
+ expect(metric).to be_a(Hawkular::Metrics::MetricDefinition)
17
+ expect(metric.id).to eql(id)
18
+ expect(metric.dataRetention).to eql(123)
19
+ expect(metric.tenantId).to eql(@tenant)
20
+ end
21
+
22
+ def create_metric_using_md(endpoint)
23
+ metric = Hawkular::Metrics::MetricDefinition::new
24
+ metric.id = SecureRandom.uuid
25
+ metric.dataRetention = 90
26
+ metric.tags = {:tag => "value"}
27
+ endpoint.create(metric)
28
+
29
+ created = endpoint.get(metric.id)
30
+ expect(created).to be_a(Hawkular::Metrics::MetricDefinition)
31
+ expect(created.id).to eql(metric.id)
32
+ expect(created.dataRetention).to eql(metric.dataRetention)
33
+ end
34
+
35
+ def push_data_to_non_existing_metric(endpoint, data)
36
+ id = SecureRandom.uuid
37
+ # push one value without timestamp (which means now)
38
+ endpoint.push_data(id, data)
39
+
40
+ data = endpoint.get_data(id)
41
+ expect(data.size).to be 1
42
+
43
+ #verify metric was auto-created
44
+ counter = endpoint.get(id)
45
+ expect(counter).to be_a(Hawkular::Metrics::MetricDefinition)
46
+ expect(counter.id).to eql(id)
47
+ end
48
+
49
+ def update_metric_by_tags(endpoint)
50
+ id = SecureRandom.uuid
51
+ endpoint.create({:id => id, :tags => {:myTag => id}})
52
+ metric = endpoint.get(id)
53
+ metric.tags = {:newTag => "newValue"}
54
+ endpoint.update_tags(metric)
55
+
56
+ metric = endpoint.get(id)
57
+ expect(metric.tags).to include({"newTag" => "newValue","myTag" => id})
58
+
59
+ # query API for a metric with given tag
60
+ data = endpoint.query({:myTag => id})
61
+ expect(data.size).to be 1
62
+ end
63
+
64
+ describe "Tenants" do
65
+
66
+ before(:all) do
67
+ setup_client
68
+ end
69
+
70
+ it "Should create and return tenant" do
71
+ tenant = SecureRandom.uuid
72
+ @client.tenants.create(tenant)
73
+ created = @client.tenants.query.select { |t|
74
+ t.id == tenant
75
+ }
76
+ expect(created).not_to be nil
77
+ end
78
+ end
79
+
80
+ describe "Mixed metrics" do
81
+
82
+ before(:all) do
83
+ setup_client_new_tenant
84
+ end
85
+
86
+ it "Should send mixed metric request of a single type" do
87
+ id = SecureRandom.uuid
88
+ @client.push_data(counters:[{:id => id, :data => [{:value => 1}]} ] )
89
+ data = @client.counters.get_data(id)
90
+ expect(data.size).to be 1
91
+
92
+ @client.push_data(availabilities:[{:id => id, :data => [{:value => "down"}]} ] )
93
+ data = @client.avail.get_data(id)
94
+ expect(data.size).to be 1
95
+
96
+ @client.push_data(gauges:[{:id => id, :data => [{:value => 1.1}]} ] )
97
+ data = @client.gauges.get_data(id)
98
+ expect(data.size).to be 1
99
+ end
100
+
101
+ it "Should send mixed metric request" do
102
+ id = SecureRandom.uuid
103
+
104
+ expect(@client.counters.get_data(id).size).to be 0
105
+ expect(@client.gauges.get_data(id).size).to be 0
106
+ expect(@client.avail.get_data(id).size).to be 0
107
+
108
+ @client.push_data(
109
+ counters:[{:id => id, :data => [{:value => 1}]}],
110
+ availabilities:[{:id => id, :data => [{:value => "down"}]}],
111
+ gauges:[{:id => id, :data => [{:value => 1.1}]}]
112
+ )
113
+
114
+ expect(@client.counters.get_data(id).size).to be 1
115
+ expect(@client.gauges.get_data(id).size).to be 1
116
+ expect(@client.avail.get_data(id).size).to be 1
117
+ end
118
+ end
119
+
120
+ describe "Counter metrics" do
121
+
122
+ before(:all) do
123
+ setup_client_new_tenant
124
+ end
125
+
126
+ it "Should create and return counter using Hash parameter" do
127
+ create_metric_using_hash @client.counters
128
+ end
129
+
130
+ it "Should create counter definition using MetricDefinition parameter" do
131
+ create_metric_using_md @client.counters
132
+ end
133
+
134
+ it "Should push metric data to existing counter" do
135
+ id = SecureRandom.uuid
136
+ #create counter
137
+ @client.counters.create({:id => id})
138
+ now = @client.now
139
+
140
+ # push 3 values with timestamps
141
+ @client.counters.push_data(id, [{:value => 1, :timestamp => now - 30}, {:value => 2, :timestamp => now - 20}, {:value => 3, :timestamp => now -10 }])
142
+
143
+ data = @client.counters.get_data(id)
144
+ expect(data.size).to be 3
145
+
146
+ # push one value without timestamp (which means now)
147
+ @client.counters.push_data(id, {:value => 4})
148
+ data = @client.counters.get_data(id)
149
+ expect(data.size).to be 4
150
+
151
+ # retrieve values from past
152
+ data = @client.counters.get_data(id, starts: @client.now - (2 * t4h), ends: @client.now - t4h)
153
+ expect(data.empty?).to be true
154
+ end
155
+
156
+ it "Should push metric data to non-existing counter" do
157
+ push_data_to_non_existing_metric @client.counters, {:value => 4}
158
+ end
159
+
160
+ end
161
+
162
+ describe "Availability metrics" do
163
+
164
+ before(:all) do
165
+ setup_client_new_tenant
166
+ end
167
+
168
+ it "Should create and return Availability using Hash parameter" do
169
+ create_metric_using_hash @client.avail
170
+ end
171
+
172
+ it "Should create Availability definition using MetricDefinition parameter" do
173
+ create_metric_using_md @client.avail
174
+ end
175
+
176
+ it "Should push metric data to non-existing Availability" do
177
+ push_data_to_non_existing_metric @client.avail, {:value =>"UP"}
178
+ end
179
+ it "Should update tags for Availability definition" do
180
+ update_metric_by_tags @client.avail
181
+ end
182
+ end
183
+
184
+ describe "Gauge metrics" do
185
+
186
+ before(:all) do
187
+ setup_client_new_tenant
188
+ end
189
+
190
+ it "Should create gauge definition using MetricDefinition" do
191
+ create_metric_using_md @client.gauges
192
+ end
193
+
194
+ it "Should create gauge definition using Hash" do
195
+ create_metric_using_hash @client.gauges
196
+ end
197
+
198
+ it "Should push metric data to non-existing gauge" do
199
+ push_data_to_non_existing_metric @client.gauges, {:value =>3.1415926}
200
+ end
201
+
202
+ it "Should push metric data to existing gauge" do
203
+ id = SecureRandom.uuid
204
+ #create gauge
205
+ @client.gauges.create({:id => id})
206
+ now = @client.now
207
+
208
+ # push 3 values with timestamps
209
+ @client.gauges.push_data(id, [{:value => 1, :timestamp => now - 30}, {:value => 2, :timestamp => now - 20}, {:value => 3, :timestamp => now -10 }])
210
+
211
+ data = @client.gauges.get_data(id)
212
+ expect(data.size).to be 3
213
+
214
+ # push one value without timestamp (which means now)
215
+ @client.gauges.push_data(id, {:value => 4})
216
+ data = @client.gauges.get_data(id)
217
+ expect(data.size).to be 4
218
+
219
+ # retrieve values from past
220
+ data = @client.counters.get_data(id, starts: @client.now - (2 * t4h), ends: @client.now - t4h)
221
+ expect(data.empty?).to be true
222
+ end
223
+
224
+ it "Should update tags for gauge definition" do
225
+ update_metric_by_tags @client.gauges
226
+ end
227
+
228
+ it "Should return periods" do
229
+ id = SecureRandom.uuid
230
+ now = @client.now
231
+ # push 3 values with timestamps
232
+ @client.gauges.push_data(id, [{:value => 1, :timestamp => now - 30}, {:value => 2, :timestamp => now - 20}, {:value => 3, :timestamp => now}])
233
+
234
+ before4h = @client.now - t4h
235
+ data = @client.gauges.get_periods(id, operation: "lte", threshold: 4, starts: before4h)
236
+ expect(data.size).to be 1
237
+ expect(data[0][0]).to eql(now - 30)
238
+ expect(data[0][1]).to eql(now)
239
+ end
240
+
241
+ end
242
+
243
+
@@ -0,0 +1,30 @@
1
+ require 'hawkularclient'
2
+ require 'rspec/core'
3
+ require 'rspec/mocks'
4
+ require 'socket'
5
+ require 'uri'
6
+ require 'yaml'
7
+
8
+ module Hawkular::Metrics::RSpec
9
+
10
+ def setup_client(options = {})
11
+ user, password, url = config['user'], config['password'], config['url']
12
+ @client = Hawkular::Metrics::Client.new(url, user, password, options)
13
+ end
14
+
15
+ def setup_client_new_tenant(options = {})
16
+ setup_client
17
+ @tenant = SecureRandom.uuid
18
+ @client.tenants.create(@tenant)
19
+ setup_client({:tenant => @tenant})
20
+ end
21
+
22
+ def config
23
+ @config ||= YAML.load(File.read(File.expand_path("endpoint.yml", File.dirname(__FILE__))))
24
+ end
25
+
26
+ end
27
+
28
+ RSpec.configure do |config|
29
+ config.include Hawkular::Metrics::RSpec
30
+ end
@@ -0,0 +1,44 @@
1
+ require "#{File.dirname(__FILE__)}/../spec_helper"
2
+
3
+ describe Hawkular::Metrics::Client do
4
+ context "client initialization" do
5
+ it "should accept no option" do
6
+ Hawkular::Metrics::Client::new("http://localhost:8080/hawkular/metrics","mockuser","mockpass")
7
+ end
8
+
9
+ it "should support no parameters" do
10
+ Hawkular::Metrics::Client::new()
11
+ end
12
+
13
+ it "should accept Hawkular-Tenant option" do
14
+ @client = Hawkular::Metrics::Client::new("http://localhost:8080/hawkular/metrics","mockuser","mockpass",{:tenant => "foo"})
15
+ headers = @client.send(:http_headers)
16
+ expect(headers[:"Hawkular-Tenant"]).to eql("foo")
17
+ end
18
+
19
+ it "should define subcomponents" do
20
+ client = Hawkular::Metrics::Client::new()
21
+ expect(client.tenants).not_to be nil
22
+ expect(client.counters).not_to be nil
23
+ expect(client.gauges).not_to be nil
24
+ end
25
+
26
+ end
27
+
28
+ context "http comms" do
29
+ before(:each) do
30
+ @client = Hawkular::Metrics::Client::new("http://localhost:8080/hawkular/metrics","mockuser","mockpass")
31
+ end
32
+
33
+ it "should add Accept: headers" do
34
+ headers = @client.send(:http_headers)
35
+ expect(headers[:accept]).to eql("application/json")
36
+ end
37
+
38
+ it "should keep existing Accept: headers" do
39
+ value = "application/json; foo=bar;"
40
+ headers = @client.send(:http_headers, {:accept => value})
41
+ expect(headers[:accept]).to eql(value)
42
+ end
43
+ end
44
+ end
metadata ADDED
@@ -0,0 +1,143 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: hawkular-client
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Libor Zoubek
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2015-08-19 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rest-client
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: shoulda
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec-rails
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '2.6'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '2.6'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: yardoc
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ description: |2
84
+ A Ruby client for Hawkular
85
+ email:
86
+ - lzoubek@redhat.com
87
+ executables: []
88
+ extensions: []
89
+ extra_rdoc_files:
90
+ - README.rdoc
91
+ - CHANGES.rdoc
92
+ files:
93
+ - ".gitignore"
94
+ - CHANGES.rdoc
95
+ - Gemfile
96
+ - LICENSE
97
+ - README.rdoc
98
+ - Rakefile
99
+ - hawkularclient.gemspec
100
+ - lib/hawkularclient.rb
101
+ - lib/metrics/metric_api.rb
102
+ - lib/metrics/tenant_api.rb
103
+ - lib/metrics/types.rb
104
+ - lib/metrics/version.rb
105
+ - spec/endpoint.yml.example
106
+ - spec/integration/metric_spec.rb
107
+ - spec/spec_helper.rb
108
+ - spec/unit/client_spec.rb
109
+ homepage: https://github.com/hawkular/hawkular-client-ruby
110
+ licenses: []
111
+ metadata: {}
112
+ post_install_message:
113
+ rdoc_options:
114
+ - "--title"
115
+ - hawkular-client
116
+ - "--main"
117
+ - README.rdoc
118
+ - "--line-numbers"
119
+ - "--inline-source"
120
+ require_paths:
121
+ - lib
122
+ required_ruby_version: !ruby/object:Gem::Requirement
123
+ requirements:
124
+ - - ">="
125
+ - !ruby/object:Gem::Version
126
+ version: '0'
127
+ required_rubygems_version: !ruby/object:Gem::Requirement
128
+ requirements:
129
+ - - ">="
130
+ - !ruby/object:Gem::Version
131
+ version: '0'
132
+ requirements: []
133
+ rubyforge_project:
134
+ rubygems_version: 2.4.5
135
+ signing_key:
136
+ specification_version: 4
137
+ summary: A Ruby client for Hawkular
138
+ test_files:
139
+ - spec/endpoint.yml.example
140
+ - spec/integration/metric_spec.rb
141
+ - spec/spec_helper.rb
142
+ - spec/unit/client_spec.rb
143
+ has_rdoc: