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