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