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 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 unsigned int ap_my_pid; /* Linux getpid() doesn't work except in main
155 thread. Use this instead */
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(int) ap_get_max_daemons(void)
173 return ap_max_daemons_limit;
176 /* a clean exit from a child with proper cleanup */
177 static void clean_child_exit(int code) __attribute__ ((noreturn));
178 void clean_child_exit(int code)
181 ap_destroy_pool(pchild);
186 /* handle all varieties of core dumping signals */
187 static void sig_coredump(int sig)
189 chdir(ap_coredump_dir);
190 ap_signal(sig, SIG_DFL);
191 kill(ap_my_pid, sig);
192 /* At this point we've got sig blocked, because we're still inside
193 * the signal handler. When we leave the signal handler it will
194 * be unblocked, and we'll take the signal... and coredump or whatever
195 * is appropriate for this particular Unix. In addition the parent
196 * will see the real signal we received -- whereas if we called
197 * abort() here, the parent would only see SIGABRT.
201 static void just_die(int sig)
206 /*****************************************************************
207 * Connection structures and accounting...
210 /* volatile just in case */
211 static int volatile shutdown_pending;
212 static int volatile restart_pending;
213 static int volatile is_graceful;
214 ap_generation_t volatile ap_my_generation;
217 * ap_start_shutdown() and ap_start_restart(), below, are a first stab at
218 * functions to initiate shutdown or restart without relying on signals.
219 * Previously this was initiated in sig_term() and restart() signal handlers,
220 * but we want to be able to start a shutdown/restart from other sources --
221 * e.g. on Win32, from the service manager. Now the service manager can
222 * call ap_start_shutdown() or ap_start_restart() as appropiate. Note that
223 * these functions can also be called by the child processes, since global
224 * variables are no longer used to pass on the required action to the parent.
226 * These should only be called from the parent process itself, since the
227 * parent process will use the shutdown_pending and restart_pending variables
228 * to determine whether to shutdown or restart. The child process should
229 * call signal_parent() directly to tell the parent to die -- this will
230 * cause neither of those variable to be set, which the parent will
231 * assume means something serious is wrong (which it will be, for the
232 * child to force an exit) and so do an exit anyway.
235 void ap_start_shutdown(void)
237 if (shutdown_pending == 1) {
238 /* Um, is this _probably_ not an error, if the user has
239 * tried to do a shutdown twice quickly, so we won't
240 * worry about reporting it.
244 shutdown_pending = 1;
247 /* do a graceful restart if graceful == 1 */
248 void ap_start_restart(int graceful)
251 if (restart_pending == 1) {
252 /* Probably not an error - don't bother reporting it */
256 is_graceful = graceful;
259 static void sig_term(int sig)
264 static void restart(int sig)
267 ap_start_restart(sig == SIGWINCH);
273 static void set_signals(void)
275 #ifndef NO_USE_SIGACTION
278 sigemptyset(&sa.sa_mask);
282 sa.sa_handler = sig_coredump;
283 #if defined(SA_ONESHOT)
284 sa.sa_flags = SA_ONESHOT;
285 #elif defined(SA_RESETHAND)
286 sa.sa_flags = SA_RESETHAND;
288 if (sigaction(SIGSEGV, &sa, NULL) < 0)
289 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGSEGV)");
291 if (sigaction(SIGBUS, &sa, NULL) < 0)
292 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGBUS)");
295 if (sigaction(SIGABORT, &sa, NULL) < 0)
296 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABORT)");
299 if (sigaction(SIGABRT, &sa, NULL) < 0)
300 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABRT)");
303 if (sigaction(SIGILL, &sa, NULL) < 0)
304 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGILL)");
308 sa.sa_handler = sig_term;
309 if (sigaction(SIGTERM, &sa, NULL) < 0)
310 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGTERM)");
312 if (sigaction(SIGINT, &sa, NULL) < 0)
313 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGINT)");
316 sa.sa_handler = SIG_DFL;
317 if (sigaction(SIGXCPU, &sa, NULL) < 0)
318 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXCPU)");
321 sa.sa_handler = SIG_DFL;
322 if (sigaction(SIGXFSZ, &sa, NULL) < 0)
323 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXFSZ)");
326 sa.sa_handler = SIG_IGN;
327 if (sigaction(SIGPIPE, &sa, NULL) < 0)
328 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGPIPE)");
331 /* we want to ignore HUPs and WINCH while we're busy processing one */
332 sigaddset(&sa.sa_mask, SIGHUP);
333 sigaddset(&sa.sa_mask, SIGWINCH);
334 sa.sa_handler = restart;
335 if (sigaction(SIGHUP, &sa, NULL) < 0)
336 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGHUP)");
337 if (sigaction(SIGWINCH, &sa, NULL) < 0)
338 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGWINCH)");
341 ap_signal(SIGSEGV, sig_coredump);
343 ap_signal(SIGBUS, sig_coredump);
346 ap_signal(SIGABORT, sig_coredump);
347 #endif /* SIGABORT */
349 ap_signal(SIGABRT, sig_coredump);
352 ap_signal(SIGILL, sig_coredump);
355 ap_signal(SIGXCPU, SIG_DFL);
358 ap_signal(SIGXFSZ, SIG_DFL);
362 ap_signal(SIGTERM, sig_term);
364 ap_signal(SIGHUP, restart);
367 ap_signal(SIGWINCH, restart);
368 #endif /* SIGWINCH */
370 ap_signal(SIGPIPE, SIG_IGN);
376 /*****************************************************************
377 * Here follows a long bunch of generic server bookkeeping stuff...
380 int ap_graceful_stop_signalled(void)
382 /* XXX - Does this really work? - Manoj */
386 /*****************************************************************
387 * Child process main loop.
390 static void process_socket(ap_pool_t *p, ap_socket_t *sock, int my_child_num, int my_thread_num)
393 conn_rec *current_conn;
395 long conn_id = my_child_num * HARD_THREAD_LIMIT + my_thread_num;
398 (void) ap_get_os_sock(&csd, sock);
400 if (csd >= FD_SETSIZE) {
401 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0, NULL,
402 "new file descriptor %d is too large; you probably need "
403 "to rebuild Apache with a larger FD_SETSIZE "
406 ap_close_socket(sock);
410 ap_sock_disable_nagle(csd);
412 iol = ap_iol_attach_socket(p, sock);
414 (void) ap_update_child_status(my_child_num, my_thread_num,
415 SERVER_BUSY_READ, (request_rec *) NULL);
416 conn_io = ap_bcreate(p, B_RDWR);
417 ap_bpush_iol(conn_io, iol);
419 current_conn = ap_new_apr_connection(p, ap_server_conf, conn_io, sock,
422 ap_process_connection(current_conn);
423 ap_lingering_close(current_conn);
425 /* Sets workers_may_exit if we received a character on the pipe_of_death */
426 static void check_pipe_of_death(void)
428 pthread_mutex_lock(&pipe_of_death_mutex);
429 if (!workers_may_exit) {
434 ret = ap_recv(listensocks[0], &pipe_read_char, &n);
435 if (ap_canonical_error(ret) == APR_EAGAIN) {
436 /* It lost the lottery. It must continue to suffer
437 * through a life of servitude. */
440 /* It won the lottery (or something else is very
441 * wrong). Embrace death with open arms. */
442 workers_may_exit = 1;
445 pthread_mutex_unlock(&pipe_of_death_mutex);
448 static void * worker_thread(void * dummy)
450 proc_info * ti = dummy;
451 int process_slot = ti->pid;
452 int thread_slot = ti->tid;
453 ap_pool_t *tpool = ti->tpool;
454 ap_socket_t *csd = NULL;
455 ap_pool_t *ptrans; /* Pool for per-transaction stuff */
456 ap_socket_t *sd = NULL;
458 int curr_pollfd, last_pollfd = 0;
459 ap_pollfd_t *pollset;
464 ap_create_pool(&ptrans, tpool);
466 pthread_mutex_lock(&worker_thread_count_mutex);
467 worker_thread_count++;
468 pthread_mutex_unlock(&worker_thread_count_mutex);
470 ap_setup_poll(&pollset, num_listensocks+1, tpool);
471 for(n=0 ; n <= num_listensocks ; ++n)
472 ap_add_poll_socket(pollset, listensocks[n], APR_POLLIN);
474 /* TODO: Switch to a system where threads reuse the results from earlier
475 poll calls - manoj */
476 while (!workers_may_exit) {
477 workers_may_exit |= (ap_max_requests_per_child != 0) && (requests_this_child <= 0);
478 if (workers_may_exit) break;
480 (void) ap_update_child_status(process_slot, thread_slot, SERVER_READY,
481 (request_rec *) NULL);
482 pthread_mutex_lock(&thread_accept_mutex);
483 if (workers_may_exit) {
484 pthread_mutex_unlock(&thread_accept_mutex);
487 if ((rv = SAFE_ACCEPT(ap_lock(process_accept_mutex)))
489 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
490 "ap_lock failed. Attempting to shutdown "
491 "process gracefully.");
492 workers_may_exit = 1;
495 while (!workers_may_exit) {
499 ret = ap_poll(pollset, &n, -1);
500 if (ret != APR_SUCCESS) {
501 if (ap_canonical_error(ret) == APR_EINTR) {
505 /* ap_poll() will only return errors in catastrophic
506 * circumstances. Let's try exiting gracefully, for now. */
507 ap_log_error(APLOG_MARK, APLOG_ERR, ret, (const server_rec *)
508 ap_server_conf, "ap_poll: (listen)");
509 workers_may_exit = 1;
512 if (workers_may_exit) break;
514 ap_get_revents(&event, listensocks[0], pollset);
515 if (event & APR_POLLIN) {
516 /* A process got a signal on the shutdown pipe. Check if we're
517 * the lucky process to die. */
518 check_pipe_of_death();
522 if (num_listensocks == 1) {
523 sd = ap_listeners->sd;
527 /* find a listener */
528 curr_pollfd = last_pollfd;
531 if (curr_pollfd > num_listensocks) {
534 /* XXX: Should we check for POLLERR? */
535 ap_get_revents(&event, listensocks[curr_pollfd], pollset);
536 if (event & APR_POLLIN) {
537 last_pollfd = curr_pollfd;
538 sd=listensocks[curr_pollfd];
541 } while (curr_pollfd != last_pollfd);
545 if (!workers_may_exit) {
546 if ((rv = ap_accept(&csd, sd, ptrans)) != APR_SUCCESS) {
547 ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf,
550 if ((rv = SAFE_ACCEPT(ap_unlock(process_accept_mutex)))
552 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
553 "ap_unlock failed. Attempting to shutdown "
554 "process gracefully.");
555 workers_may_exit = 1;
557 pthread_mutex_unlock(&thread_accept_mutex);
558 process_socket(ptrans, csd, process_slot, thread_slot);
559 requests_this_child--;
562 if ((rv = SAFE_ACCEPT(ap_unlock(process_accept_mutex)))
564 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
565 "ap_unlock failed. Attempting to shutdown "
566 "process gracefully.");
567 workers_may_exit = 1;
569 pthread_mutex_unlock(&thread_accept_mutex);
572 ap_clear_pool(ptrans);
575 ap_destroy_pool(tpool);
576 ap_update_child_status(process_slot, thread_slot, SERVER_DEAD,
577 (request_rec *) NULL);
578 pthread_mutex_lock(&worker_thread_count_mutex);
579 worker_thread_count--;
580 if (worker_thread_count == 0) {
581 /* All the threads have exited, now finish the shutdown process
582 * by signalling the sigwait thread */
583 kill(ap_my_pid, SIGTERM);
585 pthread_mutex_unlock(&worker_thread_count_mutex);
591 static void child_main(int child_num_arg)
596 pthread_attr_t thread_attr;
598 int my_child_num = child_num_arg;
599 proc_info *my_info = NULL;
604 ap_my_pid = getpid();
605 ap_create_pool(&pchild, pconf);
607 /*stuff to do before we switch id's, so we have permissions.*/
608 reopen_scoreboard(pchild);
610 rv = SAFE_ACCEPT(ap_child_init_lock(&process_accept_mutex, lock_fname,
612 if (rv != APR_SUCCESS) {
613 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
614 "Couldn't initialize cross-process lock in child");
615 clean_child_exit(APEXIT_CHILDFATAL);
618 if (unixd_setup_child()) {
619 clean_child_exit(APEXIT_CHILDFATAL);
622 ap_child_init_hook(pchild, ap_server_conf);
624 /*done with init critical section */
626 /* All threads should mask signals out, accoring to sigwait(2) man page */
627 sigfillset(&sig_mask);
629 #ifdef SIGPROCMASK_SETS_THREAD_MASK
630 if (sigprocmask(SIG_SETMASK, &sig_mask, NULL) != 0) {
631 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf, "sigprocmask");
634 if (pthread_sigmask(SIG_SETMASK, &sig_mask, NULL) != 0) {
635 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf, "pthread_sigmask");
639 requests_this_child = ap_max_requests_per_child;
641 /* Set up the pollfd array */
642 listensocks = ap_pcalloc(pchild,
643 sizeof(*listensocks) * (num_listensocks + 1));
644 #if APR_FILES_AS_SOCKETS
645 ap_socket_from_file(&listensocks[0], pipe_of_death_in);
647 for (lr = ap_listeners, i = 1; i <= num_listensocks; lr = lr->next, ++i)
648 listensocks[i]=lr->sd;
650 /* Setup worker threads */
652 worker_thread_count = 0;
653 pthread_mutex_init(&worker_thread_count_mutex, NULL);
654 pthread_mutex_init(&pipe_of_death_mutex, NULL);
655 pthread_attr_init(&thread_attr);
656 #ifdef PTHREAD_ATTR_SETDETACHSTATE_ARG2_ADDR
660 pthread_attr_setdetachstate(&thread_attr, &on);
663 pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
665 for (i=0; i < ap_threads_per_child; i++) {
667 my_info = (proc_info *)malloc(sizeof(proc_info));
668 if (my_info == NULL) {
669 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
670 "malloc: out of memory");
671 clean_child_exit(APEXIT_CHILDFATAL);
673 my_info->pid = my_child_num;
676 ap_create_pool(&my_info->tpool, pchild);
678 /* We are creating threads right now */
679 (void) ap_update_child_status(my_child_num, i, SERVER_STARTING,
680 (request_rec *) NULL);
682 if (pthread_create(&thread, &thread_attr, worker_thread, my_info)) {
683 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
684 "pthread_create: unable to create worker thread");
685 /* In case system resources are maxxed out, we don't want
686 Apache running away with the CPU trying to fork over and
687 over and over again if we exit. */
689 clean_child_exit(APEXIT_CHILDFATAL);
692 worker_thread(my_info);
693 /* The SIGTERM shouldn't let us reach this point, but just in case... */
694 clean_child_exit(APEXIT_OK);
697 /* We let each thread update it's own scoreboard entry. This is done
698 * because it let's us deal with tid better.
702 pthread_attr_destroy(&thread_attr);
704 /* This thread will be the one responsible for handling signals */
705 sigemptyset(&sig_mask);
706 sigaddset(&sig_mask, SIGTERM);
707 sigaddset(&sig_mask, SIGINT);
708 ap_sigwait(&sig_mask, &signal_received);
709 switch (signal_received) {
712 just_die(signal_received);
715 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
716 "received impossible signal: %d", signal_received);
721 static int make_child(server_rec *s, int slot, time_t now)
725 if (slot + 1 > ap_max_daemons_limit) {
726 ap_max_daemons_limit = slot + 1;
731 ap_scoreboard_image->parent[slot].pid = getpid();
735 /* Tag this slot as occupied so that perform_idle_server_maintenance
736 * doesn't try to steal it */
737 (void) ap_update_child_status(slot, 0, SERVER_STARTING, (request_rec *) NULL);
739 if ((pid = fork()) == -1) {
740 ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, "fork: Unable to fork new process");
742 /* fork didn't succeed. Fix the scoreboard or else
743 * it will say SERVER_STARTING forever and ever
745 (void) ap_update_child_status(slot, 0, SERVER_DEAD, (request_rec *) NULL);
747 /* In case system resources are maxxed out, we don't want
748 Apache running away with the CPU trying to fork over and
749 over and over again. */
756 #ifdef AIX_BIND_PROCESSOR
757 /* By default, AIX binds to a single processor. This bit unbinds
758 children which will then bind to another CPU.
760 #include <sys/processor.h>
761 int status = bindprocessor(BINDPROCESS, (int)getpid(),
762 PROCESSOR_CLASS_ANY);
764 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, ap_server_conf,
765 "processor unbind failed %d", status);
768 RAISE_SIGSTOP(MAKE_CHILD);
770 ap_signal(SIGTERM, just_die);
776 ap_scoreboard_image->parent[slot].pid = pid;
780 /* start up a bunch of children */
781 static void startup_children(int number_to_start)
785 for (i = 0; number_to_start && i < ap_daemons_limit; ++i) {
786 if (ap_scoreboard_image->parent[i].pid != 0) {
789 if (make_child(ap_server_conf, i, 0) < 0) {
798 * idle_spawn_rate is the number of children that will be spawned on the
799 * next maintenance cycle if there aren't enough idle servers. It is
800 * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
801 * without the need to spawn.
803 static int idle_spawn_rate = 1;
804 #ifndef MAX_SPAWN_RATE
805 #define MAX_SPAWN_RATE (32)
807 static int hold_off_on_exponential_spawning;
809 static void perform_idle_server_maintenance(void)
812 int idle_thread_count;
816 int free_slots[MAX_SPAWN_RATE];
822 /* initialize the free_list */
825 idle_thread_count = 0;
829 ap_sync_scoreboard_image();
830 for (i = 0; i < ap_daemons_limit; ++i) {
831 /* Initialization to satisfy the compiler. It doesn't know
832 * that ap_threads_per_child is always > 0 */
833 int status = SERVER_DEAD;
834 int any_dying_threads = 0;
835 int all_dead_threads = 1;
836 int idle_thread_addition = 0;
838 if (i >= ap_max_daemons_limit && free_length == idle_spawn_rate)
840 for (j = 0; j < ap_threads_per_child; j++) {
841 ss = &ap_scoreboard_image->servers[i][j];
844 any_dying_threads = any_dying_threads || (status == SERVER_DEAD)
845 || (status == SERVER_GRACEFUL);
846 all_dead_threads = all_dead_threads && (status == SERVER_DEAD);
848 /* We consider a starting server as idle because we started it
849 * at least a cycle ago, and if it still hasn't finished starting
850 * then we're just going to swamp things worse by forking more.
851 * So we hopefully won't need to fork more if we count it.
852 * This depends on the ordering of SERVER_READY and SERVER_STARTING.
854 if (status <= SERVER_READY) {
855 ++idle_thread_addition;
858 if (all_dead_threads && free_length < idle_spawn_rate) {
859 free_slots[free_length] = i;
862 if (!all_dead_threads) {
865 if (!any_dying_threads) {
867 idle_thread_count += idle_thread_addition;
870 ap_max_daemons_limit = last_non_dead + 1;
872 if (idle_thread_count > max_spare_threads) {
873 /* Kill off one child */
874 char char_of_death = '!';
875 if ((rv = ap_write(pipe_of_death_out, &char_of_death, &one)) != APR_SUCCESS) {
876 ap_log_error(APLOG_MARK, APLOG_WARNING, rv, ap_server_conf, "write pipe_of_death");
880 else if (idle_thread_count < min_spare_threads) {
881 /* terminate the free list */
882 if (free_length == 0) {
883 /* only report this condition once */
884 static int reported = 0;
887 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, ap_server_conf,
888 "server reached MaxClients setting, consider"
889 " raising the MaxClients setting");
896 if (idle_spawn_rate >= 8) {
897 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, ap_server_conf,
898 "server seems busy, (you may need "
899 "to increase StartServers, ThreadsPerChild "
900 "or Min/MaxSparetThreads), "
901 "spawning %d children, there are around %d idle "
902 "threads, and %d total children", idle_spawn_rate,
903 idle_thread_count, total_non_dead);
905 for (i = 0; i < free_length; ++i) {
906 make_child(ap_server_conf, free_slots[i], now);
908 /* the next time around we want to spawn twice as many if this
909 * wasn't good enough, but not if we've just done a graceful
911 if (hold_off_on_exponential_spawning) {
912 --hold_off_on_exponential_spawning;
914 else if (idle_spawn_rate < MAX_SPAWN_RATE) {
915 idle_spawn_rate *= 2;
924 static void server_main_loop(int remaining_children_to_start)
931 while (!restart_pending && !shutdown_pending) {
932 ap_wait_or_timeout(&status, &pid, pconf);
935 ap_process_child_status(&pid, status);
936 /* non-fatal death... note that it's gone in the scoreboard. */
937 child_slot = find_child_by_pid(&pid);
938 if (child_slot >= 0) {
939 ap_mpmt_pthread_force_reset_connection_status(child_slot);
940 for (i = 0; i < ap_threads_per_child; i++)
941 ap_update_child_status(child_slot, i, SERVER_DEAD, (request_rec *) NULL);
943 if (remaining_children_to_start
944 && child_slot < ap_daemons_limit) {
945 /* we're still doing a 1-for-1 replacement of dead
946 * children with new children
948 make_child(ap_server_conf, child_slot, time(NULL));
949 --remaining_children_to_start;
951 #if APR_HAS_OTHER_CHILD
953 else if (ap_reap_other_child(&pid, status) == 0) {
957 else if (is_graceful) {
958 /* Great, we've probably just lost a slot in the
959 * scoreboard. Somehow we don't know about this child.
961 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0,
963 "long lost child came home! (pid %ld)",
966 /* Don't perform idle maintenance when a child dies,
967 * only do it when there's a timeout. Remember only a
968 * finite number of children can die, and it's pretty
969 * pathological for a lot to die suddenly.
973 else if (remaining_children_to_start) {
974 /* we hit a 1 second timeout in which none of the previous
975 * generation of children needed to be reaped... so assume
976 * they're all done, and pick up the slack if any is left.
978 startup_children(remaining_children_to_start);
979 remaining_children_to_start = 0;
980 /* In any event we really shouldn't do the code below because
981 * few of the servers we just started are in the IDLE state
982 * yet, so we'd mistakenly create an extra server.
987 perform_idle_server_maintenance();
991 int ap_mpm_run(ap_pool_t *_pconf, ap_pool_t *plog, server_rec *s)
993 int remaining_children_to_start;
999 rv = ap_create_pipe(&pipe_of_death_in, &pipe_of_death_out, pconf);
1000 if (rv != APR_SUCCESS) {
1001 ap_log_error(APLOG_MARK, APLOG_ERR, rv,
1002 (const server_rec*) ap_server_conf,
1003 "ap_create_pipe (pipe_of_death)");
1007 if ((rv = ap_set_pipe_timeout(pipe_of_death_in, 0)) != APR_SUCCESS) {
1008 ap_log_error(APLOG_MARK, APLOG_ERR, rv,
1009 (const server_rec*) ap_server_conf,
1010 "ap_set_pipe_timeout (pipe_of_death)");
1014 if ((num_listensocks = ap_setup_listeners(ap_server_conf)) < 1) {
1015 /* XXX: hey, what's the right way for the mpm to indicate a fatal error? */
1016 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ALERT, 0, s,
1017 "no listening sockets available, shutting down");
1020 ap_log_pid(pconf, ap_pid_fname);
1022 /* Initialize cross-process accept lock */
1023 lock_fname = ap_psprintf(_pconf, "%s.%u",
1024 ap_server_root_relative(_pconf, lock_fname),
1026 rv = ap_create_lock(&process_accept_mutex, APR_MUTEX, APR_CROSS_PROCESS,
1027 lock_fname, _pconf);
1028 if (rv != APR_SUCCESS) {
1029 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
1030 "Couldn't create cross-process lock");
1036 reinit_scoreboard(pconf);
1040 /* Don't thrash... */
1041 if (max_spare_threads < min_spare_threads + ap_threads_per_child)
1042 max_spare_threads = min_spare_threads + ap_threads_per_child;
1044 /* If we're doing a graceful_restart then we're going to see a lot
1045 * of children exiting immediately when we get into the main loop
1046 * below (because we just sent them SIGWINCH). This happens pretty
1047 * rapidly... and for each one that exits we'll start a new one until
1048 * we reach at least daemons_min_free. But we may be permitted to
1049 * start more than that, so we'll just keep track of how many we're
1050 * supposed to start up without the 1 second penalty between each fork.
1052 remaining_children_to_start = ap_daemons_to_start;
1053 if (remaining_children_to_start > ap_daemons_limit) {
1054 remaining_children_to_start = ap_daemons_limit;
1057 startup_children(remaining_children_to_start);
1058 remaining_children_to_start = 0;
1061 /* give the system some time to recover before kicking into
1062 * exponential mode */
1063 hold_off_on_exponential_spawning = 10;
1066 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1067 "%s configured -- resuming normal operations",
1068 ap_get_server_version());
1069 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, ap_server_conf,
1070 "Server built: %s", ap_get_server_built());
1071 restart_pending = shutdown_pending = 0;
1073 server_main_loop(remaining_children_to_start);
1075 if (shutdown_pending) {
1076 /* Time to gracefully shut down:
1077 * Kill child processes, tell them to call child_exit, etc...
1079 if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
1080 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGTERM");
1082 ap_reclaim_child_processes(1); /* Start with SIGTERM */
1084 /* cleanup pid file on normal shutdown */
1086 const char *pidfile = NULL;
1087 pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1088 if ( pidfile != NULL && unlink(pidfile) == 0)
1089 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0,
1091 "removed PID file %s (pid=%ld)",
1092 pidfile, (long)getpid());
1095 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1096 "caught SIGTERM, shutting down");
1101 /* we've been told to restart */
1102 ap_signal(SIGHUP, SIG_IGN);
1105 /* not worth thinking about */
1109 /* advance to the next generation */
1110 /* XXX: we really need to make sure this new generation number isn't in
1111 * use by any of the children.
1114 ap_scoreboard_image->global.running_generation = ap_my_generation;
1115 update_scoreboard_global();
1119 char char_of_death = '!';
1121 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1122 "SIGWINCH received. Doing graceful restart");
1124 /* give the children the signal to die */
1125 for (i = 0; i < ap_daemons_limit;) {
1126 if ((rv = ap_write(pipe_of_death_in, &char_of_death, &one)) != APR_SUCCESS) {
1127 if (ap_canonical_error(rv) == APR_EINTR) continue;
1128 ap_log_error(APLOG_MARK, APLOG_WARNING, rv, ap_server_conf, "write pipe_of_death");
1133 /* This is mostly for debugging... so that we know what is still
1134 * gracefully dealing with existing request.
1137 for (i = 0; i < ap_daemons_limit; ++i) {
1138 for (j = 0; j < ap_threads_per_child; j++) {
1139 if (ap_scoreboard_image->servers[i][j].status != SERVER_DEAD) {
1140 ap_scoreboard_image->servers[i][j].status = SERVER_GRACEFUL;
1146 /* Kill 'em all. Since the child acts the same on the parents SIGTERM
1147 * and a SIGHUP, we may as well use the same signal, because some user
1148 * pthreads are stealing signals from us left and right.
1150 if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
1151 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGTERM");
1153 ap_reclaim_child_processes(1); /* Start with SIGTERM */
1154 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1155 "SIGHUP received. Attempting to restart");
1158 ap_restart_time = time(NULL);
1163 static void mpmt_pthread_pre_config(ap_pool_t *pconf, ap_pool_t *plog, ap_pool_t *ptemp)
1165 static int restart_num = 0;
1167 one_process = !!getenv("ONE_PROCESS");
1169 /* sigh, want this only the second time around */
1170 if (restart_num++ == 1) {
1176 ap_my_pid = getpid();
1180 ap_listen_pre_config();
1181 ap_daemons_to_start = DEFAULT_START_DAEMON;
1182 min_spare_threads = DEFAULT_MIN_FREE_DAEMON * DEFAULT_THREADS_PER_CHILD;
1183 max_spare_threads = DEFAULT_MAX_FREE_DAEMON * DEFAULT_THREADS_PER_CHILD;
1184 ap_daemons_limit = HARD_SERVER_LIMIT;
1185 ap_threads_per_child = DEFAULT_THREADS_PER_CHILD;
1186 ap_pid_fname = DEFAULT_PIDLOG;
1187 ap_scoreboard_fname = DEFAULT_SCOREBOARD;
1188 lock_fname = DEFAULT_LOCKFILE;
1189 ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1190 ap_extended_status = 0;
1192 ap_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1195 static void mpmt_pthread_hooks(void)
1200 ap_hook_pre_config(mpmt_pthread_pre_config, NULL, NULL, AP_HOOK_MIDDLE);
1204 static const char *set_pidfile(cmd_parms *cmd, void *dummy, const char *arg)
1206 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1211 if (cmd->server->is_virtual) {
1212 return "PidFile directive not allowed in <VirtualHost>";
1218 static const char *set_scoreboard(cmd_parms *cmd, void *dummy,
1221 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1226 ap_scoreboard_fname = arg;
1230 static const char *set_lockfile(cmd_parms *cmd, void *dummy, const char *arg)
1232 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1241 static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy,
1244 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1249 ap_daemons_to_start = atoi(arg);
1253 static const char *set_min_spare_threads(cmd_parms *cmd, void *dummy,
1256 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1261 min_spare_threads = atoi(arg);
1262 if (min_spare_threads <= 0) {
1263 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1264 "WARNING: detected MinSpareThreads set to non-positive.");
1265 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1266 "Resetting to 1 to avoid almost certain Apache failure.");
1267 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1268 "Please read the documentation.");
1269 min_spare_threads = 1;
1275 static const char *set_max_spare_threads(cmd_parms *cmd, void *dummy,
1278 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1283 max_spare_threads = atoi(arg);
1287 static const char *set_server_limit (cmd_parms *cmd, void *dummy,
1290 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1295 ap_daemons_limit = atoi(arg);
1296 if (ap_daemons_limit > HARD_SERVER_LIMIT) {
1297 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1298 "WARNING: MaxClients of %d exceeds compile time limit "
1299 "of %d servers,", ap_daemons_limit, HARD_SERVER_LIMIT);
1300 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1301 " lowering MaxClients to %d. To increase, please "
1302 "see the", HARD_SERVER_LIMIT);
1303 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1304 " HARD_SERVER_LIMIT define in %s.",
1305 AP_MPM_HARD_LIMITS_FILE);
1306 ap_daemons_limit = HARD_SERVER_LIMIT;
1308 else if (ap_daemons_limit < 1) {
1309 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, "WARNING: Require MaxClients > 0, setting to 1\n");
1310 ap_daemons_limit = 1;
1315 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy,
1318 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1323 ap_threads_per_child = atoi(arg);
1324 if (ap_threads_per_child > HARD_THREAD_LIMIT) {
1325 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1326 "WARNING: ThreadsPerChild of %d exceeds compile time"
1327 "limit of %d threads,", ap_threads_per_child,
1329 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1330 " lowering ThreadsPerChild to %d. To increase, please"
1331 " see the", HARD_THREAD_LIMIT);
1332 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1333 " HARD_THREAD_LIMIT define in %s.",
1334 AP_MPM_HARD_LIMITS_FILE);
1336 else if (ap_threads_per_child < 1) {
1337 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1338 "WARNING: Require ThreadsPerChild > 0, setting to 1");
1339 ap_threads_per_child = 1;
1344 static const char *set_max_requests(cmd_parms *cmd, void *dummy,
1347 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1352 ap_max_requests_per_child = atoi(arg);
1357 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy,
1362 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1367 fname = ap_server_root_relative(cmd->pool, arg);
1368 if ((ap_stat(&finfo, fname, cmd->pool) != APR_SUCCESS) ||
1369 (finfo.filetype != APR_DIR)) {
1370 return ap_pstrcat(cmd->pool, "CoreDumpDirectory ", fname,
1371 " does not exist or is not a directory", NULL);
1373 ap_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
1377 static const command_rec mpmt_pthread_cmds[] = {
1378 UNIX_DAEMON_COMMANDS
1380 AP_INIT_TAKE1("PidFile", set_pidfile, NULL, RSRC_CONF,
1381 "A file for logging the server process ID"),
1382 AP_INIT_TAKE1("ScoreBoardFile", set_scoreboard, NULL, RSRC_CONF,
1383 "A file for Apache to maintain runtime process management information"),
1384 AP_INIT_TAKE1("LockFile", set_lockfile, NULL, RSRC_CONF,
1385 "The lockfile used when Apache needs to lock the accept() call"),
1386 AP_INIT_TAKE1("StartServers", set_daemons_to_start, NULL, RSRC_CONF,
1387 "Number of child processes launched at server startup"),
1388 AP_INIT_TAKE1("MinSpareThreads", set_min_spare_threads, NULL, RSRC_CONF,
1389 "Minimum number of idle children, to handle request spikes"),
1390 AP_INIT_TAKE1("MaxSpareThreads", set_max_spare_threads, NULL, RSRC_CONF,
1391 "Maximum number of idle children"),
1392 AP_INIT_TAKE1("MaxClients", set_server_limit, NULL, RSRC_CONF,
1393 "Maximum number of children alive at the same time"),
1394 AP_INIT_TAKE1("ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF,
1395 "Number of threads each child creates"),
1396 AP_INIT_TAKE1("MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF,
1397 "Maximum number of requests a particular child serves before dying."),
1398 AP_INIT_TAKE1("CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF,
1399 "The location of the directory Apache changes to before dumping core"),
1403 module MODULE_VAR_EXPORT mpm_mpmt_pthread_module = {
1405 NULL, /* hook to run before apache parses args */
1406 NULL, /* create per-directory config structure */
1407 NULL, /* merge per-directory config structures */
1408 NULL, /* create per-server config structure */
1409 NULL, /* merge per-server config structures */
1410 mpmt_pthread_cmds, /* command ap_table_t */
1411 NULL, /* handlers */
1412 mpmt_pthread_hooks /* register_hooks */