logstash-input-ow 0.1.2

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