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
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
76#define MODE_SINGLE_INLINE 0
77#define MODE_SINGLE_POOL 1
78#define MODE_POOLED 2
79
81typedef struct CALLBACK_DATA {
83 size_t handled;
85 pthread_mutex_t lock;
89
94static void handle_client(NETWORK* client) {
95 __n_assert(client, return);
96
98
99 N_STR* msg = netw_wait_msg(client, 10000, 20000000);
100 if (msg) {
101 netw_add_msg(client, msg);
102 u_sleep(50000);
103 }
104
105 netw_close(&client);
106}
107
115
121static void* worker_handle_client(void* ptr) {
122 WORKER_ARG* arg = (WORKER_ARG*)ptr;
123 __n_assert(arg, return NULL);
124
125 handle_client(arg->client);
126
127 pthread_mutex_lock(&arg->cb_data->lock);
128 arg->cb_data->handled++;
129 size_t h = arg->cb_data->handled;
130 pthread_mutex_unlock(&arg->cb_data->lock);
131
132 if (h % 100 == 0) {
133 n_log(LOG_NOTICE, "handled %zu connections", h);
134 }
135
136 Free(arg);
137 return NULL;
138}
139
145static void dispatch_to_pool(NETWORK* client, CALLBACK_DATA* cb_data) {
146 __n_assert(client, return);
147 __n_assert(cb_data, netw_close(&client); return);
148 __n_assert(cb_data->worker_pool, netw_close(&client); return);
149
150 WORKER_ARG* arg = NULL;
151 Malloc(arg, WORKER_ARG, 1);
152 if (!arg) {
153 n_log(LOG_ERR, "failed to allocate worker arg");
154 netw_close(&client);
155 return;
156 }
157 arg->client = client;
158 arg->cb_data = cb_data;
159
161}
162
168static void handle_inline_and_count(NETWORK* client, CALLBACK_DATA* cb_data) {
169 __n_assert(cb_data, netw_close(&client); return);
170
171 handle_client(client);
172
173 pthread_mutex_lock(&cb_data->lock);
174 cb_data->handled++;
175 size_t h = cb_data->handled;
176 pthread_mutex_unlock(&cb_data->lock);
177
178 if (h % 100 == 0) {
179 n_log(LOG_NOTICE, "handled %zu connections", h);
180 }
181}
182
188static void on_accept_pooled(NETWORK* conn, void* user_data) {
189 CALLBACK_DATA* data = (CALLBACK_DATA*)user_data;
190 __n_assert(data, netw_close(&conn); return);
191 dispatch_to_pool(conn, data);
192}
193
194static void sighandler(int sig) {
195 (void)sig;
196 server_running = 0;
197}
198
199static void usage(void) {
200 fprintf(stderr,
201 "Usage: ex_accept_pool_server [options]\n"
202 " -p PORT port to listen on (required)\n"
203 " -a ADDR address to bind to (optional, default: all)\n"
204 " -m MODE 'single-inline', 'single-pool', or 'pooled' (default: single-inline)\n"
205 " -n COUNT number of connections to handle (default: 500)\n"
206 " -t THREADS number of threads for pool/accept (default: 4)\n"
207 " -V LEVEL log level: LOG_DEBUG, LOG_INFO, LOG_NOTICE, LOG_ERR (default: LOG_NOTICE)\n"
208 " -h show this help\n");
209}
210
211int main(int argc, char** argv) {
212 char* addr = NULL;
213 char* port = NULL;
214 char* mode_str = "single-inline";
215 int nb_threads = 4;
216 int log_level = LOG_NOTICE;
217 int opt;
218
219 while ((opt = getopt(argc, argv, "hp:a:m:n:t:V:")) != -1) {
220 switch (opt) {
221 case 'p':
222 port = strdup(optarg);
223 break;
224 case 'a':
225 addr = strdup(optarg);
226 break;
227 case 'm':
228 mode_str = optarg;
229 break;
230 case 'n':
231 total_target = atoi(optarg);
232 break;
233 case 't':
234 nb_threads = atoi(optarg);
235 break;
236 case 'V':
237 if (!strcmp(optarg, "LOG_DEBUG"))
239 else if (!strcmp(optarg, "LOG_INFO"))
241 else if (!strcmp(optarg, "LOG_NOTICE"))
243 else if (!strcmp(optarg, "LOG_ERR"))
245 break;
246 case 'h':
247 default:
248 usage();
249 exit(1);
250 }
251 }
252
253 if (!port) {
254 fprintf(stderr, "Error: -p PORT is required\n");
255 usage();
256 exit(1);
257 }
258
260 if (strcmp(mode_str, "single-pool") == 0) {
262 } else if (strcmp(mode_str, "pooled") == 0) {
264 } else if (strcmp(mode_str, "single-inline") != 0) {
265 fprintf(stderr, "Error: unknown mode '%s'\n", mode_str);
266 usage();
267 exit(1);
268 }
269
271
272 signal(SIGINT, sighandler);
273 signal(SIGTERM, sighandler);
274#ifdef __linux__
275 signal(SIGPIPE, SIG_IGN);
276#endif
277
278 /* create listening socket */
279 NETWORK* server = NULL;
280 if (netw_make_listening(&server, addr, port, 1024, NETWORK_IPALL) == FALSE) {
281 n_log(LOG_ERR, "Failed to create listening socket on %s:%s", addr ? addr : "*", port);
282 exit(1);
283 }
284 n_log(LOG_NOTICE, "Listening on %s:%s (backlog=1024)", addr ? addr : "*", port);
285
286 CALLBACK_DATA cb_data;
287 cb_data.handled = 0;
288 cb_data.worker_pool = NULL;
289 pthread_mutex_init(&cb_data.lock, NULL);
290
291 struct timespec t_start, t_end;
292 clock_gettime(CLOCK_MONOTONIC, &t_start);
293
294 const char* mode_names[] = {"SINGLE-INLINE", "SINGLE-POOL", "POOLED"};
295 n_log(LOG_NOTICE, "=== %s MODE: target %d connections ===", mode_names[mode], total_target);
296
297 if (mode == MODE_SINGLE_INLINE) {
298 /* SINGLE-INLINE MODE
299 * One thread doing accept + handle client in the same thread.
300 * Both accept and handling are fully serialized. */
301 n_log(LOG_NOTICE, "1 thread: accept + handle inline (fully serialized)");
302
303 while (server_running) {
304 pthread_mutex_lock(&cb_data.lock);
305 size_t h = cb_data.handled;
306 pthread_mutex_unlock(&cb_data.lock);
307 if ((int)h >= total_target) {
308 break;
309 }
310
311 int retval = 0;
312 NETWORK* client = netw_accept_from_ex(server, 0, 0, 500, &retval);
313 if (client) {
314 handle_inline_and_count(client, &cb_data);
315 }
316 }
317 } else if (mode == MODE_SINGLE_POOL) {
318 /* SINGLE-POOL MODE
319 * One thread doing accept, dispatching to a worker thread pool.
320 * Accept is serialized, but client handling is parallelized. */
321 n_log(LOG_NOTICE, "1 accept thread, %d worker threads", nb_threads);
322
323 cb_data.worker_pool = new_thread_pool((size_t)nb_threads, (size_t)(total_target + 16));
324 if (!cb_data.worker_pool) {
325 n_log(LOG_ERR, "Failed to create worker thread pool");
326 goto cleanup;
327 }
328
329 int accepted_count = 0;
330 while (server_running && accepted_count < total_target) {
331 int retval = 0;
332 NETWORK* client = netw_accept_from_ex(server, 0, 0, 500, &retval);
333 if (client) {
334 dispatch_to_pool(client, &cb_data);
335 accepted_count++;
336 }
337 }
338
339 /* wait for all workers to finish */
340 n_log(LOG_NOTICE, "all connections accepted, waiting for workers...");
341 wait_for_threaded_pool(cb_data.worker_pool);
342 destroy_threaded_pool(&cb_data.worker_pool, 500000);
343 } else {
344 /* POOLED MODE
345 * N accept threads (accept pool) + worker thread pool.
346 * Both accept and handling are parallelized. */
347 n_log(LOG_NOTICE, "%d accept threads, %d worker threads", nb_threads, nb_threads);
348
349 cb_data.worker_pool = new_thread_pool((size_t)nb_threads, (size_t)(total_target + 16));
350 if (!cb_data.worker_pool) {
351 n_log(LOG_ERR, "Failed to create worker thread pool");
352 goto cleanup;
353 }
354
356 server, (size_t)nb_threads, 500, on_accept_pooled, &cb_data);
357 if (!accept_pool) {
358 n_log(LOG_ERR, "Failed to create accept pool");
359 destroy_threaded_pool(&cb_data.worker_pool, 500000);
360 goto cleanup;
361 }
362
363 if (netw_accept_pool_start(accept_pool) == FALSE) {
364 n_log(LOG_ERR, "Failed to start accept pool");
365 netw_accept_pool_destroy(&accept_pool);
366 destroy_threaded_pool(&cb_data.worker_pool, 500000);
367 goto cleanup;
368 }
369
370 /* wait until we've handled enough connections or user interrupts */
371 while (server_running) {
372 pthread_mutex_lock(&cb_data.lock);
373 size_t h = cb_data.handled;
374 pthread_mutex_unlock(&cb_data.lock);
375
376 if ((int)h >= total_target) {
377 break;
378 }
379
381 netw_accept_pool_get_stats(accept_pool, &stats);
382 n_log(LOG_INFO, "stats: accepted=%zu errors=%zu timeouts=%zu active_threads=%zu",
383 stats.total_accepted, stats.total_errors, stats.total_timeouts, stats.active_threads);
384
385 u_sleep(100000);
386 }
387
388 netw_accept_pool_stop(accept_pool);
389 netw_accept_pool_wait(accept_pool, 10);
390
391 NETW_ACCEPT_POOL_STATS final_stats;
392 netw_accept_pool_get_stats(accept_pool, &final_stats);
393 n_log(LOG_NOTICE, "Pool stats: accepted=%zu errors=%zu timeouts=%zu",
394 final_stats.total_accepted, final_stats.total_errors, final_stats.total_timeouts);
395
396 netw_accept_pool_destroy(&accept_pool);
397
398 /* wait for all workers to finish */
399 n_log(LOG_NOTICE, "accept pool stopped, waiting for workers...");
400 wait_for_threaded_pool(cb_data.worker_pool);
401 destroy_threaded_pool(&cb_data.worker_pool, 500000);
402 }
403
404 clock_gettime(CLOCK_MONOTONIC, &t_end);
405 double elapsed = (double)(t_end.tv_sec - t_start.tv_sec) +
406 (double)(t_end.tv_nsec - t_start.tv_nsec) / 1e9;
407
408 n_log(LOG_NOTICE, "=== DONE: %zu connections in %.3f seconds (%.1f conn/sec) ===",
409 cb_data.handled, elapsed, (double)cb_data.handled / elapsed);
410
411cleanup:
412 pthread_mutex_destroy(&cb_data.lock);
414
417
418 netw_unload();
419 n_log(LOG_NOTICE, "Server exited cleanly");
420
421 return 0;
422}
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
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)
int log_level
Definition ex_fluid.c:60
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:89
#define LOG_DEBUG
debug-level messages
Definition n_log.h:84
#define LOG_ERR
error conditions
Definition n_log.h:76
void set_log_level(const int log_level)
Set the global log level value ( static int LOG_LEVEL )
Definition n_log.c:121
#define LOG_NOTICE
normal but significant condition
Definition n_log.h:80
#define LOG_INFO
informational
Definition n_log.h:82
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 netw_add_msg(NETWORK *netw, N_STR *msg)
Add a message to send in aimed NETWORK.
Definition n_network.c:3569
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:2885
int netw_start_thr_engine(NETWORK *netw)
Start the NETWORK netw Threaded Engine.
Definition n_network.c:3740
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:3358
#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:2662
N_STR * netw_wait_msg(NETWORK *netw, unsigned int refresh, size_t timeout)
Wait a message from aimed NETWORK.
Definition n_network.c:3688
Structure of a NETWORK.
Definition n_network.h:309
#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)
delete a thread_pool, exit the threads and free the structs
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.