@mark1russell7/harness 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -23,6 +23,9 @@
23
23
  //! `netem eth0 delay 100ms 10ms` or `netem eth0 loss 5%`.
24
24
  //! - `offload DEV on|off`: the device's TSO, GSO and GRO, so that netem and length matches act on
25
25
  //! segments rather than on GSO super-packets of up to 64 KB.
26
+ //! - `http METHOD ADDR:PORT PATH [BODY]`: one HTTP/1.1 request to an API in the VM, for example a
27
+ //! toxic of Toxiproxy. The stamps bracket the request and its answer, after the connect, so the
28
+ //! commit of the toxic is known on the same clock as the kernel's records.
26
29
  //!
27
30
  //! `--at NS` holds the commit until that instant on CLOCK_MONOTONIC, the clock every stamp is on.
28
31
  //! A stall's end is timed that way, from inside the VM: the exec only has to arrive before it, and
@@ -165,9 +168,63 @@ fn command(program: &str, args: &[&str]) -> Result<(), Box<dyn Error>> {
165
168
  Ok(())
166
169
  }
167
170
 
171
+ /// an HTTP path: a slash, then letters, digits and `/ - _ .` only
172
+ fn http_path(path: &str) -> Result<&str, Box<dyn Error>> {
173
+ if path.starts_with('/')
174
+ && path.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '-' | '_' | '.'))
175
+ {
176
+ Ok(path)
177
+ } else {
178
+ Err(format!("not an HTTP path: {path}").into())
179
+ }
180
+ }
181
+
182
+ /// the head of one HTTP/1.1 request, with its body
183
+ fn http_request(method: &str, host: &str, path: &str, body: &str) -> Result<String, Box<dyn Error>> {
184
+ if !matches!(method, "GET" | "POST" | "DELETE") {
185
+ return Err(format!("not a method: {method}").into());
186
+ }
187
+ Ok(format!(
188
+ "{method} {path} HTTP/1.1\r\nHost: {host}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
189
+ body.len()
190
+ ))
191
+ }
192
+
193
+ /// one request to an API: the status, and the stamps around the request and its answer
194
+ fn http(args: &[String]) -> Result<(), Box<dyn Error>> {
195
+ use std::io::Read;
196
+ use std::net::{SocketAddrV4, TcpStream};
197
+ let method = args.get(1).ok_or("http METHOD ADDR:PORT PATH [BODY]")?.as_str();
198
+ let addr: SocketAddrV4 = args.get(2).ok_or("and the address and port")?.parse()?;
199
+ let path = http_path(args.get(3).ok_or("and the path")?)?;
200
+ let body = args.get(4).map_or("", String::as_str);
201
+ let request = http_request(method, &addr.to_string(), path, body)?;
202
+ let mut stream = TcpStream::connect(addr)?;
203
+ let t0 = monotonic_ns();
204
+ stream.write_all(request.as_bytes())?;
205
+ let mut answer = Vec::new();
206
+ stream.read_to_end(&mut answer)?;
207
+ let t1 = monotonic_ns();
208
+ let text = String::from_utf8_lossy(&answer);
209
+ let status: u16 = text
210
+ .split_whitespace()
211
+ .nth(1)
212
+ .ok_or("no status in the answer")?
213
+ .parse()?;
214
+ if !(200..300).contains(&status) {
215
+ let detail = text.split("\r\n\r\n").nth(1).unwrap_or("").trim();
216
+ return Err(format!("{method} {path} answered {status}: {detail}").into());
217
+ }
218
+ println!("{}", json!({ "action": "http", "method": method, "path": path, "status": status, "t0": t0, "t1": t1 }));
219
+ Ok(())
220
+ }
221
+
168
222
  fn run() -> Result<(), Box<dyn Error>> {
169
223
  let args: Vec<String> = std::env::args().skip(1).collect();
170
- let action = args.first().ok_or("say an action: blackhole, clear, rst, reject, mtu, netem, offload …")?.as_str();
224
+ let action = args.first().ok_or("say an action: blackhole, clear, rst, reject, mtu, netem, offload, http …")?.as_str();
225
+ if action == "http" {
226
+ return http(&args);
227
+ }
171
228
  match action {
172
229
  "netem" | "clear-netem" | "offload" => {
173
230
  let dev = device(args.get(1).ok_or("and a device")?)?;
@@ -265,4 +322,17 @@ mod tests {
265
322
  );
266
323
  assert!(rules("reject", peer, &Options::default()).is_err());
267
324
  }
325
+
326
+ #[test]
327
+ fn http_requests_take_only_a_method_a_path_and_a_length() {
328
+ assert!(http_path("/proxies/redis/toxics").is_ok());
329
+ for path in ["proxies", "/a b", "/a;b", "/a?b=1", "/$(x)"] {
330
+ assert!(http_path(path).is_err(), "{path}");
331
+ }
332
+ let request = http_request("POST", "10.0.0.3:8474", "/proxies/redis/toxics", "{}").unwrap();
333
+ assert!(request.starts_with("POST /proxies/redis/toxics HTTP/1.1\r\n"));
334
+ assert!(request.contains("Content-Length: 2\r\n"));
335
+ assert!(request.ends_with("\r\n\r\n{}"));
336
+ assert!(http_request("PUT", "h", "/", "").is_err());
337
+ }
268
338
  }
@@ -0,0 +1,8 @@
1
+ # The router of the harness: a NAT box with conntrack, the middle of a stateful middlebox chain. It
2
+ # forgets an idle flow at its idle timeout, and its form tells what a late packet then meets (mbx.sh).
3
+ # lab.ts stages the build context: this folder, under harness/image/router. The base is pinned by
4
+ # digest, and the manifest of each run records the packages that apk installs.
5
+ FROM alpine:3.23@sha256:865b95f46d98cf867a156fe4a135ad3fe50d2056aa3f25ed31662dff6da4eb62
6
+ RUN apk add --no-cache conntrack-tools nftables iproute2 python3
7
+ COPY harness/image/router/mbx.sh harness/image/router/ctwatch.py harness/image/router/resetter.py /opt/mbx/
8
+ ENTRYPOINT ["/bin/sh", "/opt/mbx/mbx.sh"]
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env python3
2
+ """The conntrack events of the router, as JSON lines on the monotonic clock.
3
+
4
+ Each line is {"ev": "ct", "t": <CLOCK_MONOTONIC ns>, "type": "NEW|UPDATE|DESTROY", "state": ...,
5
+ "orig": "src:sport>dst:dport", "reply": "..."}. The stamp is the time that this process read the
6
+ event, which is within a millisecond of the kernel. A listing every PUMP seconds evicts the expired
7
+ entries that it walks past, thus a DESTROY follows an expiry within PUMP plus two listings. A
8
+ listing that takes longer than SLOW seconds writes a "pump-slow" line with its start and its
9
+ length: near it, that bound of the lag does not hold.
10
+
11
+ ctwatch.py [--pump SECONDS] [--slow SECONDS]
12
+ """
13
+ import argparse, json, re, subprocess, sys, threading, time
14
+
15
+ p = argparse.ArgumentParser()
16
+ p.add_argument("--pump", type=float, default=0.1)
17
+ p.add_argument("--slow", type=float, default=0.02)
18
+ a = p.parse_args()
19
+
20
+ PAT = re.compile(
21
+ r"\[(?P<type>NEW|UPDATE|DESTROY)\]\s+tcp\s+\d+\s+(?:\d+\s+)?(?P<state>[A-Z_]+)?\s*"
22
+ r"src=(?P<s>\S+) dst=(?P<d>\S+) sport=(?P<sp>\d+) dport=(?P<dp>\d+).*?"
23
+ r"src=(?P<rs>\S+) dst=(?P<rd>\S+) sport=(?P<rsp>\d+) dport=(?P<rdp>\d+)"
24
+ )
25
+ lock = threading.Lock()
26
+
27
+
28
+ def now():
29
+ return time.clock_gettime_ns(time.CLOCK_MONOTONIC)
30
+
31
+
32
+ def emit(**fields):
33
+ with lock:
34
+ print(json.dumps({"t": now(), **fields}), flush=True)
35
+
36
+
37
+ def pump():
38
+ while True:
39
+ start = now()
40
+ subprocess.run(["conntrack", "-L", "-p", "tcp"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
41
+ took = (now() - start) / 1e9
42
+ if took > a.slow:
43
+ with lock:
44
+ print(json.dumps({"ev": "pump-slow", "t": start, "took": took}), flush=True)
45
+ time.sleep(a.pump)
46
+
47
+
48
+ if a.pump > 0:
49
+ threading.Thread(target=pump, daemon=True).start()
50
+ proc = subprocess.Popen(
51
+ ["conntrack", "-E", "-p", "tcp"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1
52
+ )
53
+ emit(ev="ct-watch", pump=a.pump, slow=a.slow)
54
+ for line in proc.stdout:
55
+ m = PAT.search(line)
56
+ if m is None:
57
+ emit(ev="ct-unparsed", line=line.strip())
58
+ continue
59
+ emit(
60
+ ev="ct",
61
+ type=m["type"],
62
+ state=m["state"],
63
+ orig=f'{m["s"]}:{m["sp"]}>{m["d"]}:{m["dp"]}',
64
+ reply=f'{m["rs"]}:{m["rsp"]}>{m["rd"]}:{m["rdp"]}',
65
+ )
66
+ sys.exit(proc.wait())
@@ -0,0 +1,61 @@
1
+ #!/bin/sh
2
+ # The router of a middlebox chain: one image for the forms of a middlebox at its idle expiry.
3
+ #
4
+ # FORM=reset-both|reset-next|silent-drop|recreate|none IDLE=<seconds> [LAN=eth0] [WAN=eth1] [PUMP=0.1] [SLOW=0.02]
5
+ #
6
+ # The container is privileged, so it sets the sysctls of its own namespace. Docker Desktop keeps
7
+ # /proc/sys read-only in a container that is not. The network of the side of the client is LAN,
8
+ # and the harness connects the network of the side of the target (WAN) after the start.
9
+ #
10
+ # FORM at the expiry a late packet from inside a late packet from outside
11
+ # reset-both a reset to the two ends dropped dropped
12
+ # reset-next nothing a reset to its sender dropped
13
+ # silent-drop nothing dropped dropped
14
+ # recreate nothing passes, and starts the flow dropped
15
+ # none nothing passes (a plain NAT router) a reset from the router
16
+ #
17
+ # A lookup treats an expired entry as gone, so the router forgets a flow at its timeout to the
18
+ # jiffy. The DESTROY event of conntrack waits for the garbage collector or a lookup: ctwatch.py
19
+ # lists the table every PUMP seconds, so the event follows the expiry within PUMP and two listings.
20
+ # A listing longer than SLOW seconds writes a pump-slow line: near it, that bound does not hold.
21
+ set -eu
22
+ FORM=${FORM:-none}; LAN=${LAN:-eth0}; WAN=${WAN:-eth1}; PUMP=${PUMP:-0.1}; SLOW=${SLOW:-0.02}; IDLE=${IDLE:-432000}
23
+ sysctl -q -w net.ipv4.ip_forward=1
24
+ # the conntrack sysctls of a namespace appear when it first uses conntrack: a listing does that
25
+ conntrack -L >/dev/null 2>&1 || true
26
+ sysctl -q -w net.netfilter.nf_conntrack_events=1
27
+ sysctl -q -w "net.netfilter.nf_conntrack_tcp_timeout_established=$IDLE"
28
+ i=0
29
+ while ! ip link show "$WAN" >/dev/null 2>&1; do
30
+ i=$((i + 1)); [ "$i" -gt 600 ] && { echo "mbx: no $WAN" >&2; exit 65; }; sleep 0.1
31
+ done
32
+ case $FORM in
33
+ reset-both) INSIDE=drop; OUTSIDE=drop ;;
34
+ reset-next) INSIDE=rst; OUTSIDE=drop ;;
35
+ silent-drop) INSIDE=drop; OUTSIDE=drop ;;
36
+ recreate) INSIDE=pass; OUTSIDE=drop ;;
37
+ none) INSIDE=pass; OUTSIDE=rst ;;
38
+ *) echo "mbx: unknown FORM=$FORM" >&2; exit 64 ;;
39
+ esac
40
+ verdict() { case $1 in rst) echo "reject with tcp reset" ;; drop) echo drop ;; *) echo accept ;; esac; }
41
+ # OUTSIDE=rst: accept, and the stack of the router answers the unknown port with an exact reset
42
+ outv=$(verdict "$OUTSIDE"); [ "$OUTSIDE" = rst ] && outv=accept
43
+ nft -f - <<EOF
44
+ table ip mbx {
45
+ chain mbx_post { type nat hook postrouting priority srcnat; policy accept; oifname "$WAN" masquerade; }
46
+ chain mbx_fwd {
47
+ type filter hook forward priority filter; policy accept;
48
+ iifname "$LAN" meta l4proto tcp ct state new,invalid tcp flags & (syn|ack) != syn counter $(verdict "$INSIDE")
49
+ }
50
+ chain mbx_in {
51
+ type filter hook input priority filter; policy accept;
52
+ iifname "$WAN" meta l4proto tcp ct state new,invalid tcp flags & (syn|ack) != syn counter $outv
53
+ }
54
+ }
55
+ EOF
56
+ echo "{\"ev\":\"mbx-ready\",\"t\":0,\"form\":\"$FORM\",\"idle\":$(cat /proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established),\"inside\":\"$INSIDE\",\"outside\":\"$OUTSIDE\"}"
57
+ if [ "$FORM" = reset-both ]; then
58
+ python3 /opt/mbx/ctwatch.py --pump "$PUMP" --slow "$SLOW" &
59
+ exec python3 /opt/mbx/resetter.py "$LAN" "$WAN"
60
+ fi
61
+ exec python3 /opt/mbx/ctwatch.py --pump "$PUMP" --slow "$SLOW"
@@ -0,0 +1,104 @@
1
+ #!/usr/bin/env python3
2
+ """The reset at expiry: the form of a middlebox that resets the two ends when it forgets a flow.
3
+
4
+ It listens to the DESTROY events of conntrack in this namespace. For each destroyed TCP flow that
5
+ it saw carry traffic, and never saw closed (FIN or RST), it sends a reset to each end. Each reset
6
+ has the sequence number that its end expects: the last acknowledgment number that the end sent,
7
+ read by a raw sniffer on the interfaces, because conntrack events carry no sequence numbers.
8
+ Each line is JSON on the monotonic clock: {"ev": "reset", "t": ..., "flow": ..., "to": [...]}.
9
+
10
+ resetter.py IFACE [IFACE...]
11
+ """
12
+ import argparse, json, re, socket, struct, subprocess, threading, time
13
+
14
+ p = argparse.ArgumentParser()
15
+ p.add_argument("ifaces", nargs="+")
16
+ a = p.parse_args()
17
+
18
+ plock = threading.Lock()
19
+ flock = threading.Lock()
20
+ flows = {} # (src, sport, dst, dport) -> {"ack", "closed"}
21
+
22
+
23
+ def emit(**fields):
24
+ with plock:
25
+ print(json.dumps({"t": time.clock_gettime_ns(time.CLOCK_MONOTONIC), **fields}), flush=True)
26
+
27
+
28
+ def sniff(ifname):
29
+ s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0800))
30
+ s.bind((ifname, 0))
31
+ while True:
32
+ pkt = s.recv(65535)
33
+ ip = pkt[14:]
34
+ if len(ip) < 40 or ip[0] >> 4 != 4 or ip[9] != 6:
35
+ continue
36
+ ihl = (ip[0] & 0xF) * 4
37
+ src, dst = socket.inet_ntoa(ip[12:16]), socket.inet_ntoa(ip[16:20])
38
+ tcp = ip[ihl:]
39
+ sport, dport, _seq, ack = struct.unpack("!HHII", tcp[:12])
40
+ fl = tcp[13]
41
+ with flock:
42
+ f = flows.setdefault((src, sport, dst, dport), {"ack": None, "closed": False})
43
+ if fl & 0x10:
44
+ f["ack"] = ack
45
+ if fl & 0x05:
46
+ f["closed"] = True
47
+
48
+
49
+ raw = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
50
+
51
+
52
+ def csum(b):
53
+ if len(b) % 2:
54
+ b += b"\0"
55
+ s = sum(struct.unpack("!%dH" % (len(b) // 2), b))
56
+ while s >> 16:
57
+ s = (s & 0xFFFF) + (s >> 16)
58
+ return ~s & 0xFFFF
59
+
60
+
61
+ def send_rst(src, sport, dst, dport, seq):
62
+ tcp = struct.pack("!HHIIBBHHH", sport, dport, seq, 0, 5 << 4, 0x04, 0, 0, 0)
63
+ pseudo = socket.inet_aton(src) + socket.inet_aton(dst) + struct.pack("!BBH", 0, 6, len(tcp))
64
+ tcp = tcp[:16] + struct.pack("!H", csum(pseudo + tcp)) + tcp[18:]
65
+ iph = struct.pack(
66
+ "!BBHHHBBH4s4s", 0x45, 0, 20 + len(tcp), 0, 0x4000, 64, 6, 0, socket.inet_aton(src), socket.inet_aton(dst)
67
+ )
68
+ raw.sendto(iph + tcp, (dst, 0))
69
+
70
+
71
+ PAT = re.compile(r"src=(\S+) dst=(\S+) sport=(\d+) dport=(\d+) .*?src=(\S+) dst=(\S+) sport=(\d+) dport=(\d+)")
72
+
73
+
74
+ def main():
75
+ for i in a.ifaces:
76
+ threading.Thread(target=sniff, args=(i,), daemon=True).start()
77
+ proc = subprocess.Popen(
78
+ ["conntrack", "-E", "-e", "DESTROY", "-p", "tcp"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1
79
+ )
80
+ emit(ev="resetter", ifaces=a.ifaces)
81
+ for line in proc.stdout:
82
+ m = PAT.search(line)
83
+ if not m:
84
+ continue
85
+ c, s, cp, sp, s2, r, sp2, rp = m.groups()
86
+ cp, sp, sp2, rp = int(cp), int(sp), int(sp2), int(rp)
87
+ k_cs, k_sr = (c, cp, s, sp), (s2, sp2, r, rp)
88
+ with flock:
89
+ fs = {k: dict(flows[k]) for k in (k_cs, (s, sp, c, cp), (r, rp, s2, sp2), k_sr) if k in flows}
90
+ if not fs or any(f["closed"] for f in fs.values()):
91
+ continue
92
+ seq_c = fs.get(k_cs, {}).get("ack") # the RCV.NXT of the client
93
+ seq_s = fs.get(k_sr, {}).get("ack") # the RCV.NXT of the server, on the translated side
94
+ sent = []
95
+ if seq_c is not None:
96
+ send_rst(s, sp, c, cp, seq_c)
97
+ sent.append("client")
98
+ if seq_s is not None:
99
+ send_rst(r, rp, s2, sp2, seq_s)
100
+ sent.append("server")
101
+ emit(ev="reset", flow=f"{c}:{cp}>{s}:{sp}", nat=f"{r}:{rp}", to=sent)
102
+
103
+
104
+ main()
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/harness",
4
- "version": "0.2.0",
5
- "description": "A fault-injection harness for connection timers: a cell runs a client against a stock target in Docker, injects a fault, measures the kernel's own records and judges a prediction.",
4
+ "version": "0.3.0",
5
+ "description": "A fault-injection harness for connection timers: a cell runs a client against a stock target in Docker, through a topology of routers and proxies, injects a fault, measures the kernel's own records and judges a prediction.",
6
6
  "keywords": [
7
7
  "fault-injection",
8
8
  "chaos-engineering",
@@ -45,6 +45,10 @@
45
45
  "image/node/client-ioredis.mjs",
46
46
  "image/node/package.json",
47
47
  "image/node/npm-lock.json",
48
+ "image/router/Dockerfile",
49
+ "image/router/mbx.sh",
50
+ "image/router/ctwatch.py",
51
+ "image/router/resetter.py",
48
52
  "README.md",
49
53
  "LICENSE"
50
54
  ],