logstash-filter-elasticsearch 3.5.0 → 3.8.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 57bc6bc825a1866b1ecf39eb35bcab5e062dfb73f7b1e7590feb4fe51358b2c9
4
- data.tar.gz: 48df2bb55103e2fb6196ec8679f1b48ce70742f43dcd9ab3c5ff257637ccdda8
3
+ metadata.gz: 77145aca4fea09d207fbe7efb17c271760fb7fd7eaf3c1411c08298959a54767
4
+ data.tar.gz: 599f7a6cfdc37a5f7f867b44411f82438a53a17fb8ed9bbbfe8c34f4aa9496d2
5
5
  SHA512:
6
- metadata.gz: e93655c43a05df8d1f7cf261ff552a875cb765111903cf9bc4903e77cb423329f346f1b67d949b6cae24c85872b8ea45a7a08e7ce812d48ab93117d575236eef
7
- data.tar.gz: b3dbca71043c7cbb6ef904e19e30b88dd6e974d92c0fdf77eae52d90c1d41151bdc9b0ef4c9cc93fa8c97937dc31e30c6570a62a8343d693a0b1d00bb2d4fa6a
6
+ metadata.gz: 6c764d630938fd180399b4d0f113bb3af17b5db41594838d6e4b109b280457443c97920999c74f62c0518bc69780bc8c8569383477e576dc80e6433ccbab3c02
7
+ data.tar.gz: 998fbdba7ede11d6ab4ab74c5620076f730490cb37831041fa947540917d7da519f9ff0b75989445f5a1a25937dc5e04fc7a33afa56ebec6cc8234d48b7e9444
@@ -1,3 +1,21 @@
1
+ ## 3.8.0
2
+ - Added api_key support [#132](https://github.com/logstash-plugins/logstash-filter-elasticsearch/pull/132)
3
+
4
+ ## 3.7.2
5
+ - [DOC] Removed outdated compatibility notice [#131](https://github.com/logstash-plugins/logstash-filter-elasticsearch/pull/131)
6
+
7
+ ## 3.7.1
8
+ - Fix: solves an issue where non-ascii unicode values in a template were not handled correctly [#128](https://github.com/logstash-plugins/logstash-filter-elasticsearch/pull/128)
9
+
10
+ ## 3.7.0
11
+ - Feat: support cloud_id / cloud_auth configuration [#122](https://github.com/logstash-plugins/logstash-filter-elasticsearch/pull/122)
12
+
13
+ ## 3.6.1
14
+ - Loosen restrictions on Elasticsearch gem ([#120](https://github.com/logstash-plugins/logstash-filter-elasticsearch/pull/120))
15
+
16
+ ## 3.6.0
17
+ - Add support for extracting hits total from Elasticsearch 7.x responses
18
+
1
19
  ## 3.5.0
2
20
  - Added connection check during register to avoid failures during processing
3
21
  - Changed Elasticsearch Client transport to use Manticore
@@ -9,6 +9,7 @@ Contributors:
9
9
  * Richard Pijnenburg (electrical)
10
10
  * Suyog Rao (suyograo)
11
11
  * Adrian Solom (addrians)
12
+ * Colin Surprenant (colinsurprenant)
12
13
 
13
14
  Note: If you've sent us patches, bug reports, or otherwise contributed to
14
15
  Logstash, and you aren't on the list above and want to be, please let us know
data/LICENSE CHANGED
@@ -1,13 +1,202 @@
1
- Copyright (c) 2012-2018 Elasticsearch <http://www.elastic.co>
2
1
 
3
- Licensed under the Apache License, Version 2.0 (the "License");
4
- you may not use this file except in compliance with the License.
5
- You may obtain a copy of the License at
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
6
5
 
7
- http://www.apache.org/licenses/LICENSE-2.0
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
7
 
9
- Unless required by applicable law or agreed to in writing, software
10
- distributed under the License is distributed on an "AS IS" BASIS,
11
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- See the License for the specific language governing permissions and
13
- limitations under the License.
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2020 Elastic and contributors
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -20,18 +20,8 @@ include::{include_path}/plugin_header.asciidoc[]
20
20
 
21
21
  ==== Description
22
22
 
23
- .Compatibility Note
24
- [NOTE]
25
- ================================================================================
26
- Starting with Elasticsearch 5.3, there's an {ref}/modules-http.html[HTTP setting]
27
- called `http.content_type.required`. If this option is set to `true`, and you
28
- are using Logstash 2.4 through 5.2, you need to update the Elasticsearch filter
29
- plugin to version 3.1.1 or higher.
30
-
31
- ================================================================================
32
-
33
23
  Search Elasticsearch for a previous log event and copy some fields from it
34
- into the current event. Below are two complete examples of how this filter might
24
+ into the current event. Below are two complete examples of how this filter might
35
25
  be used.
36
26
 
37
27
  The first example uses the legacy 'query' parameter where the user is limited to an Elasticsearch query_string.
@@ -111,6 +101,14 @@ Notice also that when you use `query_template`, the Logstash attributes `result_
111
101
  and `sort` will be ignored. They should be specified directly in the JSON
112
102
  template, as shown in the example above.
113
103
 
104
+ [id="plugins-{type}s-{plugin}-auth"]
105
+ ==== Authentication
106
+
107
+ Authentication to a secure Elasticsearch cluster is possible using _one_ of the following options:
108
+
109
+ * <<plugins-{type}s-{plugin}-user>> AND <<plugins-{type}s-{plugin}-password>>
110
+ * <<plugins-{type}s-{plugin}-cloud_auth>>
111
+ * <<plugins-{type}s-{plugin}-api_key>>
114
112
 
115
113
  [id="plugins-{type}s-{plugin}-options"]
116
114
  ==== Elasticsearch Filter Configuration Options
@@ -121,7 +119,10 @@ This plugin supports the following configuration options plus the <
121
119
  |=======================================================================
122
120
  |Setting |Input type|Required
123
121
  | <<plugins-{type}s-{plugin}-aggregation_fields>> |<<hash,hash>>|No
122
+ | <<plugins-{type}s-{plugin}-api_key>> |<<password,password>>|No
124
123
  | <<plugins-{type}s-{plugin}-ca_file>> |a valid filesystem path|No
124
+ | <<plugins-{type}s-{plugin}-cloud_auth>> |<<password,password>>|No
125
+ | <<plugins-{type}s-{plugin}-cloud_id>> |<<string,string>>|No
125
126
  | <<plugins-{type}s-{plugin}-docinfo_fields>> |<<hash,hash>>|No
126
127
  | <<plugins-{type}s-{plugin}-enable_sort>> |<<boolean,boolean>>|No
127
128
  | <<plugins-{type}s-{plugin}-fields>> |<<array,array>>|No
@@ -160,6 +161,16 @@ Example:
160
161
  }
161
162
  }
162
163
 
164
+ [id="plugins-{type}s-{plugin}-api_key"]
165
+ ===== `api_key`
166
+
167
+ * Value type is <<password,password>>
168
+ * There is no default value for this setting.
169
+
170
+ Authenticate using Elasticsearch API key. Note that this option also requires enabling the `ssl` option.
171
+
172
+ Format is `id:api_key` where `id` and `api_key` are as returned by the Elasticsearch https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key.html[Create API key API].
173
+
163
174
  [id="plugins-{type}s-{plugin}-ca_file"]
164
175
  ===== `ca_file`
165
176
 
@@ -299,6 +310,26 @@ Tags the event on failure to look up previous log event information. This can be
299
310
 
300
311
  Basic Auth - username
301
312
 
313
+ [id="plugins-{type}s-{plugin}-cloud_auth"]
314
+ ===== `cloud_auth`
315
+
316
+ * Value type is <<password,password>>
317
+ * There is no default value for this setting.
318
+
319
+ Cloud authentication string ("<username>:<password>" format) is an alternative for the `user`/`password` pair.
320
+
321
+ For more info, check out the https://www.elastic.co/guide/en/logstash/current/connecting-to-cloud.html#_cloud_auth[Logstash-to-Cloud documentation]
322
+
323
+ [id="plugins-{type}s-{plugin}-cloud_id"]
324
+ ===== `cloud_id`
325
+
326
+ * Value type is <<string,string>>
327
+ * There is no default value for this setting.
328
+
329
+ Cloud ID, from the Elastic Cloud web console. If set `hosts` should not be used.
330
+
331
+ For more info, check out the https://www.elastic.co/guide/en/logstash/current/connecting-to-cloud.html#_cloud_id[Logstash-to-Cloud documentation]
332
+
302
333
 
303
334
 
304
335
  [id="plugins-{type}s-{plugin}-common-options"]
@@ -3,15 +3,18 @@ require "logstash/filters/base"
3
3
  require "logstash/namespace"
4
4
  require_relative "elasticsearch/client"
5
5
  require "logstash/json"
6
+ require "logstash/util/safe_uri"
6
7
  java_import "java.util.concurrent.ConcurrentHashMap"
7
8
 
8
9
 
9
10
  class LogStash::Filters::Elasticsearch < LogStash::Filters::Base
10
11
  config_name "elasticsearch"
11
12
 
13
+ DEFAULT_HOST = ::LogStash::Util::SafeURI.new("//localhost:9200")
14
+
12
15
  # List of elasticsearch hosts to use for querying.
13
- config :hosts, :validate => :array, :default => [ "localhost:9200" ]
14
-
16
+ config :hosts, :validate => :array, :default => [ DEFAULT_HOST ]
17
+
15
18
  # Comma-delimited list of index names to search; use `_all` or empty string to perform the operation on all indices.
16
19
  # Field substitution (e.g. `index-name-%{date_field}`) is available
17
20
  config :index, :validate => :string, :default => ""
@@ -42,6 +45,20 @@ class LogStash::Filters::Elasticsearch < LogStash::Filters::Base
42
45
  # Basic Auth - password
43
46
  config :password, :validate => :password
44
47
 
48
+ # Cloud ID, from the Elastic Cloud web console. If set `hosts` should not be used.
49
+ #
50
+ # For more info, check out the https://www.elastic.co/guide/en/logstash/current/connecting-to-cloud.html#_cloud_id[Logstash-to-Cloud documentation]
51
+ config :cloud_id, :validate => :string
52
+
53
+ # Cloud authentication string ("<username>:<password>" format) is an alternative for the `user`/`password` configuration.
54
+ #
55
+ # For more info, check out the https://www.elastic.co/guide/en/logstash/current/connecting-to-cloud.html#_cloud_auth[Logstash-to-Cloud documentation]
56
+ config :cloud_auth, :validate => :password
57
+
58
+ # Authenticate using Elasticsearch API key.
59
+ # format is id:api_key (as returned by https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-create-api-key.html[Create API key])
60
+ config :api_key, :validate => :password
61
+
45
62
  # SSL
46
63
  config :ssl, :validate => :boolean, :default => false
47
64
 
@@ -67,10 +84,16 @@ class LogStash::Filters::Elasticsearch < LogStash::Filters::Base
67
84
  if File.zero?(@query_template)
68
85
  raise "template is empty"
69
86
  end
70
- file = File.open(@query_template, "rb")
87
+ file = File.open(@query_template, 'r')
71
88
  @query_dsl = file.read
72
89
  end
73
90
 
91
+ validate_authentication
92
+ fill_user_password_from_cloud_auth
93
+ fill_hosts_from_cloud_id
94
+
95
+ @hosts = Array(@hosts).map { |host| host.to_s } # for ES client URI#to_s
96
+
74
97
  test_connection!
75
98
  end # def register
76
99
 
@@ -94,7 +117,7 @@ class LogStash::Filters::Elasticsearch < LogStash::Filters::Base
94
117
  results = get_client.search(params)
95
118
  raise "Elasticsearch query error: #{results["_shards"]["failures"]}" if results["_shards"].include? "failures"
96
119
 
97
- event.set("[@metadata][total_hits]", results['hits']['total'])
120
+ event.set("[@metadata][total_hits]", extract_total_from_hits(results['hits']))
98
121
 
99
122
  resultsHits = results["hits"]["hits"]
100
123
  if !resultsHits.nil? && !resultsHits.empty?
@@ -138,17 +161,21 @@ class LogStash::Filters::Elasticsearch < LogStash::Filters::Base
138
161
  end # def filter
139
162
 
140
163
  private
164
+
141
165
  def client_options
142
166
  {
167
+ :user => @user,
168
+ :password => @password,
169
+ :api_key => @api_key,
143
170
  :ssl => @ssl,
144
- :hosts => @hosts,
145
171
  :ca_file => @ca_file,
146
- :logger => @logger
147
172
  }
148
173
  end
149
174
 
150
175
  def new_client
151
- LogStash::Filters::ElasticsearchClient.new(@user, @password, client_options)
176
+ # NOTE: could pass cloud-id/cloud-auth to client but than we would need to be stricter on ES version requirement
177
+ # and also LS parsing might differ from ES client's parsing so for consistency we do not pass cloud options ...
178
+ LogStash::Filters::ElasticsearchClient.new(@logger, @hosts, client_options)
152
179
  end
153
180
 
154
181
  def get_client
@@ -173,6 +200,91 @@ class LogStash::Filters::Elasticsearch < LogStash::Filters::Base
173
200
  end
174
201
  end
175
202
 
203
+ # Given a "hits" object from an Elasticsearch response, return the total number of hits in
204
+ # the result set.
205
+ # @param hits [Hash{String=>Object}]
206
+ # @return [Integer]
207
+ def extract_total_from_hits(hits)
208
+ total = hits['total']
209
+
210
+ # Elasticsearch 7.x produces an object containing `value` and `relation` in order
211
+ # to enable unambiguous reporting when the total is only a lower bound; if we get
212
+ # an object back, return its `value`.
213
+ return total['value'] if total.kind_of?(Hash)
214
+
215
+ total
216
+ end
217
+
218
+ def hosts_default?(hosts)
219
+ # NOTE: would be nice if pipeline allowed us a clean way to detect a config default :
220
+ hosts.is_a?(Array) && hosts.size == 1 && hosts.first.equal?(DEFAULT_HOST)
221
+ end
222
+
223
+ def validate_authentication
224
+ authn_options = 0
225
+ authn_options += 1 if @cloud_auth
226
+ authn_options += 1 if (@api_key && @api_key.value)
227
+ authn_options += 1 if (@user || (@password && @password.value))
228
+
229
+ if authn_options > 1
230
+ raise LogStash::ConfigurationError, 'Multiple authentication options are specified, please only use one of user/password, cloud_auth or api_key'
231
+ end
232
+
233
+ if @api_key && @api_key.value && @ssl != true
234
+ raise(LogStash::ConfigurationError, "Using api_key authentication requires SSL/TLS secured communication using the `ssl => true` option")
235
+ end
236
+ end
237
+
238
+ def fill_user_password_from_cloud_auth
239
+ return unless @cloud_auth
240
+
241
+ @user, @password = parse_user_password_from_cloud_auth(@cloud_auth)
242
+ params['user'], params['password'] = @user, @password
243
+ end
244
+
245
+ def fill_hosts_from_cloud_id
246
+ return unless @cloud_id
247
+
248
+ if @hosts && !hosts_default?(@hosts)
249
+ raise LogStash::ConfigurationError, 'Both cloud_id and hosts specified, please only use one of those.'
250
+ end
251
+ @hosts = parse_host_uri_from_cloud_id(@cloud_id)
252
+ end
253
+
254
+ def parse_host_uri_from_cloud_id(cloud_id)
255
+ begin # might not be available on older LS
256
+ require 'logstash/util/cloud_setting_id'
257
+ rescue LoadError
258
+ raise LogStash::ConfigurationError, 'The cloud_id setting is not supported by your version of Logstash, ' +
259
+ 'please upgrade your installation (or set hosts instead).'
260
+ end
261
+
262
+ begin
263
+ cloud_id = LogStash::Util::CloudSettingId.new(cloud_id) # already does append ':{port}' to host
264
+ rescue ArgumentError => e
265
+ raise LogStash::ConfigurationError, e.message.to_s.sub(/Cloud Id/i, 'cloud_id')
266
+ end
267
+ cloud_uri = "#{cloud_id.elasticsearch_scheme}://#{cloud_id.elasticsearch_host}"
268
+ LogStash::Util::SafeURI.new(cloud_uri)
269
+ end
270
+
271
+ def parse_user_password_from_cloud_auth(cloud_auth)
272
+ begin # might not be available on older LS
273
+ require 'logstash/util/cloud_setting_auth'
274
+ rescue LoadError
275
+ raise LogStash::ConfigurationError, 'The cloud_auth setting is not supported by your version of Logstash, ' +
276
+ 'please upgrade your installation (or set user/password instead).'
277
+ end
278
+
279
+ cloud_auth = cloud_auth.value if cloud_auth.is_a?(LogStash::Util::Password)
280
+ begin
281
+ cloud_auth = LogStash::Util::CloudSettingAuth.new(cloud_auth)
282
+ rescue ArgumentError => e
283
+ raise LogStash::ConfigurationError, e.message.to_s.sub(/Cloud Auth/i, 'cloud_auth')
284
+ end
285
+ [ cloud_auth.username, cloud_auth.password ]
286
+ end
287
+
176
288
  def test_connection!
177
289
  get_client.client.ping
178
290
  end
@@ -10,23 +10,22 @@ module LogStash
10
10
 
11
11
  attr_reader :client
12
12
 
13
- def initialize(user, password, options={})
14
- ssl = options.fetch(:ssl, false)
15
- hosts = options[:hosts]
16
- @logger = options[:logger]
13
+ def initialize(logger, hosts, options = {})
14
+ ssl = options.fetch(:ssl, false)
15
+ user = options.fetch(:user, nil)
16
+ password = options.fetch(:password, nil)
17
+ api_key = options.fetch(:api_key, nil)
17
18
 
18
- transport_options = {}
19
- if user && password
20
- token = ::Base64.strict_encode64("#{user}:#{password.value}")
21
- transport_options[:headers] = { Authorization: "Basic #{token}" }
22
- end
19
+ transport_options = {:headers => {}}
20
+ transport_options[:headers].merge!(setup_basic_auth(user, password))
21
+ transport_options[:headers].merge!(setup_api_key(api_key))
23
22
 
24
23
  hosts.map! {|h| { host: h, scheme: 'https' } } if ssl
25
24
  # set ca_file even if ssl isn't on, since the host can be an https url
26
25
  ssl_options = { ssl: true, ca_file: options[:ca_file] } if options[:ca_file]
27
26
  ssl_options ||= {}
28
27
 
29
- @logger.info("New ElasticSearch filter client", :hosts => hosts)
28
+ logger.info("New ElasticSearch filter client", :hosts => hosts)
30
29
  @client = ::Elasticsearch::Client.new(hosts: hosts, transport_options: transport_options, transport_class: ::Elasticsearch::Transport::Transport::HTTP::Manticore, :ssl => ssl_options)
31
30
  end
32
31
 
@@ -34,6 +33,21 @@ module LogStash
34
33
  @client.search(params)
35
34
  end
36
35
 
36
+ private
37
+
38
+ def setup_basic_auth(user, password)
39
+ return {} unless user && password && password.value
40
+
41
+ token = ::Base64.strict_encode64("#{user}:#{password.value}")
42
+ { Authorization: "Basic #{token}" }
43
+ end
44
+
45
+ def setup_api_key(api_key)
46
+ return {} unless (api_key && api_key.value)
47
+
48
+ token = ::Base64.strict_encode64(api_key.value)
49
+ { Authorization: "ApiKey #{token}" }
50
+ end
37
51
  end
38
52
  end
39
53
  end
@@ -1,7 +1,7 @@
1
1
  Gem::Specification.new do |s|
2
2
 
3
3
  s.name = 'logstash-filter-elasticsearch'
4
- s.version = '3.5.0'
4
+ s.version = '3.8.0'
5
5
  s.licenses = ['Apache License (2.0)']
6
6
  s.summary = "Copies fields from previous log events in Elasticsearch to current events "
7
7
  s.description = "This gem is a Logstash plugin required to be installed on top of the Logstash core pipeline using $LS_HOME/bin/logstash-plugin install gemname. This gem is not a stand-alone program"
@@ -21,7 +21,7 @@ Gem::Specification.new do |s|
21
21
 
22
22
  # Gem dependencies
23
23
  s.add_runtime_dependency "logstash-core-plugin-api", ">= 1.60", "<= 2.99"
24
- s.add_runtime_dependency 'elasticsearch', ">= 5.0.3", " <6.0.0"
24
+ s.add_runtime_dependency 'elasticsearch', ">= 5.0.3"
25
25
  s.add_runtime_dependency 'manticore', "~> 0.6"
26
26
 
27
27
  s.add_development_dependency 'logstash-devutils'
@@ -0,0 +1,43 @@
1
+ module ESHelper
2
+ def self.get_host_port
3
+ if ENV["INTEGRATION"] == "true"
4
+ "elasticsearch:9200"
5
+ else
6
+ "localhost:9200"
7
+ end
8
+ end
9
+
10
+ def self.get_client
11
+ Elasticsearch::Client.new(:hosts => [get_host_port])
12
+ end
13
+
14
+ def self.doc_type
15
+ if ESHelper.es_version_satisfies?(">=8")
16
+ nil
17
+ elsif ESHelper.es_version_satisfies?(">=7")
18
+ "_doc"
19
+ else
20
+ "doc"
21
+ end
22
+ end
23
+
24
+ def self.index_doc(es, params)
25
+ type = doc_type
26
+ params[:type] = doc_type unless type.nil?
27
+ es.index(params)
28
+ end
29
+
30
+ def self.es_version
31
+ ENV['ES_VERSION'] || ENV['ELASTIC_STACK_VERSION']
32
+ end
33
+
34
+ def self.es_version_satisfies?(*requirement)
35
+ es_version = RSpec.configuration.filter[:es_version] || ENV['ES_VERSION'] || ENV['ELASTIC_STACK_VERSION']
36
+ if es_version.nil?
37
+ puts "Info: ES_VERSION, ELASTIC_STACK_VERSION or 'es_version' tag wasn't set. Returning false to all `es_version_satisfies?` call."
38
+ return false
39
+ end
40
+ es_release_version = Gem::Version.new(es_version).release
41
+ Gem::Requirement.new(requirement).satisfied_by?(es_release_version)
42
+ end
43
+ end
@@ -113,6 +113,26 @@ describe LogStash::Filters::Elasticsearch do
113
113
  end
114
114
  end
115
115
 
116
+ context 'when Elasticsearch 7.x gives us a totals object instead of an integer' do
117
+ let(:config) do
118
+ {
119
+ "hosts" => ["localhost:9200"],
120
+ "query" => "response: 404",
121
+ "fields" => { "response" => "code" },
122
+ "result_size" => 10
123
+ }
124
+ end
125
+
126
+ let(:response) do
127
+ LogStash::Json.load(File.read(File.join(File.dirname(__FILE__), "fixtures", "elasticsearch_7.x_hits_total_as_object.json")))
128
+ end
129
+
130
+ it "should enhance the current event with new data" do
131
+ plugin.filter(event)
132
+ expect(event.get("[@metadata][total_hits]")).to eq(13476)
133
+ end
134
+ end
135
+
116
136
  context "if something wrong happen during connection" do
117
137
 
118
138
  before(:each) do
@@ -269,7 +289,143 @@ describe LogStash::Filters::Elasticsearch do
269
289
  end
270
290
 
271
291
  end
292
+ end
293
+
294
+ describe "client" do
295
+ let(:config) do
296
+ {
297
+ "query" => "response: unknown"
298
+ }
299
+ end
300
+ let(:plugin) { described_class.new(config) }
301
+ let(:event) { LogStash::Event.new({}) }
302
+
303
+ before(:each) do
304
+ allow(plugin).to receive(:test_connection!)
305
+ end
306
+
307
+ after(:each) do
308
+ Thread.current[:filter_elasticsearch_client] = nil
309
+ end
310
+
311
+ describe "cloud.id" do
312
+ let(:valid_cloud_id) do
313
+ 'sample:dXMtY2VudHJhbDEuZ2NwLmNsb3VkLmVzLmlvJGFjMzFlYmI5MDI0MTc3MzE1NzA0M2MzNGZkMjZmZDQ2OjkyNDMkYTRjMDYyMzBlNDhjOGZjZTdiZTg4YTA3NGEzYmIzZTA6OTI0NA=='
314
+ end
315
+
316
+ let(:config) { super.merge({ 'cloud_id' => valid_cloud_id }) }
317
+
318
+ it "should set host(s)" do
319
+ plugin.register
320
+ client = plugin.send(:get_client).client
321
+ expect( client.transport.hosts ).to eql [{
322
+ :scheme => "https",
323
+ :host => "ac31ebb90241773157043c34fd26fd46.us-central1.gcp.cloud.es.io",
324
+ :port => 9243,
325
+ :path => "",
326
+ :protocol => "https"
327
+ }]
328
+ end
329
+
330
+ context 'invalid' do
331
+ let(:config) { super.merge({ 'cloud_id' => 'invalid:dXMtY2VudHJhbDEuZ2NwLmNsb3VkLmVzLmlv' }) }
332
+
333
+ it "should fail" do
334
+ expect { plugin.register }.to raise_error LogStash::ConfigurationError, /cloud_id.*? is invalid/
335
+ end
336
+ end
272
337
 
338
+ context 'hosts also set' do
339
+ let(:config) { super.merge({ 'cloud_id' => valid_cloud_id, 'hosts' => [ 'localhost:9200' ] }) }
340
+
341
+ it "should fail" do
342
+ expect { plugin.register }.to raise_error LogStash::ConfigurationError, /cloud_id and hosts/
343
+ end
344
+ end
345
+ end if LOGSTASH_VERSION > '6.0'
346
+
347
+ describe "cloud.auth" do
348
+ let(:config) { super.merge({ 'cloud_auth' => LogStash::Util::Password.new('elastic:my-passwd-00') }) }
349
+
350
+ it "should set authorization" do
351
+ plugin.register
352
+ client = plugin.send(:get_client).client
353
+ auth_header = client.transport.options[:transport_options][:headers][:Authorization]
354
+
355
+ expect( auth_header ).to eql "Basic #{Base64.encode64('elastic:my-passwd-00').rstrip}"
356
+ end
357
+
358
+ context 'invalid' do
359
+ let(:config) { super.merge({ 'cloud_auth' => 'invalid-format' }) }
360
+
361
+ it "should fail" do
362
+ expect { plugin.register }.to raise_error LogStash::ConfigurationError, /cloud_auth.*? format/
363
+ end
364
+ end
365
+
366
+ context 'user also set' do
367
+ let(:config) { super.merge({ 'cloud_auth' => 'elastic:my-passwd-00', 'user' => 'another' }) }
368
+
369
+ it "should fail" do
370
+ expect { plugin.register }.to raise_error LogStash::ConfigurationError, /Multiple authentication options are specified/
371
+ end
372
+ end
373
+ end if LOGSTASH_VERSION > '6.0'
374
+
375
+ describe "api_key" do
376
+ context "without ssl" do
377
+ let(:config) { super.merge({ 'api_key' => LogStash::Util::Password.new('foo:bar') }) }
378
+
379
+ it "should fail" do
380
+ expect { plugin.register }.to raise_error LogStash::ConfigurationError, /api_key authentication requires SSL\/TLS/
381
+ end
382
+ end
383
+
384
+ context "with ssl" do
385
+ let(:config) { super.merge({ 'api_key' => LogStash::Util::Password.new('foo:bar'), "ssl" => true }) }
386
+
387
+ it "should set authorization" do
388
+ plugin.register
389
+ client = plugin.send(:get_client).client
390
+ auth_header = client.transport.options[:transport_options][:headers][:Authorization]
391
+
392
+ expect( auth_header ).to eql "ApiKey #{Base64.strict_encode64('foo:bar')}"
393
+ end
394
+
395
+ context 'user also set' do
396
+ let(:config) { super.merge({ 'api_key' => 'foo:bar', 'user' => 'another' }) }
397
+
398
+ it "should fail" do
399
+ expect { plugin.register }.to raise_error LogStash::ConfigurationError, /Multiple authentication options are specified/
400
+ end
401
+ end
402
+ end
403
+ end if LOGSTASH_VERSION > '6.0'
273
404
  end
274
405
 
406
+ describe "query template" do
407
+ let(:config) do
408
+ {
409
+ "query_template" => File.join(File.dirname(__FILE__), "fixtures", "query_template_unicode.json"),
410
+ }
411
+ end
412
+
413
+ let(:plugin) { described_class.new(config) }
414
+
415
+ let(:client) { double(:client) }
416
+
417
+ before(:each) do
418
+ allow(LogStash::Filters::ElasticsearchClient).to receive(:new).and_return(client)
419
+ allow(plugin).to receive(:test_connection!)
420
+ plugin.register
421
+ end
422
+
423
+ it "should read and send non-ascii query" do
424
+ expect(client).to receive(:search).with(
425
+ :body => { "query" => { "terms" => { "lock" => [ "잠금", "uzávěr" ] } } },
426
+ :index => "")
427
+
428
+ plugin.filter(LogStash::Event.new)
429
+ end
430
+ end
275
431
  end
@@ -0,0 +1,70 @@
1
+ {
2
+ "took": 49,
3
+ "timed_out": false,
4
+ "_shards": {
5
+ "total": 155,
6
+ "successful": 155,
7
+ "failed": 0
8
+ },
9
+ "hits": {
10
+ "total": {
11
+ "value": 13476,
12
+ "relation": "eq"
13
+ },
14
+ "max_score": 1,
15
+ "hits": [{
16
+ "_index": "logstash-2014.08.26",
17
+ "_type": "logs",
18
+ "_id": "AVVY76L_AW7v0kX8KXo4",
19
+ "_score": 1,
20
+ "_source": {
21
+ "request": "/doc/index.html?org/elasticsearch/action/search/SearchResponse.html",
22
+ "agent": "\"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)\"",
23
+ "geoip": {
24
+ "timezone": "America/Los_Angeles",
25
+ "ip": "66.249.73.185",
26
+ "latitude": 37.386,
27
+ "continent_code": "NA",
28
+ "city_name": "Mountain View",
29
+ "country_code2": "US",
30
+ "country_name": "United States",
31
+ "dma_code": 807,
32
+ "country_code3": "US",
33
+ "region_name": "California",
34
+ "location": [-122.0838,
35
+ 37.386
36
+ ],
37
+ "postal_code": "94035",
38
+ "longitude": -122.0838,
39
+ "region_code": "CA"
40
+ },
41
+ "auth": "-",
42
+ "ident": "-",
43
+ "verb": "GET",
44
+ "useragent": {
45
+ "os": "Other",
46
+ "major": "2",
47
+ "minor": "1",
48
+ "name": "Googlebot",
49
+ "os_name": "Other",
50
+ "device": "Spider"
51
+ },
52
+ "message": "66.249.73.185 - - [26/Aug/2014:21:22:13 +0000] \"GET /doc/index.html?org/elasticsearch/action/search/SearchResponse.html HTTP/1.1\" 404 294 \"-\" \"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)\"",
53
+ "referrer": "\"-\"",
54
+ "@timestamp": "2014-08-26T21:22:13.000Z",
55
+ "response": 404,
56
+ "bytes": 294,
57
+ "clientip": "66.249.73.185",
58
+ "@version": "1",
59
+ "host": "skywalker",
60
+ "httpversion": "1.1",
61
+ "timestamp": "26/Aug/2014:21:22:13 +0000"
62
+ }
63
+ }]
64
+ },
65
+ "aggregations": {
66
+ "bytes_avg": {
67
+ "value": 294
68
+ }
69
+ }
70
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "query": {
3
+ "terms": {
4
+ "lock": [ "잠금", "uzávěr" ]
5
+ }
6
+ }
7
+ }
@@ -2,13 +2,17 @@
2
2
  require "logstash/devutils/rspec/spec_helper"
3
3
  require "logstash/plugin"
4
4
  require "logstash/filters/elasticsearch"
5
+ require_relative "../../../spec/es_helper"
5
6
 
6
7
  describe LogStash::Filters::Elasticsearch, :integration => true do
7
8
 
9
+
8
10
  let(:config) do
9
11
  {
10
- "hosts" => ["localhost:9200"],
12
+ "index" => 'logs',
13
+ "hosts" => [ESHelper.get_host_port],
11
14
  "query" => "response: 404",
15
+ "sort" => "response",
12
16
  "fields" => [ ["response", "code"] ],
13
17
  }
14
18
  end
@@ -16,21 +20,34 @@ describe LogStash::Filters::Elasticsearch, :integration => true do
16
20
  let(:event) { LogStash::Event.new({}) }
17
21
 
18
22
  before(:each) do
23
+ @es = ESHelper.get_client
24
+ # Delete all templates first.
25
+ # Clean ES of data before we start.
26
+ @es.indices.delete_template(:name => "*")
27
+ # This can fail if there are no indexes, ignore failure.
28
+ @es.indices.delete(:index => "*") rescue nil
29
+ 10.times do
30
+ ESHelper.index_doc(@es, :index => 'logs', :body => { :response => 404, :this => 'that'})
31
+ end
32
+ @es.indices.refresh
33
+
19
34
  plugin.register
20
35
  end
21
36
 
22
37
  it "should enhance the current event with new data" do
23
38
  plugin.filter(event)
24
- expect(event.get("code")).to eq(404)
39
+ expect(event.get('code')).to eq(404)
25
40
  end
26
41
 
27
42
  context "when retrieving a list of elements" do
28
43
 
29
44
  let(:config) do
30
45
  {
31
- "hosts" => ["localhost:9200"],
46
+ "index" => 'logs',
47
+ "hosts" => [ESHelper.get_host_port],
32
48
  "query" => "response: 404",
33
49
  "fields" => [ ["response", "code"] ],
50
+ "sort" => "response",
34
51
  "result_size" => 10
35
52
  }
36
53
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: logstash-filter-elasticsearch
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.5.0
4
+ version: 3.8.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Elastic
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2018-11-22 00:00:00.000000000 Z
11
+ date: 2020-06-03 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  requirement: !ruby/object:Gem::Requirement
@@ -36,9 +36,6 @@ dependencies:
36
36
  - - ">="
37
37
  - !ruby/object:Gem::Version
38
38
  version: 5.0.3
39
- - - "<"
40
- - !ruby/object:Gem::Version
41
- version: 6.0.0
42
39
  name: elasticsearch
43
40
  prerelease: false
44
41
  type: :runtime
@@ -47,9 +44,6 @@ dependencies:
47
44
  - - ">="
48
45
  - !ruby/object:Gem::Version
49
46
  version: 5.0.3
50
- - - "<"
51
- - !ruby/object:Gem::Version
52
- version: 6.0.0
53
47
  - !ruby/object:Gem::Dependency
54
48
  requirement: !ruby/object:Gem::Requirement
55
49
  requirements:
@@ -96,8 +90,11 @@ files:
96
90
  - lib/logstash/filters/elasticsearch.rb
97
91
  - lib/logstash/filters/elasticsearch/client.rb
98
92
  - logstash-filter-elasticsearch.gemspec
93
+ - spec/es_helper.rb
99
94
  - spec/filters/elasticsearch_spec.rb
95
+ - spec/filters/fixtures/elasticsearch_7.x_hits_total_as_object.json
100
96
  - spec/filters/fixtures/query_template.json
97
+ - spec/filters/fixtures/query_template_unicode.json
101
98
  - spec/filters/fixtures/request_error.json
102
99
  - spec/filters/fixtures/request_size0_agg.json
103
100
  - spec/filters/fixtures/request_x_1.json
@@ -130,8 +127,11 @@ signing_key:
130
127
  specification_version: 4
131
128
  summary: Copies fields from previous log events in Elasticsearch to current events
132
129
  test_files:
130
+ - spec/es_helper.rb
133
131
  - spec/filters/elasticsearch_spec.rb
132
+ - spec/filters/fixtures/elasticsearch_7.x_hits_total_as_object.json
134
133
  - spec/filters/fixtures/query_template.json
134
+ - spec/filters/fixtures/query_template_unicode.json
135
135
  - spec/filters/fixtures/request_error.json
136
136
  - spec/filters/fixtures/request_size0_agg.json
137
137
  - spec/filters/fixtures/request_x_1.json