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>
23 #ifdef HAVE_SYS_FILE_H
28 #include <WINNT/afsevent.h>
32 #define WCOREDUMP(x) ((x) & 0200)
37 #include <afs/afsint.h>
38 #include <rx/rx_queue.h>
40 #if !defined(AFS_SGI_ENV) && !defined(AFS_NT40_ENV)
41 #if defined(AFS_VFSINCL_ENV)
42 #include <sys/vnode.h>
44 #include <sys/fs/ufs_inode.h>
46 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
47 #include <ufs/ufs/dinode.h>
48 #include <ufs/ffs/fs.h>
50 #include <ufs/inode.h>
53 #else /* AFS_VFSINCL_ENV */
55 #include <ufs/inode.h>
56 #else /* AFS_OSF_ENV */
57 #if !defined(AFS_LINUX20_ENV) && !defined(AFS_XBSD_ENV) && !defined(AFS_DARWIN_ENV)
58 #include <sys/inode.h>
61 #endif /* AFS_VFSINCL_ENV */
62 #endif /* AFS_SGI_ENV */
65 #include <sys/lockf.h>
68 #include <checklist.h>
70 #if defined(AFS_SGI_ENV)
73 #if defined(AFS_SUN_ENV) || defined(AFS_SUN5_ENV)
75 #include <sys/mnttab.h>
76 #include <sys/mntent.h>
81 #endif /* AFS_SGI_ENV */
82 #endif /* AFS_HPUX_ENV */
86 #include <afs/osi_inode.h>
89 #include <afs/afsutil.h>
90 #include <afs/fileutil.h>
91 #include <afs/procmgmt.h> /* signal(), kill(), wait(), etc. */
97 #include <afs/afssyscalls.h>
101 #include "partition.h"
102 #include "daemon_com.h"
104 #include "salvsync.h"
105 #include "viceinode.h"
107 #include "vol-salvage.h"
114 #if !defined(AFS_DEMAND_ATTACH_FS)
115 #error "online salvager only supported for demand attach fileserver"
116 #endif /* AFS_DEMAND_ATTACH_FS */
118 #if defined(AFS_NT40_ENV)
119 #error "online salvager not supported on NT"
120 #endif /* AFS_NT40_ENV */
122 /*@+fcnmacros +macrofcndecl@*/
124 #define afs_fopen fopen64
125 #else /* !O_LARGEFILE */
126 #define afs_fopen fopen
127 #endif /* !O_LARGEFILE */
128 /*@=fcnmacros =macrofcndecl@*/
132 static volatile int current_workers = 0;
133 static volatile struct rx_queue pending_q;
134 static pthread_mutex_t worker_lock;
135 static pthread_cond_t worker_cv;
137 static void * SalvageChildReaperThread(void *);
138 static int DoSalvageVolume(struct SalvageQueueNode * node, int slot);
140 static void SalvageServer(int argc, char **argv);
141 static void SalvageClient(VolumeId vid, char * pname);
143 static int Reap_Child(char * prog, int * pid, int * status);
145 static void * SalvageLogCleanupThread(void *);
146 static int SalvageLogCleanup(int pid);
148 static void * SalvageLogScanningThread(void *);
149 static void ScanLogs(struct rx_queue *log_watch_queue);
151 struct cmdline_rock {
156 struct log_cleanup_node {
162 struct rx_queue queue_head;
163 pthread_cond_t queue_change_cv;
167 #define DEFAULT_PARALLELISM 4 /* allow 4 parallel salvage workers by default */
190 handleit(struct cmd_syndesc *opts, void *arock)
192 char pname[100], *temp;
193 afs_int32 seenpart = 0, seenvol = 0;
195 struct cmdline_rock *rock = (struct cmdline_rock *)arock;
196 char *optstring = NULL;
198 #ifdef AFS_SGI_VNODE_GLUE
199 if (afs_init_kernel_config(-1) < 0) {
201 ("Can't determine NUMA configuration, not starting salvager.\n");
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_blockreads, &forceR);
212 if (cmd_OptionAsString(opts, OPT_parallel, &optstring) == 0) {
213 if (strncmp(optstring, "all", 3) == 0) {
217 if (strlen(optstring) != 0) {
218 Parallel = atoi(optstring);
221 if (Parallel > MAXPARALLEL) {
222 printf("Setting parallel salvages to maximum of %d \n",
224 Parallel = MAXPARALLEL;
230 Parallel = min(DEFAULT_PARALLELISM, MAXPARALLEL);
232 if (cmd_OptionAsString(opts, OPT_tmpdir, &optstring) == 0) {
234 dirp = opendir(optstring);
237 ("Can't open temporary placeholder dir %s; using current partition \n",
245 cmd_OptionAsFlag(opts, OPT_showlog, &ShowLog);
246 if (cmd_OptionAsString(opts, OPT_orphans, &optstring) == 0) {
248 orphans = ORPH_IGNORE;
249 else if (strcmp(optstring, "remove") == 0
250 || strcmp(optstring, "r") == 0)
251 orphans = ORPH_REMOVE;
252 else if (strcmp(optstring, "attach") == 0
253 || strcmp(optstring, "a") == 0)
254 orphans = ORPH_ATTACH;
258 #ifndef AFS_NT40_ENV /* ignore options on NT */
259 if (cmd_OptionPresent(opts, OPT_syslog)) {
263 cmd_OptionAsInt(opts, OPT_syslogfacility, &useSyslogFacility);
265 if (cmd_OptionPresent(opts, OPT_datelogs)) {
266 TimeStampLogFile((char *)AFSDIR_SERVER_SALSRVLOG_FILEPATH);
270 if (cmd_OptionPresent(opts, OPT_client)) {
271 if (cmd_OptionAsString(opts, OPT_partition, &optstring) == 0) {
273 strlcpy(pname, optstring, sizeof(pname));
277 if (cmd_OptionAsString(opts, OPT_volumeid, &optstring) == 0) {
281 vid_l = strtoul(optstring, &end, 10);
282 if (vid_l >= MAX_AFS_UINT32 || vid_l == ULONG_MAX || *end != '\0') {
283 printf("Invalid volume id specified; salvage aborted\n");
286 vid = (VolumeId)vid_l;
290 printf("-showlog does not work with -client\n");
294 if (!seenpart || !seenvol) {
295 printf("You must specify '-partition' and '-volumeid' with the '-client' option\n");
299 SalvageClient(vid, pname);
301 } else { /* salvageserver mode */
302 SalvageServer(rock->argc, rock->argv);
309 #include "AFS_component_version_number.c"
313 char *save_args[MAX_ARGS];
315 pthread_t main_thread;
319 main(int argc, char **argv)
321 struct cmd_syndesc *ts;
323 struct cmdline_rock arock;
327 * The following signal action for AIX is necessary so that in case of a
328 * crash (i.e. core is generated) we can include the user's data section
329 * in the core dump. Unfortunately, by default, only a partial core is
330 * generated which, in many cases, isn't too useful.
332 struct sigaction nsa;
334 sigemptyset(&nsa.sa_mask);
335 nsa.sa_handler = SIG_DFL;
336 nsa.sa_flags = SA_FULLDUMP;
337 sigaction(SIGABRT, &nsa, NULL);
338 sigaction(SIGSEGV, &nsa, NULL);
341 /* Initialize directory paths */
342 if (!(initAFSDirPath() & AFSDIR_SERVER_PATHS_OK)) {
344 ReportErrorEventAlt(AFSEVT_SVR_NO_INSTALL_DIR, 0, argv[0], 0);
346 fprintf(stderr, "%s: Unable to obtain AFS server directory.\n",
351 /* Default to binary mode for fopen() */
352 _set_fmode(_O_BINARY);
354 main_thread = pthread_self();
355 if (spawnDatap && spawnDataLen) {
356 /* This is a child per partition salvager. Don't setup log or
357 * try to lock the salvager lock.
359 if (nt_SetupPartitionSalvage(spawnDatap, spawnDataLen) < 0)
365 if (geteuid() != 0) {
366 printf("Salvager must be run as root.\n");
372 /* bad for normal help flag processing, but can do nada */
381 ts = cmd_CreateSyntax("initcmd", handleit, &arock, "initialize the program");
382 cmd_AddParmAtOffset(ts, OPT_partition, "-partition", CMD_SINGLE,
383 CMD_OPTIONAL, "Name of partition to salvage");
384 cmd_AddParmAtOffset(ts, OPT_volumeid, "-volumeid", CMD_SINGLE, CMD_OPTIONAL,
385 "Volume Id to salvage");
386 cmd_AddParmAtOffset(ts, OPT_debug, "-debug", CMD_FLAG, CMD_OPTIONAL,
387 "Run in Debugging mode");
388 cmd_AddParmAtOffset(ts, OPT_nowrite, "-nowrite", CMD_FLAG, CMD_OPTIONAL,
389 "Run readonly/test mode");
390 cmd_AddParmAtOffset(ts, OPT_inodes, "-inodes", CMD_FLAG, CMD_OPTIONAL,
391 "Just list affected afs inodes - debugging flag");
392 cmd_AddParmAtOffset(ts, OPT_oktozap, "-oktozap", CMD_FLAG, CMD_OPTIONAL,
393 "Give permission to destroy bogus inodes/volumes - debugging flag");
394 cmd_AddParmAtOffset(ts, OPT_rootinodes, "-rootinodes", CMD_FLAG,
395 CMD_OPTIONAL, "Show inodes owned by root - debugging flag");
396 cmd_AddParmAtOffset(ts, OPT_salvagedirs, "-salvagedirs", CMD_FLAG,
397 CMD_OPTIONAL, "Force rebuild/salvage of all directories");
398 cmd_AddParmAtOffset(ts, OPT_blockreads, "-blockreads", CMD_FLAG,
399 CMD_OPTIONAL, "Read smaller blocks to handle IO/bad blocks");
400 cmd_AddParmAtOffset(ts, OPT_parallel, "-parallel", CMD_SINGLE, CMD_OPTIONAL,
401 "# of max parallel partition salvaging");
402 cmd_AddParmAtOffset(ts, OPT_tmpdir, "-tmpdir", CMD_SINGLE, CMD_OPTIONAL,
403 "Name of dir to place tmp files ");
404 cmd_AddParmAtOffset(ts, OPT_showlog, "-showlog", CMD_FLAG, CMD_OPTIONAL,
405 "Show log file upon completion");
406 cmd_AddParmAtOffset(ts, OPT_orphans, "-orphans", CMD_SINGLE, CMD_OPTIONAL,
407 "ignore | remove | attach");
409 #if !defined(AFS_NT40_ENV)
410 cmd_AddParmAtOffset(ts, OPT_syslog, "-syslog", CMD_FLAG, CMD_OPTIONAL,
411 "Write salvage log to syslogs");
412 cmd_AddParmAtOffset(ts, OPT_syslogfacility, "-syslogfacility", CMD_SINGLE,
413 CMD_OPTIONAL, "Syslog facility number to use");
414 cmd_AddParmAtOffset(ts, OPT_datelogs, "-datelogs", CMD_FLAG, CMD_OPTIONAL,
415 "Include timestamp in logfile filename");
418 cmd_AddParmAtOffset(ts, OPT_client, "-client", CMD_FLAG, CMD_OPTIONAL,
419 "Use SALVSYNC to ask salvageserver to salvage a volume");
421 err = cmd_Dispatch(argc, argv);
423 return 0; /* not reached */
427 SalvageClient(VolumeId vid, char * pname)
432 SALVSYNC_response_hdr sres;
433 VolumePackageOptions opts;
435 VOptDefaults(volumeUtility, &opts);
436 if (VInitVolumePackage2(volumeUtility, &opts)) {
437 /* VInitVolumePackage2 can fail on e.g. partition attachment errors,
438 * but we don't really care, since all we're doing is trying to use
440 fprintf(stderr, "errors encountered initializing volume package, but "
441 "trying to continue anyway\n");
443 SALVSYNC_clientInit();
445 code = SALVSYNC_SalvageVolume(vid, pname, SALVSYNC_SALVAGE, SALVSYNC_OPERATOR, 0, NULL);
446 if (code != SYNC_OK) {
450 res.payload.buf = (void *) &sres;
451 res.payload.len = sizeof(sres);
455 code = SALVSYNC_SalvageVolume(vid, pname, SALVSYNC_QUERY, SALVSYNC_WHATEVER, 0, &res);
456 if (code != SYNC_OK) {
459 switch (sres.state) {
460 case SALVSYNC_STATE_ERROR:
461 printf("salvageserver reports salvage ended in an error; check log files for more details\n");
462 case SALVSYNC_STATE_DONE:
463 case SALVSYNC_STATE_UNKNOWN:
467 SALVSYNC_clientFinis();
471 if (code == SYNC_DENIED) {
472 printf("salvageserver refused to salvage volume %u on partition %s\n",
474 } else if (code == SYNC_BAD_COMMAND) {
475 printf("SALVSYNC protocol mismatch; please make sure fileserver, volserver, salvageserver and salvager are same version\n");
476 } else if (code == SYNC_COM_ERROR) {
477 printf("SALVSYNC communications error\n");
479 SALVSYNC_clientFinis();
483 static int * child_slot;
486 SalvageServer(int argc, char **argv)
489 struct SalvageQueueNode * node;
491 pthread_attr_t attrs;
493 VolumePackageOptions opts;
495 /* All entries to the log will be appended. Useful if there are
496 * multiple salvagers appending to the log.
499 CheckLogFile((char *)AFSDIR_SERVER_SALSRVLOG_FILEPATH);
501 #ifdef AFS_LINUX20_ENV
502 fcntl(fileno(logFile), F_SETFL, O_APPEND); /* Isn't this redundant? */
504 fcntl(fileno(logFile), F_SETFL, FAPPEND); /* Isn't this redundant? */
509 fprintf(logFile, "%s\n", cml_version_number);
510 LogCommandLine(argc, argv, "Online Salvage Server",
511 SalvageVersion, "Starting OpenAFS", Log);
512 /* Get and hold a lock for the duration of the salvage to make sure
513 * that no other salvage runs at the same time. The routine
514 * VInitVolumePackage2 (called below) makes sure that a file server or
515 * other volume utilities don't interfere with the salvage.
518 /* even demand attach online salvager
519 * still needs this because we don't want
520 * a stand-alone salvager to conflict with
521 * the salvager daemon */
522 ObtainSharedSalvageLock();
524 child_slot = calloc(Parallel, sizeof(int));
525 opr_Assert(child_slot != NULL);
527 /* initialize things */
528 VOptDefaults(salvageServer, &opts);
529 if (VInitVolumePackage2(salvageServer, &opts)) {
530 Log("Shutting down: errors encountered initializing volume package\n");
534 queue_Init(&pending_q);
535 queue_Init(&log_cleanup_queue);
536 opr_mutex_init(&worker_lock);
537 opr_cv_init(&worker_cv);
538 opr_cv_init(&log_cleanup_queue.queue_change_cv);
539 opr_Verify(pthread_attr_init(&attrs) == 0);
541 /* start up the reaper and log cleaner threads */
542 opr_Verify(pthread_attr_setdetachstate(&attrs,
543 PTHREAD_CREATE_DETACHED) == 0);
544 opr_Verify(pthread_create(&tid, &attrs,
545 &SalvageChildReaperThread, NULL) == 0);
546 opr_Verify(pthread_create(&tid, &attrs,
547 &SalvageLogCleanupThread, NULL) == 0);
548 opr_Verify(pthread_create(&tid, &attrs,
549 &SalvageLogScanningThread, NULL) == 0);
551 /* loop forever serving requests */
553 node = SALVSYNC_getWork();
554 opr_Assert(node != NULL);
556 Log("dispatching child to salvage volume %u...\n",
557 node->command.sop.parent);
561 for (slot = 0; slot < Parallel; slot++) {
562 if (!child_slot[slot])
565 opr_Assert (slot < Parallel);
571 ret = DoSalvageVolume(node, slot);
573 } else if (pid < 0) {
574 Log("failed to fork child worker process\n");
578 child_slot[slot] = pid;
582 opr_mutex_enter(&worker_lock);
585 /* let the reaper thread know another worker was spawned */
586 opr_cv_broadcast(&worker_cv);
588 /* if we're overquota, wait for the reaper */
589 while (current_workers >= Parallel) {
590 opr_cv_wait(&worker_cv, &worker_lock);
592 opr_mutex_exit(&worker_lock);
598 DoSalvageVolume(struct SalvageQueueNode * node, int slot)
600 char childLog[AFSDIR_PATH_MAX];
601 struct DiskPartition64 * partP;
603 /* do not allow further forking inside salvager */
606 /* do not attempt to close parent's logFile handle as
607 * another thread may have held the lock on the FILE
608 * structure when fork was called! */
610 snprintf(childLog, sizeof(childLog), "%s.%d",
611 AFSDIR_SERVER_SLVGLOG_FILEPATH, getpid());
613 logFile = afs_fopen(childLog, "a");
614 if (!logFile) { /* still nothing, use stdout */
619 if (node->command.sop.parent <= 0) {
620 Log("salvageServer: invalid volume id specified; salvage aborted\n");
624 partP = VGetPartition(node->command.sop.partName, 0);
626 Log("salvageServer: Unknown or unmounted partition %s; salvage aborted\n",
627 node->command.sop.partName);
631 /* obtain a shared salvage lock in the child worker, so if the
632 * salvageserver restarts (and we continue), we will still hold a lock and
633 * prevent standalone salvagers from interfering */
634 ObtainSharedSalvageLock();
636 /* Salvage individual volume; don't notify fs */
637 SalvageFileSys1(partP, node->command.sop.parent);
645 SalvageChildReaperThread(void * args)
647 int slot, pid, status;
648 struct log_cleanup_node * cleanup;
650 opr_mutex_enter(&worker_lock);
652 /* loop reaping our children */
654 /* wait() won't block unless we have children, so
655 * block on the cond var if we're childless */
656 while (current_workers == 0) {
657 opr_cv_wait(&worker_cv, &worker_lock);
660 opr_mutex_exit(&worker_lock);
662 cleanup = malloc(sizeof(struct log_cleanup_node));
664 while (Reap_Child("salvageserver", &pid, &status) < 0) {
665 /* try to prevent livelock if something goes wrong */
670 for (slot = 0; slot < Parallel; slot++) {
671 if (child_slot[slot] == pid)
674 opr_Assert(slot < Parallel);
675 child_slot[slot] = 0;
678 SALVSYNC_doneWorkByPid(pid, status);
680 opr_mutex_enter(&worker_lock);
684 queue_Append(&log_cleanup_queue, cleanup);
685 opr_cv_signal(&log_cleanup_queue.queue_change_cv);
688 /* ok, we've reaped a child */
690 opr_cv_broadcast(&worker_cv);
697 Reap_Child(char *prog, int * pid, int * status)
704 if (WCOREDUMP(*status))
705 Log("\"%s\" core dumped!\n", prog);
706 if ((WIFSIGNALED(*status) != 0) ||
707 ((WEXITSTATUS(*status) != 0) &&
708 (WEXITSTATUS(*status) != SALSRV_EXIT_VOLGROUP_LINK)))
709 Log("\"%s\" (pid=%d) terminated abnormally!\n", prog, ret);
711 Log("wait returned -1\n");
717 * thread to combine salvager child logs
718 * back into the main salvageserver log
721 SalvageLogCleanupThread(void * arg)
723 struct log_cleanup_node * cleanup;
725 opr_mutex_enter(&worker_lock);
728 while (queue_IsEmpty(&log_cleanup_queue)) {
729 opr_cv_wait(&log_cleanup_queue.queue_change_cv, &worker_lock);
732 while (queue_IsNotEmpty(&log_cleanup_queue)) {
733 cleanup = queue_First(&log_cleanup_queue, log_cleanup_node);
734 queue_Remove(cleanup);
735 opr_mutex_exit(&worker_lock);
736 SalvageLogCleanup(cleanup->pid);
738 opr_mutex_enter(&worker_lock);
742 opr_mutex_exit(&worker_lock);
746 #define LOG_XFER_BUF_SIZE 65536
748 SalvageLogCleanup(int pid)
751 char fn[AFSDIR_PATH_MAX];
752 static char buf[LOG_XFER_BUF_SIZE];
754 snprintf(fn, sizeof(fn), "%s.%d",
755 AFSDIR_SERVER_SLVGLOG_FILEPATH, pid);
758 pidlog = open(fn, O_RDONLY);
763 len = read(pidlog, buf, LOG_XFER_BUF_SIZE);
765 fwrite(buf, len, 1, logFile);
766 len = read(pidlog, buf, LOG_XFER_BUF_SIZE);
774 /* wake up every five minutes to see if a non-child salvage has finished */
775 #define SALVAGE_SCAN_POLL_INTERVAL 300
778 * Thread to look for SalvageLog.$pid files that are not from our child
779 * worker salvagers, and notify SalvageLogCleanupThread to clean them
780 * up. This can happen if we restart during salvages, or the
781 * salvageserver crashes or something.
785 * @return always NULL
788 SalvageLogScanningThread(void * arg)
790 struct rx_queue log_watch_queue;
792 queue_Init(&log_watch_queue);
797 char prefix[AFSDIR_PATH_MAX];
800 snprintf(prefix, sizeof(prefix), "%s.", AFSDIR_SLVGLOG_FILE);
801 prefix_len = strlen(prefix);
803 dp = opendir(AFSDIR_LOGS_DIR);
806 while ((dirp = readdir(dp)) != NULL) {
808 struct log_cleanup_node *cleanup;
811 if (strncmp(dirp->d_name, prefix, prefix_len) != 0) {
812 /* not a salvage logfile; skip */
817 pid = strtol(dirp->d_name + prefix_len, NULL, 10);
820 /* file is SalvageLog.<something> but <something> isn't
826 for (i = 0; i < Parallel; ++i) {
827 if (pid == child_slot[i]) {
833 /* this pid is one of our children, so the reaper thread
834 * will take care of it; skip */
838 cleanup = malloc(sizeof(struct log_cleanup_node));
841 queue_Append(&log_watch_queue, cleanup);
847 ScanLogs(&log_watch_queue);
849 while (queue_IsNotEmpty(&log_watch_queue)) {
850 sleep(SALVAGE_SCAN_POLL_INTERVAL);
851 ScanLogs(&log_watch_queue);
858 * look through log_watch_queue, and if any processes are not still
859 * running, hand them off to the SalvageLogCleanupThread
861 * @param log_watch_queue a queue of PIDs that we should clean up if
865 ScanLogs(struct rx_queue *log_watch_queue)
867 struct log_cleanup_node *cleanup, *next;
869 opr_mutex_enter(&worker_lock);
871 for (queue_Scan(log_watch_queue, cleanup, next, log_cleanup_node)) {
872 /* if a process is still running, assume it's the salvage process
873 * still going, and keep waiting for it */
874 if (kill(cleanup->pid, 0) < 0 && errno == ESRCH) {
875 queue_Remove(cleanup);
876 queue_Append(&log_cleanup_queue, cleanup);
877 opr_cv_signal(&log_cleanup_queue.queue_change_cv);
881 opr_mutex_exit(&worker_lock);