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