/* Licensed to the Apache Software Foundation (ASF) under one or more *contributorlicenseagreements.SeetheNOTICEfiledistributedwith *thisworkforadditionalinformationregardingcopyrightownership. *TheASFlicensesthisfiletoYouundertheApacheLicense,Version2.0 *(the"License");youmaynotusethisfileexceptincompliancewith *theLicense.YoumayobtainacopyoftheLicenseat * *http://www.apache.org/licenses/LICENSE-2.0 * *Unlessrequiredbyapplicablelaworagreedtoinwriting,software *distributedundertheLicenseisdistributedonan"ASIS"BASIS, *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied. *SeetheLicenseforthespecificlanguagegoverningpermissionsand *limitationsundertheLicense.
*/
/* The purpose of this MPM is to fix the design flaws in the threaded *model.Becauseofthewaythatpthreadsandmutexlocksinteract, *itisbasicallyimpossibletocleanlygracefullyshutdownachild *processifmultiplethreadsareallblockedinaccept.Thismodel *fixesthoseproblems.
*/
#include <signal.h> #include <limits.h> /* for INT_MAX */
/* Limit on the total --- clients will be locked out if more servers than *thisareneeded.Itisintendedsolelytokeeptheserverfromcrashing *whenthingsgetoutofhand. * *Wekeepahardmaximumnumberofservers,fortworeasons---firstoff, *incasesomethinggoesseriouslywrong,wewanttostoptheforkbomb *shortofactuallycrashingthemachinewe'rerunningonbyfillingsome *kerneltable.Secondly,itkeepsthesizeofthescoreboardfilesmall *enoughthatwecanreadthewholethingwithoutworryingtoomuchabout *theoverhead.
*/ #ifndef DEFAULT_SERVER_LIMIT #define DEFAULT_SERVER_LIMIT 16 #endif
/* Limit on the threads per process. Clients will be locked out if more than *this*server_limitareneeded. * *Wekeepthisforonereasonitkeepsthesizeofthescoreboardfilesmall *enoughthatwecanreadthewholethingwithoutworryingtoomuchabout *theoverhead.
*/ #ifndef DEFAULT_THREAD_LIMIT #define DEFAULT_THREAD_LIMIT 64 #endif
/* data retained by worker across load/unload of the module *allocatedonfirstcalltopre-confighook;locatedon *subsequentcallstopre-confighook
*/ typedefstruct worker_retained_data {
ap_unixd_mpm_retained_data *mpm;
int first_server_limit; int first_thread_limit; int sick_child_detected; int maxclients_reported; int near_maxclients_reported; /* *Themaxchildsloteverassigned,preservedacrossrestarts.Necessary *todealwithMaxRequestWorkerschangesacrossAP_SIG_GRACEFULrestarts. *Weusethisvaluetooptimizeroutinesthathavetoscantheentire *scoreboard.
*/ int max_daemons_limit; /* *idle_spawn_rateisthenumberofchildrenthatwillbespawnedonthe *nextmaintenancecycleiftherearen'tenoughidleservers.Itis *maintainedperlistenersbucket,doubleduptoMAX_SPAWN_RATE,and *resetonlywhenacyclegoesbywithouttheneedtospawn.
*/ int *idle_spawn_rate; #ifndef MAX_SPAWN_RATE #define MAX_SPAWN_RATE (32) #endif int hold_off_on_exponential_spawning;
} worker_retained_data; static worker_retained_data *retained;
/* The structure used to pass unique initialization info to each thread */ typedefstruct { int pid; int tid; int sd;
} proc_info;
/* Structure used to pass information to the thread responsible for *creatingtherestofthethreads.
*/ typedefstruct {
apr_thread_t **threads;
apr_thread_t *listener; int child_num_arg;
apr_threadattr_t *threadattr;
} thread_starter;
/* The worker MPM respects a couple of runtime flags that can aid *indebugging.Settingthe-DNO_DETACHflagwillpreventtherootprocess *fromdetachingfromitscontrollingterminal.Additionally,setting *the-DONE_PROCESSflag(whichimplies-DNO_DETACH)willgetyouthe *child_mainlooprunningintheprocesswhichoriginallystartedup. *Thisgivesyouaprettynicedebuggingenvironment.(You'llgetaSIGHUP *earlyinstandalone_main;justcontinuethrough.Thisistheserver *tryingtokilloffanychildprocesseswhichitmighthavelying *around---Apachedoesn'tkeeptrackoftheirpids,itjustsends *SIGHUPtotheprocessgroup,ignoringitintherootprocess. *Continuethroughandyou'llbefine.).
*/
staticint one_process = 0;
#ifdef DEBUG_SIGSTOP int raise_sigstop_flags; #endif
static apr_pool_t *pconf; /* Pool for config stuff */ static apr_pool_t *pchild; /* Pool for httpd child stuff */ static apr_pool_t *pruntime; /* Pool for MPM threads stuff */
static pid_t ap_my_pid; /* Linux getpid() doesn't work except in main
thread. Use this instead */ static pid_t parent_pid; static apr_os_thread_t *listener_os_thread;
/* The LISTENER_SIGNAL signal will be sent from the main thread to the *listenerthreadtowakeitupforgracefultermination(whatachild *processfromanoldgenerationdoeswhentheadmindoes"apachectl *graceful").Thissignalwillbeblockedinallthreadsofachild *processexceptforthelistenerthread.
*/ #define LISTENER_SIGNAL SIGHUP
/* The WORKER_SIGNAL signal will be sent from the main thread to the *workerthreadsduringanungracefulrestartorshutdown. *Thisensuresthatonsystems(i.e.,Linux)whereclosingtheworker *socketdoesn'tawaketheworkerthreadwhenitispollingonthesocket *(especiallyinapr_wait_for_io_or_timeout()whenhandling *Keep-Aliveconnections),close_worker_sockets()andjoin_workers() *stillfunctionintimelymannerandallowungracefulshutdownsto *proceedtocompletion.Otherwisejoin_workers()doesn'treturn *beforethemainprocessdecidesthechildprocessisnon-responsive *andsendsaSIGKILL.
*/ #define WORKER_SIGNAL AP_SIG_GRACEFUL
/* An array of socket descriptors in use by each thread used to
* perform a non-graceful (forced) shutdown of the server. */ static apr_socket_t **worker_sockets;
staticvoid close_worker_sockets(void)
{ int i; for (i = 0; i < threads_per_child; i++) { if (worker_sockets[i]) {
apr_socket_close(worker_sockets[i]);
worker_sockets[i] = NULL;
}
}
}
/* in case we weren't called from the listener thread, wake up the *listenerthread
*/
wakeup_listener();
/* for ungraceful termination, let the workers exit now; *forgracefultermination,thelistenerthreadwillnotifythe *workerstoexitonceithasstoppedacceptingnewconnections
*/ if (mode == ST_UNGRACEFUL) {
workers_may_exit = 1;
ap_queue_interrupt_all(worker_queue);
close_worker_sockets(); /* forcefully kill all current connections */
}
/* requests_this_child has gone to zero or below. See if the admin coded "MaxConnectionsPerChild0",andkeepgoinginthatcase.Doingitthisway
simplifies the hot path in worker_thread */ staticvoid check_infinite_requests(void)
{ if (ap_max_requests_per_child) {
signal_threads(ST_GRACEFUL);
} else {
requests_this_child = INT_MAX; /* keep going */
}
}
staticvoid dummy_signal_handler(int sig)
{ /* XXX If specifying SIG_IGN is guaranteed to unblock a syscall, *thenwedon'tneedthisgoofyfunction.
*/
}
staticvoid accept_mutex_error(constchar *func, apr_status_t rv, int process_slot)
{ int level = APLOG_EMERG;
if (ap_scoreboard_image->parent[process_slot].generation !=
ap_scoreboard_image->global->running_generation) {
level = APLOG_DEBUG; /* common to get these at restart time */
} elseif (requests_this_child == INT_MAX
|| ((requests_this_child == ap_max_requests_per_child)
&& ap_max_requests_per_child)) {
ap_log_error(APLOG_MARK, level, rv, ap_server_conf, APLOGNO(00272) "apr_proc_mutex_%s failed " "before this child process served any requests.",
func);
clean_child_exit(APEXIT_CHILDSICK);
}
ap_log_error(APLOG_MARK, level, rv, ap_server_conf, APLOGNO(00273) "apr_proc_mutex_%s failed. Attempting to " "shutdown process gracefully.", func);
signal_threads(ST_GRACEFUL);
}
staticvoid * APR_THREAD_FUNC listener_thread(apr_thread_t *thd, void * dummy)
{
proc_info * ti = dummy; int process_slot = ti->pid; void *csd = NULL;
apr_pool_t *ptrans = NULL; /* Pool for per-transaction stuff */
apr_status_t rv;
ap_listen_rec *lr = NULL; int have_idle_worker = 0; int last_poll_idx = 0;
free(ti);
/* Unblock the signal used to wake this thread up, and set a handler for *it.
*/
apr_signal(LISTENER_SIGNAL, dummy_signal_handler);
unblock_signal(LISTENER_SIGNAL);
/* TODO: Switch to a system where threads reuse the results from earlier
poll calls - manoj */ while (1) { /* TODO: requests_this_child should be synchronized - aaron */ if (requests_this_child <= 0) {
check_infinite_requests();
} if (listener_may_exit) break;
if (!have_idle_worker) {
rv = ap_queue_info_wait_for_idler(worker_queue_info, NULL); if (APR_STATUS_IS_EOF(rv)) { break; /* we've been signaled to die now */
} elseif (rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf, "apr_queue_info_wait failed. Attempting to " " shutdown process gracefully.");
signal_threads(ST_GRACEFUL); break;
}
have_idle_worker = 1;
}
if ((rv = SAFE_ACCEPT(apr_proc_mutex_lock(my_bucket->mutex)))
!= APR_SUCCESS) {
if (!listener_may_exit) {
accept_mutex_error("lock", rv, process_slot);
} break; /* skip the lock release */
}
if (!my_bucket->listeners->next) { /* Only one listener, so skip the poll */
lr = my_bucket->listeners;
} else { while (!listener_may_exit) {
apr_int32_t numdesc; const apr_pollfd_t *pdesc;
rv = apr_pollset_poll(worker_pollset, -1, &numdesc, &pdesc); if (rv != APR_SUCCESS) { if (APR_STATUS_IS_EINTR(rv)) { continue;
}
/* apr_pollset_poll() will only return errors in catastrophic
* circumstances. Let's try exiting gracefully, for now. */
ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, APLOGNO(03137) "apr_pollset_poll: (listen)");
signal_threads(ST_GRACEFUL);
}
if (listener_may_exit) break;
/* We can always use pdesc[0], but sockets at position N *couldendupcompletelystarvedofattentioninavery *busyserver.Therefore,weround-robinacrossthe *returnedsetofdescriptors.Whileitispossiblethat *thereturnedsetofdescriptorsmightfliparoundand *continuetostarvesomesockets,wehappentoknowthe *internalpollsetimplementationretainsordering *stabilityofthesockets.Thus,theround-robinshould *ensurethatasocketwilleventuallybeserviced.
*/ if (last_poll_idx >= numdesc)
last_poll_idx = 0;
/* Grab a listener record from the client_data of the poll *descriptor,andadvanceoursavedindextoround-robin *thenextfetch. * *###hmm...thisdescriptormighthavePOLLERRrather *###thanPOLLIN
*/
lr = pdesc[last_poll_idx++].client_data; break;
} /* while */
} /* if/else */
if (!listener_may_exit) { /* the following pops a recycled ptrans pool off a stack */
ap_queue_info_pop_pool(worker_queue_info, &ptrans); if (ptrans == NULL) { /* we can't use a recycled transaction pool this time.
* create a new transaction pool */
apr_allocator_t *allocator;
apr_allocator_create(&allocator);
apr_allocator_max_free_set(allocator, ap_max_mem_free);
apr_pool_create_ex(&ptrans, pconf, NULL, allocator);
apr_allocator_owner_set(allocator, ptrans);
apr_pool_tag(ptrans, "transaction");
}
rv = lr->accept_func(&csd, lr, ptrans); /* later we trash rv and rely on csd to indicate success/failure */
AP_DEBUG_ASSERT(rv == APR_SUCCESS || !csd);
if (listener_may_exit) { break;
}
accept_mutex_error("unlock", rv, process_slot);
} if (csd != NULL) {
rv = ap_queue_push_socket(worker_queue, csd, NULL, ptrans); if (rv) { /* trash the connection; we couldn't queue the connected *sockettoaworker
*/
apr_socket_close(csd);
ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(03138) "ap_queue_push_socket failed");
} else {
have_idle_worker = 0;
}
}
} else { if ((rv = SAFE_ACCEPT(apr_proc_mutex_unlock(my_bucket->mutex)))
!= APR_SUCCESS) { int level = APLOG_EMERG;
if (ap_scoreboard_image->parent[process_slot].generation !=
ap_scoreboard_image->global->running_generation) {
level = APLOG_DEBUG; /* common to get these at restart time */
}
ap_log_error(APLOG_MARK, level, rv, ap_server_conf, APLOGNO(00274) "apr_proc_mutex_unlock failed. Attempting to " "shutdown process gracefully.");
signal_threads(ST_GRACEFUL);
} break;
}
}
/* We must create the fd queues before we start up the listener
* and worker threads. */
rv = ap_queue_create(&worker_queue, threads_per_child, pruntime); if (rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf, APLOGNO(03140) "ap_queue_create() failed");
clean_child_exit(APEXIT_CHILDFATAL);
}
/* Create the main pollset. When APR_POLLSET_WAKEABLE is asked we account *forthewakeuppipeexplicitelywithnum_listensocks+1becausesome *pollsetimplementationsdon'tdoitimplicitelyinAPR.
*/
pollset_flags = APR_POLLSET_NOCOPY | APR_POLLSET_WAKEABLE;
rv = apr_pollset_create(&worker_pollset, num_listensocks + 1, pruntime,
pollset_flags); if (rv == APR_SUCCESS) {
listener_is_wakeable = 1;
} else {
pollset_flags &= ~APR_POLLSET_WAKEABLE;
rv = apr_pollset_create(&worker_pollset, num_listensocks, pruntime,
pollset_flags);
} if (rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf, APLOGNO(03285) "Couldn't create pollset in thread;" " check system or user limits"); /* let the parent decide how bad this really is */
clean_child_exit(APEXIT_CHILDSICK);
}
for (lr = my_bucket->listeners; lr != NULL; lr = lr->next) {
apr_pollfd_t *pfd = apr_pcalloc(pruntime, sizeof *pfd);
rv = apr_pollset_add(worker_pollset, pfd); if (rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf, APLOGNO(03286) "Couldn't create add listener to pollset;" " check system or user limits"); /* let the parent decide how bad this really is */
clean_child_exit(APEXIT_CHILDSICK);
}
/* XXX under some circumstances not understood, children can get stuck *instart_threadsforevertryingtotakeoverslotswhichwill *neverbecleanedup;fornowthereisanAPLOG_DEBUGmessageissued *everysooftenwhenthisconditionoccurs
*/ staticvoid * APR_THREAD_FUNC start_threads(apr_thread_t *thd, void *dummy)
{
thread_starter *ts = dummy;
apr_thread_t **threads = ts->threads;
apr_threadattr_t *thread_attr = ts->threadattr; int my_child_num = ts->child_num_arg;
proc_info *my_info;
apr_status_t rv; int threads_created = 0; int listener_started = 0; int prev_threads_created; int loops, i;
loops = prev_threads_created = 0; while (1) { /* threads_per_child does not include the listener thread */ for (i = 0; i < threads_per_child; i++) { int status = ap_scoreboard_image->servers[my_child_num][i].status;
if (status != SERVER_GRACEFUL && status != SERVER_DEAD) { continue;
}
/* We are creating threads right now */
ap_update_child_status_from_indexes(my_child_num, i,
SERVER_STARTING, NULL); /* We let each thread update its own scoreboard entry. This is *donebecauseitletsusdealwithtidbetter.
*/
rv = ap_thread_create(&threads[i], thread_attr,
worker_thread, my_info, pruntime); if (rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf, APLOGNO(03142) "ap_thread_create: unable to create worker thread"); /* let the parent decide how bad this really is */
clean_child_exit(APEXIT_CHILDSICK);
}
threads_created++;
} /* Start the listener only when there are workers available */ if (!listener_started && threads_created) {
create_listener_thread(ts);
listener_started = 1;
} if (start_thread_may_exit || threads_created == threads_per_child) { break;
} /* wait for previous generation to clean up an entry */
apr_sleep(apr_time_from_sec(1));
++loops; if (loops % 120 == 0) { /* every couple of minutes */ if (prev_threads_created == threads_created) {
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, "child %" APR_PID_T_FMT " isn't taking over " "slots very quickly (%d of %d)",
ap_my_pid, threads_created, threads_per_child);
}
prev_threads_created = threads_created;
}
}
/* What state should this child_main process be listed as in the *scoreboard...? *ap_update_child_status_from_indexes(my_child_num,i,SERVER_STARTING, *(request_rec*)NULL); * *Thisstateshouldbelistedseparatelyinthescoreboard,insomekind *ofprocess_status,notmixedinwiththeworkerthreads'status. *"life_status"isalmostright,butit'sintheworker'sstructure,and *thenamecouldbeclearer.gla
*/
apr_thread_exit(thd, APR_SUCCESS); return NULL;
}
staticvoid join_workers(apr_thread_t *listener, apr_thread_t **threads, int mode)
{ int i;
apr_status_t rv, thread_rv;
if (listener) { int iter;
/* deal with a rare timing window which affects waking up the *listenerthread...ifthesignalsenttothelistenerthread *isdeliveredbetweenthetimeitverifiesthatthe *listener_may_exitflagisclearandthetimeitentersa *blockingsyscall,thesignaldidn'tdoanygood...workaround *thatbysleepingbrieflyandsendingitagain
*/
iter = 0; while (!dying) {
apr_sleep(apr_time_from_msec(500)); if (dying || ++iter > 10) { break;
} /* listener has not stopped accepting yet */
ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, ap_server_conf, "listener has not stopped accepting yet (%d iter)", iter);
wakeup_listener();
} if (iter > 10) {
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(00276) "the listener thread didn't exit");
} else {
rv = apr_thread_join(&thread_rv, listener); if (rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00277) "apr_thread_join: unable to join listener thread");
}
}
}
for (i = 0; i < threads_per_child; i++) { if (threads[i]) { /* if we ever created this thread */ if (mode != ST_GRACEFUL) { #ifdef HAVE_PTHREAD_KILL
apr_os_thread_t *worker_os_thread;
start_thread_may_exit = 1; /* tell it to give up in case it is still *tryingtotakeoverslotsfroma *previousgeneration
*/
rv = apr_thread_join(&thread_rv, start_thread_id); if (rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00279) "apr_thread_join: unable to join the start " "thread");
}
}
staticvoid child_main(int child_num_arg, int child_bucket)
{
apr_thread_t **threads;
apr_status_t rv;
thread_starter *ts;
apr_threadattr_t *thread_attr;
apr_thread_t *start_thread_id; int i;
/* for benefit of any hooks that run as this child initializes */
retained->mpm->mpm_state = AP_MPMQ_STARTING;
/* Get a sub context for global allocations in this child, so that *wecanhavecleanupsoccurwhenthechildexits.
*/
apr_pool_create(&pchild, pconf);
apr_pool_tag(pchild, "pchild");
#if AP_HAS_THREAD_LOCAL if (!one_process) {
apr_thread_t *thd = NULL; if ((rv = ap_thread_main_create(&thd, pchild))) {
ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf, APLOGNO(10375) "Couldn't initialize child main thread");
clean_child_exit(APEXIT_CHILDFATAL);
}
} #endif
/* close unused listeners and pods */ for (i = 0; i < retained->mpm->num_buckets; i++) { if (i != child_bucket) {
ap_close_listeners_ex(all_buckets[i].listeners);
ap_mpm_podx_close(all_buckets[i].pod);
}
}
/*stuff to do before we switch id's, so we have permissions.*/
ap_reopen_scoreboard(pchild, NULL, 0);
/* done with init critical section */ if (ap_run_drop_privileges(pchild, ap_server_conf)) {
clean_child_exit(APEXIT_CHILDFATAL);
}
/* Just use the standard apr_setup_signal_thread to block all signals *frombeingreceived.Thechildprocessesnolongerusesignalsfor *anycommunicationwiththeparentprocess.Let'salsodothisbefore *child_init()hooksarecalledandpossiblycreatethreadsthat *otherwisecould"steal"(implicitly)MPM'ssignals.
*/
rv = apr_setup_signal_thread(); if (rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf, APLOGNO(00281) "Couldn't initialize signal thread");
clean_child_exit(APEXIT_CHILDFATAL);
}
ap_run_child_init(pchild, ap_server_conf);
if (ap_max_requests_per_child) {
requests_this_child = ap_max_requests_per_child;
} else { /* coding a value of zero means infinity */
requests_this_child = INT_MAX;
}
/* Setup threads */
/* Globals used by signal_threads() so to be initialized before */
setup_threads_runtime();
/* clear the storage; we may not create all our threads immediately, *andwewanta0entrytoindicateathreadwhichwasnotcreated
*/
threads = (apr_thread_t **)ap_calloc(1, sizeof(apr_thread_t *) * threads_per_child);
ts = (thread_starter *)apr_palloc(pchild, sizeof(*ts));
apr_threadattr_create(&thread_attr, pchild); /* 0 means PTHREAD_CREATE_JOINABLE */
apr_threadattr_detach_set(thread_attr, 0);
if (ap_thread_stacksize != 0) {
rv = apr_threadattr_stacksize_set(thread_attr, ap_thread_stacksize); if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
ap_log_error(APLOG_MARK, APLOG_WARNING, rv, ap_server_conf, APLOGNO(02435) "WARNING: ThreadStackSize of %" APR_SIZE_T_FMT " is " "inappropriate, using default",
ap_thread_stacksize);
}
}
rv = ap_thread_create(&start_thread_id, thread_attr, start_threads,
ts, pchild); if (rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf, APLOGNO(00282) "ap_thread_create: unable to create worker thread"); /* let the parent decide how bad this really is */
clean_child_exit(APEXIT_CHILDSICK);
}
retained->mpm->mpm_state = AP_MPMQ_RUNNING;
/* If we are only running in one_process mode, we will want to
* still handle signals. */ if (one_process) { /* Block until we get a terminating signal. */
apr_signal_thread(check_signal); /* make sure the start thread has finished; signal_threads() *andjoin_workers()dependonthat
*/ /* XXX join_start_thread() won't be awakened if one of our *threadsencountersacriticalerrorandattemptsto *shutdownthischild
*/
join_start_thread(start_thread_id);
signal_threads(ST_UNGRACEFUL); /* helps us terminate a little more *quicklythanthedispatchofthesignalthread *beatsthePipeofDeathandthebrowsers
*/ /* A terminating signal was received. Now join each of the *workerstocleanthemup. *Iftheworkeralreadyexited,thenthejoinfrees *theirresourcesandreturns. *Iftheworkerhasn'texited,thenthisblocksuntil *theyhave(thencleansup).
*/
join_workers(ts->listener, threads, ST_UNGRACEFUL);
} else { /* !one_process */ /* remove SIGTERM from the set of blocked signals... if one of *theotherthreadsintheprocessneedstotakeusdown *(e.g.,forMaxConnectionsPerChild)itwillsendusSIGTERM
*/
apr_signal(SIGTERM, dummy_signal_handler);
unblock_signal(SIGTERM); /* Watch for any messages from the parent over the POD */ while (1) {
rv = ap_mpm_podx_check(my_bucket->pod); if (rv == AP_MPM_PODX_NORESTART) { /* see if termination was triggered while we slept */ switch(terminate_mode) { case ST_GRACEFUL:
rv = AP_MPM_PODX_GRACEFUL; break; case ST_UNGRACEFUL:
rv = AP_MPM_PODX_RESTART; break;
}
} if (rv == AP_MPM_PODX_GRACEFUL || rv == AP_MPM_PODX_RESTART) { /* make sure the start thread has finished; *signal_threads()andjoin_workersdependonthat
*/
join_start_thread(start_thread_id);
signal_threads(rv == AP_MPM_PODX_GRACEFUL ? ST_GRACEFUL : ST_UNGRACEFUL); break;
}
}
/* A terminating signal was received. Now join each of the *workerstocleanthemup. *Iftheworkeralreadyexited,thenthejoinfrees *theirresourcesandreturns. *Iftheworkerhasn'texited,thenthisblocksuntil *theyhave(thencleansup).
*/
join_workers(ts->listener, threads,
rv == AP_MPM_PODX_GRACEFUL ? ST_GRACEFUL : ST_UNGRACEFUL);
}
if ((pid = fork()) == -1) {
ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, APLOGNO(00283) "fork: Unable to fork new process"); /* fork didn't succeed. There's no need to touch the scoreboard; *ifweweretryingtoreplaceafailedchildprocess,then *server_main_loop()markeditsworkersSERVER_DEAD,andif *weweretryingtoreplaceachildprocessthatexitednormally, *itsworker_thread()sleftSERVER_DEADorSERVER_GRACEFULbehind.
*/
/* In case system resources are maxxed out, we don't want ApacherunningawaywiththeCPUtryingtoforkoverand
over and over again. */
apr_sleep(apr_time_from_sec(10));
return -1;
}
if (!pid) { #if AP_HAS_THREAD_LOCAL
ap_thread_current_after_fork(); #endif
my_bucket = &all_buckets[bucket];
#ifdef HAVE_BINDPROCESSOR /* By default, AIX binds to a single processor. This bit unbinds *childrenwhichwillthenbindtoanotherCPU.
*/ int status = bindprocessor(BINDPROCESS, (int)getpid(),
PROCESSOR_CLASS_ANY); if (status != OK)
ap_log_error(APLOG_MARK, APLOG_DEBUG, errno,
ap_server_conf, APLOGNO(00284) "processor unbind failed"); #endif
RAISE_SIGSTOP(MAKE_CHILD);
if (ap_scoreboard_image->parent[slot].pid != 0) { /* This new child process is squatting on the scoreboard *entryownedbyanexitingchildprocess,whichcannot *exituntilallactiverequestscomplete.
*/
worker_note_child_lost_slot(slot, pid);
}
ap_scoreboard_image->parent[slot].quiescing = 0;
worker_note_child_started(slot, pid); return0;
}
/* start up a bunch of children */ staticvoid startup_children(int number_to_start)
{ int i;
for (i = 0; number_to_start && i < ap_daemons_limit; ++i) { if (ap_scoreboard_image->parent[i].pid != 0) { continue;
} if (make_child(ap_server_conf, i, i % retained->mpm->num_buckets) < 0) { break;
}
--number_to_start;
}
}
staticvoid perform_idle_server_maintenance(int child_bucket)
{ int num_buckets = retained->mpm->num_buckets; int idle_thread_count;
process_score *ps; int free_length; int totally_free_length = 0; int free_slots[MAX_SPAWN_RATE]; int last_non_dead; int total_non_dead; int active_thread_count = 0; int i, j;
for (i = 0; i < ap_daemons_limit; ++i) { /* Initialization to satisfy the compiler. It doesn't know
* that threads_per_child is always > 0 */ int any_dying_threads = 0; int any_dead_threads = 0; int all_dead_threads = 1; int child_threads_active = 0;
if (num_buckets > 1 && (i % num_buckets) != child_bucket) { /* We only care about child_bucket in this call */ continue;
} if (i >= retained->max_daemons_limit &&
totally_free_length == retained->idle_spawn_rate[child_bucket]) { /* short cut if all active processes have been examined and *enoughemptyscoreboardslotshavebeenfound
*/ break;
}
ps = &ap_scoreboard_image->parent[i]; for (j = 0; j < threads_per_child; j++) { int status = ap_scoreboard_image->servers[i][j].status;
/* We consider a starting server as idle because we started it *atleastacycleago,andifitstillhasn'tfinishedstarting *thenwe'rejustgoingtoswampthingsworsebyforkingmore. *Sowehopefullywon'tneedtoforkmoreifwecountit. *ThisdependsontheorderingofSERVER_READYandSERVER_STARTING.
*/ if (ps->pid != 0) { /* XXX just set all_dead_threads in outer for
loop if no pid? not much else matters */ if (status <= SERVER_READY &&
!ps->quiescing &&
ps->generation == retained->mpm->my_generation) {
++idle_thread_count;
} if (status >= SERVER_READY && status < SERVER_GRACEFUL) {
++child_threads_active;
}
}
}
active_thread_count += child_threads_active; if (any_dead_threads
&& totally_free_length < retained->idle_spawn_rate[child_bucket]
&& free_length < MAX_SPAWN_RATE / num_buckets
&& (!ps->pid /* no process in the slot */
|| ps->quiescing)) { /* or at least one is going away */ if (all_dead_threads) { /* great! we prefer these, because the new process can *startmorethreadssooner.Soprioritizethisslot *byputtingitaheadofanyslotswithactivethreads. * *first,makeroombymovingaslotthat'spotentiallystill *inusetotheendofthearray
*/
free_slots[free_length] = free_slots[totally_free_length];
free_slots[totally_free_length++] = i;
} else { /* slot is still in use - back of the bus
*/
free_slots[free_length] = i;
}
++free_length;
} elseif (child_threads_active == threads_per_child) {
had_healthy_child = 1;
} /* XXX if (!ps->quiescing) is probably more reliable GLA */ if (!any_dying_threads) {
++total_non_dead;
} if (ps->pid != 0) {
last_non_dead = i;
}
}
retained->max_daemons_limit = last_non_dead + 1;
if (retained->sick_child_detected) { if (had_healthy_child) { /* Assume this is a transient error, even though it may not be. Leave *theserverupincaseitisabletoservesomerequestsorthe *problemwillberesolved.
*/
retained->sick_child_detected = 0;
} elseif (child_bucket < num_buckets - 1) { /* check for had_healthy_child up to the last child bucket */ return;
} else { /* looks like a basket case, as no child ever fully initialized; give up.
*/
retained->mpm->shutdown_pending = 1;
child_fatal = 1;
ap_log_error(APLOG_MARK, APLOG_ALERT, 0,
ap_server_conf, APLOGNO(02325) "A resource shortage or other unrecoverable failure " "was encountered before any child process initialized " "successfully... httpd is exiting!"); /* the child already logged the failure details */ return;
}
}
if (idle_thread_count > max_spare_threads / num_buckets) { /* Kill off one child */
ap_mpm_podx_signal(all_buckets[child_bucket].pod,
AP_MPM_PODX_GRACEFUL);
retained->idle_spawn_rate[child_bucket] = 1;
} elseif (idle_thread_count < min_spare_threads / num_buckets) { /* terminate the free list */ if (free_length == 0) { /* scoreboard is full, can't fork */
if (active_thread_count >= max_workers / num_buckets) { /* no threads are "inactive" - starting, stopping, etc. */ /* have we reached MaxRequestWorkers, or just getting close? */ if (0 == idle_thread_count) { if (!retained->maxclients_reported) { /* only report this condition once */
ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(00286) "server reached MaxRequestWorkers " "setting, consider raising the " "MaxRequestWorkers setting");
retained->maxclients_reported = 1;
}
} else { if (!retained->near_maxclients_reported) {
ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(00287) "server is within MinSpareThreads of " "MaxRequestWorkers, consider raising the " "MaxRequestWorkers setting");
retained->near_maxclients_reported = 1;
}
}
} else {
ap_log_error(APLOG_MARK, APLOG_ERR, 0,
ap_server_conf, APLOGNO(00288) "scoreboard is full, not at MaxRequestWorkers");
}
retained->idle_spawn_rate[child_bucket] = 1;
} else { if (free_length > retained->idle_spawn_rate[child_bucket]) {
free_length = retained->idle_spawn_rate[child_bucket];
} if (retained->idle_spawn_rate[child_bucket] >= 8) {
ap_log_error(APLOG_MARK, APLOG_INFO, 0,
ap_server_conf, APLOGNO(00289) "server seems busy, (you may need " "to increase StartServers, ThreadsPerChild " "or Min/MaxSpareThreads), " "spawning %d children, there are around %d idle " "threads, and %d total children", free_length,
idle_thread_count, total_non_dead);
} for (i = 0; i < free_length; ++i) {
make_child(ap_server_conf, free_slots[i], child_bucket);
} /* the next time around we want to spawn twice as many if this *wasn'tgoodenough,butnotifwe'vejustdoneagraceful
*/ if (retained->hold_off_on_exponential_spawning) {
--retained->hold_off_on_exponential_spawning;
} elseif (retained->idle_spawn_rate[child_bucket]
< MAX_SPAWN_RATE / num_buckets) {
retained->idle_spawn_rate[child_bucket] *= 2;
}
}
} else {
retained->idle_spawn_rate[child_bucket] = 1;
}
}
staticvoid server_main_loop(int remaining_children_to_start)
{ int num_buckets = retained->mpm->num_buckets; int successive_kills = 0;
ap_generation_t old_gen; int child_slot;
apr_exit_why_e exitwhy; int status, processed_status;
apr_proc_t pid; int i;
while (!retained->mpm->restart_pending && !retained->mpm->shutdown_pending) {
ap_wait_or_timeout(&exitwhy, &status, &pid, pconf, ap_server_conf);
if (pid.pid != -1) {
processed_status = ap_process_child_status(&pid, exitwhy, status);
child_slot = ap_find_child_by_pid(&pid); if (processed_status == APEXIT_CHILDFATAL) { /* fix race condition found in PR 39311 *Achildcreatedatthesametimeasagracefulhappens *canfindthelockmissingandcreateafatalerror. *Itisnotfatalforthelastgenerationtobeinthisstate.
*/ if (child_slot < 0
|| ap_get_scoreboard_process(child_slot)->generation
== retained->mpm->my_generation) {
retained->mpm->shutdown_pending = 1;
child_fatal = 1; return;
} else {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, APLOGNO(00290) "Ignoring fatal error in child of previous " "generation (pid %ld).",
(long)pid.pid);
retained->sick_child_detected = 1;
}
} elseif (processed_status == APEXIT_CHILDSICK) { /* tell perform_idle_server_maintenance to check into this *onthenexttimerpop
*/
retained->sick_child_detected = 1;
} /* non-fatal death... note that it's gone in the scoreboard. */ if (child_slot >= 0) {
process_score *ps;
for (i = 0; i < threads_per_child; i++)
ap_update_child_status_from_indexes(child_slot, i,
SERVER_DEAD, NULL);
worker_note_child_killed(child_slot, 0, 0);
ps = &ap_scoreboard_image->parent[child_slot];
ps->quiescing = 0; if (processed_status == APEXIT_CHILDSICK) { /* resource shortage, minimize the fork rate */
retained->idle_spawn_rate[child_slot % num_buckets] = 1;
} elseif (remaining_children_to_start
&& child_slot < ap_daemons_limit) { /* we're still doing a 1-for-1 replacement of dead *childrenwithnewchildren
*/
make_child(ap_server_conf, child_slot,
child_slot % num_buckets);
--remaining_children_to_start;
}
} elseif (ap_unregister_extra_mpm_process(pid.pid, &old_gen) == 1) {
worker_note_child_killed(-1, /* already out of the scoreboard */
pid.pid, old_gen); if (processed_status == APEXIT_CHILDSICK
&& old_gen == retained->mpm->my_generation) { /* resource shortage, minimize the fork rate */ for (i = 0; i < num_buckets; i++) {
retained->idle_spawn_rate[i] = 1;
}
} #if APR_HAS_OTHER_CHILD
} elseif (apr_proc_other_child_alert(&pid, APR_OC_REASON_DEATH,
status) == 0) { /* handled */ #endif
} elseif (retained->mpm->was_graceful) { /* Great, we've probably just lost a slot in the *scoreboard.Somehowwedon'tknowaboutthischild.
*/
ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
ap_server_conf, APLOGNO(00291) "long lost child came home! (pid %ld)",
(long)pid.pid);
} /* Don't perform idle maintenance when a child dies, *onlydoitwhenthere'satimeout.Rememberonlya *finitenumberofchildrencandie,andit'spretty *pathologicalforalottodiesuddenly.Ifachildis *killedbyasignal(faulting)wewanttorestartitASAP *though,upto3successivefaultsorwestopthisuntil *atimeouthappensagain(toavoidthefloodoffork()ed *processesthatkeepbeingkilledearly).
*/ if (child_slot < 0 || !APR_PROC_CHECK_SIGNALED(exitwhy)) { continue;
} if (++successive_kills >= 3) { if (successive_kills % 10 == 3) {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0,
ap_server_conf, APLOGNO(10393) "children are killed successively!");
} continue;
}
++remaining_children_to_start;
} else {
successive_kills = 0;
}
if (remaining_children_to_start) { /* we hit a 1 second timeout in which none of the previous *generationofchildrenneededtobereaped...soassume *they'realldone,andpickuptheslackifanyisleft.
*/
startup_children(remaining_children_to_start);
remaining_children_to_start = 0; /* In any event we really shouldn't do the code below because *fewoftheserverswejuststartedareintheIDLEstate *yet,sowe'dmistakenlycreateanextraserver.
*/ continue;
}
for (i = 0; i < num_buckets; i++) {
perform_idle_server_maintenance(i);
}
}
}
staticint worker_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
{ int num_buckets = retained->mpm->num_buckets; int remaining_children_to_start; int i;
ap_log_pid(pconf, ap_pid_fname);
if (!retained->mpm->was_graceful) { if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
retained->mpm->mpm_state = AP_MPMQ_STOPPING; return !OK;
} /* fix the generation number in the global score; we just got a new, *clearedscoreboard
*/
ap_scoreboard_image->global->running_generation = retained->mpm->my_generation;
}
ap_unixd_mpm_set_signals(pconf, one_process);
/* Don't thrash since num_buckets depends on the *systemandthenumberofonlineCPUcores...
*/ if (ap_daemons_limit < num_buckets)
ap_daemons_limit = num_buckets; if (ap_daemons_to_start < num_buckets)
ap_daemons_to_start = num_buckets; /* We want to create as much children at a time as the number of buckets, *sotooptimallyacceptconnections(evenlydistributedacrossbuckets). *Thusmin_spare_threadsshouldatleastmaintainnum_bucketschildren, *andmax_spare_threadsallownum_bucketsmorechildrenw/otriggering *immediately(e.g.num_bucketsidlethreadsmargin,oneperbucket).
*/ if (min_spare_threads < threads_per_child * (num_buckets - 1) + num_buckets)
min_spare_threads = threads_per_child * (num_buckets - 1) + num_buckets; if (max_spare_threads < min_spare_threads + (threads_per_child + 1) * num_buckets)
max_spare_threads = min_spare_threads + (threads_per_child + 1) * num_buckets;
/* If we're doing a graceful_restart then we're going to see a lot *ofchildrenexitingimmediatelywhenwegetintothemainloop *below(becausewejustsentthemAP_SIG_GRACEFUL).Thishappenspretty *rapidly...andforeachonethatexitswemaystartanewone,until *thereareatleastmin_spare_threadsidlethreads,countingacross *allchildren.Butwemaybepermittedtostartmorechildrenthan *that,sowe'lljustkeeptrackofhowmanywe're *supposedtostartupwithoutthe1secondpenaltybetweeneachfork.
*/
remaining_children_to_start = ap_daemons_to_start; if (remaining_children_to_start > ap_daemons_limit) {
remaining_children_to_start = ap_daemons_limit;
} if (!retained->mpm->was_graceful) {
startup_children(remaining_children_to_start);
remaining_children_to_start = 0;
} else { /* give the system some time to recover before kicking into
* exponential mode */
retained->hold_off_on_exponential_spawning = 10;
}
if (retained->mpm->shutdown_pending && retained->mpm->is_ungraceful) { /* Time to shut down: *Killchildprocesses,tellthemtocallchild_exit,etc...
*/ for (i = 0; i < num_buckets; i++) {
ap_mpm_podx_killpg(all_buckets[i].pod, ap_daemons_limit,
AP_MPM_PODX_RESTART);
}
ap_reclaim_child_processes(1, /* Start with SIGTERM */
worker_note_child_killed);
if (!child_fatal) { /* cleanup pid file on normal shutdown */
ap_remove_pid(pconf, ap_pid_fname);
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0,
ap_server_conf, APLOGNO(00295) "caught SIGTERM, shutting down");
} return DONE;
}
if (retained->mpm->shutdown_pending) { /* Time to gracefully shut down: *Killchildprocesses,tellthemtocallchild_exit,etc...
*/ int active_children; int index;
apr_time_t cutoff = 0;
/* Close our listeners, and then ask our children to do same */
ap_close_listeners();
for (i = 0; i < num_buckets; i++) {
ap_mpm_podx_killpg(all_buckets[i].pod, ap_daemons_limit,
AP_MPM_PODX_GRACEFUL);
}
ap_relieve_child_processes(worker_note_child_killed);
if (!child_fatal) { /* cleanup pid file on normal shutdown */
ap_remove_pid(pconf, ap_pid_fname);
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00296) "caught " AP_SIG_GRACEFUL_STOP_STRING ", shutting down gracefully");
}
if (ap_graceful_shutdown_timeout) {
cutoff = apr_time_now() +
apr_time_from_sec(ap_graceful_shutdown_timeout);
}
/* Don't really exit until each child has finished */
retained->mpm->shutdown_pending = 0; do { /* Pause for a second */
apr_sleep(apr_time_from_sec(1));
/* Relieve any children which have now exited */
ap_relieve_child_processes(worker_note_child_killed);
active_children = 0; for (index = 0; index < ap_daemons_limit; ++index) { if (ap_mpm_safe_kill(MPM_CHILD_PID(index), 0) == APR_SUCCESS) {
active_children = 1; /* Having just one child is enough to stay around */ break;
}
}
} while (!retained->mpm->shutdown_pending && active_children &&
(!ap_graceful_shutdown_timeout || apr_time_now() < cutoff));
/* We might be here because we received SIGTERM, either *way,tryandmakesurethatallofourprocessesare *reallydead.
*/ for (i = 0; i < num_buckets; i++) {
ap_mpm_podx_killpg(all_buckets[i].pod, ap_daemons_limit,
AP_MPM_PODX_RESTART);
}
ap_reclaim_child_processes(1, worker_note_child_killed);
return DONE;
}
/* we've been told to restart */ if (one_process) { /* not worth thinking about */ return DONE;
}
/* advance to the next generation */ /* XXX: we really need to make sure this new generation number isn't in *usebyanyofthechildren.
*/
++retained->mpm->my_generation;
ap_scoreboard_image->global->running_generation = retained->mpm->my_generation;
if (!retained->mpm->is_ungraceful) {
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00297)
AP_SIG_GRACEFUL_STRING " received. Doing graceful restart"); /* wake up the children...time to die. But we'll have more soon */ for (i = 0; i < num_buckets; i++) {
ap_mpm_podx_killpg(all_buckets[i].pod, ap_daemons_limit,
AP_MPM_PODX_GRACEFUL);
}
/* This is mostly for debugging... so that we know what is still *gracefullydealingwithexistingrequest.
*/
} else { /* Kill 'em all. Since the child acts the same on the parents SIGTERM *andaSIGHUP,wemayaswellusethesamesignal,becausesomeuser *pthreadsarestealingsignalsfromusleftandright.
*/ for (i = 0; i < num_buckets; i++) {
ap_mpm_podx_killpg(all_buckets[i].pod, ap_daemons_limit,
AP_MPM_PODX_RESTART);
}
ap_reclaim_child_processes(1, /* Start with SIGTERM */
worker_note_child_killed);
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00298) "SIGHUP received. Attempting to restart");
}
return OK;
}
/* This really should be a post_config hook, but the error log is already *redirectedbythatpoint,soweneedtodothisintheopen_logsphase.
*/ staticint worker_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
{ int startup = 0; int level_flags = 0; int num_buckets = 0;
ap_listen_rec **listen_buckets;
apr_status_t rv; char id[16]; int i;
pconf = p;
/* the reverse of pre_config, we want this only the first time around */ if (retained->mpm->module_loads == 1) {
startup = 1;
level_flags |= APLOG_STARTUP;
}
if (one_process) {
num_buckets = 1;
} elseif (retained->mpm->was_graceful) { /* Preserve the number of buckets on graceful restarts. */
num_buckets = retained->mpm->num_buckets;
} if ((rv = ap_duplicate_listeners(pconf, ap_server_conf,
&listen_buckets, &num_buckets))) {
ap_log_error(APLOG_MARK, APLOG_CRIT | level_flags, rv,
(startup ? NULL : s), "could not duplicate listeners"); return !OK;
}
all_buckets = apr_pcalloc(pconf, num_buckets * sizeof(*all_buckets)); for (i = 0; i < num_buckets; i++) { if (!one_process && /* no POD in one_process mode */
(rv = ap_mpm_podx_open(pconf, &all_buckets[i].pod))) {
ap_log_error(APLOG_MARK, APLOG_CRIT | level_flags, rv,
(startup ? NULL : s), "could not open pipe-of-death"); return !OK;
} /* Initialize cross-process accept lock (safe accept needed only) */ if ((rv = SAFE_ACCEPT((apr_snprintf(id, sizeof id, "%i", i),
ap_proc_mutex_create(&all_buckets[i].mutex,
NULL, AP_ACCEPT_MUTEX_TYPE,
id, s, pconf, 0))))) {
ap_log_error(APLOG_MARK, APLOG_CRIT | level_flags, rv,
(startup ? NULL : s), "could not create accept mutex"); return !OK;
}
all_buckets[i].listeners = listen_buckets[i];
}
if (retained->mpm->max_buckets < num_buckets) { int new_max, *new_ptr;
new_max = retained->mpm->max_buckets * 2; if (new_max < num_buckets) {
new_max = num_buckets;
}
new_ptr = (int *)apr_palloc(ap_pglobal, new_max * sizeof(int)); if (retained->idle_spawn_rate) /* NULL at startup */
memcpy(new_ptr, retained->idle_spawn_rate,
retained->mpm->num_buckets * sizeof(int));
retained->idle_spawn_rate = new_ptr;
retained->mpm->max_buckets = new_max;
} if (retained->mpm->num_buckets < num_buckets) { int rate_max = 1; /* If new buckets are added, set their idle spawn rate to *thehighestsofar,sothattheygetfilledasquickly *astheexistingones.
*/ for (i = 0; i < retained->mpm->num_buckets; i++) { if (rate_max < retained->idle_spawn_rate[i]) {
rate_max = retained->idle_spawn_rate[i];
}
} for (/* up to date i */; i < num_buckets; i++) {
retained->idle_spawn_rate[i] = rate_max;
}
}
retained->mpm->num_buckets = num_buckets;
/* sigh, want this only the second time around */ if (retained->mpm->module_loads == 2) { if (!one_process && !foreground) { /* before we detach, setup crash handlers to log to errorlog */
ap_fatal_signal_setup(ap_server_conf, pconf);
rv = apr_proc_detach(no_detach ? APR_PROC_DETACH_FOREGROUND
: APR_PROC_DETACH_DAEMONIZE); if (rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, APLOGNO(00299) "apr_proc_detach failed"); return HTTP_INTERNAL_SERVER_ERROR;
}
}
}
/* the reverse of pre_config, we want this only the first time around */ if (retained->mpm->module_loads == 1) {
startup = 1;
}
if (server_limit > MAX_SERVER_LIMIT) { if (startup) {
ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00300) "WARNING: ServerLimit of %d exceeds compile-time " "limit of %d servers, decreasing to %d.",
server_limit, MAX_SERVER_LIMIT, MAX_SERVER_LIMIT);
} else {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00301) "ServerLimit of %d exceeds compile-time limit " "of %d, decreasing to match",
server_limit, MAX_SERVER_LIMIT);
}
server_limit = MAX_SERVER_LIMIT;
} elseif (server_limit < 1) { if (startup) {
ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00302) "WARNING: ServerLimit of %d not allowed, " "increasing to 1.", server_limit);
} else {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00303) "ServerLimit of %d not allowed, increasing to 1",
server_limit);
}
server_limit = 1;
}
/* you cannot change ServerLimit across a restart; ignore *anysuchattempts
*/ if (!retained->first_server_limit) {
retained->first_server_limit = server_limit;
} elseif (server_limit != retained->first_server_limit) { /* don't need a startup console version here */
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00304) "changing ServerLimit to %d from original value of %d " "not allowed during restart",
server_limit, retained->first_server_limit);
server_limit = retained->first_server_limit;
}
if (thread_limit > MAX_THREAD_LIMIT) { if (startup) {
ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00305) "WARNING: ThreadLimit of %d exceeds compile-time " "limit of %d threads, decreasing to %d.",
thread_limit, MAX_THREAD_LIMIT, MAX_THREAD_LIMIT);
} else {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00306) "ThreadLimit of %d exceeds compile-time limit " "of %d, decreasing to match",
thread_limit, MAX_THREAD_LIMIT);
}
thread_limit = MAX_THREAD_LIMIT;
} elseif (thread_limit < 1) { if (startup) {
ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00307) "WARNING: ThreadLimit of %d not allowed, " "increasing to 1.", thread_limit);
} else {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00308) "ThreadLimit of %d not allowed, increasing to 1",
thread_limit);
}
thread_limit = 1;
}
/* you cannot change ThreadLimit across a restart; ignore *anysuchattempts
*/ if (!retained->first_thread_limit) {
retained->first_thread_limit = thread_limit;
} elseif (thread_limit != retained->first_thread_limit) { /* don't need a startup console version here */
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00309) "changing ThreadLimit to %d from original value of %d " "not allowed during restart",
thread_limit, retained->first_thread_limit);
thread_limit = retained->first_thread_limit;
}
if (threads_per_child > thread_limit) { if (startup) {
ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00310) "WARNING: ThreadsPerChild of %d exceeds ThreadLimit " "of %d threads, decreasing to %d. " "To increase, please see the ThreadLimit directive.",
threads_per_child, thread_limit, thread_limit);
} else {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00311) "ThreadsPerChild of %d exceeds ThreadLimit " "of %d, decreasing to match",
threads_per_child, thread_limit);
}
threads_per_child = thread_limit;
} elseif (threads_per_child < 1) { if (startup) {
ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00312) "WARNING: ThreadsPerChild of %d not allowed, " "increasing to 1.", threads_per_child);
} else {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00313) "ThreadsPerChild of %d not allowed, increasing to 1",
threads_per_child);
}
threads_per_child = 1;
}
if (max_workers < threads_per_child) { if (startup) {
ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00314) "WARNING: MaxRequestWorkers of %d is less than " "ThreadsPerChild of %d, increasing to %d. " "MaxRequestWorkers must be at least as large " "as the number of threads in a single server.",
max_workers, threads_per_child, threads_per_child);
} else {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00315) "MaxRequestWorkers of %d is less than ThreadsPerChild " "of %d, increasing to match",
max_workers, threads_per_child);
}
max_workers = threads_per_child;
}
if (max_workers % threads_per_child) { int tmp_max_workers = ap_daemons_limit * threads_per_child;
if (startup) {
ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00316) "WARNING: MaxRequestWorkers of %d is not an integer " "multiple of ThreadsPerChild of %d, decreasing to nearest " "multiple %d, for a maximum of %d servers.",
max_workers, threads_per_child, tmp_max_workers,
ap_daemons_limit);
} else {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00317) "MaxRequestWorkers of %d is not an integer multiple of " "ThreadsPerChild of %d, decreasing to nearest " "multiple %d", max_workers, threads_per_child,
tmp_max_workers);
}
max_workers = tmp_max_workers;
}
if (ap_daemons_limit > server_limit) { if (startup) {
ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00318) "WARNING: MaxRequestWorkers of %d would require %d " "servers and would exceed ServerLimit of %d, decreasing to %d. " "To increase, please see the ServerLimit directive.",
max_workers, ap_daemons_limit, server_limit,
server_limit * threads_per_child);
} else {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00319) "MaxRequestWorkers of %d would require %d servers and " "exceed ServerLimit of %d, decreasing to %d",
max_workers, ap_daemons_limit, server_limit,
server_limit * threads_per_child);
}
ap_daemons_limit = server_limit;
}
/* ap_daemons_to_start > ap_daemons_limit checked in worker_run() */ if (ap_daemons_to_start < 1) { if (startup) {
ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00320) "WARNING: StartServers of %d not allowed, " "increasing to 1.", ap_daemons_to_start);
} else {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00321) "StartServers of %d not allowed, increasing to 1",
ap_daemons_to_start);
}
ap_daemons_to_start = 1;
}
if (min_spare_threads < 1) { if (startup) {
ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00322) "WARNING: MinSpareThreads of %d not allowed, " "increasing to 1 to avoid almost certain server failure. " "Please read the documentation.", min_spare_threads);
} else {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00323) "MinSpareThreads of %d not allowed, increasing to 1",
min_spare_threads);
}
min_spare_threads = 1;
}
staticvoid worker_hooks(apr_pool_t *p)
{ /* Our open_logs hook function must run before the core's, or stderr *willberedirectedtoafile,andthemessageswon'tprinttothe *console.
*/ staticconstchar *const aszSucc[] = {"core.c", NULL};
one_process = 0;
ap_hook_open_logs(worker_open_logs, NULL, aszSucc, APR_HOOK_REALLY_FIRST); /* we need to set the MPM state before other pre-config hooks use MPM query *toretrieveit,soregisterasREALLY_FIRST
*/
ap_hook_pre_config(worker_pre_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
ap_hook_check_config(worker_check_config, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_mpm(worker_run, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_mpm_query(worker_query, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_mpm_get_name(worker_get_name, NULL, NULL, APR_HOOK_MIDDLE);
}
staticconst command_rec worker_cmds[] = {
LISTEN_COMMANDS,
AP_INIT_TAKE1("StartServers", set_daemons_to_start, NULL, RSRC_CONF, "Number of child processes launched at server startup"),
AP_INIT_TAKE1("MinSpareThreads", set_min_spare_threads, NULL, RSRC_CONF, "Minimum number of idle threads, to handle request spikes"),
AP_INIT_TAKE1("MaxSpareThreads", set_max_spare_threads, NULL, RSRC_CONF, "Maximum number of idle threads"),
AP_INIT_TAKE1("MaxRequestWorkers", set_max_workers, NULL, RSRC_CONF, "Maximum number of threads alive at the same time"),
AP_INIT_TAKE1("MaxClients", set_max_workers, NULL, RSRC_CONF, "Deprecated name of MaxRequestWorkers"),
AP_INIT_TAKE1("ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, "Number of threads each child creates"),
AP_INIT_TAKE1("ServerLimit", set_server_limit, NULL, RSRC_CONF, "Maximum number of child processes for this run of Apache"),
AP_INIT_TAKE1("ThreadLimit", set_thread_limit, NULL, RSRC_CONF, "Maximum number of worker threads per child process for this run of Apache - Upper limit for ThreadsPerChild"),
AP_GRACEFUL_SHUTDOWN_TIMEOUT_COMMAND,
{ NULL }
};
¤ Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.0.146Bemerkung:
(vorverarbeitet am 2026-09-30)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.