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