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