-
Notifications
You must be signed in to change notification settings - Fork 307
/
Copy pathelasticsearch_spec.rb
1881 lines (1510 loc) · 74.3 KB
/
elasticsearch_spec.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 "../../../spec/spec_helper"
require "base64"
require "flores/random"
require 'concurrent/atomic/count_down_latch'
require "logstash/outputs/elasticsearch"
require 'logstash/plugin_mixins/ecs_compatibility_support/spec_helper'
require 'rspec/collection_matchers'
describe LogStash::Outputs::ElasticSearch do
subject(:elasticsearch_output_instance) { described_class.new(options) }
let(:options) { {} }
let(:maximum_seen_major_version) { [6,7,8].sample }
let(:do_register) { true }
let(:stub_http_client_pool!) do
allow_any_instance_of(LogStash::Outputs::ElasticSearch::HttpClient::Pool).to receive(:start)
end
let(:spy_http_client_builder!) do
allow(described_class::HttpClientBuilder).to receive(:build).with(any_args).and_call_original
end
let(:after_successful_connection_thread_mock) do
double('after_successful_connection_thread', value: true)
end
before(:each) do
if do_register
spy_http_client_builder!
stub_http_client_pool!
allow(subject).to receive(:finish_register) # stub-out thread completion (to avoid error log entries)
# emulate 'successful' ES connection on the same thread
allow(subject).to receive(:after_successful_connection) { |&block| block.call }.
and_return after_successful_connection_thread_mock
allow(subject).to receive(:stop_after_successful_connection_thread)
subject.register
allow(subject.client).to receive(:maximum_seen_major_version).at_least(:once).and_return(maximum_seen_major_version)
allow(subject.client).to receive(:get_xpack_info)
subject.client.pool.adapter.manticore.respond_with(:body => "{}")
end
end
after(:each) do
subject.close
end
context "check aborting of a batch" do
context "on an unreachable ES instance" do
let(:events) { [ ::LogStash::Event.new("foo" => "bar1"), ::LogStash::Event.new("foo" => "bar2") ] }
let(:shutdown_value) { true }
let(:logger) { double("logger") }
let(:never_ending) { Thread.new { sleep 1 while true } }
let(:do_register) { false }
before(:each) do
spy_http_client_builder!
stub_http_client_pool!
allow(subject).to receive(:finish_register) # stub-out thread completion (to avoid error log entries)
# emulate 'failed' ES connection, which sleeps forever
allow(subject).to receive(:after_successful_connection) { |&block| never_ending }
allow(subject).to receive(:stop_after_successful_connection_thread)
subject.register
allow(subject.client).to receive(:maximum_seen_major_version).at_least(:once).and_return(maximum_seen_major_version)
allow(subject.client).to receive(:get_xpack_info)
subject.client.pool.adapter.manticore.respond_with(:body => "{}")
allow(subject).to receive(:logger).and_return(logger)
allow(logger).to receive(:info)
allow(subject).to receive(:pipeline_shutdown_requested?) do
shutdown_value
end
end
it "the #multi_receive abort while waiting on unreachable and a shutdown is requested" do
expect { subject.multi_receive(events) }.to raise_error(org.logstash.execution.AbortedBatchException)
expect(logger).to have_received(:info).with(/Aborting the batch due to shutdown request while waiting for connections to become live/i)
end
end
context "on a reachable ES instance" do
let(:events) { [ ::LogStash::Event.new("foo" => "bar1"), ::LogStash::Event.new("foo" => "bar2") ] }
let(:logger) { double("logger") }
before(:each) do
allow(subject).to receive(:logger).and_return(logger)
allow(logger).to receive(:info)
allow(subject).to receive(:pipeline_shutdown_requested?).and_return(true)
allow(subject).to receive(:retrying_submit)
end
it "the #multi_receive doesn't abort when waiting for a connection on alive ES and a shutdown is requested" do
subject.multi_receive(events)
expect(logger).to_not have_received(:info).with(/Aborting the batch due to shutdown request while waiting for connections to become live/i)
end
end
context "when a connected ES becomes unreachable" do
# let(:error) do
# ::LogStash::Outputs::ElasticSearch::HttpClient::Pool::BadResponseCodeError.new(
# 429, double("url").as_null_object, request_body, double("response body")
# )
# end
shared_examples 'raise an abort error' do
let(:options) {
{
"index" => "my-index",
"hosts" => ["localhost","localhost:9202"],
"path" => "some-path",
"manage_template" => false
}
}
let(:manticore_urls) { subject.client.pool.urls }
let(:manticore_url) { manticore_urls.first }
let(:stub_http_client_pool!) do
[:start_resurrectionist, :start_sniffer, :healthcheck!].each do |method|
allow_any_instance_of(LogStash::Outputs::ElasticSearch::HttpClient::Pool).to receive(method)
end
end
let(:event) { ::LogStash::Event.new("foo" => "bar") }
let(:logger) { double("logger").as_null_object }
let(:response) { { :errors => [], :items => [] } }
let(:request_body) { double(:request_body, :bytesize => 1023) }
before(:each) do
bulk_param = [["index", anything, event.to_hash]]
allow(subject).to receive(:logger).and_return(logger)
# fail consistently for ever
allow(subject.client).to receive(:bulk).with(bulk_param).and_raise(error)
end
it "should exit the retry with an abort exception if shutdown is requested" do
# trigger the shutdown signal
allow(subject).to receive(:pipeline_shutdown_requested?) { true }
# execute in another thread because it blocks in a retry loop until the shutdown is triggered
th = Thread.new do
subject.multi_receive([event])
rescue org.logstash.execution.AbortedBatchException => e
# return exception's class so that it can be verified when retrieving the thread's value
e.class
end
expect(th.value).to eq(org.logstash.execution.AbortedBatchException)
end
end
context "with 429 error" do
let(:error) do
::LogStash::Outputs::ElasticSearch::HttpClient::Pool::BadResponseCodeError.new(
429, double("url").as_null_object, request_body, double("response body")
)
end
it_behaves_like 'raise an abort error'
end
context "with 'no connections' error" do
let(:error) { ::LogStash::Outputs::ElasticSearch::HttpClient::Pool::NoConnectionAvailableError.new }
it_behaves_like 'raise an abort error'
end
end
end if LOGSTASH_VERSION >= '8.8'
context "with an active instance" do
let(:options) {
{
"index" => "my-index",
"hosts" => ["localhost","localhost:9202"],
"path" => "some-path",
"manage_template" => false
}
}
let(:manticore_urls) { subject.client.pool.urls }
let(:manticore_url) { manticore_urls.first }
let(:stub_http_client_pool!) do
[:start_resurrectionist, :start_sniffer, :healthcheck!].each do |method|
allow_any_instance_of(LogStash::Outputs::ElasticSearch::HttpClient::Pool).to receive(method)
end
end
describe "getting a document type" do
context "if document_type isn't set" do
let(:options) { super().merge("document_type" => nil)}
context "for 7.x elasticsearch clusters" do
let(:maximum_seen_major_version) { 7 }
it "should return '_doc'" do
expect(subject.send(:get_event_type, LogStash::Event.new("type" => "foo"))).to eql("_doc")
end
end
context "for 6.x elasticsearch clusters" do
let(:maximum_seen_major_version) { 6 }
it "should return 'doc'" do
expect(subject.send(:get_event_type, LogStash::Event.new("type" => "foo"))).to eql("doc")
end
end
end
context "with 'document type set'" do
let(:options) { super().merge("document_type" => "bar")}
it "should get the event type from the 'document_type' setting" do
expect(subject.send(:get_event_type, LogStash::Event.new())).to eql("bar")
end
end
end
describe "building an event action tuple" do
context "for 7.x elasticsearch clusters" do
let(:maximum_seen_major_version) { 7 }
it "should not include '_type' when 'document_type' is not explicitly defined" do
action_tuple = subject.send(:event_action_tuple, LogStash::Event.new("type" => "foo"))
action_params = action_tuple[1]
expect(action_params).not_to include(:_type => "_doc")
end
context "with 'document type set'" do
let(:options) { super().merge("document_type" => "bar")}
it "should get the event type from the 'document_type' setting" do
action_tuple = subject.send(:event_action_tuple, LogStash::Event.new("type" => "foo"))
action_params = action_tuple[1]
expect(action_params).to include(:_type => "bar")
end
end
end
context "for 8.x elasticsearch clusters" do
let(:maximum_seen_major_version) { 8 }
it "should not include '_type'" do
action_tuple = subject.send(:event_action_tuple, LogStash::Event.new("type" => "foo"))
action_params = action_tuple[1]
expect(action_params).not_to include(:_type)
end
context "with 'document type set'" do
let(:options) { super().merge("document_type" => "bar")}
it "should not include '_type'" do
action_tuple = subject.send(:event_action_tuple, LogStash::Event.new("type" => "foo"))
action_params = action_tuple[1]
expect(action_params).not_to include(:_type)
end
end
end
end
describe "with event integration metadata" do
let(:event_fields) {{}}
let(:event) { LogStash::Event.new(event_fields)}
context "when plugin's version is specified" do
let(:options) { super().merge("version" => "123")}
context "when the event contains an integration metadata version" do
let(:event) { LogStash::Event.new({"@metadata" => {"_ingest_document" => {"version" => "456"}}}) }
it "plugin's version is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:version => "123")
end
end
context "when the event DOESN'T contains an integration metadata version" do
it "plugin's version is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:version => "123")
end
end
end
context "when plugin's version is NOT specified" do
context "when the event contains an integration metadata version" do
let(:event) { LogStash::Event.new({"@metadata" => {"_ingest_document" => {"version" => "456"}}}) }
context "when datastream settings are NOT configured" do
it "event's metadata version is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:version => "456")
end
end
context "when datastream settings are configured" do
# NOTE: we validate with datastream-specific `data_stream_event_action_tuple`
let(:event_fields) { super().merge({"data_stream" => {"type" => "logs", "dataset" => "generic", "namespace" => "default"}}) }
it "no version is used" do
expect(subject.send(:data_stream_event_action_tuple, event)[1]).to_not include(:version)
end
end
end
context "when the event DOESN'T contain an integration metadata version" do
it "plugin's default id mechanism is used" do
expect(subject.send(:event_action_tuple, event)[1]).to_not include(:version)
end
end
end
context "when plugin's version_type is specified" do
let(:options) { super().merge("version_type" => "internal")}
context "when the event contains an integration metadata version_type" do
let(:event) { LogStash::Event.new({"@metadata" => {"_ingest_document" => {"version_type" => "external"}}}) }
context "when datastream settings are NOT configured" do
it "plugin's version_type is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:version_type => "internal")
end
end
context "when datastream settings are configured" do
# NOTE: we validate with datastream-specific `data_stream_event_action_tuple`
let(:event_fields) { super().merge({"data_stream" => {"type" => "logs", "dataset" => "generic", "namespace" => "default"}}) }
it "no version_type is used" do
expect(subject.send(:data_stream_event_action_tuple, event)[1]).to_not include(:version_type)
end
end
end
context "when the event DOESN'T contains an integration metadata version_type" do
it "plugin's version_type is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:version_type => "internal")
end
end
end
context "when plugin's version_type is NOT specified" do
context "when the event contains an integration metadata version_type" do
let(:event) { LogStash::Event.new({"@metadata" => {"_ingest_document" => {"version_type" => "external"}}}) }
it "event's metadata version_type is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:version_type => "external")
end
end
context "when the event DOESN'T contain an integration metadata version_type" do
it "plugin's default id mechanism is used" do
expect(subject.send(:event_action_tuple, event)[1]).to_not include(:version_type)
end
end
end
context "when plugin's routing is specified" do
let(:options) { super().merge("routing" => "settings_routing")}
context "when the event contains an integration metadata routing" do
let(:event) { LogStash::Event.new({"@metadata" => {"_ingest_document" => {"routing" => "meta-document-routing"}}}) }
it "plugin's routing is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:routing => "settings_routing")
end
end
context "when the event DOESN'T contains an integration metadata routing" do
it "plugin's routing is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:routing => "settings_routing")
end
end
end
context "when plugin's routing is NOT specified" do
context "when the event contains an integration metadata routing" do
let(:event) { LogStash::Event.new({"@metadata" => {"_ingest_document" => {"routing" => "meta-document-routing"}}}) }
it "event's metadata routing is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:routing => "meta-document-routing")
end
end
context "when the event DOESN'T contain an integration metadata routing" do
it "plugin's default id mechanism is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:routing => nil)
end
end
end
context "when plugin's index is specified" do
let(:options) { super().merge("index" => "index_from_settings")}
context "when the event contains an integration metadata index" do
let(:event_fields) { super().merge({"@metadata" => {"_ingest_document" => {"index" => "meta-document-index"}}}) }
it "plugin's index is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:_index => "index_from_settings")
end
end
context "when the event doesn't contains an integration metadata index" do
it "plugin's index is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:_index => "index_from_settings")
end
end
end
context "when plugin's index is NOT specified" do
let(:options) { super().merge("index" => nil)}
context "when the event contains an integration metadata index" do
let(:event_fields) { super().merge({"@metadata" => {"_ingest_document" => {"index" => "meta-document-index"}}}) }
it "event's metadata index is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:_index => "meta-document-index")
end
context "when datastream settings are NOT configured" do
it "event's metadata index is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:_index => "meta-document-index")
end
end
context "when datastream settings are configured" do
let(:event_fields) { super().merge({"data_stream" => {"type" => "logs", "dataset" => "generic", "namespace" => "default"}}) }
it "event's metadata index is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:_index => "meta-document-index")
end
end
end
context "when the event DOESN'T contain integration metadata index" do
let(:default_index_resolved) { event.sprintf(subject.default_index) }
it "default index is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:_index => default_index_resolved)
end
context "when datastream settings are NOT configured" do
it "default index is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:_index => default_index_resolved)
end
end
context "when datastream settings are configured" do
let(:event_fields) { super().merge({"data_stream" => {"type" => "logs", "dataset" => "generic", "namespace" => "default"}}) }
it "default index is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:_index => default_index_resolved)
end
end
end
end
context "when plugin's document_id is specified" do
let(:options) { super().merge("document_id" => "id_from_settings")}
context "when the event contains an integration metadata document_id" do
let(:event) { LogStash::Event.new({"@metadata" => {"_ingest_document" => {"id" => "meta-document-id"}}}) }
it "plugin's document_id is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:_id => "id_from_settings")
end
end
context "when the event DOESN'T contains an integration metadata document_id" do
it "plugin's document_id is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:_id => "id_from_settings")
end
end
end
context "when plugin's document_id is NOT specified" do
let(:options) { super().merge("document_id" => nil)}
context "when the event contains an integration metadata document_id" do
let(:event) { LogStash::Event.new({"@metadata" => {"_ingest_document" => {"id" => "meta-document-id"}}}) }
it "event's metadata document_id is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:_id => "meta-document-id")
end
end
context "when the event DOESN'T contains an integration metadata document_id" do
it "plugin's default id mechanism is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:_id => nil)
end
end
end
context "when plugin's pipeline is specified" do
let(:options) { {"pipeline" => "pipeline_from_settings" } }
context "when the event contains an integration metadata pipeline" do
let(:event) { LogStash::Event.new({"@metadata" => {"_ingest_document" => {"pipeline" => "integration-pipeline"}}}) }
it "plugin's pipeline is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:pipeline => "pipeline_from_settings")
end
end
context "when the event DOESN'T contains an integration metadata pipeline" do
it "plugin's pipeline is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:pipeline => "pipeline_from_settings")
end
end
end
context "when plugin's pipeline is NOT specified" do
let(:options) { super().merge("pipeline" => nil)}
context "when the event contains an integration metadata pipeline" do
let(:metadata) { {"_ingest_document" => {"pipeline" => "integration-pipeline"}} }
let(:event) { LogStash::Event.new({"@metadata" => metadata}) }
it "event's metadata pipeline is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:pipeline => "integration-pipeline")
end
context "when also target_ingest_pipeline id defined" do
let(:metadata) { super().merge({"target_ingest_pipeline" => "meta-ingest-pipeline"}) }
it "then event's pipeline from _ingest_document is used" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:pipeline => "integration-pipeline")
end
end
end
context "when the event DOESN'T contains an integration metadata pipeline" do
it "plugin's default pipeline mechanism is used" do
expect(subject.send(:event_action_tuple, event)[1]).to_not have_key(:pipeline)
end
end
end
end
describe "with auth" do
let(:user) { "myuser" }
let(:password) { ::LogStash::Util::Password.new("mypassword") }
shared_examples "an authenticated config" do
it "should set the URL auth correctly" do
expect(manticore_url.user).to eq user
end
end
context "as part of a URL" do
let(:options) {
super().merge("hosts" => ["http://#{user}:#{password.value}@localhost:9200"])
}
include_examples("an authenticated config")
end
context "as a hash option" do
let(:options) {
super().merge!(
"user" => user,
"password" => password
)
}
include_examples("an authenticated config")
end
context 'cloud_auth also set' do
let(:do_register) { false } # this is what we want to test, so we disable the before(:each) call
let(:options) { { "user" => user, "password" => password, "cloud_auth" => "elastic:my-passwd-00" } }
it "should fail" do
expect { subject.register }.to raise_error LogStash::ConfigurationError, /Multiple authentication options are specified/
end
end
context 'api_key also set' do
let(:do_register) { false } # this is what we want to test, so we disable the before(:each) call
let(:options) { { "user" => user, "password" => password, "api_key" => "some_key" } }
it "should fail" do
expect { subject.register }.to raise_error LogStash::ConfigurationError, /Multiple authentication options are specified/
end
end
end
describe "with path" do
it "should properly create a URI with the path" do
expect(subject.path).to eql(options["path"])
end
it "should properly set the path on the HTTP client adding slashes" do
expect(manticore_url.path).to eql("/" + options["path"] + "/")
end
context "with extra slashes" do
let(:path) { "/slashed-path/ "}
let(:options) { super().merge("path" => "/some-path/") }
it "should properly set the path on the HTTP client without adding slashes" do
expect(manticore_url.path).to eql(options["path"])
end
end
context "with a URI based path" do
let(:options) do
o = super()
o.delete("path")
o["hosts"] = ["http://localhost:9200/mypath/"]
o
end
let(:client_host_path) { manticore_url.path }
it "should initialize without error" do
expect { subject }.not_to raise_error
end
it "should use the URI path" do
expect(client_host_path).to eql("/mypath/")
end
context "with a path option but no URL path" do
let(:options) do
o = super()
o["path"] = "/override/"
o["hosts"] = ["http://localhost:9200"]
o
end
it "should initialize without error" do
expect { subject }.not_to raise_error
end
it "should use the option path" do
expect(client_host_path).to eql("/override/")
end
end
# If you specify the path in two spots that is an error!
context "with a path option and a URL path" do
let(:do_register) { false } # Register will fail
let(:options) do
o = super()
o["path"] = "/override"
o["hosts"] = ["http://localhost:9200/mypath/"]
o
end
it "should initialize with an error" do
expect { subject.register }.to raise_error(LogStash::ConfigurationError)
end
end
end
end
describe "without a port specified" do
let(:options) { super().merge('hosts' => 'localhost') }
it "should properly set the default port (9200) on the HTTP client" do
expect(manticore_url.port).to eql(9200)
end
end
describe "with a port other than 9200 specified" do
let(:options) { super().merge('hosts' => 'localhost:9202') }
it "should properly set the specified port on the HTTP client" do
expect(manticore_url.port).to eql(9202)
end
end
describe "when 'dlq_custom_codes'" do
let(:options) { super().merge('dlq_custom_codes' => [404]) }
let(:do_register) { false }
context "contains already defined codes" do
it "should raise a configuration error" do
expect{ subject.register }.to raise_error(LogStash::ConfigurationError, /are already defined as standard DLQ error codes/)
end
end
context "is configured but DLQ is not enabled" do
it "raise a configuration error" do
allow(subject).to receive(:dlq_enabled?).and_return(false)
expect{ subject.register }.to raise_error(LogStash::ConfigurationError, /configured while DLQ is not enabled/)
end
end
end if LOGSTASH_VERSION > '7.0'
describe "#multi_receive" do
let(:events) { [double("one"), double("two"), double("three")] }
let(:events_tuples) { [double("one t"), double("two t"), double("three t")] }
before do
allow(subject).to receive(:retrying_submit).with(anything)
events.each_with_index do |e,i|
allow(subject).to receive(:event_action_tuple).with(e).and_return(events_tuples[i])
end
subject.multi_receive(events)
end
end
context "429 errors" do
let(:event) { ::LogStash::Event.new("foo" => "bar") }
let(:error) do
::LogStash::Outputs::ElasticSearch::HttpClient::Pool::BadResponseCodeError.new(
429, double("url").as_null_object, request_body, double("response body")
)
end
let(:logger) { double("logger").as_null_object }
let(:response) { { :errors => [], :items => [] } }
let(:request_body) { double(:request_body, :bytesize => 1023) }
before(:each) do
i = 0
bulk_param = [["index", anything, event.to_hash]]
allow(subject).to receive(:logger).and_return(logger)
# Fail the first time bulk is called, succeed the next time
allow(subject.client).to receive(:bulk).with(bulk_param) do
i += 1
if i == 1
raise error
end
end.and_return(response)
subject.multi_receive([event])
end
it "should retry the 429 till it goes away" do
expect(subject.client).to have_received(:bulk).twice
end
it "should log a debug message" do
expect(subject.logger).to have_received(:debug).with(/Encountered a retryable error/i, anything)
end
end
context "unexpected bulk response" do
let(:options) do
{ "hosts" => "127.0.0.1:9999", "index" => "%{foo}", "manage_template" => false, "http_compression" => false }
end
let(:events) { [ ::LogStash::Event.new("foo" => "bar1"), ::LogStash::Event.new("foo" => "bar2") ] }
let(:bulk_response) do
# shouldn't really happen but we've seen this happen - here ES returns more items than were sent
{ "took"=>1, "ingest_took"=>9, "errors"=>true,
"items"=>[{"index"=>{"_index"=>"bar1", "_type"=>"_doc", "_id"=>nil, "status"=>500,
"error"=>{"type" => "illegal_state_exception",
"reason" => "pipeline with id [test-ingest] could not be loaded, caused by [ElasticsearchParseException[Error updating pipeline with id [test-ingest]]; nested: ElasticsearchException[java.lang.IllegalArgumentException: no enrich index exists for policy with name [test-metadata1]]; nested: IllegalArgumentException[no enrich index exists for policy with name [test-metadata1]];; ElasticsearchException[java.lang.IllegalArgumentException: no enrich index exists for policy with name [test-metadata1]]; nested: IllegalArgumentException[no enrich index exists for policy with name [test-metadata1]];; java.lang.IllegalArgumentException: no enrich index exists for policy with name [test-metadata1]]"
}
}
},
# NOTE: this is an artificial success (usually everything fails with a 500) but even if some doc where
# to succeed due the unexpected response items we can not clearly identify which actions to retry ...
{"index"=>{"_index"=>"bar2", "_type"=>"_doc", "_id"=>nil, "status"=>201}},
{"index"=>{"_index"=>"bar2", "_type"=>"_doc", "_id"=>nil, "status"=>500,
"error"=>{"type" => "illegal_state_exception",
"reason" => "pipeline with id [test-ingest] could not be loaded, caused by [ElasticsearchParseException[Error updating pipeline with id [test-ingest]]; nested: ElasticsearchException[java.lang.IllegalArgumentException: no enrich index exists for policy with name [test-metadata1]];"
}
}
}]
}
end
before(:each) do
allow(subject.client).to receive(:bulk_send).with(instance_of(StringIO), instance_of(Array)) do |stream, actions|
expect( stream.string ).to include '"foo":"bar1"'
expect( stream.string ).to include '"foo":"bar2"'
end.and_return(bulk_response, {"errors"=>false}) # let's make it go away (second call) to not retry indefinitely
end
it "should retry submit" do
allow(subject.logger).to receive(:error).with(/Encountered an unexpected error/i, anything)
allow(subject.client).to receive(:bulk).and_call_original # track count
subject.multi_receive(events)
expect(subject.client).to have_received(:bulk).twice
end
it "should log specific error message" do
expect(subject.logger).to receive(:error).with(/Encountered an unexpected error/i,
hash_including(:message => 'Sent 2 documents but Elasticsearch returned 3 responses (likely a bug with _bulk endpoint)'))
subject.multi_receive(events)
end
end
context "unsupported actions" do
let(:options) { super().merge("index" => "logstash", "action" => "%{action_field}") }
context "with multiple valid actions with one trailing invalid action" do
let(:events) {[
LogStash::Event.new("action_field" => "index", "id" => 1, "message"=> "hello"),
LogStash::Event.new("action_field" => "index", "id" => 2, "message"=> "hi"),
LogStash::Event.new("action_field" => "index", "id" => 3, "message"=> "bye"),
LogStash::Event.new("action_field" => "unsupported_action", "id" => 4, "message"=> "world!")
]}
it "rejects unsupported actions" do
event_result = subject.send(:safe_interpolation_map_events, events)
expect(event_result.successful_events).to have_exactly(3).items
event_result.successful_events.each do |action, _|
expect(action).to_not eql("unsupported_action")
end
expect(event_result.event_mapping_errors).to have_exactly(1).items
event_result.event_mapping_errors.each do |event_mapping_error|
expect(event_mapping_error.message).to eql("Elasticsearch doesn't support [unsupported_action] action")
end
end
end
context "with one leading invalid action followed by multiple valid actions" do
let(:events) {[
LogStash::Event.new("action_field" => "unsupported_action", "id" => 1, "message"=> "world!"),
LogStash::Event.new("action_field" => "index", "id" => 2, "message"=> "hello"),
LogStash::Event.new("action_field" => "index", "id" => 3, "message"=> "hi"),
LogStash::Event.new("action_field" => "index", "id" => 4, "message"=> "bye")
]}
it "rejects unsupported actions" do
event_result = subject.send(:safe_interpolation_map_events, events)
expect(event_result.successful_events).to have_exactly(3).items
event_result.successful_events.each do |action, _|
expect(action).to_not eql("unsupported_action")
end
expect(event_result.event_mapping_errors).to have_exactly(1).items
event_result.event_mapping_errors.each do |event_mapping_error|
expect(event_mapping_error.message).to eql("Elasticsearch doesn't support [unsupported_action] action")
end
end
end
context "with batch of multiple invalid actions and no valid actions" do
let(:events) {[
LogStash::Event.new("action_field" => "unsupported_action1", "id" => 1, "message"=> "world!"),
LogStash::Event.new("action_field" => "unsupported_action2", "id" => 2, "message"=> "hello"),
LogStash::Event.new("action_field" => "unsupported_action3", "id" => 3, "message"=> "hi"),
LogStash::Event.new("action_field" => "unsupported_action4", "id" => 4, "message"=> "bye")
]}
it "rejects unsupported actions" do
event_result = subject.send(:safe_interpolation_map_events, events)
expect(event_result.successful_events).to have(:no).items
event_result.successful_events.each do |action, _|
expect(action).to_not eql("unsupported_action")
end
expect(event_result.event_mapping_errors).to have_exactly(4).items
event_result.event_mapping_errors.each do |event_mapping_error|
expect(event_mapping_error.message).to include "Elasticsearch doesn't support"
end
end
end
context "with batch of intermixed valid and invalid actions" do
let(:events) {[
LogStash::Event.new("action_field" => "index", "id" => 1, "message"=> "world!"),
LogStash::Event.new("action_field" => "unsupported_action2", "id" => 2, "message"=> "hello"),
LogStash::Event.new("action_field" => "unsupported_action3", "id" => 3, "message"=> "hi"),
LogStash::Event.new("action_field" => "index", "id" => 4, "message"=> "bye")
]}
it "rejects unsupported actions" do
event_result = subject.send(:safe_interpolation_map_events, events)
expect(event_result.successful_events).to have_exactly(2).items
expect(event_result.event_mapping_errors).to have_exactly(2).items
event_result.event_mapping_errors.each do |event_mapping_error|
expect(event_mapping_error.message).to include "Elasticsearch doesn't support"
end
end
end
context "with batch of exactly one action that is invalid" do
let(:events) {[
LogStash::Event.new("action_field" => "index", "id" => 1, "message"=> "world!"),
LogStash::Event.new("action_field" => "index", "id" => 2, "message"=> "hello"),
LogStash::Event.new("action_field" => "unsupported_action3", "id" => 3, "message"=> "hi"),
LogStash::Event.new("action_field" => "index", "id" => 4, "message"=> "bye")
]}
it "rejects unsupported action" do
event_result = subject.send(:safe_interpolation_map_events, events)
expect(event_result.successful_events).to have_exactly(3).items
expect(event_result.event_mapping_errors).to have_exactly(1).items
event_result.event_mapping_errors.each do |event_mapping_error|
expect(event_mapping_error.message).to eql("Elasticsearch doesn't support [unsupported_action3] action")
end
end
end
end
end
context '413 errors' do
let(:options) { super().merge("http_compression" => "false") }
let(:payload_size) { LogStash::Outputs::ElasticSearch::TARGET_BULK_BYTES + 1024 }
let(:event) { ::LogStash::Event.new("message" => ("a" * payload_size ) ) }
let(:logger_stub) { double("logger").as_null_object }
before(:each) do
allow(elasticsearch_output_instance.client).to receive(:logger).and_return(logger_stub)
allow(elasticsearch_output_instance.client).to receive(:bulk).and_call_original
max_bytes = payload_size * 3 / 4 # ensure a failure first attempt
allow(elasticsearch_output_instance.client.pool).to receive(:post) do |path, params, body|
if body.length > max_bytes
max_bytes *= 2 # ensure a successful retry
double("Response", :code => 413, :body => "")
else
double("Response", :code => 200, :body => '{"errors":false,"items":[{"index":{"status":200,"result":"created"}}]}')
end
end
end
it 'retries the 413 until it goes away' do
elasticsearch_output_instance.multi_receive([event])
expect(elasticsearch_output_instance.client).to have_received(:bulk).twice
end
it 'logs about payload quantity and size' do
elasticsearch_output_instance.multi_receive([event])
expect(logger_stub).to have_received(:warn)
.with(a_string_matching(/413 Payload Too Large/),
hash_including(:action_count => 1, :content_length => a_value > 20_000_000))
end
end
context "with timeout set" do
let(:listener) { Flores::Random.tcp_listener }
let(:port) { listener[2] }
let(:options) do
{
"manage_template" => false,
"hosts" => "localhost:#{port}",
"timeout" => 0.1, # fast timeout
}
end
before do
# Expect a timeout to be logged.
expect(subject.logger).to receive(:error).with(/Attempted to send a bulk request/i, anything).at_least(:once)
expect(subject.client).to receive(:bulk).at_least(:twice).and_call_original
end
it "should fail after the timeout" do
#pending("This is tricky now that we do healthchecks on instantiation")
Thread.new { subject.multi_receive([LogStash::Event.new]) }
# Allow the timeout to occur
sleep 6
end
end
describe "the action option" do
context "with a sprintf action" do
let(:options) { {"action" => "%{myactionfield}" } }
let(:event) { LogStash::Event.new("myactionfield" => "update", "message" => "blah") }
it "should interpolate the requested action value when creating an event_action_tuple" do
expect(subject.send(:event_action_tuple, event).first).to eql("update")
end
end
context "with a sprintf action equals to update" do
let(:options) { {"action" => "%{myactionfield}", "upsert" => '{"message": "some text"}' } }
let(:event) { LogStash::Event.new("myactionfield" => "update", "message" => "blah") }
it "should obtain specific action's params from event_action_tuple" do
expect(subject.send(:event_action_tuple, event)[1]).to include(:_upsert)
end
end
context "with an invalid action" do
let(:options) { {"action" => "SOME Garbaaage"} }
let(:do_register) { false } # this is what we want to test, so we disable the before(:each) call
before { allow(subject).to receive(:finish_register) }
it "should raise a configuration error" do
expect { subject.register }.to raise_error(LogStash::ConfigurationError)
end
end
end
describe "the pipeline option" do