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_strings.h"
63 #include "apr_file_io.h"
64 #include "apr_thread_proc.h"
65 #include "ap_config.h"
67 #include "http_main.h"
69 #include "http_config.h" /* for read_config */
70 #include "http_core.h" /* for get_remote_host */
71 #include "http_connection.h"
74 #include "mpm_common.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 static int ap_daemons_to_start=0;
98 static int min_spare_threads=0;
99 static int max_spare_threads=0;
100 static int ap_daemons_limit=0;
101 static int workers_may_exit = 0;
102 static int requests_this_child;
103 static int num_listensocks = 0;
104 static apr_socket_t **listensocks;
106 /* The structure used to pass unique initialization info to each thread */
111 apr_pool_t *tpool; /* "pthread" would be confusing */
115 * The max child slot ever assigned, preserved across restarts. Necessary
116 * to deal with MaxClients changes across SIGWINCH restarts. We use this
117 * value to optimize routines that have to scan the entire scoreboard.
119 int ap_max_daemons_limit = -1;
121 char ap_coredump_dir[MAX_STRING_LEN];
123 static apr_file_t *pipe_of_death_in = NULL;
124 static apr_file_t *pipe_of_death_out = NULL;
125 static pthread_mutex_t pipe_of_death_mutex;
127 /* *Non*-shared http_main globals... */
129 server_rec *ap_server_conf;
131 /* one_process --- debugging mode variable; can be set from the command line
132 * with the -X flag. If set, this gets you the child_main loop running
133 * in the process which originally started up (no detach, no make_child),
134 * which is a pretty nice debugging environment. (You'll get a SIGHUP
135 * early in standalone_main; just continue through. This is the server
136 * trying to kill off any child processes which it might have lying
137 * around --- Apache doesn't keep track of their pids, it just sends
138 * SIGHUP to the process group, ignoring it in the root process.
139 * Continue through and you'll be fine.).
142 static int one_process = 0;
145 int raise_sigstop_flags;
148 static apr_pool_t *pconf; /* Pool for config stuff */
149 static apr_pool_t *pchild; /* Pool for httpd child stuff */
151 unsigned int ap_my_pid; /* Linux getpid() doesn't work except in main
152 thread. Use this instead */
153 /* Keep track of the number of worker threads currently active */
154 static int worker_thread_count;
155 static pthread_mutex_t worker_thread_count_mutex;
157 /* Locks for accept serialization */
158 static apr_lock_t *accept_mutex;
159 static const char *lock_fname;
161 #ifdef NO_SERIALIZED_ACCEPT
162 #define SAFE_ACCEPT(stmt) APR_SUCCESS
164 #define SAFE_ACCEPT(stmt) (stmt)
167 AP_DECLARE(int) ap_get_max_daemons(void)
169 return ap_max_daemons_limit;
172 /* a clean exit from a child with proper cleanup */
173 static void clean_child_exit(int code) __attribute__ ((noreturn));
174 void clean_child_exit(int code)
177 apr_pool_destroy(pchild);
182 /* handle all varieties of core dumping signals */
183 static void sig_coredump(int sig)
185 chdir(ap_coredump_dir);
186 apr_signal(sig, SIG_DFL);
187 kill(ap_my_pid, sig);
188 /* At this point we've got sig blocked, because we're still inside
189 * the signal handler. When we leave the signal handler it will
190 * be unblocked, and we'll take the signal... and coredump or whatever
191 * is appropriate for this particular Unix. In addition the parent
192 * will see the real signal we received -- whereas if we called
193 * abort() here, the parent would only see SIGABRT.
197 static void just_die(int sig)
202 /*****************************************************************
203 * Connection structures and accounting...
206 /* volatile just in case */
207 static int volatile shutdown_pending;
208 static int volatile restart_pending;
209 static int volatile is_graceful;
210 ap_generation_t volatile ap_my_generation;
213 * ap_start_shutdown() and ap_start_restart(), below, are a first stab at
214 * functions to initiate shutdown or restart without relying on signals.
215 * Previously this was initiated in sig_term() and restart() signal handlers,
216 * but we want to be able to start a shutdown/restart from other sources --
217 * e.g. on Win32, from the service manager. Now the service manager can
218 * call ap_start_shutdown() or ap_start_restart() as appropiate. Note that
219 * these functions can also be called by the child processes, since global
220 * variables are no longer used to pass on the required action to the parent.
222 * These should only be called from the parent process itself, since the
223 * parent process will use the shutdown_pending and restart_pending variables
224 * to determine whether to shutdown or restart. The child process should
225 * call signal_parent() directly to tell the parent to die -- this will
226 * cause neither of those variable to be set, which the parent will
227 * assume means something serious is wrong (which it will be, for the
228 * child to force an exit) and so do an exit anyway.
231 static void ap_start_shutdown(void)
233 if (shutdown_pending == 1) {
234 /* Um, is this _probably_ not an error, if the user has
235 * tried to do a shutdown twice quickly, so we won't
236 * worry about reporting it.
240 shutdown_pending = 1;
243 /* do a graceful restart if graceful == 1 */
244 static void ap_start_restart(int graceful)
247 if (restart_pending == 1) {
248 /* Probably not an error - don't bother reporting it */
252 is_graceful = graceful;
254 apr_pool_cleanup_kill(pconf, NULL, ap_cleanup_scoreboard);
258 static void sig_term(int sig)
263 static void restart(int sig)
266 ap_start_restart(sig == SIGWINCH);
272 static void set_signals(void)
274 #ifndef NO_USE_SIGACTION
277 sigemptyset(&sa.sa_mask);
281 sa.sa_handler = sig_coredump;
282 #if defined(SA_ONESHOT)
283 sa.sa_flags = SA_ONESHOT;
284 #elif defined(SA_RESETHAND)
285 sa.sa_flags = SA_RESETHAND;
287 if (sigaction(SIGSEGV, &sa, NULL) < 0)
288 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGSEGV)");
290 if (sigaction(SIGBUS, &sa, NULL) < 0)
291 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGBUS)");
294 if (sigaction(SIGABORT, &sa, NULL) < 0)
295 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABORT)");
298 if (sigaction(SIGABRT, &sa, NULL) < 0)
299 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABRT)");
302 if (sigaction(SIGILL, &sa, NULL) < 0)
303 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGILL)");
307 sa.sa_handler = sig_term;
308 if (sigaction(SIGTERM, &sa, NULL) < 0)
309 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGTERM)");
311 if (sigaction(SIGINT, &sa, NULL) < 0)
312 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGINT)");
315 sa.sa_handler = SIG_DFL;
316 if (sigaction(SIGXCPU, &sa, NULL) < 0)
317 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXCPU)");
320 sa.sa_handler = SIG_DFL;
321 if (sigaction(SIGXFSZ, &sa, NULL) < 0)
322 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXFSZ)");
325 sa.sa_handler = SIG_IGN;
326 if (sigaction(SIGPIPE, &sa, NULL) < 0)
327 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGPIPE)");
330 /* we want to ignore HUPs and WINCH while we're busy processing one */
331 sigaddset(&sa.sa_mask, SIGHUP);
332 sigaddset(&sa.sa_mask, SIGWINCH);
333 sa.sa_handler = restart;
334 if (sigaction(SIGHUP, &sa, NULL) < 0)
335 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGHUP)");
336 if (sigaction(SIGWINCH, &sa, NULL) < 0)
337 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGWINCH)");
340 apr_signal(SIGSEGV, sig_coredump);
342 apr_signal(SIGBUS, sig_coredump);
345 apr_signal(SIGABORT, sig_coredump);
346 #endif /* SIGABORT */
348 apr_signal(SIGABRT, sig_coredump);
351 apr_signal(SIGILL, sig_coredump);
354 apr_signal(SIGXCPU, SIG_DFL);
357 apr_signal(SIGXFSZ, SIG_DFL);
361 apr_signal(SIGTERM, sig_term);
363 apr_signal(SIGHUP, restart);
366 apr_signal(SIGWINCH, restart);
367 #endif /* SIGWINCH */
369 apr_signal(SIGPIPE, SIG_IGN);
375 /*****************************************************************
376 * Here follows a long bunch of generic server bookkeeping stuff...
379 int ap_graceful_stop_signalled(void)
381 /* XXX - Does this really work? - Manoj */
385 /*****************************************************************
386 * Child process main loop.
389 static void process_socket(apr_pool_t *p, apr_socket_t *sock, int my_child_num, int my_thread_num)
391 conn_rec *current_conn;
392 long conn_id = AP_ID_FROM_CHILD_THREAD(my_child_num, my_thread_num);
395 (void) apr_os_sock_get(&csd, sock);
397 if (csd >= FD_SETSIZE) {
398 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0, NULL,
399 "new file descriptor %d is too large; you probably need "
400 "to rebuild Apache with a larger FD_SETSIZE "
403 apr_socket_close(sock);
407 ap_sock_disable_nagle(sock);
409 (void) ap_update_child_status(my_child_num, my_thread_num,
410 SERVER_BUSY_READ, (request_rec *) NULL);
412 current_conn = ap_new_connection(p, ap_server_conf, sock, conn_id);
414 ap_process_connection(current_conn);
415 ap_lingering_close(current_conn);
418 /* Sets workers_may_exit if we received a character on the pipe_of_death */
419 static void check_pipe_of_death(void)
421 pthread_mutex_lock(&pipe_of_death_mutex);
422 if (!workers_may_exit) {
427 ret = apr_recv(listensocks[0], &pipe_read_char, &n);
428 if (APR_STATUS_IS_EAGAIN(ret)) {
429 /* It lost the lottery. It must continue to suffer
430 * through a life of servitude. */
433 /* It won the lottery (or something else is very
434 * wrong). Embrace death with open arms. */
435 workers_may_exit = 1;
438 pthread_mutex_unlock(&pipe_of_death_mutex);
441 static void * worker_thread(void * dummy)
443 proc_info * ti = dummy;
444 int process_slot = ti->pid;
445 int thread_slot = ti->tid;
446 apr_pool_t *tpool = ti->tpool;
447 apr_socket_t *csd = NULL;
448 apr_pool_t *ptrans; /* Pool for per-transaction stuff */
449 apr_socket_t *sd = NULL;
451 int curr_pollfd, last_pollfd = 0;
452 apr_pollfd_t *pollset;
457 apr_pool_create(&ptrans, tpool);
459 pthread_mutex_lock(&worker_thread_count_mutex);
460 worker_thread_count++;
461 pthread_mutex_unlock(&worker_thread_count_mutex);
463 apr_poll_setup(&pollset, num_listensocks+1, tpool);
464 for(n=0 ; n <= num_listensocks ; ++n)
465 apr_poll_socket_add(pollset, listensocks[n], APR_POLLIN);
467 /* TODO: Switch to a system where threads reuse the results from earlier
468 poll calls - manoj */
470 workers_may_exit |= (ap_max_requests_per_child != 0) && (requests_this_child <= 0);
471 if (workers_may_exit) break;
473 (void) ap_update_child_status(process_slot, thread_slot, SERVER_READY,
474 (request_rec *) NULL);
475 if ((rv = SAFE_ACCEPT(apr_lock_aquire(accept_mutex)))
477 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
478 "apr_lock_aquire failed. Attempting to shutdown "
479 "process gracefully.");
480 workers_may_exit = 1;
483 while (!workers_may_exit) {
487 ret = apr_poll(pollset, &n, -1);
488 if (ret != APR_SUCCESS) {
489 if (APR_STATUS_IS_EINTR(ret)) {
493 /* apr_poll() will only return errors in catastrophic
494 * circumstances. Let's try exiting gracefully, for now. */
495 ap_log_error(APLOG_MARK, APLOG_ERR, ret, (const server_rec *)
496 ap_server_conf, "apr_poll: (listen)");
497 workers_may_exit = 1;
500 if (workers_may_exit) break;
502 apr_poll_revents_get(&event, listensocks[0], pollset);
503 if (event & APR_POLLIN) {
504 /* A process got a signal on the shutdown pipe. Check if we're
505 * the lucky process to die. */
506 check_pipe_of_death();
510 if (num_listensocks == 1) {
511 sd = ap_listeners->sd;
515 /* find a listener */
516 curr_pollfd = last_pollfd;
519 if (curr_pollfd > num_listensocks) {
522 /* XXX: Should we check for POLLERR? */
523 apr_poll_revents_get(&event, listensocks[curr_pollfd], pollset);
524 if (event & APR_POLLIN) {
525 last_pollfd = curr_pollfd;
526 sd=listensocks[curr_pollfd];
529 } while (curr_pollfd != last_pollfd);
533 if (!workers_may_exit) {
534 if ((rv = apr_accept(&csd, sd, ptrans)) != APR_SUCCESS) {
536 ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf,
539 if ((rv = SAFE_ACCEPT(apr_lock_release(accept_mutex)))
541 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
542 "apr_lock_release failed. Attempting to shutdown "
543 "process gracefully.");
544 workers_may_exit = 1;
547 process_socket(ptrans, csd, process_slot, thread_slot);
548 requests_this_child--;
552 if ((rv = SAFE_ACCEPT(apr_lock_release(accept_mutex)))
554 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
555 "apr_lock_release failed. Attempting to shutdown "
556 "process gracefully.");
557 workers_may_exit = 1;
561 apr_clear_pool(ptrans);
564 apr_pool_destroy(tpool);
565 ap_update_child_status(process_slot, thread_slot, SERVER_DEAD,
566 (request_rec *) NULL);
567 pthread_mutex_lock(&worker_thread_count_mutex);
568 worker_thread_count--;
569 if (worker_thread_count == 0) {
570 /* All the threads have exited, now finish the shutdown process
571 * by signalling the sigwait thread */
572 kill(ap_my_pid, SIGTERM);
574 pthread_mutex_unlock(&worker_thread_count_mutex);
580 static void child_main(int child_num_arg)
585 pthread_attr_t thread_attr;
587 int my_child_num = child_num_arg;
588 proc_info *my_info = NULL;
593 ap_my_pid = getpid();
594 apr_pool_create(&pchild, pconf);
596 /*stuff to do before we switch id's, so we have permissions.*/
597 reopen_scoreboard(pchild);
599 rv = SAFE_ACCEPT(apr_lock_child_init(&accept_mutex, lock_fname,
601 if (rv != APR_SUCCESS) {
602 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
603 "Couldn't initialize cross-process lock in child");
604 clean_child_exit(APEXIT_CHILDFATAL);
607 if (unixd_setup_child()) {
608 clean_child_exit(APEXIT_CHILDFATAL);
611 ap_child_init_hook(pchild, ap_server_conf);
613 /*done with init critical section */
615 /* All threads should mask signals out, accoring to sigwait(2) man page */
616 sigfillset(&sig_mask);
618 #ifdef SIGPROCMASK_SETS_THREAD_MASK
619 if (sigprocmask(SIG_SETMASK, &sig_mask, NULL) != 0) {
620 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf, "sigprocmask");
623 if ((rv = pthread_sigmask(SIG_SETMASK, &sig_mask, NULL)) != 0) {
624 #ifdef PTHREAD_SETS_ERRNO
627 ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf, "pthread_sigmask");
631 requests_this_child = ap_max_requests_per_child;
633 /* Set up the pollfd array */
634 listensocks = apr_pcalloc(pchild,
635 sizeof(*listensocks) * (num_listensocks + 1));
636 #if APR_FILES_AS_SOCKETS
637 apr_socket_from_file(&listensocks[0], pipe_of_death_in);
639 for (lr = ap_listeners, i = 1; i <= num_listensocks; lr = lr->next, ++i)
640 listensocks[i]=lr->sd;
642 /* Setup worker threads */
644 worker_thread_count = 0;
645 pthread_mutex_init(&worker_thread_count_mutex, NULL);
646 pthread_mutex_init(&pipe_of_death_mutex, NULL);
647 pthread_attr_init(&thread_attr);
648 #ifdef PTHREAD_ATTR_SETDETACHSTATE_ARG2_ADDR
652 pthread_attr_setdetachstate(&thread_attr, &on);
655 pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
657 for (i=0; i < ap_threads_per_child; i++) {
659 my_info = (proc_info *)malloc(sizeof(proc_info));
660 if (my_info == NULL) {
661 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
662 "malloc: out of memory");
663 clean_child_exit(APEXIT_CHILDFATAL);
665 my_info->pid = my_child_num;
668 apr_pool_create(&my_info->tpool, pchild);
670 /* We are creating threads right now */
671 (void) ap_update_child_status(my_child_num, i, SERVER_STARTING,
672 (request_rec *) NULL);
674 if ((rv = pthread_create(&thread, &thread_attr, worker_thread, my_info))) {
675 #ifdef PTHREAD_SETS_ERRNO
678 ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf,
679 "pthread_create: unable to create worker thread");
680 /* In case system resources are maxxed out, we don't want
681 Apache running away with the CPU trying to fork over and
682 over and over again if we exit. */
684 clean_child_exit(APEXIT_CHILDFATAL);
687 worker_thread(my_info);
688 /* The SIGTERM shouldn't let us reach this point, but just in case... */
689 clean_child_exit(APEXIT_OK);
692 /* We let each thread update it's own scoreboard entry. This is done
693 * because it let's us deal with tid better.
697 pthread_attr_destroy(&thread_attr);
699 /* This thread will be the one responsible for handling signals */
700 sigemptyset(&sig_mask);
701 sigaddset(&sig_mask, SIGTERM);
702 sigaddset(&sig_mask, SIGINT);
703 ap_sigwait(&sig_mask, &signal_received);
704 switch (signal_received) {
707 just_die(signal_received);
710 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, ap_server_conf,
711 "received impossible signal: %d", signal_received);
716 static int make_child(server_rec *s, int slot)
720 if (slot + 1 > ap_max_daemons_limit) {
721 ap_max_daemons_limit = slot + 1;
726 ap_scoreboard_image->parent[slot].pid = getpid();
730 /* Tag this slot as occupied so that perform_idle_server_maintenance
731 * doesn't try to steal it */
732 (void) ap_update_child_status(slot, 0, SERVER_STARTING, (request_rec *) NULL);
734 if ((pid = fork()) == -1) {
735 ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, "fork: Unable to fork new process");
737 /* fork didn't succeed. Fix the scoreboard or else
738 * it will say SERVER_STARTING forever and ever
740 (void) ap_update_child_status(slot, 0, SERVER_DEAD, (request_rec *) NULL);
742 /* In case system resources are maxxed out, we don't want
743 Apache running away with the CPU trying to fork over and
744 over and over again. */
751 #ifdef AIX_BIND_PROCESSOR
752 /* By default, AIX binds to a single processor. This bit unbinds
753 children which will then bind to another CPU.
755 #include <sys/processor.h>
756 int status = bindprocessor(BINDPROCESS, (int)getpid(),
757 PROCESSOR_CLASS_ANY);
759 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, errno, ap_server_conf,
760 "processor unbind failed %d", status);
763 RAISE_SIGSTOP(MAKE_CHILD);
765 apr_signal(SIGTERM, just_die);
771 ap_scoreboard_image->parent[slot].pid = pid;
775 /* start up a bunch of children */
776 static void startup_children(int number_to_start)
780 for (i = 0; number_to_start && i < ap_daemons_limit; ++i) {
781 if (ap_scoreboard_image->parent[i].pid != 0) {
784 if (make_child(ap_server_conf, i) < 0) {
793 * idle_spawn_rate is the number of children that will be spawned on the
794 * next maintenance cycle if there aren't enough idle servers. It is
795 * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
796 * without the need to spawn.
798 static int idle_spawn_rate = 1;
799 #ifndef MAX_SPAWN_RATE
800 #define MAX_SPAWN_RATE (32)
802 static int hold_off_on_exponential_spawning;
804 static void perform_idle_server_maintenance(void)
807 int idle_thread_count;
810 int free_slots[MAX_SPAWN_RATE];
816 /* initialize the free_list */
819 idle_thread_count = 0;
823 ap_sync_scoreboard_image();
824 for (i = 0; i < ap_daemons_limit; ++i) {
825 /* Initialization to satisfy the compiler. It doesn't know
826 * that ap_threads_per_child is always > 0 */
827 int status = SERVER_DEAD;
828 int any_dying_threads = 0;
829 int all_dead_threads = 1;
830 int idle_thread_addition = 0;
832 if (i >= ap_max_daemons_limit && free_length == idle_spawn_rate)
834 for (j = 0; j < ap_threads_per_child; j++) {
835 ss = &ap_scoreboard_image->servers[i][j];
838 any_dying_threads = any_dying_threads || (status == SERVER_DEAD)
839 || (status == SERVER_GRACEFUL);
840 all_dead_threads = all_dead_threads && (status == SERVER_DEAD);
842 /* We consider a starting server as idle because we started it
843 * at least a cycle ago, and if it still hasn't finished starting
844 * then we're just going to swamp things worse by forking more.
845 * So we hopefully won't need to fork more if we count it.
846 * This depends on the ordering of SERVER_READY and SERVER_STARTING.
848 if (status <= SERVER_READY) {
849 ++idle_thread_addition;
852 if (all_dead_threads && free_length < idle_spawn_rate) {
853 free_slots[free_length] = i;
856 if (!all_dead_threads) {
859 if (!any_dying_threads) {
861 idle_thread_count += idle_thread_addition;
864 ap_max_daemons_limit = last_non_dead + 1;
866 if (idle_thread_count > max_spare_threads) {
867 /* Kill off one child */
868 char char_of_death = '!';
869 if ((rv = apr_file_write(pipe_of_death_out, &char_of_death, &one)) != APR_SUCCESS) {
870 ap_log_error(APLOG_MARK, APLOG_WARNING, rv, ap_server_conf, "write pipe_of_death");
874 else if (idle_thread_count < min_spare_threads) {
875 /* terminate the free list */
876 if (free_length == 0) {
877 /* only report this condition once */
878 static int reported = 0;
881 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, ap_server_conf,
882 "server reached MaxClients setting, consider"
883 " raising the MaxClients setting");
890 if (idle_spawn_rate >= 8) {
891 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, ap_server_conf,
892 "server seems busy, (you may need "
893 "to increase StartServers, ThreadsPerChild "
894 "or Min/MaxSpareThreads), "
895 "spawning %d children, there are around %d idle "
896 "threads, and %d total children", idle_spawn_rate,
897 idle_thread_count, total_non_dead);
899 for (i = 0; i < free_length; ++i) {
900 make_child(ap_server_conf, free_slots[i]);
902 /* the next time around we want to spawn twice as many if this
903 * wasn't good enough, but not if we've just done a graceful
905 if (hold_off_on_exponential_spawning) {
906 --hold_off_on_exponential_spawning;
908 else if (idle_spawn_rate < MAX_SPAWN_RATE) {
909 idle_spawn_rate *= 2;
918 static void server_main_loop(int remaining_children_to_start)
925 while (!restart_pending && !shutdown_pending) {
926 ap_wait_or_timeout(&status, &pid, pconf);
929 ap_process_child_status(&pid, status);
930 /* non-fatal death... note that it's gone in the scoreboard. */
931 child_slot = find_child_by_pid(&pid);
932 if (child_slot >= 0) {
933 for (i = 0; i < ap_threads_per_child; i++)
934 ap_update_child_status(child_slot, i, SERVER_DEAD, (request_rec *) NULL);
936 if (remaining_children_to_start
937 && child_slot < ap_daemons_limit) {
938 /* we're still doing a 1-for-1 replacement of dead
939 * children with new children
941 make_child(ap_server_conf, child_slot);
942 --remaining_children_to_start;
944 #if APR_HAS_OTHER_CHILD
946 else if (apr_proc_other_child_read(&pid, status) == 0) {
950 else if (is_graceful) {
951 /* Great, we've probably just lost a slot in the
952 * scoreboard. Somehow we don't know about this child.
954 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0,
956 "long lost child came home! (pid %ld)",
959 /* Don't perform idle maintenance when a child dies,
960 * only do it when there's a timeout. Remember only a
961 * finite number of children can die, and it's pretty
962 * pathological for a lot to die suddenly.
966 else if (remaining_children_to_start) {
967 /* we hit a 1 second timeout in which none of the previous
968 * generation of children needed to be reaped... so assume
969 * they're all done, and pick up the slack if any is left.
971 startup_children(remaining_children_to_start);
972 remaining_children_to_start = 0;
973 /* In any event we really shouldn't do the code below because
974 * few of the servers we just started are in the IDLE state
975 * yet, so we'd mistakenly create an extra server.
980 perform_idle_server_maintenance();
984 int ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
986 int remaining_children_to_start;
992 rv = apr_file_pipe_create(&pipe_of_death_in, &pipe_of_death_out, pconf);
993 if (rv != APR_SUCCESS) {
994 ap_log_error(APLOG_MARK, APLOG_ERR, rv,
995 (const server_rec*) ap_server_conf,
996 "apr_file_pipe_create (pipe_of_death)");
1000 if ((rv = apr_file_pipe_timeout_set(pipe_of_death_in, 0)) != APR_SUCCESS) {
1001 ap_log_error(APLOG_MARK, APLOG_ERR, rv,
1002 (const server_rec*) ap_server_conf,
1003 "apr_file_pipe_timeout_set (pipe_of_death)");
1007 if ((num_listensocks = ap_setup_listeners(ap_server_conf)) < 1) {
1008 /* XXX: hey, what's the right way for the mpm to indicate a fatal error? */
1009 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ALERT, 0, s,
1010 "no listening sockets available, shutting down");
1013 ap_log_pid(pconf, ap_pid_fname);
1015 /* Initialize cross-process accept lock */
1016 lock_fname = apr_psprintf(_pconf, "%s.%u",
1017 ap_server_root_relative(_pconf, lock_fname),
1019 rv = apr_lock_create(&accept_mutex, APR_MUTEX, APR_LOCKALL,
1020 lock_fname, _pconf);
1021 if (rv != APR_SUCCESS) {
1022 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
1023 "Couldn't create accept lock");
1029 ap_create_scoreboard(pconf, SB_SHARED);
1033 /* Don't thrash... */
1034 if (max_spare_threads < min_spare_threads + ap_threads_per_child)
1035 max_spare_threads = min_spare_threads + ap_threads_per_child;
1037 /* If we're doing a graceful_restart then we're going to see a lot
1038 * of children exiting immediately when we get into the main loop
1039 * below (because we just sent them SIGWINCH). This happens pretty
1040 * rapidly... and for each one that exits we'll start a new one until
1041 * we reach at least daemons_min_free. But we may be permitted to
1042 * start more than that, so we'll just keep track of how many we're
1043 * supposed to start up without the 1 second penalty between each fork.
1045 remaining_children_to_start = ap_daemons_to_start;
1046 if (remaining_children_to_start > ap_daemons_limit) {
1047 remaining_children_to_start = ap_daemons_limit;
1050 startup_children(remaining_children_to_start);
1051 remaining_children_to_start = 0;
1054 /* give the system some time to recover before kicking into
1055 * exponential mode */
1056 hold_off_on_exponential_spawning = 10;
1059 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1060 "%s configured -- resuming normal operations",
1061 ap_get_server_version());
1062 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, ap_server_conf,
1063 "Server built: %s", ap_get_server_built());
1064 restart_pending = shutdown_pending = 0;
1066 server_main_loop(remaining_children_to_start);
1068 if (shutdown_pending) {
1069 /* Time to gracefully shut down:
1070 * Kill child processes, tell them to call child_exit, etc...
1072 if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
1073 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGTERM");
1075 ap_reclaim_child_processes(1); /* Start with SIGTERM */
1077 /* cleanup pid file on normal shutdown */
1079 const char *pidfile = NULL;
1080 pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1081 if ( pidfile != NULL && unlink(pidfile) == 0)
1082 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0,
1084 "removed PID file %s (pid=%ld)",
1085 pidfile, (long)getpid());
1088 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1089 "caught SIGTERM, shutting down");
1094 /* we've been told to restart */
1095 apr_signal(SIGHUP, SIG_IGN);
1098 /* not worth thinking about */
1102 /* advance to the next generation */
1103 /* XXX: we really need to make sure this new generation number isn't in
1104 * use by any of the children.
1107 ap_scoreboard_image->global.running_generation = ap_my_generation;
1108 update_scoreboard_global();
1112 char char_of_death = '!';
1114 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1115 "SIGWINCH received. Doing graceful restart");
1117 /* give the children the signal to die */
1118 for (i = 0; i < ap_daemons_limit;) {
1119 if ((rv = apr_file_write(pipe_of_death_in, &char_of_death, &one)) != APR_SUCCESS) {
1120 if (APR_STATUS_IS_EINTR(rv)) continue;
1121 ap_log_error(APLOG_MARK, APLOG_WARNING, rv, ap_server_conf, "write pipe_of_death");
1126 /* This is mostly for debugging... so that we know what is still
1127 * gracefully dealing with existing request.
1130 for (i = 0; i < ap_daemons_limit; ++i) {
1131 for (j = 0; j < ap_threads_per_child; j++) {
1132 if (ap_scoreboard_image->servers[i][j].status != SERVER_DEAD) {
1133 ap_scoreboard_image->servers[i][j].status = SERVER_GRACEFUL;
1139 /* Kill 'em all. Since the child acts the same on the parents SIGTERM
1140 * and a SIGHUP, we may as well use the same signal, because some user
1141 * pthreads are stealing signals from us left and right.
1143 if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
1144 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGTERM");
1146 ap_reclaim_child_processes(1); /* Start with SIGTERM */
1147 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1148 "SIGHUP received. Attempting to restart");
1153 static void mpmt_pthread_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
1155 static int restart_num = 0;
1158 one_process = !!ap_exists_config_define("ONE_PROCESS");
1159 no_detach = !!ap_exists_config_define("NO_DETACH");
1161 /* sigh, want this only the second time around */
1162 if (restart_num++ == 1) {
1165 if (!one_process && !no_detach) {
1168 ap_my_pid = getpid();
1171 unixd_pre_config(ptemp);
1172 ap_listen_pre_config();
1173 ap_daemons_to_start = DEFAULT_START_DAEMON;
1174 min_spare_threads = DEFAULT_MIN_FREE_DAEMON * DEFAULT_THREADS_PER_CHILD;
1175 max_spare_threads = DEFAULT_MAX_FREE_DAEMON * DEFAULT_THREADS_PER_CHILD;
1176 ap_daemons_limit = HARD_SERVER_LIMIT;
1177 ap_threads_per_child = DEFAULT_THREADS_PER_CHILD;
1178 ap_pid_fname = DEFAULT_PIDLOG;
1179 ap_scoreboard_fname = DEFAULT_SCOREBOARD;
1180 lock_fname = DEFAULT_LOCKFILE;
1181 ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1182 ap_extended_status = 0;
1184 apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1187 static void mpmt_pthread_hooks(apr_pool_t *p)
1192 ap_hook_pre_config(mpmt_pthread_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
1196 static const char *set_pidfile(cmd_parms *cmd, void *dummy, const char *arg)
1198 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1203 if (cmd->server->is_virtual) {
1204 return "PidFile directive not allowed in <VirtualHost>";
1210 static const char *set_scoreboard(cmd_parms *cmd, void *dummy,
1213 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1218 ap_scoreboard_fname = arg;
1222 static const char *set_lockfile(cmd_parms *cmd, void *dummy, const char *arg)
1224 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1233 static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy,
1236 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1241 ap_daemons_to_start = atoi(arg);
1245 static const char *set_min_spare_threads(cmd_parms *cmd, void *dummy,
1248 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1253 min_spare_threads = atoi(arg);
1254 if (min_spare_threads <= 0) {
1255 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1256 "WARNING: detected MinSpareThreads set to non-positive.");
1257 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1258 "Resetting to 1 to avoid almost certain Apache failure.");
1259 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1260 "Please read the documentation.");
1261 min_spare_threads = 1;
1267 static const char *set_max_spare_threads(cmd_parms *cmd, void *dummy,
1270 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1275 max_spare_threads = atoi(arg);
1279 static const char *set_server_limit (cmd_parms *cmd, void *dummy,
1282 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1287 ap_daemons_limit = atoi(arg);
1288 if (ap_daemons_limit > HARD_SERVER_LIMIT) {
1289 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1290 "WARNING: MaxClients of %d exceeds compile time limit "
1291 "of %d servers,", ap_daemons_limit, HARD_SERVER_LIMIT);
1292 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1293 " lowering MaxClients to %d. To increase, please "
1294 "see the", HARD_SERVER_LIMIT);
1295 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1296 " HARD_SERVER_LIMIT define in %s.",
1297 AP_MPM_HARD_LIMITS_FILE);
1298 ap_daemons_limit = HARD_SERVER_LIMIT;
1300 else if (ap_daemons_limit < 1) {
1301 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, "WARNING: Require MaxClients > 0, setting to 1");
1302 ap_daemons_limit = 1;
1307 static const char *set_threads_per_child (cmd_parms *cmd, void *dummy,
1310 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1315 ap_threads_per_child = atoi(arg);
1316 if (ap_threads_per_child > HARD_THREAD_LIMIT) {
1317 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1318 "WARNING: ThreadsPerChild of %d exceeds compile time"
1319 "limit of %d threads,", ap_threads_per_child,
1321 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1322 " lowering ThreadsPerChild to %d. To increase, please"
1323 " see the", HARD_THREAD_LIMIT);
1324 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1325 " HARD_THREAD_LIMIT define in %s.",
1326 AP_MPM_HARD_LIMITS_FILE);
1328 else if (ap_threads_per_child < 1) {
1329 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1330 "WARNING: Require ThreadsPerChild > 0, setting to 1");
1331 ap_threads_per_child = 1;
1336 static const char *set_max_requests(cmd_parms *cmd, void *dummy,
1339 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1344 ap_max_requests_per_child = atoi(arg);
1349 static const char *set_coredumpdir (cmd_parms *cmd, void *dummy,
1354 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1359 fname = ap_server_root_relative(cmd->pool, arg);
1360 if ((apr_stat(&finfo, fname, APR_FINFO_TYPE, cmd->pool) != APR_SUCCESS)
1361 || (finfo.filetype != APR_DIR)) {
1362 return apr_pstrcat(cmd->pool, "CoreDumpDirectory ", fname,
1363 " does not exist or is not a directory", NULL);
1365 apr_cpystrn(ap_coredump_dir, fname, sizeof(ap_coredump_dir));
1369 static const command_rec mpmt_pthread_cmds[] = {
1370 UNIX_DAEMON_COMMANDS
1372 AP_INIT_TAKE1("PidFile", set_pidfile, NULL, RSRC_CONF,
1373 "A file for logging the server process ID"),
1374 AP_INIT_TAKE1("ScoreBoardFile", set_scoreboard, NULL, RSRC_CONF,
1375 "A file for Apache to maintain runtime process management information"),
1376 AP_INIT_TAKE1("LockFile", set_lockfile, NULL, RSRC_CONF,
1377 "The lockfile used when Apache needs to lock the accept() call"),
1378 AP_INIT_TAKE1("StartServers", set_daemons_to_start, NULL, RSRC_CONF,
1379 "Number of child processes launched at server startup"),
1380 AP_INIT_TAKE1("MinSpareThreads", set_min_spare_threads, NULL, RSRC_CONF,
1381 "Minimum number of idle children, to handle request spikes"),
1382 AP_INIT_TAKE1("MaxSpareThreads", set_max_spare_threads, NULL, RSRC_CONF,
1383 "Maximum number of idle children"),
1384 AP_INIT_TAKE1("MaxClients", set_server_limit, NULL, RSRC_CONF,
1385 "Maximum number of children alive at the same time"),
1386 AP_INIT_TAKE1("ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF,
1387 "Number of threads each child creates"),
1388 AP_INIT_TAKE1("MaxRequestsPerChild", set_max_requests, NULL, RSRC_CONF,
1389 "Maximum number of requests a particular child serves before dying."),
1390 AP_INIT_TAKE1("CoreDumpDirectory", set_coredumpdir, NULL, RSRC_CONF,
1391 "The location of the directory Apache changes to before dumping core"),
1395 module AP_MODULE_DECLARE_DATA mpm_mpmt_pthread_module = {
1397 NULL, /* hook to run before apache parses args */
1398 NULL, /* create per-directory config structure */
1399 NULL, /* merge per-directory config structures */
1400 NULL, /* create per-server config structure */
1401 NULL, /* merge per-server config structures */
1402 mpmt_pthread_cmds, /* command apr_table_t */
1403 mpmt_pthread_hooks /* register_hooks */