moonbridge

view moonbridge.c @ 267:5f437005e2ef

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

Impressum / About Us