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