logstash-input-openwhisk 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: 9db13f2d4ca718f1a1535f0eddad8e2c85d91075
4
+ data.tar.gz: e7c52b01737a328cb0da22e0181ecd5e6ac8cc8a
5
+ SHA512:
6
+ metadata.gz: 64caf68777249d6c82830327f9e8d2a171d7cfd0db9f158816729e07973e53ea169953921b7055de2cb6a1c507e5c308979fca9e8323bc4b12bb9d87b17a8541
7
+ data.tar.gz: c10fa9d69965376eb088b1c41673ccbaf7699e87bc0cf61e9fc88f496b412a4331e652d048d90b9f7650a0e8fcf7a0308588cfe2ccc795e716e03b7a82f10d9e
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in logstash-mass_effect.gemspec
4
+ 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.md ADDED
@@ -0,0 +1,106 @@
1
+ # Logstash HTTP input plugin
2
+
3
+ [![Travis Build Status](https://travis-ci.org/logstash-plugins/logstash-input-http_poller.svg)](https://travis-ci.org/logstash-plugins/logstash-input-http_poller)
4
+
5
+ This plugin is based off [logstash-input-rest](https://github.com/maximede/logstash-input-rest) by @maximede.
6
+
7
+ This [Logstash](https://github.com/elastic/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.
8
+
9
+ 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.
10
+
11
+ 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.
12
+
13
+ ## Config Example
14
+
15
+ For config examples see `http_poller.rb` in `lib/logstash/inputs/` in this repo.
16
+
17
+ ## Documentation
18
+
19
+ 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.elastic.co/guide/en/logstash/current/).
20
+
21
+ - For formatting code or config example, you can use the asciidoc `[source,ruby]` directive
22
+ - For more asciidoc formatting tips, see the excellent reference here https://github.com/elastic/docs#asciidoc-guide
23
+
24
+ ## Need Help?
25
+
26
+ Need help? Try #logstash on freenode IRC or the https://discuss.elastic.co/c/logstash discussion forum.
27
+
28
+ ## Developing
29
+
30
+ ### 1. Plugin Developement and Testing
31
+
32
+ #### Code
33
+ - To get started, you'll need JRuby with the Bundler gem installed.
34
+
35
+ - 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).
36
+
37
+ - Install dependencies
38
+ ```sh
39
+ bundle install
40
+ ```
41
+
42
+ #### Test
43
+
44
+ - Update your dependencies
45
+
46
+ ```sh
47
+ bundle install
48
+ ```
49
+
50
+ - Run tests
51
+
52
+ ```sh
53
+ bundle exec rspec
54
+ ```
55
+
56
+ ### 2. Running your unpublished Plugin in Logstash
57
+
58
+ #### 2.1 Run in a local Logstash clone
59
+
60
+ - Edit Logstash `Gemfile` and add the local plugin path, for example:
61
+ ```ruby
62
+ gem "logstash-filter-awesome", :path => "/your/local/logstash-filter-awesome"
63
+ ```
64
+ - Install plugin
65
+ ```sh
66
+ # Logstash 2.3 and higher
67
+ bin/logstash-plugin install --no-verify
68
+
69
+ # Prior to Logstash 2.3
70
+ bin/plugin install --no-verify
71
+
72
+ ```
73
+ - Run Logstash with your plugin
74
+ ```sh
75
+ bin/logstash -e 'filter {awesome {}}'
76
+ ```
77
+ At this point any modifications to the plugin code will be applied to this local Logstash setup. After modifying the plugin, simply rerun Logstash.
78
+
79
+ #### 2.2 Run in an installed Logstash
80
+
81
+ 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:
82
+
83
+ - Build your plugin gem
84
+ ```sh
85
+ gem build logstash-filter-awesome.gemspec
86
+ ```
87
+ - Install the plugin from the Logstash home
88
+ ```sh
89
+ # Logstash 2.3 and higher
90
+ bin/logstash-plugin install --no-verify
91
+
92
+ # Prior to Logstash 2.3
93
+ bin/plugin install --no-verify
94
+
95
+ ```
96
+ - Start Logstash and proceed to test the plugin
97
+
98
+ ## Contributing
99
+
100
+ All contributions are welcome: ideas, patches, documentation, bug reports, complaints, and even something you drew up on a napkin.
101
+
102
+ 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.
103
+
104
+ It is more important to the community that you are able to contribute.
105
+
106
+ For more information about contributing, see the [CONTRIBUTING](https://github.com/elastic/logstash/blob/master/CONTRIBUTING.md) file.
@@ -0,0 +1,291 @@
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
+ require "rufus/scheduler"
8
+
9
+ # This Logstash input plugin allows you to drain OpenWhisk Activation logs, decoding the output into event(s), and
10
+ # send them on their merry way. Using the OpenWhisk platform API, we poll the activation logs API according to the config schedule.
11
+ # This plugin borrows heavily from the HTTP Poller input plugin.
12
+ #
13
+ # ==== Example
14
+ # Drain logs from an OpenWhisk platform instance.
15
+ # The config should look like this:
16
+ #
17
+ # [source,ruby]
18
+ # ----------------------------------
19
+ # input {
20
+ # openwhisk {
21
+ # # Mandatory Configuration Parameters
22
+ # hostname => "openwhisk.ng.bluemix.net"
23
+ # username => "sample_user@email.com"
24
+ # password => "some_password"
25
+ # # Supports "cron", "every", "at" and "in" schedules by rufus scheduler
26
+ # schedule => { cron => "* * * * * UTC"}
27
+ #
28
+ # # Optional Configuration Parameters
29
+ # # Namespace is optional, defaults to user's default namespace.
30
+ # namespace => ""
31
+ # request_timeout => 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
+ #
45
+
46
+ class LogStash::Inputs::OpenWhisk < LogStash::Inputs::Base
47
+ include LogStash::PluginMixins::HttpClient
48
+
49
+ config_name "openwhisk"
50
+
51
+ default :codec, "json"
52
+
53
+ # OpenWhisk Platform Parameters
54
+ config :hostname, :validate => :string, :required => true
55
+ config :username, :validate => :string, :required => true
56
+ config :password, :validate => :string, :required => true
57
+
58
+ # Optional OpenWhisk namespace, defaults to user account namespace.
59
+ config :namespace, :validate => :string, :default => '_'
60
+
61
+ # How often (in seconds) the urls will be called
62
+ # DEPRECATED. Use 'schedule' option instead.
63
+ # If both interval and schedule options are specified, interval
64
+ # option takes higher precedence
65
+ config :interval, :validate => :number, :deprecated => true
66
+
67
+ # Schedule of when to periodically poll from the urls
68
+ # Format: A hash with
69
+ # + key: "cron" | "every" | "in" | "at"
70
+ # + value: string
71
+ # Examples:
72
+ # a) { "every" => "1h" }
73
+ # b) { "cron" => "* * * * * UTC" }
74
+ # See: rufus/scheduler for details about different schedule options and value string format
75
+ config :schedule, :validate => :hash
76
+
77
+ # Define the target field for placing the received data. If this setting is omitted, the data will be stored at the root (top level) of the event.
78
+ config :target, :validate => :string
79
+
80
+ # If you'd like to work with the request/response metadata.
81
+ # Set this value to the name of the field you'd like to store a nested
82
+ # hash of metadata.
83
+ config :metadata_target, :validate => :string, :default => '@metadata'
84
+
85
+ public
86
+ Schedule_types = %w(cron every at in)
87
+ def register
88
+ @host = Socket.gethostname.force_encoding(Encoding::UTF_8)
89
+
90
+ @logger.info("Registering openwhisk Input", :type => @type,
91
+ :hostname=> @hostname, :interval => @interval, :schedule => @schedule, :timeout => @timeout)
92
+
93
+ # we will start polling for logs since the current epoch
94
+ @logs_since = Time.now.to_i * 1000
95
+
96
+ # activation ids from previous poll used to control what is indexed,
97
+ # we might have overlapping results and don't want to index the same
98
+ # activations twice.
99
+ @activation_ids = Set.new
100
+ end
101
+
102
+ def stop
103
+ Stud.stop!(@interval_thread) if @interval_thread
104
+ @scheduler.stop if @scheduler
105
+ end
106
+
107
+ # generate HTTP request options for current platform host.
108
+ private
109
+ def construct_request(opts)
110
+ url = "https://#{opts['hostname']}/api/v1/namespaces/#{opts['namespace']}/activations"
111
+ auth = {user: opts['username'], pass: opts['password']}
112
+ query = {docs: true, limit: 0, skip: 0, since: @logs_since}
113
+ res = [:get, url, {:auth => auth, :query => query}]
114
+ end
115
+
116
+ public
117
+ def run(queue)
118
+ #interval or schedule must be provided. Must be exclusively either one. Not neither. Not both.
119
+ raise LogStash::ConfigurationError, "Invalid config. Neither interval nor schedule was specified." \
120
+ unless @interval || @schedule
121
+ raise LogStash::ConfigurationError, "Invalid config. Specify only interval or schedule. Not both." \
122
+ if @interval && @schedule
123
+
124
+ if @interval
125
+ setup_interval(queue)
126
+ elsif @schedule
127
+ setup_schedule(queue)
128
+ else
129
+ #should not reach here
130
+ raise LogStash::ConfigurationError, "Invalid config. Neither interval nor schedule was specified."
131
+ end
132
+ end
133
+
134
+ private
135
+ def setup_interval(queue)
136
+ @interval_thread = Thread.current
137
+ Stud.interval(@interval) do
138
+ run_once(queue)
139
+ end
140
+ end
141
+
142
+ def setup_schedule(queue)
143
+ #schedule hash must contain exactly one of the allowed keys
144
+ msg_invalid_schedule = "Invalid config. schedule hash must contain " +
145
+ "exactly one of the following keys - cron, at, every or in"
146
+ raise Logstash::ConfigurationError, msg_invalid_schedule if @schedule.keys.length !=1
147
+ schedule_type = @schedule.keys.first
148
+ schedule_value = @schedule[schedule_type]
149
+ raise LogStash::ConfigurationError, msg_invalid_schedule unless Schedule_types.include?(schedule_type)
150
+
151
+ @scheduler = Rufus::Scheduler.new(:max_work_threads => 1)
152
+ #as of v3.0.9, :first_in => :now doesn't work. Use the following workaround instead
153
+ opts = schedule_type == "every" ? { :first_in => 0.01 } : {}
154
+ @scheduler.send(schedule_type, schedule_value, opts) { run_once(queue) }
155
+ @scheduler.join
156
+ end
157
+
158
+ def run_once(queue)
159
+ request = construct_request({"hostname" => @hostname, "username" => @username, "password" => @password, "namespace" => @namespace})
160
+
161
+ request_async(queue, "openwhisk", request)
162
+ client.execute!
163
+ end
164
+
165
+ private
166
+ def request_async(queue, name, request)
167
+ @logger.debug? && @logger.debug("Fetching URL", :name => name, :url => request)
168
+ started = Time.now
169
+
170
+ method, *request_opts = request
171
+ client.async.send(method, *request_opts).
172
+ on_success {|response| handle_success(queue, name, request, response, Time.now - started)}.
173
+ on_failure {|exception|
174
+ handle_failure(queue, name, request, exception, Time.now - started)
175
+ }
176
+ end
177
+
178
+ private
179
+ def handle_success(queue, name, request, response, execution_time)
180
+ activation_ids = Set.new
181
+
182
+ @codec.decode(response.body) do |decoded|
183
+ activation_id = decoded.to_hash["activationId"]
184
+
185
+ ## ignore results we have previously seen
186
+ if !@activation_ids.include?(activation_id)
187
+ event = @target ? LogStash::Event.new(@target => decoded.to_hash) : decoded
188
+ update_logs_since(decoded.to_hash["end"])
189
+ handle_decoded_event(queue, name, request, response, event, execution_time)
190
+ end
191
+
192
+ activation_ids.add(activation_id)
193
+ end
194
+
195
+ @activation_ids = activation_ids
196
+ end
197
+
198
+ # updates the query parameter for the next request
199
+ # based upon the last activation's end time.
200
+ private
201
+ def update_logs_since(ms_since_epoch)
202
+ # actions have a maximum timeout for five minutes
203
+ max_action_time_ms = 5 * 60 * 1000
204
+ next_logs_since = ms_since_epoch - max_action_time_ms
205
+
206
+ if (next_logs_since > @logs_since)
207
+ @logs_since = next_logs_since
208
+ end
209
+ end
210
+
211
+ private
212
+ def handle_decoded_event(queue, name, request, response, event, execution_time)
213
+ apply_metadata(event, name, request, response, execution_time)
214
+ decorate(event)
215
+ queue << event
216
+ rescue StandardError, java.lang.Exception => e
217
+ @logger.error? && @logger.error("Error eventifying response!",
218
+ :exception => e,
219
+ :exception_message => e.message,
220
+ :name => name,
221
+ :url => request,
222
+ :response => response
223
+ )
224
+ end
225
+
226
+ private
227
+ # Beware, on old versions of manticore some uncommon failures are not handled
228
+ def handle_failure(queue, name, request, exception, execution_time)
229
+ event = LogStash::Event.new
230
+ apply_metadata(event, name, request)
231
+
232
+ event.tag("_http_request_failure")
233
+
234
+ # This is also in the metadata, but we send it anyone because we want this
235
+ # persisted by default, whereas metadata isn't. People don't like mysterious errors
236
+ event.set("http_request_failure", {
237
+ "request" => structure_request(request),
238
+ "name" => name,
239
+ "error" => exception.to_s,
240
+ "backtrace" => exception.backtrace,
241
+ "runtime_seconds" => execution_time
242
+ })
243
+
244
+ queue << event
245
+ rescue StandardError, java.lang.Exception => e
246
+ @logger.error? && @logger.error("Cannot read URL or send the error as an event!",
247
+ :exception => e,
248
+ :exception_message => e.message,
249
+ :exception_backtrace => e.backtrace,
250
+ :name => name,
251
+ :url => request
252
+ )
253
+ end
254
+
255
+ private
256
+ def apply_metadata(event, name, request, response=nil, execution_time=nil)
257
+ return unless @metadata_target
258
+ event.set(@metadata_target, event_metadata(name, request, response, execution_time))
259
+ end
260
+
261
+ private
262
+ def event_metadata(name, request, response=nil, execution_time=nil)
263
+ m = {
264
+ "name" => name,
265
+ "hostname" => @hostname,
266
+ "request" => structure_request(request),
267
+ }
268
+
269
+ m["runtime_seconds"] = execution_time
270
+
271
+ if response
272
+ m["code"] = response.code
273
+ m["response_headers"] = response.headers
274
+ m["response_message"] = response.message
275
+ m["times_retried"] = response.times_retried
276
+ end
277
+
278
+ m
279
+ end
280
+
281
+ private
282
+ # Turn [method, url, spec] requests into a hash for friendlier logging / ES indexing
283
+ def structure_request(request)
284
+ method, url, spec = request
285
+ # Flatten everything into the 'spec' hash, also stringify any keys to normalize
286
+ Hash[(spec||{}).merge({
287
+ "method" => method.to_s,
288
+ "url" => url,
289
+ }).map {|k,v| [k.to_s,v] }]
290
+ end
291
+ end