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