Skip to main content

panoramic_courier/
lib.rs

1//! Probes, sends, HTTP requests and file follows, run from where the software runs.
2//!
3//! Panoramic copies the `courier` binary into each container and pod and runs it there through exec, so it reaches a
4//! listener the way a peer would. A probe from outside proves nothing: the Docker port proxy accepts a connection even
5//! when nothing listens inside. For host process groups, panoramic calls this library in-process instead.
6//!
7//! The courier has four operations, and only four:
8//!
9//! - [`probe`]: whether something accepts a connection at a `tcp`, `http` or `grpc` address, whether a Unix socket
10//!   exists and accepts, or whether a named pipe exists. A probe cannot confirm a UDP listener, so it refuses `udp`.
11//! - [`send`]: opens one connection, or sends one datagram, and writes the bytes as given.
12//! - [`http_get`]: makes one plain-HTTP `GET` request and returns the status and body. The courier does not speak TLS.
13//! - [`follow`]: streams a log file's contents as they are written, so an image needs neither `sh` nor `tail`.
14//!
15//! # Addresses
16//!
17//! An [`Address`] is written as the URL a consumer receives: `tcp://<host>:<port>`, `udp://<host>:<port>`,
18//! `http://<host>:<port>`, `grpc://<host>:<port>`, `unix://<path>` for a stream socket, `unixgram://<path>` for a
19//! datagram socket, and `pipe://<name>` for the named pipe `\\.\pipe\<name>` on Windows.
20//!
21//! # Command line
22//!
23//! ```text
24//! courier --deadline <duration> probe <address>
25//! courier --deadline <duration> send <address> [--payload-hex <hex>] < payload
26//! courier --deadline <duration> http <address> [--path <path>]
27//! courier --deadline <duration> follow <path>
28//! ```
29//!
30//! `--deadline` is required, and is a whole number with a unit: `ms`, `s` or `m`, as in `500ms`, `10s` or `2m`. It
31//! bounds the whole operation, including name resolution, but not reading the input of `send` or writing the output of
32//! `http`. For `follow`, it is how long to follow: reaching it after the file was found is the normal end, even while
33//! output is being written.
34//!
35//! - `probe` writes nothing to standard output.
36//! - `send` reads its payload from standard input until end of file, then writes it. With `--payload-hex`, the payload
37//!   is the bytes its digits spell, and standard input is not read. It writes nothing to standard output.
38//! - `http` requests `--path` (default `/`) and writes the status code on one line, then the body exactly as
39//!   received.
40//! - `follow` waits for the file to exist, then writes its contents from the start, as they arrive.
41//!
42//! The library's `limit` is the same deadline, with one gap. Name resolution runs `getaddrinfo` on a blocking thread,
43//! and the deadline abandons the lookup without stopping it, so the thread stays busy until the resolver answers. The
44//! binary exits without waiting for it.
45//!
46//! On failure, the courier writes one line to standard error, starting with `courier: `. Bad arguments instead get an
47//! error and usage text on standard error.
48//!
49//! # Exit codes
50//!
51//! - `0`: the operation completed. For `http`, a response arrived, whatever its status.
52//! - `1`: the software refused or is not there yet. A name does not resolve, nothing accepted, a read or write failed,
53//!   the deadline passed, or an HTTP response was malformed. A peer's name may not resolve until the peer starts.
54//! - `2`: a harness problem. The arguments were bad, the operation does not support the address, or reading input or
55//!   writing output failed.
56//! - Any other status, such as `101` from a panic or none from a signal, is a harness problem.
57//!
58//! [`Error::fault`] makes the same split for library callers.
59#![deny(missing_docs)]
60
61use std::{io, time::Duration};
62
63use snafu::Snafu;
64
65mod address;
66mod follow;
67mod http;
68mod net;
69mod probe;
70mod send;
71
72pub use self::{
73    address::{Address, HostPort},
74    follow::follow,
75    http::{http_get, HttpResponse},
76    probe::probe,
77    send::send,
78};
79
80/// Who an [`Error`] blames.
81#[derive(Clone, Copy, Debug, Eq, PartialEq)]
82pub enum Fault {
83    /// The courier worked, and the software refused, answered badly or is not there yet.
84    Software,
85
86    /// The courier could not do what was asked: the request was invalid or a local resource failed.
87    Harness,
88}
89
90/// An error from a courier operation.
91#[derive(Debug, Snafu)]
92#[snafu(visibility(pub(crate)))]
93pub enum Error {
94    /// The text is not an address the courier understands.
95    #[snafu(display("invalid address '{address}': {reason}"))]
96    InvalidAddress {
97        /// The text as given.
98        address: String,
99        /// What is wrong with it.
100        reason: &'static str,
101    },
102
103    /// The operation cannot be done on this kind of address, or on this OS.
104    #[snafu(display("{operation} cannot reach '{address}': {reason}"))]
105    Unsupported {
106        /// The operation asked for.
107        operation: &'static str,
108        /// The address it was asked to reach.
109        address: Address,
110        /// Why not.
111        reason: &'static str,
112    },
113
114    /// The HTTP request path is not one the courier can send.
115    #[snafu(display("invalid HTTP path '{path}': it must start with '/' and hold no whitespace"))]
116    InvalidPath {
117        /// The path as given.
118        path: String,
119    },
120
121    /// The host name in the address does not resolve.
122    #[snafu(display("failed to resolve '{host}': {source}"))]
123    Resolve {
124        /// The host name.
125        host: String,
126        /// The error from the resolver.
127        source: io::Error,
128    },
129
130    /// Reaching or talking to the target failed.
131    #[snafu(display("failed to {action} '{target}': {source}"))]
132    Target {
133        /// What the courier was doing, such as `connect to`.
134        action: &'static str,
135        /// The address or file path.
136        target: String,
137        /// The I/O error.
138        source: io::Error,
139    },
140
141    /// The target answered with something that is not an HTTP/1 response.
142    #[snafu(display("'{address}' sent a malformed HTTP response: {reason}"))]
143    MalformedResponse {
144        /// The address the request went to.
145        address: Address,
146        /// What is wrong with the response.
147        reason: String,
148    },
149
150    /// The operation did not finish before its deadline.
151    #[snafu(display("{operation} on '{target}' did not finish within {limit:?}"))]
152    TimedOut {
153        /// The operation.
154        operation: &'static str,
155        /// The address or file path.
156        target: String,
157        /// The deadline it was given.
158        limit: Duration,
159    },
160
161    /// Reading the operation's input failed.
162    #[snafu(display("failed to read input: {source}"))]
163    Input {
164        /// The I/O error.
165        source: io::Error,
166    },
167
168    /// Writing the operation's output failed.
169    #[snafu(display("failed to write output: {source}"))]
170    Output {
171        /// The I/O error.
172        source: io::Error,
173    },
174}
175
176impl Error {
177    /// Returns who this error blames.
178    pub fn fault(&self) -> Fault {
179        match self {
180            Self::Resolve { .. } | Self::Target { .. } | Self::MalformedResponse { .. } | Self::TimedOut { .. } => {
181                Fault::Software
182            }
183            Self::InvalidAddress { .. }
184            | Self::Unsupported { .. }
185            | Self::InvalidPath { .. }
186            | Self::Input { .. }
187            | Self::Output { .. } => Fault::Harness,
188        }
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use tokio::{
195        io::{AsyncReadExt as _, AsyncWriteExt as _},
196        net::TcpListener,
197    };
198
199    use super::*;
200
201    const LIMIT: Duration = Duration::from_secs(5);
202
203    /// Returns an `http` address whose server answers one request with `response`, then closes.
204    async fn serve_once(response: Vec<u8>) -> Address {
205        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
206        let address = format!("http://{}", listener.local_addr().unwrap()).parse().unwrap();
207        tokio::spawn(async move {
208            let (mut stream, _) = listener.accept().await.unwrap();
209            // Read the request first: closing with it unread resets the connection.
210            assert!(stream.read(&mut [0; 1024]).await.unwrap() > 0);
211            stream.write_all(&response).await.unwrap();
212        });
213        address
214    }
215
216    /// Returns an address on which nothing listens.
217    async fn closed_port(scheme: &str) -> Address {
218        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
219        let port = listener.local_addr().unwrap().port();
220        drop(listener);
221        format!("{scheme}://127.0.0.1:{port}").parse().unwrap()
222    }
223
224    #[track_caller]
225    fn assert_software<T: std::fmt::Debug>(result: Result<T, Error>) -> Error {
226        let error = result.unwrap_err();
227        assert_eq!(error.fault(), Fault::Software, "{error}");
228        error
229    }
230
231    #[tokio::test]
232    async fn closed_port_is_refused_by_the_software() {
233        for scheme in ["tcp", "http", "grpc"] {
234            let error = assert_software(probe(&closed_port(scheme).await, LIMIT).await);
235            assert!(matches!(error, Error::Target { .. }), "{error}");
236        }
237        let error = assert_software(send(&closed_port("tcp").await, b"x", LIMIT).await);
238        assert!(matches!(error, Error::Target { .. }), "{error}");
239        let error = assert_software(http_get(&closed_port("http").await, "/", LIMIT).await);
240        assert!(matches!(error, Error::Target { .. }), "{error}");
241    }
242
243    #[cfg(unix)]
244    #[tokio::test]
245    async fn missing_socket_is_refused_by_the_software() {
246        let dir = tempfile::tempdir().unwrap();
247        let path = dir.path().join("missing.sock").display().to_string();
248        for scheme in ["unix", "unixgram"] {
249            let address: Address = format!("{scheme}://{path}").parse().unwrap();
250            let error = assert_software(probe(&address, LIMIT).await);
251            assert!(matches!(error, Error::Target { .. }), "{error}");
252            let error = assert_software(send(&address, b"x", LIMIT).await);
253            assert!(matches!(error, Error::Target { .. }), "{error}");
254        }
255    }
256
257    #[tokio::test]
258    async fn silent_server_times_out() {
259        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
260        let address: Address = format!("http://{}", listener.local_addr().unwrap()).parse().unwrap();
261        // The listener's backlog accepts the connection, and nothing ever answers.
262        let error = assert_software(http_get(&address, "/", Duration::from_millis(200)).await);
263        assert!(matches!(error, Error::TimedOut { .. }), "{error}");
264    }
265
266    #[tokio::test]
267    async fn file_that_never_appears_times_out() {
268        let dir = tempfile::tempdir().unwrap();
269        let mut out = Vec::new();
270        let result = follow(&dir.path().join("never.log"), Duration::from_millis(200), &mut out).await;
271        let error = assert_software(result);
272        assert!(matches!(error, Error::TimedOut { .. }), "{error}");
273        assert!(out.is_empty());
274    }
275
276    #[tokio::test]
277    async fn listening_port_accepts_a_probe() {
278        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
279        let address: Address = format!("tcp://{}", listener.local_addr().unwrap()).parse().unwrap();
280        probe(&address, LIMIT).await.unwrap();
281    }
282
283    #[tokio::test]
284    async fn body_ends_at_content_length() {
285        let address = serve_once(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nready, and more".to_vec()).await;
286        let response = http_get(&address, "/ready", LIMIT).await.unwrap();
287        assert_eq!(response.status, 200);
288        assert_eq!(response.body, b"ready");
289    }
290
291    #[tokio::test]
292    async fn body_without_content_length_ends_at_close() {
293        let address = serve_once(b"HTTP/1.0 503 Service Unavailable\r\n\r\nnot yet".to_vec()).await;
294        let response = http_get(&address, "/", LIMIT).await.unwrap();
295        assert_eq!(response.status, 503);
296        assert_eq!(response.body, b"not yet");
297    }
298
299    #[tokio::test]
300    async fn malformed_response_is_the_softwares_fault() {
301        let too_long = [&b"HTTP/1.1 200 OK\r\n\r\n"[..], &vec![b'x'; http::MAX_BODY_LEN + 1]].concat();
302        for response in [
303            b"SSH-2.0-OpenSSH\r\n\r\n".to_vec(),
304            b"HTTP/1.garbage 200 OK\r\n\r\n".to_vec(),
305            b"HTTP/1.1 +20 OK\r\n\r\n".to_vec(),
306            b"HTTP/1.1 000 OK\r\n\r\n".to_vec(),
307            b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nshort".to_vec(),
308            format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", http::MAX_BODY_LEN + 1).into_bytes(),
309            too_long,
310        ] {
311            let address = serve_once(response).await;
312            let error = assert_software(http_get(&address, "/", LIMIT).await);
313            assert!(matches!(error, Error::MalformedResponse { .. }), "{error}");
314        }
315    }
316
317    #[tokio::test]
318    async fn unsupported_request_is_a_harness_fault() {
319        let udp: Address = "udp://127.0.0.1:9".parse().unwrap();
320        let http: Address = "http://127.0.0.1:9".parse().unwrap();
321        let cases = [
322            probe(&udp, LIMIT).await,
323            send(&http, b"x", LIMIT).await,
324            http_get(&udp, "/", LIMIT).await.map(drop),
325            http_get(&http, "ready", LIMIT).await.map(drop),
326            http_get(&http, "/a b", LIMIT).await.map(drop),
327        ];
328        for result in cases {
329            let error = result.unwrap_err();
330            assert_eq!(error.fault(), Fault::Harness, "{error}");
331        }
332    }
333}