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