Replace bits of libutil with libroken
[openafs.git] / src / vol / salvaged.c
1 /*
2  * Copyright 2006-2007, Sine Nomine Associates 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 /*
11  * demand attach fs
12  * online salvager daemon
13  */
14
15 /* Main program file. Define globals. */
16 #define MAIN 1
17
18 #include <afsconfig.h>
19 #include <afs/param.h>
20
21 #include <roken.h>
22
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <dirent.h>
27 #include <sys/stat.h>
28 #include <time.h>
29 #include <errno.h>
30 #ifdef AFS_NT40_ENV
31 #include <io.h>
32 #include <WINNT/afsevent.h>
33 #else
34 #include <sys/param.h>
35 #include <sys/file.h>
36 #ifndef ITIMER_REAL
37 #include <sys/time.h>
38 #endif /* ITIMER_REAL */
39 #endif
40 #ifndef WCOREDUMP
41 #define WCOREDUMP(x)    ((x) & 0200)
42 #endif
43 #include <rx/xdr.h>
44 #include <afs/afsint.h>
45 #include <afs/afs_assert.h>
46 #if !defined(AFS_SGI_ENV) && !defined(AFS_NT40_ENV)
47 #if defined(AFS_VFSINCL_ENV)
48 #include <sys/vnode.h>
49 #ifdef  AFS_SUN5_ENV
50 #include <sys/fs/ufs_inode.h>
51 #else
52 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
53 #include <ufs/ufs/dinode.h>
54 #include <ufs/ffs/fs.h>
55 #else
56 #include <ufs/inode.h>
57 #endif
58 #endif
59 #else /* AFS_VFSINCL_ENV */
60 #ifdef  AFS_OSF_ENV
61 #include <ufs/inode.h>
62 #else /* AFS_OSF_ENV */
63 #if !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV)
64 #include <sys/inode.h>
65 #endif
66 #endif
67 #endif /* AFS_VFSINCL_ENV */
68 #endif /* AFS_SGI_ENV */
69 #ifdef  AFS_AIX_ENV
70 #include <sys/vfs.h>
71 #include <sys/lockf.h>
72 #else
73 #ifdef  AFS_HPUX_ENV
74 #include <unistd.h>
75 #include <checklist.h>
76 #else
77 #if defined(AFS_SGI_ENV)
78 #include <unistd.h>
79 #include <fcntl.h>
80 #include <mntent.h>
81 #else
82 #if     defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
83 #ifdef    AFS_SUN5_ENV
84 #include <unistd.h>
85 #include <sys/mnttab.h>
86 #include <sys/mntent.h>
87 #else
88 #include <mntent.h>
89 #endif
90 #else
91 #endif /* AFS_SGI_ENV */
92 #endif /* AFS_HPUX_ENV */
93 #endif
94 #endif
95 #include <fcntl.h>
96 #ifndef AFS_NT40_ENV
97 #include <afs/osi_inode.h>
98 #endif
99 #include <afs/cmd.h>
100 #include <afs/afsutil.h>
101 #include <afs/fileutil.h>
102 #include <afs/procmgmt.h>       /* signal(), kill(), wait(), etc. */
103 #include <afs/dir.h>
104 #ifndef AFS_NT40_ENV
105 #include <syslog.h>
106 #endif
107
108 #include "nfs.h"
109 #include "lwp.h"
110 #include "lock.h"
111 #include <afs/afssyscalls.h>
112 #include "ihandle.h"
113 #include "vnode.h"
114 #include "volume.h"
115 #include "partition.h"
116 #include "daemon_com.h"
117 #include "fssync.h"
118 #include "salvsync.h"
119 #include "viceinode.h"
120 #include "salvage.h"
121 #include "vol-salvage.h"
122 #include "common.h"
123 #ifdef AFS_NT40_ENV
124 #include <pthread.h>
125 #endif
126
127
128 #if !defined(AFS_DEMAND_ATTACH_FS)
129 #error "online salvager only supported for demand attach fileserver"
130 #endif /* AFS_DEMAND_ATTACH_FS */
131
132 #if defined(AFS_NT40_ENV)
133 #error "online salvager not supported on NT"
134 #endif /* AFS_NT40_ENV */
135
136 /*@+fcnmacros +macrofcndecl@*/
137 #ifdef O_LARGEFILE
138 #define afs_fopen       fopen64
139 #else /* !O_LARGEFILE */
140 #define afs_fopen       fopen
141 #endif /* !O_LARGEFILE */
142 /*@=fcnmacros =macrofcndecl@*/
143
144
145
146 static volatile int current_workers = 0;
147 static volatile struct rx_queue pending_q;
148 static pthread_mutex_t worker_lock;
149 static pthread_cond_t worker_cv;
150
151 static void * SalvageChildReaperThread(void *);
152 static int DoSalvageVolume(struct SalvageQueueNode * node, int slot);
153
154 static void SalvageServer(int argc, char **argv);
155 static void SalvageClient(VolumeId vid, char * pname);
156
157 static int Reap_Child(char * prog, int * pid, int * status);
158
159 static void * SalvageLogCleanupThread(void *);
160 static int SalvageLogCleanup(int pid);
161
162 static void * SalvageLogScanningThread(void *);
163 static void ScanLogs(struct rx_queue *log_watch_queue);
164
165 struct cmdline_rock {
166     int argc;
167     char **argv;
168 };
169
170 struct log_cleanup_node {
171     struct rx_queue q;
172     int pid;
173 };
174
175 struct {
176     struct rx_queue queue_head;
177     pthread_cond_t queue_change_cv;
178 } log_cleanup_queue;
179
180
181 #define DEFAULT_PARALLELISM 4 /* allow 4 parallel salvage workers by default */
182
183 static int
184 handleit(struct cmd_syndesc *as, void *arock)
185 {
186     struct cmd_item *ti;
187     char pname[100], *temp;
188     afs_int32 seenpart = 0, seenvol = 0, vid = 0;
189     struct cmdline_rock *rock = (struct cmdline_rock *)arock;
190
191 #ifdef AFS_SGI_VNODE_GLUE
192     if (afs_init_kernel_config(-1) < 0) {
193         printf
194             ("Can't determine NUMA configuration, not starting salvager.\n");
195         exit(1);
196     }
197 #endif
198
199     if (as->parms[2].items)     /* -debug */
200         debug = 1;
201     if (as->parms[3].items)     /* -nowrite */
202         Testing = 1;
203     if (as->parms[4].items)     /* -inodes */
204         ListInodeOption = 1;
205     if (as->parms[5].items)     /* -oktozap */
206         OKToZap = 1;
207     if (as->parms[6].items)     /* -rootinodes */
208         ShowRootFiles = 1;
209     if (as->parms[8].items)     /* -ForceReads */
210         forceR = 1;
211     if ((ti = as->parms[9].items)) {    /* -Parallel # */
212         temp = ti->data;
213         if (strncmp(temp, "all", 3) == 0) {
214             PartsPerDisk = 1;
215             temp += 3;
216         }
217         if (strlen(temp) != 0) {
218             Parallel = atoi(temp);
219             if (Parallel < 1)
220                 Parallel = 1;
221             if (Parallel > MAXPARALLEL) {
222                 printf("Setting parallel salvages to maximum of %d \n",
223                        MAXPARALLEL);
224                 Parallel = MAXPARALLEL;
225             }
226         }
227     } else {
228         Parallel = MIN(DEFAULT_PARALLELISM, MAXPARALLEL);
229     }
230     if ((ti = as->parms[10].items)) {   /* -tmpdir */
231         DIR *dirp;
232
233         tmpdir = ti->data;
234         dirp = opendir(tmpdir);
235         if (!dirp) {
236             printf
237                 ("Can't open temporary placeholder dir %s; using current partition \n",
238                  tmpdir);
239             tmpdir = NULL;
240         } else
241             closedir(dirp);
242     }
243     if ((ti = as->parms[11].items))     /* -showlog */
244         ShowLog = 1;
245     if ((ti = as->parms[12].items)) {   /* -orphans */
246         if (Testing)
247             orphans = ORPH_IGNORE;
248         else if (strcmp(ti->data, "remove") == 0
249                  || strcmp(ti->data, "r") == 0)
250             orphans = ORPH_REMOVE;
251         else if (strcmp(ti->data, "attach") == 0
252                  || strcmp(ti->data, "a") == 0)
253             orphans = ORPH_ATTACH;
254     }
255 #ifndef AFS_NT40_ENV            /* ignore options on NT */
256     if ((ti = as->parms[13].items)) {   /* -syslog */
257         useSyslog = 1;
258         ShowLog = 0;
259     }
260     if ((ti = as->parms[14].items)) {   /* -syslogfacility */
261         useSyslogFacility = atoi(ti->data);
262     }
263
264     if ((ti = as->parms[15].items)) {   /* -datelogs */
265         TimeStampLogFile((char *)AFSDIR_SERVER_SALSRVLOG_FILEPATH);
266     }
267 #endif
268
269     if ((ti = as->parms[16].items)) {   /* -client */
270         if ((ti = as->parms[0].items)) {        /* -partition */
271             seenpart = 1;
272             strlcpy(pname, ti->data, sizeof(pname));
273         }
274         if ((ti = as->parms[1].items)) {        /* -volumeid */
275             seenvol = 1;
276             vid = atoi(ti->data);
277         }
278
279         if (ShowLog) {
280             printf("-showlog does not work with -client\n");
281             exit(-1);
282         }
283
284         if (!seenpart || !seenvol) {
285             printf("You must specify '-partition' and '-volumeid' with the '-client' option\n");
286             exit(-1);
287         }
288
289         SalvageClient(vid, pname);
290
291     } else {  /* salvageserver mode */
292         SalvageServer(rock->argc, rock->argv);
293     }
294     return (0);
295 }
296
297
298 #ifndef AFS_NT40_ENV
299 #include "AFS_component_version_number.c"
300 #endif
301 #define MAX_ARGS 128
302 #ifdef AFS_NT40_ENV
303 char *save_args[MAX_ARGS];
304 int n_save_args = 0;
305 pthread_t main_thread;
306 #endif
307
308 int
309 main(int argc, char **argv)
310 {
311     struct cmd_syndesc *ts;
312     int err = 0;
313     struct cmdline_rock arock;
314
315 #ifdef  AFS_AIX32_ENV
316     /*
317      * The following signal action for AIX is necessary so that in case of a
318      * crash (i.e. core is generated) we can include the user's data section
319      * in the core dump. Unfortunately, by default, only a partial core is
320      * generated which, in many cases, isn't too useful.
321      */
322     struct sigaction nsa;
323
324     sigemptyset(&nsa.sa_mask);
325     nsa.sa_handler = SIG_DFL;
326     nsa.sa_flags = SA_FULLDUMP;
327     sigaction(SIGABRT, &nsa, NULL);
328     sigaction(SIGSEGV, &nsa, NULL);
329 #endif
330
331     /* Initialize directory paths */
332     if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
333 #ifdef AFS_NT40_ENV
334         ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
335 #endif
336         fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
337                 argv[0]);
338         exit(2);
339     }
340 #ifdef AFS_NT40_ENV
341     main_thread = pthread_self();
342     if (spawnDatap && spawnDataLen) {
343         /* This is a child per partition salvager. Don't setup log or
344          * try to lock the salvager lock.
345          */
346         if (nt_SetupPartitionSalvage(spawnDatap, spawnDataLen) < 0)
347             exit(3);
348     } else {
349 #endif
350
351 #ifndef AFS_NT40_ENV
352         if (geteuid() != 0) {
353             printf("Salvager must be run as root.\n");
354             fflush(stdout);
355             Exit(0);
356         }
357 #endif
358
359         /* bad for normal help flag processing, but can do nada */
360
361 #ifdef AFS_NT40_ENV
362     }
363 #endif
364
365     arock.argc = argc;
366     arock.argv = argv;
367
368     ts = cmd_CreateSyntax("initcmd", handleit, &arock, "initialize the program");
369     cmd_AddParm(ts, "-partition", CMD_SINGLE, CMD_OPTIONAL,
370                 "Name of partition to salvage");
371     cmd_AddParm(ts, "-volumeid", CMD_SINGLE, CMD_OPTIONAL,
372                 "Volume Id to salvage");
373     cmd_AddParm(ts, "-debug", CMD_FLAG, CMD_OPTIONAL,
374                 "Run in Debugging mode");
375     cmd_AddParm(ts, "-nowrite", CMD_FLAG, CMD_OPTIONAL,
376                 "Run readonly/test mode");
377     cmd_AddParm(ts, "-inodes", CMD_FLAG, CMD_OPTIONAL,
378                 "Just list affected afs inodes - debugging flag");
379     cmd_AddParm(ts, "-oktozap", CMD_FLAG, CMD_OPTIONAL,
380                 "Give permission to destroy bogus inodes/volumes - debugging flag");
381     cmd_AddParm(ts, "-rootinodes", CMD_FLAG, CMD_OPTIONAL,
382                 "Show inodes owned by root - debugging flag");
383     cmd_AddParm(ts, "-salvagedirs", CMD_FLAG, CMD_OPTIONAL,
384                 "Force rebuild/salvage of all directories");
385     cmd_AddParm(ts, "-blockreads", CMD_FLAG, CMD_OPTIONAL,
386                 "Read smaller blocks to handle IO/bad blocks");
387     cmd_AddParm(ts, "-parallel", CMD_SINGLE, CMD_OPTIONAL,
388                 "# of max parallel partition salvaging");
389     cmd_AddParm(ts, "-tmpdir", CMD_SINGLE, CMD_OPTIONAL,
390                 "Name of dir to place tmp files ");
391     cmd_AddParm(ts, "-showlog", CMD_FLAG, CMD_OPTIONAL,
392                 "Show log file upon completion");
393     cmd_AddParm(ts, "-orphans", CMD_SINGLE, CMD_OPTIONAL,
394                 "ignore | remove | attach");
395
396     /* note - syslog isn't avail on NT, but if we make it conditional, have
397      * to deal with screwy offsets for cmd params */
398     cmd_AddParm(ts, "-syslog", CMD_FLAG, CMD_OPTIONAL,
399                 "Write salvage log to syslogs");
400     cmd_AddParm(ts, "-syslogfacility", CMD_SINGLE, CMD_OPTIONAL,
401                 "Syslog facility number to use");
402     cmd_AddParm(ts, "-datelogs", CMD_FLAG, CMD_OPTIONAL,
403                 "Include timestamp in logfile filename");
404
405     cmd_AddParm(ts, "-client", CMD_FLAG, CMD_OPTIONAL,
406                 "Use SALVSYNC to ask salvageserver to salvage a volume");
407
408     err = cmd_Dispatch(argc, argv);
409     Exit(err);
410     return 0; /* not reached */
411 }
412
413 static void
414 SalvageClient(VolumeId vid, char * pname)
415 {
416     int done = 0;
417     afs_int32 code;
418     SYNC_response res;
419     SALVSYNC_response_hdr sres;
420     VolumePackageOptions opts;
421
422     VOptDefaults(volumeUtility, &opts);
423     if (VInitVolumePackage2(volumeUtility, &opts)) {
424         /* VInitVolumePackage2 can fail on e.g. partition attachment errors,
425          * but we don't really care, since all we're doing is trying to use
426          * SALVSYNC */
427         fprintf(stderr, "errors encountered initializing volume package, but "
428                         "trying to continue anyway\n");
429     }
430     SALVSYNC_clientInit();
431
432     code = SALVSYNC_SalvageVolume(vid, pname, SALVSYNC_SALVAGE, SALVSYNC_OPERATOR, 0, NULL);
433     if (code != SYNC_OK) {
434         goto sync_error;
435     }
436
437     res.payload.buf = (void *) &sres;
438     res.payload.len = sizeof(sres);
439
440     while(!done) {
441         sleep(2);
442         code = SALVSYNC_SalvageVolume(vid, pname, SALVSYNC_QUERY, SALVSYNC_WHATEVER, 0, &res);
443         if (code != SYNC_OK) {
444             goto sync_error;
445         }
446         switch (sres.state) {
447         case SALVSYNC_STATE_ERROR:
448             printf("salvageserver reports salvage ended in an error; check log files for more details\n");
449         case SALVSYNC_STATE_DONE:
450         case SALVSYNC_STATE_UNKNOWN:
451             done = 1;
452         }
453     }
454     SALVSYNC_clientFinis();
455     return;
456
457  sync_error:
458     if (code == SYNC_DENIED) {
459         printf("salvageserver refused to salvage volume %u on partition %s\n",
460                vid, pname);
461     } else if (code == SYNC_BAD_COMMAND) {
462         printf("SALVSYNC protocol mismatch; please make sure fileserver, volserver, salvageserver and salvager are same version\n");
463     } else if (code == SYNC_COM_ERROR) {
464         printf("SALVSYNC communications error\n");
465     }
466     SALVSYNC_clientFinis();
467     exit(-1);
468 }
469
470 static int * child_slot;
471
472 static void
473 SalvageServer(int argc, char **argv)
474 {
475     int pid, ret;
476     struct SalvageQueueNode * node;
477     pthread_t tid;
478     pthread_attr_t attrs;
479     int slot;
480     VolumePackageOptions opts;
481
482     /* All entries to the log will be appended.  Useful if there are
483      * multiple salvagers appending to the log.
484      */
485
486     CheckLogFile((char *)AFSDIR_SERVER_SALSRVLOG_FILEPATH);
487 #ifndef AFS_NT40_ENV
488 #ifdef AFS_LINUX20_ENV
489     fcntl(fileno(logFile), F_SETFL, O_APPEND);  /* Isn't this redundant? */
490 #else
491     fcntl(fileno(logFile), F_SETFL, FAPPEND);   /* Isn't this redundant? */
492 #endif
493 #endif
494     setlinebuf(logFile);
495
496     fprintf(logFile, "%s\n", cml_version_number);
497     LogCommandLine(argc, argv, "Online Salvage Server",
498                    SalvageVersion, "Starting OpenAFS", Log);
499     /* Get and hold a lock for the duration of the salvage to make sure
500      * that no other salvage runs at the same time.  The routine
501      * VInitVolumePackage2 (called below) makes sure that a file server or
502      * other volume utilities don't interfere with the salvage.
503      */
504
505     /* even demand attach online salvager
506      * still needs this because we don't want
507      * a stand-alone salvager to conflict with
508      * the salvager daemon */
509     ObtainSharedSalvageLock();
510
511     child_slot = (int *) malloc(Parallel * sizeof(int));
512     osi_Assert(child_slot != NULL);
513     memset(child_slot, 0, Parallel * sizeof(int));
514
515     /* initialize things */
516     VOptDefaults(salvageServer, &opts);
517     if (VInitVolumePackage2(salvageServer, &opts)) {
518         Log("Shutting down: errors encountered initializing volume package\n");
519         Exit(1);
520     }
521     DInit(10);
522     queue_Init(&pending_q);
523     queue_Init(&log_cleanup_queue);
524     MUTEX_INIT(&worker_lock, "worker", MUTEX_DEFAULT, 0);
525     CV_INIT(&worker_cv, "worker", CV_DEFAULT, 0);
526     CV_INIT(&log_cleanup_queue.queue_change_cv, "queuechange", CV_DEFAULT, 0);
527     osi_Assert(pthread_attr_init(&attrs) == 0);
528
529     /* start up the reaper and log cleaner threads */
530     osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
531     osi_Assert(pthread_create(&tid,
532                           &attrs,
533                           &SalvageChildReaperThread,
534                           NULL) == 0);
535     osi_Assert(pthread_create(&tid,
536                           &attrs,
537                           &SalvageLogCleanupThread,
538                           NULL) == 0);
539     osi_Assert(pthread_create(&tid,
540                           &attrs,
541                           &SalvageLogScanningThread,
542                           NULL) == 0);
543
544     /* loop forever serving requests */
545     while (1) {
546         node = SALVSYNC_getWork();
547         osi_Assert(node != NULL);
548
549         Log("dispatching child to salvage volume %u...\n",
550             node->command.sop.parent);
551
552         VOL_LOCK;
553         /* find a slot */
554         for (slot = 0; slot < Parallel; slot++) {
555           if (!child_slot[slot])
556             break;
557         }
558         osi_Assert (slot < Parallel);
559
560     do_fork:
561         pid = Fork();
562         if (pid == 0) {
563             VOL_UNLOCK;
564             ret = DoSalvageVolume(node, slot);
565             Exit(ret);
566         } else if (pid < 0) {
567             Log("failed to fork child worker process\n");
568             sleep(1);
569             goto do_fork;
570         } else {
571             child_slot[slot] = pid;
572             node->pid = pid;
573             VOL_UNLOCK;
574
575             MUTEX_ENTER(&worker_lock);
576             current_workers++;
577
578             /* let the reaper thread know another worker was spawned */
579             CV_BROADCAST(&worker_cv);
580
581             /* if we're overquota, wait for the reaper */
582             while (current_workers >= Parallel) {
583                 CV_WAIT(&worker_cv, &worker_lock);
584             }
585             MUTEX_EXIT(&worker_lock);
586         }
587     }
588 }
589
590 static int
591 DoSalvageVolume(struct SalvageQueueNode * node, int slot)
592 {
593     char childLog[AFSDIR_PATH_MAX];
594     struct DiskPartition64 * partP;
595
596     /* do not allow further forking inside salvager */
597     canfork = 0;
598
599     /* do not attempt to close parent's logFile handle as
600      * another thread may have held the lock on the FILE
601      * structure when fork was called! */
602
603     afs_snprintf(childLog, sizeof(childLog), "%s.%d",
604                  AFSDIR_SERVER_SLVGLOG_FILEPATH, getpid());
605
606     logFile = afs_fopen(childLog, "a");
607     if (!logFile) {             /* still nothing, use stdout */
608         logFile = stdout;
609         ShowLog = 0;
610     }
611
612     if (node->command.sop.parent <= 0) {
613         Log("salvageServer: invalid volume id specified; salvage aborted\n");
614         return 1;
615     }
616
617     partP = VGetPartition(node->command.sop.partName, 0);
618     if (!partP) {
619         Log("salvageServer: Unknown or unmounted partition %s; salvage aborted\n",
620             node->command.sop.partName);
621         return 1;
622     }
623
624     /* obtain a shared salvage lock in the child worker, so if the
625      * salvageserver restarts (and we continue), we will still hold a lock and
626      * prevent standalone salvagers from interfering */
627     ObtainSharedSalvageLock();
628
629     /* Salvage individual volume; don't notify fs */
630     SalvageFileSys1(partP, node->command.sop.parent);
631
632     fclose(logFile);
633     return 0;
634 }
635
636
637 static void *
638 SalvageChildReaperThread(void * args)
639 {
640     int slot, pid, status;
641     struct log_cleanup_node * cleanup;
642
643     MUTEX_ENTER(&worker_lock);
644
645     /* loop reaping our children */
646     while (1) {
647         /* wait() won't block unless we have children, so
648          * block on the cond var if we're childless */
649         while (current_workers == 0) {
650             CV_WAIT(&worker_cv, &worker_lock);
651         }
652
653         MUTEX_EXIT(&worker_lock);
654
655         cleanup = (struct log_cleanup_node *) malloc(sizeof(struct log_cleanup_node));
656
657         while (Reap_Child("salvageserver", &pid, &status) < 0) {
658             /* try to prevent livelock if something goes wrong */
659             sleep(1);
660         }
661
662         VOL_LOCK;
663         for (slot = 0; slot < Parallel; slot++) {
664             if (child_slot[slot] == pid)
665                 break;
666         }
667         osi_Assert(slot < Parallel);
668         child_slot[slot] = 0;
669         VOL_UNLOCK;
670
671         SALVSYNC_doneWorkByPid(pid, status);
672
673         MUTEX_ENTER(&worker_lock);
674
675         if (cleanup) {
676             cleanup->pid = pid;
677             queue_Append(&log_cleanup_queue, cleanup);
678             CV_SIGNAL(&log_cleanup_queue.queue_change_cv);
679         }
680
681         /* ok, we've reaped a child */
682         current_workers--;
683         CV_BROADCAST(&worker_cv);
684     }
685
686     return NULL;
687 }
688
689 static int
690 Reap_Child(char *prog, int * pid, int * status)
691 {
692     int ret;
693     ret = wait(status);
694
695     if (ret >= 0) {
696         *pid = ret;
697         if (WCOREDUMP(*status))
698             Log("\"%s\" core dumped!\n", prog);
699         if ((WIFSIGNALED(*status) != 0) ||
700             ((WEXITSTATUS(*status) != 0) &&
701              (WEXITSTATUS(*status) != SALSRV_EXIT_VOLGROUP_LINK)))
702             Log("\"%s\" (pid=%d) terminated abnormally!\n", prog, ret);
703     } else {
704         Log("wait returned -1\n");
705     }
706     return ret;
707 }
708
709 /*
710  * thread to combine salvager child logs
711  * back into the main salvageserver log
712  */
713 static void *
714 SalvageLogCleanupThread(void * arg)
715 {
716     struct log_cleanup_node * cleanup;
717
718     MUTEX_ENTER(&worker_lock);
719
720     while (1) {
721         while (queue_IsEmpty(&log_cleanup_queue)) {
722             CV_WAIT(&log_cleanup_queue.queue_change_cv, &worker_lock);
723         }
724
725         while (queue_IsNotEmpty(&log_cleanup_queue)) {
726             cleanup = queue_First(&log_cleanup_queue, log_cleanup_node);
727             queue_Remove(cleanup);
728             MUTEX_EXIT(&worker_lock);
729             SalvageLogCleanup(cleanup->pid);
730             free(cleanup);
731             MUTEX_ENTER(&worker_lock);
732         }
733     }
734
735     MUTEX_EXIT(&worker_lock);
736     return NULL;
737 }
738
739 #define LOG_XFER_BUF_SIZE 65536
740 static int
741 SalvageLogCleanup(int pid)
742 {
743     int pidlog, len;
744     char fn[AFSDIR_PATH_MAX];
745     static char buf[LOG_XFER_BUF_SIZE];
746
747     afs_snprintf(fn, sizeof(fn), "%s.%d",
748                  AFSDIR_SERVER_SLVGLOG_FILEPATH, pid);
749
750
751     pidlog = open(fn, O_RDONLY);
752     unlink(fn);
753     if (pidlog < 0)
754         return 1;
755
756     len = read(pidlog, buf, LOG_XFER_BUF_SIZE);
757     while (len) {
758         fwrite(buf, len, 1, logFile);
759         len = read(pidlog, buf, LOG_XFER_BUF_SIZE);
760     }
761
762     close(pidlog);
763
764     return 0;
765 }
766
767 /* wake up every five minutes to see if a non-child salvage has finished */
768 #define SALVAGE_SCAN_POLL_INTERVAL 300
769
770 /**
771  * Thread to look for SalvageLog.$pid files that are not from our child
772  * worker salvagers, and notify SalvageLogCleanupThread to clean them
773  * up. This can happen if we restart during salvages, or the
774  * salvageserver crashes or something.
775  *
776  * @param arg  unused
777  *
778  * @return always NULL
779  */
780 static void *
781 SalvageLogScanningThread(void * arg)
782 {
783     struct rx_queue log_watch_queue;
784
785     queue_Init(&log_watch_queue);
786
787     {
788         DIR *dp;
789         struct dirent *dirp;
790         char prefix[AFSDIR_PATH_MAX];
791         size_t prefix_len;
792
793         afs_snprintf(prefix, sizeof(prefix), "%s.", AFSDIR_SLVGLOG_FILE);
794         prefix_len = strlen(prefix);
795
796         dp = opendir(AFSDIR_LOGS_DIR);
797         osi_Assert(dp);
798
799         while ((dirp = readdir(dp)) != NULL) {
800             pid_t pid;
801             struct log_cleanup_node *cleanup;
802             int i;
803
804             if (strncmp(dirp->d_name, prefix, prefix_len) != 0) {
805                 /* not a salvage logfile; skip */
806                 continue;
807             }
808
809             errno = 0;
810             pid = strtol(dirp->d_name + prefix_len, NULL, 10);
811
812             if (errno != 0) {
813                 /* file is SalvageLog.<something> but <something> isn't
814                  * a pid, so skip */
815                  continue;
816             }
817
818             VOL_LOCK;
819             for (i = 0; i < Parallel; ++i) {
820                 if (pid == child_slot[i]) {
821                     break;
822                 }
823             }
824             VOL_UNLOCK;
825             if (i < Parallel) {
826                 /* this pid is one of our children, so the reaper thread
827                  * will take care of it; skip */
828                 continue;
829             }
830
831             cleanup =
832                 (struct log_cleanup_node *) malloc(sizeof(struct log_cleanup_node));
833             cleanup->pid = pid;
834
835             queue_Append(&log_watch_queue, cleanup);
836         }
837
838         closedir(dp);
839     }
840
841     ScanLogs(&log_watch_queue);
842
843     while (queue_IsNotEmpty(&log_watch_queue)) {
844         sleep(SALVAGE_SCAN_POLL_INTERVAL);
845         ScanLogs(&log_watch_queue);
846     }
847
848     return NULL;
849 }
850
851 /**
852  * look through log_watch_queue, and if any processes are not still
853  * running, hand them off to the SalvageLogCleanupThread
854  *
855  * @param log_watch_queue  a queue of PIDs that we should clean up if
856  * that PID has died
857  */
858 static void
859 ScanLogs(struct rx_queue *log_watch_queue)
860 {
861     struct log_cleanup_node *cleanup, *next;
862
863     MUTEX_ENTER(&worker_lock);
864
865     for (queue_Scan(log_watch_queue, cleanup, next, log_cleanup_node)) {
866         /* if a process is still running, assume it's the salvage process
867          * still going, and keep waiting for it */
868         if (kill(cleanup->pid, 0) < 0 && errno == ESRCH) {
869             queue_Remove(cleanup);
870             queue_Append(&log_cleanup_queue, cleanup);
871             CV_SIGNAL(&log_cleanup_queue.queue_change_cv);
872         }
873     }
874
875     MUTEX_EXIT(&worker_lock);
876 }