mpm_winnt.c revision 7c60e4e710c92b3c4a0eb831bc6dd65368c599bc
0N/A/* ==================================================================== 0N/A * The Apache Software License, Version 1.1 0N/A * Copyright (c) 2000-2001 The Apache Software Foundation. All rights 0N/A * Redistribution and use in source and binary forms, with or without 0N/A * modification, are permitted provided that the following conditions 0N/A * 1. Redistributions of source code must retain the above copyright 0N/A * notice, this list of conditions and the following disclaimer. 0N/A * 2. Redistributions in binary form must reproduce the above copyright 0N/A * notice, this list of conditions and the following disclaimer in 0N/A * the documentation and/or other materials provided with the 0N/A * 3. The end-user documentation included with the redistribution, 0N/A * if any, must include the following acknowledgment: 0N/A * "This product includes software developed by the 0N/A * Alternately, this acknowledgment may appear in the software itself, 0N/A * if and wherever such third-party acknowledgments normally appear. 0N/A * 4. The names "Apache" and "Apache Software Foundation" must 0N/A * not be used to endorse or promote products derived from this 0N/A * software without prior written permission. For written 0N/A * permission, please contact apache@apache.org. 0N/A * 5. Products derived from this software may not be called "Apache", 0N/A * nor may "Apache" appear in their name, without prior written 0N/A * permission of the Apache Software Foundation. 0N/A * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED 0N/A * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 0N/A * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 0N/A * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR 0N/A * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 0N/A * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 0N/A * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF 0N/A * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 0N/A * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 0N/A * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 0N/A * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 0N/A * ==================================================================== 0N/A * This software consists of voluntary contributions made by many 0N/A * individuals on behalf of the Apache Software Foundation. For more 0N/A * information on the Apache Software Foundation, please see 0N/A * Portions of this software are based upon public domain software 0N/A * originally written at the National Center for Supercomputing Applications, 0N/A * University of Illinois, Urbana-Champaign. 0N/A/* Queue for managing the passing of COMP_CONTEXTs from 0N/A * the accept thread to the worker threads and back again 0N/A/* Definitions of WINNT MPM specific config globals */ /* ap_get_max_daemons and ap_my_generation are used by the scoreboard /* This is the helper code to resolve late bound entry points * missing from one or more releases of the Win32 API... * but it sure would be nice if we didn't duplicate this code "kernel32",
"advapi32",
"mswsock",
"ws2_32" };
/* To share the semaphores with other processes, we need a NULL ACL * Code from MS KB Q106387 * The Win32 call WaitForMultipleObjects will only allow you to wait for * a maximum of MAXIMUM_WAIT_OBJECTS (current 64). Since the threading * model in the multithreaded version of apache wants to use this call, * we are restricted to a maximum of 64 threads. This is a simplistic * routine that will increase this size. * Signalling Apache on NT. * Under Unix, Apache can be told to shutdown or restart by sending various * signals (HUP, USR, TERM). On NT we don't have easy access to signals, so * we use "events" instead. The parent apache process goes into a loop * where it waits forever for a set of events. Two of those events are * (where PID is the PID of the apache parent process). When one of these * is signalled, the Apache parent performs the appropriate action. The events * can become signalled through internal Apache methods (e.g. if the child * finds a fatal error and needs to kill its parent), via the service * control manager (the control thread will signal the shutdown event when * requested to stop the Apache service), from the -k Apache command line, * or from any external program which finds the Apache PID from the * The signal_parent() function, below, is used to signal one of these events. * It can be called by any child or parent process, since it does not * rely on global variables. * On entry, type gives the event to signal. 0 means shutdown, 1 means * Initialise the signal names, in the global variables signal_name_prefix, * signal_restart_name and signal_shutdown_name. #
define MAX_SIGNAL_NAME 30 /* Long enough for apPID_shutdown, where PID is an int */ /* after updating the shutdown_pending or restart flags, we need * to wake up the parent process so it can see the changes. The * parent will normally be waiting for either a child process * to die, or for a signal on the "spache-signal" event. So set the * "apache-signal" event here. /* Um, problem, can't signal the parent, which means we can't * signal ourselves to die. Ignore for now... /* Same problem as above */ * Only used by Win9* and should go away when the win9*_accept() function is * reimplemented using apr_poll(). * get_listeners_from_parent() * The listen sockets are opened in the parent. This function, which runs * exclusively in the child process, receives them from the parent and * makes them availeble in the child. /* Set up a default listener if necessary */ /* Open the pipe to the parent process to receive the inherited socket * data. The sockets have been set to listening in the parent process. "setup_inherited_listeners: Unable to read socket data from parent");
"Child %d: setup_inherited_listener() read = %d bytes of WSAProtocolInfo.",
my_pid);
"Child %d: setup_inherited_listeners(), WSASocket failed to open the inherited socket.",
my_pid);
/* Windows 9x specific code... * model. A single thread accepts connections and queues the accepted socket * to the accept queue for consumption by a pool of worker threads. * The accept threads runs this function, which accepts connections off * the network and calls add_job() to queue jobs to the accept_queue. * Add or remove an accepted socket from the list of sockets * connected to clients. allowed_globals.jobmutex protects * against multiple concurrent access to the linked list of jobs. * Calls remove_job() to pull a job from the accept queue. All the worker * threads block on remove_job. "Ouch! Out of memory in add_job()!");
/* A "real" error occurred, log it and increment the count of * select errors. This count is used to ensure we don't go into * a busy loop of continuous errors. "Too many errors in select loop. Child process exiting.");
/* fetch the native socket descriptor */ "accept: (client socket)");
/* allocate the completion context and the transaction pool */ "win9x_get_connection: apr_pcalloc() failed. Process will exit.");
/* do we NEED_DUPPED_CSD ?? */ /* Windows NT/2000 specific code... * model. An accept thread accepts connections off the network then issues * PostQueuedCompletionStatus() to awake a thread blocked on the ThreadDispatch * One or more accept threads run in this function, each of which accepts * connections off the network and calls PostQueuedCompletionStatus() to * queue an io completion packet to the ThreadDispatch IOCompletionPort. * Worker threads block on the ThreadDispatch IOCompletionPort awaiting * connections to service. /* Grab a context off the queue */ /* If we failed to grab a context off the queue, alloc one out of * the child pool. There may be up to ap_threads_per_child contexts "Server ran out of threads to serve requests. Consider " "raising the ThreadsPerChild setting");
"winnt_accept: CreateEvent failed. Process will exit.");
/* Create and initialize the accept socket */ "winnt_accept: socket() failed. Process will exit.");
/* SO_UPDATE_ACCEPT_CONTEXT is required for shutdown() to work */ "setsockopt(SO_UPDATE_ACCEPT_CONTEXT) failed.");
/* Not a failure condition. Keep running. */ /* AcceptEx on the completion context. The completion context will be * signaled when a connection is accepted. /* Hack alert. Occasionally, TransmitFile will not recycle the * accept socket (usually when the client disconnects early). * Get a new socket and try the call again. "winnt_accept: AcceptEx failed. Reallocate the accept socket and try again.");
"winnt_accept: AcceptEx failed. Process will exit.");
/* Wait for pending i/o */ /* When a connection is received, send an io completion notification to /* Yow, hit an irrecoverable error! Tell the child to die. */ /* Recycle the completion context. * - destroy the ptrans pool * - put the context on the queue to be consumed by the accept thread * Note: pCompContext->accept_socket may be in a disconnected * but reusable state so -don't- close it. "Child %d: GetQueuedComplationStatus returned %d",
my_pid,
rc);
"Child %d: apr_pool_create failed with rc %d",
my_pid,
rc);
/* Get the local & remote address */ * Main entry point for the worker threads. Worker threads block in * win*_get_connection() awaiting a connection to service. /* Grab a connection off the network */ /* ap_new_connection closes the socket on failure */ "Child %d: Thread exiting.",
my_pid);
* Entry point for the main control thread for the child process. * This thread creates the accept thread, worker threads and * monitors the child process for maintenance and shutdown /* This is the child process or we are running in single process mode. */ /* Single process mode */ /* Initialize the child_events */ * Wait until we have permission to start accepting connections. * start_mutex is used to ensure that only one child ever "Child %d: Failed to acquire the start_mutex. Process will exit.",
my_pid);
"Child %d: Acquired the start mutex.",
my_pid);
* Create the worker thread dispatch IOCompletionPort /* Create the worker thread dispatch IOCP */ 0);
/* CONCURRENT ACTIVE THREADS */ * Create the pool of worker threads * Start the accept thread /* Start an accept thread per listener */ SOCKET nlsd;
/* native listening sock descriptor */ /* Wait for one of three events: * The exit_event is signaled by the parent process to notify * the child that it is time to exit. * This event is signaled by the worker thread pool to direct * this thread to create more completion contexts. * To do periodic maintenance on the server (check for thread exits, * number of completion contexts, etc.) /* Something serious is wrong */ "Child %d: WAIT_FAILED -- shutting down server");
/* Exit event was signaled */ "Child %d: Exit event signaled. Child process is ending.",
my_pid);
/* Child maintenance event signaled */ "Child %d: Child maintenance event signaled.",
my_pid);
/* Setting is_graceful will cause keep-alive connections to be closed * rather than block on the next network read. /* Setting shutdown_in_progress prevents new connections from * being accepted but allows the worker threads to continue * handling connections that have already been accepted. /* Close the listening sockets */ /* Give the worker threads time to handle already accepted connections */ /* Release the start_mutex to let the new process (in the restart * scenario) a chance to begin accepting and servicing requests "Child %d: Releasing the start mutex",
my_pid);
/* Tell the worker threads they may exit when done handling /* Shutdown the worker threads */ else {
/* Windows NT/2000 */ /* Post worker threads blocked on the ThreadDispatch IOCompletion port */ /* Empty the accept queue of completion contexts */ /* Give busy worker threads a chance to service their connections */ /* Kill remaining threads off the hard way */ "Child %d: All worker threads have ended.",
my_pid);
/* Build the command line. Should look something like this: * First, get the path to the executable... "Parent: Path to Apache process too long");
"Parent: GetModuleFileName() returned NULL for current process.");
/* Build the command line */ /* Build the environment, since Win9x disrespects the active env */ * Win32's CreateProcess call requires that the environment * be passed in an environment block, a null terminated block of * null terminated strings. /* Create a pipe to send socket info to the child */ "Parent: Unable to create pipe to child process.");
/* Give the read end of the pipe (hPipeRead) to the child as stdin. The * parent will write the socket data to the child on this pipe. TRUE,
/* Inherit handles */ "Parent: Not able to create the child process.");
* We must close the handles to the new process and its main thread * to prevent handle and memory leaks. /* Create the exit_event, apCchild_pid */ "Parent: Could not create exit event for child process");
/* Assume the child process lives. Update the process and event tables */ /* We never store the thread's handle, so close it now. */ /* Run the chain of open sockets. For each socket, duplicate it * for the target process then send the WSAPROTOCOL_INFO * (returned by dup socket) to the child. "Parent: Duplicating socket %d and sending it to child process %d",
nsd,
pi.
dwProcessId);
"Parent: WSADuplicateSocket failed for socket %d. Check the FAQ.",
lr->
sd );
"Parent: Unable to write duplicated socket %d to the child.",
lr->
sd );
/********************************************************************** * This is the parent process. master_main() creates a multithreaded * child process to handle connections, then blocks waiting to receive * a shutdown, restart event or child exit event. * - Child is signaled to die gracefully * - Child is signaled to die gracefully * - Child has died, either normally (max_request_per_child) * or abnormally (seg fault, irrecoverable error condition detected by the **********************************************************************/ * Should only be one in this version of Apache for WIN32 "master_main: create child process failed. Exiting.");
/* Wait for shutdown or restart events or for child death */ /* Something serious is wrong */ "master_main: WaitForMultipeObjects WAIT_FAILED -- doing server shutdown");
/* Hey, this cannot happen */ "master_main: WaitForMultipeObjects with INFINITE wait exited with WAIT_TIMEOUT");
/* shutdown_event signalled */ printf(
"shutdown event signaled\n");
"Parent: SHUTDOWN EVENT SIGNALED -- Shutting down the server.");
"ResetEvent(shutdown_event)");
/* restart_event signalled */ "Parent: RESTART EVENT SIGNALED -- Restarting the server.");
"master_main: ResetEvent(restart_event) failed.");
/* Signal each child process to die * We are making a big assumption here that the child process, once signaled, * will REALLY go away. Since this is a restart, we do not want to hold the * new child process up waiting for the old child to die. Remove the old * child out of the process_handles apr_table_t and hope for the best... "master_main: SetEvent for child process in slot #%d failed", i);
/* A child process must have exited because of a fatal error condition (seg fault, etc.). * Remove the dead process * from the process_handles and process_kill_events apr_table_t and create a new * TODO: Consider restarting the child immediately without looping through http_main * and without rereading the configuration. Will need this if we ever support multiple * children. One option, create a parent thread which waits on child death and restarts it. * Consider, however, that if the user makes httpd.conf invalid, we want to die before * our child tries it... otherwise we have a nasty loop. "Parent: CHILD PROCESS FAILED -- Restarting the child process.");
/* APD2("main_process: child in slot %d died", rv); */ /* restart_child(process_hancles, process_kill_events, cld, ¤t_live_processes); */ /* Signal each child processes to die */ "master_main: SetEvent for child process in slot #%d failed", i);
"Parent: Forcing termination of child #%d (handle %d)", i,
process_handles[i]);
return 0;
/* Tell the caller we do not want to restart */ return 1;
/* Tell the caller we want a restart */ /* service_nt_main_fn needs to append the StartService() args * outside of our call stack and thread as the service starts... /* Remember service_to_start failures to log and fail in pre_config. * Remember inst_argc and inst_argv for installing or starting the * service after we preflight the config. /* Handle the following SCM aspects in this phase: * -k runservice [transition for WinNT, nothing for Win9x] * -k (!)install [error out if name is not installed] * We can't leave this phase until we know our identity * and modify the command arguments appropriately. /* AP_PARENT_PID is only valid in the child */ /* The parent is responsible for providing the * COMPLETE ARGUMENTS REQUIRED to the child. * No further argument parsing is needed, but * for good measure we will provide a simple * signal string for later testing. /* This is the parent, we have a long way to go :-) */ /* Rewrite process->argv[]; * strip out -k signal into signal_arg * strip out -n servicename and set the names * add default -d serverroot from the path of this executable * The end result will look like: * The invocation command (%0) * The -d serverroot default from the running executable * The requested service's (-n) registry ConfigArgs * The WinNT SCM's StartService() args "Failed to get the path of Apache.exe");
/* WARNING: There is an implict assumption here that the * executable resides in ServerRoot or ServerRoot\bin /* Use process->pool so that the rewritten argv * lasts for the lifetime of the server process, * because pconf will be destroyed after the * initial pre-flight of the config parser. "-i is deprecated. Use -k install.");
"-u is deprecated. Use -k uninstall.");
/* Track the number of args actually entered by the user */ /* Provide a default 'run' -k arg to simplify signal_arg tests */ /* Start the NT Service _NOW_ because the WinNT SCM is * expecting us to rapidly assume control of our own * process, the SCM will tell us our service name, and * may have extra StartService() command arguments to * Any other process has a console, so we don't to begin * a Win9x service until the configuration is parsed and * any command line errors are reported. * We hold the return value so that we can die in pre_config * after logging begins, and the failure can land in the log. "Using ConfigArgs of the installed service " "No installed ConfigArgs for the service " /* Track the args actually entered by the user. * These will be used for the -k install parameters, as well as * for the -k start service override arguments. /* Handle the following SCM aspects in this phase: * -k runservice [WinNT errors logged from rewrite_args] * in these cases we -don't- care if httpd.conf has config errors! "%s: Unable to start the service manager.",
/* Handle the following SCM aspects in this phase: * -k runservice [Win95, only once - after we parsed the config] * because all of these signals are useful _only_ if there * is a valid conf\httpd.conf environment to start. * We reached this phase by avoiding errors that would cause * these options to fail unexpectedly in another process. /* This code should be run once in the parent and not run /* Create shutdown event, apPID_shutdown, where PID is the parent * Apache process ID. Shutdown is signaled by 'apache -k shutdown'. /* Create restart event, apPID_restart, where PID is the parent * Apache process ID. Restart is signaled by 'apache -k restart'. /* Now that we are flying at 15000 feet... * wipe out the Win95 service console, * signal the SCM the WinNT service started, or * if not a service, setup console handlers instead. "%s: Unable to start the service manager.",
else /* ! -k runservice */ /* Create the start mutex, apPID, where PID is the parent Apache process ID. * Ths start mutex is used during a restart to prevent more than one * child process from entering the accept loop at once. else /* parent_pid != my_pid */ static int restart = 0;
/* Default is "not a restart" */ /* Child process or in one_process (debug) mode */ "Child %d: Child process is running",
my_pid);
/* Set up the scoreboard. The scoreboard in this MPM only applies to the * child process and is not shared across processes "Child %d: Child process is exiting",
my_pid);
"no listening sockets available, shutting down");
/* Shutting down. Clean up... */ return "PidFile directive not allowed in <VirtualHost>";
"WARNING: ThreadsPerChild of %d exceeds compile time" " lowering ThreadsPerChild to %d. To increase, please" " see the HARD_THREAD_LIMIT define in %s.",
"WARNING: Require ThreadsPerChild > 0, setting to 1");
" does not exist or is not a directory",
NULL);
/* Stub functions until this MPM supports the connection status API */ "A file for logging the server process ID"},
"Number of threads each child creates" },
"Maximum number of requests a particular child serves before dying." },
"The location of the directory Apache changes to before dumping core" },
NULL,
/* create per-directory config structure */ NULL,
/* merge per-directory config structures */ NULL,
/* create per-server config structure */ NULL,
/* merge per-server config structures */