/* 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.
*/
#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 *thisareneeded. * *Wekeepthisforonereasonitkeepsthesizeofthescoreboardfilesmall *enoughthatwecanreadthewholethingwithoutworryingtoomuchabout *theoverhead.
*/ #ifndef DEFAULT_THREAD_LIMIT #define DEFAULT_THREAD_LIMIT 64 #endif
struct event_conn_state_t { /** APR_RING of expiration timeouts */
APR_RING_ENTRY(event_conn_state_t) timeout_list; /** the time when the entry was queued */
apr_time_t queue_timestamp; /** connection record this struct refers to */
conn_rec *c; /** request record (if any) this struct refers to */
request_rec *r; /** server config this struct refers to */
event_srv_cfg *sc; /** scoreboard handle for the conn_rec */
ap_sb_handle_t *sbh; /** is the current conn_rec suspended? (disassociated with *aparticularMPMthread;forsuspend_/resume_connection *hooks)
*/ int suspended; /** memory pool to allocate from */
apr_pool_t *p; /** bucket allocator */
apr_bucket_alloc_t *bucket_alloc; /** poll file descriptor information */
apr_pollfd_t pfd; /** public parts of the connection state */
conn_state_t pub; /** chaining in defer_linger_chain */ struct event_conn_state_t *chain; unsignedint /** Is lingering close from defer_lingering_close()? */
deferred_linger :1, /** Has ap_start_lingering_close() been called? */
linger_started :1;
};
/* Prevent extra poll/wakeup calls for timeouts close in the future (queues *havethegranularityofasecondanyway). *XXX:Wouldn't0.5s(insteadof0.1s)be"enough"?
*/ #define TIMEOUT_FUDGE_FACTOR apr_time_from_msec(100)
APR_RING_INSERT_TAIL(&q->head, el, event_conn_state_t, timeout_list);
++*q->total;
++q->count;
/* Cheaply update the global queues_next_expiry with the one of the *firstentryofthisqueue(oldest)ifitexpiresbefore.
*/
el = APR_RING_FIRST(&q->head);
elem_expiry = el->queue_timestamp + q->timeout;
next_expiry = queues_next_expiry; if (!next_expiry || next_expiry > elem_expiry + TIMEOUT_FUDGE_FACTOR) {
queues_next_expiry = elem_expiry; /* Unblock the poll()ing listener for it to update its timeout. */ if (listener_is_wakeable) {
apr_pollset_wakeup(event_pollset);
}
}
}
/* The structure used to pass unique initialization info to each thread */ typedefstruct
{ int pslot; /* process slot */ int tslot; /* worker slot of the thread */
} 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;
/* data retained by event across load/unload of the module *allocatedonfirstcalltopre-confighook;locatedon *subsequentcallstopre-confighook
*/ typedefstruct event_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_daemon_used;
/* *Allrunningworkers,activeandshuttingdown,includingthosethat *maybeleftfrombeforeagracefulrestart. *Notkeptup-to-datewhenshutdownispending.
*/ int total_daemons; /* *Workersthatstillactive,i.e.arenotshuttingdowngracefully.
*/ int active_daemons; /* *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;
} event_retained_data; static event_retained_data *retained;
/* The event 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;
staticint ap_child_slot; /* Current child process slot in scoreboard */
/* The LISTENER_SIGNAL signal will be sent from the main thread to the *listenerthreadtowakeitupforgracefultermination(whatachild *processfromanoldgenerationdoeswhentheadmindoes"apachectl *graceful").Thissignalwillbeblockedinallthreadsofachild *processexceptforthelistenerthread.
*/ #define LISTENER_SIGNAL SIGHUP
/* An array of socket descriptors in use by each thread used to *performanon-graceful(forced)shutdownoftheserver.
*/ static apr_socket_t **worker_sockets;
staticvolatile apr_uint32_t listensocks_disabled;
staticvoid disable_listensocks(void)
{ int i; if (apr_atomic_cas32(&listensocks_disabled, 1, 0) != 0) { return;
} if (event_pollset) { for (i = 0; i < num_listensocks; i++) {
apr_pollset_remove(event_pollset, &listener_pollfd[i]);
}
}
ap_scoreboard_image->parent[ap_child_slot].not_accepting = 1;
}
staticvoid enable_listensocks(void)
{ int i; if (listener_may_exit
|| apr_atomic_cas32(&listensocks_disabled, 0, 1) != 1) { return;
}
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(00457) "Accepting new connections again: " "%u active conns (%u lingering/%u clogged/%u suspended), " "%u idle workers",
apr_atomic_read32(&connection_count),
apr_atomic_read32(&lingering_count),
apr_atomic_read32(&clogged_count),
apr_atomic_read32(&suspended_count),
ap_queue_info_num_idlers(worker_queue_info)); for (i = 0; i < num_listensocks; i++)
apr_pollset_add(event_pollset, &listener_pollfd[i]); /* *XXX:Thisisnotyetoptimal.Ifmanyworkerssuddenlybecomeavailable, *XXX:theparentmaykillsomeprocessesofftoosoon.
*/
ap_scoreboard_image->parent[ap_child_slot].not_accepting = 0;
}
/* 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 */
}
/* *Deferflushandcloseoftheconnectionbyaddingittodefer_linger_chain, *foraworkertograbitanddothejob(shouldthatbeblocking). *Pre-condition:nonblocking,canbecalledfromanywhereprovidedcsisnot *inanytimeoutqueueorinthepollset.
*/ staticint defer_lingering_close(event_conn_state_t *cs)
{
ap_log_cerror(APLOG_MARK, APLOG_TRACE6, 0, cs->c, "deferring close from state %i", (int)cs->pub.state);
/* The connection is not shutdown() yet strictly speaking, but it's not *inanyqueuenorhandledbyaworkereither(willbeverysoon),so *toaccountforitsomewherewebumplingering_countnow(andset *deferred_lingerforprocess_lingering_close()toknow).
*/
cs->pub.state = CONN_STATE_LINGER;
apr_atomic_inc32(&lingering_count);
cs->deferred_linger = 1; for (;;) {
event_conn_state_t *chain = cs->chain = defer_linger_chain; if (apr_atomic_casptr((void *)&defer_linger_chain, cs,
chain) != chain) { /* Race lost, try again */ continue;
} return1;
}
}
/* Close the connection and release its resources (ptrans), either because an *unrecoverableerroroccured(queuesorpollsetadd/remove)ormoreusually *iflingeringclosetimedout. *Pre-condition:nonblocking,canbecalledfromanywhereprovidedcsisnot *inanytimeoutqueueorinthepollset.
*/ staticvoid close_connection(event_conn_state_t *cs)
{
ap_log_cerror(APLOG_MARK, APLOG_TRACE6, 0, cs->c, "closing connection from state %i", (int)cs->pub.state);
/** *XXXIftheplatformdoesnothaveausablewayofbundling *accept()withasocketreadabilitycheck,likeWin32, *andtherearemeasurabledelaysbeforethe *socketisreadableduetothefirstdatapacketarriving, *itmightbebettertocreatethecsonthelistenerthread *withthestatesettoCONN_STATE_KEEPALIVE * *FreeBSDuserswillwanttoenabletheHTTPacceptfilter *moduleintheirkernelforthehighestperformance *Whentheacceptfilterisactive,socketsarekeptinthe *kerneluntilaHTTPrequestisreceived.
*/
cs->pub.state = CONN_STATE_PROCESSING;
cs->pub.sense = CONN_SENSE_DEFAULT;
} else {
c = cs->c;
ap_update_sb_handle(cs->sbh, my_child_num, my_thread_num);
notify_resume(cs, 0);
c->current_thread = thd; /* Subsequent request on a conn, and thread number is part of ID */
c->id = conn_id;
}
if (CONN_STATE_IS_LINGERING_CLOSE(cs->pub.state)) { goto lingering_close;
}
if (cs->pub.state == CONN_STATE_PROCESSING /* If we have an input filter which 'clogs' the input stream, *likemod_sslusedto,letsjustdothenormalreadfrominput *filters,liketheWorkerMPMdoes.Filtersthatneedtowrite *wheretheywouldotherwiseread,orreadwheretheywould *otherwisewrite,shouldsetthesenseappropriately.
*/
|| c->clogging_input_filters) {
process_connection:
cs->pub.state = CONN_STATE_PROCESSING;
if (cs->pub.state == CONN_STATE_ASYNC_WAITIO) { /* Set a read/write timeout for this connection, and let the *eventthreadpollforread/writeability.
*/
cs->queue_timestamp = apr_time_now();
notify_suspend(cs);
/* Fall through */
cs->pub.state = CONN_STATE_KEEPALIVE;
}
if (cs->pub.state == CONN_STATE_KEEPALIVE) {
ap_update_child_status(cs->sbh, SERVER_BUSY_KEEPALIVE, NULL);
/* It greatly simplifies the logic to use a single timeout value per q *becausethenewelementcanjustbeaddedtotheendofthelistand *itwillstaysortedinexpirationtimesequence.Ifbrandnew *socketsaresenttotheeventthreadforareadabilitycheck,this *willbeaslightbehaviorchange-theyusethenon-keepalive *timeouttoday.Withanormalclient,thesocketwillbereadablein *afewmillisecondsanyway.
*/
cs->queue_timestamp = apr_time_now();
notify_suspend(cs);
if (cs->pub.state == CONN_STATE_SUSPENDED) {
apr_atomic_inc32(&suspended_count);
notify_suspend(cs); return;
}
lingering_close: /* CONN_STATE_LINGER[_*] fall through process_lingering_close() */
process_lingering_close(cs);
}
/* conns_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) {
ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, ap_server_conf, "Stopping process due to MaxConnectionsPerChild");
signal_threads(ST_GRACEFUL);
} /* keep going */
conns_this_child = APR_INT32_MAX;
}
ap_close_listeners_ex(my_bucket->listeners);
*closed = 1; /* once */
dying = 1;
ap_scoreboard_image->parent[ap_child_slot].quiescing = 1; for (i = 0; i < threads_per_child; ++i) {
ap_update_child_status_from_indexes(ap_child_slot, i,
SERVER_GRACEFUL, NULL);
} /* wake up the main thread */
kill(ap_my_pid, SIGTERM);
/* Same goal as for TIMEOUT_FUDGE_FACTOR (avoid extra poll calls), but applied *totimers.Sincetheirtimeoutsarecustom(userdefined),wecan'tbetoo *approximativehere(henceusing0.01s).
*/ #define EVENT_FUDGE_FACTOR apr_time_from_msec(10)
/* The following compare function is used by apr_skiplist_insert() to keep the *elements(timers)sortedandprovideO(logn)complexity(thisisalsotrue *forapr_skiplist_{find,remove}(),butthosearenotusedinMPMeventwhere *insertedtimersarenotsearchednorremoved,butwithapr_skiplist_pop() *whichdoesuseanycomparefunction).Itismeanttoreturn0whena==b, *<0whena<b,and>0whena>b.Howeverapr_skiplist_insert()willnot *addduplicates(i.e.a==b),andapr_skiplist_add()isonlyavailablein *APR1.6,yetmultipletimerscouldpossiblybecreatedinthesamemicro- *second(duplicateswithregardtoapr_time_t);thereforeweimplementthe *comparefunctiontoreturn+1insteadof0whencomparedtimersareequal, *thusduplicatesarestilladdedaftereachother(inorderofinsertion).
*/ staticint timer_comp(void *a, void *b)
{
apr_time_t t1 = (apr_time_t) ((timer_event_t *)a)->when;
apr_time_t t2 = (apr_time_t) ((timer_event_t *)b)->when;
AP_DEBUG_ASSERT(t1);
AP_DEBUG_ASSERT(t2); return ((t1 < t2) ? -1 : 1);
}
/* Okay, add sorted by when.. */
apr_skiplist_insert(timer_skiplist, te);
/* Cheaply update the global timers_next_expiry with this event's *ifitexpiresbefore.
*/
next_expiry = timers_next_expiry; if (!next_expiry || next_expiry > te->when + EVENT_FUDGE_FACTOR) {
timers_next_expiry = te->when; /* Unblock the poll()ing listener for it to update its timeout. */ if (listener_is_wakeable) {
apr_pollset_wakeup(event_pollset);
}
}
}
ap_log_cerror(APLOG_MARK, APLOG_TRACE6, 0, cs->c, "lingering close from state %i", (int)cs->pub.state);
AP_DEBUG_ASSERT(CONN_STATE_IS_LINGERING_CLOSE(cs->pub.state));
if (!cs->linger_started) {
cs->pub.state = CONN_STATE_LINGER;
cs->linger_started = 1;
/* defer_lingering_close() may have bumped lingering_count already */ if (!cs->deferred_linger) {
apr_atomic_inc32(&lingering_count);
}
apr_socket_timeout_set(csd, apr_time_from_sec(SECONDS_TO_LINGER)); if (ap_start_lingering_close(cs->c)) {
notify_suspend(cs);
close_connection(cs); return;
}
/* All nonblocking from now, no need for APR_INCOMPLETE_READ either */
apr_socket_timeout_set(csd, 0);
apr_socket_opt_set(csd, APR_INCOMPLETE_READ, 0);
/* One timestamp/duration for the whole lingering close time. *XXX:Thismakesthe(short_)linger_qnotsorted/orderedbyexpiring *timeoutswhenevermultipleschedulesarenecessary(EAGAINbelow), *butweprobabalydon'tcaresincetheseconnectionsdonotcount *forconnections_above_limit()andallofthemwillbekilledwhen *busyorgracefullystoppinganyway.
*/
cs->queue_timestamp = apr_time_now();
}
do {
nbytes = sizeof(dummybuf);
rv = apr_socket_recv(csd, dummybuf, &nbytes);
} while (rv == APR_SUCCESS);
if (!APR_STATUS_IS_EAGAIN(rv)) {
close_connection(cs); return;
}
/* (Re)queue the connection to come back when readable */
update_reqevents_from_sense(cs, CONN_SENSE_WANT_READ);
q = (cs->pub.state == CONN_STATE_LINGER_SHORT) ? short_linger_q : linger_q;
apr_thread_mutex_lock(timeout_mutex);
TO_QUEUE_APPEND(q, cs);
rv = apr_pollset_add(event_pollset, &cs->pfd); if (rv != APR_SUCCESS && !APR_STATUS_IS_EEXIST(rv)) {
AP_DEBUG_ASSERT(0);
TO_QUEUE_REMOVE(q, cs);
apr_thread_mutex_unlock(timeout_mutex);
ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, APLOGNO(03092) "process_lingering_close: apr_pollset_add failure");
close_connection(cs);
signal_threads(ST_GRACEFUL); return;
}
apr_thread_mutex_unlock(timeout_mutex);
}
/* call 'func' for all elements of 'q' above 'expiry'. *Pre-condition:timeout_mutexmustalreadybelocked *Post-condition:timeout_mutexwillbelockedagain
*/ staticvoid process_timeout_queue(struct timeout_queue *q, apr_time_t expiry, int (*func)(event_conn_state_t *))
{
apr_uint32_t total = 0, count;
event_conn_state_t *first, *cs, *last; struct event_conn_state_t trash; struct timeout_queue *qp;
apr_status_t rv;
if (!*q->total) { return;
}
APR_RING_INIT(&trash.timeout_list, event_conn_state_t, timeout_list); for (qp = q; qp; qp = qp->next) {
count = 0;
cs = first = last = APR_RING_FIRST(&qp->head); while (cs != APR_RING_SENTINEL(&qp->head, event_conn_state_t,
timeout_list)) { /* Trash the entry if: *-noexpirywasgiven(zeromeansall),or *-itexpired(accordingtothequeuetimeout),or *-thesystemclockskewedinthepast:noentryshouldbe *registeredabovethegivenexpiry(~now)+thequeue *timeout,wewon'tkeepanyhere(eg.forcenturies). * *Otherwisestop,nofollowingentrywillmatchthankstothe *singletimeoutperqueue(entriesareaddedtotheend!). *ThisallowsmaintenanceinO(1).
*/ if (expiry && cs->queue_timestamp + qp->timeout > expiry
&& cs->queue_timestamp < expiry + qp->timeout) { /* Since this is the next expiring entry of this queue, update *theglobalqueues_next_expiryifit'slaterthanthisone.
*/
apr_time_t elem_expiry = cs->queue_timestamp + qp->timeout;
apr_time_t next_expiry = queues_next_expiry; if (!next_expiry
|| next_expiry > elem_expiry + TIMEOUT_FUDGE_FACTOR) {
queues_next_expiry = elem_expiry;
} break;
}
APR_RING_UNSPLICE(first, last, timeout_list);
APR_RING_SPLICE_TAIL(&trash.timeout_list, first, last, event_conn_state_t,
timeout_list);
AP_DEBUG_ASSERT(*q->total >= count && qp->count >= count);
*q->total -= count;
qp->count -= count;
total += count;
} if (!total) return;
apr_thread_mutex_unlock(timeout_mutex);
first = APR_RING_FIRST(&trash.timeout_list); do {
cs = APR_RING_NEXT(first, timeout_list);
TO_QUEUE_ELEM_INIT(first);
func(first);
first = cs;
} while (--total);
apr_thread_mutex_lock(timeout_mutex);
}
staticvoid process_keepalive_queue(apr_time_t expiry)
{ /* If all workers are busy, we kill older keep-alive connections so *thattheymayconnecttoanotherprocess.
*/ if (!expiry && *keepalive_q->total) {
ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, ap_server_conf, "All workers are busy or dying, will shutdown %u " "keep-alive connections", *keepalive_q->total);
}
process_timeout_queue(keepalive_q, expiry, shutdown_connection);
}
/* 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);
for (;;) {
timer_event_t *te; const apr_pollfd_t *out_pfd;
apr_int32_t num = 0;
apr_interval_time_t timeout;
apr_time_t now, expiry = -1; int workers_were_busy = 0;
if (conns_this_child <= 0)
check_infinite_requests();
if (listener_may_exit) { int first_close = close_listeners(&closed);
if (terminate_mode == ST_UNGRACEFUL
|| apr_atomic_read32(&connection_count) == 0) break;
/* Don't wait in poll() for the first close (i.e. dying now), we *wanttomaintainthequeuesandscheduledefer_linger_chainASAP *tokillkept-aliveconnectionandshutdowntheworkersandchild *faster.
*/ if (first_close) { goto do_maintenance; /* with expiry == -1 */
}
}
now = apr_time_now(); if (APLOGtrace6(ap_server_conf)) { /* trace log status every second */ if (now - last_log > apr_time_from_sec(1)) {
ap_log_error(APLOG_MARK, APLOG_TRACE6, 0, ap_server_conf, "connections: %u (waitio:%u write-completion:%u" "keep-alive:%u lingering:%u suspended:%u clogged:%u), " "workers: %u/%u shutdown",
apr_atomic_read32(&connection_count),
apr_atomic_read32(waitio_q->total),
apr_atomic_read32(write_completion_q->total),
apr_atomic_read32(keepalive_q->total),
apr_atomic_read32(&lingering_count),
apr_atomic_read32(&suspended_count),
apr_atomic_read32(&clogged_count),
apr_atomic_read32(&threads_shutdown),
threads_per_child);
last_log = now;
}
}
/* Start with an infinite poll() timeout and update it according to *thenextexpiringtimerorqueueentry.Iftherearenone,either *thelisteneriswakeableanditcanpoll()indefinitelyuntilawake *upoccurs,otherwiseperiodicchecks(maintenance,shutdown,...) *mustbeperformed.
*/
now = apr_time_now();
timeout = -1;
/* Push expired timers to a worker, the first remaining one determines *themaximumtimetopoll()below,ifany.
*/
expiry = timers_next_expiry; if (expiry && expiry < now) {
apr_thread_mutex_lock(g_timer_skiplist_mtx); while ((te = apr_skiplist_peek(timer_skiplist))) { if (te->when > now) {
timers_next_expiry = te->when;
timeout = te->when - now; break;
}
apr_skiplist_pop(timer_skiplist, NULL);
push_timer2worker(te);
} if (!te) {
timers_next_expiry = 0;
}
apr_thread_mutex_unlock(g_timer_skiplist_mtx);
}
/* Same for queues, use their next expiry, if any. */
expiry = queues_next_expiry; if (expiry
&& (timeout < 0
|| expiry <= now
|| timeout > expiry - now)) {
timeout = expiry > now ? expiry - now : 0;
}
/* When non-wakeable, don't wait more than 100 ms, in any case. */ #define NON_WAKEABLE_POLL_TIMEOUT apr_time_from_msec(100) if (!listener_is_wakeable
&& (timeout < 0
|| timeout > NON_WAKEABLE_POLL_TIMEOUT)) {
timeout = NON_WAKEABLE_POLL_TIMEOUT;
} elseif (timeout > 0) { /* apr_pollset_poll() might round down the timeout to milliseconds, *let'sforciblyroundupheretoneverreturnbeforethetimeout.
*/
timeout = apr_time_from_msec(
apr_time_as_msec(timeout + apr_time_from_msec(1) - 1)
);
}
/* XXX possible optimization: stash the current time for use as *r->request_timefornewrequestsorqueuesmaintenance
*/
for (; num; --num, ++out_pfd) {
listener_poll_type *pt = (listener_poll_type *) out_pfd->client_data; if (pt->type == PT_CSD) { /* one of the sockets is readable */
event_conn_state_t *cs = (event_conn_state_t *) pt->baton; struct timeout_queue *remove_from_q = NULL; /* don't wait for a worker for a keepalive request or
* lingering close processing. */ int blocking = 0;
if (csd != NULL) {
conns_this_child--; if (push2worker(NULL, csd, ptrans) == APR_SUCCESS) {
have_idle_worker = 0;
}
} else {
ap_queue_info_push_pool(worker_queue_info, ptrans);
}
}
} /* if:else on pt->type */
} /* for processing poll */
/* We process the timeout queues here only when the global *queues_next_expiryispassed.Thishappensaccuratelysince *addingtothequeues(inworkers)canonlydecreasethisexpiry, *whilelatestonesareonlytakenintoaccounthere(inlistener) *duringqueues'processing,withthelockheld.Thisworksboth *withandwithoutwake-ability.
*/
expiry = queues_next_expiry;
do_maintenance: if (expiry && expiry < (now = apr_time_now())) {
ap_log_error(APLOG_MARK, APLOG_TRACE7, 0, ap_server_conf, "queues maintenance with timeout=%" APR_TIME_T_FMT,
expiry > 0 ? expiry - now : -1);
apr_thread_mutex_lock(timeout_mutex);
/* Steps below will recompute this. */
queues_next_expiry = 0;
/* Step 1: keepalive queue timeouts are closed */ if (workers_were_busy || dying) {
process_keepalive_queue(0); /* kill'em all \m/ */
} else {
process_keepalive_queue(now);
}
/* Step 4: normal lingering close queue timeouts are closed */ if (dying && linger_q->timeout > short_linger_q->timeout) { /* Dying, force short timeout for normal lingering close */
linger_q->timeout = short_linger_q->timeout;
}
process_timeout_queue(linger_q, now, shutdown_connection);
/* Step 5: short lingering close queue timeouts are closed */
process_timeout_queue(short_linger_q, now, shutdown_connection);
apr_thread_mutex_unlock(timeout_mutex);
ap_log_error(APLOG_MARK, APLOG_TRACE7, 0, ap_server_conf, "queues maintained with timeout=%" APR_TIME_T_FMT,
queues_next_expiry > now ? queues_next_expiry - now
: -1);
if (rv != APR_SUCCESS) { /* We get APR_EOF during a graceful shutdown once all the *connectionsacceptedbythisserverprocesshavebeenhandled.
*/ if (APR_STATUS_IS_EOF(rv)) { break;
} /* We get APR_EINTR whenever ap_queue_pop_*() has been interrupted *fromanexplicitcalltoap_queue_interrupt_all().Thisallows *ustounblockthreadsstuckinap_queue_pop_*()whenashutdown *ispending. * *Ifworkers_may_exitissetandthisisungracefultermination/ *restart,weareboundtogetanerroronsomesystems(e.g., *AIX,whichsanity-checksmutexoperations)sincethequeue *mayhavealreadybeencleanedup.Don'tlogthe"error"if *workers_may_exitisset.
*/ elseif (APR_STATUS_IS_EINTR(rv)) { goto worker_pop;
} /* We got some other error. */ elseif (!workers_may_exit) {
ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
APLOGNO(03099) "ap_queue_pop_socket failed");
} continue;
} if (te != NULL) {
te->cbfunc(te->baton);
/* 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(03100) "ap_queue_create() failed");
clean_child_exit(APEXIT_CHILDFATAL);
}
if (ap_max_mem_free != APR_ALLOCATOR_MAX_FREE_UNLIMITED) { /* If we want to conserve memory, let's not keep an unlimited number of *pools&allocators. *XXX:Thisshouldprobablybeaseparateconfigdirective
*/
max_recycled_pools = threads_per_child * 3 / 4 ;
}
rv = ap_queue_info_create(&worker_queue_info, pruntime,
threads_per_child, max_recycled_pools); if (rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf, APLOGNO(03101) "ap_queue_info_create() failed");
clean_child_exit(APEXIT_CHILDFATAL);
}
/* Create the timeout mutex and main pollset before the listener *threadstarts.
*/
rv = apr_thread_mutex_create(&timeout_mutex, APR_THREAD_MUTEX_DEFAULT,
pruntime); if (rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, APLOGNO(03102) "creation of the timeout mutex failed.");
clean_child_exit(APEXIT_CHILDFATAL);
}
/* Create the main pollset. When APR_POLLSET_WAKEABLE is asked we account *forthewakeuppipeexplicitelywithpollset_size+1becausesomepollset *implementationsdon'tdoitimplicitelyinAPR.
*/
pollset_flags = APR_POLLSET_THREADSAFE | APR_POLLSET_NOCOPY |
APR_POLLSET_WAKEABLE | APR_POLLSET_NODEFAULT; for (i = 0; i < sizeof(good_methods) / sizeof(good_methods[0]); i++) {
rv = apr_pollset_create_ex(&event_pollset, pollset_size + 1, pruntime,
pollset_flags, good_methods[i]); if (rv == APR_SUCCESS) {
listener_is_wakeable = 1; break;
}
} if (rv != APR_SUCCESS) {
pollset_flags &= ~APR_POLLSET_NODEFAULT;
rv = apr_pollset_create(&event_pollset, pollset_size + 1, pruntime,
pollset_flags); if (rv == APR_SUCCESS) {
listener_is_wakeable = 1;
} else {
pollset_flags &= ~APR_POLLSET_WAKEABLE;
rv = apr_pollset_create(&event_pollset, pollset_size, pruntime,
pollset_flags);
}
} if (rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, APLOGNO(03103) "apr_pollset_create with Thread Safety failed.");
clean_child_exit(APEXIT_CHILDFATAL);
}
/* Add listeners to the main pollset */
listener_pollfd = apr_pcalloc(pruntime, num_listensocks * sizeof(apr_pollfd_t)); for (i = 0, lr = my_bucket->listeners; lr; lr = lr->next, i++) {
apr_pollfd_t *pfd;
listener_poll_type *pt;
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;
/* 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(03104) "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;
}
/* 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(00475) "the listener thread didn't stop accepting");
} else {
rv = apr_thread_join(&thread_rv, listener); if (rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00476) "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 */
rv = apr_thread_join(&thread_rv, threads[i]); if (rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00477) "apr_thread_join: unable to join worker " "thread %d", i);
}
}
}
}
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(00478) "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(10377) "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(00479) "Couldn't initialize signal thread");
clean_child_exit(APEXIT_CHILDFATAL);
}
ap_run_child_init(pchild, ap_server_conf);
if (ap_max_requests_per_child) {
conns_this_child = ap_max_requests_per_child;
} else { /* coding a value of zero means infinity */
conns_this_child = APR_INT32_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 = ap_calloc(threads_per_child, sizeof(apr_thread_t *));
ts = 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(02436) "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(00480) "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);
/* helps us terminate a little more quickly than the dispatch of the *signalthread;beatsthePipeofDeathandthebrowsers
*/
signal_threads(ST_UNGRACEFUL);
/* A terminating signal was received. Now join each of the *workerstocleanthemup. *Iftheworkeralreadyexited,thenthejoinfrees *theirresourcesandreturns. *Iftheworkerhasn'texited,thenthisblocksuntil *theyhave(thencleansup).
*/
join_workers(ts->listener, threads);
} 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).
*/
ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, ap_server_conf, "%s termination received, joining workers",
rv == AP_MPM_PODX_GRACEFUL ? "graceful" : "ungraceful");
join_workers(ts->listener, threads);
ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, ap_server_conf, "%s termination, workers joined, exiting",
rv == AP_MPM_PODX_GRACEFUL ? "graceful" : "ungraceful");
}
if (ap_scoreboard_image->parent[slot].pid != 0) { /* XXX replace with assert or remove ? */
ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(03455) "BUG: Scoreboard slot %d should be empty but is " "in use by pid %" APR_PID_T_FMT,
slot, ap_scoreboard_image->parent[slot].pid); return -1;
}
if ((pid = fork()) == -1) {
ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, APLOGNO(00481) "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(00482) "processor unbind failed"); #endif
RAISE_SIGSTOP(MAKE_CHILD);
/* start up a bunch of children */ staticvoid startup_children(int number_to_start)
{ int i;
for (i = 0; number_to_start && i < server_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 *max_daemon_used)
{ int num_buckets = retained->mpm->num_buckets; int idle_thread_count = 0;
process_score *ps; int free_length = 0; int free_slots[MAX_SPAWN_RATE]; int last_non_dead = -1; int active_thread_count = 0; int i, j;
for (i = 0; i < server_limit; ++i) { if (num_buckets > 1 && (i % num_buckets) != child_bucket) { /* We only care about child_bucket in this call */ continue;
} if (i >= retained->max_daemon_used &&
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]; if (ps->pid != 0) { int child_threads_active = 0; if (ps->quiescing == 1) {
ps->quiescing = 2;
retained->active_daemons--;
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, "Child %d quiescing: pid %d, gen %d, " "active %d/%d, total %d/%d/%d",
i, (int)ps->pid, (int)ps->generation,
retained->active_daemons, active_daemons_limit,
retained->total_daemons, retained->max_daemon_used,
server_limit);
} 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 (status <= SERVER_READY && !ps->quiescing && !ps->not_accepting
&& 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 (child_threads_active == threads_per_child) {
had_healthy_child = 1;
}
last_non_dead = i;
} elseif (free_length < retained->idle_spawn_rate[child_bucket]) {
free_slots[free_length++] = i;
}
} if (*max_daemon_used < last_non_dead + 1) {
*max_daemon_used = 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(02324) "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) { /* *Childprocessesthatweasktoshutdownwon'tdieimmediately *butmaystayaroundforalongtimewhentheyfinishtheir *requests.Iftheserverloadchangesmanytimes,manysuch *gracefullyfinishingprocessesmayaccumulate,fillingupthe *scoreboard.Toavoidrunningoutofscoreboardentries,we *don'tshutdownmoreprocessesiftherearestoppingones *already(i.e.active_daemons!=total_daemons)andnotenough *slackspaceinthescoreboardforagracefulrestart. * *XXXItwouldbeniceifwecould *XXX-killprocesseswithoutkeepaliveconnectionsfirst *XXX-tellchildrentostopacceptingnewconnections,and *XXXdependingonserverload,laterbeabletoresurrectthem *orkillthem
*/ int do_kill = (retained->active_daemons == retained->total_daemons
|| (server_limit - retained->total_daemons >
active_daemons_limit));
ap_log_error(APLOG_MARK, APLOG_TRACE5, 0, ap_server_conf, "%shutting down one child: " "active %d/%d, total %d/%d/%d, " "idle threads %d, max workers %d",
(do_kill) ? "S" : "Not s",
retained->active_daemons, active_daemons_limit,
retained->total_daemons, retained->max_daemon_used,
server_limit, idle_thread_count, max_workers); if (do_kill) {
ap_mpm_podx_signal(all_buckets[child_bucket].pod,
AP_MPM_PODX_GRACEFUL);
} else { /* Wait for dying daemon(s) to exit */
}
retained->idle_spawn_rate[child_bucket] = 1;
} elseif (idle_thread_count < min_spare_threads / num_buckets) { if (active_thread_count >= max_workers / num_buckets) { if (0 == idle_thread_count) { if (!retained->maxclients_reported) {
ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(00484) "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(10159) "server is within MinSpareThreads of " "MaxRequestWorkers, consider raising the " "MaxRequestWorkers setting");
retained->near_maxclients_reported = 1;
}
}
retained->idle_spawn_rate[child_bucket] = 1;
} elseif (free_length == 0) { /* scoreboard is full, can't fork */
ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(03490) "scoreboard is full, not at MaxRequestWorkers." "Increase ServerLimit.");
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 (free_length + retained->active_daemons > active_daemons_limit) { if (retained->active_daemons < active_daemons_limit) {
free_length = active_daemons_limit - retained->active_daemons;
} else {
ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, ap_server_conf, "server is at active daemons limit, spawning " "of %d children cancelled: active %d/%d, " "total %d/%d/%d, rate %d", free_length,
retained->active_daemons, active_daemons_limit,
retained->total_daemons, retained->max_daemon_used,
server_limit, retained->idle_spawn_rate[child_bucket]); /* reset the spawning rate and prevent its growth below */
retained->idle_spawn_rate[child_bucket] = 1;
++retained->hold_off_on_exponential_spawning;
free_length = 0;
}
} if (retained->idle_spawn_rate[child_bucket] >= 8) {
ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf, APLOGNO(00486) "server seems busy, (you may need " "to increase StartServers, ThreadsPerChild " "or Min/MaxSpareThreads), " "spawning %d children, there are around %d idle " "threads, %d active children, and %d children " "that are shutting down", free_length,
idle_thread_count, retained->active_daemons,
retained->total_daemons);
} for (i = 0; i < free_length; ++i) { int slot = free_slots[i]; if (make_child(ap_server_conf, slot, child_bucket) < 0) { continue;
} if (*max_daemon_used < slot + 1) {
*max_daemon_used = slot + 1;
}
} /* 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 max_daemon_used = 0; int successive_kills = 0; 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; /* *total_daemonscountingwillbeoffnow,butaswe *areshuttingdown,thatisnotanissueanymore.
*/ return;
} else {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, APLOGNO(00487) "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) {
event_note_child_stopped(child_slot, 0, 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) { /* 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;
}
} #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(00488) "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(10392) "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;
}
max_daemon_used = 0; for (i = 0; i < num_buckets; i++) {
perform_idle_server_maintenance(i, &max_daemon_used);
}
retained->max_daemon_used = max_daemon_used;
}
}
staticint event_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 (active_daemons_limit < num_buckets)
active_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 > active_daemons_limit) {
remaining_children_to_start = active_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, active_daemons_limit,
AP_MPM_PODX_RESTART);
}
ap_reclaim_child_processes(1, /* Start with SIGTERM */
event_note_child_stopped);
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(00491) "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, active_daemons_limit,
AP_MPM_PODX_GRACEFUL);
}
ap_relieve_child_processes(event_note_child_stopped);
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(00492) "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(event_note_child_stopped);
active_children = 0; for (index = 0; index < retained->max_daemon_used; ++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, active_daemons_limit,
AP_MPM_PODX_RESTART);
}
ap_reclaim_child_processes(1, event_note_child_stopped);
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(00493)
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, active_daemons_limit,
AP_MPM_PODX_GRACEFUL);
}
/* This is mostly for debugging... so that we know what is still *gracefullydealingwithexistingrequest.
*/
} else {
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(00494) "SIGHUP received. Attempting to restart"); /* 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, active_daemons_limit,
AP_MPM_PODX_RESTART);
}
ap_reclaim_child_processes(1, /* Start with SIGTERM */
event_note_child_stopped);
}
/* This really should be a post_config hook, but the error log is already *redirectedbythatpoint,soweneedtodothisintheopen_logsphase.
*/ staticint event_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; 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;
}
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;
/* for skiplist */
srand((unsignedint)apr_time_now()); return OK;
}
/* test once for correct operation of fdqueue */ if (test_atomics || retained->mpm->module_loads == 2) { static apr_uint32_t foo1, foo2;
apr_atomic_set32(&foo1, 100);
foo2 = apr_atomic_add32(&foo1, -10); if (foo2 != 100 || foo1 != 90) {
ap_log_error(APLOG_MARK, APLOG_CRIT, 0, NULL, APLOGNO(02405) "atomics not working as expected - add32 of negative number"); return HTTP_INTERNAL_SERVER_ERROR;
}
}
/* sigh, want this only the second time around */ if (retained->mpm->module_loads == 2) {
rv = apr_pollset_create(&event_pollset, 1, plog,
APR_POLLSET_THREADSAFE | APR_POLLSET_NOCOPY); if (rv != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, APLOGNO(00495) "Couldn't create a Thread Safe Pollset. " "Is it supported on your platform?" "Also check system or user limits!"); return HTTP_INTERNAL_SERVER_ERROR;
}
apr_pollset_destroy(event_pollset);
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(00496) "apr_proc_detach failed"); return HTTP_INTERNAL_SERVER_ERROR;
}
}
}
for (; s; s = s->next) {
event_srv_cfg *sc = apr_pcalloc(pconf, sizeof *sc);
ap_set_module_config(s->module_config, &mpm_event_module, sc); if (!io.tail) { /* The main server uses the global queues */
io.q = TO_QUEUE_MAKE(pconf, s->timeout, NULL);
apr_hash_set(io.hash, &s->timeout, sizeof s->timeout, io.q);
io.tail = waitio_q = io.q;
/* 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(00497) "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(00498) "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(00499) "WARNING: ServerLimit of %d not allowed, " "increasing to 1.", server_limit);
} else {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00500) "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(00501) "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(00502) "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(00503) "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(00504) "WARNING: ThreadLimit of %d not allowed, " "increasing to 1.", thread_limit);
} else {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00505) "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(00506) "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(00507) "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(00508) "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(00509) "WARNING: ThreadsPerChild of %d not allowed, " "increasing to 1.", threads_per_child);
} else {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00510) "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(00511) "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(00512) "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 = active_daemons_limit * threads_per_child;
if (startup) {
ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00513) "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,
active_daemons_limit);
} else {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00514) "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 (active_daemons_limit > server_limit) { if (startup) {
ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00515) "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, active_daemons_limit, server_limit,
server_limit * threads_per_child);
} else {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00516) "MaxRequestWorkers of %d would require %d servers and " "exceed ServerLimit of %d, decreasing to %d",
max_workers, active_daemons_limit, server_limit,
server_limit * threads_per_child);
}
active_daemons_limit = server_limit;
}
/* ap_daemons_to_start > active_daemons_limit checked in ap_mpm_run() */ if (ap_daemons_to_start < 1) { if (startup) {
ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00517) "WARNING: StartServers of %d not allowed, " "increasing to 1.", ap_daemons_to_start);
} else {
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00518) "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(00519) "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(00520) "MinSpareThreads of %d not allowed, increasing to 1",
min_spare_threads);
}
min_spare_threads = 1;
}
val = strtod(arg, &endptr); if (*endptr) return"error parsing value";
if (val <= 0) return"AsyncRequestWorkerFactor argument must be a positive number";
worker_factor = val * WORKER_FACTOR_SCALE; if (worker_factor < WORKER_FACTOR_SCALE) {
worker_factor = WORKER_FACTOR_SCALE;
} return NULL;
}
staticconst command_rec event_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("ServerLimit", set_server_limit, NULL, RSRC_CONF, "Maximum number of child processes for this run of Apache"),
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("MaxClients", set_max_workers, NULL, RSRC_CONF, "Deprecated name of MaxRequestWorkers"),
AP_INIT_TAKE1("MaxRequestWorkers", set_max_workers, NULL, RSRC_CONF, "Maximum number of threads alive at the same time"),
AP_INIT_TAKE1("ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF, "Number of threads each child creates"),
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_INIT_TAKE1("AsyncRequestWorkerFactor", set_worker_factor, NULL, RSRC_CONF, "How many additional connects will be accepted per idle " "worker thread"),
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.193Bemerkung:
(vorverarbeitet am 2026-09-28)
¤
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.