forked from envoyproxy/envoy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_test.cc
1757 lines (1504 loc) · 74.1 KB
/
server_test.cc
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
#include <algorithm>
#include <memory>
#include <vector>
#include "envoy/common/scope_tracker.h"
#include "envoy/config/core/v3/base.pb.h"
#include "envoy/network/exception.h"
#include "envoy/server/bootstrap_extension_config.h"
#include "envoy/server/fatal_action_config.h"
#include "source/common/common/assert.h"
#include "source/common/network/address_impl.h"
#include "source/common/network/listen_socket_impl.h"
#include "source/common/network/socket_option_impl.h"
#include "source/common/protobuf/protobuf.h"
#include "source/common/thread_local/thread_local_impl.h"
#include "source/common/version/version.h"
#include "source/server/instance_impl.h"
#include "source/server/process_context_impl.h"
#include "test/common/config/dummy_config.pb.h"
#include "test/common/stats/stat_test_utility.h"
#include "test/config/v2_link_hacks.h"
#include "test/integration/server.h"
#include "test/mocks/common.h"
#include "test/mocks/server/bootstrap_extension_factory.h"
#include "test/mocks/server/fatal_action_factory.h"
#include "test/mocks/server/hot_restart.h"
#include "test/mocks/server/instance.h"
#include "test/mocks/server/options.h"
#include "test/mocks/server/overload_manager.h"
#include "test/mocks/stats/mocks.h"
#include "test/test_common/environment.h"
#include "test/test_common/logging.h"
#include "test/test_common/registry.h"
#include "test/test_common/simulated_time_system.h"
#include "test/test_common/test_runtime.h"
#include "test/test_common/test_time.h"
#include "test/test_common/utility.h"
#include "absl/synchronization/notification.h"
#include "gtest/gtest.h"
#include "openssl/crypto.h"
using testing::_;
using testing::Assign;
using testing::HasSubstr;
using testing::InSequence;
using testing::Invoke;
using testing::InvokeWithoutArgs;
using testing::Return;
using testing::SaveArg;
using testing::StrictMock;
namespace Envoy {
namespace Server {
namespace {
TEST(ServerInstanceUtil, flushHelper) {
InSequence s;
NiceMock<Upstream::MockClusterManager> cm;
Stats::TestUtil::TestStore store;
Event::SimulatedTimeSystem time_system;
Stats::Counter& c = store.counter("hello");
c.inc();
store.gauge("world", Stats::Gauge::ImportMode::Accumulate).set(5);
store.histogram("histogram", Stats::Histogram::Unit::Unspecified);
store.textReadout("text").set("is important");
std::list<Stats::SinkPtr> sinks;
InstanceUtil::flushMetricsToSinks(sinks, store, cm, time_system);
// Make sure that counters have been latched even if there are no sinks.
EXPECT_EQ(1UL, c.value());
EXPECT_EQ(0, c.latch());
Stats::MockSink* sink = new StrictMock<Stats::MockSink>();
sinks.emplace_back(sink);
EXPECT_CALL(*sink, flush(_)).WillOnce(Invoke([](Stats::MetricSnapshot& snapshot) {
ASSERT_EQ(snapshot.counters().size(), 1);
EXPECT_EQ(snapshot.counters()[0].counter_.get().name(), "hello");
EXPECT_EQ(snapshot.counters()[0].delta_, 1);
ASSERT_EQ(snapshot.gauges().size(), 1);
EXPECT_EQ(snapshot.gauges()[0].get().name(), "world");
EXPECT_EQ(snapshot.gauges()[0].get().value(), 5);
ASSERT_EQ(snapshot.textReadouts().size(), 1);
EXPECT_EQ(snapshot.textReadouts()[0].get().name(), "text");
EXPECT_EQ(snapshot.textReadouts()[0].get().value(), "is important");
}));
c.inc();
InstanceUtil::flushMetricsToSinks(sinks, store, cm, time_system);
// Histograms don't currently work with the isolated store so test those with a mock store.
NiceMock<Stats::MockStore> mock_store;
Stats::ParentHistogramSharedPtr parent_histogram(new Stats::MockParentHistogram());
std::vector<Stats::ParentHistogramSharedPtr> parent_histograms = {parent_histogram};
ON_CALL(mock_store, forEachSinkedHistogram)
.WillByDefault([&](std::function<void(std::size_t)> f_size,
std::function<void(Stats::ParentHistogram&)> f_stat) {
if (f_size != nullptr) {
f_size(parent_histograms.size());
}
for (auto& histogram : parent_histograms) {
f_stat(*histogram);
}
});
EXPECT_CALL(*sink, flush(_)).WillOnce(Invoke([](Stats::MetricSnapshot& snapshot) {
EXPECT_TRUE(snapshot.counters().empty());
EXPECT_TRUE(snapshot.gauges().empty());
EXPECT_EQ(snapshot.histograms().size(), 1);
EXPECT_TRUE(snapshot.textReadouts().empty());
}));
InstanceUtil::flushMetricsToSinks(sinks, mock_store, cm, time_system);
}
TEST(ServerInstanceUtil, flushImportModeUninitializedGauges) {
InSequence s;
NiceMock<Upstream::MockClusterManager> cm;
Stats::TestUtil::TestStore store;
Event::SimulatedTimeSystem time_system;
Stats::Counter& c = store.counter("hello");
c.inc();
store.gauge("world", Stats::Gauge::ImportMode::Accumulate).set(5);
store.gauge("again", Stats::Gauge::ImportMode::Uninitialized).set(10);
std::list<Stats::SinkPtr> sinks;
InstanceUtil::flushMetricsToSinks(sinks, store, cm, time_system);
// Make sure that counters have been latched even if there are no sinks.
EXPECT_EQ(1UL, c.value());
EXPECT_EQ(0, c.latch());
Stats::MockSink* sink = new StrictMock<Stats::MockSink>();
sinks.emplace_back(sink);
EXPECT_CALL(*sink, flush(_)).WillOnce(Invoke([](Stats::MetricSnapshot& snapshot) {
ASSERT_EQ(snapshot.counters().size(), 1);
EXPECT_EQ(snapshot.counters()[0].counter_.get().name(), "hello");
EXPECT_EQ(snapshot.counters()[0].delta_, 1);
ASSERT_EQ(snapshot.gauges().size(), 2);
auto world_it = std::find_if(snapshot.gauges().begin(), snapshot.gauges().end(),
[](const std::reference_wrapper<const Stats::Gauge>& gauge) {
return gauge.get().name().compare("world") == 0;
});
ASSERT_TRUE(world_it != snapshot.gauges().end());
EXPECT_EQ(world_it->get().value(), 5);
auto again_it = std::find_if(snapshot.gauges().begin(), snapshot.gauges().end(),
[](const std::reference_wrapper<const Stats::Gauge>& gauge) {
return gauge.get().name().compare("again") == 0;
});
ASSERT_TRUE(again_it != snapshot.gauges().end());
EXPECT_EQ(again_it->get().value(), 10);
ASSERT_EQ(snapshot.textReadouts().size(), 0);
}));
c.inc();
InstanceUtil::flushMetricsToSinks(sinks, store, cm, time_system);
}
class RunHelperTest : public testing::Test {
public:
RunHelperTest() {
InSequence s;
#ifndef WIN32
sigterm_ = new Event::MockSignalEvent(&dispatcher_);
sigint_ = new Event::MockSignalEvent(&dispatcher_);
sigusr1_ = new Event::MockSignalEvent(&dispatcher_);
sighup_ = new Event::MockSignalEvent(&dispatcher_);
#endif
EXPECT_CALL(overload_manager_, start());
EXPECT_CALL(cm_, setInitializedCb(_)).WillOnce(SaveArg<0>(&cm_init_callback_));
ON_CALL(server_, shutdown()).WillByDefault(Assign(&shutdown_, true));
helper_ = std::make_unique<RunHelper>(server_, options_, dispatcher_, cm_, access_log_manager_,
init_manager_, overload_manager_,
[this] { start_workers_.ready(); });
}
NiceMock<MockInstance> server_;
testing::NiceMock<MockOptions> options_;
NiceMock<Event::MockDispatcher> dispatcher_;
NiceMock<Upstream::MockClusterManager> cm_;
NiceMock<AccessLog::MockAccessLogManager> access_log_manager_;
NiceMock<MockOverloadManager> overload_manager_;
Init::ManagerImpl init_manager_{""};
ReadyWatcher start_workers_;
std::unique_ptr<RunHelper> helper_;
std::function<void()> cm_init_callback_;
#ifndef WIN32
Event::MockSignalEvent* sigterm_;
Event::MockSignalEvent* sigint_;
Event::MockSignalEvent* sigusr1_;
Event::MockSignalEvent* sighup_;
#endif
bool shutdown_ = false;
};
TEST_F(RunHelperTest, Normal) {
EXPECT_CALL(start_workers_, ready());
cm_init_callback_();
}
// no signals on Windows
#ifndef WIN32
TEST_F(RunHelperTest, ShutdownBeforeCmInitialize) {
EXPECT_CALL(start_workers_, ready()).Times(0);
sigterm_->callback_();
EXPECT_CALL(server_, isShutdown()).WillOnce(Return(shutdown_));
cm_init_callback_();
}
#endif
// no signals on Windows
#ifndef WIN32
TEST_F(RunHelperTest, ShutdownBeforeInitManagerInit) {
EXPECT_CALL(start_workers_, ready()).Times(0);
Init::ExpectableTargetImpl target;
init_manager_.add(target);
EXPECT_CALL(target, initialize());
cm_init_callback_();
sigterm_->callback_();
EXPECT_CALL(server_, isShutdown()).WillOnce(Return(shutdown_));
target.ready();
}
#endif
class InitializingInitManager : public Init::ManagerImpl {
public:
InitializingInitManager(absl::string_view name) : Init::ManagerImpl(name) {}
State state() const override { return State::Initializing; }
};
// Class creates minimally viable server instance for testing.
class ServerInstanceImplTestBase {
protected:
void initialize(const std::string& bootstrap_path) { initialize(bootstrap_path, false); }
void initialize(const std::string& bootstrap_path, const bool use_intializing_instance) {
initialize(bootstrap_path, use_intializing_instance, hooks_);
}
void initialize(const std::string& bootstrap_path, const bool use_intializing_instance,
ListenerHooks& hooks) {
if (options_.config_path_.empty()) {
options_.config_path_ = TestEnvironment::temporaryFileSubstitute(
bootstrap_path, {{"upstream_0", 0}, {"upstream_1", 0}}, version_);
}
thread_local_ = std::make_unique<ThreadLocal::InstanceImpl>();
if (process_object_ != nullptr) {
process_context_ = std::make_unique<ProcessContextImpl>(*process_object_);
}
init_manager_ = use_intializing_instance ? std::make_unique<InitializingInitManager>("Server")
: std::make_unique<Init::ManagerImpl>("Server");
server_ = std::make_unique<InstanceImpl>(
*init_manager_, options_, time_system_, hooks, restart_, stats_store_, fakelock_,
std::make_unique<NiceMock<Random::MockRandomGenerator>>(), *thread_local_,
Thread::threadFactoryForTest(), Filesystem::fileSystemForTest(),
std::move(process_context_));
server_->initialize(std::make_shared<Network::Address::Ipv4Instance>("127.0.0.1"),
component_factory_);
EXPECT_TRUE(server_->api().fileSystem().fileExists(std::string(Platform::null_device_path)));
}
void initializeWithHealthCheckParams(const std::string& bootstrap_path, const double timeout,
const double interval) {
options_.config_path_ = TestEnvironment::temporaryFileSubstitute(
bootstrap_path,
{{"health_check_timeout", fmt::format("{}", timeout).c_str()},
{"health_check_interval", fmt::format("{}", interval).c_str()}},
TestEnvironment::PortMap{}, version_);
thread_local_ = std::make_unique<ThreadLocal::InstanceImpl>();
init_manager_ = std::make_unique<Init::ManagerImpl>("Server");
server_ = std::make_unique<InstanceImpl>(
*init_manager_, options_, time_system_, hooks_, restart_, stats_store_, fakelock_,
std::make_unique<NiceMock<Random::MockRandomGenerator>>(), *thread_local_,
Thread::threadFactoryForTest(), Filesystem::fileSystemForTest(), nullptr);
server_->initialize(std::make_shared<Network::Address::Ipv4Instance>("127.0.0.1"),
component_factory_);
EXPECT_TRUE(server_->api().fileSystem().fileExists(std::string(Platform::null_device_path)));
}
Thread::ThreadPtr startTestServer(const std::string& bootstrap_path,
const bool use_intializing_instance) {
absl::Notification started;
absl::Notification post_init;
auto server_thread = Thread::threadFactoryForTest().createThread([&] {
initialize(bootstrap_path, use_intializing_instance);
auto startup_handle = server_->registerCallback(ServerLifecycleNotifier::Stage::Startup,
[&] { started.Notify(); });
auto post_init_handle = server_->registerCallback(ServerLifecycleNotifier::Stage::PostInit,
[&] { post_init.Notify(); });
auto shutdown_handle = server_->registerCallback(ServerLifecycleNotifier::Stage::ShutdownExit,
[&](Event::PostCb) { FAIL(); });
shutdown_handle = nullptr; // unregister callback
server_->run();
startup_handle = nullptr;
post_init_handle = nullptr;
server_ = nullptr;
thread_local_ = nullptr;
});
started.WaitForNotification();
post_init.WaitForNotification();
return server_thread;
}
void expectCorrectBuildVersion(const envoy::config::core::v3::BuildVersion& build_version) {
std::string version_string =
absl::StrCat(build_version.version().major_number(), ".",
build_version.version().minor_number(), ".", build_version.version().patch());
const auto& fields = build_version.metadata().fields();
if (fields.find(BuildVersionMetadataKeys::get().BuildLabel) != fields.end()) {
absl::StrAppend(&version_string, "-",
fields.at(BuildVersionMetadataKeys::get().BuildLabel).string_value());
}
EXPECT_EQ(BUILD_VERSION_NUMBER, version_string);
}
Network::Address::IpVersion version_;
testing::NiceMock<MockOptions> options_;
DefaultListenerHooks hooks_;
testing::NiceMock<MockHotRestart> restart_;
ThreadLocal::InstanceImplPtr thread_local_;
Stats::TestIsolatedStoreImpl stats_store_;
Thread::MutexBasicLockable fakelock_;
TestComponentFactory component_factory_;
Event::GlobalTimeSystem time_system_;
ProcessObject* process_object_ = nullptr;
std::unique_ptr<ProcessContextImpl> process_context_;
std::unique_ptr<Init::Manager> init_manager_;
std::unique_ptr<InstanceImpl> server_;
};
class ServerInstanceImplTest : public ServerInstanceImplTestBase,
public testing::TestWithParam<Network::Address::IpVersion> {
protected:
ServerInstanceImplTest() { version_ = GetParam(); }
};
// Custom StatsSink that just increments a counter when flush is called.
class CustomStatsSink : public Stats::Sink {
public:
CustomStatsSink(Stats::Scope& scope) : stats_flushed_(scope.counterFromString("stats.flushed")) {}
// Stats::Sink
void flush(Stats::MetricSnapshot&) override { stats_flushed_.inc(); }
void onHistogramComplete(const Stats::Histogram&, uint64_t) override {}
private:
Stats::Counter& stats_flushed_;
};
// Custom StatsSinkFactory that creates CustomStatsSink.
class CustomStatsSinkFactory : public Server::Configuration::StatsSinkFactory {
public:
// StatsSinkFactory
Stats::SinkPtr createStatsSink(const Protobuf::Message&,
Server::Configuration::ServerFactoryContext& server) override {
return std::make_unique<CustomStatsSink>(server.scope());
}
ProtobufTypes::MessagePtr createEmptyConfigProto() override {
// Using Struct instead of a custom per-filter empty config proto
// This is only allowed in tests.
return ProtobufTypes::MessagePtr{new Envoy::ProtobufWkt::Struct()};
}
std::string name() const override { return "envoy.custom_stats_sink"; }
};
// CustomListenerHooks is used for synchronization between test thread and server thread.
class CustomListenerHooks : public DefaultListenerHooks {
public:
CustomListenerHooks(std::function<void()> workers_started_cb)
: on_workers_started_cb_(workers_started_cb) {}
void onWorkersStarted() override { on_workers_started_cb_(); }
private:
std::function<void()> on_workers_started_cb_;
};
INSTANTIATE_TEST_SUITE_P(IpVersions, ServerInstanceImplTest,
testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
TestUtility::ipTestParamsToString);
// The finalize() of Http::CustomInlineHeaderRegistry will be called When InstanceImpl is
// instantiated. For this reason, the test case for inline headers must precede all other test
// cases.
// Test the case where inline headers contain names that cannot be registered as inline headers.
TEST_P(ServerInstanceImplTest, WithErrorCustomInlineHeaders) {
EXPECT_THROW_WITH_MESSAGE(
initialize("test/server/test_data/server/bootstrap_inline_headers_error.yaml"),
EnvoyException, "Header set-cookie cannot be registered as an inline header.");
}
TEST_P(ServerInstanceImplTest, WithDeathCustomInlineHeaders) {
#if !defined(NDEBUG)
// The finalize() of Http::CustomInlineHeaderRegistry will be called after the first successful
// instantiation of InstanceImpl. If InstanceImpl is instantiated again and the inline header is
// registered again, the assertion will be triggered.
EXPECT_DEATH(
{
initialize("test/server/test_data/server/bootstrap_inline_headers.yaml");
initialize("test/server/test_data/server/bootstrap_inline_headers.yaml");
},
"");
#endif // !defined(NDEBUG)
}
// Test whether the custom inline headers can be registered correctly.
TEST_P(ServerInstanceImplTest, WithCustomInlineHeaders) {
static bool is_registered = false;
if (!is_registered) {
// Avoid repeated registration of custom inline headers in the current process after the
// finalize() of Http::CustomInlineHeaderRegistry has already been called.
EXPECT_NO_THROW(initialize("test/server/test_data/server/bootstrap_inline_headers.yaml"));
is_registered = true;
}
EXPECT_TRUE(
Http::CustomInlineHeaderRegistry::getInlineHeader<Http::RequestHeaderMap::header_map_type>(
Http::LowerCaseString("test1"))
.has_value());
EXPECT_TRUE(
Http::CustomInlineHeaderRegistry::getInlineHeader<Http::RequestTrailerMap::header_map_type>(
Http::LowerCaseString("test2"))
.has_value());
EXPECT_TRUE(
Http::CustomInlineHeaderRegistry::getInlineHeader<Http::ResponseHeaderMap::header_map_type>(
Http::LowerCaseString("test3"))
.has_value());
EXPECT_TRUE(
Http::CustomInlineHeaderRegistry::getInlineHeader<Http::ResponseTrailerMap::header_map_type>(
Http::LowerCaseString("test4"))
.has_value());
{
Http::TestRequestHeaderMapImpl headers{
{"test1", "test1_value1"},
{"test1", "test1_value2"},
{"test3", "test3_value1"},
{"test3", "test3_value2"},
};
// 'test1' is registered as the inline request header.
auto test1_headers = headers.get(Http::LowerCaseString("test1"));
EXPECT_EQ(1, test1_headers.size());
EXPECT_EQ("test1_value1,test1_value2", headers.get_("test1"));
// 'test3' is not registered as an inline request header.
auto test3_headers = headers.get(Http::LowerCaseString("test3"));
EXPECT_EQ(2, test3_headers.size());
EXPECT_EQ("test3_value1", headers.get_("test3"));
}
{
Http::TestResponseHeaderMapImpl headers{
{"test1", "test1_value1"},
{"test1", "test1_value2"},
{"test3", "test3_value1"},
{"test3", "test3_value2"},
};
// 'test1' is not registered as the inline response header.
auto test1_headers = headers.get(Http::LowerCaseString("test1"));
EXPECT_EQ(2, test1_headers.size());
EXPECT_EQ("test1_value1", headers.get_("test1"));
// 'test3' is registered as an inline response header.
auto test3_headers = headers.get(Http::LowerCaseString("test3"));
EXPECT_EQ(1, test3_headers.size());
EXPECT_EQ("test3_value1,test3_value2", headers.get_("test3"));
}
}
// Validates that server stats are flushed even when server is stuck with initialization.
TEST_P(ServerInstanceImplTest, StatsFlushWhenServerIsStillInitializing) {
CustomStatsSinkFactory factory;
Registry::InjectFactory<Server::Configuration::StatsSinkFactory> registered(factory);
auto server_thread =
startTestServer("test/server/test_data/server/stats_sink_bootstrap.yaml", true);
// Wait till stats are flushed to custom sink and validate that the actual flush happens.
TestUtility::waitForCounterEq(stats_store_, "stats.flushed", 1, time_system_);
EXPECT_EQ(3L, TestUtility::findGauge(stats_store_, "server.state")->value());
EXPECT_EQ(Init::Manager::State::Initializing, server_->initManager().state());
EXPECT_TRUE(server_->enableReusePortDefault());
server_->dispatcher().post([&] { server_->shutdown(); });
server_thread->join();
}
// Validates that the "server.version" is updated with stats_server_version_override from bootstrap.
TEST_P(ServerInstanceImplTest, ProxyVersionOveridesFromBootstrap) {
auto server_thread =
startTestServer("test/server/test_data/server/proxy_version_bootstrap.yaml", true);
EXPECT_EQ(100012001, TestUtility::findGauge(stats_store_, "server.version")->value());
server_->dispatcher().post([&] { server_->shutdown(); });
server_thread->join();
}
// Validates that the "server.fips_mode" stat indicates the FIPS compliance from the Envoy Build
TEST_P(ServerInstanceImplTest, ValidateFIPSModeStat) {
auto server_thread =
startTestServer("test/server/test_data/server/proxy_version_bootstrap.yaml", true);
if (VersionInfo::sslFipsCompliant()) {
EXPECT_EQ(
1L, TestUtility::findGauge(stats_store_, "server.compilation_settings.fips_mode")->value());
} else {
EXPECT_EQ(
0L, TestUtility::findGauge(stats_store_, "server.compilation_settings.fips_mode")->value());
}
server_->dispatcher().post([&] { server_->shutdown(); });
server_thread->join();
}
// Validate the the Envoy FIPS compilation flags are consistent with the FIPS
// mode of the underlying BoringSSL build.
TEST_P(ServerInstanceImplTest, ValidateFIPSModeConsistency) {
bool isFIPS = (FIPS_mode() != 0);
EXPECT_EQ(isFIPS, VersionInfo::sslFipsCompliant());
}
TEST_P(ServerInstanceImplTest, EmptyShutdownLifecycleNotifications) {
auto server_thread = startTestServer("test/server/test_data/server/node_bootstrap.yaml", false);
server_->dispatcher().post([&] { server_->shutdown(); });
server_thread->join();
// Validate that initialization_time histogram value has been set.
EXPECT_TRUE(stats_store_
.histogramFromString("server.initialization_time_ms",
Stats::Histogram::Unit::Milliseconds)
.used());
EXPECT_EQ(0L, TestUtility::findGauge(stats_store_, "server.state")->value());
}
// Catch exceptions in secondary cluster initialization callbacks. These are not caught in the main
// initialization try/catch.
TEST_P(ServerInstanceImplTest, SecondaryClusterExceptions) {
// Error in reading illegal file path for channel credentials in secondary cluster.
EXPECT_LOG_CONTAINS("warn",
"Skipping initialization of secondary cluster: API configs must have either "
"a gRPC service or a cluster name defined",
{
initialize("test/server/test_data/server/health_check_nullptr.yaml");
server_->dispatcher().run(Event::Dispatcher::RunType::NonBlock);
});
}
// Catch exceptions in HDS cluster initialization callbacks.
TEST_P(ServerInstanceImplTest, HdsClusterException) {
// Error in reading illegal file path for channel credentials in secondary cluster.
EXPECT_LOG_CONTAINS("warn",
"Skipping initialization of HDS cluster: API configs must have either a gRPC "
"service or a cluster name defined",
{
initialize("test/server/test_data/server/hds_exception.yaml");
server_->dispatcher().run(Event::Dispatcher::RunType::NonBlock);
});
}
TEST_P(ServerInstanceImplTest, LifecycleNotifications) {
bool startup = false, post_init = false, shutdown = false, shutdown_with_completion = false;
absl::Notification started, post_init_fired, shutdown_begin, completion_block, completion_done;
// Run the server in a separate thread so we can test different lifecycle stages.
auto server_thread = Thread::threadFactoryForTest().createThread([&] {
initialize("test/server/test_data/server/node_bootstrap.yaml");
auto handle1 = server_->registerCallback(ServerLifecycleNotifier::Stage::Startup, [&] {
startup = true;
started.Notify();
});
auto handle2 = server_->registerCallback(ServerLifecycleNotifier::Stage::PostInit, [&] {
post_init = true;
post_init_fired.Notify();
});
auto handle3 = server_->registerCallback(ServerLifecycleNotifier::Stage::ShutdownExit, [&] {
shutdown = true;
shutdown_begin.Notify();
});
auto handle4 = server_->registerCallback(ServerLifecycleNotifier::Stage::ShutdownExit,
[&](Event::PostCb completion_cb) {
// Block till we're told to complete
completion_block.WaitForNotification();
shutdown_with_completion = true;
server_->dispatcher().post(std::move(completion_cb));
completion_done.Notify();
});
auto handle5 =
server_->registerCallback(ServerLifecycleNotifier::Stage::Startup, [&] { FAIL(); });
handle5 = server_->registerCallback(ServerLifecycleNotifier::Stage::ShutdownExit,
[&](Event::PostCb) { FAIL(); });
handle5 = nullptr;
server_->run();
handle1 = nullptr;
handle2 = nullptr;
handle3 = nullptr;
handle4 = nullptr;
server_ = nullptr;
thread_local_ = nullptr;
});
started.WaitForNotification();
EXPECT_TRUE(startup);
EXPECT_FALSE(shutdown);
EXPECT_TRUE(TestUtility::findGauge(stats_store_, "server.state")->used());
EXPECT_EQ(0L, TestUtility::findGauge(stats_store_, "server.state")->value());
post_init_fired.WaitForNotification();
EXPECT_TRUE(post_init);
EXPECT_FALSE(shutdown);
server_->dispatcher().post([&] { server_->shutdown(); });
shutdown_begin.WaitForNotification();
EXPECT_TRUE(shutdown);
// Expect the server to block waiting for the completion callback to be invoked
EXPECT_FALSE(completion_done.WaitForNotificationWithTimeout(absl::Seconds(1)));
completion_block.Notify();
completion_done.WaitForNotification();
EXPECT_TRUE(shutdown_with_completion);
server_thread->join();
}
class ServerInstanceImplWorkersTest : public ServerInstanceImplTest {
protected:
ServerInstanceImplWorkersTest() {
bool workers_started = false;
// Expect drainParentListeners not to be called before workers start.
EXPECT_CALL(restart_, drainParentListeners).Times(0);
// Run the server in a separate thread so we can test different lifecycle stages.
server_thread_ = Thread::threadFactoryForTest().createThread([&] {
auto hooks = CustomListenerHooks([&]() {
workers_started = true;
workers_started_fired_.Notify();
workers_started_block_.WaitForNotification();
});
initialize("test/server/test_data/server/node_bootstrap.yaml", false, hooks);
server_->run();
server_ = nullptr;
thread_local_ = nullptr;
});
workers_started_fired_.WaitForNotification();
EXPECT_TRUE(workers_started);
EXPECT_CALL(restart_, drainParentListeners);
}
~ServerInstanceImplWorkersTest() override {
server_->dispatcher().post([&] { server_->shutdown(); });
server_thread_->join();
}
absl::Notification workers_started_fired_;
absl::Notification workers_started_block_;
Thread::ThreadPtr server_thread_;
};
INSTANTIATE_TEST_SUITE_P(IpVersions, ServerInstanceImplWorkersTest,
testing::ValuesIn(TestEnvironment::getIpVersionsForTest()),
TestUtility::ipTestParamsToString);
TEST_P(ServerInstanceImplWorkersTest, DrainParentListenerAfterWorkersStarted) {
EXPECT_TRUE(TestUtility::findGauge(stats_store_, "server.state")->used());
EXPECT_EQ(0L, TestUtility::findGauge(stats_store_, "server.state")->value());
workers_started_block_.Notify();
}
TEST_P(ServerInstanceImplWorkersTest, DrainCloseAfterWorkersStarted) {
absl::Notification drain_closes_started, drain_complete;
workers_started_block_.Notify();
DrainManager& drain_manager = server_->drainManager();
// To reproduce the race condition from
// https://github.com/envoyproxy/envoy/issues/31457 we make sure that the
// infinite drainClose spin-loop (mimicing high traffic) is running before we
// initiate the drain sequence.
auto drain_thread = Thread::threadFactoryForTest().createThread([&] {
bool closed = drain_manager.drainClose();
drain_closes_started.Notify();
while (!closed) {
closed = drain_manager.drainClose();
}
});
drain_closes_started.WaitForNotification();
// Now that we are starting to try to call drainClose, we'll start the drain sequence, then
// wait for that to complete.
server_->dispatcher().post(
[&] { drain_manager.startDrainSequence([&drain_complete]() { drain_complete.Notify(); }); });
drain_complete.WaitForNotification();
drain_thread->join();
}
// A test target which never signals that it is ready.
class NeverReadyTarget : public Init::TargetImpl {
public:
NeverReadyTarget(absl::Notification& initialized)
: Init::TargetImpl("test", [this] { initialize(); }), initialized_(initialized) {}
private:
void initialize() { initialized_.Notify(); }
absl::Notification& initialized_;
};
TEST_P(ServerInstanceImplTest, NoLifecycleNotificationOnEarlyShutdown) {
absl::Notification initialized;
auto server_thread = Thread::threadFactoryForTest().createThread([&] {
initialize("test/server/test_data/server/node_bootstrap.yaml");
// This shutdown notification should never be called because we will shutdown
// early before the init manager finishes initializing and therefore before
// the server starts worker threads.
auto shutdown_handle = server_->registerCallback(ServerLifecycleNotifier::Stage::ShutdownExit,
[&](Event::PostCb) { FAIL(); });
NeverReadyTarget target(initialized);
server_->initManager().add(target);
server_->run();
shutdown_handle = nullptr;
server_ = nullptr;
thread_local_ = nullptr;
});
// Wait until the init manager starts initializing targets...
initialized.WaitForNotification();
// Now shutdown the main dispatcher and trigger server lifecycle notifications.
server_->dispatcher().post([&] { server_->shutdown(); });
server_thread->join();
}
TEST_P(ServerInstanceImplTest, ShutdownBeforeWorkersStarted) {
// Test that drainParentListeners() should never be called because we will shutdown
// early before the server starts worker threads.
EXPECT_CALL(restart_, drainParentListeners).Times(0);
auto server_thread = Thread::threadFactoryForTest().createThread([&] {
initialize("test/server/test_data/server/node_bootstrap.yaml");
auto post_init_handle = server_->registerCallback(ServerLifecycleNotifier::Stage::PostInit,
[&] { server_->shutdown(); });
// This shutdown notification should never be called because we will shutdown early.
auto shutdown_handle = server_->registerCallback(ServerLifecycleNotifier::Stage::ShutdownExit,
[&](Event::PostCb) { FAIL(); });
server_->run();
post_init_handle = nullptr;
shutdown_handle = nullptr;
server_ = nullptr;
thread_local_ = nullptr;
});
server_thread->join();
}
TEST_P(ServerInstanceImplTest, Stats) {
options_.service_cluster_name_ = "some_cluster_name";
options_.service_node_name_ = "some_node_name";
options_.concurrency_ = 2;
options_.hot_restart_epoch_ = 3;
EXPECT_NO_THROW(initialize("test/server/test_data/server/empty_bootstrap.yaml"));
EXPECT_NE(nullptr, TestUtility::findCounter(stats_store_, "main_thread.watchdog_miss"));
EXPECT_NE(nullptr, TestUtility::findCounter(stats_store_, "workers.watchdog_miss"));
EXPECT_EQ(2L, TestUtility::findGauge(stats_store_, "server.concurrency")->value());
EXPECT_EQ(3L, TestUtility::findGauge(stats_store_, "server.hot_restart_epoch")->value());
// The ENVOY_BUG stat works in release mode.
#if defined(NDEBUG)
// Test exponential back-off on a fixed line ENVOY_BUG.
for (int i = 0; i < 16; i++) {
ENVOY_BUG(false, "");
}
EXPECT_EQ(5L, TestUtility::findCounter(stats_store_, "server.envoy_bug_failures")->value());
// Another ENVOY_BUG increments the counter.
ENVOY_BUG(false, "Testing envoy bug assertion failure detection in release build.");
EXPECT_EQ(6L, TestUtility::findCounter(stats_store_, "server.envoy_bug_failures")->value());
#else
// The ENVOY_BUG macro aborts in debug mode.
EXPECT_DEATH(ENVOY_BUG(false, ""), "");
#endif
// The ASSERT stat only works in this configuration.
#if defined(NDEBUG) && defined(ENVOY_LOG_DEBUG_ASSERT_IN_RELEASE)
ASSERT(false, "Testing debug assertion failure detection in release build.");
EXPECT_EQ(1L, TestUtility::findCounter(stats_store_, "server.debug_assertion_failures")->value());
#else
EXPECT_EQ(0L, TestUtility::findCounter(stats_store_, "server.debug_assertion_failures")->value());
#endif
}
class ServerStatsTest
: public Event::TestUsingSimulatedTime,
public ServerInstanceImplTestBase,
public testing::TestWithParam<std::tuple<Network::Address::IpVersion, bool>> {
protected:
ServerStatsTest() {
version_ = std::get<0>(GetParam());
manual_flush_ = std::get<1>(GetParam());
}
void flushStats() {
if (manual_flush_) {
server_->flushStats();
server_->dispatcher().run(Event::Dispatcher::RunType::Block);
} else {
// Default flush interval is 5 seconds.
simTime().advanceTimeAndRun(std::chrono::seconds(6), server_->dispatcher(),
Event::Dispatcher::RunType::Block);
}
}
bool manual_flush_;
};
std::string ipFlushingModeTestParamsToString(
const ::testing::TestParamInfo<std::tuple<Network::Address::IpVersion, bool>>& params) {
return fmt::format(
"{}_{}",
TestUtility::ipTestParamsToString(
::testing::TestParamInfo<Network::Address::IpVersion>(std::get<0>(params.param), 0)),
std::get<1>(params.param) ? "with_manual_flush" : "with_time_based_flush");
}
INSTANTIATE_TEST_SUITE_P(
IpVersionsFlushingMode, ServerStatsTest,
testing::Combine(testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), testing::Bool()),
ipFlushingModeTestParamsToString);
TEST_P(ServerStatsTest, FlushStats) {
initialize("test/server/test_data/server/empty_bootstrap.yaml");
Stats::Gauge& recent_lookups = stats_store_.gaugeFromString(
"server.stats_recent_lookups", Stats::Gauge::ImportMode::NeverImport);
EXPECT_EQ(0, recent_lookups.value());
flushStats();
uint64_t strobed_recent_lookups = recent_lookups.value();
EXPECT_LT(100, strobed_recent_lookups); // Recently this was 319 but exact value not important.
Stats::StatNameSetPtr test_set = stats_store_.symbolTable().makeSet("test");
// When we remember a StatNameSet builtin, we charge only for the SymbolTable
// lookup, which requires a lock.
test_set->rememberBuiltin("a.b");
flushStats();
EXPECT_EQ(1, recent_lookups.value() - strobed_recent_lookups);
strobed_recent_lookups = recent_lookups.value();
// When we create a dynamic stat, there are no locks taken.
Stats::StatNameDynamicStorage dynamic_stat("c.d", stats_store_.symbolTable());
flushStats();
EXPECT_EQ(recent_lookups.value(), strobed_recent_lookups);
}
TEST_P(ServerInstanceImplTest, FlushStatsOnAdmin) {
CustomStatsSinkFactory factory;
Registry::InjectFactory<Server::Configuration::StatsSinkFactory> registered(factory);
auto server_thread =
startTestServer("test/server/test_data/server/stats_sink_manual_flush_bootstrap.yaml", true);
EXPECT_TRUE(server_->statsConfig().flushOnAdmin());
EXPECT_EQ(std::chrono::seconds(5), server_->statsConfig().flushInterval());
auto counter = TestUtility::findCounter(stats_store_, "stats.flushed");
time_system_.advanceTimeWait(std::chrono::seconds(6));
EXPECT_EQ(0L, counter->value());
// Flush via admin.
Http::TestResponseHeaderMapImpl response_headers;
std::string body;
EXPECT_EQ(Http::Code::OK, server_->admin()->request("/stats", "GET", response_headers, body));
EXPECT_EQ(1L, counter->value());
time_system_.advanceTimeWait(std::chrono::seconds(6));
EXPECT_EQ(1L, counter->value());
server_->dispatcher().post([&] { server_->shutdown(); });
server_thread->join();
}
TEST_P(ServerInstanceImplTest, ConcurrentFlushes) {
CustomStatsSinkFactory factory;
Registry::InjectFactory<Server::Configuration::StatsSinkFactory> registered(factory);
bool workers_started = false;
absl::Notification workers_started_fired;
// Run the server in a separate thread so we can test different lifecycle stages.
auto server_thread = Thread::threadFactoryForTest().createThread([&] {
auto hooks = CustomListenerHooks([&]() {
workers_started = true;
workers_started_fired.Notify();
});
initialize("test/server/test_data/server/stats_sink_manual_flush_bootstrap.yaml", false, hooks);
server_->run();
server_ = nullptr;
thread_local_ = nullptr;
});
workers_started_fired.WaitForNotification();
EXPECT_TRUE(workers_started);
// Flush three times in a row. Two of these should get dropped.
server_->dispatcher().post([&] {
server_->flushStats();
server_->flushStats();
server_->flushStats();
});
EXPECT_TRUE(
TestUtility::waitForCounterEq(stats_store_, "server.dropped_stat_flushes", 2, time_system_));
server_->dispatcher().post([&] { stats_store_.runMergeCallback(); });
EXPECT_TRUE(TestUtility::waitForCounterEq(stats_store_, "stats.flushed", 1, time_system_));
// Trigger another flush after the first one finished. This should go through an no drops should
// be recorded.
server_->dispatcher().post([&] { server_->flushStats(); });
server_->dispatcher().post([&] { stats_store_.runMergeCallback(); });
EXPECT_TRUE(TestUtility::waitForCounterEq(stats_store_, "stats.flushed", 2, time_system_));
EXPECT_TRUE(
TestUtility::waitForCounterEq(stats_store_, "server.dropped_stat_flushes", 2, time_system_));
server_->dispatcher().post([&] { server_->shutdown(); });
server_thread->join();
}
// Default validation mode
TEST_P(ServerInstanceImplTest, ValidationDefault) {
options_.service_cluster_name_ = "some_cluster_name";
options_.service_node_name_ = "some_node_name";
EXPECT_NO_THROW(initialize("test/server/test_data/server/empty_bootstrap.yaml"));
EXPECT_THAT_THROWS_MESSAGE(
server_->messageValidationContext().staticValidationVisitor().onUnknownField("foo"),
EnvoyException, "Protobuf message (foo) has unknown fields");
EXPECT_EQ(0, TestUtility::findCounter(stats_store_, "server.static_unknown_fields")->value());
EXPECT_NO_THROW(
server_->messageValidationContext().dynamicValidationVisitor().onUnknownField("bar"));
EXPECT_EQ(1, TestUtility::findCounter(stats_store_, "server.dynamic_unknown_fields")->value());
}
// Validation mode with --allow-unknown-static-fields
TEST_P(ServerInstanceImplTest, ValidationAllowStatic) {
options_.service_cluster_name_ = "some_cluster_name";
options_.service_node_name_ = "some_node_name";
options_.allow_unknown_static_fields_ = true;
EXPECT_NO_THROW(initialize("test/server/test_data/server/empty_bootstrap.yaml"));
EXPECT_NO_THROW(
server_->messageValidationContext().staticValidationVisitor().onUnknownField("foo"));
EXPECT_EQ(1, TestUtility::findCounter(stats_store_, "server.static_unknown_fields")->value());
EXPECT_NO_THROW(
server_->messageValidationContext().dynamicValidationVisitor().onUnknownField("bar"));
EXPECT_EQ(1, TestUtility::findCounter(stats_store_, "server.dynamic_unknown_fields")->value());
}
// Validation mode with --reject-unknown-dynamic-fields
TEST_P(ServerInstanceImplTest, ValidationRejectDynamic) {
options_.service_cluster_name_ = "some_cluster_name";
options_.service_node_name_ = "some_node_name";
options_.reject_unknown_dynamic_fields_ = true;
options_.ignore_unknown_dynamic_fields_ = true; // reject takes precedence over ignore
EXPECT_NO_THROW(initialize("test/server/test_data/server/empty_bootstrap.yaml"));
EXPECT_THAT_THROWS_MESSAGE(
server_->messageValidationContext().staticValidationVisitor().onUnknownField("foo"),
EnvoyException, "Protobuf message (foo) has unknown fields");
EXPECT_EQ(0, TestUtility::findCounter(stats_store_, "server.static_unknown_fields")->value());
EXPECT_THAT_THROWS_MESSAGE(
server_->messageValidationContext().dynamicValidationVisitor().onUnknownField("bar"),
EnvoyException, "Protobuf message (bar) has unknown fields");
EXPECT_EQ(0, TestUtility::findCounter(stats_store_, "server.dynamic_unknown_fields")->value());
}