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