isoloom-compose 0.11.0

The Docker Compose backend of Isoloom (docker, hosted).
Documentation
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
//! Network appliances on Docker (`docker.appliance`): router and switch OSes in containers,
//! wired the way their image expects. The images are the user's to build from software they
//! are licensed for; Isoloom ships none.
//!
//! Every kind: `eth0` is the management port, on Isoloom's management network; the machine's
//! networks follow in order as `eth1`, `eth2`... (Compose `priority`); the startup configuration
//! is Isoloom's (hostname, `admin`/`admin`, each interface with its address from the spec, for a
//! router) followed by the machine's own `config`, joined when the container starts; and IOS
//! owns the addresses (the container's own copy is removed by its network sidecar).
//!
//! - **Cisco IOL** (`vrnetlab/cisco_iol`, as containerlab runs it): `Ethernet0/0` management in
//!   its own VRF, data `Ethernet0/1`, `0/2`, `0/3`, `1/0`... (four a slot); `/iol/NETMAP` and
//!   `/iol/iouyap.ini` map the interfaces, `IOL_PID` names the instance.
//! - **QEMU images** (vrnetlab's `cisco_vios`, `cisco_viosl2`, `cisco_csr1000v`,
//!   `cisco_c8000v`): `launch.py` with containerlab's arguments (`tc` connection mode), the
//!   number of data interfaces in `CLAB_INTFS`, the startup configuration in
//!   `/config/startup-config.cfg` (vrnetlab applies it once booted), privileged for /dev/kvm.
//!   IOSv: data `GigabitEthernet0/1`...; IOS XE: data `GigabitEthernet2`...
//! - **Dynamips** (a 7200): Isoloom builds the container (Ubuntu's `dynamips`), binds each data
//!   interface to a router port (`FastEthernet0/0`, then `1/0`, `1/1`, `2/0`... on PA-2FE-TX
//!   adapters) and boots the IOS `.bin` in `firmware`.
//!
//! A LAN's `switch` (a switch kind, no `networks` of its own) takes its ports from the LAN
//! instead: an access port on each VLAN's network (at the controller address, unused on Docker,
//! as Isoloom's Linux switch had), then a trunk port on each trunk machine's link (see
//! `trunks`). Its configuration declares the VLANs (VTP transparent) and sets each port's mode.

use std::fmt;
use std::net::Ipv4Addr;

use isoloom_render::trunks;
pub(crate) use isoloom_spec::appliance::MGMT_CIDR;
use isoloom_spec::appliance::is_switch;
use isoloom_spec::model::{Appliance, Machine, Spec};
use isoloom_spec::validate::Cidr;
use isoloom_spec::vlans;

/// Isoloom's management network for appliances, outside the environment (no `reach`, no checks).
pub(crate) const MGMT_NETWORK: &str = "isoloom-mgmt";

/// The Dockerfile of the Dynamips container Isoloom builds. The packages are pinned to Ubuntu
/// 24.04's versions (hadolint's DL3008): `dynamips` as released, `iproute2` to its release's
/// series (`6.1.0-1ubuntu6*`, the newest match), so its security updates still land and the
/// pin never names a version the archive has dropped.
const DYNAMIPS_DOCKERFILE: &str = "# Dynamips, the Cisco 7200 emulator (Ubuntu's package, in its default sources), pinned to\n# Ubuntu 24.04's versions; the IOS image is the user's.\nFROM ubuntu:24.04\nRUN apt-get update && apt-get install -y --no-install-recommends dynamips=0.2.14-1build4 'iproute2=6.1.0-1ubuntu6*' && rm -rf /var/lib/apt/lists/*\n";

/// The appliance machines, in spec order.
pub(crate) fn appliances(spec: &Spec) -> Vec<(&String, &Machine, Appliance)> {
    spec.machines.iter().filter_map(|(n, m)| Some((n, m, m.docker.as_ref()?.appliance?))).collect()
}

/// [`MGMT_CIDR`] as a block, written out so reading it can't fail (a test checks they agree).
const MGMT: Cidr = Cidr {
    base: u32::from_be_bytes([10, 255, 255, 0]),
    len: 24,
};

/// An appliance's position among the environment's appliances (0 for a machine that isn't one).
fn position(spec: &Spec, name: &str) -> usize {
    appliances(spec).iter().position(|(n, _, _)| n.as_str() == name).unwrap_or(0)
}

/// An appliance's management address: .10 and up on the management network.
pub(crate) fn mgmt_address(spec: &Spec, name: &str) -> Ipv4Addr {
    Ipv4Addr::from(MGMT.base + 10 + u32::try_from(position(spec, name)).unwrap_or(0))
}

/// IOL's instance number: unique in the environment (1, 2...).
fn iol_pid(spec: &Spec, name: &str) -> usize {
    position(spec, name) + 1
}

/// The OS's name for the `k`th data interface (from 1, `eth<k>` in the container).
fn interface(kind: Appliance, k: usize) -> String {
    match kind {
        Appliance::CiscoIol | Appliance::CiscoIolL2 => format!("Ethernet{}/{}", k / 4, k % 4),
        Appliance::CiscoVios | Appliance::CiscoViosL2 => format!("GigabitEthernet0/{k}"),
        Appliance::CiscoCsr1000v | Appliance::CiscoC8000v => format!("GigabitEthernet{}", k + 1),
        Appliance::CiscoDynamips => {
            let (slot, port) = dynamips_port(k);
            format!("FastEthernet{slot}/{port}")
        }
    }
}

/// A 7200's port for the `k`th data interface: the I/O card's `0/0`, then two a PA-2FE-TX.
fn dynamips_port(k: usize) -> (usize, usize) {
    if k == 1 { (0, 0) } else { (k / 2, k % 2) }
}

/// The netmask of a prefix length.
fn mask(len: u8) -> Ipv4Addr {
    Ipv4Addr::from(u32::MAX.checked_shl(32 - u32::from(len.min(32))).unwrap_or(0))
}

/// One data interface of an appliance: `eth1`, `eth2`... in order.
pub(crate) struct Port {
    /// The Compose network it is on.
    pub(crate) network: String,
    /// The container's address there (none on a trunk's link, which has no addresses).
    pub(crate) address: Option<Ipv4Addr>,
    /// What the port carries: the network itself, one VLAN, or a trunk.
    role: Role,
}

/// What a data interface is for.
enum Role {
    /// One of the machine's own networks (a router's interface takes its address).
    Network,
    /// A LAN switch's access port in a VLAN.
    Access(u16),
    /// A LAN switch's trunk to a machine on several of its VLANs: that machine, the VLAN ids.
    Trunk(String, Vec<u16>),
}

/// The data interfaces of appliance `name`, in order: its networks; for a LAN's `switch`, an
/// access port per VLAN of the LAN, then a trunk port per machine on several of them.
pub(crate) fn ports(spec: &Spec, name: &str, m: &Machine, address: &impl Fn(&str, u8) -> Ipv4Addr) -> Vec<Port> {
    let Some(lan) = vlans::switched_by(spec, name) else {
        return m
            .networks
            .iter()
            .map(|(net, octet)| Port {
                network: net.clone(),
                address: Some(address(net, *octet)),
                role: Role::Network,
            })
            .collect();
    };
    let mut out: Vec<Port> = vlans::of_lan(spec, lan)
        .map(|(net, id)| Port {
            network: net.clone(),
            address: Some(trunks::switch_address(spec, net)),
            role: Role::Access(id),
        })
        .collect();
    for t in trunks::containers(spec).iter().filter(|t| t.lan == lan) {
        out.push(Port {
            network: trunks::link_network(t),
            address: None,
            role: Role::Trunk(t.machine.clone(), t.vlans.iter().map(|v| v.id).collect()),
        });
    }
    out
}

/// A file Isoloom writes for an appliance, mounted into its container.
pub(crate) struct File {
    /// Its name in the appliance's folder, next to the Compose file.
    pub(crate) name: &'static str,
    /// Its path inside the container.
    pub(crate) inside: &'static str,
    /// What it holds.
    pub(crate) contents: String,
}

/// How an appliance's container is set up.
pub(crate) struct Wiring {
    /// Its data interfaces, in order (`eth1`, `eth2`...).
    pub(crate) ports: Vec<Port>,
    /// The files to mount.
    pub(crate) files: Vec<File>,
    /// Where the machine's own `config` is mounted (read when the container starts).
    pub(crate) own_config: &'static str,
    /// Where the `firmware` file is mounted, for kinds that boot one.
    pub(crate) firmware: Option<&'static str>,
    /// The container's environment variables, in order.
    pub(crate) environment: Vec<(String, String)>,
    /// What the container runs: joins the startup configuration, then starts the OS.
    pub(crate) entrypoint: Vec<String>,
    /// QEMU needs /dev/kvm (and the image sets up its own taps).
    pub(crate) privileged: bool,
    /// The Dockerfile of the container Isoloom builds for the kind, if it builds one.
    pub(crate) build: Option<&'static str>,
}

/// The startup configuration Isoloom writes for an appliance: hostname, credentials, IOL's
/// management interface, a switch's VLANs, each interface (a router's with its address), the
/// management route, remote access.
struct StartupConfig<'a> {
    spec: &'a Spec,
    name: &'a str,
    kind: Appliance,
    ports: &'a [Port],
}

impl StartupConfig<'_> {
    /// Whether the kind is IOL, whose management port lives in a VRF of its own.
    fn iol(&self) -> bool {
        matches!(self.kind, Appliance::CiscoIol | Appliance::CiscoIolL2)
    }

    /// IOL's management interface, `Ethernet0/0`, in the `isoloom-mgmt` VRF.
    fn management(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "no aaa new-model\nip cef\n!\nvrf definition isoloom-mgmt\n description Isoloom management\n address-family ipv4\n exit-address-family\n!\ninterface Ethernet0/0\n{}vrf forwarding isoloom-mgmt\n description Isoloom management\n ip address {} {}\n no shutdown\n!\n",
            if is_switch(self.kind) { " no switchport\n " } else { " " },
            mgmt_address(self.spec, self.name),
            mask(MGMT.len),
        )
    }

    /// A LAN's switch: its VLANs, kept in the configuration (VTP transparent).
    fn vlans(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let access: Vec<(&str, u16)> = self
            .ports
            .iter()
            .filter_map(|p| match p.role {
                Role::Access(id) => Some((p.network.as_str(), id)),
                Role::Network | Role::Trunk(..) => None,
            })
            .collect();
        if access.is_empty() {
            return Ok(());
        }
        f.write_str("vtp mode transparent\n!\n")?;
        for (net, id) in access {
            // IOS takes VLAN names of up to 32 characters.
            write!(f, "vlan {id}\n name {}\n!\n", net.chars().take(32).collect::<String>())?;
        }
        Ok(())
    }

    /// The `k`th data interface (from 1), as its port's role sets it up.
    fn interface(&self, f: &mut fmt::Formatter<'_>, k: usize, port: &Port) -> fmt::Result {
        writeln!(f, "interface {}", interface(self.kind, k))?;
        match &port.role {
            Role::Network => {
                writeln!(f, " description {}", port.network)?;
                // The spec is validated: its blocks parse.
                let block = self.spec.networks.get(&port.network).and_then(|n| Cidr::parse(&n.cidr));
                if let (false, Some(addr), Some(block)) = (is_switch(self.kind), port.address, block) {
                    writeln!(f, " ip address {addr} {}", mask(block.len))?;
                }
            }
            Role::Access(id) => write!(f, " description {}\n switchport mode access\n switchport access vlan {id}\n", port.network)?,
            Role::Trunk(machine, ids) => {
                let ids = ids.iter().map(u16::to_string).collect::<Vec<_>>().join(",");
                write!(
                    f,
                    " description trunk to {machine}\n switchport trunk encapsulation dot1q\n switchport mode trunk\n switchport trunk allowed vlan {ids}\n"
                )?;
            }
        }
        f.write_str(" no shutdown\n!\n")
    }
}

impl fmt::Display for StartupConfig<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "hostname {}\n!\nno ip domain lookup\nip domain name lab\n!\nusername admin privilege 15 secret admin\n!\n",
            self.name
        )?;
        if self.iol() {
            self.management(f)?;
        }
        self.vlans(f)?;
        for (k, port) in self.ports.iter().enumerate() {
            self.interface(f, k + 1, port)?;
        }
        if self.iol() {
            write!(f, "ip route vrf isoloom-mgmt 0.0.0.0 0.0.0.0 Ethernet0/0 {}\n!\n", MGMT.gateway())?;
        }
        f.write_str("ip ssh version 2\n!\nline vty 0 4\n login local\n transport input ssh telnet\n!\n")
    }
}

/// How the container of appliance `name` is wired.
pub(crate) fn wiring(spec: &Spec, name: &str, m: &Machine, kind: Appliance, address: impl Fn(&str, u8) -> Ipv4Addr) -> Wiring {
    let ports = ports(spec, name, m, &address);
    let cfg = StartupConfig {
        spec,
        name,
        kind,
        ports: &ports,
    }
    .to_string();
    match kind {
        Appliance::CiscoIol | Appliance::CiscoIolL2 => iol_wiring(iol_pid(spec, name), ports, cfg),
        Appliance::CiscoVios | Appliance::CiscoViosL2 | Appliance::CiscoCsr1000v | Appliance::CiscoC8000v => vrnetlab_wiring(name, kind, ports, cfg),
        Appliance::CiscoDynamips => dynamips_wiring(ports, cfg),
    }
}

/// IOL: the interfaces mapped by `/iol/NETMAP` and `/iol/iouyap.ini`, the instance in `IOL_PID`.
fn iol_wiring(pid: usize, ports: Vec<Port>, cfg: String) -> Wiring {
    let slots: Vec<(usize, usize, usize)> = (1..=ports.len()).map(|k| (k, k / 4, k % 4)).collect();
    let iouyap: Vec<String> = slots.iter().map(|(k, slot, port)| format!("[513:{slot}/{port}]\neth_dev = eth{k}\n")).collect();
    let netmap: Vec<String> = slots.iter().map(|(_, slot, port)| format!("{pid}:{slot}/{port} 513:{slot}/{port}\n")).collect();
    Wiring {
        ports,
        files: vec![
            File {
                name: "base.txt",
                inside: "/iol/base.txt",
                contents: cfg,
            },
            File {
                name: "NETMAP",
                inside: "/iol/NETMAP",
                contents: format!("{pid}:0/0 513:0/0\n{}", netmap.concat()),
            },
            File {
                name: "iouyap.ini",
                inside: "/iol/iouyap.ini",
                contents: format!(
                    "[default]\nbase_port = 49000\nnetmap = /iol/NETMAP\n[513:0/0]\neth_dev = eth0\n{}",
                    iouyap.concat()
                ),
            },
        ],
        own_config: "/iol/own.txt",
        firmware: None,
        environment: vec![("IOL_PID".into(), pid.to_string())],
        entrypoint: shell("cat /iol/base.txt /iol/own.txt > /iol/config.txt 2>/dev/null; echo end >> /iol/config.txt; exec /entrypoint.sh"),
        privileged: false,
        build: None,
    }
}

/// vrnetlab's QEMU images: `launch.py` with containerlab's arguments, privileged for /dev/kvm.
fn vrnetlab_wiring(name: &str, kind: Appliance, ports: Vec<Port>, cfg: String) -> Wiring {
    let mut environment = vec![("CLAB_INTFS".into(), ports.len().to_string()), ("CONNECTION_MODE".into(), "tc".into())];
    if matches!(kind, Appliance::CiscoVios | Appliance::CiscoViosL2) {
        environment.push(("CLAB_MGMT_PASSTHROUGH".into(), "true".into()));
    }
    Wiring {
        ports,
        files: vec![base_cfg(cfg)],
        own_config: "/config/own.cfg",
        firmware: None,
        environment,
        entrypoint: shell(&format!(
            "cat /config/base.cfg /config/own.cfg > /config/startup-config.cfg 2>/dev/null; echo end >> /config/startup-config.cfg; exec uv run /launch.py --username admin --password admin --hostname {name} --connection-mode tc --trace"
        )),
        privileged: true,
        build: None,
    }
}

/// Dynamips: each data interface bound to a router port, the IOS image booted from `firmware`.
fn dynamips_wiring(ports: Vec<Port>, cfg: String) -> Wiring {
    let n = ports.len();
    // PA-2FE-TX adapters in the slots the data interfaces reach past the I/O card's port.
    let slots = (2..=n).map(|k| dynamips_port(k).0).max().unwrap_or(0);
    let adapters = (1..=slots).map(|slot| format!(" -p {slot}:PA-2FE-TX"));
    let bindings = (1..=n).map(|k| {
        let (slot, port) = dynamips_port(k);
        format!(" -s {slot}:{port}:linux_eth:eth{k}")
    });
    let args: Vec<String> = std::iter::once("-P 7200 -r 512 -T 2000 -C /config/startup-config.cfg".to_owned())
        .chain(adapters)
        .chain(bindings)
        .collect();
    Wiring {
        ports,
        files: vec![base_cfg(cfg)],
        own_config: "/config/own.cfg",
        firmware: Some("/firmware/ios.bin"),
        environment: vec![("DYNAMIPS_ARGS".into(), args.concat())],
        entrypoint: shell(
            "cat /config/base.cfg /config/own.cfg > /config/startup-config.cfg 2>/dev/null; echo end >> /config/startup-config.cfg; cd /tmp && exec dynamips $DYNAMIPS_ARGS /firmware/ios.bin",
        ),
        privileged: false,
        build: Some(DYNAMIPS_DOCKERFILE),
    }
}

/// Isoloom's startup configuration, as `/config/base.cfg` (vrnetlab's and Dynamips' place).
fn base_cfg(cfg: String) -> File {
    File {
        name: "base.cfg",
        inside: "/config/base.cfg",
        contents: cfg,
    }
}

/// `script`, run by `sh -c`.
fn shell(script: &str) -> Vec<String> {
    vec!["/bin/sh".into(), "-c".into(), script.into()]
}

/// What the network sidecar runs: the container lets go of the data addresses on its `ports`
/// data interfaces (IOS owns them).
pub(crate) fn sidecar_commands(ports: usize) -> Vec<String> {
    (1..=ports).map(|k| format!("ip addr flush dev eth{k}")).collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_management_block_is_the_shared_constant() {
        assert_eq!(Cidr::parse(MGMT_CIDR), Some(MGMT));
    }

    #[test]
    fn a_mask_has_its_prefix_length_in_ones() {
        assert_eq!(mask(24), Ipv4Addr::new(255, 255, 255, 0));
        assert_eq!(mask(0), Ipv4Addr::UNSPECIFIED);
        assert_eq!(mask(32), Ipv4Addr::BROADCAST);
    }

    #[test]
    fn interfaces_are_named_as_each_os_names_them() {
        assert_eq!(interface(Appliance::CiscoIol, 5), "Ethernet1/1");
        assert_eq!(interface(Appliance::CiscoVios, 2), "GigabitEthernet0/2");
        assert_eq!(interface(Appliance::CiscoC8000v, 1), "GigabitEthernet2");
        assert_eq!(interface(Appliance::CiscoDynamips, 1), "FastEthernet0/0");
        assert_eq!(interface(Appliance::CiscoDynamips, 3), "FastEthernet1/1");
    }
}