vector/sinks/util/
tcp.rs

1use std::{
2    io::ErrorKind,
3    net::SocketAddr,
4    pin::Pin,
5    task::{Context, Poll},
6};
7
8use async_trait::async_trait;
9use bytes::{Bytes, BytesMut};
10use futures::{SinkExt, StreamExt, stream::BoxStream, task::noop_waker_ref};
11use snafu::{ResultExt, Snafu};
12use tokio::{
13    io::{AsyncRead, ReadBuf},
14    net::TcpStream,
15    time::sleep,
16};
17use tokio_util::codec::Encoder;
18use vector_lib::{
19    ByteSizeOf, EstimatedJsonEncodedSizeOf, configurable::configurable_component,
20    json_size::JsonSize,
21};
22
23use crate::{
24    codecs::Transformer,
25    common::backoff::ExponentialBackoff,
26    dns,
27    event::Event,
28    internal_events::{
29        ConnectionOpen, OpenGauge, SocketMode, SocketSendError, TcpSocketConnectionEstablished,
30        TcpSocketConnectionShutdown, TcpSocketOutgoingConnectionError,
31    },
32    sink_ext::VecSinkExt,
33    sinks::{
34        Healthcheck, VectorSink,
35        util::{
36            EncodedEvent, SinkBuildError, StreamSink,
37            socket_bytes_sink::{BytesSink, ShutdownCheck},
38        },
39    },
40    tcp::TcpKeepaliveConfig,
41    tls::{MaybeTlsSettings, MaybeTlsStream, TlsEnableableConfig, TlsError},
42};
43
44#[derive(Debug, Snafu)]
45enum TcpError {
46    #[snafu(display("Connect error: {}", source))]
47    ConnectError { source: TlsError },
48    #[snafu(display("Unable to resolve DNS: {}", source))]
49    DnsError { source: dns::DnsError },
50    #[snafu(display("No addresses returned."))]
51    NoAddresses,
52}
53
54/// A TCP sink.
55#[configurable_component]
56#[derive(Clone, Debug)]
57pub struct TcpSinkConfig {
58    /// The address to connect to.
59    ///
60    /// Both IP address and hostname are accepted formats.
61    ///
62    /// The address _must_ include a port.
63    #[configurable(metadata(docs::examples = "92.12.333.224:5000"))]
64    #[configurable(metadata(docs::examples = "https://somehost:5000"))]
65    address: String,
66
67    #[configurable(derived)]
68    keepalive: Option<TcpKeepaliveConfig>,
69
70    #[configurable(derived)]
71    tls: Option<TlsEnableableConfig>,
72
73    /// The size of the socket's send buffer.
74    ///
75    /// If set, the value of the setting is passed via the `SO_SNDBUF` option.
76    #[configurable(metadata(docs::type_unit = "bytes"))]
77    #[configurable(metadata(docs::examples = 65536))]
78    send_buffer_bytes: Option<usize>,
79}
80
81impl TcpSinkConfig {
82    pub const fn new(
83        address: String,
84        keepalive: Option<TcpKeepaliveConfig>,
85        tls: Option<TlsEnableableConfig>,
86        send_buffer_bytes: Option<usize>,
87    ) -> Self {
88        Self {
89            address,
90            keepalive,
91            tls,
92            send_buffer_bytes,
93        }
94    }
95
96    pub const fn from_address(address: String) -> Self {
97        Self {
98            address,
99            keepalive: None,
100            tls: None,
101            send_buffer_bytes: None,
102        }
103    }
104
105    pub fn build(
106        &self,
107        transformer: Transformer,
108        encoder: impl Encoder<Event, Error = vector_lib::codecs::encoding::Error>
109        + Clone
110        + Send
111        + Sync
112        + 'static,
113    ) -> crate::Result<(VectorSink, Healthcheck)> {
114        let uri = self.address.parse::<http::Uri>()?;
115        let host = uri.host().ok_or(SinkBuildError::MissingHost)?.to_string();
116        let port = uri.port_u16().ok_or(SinkBuildError::MissingPort)?;
117        let tls = MaybeTlsSettings::from_config(self.tls.as_ref(), false)?;
118        let connector = TcpConnector::new(host, port, self.keepalive, tls, self.send_buffer_bytes);
119        let sink = TcpSink::new(connector.clone(), transformer, encoder);
120
121        Ok((
122            VectorSink::from_event_streamsink(sink),
123            Box::pin(async move { connector.healthcheck().await }),
124        ))
125    }
126}
127
128#[derive(Clone)]
129struct TcpConnector {
130    host: String,
131    port: u16,
132    keepalive: Option<TcpKeepaliveConfig>,
133    tls: MaybeTlsSettings,
134    send_buffer_bytes: Option<usize>,
135}
136
137impl TcpConnector {
138    const fn new(
139        host: String,
140        port: u16,
141        keepalive: Option<TcpKeepaliveConfig>,
142        tls: MaybeTlsSettings,
143        send_buffer_bytes: Option<usize>,
144    ) -> Self {
145        Self {
146            host,
147            port,
148            keepalive,
149            tls,
150            send_buffer_bytes,
151        }
152    }
153
154    #[cfg(test)]
155    fn from_host_port(host: String, port: u16) -> Self {
156        Self::new(host, port, None, None.into(), None)
157    }
158
159    fn fresh_backoff() -> ExponentialBackoff {
160        // TODO: make configurable
161        ExponentialBackoff::default()
162    }
163
164    async fn connect(&self) -> Result<MaybeTlsStream<TcpStream>, TcpError> {
165        let ip = dns::Resolver
166            .lookup_ip(self.host.clone())
167            .await
168            .context(DnsSnafu)?
169            .next()
170            .ok_or(TcpError::NoAddresses)?;
171
172        let addr = SocketAddr::new(ip, self.port);
173        self.tls
174            .connect(&self.host, &addr)
175            .await
176            .context(ConnectSnafu)
177            .map(|mut maybe_tls| {
178                if let Some(keepalive) = self.keepalive
179                    && let Err(error) = maybe_tls.set_keepalive(keepalive)
180                {
181                    warn!(message = "Failed configuring TCP keepalive.", %error);
182                }
183
184                if let Some(send_buffer_bytes) = self.send_buffer_bytes
185                    && let Err(error) = maybe_tls.set_send_buffer_bytes(send_buffer_bytes)
186                {
187                    warn!(message = "Failed configuring send buffer size on TCP socket.", %error);
188                }
189
190                maybe_tls
191            })
192    }
193
194    async fn connect_backoff(&self) -> MaybeTlsStream<TcpStream> {
195        let mut backoff = Self::fresh_backoff();
196        loop {
197            match self.connect().await {
198                Ok(socket) => {
199                    emit!(TcpSocketConnectionEstablished {
200                        peer_addr: socket.peer_addr().ok(),
201                    });
202                    return socket;
203                }
204                Err(error) => {
205                    emit!(TcpSocketOutgoingConnectionError { error });
206                    sleep(backoff.next().unwrap()).await;
207                }
208            }
209        }
210    }
211
212    async fn healthcheck(&self) -> crate::Result<()> {
213        self.connect().await.map(|_| ()).map_err(Into::into)
214    }
215}
216
217struct TcpSink<E>
218where
219    E: Encoder<Event, Error = vector_lib::codecs::encoding::Error> + Clone + Send + Sync,
220{
221    connector: TcpConnector,
222    transformer: Transformer,
223    encoder: E,
224}
225
226impl<E> TcpSink<E>
227where
228    E: Encoder<Event, Error = vector_lib::codecs::encoding::Error> + Clone + Send + Sync + 'static,
229{
230    const fn new(connector: TcpConnector, transformer: Transformer, encoder: E) -> Self {
231        Self {
232            connector,
233            transformer,
234            encoder,
235        }
236    }
237
238    async fn connect(&self) -> BytesSink<MaybeTlsStream<TcpStream>> {
239        let stream = self.connector.connect_backoff().await;
240        BytesSink::new(stream, Self::shutdown_check, SocketMode::Tcp)
241    }
242
243    fn shutdown_check(stream: &mut MaybeTlsStream<TcpStream>) -> ShutdownCheck {
244        // Test if the remote has issued a disconnect by calling read(2)
245        // with a 1 sized buffer.
246        //
247        // This can return a proper disconnect error or `Ok(0)`
248        // which means the pipe is broken and we should try to reconnect.
249        //
250        // If this returns `Poll::Pending` we know the connection is still
251        // valid and the write will most likely succeed.
252        let mut cx = Context::from_waker(noop_waker_ref());
253        let mut buf = [0u8; 1];
254        let mut buf = ReadBuf::new(&mut buf);
255        match Pin::new(stream).poll_read(&mut cx, &mut buf) {
256            Poll::Ready(Err(error)) => ShutdownCheck::Error(error),
257            Poll::Ready(Ok(())) if buf.filled().is_empty() => {
258                // Maybe this is only a sign to close the channel,
259                // in which case we should try to flush our buffers
260                // before disconnecting.
261                ShutdownCheck::Close("ShutdownCheck::Close")
262            }
263            _ => ShutdownCheck::Alive,
264        }
265    }
266}
267
268#[async_trait]
269impl<E> StreamSink<Event> for TcpSink<E>
270where
271    E: Encoder<Event, Error = vector_lib::codecs::encoding::Error>
272        + Clone
273        + Send
274        + Sync
275        + Sync
276        + 'static,
277{
278    async fn run(self: Box<Self>, input: BoxStream<'_, Event>) -> Result<(), ()> {
279        // We need [Peekable](https://docs.rs/futures/0.3.6/futures/stream/struct.Peekable.html) for initiating
280        // connection only when we have something to send.
281        let mut encoder = self.encoder.clone();
282        let mut input = input
283            .map(|mut event| {
284                let byte_size = event.size_of();
285                let json_byte_size = event.estimated_json_encoded_size_of();
286                let finalizers = event.metadata_mut().take_finalizers();
287                self.transformer.transform(&mut event);
288                let mut bytes = BytesMut::new();
289
290                // Errors are handled by `Encoder`.
291                if encoder.encode(event, &mut bytes).is_ok() {
292                    let item = bytes.freeze();
293                    EncodedEvent {
294                        item,
295                        finalizers,
296                        byte_size,
297                        json_byte_size,
298                    }
299                } else {
300                    EncodedEvent::new(Bytes::new(), 0, JsonSize::zero())
301                }
302            })
303            .peekable();
304
305        while Pin::new(&mut input).peek().await.is_some() {
306            let mut sink = self.connect().await;
307            let _open_token = OpenGauge::new().open(|count| emit!(ConnectionOpen { count }));
308
309            let result = match sink.send_all_peekable(&mut (&mut input).peekable()).await {
310                Ok(()) => sink.close().await,
311                Err(error) => Err(error),
312            };
313
314            // TODO we can consider retrying once in the Error case. This sink is a "best effort"
315            // delivery due to the nature of the underlying protocol.
316            // For now, if an error occurs we cannot assume that the events succeeded in delivery
317            // so we will emit `Error` / `EventsDropped` internal events regardless of if the server
318            // responded with Ok(0).
319            if let Err(error) = result {
320                if error.kind() == ErrorKind::Other && error.to_string() == "ShutdownCheck::Close" {
321                    emit!(TcpSocketConnectionShutdown {});
322                }
323                emit!(SocketSendError {
324                    mode: SocketMode::Tcp,
325                    error
326                });
327            }
328        }
329
330        Ok(())
331    }
332}
333
334#[cfg(test)]
335mod test {
336    use tokio::net::TcpListener;
337
338    use super::*;
339    use crate::test_util::{addr::next_addr, trace_init};
340
341    #[tokio::test]
342    async fn healthcheck() {
343        trace_init();
344
345        let (_guard, addr) = next_addr();
346        let _listener = TcpListener::bind(&addr).await.unwrap();
347        let good = TcpConnector::from_host_port(addr.ip().to_string(), addr.port());
348        assert!(good.healthcheck().await.is_ok());
349
350        let (_guard, addr) = next_addr();
351        let bad = TcpConnector::from_host_port(addr.ip().to_string(), addr.port());
352        assert!(bad.healthcheck().await.is_err());
353    }
354}