Whamcloud - gitweb
LU-1347 build: remove the vim/emacs modelines
[fs/lustre-release.git] / lustre / utils / lustre_rsync.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  */
30 /*
31  * This file is part of Lustre, http://www.lustre.org/
32  * Lustre is a trademark of Sun Microsystems, Inc.
33  *
34  * lustre/utils/lustre_rsync.c
35  *
36  * Author: Kalpak Shah <Kalpak.Shah@Sun.COM>
37  * Author: Manoj Joseph <Manoj.Joseph@Sun.COM>
38  */
39
40 /*
41  * - lustre_rsync is a tool for replicating a lustre filesystem.
42  *
43  * - The source-fs is a live lustre filesystem. It is not a
44  * snapshot. It is mounted and undergoing changes
45  *
46  * - The target-fs is a copy of the source-fs from the past. Let's
47  * call this point, the 'sync point'.
48  *
49  * - There is a changelog of all metadata operations that happened on
50  * the filesystem since the 'sync point'.
51  *
52  * - lustre_rsync replicates all the operations saved in the changelog
53  * on to the target filesystem to make it identical to the source.
54  *
55  * To facilitate replication, the lustre filesystem provides
56  *    a) a way to get the current filesystem path of a given FID
57  *    b) a way to open files by specifying its FID
58  *
59  * The changelog only has a limited amount of information.
60  *  tfid - The FID of the target file
61  *  pfid - The FID of the parent of the target file (at the time of
62  *         the operation)
63  *  name - The name of the target file (at the time of the operation)
64  *
65  * With just this information, it is not alwasy possible to determine
66  * the file paths for each operation. For instance, if pfid does not
67  * exist on the source-fs (due to a subsequent deletion), its path
68  * cannot be queried. In such cases, lustre_rsync keeps the files in a
69  * special directory ("/.lustrerepl"). Once all the operations in a
70  * changelog are replayed, all the files in this special directory
71  * will get moved to the location as in the source-fs.
72  *
73  * Shorthand used: f2p(tfid) = fid2path(tfid)
74  *
75  * The following are the metadata operations of interest.
76  * 1. creat
77  *    If tfid is absent on the source-fs, ignore this operation
78  *    If pfid is absent on the source-fs [or]
79  *    if f2p(pfid) is not present on target-fs [or]
80  *    if f2p(pfid)+name != f2p(tfid)
81  *      creat .lustrerepl/tfid
82  *      track [pfid,tfid,name]
83  *    Else
84  *      creat f2p[tfid]
85  *
86  * 2. remove
87  *    If .lustrerepl/[tfid] is present on the target
88  *      rm .lustrerepl/[tfid]
89  *    Else if pfid is present on the source-fs,
90  *      if f2p(pfid)+name is present,
91  *        rm f2p(pfid)+name(pfid,name)
92  *
93  * 3. move (pfid1,name1) to (pfid2,name2)
94  *    If pfid2 is present
95  *      if pfid1 is also present, mv (pfid1,name1) to (pfid2,name2)
96  *      else mv .lustrerepl/[tfid] to (pfid2,name2)
97  *    If pfid2 is not present,
98  *      if pfid1 is present, mv (pfid1,name1) .lustrerepl/[tfid]
99  *    If moving out of .lustrerepl
100  *      move out all its children in .lustrerepl.
101  *      [pfid,tfid,name] tracked from (1) is used for this.
102  */
103
104 #include <stdio.h>
105 #include <stdlib.h>
106 #include <string.h>
107 #include <unistd.h>
108 #include <getopt.h>
109 #include <stdarg.h>
110 #include <fcntl.h>
111 #include <sys/stat.h>
112 #include <sys/types.h>
113 #include <errno.h>
114 #include <limits.h>
115 #include <utime.h>
116 #include <sys/xattr.h>
117
118 #include <libcfs/libcfs.h>
119 #include <libcfs/libcfsutil.h>
120 #include <lustre/liblustreapi.h>
121 #include <lustre/lustre_idl.h>
122 #include "lustre_rsync.h"
123
124 #define REPLICATE_STATUS_VER 1
125 #define CLEAR_INTERVAL 100
126 #define DEFAULT_RSYNC_THRESHOLD 0xA00000 /* 10 MB */
127
128 #define TYPE_STR_LEN 16
129
130 #define DEFAULT_MDT "-MDT0000"
131 #define SPECIAL_DIR ".lustrerepl"
132 #define RSYNC "rsync"
133 #define TYPE "type"
134
135 /* Debug flags */
136 #define DINFO 1
137 #define DTRACE 2
138
139 /* Not used; declared for fulfilling obd.c's dependency. */
140 command_t cmdlist[0];
141 extern int obd_initialize(int argc, char **argv);
142
143 /* Information for processing a changelog record. This structure is
144    allocated on the heap instead of allocating large variables on the
145    stack. */
146 struct lr_info {
147         long long recno;
148         int target_no;
149         enum changelog_rec_type type;
150         char pfid[LR_FID_STR_LEN];
151         char tfid[LR_FID_STR_LEN];
152         char name[PATH_MAX + 1];
153         char src[PATH_MAX + 1];
154         char dest[PATH_MAX + 1];
155         char path[PATH_MAX + 1];
156         char savedpath[PATH_MAX + 1];
157         char link[PATH_MAX + 1];
158         char linktmp[PATH_MAX + 1];
159         char cmd[PATH_MAX];
160         int bufsize;
161         char *buf;
162
163         /* Variables for querying the xattributes */
164         char *xlist;
165         size_t xsize;
166         char *xvalue;
167         size_t xvsize;
168 };
169
170 struct lr_parent_child_list {
171         struct lr_parent_child_log pc_log;
172         struct lr_parent_child_list *pc_next;
173 };
174
175 struct lustre_rsync_status *status;
176 char *statuslog;  /* Name of the status log file */
177 int logbackedup;
178 int noxattr;    /* Flag to turn off replicating xattrs */
179 int noclear;    /* Flag to turn off clearing changelogs */
180 int debug;      /* Flag to turn debugging information on and off */
181 int verbose;    /* Verbose output */
182 long long rec_count; /* No of changelog records that were processed */
183 int errors;
184 int dryrun;
185 int use_rsync;  /* Flag to turn on use of rsync to copy data */
186 long long rsync_threshold = DEFAULT_RSYNC_THRESHOLD;
187 int quit;       /* Flag to stop processing the changelog; set on the
188                    receipt of a signal */
189 int abort_on_err = 0;
190
191 char rsync[PATH_MAX];
192 char rsync_ver[PATH_MAX];
193 struct lr_parent_child_list *parents;
194
195 /* Command line options */
196 struct option long_opts[] = {
197         {"source",      required_argument, 0, 's'},
198         {"target",      required_argument, 0, 't'},
199         {"mdt",         required_argument, 0, 'm'},
200         {"user",        required_argument, 0, 'u'},
201         {"statuslog",   required_argument, 0, 'l'},
202         {"verbose",     no_argument,       0, 'v'},
203         {"xattr",       required_argument, 0, 'x'},
204         {"dry-run",     no_argument,       0, 'z'},
205         /* Undocumented options follow */
206         {"cl-clear",    required_argument, 0, 'c'},
207         {"use-rsync",   no_argument,       0, 'r'},
208         {"rsync-threshold", required_argument, 0, 'y'},
209         {"start-recno", required_argument, 0, 'n'},
210         {"abort-on-err",no_argument,       0, 'a'},
211         {"debug",       required_argument, 0, 'd'},
212         {0, 0, 0, 0}
213 };
214
215 /* Command line usage */
216 void lr_usage()
217 {
218         fprintf(stderr, "\tlustre_rsync -s <lustre_root_path> -t <target_path> "
219                 "-m <mdt> -r <user id> -l <status log>\n"
220                 "lustre_rsync can also pick up parameters from a "
221                 "status log created earlier.\n"
222                 "\tlustre_rsync -l <log_file>\n"
223                 "options:\n"
224                 "\t--xattr <yes|no> replicate EAs\n"
225                 "\t--abort-on-err   abort at first err\n"
226                 "\t--verbose\n"
227                 "\t--dry-run        don't write anything\n");
228 }
229
230 /* Print debug information. This is controlled by the value of the
231    global variable 'debug' */
232 void lr_debug(int level, const char *fmt, ...)
233 {
234         va_list ap;
235
236         if (level > debug)
237                 return;
238
239         va_start(ap, fmt);
240         vprintf(fmt, ap);
241         va_end(ap);
242 }
243
244
245 void * lr_grow_buf(void *buf, int size)
246 {
247         void *ptr;
248
249         ptr = realloc(buf, size);
250         if (ptr == NULL)
251                 free(buf);
252         return ptr;
253 }
254
255
256 /* Use rsync to replicate file data */
257 int lr_rsync_data(struct lr_info *info)
258 {
259         int rc;
260         struct stat st_src, st_dest;
261         char cmd[PATH_MAX];
262
263         lr_debug(DTRACE, "Syncing data%s\n", info->tfid);
264
265         rc = stat(info->src, &st_src);
266         if (rc == -1) {
267                 fprintf(stderr, "Error: Unable to stat src=%s %s\n",
268                         info->src, info->name);
269                 if (errno == ENOENT)
270                         return 0;
271                 else
272                         return -errno;
273         }
274         rc = stat(info->dest, &st_dest);
275         if (rc == -1) {
276                 fprintf(stderr, "Error: Unable to stat dest=%s\n",
277                         info->dest);
278                 return -errno;
279         }
280
281         if (st_src.st_mtime != st_dest.st_mtime ||
282             st_src.st_size != st_dest.st_size) {
283                 /* XXX spawning off an rsync for every data sync and
284                  * waiting synchronously is bad for performance.
285                  * librsync could possibly used here. But it does not
286                  * seem to be of production grade. Multi-threaded
287                  * replication is also to be considered.
288                  */
289                 int status;
290                 snprintf(cmd, PATH_MAX, "%s --inplace %s %s", rsync, info->src,
291                         info->dest);
292                 lr_debug(DTRACE, "\t%s %s\n", cmd, info->tfid);
293                 status = system(cmd);
294                 if (status == -1) {
295                         rc = -errno;
296                 } else if (WIFEXITED(status)) {
297                         status = WEXITSTATUS(status);
298                         if (!status)
299                                 rc = 0;
300                         else if (status == 23 || status == 24)
301                                 /* Error due to vanished source files;
302                                    Ignore this error*/
303                                 rc = 0;
304                         else
305                                 rc = -EINVAL;
306                         if (status)
307                                 lr_debug(DINFO, "rsync %s exited with %d %d\n",
308                                          info->src, status, rc);
309                 } else {
310                         rc = -EINTR;
311                 }
312         } else {
313                 lr_debug(DTRACE, "Not syncing %s and %s %s\n", info->src,
314                          info->dest, info->tfid);
315         }
316
317         return rc;
318 }
319
320 int lr_copy_data(struct lr_info *info)
321 {
322         int fd_src = -1;
323         int fd_dest = -1;
324         int bufsize;
325         int rsize;
326         int rc = 0;
327         struct stat st_src;
328         struct stat st_dest;
329
330         fd_src = open(info->src, O_RDONLY);
331         if (fd_src == -1)
332                 return -errno;
333         if (fstat(fd_src, &st_src) == -1 ||
334             stat(info->dest, &st_dest) == -1)
335                 goto out;
336
337         if (st_src.st_mtime == st_dest.st_mtime &&
338             st_src.st_size == st_dest.st_size)
339                 goto out;
340
341         if (st_src.st_size > rsync_threshold && rsync[0] != '\0') {
342                 /* It is more efficient to use rsync to replicate
343                    large files. Any file larger than rsync_threshold
344                    is handed off to rsync. */
345                 lr_debug(DTRACE, "Using rsync to replicate %s\n", info->tfid);
346                 rc = lr_rsync_data(info);
347                 goto out;
348         }
349
350         fd_dest = open(info->dest, O_WRONLY | O_TRUNC, st_src.st_mode);
351         if (fd_dest == -1) {
352                 rc = -errno;
353                 goto out;
354         }
355         bufsize = st_dest.st_blksize;
356
357         if (info->bufsize < bufsize) {
358                 /* Grow buffer */
359                 info->buf = lr_grow_buf(info->buf, bufsize);
360                 if (info->buf == NULL) {
361                         rc = -ENOMEM;
362                         goto out;
363                 }
364                 info->bufsize = bufsize;
365         }
366
367         while (1) {
368                 rsize = read(fd_src, info->buf, bufsize);
369                 if (rsize == 0) {
370                         break;
371                 } else if (rsize < 0) {
372                         rc = -errno;
373                         goto out;
374                 }
375                 errno = 0;
376                 if (write(fd_dest, info->buf, rsize) != rsize) {
377                         if (errno != 0)
378                                 rc = -errno;
379                         else
380                                 rc = -EINTR;
381                 }
382         }
383         fsync(fd_dest);
384
385 out:
386         if (fd_src != -1)
387                 close(fd_src);
388         if (fd_dest != -1)
389                 close(fd_dest);
390
391         return rc;
392 }
393
394 /* Copy data from source to destination */
395 int lr_sync_data(struct lr_info *info)
396 {
397         if (use_rsync)
398                 return lr_rsync_data(info);
399         else
400                 return lr_copy_data(info);
401 }
402
403 /* Copy all attributes from file src to file dest */
404 int lr_copy_attr(char *src, char *dest)
405 {
406         struct stat st;
407         struct utimbuf time;
408
409         if (stat(src, &st) == -1 ||
410             chmod(dest, st.st_mode) == -1 ||
411             chown(dest, st.st_uid, st.st_gid) == -1)
412                 return -errno;
413
414         time.actime = st.st_atime;
415         time.modtime = st.st_mtime;
416         if (utime(dest, &time) == -1)
417                 return -errno;
418         return 0;
419 }
420
421 /* Copy all xattrs from file info->src to info->dest */
422 int lr_copy_xattr(struct lr_info *info)
423 {
424         size_t size = info->xsize;
425         int start;
426         int len;
427         int rc;
428
429         if (noxattr)
430                 return 0;
431
432         errno = 0;
433         rc = llistxattr(info->src, info->xlist, size);
434         lr_debug(DTRACE, "llistxattr(%s,%p) returned %d, errno=%d\n",
435                  info->src, info->xlist, rc, errno);
436         if ((rc > 0 && info->xlist == NULL) || errno == ERANGE) {
437                 size = rc > PATH_MAX ? rc : PATH_MAX;
438                 info->xlist = lr_grow_buf(info->xlist, size);
439                 if (info->xlist == NULL)
440                         return -ENOMEM;
441                 info->xsize = size;
442                 rc = llistxattr(info->src, info->xlist, size);
443                 lr_debug(DTRACE, "llistxattr %s returned %d, errno=%d\n",
444                          info->src, rc, errno);
445         }
446         if (rc < 0)
447                 return rc;
448
449         len = rc;
450         start = 0;
451         while (start < len) {
452                 size = info->xvsize;
453                 rc = lgetxattr(info->src, info->xlist + start,
454                                info->xvalue, size);
455                 if (info->xvalue == NULL || errno == ERANGE) {
456                         size = rc > PATH_MAX ? rc : PATH_MAX;
457                         info->xvalue = lr_grow_buf(info->xvalue, size);
458                         if (info->xvalue == NULL)
459                                 return -ENOMEM;
460                         info->xvsize = size;
461                         rc = lgetxattr(info->src, info->xlist + start,
462                                        info->xvalue, size);
463                 }
464                 lr_debug(DTRACE, "\t(%s,%d) rc=%p\n", info->xlist + start,
465                          info->xvalue, rc);
466                 if (rc > 0) {
467                         size = rc;
468                         rc = lsetxattr(info->dest, info->xlist + start,
469                                        info->xvalue, size, 0);
470                         lr_debug(DTRACE, "\tlsetxattr(), rc=%d, errno=%d\n",
471                                  rc, errno);
472                         if (rc == -1) {
473                                 if (errno != ENOTSUP) {
474                                         fprintf(stderr, "Error replicating "
475                                                 " xattr for %s: %d\n",
476                                                 info->dest, errno);
477                                         errors++;
478                                 }
479                                 rc = 0;
480                         }
481                 }
482                 start += strlen(info->xlist + start) + 1;
483         }
484
485         lr_debug(DINFO, "setxattr: %s %s\n", info->src, info->dest);
486
487         return rc;
488 }
489
490 /* Retrieve the filesystem path for a given FID and a given
491    linkno. The path is returned in info->path */
492 int lr_get_path_ln(struct lr_info *info, char *fidstr, int linkno)
493 {
494         long long recno = -1;
495         int rc;
496
497         rc = llapi_fid2path(status->ls_source, fidstr, info->path,
498                             PATH_MAX, &recno, &linkno);
499         if (rc < 0 && rc != -ENOENT) {
500                 fprintf(stderr, "fid2path error: (%s, %s) %d %s\n",
501                         status->ls_source, fidstr, -rc, strerror(errno = -rc));
502         }
503
504         return rc;
505 }
506
507 /* Retrieve the filesystem path for a given FID. The path is returned
508    in info->path */
509 int lr_get_path(struct lr_info *info, char *fidstr)
510 {
511         return lr_get_path_ln(info, fidstr, 0);
512 }
513
514 /* Generate the path for opening by FID */
515 void lr_get_FID_PATH(char *mntpt, char *fidstr, char *buf, int bufsize)
516 {
517         /* Open-by-FID path is <mntpt>/.lustre/fid/[SEQ:OID:VER] */
518         snprintf(buf, bufsize, "%s/%s/fid/%s", mntpt, dot_lustre_name,
519                  fidstr);
520         return;
521 }
522
523 /* Read the symlink information into 'info->link' */
524 int lr_get_symlink(struct lr_info *info)
525 {
526         int rc;
527         char *link;
528
529         lr_get_FID_PATH(status->ls_source, info->tfid, info->src, PATH_MAX);
530         rc = readlink(info->src, info->linktmp, PATH_MAX);
531         if (rc > 0)
532                 info->linktmp[rc] = '\0';
533         else
534                 return rc;
535         lr_debug(DTRACE, "symlink: readlink returned %s\n", info->linktmp);
536
537         if (strncmp(info->linktmp, status->ls_source,
538                     strlen(status->ls_source)) == 0) {
539                 /* Strip source fs path and replace with target fs path. */
540                 link = info->linktmp + strlen(status->ls_source);
541                 snprintf(info->src, PATH_MAX, "%s%s",
542                          status->ls_targets[info->target_no], link);
543                 link = info->src;
544         } else {
545                 link = info->linktmp;
546         }
547         strncpy(info->link, link, PATH_MAX);
548         info->link[PATH_MAX] = '\0';
549
550         return rc;
551 }
552
553 /* Create file/directory/device file/symlink. */
554 int lr_mkfile(struct lr_info *info)
555 {
556         struct stat st;
557         int rc = 0;
558
559         errno = 0;
560         lr_debug(DINFO, "mkfile(%d) %s \n", info->type, info->dest);
561         if (info->type == CL_MKDIR) {
562                 rc = mkdir(info->dest, 0777);
563         } else if (info->type == CL_SOFTLINK) {
564                 lr_get_symlink(info);
565                 rc = symlink(info->link, info->dest);
566         } else if (info->type == CL_MKNOD) {
567                 lr_get_FID_PATH(status->ls_source, info->tfid,
568                                     info->src, PATH_MAX);
569                 rc = stat(info->src, &st);
570                 if (rc == -1) {
571                         if (errno == ENOENT)
572                                 return 0;
573                         else
574                                 return -errno;
575                 }
576                 rc = mknod(info->dest, st.st_mode, st.st_rdev);
577         } else {
578                 rc = mknod(info->dest, S_IFREG | 0777, 0);
579         }
580         if (rc)
581                 return -errno;
582
583         /* Sync data and attributes */
584         if (info->type == CL_CREATE || info->type == CL_MKDIR) {
585                 lr_debug(DTRACE, "Syncing data and attributes %s\n",
586                          info->tfid);
587                 (void) lr_copy_xattr(info);
588                 if (info->type == CL_CREATE)
589                         rc = lr_sync_data(info);
590                 if (!rc)
591                         rc = lr_copy_attr(info->src, info->dest);
592
593                 if (rc == -ENOENT)
594                         /* Source file has disappeared. Not an error. */
595                         rc = 0;
596         } else {
597                 lr_debug(DTRACE, "Not syncing data and attributes %s\n",
598                          info->tfid);
599         }
600
601         return rc;
602 }
603
604 int lr_add_pc(const char *pfid, const char *tfid, const char *name)
605 {
606         struct lr_parent_child_list *p;
607
608         p = calloc(1, sizeof(*p));
609         if (!p)
610                 return -ENOMEM;
611         strcpy(p->pc_log.pcl_pfid, pfid);
612         strcpy(p->pc_log.pcl_tfid, tfid);
613         strcpy(p->pc_log.pcl_name, name);
614
615         p->pc_next = parents;
616         parents = p;
617         return 0;
618 }
619
620 void lr_cascade_move(const char *fid, const char *dest, struct lr_info *info)
621 {
622         struct lr_parent_child_list *curr, *prev;
623         char *d;
624         int rc;
625
626         d = calloc(1, PATH_MAX + 1);
627         prev = curr = parents;
628         while (curr) {
629                 if (strcmp(curr->pc_log.pcl_pfid, fid) == 0) {
630                         snprintf(d, PATH_MAX, "%s/%s", dest,
631                                  curr->pc_log.pcl_name);
632                         snprintf(info->src, PATH_MAX, "%s/%s/%s",
633                                 status->ls_targets[info->target_no],
634                                 SPECIAL_DIR, curr->pc_log.pcl_tfid);
635                         rc = rename(info->src, d);
636                         if (rc == -1) {
637                                 fprintf(stderr, "Error renaming file "
638                                         " %s to %s: %d\n",
639                                         info->src, d, errno);
640                                 errors++;
641                         }
642                         lr_cascade_move(curr->pc_log.pcl_tfid, d, info);
643                         if (curr == parents)
644                                 parents = curr->pc_next;
645                         else
646                                 prev->pc_next = curr->pc_next;
647                         free(curr);
648                         prev = curr = parents;
649
650                 } else {
651                         prev = curr;
652                         curr = curr->pc_next;
653                 }
654         }
655
656         free(d);
657 }
658
659 /* remove [info->pfid, ext->tfid] from parents */
660 int lr_remove_pc(const char *pfid, const char *tfid)
661 {
662         struct lr_parent_child_list *curr, *prev;
663
664         for (prev = curr = parents; curr; prev = curr, curr = curr->pc_next) {
665                 if (strcmp(curr->pc_log.pcl_pfid, pfid) == 0 &&
666                     strcmp(curr->pc_log.pcl_tfid, tfid) == 0) {
667                         if (curr == parents)
668                                 parents = curr->pc_next;
669                         else
670                                 prev->pc_next = curr->pc_next;
671                         free(curr);
672                         break;
673                 }
674         }
675         return 0;
676 }
677
678 /* Create file under SPECIAL_DIR with its tfid as its name. */
679 int lr_mk_special(struct lr_info *info)
680 {
681         int rc;
682
683         snprintf(info->dest, PATH_MAX, "%s/%s/%s",
684                 status->ls_targets[info->target_no], SPECIAL_DIR,
685                 info->tfid);
686
687         rc = lr_mkfile(info);
688         if (rc)
689                 return rc;
690
691         rc = lr_add_pc(info->pfid, info->tfid, info->name);
692         return rc;
693 }
694
695 /* Remove a file or directory */
696 int lr_rmfile(struct lr_info *info)
697 {
698         int rc;
699
700         if (info->type == CL_RMDIR)
701                 rc = rmdir(info->dest);
702         else
703                 rc = unlink(info->dest);
704         if (rc == -1)
705                 rc = -errno;
706         return rc;
707 }
708
709 /* Recursively remove directory and its contents */
710 int lr_rm_recursive(struct lr_info *info)
711 {
712         int rc;
713
714         snprintf(info->cmd, PATH_MAX, "rm -rf %s", info->dest);
715         rc = system(info->cmd);
716         if (rc == -1)
717                 rc = -errno;
718
719         return rc;
720 }
721
722 /* Remove a file under SPECIAL_DIR with its tfid as its name. */
723 int lr_rm_special(struct lr_info *info)
724 {
725         int rc;
726
727         snprintf(info->dest, PATH_MAX, "%s/%s/%s",
728                  status->ls_targets[info->target_no], SPECIAL_DIR,
729                  info->tfid);
730         rc = lr_rmfile(info);
731
732         if (rc)
733                 lr_debug(DINFO, "remove: %s; rc=%d, errno=%d\n",
734                          info->dest, rc, errno);
735         return rc;
736 }
737
738 /* Replicate file and directory create events */
739 int lr_create(struct lr_info *info)
740 {
741         int len;
742         int rc1 = 0;
743         int rc;
744         int mkspecial = 0;
745
746         /* Is target FID present on the source? */
747         rc = lr_get_path(info, info->tfid);
748         if (rc == -ENOENT) {
749                 /* Source file has disappeared. Not an error. */
750                 lr_debug(DINFO, "create: tfid %s not found on"
751                          "source-fs\n", info->tfid);
752                 return 0;
753         } else if (rc) {
754                 return rc;
755         }
756         strcpy(info->savedpath, info->path);
757
758         /* Is parent FID present on the source */
759         rc = lr_get_path(info, info->pfid);
760         if (rc == -ENOENT) {
761                 lr_debug(DINFO, "create: pfid %s not found on source-fs\n",
762                          info->tfid);
763                 mkspecial = 1;
764         } else if (rc < 0) {
765                 return rc;
766         }
767
768         /* Is f2p(pfid)+name != f2p(tfid)? If not the file has moved. */
769         len = strlen(info->path);
770         if (len - 1 >= 0 && info->path[len - 1] == '/')
771                 snprintf(info->dest, PATH_MAX, "%s%s", info->path, info->name);
772         else
773                 snprintf(info->dest, PATH_MAX, "%s/%s", info->path, info->name);
774
775         lr_debug(DTRACE, "dest = %s; savedpath = %s\n", info->dest,
776                  info->savedpath);
777         if (strncmp(info->dest, info->savedpath, PATH_MAX) != 0) {
778                 lr_debug(DTRACE, "create: file moved (%s). %s != %s\n",
779                          info->tfid, info->dest, info->savedpath);
780                 mkspecial = 1;
781         }
782
783         /* Is f2p(pfid) present on the target? If not, the parent has
784            moved */
785         if (!mkspecial) {
786                 snprintf(info->dest, PATH_MAX, "%s/%s", status->ls_targets[0],
787                         info->path);
788                 if (access(info->dest, F_OK) != 0)
789                         mkspecial = 1;
790         }
791         for (info->target_no = 0; info->target_no < status->ls_num_targets;
792              info->target_no++) {
793                 snprintf(info->dest, PATH_MAX, "%s/%s",
794                         status->ls_targets[info->target_no], info->savedpath);
795                 lr_get_FID_PATH(status->ls_source, info->tfid, info->src,
796                                     PATH_MAX);
797
798                 if (!mkspecial)
799                         rc1 = lr_mkfile(info);
800                 if (mkspecial || rc1 == -ENOENT) {
801                         rc1 = lr_mk_special(info);
802                 }
803                 if (rc1)
804                         rc = rc1;
805         }
806         return rc;
807 }
808
809 /* Replicate a file remove (rmdir/unlink) operation */
810 int lr_remove(struct lr_info *info)
811 {
812         int rc = 0;
813         int rc1;
814
815         for (info->target_no = 0; info->target_no < status->ls_num_targets;
816              info->target_no++) {
817
818                 rc1 = lr_rm_special(info);
819                 if (!rc1)
820                         continue;
821
822                 rc1 = lr_get_path(info, info->pfid);
823                 if (rc1 == -ENOENT) {
824                         lr_debug(DINFO, "remove: pfid %s not found\n",
825                                  info->pfid);
826                         continue;
827                 }
828                 if (rc1) {
829                         rc = rc1;
830                         continue;
831                 }
832                 snprintf(info->dest, PATH_MAX, "%s/%s/%s",
833                         status->ls_targets[info->target_no], info->path,
834                         info->name);
835
836                 rc1 = lr_rmfile(info);
837                 lr_debug(DINFO, "remove: %s; rc1=%d, errno=%d\n",
838                          info->dest, rc1, errno);
839                 if (rc1 == -ENOTEMPTY)
840                         rc1 = lr_rm_recursive(info);
841
842                 if (rc1) {
843                         rc = rc1;
844                         continue;
845                 }
846         }
847         return rc;
848 }
849
850 /* Replicate a rename/move operation. This operations are tracked by
851    two changelog records. */
852 int lr_move(struct lr_info *info, struct lr_info *ext)
853 {
854         int rc = 0;
855         int rc1;
856         int rc_dest, rc_src;
857         int special_src = 0;
858         int special_dest = 0;
859
860         rc_dest = lr_get_path(ext, ext->pfid);
861         if (rc_dest < 0 && rc_dest != -ENOENT)
862                 return rc_dest;
863
864         rc_src = lr_get_path(info, info->pfid);
865         if (rc_src < 0 && rc_src != -ENOENT)
866                 return rc_src;
867
868         for (info->target_no = 0; info->target_no < status->ls_num_targets;
869              info->target_no++) {
870
871                 if (!rc_dest) {
872                         snprintf(info->dest, PATH_MAX, "%s/%s",
873                                 status->ls_targets[info->target_no],
874                                 ext->path);
875                         if (access(info->dest, F_OK) != 0) {
876                                 rc_dest = -errno;
877                         } else {
878                                 snprintf(info->dest, PATH_MAX, "%s/%s/%s",
879                                         status->ls_targets[info->target_no],
880                                         ext->path, ext->name);
881                         }
882                 }
883                 if (rc_dest == -ENOENT) {
884                         snprintf(info->dest, PATH_MAX, "%s/%s/%s",
885                                 status->ls_targets[info->target_no],
886                                 SPECIAL_DIR, info->tfid);
887                         special_dest = 1;
888                 }
889
890                 if (!rc_src)
891                         snprintf(info->src, PATH_MAX, "%s/%s/%s",
892                                 status->ls_targets[info->target_no],
893                                 info->path, info->name);
894                 if (rc_src == -ENOENT || (access(info->src, F_OK) != 0 &&
895                                           errno == ENOENT)) {
896                         snprintf(info->src, PATH_MAX, "%s/%s/%s",
897                                 status->ls_targets[info->target_no],
898                                 SPECIAL_DIR, info->tfid);
899                         special_src = 1;
900                 }
901
902                 rc1 = 0;
903                 if (strcmp(info->src, info->dest) != 0) {
904                         rc1 = rename(info->src, info->dest);
905                         if (rc1 == -1)
906                                 rc1 = -errno;
907                 }
908
909                 if (special_src) {
910                         lr_remove_pc(info->pfid, info->tfid);
911                         if (!special_dest)
912                                 lr_cascade_move(info->tfid, info->dest, info);
913                 }
914                 if (special_dest)
915                         lr_add_pc(ext->pfid, info->tfid, ext->name);
916
917                 lr_debug(DINFO, "move: %s [to] %s rc1=%d, errno=%d\n",
918                          info->src, info->dest, rc1, errno);
919                 if (rc1)
920                         rc = rc1;
921         }
922         return rc;
923 }
924
925 /* Replicate a hard link */
926 int lr_link(struct lr_info *info)
927 {
928         int i;
929         int len;
930         int rc;
931         int rc1;
932         struct stat st;
933
934         lr_get_FID_PATH(status->ls_source, info->tfid, info->src, PATH_MAX);
935         rc = stat(info->src, &st);
936         if (rc == -1)
937                 return -errno;
938
939         for (info->target_no = 0; info->target_no < status->ls_num_targets;
940              info->target_no++) {
941
942                 info->src[0] = 0;
943                 info->dest[0] = 0;
944                 rc1 = 0;
945
946                 /* Search through the hardlinks to get the src and dest */
947                 for (i = 0; i < st.st_nlink && (info->src[0] == 0 ||
948                                                 info->dest[0] == 0); i++) {
949                         rc1 = lr_get_path_ln(info, info->tfid, i);
950                         lr_debug(rc1 ? 0:DTRACE, "\tfid2path %s, %s, %d rc=%d\n",
951                                  info->path, info->name, i, rc1);
952                         if (rc1)
953                                 break;
954
955                         len = strlen(info->path) - strlen(info->name);
956                         if (len > 0 && strcmp(info->path + len,
957                                               info->name) == 0)
958                                 snprintf(info->dest, PATH_MAX, "%s/%s",
959                                         status->ls_targets[info->target_no],
960                                         info->path);
961                         else if (info->src[0] == 0)
962                                 snprintf(info->src, PATH_MAX, "%s/%s",
963                                         status->ls_targets[info->target_no],
964                                         info->path);
965                 }
966
967                 if (rc1) {
968                         rc = rc1;
969                         continue;
970                 }
971
972                 if (info->src[0] == 0 || info->dest[0] == 0)
973                         /* Could not find the source or destination.
974                          This can happen when some links don't exist
975                          anymore. */
976                         return -EINVAL;
977
978                 if (info->src[0] == 0)
979                         snprintf(info->src, PATH_MAX, "%s/%s/%s",
980                                 status->ls_targets[info->target_no],
981                                 SPECIAL_DIR, info->tfid);
982                 else if (info->dest[0] == 0)
983                         snprintf(info->dest, PATH_MAX, "%s/%s/%s",
984                                 status->ls_targets[info->target_no],
985                                 SPECIAL_DIR, info->tfid);
986
987                 rc1 = link(info->src, info->dest);
988                 lr_debug(rc1?0:DINFO, "link: %s [to] %s; rc1=%d %s\n",
989                          info->src, info->dest, rc1, strerror(errno));
990
991                 if (rc1)
992                         rc = rc1;
993         }
994         return rc;
995 }
996
997 /* Replicate file attributes */
998 int lr_setattr(struct lr_info *info)
999 {
1000         int rc1;
1001         int rc;
1002
1003         lr_get_FID_PATH(status->ls_source, info->tfid, info->src, PATH_MAX);
1004
1005         rc = lr_get_path(info, info->tfid);
1006         if (rc == -ENOENT)
1007                 lr_debug(DINFO, "setattr: %s not present on source-fs\n",
1008                          info->src);
1009         if (rc)
1010                 return rc;
1011
1012         for (info->target_no = 0; info->target_no < status->ls_num_targets;
1013              info->target_no++) {
1014
1015                 snprintf(info->dest, PATH_MAX, "%s/%s",
1016                          status->ls_targets[info->target_no], info->path);
1017                 lr_debug(DINFO, "setattr: %s %s %s", info->src, info->dest,
1018                          info->tfid);
1019
1020                 rc1 = lr_sync_data(info);
1021                 if (!rc1)
1022                         rc1 = lr_copy_attr(info->src, info->dest);
1023                 if (rc1)
1024                         rc = rc1;
1025         }
1026         return rc;
1027 }
1028
1029 /* Replicate xattrs */
1030 int lr_setxattr(struct lr_info *info)
1031 {
1032         int rc, rc1;
1033
1034         lr_get_FID_PATH(status->ls_source, info->tfid, info->src, PATH_MAX);
1035
1036         rc = lr_get_path(info, info->tfid);
1037         if (rc == -ENOENT)
1038                 lr_debug(DINFO, "setxattr: %s not present on source-fs\n",
1039                          info->src);
1040         if (rc)
1041                 return rc;
1042
1043         for (info->target_no = 0; info->target_no < status->ls_num_targets;
1044              info->target_no++) {
1045
1046                 snprintf(info->dest, PATH_MAX, "%s/%s",
1047                         status->ls_targets[info->target_no], info->path);
1048                 lr_debug(DINFO, "setxattr: %s %s %s\n", info->src, info->dest,
1049                          info->tfid);
1050
1051                 rc1 = lr_copy_xattr(info);
1052                 if (rc1)
1053                         rc = rc1;
1054         }
1055
1056         return rc;
1057 }
1058
1059 /* Parse a line of changelog entry */
1060 int lr_parse_line(void *priv, struct lr_info *info)
1061 {
1062         struct changelog_rec *rec;
1063
1064         if (llapi_changelog_recv(priv, &rec) != 0)
1065                 return -1;
1066
1067         info->recno = rec->cr_index;
1068         info->type = rec->cr_type;
1069         sprintf(info->tfid, DFID, PFID(&rec->cr_tfid));
1070         sprintf(info->pfid, DFID, PFID(&rec->cr_pfid));
1071         strncpy(info->name, rec->cr_name, rec->cr_namelen);
1072         info->name[rec->cr_namelen] = '\0';
1073
1074         if (verbose > 1)
1075                 printf("Rec %lld: %d %s\n", info->recno, info->type,info->name);
1076
1077         llapi_changelog_free(&rec);
1078
1079         rec_count++;
1080         return 0;
1081 }
1082
1083 /* Initialize the replication parameters */
1084 int lr_init_status()
1085 {
1086         size_t size = sizeof(struct lustre_rsync_status) + PATH_MAX;
1087
1088         if (status != NULL)
1089                 return 0;
1090         status = calloc(size, 1);
1091         if (status == NULL)
1092                 return -ENOMEM;
1093         status->ls_version = REPLICATE_STATUS_VER;
1094         status->ls_size = size;
1095         status->ls_last_recno = -1;
1096         return 0;
1097 }
1098
1099 /* Make a backup of the statuslog */
1100 void lr_backup_log()
1101 {
1102         char backupfile[PATH_MAX];
1103
1104         if (logbackedup)
1105                 return;
1106         snprintf(backupfile, PATH_MAX, "%s.old", statuslog);
1107         (void) rename(statuslog, backupfile);
1108         logbackedup = 1;
1109
1110         return;
1111 }
1112
1113 /* Save replication parameters to a statuslog. */
1114 int lr_write_log()
1115 {
1116         int fd;
1117         size_t size;
1118         size_t write_size = status->ls_size;
1119         struct lr_parent_child_list *curr;
1120         int rc = 0;
1121
1122         if (statuslog == NULL)
1123                 return 0;
1124
1125         lr_backup_log();
1126
1127         fd = open(statuslog, O_WRONLY | O_CREAT | O_SYNC,
1128                              S_IRUSR | S_IWUSR);
1129         if (fd == -1) {
1130                 fprintf(stderr, "Error opening log file for writing (%s)\n",
1131                         statuslog);
1132                 return -1;
1133         }
1134         errno = 0;
1135         size = write(fd, status, write_size);
1136         if (size != write_size) {
1137                 fprintf(stderr, "Error writing to log file (%s) %d\n",
1138                         statuslog, errno);
1139                 close(fd);
1140                 return -1;
1141         }
1142
1143         for (curr = parents; curr; curr = curr->pc_next) {
1144                 size = write(fd, &curr->pc_log, sizeof(curr->pc_log));
1145                 if (size != sizeof(curr->pc_log)) {
1146                         fprintf(stderr, "Error writing to log file (%s) %d\n",
1147                                 statuslog, errno);
1148                         rc = -1;
1149                         break;
1150                 }
1151         }
1152         close(fd);
1153         return rc;
1154 }
1155
1156 /* Read statuslog and populate the replication parameters.  Command
1157  * line parameters take precedence over parameters in the log file.*/
1158 int lr_read_log()
1159 {
1160         struct lr_parent_child_list *tmp;
1161         struct lr_parent_child_log rec;
1162         struct lustre_rsync_status *s;
1163         int fd = -1;
1164         size_t size;
1165         size_t read_size = sizeof(struct lustre_rsync_status) + PATH_MAX;
1166         int rc = 0;
1167
1168         if (statuslog == NULL)
1169                 return 0;
1170
1171         s = calloc(1, read_size);
1172         if (s == NULL)
1173                 GOTO(out, rc = -ENOMEM);
1174
1175         fd = open(statuslog, O_RDONLY);
1176         if (fd == -1)
1177                 GOTO(out, rc = -errno);
1178         size = read(fd, s, read_size);
1179         if (size != read_size)
1180                 GOTO(out, rc = -EINVAL);
1181         if (read_size < s->ls_size) {
1182                 read_size = s->ls_size;
1183                 s = lr_grow_buf(s, read_size);
1184                 if (s == NULL)
1185                         GOTO(out, rc = -ENOMEM);
1186                 if (lseek(fd, 0, SEEK_SET) == -1)
1187                         GOTO(out, rc = -errno);
1188                 size = read(fd, s, read_size);
1189                 if (size != read_size)
1190                         GOTO(out, rc = -EINVAL);
1191         }
1192
1193         while (read(fd, &rec, sizeof(rec)) != 0) {
1194                 tmp = calloc(1, sizeof(*tmp));
1195                 if (!tmp)
1196                         GOTO(out, rc = -ENOMEM);
1197                 tmp->pc_log = rec;
1198                 tmp->pc_next = parents;
1199                 parents = tmp;
1200         }
1201
1202         /* copy uninitialized fields to status */
1203         if (status->ls_num_targets == 0) {
1204                 if (status->ls_size != s->ls_size) {
1205                         status = lr_grow_buf(status, s->ls_size);
1206                         if (status == NULL)
1207                                 GOTO(out, rc = -ENOMEM);
1208                         status->ls_size = s->ls_size;
1209                 }
1210                 status->ls_num_targets = s->ls_num_targets;
1211                 memcpy(status->ls_targets, s->ls_targets,
1212                        PATH_MAX * s->ls_num_targets);
1213         }
1214         if (status->ls_last_recno == -1)
1215                 status->ls_last_recno = s->ls_last_recno;
1216
1217         if (status->ls_registration[0] == '\0')
1218                 strncpy(status->ls_registration, s->ls_registration,
1219                         LR_NAME_MAXLEN);
1220
1221         if (status->ls_mdt_device[0] == '\0')
1222                 strncpy(status->ls_mdt_device, s->ls_mdt_device,
1223                         LR_NAME_MAXLEN);
1224
1225         if (status->ls_source_fs[0] == '\0')
1226                 strncpy(status->ls_source_fs, s->ls_source_fs,
1227                         LR_NAME_MAXLEN);
1228
1229         if (status->ls_source[0] == '\0')
1230                 strncpy(status->ls_source, s->ls_source, PATH_MAX);
1231
1232  out:
1233         if (fd != -1)
1234                 close(fd);
1235         if (s)
1236                 free(s);
1237         return rc;
1238 }
1239
1240 /* Clear changelogs every CLEAR_INTERVAL records or at the end of
1241    processing. */
1242 int lr_clear_cl(struct lr_info *info, int force)
1243 {
1244         char    mdt_device[LR_NAME_MAXLEN + 1];
1245         long long rec;
1246         int rc = 0;
1247
1248         if (force || info->recno > status->ls_last_recno + CLEAR_INTERVAL) {
1249                 if (info->type == CL_RENAME)
1250                         rec = info->recno + 1;
1251                 else
1252                         rec = info->recno;
1253                 if (!noclear && !dryrun) {
1254                         /* llapi_changelog_clear modifies the mdt
1255                          * device name so make a copy of it until this
1256                          * is fixed.
1257                         */
1258                         strncpy(mdt_device, status->ls_mdt_device,
1259                                 LR_NAME_MAXLEN);
1260                         rc = llapi_changelog_clear(mdt_device,
1261                                                    status->ls_registration,
1262                                                    rec);
1263                         if (rc)
1264                                 printf("Changelog clear (%s, %s, %lld) "
1265                                        "returned %d\n", status->ls_mdt_device,
1266                                        status->ls_registration, rec, rc);
1267                 }
1268                 if (!rc && !dryrun) {
1269                         status->ls_last_recno = rec;
1270                         lr_write_log();
1271
1272                 }
1273         }
1274
1275         return rc;
1276 }
1277
1278 /* Locate a usable version of rsync. At this point we'll use any
1279    version. */
1280 int lr_locate_rsync()
1281 {
1282         FILE *fp;
1283         int len;
1284
1285         /* Locate rsync */
1286         snprintf(rsync, PATH_MAX, "%s -p %s", TYPE, RSYNC);
1287         fp = popen(rsync, "r");
1288         if (fp == NULL)
1289                 return -1;
1290
1291         if (fgets(rsync, PATH_MAX, fp) == NULL) {
1292                 fclose(fp);
1293                 return -1;
1294         }
1295
1296         len = strlen(rsync);
1297         if (len > 0 && rsync[len - 1] == '\n')
1298                 rsync[len - 1] = '\0';
1299         fclose(fp);
1300
1301         /* Determine the version of rsync */
1302         snprintf(rsync_ver, PATH_MAX, "%s --version", rsync);
1303         fp = popen(rsync_ver, "r");
1304         if (fp == NULL)
1305                 return -1;
1306
1307         if (fgets(rsync_ver, PATH_MAX, fp) == NULL) {
1308                 fclose(fp);
1309                 return -1;
1310         }
1311         len = strlen(rsync_ver);
1312         if (len > 0 && rsync_ver[len - 1] == '\n')
1313                 rsync_ver[len - 1] = '\0';
1314         fclose(fp);
1315
1316         return 0;
1317
1318 }
1319
1320 /* Print the replication parameters */
1321 void lr_print_status(struct lr_info *info)
1322 {
1323         int i;
1324
1325         if (!verbose)
1326                 return;
1327
1328         printf("Lustre filesystem: %s\n", status->ls_source_fs);
1329         printf("MDT device: %s\n", status->ls_mdt_device);
1330         printf("Source: %s\n", status->ls_source);
1331         for (i = 0; i < status->ls_num_targets; i++)
1332                 printf("Target: %s\n", status->ls_targets[i]);
1333         if (statuslog != NULL)
1334                 printf("Statuslog: %s\n", statuslog);
1335         printf("Changelog registration: %s\n", status->ls_registration);
1336         printf("Starting changelog record: "LPD64"\n", status->ls_last_recno);
1337         if (noxattr)
1338                 printf("Replicate xattrs: no\n");
1339         if (noclear)
1340                 printf("Clear changelog after use: no\n");
1341         if (use_rsync)
1342                 printf("Using rsync: %s (%s)\n", rsync, rsync_ver);
1343 }
1344
1345 void lr_print_failure(struct lr_info *info, int rc)
1346 {
1347         fprintf(stderr, "Replication of operation failed(%d):"
1348                 " %lld %s (%d) %s %s %s\n", rc, info->recno,
1349                 changelog_type2str(info->type), info->type, info->tfid,
1350                 info->pfid, info->name);
1351 }
1352
1353 /* Replicate filesystem operations from src_path to target_path */
1354 int lr_replicate()
1355 {
1356         void *changelog_priv;
1357         struct lr_info *info;
1358         struct lr_info *ext;
1359         time_t start;
1360         int xattr_not_supp;
1361         int i;
1362         int rc;
1363
1364         start = time(NULL);
1365
1366         info = calloc(1, sizeof(struct lr_info));
1367         if (info == NULL)
1368                 return -ENOMEM;
1369
1370         rc = llapi_search_fsname(status->ls_source, status->ls_source_fs);
1371         if (rc) {
1372                 fprintf(stderr, "Source path is not a valid Lustre client "
1373                         "mountpoint.\n");
1374                 return rc;
1375         }
1376         if (status->ls_mdt_device[0] == '\0')
1377                 snprintf(status->ls_mdt_device, LR_NAME_MAXLEN, "%s%s",
1378                         status->ls_source_fs, DEFAULT_MDT);
1379
1380         ext = calloc(1, sizeof(struct lr_info));
1381         if (ext == NULL)
1382                 return -ENOMEM;
1383         memcpy(ext, info, sizeof(struct lr_info));
1384
1385         for (i = 0, xattr_not_supp = 0; i < status->ls_num_targets; i++) {
1386                 snprintf(info->dest, PATH_MAX, "%s/%s", status->ls_targets[i],
1387                         SPECIAL_DIR);
1388                 rc = mkdir(info->dest, 0777);
1389                 if (rc == -1 && errno != EEXIST) {
1390                         fprintf(stderr, "Error writing to target path %s.\n",
1391                                 status->ls_targets[i]);
1392                         return -errno;
1393                 }
1394                 rc = llistxattr(info->src, info->xlist, info->xsize);
1395                 if (rc == -1 && errno == ENOTSUP) {
1396                         fprintf(stderr, "xattrs not supported on %s\n",
1397                                 status->ls_targets[i]);
1398                         xattr_not_supp++;
1399                 }
1400         }
1401         if (xattr_not_supp == status->ls_num_targets)
1402                 /* None of the targets support xattrs. */
1403                 noxattr = 1;
1404
1405         lr_print_status(info);
1406
1407         /* Open changelogs for consumption*/
1408         rc = llapi_changelog_start(&changelog_priv, CHANGELOG_FLAG_BLOCK,
1409                                    status->ls_source_fs, status->ls_last_recno);
1410         if (rc < 0) {
1411                 fprintf(stderr, "Error opening changelog file for fs %s.\n",
1412                         status->ls_source_fs);
1413                 return rc;
1414         }
1415
1416         while (!quit && lr_parse_line(changelog_priv, info) == 0) {
1417                 rc = 0;
1418                 if (info->type == CL_RENAME)
1419                         /* Rename operations have an additional changelog
1420                            record of information. */
1421                         lr_parse_line(changelog_priv, ext);
1422
1423                 if (dryrun)
1424                         continue;
1425
1426                 switch(info->type) {
1427                 case CL_CREATE:
1428                 case CL_MKDIR:
1429                 case CL_MKNOD:
1430                 case CL_SOFTLINK:
1431                         rc = lr_create(info);
1432                         break;
1433                 case CL_RMDIR:
1434                 case CL_UNLINK:
1435                         rc = lr_remove(info);
1436                         break;
1437                 case CL_RENAME:
1438                         rc = lr_move(info, ext);
1439                         break;
1440                 case CL_HARDLINK:
1441                         rc = lr_link(info);
1442                         break;
1443                 case CL_TRUNC:
1444                 case CL_SETATTR:
1445                         rc = lr_setattr(info);
1446                         break;
1447                 case CL_XATTR:
1448                         rc = lr_setxattr(info);
1449                         break;
1450                 case CL_CLOSE:
1451                 case CL_EXT:
1452                 case CL_OPEN:
1453                 case CL_IOCTL:
1454                 case CL_MARK:
1455                         /* Nothing needs to be done for these entries */
1456                 default:
1457                         break;
1458                 }
1459                 if (rc && rc != -ENOENT) {
1460                         lr_print_failure(info, rc);
1461                         errors++;
1462                         if (abort_on_err)
1463                                 break;
1464                 }
1465                 lr_clear_cl(info, 0);
1466                 if (debug) {
1467                         bzero(info, sizeof(struct lr_info));
1468                         bzero(ext, sizeof(struct lr_info));
1469                 }
1470         }
1471
1472         llapi_changelog_fini(&changelog_priv);
1473
1474         if (errors || verbose)
1475                 printf("Errors: %d\n", errors);
1476
1477         /* Clear changelog records used so far */
1478         lr_clear_cl(info, 1);
1479
1480         if (verbose) {
1481                 printf("lustre_rsync took %ld seconds\n", time(NULL) - start);
1482                 printf("Changelog records consumed: %lld\n", rec_count);
1483         }
1484
1485         return 0;
1486 }
1487
1488 void
1489 termination_handler (int signum)
1490 {
1491         /* Set a flag for the replicator to gracefully shutdown */
1492         quit = 1;
1493         printf("lustre_rsync halting.\n");
1494 }
1495
1496 int main(int argc, char *argv[])
1497 {
1498         int newsize;
1499         int numtargets = 0;
1500         int rc = 0;
1501
1502         if ((rc = lr_init_status()) != 0)
1503                 return rc;
1504
1505         while ((rc = getopt_long(argc, argv, "as:t:m:u:l:vx:zc:ry:n:d:",
1506                                 long_opts, NULL)) >= 0) {
1507                 switch (rc) {
1508                 case 'a':
1509                         /* Assume absolute paths */
1510                         abort_on_err++;
1511                         break;
1512                 case 's':
1513                         /* Assume absolute paths */
1514                         strncpy(status->ls_source, optarg, PATH_MAX);
1515                         break;
1516                 case 't':
1517                         status->ls_num_targets++;
1518                         numtargets++;
1519                         if (numtargets != status->ls_num_targets) {
1520                                 /* Targets were read from a log
1521                                    file. The ones specified on the
1522                                    command line take precedence. The
1523                                    ones from the log file will be
1524                                    ignored. */
1525                                 status->ls_num_targets = numtargets;
1526                         }
1527                         newsize = sizeof (struct lustre_rsync_status) +
1528                                 (status->ls_num_targets * PATH_MAX);
1529                         if (status->ls_size != newsize) {
1530                                 status->ls_size = newsize;
1531                                 status = lr_grow_buf(status, newsize);
1532                                 if (status == NULL)
1533                                         return -ENOMEM;
1534                         }
1535                         strncpy(status->ls_targets[status->ls_num_targets - 1],
1536                                 optarg,
1537                                 PATH_MAX);
1538                         break;
1539                 case 'm':
1540                         strncpy(status->ls_mdt_device, optarg, LR_NAME_MAXLEN);
1541                         break;
1542                 case 'u':
1543                         strncpy(status->ls_registration, optarg,
1544                                 LR_NAME_MAXLEN);
1545                         break;
1546                 case 'l':
1547                         statuslog = optarg;
1548                         (void) lr_read_log();
1549                         break;
1550                 case 'v':
1551                         verbose++;
1552                         break;
1553                 case 'x':
1554                         if (strcmp("no", optarg) == 0) {
1555                                 noxattr = 1;
1556                         } else if (strcmp("yes", optarg) != 0) {
1557                                 printf("Invalid parameter %s. "
1558                                        "Specify --xattr=no or --xattr=yes\n",
1559                                        optarg);
1560                                 return -1;
1561                         }
1562                         break;
1563                 case 'z':
1564                         dryrun = 1;
1565                         break;
1566                 case 'c':
1567                         /* Undocumented option cl-clear */
1568                         if (strcmp("no", optarg) == 0) {
1569                                 noclear = 1;
1570                         } else if (strcmp("yes", optarg) != 0) {
1571                                 printf("Invalid parameter %s. "
1572                                        "Specify --cl-clear=no "
1573                                        "or --cl-clear=yes\n",
1574                                        optarg);
1575                                 return -1;
1576                         }
1577                         break;
1578                 case 'r':
1579                         /* Undocumented option use-rsync */
1580                         use_rsync = 1;
1581                         break;
1582                 case 'y':
1583                         /* Undocumented option rsync-threshold */
1584                         rsync_threshold = atol(optarg);
1585                         break;
1586                 case 'n':
1587                         /* Undocumented option start-recno */
1588                         status->ls_last_recno = atol(optarg);
1589                         break;
1590                 case 'd':
1591                         /* Undocumented option debug */
1592                         debug = atoi(optarg);
1593                         if (debug < 0 || debug > 2)
1594                                 debug = 0;
1595                         break;
1596                 default:
1597                         fprintf(stderr, "error: %s: option '%s' "
1598                                 "unrecognized.\n", argv[0], argv[optind - 1]);
1599                         lr_usage();
1600                         return -1;
1601                 }
1602         }
1603
1604         if (status->ls_last_recno == -1)
1605                 status->ls_last_recno = 0;
1606         if (strnlen(status->ls_registration, LR_NAME_MAXLEN) == 0) {
1607                 /* No registration ID was passed in. */
1608                 printf("Please specify changelog consumer registration id.\n");
1609                 lr_usage();
1610                 return -1;
1611         }
1612         if (strnlen(status->ls_source, PATH_MAX) == 0) {
1613                 fprintf(stderr, "Please specify the source path.\n");
1614                 lr_usage();
1615                 return -1;
1616         }
1617         if (strnlen(status->ls_targets[0], PATH_MAX) == 0) {
1618                 fprintf(stderr, "Please specify the target path.\n");
1619                 lr_usage();
1620                 return -1;
1621         }
1622
1623         /* This plumbing is needed for some of the ioctls behind
1624            llapi calls to work. */
1625         if (obd_initialize(argc, argv) < 0) {
1626                 fprintf(stderr, "obd_initialize failed.\n");
1627                 exit(-1);
1628         }
1629
1630         rc = lr_locate_rsync();
1631         if (use_rsync && rc != 0) {
1632                 fprintf(stderr, "Error: unable to locate %s.\n", RSYNC);
1633                 exit(-1);
1634         }
1635
1636         signal(SIGINT, termination_handler);
1637         signal(SIGHUP, termination_handler);
1638         signal(SIGTERM, termination_handler);
1639
1640         rc = lr_replicate();
1641
1642         return rc;
1643 }