@mark1russell7/harness 0.16.6 → 0.16.8

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.
package/build/schema.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { M as ImageSource, Rt as Subject, i as Client, o as ClientImage } from "./cell-FMlgjqVq.js";
1
+ import { F as ImageSource, Vt as Subject, i as Client, o as ClientImage } from "./cell-CYOKWfwg.js";
2
2
  import { z } from "zod";
3
3
  /**
4
4
  * This schema accepts the source of an image (`ImageSource`). It is a pinned image with its digest,
package/image/Dockerfile CHANGED
@@ -26,6 +26,6 @@ FROM alpine:3.23@sha256:865b95f46d98cf867a156fe4a135ad3fe50d2056aa3f25ed31662dff
26
26
  # tc for netem, ethtool for the offloads that decide whether netem acts on segments
27
27
  RUN apk add --no-cache iproute2 iproute2-tc iptables ethtool libelf zlib zstd-libs libgcc
28
28
  COPY --from=build /src/prober.bpf.o /src/prober/native/target/release/prober /opt/harness/
29
- COPY --from=build /src/harness/image/native/target/release/client /src/harness/image/native/target/release/inject /src/harness/image/native/target/release/queue /src/harness/image/native/target/release/ports /src/harness/image/native/target/release/ctfull /src/harness/image/native/target/release/load /src/harness/image/native/target/release/memory /opt/harness/
29
+ COPY --from=build /src/harness/image/native/target/release/client /src/harness/image/native/target/release/inject /src/harness/image/native/target/release/queue /src/harness/image/native/target/release/ports /src/harness/image/native/target/release/ctfull /src/harness/image/native/target/release/load /src/harness/image/native/target/release/memory /src/harness/image/native/target/release/egress /opt/harness/
30
30
  WORKDIR /opt/harness
31
31
  CMD ["sleep", "infinity"]
@@ -0,0 +1,540 @@
1
+ //! egress sink PORT
2
+ //! egress send --qdisc WORDS --burst AT_MS:COUNT:PAYLOAD [--burst ...] [--settle-ms N] [--wait-s N] HOST PORT [--mode M] [--max-s N]
3
+ //!
4
+ //! This program is the client of the egress cells, and the sink of their target. Each line is JSON
5
+ //! with an `ev` and a `t` on CLOCK_MONOTONIC.
6
+ //!
7
+ //! `sink` binds a UDP port and discards each datagram. Without a listener, the target answers a
8
+ //! datagram with an ICMP port unreachable, and IP_RECVERR makes it the error of a later send.
9
+ //!
10
+ //! `send` puts the qdisc of `--qdisc` (the words of `tc`) at the root of eth0, and sends bursts of
11
+ //! UDP datagrams through it to the sink. The steps:
12
+ //!
13
+ //! 1. One datagram before the qdisc resolves the address of the target. The program then makes that
14
+ //! neighbour permanent, thus no ARP packet goes through the qdisc during the bursts.
15
+ //! 2. `tc qdisc replace` sets the qdisc, and `tc -j` reads it back.
16
+ //! 3. SO_TIMESTAMPING asks for two stamps of each datagram: SCHED before the enqueue in the qdisc,
17
+ //! and SND when the device takes it from the qdisc. OPT_ID gives each datagram a key, from 0 in
18
+ //! the order of the sends. A datagram that the qdisc drops takes a key and a SCHED stamp too.
19
+ //! 4. After `--settle-ms`, the program reads the counts of the qdisc, and writes `ready`.
20
+ //! 5. Each burst starts at its time after the first, and its datagrams go back to back. A send that
21
+ //! the qdisc drops gives ENOBUFS, because IP_RECVERR is set.
22
+ //! 6. The program reads the error queue until each stamp is there, or `--wait-s` passes.
23
+ //!
24
+ //! The last lines are one `packet` line for each datagram, `stats` with the counts of the qdisc
25
+ //! before and after, `clock` with the step of CLOCK_REALTIME during the run, and `done`. The stamps
26
+ //! are on CLOCK_REALTIME. The program moves them to CLOCK_MONOTONIC with the offset of the clocks
27
+ //! before the bursts, thus a step of the clock makes the run void.
28
+
29
+ use harness_native::{emit, emit_at};
30
+ use prober::{errno_name, monotonic_ns};
31
+ use serde_json::{json, Value};
32
+ use std::collections::HashMap;
33
+ use std::error::Error;
34
+ use std::net::{Ipv4Addr, SocketAddrV4, UdpSocket};
35
+ use std::os::fd::AsRawFd;
36
+ use std::process::Command;
37
+ use std::time::Duration;
38
+
39
+ /// the interface of the container, which the qdisc goes on
40
+ const DEVICE: &str = "eth0";
41
+ const SECOND_NS: u64 = 1_000_000_000;
42
+ const MS_NS: u64 = 1_000_000;
43
+ /// The kernel doubles this size. A datagram in a qdisc keeps its memory on the socket until it
44
+ /// leaves, and a stamp in the error queue keeps its memory on the socket until a read.
45
+ const BUFFER: libc::c_int = 4 << 20;
46
+ /// the bytes of the IPv4 header and the UDP header
47
+ const HEADERS: usize = 28;
48
+ /// the time from the `ready` line to the first burst
49
+ const LEAD_NS: u64 = 20 * MS_NS;
50
+ /// the longest wait for the address of the target
51
+ const RESOLVE_MS: u64 = 2_000;
52
+ const USAGE: &str = "egress sink PORT | egress send --qdisc WORDS --burst AT_MS:COUNT:PAYLOAD... HOST PORT";
53
+
54
+ // The values of linux/net_tstamp.h, linux/errqueue.h and asm-generic/socket.h for a 64-bit time_t.
55
+ const SO_TIMESTAMPING: libc::c_int = 37;
56
+ const SOF_TIMESTAMPING_TX_SOFTWARE: u32 = 1 << 1;
57
+ const SOF_TIMESTAMPING_SOFTWARE: u32 = 1 << 4;
58
+ const SOF_TIMESTAMPING_OPT_ID: u32 = 1 << 7;
59
+ const SOF_TIMESTAMPING_TX_SCHED: u32 = 1 << 8;
60
+ const SOF_TIMESTAMPING_OPT_TSONLY: u32 = 1 << 11;
61
+ const SO_EE_ORIGIN_TIMESTAMPING: u8 = 4;
62
+ const SCM_TSTAMP_SND: u32 = 0;
63
+ const SCM_TSTAMP_SCHED: u32 = 1;
64
+
65
+ /// `struct sock_extended_err` of linux/errqueue.h. For a stamp, `info` is its kind and `data` is the
66
+ /// key of its datagram. The layout needs each field, also the fields that no code reads.
67
+ #[repr(C)]
68
+ #[derive(Clone, Copy)]
69
+ #[allow(dead_code)]
70
+ struct ExtendedErr {
71
+ errno: u32,
72
+ origin: u8,
73
+ kind: u8,
74
+ code: u8,
75
+ pad: u8,
76
+ info: u32,
77
+ data: u32,
78
+ }
79
+
80
+ /// One `struct __kernel_old_timespec` of `struct scm_timestamping`, for a 64-bit time_t.
81
+ #[repr(C)]
82
+ #[derive(Clone, Copy)]
83
+ struct Stamp {
84
+ sec: i64,
85
+ nsec: i64,
86
+ }
87
+
88
+ #[derive(Debug, PartialEq)]
89
+ struct Burst {
90
+ at_ns: u64,
91
+ count: u32,
92
+ payload: usize,
93
+ }
94
+
95
+ #[derive(Debug, PartialEq)]
96
+ struct Plan {
97
+ qdisc: Vec<String>,
98
+ bursts: Vec<Burst>,
99
+ settle_ms: u64,
100
+ wait_s: u64,
101
+ target: SocketAddrV4,
102
+ }
103
+
104
+ /// Reads one burst: its time in milliseconds after the first burst, its count of datagrams and the
105
+ /// bytes of the payload of each.
106
+ fn burst_of(text: &str) -> Result<Burst, Box<dyn Error>> {
107
+ let mut parts = text.split(':');
108
+ match (parts.next(), parts.next(), parts.next(), parts.next()) {
109
+ (Some(at), Some(count), Some(payload), None) => {
110
+ let at: f64 = at.parse()?;
111
+ if !at.is_finite() || at < 0.0 {
112
+ return Err(format!("the time of a burst is not {at}").into());
113
+ }
114
+ let count: u32 = count.parse()?;
115
+ if count == 0 {
116
+ return Err(format!("the burst {text} has no datagram").into());
117
+ }
118
+ Ok(Burst { at_ns: (at * MS_NS as f64).round() as u64, count, payload: payload.parse()? })
119
+ }
120
+ _ => Err(format!("a burst is AT_MS:COUNT:PAYLOAD, not {text}").into()),
121
+ }
122
+ }
123
+
124
+ /// Reads the flags of `send`. The harness gives the place of the target, `--mode` and `--max-s` to each client.
125
+ fn plan_of(args: &[String]) -> Result<Plan, Box<dyn Error>> {
126
+ let mut qdisc = Vec::new();
127
+ let mut bursts = Vec::new();
128
+ let mut settle_ms = 200;
129
+ let mut wait_s = 5;
130
+ let mut place = Vec::new();
131
+ let mut rest = args.iter();
132
+ while let Some(arg) = rest.next() {
133
+ let mut value = || rest.next().ok_or_else(|| format!("{arg} needs a value"));
134
+ match arg.as_str() {
135
+ "--qdisc" => qdisc = value()?.split_whitespace().map(String::from).collect(),
136
+ "--burst" => bursts.push(burst_of(value()?)?),
137
+ "--settle-ms" => settle_ms = value()?.parse()?,
138
+ "--wait-s" => wait_s = value()?.parse()?,
139
+ "--mode" | "--max-s" => {
140
+ value()?;
141
+ }
142
+ other if other.starts_with("--") => return Err(format!("no flag {other}").into()),
143
+ other => place.push(other.to_string()),
144
+ }
145
+ }
146
+ if qdisc.is_empty() {
147
+ return Err("send needs --qdisc".into());
148
+ }
149
+ if bursts.is_empty() {
150
+ return Err("send needs a --burst".into());
151
+ }
152
+ if bursts.windows(2).any(|pair| pair[1].at_ns < pair[0].at_ns) {
153
+ return Err("the bursts are not in the order of their times".into());
154
+ }
155
+ let [host, port] = place.as_slice() else {
156
+ return Err(format!("send needs HOST PORT, not {place:?}").into());
157
+ };
158
+ Ok(Plan { qdisc, bursts, settle_ms, wait_s, target: SocketAddrV4::new(host.parse()?, port.parse()?) })
159
+ }
160
+
161
+ fn sink(args: &[String]) -> Result<(), Box<dyn Error>> {
162
+ let port: u16 = args.first().ok_or("egress sink PORT")?.parse()?;
163
+ let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, port))?;
164
+ emit("listening", json!({ "port": port }));
165
+ let mut buffer = vec![0u8; 65_536];
166
+ loop {
167
+ socket.recv_from(&mut buffer)?;
168
+ }
169
+ }
170
+
171
+ /// The name of an errno, or the text of an error with no errno.
172
+ fn errno_of(error: &std::io::Error) -> String {
173
+ error.raw_os_error().map_or_else(|| error.to_string(), errno_name)
174
+ }
175
+
176
+ fn set(fd: libc::c_int, level: libc::c_int, name: libc::c_int, value: libc::c_int, what: &str) -> Result<(), Box<dyn Error>> {
177
+ // SAFETY: the value is on this stack, passed with its exact size
178
+ let status = unsafe {
179
+ libc::setsockopt(
180
+ fd,
181
+ level,
182
+ name,
183
+ (&value as *const libc::c_int).cast(),
184
+ std::mem::size_of::<libc::c_int>() as libc::socklen_t,
185
+ )
186
+ };
187
+ if status == 0 {
188
+ Ok(())
189
+ } else {
190
+ Err(format!("{what}: {}", errno_of(&std::io::Error::last_os_error())).into())
191
+ }
192
+ }
193
+
194
+ fn realtime_ns() -> u64 {
195
+ let mut now = libc::timespec { tv_sec: 0, tv_nsec: 0 };
196
+ // SAFETY: clock_gettime only writes the timespec it is handed, which is on this stack
197
+ let status = unsafe { libc::clock_gettime(libc::CLOCK_REALTIME, &mut now) };
198
+ assert_eq!(status, 0, "clock_gettime(CLOCK_REALTIME) failed");
199
+ now.tv_sec as u64 * SECOND_NS + now.tv_nsec as u64
200
+ }
201
+
202
+ /// The offset of CLOCK_REALTIME from CLOCK_MONOTONIC, from one read of each clock.
203
+ fn offset_ns() -> i128 {
204
+ let before = monotonic_ns();
205
+ let real = realtime_ns();
206
+ let after = monotonic_ns();
207
+ real as i128 - (before as i128 + after as i128) / 2
208
+ }
209
+
210
+ /// Sleeps until an instant on CLOCK_MONOTONIC, or gives at once when it has passed.
211
+ fn until(at: u64) -> Result<(), Box<dyn Error>> {
212
+ let deadline = libc::timespec {
213
+ // the fields' own types: musl is moving time_t to 64 bits
214
+ tv_sec: (at / SECOND_NS) as _,
215
+ tv_nsec: (at % SECOND_NS) as _,
216
+ };
217
+ loop {
218
+ // SAFETY: a valid timespec, and no remainder is asked for with an absolute time
219
+ let code = unsafe { libc::clock_nanosleep(libc::CLOCK_MONOTONIC, libc::TIMER_ABSTIME, &deadline, std::ptr::null_mut()) };
220
+ match code {
221
+ 0 => return Ok(()),
222
+ libc::EINTR => continue,
223
+ other => return Err(format!("clock_nanosleep failed: {other}").into()),
224
+ }
225
+ }
226
+ }
227
+
228
+ /// The output of a program, or an error with its standard error.
229
+ fn output(program: &str, args: &[&str]) -> Result<String, Box<dyn Error>> {
230
+ let out = Command::new(program).args(args).output().map_err(|error| format!("{program}: {error}"))?;
231
+ if !out.status.success() {
232
+ return Err(format!("{program} {}: {}", args.join(" "), String::from_utf8_lossy(&out.stderr).trim()).into());
233
+ }
234
+ Ok(String::from_utf8(out.stdout)?)
235
+ }
236
+
237
+ /// The JSON of `ip -j` or `tc -j`. An empty output is an empty list.
238
+ fn listed(text: &str) -> Result<Vec<Value>, Box<dyn Error>> {
239
+ if text.trim().is_empty() {
240
+ return Ok(Vec::new());
241
+ }
242
+ match serde_json::from_str::<Value>(text.trim())? {
243
+ Value::Array(each) => Ok(each),
244
+ other => Err(format!("{other} is not a list").into()),
245
+ }
246
+ }
247
+
248
+ /// The link address and the states of the neighbour `host` on the device, when it has an address.
249
+ fn neighbour_of(entries: &[Value]) -> Option<(String, Vec<String>)> {
250
+ let entry = entries.iter().find(|entry| entry["lladdr"].is_string())?;
251
+ let states = entry["state"].as_array().map(|each| each.iter().filter_map(|state| state.as_str().map(String::from)).collect()).unwrap_or_default();
252
+ Some((entry["lladdr"].as_str()?.to_string(), states))
253
+ }
254
+
255
+ fn neighbour(host: Ipv4Addr) -> Result<Option<(String, Vec<String>)>, Box<dyn Error>> {
256
+ let text = output("ip", &["-j", "neigh", "show", &host.to_string(), "dev", DEVICE])?;
257
+ Ok(neighbour_of(&listed(&text)?))
258
+ }
259
+
260
+ /// Waits for the address of the target, after the first datagram, and makes the neighbour permanent.
261
+ fn pin(host: Ipv4Addr) -> Result<Value, Box<dyn Error>> {
262
+ let end = monotonic_ns() + RESOLVE_MS * MS_NS;
263
+ let address = loop {
264
+ match neighbour(host)? {
265
+ Some((address, states)) if !states.iter().any(|state| state == "INCOMPLETE" || state == "FAILED") => break address,
266
+ _ if monotonic_ns() > end => return Err(format!("no address for {host} in {RESOLVE_MS} ms").into()),
267
+ _ => std::thread::sleep(Duration::from_millis(10)),
268
+ }
269
+ };
270
+ output("ip", &["neigh", "replace", &host.to_string(), "lladdr", &address, "dev", DEVICE, "nud", "permanent"])?;
271
+ let (address, states) = neighbour(host)?.ok_or("the neighbour is gone after its replace")?;
272
+ Ok(json!({ "lladdr": address, "state": states }))
273
+ }
274
+
275
+ /// The root qdisc of the device, with its counts.
276
+ fn root_of(entries: &[Value]) -> Result<Value, Box<dyn Error>> {
277
+ entries.iter().find(|entry| entry["root"] == true).cloned().ok_or_else(|| "tc shows no root qdisc".into())
278
+ }
279
+
280
+ fn root() -> Result<Value, Box<dyn Error>> {
281
+ root_of(&listed(&output("tc", &["-s", "-j", "qdisc", "show", "dev", DEVICE])?)?)
282
+ }
283
+
284
+ /// The counts of a qdisc that the judge compares with the sends.
285
+ fn counts_of(qdisc: &Value) -> Value {
286
+ json!({
287
+ "packets": qdisc["packets"],
288
+ "bytes": qdisc["bytes"],
289
+ "drops": qdisc["drops"],
290
+ "overlimits": qdisc["overlimits"],
291
+ "requeues": qdisc["requeues"],
292
+ "qlen": qdisc["qlen"],
293
+ })
294
+ }
295
+
296
+ /// One stamp of the error queue: its kind (`SCM_TSTAMP_*`), the key of its datagram and its time on
297
+ /// CLOCK_REALTIME.
298
+ #[derive(Debug, PartialEq)]
299
+ struct Read {
300
+ kind: u32,
301
+ key: u32,
302
+ at: u64,
303
+ }
304
+
305
+ /// The stamp of one message of the error queue, from its control messages.
306
+ ///
307
+ /// # Safety
308
+ /// `msg` is the header of a message that `recvmsg` filled.
309
+ unsafe fn read_of(msg: &libc::msghdr) -> Option<Read> {
310
+ let mut at = None;
311
+ let mut err = None;
312
+ let mut cmsg = libc::CMSG_FIRSTHDR(msg);
313
+ while !cmsg.is_null() {
314
+ let (level, kind) = ((*cmsg).cmsg_level, (*cmsg).cmsg_type);
315
+ let body = libc::CMSG_DATA(cmsg);
316
+ if level == libc::SOL_SOCKET && kind == SO_TIMESTAMPING {
317
+ // ts[0] is the stamp of the software, the other two are of the hardware
318
+ let stamp = std::ptr::read_unaligned(body.cast::<Stamp>());
319
+ at = Some(stamp.sec as u64 * SECOND_NS + stamp.nsec as u64);
320
+ } else if level == libc::SOL_IP && kind == libc::IP_RECVERR {
321
+ err = Some(std::ptr::read_unaligned(body.cast::<ExtendedErr>()));
322
+ }
323
+ cmsg = libc::CMSG_NXTHDR(msg, cmsg);
324
+ }
325
+ match (at, err) {
326
+ (Some(at), Some(err)) if err.origin == SO_EE_ORIGIN_TIMESTAMPING => Some(Read { kind: err.info, key: err.data, at }),
327
+ _ => None,
328
+ }
329
+ }
330
+
331
+ /// Takes one message of the error queue. It gives None when the queue is empty.
332
+ fn take(fd: libc::c_int) -> Result<Option<Read>, Box<dyn Error>> {
333
+ let mut data = [0u8; 256];
334
+ // u64 cells, thus the buffer has the alignment of a cmsghdr
335
+ let mut control = [0u64; 128];
336
+ let mut iov = libc::iovec { iov_base: data.as_mut_ptr().cast(), iov_len: data.len() };
337
+ // SAFETY: a msghdr of zeros is a valid header with no address, and the fields below point at this stack
338
+ let mut msg: libc::msghdr = unsafe { std::mem::zeroed() };
339
+ msg.msg_iov = &mut iov;
340
+ msg.msg_iovlen = 1;
341
+ msg.msg_control = control.as_mut_ptr().cast();
342
+ msg.msg_controllen = std::mem::size_of_val(&control) as _;
343
+ // SAFETY: the header and its buffers are on this stack, and live for the whole call
344
+ let got = unsafe { libc::recvmsg(fd, &mut msg, libc::MSG_ERRQUEUE | libc::MSG_DONTWAIT) };
345
+ if got < 0 {
346
+ let error = std::io::Error::last_os_error();
347
+ return match error.raw_os_error() {
348
+ Some(libc::EAGAIN) => Ok(None),
349
+ _ => Err(format!("recvmsg of the error queue: {}", errno_of(&error)).into()),
350
+ };
351
+ }
352
+ // SAFETY: recvmsg filled the header
353
+ Ok(unsafe { read_of(&msg) }.or(Some(Read { kind: u32::MAX, key: u32::MAX, at: 0 })))
354
+ }
355
+
356
+ /// One datagram of a burst: its key, its burst, the end of its send and its errno.
357
+ struct Sent {
358
+ key: u32,
359
+ burst: usize,
360
+ payload: usize,
361
+ call: u64,
362
+ errno: Option<String>,
363
+ }
364
+
365
+ fn send(plan: &Plan) -> Result<(), Box<dyn Error>> {
366
+ let mtu: usize = {
367
+ let path = format!("/sys/class/net/{DEVICE}/mtu");
368
+ std::fs::read_to_string(&path).map_err(|error| format!("{path}: {error}"))?.trim().parse()?
369
+ };
370
+ if let Some(burst) = plan.bursts.iter().find(|burst| burst.payload + HEADERS > mtu) {
371
+ return Err(format!("a payload of {} bytes needs two fragments at an MTU of {mtu}", burst.payload).into());
372
+ }
373
+ let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))?;
374
+ socket.connect(plan.target)?;
375
+ let fd = socket.as_raw_fd();
376
+ set(fd, libc::SOL_SOCKET, libc::SO_SNDBUFFORCE, BUFFER, "SO_SNDBUFFORCE")?;
377
+ set(fd, libc::SOL_SOCKET, libc::SO_RCVBUFFORCE, BUFFER, "SO_RCVBUFFORCE")?;
378
+ set(fd, libc::SOL_IP, libc::IP_RECVERR, 1, "IP_RECVERR")?;
379
+ // the first datagram goes before the qdisc and the stamps: it resolves the address of the target
380
+ socket.send(&[0])?;
381
+ let neighbour = pin(*plan.target.ip())?;
382
+ let mut words = vec!["qdisc", "replace", "dev", DEVICE, "root"];
383
+ words.extend(plan.qdisc.iter().map(String::as_str));
384
+ output("tc", &words)?;
385
+ let flags = SOF_TIMESTAMPING_TX_SCHED | SOF_TIMESTAMPING_TX_SOFTWARE | SOF_TIMESTAMPING_SOFTWARE | SOF_TIMESTAMPING_OPT_ID | SOF_TIMESTAMPING_OPT_TSONLY;
386
+ set(fd, libc::SOL_SOCKET, SO_TIMESTAMPING, flags as libc::c_int, "SO_TIMESTAMPING")?;
387
+ let payloads: Vec<Vec<u8>> = plan.bursts.iter().map(|burst| vec![0u8; burst.payload]).collect();
388
+ std::thread::sleep(Duration::from_millis(plan.settle_ms));
389
+ // a stamp of the first datagram, or of other traffic, goes before the count of the run
390
+ while take(fd)?.is_some() {}
391
+ let before = root()?;
392
+ let offset = offset_ns();
393
+ emit("ready", json!({ "mtu": mtu, "qdisc": before, "neighbour": neighbour }));
394
+ let start = monotonic_ns() + LEAD_NS;
395
+ let mut sent = Vec::new();
396
+ let mut key = 0u32;
397
+ for (index, burst) in plan.bursts.iter().enumerate() {
398
+ until(start + burst.at_ns)?;
399
+ for _ in 0..burst.count {
400
+ let outcome = socket.send(&payloads[index]);
401
+ let call = monotonic_ns();
402
+ let errno = match outcome {
403
+ Ok(bytes) if bytes == burst.payload => None,
404
+ Ok(bytes) => return Err(format!("a send of {} bytes wrote {bytes}", burst.payload).into()),
405
+ Err(error) => Some(errno_of(&error)),
406
+ };
407
+ sent.push(Sent { key, burst: index, payload: burst.payload, call, errno });
408
+ key += 1;
409
+ }
410
+ }
411
+ let wanted = sent.len() + sent.iter().filter(|each| each.errno.is_none()).count();
412
+ let end = monotonic_ns() + plan.wait_s * SECOND_NS;
413
+ let mut sched: HashMap<u32, u64> = HashMap::new();
414
+ let mut left: HashMap<u32, u64> = HashMap::new();
415
+ let mut other = 0u32;
416
+ while sched.len() + left.len() < wanted && monotonic_ns() < end {
417
+ match take(fd)? {
418
+ Some(Read { kind: SCM_TSTAMP_SCHED, key, at }) => {
419
+ sched.insert(key, at);
420
+ }
421
+ Some(Read { kind: SCM_TSTAMP_SND, key, at }) => {
422
+ left.insert(key, at);
423
+ }
424
+ Some(_) => other += 1,
425
+ None => std::thread::sleep(Duration::from_millis(1)),
426
+ }
427
+ }
428
+ let after = root()?;
429
+ let step = offset_ns() - offset;
430
+ // a stamp on CLOCK_REALTIME, on CLOCK_MONOTONIC with the offset before the bursts
431
+ let monotonic = |at: Option<&u64>| at.map(|&at| (at as i128 - offset) as u64);
432
+ for each in &sent {
433
+ emit_at(
434
+ "packet",
435
+ each.call,
436
+ json!({
437
+ "key": each.key,
438
+ "burst": each.burst,
439
+ "payload": each.payload,
440
+ "errno": each.errno,
441
+ "sched": monotonic(sched.get(&each.key)),
442
+ "left": monotonic(left.get(&each.key)),
443
+ }),
444
+ );
445
+ }
446
+ emit("stats", json!({ "before": counts_of(&before), "after": counts_of(&after), "kind": after["kind"] }));
447
+ emit("clock", json!({ "step": step as i64 }));
448
+ emit(
449
+ "done",
450
+ json!({
451
+ "sends": sent.len(),
452
+ "dropped": sent.iter().filter(|each| each.errno.is_some()).count(),
453
+ "sched": sched.len(),
454
+ "left": left.len(),
455
+ "other": other,
456
+ "start": start,
457
+ }),
458
+ );
459
+ Ok(())
460
+ }
461
+
462
+ fn main() {
463
+ let args: Vec<String> = std::env::args().skip(1).collect();
464
+ let outcome = match args.first().map(String::as_str) {
465
+ Some("sink") => sink(&args[1..]),
466
+ Some("send") => plan_of(&args[1..]).and_then(|plan| send(&plan)),
467
+ _ => Err(USAGE.into()),
468
+ };
469
+ // an error is a line too: the harness ends the run at it, and the judge makes the run void
470
+ if let Err(error) = outcome {
471
+ emit("error", json!({ "what": error.to_string() }));
472
+ std::process::exit(1);
473
+ }
474
+ }
475
+
476
+ #[cfg(test)]
477
+ mod tests {
478
+ use super::*;
479
+
480
+ fn argv(each: &[&str]) -> Vec<String> {
481
+ each.iter().map(|arg| arg.to_string()).collect()
482
+ }
483
+
484
+ #[test]
485
+ fn a_send_reads_its_qdisc_and_its_bursts_and_skips_the_flags_of_the_harness() {
486
+ let plan = plan_of(&argv(&[
487
+ "--qdisc", "netem delay 100ms rate 10mbit limit 12", "--burst", "0:8:1472", "--burst", "30:8:1472",
488
+ "10.0.0.2", "6393", "--mode", "idle", "--max-s", "20",
489
+ ]))
490
+ .expect("a plan");
491
+ assert_eq!(plan.qdisc, ["netem", "delay", "100ms", "rate", "10mbit", "limit", "12"]);
492
+ assert_eq!(plan.bursts, [Burst { at_ns: 0, count: 8, payload: 1472 }, Burst { at_ns: 30 * MS_NS, count: 8, payload: 1472 }]);
493
+ assert_eq!(plan.target, SocketAddrV4::new(Ipv4Addr::new(10, 0, 0, 2), 6393));
494
+ assert_eq!((plan.settle_ms, plan.wait_s), (200, 5));
495
+ }
496
+
497
+ #[test]
498
+ fn a_send_refuses_a_plan_with_no_qdisc_no_burst_or_bursts_out_of_order() {
499
+ assert!(plan_of(&argv(&["--burst", "0:1:1", "10.0.0.2", "6393"])).is_err());
500
+ assert!(plan_of(&argv(&["--qdisc", "netem", "10.0.0.2", "6393"])).is_err());
501
+ assert!(plan_of(&argv(&["--qdisc", "netem", "--burst", "5:1:1", "--burst", "1:1:1", "10.0.0.2", "6393"])).is_err());
502
+ assert!(plan_of(&argv(&["--qdisc", "netem", "--burst", "0:1:1", "10.0.0.2"])).is_err());
503
+ assert!(plan_of(&argv(&["--qdisc", "netem", "--burst", "0:1:1", "--no-such", "1", "10.0.0.2", "6393"])).is_err());
504
+ assert!(burst_of("0:0:100").is_err());
505
+ assert!(burst_of("-1:1:100").is_err());
506
+ assert!(burst_of("0:1").is_err());
507
+ assert_eq!(burst_of("12.5:3:958").expect("a burst"), Burst { at_ns: 12_500_000, count: 3, payload: 958 });
508
+ }
509
+
510
+ #[test]
511
+ fn the_json_of_ip_and_tc_gives_the_neighbour_and_the_root_qdisc() {
512
+ let neighbours = listed(r#"[{"dst":"10.0.0.2","lladdr":"02:42:0a:00:00:02","state":["PERMANENT"]}]"#).expect("a list");
513
+ assert_eq!(neighbour_of(&neighbours), Some(("02:42:0a:00:00:02".to_string(), vec!["PERMANENT".to_string()])));
514
+ assert_eq!(neighbour_of(&listed(r#"[{"dst":"10.0.0.2","state":["INCOMPLETE"]}]"#).expect("a list")), None);
515
+ assert!(listed("").expect("a list").is_empty());
516
+ assert!(listed("{}").is_err());
517
+ let qdiscs = listed(
518
+ r#"[{"kind":"tbf","handle":"8001:","root":true,"options":{"rate":125000,"burst":3000},"bytes":0,"packets":0,"drops":0,"overlimits":0,"requeues":0,"qlen":0},
519
+ {"kind":"bfifo","handle":"0:","parent":"8001:1","options":{"limit":30000},"bytes":0,"packets":0,"drops":0}]"#,
520
+ )
521
+ .expect("a list");
522
+ let root = root_of(&qdiscs).expect("a root");
523
+ assert_eq!(root["kind"], "tbf");
524
+ assert_eq!(counts_of(&root)["drops"], 0);
525
+ assert!(root_of(&qdiscs[1..]).is_err());
526
+ }
527
+
528
+ #[test]
529
+ fn the_constants_of_the_stamps_are_those_of_the_kernel_headers() {
530
+ assert_eq!(std::mem::size_of::<ExtendedErr>(), 16);
531
+ assert_eq!(std::mem::size_of::<Stamp>(), 16);
532
+ assert_eq!(SOF_TIMESTAMPING_TX_SCHED | SOF_TIMESTAMPING_TX_SOFTWARE | SOF_TIMESTAMPING_SOFTWARE | SOF_TIMESTAMPING_OPT_ID | SOF_TIMESTAMPING_OPT_TSONLY, 0x992);
533
+ }
534
+
535
+ #[test]
536
+ fn the_clocks_give_an_offset_that_does_not_step_between_two_reads() {
537
+ let (first, second) = (offset_ns(), offset_ns());
538
+ assert!((second - first).abs() < 1_000_000);
539
+ }
540
+ }
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.16.6",
5
- "description": "Network labs in Docker, declared as data. A cell builds a topology of networks, routers and proxies around a stock target. It injects a fault at layer 3 or 4 from a NET_ADMIN sidecar, measures the records of the kernel and judges a prediction. The faults are black holes, resets, ICMP unreachable, one-way and MTU drops, tc netem, the toxics of Toxiproxy and frozen processes. Its disk tier cuts the power of a program on LazyFS: the disk loses each write after the last fsync. Its memory tier sets the limits of the cgroup of a client, and judges its throttle above memory.high and the choice of the OOM killer. Its replicated groups are Redis with Sentinels, MongoDB replica sets, PostgreSQL standbys, Kafka, RabbitMQ and BGP fabrics with BFD. A lab can also operate in a QEMU guest. Its first use is connection timers: keep-alive, TCP retransmission, heartbeats and reconnects.",
4
+ "version": "0.16.8",
5
+ "description": "Network labs in Docker, declared as data. A cell builds a topology of networks, routers and proxies around a stock target. It injects a fault at layer 3 or 4 from a NET_ADMIN sidecar, measures the records of the kernel and judges a prediction. The faults are black holes, resets, ICMP unreachable, one-way and MTU drops, tc netem, the toxics of Toxiproxy and frozen processes. Its disk tier cuts the power of a program on LazyFS: the disk loses each write after the last fsync. Its memory tier sets the limits of the cgroup of a client, and judges its throttle above memory.high and the choice of the OOM killer. Its egress tier puts a netem or tbf qdisc on the interface of a client, and judges the departure of each datagram from the stamps of the kernel. Its replicated groups are Redis with Sentinels, MongoDB replica sets, PostgreSQL standbys, Kafka, RabbitMQ and BGP fabrics with BFD. A lab can also operate in a QEMU guest. Its first use is connection timers: keep-alive, TCP retransmission, heartbeats and reconnects.",
6
6
  "keywords": [
7
7
  "fault-injection",
8
8
  "chaos-engineering",
@@ -119,7 +119,7 @@
119
119
  "node": ">=22.19"
120
120
  },
121
121
  "dependencies": {
122
- "@mark1russell7/prober": "^0.3.4",
122
+ "@mark1russell7/prober": "^0.3.5",
123
123
  "@mark1russell7/quantity": "^0.4.1",
124
124
  "@mark1russell7/rigor-bench": "^0.2.10",
125
125
  "@mark1russell7/rigor-chaos": "^0.3.3",