-
Notifications
You must be signed in to change notification settings - Fork 307
/
Copy pathtest_out_elasticsearch.rb
6257 lines (5701 loc) · 268 KB
/
test_out_elasticsearch.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require_relative '../helper'
require 'date'
require 'fluent/test/helpers'
require 'json'
require 'fluent/test/driver/output'
require 'flexmock/test_unit'
require 'fluent/plugin/out_elasticsearch'
class ElasticsearchOutputTest < Test::Unit::TestCase
include FlexMock::TestCase
include Fluent::Test::Helpers
attr_accessor :index_cmds, :index_command_counts, :index_cmds_all_requests
def setup
Fluent::Test.setup
@driver = nil
log = Fluent::Engine.log
log.out.logs.slice!(0, log.out.logs.length)
end
def elasticsearch_version
if Gem::Version.new(TRANSPORT_CLASS::VERSION) >= Gem::Version.new("7.14.0")
TRANSPORT_CLASS::VERSION.split(".")[0..1].join(".")
else
"7.17".freeze
end
end
def driver(conf='', es_version=elasticsearch_version.to_i, client_version="\"#{elasticsearch_version}\"")
# For request stub to detect compatibility.
@es_version ||= es_version
@client_version ||= client_version
if @es_version
Fluent::Plugin::ElasticsearchOutput.module_eval(<<-CODE)
def detect_es_major_version
#{@es_version}
end
CODE
end
Fluent::Plugin::ElasticsearchOutput.module_eval(<<-CODE)
def client_library_version
#{@client_version}
end
CODE
@driver ||= Fluent::Test::Driver::Output.new(Fluent::Plugin::ElasticsearchOutput) {
# v0.12's test driver assume format definition. This simulates ObjectBufferedOutput format
if !defined?(Fluent::Plugin::Output)
def format(tag, time, record)
[time, record].to_msgpack
end
end
}.configure(conf)
end
def elasticsearch_transport_layer_decoupling?
Gem::Version.create(::TRANSPORT_CLASS::VERSION) >= Gem::Version.new("7.14.0")
end
def elastic_perform_request_refactored?
Gem::Version.create(Elasticsearch::VERSION) >= Gem::Version.new("8.8.0")
end
def elastic_transport_layer?
Gem::Version.create(::TRANSPORT_CLASS::VERSION) >= Gem::Version.new("8.0.0")
end
def default_type_name
Fluent::Plugin::ElasticsearchOutput::DEFAULT_TYPE_NAME
end
def sample_record(content={})
{'age' => 26, 'request_id' => '42', 'parent_id' => 'parent', 'routing_id' => 'routing'}.merge(content)
end
def nested_sample_record
{'nested' =>
{'age' => 26, 'parent_id' => 'parent', 'routing_id' => 'routing', 'request_id' => '42'}
}
end
def stub_elastic_info(url="http://localhost:9200/", version=elasticsearch_version)
body ="{\"version\":{\"number\":\"#{version}\", \"build_flavor\":\"default\"},\"tagline\" : \"You Know, for Search\"}"
stub_request(:get, url)
.to_return({:status => 200, :body => body, :headers => { 'Content-Type' => 'json', 'X-elastic-product' => 'Elasticsearch' } })
end
def stub_elastic(url="http://localhost:9200/_bulk")
stub_request(:post, url).with do |req|
@index_cmds = req.body.split("\n").map {|r| JSON.parse(r) }
end.to_return({:status => 200, :body => "", :headers => { 'Content-Type' => 'json', 'x-elastic-product' => 'Elasticsearch' } })
end
def stub_elastic_all_requests(url="http://localhost:9200/_bulk")
@index_cmds_all_requests = Array.new
stub_request(:post, url).with do |req|
@index_cmds = req.body.split("\n").map {|r| JSON.parse(r) }
@index_cmds_all_requests << @index_cmds
end.to_return({:status => 200, :body => "", :headers => { 'Content-Type' => 'json', 'x-elastic-product' => 'Elasticsearch' } })
end
def stub_elastic_unavailable(url="http://localhost:9200/_bulk")
stub_request(:post, url).to_return(:status => [503, "Service Unavailable"])
end
def stub_elastic_timeout(url="http://localhost:9200/_bulk")
stub_request(:post, url).to_timeout
end
def stub_elastic_with_store_index_command_counts(url="http://localhost:9200/_bulk")
if @index_command_counts == nil
@index_command_counts = {}
@index_command_counts.default = 0
end
stub_request(:post, url).with do |req|
index_cmds = req.body.split("\n").map {|r| JSON.parse(r) }
@index_command_counts[url] += index_cmds.size
end.to_return({:status => 200, :body => "{}", :headers => { 'Content-Type' => 'json', 'x-elastic-product' => 'Elasticsearch' } })
end
def make_response_body(req, error_el = nil, error_status = nil, error = nil)
req_index_cmds = req.body.split("\n").map { |r| JSON.parse(r) }
items = []
count = 0
ids = 1
op = nil
index = nil
type = nil
id = nil
req_index_cmds.each do |cmd|
if count.even?
op = cmd.keys[0]
index = cmd[op]['_index']
type = cmd[op]['_type']
if cmd[op].has_key?('_id')
id = cmd[op]['_id']
else
# Note: this appears to be an undocumented feature of Elasticsearch
# https://www.elastic.co/guide/en/elasticsearch/reference/2.4/docs-bulk.html
# When you submit an "index" write_operation, with no "_id" field in the
# metadata header, Elasticsearch will turn this into a "create"
# operation in the response.
if "index" == op
op = "create"
end
id = ids
ids += 1
end
else
item = {
op => {
'_index' => index, '_type' => type, '_id' => id, '_version' => 1,
'_shards' => { 'total' => 1, 'successful' => 1, 'failed' => 0 },
'status' => op == 'create' ? 201 : 200
}
}
items.push(item)
end
count += 1
end
if !error_el.nil? && !error_status.nil? && !error.nil?
op = items[error_el].keys[0]
items[error_el][op].delete('_version')
items[error_el][op].delete('_shards')
items[error_el][op]['error'] = error
items[error_el][op]['status'] = error_status
errors = true
else
errors = false
end
@index_cmds = items
body = { 'took' => 6, 'errors' => errors, 'items' => items }
return body.to_json
end
def stub_elastic_bad_argument(url="http://localhost:9200/_bulk")
error = {
"type" => "mapper_parsing_exception",
"reason" => "failed to parse [...]",
"caused_by" => {
"type" => "illegal_argument_exception",
"reason" => "Invalid format: \"...\""
}
}
stub_request(:post, url).to_return(lambda { |req| { :status => 200, :body => make_response_body(req, 1, 400, error), :headers => { 'Content-Type' => 'json', 'x-elastic-product' => 'Elasticsearch' } } })
end
def stub_elastic_bulk_error(url="http://localhost:9200/_bulk")
error = {
"type" => "some-unrecognized-error",
"reason" => "some message printed here ...",
}
stub_request(:post, url).to_return(lambda { |req| { :status => 200, :body => make_response_body(req, 1, 500, error), :headers => { 'Content-Type' => 'json', 'x-elastic-product' => 'Elasticsearch' } } })
end
def stub_elastic_bulk_rejected(url="http://localhost:9200/_bulk")
error = {
"status" => 500,
"type" => "es_rejected_execution_exception",
"reason" => "rejected execution of org.elasticsearch.transport.TransportService$4@1a34d37a on EsThreadPoolExecutor[bulk, queue capacity = 50, org.elasticsearch.common.util.concurrent.EsThreadPoolExecutor@312a2162[Running, pool size = 32, active threads = 32, queued tasks = 50, completed tasks = 327053]]"
}
stub_request(:post, url).to_return(lambda { |req| { :status => 200, :body => make_response_body(req, 1, 429, error), :headers => { 'Content-Type' => 'json', 'x-elastic-product' => 'Elasticsearch' } } })
end
def stub_elastic_out_of_memory(url="http://localhost:9200/_bulk")
error = {
"status" => 500,
"type" => "out_of_memory_error",
"reason" => "Java heap space"
}
stub_request(:post, url).to_return(lambda { |req| { :status => 200, :body => make_response_body(req, 1, 500, error), :headers => { 'Content-Type' => 'json', 'x-elastic-product' => 'Elasticsearch' } } })
end
def stub_elastic_unexpected_response_op(url="http://localhost:9200/_bulk")
error = {
"category" => "some-other-type",
"reason" => "some-other-reason"
}
stub_request(:post, url).to_return(lambda { |req| bodystr = make_response_body(req, 0, 500, error); body = JSON.parse(bodystr); body['items'][0]['unknown'] = body['items'][0].delete('create'); { :status => 200, :body => body.to_json, :headers => { 'Content-Type' => 'json', 'x-elastic-product' => 'Elasticsearch' } } })
end
def assert_logs_include(logs, msg, exp_matches=1)
matches = logs.grep /#{msg}/
assert_equal(exp_matches, matches.length, "Logs do not contain '#{msg}' '#{logs}'")
end
def assert_logs_include_compare_size(exp_matches=1, operator="<=", logs="", msg="")
matches = logs.grep /#{msg}/
assert_compare(exp_matches, operator, matches.length, "Logs do not contain '#{msg}' '#{logs}'")
end
def alias_endpoint
if Gem::Version.create(::Elasticsearch::VERSION) >= Gem::Version.create("7.5.0-pre")
"_aliases"
else
"_alias"
end
end
def test_configure
config = %{
host logs.google.com
port 777
scheme https
path /es/
user john
password doe
}
instance = driver(config).instance
assert_equal 'logs.google.com', instance.host
assert_equal 777, instance.port
assert_equal :https, instance.scheme
assert_equal '/es/', instance.path
assert_equal 'john', instance.user
assert_equal 'doe', instance.password
assert_equal Fluent::Plugin::ElasticsearchTLS::DEFAULT_VERSION, instance.ssl_version
assert_nil instance.ssl_max_version
assert_nil instance.ssl_min_version
if Fluent::Plugin::ElasticsearchTLS::USE_TLS_MINMAX_VERSION
if defined?(OpenSSL::SSL::TLS1_3_VERSION)
assert_equal({max_version: OpenSSL::SSL::TLS1_3_VERSION, min_version: OpenSSL::SSL::TLS1_2_VERSION},
instance.ssl_version_options)
else
assert_equal({max_version: nil, min_version: OpenSSL::SSL::TLS1_2_VERSION},
instance.ssl_version_options)
end
else
assert_equal({version: Fluent::Plugin::ElasticsearchTLS::DEFAULT_VERSION},
instance.ssl_version_options)
end
assert_nil instance.client_key
assert_nil instance.client_cert
assert_nil instance.client_key_pass
assert_false instance.with_transporter_log
assert_equal :"application/json", instance.content_type
assert_equal "fluentd", default_type_name
assert_equal :excon, instance.http_backend
assert_false instance.prefer_oj_serializer
assert_equal ["out_of_memory_error", "es_rejected_execution_exception"], instance.unrecoverable_error_types
assert_true instance.verify_es_version_at_startup
assert_equal Fluent::Plugin::ElasticsearchOutput::DEFAULT_ELASTICSEARCH_VERSION, instance.default_elasticsearch_version
assert_false instance.log_es_400_reason
assert_equal -1, Fluent::Plugin::ElasticsearchOutput::DEFAULT_TARGET_BULK_BYTES
assert_false instance.compression
assert_equal :no_compression, instance.compression_level
assert_true instance.http_backend_excon_nonblock
assert_equal({}, instance.api_key_header)
end
test 'configure compression' do
omit "elastisearch-ruby v7.2.0 or later is needed." if Gem::Version.create(::TRANSPORT_CLASS::VERSION) < Gem::Version.create("7.2.0")
config = %{
compression_level best_compression
}
instance = driver(config).instance
assert_equal true, instance.compression
end
test 'check compression strategy' do
omit "elastisearch-ruby v7.2.0 or later is needed." if Gem::Version.create(::TRANSPORT_CLASS::VERSION) < Gem::Version.create("7.2.0")
config = %{
compression_level best_speed
}
instance = driver(config).instance
assert_equal Zlib::BEST_SPEED, instance.compression_strategy
end
test 'check content-encoding header with compression' do
omit "elastisearch-ruby v7.2.0 or later is needed." if Gem::Version.create(::TRANSPORT_CLASS::VERSION) < Gem::Version.create("7.2.0")
config = %{
compression_level best_compression
}
instance = driver(config).instance
if elastic_transport_layer?
assert_equal nil, instance.client.transport.options[:transport_options][:headers]["Content-Encoding"]
elsif elasticsearch_transport_layer_decoupling?
assert_equal nil, instance.client.transport.transport.options[:transport_options][:headers]["Content-Encoding"]
else
assert_equal nil, instance.client.transport.options[:transport_options][:headers]["Content-Encoding"]
end
stub_request(:post, "http://localhost:9200/_bulk").
to_return(status: 200, body: "", headers: {'x-elastic-product' => 'Elasticsearch'})
stub_elastic_info
driver.run(default_tag: 'test') do
driver.feed(sample_record)
end
compressable = instance.compressable_connection
if elastic_transport_layer?
assert_equal "gzip", instance.client(nil, compressable).transport.options[:transport_options][:headers]["Content-Encoding"]
elsif elasticsearch_transport_layer_decoupling?
assert_equal "gzip", instance.client(nil, compressable).transport.transport.options[:transport_options][:headers]["Content-Encoding"]
else
assert_equal "gzip", instance.client(nil, compressable).transport.options[:transport_options][:headers]["Content-Encoding"]
end
end
test 'check compression option is passed to transport' do
omit "elastisearch-ruby v7.2.0 or later is needed." if Gem::Version.create(::TRANSPORT_CLASS::VERSION) < Gem::Version.create("7.2.0")
config = %{
compression_level best_compression
}
instance = driver(config).instance
if elastic_transport_layer?
assert_equal false, instance.client.transport.options[:compression]
elsif elasticsearch_transport_layer_decoupling?
assert_equal false, instance.client.transport.transport.options[:compression]
else
assert_equal false, instance.client.transport.options[:compression]
end
stub_request(:post, "http://localhost:9200/_bulk").
to_return(status: 200, body: "", headers: {'x-elastic-product' => 'Elasticsearch' })
stub_elastic_info
driver.run(default_tag: 'test') do
driver.feed(sample_record)
end
compressable = instance.compressable_connection
if elastic_transport_layer?
assert_equal true, instance.client(nil, compressable).transport.options[:compression]
elsif elasticsearch_transport_layer_decoupling?
assert_equal true, instance.client(nil, compressable).transport.transport.options[:compression]
else
assert_equal true, instance.client(nil, compressable).transport.options[:compression]
end
end
test 'check configure cloud_id based client' do
config = %{
cloud_id "name:bG9jYWxob3N0JGFiY2QkZWZnaA=="
cloud_auth "some:auth"
}
instance = driver(config).instance
assert_equal "name:bG9jYWxob3N0JGFiY2QkZWZnaA==", instance.cloud_id
assert_equal "some", instance.user
assert_equal "auth", instance.password
end
test 'configure Content-Type' do
config = %{
content_type application/x-ndjson
}
instance = driver(config).instance
assert_equal :"application/x-ndjson", instance.content_type
end
test 'invalid Content-Type' do
config = %{
content_type nonexistent/invalid
}
assert_raise(Fluent::ConfigError) {
driver(config)
}
end
test 'invalid specification of times of retrying template installation' do
config = %{
max_retry_putting_template -3
}
assert_raise(Fluent::ConfigError) {
driver(config)
}
end
test 'invalid specification of times of retrying get es version' do
config = %{
max_retry_get_es_version -3
}
assert_raise(Fluent::ConfigError) {
driver(config)
}
end
sub_test_case 'Check client.info response' do
def create_driver(conf='', es_version=5, client_version="\"5.0\"")
# For request stub to detect compatibility.
@client_version ||= client_version
@default_elasticsearch_version ||= es_version
Fluent::Plugin::ElasticsearchOutput.module_eval(<<-CODE)
def detect_es_major_version
@_es_info ||= client.info
begin
unless version = @_es_info.dig("version", "number")
version = @default_elasticsearch_version
end
rescue NoMethodError => e
log.warn "#{@_es_info} can not dig version information. Assuming Elasticsearch #{@default_elasticsearch_version}", error: e
version = @default_elasticsearch_version
end
version.to_i
end
CODE
Fluent::Plugin::ElasticsearchOutput.module_eval(<<-CODE)
def client_library_version
#{@client_version}
end
CODE
@driver ||= Fluent::Test::Driver::Output.new(Fluent::Plugin::ElasticsearchOutput) {
# v0.12's test driver assume format definition. This simulates ObjectBufferedOutput format
if !defined?(Fluent::Plugin::Output)
def format(tag, time, record)
[time, record].to_msgpack
end
end
}.configure(conf)
end
def stub_elastic_info_bad(url="http://localhost:9200/", version="6.4.2")
body ="{\"version\":{\"number\":\"#{version}\",\"build_flavor\":\"default\"},\"tagline\":\"You Know, for Search\"}"
stub_request(:get, url).to_return({:status => 200, :body => body, :headers => { 'Content-Type' => 'text/plain', 'x-elastic-product' => 'Elasticsearch'} })
end
test 'handle invalid client.info' do
stub_elastic_info_bad("https://logs.fluentd.com:24225/es//", elasticsearch_version)
config = %{
host logs.fluentd.com
port 24225
scheme https
path /es/
user john
password doe
default_elasticsearch_version 7
scheme https
@log_level info
}
if elastic_perform_request_refactored?
d = create_driver(config, 8, "\"8.8.0\"")
logs = d.logs
assert_logs_include(logs, /Detected ES 7.x: `_doc` will be used as the document `_type`./)
elsif elastic_transport_layer?
assert_raise(NoMethodError) do
d = create_driver(config, 8, "\"8.0.0\"")
end
elsif elasticsearch_transport_layer_decoupling?
assert_raise(NoMethodError) do
d = create_driver(config, 7, "\"7.10.1\"")
end
else
d = create_driver(config, 7, "\"7.10.1\"")
logs = d.logs
assert_logs_include(logs, /can not dig version information. Assuming Elasticsearch 7/)
end
end
end
sub_test_case 'Check TLS handshake stuck warning log' do
test 'warning TLS log' do
config = %{
scheme https
http_backend_excon_nonblock false
ssl_version TLSv1_2
@log_level info
}
driver(config)
logs = driver.logs
assert_logs_include(logs, /TLS handshake will be stucked with block connection.\n Consider to set `http_backend_excon_nonblock` as true\n/)
end
end
sub_test_case 'ILM default config' do
setup do
if Gem::Version.new(TRANSPORT_CLASS::VERSION) < Gem::Version.new("8.0.0")
begin
require "elasticsearch/xpack"
rescue LoadError
omit "ILM testcase needs elasticsearch-xpack gem."
end
end
end
def ilm_endpoint
'_ilm'.freeze
end
data("legacy_template" => [true, "_template"],
"new_template" => [false, "_index_template"])
test 'valid configuration of index lifecycle management' do |data|
if Gem::Version.create(::TRANSPORT_CLASS::VERSION) < Gem::Version.create("7.4.0")
omit "elastisearch-ruby v7.4.0 or later is needed for ILM."
end
use_legacy_template_flag, endpoint = data
if !use_legacy_template_flag && Gem::Version.create(::TRANSPORT_CLASS::VERSION) < Gem::Version.create("7.8.0")
omit "elastisearch-ruby v7.8.0 or later is needed."
end
cwd = File.dirname(__FILE__)
template_file = File.join(cwd, 'test_template.json')
config = %{
enable_ilm true
template_name logstash
template_file #{template_file}
use_legacy_template #{use_legacy_template_flag}
}
stub_request(:get, "http://localhost:9200/#{endpoint}/fluentd").
to_return(status: 200, body: "", headers: {'x-elastic-product' => 'Elasticsearch'})
stub_request(:head, "http://localhost:9200/_alias/fluentd").
to_return(status: 404, body: "", headers: {'x-elastic-product' => 'Elasticsearch'})
stub_request(:put, "http://localhost:9200/%3Cfluentd-default-%7Bnow%2Fd%7D-000001%3E/#{alias_endpoint}/fluentd").
with(body: "{\"aliases\":{\"fluentd\":{\"is_write_index\":true}}}").
to_return(status: 200, body: "", headers: {'x-elastic-product' => 'Elasticsearch'})
stub_request(:put, "http://localhost:9200/%3Cfluentd-default-%7Bnow%2Fd%7D-000001%3E").
to_return(status: 200, body: "", headers: {'x-elastic-product' => 'Elasticsearch'})
stub_request(:get, "http://localhost:9200/_xpack").
to_return(:status => 200, :body => '{"features":{"ilm":{"available":true,"enabled":true}}}',
:headers => {"Content-Type"=> "application/json", 'x-elastic-product' => 'Elasticsearch'})
stub_request(:get, "http://localhost:9200/#{ilm_endpoint}/policy/logstash-policy").
to_return(status: 404, body: "", headers: {'x-elastic-product' => 'Elasticsearch'})
stub_request(:put, "http://localhost:9200/#{ilm_endpoint}/policy/logstash-policy").
with(body: "{\"policy\":{\"phases\":{\"hot\":{\"actions\":{\"rollover\":{\"max_size\":\"50gb\",\"max_age\":\"30d\"}}}}}}").
to_return(status: 200, body: "", headers: {'x-elastic-product' => 'Elasticsearch'})
stub_elastic_info
assert_nothing_raised {
driver(config)
}
end
data("legacy_template" => [true, "_template"],
"new_template" => [false, "_index_template"])
test 'valid configuration of overwriting ilm_policy' do |data|
if Gem::Version.create(::TRANSPORT_CLASS::VERSION) < Gem::Version.create("7.4.0")
omit "elastisearch-ruby v7.4.0 or later is needed for ILM."
end
use_legacy_template_flag, endpoint = data
if !use_legacy_template_flag && Gem::Version.create(::TRANSPORT_CLASS::VERSION) < Gem::Version.create("7.8.0")
omit "elastisearch-ruby v7.8.0 or later is needed."
end
cwd = File.dirname(__FILE__)
template_file = File.join(cwd, 'test_template.json')
config = %{
enable_ilm true
template_name logstash
template_file #{template_file}
ilm_policy_overwrite true
ilm_policy {"policy":{"phases":{"hot":{"actions":{"rollover":{"max_size":"75gb","max_age": "50d"}}}}}}
use_legacy_template #{use_legacy_template_flag}
}
stub_request(:get, "http://localhost:9200/#{endpoint}/fluentd").
to_return(status: 200, body: "", headers: {'x-elastic-product' => 'Elasticsearch'})
stub_request(:head, "http://localhost:9200/_alias/fluentd").
to_return(status: 404, body: "", headers: {'x-elastic-product' => 'Elasticsearch'})
stub_request(:put, "http://localhost:9200/%3Cfluentd-default-%7Bnow%2Fd%7D-000001%3E/#{alias_endpoint}/fluentd").
with(body: "{\"aliases\":{\"fluentd\":{\"is_write_index\":true}}}").
to_return(status: 200, body: "", headers: {'x-elastic-product' => 'Elasticsearch'})
stub_request(:put, "http://localhost:9200/%3Cfluentd-default-%7Bnow%2Fd%7D-000001%3E").
to_return(status: 200, body: "", headers: {'x-elastic-product' => 'Elasticsearch'})
stub_request(:get, "http://localhost:9200/_xpack").
to_return(:status => 200, :body => '{"features":{"ilm":{"available":true,"enabled":true}}}',
:headers => {"Content-Type"=> "application/json", 'x-elastic-product' => 'Elasticsearch'})
stub_request(:get, "http://localhost:9200/#{ilm_endpoint}/policy/logstash-policy").
to_return(status: 200, body: "", headers: {'x-elastic-product' => 'Elasticsearch'})
stub_request(:put, "http://localhost:9200/#{ilm_endpoint}/policy/logstash-policy").
with(body: "{\"policy\":{\"phases\":{\"hot\":{\"actions\":{\"rollover\":{\"max_size\":\"75gb\",\"max_age\":\"50d\"}}}}}}").
to_return(status: 200, body: "", headers: {'x-elastic-product' => 'Elasticsearch'})
stub_elastic_info
assert_nothing_raised {
driver(config)
}
end
test 'invalid configuration of overwriting ilm_policy' do
cwd = File.dirname(__FILE__)
template_file = File.join(cwd, 'test_template.json')
config = %{
enable_ilm true
template_name logstash
template_file #{template_file}
ilm_policy_overwrite true
}
stub_elastic_info
assert_raise(Fluent::ConfigError) {
driver(config)
}
end
end
test 'Detected Elasticsearch 7' do
config = %{
type_name changed
}
instance = driver(config, 7).instance
assert_equal '_doc', instance.type_name
end
test 'Detected Elasticsearch 8' do
config = %{
type_name noeffect
}
instance = driver(config, 8).instance
assert_equal nil, instance.type_name
end
test 'Detected Elasticsearch 6 and insecure security' do
config = %{
ssl_version TLSv1_1
@log_level warn
scheme https
}
driver(config, 6)
logs = driver.logs
assert_logs_include(logs, /Detected ES 6.x or above and enabled insecure security/, 1)
end
test 'Detected Elasticsearch 7 and secure security' do
config = %{
ssl_version TLSv1_2
@log_level warn
scheme https
}
driver(config, 7)
logs = driver.logs
assert_logs_include(logs, /Detected ES 6.x or above and enabled insecure security/, 0)
end
test 'Pass Elasticsearch and client library are same' do
config = %{
@log_level warn
validate_client_version true
}
assert_nothing_raised do
driver(config, 6, "\"6.1.0\"")
end
end
test 'Detected Elasticsearch and client library mismatch' do
config = %{
@log_level warn
validate_client_version true
}
assert_raise_message(/Detected ES 7 but you use ES client 5.0/) do
driver(config, 7, "\"5.0.5\"")
end
end
sub_test_case "placeholder substitution needed?" do
data("host placeholder" => ["host", "host-${tag}.google.com"],
"index_name_placeholder" => ["index_name", "logstash-${tag}"],
"template_name_placeholder" => ["template_name", "logstash-${tag}"],
"customize_template" => ["customize_template", '{"<<TAG>>":"${tag}"}'],
"logstash_prefix_placeholder" => ["logstash_prefix", "fluentd-${tag}"],
"deflector_alias_placeholder" => ["deflector_alias", "fluentd-${tag}"],
"application_name_placeholder" => ["application_name", "fluentd-${tag}"],
)
test 'tag placeholder' do |data|
param, value = data
config = Fluent::Config::Element.new(
'ROOT', '', {
'@type' => 'elasticsearch',
param => value
}, [
Fluent::Config::Element.new('buffer', 'tag', {}, [])
])
driver(config)
assert_true driver.instance.placeholder_substitution_needed_for_template?
end
data("host placeholder" => ["host", "host-%Y%m%d.google.com"],
"index_name_placeholder" => ["index_name", "logstash-%Y%m%d"],
"template_name_placeholder" => ["template_name", "logstash-%Y%m%d"],
"customize_template" => ["customize_template", '{"<<TAG>>":"fluentd-%Y%m%d"}'],
"logstash_prefix_placeholder" => ["logstash_prefix", "fluentd-%Y%m%d"],
"deflector_alias_placeholder" => ["deflector_alias", "fluentd-%Y%m%d"],
"application_name_placeholder" => ["application_name", "fluentd-%Y%m%d"],
)
test 'time placeholder' do |data|
param, value = data
config = Fluent::Config::Element.new(
'ROOT', '', {
'@type' => 'elasticsearch',
param => value
}, [
Fluent::Config::Element.new('buffer', 'time', {
'timekey' => '1d'
}, [])
])
driver(config)
assert_true driver.instance.placeholder_substitution_needed_for_template?
end
data("host placeholder" => ["host", "host-${mykey}.google.com"],
"index_name_placeholder" => ["index_name", "logstash-${mykey}"],
"template_name_placeholder" => ["template_name", "logstash-${mykey}"],
"customize_template" => ["customize_template", '{"<<TAG>>":"${mykey}"}'],
"logstash_prefix_placeholder" => ["logstash_prefix", "fluentd-${mykey}"],
"logstash_dateformat_placeholder" => ["logstash_dateformat", "${mykey}"],
"deflector_alias_placeholder" => ["deflector_alias", "fluentd-${mykey}"],
"application_name_placeholder" => ["application_name", "fluentd-${mykey}"],
)
test 'custom placeholder' do |data|
param, value = data
config = Fluent::Config::Element.new(
'ROOT', '', {
'@type' => 'elasticsearch',
param => value
}, [
Fluent::Config::Element.new('buffer', 'mykey', {
'chunk_keys' => 'mykey',
'timekey' => '1d',
}, [])
])
driver(config)
assert_true driver.instance.placeholder_substitution_needed_for_template?
end
data("host placeholder" => ["host", "host-${tag}.google.com"],
"index_name_placeholder" => ["index_name", "logstash-${es_index}-%Y%m%d"],
"template_name_placeholder" => ["template_name", "logstash-${tag}-%Y%m%d"],
"customize_template" => ["customize_template", '{"<<TAG>>":"${es_index}"}'],
"logstash_prefix_placeholder" => ["logstash_prefix", "fluentd-${es_index}-%Y%m%d"],
"logstash_dataformat_placeholder" => ["logstash_dateformat", "${es_index}"],
"deflector_alias_placeholder" => ["deflector_alias", "fluentd-%Y%m%d"],
"application_name_placeholder" => ["application_name", "fluentd-${tag}-${es_index}-%Y%m%d"],
)
test 'mixed placeholder' do |data|
param, value = data
config = Fluent::Config::Element.new(
'ROOT', '', {
'@type' => 'elasticsearch',
param => value
}, [
Fluent::Config::Element.new('buffer', 'tag,time,es_index', {
'chunk_keys' => 'es_index',
'timekey' => '1d',
}, [])
])
driver(config)
assert_true driver.instance.placeholder_substitution_needed_for_template?
end
end
sub_test_case 'chunk_keys requirement' do
test 'tag in chunk_keys' do
assert_nothing_raised do
driver(Fluent::Config::Element.new(
'ROOT', '', {
'@type' => 'elasticsearch',
'host' => 'log.google.com',
'port' => 777,
'scheme' => 'https',
'path' => '/es/',
'user' => 'john',
'password' => 'doe',
}, [
Fluent::Config::Element.new('buffer', 'tag', {
'chunk_keys' => 'tag'
}, [])
]
))
end
end
test '_index in chunk_keys' do
assert_nothing_raised do
driver(Fluent::Config::Element.new(
'ROOT', '', {
'@type' => 'elasticsearch',
'host' => 'log.google.com',
'port' => 777,
'scheme' => 'https',
'path' => '/es/',
'user' => 'john',
'password' => 'doe',
}, [
Fluent::Config::Element.new('buffer', '_index', {
'chunk_keys' => '_index'
}, [])
]
))
end
end
test 'lack of tag and _index in chunk_keys' do
assert_raise_message(/'tag' or '_index' in chunk_keys is required./) do
driver(Fluent::Config::Element.new(
'ROOT', '', {
'@type' => 'elasticsearch',
'host' => 'log.google.com',
'port' => 777,
'scheme' => 'https',
'path' => '/es/',
'user' => 'john',
'password' => 'doe',
}, [
Fluent::Config::Element.new('buffer', 'mykey', {
'chunk_keys' => 'mykey'
}, [])
]
))
end
end
end
test 'Detected exclusive features which are host placeholder, template installation, and verify Elasticsearch version at startup' do
cwd = File.dirname(__FILE__)
template_file = File.join(cwd, 'test_template.json')
assert_raise_message(/host placeholder, template installation, and verify Elasticsearch version at startup are exclusive feature at same time./) do
config = %{
host logs-${tag}.google.com
port 777
scheme https
path /es/
user john
password doe
template_name logstash
template_file #{template_file}
verify_es_version_at_startup true
default_elasticsearch_version 6
}
driver(config)
end
end
class GetElasticsearchIncompatibleVersionTest < self
def create_driver(conf='', client_version="7.14")
# For request stub to detect compatibility.
@client_version ||= client_version
# Ensure original implementation existence.
Fluent::Plugin::ElasticsearchOutput.module_eval(<<-CODE)
def detect_es_major_version
begin
@_es_info ||= client.info
rescue ::Elasticsearch::UnsupportedProductError => e
raise Fluent::ConfigError, "Using Elasticsearch client #{@client_version} is not compatible for your Elasticsearch server. Please check your using elasticsearch gem version and Elasticsearch server."
end
begin
unless version = @_es_info.dig("version", "number")
version = @default_elasticsearch_version
end
rescue NoMethodError => e
log.warn "#{@_es_info} can not dig version information. Assuming Elasticsearch #{@default_elasticsearch_version}", error: e
version = @default_elasticsearch_version
end
version.to_i
end
CODE
Fluent::Plugin::ElasticsearchOutput.module_eval(<<-CODE)
def client_library_version
#{@client_version}
end
CODE
Fluent::Test::Driver::Output.new(Fluent::Plugin::ElasticsearchOutput).configure(conf)
end
def test_incompatible_es_version
if Gem::Version.create(::TRANSPORT_CLASS::VERSION) < Gem::Version.create("7.14.0")
omit "This test is not effective before elasticsearch 7.14"
end
config = %{
host logs.google.com
port 778
scheme https
path /es/
user john
password doe
verify_es_version_at_startup true
max_retry_get_es_version 1
}
connection_resets = 0
stub_request(:get, "https://logs.google.com:778/es//").
with(basic_auth: ['john', 'doe']) do |req|
connection_resets += 1
raise ::Elasticsearch::UnsupportedProductError
end
assert_raise(Fluent::ConfigError) do
create_driver(config)
end
assert_equal(1, connection_resets)
end
end
data("legacy_template" => [true, "_template"],
"new_template" => [false, "_index_template"])
def test_template_already_present(data)
use_legacy_template_flag, endpoint = data
if !use_legacy_template_flag && Gem::Version.create(::TRANSPORT_CLASS::VERSION) < Gem::Version.create("7.8.0")
omit "elastisearch-ruby v7.8.0 or later is needed."
end
config = %{
host logs.google.com
port 777
scheme https
path /es/
user john
password doe
template_name logstash
template_file /abc123
use_legacy_template #{use_legacy_template_flag}
}
# connection start
stub_request(:head, "https://logs.google.com:777/es//").
with(basic_auth: ['john', 'doe']).
to_return(:status => 200, :body => "", :headers => {'x-elastic-product' => 'Elasticsearch'})
# check if template exists
stub_request(:get, "https://logs.google.com:777/es//#{endpoint}/logstash").
with(basic_auth: ['john', 'doe']).
to_return(:status => 200, :body => "", :headers => {'x-elastic-product' => 'Elasticsearch'})
stub_elastic_info("https://logs.google.com:777/es//")
driver(config)
assert_not_requested(:put, "https://logs.google.com:777/es//#{endpoint}/logstash")
end
data("legacy_template" => [true, "_template"],
"new_template" => [false, "_index_template"])
def test_template_create(data)
use_legacy_template_flag, endpoint = data
if !use_legacy_template_flag && Gem::Version.create(::TRANSPORT_CLASS::VERSION) < Gem::Version.create("7.8.0")
omit "elastisearch-ruby v7.8.0 or later is needed."
end
cwd = File.dirname(__FILE__)
template_file = if use_legacy_template_flag
File.join(cwd, 'test_template.json')
else
File.join(cwd, 'test_index_template.json')
end
config = %{
host logs.google.com
port 777
scheme https
path /es/
user john
password doe
template_name logstash
template_file #{template_file}
use_legacy_template #{use_legacy_template_flag}
}
# connection start
stub_request(:head, "https://logs.google.com:777/es//").