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