moonbridge

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

Impressum / About Us