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