1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000-2001 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"
94 #include <bstring.h> /* for IRIX, FD_SET calls bzero() */
99 #ifdef HAVE_SYS_PROCESSOR_H
100 #include <sys/processor.h> /* for bindprocessor() */
104 #include <sys/times.h>
106 /* Limit on the total --- clients will be locked out if more servers than
107 * this are needed. It is intended solely to keep the server from crashing
108 * when things get out of hand.
110 * We keep a hard maximum number of servers, for two reasons --- first off,
111 * in case something goes seriously wrong, we want to stop the fork bomb
112 * short of actually crashing the machine we're running on by filling some
113 * kernel table. Secondly, it keeps the size of the scoreboard file small
114 * enough that we can read the whole thing without worrying too much about
117 #ifndef DEFAULT_SERVER_LIMIT
118 #define DEFAULT_SERVER_LIMIT 256
121 /* Admin can't tune ServerLimit beyond MAX_SERVER_LIMIT. We want
122 * some sort of compile-time limit to help catch typos.
124 #ifndef MAX_SERVER_LIMIT
125 #define MAX_SERVER_LIMIT 20000
128 #ifndef HARD_THREAD_LIMIT
129 #define HARD_THREAD_LIMIT 1
134 int ap_threads_per_child=0; /* Worker threads per child */
135 static apr_proc_mutex_t *accept_mutex;
136 static int ap_daemons_to_start=0;
137 static int ap_daemons_min_free=0;
138 static int ap_daemons_max_free=0;
139 static int ap_daemons_limit=0; /* MaxClients */
140 static int server_limit = DEFAULT_SERVER_LIMIT;
141 static int first_server_limit;
142 static int changed_limit_at_restart;
144 static ap_pod_t *pod;
147 * The max child slot ever assigned, preserved across restarts. Necessary
148 * to deal with MaxClients changes across AP_SIG_GRACEFUL restarts. We
149 * use this value to optimize routines that have to scan the entire scoreboard.
151 int ap_max_daemons_limit = -1;
152 server_rec *ap_server_conf;
154 /* one_process --- debugging mode variable; can be set from the command line
155 * with the -X flag. If set, this gets you the child_main loop running
156 * in the process which originally started up (no detach, no make_child),
157 * which is a pretty nice debugging environment. (You'll get a SIGHUP
158 * early in standalone_main; just continue through. This is the server
159 * trying to kill off any child processes which it might have lying
160 * around --- Apache doesn't keep track of their pids, it just sends
161 * SIGHUP to the process group, ignoring it in the root process.
162 * Continue through and you'll be fine.).
165 static int one_process = 0;
167 static apr_pool_t *pconf; /* Pool for config stuff */
168 static apr_pool_t *pchild; /* Pool for httpd child stuff */
170 static pid_t ap_my_pid; /* it seems silly to call getpid all the time */
171 static pid_t parent_pid;
173 static int my_child_num;
178 char tpf_server_name[INETD_SERVNAME_LENGTH+1];
181 static int die_now = 0;
185 * change directory for gprof to plop the gmon.out file
186 * configure in httpd.conf:
187 * GprofDir logs/ -> $ServerRoot/logs/gmon.out
188 * GprofDir logs/% -> $ServerRoot/logs/gprof.$pid/gmon.out
190 static void chdir_for_gprof(void)
192 core_server_config *sconf =
193 ap_get_module_config(ap_server_conf->module_config, &core_module);
194 char *dir = sconf->gprof_dir;
200 int len = strlen(sconf->gprof_dir) - 1;
201 if(*(dir + len) == '%') {
203 apr_snprintf(buf, sizeof(buf), "%sgprof.%d", dir, (int)getpid());
205 use_dir = ap_server_root_relative(pconf, buf[0] ? buf : dir);
206 res = apr_dir_make(use_dir, 0755, pconf);
207 if(res != APR_SUCCESS && !APR_STATUS_IS_EEXIST(res)) {
208 ap_log_error(APLOG_MARK, APLOG_ERR, errno, ap_server_conf,
209 "gprof: error creating directory %s", dir);
213 use_dir = ap_server_root_relative(pconf, "logs");
219 #define chdir_for_gprof()
222 /* XXX - I don't know if TPF will ever use this module or not, so leave
223 * the ap_check_signals calls in but disable them - manoj */
224 #define ap_check_signals()
226 /* a clean exit from a child with proper cleanup */
227 static void clean_child_exit(int code) __attribute__ ((noreturn));
228 static void clean_child_exit(int code)
231 apr_pool_destroy(pchild);
233 ap_mpm_pod_close(pod);
238 static void accept_mutex_on(void)
240 apr_status_t rv = apr_proc_mutex_lock(accept_mutex);
241 if (rv != APR_SUCCESS) {
242 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "couldn't grab the accept mutex");
243 exit(APEXIT_CHILDFATAL);
247 static void accept_mutex_off(void)
249 apr_status_t rv = apr_proc_mutex_unlock(accept_mutex);
250 if (rv != APR_SUCCESS) {
251 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "couldn't release the accept mutex");
252 exit(APEXIT_CHILDFATAL);
256 /* On some architectures it's safe to do unserialized accept()s in the single
257 * Listen case. But it's never safe to do it in the case where there's
258 * multiple Listen statements. Define SINGLE_LISTEN_UNSERIALIZED_ACCEPT
259 * when it's safe in the single Listen case.
261 #ifdef SINGLE_LISTEN_UNSERIALIZED_ACCEPT
262 #define SAFE_ACCEPT(stmt) do {if (ap_listeners->next) {stmt;}} while(0)
264 #define SAFE_ACCEPT(stmt) do {stmt;} while(0)
267 AP_DECLARE(apr_status_t) ap_mpm_query(int query_code, int *result)
270 case AP_MPMQ_MAX_DAEMON_USED:
271 *result = ap_daemons_limit;
273 case AP_MPMQ_IS_THREADED:
274 *result = AP_MPMQ_NOT_SUPPORTED;
276 case AP_MPMQ_IS_FORKED:
277 *result = AP_MPMQ_DYNAMIC;
279 case AP_MPMQ_HARD_LIMIT_DAEMONS:
280 *result = server_limit;
282 case AP_MPMQ_HARD_LIMIT_THREADS:
283 *result = HARD_THREAD_LIMIT;
285 case AP_MPMQ_MAX_THREADS:
288 case AP_MPMQ_MIN_SPARE_DAEMONS:
289 *result = ap_daemons_min_free;
291 case AP_MPMQ_MIN_SPARE_THREADS:
294 case AP_MPMQ_MAX_SPARE_DAEMONS:
295 *result = ap_daemons_max_free;
297 case AP_MPMQ_MAX_SPARE_THREADS:
300 case AP_MPMQ_MAX_REQUESTS_DAEMON:
301 *result = ap_max_requests_per_child;
303 case AP_MPMQ_MAX_DAEMONS:
304 *result = ap_daemons_limit;
310 #if defined(NEED_WAITPID)
312 Systems without a real waitpid sometimes lose a child's exit while waiting
313 for another. Search through the scoreboard for missing children.
315 int reap_children(int *exitcode, apr_exit_why_e *status)
319 for (n = 0; n < ap_max_daemons_limit; ++n) {
320 ap_sync_scoreboard_image();
321 if (ap_scoreboard_image->servers[n][0].status != SERVER_DEAD &&
322 kill((pid = ap_scoreboard_image->parent[n].pid), 0) == -1) {
323 ap_update_child_status_from_indexes(n, 0, SERVER_DEAD, NULL);
324 /* just mark it as having a successful exit status */
325 *status = APR_PROC_EXIT;
334 /* handle all varieties of core dumping signals */
335 static void sig_coredump(int sig)
337 chdir(ap_coredump_dir);
338 apr_signal(sig, SIG_DFL);
339 if (ap_my_pid == parent_pid) {
340 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE,
342 "seg fault or similar nasty error detected "
343 "in the parent process");
346 /* At this point we've got sig blocked, because we're still inside
347 * the signal handler. When we leave the signal handler it will
348 * be unblocked, and we'll take the signal... and coredump or whatever
349 * is appropriate for this particular Unix. In addition the parent
350 * will see the real signal we received -- whereas if we called
351 * abort() here, the parent would only see SIGABRT.
355 /*****************************************************************
356 * Connection structures and accounting...
359 static void just_die(int sig)
364 /* volatile just in case */
365 static int volatile shutdown_pending;
366 static int volatile restart_pending;
367 static int volatile is_graceful;
368 ap_generation_t volatile ap_my_generation=0;
370 static void sig_term(int sig)
372 if (shutdown_pending == 1) {
373 /* Um, is this _probably_ not an error, if the user has
374 * tried to do a shutdown twice quickly, so we won't
375 * worry about reporting it.
379 shutdown_pending = 1;
382 /* restart() is the signal handler for SIGHUP and AP_SIG_GRACEFUL
383 * in the parent process, unless running in ONE_PROCESS mode
385 static void restart(int sig)
387 if (restart_pending == 1) {
388 /* Probably not an error - don't bother reporting it */
392 if ((is_graceful = (sig == AP_SIG_GRACEFUL))) {
393 apr_pool_cleanup_kill(pconf, NULL, ap_cleanup_scoreboard);
397 static void set_signals(void)
399 #ifndef NO_USE_SIGACTION
402 sigemptyset(&sa.sa_mask);
406 sa.sa_handler = sig_coredump;
407 #if defined(SA_ONESHOT)
408 sa.sa_flags = SA_ONESHOT;
409 #elif defined(SA_RESETHAND)
410 sa.sa_flags = SA_RESETHAND;
412 if (sigaction(SIGSEGV, &sa, NULL) < 0)
413 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGSEGV)");
415 if (sigaction(SIGBUS, &sa, NULL) < 0)
416 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGBUS)");
419 if (sigaction(SIGABORT, &sa, NULL) < 0)
420 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABORT)");
423 if (sigaction(SIGABRT, &sa, NULL) < 0)
424 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABRT)");
427 if (sigaction(SIGILL, &sa, NULL) < 0)
428 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGILL)");
432 sa.sa_handler = sig_term;
433 if (sigaction(SIGTERM, &sa, NULL) < 0)
434 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGTERM)");
436 if (sigaction(SIGINT, &sa, NULL) < 0)
437 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGINT)");
440 sa.sa_handler = SIG_DFL;
441 if (sigaction(SIGXCPU, &sa, NULL) < 0)
442 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXCPU)");
445 sa.sa_handler = SIG_DFL;
446 if (sigaction(SIGXFSZ, &sa, NULL) < 0)
447 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXFSZ)");
450 sa.sa_handler = SIG_IGN;
451 if (sigaction(SIGPIPE, &sa, NULL) < 0)
452 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGPIPE)");
455 /* we want to ignore HUPs and AP_SIG_GRACEFUL while we're busy
457 sigaddset(&sa.sa_mask, SIGHUP);
458 sigaddset(&sa.sa_mask, AP_SIG_GRACEFUL);
459 sa.sa_handler = restart;
460 if (sigaction(SIGHUP, &sa, NULL) < 0)
461 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGHUP)");
462 if (sigaction(AP_SIG_GRACEFUL, &sa, NULL) < 0)
463 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(" AP_SIG_GRACEFUL_STRING ")");
466 apr_signal(SIGSEGV, sig_coredump);
468 apr_signal(SIGBUS, sig_coredump);
471 apr_signal(SIGABORT, sig_coredump);
472 #endif /* SIGABORT */
474 apr_signal(SIGABRT, sig_coredump);
477 apr_signal(SIGILL, sig_coredump);
480 apr_signal(SIGXCPU, SIG_DFL);
483 apr_signal(SIGXFSZ, SIG_DFL);
487 apr_signal(SIGTERM, sig_term);
489 apr_signal(SIGHUP, restart);
491 #ifdef AP_SIG_GRACEFUL
492 apr_signal(AP_SIG_GRACEFUL, restart);
493 #endif /* AP_SIG_GRACEFUL */
495 apr_signal(SIGPIPE, SIG_IGN);
501 /*****************************************************************
502 * Child process main loop.
503 * The following vars are static to avoid getting clobbered by longjmp();
504 * they are really private to child_main.
507 static int requests_this_child;
508 static int num_listensocks = 0;
509 static ap_listen_rec *listensocks;
511 int ap_graceful_stop_signalled(void)
513 /* not ever called anymore... */
518 static void child_main(int child_num_arg)
521 conn_rec *current_conn;
522 apr_status_t status = APR_EINIT;
525 int curr_pollfd, last_pollfd = 0;
526 apr_pollfd_t *pollset;
532 my_child_num = child_num_arg;
533 ap_my_pid = getpid();
535 requests_this_child = 0;
537 /* Get a sub context for global allocations in this child, so that
538 * we can have cleanups occur when the child exits.
540 apr_pool_create_ex(&pchild, pconf, NULL, APR_POOL_FNEW_ALLOCATOR);
542 apr_pool_create(&ptrans, pchild);
543 apr_pool_tag(ptrans, "transaction");
545 /* needs to be done before we switch UIDs so we have permissions */
546 ap_reopen_scoreboard(pchild, NULL, 0);
547 rv = apr_proc_mutex_child_init(&accept_mutex, ap_lock_fname, pchild);
548 if (rv != APR_SUCCESS) {
549 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
550 "Couldn't initialize cross-process lock in child");
551 clean_child_exit(APEXIT_CHILDFATAL);
554 if (unixd_setup_child()) {
555 clean_child_exit(APEXIT_CHILDFATAL);
558 ap_run_child_init(pchild, ap_server_conf);
560 ap_create_sb_handle(&sbh, pchild, my_child_num, 0);
562 (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
564 ap_sync_scoreboard_image();
566 /* Set up the pollfd array */
567 listensocks = apr_pcalloc(pchild,
568 sizeof(*listensocks) * (num_listensocks));
569 for (lr = ap_listeners, i = 0; i < num_listensocks; lr = lr->next, i++) {
570 listensocks[i].accept_func = lr->accept_func;
571 listensocks[i].sd = lr->sd;
574 apr_poll_setup(&pollset, num_listensocks, pchild);
575 for (i = 0; i < num_listensocks; i++)
576 apr_poll_socket_add(pollset, listensocks[i].sd, APR_POLLIN);
580 * (Re)initialize this child to a pre-connection state.
585 apr_pool_clear(ptrans);
587 if ((ap_max_requests_per_child > 0
588 && requests_this_child++ >= ap_max_requests_per_child)) {
592 (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
595 * Wait for an acceptable connection to arrive.
598 /* Lock around "accept", if necessary */
599 SAFE_ACCEPT(accept_mutex_on());
601 if (num_listensocks == 1) {
605 /* multiple listening sockets - need to poll */
611 ret = apr_poll(pollset, &n, -1);
612 if (ret != APR_SUCCESS) {
613 if (APR_STATUS_IS_EINTR(ret)) {
616 /* Single Unix documents select as returning errnos
617 * EBADF, EINTR, and EINVAL... and in none of those
618 * cases does it make sense to continue. In fact
619 * on Linux 2.0.x we seem to end up with EFAULT
620 * occasionally, and we'd loop forever due to it.
622 ap_log_error(APLOG_MARK, APLOG_ERR, ret, ap_server_conf,
623 "apr_poll: (listen)");
626 /* find a listener */
627 curr_pollfd = last_pollfd;
630 if (curr_pollfd >= num_listensocks) {
633 /* XXX: Should we check for POLLERR? */
634 apr_poll_revents_get(&event, listensocks[curr_pollfd].sd, pollset);
635 if (event & APR_POLLIN) {
636 last_pollfd = curr_pollfd;
637 offset = curr_pollfd;
640 } while (curr_pollfd != last_pollfd);
646 /* if we accept() something we don't want to die, so we have to
650 ap_sync_scoreboard_image();
651 status = listensocks[offset].accept_func(&csd,
652 &listensocks[offset], ptrans);
654 if (status == APR_SUCCESS) {
657 if (status == APR_EGENERAL) {
658 /* resource shortage or should-not-occur occured */
662 SAFE_ACCEPT(accept_mutex_off()); /* unlock after "accept" */
665 * We now have a connection, so set it up with the appropriate
666 * socket options, file descriptors, and read/write buffers.
669 current_conn = ap_run_create_connection(ptrans, ap_server_conf, csd, my_child_num, sbh);
671 ap_process_connection(current_conn, csd);
672 ap_lingering_close(current_conn);
675 /* Check the pod after processing a connection so that we'll go away
676 * if a graceful restart occurred while we were processing the
677 * connection. Otherwise, we won't wake up until a real connection
678 * comes in and we'll use the wrong config to process it and we may
679 * block in the wrong syscall (because the new generation is using a
680 * different accept mutex) and in general it is goofy.
682 if (!ap_mpm_pod_check(pod)) {
685 ap_sync_scoreboard_image();
691 static int make_child(server_rec *s, int slot)
695 if (slot + 1 > ap_max_daemons_limit) {
696 ap_max_daemons_limit = slot + 1;
700 apr_signal(SIGHUP, just_die);
701 /* Don't catch AP_SIG_GRACEFUL in ONE_PROCESS mode :) */
702 apr_signal(SIGINT, just_die);
704 apr_signal(SIGQUIT, SIG_DFL);
706 apr_signal(SIGTERM, just_die);
710 (void) ap_update_child_status_from_indexes(slot, 0, SERVER_STARTING,
711 (request_rec *) NULL);
715 /* BS2000 requires a "special" version of fork() before a setuid() call */
716 if ((pid = os_fork(unixd_config.user_name)) == -1) {
718 if ((pid = os_fork(s, slot)) == -1) {
720 if ((pid = fork()) == -1) {
722 ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, "fork: Unable to fork new process");
724 /* fork didn't succeed. Fix the scoreboard or else
725 * it will say SERVER_STARTING forever and ever
727 (void) ap_update_child_status_from_indexes(slot, 0, SERVER_DEAD,
728 (request_rec *) NULL);
730 /* In case system resources are maxxed out, we don't want
731 Apache running away with the CPU trying to fork over and
732 over and over again. */
739 #ifdef HAVE_BINDPROCESSOR
740 /* by default AIX binds to a single processor
741 * this bit unbinds children which will then bind to another cpu
743 int status = bindprocessor(BINDPROCESS, (int)getpid(),
744 PROCESSOR_CLASS_ANY);
746 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, errno,
747 ap_server_conf, "processor unbind failed %d", status);
750 RAISE_SIGSTOP(MAKE_CHILD);
752 /* Disable the parent's signal handlers and set up proper handling in
755 apr_signal(SIGHUP, just_die);
756 apr_signal(SIGTERM, just_die);
757 /* The child process doesn't do anything for AP_SIG_GRACEFUL.
758 * Instead, the pod is used for signalling graceful restart.
760 apr_signal(AP_SIG_GRACEFUL, SIG_IGN);
764 ap_scoreboard_image->parent[slot].pid = pid;
765 #ifdef SCOREBOARD_FILE
766 lseek(scoreboard_fd, APR_XtOffsetOf(scoreboard, parent[slot]), 0);
767 force_write(scoreboard_fd, &ap_scoreboard_image->parent[slot],
768 sizeof(process_score));
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->servers[i][0].status != SERVER_DEAD) {
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(apr_pool_t *p)
811 int free_slots[MAX_SPAWN_RATE];
815 /* initialize the free_list */
823 ap_sync_scoreboard_image();
824 for (i = 0; i < ap_daemons_limit; ++i) {
827 if (i >= ap_max_daemons_limit && free_length == idle_spawn_rate)
829 ws = &ap_scoreboard_image->servers[i][0];
831 if (status == SERVER_DEAD) {
832 /* try to keep children numbers as low as possible */
833 if (free_length < idle_spawn_rate) {
834 free_slots[free_length] = i;
839 /* We consider a starting server as idle because we started it
840 * at least a cycle ago, and if it still hasn't finished starting
841 * then we're just going to swamp things worse by forking more.
842 * So we hopefully won't need to fork more if we count it.
843 * This depends on the ordering of SERVER_READY and SERVER_STARTING.
845 if (status <= SERVER_READY) {
847 /* always kill the highest numbered child if we have to...
848 * no really well thought out reason ... other than observing
849 * the server behaviour under linux where lower numbered children
850 * tend to service more hits (and hence are more likely to have
851 * their data in cpu caches).
860 ap_max_daemons_limit = last_non_dead + 1;
861 if (idle_count > ap_daemons_max_free) {
862 /* kill off one child... we use the pod because that'll cause it to
863 * shut down gracefully, in case it happened to pick up a request
864 * while we were counting
866 ap_mpm_pod_signal(pod);
869 else if (idle_count < ap_daemons_min_free) {
870 /* terminate the free list */
871 if (free_length == 0) {
872 /* only report this condition once */
873 static int reported = 0;
876 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, ap_server_conf,
877 "server reached MaxClients setting, consider"
878 " raising the MaxClients setting");
884 if (idle_spawn_rate >= 8) {
885 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, ap_server_conf,
886 "server seems busy, (you may need "
887 "to increase StartServers, or Min/MaxSpareServers), "
888 "spawning %d children, there are %d idle, and "
889 "%d total children", idle_spawn_rate,
890 idle_count, total_non_dead);
892 for (i = 0; i < free_length; ++i) {
894 if (make_child(ap_server_conf, free_slots[i]) == -1) {
895 if(free_length == 1) {
896 shutdown_pending = 1;
897 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_EMERG, 0, ap_server_conf,
898 "No active child processes: shutting down");
902 make_child(ap_server_conf, free_slots[i]);
905 /* the next time around we want to spawn twice as many if this
906 * wasn't good enough, but not if we've just done a graceful
908 if (hold_off_on_exponential_spawning) {
909 --hold_off_on_exponential_spawning;
911 else if (idle_spawn_rate < MAX_SPAWN_RATE) {
912 idle_spawn_rate *= 2;
921 /*****************************************************************
922 * Executive routines.
925 int ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
928 int remaining_children_to_start;
931 ap_log_pid(pconf, ap_pid_fname);
933 first_server_limit = server_limit;
934 if (changed_limit_at_restart) {
935 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_NOERRNO, 0, s,
936 "WARNING: Attempt to change ServerLimit "
937 "ignored during restart");
938 changed_limit_at_restart = 0;
941 /* Initialize cross-process accept lock */
942 ap_lock_fname = apr_psprintf(_pconf, "%s.%" APR_OS_PROC_T_FMT,
943 ap_server_root_relative(_pconf, ap_lock_fname),
946 rv = apr_proc_mutex_create(&accept_mutex, ap_lock_fname,
947 ap_accept_lock_mech, _pconf);
948 if (rv != APR_SUCCESS) {
949 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
950 "Couldn't create accept lock");
954 #if APR_USE_SYSVSEM_SERIALIZE
955 if (ap_accept_lock_mech == APR_LOCK_DEFAULT ||
956 ap_accept_lock_mech == APR_LOCK_SYSVSEM) {
958 if (ap_accept_lock_mech == APR_LOCK_SYSVSEM) {
960 rv = unixd_set_proc_mutex_perms(accept_mutex);
961 if (rv != APR_SUCCESS) {
962 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
963 "Couldn't set permissions on cross-process lock");
969 if (ap_run_pre_mpm(pconf, SB_SHARED) != OK) {
973 #ifdef SCOREBOARD_FILE
975 ap_scoreboard_fname = ap_server_root_relative(pconf, ap_scoreboard_fname);
976 ap_note_cleanups_for_fd(pconf, scoreboard_fd);
986 if (ap_daemons_max_free < ap_daemons_min_free + 1) /* Don't thrash... */
987 ap_daemons_max_free = ap_daemons_min_free + 1;
989 /* If we're doing a graceful_restart then we're going to see a lot
990 * of children exiting immediately when we get into the main loop
991 * below (because we just sent them AP_SIG_GRACEFUL). This happens pretty
992 * rapidly... and for each one that exits we'll start a new one until
993 * we reach at least daemons_min_free. But we may be permitted to
994 * start more than that, so we'll just keep track of how many we're
995 * supposed to start up without the 1 second penalty between each fork.
997 remaining_children_to_start = ap_daemons_to_start;
998 if (remaining_children_to_start > ap_daemons_limit) {
999 remaining_children_to_start = ap_daemons_limit;
1002 startup_children(remaining_children_to_start);
1003 remaining_children_to_start = 0;
1006 /* give the system some time to recover before kicking into
1007 * exponential mode */
1008 hold_off_on_exponential_spawning = 10;
1011 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1012 "%s configured -- resuming normal operations",
1013 ap_get_server_version());
1014 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, ap_server_conf,
1015 "Server built: %s", ap_get_server_built());
1016 restart_pending = shutdown_pending = 0;
1018 while (!restart_pending && !shutdown_pending) {
1020 apr_exit_why_e exitwhy;
1021 int status, processed_status;
1022 /* this is a memory leak, but I'll fix it later. */
1025 ap_wait_or_timeout(&exitwhy, &status, &pid, pconf);
1027 /* XXX: if it takes longer than 1 second for all our children
1028 * to start up and get into IDLE state then we may spawn an
1031 if (pid.pid != -1) {
1032 processed_status = ap_process_child_status(&pid, exitwhy, status);
1033 if (processed_status == APEXIT_CHILDFATAL) {
1037 /* non-fatal death... note that it's gone in the scoreboard. */
1038 ap_sync_scoreboard_image();
1039 child_slot = find_child_by_pid(&pid);
1040 if (child_slot >= 0) {
1041 (void) ap_update_child_status_from_indexes(child_slot, 0, SERVER_DEAD,
1042 (request_rec *) NULL);
1043 if (processed_status == APEXIT_CHILDSICK) {
1044 /* child detected a resource shortage (E[NM]FILE, ENOBUFS, etc)
1045 * cut the fork rate to the minimum
1047 idle_spawn_rate = 1;
1049 else if (remaining_children_to_start
1050 && child_slot < ap_daemons_limit) {
1051 /* we're still doing a 1-for-1 replacement of dead
1052 * children with new children
1054 make_child(ap_server_conf, child_slot);
1055 --remaining_children_to_start;
1057 #if APR_HAS_OTHER_CHILD
1059 else if (apr_proc_other_child_read(&pid, status) == 0) {
1063 else if (is_graceful) {
1064 /* Great, we've probably just lost a slot in the
1065 * scoreboard. Somehow we don't know about this
1068 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING,
1070 "long lost child came home! (pid %ld)", (long)pid.pid);
1072 /* Don't perform idle maintenance when a child dies,
1073 * only do it when there's a timeout. Remember only a
1074 * finite number of children can die, and it's pretty
1075 * pathological for a lot to die suddenly.
1079 else if (remaining_children_to_start) {
1080 /* we hit a 1 second timeout in which none of the previous
1081 * generation of children needed to be reaped... so assume
1082 * they're all done, and pick up the slack if any is left.
1084 startup_children(remaining_children_to_start);
1085 remaining_children_to_start = 0;
1086 /* In any event we really shouldn't do the code below because
1087 * few of the servers we just started are in the IDLE state
1088 * yet, so we'd mistakenly create an extra server.
1093 perform_idle_server_maintenance(pconf);
1095 shutdown_pending = os_check_server(tpf_server_name);
1101 if (shutdown_pending) {
1102 /* Time to gracefully shut down:
1103 * Kill child processes, tell them to call child_exit, etc...
1105 if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
1106 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGTERM");
1108 ap_reclaim_child_processes(1); /* Start with SIGTERM */
1110 /* cleanup pid file on normal shutdown */
1112 const char *pidfile = NULL;
1113 pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1114 if ( pidfile != NULL && unlink(pidfile) == 0)
1115 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO,
1117 "removed PID file %s (pid=%ld)",
1118 pidfile, (long)getpid());
1121 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1122 "caught SIGTERM, shutting down");
1126 /* we've been told to restart */
1127 apr_signal(SIGHUP, SIG_IGN);
1129 /* not worth thinking about */
1133 /* advance to the next generation */
1134 /* XXX: we really need to make sure this new generation number isn't in
1135 * use by any of the children.
1138 ap_scoreboard_image->global->running_generation = ap_my_generation;
1139 update_scoreboard_global();
1142 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1143 "Graceful restart requested, doing restart");
1145 /* kill off the idle ones */
1146 ap_mpm_pod_killpg(pod, ap_daemons_limit);
1148 #ifndef SCOREBOARD_FILE
1149 /* This is mostly for debugging... so that we know what is still
1150 * gracefully dealing with existing request. But we can't really
1151 * do it if we're in a SCOREBOARD_FILE because it'll cause
1152 * corruption too easily.
1154 ap_sync_scoreboard_image();
1155 for (index = 0; index < ap_daemons_limit; ++index) {
1156 if (ap_scoreboard_image->servers[index][0].status != SERVER_DEAD) {
1157 ap_scoreboard_image->servers[index][0].status = SERVER_GRACEFUL;
1164 if (unixd_killpg(getpgrp(), SIGHUP) < 0) {
1165 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGHUP");
1167 ap_reclaim_child_processes(0); /* Not when just starting up */
1168 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, ap_server_conf,
1169 "SIGHUP received. Attempting to restart");
1175 /* This really should be a post_config hook, but the error log is already
1176 * redirected by that point, so we need to do this in the open_logs phase.
1178 static int prefork_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
1185 if ((num_listensocks = ap_setup_listeners(ap_server_conf)) < 1) {
1186 ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ALERT|APLOG_STARTUP, 0,
1187 NULL, "no listening sockets available, shutting down");
1191 if ((rv = ap_mpm_pod_open(pconf, &pod))) {
1192 ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_STARTUP, rv, NULL,
1193 "Could not open pipe-of-death.");
1199 static int prefork_pre_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp)
1201 static int restart_num = 0;
1202 int no_detach, debug;
1205 debug = ap_exists_config_define("DEBUG");
1208 no_detach = one_process = 1;
1211 no_detach = ap_exists_config_define("NO_DETACH");
1212 one_process = ap_exists_config_define("ONE_PROCESS");
1215 /* sigh, want this only the second time around */
1216 if (restart_num++ == 1) {
1220 rv = apr_proc_detach(no_detach ? APR_PROC_DETACH_FOREGROUND
1221 : APR_PROC_DETACH_DAEMONIZE);
1222 if (rv != APR_SUCCESS) {
1223 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
1224 "apr_proc_detach failed");
1225 return HTTP_INTERNAL_SERVER_ERROR;
1229 parent_pid = ap_my_pid = getpid();
1232 unixd_pre_config(ptemp);
1233 ap_listen_pre_config();
1234 ap_daemons_to_start = DEFAULT_START_DAEMON;
1235 ap_daemons_min_free = DEFAULT_MIN_FREE_DAEMON;
1236 ap_daemons_max_free = DEFAULT_MAX_FREE_DAEMON;
1237 ap_daemons_limit = server_limit;
1238 ap_pid_fname = DEFAULT_PIDLOG;
1239 ap_lock_fname = DEFAULT_LOCKFILE;
1240 ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1241 ap_extended_status = 0;
1243 apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1248 static void prefork_hooks(apr_pool_t *p)
1250 /* The prefork open_logs phase must run before the core's, or stderr
1251 * will be redirected to a file, and the messages won't print to the
1254 static const char *const aszSucc[] = {"core.c", NULL};
1260 ap_hook_open_logs(prefork_open_logs, NULL, aszSucc, APR_HOOK_MIDDLE);
1261 ap_hook_pre_config(prefork_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
1264 static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy, const char *arg)
1266 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1271 ap_daemons_to_start = atoi(arg);
1275 static const char *set_min_free_servers(cmd_parms *cmd, void *dummy, const char *arg)
1277 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1282 ap_daemons_min_free = atoi(arg);
1283 if (ap_daemons_min_free <= 0) {
1284 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1285 "WARNING: detected MinSpareServers set to non-positive.");
1286 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1287 "Resetting to 1 to avoid almost certain Apache failure.");
1288 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1289 "Please read the documentation.");
1290 ap_daemons_min_free = 1;
1296 static const char *set_max_free_servers(cmd_parms *cmd, void *dummy, const char *arg)
1298 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1303 ap_daemons_max_free = atoi(arg);
1307 static const char *set_max_clients (cmd_parms *cmd, void *dummy, const char *arg)
1309 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1314 ap_daemons_limit = atoi(arg);
1315 if (ap_daemons_limit > server_limit) {
1316 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1317 "WARNING: MaxClients of %d exceeds ServerLimit value "
1318 "of %d servers,", ap_daemons_limit, server_limit);
1319 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1320 " lowering MaxClients to %d. To increase, please "
1321 "see the ServerLimit", server_limit);
1322 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1324 ap_daemons_limit = server_limit;
1326 else if (ap_daemons_limit < 1) {
1327 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1328 "WARNING: Require MaxClients > 0, setting to 1");
1329 ap_daemons_limit = 1;
1334 static const char *set_server_limit (cmd_parms *cmd, void *dummy, const char *arg)
1336 int tmp_server_limit;
1338 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1343 tmp_server_limit = atoi(arg);
1344 /* you cannot change ServerLimit across a restart; ignore
1347 if (first_server_limit &&
1348 tmp_server_limit != server_limit) {
1349 /* how do we log a message? the error log is a bit bucket at this
1350 * point; we'll just have to set a flag so that ap_mpm_run()
1351 * logs a warning later
1353 changed_limit_at_restart = 1;
1356 server_limit = tmp_server_limit;
1358 if (server_limit > MAX_SERVER_LIMIT) {
1359 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1360 "WARNING: ServerLimit of %d exceeds compile time limit "
1361 "of %d servers,", server_limit, MAX_SERVER_LIMIT);
1362 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1363 " lowering ServerLimit to %d.", MAX_SERVER_LIMIT);
1364 server_limit = MAX_SERVER_LIMIT;
1366 else if (server_limit < 1) {
1367 ap_log_error(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL,
1368 "WARNING: Require ServerLimit > 0, setting to 1");
1374 static const command_rec prefork_cmds[] = {
1375 UNIX_DAEMON_COMMANDS,
1377 AP_INIT_TAKE1("StartServers", set_daemons_to_start, NULL, RSRC_CONF,
1378 "Number of child processes launched at server startup"),
1379 AP_INIT_TAKE1("MinSpareServers", set_min_free_servers, NULL, RSRC_CONF,
1380 "Minimum number of idle children, to handle request spikes"),
1381 AP_INIT_TAKE1("MaxSpareServers", set_max_free_servers, NULL, RSRC_CONF,
1382 "Maximum number of idle children"),
1383 AP_INIT_TAKE1("MaxClients", set_max_clients, NULL, RSRC_CONF,
1384 "Maximum number of children alive at the same time"),
1385 AP_INIT_TAKE1("ServerLimit", set_server_limit, NULL, RSRC_CONF,
1386 "Maximum value of MaxClients for this run of Apache"),
1390 module AP_MODULE_DECLARE_DATA mpm_prefork_module = {
1392 NULL, /* hook to run before apache parses args */
1393 NULL, /* create per-directory config structure */
1394 NULL, /* merge per-directory config structures */
1395 NULL, /* create per-server config structure */
1396 NULL, /* merge per-server config structures */
1397 prefork_cmds, /* command apr_table_t */
1398 prefork_hooks, /* register hooks */