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