moonbridge

view moonbridge.c @ 210:7967c1e4f6d1

Avoid compiler warnings on GNU/Linux (fix)
author jbe
date Mon Jun 22 21:17:17 2015 +0200 (2015-06-22)
parents 05fd82e3cfb7
children a3d569d3e85d
line source
2 /*** Version ***/
3 #define MOONBR_VERSION_STRING "0.4.0"
6 /*** Compile-time configuration ***/
8 #define MOONBR_LUA_PANIC_BUG_WORKAROUND 1
11 /*** C preprocessor macros for portability support ***/
13 #ifndef __has_include
14 #define __has_include(x) 0
15 #endif
18 /*** Include directives for used system libraries ***/
20 #if defined(__linux__)
21 #define _GNU_SOURCE
22 #endif
23 #include <stdlib.h>
24 #include <stdint.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <unistd.h>
28 #include <signal.h>
29 #include <sys/wait.h>
30 #include <sys/resource.h>
31 #include <poll.h>
32 #include <time.h>
33 #include <sys/time.h>
34 #include <sys/socket.h>
35 #include <sys/un.h>
36 #include <netinet/in.h>
37 #include <netdb.h>
38 #include <arpa/inet.h>
39 #include <getopt.h>
40 #include <sys/file.h>
41 #include <syslog.h>
42 #if defined(__FreeBSD__) || __has_include(<libutil.h>)
43 #include <libutil.h>
44 #endif
45 #if defined(__linux__) || __has_include(<bsd/stdio.h>)
46 #include <bsd/stdio.h>
47 #endif
48 #if defined(__linux__) || __has_include(<bsd/libutil.h>)
49 #include <bsd/libutil.h>
50 #endif
51 #if defined(__linux__) || __has_include(<bsd/unistd.h>)
52 #include <bsd/unistd.h>
53 #endif
56 /*** Fallback definitions for missing constants on some platforms ***/
58 /* INFTIM is used as timeout parameter for poll() */
59 #ifndef INFTIM
60 #define INFTIM -1
61 #endif
64 /*** Include directives for Lua ***/
66 #include <lua.h>
67 #include <lauxlib.h>
68 #include <lualib.h>
71 /*** Include directive for moonbridge_io library ***/
73 #include "moonbridge_io.h"
76 /*** Constants ***/
78 /* Backlog option for listen() call */
79 #define MOONBR_LISTEN_BACKLOG 1024
81 /* Maximum length of a timestamp used for strftime() */
82 #define MOONBR_LOG_MAXTIMELEN 40
84 /* Maximum length of a log message */
85 #define MOONBR_LOG_MAXMSGLEN 4095
87 /* Exitcodes passed to exit() call */
88 #define MOONBR_EXITCODE_GRACEFUL 0
89 #define MOONBR_EXITCODE_CMDLINEERROR 1
90 #define MOONBR_EXITCODE_ALREADYRUNNING 2
91 #define MOONBR_EXITCODE_STARTUPERROR 3
92 #define MOONBR_EXITCODE_RUNTIMEERROR 4
94 /* Maximum length of a line sent to stderr by child processes */
95 #define MOONBR_MAXERRORLINELEN 1024
97 /* Maximum length of an error string returned by strerror() */
98 #define MOONBR_MAXSTRERRORLEN 80
100 /* Status bytes exchanged between master and child processes */
101 #define MOONBR_STATUS_IDLE 'I'
102 #define MOONBR_COMMAND_CONNECT 'C'
103 #define MOONBR_COMMAND_TERMINATE 'T'
104 #define MOONBR_STATUS_GOODBYE 'B'
106 /* Constant file descriptors */
107 #define MOONBR_FD_STDERR 2
108 #define MOONBR_FD_CONTROL 3
109 #define MOONBR_FD_END 4
111 /* Return values of moonbr_try_destroy_worker() */
112 #define MOONBR_DESTROY_NONE 0
113 #define MOONBR_DESTROY_PREPARE 1
114 #define MOONBR_DESTROY_IDLE_OR_ASSIGNED 2
117 /*** Types ***/
119 /* Enum for 'moonbr_pstate' */
120 #define MOONBR_PSTATE_STARTUP 0
121 #define MOONBR_PSTATE_RUNNING 1
122 #define MOONBR_PSTATE_FORKED 2
124 /* Enum for 'proto' field of struct moonbr_listener */
125 #define MOONBR_PROTO_MAIN 1
126 #define MOONBR_PROTO_INTERVAL 2
127 #define MOONBR_PROTO_LOCAL 3
128 #define MOONBR_PROTO_TCP 4
130 /* Data structure for a pool's listener that can accept incoming connections */
131 struct moonbr_listener {
132 struct moonbr_pool *pool;
133 struct moonbr_listener *prev_listener; /* previous idle or(!) connected listener */
134 struct moonbr_listener *next_listener; /* next idle or(!) connected listener */
135 int proto;
136 union {
137 struct {
138 char *name; /* name of interval passed to 'connect' function as 'interval' field in table */
139 int strict; /* nonzero = runtime of 'connect' function does not delay interval */
140 struct timeval delay; /* interval between invocations of 'connect' function */
141 struct timeval wakeup; /* point in time of next invocation */
142 } interval;
143 struct {
144 union {
145 struct sockaddr addr_abstract;
146 struct sockaddr_un addr_un;
147 struct sockaddr_in addr_in;
148 struct sockaddr_in6 addr_in6;
149 } addr;
150 socklen_t addrlen;
151 } socket;
152 } type_specific;
153 union {
154 struct {
155 char ip[INET6_ADDRSTRLEN]; /* IP to listen on */
156 int port; /* port number to listen on (in host endianess) */
157 } tcp;
158 } proto_specific;
159 int listenfd; /* -1 = none */
160 int pollidx; /* -1 = none */
161 };
163 /* Data structure for a child process that is handling incoming connections */
164 struct moonbr_worker {
165 struct moonbr_pool *pool;
166 struct moonbr_worker *prev_worker;
167 struct moonbr_worker *next_worker;
168 struct moonbr_worker *prev_idle_worker;
169 struct moonbr_worker *next_idle_worker;
170 int main; /* nonzero = terminate Moonbridge when this worker dies */
171 int idle; /* nonzero = waiting for command from parent process */
172 int assigned; /* nonzero = currently handling a connection */
173 pid_t pid;
174 int controlfd; /* socket to send/receive control message to/from child process */
175 int errorfd; /* socket to receive error output from child process' stderr */
176 char *errorlinebuf; /* optional buffer for collecting stderr data from child process */
177 int errorlinelen; /* number of bytes stored in 'errorlinebuf' */
178 int errorlineovf; /* nonzero = line length overflow */
179 struct timeval idle_expiration; /* point in time until child process may stay in idle state */
180 struct moonbr_listener *restart_interval_listener; /* set while interval listener is assigned */
181 };
183 /* Data structure for a pool of workers and listeners */
184 struct moonbr_pool {
185 int poolnum; /* number of pool for log output */
186 struct moonbr_pool *next_pool; /* next entry in linked list starting with 'moonbr_first_pool' */
187 struct moonbr_worker *first_worker; /* first worker of pool */
188 struct moonbr_worker *last_worker; /* last worker of pool */
189 struct moonbr_worker *first_idle_worker; /* first idle worker of pool */
190 struct moonbr_worker *last_idle_worker; /* last idle worker of pool */
191 int idle_worker_count;
192 int unassigned_worker_count;
193 int total_worker_count;
194 int worker_count_stat; /* only needed for statistics */
195 int pre_fork; /* desired minimum number of unassigned workers */
196 int min_fork; /* desired minimum number of workers in total */
197 int max_fork; /* maximum number of workers */
198 struct timeval fork_delay; /* delay after each fork() until a fork may happen again */
199 struct timeval fork_wakeup; /* point in time when a fork may happen again (unless a worker terminates before) */
200 struct timeval fork_error_delay; /* delay between fork()s when an error during fork or preparation occurred */
201 struct timeval fork_error_wakeup; /* point in time when fork may happen again if an error in preparation occurred */
202 int use_fork_error_wakeup; /* nonzero = error in preparation occured; gets reset on next fork */
203 struct timeval exit_delay; /* delay for terminating excessive workers (unassigned_worker_count > pre_fork) */
204 struct timeval exit_wakeup; /* point in time when terminating an excessive worker */
205 struct timeval idle_timeout; /* delay before an idle worker is terminated */
206 size_t memory_limit; /* maximum bytes of memory that the Lua machine may allocate */
207 int listener_count; /* total number of listeners of pool (and size of 'listener' array at end of this struct) */
208 struct moonbr_listener *first_idle_listener; /* first listener that is idle (i.e. has no waiting connection) */
209 struct moonbr_listener *last_idle_listener; /* last listener that is idle (i.e. has no waiting connection) */
210 struct moonbr_listener *first_connected_listener; /* first listener that has a pending connection */
211 struct moonbr_listener *last_connected_listener; /* last listener that has a pending connection */
212 struct moonbr_listener listener[1]; /* static array of variable(!) size to contain 'listener' structures */
213 };
215 /* Enum for 'channel' field of struct moonbr_poll_worker */
216 #define MOONBR_POLL_WORKER_CONTROLCHANNEL 1
217 #define MOONBR_POLL_WORKER_ERRORCHANNEL 2
219 /* Structure to refer from 'moonbr_poll_worker_fds' entry to worker structure */
220 struct moonbr_poll_worker {
221 struct moonbr_worker *worker;
222 int channel; /* field indicating whether file descriptor is 'controlfd' or 'errorfd' */
223 };
225 /* Variable indicating that clean shutdown was requested */
226 static int moonbr_shutdown_in_progress = 0;
229 /*** Macros for Lua registry ***/
231 /* Lightuserdata keys for Lua registry to store 'prepare', 'connect', and 'finish' functions */
232 #define moonbr_luakey_prepare_func(pool) ((void *)(intptr_t)(pool) + 0)
233 #define moonbr_luakey_connect_func(pool) ((void *)(intptr_t)(pool) + 1)
234 #define moonbr_luakey_finish_func(pool) ((void *)(intptr_t)(pool) + 2)
237 /*** Global variables ***/
239 /* State of process execution */
240 static int moonbr_pstate = MOONBR_PSTATE_STARTUP;
242 /* Process ID of the main process */
243 static pid_t moonbr_masterpid;
245 /* Condition variables set by the signal handler */
246 static volatile sig_atomic_t moonbr_cond_poll = 0;
247 static volatile sig_atomic_t moonbr_cond_terminate = 0;
248 static volatile sig_atomic_t moonbr_cond_interrupt = 0;
249 static volatile sig_atomic_t moonbr_cond_child = 0;
251 /* Socket pair to denote signal delivery when signal handler was called just before poll() */
252 static int moonbr_poll_signalfds[2];
253 #define moonbr_poll_signalfd_read moonbr_poll_signalfds[0]
254 #define moonbr_poll_signalfd_write moonbr_poll_signalfds[1]
256 /* Global variables for pidfile and logging */
257 static struct pidfh *moonbr_pidfh = NULL;
258 static FILE *moonbr_logfile = NULL;
259 static int moonbr_use_syslog = 0;
261 /* First and last entry of linked list of all created pools during initialization */
262 static struct moonbr_pool *moonbr_first_pool = NULL;
263 static struct moonbr_pool *moonbr_last_pool = NULL;
265 /* Total count of pools */
266 static int moonbr_pool_count = 0;
268 /* Set to a nonzero value if dynamic part of 'moonbr_poll_fds' ('moonbr_poll_worker_fds') needs an update */
269 static int moonbr_poll_refresh_needed = 0;
271 /* Array passed to poll(), consisting of static part and dynamic part ('moonbr_poll_worker_fds') */
272 static struct pollfd *moonbr_poll_fds = NULL; /* the array */
273 static int moonbr_poll_fds_bufsize = 0; /* memory allocated for this number of elements */
274 static int moonbr_poll_fds_count = 0; /* total number of elements */
275 static int moonbr_poll_fds_static_count; /* number of elements in static part */
277 /* Dynamic part of 'moonbr_poll_fds' array */
278 #define moonbr_poll_worker_fds (moonbr_poll_fds+moonbr_poll_fds_static_count)
280 /* Additional information for dynamic part of 'moonbr_poll_fds' array */
281 struct moonbr_poll_worker *moonbr_poll_workers; /* the array */
282 static int moonbr_poll_workers_bufsize = 0; /* memory allocated for this number of elements */
283 static int moonbr_poll_worker_count = 0; /* number of elements in array */
285 /* Variable set to nonzero value to disallow further calls of 'listen' function */
286 static int moonbr_booted = 0;
288 /* Verbosity settings */
289 static int moonbr_debug = 0;
290 static int moonbr_stat = 0;
292 /* Memory consumption by Lua machine */
293 static size_t moonbr_memory_usage = 0;
294 static size_t moonbr_memory_limit = 0;
297 /*** Functions for signal handling ***/
299 /* Signal handler for master and child processes */
300 static void moonbr_signal(int sig) {
301 if (getpid() == moonbr_masterpid) {
302 /* master process */
303 switch (sig) {
304 case SIGHUP:
305 case SIGINT:
306 /* fast shutdown requested */
307 moonbr_cond_interrupt = 1;
308 break;
309 case SIGTERM:
310 /* clean shutdown requested */
311 moonbr_cond_terminate = 1;
312 break;
313 case SIGCHLD:
314 /* child process terminated */
315 moonbr_cond_child = 1;
316 break;
317 }
318 if (moonbr_cond_poll) {
319 /* avoid race condition if signal handler is invoked right before poll() */
320 char buf[1] = {0};
321 write(moonbr_poll_signalfd_write, buf, 1);
322 }
323 } else {
324 /* child process forwards certain signals to parent process */
325 switch (sig) {
326 case SIGHUP:
327 case SIGINT:
328 case SIGTERM:
329 kill(moonbr_masterpid, sig);
330 }
331 }
332 }
334 /* Initialize signal handling */
335 static void moonbr_signal_init(){
336 moonbr_masterpid = getpid();
337 signal(SIGHUP, moonbr_signal);
338 signal(SIGINT, moonbr_signal);
339 signal(SIGTERM, moonbr_signal);
340 signal(SIGCHLD, moonbr_signal);
341 signal(SIGUSR1, moonbr_signal);
342 }
345 /*** Functions for logging in master process ***/
347 /* Logs a pre-formatted message with given syslog() priority */
348 static void moonbr_log_msg(int priority, const char *msg) {
349 if (moonbr_logfile) {
350 /* logging to logfile desired (timestamp is prepended in that case) */
351 time_t now_time = 0;
352 struct tm now_tmstruct;
353 char timestr[MOONBR_LOG_MAXTIMELEN+1];
354 time(&now_time);
355 localtime_r(&now_time, &now_tmstruct);
356 if (!strftime(
357 timestr, MOONBR_LOG_MAXTIMELEN+1, "%Y-%m-%d %H:%M:%S %Z: ", &now_tmstruct
358 )) timestr[0] = 0;
359 fprintf(moonbr_logfile, "%s%s\n", timestr, msg);
360 }
361 if (moonbr_use_syslog) {
362 /* logging through syslog desired */
363 syslog(priority, "%s", msg);
364 }
365 }
367 /* Formats a message via vsnprintf() and logs it with given syslog() priority */
368 static void moonbr_log(int priority, const char *message, ...) {
369 char msgbuf[MOONBR_LOG_MAXMSGLEN+1]; /* buffer of static size to store formatted message */
370 int msglen; /* length of full message (may exceed MOONBR_LOG_MAXMSGLEN) */
371 {
372 /* pass variable arguments to vsnprintf() to format message */
373 va_list ap;
374 va_start(ap, message);
375 msglen = vsnprintf(msgbuf, MOONBR_LOG_MAXMSGLEN+1, message, ap);
376 va_end(ap);
377 }
378 {
379 /* split and log message line by line */
380 char *line = msgbuf;
381 while (1) {
382 char *endptr = strchr(line, '\n');
383 if (endptr) {
384 /* terminate string where newline character is found */
385 *endptr = 0;
386 } else if (line != msgbuf && msglen > MOONBR_LOG_MAXMSGLEN) {
387 /* break if line is incomplete and not the first line */
388 break;
389 }
390 moonbr_log_msg(priority, line);
391 if (!endptr) break; /* break if end of formatted message is reached */
392 line = endptr+1; /* otherwise continue with remaining message */
393 }
394 }
395 if (msglen > MOONBR_LOG_MAXMSGLEN) {
396 /* print warning if message was truncated */
397 moonbr_log_msg(priority, "Previous log message has been truncated due to excessive length");
398 }
399 }
402 /*** Termination function ***/
404 /* Kill all child processes, remove PID file (if existent), and exit master process with given exitcode */
405 static void moonbr_terminate(int exitcode) {
406 {
407 struct moonbr_pool *pool;
408 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
409 {
410 struct moonbr_worker *worker;
411 for (worker=pool->first_worker; worker; worker=worker->next_worker) {
412 moonbr_log(LOG_INFO, "Sending SIGKILL to child with PID %i", (int)worker->pid);
413 if (kill(worker->pid, SIGKILL)) {
414 moonbr_log(LOG_ERR, "Error while killing child process: %s", strerror(errno));
415 }
416 }
417 }
418 {
419 int i;
420 for (i=0; i<pool->listener_count; i++) {
421 struct moonbr_listener *listener = &pool->listener[i];
422 if (listener->proto == MOONBR_PROTO_LOCAL) {
423 moonbr_log(LOG_INFO, "Unlinking local socket \"%s\"", listener->type_specific.socket.addr.addr_un.sun_path);
424 if (unlink(listener->type_specific.socket.addr.addr_un.sun_path)) {
425 moonbr_log(LOG_ERR, "Error while unlinking local socket: %s", strerror(errno));
426 }
427 }
428 }
429 }
430 }
431 }
432 moonbr_log(exitcode ? LOG_ERR : LOG_NOTICE, "Terminating with exit code %i", exitcode);
433 if (moonbr_pidfh && pidfile_remove(moonbr_pidfh)) {
434 moonbr_log(LOG_ERR, "Error while removing PID file: %s", strerror(errno));
435 }
436 exit(exitcode);
437 }
439 /* Terminate with either MOONBR_EXITCODE_STARTUPERROR or MOONBR_EXITCODE_RUNTIMEERROR */
440 #define moonbr_terminate_error() \
441 moonbr_terminate( \
442 moonbr_pstate == MOONBR_PSTATE_STARTUP ? \
443 MOONBR_EXITCODE_STARTUPERROR : \
444 MOONBR_EXITCODE_RUNTIMEERROR \
445 )
448 /*** Helper functions ***/
450 /* Fills a 'struct timeval' structure with the current time (using CLOCK_MONOTONIC) */
451 static void moonbr_now(struct timeval *now) {
452 struct timespec ts = {0, };
453 if (clock_gettime(CLOCK_MONOTONIC, &ts)) {
454 moonbr_log(LOG_CRIT, "Error in clock_gettime() call: %s", strerror(errno));
455 moonbr_terminate_error();
456 }
457 *now = (struct timeval){ .tv_sec = ts.tv_sec, .tv_usec = ts.tv_nsec / 1000 };
458 }
460 /* Formats a 'struct timeval' value (not thread-safe) */
461 static char *moonbr_format_timeval(struct timeval *t) {
462 static char buf[32];
463 snprintf(buf, 32, "%ji.%06ji seconds", (intmax_t)t->tv_sec, (intmax_t)t->tv_usec);
464 return buf;
465 }
468 /*** Functions for pool creation and startup ***/
470 /* Creates a 'struct moonbr_pool' structure with a given number of listeners */
471 static struct moonbr_pool *moonbr_create_pool(int listener_count) {
472 struct moonbr_pool *pool;
473 pool = calloc(1,
474 sizeof(struct moonbr_pool) + /* size of 'struct moonbr_pool' with one listener */
475 (listener_count-1) * sizeof(struct moonbr_listener) /* size of extra listeners */
476 );
477 if (!pool) {
478 moonbr_log(LOG_CRIT, "Memory allocation error");
479 moonbr_terminate_error();
480 }
481 pool->listener_count = listener_count;
482 {
483 /* initialization of listeners */
484 int i;
485 for (i=0; i<listener_count; i++) {
486 struct moonbr_listener *listener = &pool->listener[i];
487 listener->pool = pool;
488 listener->listenfd = -1;
489 listener->pollidx = -1;
490 }
491 }
492 return pool;
493 }
495 /* Destroys a 'struct moonbr_pool' structure before it has been started */
496 static void moonbr_destroy_pool(struct moonbr_pool *pool) {
497 int i;
498 for (i=0; i<pool->listener_count; i++) {
499 struct moonbr_listener *listener = &pool->listener[i];
500 if (
501 listener->proto == MOONBR_PROTO_INTERVAL &&
502 listener->type_specific.interval.name
503 ) {
504 free(listener->type_specific.interval.name);
505 }
506 }
507 free(pool);
508 }
510 /* Starts a all listeners in a pool */
511 static int moonbr_start_pool(struct moonbr_pool *pool) {
512 moonbr_log(LOG_INFO, "Creating pool", pool->poolnum);
513 {
514 int i;
515 for (i=0; i<pool->listener_count; i++) {
516 struct moonbr_listener *listener = &pool->listener[i];
517 switch (listener->proto) {
518 case MOONBR_PROTO_MAIN:
519 /* nothing to do here: starting main thread is performed in moonbr_run() function */
520 moonbr_log(LOG_INFO, "Adding main thread");
521 break;
522 case MOONBR_PROTO_INTERVAL:
523 /* nothing to do here: starting intervals is performed in moonbr_run() function */
524 if (!listener->type_specific.interval.name) {
525 moonbr_log(LOG_INFO, "Adding unnamed interval listener");
526 } else {
527 moonbr_log(LOG_INFO, "Adding interval listener \"%s\"", listener->type_specific.interval.name);
528 }
529 break;
530 case MOONBR_PROTO_LOCAL:
531 moonbr_log(LOG_INFO, "Adding local socket listener for path \"%s\"", listener->type_specific.socket.addr.addr_un.sun_path);
532 listener->listenfd = socket(PF_LOCAL, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
533 if (listener->listenfd == -1) goto moonbr_start_pool_error;
534 if (!unlink(listener->type_specific.socket.addr.addr_un.sun_path)) {
535 moonbr_log(LOG_WARNING, "Unlinked named socket \"%s\" prior to listening", listener->type_specific.socket.addr.addr_un.sun_path);
536 } else {
537 if (errno != ENOENT) {
538 moonbr_log(LOG_ERR, "Could not unlink named socket \"%s\" prior to listening: %s", listener->type_specific.socket.addr.addr_un.sun_path, strerror(errno));
539 }
540 }
541 if (
542 bind(listener->listenfd, &listener->type_specific.socket.addr.addr_abstract, listener->type_specific.socket.addrlen)
543 ) goto moonbr_start_pool_error;
544 if (listen(listener->listenfd, MOONBR_LISTEN_BACKLOG)) goto moonbr_start_pool_error;
545 break;
546 case MOONBR_PROTO_TCP:
547 moonbr_log(LOG_INFO, "Adding TCP listener on interface \"%s\", port %i", listener->proto_specific.tcp.ip, listener->proto_specific.tcp.port);
548 listener->listenfd = socket(listener->type_specific.socket.addr.addr_abstract.sa_family, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0); /* NOTE: not correctly using PF_* but AF_* constants here */
549 if (listener->listenfd == -1) goto moonbr_start_pool_error;
550 {
551 /* avoid "Address already in use" error when restarting service */
552 static const int reuseval = 1;
553 if (setsockopt(
554 listener->listenfd, SOL_SOCKET, SO_REUSEADDR, &reuseval, sizeof(reuseval)
555 )) goto moonbr_start_pool_error;
556 }
557 {
558 /* default to send TCP RST when process terminates unexpectedly */
559 static const struct linger lingerval = {
560 .l_onoff = 1,
561 .l_linger = 0
562 };
563 if (setsockopt(
564 listener->listenfd, SOL_SOCKET, SO_LINGER, &lingerval, sizeof(lingerval)
565 )) goto moonbr_start_pool_error;
566 }
567 if (
568 bind(listener->listenfd, &listener->type_specific.socket.addr.addr_abstract, listener->type_specific.socket.addrlen)
569 ) goto moonbr_start_pool_error;
570 if (listen(listener->listenfd, MOONBR_LISTEN_BACKLOG)) goto moonbr_start_pool_error;
571 break;
572 default:
573 moonbr_log(LOG_CRIT, "Internal error (should not happen): Unexpected value in listener.proto field");
574 moonbr_terminate_error();
575 }
576 }
577 goto moonbr_start_pool_ok;
578 moonbr_start_pool_error:
579 {
580 int j = i;
581 int errno2 = errno;
582 for (; i>=0; i--) {
583 struct moonbr_listener *listener = &pool->listener[i];
584 if (listener->listenfd != -1) close(listener->listenfd);
585 }
586 errno = errno2;
587 return j;
588 }
589 }
590 moonbr_start_pool_ok:
591 pool->poolnum = ++moonbr_pool_count;
592 moonbr_log(LOG_INFO, "Pool #%i created", pool->poolnum);
593 if (moonbr_last_pool) moonbr_last_pool->next_pool = pool;
594 else moonbr_first_pool = pool;
595 moonbr_last_pool = pool;
596 return -1;
597 }
600 /*** Function to send data and a file descriptor to child process */
602 /* Sends control message of one bye plus optional file descriptor plus optional pointer to child process */
603 static void moonbr_send_control_message(struct moonbr_worker *worker, char status, int fd, void *ptr) {
604 {
605 struct iovec iovector = { .iov_base = &status, .iov_len = 1 }; /* carrying status byte */
606 char control_message_buffer[CMSG_SPACE(sizeof(int))] = {0, }; /* used to transfer file descriptor */
607 struct msghdr message = { .msg_iov = &iovector, .msg_iovlen = 1 }; /* data structure passed to sendmsg() call */
608 if (moonbr_debug) {
609 if (fd == -1) {
610 moonbr_log(LOG_DEBUG, "Sending control message \"%c\" to child process in pool #%i (PID %i)", (int)status, worker->pool->poolnum, (int)worker->pid);
611 } else {
612 moonbr_log(LOG_DEBUG, "Sending control message \"%c\" with file descriptor #%i to child process in pool #%i (PID %i)", (int)status, fd, worker->pool->poolnum, (int)worker->pid);
613 }
614 }
615 if (fd != -1) {
616 /* attach control message with file descriptor */
617 message.msg_control = control_message_buffer;
618 message.msg_controllen = CMSG_SPACE(sizeof(int));
619 {
620 struct cmsghdr *control_message = CMSG_FIRSTHDR(&message);
621 control_message->cmsg_level = SOL_SOCKET;
622 control_message->cmsg_type = SCM_RIGHTS;
623 control_message->cmsg_len = CMSG_LEN(sizeof(int));
624 memcpy(CMSG_DATA(control_message), &fd, sizeof(int));
625 }
626 }
627 while (sendmsg(worker->controlfd, &message, MSG_NOSIGNAL) < 0) {
628 if (errno == EPIPE) {
629 moonbr_log(LOG_ERR, "Error while communicating with idle child process in pool #%i (PID %i): %s", worker->pool->poolnum, (int)worker->pid, strerror(errno));
630 return; /* do not close socket; socket is closed when reading from it */
631 }
632 if (errno != EINTR) {
633 moonbr_log(LOG_CRIT, "Unexpected error while communicating with idle child process in pool #%i (PID %i): %s", worker->pool->poolnum, (int)worker->pid, strerror(errno));
634 moonbr_terminate_error();
635 }
636 }
637 }
638 if (ptr) {
639 char buf[sizeof(void *)];
640 char *pos = buf;
641 int len = sizeof(void *);
642 ssize_t written;
643 if (moonbr_debug) {
644 moonbr_log(LOG_DEBUG, "Sending memory pointer to child process in pool #%i (PID %i)", (int)status, worker->pool->poolnum, (int)worker->pid);
645 }
646 memcpy(buf, &ptr, sizeof(void *));
647 while (len) {
648 written = send(worker->controlfd, pos, len, MSG_NOSIGNAL);
649 if (written > 0) {
650 pos += written;
651 len -= written;
652 } else if (errno == EPIPE) {
653 moonbr_log(LOG_ERR, "Error while communicating with idle child process in pool #%i (PID %i): %s", worker->pool->poolnum, (int)worker->pid, strerror(errno));
654 return; /* do not close socket; socket is closed when reading from it */
655 } else if (errno != EINTR) {
656 moonbr_log(LOG_CRIT, "Unexpected error while communicating with idle child process in pool #%i (PID %i): %s", worker->pool->poolnum, (int)worker->pid, strerror(errno));
657 moonbr_terminate_error();
658 }
659 }
660 }
661 }
664 /*** Functions running in child process ***/
666 /* Logs an error in child process */
667 static void moonbr_child_log(const char *message) {
668 fprintf(stderr, "%s\n", message);
669 }
671 /* Logs a fatal error in child process and terminates process with error status */
672 static void moonbr_child_log_fatal(const char *message) {
673 moonbr_child_log(message);
674 exit(1);
675 }
677 /* Logs an error in child process while appending error string for global errno variable */
678 static void moonbr_child_log_errno(const char *message) {
679 char errmsg[MOONBR_MAXSTRERRORLEN];
680 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
681 fprintf(stderr, "%s: %s\n", message, errmsg);
682 }
684 /* Logs a fatal error in child process while appending error string for errno and terminating process */
685 static void moonbr_child_log_errno_fatal(const char *message) {
686 moonbr_child_log_errno(message);
687 exit(1);
688 }
690 /* Receives a control message consisting of one character plus an optional file descriptor from parent process */
691 static void moonbr_child_receive_control_message(int socketfd, char *status, int *fd) {
692 struct iovec iovector = { .iov_base = status, .iov_len = 1 }; /* reference to status byte variable */
693 char control_message_buffer[CMSG_SPACE(sizeof(int))] = {0, }; /* used to receive file descriptor */
694 struct msghdr message = { /* data structure passed to recvmsg() call */
695 .msg_iov = &iovector,
696 .msg_iovlen = 1,
697 .msg_control = control_message_buffer,
698 .msg_controllen = CMSG_SPACE(sizeof(int))
699 };
700 {
701 int received;
702 while ((received = recvmsg(socketfd, &message, MSG_CMSG_CLOEXEC)) < 0) {
703 if (errno != EINTR) {
704 moonbr_child_log_errno_fatal("Error while trying to receive connection socket from parent process");
705 }
706 }
707 if (!received) {
708 moonbr_child_log_fatal("Unexpected EOF while trying to receive connection socket from parent process");
709 }
710 }
711 {
712 struct cmsghdr *control_message = CMSG_FIRSTHDR(&message);
713 if (control_message) {
714 if (control_message->cmsg_level != SOL_SOCKET) {
715 moonbr_child_log_fatal("Received control message with cmsg_level not equal to SOL_SOCKET");
716 }
717 if (control_message->cmsg_type != SCM_RIGHTS) {
718 moonbr_child_log_fatal("Received control message with cmsg_type not equal to SCM_RIGHTS");
719 }
720 memcpy(fd, CMSG_DATA(control_message), sizeof(int));
721 } else {
722 *fd = -1;
723 }
724 }
725 }
727 /* Receives a pointer from parent process */
728 static void *moonbr_child_receive_pointer(int socketfd) {
729 char buf[sizeof(void *)];
730 char *pos = buf;
731 int len = sizeof(void *);
732 ssize_t bytes_read;
733 while (len) {
734 bytes_read = recv(socketfd, pos, len, 0);
735 if (bytes_read > 0) {
736 pos += bytes_read;
737 len -= bytes_read;
738 } else if (!bytes_read) {
739 moonbr_child_log_fatal("Unexpected EOF while trying to receive memory pointer from parent process");
740 } else if (errno != EINTR) {
741 moonbr_child_log_errno_fatal("Error while trying to receive memory pointer from parent process");
742 }
743 }
744 {
745 void *ptr; /* avoid breaking strict-aliasing rules */
746 memcpy(&ptr, buf, sizeof(void *));
747 return ptr;
748 }
749 }
751 /* Main function of child process to be called after fork() and file descriptor rearrangement */
752 void moonbr_child_run(struct moonbr_pool *pool, lua_State *L) {
753 char controlmsg;
754 int fd;
755 struct itimerval notimer = { { 0, }, { 0, } };
756 lua_rawgetp(L, LUA_REGISTRYINDEX, moonbr_luakey_prepare_func(pool));
757 if (lua_isnil(L, -1)) lua_pop(L, 1);
758 else if (lua_pcall(L, 0, 0, 1)) {
759 fprintf(stderr, "Error in \"prepare\" function: %s\n", lua_tostring(L, -1));
760 exit(1);
761 }
762 while (1) {
763 struct moonbr_listener *listener;
764 if (setitimer(ITIMER_REAL, &notimer, NULL)) {
765 moonbr_child_log_errno_fatal("Could not reset ITIMER_REAL via setitimer()");
766 }
767 controlmsg = MOONBR_STATUS_IDLE;
768 if (write(MOONBR_FD_CONTROL, &controlmsg, 1) <= 0) {
769 moonbr_child_log_errno_fatal("Error while sending ready message to parent process");
770 }
771 moonbr_child_receive_control_message(MOONBR_FD_CONTROL, &controlmsg, &fd);
772 if (!(
773 (controlmsg == MOONBR_COMMAND_TERMINATE && fd == -1) ||
774 (controlmsg == MOONBR_COMMAND_CONNECT)
775 )) {
776 moonbr_child_log_fatal("Received illegal control message from parent process");
777 }
778 if (controlmsg == MOONBR_COMMAND_TERMINATE) break;
779 listener = moonbr_child_receive_pointer(MOONBR_FD_CONTROL);
780 if (
781 listener->proto != MOONBR_PROTO_LOCAL &&
782 listener->proto != MOONBR_PROTO_TCP &&
783 fd >= 0
784 ) {
785 moonbr_child_log_fatal("Received unexpected file descriptor from parent process");
786 } else if (
787 listener->proto != MOONBR_PROTO_MAIN &&
788 listener->proto != MOONBR_PROTO_INTERVAL &&
789 fd < 0
790 ) {
791 moonbr_child_log_fatal("Missing file descriptor from parent process");
792 }
793 if (fd >= 0) moonbr_io_pushhandle(L, fd);
794 lua_rawgetp(L, LUA_REGISTRYINDEX, moonbr_luakey_connect_func(pool));
795 if (fd < 0) {
796 lua_newtable(L);
797 if (listener->proto == MOONBR_PROTO_MAIN) {
798 lua_pushboolean(L, 1);
799 lua_setfield(L, -2, "main");
800 } else if (listener->proto == MOONBR_PROTO_INTERVAL) {
801 lua_pushstring(L,
802 listener->type_specific.interval.name ?
803 listener->type_specific.interval.name : ""
804 );
805 lua_setfield(L, -2, "interval");
806 }
807 } else {
808 lua_pushvalue(L, -2);
809 }
810 if (lua_pcall(L, 1, 1, 1)) {
811 fprintf(stderr, "Error in \"connect\" function: %s\n", lua_tostring(L, -1));
812 exit(1);
813 }
814 if (fd >= 0) moonbr_io_closehandle(L, -2, 0); /* attemt clean close */
815 if (lua_type(L, -1) != LUA_TBOOLEAN || !lua_toboolean(L, -1)) break;
816 #ifdef MOONBR_LUA_PANIC_BUG_WORKAROUND
817 lua_settop(L, 2);
818 #else
819 lua_settop(L, 1);
820 #endif
821 }
822 controlmsg = MOONBR_STATUS_GOODBYE;
823 if (write(MOONBR_FD_CONTROL, &controlmsg, 1) <= 0) {
824 moonbr_child_log_errno_fatal("Error while sending goodbye message to parent process");
825 }
826 if (close(MOONBR_FD_CONTROL) && errno != EINTR) {
827 moonbr_child_log_errno("Error while closing control socket");
828 }
829 lua_rawgetp(L, LUA_REGISTRYINDEX, moonbr_luakey_finish_func(pool));
830 if (lua_isnil(L, -1)) lua_pop(L, 1);
831 else if (lua_pcall(L, 0, 0, 1)) {
832 fprintf(stderr, "Error in \"finish\" function: %s\n", lua_tostring(L, -1));
833 exit(1);
834 }
835 lua_close(L);
836 exit(0);
837 }
840 /*** Functions to spawn child process ***/
842 /* Helper function to send an error message to a file descriptor (not needing a file stream) */
843 static void moonbr_child_emergency_print(int fd, char *message) {
844 size_t len = strlen(message);
845 ssize_t written;
846 while (len) {
847 written = write(fd, message, len);
848 if (written > 0) {
849 message += written;
850 len -= written;
851 } else {
852 if (written != -1 || errno != EINTR) break;
853 }
854 }
855 }
857 /* Helper function to send an error message plus a text for errno to a file descriptor and terminate the process */
858 static void moonbr_child_emergency_error(int fd, char *message) {
859 int errno2 = errno;
860 moonbr_child_emergency_print(fd, message);
861 moonbr_child_emergency_print(fd, ": ");
862 moonbr_child_emergency_print(fd, strerror(errno2));
863 moonbr_child_emergency_print(fd, "\n");
864 exit(1);
865 }
867 /* Creates a child process and (in case of success) registers it in the 'struct moonbr_pool' structure */
868 static int moonbr_create_worker(struct moonbr_pool *pool, lua_State *L) {
869 struct moonbr_worker *worker;
870 worker = calloc(1, sizeof(struct moonbr_worker));
871 if (!worker) {
872 moonbr_log(LOG_CRIT, "Memory allocation error");
873 return -1;
874 }
875 worker->pool = pool;
876 {
877 int controlfds[2];
878 int errorfds[2];
879 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, controlfds)) {
880 moonbr_log(LOG_ERR, "Could not create control socket pair for communcation with child process: %s", strerror(errno));
881 free(worker);
882 return -1;
883 }
884 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, errorfds)) {
885 moonbr_log(LOG_ERR, "Could not create socket pair to redirect stderr of child process: %s", strerror(errno));
886 close(controlfds[0]);
887 close(controlfds[1]);
888 free(worker);
889 return -1;
890 }
891 if (moonbr_logfile && fflush(moonbr_logfile)) {
892 moonbr_log(LOG_CRIT, "Could not flush log file prior to forking: %s", strerror(errno));
893 moonbr_terminate_error();
894 }
895 worker->pid = fork();
896 if (worker->pid == -1) {
897 moonbr_log(LOG_ERR, "Could not fork: %s", strerror(errno));
898 close(controlfds[0]);
899 close(controlfds[1]);
900 close(errorfds[0]);
901 close(errorfds[1]);
902 free(worker);
903 return -1;
904 } else if (!worker->pid) {
905 moonbr_pstate = MOONBR_PSTATE_FORKED;
906 #ifdef MOONBR_LUA_PANIC_BUG_WORKAROUND
907 lua_pushliteral(L, "Failed to pass error message due to bug in Lua panic handler (hint: not enough memory?)");
908 #endif
909 moonbr_memory_limit = pool->memory_limit;
910 if (moonbr_pidfh && pidfile_close(moonbr_pidfh)) {
911 moonbr_child_emergency_error(errorfds[1], "Could not close PID file in forked child process");
912 }
913 if (moonbr_logfile && moonbr_logfile != stderr && fclose(moonbr_logfile)) {
914 moonbr_child_emergency_error(errorfds[1], "Could not close log file in forked child process");
915 }
916 if (dup2(errorfds[1], MOONBR_FD_STDERR) == -1) {
917 moonbr_child_emergency_error(errorfds[1], "Could not duplicate socket to stderr file descriptor");
918 }
919 if (dup2(controlfds[1], MOONBR_FD_CONTROL) == -1) {
920 moonbr_child_emergency_error(errorfds[1], "Could not duplicate control socket");
921 }
922 closefrom(MOONBR_FD_END);
923 moonbr_child_run(pool, L);
924 }
925 if (moonbr_stat) {
926 moonbr_log(LOG_INFO, "Created new worker in pool #%i with PID %i", worker->pool->poolnum, (int)worker->pid);
927 }
928 worker->controlfd = controlfds[0];
929 worker->errorfd = errorfds[0];
930 if (close(controlfds[1]) && errno != EINTR) {
931 moonbr_log(LOG_CRIT, "Could not close opposite end of control file descriptor after forking");
932 moonbr_terminate_error();
933 }
934 if (close(errorfds[1]) && errno != EINTR) {
935 moonbr_log(LOG_CRIT, "Could not close opposite end of control file descriptor after forking");
936 moonbr_terminate_error();
937 }
938 }
939 worker->prev_worker = pool->last_worker;
940 if (worker->prev_worker) worker->prev_worker->next_worker = worker;
941 else pool->first_worker = worker;
942 pool->last_worker = worker;
943 pool->unassigned_worker_count++;
944 pool->total_worker_count++;
945 pool->worker_count_stat = 1;
946 moonbr_poll_refresh_needed = 1;
947 return 0; /* return zero only in case of success */
948 }
951 /*** Functions for queues of 'struct moonbr_listener' ***/
953 /* Appends a 'struct moonbr_listener' to the queue of idle listeners and registers it for poll() */
954 static void moonbr_add_idle_listener(struct moonbr_listener *listener) {
955 listener->prev_listener = listener->pool->last_idle_listener;
956 if (listener->prev_listener) listener->prev_listener->next_listener = listener;
957 else listener->pool->first_idle_listener = listener;
958 listener->pool->last_idle_listener = listener;
959 if (listener->pollidx != -1) moonbr_poll_fds[listener->pollidx].events |= POLLIN;
960 }
962 /* Removes a 'struct moonbr_listener' from the queue of idle listeners and unregisters it from poll() */
963 static void moonbr_remove_idle_listener(struct moonbr_listener *listener) {
964 if (listener->prev_listener) listener->prev_listener->next_listener = listener->next_listener;
965 else listener->pool->first_idle_listener = listener->next_listener;
966 if (listener->next_listener) listener->next_listener->prev_listener = listener->prev_listener;
967 else listener->pool->last_idle_listener = listener->prev_listener;
968 listener->prev_listener = NULL;
969 listener->next_listener = NULL;
970 if (listener->pollidx != -1) moonbr_poll_fds[listener->pollidx].events &= ~POLLIN;
971 }
973 /* Adds a listener to the queue of connected listeners (i.e. waiting to have their incoming connection accepted) */
974 static void moonbr_add_connected_listener(struct moonbr_listener *listener) {
975 listener->prev_listener = listener->pool->last_connected_listener;
976 if (listener->prev_listener) listener->prev_listener->next_listener = listener;
977 else listener->pool->first_connected_listener = listener;
978 listener->pool->last_connected_listener = listener;
979 }
981 /* Removes and returns the first connected listener in the queue */
982 static struct moonbr_listener *moonbr_pop_connected_listener(struct moonbr_pool *pool) {
983 struct moonbr_listener *listener = pool->first_connected_listener;
984 listener->pool->first_connected_listener = listener->next_listener;
985 if (listener->pool->first_connected_listener) listener->pool->first_connected_listener->prev_listener = NULL;
986 else listener->pool->last_connected_listener = NULL;
987 listener->next_listener = NULL;
988 return listener;
989 }
992 /*** Functions to handle polling ***/
994 /* Returns an index to a new initialized entry in moonbr_poll_fds[] */
995 int moonbr_poll_fds_nextindex() {
996 if (moonbr_poll_fds_count >= moonbr_poll_fds_bufsize) {
997 if (moonbr_poll_fds_bufsize) moonbr_poll_fds_bufsize *= 2;
998 else moonbr_poll_fds_bufsize = 1;
999 moonbr_poll_fds = realloc(
1000 moonbr_poll_fds, moonbr_poll_fds_bufsize * sizeof(struct pollfd)
1001 );
1002 if (!moonbr_poll_fds) {
1003 moonbr_log(LOG_CRIT, "Memory allocation error");
1004 moonbr_terminate_error();
1007 moonbr_poll_fds[moonbr_poll_fds_count] = (struct pollfd){0, };
1008 return moonbr_poll_fds_count++;
1011 /* Returns an index to a new initialized entry in moonbr_poll_workers[] */
1012 int moonbr_poll_workers_nextindex() {
1013 if (moonbr_poll_worker_count >= moonbr_poll_workers_bufsize) {
1014 if (moonbr_poll_workers_bufsize) moonbr_poll_workers_bufsize *= 2;
1015 else moonbr_poll_workers_bufsize = 1;
1016 moonbr_poll_workers = realloc(
1017 moonbr_poll_workers, moonbr_poll_workers_bufsize * sizeof(struct moonbr_poll_worker)
1018 );
1019 if (!moonbr_poll_workers) {
1020 moonbr_log(LOG_CRIT, "Memory allocation error");
1021 moonbr_terminate_error();
1024 moonbr_poll_workers[moonbr_poll_worker_count] = (struct moonbr_poll_worker){0, };
1025 return moonbr_poll_worker_count++;
1028 /* Queues all listeners as idle, and initializes static part of moonbr_poll_fds[], which is passed to poll() */
1029 static void moonbr_poll_init() {
1030 if (socketpair(
1031 PF_LOCAL,
1032 SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1033 0,
1034 moonbr_poll_signalfds
1035 )) {
1036 moonbr_log(LOG_CRIT, "Could not create socket pair for signal delivery during polling: %s", strerror(errno));
1037 moonbr_terminate_error();
1040 int j = moonbr_poll_fds_nextindex();
1041 struct pollfd *pollfd = &moonbr_poll_fds[j];
1042 pollfd->fd = moonbr_poll_signalfd_read;
1043 pollfd->events = POLLIN;
1046 struct moonbr_pool *pool;
1047 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1048 int i;
1049 for (i=0; i<pool->listener_count; i++) {
1050 struct moonbr_listener *listener = &pool->listener[i];
1051 if (listener->listenfd != -1) {
1052 int j = moonbr_poll_fds_nextindex();
1053 listener->pollidx = j;
1054 moonbr_poll_fds[j].fd = listener->listenfd;
1056 moonbr_add_idle_listener(listener);
1060 moonbr_poll_fds_static_count = moonbr_poll_fds_count; /* remember size of static part of array */
1063 /* Disables polling of all listeners (required for clean shutdown) */
1064 static void moonbr_poll_shutdown() {
1065 int i;
1066 for (i=1; i<moonbr_poll_fds_static_count; i++) {
1067 moonbr_poll_fds[i].fd = -1;
1071 /* (Re)builds dynamic part of moonbr_poll_fds[] array, and (re)builds moonbr_poll_workers[] array */
1072 static void moonbr_poll_refresh() {
1073 moonbr_poll_refresh_needed = 0;
1074 moonbr_poll_fds_count = moonbr_poll_fds_static_count;
1075 moonbr_poll_worker_count = 0;
1077 struct moonbr_pool *pool;
1078 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1079 struct moonbr_worker *worker;
1080 for (worker=pool->first_worker; worker; worker=worker->next_worker) {
1081 if (worker->controlfd != -1) {
1082 int j = moonbr_poll_fds_nextindex();
1083 int k = moonbr_poll_workers_nextindex();
1084 struct pollfd *pollfd = &moonbr_poll_fds[j];
1085 struct moonbr_poll_worker *poll_worker = &moonbr_poll_workers[k];
1086 pollfd->fd = worker->controlfd;
1087 pollfd->events = POLLIN;
1088 poll_worker->channel = MOONBR_POLL_WORKER_CONTROLCHANNEL;
1089 poll_worker->worker = worker;
1091 if (worker->errorfd != -1) {
1092 int j = moonbr_poll_fds_nextindex();
1093 int k = moonbr_poll_workers_nextindex();
1094 struct pollfd *pollfd = &moonbr_poll_fds[j];
1095 struct moonbr_poll_worker *poll_worker = &moonbr_poll_workers[k];
1096 pollfd->fd = worker->errorfd;
1097 pollfd->events = POLLIN;
1098 poll_worker->channel = MOONBR_POLL_WORKER_ERRORCHANNEL;
1099 poll_worker->worker = worker;
1106 /* resets socket and 'revents' field of moonbr_poll_fds[] for signal delivery just before poll() is called */
1107 static void moonbr_poll_reset_signal() {
1108 ssize_t readcount;
1109 char buf[1];
1110 moonbr_poll_fds[0].revents = 0;
1111 while ((readcount = read(moonbr_poll_signalfd_read, buf, 1)) < 0) {
1112 if (errno == EAGAIN) break;
1113 if (errno != EINTR) {
1114 moonbr_log(LOG_CRIT, "Error while reading from signal delivery socket: %s", strerror(errno));
1115 moonbr_terminate_error();
1118 if (!readcount) {
1119 moonbr_log(LOG_CRIT, "Unexpected EOF when reading from signal delivery socket: %s", strerror(errno));
1120 moonbr_terminate_error();
1125 /*** Shutdown initiation ***/
1127 /* Sets global variable 'moonbr_shutdown_in_progress', closes listeners, and demands worker termination */
1128 static void moonbr_initiate_shutdown() {
1129 struct moonbr_pool *pool;
1130 int i;
1131 if (moonbr_shutdown_in_progress) {
1132 moonbr_log(LOG_NOTICE, "Shutdown already in progress");
1133 return;
1135 moonbr_shutdown_in_progress = 1;
1136 moonbr_log(LOG_NOTICE, "Initiate shutdown");
1137 for (pool = moonbr_first_pool; pool; pool = pool->next_pool) {
1138 for (i=0; i<pool->listener_count; i++) {
1139 struct moonbr_listener *listener = &pool->listener[i];
1140 if (listener->listenfd != -1) {
1141 if (close(listener->listenfd) && errno != EINTR) {
1142 moonbr_log(LOG_CRIT, "Could not close listening socket: %s", strerror(errno));
1143 moonbr_terminate_error();
1148 moonbr_poll_shutdown(); /* avoids loops due to error condition when polling closed listeners */
1150 pid_t pgrp = getpgrp();
1151 moonbr_log(LOG_INFO, "Sending SIGUSR1 to all processes in group %i", (int)pgrp);
1152 if (killpg(pgrp, SIGUSR1)) {
1153 moonbr_log(LOG_WARNING, "Error while sending SIGUSR1 to own process group: %s", strerror(errno));
1159 /*** Functions to handle previously created 'struct moonbr_worker' structures ***/
1161 #define moonbr_try_destroy_worker_stat(str, field) \
1162 moonbr_log(LOG_INFO, "Resource usage in pool #%i for PID %i: " str " %li", worker->pool->poolnum, (int)worker->pid, (long)childusage.field);
1164 /* Destroys a worker structure if socket connections have been closed and child process has terminated */
1165 static int moonbr_try_destroy_worker(struct moonbr_worker *worker) {
1166 if (worker->controlfd != -1 || worker->errorfd != -1) return MOONBR_DESTROY_NONE;
1168 int childstatus;
1169 struct rusage childusage;
1171 pid_t waitedpid;
1172 while (
1173 (waitedpid = wait4(worker->pid, &childstatus, WNOHANG, &childusage)) == -1
1174 ) {
1175 if (errno != EINTR) {
1176 moonbr_log(LOG_CRIT, "Error in wait4() call: %s", strerror(errno));
1177 moonbr_terminate_error();
1180 if (!waitedpid) return 0; /* return 0 if worker couldn't be destroyed */
1181 if (waitedpid != worker->pid) {
1182 moonbr_log(LOG_CRIT, "Wrong PID returned by wait4() call");
1183 moonbr_terminate_error();
1186 if (WIFEXITED(childstatus)) {
1187 if (WEXITSTATUS(childstatus) || moonbr_stat) {
1188 moonbr_log(
1189 WEXITSTATUS(childstatus) ? LOG_WARNING : LOG_INFO,
1190 "Child process in pool #%i with PID %i returned with exit code %i", worker->pool->poolnum, (int)worker->pid, WEXITSTATUS(childstatus)
1191 );
1193 } else if (WIFSIGNALED(childstatus)) {
1194 if (WCOREDUMP(childstatus)) {
1195 moonbr_log(LOG_ERR, "Child process in pool #%i with PID %i died from signal %i (core dump was created)", worker->pool->poolnum, (int)worker->pid, WTERMSIG(childstatus));
1196 } else if (WTERMSIG(childstatus) == SIGALRM) {
1197 moonbr_log(LOG_WARNING, "Child process in pool #%i with PID %i exited prematurely due to timeout", worker->pool->poolnum, (int)worker->pid);
1198 } else {
1199 moonbr_log(LOG_ERR, "Child process in pool #%i with PID %i died from signal %i", worker->pool->poolnum, (int)worker->pid, WTERMSIG(childstatus));
1201 } else {
1202 moonbr_log(LOG_CRIT, "Illegal exit status from child process in pool #%i with PID %i", worker->pool->poolnum, (int)worker->pid);
1203 moonbr_terminate_error();
1205 if (moonbr_stat) {
1206 moonbr_log(LOG_INFO, "Resource usage in pool #%i for PID %i: user time %s", worker->pool->poolnum, (int)worker->pid, moonbr_format_timeval(&childusage.ru_utime));
1207 moonbr_log(LOG_INFO, "Resource usage in pool #%i for PID %i: system time %s", worker->pool->poolnum, (int)worker->pid, moonbr_format_timeval(&childusage.ru_stime));
1208 moonbr_try_destroy_worker_stat("max resident set size", ru_maxrss);
1209 moonbr_try_destroy_worker_stat("integral shared memory size", ru_ixrss);
1210 moonbr_try_destroy_worker_stat("integral unshared data", ru_idrss);
1211 moonbr_try_destroy_worker_stat("integral unshared stack", ru_isrss);
1212 moonbr_try_destroy_worker_stat("page replaims", ru_minflt);
1213 moonbr_try_destroy_worker_stat("page faults", ru_majflt);
1214 moonbr_try_destroy_worker_stat("swaps", ru_nswap);
1215 moonbr_try_destroy_worker_stat("block input operations", ru_inblock);
1216 moonbr_try_destroy_worker_stat("block output operations", ru_oublock);
1217 moonbr_try_destroy_worker_stat("messages sent", ru_msgsnd);
1218 moonbr_try_destroy_worker_stat("messages received", ru_msgrcv);
1219 moonbr_try_destroy_worker_stat("signals received", ru_nsignals);
1220 moonbr_try_destroy_worker_stat("voluntary context switches", ru_nvcsw);
1221 moonbr_try_destroy_worker_stat("involuntary context switches", ru_nivcsw);
1225 int retval = (
1226 (worker->idle || worker->assigned) ?
1227 MOONBR_DESTROY_IDLE_OR_ASSIGNED :
1228 MOONBR_DESTROY_PREPARE
1229 );
1230 if (worker->main) moonbr_initiate_shutdown();
1231 if (worker->prev_worker) worker->prev_worker->next_worker = worker->next_worker;
1232 else worker->pool->first_worker = worker->next_worker;
1233 if (worker->next_worker) worker->next_worker->prev_worker = worker->prev_worker;
1234 else worker->pool->last_worker = worker->prev_worker;
1235 if (worker->idle) {
1236 if (worker->prev_idle_worker) worker->prev_idle_worker->next_idle_worker = worker->next_idle_worker;
1237 else worker->pool->first_idle_worker = worker->next_idle_worker;
1238 if (worker->next_idle_worker) worker->next_idle_worker->prev_idle_worker = worker->prev_idle_worker;
1239 else worker->pool->last_idle_worker = worker->prev_idle_worker;
1240 worker->pool->idle_worker_count--;
1242 if (!worker->assigned) worker->pool->unassigned_worker_count--;
1243 worker->pool->total_worker_count--;
1244 worker->pool->worker_count_stat = 1;
1245 if (worker->errorlinebuf) free(worker->errorlinebuf);
1246 free(worker);
1247 return retval;
1251 /* Marks a worker as idle and stores it in a queue, optionally setting 'idle_expiration' value */
1252 static void moonbr_add_idle_worker(struct moonbr_worker *worker) {
1253 worker->prev_idle_worker = worker->pool->last_idle_worker;
1254 if (worker->prev_idle_worker) worker->prev_idle_worker->next_idle_worker = worker;
1255 else worker->pool->first_idle_worker = worker;
1256 worker->pool->last_idle_worker = worker;
1257 worker->idle = 1;
1258 worker->pool->idle_worker_count++;
1259 if (worker->assigned) {
1260 worker->assigned = 0;
1261 worker->pool->unassigned_worker_count++;
1263 worker->pool->worker_count_stat = 1;
1264 if (timerisset(&worker->pool->idle_timeout)) {
1265 struct timeval now;
1266 moonbr_now(&now);
1267 timeradd(&now, &worker->pool->idle_timeout, &worker->idle_expiration);
1271 /* Pops a worker from the queue of idle workers (idle queue must not be empty) */
1272 static struct moonbr_worker *moonbr_pop_idle_worker(struct moonbr_pool *pool) {
1273 struct moonbr_worker *worker;
1274 worker = pool->first_idle_worker;
1275 pool->first_idle_worker = worker->next_idle_worker;
1276 if (pool->first_idle_worker) pool->first_idle_worker->prev_idle_worker = NULL;
1277 else pool->last_idle_worker = NULL;
1278 worker->next_idle_worker = NULL;
1279 worker->idle = 0;
1280 worker->pool->idle_worker_count--;
1281 worker->assigned = 1;
1282 worker->pool->unassigned_worker_count--;
1283 worker->pool->worker_count_stat = 1;
1284 return worker;
1288 /*** Functions to communicate with child processes ***/
1290 /* Tells child process to terminate */
1291 static void moonbr_terminate_idle_worker(struct moonbr_worker *worker) {
1292 moonbr_send_control_message(worker, MOONBR_COMMAND_TERMINATE, -1, NULL);
1295 /* Handles status messages from child process */
1296 static void moonbr_read_controlchannel(struct moonbr_worker *worker) {
1297 char controlmsg;
1299 ssize_t bytes_read;
1300 while ((bytes_read = read(worker->controlfd, &controlmsg, 1)) <= 0) {
1301 if (bytes_read == 0 || errno == ECONNRESET) {
1302 moonbr_log(LOG_WARNING, "Child process in pool #%i with PID %i unexpectedly closed control socket", worker->pool->poolnum, (int)worker->pid);
1303 if (close(worker->controlfd) && errno != EINTR) {
1304 moonbr_log(LOG_CRIT, "Error while closing control socket to child process in pool #%i with PID %i: %s", worker->pool->poolnum, (int)worker->pid, strerror(errno));
1305 moonbr_terminate_error();
1307 worker->controlfd = -1;
1308 moonbr_poll_refresh_needed = 1;
1309 return;
1311 if (errno != EINTR) {
1312 moonbr_log(LOG_CRIT, "Unexpected error while reading control socket from child process in pool #%i with PID %i: %s", worker->pool->poolnum, (int)worker->pid, strerror(errno));
1313 moonbr_terminate_error();
1317 if (worker->idle) {
1318 moonbr_log(LOG_CRIT, "Unexpected data from supposedly idle child process in pool #%i with PID %i", worker->pool->poolnum, (int)worker->pid);
1319 moonbr_terminate_error();
1321 if (moonbr_debug) {
1322 moonbr_log(LOG_DEBUG, "Received control message from child in pool #%i with PID %i: \"%c\"", worker->pool->poolnum, (int)worker->pid, (int)controlmsg);
1324 switch (controlmsg) {
1325 case MOONBR_STATUS_IDLE:
1326 if (moonbr_stat) {
1327 moonbr_log(LOG_INFO, "Child process in pool #%i with PID %i reports as idle", worker->pool->poolnum, (int)worker->pid);
1329 moonbr_add_idle_worker(worker);
1330 break;
1331 case MOONBR_STATUS_GOODBYE:
1332 if (moonbr_stat) {
1333 moonbr_log(LOG_INFO, "Child process in pool #%i with PID %i announced termination", worker->pool->poolnum, (int)worker->pid);
1335 if (close(worker->controlfd) && errno != EINTR) {
1336 moonbr_log(LOG_CRIT, "Error while closing control socket to child process in pool #%i with PID %i: %s", worker->pool->poolnum, (int)worker->pid, strerror(errno));
1337 moonbr_terminate_error();
1339 worker->controlfd = -1;
1340 moonbr_poll_refresh_needed = 1;
1341 break;
1342 default:
1343 moonbr_log(LOG_CRIT, "Received illegal data (\"%c\") while reading control socket from child process in pool #%i with PID %i", (int)controlmsg, worker->pool->poolnum, (int)worker->pid);
1344 moonbr_terminate_error();
1348 /* Handles stderr stream from child process */
1349 static void moonbr_read_errorchannel(struct moonbr_worker *worker) {
1350 char staticbuf[MOONBR_MAXERRORLINELEN+1];
1351 char *buf = worker->errorlinebuf;
1352 if (!buf) buf = staticbuf;
1354 ssize_t bytes_read;
1355 while (
1356 (bytes_read = read(
1357 worker->errorfd,
1358 buf + worker->errorlinelen,
1359 MOONBR_MAXERRORLINELEN+1 - worker->errorlinelen
1360 )) <= 0
1361 ) {
1362 if (bytes_read == 0 || errno == ECONNRESET) {
1363 if (moonbr_debug) {
1364 moonbr_log(LOG_DEBUG, "Child process in pool #%i with PID %i closed stderr socket", worker->pool->poolnum, (int)worker->pid);
1366 if (close(worker->errorfd) && errno != EINTR) {
1367 moonbr_log(LOG_CRIT, "Error while closing stderr socket to child process in pool #%i with PID %i: %s", worker->pool->poolnum, (int)worker->pid, strerror(errno));
1368 moonbr_terminate_error();
1370 worker->errorfd = -1;
1371 moonbr_poll_refresh_needed = 1;
1372 break;
1374 if (errno != EINTR) {
1375 moonbr_log(LOG_CRIT, "Unexpected error while reading stderr from child process in pool #%i with PID %i: %s", worker->pool->poolnum, (int)worker->pid, strerror(errno));
1376 moonbr_terminate_error();
1379 worker->errorlinelen += bytes_read;
1382 int i;
1383 for (i=0; i<worker->errorlinelen; i++) {
1384 if (buf[i] == '\n') buf[i] = 0;
1385 if (!buf[i]) {
1386 if (worker->errorlineovf) {
1387 worker->errorlineovf = 0;
1388 } else {
1389 moonbr_log(LOG_WARNING, "Error log from process in pool #%i with PID %i: %s", worker->pool->poolnum, (int)worker->pid, buf);
1391 worker->errorlinelen -= i+1;
1392 memmove(buf, buf+i+1, worker->errorlinelen);
1393 i = -1;
1396 if (i > MOONBR_MAXERRORLINELEN) {
1397 buf[MOONBR_MAXERRORLINELEN] = 0;
1398 if (!worker->errorlineovf) {
1399 moonbr_log(LOG_WARNING, "Error log from process in pool #%i with PID %i (line has been truncated): %s", worker->pool->poolnum, (int)worker->pid, buf);
1401 worker->errorlinelen = 0;
1402 worker->errorlineovf = 1;
1405 if (!worker->errorlinebuf && worker->errorlinelen) { /* allocate buffer on heap only if necessary */
1406 worker->errorlinebuf = malloc((MOONBR_MAXERRORLINELEN+1) * sizeof(char));
1407 if (!worker->errorlinebuf) {
1408 moonbr_log(LOG_CRIT, "Memory allocation error");
1409 moonbr_terminate_error();
1411 memcpy(worker->errorlinebuf, staticbuf, worker->errorlinelen);
1416 /*** Handler for incoming connections ***/
1418 /* Accepts one or more incoming connections on listener socket and passes it to worker(s) popped from idle queue */
1419 static void moonbr_connect(struct moonbr_pool *pool) {
1420 struct moonbr_listener *listener = moonbr_pop_connected_listener(pool);
1421 struct moonbr_worker *worker;
1422 if (listener->proto == MOONBR_PROTO_MAIN) {
1423 worker = moonbr_pop_idle_worker(pool);
1424 if (moonbr_stat) {
1425 moonbr_log(LOG_INFO, "Dispatching main thread of pool #%i to PID %i", listener->pool->poolnum, (int)worker->pid);
1427 worker->main = 1;
1428 moonbr_send_control_message(worker, MOONBR_COMMAND_CONNECT, -1, listener);
1429 /* do not push listener to queue of idle listeners */
1430 } else if (listener->proto == MOONBR_PROTO_INTERVAL) {
1431 worker = moonbr_pop_idle_worker(pool);
1432 if (moonbr_stat) {
1433 moonbr_log(LOG_INFO, "Dispatching interval timer \"%s\" of pool #%i to PID %i", listener->type_specific.interval.name, listener->pool->poolnum, (int)worker->pid);
1435 worker->restart_interval_listener = listener;
1436 moonbr_send_control_message(worker, MOONBR_COMMAND_CONNECT, -1, listener);
1437 /* do not push listener to queue of idle listeners yet */
1438 } else {
1439 int peerfd;
1440 do {
1441 peerfd = accept4(listener->listenfd, NULL, NULL, SOCK_CLOEXEC);
1442 if (peerfd == -1) {
1443 if (errno == EWOULDBLOCK) {
1444 break;
1445 } else if (errno == ECONNABORTED) {
1446 moonbr_log(LOG_WARNING, "Connection aborted before accepting it");
1447 break;
1448 } else if (errno != EINTR) {
1449 moonbr_log(LOG_ERR, "Could not accept socket connection: %s", strerror(errno));
1450 moonbr_terminate_error();
1452 } else {
1453 worker = moonbr_pop_idle_worker(pool);
1454 if (moonbr_stat) {
1455 moonbr_log(LOG_INFO, "Dispatching connection for pool #%i to PID %i", listener->pool->poolnum, (int)worker->pid);
1457 moonbr_send_control_message(worker, MOONBR_COMMAND_CONNECT, peerfd, listener);
1458 if (close(peerfd) && errno != EINTR) {
1459 moonbr_log(LOG_ERR, "Could not close incoming socket connection in parent process: %s", strerror(errno));
1460 moonbr_terminate_error();
1463 } while (pool->first_idle_worker);
1464 moonbr_add_idle_listener(listener);
1469 /*** Functions to initialize and restart interval timers ***/
1471 /* Initializes all interval timers */
1472 static void moonbr_interval_initialize() {
1473 struct timeval now;
1474 struct moonbr_pool *pool;
1475 moonbr_now(&now);
1476 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1477 int i;
1478 for (i=0; i<pool->listener_count; i++) {
1479 struct moonbr_listener *listener = &pool->listener[i];
1480 if (listener->proto == MOONBR_PROTO_INTERVAL) {
1481 timeradd(
1482 &now,
1483 &listener->type_specific.interval.delay,
1484 &listener->type_specific.interval.wakeup
1485 );
1491 /* If necessary, restarts interval timers and queues interval listener as idle after a worker changed status */
1492 static void moonbr_interval_restart(
1493 struct moonbr_worker *worker,
1494 struct timeval *now /* passed to synchronize with moonbr_run() function */
1495 ) {
1496 struct moonbr_listener *listener = worker->restart_interval_listener;
1497 if (listener) {
1498 moonbr_add_idle_listener(listener);
1499 worker->restart_interval_listener = NULL;
1500 if (listener->type_specific.interval.strict) {
1501 timeradd(
1502 &listener->type_specific.interval.wakeup,
1503 &listener->type_specific.interval.delay,
1504 &listener->type_specific.interval.wakeup
1505 );
1506 if (timercmp(&listener->type_specific.interval.wakeup, now, <)) {
1507 listener->type_specific.interval.wakeup = *now;
1509 } else {
1510 timeradd(
1511 now,
1512 &listener->type_specific.interval.delay,
1513 &listener->type_specific.interval.wakeup
1514 );
1520 /*** Main loop and helper functions ***/
1522 /* Stores the earliest required wakeup time in 'wait' variable */
1523 static void moonbr_calc_wait(struct timeval *wait, struct timeval *wakeup) {
1524 if (!timerisset(wait) || timercmp(wakeup, wait, <)) *wait = *wakeup;
1527 /* Main loop of Moonbridge system (including initialization of signal handlers and polling structures) */
1528 static void moonbr_run(lua_State *L) {
1529 struct timeval now;
1530 struct moonbr_pool *pool;
1531 struct moonbr_worker *worker;
1532 struct moonbr_worker *next_worker; /* needed when worker is removed during iteration of workers */
1533 struct moonbr_listener *listener;
1534 struct moonbr_listener *next_listener; /* needed when listener is removed during iteration of listeners */
1535 int i;
1536 moonbr_poll_init(); /* must be executed before moonbr_signal_init() */
1537 moonbr_signal_init();
1538 moonbr_interval_initialize();
1539 moonbr_pstate = MOONBR_PSTATE_RUNNING;
1540 while (1) {
1541 struct timeval wait = {0, }; /* point in time when premature wakeup of poll() is required */
1542 if (moonbr_cond_interrupt) {
1543 moonbr_log(LOG_WARNING, "Fast shutdown requested");
1544 moonbr_terminate(MOONBR_EXITCODE_GRACEFUL);
1546 if (moonbr_cond_terminate) {
1547 moonbr_initiate_shutdown();
1548 moonbr_cond_terminate = 0;
1550 moonbr_cond_child = 0; /* must not be reset between moonbr_try_destroy_worker() and poll() */
1551 moonbr_now(&now);
1552 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1553 int terminated_worker_count = 0; /* allows shortcut for new worker creation */
1554 /* terminate idle workers when expired */
1555 if (timerisset(&pool->idle_timeout)) {
1556 while ((worker = pool->first_idle_worker) != NULL) {
1557 if (timercmp(&worker->idle_expiration, &now, >)) break;
1558 moonbr_pop_idle_worker(pool);
1559 moonbr_terminate_idle_worker(worker);
1562 /* mark listeners as connected when incoming connection is pending */
1563 for (listener=pool->first_idle_listener; listener; listener=next_listener) {
1564 next_listener = listener->next_listener; /* extra variable necessary due to changing list */
1565 if (listener->pollidx != -1) {
1566 if (moonbr_poll_fds[listener->pollidx].revents) {
1567 moonbr_poll_fds[listener->pollidx].revents = 0;
1568 moonbr_remove_idle_listener(listener);
1569 moonbr_add_connected_listener(listener);
1571 } else if (
1572 listener->proto != MOONBR_PROTO_INTERVAL ||
1573 !timercmp(&listener->type_specific.interval.wakeup, &now, >)
1574 ) {
1575 moonbr_remove_idle_listener(listener);
1576 moonbr_add_connected_listener(listener);
1579 /* process input from child processes */
1580 for (i=0; i<moonbr_poll_worker_count; i++) {
1581 if (moonbr_poll_worker_fds[i].revents) {
1582 moonbr_poll_worker_fds[i].revents = 0;
1583 struct moonbr_poll_worker *poll_worker = &moonbr_poll_workers[i];
1584 switch (poll_worker->channel) {
1585 case MOONBR_POLL_WORKER_CONTROLCHANNEL:
1586 moonbr_read_controlchannel(poll_worker->worker);
1587 moonbr_interval_restart(poll_worker->worker, &now);
1588 break;
1589 case MOONBR_POLL_WORKER_ERRORCHANNEL:
1590 moonbr_read_errorchannel(poll_worker->worker);
1591 break;
1595 /* collect dead child processes */
1596 for (worker=pool->first_worker; worker; worker=next_worker) {
1597 next_worker = worker->next_worker; /* extra variable necessary due to changing list */
1598 switch (moonbr_try_destroy_worker(worker)) {
1599 case MOONBR_DESTROY_PREPARE:
1600 pool->use_fork_error_wakeup = 1;
1601 break;
1602 case MOONBR_DESTROY_IDLE_OR_ASSIGNED:
1603 terminated_worker_count++;
1604 break;
1607 if (!moonbr_shutdown_in_progress) {
1608 /* connect listeners with idle workers */
1609 while (pool->first_connected_listener && pool->first_idle_worker) {
1610 moonbr_connect(pool);
1612 /* create new worker processes */
1613 while (
1614 pool->total_worker_count < pool->max_fork && (
1615 pool->unassigned_worker_count < pool->pre_fork ||
1616 pool->total_worker_count < pool->min_fork
1618 ) {
1619 if (pool->use_fork_error_wakeup) {
1620 if (timercmp(&pool->fork_error_wakeup, &now, >)) {
1621 moonbr_calc_wait(&wait, &pool->fork_error_wakeup);
1622 break;
1624 } else {
1625 if (terminated_worker_count) {
1626 terminated_worker_count--;
1627 } else if (timercmp(&pool->fork_wakeup, &now, >)) {
1628 moonbr_calc_wait(&wait, &pool->fork_wakeup);
1629 break;
1632 if (moonbr_create_worker(pool, L)) {
1633 /* on error, enforce error delay */
1634 timeradd(&now, &pool->fork_error_delay, &pool->fork_error_wakeup);
1635 pool->use_fork_error_wakeup = 1;
1636 moonbr_calc_wait(&wait, &pool->fork_error_wakeup);
1637 break;
1638 } else {
1639 /* normal fork delay on success */
1640 timeradd(&now, &pool->fork_delay, &pool->fork_wakeup);
1641 timeradd(&now, &pool->fork_error_delay, &pool->fork_error_wakeup);
1642 pool->use_fork_error_wakeup = 0; /* gets set later if error occures during preparation */
1645 /* terminate excessive worker processes */
1646 while (
1647 pool->total_worker_count > pool->min_fork &&
1648 pool->idle_worker_count > pool->pre_fork
1649 ) {
1650 if (timerisset(&pool->exit_wakeup)) {
1651 if (timercmp(&pool->exit_wakeup, &now, >)) {
1652 moonbr_calc_wait(&wait, &pool->exit_wakeup);
1653 break;
1655 moonbr_terminate_idle_worker(moonbr_pop_idle_worker(pool));
1656 timeradd(&now, &pool->exit_delay, &pool->exit_wakeup);
1657 } else {
1658 timeradd(&now, &pool->exit_delay, &pool->exit_wakeup);
1659 break;
1662 if (!(
1663 pool->total_worker_count > pool->min_fork &&
1664 pool->idle_worker_count > pool->pre_fork
1665 )) {
1666 timerclear(&pool->exit_wakeup); /* timer gets restarted later when there are excessive workers */
1669 /* optionally output worker count stats */
1670 if (moonbr_stat && pool->worker_count_stat) {
1671 pool->worker_count_stat = 0;
1672 moonbr_log(
1673 LOG_INFO,
1674 "Worker count for pool #%i: %i idle, %i assigned, %i total",
1675 pool->poolnum, pool->idle_worker_count,
1676 pool->total_worker_count - pool->unassigned_worker_count,
1677 pool->total_worker_count);
1679 /* calculate wakeup time for interval listeners */
1680 for (listener=pool->first_idle_listener; listener; listener=listener->next_listener) {
1681 if (listener->proto == MOONBR_PROTO_INTERVAL) {
1682 moonbr_calc_wait(&wait, &listener->type_specific.interval.wakeup);
1685 /* calculate wakeup time for idle workers (only first idle worker is significant) */
1686 if (timerisset(&pool->idle_timeout) && pool->first_idle_worker) {
1687 moonbr_calc_wait(&wait, &pool->first_idle_worker->idle_expiration);
1690 /* terminate idle workers in case of shutdown and check if shutdown is complete */
1691 if (moonbr_shutdown_in_progress) {
1692 int remaining = 0;
1693 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1694 while (pool->idle_worker_count) {
1695 moonbr_terminate_idle_worker(moonbr_pop_idle_worker(pool));
1697 if (pool->first_worker) remaining = 1;
1699 if (!remaining) {
1700 moonbr_log(LOG_INFO, "All worker threads have terminated");
1701 moonbr_terminate(MOONBR_EXITCODE_GRACEFUL);
1704 if (moonbr_poll_refresh_needed) moonbr_poll_refresh();
1705 moonbr_cond_poll = 1;
1706 if (!moonbr_cond_child && !moonbr_cond_terminate && !moonbr_cond_interrupt) {
1707 int timeout;
1708 if (timerisset(&wait)) {
1709 if (timercmp(&wait, &now, <)) {
1710 moonbr_log(LOG_CRIT, "Internal error (should not happen): Future is in the past");
1711 moonbr_terminate_error();
1713 timersub(&wait, &now, &wait);
1714 timeout = wait.tv_sec * 1000 + wait.tv_usec / 1000;
1715 } else {
1716 timeout = INFTIM;
1718 if (moonbr_debug) {
1719 moonbr_log(LOG_DEBUG, "Waiting for I/O");
1721 poll(moonbr_poll_fds, moonbr_poll_fds_count, timeout);
1722 } else {
1723 if (moonbr_debug) {
1724 moonbr_log(LOG_DEBUG, "Do not wait for I/O");
1727 moonbr_cond_poll = 0;
1728 moonbr_poll_reset_signal();
1733 /*** Lua interface ***/
1735 static int moonbr_lua_panic(lua_State *L) {
1736 const char *errmsg;
1737 errmsg = lua_tostring(L, -1);
1738 if (!errmsg) {
1739 if (lua_isnoneornil(L, -1)) errmsg = "(error message is nil)";
1740 else errmsg = "(error message is not a string)";
1742 if (moonbr_pstate == MOONBR_PSTATE_FORKED) {
1743 fprintf(stderr, "Uncaught Lua error: %s\n", errmsg);
1744 exit(1);
1745 } else {
1746 moonbr_log(LOG_CRIT, "Uncaught Lua error: %s", errmsg);
1747 moonbr_terminate_error();
1749 return 0;
1752 static int moonbr_addtraceback(lua_State *L) {
1753 luaL_traceback(L, L, luaL_tolstring(L, 1, NULL), 1);
1754 return 1;
1757 /* Memory allocator that allows limiting memory consumption */
1758 static void *moonbr_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
1759 (void)ud; /* not used */
1760 if (nsize == 0) {
1761 if (ptr) {
1762 moonbr_memory_usage -= osize;
1763 free(ptr);
1765 return NULL;
1766 } else if (ptr) {
1767 if (
1768 moonbr_memory_limit &&
1769 nsize > osize &&
1770 moonbr_memory_usage + (nsize - osize) > moonbr_memory_limit
1771 ) {
1772 return NULL;
1773 } else {
1774 ptr = realloc(ptr, nsize);
1775 if (ptr) moonbr_memory_usage += nsize - osize;
1777 } else {
1778 if (
1779 moonbr_memory_limit &&
1780 moonbr_memory_usage + nsize > moonbr_memory_limit
1781 ) {
1782 return NULL;
1783 } else {
1784 ptr = realloc(ptr, nsize);
1785 if (ptr) moonbr_memory_usage += nsize;
1788 return ptr;
1791 static int moonbr_lua_tonatural(lua_State *L, int idx) {
1792 int isnum;
1793 lua_Number n;
1794 n = lua_tonumberx(L, idx, &isnum);
1795 if (isnum && n>=0 && n<INT_MAX && (lua_Number)(int)n == n) return n;
1796 else return -1;
1799 static int moonbr_lua_totimeval(lua_State *L, int idx, struct timeval *value) {
1800 int isnum;
1801 lua_Number n;
1802 n = lua_tonumberx(L, idx, &isnum);
1803 if (isnum && n>=0 && n<=100000000) {
1804 value->tv_sec = n;
1805 value->tv_usec = 1e6 * (n - value->tv_sec);
1806 return 1;
1807 } else {
1808 return 0;
1812 static int moonbr_timeout(lua_State *L) {
1813 struct itimerval oldval;
1814 if (lua_isnoneornil(L, 1) && lua_isnoneornil(L, 2)) {
1815 getitimer(ITIMER_REAL, &oldval);
1816 } else {
1817 struct itimerval newval = {};
1818 timerclear(&newval.it_interval);
1819 timerclear(&newval.it_value);
1820 if (lua_toboolean(L, 1)) {
1821 luaL_argcheck(
1822 L, moonbr_lua_totimeval(L, 1, &newval.it_value), 1,
1823 "interval in seconds expected"
1824 );
1826 if (lua_isnoneornil(L, 2)) {
1827 if (setitimer(ITIMER_REAL, &newval, &oldval)) {
1828 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
1829 moonbr_terminate_error();
1831 } else {
1832 getitimer(ITIMER_REAL, &oldval);
1833 if (!timerisset(&oldval.it_value)) {
1834 if (setitimer(ITIMER_REAL, &newval, NULL)) {
1835 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
1836 moonbr_terminate_error();
1838 lua_call(L, lua_gettop(L) - 2, LUA_MULTRET);
1839 timerclear(&newval.it_value);
1840 if (setitimer(ITIMER_REAL, &newval, NULL)) {
1841 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
1842 moonbr_terminate_error();
1844 } else if (timercmp(&newval.it_value, &oldval.it_value, <)) {
1845 struct itimerval remval;
1846 if (setitimer(ITIMER_REAL, &newval, NULL)) {
1847 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
1848 moonbr_terminate_error();
1850 lua_call(L, lua_gettop(L) - 2, LUA_MULTRET);
1851 getitimer(ITIMER_REAL, &remval);
1852 timersub(&oldval.it_value, &newval.it_value, &newval.it_value);
1853 timeradd(&newval.it_value, &remval.it_value, &newval.it_value);
1854 if (setitimer(ITIMER_REAL, &newval, NULL)) {
1855 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
1856 moonbr_terminate_error();
1858 } else {
1859 lua_call(L, lua_gettop(L) - 2, LUA_MULTRET);
1861 return lua_gettop(L) - 1;
1864 lua_pushnumber(L, oldval.it_value.tv_sec + 1e-6 * oldval.it_value.tv_usec);
1865 return 1;
1868 #define moonbr_listen_init_pool_forkoption(luaname, cname, defval) { \
1869 lua_getfield(L, 2, luaname); \
1870 pool->cname = lua_isnil(L, -1) ? (defval) : moonbr_lua_tonatural(L, -1); \
1871 } while(0)
1873 #define moonbr_listen_init_pool_timeoption(luaname, cname, defval, defvalu) ( \
1874 lua_getfield(L, 2, luaname), \
1875 lua_isnil(L, -1) ? ( \
1876 pool->cname.tv_sec = (defval), pool->cname.tv_usec = (defvalu), \
1877 1 \
1878 ) : ( \
1879 (lua_isboolean(L, -1) && !lua_toboolean(L, -1)) ? ( \
1880 pool->cname.tv_sec = 0, pool->cname.tv_usec = 0, \
1881 1 \
1882 ) : ( \
1883 moonbr_lua_totimeval(L, -1, &pool->cname) \
1884 ) \
1885 ) \
1888 static int moonbr_listen_init_pool(lua_State *L) {
1889 struct moonbr_pool *pool;
1890 const char *proto;
1891 int i;
1892 int dynamic = 0; /* nonzero = listeners exist which require dynamic worker creation */
1893 pool = lua_touserdata(L, 1);
1894 for (i=0; i<pool->listener_count; i++) {
1895 struct moonbr_listener *listener = &pool->listener[i];
1896 lua_settop(L, 2);
1897 #if LUA_VERSION_NUM >= 503
1898 lua_geti(L, 2, i+1);
1899 #else
1900 lua_pushinteger(L, i+1);
1901 lua_gettable(L, 2);
1902 #endif
1903 lua_getfield(L, 3, "proto");
1904 proto = lua_tostring(L, -1);
1905 if (proto && !strcmp(proto, "main")) {
1906 listener->proto = MOONBR_PROTO_MAIN;
1907 } else if (proto && !strcmp(proto, "interval")) {
1908 dynamic = 1;
1909 listener->proto = MOONBR_PROTO_INTERVAL;
1910 lua_getfield(L, 3, "name");
1912 const char *name = lua_tostring(L, -1);
1913 if (name) {
1914 if (asprintf(&listener->type_specific.interval.name, "%s", name) < 0) {
1915 moonbr_log(LOG_CRIT, "Memory allocation_error");
1916 moonbr_terminate_error();
1920 lua_getfield(L, 3, "delay");
1921 if (
1922 !moonbr_lua_totimeval(L, -1, &listener->type_specific.interval.delay) ||
1923 !timerisset(&listener->type_specific.interval.delay)
1924 ) {
1925 luaL_error(L, "No valid interval delay specified; use listen{{proto=\"interval\", delay=...}, ...}");
1927 lua_getfield(L, 3, "strict");
1928 if (!lua_isnil(L, -1)) {
1929 if (lua_isboolean(L, -1)) {
1930 if (lua_toboolean(L, -1)) listener->type_specific.interval.strict = 1;
1931 } else {
1932 luaL_error(L, "Option \"strict\" must be a boolean if set; use listen{{proto=\"interval\", strict=true, ...}, ...}");
1935 } else if (proto && !strcmp(proto, "local")) {
1936 const char *path;
1937 const int path_maxlen = (
1938 sizeof(listener->type_specific.socket.addr.addr_un) -
1939 ((void *)listener->type_specific.socket.addr.addr_un.sun_path - (void *)&listener->type_specific.socket.addr.addr_un)
1940 ) - 1; /* one byte for termination */
1941 dynamic = 1;
1942 listener->proto = MOONBR_PROTO_LOCAL;
1943 lua_getfield(L, 3, "path");
1944 path = lua_tostring(L, -1);
1945 if (!path) {
1946 luaL_error(L, "No valid path specified for local socket; use listen{{proto=\"local\", path=...}, ...}");
1948 if (strlen(path) > path_maxlen) {
1949 luaL_error(L, "Path name for local socket exceeded maximum length of %i characters", path_maxlen);
1951 strcpy(listener->type_specific.socket.addr.addr_un.sun_path, path);
1952 } else if (proto && !strcmp(proto, "tcp")) {
1953 const char *host, *port;
1954 struct addrinfo hints = { 0, };
1955 struct addrinfo *res, *addrinfo;
1956 int errcode;
1957 const char *ip;
1958 dynamic = 1;
1959 lua_getfield(L, 3, "host");
1960 host = lua_isnil(L, -1) ? "::" : lua_tostring(L, -1);
1961 if (!host) {
1962 luaL_error(L, "No host specified; use listen{{proto=\"tcp\", host=...}, ...}");
1964 lua_getfield(L, 3, "port");
1965 port = lua_tostring(L, -1);
1966 if (!port) {
1967 luaL_error(L, "No port specified; use listen{{proto=\"tcp\", host=...}, ...}");
1969 hints.ai_family = AF_UNSPEC;
1970 hints.ai_socktype = SOCK_STREAM;
1971 hints.ai_protocol = IPPROTO_TCP;
1972 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1973 errcode = getaddrinfo(host, port, &hints, &res);
1974 if (errcode) {
1975 freeaddrinfo(res);
1976 if (errcode == EAI_SYSTEM) {
1977 char errmsg[MOONBR_MAXSTRERRORLEN];
1978 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
1979 luaL_error(L, "Could not resolve host: %s: %s", gai_strerror(errcode), errmsg);
1980 } else {
1981 luaL_error(L, "Could not resolve host: %s", gai_strerror(errcode));
1984 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1985 if (addrinfo->ai_family == AF_INET6) goto moonbr_listen_init_pool_found;
1987 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1988 if (addrinfo->ai_family == AF_INET) goto moonbr_listen_init_pool_found;
1990 addrinfo = res;
1991 moonbr_listen_init_pool_found:
1992 if (addrinfo->ai_addrlen > sizeof(listener->type_specific.socket.addr)) {
1993 moonbr_log(LOG_CRIT, "Size of ai_addrlen is unexpectedly big (should not happen)");
1994 moonbr_terminate_error();
1996 memcpy(&listener->type_specific.socket.addr, addrinfo->ai_addr, addrinfo->ai_addrlen);
1997 listener->type_specific.socket.addrlen = addrinfo->ai_addrlen;
1998 switch (addrinfo->ai_family) {
1999 case AF_INET6:
2000 ip = inet_ntop(
2001 addrinfo->ai_family,
2002 &((struct sockaddr_in6 *)addrinfo->ai_addr)->sin6_addr,
2003 listener->proto_specific.tcp.ip,
2004 INET6_ADDRSTRLEN
2005 );
2006 if (!ip) {
2007 moonbr_log(LOG_CRIT, "System error in inet_ntop call: %s", strerror(errno));
2008 moonbr_terminate_error();
2010 listener->proto_specific.tcp.port = ntohs(((struct sockaddr_in6 *)addrinfo->ai_addr)->sin6_port);
2011 break;
2012 case AF_INET:
2013 ip = inet_ntop(
2014 addrinfo->ai_family,
2015 &((struct sockaddr_in *)addrinfo->ai_addr)->sin_addr,
2016 listener->proto_specific.tcp.ip,
2017 INET6_ADDRSTRLEN
2018 );
2019 if (!ip) {
2020 moonbr_log(LOG_CRIT, "System error in inet_ntop call: %s", strerror(errno));
2021 moonbr_terminate_error();
2023 listener->proto_specific.tcp.port = ntohs(((struct sockaddr_in *)addrinfo->ai_addr)->sin_port);
2024 break;
2025 default:
2026 strcpy(listener->proto_specific.tcp.ip, "unknown");
2027 listener->proto_specific.tcp.port = 0;
2029 listener->proto = MOONBR_PROTO_TCP;
2030 } else if (proto) {
2031 luaL_error(L, "Unknown protocol \"%s\"", proto);
2032 } else {
2033 luaL_error(L, "No valid protocol specified; use listen{{proto=..., ...}, ...}");
2036 lua_settop(L, 2);
2037 if (dynamic) {
2038 moonbr_listen_init_pool_forkoption("pre_fork", pre_fork, 1);
2039 moonbr_listen_init_pool_forkoption("min_fork", min_fork, pool->pre_fork > 2 ? pool->pre_fork : 2);
2040 moonbr_listen_init_pool_forkoption("max_fork", max_fork, pool->min_fork > 16 ? pool->min_fork : 16);
2041 if (!moonbr_listen_init_pool_timeoption("fork_delay", fork_delay, 0, 250000)) {
2042 luaL_error(L, "Option \"fork_delay\" is expected to be a non-negative number");
2044 if (!moonbr_listen_init_pool_timeoption("fork_error_delay", fork_error_delay, 2, 0)) {
2045 luaL_error(L, "Option \"fork_error_delay\" is expected to be a non-negative number");
2047 if (!moonbr_listen_init_pool_timeoption("exit_delay", exit_delay, 60, 0)) {
2048 luaL_error(L, "Option \"exit_delay\" is expected to be a non-negative number");
2050 if (timercmp(&pool->fork_error_delay, &pool->fork_delay, <)) {
2051 pool->fork_error_delay = pool->fork_delay;
2053 if (!moonbr_listen_init_pool_timeoption("idle_timeout", idle_timeout, 0, 0)) {
2054 luaL_error(L, "Option \"idle_timeout\" is expected to be a non-negative number");
2056 } else {
2057 pool->pre_fork = 0;
2058 pool->min_fork = pool->listener_count;
2059 pool->max_fork = pool->listener_count;
2061 lua_getfield(L, 2, "memory_limit");
2062 if (!lua_isnil(L, -1)) {
2063 int isnum;
2064 lua_Number n;
2065 n = lua_tonumberx(L, -1, &isnum);
2066 if (n < 0 || !isnum) {
2067 luaL_error(L, "Option \"memory_limit\" is expected to be a non-negative number");
2069 pool->memory_limit = n;
2071 lua_settop(L, 2);
2072 lua_getfield(L, 2, "prepare");
2073 if (!lua_isnil(L, -1) && !lua_isfunction(L, -1)) {
2074 luaL_error(L, "Option \"prepare\" must be nil or a function");
2076 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_prepare_func(pool));
2077 lua_getfield(L, 2, "connect");
2078 if (!lua_isfunction(L, -1)) {
2079 luaL_error(L, "Option \"connect\" must be a function; use listen{{...}, {...}, connect=function(socket) ... end, ...}");
2081 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_connect_func(pool));
2082 lua_getfield(L, 2, "finish");
2083 if (!lua_isnil(L, -1) && !lua_isfunction(L, -1)) {
2084 luaL_error(L, "Option \"finish\" must be nil or a function");
2086 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_finish_func(pool));
2087 return 0;
2090 static int moonbr_listen(lua_State *L) {
2091 struct moonbr_pool *pool;
2092 lua_Integer listener_count;
2093 if (moonbr_booted) luaL_error(L, "Moonbridge bootup is already complete");
2094 luaL_checktype(L, 1, LUA_TTABLE);
2095 listener_count = luaL_len(L, 1);
2096 if (!listener_count) luaL_error(L, "No listen ports specified; use listen{{proto=..., port=...},...}");
2097 if (listener_count > 100) luaL_error(L, "Too many listeners");
2098 pool = moonbr_create_pool(listener_count);
2099 lua_pushcfunction(L, moonbr_listen_init_pool);
2100 lua_pushlightuserdata(L, pool);
2101 lua_pushvalue(L, 1);
2102 if (lua_pcall(L, 2, 0, 0)) goto moonbr_listen_error;
2104 int i;
2105 i = moonbr_start_pool(pool);
2106 if (i >= 0) {
2107 lua_pushfstring(L, "Could not initialize listener #%d: %s", i+1, strerror(errno));
2108 moonbr_listen_error:
2109 moonbr_destroy_pool(pool);
2110 lua_pushnil(L);
2111 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_prepare_func(pool));
2112 lua_pushnil(L);
2113 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_connect_func(pool));
2114 lua_pushnil(L);
2115 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_finish_func(pool));
2116 lua_error(L);
2119 return 0;
2123 /*** Function to modify Lua's library path and/or cpath ***/
2125 #if defined(MOONBR_LUA_PATH) || defined(MOONBR_LUA_CPATH)
2126 static void moonbr_modify_path(lua_State *L, char *key, char *value) {
2127 int stackbase;
2128 stackbase = lua_gettop(L);
2129 lua_getglobal(L, "package");
2130 lua_getfield(L, stackbase+1, key);
2132 const char *current_str;
2133 size_t current_strlen;
2134 luaL_Buffer buf;
2135 current_str = lua_tolstring(L, stackbase+2, &current_strlen);
2136 luaL_buffinit(L, &buf);
2137 if (current_str) {
2138 lua_pushvalue(L, stackbase+2);
2139 luaL_addvalue(&buf);
2140 if (current_strlen && current_str[current_strlen-1] != ';') {
2141 luaL_addchar(&buf, ';');
2144 luaL_addstring(&buf, value);
2145 luaL_pushresult(&buf);
2147 lua_setfield(L, stackbase+1, key);
2148 lua_settop(L, stackbase);
2150 #endif
2153 /*** Main function and command line invokation ***/
2155 static void moonbr_usage(int err, const char *cmd) {
2156 FILE *out;
2157 out = err ? stderr : stdout;
2158 if (!cmd) cmd = "moonbridge";
2159 fprintf(out, "Get this help message: %s {-h|--help}\n", cmd);
2160 fprintf(out, "Usage: %s \\\n", cmd);
2161 fprintf(out, " [-b|--background] \\\n");
2162 fprintf(out, " [-d|--debug] \\\n");
2163 fprintf(out, " [-f|--logfacility {DAEMON|USER|0|1|...|7}] \\\n");
2164 fprintf(out, " [-i|--logident <syslog ident> \\\n");
2165 fprintf(out, " [-l|--logfile <logfile>] \\\n");
2166 fprintf(out, " [-p|--pidfile <pidfile>] \\\n");
2167 fprintf(out, " [-s|--stats] \\\n");
2168 fprintf(out, " -- <Lua script> [<cmdline options for Lua script>]\n");
2169 exit(err);
2172 #define moonbr_usage_error() moonbr_usage(MOONBR_EXITCODE_CMDLINEERROR, argc ? argv[0] : NULL)
2174 int main(int argc, char **argv) {
2176 int daemonize = 0;
2177 int log_facility = LOG_USER;
2178 const char *log_ident = "moonbridge";
2179 const char *log_filename = NULL;
2180 const char *pid_filename = NULL;
2181 int option;
2182 struct option longopts[] = {
2183 { "background", no_argument, NULL, 'b' },
2184 { "debug", no_argument, NULL, 'd' },
2185 { "logfacility", required_argument, NULL, 'f' },
2186 { "help", no_argument, NULL, 'h' },
2187 { "logident", required_argument, NULL, 'i' },
2188 { "logfile", required_argument, NULL, 'l' },
2189 { "pidfile", required_argument, NULL, 'p' },
2190 { "stats", no_argument, NULL, 's' }
2191 };
2192 while ((option = getopt_long(argc, argv, "bdf:hi:l:p:s", longopts, NULL)) != -1) {
2193 switch (option) {
2194 case 'b':
2195 daemonize = 1;
2196 break;
2197 case 'd':
2198 moonbr_debug = 1;
2199 moonbr_stat = 1;
2200 break;
2201 case 'f':
2202 if (!strcmp(optarg, "DAEMON")) {
2203 log_facility = LOG_DAEMON;
2204 } else if (!strcmp(optarg, "USER")) {
2205 log_facility = LOG_USER;
2206 } else if (!strcmp(optarg, "0")) {
2207 log_facility = LOG_LOCAL0;
2208 } else if (!strcmp(optarg, "1")) {
2209 log_facility = LOG_LOCAL1;
2210 } else if (!strcmp(optarg, "2")) {
2211 log_facility = LOG_LOCAL2;
2212 } else if (!strcmp(optarg, "3")) {
2213 log_facility = LOG_LOCAL3;
2214 } else if (!strcmp(optarg, "4")) {
2215 log_facility = LOG_LOCAL4;
2216 } else if (!strcmp(optarg, "5")) {
2217 log_facility = LOG_LOCAL5;
2218 } else if (!strcmp(optarg, "6")) {
2219 log_facility = LOG_LOCAL6;
2220 } else if (!strcmp(optarg, "7")) {
2221 log_facility = LOG_LOCAL7;
2222 } else {
2223 moonbr_usage_error();
2225 moonbr_use_syslog = 1;
2226 break;
2227 case 'h':
2228 moonbr_usage(MOONBR_EXITCODE_GRACEFUL, argv[0]);
2229 break;
2230 case 'i':
2231 log_ident = optarg;
2232 moonbr_use_syslog = 1;
2233 break;
2234 case 'l':
2235 log_filename = optarg;
2236 break;
2237 case 'p':
2238 pid_filename = optarg;
2239 break;
2240 case 's':
2241 moonbr_stat = 1;
2242 break;
2243 default:
2244 moonbr_usage_error();
2247 if (argc - optind < 1) moonbr_usage_error();
2248 if (pid_filename) {
2249 pid_t otherpid;
2250 while ((moonbr_pidfh = pidfile_open(pid_filename, 0644, &otherpid)) == NULL) {
2251 if (errno == EEXIST) {
2252 if (otherpid == -1) {
2253 fprintf(stderr, "PID file \"%s\" is already locked\n", pid_filename);
2254 } else {
2255 fprintf(stderr, "PID file \"%s\" is already locked by process with PID: %i\n", pid_filename, (int)otherpid);
2257 exit(MOONBR_EXITCODE_ALREADYRUNNING);
2258 } else if (errno != EINTR) {
2259 fprintf(stderr, "Could not write PID file \"%s\": %s\n", pid_filename, strerror(errno));
2260 exit(MOONBR_EXITCODE_STARTUPERROR);
2264 if (log_filename) {
2265 int logfd;
2266 while (
2267 ( logfd = flopen(
2268 log_filename,
2269 O_WRONLY|O_NONBLOCK|O_CREAT|O_APPEND|O_CLOEXEC,
2270 0640
2272 ) < 0
2273 ) {
2274 if (errno == EWOULDBLOCK) {
2275 fprintf(stderr, "Logfile \"%s\" is locked\n", log_filename);
2276 exit(MOONBR_EXITCODE_ALREADYRUNNING);
2277 } else if (errno != EINTR) {
2278 fprintf(stderr, "Could not open logfile \"%s\": %s\n", log_filename, strerror(errno));
2279 exit(MOONBR_EXITCODE_STARTUPERROR);
2282 moonbr_logfile = fdopen(logfd, "a");
2283 if (!moonbr_logfile) {
2284 fprintf(stderr, "Could not open write stream to logfile \"%s\": %s\n", log_filename, strerror(errno));
2285 exit(MOONBR_EXITCODE_STARTUPERROR);
2288 if (daemonize == 0 && !moonbr_logfile) moonbr_logfile = stderr;
2289 if (moonbr_logfile) setlinebuf(moonbr_logfile);
2290 else moonbr_use_syslog = 1;
2291 if (moonbr_use_syslog) openlog(log_ident, LOG_NDELAY | LOG_PID, log_facility);
2292 if (daemonize) {
2293 if (daemon(1, 0)) {
2294 moonbr_log(LOG_ERR, "Could not daemonize moonbridge process");
2295 moonbr_terminate_error();
2299 moonbr_log(LOG_NOTICE, "Starting moonbridge server");
2300 if (moonbr_pidfh && pidfile_write(moonbr_pidfh)) {
2301 moonbr_log(LOG_ERR, "Could not write pidfile (after locking)");
2304 lua_State *L;
2305 L = lua_newstate(moonbr_alloc, NULL);
2306 if (!L) {
2307 moonbr_log(LOG_CRIT, "Could not initialize Lua state");
2308 moonbr_terminate_error();
2310 lua_atpanic(L, moonbr_lua_panic);
2311 lua_pushliteral(L, MOONBR_VERSION_STRING);
2312 lua_setglobal(L, "_MOONBRIDGE_VERSION");
2313 luaL_openlibs(L);
2314 luaL_requiref(L, "moonbridge_io", luaopen_moonbridge_io, 1);
2315 lua_pop(L, 1);
2316 #ifdef MOONBR_LUA_PATH
2317 moonbr_modify_path(L, "path", MOONBR_LUA_PATH);
2318 #endif
2319 #ifdef MOONBR_LUA_CPATH
2320 moonbr_modify_path(L, "cpath", MOONBR_LUA_CPATH);
2321 #endif
2322 lua_pushcfunction(L, moonbr_timeout);
2323 lua_setglobal(L, "timeout");
2324 lua_pushcfunction(L, moonbr_listen);
2325 lua_setglobal(L, "listen");
2326 lua_pushcfunction(L, moonbr_addtraceback); /* on stack position 1 */
2327 moonbr_log(LOG_INFO, "Loading \"%s\"", argv[optind]);
2328 if (luaL_loadfile(L, argv[optind])) {
2329 moonbr_log(LOG_ERR, "Error while loading \"%s\": %s", argv[optind], lua_tostring(L, -1));
2330 moonbr_terminate_error();
2332 { int i; for (i=optind+1; i<argc; i++) lua_pushstring(L, argv[i]); }
2333 if (lua_pcall(L, argc-(optind+1), 0, 1)) {
2334 moonbr_log(LOG_ERR, "Error while executing \"%s\": %s", argv[optind], lua_tostring(L, -1));
2335 moonbr_terminate_error();
2337 if (!moonbr_first_pool) {
2338 moonbr_log(LOG_WARNING, "No listener initialized.");
2339 moonbr_terminate_error();
2341 lua_getglobal(L, "listen");
2342 lua_pushcfunction(L, moonbr_listen);
2343 if (lua_compare(L, -2, -1, LUA_OPEQ)) {
2344 lua_pushnil(L);
2345 lua_setglobal(L, "listen");
2347 lua_settop(L, 1);
2348 lua_gc(L, LUA_GCCOLLECT, 0); // collect garbage before forking later
2349 moonbr_run(L);
2351 return 0;

Impressum / About Us