Debian Codegraph @

crt/aws-c-io/tests/event_loop_test.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5
6 #include <aws/common/atomics.h>
7 #include <aws/common/clock.h>
8 #include <aws/common/condition_variable.h>
9 #include <aws/common/system_info.h>
10 #include <aws/common/task_scheduler.h>
11 #include <aws/common/thread.h>
12 #include <aws/io/event_loop.h>
13 #include <aws/io/private/event_loop_impl.h>
14 #include <aws/testing/aws_test_harness.h>
15
16 struct task_args {
17 bool invoked;
18 bool was_in_thread;
19 aws_thread_id_t thread_id;
20 struct aws_event_loop *loop;
21 struct aws_event_loop_group *el_group;
22 enum aws_task_status status;
23 struct aws_mutex mutex;
24 struct aws_condition_variable condition_variable;
25 struct aws_atomic_var thread_complete;
26 };
27
28 static void s_test_task(struct aws_task *task, void *user_data, enum aws_task_status status) {
29 (void)task;
30 struct task_args *args = user_data;
31
32 aws_mutex_lock(&args->mutex);
33 args->thread_id = aws_thread_current_thread_id();
34 args->invoked = true;
35 args->status = status;
36 args->was_in_thread = aws_event_loop_thread_is_callers_thread(args->loop);
37 aws_mutex_unlock((&args->mutex));
38 aws_condition_variable_notify_one(&args->condition_variable);
39 }
40
41 static bool s_task_ran_predicate(void *args) {
42 struct task_args *task_args = args;
43 return task_args->invoked;
44 }
45
46 static bool s_validate_thread_id_equal(aws_thread_id_t thread_id, bool expected_result) {
47 // The dispatch queue will schedule tasks on thread pools, it is unpredictable which thread we run the task on,
48 // therefore we do not validate the thread id for dispatch queue.
49 if (aws_event_loop_get_default_type() != AWS_EVENT_LOOP_DISPATCH_QUEUE) {
50 return aws_thread_thread_id_equal(thread_id, aws_thread_current_thread_id());
51 }
52 return expected_result;
53 }
54
55 static void s_dispatch_queue_sleep(void) {
56 /*
57 * The dispatch queue can have a block waiting to execute up to one second in the future. This iteration block needs
58 * to run to clean up memory allocated to the paired scheduled iteration entry. We wait for two seconds to allow the
59 * Apple dispatch queue to run its delayed blocks and clean up for memory release purposes.
60 */
61 #if defined(AWS_USE_APPLE_DISPATCH_QUEUE) || defined(AWS_USE_APPLE_NETWORK_FRAMEWORK)
62 aws_thread_current_sleep(2000000000);
63 #endif
64 }
65
66 /*
67 * Test that a scheduled task from a non-event loop owned thread executes.
68 */
69 static int s_test_event_loop_xthread_scheduled_tasks_execute(struct aws_allocator *allocator, void *ctx) {
70
71 (void)ctx;
72 struct aws_event_loop *event_loop = aws_event_loop_new_default(allocator, aws_high_res_clock_get_ticks);
73
74 ASSERT_NOT_NULL(event_loop, "Event loop creation failed with error: %s", aws_error_debug_str(aws_last_error()));
75 ASSERT_SUCCESS(aws_event_loop_run(event_loop));
76
77 struct task_args task_args = {
78 .condition_variable = AWS_CONDITION_VARIABLE_INIT,
79 .mutex = AWS_MUTEX_INIT,
80 .invoked = false,
81 .was_in_thread = false,
82 .status = -1,
83 .loop = event_loop,
84 .thread_id = 0,
85 };
86
87 struct aws_task task;
88 aws_task_init(&task, s_test_task, &task_args, "xthread_scheduled_tasks_execute");
89
90 /* Test "future" tasks */
91 ASSERT_SUCCESS(aws_mutex_lock(&task_args.mutex));
92
93 uint64_t now;
94 ASSERT_SUCCESS(aws_event_loop_current_clock_time(event_loop, &now));
95 aws_event_loop_schedule_task_future(event_loop, &task, now);
96
97 ASSERT_SUCCESS(aws_condition_variable_wait_pred(
98 &task_args.condition_variable, &task_args.mutex, s_task_ran_predicate, &task_args));
99 ASSERT_TRUE(task_args.invoked);
100 aws_mutex_unlock(&task_args.mutex);
101
102 ASSERT_FALSE(s_validate_thread_id_equal(task_args.thread_id, false));
103
104 /* Test "now" tasks */
105 task_args.invoked = false;
106 ASSERT_SUCCESS(aws_mutex_lock(&task_args.mutex));
107
108 aws_event_loop_schedule_task_now(event_loop, &task);
109
110 ASSERT_SUCCESS(aws_condition_variable_wait_pred(
111 &task_args.condition_variable, &task_args.mutex, s_task_ran_predicate, &task_args));
112 ASSERT_TRUE(task_args.invoked);
113 aws_mutex_unlock(&task_args.mutex);
114
115 aws_event_loop_destroy(event_loop);
116
117 return AWS_OP_SUCCESS;
118 }
119
120 AWS_TEST_CASE(event_loop_xthread_scheduled_tasks_execute, s_test_event_loop_xthread_scheduled_tasks_execute)
121
122 static bool s_test_cancel_thread_task_predicate(void *args) {
123 struct task_args *task_args = args;
124 return task_args->invoked;
125 }
126 /*
127 * Test that a scheduled task from a non-event loop owned thread executes.
128 */
129 static int s_test_event_loop_canceled_tasks_run_in_el_thread(struct aws_allocator *allocator, void *ctx) {
130
131 (void)ctx;
132 struct aws_event_loop *event_loop = aws_event_loop_new_default(allocator, aws_high_res_clock_get_ticks);
133
134 ASSERT_NOT_NULL(event_loop, "Event loop creation failed with error: %s", aws_error_debug_str(aws_last_error()));
135 ASSERT_SUCCESS(aws_event_loop_run(event_loop));
136
137 struct task_args task1_args = {
138 .condition_variable = AWS_CONDITION_VARIABLE_INIT,
139 .mutex = AWS_MUTEX_INIT,
140 .invoked = false,
141 .was_in_thread = false,
142 .status = -1,
143 .loop = event_loop,
144 .thread_id = 0,
145 };
146
147 struct task_args task2_args = {
148 .condition_variable = AWS_CONDITION_VARIABLE_INIT,
149 .mutex = AWS_MUTEX_INIT,
150 .invoked = false,
151 .was_in_thread = false,
152 .status = -1,
153 .loop = event_loop,
154 .thread_id = 0,
155 };
156
157 struct aws_task task1;
158 aws_task_init(&task1, s_test_task, &task1_args, "canceled_tasks_run_in_el_thread1");
159 struct aws_task task2;
160 aws_task_init(&task2, s_test_task, &task2_args, "canceled_tasks_run_in_el_thread2");
161
162 aws_event_loop_schedule_task_now(event_loop, &task1);
163 uint64_t now;
164 ASSERT_SUCCESS(aws_event_loop_current_clock_time(event_loop, &now));
165 aws_event_loop_schedule_task_future(event_loop, &task2, now + 10000000000);
166
167 ASSERT_FALSE(aws_event_loop_thread_is_callers_thread(event_loop));
168
169 ASSERT_SUCCESS(aws_mutex_lock(&task1_args.mutex));
170 ASSERT_SUCCESS(aws_condition_variable_wait_pred(
171 &task1_args.condition_variable, &task1_args.mutex, s_task_ran_predicate, &task1_args));
172 ASSERT_TRUE(task1_args.invoked);
173 ASSERT_TRUE(task1_args.was_in_thread);
174
175 ASSERT_FALSE(s_validate_thread_id_equal(task1_args.thread_id, false));
176
177 ASSERT_INT_EQUALS(AWS_TASK_STATUS_RUN_READY, task1_args.status);
178 aws_mutex_unlock(&task1_args.mutex);
179
180 aws_event_loop_destroy(event_loop);
181
182 aws_mutex_lock(&task2_args.mutex);
183
184 ASSERT_SUCCESS(aws_condition_variable_wait_pred(
185 &task2_args.condition_variable, &task2_args.mutex, s_test_cancel_thread_task_predicate, &task2_args));
186 ASSERT_TRUE(task2_args.invoked);
187 aws_mutex_unlock(&task2_args.mutex);
188
189 ASSERT_TRUE(task2_args.was_in_thread);
190 ASSERT_TRUE(s_validate_thread_id_equal(task2_args.thread_id, true));
191 ASSERT_INT_EQUALS(AWS_TASK_STATUS_CANCELED, task2_args.status);
192
193 s_dispatch_queue_sleep();
194
195 return AWS_OP_SUCCESS;
196 }
197
198 AWS_TEST_CASE(event_loop_canceled_tasks_run_in_el_thread, s_test_event_loop_canceled_tasks_run_in_el_thread)
199
200 #if AWS_ENABLE_IO_COMPLETION_PORTS
201
202 int aws_pipe_get_unique_name(char *dst, size_t dst_size);
203
204 /* Open read/write handles to a pipe with support for async (overlapped) read and write */
205 static int s_async_pipe_init(struct aws_io_handle *read_handle, struct aws_io_handle *write_handle) {
206 char pipe_name[256];
207 ASSERT_SUCCESS(aws_pipe_get_unique_name(pipe_name, sizeof(pipe_name)));
208
209 write_handle->data.handle = CreateNamedPipeA(
210 pipe_name, /* lpName */
211 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE, /* dwOpenMode */
212 PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS, /* dwPipeMode */
213 1, /* nMaxInstances */
214 2048, /* nOutBufferSize */
215 2048, /* nInBufferSize */
216 0, /* nDefaultTimeOut */
217 NULL); /* lpSecurityAttributes */
218
219 ASSERT_TRUE(write_handle->data.handle != INVALID_HANDLE_VALUE);
220
221 read_handle->data.handle = CreateFileA(
222 pipe_name, /* lpFileName */
223 GENERIC_READ, /* dwDesiredAccess */
224 0, /* dwShareMode */
225 NULL, /* lpSecurityAttributes */
226 OPEN_EXISTING, /* dwCreationDisposition */
227 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, /* dwFlagsAndAttributes */
228 NULL); /* hTemplateFile */
229
230 ASSERT_TRUE(read_handle->data.handle != INVALID_HANDLE_VALUE);
231
232 return AWS_OP_SUCCESS;
233 }
234
235 static void s_async_pipe_clean_up(struct aws_io_handle *read_handle, struct aws_io_handle *write_handle) {
236 CloseHandle(read_handle->data.handle);
237 CloseHandle(write_handle->data.handle);
238 }
239
240 struct overlapped_completion_data {
241 struct aws_mutex mutex;
242 struct aws_condition_variable condition_variable;
243 bool signaled;
244 struct aws_event_loop *event_loop;
245 struct aws_overlapped *overlapped;
246 int status_code;
247 size_t num_bytes_transferred;
248 };
249
250 static int s_overlapped_completion_data_init(struct overlapped_completion_data *data) {
251 AWS_ZERO_STRUCT(*data);
252 ASSERT_SUCCESS(aws_mutex_init(&data->mutex));
253 ASSERT_SUCCESS(aws_condition_variable_init(&data->condition_variable));
254 return AWS_OP_SUCCESS;
255 }
256
257 static void s_overlapped_completion_data_clean_up(struct overlapped_completion_data *data) {
258 aws_condition_variable_clean_up(&data->condition_variable);
259 aws_mutex_clean_up(&data->mutex);
260 }
261
262 static void s_on_overlapped_operation_complete(
263 struct aws_event_loop *event_loop,
264 struct aws_overlapped *overlapped,
265 int status_code,
266 size_t num_bytes_transferred) {
267
268 struct overlapped_completion_data *data = overlapped->user_data;
269 aws_mutex_lock(&data->mutex);
270 data->event_loop = event_loop;
271 data->overlapped = overlapped;
272 data->status_code = status_code;
273 data->num_bytes_transferred = num_bytes_transferred;
274 data->signaled = true;
275 aws_condition_variable_notify_one(&data->condition_variable);
276 aws_mutex_unlock(&data->mutex);
277 }
278
279 static bool s_overlapped_completion_predicate(void *args) {
280 struct overlapped_completion_data *data = args;
281 return data->signaled;
282 }
283
284 static int s_test_event_loop_completion_events(struct aws_allocator *allocator, void *ctx) {
285 (void)ctx;
286
287 /* Start event-loop */
288 struct aws_event_loop *event_loop = aws_event_loop_new_default(allocator, aws_high_res_clock_get_ticks);
289 ASSERT_NOT_NULL(event_loop);
290 ASSERT_SUCCESS(aws_event_loop_run(event_loop));
291
292 /* Open a pipe */
293 struct aws_io_handle read_handle;
294 struct aws_io_handle write_handle;
295 ASSERT_SUCCESS(s_async_pipe_init(&read_handle, &write_handle));
296
297 /* Connect to event-loop */
298 ASSERT_SUCCESS(aws_event_loop_connect_handle_to_io_completion_port(event_loop, &write_handle));
299
300 /* Set up an async (overlapped) write that will result in s_on_overlapped_operation_complete() getting run
301 * and filling out `completion_data` */
302 struct overlapped_completion_data completion_data;
303 s_overlapped_completion_data_init(&completion_data);
304
305 struct aws_overlapped overlapped;
306 aws_overlapped_init(&overlapped, s_on_overlapped_operation_complete, &completion_data);
307
308 /* Do async write */
309 const char msg[] = "Cherry Pie";
310 bool write_success =
311 WriteFile(write_handle.data.handle, msg, sizeof(msg), NULL, aws_overlapped_to_windows_overlapped(&overlapped));
312 ASSERT_TRUE(write_success || GetLastError() == ERROR_IO_PENDING);
313
314 /* Wait for completion callbacks */
315 ASSERT_SUCCESS(aws_mutex_lock(&completion_data.mutex));
316 ASSERT_SUCCESS(aws_condition_variable_wait_pred(
317 &completion_data.condition_variable,
318 &completion_data.mutex,
319 s_overlapped_completion_predicate,
320 &completion_data));
321 ASSERT_SUCCESS(aws_mutex_unlock(&completion_data.mutex));
322
323 /* Assert that the aws_event_loop_on_completion_fn passed the appropriate args */
324 ASSERT_PTR_EQUALS(event_loop, completion_data.event_loop);
325 ASSERT_PTR_EQUALS(&overlapped, completion_data.overlapped);
326 ASSERT_INT_EQUALS(0, completion_data.status_code); /* Check status code for I/O operation */
327 ASSERT_INT_EQUALS(sizeof(msg), completion_data.num_bytes_transferred);
328
329 /* Shut it all down */
330 s_overlapped_completion_data_clean_up(&completion_data);
331 s_async_pipe_clean_up(&read_handle, &write_handle);
332 aws_event_loop_destroy(event_loop);
333
334 return AWS_OP_SUCCESS;
335 }
336
337 AWS_TEST_CASE(event_loop_completion_events, s_test_event_loop_completion_events)
338
339 #else /* !AWS_ENABLE_IO_COMPLETION_PORTS */
340
341 # include <unistd.h>
342
343 int aws_open_nonblocking_posix_pipe(int pipe_fds[2]);
344
345 /* Define simple pipe for testing. */
346 int simple_pipe_open(struct aws_io_handle *read_handle, struct aws_io_handle *write_handle) {
347 AWS_ZERO_STRUCT(*read_handle);
348 AWS_ZERO_STRUCT(*write_handle);
349
350 int pipe_fds[2];
351 ASSERT_SUCCESS(aws_open_nonblocking_posix_pipe(pipe_fds));
352
353 read_handle->data.fd = pipe_fds[0];
354 write_handle->data.fd = pipe_fds[1];
355
356 return AWS_OP_SUCCESS;
357 }
358 void simple_pipe_close(struct aws_io_handle *read_handle, struct aws_io_handle *write_handle) {
359 close(read_handle->data.fd);
360 close(write_handle->data.fd);
361 }
362
363 /* return number of bytes written */
364 size_t simple_pipe_write(struct aws_io_handle *handle, const uint8_t *src, size_t src_size) {
365 ssize_t write_val = write(handle->data.fd, src, src_size);
366 return (write_val < 0) ? 0 : write_val;
367 }
368
369 /* return number of bytes read */
370 size_t simple_pipe_read(struct aws_io_handle *handle, uint8_t *dst, size_t dst_size) {
371 ssize_t read_val = read(handle->data.fd, dst, dst_size);
372 return (read_val < 0) ? 0 : read_val;
373 }
374
375 struct unsubrace_data {
376 struct aws_event_loop *event_loop;
377
378 struct aws_io_handle read_handle[2];
379 struct aws_io_handle write_handle[2];
380 bool is_writable[2];
381 bool wrote_to_both_pipes;
382 bool is_unsubscribed;
383
384 struct aws_task task;
385
386 struct aws_mutex mutex;
387 struct aws_condition_variable condition_variable;
388 bool done;
389 int result_code;
390 };
391
392 void s_unsubrace_error(struct unsubrace_data *data) {
393 aws_mutex_lock(&data->mutex);
394 data->result_code = -1;
395 data->done = true;
396 aws_condition_variable_notify_one(&data->condition_variable);
397 aws_mutex_unlock(&data->mutex);
398 }
399
400 void s_unsubrace_done(struct unsubrace_data *data) {
401 aws_mutex_lock(&data->mutex);
402 data->done = true;
403 aws_condition_variable_notify_one(&data->condition_variable);
404 aws_mutex_unlock(&data->mutex);
405 }
406
407 /* Wait until both pipes are writable, then write data to both of them.
408 * This make it likely that both pipes receive events in the same iteration of the event-loop. */
409 void s_unsubrace_on_writable_event(
410 struct aws_event_loop *event_loop,
411 struct aws_io_handle *handle,
412 int events,
413 void *user_data) {
414
415 (void)event_loop;
416 struct unsubrace_data *data = user_data;
417
418 /* There should be no events after unsubscribe */
419 if (data->is_unsubscribed) {
420 s_unsubrace_error(data);
421 return;
422 }
423
424 if (!(events & AWS_IO_EVENT_TYPE_WRITABLE)) {
425 return;
426 }
427
428 if (data->wrote_to_both_pipes) {
429 return;
430 }
431
432 bool all_writable = true;
433
434 for (int i = 0; i < 2; ++i) {
435 if (&data->write_handle[i] == handle) {
436 data->is_writable[i] = true;
437 }
438
439 if (!data->is_writable[i]) {
440 all_writable = false;
441 }
442 }
443
444 if (!all_writable) {
445 return;
446 }
447
448 for (int i = 0; i < 2; ++i) {
449 uint8_t buffer[] = "abc";
450 size_t bytes_written = simple_pipe_write(&data->write_handle[i], buffer, 3);
451 if (bytes_written == 0) {
452 s_unsubrace_error(data);
453 return;
454 }
455 }
456
457 data->wrote_to_both_pipes = true;
458 }
459
460 void s_unsubrace_done_task(struct aws_task *task, void *arg, enum aws_task_status status) {
461 (void)task;
462 struct unsubrace_data *data = arg;
463
464 if (status != AWS_TASK_STATUS_RUN_READY) {
465 s_unsubrace_error(data);
466 return;
467 }
468
469 s_unsubrace_done(data);
470 }
471
472 /* Both pipes should have a readable event on the way.
473 * The first pipe to get the event closes both pipes.
474 * Since both pipes are unsubscribed, the second readable event shouldn't be delivered */
475 void s_unsubrace_on_readable_event(
476 struct aws_event_loop *event_loop,
477 struct aws_io_handle *handle,
478 int events,
479 void *user_data) {
480
481 (void)handle;
482 struct unsubrace_data *data = user_data;
483 int err;
484
485 if (data->is_unsubscribed) {
486 s_unsubrace_error(data);
487 return;
488 }
489
490 if (!(events & AWS_IO_EVENT_TYPE_READABLE)) {
491 return;
492 }
493
494 for (int i = 0; i < 2; ++i) {
495 err = aws_event_loop_unsubscribe_from_io_events(event_loop, &data->read_handle[i]);
496 if (err) {
497 s_unsubrace_error(data);
498 return;
499 }
500
501 err = aws_event_loop_unsubscribe_from_io_events(event_loop, &data->write_handle[i]);
502 if (err) {
503 s_unsubrace_error(data);
504 return;
505 }
506
507 simple_pipe_close(&data->read_handle[i], &data->write_handle[i]);
508 }
509
510 /* Zero out the handles so that further accesses to the closed pipe are extra likely to cause crashes */
511 AWS_ZERO_ARRAY(data->read_handle);
512 AWS_ZERO_ARRAY(data->write_handle);
513
514 data->is_unsubscribed = true;
515
516 /* Have a short delay before ending test. Any events that fire during that delay would be an error. */
517 uint64_t time_ns;
518 err = aws_event_loop_current_clock_time(data->event_loop, &time_ns);
519 if (err) {
520 s_unsubrace_error(data);
521 return;
522 }
523 time_ns += aws_timestamp_convert(1, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL);
524
525 aws_task_init(&data->task, s_unsubrace_done_task, data, "unsubrace");
526 aws_event_loop_schedule_task_future(data->event_loop, &data->task, time_ns);
527 }
528
529 static void s_unsubrace_setup_task(struct aws_task *task, void *arg, enum aws_task_status status) {
530 (void)task;
531 struct unsubrace_data *data = arg;
532 int err;
533
534 if (status != AWS_TASK_STATUS_RUN_READY) {
535 s_unsubrace_error(data);
536 return;
537 }
538
539 for (int i = 0; i < 2; ++i) {
540 err = simple_pipe_open(&data->read_handle[i], &data->write_handle[i]);
541 if (err) {
542 s_unsubrace_error(data);
543 return;
544 }
545
546 err = aws_event_loop_subscribe_to_io_events(
547 data->event_loop, &data->write_handle[i], AWS_IO_EVENT_TYPE_WRITABLE, s_unsubrace_on_writable_event, data);
548 if (err) {
549 s_unsubrace_error(data);
550 return;
551 }
552
553 err = aws_event_loop_subscribe_to_io_events(
554 data->event_loop, &data->read_handle[i], AWS_IO_EVENT_TYPE_READABLE, s_unsubrace_on_readable_event, data);
555 if (err) {
556 s_unsubrace_error(data);
557 return;
558 }
559 }
560 }
561
562 static bool s_unsubrace_predicate(void *arg) {
563 struct unsubrace_data *data = arg;
564 return data->done;
565 }
566
567 /* Regression test: Ensure that a handle cannot receive an event after it's been unsubscribed.
568 * This was occuring in the case that there were events on two handles in the same event-loop tick,
569 * and the first handle to receive its event unsubscribed the other handle.
570 * Shortname: unsubrace */
571 static int s_test_event_loop_no_events_after_unsubscribe(struct aws_allocator *allocator, void *ctx) {
572 (void)ctx;
573 struct aws_event_loop *event_loop = aws_event_loop_new_default(allocator, aws_high_res_clock_get_ticks);
574 ASSERT_NOT_NULL(event_loop);
575
576 ASSERT_SUCCESS(aws_event_loop_run(event_loop));
577
578 struct unsubrace_data data = {
579 .mutex = AWS_MUTEX_INIT,
580 .condition_variable = AWS_CONDITION_VARIABLE_INIT,
581 .event_loop = event_loop,
582 };
583
584 aws_task_init(&data.task, s_unsubrace_setup_task, &data, "no_events_after_unsubscribe");
585 aws_event_loop_schedule_task_now(event_loop, &data.task);
586
587 ASSERT_SUCCESS(aws_mutex_lock(&data.mutex));
588 ASSERT_SUCCESS(
589 aws_condition_variable_wait_pred(&data.condition_variable, &data.mutex, s_unsubrace_predicate, &data));
590 ASSERT_SUCCESS(aws_mutex_unlock(&data.mutex));
591
592 ASSERT_SUCCESS(data.result_code);
593
594 aws_event_loop_destroy(event_loop);
595
596 return AWS_OP_SUCCESS;
597 }
598
599 AWS_TEST_CASE(event_loop_no_events_after_unsubscribe, s_test_event_loop_no_events_after_unsubscribe)
600
601 /* For testing logic that must occur on the event-loop thread.
602 * The main thread should give the tester an array of state functions (last entry should be NULL),
603 * then kick off the tester and then wait for it to be done.
604 * Each function should return one of:
605 * - AWS_OP_SUCCESS: continue to next state function
606 * - AWS_OP_ERRROR: fail the test
607 * - REMAIN_IN_STATE: try this state function again next time
608 */
609 struct thread_tester;
610 enum { REMAIN_IN_STATE = -2 };
611 typedef int(thread_tester_state_fn)(struct thread_tester *tester);
612
613 struct thread_tester {
614 struct aws_allocator *alloc;
615 struct aws_event_loop *event_loop;
616
617 bool done;
618 int error_code;
619 struct aws_mutex mutex;
620 struct aws_condition_variable condition_variable;
621
622 thread_tester_state_fn **state_functions;
623 size_t current_state;
624 size_t last_printed_state;
625
626 /* data for tests */
627 struct aws_io_handle read_handle;
628 struct aws_io_handle write_handle;
629 int read_handle_event_counts[AWS_IO_EVENT_TYPE_ERROR + 1];
630 int write_handle_event_counts[AWS_IO_EVENT_TYPE_ERROR + 1];
631
632 enum { TIMER_NOT_SET, TIMER_WAITING, TIMER_DONE } timer_state;
633 struct aws_task timer_task;
634 };
635
636 static void s_thread_tester_abort(struct thread_tester *tester) {
637 aws_mutex_lock(&tester->mutex);
638 tester->error_code = AWS_OP_ERR;
639 tester->done = true;
640 aws_condition_variable_notify_one(&tester->condition_variable);
641 aws_mutex_unlock(&tester->mutex);
642 }
643
644 static bool s_print_state_transitions = false; /* Set this true to print state transitions */
645
646 static void s_thread_tester_print_state(struct thread_tester *tester, const char *state_name) {
647 if (tester->last_printed_state != tester->current_state) {
648 if (s_print_state_transitions) {
649 printf("entering state[%zu]: %s\n", tester->current_state, state_name);
650 }
651 tester->last_printed_state = tester->current_state;
652 }
653 }
654 # define PRINT_STATE() s_thread_tester_print_state(tester, __func__)
655
656 static void s_thread_tester_update(struct thread_tester *tester) {
657 thread_tester_state_fn *current_fn;
658 while (true) {
659 current_fn = tester->state_functions[tester->current_state];
660
661 if (!current_fn) {
662 /* We've reached the final state, success */
663 aws_mutex_lock(&tester->mutex);
664 tester->error_code = AWS_OP_SUCCESS;
665 tester->done = true;
666 aws_condition_variable_notify_one(&tester->condition_variable);
667 aws_mutex_unlock(&tester->mutex);
668 return;
669 }
670
671 int err = current_fn(tester);
672
673 if (err == AWS_OP_SUCCESS) {
674 /* Go to next state, loop again */
675 tester->current_state++;
676
677 } else if (err == REMAIN_IN_STATE) {
678 /* End loop, wait for update function to be invoked again */
679 return;
680
681 } else /* AWS_OP_ERR */ {
682 /* End loop, end tester, end it all */
683 s_thread_tester_abort(tester);
684 return;
685 }
686 }
687 }
688
689 static void s_thread_tester_update_task(struct aws_task *task, void *arg, enum aws_task_status status) {
690 (void)task;
691 struct thread_tester *tester = arg;
692
693 if (status != AWS_TASK_STATUS_RUN_READY) {
694 return s_thread_tester_abort(tester);
695 }
696
697 s_thread_tester_update(tester);
698 }
699
700 static bool s_thread_tester_pred(void *arg) {
701 struct thread_tester *tester = arg;
702 return tester->done;
703 }
704
705 static void s_timer_done_task(struct aws_task *task, void *arg, enum aws_task_status status) {
706 (void)task;
707 struct thread_tester *tester = arg;
708
709 if (status != AWS_TASK_STATUS_RUN_READY) {
710 return s_thread_tester_abort(tester);
711 }
712
713 tester->timer_state = TIMER_DONE;
714 s_thread_tester_update(tester);
715 }
716
717 static int s_thread_tester_run(struct aws_allocator *alloc, thread_tester_state_fn *state_functions[]) {
718
719 /* Set up tester */
720 struct thread_tester tester = {
721 .alloc = alloc,
722 .event_loop = aws_event_loop_new_default(alloc, aws_high_res_clock_get_ticks),
723 .mutex = AWS_MUTEX_INIT,
724 .condition_variable = AWS_CONDITION_VARIABLE_INIT,
725 .state_functions = state_functions,
726 .last_printed_state = -1,
727 };
728
729 ASSERT_NOT_NULL(tester.event_loop);
730 ASSERT_SUCCESS(aws_event_loop_run(tester.event_loop));
731
732 /* Set up data to test with */
733 ASSERT_SUCCESS(simple_pipe_open(&tester.read_handle, &tester.write_handle));
734 aws_task_init(&tester.timer_task, s_timer_done_task, &tester, "timer_done");
735
736 /* Wait for tester to finish running its state functions on the event-loop thread */
737 aws_mutex_lock(&tester.mutex);
738 struct aws_task task;
739 aws_task_init(&task, s_thread_tester_update_task, &tester, "thread_tester_update");
740 aws_event_loop_schedule_task_now(tester.event_loop, &task);
741 aws_condition_variable_wait_pred(&tester.condition_variable, &tester.mutex, s_thread_tester_pred, &tester);
742 aws_mutex_unlock(&tester.mutex);
743
744 /* Clean up tester*/
745 aws_event_loop_destroy(tester.event_loop);
746
747 /* Clean up data */
748 simple_pipe_close(&tester.read_handle, &tester.write_handle);
749
750 /* Return tester results */
751 return tester.error_code;
752 }
753
754 /* Count how many times each type of event fires on the readable and writable handles */
755 static void s_io_event_counter(
756 struct aws_event_loop *event_loop,
757 struct aws_io_handle *handle,
758 int events,
759 void *user_data) {
760
761 (void)event_loop;
762 (void)handle;
763 struct thread_tester *tester = user_data;
764
765 int *event_counts;
766 if (handle == &tester->read_handle) {
767 event_counts = tester->read_handle_event_counts;
768
769 } else if (handle == &tester->write_handle) {
770 event_counts = tester->write_handle_event_counts;
771
772 } else {
773 return s_thread_tester_abort(tester);
774 }
775
776 for (int flag = 1; flag <= AWS_IO_EVENT_TYPE_ERROR; flag <<= 1) {
777 if (events & flag) {
778 event_counts[flag] += 1;
779 }
780 }
781
782 s_thread_tester_update(tester);
783 }
784
785 static int s_state_subscribe(struct thread_tester *tester) {
786 PRINT_STATE();
787 ASSERT_SUCCESS(aws_event_loop_subscribe_to_io_events(
788 tester->event_loop, &tester->read_handle, AWS_IO_EVENT_TYPE_READABLE, s_io_event_counter, tester));
789
790 ASSERT_SUCCESS(aws_event_loop_subscribe_to_io_events(
791 tester->event_loop, &tester->write_handle, AWS_IO_EVENT_TYPE_WRITABLE, s_io_event_counter, tester));
792
793 return AWS_OP_SUCCESS;
794 }
795
796 static int s_state_unsubscribe(struct thread_tester *tester) {
797 PRINT_STATE();
798 ASSERT_SUCCESS(aws_event_loop_unsubscribe_from_io_events(tester->event_loop, &tester->read_handle));
799 ASSERT_SUCCESS(aws_event_loop_unsubscribe_from_io_events(tester->event_loop, &tester->write_handle));
800 return AWS_OP_SUCCESS;
801 }
802
803 /* Remain in state until readable event fires, then reset readable event count and proceed to next state */
804 static int s_state_on_readable(struct thread_tester *tester) {
805 PRINT_STATE();
806
807 if (tester->read_handle_event_counts[AWS_IO_EVENT_TYPE_READABLE] == 0) {
808 return REMAIN_IN_STATE;
809 }
810
811 ASSERT_UINT_EQUALS(1, tester->read_handle_event_counts[AWS_IO_EVENT_TYPE_READABLE]);
812
813 tester->read_handle_event_counts[AWS_IO_EVENT_TYPE_READABLE] = 0;
814 return AWS_OP_SUCCESS;
815 }
816
817 /* Remain in state until writable event fires, then reset writable event count and proceed to next state. */
818 static int s_state_on_writable(struct thread_tester *tester) {
819 PRINT_STATE();
820
821 if (tester->write_handle_event_counts[AWS_IO_EVENT_TYPE_WRITABLE] == 0) {
822 return REMAIN_IN_STATE;
823 }
824
825 ASSERT_UINT_EQUALS(1, tester->write_handle_event_counts[AWS_IO_EVENT_TYPE_WRITABLE]);
826
827 tester->write_handle_event_counts[AWS_IO_EVENT_TYPE_WRITABLE] = 0;
828 return AWS_OP_SUCCESS;
829 }
830
831 static int s_state_fail_if_more_readable_events(struct thread_tester *tester) {
832 PRINT_STATE();
833 ASSERT_INT_EQUALS(0, tester->read_handle_event_counts[AWS_IO_EVENT_TYPE_READABLE]);
834
835 return AWS_OP_SUCCESS;
836 }
837
838 static int s_state_fail_if_more_writable_events(struct thread_tester *tester) {
839 PRINT_STATE();
840 ASSERT_INT_EQUALS(0, tester->write_handle_event_counts[AWS_IO_EVENT_TYPE_WRITABLE]);
841
842 return AWS_OP_SUCCESS;
843 }
844
845 /* Write some data to the pipe */
846 static int s_state_write_data(struct thread_tester *tester) {
847 PRINT_STATE();
848
849 const uint8_t data_to_copy[] = "abcdefghijklmnopqrstuvwxyz";
850 size_t num_bytes_written = simple_pipe_write(&tester->write_handle, data_to_copy, sizeof(data_to_copy));
851 ASSERT_UINT_EQUALS(sizeof(data_to_copy), num_bytes_written);
852
853 return AWS_OP_SUCCESS;
854 }
855
856 /* Read from pipe until no data remains */
857 static int s_state_read_until_blocked(struct thread_tester *tester) {
858 PRINT_STATE();
859
860 uint8_t buffer[512];
861 while (simple_pipe_read(&tester->read_handle, buffer, sizeof(buffer)) > 0) {
862 }
863
864 return AWS_OP_SUCCESS;
865 }
866
867 /* Entering the state starts a timer, and we remain in this state until the time completes */
868 static int s_state_wait_1sec(struct thread_tester *tester) {
869 PRINT_STATE();
870 uint64_t time_ns;
871 switch (tester->timer_state) {
872 case TIMER_NOT_SET:
873 time_ns = 0;
874 ASSERT_SUCCESS(aws_event_loop_current_clock_time(tester->event_loop, &time_ns));
875 time_ns += aws_timestamp_convert(1, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL);
876 aws_event_loop_schedule_task_future(tester->event_loop, &tester->timer_task, time_ns);
877
878 tester->timer_state = TIMER_WAITING;
879 return REMAIN_IN_STATE;
880
881 case TIMER_WAITING:
882 return REMAIN_IN_STATE;
883
884 default:
885 ASSERT_INT_EQUALS(TIMER_DONE, tester->timer_state);
886 return AWS_OP_SUCCESS;
887 }
888 }
889
890 /* Test that subscribe/unubscribe work at all */
891 static int s_test_event_loop_subscribe_unsubscribe(struct aws_allocator *allocator, void *ctx) {
892 (void)ctx;
893
894 thread_tester_state_fn *state_functions[] = {
895 s_state_subscribe,
896 s_state_unsubscribe,
897 NULL,
898 };
899
900 ASSERT_SUCCESS(s_thread_tester_run(allocator, state_functions));
901
902 return AWS_OP_SUCCESS;
903 }
904 AWS_TEST_CASE(event_loop_subscribe_unsubscribe, s_test_event_loop_subscribe_unsubscribe)
905
906 static int s_test_event_loop_writable_event_on_subscribe(struct aws_allocator *allocator, void *ctx) {
907 (void)ctx;
908
909 thread_tester_state_fn *state_functions[] = {
910 s_state_subscribe,
911 s_state_on_writable,
912 s_state_wait_1sec,
913 s_state_fail_if_more_writable_events,
914 s_state_unsubscribe,
915 NULL,
916 };
917
918 ASSERT_SUCCESS(s_thread_tester_run(allocator, state_functions));
919
920 return AWS_OP_SUCCESS;
921 }
922 AWS_TEST_CASE(event_loop_writable_event_on_subscribe, s_test_event_loop_writable_event_on_subscribe)
923
924 static int s_test_event_loop_no_readable_event_before_write(struct aws_allocator *allocator, void *ctx) {
925 (void)ctx;
926
927 thread_tester_state_fn *state_functions[] = {
928 s_state_subscribe,
929 s_state_wait_1sec,
930 s_state_fail_if_more_readable_events,
931 s_state_unsubscribe,
932 NULL,
933 };
934
935 ASSERT_SUCCESS(s_thread_tester_run(allocator, state_functions));
936 return AWS_OP_SUCCESS;
937 }
938 AWS_TEST_CASE(event_loop_no_readable_event_before_write, s_test_event_loop_no_readable_event_before_write);
939
940 static int s_test_event_loop_readable_event_on_subscribe_if_data_present(struct aws_allocator *allocator, void *ctx) {
941 (void)ctx;
942
943 thread_tester_state_fn *state_functions[] = {
944 s_state_write_data,
945 s_state_subscribe,
946 s_state_on_readable,
947 s_state_wait_1sec,
948 s_state_fail_if_more_readable_events,
949 s_state_unsubscribe,
950 NULL,
951 };
952
953 ASSERT_SUCCESS(s_thread_tester_run(allocator, state_functions));
954 return AWS_OP_SUCCESS;
955 }
956 AWS_TEST_CASE(
957 event_loop_readable_event_on_subscribe_if_data_present,
958 s_test_event_loop_readable_event_on_subscribe_if_data_present);
959
960 static int s_test_event_loop_readable_event_after_write(struct aws_allocator *allocator, void *ctx) {
961 (void)ctx;
962
963 thread_tester_state_fn *state_functions[] = {
964 s_state_subscribe,
965 s_state_on_writable,
966 s_state_write_data,
967 s_state_on_readable,
968 s_state_wait_1sec,
969 s_state_fail_if_more_readable_events,
970 s_state_unsubscribe,
971 NULL,
972 };
973
974 ASSERT_SUCCESS(s_thread_tester_run(allocator, state_functions));
975 return AWS_OP_SUCCESS;
976 }
977 AWS_TEST_CASE(event_loop_readable_event_after_write, s_test_event_loop_readable_event_after_write);
978
979 static int s_test_event_loop_readable_event_on_2nd_time_readable(struct aws_allocator *allocator, void *ctx) {
980 (void)ctx;
981
982 thread_tester_state_fn *state_functions[] = {
983 s_state_subscribe,
984 s_state_on_writable,
985 s_state_write_data,
986 s_state_on_readable,
987 s_state_read_until_blocked,
988 s_state_write_data,
989 s_state_on_readable,
990 s_state_unsubscribe,
991 NULL,
992 };
993
994 ASSERT_SUCCESS(s_thread_tester_run(allocator, state_functions));
995 return AWS_OP_SUCCESS;
996 }
997 AWS_TEST_CASE(event_loop_readable_event_on_2nd_time_readable, s_test_event_loop_readable_event_on_2nd_time_readable);
998
999 #endif /* AWS_ENABLE_IO_COMPLETION_PORTS */
1000
1001 /* Verify default event loop type */
1002 static int s_test_event_loop_creation(
1003 struct aws_allocator *allocator,
1004 enum aws_event_loop_type type,
1005 bool expect_success) {
1006 struct aws_event_loop_options event_loop_options = {
1007 .thread_options = NULL,
1008 .clock = aws_high_res_clock_get_ticks,
1009 .type = type,
1010 };
1011
1012 struct aws_event_loop *event_loop = aws_event_loop_new(allocator, &event_loop_options);
1013
1014 if (expect_success) {
1015 ASSERT_NOT_NULL(event_loop);
1016 /* Clean up tester*/
1017 aws_event_loop_destroy(event_loop);
1018 } else {
1019 ASSERT_NULL(event_loop);
1020 }
1021
1022 return AWS_OP_SUCCESS;
1023 }
1024
1025 static bool s_eventloop_test_enable_kqueue = false;
1026 static bool s_eventloop_test_enable_epoll = false;
1027 static bool s_eventloop_test_enable_iocp = false;
1028 static bool s_eventloop_test_enable_dispatch_queue = false;
1029
1030 static int s_test_event_loop_epoll_creation(struct aws_allocator *allocator, void *ctx) {
1031 (void)ctx;
1032
1033 #ifdef AWS_ENABLE_EPOLL
1034 s_eventloop_test_enable_epoll = true;
1035 #endif
1036 return s_test_event_loop_creation(allocator, AWS_EVENT_LOOP_EPOLL, s_eventloop_test_enable_epoll);
1037 }
1038
1039 AWS_TEST_CASE(event_loop_epoll_creation, s_test_event_loop_epoll_creation)
1040
1041 static int s_test_event_loop_iocp_creation(struct aws_allocator *allocator, void *ctx) {
1042 (void)ctx;
1043
1044 #ifdef AWS_ENABLE_IO_COMPLETION_PORTS
1045 s_eventloop_test_enable_iocp = true;
1046 #endif
1047 return s_test_event_loop_creation(allocator, AWS_EVENT_LOOP_IOCP, s_eventloop_test_enable_iocp);
1048 }
1049
1050 AWS_TEST_CASE(event_loop_iocp_creation, s_test_event_loop_iocp_creation)
1051
1052 static int s_test_event_loop_kqueue_creation(struct aws_allocator *allocator, void *ctx) {
1053 (void)ctx;
1054 #ifdef AWS_ENABLE_KQUEUE
1055 s_eventloop_test_enable_kqueue = true;
1056 #endif
1057 return s_test_event_loop_creation(allocator, AWS_EVENT_LOOP_KQUEUE, s_eventloop_test_enable_kqueue);
1058 }
1059
1060 AWS_TEST_CASE(event_loop_kqueue_creation, s_test_event_loop_kqueue_creation)
1061
1062 static int s_test_event_loop_dispatch_queue_creation(struct aws_allocator *allocator, void *ctx) {
1063 (void)ctx;
1064
1065 #ifdef AWS_ENABLE_DISPATCH_QUEUE
1066 s_eventloop_test_enable_dispatch_queue = true;
1067 #endif
1068 return s_test_event_loop_creation(allocator, AWS_EVENT_LOOP_DISPATCH_QUEUE, s_eventloop_test_enable_dispatch_queue);
1069 }
1070
1071 AWS_TEST_CASE(event_loop_dispatch_queue_creation, s_test_event_loop_dispatch_queue_creation)
1072
1073 static int s_event_loop_test_stop_then_restart(struct aws_allocator *allocator, void *ctx) {
1074 (void)ctx;
1075 struct aws_event_loop *event_loop = aws_event_loop_new_default(allocator, aws_high_res_clock_get_ticks);
1076
1077 ASSERT_NOT_NULL(event_loop, "Event loop creation failed with error: %s", aws_error_debug_str(aws_last_error()));
1078 ASSERT_SUCCESS(aws_event_loop_run(event_loop));
1079
1080 struct task_args task_args = {
1081 .condition_variable = AWS_CONDITION_VARIABLE_INIT,
1082 .mutex = AWS_MUTEX_INIT,
1083 .invoked = false,
1084 .was_in_thread = false,
1085 .status = -1,
1086 .loop = event_loop,
1087 .thread_id = 0,
1088 };
1089
1090 struct aws_task task;
1091 aws_task_init(&task, s_test_task, &task_args, "stop_then_restart");
1092
1093 ASSERT_SUCCESS(aws_mutex_lock(&task_args.mutex));
1094
1095 aws_event_loop_schedule_task_now(event_loop, &task);
1096
1097 ASSERT_SUCCESS(aws_condition_variable_wait_pred(
1098 &task_args.condition_variable, &task_args.mutex, s_task_ran_predicate, &task_args));
1099 ASSERT_TRUE(task_args.invoked);
1100
1101 ASSERT_SUCCESS(aws_event_loop_stop(event_loop));
1102 ASSERT_SUCCESS(aws_event_loop_wait_for_stop_completion(event_loop));
1103 ASSERT_SUCCESS(aws_event_loop_run(event_loop));
1104
1105 aws_event_loop_schedule_task_now(event_loop, &task);
1106
1107 task_args.invoked = false;
1108 ASSERT_SUCCESS(aws_condition_variable_wait_pred(
1109 &task_args.condition_variable, &task_args.mutex, s_task_ran_predicate, &task_args));
1110 ASSERT_TRUE(task_args.invoked);
1111
1112 aws_event_loop_destroy(event_loop);
1113
1114 return AWS_OP_SUCCESS;
1115 }
1116
1117 AWS_TEST_CASE(event_loop_stop_then_restart, s_event_loop_test_stop_then_restart)
1118
1119 static int s_event_loop_test_multiple_stops(struct aws_allocator *allocator, void *ctx) {
1120 (void)ctx;
1121
1122 struct aws_event_loop *event_loop = aws_event_loop_new_default(allocator, aws_high_res_clock_get_ticks);
1123
1124 ASSERT_NOT_NULL(event_loop, "Event loop creation failed with error: %s", aws_error_debug_str(aws_last_error()));
1125 ASSERT_SUCCESS(aws_event_loop_run(event_loop));
1126 for (int i = 0; i < 8; ++i) {
1127 ASSERT_SUCCESS(aws_event_loop_stop(event_loop));
1128 }
1129 aws_event_loop_destroy(event_loop);
1130
1131 return AWS_OP_SUCCESS;
1132 }
1133
1134 AWS_TEST_CASE(event_loop_multiple_stops, s_event_loop_test_multiple_stops)
1135
1136 static int test_event_loop_group_setup_and_shutdown(struct aws_allocator *allocator, void *ctx) {
1137
1138 (void)ctx;
1139 aws_io_library_init(allocator);
1140
1141 struct aws_event_loop_group_options elg_options = {
1142 .loop_count = 0,
1143 };
1144 struct aws_event_loop_group *event_loop_group = aws_event_loop_group_new(allocator, &elg_options);
1145
1146 size_t cpu_count = aws_system_info_processor_count();
1147 size_t el_count = aws_event_loop_group_get_loop_count(event_loop_group);
1148
1149 struct aws_event_loop *event_loop = aws_event_loop_group_get_next_loop(event_loop_group);
1150 ASSERT_NOT_NULL(event_loop);
1151
1152 if (cpu_count > 1) {
1153 ASSERT_INT_EQUALS(cpu_count / 2, el_count);
1154 }
1155
1156 if (cpu_count > 1) {
1157 ASSERT_INT_EQUALS(cpu_count / 2, el_count);
1158 }
1159
1160 aws_event_loop_group_release(event_loop_group);
1161
1162 aws_io_library_clean_up();
1163
1164 return AWS_OP_SUCCESS;
1165 }
1166
1167 AWS_TEST_CASE(event_loop_group_setup_and_shutdown, test_event_loop_group_setup_and_shutdown)
1168
1169 static int test_numa_aware_event_loop_group_setup_and_shutdown(struct aws_allocator *allocator, void *ctx) {
1170
1171 (void)ctx;
1172 aws_io_library_init(allocator);
1173
1174 size_t cpus_for_group = aws_get_cpu_count_for_group(0);
1175 size_t el_count = 1;
1176
1177 uint16_t cpu_group = 0;
1178 struct aws_event_loop_group_options elg_options = {
1179 /*
1180 * pass UINT16_MAX here to check the boundary conditions on numa cpu detection. It should never create more
1181 * threads than hw cpus available
1182 */
1183 .loop_count = UINT16_MAX,
1184 .cpu_group = &cpu_group,
1185 };
1186 struct aws_event_loop_group *event_loop_group = aws_event_loop_group_new(allocator, &elg_options);
1187
1188 el_count = aws_event_loop_group_get_loop_count(event_loop_group);
1189
1190 size_t hw_thread_count = 0;
1191 struct aws_cpu_info *cpu_info = aws_mem_calloc(allocator, cpus_for_group, sizeof(struct aws_cpu_info));
1192 ASSERT_NOT_NULL(cpu_info);
1193
1194 aws_get_cpu_ids_for_group(0, cpu_info, cpus_for_group);
1195
1196 for (size_t i = 0; i < cpus_for_group; ++i) {
1197 if (!cpu_info[i].suspected_hyper_thread) {
1198 hw_thread_count++;
1199 }
1200 }
1201
1202 aws_mem_release(allocator, cpu_info);
1203
1204 ASSERT_INT_EQUALS(hw_thread_count, el_count);
1205
1206 aws_event_loop_group_release(event_loop_group);
1207
1208 aws_io_library_clean_up();
1209
1210 return AWS_OP_SUCCESS;
1211 }
1212
1213 AWS_TEST_CASE(numa_aware_event_loop_group_setup_and_shutdown, test_numa_aware_event_loop_group_setup_and_shutdown)
1214
1215 static void s_async_shutdown_complete_callback(void *user_data) {
1216
1217 struct task_args *args = user_data;
1218
1219 aws_mutex_lock(&args->mutex);
1220 args->thread_id = aws_thread_current_thread_id();
1221 args->invoked = true;
1222 aws_mutex_unlock((&args->mutex));
1223 aws_atomic_store_int(&args->thread_complete, true);
1224 aws_condition_variable_notify_one(&args->condition_variable);
1225 }
1226
1227 static void s_async_shutdown_task(struct aws_task *task, void *user_data, enum aws_task_status status) {
1228 (void)task;
1229 (void)status;
1230
1231 struct aws_event_loop_group *el_group = user_data;
1232
1233 aws_event_loop_group_release(el_group);
1234 }
1235
1236 static int test_event_loop_group_setup_and_shutdown_async(struct aws_allocator *allocator, void *ctx) {
1237
1238 (void)ctx;
1239
1240 aws_io_library_init(allocator);
1241
1242 /*
1243 * Small chicken-and-egg problem here: the task args needs the event loop group and loop, but
1244 * creating the event loop group needs shutdown options that refer to the task args.
1245 */
1246 struct task_args task_args = {
1247 .condition_variable = AWS_CONDITION_VARIABLE_INIT,
1248 .mutex = AWS_MUTEX_INIT,
1249 .invoked = false,
1250 .was_in_thread = false,
1251 .status = -1,
1252 .loop = NULL,
1253 .el_group = NULL,
1254 .thread_id = 0,
1255 };
1256 aws_atomic_init_int(&task_args.thread_complete, false);
1257
1258 struct aws_shutdown_callback_options async_shutdown_options;
1259 AWS_ZERO_STRUCT(async_shutdown_options);
1260 async_shutdown_options.shutdown_callback_user_data = &task_args;
1261 async_shutdown_options.shutdown_callback_fn = s_async_shutdown_complete_callback;
1262
1263 struct aws_event_loop_group_options elg_options = {
1264 .loop_count = 0,
1265 .shutdown_options = &async_shutdown_options,
1266 };
1267
1268 struct aws_event_loop_group *event_loop_group = aws_event_loop_group_new(allocator, &elg_options);
1269
1270 struct aws_event_loop *event_loop = aws_event_loop_group_get_next_loop(event_loop_group);
1271
1272 task_args.loop = event_loop;
1273 task_args.el_group = event_loop_group;
1274
1275 struct aws_task task;
1276 aws_task_init(
1277 &task, s_async_shutdown_task, event_loop_group, "async elg shutdown invoked from an event loop thread");
1278
1279 /* Test "future" tasks */
1280 uint64_t now;
1281 ASSERT_SUCCESS(aws_event_loop_current_clock_time(event_loop, &now));
1282 aws_event_loop_schedule_task_future(event_loop, &task, now);
1283
1284 ASSERT_SUCCESS(aws_mutex_lock(&task_args.mutex));
1285 ASSERT_SUCCESS(aws_condition_variable_wait_pred(
1286 &task_args.condition_variable, &task_args.mutex, s_task_ran_predicate, &task_args));
1287 ASSERT_TRUE(task_args.invoked);
1288 aws_mutex_unlock(&task_args.mutex);
1289
1290 while (!aws_atomic_load_int(&task_args.thread_complete)) {
1291 aws_thread_current_sleep(15);
1292 }
1293
1294 aws_io_library_clean_up();
1295
1296 return AWS_OP_SUCCESS;
1297 }
1298
1299 AWS_TEST_CASE(event_loop_group_setup_and_shutdown_async, test_event_loop_group_setup_and_shutdown_async)
1300
1301 enum scheduling_source { EVENT_LOOP_THREAD, EXTERNAL_THREAD };
1302
1303 struct serialized_scheduling_context {
1304 struct aws_allocator *allocator;
1305 struct aws_event_loop *loop;
1306 size_t max_ids;
1307
1308 struct aws_condition_variable signal;
1309 struct aws_mutex lock;
1310 struct {
1311 size_t next_id;
1312 size_t last_processed_id;
1313
1314 size_t event_loop_schedules;
1315 size_t event_loop_schedules_processed;
1316 size_t external_schedules;
1317 size_t external_schedules_processed;
1318
1319 bool scheduling_allowed;
1320 bool el_scheduling_finished;
1321 bool external_thread_finished;
1322 bool test_failed;
1323
1324 enum scheduling_source current_source;
1325 } synced_data;
1326 };
1327
1328 static void s_serialized_scheduling_context_init(
1329 struct serialized_scheduling_context *context,
1330 struct aws_allocator *allocator,
1331 struct aws_event_loop *event_loop,
1332 size_t max_ids) {
1333 AWS_ZERO_STRUCT(*context);
1334 context->allocator = allocator;
1335 context->loop = event_loop;
1336 context->max_ids = max_ids;
1337 context->synced_data.next_id = 1;
1338
1339 aws_mutex_init(&context->lock);
1340 aws_condition_variable_init(&context->signal);
1341 }
1342
1343 static void s_serialized_scheduling_context_clean_up(struct serialized_scheduling_context *context) {
1344 aws_mutex_clean_up(&context->lock);
1345 aws_condition_variable_clean_up(&context->signal);
1346 }
1347
1348 struct aws_serialized_scheduling_task {
1349 struct aws_allocator *allocator;
1350
1351 struct aws_task base;
1352 struct serialized_scheduling_context *test_context;
1353 size_t id;
1354 enum scheduling_source source;
1355 };
1356
1357 static void s_process_serialized_scheduling_task(struct aws_task *task, void *arg, enum aws_task_status status) {
1358 (void)task;
1359 (void)status;
1360
1361 struct aws_serialized_scheduling_task *test_task = arg;
1362
1363 aws_mutex_lock(&test_task->test_context->lock);
1364
1365 if (test_task->source == EVENT_LOOP_THREAD) {
1366 ++test_task->test_context->synced_data.event_loop_schedules_processed;
1367 } else {
1368 ++test_task->test_context->synced_data.external_schedules_processed;
1369 }
1370
1371 if (test_task->id != test_task->test_context->synced_data.last_processed_id + 1) {
1372 test_task->test_context->synced_data.test_failed = true;
1373 }
1374
1375 test_task->test_context->synced_data.last_processed_id = test_task->id;
1376
1377 aws_condition_variable_notify_all(&test_task->test_context->signal);
1378 aws_mutex_unlock(&test_task->test_context->lock);
1379
1380 aws_mem_release(test_task->allocator, test_task);
1381 }
1382
1383 static bool s_wait_for_scheduling_allowed_predicate(void *arg) {
1384 struct serialized_scheduling_context *context = arg;
1385
1386 return context->synced_data.scheduling_allowed || context->synced_data.next_id > context->max_ids;
1387 }
1388
1389 static bool s_serialized_scheduling_context_schedule_task(
1390 struct serialized_scheduling_context *context,
1391 enum scheduling_source source) {
1392 bool no_ids_left = false;
1393
1394 aws_mutex_lock(&context->lock);
1395 aws_condition_variable_wait_pred(
1396 &context->signal, &context->lock, s_wait_for_scheduling_allowed_predicate, context);
1397
1398 if (context->synced_data.next_id <= context->max_ids) {
1399 size_t id = context->synced_data.next_id++;
1400 struct aws_serialized_scheduling_task *task =
1401 aws_mem_calloc(context->allocator, 1, sizeof(struct aws_serialized_scheduling_task));
1402 task->allocator = context->allocator;
1403 aws_task_init(&task->base, s_process_serialized_scheduling_task, task, "serialized scheduling test task");
1404 task->test_context = context;
1405 task->id = id;
1406 task->source = source;
1407
1408 aws_event_loop_schedule_task_now_serialized(context->loop, &task->base);
1409
1410 if (source == EXTERNAL_THREAD) {
1411 ++context->synced_data.external_schedules;
1412 } else {
1413 ++context->synced_data.event_loop_schedules;
1414 }
1415 } else {
1416 no_ids_left = true;
1417 }
1418
1419 aws_mutex_unlock(&context->lock);
1420
1421 return no_ids_left;
1422 }
1423
1424 static bool s_wait_for_all_threads_predicate(void *arg) {
1425 struct serialized_scheduling_context *context = arg;
1426
1427 return context->synced_data.el_scheduling_finished && context->synced_data.external_thread_finished;
1428 }
1429
1430 static void s_serialized_scheduling_context_wait_for_all_threads(struct serialized_scheduling_context *context) {
1431 aws_mutex_lock(&context->lock);
1432 aws_condition_variable_wait_pred(&context->signal, &context->lock, s_wait_for_all_threads_predicate, context);
1433 aws_mutex_unlock(&context->lock);
1434 }
1435
1436 static bool s_wait_for_all_ids_processed_predicate(void *arg) {
1437 struct serialized_scheduling_context *context = arg;
1438
1439 return context->synced_data.last_processed_id == context->max_ids;
1440 }
1441
1442 static void s_serialized_scheduling_context_wait_for_all_ids_processed(struct serialized_scheduling_context *context) {
1443 aws_mutex_lock(&context->lock);
1444 aws_condition_variable_wait_pred(&context->signal, &context->lock, s_wait_for_all_ids_processed_predicate, context);
1445 aws_mutex_unlock(&context->lock);
1446 }
1447
1448 static enum scheduling_source s_switch_source(enum scheduling_source source) {
1449 return source == EVENT_LOOP_THREAD ? EXTERNAL_THREAD : EVENT_LOOP_THREAD;
1450 }
1451
1452 static void s_alternate_scheduling_source(
1453 struct serialized_scheduling_context *context,
1454 enum scheduling_source source,
1455 bool need_wait) {
1456 aws_mutex_lock(&context->lock);
1457 context->synced_data.current_source = s_switch_source(source);
1458 aws_condition_variable_notify_all(&context->signal);
1459
1460 while (need_wait && context->synced_data.current_source != source && !context->synced_data.el_scheduling_finished &&
1461 !context->synced_data.external_thread_finished) {
1462 aws_condition_variable_wait(&context->signal, &context->lock);
1463 }
1464 aws_mutex_unlock(&context->lock);
1465 }
1466
1467 static void s_serialized_scheduling_thread_fn(void *arg) {
1468
1469 struct serialized_scheduling_context *context = arg;
1470
1471 bool done = false;
1472 while (!done) {
1473 done = s_serialized_scheduling_context_schedule_task(context, EXTERNAL_THREAD);
1474 s_alternate_scheduling_source(context, EXTERNAL_THREAD, /*need_wait=*/!done);
1475 }
1476
1477 aws_mutex_lock(&context->lock);
1478 context->synced_data.external_thread_finished = true;
1479 aws_condition_variable_notify_all(&context->signal);
1480 aws_mutex_unlock(&context->lock);
1481 }
1482
1483 struct aws_in_event_loop_scheduling_task {
1484 struct aws_allocator *allocator;
1485
1486 struct aws_task base;
1487 struct serialized_scheduling_context *test_context;
1488 };
1489
1490 static void s_in_event_loop_scheduling_task(struct aws_task *task, void *arg, enum aws_task_status);
1491
1492 static void s_schedule_next_in_event_loop_scheduling_task(
1493 struct aws_allocator *allocator,
1494 struct serialized_scheduling_context *context) {
1495 struct aws_in_event_loop_scheduling_task *task =
1496 aws_mem_calloc(allocator, 1, sizeof(struct aws_in_event_loop_scheduling_task));
1497 task->allocator = allocator;
1498 aws_task_init(&task->base, s_in_event_loop_scheduling_task, task, "in event loop control task");
1499 task->test_context = context;
1500
1501 aws_event_loop_schedule_task_now_serialized(context->loop, &task->base);
1502 }
1503
1504 static void s_enable_scheduling(struct serialized_scheduling_context *context) {
1505 aws_mutex_lock(&context->lock);
1506 context->synced_data.scheduling_allowed = true;
1507 aws_mutex_unlock(&context->lock);
1508 aws_condition_variable_notify_all(&context->signal);
1509 }
1510
1511 static void s_disable_scheduling(struct serialized_scheduling_context *context) {
1512 aws_mutex_lock(&context->lock);
1513 context->synced_data.scheduling_allowed = false;
1514 aws_mutex_unlock(&context->lock);
1515 aws_condition_variable_notify_all(&context->signal);
1516 }
1517
1518 #define IN_EVENT_LOOP_SCHEDULE_BLOCK_SIZE 200
1519
1520 static void s_in_event_loop_scheduling_task(struct aws_task *task, void *arg, enum aws_task_status status) {
1521 (void)task;
1522 (void)status;
1523
1524 struct aws_in_event_loop_scheduling_task *scheduling_task = arg;
1525
1526 s_enable_scheduling(scheduling_task->test_context);
1527
1528 bool ids_left = true;
1529 for (size_t i = 0; i < IN_EVENT_LOOP_SCHEDULE_BLOCK_SIZE; ++i) {
1530 if (s_serialized_scheduling_context_schedule_task(scheduling_task->test_context, EVENT_LOOP_THREAD)) {
1531 ids_left = false;
1532 s_alternate_scheduling_source(scheduling_task->test_context, EVENT_LOOP_THREAD, /*need_wait=*/false);
1533 break;
1534 }
1535 s_alternate_scheduling_source(scheduling_task->test_context, EVENT_LOOP_THREAD, /*need_wait=*/true);
1536 }
1537
1538 s_disable_scheduling(scheduling_task->test_context);
1539
1540 if (ids_left) {
1541 s_schedule_next_in_event_loop_scheduling_task(scheduling_task->allocator, scheduling_task->test_context);
1542 } else {
1543 aws_mutex_lock(&scheduling_task->test_context->lock);
1544 scheduling_task->test_context->synced_data.el_scheduling_finished = true;
1545 aws_mutex_unlock(&scheduling_task->test_context->lock);
1546 aws_condition_variable_notify_all(&scheduling_task->test_context->signal);
1547 }
1548
1549 aws_mem_release(scheduling_task->allocator, scheduling_task);
1550 }
1551
1552 /*
1553 * Test that verifies serialized scheduling by running two concurrent executions, one on the target event loop, one
1554 * on an external thread. The two submit tasks as fast as they can (although the event loop thread must yield
1555 * occasionally in order for the scheduled tasks to get serviced) and we verify that order-of-execution matches
1556 * order-of-submission.
1557 *
1558 * There are a couple of sleep(0)s in the logic to help achieve some approximate mutex-locking fairness. Without them,
1559 * the external thread was successfully taking the lock at a much higher rate (30x) than the in-event-loop execution.
1560 */
1561 static int s_test_event_loop_serialized_scheduling(struct aws_allocator *allocator, void *ctx) {
1562
1563 (void)ctx;
1564
1565 aws_io_library_init(allocator);
1566
1567 struct aws_event_loop_group_options elg_options = {
1568 .loop_count = 1,
1569 };
1570
1571 struct aws_event_loop_group *event_loop_group = aws_event_loop_group_new(allocator, &elg_options);
1572 struct aws_event_loop *event_loop = aws_event_loop_group_get_next_loop(event_loop_group);
1573
1574 struct serialized_scheduling_context context;
1575 s_serialized_scheduling_context_init(&context, allocator, event_loop, 100000);
1576
1577 struct aws_thread external_thread;
1578 aws_thread_init(&external_thread, allocator);
1579 aws_thread_launch(&external_thread, s_serialized_scheduling_thread_fn, &context, NULL);
1580
1581 s_schedule_next_in_event_loop_scheduling_task(allocator, &context);
1582
1583 s_serialized_scheduling_context_wait_for_all_ids_processed(&context);
1584 s_serialized_scheduling_context_wait_for_all_threads(&context);
1585
1586 ASSERT_FALSE(context.synced_data.test_failed);
1587 ASSERT_TRUE(context.synced_data.external_schedules_processed > 0);
1588 ASSERT_TRUE(context.synced_data.event_loop_schedules_processed > 0);
1589
1590 aws_thread_join(&external_thread);
1591 aws_thread_clean_up(&external_thread);
1592
1593 aws_event_loop_group_release(event_loop_group);
1594
1595 aws_io_library_clean_up();
1596
1597 s_serialized_scheduling_context_clean_up(&context);
1598
1599 return AWS_OP_SUCCESS;
1600 }
1601
1602 AWS_TEST_CASE(event_loop_serialized_scheduling, s_test_event_loop_serialized_scheduling)