2 * Copyright 2006-2007, Sine Nomine Associates and others.
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
12 * online salvager daemon
15 /* Main program file. Define globals. */
18 #include <afsconfig.h>
19 #include <afs/param.h>
32 #include <WINNT/afsevent.h>
34 #include <sys/param.h>
38 #endif /* ITIMER_REAL */
41 #define WCOREDUMP(x) ((x) & 0200)
44 #include <afs/afsint.h>
45 #include <afs/afs_assert.h>
46 #if !defined(AFS_SGI_ENV) && !defined(AFS_NT40_ENV)
47 #if defined(AFS_VFSINCL_ENV)
48 #include <sys/vnode.h>
50 #include <sys/fs/ufs_inode.h>
52 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
53 #include <ufs/ufs/dinode.h>
54 #include <ufs/ffs/fs.h>
56 #include <ufs/inode.h>
59 #else /* AFS_VFSINCL_ENV */
61 #include <ufs/inode.h>
62 #else /* AFS_OSF_ENV */
63 #if !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV) && !defined(AFS_ARM_DARWIN_ENV)
64 #include <sys/inode.h>
67 #endif /* AFS_VFSINCL_ENV */
68 #endif /* AFS_SGI_ENV */
71 #include <sys/lockf.h>
75 #include <checklist.h>
77 #if defined(AFS_SGI_ENV)
82 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
85 #include <sys/mnttab.h>
86 #include <sys/mntent.h>
91 #endif /* AFS_SGI_ENV */
92 #endif /* AFS_HPUX_ENV */
97 #include <afs/osi_inode.h>
100 #include <afs/afsutil.h>
101 #include <afs/fileutil.h>
102 #include <afs/procmgmt.h> /* signal(), kill(), wait(), etc. */
111 #include <afs/afssyscalls.h>
115 #include "partition.h"
116 #include "daemon_com.h"
118 #include "salvsync.h"
119 #include "viceinode.h"
121 #include "vol-salvage.h"
128 #if !defined(AFS_DEMAND_ATTACH_FS)
129 #error "online salvager only supported for demand attach fileserver"
130 #endif /* AFS_DEMAND_ATTACH_FS */
132 #if defined(AFS_NT40_ENV)
133 #error "online salvager not supported on NT"
134 #endif /* AFS_NT40_ENV */
136 /*@+fcnmacros +macrofcndecl@*/
138 #define afs_fopen fopen64
139 #else /* !O_LARGEFILE */
140 #define afs_fopen fopen
141 #endif /* !O_LARGEFILE */
142 /*@=fcnmacros =macrofcndecl@*/
146 static volatile int current_workers = 0;
147 static volatile struct rx_queue pending_q;
148 static pthread_mutex_t worker_lock;
149 static pthread_cond_t worker_cv;
151 static void * SalvageChildReaperThread(void *);
152 static int DoSalvageVolume(struct SalvageQueueNode * node, int slot);
154 static void SalvageServer(int argc, char **argv);
155 static void SalvageClient(VolumeId vid, char * pname);
157 static int Reap_Child(char * prog, int * pid, int * status);
159 static void * SalvageLogCleanupThread(void *);
160 static int SalvageLogCleanup(int pid);
162 static void * SalvageLogScanningThread(void *);
163 static void ScanLogs(struct rx_queue *log_watch_queue);
165 struct cmdline_rock {
170 struct log_cleanup_node {
176 struct rx_queue queue_head;
177 pthread_cond_t queue_change_cv;
181 #define DEFAULT_PARALLELISM 4 /* allow 4 parallel salvage workers by default */
184 handleit(struct cmd_syndesc *as, void *arock)
187 char pname[100], *temp;
188 afs_int32 seenpart = 0, seenvol = 0;
190 struct cmdline_rock *rock = (struct cmdline_rock *)arock;
192 #ifdef AFS_SGI_VNODE_GLUE
193 if (afs_init_kernel_config(-1) < 0) {
195 ("Can't determine NUMA configuration, not starting salvager.\n");
200 if (as->parms[2].items) /* -debug */
202 if (as->parms[3].items) /* -nowrite */
204 if (as->parms[4].items) /* -inodes */
206 if (as->parms[5].items) /* -oktozap */
208 if (as->parms[6].items) /* -rootinodes */
210 if (as->parms[8].items) /* -ForceReads */
212 if ((ti = as->parms[9].items)) { /* -Parallel # */
214 if (strncmp(temp, "all", 3) == 0) {
218 if (strlen(temp) != 0) {
219 Parallel = atoi(temp);
222 if (Parallel > MAXPARALLEL) {
223 printf("Setting parallel salvages to maximum of %d \n",
225 Parallel = MAXPARALLEL;
229 Parallel = MIN(DEFAULT_PARALLELISM, MAXPARALLEL);
231 if ((ti = as->parms[10].items)) { /* -tmpdir */
235 dirp = opendir(tmpdir);
238 ("Can't open temporary placeholder dir %s; using current partition \n",
244 if ((ti = as->parms[11].items)) /* -showlog */
246 if ((ti = as->parms[12].items)) { /* -orphans */
248 orphans = ORPH_IGNORE;
249 else if (strcmp(ti->data, "remove") == 0
250 || strcmp(ti->data, "r") == 0)
251 orphans = ORPH_REMOVE;
252 else if (strcmp(ti->data, "attach") == 0
253 || strcmp(ti->data, "a") == 0)
254 orphans = ORPH_ATTACH;
256 #ifndef AFS_NT40_ENV /* ignore options on NT */
257 if ((ti = as->parms[13].items)) { /* -syslog */
261 if ((ti = as->parms[14].items)) { /* -syslogfacility */
262 useSyslogFacility = atoi(ti->data);
265 if ((ti = as->parms[15].items)) { /* -datelogs */
266 TimeStampLogFile((char *)AFSDIR_SERVER_SALSRVLOG_FILEPATH);
270 if ((ti = as->parms[16].items)) { /* -client */
271 if ((ti = as->parms[0].items)) { /* -partition */
273 strlcpy(pname, ti->data, sizeof(pname));
275 if ((ti = as->parms[1].items)) { /* -volumeid */
279 vid_l = strtoul(ti->data, &end, 10);
280 if (vid_l >= MAX_AFS_UINT32 || vid_l == ULONG_MAX || *end != '\0') {
281 printf("Invalid volume id specified; salvage aborted\n");
284 vid = (VolumeId)vid_l;
288 printf("-showlog does not work with -client\n");
292 if (!seenpart || !seenvol) {
293 printf("You must specify '-partition' and '-volumeid' with the '-client' option\n");
297 SalvageClient(vid, pname);
299 } else { /* salvageserver mode */
300 SalvageServer(rock->argc, rock->argv);
307 #include "AFS_component_version_number.c"
311 char *save_args[MAX_ARGS];
313 pthread_t main_thread;
317 main(int argc, char **argv)
319 struct cmd_syndesc *ts;
321 struct cmdline_rock arock;
325 * The following signal action for AIX is necessary so that in case of a
326 * crash (i.e. core is generated) we can include the user's data section
327 * in the core dump. Unfortunately, by default, only a partial core is
328 * generated which, in many cases, isn't too useful.
330 struct sigaction nsa;
332 sigemptyset(&nsa.sa_mask);
333 nsa.sa_handler = SIG_DFL;
334 nsa.sa_flags = SA_FULLDUMP;
335 sigaction(SIGABRT, &nsa, NULL);
336 sigaction(SIGSEGV, &nsa, NULL);
339 /* Initialize directory paths */
340 if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
342 ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
344 fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
349 /* Default to binary mode for fopen() */
350 _set_fmode(_O_BINARY);
352 main_thread = pthread_self();
353 if (spawnDatap && spawnDataLen) {
354 /* This is a child per partition salvager. Don't setup log or
355 * try to lock the salvager lock.
357 if (nt_SetupPartitionSalvage(spawnDatap, spawnDataLen) < 0)
363 if (geteuid() != 0) {
364 printf("Salvager must be run as root.\n");
370 /* bad for normal help flag processing, but can do nada */
379 ts = cmd_CreateSyntax("initcmd", handleit, &arock, "initialize the program");
380 cmd_AddParm(ts, "-partition", CMD_SINGLE, CMD_OPTIONAL,
381 "Name of partition to salvage");
382 cmd_AddParm(ts, "-volumeid", CMD_SINGLE, CMD_OPTIONAL,
383 "Volume Id to salvage");
384 cmd_AddParm(ts, "-debug", CMD_FLAG, CMD_OPTIONAL,
385 "Run in Debugging mode");
386 cmd_AddParm(ts, "-nowrite", CMD_FLAG, CMD_OPTIONAL,
387 "Run readonly/test mode");
388 cmd_AddParm(ts, "-inodes", CMD_FLAG, CMD_OPTIONAL,
389 "Just list affected afs inodes - debugging flag");
390 cmd_AddParm(ts, "-oktozap", CMD_FLAG, CMD_OPTIONAL,
391 "Give permission to destroy bogus inodes/volumes - debugging flag");
392 cmd_AddParm(ts, "-rootinodes", CMD_FLAG, CMD_OPTIONAL,
393 "Show inodes owned by root - debugging flag");
394 cmd_AddParm(ts, "-salvagedirs", CMD_FLAG, CMD_OPTIONAL,
395 "Force rebuild/salvage of all directories");
396 cmd_AddParm(ts, "-blockreads", CMD_FLAG, CMD_OPTIONAL,
397 "Read smaller blocks to handle IO/bad blocks");
398 cmd_AddParm(ts, "-parallel", CMD_SINGLE, CMD_OPTIONAL,
399 "# of max parallel partition salvaging");
400 cmd_AddParm(ts, "-tmpdir", CMD_SINGLE, CMD_OPTIONAL,
401 "Name of dir to place tmp files ");
402 cmd_AddParm(ts, "-showlog", CMD_FLAG, CMD_OPTIONAL,
403 "Show log file upon completion");
404 cmd_AddParm(ts, "-orphans", CMD_SINGLE, CMD_OPTIONAL,
405 "ignore | remove | attach");
407 /* note - syslog isn't avail on NT, but if we make it conditional, have
408 * to deal with screwy offsets for cmd params */
409 cmd_AddParm(ts, "-syslog", CMD_FLAG, CMD_OPTIONAL,
410 "Write salvage log to syslogs");
411 cmd_AddParm(ts, "-syslogfacility", CMD_SINGLE, CMD_OPTIONAL,
412 "Syslog facility number to use");
413 cmd_AddParm(ts, "-datelogs", CMD_FLAG, CMD_OPTIONAL,
414 "Include timestamp in logfile filename");
416 cmd_AddParm(ts, "-client", CMD_FLAG, CMD_OPTIONAL,
417 "Use SALVSYNC to ask salvageserver to salvage a volume");
419 err = cmd_Dispatch(argc, argv);
421 return 0; /* not reached */
425 SalvageClient(VolumeId vid, char * pname)
430 SALVSYNC_response_hdr sres;
431 VolumePackageOptions opts;
433 VOptDefaults(volumeUtility, &opts);
434 if (VInitVolumePackage2(volumeUtility, &opts)) {
435 /* VInitVolumePackage2 can fail on e.g. partition attachment errors,
436 * but we don't really care, since all we're doing is trying to use
438 fprintf(stderr, "errors encountered initializing volume package, but "
439 "trying to continue anyway\n");
441 SALVSYNC_clientInit();
443 code = SALVSYNC_SalvageVolume(vid, pname, SALVSYNC_SALVAGE, SALVSYNC_OPERATOR, 0, NULL);
444 if (code != SYNC_OK) {
448 res.payload.buf = (void *) &sres;
449 res.payload.len = sizeof(sres);
453 code = SALVSYNC_SalvageVolume(vid, pname, SALVSYNC_QUERY, SALVSYNC_WHATEVER, 0, &res);
454 if (code != SYNC_OK) {
457 switch (sres.state) {
458 case SALVSYNC_STATE_ERROR:
459 printf("salvageserver reports salvage ended in an error; check log files for more details\n");
460 case SALVSYNC_STATE_DONE:
461 case SALVSYNC_STATE_UNKNOWN:
465 SALVSYNC_clientFinis();
469 if (code == SYNC_DENIED) {
470 printf("salvageserver refused to salvage volume %u on partition %s\n",
472 } else if (code == SYNC_BAD_COMMAND) {
473 printf("SALVSYNC protocol mismatch; please make sure fileserver, volserver, salvageserver and salvager are same version\n");
474 } else if (code == SYNC_COM_ERROR) {
475 printf("SALVSYNC communications error\n");
477 SALVSYNC_clientFinis();
481 static int * child_slot;
484 SalvageServer(int argc, char **argv)
487 struct SalvageQueueNode * node;
489 pthread_attr_t attrs;
491 VolumePackageOptions opts;
493 /* All entries to the log will be appended. Useful if there are
494 * multiple salvagers appending to the log.
497 CheckLogFile((char *)AFSDIR_SERVER_SALSRVLOG_FILEPATH);
499 #ifdef AFS_LINUX20_ENV
500 fcntl(fileno(logFile), F_SETFL, O_APPEND); /* Isn't this redundant? */
502 fcntl(fileno(logFile), F_SETFL, FAPPEND); /* Isn't this redundant? */
507 fprintf(logFile, "%s\n", cml_version_number);
508 LogCommandLine(argc, argv, "Online Salvage Server",
509 SalvageVersion, "Starting OpenAFS", Log);
510 /* Get and hold a lock for the duration of the salvage to make sure
511 * that no other salvage runs at the same time. The routine
512 * VInitVolumePackage2 (called below) makes sure that a file server or
513 * other volume utilities don't interfere with the salvage.
516 /* even demand attach online salvager
517 * still needs this because we don't want
518 * a stand-alone salvager to conflict with
519 * the salvager daemon */
520 ObtainSharedSalvageLock();
522 child_slot = (int *) malloc(Parallel * sizeof(int));
523 osi_Assert(child_slot != NULL);
524 memset(child_slot, 0, Parallel * sizeof(int));
526 /* initialize things */
527 VOptDefaults(salvageServer, &opts);
528 if (VInitVolumePackage2(salvageServer, &opts)) {
529 Log("Shutting down: errors encountered initializing volume package\n");
533 queue_Init(&pending_q);
534 queue_Init(&log_cleanup_queue);
535 MUTEX_INIT(&worker_lock, "worker", MUTEX_DEFAULT, 0);
536 CV_INIT(&worker_cv, "worker", CV_DEFAULT, 0);
537 CV_INIT(&log_cleanup_queue.queue_change_cv, "queuechange", CV_DEFAULT, 0);
538 osi_Assert(pthread_attr_init(&attrs) == 0);
540 /* start up the reaper and log cleaner threads */
541 osi_Assert(pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED) == 0);
542 osi_Assert(pthread_create(&tid,
544 &SalvageChildReaperThread,
546 osi_Assert(pthread_create(&tid,
548 &SalvageLogCleanupThread,
550 osi_Assert(pthread_create(&tid,
552 &SalvageLogScanningThread,
555 /* loop forever serving requests */
557 node = SALVSYNC_getWork();
558 osi_Assert(node != NULL);
560 Log("dispatching child to salvage volume %u...\n",
561 node->command.sop.parent);
565 for (slot = 0; slot < Parallel; slot++) {
566 if (!child_slot[slot])
569 osi_Assert (slot < Parallel);
575 ret = DoSalvageVolume(node, slot);
577 } else if (pid < 0) {
578 Log("failed to fork child worker process\n");
582 child_slot[slot] = pid;
586 MUTEX_ENTER(&worker_lock);
589 /* let the reaper thread know another worker was spawned */
590 CV_BROADCAST(&worker_cv);
592 /* if we're overquota, wait for the reaper */
593 while (current_workers >= Parallel) {
594 CV_WAIT(&worker_cv, &worker_lock);
596 MUTEX_EXIT(&worker_lock);
602 DoSalvageVolume(struct SalvageQueueNode * node, int slot)
604 char childLog[AFSDIR_PATH_MAX];
605 struct DiskPartition64 * partP;
607 /* do not allow further forking inside salvager */
610 /* do not attempt to close parent's logFile handle as
611 * another thread may have held the lock on the FILE
612 * structure when fork was called! */
614 snprintf(childLog, sizeof(childLog), "%s.%d",
615 AFSDIR_SERVER_SLVGLOG_FILEPATH, getpid());
617 logFile = afs_fopen(childLog, "a");
618 if (!logFile) { /* still nothing, use stdout */
623 if (node->command.sop.parent <= 0) {
624 Log("salvageServer: invalid volume id specified; salvage aborted\n");
628 partP = VGetPartition(node->command.sop.partName, 0);
630 Log("salvageServer: Unknown or unmounted partition %s; salvage aborted\n",
631 node->command.sop.partName);
635 /* obtain a shared salvage lock in the child worker, so if the
636 * salvageserver restarts (and we continue), we will still hold a lock and
637 * prevent standalone salvagers from interfering */
638 ObtainSharedSalvageLock();
640 /* Salvage individual volume; don't notify fs */
641 SalvageFileSys1(partP, node->command.sop.parent);
649 SalvageChildReaperThread(void * args)
651 int slot, pid, status;
652 struct log_cleanup_node * cleanup;
654 MUTEX_ENTER(&worker_lock);
656 /* loop reaping our children */
658 /* wait() won't block unless we have children, so
659 * block on the cond var if we're childless */
660 while (current_workers == 0) {
661 CV_WAIT(&worker_cv, &worker_lock);
664 MUTEX_EXIT(&worker_lock);
666 cleanup = (struct log_cleanup_node *) malloc(sizeof(struct log_cleanup_node));
668 while (Reap_Child("salvageserver", &pid, &status) < 0) {
669 /* try to prevent livelock if something goes wrong */
674 for (slot = 0; slot < Parallel; slot++) {
675 if (child_slot[slot] == pid)
678 osi_Assert(slot < Parallel);
679 child_slot[slot] = 0;
682 SALVSYNC_doneWorkByPid(pid, status);
684 MUTEX_ENTER(&worker_lock);
688 queue_Append(&log_cleanup_queue, cleanup);
689 CV_SIGNAL(&log_cleanup_queue.queue_change_cv);
692 /* ok, we've reaped a child */
694 CV_BROADCAST(&worker_cv);
701 Reap_Child(char *prog, int * pid, int * status)
708 if (WCOREDUMP(*status))
709 Log("\"%s\" core dumped!\n", prog);
710 if ((WIFSIGNALED(*status) != 0) ||
711 ((WEXITSTATUS(*status) != 0) &&
712 (WEXITSTATUS(*status) != SALSRV_EXIT_VOLGROUP_LINK)))
713 Log("\"%s\" (pid=%d) terminated abnormally!\n", prog, ret);
715 Log("wait returned -1\n");
721 * thread to combine salvager child logs
722 * back into the main salvageserver log
725 SalvageLogCleanupThread(void * arg)
727 struct log_cleanup_node * cleanup;
729 MUTEX_ENTER(&worker_lock);
732 while (queue_IsEmpty(&log_cleanup_queue)) {
733 CV_WAIT(&log_cleanup_queue.queue_change_cv, &worker_lock);
736 while (queue_IsNotEmpty(&log_cleanup_queue)) {
737 cleanup = queue_First(&log_cleanup_queue, log_cleanup_node);
738 queue_Remove(cleanup);
739 MUTEX_EXIT(&worker_lock);
740 SalvageLogCleanup(cleanup->pid);
742 MUTEX_ENTER(&worker_lock);
746 MUTEX_EXIT(&worker_lock);
750 #define LOG_XFER_BUF_SIZE 65536
752 SalvageLogCleanup(int pid)
755 char fn[AFSDIR_PATH_MAX];
756 static char buf[LOG_XFER_BUF_SIZE];
758 snprintf(fn, sizeof(fn), "%s.%d",
759 AFSDIR_SERVER_SLVGLOG_FILEPATH, pid);
762 pidlog = open(fn, O_RDONLY);
767 len = read(pidlog, buf, LOG_XFER_BUF_SIZE);
769 fwrite(buf, len, 1, logFile);
770 len = read(pidlog, buf, LOG_XFER_BUF_SIZE);
778 /* wake up every five minutes to see if a non-child salvage has finished */
779 #define SALVAGE_SCAN_POLL_INTERVAL 300
782 * Thread to look for SalvageLog.$pid files that are not from our child
783 * worker salvagers, and notify SalvageLogCleanupThread to clean them
784 * up. This can happen if we restart during salvages, or the
785 * salvageserver crashes or something.
789 * @return always NULL
792 SalvageLogScanningThread(void * arg)
794 struct rx_queue log_watch_queue;
796 queue_Init(&log_watch_queue);
801 char prefix[AFSDIR_PATH_MAX];
804 snprintf(prefix, sizeof(prefix), "%s.", AFSDIR_SLVGLOG_FILE);
805 prefix_len = strlen(prefix);
807 dp = opendir(AFSDIR_LOGS_DIR);
810 while ((dirp = readdir(dp)) != NULL) {
812 struct log_cleanup_node *cleanup;
815 if (strncmp(dirp->d_name, prefix, prefix_len) != 0) {
816 /* not a salvage logfile; skip */
821 pid = strtol(dirp->d_name + prefix_len, NULL, 10);
824 /* file is SalvageLog.<something> but <something> isn't
830 for (i = 0; i < Parallel; ++i) {
831 if (pid == child_slot[i]) {
837 /* this pid is one of our children, so the reaper thread
838 * will take care of it; skip */
843 (struct log_cleanup_node *) malloc(sizeof(struct log_cleanup_node));
846 queue_Append(&log_watch_queue, cleanup);
852 ScanLogs(&log_watch_queue);
854 while (queue_IsNotEmpty(&log_watch_queue)) {
855 sleep(SALVAGE_SCAN_POLL_INTERVAL);
856 ScanLogs(&log_watch_queue);
863 * look through log_watch_queue, and if any processes are not still
864 * running, hand them off to the SalvageLogCleanupThread
866 * @param log_watch_queue a queue of PIDs that we should clean up if
870 ScanLogs(struct rx_queue *log_watch_queue)
872 struct log_cleanup_node *cleanup, *next;
874 MUTEX_ENTER(&worker_lock);
876 for (queue_Scan(log_watch_queue, cleanup, next, log_cleanup_node)) {
877 /* if a process is still running, assume it's the salvage process
878 * still going, and keep waiting for it */
879 if (kill(cleanup->pid, 0) < 0 && errno == ESRCH) {
880 queue_Remove(cleanup);
881 queue_Append(&log_cleanup_queue, cleanup);
882 CV_SIGNAL(&log_cleanup_queue.queue_change_cv);
886 MUTEX_EXIT(&worker_lock);