Skip to content

Commit 22dedae

Browse files
git-hulkclaude
andcommitted
Synchronise the endpoint stats between the capture and stats threads
The stats thread walked syn_tab and read every query_stats in it while the capture thread was inserting endpoints and bumping counters, with nothing between them. Replaying a 16000 packet capture while polling the stats endpoint reports six data races under ThreadSanitizer and aborts: in stats_incr, in create_stats_object and on srv->stopped. - Add stats_lock to the sniffer, held by the capture thread around every syn_tab lookup, insert and counter update, and by the stats thread across the whole walk so a response cannot be counted half way through serialisation. The requests table stays lock free: only the capture thread touches it. - srv->stopped is written by server_terminate, which also runs from the signal handler, and read by the stats thread's loop. It is now sig_atomic_t accessed through the compiler's atomic builtins. - Skip the endpoint instead of dereferencing NULL when the calloc for a new query_stats fails. `make test-race` rebuilds under ThreadSanitizer and replays a generated stress capture while polling the endpoint; it reports 0 races where the previous code reported 6. It is opt-in because it clobbers the ordinary build, and runs as its own CI job. Assistant By Opus 5 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 2448159 commit 22dedae

11 files changed

Lines changed: 192 additions & 23 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@ jobs:
1818
- name: Install libpcap
1919
if: runner.os == 'Linux'
2020
run: sudo apt-get update && sudo apt-get install -y libpcap-dev
21+
# The sanitizers the test suite uses need this on newer Ubuntu kernels.
22+
- name: Widen mmap randomisation for the sanitizers
23+
if: runner.os == 'Linux'
24+
run: sudo sysctl -w vm.mmap_rnd_bits=28 || true
2125
- name: Build
2226
run: make
2327
- name: Test
@@ -33,6 +37,18 @@ jobs:
3337
- name: Build
3438
run: make USE_SYSTEM_PCAP=0
3539

40+
race:
41+
name: thread sanitizer
42+
runs-on: ubuntu-latest
43+
steps:
44+
- uses: actions/checkout@v4
45+
- name: Install libpcap
46+
run: sudo apt-get update && sudo apt-get install -y libpcap-dev
47+
- name: Widen mmap randomisation for the sanitizers
48+
run: sudo sysctl -w vm.mmap_rnd_bits=28 || true
49+
- name: Replay a busy capture while polling the stats endpoint
50+
run: make test-race
51+
3652
fixtures:
3753
name: fixtures are reproducible
3854
runs-on: ubuntu-latest

‎Makefile‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ all:
66
test: all
77
cd tests && $(MAKE) test
88

9+
test-race:
10+
cd tests && $(MAKE) test-race
11+
912
fixtures:
1013
cd tests && $(MAKE) fixtures
1114

@@ -19,4 +22,4 @@ clean:
1922
.DEFAULT:
2023
cd src && $(MAKE) $@
2124

22-
.PHONY: default all test fixtures install clean
25+
.PHONY: default all test test-race fixtures install clean

‎src/Makefile‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ CFLAGS = -g $(OPTIMIZATION) -Wall
1010
# SANITIZE=address builds the binary and the test suite under ASan/UBSan.
1111
ifdef SANITIZE
1212
CFLAGS += -fsanitize=$(SANITIZE) -fno-omit-frame-pointer
13-
LDFLAGS += -fsanitize=$(SANITIZE)
1413
endif
1514

1615
LUA_DIR = ../deps/lua/src

‎src/packet.c‎

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -119,19 +119,23 @@ int process_udp_packet(const struct timeval tv,
119119

120120
static int packet_direction(struct sniffer *sniffer, struct user_packet *upacket) {
121121
char key[32];
122+
int direction = -1;
122123
struct query_stats *stats;
123124

125+
sniffer_stats_lock(sniffer);
124126
snprintf(key, sizeof(key), "%u:%d", upacket->ip_src.s_addr, upacket->port_src);
125127
if ((stats = hashtable_get(sniffer->syn_tab, key)) != NULL) {
126128
stats_incr(stats, 0, upacket->size);
127-
return 0;
128-
}
129-
snprintf(key, sizeof(key), "%u:%d", upacket->ip_dst.s_addr, upacket->port_dst);
130-
if ((stats = hashtable_get(sniffer->syn_tab, key)) != NULL) {
131-
stats_incr(stats, 1, upacket->size);
132-
return 1;
129+
direction = 0;
130+
} else {
131+
snprintf(key, sizeof(key), "%u:%d", upacket->ip_dst.s_addr, upacket->port_dst);
132+
if ((stats = hashtable_get(sniffer->syn_tab, key)) != NULL) {
133+
stats_incr(stats, 1, upacket->size);
134+
direction = 1;
135+
}
133136
}
134-
return -1;
137+
sniffer_stats_unlock(sniffer);
138+
return direction;
135139
}
136140

137141
static void push_packet_to_lua_state(lua_State *state, struct user_packet *upacket) {
@@ -204,9 +208,11 @@ static void process_response_packet(struct sniffer *sniffer, struct user_packet
204208
delta = (upacket->tv.tv_sec - req->tv.tv_sec) * 1000000
205209
+ (upacket->tv.tv_usec - req->tv.tv_usec);
206210
snprintf(target, sizeof(target), "%u:%d", upacket->ip_src.s_addr, upacket->port_src);
211+
sniffer_stats_lock(sniffer);
207212
if ((stats = hashtable_get(sniffer->syn_tab, target)) != NULL) {
208213
stats_observer_latency(stats, delta);
209214
}
215+
sniffer_stats_unlock(sniffer);
210216
if (sniffer->threshold && delta < sniffer->threshold*1000) {
211217
hashtable_del(sniffer->requests, key);
212218
return;
@@ -297,12 +303,16 @@ void process_user_packet(struct sniffer *sniffer, struct user_packet *upacket) {
297303
} else {
298304
snprintf(key, sizeof(key), "%u:%d", upacket->ip_dst.s_addr, upacket->port_dst);
299305
}
306+
sniffer_stats_lock(sniffer);
300307
if (!hashtable_get(sniffer->syn_tab, key)) {
301308
stats = calloc(1, sizeof(*stats));
302-
stats->ip = src ? upacket->ip_src : upacket->ip_dst;
303-
stats->port = src ? upacket->port_src : upacket->port_dst;
304-
hashtable_add(sniffer->syn_tab, key, stats);
309+
if (stats) {
310+
stats->ip = src ? upacket->ip_src : upacket->ip_dst;
311+
stats->port = src ? upacket->port_src : upacket->port_dst;
312+
hashtable_add(sniffer->syn_tab, key, stats);
313+
}
305314
}
315+
sniffer_stats_unlock(sniffer);
306316
}
307317
} else {
308318
switch(packet_direction(sniffer, upacket)) {

‎src/server.c‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,8 @@ int server_run(struct server *srv, char *err) {
9595
}
9696

9797
void server_terminate(struct server *srv) {
98-
if (!srv || srv->stopped) return;
99-
srv->stopped = 1;
98+
if (!srv || TK_LOAD(&srv->stopped)) return;
99+
TK_STORE(&srv->stopped, 1);
100100
sniffer_terminate(srv->sniffer);
101101
if (srv->dumper) dumper_terminate(srv->dumper);
102102
}
@@ -195,13 +195,17 @@ static char *server_stats_to_json(struct server *srv) {
195195
char buf[64], *stats_json_str;
196196

197197
object = cJSON_CreateObject();
198+
/* Held across the whole walk: the capture thread may otherwise add an
199+
* endpoint or bump a counter half way through. */
200+
sniffer_stats_lock(srv->sniffer);
198201
values = hashtable_values(srv->sniffer->syn_tab, &cnt);
199202
for (i = 0; i < cnt; i++) {
200-
stats = (struct query_stats *)values[i];
203+
stats = (struct query_stats *)values[i];
201204
if (!stats) continue;
202-
snprintf(buf, 64, "%s:%d", inet_ntoa(stats->ip), stats->port);
205+
snprintf(buf, sizeof(buf), "%s:%d", inet_ntoa(stats->ip), stats->port);
203206
cJSON_AddItemToObject(object, buf, create_stats_object(stats));
204207
}
208+
sniffer_stats_unlock(srv->sniffer);
205209
stats_json_str = cJSON_Print(object);
206210
cJSON_Delete(object);
207211
free(values);
@@ -223,7 +227,7 @@ static void *server_stats_loop(void *arg) {
223227
}
224228
fds[0].fd = listen_fd;
225229
fds[0].events = POLLIN;
226-
while(!srv->stopped) {
230+
while(!TK_LOAD(&srv->stopped)) {
227231
rc = poll(fds, 1, 100);
228232
if (rc <= 0) continue;
229233
new_fd = accept(listen_fd, NULL, NULL);

‎src/server.h‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,26 @@
1313
#define TCPKIT_SERVER_H
1414

1515
#include <pthread.h>
16+
#include <signal.h>
1617
#include "tcpkit.h"
1718

19+
#if defined(__GNUC__)
20+
#define TK_LOAD(p) __atomic_load_n((p), __ATOMIC_ACQUIRE)
21+
#define TK_STORE(p, v) __atomic_store_n((p), (v), __ATOMIC_RELEASE)
22+
#else
23+
#define TK_LOAD(p) (*(p))
24+
#define TK_STORE(p, v) (*(p) = (v))
25+
#endif
26+
1827
struct server {
1928
struct options *opts;
2029
struct sniffer *sniffer;
2130
struct dumper* dumper;
2231
pthread_t dumper_tid;
2332
pthread_t stats_tid;
24-
int stopped;
33+
/* Set by server_terminate, which also runs from the signal handler, and
34+
* read by the stats thread. */
35+
sig_atomic_t stopped;
2536
};
2637

2738
struct server *server_create(struct options *opts, char *err);

‎src/sniffer.c‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,11 @@ struct sniffer *sniffer_create(struct options *opts, char *err) {
8282
snprintf(err, MAX_ERR_BUFF_SIZE, "out of memory");
8383
goto error;
8484
}
85+
if (pthread_mutex_init(&sniffer->stats_lock, NULL) != 0) {
86+
snprintf(err, MAX_ERR_BUFF_SIZE, "failed to init the stats lock");
87+
goto error;
88+
}
89+
sniffer->lock_ready = 1;
8590
sniffer->syn_tab->free = free_stats;
8691
sniffer->requests->free = free_request;
8792

@@ -120,6 +125,7 @@ struct sniffer *sniffer_create(struct options *opts, char *err) {
120125

121126
void sniffer_destroy(struct sniffer *sniffer) {
122127
if (!sniffer) return;
128+
if (sniffer->lock_ready) pthread_mutex_destroy(&sniffer->stats_lock);
123129
if (sniffer->pcap) pcap_close(sniffer->pcap);
124130
free(sniffer->dev);
125131
free(sniffer->filter);

‎src/sniffer.h‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
#define TCPKIT_SNIFFER_H
1414

1515
#include <pcap.h>
16+
#include <pthread.h>
1617
#include <lua.h>
1718
#include "tcpkit.h"
1819
#include "stats.h"
@@ -26,12 +27,25 @@ struct sniffer {
2627
int threshold;
2728
int ascii;
2829

30+
/* syn_tab and the query_stats it owns are read by the stats thread while
31+
* the capture thread updates them, so both sides hold stats_lock.
32+
* requests belongs to the capture thread alone and needs no lock. */
33+
pthread_mutex_t stats_lock;
34+
int lock_ready;
2935
struct hashtable *syn_tab;
3036
struct hashtable *requests;
3137
lua_State *lua_state;
3238
struct bpf_program *bpf;
3339
};
3440

41+
static inline void sniffer_stats_lock(struct sniffer *sniffer) {
42+
pthread_mutex_lock(&sniffer->stats_lock);
43+
}
44+
45+
static inline void sniffer_stats_unlock(struct sniffer *sniffer) {
46+
pthread_mutex_unlock(&sniffer->stats_lock);
47+
}
48+
3549
struct request {
3650
struct timeval tv;
3751
int seq;

‎tests/Makefile‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,19 @@ PACKET_SRCS = $(SRC_DIR)/packet.c $(SRC_DIR)/protocol.c $(SRC_DIR)/hashtable.c \
4141
$(SRC_DIR)/stats.c $(SRC_DIR)/cJSON.c $(SRC_DIR)/log.c $(SRC_DIR)/lua.c
4242

4343
test_packet: unit/test_packet.c $(PACKET_SRCS) $(LUA_DIR)/liblua.a
44-
$(CC) $(CFLAGS) -o $@ $^ -lm -ldl
44+
$(CC) $(CFLAGS) -o $@ $^ -lm -ldl -lpthread
45+
46+
# Opt-in: rebuilds the binary under ThreadSanitizer, so it is kept out of
47+
# `make test` and clobbers the ordinary build.
48+
test-race:
49+
$(MAKE) -C $(SRC_DIR) clean
50+
$(MAKE) -C $(SRC_DIR) SANITIZE=thread
51+
python3 e2e/race.py
4552

4653
fixtures:
4754
cd fixtures && python3 gen_fixtures.py
4855

4956
clean:
5057
- rm -rf $(SUITES) *.dSYM
5158

52-
.PHONY: unit e2e fixtures clean
59+
.PHONY: unit e2e test-race fixtures clean

‎tests/e2e/race.py‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#!/usr/bin/env python3
2+
"""Replays a busy capture while hammering the stats endpoint.
3+
4+
Meant to be run against a binary built with -fsanitize=thread: the stats
5+
thread walks the endpoint table that the capture thread is still filling in,
6+
so any missing synchronisation shows up as a ThreadSanitizer report.
7+
"""
8+
9+
import os
10+
import re
11+
import socket
12+
import subprocess
13+
import sys
14+
import tempfile
15+
import time
16+
17+
HERE = os.path.dirname(os.path.abspath(__file__))
18+
TESTS = os.path.dirname(HERE)
19+
TCPKIT = os.environ.get("TCPKIT", os.path.join(TESTS, os.pardir, "src", "tcpkit"))
20+
PORT = int(os.environ.get("STATS_PORT", "34100"))
21+
TIMEOUT = float(os.environ.get("RACE_TIMEOUT", "60"))
22+
23+
24+
def main():
25+
if not os.path.exists(TCPKIT):
26+
print("race: %s not built" % TCPKIT)
27+
return 1
28+
29+
with tempfile.TemporaryDirectory() as tmp:
30+
capture = os.path.join(tmp, "stress.pcap")
31+
subprocess.run([sys.executable, "gen_fixtures.py", "--stress", capture],
32+
cwd=os.path.join(TESTS, "fixtures"), check=True,
33+
stdout=subprocess.DEVNULL)
34+
35+
env = dict(os.environ)
36+
env["TSAN_OPTIONS"] = "halt_on_error=0 " + env.get("TSAN_OPTIONS", "")
37+
proc = subprocess.Popen(
38+
[TCPKIT, "-r", capture, "-p", "redis", "-P", str(PORT)],
39+
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, env=env)
40+
41+
polls = 0
42+
deadline = time.time() + TIMEOUT
43+
while proc.poll() is None and time.time() < deadline:
44+
try:
45+
conn = socket.create_connection(("127.0.0.1", PORT), timeout=0.5)
46+
conn.recv(1 << 20)
47+
conn.close()
48+
polls += 1
49+
except OSError:
50+
time.sleep(0.01)
51+
52+
try:
53+
err = proc.communicate(timeout=30)[1]
54+
except subprocess.TimeoutExpired:
55+
proc.kill()
56+
print("race: the capture did not finish in time")
57+
return 1
58+
59+
races = re.findall(r"SUMMARY: ThreadSanitizer: data race (.+)", err)
60+
print("race: %d stats requests served during the replay" % polls)
61+
if polls == 0:
62+
print("race: the stats endpoint was never reached, nothing was exercised")
63+
return 1
64+
if races:
65+
print("race: %d data races reported" % len(races))
66+
for where in sorted(set(races)):
67+
print(" " + where)
68+
return 1
69+
if proc.returncode != 0:
70+
print("race: the capture exited with %d" % proc.returncode)
71+
sys.stderr.write(err)
72+
return 1
73+
print("race: no data races reported")
74+
return 0
75+
76+
77+
if __name__ == "__main__":
78+
sys.exit(main())

0 commit comments

Comments
 (0)