prefork.c revision 40965c37b2fd320093215de6c3fbd516382077ea
* contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. /* Limit on the total --- clients will be locked out if more servers than * this are needed. It is intended solely to keep the server from crashing * when things get out of hand. * We keep a hard maximum number of servers, for two reasons --- first off, * in case something goes seriously wrong, we want to stop the fork bomb * short of actually crashing the machine we're running on by filling some * kernel table. Secondly, it keeps the size of the scoreboard file small * enough that we can read the whole thing without worrying too much about /* Admin can't tune ServerLimit beyond MAX_SERVER_LIMIT. We want * some sort of compile-time limit to help catch typos. /* data retained by prefork across load/unload of the module * allocated on first call to pre-config hook; located on * subsequent calls to pre-config hook * The max child slot ever assigned, preserved across restarts. Necessary * to deal with MaxClients changes across AP_SIG_GRACEFUL restarts. We * use this value to optimize routines that have to scan the entire scoreboard. /* one_process --- debugging mode variable; can be set from the command line * with the -X flag. If set, this gets you the child_main loop running * in the process which originally started up (no detach, no make_child), * which is a pretty nice debugging environment. (You'll get a SIGHUP * early in standalone_main; just continue through. This is the server * trying to kill off any child processes which it might have lying * around --- Apache doesn't keep track of their pids, it just sends * SIGHUP to the process group, ignoring it in the root process. * Continue through and you'll be fine.). static pid_t ap_my_pid;
/* it seems silly to call getpid all the time */ * change directory for gprof to plop the gmon.out file "gprof: error creating directory %s",
dir);
/* a clean exit from a child with proper cleanup */ const char *
msg =
"couldn't grab the accept mutex";
const char *
msg =
"couldn't release the accept mutex";
/* don't exit here... we have a connection to * process, after which point we'll see that the * generation changed and we'll exit cleanly /* On some architectures it's safe to do unserialized accept()s in the single * Listen case. But it's never safe to do it in the case where there's * multiple Listen statements. Define SINGLE_LISTEN_UNSERIALIZED_ACCEPT * when it's safe in the single Listen case. /***************************************************************** * Connection structures and accounting... /* For a graceful stop, we want the child to exit when done */ /* volatile just in case */ /* Um, is this _probably_ not an error, if the user has * tried to do a shutdown twice quickly, so we won't * worry about reporting it. /* restart() is the signal handler for SIGHUP and AP_SIG_GRACEFUL * in the parent process, unless running in ONE_PROCESS mode /* Probably not an error - don't bother reporting it */ /* we want to ignore HUPs and AP_SIG_GRACEFUL while we're busy #
endif /* AP_SIG_GRACEFUL */#
endif /* AP_SIG_GRACEFUL *//***************************************************************** * Child process main loop. * The following vars are static to avoid getting clobbered by longjmp(); * they are really private to child_main. /* Get a sub context for global allocations in this child, so that * we can have cleanups occur when the child exits. /* needs to be done before we switch UIDs so we have permissions */ "Couldn't initialize cross-process lock in child " /* Set up the pollfd array */ "Couldn't create pollset in child; check system or user limits");
"Couldn't add listener to pollset; check system or user limits");
/* die_now is set when AP_SIG_GRACEFUL is received in the child; * shutdown_pending is set when SIGTERM is received when running * in single process mode. */ * (Re)initialize this child to a pre-connection state. * Wait for an acceptable connection to arrive. /* Lock around "accept", if necessary */ /* There is only one listener record, so refer to that one. */ /* multiple listening sockets - need to poll */ /* check for termination first so we don't sleep for a while in * poll if already signalled * and terminate the child. */ /* timeout == 10 seconds to avoid a hang at graceful restart/stop * caused by the closing of sockets by the signal handler /* Single Unix documents select as returning errnos * EBADF, EINTR, and EINVAL... and in none of those * cases does it make sense to continue. In fact * on Linux 2.0.x we seem to end up with EFAULT * occasionally, and we'd loop forever due to it. /* We can always use pdesc[0], but sockets at position N * could end up completely starved of attention in a very * busy server. Therefore, we round-robin across the * returned set of descriptors. While it is possible that * the returned set of descriptors might flip around and * continue to starve some sockets, we happen to know the * internal pollset implementation retains ordering * stability of the sockets. Thus, the round-robin should * ensure that a socket will eventually be serviced. /* Grab a listener record from the client_data of the poll * descriptor, and advance our saved index to round-robin * ### hmm... this descriptor might have POLLERR rather /* if we accept() something we don't want to die, so we have to /* resource shortage or should-not-occur occured */ * We now have a connection, so set it up with the appropriate * socket options, file descriptors, and read/write buffers. /* Check the pod and the generation number after processing a * connection so that we'll go away if a graceful restart occurred * while we were processing the connection or we are the lucky * idle server process that gets to die. /* yeah, this could be non-graceful restart, in which case the * parent will kill us soon enough, but why bother checking? /* Don't catch AP_SIG_GRACEFUL in ONE_PROCESS mode :) */ /* BS2000 requires a "special" version of fork() before a setuid() call */ /* fork didn't succeed. Fix the scoreboard or else * it will say SERVER_STARTING forever and ever /* In case system resources are maxxed out, we don't want * Apache running away with the CPU trying to fork over and /* by default AIX binds to a single processor * this bit unbinds children which will then bind to another cpu /* Disable the parent's signal handlers and set up proper handling in /* The child process just closes listeners on AP_SIG_GRACEFUL. * The pod is used for signalling the graceful restart. /* start up a bunch of children */ * idle_spawn_rate is the number of children that will be spawned on the * next maintenance cycle if there aren't enough idle servers. It is * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by * without the need to spawn. /* initialize the free_list */ /* try to keep children numbers as low as possible */ /* We consider a starting server as idle because we started it * at least a cycle ago, and if it still hasn't finished starting * then we're just going to swamp things worse by forking more. * So we hopefully won't need to fork more if we count it. * This depends on the ordering of SERVER_READY and SERVER_STARTING. /* always kill the highest numbered child if we have to... * no really well thought out reason ... other than observing * the server behaviour under linux where lower numbered children * tend to service more hits (and hence are more likely to have * their data in cpu caches). /* kill off one child... we use the pod because that'll cause it to * shut down gracefully, in case it happened to pick up a request /* terminate the free list */ /* only report this condition once */ "server reached MaxClients setting, consider" " raising the MaxClients setting");
"server seems busy, (you may need " "spawning %d children, there are %d idle, and " /* the next time around we want to spawn twice as many if this * wasn't good enough, but not if we've just done a graceful /***************************************************************** /* Initialize cross-process accept lock */ "Couldn't create accept lock (%s) (%d)",
"Couldn't set permissions on cross-process lock; " "check User and Group directives");
/* fix the generation number in the global score; we just got a new, /* If we're doing a graceful_restart then we're going to see a lot * of children exiting immediately when we get into the main loop * below (because we just sent them AP_SIG_GRACEFUL). This happens pretty * rapidly... and for each one that exits we'll start a new one until * we reach at least daemons_min_free. But we may be permitted to * start more than that, so we'll just keep track of how many we're * supposed to start up without the 1 second penalty between each fork. /* give the system some time to recover before kicking into "%s configured -- resuming normal operations",
"AcceptMutex: %s (default: %s)",
/* this is a memory leak, but I'll fix it later. */ /* XXX: if it takes longer than 1 second for all our children * to start up and get into IDLE state then we may spawn an /* non-fatal death... note that it's gone in the scoreboard. */ /* child detected a resource shortage (E[NM]FILE, ENOBUFS, etc) * cut the fork rate to the minimum /* we're still doing a 1-for-1 replacement of dead * children with new children /* Great, we've probably just lost a slot in the * scoreboard. Somehow we don't know about this "long lost child came home! (pid %ld)", (
long)
pid.
pid);
/* Don't perform idle maintenance when a child dies, * only do it when there's a timeout. Remember only a * finite number of children can die, and it's pretty * pathological for a lot to die suddenly. /* we hit a 1 second timeout in which none of the previous * generation of children needed to be reaped... so assume * they're all done, and pick up the slack if any is left. /* In any event we really shouldn't do the code below because * few of the servers we just started are in the IDLE state * yet, so we'd mistakenly create an extra server. * Kill child processes, tell them to call child_exit, etc... /* cleanup pid file on normal shutdown */ "removed PID file %s (pid=%ld)",
"caught SIGTERM, shutting down");
/* Time to perform a graceful shut down: * Reap the inactive children, and ask the active ones * to close their listeners, then wait until they are /* kill off the idle ones */ /* Send SIGUSR1 to the active children */ /* Ask each child to close its listeners. */ /* Allow each child which actually finished to exit */ "removed PID file %s (pid=%ld)",
/* Don't really exit until each child has finished */ /* Relieve any children which have now exited */ /* Having just one child is enough to stay around */ /* We might be here because we received SIGTERM, either * way, try and make sure that all of our processes are /* we've been told to restart */ /* not worth thinking about */ /* advance to the next generation */ /* XXX: we really need to make sure this new generation number isn't in * use by any of the children. "Graceful restart requested, doing restart");
/* kill off the idle ones */ /* This is mostly for debugging... so that we know what is still * gracefully dealing with existing request. This will break * in a very nasty way if we ever have the scoreboard totally * file-based (no shared memory) /* Ask each child to close its listeners. * NOTE: we use the scoreboard, because if we send SIGUSR1 * to every process in the group, this may include CGI's, * piped loggers, etc. They almost certainly won't handle "SIGHUP received. Attempting to restart");
/* This really should be a post_config hook, but the error log is already * redirected by that point, so we need to do this in the open_logs phase. /* the reverse of pre_config, we want this only the first time around */ "no listening sockets available, shutting down");
"could not open pipe-of-death");
/* sigh, want this only the second time around */ "apr_proc_detach failed");
/* the reverse of pre_config, we want this only the first time around */ "WARNING: ServerLimit of %d exceeds compile-time " " %d servers, decreasing to %d.",
"ServerLimit of %d exceeds compile-time limit " "of %d, decreasing to match",
"WARNING: ServerLimit of %d not allowed, " "ServerLimit of %d not allowed, increasing to 1",
/* you cannot change ServerLimit across a restart; ignore /* don't need a startup console version here */ "changing ServerLimit to %d from original value of %d " "not allowed during restart",
"WARNING: MaxClients of %d exceeds ServerLimit " " %d servers, decreasing MaxClients to %d.",
" To increase, please see the ServerLimit " "MaxClients of %d exceeds ServerLimit value " "of %d, decreasing to match",
"WARNING: MaxClients of %d not allowed, " "MaxClients of %d not allowed, increasing to 1",
/* ap_daemons_to_start > ap_daemons_limit checked in prefork_run() */ "WARNING: StartServers of %d not allowed, " "StartServers of %d not allowed, increasing to 1",
"WARNING: MinSpareServers of %d not allowed, " " to avoid almost certain server failure.");
" Please read the documentation.");
"MinSpareServers of %d not allowed, increasing to 1",
/* ap_daemons_max_free < ap_daemons_min_free + 1 checked in prefork_run() */ /* Our open_logs hook function must run before the core's, or stderr * will be redirected to a file, and the messages won't print to the /* we need to set the MPM state before other pre-config hooks use MPM query * to retrieve it, so register as REALLY_FIRST "Number of child processes launched at server startup"),
"Minimum number of idle children, to handle request spikes"),
"Maximum number of idle children"),
"Maximum number of children alive at the same time"),
"Maximum value of MaxClients for this run of Apache"),
NULL,
/* hook to run before apache parses args */ NULL,
/* create per-directory config structure */ NULL,
/* merge per-directory config structures */ NULL,
/* create per-server config structure */ NULL,
/* merge per-server config structures */