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