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