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