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