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_thread_proc.h"
63 #include "ap_config.h"
65 #include "http_main.h"
67 #include "http_config.h" /* for read_config */
68 #include "http_core.h" /* for get_remote_host */
69 #include "http_connection.h"
72 #include "mpm_common.h"
73 #include "iol_socket.h"
74 #include "ap_listen.h"
75 #include "scoreboard.h"
77 #ifdef HAVE_NETINET_TCP_H
78 #include <netinet/tcp.h>
85 * Actual definitions of config globals
88 int ap_threads_per_child=0; /* Worker threads per child */
89 int ap_max_requests_per_child=0;
90 static char *ap_pid_fname=NULL;
91 API_VAR_EXPORT char *ap_scoreboard_fname=NULL;
92 static int ap_daemons_to_start=0;
93 static int min_spare_threads=0;
94 static int max_spare_threads=0;
95 static int ap_daemons_limit=0;
96 static time_t ap_restart_time=0;
97 API_VAR_EXPORT int ap_extended_status = 0;
98 static int workers_may_exit = 0;
99 static int requests_this_child;
100 static int num_listensocks = 0;
101 static ap_socket_t **listensocks;
103 /* The structure used to pass unique initialization info to each thread */
108 ap_pool_t *tpool; /* "pthread" would be confusing */
112 * The max child slot ever assigned, preserved across restarts. Necessary
113 * to deal with MaxClients changes across SIGWINCH restarts. We use this
114 * value to optimize routines that have to scan the entire scoreboard.
116 int ap_max_daemons_limit = -1;
118 static char ap_coredump_dir[MAX_STRING_LEN];
120 int pipe_of_death[2];
121 static pthread_mutex_t pipe_of_death_mutex;
123 /* *Non*-shared http_main globals... */
125 server_rec *ap_server_conf;
127 /* one_process --- debugging mode variable; can be set from the command line
128 * with the -X flag. If set, this gets you the child_main loop running
129 * in the process which originally started up (no detach, no make_child),
130 * which is a pretty nice debugging environment. (You'll get a SIGHUP
131 * early in standalone_main; just continue through. This is the server
132 * trying to kill off any child processes which it might have lying
133 * around --- Apache doesn't keep track of their pids, it just sends
134 * SIGHUP to the process group, ignoring it in the root process.
135 * Continue through and you'll be fine.).
138 static int one_process = 0;
141 int raise_sigstop_flags;
144 static ap_pool_t *pconf; /* Pool for config stuff */
145 static ap_pool_t *pchild; /* Pool for httpd child stuff */
147 int ap_my_pid; /* Linux getpid() doesn't work except in main thread. Use
149 /* Keep track of the number of worker threads currently active */
150 static int worker_thread_count;
151 static pthread_mutex_t worker_thread_count_mutex;
153 /* Locks for accept serialization */
154 static pthread_mutex_t thread_accept_mutex = PTHREAD_MUTEX_INITIALIZER;
155 static ap_lock_t *process_accept_mutex;
156 static char *lock_fname;
158 #ifdef NO_SERIALIZED_ACCEPT
159 #define SAFE_ACCEPT(stmt) APR_SUCCESS
161 #define SAFE_ACCEPT(stmt) (stmt)
165 /* Global, alas, so http_core can talk to us */
166 enum server_token_type ap_server_tokens = SrvTk_FULL;
168 API_EXPORT(const server_rec *) ap_get_server_conf(void)
170 return (ap_server_conf);
173 API_EXPORT(int) ap_get_max_daemons(void)
175 return ap_max_daemons_limit;
178 /* a clean exit from a child with proper cleanup */
179 static void clean_child_exit(int code) __attribute__ ((noreturn));
180 void clean_child_exit(int code)
183 ap_destroy_pool(pchild);
188 /* handle all varieties of core dumping signals */
189 static void sig_coredump(int sig)
191 chdir(ap_coredump_dir);
192 ap_signal(sig, SIG_DFL);
193 kill(ap_my_pid, sig);
194 /* At this point we've got sig blocked, because we're still inside
195 * the signal handler. When we leave the signal handler it will
196 * be unblocked, and we'll take the signal... and coredump or whatever
197 * is appropriate for this particular Unix. In addition the parent
198 * will see the real signal we received -- whereas if we called
199 * abort() here, the parent would only see SIGABRT.
203 static void just_die(int sig)
208 /*****************************************************************
209 * Connection structures and accounting...
212 /* volatile just in case */
213 static int volatile shutdown_pending;
214 static int volatile restart_pending;
215 static int volatile is_graceful;
216 ap_generation_t volatile ap_my_generation;
219 * ap_start_shutdown() and ap_start_restart(), below, are a first stab at
220 * functions to initiate shutdown or restart without relying on signals.
221 * Previously this was initiated in sig_term() and restart() signal handlers,
222 * but we want to be able to start a shutdown/restart from other sources --
223 * e.g. on Win32, from the service manager. Now the service manager can
224 * call ap_start_shutdown() or ap_start_restart() as appropiate. Note that
225 * these functions can also be called by the child processes, since global
226 * variables are no longer used to pass on the required action to the parent.
228 * These should only be called from the parent process itself, since the
229 * parent process will use the shutdown_pending and restart_pending variables
230 * to determine whether to shutdown or restart. The child process should
231 * call signal_parent() directly to tell the parent to die -- this will
232 * cause neither of those variable to be set, which the parent will
233 * assume means something serious is wrong (which it will be, for the
234 * child to force an exit) and so do an exit anyway.
237 void ap_start_shutdown(void)
239 if (shutdown_pending == 1) {
240 /* Um, is this _probably_ not an error, if the user has
241 * tried to do a shutdown twice quickly, so we won't
242 * worry about reporting it.
246 shutdown_pending = 1;
249 /* do a graceful restart if graceful == 1 */
250 void ap_start_restart(int graceful)
253 if (restart_pending == 1) {
254 /* Probably not an error - don't bother reporting it */
258 is_graceful = graceful;
261 static void sig_term(int sig)
266 static void restart(int sig)
269 ap_start_restart(sig == SIGWINCH);
275 static void set_signals(void)
277 #ifndef NO_USE_SIGACTION
280 sigemptyset(&sa.sa_mask);
284 sa.sa_handler = sig_coredump;
285 #if defined(SA_ONESHOT)
286 sa.sa_flags = SA_ONESHOT;
287 #elif defined(SA_RESETHAND)
288 sa.sa_flags = SA_RESETHAND;
290 if (sigaction(SIGSEGV, &sa, NULL) < 0)
291 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGSEGV)");
293 if (sigaction(SIGBUS, &sa, NULL) < 0)
294 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGBUS)");
297 if (sigaction(SIGABORT, &sa, NULL) < 0)
298 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABORT)");
301 if (sigaction(SIGABRT, &sa, NULL) < 0)
302 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABRT)");
305 if (sigaction(SIGILL, &sa, NULL) < 0)
306 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGILL)");
310 sa.sa_handler = sig_term;
311 if (sigaction(SIGTERM, &sa, NULL) < 0)
312 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGTERM)");
314 if (sigaction(SIGINT, &sa, NULL) < 0)
315 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGINT)");
318 sa.sa_handler = SIG_DFL;
319 if (sigaction(SIGXCPU, &sa, NULL) < 0)
320 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXCPU)");
323 sa.sa_handler = SIG_DFL;
324 if (sigaction(SIGXFSZ, &sa, NULL) < 0)
325 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXFSZ)");
328 sa.sa_handler = SIG_IGN;
329 if (sigaction(SIGPIPE, &sa, NULL) < 0)
330 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGPIPE)");
333 /* we want to ignore HUPs and WINCH while we're busy processing one */
334 sigaddset(&sa.sa_mask, SIGHUP);
335 sigaddset(&sa.sa_mask, SIGWINCH);
336 sa.sa_handler = restart;
337 if (sigaction(SIGHUP, &sa, NULL) < 0)
338 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGHUP)");
339 if (sigaction(SIGWINCH, &sa, NULL) < 0)
340 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGWINCH)");
343 ap_signal(SIGSEGV, sig_coredump);
345 ap_signal(SIGBUS, sig_coredump);
348 ap_signal(SIGABORT, sig_coredump);
349 #endif /* SIGABORT */
351 ap_signal(SIGABRT, sig_coredump);
354 ap_signal(SIGILL, sig_coredump);
357 ap_signal(SIGXCPU, SIG_DFL);
360 ap_signal(SIGXFSZ, SIG_DFL);
364 ap_signal(SIGTERM, sig_term);
366 ap_signal(SIGHUP, restart);
369 ap_signal(SIGWINCH, restart);
370 #endif /* SIGWINCH */
372 ap_signal(SIGPIPE, SIG_IGN);
378 static void process_child_status(ap_proc_t *abs_pid, ap_wait_t status)
381 ap_get_os_proc(&pid, abs_pid);
382 /* Child died... if it died due to a fatal error,
383 * we should simply bail out.
385 if ((WIFEXITED(status)) &&
386 WEXITSTATUS(status) == APEXIT_CHILDFATAL) {
387 ap_log_error(APLOG_MARK, APLOG_ALERT|APLOG_NOERRNO, 0, ap_server_conf,
388 "Child %ld returned a Fatal error... \n"
389 "Apache is exiting!",
391 exit(APEXIT_CHILDFATAL);
393 if (WIFSIGNALED(status)) {
394 switch (WTERMSIG(status)) {
403 if (WCOREDUMP(status)) {
404 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE,
406 "child pid %ld exit signal %s (%d), "
407 "possible coredump in %s",
408 (long)pid, (WTERMSIG(status) >= NumSIG) ? "" :
409 SYS_SIGLIST[WTERMSIG(status)], WTERMSIG(status),
414 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE,
416 "child pid %ld exit signal %s (%d)", (long)pid,
417 SYS_SIGLIST[WTERMSIG(status)], WTERMSIG(status));
422 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE,
424 "child pid %ld exit signal %d",
425 (long)pid, WTERMSIG(status));
431 static int setup_listeners(server_rec *s)
434 int num_listeners = 0;
435 if (ap_listen_open(s->process, s->port)) {
438 for (lr = ap_listeners; lr; lr = lr->next) {
441 return num_listeners;
444 /*****************************************************************
445 * Here follows a long bunch of generic server bookkeeping stuff...
448 #if defined(TCP_NODELAY) && !defined(MPE) && !defined(TPF)
449 static void sock_disable_nagle(int s)
451 /* The Nagle algorithm says that we should delay sending partial
452 * packets in hopes of getting more data. We don't want to do
453 * this; we are not telnet. There are bad interactions between
454 * persistent connections and Nagle's algorithm that have very severe
455 * performance penalties. (Failing to disable Nagle is not much of a
456 * problem with simple HTTP.)
458 * In spite of these problems, failure here is not a shooting offense.
462 if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *) &just_say_no,
464 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf,
465 "setsockopt: (TCP_NODELAY)");
470 #define sock_disable_nagle(s) /* NOOP */
473 int ap_graceful_stop_signalled(void)
475 /* XXX - Does this really work? - Manoj */
479 /*****************************************************************
480 * Child process main loop.
483 static void process_socket(ap_pool_t *p, ap_socket_t *sock, int my_child_num, int my_thread_num)
486 conn_rec *current_conn;
488 long conn_id = my_child_num * HARD_THREAD_LIMIT + my_thread_num;
491 (void) ap_get_os_sock(&csd, sock);
493 sock_disable_nagle(csd);
495 iol = unix_attach_socket(sock);
497 if (errno == EBADF) {
498 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0, NULL,
499 "filedescriptor (%u) larger than FD_SETSIZE (%u) "
500 "found, you probably need to rebuild Apache with a "
501 "larger FD_SETSIZE", csd, FD_SETSIZE);
504 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, NULL,
505 "error attaching to socket");
507 ap_close_socket(sock);
511 (void) ap_update_child_status(my_child_num, my_thread_num,
512 SERVER_BUSY_READ, (request_rec *) NULL);
513 conn_io = ap_bcreate(p, B_RDWR);
514 ap_bpush_iol(conn_io, iol);
516 current_conn = ap_new_apr_connection(p, ap_server_conf, conn_io, sock,
519 ap_process_connection(current_conn);
520 ap_lingering_close(current_conn);
522 /* Sets workers_may_exit if we received a character on the pipe_of_death */
523 static void check_pipe_of_death(void)
525 pthread_mutex_lock(&pipe_of_death_mutex);
526 if (!workers_may_exit) {
531 ret = ap_recv(listensocks[0], &pipe_read_char, &n);
532 if (ap_canonical_error(ret) == APR_EAGAIN) {
533 /* It lost the lottery. It must continue to suffer
534 * through a life of servitude. */
537 /* It won the lottery (or something else is very
538 * wrong). Embrace death with open arms. */
539 workers_may_exit = 1;
542 pthread_mutex_unlock(&pipe_of_death_mutex);
545 static void * worker_thread(void * dummy)
547 proc_info * ti = dummy;
548 int process_slot = ti->pid;
549 int thread_slot = ti->tid;
550 ap_pool_t *tpool = ti->tpool;
551 ap_socket_t *csd = NULL;
552 ap_pool_t *ptrans; /* Pool for per-transaction stuff */
553 ap_socket_t *sd = NULL;
555 int curr_pollfd, last_pollfd = 0;
556 ap_pollfd_t *pollset;
561 ap_create_pool(&ptrans, tpool);
563 pthread_mutex_lock(&worker_thread_count_mutex);
564 worker_thread_count++;
565 pthread_mutex_unlock(&worker_thread_count_mutex);
567 ap_setup_poll(&pollset, num_listensocks+1, tpool);
568 for(n=0 ; n <= num_listensocks ; ++n)
569 ap_add_poll_socket(pollset, listensocks[n], APR_POLLIN);
571 /* TODO: Switch to a system where threads reuse the results from earlier
572 poll calls - manoj */
573 while (!workers_may_exit) {
574 workers_may_exit |= (ap_max_requests_per_child != 0) && (requests_this_child <= 0);
575 if (workers_may_exit) break;
577 (void) ap_update_child_status(process_slot, thread_slot, SERVER_READY,
578 (request_rec *) NULL);
579 pthread_mutex_lock(&thread_accept_mutex);
580 if (workers_may_exit) {
581 pthread_mutex_unlock(&thread_accept_mutex);
584 if ((rv = SAFE_ACCEPT(ap_lock(process_accept_mutex)))
586 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
587 "ap_lock failed. Attempting to shutdown "
588 "process gracefully.");
589 workers_may_exit = 1;
592 while (!workers_may_exit) {
596 ret = ap_poll(pollset, &n, -1);
597 if (ret != APR_SUCCESS) {
598 if (ret == APR_EINTR) {
602 /* poll() will only return errors in catastrophic
603 * circumstances. Let's try exiting gracefully, for now. */
604 ap_log_error(APLOG_MARK, APLOG_ERR, errno, (const server_rec *)
605 ap_get_server_conf(), "poll: (listen)");
606 workers_may_exit = 1;
609 if (workers_may_exit) break;
611 ap_get_revents(&event, listensocks[0], pollset);
612 if (event & APR_POLLIN) {
613 /* A process got a signal on the shutdown pipe. Check if we're
614 * the lucky process to die. */
615 check_pipe_of_death();
619 if (num_listensocks == 1) {
620 sd = ap_listeners->sd;
624 /* find a listener */
625 curr_pollfd = last_pollfd;
628 if (curr_pollfd > num_listensocks) {
631 /* XXX: Should we check for POLLERR? */
632 ap_get_revents(&event, listensocks[curr_pollfd], pollset);
633 if (event & APR_POLLIN) {
634 last_pollfd = curr_pollfd;
635 sd=listensocks[curr_pollfd];
638 } while (curr_pollfd != last_pollfd);
642 if (!workers_may_exit) {
643 ap_accept(&csd, sd, ptrans);
644 if ((rv = SAFE_ACCEPT(ap_unlock(process_accept_mutex)))
646 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
647 "ap_unlock failed. Attempting to shutdown "
648 "process gracefully.");
649 workers_may_exit = 1;
651 pthread_mutex_unlock(&thread_accept_mutex);
652 process_socket(ptrans, csd, process_slot, thread_slot);
653 requests_this_child--;
656 if ((rv = SAFE_ACCEPT(ap_unlock(process_accept_mutex)))
658 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
659 "ap_unlock failed. Attempting to shutdown "
660 "process gracefully.");
661 workers_may_exit = 1;
663 pthread_mutex_unlock(&thread_accept_mutex);
666 ap_clear_pool(ptrans);
669 ap_destroy_pool(tpool);
670 ap_update_child_status(process_slot, thread_slot, SERVER_DEAD,
671 (request_rec *) NULL);
672 pthread_mutex_lock(&worker_thread_count_mutex);
673 worker_thread_count--;
674 if (worker_thread_count == 0) {
675 /* All the threads have exited, now finish the shutdown process
676 * by signalling the sigwait thread */
677 kill(ap_my_pid, SIGTERM);
679 pthread_mutex_unlock(&worker_thread_count_mutex);
685 static void child_main(int child_num_arg)
690 pthread_attr_t thread_attr;
692 int my_child_num = child_num_arg;
693 proc_info *my_info = NULL;
698 ap_my_pid = getpid();
699 ap_create_pool(&pchild, pconf);
701 /*stuff to do before we switch id's, so we have permissions.*/
702 reopen_scoreboard(pchild);
704 rv = SAFE_ACCEPT(ap_child_init_lock(&process_accept_mutex, lock_fname,
706 if (rv != APR_SUCCESS) {
707 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
708 "Couldn't initialize cross-process lock in child");
709 clean_child_exit(APEXIT_CHILDFATAL);
712 if (unixd_setup_child()) {
713 clean_child_exit(APEXIT_CHILDFATAL);
716 ap_child_init_hook(pchild, ap_server_conf);
718 /*done with init critical section */
720 /* All threads should mask signals out, accoring to sigwait(2) man page */
721 sigfillset(&sig_mask);
723 #ifdef SIGPROCMASK_SETS_THREAD_MASK
724 if (sigprocmask(SIG_SETMASK, &sig_mask, NULL) != 0) {
725 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf, "sigprocmask");
728 if (pthread_sigmask(SIG_SETMASK, &sig_mask, NULL) != 0) {
729 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf, "pthread_sigmask");
733 requests_this_child = ap_max_requests_per_child;
735 /* Set up the pollfd array */
736 listensocks = ap_palloc(pchild,
737 sizeof(*listensocks) * (num_listensocks + 1));
738 ap_create_tcp_socket(&listensocks[0], pchild);
739 ap_put_os_sock(&listensocks[0], &pipe_of_death[0], pchild);
740 for (lr = ap_listeners, i = 1; i <= num_listensocks; lr = lr->next, ++i)
741 listensocks[i]=lr->sd;
743 /* Setup worker threads */
745 worker_thread_count = 0;
746 pthread_mutex_init(&worker_thread_count_mutex, NULL);
747 pthread_mutex_init(&pipe_of_death_mutex, NULL);
748 pthread_attr_init(&thread_attr);
749 #ifdef PTHREAD_ATTR_SETDETACHSTATE_ARG2_ADDR
753 pthread_attr_setdetachstate(&thread_attr, &on);
756 pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
758 for (i=0; i < ap_threads_per_child; i++) {
760 my_info = (proc_info *)malloc(sizeof(proc_info));
761 if (my_info == NULL) {
762 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
763 "malloc: out of memory");
764 clean_child_exit(APEXIT_CHILDFATAL);
766 my_info->pid = my_child_num;
769 ap_create_pool(&my_info->tpool, pchild);
771 /* We are creating threads right now */
772 (void) ap_update_child_status(my_child_num, i, SERVER_STARTING,
773 (request_rec *) NULL);
775 if (pthread_create(&thread, &thread_attr, worker_thread, my_info)) {
776 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
777 "pthread_create: unable to create worker thread");
778 /* In case system resources are maxxed out, we don't want
779 Apache running away with the CPU trying to fork over and
780 over and over again if we exit. */
782 clean_child_exit(APEXIT_CHILDFATAL);
785 worker_thread(my_info);
786 /* The SIGTERM shouldn't let us reach this point, but just in case... */
787 clean_child_exit(APEXIT_OK);
790 /* We let each thread update it's own scoreboard entry. This is done
791 * because it let's us deal with tid better.
795 pthread_attr_destroy(&thread_attr);
797 /* This thread will be the one responsible for handling signals */
798 sigemptyset(&sig_mask);
799 sigaddset(&sig_mask, SIGTERM);
800 sigaddset(&sig_mask, SIGINT);
801 ap_sigwait(&sig_mask, &signal_received);
802 switch (signal_received) {
805 just_die(signal_received);
808 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
809 "received impossible signal: %d", signal_received);
814 static int make_child(server_rec *s, int slot, time_t now)
818 if (slot + 1 > ap_max_daemons_limit) {
819 ap_max_daemons_limit = slot + 1;
824 ap_scoreboard_image->parent[slot].pid = getpid();
828 /* Tag this slot as occupied so that perform_idle_server_maintenance
829 * doesn't try to steal it */
830 (void) ap_update_child_status(slot, 0, SERVER_STARTING, (request_rec *) NULL);
832 if ((pid = fork()) == -1) {
833 ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, "fork: Unable to fork new process");
835 /* fork didn't succeed. Fix the scoreboard or else
836 * it will say SERVER_STARTING forever and ever
838 (void) ap_update_child_status(slot, 0, SERVER_DEAD, (request_rec *) NULL);
840 /* In case system resources are maxxed out, we don't want
841 Apache running away with the CPU trying to fork over and
842 over and over again. */
849 #ifdef AIX_BIND_PROCESSOR
850 /* By default, AIX binds to a single processor. This bit unbinds
851 children which will then bind to another CPU.
853 #include <sys/processor.h>
854 int status = bindprocessor(BINDPROCESS, (int)getpid(),
855 PROCESSOR_CLASS_ANY);
857 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, ap_server_conf,
858 "processor unbind failed %d", status);
861 RAISE_SIGSTOP(MAKE_CHILD);
863 ap_signal(SIGTERM, just_die);
869 ap_scoreboard_image->parent[slot].pid = pid;
873 /* start up a bunch of children */
874 static void startup_children(int number_to_start)
878 for (i = 0; number_to_start && i < ap_daemons_limit; ++i) {
879 if (ap_scoreboard_image->parent[i].pid != 0) {
882 if (make_child(ap_server_conf, i, 0) < 0) {
891 * idle_spawn_rate is the number of children that will be spawned on the
892 * next maintenance cycle if there aren't enough idle servers. It is
893 * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
894 * without the need to spawn.
896 static int idle_spawn_rate = 1;
897 #ifndef MAX_SPAWN_RATE
898 #define MAX_SPAWN_RATE (32)
900 static int hold_off_on_exponential_spawning;
902 static void perform_idle_server_maintenance(void)
905 int idle_thread_count;
909 int free_slots[MAX_SPAWN_RATE];
913 /* initialize the free_list */
916 idle_thread_count = 0;
920 ap_sync_scoreboard_image();
921 for (i = 0; i < ap_daemons_limit; ++i) {
922 /* Initialization to satisfy the compiler. It doesn't know
923 * that ap_threads_per_child is always > 0 */
924 int status = SERVER_DEAD;
925 int any_dying_threads = 0;
926 int all_dead_threads = 1;
927 int idle_thread_addition = 0;
929 if (i >= ap_max_daemons_limit && free_length == idle_spawn_rate)
931 for (j = 0; j < ap_threads_per_child; j++) {
932 ss = &ap_scoreboard_image->servers[i][j];
935 any_dying_threads = any_dying_threads || (status == SERVER_DEAD)
936 || (status == SERVER_GRACEFUL);
937 all_dead_threads = all_dead_threads && (status == SERVER_DEAD);
939 /* We consider a starting server as idle because we started it
940 * at least a cycle ago, and if it still hasn't finished starting
941 * then we're just going to swamp things worse by forking more.
942 * So we hopefully won't need to fork more if we count it.
943 * This depends on the ordering of SERVER_READY and SERVER_STARTING.
945 if (status <= SERVER_READY) {
946 ++idle_thread_addition;
949 if (all_dead_threads && free_length < idle_spawn_rate) {
950 free_slots[free_length] = i;
953 if (!all_dead_threads) {
956 if (!any_dying_threads) {
958 idle_thread_count += idle_thread_addition;
961 ap_max_daemons_limit = last_non_dead + 1;
963 if (idle_thread_count > max_spare_threads) {
964 /* Kill off one child */
965 char char_of_death = '!';
966 if (write(pipe_of_death[1], &char_of_death, 1) == -1) {
967 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "write pipe_of_death");
971 else if (idle_thread_count < min_spare_threads) {
972 /* terminate the free list */
973 if (free_length == 0) {
974 /* only report this condition once */
975 static int reported = 0;
978 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, ap_server_conf,
979 "server reached MaxClients setting, consider"
980 " raising the MaxClients setting");
987 if (idle_spawn_rate >= 8) {
988 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, ap_server_conf,
989 "server seems busy, (you may need "
990 "to increase StartServers, ThreadsPerChild "
991 "or Min/MaxSparetThreads), "
992 "spawning %d children, there are around %d idle "
993 "threads, and %d total children", idle_spawn_rate,
994 idle_thread_count, total_non_dead);
996 for (i = 0; i < free_length; ++i) {
997 make_child(ap_server_conf, free_slots[i], now);
999 /* the next time around we want to spawn twice as many if this
1000 * wasn't good enough, but not if we've just done a graceful
1002 if (hold_off_on_exponential_spawning) {
1003 --hold_off_on_exponential_spawning;
1005 else if (idle_spawn_rate < MAX_SPAWN_RATE) {
1006 idle_spawn_rate *= 2;
1011 idle_spawn_rate = 1;
1015 static void server_main_loop(int remaining_children_to_start)
1022 while (!restart_pending && !shutdown_pending) {
1023 /* this is a memory leak, but I'll fix it later. */
1024 pid = ap_wait_or_timeout(&status, pconf);
1027 process_child_status(pid, status);
1028 /* non-fatal death... note that it's gone in the scoreboard. */
1029 child_slot = find_child_by_pid(pid);
1030 if (child_slot >= 0) {
1031 ap_mpmt_pthread_force_reset_connection_status(child_slot);
1032 for (i = 0; i < ap_threads_per_child; i++)
1033 ap_update_child_status(child_slot, i, SERVER_DEAD, (request_rec *) NULL);
1035 if (remaining_children_to_start
1036 && child_slot < ap_daemons_limit) {
1037 /* we're still doing a 1-for-1 replacement of dead
1038 * children with new children
1040 make_child(ap_server_conf, child_slot, time(NULL));
1041 --remaining_children_to_start;
1043 #ifdef APR_HAS_OTHER_CHILD
1045 else if (ap_reap_other_child(pid, status) == 0) {
1049 else if (is_graceful) {
1050 /* Great, we've probably just lost a slot in the
1051 * scoreboard. Somehow we don't know about this child.
1053 ap_os_proc_t actual_pid;
1055 ap_get_os_proc(&actual_pid, pid);
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;
1093 if (pipe(pipe_of_death) == -1) {
1094 ap_log_error(APLOG_MARK, APLOG_ERR, errno,
1095 (const server_rec*) ap_server_conf,
1096 "pipe: (pipe_of_death)");
1100 if (fcntl(pipe_of_death[0], F_SETFL, O_NONBLOCK) == -1) {
1101 ap_log_error(APLOG_MARK, APLOG_ERR, errno,
1102 (const server_rec*) ap_server_conf,
1103 "fcntl: O_NONBLOCKing (pipe_of_death)");
1107 if ((num_listensocks = setup_listeners(ap_server_conf)) < 1) {
1108 /* XXX: hey, what's the right way for the mpm to indicate a fatal error? */
1109 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ALERT, 0, s,
1110 "no listening sockets available, shutting down");
1113 ap_log_pid(pconf, ap_pid_fname);
1115 /* Initialize cross-process accept lock */
1116 lock_fname = ap_psprintf(_pconf, "%s.%lu",
1117 ap_server_root_relative(_pconf, lock_fname),
1119 rv = ap_create_lock(&process_accept_mutex, APR_MUTEX, APR_CROSS_PROCESS,
1120 lock_fname, _pconf);
1121 if (rv != APR_SUCCESS) {
1122 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
1123 "Couldn't create cross-process lock");
1129 reinit_scoreboard(pconf);
1133 /* Don't thrash... */
1134 if (max_spare_threads < min_spare_threads + ap_threads_per_child)
1135 max_spare_threads = min_spare_threads + ap_threads_per_child;
1137 /* If we're doing a graceful_restart then we're going to see a lot
1138 * of children exiting immediately when we get into the main loop
1139 * below (because we just sent them SIGWINCH). This happens pretty
1140 * rapidly... and for each one that exits we'll start a new one until
1141 * we reach at least daemons_min_free. But we may be permitted to
1142 * start more than that, so we'll just keep track of how many we're
1143 * supposed to start up without the 1 second penalty between each fork.
1145 remaining_children_to_start = ap_daemons_to_start;
1146 if (remaining_children_to_start > ap_daemons_limit) {
1147 remaining_children_to_start = ap_daemons_limit;
1150 startup_children(remaining_children_to_start);
1151 remaining_children_to_start = 0;
1154 /* give the system some time to recover before kicking into
1155 * exponential mode */
1156 hold_off_on_exponential_spawning = 10;
1159 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1160 "%s configured -- resuming normal operations",
1161 ap_get_server_version());
1162 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, ap_server_conf,
1163 "Server built: %s", ap_get_server_built());
1164 restart_pending = shutdown_pending = 0;
1166 server_main_loop(remaining_children_to_start);
1168 if (shutdown_pending) {
1169 /* Time to gracefully shut down:
1170 * Kill child processes, tell them to call child_exit, etc...
1172 if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
1173 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGTERM");
1175 ap_reclaim_child_processes(1); /* Start with SIGTERM */
1177 /* cleanup pid file on normal shutdown */
1179 const char *pidfile = NULL;
1180 pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1181 if ( pidfile != NULL && unlink(pidfile) == 0)
1182 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0,
1184 "removed PID file %s (pid=%ld)",
1185 pidfile, (long)getpid());
1188 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1189 "caught SIGTERM, shutting down");
1194 /* we've been told to restart */
1195 ap_signal(SIGHUP, SIG_IGN);
1198 /* not worth thinking about */
1202 /* advance to the next generation */
1203 /* XXX: we really need to make sure this new generation number isn't in
1204 * use by any of the children.
1207 ap_scoreboard_image->global.running_generation = ap_my_generation;
1208 update_scoreboard_global();
1212 char char_of_death = '!';
1214 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1215 "SIGWINCH received. Doing graceful restart");
1217 /* give the children the signal to die */
1218 for (i = 0; i < ap_daemons_limit;) {
1219 if (write(pipe_of_death[1], &char_of_death, 1) == -1) {
1220 if (errno == EINTR) continue;
1221 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "write pipe_of_death");
1226 /* This is mostly for debugging... so that we know what is still
1227 * gracefully dealing with existing request.
1230 for (i = 0; i < ap_daemons_limit; ++i) {
1231 for (j = 0; j < ap_threads_per_child; j++) {
1232 if (ap_scoreboard_image->servers[i][j].status != SERVER_DEAD) {
1233 ap_scoreboard_image->servers[i][j].status = SERVER_GRACEFUL;
1239 /* Kill 'em all. Since the child acts the same on the parents SIGTERM
1240 * and a SIGHUP, we may as well use the same signal, because some user
1241 * pthreads are stealing signals from us left and right.
1243 if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
1244 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGTERM");
1246 ap_reclaim_child_processes(1); /* Start with SIGTERM */
1247 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1248 "SIGHUP received. Attempting to restart");
1251 ap_restart_time = time(NULL);
1256 static void mpmt_pthread_pre_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp)
1258 static int restart_num = 0;
1260 one_process = !!getenv("ONE_PROCESS");
1262 /* sigh, want this only the second time around */
1263 if (restart_num++ == 1) {
1269 ap_my_pid = getpid();
1273 ap_listen_pre_config();
1274 ap_daemons_to_start = DEFAULT_START_DAEMON;
1275 min_spare_threads = DEFAULT_MIN_FREE_DAEMON * DEFAULT_THREADS_PER_CHILD;
1276 max_spare_threads = DEFAULT_MAX_FREE_DAEMON * DEFAULT_THREADS_PER_CHILD;
1277 ap_daemons_limit = HARD_SERVER_LIMIT;
1278 ap_threads_per_child = DEFAULT_THREADS_PER_CHILD;
1279 ap_pid_fname = DEFAULT_PIDLOG;
1280 ap_scoreboard_fname = DEFAULT_SCOREBOARD;
1281 lock_fname = DEFAULT_LOCKFILE;
1282 ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1283 ap_extended_status = 0;
1285 ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1288 static void mpmt_pthread_hooks(void)
1295 static const char *set_pidfile(cmd_parms *cmd, void *dummy, char *arg)
1297 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1302 if (cmd->server->is_virtual) {
1303 return "PidFile directive not allowed in <VirtualHost>";
1309 static const char *set_scoreboard(cmd_parms *cmd, void *dummy, char *arg)
1311 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1316 ap_scoreboard_fname = arg;
1320 static const char *set_lockfile(cmd_parms *cmd, void *dummy, char *arg)
1322 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1331 static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy, char *arg)
1333 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1338 ap_daemons_to_start = atoi(arg);
1342 static const char *set_min_spare_threads(cmd_parms *cmd, void *dummy, char *arg)
1344 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1349 min_spare_threads = atoi(arg);
1350 if (min_spare_threads <= 0) {
1351 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1352 "WARNING: detected MinSpareThreads set to non-positive.");
1353 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1354 "Resetting to 1 to avoid almost certain Apache failure.");
1355 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1356 "Please read the documentation.");
1357 min_spare_threads = 1;
1363 static const char *set_max_spare_threads(cmd_parms *cmd, void *dummy, char *arg)
1365 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1370 max_spare_threads = atoi(arg);
1374 static const char *set_server_limit (cmd_parms *cmd, void *dummy, char *arg)
1376 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1381 ap_daemons_limit = atoi(arg);
1382 if (ap_daemons_limit > HARD_SERVER_LIMIT) {
1383 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1384 "WARNING: MaxClients of %d exceeds compile time limit "
1385 "of %d servers,", ap_daemons_limit, HARD_SERVER_LIMIT);
1386 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1387 " lowering MaxClients to %d. To increase, please "
1388 "see the", HARD_SERVER_LIMIT);
1389 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1390 " HARD_SERVER_LIMIT define in src/include/httpd.h.");
1391 ap_daemons_limit = HARD_SERVER_LIMIT;
1393 else if (ap_daemons_limit < 1) {
1394 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, "WARNING: Require MaxClients > 0, setting to 1\n");
1395 ap_daemons_limit = 1;
1400 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy, char *arg)
1402 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1407 ap_threads_per_child = atoi(arg);
1408 if (ap_threads_per_child > HARD_THREAD_LIMIT) {
1409 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1410 "WARNING: ThreadsPerChild of %d exceeds compile time"
1411 "limit of %d threads,", ap_threads_per_child,
1413 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1414 " lowering ThreadsPerChild to %d. To increase, please"
1415 "see the", HARD_THREAD_LIMIT);
1416 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1417 " HARD_THREAD_LIMIT define in src/include/httpd.h.");
1419 else if (ap_threads_per_child < 1) {
1420 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1421 "WARNING: Require ThreadsPerChild > 0, setting to 1");
1422 ap_threads_per_child = 1;
1427 static const char *set_max_requests(cmd_parms *cmd, void *dummy, char *arg)
1429 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1434 ap_max_requests_per_child = atoi(arg);
1439 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy, char *arg)
1443 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1448 fname = ap_server_root_relative(cmd->pool, arg);
1449 if ((stat(fname, &finfo) == -1) || !S_ISDIR(finfo.st_mode)) {
1450 return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", fname,
1451 " does not exist or is not a directory", NULL);
1453 ap_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
1457 static const command_rec mpmt_pthread_cmds[] = {
1458 UNIX_DAEMON_COMMANDS
1460 { "PidFile", set_pidfile, NULL, RSRC_CONF, TAKE1,
1461 "A file for logging the server process ID"},
1462 { "ScoreBoardFile", set_scoreboard, NULL, RSRC_CONF, TAKE1,
1463 "A file for Apache to maintain runtime process management information"},
1464 { "LockFile", set_lockfile, NULL, RSRC_CONF, TAKE1,
1465 "The lockfile used when Apache needs to lock the accept() call"},
1466 { "StartServers", set_daemons_to_start, NULL, RSRC_CONF, TAKE1,
1467 "Number of child processes launched at server startup" },
1468 { "MinSpareThreads", set_min_spare_threads, NULL, RSRC_CONF, TAKE1,
1469 "Minimum number of idle children, to handle request spikes" },
1470 { "MaxSpareThreads", set_max_spare_threads, NULL, RSRC_CONF, TAKE1,
1471 "Maximum number of idle children" },
1472 { "MaxClients", set_server_limit, NULL, RSRC_CONF, TAKE1,
1473 "Maximum number of children alive at the same time" },
1474 { "ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, TAKE1,
1475 "Number of threads each child creates" },
1476 { "MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF, TAKE1,
1477 "Maximum number of requests a particular child serves before dying." },
1478 { "CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF, TAKE1,
1479 "The location of the directory Apache changes to before dumping core" },
1483 module MODULE_VAR_EXPORT mpm_mpmt_pthread_module = {
1485 mpmt_pthread_pre_config, /* run hook before the configuration is read */
1486 NULL, /* create per-directory config structure */
1487 NULL, /* merge per-directory config structures */
1488 NULL, /* create per-server config structure */
1489 NULL, /* merge per-server config structures */
1490 mpmt_pthread_cmds, /* command ap_table_t */
1491 NULL, /* handlers */
1492 mpmt_pthread_hooks /* register_hooks */