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