Remove the RCSID macro
[openafs.git] / src / bozo / bnode.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #include <afsconfig.h>
11 #include <afs/param.h>
12
13
14 #include <stddef.h>
15 #include <stdlib.h>
16 #include <stdio.h>
17 #include <dirent.h>
18 #include <errno.h>
19 #include <sys/types.h>
20 #ifdef AFS_NT40_ENV
21 #include <io.h>
22 #else
23 #include <sys/file.h>
24 #include <sys/time.h>
25 #endif
26 #ifdef BOZO_SAVE_CORES
27 #include <time.h>
28 #endif
29 #include <sys/stat.h>
30 #include <string.h>
31
32 #include <afs/procmgmt.h>       /* signal(), kill(), wait(), etc. */
33 #include <lwp.h>
34 #include <rx/rx.h>
35 #include <afs/audit.h>
36 #include <afs/afsutil.h>
37 #include <afs/fileutil.h>
38 #include "bnode.h"
39 #include "bosprototypes.h"
40
41 #if defined(AFS_AIX_ENV) || defined(AFS_SUN4_ENV)
42 /* All known versions of AIX lack WCOREDUMP but this works */
43 #define WCOREDUMP(x) ((x) & 0x80)
44 #endif
45
46 #define BNODE_LWP_STACKSIZE     (16 * 1024)
47
48 int bnode_waiting = 0;
49 static PROCESS bproc_pid;       /* pid of waker-upper */
50 static struct bnode *allBnodes = 0;     /* list of all bnodes */
51 static struct bnode_proc *allProcs = 0; /* list of all processes for which we're waiting */
52 static struct bnode_type *allTypes = 0; /* list of registered type handlers */
53
54 static struct bnode_stats {
55     int weirdPids;
56 } bnode_stats;
57
58 #ifndef AFS_NT40_ENV
59 extern char **environ;          /* env structure */
60 #endif
61
62 int hdl_notifier(struct bnode_proc *tp);
63
64 /* Remember the name of the process, if any, that failed last */
65 static void
66 RememberProcName(register struct bnode_proc *ap)
67 {
68     register struct bnode *tbnodep;
69
70     tbnodep = ap->bnode;
71     if (tbnodep->lastErrorName) {
72         free(tbnodep->lastErrorName);
73         tbnodep->lastErrorName = NULL;
74     }
75     if (ap->coreName) {
76         tbnodep->lastErrorName = (char *)malloc(strlen(ap->coreName) + 1);
77         strcpy(tbnodep->lastErrorName, ap->coreName);
78     }
79 }
80
81 /* utility for use by BOP_HASCORE functions to determine where a core file might
82  * be stored.
83  */
84 int
85 bnode_CoreName(register struct bnode *abnode, char *acoreName, char *abuffer)
86 {
87     strcpy(abuffer, AFSDIR_SERVER_CORELOG_FILEPATH);
88     if (acoreName) {
89         strcat(abuffer, acoreName);
90         strcat(abuffer, ".");
91     }
92     strcat(abuffer, abnode->name);
93     return 0;
94 }
95
96 /* save core file, if any */
97 static void
98 SaveCore(register struct bnode *abnode, register struct bnode_proc
99          *aproc)
100 {
101     char tbuffer[256];
102     struct stat tstat;
103     register afs_int32 code;
104     char *corefile = NULL;
105 #ifdef BOZO_SAVE_CORES
106     struct timeval Start;
107     struct tm *TimeFields;
108     char FileName[256];
109 #endif
110
111     /* Linux always appends the PID to core dumps from threaded processes, so
112      * we have to scan the directory to find core files under another name. */
113     code = stat(AFSDIR_SERVER_CORELOG_FILEPATH, &tstat);
114     if (code) {
115         DIR *logdir;
116         struct dirent *file;
117         size_t length;
118         unsigned long pid;
119
120         logdir = opendir(AFSDIR_LOGS_DIR);
121         if (logdir == NULL)
122             return;
123         while ((file = readdir(logdir)) != NULL) {
124             if (strncmp(file->d_name, "core.", 5) != 0)
125                 continue;
126             pid = atol(file->d_name + 5);
127             if (pid == aproc->pid) {
128                 length = strlen(AFSDIR_LOGS_DIR) + strlen(file->d_name) + 2;
129                 corefile = malloc(length);
130                 if (corefile == NULL) {
131                     closedir(logdir);
132                     return;
133                 }
134                 snprintf(corefile, length, "%s/%s", AFSDIR_LOGS_DIR,
135                          file->d_name);
136                 code = 0;
137                 break;
138             }
139         }
140         closedir(logdir);
141     }
142     if (code)
143         return;
144
145     bnode_CoreName(abnode, aproc->coreName, tbuffer);
146 #ifdef BOZO_SAVE_CORES
147     FT_GetTimeOfDay(&Start, 0);
148     TimeFields = localtime(&Start.tv_sec);
149     sprintf(FileName, "%s.%d%02d%02d%02d%02d%02d", tbuffer,
150             TimeFields->tm_year + 1900, TimeFields->tm_mon + 1, TimeFields->tm_mday,
151             TimeFields->tm_hour, TimeFields->tm_min, TimeFields->tm_sec);
152     strcpy(tbuffer, FileName);
153 #endif
154     if (corefile == NULL)
155         code = renamefile(AFSDIR_SERVER_CORELOG_FILEPATH, tbuffer);
156     else {
157         code = renamefile(corefile, tbuffer);
158         free(corefile);
159     }
160 }
161
162 int
163 bnode_GetString(register struct bnode *abnode, register char *abuffer,
164                 register afs_int32 alen)
165 {
166     return BOP_GETSTRING(abnode, abuffer, alen);
167 }
168
169 int
170 bnode_GetParm(register struct bnode *abnode, register afs_int32 aindex,
171               register char *abuffer, afs_int32 alen)
172 {
173     return BOP_GETPARM(abnode, aindex, abuffer, alen);
174 }
175
176 int
177 bnode_GetStat(register struct bnode *abnode, register afs_int32 * astatus)
178 {
179     return BOP_GETSTAT(abnode, astatus);
180 }
181
182 int
183 bnode_RestartP(register struct bnode *abnode)
184 {
185     return BOP_RESTARTP(abnode);
186 }
187
188 static int
189 bnode_Check(register struct bnode *abnode)
190 {
191     if (abnode->flags & BNODE_WAIT) {
192         abnode->flags &= ~BNODE_WAIT;
193         LWP_NoYieldSignal(abnode);
194     }
195     return 0;
196 }
197
198 /* tell if an instance has a core file */
199 int
200 bnode_HasCore(register struct bnode *abnode)
201 {
202     return BOP_HASCORE(abnode);
203 }
204
205 /* wait for all bnodes to stabilize */
206 int
207 bnode_WaitAll(void)
208 {
209     register struct bnode *tb;
210     register afs_int32 code;
211     afs_int32 stat;
212
213   retry:
214     for (tb = allBnodes; tb; tb = tb->next) {
215         bnode_Hold(tb);
216         code = BOP_GETSTAT(tb, &stat);
217         if (code) {
218             bnode_Release(tb);
219             return code;
220         }
221         if (stat != tb->goal) {
222             tb->flags |= BNODE_WAIT;
223             LWP_WaitProcess(tb);
224             bnode_Release(tb);
225             goto retry;
226         }
227         bnode_Release(tb);
228     }
229     return 0;
230 }
231
232 /* wait until bnode status is correct */
233 int
234 bnode_WaitStatus(register struct bnode *abnode, int astatus)
235 {
236     register afs_int32 code;
237     afs_int32 stat;
238
239     bnode_Hold(abnode);
240     while (1) {
241         /* get the status */
242         code = BOP_GETSTAT(abnode, &stat);
243         if (code)
244             return code;
245
246         /* otherwise, check if we're done */
247         if (stat == astatus) {
248             bnode_Release(abnode);
249             return 0;           /* done */
250         }
251         if (astatus != abnode->goal) {
252             bnode_Release(abnode);
253             return -1;          /* no longer our goal, don't keep waiting */
254         }
255         /* otherwise, block */
256         abnode->flags |= BNODE_WAIT;
257         LWP_WaitProcess(abnode);
258     }
259 }
260
261 int
262 bnode_SetStat(register struct bnode *abnode, register int agoal)
263 {
264     abnode->goal = agoal;
265     bnode_Check(abnode);
266     BOP_SETSTAT(abnode, agoal);
267     abnode->flags &= ~BNODE_ERRORSTOP;
268     return 0;
269 }
270
271 int
272 bnode_SetGoal(register struct bnode *abnode, register int agoal)
273 {
274     abnode->goal = agoal;
275     bnode_Check(abnode);
276     return 0;
277 }
278
279 int
280 bnode_SetFileGoal(register struct bnode *abnode, register int agoal)
281 {
282     if (abnode->fileGoal == agoal)
283         return 0;               /* already done */
284     abnode->fileGoal = agoal;
285     WriteBozoFile(0);
286     return 0;
287 }
288
289 /* apply a function to all bnodes in the system */
290 int
291 bnode_ApplyInstance(int (*aproc) (struct bnode *tb, void *), void *arock)
292 {
293     register struct bnode *tb, *nb;
294     register afs_int32 code;
295
296     for (tb = allBnodes; tb; tb = nb) {
297         nb = tb->next;
298         code = (*aproc) (tb, arock);
299         if (code)
300             return code;
301     }
302     return 0;
303 }
304
305 struct bnode *
306 bnode_FindInstance(register char *aname)
307 {
308     register struct bnode *tb;
309
310     for (tb = allBnodes; tb; tb = tb->next) {
311         if (!strcmp(tb->name, aname))
312             return tb;
313     }
314     return NULL;
315 }
316
317 static struct bnode_type *
318 FindType(register char *aname)
319 {
320     register struct bnode_type *tt;
321
322     for (tt = allTypes; tt; tt = tt->next) {
323         if (!strcmp(tt->name, aname))
324             return tt;
325     }
326     return (struct bnode_type *)0;
327 }
328
329 int
330 bnode_Register(char *atype, struct bnode_ops *aprocs, int anparms)
331 {
332     register struct bnode_type *tt;
333
334     for (tt = allTypes; tt; tt = tt->next) {
335         if (!strcmp(tt->name, atype))
336             break;
337     }
338     if (!tt) {
339         tt = (struct bnode_type *)malloc(sizeof(struct bnode_type));
340         memset(tt, 0, sizeof(struct bnode_type));
341         tt->next = allTypes;
342         allTypes = tt;
343         tt->name = atype;
344     }
345     tt->ops = aprocs;
346     return 0;
347 }
348
349 afs_int32
350 bnode_Create(char *atype, char *ainstance, struct bnode ** abp, char *ap1,
351              char *ap2, char *ap3, char *ap4, char *ap5, char *notifier,
352              int fileGoal, int rewritefile)
353 {
354     struct bnode_type *type;
355     struct bnode *tb;
356     char *notifierpath = NULL;
357     struct stat tstat;
358
359     if (bnode_FindInstance(ainstance))
360         return BZEXISTS;
361     type = FindType(atype);
362     if (!type)
363         return BZBADTYPE;
364
365     if (notifier && strcmp(notifier, NONOTIFIER)) {
366         /* construct local path from canonical (wire-format) path */
367         if (ConstructLocalBinPath(notifier, &notifierpath)) {
368             bozo_Log("BNODE-Create: Notifier program path invalid '%s'\n",
369                      notifier);
370             return BZNOCREATE;
371         }
372
373         if (stat(notifierpath, &tstat)) {
374             bozo_Log("BNODE-Create: Notifier program '%s' not found\n",
375                      notifierpath);
376             free(notifierpath);
377             return BZNOCREATE;
378         }
379     }
380     tb = (*type->ops->create) (ainstance, ap1, ap2, ap3, ap4, ap5);
381     if (!tb) {
382         free(notifierpath);
383         return BZNOCREATE;
384     }
385     tb->notifier = notifierpath;
386     *abp = tb;
387     tb->type = type;
388
389     /* The fs_create above calls bnode_InitBnode() which always sets the 
390      ** fileGoal to BSTAT_NORMAL .... overwrite it with whatever is passed into
391      ** this function as a parameter... */
392     tb->fileGoal = fileGoal;
393
394     bnode_SetStat(tb, tb->goal);        /* nudge it once */
395
396     if (rewritefile != 0)
397         WriteBozoFile(0);
398
399     return 0;
400 }
401
402 int
403 bnode_DeleteName(char *ainstance)
404 {
405     register struct bnode *tb;
406
407     tb = bnode_FindInstance(ainstance);
408     if (!tb)
409         return BZNOENT;
410
411     return bnode_Delete(tb);
412 }
413
414 int
415 bnode_Hold(register struct bnode *abnode)
416 {
417     abnode->refCount++;
418     return 0;
419 }
420
421 int
422 bnode_Release(register struct bnode *abnode)
423 {
424     abnode->refCount--;
425     if (abnode->refCount == 0 && abnode->flags & BNODE_DELETE) {
426         abnode->flags &= ~BNODE_DELETE; /* we're going for it */
427         bnode_Delete(abnode);
428     }
429     return 0;
430 }
431
432 int
433 bnode_Delete(register struct bnode *abnode)
434 {
435     register afs_int32 code;
436     register struct bnode **lb, *ub;
437     afs_int32 temp;
438
439     if (abnode->refCount != 0) {
440         abnode->flags |= BNODE_DELETE;
441         return 0;
442     }
443
444     /* make sure the bnode is idle before zapping */
445     bnode_Hold(abnode);
446     code = BOP_GETSTAT(abnode, &temp);
447     bnode_Release(abnode);
448     if (code)
449         return code;
450     if (temp != BSTAT_SHUTDOWN)
451         return BZBUSY;
452
453     /* all clear to zap */
454     for (lb = &allBnodes, ub = *lb; ub; lb = &ub->next, ub = *lb) {
455         if (ub == abnode) {
456             /* unthread it from the list */
457             *lb = ub->next;
458             break;
459         }
460     }
461     free(abnode->name);         /* do this first, since bnode fields may be bad after BOP_DELETE */
462     code = BOP_DELETE(abnode);  /* don't play games like holding over this one */
463     WriteBozoFile(0);
464     return code;
465 }
466
467 /* function to tell if there's a timeout coming up */
468 int
469 bnode_PendingTimeout(register struct bnode *abnode)
470 {
471     return (abnode->flags & BNODE_NEEDTIMEOUT);
472 }
473
474 /* function called to set / clear periodic bnode wakeup times */
475 int
476 bnode_SetTimeout(register struct bnode *abnode, afs_int32 atimeout)
477 {
478     if (atimeout != 0) {
479         abnode->nextTimeout = FT_ApproxTime() + atimeout;
480         abnode->flags |= BNODE_NEEDTIMEOUT;
481         abnode->period = atimeout;
482         IOMGR_Cancel(bproc_pid);
483     } else {
484         abnode->flags &= ~BNODE_NEEDTIMEOUT;
485     }
486     return 0;
487 }
488
489 /* used by new bnode creation code to format bnode header */
490 int
491 bnode_InitBnode(register struct bnode *abnode, struct bnode_ops *abnodeops,
492                 char *aname)
493 {
494     struct bnode **lb, *nb;
495
496     /* format the bnode properly */
497     memset(abnode, 0, sizeof(struct bnode));
498     abnode->ops = abnodeops;
499     abnode->name = (char *)malloc(strlen(aname) + 1);
500     if (!abnode->name)
501         return ENOMEM;
502     strcpy(abnode->name, aname);
503     abnode->flags = BNODE_ACTIVE;
504     abnode->fileGoal = BSTAT_NORMAL;
505     abnode->goal = BSTAT_SHUTDOWN;
506
507     /* put the bnode at the end of the list so we write bnode file in same order */
508     for (lb = &allBnodes, nb = *lb; nb; lb = &nb->next, nb = *lb);
509     *lb = abnode;
510
511     return 0;
512 }
513
514 static int
515 DeleteProc(register struct bnode_proc *abproc)
516 {
517     register struct bnode_proc **pb, *tb;
518     struct bnode_proc *nb;
519
520     for (pb = &allProcs, tb = *pb; tb; pb = &tb->next, tb = nb) {
521         nb = tb->next;
522         if (tb == abproc) {
523             *pb = nb;
524             free(tb);
525             return 0;
526         }
527     }
528     return BZNOENT;
529 }
530
531 /* bnode lwp executes this code repeatedly */
532 static void *
533 bproc(void *unused)
534 {
535     register afs_int32 code;
536     register struct bnode *tb;
537     register afs_int32 temp;
538     register struct bnode_proc *tp;
539     struct bnode *nb;
540     int options;                /* must not be register */
541     struct timeval tv;
542     int setAny;
543     int status;
544
545     while (1) {
546         /* first figure out how long to sleep for */
547         temp = 0x7fffffff;      /* afs_int32 time; maxint doesn't work in select */
548         setAny = 0;
549         for (tb = allBnodes; tb; tb = tb->next) {
550             if (tb->flags & BNODE_NEEDTIMEOUT) {
551                 if (tb->nextTimeout < temp) {
552                     setAny = 1;
553                     temp = tb->nextTimeout;
554                 }
555             }
556         }
557         /* now temp has the time at which we should wakeup next */
558
559         /* sleep */
560         if (setAny)
561             temp -= FT_ApproxTime();    /* how many seconds until next event */
562         else
563             temp = 999999;
564         if (temp > 0) {
565             tv.tv_sec = temp;
566             tv.tv_usec = 0;
567             code = IOMGR_Select(0, 0, 0, 0, &tv);
568         } else
569             code = 0;           /* fake timeout code */
570
571         /* figure out why we woke up; child exit or timeouts */
572         FT_GetTimeOfDay(&tv, 0);        /* must do the real gettimeofday once and a while */
573         temp = tv.tv_sec;
574
575         /* check all bnodes to see which ones need timeout events */
576         for (tb = allBnodes; tb; tb = nb) {
577             if ((tb->flags & BNODE_NEEDTIMEOUT) && temp > tb->nextTimeout) {
578                 bnode_Hold(tb);
579                 BOP_TIMEOUT(tb);
580                 bnode_Check(tb);
581                 if (tb->flags & BNODE_NEEDTIMEOUT) {    /* check again, BOP_TIMEOUT could change */
582                     tb->nextTimeout = FT_ApproxTime() + tb->period;
583                 }
584                 nb = tb->next;
585                 bnode_Release(tb);      /* delete may occur here */
586             } else
587                 nb = tb->next;
588         }
589
590         if (code < 0) {
591             /* signalled, probably by incoming signal */
592             while (1) {
593                 options = WNOHANG;
594                 bnode_waiting = options | 0x800000;
595                 code = waitpid((pid_t) - 1, &status, options);
596                 bnode_waiting = 0;
597                 if (code == 0 || code == -1)
598                     break;      /* all done */
599                 /* otherwise code has a process id, which we now search for */
600                 for (tp = allProcs; tp; tp = tp->next)
601                     if (tp->pid == code)
602                         break;
603                 if (tp) {
604                     /* found the pid */
605                     tb = tp->bnode;
606                     bnode_Hold(tb);
607
608                     /* count restarts in last 10 seconds */
609                     if (temp > tb->rsTime + 30) {
610                         /* it's been 10 seconds we've been counting */
611                         tb->rsTime = temp;
612                         tb->rsCount = 0;
613                     }
614
615                     if (WIFSIGNALED(status) == 0) {
616                         /* exited, not signalled */
617                         tp->lastExit = WEXITSTATUS(status);
618                         tp->lastSignal = 0;
619                         if (tp->lastExit) {
620                             tb->errorCode = tp->lastExit;
621                             tb->lastErrorExit = FT_ApproxTime();
622                             RememberProcName(tp);
623                             tb->errorSignal = 0;
624                         }
625                         if (tp->coreName)
626                             bozo_Log("%s:%s exited with code %d\n", tb->name,
627                                      tp->coreName, tp->lastExit);
628                         else
629                             bozo_Log("%s exited with code %d\n", tb->name,
630                                      tp->lastExit);
631                     } else {
632                         /* Signal occurred, perhaps spurious due to shutdown request.
633                          * If due to a shutdown request, don't overwrite last error
634                          * information.
635                          */
636                         tp->lastSignal = WTERMSIG(status);
637                         tp->lastExit = 0;
638                         if (tp->lastSignal != SIGQUIT
639                             && tp->lastSignal != SIGTERM
640                             && tp->lastSignal != SIGKILL) {
641                             tb->errorSignal = tp->lastSignal;
642                             tb->lastErrorExit = FT_ApproxTime();
643                             RememberProcName(tp);
644                         }
645                         if (tp->coreName)
646                             bozo_Log("%s:%s exited on signal %d%s\n",
647                                      tb->name, tp->coreName, tp->lastSignal,
648                                      WCOREDUMP(status) ? " (core dumped)" :
649                                      "");
650                         else
651                             bozo_Log("%s exited on signal %d%s\n", tb->name,
652                                      tp->lastSignal,
653                                      WCOREDUMP(status) ? " (core dumped)" :
654                                      "");
655                         SaveCore(tb, tp);
656                     }
657                     tb->lastAnyExit = FT_ApproxTime();
658
659                     if (tb->notifier) {
660                         bozo_Log("BNODE: Notifier %s will be called\n",
661                                  tb->notifier);
662                         hdl_notifier(tp);
663                     }
664                     BOP_PROCEXIT(tb, tp);
665
666                     bnode_Check(tb);
667                     if (tb->rsCount++ > 10) {
668                         /* 10 in 10 seconds */
669                         tb->flags |= BNODE_ERRORSTOP;
670                         bnode_SetGoal(tb, BSTAT_SHUTDOWN);
671                         bozo_Log
672                             ("BNODE '%s' repeatedly failed to start, perhaps missing executable.\n",
673                              tb->name);
674                     }
675                     bnode_Release(tb);  /* bnode delete can happen here */
676                     DeleteProc(tp);
677                 } else
678                     bnode_stats.weirdPids++;
679             }
680         }
681     }
682     return NULL;
683 }
684
685 static afs_int32
686 SendNotifierData(register int fd, register struct bnode_proc *tp)
687 {
688     register struct bnode *tb = tp->bnode;
689     char buffer[1000], *bufp = buffer, *buf1;
690     register int len;
691
692     /*
693      * First sent out the bnode_proc struct
694      */
695     (void)sprintf(bufp, "BEGIN bnode_proc\n");
696     bufp += strlen(bufp);
697     (void)sprintf(bufp, "comLine: %s\n", tp->comLine);
698     bufp += strlen(bufp);
699     if (!(buf1 = tp->coreName))
700         buf1 = "(null)";
701     (void)sprintf(bufp, "coreName: %s\n", buf1);
702     bufp += strlen(bufp);
703     (void)sprintf(bufp, "pid: %ld\n", afs_cast_int32(tp->pid));
704     bufp += strlen(bufp);
705     (void)sprintf(bufp, "lastExit: %ld\n", afs_cast_int32(tp->lastExit));
706     bufp += strlen(bufp);
707 #ifdef notdef
708     (void)sprintf(bufp, "lastSignal: %ld\n", afs_cast_int32(tp->lastSignal));
709     bufp += strlen(bufp);
710 #endif
711     (void)sprintf(bufp, "flags: %ld\n", afs_cast_int32(tp->flags));
712     bufp += strlen(bufp);
713     (void)sprintf(bufp, "END bnode_proc\n");
714     bufp += strlen(bufp);
715     len = (int)(bufp - buffer);
716     if (write(fd, buffer, len) < 0) {
717         return -1;
718     }
719
720     /*
721      * Now sent out the bnode struct
722      */
723     bufp = buffer;
724     (void)sprintf(bufp, "BEGIN bnode\n");
725     bufp += strlen(bufp);
726     (void)sprintf(bufp, "name: %s\n", tb->name);
727     bufp += strlen(bufp);
728     (void)sprintf(bufp, "rsTime: %ld\n", afs_cast_int32(tb->rsTime));
729     bufp += strlen(bufp);
730     (void)sprintf(bufp, "rsCount: %ld\n", afs_cast_int32(tb->rsCount));
731     bufp += strlen(bufp);
732     (void)sprintf(bufp, "procStartTime: %ld\n", afs_cast_int32(tb->procStartTime));
733     bufp += strlen(bufp);
734     (void)sprintf(bufp, "procStarts: %ld\n", afs_cast_int32(tb->procStarts));
735     bufp += strlen(bufp);
736     (void)sprintf(bufp, "lastAnyExit: %ld\n", afs_cast_int32(tb->lastAnyExit));
737     bufp += strlen(bufp);
738     (void)sprintf(bufp, "lastErrorExit: %ld\n", afs_cast_int32(tb->lastErrorExit));
739     bufp += strlen(bufp);
740     (void)sprintf(bufp, "errorCode: %ld\n", afs_cast_int32(tb->errorCode));
741     bufp += strlen(bufp);
742     (void)sprintf(bufp, "errorSignal: %ld\n", afs_cast_int32(tb->errorSignal));
743     bufp += strlen(bufp);
744 /*
745     (void) sprintf(bufp, "lastErrorName: %s\n", tb->lastErrorName);
746     bufp += strlen(bufp);
747 */
748     (void)sprintf(bufp, "goal: %d\n", tb->goal);
749     bufp += strlen(bufp);
750     (void)sprintf(bufp, "END bnode\n");
751     bufp += strlen(bufp);
752     len = (int)(bufp - buffer);
753     if (write(fd, buffer, len) < 0) {
754         return -1;
755     }
756     return 0;
757 }
758
759 int
760 hdl_notifier(struct bnode_proc *tp)
761 {
762 #ifndef AFS_NT40_ENV            /* NT notifier callout not yet implemented */
763     int code, pid;
764     struct stat tstat;
765
766     if (stat(tp->bnode->notifier, &tstat)) {
767         bozo_Log("BNODE: Failed to find notifier '%s'; ignored\n",
768                  tp->bnode->notifier);
769         return (1);
770     }
771     if ((pid = fork()) == 0) {
772         FILE *fout;
773         struct bnode *tb = tp->bnode;
774         int ec;
775
776 #if defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV) || defined(AFS_SGI51_ENV)
777         ec = setsid();
778 #elif defined(AFS_DARWIN90_ENV)
779         ec = setpgid(0, 0);
780 #elif defined(AFS_LINUX20_ENV) || defined(AFS_AIX_ENV)  
781         ec = setpgrp();
782 #else
783         ec = setpgrp(0, 0);
784 #endif
785         fout = popen(tb->notifier, "w");
786         if (fout == NULL) {
787             bozo_Log("BNODE: Failed to find notifier '%s'; ignored\n",
788                      tb->notifier);
789             perror(tb->notifier);
790             exit(1);
791         }
792         code = SendNotifierData(fileno(fout), tp);
793         pclose(fout);
794         exit(0);
795     } else if (pid < 0) {
796         bozo_Log("Failed to fork creating process to handle notifier '%s'\n",
797                  tp->bnode->notifier);
798         return -1;
799     }
800 #endif /* AFS_NT40_ENV */
801     return (0);
802 }
803
804 /* Called by IOMGR at low priority on IOMGR's stack shortly after a SIGCHLD
805  * occurs.  Wakes up bproc do redo things */
806 void *
807 bnode_SoftInt(void *param)
808 {
809     /* int asignal = (int) param; */
810
811     IOMGR_Cancel(bproc_pid);
812     return 0;
813 }
814
815 /* Called at signal interrupt level; queues function to be called
816  * when IOMGR runs again.
817  */
818 void
819 bnode_Int(int asignal)
820 {
821     if (asignal == SIGQUIT) {
822         IOMGR_SoftSig(bozo_ShutdownAndExit, (void *) asignal);
823     } else {
824         IOMGR_SoftSig(bnode_SoftInt, (void *) asignal);
825     }
826 }
827
828
829 /* intialize the whole system */
830 int
831 bnode_Init(void)
832 {
833     PROCESS junk;
834     register afs_int32 code;
835     struct sigaction newaction;
836     static int initDone = 0;
837
838     if (initDone)
839         return 0;
840     initDone = 1;
841     memset(&bnode_stats, 0, sizeof(bnode_stats));
842     LWP_InitializeProcessSupport(1, &junk);     /* just in case */
843     IOMGR_Initialize();
844     code = LWP_CreateProcess(bproc, BNODE_LWP_STACKSIZE,
845                              /* priority */ 1, (void *) /* parm */ 0,
846                              "bnode-manager", &bproc_pid);
847     if (code)
848         return code;
849     memset((char *)&newaction, 0, sizeof(newaction));
850     newaction.sa_handler = bnode_Int;
851     code = sigaction(SIGCHLD, &newaction, NULL);
852     if (code)
853         return errno;
854     code = sigaction(SIGQUIT, &newaction, NULL);
855     if (code)
856         return errno;
857     return code;
858 }
859
860 /* free token list returned by parseLine */
861 int
862 bnode_FreeTokens(register struct bnode_token *alist)
863 {
864     register struct bnode_token *nlist;
865     for (; alist; alist = nlist) {
866         nlist = alist->next;
867         free(alist->key);
868         free(alist);
869     }
870     return 0;
871 }
872
873 static int
874 space(int x)
875 {
876     if (x == 0 || x == ' ' || x == '\t' || x == '\n')
877         return 1;
878     else
879         return 0;
880 }
881
882 int
883 bnode_ParseLine(char *aline, struct bnode_token **alist)
884 {
885     char tbuffer[256];
886     register char *tptr = NULL;
887     int inToken;
888     struct bnode_token *first, *last;
889     register struct bnode_token *ttok;
890     register int tc;
891
892     inToken = 0;                /* not copying token chars at start */
893     first = (struct bnode_token *)0;
894     last = (struct bnode_token *)0;
895     while (1) {
896         tc = *aline++;
897         if (tc == 0 || space(tc)) {     /* terminating null gets us in here, too */
898             if (inToken) {
899                 inToken = 0;    /* end of this token */
900                 *tptr++ = 0;
901                 ttok =
902                     (struct bnode_token *)malloc(sizeof(struct bnode_token));
903                 ttok->next = (struct bnode_token *)0;
904                 ttok->key = (char *)malloc(strlen(tbuffer) + 1);
905                 strcpy(ttok->key, tbuffer);
906                 if (last) {
907                     last->next = ttok;
908                     last = ttok;
909                 } else
910                     last = ttok;
911                 if (!first)
912                     first = ttok;
913             }
914         } else {
915             /* an alpha character */
916             if (!inToken) {
917                 tptr = tbuffer;
918                 inToken = 1;
919             }
920             if (tptr - tbuffer >= sizeof(tbuffer))
921                 return -1;      /* token too long */
922             *tptr++ = tc;
923         }
924         if (tc == 0) {
925             /* last token flushed 'cause space(0) --> true */
926             if (last)
927                 last->next = (struct bnode_token *)0;
928             *alist = first;
929             return 0;
930         }
931     }
932     return 0;
933 }
934
935 #define MAXVARGS            128
936 int
937 bnode_NewProc(struct bnode *abnode, char *aexecString, char *coreName,
938               struct bnode_proc **aproc)
939 {
940     struct bnode_token *tlist, *tt;
941     afs_int32 code;
942     struct bnode_proc *tp;
943     pid_t cpid;
944     char *argv[MAXVARGS];
945     int i;
946
947     code = bnode_ParseLine(aexecString, &tlist);        /* try parsing first */
948     if (code)
949         return code;
950     tp = (struct bnode_proc *)malloc(sizeof(struct bnode_proc));
951     memset(tp, 0, sizeof(struct bnode_proc));
952     tp->next = allProcs;
953     tp->bnode = abnode;
954     tp->comLine = aexecString;
955     tp->coreName = coreName;    /* may be null */
956     abnode->procStartTime = FT_ApproxTime();
957     abnode->procStarts++;
958
959     /* convert linked list of tokens into argv structure */
960     for (tt = tlist, i = 0; i < (MAXVARGS - 1) && tt; tt = tt->next, i++) {
961         argv[i] = tt->key;
962     }
963     argv[i] = NULL;             /* null-terminated */
964
965     cpid = spawnprocve(argv[0], argv, environ, -1);
966     osi_audit(BOSSpawnProcEvent, 0, AUD_STR, aexecString, AUD_END);
967
968     if (cpid == (pid_t) - 1) {
969         bozo_Log("Failed to spawn process for bnode '%s'\n", abnode->name);
970         bnode_FreeTokens(tlist);
971         free(tp);
972         return errno;
973     }
974
975     bnode_FreeTokens(tlist);
976     allProcs = tp;
977     *aproc = tp;
978     tp->pid = cpid;
979     tp->flags = BPROC_STARTED;
980     tp->flags &= ~BPROC_EXITED;
981     bnode_Check(abnode);
982     return 0;
983 }
984
985 int
986 bnode_StopProc(register struct bnode_proc *aproc, int asignal)
987 {
988     register int code;
989     if (!(aproc->flags & BPROC_STARTED) || (aproc->flags & BPROC_EXITED))
990         return BZNOTACTIVE;
991
992     osi_audit(BOSStopProcEvent, 0, AUD_STR, (aproc ? aproc->comLine : NULL),
993               AUD_END);
994
995     code = kill(aproc->pid, asignal);
996     bnode_Check(aproc->bnode);
997     return code;
998 }
999
1000 int
1001 bnode_Deactivate(register struct bnode *abnode)
1002 {
1003     register struct bnode **pb, *tb;
1004     struct bnode *nb;
1005     if (!(abnode->flags & BNODE_ACTIVE))
1006         return BZNOTACTIVE;
1007     for (pb = &allBnodes, tb = *pb; tb; tb = nb) {
1008         nb = tb->next;
1009         if (tb == abnode) {
1010             *pb = nb;
1011             tb->flags &= ~BNODE_ACTIVE;
1012             return 0;
1013         }
1014     }
1015     return BZNOENT;
1016 }