1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #include "apr_portable.h"
19 #include "apr_strings.h"
20 #include "apr_thread_proc.h"
21 #include "apr_signal.h"
23 #define APR_WANT_STDIO
24 #define APR_WANT_STRFUNC
30 #if APR_HAVE_SYS_TYPES_H
31 #include <sys/types.h>
36 #include "ap_config.h"
38 #include "mpm_default.h"
39 #include "http_main.h"
41 #include "http_config.h"
42 #include "http_core.h" /* for get_remote_host */
43 #include "http_connection.h"
44 #include "scoreboard.h"
47 #include "mpm_common.h"
48 #include "ap_listen.h"
53 #include <bstring.h> /* for IRIX, FD_SET calls bzero() */
58 #ifdef HAVE_SYS_PROCESSOR_H
59 #include <sys/processor.h> /* for bindprocessor() */
63 #include <sys/times.h>
65 /* Limit on the total --- clients will be locked out if more servers than
66 * this are needed. It is intended solely to keep the server from crashing
67 * when things get out of hand.
69 * We keep a hard maximum number of servers, for two reasons --- first off,
70 * in case something goes seriously wrong, we want to stop the fork bomb
71 * short of actually crashing the machine we're running on by filling some
72 * kernel table. Secondly, it keeps the size of the scoreboard file small
73 * enough that we can read the whole thing without worrying too much about
76 #ifndef DEFAULT_SERVER_LIMIT
77 #define DEFAULT_SERVER_LIMIT 256
80 /* Admin can't tune ServerLimit beyond MAX_SERVER_LIMIT. We want
81 * some sort of compile-time limit to help catch typos.
83 #ifndef MAX_SERVER_LIMIT
84 #define MAX_SERVER_LIMIT 20000
87 #ifndef HARD_THREAD_LIMIT
88 #define HARD_THREAD_LIMIT 1
93 int ap_threads_per_child=0; /* Worker threads per child */
94 static apr_proc_mutex_t *accept_mutex;
95 static int ap_daemons_to_start=0;
96 static int ap_daemons_min_free=0;
97 static int ap_daemons_max_free=0;
98 static int ap_daemons_limit=0; /* MaxClients */
99 static int server_limit = DEFAULT_SERVER_LIMIT;
100 static int first_server_limit;
101 static int changed_limit_at_restart;
102 static int mpm_state = AP_MPMQ_STARTING;
103 static ap_pod_t *pod;
106 * The max child slot ever assigned, preserved across restarts. Necessary
107 * to deal with MaxClients changes across AP_SIG_GRACEFUL restarts. We
108 * use this value to optimize routines that have to scan the entire scoreboard.
110 int ap_max_daemons_limit = -1;
111 server_rec *ap_server_conf;
113 /* one_process --- debugging mode variable; can be set from the command line
114 * with the -X flag. If set, this gets you the child_main loop running
115 * in the process which originally started up (no detach, no make_child),
116 * which is a pretty nice debugging environment. (You'll get a SIGHUP
117 * early in standalone_main; just continue through. This is the server
118 * trying to kill off any child processes which it might have lying
119 * around --- Apache doesn't keep track of their pids, it just sends
120 * SIGHUP to the process group, ignoring it in the root process.
121 * Continue through and you'll be fine.).
124 static int one_process = 0;
126 static apr_pool_t *pconf; /* Pool for config stuff */
127 static apr_pool_t *pchild; /* Pool for httpd child stuff */
129 static pid_t ap_my_pid; /* it seems silly to call getpid all the time */
130 static pid_t parent_pid;
132 static int my_child_num;
134 ap_generation_t volatile ap_my_generation=0;
138 char tpf_server_name[INETD_SERVNAME_LENGTH+1];
141 static int die_now = 0;
145 * change directory for gprof to plop the gmon.out file
146 * configure in httpd.conf:
147 * GprofDir $RuntimeDir/ -> $ServerRoot/$RuntimeDir/gmon.out
148 * GprofDir $RuntimeDir/% -> $ServerRoot/$RuntimeDir/gprof.$pid/gmon.out
150 static void chdir_for_gprof(void)
152 core_server_config *sconf =
153 ap_get_module_config(ap_server_conf->module_config, &core_module);
154 char *dir = sconf->gprof_dir;
160 int len = strlen(sconf->gprof_dir) - 1;
161 if(*(dir + len) == '%') {
163 apr_snprintf(buf, sizeof(buf), "%sgprof.%d", dir, (int)getpid());
165 use_dir = ap_server_root_relative(pconf, buf[0] ? buf : dir);
166 res = apr_dir_make(use_dir, 0755, pconf);
167 if(res != APR_SUCCESS && !APR_STATUS_IS_EEXIST(res)) {
168 ap_log_error(APLOG_MARK, APLOG_ERR, errno, ap_server_conf,
169 "gprof: error creating directory %s", dir);
173 use_dir = ap_server_root_relative(pconf, DEFAULT_REL_RUNTIMEDIR);
179 #define chdir_for_gprof()
182 /* XXX - I don't know if TPF will ever use this module or not, so leave
183 * the ap_check_signals calls in but disable them - manoj */
184 #define ap_check_signals()
186 /* a clean exit from a child with proper cleanup */
187 static void clean_child_exit(int code) __attribute__ ((noreturn));
188 static void clean_child_exit(int code)
190 mpm_state = AP_MPMQ_STOPPING;
193 apr_pool_destroy(pchild);
195 ap_mpm_pod_close(pod);
200 static void accept_mutex_on(void)
202 apr_status_t rv = apr_proc_mutex_lock(accept_mutex);
203 if (rv != APR_SUCCESS) {
204 const char *msg = "couldn't grab the accept mutex";
206 if (ap_my_generation !=
207 ap_scoreboard_image->global->running_generation) {
208 ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, NULL, msg);
212 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, msg);
213 exit(APEXIT_CHILDFATAL);
218 static void accept_mutex_off(void)
220 apr_status_t rv = apr_proc_mutex_unlock(accept_mutex);
221 if (rv != APR_SUCCESS) {
222 const char *msg = "couldn't release the accept mutex";
224 if (ap_my_generation !=
225 ap_scoreboard_image->global->running_generation) {
226 ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, NULL, msg);
227 /* don't exit here... we have a connection to
228 * process, after which point we'll see that the
229 * generation changed and we'll exit cleanly
233 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, msg);
234 exit(APEXIT_CHILDFATAL);
239 /* On some architectures it's safe to do unserialized accept()s in the single
240 * Listen case. But it's never safe to do it in the case where there's
241 * multiple Listen statements. Define SINGLE_LISTEN_UNSERIALIZED_ACCEPT
242 * when it's safe in the single Listen case.
244 #ifdef SINGLE_LISTEN_UNSERIALIZED_ACCEPT
245 #define SAFE_ACCEPT(stmt) do {if (ap_listeners->next) {stmt;}} while(0)
247 #define SAFE_ACCEPT(stmt) do {stmt;} while(0)
250 AP_DECLARE(apr_status_t) ap_mpm_query(int query_code, int *result)
253 case AP_MPMQ_MAX_DAEMON_USED:
254 *result = ap_daemons_limit;
256 case AP_MPMQ_IS_THREADED:
257 *result = AP_MPMQ_NOT_SUPPORTED;
259 case AP_MPMQ_IS_FORKED:
260 *result = AP_MPMQ_DYNAMIC;
262 case AP_MPMQ_HARD_LIMIT_DAEMONS:
263 *result = server_limit;
265 case AP_MPMQ_HARD_LIMIT_THREADS:
266 *result = HARD_THREAD_LIMIT;
268 case AP_MPMQ_MAX_THREADS:
271 case AP_MPMQ_MIN_SPARE_DAEMONS:
272 *result = ap_daemons_min_free;
274 case AP_MPMQ_MIN_SPARE_THREADS:
277 case AP_MPMQ_MAX_SPARE_DAEMONS:
278 *result = ap_daemons_max_free;
280 case AP_MPMQ_MAX_SPARE_THREADS:
283 case AP_MPMQ_MAX_REQUESTS_DAEMON:
284 *result = ap_max_requests_per_child;
286 case AP_MPMQ_MAX_DAEMONS:
287 *result = server_limit;
289 case AP_MPMQ_MPM_STATE:
296 #if defined(NEED_WAITPID)
298 Systems without a real waitpid sometimes lose a child's exit while waiting
299 for another. Search through the scoreboard for missing children.
301 int reap_children(int *exitcode, apr_exit_why_e *status)
305 for (n = 0; n < ap_max_daemons_limit; ++n) {
306 if (ap_scoreboard_image->servers[n][0].status != SERVER_DEAD &&
307 kill((pid = ap_scoreboard_image->parent[n].pid), 0) == -1) {
308 ap_update_child_status_from_indexes(n, 0, SERVER_DEAD, NULL);
309 /* just mark it as having a successful exit status */
310 *status = APR_PROC_EXIT;
319 /*****************************************************************
320 * Connection structures and accounting...
323 static void just_die(int sig)
328 /* volatile just in case */
329 static int volatile shutdown_pending;
330 static int volatile restart_pending;
331 static int volatile is_graceful;
333 static void sig_term(int sig)
335 if (shutdown_pending == 1) {
336 /* Um, is this _probably_ not an error, if the user has
337 * tried to do a shutdown twice quickly, so we won't
338 * worry about reporting it.
342 shutdown_pending = 1;
345 /* restart() is the signal handler for SIGHUP and AP_SIG_GRACEFUL
346 * in the parent process, unless running in ONE_PROCESS mode
348 static void restart(int sig)
350 if (restart_pending == 1) {
351 /* Probably not an error - don't bother reporting it */
355 is_graceful = (sig == AP_SIG_GRACEFUL);
358 static void set_signals(void)
360 #ifndef NO_USE_SIGACTION
365 ap_fatal_signal_setup(ap_server_conf, pconf);
368 #ifndef NO_USE_SIGACTION
369 sigemptyset(&sa.sa_mask);
372 sa.sa_handler = sig_term;
373 if (sigaction(SIGTERM, &sa, NULL) < 0)
374 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGTERM)");
376 if (sigaction(SIGINT, &sa, NULL) < 0)
377 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGINT)");
380 sa.sa_handler = SIG_DFL;
381 if (sigaction(SIGXCPU, &sa, NULL) < 0)
382 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXCPU)");
385 sa.sa_handler = SIG_DFL;
386 if (sigaction(SIGXFSZ, &sa, NULL) < 0)
387 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXFSZ)");
390 sa.sa_handler = SIG_IGN;
391 if (sigaction(SIGPIPE, &sa, NULL) < 0)
392 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGPIPE)");
395 /* we want to ignore HUPs and AP_SIG_GRACEFUL while we're busy
397 sigaddset(&sa.sa_mask, SIGHUP);
398 sigaddset(&sa.sa_mask, AP_SIG_GRACEFUL);
399 sa.sa_handler = restart;
400 if (sigaction(SIGHUP, &sa, NULL) < 0)
401 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGHUP)");
402 if (sigaction(AP_SIG_GRACEFUL, &sa, NULL) < 0)
403 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(" AP_SIG_GRACEFUL_STRING ")");
407 apr_signal(SIGXCPU, SIG_DFL);
410 apr_signal(SIGXFSZ, SIG_DFL);
414 apr_signal(SIGTERM, sig_term);
416 apr_signal(SIGHUP, restart);
418 #ifdef AP_SIG_GRACEFUL
419 apr_signal(AP_SIG_GRACEFUL, restart);
420 #endif /* AP_SIG_GRACEFUL */
422 apr_signal(SIGPIPE, SIG_IGN);
428 /*****************************************************************
429 * Child process main loop.
430 * The following vars are static to avoid getting clobbered by longjmp();
431 * they are really private to child_main.
434 static int requests_this_child;
435 static int num_listensocks = 0;
436 static ap_listen_rec *listensocks;
438 int ap_graceful_stop_signalled(void)
440 /* not ever called anymore... */
445 static void child_main(int child_num_arg)
448 apr_allocator_t *allocator;
449 conn_rec *current_conn;
450 apr_status_t status = APR_EINIT;
453 int curr_pollfd, last_pollfd = 0;
454 apr_pollfd_t *pollset;
459 apr_bucket_alloc_t *bucket_alloc;
461 mpm_state = AP_MPMQ_STARTING; /* for benefit of any hooks that run as this
465 my_child_num = child_num_arg;
466 ap_my_pid = getpid();
468 requests_this_child = 0;
470 ap_fatal_signal_child_setup(ap_server_conf);
472 /* Get a sub context for global allocations in this child, so that
473 * we can have cleanups occur when the child exits.
475 apr_allocator_create(&allocator);
476 apr_allocator_max_free_set(allocator, ap_max_mem_free);
477 apr_pool_create_ex(&pchild, pconf, NULL, allocator);
478 apr_allocator_owner_set(allocator, pchild);
480 apr_pool_create(&ptrans, pchild);
481 apr_pool_tag(ptrans, "transaction");
483 /* needs to be done before we switch UIDs so we have permissions */
484 ap_reopen_scoreboard(pchild, NULL, 0);
485 rv = apr_proc_mutex_child_init(&accept_mutex, ap_lock_fname, pchild);
486 if (rv != APR_SUCCESS) {
487 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
488 "Couldn't initialize cross-process lock in child");
489 clean_child_exit(APEXIT_CHILDFATAL);
492 if (unixd_setup_child()) {
493 clean_child_exit(APEXIT_CHILDFATAL);
496 ap_run_child_init(pchild, ap_server_conf);
498 ap_create_sb_handle(&sbh, pchild, my_child_num, 0);
500 (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
502 /* Set up the pollfd array */
503 listensocks = apr_pcalloc(pchild,
504 sizeof(*listensocks) * (num_listensocks));
505 for (lr = ap_listeners, i = 0; i < num_listensocks; lr = lr->next, i++) {
506 listensocks[i].accept_func = lr->accept_func;
507 listensocks[i].sd = lr->sd;
510 pollset = apr_palloc(pchild, sizeof(*pollset) * num_listensocks);
511 pollset[0].p = pchild;
512 for (i = 0; i < num_listensocks; i++) {
513 pollset[i].desc.s = listensocks[i].sd;
514 pollset[i].desc_type = APR_POLL_SOCKET;
515 pollset[i].reqevents = APR_POLLIN;
518 mpm_state = AP_MPMQ_RUNNING;
520 bucket_alloc = apr_bucket_alloc_create(pchild);
524 * (Re)initialize this child to a pre-connection state.
529 apr_pool_clear(ptrans);
531 if ((ap_max_requests_per_child > 0
532 && requests_this_child++ >= ap_max_requests_per_child)) {
536 (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
539 * Wait for an acceptable connection to arrive.
542 /* Lock around "accept", if necessary */
543 SAFE_ACCEPT(accept_mutex_on());
545 if (num_listensocks == 1) {
549 /* multiple listening sockets - need to poll */
554 ret = apr_poll(pollset, num_listensocks, &n, -1);
555 if (ret != APR_SUCCESS) {
556 if (APR_STATUS_IS_EINTR(ret)) {
559 /* Single Unix documents select as returning errnos
560 * EBADF, EINTR, and EINVAL... and in none of those
561 * cases does it make sense to continue. In fact
562 * on Linux 2.0.x we seem to end up with EFAULT
563 * occasionally, and we'd loop forever due to it.
565 ap_log_error(APLOG_MARK, APLOG_ERR, ret, ap_server_conf,
566 "apr_poll: (listen)");
569 /* find a listener */
570 curr_pollfd = last_pollfd;
573 if (curr_pollfd >= num_listensocks) {
576 /* XXX: Should we check for POLLERR? */
577 if (pollset[curr_pollfd].rtnevents & APR_POLLIN) {
578 last_pollfd = curr_pollfd;
579 offset = curr_pollfd;
582 } while (curr_pollfd != last_pollfd);
588 /* if we accept() something we don't want to die, so we have to
591 status = listensocks[offset].accept_func(&csd,
592 &listensocks[offset], ptrans);
593 SAFE_ACCEPT(accept_mutex_off()); /* unlock after "accept" */
595 if (status == APR_EGENERAL) {
596 /* resource shortage or should-not-occur occured */
599 else if (status != APR_SUCCESS) {
604 * We now have a connection, so set it up with the appropriate
605 * socket options, file descriptors, and read/write buffers.
608 current_conn = ap_run_create_connection(ptrans, ap_server_conf, csd, my_child_num, sbh, bucket_alloc);
610 ap_process_connection(current_conn, csd);
611 ap_lingering_close(current_conn);
614 /* Check the pod and the generation number after processing a
615 * connection so that we'll go away if a graceful restart occurred
616 * while we were processing the connection or we are the lucky
617 * idle server process that gets to die.
619 if (ap_mpm_pod_check(pod) == APR_SUCCESS) { /* selected as idle? */
622 else if (ap_my_generation !=
623 ap_scoreboard_image->global->running_generation) { /* restart? */
624 /* yeah, this could be non-graceful restart, in which case the
625 * parent will kill us soon enough, but why bother checking?
634 static int make_child(server_rec *s, int slot)
638 if (slot + 1 > ap_max_daemons_limit) {
639 ap_max_daemons_limit = slot + 1;
643 apr_signal(SIGHUP, just_die);
644 /* Don't catch AP_SIG_GRACEFUL in ONE_PROCESS mode :) */
645 apr_signal(SIGINT, just_die);
647 apr_signal(SIGQUIT, SIG_DFL);
649 apr_signal(SIGTERM, just_die);
653 (void) ap_update_child_status_from_indexes(slot, 0, SERVER_STARTING,
654 (request_rec *) NULL);
658 /* BS2000 requires a "special" version of fork() before a setuid() call */
659 if ((pid = os_fork(unixd_config.user_name)) == -1) {
661 if ((pid = os_fork(s, slot)) == -1) {
663 if ((pid = fork()) == -1) {
665 ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, "fork: Unable to fork new process");
667 /* fork didn't succeed. Fix the scoreboard or else
668 * it will say SERVER_STARTING forever and ever
670 (void) ap_update_child_status_from_indexes(slot, 0, SERVER_DEAD,
671 (request_rec *) NULL);
673 /* In case system resources are maxxed out, we don't want
674 Apache running away with the CPU trying to fork over and
675 over and over again. */
682 #ifdef HAVE_BINDPROCESSOR
683 /* by default AIX binds to a single processor
684 * this bit unbinds children which will then bind to another cpu
686 int status = bindprocessor(BINDPROCESS, (int)getpid(),
687 PROCESSOR_CLASS_ANY);
689 ap_log_error(APLOG_MARK, APLOG_WARNING, errno,
690 ap_server_conf, "processor unbind failed %d", status);
693 RAISE_SIGSTOP(MAKE_CHILD);
695 /* Disable the parent's signal handlers and set up proper handling in
698 apr_signal(SIGHUP, just_die);
699 apr_signal(SIGTERM, just_die);
700 /* The child process doesn't do anything for AP_SIG_GRACEFUL.
701 * Instead, the pod is used for signalling graceful restart.
703 apr_signal(AP_SIG_GRACEFUL, SIG_IGN);
707 ap_scoreboard_image->parent[slot].pid = pid;
713 /* start up a bunch of children */
714 static void startup_children(int number_to_start)
718 for (i = 0; number_to_start && i < ap_daemons_limit; ++i) {
719 if (ap_scoreboard_image->servers[i][0].status != SERVER_DEAD) {
722 if (make_child(ap_server_conf, i) < 0) {
731 * idle_spawn_rate is the number of children that will be spawned on the
732 * next maintenance cycle if there aren't enough idle servers. It is
733 * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
734 * without the need to spawn.
736 static int idle_spawn_rate = 1;
737 #ifndef MAX_SPAWN_RATE
738 #define MAX_SPAWN_RATE (32)
740 static int hold_off_on_exponential_spawning;
742 static void perform_idle_server_maintenance(apr_pool_t *p)
749 int free_slots[MAX_SPAWN_RATE];
753 /* initialize the free_list */
761 for (i = 0; i < ap_daemons_limit; ++i) {
764 if (i >= ap_max_daemons_limit && free_length == idle_spawn_rate)
766 ws = &ap_scoreboard_image->servers[i][0];
768 if (status == SERVER_DEAD) {
769 /* try to keep children numbers as low as possible */
770 if (free_length < idle_spawn_rate) {
771 free_slots[free_length] = i;
776 /* We consider a starting server as idle because we started it
777 * at least a cycle ago, and if it still hasn't finished starting
778 * then we're just going to swamp things worse by forking more.
779 * So we hopefully won't need to fork more if we count it.
780 * This depends on the ordering of SERVER_READY and SERVER_STARTING.
782 if (status <= SERVER_READY) {
784 /* always kill the highest numbered child if we have to...
785 * no really well thought out reason ... other than observing
786 * the server behaviour under linux where lower numbered children
787 * tend to service more hits (and hence are more likely to have
788 * their data in cpu caches).
797 ap_max_daemons_limit = last_non_dead + 1;
798 if (idle_count > ap_daemons_max_free) {
799 /* kill off one child... we use the pod because that'll cause it to
800 * shut down gracefully, in case it happened to pick up a request
801 * while we were counting
803 ap_mpm_pod_signal(pod);
806 else if (idle_count < ap_daemons_min_free) {
807 /* terminate the free list */
808 if (free_length == 0) {
809 /* only report this condition once */
810 static int reported = 0;
813 ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf,
814 "server reached MaxClients setting, consider"
815 " raising the MaxClients setting");
821 if (idle_spawn_rate >= 8) {
822 ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf,
823 "server seems busy, (you may need "
824 "to increase StartServers, or Min/MaxSpareServers), "
825 "spawning %d children, there are %d idle, and "
826 "%d total children", idle_spawn_rate,
827 idle_count, total_non_dead);
829 for (i = 0; i < free_length; ++i) {
831 if (make_child(ap_server_conf, free_slots[i]) == -1) {
832 if(free_length == 1) {
833 shutdown_pending = 1;
834 ap_log_error(APLOG_MARK, APLOG_EMERG, 0, ap_server_conf,
835 "No active child processes: shutting down");
839 make_child(ap_server_conf, free_slots[i]);
842 /* the next time around we want to spawn twice as many if this
843 * wasn't good enough, but not if we've just done a graceful
845 if (hold_off_on_exponential_spawning) {
846 --hold_off_on_exponential_spawning;
848 else if (idle_spawn_rate < MAX_SPAWN_RATE) {
849 idle_spawn_rate *= 2;
858 /*****************************************************************
859 * Executive routines.
862 int ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
865 int remaining_children_to_start;
868 ap_log_pid(pconf, ap_pid_fname);
870 first_server_limit = server_limit;
871 if (changed_limit_at_restart) {
872 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
873 "WARNING: Attempt to change ServerLimit "
874 "ignored during restart");
875 changed_limit_at_restart = 0;
878 /* Initialize cross-process accept lock */
879 ap_lock_fname = apr_psprintf(_pconf, "%s.%" APR_PID_T_FMT,
880 ap_server_root_relative(_pconf, ap_lock_fname),
883 rv = apr_proc_mutex_create(&accept_mutex, ap_lock_fname,
884 ap_accept_lock_mech, _pconf);
885 if (rv != APR_SUCCESS) {
886 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
887 "Couldn't create accept lock");
888 mpm_state = AP_MPMQ_STOPPING;
892 #if APR_USE_SYSVSEM_SERIALIZE
893 if (ap_accept_lock_mech == APR_LOCK_DEFAULT ||
894 ap_accept_lock_mech == APR_LOCK_SYSVSEM) {
896 if (ap_accept_lock_mech == APR_LOCK_SYSVSEM) {
898 rv = unixd_set_proc_mutex_perms(accept_mutex);
899 if (rv != APR_SUCCESS) {
900 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
901 "Couldn't set permissions on cross-process lock; "
902 "check User and Group directives");
903 mpm_state = AP_MPMQ_STOPPING;
909 if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
910 mpm_state = AP_MPMQ_STOPPING;
913 /* fix the generation number in the global score; we just got a new,
916 ap_scoreboard_image->global->running_generation = ap_my_generation;
925 if (ap_daemons_max_free < ap_daemons_min_free + 1) /* Don't thrash... */
926 ap_daemons_max_free = ap_daemons_min_free + 1;
928 /* If we're doing a graceful_restart then we're going to see a lot
929 * of children exiting immediately when we get into the main loop
930 * below (because we just sent them AP_SIG_GRACEFUL). This happens pretty
931 * rapidly... and for each one that exits we'll start a new one until
932 * we reach at least daemons_min_free. But we may be permitted to
933 * start more than that, so we'll just keep track of how many we're
934 * supposed to start up without the 1 second penalty between each fork.
936 remaining_children_to_start = ap_daemons_to_start;
937 if (remaining_children_to_start > ap_daemons_limit) {
938 remaining_children_to_start = ap_daemons_limit;
941 startup_children(remaining_children_to_start);
942 remaining_children_to_start = 0;
945 /* give the system some time to recover before kicking into
946 * exponential mode */
947 hold_off_on_exponential_spawning = 10;
950 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
951 "%s configured -- resuming normal operations",
952 ap_get_server_version());
953 ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf,
954 "Server built: %s", ap_get_server_built());
955 #ifdef AP_MPM_WANT_SET_ACCEPT_LOCK_MECH
956 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
957 "AcceptMutex: %s (default: %s)",
958 apr_proc_mutex_name(accept_mutex),
959 apr_proc_mutex_defname());
961 restart_pending = shutdown_pending = 0;
963 mpm_state = AP_MPMQ_RUNNING;
965 while (!restart_pending && !shutdown_pending) {
967 apr_exit_why_e exitwhy;
968 int status, processed_status;
969 /* this is a memory leak, but I'll fix it later. */
972 ap_wait_or_timeout(&exitwhy, &status, &pid, pconf);
974 /* XXX: if it takes longer than 1 second for all our children
975 * to start up and get into IDLE state then we may spawn an
979 processed_status = ap_process_child_status(&pid, exitwhy, status);
980 if (processed_status == APEXIT_CHILDFATAL) {
981 mpm_state = AP_MPMQ_STOPPING;
985 /* non-fatal death... note that it's gone in the scoreboard. */
986 child_slot = find_child_by_pid(&pid);
987 if (child_slot >= 0) {
988 (void) ap_update_child_status_from_indexes(child_slot, 0, SERVER_DEAD,
989 (request_rec *) NULL);
990 if (processed_status == APEXIT_CHILDSICK) {
991 /* child detected a resource shortage (E[NM]FILE, ENOBUFS, etc)
992 * cut the fork rate to the minimum
996 else if (remaining_children_to_start
997 && child_slot < ap_daemons_limit) {
998 /* we're still doing a 1-for-1 replacement of dead
999 * children with new children
1001 make_child(ap_server_conf, child_slot);
1002 --remaining_children_to_start;
1004 #if APR_HAS_OTHER_CHILD
1006 else if (apr_proc_other_child_read(&pid, status) == 0) {
1010 else if (is_graceful) {
1011 /* Great, we've probably just lost a slot in the
1012 * scoreboard. Somehow we don't know about this
1015 ap_log_error(APLOG_MARK, APLOG_WARNING,
1017 "long lost child came home! (pid %ld)", (long)pid.pid);
1019 /* Don't perform idle maintenance when a child dies,
1020 * only do it when there's a timeout. Remember only a
1021 * finite number of children can die, and it's pretty
1022 * pathological for a lot to die suddenly.
1026 else if (remaining_children_to_start) {
1027 /* we hit a 1 second timeout in which none of the previous
1028 * generation of children needed to be reaped... so assume
1029 * they're all done, and pick up the slack if any is left.
1031 startup_children(remaining_children_to_start);
1032 remaining_children_to_start = 0;
1033 /* In any event we really shouldn't do the code below because
1034 * few of the servers we just started are in the IDLE state
1035 * yet, so we'd mistakenly create an extra server.
1040 perform_idle_server_maintenance(pconf);
1042 shutdown_pending = os_check_server(tpf_server_name);
1048 mpm_state = AP_MPMQ_STOPPING;
1050 if (shutdown_pending) {
1051 /* Time to gracefully shut down:
1052 * Kill child processes, tell them to call child_exit, etc...
1054 if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
1055 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGTERM");
1057 ap_reclaim_child_processes(1); /* Start with SIGTERM */
1059 /* cleanup pid file on normal shutdown */
1061 const char *pidfile = NULL;
1062 pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1063 if ( pidfile != NULL && unlink(pidfile) == 0)
1064 ap_log_error(APLOG_MARK, APLOG_INFO,
1066 "removed PID file %s (pid=%ld)",
1067 pidfile, (long)getpid());
1070 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1071 "caught SIGTERM, shutting down");
1075 /* we've been told to restart */
1076 apr_signal(SIGHUP, SIG_IGN);
1078 /* not worth thinking about */
1082 /* advance to the next generation */
1083 /* XXX: we really need to make sure this new generation number isn't in
1084 * use by any of the children.
1087 ap_scoreboard_image->global->running_generation = ap_my_generation;
1090 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1091 "Graceful restart requested, doing restart");
1093 /* kill off the idle ones */
1094 ap_mpm_pod_killpg(pod, ap_max_daemons_limit);
1096 /* This is mostly for debugging... so that we know what is still
1097 * gracefully dealing with existing request. This will break
1098 * in a very nasty way if we ever have the scoreboard totally
1099 * file-based (no shared memory)
1101 for (index = 0; index < ap_daemons_limit; ++index) {
1102 if (ap_scoreboard_image->servers[index][0].status != SERVER_DEAD) {
1103 ap_scoreboard_image->servers[index][0].status = SERVER_GRACEFUL;
1109 if (unixd_killpg(getpgrp(), SIGHUP) < 0) {
1110 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGHUP");
1112 ap_reclaim_child_processes(0); /* Not when just starting up */
1113 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1114 "SIGHUP received. Attempting to restart");
1120 /* This really should be a post_config hook, but the error log is already
1121 * redirected by that point, so we need to do this in the open_logs phase.
1123 static int prefork_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
1130 if ((num_listensocks = ap_setup_listeners(ap_server_conf)) < 1) {
1131 ap_log_error(APLOG_MARK, APLOG_ALERT|APLOG_STARTUP, 0,
1132 NULL, "no listening sockets available, shutting down");
1136 if ((rv = ap_mpm_pod_open(pconf, &pod))) {
1137 ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_STARTUP, rv, NULL,
1138 "Could not open pipe-of-death.");
1144 static int prefork_pre_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp)
1146 static int restart_num = 0;
1147 int no_detach, debug, foreground;
1150 mpm_state = AP_MPMQ_STARTING;
1152 debug = ap_exists_config_define("DEBUG");
1155 foreground = one_process = 1;
1160 no_detach = ap_exists_config_define("NO_DETACH");
1161 one_process = ap_exists_config_define("ONE_PROCESS");
1162 foreground = ap_exists_config_define("FOREGROUND");
1165 /* sigh, want this only the second time around */
1166 if (restart_num++ == 1) {
1169 if (!one_process && !foreground) {
1170 rv = apr_proc_detach(no_detach ? APR_PROC_DETACH_FOREGROUND
1171 : APR_PROC_DETACH_DAEMONIZE);
1172 if (rv != APR_SUCCESS) {
1173 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
1174 "apr_proc_detach failed");
1175 return HTTP_INTERNAL_SERVER_ERROR;
1179 parent_pid = ap_my_pid = getpid();
1182 unixd_pre_config(ptemp);
1183 ap_listen_pre_config();
1184 ap_daemons_to_start = DEFAULT_START_DAEMON;
1185 ap_daemons_min_free = DEFAULT_MIN_FREE_DAEMON;
1186 ap_daemons_max_free = DEFAULT_MAX_FREE_DAEMON;
1187 ap_daemons_limit = server_limit;
1188 ap_pid_fname = DEFAULT_PIDLOG;
1189 ap_lock_fname = DEFAULT_LOCKFILE;
1190 ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1191 ap_extended_status = 0;
1192 #ifdef AP_MPM_WANT_SET_MAX_MEM_FREE
1193 ap_max_mem_free = APR_ALLOCATOR_MAX_FREE_UNLIMITED;
1196 apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1201 static void prefork_hooks(apr_pool_t *p)
1203 /* The prefork open_logs phase must run before the core's, or stderr
1204 * will be redirected to a file, and the messages won't print to the
1207 static const char *const aszSucc[] = {"core.c", NULL};
1213 ap_hook_open_logs(prefork_open_logs, NULL, aszSucc, APR_HOOK_MIDDLE);
1214 /* we need to set the MPM state before other pre-config hooks use MPM query
1215 * to retrieve it, so register as REALLY_FIRST
1217 ap_hook_pre_config(prefork_pre_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
1220 static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy, const char *arg)
1222 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1227 ap_daemons_to_start = atoi(arg);
1231 static const char *set_min_free_servers(cmd_parms *cmd, void *dummy, const char *arg)
1233 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1238 ap_daemons_min_free = atoi(arg);
1239 if (ap_daemons_min_free <= 0) {
1240 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1241 "WARNING: detected MinSpareServers set to non-positive.");
1242 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1243 "Resetting to 1 to avoid almost certain Apache failure.");
1244 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1245 "Please read the documentation.");
1246 ap_daemons_min_free = 1;
1252 static const char *set_max_free_servers(cmd_parms *cmd, void *dummy, const char *arg)
1254 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1259 ap_daemons_max_free = atoi(arg);
1263 static const char *set_max_clients (cmd_parms *cmd, void *dummy, const char *arg)
1265 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1270 ap_daemons_limit = atoi(arg);
1271 if (ap_daemons_limit > server_limit) {
1272 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1273 "WARNING: MaxClients of %d exceeds ServerLimit value "
1274 "of %d servers,", ap_daemons_limit, server_limit);
1275 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1276 " lowering MaxClients to %d. To increase, please "
1277 "see the ServerLimit", server_limit);
1278 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1280 ap_daemons_limit = server_limit;
1282 else if (ap_daemons_limit < 1) {
1283 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1284 "WARNING: Require MaxClients > 0, setting to 1");
1285 ap_daemons_limit = 1;
1290 static const char *set_server_limit (cmd_parms *cmd, void *dummy, const char *arg)
1292 int tmp_server_limit;
1294 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1299 tmp_server_limit = atoi(arg);
1300 /* you cannot change ServerLimit across a restart; ignore
1303 if (first_server_limit &&
1304 tmp_server_limit != server_limit) {
1305 /* how do we log a message? the error log is a bit bucket at this
1306 * point; we'll just have to set a flag so that ap_mpm_run()
1307 * logs a warning later
1309 changed_limit_at_restart = 1;
1312 server_limit = tmp_server_limit;
1314 if (server_limit > MAX_SERVER_LIMIT) {
1315 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1316 "WARNING: ServerLimit of %d exceeds compile time limit "
1317 "of %d servers,", server_limit, MAX_SERVER_LIMIT);
1318 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1319 " lowering ServerLimit to %d.", MAX_SERVER_LIMIT);
1320 server_limit = MAX_SERVER_LIMIT;
1322 else if (server_limit < 1) {
1323 ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1324 "WARNING: Require ServerLimit > 0, setting to 1");
1330 static const command_rec prefork_cmds[] = {
1331 UNIX_DAEMON_COMMANDS,
1333 AP_INIT_TAKE1("StartServers", set_daemons_to_start, NULL, RSRC_CONF,
1334 "Number of child processes launched at server startup"),
1335 AP_INIT_TAKE1("MinSpareServers", set_min_free_servers, NULL, RSRC_CONF,
1336 "Minimum number of idle children, to handle request spikes"),
1337 AP_INIT_TAKE1("MaxSpareServers", set_max_free_servers, NULL, RSRC_CONF,
1338 "Maximum number of idle children"),
1339 AP_INIT_TAKE1("MaxClients", set_max_clients, NULL, RSRC_CONF,
1340 "Maximum number of children alive at the same time"),
1341 AP_INIT_TAKE1("ServerLimit", set_server_limit, NULL, RSRC_CONF,
1342 "Maximum value of MaxClients for this run of Apache"),
1346 module AP_MODULE_DECLARE_DATA mpm_prefork_module = {
1348 ap_mpm_rewrite_args, /* hook to run before apache parses args */
1349 NULL, /* create per-directory config structure */
1350 NULL, /* merge per-directory config structures */
1351 NULL, /* create per-server config structure */
1352 NULL, /* merge per-server config structures */
1353 prefork_cmds, /* command apr_table_t */
1354 prefork_hooks, /* register hooks */