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