1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * 3. The end-user documentation included with the redistribution,
20 * if any, must include the following acknowledgment:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowledgment may appear in the software itself,
24 * if and wherever such third-party acknowledgments normally appear.
26 * 4. The names "Apache" and "Apache Software Foundation" must
27 * not be used to endorse or promote products derived from this
28 * software without prior written permission. For written
29 * permission, please contact apache@apache.org.
31 * 5. Products derived from this software may not be called "Apache",
32 * nor may "Apache" appear in their name, without prior written
33 * permission of the Apache Software Foundation.
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * ====================================================================
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
54 * Portions of this software are based upon public domain software
55 * originally written at the National Center for Supercomputing Applications,
56 * University of Illinois, Urbana-Champaign.
61 #include "apr_portable.h"
62 #include "apr_file_io.h"
63 #include "apr_thread_proc.h"
64 #include "ap_config.h"
66 #include "http_main.h"
68 #include "http_config.h" /* for read_config */
69 #include "http_core.h" /* for get_remote_host */
70 #include "http_connection.h"
73 #include "mpm_common.h"
74 #include "iol_socket.h"
75 #include "ap_listen.h"
76 #include "scoreboard.h"
78 #ifdef HAVE_NETINET_TCP_H
79 #include <netinet/tcp.h>
81 #ifdef HAVE_SYS_SOCKET_H
82 #include <sys/socket.h>
84 #ifdef HAVE_SYS_WAIT_H
91 * Actual definitions of config globals
94 int ap_threads_per_child=0; /* Worker threads per child */
95 int ap_max_requests_per_child=0;
96 static const char *ap_pid_fname=NULL;
97 API_VAR_EXPORT const char *ap_scoreboard_fname=NULL;
98 static int ap_daemons_to_start=0;
99 static int min_spare_threads=0;
100 static int max_spare_threads=0;
101 static int ap_daemons_limit=0;
102 static time_t ap_restart_time=0;
103 API_VAR_EXPORT int ap_extended_status = 0;
104 static int workers_may_exit = 0;
105 static int requests_this_child;
106 static int num_listensocks = 0;
107 static ap_socket_t **listensocks;
109 /* The structure used to pass unique initialization info to each thread */
114 ap_pool_t *tpool; /* "pthread" would be confusing */
118 * The max child slot ever assigned, preserved across restarts. Necessary
119 * to deal with MaxClients changes across SIGWINCH restarts. We use this
120 * value to optimize routines that have to scan the entire scoreboard.
122 int ap_max_daemons_limit = -1;
124 static char ap_coredump_dir[MAX_STRING_LEN];
126 static ap_file_t *pipe_of_death_in = NULL;
127 static ap_file_t *pipe_of_death_out = NULL;
128 static pthread_mutex_t pipe_of_death_mutex;
130 /* *Non*-shared http_main globals... */
132 server_rec *ap_server_conf;
134 /* one_process --- debugging mode variable; can be set from the command line
135 * with the -X flag. If set, this gets you the child_main loop running
136 * in the process which originally started up (no detach, no make_child),
137 * which is a pretty nice debugging environment. (You'll get a SIGHUP
138 * early in standalone_main; just continue through. This is the server
139 * trying to kill off any child processes which it might have lying
140 * around --- Apache doesn't keep track of their pids, it just sends
141 * SIGHUP to the process group, ignoring it in the root process.
142 * Continue through and you'll be fine.).
145 static int one_process = 0;
148 int raise_sigstop_flags;
151 static ap_pool_t *pconf; /* Pool for config stuff */
152 static ap_pool_t *pchild; /* Pool for httpd child stuff */
154 int ap_my_pid; /* Linux getpid() doesn't work except in main thread. Use
156 /* Keep track of the number of worker threads currently active */
157 static int worker_thread_count;
158 static pthread_mutex_t worker_thread_count_mutex;
160 /* Locks for accept serialization */
161 static pthread_mutex_t thread_accept_mutex = PTHREAD_MUTEX_INITIALIZER;
162 static ap_lock_t *process_accept_mutex;
163 static const char *lock_fname;
165 #ifdef NO_SERIALIZED_ACCEPT
166 #define SAFE_ACCEPT(stmt) APR_SUCCESS
168 #define SAFE_ACCEPT(stmt) (stmt)
171 API_EXPORT(const server_rec *) ap_get_server_conf(void)
173 return (ap_server_conf);
176 API_EXPORT(int) ap_get_max_daemons(void)
178 return ap_max_daemons_limit;
181 /* a clean exit from a child with proper cleanup */
182 static void clean_child_exit(int code) __attribute__ ((noreturn));
183 void clean_child_exit(int code)
186 ap_destroy_pool(pchild);
191 /* handle all varieties of core dumping signals */
192 static void sig_coredump(int sig)
194 chdir(ap_coredump_dir);
195 ap_signal(sig, SIG_DFL);
196 kill(ap_my_pid, sig);
197 /* At this point we've got sig blocked, because we're still inside
198 * the signal handler. When we leave the signal handler it will
199 * be unblocked, and we'll take the signal... and coredump or whatever
200 * is appropriate for this particular Unix. In addition the parent
201 * will see the real signal we received -- whereas if we called
202 * abort() here, the parent would only see SIGABRT.
206 static void just_die(int sig)
211 /*****************************************************************
212 * Connection structures and accounting...
215 /* volatile just in case */
216 static int volatile shutdown_pending;
217 static int volatile restart_pending;
218 static int volatile is_graceful;
219 ap_generation_t volatile ap_my_generation;
222 * ap_start_shutdown() and ap_start_restart(), below, are a first stab at
223 * functions to initiate shutdown or restart without relying on signals.
224 * Previously this was initiated in sig_term() and restart() signal handlers,
225 * but we want to be able to start a shutdown/restart from other sources --
226 * e.g. on Win32, from the service manager. Now the service manager can
227 * call ap_start_shutdown() or ap_start_restart() as appropiate. Note that
228 * these functions can also be called by the child processes, since global
229 * variables are no longer used to pass on the required action to the parent.
231 * These should only be called from the parent process itself, since the
232 * parent process will use the shutdown_pending and restart_pending variables
233 * to determine whether to shutdown or restart. The child process should
234 * call signal_parent() directly to tell the parent to die -- this will
235 * cause neither of those variable to be set, which the parent will
236 * assume means something serious is wrong (which it will be, for the
237 * child to force an exit) and so do an exit anyway.
240 void ap_start_shutdown(void)
242 if (shutdown_pending == 1) {
243 /* Um, is this _probably_ not an error, if the user has
244 * tried to do a shutdown twice quickly, so we won't
245 * worry about reporting it.
249 shutdown_pending = 1;
252 /* do a graceful restart if graceful == 1 */
253 void ap_start_restart(int graceful)
256 if (restart_pending == 1) {
257 /* Probably not an error - don't bother reporting it */
261 is_graceful = graceful;
264 static void sig_term(int sig)
269 static void restart(int sig)
272 ap_start_restart(sig == SIGWINCH);
278 static void set_signals(void)
280 #ifndef NO_USE_SIGACTION
283 sigemptyset(&sa.sa_mask);
287 sa.sa_handler = sig_coredump;
288 #if defined(SA_ONESHOT)
289 sa.sa_flags = SA_ONESHOT;
290 #elif defined(SA_RESETHAND)
291 sa.sa_flags = SA_RESETHAND;
293 if (sigaction(SIGSEGV, &sa, NULL) < 0)
294 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGSEGV)");
296 if (sigaction(SIGBUS, &sa, NULL) < 0)
297 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGBUS)");
300 if (sigaction(SIGABORT, &sa, NULL) < 0)
301 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABORT)");
304 if (sigaction(SIGABRT, &sa, NULL) < 0)
305 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABRT)");
308 if (sigaction(SIGILL, &sa, NULL) < 0)
309 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGILL)");
313 sa.sa_handler = sig_term;
314 if (sigaction(SIGTERM, &sa, NULL) < 0)
315 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGTERM)");
317 if (sigaction(SIGINT, &sa, NULL) < 0)
318 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGINT)");
321 sa.sa_handler = SIG_DFL;
322 if (sigaction(SIGXCPU, &sa, NULL) < 0)
323 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXCPU)");
326 sa.sa_handler = SIG_DFL;
327 if (sigaction(SIGXFSZ, &sa, NULL) < 0)
328 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXFSZ)");
331 sa.sa_handler = SIG_IGN;
332 if (sigaction(SIGPIPE, &sa, NULL) < 0)
333 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGPIPE)");
336 /* we want to ignore HUPs and WINCH while we're busy processing one */
337 sigaddset(&sa.sa_mask, SIGHUP);
338 sigaddset(&sa.sa_mask, SIGWINCH);
339 sa.sa_handler = restart;
340 if (sigaction(SIGHUP, &sa, NULL) < 0)
341 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGHUP)");
342 if (sigaction(SIGWINCH, &sa, NULL) < 0)
343 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGWINCH)");
346 ap_signal(SIGSEGV, sig_coredump);
348 ap_signal(SIGBUS, sig_coredump);
351 ap_signal(SIGABORT, sig_coredump);
352 #endif /* SIGABORT */
354 ap_signal(SIGABRT, sig_coredump);
357 ap_signal(SIGILL, sig_coredump);
360 ap_signal(SIGXCPU, SIG_DFL);
363 ap_signal(SIGXFSZ, SIG_DFL);
367 ap_signal(SIGTERM, sig_term);
369 ap_signal(SIGHUP, restart);
372 ap_signal(SIGWINCH, restart);
373 #endif /* SIGWINCH */
375 ap_signal(SIGPIPE, SIG_IGN);
381 static void process_child_status(ap_proc_t *pid, ap_wait_t status)
383 /* Child died... if it died due to a fatal error,
384 * we should simply bail out.
386 if ((WIFEXITED(status)) &&
387 WEXITSTATUS(status) == APEXIT_CHILDFATAL) {
388 ap_log_error(APLOG_MARK, APLOG_ALERT|APLOG_NOERRNO, 0, ap_server_conf,
389 "Child %ld returned a Fatal error... \n"
390 "Apache is exiting!",
392 exit(APEXIT_CHILDFATAL);
394 if (WIFSIGNALED(status)) {
395 switch (WTERMSIG(status)) {
404 if (WCOREDUMP(status)) {
405 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE,
407 "child pid %ld exit signal %s (%d), "
408 "possible coredump in %s",
409 (long)pid->pid, (WTERMSIG(status) >= NumSIG) ? "" :
410 SYS_SIGLIST[WTERMSIG(status)], WTERMSIG(status),
415 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE,
417 "child pid %ld exit signal %s (%d)",
419 SYS_SIGLIST[WTERMSIG(status)], WTERMSIG(status));
424 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE,
426 "child pid %ld exit signal %d",
427 (long)pid->pid, WTERMSIG(status));
433 static int setup_listeners(server_rec *s)
436 int num_listeners = 0;
437 if (ap_listen_open(s->process, s->port)) {
440 for (lr = ap_listeners; lr; lr = lr->next) {
443 return num_listeners;
446 /*****************************************************************
447 * Here follows a long bunch of generic server bookkeeping stuff...
450 #if defined(TCP_NODELAY) && !defined(MPE) && !defined(TPF)
451 static void sock_disable_nagle(int s)
453 /* The Nagle algorithm says that we should delay sending partial
454 * packets in hopes of getting more data. We don't want to do
455 * this; we are not telnet. There are bad interactions between
456 * persistent connections and Nagle's algorithm that have very severe
457 * performance penalties. (Failing to disable Nagle is not much of a
458 * problem with simple HTTP.)
460 * In spite of these problems, failure here is not a shooting offense.
464 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *) &just_say_no,
466 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf,
467 "setsockopt: (TCP_NODELAY)");
472 #define sock_disable_nagle(s) /* NOOP */
475 int ap_graceful_stop_signalled(void)
477 /* XXX - Does this really work? - Manoj */
481 /*****************************************************************
482 * Child process main loop.
485 static void process_socket(ap_pool_t *p, ap_socket_t *sock, int my_child_num, int my_thread_num)
488 conn_rec *current_conn;
490 long conn_id = my_child_num * HARD_THREAD_LIMIT + my_thread_num;
493 (void) ap_get_os_sock(&csd, sock);
495 sock_disable_nagle(csd);
497 iol = unix_attach_socket(sock);
499 if (errno == EBADF) {
500 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0, NULL,
501 "filedescriptor (%u) larger than FD_SETSIZE (%u) "
502 "found, you probably need to rebuild Apache with a "
503 "larger FD_SETSIZE", csd, FD_SETSIZE);
506 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, NULL,
507 "error attaching to socket");
509 ap_close_socket(sock);
513 (void) ap_update_child_status(my_child_num, my_thread_num,
514 SERVER_BUSY_READ, (request_rec *) NULL);
515 conn_io = ap_bcreate(p, B_RDWR);
516 ap_bpush_iol(conn_io, iol);
518 current_conn = ap_new_apr_connection(p, ap_server_conf, conn_io, sock,
521 ap_process_connection(current_conn);
522 ap_lingering_close(current_conn);
524 /* Sets workers_may_exit if we received a character on the pipe_of_death */
525 static void check_pipe_of_death(void)
527 pthread_mutex_lock(&pipe_of_death_mutex);
528 if (!workers_may_exit) {
533 ret = ap_recv(listensocks[0], &pipe_read_char, &n);
534 if (ap_canonical_error(ret) == APR_EAGAIN) {
535 /* It lost the lottery. It must continue to suffer
536 * through a life of servitude. */
539 /* It won the lottery (or something else is very
540 * wrong). Embrace death with open arms. */
541 workers_may_exit = 1;
544 pthread_mutex_unlock(&pipe_of_death_mutex);
547 static void * worker_thread(void * dummy)
549 proc_info * ti = dummy;
550 int process_slot = ti->pid;
551 int thread_slot = ti->tid;
552 ap_pool_t *tpool = ti->tpool;
553 ap_socket_t *csd = NULL;
554 ap_pool_t *ptrans; /* Pool for per-transaction stuff */
555 ap_socket_t *sd = NULL;
557 int curr_pollfd, last_pollfd = 0;
558 ap_pollfd_t *pollset;
563 ap_create_pool(&ptrans, tpool);
565 pthread_mutex_lock(&worker_thread_count_mutex);
566 worker_thread_count++;
567 pthread_mutex_unlock(&worker_thread_count_mutex);
569 ap_setup_poll(&pollset, num_listensocks+1, tpool);
570 for(n=0 ; n <= num_listensocks ; ++n)
571 ap_add_poll_socket(pollset, listensocks[n], APR_POLLIN);
573 /* TODO: Switch to a system where threads reuse the results from earlier
574 poll calls - manoj */
575 while (!workers_may_exit) {
576 workers_may_exit |= (ap_max_requests_per_child != 0) && (requests_this_child <= 0);
577 if (workers_may_exit) break;
579 (void) ap_update_child_status(process_slot, thread_slot, SERVER_READY,
580 (request_rec *) NULL);
581 pthread_mutex_lock(&thread_accept_mutex);
582 if (workers_may_exit) {
583 pthread_mutex_unlock(&thread_accept_mutex);
586 if ((rv = SAFE_ACCEPT(ap_lock(process_accept_mutex)))
588 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
589 "ap_lock failed. Attempting to shutdown "
590 "process gracefully.");
591 workers_may_exit = 1;
594 while (!workers_may_exit) {
598 ret = ap_poll(pollset, &n, -1);
599 if (ret != APR_SUCCESS) {
600 if (ap_canonical_error(ret) == APR_EINTR) {
604 /* poll() will only return errors in catastrophic
605 * circumstances. Let's try exiting gracefully, for now. */
606 ap_log_error(APLOG_MARK, APLOG_ERR, errno, (const server_rec *)
607 ap_get_server_conf(), "poll: (listen)");
608 workers_may_exit = 1;
611 if (workers_may_exit) break;
613 ap_get_revents(&event, listensocks[0], pollset);
614 if (event & APR_POLLIN) {
615 /* A process got a signal on the shutdown pipe. Check if we're
616 * the lucky process to die. */
617 check_pipe_of_death();
621 if (num_listensocks == 1) {
622 sd = ap_listeners->sd;
626 /* find a listener */
627 curr_pollfd = last_pollfd;
630 if (curr_pollfd > num_listensocks) {
633 /* XXX: Should we check for POLLERR? */
634 ap_get_revents(&event, listensocks[curr_pollfd], pollset);
635 if (event & APR_POLLIN) {
636 last_pollfd = curr_pollfd;
637 sd=listensocks[curr_pollfd];
640 } while (curr_pollfd != last_pollfd);
644 if (!workers_may_exit) {
645 ap_accept(&csd, sd, ptrans);
646 if ((rv = SAFE_ACCEPT(ap_unlock(process_accept_mutex)))
648 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
649 "ap_unlock failed. Attempting to shutdown "
650 "process gracefully.");
651 workers_may_exit = 1;
653 pthread_mutex_unlock(&thread_accept_mutex);
654 process_socket(ptrans, csd, process_slot, thread_slot);
655 requests_this_child--;
658 if ((rv = SAFE_ACCEPT(ap_unlock(process_accept_mutex)))
660 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
661 "ap_unlock failed. Attempting to shutdown "
662 "process gracefully.");
663 workers_may_exit = 1;
665 pthread_mutex_unlock(&thread_accept_mutex);
668 ap_clear_pool(ptrans);
671 ap_destroy_pool(tpool);
672 ap_update_child_status(process_slot, thread_slot, SERVER_DEAD,
673 (request_rec *) NULL);
674 pthread_mutex_lock(&worker_thread_count_mutex);
675 worker_thread_count--;
676 if (worker_thread_count == 0) {
677 /* All the threads have exited, now finish the shutdown process
678 * by signalling the sigwait thread */
679 kill(ap_my_pid, SIGTERM);
681 pthread_mutex_unlock(&worker_thread_count_mutex);
687 static void child_main(int child_num_arg)
692 pthread_attr_t thread_attr;
694 int my_child_num = child_num_arg;
695 proc_info *my_info = NULL;
700 ap_my_pid = getpid();
701 ap_create_pool(&pchild, pconf);
703 /*stuff to do before we switch id's, so we have permissions.*/
704 reopen_scoreboard(pchild);
706 rv = SAFE_ACCEPT(ap_child_init_lock(&process_accept_mutex, lock_fname,
708 if (rv != APR_SUCCESS) {
709 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
710 "Couldn't initialize cross-process lock in child");
711 clean_child_exit(APEXIT_CHILDFATAL);
714 if (unixd_setup_child()) {
715 clean_child_exit(APEXIT_CHILDFATAL);
718 ap_child_init_hook(pchild, ap_server_conf);
720 /*done with init critical section */
722 /* All threads should mask signals out, accoring to sigwait(2) man page */
723 sigfillset(&sig_mask);
725 #ifdef SIGPROCMASK_SETS_THREAD_MASK
726 if (sigprocmask(SIG_SETMASK, &sig_mask, NULL) != 0) {
727 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf, "sigprocmask");
730 if (pthread_sigmask(SIG_SETMASK, &sig_mask, NULL) != 0) {
731 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf, "pthread_sigmask");
735 requests_this_child = ap_max_requests_per_child;
737 /* Set up the pollfd array */
738 listensocks = ap_pcalloc(pchild,
739 sizeof(*listensocks) * (num_listensocks + 1));
740 #if APR_FILES_AS_SOCKETS
741 ap_socket_from_file(&listensocks[0], pipe_of_death_in);
743 for (lr = ap_listeners, i = 1; i <= num_listensocks; lr = lr->next, ++i)
744 listensocks[i]=lr->sd;
746 /* Setup worker threads */
748 worker_thread_count = 0;
749 pthread_mutex_init(&worker_thread_count_mutex, NULL);
750 pthread_mutex_init(&pipe_of_death_mutex, NULL);
751 pthread_attr_init(&thread_attr);
752 #ifdef PTHREAD_ATTR_SETDETACHSTATE_ARG2_ADDR
756 pthread_attr_setdetachstate(&thread_attr, &on);
759 pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
761 for (i=0; i < ap_threads_per_child; i++) {
763 my_info = (proc_info *)malloc(sizeof(proc_info));
764 if (my_info == NULL) {
765 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
766 "malloc: out of memory");
767 clean_child_exit(APEXIT_CHILDFATAL);
769 my_info->pid = my_child_num;
772 ap_create_pool(&my_info->tpool, pchild);
774 /* We are creating threads right now */
775 (void) ap_update_child_status(my_child_num, i, SERVER_STARTING,
776 (request_rec *) NULL);
778 if (pthread_create(&thread, &thread_attr, worker_thread, my_info)) {
779 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
780 "pthread_create: unable to create worker thread");
781 /* In case system resources are maxxed out, we don't want
782 Apache running away with the CPU trying to fork over and
783 over and over again if we exit. */
785 clean_child_exit(APEXIT_CHILDFATAL);
788 worker_thread(my_info);
789 /* The SIGTERM shouldn't let us reach this point, but just in case... */
790 clean_child_exit(APEXIT_OK);
793 /* We let each thread update it's own scoreboard entry. This is done
794 * because it let's us deal with tid better.
798 pthread_attr_destroy(&thread_attr);
800 /* This thread will be the one responsible for handling signals */
801 sigemptyset(&sig_mask);
802 sigaddset(&sig_mask, SIGTERM);
803 sigaddset(&sig_mask, SIGINT);
804 ap_sigwait(&sig_mask, &signal_received);
805 switch (signal_received) {
808 just_die(signal_received);
811 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
812 "received impossible signal: %d", signal_received);
817 static int make_child(server_rec *s, int slot, time_t now)
821 if (slot + 1 > ap_max_daemons_limit) {
822 ap_max_daemons_limit = slot + 1;
827 ap_scoreboard_image->parent[slot].pid = getpid();
831 /* Tag this slot as occupied so that perform_idle_server_maintenance
832 * doesn't try to steal it */
833 (void) ap_update_child_status(slot, 0, SERVER_STARTING, (request_rec *) NULL);
835 if ((pid = fork()) == -1) {
836 ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, "fork: Unable to fork new process");
838 /* fork didn't succeed. Fix the scoreboard or else
839 * it will say SERVER_STARTING forever and ever
841 (void) ap_update_child_status(slot, 0, SERVER_DEAD, (request_rec *) NULL);
843 /* In case system resources are maxxed out, we don't want
844 Apache running away with the CPU trying to fork over and
845 over and over again. */
852 #ifdef AIX_BIND_PROCESSOR
853 /* By default, AIX binds to a single processor. This bit unbinds
854 children which will then bind to another CPU.
856 #include <sys/processor.h>
857 int status = bindprocessor(BINDPROCESS, (int)getpid(),
858 PROCESSOR_CLASS_ANY);
860 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, ap_server_conf,
861 "processor unbind failed %d", status);
864 RAISE_SIGSTOP(MAKE_CHILD);
866 ap_signal(SIGTERM, just_die);
872 ap_scoreboard_image->parent[slot].pid = pid;
876 /* start up a bunch of children */
877 static void startup_children(int number_to_start)
881 for (i = 0; number_to_start && i < ap_daemons_limit; ++i) {
882 if (ap_scoreboard_image->parent[i].pid != 0) {
885 if (make_child(ap_server_conf, i, 0) < 0) {
894 * idle_spawn_rate is the number of children that will be spawned on the
895 * next maintenance cycle if there aren't enough idle servers. It is
896 * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
897 * without the need to spawn.
899 static int idle_spawn_rate = 1;
900 #ifndef MAX_SPAWN_RATE
901 #define MAX_SPAWN_RATE (32)
903 static int hold_off_on_exponential_spawning;
905 static void perform_idle_server_maintenance(void)
908 int idle_thread_count;
912 int free_slots[MAX_SPAWN_RATE];
917 /* initialize the free_list */
920 idle_thread_count = 0;
924 ap_sync_scoreboard_image();
925 for (i = 0; i < ap_daemons_limit; ++i) {
926 /* Initialization to satisfy the compiler. It doesn't know
927 * that ap_threads_per_child is always > 0 */
928 int status = SERVER_DEAD;
929 int any_dying_threads = 0;
930 int all_dead_threads = 1;
931 int idle_thread_addition = 0;
933 if (i >= ap_max_daemons_limit && free_length == idle_spawn_rate)
935 for (j = 0; j < ap_threads_per_child; j++) {
936 ss = &ap_scoreboard_image->servers[i][j];
939 any_dying_threads = any_dying_threads || (status == SERVER_DEAD)
940 || (status == SERVER_GRACEFUL);
941 all_dead_threads = all_dead_threads && (status == SERVER_DEAD);
943 /* We consider a starting server as idle because we started it
944 * at least a cycle ago, and if it still hasn't finished starting
945 * then we're just going to swamp things worse by forking more.
946 * So we hopefully won't need to fork more if we count it.
947 * This depends on the ordering of SERVER_READY and SERVER_STARTING.
949 if (status <= SERVER_READY) {
950 ++idle_thread_addition;
953 if (all_dead_threads && free_length < idle_spawn_rate) {
954 free_slots[free_length] = i;
957 if (!all_dead_threads) {
960 if (!any_dying_threads) {
962 idle_thread_count += idle_thread_addition;
965 ap_max_daemons_limit = last_non_dead + 1;
967 if (idle_thread_count > max_spare_threads) {
968 /* Kill off one child */
969 char char_of_death = '!';
970 if (ap_write(pipe_of_death_out, &char_of_death, &one) != APR_SUCCESS) {
971 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "write pipe_of_death");
975 else if (idle_thread_count < min_spare_threads) {
976 /* terminate the free list */
977 if (free_length == 0) {
978 /* only report this condition once */
979 static int reported = 0;
982 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, ap_server_conf,
983 "server reached MaxClients setting, consider"
984 " raising the MaxClients setting");
991 if (idle_spawn_rate >= 8) {
992 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, ap_server_conf,
993 "server seems busy, (you may need "
994 "to increase StartServers, ThreadsPerChild "
995 "or Min/MaxSparetThreads), "
996 "spawning %d children, there are around %d idle "
997 "threads, and %d total children", idle_spawn_rate,
998 idle_thread_count, total_non_dead);
1000 for (i = 0; i < free_length; ++i) {
1001 make_child(ap_server_conf, free_slots[i], now);
1003 /* the next time around we want to spawn twice as many if this
1004 * wasn't good enough, but not if we've just done a graceful
1006 if (hold_off_on_exponential_spawning) {
1007 --hold_off_on_exponential_spawning;
1009 else if (idle_spawn_rate < MAX_SPAWN_RATE) {
1010 idle_spawn_rate *= 2;
1015 idle_spawn_rate = 1;
1019 static void server_main_loop(int remaining_children_to_start)
1026 while (!restart_pending && !shutdown_pending) {
1027 ap_wait_or_timeout(&status, &pid, pconf);
1029 if (pid.pid != -1) {
1030 process_child_status(&pid, status);
1031 /* non-fatal death... note that it's gone in the scoreboard. */
1032 child_slot = find_child_by_pid(&pid);
1033 if (child_slot >= 0) {
1034 ap_mpmt_pthread_force_reset_connection_status(child_slot);
1035 for (i = 0; i < ap_threads_per_child; i++)
1036 ap_update_child_status(child_slot, i, SERVER_DEAD, (request_rec *) NULL);
1038 if (remaining_children_to_start
1039 && child_slot < ap_daemons_limit) {
1040 /* we're still doing a 1-for-1 replacement of dead
1041 * children with new children
1043 make_child(ap_server_conf, child_slot, time(NULL));
1044 --remaining_children_to_start;
1046 #ifdef APR_HAS_OTHER_CHILD
1048 else if (ap_reap_other_child(&pid, status) == 0) {
1052 else if (is_graceful) {
1053 /* Great, we've probably just lost a slot in the
1054 * scoreboard. Somehow we don't know about this child.
1056 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0,
1058 "long lost child came home! (pid %ld)",
1061 /* Don't perform idle maintenance when a child dies,
1062 * only do it when there's a timeout. Remember only a
1063 * finite number of children can die, and it's pretty
1064 * pathological for a lot to die suddenly.
1068 else if (remaining_children_to_start) {
1069 /* we hit a 1 second timeout in which none of the previous
1070 * generation of children needed to be reaped... so assume
1071 * they're all done, and pick up the slack if any is left.
1073 startup_children(remaining_children_to_start);
1074 remaining_children_to_start = 0;
1075 /* In any event we really shouldn't do the code below because
1076 * few of the servers we just started are in the IDLE state
1077 * yet, so we'd mistakenly create an extra server.
1082 perform_idle_server_maintenance();
1086 int ap_mpm_run(ap_pool_t *_pconf, ap_pool_t *plog, server_rec *s)
1088 int remaining_children_to_start;
1094 if (ap_create_pipe(&pipe_of_death_in, &pipe_of_death_out, pconf) == -1) {
1095 ap_log_error(APLOG_MARK, APLOG_ERR, errno,
1096 (const server_rec*) ap_server_conf,
1097 "pipe: (pipe_of_death)");
1101 if (ap_set_pipe_timeout(pipe_of_death_in, 0) != APR_SUCCESS) {
1102 ap_log_error(APLOG_MARK, APLOG_ERR, errno,
1103 (const server_rec*) ap_server_conf,
1104 "fcntl: O_NONBLOCKing (pipe_of_death)");
1108 if ((num_listensocks = setup_listeners(ap_server_conf)) < 1) {
1109 /* XXX: hey, what's the right way for the mpm to indicate a fatal error? */
1110 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ALERT, 0, s,
1111 "no listening sockets available, shutting down");
1114 ap_log_pid(pconf, ap_pid_fname);
1116 /* Initialize cross-process accept lock */
1117 lock_fname = ap_psprintf(_pconf, "%s.%lu",
1118 ap_server_root_relative(_pconf, lock_fname),
1120 rv = ap_create_lock(&process_accept_mutex, APR_MUTEX, APR_CROSS_PROCESS,
1121 lock_fname, _pconf);
1122 if (rv != APR_SUCCESS) {
1123 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
1124 "Couldn't create cross-process lock");
1130 reinit_scoreboard(pconf);
1134 /* Don't thrash... */
1135 if (max_spare_threads < min_spare_threads + ap_threads_per_child)
1136 max_spare_threads = min_spare_threads + ap_threads_per_child;
1138 /* If we're doing a graceful_restart then we're going to see a lot
1139 * of children exiting immediately when we get into the main loop
1140 * below (because we just sent them SIGWINCH). This happens pretty
1141 * rapidly... and for each one that exits we'll start a new one until
1142 * we reach at least daemons_min_free. But we may be permitted to
1143 * start more than that, so we'll just keep track of how many we're
1144 * supposed to start up without the 1 second penalty between each fork.
1146 remaining_children_to_start = ap_daemons_to_start;
1147 if (remaining_children_to_start > ap_daemons_limit) {
1148 remaining_children_to_start = ap_daemons_limit;
1151 startup_children(remaining_children_to_start);
1152 remaining_children_to_start = 0;
1155 /* give the system some time to recover before kicking into
1156 * exponential mode */
1157 hold_off_on_exponential_spawning = 10;
1160 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1161 "%s configured -- resuming normal operations",
1162 ap_get_server_version());
1163 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, ap_server_conf,
1164 "Server built: %s", ap_get_server_built());
1165 restart_pending = shutdown_pending = 0;
1167 server_main_loop(remaining_children_to_start);
1169 if (shutdown_pending) {
1170 /* Time to gracefully shut down:
1171 * Kill child processes, tell them to call child_exit, etc...
1173 if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
1174 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGTERM");
1176 ap_reclaim_child_processes(1); /* Start with SIGTERM */
1178 /* cleanup pid file on normal shutdown */
1180 const char *pidfile = NULL;
1181 pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1182 if ( pidfile != NULL && unlink(pidfile) == 0)
1183 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0,
1185 "removed PID file %s (pid=%ld)",
1186 pidfile, (long)getpid());
1189 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1190 "caught SIGTERM, shutting down");
1195 /* we've been told to restart */
1196 ap_signal(SIGHUP, SIG_IGN);
1199 /* not worth thinking about */
1203 /* advance to the next generation */
1204 /* XXX: we really need to make sure this new generation number isn't in
1205 * use by any of the children.
1208 ap_scoreboard_image->global.running_generation = ap_my_generation;
1209 update_scoreboard_global();
1213 char char_of_death = '!';
1215 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1216 "SIGWINCH received. Doing graceful restart");
1218 /* give the children the signal to die */
1219 for (i = 0; i < ap_daemons_limit;) {
1220 if (ap_write(pipe_of_death_in, &char_of_death, &one) == -1) {
1221 if (errno == EINTR) continue;
1222 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "write pipe_of_death");
1227 /* This is mostly for debugging... so that we know what is still
1228 * gracefully dealing with existing request.
1231 for (i = 0; i < ap_daemons_limit; ++i) {
1232 for (j = 0; j < ap_threads_per_child; j++) {
1233 if (ap_scoreboard_image->servers[i][j].status != SERVER_DEAD) {
1234 ap_scoreboard_image->servers[i][j].status = SERVER_GRACEFUL;
1240 /* Kill 'em all. Since the child acts the same on the parents SIGTERM
1241 * and a SIGHUP, we may as well use the same signal, because some user
1242 * pthreads are stealing signals from us left and right.
1244 if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
1245 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGTERM");
1247 ap_reclaim_child_processes(1); /* Start with SIGTERM */
1248 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1249 "SIGHUP received. Attempting to restart");
1252 ap_restart_time = time(NULL);
1257 static void mpmt_pthread_pre_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp)
1259 static int restart_num = 0;
1261 one_process = !!getenv("ONE_PROCESS");
1263 /* sigh, want this only the second time around */
1264 if (restart_num++ == 1) {
1270 ap_my_pid = getpid();
1274 ap_listen_pre_config();
1275 ap_daemons_to_start = DEFAULT_START_DAEMON;
1276 min_spare_threads = DEFAULT_MIN_FREE_DAEMON * DEFAULT_THREADS_PER_CHILD;
1277 max_spare_threads = DEFAULT_MAX_FREE_DAEMON * DEFAULT_THREADS_PER_CHILD;
1278 ap_daemons_limit = HARD_SERVER_LIMIT;
1279 ap_threads_per_child = DEFAULT_THREADS_PER_CHILD;
1280 ap_pid_fname = DEFAULT_PIDLOG;
1281 ap_scoreboard_fname = DEFAULT_SCOREBOARD;
1282 lock_fname = DEFAULT_LOCKFILE;
1283 ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1284 ap_extended_status = 0;
1286 ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1289 static void mpmt_pthread_hooks(void)
1294 ap_hook_pre_config(mpmt_pthread_pre_config, NULL, NULL, AP_HOOK_MIDDLE);
1298 static const char *set_pidfile(cmd_parms *cmd, void *dummy, const char *arg)
1300 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1305 if (cmd->server->is_virtual) {
1306 return "PidFile directive not allowed in <VirtualHost>";
1312 static const char *set_scoreboard(cmd_parms *cmd, void *dummy,
1315 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1320 ap_scoreboard_fname = arg;
1324 static const char *set_lockfile(cmd_parms *cmd, void *dummy, const char *arg)
1326 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1335 static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy,
1338 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1343 ap_daemons_to_start = atoi(arg);
1347 static const char *set_min_spare_threads(cmd_parms *cmd, void *dummy,
1350 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1355 min_spare_threads = atoi(arg);
1356 if (min_spare_threads <= 0) {
1357 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1358 "WARNING: detected MinSpareThreads set to non-positive.");
1359 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1360 "Resetting to 1 to avoid almost certain Apache failure.");
1361 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1362 "Please read the documentation.");
1363 min_spare_threads = 1;
1369 static const char *set_max_spare_threads(cmd_parms *cmd, void *dummy,
1372 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1377 max_spare_threads = atoi(arg);
1381 static const char *set_server_limit (cmd_parms *cmd, void *dummy,
1384 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1389 ap_daemons_limit = atoi(arg);
1390 if (ap_daemons_limit > HARD_SERVER_LIMIT) {
1391 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1392 "WARNING: MaxClients of %d exceeds compile time limit "
1393 "of %d servers,", ap_daemons_limit, HARD_SERVER_LIMIT);
1394 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1395 " lowering MaxClients to %d. To increase, please "
1396 "see the", HARD_SERVER_LIMIT);
1397 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1398 " HARD_SERVER_LIMIT define in %s.",
1399 AP_MPM_HARD_LIMITS_FILE);
1400 ap_daemons_limit = HARD_SERVER_LIMIT;
1402 else if (ap_daemons_limit < 1) {
1403 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, "WARNING: Require MaxClients > 0, setting to 1\n");
1404 ap_daemons_limit = 1;
1409 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy,
1412 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1417 ap_threads_per_child = atoi(arg);
1418 if (ap_threads_per_child > HARD_THREAD_LIMIT) {
1419 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1420 "WARNING: ThreadsPerChild of %d exceeds compile time"
1421 "limit of %d threads,", ap_threads_per_child,
1423 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1424 " lowering ThreadsPerChild to %d. To increase, please"
1425 " see the", HARD_THREAD_LIMIT);
1426 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1427 " HARD_THREAD_LIMIT define in %s.",
1428 AP_MPM_HARD_LIMITS_FILE);
1430 else if (ap_threads_per_child < 1) {
1431 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1432 "WARNING: Require ThreadsPerChild > 0, setting to 1");
1433 ap_threads_per_child = 1;
1438 static const char *set_max_requests(cmd_parms *cmd, void *dummy,
1441 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1446 ap_max_requests_per_child = atoi(arg);
1451 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy,
1456 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1461 fname = ap_server_root_relative(cmd->pool, arg);
1462 if ((ap_stat(&finfo, fname, cmd->pool) != APR_SUCCESS) ||
1463 (finfo.filetype != APR_DIR)) {
1464 return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", fname,
1465 " does not exist or is not a directory", NULL);
1467 ap_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
1471 static const command_rec mpmt_pthread_cmds[] = {
1472 UNIX_DAEMON_COMMANDS
1474 AP_INIT_TAKE1("PidFile", set_pidfile, NULL, RSRC_CONF,
1475 "A file for logging the server process ID"),
1476 AP_INIT_TAKE1("ScoreBoardFile", set_scoreboard, NULL, RSRC_CONF,
1477 "A file for Apache to maintain runtime process management information"),
1478 AP_INIT_TAKE1("LockFile", set_lockfile, NULL, RSRC_CONF,
1479 "The lockfile used when Apache needs to lock the accept() call"),
1480 AP_INIT_TAKE1("StartServers", set_daemons_to_start, NULL, RSRC_CONF,
1481 "Number of child processes launched at server startup"),
1482 AP_INIT_TAKE1("MinSpareThreads", set_min_spare_threads, NULL, RSRC_CONF,
1483 "Minimum number of idle children, to handle request spikes"),
1484 AP_INIT_TAKE1("MaxSpareThreads", set_max_spare_threads, NULL, RSRC_CONF,
1485 "Maximum number of idle children"),
1486 AP_INIT_TAKE1("MaxClients", set_server_limit, NULL, RSRC_CONF,
1487 "Maximum number of children alive at the same time"),
1488 AP_INIT_TAKE1("ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF,
1489 "Number of threads each child creates"),
1490 AP_INIT_TAKE1("MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF,
1491 "Maximum number of requests a particular child serves before dying."),
1492 AP_INIT_TAKE1("CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF,
1493 "The location of the directory Apache changes to before dumping core"),
1497 module MODULE_VAR_EXPORT mpm_mpmt_pthread_module = {
1499 NULL, /* hook to run before apache parses args */
1500 NULL, /* create per-directory config structure */
1501 NULL, /* merge per-directory config structures */
1502 NULL, /* create per-server config structure */
1503 NULL, /* merge per-server config structures */
1504 mpmt_pthread_cmds, /* command ap_table_t */
1505 NULL, /* handlers */
1506 mpmt_pthread_hooks /* register_hooks */