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