static int make_child(server_rec *s, int slot) { int pid; if (slot + 1 > ap_max_daemons_limit) { ap_max_daemons_limit = slot + 1; } if (one_process) { apr_signal(SIGHUP, just_die); /* Don't catch AP_SIG_GRACEFUL in ONE_PROCESS mode :) */ apr_signal(SIGINT, just_die); #ifdef SIGQUIT apr_signal(SIGQUIT, SIG_DFL); #endif apr_signal(SIGTERM, just_die); child_main(slot); } (void) ap_update_child_status_from_indexes(slot, 0, SERVER_STARTING, (request_rec *) NULL); #ifdef _OSD_POSIX /* BS2000 requires a "special" version of fork() before a setuid() call */ if ((pid = os_fork(unixd_config.user_name)) == -1) { #elif defined(TPF) if ((pid = os_fork(s, slot)) == -1) { #else if ((pid = fork()) == -1) { #endif ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, "fork: Unable to fork new process"); /* fork didn't succeed. Fix the scoreboard or else * it will say SERVER_STARTING forever and ever */ (void) ap_update_child_status_from_indexes(slot, 0, SERVER_DEAD, (request_rec *) NULL); /* In case system resources are maxxed out, we don't want Apache running away with the CPU trying to fork over and over and over again. */ sleep(10); return -1; } if (!pid) { #ifdef HAVE_BINDPROCESSOR /* by default AIX binds to a single processor * this bit unbinds children which will then bind to another cpu */ int status = bindprocessor(BINDPROCESS, (int)getpid(), PROCESSOR_CLASS_ANY); if (status != OK) { ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "processor unbind failed %d", status); } #endif RAISE_SIGSTOP(MAKE_CHILD); AP_MONCONTROL(1); /* Disable the parent's signal handlers and set up proper handling in * the child. */ apr_signal(SIGHUP, just_die); apr_signal(SIGTERM, just_die); /* The child process doesn't do anything for AP_SIG_GRACEFUL. * Instead, the pod is used for signalling graceful restart. */ apr_signal(AP_SIG_GRACEFUL, SIG_IGN); child_main(slot); } ap_scoreboard_image->parent[slot].pid = pid; return 0; } /* start up a bunch of children */ static void startup_children(int number_to_start) { int i; for (i = 0; number_to_start && i < ap_daemons_limit; ++i) { if (ap_scoreboard_image->servers[i][0].status != SERVER_DEAD) { continue; } if (make_child(ap_server_conf, i) < 0) { break; } --number_to_start; } } /* * idle_spawn_rate is the number of children that will be spawned on the * next maintenance cycle if there aren't enough idle servers. It is * doubled up to MAX_SPAWN_RATE, and reset only when a cycle goes by * without the need to spawn. */ static int idle_spawn_rate = 1; #ifndef MAX_SPAWN_RATE #define MAX_SPAWN_RATE (32) #endif static int hold_off_on_exponential_spawning; static void perform_idle_server_maintenance(apr_pool_t *p) { int i; int to_kill; int idle_count; worker_score *ws; int free_length; int free_slots[MAX_SPAWN_RATE]; int last_non_dead; int total_non_dead; /* initialize the free_list */ free_length = 0; to_kill = -1; idle_count = 0; last_non_dead = -1; total_non_dead = 0; for (i = 0; i < ap_daemons_limit; ++i) { int status; if (i >= ap_max_daemons_limit && free_length == idle_spawn_rate) break; ws = &ap_scoreboard_image->servers[i][0]; status = ws->status; if (status == SERVER_DEAD) { /* try to keep children numbers as low as possible */ if (free_length < idle_spawn_rate) { free_slots[free_length] = i; ++free_length; } } else { /* We consider a starting server as idle because we started it * at least a cycle ago, and if it still hasn't finished starting * then we're just going to swamp things worse by forking more. * So we hopefully won't need to fork more if we count it. * This depends on the ordering of SERVER_READY and SERVER_STARTING. */ if (status <= SERVER_READY) { ++ idle_count; /* always kill the highest numbered child if we have to... * no really well thought out reason ... other than observing * the server behaviour under linux where lower numbered children * tend to service more hits (and hence are more likely to have * their data in cpu caches). */ to_kill = i; } ++total_non_dead; last_non_dead = i; } } ap_max_daemons_limit = last_non_dead + 1; if (idle_count > ap_daemons_max_free) { /* kill off one child... we use the pod because that'll cause it to * shut down gracefully, in case it happened to pick up a request * while we were counting */ ap_mpm_pod_signal(pod); idle_spawn_rate = 1; } else if (idle_count < ap_daemons_min_free) { /* terminate the free list */ if (free_length == 0) { /* only report this condition once */ static int reported = 0; if (!reported) { ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, "server reached MaxClients setting, consider" " raising the MaxClients setting"); reported = 1; } idle_spawn_rate = 1; } else { if (idle_spawn_rate >= 8) { ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf, "server seems busy, (you may need " "to increase StartServers, or Min/MaxSpareServers), " "spawning %d children, there are %d idle, and " "%d total children", idle_spawn_rate, idle_count, total_non_dead); } for (i = 0; i < free_length; ++i) { #ifdef TPF if (make_child(ap_server_conf, free_slots[i]) == -1) { if(free_length == 1) { shutdown_pending = 1; ap_log_error(APLOG_MARK, APLOG_EMERG, 0, ap_server_conf, "No active child processes: shutting down"); } } #else make_child(ap_server_conf, free_slots[i]); #endif /* TPF */ } /* the next time around we want to spawn twice as many if this * wasn't good enough, but not if we've just done a graceful */ if (hold_off_on_exponential_spawning) { --hold_off_on_exponential_spawning; } else if (idle_spawn_rate < MAX_SPAWN_RATE) { idle_spawn_rate *= 2; } } } else { idle_spawn_rate = 1; } }
int ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s) { int index; int remaining_children_to_start; apr_status_t rv; ap_log_pid(pconf, ap_pid_fname); first_server_limit = server_limit; if (changed_limit_at_restart) { ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, "WARNING: Attempt to change ServerLimit " "ignored during restart"); changed_limit_at_restart = 0; } /* Initialize cross-process accept lock */ ap_lock_fname = apr_psprintf(_pconf, "%s.%" APR_PID_T_FMT, ap_server_root_relative(_pconf, ap_lock_fname), ap_my_pid); rv = apr_proc_mutex_create(&accept_mutex, ap_lock_fname, ap_accept_lock_mech, _pconf); if (rv != APR_SUCCESS) { ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, "Couldn't create accept lock"); mpm_state = AP_MPMQ_STOPPING; return 1; } #if APR_USE_SYSVSEM_SERIALIZE if (ap_accept_lock_mech == APR_LOCK_DEFAULT || ap_accept_lock_mech == APR_LOCK_SYSVSEM) { #else if (ap_accept_lock_mech == APR_LOCK_SYSVSEM) { #endif rv = unixd_set_proc_mutex_perms(accept_mutex); if (rv != APR_SUCCESS) { ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, "Couldn't set permissions on cross-process lock; " "check User and Group directives"); mpm_state = AP_MPMQ_STOPPING; return 1; } } if (!is_graceful) { if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) { mpm_state = AP_MPMQ_STOPPING; return 1; } /* fix the generation number in the global score; we just got a new, * cleared scoreboard */ ap_scoreboard_image->global->running_generation = ap_my_generation; } set_signals(); if (one_process) { AP_MONCONTROL(1); } if (ap_daemons_max_free < ap_daemons_min_free + 1) /* Don't thrash... */ ap_daemons_max_free = ap_daemons_min_free + 1; /* If we're doing a graceful_restart then we're going to see a lot * of children exiting immediately when we get into the main loop * below (because we just sent them AP_SIG_GRACEFUL). This happens pretty * rapidly... and for each one that exits we'll start a new one until * we reach at least daemons_min_free. But we may be permitted to * start more than that, so we'll just keep track of how many we're * supposed to start up without the 1 second penalty between each fork. */ remaining_children_to_start = ap_daemons_to_start; if (remaining_children_to_start > ap_daemons_limit) { remaining_children_to_start = ap_daemons_limit; } if (!is_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 */ hold_off_on_exponential_spawning = 10; } ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, "%s configured -- resuming normal operations", ap_get_server_version()); ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf, "Server built: %s", ap_get_server_built()); #ifdef AP_MPM_WANT_SET_ACCEPT_LOCK_MECH ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, "AcceptMutex: %s (default: %s)", apr_proc_mutex_name(accept_mutex), apr_proc_mutex_defname()); #endif restart_pending = shutdown_pending = 0; mpm_state = AP_MPMQ_RUNNING; while (!restart_pending && !shutdown_pending) { int child_slot; apr_exit_why_e exitwhy; int status, processed_status; /* this is a memory leak, but I'll fix it later. */ apr_proc_t pid; ap_wait_or_timeout(&exitwhy, &status, &pid, pconf); /* XXX: if it takes longer than 1 second for all our children * to start up and get into IDLE state then we may spawn an * extra child */ if (pid.pid != -1) { processed_status = ap_process_child_status(&pid, exitwhy, status); if (processed_status == APEXIT_CHILDFATAL) { mpm_state = AP_MPMQ_STOPPING; return 1; } /* non-fatal death... note that it's gone in the scoreboard. */ child_slot = find_child_by_pid(&pid); if (child_slot >= 0) { (void) ap_update_child_status_from_indexes(child_slot, 0, SERVER_DEAD, (request_rec *) NULL); if (processed_status == APEXIT_CHILDSICK) { /* child detected a resource shortage (E[NM]FILE, ENOBUFS, etc) * cut the fork rate to the minimum */ idle_spawn_rate = 1; } else if (remaining_children_to_start && child_slot < ap_daemons_limit) { /* we're still doing a 1-for-1 replacement of dead * children with new children */ make_child(ap_server_conf, child_slot); --remaining_children_to_start; } #if APR_HAS_OTHER_CHILD } else if (apr_proc_other_child_read(&pid, status) == 0) { /* handled */ #endif } else if (is_graceful) { /* Great, we've probably just lost a slot in the * scoreboard. Somehow we don't know about this * child. */ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, "long lost child came home! (pid %ld)", (long)pid.pid); } /* Don't perform idle maintenance when a child dies, * only do it when there's a timeout. Remember only a * finite number of children can die, and it's pretty * pathological for a lot to die suddenly. */ continue; } else if (remaining_children_to_start) { /* we hit a 1 second timeout in which none of the previous * generation of children needed to be reaped... so assume * they're all done, and pick up the slack if any is left. */ startup_children(remaining_children_to_start); remaining_children_to_start = 0; /* In any event we really shouldn't do the code below because * few of the servers we just started are in the IDLE state * yet, so we'd mistakenly create an extra server. */ continue; } perform_idle_server_maintenance(pconf); #ifdef TPF shutdown_pending = os_check_server(tpf_server_name); ap_check_signals(); sleep(1); #endif /*TPF */ } mpm_state = AP_MPMQ_STOPPING; if (shutdown_pending) { /* Time to gracefully shut down: * Kill child processes, tell them to call child_exit, etc... */ if (unixd_killpg(getpgrp(), SIGTERM) < 0) { ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGTERM"); } ap_reclaim_child_processes(1); /* Start with SIGTERM */ /* cleanup pid file on normal shutdown */ { const char *pidfile = NULL; pidfile = ap_server_root_relative (pconf, ap_pid_fname); if ( pidfile != NULL && unlink(pidfile) == 0) ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf, "removed PID file %s (pid=%ld)", pidfile, (long)getpid()); } ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, "caught SIGTERM, shutting down"); return 1; } /* we've been told to restart */ apr_signal(SIGHUP, SIG_IGN); if (one_process) { /* not worth thinking about */ return 1; } /* advance to the next generation */ /* XXX: we really need to make sure this new generation number isn't in * use by any of the children. */ ++ap_my_generation; ap_scoreboard_image->global->running_generation = ap_my_generation; if (is_graceful) { ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, "Graceful restart requested, doing restart"); /* kill off the idle ones */ ap_mpm_pod_killpg(pod, ap_max_daemons_limit); /* This is mostly for debugging... so that we know what is still * gracefully dealing with existing request. This will break * in a very nasty way if we ever have the scoreboard totally * file-based (no shared memory) */ for (index = 0; index < ap_daemons_limit; ++index) { if (ap_scoreboard_image->servers[index][0].status != SERVER_DEAD) { ap_scoreboard_image->servers[index][0].status = SERVER_GRACEFUL; } } } else { /* Kill 'em off */ if (unixd_killpg(getpgrp(), SIGHUP) < 0) { ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, "killpg SIGHUP"); } ap_reclaim_child_processes(0); /* Not when just starting up */ ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, "SIGHUP received. Attempting to restart"); } return 0; } /* This really should be a post_config hook, but the error log is already * redirected by that point, so we need to do this in the open_logs phase. */ static int prefork_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s) { apr_status_t rv; pconf = p; ap_server_conf = s; if ((num_listensocks = ap_setup_listeners(ap_server_conf)) < 1) { ap_log_error(APLOG_MARK, APLOG_ALERT|APLOG_STARTUP, 0, NULL, "no listening sockets available, shutting down"); return DONE; } if ((rv = ap_mpm_pod_open(pconf, &pod))) { ap_log_error(APLOG_MARK, APLOG_CRIT|APLOG_STARTUP, rv, NULL, "Could not open pipe-of-death."); return DONE; } return OK; }
int main(int argc, const char * const argv[]) { char c; const char *ap_confname = "httpd.conf"; const char *ngx_confname = "nginx.conf"; const char *def_server_root = NULL; const char *temp_error_log = NULL; const char *error; process_rec *process; server_rec *server_conf; apr_pool_t *pglobal; apr_pool_t *pconf; apr_pool_t *plog; /* Pool of log streams, reset _after_ each read of conf */ apr_pool_t *ptemp; /* Pool for temporary config stuff, reset often */ apr_pool_t *pcommands; /* Pool for -D, -C and -c switches */ apr_getopt_t *opt; apr_status_t rv; const char *optarg; AP_MONCONTROL(0); /* turn off profiling of startup */ process = init_process(&argc, &argv); pglobal = process->pool; pconf = process->pconf; ap_server_argv0 = process->short_name; #if APR_CHARSET_EBCDIC if (ap_init_ebcdic(pglobal) != APR_SUCCESS) { destroy_and_exit_process(process, 1); } #endif apr_pool_create(&pcommands, pglobal); apr_pool_tag(pcommands, "pcommands"); ap_server_pre_read_config = apr_array_make(pcommands, 1, sizeof(char *)); ap_server_post_read_config = apr_array_make(pcommands, 1, sizeof(char *)); ap_server_config_defines = apr_array_make(pcommands, 1, sizeof(char *)); error = ap_setup_prelinked_modules(process); if (error) { ap_log_error(APLOG_MARK, APLOG_STARTUP|APLOG_EMERG, 0, NULL, "%s: %s", ap_server_argv0, error); destroy_and_exit_process(process, 1); } ap_run_rewrite_args(process); /* Maintain AP_SERVER_BASEARGS list in http_main.h to allow the MPM * to safely pass on our args from its rewrite_args() handler. */ apr_getopt_init(&opt, pcommands, process->argc, process->argv); while ((rv = apr_getopt(opt, APN_SERVER_BASEARGS, &c, &optarg)) == APR_SUCCESS) { switch (c) { case 'f': ap_confname = optarg; break; case 'o': ngx_confname = optarg; break; case 'd': def_server_root = optarg; break; case 'l': ap_show_modules(); destroy_and_exit_process(process, 0); case 'L': ap_show_directives(); destroy_and_exit_process(process, 0); case 'h': case '?': usage(process); destroy_and_exit_process(process, 0); case 'H': setconf = 1; confname = optarg; break; case 'i': defindex = 1; break; case 'G': defgzip = 1; break; case 'D': cleancfg = 1; break; case 'R': forcerm = 1; break; } } if (rv != APR_EOF || argc < 3) { if (c != 'h' && c != '?') { usage(process); } destroy_and_exit_process(process, 1); } apr_pool_create(&plog, pglobal); apr_pool_tag(plog, "plog"); apr_pool_create(&ptemp, pconf); apr_pool_tag(ptemp, "ptemp"); /** we need the real path */ char* fullpath = NULL; rv = apr_get_realpath(&fullpath, ap_confname, plog); if (rv != APR_SUCCESS){ apn_error("Apache conf file is not found " "or the given path is invalid! Exit.\n"); destroy_and_exit_process(process, 1); } ap_confname = apr_pstrdup(plog, fullpath); /* Note that we preflight the config file once * before reading it _again_ in the main loop. * This allows things, log files configuration * for example, to settle down. */ ap_server_root = def_server_root; if (!ap_server_root){ // no specify serverroot by -d in commandline. if (!ap_confname) { apn_error("Apache conf file name is null!\n"); destroy_and_exit_process(process, 1); } /** * if ap_confname is absolute path, get the prefix as serverroot. * if it is not, set the current path as serverroot. */ char* basedir; rv = apr_get_basedir(&basedir, ap_confname, process->pool); if(rv!=APR_SUCCESS){ apn_error("Apache conf file is not found " "or the given path is invalid! Exit.\n"); destroy_and_exit_process(process, 1); } ap_server_root = def_server_root = basedir; /** * Sometimes, ap_server_root should be set more intelligence. * Because of apache conf depend on the ServerRoot. * when not in localhost, maybe ServerRoot is not valid, * and here need to guess the ap_server_root. */ apn_fixed_server_root(plog); } if (temp_error_log) { ap_replace_stderr_log(process->pool, temp_error_log); } char *ngx_fullpath = NULL; rv = apr_get_realpath(&ngx_fullpath, ngx_confname, plog); if (rv == APR_SUCCESS && forcerm != 1) { apn_error("Config file exists: %s. Exit.\n", ngx_fullpath); destroy_and_exit_process(process, 1); } else { /* Create a empty nginx.conf, because mod_mime needs this file. */ apr_file_t *f; rv = apr_file_open(&f, ngx_confname, (forcerm == 1 ? APR_TRUNCATE : APR_CREATE ) |APR_APPEND|APR_WRITE, APR_OS_DEFAULT, plog); if (rv != APR_SUCCESS) { apn_error("Create file error: %s\n", ngx_fullpath); destroy_and_exit_process(process, 1); } apr_file_close(f); } /* * here just create the main server, and the vhost is not created. */ server_conf = ap_read_config(process, ptemp, ap_confname, &ap_conftree); if (!server_conf) { destroy_and_exit_process(process, 1); } /* sort hooks here to make sure pre_config hooks are sorted properly */ apr_hook_sort_all(); if (ap_run_pre_config(pconf, plog, ptemp) != OK) { ap_log_error(APLOG_MARK, APLOG_STARTUP |APLOG_ERR, 0, NULL, "Pre-configuration failed"); destroy_and_exit_process(process, 1); } /* Lijinhu added : check the configuration validation */ if (ap_conftree == NULL) { apn_error("The apache conf file is invalid! Please check it. Exit.\n"); destroy_and_exit_process(process, 1); } rv = ap_process_config_tree(server_conf, ap_conftree, process->pconf, ptemp); if (rv == OK) { /* * 1. merge server configs. * 2. merge per dir configs for each server. * 3. re-order the directorise. */ ap_fixup_virtual_hosts(pconf, server_conf); /* compile the tables and such we need to do the run-time vhost lookups */ ap_fini_vhost_config(pconf, server_conf); /* * Sort hooks again because ap_process_config_tree may have added * modules and hence hooks. This happens with mod_perl and modules * written in perl. */ apr_hook_sort_all(); ap_run_test_config(pconf, server_conf); ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, "Syntax OK"); if ( ap_run_post_config(pconf, plog, ptemp, server_conf) != OK) { ap_log_error(APLOG_MARK, APLOG_STARTUP |APLOG_ERR, 0, NULL, "Failed when merge some configurations"); destroy_and_exit_process(process, 1); } /* * migrate the config to nginx conf format. * generate the conf file of nginx. */ rv = apn_migrate_to_nginx(plog, server_conf, ngx_confname); if (rv != OK) { ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, "Migrate Error!"); } destroy_and_exit_process(process, 0); } return 0; /* Termination 'ok' */ }