logstash-input-http_poller 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 27ad585ea744dd3feb40d3acfe744dabbfb5a122
4
+ data.tar.gz: 74ecba4a7d356cf7386c62469d6c16091f34f794
5
+ SHA512:
6
+ metadata.gz: 664d8bf1546d7b866c623b14d6a7dfeb799becb06e223a51510aed06cc2d2c3e3a0ca6c1e512e14e74dc96799624a34b83f1ab643d02a7ce1112b162866be04d
7
+ data.tar.gz: fd6716eaa478426b08494312a7e2939537d652780fa6455f58ef1bac3f01547f01a380d425fea9b7867535cd58277ff120f0f17e0775e4f11e6a0b664e10420f
@@ -0,0 +1,7 @@
1
+ *.gem
2
+ Gemfile.lock
3
+ .bundle
4
+ vendor
5
+ *~
6
+ .idea
7
+ *.log
@@ -0,0 +1,2 @@
1
+ * 1.0.0
2
+ - Initial release
@@ -0,0 +1,2 @@
1
+ # logstash-input-example
2
+ Example input plugin. This should help bootstrap your effort to write your own input plugin!
data/Gemfile ADDED
@@ -0,0 +1,2 @@
1
+ source 'https://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
+
@@ -0,0 +1,94 @@
1
+ # Logstash HTTP input plugin
2
+
3
+ This plugin is based off [logstash-input-rest](https://github.com/maximede/logstash-input-rest) by @maximede.
4
+
5
+ This [Logstash](https://github.com/elasticsearch/logstash) input plugin allows you to call an HTTP API, decode the output of it into event(s), and send them on their merry way.
6
+
7
+ The idea behind this plugins came from a need to read springboot metrics endpoint, instead of configuring jmx to monitor my java application memory / gc/ etc.
8
+
9
+ It is fully free and fully open source. The license is Apache 2.0, meaning you are pretty much free to use it however you want in whatever way.
10
+
11
+ ## Config Example
12
+
13
+ For config examples see `http_poller.rb` in `lib/logstash/inputs/` in this repo.
14
+
15
+ ## Documentation
16
+
17
+ Logstash provides infrastructure to automatically generate documentation for this plugin. We use the asciidoc format to write documentation so any comments in the source code will be first converted into asciidoc and then into html. All plugin documentation are placed under one [central location](http://www.elasticsearch.org/guide/en/logstash/current/).
18
+
19
+ - For formatting code or config example, you can use the asciidoc `[source,ruby]` directive
20
+ - For more asciidoc formatting tips, see the excellent reference here https://github.com/elasticsearch/docs#asciidoc-guide
21
+
22
+ ## Need Help?
23
+
24
+ Need help? Try #logstash on freenode IRC or the https://discuss.elastic.co/c/logstash discussion forum.
25
+
26
+ ## Developing
27
+
28
+ ### 1. Plugin Developement and Testing
29
+
30
+ #### Code
31
+ - To get started, you'll need JRuby with the Bundler gem installed.
32
+
33
+ - Create a new plugin or clone and existing from the GitHub [logstash-plugins](https://github.com/logstash-plugins) organization. We also provide [example plugins](https://github.com/logstash-plugins?query=example).
34
+
35
+ - Install dependencies
36
+ ```sh
37
+ bundle install
38
+ ```
39
+
40
+ #### Test
41
+
42
+ - Update your dependencies
43
+
44
+ ```sh
45
+ bundle install
46
+ ```
47
+
48
+ - Run tests
49
+
50
+ ```sh
51
+ bundle exec rspec
52
+ ```
53
+
54
+ ### 2. Running your unpublished Plugin in Logstash
55
+
56
+ #### 2.1 Run in a local Logstash clone
57
+
58
+ - Edit Logstash `Gemfile` and add the local plugin path, for example:
59
+ ```ruby
60
+ gem "logstash-filter-awesome", :path => "/your/local/logstash-filter-awesome"
61
+ ```
62
+ - Install plugin
63
+ ```sh
64
+ bin/plugin install --no-verify
65
+ ```
66
+ - Run Logstash with your plugin
67
+ ```sh
68
+ bin/logstash -e 'filter {awesome {}}'
69
+ ```
70
+ At this point any modifications to the plugin code will be applied to this local Logstash setup. After modifying the plugin, simply rerun Logstash.
71
+
72
+ #### 2.2 Run in an installed Logstash
73
+
74
+ You can use the same **2.1** method to run your plugin in an installed Logstash by editing its `Gemfile` and pointing the `:path` to your local plugin development directory or you can build the gem and install it using:
75
+
76
+ - Build your plugin gem
77
+ ```sh
78
+ gem build logstash-filter-awesome.gemspec
79
+ ```
80
+ - Install the plugin from the Logstash home
81
+ ```sh
82
+ bin/plugin install /your/local/plugin/logstash-filter-awesome.gem
83
+ ```
84
+ - Start Logstash and proceed to test the plugin
85
+
86
+ ## Contributing
87
+
88
+ All contributions are welcome: ideas, patches, documentation, bug reports, complaints, and even something you drew up on a napkin.
89
+
90
+ Programming is not a required skill. Whatever you've seen about open source and maintainers or community members saying "send patches or die" - you will not see that here.
91
+
92
+ It is more important to the community that you are able to contribute.
93
+
94
+ For more information about contributing, see the [CONTRIBUTING](https://github.com/elasticsearch/logstash/blob/master/CONTRIBUTING.md) file.
@@ -0,0 +1 @@
1
+ require "logstash/devutils/rake"
@@ -0,0 +1,38 @@
1
+ input {
2
+ http_poller {
3
+ urls => {
4
+ haproxy => {
5
+ method => get
6
+ url => "http://localhost:9201/haproxy?stats;csv"
7
+ auth => {
8
+ user => "myuser"
9
+ password => "mypass"
10
+ }
11
+ }
12
+ }
13
+ request_timeout => 60
14
+ interval => 60
15
+ codec => "plain" # This is CSV data, so just let it be plain for now
16
+ metadata_target => "_http_poller_metadata"
17
+ }
18
+ }
19
+
20
+ filter {
21
+ split {
22
+ }
23
+
24
+ csv {
25
+ columns => [ pxname,svname,qcur,qmax,scur,smax,slim,stot,bin,bout,dreq,dresp,ereq,econ,eresp,wretr,wredis,status,weight,act,bck,chkfail,chkdown,lastchg,downtime,qlimit,pid,iid,sid,throttle,lbtot,tracked,type,rate,rate_lim,rate_max,check_status,check_code,check_duration,hrsp_1xx,hrsp_2xx,hrsp_3xx,hrsp_4xx,hrsp_5xx,hrsp_other,hanafail,req_rate,req_rate_max,req_tot,cli_abrt,srv_abrt,comp_in,comp_out,comp_byp,comp_rsp,lastsess,last_chk,last_agt,qtime,ctime,rtime,ttime ]
26
+ }
27
+
28
+ # This is a pointless CSV header
29
+ if [pxname] == "# pxname" {
30
+ drop{}
31
+ }
32
+ }
33
+
34
+ output {
35
+ stdout {
36
+ codec => rubydebug
37
+ }
38
+ }
@@ -0,0 +1,28 @@
1
+ input {
2
+ http_poller {
3
+ urls => {
4
+ test1 => "http://localhost:9200"
5
+ test2 => {
6
+ # Supports all options supported by ruby's Manticore HTTP client
7
+ method => get
8
+ url => "http://localhost:9200/_cluster/health"
9
+ headers => {
10
+ Accept => "application/json"
11
+ }
12
+ auth => {
13
+ user => "AzureDiamond"
14
+ pass => "hunter2"
15
+ }
16
+ }
17
+ }
18
+ request_timeout => 60
19
+ interval => 60
20
+ codec => "json"
21
+ # A hash of request metadata info (timing, response headers, etc.) will be sent here
22
+ metadata_target => "_http_poller_metadata"
23
+ }
24
+ }
25
+
26
+ output {
27
+ elasticsearch {}
28
+ }
@@ -0,0 +1,237 @@
1
+ # encoding: utf-8
2
+ require "logstash/inputs/base"
3
+ require "logstash/namespace"
4
+ require "logstash/plugin_mixins/http_client"
5
+ require "socket" # for Socket.gethostname
6
+ require "manticore"
7
+
8
+ # Note. This plugin is a WIP! Things will change and break!
9
+ #
10
+ # Reads from a list of urls and decodes the body of the response with a codec
11
+ # The config should look like this:
12
+ #
13
+ # input {
14
+ # http_poller {
15
+ # urls => {
16
+ # test1 => "http://localhost:9200"
17
+ # test2 => {
18
+ # # Supports all options supported by ruby's Manticore HTTP client
19
+ # method => get
20
+ # url => "http://localhost:9200/_cluster/health"
21
+ # headers => {
22
+ # Accept => "application/json"
23
+ # }
24
+ # auth => {
25
+ # user => "AzureDiamond"
26
+ # password => "hunter2"
27
+ # }
28
+ # }
29
+ # }
30
+ # request_timeout => 60
31
+ # interval => 60
32
+ # codec => "json"
33
+ # # A hash of request metadata info (timing, response headers, etc.) will be sent here
34
+ # metadata_target => "_http_poller_metadata"
35
+ # }
36
+ # }
37
+ #
38
+ # output {
39
+ # stdout {
40
+ # codec => rubydebug
41
+ # }
42
+ # }
43
+
44
+ class LogStash::Inputs::HTTP_Poller < LogStash::Inputs::Base
45
+ include LogStash::PluginMixins::HttpClient
46
+
47
+ config_name "http_poller"
48
+
49
+ default :codec, "json"
50
+
51
+ # A Hash of urls in this format : "name" => "url"
52
+ # The name and the url will be passed in the outputed event
53
+ #
54
+ config :urls, :validate => :hash, :required => true
55
+
56
+ # How often (in seconds) the urls will be called
57
+ config :interval, :validate => :number, :required => true
58
+
59
+ # If you'd like to work with the request/response metadata
60
+ # Set this value to the name of the field you'd like to store a nested
61
+ # hash of metadata.
62
+ config :metadata_target, :validate => :string, :default => '@metadata'
63
+
64
+ public
65
+ def register
66
+ @host = Socket.gethostname.force_encoding(Encoding::UTF_8)
67
+
68
+ @logger.info("Registering http_poller Input", :type => @type,
69
+ :urls => @urls, :interval => @interval, :timeout => @timeout)
70
+
71
+ setup_requests!
72
+ end
73
+
74
+ private
75
+ def setup_requests!
76
+ @requests = Hash[@urls.map {|name, url| [name, normalize_request(url)] }]
77
+ end
78
+
79
+ private
80
+ def normalize_request(url_or_spec)
81
+ if url_or_spec.is_a?(String)
82
+ res = [:get, url_or_spec]
83
+ elsif url_or_spec.is_a?(Hash)
84
+ # The client will expect keys / values
85
+ spec = Hash[url_or_spec.clone.map {|k,v| [k.to_sym, v] }] # symbolize keys
86
+
87
+ # method and url aren't really part of the options, so we pull them out
88
+ method = (spec.delete(:method) || :get).to_sym.downcase
89
+ url = spec.delete(:url)
90
+
91
+ # We need these strings to be keywords!
92
+ spec[:auth] = {user: spec[:auth]["user"], pass: spec[:auth]["password"]} if spec[:auth]
93
+
94
+ res = [method, url, spec]
95
+ else
96
+ raise LogStash::ConfigurationError, "Invalid URL or request spec: '#{url_or_spec}', expected a String or Hash!"
97
+ end
98
+
99
+ validate_request!(url_or_spec, res)
100
+ res
101
+ end
102
+
103
+ private
104
+ def validate_request!(url_or_spec, request)
105
+ method, url, spec = request
106
+
107
+ raise LogStash::ConfigurationError, "Invalid URL #{url}" unless URI::DEFAULT_PARSER.regexp[:ABS_URI].match(url)
108
+
109
+ raise LogStash::ConfigurationError, "No URL provided for request! #{url_or_spec}" unless url
110
+ if spec && spec[:auth]
111
+ if !spec[:auth][:user]
112
+ raise LogStash::ConfigurationError, "Auth was specified, but 'user' was not!"
113
+ end
114
+ if !spec[:auth][:pass]
115
+ raise LogStash::ConfigurationError, "Auth was specified, but 'password' was not!"
116
+ end
117
+ end
118
+
119
+ request
120
+ end
121
+
122
+ public
123
+ def run(queue)
124
+ Stud.interval(@interval) do
125
+ run_once(queue)
126
+ end
127
+ end
128
+
129
+ private
130
+ def run_once(queue)
131
+ @requests.each do |name, request|
132
+ request_async(queue, name, request)
133
+ end
134
+
135
+ # TODO: Remove this once our patch to manticore is accepted. The real callback should work
136
+ # Some exceptions are only returned here! There is no callback,
137
+ # for example, if there is a bad port number.
138
+ # https://github.com/cheald/manticore/issues/22
139
+ # This issue is now fixed, but we'll leave this code in for older versions
140
+ # of manticore. Once the plugin ecosystem is more updated we can kill this.
141
+ client.execute!.each_with_index do |resp, i|
142
+ if resp.is_a?(java.lang.Exception) || resp.is_a?(StandardError)
143
+ name = @requests.keys[i]
144
+ request = @requests[name]
145
+ # We can't report the time here because this is as slow as the slowest request
146
+ # This is all temporary code anyway
147
+ handle_failure(queue, name, request, resp, nil)
148
+ end
149
+ end
150
+ end
151
+
152
+ private
153
+ def request_async(queue, name, request)
154
+ @logger.debug? && @logger.debug("Fetching URL", :name => name, :url => request)
155
+ started = Time.now
156
+
157
+ method, *request_opts = request
158
+ client.async.send(method, *request_opts).
159
+ on_success {|response| handle_success(queue, name, request, response, Time.now - started)}.
160
+ on_failure {|exception|
161
+ handle_failure(queue, name, request, exception, Time.now - started)
162
+ }
163
+ end
164
+
165
+ private
166
+ def handle_success(queue, name, request, response, execution_time)
167
+ @codec.decode(response.body) do |decoded|
168
+ handle_decoded_event(queue, name, request, response, decoded, execution_time)
169
+ end
170
+ end
171
+
172
+ private
173
+ def handle_decoded_event(queue, name, request, response, event, execution_time)
174
+ apply_metadata(event, name, request, response, execution_time)
175
+ queue << event
176
+ rescue StandardError, java.lang.Exception => e
177
+ @logger.error? && @logger.error("Error eventifying response!",
178
+ :exception => e,
179
+ :exception_message => e.message,
180
+ :name => name,
181
+ :url => request,
182
+ :response => response
183
+ )
184
+ end
185
+
186
+ private
187
+ def handle_failure(queue, name, request, exception, execution_time)
188
+ event = LogStash::Event.new
189
+ apply_metadata(event, name, request)
190
+
191
+ event.tag("_http_request_failure")
192
+
193
+ # This is also in the metadata, but we send it anyone because we want this
194
+ # persisted by default, whereas metadata isn't. People don't like mysterious errors
195
+ event["_http_request_failure"] = {
196
+ "url" => @urls[name], # We want the exact parameter they passed in
197
+ "name" => name,
198
+ "error" => exception.to_s,
199
+ "runtime_seconds" => execution_time
200
+ }
201
+
202
+ queue << event
203
+ rescue StandardError, java.lang.Exception => e
204
+ @logger.error? && @logger.error("Cannot read URL or send the error as an event!",
205
+ :exception => exception,
206
+ :exception_message => exception.message,
207
+ :name => name,
208
+ :url => request
209
+ )
210
+ end
211
+
212
+ private
213
+ def apply_metadata(event, name, request, response=nil, execution_time=nil)
214
+ return unless @metadata_target
215
+ event[@metadata_target] = event_metadata(name, request, response, execution_time)
216
+ end
217
+
218
+ private
219
+ def event_metadata(name, request, response=nil, execution_time=nil)
220
+ m = {
221
+ "name" => name,
222
+ "host" => @host,
223
+ "url" => @urls[name]
224
+ }
225
+
226
+ m["runtime_seconds"] = execution_time
227
+
228
+ if response
229
+ m["code"] = response.code
230
+ m["response_headers"] = response.headers
231
+ m["response_message"] = response.message
232
+ m["times_retried"] = response.times_retried
233
+ end
234
+
235
+ m
236
+ end
237
+ end
@@ -0,0 +1,29 @@
1
+ Gem::Specification.new do |s|
2
+ s.name = 'logstash-input-http_poller'
3
+ s.version = '1.0.0'
4
+ s.licenses = ['Apache License (2.0)']
5
+ s.summary = "Poll HTTP endpoints with Logstash."
6
+ s.description = "This gem is a logstash plugin required to be installed on top of the Logstash core pipeline using $LS_HOME/bin/plugin install gemname. This gem is not a stand-alone program."
7
+ s.authors = ["andrewvc"]
8
+ s.homepage = "http://www.elastic.co/guide/en/logstash/current/index.html"
9
+ s.require_paths = ["lib"]
10
+
11
+ # Files
12
+ s.files = `git ls-files`.split($\)
13
+ # Tests
14
+ s.test_files = s.files.grep(%r{^(test|spec|features)/})
15
+
16
+ # Special flag to let us know this is actually a logstash plugin
17
+ s.metadata = { "logstash_plugin" => "true", "logstash_group" => "input" }
18
+
19
+ # Gem dependencies
20
+ s.add_runtime_dependency "logstash-core", '>= 1.5.0', '< 2.0.0'
21
+ s.add_runtime_dependency 'logstash-codec-plain'
22
+ s.add_runtime_dependency 'logstash-codec-json'
23
+ s.add_runtime_dependency 'logstash-mixin-http_client', ">= 1.0.0"
24
+ s.add_runtime_dependency 'stud'
25
+ s.add_runtime_dependency 'manticore'
26
+
27
+ s.add_development_dependency 'logstash-devutils'
28
+ s.add_development_dependency 'flores'
29
+ end
@@ -0,0 +1,294 @@
1
+ require "logstash/devutils/rspec/spec_helper"
2
+ require 'logstash/inputs/http_poller'
3
+ require 'flores/random'
4
+
5
+ describe LogStash::Inputs::HTTP_Poller do
6
+ let(:metadata_target) { "_http_poller_metadata" }
7
+ let(:queue) { Queue.new }
8
+ let(:default_interval) { 5 }
9
+ let(:default_name) { "url1 " }
10
+ let(:default_url) { "http://localhost:1827" }
11
+ let(:default_urls) {
12
+ {
13
+ default_name => default_url
14
+ }
15
+ }
16
+ let(:default_opts) {
17
+ {
18
+ "interval" => default_interval,
19
+ "urls" => default_urls,
20
+ "codec" => "json",
21
+ "metadata_target" => metadata_target
22
+ }
23
+ }
24
+ let(:klass) { LogStash::Inputs::HTTP_Poller }
25
+
26
+ describe "instances" do
27
+ subject { klass.new(default_opts) }
28
+
29
+ before do
30
+ subject.register
31
+ end
32
+
33
+ describe "#run" do
34
+ it "should run at the specified interval" do
35
+ expect(Stud).to receive(:interval).with(default_interval).once
36
+ subject.run(double("queue"))
37
+ end
38
+ end
39
+
40
+ describe "#run_once" do
41
+ it "should issue an async request for each url" do
42
+ default_urls.each do |name, url|
43
+ normalized_url = subject.send(:normalize_request, url)
44
+ expect(subject).to receive(:request_async).with(queue, name, normalized_url).once
45
+ end
46
+
47
+ subject.send(:run_once, queue) # :run_once is a private method
48
+ end
49
+ end
50
+
51
+ describe "normalizing a request spec" do
52
+ shared_examples "a normalized request" do
53
+ it "should set the method correctly" do
54
+ expect(normalized.first).to eql(spec_method.to_sym)
55
+ end
56
+
57
+ it "should set the options to the URL string" do
58
+ expect(normalized[1]).to eql(spec_url)
59
+ end
60
+
61
+ it "should to set additional options correctly" do
62
+ opts = normalized.length > 2 ? normalized[2] : nil
63
+ expect(opts).to eql(spec_opts)
64
+ end
65
+ end
66
+
67
+ let(:normalized) { subject.send(:normalize_request, url) }
68
+
69
+ describe "a string URL" do
70
+ let(:url) { "http://localhost:3000" }
71
+ let(:spec_url) { url }
72
+ let(:spec_method) { :get }
73
+ let(:spec_opts) { nil }
74
+
75
+ include_examples("a normalized request")
76
+ end
77
+
78
+ describe "URL specs" do
79
+ context "with basic opts" do
80
+ let(:spec_url) { "http://localhost:3000" }
81
+ let(:spec_method) { "post" }
82
+ let(:spec_opts) { {:"X-Bender" => "Je Suis Napoleon!"} }
83
+
84
+ let(:url) do
85
+ {
86
+ "url" => spec_url,
87
+ "method" => spec_method,
88
+ }.merge(Hash[spec_opts.map {|k,v| [k.to_s,v]}])
89
+ end
90
+
91
+ include_examples("a normalized request")
92
+ end
93
+
94
+ context "missing an URL" do
95
+ let(:url) { {"method" => "get"} }
96
+
97
+ it "should raise an error" do
98
+ expect { normalized }.to raise_error(LogStash::ConfigurationError)
99
+ end
100
+ end
101
+
102
+ describe "auth" do
103
+ let(:url) { {"url" => "http://localhost", "method" => "get", "auth" => auth} }
104
+
105
+ context "with auth enabled but no pass" do
106
+ let(:auth) { {"user" => "foo"} }
107
+
108
+ it "should raise an error" do
109
+ expect { normalized }.to raise_error(LogStash::ConfigurationError)
110
+ end
111
+ end
112
+
113
+ context "with auth enabled, a path, but no user" do
114
+ let(:url) { {"method" => "get", "auth" => {"password" => "bar"}} }
115
+ it "should raise an error" do
116
+ expect { normalized }.to raise_error(LogStash::ConfigurationError)
117
+ end
118
+ end
119
+ context "with auth enabled correctly" do
120
+ let(:auth) { {"user" => "foo", "password" => "bar"} }
121
+
122
+ it "should raise an error" do
123
+ expect { normalized }.not_to raise_error
124
+ end
125
+
126
+ it "should properly set the auth parameter" do
127
+ expect(normalized[2][:auth]).to eql({:user => auth["user"], :pass => auth["password"]})
128
+ end
129
+ end
130
+ end
131
+ end
132
+ end
133
+ end
134
+
135
+ describe "events" do
136
+ shared_examples("matching metadata") {
137
+ let(:metadata) { event[metadata_target] }
138
+
139
+ it "should have the correct name" do
140
+ expect(metadata["name"]).to eql(name)
141
+ end
142
+
143
+ it "should have the correct url" do
144
+ expect(metadata["url"]).to eql(url)
145
+ end
146
+
147
+ it "should have the correct code" do
148
+ expect(metadata["code"]).to eql(code)
149
+ end
150
+ }
151
+
152
+ shared_examples "unprocessable_requests" do
153
+ let(:poller) { LogStash::Inputs::HTTP_Poller.new(settings) }
154
+ subject(:event) {
155
+ poller.send(:run_once, queue)
156
+ queue.pop(true)
157
+ }
158
+
159
+ before do
160
+ poller.register
161
+ allow(poller).to receive(:handle_failure).and_call_original
162
+ allow(poller).to receive(:handle_success)
163
+ event # materialize the subject
164
+ end
165
+
166
+ it "should enqueue a message" do
167
+ expect(event).to be_a(LogStash::Event)
168
+ end
169
+
170
+ it "should enqueue a message with '_http_request_failure' set" do
171
+ expect(event["_http_request_failure"]).to be_a(Hash)
172
+ end
173
+
174
+ it "should tag the event with '_http_request_failure'" do
175
+ expect(event["tags"]).to include('_http_request_failure')
176
+ end
177
+
178
+ it "should invoke handle failure exactly once" do
179
+ expect(poller).to have_received(:handle_failure).once
180
+ end
181
+
182
+ it "should not invoke handle success at all" do
183
+ expect(poller).not_to have_received(:handle_success)
184
+ end
185
+
186
+ include_examples("matching metadata")
187
+ end
188
+
189
+ context "with a non responsive server" do
190
+ context "due to a non-existant host" do # Fail with handlers
191
+ let(:name) { default_name }
192
+ let(:url) { "http://thouetnhoeu89ueoueohtueohtneuohn" }
193
+ let(:code) { nil } # no response expected
194
+
195
+ let(:settings) { default_opts.merge("urls" => { name => url}) }
196
+
197
+ include_examples("unprocessable_requests")
198
+ end
199
+
200
+ context "due to a bogus port number" do # fail with return?
201
+ let(:invalid_port) { Flores::Random.integer(65536..1000000) }
202
+
203
+ let(:name) { default_name }
204
+ let(:url) { "http://127.0.0.1:#{invalid_port}" }
205
+ let(:settings) { default_opts.merge("urls" => {name => url}) }
206
+ let(:code) { nil } # No response expected
207
+
208
+ include_examples("unprocessable_requests")
209
+ end
210
+ end
211
+
212
+
213
+ describe "a valid request and decoded response" do
214
+ let(:payload) { {"a" => 2, "hello" => ["a", "b", "c"]} }
215
+ let(:opts) { default_opts }
216
+ let(:instance) {
217
+ klass.new(opts)
218
+ }
219
+ let(:name) { default_name }
220
+ let(:url) { default_url }
221
+ let(:code) { 202 }
222
+
223
+ subject(:event) {
224
+ queue.pop(true)
225
+ }
226
+
227
+ before do
228
+ instance.register
229
+ u = url.is_a?(Hash) ? url["url"] : url # handle both complex specs and simple string URLs
230
+ instance.client.stub(u,
231
+ :body => LogStash::Json.dump(payload),
232
+ :code => code
233
+ )
234
+ instance.send(:run_once, queue)
235
+ end
236
+
237
+ it "should have a matching message" do
238
+ expect(event.to_hash).to include(payload)
239
+ end
240
+
241
+ include_examples("matching metadata")
242
+
243
+ context "with metadata omitted" do
244
+ let(:opts) {
245
+ opts = default_opts.clone
246
+ opts.delete("metadata_target")
247
+ opts
248
+ }
249
+
250
+ it "should not have any metadata on the event" do
251
+ instance.send(:run_once, queue)
252
+ expect(event[metadata_target]).to be_nil
253
+ end
254
+ end
255
+
256
+ context "with a complex URL spec" do
257
+ let(:url) {
258
+ {
259
+ "method" => "get",
260
+ "url" => default_url,
261
+ "headers" => {
262
+ "X-Fry" => "I'm having one of those things, like a headache, with pictures..."
263
+ }
264
+ }
265
+ }
266
+ let(:opts) {
267
+ {
268
+ "interval" => default_interval,
269
+ "urls" => {
270
+ default_name => url
271
+ },
272
+ "codec" => "json",
273
+ "metadata_target" => metadata_target
274
+ }
275
+ }
276
+
277
+ include_examples("matching metadata")
278
+
279
+ it "should have a matching message" do
280
+ expect(event.to_hash).to include(payload)
281
+ end
282
+ end
283
+ end
284
+ end
285
+
286
+
287
+
288
+
289
+
290
+
291
+
292
+
293
+
294
+ end
metadata ADDED
@@ -0,0 +1,176 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: logstash-input-http_poller
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - andrewvc
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2015-07-15 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: logstash-core
15
+ version_requirements: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - '>='
18
+ - !ruby/object:Gem::Version
19
+ version: 1.5.0
20
+ - - <
21
+ - !ruby/object:Gem::Version
22
+ version: 2.0.0
23
+ requirement: !ruby/object:Gem::Requirement
24
+ requirements:
25
+ - - '>='
26
+ - !ruby/object:Gem::Version
27
+ version: 1.5.0
28
+ - - <
29
+ - !ruby/object:Gem::Version
30
+ version: 2.0.0
31
+ prerelease: false
32
+ type: :runtime
33
+ - !ruby/object:Gem::Dependency
34
+ name: logstash-codec-plain
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - '>='
38
+ - !ruby/object:Gem::Version
39
+ version: '0'
40
+ requirement: !ruby/object:Gem::Requirement
41
+ requirements:
42
+ - - '>='
43
+ - !ruby/object:Gem::Version
44
+ version: '0'
45
+ prerelease: false
46
+ type: :runtime
47
+ - !ruby/object:Gem::Dependency
48
+ name: logstash-codec-json
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - '>='
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ requirement: !ruby/object:Gem::Requirement
55
+ requirements:
56
+ - - '>='
57
+ - !ruby/object:Gem::Version
58
+ version: '0'
59
+ prerelease: false
60
+ type: :runtime
61
+ - !ruby/object:Gem::Dependency
62
+ name: logstash-mixin-http_client
63
+ version_requirements: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - '>='
66
+ - !ruby/object:Gem::Version
67
+ version: 1.0.0
68
+ requirement: !ruby/object:Gem::Requirement
69
+ requirements:
70
+ - - '>='
71
+ - !ruby/object:Gem::Version
72
+ version: 1.0.0
73
+ prerelease: false
74
+ type: :runtime
75
+ - !ruby/object:Gem::Dependency
76
+ name: stud
77
+ version_requirements: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - '>='
80
+ - !ruby/object:Gem::Version
81
+ version: '0'
82
+ requirement: !ruby/object:Gem::Requirement
83
+ requirements:
84
+ - - '>='
85
+ - !ruby/object:Gem::Version
86
+ version: '0'
87
+ prerelease: false
88
+ type: :runtime
89
+ - !ruby/object:Gem::Dependency
90
+ name: manticore
91
+ version_requirements: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - '>='
94
+ - !ruby/object:Gem::Version
95
+ version: '0'
96
+ requirement: !ruby/object:Gem::Requirement
97
+ requirements:
98
+ - - '>='
99
+ - !ruby/object:Gem::Version
100
+ version: '0'
101
+ prerelease: false
102
+ type: :runtime
103
+ - !ruby/object:Gem::Dependency
104
+ name: logstash-devutils
105
+ version_requirements: !ruby/object:Gem::Requirement
106
+ requirements:
107
+ - - '>='
108
+ - !ruby/object:Gem::Version
109
+ version: '0'
110
+ requirement: !ruby/object:Gem::Requirement
111
+ requirements:
112
+ - - '>='
113
+ - !ruby/object:Gem::Version
114
+ version: '0'
115
+ prerelease: false
116
+ type: :development
117
+ - !ruby/object:Gem::Dependency
118
+ name: flores
119
+ version_requirements: !ruby/object:Gem::Requirement
120
+ requirements:
121
+ - - '>='
122
+ - !ruby/object:Gem::Version
123
+ version: '0'
124
+ requirement: !ruby/object:Gem::Requirement
125
+ requirements:
126
+ - - '>='
127
+ - !ruby/object:Gem::Version
128
+ version: '0'
129
+ prerelease: false
130
+ type: :development
131
+ description: This gem is a logstash plugin required to be installed on top of the Logstash core pipeline using $LS_HOME/bin/plugin install gemname. This gem is not a stand-alone program.
132
+ email:
133
+ executables: []
134
+ extensions: []
135
+ extra_rdoc_files: []
136
+ files:
137
+ - .gitignore
138
+ - CHANGELOG.md
139
+ - DEVELOPER.md
140
+ - Gemfile
141
+ - LICENSE
142
+ - README.md
143
+ - Rakefile
144
+ - examples/ha_proxy.conf
145
+ - examples/local_elasticsearch.conf
146
+ - lib/logstash/inputs/http_poller.rb
147
+ - logstash-input-http_poller.gemspec
148
+ - spec/inputs/http_poller_spec.rb
149
+ homepage: http://www.elastic.co/guide/en/logstash/current/index.html
150
+ licenses:
151
+ - Apache License (2.0)
152
+ metadata:
153
+ logstash_plugin: 'true'
154
+ logstash_group: input
155
+ post_install_message:
156
+ rdoc_options: []
157
+ require_paths:
158
+ - lib
159
+ required_ruby_version: !ruby/object:Gem::Requirement
160
+ requirements:
161
+ - - '>='
162
+ - !ruby/object:Gem::Version
163
+ version: '0'
164
+ required_rubygems_version: !ruby/object:Gem::Requirement
165
+ requirements:
166
+ - - '>='
167
+ - !ruby/object:Gem::Version
168
+ version: '0'
169
+ requirements: []
170
+ rubyforge_project:
171
+ rubygems_version: 2.1.9
172
+ signing_key:
173
+ specification_version: 4
174
+ summary: Poll HTTP endpoints with Logstash.
175
+ test_files:
176
+ - spec/inputs/http_poller_spec.rb