worker.c revision 00b8146bf5d1f543ce19917c6b4fe252d33baf79
6498N/A/* ==================================================================== 6498N/A * The Apache Software License, Version 1.1 6498N/A * Copyright (c) 2000-2001 The Apache Software Foundation. All rights 6498N/A * Redistribution and use in source and binary forms, with or without 6498N/A * modification, are permitted provided that the following conditions 6498N/A * 1. Redistributions of source code must retain the above copyright 6498N/A * notice, this list of conditions and the following disclaimer. 6498N/A * 2. Redistributions in binary form must reproduce the above copyright 6498N/A * notice, this list of conditions and the following disclaimer in 6498N/A * the documentation and/or other materials provided with the 6498N/A * 3. The end-user documentation included with the redistribution, 6498N/A * if any, must include the following acknowledgment: 6498N/A * "This product includes software developed by the 6498N/A * Alternately, this acknowledgment may appear in the software itself, 6498N/A * if and wherever such third-party acknowledgments normally appear. 6498N/A * 4. The names "Apache" and "Apache Software Foundation" must 6498N/A * not be used to endorse or promote products derived from this 6498N/A * software without prior written permission. For written 6498N/A * permission, please contact apache@apache.org. 6498N/A * 5. Products derived from this software may not be called "Apache", 6498N/A * nor may "Apache" appear in their name, without prior written 6498N/A * permission of the Apache Software Foundation. 6498N/A * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED 6498N/A * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 6498N/A * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 6498N/A * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR 6498N/A * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 6498N/A * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 6498N/A * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF 6498N/A * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 6498N/A * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 6498N/A * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 6498N/A * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 6498N/A * ==================================================================== 6498N/A * This software consists of voluntary contributions made by many 6498N/A * individuals on behalf of the Apache Software Foundation. For more 6498N/A * information on the Apache Software Foundation, please see 6498N/A * Portions of this software are based upon public domain software 6498N/A * originally written at the National Center for Supercomputing Applications, 6498N/A * University of Illinois, Urbana-Champaign. 6498N/A/* The purpose of this MPM is to fix the design flaws in the threaded 6498N/A * model. Because of the way that pthreads and mutex locks interact, 6498N/A * it is basically impossible to cleanly gracefully shutdown a child 6498N/A * process if multiple threads are all blocked in accept. This model * Actual definitions of config globals /* The structure used to pass unique initialization info to each thread */ /* Structure used to pass information to the thread responsible for * creating the rest of the threads. * The max child slot ever assigned, preserved across restarts. Necessary * to deal with MaxClients changes across SIGWINCH restarts. We use this * value to optimize routines that have to scan the entire scoreboard. consumes one character */ /* *Non*-shared http_main globals... */ /* 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.). thread. Use this instead */ /* Keep track of the number of worker threads currently active */ /* Locks for accept serialization */ /* a clean exit from a child with proper cleanup */ /* handle all varieties of core dumping signals */ "seg fault or similar nasty error detected " "in the parent process");
/* XXX we can probably add some rudimentary cleanup code here, * like getting rid of the pid file. If any additional bad stuff * happens, we are protected from recursive errors taking down the * system since this function is no longer the signal handler GLA /* At this point we've got sig blocked, because we're still inside * the signal handler. When we leave the signal handler it will * be unblocked, and we'll take the signal... and coredump or whatever * is appropriate for this particular Unix. In addition the parent * will see the real signal we received -- whereas if we called * abort() here, the parent would only see SIGABRT. /***************************************************************** * Connection structures and accounting... /* volatile just in case */ * ap_start_shutdown() and ap_start_restart(), below, are a first stab at * functions to initiate shutdown or restart without relying on signals. * Previously this was initiated in sig_term() and restart() signal handlers, * e.g. on Win32, from the service manager. Now the service manager can * call ap_start_shutdown() or ap_start_restart() as appropiate. Note that * these functions can also be called by the child processes, since global * variables are no longer used to pass on the required action to the parent. * These should only be called from the parent process itself, since the * parent process will use the shutdown_pending and restart_pending variables * to determine whether to shutdown or restart. The child process should * call signal_parent() directly to tell the parent to die -- this will * cause neither of those variable to be set, which the parent will * assume means something serious is wrong (which it will be, for the * child to force an exit) and so do an exit anyway. /* 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. /* do a graceful restart if graceful == 1 */ /* Probably not an error - don't bother reporting it */ /* we want to ignore HUPs and WINCH while we're busy processing one */ /***************************************************************** * Here follows a long bunch of generic server bookkeeping stuff... /* XXX this is really a bad confusing obsolete name * maybe it should be ap_mpm_process_exiting? /***************************************************************** * Child process main loop. "new file descriptor %d is too large; you probably need " "to rebuild Apache with a larger FD_SETSIZE " /* requests_this_child has gone to zero or below. See if the admin coded "MaxRequestsPerChild 0", and keep going in that case. Doing it this way simplifies the hot path in worker_thread */ /* wow! if you're executing this code, you may have set a record. * either this child process has served over 2 billion requests, or * you're running a threaded 2.0 on a 16 bit machine. * I'll buy pizza and beers at Apachecon for the first person to do * the former without cheating (dorking with INT_MAX, or running with * uncommitted performance patches, for example). * for the latter case, you probably deserve a beer too. Greg Ames /* Sets workers_may_exit if we received a character on the pipe_of_death */ /* It lost the lottery. It must continue to suffer * through a life of servitude. */ /* It won the lottery (or something else is very * wrong). Embrace death with open arms. */ /* TODO: Switch to a system where threads reuse the results from earlier "apr_lock_acquire failed. Attempting to shutdown " /* apr_poll() will only return errors in catastrophic * circumstances. Let's try exiting gracefully, for now. */ /* A process got a signal on the shutdown pipe. Check if we're * the lucky process to die. */ /* XXX: Should we check for POLLERR? */ "apr_lock_release failed. Attempting to shutdown " "apr_lock_release failed. Attempting to shutdown " "malloc: out of memory");
/* We are creating threads right now */ /* We let each thread update its own scoreboard entry. This is * done because it lets us deal with tid better. "apr_thread_create: unable to create worker thread");
/* In case system resources are maxxed out, we don't want Apache running away with the CPU trying to fork over and over and over again if we exit. */ sleep(
1);
/* wait for previous generation to clean up an entry */ /* What state should this child_main process be listed as in the scoreboard...? * ap_update_child_status(my_child_num, i, SERVER_STARTING, (request_rec *) NULL); * This state should be listed separately in the scoreboard, in some kind * of process_status, not mixed in with the worker threads' status. * "life_status" is almost right, but it's in the worker's structure, and * the name could be clearer. gla /*stuff to do before we switch id's, so we have permissions.*/ "Couldn't initialize cross-process lock in child");
/*done with init critical section */ "Couldn't initialize signal thread");
/* coding a value of zero means infinity */ /* Set up the pollfd array */ /* Setup worker threads */ /* clear the storage; we may not create all our threads immediately, and we want * a 0 entry to indicate a thread which was not created "malloc: out of memory");
"apr_thread_create: unable to create worker thread");
/* In case system resources are maxxed out, we don't want Apache running away with the CPU trying to fork over and over and over again if we exit. */ * the dispatch of the signal thread * beats the Pipe of Death and the browsers /* A terminating signal was received. Now join each of the workers to clean them up. * If the worker already exited, then the join frees their resources and returns. * If the worker hasn't exited, then this blocks until they have (then cleans up). if (
threads[i]) {
/* if we ever created this thread */ /* 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. "processor unbind failed %d",
status);
/* If there aren't many connections coming in from the network, the child * processes may need to be awakened from their network i/o waits. * The pipe of death is an effective prod. /* 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 */ /* Initialization to satisfy the compiler. It doesn't know * that ap_threads_per_child is always > 0 */ /* XXX any_dying_threads is probably no longer needed GLA */ /* 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. /* XXX the following shouldn't be necessary if we clean up * properly after seg faults, but we're not yet GLA && (!
ps->
pid /* no process in the slot */ ||
ps->
quiescing)) {
/* or at least one is going away */ /* great! we prefer these, because the new process can * start more threads sooner. So prioritize this slot * by putting it ahead of any slots with active threads. * first, make room by moving a slot that's potentially still * in use to the end of the array /* slot is still in use - back of the bus /* XXX if (!ps->quiescing) is probably more reliable GLA */ /* terminate the free list */ /* only report this condition once */ "server reached MaxClients setting, consider" " raising the MaxClients setting");
"server seems busy, (you may need " "to increase StartServers, ThreadsPerChild " "spawning %d children, there are around %d idle " /* 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 /* non-fatal death... note that it's gone in the scoreboard. */ /* 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 child. "long lost child came home! (pid %ld)",
/* 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. "apr_file_pipe_create (pipe_of_death)");
"apr_file_pipe_timeout_set (pipe_of_death)");
/* XXX: hey, what's the right way for the mpm to indicate a fatal error? */ "no listening sockets available, shutting down");
/* Initialize cross-process accept lock */ "Couldn't create accept lock");
/* 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 SIGWINCH). 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",
/* Time to gracefully shut down: * 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");
/* 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. /* wake up the children...time to die. But we'll have more soon */ "SIGWINCH received. Doing graceful restart");
/* This is mostly for debugging... so that we know what is still * gracefully dealing with existing request. /* Kill 'em all. Since the child acts the same on the parents SIGTERM * and a SIGHUP, we may as well use the same signal, because some user * pthreads are stealing signals from us left and right. "SIGHUP received. Attempting to restart");
/* sigh, want this only the second time around */ "WARNING: detected MinSpareThreads set to non-positive.");
"Resetting to 1 to avoid almost certain Apache failure.");
"Please read the documentation.");
"WARNING: MaxClients of %d exceeds compile time limit " " lowering MaxClients to %d. To increase, please " " HARD_SERVER_LIMIT define in %s.",
"WARNING: ThreadsPerChild of %d exceeds compile time " " lowering ThreadsPerChild to %d. To increase, please" " HARD_THREAD_LIMIT define in %s.",
"WARNING: Require ThreadsPerChild > 0, setting to 1");
"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"),
"Number of threads each child creates"),
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 */