Skip to main content

isothrum_runner/
address_blocks.rs

1//! The address blocks a container engine's networks hold ([`Runner::address_blocks_in_use`]),
2//! so a deployment's own networks can be given blocks nothing else holds.
3
4use crate::Result;
5use crate::cli::docker;
6use crate::formats::compose::PROJECT_LABEL;
7use crate::formats::tool_error;
8use crate::name::RunName;
9use crate::runner::Runner;
10
11impl Runner {
12    /// The IPv4 address blocks (CIDR, `172.17.0.0/16`) the networks of the engine Docker context
13    /// `docker_context` reaches (the current one when none is named) hold, but those of run
14    /// `except`'s own networks (left from an earlier start): what a deployment's networks must
15    /// stay clear of. IPv6 blocks are left out.
16    ///
17    /// # Errors
18    ///
19    /// Docker is missing, or the engine can't say (it doesn't answer, a network went while it
20    /// was read).
21    pub async fn address_blocks_in_use(&self, except: Option<&RunName>, docker_context: Option<&str>) -> Result<Vec<String>> {
22        let processes = self.docker(docker_context);
23        let call = self.call(&processes);
24        docker::network_blocks(&call, PROJECT_LABEL, except.map(RunName::as_str))
25            .await
26            .map_err(|e| tool_error("address-blocks", e))
27    }
28}
29
30#[cfg(test)]
31mod tests {
32    use std::sync::Arc;
33
34    use crate::process::fake::{FakeProcesses, Reply};
35    use crate::testing::{no_ports, processes, runner_config};
36    use crate::{RunName, Runner};
37
38    /// A runner with a temporary home on `fake`.
39    fn a_runner(fake: FakeProcesses) -> (tempfile::TempDir, Runner) {
40        let home = tempfile::tempdir().expect("a folder");
41        let config = runner_config(home.path(), processes(&Arc::new(fake)), no_ports(), crate::runner::this_host());
42        (home, Runner::new(config).expect("a runner"))
43    }
44
45    /// An engine whose networks are `listed` (`<name>\t<project>` lines; none: it doesn't
46    /// answer), each inspected network's blocks as `inspect` gives them.
47    fn engine(listed: Option<&'static str>, inspect: fn(&str) -> &'static str) -> FakeProcesses {
48        FakeProcesses::model(move |call| match call.args.iter().map(String::as_str).collect::<Vec<_>>().as_slice() {
49            ["network", "ls", "--format", format] if format.contains(".Label \"com.docker.compose.project\"") => match listed {
50                Some(listed) => Reply::ok(listed),
51                None => Reply::fail(1, "Cannot connect to the Docker daemon at unix:///var/run/docker.sock"),
52            },
53            ["network", "inspect", "--format", _, names @ ..] => Reply::ok(&names.iter().map(|n| inspect(n)).collect::<Vec<_>>().join("\n")),
54            other => panic!("unexpected call {other:?}"),
55        })
56    }
57
58    #[tokio::test]
59    async fn the_blocks_of_every_other_network_are_listed_ipv4_only() {
60        // `web`'s own network is told by its exact project label: `web-2`'s, whose name starts
61        // the same, is another's.
62        let fake = engine(Some("bridge\t\nweb_default\tweb\nweb-2_default\tweb-2\n"), |name| match name {
63            "bridge" => "172.17.0.0/16 fd00::/64 ",
64            "web-2_default" => "10.9.0.0/24 ",
65            other => panic!("{other} is web's own"),
66        });
67        let (_home, runner) = a_runner(fake);
68        let web = RunName::new("web").expect("a name");
69        assert_eq!(
70            runner.address_blocks_in_use(Some(&web), None).await.expect("listed"),
71            ["172.17.0.0/16", "10.9.0.0/24"]
72        );
73    }
74
75    #[tokio::test]
76    async fn an_engine_that_cant_say_is_an_error_and_no_other_network_inspects_nothing() {
77        let web = RunName::new("web").expect("a name");
78        let (_silent, silent) = a_runner(engine(None, |_| ""));
79        let err = silent.address_blocks_in_use(Some(&web), None).await.expect_err("no answer");
80        assert_eq!(err.code(), crate::ErrorCode::ToolFailed, "{err}");
81        let (_alone, alone) = a_runner(engine(Some("web_default\tweb\n"), |name| panic!("{name} is web's own")));
82        assert_eq!(alone.address_blocks_in_use(Some(&web), None).await.expect("listed"), Vec::<String>::new());
83    }
84}