add a comment about using AddModule to the WIN section
[mod_fastcgi.git] / fcgi_pm.c
blob3eb0624547d4333ae9696cc7180261bf459c3365
1 /*
2 * $Id: fcgi_pm.c,v 1.68 2002/02/23 21:31:19 robs Exp $
3 */
6 #include "fcgi.h"
8 #ifdef _HPUX_SOURCE
9 #include <unistd.h>
10 #define seteuid(arg) setresuid(-1, (arg), -1)
11 #endif
13 int fcgi_dynamic_total_proc_count = 0; /* number of running apps */
14 time_t fcgi_dynamic_epoch = 0; /* last time kill_procs was
15 * invoked by process mgr */
16 time_t fcgi_dynamic_last_analyzed = 0; /* last time calculation was
17 * made for the dynamic procs */
19 static time_t now = 0;
21 #ifdef WIN32
22 #pragma warning ( disable : 4100 4102 )
23 static BOOL bTimeToDie = FALSE; /* process termination flag */
24 HANDLE fcgi_event_handles[3];
25 #ifndef SIGKILL
26 #define SIGKILL 9
27 #endif
28 #endif
31 #ifndef WIN32
32 static int seteuid_root(void)
34 int rc = seteuid((uid_t)0);
35 if (rc == -1) {
36 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
37 "FastCGI: seteuid(0) failed");
39 return rc;
42 static int seteuid_user(void)
44 int rc = seteuid(ap_user_id);
45 if (rc == -1) {
46 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
47 "FastCGI: seteuid(%u) failed", (unsigned)ap_user_id);
49 return rc;
51 #endif
54 * Signal the process to exit. How (or if) the process responds
55 * depends on the FastCGI application library (esp. on Win32) and
56 * possibly application code (signal handlers and whether or not
57 * SA_RESTART is on). At any rate, we send the signal with the
58 * hopes that the process will exit on its own. Later, as we
59 * review the state of application processes, if we see one marked
60 * for death, but that hasn't died within a specified period of
61 * time, fcgi_kill() is called again with a KILL)
63 static void fcgi_kill(ServerProcess *process, int sig)
65 FCGIDBG3("fcgi_kill(%ld, %d)", (long) process->pid, sig);
67 process->state = FCGI_VICTIM_STATE;
69 #ifdef WIN32
70 if (sig == SIGTERM)
72 SetEvent(process->terminationEvent);
74 else if (sig == SIGKILL)
76 TerminateProcess(process->handle, 1);
78 else
80 ap_assert(0);
82 #else
83 if (fcgi_wrapper)
85 seteuid_root();
88 kill(process->pid, sig);
90 if (fcgi_wrapper)
92 seteuid_user();
94 #endif
97 /*******************************************************************************
98 * Send SIGTERM to each process in the server class, remove socket
99 * file if appropriate. Currently this is only called when the PM is shutting
100 * down and thus memory isn't freed and sockets and files aren't closed.
102 static void shutdown_all()
104 fcgi_server *s = fcgi_servers;
106 while (s)
108 ServerProcess *proc = s->procs;
109 int i;
110 int numChildren = (s->directive == APP_CLASS_DYNAMIC)
111 ? dynamicMaxClassProcs
112 : s->numProcesses;
114 #ifndef WIN32
115 if (s->socket_path != NULL && s->directive != APP_CLASS_EXTERNAL)
117 /* Remove the socket file */
118 if (unlink(s->socket_path) != 0 && errno != ENOENT) {
119 ap_log_error(FCGI_LOG_ERR, fcgi_apache_main_server,
120 "FastCGI: unlink() failed to remove socket file \"%s\" for%s server \"%s\"",
121 s->socket_path,
122 (s->directive == APP_CLASS_DYNAMIC) ? " (dynamic)" : "", s->fs_path);
125 #endif
127 /* Send TERM to all processes */
128 for (i = 0; i < numChildren; i++, proc++)
130 if (proc->state == FCGI_RUNNING_STATE)
132 fcgi_kill(proc, SIGTERM);
136 s = s->next;
140 static int init_listen_sock(fcgi_server * fs)
142 ap_assert(fs->directive != APP_CLASS_EXTERNAL);
144 /* Create the socket */
145 if ((fs->listenFd = socket(fs->socket_addr->sa_family, SOCK_STREAM, 0)) < 0)
147 #ifdef WIN32
148 errno = WSAGetLastError(); // Not sure if this will work as expected
149 #endif
150 ap_log_error(FCGI_LOG_CRIT_ERRNO, fcgi_apache_main_server,
151 "FastCGI: can't create %sserver \"%s\": socket() failed",
152 (fs->directive == APP_CLASS_DYNAMIC) ? "(dynamic) " : "",
153 fs->fs_path);
154 return -1;
157 #ifndef WIN32
158 if (fs->socket_addr->sa_family == AF_UNIX)
160 /* Remove any existing socket file.. just in case */
161 unlink(((struct sockaddr_un *)fs->socket_addr)->sun_path);
163 else
164 #endif
166 int flag = 1;
167 setsockopt(fs->listenFd, SOL_SOCKET, SO_REUSEADDR, (char *)&flag, sizeof(flag));
170 /* Bind it to the socket_addr */
171 if (bind(fs->listenFd, fs->socket_addr, fs->socket_addr_len))
173 char port[11];
175 #ifdef WIN32
176 errno = WSAGetLastError();
177 #endif
178 ap_snprintf(port, sizeof(port), "port=%d",
179 ((struct sockaddr_in *)fs->socket_addr)->sin_port);
181 ap_log_error(FCGI_LOG_CRIT_ERRNO, fcgi_apache_main_server,
182 "FastCGI: can't create %sserver \"%s\": bind() failed [%s]",
183 (fs->directive == APP_CLASS_DYNAMIC) ? "(dynamic) " : "",
184 fs->fs_path,
185 #ifndef WIN32
186 (fs->socket_addr->sa_family == AF_UNIX) ?
187 ((struct sockaddr_un *)fs->socket_addr)->sun_path :
188 #endif
189 port);
192 #ifndef WIN32
193 /* Twiddle Unix socket permissions */
194 else if (fs->socket_addr->sa_family == AF_UNIX
195 && chmod(((struct sockaddr_un *)fs->socket_addr)->sun_path, S_IRUSR | S_IWUSR))
197 ap_log_error(FCGI_LOG_CRIT, fcgi_apache_main_server,
198 "FastCGI: can't create %sserver \"%s\": chmod() of socket failed",
199 (fs->directive == APP_CLASS_DYNAMIC) ? "(dynamic) " : "",
200 fs->fs_path);
202 #endif
204 /* Set to listen */
205 else if (listen(fs->listenFd, fs->listenQueueDepth))
207 #ifdef WIN32
208 errno = WSAGetLastError();
209 #endif
210 ap_log_error(FCGI_LOG_CRIT_ERRNO, fcgi_apache_main_server,
211 "FastCGI: can't create %sserver \"%s\": listen() failed",
212 (fs->directive == APP_CLASS_DYNAMIC) ? "(dynamic) " : "",
213 fs->fs_path);
215 else
217 return 0;
220 ap_pclosesocket(fcgi_config_pool, fs->listenFd);
221 fs->listenFd = -1;
222 return -2;
226 *----------------------------------------------------------------------
228 * pm_main
230 * The FastCGI process manager, which runs as a separate
231 * process responsible for:
232 * - Starting all the FastCGI proceses.
233 * - Restarting any of these processes that die (indicated
234 * by SIGCHLD).
235 * - Catching SIGTERM and relaying it to all the FastCGI
236 * processes before exiting.
238 * Inputs:
239 * Uses global variable fcgi_servers.
241 * Results:
242 * Does not return.
244 * Side effects:
245 * Described above.
247 *----------------------------------------------------------------------
249 #ifndef WIN32
250 static int caughtSigTerm = FALSE;
251 static int caughtSigChld = FALSE;
252 static int caughtSigAlarm = FALSE;
254 static void signal_handler(int signo)
256 if ((signo == SIGTERM) || (signo == SIGUSR1) || (signo == SIGHUP)) {
257 /* SIGUSR1 & SIGHUP are sent by apache to its process group
258 * when apache get 'em. Apache follows up (1.2.x) with attacks
259 * on each of its child processes, but we've got the KillMgr
260 * sitting between us so we never see the KILL. The main loop
261 * in ProcMgr also checks to see if the KillMgr has terminated,
262 * and if it has, we handl it as if we should shutdown too. */
263 caughtSigTerm = TRUE;
264 } else if(signo == SIGCHLD) {
265 caughtSigChld = TRUE;
266 } else if(signo == SIGALRM) {
267 caughtSigAlarm = TRUE;
270 #endif
273 *----------------------------------------------------------------------
275 * spawn_fs_process --
277 * Fork and exec the specified fcgi process.
279 * Results:
280 * 0 for successful fork, -1 for failed fork.
282 * In case the child fails before or in the exec, the child
283 * obtains the error log by calling getErrLog, logs
284 * the error, and exits with exit status = errno of
285 * the failed system call.
287 * Side effects:
288 * Child process created.
290 *----------------------------------------------------------------------
292 static pid_t spawn_fs_process(fcgi_server *fs, ServerProcess *process)
294 #ifndef WIN32
295 pid_t child_pid;
296 int i;
297 char *dirName;
298 char *dnEnd, *failedSysCall;
300 child_pid = fork();
301 if (child_pid) {
302 return child_pid;
305 /* We're the child. We're gonna exec() so pools don't matter. */
307 dnEnd = strrchr(fs->fs_path, '/');
308 if (dnEnd == NULL) {
309 dirName = "./";
310 } else {
311 dirName = ap_pcalloc(fcgi_config_pool, dnEnd - fs->fs_path + 1);
312 dirName = memcpy(dirName, fs->fs_path, dnEnd - fs->fs_path);
314 if (chdir(dirName) < 0) {
315 failedSysCall = "chdir()";
316 goto FailedSystemCallExit;
319 #ifndef __EMX__
320 /* OS/2 dosen't support nice() */
321 if (fs->processPriority != 0) {
322 if (nice(fs->processPriority) == -1) {
323 failedSysCall = "nice()";
324 goto FailedSystemCallExit;
327 #endif
329 /* Open the listenFd on spec'd fd */
330 if (fs->listenFd != FCGI_LISTENSOCK_FILENO)
331 dup2(fs->listenFd, FCGI_LISTENSOCK_FILENO);
333 /* Close all other open fds, except stdout/stderr. Leave these two open so
334 * FastCGI applications don't have to find and fix ALL 3rd party libs that
335 * write to stdout/stderr inadvertantly. For now, just leave 'em open to the
336 * main server error_log - @@@ provide a directive control where this goes.
338 ap_error_log2stderr(fcgi_apache_main_server);
339 dup2(STDERR_FILENO, STDOUT_FILENO);
340 for (i = 0; i < FCGI_MAX_FD; i++) {
341 if (i != FCGI_LISTENSOCK_FILENO && i != STDERR_FILENO && i != STDOUT_FILENO) {
342 close(i);
346 /* Ignore SIGPIPE by default rather than terminate. The fs SHOULD
347 * install its own handler. */
348 signal(SIGPIPE, SIG_IGN);
350 if (fcgi_wrapper && (fcgi_user_id != fs->uid || fcgi_group_id != fs->gid)) {
351 char *shortName = strrchr(fs->fs_path, '/') + 1;
353 /* Relinquish our root real uid powers */
354 seteuid_root();
355 setuid(ap_user_id);
357 do {
358 execle(fcgi_wrapper, fcgi_wrapper, fs->username, fs->group, shortName, NULL, fs->envp);
359 } while (errno == EINTR);
361 else {
362 do {
363 execle(fs->fs_path, fs->fs_path, NULL, fs->envp);
364 } while (errno == EINTR);
367 failedSysCall = "execle()";
369 FailedSystemCallExit:
370 fprintf(stderr, "FastCGI: can't start server \"%s\" (pid %ld), %s failed: %s\n",
371 fs->fs_path, (long) getpid(), failedSysCall, strerror(errno));
372 exit(-1);
374 /* avoid an irrelevant compiler warning */
375 return(0);
377 #else
379 /* Adapted from Apache's util_script.c ap_call_exec() */
380 char *interpreter = NULL;
381 char *quoted_filename;
382 char *pCommand;
383 char *pEnvBlock, *pNext;
385 int i = 0;
386 int iEnvBlockLen = 1;
388 file_type_e fileType;
390 STARTUPINFO si;
391 PROCESS_INFORMATION pi;
393 request_rec r;
394 pid_t pid = -1;
396 pool * tp = ap_make_sub_pool(fcgi_config_pool);
398 HANDLE listen_handle;
399 char * termination_env_string = NULL;
401 process->terminationEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
402 if (process->terminationEvent == NULL)
404 ap_log_error(FCGI_LOG_CRIT, fcgi_apache_main_server,
405 "FastCGI: can't create termination event for server \"%s\", "
406 "CreateEvent() failed", fs->fs_path);
407 exit(0);
409 SetHandleInformation(process->terminationEvent, HANDLE_FLAG_INHERIT, TRUE);
411 termination_env_string = ap_psprintf(tp,
412 "_FCGI_SHUTDOWN_EVENT_=%ld", process->terminationEvent);
414 if (fs->socket_path)
416 SECURITY_ATTRIBUTES sa;
418 sa.lpSecurityDescriptor = NULL;
419 sa.bInheritHandle = TRUE;
420 sa.nLength = sizeof(sa);
422 listen_handle = CreateNamedPipe(fs->socket_path,
423 PIPE_ACCESS_DUPLEX,
424 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
425 PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, &sa);
427 if (listen_handle == INVALID_HANDLE_VALUE)
429 ap_log_error(FCGI_LOG_CRIT, fcgi_apache_main_server,
430 "FastCGI: can't exec server \"%s\", CreateNamedPipe() failed", fs->fs_path);
431 exit(0);
434 else
436 listen_handle = (HANDLE) fs->listenFd;
439 memset(&si, 0, sizeof(si));
440 memset(&pi, 0, sizeof(pi));
441 memset(&r, 0, sizeof(r));
443 // Can up a fake request to pass to ap_get_win32_interpreter()
444 r.per_dir_config = fcgi_apache_main_server->lookup_defaults;
445 r.server = fcgi_apache_main_server;
446 r.filename = (char *) fs->fs_path;
447 r.pool = tp;
449 fileType = ap_get_win32_interpreter(&r, &interpreter);
451 if (fileType == eFileTypeUNKNOWN) {
452 ap_log_error(FCGI_LOG_ERR_NOERRNO, fcgi_apache_main_server,
453 "FastCGI: %s is not executable; ensure interpreted scripts have "
454 "\"#!\" as their first line",
455 fs->fs_path);
456 ap_destroy_pool(tp);
457 return (pid);
461 * We have the interpreter (if there is one) and we have
462 * the arguments (if there are any).
463 * Build the command string to pass to CreateProcess.
465 quoted_filename = ap_pstrcat(tp, "\"", fs->fs_path, "\"", NULL);
466 if (interpreter && *interpreter) {
467 pCommand = ap_pstrcat(tp, interpreter, " ", quoted_filename, NULL);
469 else {
470 pCommand = quoted_filename;
474 * Make child process use hPipeOutputWrite as standard out,
475 * and make sure it does not show on screen.
477 si.cb = sizeof(si);
478 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
479 si.wShowWindow = SW_HIDE;
480 si.hStdInput = listen_handle;
482 // XXX These should be open to the error_log
483 si.hStdOutput = INVALID_HANDLE_VALUE;
484 si.hStdError = INVALID_HANDLE_VALUE;
487 * Win32's CreateProcess call requires that the environment
488 * be passed in an environment block, a null terminated block of
489 * null terminated strings.
490 * @todo we should store the env in this format for win32.
492 while (fs->envp[i])
494 iEnvBlockLen += strlen(fs->envp[i]) + 1;
495 i++;
498 iEnvBlockLen += strlen(termination_env_string) + 1;
499 iEnvBlockLen += strlen(fs->mutex_env_string) + 1;
501 pEnvBlock = (char *) ap_pcalloc(tp, iEnvBlockLen);
503 i = 0;
504 pNext = pEnvBlock;
505 while (fs->envp[i])
507 strcpy(pNext, fs->envp[i]);
508 pNext += strlen(pNext) + 1;
509 i++;
512 strcpy(pNext, termination_env_string);
513 pNext += strlen(pNext) + 1;
514 strcpy(pNext, fs->mutex_env_string);
516 if (CreateProcess(NULL, pCommand, NULL, NULL, TRUE,
518 pEnvBlock,
519 ap_make_dirstr_parent(tp, fs->fs_path),
520 &si, &pi))
522 /* Hack to get 16-bit CGI's working. It works for all the
523 * standard modules shipped with Apache. pi.dwProcessId is 0
524 * for 16-bit CGIs and all the Unix specific code that calls
525 * ap_call_exec interprets this as a failure case. And we can't
526 * use -1 either because it is mapped to 0 by the caller.
528 pid = (fileType == eFileTypeEXE16) ? -2 : pi.dwProcessId;
530 process->handle = pi.hProcess;
531 CloseHandle(pi.hThread);
534 if (fs->socket_path)
536 CloseHandle(listen_handle);
539 ap_destroy_pool(tp);
541 return pid;
543 #endif
546 #ifndef WIN32
547 static void reduce_privileges(void)
549 char *name;
551 if (geteuid() != 0)
552 return;
554 #ifndef __EMX__
555 /* Get username if passed as a uid */
556 if (ap_user_name[0] == '#') {
557 uid_t uid = atoi(&ap_user_name[1]);
558 struct passwd *ent = getpwuid(uid);
560 if (ent == NULL) {
561 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
562 "FastCGI: process manager exiting, getpwuid(%u) couldn't determine user name, "
563 "you probably need to modify the User directive", (unsigned)uid);
564 exit(1);
566 name = ent->pw_name;
568 else
569 name = ap_user_name;
571 /* Change Group */
572 if (setgid(ap_group_id) == -1) {
573 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
574 "FastCGI: process manager exiting, setgid(%u) failed", (unsigned)ap_group_id);
575 exit(1);
578 /* See Apache PR2580. Until its resolved, do it the same way CGI is done.. */
580 /* Initialize supplementary groups */
581 if (initgroups(name, ap_group_id) == -1) {
582 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
583 "FastCGI: process manager exiting, initgroups(%s,%u) failed",
584 name, (unsigned)ap_group_id);
585 exit(1);
587 #endif /* __EMX__ */
589 /* Change User */
590 if (fcgi_wrapper) {
591 if (seteuid_user() == -1) {
592 ap_log_error(FCGI_LOG_ALERT_NOERRNO, fcgi_apache_main_server,
593 "FastCGI: process manager exiting, failed to reduce privileges");
594 exit(1);
597 else {
598 if (setuid(ap_user_id) == -1) {
599 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
600 "FastCGI: process manager exiting, setuid(%u) failed", (unsigned)ap_user_id);
601 exit(1);
606 /*************
607 * Change the name of this process - best we can easily.
609 static void change_process_name(const char * const name)
611 strncpy(ap_server_argv0, name, strlen(ap_server_argv0));
613 #endif
615 static void schedule_start(fcgi_server *s, int proc)
617 /* If we've started one recently, don't register another */
618 time_t time_passed = now - s->restartTime;
620 if ((s->procs[proc].pid && (time_passed < (int) s->restartDelay))
621 || ((s->procs[proc].pid == 0) && (time_passed < s->initStartDelay)))
623 FCGIDBG6("ignore_job: slot=%d, pid=%ld, time_passed=%ld, initStartDelay=%ld, restartDelay=%ld", proc, (long) s->procs[proc].pid, time_passed, s->initStartDelay, s->restartDelay);
624 return;
627 FCGIDBG3("scheduling_start: %s (%d)", s->fs_path, proc);
628 s->procs[proc].state = FCGI_START_STATE;
629 if (proc == dynamicMaxClassProcs - 1) {
630 ap_log_error(FCGI_LOG_WARN_NOERRNO, fcgi_apache_main_server,
631 "FastCGI: scheduled the %sstart of the last (dynamic) server "
632 "\"%s\" process: reached dynamicMaxClassProcs (%d)",
633 s->procs[proc].pid ? "re" : "", s->fs_path, dynamicMaxClassProcs);
638 *----------------------------------------------------------------------
640 * dynamic_read_msgs
642 * Removes the records written by request handlers and decodes them.
643 * We also update the data structures to reflect the changes.
645 *----------------------------------------------------------------------
648 static void dynamic_read_msgs(int read_ready)
650 fcgi_server *s;
651 int rc;
653 #ifndef WIN32
654 static int buflen = 0;
655 static char buf[FCGI_MSGS_BUFSIZE + 1];
656 char *ptr1, *ptr2, opcode;
657 char execName[FCGI_MAXPATH + 1];
658 char user[MAX_USER_NAME_LEN + 2];
659 char group[MAX_GID_CHAR_LEN + 1];
660 unsigned long q_usec = 0UL, req_usec = 0UL;
661 #else
662 fcgi_pm_job *joblist = NULL;
663 fcgi_pm_job *cjob = NULL;
664 #endif
666 pool *sp = NULL, *tp;
668 #ifndef WIN32
669 user[MAX_USER_NAME_LEN + 1] = group[MAX_GID_CHAR_LEN] = '\0';
670 #endif
673 * To prevent the idle application from running indefinitely, we
674 * check the timer and if it is expired, we recompute the values
675 * for each running application class. Then, when FCGI_REQUEST_COMPLETE_JOB
676 * message is received, only updates are made to the data structures.
678 if (fcgi_dynamic_last_analyzed == 0) {
679 fcgi_dynamic_last_analyzed = now;
681 if ((now - fcgi_dynamic_last_analyzed) >= (int)dynamicUpdateInterval) {
682 for (s = fcgi_servers; s != NULL; s = s->next) {
683 if (s->directive != APP_CLASS_DYNAMIC)
684 break;
686 /* Advance the last analyzed timestamp by the elapsed time since
687 * it was last set. Round the increase down to the nearest
688 * multiple of dynamicUpdateInterval */
690 fcgi_dynamic_last_analyzed += (((long)(now-fcgi_dynamic_last_analyzed)/dynamicUpdateInterval)*dynamicUpdateInterval);
691 s->smoothConnTime = (unsigned long) ((1.0-dynamicGain)*s->smoothConnTime + dynamicGain*s->totalConnTime);
692 s->totalConnTime = 0UL;
693 s->totalQueueTime = 0UL;
697 if (read_ready <= 0) {
698 return;
701 #ifndef WIN32
702 rc = read(fcgi_pm_pipe[0], (void *)(buf + buflen), FCGI_MSGS_BUFSIZE - buflen);
703 if (rc <= 0) {
704 if (!caughtSigTerm) {
705 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
706 "FastCGI: read() from pipe failed (%d)", rc);
707 if (rc == 0) {
708 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
709 "FastCGI: the PM is shutting down, Apache seems to have disappeared - bye");
710 caughtSigTerm = TRUE;
713 return;
715 buflen += rc;
716 buf[buflen] = '\0';
718 #else
720 /* dynamic_read_msgs() is called when a MBOX_EVENT is received (a
721 * request to do something) and/or when a timeout expires.
722 * There really should be no reason why this wait would get stuck
723 * but there's no point in waiting forever. */
725 rc = WaitForSingleObject(fcgi_dynamic_mbox_mutex, FCGI_MBOX_MUTEX_TIMEOUT);
727 if (rc != WAIT_OBJECT_0 && rc != WAIT_ABANDONED)
729 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
730 "FastCGI: failed to aquire the dynamic mbox mutex - something is broke?!");
731 return;
734 joblist = fcgi_dynamic_mbox;
735 fcgi_dynamic_mbox = NULL;
737 if (! ReleaseMutex(fcgi_dynamic_mbox_mutex))
739 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
740 "FastCGI: failed to release the dynamic mbox mutex - something is broke?!");
743 cjob = joblist;
744 #endif
746 tp = ap_make_sub_pool(fcgi_config_pool);
748 #ifndef WIN32
749 for (ptr1 = buf; ptr1; ptr1 = ptr2) {
750 int scan_failed = 0;
752 ptr2 = strchr(ptr1, '*');
753 if (ptr2) {
754 *ptr2++ = '\0';
756 else {
757 break;
760 opcode = *ptr1;
762 switch (opcode)
764 case FCGI_SERVER_START_JOB:
765 case FCGI_SERVER_RESTART_JOB:
767 if (sscanf(ptr1, "%c %s %16s %15s",
768 &opcode, execName, user, group) != 4)
770 scan_failed = 1;
772 break;
774 case FCGI_REQUEST_TIMEOUT_JOB:
776 if (sscanf(ptr1, "%c %s %16s %15s",
777 &opcode, execName, user, group) != 4)
779 scan_failed = 1;
781 break;
783 case FCGI_REQUEST_COMPLETE_JOB:
785 if (sscanf(ptr1, "%c %s %16s %15s %lu %lu",
786 &opcode, execName, user, group, &q_usec, &req_usec) != 6)
788 scan_failed = 1;
790 break;
792 default:
794 scan_failed = 1;
795 break;
798 if (scan_failed) {
799 ap_log_error(FCGI_LOG_ERR_NOERRNO, fcgi_apache_main_server,
800 "FastCGI: bogus message, sscanf() failed: \"%s\"", ptr1);
801 goto NextJob;
803 #else
804 /* Update data structures for processing */
805 while (cjob != NULL) {
806 joblist = cjob->next;
807 FCGIDBG7("read_job: %c %s %s %s %lu %lu", cjob->id, cjob->fs_path, cjob->user, cjob->group, cjob->qsec, cjob->start_time);
808 #endif
810 #ifndef WIN32
811 s = fcgi_util_fs_get(execName, user, group);
812 #else
813 s = fcgi_util_fs_get(cjob->fs_path, cjob->user, cjob->group);
814 #endif
816 #ifndef WIN32
817 if (s==NULL && opcode != FCGI_REQUEST_COMPLETE_JOB)
818 #else
819 if (s==NULL && cjob->id != FCGI_REQUEST_COMPLETE_JOB)
820 #endif
822 #ifdef WIN32
824 HANDLE mutex = CreateMutex(NULL, FALSE, cjob->fs_path);
826 if (mutex == NULL)
828 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
829 "FastCGI: can't create accept mutex "
830 "for (dynamic) server \"%s\"", cjob->fs_path);
831 goto BagNewServer;
834 SetHandleInformation(mutex, HANDLE_FLAG_INHERIT, TRUE);
835 #else
836 const char *err;
837 #endif
839 /* Create a perm subpool to hold the new server data,
840 * we can destroy it if something doesn't pan out */
841 sp = ap_make_sub_pool(fcgi_config_pool);
843 /* Create a new "dynamic" server */
844 s = fcgi_util_fs_new(sp);
846 s->directive = APP_CLASS_DYNAMIC;
847 s->restartDelay = dynamicRestartDelay;
848 s->listenQueueDepth = dynamicListenQueueDepth;
849 s->initStartDelay = dynamicInitStartDelay;
850 s->envp = dynamicEnvp;
851 s->flush = dynamicFlush;
853 #ifdef WIN32
854 s->mutex_env_string = ap_psprintf(sp, "_FCGI_MUTEX_=%ld", mutex);
855 s->fs_path = ap_pstrdup(sp, cjob->fs_path);
856 #else
857 s->fs_path = ap_pstrdup(sp, execName);
858 #endif
859 ap_getparents(s->fs_path);
860 ap_no2slash(s->fs_path);
861 s->procs = fcgi_util_fs_create_procs(sp, dynamicMaxClassProcs);
863 /* XXX the socket_path (both Unix and Win) *is* deducible and
864 * thus can and will be used by other apache instances without
865 * the use of shared data regarding the processes serving the
866 * requests. This can result in slightly unintuitive process
867 * counts and security implications. This is prevented
868 * if suexec (Unix) is in use. This is both a feature and a flaw.
869 * Changing it now would break existing installations. */
871 #ifndef WIN32
872 /* Create socket file's path */
873 s->socket_path = fcgi_util_socket_hash_filename(tp, execName, user, group);
874 s->socket_path = fcgi_util_socket_make_path_absolute(sp, s->socket_path, 1);
876 /* Create sockaddr, prealloc it so it won't get created in tp */
877 s->socket_addr = ap_pcalloc(sp, sizeof(struct sockaddr_un));
878 err = fcgi_util_socket_make_domain_addr(tp, (struct sockaddr_un **)&s->socket_addr,
879 &s->socket_addr_len, s->socket_path);
880 if (err) {
881 ap_log_error(FCGI_LOG_CRIT, fcgi_apache_main_server,
882 "FastCGI: can't create (dynamic) server \"%s\": %s", execName, err);
883 goto BagNewServer;
886 if (init_listen_sock(s)) {
887 goto BagNewServer;
890 /* If a wrapper is being used, config user/group info */
891 if (fcgi_wrapper) {
892 if (user[0] == '~') {
893 /* its a user dir uri, the rest is a username, not a uid */
894 struct passwd *pw = getpwnam(&user[1]);
896 if (!pw) {
897 ap_log_error(FCGI_LOG_CRIT, fcgi_apache_main_server,
898 "FastCGI: can't create (dynamic) server \"%s\": can't get uid/gid for wrapper: getpwnam(%s) failed",
899 execName, &user[1]);
900 goto BagNewServer;
902 s->uid = pw->pw_uid;
903 s->user = ap_pstrdup(sp, user);
904 s->username = s->user;
906 s->gid = pw->pw_gid;
907 s->group = ap_psprintf(sp, "%ld", (long)s->gid);
909 else {
910 struct passwd *pw;
912 s->uid = (uid_t)atol(user);
913 pw = getpwuid(s->uid);
914 if (!pw) {
915 ap_log_error(FCGI_LOG_CRIT, fcgi_apache_main_server,
916 "FastCGI: can't create (dynamic) server \"%s\": can't get uid/gid for wrapper: getwpuid(%ld) failed",
917 execName, (long)s->uid);
918 goto BagNewServer;
920 s->user = ap_pstrdup(sp, user);
921 s->username = ap_pstrdup(sp, pw->pw_name);
923 s->gid = (gid_t)atol(group);
924 s->group = ap_pstrdup(sp, group);
927 #else
928 /* Create socket file's path */
929 s->socket_path = fcgi_util_socket_hash_filename(tp, cjob->fs_path, cjob->user, cjob->group);
930 s->socket_path = fcgi_util_socket_make_path_absolute(sp, s->socket_path, 1);
931 s->listenFd = 0;
932 #endif
934 fcgi_util_fs_add(s);
936 else {
937 #ifndef WIN32
938 if (opcode == FCGI_SERVER_RESTART_JOB) {
939 #else
940 if (cjob->id==FCGI_SERVER_RESTART_JOB) {
941 #endif
942 /* Check to see if the binary has changed. If so,
943 * kill the FCGI application processes, and
944 * restart them.
946 struct stat stbuf;
947 int i;
949 #ifndef WIN32
950 if ((stat(execName, &stbuf)==0) &&
951 #else
952 if ((stat(cjob->fs_path, &stbuf)==0) &&
953 #endif
954 (stbuf.st_mtime > s->restartTime)) {
955 /* kill old server(s) */
956 for (i = 0; i < dynamicMaxClassProcs; i++) {
957 if (s->procs[i].pid > 0) {
958 fcgi_kill(&s->procs[i], SIGTERM);
962 ap_log_error(FCGI_LOG_WARN_NOERRNO, fcgi_apache_main_server,
963 "FastCGI: restarting server \"%s\" processes, newer version found",
964 #ifndef WIN32
965 execName);
966 #else
967 cjob->fs_path);
968 #endif
971 /* If dynamicAutoRestart, don't mark any new processes
972 * for starting because we probably got the
973 * FCGI_SERVER_START_JOB due to dynamicAutoUpdate and the ProcMgr
974 * will be restarting all of those we just killed.
976 if (dynamicAutoRestart)
977 goto NextJob;
979 #ifndef WIN32
980 else if (opcode == FCGI_SERVER_START_JOB) {
981 #else
982 else if (cjob->id==FCGI_SERVER_START_JOB) {
983 #endif
984 /* we've been asked to start a process--only start
985 * it if we're not already running at least one
986 * instance.
988 int i;
990 for (i = 0; i < dynamicMaxClassProcs; i++) {
991 if (s->procs[i].state == FCGI_RUNNING_STATE)
992 break;
994 /* if already running, don't start another one */
995 if (i < dynamicMaxClassProcs) {
996 goto NextJob;
1001 #ifndef WIN32
1002 switch (opcode)
1003 #else
1004 switch (cjob->id)
1005 #endif
1007 int i, start;
1009 case FCGI_SERVER_RESTART_JOB:
1011 start = FALSE;
1013 /* We just waxed 'em all. Try to find an idle slot. */
1015 for (i = 0; i < dynamicMaxClassProcs; ++i)
1017 if (s->procs[i].state == FCGI_START_STATE
1018 || s->procs[i].state == FCGI_RUNNING_STATE)
1020 break;
1022 else if (s->procs[i].state == FCGI_KILLED_STATE
1023 || s->procs[i].state == FCGI_READY_STATE)
1025 start = TRUE;
1026 break;
1030 /* Nope, just use the first slot */
1031 if (i == dynamicMaxClassProcs)
1033 start = TRUE;
1034 i = 0;
1037 if (start)
1039 schedule_start(s, i);
1042 break;
1044 case FCGI_SERVER_START_JOB:
1045 case FCGI_REQUEST_TIMEOUT_JOB:
1047 if ((fcgi_dynamic_total_proc_count + 1) > (int) dynamicMaxProcs) {
1049 * Extra instances should have been
1050 * terminated beforehand, probably need
1051 * to increase ProcessSlack parameter
1053 ap_log_error(FCGI_LOG_WARN_NOERRNO, fcgi_apache_main_server,
1054 "FastCGI: can't schedule the start of another (dynamic) server \"%s\" process: "
1055 "exceeded dynamicMaxProcs (%d)", s->fs_path, dynamicMaxProcs);
1056 goto NextJob;
1059 /* find next free slot */
1060 for (i = 0; i < dynamicMaxClassProcs; i++)
1062 if (s->procs[i].state == FCGI_START_STATE)
1064 FCGIDBG2("ignore_job: slot (%d) is already scheduled for starting", i);
1065 break;
1067 else if (s->procs[i].state == FCGI_RUNNING_STATE)
1069 continue;
1072 schedule_start(s, i);
1073 break;
1076 #ifdef FCGI_DEBUG
1077 if (i >= dynamicMaxClassProcs) {
1078 FCGIDBG1("ignore_job: slots are max'd");
1080 #endif
1081 break;
1082 case FCGI_REQUEST_COMPLETE_JOB:
1083 /* only record stats if we have a structure */
1084 if (s) {
1085 #ifndef WIN32
1086 s->totalConnTime += req_usec;
1087 s->totalQueueTime += q_usec;
1088 #else
1089 s->totalConnTime += cjob->start_time;
1090 s->totalQueueTime += cjob->qsec;
1091 #endif
1093 break;
1096 NextJob:
1098 #ifdef WIN32
1099 /* Cleanup job data */
1100 free(cjob->fs_path);
1101 free(cjob->user);
1102 free(cjob->group);
1103 free(cjob);
1104 cjob = joblist;
1105 #endif
1107 continue;
1109 BagNewServer:
1110 if (sp) ap_destroy_pool(sp);
1112 #ifdef WIN32
1113 free(cjob->fs_path);
1114 free(cjob);
1115 cjob = joblist;
1116 #endif
1119 #ifndef WIN32
1120 if (ptr1 == buf) {
1121 ap_log_error(FCGI_LOG_ERR_NOERRNO, fcgi_apache_main_server,
1122 "FastCGI: really bogus message: \"%s\"", ptr1);
1123 ptr1 += strlen(buf);
1126 buflen -= ptr1 - buf;
1127 if (buflen) {
1128 memmove(buf, ptr1, buflen);
1130 #endif
1132 ap_destroy_pool(tp);
1136 *----------------------------------------------------------------------
1138 * dynamic_kill_idle_fs_procs
1140 * Implement a kill policy for the dynamic FastCGI applications.
1141 * We also update the data structures to reflect the changes.
1143 * Side effects:
1144 * Processes are marked for deletion possibly killed.
1146 *----------------------------------------------------------------------
1148 static void dynamic_kill_idle_fs_procs(void)
1150 fcgi_server *s;
1151 int victims = 0;
1153 for (s = fcgi_servers; s != NULL; s = s->next)
1156 * server's smoothed running time, or if that's 0, the current total
1158 unsigned long connTime;
1161 * maximum number of microseconds that all of a server's running
1162 * processes together could have spent running since the last check
1164 unsigned long totalTime;
1167 * percentage, 0-100, of totalTime that the processes actually used
1169 int loadFactor;
1171 int i;
1172 int really_running = 0;
1174 if (s->directive != APP_CLASS_DYNAMIC || s->numProcesses == 0)
1176 continue;
1179 /* s->numProcesses includes pending kills so get the "active" count */
1180 for (i = 0; i < dynamicMaxClassProcs; ++i)
1182 if (s->procs[i].state == FCGI_RUNNING_STATE) ++really_running;
1185 connTime = s->smoothConnTime ? s->smoothConnTime : s->totalConnTime;
1186 totalTime = really_running * (now - fcgi_dynamic_epoch) * 1000000 + 1;
1188 loadFactor = 100 * connTime / totalTime;
1190 if (really_running == 1)
1192 if (loadFactor >= dynamicThreshold1)
1194 continue;
1197 else
1199 int load = really_running / ( really_running - 1) * loadFactor;
1201 if (load >= dynamicThresholdN)
1203 continue;
1208 * Run through the procs to see if we can get away w/o waxing one.
1210 for (i = 0; i < dynamicMaxClassProcs; ++i)
1212 if (s->procs[i].state == FCGI_START_STATE)
1214 s->procs[i].state = FCGI_READY_STATE;
1215 break;
1217 else if (s->procs[i].state == FCGI_VICTIM_STATE)
1219 break;
1223 if (i >= dynamicMaxClassProcs)
1225 ServerProcess * procs = s->procs;
1226 int youngest = -1;
1228 for (i = 0; i < dynamicMaxClassProcs; ++i)
1230 if (procs[i].state == FCGI_RUNNING_STATE)
1232 if (youngest == -1 || procs[i].start_time >= procs[youngest].start_time)
1234 youngest = i;
1239 if (youngest != -1)
1241 ap_log_error(FCGI_LOG_WARN_NOERRNO, fcgi_apache_main_server,
1242 "FastCGI: (dynamic) server \"%s\" (pid %ld) termination signaled",
1243 s->fs_path, (long) s->procs[youngest].pid);
1245 fcgi_kill(&s->procs[youngest], SIGTERM);
1247 victims++;
1251 * If the number of non-victims is less than or equal to
1252 * the minimum that may be running without being killed off,
1253 * don't select any more victims.
1255 if (fcgi_dynamic_total_proc_count - victims <= dynamicMinProcs)
1257 break;
1263 #ifdef WIN32
1265 // This is a little bogus, there's gotta be a better way to do this
1266 // Can we use WaitForMultipleObjects()
1267 #define FCGI_PROC_WAIT_TIME 100
1269 void child_wait_thread_main(void *dummy) {
1270 fcgi_server *s;
1271 DWORD dwRet = WAIT_TIMEOUT;
1272 int numChildren;
1273 int i;
1274 int waited;
1276 while (!bTimeToDie) {
1277 waited = 0;
1279 for (s = fcgi_servers; s != NULL; s = s->next) {
1280 if (s->directive == APP_CLASS_EXTERNAL || s->listenFd < 0) {
1281 continue;
1283 if (s->directive == APP_CLASS_DYNAMIC) {
1284 numChildren = dynamicMaxClassProcs;
1286 else {
1287 numChildren = s->numProcesses;
1290 for (i=0; i < numChildren; i++) {
1291 if (s->procs[i].handle != INVALID_HANDLE_VALUE)
1293 DWORD exitStatus = 0;
1295 /* timeout is currently set for 100 miliecond */
1296 /* it may need to be longer or user customizable */
1297 dwRet = WaitForSingleObject(s->procs[i].handle, FCGI_PROC_WAIT_TIME);
1299 waited = 1;
1301 if (dwRet != WAIT_TIMEOUT && dwRet != WAIT_FAILED) {
1302 /* a child fs has died */
1303 /* mark the child as dead */
1305 if (s->directive == APP_CLASS_STANDARD) {
1306 /* restart static app */
1307 s->procs[i].state = FCGI_START_STATE;
1308 s->numFailures++;
1310 else {
1311 s->numProcesses--;
1312 fcgi_dynamic_total_proc_count--;
1313 FCGIDBG2("-- fcgi_dynamic_total_proc_count=%d", fcgi_dynamic_total_proc_count);
1315 if (s->procs[i].state == FCGI_VICTIM_STATE) {
1316 s->procs[i].state = FCGI_KILLED_STATE;
1318 else {
1319 /* dynamic app shouldn't have died or dynamicAutoUpdate killed it*/
1320 s->numFailures++;
1322 if (dynamicAutoRestart || (s->numProcesses <= 0 && dynamicThreshold1 == 0)) {
1323 s->procs[i].state = FCGI_START_STATE;
1325 else {
1326 s->procs[i].state = FCGI_READY_STATE;
1331 GetExitCodeProcess(s->procs[i].handle, &exitStatus);
1333 ap_log_error(FCGI_LOG_WARN_NOERRNO, fcgi_apache_main_server,
1334 "FastCGI:%s server \"%s\" (pid %d) terminated with exit with status '%d'",
1335 (s->directive == APP_CLASS_DYNAMIC) ? " (dynamic)" : "",
1336 s->fs_path, (long) s->procs[i].pid, exitStatus);
1338 CloseHandle(s->procs[i].handle);
1339 s->procs[i].handle = INVALID_HANDLE_VALUE;
1340 s->procs[i].pid = -1;
1342 /* wake up the main thread */
1343 SetEvent(fcgi_event_handles[WAKE_EVENT]);
1348 Sleep(waited ? 0 : FCGI_PROC_WAIT_TIME);
1351 #endif
1353 #ifndef WIN32
1354 static void setup_signals(void)
1356 struct sigaction sa;
1358 /* Setup handlers */
1360 sa.sa_handler = signal_handler;
1361 sigemptyset(&sa.sa_mask);
1362 sa.sa_flags = 0;
1364 if (sigaction(SIGTERM, &sa, NULL) < 0) {
1365 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
1366 "sigaction(SIGTERM) failed");
1368 /* httpd restart */
1369 if (sigaction(SIGHUP, &sa, NULL) < 0) {
1370 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
1371 "sigaction(SIGHUP) failed");
1373 /* httpd graceful restart */
1374 if (sigaction(SIGUSR1, &sa, NULL) < 0) {
1375 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
1376 "sigaction(SIGUSR1) failed");
1378 /* read messages from request handlers - kill interval expired */
1379 if (sigaction(SIGALRM, &sa, NULL) < 0) {
1380 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
1381 "sigaction(SIGALRM) failed");
1383 if (sigaction(SIGCHLD, &sa, NULL) < 0) {
1384 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
1385 "sigaction(SIGCHLD) failed");
1388 #endif
1390 #ifndef WIN32
1391 int fcgi_pm_main(void *dummy, child_info *info)
1392 #else
1393 void fcgi_pm_main(void *dummy)
1394 #endif
1396 fcgi_server *s;
1397 unsigned int i;
1398 int read_ready = 0;
1399 int alarmLeft = 0;
1401 #ifdef WIN32
1402 DWORD dwRet;
1403 HANDLE child_wait_thread = INVALID_HANDLE_VALUE;
1404 #else
1405 int callWaitPid, callDynamicProcs;
1406 #endif
1408 #ifdef WIN32
1409 // Add SystemRoot to the dynamic environment
1410 char ** envp = dynamicEnvp;
1411 for (i = 0; *envp; ++i) {
1412 ++envp;
1414 fcgi_config_set_env_var(fcgi_config_pool, dynamicEnvp, &i, "SystemRoot");
1416 #else
1417 reduce_privileges();
1419 close(fcgi_pm_pipe[1]);
1420 change_process_name("fcgi-pm");
1421 setup_signals();
1423 if (fcgi_wrapper) {
1424 ap_log_error(FCGI_LOG_NOTICE_NOERRNO, fcgi_apache_main_server,
1425 "FastCGI: wrapper mechanism enabled (wrapper: %s)", fcgi_wrapper);
1427 #endif
1429 /* Initialize AppClass */
1430 for (s = fcgi_servers; s != NULL; s = s->next)
1432 if (s->directive != APP_CLASS_STANDARD)
1433 continue;
1435 #ifdef WIN32
1436 if (s->socket_path)
1437 s->listenFd = 0;
1438 #endif
1440 for (i = 0; i < s->numProcesses; ++i)
1441 s->procs[i].state = FCGI_START_STATE;
1444 #ifdef WIN32
1445 child_wait_thread = (HANDLE) _beginthread(child_wait_thread_main, 0, NULL);
1447 if (child_wait_thread == (HANDLE) -1)
1449 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
1450 "FastCGI: failed to create process manager's wait thread!");
1453 ap_log_error(FCGI_LOG_NOTICE_NOERRNO, fcgi_apache_main_server,
1454 "FastCGI: process manager initialized");
1455 #else
1456 ap_log_error(FCGI_LOG_NOTICE_NOERRNO, fcgi_apache_main_server,
1457 "FastCGI: process manager initialized (pid %ld)", (long) getpid());
1458 #endif
1460 now = time(NULL);
1463 * Loop until SIGTERM
1465 for (;;) {
1466 int sleepSeconds = min(dynamicKillInterval, dynamicUpdateInterval);
1467 #ifdef WIN32
1468 time_t expire;
1469 #else
1470 pid_t childPid;
1471 int waitStatus;
1472 #endif
1473 unsigned int numChildren;
1476 * If we came out of sigsuspend() for any reason other than
1477 * SIGALRM, pick up where we left off.
1479 if (alarmLeft)
1480 sleepSeconds = alarmLeft;
1483 * Examine each configured AppClass for a process that needs
1484 * starting. Compute the earliest time when the start should
1485 * be attempted, starting it now if the time has passed. Also,
1486 * remember that we do NOT need to restart externally managed
1487 * FastCGI applications.
1489 for (s = fcgi_servers; s != NULL; s = s->next)
1491 if (s->directive == APP_CLASS_EXTERNAL)
1492 continue;
1494 numChildren = (s->directive == APP_CLASS_DYNAMIC)
1495 ? dynamicMaxClassProcs
1496 : s->numProcesses;
1498 for (i = 0; i < numChildren; ++i)
1500 if (s->procs[i].pid <= 0 && s->procs[i].state == FCGI_START_STATE)
1502 int restart = (s->procs[i].pid < 0);
1503 time_t restartTime = s->restartTime;
1505 restartTime += (restart) ? s->restartDelay : s->initStartDelay;
1507 if (restartTime <= now)
1509 if (s->listenFd < 0 && init_listen_sock(s))
1511 if (sleepSeconds > s->initStartDelay)
1512 sleepSeconds = s->initStartDelay;
1513 break;
1515 #ifndef WIN32
1516 if (caughtSigTerm) {
1517 goto ProcessSigTerm;
1519 #endif
1520 s->procs[i].pid = spawn_fs_process(s, &s->procs[i]);
1521 if (s->procs[i].pid <= 0) {
1522 ap_log_error(FCGI_LOG_CRIT, fcgi_apache_main_server,
1523 "FastCGI: can't start%s server \"%s\": spawn_fs_process() failed",
1524 (s->directive == APP_CLASS_DYNAMIC) ? " (dynamic)" : "",
1525 s->fs_path);
1527 sleepSeconds = min(sleepSeconds,
1528 max((int) s->restartDelay, FCGI_MIN_EXEC_RETRY_DELAY));
1530 ap_assert(s->procs[i].pid < 0);
1531 break;
1534 s->procs[i].start_time = now;
1535 s->restartTime = now;
1537 if (s->directive == APP_CLASS_DYNAMIC) {
1538 s->numProcesses++;
1539 fcgi_dynamic_total_proc_count++;
1540 FCGIDBG2("++ fcgi_dynamic_total_proc_count=%d", fcgi_dynamic_total_proc_count);
1543 s->procs[i].state = FCGI_RUNNING_STATE;
1545 if (restart)
1546 s->numRestarts++;
1548 if (fcgi_wrapper) {
1549 ap_log_error(FCGI_LOG_WARN_NOERRNO, fcgi_apache_main_server,
1550 "FastCGI:%s server \"%s\" (uid %ld, gid %ld) %sstarted (pid %ld)",
1551 (s->directive == APP_CLASS_DYNAMIC) ? " (dynamic)" : "",
1552 s->fs_path, (long) s->uid, (long) s->gid,
1553 restart ? "re" : "", (long) s->procs[i].pid);
1555 else {
1556 ap_log_error(FCGI_LOG_WARN_NOERRNO, fcgi_apache_main_server,
1557 "FastCGI:%s server \"%s\" %sstarted (pid %ld)",
1558 (s->directive == APP_CLASS_DYNAMIC) ? " (dynamic)" : "",
1559 s->fs_path, restart ? "re" : "", (long) s->procs[i].pid);
1561 ap_assert(s->procs[i].pid > 0);
1562 } else {
1563 sleepSeconds = min(sleepSeconds, restartTime - now);
1569 #ifndef WIN32
1571 if(caughtSigTerm) {
1572 goto ProcessSigTerm;
1574 if((!caughtSigChld) && (!caughtSigAlarm)) {
1575 fd_set rfds;
1577 alarm(sleepSeconds);
1579 FD_ZERO(&rfds);
1580 FD_SET(fcgi_pm_pipe[0], &rfds);
1581 read_ready = ap_select(fcgi_pm_pipe[0] + 1, &rfds, NULL, NULL, NULL);
1583 alarmLeft = alarm(0);
1585 callWaitPid = caughtSigChld;
1586 caughtSigChld = FALSE;
1587 callDynamicProcs = caughtSigAlarm;
1588 caughtSigAlarm = FALSE;
1590 now = time(NULL);
1593 * Dynamic fcgi process management
1595 if((callDynamicProcs) || (!callWaitPid)) {
1596 dynamic_read_msgs(read_ready);
1597 if(fcgi_dynamic_epoch == 0) {
1598 fcgi_dynamic_epoch = now;
1600 if(((long)(now-fcgi_dynamic_epoch)>=dynamicKillInterval) ||
1601 ((fcgi_dynamic_total_proc_count+dynamicProcessSlack)>=dynamicMaxProcs)) {
1602 dynamic_kill_idle_fs_procs();
1603 fcgi_dynamic_epoch = now;
1607 if(!callWaitPid) {
1608 continue;
1611 /* We've caught SIGCHLD, so find out who it was using waitpid,
1612 * write a log message and update its data structure. */
1614 for (;;) {
1615 if (caughtSigTerm)
1616 goto ProcessSigTerm;
1618 childPid = waitpid(-1, &waitStatus, WNOHANG);
1620 if (childPid == -1 || childPid == 0)
1621 break;
1623 for (s = fcgi_servers; s != NULL; s = s->next) {
1624 if (s->directive == APP_CLASS_EXTERNAL)
1625 continue;
1627 if (s->directive == APP_CLASS_DYNAMIC)
1628 numChildren = dynamicMaxClassProcs;
1629 else
1630 numChildren = s->numProcesses;
1632 for (i = 0; i < numChildren; i++) {
1633 if (s->procs[i].pid == childPid)
1634 goto ChildFound;
1638 /* TODO: print something about this unknown child */
1639 continue;
1641 ChildFound:
1642 s->procs[i].pid = -1;
1644 if (s->directive == APP_CLASS_STANDARD) {
1645 /* Always restart static apps */
1646 s->procs[i].state = FCGI_START_STATE;
1647 s->numFailures++;
1649 else {
1650 s->numProcesses--;
1651 fcgi_dynamic_total_proc_count--;
1653 if (s->procs[i].state == FCGI_VICTIM_STATE) {
1654 s->procs[i].state = FCGI_KILLED_STATE;
1656 else {
1657 /* A dynamic app died or exited without provocation from the PM */
1658 s->numFailures++;
1660 if (dynamicAutoRestart || (s->numProcesses <= 0 && dynamicThreshold1 == 0))
1661 s->procs[i].state = FCGI_START_STATE;
1662 else
1663 s->procs[i].state = FCGI_READY_STATE;
1667 if (WIFEXITED(waitStatus)) {
1668 ap_log_error(FCGI_LOG_WARN_NOERRNO, fcgi_apache_main_server,
1669 "FastCGI:%s server \"%s\" (pid %ld) terminated by calling exit with status '%d'",
1670 (s->directive == APP_CLASS_DYNAMIC) ? " (dynamic)" : "",
1671 s->fs_path, (long) childPid, WEXITSTATUS(waitStatus));
1673 else if (WIFSIGNALED(waitStatus)) {
1674 ap_log_error(FCGI_LOG_WARN_NOERRNO, fcgi_apache_main_server,
1675 "FastCGI:%s server \"%s\" (pid %ld) terminated due to uncaught signal '%d' (%s)%s",
1676 (s->directive == APP_CLASS_DYNAMIC) ? " (dynamic)" : "",
1677 s->fs_path, (long) childPid, WTERMSIG(waitStatus), SYS_SIGLIST[WTERMSIG(waitStatus)],
1678 #ifdef WCOREDUMP
1679 WCOREDUMP(waitStatus) ? ", a core file may have been generated" : "");
1680 #else
1681 "");
1682 #endif
1684 else if (WIFSTOPPED(waitStatus)) {
1685 ap_log_error(FCGI_LOG_WARN_NOERRNO, fcgi_apache_main_server,
1686 "FastCGI:%s server \"%s\" (pid %ld) stopped due to uncaught signal '%d' (%s)",
1687 (s->directive == APP_CLASS_DYNAMIC) ? " (dynamic)" : "",
1688 s->fs_path, (long) childPid, WTERMSIG(waitStatus), SYS_SIGLIST[WTERMSIG(waitStatus)]);
1690 } /* for (;;), waitpid() */
1692 #else /* WIN32 */
1694 /* wait for an event to occur or timer expires */
1695 expire = time(NULL) + sleepSeconds;
1696 dwRet = WaitForMultipleObjects(3, (HANDLE *) fcgi_event_handles, FALSE, sleepSeconds * 1000);
1698 if (dwRet == WAIT_FAILED) {
1699 /* There is something seriously wrong here */
1700 ap_log_error(FCGI_LOG_CRIT, fcgi_apache_main_server,
1701 "FastCGI: WaitForMultipleObjects() failed on event handles -- pm is shuting down");
1702 bTimeToDie = TRUE;
1705 if (dwRet != WAIT_TIMEOUT) {
1706 now = time(NULL);
1708 if (now < expire)
1709 alarmLeft = expire - now;
1713 * Dynamic fcgi process management
1715 if ((dwRet == MBOX_EVENT) || (dwRet == WAIT_TIMEOUT)) {
1716 if (dwRet == MBOX_EVENT) {
1717 read_ready = 1;
1720 now = time(NULL);
1722 dynamic_read_msgs(read_ready);
1724 if(fcgi_dynamic_epoch == 0) {
1725 fcgi_dynamic_epoch = now;
1728 if ((now-fcgi_dynamic_epoch >= (int) dynamicKillInterval) ||
1729 ((fcgi_dynamic_total_proc_count+dynamicProcessSlack) >= dynamicMaxProcs)) {
1730 dynamic_kill_idle_fs_procs();
1731 fcgi_dynamic_epoch = now;
1733 read_ready = 0;
1735 else if (dwRet == WAKE_EVENT) {
1736 continue;
1738 else if (dwRet == TERM_EVENT) {
1739 ap_log_error(FCGI_LOG_INFO_NOERRNO, fcgi_apache_main_server,
1740 "FastCGI: Termination event received process manager shutting down");
1742 bTimeToDie = TRUE;
1743 dwRet = WaitForSingleObject(child_wait_thread, INFINITE);
1745 goto ProcessSigTerm;
1747 else {
1748 // Have an received an unknown event - should not happen
1749 ap_log_error(FCGI_LOG_CRIT, fcgi_apache_main_server,
1750 "FastCGI: WaitForMultipleobjects() return an unrecognized event");
1752 bTimeToDie = TRUE;
1753 dwRet = WaitForSingleObject(child_wait_thread, INFINITE);
1755 goto ProcessSigTerm;
1758 #endif /* WIN32 */
1760 } /* for (;;), the whole shoot'n match */
1762 ProcessSigTerm:
1764 * Kill off the children, then exit.
1766 shutdown_all();
1768 #ifdef WIN32
1769 return;
1770 #else
1771 exit(0);
1772 #endif
1775 #ifdef WIN32
1776 int fcgi_pm_add_job(fcgi_pm_job *new_job)
1778 int rv = WaitForSingleObject(fcgi_dynamic_mbox_mutex, FCGI_MBOX_MUTEX_TIMEOUT);
1780 if (rv != WAIT_OBJECT_0 && rv != WAIT_ABANDONED)
1782 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
1783 "FastCGI: failed to aquire the dynamic mbox mutex - something is broke?!");
1784 return -1;
1787 new_job->next = fcgi_dynamic_mbox;
1788 fcgi_dynamic_mbox = new_job;
1790 if (! ReleaseMutex(fcgi_dynamic_mbox_mutex))
1792 ap_log_error(FCGI_LOG_ALERT, fcgi_apache_main_server,
1793 "FastCGI: failed to release the dynamic mbox mutex - something is broke?!");
1796 return 0;
1798 #endif