cadet.network¶
Shared description of how one direction of a link perturbs traffic.
Both packet-level backends (netem and netwaggle) need the same numbers
(delay, jitter, loss, bandwidth) for one direction of one link, and both need
the same answer to “what does this distribution mean in the kernel?”. Keeping
that here means the two backends agree on what a link’s network model means
and differ only in where the qdisc is installed.
These are packet-level parameters: they are rendered into tc arguments and
TCLink keywords so they act on packets and the transport reacts to them. The
message-level backend (mode: delay) does not use this object; it samples
its distribution per application message in cadet.core.network.
Two measured facts about netem drive the mapping:
netem’s own jitter is uniform, not Gaussian:
delay 30ms 15msproduces delays spread evenly over 15-45 ms. Its p99 sits atdelay + 0.98 * jitter, and it cannot represent a long tail.netem reorders packets when it jitters them. Each packet is given an independent delay and released when that delay expires, so a packet behind can overtake one in front. Measured on a veth pair with 200 paced datagrams:
delay 30msgave 0 inversions,delay 30ms 15msgave 65. Adding arategave 0 inversions, because netem serialises its output through a rate stage. A jittered link is therefore only installed with arate, and a config that asks for jitter without a bandwidth is refused.
Contains: Z99 (re-exported from cadet.core.network, which
samples the distributions) and percentiles_ms() (p50/p99 of a configured
distribution), Shaping (parameters plus renderers for
Mininet’s TCLink keywords and tc arguments), and shaping_from_network()
(the mapping from a config network block to a Shaping).
Built from config.links[*].network via cadet.network.netwaggle.generator
and cadet.network.netem. Nothing here imports Mininet or runs commands.
- exception cadet.network.shaping.UnrepresentableDelay¶
Bases:
ValueErrorA delay distribution cannot be installed in the kernel as configured.
- cadet.network.shaping.percentiles_ms(dist)¶
Return
(p50_ms, p99_ms)for a configured delay distribution.This is what lets a link report state the intent next to the achieved shaping.
lognormalstates its two percentiles directly, so for that kind this only reads them back.- Return type:
Tuple[float,float]
- class cadet.network.shaping.Shaping(delay_ms=None, jitter_ms=None, loss_pct=None, bandwidth_mbps=None)¶
Bases:
objectHow one direction of a link perturbs traffic.
All fields are optional, and
Nonemeans “not configured”, which is not the same as zero: netem with an explicit 0 ms delay still installs a qdisc and so adds a little latency and reordering risk. An emptyShapingtherefore installs nothing at all.- Parameters:
delay_ms (float | None)
jitter_ms (float | None)
loss_pct (float | None)
bandwidth_mbps (float | None)
- property is_empty: bool¶
True when nothing is configured, so no qdisc need be installed.
- property jitters: bool¶
True when this direction varies its per-packet delay.
- property preserves_order: bool¶
True when this shaping cannot reorder packets within a flow.
Either it does not jitter at all, or it jitters behind a
ratethat serialises netem’s output.shaping_from_network()refuses anything else, so this should hold for every installed link.
- property achieved_percentiles_ms: Tuple[float, float]¶
The
(p50, p99)this shaping will actually produce, in ms.netem’s jitter is uniform, so the p99 is a fixed fraction of the way to
delay + jitterrather than a Gaussian tail.
- as_mininet_params()¶
Return TCLink keyword parameters for this direction.
Mininet wants
delay/jitteras strings with units,lossas a percentage number andbwin Mbit/s. Only configured fields appear.A jittered direction cannot be expressed here in an order-preserving way: TCLink puts its bandwidth stage (htb) before netem, so netem is last in the egress path and its reordering survives. The emulator therefore replaces the qdisc on such an interface after the topology is up, using
netem_args(); seecadet.network.netwaggle.emulator.Emulator().- Return type:
Dict[str,object]
- netem_args()¶
Return the
netemarguments for delay, jitter, loss and rate.Jitter requires a delay:
netem delaytakes the jitter as its second positional value, so a jitter without a delay is rendered against a zero base rather than silently dropped.A
rateis emitted whenever this direction jitters, because that is what keeps netem from reordering the flow (see the module docstring).- Return type:
List[str]
- cadet.network.shaping.shaping_from_network(net)¶
Build a
Shapingfrom a link’snetworkblock.The one place a configured distribution becomes kernel parameters, shared by both packet-level backends so they cannot drift apart.
constantis exact.normalandlognormalare matched on their p50 and p99 onto netem’s uniform jitter, which is the most a single netem can represent; the achieved shape is recorded in the run’s link report so the approximation is visible. Two cases are refused outright rather than approximated into something that measures itself:a spread too wide for a symmetric jitter (
p99 > 2 * p50), which would need negative delays that netem clamps to zero, moving the p50;a jittered link with no
bandwidth_mbps, which netem can only deliver by reordering the flow.
- Return type:
- cadet.network.shaping.shaping_from_path(nets)¶
Build one
Shapingfor a composed path of hopnetworkblocks.A composed route (
routes[*].realise: compose) keeps one end-to-end connection, so there is one sender and therefore one qdisc: the hops have to be collapsed into a single delay, jitter, loss and rate. The composition is stated in percentiles, which is what the mapping already works in:the p50 and the p99 add. Adding the p99s is an upper bound, not a prediction: independent hops’ samples add, but the tail of a sum is narrower than the sum of the tails. It is the conservative direction - the installed spread is at least what the hops ask for - and it is what makes a two-hop path with hops 30 ms +/- a little representable at all.
loss is the chance of not surviving every hop.
bandwidth is the slowest hop’s: hops in series are a pipeline, and the bottleneck sets the rate.
The refusals are then evaluated on the composed shaping, because the composition is what gets installed. That is not the same as checking each hop, and it is worth knowing which way it differs:
the spread rule is linear, so hops that are each representable always compose into a representable path (each hop’s jitter is at most its own delay, so the sums keep that relation). Composing cannot turn acceptable hops into a refusal.
the bandwidth rule is weaker on a path than on a hop. A jittered hop with no bandwidth of its own is refused as a link, because netem would reorder its flow; in a composed path it is accepted when any hop sets a bandwidth, because there is one qdisc and that rate serialises the whole path’s output. The reordering the rule exists to prevent cannot happen.
- Return type:
- cadet.network.shaping.shaping_from_percentiles(p50_ms, p99_ms, loss_fraction=0.0, bandwidth_mbps=None, subject='link')¶
Map a
(p50, p99)intent onto netem, or refuse it.One link and a composed path differ only in how their percentiles were arrived at, so both are checked here and
subjectonly names which one a refusal is talking about.- Return type:
- Parameters:
p50_ms (float)
p99_ms (float)
loss_fraction (float)
bandwidth_mbps (float | None)
subject (str)
netem backend: shape a link’s traffic with tc inside the sending node.
- What this is for:
Implements
links[*].network.mode: netem. Where thenetwagglebackend builds a whole emulated network, this one changes nothing about the topology: it installs atcqueueing discipline on the sending node’s own interface and filters it to the link peer’s address and port, so only that flow is delayed, dropped and rate-limited. Everything else on the same interface (channels, the simulator connection, log shipping) stays in the unshaped default class.That is what makes this the simple option: no namespaces, no switches, no privileged emulation container. A node’s container needs only NET_ADMIN.
This is packet-level emulation. The qdisc holds packets, so the configured delay applies to every packet leaving the sender on this flow (data, the handshake and ACKs alike), and
lossdrops packets that TCP retransmits rather than application messages. A request/response workload therefore pays the configured delay more than once unless Nagle is disabled (nodes.*.transport_tuning.tcp_nodelay), and configured loss shows up as p99 latency rather than as unanswered messages. That is the transport reacting to the link, which is the point of emulating at this layer; the message-level alternative ismode: delay. See “Link backend semantics” indocs/config-reference.md.- What it contains:
ShapeRule: one flow to shape (peer address, which port to match, and theShapingto apply).rules_for_node(): the rules a given node must install, derived from the config’s links and routes and that node’s direction of each. A composed route is one rule on the node at the start of the path, carrying the hops’ composed shaping and matching the far end: the connection is end to end, so no packet of it ever leaves a waypoint.build_commands()/teardown_commands(): thetccommand lines, as argv lists.NetemBackend: applies and removes them through a caller-supplied runner, so the same code works locally or overdocker exec.local_runner(),interface_for()andsessions_for_config(): the glue the orchestrator uses to install the rules in the right place.
Nothing here executes a command on import, and no function runs
tcitself: a backend returns argv and the orchestrator’s launcher runs it in the right place. That keeps the whole mapping testable without root.- How it fits into CADET:
The orchestrator asks
rules_for_node()what each node needs, then usesNetemBackendto apply before the role starts and remove on teardown. Ordering matters: apply before traffic flows, remove even when the run fails, which is why teardown is a single idempotent qdisc delete.- How to configure it:
Per link via
links[*].networkwithmode: netem. Delay, jitter and loss come from the distribution andloss;bandwidth_mbpsbecomes the shaped class’s rate.
- cadet.network.netem.ifb_name(interface)¶
Return the intermediate device that carries
interface’s ingress.An interface’s ingress cannot hold a shaping tree directly - the qdisc there classifies and redirects, it does not queue - so the tree lives on an intermediate functional block device and the ingress hook mirrors traffic to it. The name is derived from the interface so it is the same on every call and distinct per interface, and kept inside the kernel’s 15-character limit.
- Return type:
str- Parameters:
interface (str)
- class cadet.network.netem.ShapeRule(link_name, peer_ip, port, shaping, match='dport', hook='egress')¶
Bases:
objectOne flow to shape on a node’s interface.
matchsays which port identifies the flow:"dport"the peer’s listening port. Used by the side that initiates; a client’s requests go to
server:port."sport"the local listening port. Used by the listener for its replies, which leave from
server:porttowards an ephemeral client port, so the destination port cannot identify them.
hooksays which direction of the interface the rule shapes."egress"matches the address as the destination, which is what a node sending to a peer needs."ingress"matches it as the source, for a direction whose sender runs on another machine: that sender’s own interface is that machine’s, and shaping it would shape everything else on it, so the receiver shapes what arrives from that address instead. Per-direction latency, loss and rate are what the link states either way.- Parameters:
link_name (str)
peer_ip (str)
port (int)
shaping (Shaping)
match (str)
hook (str)
- cadet.network.netem.rules_for_node(config, node_name, offmachine=())¶
Return the shaping rules
node_namemust install on its interface.A link’s
directiondecides which side shapes.forwardshapes the request path, so the rule belongs on thefromnode and matches the peer’s listening port.reverseshapes replies, so it belongs on thetonode and matches its own listening port as the source.bothinstalls a rule on each side.offmachinenames the nodes whose own interface is another machine’s. A direction whose sender is one of them cannot be shaped where it is sent: that interface carries everything else on that machine. Such a direction is shaped where it arrives instead - an ingress rule on the node at the other end, matching the sender’s address as the source - so every qdisc stays on an interface this orchestrator owns. The flow matched is the same flow, and the link’s latency, loss and rate are what the configuration states.Nodes named only by
channelsget no rules at all, which is how channel traffic stays unshaped: there is nothing to match it.- Return type:
List[ShapeRule]- Parameters:
node_name (str)
- cadet.network.netem.egress_rules(rules)¶
The rules shaping what the node sends.
- cadet.network.netem.ingress_rules(rules)¶
The rules shaping what arrives from a sender on another machine.
- cadet.network.netem.ingress_commands(interface, rules)¶
Return the commands shaping what arrives on
interface.An interface’s ingress hook classifies and redirects; it cannot queue, so the shaping tree lives on an intermediate functional block device and every arriving packet is mirrored to it. The tree there is the same htb root, wide default class and netem leaf per rule that egress uses - what differs is only that a rule matches its peer as the source, because these packets are arriving from it.
The device is created here rather than assumed: it lives in the namespace of the node’s own container, so it appears with the container and goes with it. Returns an empty list when there is nothing to install.
- Return type:
List[List[str]]- Parameters:
interface (str)
rules (List[ShapeRule])
- cadet.network.netem.build_commands(interface, rules)¶
Return the
tccommands installingrulesoninterface.The tree is an htb root whose default class is effectively unlimited, plus one shaped class per rule with a netem leaf. Unmatched traffic lands in the default class and is untouched, so channels sharing the interface are not shaped. Returns an empty list when there is nothing to install.
Egress rules only: what arrives from a sender on another machine is shaped by
ingress_commands(), which puts the same tree on an intermediate device.- Return type:
List[List[str]]- Parameters:
interface (str)
rules (List[ShapeRule])
- cadet.network.netem.teardown_commands(interface, ingress=False)¶
Return the commands removing everything this backend installed.
Deleting a root qdisc takes the classes, leaf qdiscs and filters with it.
--forceis not used; instead each delete tolerates its object being absent, so teardown is idempotent and safe to run after a failed apply.ingressadds the removal of the ingress hook and its intermediate device, in that order, because the device cannot go while traffic is still redirected to it. Asked for rather than always emitted, so a node that shaped only what it sends tears down exactly what it built.- Return type:
List[List[str]]- Parameters:
interface (str)
ingress (bool)
- class cadet.network.netem.NetemBackend(interface, rules, runner)¶
Bases:
objectApplies and removes netem shaping through a caller-supplied runner.
runnertakes an argv list and returns(returncode, output). The orchestrator supplies one that runs locally or inside the node’s container, so this class never decides where a command executes.- Parameters:
interface (str)
rules (List[ShapeRule])
runner (Callable[[List[str]], object])
- apply()¶
Install the qdisc tree. Returns the commands run, for the run record.
Any failure removes what was already installed, so a partially built tree never shapes traffic in a way the config did not ask for.
- Return type:
List[str]
- remove()¶
Remove the qdisc tree; tolerates it being absent already.
- Return type:
None
- cadet.network.netem.local_runner(argv)¶
Run a tc command on this machine. The default runner for local runs.
- Return type:
Tuple[int,str]- Parameters:
argv (List[str])
- cadet.network.netem.interface_for(ip, runner=None)¶
Return the interface the kernel would use to reach
ip.Asks the routing table rather than guessing, because the answer differs by deployment: a local run between two processes on one machine leaves by the loopback, while a containerised node leaves by its bridge interface. Falls back to
lowhen the lookup cannot be parsed, since that is the only sensible default for an address on this host.- Return type:
str- Parameters:
ip (str)
runner (Callable[[List[str]], object] | None)
- cadet.network.netem.sessions_for_config(config, node_names=None, runner=None, interface_resolver=None, offmachine=())¶
Build one
NetemBackendper (node, interface) the config needs.Rules are grouped by the interface that reaches their peer, because a node may hold links whose peers are reached by different interfaces and each interface carries its own qdisc tree. Returns an empty list when no link uses
mode: netem, so the caller can treat it as “nothing to do”.offmachinenames the nodes running on another machine; a direction they send is shaped where it arrives. Seerules_for_node().- Return type:
List[NetemBackend]- Parameters:
node_names (List[str] | None)
runner (Callable[[List[str]], object] | None)
interface_resolver (Callable[[str], str] | None)
- cadet.network.netem.apply_sessions(sessions)¶
Apply every session, rolling back all of them if any one fails.
Partial shaping is worse than none: it would quietly measure a different experiment from the configured one. On failure every session already applied is removed before the error propagates.
- Return type:
List[str]- Parameters:
sessions (List[NetemBackend])
- cadet.network.netem.remove_sessions(sessions)¶
Remove every session; tolerates sessions that were never applied.
- Return type:
None- Parameters:
sessions (List[NetemBackend])
Per-node transport tuning, applied only inside that node’s own namespace.
- What this is for:
Packet-level emulation includes the transport’s reaction to a link, and for a request/response workload of small messages that reaction is substantial: on a 60 ms forward-shaped link, the same traffic measured 141 ms with kernel defaults and 110 ms with Nagle disabled. Those are properties of the TCP stack, not of the emulated link, so they belong in the config as explicit per-node knobs rather than being silently inherited or silently changed.
Defaults are deliberately the kernel’s. CADET does not pick a TCP policy on the experimenter’s behalf; it makes the policy visible and selectable, and records it in the run.
- What it contains:
SYSCTL_KEYS: which tunables are sysctls (and so need a namespace).socket_options(): the setsockopt triples for a node.apply_socket_options(): apply them to a socket.sysctl_settings()/route_settings(): namespace-scoped settings, as(key, value)pairs and as argv.namespace_commands(): the commands to run inside a node’s namespace.docker_sysctl_args(): the same settings asdocker runflags.requires_namespace(): whether a node’s tuning needs one, used to refuse a setting that would otherwise leak to the host.
- How it fits into CADET:
nodes[*].transport_tuningfeeds this module.cadet.core.transportapplies the socket options when it creates a socket;Emulatorrunsnamespace_commands()inside each emulated host;DockerLauncherpassesdocker_sysctl_args()todocker run. The orchestrator’s preflight refuses a sysctl or route setting for a node whose launcher islocal, because there is no namespace there and the change would be host-wide.Nothing here ever writes a host-wide setting. The sysctls involved are per-network-namespace, which was verified on this platform: setting
tcp_slow_start_after_idleinside a container (whether bydocker --sysctlat creation or bysysctl -win a privileged container with its own namespace) leaves the host’s value unchanged.- How to configure it:
Per node:
nodes: - name: client transport_tuning: tcp_nodelay: true # socket option, no namespace needed tcp_slow_start_after_idle: false # sysctl, needs a namespace initcwnd: 20 # route attribute, needs a namespace
- cadet.network.tuning.socket_options(node)¶
Return
(level, option, value)triples for this node’s sockets.Only
tcp_nodelayis a socket option; it needs no namespace and no privilege, which is why it is the one knob that works under every launcher. An unset field yields nothing, so the kernel default stands.- Return type:
List[Tuple[int,int,int]]
- cadet.network.tuning.apply_socket_options(sock, node)¶
Apply this node’s socket options to
sock; return what was applied.Failures are swallowed deliberately: a platform that rejects an option should not fail the run, and the returned list records what actually took effect so the run report cannot overstate it.
- Return type:
List[str]
- cadet.network.tuning.sysctl_settings(node)¶
Return the
{sysctl key: value}this node asks for.- Return type:
Dict[str,str]
- cadet.network.tuning.route_settings(node)¶
Return the requested
initcwnd, or None.initcwnd is an attribute of a route, not a socket or a sysctl, so it is applied by rewriting the route inside the node’s namespace.
- Return type:
Optional[int]
- cadet.network.tuning.requires_namespace(node)¶
True when this node’s tuning can only be applied inside a namespace.
tcp_nodelayalone does not require one. Anything else does, and applying it without one would change the host.- Return type:
bool
- cadet.network.tuning.namespace_commands(node, routes=None)¶
Return the commands to run inside this node’s namespace.
routesmatters only forinitcwnd, which is an attribute of a route and so must name one. Each entry is(destination, interface); the netwaggle backend gives a host one /32 route per link peer, so there is normally one entry per peer. With no routes supplied the setting is skipped rather than guessed at, because rewriting the wrong route would change traffic the config never mentioned — the bypass default route in particular must stay at the kernel default, like the rest of the plumbing.- Return type:
List[List[str]]- Parameters:
routes (List[Tuple[str, str]] | None)
- cadet.network.tuning.docker_sysctl_args(node)¶
Return
--sysctl k=vflags fordocker run.Docker applies these at container creation, inside the container’s own network namespace, which is why this is the right mechanism for a containerised node: an unprivileged container has a read-only
/proc/sysand could not set them afterwards.- Return type:
List[str]
- cadet.network.tuning.describe(node)¶
Return this node’s effective tuning, for the run record.
Fields the config left unset are reported as
Nonerather than as the kernel’s value: CADET does not know the kernel default and should not claim one.- Return type:
Dict[str,object]