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