1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000-2003 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.
60 #include "apr_portable.h"
61 #include "apr_strings.h"
62 #include "apr_thread_proc.h"
63 #include "apr_signal.h"
65 #define APR_WANT_STDIO
66 #define APR_WANT_STRFUNC
72 #if APR_HAVE_SYS_TYPES_H
73 #include <sys/types.h>
78 #include "ap_config.h"
80 #include "mpm_default.h"
81 #include "http_main.h"
83 #include "http_config.h"
84 #include "http_core.h" /* for get_remote_host */
85 #include "http_connection.h"
86 #include "scoreboard.h"
89 #include "mpm_common.h"
90 #include "ap_listen.h"
95 #include <bstring.h> /* for IRIX, FD_SET calls bzero() */
100 #ifdef HAVE_SYS_PROCESSOR_H
101 #include <sys/processor.h> /* for bindprocessor() */
105 #include <sys/times.h>
107 /* Limit on the total --- clients will be locked out if more servers than
108 * this are needed. It is intended solely to keep the server from crashing
109 * when things get out of hand.
111 * We keep a hard maximum number of servers, for two reasons --- first off,
112 * in case something goes seriously wrong, we want to stop the fork bomb
113 * short of actually crashing the machine we're running on by filling some
114 * kernel table. Secondly, it keeps the size of the scoreboard file small
115 * enough that we can read the whole thing without worrying too much about
118 #ifndef DEFAULT_SERVER_LIMIT
119 #define DEFAULT_SERVER_LIMIT 256
122 /* Admin can't tune ServerLimit beyond MAX_SERVER_LIMIT. We want
123 * some sort of compile-time limit to help catch typos.
125 #ifndef MAX_SERVER_LIMIT
126 #define MAX_SERVER_LIMIT 20000
129 #ifndef HARD_THREAD_LIMIT
130 #define HARD_THREAD_LIMIT 1
135 int ap_threads_per_child=0; /* Worker threads per child */
136 static apr_proc_mutex_t *accept_mutex;
137 static int ap_daemons_to_start=0;
138 static int ap_daemons_min_free=0;
139 static int ap_daemons_max_free=0;
140 static int ap_daemons_limit=0; /* MaxClients */
141 static int server_limit = DEFAULT_SERVER_LIMIT;
142 static int first_server_limit;
143 static int changed_limit_at_restart;
145 static ap_pod_t *pod;
148 * The max child slot ever assigned, preserved across restarts. Necessary
149 * to deal with MaxClients changes across AP_SIG_GRACEFUL restarts. We
150 * use this value to optimize routines that have to scan the entire scoreboard.
152 int ap_max_daemons_limit = -1;
153 server_rec *ap_server_conf;
155 /* one_process --- debugging mode variable; can be set from the command line
156 * with the -X flag. If set, this gets you the child_main loop running
157 * in the process which originally started up (no detach, no make_child),
158 * which is a pretty nice debugging environment. (You'll get a SIGHUP
159 * early in standalone_main; just continue through. This is the server
160 * trying to kill off any child processes which it might have lying
161 * around --- Apache doesn't keep track of their pids, it just sends
162 * SIGHUP to the process group, ignoring it in the root process.
163 * Continue through and you'll be fine.).
166 static int one_process = 0;
168 static apr_pool_t *pconf; /* Pool for config stuff */
169 static apr_pool_t *pchild; /* Pool for httpd child stuff */
171 static pid_t ap_my_pid; /* it seems silly to call getpid all the time */
172 static pid_t parent_pid;
174 static int my_child_num;
176 ap_generation_t volatile ap_my_generation=0;
180 char tpf_server_name[INETD_SERVNAME_LENGTH+1];
183 static int die_now = 0;
187 * change directory for gprof to plop the gmon.out file
188 * configure in httpd.conf:
189 * GprofDir $RuntimeDir/ -> $ServerRoot/$RuntimeDir/gmon.out
190 * GprofDir $RuntimeDir/% -> $ServerRoot/$RuntimeDir/gprof.$pid/gmon.out
192 static void chdir_for_gprof(void)
194 core_server_config *sconf =
195 ap_get_module_config(ap_server_conf->module_config, &core_module);
196 char *dir = sconf->gprof_dir;
202 int len = strlen(sconf->gprof_dir) - 1;
203 if(*(dir + len) == '%') {
205 apr_snprintf(buf, sizeof(buf), "%sgprof.%d", dir, (int)getpid());
207 use_dir = ap_server_root_relative(pconf, buf[0] ? buf : dir);
208 res = apr_dir_make(use_dir,
209 APR_UREAD | APR_UWRITE | APR_UEXECUTE |
210 APR_GREAD | APR_GEXECUTE |
211 APR_WREAD | APR_WEXECUTE, pconf);
212 if(res != APR_SUCCESS && !APR_STATUS_IS_EEXIST(res)) {
213 ap_log_error(APLOG_MARK, APLOG_ERR, res, ap_server_conf,
214 "gprof: error creating directory %s", dir);
218 use_dir = ap_server_root_relative(pconf, DEFAULT_REL_RUNTIMEDIR);
224 #define chdir_for_gprof()
227 /* XXX - I don't know if TPF will ever use this module or not, so leave
228 * the ap_check_signals calls in but disable them - manoj */
229 #define ap_check_signals()
231 /* a clean exit from a child with proper cleanup */
232 static void clean_child_exit(int code) __attribute__ ((noreturn));
233 static void clean_child_exit(int code)
236 apr_pool_destroy(pchild);
238 ap_mpm_pod_close(pod);
243 static void accept_mutex_on(void)
245 apr_status_t rv = apr_proc_mutex_lock(accept_mutex);
246 if (rv != APR_SUCCESS) {
247 const char *msg = "couldn't grab the accept mutex";
249 if (ap_my_generation !=
250 ap_scoreboard_image->global->running_generation) {
251 ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, NULL, msg);
255 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, msg);
256 exit(APEXIT_CHILDFATAL);
261 static void accept_mutex_off(void)
263 apr_status_t rv = apr_proc_mutex_unlock(accept_mutex);
264 if (rv != APR_SUCCESS) {
265 const char *msg = "couldn't release the accept mutex";
267 if (ap_my_generation !=
268 ap_scoreboard_image->global->running_generation) {
269 ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, NULL, msg);
270 /* don't exit here... we have a connection to
271 * process, after which point we'll see that the
272 * generation changed and we'll exit cleanly
276 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, msg);
277 exit(APEXIT_CHILDFATAL);
282 /* On some architectures it's safe to do unserialized accept()s in the single
283 * Listen case. But it's never safe to do it in the case where there's
284 * multiple Listen statements. Define SINGLE_LISTEN_UNSERIALIZED_ACCEPT
285 * when it's safe in the single Listen case.
287 #ifdef SINGLE_LISTEN_UNSERIALIZED_ACCEPT
288 #define SAFE_ACCEPT(stmt) do {if (ap_listeners->next) {stmt;}} while(0)
290 #define SAFE_ACCEPT(stmt) do {stmt;} while(0)
293 AP_DECLARE(apr_status_t) ap_mpm_query(int query_code, int *result)
296 case AP_MPMQ_MAX_DAEMON_USED:
297 *result = ap_daemons_limit;
299 case AP_MPMQ_IS_THREADED:
300 *result = AP_MPMQ_NOT_SUPPORTED;
302 case AP_MPMQ_IS_FORKED:
303 *result = AP_MPMQ_DYNAMIC;
305 case AP_MPMQ_HARD_LIMIT_DAEMONS:
306 *result = server_limit;
308 case AP_MPMQ_HARD_LIMIT_THREADS:
309 *result = HARD_THREAD_LIMIT;
311 case AP_MPMQ_MAX_THREADS:
314 case AP_MPMQ_MIN_SPARE_DAEMONS:
315 *result = ap_daemons_min_free;
317 case AP_MPMQ_MIN_SPARE_THREADS:
320 case AP_MPMQ_MAX_SPARE_DAEMONS:
321 *result = ap_daemons_max_free;
323 case AP_MPMQ_MAX_SPARE_THREADS:
326 case AP_MPMQ_MAX_REQUESTS_DAEMON:
327 *result = ap_max_requests_per_child;
329 case AP_MPMQ_MAX_DAEMONS:
330 *result = server_limit;
336 #if defined(NEED_WAITPID)
338 Systems without a real waitpid sometimes lose a child's exit while waiting
339 for another. Search through the scoreboard for missing children.
341 int reap_children(int *exitcode, apr_exit_why_e *status)
345 for (n = 0; n < ap_max_daemons_limit; ++n) {
346 if (ap_scoreboard_image->servers[n][0].status != SERVER_DEAD &&
347 kill((pid = ap_scoreboard_image->parent[n].pid), 0) == -1) {
348 ap_update_child_status_from_indexes(n, 0, SERVER_DEAD, NULL);
349 /* just mark it as having a successful exit status */
350 *status = APR_PROC_EXIT;
359 /*****************************************************************
360 * Connection structures and accounting...
363 static void just_die(int sig)
368 /* volatile just in case */
369 static int volatile shutdown_pending;
370 static int volatile restart_pending;
371 static int volatile is_graceful;
373 static void sig_term(int sig)
375 if (shutdown_pending == 1) {
376 /* Um, is this _probably_ not an error, if the user has
377 * tried to do a shutdown twice quickly, so we won't
378 * worry about reporting it.
382 shutdown_pending = 1;
385 /* restart() is the signal handler for SIGHUP and AP_SIG_GRACEFUL
386 * in the parent process, unless running in ONE_PROCESS mode
388 static void restart(int sig)
390 if (restart_pending == 1) {
391 /* Probably not an error - don't bother reporting it */
395 is_graceful = (sig == AP_SIG_GRACEFUL);
398 static void set_signals(void)
400 #ifndef NO_USE_SIGACTION
405 ap_fatal_signal_setup(ap_server_conf, pconf);
408 #ifndef NO_USE_SIGACTION
409 sigemptyset(&sa.sa_mask);
412 sa.sa_handler = sig_term;
413 if (sigaction(SIGTERM, &sa, NULL) < 0)
414 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGTERM)");
416 if (sigaction(SIGINT, &sa, NULL) < 0)
417 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGINT)");
420 sa.sa_handler = SIG_DFL;
421 if (sigaction(SIGXCPU, &sa, NULL) < 0)
422 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXCPU)");
425 sa.sa_handler = SIG_DFL;
426 if (sigaction(SIGXFSZ, &sa, NULL) < 0)
427 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXFSZ)");
430 sa.sa_handler = SIG_IGN;
431 if (sigaction(SIGPIPE, &sa, NULL) < 0)
432 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGPIPE)");
435 /* we want to ignore HUPs and AP_SIG_GRACEFUL while we're busy
437 sigaddset(&sa.sa_mask, SIGHUP);
438 sigaddset(&sa.sa_mask, AP_SIG_GRACEFUL);
439 sa.sa_handler = restart;
440 if (sigaction(SIGHUP, &sa, NULL) < 0)
441 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGHUP)");
442 if (sigaction(AP_SIG_GRACEFUL, &sa, NULL) < 0)
443 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(" AP_SIG_GRACEFUL_STRING ")");
447 apr_signal(SIGXCPU, SIG_DFL);
450 apr_signal(SIGXFSZ, SIG_DFL);
454 apr_signal(SIGTERM, sig_term);
456 apr_signal(SIGHUP, restart);
458 #ifdef AP_SIG_GRACEFUL
459 apr_signal(AP_SIG_GRACEFUL, restart);
460 #endif /* AP_SIG_GRACEFUL */
462 apr_signal(SIGPIPE, SIG_IGN);
468 /*****************************************************************
469 * Child process main loop.
470 * The following vars are static to avoid getting clobbered by longjmp();
471 * they are really private to child_main.
474 static int requests_this_child;
475 static int num_listensocks = 0;
476 static ap_listen_rec *listensocks;
478 int ap_graceful_stop_signalled(void)
480 /* not ever called anymore... */
485 static void child_main(int child_num_arg)
488 apr_allocator_t *allocator;
489 conn_rec *current_conn;
490 apr_status_t status = APR_EINIT;
493 int curr_pollfd, last_pollfd = 0;
494 apr_pollfd_t *pollset;
499 apr_bucket_alloc_t *bucket_alloc;
501 my_child_num = child_num_arg;
502 ap_my_pid = getpid();
504 requests_this_child = 0;
506 ap_fatal_signal_child_setup(ap_server_conf);
508 /* Get a sub context for global allocations in this child, so that
509 * we can have cleanups occur when the child exits.
511 apr_allocator_create(&allocator);
512 apr_allocator_max_free_set(allocator, ap_max_mem_free);
513 apr_pool_create_ex(&pchild, pconf, NULL, allocator);
514 apr_allocator_owner_set(allocator, pchild);
516 apr_pool_create(&ptrans, pchild);
517 apr_pool_tag(ptrans, "transaction");
519 /* needs to be done before we switch UIDs so we have permissions */
520 ap_reopen_scoreboard(pchild, NULL, 0);
521 rv = apr_proc_mutex_child_init(&accept_mutex, ap_lock_fname, pchild);
522 if (rv != APR_SUCCESS) {
523 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
524 "Couldn't initialize cross-process lock in child");
525 clean_child_exit(APEXIT_CHILDFATAL);
528 if (unixd_setup_child()) {
529 clean_child_exit(APEXIT_CHILDFATAL);
532 ap_run_child_init(pchild, ap_server_conf);
534 ap_create_sb_handle(&sbh, pchild, my_child_num, 0);
536 (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
538 /* Set up the pollfd array */
539 listensocks = apr_pcalloc(pchild,
540 sizeof(*listensocks) * (num_listensocks));
541 for (lr = ap_listeners, i = 0; i < num_listensocks; lr = lr->next, i++) {
542 listensocks[i].accept_func = lr->accept_func;
543 listensocks[i].sd = lr->sd;
546 pollset = apr_palloc(pchild, sizeof(*pollset) * num_listensocks);
547 pollset[0].p = pchild;
548 for (i = 0; i < num_listensocks; i++) {
549 pollset[i].desc.s = listensocks[i].sd;
550 pollset[i].desc_type = APR_POLL_SOCKET;
551 pollset[i].reqevents = APR_POLLIN;
554 bucket_alloc = apr_bucket_alloc_create(pchild);
558 * (Re)initialize this child to a pre-connection state.
563 apr_pool_clear(ptrans);
565 if ((ap_max_requests_per_child > 0
566 && requests_this_child++ >= ap_max_requests_per_child)) {
570 (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
573 * Wait for an acceptable connection to arrive.
576 /* Lock around "accept", if necessary */
577 SAFE_ACCEPT(accept_mutex_on());
579 if (num_listensocks == 1) {
583 /* multiple listening sockets - need to poll */
588 ret = apr_poll(pollset, num_listensocks, &n, -1);
589 if (ret != APR_SUCCESS) {
590 if (APR_STATUS_IS_EINTR(ret)) {
591 if (one_process && shutdown_pending) {
596 /* Single Unix documents select as returning errnos
597 * EBADF, EINTR, and EINVAL... and in none of those
598 * cases does it make sense to continue. In fact
599 * on Linux 2.0.x we seem to end up with EFAULT
600 * occasionally, and we'd loop forever due to it.
602 ap_log_error(APLOG_MARK, APLOG_ERR, ret, ap_server_conf,
603 "apr_poll: (listen)");
606 /* find a listener */
607 curr_pollfd = last_pollfd;
610 if (curr_pollfd >= num_listensocks) {
613 /* XXX: Should we check for POLLERR? */
614 if (pollset[curr_pollfd].rtnevents & APR_POLLIN) {
615 last_pollfd = curr_pollfd;
616 offset = curr_pollfd;
619 } while (curr_pollfd != last_pollfd);
625 /* if we accept() something we don't want to die, so we have to
628 status = listensocks[offset].accept_func(&csd,
629 &listensocks[offset], ptrans);
630 SAFE_ACCEPT(accept_mutex_off()); /* unlock after "accept" */
632 if (status == APR_EGENERAL) {
633 /* resource shortage or should-not-occur occured */
636 else if (status != APR_SUCCESS) {
641 * We now have a connection, so set it up with the appropriate
642 * socket options, file descriptors, and read/write buffers.
645 current_conn = ap_run_create_connection(ptrans, ap_server_conf, csd, my_child_num, sbh, bucket_alloc);
647 ap_process_connection(current_conn, csd);
648 ap_lingering_close(current_conn);
651 /* Check the pod and the generation number after processing a
652 * connection so that we'll go away if a graceful restart occurred
653 * while we were processing the connection or we are the lucky
654 * idle server process that gets to die.
656 if (ap_mpm_pod_check(pod) == APR_SUCCESS) { /* selected as idle? */
659 else if (ap_my_generation !=
660 ap_scoreboard_image->global->running_generation) { /* restart? */
661 /* yeah, this could be non-graceful restart, in which case the
662 * parent will kill us soon enough, but why bother checking?
671 static int make_child(server_rec *s, int slot)
675 if (slot + 1 > ap_max_daemons_limit) {
676 ap_max_daemons_limit = slot + 1;
680 apr_signal(SIGHUP, sig_term);
681 /* Don't catch AP_SIG_GRACEFUL in ONE_PROCESS mode :) */
682 apr_signal(SIGINT, sig_term);
684 apr_signal(SIGQUIT, SIG_DFL);
686 apr_signal(SIGTERM, sig_term);
691 (void) ap_update_child_status_from_indexes(slot, 0, SERVER_STARTING,
692 (request_rec *) NULL);
696 /* BS2000 requires a "special" version of fork() before a setuid() call */
697 if ((pid = os_fork(unixd_config.user_name)) == -1) {
699 if ((pid = os_fork(s, slot)) == -1) {
701 if ((pid = fork()) == -1) {
703 ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, "fork: Unable to fork new process");
705 /* fork didn't succeed. Fix the scoreboard or else
706 * it will say SERVER_STARTING forever and ever
708 (void) ap_update_child_status_from_indexes(slot, 0, SERVER_DEAD,
709 (request_rec *) NULL);
711 /* In case system resources are maxxed out, we don't want
712 Apache running away with the CPU trying to fork over and
713 over and over again. */
720 #ifdef HAVE_BINDPROCESSOR
721 /* by default AIX binds to a single processor
722 * this bit unbinds children which will then bind to another cpu
724 int status = bindprocessor(BINDPROCESS, (int)getpid(),
725 PROCESSOR_CLASS_ANY);
727 ap_log_error(APLOG_MARK, APLOG_WARNING, errno,
728 ap_server_conf, "processor unbind failed %d", status);
731 RAISE_SIGSTOP(MAKE_CHILD);
733 /* Disable the parent's signal handlers and set up proper handling in
736 apr_signal(SIGHUP, just_die);
737 apr_signal(SIGTERM, just_die);
738 /* The child process doesn't do anything for AP_SIG_GRACEFUL.
739 * Instead, the pod is used for signalling graceful restart.
741 apr_signal(AP_SIG_GRACEFUL, SIG_IGN);
745 ap_scoreboard_image->parent[slot].pid = pid;
751 /* start up a bunch of children */
752 static void startup_children(int number_to_start)
756 for (i = 0; number_to_start && i < ap_daemons_limit; ++i) {
757 if (ap_scoreboard_image->servers[i][0].status != SERVER_DEAD) {
760 if (make_child(ap_server_conf, i) < 0) {
769 * idle_spawn_rate is the number of children that will be spawned on the
770 * next maintenance cycle if there aren't enough idle servers. It is
771 * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
772 * without the need to spawn.
774 static int idle_spawn_rate = 1;
775 #ifndef MAX_SPAWN_RATE
776 #define MAX_SPAWN_RATE (32)
778 static int hold_off_on_exponential_spawning;
780 static void perform_idle_server_maintenance(apr_pool_t *p)
787 int free_slots[MAX_SPAWN_RATE];
791 /* initialize the free_list */
799 for (i = 0; i < ap_daemons_limit; ++i) {
802 if (i >= ap_max_daemons_limit && free_length == idle_spawn_rate)
804 ws = &ap_scoreboard_image->servers[i][0];
806 if (status == SERVER_DEAD) {
807 /* try to keep children numbers as low as possible */
808 if (free_length < idle_spawn_rate) {
809 free_slots[free_length] = i;
814 /* We consider a starting server as idle because we started it
815 * at least a cycle ago, and if it still hasn't finished starting
816 * then we're just going to swamp things worse by forking more.
817 * So we hopefully won't need to fork more if we count it.
818 * This depends on the ordering of SERVER_READY and SERVER_STARTING.
820 if (status <= SERVER_READY) {
822 /* always kill the highest numbered child if we have to...
823 * no really well thought out reason ... other than observing
824 * the server behaviour under linux where lower numbered children
825 * tend to service more hits (and hence are more likely to have
826 * their data in cpu caches).
835 ap_max_daemons_limit = last_non_dead + 1;
836 if (idle_count > ap_daemons_max_free) {
837 /* kill off one child... we use the pod because that'll cause it to
838 * shut down gracefully, in case it happened to pick up a request
839 * while we were counting
841 ap_mpm_pod_signal(pod);
844 else if (idle_count < ap_daemons_min_free) {
845 /* terminate the free list */
846 if (free_length == 0) {
847 /* only report this condition once */
848 static int reported = 0;
851 ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf,
852 "server reached MaxClients setting, consider"
853 " raising the MaxClients setting");
859 if (idle_spawn_rate >= 8) {
860 ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf,
861 "server seems busy, (you may need "
862 "to increase StartServers, or Min/MaxSpareServers), "
863 "spawning %d children, there are %d idle, and "
864 "%d total children", idle_spawn_rate,
865 idle_count, total_non_dead);
867 for (i = 0; i < free_length; ++i) {
869 if (make_child(ap_server_conf, free_slots[i]) == -1) {
870 if(free_length == 1) {
871 shutdown_pending = 1;
872 ap_log_error(APLOG_MARK, APLOG_EMERG, 0, ap_server_conf,
873 "No active child processes: shutting down");
877 make_child(ap_server_conf, free_slots[i]);
880 /* the next time around we want to spawn twice as many if this
881 * wasn't good enough, but not if we've just done a graceful
883 if (hold_off_on_exponential_spawning) {
884 --hold_off_on_exponential_spawning;
886 else if (idle_spawn_rate < MAX_SPAWN_RATE) {
887 idle_spawn_rate *= 2;
896 /*****************************************************************
897 * Executive routines.
900 int ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
903 int remaining_children_to_start;
906 ap_log_pid(pconf, ap_pid_fname);
908 first_server_limit = server_limit;
909 if (changed_limit_at_restart) {
910 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
911 "WARNING: Attempt to change ServerLimit "
912 "ignored during restart");
913 changed_limit_at_restart = 0;
916 /* Initialize cross-process accept lock */
917 ap_lock_fname = apr_psprintf(_pconf, "%s.%" APR_PID_T_FMT,
918 ap_server_root_relative(_pconf, ap_lock_fname),
921 rv = apr_proc_mutex_create(&accept_mutex, ap_lock_fname,
922 ap_accept_lock_mech, _pconf);
923 if (rv != APR_SUCCESS) {
924 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
925 "Couldn't create accept lock");
929 #if APR_USE_SYSVSEM_SERIALIZE
930 if (ap_accept_lock_mech == APR_LOCK_DEFAULT ||
931 ap_accept_lock_mech == APR_LOCK_SYSVSEM) {
933 if (ap_accept_lock_mech == APR_LOCK_SYSVSEM) {
935 rv = unixd_set_proc_mutex_perms(accept_mutex);
936 if (rv != APR_SUCCESS) {
937 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
938 "Couldn't set permissions on cross-process lock; "
939 "check User and Group directives");
945 if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
948 /* fix the generation number in the global score; we just got a new,
951 ap_scoreboard_image->global->running_generation = ap_my_generation;
958 make_child(ap_server_conf, 0);
961 if (ap_daemons_max_free < ap_daemons_min_free + 1) /* Don't thrash... */
962 ap_daemons_max_free = ap_daemons_min_free + 1;
964 /* If we're doing a graceful_restart then we're going to see a lot
965 * of children exiting immediately when we get into the main loop
966 * below (because we just sent them AP_SIG_GRACEFUL). This happens pretty
967 * rapidly... and for each one that exits we'll start a new one until
968 * we reach at least daemons_min_free. But we may be permitted to
969 * start more than that, so we'll just keep track of how many we're
970 * supposed to start up without the 1 second penalty between each fork.
972 remaining_children_to_start = ap_daemons_to_start;
973 if (remaining_children_to_start > ap_daemons_limit) {
974 remaining_children_to_start = ap_daemons_limit;
977 startup_children(remaining_children_to_start);
978 remaining_children_to_start = 0;
981 /* give the system some time to recover before kicking into
982 * exponential mode */
983 hold_off_on_exponential_spawning = 10;
986 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
987 "%s configured -- resuming normal operations",
988 ap_get_server_version());
989 ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf,
990 "Server built: %s", ap_get_server_built());
991 #ifdef AP_MPM_WANT_SET_ACCEPT_LOCK_MECH
992 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
993 "AcceptMutex: %s (default: %s)",
994 apr_proc_mutex_name(accept_mutex),
995 apr_proc_mutex_defname());
997 restart_pending = shutdown_pending = 0;
999 while (!restart_pending && !shutdown_pending) {
1001 apr_exit_why_e exitwhy;
1002 int status, processed_status;
1003 /* this is a memory leak, but I'll fix it later. */
1006 ap_wait_or_timeout(&exitwhy, &status, &pid, pconf);
1008 /* XXX: if it takes longer than 1 second for all our children
1009 * to start up and get into IDLE state then we may spawn an
1012 if (pid.pid != -1) {
1013 processed_status = ap_process_child_status(&pid, exitwhy, status);
1014 if (processed_status == APEXIT_CHILDFATAL) {
1018 /* non-fatal death... note that it's gone in the scoreboard. */
1019 child_slot = find_child_by_pid(&pid);
1020 if (child_slot >= 0) {
1021 (void) ap_update_child_status_from_indexes(child_slot, 0, SERVER_DEAD,
1022 (request_rec *) NULL);
1023 if (processed_status == APEXIT_CHILDSICK) {
1024 /* child detected a resource shortage (E[NM]FILE, ENOBUFS, etc)
1025 * cut the fork rate to the minimum
1027 idle_spawn_rate = 1;
1029 else if (remaining_children_to_start
1030 && child_slot < ap_daemons_limit) {
1031 /* we're still doing a 1-for-1 replacement of dead
1032 * children with new children
1034 make_child(ap_server_conf, child_slot);
1035 --remaining_children_to_start;
1037 #if APR_HAS_OTHER_CHILD
1039 else if (apr_proc_other_child_read(&pid, status) == 0) {
1043 else if (is_graceful) {
1044 /* Great, we've probably just lost a slot in the
1045 * scoreboard. Somehow we don't know about this
1048 ap_log_error(APLOG_MARK, APLOG_WARNING,
1050 "long lost child came home! (pid %ld)", (long)pid.pid);
1052 /* Don't perform idle maintenance when a child dies,
1053 * only do it when there's a timeout. Remember only a
1054 * finite number of children can die, and it's pretty
1055 * pathological for a lot to die suddenly.
1059 else if (remaining_children_to_start) {
1060 /* we hit a 1 second timeout in which none of the previous
1061 * generation of children needed to be reaped... so assume
1062 * they're all done, and pick up the slack if any is left.
1064 startup_children(remaining_children_to_start);
1065 remaining_children_to_start = 0;
1066 /* In any event we really shouldn't do the code below because
1067 * few of the servers we just started are in the IDLE state
1068 * yet, so we'd mistakenly create an extra server.
1073 perform_idle_server_maintenance(pconf);
1075 shutdown_pending = os_check_server(tpf_server_name);
1082 if (shutdown_pending) {
1083 /* Time to gracefully shut down:
1084 * Kill child processes, tell them to call child_exit, etc...
1086 if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
1087 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGTERM");
1089 ap_reclaim_child_processes(1); /* Start with SIGTERM */
1091 /* cleanup pid file on normal shutdown */
1093 const char *pidfile = NULL;
1094 pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1095 if ( pidfile != NULL && unlink(pidfile) == 0)
1096 ap_log_error(APLOG_MARK, APLOG_INFO,
1098 "removed PID file %s (pid=%ld)",
1099 pidfile, (long)getpid());
1102 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1103 "caught SIGTERM, shutting down");
1107 /* we've been told to restart */
1108 apr_signal(SIGHUP, SIG_IGN);
1110 /* not worth thinking about */
1114 /* advance to the next generation */
1115 /* XXX: we really need to make sure this new generation number isn't in
1116 * use by any of the children.
1119 ap_scoreboard_image->global->running_generation = ap_my_generation;
1122 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1123 "Graceful restart requested, doing restart");
1125 /* kill off the idle ones */
1126 ap_mpm_pod_killpg(pod, ap_daemons_limit);
1128 /* This is mostly for debugging... so that we know what is still
1129 * gracefully dealing with existing request. This will break
1130 * in a very nasty way if we ever have the scoreboard totally
1131 * file-based (no shared memory)
1133 for (index = 0; index < ap_daemons_limit; ++index) {
1134 if (ap_scoreboard_image->servers[index][0].status != SERVER_DEAD) {
1135 ap_scoreboard_image->servers[index][0].status = SERVER_GRACEFUL;
1141 if (unixd_killpg(getpgrp(), SIGHUP) < 0) {
1142 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGHUP");
1144 ap_reclaim_child_processes(0); /* Not when just starting up */
1145 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1146 "SIGHUP received. Attempting to restart");
1152 /* This really should be a post_config hook, but the error log is already
1153 * redirected by that point, so we need to do this in the open_logs phase.
1155 static int prefork_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
1162 if ((num_listensocks = ap_setup_listeners(ap_server_conf)) < 1) {
1163 ap_log_error(APLOG_MARK, APLOG_ALERT|APLOG_STARTUP, 0,
1164 NULL, "no listening sockets available, shutting down");
1168 if ((rv = ap_mpm_pod_open(pconf, &pod))) {
1169 ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_STARTUP, rv, NULL,
1170 "Could not open pipe-of-death.");
1176 static int prefork_pre_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp)
1178 static int restart_num = 0;
1179 int no_detach, debug, foreground;
1182 debug = ap_exists_config_define("DEBUG");
1185 foreground = one_process = 1;
1190 no_detach = ap_exists_config_define("NO_DETACH");
1191 one_process = ap_exists_config_define("ONE_PROCESS");
1192 foreground = ap_exists_config_define("FOREGROUND");
1195 /* sigh, want this only the second time around */
1196 if (restart_num++ == 1) {
1199 if (!one_process && !foreground) {
1200 rv = apr_proc_detach(no_detach ? APR_PROC_DETACH_FOREGROUND
1201 : APR_PROC_DETACH_DAEMONIZE);
1202 if (rv != APR_SUCCESS) {
1203 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
1204 "apr_proc_detach failed");
1205 return HTTP_INTERNAL_SERVER_ERROR;
1209 parent_pid = ap_my_pid = getpid();
1212 unixd_pre_config(ptemp);
1213 ap_listen_pre_config();
1214 ap_daemons_to_start = DEFAULT_START_DAEMON;
1215 ap_daemons_min_free = DEFAULT_MIN_FREE_DAEMON;
1216 ap_daemons_max_free = DEFAULT_MAX_FREE_DAEMON;
1217 ap_daemons_limit = server_limit;
1218 ap_pid_fname = DEFAULT_PIDLOG;
1219 ap_lock_fname = DEFAULT_LOCKFILE;
1220 ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1221 ap_extended_status = 0;
1223 apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1228 static void prefork_hooks(apr_pool_t *p)
1230 /* The prefork open_logs phase must run before the core's, or stderr
1231 * will be redirected to a file, and the messages won't print to the
1234 static const char *const aszSucc[] = {"core.c", NULL};
1240 ap_hook_open_logs(prefork_open_logs, NULL, aszSucc, APR_HOOK_MIDDLE);
1241 ap_hook_pre_config(prefork_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
1244 static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy, const char *arg)
1246 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1251 ap_daemons_to_start = atoi(arg);
1255 static const char *set_min_free_servers(cmd_parms *cmd, void *dummy, const char *arg)
1257 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1262 ap_daemons_min_free = atoi(arg);
1263 if (ap_daemons_min_free <= 0) {
1264 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1265 "WARNING: detected MinSpareServers set to non-positive.");
1266 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1267 "Resetting to 1 to avoid almost certain Apache failure.");
1268 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1269 "Please read the documentation.");
1270 ap_daemons_min_free = 1;
1276 static const char *set_max_free_servers(cmd_parms *cmd, void *dummy, const char *arg)
1278 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1283 ap_daemons_max_free = atoi(arg);
1287 static const char *set_max_clients (cmd_parms *cmd, void *dummy, const char *arg)
1289 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1294 ap_daemons_limit = atoi(arg);
1295 if (ap_daemons_limit > server_limit) {
1296 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1297 "WARNING: MaxClients of %d exceeds ServerLimit value "
1298 "of %d servers,", ap_daemons_limit, server_limit);
1299 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1300 " lowering MaxClients to %d. To increase, please "
1301 "see the ServerLimit", server_limit);
1302 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1304 ap_daemons_limit = server_limit;
1306 else if (ap_daemons_limit < 1) {
1307 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1308 "WARNING: Require MaxClients > 0, setting to 1");
1309 ap_daemons_limit = 1;
1314 static const char *set_server_limit (cmd_parms *cmd, void *dummy, const char *arg)
1316 int tmp_server_limit;
1318 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1323 tmp_server_limit = atoi(arg);
1324 /* you cannot change ServerLimit across a restart; ignore
1327 if (first_server_limit &&
1328 tmp_server_limit != server_limit) {
1329 /* how do we log a message? the error log is a bit bucket at this
1330 * point; we'll just have to set a flag so that ap_mpm_run()
1331 * logs a warning later
1333 changed_limit_at_restart = 1;
1336 server_limit = tmp_server_limit;
1338 if (server_limit > MAX_SERVER_LIMIT) {
1339 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1340 "WARNING: ServerLimit of %d exceeds compile time limit "
1341 "of %d servers,", server_limit, MAX_SERVER_LIMIT);
1342 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1343 " lowering ServerLimit to %d.", MAX_SERVER_LIMIT);
1344 server_limit = MAX_SERVER_LIMIT;
1346 else if (server_limit < 1) {
1347 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1348 "WARNING: Require ServerLimit > 0, setting to 1");
1354 static const command_rec prefork_cmds[] = {
1355 UNIX_DAEMON_COMMANDS,
1357 AP_INIT_TAKE1("StartServers", set_daemons_to_start, NULL, RSRC_CONF,
1358 "Number of child processes launched at server startup"),
1359 AP_INIT_TAKE1("MinSpareServers", set_min_free_servers, NULL, RSRC_CONF,
1360 "Minimum number of idle children, to handle request spikes"),
1361 AP_INIT_TAKE1("MaxSpareServers", set_max_free_servers, NULL, RSRC_CONF,
1362 "Maximum number of idle children"),
1363 AP_INIT_TAKE1("MaxClients", set_max_clients, NULL, RSRC_CONF,
1364 "Maximum number of children alive at the same time"),
1365 AP_INIT_TAKE1("ServerLimit", set_server_limit, NULL, RSRC_CONF,
1366 "Maximum value of MaxClients for this run of Apache"),
1370 module AP_MODULE_DECLARE_DATA mpm_prefork_module = {
1372 ap_mpm_rewrite_args, /* hook to run before apache parses args */
1373 NULL, /* create per-directory config structure */
1374 NULL, /* merge per-directory config structures */
1375 NULL, /* create per-server config structure */
1376 NULL, /* merge per-server config structures */
1377 prefork_cmds, /* command apr_table_t */
1378 prefork_hooks, /* register hooks */