1
/* Licensed to the Apache Software Foundation (ASF) under one or more
2
* contributor license agreements. See the NOTICE file distributed with
3
* this work for additional information regarding copyright ownership.
4
* The ASF licenses this file to You under the Apache License, Version 2.0
5
* (the "License"); you may not use this file except in compliance with
6
* the License. You may obtain a copy of the License at
8
* http://www.apache.org/licenses/LICENSE-2.0
10
* Unless required by applicable law or agreed to in writing, software
11
* distributed under the License is distributed on an "AS IS" BASIS,
12
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
* See the License for the specific language governing permissions and
14
* limitations under the License.
18
#include "apr_portable.h"
19
#include "apr_strings.h"
20
#include "apr_thread_proc.h"
21
#include "apr_signal.h"
23
#define APR_WANT_STDIO
24
#define APR_WANT_STRFUNC
30
#if APR_HAVE_SYS_TYPES_H
31
#include <sys/types.h>
36
#include "ap_config.h"
38
#include "mpm_default.h"
39
#include "http_main.h"
41
#include "http_config.h"
42
#include "http_core.h" /* for get_remote_host */
43
#include "http_connection.h"
44
#include "scoreboard.h"
47
#include "mpm_common.h"
48
#include "ap_listen.h"
53
#include <bstring.h> /* for IRIX, FD_SET calls bzero() */
58
#ifdef HAVE_SYS_PROCESSOR_H
59
#include <sys/processor.h> /* for bindprocessor() */
63
#include <sys/times.h>
65
/* Limit on the total --- clients will be locked out if more servers than
66
* this are needed. It is intended solely to keep the server from crashing
67
* when things get out of hand.
69
* We keep a hard maximum number of servers, for two reasons --- first off,
70
* in case something goes seriously wrong, we want to stop the fork bomb
71
* short of actually crashing the machine we're running on by filling some
72
* kernel table. Secondly, it keeps the size of the scoreboard file small
73
* enough that we can read the whole thing without worrying too much about
76
#ifndef DEFAULT_SERVER_LIMIT
77
#define DEFAULT_SERVER_LIMIT 256
80
/* Admin can't tune ServerLimit beyond MAX_SERVER_LIMIT. We want
81
* some sort of compile-time limit to help catch typos.
83
#ifndef MAX_SERVER_LIMIT
84
#define MAX_SERVER_LIMIT 200000
87
#ifndef HARD_THREAD_LIMIT
88
#define HARD_THREAD_LIMIT 1
93
int ap_threads_per_child=0; /* Worker threads per child */
94
static apr_proc_mutex_t *accept_mutex;
95
static int ap_daemons_to_start=0;
96
static int ap_daemons_min_free=0;
97
static int ap_daemons_max_free=0;
98
static int ap_daemons_limit=0; /* MaxClients */
99
static int server_limit = DEFAULT_SERVER_LIMIT;
100
static int first_server_limit = 0;
101
static int changed_limit_at_restart;
102
static int mpm_state = AP_MPMQ_STARTING;
103
static ap_pod_t *pod;
106
* The max child slot ever assigned, preserved across restarts. Necessary
107
* to deal with MaxClients changes across AP_SIG_GRACEFUL restarts. We
108
* use this value to optimize routines that have to scan the entire scoreboard.
110
int ap_max_daemons_limit = -1;
111
server_rec *ap_server_conf;
113
/* one_process --- debugging mode variable; can be set from the command line
114
* with the -X flag. If set, this gets you the child_main loop running
115
* in the process which originally started up (no detach, no make_child),
116
* which is a pretty nice debugging environment. (You'll get a SIGHUP
117
* early in standalone_main; just continue through. This is the server
118
* trying to kill off any child processes which it might have lying
119
* around --- Apache doesn't keep track of their pids, it just sends
120
* SIGHUP to the process group, ignoring it in the root process.
121
* Continue through and you'll be fine.).
124
static int one_process = 0;
126
static apr_pool_t *pconf; /* Pool for config stuff */
127
static apr_pool_t *pchild; /* Pool for httpd child stuff */
129
static pid_t ap_my_pid; /* it seems silly to call getpid all the time */
130
static pid_t parent_pid;
132
static int my_child_num;
134
ap_generation_t volatile ap_my_generation=0;
138
char tpf_server_name[INETD_SERVNAME_LENGTH+1];
141
static volatile int die_now = 0;
145
* change directory for gprof to plop the gmon.out file
146
* configure in httpd.conf:
147
* GprofDir $RuntimeDir/ -> $ServerRoot/$RuntimeDir/gmon.out
148
* GprofDir $RuntimeDir/% -> $ServerRoot/$RuntimeDir/gprof.$pid/gmon.out
150
static void chdir_for_gprof(void)
152
core_server_config *sconf =
153
ap_get_module_config(ap_server_conf->module_config, &core_module);
154
char *dir = sconf->gprof_dir;
160
int len = strlen(sconf->gprof_dir) - 1;
161
if(*(dir + len) == '%') {
163
buf = ap_append_pid(pconf, dir, "gprof.");
165
use_dir = ap_server_root_relative(pconf, buf ? buf : dir);
166
res = apr_dir_make(use_dir,
167
APR_UREAD | APR_UWRITE | APR_UEXECUTE |
168
APR_GREAD | APR_GEXECUTE |
169
APR_WREAD | APR_WEXECUTE, pconf);
170
if(res != APR_SUCCESS && !APR_STATUS_IS_EEXIST(res)) {
171
ap_log_error(APLOG_MARK, APLOG_ERR, res, ap_server_conf,
172
"gprof: error creating directory %s", dir);
176
use_dir = ap_server_root_relative(pconf, DEFAULT_REL_RUNTIMEDIR);
182
#define chdir_for_gprof()
185
/* XXX - I don't know if TPF will ever use this module or not, so leave
186
* the ap_check_signals calls in but disable them - manoj */
187
#define ap_check_signals()
189
/* a clean exit from a child with proper cleanup */
190
static void clean_child_exit(int code) __attribute__ ((noreturn));
191
static void clean_child_exit(int code)
193
mpm_state = AP_MPMQ_STOPPING;
196
apr_pool_destroy(pchild);
198
ap_mpm_pod_close(pod);
203
static void accept_mutex_on(void)
205
apr_status_t rv = apr_proc_mutex_lock(accept_mutex);
206
if (rv != APR_SUCCESS) {
207
const char *msg = "couldn't grab the accept mutex";
209
if (ap_my_generation !=
210
ap_scoreboard_image->global->running_generation) {
211
ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, NULL, "%s", msg);
215
ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "%s", msg);
216
exit(APEXIT_CHILDFATAL);
221
static void accept_mutex_off(void)
223
apr_status_t rv = apr_proc_mutex_unlock(accept_mutex);
224
if (rv != APR_SUCCESS) {
225
const char *msg = "couldn't release the accept mutex";
227
if (ap_my_generation !=
228
ap_scoreboard_image->global->running_generation) {
229
ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, NULL, "%s", msg);
230
/* don't exit here... we have a connection to
231
* process, after which point we'll see that the
232
* generation changed and we'll exit cleanly
236
ap_log_error(APLOG_MARK, APLOG_EMERG, rv, NULL, "%s", msg);
237
exit(APEXIT_CHILDFATAL);
242
/* On some architectures it's safe to do unserialized accept()s in the single
243
* Listen case. But it's never safe to do it in the case where there's
244
* multiple Listen statements. Define SINGLE_LISTEN_UNSERIALIZED_ACCEPT
245
* when it's safe in the single Listen case.
247
#ifdef SINGLE_LISTEN_UNSERIALIZED_ACCEPT
248
#define SAFE_ACCEPT(stmt) do {if (ap_listeners->next) {stmt;}} while(0)
250
#define SAFE_ACCEPT(stmt) do {stmt;} while(0)
253
AP_DECLARE(apr_status_t) ap_mpm_query(int query_code, int *result)
256
case AP_MPMQ_MAX_DAEMON_USED:
257
*result = ap_daemons_limit;
259
case AP_MPMQ_IS_THREADED:
260
*result = AP_MPMQ_NOT_SUPPORTED;
262
case AP_MPMQ_IS_FORKED:
263
*result = AP_MPMQ_DYNAMIC;
265
case AP_MPMQ_HARD_LIMIT_DAEMONS:
266
*result = server_limit;
268
case AP_MPMQ_HARD_LIMIT_THREADS:
269
*result = HARD_THREAD_LIMIT;
271
case AP_MPMQ_MAX_THREADS:
274
case AP_MPMQ_MIN_SPARE_DAEMONS:
275
*result = ap_daemons_min_free;
277
case AP_MPMQ_MIN_SPARE_THREADS:
280
case AP_MPMQ_MAX_SPARE_DAEMONS:
281
*result = ap_daemons_max_free;
283
case AP_MPMQ_MAX_SPARE_THREADS:
286
case AP_MPMQ_MAX_REQUESTS_DAEMON:
287
*result = ap_max_requests_per_child;
289
case AP_MPMQ_MAX_DAEMONS:
290
*result = server_limit;
292
case AP_MPMQ_MPM_STATE:
299
#if defined(NEED_WAITPID)
301
Systems without a real waitpid sometimes lose a child's exit while waiting
302
for another. Search through the scoreboard for missing children.
304
int reap_children(int *exitcode, apr_exit_why_e *status)
308
for (n = 0; n < ap_max_daemons_limit; ++n) {
309
if (ap_scoreboard_image->servers[n][0].status != SERVER_DEAD &&
310
kill((pid = ap_scoreboard_image->parent[n].pid), 0) == -1) {
311
ap_update_child_status_from_indexes(n, 0, SERVER_DEAD, NULL);
312
/* just mark it as having a successful exit status */
313
*status = APR_PROC_EXIT;
322
/*****************************************************************
323
* Connection structures and accounting...
326
static void just_die(int sig)
331
static void stop_listening(int sig)
333
ap_close_listeners();
335
/* For a graceful stop, we want the child to exit when done */
339
/* volatile just in case */
340
static int volatile shutdown_pending;
341
static int volatile restart_pending;
342
static int volatile is_graceful;
344
static void sig_term(int sig)
346
if (shutdown_pending == 1) {
347
/* Um, is this _probably_ not an error, if the user has
348
* tried to do a shutdown twice quickly, so we won't
349
* worry about reporting it.
353
shutdown_pending = 1;
354
is_graceful = (sig == AP_SIG_GRACEFUL_STOP);
357
/* restart() is the signal handler for SIGHUP and AP_SIG_GRACEFUL
358
* in the parent process, unless running in ONE_PROCESS mode
360
static void restart(int sig)
362
if (restart_pending == 1) {
363
/* Probably not an error - don't bother reporting it */
367
is_graceful = (sig == AP_SIG_GRACEFUL);
370
static void set_signals(void)
372
#ifndef NO_USE_SIGACTION
377
ap_fatal_signal_setup(ap_server_conf, pconf);
380
#ifndef NO_USE_SIGACTION
381
sigemptyset(&sa.sa_mask);
384
sa.sa_handler = sig_term;
385
if (sigaction(SIGTERM, &sa, NULL) < 0)
386
ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGTERM)");
387
#ifdef AP_SIG_GRACEFUL_STOP
388
if (sigaction(AP_SIG_GRACEFUL_STOP, &sa, NULL) < 0)
389
ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf,
390
"sigaction(" AP_SIG_GRACEFUL_STOP_STRING ")");
393
if (sigaction(SIGINT, &sa, NULL) < 0)
394
ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGINT)");
397
sa.sa_handler = SIG_DFL;
398
if (sigaction(SIGXCPU, &sa, NULL) < 0)
399
ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXCPU)");
402
sa.sa_handler = SIG_DFL;
403
if (sigaction(SIGXFSZ, &sa, NULL) < 0)
404
ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGXFSZ)");
407
sa.sa_handler = SIG_IGN;
408
if (sigaction(SIGPIPE, &sa, NULL) < 0)
409
ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGPIPE)");
412
/* we want to ignore HUPs and AP_SIG_GRACEFUL while we're busy
415
sigaddset(&sa.sa_mask, SIGHUP);
416
sigaddset(&sa.sa_mask, AP_SIG_GRACEFUL);
417
sa.sa_handler = restart;
418
if (sigaction(SIGHUP, &sa, NULL) < 0)
419
ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGHUP)");
420
if (sigaction(AP_SIG_GRACEFUL, &sa, NULL) < 0)
421
ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(" AP_SIG_GRACEFUL_STRING ")");
425
apr_signal(SIGXCPU, SIG_DFL);
428
apr_signal(SIGXFSZ, SIG_DFL);
432
apr_signal(SIGTERM, sig_term);
434
apr_signal(SIGHUP, restart);
436
#ifdef AP_SIG_GRACEFUL
437
apr_signal(AP_SIG_GRACEFUL, restart);
438
#endif /* AP_SIG_GRACEFUL */
439
#ifdef AP_SIG_GRACEFUL_STOP
440
apr_signal(AP_SIG_GRACEFUL_STOP, sig_term);
441
#endif /* AP_SIG_GRACEFUL */
443
apr_signal(SIGPIPE, SIG_IGN);
449
/*****************************************************************
450
* Child process main loop.
451
* The following vars are static to avoid getting clobbered by longjmp();
452
* they are really private to child_main.
455
static int requests_this_child;
456
static int num_listensocks = 0;
459
int ap_graceful_stop_signalled(void)
461
/* not ever called anymore... */
466
static void child_main(int child_num_arg)
469
apr_allocator_t *allocator;
473
apr_pollset_t *pollset;
475
apr_bucket_alloc_t *bucket_alloc;
476
int last_poll_idx = 0;
478
mpm_state = AP_MPMQ_STARTING; /* for benefit of any hooks that run as this
482
my_child_num = child_num_arg;
483
ap_my_pid = getpid();
484
requests_this_child = 0;
486
ap_fatal_signal_child_setup(ap_server_conf);
488
/* Get a sub context for global allocations in this child, so that
489
* we can have cleanups occur when the child exits.
491
apr_allocator_create(&allocator);
492
apr_allocator_max_free_set(allocator, ap_max_mem_free);
493
apr_pool_create_ex(&pchild, pconf, NULL, allocator);
494
apr_allocator_owner_set(allocator, pchild);
496
apr_pool_create(&ptrans, pchild);
497
apr_pool_tag(ptrans, "transaction");
499
/* needs to be done before we switch UIDs so we have permissions */
500
ap_reopen_scoreboard(pchild, NULL, 0);
501
status = apr_proc_mutex_child_init(&accept_mutex, ap_lock_fname, pchild);
502
if (status != APR_SUCCESS) {
503
ap_log_error(APLOG_MARK, APLOG_EMERG, status, ap_server_conf,
504
"Couldn't initialize cross-process lock in child "
505
"(%s) (%d)", ap_lock_fname, ap_accept_lock_mech);
506
clean_child_exit(APEXIT_CHILDFATAL);
509
if (unixd_setup_child()) {
510
clean_child_exit(APEXIT_CHILDFATAL);
513
ap_run_child_init(pchild, ap_server_conf);
515
ap_create_sb_handle(&sbh, pchild, my_child_num, 0);
517
(void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
519
/* Set up the pollfd array */
520
/* ### check the status */
521
(void) apr_pollset_create(&pollset, num_listensocks, pchild, 0);
523
for (lr = ap_listeners, i = num_listensocks; i--; lr = lr->next) {
524
apr_pollfd_t pfd = { 0 };
526
pfd.desc_type = APR_POLL_SOCKET;
528
pfd.reqevents = APR_POLLIN;
529
pfd.client_data = lr;
531
/* ### check the status */
532
(void) apr_pollset_add(pollset, &pfd);
535
mpm_state = AP_MPMQ_RUNNING;
537
bucket_alloc = apr_bucket_alloc_create(pchild);
540
conn_rec *current_conn;
544
* (Re)initialize this child to a pre-connection state.
547
apr_pool_clear(ptrans);
549
if ((ap_max_requests_per_child > 0
550
&& requests_this_child++ >= ap_max_requests_per_child)) {
554
(void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
557
* Wait for an acceptable connection to arrive.
560
/* Lock around "accept", if necessary */
561
SAFE_ACCEPT(accept_mutex_on());
563
if (num_listensocks == 1) {
564
/* There is only one listener record, so refer to that one. */
568
/* multiple listening sockets - need to poll */
571
const apr_pollfd_t *pdesc;
573
/* timeout == -1 == wait forever */
574
status = apr_pollset_poll(pollset, -1, &numdesc, &pdesc);
575
if (status != APR_SUCCESS) {
576
if (APR_STATUS_IS_EINTR(status)) {
577
if (one_process && shutdown_pending) {
582
/* Single Unix documents select as returning errnos
583
* EBADF, EINTR, and EINVAL... and in none of those
584
* cases does it make sense to continue. In fact
585
* on Linux 2.0.x we seem to end up with EFAULT
586
* occasionally, and we'd loop forever due to it.
588
ap_log_error(APLOG_MARK, APLOG_ERR, status,
589
ap_server_conf, "apr_pollset_poll: (listen)");
593
/* We can always use pdesc[0], but sockets at position N
594
* could end up completely starved of attention in a very
595
* busy server. Therefore, we round-robin across the
596
* returned set of descriptors. While it is possible that
597
* the returned set of descriptors might flip around and
598
* continue to starve some sockets, we happen to know the
599
* internal pollset implementation retains ordering
600
* stability of the sockets. Thus, the round-robin should
601
* ensure that a socket will eventually be serviced.
603
if (last_poll_idx >= numdesc)
606
/* Grab a listener record from the client_data of the poll
607
* descriptor, and advance our saved index to round-robin
610
* ### hmm... this descriptor might have POLLERR rather
613
lr = pdesc[last_poll_idx++].client_data;
618
/* if we accept() something we don't want to die, so we have to
621
status = lr->accept_func(&csd, lr, ptrans);
623
SAFE_ACCEPT(accept_mutex_off()); /* unlock after "accept" */
625
if (status == APR_EGENERAL) {
626
/* resource shortage or should-not-occur occured */
629
else if (status != APR_SUCCESS) {
634
* We now have a connection, so set it up with the appropriate
635
* socket options, file descriptors, and read/write buffers.
638
current_conn = ap_run_create_connection(ptrans, ap_server_conf, csd, my_child_num, sbh, bucket_alloc);
640
ap_process_connection(current_conn, csd);
641
ap_lingering_close(current_conn);
644
/* Check the pod and the generation number after processing a
645
* connection so that we'll go away if a graceful restart occurred
646
* while we were processing the connection or we are the lucky
647
* idle server process that gets to die.
649
if (ap_mpm_pod_check(pod) == APR_SUCCESS) { /* selected as idle? */
652
else if (ap_my_generation !=
653
ap_scoreboard_image->global->running_generation) { /* restart? */
654
/* yeah, this could be non-graceful restart, in which case the
655
* parent will kill us soon enough, but why bother checking?
664
static int make_child(server_rec *s, int slot)
668
if (slot + 1 > ap_max_daemons_limit) {
669
ap_max_daemons_limit = slot + 1;
673
apr_signal(SIGHUP, sig_term);
674
/* Don't catch AP_SIG_GRACEFUL in ONE_PROCESS mode :) */
675
apr_signal(SIGINT, sig_term);
677
apr_signal(SIGQUIT, SIG_DFL);
679
apr_signal(SIGTERM, sig_term);
684
(void) ap_update_child_status_from_indexes(slot, 0, SERVER_STARTING,
685
(request_rec *) NULL);
689
/* BS2000 requires a "special" version of fork() before a setuid() call */
690
if ((pid = os_fork(unixd_config.user_name)) == -1) {
692
if ((pid = os_fork(s, slot)) == -1) {
694
if ((pid = fork()) == -1) {
696
ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, "fork: Unable to fork new process");
698
/* fork didn't succeed. Fix the scoreboard or else
699
* it will say SERVER_STARTING forever and ever
701
(void) ap_update_child_status_from_indexes(slot, 0, SERVER_DEAD,
702
(request_rec *) NULL);
704
/* In case system resources are maxxed out, we don't want
705
* Apache running away with the CPU trying to fork over and
706
* over and over again.
714
#ifdef HAVE_BINDPROCESSOR
715
/* by default AIX binds to a single processor
716
* this bit unbinds children which will then bind to another cpu
718
int status = bindprocessor(BINDPROCESS, (int)getpid(),
719
PROCESSOR_CLASS_ANY);
721
ap_log_error(APLOG_MARK, APLOG_WARNING, errno,
722
ap_server_conf, "processor unbind failed %d", status);
725
RAISE_SIGSTOP(MAKE_CHILD);
727
/* Disable the parent's signal handlers and set up proper handling in
730
apr_signal(SIGHUP, just_die);
731
apr_signal(SIGTERM, just_die);
732
/* The child process just closes listeners on AP_SIG_GRACEFUL.
733
* The pod is used for signalling the graceful restart.
735
apr_signal(AP_SIG_GRACEFUL, stop_listening);
739
ap_scoreboard_image->parent[slot].pid = pid;
745
/* start up a bunch of children */
746
static void startup_children(int number_to_start)
750
for (i = 0; number_to_start && i < ap_daemons_limit; ++i) {
751
if (ap_scoreboard_image->servers[i][0].status != SERVER_DEAD) {
754
if (make_child(ap_server_conf, i) < 0) {
763
* idle_spawn_rate is the number of children that will be spawned on the
764
* next maintenance cycle if there aren't enough idle servers. It is
765
* doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
766
* without the need to spawn.
768
static int idle_spawn_rate = 1;
769
#ifndef MAX_SPAWN_RATE
770
#define MAX_SPAWN_RATE (32)
772
static int hold_off_on_exponential_spawning;
774
static void perform_idle_server_maintenance(apr_pool_t *p)
781
int free_slots[MAX_SPAWN_RATE];
785
/* initialize the free_list */
793
for (i = 0; i < ap_daemons_limit; ++i) {
796
if (i >= ap_max_daemons_limit && free_length == idle_spawn_rate)
798
ws = &ap_scoreboard_image->servers[i][0];
800
if (status == SERVER_DEAD) {
801
/* try to keep children numbers as low as possible */
802
if (free_length < idle_spawn_rate) {
803
free_slots[free_length] = i;
808
/* We consider a starting server as idle because we started it
809
* at least a cycle ago, and if it still hasn't finished starting
810
* then we're just going to swamp things worse by forking more.
811
* So we hopefully won't need to fork more if we count it.
812
* This depends on the ordering of SERVER_READY and SERVER_STARTING.
814
if (status <= SERVER_READY) {
816
/* always kill the highest numbered child if we have to...
817
* no really well thought out reason ... other than observing
818
* the server behaviour under linux where lower numbered children
819
* tend to service more hits (and hence are more likely to have
820
* their data in cpu caches).
829
ap_max_daemons_limit = last_non_dead + 1;
830
if (idle_count > ap_daemons_max_free) {
831
/* kill off one child... we use the pod because that'll cause it to
832
* shut down gracefully, in case it happened to pick up a request
833
* while we were counting
835
ap_mpm_pod_signal(pod);
838
else if (idle_count < ap_daemons_min_free) {
839
/* terminate the free list */
840
if (free_length == 0) {
841
/* only report this condition once */
842
static int reported = 0;
845
ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf,
846
"server reached MaxClients setting, consider"
847
" raising the MaxClients setting");
853
if (idle_spawn_rate >= 8) {
854
ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf,
855
"server seems busy, (you may need "
856
"to increase StartServers, or Min/MaxSpareServers), "
857
"spawning %d children, there are %d idle, and "
858
"%d total children", idle_spawn_rate,
859
idle_count, total_non_dead);
861
for (i = 0; i < free_length; ++i) {
863
if (make_child(ap_server_conf, free_slots[i]) == -1) {
864
if(free_length == 1) {
865
shutdown_pending = 1;
866
ap_log_error(APLOG_MARK, APLOG_EMERG, 0, ap_server_conf,
867
"No active child processes: shutting down");
871
make_child(ap_server_conf, free_slots[i]);
874
/* the next time around we want to spawn twice as many if this
875
* wasn't good enough, but not if we've just done a graceful
877
if (hold_off_on_exponential_spawning) {
878
--hold_off_on_exponential_spawning;
880
else if (idle_spawn_rate < MAX_SPAWN_RATE) {
881
idle_spawn_rate *= 2;
890
/*****************************************************************
891
* Executive routines.
894
int ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
897
int remaining_children_to_start;
900
ap_log_pid(pconf, ap_pid_fname);
902
first_server_limit = server_limit;
903
if (changed_limit_at_restart) {
904
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
905
"WARNING: Attempt to change ServerLimit "
906
"ignored during restart");
907
changed_limit_at_restart = 0;
910
/* Initialize cross-process accept lock */
911
ap_lock_fname = apr_psprintf(_pconf, "%s.%" APR_PID_T_FMT,
912
ap_server_root_relative(_pconf, ap_lock_fname),
915
rv = apr_proc_mutex_create(&accept_mutex, ap_lock_fname,
916
ap_accept_lock_mech, _pconf);
917
if (rv != APR_SUCCESS) {
918
ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
919
"Couldn't create accept lock (%s) (%d)",
920
ap_lock_fname, ap_accept_lock_mech);
921
mpm_state = AP_MPMQ_STOPPING;
925
#if APR_USE_SYSVSEM_SERIALIZE
926
if (ap_accept_lock_mech == APR_LOCK_DEFAULT ||
927
ap_accept_lock_mech == APR_LOCK_SYSVSEM) {
929
if (ap_accept_lock_mech == APR_LOCK_SYSVSEM) {
931
rv = unixd_set_proc_mutex_perms(accept_mutex);
932
if (rv != APR_SUCCESS) {
933
ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
934
"Couldn't set permissions on cross-process lock; "
935
"check User and Group directives");
936
mpm_state = AP_MPMQ_STOPPING;
942
if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
943
mpm_state = AP_MPMQ_STOPPING;
946
/* fix the generation number in the global score; we just got a new,
949
ap_scoreboard_image->global->running_generation = ap_my_generation;
956
make_child(ap_server_conf, 0);
959
if (ap_daemons_max_free < ap_daemons_min_free + 1) /* Don't thrash... */
960
ap_daemons_max_free = ap_daemons_min_free + 1;
962
/* If we're doing a graceful_restart then we're going to see a lot
963
* of children exiting immediately when we get into the main loop
964
* below (because we just sent them AP_SIG_GRACEFUL). This happens pretty
965
* rapidly... and for each one that exits we'll start a new one until
966
* we reach at least daemons_min_free. But we may be permitted to
967
* start more than that, so we'll just keep track of how many we're
968
* supposed to start up without the 1 second penalty between each fork.
970
remaining_children_to_start = ap_daemons_to_start;
971
if (remaining_children_to_start > ap_daemons_limit) {
972
remaining_children_to_start = ap_daemons_limit;
975
startup_children(remaining_children_to_start);
976
remaining_children_to_start = 0;
979
/* give the system some time to recover before kicking into
982
hold_off_on_exponential_spawning = 10;
985
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
986
"%s configured -- resuming normal operations",
987
ap_get_server_version());
988
ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf,
989
"Server built: %s", ap_get_server_built());
990
#ifdef AP_MPM_WANT_SET_ACCEPT_LOCK_MECH
991
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
992
"AcceptMutex: %s (default: %s)",
993
apr_proc_mutex_name(accept_mutex),
994
apr_proc_mutex_defname());
996
restart_pending = shutdown_pending = 0;
998
mpm_state = AP_MPMQ_RUNNING;
1000
while (!restart_pending && !shutdown_pending) {
1002
apr_exit_why_e exitwhy;
1003
int status, processed_status;
1004
/* this is a memory leak, but I'll fix it later. */
1007
ap_wait_or_timeout(&exitwhy, &status, &pid, pconf);
1009
/* XXX: if it takes longer than 1 second for all our children
1010
* to start up and get into IDLE state then we may spawn an
1013
if (pid.pid != -1) {
1014
processed_status = ap_process_child_status(&pid, exitwhy, status);
1015
if (processed_status == APEXIT_CHILDFATAL) {
1016
mpm_state = AP_MPMQ_STOPPING;
1020
/* non-fatal death... note that it's gone in the scoreboard. */
1021
child_slot = find_child_by_pid(&pid);
1022
if (child_slot >= 0) {
1023
(void) ap_update_child_status_from_indexes(child_slot, 0, SERVER_DEAD,
1024
(request_rec *) NULL);
1025
if (processed_status == APEXIT_CHILDSICK) {
1026
/* child detected a resource shortage (E[NM]FILE, ENOBUFS, etc)
1027
* cut the fork rate to the minimum
1029
idle_spawn_rate = 1;
1031
else if (remaining_children_to_start
1032
&& child_slot < ap_daemons_limit) {
1033
/* we're still doing a 1-for-1 replacement of dead
1034
* children with new children
1036
make_child(ap_server_conf, child_slot);
1037
--remaining_children_to_start;
1039
#if APR_HAS_OTHER_CHILD
1041
else if (apr_proc_other_child_alert(&pid, APR_OC_REASON_DEATH, status) == APR_SUCCESS) {
1045
else if (is_graceful) {
1046
/* Great, we've probably just lost a slot in the
1047
* scoreboard. Somehow we don't know about this
1050
ap_log_error(APLOG_MARK, APLOG_WARNING,
1052
"long lost child came home! (pid %ld)", (long)pid.pid);
1054
/* Don't perform idle maintenance when a child dies,
1055
* only do it when there's a timeout. Remember only a
1056
* finite number of children can die, and it's pretty
1057
* pathological for a lot to die suddenly.
1061
else if (remaining_children_to_start) {
1062
/* we hit a 1 second timeout in which none of the previous
1063
* generation of children needed to be reaped... so assume
1064
* they're all done, and pick up the slack if any is left.
1066
startup_children(remaining_children_to_start);
1067
remaining_children_to_start = 0;
1068
/* In any event we really shouldn't do the code below because
1069
* few of the servers we just started are in the IDLE state
1070
* yet, so we'd mistakenly create an extra server.
1075
perform_idle_server_maintenance(pconf);
1077
shutdown_pending = os_check_server(tpf_server_name);
1084
mpm_state = AP_MPMQ_STOPPING;
1086
if (shutdown_pending && !is_graceful) {
1087
/* Time to shut down:
1088
* Kill child processes, tell them to call child_exit, etc...
1090
if (unixd_killpg(getpgrp(), SIGTERM) < 0) {
1091
ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGTERM");
1093
ap_reclaim_child_processes(1); /* Start with SIGTERM */
1095
/* cleanup pid file on normal shutdown */
1097
const char *pidfile = NULL;
1098
pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1099
if ( pidfile != NULL && unlink(pidfile) == 0)
1100
ap_log_error(APLOG_MARK, APLOG_INFO,
1102
"removed PID file %s (pid=%ld)",
1103
pidfile, (long)getpid());
1106
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1107
"caught SIGTERM, shutting down");
1110
} else if (shutdown_pending) {
1111
/* Time to perform a graceful shut down:
1112
* Reap the inactive children, and ask the active ones
1113
* to close their listeners, then wait until they are
1116
int active_children;
1117
apr_time_t cutoff = 0;
1119
/* Stop listening */
1120
ap_close_listeners();
1122
/* kill off the idle ones */
1123
ap_mpm_pod_killpg(pod, ap_max_daemons_limit);
1125
/* Send SIGUSR1 to the active children */
1126
active_children = 0;
1127
for (index = 0; index < ap_daemons_limit; ++index) {
1128
if (ap_scoreboard_image->servers[index][0].status != SERVER_DEAD) {
1129
/* Ask each child to close its listeners. */
1130
kill(MPM_CHILD_PID(index), AP_SIG_GRACEFUL);
1135
/* Allow each child which actually finished to exit */
1136
ap_relieve_child_processes();
1138
/* cleanup pid file */
1140
const char *pidfile = NULL;
1141
pidfile = ap_server_root_relative (pconf, ap_pid_fname);
1142
if ( pidfile != NULL && unlink(pidfile) == 0)
1143
ap_log_error(APLOG_MARK, APLOG_INFO,
1145
"removed PID file %s (pid=%ld)",
1146
pidfile, (long)getpid());
1149
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1150
"caught " AP_SIG_GRACEFUL_STOP_STRING ", shutting down gracefully");
1152
if (ap_graceful_shutdown_timeout) {
1153
cutoff = apr_time_now() +
1154
apr_time_from_sec(ap_graceful_shutdown_timeout);
1157
/* Don't really exit until each child has finished */
1158
shutdown_pending = 0;
1160
/* Pause for a second */
1163
/* Relieve any children which have now exited */
1164
ap_relieve_child_processes();
1166
active_children = 0;
1167
for (index = 0; index < ap_daemons_limit; ++index) {
1168
if (MPM_CHILD_PID(index) != 0) {
1169
if (kill(MPM_CHILD_PID(index), 0) == 0) {
1170
active_children = 1;
1171
/* Having just one child is enough to stay around */
1176
} while (!shutdown_pending && active_children &&
1177
(!ap_graceful_shutdown_timeout || apr_time_now() < cutoff));
1179
/* We might be here because we received SIGTERM, either
1180
* way, try and make sure that all of our processes are
1183
unixd_killpg(getpgrp(), SIGTERM);
1188
/* we've been told to restart */
1189
apr_signal(SIGHUP, SIG_IGN);
1190
apr_signal(AP_SIG_GRACEFUL, SIG_IGN);
1192
/* not worth thinking about */
1196
/* advance to the next generation */
1197
/* XXX: we really need to make sure this new generation number isn't in
1198
* use by any of the children.
1201
ap_scoreboard_image->global->running_generation = ap_my_generation;
1204
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1205
"Graceful restart requested, doing restart");
1207
/* kill off the idle ones */
1208
ap_mpm_pod_killpg(pod, ap_max_daemons_limit);
1210
/* This is mostly for debugging... so that we know what is still
1211
* gracefully dealing with existing request. This will break
1212
* in a very nasty way if we ever have the scoreboard totally
1213
* file-based (no shared memory)
1215
for (index = 0; index < ap_daemons_limit; ++index) {
1216
if (ap_scoreboard_image->servers[index][0].status != SERVER_DEAD) {
1217
ap_scoreboard_image->servers[index][0].status = SERVER_GRACEFUL;
1218
/* Ask each child to close its listeners.
1220
* NOTE: we use the scoreboard, because if we send SIGUSR1
1221
* to every process in the group, this may include CGI's,
1222
* piped loggers, etc. They almost certainly won't handle
1225
kill(ap_scoreboard_image->parent[index].pid, AP_SIG_GRACEFUL);
1231
if (unixd_killpg(getpgrp(), SIGHUP) < 0) {
1232
ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGHUP");
1234
ap_reclaim_child_processes(0); /* Not when just starting up */
1235
ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1236
"SIGHUP received. Attempting to restart");
1242
/* This really should be a post_config hook, but the error log is already
1243
* redirected by that point, so we need to do this in the open_logs phase.
1245
static int prefork_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
1252
if ((num_listensocks = ap_setup_listeners(ap_server_conf)) < 1) {
1253
ap_log_error(APLOG_MARK, APLOG_ALERT|APLOG_STARTUP, 0,
1254
NULL, "no listening sockets available, shutting down");
1258
if ((rv = ap_mpm_pod_open(pconf, &pod))) {
1259
ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_STARTUP, rv, NULL,
1260
"Could not open pipe-of-death.");
1266
static int prefork_pre_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp)
1268
static int restart_num = 0;
1269
int no_detach, debug, foreground;
1272
mpm_state = AP_MPMQ_STARTING;
1274
debug = ap_exists_config_define("DEBUG");
1277
foreground = one_process = 1;
1282
no_detach = ap_exists_config_define("NO_DETACH");
1283
one_process = ap_exists_config_define("ONE_PROCESS");
1284
foreground = ap_exists_config_define("FOREGROUND");
1287
/* sigh, want this only the second time around */
1288
if (restart_num++ == 1) {
1291
if (!one_process && !foreground) {
1292
rv = apr_proc_detach(no_detach ? APR_PROC_DETACH_FOREGROUND
1293
: APR_PROC_DETACH_DAEMONIZE);
1294
if (rv != APR_SUCCESS) {
1295
ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
1296
"apr_proc_detach failed");
1297
return HTTP_INTERNAL_SERVER_ERROR;
1301
parent_pid = ap_my_pid = getpid();
1304
unixd_pre_config(ptemp);
1305
ap_listen_pre_config();
1306
ap_daemons_to_start = DEFAULT_START_DAEMON;
1307
ap_daemons_min_free = DEFAULT_MIN_FREE_DAEMON;
1308
ap_daemons_max_free = DEFAULT_MAX_FREE_DAEMON;
1309
ap_daemons_limit = server_limit;
1310
ap_pid_fname = DEFAULT_PIDLOG;
1311
ap_lock_fname = DEFAULT_LOCKFILE;
1312
ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
1313
ap_extended_status = 0;
1314
#ifdef AP_MPM_WANT_SET_MAX_MEM_FREE
1315
ap_max_mem_free = APR_ALLOCATOR_MAX_FREE_UNLIMITED;
1318
apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1323
static void prefork_hooks(apr_pool_t *p)
1325
/* The prefork open_logs phase must run before the core's, or stderr
1326
* will be redirected to a file, and the messages won't print to the
1329
static const char *const aszSucc[] = {"core.c", NULL};
1335
ap_hook_open_logs(prefork_open_logs, NULL, aszSucc, APR_HOOK_MIDDLE);
1336
/* we need to set the MPM state before other pre-config hooks use MPM query
1337
* to retrieve it, so register as REALLY_FIRST
1339
ap_hook_pre_config(prefork_pre_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
1342
static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy, const char *arg)
1344
const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1349
ap_daemons_to_start = atoi(arg);
1353
static const char *set_min_free_servers(cmd_parms *cmd, void *dummy, const char *arg)
1355
const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1360
ap_daemons_min_free = atoi(arg);
1361
if (ap_daemons_min_free <= 0) {
1362
ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1363
"WARNING: detected MinSpareServers set to non-positive.");
1364
ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1365
"Resetting to 1 to avoid almost certain Apache failure.");
1366
ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1367
"Please read the documentation.");
1368
ap_daemons_min_free = 1;
1374
static const char *set_max_free_servers(cmd_parms *cmd, void *dummy, const char *arg)
1376
const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1381
ap_daemons_max_free = atoi(arg);
1385
static const char *set_max_clients (cmd_parms *cmd, void *dummy, const char *arg)
1387
const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1392
ap_daemons_limit = atoi(arg);
1393
if (ap_daemons_limit > server_limit) {
1394
ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1395
"WARNING: MaxClients of %d exceeds ServerLimit value "
1396
"of %d servers,", ap_daemons_limit, server_limit);
1397
ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1398
" lowering MaxClients to %d. To increase, please "
1399
"see the ServerLimit", server_limit);
1400
ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1402
ap_daemons_limit = server_limit;
1404
else if (ap_daemons_limit < 1) {
1405
ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1406
"WARNING: Require MaxClients > 0, setting to 1");
1407
ap_daemons_limit = 1;
1412
static const char *set_server_limit (cmd_parms *cmd, void *dummy, const char *arg)
1414
int tmp_server_limit;
1416
const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1421
tmp_server_limit = atoi(arg);
1422
/* you cannot change ServerLimit across a restart; ignore
1425
if (first_server_limit &&
1426
tmp_server_limit != server_limit) {
1427
/* how do we log a message? the error log is a bit bucket at this
1428
* point; we'll just have to set a flag so that ap_mpm_run()
1429
* logs a warning later
1431
changed_limit_at_restart = 1;
1434
server_limit = tmp_server_limit;
1436
if (server_limit > MAX_SERVER_LIMIT) {
1437
ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1438
"WARNING: ServerLimit of %d exceeds compile time limit "
1439
"of %d servers,", server_limit, MAX_SERVER_LIMIT);
1440
ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1441
" lowering ServerLimit to %d.", MAX_SERVER_LIMIT);
1442
server_limit = MAX_SERVER_LIMIT;
1444
else if (server_limit < 1) {
1445
ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
1446
"WARNING: Require ServerLimit > 0, setting to 1");
1452
static const command_rec prefork_cmds[] = {
1453
UNIX_DAEMON_COMMANDS,
1455
AP_INIT_TAKE1("StartServers", set_daemons_to_start, NULL, RSRC_CONF,
1456
"Number of child processes launched at server startup"),
1457
AP_INIT_TAKE1("MinSpareServers", set_min_free_servers, NULL, RSRC_CONF,
1458
"Minimum number of idle children, to handle request spikes"),
1459
AP_INIT_TAKE1("MaxSpareServers", set_max_free_servers, NULL, RSRC_CONF,
1460
"Maximum number of idle children"),
1461
AP_INIT_TAKE1("MaxClients", set_max_clients, NULL, RSRC_CONF,
1462
"Maximum number of children alive at the same time"),
1463
AP_INIT_TAKE1("ServerLimit", set_server_limit, NULL, RSRC_CONF,
1464
"Maximum value of MaxClients for this run of Apache"),
1465
AP_GRACEFUL_SHUTDOWN_TIMEOUT_COMMAND,
1469
module AP_MODULE_DECLARE_DATA mpm_prefork_module = {
1471
ap_mpm_rewrite_args, /* hook to run before apache parses args */
1472
NULL, /* create per-directory config structure */
1473
NULL, /* merge per-directory config structures */
1474
NULL, /* create per-server config structure */
1475
NULL, /* merge per-server config structures */
1476
prefork_cmds, /* command apr_table_t */
1477
prefork_hooks, /* register hooks */