moonbridge

view moonbridge.c @ 130:ee98e12427a9

Modified termination sequence handling
author jbe
date Wed Apr 15 00:54:17 2015 +0200 (2015-04-15)
parents ebaac38b7224
children 89fc89b22e28
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 <unistd.h>
25 #include <stdint.h>
26 #include <errno.h>
27 #include <getopt.h>
28 #include <syslog.h>
29 #include <string.h>
30 #include <stdio.h>
31 #include <time.h>
32 #include <sys/time.h>
33 #include <sys/socket.h>
34 #include <sys/un.h>
35 #include <netinet/in.h>
36 #include <netdb.h>
37 #include <arpa/inet.h>
38 #include <poll.h>
39 #include <signal.h>
40 #include <sys/wait.h>
41 #include <sys/resource.h>
42 #include <sys/file.h>
43 #if defined(__FreeBSD__) || __has_include(<libutil.h>)
44 #include <libutil.h>
45 #endif
46 #if defined(__linux__) || __has_include(<bsd/stdio.h>)
47 #include <bsd/stdio.h>
48 #endif
49 #if defined(__linux__) || __has_include(<bsd/libutil.h>)
50 #include <bsd/libutil.h>
51 #endif
52 #if defined(__linux__) || __has_include(<bsd/unistd.h>)
53 #include <bsd/unistd.h>
54 #endif
57 /*** Fallback definitions for missing constants on some platforms ***/
59 /* INFTIM is used as timeout parameter for poll() */
60 #ifndef INFTIM
61 #define INFTIM -1
62 #endif
65 /*** Include directives for Lua ***/
67 #include <lua.h>
68 #include <lauxlib.h>
69 #include <lualib.h>
72 /*** Include directive for moonbridge_io library ***/
74 #include "moonbridge_io.h"
77 /*** Constants ***/
79 /* Backlog option for listen() call */
80 #define MOONBR_LISTEN_BACKLOG 1024
82 /* Maximum length of a timestamp used for strftime() */
83 #define MOONBR_LOG_MAXTIMELEN 40
85 /* Maximum length of a log message */
86 #define MOONBR_LOG_MAXMSGLEN 4095
88 /* Exitcodes passed to exit() call */
89 #define MOONBR_EXITCODE_GRACEFUL 0
90 #define MOONBR_EXITCODE_CMDLINEERROR 1
91 #define MOONBR_EXITCODE_ALREADYRUNNING 2
92 #define MOONBR_EXITCODE_STARTUPERROR 3
93 #define MOONBR_EXITCODE_RUNTIMEERROR 4
95 /* Maximum length of a line sent to stderr by child processes */
96 #define MOONBR_MAXERRORLINELEN 1024
98 /* Maximum length of an error string returned by strerror() */
99 #define MOONBR_MAXSTRERRORLEN 80
101 /* Status bytes exchanged between master and child processes */
102 #define MOONBR_STATUS_IDLE 'I'
103 #define MOONBR_COMMAND_CONNECT 'C'
104 #define MOONBR_COMMAND_TERMINATE 'T'
105 #define MOONBR_STATUS_GOODBYE 'B'
107 /* Constant file descriptors */
108 #define MOONBR_FD_STDERR 2
109 #define MOONBR_FD_CONTROL 3
110 #define MOONBR_FD_END 4
112 /* Return values of moonbr_try_destroy_worker() */
113 #define MOONBR_DESTROY_NONE 0
114 #define MOONBR_DESTROY_PREPARE 1
115 #define MOONBR_DESTROY_IDLE_OR_ASSIGNED 2
118 /*** Types ***/
120 /* Enum for 'moonbr_pstate' */
121 #define MOONBR_PSTATE_STARTUP 0
122 #define MOONBR_PSTATE_RUNNING 1
123 #define MOONBR_PSTATE_FORKED 2
125 /* Enum for 'proto' field of struct moonbr_listener */
126 #define MOONBR_PROTO_MAIN 1
127 #define MOONBR_PROTO_INTERVAL 2
128 #define MOONBR_PROTO_LOCAL 3
129 #define MOONBR_PROTO_TCP 4
131 /* Data structure for a pool's listener that can accept incoming connections */
132 struct moonbr_listener {
133 struct moonbr_pool *pool;
134 struct moonbr_listener *prev_listener; /* previous idle or(!) connected listener */
135 struct moonbr_listener *next_listener; /* next idle or(!) connected listener */
136 int proto;
137 union {
138 struct {
139 char *name; /* name of interval passed to 'connect' function as 'interval' field in table */
140 int strict; /* nonzero = runtime of 'connect' function does not delay interval */
141 struct timeval delay; /* interval between invocations of 'connect' function */
142 struct timeval wakeup; /* point in time of next invocation */
143 } interval;
144 struct {
145 union {
146 struct sockaddr addr_abstract;
147 struct sockaddr_un addr_un;
148 struct sockaddr_in addr_in;
149 struct sockaddr_in6 addr_in6;
150 } addr;
151 socklen_t addrlen;
152 } socket;
153 } type_specific;
154 union {
155 struct {
156 char ip[INET6_ADDRSTRLEN]; /* IP to listen on */
157 int port; /* port number to listen on (in host endianess) */
158 } tcp;
159 } proto_specific;
160 int listenfd; /* -1 = none */
161 int pollidx; /* -1 = none */
162 };
164 /* Data structure for a child process that is handling incoming connections */
165 struct moonbr_worker {
166 struct moonbr_pool *pool;
167 struct moonbr_worker *prev_worker;
168 struct moonbr_worker *next_worker;
169 struct moonbr_worker *prev_idle_worker;
170 struct moonbr_worker *next_idle_worker;
171 int main; /* nonzero = terminate Moonbridge when this worker dies */
172 int idle; /* nonzero = waiting for command from parent process */
173 int assigned; /* nonzero = currently handling a connection */
174 pid_t pid;
175 int controlfd; /* socket to send/receive control message to/from child process */
176 int errorfd; /* socket to receive error output from child process' stderr */
177 char *errorlinebuf; /* optional buffer for collecting stderr data from child process */
178 int errorlinelen; /* number of bytes stored in 'errorlinebuf' */
179 int errorlineovf; /* nonzero = line length overflow */
180 struct timeval idle_expiration; /* point in time until child process may stay in idle state */
181 struct moonbr_listener *restart_interval_listener; /* set while interval listener is assigned */
182 };
184 /* Data structure for a pool of workers and listeners */
185 struct moonbr_pool {
186 int poolnum; /* number of pool for log output */
187 struct moonbr_pool *next_pool; /* next entry in linked list starting with 'moonbr_first_pool' */
188 struct moonbr_worker *first_worker; /* first worker of pool */
189 struct moonbr_worker *last_worker; /* last worker of pool */
190 struct moonbr_worker *first_idle_worker; /* first idle worker of pool */
191 struct moonbr_worker *last_idle_worker; /* last idle worker of pool */
192 int idle_worker_count;
193 int unassigned_worker_count;
194 int total_worker_count;
195 int worker_count_stat; /* only needed for statistics */
196 int pre_fork; /* desired minimum number of unassigned workers */
197 int min_fork; /* desired minimum number of workers in total */
198 int max_fork; /* maximum number of workers */
199 struct timeval fork_delay; /* delay after each fork() until a fork may happen again */
200 struct timeval fork_wakeup; /* point in time when a fork may happen again (unless a worker terminates before) */
201 struct timeval fork_error_delay; /* delay between fork()s when an error during fork or preparation occurred */
202 struct timeval fork_error_wakeup; /* point in time when fork may happen again if an error in preparation occurred */
203 int use_fork_error_wakeup; /* nonzero = error in preparation occured; gets reset on next fork */
204 struct timeval exit_delay; /* delay for terminating excessive workers (unassigned_worker_count > pre_fork) */
205 struct timeval exit_wakeup; /* point in time when terminating an excessive worker */
206 struct timeval idle_timeout; /* delay before an idle worker is terminated */
207 size_t memory_limit; /* maximum bytes of memory that the Lua machine may allocate */
208 int listener_count; /* total number of listeners of pool (and size of 'listener' array at end of this struct) */
209 struct moonbr_listener *first_idle_listener; /* first listener that is idle (i.e. has no waiting connection) */
210 struct moonbr_listener *last_idle_listener; /* last listener that is idle (i.e. has no waiting connection) */
211 struct moonbr_listener *first_connected_listener; /* first listener that has a pending connection */
212 struct moonbr_listener *last_connected_listener; /* last listener that has a pending connection */
213 struct moonbr_listener listener[1]; /* static array of variable(!) size to contain 'listener' structures */
214 };
216 /* Enum for 'channel' field of struct moonbr_poll_worker */
217 #define MOONBR_POLL_WORKER_CONTROLCHANNEL 1
218 #define MOONBR_POLL_WORKER_ERRORCHANNEL 2
220 /* Structure to refer from 'moonbr_poll_worker_fds' entry to worker structure */
221 struct moonbr_poll_worker {
222 struct moonbr_worker *worker;
223 int channel; /* field indicating whether file descriptor is 'controlfd' or 'errorfd' */
224 };
226 /* Variable indicating that clean shutdown was requested */
227 static int moonbr_shutdown_in_progress = 0;
230 /*** Macros for Lua registry ***/
232 /* Lightuserdata keys for Lua registry to store 'prepare', 'connect', and 'finish' functions */
233 #define moonbr_luakey_prepare_func(pool) ((void *)(intptr_t)(pool) + 0)
234 #define moonbr_luakey_connect_func(pool) ((void *)(intptr_t)(pool) + 1)
235 #define moonbr_luakey_finish_func(pool) ((void *)(intptr_t)(pool) + 2)
238 /*** Global variables ***/
240 /* State of process execution */
241 static int moonbr_pstate = MOONBR_PSTATE_STARTUP;
243 /* Process ID of the main process */
244 static pid_t moonbr_masterpid;
246 /* Condition variables set by the signal handler */
247 static volatile sig_atomic_t moonbr_cond_poll = 0;
248 static volatile sig_atomic_t moonbr_cond_terminate = 0;
249 static volatile sig_atomic_t moonbr_cond_interrupt = 0;
250 static volatile sig_atomic_t moonbr_cond_child = 0;
252 /* Socket pair to denote signal delivery when signal handler was called just before poll() */
253 static int moonbr_poll_signalfds[2];
254 #define moonbr_poll_signalfd_read moonbr_poll_signalfds[0]
255 #define moonbr_poll_signalfd_write moonbr_poll_signalfds[1]
257 /* Global variables for pidfile and logging */
258 static struct pidfh *moonbr_pidfh = NULL;
259 static FILE *moonbr_logfile = NULL;
260 static int moonbr_use_syslog = 0;
262 /* First and last entry of linked list of all created pools during initialization */
263 static struct moonbr_pool *moonbr_first_pool = NULL;
264 static struct moonbr_pool *moonbr_last_pool = NULL;
266 /* Total count of pools */
267 static int moonbr_pool_count = 0;
269 /* Set to a nonzero value if dynamic part of 'moonbr_poll_fds' ('moonbr_poll_worker_fds') needs an update */
270 static int moonbr_poll_refresh_needed = 0;
272 /* Array passed to poll(), consisting of static part and dynamic part ('moonbr_poll_worker_fds') */
273 static struct pollfd *moonbr_poll_fds = NULL; /* the array */
274 static int moonbr_poll_fds_bufsize = 0; /* memory allocated for this number of elements */
275 static int moonbr_poll_fds_count = 0; /* total number of elements */
276 static int moonbr_poll_fds_static_count; /* number of elements in static part */
278 /* Dynamic part of 'moonbr_poll_fds' array */
279 #define moonbr_poll_worker_fds (moonbr_poll_fds+moonbr_poll_fds_static_count)
281 /* Additional information for dynamic part of 'moonbr_poll_fds' array */
282 struct moonbr_poll_worker *moonbr_poll_workers; /* the array */
283 static int moonbr_poll_workers_bufsize = 0; /* memory allocated for this number of elements */
284 static int moonbr_poll_worker_count = 0; /* number of elements in array */
286 /* Variable set to nonzero value to disallow further calls of 'listen' function */
287 static int moonbr_booted = 0;
289 /* Verbosity settings */
290 static int moonbr_debug = 0;
291 static int moonbr_stat = 0;
293 /* Memory consumption by Lua machine */
294 static size_t moonbr_memory_usage = 0;
295 static size_t moonbr_memory_limit = 0;
298 /*** Functions for signal handling ***/
300 /* Signal handler for master and child processes */
301 static void moonbr_signal(int sig) {
302 if (getpid() == moonbr_masterpid) {
303 /* master process */
304 switch (sig) {
305 case SIGHUP:
306 case SIGINT:
307 /* fast shutdown requested */
308 moonbr_cond_interrupt = 1;
309 break;
310 case SIGTERM:
311 /* clean shutdown requested */
312 moonbr_cond_terminate = 1;
313 break;
314 case SIGCHLD:
315 /* child process terminated */
316 moonbr_cond_child = 1;
317 break;
318 }
319 if (moonbr_cond_poll) {
320 /* avoid race condition if signal handler is invoked right before poll() */
321 char buf[1] = {0};
322 write(moonbr_poll_signalfd_write, buf, 1);
323 }
324 } else {
325 /* child process forwards certain signals to parent process */
326 switch (sig) {
327 case SIGHUP:
328 case SIGINT:
329 case SIGTERM:
330 kill(moonbr_masterpid, sig);
331 }
332 }
333 }
335 /* Initialize signal handling */
336 static void moonbr_signal_init(){
337 moonbr_masterpid = getpid();
338 signal(SIGHUP, moonbr_signal);
339 signal(SIGINT, moonbr_signal);
340 signal(SIGTERM, moonbr_signal);
341 signal(SIGCHLD, 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);
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 lua_pushstring(L,
798 listener->type_specific.interval.name ?
799 listener->type_specific.interval.name : ""
800 );
801 lua_setfield(L, -2, "interval");
802 } else {
803 lua_pushvalue(L, -2);
804 }
805 if (lua_pcall(L, 1, 1, 1)) {
806 fprintf(stderr, "Error in \"connect\" function: %s\n", lua_tostring(L, -1));
807 exit(1);
808 }
809 if (fd >= 0) moonbr_io_closehandle(L, -2, 0); /* attemt clean close */
810 if (lua_type(L, -1) != LUA_TBOOLEAN || !lua_toboolean(L, -1)) break;
811 #ifdef MOONBR_LUA_PANIC_BUG_WORKAROUND
812 lua_settop(L, 2);
813 #else
814 lua_settop(L, 1);
815 #endif
816 }
817 controlmsg = MOONBR_STATUS_GOODBYE;
818 if (write(MOONBR_FD_CONTROL, &controlmsg, 1) <= 0) {
819 moonbr_child_log_errno_fatal("Error while sending goodbye message to parent process");
820 }
821 if (close(MOONBR_FD_CONTROL) && errno != EINTR) {
822 moonbr_child_log_errno("Error while closing control socket");
823 }
824 lua_rawgetp(L, LUA_REGISTRYINDEX, moonbr_luakey_finish_func(pool));
825 if (lua_isnil(L, -1)) lua_pop(L, 1);
826 else if (lua_pcall(L, 0, 0, 1)) {
827 fprintf(stderr, "Error in \"finish\" function: %s\n", lua_tostring(L, -1));
828 exit(1);
829 }
830 lua_close(L);
831 exit(0);
832 }
835 /*** Functions to spawn child process ***/
837 /* Helper function to send an error message to a file descriptor (not needing a file stream) */
838 static void moonbr_child_emergency_print(int fd, char *message) {
839 size_t len = strlen(message);
840 ssize_t written;
841 while (len) {
842 written = write(fd, message, len);
843 if (written > 0) {
844 message += written;
845 len -= written;
846 } else {
847 if (written != -1 || errno != EINTR) break;
848 }
849 }
850 }
852 /* Helper function to send an error message plus a text for errno to a file descriptor and terminate the process */
853 static void moonbr_child_emergency_error(int fd, char *message) {
854 int errno2 = errno;
855 moonbr_child_emergency_print(fd, message);
856 moonbr_child_emergency_print(fd, ": ");
857 moonbr_child_emergency_print(fd, strerror(errno2));
858 moonbr_child_emergency_print(fd, "\n");
859 exit(1);
860 }
862 /* Creates a child process and (in case of success) registers it in the 'struct moonbr_pool' structure */
863 static int moonbr_create_worker(struct moonbr_pool *pool, lua_State *L) {
864 struct moonbr_worker *worker;
865 worker = calloc(1, sizeof(struct moonbr_worker));
866 if (!worker) {
867 moonbr_log(LOG_CRIT, "Memory allocation error");
868 return -1;
869 }
870 worker->pool = pool;
871 {
872 int controlfds[2];
873 int errorfds[2];
874 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, controlfds)) {
875 moonbr_log(LOG_ERR, "Could not create control socket pair for communcation with child process: %s", strerror(errno));
876 free(worker);
877 return -1;
878 }
879 if (socketpair(PF_LOCAL, SOCK_STREAM | SOCK_CLOEXEC, 0, errorfds)) {
880 moonbr_log(LOG_ERR, "Could not create socket pair to redirect stderr of child process: %s", strerror(errno));
881 close(controlfds[0]);
882 close(controlfds[1]);
883 free(worker);
884 return -1;
885 }
886 if (moonbr_logfile && fflush(moonbr_logfile)) {
887 moonbr_log(LOG_CRIT, "Could not flush log file prior to forking: %s", strerror(errno));
888 moonbr_terminate_error();
889 }
890 worker->pid = fork();
891 if (worker->pid == -1) {
892 moonbr_log(LOG_ERR, "Could not fork: %s", strerror(errno));
893 close(controlfds[0]);
894 close(controlfds[1]);
895 close(errorfds[0]);
896 close(errorfds[1]);
897 free(worker);
898 return -1;
899 } else if (!worker->pid) {
900 moonbr_pstate = MOONBR_PSTATE_FORKED;
901 #ifdef MOONBR_LUA_PANIC_BUG_WORKAROUND
902 lua_pushliteral(L, "Failed to pass error message due to bug in Lua panic handler (hint: not enough memory?)");
903 #endif
904 moonbr_memory_limit = pool->memory_limit;
905 if (moonbr_pidfh && pidfile_close(moonbr_pidfh)) {
906 moonbr_child_emergency_error(errorfds[1], "Could not close PID file in forked child process");
907 }
908 if (moonbr_logfile && moonbr_logfile != stderr && fclose(moonbr_logfile)) {
909 moonbr_child_emergency_error(errorfds[1], "Could not close log file in forked child process");
910 }
911 if (dup2(errorfds[1], MOONBR_FD_STDERR) == -1) {
912 moonbr_child_emergency_error(errorfds[1], "Could not duplicate socket to stderr file descriptor");
913 }
914 if (dup2(controlfds[1], MOONBR_FD_CONTROL) == -1) {
915 moonbr_child_emergency_error(errorfds[1], "Could not duplicate control socket");
916 }
917 closefrom(MOONBR_FD_END);
918 moonbr_child_run(pool, L);
919 }
920 if (moonbr_stat) {
921 moonbr_log(LOG_INFO, "Created new worker in pool #%i with PID %i", worker->pool->poolnum, (int)worker->pid);
922 }
923 worker->controlfd = controlfds[0];
924 worker->errorfd = errorfds[0];
925 if (close(controlfds[1]) && errno != EINTR) {
926 moonbr_log(LOG_CRIT, "Could not close opposite end of control file descriptor after forking");
927 moonbr_terminate_error();
928 }
929 if (close(errorfds[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 }
934 worker->prev_worker = pool->last_worker;
935 if (worker->prev_worker) worker->prev_worker->next_worker = worker;
936 else pool->first_worker = worker;
937 pool->last_worker = worker;
938 pool->unassigned_worker_count++;
939 pool->total_worker_count++;
940 pool->worker_count_stat = 1;
941 moonbr_poll_refresh_needed = 1;
942 return 0; /* return zero only in case of success */
943 }
946 /*** Functions for queues of 'struct moonbr_listener' ***/
948 /* Appends a 'struct moonbr_listener' to the queue of idle listeners and registers it for poll() */
949 static void moonbr_add_idle_listener(struct moonbr_listener *listener) {
950 listener->prev_listener = listener->pool->last_idle_listener;
951 if (listener->prev_listener) listener->prev_listener->next_listener = listener;
952 else listener->pool->first_idle_listener = listener;
953 listener->pool->last_idle_listener = listener;
954 if (listener->pollidx != -1) moonbr_poll_fds[listener->pollidx].events |= POLLIN;
955 }
957 /* Removes a 'struct moonbr_listener' from the queue of idle listeners and unregisters it from poll() */
958 static void moonbr_remove_idle_listener(struct moonbr_listener *listener) {
959 if (listener->prev_listener) listener->prev_listener->next_listener = listener->next_listener;
960 else listener->pool->first_idle_listener = listener->next_listener;
961 if (listener->next_listener) listener->next_listener->prev_listener = listener->prev_listener;
962 else listener->pool->last_idle_listener = listener->prev_listener;
963 listener->prev_listener = NULL;
964 listener->next_listener = NULL;
965 if (listener->pollidx != -1) moonbr_poll_fds[listener->pollidx].events &= ~POLLIN;
966 }
968 /* Adds a listener to the queue of connected listeners (i.e. waiting to have their incoming connection accepted) */
969 static void moonbr_add_connected_listener(struct moonbr_listener *listener) {
970 listener->prev_listener = listener->pool->last_connected_listener;
971 if (listener->prev_listener) listener->prev_listener->next_listener = listener;
972 else listener->pool->first_connected_listener = listener;
973 listener->pool->last_connected_listener = listener;
974 }
976 /* Removes and returns the first connected listener in the queue */
977 static struct moonbr_listener *moonbr_pop_connected_listener(struct moonbr_pool *pool) {
978 struct moonbr_listener *listener = pool->first_connected_listener;
979 listener->pool->first_connected_listener = listener->next_listener;
980 if (listener->pool->first_connected_listener) listener->pool->first_connected_listener->prev_listener = NULL;
981 else listener->pool->last_connected_listener = NULL;
982 listener->next_listener = NULL;
983 return listener;
984 }
987 /*** Functions to handle polling ***/
989 /* Returns an index to a new initialized entry in moonbr_poll_fds[] */
990 int moonbr_poll_fds_nextindex() {
991 if (moonbr_poll_fds_count >= moonbr_poll_fds_bufsize) {
992 if (moonbr_poll_fds_bufsize) moonbr_poll_fds_bufsize *= 2;
993 else moonbr_poll_fds_bufsize = 1;
994 moonbr_poll_fds = realloc(
995 moonbr_poll_fds, moonbr_poll_fds_bufsize * sizeof(struct pollfd)
996 );
997 if (!moonbr_poll_fds) {
998 moonbr_log(LOG_CRIT, "Memory allocation error");
999 moonbr_terminate_error();
1002 moonbr_poll_fds[moonbr_poll_fds_count] = (struct pollfd){0, };
1003 return moonbr_poll_fds_count++;
1006 /* Returns an index to a new initialized entry in moonbr_poll_workers[] */
1007 int moonbr_poll_workers_nextindex() {
1008 if (moonbr_poll_worker_count >= moonbr_poll_workers_bufsize) {
1009 if (moonbr_poll_workers_bufsize) moonbr_poll_workers_bufsize *= 2;
1010 else moonbr_poll_workers_bufsize = 1;
1011 moonbr_poll_workers = realloc(
1012 moonbr_poll_workers, moonbr_poll_workers_bufsize * sizeof(struct moonbr_poll_worker)
1013 );
1014 if (!moonbr_poll_workers) {
1015 moonbr_log(LOG_CRIT, "Memory allocation error");
1016 moonbr_terminate_error();
1019 moonbr_poll_workers[moonbr_poll_worker_count] = (struct moonbr_poll_worker){0, };
1020 return moonbr_poll_worker_count++;
1023 /* Queues all listeners as idle, and initializes static part of moonbr_poll_fds[], which is passed to poll() */
1024 static void moonbr_poll_init() {
1025 if (socketpair(
1026 PF_LOCAL,
1027 SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
1028 0,
1029 moonbr_poll_signalfds
1030 )) {
1031 moonbr_log(LOG_CRIT, "Could not create socket pair for signal delivery during polling: %s", strerror(errno));
1032 moonbr_terminate_error();
1035 int j = moonbr_poll_fds_nextindex();
1036 struct pollfd *pollfd = &moonbr_poll_fds[j];
1037 pollfd->fd = moonbr_poll_signalfd_read;
1038 pollfd->events = POLLIN;
1041 struct moonbr_pool *pool;
1042 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1043 int i;
1044 for (i=0; i<pool->listener_count; i++) {
1045 struct moonbr_listener *listener = &pool->listener[i];
1046 if (listener->listenfd != -1) {
1047 int j = moonbr_poll_fds_nextindex();
1048 listener->pollidx = j;
1049 moonbr_poll_fds[j].fd = listener->listenfd;
1051 moonbr_add_idle_listener(listener);
1055 moonbr_poll_fds_static_count = moonbr_poll_fds_count; /* remember size of static part of array */
1058 /* Disables polling of all listeners (required for clean shutdown) */
1059 static void moonbr_poll_shutdown() {
1060 int i;
1061 for (i=1; i<moonbr_poll_fds_static_count; i++) {
1062 moonbr_poll_fds[i].fd = -1;
1066 /* (Re)builds dynamic part of moonbr_poll_fds[] array, and (re)builds moonbr_poll_workers[] array */
1067 static void moonbr_poll_refresh() {
1068 moonbr_poll_refresh_needed = 0;
1069 moonbr_poll_fds_count = moonbr_poll_fds_static_count;
1070 moonbr_poll_worker_count = 0;
1072 struct moonbr_pool *pool;
1073 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1074 struct moonbr_worker *worker;
1075 for (worker=pool->first_worker; worker; worker=worker->next_worker) {
1076 if (worker->controlfd != -1) {
1077 int j = moonbr_poll_fds_nextindex();
1078 int k = moonbr_poll_workers_nextindex();
1079 struct pollfd *pollfd = &moonbr_poll_fds[j];
1080 struct moonbr_poll_worker *poll_worker = &moonbr_poll_workers[k];
1081 pollfd->fd = worker->controlfd;
1082 pollfd->events = POLLIN;
1083 poll_worker->channel = MOONBR_POLL_WORKER_CONTROLCHANNEL;
1084 poll_worker->worker = worker;
1086 if (worker->errorfd != -1) {
1087 int j = moonbr_poll_fds_nextindex();
1088 int k = moonbr_poll_workers_nextindex();
1089 struct pollfd *pollfd = &moonbr_poll_fds[j];
1090 struct moonbr_poll_worker *poll_worker = &moonbr_poll_workers[k];
1091 pollfd->fd = worker->errorfd;
1092 pollfd->events = POLLIN;
1093 poll_worker->channel = MOONBR_POLL_WORKER_ERRORCHANNEL;
1094 poll_worker->worker = worker;
1101 /* resets socket and 'revents' field of moonbr_poll_fds[] for signal delivery just before poll() is called */
1102 static void moonbr_poll_reset_signal() {
1103 ssize_t readcount;
1104 char buf[1];
1105 moonbr_poll_fds[0].revents = 0;
1106 while ((readcount = read(moonbr_poll_signalfd_read, buf, 1)) < 0) {
1107 if (errno == EAGAIN) break;
1108 if (errno != EINTR) {
1109 moonbr_log(LOG_CRIT, "Error while reading from signal delivery socket: %s", strerror(errno));
1110 moonbr_terminate_error();
1113 if (!readcount) {
1114 moonbr_log(LOG_CRIT, "Unexpected EOF when reading from signal delivery socket: %s", strerror(errno));
1115 moonbr_terminate_error();
1120 /*** Shutdown initiation ***/
1122 /* Sets global variable 'moonbr_shutdown_in_progress', closes listeners, and demands worker termination */
1123 static void moonbr_initiate_shutdown() {
1124 struct moonbr_pool *pool;
1125 int i;
1126 if (moonbr_shutdown_in_progress) {
1127 moonbr_log(LOG_NOTICE, "Shutdown already in progress");
1128 return;
1130 moonbr_shutdown_in_progress = 1;
1131 moonbr_log(LOG_NOTICE, "Initiate shutdown");
1132 for (pool = moonbr_first_pool; pool; pool = pool->next_pool) {
1133 for (i=0; i<pool->listener_count; i++) {
1134 struct moonbr_listener *listener = &pool->listener[i];
1135 if (listener->listenfd != -1) {
1136 if (close(listener->listenfd) && errno != EINTR) {
1137 moonbr_log(LOG_CRIT, "Could not close listening socket: %s", strerror(errno));
1138 moonbr_terminate_error();
1143 moonbr_poll_shutdown(); /* avoids loops due to error condition when polling closed listeners */
1147 /*** Functions to handle previously created 'struct moonbr_worker' structures ***/
1149 #define moonbr_try_destroy_worker_stat(str, field) \
1150 moonbr_log(LOG_INFO, "Resource usage in pool #%i for PID %i: " str " %li", worker->pool->poolnum, (int)worker->pid, (long)childusage.field);
1152 /* Destroys a worker structure if socket connections have been closed and child process has terminated */
1153 static int moonbr_try_destroy_worker(struct moonbr_worker *worker) {
1154 if (worker->controlfd != -1 || worker->errorfd != -1) return MOONBR_DESTROY_NONE;
1156 int childstatus;
1157 struct rusage childusage;
1159 pid_t waitedpid;
1160 while (
1161 (waitedpid = wait4(worker->pid, &childstatus, WNOHANG, &childusage)) == -1
1162 ) {
1163 if (errno != EINTR) {
1164 moonbr_log(LOG_CRIT, "Error in wait4() call: %s", strerror(errno));
1165 moonbr_terminate_error();
1168 if (!waitedpid) return 0; /* return 0 if worker couldn't be destroyed */
1169 if (waitedpid != worker->pid) {
1170 moonbr_log(LOG_CRIT, "Wrong PID returned by wait4() call");
1171 moonbr_terminate_error();
1174 if (WIFEXITED(childstatus)) {
1175 if (WEXITSTATUS(childstatus) || moonbr_stat) {
1176 moonbr_log(
1177 WEXITSTATUS(childstatus) ? LOG_WARNING : LOG_INFO,
1178 "Child process in pool #%i with PID %i returned with exit code %i", worker->pool->poolnum, (int)worker->pid, WEXITSTATUS(childstatus)
1179 );
1181 } else if (WIFSIGNALED(childstatus)) {
1182 if (WCOREDUMP(childstatus)) {
1183 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));
1184 } else if (WTERMSIG(childstatus) == SIGALRM) {
1185 moonbr_log(LOG_WARNING, "Child process in pool #%i with PID %i exited prematurely due to timeout", worker->pool->poolnum, (int)worker->pid);
1186 } else {
1187 moonbr_log(LOG_ERR, "Child process in pool #%i with PID %i died from signal %i", worker->pool->poolnum, (int)worker->pid, WTERMSIG(childstatus));
1189 } else {
1190 moonbr_log(LOG_CRIT, "Illegal exit status from child process in pool #%i with PID %i", worker->pool->poolnum, (int)worker->pid);
1191 moonbr_terminate_error();
1193 if (moonbr_stat) {
1194 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));
1195 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));
1196 moonbr_try_destroy_worker_stat("max resident set size", ru_maxrss);
1197 moonbr_try_destroy_worker_stat("integral shared memory size", ru_ixrss);
1198 moonbr_try_destroy_worker_stat("integral unshared data", ru_idrss);
1199 moonbr_try_destroy_worker_stat("integral unshared stack", ru_isrss);
1200 moonbr_try_destroy_worker_stat("page replaims", ru_minflt);
1201 moonbr_try_destroy_worker_stat("page faults", ru_majflt);
1202 moonbr_try_destroy_worker_stat("swaps", ru_nswap);
1203 moonbr_try_destroy_worker_stat("block input operations", ru_inblock);
1204 moonbr_try_destroy_worker_stat("block output operations", ru_oublock);
1205 moonbr_try_destroy_worker_stat("messages sent", ru_msgsnd);
1206 moonbr_try_destroy_worker_stat("messages received", ru_msgrcv);
1207 moonbr_try_destroy_worker_stat("signals received", ru_nsignals);
1208 moonbr_try_destroy_worker_stat("voluntary context switches", ru_nvcsw);
1209 moonbr_try_destroy_worker_stat("involuntary context switches", ru_nivcsw);
1213 int retval = (
1214 (worker->idle || worker->assigned) ?
1215 MOONBR_DESTROY_IDLE_OR_ASSIGNED :
1216 MOONBR_DESTROY_PREPARE
1217 );
1218 if (worker->main) moonbr_initiate_shutdown();
1219 if (worker->prev_worker) worker->prev_worker->next_worker = worker->next_worker;
1220 else worker->pool->first_worker = worker->next_worker;
1221 if (worker->next_worker) worker->next_worker->prev_worker = worker->prev_worker;
1222 else worker->pool->last_worker = worker->prev_worker;
1223 if (worker->idle) {
1224 if (worker->prev_idle_worker) worker->prev_idle_worker->next_idle_worker = worker->next_idle_worker;
1225 else worker->pool->first_idle_worker = worker->next_idle_worker;
1226 if (worker->next_idle_worker) worker->next_idle_worker->prev_idle_worker = worker->prev_idle_worker;
1227 else worker->pool->last_idle_worker = worker->prev_idle_worker;
1228 worker->pool->idle_worker_count--;
1230 if (!worker->assigned) worker->pool->unassigned_worker_count--;
1231 worker->pool->total_worker_count--;
1232 worker->pool->worker_count_stat = 1;
1233 if (worker->errorlinebuf) free(worker->errorlinebuf);
1234 free(worker);
1235 return retval;
1239 /* Marks a worker as idle and stores it in a queue, optionally setting 'idle_expiration' value */
1240 static void moonbr_add_idle_worker(struct moonbr_worker *worker) {
1241 worker->prev_idle_worker = worker->pool->last_idle_worker;
1242 if (worker->prev_idle_worker) worker->prev_idle_worker->next_idle_worker = worker;
1243 else worker->pool->first_idle_worker = worker;
1244 worker->pool->last_idle_worker = worker;
1245 worker->idle = 1;
1246 worker->pool->idle_worker_count++;
1247 if (worker->assigned) {
1248 worker->assigned = 0;
1249 worker->pool->unassigned_worker_count++;
1251 worker->pool->worker_count_stat = 1;
1252 if (timerisset(&worker->pool->idle_timeout)) {
1253 struct timeval now;
1254 moonbr_now(&now);
1255 timeradd(&now, &worker->pool->idle_timeout, &worker->idle_expiration);
1259 /* Pops a worker from the queue of idle workers (idle queue must not be empty) */
1260 static struct moonbr_worker *moonbr_pop_idle_worker(struct moonbr_pool *pool) {
1261 struct moonbr_worker *worker;
1262 worker = pool->first_idle_worker;
1263 pool->first_idle_worker = worker->next_idle_worker;
1264 if (pool->first_idle_worker) pool->first_idle_worker->prev_idle_worker = NULL;
1265 else pool->last_idle_worker = NULL;
1266 worker->next_idle_worker = NULL;
1267 worker->idle = 0;
1268 worker->pool->idle_worker_count--;
1269 worker->assigned = 1;
1270 worker->pool->unassigned_worker_count--;
1271 worker->pool->worker_count_stat = 1;
1272 return worker;
1276 /*** Functions to communicate with child processes ***/
1278 /* Tells child process to terminate */
1279 static void moonbr_terminate_idle_worker(struct moonbr_worker *worker) {
1280 moonbr_send_control_message(worker, MOONBR_COMMAND_TERMINATE, -1, NULL);
1283 /* Handles status messages from child process */
1284 static void moonbr_read_controlchannel(struct moonbr_worker *worker) {
1285 char controlmsg;
1287 ssize_t bytes_read;
1288 while ((bytes_read = read(worker->controlfd, &controlmsg, 1)) <= 0) {
1289 if (bytes_read == 0 || errno == ECONNRESET) {
1290 moonbr_log(LOG_WARNING, "Child process in pool #%i with PID %i unexpectedly closed control socket", worker->pool->poolnum, (int)worker->pid);
1291 if (close(worker->controlfd) && errno != EINTR) {
1292 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));
1293 moonbr_terminate_error();
1295 worker->controlfd = -1;
1296 moonbr_poll_refresh_needed = 1;
1297 return;
1299 if (errno != EINTR) {
1300 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));
1301 moonbr_terminate_error();
1305 if (worker->idle) {
1306 moonbr_log(LOG_CRIT, "Unexpected data from supposedly idle child process in pool #%i with PID %i", worker->pool->poolnum, (int)worker->pid);
1307 moonbr_terminate_error();
1309 if (moonbr_debug) {
1310 moonbr_log(LOG_DEBUG, "Received control message from child in pool #%i with PID %i: \"%c\"", worker->pool->poolnum, (int)worker->pid, (int)controlmsg);
1312 switch (controlmsg) {
1313 case MOONBR_STATUS_IDLE:
1314 if (moonbr_stat) {
1315 moonbr_log(LOG_INFO, "Child process in pool #%i with PID %i reports as idle", worker->pool->poolnum, (int)worker->pid);
1317 moonbr_add_idle_worker(worker);
1318 break;
1319 case MOONBR_STATUS_GOODBYE:
1320 if (moonbr_stat) {
1321 moonbr_log(LOG_INFO, "Child process in pool #%i with PID %i announced termination", worker->pool->poolnum, (int)worker->pid);
1323 if (close(worker->controlfd) && errno != EINTR) {
1324 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));
1325 moonbr_terminate_error();
1327 worker->controlfd = -1;
1328 moonbr_poll_refresh_needed = 1;
1329 break;
1330 default:
1331 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);
1332 moonbr_terminate_error();
1336 /* Handles stderr stream from child process */
1337 static void moonbr_read_errorchannel(struct moonbr_worker *worker) {
1338 char staticbuf[MOONBR_MAXERRORLINELEN+1];
1339 char *buf = worker->errorlinebuf;
1340 if (!buf) buf = staticbuf;
1342 ssize_t bytes_read;
1343 while (
1344 (bytes_read = read(
1345 worker->errorfd,
1346 buf + worker->errorlinelen,
1347 MOONBR_MAXERRORLINELEN+1 - worker->errorlinelen
1348 )) <= 0
1349 ) {
1350 if (bytes_read == 0 || errno == ECONNRESET) {
1351 if (moonbr_debug) {
1352 moonbr_log(LOG_DEBUG, "Child process in pool #%i with PID %i closed stderr socket", worker->pool->poolnum, (int)worker->pid);
1354 if (close(worker->errorfd) && errno != EINTR) {
1355 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));
1356 moonbr_terminate_error();
1358 worker->errorfd = -1;
1359 moonbr_poll_refresh_needed = 1;
1360 break;
1362 if (errno != EINTR) {
1363 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));
1364 moonbr_terminate_error();
1367 worker->errorlinelen += bytes_read;
1370 int i;
1371 for (i=0; i<worker->errorlinelen; i++) {
1372 if (buf[i] == '\n') buf[i] = 0;
1373 if (!buf[i]) {
1374 if (worker->errorlineovf) {
1375 worker->errorlineovf = 0;
1376 } else {
1377 moonbr_log(LOG_WARNING, "Error log from process in pool #%i with PID %i: %s", worker->pool->poolnum, (int)worker->pid, buf);
1379 worker->errorlinelen -= i+1;
1380 memmove(buf, buf+i+1, worker->errorlinelen);
1381 i = -1;
1384 if (i > MOONBR_MAXERRORLINELEN) {
1385 buf[MOONBR_MAXERRORLINELEN] = 0;
1386 if (!worker->errorlineovf) {
1387 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);
1389 worker->errorlinelen = 0;
1390 worker->errorlineovf = 1;
1393 if (!worker->errorlinebuf && worker->errorlinelen) { /* allocate buffer on heap only if necessary */
1394 worker->errorlinebuf = malloc((MOONBR_MAXERRORLINELEN+1) * sizeof(char));
1395 if (!worker->errorlinebuf) {
1396 moonbr_log(LOG_CRIT, "Memory allocation error");
1397 moonbr_terminate_error();
1399 memcpy(worker->errorlinebuf, staticbuf, worker->errorlinelen);
1404 /*** Handler for incoming connections ***/
1406 /* Accepts one or more incoming connections on listener socket and passes it to worker(s) popped from idle queue */
1407 static void moonbr_connect(struct moonbr_pool *pool) {
1408 struct moonbr_listener *listener = moonbr_pop_connected_listener(pool);
1409 struct moonbr_worker *worker;
1410 if (listener->proto == MOONBR_PROTO_MAIN) {
1411 worker = moonbr_pop_idle_worker(pool);
1412 if (moonbr_stat) {
1413 moonbr_log(LOG_INFO, "Dispatching main thread of pool #%i to PID %i", listener->pool->poolnum, (int)worker->pid);
1415 worker->main = 1;
1416 moonbr_send_control_message(worker, MOONBR_COMMAND_CONNECT, -1, listener);
1417 /* do not push listener to queue of idle listeners */
1418 } else if (listener->proto == MOONBR_PROTO_INTERVAL) {
1419 worker = moonbr_pop_idle_worker(pool);
1420 if (moonbr_stat) {
1421 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);
1423 worker->restart_interval_listener = listener;
1424 moonbr_send_control_message(worker, MOONBR_COMMAND_CONNECT, -1, listener);
1425 /* do not push listener to queue of idle listeners yet */
1426 } else {
1427 int peerfd;
1428 do {
1429 peerfd = accept4(listener->listenfd, NULL, NULL, SOCK_CLOEXEC);
1430 if (peerfd == -1) {
1431 if (errno == EWOULDBLOCK) {
1432 break;
1433 } else if (errno == ECONNABORTED) {
1434 moonbr_log(LOG_WARNING, "Connection aborted before accepting it");
1435 break;
1436 } else if (errno != EINTR) {
1437 moonbr_log(LOG_ERR, "Could not accept socket connection: %s", strerror(errno));
1438 moonbr_terminate_error();
1440 } else {
1441 worker = moonbr_pop_idle_worker(pool);
1442 if (moonbr_stat) {
1443 moonbr_log(LOG_INFO, "Dispatching connection for pool #%i to PID %i", listener->pool->poolnum, (int)worker->pid);
1445 moonbr_send_control_message(worker, MOONBR_COMMAND_CONNECT, peerfd, listener);
1446 if (close(peerfd) && errno != EINTR) {
1447 moonbr_log(LOG_ERR, "Could not close incoming socket connection in parent process: %s", strerror(errno));
1448 moonbr_terminate_error();
1451 } while (pool->first_idle_worker);
1452 moonbr_add_idle_listener(listener);
1457 /*** Functions to initialize and restart interval timers ***/
1459 /* Initializes all interval timers */
1460 static void moonbr_interval_initialize() {
1461 struct timeval now;
1462 struct moonbr_pool *pool;
1463 moonbr_now(&now);
1464 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1465 int i;
1466 for (i=0; i<pool->listener_count; i++) {
1467 struct moonbr_listener *listener = &pool->listener[i];
1468 if (listener->proto == MOONBR_PROTO_INTERVAL) {
1469 timeradd(
1470 &now,
1471 &listener->type_specific.interval.delay,
1472 &listener->type_specific.interval.wakeup
1473 );
1479 /* If necessary, restarts interval timers and queues interval listener as idle after a worker changed status */
1480 static void moonbr_interval_restart(
1481 struct moonbr_worker *worker,
1482 struct timeval *now /* passed to synchronize with moonbr_run() function */
1483 ) {
1484 struct moonbr_listener *listener = worker->restart_interval_listener;
1485 if (listener) {
1486 moonbr_add_idle_listener(listener);
1487 worker->restart_interval_listener = NULL;
1488 if (listener->type_specific.interval.strict) {
1489 timeradd(
1490 &listener->type_specific.interval.wakeup,
1491 &listener->type_specific.interval.delay,
1492 &listener->type_specific.interval.wakeup
1493 );
1494 if (timercmp(&listener->type_specific.interval.wakeup, now, <)) {
1495 listener->type_specific.interval.wakeup = *now;
1497 } else {
1498 timeradd(
1499 now,
1500 &listener->type_specific.interval.delay,
1501 &listener->type_specific.interval.wakeup
1502 );
1508 /*** Main loop and helper functions ***/
1510 /* Stores the earliest required wakeup time in 'wait' variable */
1511 static void moonbr_calc_wait(struct timeval *wait, struct timeval *wakeup) {
1512 if (!timerisset(wait) || timercmp(wakeup, wait, <)) *wait = *wakeup;
1515 /* Main loop of Moonbridge system (including initialization of signal handlers and polling structures) */
1516 static void moonbr_run(lua_State *L) {
1517 struct timeval now;
1518 struct moonbr_pool *pool;
1519 struct moonbr_worker *worker;
1520 struct moonbr_worker *next_worker; /* needed when worker is removed during iteration of workers */
1521 struct moonbr_listener *listener;
1522 struct moonbr_listener *next_listener; /* needed when listener is removed during iteration of listeners */
1523 int i;
1524 moonbr_poll_init(); /* must be executed before moonbr_signal_init() */
1525 moonbr_signal_init();
1526 moonbr_interval_initialize();
1527 moonbr_pstate = MOONBR_PSTATE_RUNNING;
1528 while (1) {
1529 struct timeval wait = {0, }; /* point in time when premature wakeup of poll() is required */
1530 if (moonbr_cond_interrupt) {
1531 moonbr_log(LOG_WARNING, "Fast shutdown requested");
1532 moonbr_terminate(MOONBR_EXITCODE_GRACEFUL);
1534 if (moonbr_cond_terminate) {
1535 moonbr_initiate_shutdown();
1536 moonbr_cond_terminate = 0;
1538 moonbr_cond_child = 0; /* must not be reset between moonbr_try_destroy_worker() and poll() */
1539 moonbr_now(&now);
1540 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1541 int terminated_worker_count = 0; /* allows shortcut for new worker creation */
1542 /* terminate idle workers when expired */
1543 if (timerisset(&pool->idle_timeout)) {
1544 while ((worker = pool->first_idle_worker) != NULL) {
1545 if (timercmp(&worker->idle_expiration, &now, >)) break;
1546 moonbr_pop_idle_worker(pool);
1547 moonbr_terminate_idle_worker(worker);
1550 /* mark listeners as connected when incoming connection is pending */
1551 for (listener=pool->first_idle_listener; listener; listener=next_listener) {
1552 next_listener = listener->next_listener; /* extra variable necessary due to changing list */
1553 if (listener->pollidx != -1) {
1554 if (moonbr_poll_fds[listener->pollidx].revents) {
1555 moonbr_poll_fds[listener->pollidx].revents = 0;
1556 moonbr_remove_idle_listener(listener);
1557 moonbr_add_connected_listener(listener);
1559 } else if (
1560 listener->proto != MOONBR_PROTO_INTERVAL ||
1561 !timercmp(&listener->type_specific.interval.wakeup, &now, >)
1562 ) {
1563 moonbr_remove_idle_listener(listener);
1564 moonbr_add_connected_listener(listener);
1567 /* process input from child processes */
1568 for (i=0; i<moonbr_poll_worker_count; i++) {
1569 if (moonbr_poll_worker_fds[i].revents) {
1570 moonbr_poll_worker_fds[i].revents = 0;
1571 struct moonbr_poll_worker *poll_worker = &moonbr_poll_workers[i];
1572 switch (poll_worker->channel) {
1573 case MOONBR_POLL_WORKER_CONTROLCHANNEL:
1574 moonbr_read_controlchannel(poll_worker->worker);
1575 moonbr_interval_restart(poll_worker->worker, &now);
1576 break;
1577 case MOONBR_POLL_WORKER_ERRORCHANNEL:
1578 moonbr_read_errorchannel(poll_worker->worker);
1579 break;
1583 /* collect dead child processes */
1584 for (worker=pool->first_worker; worker; worker=next_worker) {
1585 next_worker = worker->next_worker; /* extra variable necessary due to changing list */
1586 switch (moonbr_try_destroy_worker(worker)) {
1587 case MOONBR_DESTROY_PREPARE:
1588 pool->use_fork_error_wakeup = 1;
1589 break;
1590 case MOONBR_DESTROY_IDLE_OR_ASSIGNED:
1591 terminated_worker_count++;
1592 break;
1595 if (!moonbr_shutdown_in_progress) {
1596 /* connect listeners with idle workers */
1597 while (pool->first_connected_listener && pool->first_idle_worker) {
1598 moonbr_connect(pool);
1600 /* create new worker processes */
1601 while (
1602 pool->total_worker_count < pool->max_fork && (
1603 pool->unassigned_worker_count < pool->pre_fork ||
1604 pool->total_worker_count < pool->min_fork
1606 ) {
1607 if (pool->use_fork_error_wakeup) {
1608 if (timercmp(&pool->fork_error_wakeup, &now, >)) {
1609 moonbr_calc_wait(&wait, &pool->fork_error_wakeup);
1610 break;
1612 } else {
1613 if (terminated_worker_count) {
1614 terminated_worker_count--;
1615 } else if (timercmp(&pool->fork_wakeup, &now, >)) {
1616 moonbr_calc_wait(&wait, &pool->fork_wakeup);
1617 break;
1620 if (moonbr_create_worker(pool, L)) {
1621 /* on error, enforce error delay */
1622 timeradd(&now, &pool->fork_error_delay, &pool->fork_error_wakeup);
1623 pool->use_fork_error_wakeup = 1;
1624 moonbr_calc_wait(&wait, &pool->fork_error_wakeup);
1625 break;
1626 } else {
1627 /* normal fork delay on success */
1628 timeradd(&now, &pool->fork_delay, &pool->fork_wakeup);
1629 timeradd(&now, &pool->fork_error_delay, &pool->fork_error_wakeup);
1630 pool->use_fork_error_wakeup = 0; /* gets set later if error occures during preparation */
1633 /* terminate excessive worker processes */
1634 while (
1635 pool->total_worker_count > pool->min_fork &&
1636 pool->idle_worker_count > pool->pre_fork
1637 ) {
1638 if (timerisset(&pool->exit_wakeup)) {
1639 if (timercmp(&pool->exit_wakeup, &now, >)) {
1640 moonbr_calc_wait(&wait, &pool->exit_wakeup);
1641 break;
1643 moonbr_terminate_idle_worker(moonbr_pop_idle_worker(pool));
1644 timeradd(&now, &pool->exit_delay, &pool->exit_wakeup);
1645 } else {
1646 timeradd(&now, &pool->exit_delay, &pool->exit_wakeup);
1647 break;
1650 if (!(
1651 pool->total_worker_count > pool->min_fork &&
1652 pool->idle_worker_count > pool->pre_fork
1653 )) {
1654 timerclear(&pool->exit_wakeup); /* timer gets restarted later when there are excessive workers */
1657 /* optionally output worker count stats */
1658 if (moonbr_stat && pool->worker_count_stat) {
1659 pool->worker_count_stat = 0;
1660 moonbr_log(
1661 LOG_INFO,
1662 "Worker count for pool #%i: %i idle, %i assigned, %i total",
1663 pool->poolnum, pool->idle_worker_count,
1664 pool->total_worker_count - pool->unassigned_worker_count,
1665 pool->total_worker_count);
1667 /* calculate wakeup time for interval listeners */
1668 for (listener=pool->first_idle_listener; listener; listener=listener->next_listener) {
1669 if (listener->proto == MOONBR_PROTO_INTERVAL) {
1670 moonbr_calc_wait(&wait, &listener->type_specific.interval.wakeup);
1673 /* calculate wakeup time for idle workers (only first idle worker is significant) */
1674 if (timerisset(&pool->idle_timeout) && pool->first_idle_worker) {
1675 moonbr_calc_wait(&wait, &pool->first_idle_worker->idle_expiration);
1678 /* terminate idle workers in case of shutdown and check if shutdown is complete */
1679 if (moonbr_shutdown_in_progress) {
1680 for (pool=moonbr_first_pool; pool; pool=pool->next_pool) {
1681 if (pool->first_worker) {
1682 while (pool->idle_worker_count) {
1683 moonbr_terminate_idle_worker(moonbr_pop_idle_worker(pool));
1685 break;
1688 if (!pool) {
1689 moonbr_log(LOG_INFO, "All worker threads have terminated");
1690 moonbr_terminate(MOONBR_EXITCODE_GRACEFUL);
1693 if (moonbr_poll_refresh_needed) moonbr_poll_refresh();
1694 moonbr_cond_poll = 1;
1695 if (!moonbr_cond_child && !moonbr_cond_terminate && !moonbr_cond_interrupt) {
1696 int timeout;
1697 if (timerisset(&wait)) {
1698 if (timercmp(&wait, &now, <)) {
1699 moonbr_log(LOG_CRIT, "Internal error (should not happen): Future is in the past");
1700 moonbr_terminate_error();
1702 timersub(&wait, &now, &wait);
1703 timeout = wait.tv_sec * 1000 + wait.tv_usec / 1000;
1704 } else {
1705 timeout = INFTIM;
1707 if (moonbr_debug) {
1708 moonbr_log(LOG_DEBUG, "Waiting for I/O");
1710 poll(moonbr_poll_fds, moonbr_poll_fds_count, timeout);
1711 } else {
1712 if (moonbr_debug) {
1713 moonbr_log(LOG_DEBUG, "Do not wait for I/O");
1716 moonbr_cond_poll = 0;
1717 moonbr_poll_reset_signal();
1722 /*** Lua interface ***/
1724 static int moonbr_lua_panic(lua_State *L) {
1725 const char *errmsg;
1726 errmsg = lua_tostring(L, -1);
1727 if (!errmsg) {
1728 if (lua_isnoneornil(L, -1)) errmsg = "(error message is nil)";
1729 else errmsg = "(error message is not a string)";
1731 if (moonbr_pstate == MOONBR_PSTATE_FORKED) {
1732 fprintf(stderr, "Uncaught Lua error: %s\n", errmsg);
1733 exit(1);
1734 } else {
1735 moonbr_log(LOG_CRIT, "Uncaught Lua error: %s", errmsg);
1736 moonbr_terminate_error();
1738 return 0;
1741 static int moonbr_addtraceback(lua_State *L) {
1742 luaL_traceback(L, L, luaL_tolstring(L, 1, NULL), 1);
1743 return 1;
1746 /* Memory allocator that allows limiting memory consumption */
1747 static void *moonbr_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
1748 (void)ud; /* not used */
1749 if (nsize == 0) {
1750 if (ptr) {
1751 moonbr_memory_usage -= osize;
1752 free(ptr);
1754 return NULL;
1755 } else if (ptr) {
1756 if (
1757 moonbr_memory_limit &&
1758 nsize > osize &&
1759 moonbr_memory_usage + (nsize - osize) > moonbr_memory_limit
1760 ) {
1761 return NULL;
1762 } else {
1763 ptr = realloc(ptr, nsize);
1764 if (ptr) moonbr_memory_usage += nsize - osize;
1766 } else {
1767 if (
1768 moonbr_memory_limit &&
1769 moonbr_memory_usage + nsize > moonbr_memory_limit
1770 ) {
1771 return NULL;
1772 } else {
1773 ptr = realloc(ptr, nsize);
1774 if (ptr) moonbr_memory_usage += nsize;
1777 return ptr;
1780 static int moonbr_lua_tonatural(lua_State *L, int idx) {
1781 int isnum;
1782 lua_Number n;
1783 n = lua_tonumberx(L, idx, &isnum);
1784 if (isnum && n>=0 && n<INT_MAX && (lua_Number)(int)n == n) return n;
1785 else return -1;
1788 static int moonbr_lua_totimeval(lua_State *L, int idx, struct timeval *value) {
1789 int isnum;
1790 lua_Number n;
1791 n = lua_tonumberx(L, idx, &isnum);
1792 if (isnum && n>=0 && n<=100000000) {
1793 value->tv_sec = n;
1794 value->tv_usec = 1e6 * (n - value->tv_sec);
1795 return 1;
1796 } else {
1797 return 0;
1801 static int moonbr_timeout(lua_State *L) {
1802 struct itimerval oldval;
1803 if (lua_isnoneornil(L, 1) && lua_isnoneornil(L, 2)) {
1804 getitimer(ITIMER_REAL, &oldval);
1805 } else {
1806 struct itimerval newval = {};
1807 timerclear(&newval.it_interval);
1808 timerclear(&newval.it_value);
1809 if (lua_toboolean(L, 1)) {
1810 luaL_argcheck(
1811 L, moonbr_lua_totimeval(L, 1, &newval.it_value), 1,
1812 "interval in seconds expected"
1813 );
1815 if (lua_isnoneornil(L, 2)) {
1816 if (setitimer(ITIMER_REAL, &newval, &oldval)) {
1817 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
1818 moonbr_terminate_error();
1820 } else {
1821 getitimer(ITIMER_REAL, &oldval);
1822 if (!timerisset(&oldval.it_value)) {
1823 if (setitimer(ITIMER_REAL, &newval, NULL)) {
1824 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
1825 moonbr_terminate_error();
1827 lua_call(L, lua_gettop(L) - 2, LUA_MULTRET);
1828 timerclear(&newval.it_value);
1829 if (setitimer(ITIMER_REAL, &newval, NULL)) {
1830 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
1831 moonbr_terminate_error();
1833 } else if (timercmp(&newval.it_value, &oldval.it_value, <)) {
1834 struct itimerval remval;
1835 if (setitimer(ITIMER_REAL, &newval, NULL)) {
1836 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
1837 moonbr_terminate_error();
1839 lua_call(L, lua_gettop(L) - 2, LUA_MULTRET);
1840 getitimer(ITIMER_REAL, &remval);
1841 timersub(&oldval.it_value, &newval.it_value, &newval.it_value);
1842 timeradd(&newval.it_value, &remval.it_value, &newval.it_value);
1843 if (setitimer(ITIMER_REAL, &newval, NULL)) {
1844 moonbr_log(LOG_CRIT, "Could not set ITIMER_REAL via setitimer()");
1845 moonbr_terminate_error();
1847 } else {
1848 lua_call(L, lua_gettop(L) - 2, LUA_MULTRET);
1850 return lua_gettop(L) - 1;
1853 lua_pushnumber(L, oldval.it_value.tv_sec + 1e-6 * oldval.it_value.tv_usec);
1854 return 1;
1857 #define moonbr_listen_init_pool_forkoption(luaname, cname, defval) { \
1858 lua_getfield(L, 2, luaname); \
1859 pool->cname = lua_isnil(L, -1) ? (defval) : moonbr_lua_tonatural(L, -1); \
1860 } while(0)
1862 #define moonbr_listen_init_pool_timeoption(luaname, cname, defval, defvalu) ( \
1863 lua_getfield(L, 2, luaname), \
1864 lua_isnil(L, -1) ? ( \
1865 pool->cname.tv_sec = (defval), pool->cname.tv_usec = (defvalu), \
1866 1 \
1867 ) : ( \
1868 (lua_isboolean(L, -1) && !lua_toboolean(L, -1)) ? ( \
1869 pool->cname.tv_sec = 0, pool->cname.tv_usec = 0, \
1870 1 \
1871 ) : ( \
1872 moonbr_lua_totimeval(L, -1, &pool->cname) \
1873 ) \
1874 ) \
1877 static int moonbr_listen_init_pool(lua_State *L) {
1878 struct moonbr_pool *pool;
1879 const char *proto;
1880 int i;
1881 int dynamic = 0; /* nonzero = listeners exist which require dynamic worker creation */
1882 pool = lua_touserdata(L, 1);
1883 for (i=0; i<pool->listener_count; i++) {
1884 struct moonbr_listener *listener = &pool->listener[i];
1885 lua_settop(L, 2);
1886 #if LUA_VERSION_NUM >= 503
1887 lua_geti(L, 2, i+1);
1888 #else
1889 lua_pushinteger(L, i+1);
1890 lua_gettable(L, 2);
1891 #endif
1892 lua_getfield(L, 3, "proto");
1893 proto = lua_tostring(L, -1);
1894 if (proto && !strcmp(proto, "main")) {
1895 listener->proto = MOONBR_PROTO_MAIN;
1896 } else if (proto && !strcmp(proto, "interval")) {
1897 dynamic = 1;
1898 listener->proto = MOONBR_PROTO_INTERVAL;
1899 lua_getfield(L, 3, "name");
1901 const char *name = lua_tostring(L, -1);
1902 if (name) {
1903 if (asprintf(&listener->type_specific.interval.name, "%s", name) < 0) {
1904 moonbr_log(LOG_CRIT, "Memory allocation_error");
1905 moonbr_terminate_error();
1909 lua_getfield(L, 3, "delay");
1910 if (
1911 !moonbr_lua_totimeval(L, -1, &listener->type_specific.interval.delay) ||
1912 !timerisset(&listener->type_specific.interval.delay)
1913 ) {
1914 luaL_error(L, "No valid interval delay specified; use listen{{proto=\"interval\", delay=...}, ...}");
1916 lua_getfield(L, 3, "strict");
1917 if (!lua_isnil(L, -1)) {
1918 if (lua_isboolean(L, -1)) {
1919 if (lua_toboolean(L, -1)) listener->type_specific.interval.strict = 1;
1920 } else {
1921 luaL_error(L, "Option \"strict\" must be a boolean if set; use listen{{proto=\"interval\", strict=true, ...}, ...}");
1924 } else if (proto && !strcmp(proto, "local")) {
1925 const char *path;
1926 const int path_maxlen = (
1927 sizeof(listener->type_specific.socket.addr.addr_un) -
1928 ((void *)listener->type_specific.socket.addr.addr_un.sun_path - (void *)&listener->type_specific.socket.addr.addr_un)
1929 ) - 1; /* one byte for termination */
1930 dynamic = 1;
1931 listener->proto = MOONBR_PROTO_LOCAL;
1932 lua_getfield(L, 3, "path");
1933 path = lua_tostring(L, -1);
1934 if (!path) {
1935 luaL_error(L, "No valid path specified for local socket; use listen{{proto=\"local\", path=...}, ...}");
1937 if (strlen(path) > path_maxlen) {
1938 luaL_error(L, "Path name for local socket exceeded maximum length of %i characters", path_maxlen);
1940 strcpy(listener->type_specific.socket.addr.addr_un.sun_path, path);
1941 } else if (proto && !strcmp(proto, "tcp")) {
1942 const char *host, *port;
1943 struct addrinfo hints = { 0, };
1944 struct addrinfo *res, *addrinfo;
1945 int errcode;
1946 const char *ip;
1947 dynamic = 1;
1948 lua_getfield(L, 3, "host");
1949 host = lua_isnil(L, -1) ? "::" : lua_tostring(L, -1);
1950 if (!host) {
1951 luaL_error(L, "No host specified; use listen{{proto=\"tcp\", host=...}, ...}");
1953 lua_getfield(L, 3, "port");
1954 port = lua_tostring(L, -1);
1955 if (!port) {
1956 luaL_error(L, "No port specified; use listen{{proto=\"tcp\", host=...}, ...}");
1958 hints.ai_family = AF_UNSPEC;
1959 hints.ai_socktype = SOCK_STREAM;
1960 hints.ai_protocol = IPPROTO_TCP;
1961 hints.ai_flags = AI_ADDRCONFIG | AI_PASSIVE;
1962 errcode = getaddrinfo(host, port, &hints, &res);
1963 if (errcode) {
1964 freeaddrinfo(res);
1965 if (errcode == EAI_SYSTEM) {
1966 char errmsg[MOONBR_MAXSTRERRORLEN];
1967 strerror_r(errno, errmsg, MOONBR_MAXSTRERRORLEN); /* use thread-safe call in case child created threads */
1968 luaL_error(L, "Could not resolve host: %s: %s", gai_strerror(errcode), errmsg);
1969 } else {
1970 luaL_error(L, "Could not resolve host: %s", gai_strerror(errcode));
1973 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1974 if (addrinfo->ai_family == AF_INET6) goto moonbr_listen_init_pool_found;
1976 for (addrinfo=res; addrinfo; addrinfo=addrinfo->ai_next) {
1977 if (addrinfo->ai_family == AF_INET) goto moonbr_listen_init_pool_found;
1979 addrinfo = res;
1980 moonbr_listen_init_pool_found:
1981 if (addrinfo->ai_addrlen > sizeof(listener->type_specific.socket.addr)) {
1982 moonbr_log(LOG_CRIT, "Size of ai_addrlen is unexpectedly big (should not happen)");
1983 moonbr_terminate_error();
1985 memcpy(&listener->type_specific.socket.addr, addrinfo->ai_addr, addrinfo->ai_addrlen);
1986 listener->type_specific.socket.addrlen = addrinfo->ai_addrlen;
1987 switch (addrinfo->ai_family) {
1988 case AF_INET6:
1989 ip = inet_ntop(
1990 addrinfo->ai_family,
1991 &((struct sockaddr_in6 *)addrinfo->ai_addr)->sin6_addr,
1992 listener->proto_specific.tcp.ip,
1993 INET6_ADDRSTRLEN
1994 );
1995 if (!ip) {
1996 moonbr_log(LOG_CRIT, "System error in inet_ntop call: %s", strerror(errno));
1997 moonbr_terminate_error();
1999 listener->proto_specific.tcp.port = ntohs(((struct sockaddr_in6 *)addrinfo->ai_addr)->sin6_port);
2000 break;
2001 case AF_INET:
2002 ip = inet_ntop(
2003 addrinfo->ai_family,
2004 &((struct sockaddr_in *)addrinfo->ai_addr)->sin_addr,
2005 listener->proto_specific.tcp.ip,
2006 INET6_ADDRSTRLEN
2007 );
2008 if (!ip) {
2009 moonbr_log(LOG_CRIT, "System error in inet_ntop call: %s", strerror(errno));
2010 moonbr_terminate_error();
2012 listener->proto_specific.tcp.port = ntohs(((struct sockaddr_in *)addrinfo->ai_addr)->sin_port);
2013 break;
2014 default:
2015 strcpy(listener->proto_specific.tcp.ip, "unknown");
2016 listener->proto_specific.tcp.port = 0;
2018 listener->proto = MOONBR_PROTO_TCP;
2019 } else if (proto) {
2020 luaL_error(L, "Unknown protocol \"%s\"", proto);
2021 } else {
2022 luaL_error(L, "No valid protocol specified; use listen{{proto=..., ...}, ...}");
2025 lua_settop(L, 2);
2026 if (dynamic) {
2027 moonbr_listen_init_pool_forkoption("pre_fork", pre_fork, 1);
2028 moonbr_listen_init_pool_forkoption("min_fork", min_fork, pool->pre_fork > 2 ? pool->pre_fork : 2);
2029 moonbr_listen_init_pool_forkoption("max_fork", max_fork, pool->min_fork > 16 ? pool->min_fork : 16);
2030 if (!moonbr_listen_init_pool_timeoption("fork_delay", fork_delay, 0, 250000)) {
2031 luaL_error(L, "Option \"fork_delay\" is expected to be a non-negative number");
2033 if (!moonbr_listen_init_pool_timeoption("fork_error_delay", fork_error_delay, 2, 0)) {
2034 luaL_error(L, "Option \"fork_error_delay\" is expected to be a non-negative number");
2036 if (!moonbr_listen_init_pool_timeoption("exit_delay", exit_delay, 60, 0)) {
2037 luaL_error(L, "Option \"exit_delay\" is expected to be a non-negative number");
2039 if (timercmp(&pool->fork_error_delay, &pool->fork_delay, <)) {
2040 pool->fork_error_delay = pool->fork_delay;
2042 if (!moonbr_listen_init_pool_timeoption("idle_timeout", idle_timeout, 0, 0)) {
2043 luaL_error(L, "Option \"idle_timeout\" is expected to be a non-negative number");
2045 } else {
2046 pool->pre_fork = 0;
2047 pool->min_fork = pool->listener_count;
2048 pool->max_fork = pool->listener_count;
2050 lua_getfield(L, 2, "memory_limit");
2051 if (!lua_isnil(L, -1)) {
2052 int isnum;
2053 lua_Number n;
2054 n = lua_tonumberx(L, -1, &isnum);
2055 if (n < 0 || !isnum) {
2056 luaL_error(L, "Option \"memory_limit\" is expected to be a non-negative number");
2058 pool->memory_limit = n;
2060 lua_settop(L, 2);
2061 lua_getfield(L, 2, "prepare");
2062 if (!lua_isnil(L, -1) && !lua_isfunction(L, -1)) {
2063 luaL_error(L, "Option \"prepare\" must be nil or a function");
2065 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_prepare_func(pool));
2066 lua_getfield(L, 2, "connect");
2067 if (!lua_isfunction(L, -1)) {
2068 luaL_error(L, "Option \"connect\" must be a function; use listen{{...}, {...}, connect=function(socket) ... end, ...}");
2070 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_connect_func(pool));
2071 lua_getfield(L, 2, "finish");
2072 if (!lua_isnil(L, -1) && !lua_isfunction(L, -1)) {
2073 luaL_error(L, "Option \"finish\" must be nil or a function");
2075 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_finish_func(pool));
2076 return 0;
2079 static int moonbr_listen(lua_State *L) {
2080 struct moonbr_pool *pool;
2081 lua_Integer listener_count;
2082 if (moonbr_booted) luaL_error(L, "Moonbridge bootup is already complete");
2083 luaL_checktype(L, 1, LUA_TTABLE);
2084 listener_count = luaL_len(L, 1);
2085 if (!listener_count) luaL_error(L, "No listen ports specified; use listen{{proto=..., port=...},...}");
2086 if (listener_count > 100) luaL_error(L, "Too many listeners");
2087 pool = moonbr_create_pool(listener_count);
2088 lua_pushcfunction(L, moonbr_listen_init_pool);
2089 lua_pushlightuserdata(L, pool);
2090 lua_pushvalue(L, 1);
2091 if (lua_pcall(L, 2, 0, 0)) goto moonbr_listen_error;
2093 int i;
2094 i = moonbr_start_pool(pool);
2095 if (i >= 0) {
2096 lua_pushfstring(L, "Could not initialize listener #%d: %s", i+1, strerror(errno));
2097 moonbr_listen_error:
2098 moonbr_destroy_pool(pool);
2099 lua_pushnil(L);
2100 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_prepare_func(pool));
2101 lua_pushnil(L);
2102 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_connect_func(pool));
2103 lua_pushnil(L);
2104 lua_rawsetp(L, LUA_REGISTRYINDEX, moonbr_luakey_finish_func(pool));
2105 lua_error(L);
2108 return 0;
2112 /*** Function to modify Lua's library path and/or cpath ***/
2114 #if defined(MOONBR_LUA_PATH) || defined(MOONBR_LUA_CPATH)
2115 static void moonbr_modify_path(lua_State *L, char *key, char *value) {
2116 int stackbase;
2117 stackbase = lua_gettop(L);
2118 lua_getglobal(L, "package");
2119 lua_getfield(L, stackbase+1, key);
2121 const char *current_str;
2122 size_t current_strlen;
2123 luaL_Buffer buf;
2124 current_str = lua_tolstring(L, stackbase+2, &current_strlen);
2125 luaL_buffinit(L, &buf);
2126 if (current_str) {
2127 lua_pushvalue(L, stackbase+2);
2128 luaL_addvalue(&buf);
2129 if (current_strlen && current_str[current_strlen-1] != ';') {
2130 luaL_addchar(&buf, ';');
2133 luaL_addstring(&buf, value);
2134 luaL_pushresult(&buf);
2136 lua_setfield(L, stackbase+1, key);
2137 lua_settop(L, stackbase);
2139 #endif
2142 /*** Main function and command line invokation ***/
2144 static void moonbr_usage(int err, const char *cmd) {
2145 FILE *out;
2146 out = err ? stderr : stdout;
2147 if (!cmd) cmd = "moonbridge";
2148 fprintf(out, "Get this help message: %s {-h|--help}\n", cmd);
2149 fprintf(out, "Usage: %s \\\n", cmd);
2150 fprintf(out, " [-b|--background] \\\n");
2151 fprintf(out, " [-d|--debug] \\\n");
2152 fprintf(out, " [-f|--logfacility {DAEMON|USER|0|1|...|7}] \\\n");
2153 fprintf(out, " [-i|--logident <syslog ident> \\\n");
2154 fprintf(out, " [-l|--logfile <logfile>] \\\n");
2155 fprintf(out, " [-p|--pidfile <pidfile>] \\\n");
2156 fprintf(out, " [-s|--stats] \\\n");
2157 fprintf(out, " -- <Lua script> [<cmdline options for Lua script>]\n");
2158 exit(err);
2161 #define moonbr_usage_error() moonbr_usage(MOONBR_EXITCODE_CMDLINEERROR, argc ? argv[0] : NULL)
2163 int main(int argc, char **argv) {
2165 int daemonize = 0;
2166 int log_facility = LOG_USER;
2167 const char *log_ident = "moonbridge";
2168 const char *log_filename = NULL;
2169 const char *pid_filename = NULL;
2170 int option;
2171 struct option longopts[] = {
2172 { "background", no_argument, NULL, 'b' },
2173 { "debug", no_argument, NULL, 'd' },
2174 { "logfacility", required_argument, NULL, 'f' },
2175 { "help", no_argument, NULL, 'h' },
2176 { "logident", required_argument, NULL, 'i' },
2177 { "logfile", required_argument, NULL, 'l' },
2178 { "pidfile", required_argument, NULL, 'p' },
2179 { "stats", no_argument, NULL, 's' }
2180 };
2181 while ((option = getopt_long(argc, argv, "bdf:hi:l:p:s", longopts, NULL)) != -1) {
2182 switch (option) {
2183 case 'b':
2184 daemonize = 1;
2185 break;
2186 case 'd':
2187 moonbr_debug = 1;
2188 moonbr_stat = 1;
2189 break;
2190 case 'f':
2191 if (!strcmp(optarg, "DAEMON")) {
2192 log_facility = LOG_DAEMON;
2193 } else if (!strcmp(optarg, "USER")) {
2194 log_facility = LOG_USER;
2195 } else if (!strcmp(optarg, "0")) {
2196 log_facility = LOG_LOCAL0;
2197 } else if (!strcmp(optarg, "1")) {
2198 log_facility = LOG_LOCAL1;
2199 } else if (!strcmp(optarg, "2")) {
2200 log_facility = LOG_LOCAL2;
2201 } else if (!strcmp(optarg, "3")) {
2202 log_facility = LOG_LOCAL3;
2203 } else if (!strcmp(optarg, "4")) {
2204 log_facility = LOG_LOCAL4;
2205 } else if (!strcmp(optarg, "5")) {
2206 log_facility = LOG_LOCAL5;
2207 } else if (!strcmp(optarg, "6")) {
2208 log_facility = LOG_LOCAL6;
2209 } else if (!strcmp(optarg, "7")) {
2210 log_facility = LOG_LOCAL7;
2211 } else {
2212 moonbr_usage_error();
2214 moonbr_use_syslog = 1;
2215 break;
2216 case 'h':
2217 moonbr_usage(MOONBR_EXITCODE_GRACEFUL, argv[0]);
2218 break;
2219 case 'i':
2220 log_ident = optarg;
2221 moonbr_use_syslog = 1;
2222 break;
2223 case 'l':
2224 log_filename = optarg;
2225 break;
2226 case 'p':
2227 pid_filename = optarg;
2228 break;
2229 case 's':
2230 moonbr_stat = 1;
2231 break;
2232 default:
2233 moonbr_usage_error();
2236 if (argc - optind < 1) moonbr_usage_error();
2237 if (pid_filename) {
2238 pid_t otherpid;
2239 while ((moonbr_pidfh = pidfile_open(pid_filename, 0644, &otherpid)) == NULL) {
2240 if (errno == EEXIST) {
2241 if (otherpid == -1) {
2242 fprintf(stderr, "PID file \"%s\" is already locked\n", pid_filename);
2243 } else {
2244 fprintf(stderr, "PID file \"%s\" is already locked by process with PID: %i\n", pid_filename, (int)otherpid);
2246 exit(MOONBR_EXITCODE_ALREADYRUNNING);
2247 } else if (errno != EINTR) {
2248 fprintf(stderr, "Could not write PID file \"%s\": %s\n", pid_filename, strerror(errno));
2249 exit(MOONBR_EXITCODE_STARTUPERROR);
2253 if (log_filename) {
2254 int logfd;
2255 while (
2256 ( logfd = flopen(
2257 log_filename,
2258 O_WRONLY|O_NONBLOCK|O_CREAT|O_APPEND|O_CLOEXEC,
2259 0640
2261 ) < 0
2262 ) {
2263 if (errno == EWOULDBLOCK) {
2264 fprintf(stderr, "Logfile \"%s\" is locked\n", log_filename);
2265 exit(MOONBR_EXITCODE_ALREADYRUNNING);
2266 } else if (errno != EINTR) {
2267 fprintf(stderr, "Could not open logfile \"%s\": %s\n", log_filename, strerror(errno));
2268 exit(MOONBR_EXITCODE_STARTUPERROR);
2271 moonbr_logfile = fdopen(logfd, "a");
2272 if (!moonbr_logfile) {
2273 fprintf(stderr, "Could not open write stream to logfile \"%s\": %s\n", log_filename, strerror(errno));
2274 exit(MOONBR_EXITCODE_STARTUPERROR);
2277 if (daemonize == 0 && !moonbr_logfile) moonbr_logfile = stderr;
2278 if (moonbr_logfile) setlinebuf(moonbr_logfile);
2279 else moonbr_use_syslog = 1;
2280 if (moonbr_use_syslog) openlog(log_ident, LOG_NDELAY | LOG_PID, log_facility);
2281 if (daemonize) {
2282 if (daemon(1, 0)) {
2283 moonbr_log(LOG_ERR, "Could not daemonize moonbridge process");
2284 moonbr_terminate_error();
2288 moonbr_log(LOG_NOTICE, "Starting moonbridge server");
2289 if (moonbr_pidfh && pidfile_write(moonbr_pidfh)) {
2290 moonbr_log(LOG_ERR, "Could not write pidfile (after locking)");
2293 lua_State *L;
2294 L = lua_newstate(moonbr_alloc, NULL);
2295 if (!L) {
2296 moonbr_log(LOG_CRIT, "Could not initialize Lua state");
2297 moonbr_terminate_error();
2299 lua_atpanic(L, moonbr_lua_panic);
2300 lua_pushliteral(L, MOONBR_VERSION_STRING);
2301 lua_setglobal(L, "_MOONBRIDGE_VERSION");
2302 luaL_openlibs(L);
2303 luaL_requiref(L, "moonbridge_io", luaopen_moonbridge_io, 1);
2304 lua_pop(L, 1);
2305 #ifdef MOONBR_LUA_PATH
2306 moonbr_modify_path(L, "path", MOONBR_LUA_PATH);
2307 #endif
2308 #ifdef MOONBR_LUA_CPATH
2309 moonbr_modify_path(L, "cpath", MOONBR_LUA_CPATH);
2310 #endif
2311 lua_pushcfunction(L, moonbr_timeout);
2312 lua_setglobal(L, "timeout");
2313 lua_pushcfunction(L, moonbr_listen);
2314 lua_setglobal(L, "listen");
2315 lua_pushcfunction(L, moonbr_addtraceback); /* on stack position 1 */
2316 moonbr_log(LOG_INFO, "Loading \"%s\"", argv[optind]);
2317 if (luaL_loadfile(L, argv[optind])) {
2318 moonbr_log(LOG_ERR, "Error while loading \"%s\": %s", argv[optind], lua_tostring(L, -1));
2319 moonbr_terminate_error();
2321 { int i; for (i=optind+1; i<argc; i++) lua_pushstring(L, argv[i]); }
2322 if (lua_pcall(L, argc-(optind+1), 0, 1)) {
2323 moonbr_log(LOG_ERR, "Error while executing \"%s\": %s", argv[optind], lua_tostring(L, -1));
2324 moonbr_terminate_error();
2326 if (!moonbr_first_pool) {
2327 moonbr_log(LOG_WARNING, "No listener initialized.");
2328 moonbr_terminate_error();
2330 lua_getglobal(L, "listen");
2331 lua_pushcfunction(L, moonbr_listen);
2332 if (lua_compare(L, -2, -1, LUA_OPEQ)) {
2333 lua_pushnil(L);
2334 lua_setglobal(L, "listen");
2336 lua_settop(L, 1);
2337 lua_gc(L, LUA_GCCOLLECT, 0); // collect garbage before forking later
2338 moonbr_run(L);
2340 return 0;

Impressum / About Us