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.
19 * This is a single process, with multiple worker threads.
21 * Under testing I found that given the inability of BeOS to handle threads
22 * and forks it didn't make sense to try and have a set of "children" threads
23 * that spawned the "worker" threads, so just missed out the middle mand and
24 * somehow arrived here.
26 * For 2.1 this has been rewritten to have simpler logic, though there is still
27 * some simplification that can be done. It's still a work in progress!
31 * - on exit most worker threads segfault trying to access a kernel page.
36 #include <kernel/OS.h>
38 #include <sys/socket.h>
41 #include "apr_strings.h"
42 #include "apr_portable.h"
44 #include "http_main.h"
46 #include "http_config.h" /* for read_config */
47 #include "http_core.h" /* for get_remote_host */
48 #include "http_connection.h"
51 #include "ap_listen.h"
52 #include "scoreboard.h"
53 #include "mpm_common.h"
55 #include "mpm_default.h"
56 #include "apr_thread_mutex.h"
59 extern int _kset_fd_limit_(int num);
61 /* Limit on the total --- clients will be locked out if more servers than
62 * this are needed. It is intended solely to keep the server from crashing
63 * when things get out of hand.
65 * We keep a hard maximum number of servers, for two reasons:
66 * 1) in case something goes seriously wrong, we want to stop the server starting
67 * threads ad infinitum and crashing the server (remember that BeOS has a 192
68 * thread per team limit).
69 * 2) it keeps the size of the scoreboard file small
70 * enough that we can read the whole thing without worrying too much about
74 /* we only ever have 1 main process running... */
75 #define HARD_SERVER_LIMIT 1
77 /* Limit on the threads per process. Clients will be locked out if more than
78 * this * HARD_SERVER_LIMIT are needed.
80 * We keep this for one reason it keeps the size of the scoreboard file small
81 * enough that we can read the whole thing without worrying too much about
85 #define HARD_THREAD_LIMIT 1
87 #ifndef HARD_THREAD_LIMIT
88 #define HARD_THREAD_LIMIT 50
92 * Actual definitions of config globals
95 static int ap_threads_to_start=0;
96 static int ap_max_requests_per_thread = 0;
97 static int min_spare_threads=0;
98 static int max_spare_threads=0;
99 static int ap_thread_limit=0;
100 static int num_listening_sockets = 0;
101 static int mpm_state = AP_MPMQ_STARTING;
102 apr_thread_mutex_t *accept_mutex = NULL;
104 static apr_pool_t *pconf; /* Pool for config stuff */
105 static apr_pool_t *pmain; /* Pool for httpd child stuff */
107 static int server_pid;
111 * The max child slot ever assigned, preserved across restarts. Necessary
112 * to deal with MaxClients changes across AP_SIG_GRACEFUL restarts. We use
113 * this value to optimize routines that have to scan the entire scoreboard.
115 int ap_max_child_assigned = -1;
116 int ap_max_threads_limit = -1;
118 static apr_socket_t *udp_sock;
119 static apr_sockaddr_t *udp_sa;
121 server_rec *ap_server_conf;
124 static int one_process = 0;
127 int raise_sigstop_flags;
130 static void check_restart(void *data);
132 /* When a worker thread gets to the end of it's life it dies with an
133 * exit value of the code supplied to this function. The thread has
134 * already had check_restart() registered to be called when dying, so
135 * we don't concern ourselves with restarting at all here. We do however
136 * mark the scoreboard slot as belonging to a dead server and zero out
139 * TODO - use the status we set to determine if we need to restart the
142 static void clean_child_exit(int code, int slot)
144 (void) ap_update_child_status_from_indexes(0, slot, SERVER_DEAD,
146 ap_scoreboard_image->servers[0][slot].tid = 0;
150 /* proper cleanup when returning from ap_mpm_run() */
151 static void mpm_main_cleanup(void)
154 apr_pool_destroy(pmain);
159 /*****************************************************************
160 * Connection structures and accounting...
163 /* volatile just in case */
164 static int volatile shutdown_pending;
165 static int volatile restart_pending;
166 static int volatile is_graceful;
167 static int volatile child_fatal;
168 ap_generation_t volatile ap_my_generation = 0;
171 * ap_start_shutdown() and ap_start_restart(), below, are a first stab at
172 * functions to initiate shutdown or restart without relying on signals.
173 * Previously this was initiated in sig_term() and restart() signal handlers,
174 * but we want to be able to start a shutdown/restart from other sources --
175 * e.g. on Win32, from the service manager. Now the service manager can
176 * call ap_start_shutdown() or ap_start_restart() as appropiate. Note that
177 * these functions can also be called by the child processes, since global
178 * variables are no longer used to pass on the required action to the parent.
180 * These should only be called from the parent process itself, since the
181 * parent process will use the shutdown_pending and restart_pending variables
182 * to determine whether to shutdown or restart. The child process should
183 * call signal_parent() directly to tell the parent to die -- this will
184 * cause neither of those variable to be set, which the parent will
185 * assume means something serious is wrong (which it will be, for the
186 * child to force an exit) and so do an exit anyway.
189 static void ap_start_shutdown(void)
191 /* If the user tries to shut us down twice in quick succession then we
192 * may well get triggered while we are working through previous attempt
193 * to shutdown. We won't worry about even reporting it as it seems a little
196 if (shutdown_pending == 1)
199 shutdown_pending = 1;
202 /* do a graceful restart if graceful == 1 */
203 static void ap_start_restart(int graceful)
205 if (restart_pending == 1) {
206 /* Probably not an error - don't bother reporting it */
210 is_graceful = graceful;
213 /* sig_coredump attempts to handle all the potential signals we
214 * may get that should result in a core dump. This is called from
215 * the signal handler routine, so when we enter we are essentially blocked
216 * on the signal. Once we exit we will allow the signal to be processed by
217 * system, which may or may not produce a .core file. All this function does
218 * is try and respect the users wishes about where that file should be
219 * located (chdir) and then signal the parent with the signal.
221 * If we called abort() the parent would only see SIGABRT which doesn't provide
222 * as much information.
224 static void sig_coredump(int sig)
226 chdir(ap_coredump_dir);
227 signal(sig, SIG_DFL);
228 kill(server_pid, sig);
231 static void sig_term(int sig)
236 static void restart(int sig)
238 ap_start_restart(sig == AP_SIG_GRACEFUL);
241 /* Handle queries about our inner workings... */
242 AP_DECLARE(apr_status_t) ap_mpm_query(int query_code, int *result)
245 case AP_MPMQ_MAX_DAEMON_USED:
246 *result = ap_max_child_assigned;
248 case AP_MPMQ_IS_THREADED:
249 *result = AP_MPMQ_DYNAMIC;
251 case AP_MPMQ_IS_FORKED:
252 *result = AP_MPMQ_NOT_SUPPORTED;
254 case AP_MPMQ_HARD_LIMIT_DAEMONS:
255 *result = HARD_SERVER_LIMIT;
257 case AP_MPMQ_HARD_LIMIT_THREADS:
258 *result = HARD_THREAD_LIMIT;
260 case AP_MPMQ_MAX_THREADS:
261 *result = HARD_THREAD_LIMIT;
263 case AP_MPMQ_MIN_SPARE_DAEMONS:
266 case AP_MPMQ_MIN_SPARE_THREADS:
267 *result = max_spare_threads;
269 case AP_MPMQ_MAX_SPARE_DAEMONS:
272 case AP_MPMQ_MAX_SPARE_THREADS:
273 *result = min_spare_threads;
275 case AP_MPMQ_MAX_REQUESTS_DAEMON:
276 *result = ap_max_requests_per_thread;
278 case AP_MPMQ_MAX_DAEMONS:
279 *result = HARD_SERVER_LIMIT;
281 case AP_MPMQ_MPM_STATE:
288 /* This accepts a connection and allows us to handle the error codes better than
289 * the previous code, while also making it more obvious.
291 static apr_status_t beos_accept(void **accepted, ap_listen_rec *lr, apr_pool_t *ptrans)
298 status = apr_socket_accept(&csd, lr->sd, ptrans);
299 if (status == APR_SUCCESS) {
301 apr_os_sock_get(&sockdes, csd);
305 if (APR_STATUS_IS_EINTR(status)) {
308 /* This switch statement provides us with better error details. */
326 * When the network layer has been shut down, there
327 * is not much use in simply exiting: the parent
328 * would simply re-create us (and we'd fail again).
329 * Use the CHILDFATAL code to tear the server down.
330 * @@@ Martin's idea for possible improvement:
331 * A different approach would be to define
332 * a new APEXIT_NETDOWN exit code, the reception
333 * of which would make the parent shutdown all
334 * children, then idle-loop until it detected that
335 * the network is up again, and restart the children.
336 * Ben Hyde noted that temporary ENETDOWN situations
337 * occur in mobile IP.
339 ap_log_error(APLOG_MARK, APLOG_EMERG, status, ap_server_conf,
340 "apr_socket_accept: giving up.");
345 ap_log_error(APLOG_MARK, APLOG_ERR, status, ap_server_conf,
346 "apr_socket_accept: (client socket)");
352 static void tell_workers_to_exit(void)
356 for (i = 0 ; i < ap_max_child_assigned; i++){
358 if (apr_socket_sendto(udp_sock, udp_sa, 0, "die!", &len) != APR_SUCCESS)
363 static void set_signals(void)
367 sigemptyset(&sa.sa_mask);
370 /* The first batch get handled by sig_coredump */
372 sa.sa_handler = sig_coredump;
374 if (sigaction(SIGSEGV, &sa, NULL) < 0)
375 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGSEGV)");
376 if (sigaction(SIGBUS, &sa, NULL) < 0)
377 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGBUS)");
378 if (sigaction(SIGABRT, &sa, NULL) < 0)
379 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGABRT)");
380 if (sigaction(SIGILL, &sa, NULL) < 0)
381 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGILL)");
385 /* These next two are handled by sig_term */
386 sa.sa_handler = sig_term;
387 if (sigaction(SIGTERM, &sa, NULL) < 0)
388 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGTERM)");
389 if (sigaction(SIGINT, &sa, NULL) < 0)
390 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGINT)");
392 /* We ignore SIGPIPE */
393 sa.sa_handler = SIG_IGN;
394 if (sigaction(SIGPIPE, &sa, NULL) < 0)
395 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGPIPE)");
397 /* we want to ignore HUPs and AP_SIG_GRACEFUL while we're busy
399 sigaddset(&sa.sa_mask, SIGHUP);
400 sigaddset(&sa.sa_mask, AP_SIG_GRACEFUL);
401 sa.sa_handler = restart;
402 if (sigaction(SIGHUP, &sa, NULL) < 0)
403 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(SIGHUP)");
404 if (sigaction(AP_SIG_GRACEFUL, &sa, NULL) < 0)
405 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "sigaction(" AP_SIG_GRACEFUL_STRING ")");
408 /*****************************************************************
409 * Here follows a long bunch of generic server bookkeeping stuff...
412 int ap_graceful_stop_signalled(void)
417 /* This is the thread that actually does all the work. */
418 static int32 worker_thread(void *dummy)
420 int worker_slot = (int)dummy;
421 apr_allocator_t *allocator;
422 apr_bucket_alloc_t *bucket_alloc;
423 apr_status_t rv = APR_EINIT;
424 int last_poll_idx = 0;
426 int requests_this_child = 0;
427 apr_pollset_t *pollset = NULL;
428 ap_listen_rec *lr = NULL;
429 ap_sb_handle_t *sbh = NULL;
431 /* each worker thread is in control of its own destiny...*/
432 int this_worker_should_exit = 0;
433 /* We have 2 pools that we create/use throughout the lifetime of this
434 * worker. The first and longest lived is the pworker pool. From
435 * this we create the ptrans pool, the lifetime of which is the same
436 * as each connection and is reset prior to each attempt to
437 * process a connection.
439 apr_pool_t *ptrans = NULL;
440 apr_pool_t *pworker = NULL;
442 mpm_state = AP_MPMQ_STARTING; /* for benefit of any hooks that run as this
446 on_exit_thread(check_restart, (void*)worker_slot);
448 /* block the signals for this thread only if we're not running as a
452 sigfillset(&sig_mask);
453 sigprocmask(SIG_BLOCK, &sig_mask, NULL);
456 /* Each worker thread is fully in control of it's destinay and so
457 * to allow each thread to handle the lifetime of it's own resources
458 * we create and use a subcontext for every thread.
459 * The subcontext is a child of the pconf pool.
461 apr_allocator_create(&allocator);
462 apr_allocator_max_free_set(allocator, ap_max_mem_free);
463 apr_pool_create_ex(&pworker, pconf, NULL, allocator);
464 apr_allocator_owner_set(allocator, pworker);
466 apr_pool_create(&ptrans, pworker);
467 apr_pool_tag(ptrans, "transaction");
469 ap_create_sb_handle(&sbh, pworker, 0, worker_slot);
470 (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
472 /* We add an extra socket here as we add the udp_sock we use for signalling
473 * death. This gets added after the others.
475 apr_pollset_create(&pollset, num_listening_sockets + 1, pworker, 0);
477 for (lr = ap_listeners, i = num_listening_sockets; i--; lr = lr->next) {
478 apr_pollfd_t pfd = {0};
480 pfd.desc_type = APR_POLL_SOCKET;
482 pfd.reqevents = APR_POLLIN;
483 pfd.client_data = lr;
485 apr_pollset_add(pollset, &pfd);
488 apr_pollfd_t pfd = {0};
490 pfd.desc_type = APR_POLL_SOCKET;
491 pfd.desc.s = udp_sock;
492 pfd.reqevents = APR_POLLIN;
494 apr_pollset_add(pollset, &pfd);
497 bucket_alloc = apr_bucket_alloc_create(pworker);
499 mpm_state = AP_MPMQ_RUNNING;
501 while (!this_worker_should_exit) {
502 conn_rec *current_conn;
505 /* (Re)initialize this child to a pre-connection state. */
506 apr_pool_clear(ptrans);
508 if ((ap_max_requests_per_thread > 0
509 && requests_this_child++ >= ap_max_requests_per_thread))
510 clean_child_exit(0, worker_slot);
512 (void) ap_update_child_status(sbh, SERVER_READY, (request_rec *) NULL);
514 apr_thread_mutex_lock(accept_mutex);
516 /* We always (presently) have at least 2 sockets we listen on, so
517 * we don't have the ability for a fast path for a single socket
518 * as some MPM's allow :(
521 apr_int32_t numdesc = 0;
522 const apr_pollfd_t *pdesc = NULL;
524 rv = apr_pollset_poll(pollset, -1, &numdesc, &pdesc);
525 if (rv != APR_SUCCESS) {
526 if (APR_STATUS_IS_EINTR(rv)) {
527 if (one_process && shutdown_pending)
531 ap_log_error(APLOG_MARK, APLOG_ERR, rv,
532 ap_server_conf, "apr_pollset_poll: (listen)");
533 clean_child_exit(1, worker_slot);
535 /* We can always use pdesc[0], but sockets at position N
536 * could end up completely starved of attention in a very
537 * busy server. Therefore, we round-robin across the
538 * returned set of descriptors. While it is possible that
539 * the returned set of descriptors might flip around and
540 * continue to starve some sockets, we happen to know the
541 * internal pollset implementation retains ordering
542 * stability of the sockets. Thus, the round-robin should
543 * ensure that a socket will eventually be serviced.
545 if (last_poll_idx >= numdesc)
548 /* Grab a listener record from the client_data of the poll
549 * descriptor, and advance our saved index to round-robin
552 * ### hmm... this descriptor might have POLLERR rather
556 lr = pdesc[last_poll_idx++].client_data;
558 /* The only socket we add without client_data is the first, the UDP socket
559 * we listen on for restart signals. If we've therefore gotten a hit on that
560 * listener lr will be NULL here and we know we've been told to die.
561 * Before we jump to the end of the while loop with this_worker_should_exit
562 * set to 1 (causing us to exit normally we hope) we release the accept_mutex
563 * as we want every thread to go through this same routine :)
564 * Bit of a hack, but compared to what I had before...
567 this_worker_should_exit = 1;
568 apr_thread_mutex_unlock(accept_mutex);
569 goto got_a_black_spot;
574 /* Run beos_accept to accept the connection and set things up to
575 * allow us to process it. We always release the accept_lock here,
576 * even if we failt o accept as otherwise we'll starve other workers
577 * which would be bad.
579 rv = beos_accept(&csd, lr, ptrans);
580 apr_thread_mutex_unlock(accept_mutex);
582 if (rv == APR_EGENERAL) {
583 /* resource shortage or should-not-occur occured */
584 clean_child_exit(1, worker_slot);
585 } else if (rv != APR_SUCCESS)
588 current_conn = ap_run_create_connection(ptrans, ap_server_conf, csd, worker_slot, sbh, bucket_alloc);
590 ap_process_connection(current_conn, csd);
591 ap_lingering_close(current_conn);
594 if (ap_my_generation !=
595 ap_scoreboard_image->global->running_generation) { /* restart? */
596 /* yeah, this could be non-graceful restart, in which case the
597 * parent will kill us soon enough, but why bother checking?
599 this_worker_should_exit = 1;
604 apr_pool_destroy(ptrans);
605 apr_pool_destroy(pworker);
607 clean_child_exit(0, worker_slot);
610 static int make_worker(int slot)
614 if (slot + 1 > ap_max_child_assigned)
615 ap_max_child_assigned = slot + 1;
617 (void) ap_update_child_status_from_indexes(0, slot, SERVER_STARTING, (request_rec*)NULL);
621 ap_scoreboard_image->parent[0].pid = getpid();
622 ap_scoreboard_image->servers[0][slot].tid = find_thread(NULL);
626 tid = spawn_thread(worker_thread, "apache_worker", B_NORMAL_PRIORITY,
628 if (tid < B_NO_ERROR) {
629 ap_log_error(APLOG_MARK, APLOG_ERR, errno, NULL,
630 "spawn_thread: Unable to start a new thread");
631 /* In case system resources are maxed out, we don't want
632 * Apache running away with the CPU trying to fork over and
633 * over and over again.
635 (void) ap_update_child_status_from_indexes(0, slot, SERVER_DEAD,
643 ap_scoreboard_image->servers[0][slot].tid = tid;
647 /* When a worker thread exits, this function is called. If we are not in
648 * a shutdown situation then we restart the worker in the slot that was
651 static void check_restart(void *data)
653 if (!restart_pending && !shutdown_pending) {
654 int slot = (int)data;
656 ap_log_error(APLOG_MARK, APLOG_INFO, 0, NULL,
657 "spawning a new worker thread in slot %d", slot);
661 /* Start number_to_start children. This is used to start both the
662 * initial 'pool' of workers but also to replace existing workers who
663 * have reached the end of their time. It walks through the scoreboard to find
664 * an empty slot and starts the worker thread in that slot.
666 static void startup_threads(int number_to_start)
670 for (i = 0; number_to_start && i < ap_thread_limit; ++i) {
671 if (ap_scoreboard_image->servers[0][i].tid)
674 if (make_worker(i) < 0)
683 * spawn_rate is the number of children that will be spawned on the
684 * next maintenance cycle if there aren't enough idle servers. It is
685 * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by
686 * without the need to spawn.
688 static int spawn_rate = 1;
689 #ifndef MAX_SPAWN_RATE
690 #define MAX_SPAWN_RATE (32)
692 static int hold_off_on_exponential_spawning;
694 static void perform_idle_server_maintenance(void)
698 int free_slots[MAX_SPAWN_RATE];
699 int last_non_dead = -1;
701 /* initialize the free_list */
704 for (i = 0; i < ap_thread_limit; ++i) {
705 if (ap_scoreboard_image->servers[0][i].tid == 0) {
706 if (free_length < spawn_rate) {
707 free_slots[free_length] = i;
715 if (i >= ap_max_child_assigned && free_length >= spawn_rate) {
719 ap_max_child_assigned = last_non_dead + 1;
721 if (free_length > 0) {
722 for (i = 0; i < free_length; ++i) {
723 make_worker(free_slots[i]);
725 /* the next time around we want to spawn twice as many if this
726 * wasn't good enough, but not if we've just done a graceful
728 if (hold_off_on_exponential_spawning) {
729 --hold_off_on_exponential_spawning;
730 } else if (spawn_rate < MAX_SPAWN_RATE) {
738 static void server_main_loop(int remaining_threads_to_start)
741 apr_exit_why_e exitwhy;
746 while (!restart_pending && !shutdown_pending) {
748 ap_wait_or_timeout(&exitwhy, &status, &pid, pconf);
751 if (ap_process_child_status(&pid, exitwhy, status) == APEXIT_CHILDFATAL) {
752 shutdown_pending = 1;
756 /* non-fatal death... note that it's gone in the scoreboard. */
758 for (i = 0; i < ap_max_child_assigned; ++i) {
759 if (ap_scoreboard_image->servers[0][i].tid == pid.pid) {
764 if (child_slot >= 0) {
765 ap_scoreboard_image->servers[0][child_slot].tid = 0;
766 (void) ap_update_child_status_from_indexes(0, child_slot,
770 if (remaining_threads_to_start
771 && child_slot < ap_thread_limit) {
772 /* we're still doing a 1-for-1 replacement of dead
773 * children with new children
775 make_worker(child_slot);
776 --remaining_threads_to_start;
779 #if APR_HAS_OTHER_CHILD
781 else if (apr_proc_other_child_refresh(&pid, status) == 0) {
785 else if (is_graceful) {
786 /* Great, we've probably just lost a slot in the
787 * scoreboard. Somehow we don't know about this
790 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf,
791 "long lost child came home! (pid %ld)", pid.pid);
794 /* Don't perform idle maintenance when a child dies,
795 * only do it when there's a timeout. Remember only a
796 * finite number of children can die, and it's pretty
797 * pathological for a lot to die suddenly.
801 else if (remaining_threads_to_start) {
802 /* we hit a 1 second timeout in which none of the previous
803 * generation of children needed to be reaped... so assume
804 * they're all done, and pick up the slack if any is left.
806 startup_threads(remaining_threads_to_start);
807 remaining_threads_to_start = 0;
808 /* In any event we really shouldn't do the code below because
809 * few of the servers we just started are in the IDLE state
810 * yet, so we'd mistakenly create an extra server.
814 perform_idle_server_maintenance();
818 /* This is called to not only setup and run for the initial time, but also
819 * when we've asked for a restart. This means it must be able to handle both
820 * situations. It also means that when we exit here we should have tidied
821 * up after ourselves fully.
823 int ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
825 int remaining_threads_to_start, i,j;
831 /* Increase the available pool of fd's. This code from
832 * Joe Kloss <joek@be.com>
834 if( FD_SETSIZE > 128 && (i = _kset_fd_limit_( 128 )) < 0 ){
835 ap_log_error(APLOG_MARK, APLOG_ERR, i, s,
836 "could not set FD_SETSIZE (_kset_fd_limit_ failed)");
839 /* BeOS R5 doesn't support pipes on select() calls, so we use a
840 * UDP socket as these are supported in both R5 and BONE. If we only cared
841 * about BONE we'd use a pipe, but there it is.
842 * As we have UDP support in APR, now use the APR functions and check all the
845 if (apr_sockaddr_info_get(&udp_sa, "127.0.0.1", APR_UNSPEC, 7772, 0, _pconf)
847 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, s,
848 "couldn't create control socket information, shutting down");
851 if (apr_socket_create(&udp_sock, udp_sa->family, SOCK_DGRAM, 0,
852 _pconf) != APR_SUCCESS){
853 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, s,
854 "couldn't create control socket, shutting down");
857 if (apr_socket_bind(udp_sock, udp_sa) != APR_SUCCESS){
858 ap_log_error(APLOG_MARK, APLOG_ALERT, errno, s,
859 "couldn't bind UDP socket!");
863 if ((num_listening_sockets = ap_setup_listeners(ap_server_conf)) < 1) {
864 ap_log_error(APLOG_MARK, APLOG_ALERT, 0, s,
865 "no listening sockets available, shutting down");
869 ap_log_pid(pconf, ap_pid_fname);
872 * Create our locks...
876 * used to lock around select so we only have one thread
877 * in select at a time
879 rv = apr_thread_mutex_create(&accept_mutex, 0, pconf);
880 if (rv != APR_SUCCESS) {
881 /* tsch tsch, can't have more than one thread in the accept loop
882 at a time so we need to fall on our sword... */
883 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s,
884 "Couldn't create accept lock");
889 * Startup/shutdown...
893 /* setup the scoreboard shared memory */
894 if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
898 for (i = 0; i < HARD_SERVER_LIMIT; i++) {
899 ap_scoreboard_image->parent[i].pid = 0;
900 for (j = 0;j < HARD_THREAD_LIMIT; j++)
901 ap_scoreboard_image->servers[i][j].tid = 0;
905 if (HARD_SERVER_LIMIT == 1)
906 ap_scoreboard_image->parent[0].pid = getpid();
910 apr_pool_create(&pmain, pconf);
911 ap_run_child_init(pmain, ap_server_conf);
913 /* Sanity checks to avoid thrashing... */
914 if (max_spare_threads < min_spare_threads )
915 max_spare_threads = min_spare_threads;
917 /* If we're doing a graceful_restart then we're going to see a lot
918 * of threads exiting immediately when we get into the main loop
919 * below (because we just sent them AP_SIG_GRACEFUL). This happens
920 * pretty rapidly... and for each one that exits we'll start a new one
921 * until we reach at least threads_min_free. But we may be permitted to
922 * start more than that, so we'll just keep track of how many we're
923 * supposed to start up without the 1 second penalty between each fork.
925 remaining_threads_to_start = ap_threads_to_start;
926 /* sanity check on the number to start... */
927 if (remaining_threads_to_start > ap_thread_limit) {
928 remaining_threads_to_start = ap_thread_limit;
931 /* If we're doing the single process thing or we're in a graceful_restart
932 * then we don't start threads here.
933 * if we're in one_process mode we don't want to start threads
936 if (!is_graceful && !one_process) {
937 startup_threads(remaining_threads_to_start);
938 remaining_threads_to_start = 0;
940 /* give the system some time to recover before kicking into
941 * exponential mode */
942 hold_off_on_exponential_spawning = 10;
946 * record that we've entered the world !
948 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
949 "%s configured -- resuming normal operations",
950 ap_get_server_description());
952 ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf,
953 "Server built: %s", ap_get_server_built());
955 restart_pending = shutdown_pending = 0;
957 mpm_state = AP_MPMQ_RUNNING;
959 /* We sit in the server_main_loop() until we somehow manage to exit. When
960 * we do, we need to kill the workers we have, so we start by using the
961 * tell_workers_to_exit() function, but as it sometimes takes a short while
962 * to accomplish this we have a pause builtin to allow them the chance to
966 server_main_loop(remaining_threads_to_start);
967 tell_workers_to_exit();
970 worker_thread((void*)0);
972 mpm_state = AP_MPMQ_STOPPING;
974 /* close the UDP socket we've been using... */
975 apr_socket_close(udp_sock);
977 if ((one_process || shutdown_pending) && !child_fatal) {
978 const char *pidfile = NULL;
979 pidfile = ap_server_root_relative (pconf, ap_pid_fname);
980 if ( pidfile != NULL && unlink(pidfile) == 0)
981 ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf,
982 "removed PID file %s (pid=%ld)", pidfile,
992 * If we get here we're shutting down...
994 if (shutdown_pending) {
995 /* Time to gracefully shut down:
996 * Kill child processes, tell them to call child_exit, etc...
998 if (beosd_killpg(getpgrp(), SIGTERM) < 0)
999 ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf,
1002 /* use ap_reclaim_child_processes starting with SIGTERM */
1003 ap_reclaim_child_processes(1);
1005 if (!child_fatal) { /* already recorded */
1006 /* record the shutdown in the log */
1007 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1008 "caught SIGTERM, shutting down");
1015 /* we've been told to restart */
1016 signal(SIGHUP, SIG_IGN);
1019 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1020 AP_SIG_GRACEFUL_STRING " received. Doing graceful restart");
1022 /* Kill 'em all. Since the child acts the same on the parents SIGTERM
1023 * and a SIGHUP, we may as well use the same signal, because some user
1024 * pthreads are stealing signals from us left and right.
1027 ap_reclaim_child_processes(1); /* Start with SIGTERM */
1028 ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
1029 "SIGHUP received. Attempting to restart");
1032 /* just before we go, tidy up the lock we created to prevent a
1033 * potential leak of semaphores...
1035 apr_thread_mutex_destroy(accept_mutex);
1041 static int beos_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp)
1043 static int restart_num = 0;
1044 int no_detach, debug, foreground;
1047 mpm_state = AP_MPMQ_STARTING;
1049 debug = ap_exists_config_define("DEBUG");
1052 foreground = one_process = 1;
1057 one_process = ap_exists_config_define("ONE_PROCESS");
1058 no_detach = ap_exists_config_define("NO_DETACH");
1059 foreground = ap_exists_config_define("FOREGROUND");
1062 /* sigh, want this only the second time around */
1063 if (restart_num++ == 1) {
1066 if (!one_process && !foreground) {
1067 rv = apr_proc_detach(no_detach ? APR_PROC_DETACH_FOREGROUND
1068 : APR_PROC_DETACH_DAEMONIZE);
1069 if (rv != APR_SUCCESS) {
1070 ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL,
1071 "apr_proc_detach failed");
1072 return HTTP_INTERNAL_SERVER_ERROR;
1076 server_pid = getpid();
1080 ap_listen_pre_config();
1081 ap_threads_to_start = DEFAULT_START_THREADS;
1082 min_spare_threads = DEFAULT_MIN_FREE_THREADS;
1083 max_spare_threads = DEFAULT_MAX_FREE_THREADS;
1084 ap_thread_limit = HARD_THREAD_LIMIT;
1085 ap_pid_fname = DEFAULT_PIDLOG;
1086 ap_max_requests_per_thread = DEFAULT_MAX_REQUESTS_PER_THREAD;
1087 #ifdef AP_MPM_WANT_SET_MAX_MEM_FREE
1088 ap_max_mem_free = APR_ALLOCATOR_MAX_FREE_UNLIMITED;
1091 apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
1096 static int beos_check_config(apr_pool_t *pconf, apr_pool_t *plog,
1097 apr_pool_t *ptemp, server_rec *s)
1099 static int restart_num = 0;
1102 /* the reverse of pre_config, we want this only the first time around */
1103 if (restart_num++ == 0) {
1107 if (ap_thread_limit > HARD_THREAD_LIMIT) {
1109 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1110 "WARNING: MaxClients of %d exceeds compile-time "
1111 "limit of", ap_thread_limit);
1112 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1113 " %d servers, decreasing to %d.",
1114 HARD_THREAD_LIMIT, HARD_THREAD_LIMIT);
1115 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1116 " To increase, please see the HARD_THREAD_LIMIT"
1118 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1119 " server/mpm/beos%s.", AP_MPM_HARD_LIMITS_FILE);
1121 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1122 "MaxClients of %d exceeds compile-time limit "
1123 "of %d, decreasing to match",
1124 ap_thread_limit, HARD_THREAD_LIMIT);
1126 ap_thread_limit = HARD_THREAD_LIMIT;
1128 else if (ap_thread_limit < 1) {
1130 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1131 "WARNING: MaxClients of %d not allowed, "
1132 "increasing to 1.", ap_thread_limit);
1134 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1135 "MaxClients of %d not allowed, increasing to 1",
1138 ap_thread_limit = 1;
1141 /* ap_threads_to_start > ap_thread_limit checked in ap_mpm_run() */
1142 if (ap_threads_to_start < 0) {
1144 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1145 "WARNING: StartThreads of %d not allowed, "
1146 "increasing to 1.", ap_threads_to_start);
1148 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1149 "StartThreads of %d not allowed, increasing to 1",
1150 ap_threads_to_start);
1152 ap_threads_to_start = 1;
1155 if (min_spare_threads < 1) {
1157 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1158 "WARNING: MinSpareThreads of %d not allowed, "
1159 "increasing to 1", min_spare_threads);
1160 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1161 " to avoid almost certain server failure.");
1162 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1163 " Please read the documentation.");
1165 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1166 "MinSpareThreads of %d not allowed, increasing to 1",
1169 min_spare_threads = 1;
1172 /* max_spare_threads < min_spare_threads checked in ap_mpm_run() */
1174 if (ap_max_requests_per_thread < 0) {
1176 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1177 "WARNING: MaxRequestsPerThread of %d not allowed, "
1178 "increasing to 0,", ap_max_requests_per_thread);
1179 ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
1180 " but this may not be what you want.");
1182 ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s,
1183 "MaxRequestsPerThread of %d not allowed, "
1184 "increasing to 0", ap_max_requests_per_thread);
1186 ap_max_requests_per_thread = 0;
1192 static void beos_hooks(apr_pool_t *p)
1196 ap_hook_pre_config(beos_pre_config, NULL, NULL, APR_HOOK_MIDDLE);
1197 ap_hook_check_config(beos_check_config, NULL, NULL, APR_HOOK_MIDDLE);
1200 static const char *set_threads_to_start(cmd_parms *cmd, void *dummy, const char *arg)
1202 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1207 ap_threads_to_start = atoi(arg);
1211 static const char *set_min_spare_threads(cmd_parms *cmd, void *dummy, const char *arg)
1213 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1218 min_spare_threads = atoi(arg);
1222 static const char *set_max_spare_threads(cmd_parms *cmd, void *dummy, const char *arg)
1224 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1229 max_spare_threads = atoi(arg);
1233 static const char *set_threads_limit (cmd_parms *cmd, void *dummy, const char *arg)
1235 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1240 ap_thread_limit = atoi(arg);
1244 static const char *set_max_requests_per_thread (cmd_parms *cmd, void *dummy, const char *arg)
1246 const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
1251 ap_max_requests_per_thread = atoi(arg);
1255 static const command_rec beos_cmds[] = {
1256 BEOS_DAEMON_COMMANDS,
1258 AP_INIT_TAKE1( "StartThreads", set_threads_to_start, NULL, RSRC_CONF,
1259 "Number of threads to launch at server startup"),
1260 AP_INIT_TAKE1( "MinSpareThreads", set_min_spare_threads, NULL, RSRC_CONF,
1261 "Minimum number of idle children, to handle request spikes"),
1262 AP_INIT_TAKE1( "MaxSpareThreads", set_max_spare_threads, NULL, RSRC_CONF,
1263 "Maximum number of idle children" ),
1264 AP_INIT_TAKE1( "MaxClients", set_threads_limit, NULL, RSRC_CONF,
1265 "Maximum number of children alive at the same time (max threads)" ),
1266 AP_INIT_TAKE1( "MaxRequestsPerThread", set_max_requests_per_thread, NULL, RSRC_CONF,
1267 "Maximum number of requests served by a thread" ),
1271 module AP_MODULE_DECLARE_DATA mpm_beos_module = {
1273 NULL, /* hook to run before apache parses args */
1274 NULL, /* create per-directory config structure */
1275 NULL, /* merge per-directory config structures */
1276 NULL, /* create per-server config structure */
1277 NULL, /* merge per-server config structures */
1278 beos_cmds, /* command apr_table_t */
1279 beos_hooks /* register_hooks */