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