Nilorea Library
C utilities for networking, threading, graphics
Loading...
Searching...
No Matches
ex_accept_pool_server.c
Go to the documentation of this file.
1/*
2 * Nilorea Library
3 * Copyright (C) 2005-2026 Castagnier Mickael
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14 * implied. See the License for the specific language governing
15 * permissions and limitations under the License.
16 *
17 * SPDX-License-Identifier: Apache-2.0
18 */
19
58
59#include <stdio.h>
60#include <stdlib.h>
61#include <string.h>
62#include <errno.h>
63#include <getopt.h>
64#include <signal.h>
65
66#include "nilorea/n_common.h"
67#include "nilorea/n_log.h"
68#include "nilorea/n_network.h"
71
72static volatile int server_running = 1;
73static int total_target = 500;
74/* Seconds to wait for progress before giving up, 0 disables the deadline.
75 * Without it a server whose client never showed up sat in its accept loop
76 * forever and only died when the test harness killed it on its global
77 * timeout, which surfaced as a bare exit 124 with nothing to diagnose. */
78static int idle_timeout = 30;
79
81#define MODE_SINGLE_INLINE 0
82#define MODE_SINGLE_POOL 1
83#define MODE_POOLED 2
84
86typedef struct CALLBACK_DATA {
88 size_t handled;
90 pthread_mutex_t lock;
94
99static void handle_client(NETWORK* client) {
100 __n_assert(client, return);
101
102 netw_start_thr_engine(client);
103
104 N_STR* msg = netw_wait_msg(client, 10000, 20000000);
105 if (msg) {
106 netw_add_msg(client, msg);
107 u_sleep(50000);
108 }
109
110 netw_close(&client);
111}
112
120
126static void* worker_handle_client(void* ptr) {
127 WORKER_ARG* arg = (WORKER_ARG*)ptr;
128 __n_assert(arg, return NULL);
129
130 handle_client(arg->client);
131
132 pthread_mutex_lock(&arg->cb_data->lock);
133 arg->cb_data->handled++;
134 size_t h = arg->cb_data->handled;
135 pthread_mutex_unlock(&arg->cb_data->lock);
136
137 if (h % 100 == 0) {
138 n_log(LOG_NOTICE, "handled %zu connections", h);
139 }
140
141 Free(arg);
142 return NULL;
143}
144
150static void dispatch_to_pool(NETWORK* client, CALLBACK_DATA* cb_data) {
151 __n_assert(client, return);
152 __n_assert(cb_data, netw_close(&client); return);
153 __n_assert(cb_data->worker_pool, netw_close(&client); return);
154
155 WORKER_ARG* arg = NULL;
156 Malloc(arg, WORKER_ARG, 1);
157 if (!arg) {
158 n_log(LOG_ERR, "failed to allocate worker arg");
159 netw_close(&client);
160 return;
161 }
162 arg->client = client;
163 arg->cb_data = cb_data;
164
166}
167
173static void handle_inline_and_count(NETWORK* client, CALLBACK_DATA* cb_data) {
174 __n_assert(cb_data, netw_close(&client); return);
175
176 handle_client(client);
177
178 pthread_mutex_lock(&cb_data->lock);
179 cb_data->handled++;
180 size_t h = cb_data->handled;
181 pthread_mutex_unlock(&cb_data->lock);
182
183 if (h % 100 == 0) {
184 n_log(LOG_NOTICE, "handled %zu connections", h);
185 }
186}
187
193static void on_accept_pooled(NETWORK* conn, void* user_data) {
194 CALLBACK_DATA* data = (CALLBACK_DATA*)user_data;
195 __n_assert(data, netw_close(&conn); return);
196 dispatch_to_pool(conn, data);
197}
198
199static void sighandler(int sig) {
200 (void)sig;
201 server_running = 0;
202}
203
204static void usage(void) {
205 fprintf(stderr,
206 "Usage: ex_accept_pool_server [options]\n"
207 " -p PORT port to listen on (required)\n"
208 " -a ADDR address to bind to (optional, default: all)\n"
209 " -m MODE 'single-inline', 'single-pool', or 'pooled' (default: single-inline)\n"
210 " -n COUNT number of connections to handle (default: 500)\n"
211 " -t THREADS number of threads for pool/accept (default: 4)\n"
212 " -w SECONDS give up after SECONDS without progress, 0 to wait forever (default: 30)\n"
213 " -V LEVEL log level: LOG_DEBUG, LOG_INFO, LOG_NOTICE, LOG_ERR (default: LOG_NOTICE)\n"
214 " -h show this help\n");
215}
216
217int main(int argc, char** argv) {
218 char* addr = NULL;
219 char* port = NULL;
220 char* mode_str = "single-inline";
221 int nb_threads = 4;
222 int log_level = LOG_NOTICE;
223 int opt;
224
225 while ((opt = getopt(argc, argv, "hp:a:m:n:t:w:V:")) != -1) {
226 switch (opt) {
227 case 'p':
228 port = strdup(optarg);
229 break;
230 case 'a':
231 addr = strdup(optarg);
232 break;
233 case 'm':
234 mode_str = optarg;
235 break;
236 case 'n':
237 total_target = atoi(optarg);
238 break;
239 case 't':
240 nb_threads = atoi(optarg);
241 break;
242 case 'w':
243 idle_timeout = atoi(optarg);
244 break;
245 case 'V':
246 if (!strcmp(optarg, "LOG_DEBUG"))
248 else if (!strcmp(optarg, "LOG_INFO"))
250 else if (!strcmp(optarg, "LOG_NOTICE"))
252 else if (!strcmp(optarg, "LOG_ERR"))
254 break;
255 case 'h':
256 default:
257 usage();
258 exit(1);
259 }
260 }
261
262 if (!port) {
263 fprintf(stderr, "Error: -p PORT is required\n");
264 usage();
265 exit(1);
266 }
267
269 if (strcmp(mode_str, "single-pool") == 0) {
271 } else if (strcmp(mode_str, "pooled") == 0) {
273 } else if (strcmp(mode_str, "single-inline") != 0) {
274 fprintf(stderr, "Error: unknown mode '%s'\n", mode_str);
275 usage();
276 exit(1);
277 }
278
280
281 signal(SIGINT, sighandler);
282 signal(SIGTERM, sighandler);
283#ifdef __linux__
284 signal(SIGPIPE, SIG_IGN);
285#endif
286
287 /* create listening socket */
288 NETWORK* server = NULL;
289 if (netw_make_listening(&server, addr, port, 1024, NETWORK_IPALL) == FALSE) {
290 n_log(LOG_ERR, "Failed to create listening socket on %s:%s", addr ? addr : "*", port);
291 exit(1);
292 }
293 n_log(LOG_NOTICE, "Listening on %s:%s (backlog=1024)", addr ? addr : "*", port);
294
295 CALLBACK_DATA cb_data;
296 cb_data.handled = 0;
297 cb_data.worker_pool = NULL;
298 pthread_mutex_init(&cb_data.lock, NULL);
299
300 struct timespec t_start, t_end;
301 clock_gettime(CLOCK_MONOTONIC, &t_start);
302
303 const char* mode_names[] = {"SINGLE-INLINE", "SINGLE-POOL", "POOLED"};
304 n_log(LOG_NOTICE, "=== %s MODE: target %d connections ===", mode_names[mode], total_target);
305
306 int exit_code = 0;
307 /* progress watchdog: get_msec() returns the delta since the previous
308 * poll, so accumulating it gives the time since the last connection */
309 N_TIME idle_timer;
310 start_HiTimer(&idle_timer);
311 time_t idle_msec = 0;
312 size_t seen_progress = 0;
313
314 if (mode == MODE_SINGLE_INLINE) {
315 /* SINGLE-INLINE MODE
316 * One thread doing accept + handle client in the same thread.
317 * Both accept and handling are fully serialized. */
318 n_log(LOG_NOTICE, "1 thread: accept + handle inline (fully serialized)");
319
320 while (server_running) {
321 pthread_mutex_lock(&cb_data.lock);
322 size_t h = cb_data.handled;
323 pthread_mutex_unlock(&cb_data.lock);
324 if ((int)h >= total_target) {
325 break;
326 }
327 idle_msec += get_msec(&idle_timer);
328 if (h != seen_progress) {
329 seen_progress = h;
330 idle_msec = 0;
331 }
332 if (idle_timeout > 0 && idle_msec > (time_t)idle_timeout * 1000) {
333 n_log(LOG_ERR, "no connection for %d seconds, giving up with %zu/%d handled", idle_timeout, h, total_target);
334 exit_code = 1;
335 break;
336 }
337
338 int retval = 0;
339 NETWORK* client = netw_accept_from_ex(server, 0, 0, 500, &retval);
340 if (client) {
341 handle_inline_and_count(client, &cb_data);
342 }
343 }
344 } else if (mode == MODE_SINGLE_POOL) {
345 /* SINGLE-POOL MODE
346 * One thread doing accept, dispatching to a worker thread pool.
347 * Accept is serialized, but client handling is parallelized. */
348 n_log(LOG_NOTICE, "1 accept thread, %d worker threads", nb_threads);
349
350 cb_data.worker_pool = new_thread_pool((size_t)nb_threads, (size_t)(total_target + 16));
351 if (!cb_data.worker_pool) {
352 n_log(LOG_ERR, "Failed to create worker thread pool");
353 goto cleanup;
354 }
355
356 int accepted_count = 0;
357 while (server_running && accepted_count < total_target) {
358 idle_msec += get_msec(&idle_timer);
359 if ((size_t)accepted_count != seen_progress) {
360 seen_progress = (size_t)accepted_count;
361 idle_msec = 0;
362 }
363 if (idle_timeout > 0 && idle_msec > (time_t)idle_timeout * 1000) {
364 n_log(LOG_ERR, "no connection for %d seconds, giving up with %d/%d accepted", idle_timeout, accepted_count, total_target);
365 exit_code = 1;
366 break;
367 }
368
369 int retval = 0;
370 NETWORK* client = netw_accept_from_ex(server, 0, 0, 500, &retval);
371 if (client) {
372 dispatch_to_pool(client, &cb_data);
373 accepted_count++;
374 }
375 }
376
377 /* wait for all workers to finish */
378 n_log(LOG_NOTICE, "all connections accepted, waiting for workers...");
380 destroy_threaded_pool(&cb_data.worker_pool, 500000);
381 } else {
382 /* POOLED MODE
383 * N accept threads (accept pool) + worker thread pool.
384 * Both accept and handling are parallelized. */
385 n_log(LOG_NOTICE, "%d accept threads, %d worker threads", nb_threads, nb_threads);
386
387 cb_data.worker_pool = new_thread_pool((size_t)nb_threads, (size_t)(total_target + 16));
388 if (!cb_data.worker_pool) {
389 n_log(LOG_ERR, "Failed to create worker thread pool");
390 goto cleanup;
391 }
392
394 server, (size_t)nb_threads, 500, on_accept_pooled, &cb_data);
395 if (!accept_pool) {
396 n_log(LOG_ERR, "Failed to create accept pool");
397 destroy_threaded_pool(&cb_data.worker_pool, 500000);
398 goto cleanup;
399 }
400
401 if (netw_accept_pool_start(accept_pool) == FALSE) {
402 n_log(LOG_ERR, "Failed to start accept pool");
403 netw_accept_pool_destroy(&accept_pool);
404 destroy_threaded_pool(&cb_data.worker_pool, 500000);
405 goto cleanup;
406 }
407
408 /* wait until we've handled enough connections or user interrupts */
409 while (server_running) {
410 pthread_mutex_lock(&cb_data.lock);
411 size_t h = cb_data.handled;
412 pthread_mutex_unlock(&cb_data.lock);
413
414 if ((int)h >= total_target) {
415 break;
416 }
417 idle_msec += get_msec(&idle_timer);
418 if (h != seen_progress) {
419 seen_progress = h;
420 idle_msec = 0;
421 }
422 if (idle_timeout > 0 && idle_msec > (time_t)idle_timeout * 1000) {
423 n_log(LOG_ERR, "no connection for %d seconds, giving up with %zu/%d handled", idle_timeout, h, total_target);
424 exit_code = 1;
425 break;
426 }
427
429 netw_accept_pool_get_stats(accept_pool, &stats);
430 n_log(LOG_INFO, "stats: accepted=%zu errors=%zu timeouts=%zu active_threads=%zu",
431 stats.total_accepted, stats.total_errors, stats.total_timeouts, stats.active_threads);
432
433 u_sleep(100000);
434 }
435
436 netw_accept_pool_stop(accept_pool);
437 netw_accept_pool_wait(accept_pool, 10);
438
439 NETW_ACCEPT_POOL_STATS final_stats;
440 netw_accept_pool_get_stats(accept_pool, &final_stats);
441 n_log(LOG_NOTICE, "Pool stats: accepted=%zu errors=%zu timeouts=%zu",
442 final_stats.total_accepted, final_stats.total_errors, final_stats.total_timeouts);
443
444 netw_accept_pool_destroy(&accept_pool);
445
446 /* wait for all workers to finish */
447 n_log(LOG_NOTICE, "accept pool stopped, waiting for workers...");
449 destroy_threaded_pool(&cb_data.worker_pool, 500000);
450 }
451
452 clock_gettime(CLOCK_MONOTONIC, &t_end);
453 double elapsed = (double)(t_end.tv_sec - t_start.tv_sec) +
454 (double)(t_end.tv_nsec - t_start.tv_nsec) / 1e9;
455
456 n_log(LOG_NOTICE, "=== DONE: %zu connections in %.3f seconds (%.1f conn/sec) ===",
457 cb_data.handled, elapsed, (double)cb_data.handled / elapsed);
458
459cleanup:
460 pthread_mutex_destroy(&cb_data.lock);
462
465
466 netw_unload();
467 if (exit_code == 0) {
468 n_log(LOG_NOTICE, "Server exited cleanly");
469 } else {
470 n_log(LOG_ERR, "Server exited with code %d", exit_code);
471 }
472
473 return exit_code;
474}
static void usage(void)
#define MODE_SINGLE_POOL
static void * worker_handle_client(void *ptr)
Worker thread function: handles a client and updates counter.
static int total_target
size_t handled
atomic counter of handled connections
static void sighandler(int sig)
pthread_mutex_t lock
mutex for counter
static volatile int server_running
static int idle_timeout
NETWORK * client
the accepted connection
static void handle_inline_and_count(NETWORK *client, CALLBACK_DATA *cb_data)
Handle client inline in the accept thread and update counter.
THREAD_POOL * worker_pool
thread pool for dispatching (modes single-pool and pooled)
static void on_accept_pooled(NETWORK *conn, void *user_data)
Accept pool callback: dispatches to thread pool.
#define MODE_SINGLE_INLINE
mode constants
CALLBACK_DATA * cb_data
back pointer to callback data for counting
static void handle_client(NETWORK *client)
Handle a single client: read one message, echo it back, close.
#define MODE_POOLED
static void dispatch_to_pool(NETWORK *client, CALLBACK_DATA *cb_data)
Dispatch a client to the thread pool for handling.
data passed to accept callback and worker threads
data passed to worker thread function
int main(void)
Definition ex_atlas.c:117
static int log_level
static int mode
NETWORK * server
char * addr
char * port
size_t total_errors
total accept errors
size_t active_threads
number of accept threads currently running
size_t total_timeouts
total accept timeouts (no connection available)
size_t total_accepted
total connections successfully accepted
NETW_ACCEPT_POOL * netw_accept_pool_create(NETWORK *server, size_t nb_threads, int accept_timeout, netw_accept_callback_t callback, void *user_data)
Create a new accept pool.
int netw_accept_pool_get_stats(NETW_ACCEPT_POOL *pool, NETW_ACCEPT_POOL_STATS *stats)
Get a snapshot of pool statistics.
int netw_accept_pool_wait(NETW_ACCEPT_POOL *pool, int timeout_sec)
Wait for all accept threads to finish after a stop request.
int netw_accept_pool_destroy(NETW_ACCEPT_POOL **pool)
Destroy an accept pool.
int netw_accept_pool_stop(NETW_ACCEPT_POOL *pool)
Request the accept pool to stop.
int netw_accept_pool_start(NETW_ACCEPT_POOL *pool)
Start the accept pool (launches accept threads).
Structure of a parallel accept pool.
Statistics for the accept pool.
#define FreeNoLog(__ptr)
Free Handler without log.
Definition n_common.h:272
#define Malloc(__ptr, __struct, __size)
Malloc Handler to get errors and set to 0.
Definition n_common.h:204
#define __n_assert(__ptr, __ret)
macro to assert things
Definition n_common.h:279
#define Free(__ptr)
Free Handler to get errors.
Definition n_common.h:263
#define n_log(__LEVEL__,...)
Logging function wrapper to get line and func.
Definition n_log.h:113
#define LOG_DEBUG
debug-level messages
Definition n_log.h:108
#define LOG_ERR
error conditions
Definition n_log.h:100
void set_log_level(const int log_level)
Set the global log level value ( static int LOG_LEVEL ).
Definition n_log.c:123
#define LOG_NOTICE
normal but significant condition
Definition n_log.h:104
#define LOG_INFO
informational
Definition n_log.h:106
A box including a string and his lenght.
Definition n_str.h:61
void u_sleep(unsigned int usec)
wrapper around usleep for API consistency
Definition n_time.c:54
int start_HiTimer(N_TIME *timer)
Initialize or restart from zero any N_TIME HiTimer.
Definition n_time.c:85
time_t get_msec(N_TIME *timer)
Poll any N_TIME HiTimer, returning msec, and moving currentTime to startTime.
Definition n_time.c:128
Timing Structure.
Definition n_time.h:49
int netw_add_msg(NETWORK *netw, N_STR *msg)
Add a message to send in aimed NETWORK.
Definition n_network.c:4204
int netw_make_listening(NETWORK **netw, char *addr, char *port, int nbpending, int ip_version)
Make a NETWORK be a Listening network.
Definition n_network.c:3493
int netw_start_thr_engine(NETWORK *netw)
Start the NETWORK netw Threaded Engine.
Definition n_network.c:4375
NETWORK * netw_accept_from_ex(NETWORK *from, size_t send_list_limit, size_t recv_list_limit, int blocking, int *retval)
make a normal 'accept' .
Definition n_network.c:3992
#define NETWORK_IPALL
Flag for auto detection by OS of ip version to use.
Definition n_network.h:48
int netw_close(NETWORK **netw)
Closing a specified Network, destroy queues, free the structure.
Definition n_network.c:3258
N_STR * netw_wait_msg(NETWORK *netw, unsigned int refresh, size_t timeout)
Wait a message from aimed NETWORK.
Definition n_network.c:4323
Structure of a NETWORK.
Definition n_network.h:375
#define NORMAL_PROC
processing mode for added func, synced start, can be queued
THREAD_POOL * new_thread_pool(size_t nbmaxthr, size_t nb_max_waiting)
Create a new pool of nbmaxthr threads.
int add_threaded_process(THREAD_POOL *thread_pool, void *(*func_ptr)(void *param), void *param, int mode)
add a function and params to a thread pool
int wait_for_threaded_pool(THREAD_POOL *thread_pool)
Wait for the thread pool to become idle (no active threads, empty waiting list), blocking without pol...
int destroy_threaded_pool(THREAD_POOL **pool, unsigned int delay)
Stop every thread of a pool and free it.
Structure of a thread pool.
Common headers and low-level functions & define.
Generic log system.
Network Engine.
Accept pool for parallel connection acceptance (nginx-style).
Thread pool declaration.