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