Debian Codegraph @

c/tests/threaderciser.c

raw
1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 /* This test is intended to be run under a race detector (e.g. helgrind,
21 libtsan) to uncover races by generating concurrent, pseudo-random activity.
22 It should also be run under memory checkers (e.g. valgrind memcheck, libasan)
23 for race conditions that leak memory.
24
25 The goal is to drive concurrent activity as hard as possible while staying
26 within the rules of the API. It may do things that an application is unlikely
27 to do (e.g. close a listener before it opens) but that are not disallowed by
28 the API rules - that's the goal.
29
30 It is impossible to get repeatable behaviour with multiple threads due to
31 unpredictable scheduling. Currently using plain old rand(), if quality of
32 randomness is problem we can upgrade.
33
34 NOTE: to narrow down race conditions you have two tools
35 - specify a limited set of actions with command line flags, e.g.
36 $ threaderciser -no-close-connect # Do everything but close connections
37 $ threaderciser -timeout -cancel-timeout # Only do timeout actions
38 - use suppressions to hide races you know about but are not ready to fix
39 $ TSAN_OPTIONS="suppressions=/my/suppressions/file" threaderciser
40 $ valgrind --tool=helgrind --suppressions=/my/suppressions/file threaderciser
41
42 TODO:
43 - pn_proactor_release_connection and re-use with pn_proactor_connect/accept
44 - sending/receiving/tracking messages
45 */
46
47 /* Enable POSIX features beyond c99 for modern pthread and standard strerror_r() */
48 #ifndef _POSIX_C_SOURCE
49 #define _POSIX_C_SOURCE 200809L
50 #endif
51
52 #include "thread.h"
53
54 #include <proton/connection.h>
55 #include <proton/event.h>
56 #include <proton/listener.h>
57 #include <proton/netaddr.h>
58 #include <proton/proactor.h>
59
60 #include <inttypes.h>
61 #include <stdarg.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <time.h>
66
67 #undef NDEBUG /* Enable assert even in release builds */
68 #include <assert.h>
69
70 #define BACKLOG 16 /* Listener backlog */
71 #define TIMEOUT_MAX 100 /* Milliseconds */
72 #define SLEEP_MAX 100 /* Milliseconds */
73
74 /* Set of actions that can be enabled/disabled/counted */
75 typedef enum { A_LISTEN, A_CLOSE_LISTEN, A_CONNECT, A_CLOSE_CONNECT, A_WAKE, A_TIMEOUT, A_CANCEL_TIMEOUT } action;
76 const char* action_name[] = { "listen", "close-listen", "connect", "close-connect", "wake", "timeout", "cancel-timeout" };
77 #define action_size (sizeof(action_name)/sizeof(*action_name))
78 bool action_enabled[action_size] = { 0 } ;
79
80 static int assert_no_err(int n) { assert(n >= 0); return n; }
81
82 static bool debug_enable = false;
83
84 /*
85 NOTE: Printing to a single debug log from many threads creates artificial
86 before/after relationships that may mask race conditions (locks in fputs)
87
88 TODO: something better, e.g. per-thread timestamped logs that are only
89 collated and printed periodically or at end of process.
90 */
91 #define debug(...) if (debug_enable) debug_impl(__VA_ARGS__)
92
93 static void debug_impl(const char *fmt, ...) {
94 /* Collect thread-id and message in a single buffer to minimize mixed messages */
95 char msg[256];
96 char *i = msg;
97 char *end = i + sizeof(msg);
98 i += assert_no_err(snprintf(i, end-i, "(%" PRIxPTR ") ", (uintptr_t) pthread_self()));
99 if (i < end) {
100 va_list ap;
101 va_start(ap, fmt);
102 i += assert_no_err(vsnprintf(i, end-i, fmt, ap));
103 va_end(ap);
104 }
105 fprintf(stderr, "%s\n", msg);
106 }
107
108 /* Shorthand for debugging an action using id as identifier */
109 static inline void debuga(action a, void *id) {
110 debug("[%p] %s", id, action_name[a]);
111 }
112
113 /* Thread safe pools of structs.
114
115 An element can be "picked" at random concurrently by many threads, and is
116 guaranteed not to be freed until "done" is called by all threads. Element
117 structs must have their own locks if picking threads can modify the element.
118 */
119
120 struct pool;
121
122 /* This must be the first field in structs that go in a pool */
123 typedef struct pool_entry {
124 struct pool *pool;
125 int ref; /* threads using this entry */
126 } pool_entry;
127
128 typedef void (*pool_free_fn)(void*);
129
130 typedef struct pool {
131 pthread_mutex_t lock;
132 pool_entry **entries;
133 size_t size, max;
134 pool_free_fn free_fn;
135 } pool;
136
137
138 void pool_init(pool *p, size_t max, pool_free_fn free_fn) {
139 pthread_mutex_init(&p->lock, NULL);
140 p->entries = (pool_entry**)calloc(max, sizeof(*p->entries));
141 p->size = 0;
142 p->max = max;
143 p->free_fn = free_fn;
144 }
145
146 void pool_destroy(pool *p) {
147 pthread_mutex_destroy(&p->lock);
148 free(p->entries);
149 }
150
151 bool pool_add(pool *p, pool_entry *entry) {
152 pthread_mutex_lock(&p->lock);
153 entry->pool = p;
154 entry->ref = 1;
155 bool ok = false;
156 if (p->size < p->max) {
157 p->entries[p->size++] = entry;
158 ok = true;
159 }
160 pthread_mutex_unlock(&p->lock);
161 return ok;
162 }
163
164 void pool_unref(pool_entry *entry) {
165 pool *p = (pool*)entry->pool;
166 pthread_mutex_lock(&p->lock);
167 if (--entry->ref == 0) {
168 size_t i = 0;
169 while (i < p->size && p->entries[i] != entry) ++i;
170 if (i < p->size) {
171 --p->size;
172 memmove(p->entries + i, p->entries + i + 1, (p->size - i)*sizeof(*p->entries));
173 (*p->free_fn)(entry);
174 }
175 }
176 pthread_mutex_unlock(&p->lock);
177 }
178
179 /* Pick a random element, NULL if empty. Call pool_unref(entry) when finished */
180 pool_entry *pool_pick(pool *p) {
181 pthread_mutex_lock(&p->lock);
182 pool_entry *entry = NULL;
183 if (p->size) {
184 entry = p->entries[rand() % p->size];
185 ++entry->ref;
186 }
187 pthread_mutex_unlock(&p->lock);
188 return entry;
189 }
190
191 /* Macro for type-safe pools */
192 #define DECLARE_POOL(P, T) \
193 typedef struct P { pool p; } P; \
194 void P##_init(P *p, size_t max, void (*free_fn)(T*)) { pool_init((pool*)p, max, (pool_free_fn) free_fn); } \
195 bool P##_add(P *p, T *entry) { return pool_add((pool*)p, &entry->entry); } \
196 void P##_unref(T *entry) { pool_unref(&entry->entry); } \
197 T *P##_pick(P *p) { return (T*)pool_pick((pool*) p); } \
198 void P##_destroy(P *p) { pool_destroy(&p->p); }
199
200
201 /* Connection pool */
202
203 typedef struct connection_ctx {
204 pool_entry entry;
205 pn_connection_t *pn_connection;
206 pthread_mutex_t lock; /* Lock PN_TRANSPORT_CLOSED vs. pn_connection_wake() */
207 } connection_ctx;
208
209 DECLARE_POOL(cpool, connection_ctx)
210
211 static connection_ctx* connection_ctx_new(void) {
212 connection_ctx *ctx = (connection_ctx*)malloc(sizeof(*ctx));
213 ctx->pn_connection = pn_connection();
214 pthread_mutex_init(&ctx->lock, NULL);
215 pn_connection_set_context(ctx->pn_connection, ctx);
216 return ctx;
217 }
218
219 static void connection_ctx_free(connection_ctx* ctx) {
220 /* Don't free ctx->pn_connection, freed by proactor */
221 pthread_mutex_destroy(&ctx->lock);
222 free(ctx);
223 }
224
225 void cpool_connect(cpool *cp, pn_proactor_t *proactor, const char *addr) {
226 if (!action_enabled[A_CONNECT]) return;
227 connection_ctx *ctx = connection_ctx_new();
228 if (cpool_add(cp, ctx)) {
229 debuga(A_CONNECT, ctx->pn_connection);
230 pn_proactor_connect(proactor, ctx->pn_connection, addr);
231 } else {
232 pn_connection_free(ctx->pn_connection); /* Won't be freed by proactor */
233 connection_ctx_free(ctx);
234 }
235 }
236
237 void cpool_wake(cpool *cp) {
238 if (!action_enabled[A_WAKE]) return;
239 connection_ctx *ctx = cpool_pick(cp);
240 if (ctx) {
241 /* Required locking: application may not call wake on a freed connection */
242 pthread_mutex_lock(&ctx->lock);
243 if (ctx && ctx->pn_connection) {
244 debuga(A_WAKE, ctx->pn_connection);
245 pn_connection_wake(ctx->pn_connection);
246 }
247 pthread_mutex_unlock(&ctx->lock);
248 cpool_unref(ctx);
249 }
250 }
251
252 /* Listener pool */
253
254 typedef struct listener_ctx {
255 pool_entry entry;
256 pn_listener_t *pn_listener;
257 pthread_mutex_t lock; /* Lock PN_LISTENER_CLOSE vs. pn_listener_close() */
258 char addr[PN_MAX_ADDR];
259 } listener_ctx;
260
261 DECLARE_POOL(lpool, listener_ctx)
262
263 static listener_ctx* listener_ctx_new(void) {
264 listener_ctx *ctx = (listener_ctx*)malloc(sizeof(*ctx));
265 ctx->pn_listener = pn_listener();
266 pthread_mutex_init(&ctx->lock, NULL);
267 /* Use "invalid:address" because "" is treated as ":5672" */
268 strncpy(ctx->addr, "invalid:address", sizeof(ctx->addr));
269 pn_listener_set_context(ctx->pn_listener, ctx);
270 return ctx;
271 }
272
273 static void listener_ctx_free(listener_ctx *ctx) {
274 /* Don't free ctx->pn_listener, freed by proactor */
275 pthread_mutex_destroy(&ctx->lock);
276 free(ctx);
277 }
278
279 static void lpool_listen(lpool *lp, pn_proactor_t *proactor) {
280 if (!action_enabled[A_LISTEN]) return;
281 char a[PN_MAX_ADDR];
282 pn_proactor_addr(a, sizeof(a), "", "0");
283 listener_ctx *ctx = listener_ctx_new();
284 if (lpool_add(lp, ctx)) {
285 debuga(A_LISTEN, ctx->pn_listener);
286 pn_proactor_listen(proactor, ctx->pn_listener, a, BACKLOG);
287 } else {
288 pn_listener_free(ctx->pn_listener); /* Won't be freed by proactor */
289 listener_ctx_free(ctx);
290 }
291 }
292
293 /* Pick a random listening address from the listener pool.
294 Returns "invalid:address" for no address.
295 */
296 static void lpool_addr(lpool *lp, char* a, size_t s) {
297 strncpy(a, "invalid:address", s);
298 listener_ctx *ctx = lpool_pick(lp);
299 if (ctx) {
300 pthread_mutex_lock(&ctx->lock);
301 strncpy(a, ctx->addr, s);
302 pthread_mutex_unlock(&ctx->lock);
303 lpool_unref(ctx);
304 }
305 }
306
307 void lpool_close(lpool *lp) {
308 if (!action_enabled[A_CLOSE_LISTEN]) return;
309 listener_ctx *ctx = lpool_pick(lp);
310 if (ctx) {
311 pthread_mutex_lock(&ctx->lock);
312 if (ctx->pn_listener) {
313 pn_listener_close(ctx->pn_listener);
314 debuga(A_CLOSE_LISTEN, ctx->pn_listener);
315 }
316 pthread_mutex_unlock(&ctx->lock);
317 lpool_unref(ctx);
318 }
319 }
320
321 /* Global state */
322
323 typedef struct {
324 pn_proactor_t *proactor;
325 int threads;
326 lpool listeners; /* waiting for PN_PROACTOR_LISTEN */
327 cpool connections_active; /* active in the proactor */
328 cpool connections_idle; /* released and can be reused */
329
330 pthread_mutex_t lock;
331 bool shutdown;
332 } global;
333
334 void global_init(global *g, int threads) {
335 memset(g, 0, sizeof(*g));
336 g->proactor = pn_proactor();
337 g->threads = threads;
338 lpool_init(&g->listeners, g->threads/2, listener_ctx_free);
339 cpool_init(&g->connections_active, g->threads/2, connection_ctx_free);
340 cpool_init(&g->connections_idle, g->threads/2, connection_ctx_free);
341 pthread_mutex_init(&g->lock, NULL);
342 }
343
344 void global_destroy(global *g) {
345 pn_proactor_free(g->proactor);
346 lpool_destroy(&g->listeners);
347 cpool_destroy(&g->connections_active);
348 cpool_destroy(&g->connections_idle);
349 pthread_mutex_destroy(&g->lock);
350 }
351
352 bool global_get_shutdown(global *g) {
353 pthread_mutex_lock(&g->lock);
354 bool ret = g->shutdown;
355 pthread_mutex_unlock(&g->lock);
356 return ret;
357 }
358
359 void global_set_shutdown(global *g, bool set) {
360 pthread_mutex_lock(&g->lock);
361 g->shutdown = set;
362 pthread_mutex_unlock(&g->lock);
363 }
364
365 void global_connect(global *g) {
366 char a[PN_MAX_ADDR];
367 lpool_addr(&g->listeners, a, sizeof(a));
368 cpool_connect(&g->connections_active, g->proactor, a);
369 }
370
371 /* Return true with given probability */
372 static bool maybe(double probability) {
373 if (probability == 1.0) return true;
374 return rand() < (probability * RAND_MAX);
375 }
376
377 /* Run random activities that can be done from any thread. */
378 static void global_do_stuff(global *g) {
379 if (maybe(0.5)) global_connect(g);
380 if (maybe(0.3)) lpool_listen(&g->listeners, g->proactor);
381 if (maybe(0.1)) lpool_close(&g->listeners);
382 if (maybe(0.5)) cpool_wake(&g->connections_active);
383 if (maybe(0.5)) cpool_wake(&g->connections_idle);
384 if (action_enabled[A_TIMEOUT] && maybe(0.5)) {
385 debuga(A_TIMEOUT, g->proactor);
386 pn_proactor_set_timeout(g->proactor, rand() % TIMEOUT_MAX);
387 }
388 if (action_enabled[A_CANCEL_TIMEOUT] && maybe(0.1)) {
389 debuga(A_CANCEL_TIMEOUT, g->proactor);
390 pn_proactor_cancel_timeout(g->proactor);
391 }
392 }
393
394 static void* user_thread(void* void_g) {
395 debug("user_thread start");
396 global *g = (global*)void_g;
397 while (!global_get_shutdown(g)) {
398 global_do_stuff(g);
399 millisleep(rand() % SLEEP_MAX);
400 }
401 debug("user_thread end");
402 return NULL;
403 }
404
405 static bool handle(global *g, pn_event_t *e) {
406 pn_connection_t *c = pn_event_connection(e);
407 connection_ctx *cctx = c ? (connection_ctx*)pn_connection_get_context(c) : NULL;
408 pn_listener_t *l = pn_event_listener(e);
409 listener_ctx *lctx = l ? (listener_ctx*)pn_listener_get_context(l) : NULL;
410
411 switch (pn_event_type(e)) {
412
413 case PN_PROACTOR_TIMEOUT: {
414 if (global_get_shutdown(g)) return false;
415 global_do_stuff(g);
416 break;
417 }
418
419 case PN_LISTENER_OPEN: {
420 pthread_mutex_lock(&lctx->lock);
421 if (lctx->pn_listener) {
422 pn_netaddr_str(pn_listener_addr(lctx->pn_listener), lctx->addr, sizeof(lctx->addr));
423 }
424 debug("[%p] listening on %s", lctx->pn_listener, lctx->addr);
425 pthread_mutex_unlock(&lctx->lock);
426 cpool_connect(&g->connections_active, g->proactor, lctx->addr); /* Initial connection */
427 break;
428 }
429 case PN_LISTENER_CLOSE: {
430 pthread_mutex_lock(&lctx->lock);
431 lctx->pn_listener = NULL;
432 pthread_mutex_unlock(&lctx->lock);
433 lpool_unref(lctx);
434 break;
435 }
436
437 case PN_CONNECTION_WAKE: {
438 if (!action_enabled[A_CLOSE_CONNECT] && maybe(0.5)) pn_connection_close(c);
439 /* TODO aconway 2018-05-16: connection release/re-use */
440 break;
441 }
442
443 case PN_TRANSPORT_CLOSED: {
444 if (cctx) {
445 /* Required locking: mark connection as closed, no more wake calls */
446 pthread_mutex_lock(&cctx->lock);
447 cctx->pn_connection = NULL;
448 pthread_mutex_unlock(&cctx->lock);
449 cpool_unref(cctx);
450 }
451 break;
452 }
453 // Following events are used to shut down the threaderciser
454
455 case PN_PROACTOR_INACTIVE: { /* Shutting down */
456 pn_proactor_interrupt(g->proactor); /* Interrupt remaining threads */
457 return false;
458 }
459 case PN_PROACTOR_INTERRUPT:
460 pn_proactor_interrupt(g->proactor); /* Pass the interrupt along */
461 return false;
462
463 default:
464 break;
465 }
466 return true;
467 }
468
469 static void* proactor_thread(void* void_g) {
470 debug("proactor_thread start");
471 global *g = (global*) void_g;
472 bool ok = true;
473 while (ok) {
474 pn_event_batch_t *events = pn_proactor_wait(g->proactor);
475 pn_event_t *e;
476 while (ok && (e = pn_event_batch_next(events))) {
477 ok = ok && handle(g, e);
478 }
479 pn_proactor_done(g->proactor, events);
480 }
481 debug("proactor_thread end");
482 return NULL;
483 }
484
485 /* Command line arguments */
486
487 static const int default_runtime = 1;
488 static const int default_threads = 8;
489
490 void usage(const char **argv, const char **arg) {
491 fprintf(stderr, "usage: %s [options]\n", argv[0]);
492 fprintf(stderr, " -time TIME: total run-time in seconds (default %d)\n", default_runtime);
493 fprintf(stderr, " -threads THREADS: total number of threads (default %d)\n", default_threads);
494 fprintf(stderr, " -debug: print debug messages\n");
495 fprintf(stderr, "Flags to enable specific actions (all enabled by default)\n");
496 fprintf(stderr, " ");
497 for (int i = 0; i < (int)action_size; ++i) fprintf(stderr, " -%s", action_name[i]);
498 fprintf(stderr, "\n");
499 fprintf(stderr, "Flags to disable specific actions (all enabled by default)\n");
500 for (int i = 0; i < (int)action_size; ++i) fprintf(stderr, " -no-%s", action_name[i]);
501 fprintf(stderr, "\n\n");
502 fprintf(stderr, "bad argument: %s\n", *arg);
503 exit(1);
504 }
505
506 size_t find_action(const char *name, const char **argv, const char **arg) {
507 for (size_t i = 0; i < action_size; ++i) {
508 if (!strcmp(name, action_name[i])) return i;
509 }
510 usage(argv, arg);
511 return 0; /* Can't get here. */
512 }
513
514 int main(int argc, const char* argv[]) {
515 const char **arg = argv + 1;
516 const char **end = argv + argc;
517 int runtime = default_runtime;
518 int threads = default_threads;
519 bool action_default = true;
520 for (size_t i = 0; i < action_size; ++i) action_enabled[i] = action_default;
521
522 while (arg < end) {
523 if (!strcmp(*arg, "-time") && ++arg < end) {
524 runtime = atoi(*arg);
525 if (runtime <= 0) usage(argv, arg);
526 }
527 else if (!strcmp(*arg, "-threads") && ++arg < end) {
528 threads = atoi(*arg);
529 if (threads <= 0) usage(argv, arg);
530 if (threads % 2) threads += 1; /* Round up to even: half proactor, half user */
531 }
532 else if (!strcmp(*arg, "-debug")) {
533 debug_enable = true;
534 }
535 else if (!strncmp(*arg, "-no-", 4)) {
536 action_enabled[find_action((*arg) + 4, argv, arg)] = false;
537 }
538 else if (!strncmp(*arg, "-", 1)) {
539 if (action_default) { /* First enable-action flag, switch to default-off */
540 action_default = false;
541 for (size_t i = 0; i < action_size; ++i) action_enabled[i] = action_default;
542 }
543 action_enabled[find_action((*arg) + 1, argv, arg)] = true;
544 }
545 else {
546 usage(argv, arg);
547 }
548 ++arg;
549 }
550
551 /* Set up global state, start threads */
552
553 printf("threaderciser start: threads=%d, time=%d, actions=[", threads, runtime);
554 bool comma = false;
555 for (size_t i = 0; i < action_size; ++i) {
556 if (action_enabled[i]) {
557 printf("%s%s", (comma ? ", " : ""), action_name[i]);
558 comma = true;
559 }
560 }
561 printf("]\n");
562 fflush(stdout);
563
564 global g;
565 global_init(&g, threads);
566 lpool_listen(&g.listeners, g.proactor); /* Start initial listener */
567
568 pthread_t *user_threads = (pthread_t*)calloc(threads/2, sizeof(pthread_t));
569 pthread_t *proactor_threads = (pthread_t*)calloc(threads/2, sizeof(pthread_t));
570 int i;
571 for (i = 0; i < threads/2; ++i) {
572 pthread_create(&user_threads[i], NULL, user_thread, &g);
573 pthread_create(&proactor_threads[i], NULL, proactor_thread, &g);
574 }
575 millisleep(runtime*1000);
576
577 debug("shut down");
578 global_set_shutdown(&g, true);
579 void *ignore;
580 for (i = 0; i < threads/2; ++i) pthread_join(user_threads[i], &ignore);
581 debug("disconnect");
582 pn_proactor_disconnect(g.proactor, NULL);
583 for (i = 0; i < threads/2; ++i) pthread_join(proactor_threads[i], &ignore);
584
585 free(user_threads);
586 free(proactor_threads);
587 global_destroy(&g);
588 }