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