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