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