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