-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmod.rs
More file actions
1976 lines (1702 loc) · 67.3 KB
/
Copy pathmod.rs
File metadata and controls
1976 lines (1702 loc) · 67.3 KB
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
pub mod tcp;
pub mod udp;
#[cfg(unix)]
mod unix;
use vector_lib::codecs::decoding::DeserializerConfig;
use vector_lib::config::{log_schema, LegacyKey, LogNamespace};
use vector_lib::configurable::configurable_component;
use vector_lib::lookup::{lookup_v2::OptionalValuePath, owned_value_path};
use vrl::value::{kind::Collection, Kind};
use crate::{
codecs::DecodingConfig,
config::{GenerateConfig, Resource, SourceConfig, SourceContext, SourceOutput},
sources::util::net::TcpSource,
tls::MaybeTlsSettings,
};
/// Configuration for the `socket` source.
#[configurable_component(source("socket", "Collect logs over a socket."))]
#[derive(Clone, Debug)]
pub struct SocketConfig {
#[serde(flatten)]
pub mode: Mode,
}
/// Listening mode for the `socket` source.
#[configurable_component]
#[derive(Clone, Debug)]
#[serde(tag = "mode", rename_all = "snake_case")]
#[configurable(metadata(docs::enum_tag_description = "The type of socket to use."))]
#[allow(clippy::large_enum_variant)] // just used for configuration
pub enum Mode {
/// Listen on TCP.
Tcp(tcp::TcpConfig),
/// Listen on UDP.
Udp(udp::UdpConfig),
/// Listen on a Unix domain socket (UDS), in datagram mode.
#[cfg(unix)]
UnixDatagram(unix::UnixConfig),
/// Listen on a Unix domain socket (UDS), in stream mode.
#[cfg(unix)]
#[serde(alias = "unix")]
UnixStream(unix::UnixConfig),
}
impl SocketConfig {
pub fn new_tcp(tcp_config: tcp::TcpConfig) -> Self {
tcp_config.into()
}
pub fn make_basic_tcp_config(addr: std::net::SocketAddr) -> Self {
tcp::TcpConfig::from_address(addr.into()).into()
}
fn decoding(&self) -> DeserializerConfig {
match &self.mode {
Mode::Tcp(config) => config.decoding().clone(),
Mode::Udp(config) => config.decoding().clone(),
#[cfg(unix)]
Mode::UnixDatagram(config) => config.decoding().clone(),
#[cfg(unix)]
Mode::UnixStream(config) => config.decoding().clone(),
}
}
fn log_namespace(&self, global_log_namespace: LogNamespace) -> LogNamespace {
match &self.mode {
Mode::Tcp(config) => global_log_namespace.merge(config.log_namespace),
Mode::Udp(config) => global_log_namespace.merge(config.log_namespace),
#[cfg(unix)]
Mode::UnixDatagram(config) => global_log_namespace.merge(config.log_namespace),
#[cfg(unix)]
Mode::UnixStream(config) => global_log_namespace.merge(config.log_namespace),
}
}
}
impl From<tcp::TcpConfig> for SocketConfig {
fn from(config: tcp::TcpConfig) -> Self {
SocketConfig {
mode: Mode::Tcp(config),
}
}
}
impl From<udp::UdpConfig> for SocketConfig {
fn from(config: udp::UdpConfig) -> Self {
SocketConfig {
mode: Mode::Udp(config),
}
}
}
impl GenerateConfig for SocketConfig {
fn generate_config() -> toml::Value {
toml::from_str(
r#"mode = "tcp"
address = "0.0.0.0:9000""#,
)
.unwrap()
}
}
#[async_trait::async_trait]
#[typetag::serde(name = "socket")]
impl SourceConfig for SocketConfig {
async fn build(&self, cx: SourceContext) -> crate::Result<super::Source> {
match self.mode.clone() {
Mode::Tcp(config) => {
let log_namespace = cx.log_namespace(config.log_namespace);
let decoding = config.decoding().clone();
let decoder = DecodingConfig::new(
config
.framing
.clone()
.unwrap_or_else(|| decoding.default_stream_framing()),
decoding,
log_namespace,
)
.build()?;
let tcp = tcp::RawTcpSource::new(config.clone(), decoder, log_namespace);
let tls_config = config.tls().as_ref().map(|tls| tls.tls_config.clone());
let tls_client_metadata_key = config
.tls()
.as_ref()
.and_then(|tls| tls.client_metadata_key.clone())
.and_then(|k| k.path);
let tls = MaybeTlsSettings::from_config(tls_config.as_ref(), true)?;
let allowlist = cx.effective_permit_origin(config.permit_origin.clone()).map(Into::into);
tcp.run(
config.address(),
config.keepalive(),
config.shutdown_timeout_secs(),
tls,
tls_client_metadata_key,
config.receive_buffer_bytes(),
config.max_connection_duration_secs(),
cx,
false.into(),
config.connection_limit,
allowlist,
SocketConfig::NAME,
log_namespace,
)
}
Mode::Udp(mut config) => {
let log_namespace = cx.log_namespace(config.log_namespace);
let decoding = config.decoding().clone();
let framing = config
.framing()
.clone()
.unwrap_or_else(|| decoding.default_message_based_framing());
let decoder = DecodingConfig::new(framing, decoding, log_namespace).build()?;
config.permit_origin = cx.effective_permit_origin(config.permit_origin);
Ok(udp::udp(
config,
decoder,
cx.shutdown,
cx.out,
log_namespace,
))
}
#[cfg(unix)]
Mode::UnixDatagram(config) => {
let log_namespace = cx.log_namespace(config.log_namespace);
let decoding = config.decoding.clone();
let framing = config
.framing
.clone()
.unwrap_or_else(|| decoding.default_message_based_framing());
let decoder = DecodingConfig::new(framing, decoding, log_namespace).build()?;
unix::unix_datagram(config, decoder, cx.shutdown, cx.out, log_namespace)
}
#[cfg(unix)]
Mode::UnixStream(config) => {
let log_namespace = cx.log_namespace(config.log_namespace);
let decoding = config.decoding().clone();
let decoder = DecodingConfig::new(
config
.framing
.clone()
.unwrap_or_else(|| decoding.default_stream_framing()),
decoding,
log_namespace,
)
.build()?;
unix::unix_stream(config, decoder, cx.shutdown, cx.out, log_namespace)
}
}
}
fn outputs(&self, global_log_namespace: LogNamespace) -> Vec<SourceOutput> {
let log_namespace = self.log_namespace(global_log_namespace);
let schema_definition = self
.decoding()
.schema_definition(log_namespace)
.with_standard_vector_source_metadata();
let schema_definition = match &self.mode {
Mode::Tcp(config) => {
let legacy_host_key = config.host_key().path.map(LegacyKey::InsertIfEmpty);
let legacy_port_key = config.port_key().clone().path.map(LegacyKey::InsertIfEmpty);
let tls_client_metadata_path = config
.tls()
.as_ref()
.and_then(|tls| tls.client_metadata_key.as_ref())
.and_then(|k| k.path.clone())
.map(LegacyKey::Overwrite);
schema_definition
.with_source_metadata(
Self::NAME,
legacy_host_key,
&owned_value_path!("host"),
Kind::bytes(),
Some("host"),
)
.with_source_metadata(
Self::NAME,
legacy_port_key,
&owned_value_path!("port"),
Kind::integer(),
None,
)
.with_source_metadata(
Self::NAME,
tls_client_metadata_path,
&owned_value_path!("tls_client_metadata"),
Kind::object(Collection::empty().with_unknown(Kind::bytes()))
.or_undefined(),
None,
)
}
Mode::Udp(config) => {
let legacy_host_key = config.host_key().path.map(LegacyKey::InsertIfEmpty);
let legacy_port_key = config.port_key().clone().path.map(LegacyKey::InsertIfEmpty);
schema_definition
.with_source_metadata(
Self::NAME,
legacy_host_key,
&owned_value_path!("host"),
Kind::bytes(),
None,
)
.with_source_metadata(
Self::NAME,
legacy_port_key,
&owned_value_path!("port"),
Kind::integer(),
None,
)
}
#[cfg(unix)]
Mode::UnixDatagram(config) => {
let legacy_host_key = config.host_key().clone().path.map(LegacyKey::InsertIfEmpty);
schema_definition.with_source_metadata(
Self::NAME,
legacy_host_key,
&owned_value_path!("host"),
Kind::bytes(),
None,
)
}
#[cfg(unix)]
Mode::UnixStream(config) => {
let legacy_host_key = config.host_key().clone().path.map(LegacyKey::InsertIfEmpty);
schema_definition.with_source_metadata(
Self::NAME,
legacy_host_key,
&owned_value_path!("host"),
Kind::bytes(),
None,
)
}
};
vec![SourceOutput::new_maybe_logs(
self.decoding().output_type(),
schema_definition,
)]
}
fn resources(&self) -> Vec<Resource> {
match self.mode.clone() {
Mode::Tcp(tcp) => vec![tcp.address().as_tcp_resource()],
Mode::Udp(udp) => vec![udp.address().as_udp_resource()],
#[cfg(unix)]
Mode::UnixDatagram(_) => vec![],
#[cfg(unix)]
Mode::UnixStream(_) => vec![],
}
}
fn can_acknowledge(&self) -> bool {
false
}
}
pub(crate) fn default_host_key() -> OptionalValuePath {
log_schema().host_key().cloned().into()
}
#[cfg(test)]
mod test {
use approx::assert_relative_eq;
use std::{
collections::HashMap,
net::{SocketAddr, UdpSocket},
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
thread,
};
use bytes::{BufMut, Bytes, BytesMut};
use futures::{stream, StreamExt};
use rand::{rngs::SmallRng, seq::SliceRandom, SeedableRng};
use serde_json::json;
use tokio::io::AsyncReadExt;
use tokio::net::TcpStream;
use tokio::{
task::JoinHandle,
time::{timeout, Duration, Instant},
};
#[cfg(unix)]
use vector_lib::codecs::{
decoding::CharacterDelimitedDecoderOptions, CharacterDelimitedDecoderConfig,
};
use vector_lib::codecs::{GelfDeserializerConfig, NewlineDelimitedDecoderConfig};
use vector_lib::event::EventContainer;
use vector_lib::lookup::{lookup_v2::OptionalValuePath, owned_value_path, path};
use vrl::value::ObjectMap;
use vrl::{btreemap, value};
#[cfg(unix)]
use {
super::{unix::UnixConfig, Mode},
crate::sources::util::unix::UNNAMED_SOCKET_HOST,
crate::test_util::wait_for,
futures::{SinkExt, Stream},
std::future::ready,
std::os::unix::fs::PermissionsExt,
std::path::PathBuf,
tokio::{
io::AsyncWriteExt,
net::{UnixDatagram, UnixStream},
task::yield_now,
},
tokio_util::codec::{FramedWrite, LinesCodec},
};
use super::{tcp::TcpConfig, udp::UdpConfig, SocketConfig};
use crate::{
config::{log_schema, ComponentKey, GlobalOptions, SourceConfig, SourceContext},
event::{Event, LogEvent},
shutdown::{ShutdownSignal, SourceShutdownCoordinator},
sinks::util::tcp::TcpSinkConfig,
sources::util::net::SocketListenAddr,
test_util::{
collect_n, collect_n_limited,
components::{assert_source_compliance, SOCKET_PUSH_SOURCE_TAGS},
next_addr, random_string, send_lines, send_lines_tls, wait_for_tcp,
},
tls::{self, TlsConfig, TlsEnableableConfig, TlsSourceConfig},
SourceSender,
};
fn get_gelf_payload(message: &str) -> String {
serde_json::to_string(&json!({
"version": "1.1",
"host": "example.org",
"short_message": message,
"timestamp": 1234567890.123,
"level": 6,
"_foo": "bar",
}))
.unwrap()
}
fn create_gelf_chunk(
message_id: u64,
sequence_number: u8,
total_chunks: u8,
payload: &[u8],
) -> Bytes {
const GELF_MAGIC: [u8; 2] = [0x1e, 0x0f];
let mut chunk = BytesMut::new();
chunk.put_slice(&GELF_MAGIC);
chunk.put_u64(message_id);
chunk.put_u8(sequence_number);
chunk.put_u8(total_chunks);
chunk.put(payload);
chunk.freeze()
}
fn get_gelf_chunks(short_message: &str, max_size: usize, rng: &mut SmallRng) -> Vec<Bytes> {
let message_id = rand::random();
let payload = get_gelf_payload(short_message);
let payload_chunks = payload.as_bytes().chunks(max_size).collect::<Vec<_>>();
let total_chunks = payload_chunks.len();
assert!(total_chunks <= 128, "too many gelf chunks");
let mut chunks = payload_chunks
.into_iter()
.enumerate()
.map(|(i, payload_chunk)| {
create_gelf_chunk(message_id, i as u8, total_chunks as u8, payload_chunk)
})
.collect::<Vec<_>>();
// Shuffle the chunks to simulate out-of-order delivery
chunks.shuffle(rng);
chunks
}
#[test]
fn generate_config() {
crate::test_util::test_generate_config::<SocketConfig>();
}
//////// TCP TESTS ////////
#[tokio::test]
async fn tcp_it_includes_host() {
assert_source_compliance(&SOCKET_PUSH_SOURCE_TAGS, async {
let (tx, mut rx) = SourceSender::new_test();
let addr = next_addr();
let server = SocketConfig::from(TcpConfig::from_address(addr.into()))
.build(SourceContext::new_test(tx, None))
.await
.unwrap();
tokio::spawn(server);
wait_for_tcp(addr).await;
let addr = send_lines(addr, vec!["test".to_owned()].into_iter())
.await
.unwrap();
let event = rx.next().await.unwrap();
assert_eq!(event.as_log()["host"], addr.ip().to_string().into());
assert_eq!(event.as_log()["port"], addr.port().into());
})
.await;
}
#[tokio::test]
async fn tcp_it_includes_vector_namespaced_fields() {
assert_source_compliance(&SOCKET_PUSH_SOURCE_TAGS, async {
let (tx, mut rx) = SourceSender::new_test();
let addr = next_addr();
let mut conf = TcpConfig::from_address(addr.into());
conf.set_log_namespace(Some(true));
let server = SocketConfig::from(conf)
.build(SourceContext::new_test(tx, None))
.await
.unwrap();
tokio::spawn(server);
wait_for_tcp(addr).await;
let addr = send_lines(addr, vec!["test".to_owned()].into_iter())
.await
.unwrap();
let event = rx.next().await.unwrap();
let log = event.as_log();
let event_meta = log.metadata().value();
assert_eq!(log.value(), &"test".into());
assert_eq!(
event_meta.get(path!("vector", "source_type")).unwrap(),
&value!(SocketConfig::NAME)
);
assert_eq!(
event_meta.get(path!(SocketConfig::NAME, "host")).unwrap(),
&value!(addr.ip().to_string())
);
assert_eq!(
event_meta.get(path!(SocketConfig::NAME, "port")).unwrap(),
&value!(addr.port())
);
})
.await;
}
#[tokio::test]
async fn tcp_splits_on_newline() {
assert_source_compliance(&SOCKET_PUSH_SOURCE_TAGS, async {
let (tx, rx) = SourceSender::new_test();
let addr = next_addr();
let server = SocketConfig::from(TcpConfig::from_address(addr.into()))
.build(SourceContext::new_test(tx, None))
.await
.unwrap();
tokio::spawn(server);
wait_for_tcp(addr).await;
send_lines(addr, vec!["foo\nbar".to_owned()].into_iter())
.await
.unwrap();
let events = collect_n(rx, 2).await;
assert_eq!(events.len(), 2);
assert_eq!(
events[0].as_log()[log_schema().message_key().unwrap().to_string()],
"foo".into()
);
assert_eq!(
events[1].as_log()[log_schema().message_key().unwrap().to_string()],
"bar".into()
);
})
.await;
}
#[tokio::test]
async fn tcp_it_includes_source_type() {
assert_source_compliance(&SOCKET_PUSH_SOURCE_TAGS, async {
let (tx, mut rx) = SourceSender::new_test();
let addr = next_addr();
let server = SocketConfig::from(TcpConfig::from_address(addr.into()))
.build(SourceContext::new_test(tx, None))
.await
.unwrap();
tokio::spawn(server);
wait_for_tcp(addr).await;
send_lines(addr, vec!["test".to_owned()].into_iter())
.await
.unwrap();
let event = rx.next().await.unwrap();
assert_eq!(
event.as_log()[log_schema().source_type_key().unwrap().to_string()],
"socket".into()
);
})
.await;
}
#[tokio::test]
async fn tcp_continue_after_long_line() {
assert_source_compliance(&SOCKET_PUSH_SOURCE_TAGS, async {
let (tx, mut rx) = SourceSender::new_test();
let addr = next_addr();
let mut config = TcpConfig::from_address(addr.into());
config.set_framing(Some(
NewlineDelimitedDecoderConfig::new_with_max_length(10).into(),
));
let server = SocketConfig::from(config)
.build(SourceContext::new_test(tx, None))
.await
.unwrap();
tokio::spawn(server);
let lines = vec![
"short".to_owned(),
"this is too long".to_owned(),
"more short".to_owned(),
];
wait_for_tcp(addr).await;
send_lines(addr, lines.into_iter()).await.unwrap();
let event = rx.next().await.unwrap();
assert_eq!(
event.as_log()[log_schema().message_key().unwrap().to_string()],
"short".into()
);
let event = rx.next().await.unwrap();
assert_eq!(
event.as_log()[log_schema().message_key().unwrap().to_string()],
"more short".into()
);
})
.await;
}
#[tokio::test]
async fn tcp_with_tls() {
assert_source_compliance(&SOCKET_PUSH_SOURCE_TAGS, async {
let (tx, mut rx) = SourceSender::new_test();
let addr = next_addr();
let mut config = TcpConfig::from_address(addr.into());
config.set_tls(Some(TlsSourceConfig {
tls_config: TlsEnableableConfig {
enabled: Some(true),
options: TlsConfig {
verify_certificate: Some(true),
crt_file: Some(tls::TEST_PEM_CRT_PATH.into()),
key_file: Some(tls::TEST_PEM_KEY_PATH.into()),
ca_file: Some(tls::TEST_PEM_CA_PATH.into()),
..Default::default()
},
},
client_metadata_key: Some(OptionalValuePath::from(owned_value_path!("tls_peer"))),
}));
let server = SocketConfig::from(config)
.build(SourceContext::new_test(tx, None))
.await
.unwrap();
tokio::spawn(server);
let lines = vec!["one line".to_owned(), "another line".to_owned()];
wait_for_tcp(addr).await;
send_lines_tls(
addr,
"localhost".into(),
lines.into_iter(),
std::path::Path::new(tls::TEST_PEM_CA_PATH),
std::path::Path::new(tls::TEST_PEM_CLIENT_CRT_PATH),
std::path::Path::new(tls::TEST_PEM_CLIENT_KEY_PATH),
)
.await
.unwrap();
let event = rx.next().await.unwrap();
assert_eq!(
event.as_log()[log_schema().message_key().unwrap().to_string()],
"one line".into()
);
let tls_meta: ObjectMap = btreemap!(
"subject" => "CN=localhost,OU=Vector,O=Datadog,L=New York,ST=New York,C=US"
);
assert_eq!(event.as_log()["tls_peer"], tls_meta.clone().into(),);
let event = rx.next().await.unwrap();
assert_eq!(
event.as_log()[log_schema().message_key().unwrap().to_string()],
"another line".into()
);
assert_eq!(event.as_log()["tls_peer"], tls_meta.clone().into(),);
})
.await;
}
#[tokio::test]
async fn tcp_with_tls_vector_namespace() {
assert_source_compliance(&SOCKET_PUSH_SOURCE_TAGS, async {
let (tx, mut rx) = SourceSender::new_test();
let addr = next_addr();
let mut config = TcpConfig::from_address(addr.into());
config.set_tls(Some(TlsSourceConfig {
tls_config: TlsEnableableConfig {
enabled: Some(true),
options: TlsConfig {
verify_certificate: Some(true),
crt_file: Some(tls::TEST_PEM_CRT_PATH.into()),
key_file: Some(tls::TEST_PEM_KEY_PATH.into()),
ca_file: Some(tls::TEST_PEM_CA_PATH.into()),
..Default::default()
},
},
client_metadata_key: None,
}));
config.log_namespace = Some(true);
let server = SocketConfig::from(config)
.build(SourceContext::new_test(tx, None))
.await
.unwrap();
tokio::spawn(server);
let lines = vec!["one line".to_owned(), "another line".to_owned()];
wait_for_tcp(addr).await;
send_lines_tls(
addr,
"localhost".into(),
lines.into_iter(),
std::path::Path::new(tls::TEST_PEM_CA_PATH),
std::path::Path::new(tls::TEST_PEM_CLIENT_CRT_PATH),
std::path::Path::new(tls::TEST_PEM_CLIENT_KEY_PATH),
)
.await
.unwrap();
let event = rx.next().await.unwrap();
let log = event.as_log();
let event_meta = log.metadata().value();
assert_eq!(log.value(), &"one line".into());
let tls_meta: ObjectMap = btreemap!(
"subject" => "CN=localhost,OU=Vector,O=Datadog,L=New York,ST=New York,C=US"
);
assert_eq!(
event_meta
.get(path!(SocketConfig::NAME, "tls_client_metadata"))
.unwrap(),
&value!(tls_meta.clone())
);
let event = rx.next().await.unwrap();
let log = event.as_log();
let event_meta = log.metadata().value();
assert_eq!(log.value(), &"another line".into());
assert_eq!(
event_meta
.get(path!(SocketConfig::NAME, "tls_client_metadata"))
.unwrap(),
&value!(tls_meta.clone())
);
})
.await;
}
#[tokio::test]
async fn tcp_shutdown_simple() {
assert_source_compliance(&SOCKET_PUSH_SOURCE_TAGS, async {
let source_id = ComponentKey::from("tcp_shutdown_simple");
let (tx, mut rx) = SourceSender::new_test();
let addr = next_addr();
let (cx, mut shutdown) = SourceContext::new_shutdown(&source_id, tx);
// Start TCP Source
let server = SocketConfig::from(TcpConfig::from_address(addr.into()))
.build(cx)
.await
.unwrap();
let source_handle = tokio::spawn(server);
// Send data to Source.
wait_for_tcp(addr).await;
send_lines(addr, vec!["test".to_owned()].into_iter())
.await
.unwrap();
let event = rx.next().await.unwrap();
assert_eq!(
event.as_log()[log_schema().message_key().unwrap().to_string()],
"test".into()
);
// Now signal to the Source to shut down.
let deadline = Instant::now() + Duration::from_secs(10);
let shutdown_complete = shutdown.shutdown_source(&source_id, deadline);
let shutdown_success = shutdown_complete.await;
assert!(shutdown_success);
// Ensure source actually shut down successfully.
_ = source_handle.await.unwrap();
})
.await;
}
// Intentially not using assert_source_compliance here because this is a round-trip test which
// means source and sink will both emit `EventsSent` , triggering multi-emission check.
#[tokio::test]
async fn tcp_shutdown_infinite_stream() {
// We create our TCP source with a larger-than-normal send buffer, which helps ensure that
// the source doesn't block on sending the events downstream, otherwise if it was blocked on
// doing so, it wouldn't be able to wake up and loop to see that it had been signalled to
// shutdown.
let addr = next_addr();
let (source_tx, source_rx) = SourceSender::new_test_sender_with_buffer(10_000);
let source_key = ComponentKey::from("tcp_shutdown_infinite_stream");
let (source_cx, mut shutdown) = SourceContext::new_shutdown(&source_key, source_tx);
let mut source_config = TcpConfig::from_address(addr.into());
source_config.set_shutdown_timeout_secs(1);
let source_task = SocketConfig::from(source_config)
.build(source_cx)
.await
.unwrap();
// Spawn the source task and wait until we're sure it's listening:
let source_handle = tokio::spawn(source_task);
wait_for_tcp(addr).await;
// Now we create a TCP _sink_ which we'll feed with an infinite stream of events to ship to
// our TCP source. This will ensure that our TCP source is fully-loaded as we try to shut
// it down, exercising the logic we have to ensure timely shutdown even under load:
let message = random_string(512);
let message_bytes = Bytes::from(message.clone());
#[derive(Clone, Debug)]
struct Serializer {
bytes: Bytes,
}
impl tokio_util::codec::Encoder<Event> for Serializer {
type Error = vector_lib::codecs::encoding::Error;
fn encode(&mut self, _: Event, buffer: &mut BytesMut) -> Result<(), Self::Error> {
buffer.put(self.bytes.as_ref());
buffer.put_u8(b'\n');
Ok(())
}
}
let sink_config = TcpSinkConfig::from_address(format!("localhost:{}", addr.port()));
let encoder = Serializer {
bytes: message_bytes,
};
let (sink, _healthcheck) = sink_config.build(Default::default(), encoder).unwrap();
tokio::spawn(async move {
let input = stream::repeat_with(|| LogEvent::default().into()).boxed();
sink.run(input).await.unwrap();
});
// Now with our sink running, feeding events to the source, collect 100 event arrays from
// the source and make sure each event within them matches the single message we repeatedly
// sent via the sink:
let events = collect_n_limited(source_rx, 100)
.await
.into_iter()
.collect::<Vec<_>>();
assert_eq!(100, events.len());
let message_key = log_schema().message_key().unwrap().to_string();
let expected_message = message.clone().into();
for event in events.into_iter().flat_map(EventContainer::into_events) {
assert_eq!(event.as_log()[message_key.as_str()], expected_message);
}
// Now trigger shutdown on the source and ensure that it shuts down before or at the
// deadline, and make sure the source task actually finished as well:
let shutdown_timeout_limit = Duration::from_secs(10);
let deadline = Instant::now() + shutdown_timeout_limit;
let shutdown_complete = shutdown.shutdown_source(&source_key, deadline);
let shutdown_result = timeout(shutdown_timeout_limit, shutdown_complete).await;
assert_eq!(shutdown_result, Ok(true));
let source_result = source_handle.await.expect("source task should not panic");
assert_eq!(source_result, Ok(()));
}
#[tokio::test]
async fn tcp_connection_close_after_max_duration() {
let (tx, _) = SourceSender::new_test();
let addr = next_addr();
let mut source_config = TcpConfig::from_address(addr.into());
source_config.set_max_connection_duration_secs(Some(1));
let source_task = SocketConfig::from(source_config)
.build(SourceContext::new_test(tx, None))
.await
.unwrap();
// Spawn the source task and wait until we're sure it's listening:
drop(tokio::spawn(source_task));
wait_for_tcp(addr).await;
let mut stream: TcpStream = TcpStream::connect(addr)
.await
.expect("stream should be able to connect");
let start = Instant::now();
let timeout = tokio::time::sleep(Duration::from_millis(1200));
let mut buffer = [0u8; 10];
tokio::select! {
_ = timeout => {
panic!("timed out waiting for stream to close")
},
read_result = stream.read(&mut buffer) => {
match read_result {
// read resulting with 0 bytes -> the connection was closed
Ok(0) => assert_relative_eq!(start.elapsed().as_secs_f64(), 1.0, epsilon = 0.3),
Ok(_) => panic!("unexpectedly read data from stream"),
Err(e) => panic!("{:}", e)
}
}
}
}
//////// UDP TESTS ////////
fn send_lines_udp(addr: SocketAddr, lines: impl IntoIterator<Item = String>) -> SocketAddr {
send_packets_udp(addr, lines.into_iter().map(|line| line.into()))
}
fn send_packets_udp(addr: SocketAddr, packets: impl IntoIterator<Item = Bytes>) -> SocketAddr {
let bind = next_addr();
let socket = UdpSocket::bind(bind)
.map_err(|error| panic!("{:}", error))
.ok()
.unwrap();
for packet in packets {
assert_eq!(
socket
.send_to(&packet, addr)
.map_err(|error| panic!("{:}", error))
.ok()
.unwrap(),
packet.len()
);
// Space things out slightly to try to avoid dropped packets
thread::sleep(Duration::from_millis(1));
}
// Give packets some time to flow through
thread::sleep(Duration::from_millis(10));
// Done
bind
}
async fn init_udp_with_shutdown(
sender: SourceSender,
source_id: &ComponentKey,
shutdown: &mut SourceShutdownCoordinator,
) -> (SocketAddr, JoinHandle<Result<(), ()>>) {
let (shutdown_signal, _) = shutdown.register_source(source_id, false);
init_udp_inner(sender, source_id, shutdown_signal, None, false).await
}
async fn init_udp(sender: SourceSender, use_log_namespace: bool) -> SocketAddr {
let (addr, _handle) = init_udp_inner(
sender,
&ComponentKey::from("default"),
ShutdownSignal::noop(),
None,
use_log_namespace,
)
.await;
addr
}
async fn init_udp_with_config(sender: SourceSender, config: UdpConfig) -> SocketAddr {
let (addr, _handle) = init_udp_inner(
sender,
&ComponentKey::from("default"),
ShutdownSignal::noop(),
Some(config),
false,
)
.await;
addr
}
async fn init_udp_inner(
sender: SourceSender,
source_key: &ComponentKey,
shutdown_signal: ShutdownSignal,
config: Option<UdpConfig>,
use_vector_namespace: bool,
) -> (SocketAddr, JoinHandle<Result<(), ()>>) {
let (address, mut config) = match config {
Some(config) => match config.address() {
SocketListenAddr::SocketAddr(addr) => (addr, config),
_ => panic!("listen address should not be systemd FD offset in tests"),
},
None => {
let address = next_addr();
(address, UdpConfig::from_address(address.into()))
}
};
let config = if use_vector_namespace {
config.set_log_namespace(Some(true));
config
} else {
config
};
let server = SocketConfig::from(config)
.build(SourceContext::new(
source_key.clone(),
GlobalOptions::default(),
shutdown_signal,
sender,
Default::default(),
false,
Default::default(),